/** * The local matching server: one session per TCP connection the client opens to the * matching address (network.blk, pointed at the local service's port by the build). * * A connection starts unencrypted; the client sends mlogin.login in clear packets and from * then on encrypts both directions with the session key sealed in that request * (session-crypto/). The answer to mlogin.login is already encrypted. * * Every request gets an answer. A request with no handler yet is answered with success and * empty data and marked unhandled in the traffic log, so the client carries on and shows * what it asks for next (the same policy as the char service). Keep-alive pings are * answered with their id (matching-message.ts). Other messages are only logged. */ import type { Socket } from 'node:net'; import type { TrafficLog } from '../traffic-log/traffic-log.ts'; import { encodePacket, PacketReader } from './matching-frame.ts'; import { answerTo, asPing, asRequest, decodeMessage, encodeMessage, notifyMessage, pingAnswer, type MatchingMessage } from './matching-message.ts'; import type { MatchingRequestTable, MatchingSessionControl } from './matching-requests.ts'; import { messageLogText } from './message-redaction.ts'; import { EnvelopeReader, sealEnvelope } from './session-crypto/encrypted-envelope.ts'; export class MatchingService { readonly #requests: MatchingRequestTable; readonly #log: TrafficLog; readonly #sessions = new Set(); constructor(requests: MatchingRequestTable, log: TrafficLog) { this.#requests = requests; this.#log = log; } accept(socket: Socket, connectionId: number): void { const session = new MatchingSession(socket, connectionId, this.#requests, this.#log); this.#sessions.add(session); socket.on('close', () => this.#sessions.delete(session)); socket.on('data', (chunk: Buffer) => { try { session.receive(chunk); } catch (error) { this.#log.matchingError(connectionId, error instanceof Error ? error.message : String(error)); socket.destroy(); } }); socket.on('error', () => socket.destroy()); } /** Push a matching notification (such as mrpc.generic_notify) to every active client session. */ broadcastNotify(name: string, data: Record): void { const message = notifyMessage(name, data); for (const session of this.#sessions) session.pushNotify(message, name); } } class MatchingSession { readonly #socket: Socket; readonly #connectionId: number; readonly #requests: MatchingRequestTable; readonly #log: TrafficLog; readonly #packets = new PacketReader(); #sessionKey: Buffer | undefined; #envelopes: EnvelopeReader | undefined; constructor(socket: Socket, connectionId: number, requests: MatchingRequestTable, log: TrafficLog) { this.#socket = socket; this.#connectionId = connectionId; this.#requests = requests; this.#log = log; } receive(chunk: Buffer): void { if (this.#envelopes) { for (const plaintext of this.#envelopes.push(chunk)) this.#readPackets(plaintext); return; } this.#readPackets(chunk); // The request just handled switched the connection to encryption: what followed it in // the same read is already encrypted. if (this.#envelopes) { const rest = this.#packets.takeRest(); if (rest.length) this.receive(rest); } } #readPackets(plaintext: Buffer): void { this.#packets.append(plaintext); const wasEncrypted = this.#envelopes !== undefined; for (let packet = this.#packets.next(); packet; packet = this.#packets.next()) { this.#handle(decodeMessage(packet.payload)); if (!wasEncrypted && this.#envelopes) return; } } #handle(message: MatchingMessage): void { const pingId = asPing(message); if (pingId !== undefined) { this.#record('in', message, `ping #${pingId}`, false); this.#send(pingAnswer(pingId)); return; } const request = asRequest(message); if (!request) { this.#record('in', message, 'not a request', false); return; } const handler = this.#requests.get(request.name); const notes: string[] = []; const control: MatchingSessionControl = { useSessionKey: (key) => { this.#sessionKey = key; this.#envelopes = new EnvelopeReader(key); }, note: (text) => notes.push(text), }; const data = handler ? handler(request, control) : {}; this.#record('in', message, `${request.name} #${request.id}${notes.length ? ` (${notes.join('; ')})` : ''}`, !handler); const answer = answerTo(request, data); this.#record('out', answer, `answer ${request.name} #${request.id}${this.#sessionKey ? ' (encrypted)' : ''}`, false); this.#send(answer); } #send(message: MatchingMessage): void { const packet = encodePacket(encodeMessage(message)); this.#socket.write(this.#sessionKey ? sealEnvelope(this.#sessionKey, packet) : packet); } pushNotify(message: MatchingMessage, summaryName: string): void { if (!this.#sessionKey || this.#socket.destroyed) return; this.#record('out', message, `notify ${summaryName} (encrypted)`, false); this.#send(message); } #record(direction: 'in' | 'out', message: MatchingMessage, summary: string, unhandled: boolean): void { this.#log.matchingMessage(this.#connectionId, { direction, kind: message.kind, summary, unhandled, text: messageLogText(message) }); } }