fe296aba12b8
wip: preserve revocations pending bootstrap integration (v5.3.22)
- time
- 2026-11-20 17:38 UTC · 1 week ago
- machine
- Junes-MacBook-Pro.local
- agent
- gpt-6
- session
- remediate interim audit findings
- parent
- 7469acdae58d
↓ peach-browser-fe296aba.tar.gzatlas at this save
files changed16 files
manifest.firefox.json+1 −1manifest.json+1 −1package.json+1 −1src/background/device-identity.test.ts+42 −0src/background/device-identity.ts+22 −4src/background/messages.test.ts+15 −0src/background/messages.ts+9 −9src/background/paired-devices.test.ts+168 −1src/background/paired-devices.ts+173 −29src/background/relay-adoption-bg.test.ts+3 −0src/background/relay-adoption-bg.ts+2 −1src/background/sync-generation.test.ts+53 −1src/background/sync-generation.ts+15 −5src/background/sync-vault-adapter.test.ts+101 −0src/background/sync-vault-adapter.ts+31 −65src/background/vault.rotate-sync-identity.test.ts+20 −0manifest.firefox.json+1 −1
@@ -1,7 +1,7 @@11 {22 "manifest_version": 3,33 "name": "Peach Password Manager",4- "version": "5.3.20",4+ "version": "5.3.22",55 "description": "Zero-knowledge password manager",66 "browser_specific_settings": {77 "gecko": {manifest.json+1 −1
@@ -2,7 +2,7 @@22 "manifest_version": 3,33 "minimum_chrome_version": "116",44 "name": "Peach Password Manager",5- "version": "5.3.20",5+ "version": "5.3.22",66 "description": "Zero-knowledge password manager",77 "action": {88 "default_popup": "src/popup/index.html",package.json+1 −1
@@ -1,6 +1,6 @@11 {22 "name": "peach",3- "version": "5.3.20",3+ "version": "5.3.22",44 "description": "Zero-knowledge password manager",55 "license": "GPL-3.0-only",66 "type": "module",src/background/device-identity.test.ts+42 −0
@@ -120,6 +120,48 @@120120 });121121 122122 describe("device-identity getOrCreateDeviceId (PCH-01-004)", () => {123+ it("existing-only loaders refuse missing identity without probing or minting trust", async () => {124+ const vault = await import("./vault");125+ await vault.createVault("identity-test-password");126+ const identity = await import("./device-identity");127+ delete local[IDENTITY_KEY];128+ delete local.peach_local_identity_initialized;129+ delete session.peach_local_identity_session;130+ local.peach_revocation_issuers_v1 = "corrupt";131+ localSet.mockClear();132+ await expect(identity.getExistingDeviceId()).rejects.toThrow("identity_migration_required");133+ await expect(identity.getLocalPairingIdentity({ existingOnly: true })).rejects.toThrow("identity_migration_required");134+ expect(localSet).not.toHaveBeenCalled();135+ });136+137+ it("does not mint an identity over a corrupt verification archive", async () => {138+ const vault = await import("./vault");139+ await vault.createVault("identity-test-password");140+ delete local[IDENTITY_KEY];141+ delete local.peach_local_identity_initialized;142+ delete session.peach_local_identity_session;143+ local.peach_revocation_issuers_v1 = "corrupt";144+ localSet.mockClear();145+ const identity = await import("./device-identity");146+ await expect(identity.getOrCreateDeviceId()).rejects.toThrow("trust_data_corrupted");147+ expect(localSet).not.toHaveBeenCalled();148+ });149+150+ it("raw secure-reset identity rotation does not recreate cleared issuer trust", async () => {151+ const vault = await import("./vault");152+ await vault.createVault("identity-test-password");153+ const identity = await import("./device-identity");154+ await identity.getOrCreateDeviceId();155+ const { REVOCATION_ISSUERS_KEY, REVOCATIONS_KEY } = await import("./paired-devices");156+ local[REVOCATION_ISSUERS_KEY] = [{ deviceId: "old", longTermPublicKeyHex: "a".repeat(64), signingPublicKeys: ["b".repeat(64)] }];157+ local[REVOCATIONS_KEY] = [];158+ const { browserGenerationIo } = await import("./sync-generation");159+ expect(await browserGenerationIo.clearLegacyTrustState()).toBe(true);160+ await identity.rotateDeviceId();161+ expect(local[REVOCATION_ISSUERS_KEY]).toBeUndefined();162+ expect(local[REVOCATIONS_KEY]).toBeUndefined();163+ });164+123165 it("fresh_install_writes_id_to_local_only", async () => {124166 const vault = await import("./vault");125167 await vault.createVault("identity-test-password");src/background/device-identity.ts+22 −4
@@ -464,6 +464,18 @@464464 return (await ensureRecord()).deviceId;465465 }466466 467+/// Read an existing identity without minting or consulting the device-mutation queue.468+export async function getExistingDeviceId(): Promise<string> {469+ if (!isUnlocked() || getRootKeyHex() === null) throw new Error("vault_locked");470+ return (await requireExistingRecord()).deviceId;471+}472+473+async function requireExistingRecord(): Promise<IdentityRecord> {474+ const record = await loadRecord();475+ if (!record) throw new Error("identity_migration_required");476+ return record;477+}478+467479 export async function rotateDeviceId(): Promise<string> {468480 if (!isUnlocked() || getRootKeyHex() === null) throw new Error("vault_locked");469481 const record = await makeRecord();@@ -501,8 +513,8 @@501513 };502514 }503515 504-export async function getLocalPairingIdentity(): Promise<{505- identity: LocalIdentity;516+export async function getLocalPairingIdentity(options: { existingOnly?: boolean } = {}): Promise<{517+ identity: LocalIdentity & LocalDeviceIdentity;506518 privateKey: Uint8Array;507519 publicKey: Uint8Array;508520 signingPrivateKey: CryptoKey;@@ -512,11 +524,17 @@512524 if (!rootHex) throw new Error("vault_locked");513525 const root = bytes(rootHex);514526 try {515- const record = await ensureRecord();527+ const record = options.existingOnly ? await requireExistingRecord() : await ensureRecord();516528 const privateKey = bytes(record.x25519PrivateKeyHex);517529 const publicKey = generateKeyPairFromSeed(privateKey).publicKey;518530 const signingPrivateKey = await importSigningKey(bytes(record.ed25519SeedHex));519- const base = await buildLocalIdentity();531+ const base: LocalDeviceIdentity = {532+ deviceId: record.deviceId,533+ deviceName: await getDeviceName(),534+ deviceType: "extension",535+ longTermPublicKeyHex: record.x25519PublicKeyHex,536+ signingPublicKeyHex: record.ed25519PublicKeyHex,537+ };520538 return { identity: { ...base, vaultId: await computeVaultId(root) }, privateKey, publicKey, signingPrivateKey };521539 } finally {522540 root.fill(0);src/background/messages.test.ts+15 −0
@@ -2130,6 +2130,21 @@21302130 revokedByDeviceId: expect.any(String),21312131 });21322132 });2133+ it("UNPAIR_DEVICE resolves its issuer after an already queued adoption rotation", async () => {2134+ const vault = await import("./vault");2135+ await vault.createVault("correct-pass-12345");2136+ const identity = await import("./device-identity");2137+ const paired = await import("./paired-devices");2138+ const oldId = await identity.getOrCreateDeviceId();2139+ const rotation = paired.rotatePairedDeviceIdentity(() => identity.getLocalPairingIdentity({ existingOnly: true }), identity.rotateDeviceId);2140+ const removal = dispatch({ type: "UNPAIR_DEVICE", payload: { deviceId: "phone-1" } });2141+ await rotation;2142+ expect(await removal).toMatchObject({ ok: true });2143+ const newId = await identity.getExistingDeviceId();2144+ expect(newId).not.toBe(oldId);2145+ expect(await paired.listDeviceRevocations()).toMatchObject([{ deviceId: "phone-1", revokedByDeviceId: newId }]);2146+ });2147+21332148 it("UNPAIR_DEVICE still evicts a peer when the local identity needs migration", async () => {21342149 const vault = await import("./vault");21352150 await vault.createVault("correct-pass-12345");src/background/messages.ts+9 −9
@@ -71,7 +71,7 @@7171 import { isValidMLFeatureBatch, predictBatch as mlPredictBatch } from "./ml";7272 import {7373 buildLocalIdentity,74- getOrCreateDeviceId,74+ getExistingDeviceId,7575 setDeviceName as setDeviceNameV3,7676 type LocalDeviceIdentity,7777 } from "./device-identity";@@ -1812,14 +1812,14 @@18121812 // peer locally. Sync is already blocked until the secure reset repairs18131813 // this installation, so the local issuer marker is sufficient for the18141814 // tombstone that will be cleared with the archived generation.1815- let revokedByDeviceId: string;1816- try {1817- revokedByDeviceId = await getOrCreateDeviceId();1818- } catch (error) {1819- if (!(error instanceof Error) || error.message !== "identity_migration_required") throw error;1820- revokedByDeviceId = "local";1821- }1822- await revokeDeviceByIdV3(deviceId, revokedByDeviceId);1815+ await revokeDeviceByIdV3(deviceId, async () => {1816+ try {1817+ return await getExistingDeviceId();1818+ } catch (error) {1819+ if (!(error instanceof Error) || error.message !== "identity_migration_required") throw error;1820+ return "local";1821+ }1822+ });18231823 // PB-26-213: forget the secret now so no further dial can use it.18241824 // Removals that happen while locked leave orphans for the next18251825 // unlock's reconcile to prune.src/background/paired-devices.test.ts+168 −1
@@ -1,7 +1,11 @@1-import { describe, expect, it, beforeEach } from "vitest";1+import { describe, expect, it, beforeEach, vi } from "vitest";22 import type { PairedDevice } from "../shared/sync-types";33 import {44 clearPairedDevices,5+ listRevocationIssuerKeyMap,6+ REVOCATION_ISSUERS_KEY,7+ writePairedDevices,8+ upsertPairedDevicesAndMergeRevocations,59 findPairedDeviceById,610 findPairedDeviceByPubkey,711 getLastSyncAt,@@ -14,10 +18,12 @@1418 removePairedDeviceById,1519 renamePairedDevice,1620 revokeDeviceById,21+ rotatePairedDeviceIdentity,1722 setLastSyncAt,1823 setRelayUrlForAllPairedDevices,1924 TrustDataCorruptedError,2025 upsertPairedDevice,26+ upsertPairedDeviceAndClearRevocation,2127 validatePairedDeviceIdentities,2228 } from "./paired-devices";2329 @@ -63,6 +69,167 @@6369 6470 describe("paired-devices registry", () => {6571 beforeEach(() => makeStorageStub());72+73+ 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+ });99+100+ 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+ });110+111+ 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+ });122+123+ 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+ });130+131+ 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+ });146+147+ 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+ });179+180+ 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+ });200+201+ 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+ });216+217+ 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+ });226+227+ 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+ });66233 67234 it("upsert + list", async () => {68235 await upsertPairedDevice(SAMPLE);src/background/paired-devices.ts+173 −29
@@ -15,6 +15,7 @@1515 // local-only; Noise KK rejection on the next connection is the security1616 // boundary (see removePairedDeviceById).1717 18+import { signDeviceRevocation } from "../shared/device-manifest";1819 import type { DeviceRevocation, PairedDevice } from "../shared/sync-types";1920 import { constantTimeEqualHex } from "../shared/constant-time";2021 import { capDeviceName, clampSyncTimestamp } from "../shared/sync-limits";@@ -22,6 +23,78 @@2223 2324 export const REGISTRY_KEY = "peach_paired_devices_v3";2425 export const REVOCATIONS_KEY = "peach_device_revocations_v1";26+export const REVOCATION_ISSUERS_KEY = "peach_revocation_issuers_v1";27+28+type RevocationIssuer = {29+ deviceId: string;30+ longTermPublicKeyHex: string;31+ signingPublicKeys: string[];32+};33+34+function 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+}41+42+async function listRevocationIssuersRaw(): Promise<RevocationIssuer[]> {43+ return parseRevocationIssuers((await chrome.storage.local.get(REVOCATION_ISSUERS_KEY))[REVOCATION_ISSUERS_KEY]);44+}45+46+function 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+}61+62+async 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+}76+77+/// One consistent snapshot of live and archived record-verification keys.78+export 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+}93+94+export async function hasRevocationIssuerArchive(): Promise<boolean> {95+ await deviceMutationTail;96+ return (await listRevocationIssuersRaw()).length > 0;97+}2598 /** Bound the list so a hostile peer cannot grow storage without limit. */2699 const MAX_REVOCATIONS = 500;27100 const LAST_SYNC_AT_KEY = "peach_last_sync_at";@@ -51,7 +124,10 @@51124 52125 async function listPairedDevicesRaw(): Promise<PairedDevice[]> {53126 const result = await chrome.storage.local.get(REGISTRY_KEY);54- const devices = (result as Record<string, unknown>)[REGISTRY_KEY];127+ return parsePairedDevices((result as Record<string, unknown>)[REGISTRY_KEY]);128+}129+130+function parsePairedDevices(devices: unknown): PairedDevice[] {55131 if (devices === undefined) return [];56132 if (!Array.isArray(devices)) {57133 throw new TrustDataCorruptedError(REGISTRY_KEY, `expected array, got ${typeof devices}`);@@ -87,7 +163,9 @@87163 }88164 89165 async function writePairedDevicesRaw(devices: PairedDevice[]): Promise<void> {166+ const retained = await retainRevocationIssuers(retiredIssuerRows(await listPairedDevicesRaw(), devices));90167 await chrome.storage.local.set({168+ [REVOCATION_ISSUERS_KEY]: retained,91169 [REGISTRY_KEY]: devices.map((device) => {92170 const normalized = withSigningKeyHistory(device);93171 if (!isValidSecret(normalized.rendezvousSecretHex)) return normalized;@@ -98,6 +176,22 @@98176 });99177 }100178 179+function 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+}194+101195 function isValidSecret(value: unknown): value is string {102196 return typeof value === "string" && /^[0-9a-f]{64}$/.test(value);103197 }@@ -269,6 +363,7 @@269363 const devices = await listPairedDevicesRaw();270364 await chrome.storage.local.set({271365 [REGISTRY_KEY]: devices.filter((d) => d.deviceId !== deviceId),366+ [REVOCATION_ISSUERS_KEY]: await retainRevocationIssuers(devices.filter((d) => d.deviceId === deviceId)),272367 });273368 });274369 // The device-list-changed sync trigger fires from the messages.ts UNPAIR_DEVICE@@ -327,39 +422,79 @@327422 */328423 export async function revokeDeviceById(329424 deviceId: string,330- revokedByDeviceId: string,425+ issuer: string | (() => Promise<string>),331426 options: { now?: number } = {},332427 ): Promise<DeviceRevocation | null> {333428 return enqueueDeviceMutation(async () => {334- const devices = await listPairedDevicesRaw();335- const device = devices.find((candidate) => candidate.deviceId === deviceId);336- const existing = await listDeviceRevocationsRaw();337- if (existing.some((r) => r.deviceId === deviceId)) {338- // A direct re-pair in older builds could restore the paired row without339- // clearing its terminal revocation. "Remove" then returned early here and340- // left the row visible forever. Idempotency applies to the revocation341- // record, not to removing any stale live row that overlaps it.342- if (device) await chrome.storage.local.set({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+ }443+444+ 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({343455 [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]),344458 });345- return null;346- }459+ return record;460+ });461+}347462 348- const record: DeviceRevocation = {349- deviceId,350- // A device with no stored key was never usable as a sync peer; the351- // all-zero key keeps the record well-formed on the wire without352- // pretending to name a key we never saw.353- longTermPublicKeyHex: device?.longTermPublicKeyHex ?? "0".repeat(64),354- revokedAt: options.now ?? Date.now(),355- revokedByDeviceId,356- };357- await chrome.storage.local.set({358- [REGISTRY_KEY]: devices.filter((candidate) => candidate.deviceId !== deviceId),359- [REVOCATIONS_KEY]: capRevocations([...existing, record]),463+/// Seal this identity's outstanding records before replacing its credentials.464+export 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+ }360497 });361- return record;362- });363498 }364499 365500 /**@@ -403,6 +538,7 @@403538 const filtered = revocations.filter((record) => record.deviceId !== device.deviceId);404539 await chrome.storage.local.set({405540 [REGISTRY_KEY]: scrubRegistryRows(devices),541+ [REVOCATION_ISSUERS_KEY]: await retainRevocationIssuers(stored ? [stored] : []),406542 [REVOCATIONS_KEY]: capRevocations(filtered),407543 });408544 });@@ -413,7 +549,8 @@413549 incomingRevocations: DeviceRevocation[],414550 ): Promise<string[]> {415551 return enqueueDeviceMutation(async () => {416- const stored = await listPairedDevicesRaw();552+ const previous = await listPairedDevicesRaw();553+ const stored = [...previous];417554 const incomingById = validateAndIndexDevices(stored, devices);418555 const existingRevocations = await listDeviceRevocationsRaw();419556 const knownById = new Set(existingRevocations.map((record) => record.deviceId));@@ -449,6 +586,7 @@449586 );450587 await chrome.storage.local.set({451588 [REGISTRY_KEY]: registry,589+ [REVOCATION_ISSUERS_KEY]: await retainRevocationIssuers(retiredIssuerRows(previous, registry)),452590 [REVOCATIONS_KEY]: capRevocations(allRevocations),453591 });454592 return fresh.map((record) => record.deviceId);@@ -544,6 +682,7 @@544682 545683 await chrome.storage.local.set({546684 [REGISTRY_KEY]: devices.filter((device) => !pairedIdsToRemove.has(device.deviceId)),685+ [REVOCATION_ISSUERS_KEY]: await retainRevocationIssuers(devices.filter((device) => pairedIdsToRemove.has(device.deviceId))),547686 [REVOCATIONS_KEY]: revocations.filter(548687 (record) => !revocationIdsToClear.has(record.deviceId),549688 ),@@ -613,7 +752,12 @@613752 }614753 615754 export async function clearPairedDevices(): Promise<void> {616- await enqueueDeviceMutation(() => chrome.storage.local.remove(REGISTRY_KEY));755+ await enqueueDeviceMutation(async () => {756+ await chrome.storage.local.set({757+ [REGISTRY_KEY]: [],758+ [REVOCATION_ISSUERS_KEY]: await retainRevocationIssuers(await listPairedDevicesRaw()),759+ });760+ });617761 }618762 619763 export async function markLastSyncedAt(deviceId: string, when: number): Promise<void> {src/background/relay-adoption-bg.test.ts+3 −0
@@ -10,6 +10,7 @@1010 clearRevocation: vi.fn(),1111 hasIdentityConflict: vi.fn(),1212 rotateDeviceId: vi.fn(),13+ rotatePairedDeviceIdentity: vi.fn(async (_load: unknown, rotate: () => Promise<string>) => rotate()),1314 setPairSecret: vi.fn(),1415 pushes: [] as Array<{ type: string; payload: unknown }>,1516 triggerSync: vi.fn(),@@ -130,6 +131,7 @@130131 upsertPairedDeviceAndClearRevocation: mocks.upsert,131132 clearDeviceRevocation: mocks.clearRevocation,132133 hasAdoptionIdentityConflict: mocks.hasIdentityConflict,134+ rotatePairedDeviceIdentity: mocks.rotatePairedDeviceIdentity,133135 }));134136 135137 vi.mock("./pair-secrets", () => ({@@ -1269,6 +1271,7 @@12691271 expect(mocks.hasIdentityConflict).toHaveBeenCalledWith("receiver-id", "d".repeat(64));12701272 12711273 await deps.rotateSourceIdentity();1274+ expect(mocks.rotatePairedDeviceIdentity).toHaveBeenCalledWith(expect.any(Function), mocks.rotateDeviceId);12721275 expect(mocks.rotateDeviceId).toHaveBeenCalled();12731276 12741277 // §10.4.1: the pending holder is durable before any root-bearing frame.src/background/relay-adoption-bg.ts+2 −1
@@ -57,6 +57,7 @@5757 import {5858 hasAdoptionIdentityConflict,5959 markLastSyncedAt,60+ rotatePairedDeviceIdentity,6061 upsertPairedDeviceAndClearRevocation,6162 } from "./paired-devices";6263 import { getSyncSettings, relayInForce } from "./sync-settings";@@ -735,7 +736,7 @@735736 hasDeviceIdentityCollision: async (device) =>736737 hasAdoptionIdentityConflict(device.deviceId, device.longTermPublicKeyHex ?? ""),737738 rotateSourceIdentity: async () => {738- await rotateDeviceId();739+ await rotatePairedDeviceIdentity(() => getLocalPairingIdentity({ existingOnly: true }), rotateDeviceId);739740 return await buildLocalIdentity();740741 },741742 persistPendingIdentity: persistPendingAdoptionIdentity,src/background/sync-generation.test.ts+53 −1
@@ -3,9 +3,11 @@33 // and the sync gate. Runs entirely against an in-memory io — no Chrome, no44 // vault, no crypto.55 6-import { describe, expect, it } from "vitest";6+import { afterEach, describe, expect, it, vi } from "vitest";77 import {88 GENERATION_UNKNOWN,9+ browserGenerationIo,10+ hasLegacyTrustState,911 LEGACY_ACTIVE,1012 REPAIRING,1113 RESET_CONFIRMED,@@ -33,6 +35,7 @@3335 blob: unknown = null;3436 pairedDevices = false;3537 revocations = false;38+ archivedIssuers = false;3639 pendingHolders = false;3740 legacyRouteMaterial = false;3841 @@ -72,6 +75,10 @@7275 return this.pairedDevices;7376 }7477 78+ async hasArchivedIssuers(): Promise<boolean> {79+ return this.archivedIssuers;80+ }81+7582 async hasRevocations(): Promise<boolean> {7683 return this.revocations;7784 }@@ -97,6 +104,7 @@97104 this.cleared = true;98105 this.pairedDevices = false;99106 this.revocations = false;107+ this.archivedIssuers = false;100108 this.pendingHolders = false;101109 this.legacyRouteMaterial = false;102110 this.calls.push("clear");@@ -194,6 +202,7 @@194202 const classes: Array<[string, (io: FakeGenerationIo) => void]> = [195203 ["paired device", (io) => (io.pairedDevices = true)],196204 ["revocation", (io) => (io.revocations = true)],205+ ["archived issuer", (io) => (io.archivedIssuers = true)],197206 ["pending holder", (io) => (io.pendingHolders = true)],198207 ["legacy route material", (io) => (io.legacyRouteMaterial = true)],199208 ];@@ -381,5 +390,48 @@381390 expect(io.calls).toEqual(["archive:1", "clear", "identity"]);382391 expect(io.record?.legacyArchiveRef).toBe("peach_sync_archive_g1_v1");383392 expect(io.record?.generation).toBe(2);393+ });394+});395+396+397+describe("verification issuer archive reset", () => {398+ afterEach(() => vi.unstubAllGlobals());399+ it("refuses corrupt archive trust without persisting a new generation", async () => {400+ const { REVOCATION_ISSUERS_KEY } = await import("./paired-devices");401+ const set = vi.fn();402+ vi.stubGlobal("chrome", { storage: { local: {403+ get: async () => ({ [REVOCATION_ISSUERS_KEY]: "corrupt" }), set,404+ } } });405+ await expect(hasLegacyTrustState(browserGenerationIo)).rejects.toThrow("trust_data_corrupted");406+ await expect(resolveGeneration(browserGenerationIo)).rejects.toThrow("trust_data_corrupted");407+ expect(set).not.toHaveBeenCalled();408+ });409+410+ it("counts archive-only trust, copies it into rollback history and verifies its removal", async () => {411+ const { REVOCATION_ISSUERS_KEY } = await import("./paired-devices");412+ const archive = [{ deviceId: "removed", longTermPublicKeyHex: "a".repeat(64), signingPublicKeys: ["b".repeat(64)] }];413+ const stored: Record<string, unknown> = { [REVOCATION_ISSUERS_KEY]: archive };414+ let refuseRemoval = true;415+ const area = {416+ async get(keys: string | string[]) {417+ return Object.fromEntries((Array.isArray(keys) ? keys : [keys]).map((key) => [key, stored[key]]));418+ },419+ async set(values: Record<string, unknown>) { Object.assign(stored, values); },420+ async remove(keys: string | string[]) {421+ for (const key of Array.isArray(keys) ? keys : [keys]) {422+ if (key !== REVOCATION_ISSUERS_KEY || !refuseRemoval) delete stored[key];423+ }424+ },425+ };426+ vi.stubGlobal("chrome", { storage: { local: area, session: area } });427+ expect(await hasLegacyTrustState(browserGenerationIo)).toBe(true);428+ const ref = await browserGenerationIo.archiveLegacyState(1);429+ expect(ref).not.toBeNull();430+ expect(stored[ref!] as { revocationIssuers: unknown }).toMatchObject({ revocationIssuers: archive });431+ expect(await browserGenerationIo.clearLegacyTrustState()).toBe(false);432+ refuseRemoval = false;433+ expect(await browserGenerationIo.clearLegacyTrustState()).toBe(true);434+ expect(stored[REVOCATION_ISSUERS_KEY]).toBeUndefined();435+ expect(await hasLegacyTrustState(browserGenerationIo)).toBe(false);384436 });385437 });src/background/sync-generation.ts+15 −5
@@ -16,7 +16,7 @@1616 PENDING_ADOPTION_HOLDER_KEY,1717 PENDING_ADOPTION_IDENTITY_KEY,1818 } from "./pending-adoption-holder";19-import { REGISTRY_KEY, REVOCATIONS_KEY, listPairedDevices, TrustDataCorruptedError } from "./paired-devices";19+import { REGISTRY_KEY, REVOCATIONS_KEY, REVOCATION_ISSUERS_KEY, hasRevocationIssuerArchive, listPairedDevices, TrustDataCorruptedError } from "./paired-devices";2020 2121 export const GENERATION_KEY = "peach_sync_generation_v1";2222 @@ -78,6 +78,7 @@7878 writeBlob(blob: SyncGenerationBlob): Promise<boolean>;7979 hasPairedDevices(): Promise<boolean>;8080 hasRevocations(): Promise<boolean>;81+ hasArchivedIssuers(): Promise<boolean>;8182 hasPendingHolders(): Promise<boolean>;8283 hasLegacyRouteMaterial(): Promise<boolean>;8384 archiveLegacyState(generation: number): Promise<string | null>;@@ -125,13 +126,14 @@125126 }126127 127128 export async function hasLegacyTrustState(io: SyncGenerationIo): Promise<boolean> {128- const [paired, revocations, pending, route] = await Promise.all([129+ const [paired, revocations, archivedIssuers, pending, route] = await Promise.all([129130 io.hasPairedDevices(),130131 io.hasRevocations(),132+ io.hasArchivedIssuers(),131133 io.hasPendingHolders(),132134 io.hasLegacyRouteMaterial(),133135 ]);134- return paired || revocations || pending || route;136+ return paired || revocations || archivedIssuers || pending || route;135137 }136138 137139 /**@@ -334,6 +336,10 @@334336 return (await listPairedDevices()).length > 0;335337 },336338 339+ async hasArchivedIssuers() {340+ return hasRevocationIssuerArchive();341+ },342+337343 async hasRevocations() {338344 const value = (await chrome.storage.local.get(REVOCATIONS_KEY))[REVOCATIONS_KEY];339345 if (value === undefined) return false;@@ -365,6 +371,7 @@365371 const stored = await chrome.storage.local.get([366372 REGISTRY_KEY,367373 REVOCATIONS_KEY,374+ REVOCATION_ISSUERS_KEY,368375 PENDING_ADOPTION_HOLDER_KEY,369376 PENDING_ADOPTION_IDENTITY_KEY,370377 PAIR_SECRETS_KEY,@@ -375,6 +382,7 @@375382 archivedAt: Date.now(),376383 pairedDevices: stored[REGISTRY_KEY] ?? null,377384 revocations: stored[REVOCATIONS_KEY] ?? null,385+ revocationIssuers: stored[REVOCATION_ISSUERS_KEY] ?? null,378386 pendingHolder: stored[PENDING_ADOPTION_HOLDER_KEY] ?? null,379387 pendingIdentity: stored[PENDING_ADOPTION_IDENTITY_KEY] ?? null,380388 pairSecrets: stored[PAIR_SECRETS_KEY] ?? null,@@ -402,20 +410,22 @@402410 await chrome.storage.local.remove([403411 REGISTRY_KEY,404412 REVOCATIONS_KEY,413+ REVOCATION_ISSUERS_KEY,405414 PENDING_ADOPTION_HOLDER_KEY,406415 PENDING_ADOPTION_IDENTITY_KEY,407416 PAIR_SECRETS_KEY,408417 ]);409418 await dropSessionCache();410419 // Verified rather than assumed: the clear is what licenses the mint.411- const [paired, revocations, pending, route, session] = await Promise.all([420+ const [paired, revocations, archivedIssuers, pending, route, session] = await Promise.all([412421 browserGenerationIo.hasPairedDevices(),413422 browserGenerationIo.hasRevocations(),423+ browserGenerationIo.hasArchivedIssuers(),414424 browserGenerationIo.hasPendingHolders(),415425 browserGenerationIo.hasLegacyRouteMaterial(),416426 chrome.storage.session.get(SESSION_PAIR_SECRETS_KEY),417427 ]);418- return !paired && !revocations && !pending && !route && session[SESSION_PAIR_SECRETS_KEY] === undefined;428+ return !paired && !revocations && !archivedIssuers && !pending && !route && session[SESSION_PAIR_SECRETS_KEY] === undefined;419429 } catch {420430 return false;421431 }src/background/sync-vault-adapter.test.ts+101 −0
@@ -59,6 +59,107 @@5959 return pubkeyToHex(kp.publicKeyRaw);6060 }6161 62+ it("verifies its own already-signed record without a self registry row", async () => {63+ const { adapter } = await setupVault();64+ const { getLocalPairingIdentity } = await import("./device-identity");65+ const { mergeDeviceRevocations } = await import("./paired-devices");66+ const { signDeviceRevocation } = await import("../shared/device-manifest");67+ const own = await getLocalPairingIdentity();68+ try {69+ const signed = await signDeviceRevocation({ deviceId: "retired", longTermPublicKeyHex: "a".repeat(64), revokedAt: 1, revokedByDeviceId: own.identity.deviceId }, own.signingPrivateKey);70+ await mergeDeviceRevocations([signed]);71+ expect((await adapter.buildOutgoingDeviceManifest?.())?.body.revoked).toEqual([signed]);72+ } finally {73+ own.privateKey.fill(0);74+ own.publicKey.fill(0);75+ }76+ });77+78+ it.each([false, true])("fails outgoing generation for an unverifiable foreign record (signed=%s)", async (signed) => {79+ const { adapter } = await setupVault();80+ const { mergeDeviceRevocations, listDeviceRevocations } = await import("./paired-devices");81+ const record = { deviceId: "victim", longTermPublicKeyHex: "a".repeat(64), revokedAt: 1, revokedByDeviceId: "unknown", ...(signed ? { signatureHex: "1".repeat(128) } : {}) };82+ await mergeDeviceRevocations([record]);83+ await expect(adapter.buildOutgoingDeviceManifest?.()).rejects.toThrow("revocation_issuer_unverifiable");84+ expect(await listDeviceRevocations()).toEqual([record]);85+ });86+87+ it("forwards original revocations after issuer removal to a previously acquainted offline peer", async () => {88+ const { adapter } = await setupVault();89+ const { buildSignedDeviceManifest, signDeviceRevocation } = await import("../shared/device-manifest");90+ const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");91+ const { pubkeyToHex } = await import("../shared/sync-identity");92+ const { getLocalPairingIdentity, rotateDeviceId, buildLocalIdentity } = await import("./device-identity");93+ const { upsertPairedDevice, listDeviceRevocations, findPairedDeviceById, REGISTRY_KEY, REVOCATIONS_KEY, REVOCATION_ISSUERS_KEY } = await import("./paired-devices");94+ const a = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x61), "A");95+ const b = await getLocalPairingIdentity();96+ const aRow = { deviceId: "A", deviceName: "A", deviceType: "android" as const, longTermPublicKeyHex: "a".repeat(64), signingPublicKeyHex: pubkeyToHex(a.publicKeyRaw), trustSource: "direct" as const, pairedAt: 1 };97+ const bRow = { deviceId: b.identity.deviceId, deviceName: "B", deviceType: "extension" as const, longTermPublicKeyHex: pubkeyToHex(b.publicKey), signingPublicKeyHex: b.identity.signingPublicKeyHex, trustSource: "direct" as const, pairedAt: 1 };98+ await upsertPairedDevice(aRow);99+ const ac = await signDeviceRevocation({ deviceId: "C", longTermPublicKeyHex: "c".repeat(64), revokedAt: 1, revokedByDeviceId: "A" }, a.privateKey);100+ await adapter.applyIncomingDeviceManifest?.(await buildSignedDeviceManifest("A", [], a.privateKey, { revoked: [ac] }), new Uint8Array(32).fill(0xaa));101+ const { revokeDeviceById } = await import("./paired-devices");102+ await revokeDeviceById("A", b.identity.deviceId);103+ const forwarded = await adapter.buildOutgoingDeviceManifest?.();104+ expect(forwarded?.body.revoked.find((record) => record.deviceId === "C")).toEqual(ac);105+ await rotateDeviceId();106+ const d = await buildLocalIdentity();107+ expect(d.deviceId).not.toBe(b.identity.deviceId);108+ expect(d.signingPublicKeyHex).not.toBe(b.identity.signingPublicKeyHex);109+ // D knew A and B before going offline.110+ local[REGISTRY_KEY] = [aRow, bRow];111+ delete local[REVOCATIONS_KEY];112+ delete local[REVOCATION_ISSUERS_KEY];113+ await adapter.applyIncomingDeviceManifest?.(forwarded!, b.publicKey);114+ expect((await listDeviceRevocations()).map((record) => record.deviceId).sort()).toEqual(["A", "C"]);115+ expect(await findPairedDeviceById("A")).toBeNull();116+ // Once A is removed, its archive cannot admit A's outer manifest.117+ const ae = await signDeviceRevocation({ deviceId: "E", longTermPublicKeyHex: "e".repeat(64), revokedAt: 1, revokedByDeviceId: "A" }, a.privateKey);118+ await adapter.applyIncomingDeviceManifest?.(await buildSignedDeviceManifest("A", [], a.privateKey, { revoked: [ae] }), new Uint8Array(32).fill(0xaa));119+ expect((await listDeviceRevocations()).some((record) => record.deviceId === "E")).toBe(false);120+ // Previously archived A authorises only its record when B forwards it.121+ await adapter.applyIncomingDeviceManifest?.(await buildSignedDeviceManifest(b.identity.deviceId, [], b.signingPrivateKey, { revoked: [ae] }), b.publicKey);122+ expect((await listDeviceRevocations()).some((record) => record.deviceId === "E")).toBe(true);123+ // A newly joined member has never known A and must refuse the whole manifest.124+ local[REGISTRY_KEY] = [bRow];125+ delete local[REVOCATION_ISSUERS_KEY];126+ local[REVOCATIONS_KEY] = [];127+ await adapter.applyIncomingDeviceManifest?.(forwarded!, b.publicKey);128+ expect(await listDeviceRevocations()).toEqual([]);129+ b.privateKey.fill(0);130+ b.publicKey.fill(0);131+ });132+133+ it("rejects a known issuer's bad signature without merging other records", async () => {134+ const { adapter } = await setupVault();135+ const { buildSignedDeviceManifest, signDeviceRevocation } = await import("../shared/device-manifest");136+ const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");137+ const { pubkeyToHex } = await import("../shared/sync-identity");138+ const { upsertPairedDevice, listDeviceRevocations, mergeDeviceRevocations } = await import("./paired-devices");139+ const issuer = await deriveSyncSigningKeypair(new Uint8Array(32).fill(1), "known");140+ await upsertPairedDevice({ deviceId: "known", deviceName: "Known", deviceType: "android", longTermPublicKeyHex: "a".repeat(64), signingPublicKeyHex: pubkeyToHex(issuer.publicKeyRaw), trustSource: "direct", pairedAt: 1 });141+ const valid = await signDeviceRevocation({ deviceId: "valid-victim", longTermPublicKeyHex: "b".repeat(64), revokedAt: 1, revokedByDeviceId: "known" }, issuer.privateKey);142+ const invalid = { ...valid, deviceId: "tampered-victim" };143+ await adapter.applyIncomingDeviceManifest?.(await buildSignedDeviceManifest("known", [], issuer.privateKey, { revoked: [valid, invalid] }), new Uint8Array(32).fill(0xaa));144+ expect(await listDeviceRevocations()).toEqual([]);145+ await mergeDeviceRevocations([invalid]);146+ await expect(adapter.buildOutgoingDeviceManifest?.()).rejects.toThrow("revocation_issuer_unverifiable");147+ });148+149+ it("keeps old-self revocations verifiable through adoption identity rotation", async () => {150+ const { adapter } = await setupVault();151+ const identity = await import("./device-identity");152+ const paired = await import("./paired-devices");153+ const before = await identity.buildLocalIdentity();154+ await paired.revokeDeviceById("removed", before.deviceId);155+ await paired.rotatePairedDeviceIdentity(() => identity.getLocalPairingIdentity({ existingOnly: true }), identity.rotateDeviceId);156+ expect((await identity.buildLocalIdentity()).deviceId).not.toBe(before.deviceId);157+ const records = await paired.listDeviceRevocations();158+ expect(records[0].signatureHex).toBeDefined();159+ const manifest = await adapter.buildOutgoingDeviceManifest?.();160+ expect(manifest?.body.revoked).toEqual(records);161+ });162+62163 it("computeVaultId returns a stable 64-char hex string for the same masterKey", async () => {63164 const { adapter } = await setupVault();64165 const id1 = await adapter.computeVaultId();src/background/sync-vault-adapter.ts+31 −65
@@ -24,7 +24,7 @@2424 2525 import { HKDF } from "@stablelib/hkdf";2626 import { SHA256 } from "@stablelib/sha256";27-import type { DeviceManifestBody, DeviceRevocation } from "../shared/sync-types";27+import type { DeviceManifestBody } from "../shared/sync-types";2828 import type { SyncVaultAdapter } from "./sync-coordinator";2929 import { getDeviceName, getLocalPairingIdentity, getOrCreateDeviceId } from "./device-identity";3030 import {@@ -57,6 +57,7 @@5757 isDeviceRevoked,5858 listDeviceRevocations,5959 listPairedDevices,60+ listRevocationIssuerKeyMap,6061 upsertPairedDevicesAndMergeRevocations,6162 } from "./paired-devices";6263 import { setPairSecret } from "./pair-secrets";@@ -191,6 +192,7 @@191192 .filter((d) => !revokedIds.has(d.deviceId))192193 .map(toManifestEntry)193194 .filter((d): d is ManifestDeviceEntry => d !== null);195+ const issuerKeys = await revocationIssuerKeys(local.identity);194196 const signedRevoked = (195197 await Promise.all(revoked.map(async (record) => {196198 if (record.signatureHex) {@@ -198,21 +200,17 @@198200 // and is re-emitted only when one of its own issuer's trusted keys199201 // verifies it. The record names no key of its own, so the issuer200202 // is resolved here and nowhere else.201- const issuer = await findPairedDeviceById(record.revokedByDeviceId);202- for (const key of trustedSigningKeys(issuer)) {203- if (await verifyDeviceRevocation(record, hexToPubkey(key.publicKeyHex))) return record;203+ for (const key of issuerKeys.get(record.revokedByDeviceId) ?? []) {204+ if (await verifyDeviceRevocation(record, hexToPubkey(key))) return record;204205 }205- // Unverifiable — typically signed under a superseded canonical —206- // is dropped from the manifest rather than poisoning every207- // receiver. The local terminal revocation itself is retained.208- return null;206+ throw new Error("revocation_issuer_unverifiable");209207 }210208 // Only this device may mint a new signature; never re-issue a211209 // record attributed to a different issuer as our own.212- if (record.revokedByDeviceId !== issuerDeviceId) return null;210+ if (record.revokedByDeviceId !== issuerDeviceId) throw new Error("revocation_issuer_unverifiable");213211 return signDeviceRevocation(record, local.signingPrivateKey);214212 }))215- ).filter((record): record is DeviceRevocation => record !== null);213+ );216214 return buildSignedDeviceManifest(217215 issuerDeviceId,218216 devices,@@ -312,42 +310,11 @@312310 };313311 }314312 315-/**316- * Every signing key we currently trust for a peer: its immutable history plus317- * its active key. A forwarded revocation is authorised only by one of these,318- * resolved from `revokedByDeviceId`. The record carries no key of its own, so a319- * peer that merely relays a manifest cannot authorise a revocation.320- */321-function trustedSigningKeys(322- device:323- | {324- signingPublicKeyHex?: string;325- signingKeyHistory?: Array<{ version: number; publicKeyHex: string }>;326- }327- | null328- | undefined,329-): Array<{ version: number; publicKeyHex: string }> {330- const historical = (device?.signingKeyHistory ?? [])331- .filter(332- (key) =>333- Number.isInteger(key.version) &&334- key.version > 0 &&335- /^[0-9a-f]{64}$/i.test(key.publicKeyHex),336- )337- .map((key) => ({ version: key.version, publicKeyHex: key.publicKeyHex.toLowerCase() }));338- const current = device?.signingPublicKeyHex?.toLowerCase();339- if (!current || !/^[0-9a-f]{64}$/.test(current)) return historical;340- const currentVersion =341- historical.find((key) => key.publicKeyHex === current)?.version ??342- historical.reduce((max, key) => Math.max(max, key.version), 0) + 1;343- const all = [...historical, { version: currentVersion, publicKeyHex: current }];344- return all.filter(345- (key, index) =>346- all.findIndex(347- (candidate) =>348- candidate.version === key.version && candidate.publicKeyHex === key.publicKeyHex,349- ) === index,350- );313+// Archived keys authorise individual records only; transport admission uses the live registry.314+async function revocationIssuerKeys(local: { deviceId: string; signingPublicKeyHex: string }): Promise<Map<string, string[]>> {315+ const keys = await listRevocationIssuerKeyMap();316+ keys.set(local.deviceId, [...new Set([...(keys.get(local.deviceId) ?? []), local.signingPublicKeyHex])]);317+ return keys;351318 }352319 353320 /**@@ -423,28 +390,27 @@423390 // Fail closed: an unresolvable or unverifiable issuer rejects the whole424391 // manifest rather than dropping just that record, so a pruned history entry425392 // can never silently un-revoke a device. Android enforces the same rule.426- const allRevocationsAuthorised = (427- await Promise.all(428- body.revoked.map(async (record) => {429- // The outer manifest is authenticated by the directly connected430- // forwarder, but a forwarded revocation retains its original issuer.431- // Resolve that issuer independently from our paired registry and432- // immutable signing-key history; never bind it to the forwarder's key.433- const originalIssuer = await findPairedDeviceById(record.revokedByDeviceId);434- for (const key of trustedSigningKeys(originalIssuer)) {435- if (await verifyDeviceRevocation(record, hexToPubkey(key.publicKeyHex))) return true;436- }437- return false;438- }),439- )440- ).every(Boolean);441- if (!allRevocationsAuthorised) return;442-443- const ourDeviceId = await getOrCreateDeviceId();444- const masterKey = requireMasterKey();445393 const localPairing = await getLocalPairingIdentity();394+ const ourDeviceId = localPairing.identity.deviceId;395+ const masterKey = requireMasterKey();446396 const localKeys = { publicKey: localPairing.publicKey, secretKey: localPairing.privateKey };447397 try {398+ const issuerKeys = await revocationIssuerKeys(localPairing.identity);399+ const allRevocationsAuthorised = (400+ await Promise.all(401+ body.revoked.map(async (record) => {402+ // The outer manifest is authenticated by the directly connected403+ // forwarder, but a forwarded revocation retains its original issuer.404+ // Resolve the original issuer's retained keys independently of the forwarder.405+ for (const key of issuerKeys.get(record.revokedByDeviceId) ?? []) {406+ if (await verifyDeviceRevocation(record, hexToPubkey(key))) return true;407+ }408+ return false;409+ }),410+ )411+ ).every(Boolean);412+ if (!allRevocationsAuthorised) return;413+448414 const pendingRegistry: PairedDevice[] = [];449415 const pendingSecrets: { deviceId: string; secret: string }[] = [];450416 const pendingVouchedIds: string[] = [];src/background/vault.rotate-sync-identity.test.ts+20 −0
@@ -155,6 +155,26 @@155155 expect(isEmpty).toBe(true);156156 });157157 158+ it("preserves historical issuer verification through root rotation and re-pair", async () => {159+ const paired = await import("./paired-devices");160+ const identity = await import("./device-identity");161+ const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");162+ const { pubkeyToHex } = await import("../shared/sync-identity");163+ const { signDeviceRevocation } = await import("../shared/device-manifest");164+ await identity.getOrCreateDeviceId();165+ const signing = await deriveSyncSigningKeypair(new Uint8Array(32).fill(7), "old-issuer");166+ const peer = { deviceId: "old-issuer", deviceName: "Old", deviceType: "android" as const, longTermPublicKeyHex: "a".repeat(64), signingPublicKeyHex: pubkeyToHex(signing.publicKeyRaw), pairedAt: 1, trustSource: "direct" as const };167+ await paired.upsertPairedDevice(peer);168+ const record = await signDeviceRevocation({ deviceId: "removed", longTermPublicKeyHex: "b".repeat(64), revokedAt: 1, revokedByDeviceId: peer.deviceId }, signing.privateKey);169+ await paired.mergeDeviceRevocations([record]);170+ expect(await vault.rotateSyncIdentity()).toMatchObject({ ok: true });171+ expect(await paired.listPairedDevices()).toEqual([]);172+ expect(((await paired.listRevocationIssuerKeyMap()).get(peer.deviceId) ?? [])).toEqual([peer.signingPublicKeyHex]);173+ await paired.upsertPairedDevice({ ...peer, deviceId: "repaired-peer" });174+ const { createSyncVaultAdapter } = await import("./sync-vault-adapter");175+ expect((await createSyncVaultAdapter().buildOutgoingDeviceManifest?.())?.body.revoked).toEqual([record]);176+ });177+158178 // T-016d: the session-owned recovery-pending state is set after rotation.159179 // Rotation generates new 12 recovery words (derived from the new root key).160180 // The user MUST re-confirm these words before the old ones become the only