1import { beforeEach, describe, expect, it, vi } from "vitest";23type StorageShape = Record<string, unknown>;4const MESH_RELAY = "wss://relay.peachpasswords.com";56function makeChromeMock(local: StorageShape, sync: StorageShape): typeof chrome {7 const area = (store: StorageShape) => ({8 get: vi.fn(async (key?: string | string[]) => {9 if (!key) return store;10 if (typeof key === "string") return { [key]: store[key] };11 return key.reduce<Record<string, unknown>>((acc, k) => { acc[k] = store[k]; return acc; }, {});12 }),13 set: vi.fn(async (next: Record<string, unknown>) => { Object.assign(store, next); }),14 remove: vi.fn(async (keys: string | string[]) => {15 const list = Array.isArray(keys) ? keys : [keys];16 for (const k of list) delete store[k];17 }),18 });19 return {20 storage: { local: area(local), sync: area(sync) },21 alarms: {22 clear: vi.fn(),23 create: vi.fn(),24 onAlarm: { addListener: vi.fn() },25 },26 idle: { setDetectionInterval: vi.fn(), onStateChanged: { addListener: vi.fn() } },27 runtime: { sendMessage: vi.fn(async () => undefined) },28 } as unknown as typeof chrome;29}3031describe("SyncVaultAdapter", () => {32 let local: StorageShape;33 let sync: StorageShape;3435 beforeEach(() => {36 vi.resetModules();37 local = {};38 sync = {};39 (globalThis as { chrome?: typeof chrome }).chrome = makeChromeMock(local, sync);40 vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("network disabled"); }));41 });4243 async function setupVault(): Promise<{ vault: typeof import("./vault"); adapter: import("./sync-coordinator").SyncVaultAdapter }> {44 const vault = await import("./vault");45 await vault.createVault("correct horse battery staple");46 const { createSyncVaultAdapter } = await import("./sync-vault-adapter");47 const adapter = createSyncVaultAdapter();48 return { vault, adapter };49 }5051 async function signingPubkeyHex(deviceId: string): Promise<string> {52 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");53 const kp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x42), deviceId);54 return pubkeyToHex(kp.publicKeyRaw);55 }5657 it("computeVaultId returns a stable 64-char hex string for the same masterKey", async () => {58 const { adapter } = await setupVault();59 const id1 = await adapter.computeVaultId();60 const id2 = await adapter.computeVaultId();61 expect(id1).toBe(id2);62 expect(id1).toMatch(/^[0-9a-f]{64}$/);63 });6465 it("vault_id and sync signing key are unchanged after a password change (SEV-2-B)", async () => {66 const { vault, adapter } = await setupVault();67 const deviceId = await adapter.getOurDeviceId();68 const vaultIdBefore = await adapter.computeVaultId();6970 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");71 const rootBefore = vault.getRootKeyHex()!;72 const unhex = (h: string) => Uint8Array.from(h.match(/../g)!.map((b) => parseInt(b, 16)));73 const signBefore = pubkeyToHex(74 (await deriveSyncSigningKeypair(unhex(rootBefore), deviceId)).publicKeyRaw,75 );7677 expect(await vault.changePassword("correct horse battery staple", "a different passphrase")).toBe(true);78 vault.lock();79 expect(await vault.unlock("a different passphrase")).toBe(true);8081 82 expect(await adapter.computeVaultId()).toBe(vaultIdBefore);83 const rootAfter = vault.getRootKeyHex()!;84 expect(rootAfter).toBe(rootBefore);85 const signAfter = pubkeyToHex(86 (await deriveSyncSigningKeypair(unhex(rootAfter), deviceId)).publicKeyRaw,87 );88 expect(signAfter).toBe(signBefore);89 });9091 it("getOurDeviceId is stable across calls and a fresh UUID v4 on first call", async () => {92 const { adapter } = await setupVault();93 const id1 = await adapter.getOurDeviceId();94 const id2 = await adapter.getOurDeviceId();95 expect(id1).toBe(id2);96 expect(id1).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);97 });9899 it("buildEntryManifest reports {id: modifiedAt} for live entries only", async () => {100 const { vault, adapter } = await setupVault();101 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });102 const b = await vault.addEntry({ type: "login", title: "Beta", password: "pw" });103 await vault.deleteEntry(b.id);104 const m = await adapter.buildEntryManifest();105 expect(Object.keys(m).sort()).toEqual([a.id]);106 expect(m[a.id]).toBe(a.modifiedAt);107 });108109 it("buildTombstoneManifest reports {id: deletedAt} for soft-deleted entries", async () => {110 const { vault, adapter } = await setupVault();111 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });112 await vault.deleteEntry(a.id);113 const t = await adapter.buildTombstoneManifest();114 expect(Object.keys(t)).toEqual([a.id]);115 expect(typeof t[a.id]).toBe("number");116 expect(t[a.id]).toBeGreaterThan(0);117 });118119 it("buildTombstoneManifest retains ids after a full-entry purge", async () => {120 const { vault, adapter } = await setupVault();121 const entry = await vault.addEntry({ type: "login", title: "Purged", password: "pw" });122 await vault.deleteEntry(entry.id);123 const deletedAt = vault.getDeletedEntries().find((item) => item.id === entry.id)!.deletedAt!;124125 await vault.purgeEntry(entry.id);126127 expect(await adapter.buildTombstoneManifest()).toEqual({ [entry.id]: deletedAt });128 });129130 it("getEncryptedEntries returns opaque base64 strings keyed by id", async () => {131 const { vault, adapter } = await setupVault();132 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });133 const env = await adapter.getEncryptedEntries([a.id]);134 expect(Object.keys(env)).toEqual([a.id]);135 expect(env[a.id]).toMatch(/^[A-Za-z0-9+/]+=*$/);136 137 expect(env[a.id]).not.toContain("Alpha");138 });139140 it("getEncryptedEntries silently skips unknown ids (peer may have a manifest item we dropped)", async () => {141 const { adapter } = await setupVault();142 const env = await adapter.getEncryptedEntries(["does-not-exist"]);143 expect(env).toEqual({});144 });145146 it("encryption uses a fresh nonce per call — same entry yields different envelopes", async () => {147 const { vault, adapter } = await setupVault();148 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });149 const e1 = await adapter.getEncryptedEntries([a.id]);150 const e2 = await adapter.getEncryptedEntries([a.id]);151 expect(e1[a.id]).not.toBe(e2[a.id]);152 });153154 it("round-trips: encrypt on one adapter, apply on a fresh import of the same vault", async () => {155 const { vault, adapter } = await setupVault();156 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "secret", url: "https://a.example" });157 const envelopes = await adapter.getEncryptedEntries([a.id]);158 159 160 161 162 163 164 165 vault.lock();166 await vault.unlock("correct horse battery staple");167 const { createSyncVaultAdapter } = await import("./sync-vault-adapter");168 const adapter2 = createSyncVaultAdapter();169 170 await adapter2.applyEntries(envelopes);171 expect(vault.getEntries().find((e) => e.id === a.id)?.title).toBe("Alpha");172 });173174 it("applyEntries decrypts and merges newer remote entries (last-write-wins)", async () => {175 const { vault, adapter } = await setupVault();176 const local = await vault.addEntry({ type: "login", title: "Original", password: "pw" });177 178 179 180 await vault.updateEntry(local.id, { title: "Updated" });181 const newer = vault.getEntries().find((e) => e.id === local.id);182 expect(newer?.title).toBe("Updated");183 const envelopes = await adapter.getEncryptedEntries([local.id]);184 185 186 187 188 189 190 const older: typeof local = { ...local, modifiedAt: local.modifiedAt - 1000, title: "Stale" };191 await vault.restoreEntries([older], "replace");192 expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Stale");193 await adapter.applyEntries(envelopes);194 expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Updated");195 });196197 it("applyEntries rejects envelopes whose decrypted id differs from the map key", async () => {198 const { vault, adapter } = await setupVault();199 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });200 const env = await adapter.getEncryptedEntries([a.id]);201 202 const swapped: Record<string, string> = { "wrong-id": env[a.id] };203 await adapter.applyEntries(swapped);204 205 expect(vault.getEntries().map((e) => e.id)).toEqual([a.id]);206 });207208 it("entry_envelope_roundtrips_with_separated_info (HKDF separator)", async () => {209 const { vault, adapter } = await setupVault();210 const a = await vault.addEntry({ type: "login", title: "Original", password: "pw" });211 await vault.updateEntry(a.id, { title: "Fresh" });212 const envelopes = await adapter.getEncryptedEntries([a.id]);213 214 215 const stale = { ...a, modifiedAt: a.modifiedAt - 1000, title: "Stale" };216 await vault.restoreEntries([stale], "replace");217 await adapter.applyEntries(envelopes);218 expect(vault.getEntries().find((e) => e.id === a.id)?.title).toBe("Fresh");219 });220221 it("legacy_info_envelope_fails_closed (HKDF separator wire break)", async () => {222 223 224 225 const { vault, adapter } = await setupVault();226 const { HKDF } = await import("@stablelib/hkdf");227 const { SHA256 } = await import("@stablelib/sha256");228229 const masterHex = vault.getRootKeyHex()!;230 const masterKey = Uint8Array.from(masterHex.match(/../g)!.map((b) => parseInt(b, 16)));231 const entryId = crypto.randomUUID();232 const legacyInfo = new TextEncoder().encode(entryId + "sync-entry-v1"); 233 const raw = new HKDF(SHA256, masterKey, new Uint8Array(0), legacyInfo).expand(32);234 const key = await crypto.subtle.importKey("raw", raw.buffer as ArrayBuffer, { name: "AES-GCM" }, false, ["encrypt"]);235236 const entry = { id: entryId, type: "login", title: "LegacyOnly", password: "pw", createdAt: Date.now(), modifiedAt: Date.now() };237 const nonce = crypto.getRandomValues(new Uint8Array(12));238 const aad = new TextEncoder().encode("peach-sync-entry-v1");239 const ct = new Uint8Array(240 await crypto.subtle.encrypt(241 { name: "AES-GCM", iv: nonce.buffer as ArrayBuffer, additionalData: aad.buffer as ArrayBuffer, tagLength: 128 },242 key,243 new TextEncoder().encode(JSON.stringify(entry)).buffer as ArrayBuffer,244 ),245 );246 const envelope = new Uint8Array(nonce.length + ct.length);247 envelope.set(nonce, 0);248 envelope.set(ct, nonce.length);249 const legacyB64 = Buffer.from(envelope).toString("base64");250251 await adapter.applyEntries({ [entryId]: legacyB64 });252 253 expect(vault.getEntries().some((e) => e.id === entryId)).toBe(false);254 });255256 it("applyTombstones soft-deletes locally-live entries with newer deletedAt", async () => {257 const { vault, adapter } = await setupVault();258 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });259 await adapter.applyTombstones({ [a.id]: a.modifiedAt + 10_000 });260 expect(vault.getEntries().find((e) => e.id === a.id)).toBeUndefined();261 expect(vault.getDeletedEntries().find((e) => e.id === a.id)).toBeDefined();262 });263264 it("applyTombstones leaves entries alone when local modifiedAt is newer", async () => {265 const { vault, adapter } = await setupVault();266 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });267 await adapter.applyTombstones({ [a.id]: a.modifiedAt - 10_000 });268 expect(vault.getEntries().find((e) => e.id === a.id)).toBeDefined();269 });270271 272273 it("MV-3: applyEntries throws when the batch exceeds MAX_ENTRY_COUNT", async () => {274 const { adapter } = await setupVault();275 const { SYNC_LIMITS } = await import("../shared/sync-limits");276 const tooMany: Record<string, string> = {};277 for (let i = 0; i <= SYNC_LIMITS.MAX_ENTRY_COUNT; i++) tooMany[`id-${i}`] = "AAAA";278 await expect(adapter.applyEntries(tooMany)).rejects.toThrow(/exceeds limit/);279 });280281 it("MV-3: applyEntries skips an oversized envelope but still applies valid ones", async () => {282 const { vault, adapter } = await setupVault();283 const { SYNC_LIMITS } = await import("../shared/sync-limits");284 const local = await vault.addEntry({ type: "login", title: "Original", password: "pw" });285 await vault.updateEntry(local.id, { title: "Updated" });286 const envelopes = await adapter.getEncryptedEntries([local.id]);287 288 const older = { ...local, modifiedAt: local.modifiedAt - 1000, title: "Stale" };289 await vault.restoreEntries([older], "replace");290 expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Stale");291292 const oversized = "A".repeat(293 Math.ceil((SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES * 4) / 3) + 128,294 );295 await adapter.applyEntries({ ...envelopes, "oversized-id": oversized });296297 298 expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Updated");299 expect(vault.getEntries().some((e) => e.id === "oversized-id")).toBe(false);300 });301302 it("MV-3: applyTombstones throws when the batch exceeds MAX_TOMBSTONE_COUNT", async () => {303 const { adapter } = await setupVault();304 const { SYNC_LIMITS } = await import("../shared/sync-limits");305 const tooMany: Record<string, number> = {};306 for (let i = 0; i <= SYNC_LIMITS.MAX_TOMBSTONE_COUNT; i++) tooMany[`id-${i}`] = i + 1;307 await expect(adapter.applyTombstones(tooMany)).rejects.toThrow(/exceeds limit/);308 });309310 it("buildOutgoingDeviceManifest signs manifestable paired devices and skips legacy entries without signing keys", async () => {311 const { adapter } = await setupVault();312 const { upsertPairedDevice } = await import("./paired-devices");313 await upsertPairedDevice({314 deviceId: "android-1",315 deviceName: "Pixel",316 deviceType: "android",317 longTermPublicKeyHex: "a".repeat(64),318 signingPublicKeyHex: await signingPubkeyHex("android-1"),319 wsPort: 49152,320 relayUrl: MESH_RELAY,321 pairedAt: 1_700_000_000_000,322 trustSource: "direct",323 });324 await upsertPairedDevice({325 deviceId: "legacy-android",326 deviceName: "Legacy Pixel",327 deviceType: "android",328 longTermPublicKeyHex: "b".repeat(64),329 pairedAt: 1_700_000_000_100,330 trustSource: "direct",331 });332333 const manifest = await adapter.buildOutgoingDeviceManifest?.();334 expect(manifest).toBeDefined();335 expect(manifest?.signatureHex).toMatch(/^[0-9a-f]{128}$/);336 expect(manifest?.body.devices).toHaveLength(1);337 expect(manifest?.body.devices[0]).toMatchObject({338 deviceId: "android-1",339 deviceName: "Pixel",340 deviceType: "android",341 longTermPublicKeyHex: "a".repeat(64),342 wsPort: 49152,343 relayUrl: MESH_RELAY,344 });345 });346347 it("v3 auto-admits same-vault manifest peers with an independent mesh route", async () => {348 const { vault, adapter } = await setupVault();349 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");350 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");351 const {352 findPairedDeviceById,353 listPairedDevices,354 upsertPairedDevice,355 } = await import("./paired-devices");356 const { listPendingVouchedDevices } = await import(357 "./pending-vouched-devices"358 );359360 const issuerId = "extension-issuer";361 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x24), issuerId);362 await upsertPairedDevice({363 deviceId: issuerId,364 deviceName: "Firefox",365 deviceType: "extension",366 longTermPublicKeyHex: "c".repeat(64),367 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),368 pairedAt: 1_700_000_000_000,369 trustSource: "direct",370 });371 await upsertPairedDevice({372 deviceId: "android-existing",373 deviceName: "Existing Pixel",374 deviceType: "android",375 longTermPublicKeyHex: "d".repeat(64),376 signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),377 pairedAt: 1_700_000_000_010,378 trustSource: "direct",379 });380381 const manifest = await buildSignedDeviceManifest(382 issuerId,383 [384 {385 deviceId: "android-new",386 deviceName: "New Pixel",387 deviceType: "android",388 longTermPublicKeyHex: "e".repeat(64),389 signingPublicKeyHex: await signingPubkeyHex("android-new"),390 wsPort: 51234,391 relayUrl: MESH_RELAY,392 pairedAt: 1_700_000_000_020,393 },394 {395 deviceId: "android-existing",396 deviceName: "Existing Pixel renamed",397 deviceType: "android",398 longTermPublicKeyHex: "d".repeat(64),399 signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),400 wsPort: 52345,401 relayUrl: MESH_RELAY,402 pairedAt: 1_700_000_000_030,403 },404 ],405 issuerKp.privateKey,406 );407408 await adapter.applyIncomingDeviceManifest?.(409 manifest,410 new Uint8Array(32).fill(0xcc),411 );412413 expect(await findPairedDeviceById("android-new")).toMatchObject({414 deviceName: "New Pixel",415 trustSource: "vouched",416 relayUrl: MESH_RELAY,417 });418 419 420 expect((await findPairedDeviceById("android-new"))?.rendezvousSecretHex).toBeUndefined();421 const { getPairSecret } = await import("./pair-secrets");422 await expect(getPairSecret("android-new", vault.getRootKeyHex())).resolves.toMatch(423 /^[0-9a-f]{64}$/,424 );425 const pending = await listPendingVouchedDevices();426 expect(pending).toEqual([]);427428 429 430 const existing = await findPairedDeviceById("android-existing");431 expect(existing).toMatchObject({432 deviceName: "Existing Pixel",433 longTermPublicKeyHex: "d".repeat(64),434 trustSource: "direct",435 wsPort: 52345,436 });437 expect((await listPairedDevices()).map((d) => d.deviceId).sort()).toEqual([438 "android-existing",439 "android-new",440 "extension-issuer",441 ]);442 });443444 it("rejects manifest key replacement for an existing device", async () => {445 const { adapter } = await setupVault();446 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");447 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");448 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");449 const issuerId = "extension-issuer";450 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x24), issuerId);451 await upsertPairedDevice({452 deviceId: issuerId,453 deviceName: "Firefox",454 deviceType: "extension",455 longTermPublicKeyHex: "c".repeat(64),456 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),457 pairedAt: 1,458 trustSource: "direct",459 });460 await upsertPairedDevice({461 deviceId: "android-existing",462 deviceName: "Pixel",463 deviceType: "android",464 longTermPublicKeyHex: "d".repeat(64),465 signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),466 pairedAt: 2,467 trustSource: "direct",468 });469 const manifest = await buildSignedDeviceManifest(470 issuerId,471 [{472 deviceId: "android-existing",473 deviceName: "Pixel",474 deviceType: "android",475 longTermPublicKeyHex: "f".repeat(64),476 signingPublicKeyHex: await signingPubkeyHex("android-existing-new"),477 wsPort: 52345,478 pairedAt: 3,479 }],480 issuerKp.privateKey,481 );482 await expect(483 adapter.applyIncomingDeviceManifest?.(manifest, new Uint8Array(32).fill(0xcc)),484 ).rejects.toThrow("device_identity_immutable");485 await expect(findPairedDeviceById("android-existing")).resolves.toMatchObject({486 longTermPublicKeyHex: "d".repeat(64),487 });488 });489490 it("rejects manifest replacement even when the device name changes", async () => {491 const { adapter } = await setupVault();492 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");493 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");494 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");495 const issuerId = "hostile-issuer";496 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x26), issuerId);497 await upsertPairedDevice({498 deviceId: issuerId,499 deviceName: "Old Laptop",500 deviceType: "extension",501 longTermPublicKeyHex: "c".repeat(64),502 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),503 pairedAt: 1,504 trustSource: "direct",505 });506 await upsertPairedDevice({507 deviceId: "android-existing",508 deviceName: "Spare Tablet",509 deviceType: "android",510 longTermPublicKeyHex: "d".repeat(64),511 signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),512 pairedAt: 2,513 trustSource: "direct",514 });515 const manifest = await buildSignedDeviceManifest(516 issuerId,517 [{518 deviceId: "android-existing",519 deviceName: "June's Primary Phone",520 deviceType: "android",521 longTermPublicKeyHex: "f".repeat(64),522 signingPublicKeyHex: await signingPubkeyHex("android-existing-new"),523 wsPort: 52345,524 pairedAt: 3,525 }],526 issuerKp.privateKey,527 );528 await expect(529 adapter.applyIncomingDeviceManifest?.(manifest, new Uint8Array(32).fill(0xcc)),530 ).rejects.toThrow("device_identity_immutable");531 await expect(findPairedDeviceById("android-existing")).resolves.toMatchObject({532 deviceName: "Spare Tablet",533 longTermPublicKeyHex: "d".repeat(64),534 });535 });536537 it("§C: a vouched peer's revocation evicts the device and permanently blocks re-vouching", async () => {538 const { adapter } = await setupVault();539 const { buildSignedDeviceManifest, signDeviceRevocation } = await import("../shared/device-manifest");540 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");541 const { findPairedDeviceById, isDeviceRevoked, upsertPairedDevice } =542 await import("./paired-devices");543544 const issuerId = "phone-issuer";545 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x27), issuerId);546 await upsertPairedDevice({547 deviceId: issuerId,548 deviceName: "Pixel",549 deviceType: "android",550 longTermPublicKeyHex: "c".repeat(64),551 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),552 pairedAt: 1,553 trustSource: "vouched",554 });555 await upsertPairedDevice({556 deviceId: "stolen-laptop",557 deviceName: "Old Laptop",558 deviceType: "extension",559 longTermPublicKeyHex: "d".repeat(64),560 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),561 pairedAt: 2,562 trustSource: "direct",563 });564565 const issuerSigningPublicKeyHex = pubkeyToHex(issuerKp.publicKeyRaw);566 const signedRevocation = await signDeviceRevocation(567 {568 deviceId: "stolen-laptop",569 longTermPublicKeyHex: "d".repeat(64),570 revokedAt: Date.now(),571 revokedByDeviceId: issuerId,572 },573 issuerKp.privateKey,574 issuerSigningPublicKeyHex,575 );576 const revocation = await buildSignedDeviceManifest(577 issuerId,578 [],579 issuerKp.privateKey,580 { revoked: [signedRevocation] },581 );582 await adapter.applyIncomingDeviceManifest?.(583 revocation,584 new Uint8Array(32).fill(0xcc),585 );586587 expect(await findPairedDeviceById("stolen-laptop")).toBeNull();588 expect(await isDeviceRevoked("stolen-laptop")).toBe(true);589590 591 592 593 const revouch = await buildSignedDeviceManifest(594 issuerId,595 [596 {597 deviceId: "stolen-laptop",598 deviceName: "Old Laptop",599 deviceType: "extension",600 longTermPublicKeyHex: "d".repeat(64),601 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),602 pairedAt: Date.now() + 60_000,603 },604 ],605 issuerKp.privateKey,606 );607 await adapter.applyIncomingDeviceManifest?.(608 revouch,609 new Uint8Array(32).fill(0xcc),610 );611612 expect(await findPairedDeviceById("stolen-laptop")).toBeNull();613 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");614 expect(await listPendingVouchedDevices()).toHaveLength(0);615 });616617 it("§C: a peer cannot revoke US, and our outgoing manifest carries our revocations", async () => {618 const { adapter } = await setupVault();619 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");620 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");621 const {622 isDeviceRevoked,623 revokeDeviceById,624 upsertPairedDevice,625 } = await import("./paired-devices");626 const { getOrCreateDeviceId } = await import("./device-identity");627628 const ourDeviceId = await getOrCreateDeviceId();629 const issuerId = "phone-issuer";630 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x28), issuerId);631 await upsertPairedDevice({632 deviceId: issuerId,633 deviceName: "Pixel",634 deviceType: "android",635 longTermPublicKeyHex: "c".repeat(64),636 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),637 pairedAt: 1,638 trustSource: "direct",639 });640641 642 const selfRevoke = await buildSignedDeviceManifest(643 issuerId,644 [],645 issuerKp.privateKey,646 {647 revoked: [648 {649 deviceId: ourDeviceId,650 longTermPublicKeyHex: "e".repeat(64),651 revokedAt: Date.now(),652 revokedByDeviceId: issuerId,653 },654 ],655 },656 );657 await adapter.applyIncomingDeviceManifest?.(658 selfRevoke,659 new Uint8Array(32).fill(0xcc),660 );661 expect(await isDeviceRevoked(ourDeviceId)).toBe(false);662663 664 665 await upsertPairedDevice({666 deviceId: "retired-tablet",667 deviceName: "Retired Tablet",668 deviceType: "android",669 longTermPublicKeyHex: "f".repeat(64),670 signingPublicKeyHex: await signingPubkeyHex("retired-tablet"),671 pairedAt: 3,672 trustSource: "direct",673 });674 await revokeDeviceById("retired-tablet", ourDeviceId);675676 const outgoing = await adapter.buildOutgoingDeviceManifest?.();677 expect(outgoing?.body.revoked.map((r) => r.deviceId)).toEqual(["retired-tablet"]);678 expect(outgoing?.body.devices.map((d) => d.deviceId)).not.toContain("retired-tablet");679 });680681 682 683 684 685 686 it("a legacy row with no trustSource is not upgraded to direct by a manifest apply", async () => {687 const { adapter } = await setupVault();688 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");689 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");690 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");691 const { isRouteCapableMeshPeer } = await import("../shared/mesh-peer-role");692693 const issuerId = "android-legacy-issuer";694 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x25), issuerId);695 await upsertPairedDevice({696 deviceId: issuerId,697 deviceName: "Issuer Pixel",698 deviceType: "android",699 longTermPublicKeyHex: "1".repeat(64),700 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),701 pairedAt: 1_700_000_000_000,702 trustSource: "direct",703 });704705 706 707 const legacyId = "legacy-peer";708 const registry = local.peach_paired_devices_v3 as Array<Record<string, unknown>>;709 registry.push({710 deviceId: legacyId,711 deviceName: "Legacy Peer",712 deviceType: "android",713 longTermPublicKeyHex: "3".repeat(64),714 signingPublicKeyHex: await signingPubkeyHex(legacyId),715 rendezvousSecretHex: "9".repeat(64),716 relayUrl: MESH_RELAY,717 pairedAt: 1_700_000_000_000,718 });719720 const manifest = await buildSignedDeviceManifest(721 issuerId,722 [{723 deviceId: legacyId,724 deviceName: "Legacy Peer",725 deviceType: "android",726 longTermPublicKeyHex: "3".repeat(64),727 signingPublicKeyHex: await signingPubkeyHex(legacyId),728 relayUrl: MESH_RELAY,729 pairedAt: 1_700_000_000_000,730 }],731 issuerKp.privateKey,732 );733 await adapter.applyIncomingDeviceManifest?.(734 manifest,735 new Uint8Array(32).fill(0x11),736 );737738 const row = await findPairedDeviceById(legacyId);739 expect(row).not.toBeNull();740 741 expect(row?.trustSource).toBeUndefined();742 expect(row?.trustSource).not.toBe("direct");743 744 expect(isRouteCapableMeshPeer(row!)).toBe(false);745 });746747 it("accepts a manifest from the phone it paired with — mesh introduction runs in that direction", async () => {748 749 750 751 752 const { adapter } = await setupVault();753 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");754 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");755 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");756 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");757 const vault = await import("./vault");758759 const mobileIssuerId = "android-issuer";760 const mobileIssuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x25), mobileIssuerId);761 await upsertPairedDevice({762 deviceId: mobileIssuerId,763 deviceName: "Issuer Pixel",764 deviceType: "android",765 longTermPublicKeyHex: "1".repeat(64),766 signingPublicKeyHex: pubkeyToHex(mobileIssuerKp.publicKeyRaw),767 pairedAt: 1_700_000_000_000,768 trustSource: "direct",769 });770 const mobileManifest = await buildSignedDeviceManifest(771 mobileIssuerId,772 [{773 deviceId: "mesh-peer",774 deviceName: "Other Pixel",775 deviceType: "android",776 longTermPublicKeyHex: "2".repeat(64),777 signingPublicKeyHex: await signingPubkeyHex("mesh-peer"),778 relayUrl: MESH_RELAY,779 pairedAt: 1_700_000_000_010,780 }],781 mobileIssuerKp.privateKey,782 );783 await adapter.applyIncomingDeviceManifest?.(784 mobileManifest,785 new Uint8Array(32).fill(0x11),786 );787788 expect(await findPairedDeviceById("mesh-peer")).toMatchObject({789 trustSource: "vouched",790 relayUrl: MESH_RELAY,791 });792 expect((await findPairedDeviceById("mesh-peer"))?.rendezvousSecretHex).toBeUndefined();793 const { getPairSecret: getPairSecretMesh } = await import("./pair-secrets");794 await expect(getPairSecretMesh("mesh-peer", vault.getRootKeyHex())).resolves.toMatch(795 /^[0-9a-f]{64}$/,796 );797 expect(await listPendingVouchedDevices()).toEqual([]);798 });799800 it("applyIncomingDeviceManifest accepts vouched issuers but rejects unauthenticated and bad signatures", async () => {801 const { vault, adapter } = await setupVault();802 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");803 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");804 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");805 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");806807 808 809 810 const vouchedIssuerId = "android-vouched-issuer";811 const vouchedKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x25), vouchedIssuerId);812 await upsertPairedDevice({813 deviceId: vouchedIssuerId,814 deviceName: "Second-hand Pixel",815 deviceType: "android",816 longTermPublicKeyHex: "1".repeat(64),817 signingPublicKeyHex: pubkeyToHex(vouchedKp.publicKeyRaw),818 pairedAt: 1_700_000_000_000,819 trustSource: "vouched",820 });821 const onward = await buildSignedDeviceManifest(822 vouchedIssuerId,823 [{824 deviceId: "onward-mesh-peer",825 deviceName: "Other Pixel",826 deviceType: "android",827 longTermPublicKeyHex: "2".repeat(64),828 signingPublicKeyHex: await signingPubkeyHex("onward-mesh-peer"),829 relayUrl: MESH_RELAY,830 pairedAt: 1_700_000_000_010,831 }],832 vouchedKp.privateKey,833 );834 await adapter.applyIncomingDeviceManifest?.(835 onward,836 new Uint8Array(32).fill(0x11),837 );838 expect(await findPairedDeviceById("onward-mesh-peer")).toMatchObject({839 trustSource: "vouched",840 relayUrl: MESH_RELAY,841 });842 expect((await findPairedDeviceById("onward-mesh-peer"))?.rendezvousSecretHex).toBeUndefined();843 const { getPairSecret: getPairSecretOnward } = await import("./pair-secrets");844 await expect(getPairSecretOnward("onward-mesh-peer", vault.getRootKeyHex())).resolves.toMatch(845 /^[0-9a-f]{64}$/,846 );847 expect(await listPendingVouchedDevices()).toEqual([]);848849 const extensionIssuerId = "extension-bad-sig";850 const extensionKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x26), extensionIssuerId);851 await upsertPairedDevice({852 deviceId: extensionIssuerId,853 deviceName: "Chrome",854 deviceType: "extension",855 longTermPublicKeyHex: "3".repeat(64),856 signingPublicKeyHex: pubkeyToHex(extensionKp.publicKeyRaw),857 pairedAt: 1_700_000_000_020,858 trustSource: "direct",859 });860 const good = await buildSignedDeviceManifest(861 extensionIssuerId,862 [{863 deviceId: "forged-add",864 deviceName: "Forged Pixel",865 deviceType: "android",866 longTermPublicKeyHex: "4".repeat(64),867 signingPublicKeyHex: await signingPubkeyHex("forged-add"),868 pairedAt: 1_700_000_000_030,869 }],870 extensionKp.privateKey,871 );872 await adapter.applyIncomingDeviceManifest?.(873 good,874 new Uint8Array(32).fill(0x44),875 );876 expect(await findPairedDeviceById("forged-add")).toBeNull();877878 const forged = {879 ...good,880 signatureHex:881 good.signatureHex.slice(0, 2) +882 ((parseInt(good.signatureHex.slice(2, 4), 16) ^ 0xff).toString(16).padStart(2, "0")) +883 good.signatureHex.slice(4),884 };885 await adapter.applyIncomingDeviceManifest?.(886 forged,887 new Uint8Array(32).fill(0x33),888 );889 expect(await findPairedDeviceById("forged-add")).toBeNull();890 });891892 it("rejects a manifest when the stored issuer signing key is stale", async () => {893 const { vault, adapter } = await setupVault();894 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");895 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");896 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");897898 const issuerId = "stale-key-android";899 const rootHex = vault.getRootKeyHex()!;900 const root = Uint8Array.from(rootHex.match(/../g)!.map((b) => parseInt(b, 16)));901 const issuerKp = await deriveSyncSigningKeypair(root, issuerId);902903 await upsertPairedDevice({904 deviceId: issuerId,905 deviceName: "Pixel",906 deviceType: "android",907 longTermPublicKeyHex: "c".repeat(64),908 signingPublicKeyHex: "ff".repeat(32),909 pairedAt: 1_700_000_000_000,910 trustSource: "direct",911 });912913 const manifest = await buildSignedDeviceManifest(914 issuerId,915 [{916 deviceId: "onward-peer",917 deviceName: "Forwarded iPad",918 deviceType: "extension",919 longTermPublicKeyHex: "e".repeat(64),920 signingPublicKeyHex: pubkeyToHex(921 (await deriveSyncSigningKeypair(root, "onward-peer")).publicKeyRaw,922 ),923 relayUrl: MESH_RELAY,924 pairedAt: 1_700_000_000_010,925 }],926 issuerKp.privateKey,927 );928929 await adapter.applyIncomingDeviceManifest?.(manifest, new Uint8Array(32).fill(0xcc));930931 expect(await findPairedDeviceById("onward-peer")).toBeNull();932 });933934 it("S1: a manifest signed by one paired peer is refused over a session authenticated as another", async () => {935 const { adapter } = await setupVault();936 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");937 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");938 const { upsertPairedDevice } = await import("./paired-devices");939 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");940941 942 943 944 const alphaKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x51), "peer-alpha");945 const betaKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x52), "peer-beta");946 await upsertPairedDevice({947 deviceId: "peer-alpha",948 deviceName: "Alpha",949 deviceType: "android",950 longTermPublicKeyHex: "a".repeat(64),951 signingPublicKeyHex: pubkeyToHex(alphaKp.publicKeyRaw),952 pairedAt: 1,953 trustSource: "direct",954 });955 await upsertPairedDevice({956 deviceId: "peer-beta",957 deviceName: "Beta",958 deviceType: "android",959 longTermPublicKeyHex: "b".repeat(64),960 signingPublicKeyHex: pubkeyToHex(betaKp.publicKeyRaw),961 pairedAt: 2,962 trustSource: "direct",963 });964965 const fromBeta = await buildSignedDeviceManifest(966 "peer-beta",967 [{968 deviceId: "smuggled",969 deviceName: "Smuggled",970 deviceType: "android",971 longTermPublicKeyHex: "5".repeat(64),972 signingPublicKeyHex: await signingPubkeyHex("smuggled"),973 relayUrl: MESH_RELAY,974 pairedAt: 3,975 }],976 betaKp.privateKey,977 );978979 980 await adapter.applyIncomingDeviceManifest?.(fromBeta, new Uint8Array(32).fill(0xaa));981 expect(await listPendingVouchedDevices()).toEqual([]);982983 984 985 await adapter.applyIncomingDeviceManifest?.(fromBeta, new Uint8Array(32).fill(0xbb));986 const { findPairedDeviceById } = await import("./paired-devices");987 expect(await findPairedDeviceById("smuggled")).toMatchObject({988 trustSource: "vouched",989 relayUrl: MESH_RELAY,990 });991 expect(await listPendingVouchedDevices()).toEqual([]);992 });993 it("S1: a revoked long-term key cannot walk back in under a fresh deviceId", async () => {994 const { adapter } = await setupVault();995 const { buildSignedDeviceManifest, signDeviceRevocation } = await import("../shared/device-manifest");996 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");997 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");998 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");9991000 const issuerId = "phone-issuer";1001 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x53), issuerId);1002 const stolenKey = "d".repeat(64);1003 await upsertPairedDevice({1004 deviceId: issuerId,1005 deviceName: "Pixel",1006 deviceType: "android",1007 longTermPublicKeyHex: "c".repeat(64),1008 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),1009 pairedAt: 1,1010 trustSource: "direct",1011 });1012 await upsertPairedDevice({1013 deviceId: "stolen-laptop",1014 deviceName: "Old Laptop",1015 deviceType: "extension",1016 longTermPublicKeyHex: stolenKey,1017 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),1018 pairedAt: 2,1019 trustSource: "direct",1020 });1021 const issuerSigningPublicKeyHex = pubkeyToHex(issuerKp.publicKeyRaw);1022 const signedRevocation = await signDeviceRevocation({1023 deviceId: "stolen-laptop",1024 longTermPublicKeyHex: stolenKey,1025 revokedAt: Date.now(),1026 revokedByDeviceId: issuerId,1027 }, issuerKp.privateKey, issuerSigningPublicKeyHex);1028 const revoke = await buildSignedDeviceManifest(issuerId, [], issuerKp.privateKey, {1029 revoked: [signedRevocation],1030 });1031 await adapter.applyIncomingDeviceManifest?.(revoke, new Uint8Array(32).fill(0xcc));1032 expect(await findPairedDeviceById("stolen-laptop")).toBeNull();10331034 1035 1036 const renamed = await buildSignedDeviceManifest(1037 issuerId,1038 [{1039 deviceId: "stolen-laptop-mk2",1040 deviceName: "New Laptop",1041 deviceType: "extension",1042 longTermPublicKeyHex: stolenKey,1043 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),1044 relayUrl: MESH_RELAY,1045 pairedAt: Date.now(),1046 }],1047 issuerKp.privateKey,1048 );1049 await adapter.applyIncomingDeviceManifest?.(renamed, new Uint8Array(32).fill(0xcc));1050 expect(await listPendingVouchedDevices()).toEqual([]);1051 expect(await findPairedDeviceById("stolen-laptop-mk2")).toBeNull();10521053 1054 1055 const clean = await buildSignedDeviceManifest(1056 issuerId,1057 [{1058 deviceId: "stolen-laptop-mk2",1059 deviceName: "New Laptop",1060 deviceType: "extension",1061 longTermPublicKeyHex: "9".repeat(64),1062 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),1063 relayUrl: MESH_RELAY,1064 pairedAt: Date.now(),1065 }],1066 issuerKp.privateKey,1067 );1068 await adapter.applyIncomingDeviceManifest?.(clean, new Uint8Array(32).fill(0xcc));1069 expect(await findPairedDeviceById("stolen-laptop-mk2")).toMatchObject({1070 trustSource: "vouched",1071 relayUrl: MESH_RELAY,1072 });1073 expect(await listPendingVouchedDevices()).toEqual([]);1074 });10751076 it("S1: a revoked key cannot be written onto a device we still trust", async () => {1077 const { adapter } = await setupVault();1078 const { buildSignedDeviceManifest, signDeviceRevocation } = await import("../shared/device-manifest");1079 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");1080 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");10811082 const issuerId = "phone-issuer";1083 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x54), issuerId);1084 const revokedKey = "d".repeat(64);1085 await upsertPairedDevice({1086 deviceId: issuerId,1087 deviceName: "Pixel",1088 deviceType: "android",1089 longTermPublicKeyHex: "c".repeat(64),1090 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),1091 pairedAt: 1,1092 trustSource: "direct",1093 });1094 await upsertPairedDevice({1095 deviceId: "trusted-tablet",1096 deviceName: "Tablet",1097 deviceType: "android",1098 longTermPublicKeyHex: "7".repeat(64),1099 signingPublicKeyHex: await signingPubkeyHex("trusted-tablet"),1100 pairedAt: 2,1101 trustSource: "direct",1102 });11031104 const issuerSigningPublicKeyHex = pubkeyToHex(issuerKp.publicKeyRaw);1105 const signedRevocation = await signDeviceRevocation({1106 deviceId: "stolen-laptop",1107 longTermPublicKeyHex: revokedKey,1108 revokedAt: Date.now(),1109 revokedByDeviceId: issuerId,1110 }, issuerKp.privateKey, issuerSigningPublicKeyHex);1111 const revoke = await buildSignedDeviceManifest(issuerId, [], issuerKp.privateKey, {1112 revoked: [signedRevocation],1113 });1114 await adapter.applyIncomingDeviceManifest?.(revoke, new Uint8Array(32).fill(0xcc));11151116 1117 1118 const rotate = await buildSignedDeviceManifest(1119 issuerId,1120 [{1121 deviceId: "trusted-tablet",1122 deviceName: "Tablet",1123 deviceType: "android",1124 longTermPublicKeyHex: revokedKey,1125 signingPublicKeyHex: await signingPubkeyHex("trusted-tablet"),1126 pairedAt: 2,1127 }],1128 issuerKp.privateKey,1129 );1130 await adapter.applyIncomingDeviceManifest?.(rotate, new Uint8Array(32).fill(0xcc));1131 expect(await findPairedDeviceById("trusted-tablet")).toMatchObject({1132 longTermPublicKeyHex: "7".repeat(64),1133 });1134 });11351136 it("methods throw VaultLockedError when the vault is locked", async () => {1137 const { vault, adapter } = await setupVault();1138 vault.lock();1139 await expect(adapter.computeVaultId()).rejects.toMatchObject({ message: "vault_locked" });1140 await expect(adapter.buildEntryManifest()).rejects.toMatchObject({ message: "vault_locked" });1141 await expect(adapter.buildTombstoneManifest()).rejects.toMatchObject({ message: "vault_locked" });1142 await expect(adapter.getEncryptedEntries(["x"])).rejects.toMatchObject({ message: "vault_locked" });1143 await expect(adapter.applyEntries({ x: "AAAA" })).rejects.toMatchObject({ message: "vault_locked" });1144 await expect(adapter.applyTombstones({ x: 1 })).rejects.toMatchObject({ message: "vault_locked" });1145 await expect(adapter.buildOutgoingDeviceManifest?.()).rejects.toMatchObject({ message: "vault_locked" });1146 });1147});