* Read one CRLF/LF-terminated JSON line from the socket, parse it as the * daemon hello, and return it. Bounded to MAX_HELLO_LINE_BYTES so a * malicious or broken peer can't OOM us. Times out after `timeoutMs` (3s by * default) — a healthy daemon sends hello immediately on accept.
(socket: net.Socket, timeoutMs: number = DAEMON_HELLO_TIMEOUT_MS)
| 654 | * default) — a healthy daemon sends hello immediately on accept. |
| 655 | */ |
| 656 | function readHelloLine(socket: net.Socket, timeoutMs: number = DAEMON_HELLO_TIMEOUT_MS): Promise<DaemonHello> { |
| 657 | return new Promise((resolve, reject) => { |
| 658 | let buffer = ''; |
| 659 | const cleanup = () => { |
| 660 | socket.removeListener('data', onData); |
| 661 | socket.removeListener('error', onError); |
| 662 | socket.removeListener('close', onClose); |
| 663 | clearTimeout(timer); |
| 664 | }; |
| 665 | const onData = (chunk: string | Buffer) => { |
| 666 | buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8'); |
| 667 | const idx = buffer.indexOf('\n'); |
| 668 | if (idx === -1) { |
| 669 | if (buffer.length > MAX_HELLO_LINE_BYTES) { |
| 670 | cleanup(); |
| 671 | reject(new Error('daemon hello line exceeded size limit')); |
| 672 | } |
| 673 | return; |
| 674 | } |
| 675 | const line = buffer.slice(0, idx); |
| 676 | // Re-emit anything past the newline so the pipe-stage sees it. |
| 677 | const tail = buffer.slice(idx + 1); |
| 678 | cleanup(); |
| 679 | if (tail.length > 0) { |
| 680 | // Push back via unshift — Node's net.Socket supports it on readable streams. |
| 681 | socket.unshift(tail); |
| 682 | } |
| 683 | try { |
| 684 | const parsed = JSON.parse(line) as DaemonHello; |
| 685 | if (typeof parsed.codegraph !== 'string' || typeof parsed.pid !== 'number') { |
| 686 | reject(new Error('daemon hello missing required fields')); |
| 687 | return; |
| 688 | } |
| 689 | resolve(parsed); |
| 690 | } catch (err) { |
| 691 | reject(new Error(`daemon hello not JSON: ${err instanceof Error ? err.message : String(err)}`)); |
| 692 | } |
| 693 | }; |
| 694 | const onError = (err: Error) => { cleanup(); reject(err); }; |
| 695 | const onClose = () => { cleanup(); reject(new Error('daemon closed connection before hello')); }; |
| 696 | const timer = setTimeout(() => { |
| 697 | cleanup(); |
| 698 | reject(new Error('timed out waiting for daemon hello')); |
| 699 | }, timeoutMs); |
| 700 | timer.unref?.(); |
| 701 | socket.on('data', onData); |
| 702 | socket.on('error', onError); |
| 703 | socket.on('close', onClose); |
| 704 | }); |
| 705 | } |
| 706 | |
| 707 | /** |
| 708 | * Pipe stdin → socket and socket → stdout. Resolves once either end closes |
no test coverage detected