// Pairing handshake — Noise NK, the SAS, and the PAIR_IDENTITY frame. // // STATUS: the audio chirp this file describes 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/desktop-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 original design notes follow, for the trust model in the SECURITY block // further down — which still governs the flow. // // After both devices have exchanged ephemeral X25519 keys via the audio // chirp, the actual trust transfer happens over an authenticated, encrypted // channel built on top of those ephemerals. The handshake: // // 1. Both sides instantiate Noise NK using the chirp-derived ephemerals. // The Android device drives the initiator side; the extension drives // the responder side. Treating the chirp ephemerals as the NK "static" // key works because the chirp transports the ephemeral with checksum // integrity; an attacker who could substitute keys would have to do // so in the audio band, in real time, in the same room. // // 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 receive the counterpart's frame and persist it in the paired // device registry. // // 3. The Noise NK session and the chirp ephemerals are discarded — // future WebSocket sessions use Noise XX with the long-term static // keys exchanged in step 2. // // The transport for the Noise NK round is provided by the caller. In the // real pairing flow it is a WebSocket (Android-as-server, extension-as- // client). Tests pass an in-memory transport. import { noiseNKInitiator, noiseNKResponder } from "./noise-js"; import type { DeviceType, PairedDevice } from "./sync-types"; 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/desktop sync hosts announce their port. */ wsPort?: number; /** * Stable per-vault id (`computeVaultId`, sync-identity.ts). Sent in the * outbound PAIR_IDENTITY so a desktop helper 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; } 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); chirp mobile peers 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; } export interface PostNoiseFrame { sas: string; frame: unknown; channel: PairingTransport; } export interface PostNoiseChannel { sas: 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"); } return value as unknown as PairingFrame; } /** * Run the post-chirp pairing handshake from the INITIATOR side (Android). * * `remoteEphemeralPublicKey` is the responder's ephemeral pubkey, which we * learned from the inbound chirp. The Noise NK transport message 1 will * encrypt 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, })); 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), 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), 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 // chirp ephemeral the responder BROADCAST in the clear over audio). 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: `gateOnSAS` in `src/popup/chirp-pair.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 acoustic chirp 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 post-chirp pairing handshake from the RESPONDER side (extension). * * `ourEphemeralPrivateKey` / `ourEphemeralPublicKey` come from the chirp * the responder broadcast; the initiator's chirp told them which key to * authenticate against. */ 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); } 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), frame: theirFrame, channel, }; } export async function handlePairIdentityFrame( frame: unknown, channel: PairingTransport, ourIdentity: LocalIdentity, sas: 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, }); 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), 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, 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)]; }