paired-devices.test.ts

32.3 KB · raw

1import { describe, expect, it, beforeEach, vi } from "vitest";2import type { PairedDevice } from "../shared/sync-types";3import {4  clearPairedDevices,5  listRevocationIssuerKeyMap,6  REVOCATION_ISSUERS_KEY,7  writePairedDevices,8  upsertPairedDevicesAndMergeRevocations,9  findPairedDeviceById,10  findPairedDeviceByPubkey,11  getLastSyncAt,12  listPairedDevices,13  markLastSyncedAt,14  isDeviceRevoked,15  listDeviceRevocations,16  mergeDeviceRevocations,17  repairPairedRevocationOverlaps,18  removePairedDeviceById,19  renamePairedDevice,20  revokeDeviceById,21  rotatePairedDeviceIdentity,22  setLastSyncAt,23  setRelayUrlForAllPairedDevices,24  TrustDataCorruptedError,25  upsertPairedDevice,26  upsertPairedDeviceAndClearRevocation,27  validatePairedDeviceIdentities,28} from "./paired-devices";2930function makeStorageStub() {31  const sync = new Map<string, unknown>();32  const local = new Map<string, unknown>();33  function area(store: Map<string, unknown>) {34    return {35      async get(key?: string | string[] | null) {36        if (key === null || key === undefined) {37          const all: Record<string, unknown> = {};38          for (const [k, v] of store) all[k] = v;39          return all;40        }41        const keys = Array.isArray(key) ? key : [key];42        const out: Record<string, unknown> = {};43        for (const k of keys) if (store.has(k)) out[k] = store.get(k);44        return out;45      },46      async set(values: Record<string, unknown>) {47        for (const [k, v] of Object.entries(values)) store.set(k, v);48      },49      async remove(key: string | string[]) {50        const keys = Array.isArray(key) ? key : [key];51        for (const k of keys) store.delete(k);52      },53    };54  }55  (globalThis as unknown as { chrome: unknown }).chrome = {56    storage: { sync: area(sync), local: area(local) },57  };58  return { sync, local };59}6061const SAMPLE: PairedDevice = {62  deviceId: "AAA-111",63  deviceName: "June's Pixel 9",64  deviceType: "android",65  longTermPublicKeyHex: "0".repeat(64),66  signingPublicKeyHex: "1".repeat(64),67  pairedAt: 1700000000000,68};6970describe("paired-devices registry", () => {71  beforeEach(() => makeStorageStub());7273  it.each(["remove", "revoke", "stale revoke", "merge", "repair", "replace"])("retains verification keys atomically on %s", async (path) => {74    const peer = { ...SAMPLE, trustSource: "direct" as const, longTermPublicKeyHex: "a".repeat(64) };75    await upsertPairedDevice(peer);76    const record = { deviceId: peer.deviceId, longTermPublicKeyHex: peer.longTermPublicKeyHex, revokedAt: peer.pairedAt + 1, revokedByDeviceId: "other" };77    if (path === "stale revoke" || path === "repair") await mergeDeviceRevocations([record]);78    const originalSet = chrome.storage.local.set;79    let captured = false;80    chrome.storage.local.set = async (values) => {81      const write = values as Record<string, unknown>;82      if (Array.isArray(write.peach_paired_devices_v3) && write.peach_paired_devices_v3.length === 0) {83        expect(write[REVOCATION_ISSUERS_KEY]).toEqual([{ deviceId: peer.deviceId, longTermPublicKeyHex: peer.longTermPublicKeyHex, signingPublicKeys: [peer.signingPublicKeyHex] }]);84        captured = true;85      }86      return originalSet(values);87    };88    if (path === "remove") await removePairedDeviceById(peer.deviceId);89    if (path === "revoke" || path === "stale revoke") await revokeDeviceById(peer.deviceId, "other");90    if (path === "merge") await upsertPairedDevicesAndMergeRevocations([], [record]);91    if (path === "repair") await repairPairedRevocationOverlaps();92    if (path === "replace") await writePairedDevices([]);93    expect(captured).toBe(true);94    expect(((await listRevocationIssuerKeyMap()).get(peer.deviceId) ?? [])).toEqual([peer.signingPublicKeyHex]);95    expect(await findPairedDeviceById(peer.deviceId)).toBeNull();96    await clearPairedDevices();97    expect(((await listRevocationIssuerKeyMap()).get(peer.deviceId) ?? [])).toEqual([peer.signingPublicKeyHex]);98  });99100  it("does not archive active rows on metadata writes or new rows removed by the same merge", async () => {101    const peer = { ...SAMPLE, trustSource: "direct" as const };102    await upsertPairedDevice(peer);103    await upsertPairedDevice({ ...peer, deviceName: "Updated" });104    expect((await chrome.storage.local.get(REVOCATION_ISSUERS_KEY))[REVOCATION_ISSUERS_KEY]).toEqual([]);105    const introduced = { ...peer, deviceId: "never-live", longTermPublicKeyHex: "c".repeat(64) };106    await upsertPairedDevicesAndMergeRevocations([introduced], [{ deviceId: introduced.deviceId, longTermPublicKeyHex: introduced.longTermPublicKeyHex, revokedAt: 1, revokedByDeviceId: "other" }]);107    expect(((await listRevocationIssuerKeyMap()).get(introduced.deviceId) ?? [])).toEqual([]);108    expect((await chrome.storage.local.get(REVOCATION_ISSUERS_KEY))[REVOCATION_ISSUERS_KEY]).toEqual([]);109  });110111  it("retains retired signing keys during generic replacement and direct re-pair", async () => {112    const peer = { ...SAMPLE, trustSource: "direct" as const };113    await upsertPairedDevice(peer);114    await writePairedDevices([{ ...peer, signingPublicKeyHex: "2".repeat(64) }]);115    expect(((await listRevocationIssuerKeyMap()).get(peer.deviceId) ?? [])).toEqual(expect.arrayContaining([peer.signingPublicKeyHex, "2".repeat(64)]));116    await upsertPairedDeviceAndClearRevocation({ ...peer, signingPublicKeyHex: "3".repeat(64) });117    expect(((await listRevocationIssuerKeyMap()).get(peer.deviceId) ?? [])).toEqual(expect.arrayContaining([peer.signingPublicKeyHex, "2".repeat(64), "3".repeat(64)]));118    await clearPairedDevices();119    expect(await listPairedDevices()).toEqual([]);120    expect(((await listRevocationIssuerKeyMap()).get(peer.deviceId) ?? [])).toEqual(expect.arrayContaining([peer.signingPublicKeyHex, "2".repeat(64), "3".repeat(64)]));121  });122123  it("archives only a retired signing key when the current binding remains live", async () => {124    const peer = { ...SAMPLE, trustSource: "direct" as const, signingKeyHistory: [{ version: 1, publicKeyHex: "2".repeat(64) }] };125    await upsertPairedDevice(peer);126    await writePairedDevices([{ ...peer, signingKeyHistory: [] }]);127    expect((await chrome.storage.local.get(REVOCATION_ISSUERS_KEY))[REVOCATION_ISSUERS_KEY]).toEqual([{ deviceId: peer.deviceId, longTermPublicKeyHex: peer.longTermPublicKeyHex, signingPublicKeys: ["2".repeat(64)] }]);128    expect(((await listRevocationIssuerKeyMap()).get(peer.deviceId) ?? [])).toEqual(expect.arrayContaining(["2".repeat(64), peer.signingPublicKeyHex]));129  });130131  it("reads live and archived issuer keys from one storage snapshot", async () => {132    const peer = { ...SAMPLE, trustSource: "direct" as const };133    await upsertPairedDevice(peer);134    await chrome.storage.local.set({ [REVOCATION_ISSUERS_KEY]: [{ deviceId: "old", longTermPublicKeyHex: "b".repeat(64), signingPublicKeys: ["c".repeat(64)] }] });135    const originalGet = chrome.storage.local.get;136    const reads: unknown[] = [];137    chrome.storage.local.get = (async (keys: string | string[]) => {138      reads.push(keys);139      return originalGet(keys);140    }) as unknown as typeof chrome.storage.local.get;141    const keys = await listRevocationIssuerKeyMap();142    expect(keys.get(peer.deviceId)).toEqual([peer.signingPublicKeyHex]);143    expect(keys.get("old")).toEqual(["c".repeat(64)]);144    expect(reads).toEqual([["peach_paired_devices_v3", REVOCATION_ISSUERS_KEY]]);145  });146147  it("seals only old-self unsigned records before queued identity rotation and resolves unpair inside the queue", async () => {148    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");149    const { pubkeyToHex } = await import("../shared/sync-identity");150    const { signDeviceRevocation, verifyDeviceRevocation } = await import("../shared/device-manifest");151    const signing = await deriveSyncSigningKeypair(new Uint8Array(32).fill(7), "old-self");152    const own = { deviceName: "Self", deviceType: "extension" as const, deviceId: "old-self", longTermPublicKeyHex: "a".repeat(64), signingPublicKeyHex: pubkeyToHex(signing.publicKeyRaw) };153    const unsigned = { deviceId: "victim", longTermPublicKeyHex: "b".repeat(64), revokedAt: 1, revokedByDeviceId: own.deviceId };154    const foreign = { ...unsigned, deviceId: "foreign", revokedByDeviceId: "other" };155    const signed = await signDeviceRevocation({ ...unsigned, deviceId: "already-signed" }, signing.privateKey);156    await mergeDeviceRevocations([unsigned, foreign, signed]);157    let currentId = own.deviceId;158    const privateKey = new Uint8Array(32).fill(1);159    const publicKey = new Uint8Array(32).fill(2);160    const rotation = rotatePairedDeviceIdentity(async () => ({ identity: own, privateKey, publicKey, signingPrivateKey: signing.privateKey }), async () => {161      const records = await chrome.storage.local.get("peach_device_revocations_v1");162      expect((records.peach_device_revocations_v1 as { signatureHex?: string }[])[0].signatureHex).toBeDefined();163      currentId = "new-self";164      return currentId;165    });166    const removal = revokeDeviceById("after-rotation", async () => currentId);167    await rotation;168    await removal;169    const records = await listDeviceRevocations();170    expect(await verifyDeviceRevocation(records[0], signing.publicKeyRaw)).toBe(true);171    expect(records[1]).toEqual(foreign);172    expect(records[2]).toEqual(signed);173    expect(records[3].revokedByDeviceId).toBe("new-self");174    expect(((await listRevocationIssuerKeyMap()).get(own.deviceId) ?? [])).toEqual([own.signingPublicKeyHex]);175    expect(await findPairedDeviceById(own.deviceId)).toBeNull();176    expect(privateKey.every((value) => value === 0)).toBe(true);177    expect(publicKey.every((value) => value === 0)).toBe(true);178  });179180  it.each(["archive", "write", "rotate"])("preserves trust and zeroes rotation buffers when %s fails", async (failure) => {181    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");182    const { pubkeyToHex } = await import("../shared/sync-identity");183    const signing = await deriveSyncSigningKeypair(new Uint8Array(32).fill(7), "old-self");184    const own = { deviceName: "Self", deviceType: "extension" as const, deviceId: "old-self", longTermPublicKeyHex: "a".repeat(64), signingPublicKeyHex: pubkeyToHex(signing.publicKeyRaw) };185    const record = { deviceId: "victim", longTermPublicKeyHex: "b".repeat(64), revokedAt: 1, revokedByDeviceId: own.deviceId };186    await mergeDeviceRevocations([record]);187    if (failure === "archive") await chrome.storage.local.set({ [REVOCATION_ISSUERS_KEY]: "corrupt" });188    if (failure === "write") chrome.storage.local.set = async () => { throw new Error("write failed"); };189    const rotate = vi.fn(async () => { throw new Error("rotate failed"); });190    const privateKey = new Uint8Array(32).fill(1);191    const publicKey = new Uint8Array(32).fill(2);192    await expect(rotatePairedDeviceIdentity(async () => ({ identity: own, privateKey, publicKey, signingPrivateKey: signing.privateKey }), rotate)).rejects.toThrow();193    expect(rotate).toHaveBeenCalledTimes(failure === "rotate" ? 1 : 0);194    const records = await listDeviceRevocations();195    if (failure === "rotate") expect(records[0]).toMatchObject({ ...record, signatureHex: expect.any(String) });196    else expect(records).toEqual([record]);197    expect(privateKey.every((value) => value === 0)).toBe(true);198    expect(publicKey.every((value) => value === 0)).toBe(true);199  });200201  it("archives all long-term-key overlap victims without merging identity bindings or losing equal-version keys", async () => {202    const key = "a".repeat(64);203    await upsertPairedDevice({ ...SAMPLE, longTermPublicKeyHex: key, trustSource: "direct", signingKeyHistory: [{ version: 1, publicKeyHex: "2".repeat(64) }, { version: 1, publicKeyHex: "3".repeat(64) }] });204    await upsertPairedDevice({ ...SAMPLE, deviceId: "alias", longTermPublicKeyHex: key, trustSource: "vouched" });205    await upsertPairedDevicesAndMergeRevocations([], [{ deviceId: "elsewhere", longTermPublicKeyHex: key, revokedAt: 1, revokedByDeviceId: "other" }]);206    expect(await listPairedDevices()).toEqual([]);207    expect(((await listRevocationIssuerKeyMap()).get(SAMPLE.deviceId) ?? [])).toEqual(expect.arrayContaining(["1".repeat(64), "2".repeat(64), "3".repeat(64)]));208    expect(((await listRevocationIssuerKeyMap()).get("alias") ?? [])).toEqual([SAMPLE.signingPublicKeyHex]);209    await upsertPairedDevice({ ...SAMPLE, longTermPublicKeyHex: "b".repeat(64), signingPublicKeyHex: "4".repeat(64), trustSource: "direct" });210    await removePairedDeviceById(SAMPLE.deviceId);211    const archive = (await chrome.storage.local.get(REVOCATION_ISSUERS_KEY))[REVOCATION_ISSUERS_KEY];212    if (!Array.isArray(archive)) throw new Error("missing issuer archive");213    expect(archive.filter((entry: { deviceId: string }) => entry.deviceId === SAMPLE.deviceId)).toHaveLength(2);214    expect(((await listRevocationIssuerKeyMap()).get(SAMPLE.deviceId) ?? [])).toEqual(expect.arrayContaining(["1".repeat(64), "2".repeat(64), "3".repeat(64), "4".repeat(64)]));215  });216217  it("retains only authenticated public verification material", async () => {218    await upsertPairedDevice({ ...SAMPLE, trustSource: "direct", rendezvousSecretHex: "f".repeat(64), relayUrl: "wss://private.example", signingKeyHistory: [{ version: 0, publicKeyHex: "e".repeat(64) }, { version: 1, publicKeyHex: "d".repeat(64) }] });219    await removePairedDeviceById(SAMPLE.deviceId);220    const archive = (await chrome.storage.local.get(REVOCATION_ISSUERS_KEY))[REVOCATION_ISSUERS_KEY];221    expect(archive).toEqual([{ deviceId: SAMPLE.deviceId, longTermPublicKeyHex: SAMPLE.longTermPublicKeyHex, signingPublicKeys: ["d".repeat(64), SAMPLE.signingPublicKeyHex] }]);222    await upsertPairedDevice({ ...SAMPLE, deviceId: "legacy-unattributed" });223    await removePairedDeviceById("legacy-unattributed");224    expect(((await listRevocationIssuerKeyMap()).get("legacy-unattributed") ?? [])).toEqual([]);225  });226227  it("refuses removal over a corrupt issuer archive without losing the live peer", async () => {228    await upsertPairedDevice({ ...SAMPLE, trustSource: "direct" });229    await chrome.storage.local.set({ [REVOCATION_ISSUERS_KEY]: "damaged" });230    await expect(removePairedDeviceById(SAMPLE.deviceId)).rejects.toBeInstanceOf(TrustDataCorruptedError);231    expect(await findPairedDeviceById(SAMPLE.deviceId)).toMatchObject(SAMPLE);232  });233234  it("upsert + list", async () => {235    await upsertPairedDevice(SAMPLE);236    expect(await listPairedDevices()).toEqual([SAMPLE]);237  });238239  it("upsert is idempotent on the same deviceId — updates metadata in place, no duplicate", async () => {240    await upsertPairedDevice(SAMPLE);241    await upsertPairedDevice({ ...SAMPLE, deviceName: "Renamed Pixel", pairedAt: 1700000001000 });242    const all = await listPairedDevices();243    expect(all).toHaveLength(1);244    expect(all[0]).toMatchObject({245      deviceName: "Renamed Pixel",246      pairedAt: 1700000001000,247      longTermPublicKeyHex: SAMPLE.longTermPublicKeyHex,248      signingPublicKeyHex: SAMPLE.signingPublicKeyHex,249    });250  });251252  it("stores a local alias without changing the peer-reported name or identity", async () => {253    await upsertPairedDevice(SAMPLE);254    await renamePairedDevice(SAMPLE.deviceId, "  Travel phone  ");255    const renamed = await findPairedDeviceById(SAMPLE.deviceId);256    expect(renamed).toMatchObject({257      deviceName: SAMPLE.deviceName,258      localAlias: "Travel phone",259      longTermPublicKeyHex: SAMPLE.longTermPublicKeyHex,260    });261  });262263  it("rejects blank, oversized, and unknown-device aliases", async () => {264    await upsertPairedDevice(SAMPLE);265    await expect(renamePairedDevice(SAMPLE.deviceId, " ")).rejects.toThrow(/empty/);266    await expect(renamePairedDevice(SAMPLE.deviceId, "x".repeat(65))).rejects.toThrow(/64/);267    await expect(renamePairedDevice("missing", "Phone")).rejects.toThrow(/not_found/);268  });269270  it("rejects a same-deviceId long-term key replacement and leaves the stored row unchanged", async () => {271    await upsertPairedDevice(SAMPLE);272    const before = await findPairedDeviceById(SAMPLE.deviceId);273    await expect(274      upsertPairedDevice({ ...SAMPLE, longTermPublicKeyHex: "f".repeat(64) }),275    ).rejects.toThrow("device_identity_immutable");276    expect(await findPairedDeviceById(SAMPLE.deviceId)).toEqual(before);277  });278279  it("rejects a same-deviceId signing key replacement and leaves the stored row unchanged", async () => {280    await upsertPairedDevice(SAMPLE);281    const before = await findPairedDeviceById(SAMPLE.deviceId);282    await expect(283      upsertPairedDevice({ ...SAMPLE, signingPublicKeyHex: "2".repeat(64) }),284    ).rejects.toThrow("device_identity_immutable");285    expect(await findPairedDeviceById(SAMPLE.deviceId)).toEqual(before);286  });287  it("preserves an existing signing key when an incoming row omits or nulls it", async () => {288    await upsertPairedDevice(SAMPLE);289    await upsertPairedDevice({ ...SAMPLE, deviceName: "Updated Pixel", signingPublicKeyHex: undefined });290    await upsertPairedDevice({291      ...SAMPLE,292      deviceName: "Updated Again",293      signingPublicKeyHex: null as unknown as string,294    });295    expect((await findPairedDeviceById(SAMPLE.deviceId))?.signingPublicKeyHex).toBe(296      SAMPLE.signingPublicKeyHex,297    );298  });299300  it("rejects duplicate manifest identities before any registry mutation", async () => {301    await expect(302      validatePairedDeviceIdentities([303        { ...SAMPLE, deviceName: "First" },304        { ...SAMPLE, deviceName: "Second", longTermPublicKeyHex: "f".repeat(64) },305      ]),306    ).rejects.toThrow("device_identity_immutable");307    expect(await listPairedDevices()).toEqual([]);308  });309  it("rejects upsert with missing fields", async () => {310    await expect(upsertPairedDevice({ ...SAMPLE, deviceId: "" })).rejects.toThrow(/deviceId/);311    await expect(upsertPairedDevice({ ...SAMPLE, longTermPublicKeyHex: undefined })).rejects.toThrow(/longTermPublicKeyHex/);312    await expect(upsertPairedDevice({ ...SAMPLE, deviceName: undefined })).rejects.toThrow(/deviceName/);313    await expect(upsertPairedDevice({ ...SAMPLE, deviceType: undefined })).rejects.toThrow(/deviceType/);314  });315316  it("caps oversized peer device names at the registry seam", async () => {317    await upsertPairedDevice({ ...SAMPLE, deviceId: "LONG-1", deviceName: "N".repeat(100) });318    const found = await findPairedDeviceById("LONG-1");319    expect(found?.deviceName).toBe("N".repeat(64));320  });321322  it("findPairedDeviceByPubkey returns the correct device", async () => {323    const other: PairedDevice = { ...SAMPLE, deviceId: "BBB-222", longTermPublicKeyHex: "1".repeat(64) };324    await upsertPairedDevice(SAMPLE);325    await upsertPairedDevice(other);326    expect(await findPairedDeviceByPubkey("1".repeat(64))).toEqual(other);327    expect(await findPairedDeviceByPubkey("9".repeat(64))).toBeNull();328  });329330  it("removePairedDeviceById drops the device", async () => {331    await upsertPairedDevice(SAMPLE);332    await removePairedDeviceById(SAMPLE.deviceId);333    expect(await listPairedDevices()).toEqual([]);334  });335336  it("clearPairedDevices wipes the whole registry", async () => {337    await upsertPairedDevice(SAMPLE);338    await clearPairedDevices();339    expect(await listPairedDevices()).toEqual([]);340  });341342  it("markLastSyncedAt mutates only the target device", async () => {343    const other: PairedDevice = { ...SAMPLE, deviceId: "BBB-222", longTermPublicKeyHex: "1".repeat(64) };344    await upsertPairedDevice(SAMPLE);345    await upsertPairedDevice(other);346    await markLastSyncedAt(SAMPLE.deviceId, 1700001000000);347    const found = await findPairedDeviceById(SAMPLE.deviceId);348    expect(found?.lastSyncedAt).toBe(1700001000000);349    const untouched = await findPairedDeviceById(other.deviceId);350    expect(untouched?.lastSyncedAt).toBeUndefined();351  });352353  it("serializes a concurrent pairing upsert with a sync timestamp update", async () => {354    const other: PairedDevice = {355      ...SAMPLE,356      deviceId: "BBB-222",357      longTermPublicKeyHex: "1".repeat(64),358    };359    await upsertPairedDevice(SAMPLE);360361    await Promise.all([362      upsertPairedDevice(other),363      markLastSyncedAt(SAMPLE.deviceId, 1700001000000),364    ]);365366    expect(await listPairedDevices()).toEqual([367      { ...SAMPLE, lastSyncedAt: 1700001000000 },368      other,369    ]);370  });371372  it("moves every existing pair to a new mesh relay", async () => {373    const other: PairedDevice = {374      ...SAMPLE,375      deviceId: "BBB-222",376      longTermPublicKeyHex: "1".repeat(64),377      relayUrl: "wss://old-relay.example",378    };379    await upsertPairedDevice(SAMPLE);380    await upsertPairedDevice(other);381382    await setRelayUrlForAllPairedDevices("wss://new-relay.example/base");383384    expect((await listPairedDevices()).map((device) => device.relayUrl)).toEqual([385      "wss://new-relay.example/base",386      "wss://new-relay.example/base",387    ]);388  });389390  it("last sync timestamp accepts a legacy string value", async () => {391    (globalThis as unknown as { chrome: { storage: { local: { set: (v: Record<string, unknown>) => Promise<void> } } } }).chrome.storage.local.set({392      peach_last_sync_at: "1700002000000",393    });394    expect(await getLastSyncAt()).toBe(1700002000000);395  });396397  it("setLastSyncAt persists a numeric value", async () => {398    await setLastSyncAt(1700003000000);399    expect(await getLastSyncAt()).toBe(1700003000000);400  });401402  it("listPairedDevices filters invalid entries from an otherwise valid array", async () => {403    (globalThis as unknown as { chrome: { storage: { local: { set: (v: Record<string, unknown>) => Promise<void> } } } }).chrome.storage.local.set({404      peach_paired_devices_v3: [405        { deviceId: "real", pairedAt: 1, deviceName: "x", deviceType: "android", longTermPublicKeyHex: "0".repeat(64) },406        { not: "a device" },407        null,408        42,409      ],410    });411    const devices = await listPairedDevices();412    expect(devices).toHaveLength(1);413    expect(devices[0].deviceId).toBe("real");414  });415416  // §18.4: a corrupt persisted ledger must not be read as empty — that would417  // silently un-revoke every device. A non-array value is integrity damage.418  it("listPairedDevices throws TrustDataCorruptedError on a non-array registry", async () => {419    (globalThis as unknown as { chrome: { storage: { local: { set: (v: Record<string, unknown>) => Promise<void> } } } }).chrome.storage.local.set({420      peach_paired_devices_v3: { corrupted: true },421    });422    await expect(listPairedDevices()).rejects.toThrow(TrustDataCorruptedError);423  });424425  it("listDeviceRevocations throws TrustDataCorruptedError on a non-array ledger", async () => {426    (globalThis as unknown as { chrome: { storage: { local: { set: (v: Record<string, unknown>) => Promise<void> } } } }).chrome.storage.local.set({427      peach_device_revocations_v1: "not-an-array",428    });429    await expect(listDeviceRevocations()).rejects.toThrow(TrustDataCorruptedError);430  });431432  it("a corrupt registry is not overwritten by a mutation attempt", async () => {433    const corrupt = { corrupted: true };434    (globalThis as unknown as { chrome: { storage: { local: { set: (v: Record<string, unknown>) => Promise<void> } } } }).chrome.storage.local.set({435      peach_paired_devices_v3: corrupt,436    });437    await expect(upsertPairedDevice(SAMPLE)).rejects.toThrow(TrustDataCorruptedError);438    // The corrupt payload is preserved — the mutation never wrote.439    const result = await chrome.storage.local.get("peach_paired_devices_v3");440    expect(result["peach_paired_devices_v3"]).toBe(corrupt);441  });442443  describe("device revocation", () => {444    it("revokeDeviceById records the device's key and drops it from the registry", async () => {445      await upsertPairedDevice(SAMPLE);446      const record = await revokeDeviceById(SAMPLE.deviceId, "this-device", {447        now: 1_700_000_000_000,448      });449450      expect(record).toMatchObject({451        deviceId: SAMPLE.deviceId,452        longTermPublicKeyHex: SAMPLE.longTermPublicKeyHex,453        revokedAt: 1_700_000_000_000,454        revokedByDeviceId: "this-device",455      });456      expect(await findPairedDeviceById(SAMPLE.deviceId)).toBeNull();457      expect(await isDeviceRevoked(SAMPLE.deviceId)).toBe(true);458    });459460    it("revoking twice is a no-op rather than a duplicate record", async () => {461      await upsertPairedDevice(SAMPLE);462      await revokeDeviceById(SAMPLE.deviceId, "this-device");463      expect(await revokeDeviceById(SAMPLE.deviceId, "this-device")).toBeNull();464      expect(await listDeviceRevocations()).toHaveLength(1);465    });466467    it("an existing revocation still removes a stale re-paired row", async () => {468      await upsertPairedDevice(SAMPLE);469      await revokeDeviceById(SAMPLE.deviceId, "this-device");470      // Reproduce the real corrupt overlap created by older direct-pair471      // handlers: the row returned but its terminal revocation remained.472      await upsertPairedDevice(SAMPLE);473474      expect(await revokeDeviceById(SAMPLE.deviceId, "this-device")).toBeNull();475      expect(await findPairedDeviceById(SAMPLE.deviceId)).toBeNull();476      expect(await listDeviceRevocations()).toHaveLength(1);477    });478479    it("mergeDeviceRevocations reports only the ids it had not already seen", async () => {480      const first = await mergeDeviceRevocations([481        { deviceId: "a", longTermPublicKeyHex: "a".repeat(64), revokedAt: 1, revokedByDeviceId: "x" },482      ]);483      expect(first).toEqual(["a"]);484485      const second = await mergeDeviceRevocations([486        { deviceId: "a", longTermPublicKeyHex: "a".repeat(64), revokedAt: 2, revokedByDeviceId: "y" },487        { deviceId: "b", longTermPublicKeyHex: "b".repeat(64), revokedAt: 3, revokedByDeviceId: "y" },488      ]);489      expect(second).toEqual(["b"]);490      expect(await listDeviceRevocations()).toHaveLength(2);491    });492493    // PB-26-110: the ledger must stay bounded without letting an early flood494    // consume it permanently. A later revocation from a DIFFERENT issuer is495    // the record that matters — it has to be admitted even when the ledger is496    // already full of another issuer's junk.497    it("a later revocation from a different issuer is still admitted on a full ledger", async () => {498      await mergeDeviceRevocations(Array.from({ length: 500 }, (_, index) => ({499        deviceId: `terminal-${index}`,500        longTermPublicKeyHex: index.toString(16).padStart(64, "0"),501        revokedAt: index + 1,502        revokedByDeviceId: "issuer-a",503      })));504505      expect(await mergeDeviceRevocations([{506        deviceId: "peer-extra",507        longTermPublicKeyHex: "f".repeat(64),508        revokedAt: 999,509        revokedByDeviceId: "issuer-b",510      }])).toEqual(["peer-extra"]);511512      const records = await listDeviceRevocations();513      expect(records).toHaveLength(500);514      // The genuine record is admitted and still blocks re-vouching.515      expect(await isDeviceRevoked("peer-extra")).toBe(true);516      // Room was made by evicting the over-represented issuer's own record,517      // not another issuer's.518      expect(records.filter((r) => r.revokedByDeviceId === "issuer-b")).toHaveLength(1);519      expect(await isDeviceRevoked("terminal-0")).toBe(false);520    });521522    it("a same-issuer local flood retains the bounded ledger", async () => {523      for (let index = 0; index < 501; index += 1) {524        await upsertPairedDevice({525          ...SAMPLE,526          deviceId: `local-${index}`,527          longTermPublicKeyHex: index.toString(16).padStart(64, "0"),528        });529        await revokeDeviceById(`local-${index}`, "issuer-a", { now: index + 1 });530      }531      const records = await listDeviceRevocations();532      expect(records).toHaveLength(500);533      expect(records.some((record) => record.deviceId === "local-0")).toBe(false);534      expect(records.at(-1)?.deviceId).toBe("local-500");535    });536537    it("a different issuer local revoke preserves one of its genuine records", async () => {538      await mergeDeviceRevocations(Array.from({ length: 500 }, (_, index) => ({539        deviceId: `terminal-${index}`,540        longTermPublicKeyHex: index.toString(16).padStart(64, "0"),541        revokedAt: index + 1,542        revokedByDeviceId: index === 0 ? "issuer-a" : "issuer-b",543      })));544      await upsertPairedDevice({ ...SAMPLE, deviceId: "local-new", longTermPublicKeyHex: "f".repeat(64) });545      await revokeDeviceById("local-new", "issuer-a", { now: 501 });546      const records = await listDeviceRevocations();547      expect(records).toHaveLength(500);548      expect(records.some((record) => record.deviceId === "terminal-0")).toBe(true);549      expect(records.some((record) => record.deviceId === "local-new")).toBe(true);550    });551552    it("a peer flood cannot evict an older revocation from another issuer", async () => {553      await mergeDeviceRevocations([{554        deviceId: "genuine",555        longTermPublicKeyHex: "a".repeat(64),556        revokedAt: 1,557        revokedByDeviceId: "honest-issuer",558      }]);559      const flood = Array.from({ length: 600 }, (_, index) => ({560        deviceId: `junk-${index}`,561        longTermPublicKeyHex: index.toString(16).padStart(64, "0"),562        revokedAt: index + 2,563        revokedByDeviceId: "flooding-issuer",564      }));565      const admitted = await mergeDeviceRevocations(flood);566      expect(admitted).toHaveLength(600);567      const records = await listDeviceRevocations();568      expect(records).toHaveLength(500);569      expect(await isDeviceRevoked("genuine")).toBe(true);570      // The flooder is the over-represented issuer, so its own oldest records571      // are what get dropped — the newest junk survives, the oldest does not.572      expect(await isDeviceRevoked("junk-599")).toBe(true);573      expect(await isDeviceRevoked("junk-0")).toBe(false);574    });575576    it("a later revokedAt cannot displace an existing record — revocation is terminal", async () => {577      await mergeDeviceRevocations([578        { deviceId: "a", longTermPublicKeyHex: "a".repeat(64), revokedAt: 1, revokedByDeviceId: "x" },579      ]);580      await mergeDeviceRevocations([581        { deviceId: "a", longTermPublicKeyHex: "c".repeat(64), revokedAt: 9_999, revokedByDeviceId: "attacker" },582      ]);583      const records = await listDeviceRevocations();584      expect(records).toHaveLength(1);585      expect(records[0]).toMatchObject({ revokedAt: 1, revokedByDeviceId: "x" });586    });587588    it("HOLE 2: a far-future revokedAt is clamped rather than stored verbatim", async () => {589      const farFuture = Date.now() + 10 * 365 * 24 * 60 * 60 * 1000;590      await mergeDeviceRevocations([591        { deviceId: "a", longTermPublicKeyHex: "a".repeat(64), revokedAt: farFuture, revokedByDeviceId: "peer" },592      ]);593      const [record] = await listDeviceRevocations();594      expect(record.revokedAt).toBeLessThanOrEqual(Date.now() + 5 * 60 * 1000);595    });596597    it("startup repair keeps a newer direct pair and clears its older revocation", async () => {598      const now = Date.now();599      await mergeDeviceRevocations([{600        deviceId: SAMPLE.deviceId,601        longTermPublicKeyHex: SAMPLE.longTermPublicKeyHex!,602        revokedAt: now - 1_000,603        revokedByDeviceId: "this-device",604      }]);605      await upsertPairedDevice({606        ...SAMPLE,607        pairedAt: now,608        trustSource: "direct",609      });610611      expect(await repairPairedRevocationOverlaps()).toEqual({612        revocationsCleared: 1,613        pairedRowsRemoved: 0,614      });615      expect(await findPairedDeviceById(SAMPLE.deviceId)).not.toBeNull();616      expect(await isDeviceRevoked(SAMPLE.deviceId)).toBe(false);617    });618619    it("startup repair removes a direct pair older than its revocation", async () => {620      const now = Date.now();621      await upsertPairedDevice({622        ...SAMPLE,623        pairedAt: now - 2_000,624        trustSource: "direct",625      });626      await mergeDeviceRevocations([{627        deviceId: SAMPLE.deviceId,628        longTermPublicKeyHex: SAMPLE.longTermPublicKeyHex!,629        revokedAt: now - 1_000,630        revokedByDeviceId: "this-device",631      }]);632633      expect(await repairPairedRevocationOverlaps()).toEqual({634        revocationsCleared: 0,635        pairedRowsRemoved: 1,636      });637      expect(await findPairedDeviceById(SAMPLE.deviceId)).toBeNull();638      expect(await isDeviceRevoked(SAMPLE.deviceId)).toBe(true);639    });640641    it("startup repair never lets a newer vouched pair lift a revocation", async () => {642      const now = Date.now();643      await mergeDeviceRevocations([{644        deviceId: SAMPLE.deviceId,645        longTermPublicKeyHex: SAMPLE.longTermPublicKeyHex!,646        revokedAt: now - 1_000,647        revokedByDeviceId: "this-device",648      }]);649      await upsertPairedDevice({650        ...SAMPLE,651        pairedAt: now,652        trustSource: "vouched",653      });654655      expect(await repairPairedRevocationOverlaps()).toEqual({656        revocationsCleared: 0,657        pairedRowsRemoved: 1,658      });659      expect(await findPairedDeviceById(SAMPLE.deviceId)).toBeNull();660      expect(await isDeviceRevoked(SAMPLE.deviceId)).toBe(true);661    });662  });663});