paired-devices.ts

12.2 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 { clampSyncTimestamp } from "../shared/sync-limits";2627const REGISTRY_KEY = "peach_paired_devices_v3";28const REVOCATIONS_KEY = "peach_device_revocations_v1";29/** Bound the list so a hostile peer cannot grow storage without limit. */30const MAX_REVOCATIONS = 500;31const LAST_IP_KEY_PREFIX = "peach_last_known_ip_v3:";32const LAST_SYNC_AT_KEY = "peach_last_sync_at";33const LAST_SYNC_RESULT_KEY = "peach_last_sync_result";3435export async function listPairedDevices(): Promise<PairedDevice[]> {36  try {37    const result = await chrome.storage.local.get(REGISTRY_KEY);38    const devices = (result as Record<string, unknown>)[REGISTRY_KEY];39    if (Array.isArray(devices)) return devices.filter(isPairedDevice);40    return [];41  } catch {42    return [];43  }44}4546export async function findPairedDeviceById(deviceId: string): Promise<PairedDevice | null> {47  const devices = await listPairedDevices();48  return devices.find((d) => d.deviceId === deviceId) ?? null;49}5051export async function findPairedDeviceByPubkey(pubkeyHex: string): Promise<PairedDevice | null> {52  const devices = await listPairedDevices();53  return devices.find((d) =>54    d.longTermPublicKeyHex !== undefined &&55    constantTimeEqualHex(d.longTermPublicKeyHex, pubkeyHex)56  ) ?? null;57}5859/**60 * Add or update a device by `deviceId`. On re-pair the new pubkey61 * silently replaces the old one; the deviceId is stable across the62 * other device's reinstall.63 */64export async function upsertPairedDevice(device: PairedDevice): Promise<void> {65  if (!device.deviceId) throw new Error("device.deviceId is required");66  if (!device.longTermPublicKeyHex) throw new Error("device.longTermPublicKeyHex is required");67  if (!device.deviceName) throw new Error("device.deviceName is required");68  if (!device.deviceType) throw new Error("device.deviceType is required");6970  const devices = await listPairedDevices();71  const idx = devices.findIndex((d) => d.deviceId === device.deviceId);72  if (idx >= 0) {73    devices[idx] = { ...devices[idx], ...device };74  } else {75    devices.push(device);76  }77  await chrome.storage.local.set({ [REGISTRY_KEY]: devices });78}7980/**81 * Move every existing pair to the user-selected mesh relay.82 *83 * Reconnect prefers the relay stored on each pair over the global fallback, so84 * changing only the setting would leave established devices on the old relay.85 */86export async function setRelayUrlForAllPairedDevices(87  relayUrl: string,88): Promise<void> {89  const devices = await listPairedDevices();90  if (devices.length === 0) return;91  await chrome.storage.local.set({92    [REGISTRY_KEY]: devices.map((device) => ({ ...device, relayUrl })),93  });94}9596/**97 * Removes the device from the LOCAL paired-devices registry only, leaving no98 * record behind. Prefer `revokeDeviceById` for anything the user would call99 * "remove this device" — a plain removal is silently undone the next time any100 * peer vouches the device back through a manifest.101 *102 * SECURITY NOTE (MV-8): this does NOT prevent the removed device from103 * syncing with OTHER peers in the device graph, and the device RETAINS104 * its copy of the vault root key (syncMasterKey) — it can still decrypt105 * anything it already holds and anything other peers send it. For a106 * lost or stolen device, removal is insufficient: use "Rotate sync107 * identity" (vault.ts rotateSyncIdentity), which re-keys the vault so108 * the old device's key material is useless.109 */110export async function removePairedDeviceById(deviceId: string): Promise<void> {111  const devices = await listPairedDevices();112  const filtered = devices.filter((d) => d.deviceId !== deviceId);113  // Unpairing is local-only — there is no remote unpair RPC. The remote114  // device retains this device in its own registry. Noise KK rejection on115  // the next connection attempt is the security boundary.116  await chrome.storage.local.set({ [REGISTRY_KEY]: filtered });117  // Also clear the per-network IP cache for this device.118  const device = devices.find((d) => d.deviceId === deviceId);119  if (device?.longTermPublicKeyHex) {120    await chrome.storage.local.remove(LAST_IP_KEY_PREFIX + device.longTermPublicKeyHex);121  }122}123124// ---------------------------------------------------------------------------125// Device revocation (Part 5 §C) — a removal that propagates and stays removed.126// ---------------------------------------------------------------------------127128export async function listDeviceRevocations(): Promise<DeviceRevocation[]> {129  try {130    const result = await chrome.storage.local.get(REVOCATIONS_KEY);131    const value = (result as Record<string, unknown>)[REVOCATIONS_KEY];132    if (Array.isArray(value)) return value.filter(isDeviceRevocation);133    return [];134  } catch {135    return [];136  }137}138139export async function isDeviceRevoked(deviceId: string): Promise<boolean> {140  return (await listDeviceRevocations()).some((r) => r.deviceId === deviceId);141}142143/**144 * Revoke a device: record it locally, then drop it from the registry and the145 * pending-vouch queue. The record rides out in every manifest this device146 * signs from now on, and blocks the device being vouched back in.147 */148export async function revokeDeviceById(149  deviceId: string,150  revokedByDeviceId: string,151  options: { now?: number } = {},152): Promise<DeviceRevocation | null> {153  const device = await findPairedDeviceById(deviceId);154  const existing = await listDeviceRevocations();155  if (existing.some((r) => r.deviceId === deviceId)) return null;156157  const record: DeviceRevocation = {158    deviceId,159    // A device with no stored key was never usable as a sync peer; the160    // all-zero key keeps the record well-formed on the wire without161    // pretending to name a key we never saw.162    longTermPublicKeyHex: device?.longTermPublicKeyHex ?? "0".repeat(64),163    revokedAt: options.now ?? Date.now(),164    revokedByDeviceId,165  };166  await storeRevocations([...existing, record]);167  await removePairedDeviceById(deviceId);168  return record;169}170171/**172 * Merge revocations learned from a peer's manifest. Returns the deviceIds that173 * were newly revoked, so the caller can evict them.174 *175 * `revokedAt` is peer-supplied and is NOT used for ordering — revocation is176 * terminal, so the timestamp is display metadata only and cannot be used to177 * win or lose a race (HOLE 2).178 */179export async function mergeDeviceRevocations(180  incoming: DeviceRevocation[],181): Promise<string[]> {182  const existing = await listDeviceRevocations();183  const known = new Set(existing.map((r) => r.deviceId));184  const fresh = incoming185    .filter((r) => !known.has(r.deviceId))186    // Clamped for display sanity only — a year-9999 revokedAt would render as187    // nonsense. The protection against ordering games is that revocation is188    // terminal, not this clamp (HOLE 2 audit in sync-limits.ts).189    .map((r) => ({ ...r, revokedAt: clampSyncTimestamp(r.revokedAt) }));190  if (fresh.length === 0) return [];191  await storeRevocations([...existing, ...fresh].slice(-MAX_REVOCATIONS));192  return fresh.map((r) => r.deviceId);193}194195/**196 * Clear a revocation. The ONLY legitimate caller is a direct, SAS-confirmed197 * re-pair: a physically present user on both devices is a stronger consent198 * signal than whatever created the original pairing. Never call this from a199 * path a remote peer can reach.200 */201export async function clearDeviceRevocation(deviceId: string): Promise<void> {202  const existing = await listDeviceRevocations();203  const filtered = existing.filter((r) => r.deviceId !== deviceId);204  if (filtered.length === existing.length) return;205  await storeRevocations(filtered);206}207208async function storeRevocations(records: DeviceRevocation[]): Promise<void> {209  await chrome.storage.local.set({ [REVOCATIONS_KEY]: records });210}211212function isDeviceRevocation(x: unknown): x is DeviceRevocation {213  if (typeof x !== "object" || x === null) return false;214  const r = x as Record<string, unknown>;215  return (216    typeof r.deviceId === "string" &&217    !!r.deviceId &&218    typeof r.longTermPublicKeyHex === "string" &&219    typeof r.revokedAt === "number" &&220    typeof r.revokedByDeviceId === "string"221  );222}223224export async function clearPairedDevices(): Promise<void> {225  await chrome.storage.local.remove(REGISTRY_KEY);226}227228export async function markLastSyncedAt(deviceId: string, when: number): Promise<void> {229  const devices = await listPairedDevices();230  const idx = devices.findIndex((d) => d.deviceId === deviceId);231  if (idx < 0) return;232  devices[idx] = { ...devices[idx], lastSyncedAt: when };233  await chrome.storage.local.set({ [REGISTRY_KEY]: devices });234}235236export async function getLastKnownIp(pubkeyHex: string): Promise<string | null> {237  try {238    const key = LAST_IP_KEY_PREFIX + pubkeyHex;239    const result = await chrome.storage.local.get(key);240    const value = (result as Record<string, unknown>)[key];241    return typeof value === "string" ? value : null;242  } catch {243    return null;244  }245}246247export async function setLastKnownIp(pubkeyHex: string, ip: string): Promise<void> {248  await chrome.storage.local.set({ [LAST_IP_KEY_PREFIX + pubkeyHex]: ip });249}250251export async function clearLastKnownIp(pubkeyHex: string): Promise<void> {252  await chrome.storage.local.remove(LAST_IP_KEY_PREFIX + pubkeyHex);253}254255export async function getLastSyncAt(): Promise<number | null> {256  try {257    const result = await chrome.storage.local.get(LAST_SYNC_AT_KEY);258    const value = (result as Record<string, unknown>)[LAST_SYNC_AT_KEY];259    if (typeof value === "number") return value;260    if (typeof value === "string" && value !== "") {261      const n = Number.parseInt(value, 10);262      return Number.isFinite(n) ? n : null;263    }264    return null;265  } catch {266    return null;267  }268}269270export async function setLastSyncAt(when: number): Promise<void> {271  await chrome.storage.local.set({ [LAST_SYNC_AT_KEY]: when });272}273274export interface SyncResult {275  entriesReceived: number;276  entriesSent: number;277}278279export async function getLastSyncResult(): Promise<SyncResult | null> {280  try {281    const result = await chrome.storage.local.get(LAST_SYNC_RESULT_KEY);282    const value = (result as Record<string, unknown>)[LAST_SYNC_RESULT_KEY];283    if (284      value &&285      typeof value === "object" &&286      typeof (value as Record<string, unknown>).entriesReceived === "number" &&287      typeof (value as Record<string, unknown>).entriesSent === "number"288    ) {289      return value as SyncResult;290    }291    return null;292  } catch {293    return null;294  }295}296297export async function setLastSyncResult(result: SyncResult): Promise<void> {298  await chrome.storage.local.set({ [LAST_SYNC_RESULT_KEY]: result });299}300301function isPairedDevice(x: unknown): x is PairedDevice {302  if (typeof x !== "object" || x === null) return false;303  const r = x as Record<string, unknown>;304  if (typeof r.deviceId !== "string" || !r.deviceId) return false;305  if (typeof r.pairedAt !== "number") return false;306  if (307    r.rendezvousSecretHex !== undefined &&308    (typeof r.rendezvousSecretHex !== "string" || !/^[0-9a-f]{64}$/.test(r.rendezvousSecretHex))309  ) {310    return false;311  }312  if (r.relayUrl !== undefined) {313    if (typeof r.relayUrl !== "string") return false;314    try {315      if (new URL(r.relayUrl).protocol !== "wss:") return false;316    } catch {317      return false;318    }319  }320  return true;321}