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 47 48 const identity = await import("./device-identity");49 await identity.getOrCreateDeviceId();50 const { createSyncVaultAdapter } = await import("./sync-vault-adapter");51 const adapter = createSyncVaultAdapter();52 return { vault, adapter };53 }5455 async function signingPubkeyHex(deviceId: string): Promise<string> {56 const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");57 const { pubkeyToHex } = await import("../shared/sync-identity");58 const kp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x42), deviceId);59 return pubkeyToHex(kp.publicKeyRaw);60 }6162 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 });7778 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 });8687 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 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 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 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 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 });132133 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 });148149 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 });162163 it("computeVaultId returns a stable 64-char hex string for the same masterKey", async () => {164 const { adapter } = await setupVault();165 const id1 = await adapter.computeVaultId();166 const id2 = await adapter.computeVaultId();167 expect(id1).toBe(id2);168 expect(id1).toMatch(/^[0-9a-f]{64}$/);169 });170171 it("vault_id and sync signing key are unchanged after a password change (SEV-2-B)", async () => {172 const { vault, adapter } = await setupVault();173 const deviceId = await adapter.getOurDeviceId();174 const vaultIdBefore = await adapter.computeVaultId();175176 const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");177 const { pubkeyToHex } = await import("../shared/sync-identity");178 const rootBefore = vault.getRootKeyHex()!;179 const unhex = (h: string) => Uint8Array.from(h.match(/../g)!.map((b) => parseInt(b, 16)));180 const signBefore = pubkeyToHex(181 (await deriveSyncSigningKeypair(unhex(rootBefore), deviceId)).publicKeyRaw,182 );183184 expect(await vault.changePassword("correct horse battery staple", "a different passphrase")).toBe(true);185 vault.lock();186 expect(await vault.unlock("a different passphrase")).toBe(true);187188 189 expect(await adapter.computeVaultId()).toBe(vaultIdBefore);190 const rootAfter = vault.getRootKeyHex()!;191 expect(rootAfter).toBe(rootBefore);192 const signAfter = pubkeyToHex(193 (await deriveSyncSigningKeypair(unhex(rootAfter), deviceId)).publicKeyRaw,194 );195 expect(signAfter).toBe(signBefore);196 });197198 it("getOurDeviceId is stable across calls and a fresh UUID v4 on first call", async () => {199 const { adapter } = await setupVault();200 const id1 = await adapter.getOurDeviceId();201 const id2 = await adapter.getOurDeviceId();202 expect(id1).toBe(id2);203 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}$/);204 });205206 it("buildEntryManifest reports {id: modifiedAt} for live entries only", async () => {207 const { vault, adapter } = await setupVault();208 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });209 const b = await vault.addEntry({ type: "login", title: "Beta", password: "pw" });210 await vault.deleteEntry(b.id);211 const m = await adapter.buildEntryManifest();212 expect(Object.keys(m).sort()).toEqual([a.id]);213 expect(m[a.id]).toBe(a.modifiedAt);214 });215216 it("buildTombstoneManifest reports {id: deletedAt} for soft-deleted entries", async () => {217 const { vault, adapter } = await setupVault();218 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });219 await vault.deleteEntry(a.id);220 const t = await adapter.buildTombstoneManifest();221 expect(Object.keys(t)).toEqual([a.id]);222 expect(typeof t[a.id]).toBe("number");223 expect(t[a.id]).toBeGreaterThan(0);224 });225226 it("buildTombstoneManifest retains ids after a full-entry purge", async () => {227 const { vault, adapter } = await setupVault();228 const entry = await vault.addEntry({ type: "login", title: "Purged", password: "pw" });229 await vault.deleteEntry(entry.id);230 const deletedAt = vault.getDeletedEntries().find((item) => item.id === entry.id)!.deletedAt!;231232 await vault.purgeEntry(entry.id);233234 expect(await adapter.buildTombstoneManifest()).toEqual({ [entry.id]: deletedAt });235 });236237 it("getEncryptedEntries returns opaque base64 strings keyed by id", async () => {238 const { vault, adapter } = await setupVault();239 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });240 const env = await adapter.getEncryptedEntries([a.id]);241 expect(Object.keys(env)).toEqual([a.id]);242 expect(env[a.id]).toMatch(/^[A-Za-z0-9+/]+=*$/);243 244 expect(env[a.id]).not.toContain("Alpha");245 });246247 it("getEncryptedEntries silently skips unknown ids (peer may have a manifest item we dropped)", async () => {248 const { adapter } = await setupVault();249 const env = await adapter.getEncryptedEntries(["does-not-exist"]);250 expect(env).toEqual({});251 });252253 it("encryption uses a fresh nonce per call — same entry yields different envelopes", async () => {254 const { vault, adapter } = await setupVault();255 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });256 const e1 = await adapter.getEncryptedEntries([a.id]);257 const e2 = await adapter.getEncryptedEntries([a.id]);258 expect(e1[a.id]).not.toBe(e2[a.id]);259 });260261 it("round-trips: encrypt on one adapter, apply on a fresh import of the same vault", async () => {262 const { vault, adapter } = await setupVault();263 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "secret", url: "https://a.example" });264 const envelopes = await adapter.getEncryptedEntries([a.id]);265 266 267 268 269 270 271 272 vault.lock();273 await vault.unlock("correct horse battery staple");274 const { createSyncVaultAdapter } = await import("./sync-vault-adapter");275 const adapter2 = createSyncVaultAdapter();276 277 await adapter2.applyEntries(envelopes);278 expect(vault.getEntries().find((e) => e.id === a.id)?.title).toBe("Alpha");279 });280281 it("applyEntries decrypts and merges newer remote entries (last-write-wins)", async () => {282 const { vault, adapter } = await setupVault();283 const local = await vault.addEntry({ type: "login", title: "Original", password: "pw" });284 285 286 287 await vault.updateEntry(local.id, { title: "Updated" });288 const newer = vault.getEntries().find((e) => e.id === local.id);289 expect(newer?.title).toBe("Updated");290 const envelopes = await adapter.getEncryptedEntries([local.id]);291 292 293 294 295 296 297 const older: typeof local = { ...local, modifiedAt: local.modifiedAt - 1000, title: "Stale" };298 await vault.restoreEntries([older], "replace");299 expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Stale");300 await adapter.applyEntries(envelopes);301 expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Updated");302 });303304 it("tells an open popup to reload when a round merges remote entries, and stays silent otherwise", async () => {305 const { vault, adapter } = await setupVault();306 307 308 309 const note = await vault.addEntry({ type: "note", title: "From phone", notes: "body" });310 await vault.updateEntry(note.id, { notes: "edited on the peer" });311 const envelopes = await adapter.getEncryptedEntries([note.id]);312313 const sendMessage = vi.mocked(chrome.runtime.sendMessage);314 await vault.restoreEntries([{ ...note, modifiedAt: note.modifiedAt - 1000, notes: "stale" }], "replace");315316 sendMessage.mockClear();317 await adapter.applyEntries(envelopes);318 expect(sendMessage).toHaveBeenCalledWith({ type: "VAULT_ENTRIES_CHANGED" });319320 321 322 sendMessage.mockClear();323 await adapter.applyEntries(envelopes);324 expect(sendMessage).not.toHaveBeenCalled();325 });326327 it("applyEntries rejects envelopes whose decrypted id differs from the map key", async () => {328 const { vault, adapter } = await setupVault();329 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });330 const env = await adapter.getEncryptedEntries([a.id]);331 332 const swapped: Record<string, string> = { "wrong-id": env[a.id] };333 await adapter.applyEntries(swapped);334 335 expect(vault.getEntries().map((e) => e.id)).toEqual([a.id]);336 });337338 it("entry_envelope_roundtrips_with_separated_info (HKDF separator)", async () => {339 const { vault, adapter } = await setupVault();340 const a = await vault.addEntry({ type: "login", title: "Original", password: "pw" });341 await vault.updateEntry(a.id, { title: "Fresh" });342 const envelopes = await adapter.getEncryptedEntries([a.id]);343 344 345 const stale = { ...a, modifiedAt: a.modifiedAt - 1000, title: "Stale" };346 await vault.restoreEntries([stale], "replace");347 await adapter.applyEntries(envelopes);348 expect(vault.getEntries().find((e) => e.id === a.id)?.title).toBe("Fresh");349 });350351 it("legacy_info_envelope_fails_closed (HKDF separator wire break)", async () => {352 353 354 355 const { vault, adapter } = await setupVault();356 const { HKDF } = await import("@stablelib/hkdf");357 const { SHA256 } = await import("@stablelib/sha256");358359 const masterHex = vault.getRootKeyHex()!;360 const masterKey = Uint8Array.from(masterHex.match(/../g)!.map((b) => parseInt(b, 16)));361 const entryId = crypto.randomUUID();362 const legacyInfo = new TextEncoder().encode(entryId + "sync-entry-v1"); 363 const raw = new HKDF(SHA256, masterKey, new Uint8Array(0), legacyInfo).expand(32);364 const key = await crypto.subtle.importKey("raw", raw.buffer as ArrayBuffer, { name: "AES-GCM" }, false, ["encrypt"]);365366 const entry = { id: entryId, type: "login", title: "LegacyOnly", password: "pw", createdAt: Date.now(), modifiedAt: Date.now() };367 const nonce = crypto.getRandomValues(new Uint8Array(12));368 const aad = new TextEncoder().encode("peach-sync-entry-v1");369 const ct = new Uint8Array(370 await crypto.subtle.encrypt(371 { name: "AES-GCM", iv: nonce.buffer as ArrayBuffer, additionalData: aad.buffer as ArrayBuffer, tagLength: 128 },372 key,373 new TextEncoder().encode(JSON.stringify(entry)).buffer as ArrayBuffer,374 ),375 );376 const envelope = new Uint8Array(nonce.length + ct.length);377 envelope.set(nonce, 0);378 envelope.set(ct, nonce.length);379 const legacyB64 = Buffer.from(envelope).toString("base64");380381 await adapter.applyEntries({ [entryId]: legacyB64 });382 383 expect(vault.getEntries().some((e) => e.id === entryId)).toBe(false);384 });385386 it("applyTombstones soft-deletes locally-live entries with newer deletedAt", async () => {387 const { vault, adapter } = await setupVault();388 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });389 await adapter.applyTombstones({ [a.id]: a.modifiedAt + 10_000 });390 expect(vault.getEntries().find((e) => e.id === a.id)).toBeUndefined();391 expect(vault.getDeletedEntries().find((e) => e.id === a.id)).toBeDefined();392 });393394 it("applyTombstones leaves entries alone when local modifiedAt is newer", async () => {395 const { vault, adapter } = await setupVault();396 const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });397 await adapter.applyTombstones({ [a.id]: a.modifiedAt - 10_000 });398 expect(vault.getEntries().find((e) => e.id === a.id)).toBeDefined();399 });400401 402403 it("MV-3: applyEntries throws when the batch exceeds MAX_ENTRY_COUNT", async () => {404 const { adapter } = await setupVault();405 const { SYNC_LIMITS } = await import("../shared/sync-limits");406 const tooMany: Record<string, string> = {};407 for (let i = 0; i <= SYNC_LIMITS.MAX_ENTRY_COUNT; i++) tooMany[`id-${i}`] = "AAAA";408 await expect(adapter.applyEntries(tooMany)).rejects.toThrow(/exceeds limit/);409 });410411 it("MV-3: applyEntries skips an oversized envelope but still applies valid ones", async () => {412 const { vault, adapter } = await setupVault();413 const { SYNC_LIMITS } = await import("../shared/sync-limits");414 const local = await vault.addEntry({ type: "login", title: "Original", password: "pw" });415 await vault.updateEntry(local.id, { title: "Updated" });416 const envelopes = await adapter.getEncryptedEntries([local.id]);417 418 const older = { ...local, modifiedAt: local.modifiedAt - 1000, title: "Stale" };419 await vault.restoreEntries([older], "replace");420 expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Stale");421422 const oversized = "A".repeat(423 Math.ceil((SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES * 4) / 3) + 128,424 );425 await adapter.applyEntries({ ...envelopes, "oversized-id": oversized });426427 428 expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Updated");429 expect(vault.getEntries().some((e) => e.id === "oversized-id")).toBe(false);430 });431432 it("MV-3: applyTombstones throws when the batch exceeds MAX_TOMBSTONE_COUNT", async () => {433 const { adapter } = await setupVault();434 const { SYNC_LIMITS } = await import("../shared/sync-limits");435 const tooMany: Record<string, number> = {};436 for (let i = 0; i <= SYNC_LIMITS.MAX_TOMBSTONE_COUNT; i++) tooMany[`id-${i}`] = i + 1;437 await expect(adapter.applyTombstones(tooMany)).rejects.toThrow(/exceeds limit/);438 });439440 it("buildOutgoingDeviceManifest signs manifestable paired devices and skips legacy entries without signing keys", async () => {441 const { adapter } = await setupVault();442 const { upsertPairedDevice } = await import("./paired-devices");443 await upsertPairedDevice({444 deviceId: "android-1",445 deviceName: "Pixel",446 deviceType: "android",447 longTermPublicKeyHex: "a".repeat(64),448 signingPublicKeyHex: await signingPubkeyHex("android-1"),449 wsPort: 49152,450 relayUrl: MESH_RELAY,451 pairedAt: 1_700_000_000_000,452 trustSource: "direct",453 });454 await upsertPairedDevice({455 deviceId: "legacy-android",456 deviceName: "Legacy Pixel",457 deviceType: "android",458 longTermPublicKeyHex: "b".repeat(64),459 pairedAt: 1_700_000_000_100,460 trustSource: "direct",461 });462463 const manifest = await adapter.buildOutgoingDeviceManifest?.();464 expect(manifest).toBeDefined();465 expect(manifest?.signatureHex).toMatch(/^[0-9a-f]{128}$/);466 expect(manifest?.body.devices).toHaveLength(1);467 expect(manifest?.body.devices[0]).toMatchObject({468 deviceId: "android-1",469 deviceName: "Pixel",470 deviceType: "android",471 longTermPublicKeyHex: "a".repeat(64),472 wsPort: 49152,473 relayUrl: MESH_RELAY,474 });475 });476477 it("v3 auto-admits same-vault manifest peers with an independent mesh route", async () => {478 const { vault, adapter } = await setupVault();479 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");480 const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");481 const { pubkeyToHex } = await import("../shared/sync-identity");482 const {483 findPairedDeviceById,484 listPairedDevices,485 upsertPairedDevice,486 } = await import("./paired-devices");487 const { listPendingVouchedDevices } = await import(488 "./pending-vouched-devices"489 );490491 const issuerId = "extension-issuer";492 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x24), issuerId);493 await upsertPairedDevice({494 deviceId: issuerId,495 deviceName: "Firefox",496 deviceType: "extension",497 longTermPublicKeyHex: "c".repeat(64),498 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),499 pairedAt: 1_700_000_000_000,500 trustSource: "direct",501 });502 await upsertPairedDevice({503 deviceId: "android-existing",504 deviceName: "Existing Pixel",505 deviceType: "android",506 longTermPublicKeyHex: "d".repeat(64),507 signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),508 pairedAt: 1_700_000_000_010,509 trustSource: "direct",510 });511512 const manifest = await buildSignedDeviceManifest(513 issuerId,514 [515 {516 deviceId: "android-new",517 deviceName: "New Pixel",518 deviceType: "android",519 longTermPublicKeyHex: "e".repeat(64),520 signingPublicKeyHex: await signingPubkeyHex("android-new"),521 wsPort: 51234,522 relayUrl: MESH_RELAY,523 pairedAt: 1_700_000_000_020,524 },525 {526 deviceId: "android-existing",527 deviceName: "Existing Pixel renamed",528 deviceType: "android",529 longTermPublicKeyHex: "d".repeat(64),530 signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),531 wsPort: 52345,532 relayUrl: MESH_RELAY,533 pairedAt: 1_700_000_000_030,534 },535 ],536 issuerKp.privateKey,537 );538539 await adapter.applyIncomingDeviceManifest?.(540 manifest,541 new Uint8Array(32).fill(0xcc),542 );543544 expect(await findPairedDeviceById("android-new")).toMatchObject({545 deviceName: "New Pixel",546 trustSource: "vouched",547 relayUrl: MESH_RELAY,548 });549 550 551 expect((await findPairedDeviceById("android-new"))?.rendezvousSecretHex).toBeUndefined();552 const { getPairSecret } = await import("./pair-secrets");553 await expect(getPairSecret("android-new", vault.getRootKeyHex())).resolves.toMatch(554 /^[0-9a-f]{64}$/,555 );556 const pending = await listPendingVouchedDevices();557 expect(pending).toEqual([]);558559 560 561 const existing = await findPairedDeviceById("android-existing");562 expect(existing).toMatchObject({563 deviceName: "Existing Pixel",564 longTermPublicKeyHex: "d".repeat(64),565 trustSource: "direct",566 wsPort: 52345,567 });568 expect((await listPairedDevices()).map((d) => d.deviceId).sort()).toEqual([569 "android-existing",570 "android-new",571 "extension-issuer",572 ]);573 });574575 it("drops manifest key replacement for an existing vouched device", async () => {576 const { adapter } = await setupVault();577 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");578 const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");579 const { pubkeyToHex } = await import("../shared/sync-identity");580 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");581 const issuerId = "extension-issuer";582 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x24), issuerId);583 await upsertPairedDevice({584 deviceId: issuerId,585 deviceName: "Firefox",586 deviceType: "extension",587 longTermPublicKeyHex: "c".repeat(64),588 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),589 pairedAt: 1,590 trustSource: "direct",591 });592 await upsertPairedDevice({593 deviceId: "android-existing",594 deviceName: "Pixel",595 deviceType: "android",596 longTermPublicKeyHex: "d".repeat(64),597 signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),598 pairedAt: 2,599 trustSource: "vouched",600 });601 const manifest = await buildSignedDeviceManifest(602 issuerId,603 [{604 deviceId: "android-existing",605 deviceName: "Pixel",606 deviceType: "android",607 longTermPublicKeyHex: "f".repeat(64),608 signingPublicKeyHex: await signingPubkeyHex("android-existing-new"),609 wsPort: 52345,610 pairedAt: 3,611 }],612 issuerKp.privateKey,613 );614 await adapter.applyIncomingDeviceManifest?.(manifest, new Uint8Array(32).fill(0xcc));615 await expect(findPairedDeviceById("android-existing")).resolves.toMatchObject({616 longTermPublicKeyHex: "d".repeat(64),617 });618 });619620 it("drops manifest replacement even when the device name changes", async () => {621 const { adapter } = await setupVault();622 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");623 const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");624 const { pubkeyToHex } = await import("../shared/sync-identity");625 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");626 const issuerId = "hostile-issuer";627 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x26), issuerId);628 await upsertPairedDevice({629 deviceId: issuerId,630 deviceName: "Old Laptop",631 deviceType: "extension",632 longTermPublicKeyHex: "c".repeat(64),633 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),634 pairedAt: 1,635 trustSource: "direct",636 });637 await upsertPairedDevice({638 deviceId: "android-existing",639 deviceName: "Spare Tablet",640 deviceType: "android",641 longTermPublicKeyHex: "d".repeat(64),642 signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),643 pairedAt: 2,644 trustSource: "direct",645 });646 const manifest = await buildSignedDeviceManifest(647 issuerId,648 [{649 deviceId: "android-existing",650 deviceName: "June's Primary Phone",651 deviceType: "android",652 longTermPublicKeyHex: "f".repeat(64),653 signingPublicKeyHex: await signingPubkeyHex("android-existing-new"),654 wsPort: 52345,655 pairedAt: 3,656 }],657 issuerKp.privateKey,658 );659 await adapter.applyIncomingDeviceManifest?.(manifest, new Uint8Array(32).fill(0xcc));660 await expect(findPairedDeviceById("android-existing")).resolves.toMatchObject({661 deviceName: "Spare Tablet",662 longTermPublicKeyHex: "d".repeat(64),663 });664 });665666 it("§C: a vouched peer's revocation evicts the device and permanently blocks re-vouching", async () => {667 const { adapter } = await setupVault();668 const { buildSignedDeviceManifest, signDeviceRevocation } = await import("../shared/device-manifest");669 const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");670 const { pubkeyToHex } = await import("../shared/sync-identity");671 const { findPairedDeviceById, isDeviceRevoked, upsertPairedDevice } =672 await import("./paired-devices");673674 const issuerId = "phone-issuer";675 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x27), issuerId);676 await upsertPairedDevice({677 deviceId: issuerId,678 deviceName: "Pixel",679 deviceType: "android",680 longTermPublicKeyHex: "c".repeat(64),681 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),682 pairedAt: 1,683 trustSource: "vouched",684 });685 await upsertPairedDevice({686 deviceId: "stolen-laptop",687 deviceName: "Old Laptop",688 deviceType: "extension",689 longTermPublicKeyHex: "d".repeat(64),690 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),691 pairedAt: 2,692 trustSource: "direct",693 });694695 const signedRevocation = await signDeviceRevocation(696 {697 deviceId: "stolen-laptop",698 longTermPublicKeyHex: "d".repeat(64),699 revokedAt: Date.now(),700 revokedByDeviceId: issuerId,701 },702 issuerKp.privateKey,703 );704 const revocation = await buildSignedDeviceManifest(705 issuerId,706 [],707 issuerKp.privateKey,708 { revoked: [signedRevocation] },709 );710 await adapter.applyIncomingDeviceManifest?.(711 revocation,712 new Uint8Array(32).fill(0xcc),713 );714715 expect(await findPairedDeviceById("stolen-laptop")).toBeNull();716 expect(await isDeviceRevoked("stolen-laptop")).toBe(true);717718 719 720 721 const revouch = await buildSignedDeviceManifest(722 issuerId,723 [724 {725 deviceId: "stolen-laptop",726 deviceName: "Old Laptop",727 deviceType: "extension",728 longTermPublicKeyHex: "d".repeat(64),729 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),730 pairedAt: Date.now() + 60_000,731 },732 ],733 issuerKp.privateKey,734 );735 await adapter.applyIncomingDeviceManifest?.(736 revouch,737 new Uint8Array(32).fill(0xcc),738 );739740 expect(await findPairedDeviceById("stolen-laptop")).toBeNull();741 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");742 expect(await listPendingVouchedDevices()).toHaveLength(0);743 });744745 it("§C: a peer cannot revoke US, and our outgoing manifest carries our revocations", async () => {746 const { adapter } = await setupVault();747 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");748 const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");749 const { pubkeyToHex } = await import("../shared/sync-identity");750 const {751 isDeviceRevoked,752 revokeDeviceById,753 upsertPairedDevice,754 } = await import("./paired-devices");755 const { getOrCreateDeviceId } = await import("./device-identity");756757 const ourDeviceId = await getOrCreateDeviceId();758 const issuerId = "phone-issuer";759 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x28), issuerId);760 await upsertPairedDevice({761 deviceId: issuerId,762 deviceName: "Pixel",763 deviceType: "android",764 longTermPublicKeyHex: "c".repeat(64),765 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),766 pairedAt: 1,767 trustSource: "direct",768 });769770 771 const selfRevoke = await buildSignedDeviceManifest(772 issuerId,773 [],774 issuerKp.privateKey,775 {776 revoked: [777 {778 deviceId: ourDeviceId,779 longTermPublicKeyHex: "e".repeat(64),780 revokedAt: Date.now(),781 revokedByDeviceId: issuerId,782 },783 ],784 },785 );786 await adapter.applyIncomingDeviceManifest?.(787 selfRevoke,788 new Uint8Array(32).fill(0xcc),789 );790 expect(await isDeviceRevoked(ourDeviceId)).toBe(false);791792 793 794 await upsertPairedDevice({795 deviceId: "retired-tablet",796 deviceName: "Retired Tablet",797 deviceType: "android",798 longTermPublicKeyHex: "f".repeat(64),799 signingPublicKeyHex: await signingPubkeyHex("retired-tablet"),800 pairedAt: 3,801 trustSource: "direct",802 });803 await revokeDeviceById("retired-tablet", ourDeviceId);804805 const outgoing = await adapter.buildOutgoingDeviceManifest?.();806 expect(outgoing?.body.revoked.map((r) => r.deviceId)).toEqual(["retired-tablet"]);807 expect(outgoing?.body.devices.map((d) => d.deviceId)).not.toContain("retired-tablet");808 });809810 811 812 813 814 815 it("a legacy row with no trustSource is not upgraded to direct by a manifest apply", async () => {816 const { adapter } = await setupVault();817 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");818 const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");819 const { pubkeyToHex } = await import("../shared/sync-identity");820 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");821 const { isRouteCapableMeshPeer } = await import("../shared/mesh-peer-role");822823 const issuerId = "android-legacy-issuer";824 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x25), issuerId);825 await upsertPairedDevice({826 deviceId: issuerId,827 deviceName: "Issuer Pixel",828 deviceType: "android",829 longTermPublicKeyHex: "1".repeat(64),830 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),831 pairedAt: 1_700_000_000_000,832 trustSource: "direct",833 });834835 836 837 const legacyId = "legacy-peer";838 const registry = local.peach_paired_devices_v3 as Array<Record<string, unknown>>;839 registry.push({840 deviceId: legacyId,841 deviceName: "Legacy Peer",842 deviceType: "android",843 longTermPublicKeyHex: "3".repeat(64),844 signingPublicKeyHex: await signingPubkeyHex(legacyId),845 rendezvousSecretHex: "9".repeat(64),846 relayUrl: MESH_RELAY,847 pairedAt: 1_700_000_000_000,848 });849850 const manifest = await buildSignedDeviceManifest(851 issuerId,852 [{853 deviceId: legacyId,854 deviceName: "Legacy Peer",855 deviceType: "android",856 longTermPublicKeyHex: "3".repeat(64),857 signingPublicKeyHex: await signingPubkeyHex(legacyId),858 relayUrl: MESH_RELAY,859 pairedAt: 1_700_000_000_000,860 }],861 issuerKp.privateKey,862 );863 await adapter.applyIncomingDeviceManifest?.(864 manifest,865 new Uint8Array(32).fill(0x11),866 );867868 const row = await findPairedDeviceById(legacyId);869 expect(row).not.toBeNull();870 871 expect(row?.trustSource).toBeUndefined();872 expect(row?.trustSource).not.toBe("direct");873 874 expect(isRouteCapableMeshPeer(row!)).toBe(false);875 });876877 it("accepts a manifest from the phone it paired with — mesh introduction runs in that direction", async () => {878 879 880 881 882 const { adapter } = await setupVault();883 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");884 const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");885 const { pubkeyToHex } = await import("../shared/sync-identity");886 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");887 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");888 const vault = await import("./vault");889890 const mobileIssuerId = "android-issuer";891 const mobileIssuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x25), mobileIssuerId);892 await upsertPairedDevice({893 deviceId: mobileIssuerId,894 deviceName: "Issuer Pixel",895 deviceType: "android",896 longTermPublicKeyHex: "1".repeat(64),897 signingPublicKeyHex: pubkeyToHex(mobileIssuerKp.publicKeyRaw),898 pairedAt: 1_700_000_000_000,899 trustSource: "direct",900 });901 const mobileManifest = await buildSignedDeviceManifest(902 mobileIssuerId,903 [{904 deviceId: "mesh-peer",905 deviceName: "Other Pixel",906 deviceType: "android",907 longTermPublicKeyHex: "2".repeat(64),908 signingPublicKeyHex: await signingPubkeyHex("mesh-peer"),909 relayUrl: MESH_RELAY,910 pairedAt: 1_700_000_000_010,911 }],912 mobileIssuerKp.privateKey,913 );914 await adapter.applyIncomingDeviceManifest?.(915 mobileManifest,916 new Uint8Array(32).fill(0x11),917 );918919 expect(await findPairedDeviceById("mesh-peer")).toMatchObject({920 trustSource: "vouched",921 relayUrl: MESH_RELAY,922 });923 expect((await findPairedDeviceById("mesh-peer"))?.rendezvousSecretHex).toBeUndefined();924 const { getPairSecret: getPairSecretMesh } = await import("./pair-secrets");925 await expect(getPairSecretMesh("mesh-peer", vault.getRootKeyHex())).resolves.toMatch(926 /^[0-9a-f]{64}$/,927 );928 expect(await listPendingVouchedDevices()).toEqual([]);929 });930931 it("applyIncomingDeviceManifest accepts vouched issuers but rejects unauthenticated and bad signatures", async () => {932 const { vault, adapter } = await setupVault();933 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");934 const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");935 const { pubkeyToHex } = await import("../shared/sync-identity");936 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");937 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");938939 940 941 942 const vouchedIssuerId = "android-vouched-issuer";943 const vouchedKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x25), vouchedIssuerId);944 await upsertPairedDevice({945 deviceId: vouchedIssuerId,946 deviceName: "Second-hand Pixel",947 deviceType: "android",948 longTermPublicKeyHex: "1".repeat(64),949 signingPublicKeyHex: pubkeyToHex(vouchedKp.publicKeyRaw),950 pairedAt: 1_700_000_000_000,951 trustSource: "vouched",952 });953 const onward = await buildSignedDeviceManifest(954 vouchedIssuerId,955 [{956 deviceId: "onward-mesh-peer",957 deviceName: "Other Pixel",958 deviceType: "android",959 longTermPublicKeyHex: "2".repeat(64),960 signingPublicKeyHex: await signingPubkeyHex("onward-mesh-peer"),961 relayUrl: MESH_RELAY,962 pairedAt: 1_700_000_000_010,963 }],964 vouchedKp.privateKey,965 );966 await adapter.applyIncomingDeviceManifest?.(967 onward,968 new Uint8Array(32).fill(0x11),969 );970 expect(await findPairedDeviceById("onward-mesh-peer")).toMatchObject({971 trustSource: "vouched",972 relayUrl: MESH_RELAY,973 });974 expect((await findPairedDeviceById("onward-mesh-peer"))?.rendezvousSecretHex).toBeUndefined();975 const { getPairSecret: getPairSecretOnward } = await import("./pair-secrets");976 await expect(getPairSecretOnward("onward-mesh-peer", vault.getRootKeyHex())).resolves.toMatch(977 /^[0-9a-f]{64}$/,978 );979 expect(await listPendingVouchedDevices()).toEqual([]);980981 const extensionIssuerId = "extension-bad-sig";982 const extensionKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x26), extensionIssuerId);983 await upsertPairedDevice({984 deviceId: extensionIssuerId,985 deviceName: "Chrome",986 deviceType: "extension",987 longTermPublicKeyHex: "3".repeat(64),988 signingPublicKeyHex: pubkeyToHex(extensionKp.publicKeyRaw),989 pairedAt: 1_700_000_000_020,990 trustSource: "direct",991 });992 const good = await buildSignedDeviceManifest(993 extensionIssuerId,994 [{995 deviceId: "forged-add",996 deviceName: "Forged Pixel",997 deviceType: "android",998 longTermPublicKeyHex: "4".repeat(64),999 signingPublicKeyHex: await signingPubkeyHex("forged-add"),1000 pairedAt: 1_700_000_000_030,1001 }],1002 extensionKp.privateKey,1003 );1004 await adapter.applyIncomingDeviceManifest?.(1005 good,1006 new Uint8Array(32).fill(0x44),1007 );1008 expect(await findPairedDeviceById("forged-add")).toBeNull();10091010 const forged = {1011 ...good,1012 signatureHex:1013 good.signatureHex.slice(0, 2) +1014 ((parseInt(good.signatureHex.slice(2, 4), 16) ^ 0xff).toString(16).padStart(2, "0")) +1015 good.signatureHex.slice(4),1016 };1017 await adapter.applyIncomingDeviceManifest?.(1018 forged,1019 new Uint8Array(32).fill(0x33),1020 );1021 expect(await findPairedDeviceById("forged-add")).toBeNull();1022 });10231024 it("rejects a manifest when the stored issuer signing key is stale", async () => {1025 const { vault, adapter } = await setupVault();1026 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");1027 const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");1028 const { pubkeyToHex } = await import("../shared/sync-identity");1029 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");10301031 const issuerId = "stale-key-android";1032 const rootHex = vault.getRootKeyHex()!;1033 const root = Uint8Array.from(rootHex.match(/../g)!.map((b) => parseInt(b, 16)));1034 const issuerKp = await deriveSyncSigningKeypair(root, issuerId);10351036 await upsertPairedDevice({1037 deviceId: issuerId,1038 deviceName: "Pixel",1039 deviceType: "android",1040 longTermPublicKeyHex: "c".repeat(64),1041 signingPublicKeyHex: "ff".repeat(32),1042 pairedAt: 1_700_000_000_000,1043 trustSource: "direct",1044 });10451046 const manifest = await buildSignedDeviceManifest(1047 issuerId,1048 [{1049 deviceId: "onward-peer",1050 deviceName: "Forwarded iPad",1051 deviceType: "extension",1052 longTermPublicKeyHex: "e".repeat(64),1053 signingPublicKeyHex: pubkeyToHex(1054 (await deriveSyncSigningKeypair(root, "onward-peer")).publicKeyRaw,1055 ),1056 relayUrl: MESH_RELAY,1057 pairedAt: 1_700_000_000_010,1058 }],1059 issuerKp.privateKey,1060 );10611062 await adapter.applyIncomingDeviceManifest?.(manifest, new Uint8Array(32).fill(0xcc));10631064 expect(await findPairedDeviceById("onward-peer")).toBeNull();1065 });10661067 it("S1: a manifest signed by one paired peer is refused over a session authenticated as another", async () => {1068 const { adapter } = await setupVault();1069 const { buildSignedDeviceManifest } = await import("../shared/device-manifest");1070 const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");1071 const { pubkeyToHex } = await import("../shared/sync-identity");1072 const { upsertPairedDevice } = await import("./paired-devices");1073 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");10741075 1076 1077 1078 const alphaKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x51), "peer-alpha");1079 const betaKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x52), "peer-beta");1080 await upsertPairedDevice({1081 deviceId: "peer-alpha",1082 deviceName: "Alpha",1083 deviceType: "android",1084 longTermPublicKeyHex: "a".repeat(64),1085 signingPublicKeyHex: pubkeyToHex(alphaKp.publicKeyRaw),1086 pairedAt: 1,1087 trustSource: "direct",1088 });1089 await upsertPairedDevice({1090 deviceId: "peer-beta",1091 deviceName: "Beta",1092 deviceType: "android",1093 longTermPublicKeyHex: "b".repeat(64),1094 signingPublicKeyHex: pubkeyToHex(betaKp.publicKeyRaw),1095 pairedAt: 2,1096 trustSource: "direct",1097 });10981099 const fromBeta = await buildSignedDeviceManifest(1100 "peer-beta",1101 [{1102 deviceId: "smuggled",1103 deviceName: "Smuggled",1104 deviceType: "android",1105 longTermPublicKeyHex: "5".repeat(64),1106 signingPublicKeyHex: await signingPubkeyHex("smuggled"),1107 relayUrl: MESH_RELAY,1108 pairedAt: 3,1109 }],1110 betaKp.privateKey,1111 );11121113 1114 await adapter.applyIncomingDeviceManifest?.(fromBeta, new Uint8Array(32).fill(0xaa));1115 expect(await listPendingVouchedDevices()).toEqual([]);11161117 1118 1119 await adapter.applyIncomingDeviceManifest?.(fromBeta, new Uint8Array(32).fill(0xbb));1120 const { findPairedDeviceById } = await import("./paired-devices");1121 expect(await findPairedDeviceById("smuggled")).toMatchObject({1122 trustSource: "vouched",1123 relayUrl: MESH_RELAY,1124 });1125 expect(await listPendingVouchedDevices()).toEqual([]);1126 });1127 it("S1: a revoked long-term key cannot walk back in under a fresh deviceId", async () => {1128 const { adapter } = await setupVault();1129 const { buildSignedDeviceManifest, signDeviceRevocation } = await import("../shared/device-manifest");1130 const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");1131 const { pubkeyToHex } = await import("../shared/sync-identity");1132 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");1133 const { listPendingVouchedDevices } = await import("./pending-vouched-devices");11341135 const issuerId = "phone-issuer";1136 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x53), issuerId);1137 const stolenKey = "d".repeat(64);1138 await upsertPairedDevice({1139 deviceId: issuerId,1140 deviceName: "Pixel",1141 deviceType: "android",1142 longTermPublicKeyHex: "c".repeat(64),1143 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),1144 pairedAt: 1,1145 trustSource: "direct",1146 });1147 await upsertPairedDevice({1148 deviceId: "stolen-laptop",1149 deviceName: "Old Laptop",1150 deviceType: "extension",1151 longTermPublicKeyHex: stolenKey,1152 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),1153 pairedAt: 2,1154 trustSource: "direct",1155 });1156 const signedRevocation = await signDeviceRevocation({1157 deviceId: "stolen-laptop",1158 longTermPublicKeyHex: stolenKey,1159 revokedAt: Date.now(),1160 revokedByDeviceId: issuerId,1161 }, issuerKp.privateKey);1162 const revoke = await buildSignedDeviceManifest(issuerId, [], issuerKp.privateKey, {1163 revoked: [signedRevocation],1164 });1165 await adapter.applyIncomingDeviceManifest?.(revoke, new Uint8Array(32).fill(0xcc));1166 expect(await findPairedDeviceById("stolen-laptop")).toBeNull();11671168 1169 1170 const renamed = await buildSignedDeviceManifest(1171 issuerId,1172 [{1173 deviceId: "stolen-laptop-mk2",1174 deviceName: "New Laptop",1175 deviceType: "extension",1176 longTermPublicKeyHex: stolenKey,1177 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),1178 relayUrl: MESH_RELAY,1179 pairedAt: Date.now(),1180 }],1181 issuerKp.privateKey,1182 );1183 await adapter.applyIncomingDeviceManifest?.(renamed, new Uint8Array(32).fill(0xcc));1184 expect(await listPendingVouchedDevices()).toEqual([]);1185 expect(await findPairedDeviceById("stolen-laptop-mk2")).toBeNull();11861187 1188 1189 const clean = await buildSignedDeviceManifest(1190 issuerId,1191 [{1192 deviceId: "stolen-laptop-mk2",1193 deviceName: "New Laptop",1194 deviceType: "extension",1195 longTermPublicKeyHex: "9".repeat(64),1196 signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),1197 relayUrl: MESH_RELAY,1198 pairedAt: Date.now(),1199 }],1200 issuerKp.privateKey,1201 );1202 await adapter.applyIncomingDeviceManifest?.(clean, new Uint8Array(32).fill(0xcc));1203 expect(await findPairedDeviceById("stolen-laptop-mk2")).toMatchObject({1204 trustSource: "vouched",1205 relayUrl: MESH_RELAY,1206 });1207 expect(await listPendingVouchedDevices()).toEqual([]);1208 });12091210 it("S1: a revoked key cannot be written onto a device we still trust", async () => {1211 const { adapter } = await setupVault();1212 const { buildSignedDeviceManifest, signDeviceRevocation } = await import("../shared/device-manifest");1213 const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");1214 const { pubkeyToHex } = await import("../shared/sync-identity");1215 const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");12161217 const issuerId = "phone-issuer";1218 const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x54), issuerId);1219 const revokedKey = "d".repeat(64);1220 await upsertPairedDevice({1221 deviceId: issuerId,1222 deviceName: "Pixel",1223 deviceType: "android",1224 longTermPublicKeyHex: "c".repeat(64),1225 signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),1226 pairedAt: 1,1227 trustSource: "direct",1228 });1229 await upsertPairedDevice({1230 deviceId: "trusted-tablet",1231 deviceName: "Tablet",1232 deviceType: "android",1233 longTermPublicKeyHex: "7".repeat(64),1234 signingPublicKeyHex: await signingPubkeyHex("trusted-tablet"),1235 pairedAt: 2,1236 trustSource: "direct",1237 });12381239 const signedRevocation = await signDeviceRevocation({1240 deviceId: "stolen-laptop",1241 longTermPublicKeyHex: revokedKey,1242 revokedAt: Date.now(),1243 revokedByDeviceId: issuerId,1244 }, issuerKp.privateKey);1245 const revoke = await buildSignedDeviceManifest(issuerId, [], issuerKp.privateKey, {1246 revoked: [signedRevocation],1247 });1248 await adapter.applyIncomingDeviceManifest?.(revoke, new Uint8Array(32).fill(0xcc));12491250 1251 1252 const rotate = await buildSignedDeviceManifest(1253 issuerId,1254 [{1255 deviceId: "trusted-tablet",1256 deviceName: "Tablet",1257 deviceType: "android",1258 longTermPublicKeyHex: revokedKey,1259 signingPublicKeyHex: await signingPubkeyHex("trusted-tablet"),1260 pairedAt: 2,1261 }],1262 issuerKp.privateKey,1263 );1264 await adapter.applyIncomingDeviceManifest?.(rotate, new Uint8Array(32).fill(0xcc));1265 expect(await findPairedDeviceById("trusted-tablet")).toMatchObject({1266 longTermPublicKeyHex: "7".repeat(64),1267 });1268 });12691270 it("methods throw VaultLockedError when the vault is locked", async () => {1271 const { vault, adapter } = await setupVault();1272 vault.lock();1273 await expect(adapter.computeVaultId()).rejects.toMatchObject({ message: "vault_locked" });1274 await expect(adapter.buildEntryManifest()).rejects.toMatchObject({ message: "vault_locked" });1275 await expect(adapter.buildTombstoneManifest()).rejects.toMatchObject({ message: "vault_locked" });1276 await expect(adapter.getEncryptedEntries(["x"])).rejects.toMatchObject({ message: "vault_locked" });1277 await expect(adapter.applyEntries({ x: "AAAA" })).rejects.toMatchObject({ message: "vault_locked" });1278 await expect(adapter.applyTombstones({ x: 1 })).rejects.toMatchObject({ message: "vault_locked" });1279 await expect(adapter.buildOutgoingDeviceManifest?.()).rejects.toMatchObject({ message: "vault_locked" });1280 });1281});