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 { 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: "f".repeat(64),399 signingPublicKeyHex: await signingPubkeyHex("android-existing-new"),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 rendezvousSecretHex: expect.stringMatching(/^[0-9a-f]{64}$/),418 });419 const pending = await listPendingVouchedDevices();420 expect(pending).toEqual([]);421422 423 424 425 const existing = await findPairedDeviceById("android-existing");426 expect(existing).toMatchObject({427 deviceName: "Existing Pixel",428 longTermPublicKeyHex: "f".repeat(64),429 trustSource: "direct",430 wsPort: 52345,431 });432 expect((await listPairedDevices()).map((d) => d.deviceId).sort()).toEqual([433 "android-existing",434 "android-new",435 "extension-issuer",436 ]);437 });438439 it("MV-8d: records a DEVICE_KEY_ROTATED alert when an existing device's key changes in a manifest", async () => {440 const { adapter } = await setupVault();441 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");442 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");443 const { upsertPairedDevice } = await import("./paired-devices");444 const { getPendingSyncAlerts } = await import("./sync-alerts");445446 const issuerId = "extension-issuer";447 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x24), issuerId);448 await upsertPairedDevice({449 deviceId: issuerId,450 deviceName: "Firefox",451 deviceType: "extension",452 longTermPublicKeyHex: "c".repeat(64),453 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),454 pairedAt: 1,455 trustSource: "direct",456 });457 await upsertPairedDevice({458 deviceId: "android-existing",459 deviceName: "Pixel",460 deviceType: "android",461 longTermPublicKeyHex: "d".repeat(64),462 signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),463 pairedAt: 2,464 trustSource: "direct",465 });466467 const manifest = await buildSignedDeviceManifest(468 issuerId,469 [470 {471 deviceId: "android-existing",472 deviceName: "Pixel",473 deviceType: "android",474 longTermPublicKeyHex: "f".repeat(64),475 signingPublicKeyHex: await signingPubkeyHex("android-existing-new"),476 wsPort: 52345,477 pairedAt: 3,478 },479 ],480 issuerKp.privateKey,481 );482483 await adapter.applyIncomingDeviceManifest?.(484 manifest,485 new Uint8Array(32).fill(0xcc),486 );487 488 for (let i = 0; i < 25; i++) await Promise.resolve();489490 const alerts = await getPendingSyncAlerts();491 expect(492 alerts.some(493 (a) => a.type === "DEVICE_KEY_ROTATED" && a.deviceName === "Pixel",494 ),495 ).toBe(true);496 });497498 it("S5: a rotation alert names the device from local state, not from the manifest", async () => {499 500 501 502 503 const { adapter } = await setupVault();504 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");505 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");506 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");507 const { getPendingSyncAlerts } = await import("./sync-alerts");508509 const issuerId = "hostile-issuer";510 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x26), issuerId);511 await upsertPairedDevice({512 deviceId: issuerId,513 deviceName: "Old Laptop",514 deviceType: "extension",515 longTermPublicKeyHex: "c".repeat(64),516 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),517 pairedAt: 1,518 trustSource: "direct",519 });520 await upsertPairedDevice({521 deviceId: "android-existing",522 deviceName: "Spare Tablet",523 deviceType: "android",524 longTermPublicKeyHex: "d".repeat(64),525 signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),526 pairedAt: 2,527 trustSource: "direct",528 });529530 const manifest = await buildSignedDeviceManifest(531 issuerId,532 [533 {534 deviceId: "android-existing",535 deviceName: "June's Primary Phone",536 deviceType: "android",537 longTermPublicKeyHex: "f".repeat(64),538 signingPublicKeyHex: await signingPubkeyHex("android-existing-new"),539 wsPort: 52345,540 pairedAt: 3,541 },542 ],543 issuerKp.privateKey,544 );545546 await adapter.applyIncomingDeviceManifest?.(547 manifest,548 new Uint8Array(32).fill(0xcc),549 );550 for (let i = 0; i < 25; i++) await Promise.resolve();551552 const alerts = await getPendingSyncAlerts();553 const rotation = alerts.find((a) => a.type === "DEVICE_KEY_ROTATED");554 expect(rotation?.deviceName).toBe("Spare Tablet");555 expect(rotation?.entryTitle).toBe("Spare Tablet");556 expect(alerts.some((a) => a.deviceName === "June's Primary Phone")).toBe(false);557558 559 const stored = await findPairedDeviceById("android-existing");560 expect(stored).toMatchObject({561 deviceName: "Spare Tablet",562 longTermPublicKeyHex: "f".repeat(64),563 });564 });565566 it("§C: a vouched peer's revocation evicts the device and permanently blocks re-vouching", async () => {567 const { adapter } = await setupVault();568 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");569 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");570 const { findPairedDeviceById, isDeviceRevoked, upsertPairedDevice } =571 await import("./paired-devices");572573 const issuerId = "phone-issuer";574 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x27), issuerId);575 await upsertPairedDevice({576 deviceId: issuerId,577 deviceName: "Pixel",578 deviceType: "android",579 longTermPublicKeyHex: "c".repeat(64),580 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),581 pairedAt: 1,582 trustSource: "vouched",583 });584 await upsertPairedDevice({585 deviceId: "stolen-laptop",586 deviceName: "Old Laptop",587 deviceType: "extension",588 longTermPublicKeyHex: "d".repeat(64),589 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),590 pairedAt: 2,591 trustSource: "direct",592 });593594 const revocation = await buildSignedDeviceManifest(595 issuerId,596 [],597 issuerKp.privateKey,598 {599 revoked: [600 {601 deviceId: "stolen-laptop",602 longTermPublicKeyHex: "d".repeat(64),603 revokedAt: Date.now(),604 revokedByDeviceId: issuerId,605 },606 ],607 },608 );609 await adapter.applyIncomingDeviceManifest?.(610 revocation,611 new Uint8Array(32).fill(0xcc),612 );613614 expect(await findPairedDeviceById("stolen-laptop")).toBeNull();615 expect(await isDeviceRevoked("stolen-laptop")).toBe(true);616617 618 619 620 const revouch = await buildSignedDeviceManifest(621 issuerId,622 [623 {624 deviceId: "stolen-laptop",625 deviceName: "Old Laptop",626 deviceType: "extension",627 longTermPublicKeyHex: "d".repeat(64),628 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),629 pairedAt: Date.now() + 60_000,630 },631 ],632 issuerKp.privateKey,633 );634 await adapter.applyIncomingDeviceManifest?.(635 revouch,636 new Uint8Array(32).fill(0xcc),637 );638639 expect(await findPairedDeviceById("stolen-laptop")).toBeNull();640 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");641 expect(await listPendingVouchedDevices()).toHaveLength(0);642 });643644 it("§C: a peer cannot revoke US, and our outgoing manifest carries our revocations", async () => {645 const { adapter } = await setupVault();646 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");647 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");648 const {649 isDeviceRevoked,650 revokeDeviceById,651 upsertPairedDevice,652 } = await import("./paired-devices");653 const { getOrCreateDeviceId } = await import("./device-identity");654655 const ourDeviceId = await getOrCreateDeviceId();656 const issuerId = "phone-issuer";657 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x28), issuerId);658 await upsertPairedDevice({659 deviceId: issuerId,660 deviceName: "Pixel",661 deviceType: "android",662 longTermPublicKeyHex: "c".repeat(64),663 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),664 pairedAt: 1,665 trustSource: "direct",666 });667668 669 const selfRevoke = await buildSignedDeviceManifest(670 issuerId,671 [],672 issuerKp.privateKey,673 {674 revoked: [675 {676 deviceId: ourDeviceId,677 longTermPublicKeyHex: "e".repeat(64),678 revokedAt: Date.now(),679 revokedByDeviceId: issuerId,680 },681 ],682 },683 );684 await adapter.applyIncomingDeviceManifest?.(685 selfRevoke,686 new Uint8Array(32).fill(0xcc),687 );688 expect(await isDeviceRevoked(ourDeviceId)).toBe(false);689690 691 692 await upsertPairedDevice({693 deviceId: "retired-tablet",694 deviceName: "Retired Tablet",695 deviceType: "android",696 longTermPublicKeyHex: "f".repeat(64),697 signingPublicKeyHex: await signingPubkeyHex("retired-tablet"),698 pairedAt: 3,699 trustSource: "direct",700 });701 await revokeDeviceById("retired-tablet", ourDeviceId);702703 const outgoing = await adapter.buildOutgoingDeviceManifest?.();704 expect(outgoing?.body.revoked.map((r) => r.deviceId)).toEqual(["retired-tablet"]);705 expect(outgoing?.body.devices.map((d) => d.deviceId)).not.toContain("retired-tablet");706 });707708 it("accepts a manifest from the phone it paired with — mesh introduction runs in that direction", async () => {709 710 711 712 713 const { adapter } = await setupVault();714 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");715 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");716 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");717 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");718719 const mobileIssuerId = "android-issuer";720 const mobileIssuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x25), mobileIssuerId);721 await upsertPairedDevice({722 deviceId: mobileIssuerId,723 deviceName: "Issuer Pixel",724 deviceType: "android",725 longTermPublicKeyHex: "1".repeat(64),726 signingPublicKeyHex: pubkeyToHex(mobileIssuerKp.publicKeyRaw),727 pairedAt: 1_700_000_000_000,728 trustSource: "direct",729 });730 const mobileManifest = await buildSignedDeviceManifest(731 mobileIssuerId,732 [{733 deviceId: "mesh-peer",734 deviceName: "Other Pixel",735 deviceType: "android",736 longTermPublicKeyHex: "2".repeat(64),737 signingPublicKeyHex: await signingPubkeyHex("mesh-peer"),738 relayUrl: MESH_RELAY,739 pairedAt: 1_700_000_000_010,740 }],741 mobileIssuerKp.privateKey,742 );743 await adapter.applyIncomingDeviceManifest?.(744 mobileManifest,745 new Uint8Array(32).fill(0x11),746 );747748 expect(await findPairedDeviceById("mesh-peer")).toMatchObject({749 trustSource: "vouched",750 relayUrl: MESH_RELAY,751 rendezvousSecretHex: expect.stringMatching(/^[0-9a-f]{64}$/),752 });753 expect(await listPendingVouchedDevices()).toEqual([]);754 });755756 it("applyIncomingDeviceManifest accepts vouched issuers but rejects unauthenticated and bad signatures", async () => {757 const { adapter } = await setupVault();758 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");759 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");760 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");761 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");762763 764 765 766 const vouchedIssuerId = "android-vouched-issuer";767 const vouchedKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x25), vouchedIssuerId);768 await upsertPairedDevice({769 deviceId: vouchedIssuerId,770 deviceName: "Second-hand Pixel",771 deviceType: "android",772 longTermPublicKeyHex: "1".repeat(64),773 signingPublicKeyHex: pubkeyToHex(vouchedKp.publicKeyRaw),774 pairedAt: 1_700_000_000_000,775 trustSource: "vouched",776 });777 const onward = await buildSignedDeviceManifest(778 vouchedIssuerId,779 [{780 deviceId: "onward-mesh-peer",781 deviceName: "Other Pixel",782 deviceType: "android",783 longTermPublicKeyHex: "2".repeat(64),784 signingPublicKeyHex: await signingPubkeyHex("onward-mesh-peer"),785 relayUrl: MESH_RELAY,786 pairedAt: 1_700_000_000_010,787 }],788 vouchedKp.privateKey,789 );790 await adapter.applyIncomingDeviceManifest?.(791 onward,792 new Uint8Array(32).fill(0x11),793 );794 expect(await findPairedDeviceById("onward-mesh-peer")).toMatchObject({795 trustSource: "vouched",796 relayUrl: MESH_RELAY,797 rendezvousSecretHex: expect.stringMatching(/^[0-9a-f]{64}$/),798 });799 expect(await listPendingVouchedDevices()).toEqual([]);800801 const extensionIssuerId = "extension-bad-sig";802 const extensionKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x26), extensionIssuerId);803 await upsertPairedDevice({804 deviceId: extensionIssuerId,805 deviceName: "Chrome",806 deviceType: "extension",807 longTermPublicKeyHex: "3".repeat(64),808 signingPublicKeyHex: pubkeyToHex(extensionKp.publicKeyRaw),809 pairedAt: 1_700_000_000_020,810 trustSource: "direct",811 });812 const good = await buildSignedDeviceManifest(813 extensionIssuerId,814 [{815 deviceId: "forged-add",816 deviceName: "Forged Pixel",817 deviceType: "android",818 longTermPublicKeyHex: "4".repeat(64),819 signingPublicKeyHex: await signingPubkeyHex("forged-add"),820 pairedAt: 1_700_000_000_030,821 }],822 extensionKp.privateKey,823 );824 await adapter.applyIncomingDeviceManifest?.(825 good,826 new Uint8Array(32).fill(0x44),827 );828 expect(await findPairedDeviceById("forged-add")).toBeNull();829830 const forged = {831 ...good,832 signatureHex:833 good.signatureHex.slice(0, 2) +834 ((parseInt(good.signatureHex.slice(2, 4), 16) ^ 0xff).toString(16).padStart(2, "0")) +835 good.signatureHex.slice(4),836 };837 await adapter.applyIncomingDeviceManifest?.(838 forged,839 new Uint8Array(32).fill(0x33),840 );841 expect(await findPairedDeviceById("forged-add")).toBeNull();842 });843844 it("falls back to derived signing key when stored issuer key is stale", async () => {845 const { vault, adapter } = await setupVault();846 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");847 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");848 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");849 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");850851 const issuerId = "stale-key-android";852 const rootHex = vault.getRootKeyHex()!;853 const root = Uint8Array.from(rootHex.match(/../g)!.map((b) => parseInt(b, 16)));854 const issuerKp = await deriveSyncSigningKeypair(root, issuerId);855856 await upsertPairedDevice({857 deviceId: issuerId,858 deviceName: "Pixel",859 deviceType: "android",860 longTermPublicKeyHex: "c".repeat(64),861 862 863 signingPublicKeyHex: "ff".repeat(32),864 pairedAt: 1_700_000_000_000,865 trustSource: "direct",866 });867868 const manifest = await buildSignedDeviceManifest(869 issuerId,870 [{871 deviceId: "onward-peer",872 deviceName: "Forwarded iPad",873 deviceType: "extension",874 longTermPublicKeyHex: "e".repeat(64),875 signingPublicKeyHex: pubkeyToHex(876 (await deriveSyncSigningKeypair(root, "onward-peer")).publicKeyRaw,877 ),878 relayUrl: MESH_RELAY,879 pairedAt: 1_700_000_000_010,880 }],881 issuerKp.privateKey,882 );883884 await adapter.applyIncomingDeviceManifest?.(885 manifest,886 new Uint8Array(32).fill(0xcc),887 );888889 expect(await findPairedDeviceById("onward-peer")).toMatchObject({890 trustSource: "vouched",891 relayUrl: MESH_RELAY,892 rendezvousSecretHex: expect.stringMatching(/^[0-9a-f]{64}$/),893 });894 expect(await listPendingVouchedDevices()).toEqual([]);895 });896897 it("S1: a manifest signed by one paired peer is refused over a session authenticated as another", async () => {898 const { adapter } = await setupVault();899 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");900 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");901 const { upsertPairedDevice } = await import("./paired-devices");902 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");903904 905 906 907 const alphaKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x51), "peer-alpha");908 const betaKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x52), "peer-beta");909 await upsertPairedDevice({910 deviceId: "peer-alpha",911 deviceName: "Alpha",912 deviceType: "android",913 longTermPublicKeyHex: "a".repeat(64),914 signingPublicKeyHex: pubkeyToHex(alphaKp.publicKeyRaw),915 pairedAt: 1,916 trustSource: "direct",917 });918 await upsertPairedDevice({919 deviceId: "peer-beta",920 deviceName: "Beta",921 deviceType: "android",922 longTermPublicKeyHex: "b".repeat(64),923 signingPublicKeyHex: pubkeyToHex(betaKp.publicKeyRaw),924 pairedAt: 2,925 trustSource: "direct",926 });927928 const fromBeta = await buildSignedDeviceManifest(929 "peer-beta",930 [{931 deviceId: "smuggled",932 deviceName: "Smuggled",933 deviceType: "android",934 longTermPublicKeyHex: "5".repeat(64),935 signingPublicKeyHex: await signingPubkeyHex("smuggled"),936 relayUrl: MESH_RELAY,937 pairedAt: 3,938 }],939 betaKp.privateKey,940 );941942 943 await adapter.applyIncomingDeviceManifest?.(fromBeta, new Uint8Array(32).fill(0xaa));944 expect(await listPendingVouchedDevices()).toEqual([]);945946 947 948 await adapter.applyIncomingDeviceManifest?.(fromBeta, new Uint8Array(32).fill(0xbb));949 const { findPairedDeviceById } = await import("./paired-devices");950 expect(await findPairedDeviceById("smuggled")).toMatchObject({951 trustSource: "vouched",952 relayUrl: MESH_RELAY,953 });954 expect(await listPendingVouchedDevices()).toEqual([]);955 });956957 it("S1: a revoked long-term key cannot walk back in under a fresh deviceId", async () => {958 const { adapter } = await setupVault();959 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");960 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");961 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");962 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");963964 const issuerId = "phone-issuer";965 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x53), issuerId);966 const stolenKey = "d".repeat(64);967 await upsertPairedDevice({968 deviceId: issuerId,969 deviceName: "Pixel",970 deviceType: "android",971 longTermPublicKeyHex: "c".repeat(64),972 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),973 pairedAt: 1,974 trustSource: "direct",975 });976 await upsertPairedDevice({977 deviceId: "stolen-laptop",978 deviceName: "Old Laptop",979 deviceType: "extension",980 longTermPublicKeyHex: stolenKey,981 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),982 pairedAt: 2,983 trustSource: "direct",984 });985986 const revoke = await buildSignedDeviceManifest(issuerId, [], issuerKp.privateKey, {987 revoked: [{988 deviceId: "stolen-laptop",989 longTermPublicKeyHex: stolenKey,990 revokedAt: Date.now(),991 revokedByDeviceId: issuerId,992 }],993 });994 await adapter.applyIncomingDeviceManifest?.(revoke, new Uint8Array(32).fill(0xcc));995 expect(await findPairedDeviceById("stolen-laptop")).toBeNull();996997 998 999 const renamed = await buildSignedDeviceManifest(1000 issuerId,1001 [{1002 deviceId: "stolen-laptop-mk2",1003 deviceName: "New Laptop",1004 deviceType: "extension",1005 longTermPublicKeyHex: stolenKey,1006 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),1007 relayUrl: MESH_RELAY,1008 pairedAt: Date.now(),1009 }],1010 issuerKp.privateKey,1011 );1012 await adapter.applyIncomingDeviceManifest?.(renamed, new Uint8Array(32).fill(0xcc));1013 expect(await listPendingVouchedDevices()).toEqual([]);1014 expect(await findPairedDeviceById("stolen-laptop-mk2")).toBeNull();10151016 1017 1018 const clean = await buildSignedDeviceManifest(1019 issuerId,1020 [{1021 deviceId: "stolen-laptop-mk2",1022 deviceName: "New Laptop",1023 deviceType: "extension",1024 longTermPublicKeyHex: "9".repeat(64),1025 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),1026 relayUrl: MESH_RELAY,1027 pairedAt: Date.now(),1028 }],1029 issuerKp.privateKey,1030 );1031 await adapter.applyIncomingDeviceManifest?.(clean, new Uint8Array(32).fill(0xcc));1032 expect(await findPairedDeviceById("stolen-laptop-mk2")).toMatchObject({1033 trustSource: "vouched",1034 relayUrl: MESH_RELAY,1035 });1036 expect(await listPendingVouchedDevices()).toEqual([]);1037 });10381039 it("S1: a revoked key cannot be written onto a device we still trust", async () => {1040 const { adapter } = await setupVault();1041 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");1042 const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");1043 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");10441045 const issuerId = "phone-issuer";1046 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x54), issuerId);1047 const revokedKey = "d".repeat(64);1048 await upsertPairedDevice({1049 deviceId: issuerId,1050 deviceName: "Pixel",1051 deviceType: "android",1052 longTermPublicKeyHex: "c".repeat(64),1053 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),1054 pairedAt: 1,1055 trustSource: "direct",1056 });1057 await upsertPairedDevice({1058 deviceId: "trusted-tablet",1059 deviceName: "Tablet",1060 deviceType: "android",1061 longTermPublicKeyHex: "7".repeat(64),1062 signingPublicKeyHex: await signingPubkeyHex("trusted-tablet"),1063 pairedAt: 2,1064 trustSource: "direct",1065 });10661067 const revoke = await buildSignedDeviceManifest(issuerId, [], issuerKp.privateKey, {1068 revoked: [{1069 deviceId: "stolen-laptop",1070 longTermPublicKeyHex: revokedKey,1071 revokedAt: Date.now(),1072 revokedByDeviceId: issuerId,1073 }],1074 });1075 await adapter.applyIncomingDeviceManifest?.(revoke, new Uint8Array(32).fill(0xcc));10761077 1078 1079 const rotate = await buildSignedDeviceManifest(1080 issuerId,1081 [{1082 deviceId: "trusted-tablet",1083 deviceName: "Tablet",1084 deviceType: "android",1085 longTermPublicKeyHex: revokedKey,1086 signingPublicKeyHex: await signingPubkeyHex("trusted-tablet"),1087 pairedAt: 2,1088 }],1089 issuerKp.privateKey,1090 );1091 await adapter.applyIncomingDeviceManifest?.(rotate, new Uint8Array(32).fill(0xcc));1092 expect(await findPairedDeviceById("trusted-tablet")).toMatchObject({1093 longTermPublicKeyHex: "7".repeat(64),1094 });1095 });10961097 it("methods throw VaultLockedError when the vault is locked", async () => {1098 const { vault, adapter } = await setupVault();1099 vault.lock();1100 await expect(adapter.computeVaultId()).rejects.toMatchObject({ message: "vault_locked" });1101 await expect(adapter.buildEntryManifest()).rejects.toMatchObject({ message: "vault_locked" });1102 await expect(adapter.buildTombstoneManifest()).rejects.toMatchObject({ message: "vault_locked" });1103 await expect(adapter.getEncryptedEntries(["x"])).rejects.toMatchObject({ message: "vault_locked" });1104 await expect(adapter.applyEntries({ x: "AAAA" })).rejects.toMatchObject({ message: "vault_locked" });1105 await expect(adapter.applyTombstones({ x: 1 })).rejects.toMatchObject({ message: "vault_locked" });1106 await expect(adapter.buildOutgoingDeviceManifest?.()).rejects.toMatchObject({ message: "vault_locked" });1107 });1108});