paired-devices.ts

16.5 KB · raw

1// Paired-device registry — v3 sync.2//3// Long-term records live in `chrome.storage.local`. Keys must not leave4// the device via a third-party sync service — `longTermPublicKeyHex` and5// `signingPublicKeyHex` are cryptographic keys; routing them through6// Google's or Mozilla's sync back-end violates the local-only trust model.7//8// `lastKnownIp` is network-specific and also lives in `chrome.storage.local`,9// keyed by `longTermPublicKeyHex` (not on the device record itself) so10// network-specific addresses don't roam across profiles.11//12// `deviceId` is the canonical primary key (UUID v4, stable for the13// lifetime of the installation). `longTermPublicKeyHex` is also unique14// per device but rotates if the user reinstalls before re-pairing, so we15// key on deviceId and update the key in place during re-pair.16//17// The registry has only ever lived in `chrome.storage.local` for released18// builds, so no cross-profile evacuation path is needed — the public keys19// never leave the device via a third-party sync back-end. Unpairing is20// local-only; Noise KK rejection on the next connection is the security21// boundary (see removePairedDeviceById).2223import type { DeviceRevocation, PairedDevice } from "../shared/sync-types";24import { constantTimeEqualHex } from "../shared/constant-time";25import { capDeviceName, clampSyncTimestamp } from "../shared/sync-limits";26import type { SyncOutcome } from "../shared/sync-outcome";2728const REGISTRY_KEY = "peach_paired_devices_v3";29const REVOCATIONS_KEY = "peach_device_revocations_v1";30/** Bound the list so a hostile peer cannot grow storage without limit. */31const MAX_REVOCATIONS = 500;32const LAST_IP_KEY_PREFIX = "peach_last_known_ip_v3:";33const LAST_SYNC_AT_KEY = "peach_last_sync_at";34const LAST_SYNC_RESULT_KEY = "peach_last_sync_result";3536export async function listPairedDevices(): Promise<PairedDevice[]> {37  try {38    const result = await chrome.storage.local.get(REGISTRY_KEY);39    const devices = (result as Record<string, unknown>)[REGISTRY_KEY];40    if (Array.isArray(devices)) return devices.filter(isPairedDevice);41    return [];42  } catch {43    return [];44  }45}4647export async function findPairedDeviceById(deviceId: string): Promise<PairedDevice | null> {48  const devices = await listPairedDevices();49  return devices.find((d) => d.deviceId === deviceId) ?? null;50}5152export async function findPairedDeviceByPubkey(pubkeyHex: string): Promise<PairedDevice | null> {53  const devices = await listPairedDevices();54  return devices.find((d) =>55    d.longTermPublicKeyHex !== undefined &&56    constantTimeEqualHex(d.longTermPublicKeyHex, pubkeyHex)57  ) ?? null;58}5960/**61 * Add or update a device by `deviceId`. On re-pair the new pubkey62 * silently replaces the old one; the deviceId is stable across the63 * other device's reinstall.64 */65export async function upsertPairedDevice(device: PairedDevice): Promise<void> {66  if (!device.deviceId) throw new Error("device.deviceId is required");67  if (!device.longTermPublicKeyHex) throw new Error("device.longTermPublicKeyHex is required");68  if (!device.deviceName) throw new Error("device.deviceName is required");69  if (!device.deviceType) throw new Error("device.deviceType is required");7071  // Peer-supplied names arrive capped (MAX_DEVICE_NAME_CHARS) so a hostile72  // peer cannot grow the registry without limit; the local name already73  // obeys the same bound at the Settings write path.74  const stored = { ...device, deviceName: capDeviceName(device.deviceName) };75  const devices = await listPairedDevices();76  const idx = devices.findIndex((d) => d.deviceId === stored.deviceId);77  if (idx >= 0) {78    devices[idx] = { ...devices[idx], ...stored };79  } else {80    devices.push(stored);81  }82  await chrome.storage.local.set({ [REGISTRY_KEY]: devices });83  // The device-list-changed sync trigger fires from the messages.ts handlers84  // (IMPORT_PAIRED_DEVICE / CONFIRM_VOUCHED_DEVICE / UNPAIR_DEVICE) — they85  // own the post-mutation contract and have the full payload available. Firing86  // here would race with the test setup pattern (setSyncRunner AFTER upsert).87}8889/**90 * Move every existing pair to the user-selected mesh relay.91 *92 * Reconnect prefers the relay stored on each pair over the global fallback, so93 * changing only the setting would leave established devices on the old relay.94 */95export async function setRelayUrlForAllPairedDevices(96  relayUrl: string,97): Promise<void> {98  const devices = await listPairedDevices();99  if (devices.length === 0) return;100  await chrome.storage.local.set({101    [REGISTRY_KEY]: devices.map((device) => ({ ...device, relayUrl })),102  });103  // A relay change is mesh state — the next alarm tick or popup open will dial104  // with the new relay. No fire-and-forget trigger here; the in-flight guard105  // would just drop it on the burst of upserts that often follows.106}107108/**109 * Removes the device from the LOCAL paired-devices registry only, leaving no110 * record behind. Prefer `revokeDeviceById` for anything the user would call111 * "remove this device" — a plain removal is silently undone the next time any112 * peer vouches the device back through a manifest.113 *114 * SECURITY NOTE (MV-8): this does NOT prevent the removed device from115 * syncing with OTHER peers in the device graph, and the device RETAINS116 * its copy of the vault root key (syncMasterKey) — it can still decrypt117 * anything it already holds and anything other peers send it. For a118 * lost or stolen device, removal is insufficient: use "Rotate sync119 * identity" (vault.ts rotateSyncIdentity), which re-keys the vault so120 * the old device's key material is useless.121 */122export async function removePairedDeviceById(deviceId: string): Promise<void> {123  const devices = await listPairedDevices();124  const filtered = devices.filter((d) => d.deviceId !== deviceId);125  // Unpairing is local-only — there is no remote unpair RPC. The remote126  // device retains this device in its own registry. Noise KK rejection on127  // the next connection attempt is the security boundary.128  await chrome.storage.local.set({ [REGISTRY_KEY]: filtered });129  // Also clear the per-network IP cache for this device.130  const device = devices.find((d) => d.deviceId === deviceId);131  if (device?.longTermPublicKeyHex) {132    await chrome.storage.local.remove(LAST_IP_KEY_PREFIX + device.longTermPublicKeyHex);133  }134  // The device-list-changed sync trigger fires from the messages.ts UNPAIR_DEVICE135  // handler — see upsertPairedDevice for why this lives there, not here.136}137138// ---------------------------------------------------------------------------139// Device revocation (Part 5 §C) — a removal that propagates and stays removed.140// ---------------------------------------------------------------------------141142export async function listDeviceRevocations(): Promise<DeviceRevocation[]> {143  try {144    const result = await chrome.storage.local.get(REVOCATIONS_KEY);145    const value = (result as Record<string, unknown>)[REVOCATIONS_KEY];146    if (Array.isArray(value)) return value.filter(isDeviceRevocation);147    return [];148  } catch {149    return [];150  }151}152153/**154 * True when either the id or the long-term key is under a terminal revocation.155 *156 * `deviceId` is a self-asserted string in a manifest, so keying terminality on157 * it alone is bypassed by re-vouching a revoked device's key under a fresh id.158 * The key is the thing a revoked device actually still holds, so it is the159 * thing terminality has to follow.160 */161export async function isDeviceRevoked(162  deviceId: string,163  longTermPublicKeyHex?: string,164): Promise<boolean> {165  // The all-zero sentinel stands for "we never stored a key for this device"166  // (see revokeDeviceById) and must not match a real one.167  const key = longTermPublicKeyHex?.toLowerCase();168  const keyIsRevocable = key !== undefined && key !== "0".repeat(64);169  return (await listDeviceRevocations()).some(170    (r) =>171      r.deviceId === deviceId ||172      (keyIsRevocable && r.longTermPublicKeyHex.toLowerCase() === key),173  );174}175176/**177 * Revoke a device: record it locally, then drop it from the registry. The178 * record rides out in every manifest this device signs from now on, and blocks179 * the device being vouched back in. A stale entry may survive in the180 * pending-vouch queue; the confirm handler re-checks revocation before181 * promoting anything out of it.182 */183export async function revokeDeviceById(184  deviceId: string,185  revokedByDeviceId: string,186  options: { now?: number } = {},187): Promise<DeviceRevocation | null> {188  const device = await findPairedDeviceById(deviceId);189  const existing = await listDeviceRevocations();190  if (existing.some((r) => r.deviceId === deviceId)) {191    // A direct re-pair in older builds could restore the paired row without192    // clearing its terminal revocation. "Remove" then returned early here and193    // left the row visible forever. Idempotency applies to the revocation194    // record, not to removing any stale live row that overlaps it.195    if (device) await removePairedDeviceById(deviceId);196    return null;197  }198199  const record: DeviceRevocation = {200    deviceId,201    // A device with no stored key was never usable as a sync peer; the202    // all-zero key keeps the record well-formed on the wire without203    // pretending to name a key we never saw.204    longTermPublicKeyHex: device?.longTermPublicKeyHex ?? "0".repeat(64),205    revokedAt: options.now ?? Date.now(),206    revokedByDeviceId,207  };208  await storeRevocations([...existing, record]);209  await removePairedDeviceById(deviceId);210  return record;211}212213/**214 * Merge revocations learned from a peer's manifest. Returns the deviceIds that215 * were newly revoked, so the caller can evict them.216 *217 * `revokedAt` is peer-supplied and is NOT used for ordering — revocation is218 * terminal, so the timestamp is display metadata only and cannot be used to219 * win or lose a race (HOLE 2).220 */221export async function mergeDeviceRevocations(222  incoming: DeviceRevocation[],223): Promise<string[]> {224  const existing = await listDeviceRevocations();225  const known = new Set(existing.map((r) => r.deviceId));226  const fresh = incoming227    .filter((r) => !known.has(r.deviceId))228    // Clamped for display sanity only — a year-9999 revokedAt would render as229    // nonsense. The protection against ordering games is that revocation is230    // terminal, not this clamp (HOLE 2 audit in sync-limits.ts).231    .map((r) => ({ ...r, revokedAt: clampSyncTimestamp(r.revokedAt) }));232  if (fresh.length === 0) return [];233  await storeRevocations([...existing, ...fresh].slice(-MAX_REVOCATIONS));234  return fresh.map((r) => r.deviceId);235}236237/**238 * Clear a revocation. The ONLY legitimate caller is a direct, SAS-confirmed239 * re-pair: a physically present user on both devices is a stronger consent240 * signal than whatever created the original pairing. Never call this from a241 * path a remote peer can reach.242 */243export async function clearDeviceRevocation(deviceId: string): Promise<void> {244  const existing = await listDeviceRevocations();245  const filtered = existing.filter((r) => r.deviceId !== deviceId);246  if (filtered.length === existing.length) return;247  await storeRevocations(filtered);248}249250/**251 * Repair the invalid paired+revoked overlap produced by older direct-pair252 * handlers.253 *254 * A newer direct, SAS-confirmed pair is the only state allowed to lift the255 * older revocation. Every other overlap resolves in favour of the revocation,256 * including vouched devices and pairs that predate the removal.257 */258export async function repairPairedRevocationOverlaps(): Promise<{259  revocationsCleared: number;260  pairedRowsRemoved: number;261}> {262  const devices = await listPairedDevices();263  const revocations = await listDeviceRevocations();264  const revocationById = new Map(revocations.map((record) => [record.deviceId, record]));265  const revocationIdsToClear = new Set<string>();266  const pairedIdsToRemove = new Set<string>();267268  for (const device of devices) {269    const revocation = revocationById.get(device.deviceId);270    if (!revocation) continue;271    if (device.trustSource === "direct" && device.pairedAt > revocation.revokedAt) {272      revocationIdsToClear.add(device.deviceId);273    } else {274      pairedIdsToRemove.add(device.deviceId);275    }276  }277278  if (revocationIdsToClear.size === 0 && pairedIdsToRemove.size === 0) {279    return { revocationsCleared: 0, pairedRowsRemoved: 0 };280  }281282  await chrome.storage.local.set({283    [REGISTRY_KEY]: devices.filter((device) => !pairedIdsToRemove.has(device.deviceId)),284    [REVOCATIONS_KEY]: revocations.filter(285      (record) => !revocationIdsToClear.has(record.deviceId),286    ),287  });288  return {289    revocationsCleared: revocationIdsToClear.size,290    pairedRowsRemoved: pairedIdsToRemove.size,291  };292}293294async function storeRevocations(records: DeviceRevocation[]): Promise<void> {295  await chrome.storage.local.set({ [REVOCATIONS_KEY]: records });296}297298function isDeviceRevocation(x: unknown): x is DeviceRevocation {299  if (typeof x !== "object" || x === null) return false;300  const r = x as Record<string, unknown>;301  return (302    typeof r.deviceId === "string" &&303    !!r.deviceId &&304    typeof r.longTermPublicKeyHex === "string" &&305    typeof r.revokedAt === "number" &&306    typeof r.revokedByDeviceId === "string"307  );308}309310export async function clearPairedDevices(): Promise<void> {311  await chrome.storage.local.remove(REGISTRY_KEY);312}313314export async function markLastSyncedAt(deviceId: string, when: number): Promise<void> {315  const devices = await listPairedDevices();316  const idx = devices.findIndex((d) => d.deviceId === deviceId);317  if (idx < 0) return;318  devices[idx] = { ...devices[idx], lastSyncedAt: when };319  await chrome.storage.local.set({ [REGISTRY_KEY]: devices });320}321322export async function getLastKnownIp(pubkeyHex: string): Promise<string | null> {323  try {324    const key = LAST_IP_KEY_PREFIX + pubkeyHex;325    const result = await chrome.storage.local.get(key);326    const value = (result as Record<string, unknown>)[key];327    return typeof value === "string" ? value : null;328  } catch {329    return null;330  }331}332333export async function setLastKnownIp(pubkeyHex: string, ip: string): Promise<void> {334  await chrome.storage.local.set({ [LAST_IP_KEY_PREFIX + pubkeyHex]: ip });335}336337export async function clearLastKnownIp(pubkeyHex: string): Promise<void> {338  await chrome.storage.local.remove(LAST_IP_KEY_PREFIX + pubkeyHex);339}340341export async function getLastSyncAt(): Promise<number | null> {342  try {343    const result = await chrome.storage.local.get(LAST_SYNC_AT_KEY);344    const value = (result as Record<string, unknown>)[LAST_SYNC_AT_KEY];345    if (typeof value === "number") return value;346    if (typeof value === "string" && value !== "") {347      const n = Number.parseInt(value, 10);348      return Number.isFinite(n) ? n : null;349    }350    return null;351  } catch {352    return null;353  }354}355356export async function setLastSyncAt(when: number): Promise<void> {357  await chrome.storage.local.set({ [LAST_SYNC_AT_KEY]: when });358}359360/**361 * The last sync ATTEMPT, not just the last success. A 3-second flash in the362 * popup is useless for debugging a real phone, so every terminating path363 * writes this and Settings reads it back after the fact — including across an364 * MV3 service-worker restart.365 */366export interface SyncResult {367  outcome: SyncOutcome;368  detail?: string;369  /** When the attempt finished, success or not. */370  at: number;371  entriesReceived: number;372  entriesSent: number;373}374375export async function getLastSyncResult(): Promise<SyncResult | null> {376  try {377    const result = await chrome.storage.local.get(LAST_SYNC_RESULT_KEY);378    const value = (result as Record<string, unknown>)[LAST_SYNC_RESULT_KEY];379    if (380      value &&381      typeof value === "object" &&382      typeof (value as Record<string, unknown>).outcome === "string" &&383      typeof (value as Record<string, unknown>).at === "number" &&384      typeof (value as Record<string, unknown>).entriesReceived === "number" &&385      typeof (value as Record<string, unknown>).entriesSent === "number"386    ) {387      return value as SyncResult;388    }389    return null;390  } catch {391    return null;392  }393}394395export async function setLastSyncResult(result: SyncResult): Promise<void> {396  await chrome.storage.local.set({ [LAST_SYNC_RESULT_KEY]: result });397}398399function isPairedDevice(x: unknown): x is PairedDevice {400  if (typeof x !== "object" || x === null) return false;401  const r = x as Record<string, unknown>;402  if (typeof r.deviceId !== "string" || !r.deviceId) return false;403  if (typeof r.pairedAt !== "number") return false;404  if (405    r.rendezvousSecretHex !== undefined &&406    (typeof r.rendezvousSecretHex !== "string" || !/^[0-9a-f]{64}$/.test(r.rendezvousSecretHex))407  ) {408    return false;409  }410  if (r.relayUrl !== undefined) {411    if (typeof r.relayUrl !== "string") return false;412    try {413      if (new URL(r.relayUrl).protocol !== "wss:") return false;414    } catch {415      return false;416    }417  }418  return true;419}