paired-devices.ts

35.8 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// `deviceId` is the canonical primary key (UUID v4, stable for the9// lifetime of the installation). Its cryptographic identity keys are10// immutable once persisted; a direct re-pair must use a fresh deviceId.11//12// The registry has only ever lived in `chrome.storage.local` for released13// builds, so no cross-profile evacuation path is needed — the public keys14// never leave the device via a third-party sync back-end. Unpairing is15// local-only; Noise KK rejection on the next connection is the security16// boundary (see removePairedDeviceById).1718import { signDeviceRevocation } from "../shared/device-manifest";19import type { DeviceRevocation, PairedDevice } from "../shared/sync-types";20import { constantTimeEqualHex } from "../shared/constant-time";21import { capDeviceName, clampSyncTimestamp } from "../shared/sync-limits";22import type { SyncOutcome } from "../shared/sync-outcome";2324export const REGISTRY_KEY = "peach_paired_devices_v3";25export const REVOCATIONS_KEY = "peach_device_revocations_v1";26export const REVOCATION_ISSUERS_KEY = "peach_revocation_issuers_v1";2728type RevocationIssuer = {29  deviceId: string;30  longTermPublicKeyHex: string;31  signingPublicKeys: string[];32};3334function publicSigningKeys(device: PairedDevice): string[] {35  return [...new Set([36    ...(device.signingKeyHistory ?? []).filter((key) => Number.isInteger(key.version) && key.version > 0).map((key) => key.publicKeyHex),37    device.signingPublicKeyHex,38  ].filter((key): key is string => typeof key === "string" && /^[0-9a-f]{64}$/i.test(key))39    .map((key) => key.toLowerCase()))];40}4142async function listRevocationIssuersRaw(): Promise<RevocationIssuer[]> {43  return parseRevocationIssuers((await chrome.storage.local.get(REVOCATION_ISSUERS_KEY))[REVOCATION_ISSUERS_KEY]);44}4546function parseRevocationIssuers(value: unknown): RevocationIssuer[] {47  if (value === undefined) return [];48  if (!Array.isArray(value) || value.some((entry: unknown) => {49    if (!entry || typeof entry !== "object") return true;50    const issuer = entry as Partial<RevocationIssuer>;51    return typeof issuer.deviceId !== "string" || !issuer.deviceId ||52      typeof issuer.longTermPublicKeyHex !== "string" || !/^[0-9a-f]{64}$/i.test(issuer.longTermPublicKeyHex) ||53      !Array.isArray(issuer.signingPublicKeys) || issuer.signingPublicKeys.some((key: unknown) => typeof key !== "string" || !/^[0-9a-f]{64}$/i.test(key));54  })) throw new TrustDataCorruptedError(REVOCATION_ISSUERS_KEY, "invalid issuer archive");55  return (value as RevocationIssuer[]).map((issuer) => ({56    deviceId: issuer.deviceId,57    longTermPublicKeyHex: issuer.longTermPublicKeyHex.toLowerCase(),58    signingPublicKeys: issuer.signingPublicKeys.map((key) => key.toLowerCase()),59  }));60}6162async function retainRevocationIssuers(devices: PairedDevice[]): Promise<RevocationIssuer[]> {63  const archive = (await listRevocationIssuersRaw()).map((issuer) => ({ ...issuer, signingPublicKeys: [...issuer.signingPublicKeys] }));64  for (const device of devices) {65    if (device.trustSource !== "direct" && device.trustSource !== "vouched") continue;66    if (!device.longTermPublicKeyHex || !/^[0-9a-f]{64}$/i.test(device.longTermPublicKeyHex)) continue;67    const keys = publicSigningKeys(device);68    if (!keys.length) continue;69    const binding = device.longTermPublicKeyHex.toLowerCase();70    const existing = archive.find((issuer) => issuer.deviceId === device.deviceId && issuer.longTermPublicKeyHex === binding);71    if (existing) existing.signingPublicKeys = [...new Set([...existing.signingPublicKeys, ...keys])];72    else archive.push({ deviceId: device.deviceId, longTermPublicKeyHex: binding, signingPublicKeys: keys });73  }74  return archive;75}7677/// One consistent snapshot of live and archived record-verification keys.78export async function listRevocationIssuerKeyMap(): Promise<Map<string, string[]>> {79  await deviceMutationTail;80  const stored = await chrome.storage.local.get([REGISTRY_KEY, REVOCATION_ISSUERS_KEY]);81  const keys = new Map<string, string[]>();82  const issuers = parseRevocationIssuers(stored[REVOCATION_ISSUERS_KEY]);83  for (const device of parsePairedDevices(stored[REGISTRY_KEY])) {84    if (device.trustSource === "direct" || device.trustSource === "vouched") {85      issuers.push({ deviceId: device.deviceId, longTermPublicKeyHex: device.longTermPublicKeyHex ?? "", signingPublicKeys: publicSigningKeys(device) });86    }87  }88  for (const issuer of issuers) {89    keys.set(issuer.deviceId, [...new Set([...(keys.get(issuer.deviceId) ?? []), ...issuer.signingPublicKeys])]);90  }91  return keys;92}9394export async function hasRevocationIssuerArchive(): Promise<boolean> {95  await deviceMutationTail;96  return (await listRevocationIssuersRaw()).length > 0;97}98/** Bound the list so a hostile peer cannot grow storage without limit. */99const MAX_REVOCATIONS = 500;100const LAST_SYNC_AT_KEY = "peach_last_sync_at";101const LAST_SYNC_RESULT_KEY = "peach_last_sync_result";102let deviceMutationTail: Promise<void> = Promise.resolve();103104function enqueueDeviceMutation<T>(mutation: () => Promise<T>): Promise<T> {105  const result = deviceMutationTail.then(mutation, mutation);106  deviceMutationTail = result.then(() => undefined, () => undefined);107  return result;108}109110/**111 * §18.4: a corrupt persisted registry is an integrity error, not an empty112 * list. An absent key is legitimate (no devices paired yet); a present but113 * unparseable value means trust state was damaged and must not be silently114 * cleared — that would un-revoke every device. The corrupt payload is115 * preserved (this function never writes) so a future repair can attempt116 * recovery.117 */118export class TrustDataCorruptedError extends Error {119  constructor(key: string, detail: string) {120    super(`trust_data_corrupted:${key}:${detail}`);121    this.name = "TrustDataCorruptedError";122  }123}124125async function listPairedDevicesRaw(): Promise<PairedDevice[]> {126  const result = await chrome.storage.local.get(REGISTRY_KEY);127  return parsePairedDevices((result as Record<string, unknown>)[REGISTRY_KEY]);128}129130function parsePairedDevices(devices: unknown): PairedDevice[] {131  if (devices === undefined) return [];132  if (!Array.isArray(devices)) {133    throw new TrustDataCorruptedError(REGISTRY_KEY, `expected array, got ${typeof devices}`);134  }135  return devices.filter(isPairedDevice);136}137138export async function listPairedDevices(): Promise<PairedDevice[]> {139  await deviceMutationTail;140  return listPairedDevicesRaw();141}142143export async function findPairedDeviceById(deviceId: string): Promise<PairedDevice | null> {144  const devices = await listPairedDevices();145  return devices.find((d) => d.deviceId === deviceId) ?? null;146}147148export async function findPairedDeviceByPubkey(pubkeyHex: string): Promise<PairedDevice | null> {149  const devices = await listPairedDevices();150  return devices.find((d) =>151    d.longTermPublicKeyHex !== undefined &&152    constantTimeEqualHex(d.longTermPublicKeyHex, pubkeyHex),153  ) ?? null;154}155156/**157 * Durable registry write. PB-26-213: the reusable rendezvous secret must158 * never persist into the public registry — it is stripped here so a159 * missed writer fails closed to a secretless row instead of plaintext disk.160 */161export async function writePairedDevices(devices: PairedDevice[]): Promise<void> {162  await enqueueDeviceMutation(() => writePairedDevicesRaw(devices));163}164165async function writePairedDevicesRaw(devices: PairedDevice[]): Promise<void> {166  const retained = await retainRevocationIssuers(retiredIssuerRows(await listPairedDevicesRaw(), devices));167  await chrome.storage.local.set({168    [REVOCATION_ISSUERS_KEY]: retained,169    [REGISTRY_KEY]: devices.map((device) => {170      const normalized = withSigningKeyHistory(device);171      if (!isValidSecret(normalized.rendezvousSecretHex)) return normalized;172      const scrubbed = { ...normalized };173      delete scrubbed.rendezvousSecretHex;174      return scrubbed;175    }),176  });177}178179function retiredIssuerRows(previous: PairedDevice[], next: PairedDevice[]): PairedDevice[] {180  return previous.flatMap((device) => {181    const remaining = next.find((row) => row.deviceId === device.deviceId &&182      row.longTermPublicKeyHex?.toLowerCase() === device.longTermPublicKeyHex?.toLowerCase());183    if (!remaining || (remaining.trustSource !== "direct" && remaining.trustSource !== "vouched")) return [device];184    const retainedKeys = new Set(publicSigningKeys(remaining));185    const retiredKeys = new Set(publicSigningKeys(device).filter((key) => !retainedKeys.has(key)));186    if (!retiredKeys.size) return [];187    return [{188      ...device,189      signingPublicKeyHex: retiredKeys.has(device.signingPublicKeyHex?.toLowerCase() ?? "") ? device.signingPublicKeyHex : undefined,190      signingKeyHistory: device.signingKeyHistory?.filter((key) => retiredKeys.has(key.publicKeyHex.toLowerCase())),191    }];192  });193}194195function isValidSecret(value: unknown): value is string {196  return typeof value === "string" && /^[0-9a-f]{64}$/.test(value);197}198199/**200 * Add or update a device by `deviceId`. Existing cryptographic identity keys201 * are immutable; metadata-only updates merge into the stored row.202 */203export async function upsertPairedDevice(device: PairedDevice): Promise<void> {204  if (!device.deviceId) throw new Error("device.deviceId is required");205  if (!device.longTermPublicKeyHex) throw new Error("device.longTermPublicKeyHex is required");206  if (!device.deviceName) throw new Error("device.deviceName is required");207  if (!device.deviceType) throw new Error("device.deviceType is required");208  await upsertPairedDevices([device]);209}210211export async function upsertPairedDevices(devices: PairedDevice[]): Promise<void> {212  await enqueueDeviceMutation(async () => {213    const stored = await listPairedDevicesRaw();214    const incomingById = new Map<string, PairedDevice>();215    for (const device of devices) {216      if (!device.deviceId) throw new Error("device.deviceId is required");217      if (!device.longTermPublicKeyHex) throw new Error("device.longTermPublicKeyHex is required");218      if (!device.deviceName) throw new Error("device.deviceName is required");219      if (!device.deviceType) throw new Error("device.deviceType is required");220      const normalized = { ...device, deviceName: capDeviceName(device.deviceName) };221      const previous = incomingById.get(normalized.deviceId);222      if (previous) {223        assertIdentityBinding(previous, normalized);224        throw new Error("device_identity_duplicate");225      }226      incomingById.set(normalized.deviceId, normalized);227      const existing = stored.find((candidate) => candidate.deviceId === normalized.deviceId);228      if (existing) assertIdentityBinding(existing, normalized);229    }230    for (const device of incomingById.values()) {231      const index = stored.findIndex((candidate) => candidate.deviceId === device.deviceId);232      if (index >= 0) {233        const existing = stored[index];234        const merged = { ...existing, ...device };235        if (typeof existing.signingPublicKeyHex === "string" && device.signingPublicKeyHex == null) {236          merged.signingPublicKeyHex = existing.signingPublicKeyHex;237        }238        stored[index] = merged;239      } else {240        stored.push(device);241      }242    }243    await writePairedDevicesRaw(stored);244  });245}246247/** Validate identity bindings without changing the registry. */248export async function validatePairedDeviceIdentities(devices: PairedDevice[]): Promise<void> {249  await enqueueDeviceMutation(async () => {250    const stored = await listPairedDevicesRaw();251    const incomingById = new Map<string, PairedDevice>();252    for (const device of devices) {253      const previous = incomingById.get(device.deviceId);254      if (previous) {255        assertIdentityBinding(previous, device);256        throw new Error("device_identity_duplicate");257      }258      incomingById.set(device.deviceId, device);259      const existing = stored.find((candidate) => candidate.deviceId === device.deviceId);260      if (existing) assertIdentityBinding(existing, device);261    }262  });263}264265function validateAndIndexDevices(266  stored: PairedDevice[],267  devices: PairedDevice[],268): Map<string, PairedDevice> {269  const incomingById = new Map<string, PairedDevice>();270  for (const device of devices) {271    if (!device.deviceId) throw new Error("device.deviceId is required");272    if (!device.longTermPublicKeyHex) throw new Error("device.longTermPublicKeyHex is required");273    if (!device.deviceName) throw new Error("device.deviceName is required");274    if (!device.deviceType) throw new Error("device.deviceType is required");275    const normalized = { ...device, deviceName: capDeviceName(device.deviceName) };276    const previous = incomingById.get(normalized.deviceId);277    if (previous) {278      assertIdentityBinding(previous, normalized);279      throw new Error("device_identity_duplicate");280    }281    incomingById.set(normalized.deviceId, normalized);282    const existing = stored.find((candidate) => candidate.deviceId === normalized.deviceId);283    if (existing) assertIdentityBinding(existing, normalized);284  }285  return incomingById;286}287288function assertIdentityBinding(existing: PairedDevice, incoming: PairedDevice): void {289  if (290    typeof existing.longTermPublicKeyHex === "string" &&291    typeof incoming.longTermPublicKeyHex === "string" &&292    !constantTimeEqualHex(existing.longTermPublicKeyHex, incoming.longTermPublicKeyHex)293  ) {294    throw new Error("device_identity_immutable");295  }296  if (297    typeof existing.signingPublicKeyHex === "string" &&298    typeof incoming.signingPublicKeyHex === "string" &&299    !constantTimeEqualHex(existing.signingPublicKeyHex, incoming.signingPublicKeyHex)300  ) {301    throw new Error("device_identity_immutable");302  }303}304function withSigningKeyHistory(device: PairedDevice): PairedDevice {305  if (!device.signingPublicKeyHex || !device.signingKeyHistory?.length) return device;306  const current = device.signingPublicKeyHex.toLowerCase();307  const history = device.signingKeyHistory308    .filter((key) => Number.isInteger(key.version) && key.version > 0 && /^[0-9a-f]{64}$/i.test(key.publicKeyHex))309    .map((key) => ({ version: key.version, publicKeyHex: key.publicKeyHex.toLowerCase() }));310  return { ...device, signingKeyHistory: [...history.filter((key) => key.publicKeyHex !== current), { version: history.find((key) => key.publicKeyHex === current)?.version ?? history.reduce((max, key) => Math.max(max, key.version), 0) + 1, publicKeyHex: current }] };311}312313export async function renamePairedDevice(deviceId: string, name: string): Promise<void> {314  const alias = name.trim();315  if (!alias) throw new Error("device name must not be empty");316  if (alias.length > 64) throw new Error("device name must be 64 chars or fewer");317  await enqueueDeviceMutation(async () => {318    const devices = await listPairedDevicesRaw();319    const index = devices.findIndex((device) => device.deviceId === deviceId);320    if (index < 0) throw new Error("device_not_found");321    devices[index] = { ...devices[index], localAlias: alias };322    await chrome.storage.local.set({ [REGISTRY_KEY]: devices });323  });324}325326/**327 * Move every existing pair to the user-selected mesh relay.328 *329 * Reconnect prefers the relay stored on each pair over the global fallback, so330 * changing only the setting would leave established devices on the old relay.331 */332export async function setRelayUrlForAllPairedDevices(333  relayUrl: string,334): Promise<void> {335  await enqueueDeviceMutation(async () => {336    const devices = await listPairedDevicesRaw();337    if (devices.length === 0) return;338    await chrome.storage.local.set({339      [REGISTRY_KEY]: devices.map((device) => ({ ...device, relayUrl })),340    });341  });342  // A relay change is mesh state — the next alarm tick or popup open will dial343  // with the new relay. No fire-and-forget trigger here; the in-flight guard344  // would just drop it on the burst of upserts that often follows.345}346347/**348 * Removes the device from the LOCAL paired-devices registry only, leaving no349 * record behind. Prefer `revokeDeviceById` for anything the user would call350 * "remove this device" — a plain removal is silently undone the next time any351 * peer vouches the device back through a manifest.352 *353 * SECURITY NOTE (MV-8): this does NOT prevent the removed device from354 * syncing with OTHER peers in the device graph, and the device RETAINS355 * its copy of the vault root key (syncMasterKey) — it can still decrypt356 * anything it already holds and anything other peers send it. For a357 * lost or stolen device, removal is insufficient: use "Rotate sync358 * identity" (vault.ts rotateSyncIdentity), which re-keys the vault so359 * the old device's key material is useless.360 */361export async function removePairedDeviceById(deviceId: string): Promise<void> {362  await enqueueDeviceMutation(async () => {363    const devices = await listPairedDevicesRaw();364    await chrome.storage.local.set({365      [REGISTRY_KEY]: devices.filter((d) => d.deviceId !== deviceId),366      [REVOCATION_ISSUERS_KEY]: await retainRevocationIssuers(devices.filter((d) => d.deviceId === deviceId)),367    });368  });369  // The device-list-changed sync trigger fires from the messages.ts UNPAIR_DEVICE370  // handler — see upsertPairedDevice for why this lives there, not here.371}372373// ---------------------------------------------------------------------------374// Device revocation (Part 5 §C) — a removal that propagates and stays removed.375// ---------------------------------------------------------------------------376377async function listDeviceRevocationsRaw(): Promise<DeviceRevocation[]> {378  const result = await chrome.storage.local.get(REVOCATIONS_KEY);379  const value = (result as Record<string, unknown>)[REVOCATIONS_KEY];380  if (value === undefined) return [];381  if (!Array.isArray(value)) {382    throw new TrustDataCorruptedError(REVOCATIONS_KEY, `expected array, got ${typeof value}`);383  }384  return value.filter(isDeviceRevocation);385}386387export async function listDeviceRevocations(): Promise<DeviceRevocation[]> {388  await deviceMutationTail;389  return listDeviceRevocationsRaw();390}391392/**393 * True when either the id or the long-term key is under a terminal revocation.394 *395 * `deviceId` is a self-asserted string in a manifest, so keying terminality on396 * it alone is bypassed by re-vouching a revoked device's key under a fresh id.397 * The key is the thing a revoked device actually still holds, so it is the398 * thing terminality has to follow.399 */400export async function isDeviceRevoked(401  deviceId: string,402  longTermPublicKeyHex?: string,403): Promise<boolean> {404  // The all-zero sentinel stands for "we never stored a key for this device"405  // (see revokeDeviceById) and must not match a real one.406  const key = longTermPublicKeyHex?.toLowerCase();407  const keyIsRevocable = key !== undefined && key !== "0".repeat(64);408  await deviceMutationTail;409  return (await listDeviceRevocationsRaw()).some(410    (r) =>411      r.deviceId === deviceId ||412      (keyIsRevocable && r.longTermPublicKeyHex.toLowerCase() === key),413  );414}415416/**417 * Revoke a device: record it locally, then drop it from the registry. The418 * record rides out in every manifest this device signs from now on, and blocks419 * the device being vouched back in. A stale entry may survive in the420 * pending-vouch queue; the confirm handler re-checks revocation before421 * promoting anything out of it.422 */423export async function revokeDeviceById(424  deviceId: string,425  issuer: string | (() => Promise<string>),426  options: { now?: number } = {},427): Promise<DeviceRevocation | null> {428  return enqueueDeviceMutation(async () => {429    const devices = await listPairedDevicesRaw();430    const device = devices.find((candidate) => candidate.deviceId === deviceId);431    const existing = await listDeviceRevocationsRaw();432    if (existing.some((r) => r.deviceId === deviceId)) {433      // A direct re-pair in older builds could restore the paired row without434      // clearing its terminal revocation. "Remove" then returned early here and435      // left the row visible forever. Idempotency applies to the revocation436      // record, not to removing any stale live row that overlaps it.437      if (device) await chrome.storage.local.set({438        [REGISTRY_KEY]: devices.filter((candidate) => candidate.deviceId !== deviceId),439        [REVOCATION_ISSUERS_KEY]: await retainRevocationIssuers(devices.filter((candidate) => candidate.deviceId === deviceId)),440      });441      return null;442    }443444    const revokedByDeviceId = typeof issuer === "string" ? issuer : await issuer();445    const record: DeviceRevocation = {446      deviceId,447      // A device with no stored key was never usable as a sync peer; the448      // all-zero key keeps the record well-formed on the wire without449      // pretending to name a key we never saw.450      longTermPublicKeyHex: device?.longTermPublicKeyHex ?? "0".repeat(64),451      revokedAt: options.now ?? Date.now(),452      revokedByDeviceId,453    };454    await chrome.storage.local.set({455      [REGISTRY_KEY]: devices.filter((candidate) => candidate.deviceId !== deviceId),456      [REVOCATION_ISSUERS_KEY]: await retainRevocationIssuers(devices.filter((candidate) => candidate.deviceId === deviceId)),457      [REVOCATIONS_KEY]: capRevocations([...existing, record]),458    });459    return record;460  });461}462463/// Seal this identity's outstanding records before replacing its credentials.464export async function rotatePairedDeviceIdentity(465  loadExistingIdentity: () => Promise<{466    identity: { deviceId: string; longTermPublicKeyHex: string; signingPublicKeyHex: string };467    privateKey: Uint8Array;468    publicKey: Uint8Array;469    signingPrivateKey: CryptoKey;470  }>,471  rotate: () => Promise<string>,472): Promise<string> {473  return enqueueDeviceMutation(async () => {474    const local = await loadExistingIdentity();475    try {476      const records = await listDeviceRevocationsRaw();477      const sealed = await Promise.all(records.map((record) =>478        record.revokedByDeviceId === local.identity.deviceId && !record.signatureHex479          ? signDeviceRevocation(record, local.signingPrivateKey)480          : record,481      ));482      await chrome.storage.local.set({483        [REVOCATIONS_KEY]: sealed,484        [REVOCATION_ISSUERS_KEY]: await retainRevocationIssuers([{485          deviceId: local.identity.deviceId,486          longTermPublicKeyHex: local.identity.longTermPublicKeyHex,487          signingPublicKeyHex: local.identity.signingPublicKeyHex,488          pairedAt: 0,489          trustSource: "direct",490        }]),491      });492      return await rotate();493    } finally {494      local.privateKey.fill(0);495      local.publicKey.fill(0);496    }497  });498}499500/**501 * Clear a revocation after an authenticated, SAS-confirmed direct re-pair.502 * A changed signing key is accepted only through this seam and the old key503 * remains in immutable history.504 */505export async function upsertPairedDeviceAndClearRevocation(device: PairedDevice): Promise<void> {506  if (!device.deviceId || !device.longTermPublicKeyHex || !device.deviceName || !device.deviceType) {507    throw new Error("invalid paired device");508  }509  await enqueueDeviceMutation(async () => {510    const devices = await listPairedDevicesRaw();511    const stored = devices.find((candidate) => candidate.deviceId === device.deviceId);512    const incoming = { ...device, deviceName: capDeviceName(device.deviceName!) };513    if (stored) {514      if (stored.longTermPublicKeyHex && incoming.longTermPublicKeyHex &&515          !constantTimeEqualHex(stored.longTermPublicKeyHex, incoming.longTermPublicKeyHex)) {516        throw new Error("device_identity_immutable");517      }518      if (stored.signingPublicKeyHex && incoming.signingPublicKeyHex &&519          !constantTimeEqualHex(stored.signingPublicKeyHex, incoming.signingPublicKeyHex)) {520        incoming.signingKeyHistory = [521          ...(stored.signingKeyHistory ?? []),522          { version: (stored.signingKeyHistory?.reduce((m, k) => Math.max(m, k.version), 0) ?? 0) + 1,523            publicKeyHex: stored.signingPublicKeyHex.toLowerCase() },524        ];525      }526    }527    const index = devices.findIndex((candidate) => candidate.deviceId === device.deviceId);528    if (index >= 0) {529      const merged = { ...devices[index], ...incoming };530      if (typeof devices[index].signingPublicKeyHex === "string" && incoming.signingPublicKeyHex == null) {531        merged.signingPublicKeyHex = devices[index].signingPublicKeyHex;532      }533      devices[index] = merged;534    } else {535      devices.push(incoming);536    }537    const revocations = await listDeviceRevocationsRaw();538    const filtered = revocations.filter((record) => record.deviceId !== device.deviceId);539    await chrome.storage.local.set({540      [REGISTRY_KEY]: scrubRegistryRows(devices),541      [REVOCATION_ISSUERS_KEY]: await retainRevocationIssuers(stored ? [stored] : []),542      [REVOCATIONS_KEY]: capRevocations(filtered),543    });544  });545}546547export async function upsertPairedDevicesAndMergeRevocations(548  devices: PairedDevice[],549  incomingRevocations: DeviceRevocation[],550): Promise<string[]> {551  return enqueueDeviceMutation(async () => {552    const previous = await listPairedDevicesRaw();553    const stored = [...previous];554    const incomingById = validateAndIndexDevices(stored, devices);555    const existingRevocations = await listDeviceRevocationsRaw();556    const knownById = new Set(existingRevocations.map((record) => record.deviceId));557    const fresh = incomingRevocations558      .filter((record) => !knownById.has(record.deviceId))559      .map((record) => ({ ...record, revokedAt: clampSyncTimestamp(record.revokedAt) }));560    const allRevocations = [...existingRevocations, ...fresh];561    const revokedIds = new Set(allRevocations.map((record) => record.deviceId));562    for (const device of incomingById.values()) {563      const index = stored.findIndex((candidate) => candidate.deviceId === device.deviceId);564      if (index >= 0) {565        const existing = stored[index];566        const merged = { ...existing, ...device };567        if (typeof existing.signingPublicKeyHex === "string" && device.signingPublicKeyHex == null) {568          merged.signingPublicKeyHex = existing.signingPublicKeyHex;569        }570        stored[index] = merged;571      } else {572        stored.push(device);573      }574    }575    const revokedKeys = new Set(576      allRevocations577        .map((record) => record.longTermPublicKeyHex.toLowerCase())578        .filter((key) => key !== "0".repeat(64)),579    );580    const registry = scrubRegistryRows(581      stored.filter(582        (device) =>583          !revokedIds.has(device.deviceId) &&584          !revokedKeys.has(device.longTermPublicKeyHex?.toLowerCase() ?? ""),585      ),586    );587    await chrome.storage.local.set({588      [REGISTRY_KEY]: registry,589      [REVOCATION_ISSUERS_KEY]: await retainRevocationIssuers(retiredIssuerRows(previous, registry)),590      [REVOCATIONS_KEY]: capRevocations(allRevocations),591    });592    return fresh.map((record) => record.deviceId);593  });594}595596function scrubRegistryRows(devices: PairedDevice[]): PairedDevice[] {597  return devices.map((entry) => {598    if (!isValidSecret(entry.rendezvousSecretHex)) return entry;599    const scrubbed = { ...entry };600    delete scrubbed.rendezvousSecretHex;601    return scrubbed;602  });603}604605/**606 * True when the incoming identity matches an existing paired device's deviceId607 * OR a terminal revocation record (by deviceId or long-term public key).608 * A fresh pairing ceremony must not reuse terminally revoked identity material.609 */610export async function hasAdoptionIdentityConflict(611  deviceId: string,612  longTermPublicKeyHex: string,613): Promise<boolean> {614  await deviceMutationTail;615  const devices = await listPairedDevicesRaw();616  if (devices.some((d) => d.deviceId === deviceId)) return true;617  const key = longTermPublicKeyHex.toLowerCase();618  return (await listDeviceRevocationsRaw()).some((record) =>619    record.deviceId === deviceId ||620    (key !== "0".repeat(64) && record.longTermPublicKeyHex.toLowerCase() === key)621  );622}623624/**625 * Merge revocations learned from a peer's manifest. Returns the deviceIds that626 * were newly revoked, so the caller can evict them.627 *628 * `revokedAt` is peer-supplied and is NOT used for ordering — revocation is629 * terminal, so the timestamp is display metadata only and cannot be used to630 * win or lose a race (HOLE 2).631 */632export async function mergeDeviceRevocations(633  incoming: DeviceRevocation[],634): Promise<string[]> {635  return enqueueDeviceMutation(async () => {636  const existing = await listDeviceRevocationsRaw();637  const known = new Set(existing.map((r) => r.deviceId));638  const fresh = incoming639    .filter((r) => !known.has(r.deviceId))640    // Clamped for display sanity only — a year-9999 revokedAt would render as641    // nonsense. The protection against ordering games is that revocation is642    // terminal, not this clamp (HOLE 2 audit in sync-limits.ts).643    .map((r) => ({ ...r, revokedAt: clampSyncTimestamp(r.revokedAt) }));644  if (fresh.length === 0) return [];645  await storeRevocationsRaw([...existing, ...fresh]);646  return fresh.map((r) => r.deviceId);647  });648}649650/**651 * Repair the invalid paired+revoked overlap produced by older direct-pair652 * handlers.653 *654 * A newer direct, SAS-confirmed pair is the only state allowed to lift the655 * older revocation. Every other overlap resolves in favour of the revocation,656 * including vouched devices and pairs that predate the removal.657 */658export async function repairPairedRevocationOverlaps(): Promise<{659  revocationsCleared: number;660  pairedRowsRemoved: number;661}> {662  return enqueueDeviceMutation(async () => {663  const devices = await listPairedDevicesRaw();664  const revocations = await listDeviceRevocationsRaw();665  const revocationById = new Map(revocations.map((record) => [record.deviceId, record]));666  const revocationIdsToClear = new Set<string>();667  const pairedIdsToRemove = new Set<string>();668669  for (const device of devices) {670    const revocation = revocationById.get(device.deviceId);671    if (!revocation) continue;672    if (device.trustSource === "direct" && device.pairedAt > revocation.revokedAt) {673      revocationIdsToClear.add(device.deviceId);674    } else {675      pairedIdsToRemove.add(device.deviceId);676    }677  }678679  if (revocationIdsToClear.size === 0 && pairedIdsToRemove.size === 0) {680    return { revocationsCleared: 0, pairedRowsRemoved: 0 };681  }682683  await chrome.storage.local.set({684    [REGISTRY_KEY]: devices.filter((device) => !pairedIdsToRemove.has(device.deviceId)),685    [REVOCATION_ISSUERS_KEY]: await retainRevocationIssuers(devices.filter((device) => pairedIdsToRemove.has(device.deviceId))),686    [REVOCATIONS_KEY]: revocations.filter(687      (record) => !revocationIdsToClear.has(record.deviceId),688    ),689  });690  return {691    revocationsCleared: revocationIdsToClear.size,692    pairedRowsRemoved: pairedIdsToRemove.size,693  };694  });695}696697async function storeRevocationsRaw(records: DeviceRevocation[]): Promise<void> {698  await chrome.storage.local.set({ [REVOCATIONS_KEY]: capRevocations(records) });699}700701/**702 * PB-26-110: bound the ledger by evicting from whichever issuer currently holds703 * the most records, oldest first.704 *705 * Evicting globally-oldest-first let one early flood consume the whole cap and706 * permanently starve every other issuer, including genuine revocations, because707 * declining to evict at all is not a bounded option. Largest-holder-first keeps708 * the bound while guaranteeing a flood can only ever displace its own records:709 * once an issuer holds more than anyone else, everything it adds costs it one of710 * its own oldest.711 *712 * ponytail: O(evictions x issuers) rescan of the per-issuer lists. Fine at a713 * 500-record cap; switch to a live-count map if the cap ever grows by orders of714 * magnitude.715 */716function capRevocations(records: DeviceRevocation[]): DeviceRevocation[] {717  if (records.length <= MAX_REVOCATIONS) return records;718  const byIssuer = new Map<string, DeviceRevocation[]>();719  for (const record of records) {720    const key = record.revokedByDeviceId ?? "";721    const list = byIssuer.get(key);722    if (list) list.push(record);723    else byIssuer.set(key, [record]);724  }725  const dropped = new Set<DeviceRevocation>();726  for (let total = records.length; total > MAX_REVOCATIONS; total -= 1) {727    let victim: DeviceRevocation[] | undefined;728    for (const list of byIssuer.values()) {729      const live = list.reduce((count, r) => (dropped.has(r) ? count : count + 1), 0);730      if (!victim || live > victim.reduce((c, r) => (dropped.has(r) ? c : c + 1), 0)) {731        victim = list;732      }733    }734    if (!victim) break;735    const oldest = victim.find((r) => !dropped.has(r));736    if (!oldest) break;737    dropped.add(oldest);738  }739  return records.filter((r) => !dropped.has(r));740}741742function isDeviceRevocation(x: unknown): x is DeviceRevocation {743  if (typeof x !== "object" || x === null) return false;744  const r = x as Record<string, unknown>;745  return (746    typeof r.deviceId === "string" &&747    !!r.deviceId &&748    typeof r.longTermPublicKeyHex === "string" &&749    typeof r.revokedAt === "number" &&750    typeof r.revokedByDeviceId === "string"751  );752}753754export async function clearPairedDevices(): Promise<void> {755  await enqueueDeviceMutation(async () => {756    await chrome.storage.local.set({757      [REGISTRY_KEY]: [],758      [REVOCATION_ISSUERS_KEY]: await retainRevocationIssuers(await listPairedDevicesRaw()),759    });760  });761}762763export async function markLastSyncedAt(deviceId: string, when: number): Promise<void> {764  await enqueueDeviceMutation(async () => {765  const devices = await listPairedDevicesRaw();766  const idx = devices.findIndex((d) => d.deviceId === deviceId);767  if (idx < 0) return;768  devices[idx] = { ...devices[idx], lastSyncedAt: when };769  await chrome.storage.local.set({ [REGISTRY_KEY]: devices });770  });771}772773export async function getLastSyncAt(): Promise<number | null> {774  try {775    const result = await chrome.storage.local.get(LAST_SYNC_AT_KEY);776    const value = (result as Record<string, unknown>)[LAST_SYNC_AT_KEY];777    if (typeof value === "number") return value;778    if (typeof value === "string" && value !== "") {779      const n = Number.parseInt(value, 10);780      return Number.isFinite(n) ? n : null;781    }782    return null;783  } catch {784    return null;785  }786}787788export async function setLastSyncAt(when: number): Promise<void> {789  await chrome.storage.local.set({ [LAST_SYNC_AT_KEY]: when });790}791792/**793 * The last sync ATTEMPT, not just the last success. A 3-second flash in the794 * popup is useless for debugging a real phone, so every terminating path795 * writes this and Settings reads it back after the fact — including across an796 * MV3 service-worker restart.797 */798export interface SyncResult {799  outcome: SyncOutcome;800  detail?: string;801  /** When the attempt finished, success or not. */802  at: number;803  entriesReceived: number;804  entriesSent: number;805}806807export async function getLastSyncResult(): Promise<SyncResult | null> {808  try {809    const result = await chrome.storage.local.get(LAST_SYNC_RESULT_KEY);810    const value = (result as Record<string, unknown>)[LAST_SYNC_RESULT_KEY];811    if (812      value &&813      typeof value === "object" &&814      typeof (value as Record<string, unknown>).outcome === "string" &&815      typeof (value as Record<string, unknown>).at === "number" &&816      typeof (value as Record<string, unknown>).entriesReceived === "number" &&817      typeof (value as Record<string, unknown>).entriesSent === "number"818    ) {819      return value as SyncResult;820    }821    return null;822  } catch {823    return null;824  }825}826827export async function setLastSyncResult(result: SyncResult): Promise<void> {828  await chrome.storage.local.set({ [LAST_SYNC_RESULT_KEY]: result });829}830831function isPairedDevice(x: unknown): x is PairedDevice {832  if (typeof x !== "object" || x === null) return false;833  const r = x as Record<string, unknown>;834  if (typeof r.deviceId !== "string" || !r.deviceId) return false;835  if (typeof r.pairedAt !== "number") return false;836  if (837    r.localAlias !== undefined &&838    (typeof r.localAlias !== "string" || !r.localAlias || r.localAlias.length > 64)839  ) {840    return false;841  }842  if (843    r.rendezvousSecretHex !== undefined &&844    (typeof r.rendezvousSecretHex !== "string" || !/^[0-9a-f]{64}$/.test(r.rendezvousSecretHex))845  ) {846    return false;847  }848  if (r.relayUrl !== undefined) {849    if (typeof r.relayUrl !== "string") return false;850    try {851      if (new URL(r.relayUrl).protocol !== "wss:") return false;852    } catch {853      return false;854    }855  }856  return true;857}