// Pairing handshake — Noise NK, the SAS, and the PAIR_IDENTITY frame. // // STATUS: the audio-pairing flow this module was written for is gone. What production still // uses from here is `derivePairingSAS` and the `LocalIdentity` / // `PairingTransport` types; the live dial-and-handshake path is // `shared/pairing-dial.ts`, and the live PAIR_IDENTITY exchange is // `background/code-pairing.ts`. // // The `runPairing*` helpers below are exercised only by this module's own // specs. Do NOT reach for the RESPONDER ones in new code: they assume this // device can accept an inbound connection, which a browser extension cannot // do. The browser is always the dialler, always the NK initiator. // // The shape of the exchange, which the live path still follows: // // 1. Both sides instantiate Noise NK over a caller-supplied transport. The // responder's "static" is an ephemeral it published out of band — today // that is the `ephemeralPublicKeyHex` it returns in PEACH_HELLO_ACK, // which is why the SAS below carries the real authentication weight. // // 2. Over the resulting Noise transport, each side sends ONE JSON frame with // its `device_id`, `device_name`, `device_type`, // `long_term_public_key_hex`, and device-manifest signing key. Both sides // persist the counterpart in the paired-device registry. // // 3. The Noise NK session and the ephemerals are discarded — future // WebSocket sessions (`shared/sync-transport.ts`) run Noise NK again, // this time against the long-term static key exchanged in step 2, // followed by a fresh PAIR_IDENTITY exchange (see // HANDSHAKE_STANDARDIZE_ON_NK.md; ongoing sync uses the same pattern). import { noiseNKInitiator, noiseNKResponder } from "./noise-js"; import type { DeviceType, PairedDevice } from "./sync-types"; import { bytesToHex, deriveRendezvousSecret, normalizeRelayUrl, } from "./rendezvous"; export interface PairingTransport { send(msg: Uint8Array): Promise; receive(): Promise; } /** Result of a pairing handshake: the peer's identity plus the SAS the user * must confirm matches the peer device before the pair is persisted. */ export interface PairingHandshakeResult { device: PairedDevice; sas: string; /** * The peer's signed Pro license blob, if it advertised one. The caller * activates it (signature-verified) AFTER the SAS is confirmed, so one Pro * device can grant Pro to the other when pairing. Never persisted as-is. */ peerLicense?: string; } export interface LocalIdentity { deviceId: string; deviceName: string; deviceType: DeviceType; longTermPublicKeyHex: string; signingPublicKeyHex?: string; /** Server-only field — Android/iOS sync hosts announce their port. */ wsPort?: number; /** * Stable per-vault id (`computeVaultId`, sync-identity.ts). Sent in the * outbound PAIR_IDENTITY so a native peer can record which vault it * paired to. Optional: the caller omits it when the vault is locked (no * master key). Privacy: this is the LAN-linkable id — see the PRIVACY NOTE * at sync-identity.ts:62 (PCH-02-006). */ vaultId?: string; /** * This device's signed Pro license blob (`PPK-…`), included only when this * device is Pro. The peer activates it (signature-verified) after the SAS is * confirmed, so pairing carries Pro to a free device. Either direction. */ license?: string; relayUrl?: string; } interface PairingFrame { type: "PAIR_IDENTITY"; device_id: string; device_name: string; device_type: DeviceType; long_term_public_key_hex: string; signing_public_key_hex?: string; ws_port?: number; // Optional: present only when the sender knows its vault id. peach-sync // treats this as optional (pairing.zig:54); mobile peers may omit it. vault_id?: string; // Optional signed Pro license blob — additive; peers that don't understand // it ignore it. Activated by the receiver only after SAS confirmation. license?: string; relay_url?: string; } export interface PostNoiseFrame { sas: string; rendezvousSecretHex: string; frame: unknown; channel: PairingTransport; } export interface PostNoiseChannel { sas: string; rendezvousSecretHex: string; channel: PairingTransport; } function encodeFrame(frame: PairingFrame): Uint8Array { return new TextEncoder().encode(JSON.stringify(frame)); } function decodeParsedFrame(parsed: unknown): PairingFrame { const value = parsed as Record | null; if (value?.type !== "PAIR_IDENTITY") throw new Error("expected PAIR_IDENTITY frame"); if (typeof value.device_id !== "string" || !value.device_id) throw new Error("device_id missing"); if (typeof value.device_name !== "string") throw new Error("device_name missing"); if (typeof value.device_type !== "string") throw new Error("device_type missing"); if (typeof value.long_term_public_key_hex !== "string") throw new Error("long_term_public_key_hex missing"); // Long-term pubkey is a hex-encoded 32-byte X25519 key. if (!/^[0-9a-f]{64}$/.test(value.long_term_public_key_hex)) { throw new Error("long_term_public_key_hex is not 32-byte hex"); } if ( value.signing_public_key_hex !== undefined && (typeof value.signing_public_key_hex !== "string" || !/^[0-9a-f]{64}$/.test(value.signing_public_key_hex)) ) { throw new Error("signing_public_key_hex is not 32-byte hex"); } if (value.relay_url !== undefined) { if (typeof value.relay_url !== "string") throw new Error("relay_url invalid"); value.relay_url = normalizeRelayUrl(value.relay_url); } return value as unknown as PairingFrame; } /** * Run the pairing handshake from the INITIATOR side. * * `remoteEphemeralPublicKey` is the responder's ephemeral pubkey, learned out * of band. The Noise NK transport message 1 encrypts to that key; the * responder must hold the matching private key. */ export async function runPairingInitiator( remoteEphemeralPublicKey: Uint8Array, ourIdentity: LocalIdentity, transport: PairingTransport, ): Promise { const postNoise = await runPairingInitiatorOpenChannel(remoteEphemeralPublicKey, transport); // Send our identity, then receive theirs. await postNoise.channel.send(encodeFrame({ type: "PAIR_IDENTITY", device_id: ourIdentity.deviceId, device_name: ourIdentity.deviceName, device_type: ourIdentity.deviceType, long_term_public_key_hex: ourIdentity.longTermPublicKeyHex, signing_public_key_hex: ourIdentity.signingPublicKeyHex, ws_port: ourIdentity.wsPort, vault_id: ourIdentity.vaultId, license: ourIdentity.license, relay_url: ourIdentity.relayUrl, })); const theirFrame = decodeParsedFrame(JSON.parse(new TextDecoder().decode(await postNoise.channel.receive()))); // The SAS is derived from the shared Noise handshake hash; the caller MUST // have the user confirm it matches the peer's before persisting the device. return { device: { ...frameToPairedDevice(theirFrame), rendezvousSecretHex: postNoise.rendezvousSecretHex, }, sas: postNoise.sas, peerLicense: peerLicenseOf(theirFrame), }; } export async function runPairingInitiatorOpenChannel( remoteEphemeralPublicKey: Uint8Array, transport: PairingTransport, ): Promise { const session = await noiseNKInitiator( remoteEphemeralPublicKey, transport.send, transport.receive, ); const channel: PairingTransport = { async send(msg) { await transport.send(session.encrypt(msg)); }, async receive() { return session.decrypt(await transport.receive()); }, }; return { sas: derivePairingSAS(session.handshakeHash), rendezvousSecretHex: bytesToHex(deriveRendezvousSecret(session.handshakeHash)), channel, }; } // ─────────────────────────────────────────────────────────────────────────── // SECURITY — TRUST MODEL (PCH-02-003): the pairing handshake does NOT cryptographically // authenticate the initiator. Noise NK authenticates only the RESPONDER (it // proves the initiator encrypted to the responder's "static" key — here the // ephemeral the responder published in the clear out of band). On its own // it gives the extension (always the responder) zero assurance about *who* // completed the handshake, and there is no proof-of-possession over the // long_term_public_key_hex a peer advertises in its PAIR_IDENTITY frame. // // COMPENSATING CONTROL (IMPLEMENTED, MANDATORY on the extension side): a // user-verified Short Authentication String. Both peers derive the SAME 6-digit // SAS via `derivePairingSAS(session.handshakeHash)` (below) — identical on both // ends because the Noise handshake hash is shared — and DISPLAY it. The // extension pairing flow gates persistence on the user confirming the codes // match: the SAS gate in `background/code-pairing.ts` runs BEFORE any device is // written to the registry and ABORTS pairing on mismatch/rejection. This is the // Bluetooth-numeric-comparison / Signal-safety-number model and detects a // MITM/relay despite the lack of full mutual auth. Residual risk is the standard // 6-digit SAS bound: a MITM survives with probability 1e-6 per attempt, and the // guarantee depends on the user actually comparing the codes. // // OPEN ITEM (NOT verifiable from this repository): the Android/native client // MUST surface and enforce the identical SAS gate before it persists the peer. // If the app skips or auto-confirms the SAS, the channel is only as strong as // the app's weakest end — confirm the app-side gate against the Android source // at kepr.uk/peach-android before any release that touches pairing. A MITM who // intercepts the out-of-band ephemeral and completes the handshake against a non- // enforcing peer can pair without user awareness. // A future hardening step (coordinated wire change with the app) could add // proof-of-possession via `performInitiatorAuth`/`performResponderAuth` // (noise-js) so each side proves possession of the key it advertises, making // authentication structural rather than dependent on the user's SAS comparison. // // This is documented residual risk in the cross-repo trust model, not a bug in // this codebase: the extension-side gateOnSAS is enforced here and regression- // tested (PCH-01-024); the peer-side gate lives in Android and must be re- // verified there on every pairing-touching Android release. // ─────────────────────────────────────────────────────────────────────────── /** * Derive a 6-digit Short Authentication String from a Noise handshake hash. * Both pairing peers compute the SAME value because the Noise `handshakeHash` * is shared after the handshake. Showing it on both devices and having the * user confirm they match authenticates the channel out-of-band, detecting a * man-in-the-middle the NK handshake alone cannot (see SECURITY note above). */ export function derivePairingSAS(handshakeHash: Uint8Array): string { // Fold the first 4 bytes into an unsigned int, mod 1e6, zero-padded. Uniform // enough for a 6-digit comparison code; the handshake hash is already a PRF // output so no further mixing is needed. if (handshakeHash.length < 4) return "000000"; const n = ((handshakeHash[0] << 24) >>> 0) + (handshakeHash[1] << 16) + (handshakeHash[2] << 8) + handshakeHash[3]; return String((n >>> 0) % 1_000_000).padStart(6, "0"); } /** * Run the pairing handshake from the RESPONDER side. * * NOT REACHABLE FROM A BROWSER — responding means accepting an inbound * connection. Retained for the protocol definition and its specs only. */ export async function runPairingResponder( ourEphemeralPrivateKey: Uint8Array, ourEphemeralPublicKey: Uint8Array, ourIdentity: LocalIdentity, transport: PairingTransport, ): Promise { const postNoise = await runPairingResponderOpenFrame( ourEphemeralPrivateKey, ourEphemeralPublicKey, transport, ); return handlePairIdentityFrame( postNoise.frame, postNoise.channel, ourIdentity, postNoise.sas, postNoise.rendezvousSecretHex, ); } export async function runPairingResponderOpenFrame( ourEphemeralPrivateKey: Uint8Array, ourEphemeralPublicKey: Uint8Array, transport: PairingTransport, ): Promise { const session = await noiseNKResponder( ourEphemeralPrivateKey, ourEphemeralPublicKey, transport.send, transport.receive, ); const channel: PairingTransport = { async send(msg) { await transport.send(session.encrypt(msg)); }, async receive() { return session.decrypt(await transport.receive()); }, }; const theirFrame = JSON.parse(new TextDecoder().decode(await channel.receive())); return { sas: derivePairingSAS(session.handshakeHash), rendezvousSecretHex: bytesToHex(deriveRendezvousSecret(session.handshakeHash)), frame: theirFrame, channel, }; } export async function handlePairIdentityFrame( frame: unknown, channel: PairingTransport, ourIdentity: LocalIdentity, sas: string, rendezvousSecretHex: string, ): Promise { const theirFrame = decodeParsedFrame(frame); const ourFrame = encodeFrame({ type: "PAIR_IDENTITY", device_id: ourIdentity.deviceId, device_name: ourIdentity.deviceName, device_type: ourIdentity.deviceType, long_term_public_key_hex: ourIdentity.longTermPublicKeyHex, signing_public_key_hex: ourIdentity.signingPublicKeyHex, ws_port: ourIdentity.wsPort, vault_id: ourIdentity.vaultId, license: ourIdentity.license, relay_url: ourIdentity.relayUrl, }); await channel.send(ourFrame); // SAS derived from the shared handshake hash — caller must have the user // confirm it matches the peer's code before persisting (defeats the // initiator-impersonation / MITM attack the NK handshake alone allows). return { device: { ...frameToPairedDevice(theirFrame), rendezvousSecretHex, }, sas, peerLicense: peerLicenseOf(theirFrame), }; } /** Pull a plausible license string off a peer frame (signature is verified * later, on activation). Anything non-string is ignored. */ function peerLicenseOf(frame: PairingFrame): string | undefined { return typeof frame.license === "string" && frame.license.length > 0 ? frame.license : undefined; } function frameToPairedDevice(frame: PairingFrame): PairedDevice { return { deviceId: frame.device_id, deviceName: frame.device_name, deviceType: frame.device_type, longTermPublicKeyHex: frame.long_term_public_key_hex, signingPublicKeyHex: frame.signing_public_key_hex, trustSource: "direct", wsPort: typeof frame.ws_port === "number" ? frame.ws_port : undefined, relayUrl: frame.relay_url, pairedAt: Date.now(), }; } /** * Test-helper: an in-memory pair of transports that connect to each other. * Use one half for the initiator and the other for the responder. */ export function memoryTransportPair(): [PairingTransport, PairingTransport] { const a: Uint8Array[] = []; const b: Uint8Array[] = []; const aReaders: Array<(b: Uint8Array) => void> = []; const bReaders: Array<(b: Uint8Array) => void> = []; function makeTransport( inbox: Uint8Array[], outbox: Uint8Array[], inboxReaders: Array<(b: Uint8Array) => void>, outboxReaders: Array<(b: Uint8Array) => void>, ): PairingTransport { return { async send(msg: Uint8Array) { const r = outboxReaders.shift(); if (r) r(msg); else outbox.push(msg); }, receive() { const msg = inbox.shift(); if (msg) return Promise.resolve(msg); return new Promise((resolve) => inboxReaders.push(resolve)); }, }; } return [makeTransport(a, b, aReaders, bReaders), makeTransport(b, a, bReaders, aReaders)]; }