(root: string, opts: FakeDaemonOptions)
| 54 | } |
| 55 | |
| 56 | export async function startFakeDaemon(root: string, opts: FakeDaemonOptions): Promise<FakeDaemon> { |
| 57 | const socketPath = opts.socketPath ?? getDaemonSocketCandidates(root)[0]!; |
| 58 | if (process.platform !== 'win32') fs.mkdirSync(path.dirname(socketPath), { recursive: true }); |
| 59 | const requests: RecordedRequest[] = []; |
| 60 | const challenges: string[] = []; |
| 61 | const sockets = new Set<net.Socket>(); |
| 62 | const proofFor = (challenge: string): string | null => { |
| 63 | const mode = opts.proof ?? 'valid'; |
| 64 | if (mode === 'none') return null; |
| 65 | if (mode === 'other-key') return daemonProof(randomBytes(32), challenge, socketPath); |
| 66 | // A key this process can't read (a test faking another uid) proves nothing, as in the daemon. |
| 67 | const key = daemonKey(); |
| 68 | return key ? daemonProof(key, challenge, mode === 'other-path' ? `${socketPath}-elsewhere` : socketPath) : null; |
| 69 | }; |
| 70 | const server = net.createServer((socket) => { |
| 71 | sockets.add(socket); |
| 72 | socket.on('close', () => sockets.delete(socket)); |
| 73 | socket.on('error', () => { /* a client that hung up */ }); |
| 74 | socket.write(JSON.stringify({ codegraph: opts.version ?? CodeGraphPackageVersion, pid: process.pid, socketPath, protocol: 1 }) + '\n'); |
| 75 | let buffer = ''; |
| 76 | socket.on('data', (chunk) => { |
| 77 | buffer += chunk.toString('utf8'); |
| 78 | let newline: number; |
| 79 | while ((newline = buffer.indexOf('\n')) !== -1) { |
| 80 | const message = JSON.parse(buffer.slice(0, newline)); |
| 81 | buffer = buffer.slice(newline + 1); |
| 82 | if (message.codegraph_client) { |
| 83 | if (typeof message.challenge === 'string') { |
| 84 | challenges.push(message.challenge); |
| 85 | const proof = proofFor(message.challenge); |
| 86 | if (proof !== null) socket.write(JSON.stringify({ codegraph_proof: proof }) + '\n'); |
| 87 | } |
| 88 | continue; |
| 89 | } |
| 90 | requests.push({ method: message.method, params: message.params }); |
| 91 | for (const extra of opts.before ?? []) socket.write(JSON.stringify(extra) + '\n'); |
| 92 | const body = opts.reply(message); |
| 93 | if (body !== undefined) socket.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, ...(body as object) }) + '\n'); |
| 94 | } |
| 95 | }); |
| 96 | }); |
| 97 | await new Promise<void>((resolve, reject) => { |
| 98 | server.once('error', reject); |
| 99 | server.listen(socketPath, () => resolve()); |
| 100 | }); |
| 101 | return { |
| 102 | socketPath, |
| 103 | requests, |
| 104 | challenges, |
| 105 | close: () => new Promise<void>((resolve) => { |
| 106 | for (const socket of sockets) socket.destroy(); |
| 107 | server.close(() => resolve()); |
| 108 | if (process.platform !== 'win32') fs.rmSync(socketPath, { force: true }); |
| 109 | }), |
| 110 | }; |
| 111 | } |
no test coverage detected