| 1 | import http from "node:http"; |
| 2 | import { createHash } from "node:crypto"; |
| 3 | |
| 4 | |
| 5 | |
| 6 | export async function startDisplay(upstream, { frameInterval = 50, sharedClipboard = false } = {}) { |
| 7 | const stats = { connections: 0, closed: 0, frames: 0, clipboardConnections: 0, clipboardUpdates: [], keys: [] }; |
| 8 | const sockets = new Set(); |
| 9 | const displays = new Set(); |
| 10 | const clipboardWriters = new Set(); |
| 11 | const sharedWriters = new Set(), sharedSockets = new Set(); |
| 12 | const terminalWriters = new Set(); |
| 13 | let width = 640, height = 480, framesPaused = false; |
| 14 | const server = http.createServer((req, res) => { |
| 15 | if (req.url.startsWith("/api/")) { |
| 16 | res.writeHead(503); res.end("Unmocked fixture request"); return; |
| 17 | } |
| 18 | const target = new URL(req.url, upstream); |
| 19 | const proxy = http.get(target, (response) => { |
| 20 | res.writeHead(response.statusCode, response.headers); |
| 21 | response.pipe(res); |
| 22 | }); |
| 23 | proxy.on("error", () => { res.writeHead(502); res.end(); }); |
| 24 | }); |
| 25 | server.on("upgrade", (req, socket) => { |
| 26 | const shared = sharedClipboard && new URL(req.url,upstream).pathname === "/api/clipboard"; |
| 27 | const terminal = sharedClipboard && /^\/api\/terminals\/[^/]+\/stream$/.test(new URL(req.url, upstream).pathname); |
| 28 | if (!shared && !terminal && !["/api/vnc", "/api/claude-desktop/vnc"].includes(new URL(req.url, upstream).pathname)) { socket.destroy(); return; } |
| 29 | sockets.add(socket); |
| 30 | stats.connections++; |
| 31 | const key = createHash("sha1").update(req.headers["sec-websocket-key"] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64"); |
| 32 | socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${key}\r\n\r\n`); |
| 33 | const send = (payload, opcode = 2) => { |
| 34 | if (socket.destroyed) return; |
| 35 | const length = payload.length; |
| 36 | const header = Buffer.alloc(length < 126 ? 2 : length < 65536 ? 4 : 10); |
| 37 | header[0] = 0x80 | opcode; |
| 38 | header[1] = length < 126 ? length : length < 65536 ? 126 : 127; |
| 39 | if (header.length === 4) header.writeUInt16BE(length, 2); |
| 40 | if (header.length === 10) header.writeBigUInt64BE(BigInt(length), 2); |
| 41 | socket.write(Buffer.concat([header, payload])); |
| 42 | }; |
| 43 | const sharedWrite = value => send(Buffer.from(JSON.stringify(value)),1); |
| 44 | const terminalWrite = text => send(Buffer.from(text)); |
| 45 | if (terminal) terminalWriters.add(terminalWrite); |
| 46 | if (shared) { |
| 47 | stats.clipboardConnections++; sharedWriters.add(sharedWrite); sharedSockets.add(socket); |
| 48 | sharedWrite({ hello: { version: 1, os: "linux", session: "fixture-session", formats: ["text", "png", "files"], available: true } }); |
| 49 | } |
| 50 | const clipboard = (text) => { |
| 51 | const bytes = Buffer.from(text, "latin1"), message = Buffer.alloc(8 + bytes.length); |
| 52 | message[0] = 3; |
| 53 | message.writeUInt32BE(bytes.length, 4); |
| 54 | bytes.copy(message, 8); |
| 55 | send(message); |
| 56 | }; |
| 57 | let wire = Buffer.alloc(0), rfb = Buffer.alloc(0), phase = 0, timer, frame; |
| 58 | const makeFrame = () => { |
| 59 | frame = Buffer.alloc(16 + width * height * 4); |
| 60 | frame.writeUInt16BE(1, 2); frame.writeUInt16BE(width, 8); frame.writeUInt16BE(height, 10); |
| 61 | }; |
| 62 | const resize = () => { |
| 63 | const update = Buffer.alloc(16); |
| 64 | update.writeUInt16BE(1, 2); update.writeUInt16BE(width, 8); update.writeUInt16BE(height, 10); |
| 65 | update.writeInt32BE(-223, 12); |
| 66 | send(update); |
| 67 | makeFrame(); |
| 68 | }; |
| 69 | const consume = (data) => { |
| 70 | rfb = Buffer.concat([rfb, data]); |
| 71 | if (phase === 0 && rfb.length >= 12) { rfb = rfb.subarray(12); phase = 1; send(Buffer.from([1, 1])); } |
| 72 | if (phase === 1 && rfb.length >= 1) { rfb = rfb.subarray(1); phase = 2; send(Buffer.alloc(4)); } |
| 73 | if (phase === 2 && rfb.length >= 1) { |
| 74 | rfb = rfb.subarray(1); |
| 75 | phase = 3; |
| 76 | const name = Buffer.from("Cage test display"); |
| 77 | const init = Buffer.alloc(24 + name.length); |
| 78 | init.writeUInt16BE(width, 0); init.writeUInt16BE(height, 2); |
| 79 | init.set([32, 24, 0, 1], 4); |
| 80 | for (const offset of [8, 10, 12]) init.writeUInt16BE(255, offset); |
| 81 | init.set([16, 8, 0], 14); |
| 82 | init.writeUInt32BE(name.length, 20); name.copy(init, 24); send(init); |
| 83 | const fence = Buffer.alloc(9); |
| 84 | fence[0] = 248; |
| 85 | fence.writeUInt32BE(0x80000000, 4); |
| 86 | send(fence); |
| 87 | makeFrame(); |
| 88 | displays.add(resize); |
| 89 | clipboardWriters.add(clipboard); |
| 90 | timer = setInterval(() => { |
| 91 | if (framesPaused || socket.writableLength > frame.length * 2) return; |
| 92 | frame.fill(stats.frames % 255, 16); |
| 93 | send(frame); stats.frames++; |
| 94 | }, frameInterval); |
| 95 | } |
| 96 | while (phase === 3 && rfb.length) { |
| 97 | const type = rfb[0]; |
| 98 | let length = { 0: 20, 3: 10, 4: 8, 5: 6, 150: 10 }[type]; |
| 99 | if (type === 2) { |
| 100 | if (rfb.length < 4) return; |
| 101 | length = 4 + 4 * rfb.readUInt16BE(2); |
| 102 | } else if (type === 6) { |
| 103 | if (rfb.length < 8) return; |
| 104 | length = 8 + Math.abs(rfb.readInt32BE(4)); |
| 105 | } else if (type === 248) { |
| 106 | if (rfb.length < 9) return; |
| 107 | length = 9 + rfb[8]; |
| 108 | } |
| 109 | if (!length) { socket.destroy(); return; } |
| 110 | if (rfb.length < length) return; |
| 111 | if (type === 5) stats.pointer = { x: rfb.readUInt16BE(2), y: rfb.readUInt16BE(4) }; |
| 112 | if (type === 4) stats.keys.push({ down: Boolean(rfb[1]), symbol: rfb.readUInt32BE(4) }); |
| 113 | if (type === 248 && (rfb.readUInt32BE(4) & 0x80000000)) { |
| 114 | const response = Buffer.from(rfb.subarray(0, length)); |
| 115 | response.writeUInt32BE(rfb.readUInt32BE(4) & 3, 4); |
| 116 | send(response); |
| 117 | } |
| 118 | rfb = rfb.subarray(length); |
| 119 | } |
| 120 | }; |
| 121 | socket.on("data", (data) => { |
| 122 | wire = Buffer.concat([wire, data]); |
| 123 | while (wire.length >= 2) { |
| 124 | const opcode = wire[0] & 15, masked = Boolean(wire[1] & 128); |
| 125 | let length = wire[1] & 127, offset = 2; |
| 126 | if (length === 126) { if (wire.length < 4) return; length = wire.readUInt16BE(2); offset = 4; } |
| 127 | if (length === 127) { if (wire.length < 10) return; length = Number(wire.readBigUInt64BE(2)); offset = 10; } |
| 128 | if (length > 65536) { socket.destroy(); return; } |
| 129 | const maskBytes = masked ? 4 : 0; |
| 130 | if (wire.length < offset + maskBytes + length) return; |
| 131 | const payload = Buffer.from(wire.subarray(offset + maskBytes, offset + maskBytes + length)); |
| 132 | if (masked) for (let i = 0; i < length; i++) payload[i] ^= wire[offset + (i % 4)]; |
| 133 | wire = wire.subarray(offset + maskBytes + length); |
| 134 | if (opcode === 8) { send(payload, 8); socket.end(); return; } |
| 135 | if (opcode === 9) send(payload, 10); |
| 136 | if (shared && opcode === 1) { |
| 137 | const value = JSON.parse(payload.toString()); |
| 138 | stats.clipboardUpdates.push(value); |
| 139 | sharedWrite({ ack: value.serial }); |
| 140 | } else if (!terminal && (opcode === 1 || opcode === 2)) consume(payload); |
| 141 | } |
| 142 | }); |
| 143 | socket.on("error", () => {}); |
| 144 | socket.on("close", () => { clearInterval(timer); displays.delete(resize); clipboardWriters.delete(clipboard); sharedWriters.delete(sharedWrite); terminalWriters.delete(terminalWrite); sharedSockets.delete(socket); sockets.delete(socket); stats.closed++; }); |
| 145 | if (terminal) terminalWrite("Terminal clipboard ready\r\n$ "); |
| 146 | else if (!shared) send(Buffer.from("RFB 003.008\n")); |
| 147 | }); |
| 148 | await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); |
| 149 | return { |
| 150 | url: `http://127.0.0.1:${server.address().port}`, |
| 151 | stats, |
| 152 | pauseFrames(paused) { framesPaused = paused; }, |
| 153 | clipboard(text) { for (const write of clipboardWriters) write(text); }, |
| 154 | sharedClipboard(value) { for (const write of sharedWriters) write(value); }, |
| 155 | terminalOutput(text) { for (const write of terminalWriters) write(text); }, |
| 156 | disconnectClipboard() { for (const socket of sharedSockets) socket.destroy(); }, |
| 157 | resize(size) { width = size.width; height = size.height; for (const resize of displays) resize(); }, |
| 158 | close: async () => { |
| 159 | for (const socket of sockets) socket.destroy(); |
| 160 | server.closeAllConnections(); |
| 161 | await new Promise((resolve) => server.close(resolve)); |
| 162 | }, |
| 163 | }; |
| 164 | } |