import { describe, expect, it, beforeEach, vi } from "vitest"; import type { PairedDevice } from "../shared/sync-types"; import { clearPairedDevices, listRevocationIssuerKeyMap, REVOCATION_ISSUERS_KEY, writePairedDevices, upsertPairedDevicesAndMergeRevocations, findPairedDeviceById, findPairedDeviceByPubkey, getLastSyncAt, listPairedDevices, markLastSyncedAt, isDeviceRevoked, listDeviceRevocations, mergeDeviceRevocations, repairPairedRevocationOverlaps, removePairedDeviceById, renamePairedDevice, revokeDeviceById, rotatePairedDeviceIdentity, setLastSyncAt, setRelayUrlForAllPairedDevices, TrustDataCorruptedError, upsertPairedDevice, upsertPairedDeviceAndClearRevocation, validatePairedDeviceIdentities, } from "./paired-devices"; function makeStorageStub() { const sync = new Map(); const local = new Map(); function area(store: Map) { return { async get(key?: string | string[] | null) { if (key === null || key === undefined) { const all: Record = {}; for (const [k, v] of store) all[k] = v; return all; } const keys = Array.isArray(key) ? key : [key]; const out: Record = {}; for (const k of keys) if (store.has(k)) out[k] = store.get(k); return out; }, async set(values: Record) { for (const [k, v] of Object.entries(values)) store.set(k, v); }, async remove(key: string | string[]) { const keys = Array.isArray(key) ? key : [key]; for (const k of keys) store.delete(k); }, }; } (globalThis as unknown as { chrome: unknown }).chrome = { storage: { sync: area(sync), local: area(local) }, }; return { sync, local }; } const SAMPLE: PairedDevice = { deviceId: "AAA-111", deviceName: "June's Pixel 9", deviceType: "android", longTermPublicKeyHex: "0".repeat(64), signingPublicKeyHex: "1".repeat(64), pairedAt: 1700000000000, }; describe("paired-devices registry", () => { beforeEach(() => makeStorageStub()); it.each(["remove", "revoke", "stale revoke", "merge", "repair", "replace"])("retains verification keys atomically on %s", async (path) => { const peer = { ...SAMPLE, trustSource: "direct" as const, longTermPublicKeyHex: "a".repeat(64) }; await upsertPairedDevice(peer); const record = { deviceId: peer.deviceId, longTermPublicKeyHex: peer.longTermPublicKeyHex, revokedAt: peer.pairedAt + 1, revokedByDeviceId: "other" }; if (path === "stale revoke" || path === "repair") await mergeDeviceRevocations([record]); const originalSet = chrome.storage.local.set; let captured = false; chrome.storage.local.set = async (values) => { const write = values as Record; if (Array.isArray(write.peach_paired_devices_v3) && write.peach_paired_devices_v3.length === 0) { expect(write[REVOCATION_ISSUERS_KEY]).toEqual([{ deviceId: peer.deviceId, longTermPublicKeyHex: peer.longTermPublicKeyHex, signingPublicKeys: [peer.signingPublicKeyHex] }]); captured = true; } return originalSet(values); }; if (path === "remove") await removePairedDeviceById(peer.deviceId); if (path === "revoke" || path === "stale revoke") await revokeDeviceById(peer.deviceId, "other"); if (path === "merge") await upsertPairedDevicesAndMergeRevocations([], [record]); if (path === "repair") await repairPairedRevocationOverlaps(); if (path === "replace") await writePairedDevices([]); expect(captured).toBe(true); expect(((await listRevocationIssuerKeyMap()).get(peer.deviceId) ?? [])).toEqual([peer.signingPublicKeyHex]); expect(await findPairedDeviceById(peer.deviceId)).toBeNull(); await clearPairedDevices(); expect(((await listRevocationIssuerKeyMap()).get(peer.deviceId) ?? [])).toEqual([peer.signingPublicKeyHex]); }); it("does not archive active rows on metadata writes or new rows removed by the same merge", async () => { const peer = { ...SAMPLE, trustSource: "direct" as const }; await upsertPairedDevice(peer); await upsertPairedDevice({ ...peer, deviceName: "Updated" }); expect((await chrome.storage.local.get(REVOCATION_ISSUERS_KEY))[REVOCATION_ISSUERS_KEY]).toEqual([]); const introduced = { ...peer, deviceId: "never-live", longTermPublicKeyHex: "c".repeat(64) }; await upsertPairedDevicesAndMergeRevocations([introduced], [{ deviceId: introduced.deviceId, longTermPublicKeyHex: introduced.longTermPublicKeyHex, revokedAt: 1, revokedByDeviceId: "other" }]); expect(((await listRevocationIssuerKeyMap()).get(introduced.deviceId) ?? [])).toEqual([]); expect((await chrome.storage.local.get(REVOCATION_ISSUERS_KEY))[REVOCATION_ISSUERS_KEY]).toEqual([]); }); it("retains retired signing keys during generic replacement and direct re-pair", async () => { const peer = { ...SAMPLE, trustSource: "direct" as const }; await upsertPairedDevice(peer); await writePairedDevices([{ ...peer, signingPublicKeyHex: "2".repeat(64) }]); expect(((await listRevocationIssuerKeyMap()).get(peer.deviceId) ?? [])).toEqual(expect.arrayContaining([peer.signingPublicKeyHex, "2".repeat(64)])); await upsertPairedDeviceAndClearRevocation({ ...peer, signingPublicKeyHex: "3".repeat(64) }); expect(((await listRevocationIssuerKeyMap()).get(peer.deviceId) ?? [])).toEqual(expect.arrayContaining([peer.signingPublicKeyHex, "2".repeat(64), "3".repeat(64)])); await clearPairedDevices(); expect(await listPairedDevices()).toEqual([]); expect(((await listRevocationIssuerKeyMap()).get(peer.deviceId) ?? [])).toEqual(expect.arrayContaining([peer.signingPublicKeyHex, "2".repeat(64), "3".repeat(64)])); }); it("archives only a retired signing key when the current binding remains live", async () => { const peer = { ...SAMPLE, trustSource: "direct" as const, signingKeyHistory: [{ version: 1, publicKeyHex: "2".repeat(64) }] }; await upsertPairedDevice(peer); await writePairedDevices([{ ...peer, signingKeyHistory: [] }]); expect((await chrome.storage.local.get(REVOCATION_ISSUERS_KEY))[REVOCATION_ISSUERS_KEY]).toEqual([{ deviceId: peer.deviceId, longTermPublicKeyHex: peer.longTermPublicKeyHex, signingPublicKeys: ["2".repeat(64)] }]); expect(((await listRevocationIssuerKeyMap()).get(peer.deviceId) ?? [])).toEqual(expect.arrayContaining(["2".repeat(64), peer.signingPublicKeyHex])); }); it("reads live and archived issuer keys from one storage snapshot", async () => { const peer = { ...SAMPLE, trustSource: "direct" as const }; await upsertPairedDevice(peer); await chrome.storage.local.set({ [REVOCATION_ISSUERS_KEY]: [{ deviceId: "old", longTermPublicKeyHex: "b".repeat(64), signingPublicKeys: ["c".repeat(64)] }] }); const originalGet = chrome.storage.local.get; const reads: unknown[] = []; chrome.storage.local.get = (async (keys: string | string[]) => { reads.push(keys); return originalGet(keys); }) as unknown as typeof chrome.storage.local.get; const keys = await listRevocationIssuerKeyMap(); expect(keys.get(peer.deviceId)).toEqual([peer.signingPublicKeyHex]); expect(keys.get("old")).toEqual(["c".repeat(64)]); expect(reads).toEqual([["peach_paired_devices_v3", REVOCATION_ISSUERS_KEY]]); }); it("seals only old-self unsigned records before queued identity rotation and resolves unpair inside the queue", async () => { const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support"); const { pubkeyToHex } = await import("../shared/sync-identity"); const { signDeviceRevocation, verifyDeviceRevocation } = await import("../shared/device-manifest"); const signing = await deriveSyncSigningKeypair(new Uint8Array(32).fill(7), "old-self"); const own = { deviceName: "Self", deviceType: "extension" as const, deviceId: "old-self", longTermPublicKeyHex: "a".repeat(64), signingPublicKeyHex: pubkeyToHex(signing.publicKeyRaw) }; const unsigned = { deviceId: "victim", longTermPublicKeyHex: "b".repeat(64), revokedAt: 1, revokedByDeviceId: own.deviceId }; const foreign = { ...unsigned, deviceId: "foreign", revokedByDeviceId: "other" }; const signed = await signDeviceRevocation({ ...unsigned, deviceId: "already-signed" }, signing.privateKey); await mergeDeviceRevocations([unsigned, foreign, signed]); let currentId = own.deviceId; const privateKey = new Uint8Array(32).fill(1); const publicKey = new Uint8Array(32).fill(2); const rotation = rotatePairedDeviceIdentity(async () => ({ identity: own, privateKey, publicKey, signingPrivateKey: signing.privateKey }), async () => { const records = await chrome.storage.local.get("peach_device_revocations_v1"); expect((records.peach_device_revocations_v1 as { signatureHex?: string }[])[0].signatureHex).toBeDefined(); currentId = "new-self"; return currentId; }); const removal = revokeDeviceById("after-rotation", async () => currentId); await rotation; await removal; const records = await listDeviceRevocations(); expect(await verifyDeviceRevocation(records[0], signing.publicKeyRaw)).toBe(true); expect(records[1]).toEqual(foreign); expect(records[2]).toEqual(signed); expect(records[3].revokedByDeviceId).toBe("new-self"); expect(((await listRevocationIssuerKeyMap()).get(own.deviceId) ?? [])).toEqual([own.signingPublicKeyHex]); expect(await findPairedDeviceById(own.deviceId)).toBeNull(); expect(privateKey.every((value) => value === 0)).toBe(true); expect(publicKey.every((value) => value === 0)).toBe(true); }); it.each(["archive", "write", "rotate"])("preserves trust and zeroes rotation buffers when %s fails", async (failure) => { const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support"); const { pubkeyToHex } = await import("../shared/sync-identity"); const signing = await deriveSyncSigningKeypair(new Uint8Array(32).fill(7), "old-self"); const own = { deviceName: "Self", deviceType: "extension" as const, deviceId: "old-self", longTermPublicKeyHex: "a".repeat(64), signingPublicKeyHex: pubkeyToHex(signing.publicKeyRaw) }; const record = { deviceId: "victim", longTermPublicKeyHex: "b".repeat(64), revokedAt: 1, revokedByDeviceId: own.deviceId }; await mergeDeviceRevocations([record]); if (failure === "archive") await chrome.storage.local.set({ [REVOCATION_ISSUERS_KEY]: "corrupt" }); if (failure === "write") chrome.storage.local.set = async () => { throw new Error("write failed"); }; const rotate = vi.fn(async () => { throw new Error("rotate failed"); }); const privateKey = new Uint8Array(32).fill(1); const publicKey = new Uint8Array(32).fill(2); await expect(rotatePairedDeviceIdentity(async () => ({ identity: own, privateKey, publicKey, signingPrivateKey: signing.privateKey }), rotate)).rejects.toThrow(); expect(rotate).toHaveBeenCalledTimes(failure === "rotate" ? 1 : 0); const records = await listDeviceRevocations(); if (failure === "rotate") expect(records[0]).toMatchObject({ ...record, signatureHex: expect.any(String) }); else expect(records).toEqual([record]); expect(privateKey.every((value) => value === 0)).toBe(true); expect(publicKey.every((value) => value === 0)).toBe(true); }); it("archives all long-term-key overlap victims without merging identity bindings or losing equal-version keys", async () => { const key = "a".repeat(64); await upsertPairedDevice({ ...SAMPLE, longTermPublicKeyHex: key, trustSource: "direct", signingKeyHistory: [{ version: 1, publicKeyHex: "2".repeat(64) }, { version: 1, publicKeyHex: "3".repeat(64) }] }); await upsertPairedDevice({ ...SAMPLE, deviceId: "alias", longTermPublicKeyHex: key, trustSource: "vouched" }); await upsertPairedDevicesAndMergeRevocations([], [{ deviceId: "elsewhere", longTermPublicKeyHex: key, revokedAt: 1, revokedByDeviceId: "other" }]); expect(await listPairedDevices()).toEqual([]); expect(((await listRevocationIssuerKeyMap()).get(SAMPLE.deviceId) ?? [])).toEqual(expect.arrayContaining(["1".repeat(64), "2".repeat(64), "3".repeat(64)])); expect(((await listRevocationIssuerKeyMap()).get("alias") ?? [])).toEqual([SAMPLE.signingPublicKeyHex]); await upsertPairedDevice({ ...SAMPLE, longTermPublicKeyHex: "b".repeat(64), signingPublicKeyHex: "4".repeat(64), trustSource: "direct" }); await removePairedDeviceById(SAMPLE.deviceId); const archive = (await chrome.storage.local.get(REVOCATION_ISSUERS_KEY))[REVOCATION_ISSUERS_KEY]; if (!Array.isArray(archive)) throw new Error("missing issuer archive"); expect(archive.filter((entry: { deviceId: string }) => entry.deviceId === SAMPLE.deviceId)).toHaveLength(2); expect(((await listRevocationIssuerKeyMap()).get(SAMPLE.deviceId) ?? [])).toEqual(expect.arrayContaining(["1".repeat(64), "2".repeat(64), "3".repeat(64), "4".repeat(64)])); }); it("retains only authenticated public verification material", async () => { 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) }] }); await removePairedDeviceById(SAMPLE.deviceId); const archive = (await chrome.storage.local.get(REVOCATION_ISSUERS_KEY))[REVOCATION_ISSUERS_KEY]; expect(archive).toEqual([{ deviceId: SAMPLE.deviceId, longTermPublicKeyHex: SAMPLE.longTermPublicKeyHex, signingPublicKeys: ["d".repeat(64), SAMPLE.signingPublicKeyHex] }]); await upsertPairedDevice({ ...SAMPLE, deviceId: "legacy-unattributed" }); await removePairedDeviceById("legacy-unattributed"); expect(((await listRevocationIssuerKeyMap()).get("legacy-unattributed") ?? [])).toEqual([]); }); it("refuses removal over a corrupt issuer archive without losing the live peer", async () => { await upsertPairedDevice({ ...SAMPLE, trustSource: "direct" }); await chrome.storage.local.set({ [REVOCATION_ISSUERS_KEY]: "damaged" }); await expect(removePairedDeviceById(SAMPLE.deviceId)).rejects.toBeInstanceOf(TrustDataCorruptedError); expect(await findPairedDeviceById(SAMPLE.deviceId)).toMatchObject(SAMPLE); }); it("upsert + list", async () => { await upsertPairedDevice(SAMPLE); expect(await listPairedDevices()).toEqual([SAMPLE]); }); it("upsert is idempotent on the same deviceId — updates metadata in place, no duplicate", async () => { await upsertPairedDevice(SAMPLE); await upsertPairedDevice({ ...SAMPLE, deviceName: "Renamed Pixel", pairedAt: 1700000001000 }); const all = await listPairedDevices(); expect(all).toHaveLength(1); expect(all[0]).toMatchObject({ deviceName: "Renamed Pixel", pairedAt: 1700000001000, longTermPublicKeyHex: SAMPLE.longTermPublicKeyHex, signingPublicKeyHex: SAMPLE.signingPublicKeyHex, }); }); it("stores a local alias without changing the peer-reported name or identity", async () => { await upsertPairedDevice(SAMPLE); await renamePairedDevice(SAMPLE.deviceId, " Travel phone "); const renamed = await findPairedDeviceById(SAMPLE.deviceId); expect(renamed).toMatchObject({ deviceName: SAMPLE.deviceName, localAlias: "Travel phone", longTermPublicKeyHex: SAMPLE.longTermPublicKeyHex, }); }); it("rejects blank, oversized, and unknown-device aliases", async () => { await upsertPairedDevice(SAMPLE); await expect(renamePairedDevice(SAMPLE.deviceId, " ")).rejects.toThrow(/empty/); await expect(renamePairedDevice(SAMPLE.deviceId, "x".repeat(65))).rejects.toThrow(/64/); await expect(renamePairedDevice("missing", "Phone")).rejects.toThrow(/not_found/); }); it("rejects a same-deviceId long-term key replacement and leaves the stored row unchanged", async () => { await upsertPairedDevice(SAMPLE); const before = await findPairedDeviceById(SAMPLE.deviceId); await expect( upsertPairedDevice({ ...SAMPLE, longTermPublicKeyHex: "f".repeat(64) }), ).rejects.toThrow("device_identity_immutable"); expect(await findPairedDeviceById(SAMPLE.deviceId)).toEqual(before); }); it("rejects a same-deviceId signing key replacement and leaves the stored row unchanged", async () => { await upsertPairedDevice(SAMPLE); const before = await findPairedDeviceById(SAMPLE.deviceId); await expect( upsertPairedDevice({ ...SAMPLE, signingPublicKeyHex: "2".repeat(64) }), ).rejects.toThrow("device_identity_immutable"); expect(await findPairedDeviceById(SAMPLE.deviceId)).toEqual(before); }); it("preserves an existing signing key when an incoming row omits or nulls it", async () => { await upsertPairedDevice(SAMPLE); await upsertPairedDevice({ ...SAMPLE, deviceName: "Updated Pixel", signingPublicKeyHex: undefined }); await upsertPairedDevice({ ...SAMPLE, deviceName: "Updated Again", signingPublicKeyHex: null as unknown as string, }); expect((await findPairedDeviceById(SAMPLE.deviceId))?.signingPublicKeyHex).toBe( SAMPLE.signingPublicKeyHex, ); }); it("rejects duplicate manifest identities before any registry mutation", async () => { await expect( validatePairedDeviceIdentities([ { ...SAMPLE, deviceName: "First" }, { ...SAMPLE, deviceName: "Second", longTermPublicKeyHex: "f".repeat(64) }, ]), ).rejects.toThrow("device_identity_immutable"); expect(await listPairedDevices()).toEqual([]); }); it("rejects upsert with missing fields", async () => { await expect(upsertPairedDevice({ ...SAMPLE, deviceId: "" })).rejects.toThrow(/deviceId/); await expect(upsertPairedDevice({ ...SAMPLE, longTermPublicKeyHex: undefined })).rejects.toThrow(/longTermPublicKeyHex/); await expect(upsertPairedDevice({ ...SAMPLE, deviceName: undefined })).rejects.toThrow(/deviceName/); await expect(upsertPairedDevice({ ...SAMPLE, deviceType: undefined })).rejects.toThrow(/deviceType/); }); it("caps oversized peer device names at the registry seam", async () => { await upsertPairedDevice({ ...SAMPLE, deviceId: "LONG-1", deviceName: "N".repeat(100) }); const found = await findPairedDeviceById("LONG-1"); expect(found?.deviceName).toBe("N".repeat(64)); }); it("findPairedDeviceByPubkey returns the correct device", async () => { const other: PairedDevice = { ...SAMPLE, deviceId: "BBB-222", longTermPublicKeyHex: "1".repeat(64) }; await upsertPairedDevice(SAMPLE); await upsertPairedDevice(other); expect(await findPairedDeviceByPubkey("1".repeat(64))).toEqual(other); expect(await findPairedDeviceByPubkey("9".repeat(64))).toBeNull(); }); it("removePairedDeviceById drops the device", async () => { await upsertPairedDevice(SAMPLE); await removePairedDeviceById(SAMPLE.deviceId); expect(await listPairedDevices()).toEqual([]); }); it("clearPairedDevices wipes the whole registry", async () => { await upsertPairedDevice(SAMPLE); await clearPairedDevices(); expect(await listPairedDevices()).toEqual([]); }); it("markLastSyncedAt mutates only the target device", async () => { const other: PairedDevice = { ...SAMPLE, deviceId: "BBB-222", longTermPublicKeyHex: "1".repeat(64) }; await upsertPairedDevice(SAMPLE); await upsertPairedDevice(other); await markLastSyncedAt(SAMPLE.deviceId, 1700001000000); const found = await findPairedDeviceById(SAMPLE.deviceId); expect(found?.lastSyncedAt).toBe(1700001000000); const untouched = await findPairedDeviceById(other.deviceId); expect(untouched?.lastSyncedAt).toBeUndefined(); }); it("serializes a concurrent pairing upsert with a sync timestamp update", async () => { const other: PairedDevice = { ...SAMPLE, deviceId: "BBB-222", longTermPublicKeyHex: "1".repeat(64), }; await upsertPairedDevice(SAMPLE); await Promise.all([ upsertPairedDevice(other), markLastSyncedAt(SAMPLE.deviceId, 1700001000000), ]); expect(await listPairedDevices()).toEqual([ { ...SAMPLE, lastSyncedAt: 1700001000000 }, other, ]); }); it("moves every existing pair to a new mesh relay", async () => { const other: PairedDevice = { ...SAMPLE, deviceId: "BBB-222", longTermPublicKeyHex: "1".repeat(64), relayUrl: "wss://old-relay.example", }; await upsertPairedDevice(SAMPLE); await upsertPairedDevice(other); await setRelayUrlForAllPairedDevices("wss://new-relay.example/base"); expect((await listPairedDevices()).map((device) => device.relayUrl)).toEqual([ "wss://new-relay.example/base", "wss://new-relay.example/base", ]); }); it("last sync timestamp accepts a legacy string value", async () => { (globalThis as unknown as { chrome: { storage: { local: { set: (v: Record) => Promise } } } }).chrome.storage.local.set({ peach_last_sync_at: "1700002000000", }); expect(await getLastSyncAt()).toBe(1700002000000); }); it("setLastSyncAt persists a numeric value", async () => { await setLastSyncAt(1700003000000); expect(await getLastSyncAt()).toBe(1700003000000); }); it("listPairedDevices filters invalid entries from an otherwise valid array", async () => { (globalThis as unknown as { chrome: { storage: { local: { set: (v: Record) => Promise } } } }).chrome.storage.local.set({ peach_paired_devices_v3: [ { deviceId: "real", pairedAt: 1, deviceName: "x", deviceType: "android", longTermPublicKeyHex: "0".repeat(64) }, { not: "a device" }, null, 42, ], }); const devices = await listPairedDevices(); expect(devices).toHaveLength(1); expect(devices[0].deviceId).toBe("real"); }); // §18.4: a corrupt persisted ledger must not be read as empty — that would // silently un-revoke every device. A non-array value is integrity damage. it("listPairedDevices throws TrustDataCorruptedError on a non-array registry", async () => { (globalThis as unknown as { chrome: { storage: { local: { set: (v: Record) => Promise } } } }).chrome.storage.local.set({ peach_paired_devices_v3: { corrupted: true }, }); await expect(listPairedDevices()).rejects.toThrow(TrustDataCorruptedError); }); it("listDeviceRevocations throws TrustDataCorruptedError on a non-array ledger", async () => { (globalThis as unknown as { chrome: { storage: { local: { set: (v: Record) => Promise } } } }).chrome.storage.local.set({ peach_device_revocations_v1: "not-an-array", }); await expect(listDeviceRevocations()).rejects.toThrow(TrustDataCorruptedError); }); it("a corrupt registry is not overwritten by a mutation attempt", async () => { const corrupt = { corrupted: true }; (globalThis as unknown as { chrome: { storage: { local: { set: (v: Record) => Promise } } } }).chrome.storage.local.set({ peach_paired_devices_v3: corrupt, }); await expect(upsertPairedDevice(SAMPLE)).rejects.toThrow(TrustDataCorruptedError); // The corrupt payload is preserved — the mutation never wrote. const result = await chrome.storage.local.get("peach_paired_devices_v3"); expect(result["peach_paired_devices_v3"]).toBe(corrupt); }); describe("device revocation", () => { it("revokeDeviceById records the device's key and drops it from the registry", async () => { await upsertPairedDevice(SAMPLE); const record = await revokeDeviceById(SAMPLE.deviceId, "this-device", { now: 1_700_000_000_000, }); expect(record).toMatchObject({ deviceId: SAMPLE.deviceId, longTermPublicKeyHex: SAMPLE.longTermPublicKeyHex, revokedAt: 1_700_000_000_000, revokedByDeviceId: "this-device", }); expect(await findPairedDeviceById(SAMPLE.deviceId)).toBeNull(); expect(await isDeviceRevoked(SAMPLE.deviceId)).toBe(true); }); it("revoking twice is a no-op rather than a duplicate record", async () => { await upsertPairedDevice(SAMPLE); await revokeDeviceById(SAMPLE.deviceId, "this-device"); expect(await revokeDeviceById(SAMPLE.deviceId, "this-device")).toBeNull(); expect(await listDeviceRevocations()).toHaveLength(1); }); it("an existing revocation still removes a stale re-paired row", async () => { await upsertPairedDevice(SAMPLE); await revokeDeviceById(SAMPLE.deviceId, "this-device"); // Reproduce the real corrupt overlap created by older direct-pair // handlers: the row returned but its terminal revocation remained. await upsertPairedDevice(SAMPLE); expect(await revokeDeviceById(SAMPLE.deviceId, "this-device")).toBeNull(); expect(await findPairedDeviceById(SAMPLE.deviceId)).toBeNull(); expect(await listDeviceRevocations()).toHaveLength(1); }); it("mergeDeviceRevocations reports only the ids it had not already seen", async () => { const first = await mergeDeviceRevocations([ { deviceId: "a", longTermPublicKeyHex: "a".repeat(64), revokedAt: 1, revokedByDeviceId: "x" }, ]); expect(first).toEqual(["a"]); const second = await mergeDeviceRevocations([ { deviceId: "a", longTermPublicKeyHex: "a".repeat(64), revokedAt: 2, revokedByDeviceId: "y" }, { deviceId: "b", longTermPublicKeyHex: "b".repeat(64), revokedAt: 3, revokedByDeviceId: "y" }, ]); expect(second).toEqual(["b"]); expect(await listDeviceRevocations()).toHaveLength(2); }); // PB-26-110: the ledger must stay bounded without letting an early flood // consume it permanently. A later revocation from a DIFFERENT issuer is // the record that matters — it has to be admitted even when the ledger is // already full of another issuer's junk. it("a later revocation from a different issuer is still admitted on a full ledger", async () => { await mergeDeviceRevocations(Array.from({ length: 500 }, (_, index) => ({ deviceId: `terminal-${index}`, longTermPublicKeyHex: index.toString(16).padStart(64, "0"), revokedAt: index + 1, revokedByDeviceId: "issuer-a", }))); expect(await mergeDeviceRevocations([{ deviceId: "peer-extra", longTermPublicKeyHex: "f".repeat(64), revokedAt: 999, revokedByDeviceId: "issuer-b", }])).toEqual(["peer-extra"]); const records = await listDeviceRevocations(); expect(records).toHaveLength(500); // The genuine record is admitted and still blocks re-vouching. expect(await isDeviceRevoked("peer-extra")).toBe(true); // Room was made by evicting the over-represented issuer's own record, // not another issuer's. expect(records.filter((r) => r.revokedByDeviceId === "issuer-b")).toHaveLength(1); expect(await isDeviceRevoked("terminal-0")).toBe(false); }); it("a same-issuer local flood retains the bounded ledger", async () => { for (let index = 0; index < 501; index += 1) { await upsertPairedDevice({ ...SAMPLE, deviceId: `local-${index}`, longTermPublicKeyHex: index.toString(16).padStart(64, "0"), }); await revokeDeviceById(`local-${index}`, "issuer-a", { now: index + 1 }); } const records = await listDeviceRevocations(); expect(records).toHaveLength(500); expect(records.some((record) => record.deviceId === "local-0")).toBe(false); expect(records.at(-1)?.deviceId).toBe("local-500"); }); it("a different issuer local revoke preserves one of its genuine records", async () => { await mergeDeviceRevocations(Array.from({ length: 500 }, (_, index) => ({ deviceId: `terminal-${index}`, longTermPublicKeyHex: index.toString(16).padStart(64, "0"), revokedAt: index + 1, revokedByDeviceId: index === 0 ? "issuer-a" : "issuer-b", }))); await upsertPairedDevice({ ...SAMPLE, deviceId: "local-new", longTermPublicKeyHex: "f".repeat(64) }); await revokeDeviceById("local-new", "issuer-a", { now: 501 }); const records = await listDeviceRevocations(); expect(records).toHaveLength(500); expect(records.some((record) => record.deviceId === "terminal-0")).toBe(true); expect(records.some((record) => record.deviceId === "local-new")).toBe(true); }); it("a peer flood cannot evict an older revocation from another issuer", async () => { await mergeDeviceRevocations([{ deviceId: "genuine", longTermPublicKeyHex: "a".repeat(64), revokedAt: 1, revokedByDeviceId: "honest-issuer", }]); const flood = Array.from({ length: 600 }, (_, index) => ({ deviceId: `junk-${index}`, longTermPublicKeyHex: index.toString(16).padStart(64, "0"), revokedAt: index + 2, revokedByDeviceId: "flooding-issuer", })); const admitted = await mergeDeviceRevocations(flood); expect(admitted).toHaveLength(600); const records = await listDeviceRevocations(); expect(records).toHaveLength(500); expect(await isDeviceRevoked("genuine")).toBe(true); // The flooder is the over-represented issuer, so its own oldest records // are what get dropped — the newest junk survives, the oldest does not. expect(await isDeviceRevoked("junk-599")).toBe(true); expect(await isDeviceRevoked("junk-0")).toBe(false); }); it("a later revokedAt cannot displace an existing record — revocation is terminal", async () => { await mergeDeviceRevocations([ { deviceId: "a", longTermPublicKeyHex: "a".repeat(64), revokedAt: 1, revokedByDeviceId: "x" }, ]); await mergeDeviceRevocations([ { deviceId: "a", longTermPublicKeyHex: "c".repeat(64), revokedAt: 9_999, revokedByDeviceId: "attacker" }, ]); const records = await listDeviceRevocations(); expect(records).toHaveLength(1); expect(records[0]).toMatchObject({ revokedAt: 1, revokedByDeviceId: "x" }); }); it("HOLE 2: a far-future revokedAt is clamped rather than stored verbatim", async () => { const farFuture = Date.now() + 10 * 365 * 24 * 60 * 60 * 1000; await mergeDeviceRevocations([ { deviceId: "a", longTermPublicKeyHex: "a".repeat(64), revokedAt: farFuture, revokedByDeviceId: "peer" }, ]); const [record] = await listDeviceRevocations(); expect(record.revokedAt).toBeLessThanOrEqual(Date.now() + 5 * 60 * 1000); }); it("startup repair keeps a newer direct pair and clears its older revocation", async () => { const now = Date.now(); await mergeDeviceRevocations([{ deviceId: SAMPLE.deviceId, longTermPublicKeyHex: SAMPLE.longTermPublicKeyHex!, revokedAt: now - 1_000, revokedByDeviceId: "this-device", }]); await upsertPairedDevice({ ...SAMPLE, pairedAt: now, trustSource: "direct", }); expect(await repairPairedRevocationOverlaps()).toEqual({ revocationsCleared: 1, pairedRowsRemoved: 0, }); expect(await findPairedDeviceById(SAMPLE.deviceId)).not.toBeNull(); expect(await isDeviceRevoked(SAMPLE.deviceId)).toBe(false); }); it("startup repair removes a direct pair older than its revocation", async () => { const now = Date.now(); await upsertPairedDevice({ ...SAMPLE, pairedAt: now - 2_000, trustSource: "direct", }); await mergeDeviceRevocations([{ deviceId: SAMPLE.deviceId, longTermPublicKeyHex: SAMPLE.longTermPublicKeyHex!, revokedAt: now - 1_000, revokedByDeviceId: "this-device", }]); expect(await repairPairedRevocationOverlaps()).toEqual({ revocationsCleared: 0, pairedRowsRemoved: 1, }); expect(await findPairedDeviceById(SAMPLE.deviceId)).toBeNull(); expect(await isDeviceRevoked(SAMPLE.deviceId)).toBe(true); }); it("startup repair never lets a newer vouched pair lift a revocation", async () => { const now = Date.now(); await mergeDeviceRevocations([{ deviceId: SAMPLE.deviceId, longTermPublicKeyHex: SAMPLE.longTermPublicKeyHex!, revokedAt: now - 1_000, revokedByDeviceId: "this-device", }]); await upsertPairedDevice({ ...SAMPLE, pairedAt: now, trustSource: "vouched", }); expect(await repairPairedRevocationOverlaps()).toEqual({ revocationsCleared: 0, pairedRowsRemoved: 1, }); expect(await findPairedDeviceById(SAMPLE.deviceId)).toBeNull(); expect(await isDeviceRevoked(SAMPLE.deviceId)).toBe(true); }); }); });