code-pairing.ts

7.3 KB · raw

1// Device pairing over a code — the PAIR_IDENTITY half.2//3// The dialling half (decode the code, connect, plaintext hello, Noise NK) lives4// in `shared/pairing-dial.ts` and is shared with vault adoption, which speaks5// ADOPT_* frames over the same channel instead. This module is only what6// happens once that channel is open:7//8//   1. exchange PAIR_IDENTITY (send ours incl. vault_id, then read theirs)9//   2. derive the SAS, surface it for user confirmation10//   3. on confirm -> persist the PairedDevice; on reject -> abort without11//      persisting12//13// A pairing code (`A74H-48J3-KI32-OEP4`) carries the listener's endpoint and14// one-time token.1516import { dialPairingChannel, PAIRING_PORT, type PairingDialDeps } from "../shared/pairing-dial";17import type { LocalIdentity } from "../shared/pairing-handshake";18import type { DeviceType, PairedDevice } from "../shared/sync-types";19import { bytesToHex, normalizeRelayUrl } from "../shared/rendezvous";2021/** Default sync port a peer announces; used when ws_port is absent. Same22 *  fixed port pairing dials — SyncReconnectListener.SYNC_PORT on Android. */23const DEFAULT_SYNC_PORT = PAIRING_PORT;2425export type CodePairingError =26  | "invalid_code"      // socket closed before PEACH_HELLO_ACK (wrong/expired)27  | "no_host_found"     // nothing answered at the endpoint28  | "handshake_failed"  // Noise NK / PAIR_IDENTITY decode failed29  | "sas_mismatch"      // user rejected the SAS30  | "vault_locked";     // no master key available3132export interface CodePairingDeps extends PairingDialDeps {33  /**34   * Public identity plus the private key used for structural35   * proof-of-possession. The private half never enters a wire frame.36   */37  getLocalIdentity(): Promise<{38    identity: LocalIdentity;39    privateKey: Uint8Array;40    publicKey: Uint8Array;41  }>;42  /** Current mesh relay URL; sent in the encrypted pairing identity. */43  getRelayUrl(): Promise<string>;44  /** Persist on user confirm. */45  persistDevice(device: PairedDevice): Promise<void>;46  /** Optional fast-path cache for the next sync round. */47  cacheLastKnownIp?(pubkeyHex: string, ip: string): Promise<void>;48}4950export interface CodePairingCallbacks {51  /** Show the 6-digit SAS; the popup must compare it against the peer's. */52  onSasReady(sas: string): void;53  /** Pairing succeeded and the device was persisted. */54  onComplete(device: PairedDevice): void;55  /** Pairing failed at some stage. */56  onError(error: CodePairingError): void;57}5859interface PairingFrame {60  type: "PAIR_IDENTITY";61  device_id: string;62  device_name: string;63  device_type: DeviceType;64  long_term_public_key_hex: string;65  signing_public_key_hex?: string;66  ws_port?: number;67  vault_id?: string; // Change 1 — additive, optional68  relay_url?: string;69}7071function encodeJson(obj: unknown): Uint8Array {72  return new TextEncoder().encode(JSON.stringify(obj));73}7475function decodePairIdentity(bytes: Uint8Array): PairingFrame {76  const p = JSON.parse(new TextDecoder().decode(bytes)) as Record<string, unknown>;77  if (p?.type !== "PAIR_IDENTITY") throw new Error("expected PAIR_IDENTITY");78  if (typeof p.device_id !== "string" || !p.device_id) throw new Error("device_id missing");79  if (typeof p.device_name !== "string") throw new Error("device_name missing");80  if (81    p.device_type !== "extension" &&82    p.device_type !== "android" &&83    p.device_type !== "ios"84  ) {85    throw new Error("device_type invalid");86  }87  if (typeof p.long_term_public_key_hex !== "string" ||88      !/^[0-9a-f]{64}$/.test(p.long_term_public_key_hex)) {89    throw new Error("long_term_public_key_hex is not 32-byte hex");90  }91  if (p.relay_url !== undefined) {92    if (typeof p.relay_url !== "string") throw new Error("relay_url invalid");93    p.relay_url = normalizeRelayUrl(p.relay_url);94  }95  return p as unknown as PairingFrame;96}9798/**99 * Drive a complete code pairing.100 *101 * `confirm` is a function the caller resolves AFTER the user has compared the102 * SAS shown here against the SAS the peer displays. Resolving false (or103 * rejecting) aborts before any device is persisted — this is the out-of-band104 * MITM defence (see the SECURITY note in pairing-handshake.ts), and it, not the105 * pairing token, is what actually authenticates the peer.106 */107export async function pairWithCode(108  code: string,109  cb: CodePairingCallbacks,110  deps: CodePairingDeps,111  confirm: (sas: string) => Promise<boolean>,112): Promise<void> {113  let local: Awaited<ReturnType<CodePairingDeps["getLocalIdentity"]>>;114  try {115    local = await deps.getLocalIdentity();116  } catch {117    cb.onError("vault_locked");118    return;119  }120121  const dial = await dialPairingChannel(code, deps);122  if (!dial.ok) {123    cb.onError(dial.error);124    return;125  }126  const {127    channel,128    sas,129    host,130    rendezvousSecretHex,131    remoteStaticPublicKey,132    authenticateInitiator,133    socket,134  } = dial.dialled;135136  try {137    const { identity, privateKey, publicKey } = local;138    if (bytesToHex(publicKey) !== identity.longTermPublicKeyHex) {139      throw new Error("local pairing key does not match advertised identity");140    }141    // E1: prove the private half of the advertised initiator identity before142    // either side trusts a PAIR_IDENTITY frame or asks the user for SAS consent.143    await authenticateInitiator(privateKey, publicKey);144145    const relayUrl = await deps.getRelayUrl();146    // Initiator (browser) sends its identity FIRST, then reads the peer's.147    const ourFrame: PairingFrame = {148      type: "PAIR_IDENTITY",149      device_id: identity.deviceId,150      device_name: identity.deviceName,151      device_type: identity.deviceType,152      long_term_public_key_hex: identity.longTermPublicKeyHex,153      signing_public_key_hex: identity.signingPublicKeyHex,154      ws_port: identity.wsPort,155      vault_id: identity.vaultId, // Change 1156      relay_url: relayUrl,157    };158    await channel.send(encodeJson(ourFrame));159160    const theirFrame = decodePairIdentity(await channel.receive());161    if (theirFrame.long_term_public_key_hex !== bytesToHex(remoteStaticPublicKey)) {162      throw new Error("peer identity does not match Noise responder key");163    }164165    cb.onSasReady(sas);166    const confirmed = await confirm(sas);167    if (!confirmed) {168      cb.onError("sas_mismatch");169      return;170    }171172    // ws_port comes from the authenticated peer frame and falls back to the173    // native listener's fixed pairing/sync port for older peers.174    const device: PairedDevice = {175      deviceId: theirFrame.device_id,176      deviceName: theirFrame.device_name,177      deviceType: theirFrame.device_type,178      longTermPublicKeyHex: theirFrame.long_term_public_key_hex,179      signingPublicKeyHex: theirFrame.signing_public_key_hex,180      trustSource: "direct",181      wsPort: typeof theirFrame.ws_port === "number" ? theirFrame.ws_port : DEFAULT_SYNC_PORT,182      rendezvousSecretHex,183      // The listening phone is the authority for the relay this pair will use.184      relayUrl: theirFrame.relay_url ?? relayUrl,185      pairedAt: Date.now(),186    };187    await deps.persistDevice(device);188    if (deps.cacheLastKnownIp && device.longTermPublicKeyHex) {189      await deps.cacheLastKnownIp(device.longTermPublicKeyHex, host).catch(() => undefined);190    }191    cb.onComplete(device);192  } catch (err) {193    if (typeof console !== "undefined") console.error("[code-pairing] handshake failed:", err);194    cb.onError("handshake_failed");195  } finally {196    socket.close();197  }198}