chirp-handshake.ts

13.4 KB · raw

1// Post-chirp pairing handshake.2//3// After both devices have exchanged ephemeral X25519 keys via the audio4// chirp, the actual trust transfer happens over an authenticated, encrypted5// channel built on top of those ephemerals. The handshake:6//7//   1. Both sides instantiate Noise NK using the chirp-derived ephemerals.8//      The Android device drives the initiator side; the extension drives9//      the responder side. Treating the chirp ephemerals as the NK "static"10//      key works because the chirp transports the ephemeral with checksum11//      integrity; an attacker who could substitute keys would have to do12//      so in the audio band, in real time, in the same room.13//14//   2. Over the resulting Noise transport, each side sends ONE JSON frame15//      with its `device_id`, `device_name`, `device_type`,16//      `long_term_public_key_hex`, and device-manifest signing key. Both17//      sides receive the counterpart's frame and persist it in the paired18//      device registry.19//20//   3. The Noise NK session and the chirp ephemerals are discarded —21//      future WebSocket sessions use Noise XX with the long-term static22//      keys exchanged in step 2.23//24// The transport for the Noise NK round is provided by the caller. In the25// real pairing flow it is a WebSocket (Android-as-server, extension-as-26// client). Tests pass an in-memory transport.2728import { noiseNKInitiator, noiseNKResponder } from "./noise-js";29import type { DeviceType, PairedDevice } from "./sync-types";3031export interface PairingTransport {32  send(msg: Uint8Array): Promise<void>;33  receive(): Promise<Uint8Array>;34}3536/** Result of a pairing handshake: the peer's identity plus the SAS the user37 *  must confirm matches the peer device before the pair is persisted. */38export interface PairingHandshakeResult {39  device: PairedDevice;40  sas: string;41  /**42   * The peer's signed Pro license blob, if it advertised one. The caller43   * activates it (signature-verified) AFTER the SAS is confirmed, so one Pro44   * device can grant Pro to the other when pairing. Never persisted as-is.45   */46  peerLicense?: string;47}4849export interface LocalIdentity {50  deviceId: string;51  deviceName: string;52  deviceType: DeviceType;53  longTermPublicKeyHex: string;54  signingPublicKeyHex?: string;55  /** Server-only field — Android/iOS/desktop sync hosts announce their port. */56  wsPort?: number;57  /**58   * Stable per-vault id (`computeVaultId`, sync-identity.ts). Sent in the59   * outbound PAIR_IDENTITY so a desktop helper can record which vault it60   * paired to. Optional: the caller omits it when the vault is locked (no61   * master key). Privacy: this is the LAN-linkable id — see the PRIVACY NOTE62   * at sync-identity.ts:62 (PCH-02-006).63   */64  vaultId?: string;65  /**66   * This device's signed Pro license blob (`PPK-…`), included only when this67   * device is Pro. The peer activates it (signature-verified) after the SAS is68   * confirmed, so pairing carries Pro to a free device. Either direction.69   */70  license?: string;71}7273interface PairingFrame {74  type: "PAIR_IDENTITY";75  device_id: string;76  device_name: string;77  device_type: DeviceType;78  long_term_public_key_hex: string;79  signing_public_key_hex?: string;80  ws_port?: number;81  // Optional: present only when the sender knows its vault id. peach-sync82  // treats this as optional (pairing.zig:54); chirp mobile peers omit it.83  vault_id?: string;84  // Optional signed Pro license blob — additive; peers that don't understand85  // it ignore it. Activated by the receiver only after SAS confirmation.86  license?: string;87}8889function encodeFrame(frame: PairingFrame): Uint8Array {90  return new TextEncoder().encode(JSON.stringify(frame));91}9293function decodeFrame(bytes: Uint8Array): PairingFrame {94  const parsed = JSON.parse(new TextDecoder().decode(bytes));95  if (parsed?.type !== "PAIR_IDENTITY") throw new Error("expected PAIR_IDENTITY frame");96  if (typeof parsed.device_id !== "string" || !parsed.device_id) throw new Error("device_id missing");97  if (typeof parsed.device_name !== "string") throw new Error("device_name missing");98  if (typeof parsed.device_type !== "string") throw new Error("device_type missing");99  if (typeof parsed.long_term_public_key_hex !== "string") throw new Error("long_term_public_key_hex missing");100  // Long-term pubkey is a hex-encoded 32-byte X25519 key.101  if (!/^[0-9a-f]{64}$/.test(parsed.long_term_public_key_hex)) {102    throw new Error("long_term_public_key_hex is not 32-byte hex");103  }104  if (105    parsed.signing_public_key_hex !== undefined &&106    !/^[0-9a-f]{64}$/.test(parsed.signing_public_key_hex)107  ) {108    throw new Error("signing_public_key_hex is not 32-byte hex");109  }110  return parsed as PairingFrame;111}112113/**114 * Run the post-chirp pairing handshake from the INITIATOR side (Android).115 *116 * `remoteEphemeralPublicKey` is the responder's ephemeral pubkey, which we117 * learned from the inbound chirp. The Noise NK transport message 1 will118 * encrypt to that key; the responder must hold the matching private key.119 */120export async function runPairingInitiator(121  remoteEphemeralPublicKey: Uint8Array,122  ourIdentity: LocalIdentity,123  transport: PairingTransport,124): Promise<PairingHandshakeResult> {125  const session = await noiseNKInitiator(126    remoteEphemeralPublicKey,127    transport.send,128    transport.receive,129  );130131  // Send our identity, then receive theirs.132  const ourFrame = encodeFrame({133    type: "PAIR_IDENTITY",134    device_id: ourIdentity.deviceId,135    device_name: ourIdentity.deviceName,136    device_type: ourIdentity.deviceType,137    long_term_public_key_hex: ourIdentity.longTermPublicKeyHex,138    signing_public_key_hex: ourIdentity.signingPublicKeyHex,139    ws_port: ourIdentity.wsPort,140    vault_id: ourIdentity.vaultId,141    license: ourIdentity.license,142  });143  await transport.send(session.encrypt(ourFrame));144145  const theirCipher = await transport.receive();146  const theirPlain = session.decrypt(theirCipher);147  const theirFrame = decodeFrame(theirPlain);148  // The SAS is derived from the shared Noise handshake hash; the caller MUST149  // have the user confirm it matches the peer's before persisting the device.150  return {151    device: frameToPairedDevice(theirFrame),152    sas: derivePairingSAS(session.handshakeHash),153    peerLicense: peerLicenseOf(theirFrame),154  };155}156157// ───────────────────────────────────────────────────────────────────────────158// SECURITY — TRUST MODEL (PCH-02-003): the pairing handshake does NOT cryptographically159// authenticate the initiator. Noise NK authenticates only the RESPONDER (it160// proves the initiator encrypted to the responder's "static" key — here the161// chirp ephemeral the responder BROADCAST in the clear over audio). On its own162// it gives the extension (always the responder) zero assurance about *who*163// completed the handshake, and there is no proof-of-possession over the164// long_term_public_key_hex a peer advertises in its PAIR_IDENTITY frame.165//166// COMPENSATING CONTROL (IMPLEMENTED, MANDATORY on the extension side): a167// user-verified Short Authentication String. Both peers derive the SAME 6-digit168// SAS via `derivePairingSAS(session.handshakeHash)` (below) — identical on both169// ends because the Noise handshake hash is shared — and DISPLAY it. The170// extension pairing flow gates persistence on the user confirming the codes171// match: `gateOnSAS` in `src/popup/chirp-pair.ts` runs BEFORE any device is172// written to the registry and ABORTS pairing on mismatch/rejection. This is the173// Bluetooth-numeric-comparison / Signal-safety-number model and detects a174// MITM/relay despite the lack of full mutual auth. Residual risk is the standard175// 6-digit SAS bound: a MITM survives with probability 1e-6 per attempt, and the176// guarantee depends on the user actually comparing the codes.177//178// OPEN ITEM (NOT verifiable from this repository): the Android/native client179// MUST surface and enforce the identical SAS gate before it persists the peer.180// If the app skips or auto-confirms the SAS, the channel is only as strong as181// the app's weakest end — confirm the app-side gate against the Android source182// at kepr.uk/peach-android before any release that touches pairing. A MITM who183// intercepts the acoustic chirp and completes the handshake against a non-184// enforcing peer can pair without user awareness.185// A future hardening step (coordinated wire change with the app) could add186// proof-of-possession via `performInitiatorAuth`/`performResponderAuth`187// (noise-js) so each side proves possession of the key it advertises, making188// authentication structural rather than dependent on the user's SAS comparison.189//190// This is documented residual risk in the cross-repo trust model, not a bug in191// this codebase: the extension-side gateOnSAS is enforced here and regression-192// tested (PCH-01-024); the peer-side gate lives in Android and must be re-193// verified there on every pairing-touching Android release.194// ───────────────────────────────────────────────────────────────────────────195196/**197 * Derive a 6-digit Short Authentication String from a Noise handshake hash.198 * Both pairing peers compute the SAME value because the Noise `handshakeHash`199 * is shared after the handshake. Showing it on both devices and having the200 * user confirm they match authenticates the channel out-of-band, detecting a201 * man-in-the-middle the NK handshake alone cannot (see SECURITY note above).202 */203export function derivePairingSAS(handshakeHash: Uint8Array): string {204  // Fold the first 4 bytes into an unsigned int, mod 1e6, zero-padded. Uniform205  // enough for a 6-digit comparison code; the handshake hash is already a PRF206  // output so no further mixing is needed.207  if (handshakeHash.length < 4) return "000000";208  const n =209    ((handshakeHash[0] << 24) >>> 0) +210    (handshakeHash[1] << 16) +211    (handshakeHash[2] << 8) +212    handshakeHash[3];213  return String((n >>> 0) % 1_000_000).padStart(6, "0");214}215216/**217 * Run the post-chirp pairing handshake from the RESPONDER side (extension).218 *219 * `ourEphemeralPrivateKey` / `ourEphemeralPublicKey` come from the chirp220 * the responder broadcast; the initiator's chirp told them which key to221 * authenticate against.222 */223export async function runPairingResponder(224  ourEphemeralPrivateKey: Uint8Array,225  ourEphemeralPublicKey: Uint8Array,226  ourIdentity: LocalIdentity,227  transport: PairingTransport,228): Promise<PairingHandshakeResult> {229  const session = await noiseNKResponder(230    ourEphemeralPrivateKey,231    ourEphemeralPublicKey,232    transport.send,233    transport.receive,234  );235236  // Receive theirs first, then send ours — the initiator sends first.237  const theirCipher = await transport.receive();238  const theirPlain = session.decrypt(theirCipher);239  const theirFrame = decodeFrame(theirPlain);240241  const ourFrame = encodeFrame({242    type: "PAIR_IDENTITY",243    device_id: ourIdentity.deviceId,244    device_name: ourIdentity.deviceName,245    device_type: ourIdentity.deviceType,246    long_term_public_key_hex: ourIdentity.longTermPublicKeyHex,247    signing_public_key_hex: ourIdentity.signingPublicKeyHex,248    ws_port: ourIdentity.wsPort,249    vault_id: ourIdentity.vaultId,250    license: ourIdentity.license,251  });252  await transport.send(session.encrypt(ourFrame));253254  // SAS derived from the shared handshake hash — caller must have the user255  // confirm it matches the peer's code before persisting (defeats the256  // initiator-impersonation / MITM attack the NK handshake alone allows).257  return {258    device: frameToPairedDevice(theirFrame),259    sas: derivePairingSAS(session.handshakeHash),260    peerLicense: peerLicenseOf(theirFrame),261  };262}263264/** Pull a plausible license string off a peer frame (signature is verified265 *  later, on activation). Anything non-string is ignored. */266function peerLicenseOf(frame: PairingFrame): string | undefined {267  return typeof frame.license === "string" && frame.license.length > 0 ? frame.license : undefined;268}269270function frameToPairedDevice(frame: PairingFrame): PairedDevice {271  return {272    deviceId: frame.device_id,273    deviceName: frame.device_name,274    deviceType: frame.device_type,275    longTermPublicKeyHex: frame.long_term_public_key_hex,276    signingPublicKeyHex: frame.signing_public_key_hex,277    trustSource: "direct",278    wsPort: typeof frame.ws_port === "number" ? frame.ws_port : undefined,279    pairedAt: Date.now(),280  };281}282283/**284 * Test-helper: an in-memory pair of transports that connect to each other.285 * Use one half for the initiator and the other for the responder.286 */287export function memoryTransportPair(): [PairingTransport, PairingTransport] {288  const a: Uint8Array[] = [];289  const b: Uint8Array[] = [];290  const aReaders: Array<(b: Uint8Array) => void> = [];291  const bReaders: Array<(b: Uint8Array) => void> = [];292293  function makeTransport(294    inbox: Uint8Array[],295    outbox: Uint8Array[],296    inboxReaders: Array<(b: Uint8Array) => void>,297    outboxReaders: Array<(b: Uint8Array) => void>,298  ): PairingTransport {299    return {300      async send(msg: Uint8Array) {301        const r = outboxReaders.shift();302        if (r) r(msg);303        else outbox.push(msg);304      },305      receive() {306        const msg = inbox.shift();307        if (msg) return Promise.resolve(msg);308        return new Promise<Uint8Array>((resolve) => inboxReaders.push(resolve));309      },310    };311  }312  return [makeTransport(a, b, aReaders, bReaders), makeTransport(b, a, bReaders, aReaders)];313}