* Read the daemon's answer to our client-hello's challenge: one * `{"codegraph_proof": …}` line (see `./daemon-proof`), the line a daemon sends * before the session's first byte. Resolves the proof (null from a daemon that * holds no key); rejects on anything else, a close, or no line within * `
(socket: net.Socket, timeoutMs: number)
| 714 | * stream, so the pipe that follows sees the session intact. |
| 715 | */ |
| 716 | function readProofLine(socket: net.Socket, timeoutMs: number): Promise<unknown> { |
| 717 | return new Promise((resolve, reject) => { |
| 718 | let buffer = ''; |
| 719 | const cleanup = () => { |
| 720 | socket.removeListener('data', onData); |
| 721 | socket.removeListener('error', onError); |
| 722 | socket.removeListener('close', onClose); |
| 723 | clearTimeout(timer); |
| 724 | }; |
| 725 | const onData = (chunk: string | Buffer) => { |
| 726 | buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8'); |
| 727 | const idx = buffer.indexOf('\n'); |
| 728 | if (idx === -1) { |
| 729 | if (buffer.length > MAX_HELLO_LINE_BYTES) { |
| 730 | cleanup(); |
| 731 | reject(new Error('daemon proof line exceeded size limit')); |
| 732 | } |
| 733 | return; |
| 734 | } |
| 735 | const line = buffer.slice(0, idx); |
| 736 | const tail = buffer.slice(idx + 1); |
| 737 | cleanup(); |
| 738 | if (tail.length > 0) socket.unshift(tail); |
| 739 | try { |
| 740 | const parsed = JSON.parse(line) as Record<string, unknown> | null; |
| 741 | if (!parsed || typeof parsed !== 'object' || !('codegraph_proof' in parsed)) { |
| 742 | reject(new Error('daemon sent no proof')); |
| 743 | return; |
| 744 | } |
| 745 | resolve(parsed.codegraph_proof); |
| 746 | } catch (err) { |
| 747 | reject(new Error(`daemon proof not JSON: ${err instanceof Error ? err.message : String(err)}`)); |
| 748 | } |
| 749 | }; |
| 750 | const onError = (err: Error) => { cleanup(); reject(err); }; |
| 751 | const onClose = () => { cleanup(); reject(new Error('daemon closed connection before its proof')); }; |
| 752 | const timer = setTimeout(() => { |
| 753 | cleanup(); |
| 754 | reject(new Error('timed out waiting for the daemon proof')); |
| 755 | }, timeoutMs); |
| 756 | timer.unref?.(); |
| 757 | socket.on('data', onData); |
| 758 | socket.on('error', onError); |
| 759 | socket.on('close', onClose); |
| 760 | }); |
| 761 | } |
| 762 | |
| 763 | /** |
| 764 | * Pipe stdin → socket and socket → stdout. Resolves once either end closes |
no test coverage detected