sync-vault-adapter.test.ts

48.7 KB · raw

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 } = await import("../shared/legacy-identity-derivation.test-support");53    const { pubkeyToHex } = await import("../shared/sync-identity");54    const kp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x42), deviceId);55    return pubkeyToHex(kp.publicKeyRaw);56  }5758  it("computeVaultId returns a stable 64-char hex string for the same masterKey", async () => {59    const { adapter } = await setupVault();60    const id1 = await adapter.computeVaultId();61    const id2 = await adapter.computeVaultId();62    expect(id1).toBe(id2);63    expect(id1).toMatch(/^[0-9a-f]{64}$/);64  });6566  it("vault_id and sync signing key are unchanged after a password change (SEV-2-B)", async () => {67    const { vault, adapter } = await setupVault();68    const deviceId = await adapter.getOurDeviceId();69    const vaultIdBefore = await adapter.computeVaultId();7071    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");72    const { pubkeyToHex } = await import("../shared/sync-identity");73    const rootBefore = vault.getRootKeyHex()!;74    const unhex = (h: string) => Uint8Array.from(h.match(/../g)!.map((b) => parseInt(b, 16)));75    const signBefore = pubkeyToHex(76      (await deriveSyncSigningKeypair(unhex(rootBefore), deviceId)).publicKeyRaw,77    );7879    expect(await vault.changePassword("correct horse battery staple", "a different passphrase")).toBe(true);80    vault.lock();81    expect(await vault.unlock("a different passphrase")).toBe(true);8283    // vault_id derives from the stable root key, so it must not move.84    expect(await adapter.computeVaultId()).toBe(vaultIdBefore);85    const rootAfter = vault.getRootKeyHex()!;86    expect(rootAfter).toBe(rootBefore);87    const signAfter = pubkeyToHex(88      (await deriveSyncSigningKeypair(unhex(rootAfter), deviceId)).publicKeyRaw,89    );90    expect(signAfter).toBe(signBefore);91  });9293  it("getOurDeviceId is stable across calls and a fresh UUID v4 on first call", async () => {94    const { adapter } = await setupVault();95    const id1 = await adapter.getOurDeviceId();96    const id2 = await adapter.getOurDeviceId();97    expect(id1).toBe(id2);98    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}$/);99  });100101  it("buildEntryManifest reports {id: modifiedAt} for live entries only", async () => {102    const { vault, adapter } = await setupVault();103    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });104    const b = await vault.addEntry({ type: "login", title: "Beta", password: "pw" });105    await vault.deleteEntry(b.id);106    const m = await adapter.buildEntryManifest();107    expect(Object.keys(m).sort()).toEqual([a.id]);108    expect(m[a.id]).toBe(a.modifiedAt);109  });110111  it("buildTombstoneManifest reports {id: deletedAt} for soft-deleted entries", async () => {112    const { vault, adapter } = await setupVault();113    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });114    await vault.deleteEntry(a.id);115    const t = await adapter.buildTombstoneManifest();116    expect(Object.keys(t)).toEqual([a.id]);117    expect(typeof t[a.id]).toBe("number");118    expect(t[a.id]).toBeGreaterThan(0);119  });120121  it("buildTombstoneManifest retains ids after a full-entry purge", async () => {122    const { vault, adapter } = await setupVault();123    const entry = await vault.addEntry({ type: "login", title: "Purged", password: "pw" });124    await vault.deleteEntry(entry.id);125    const deletedAt = vault.getDeletedEntries().find((item) => item.id === entry.id)!.deletedAt!;126127    await vault.purgeEntry(entry.id);128129    expect(await adapter.buildTombstoneManifest()).toEqual({ [entry.id]: deletedAt });130  });131132  it("getEncryptedEntries returns opaque base64 strings keyed by id", async () => {133    const { vault, adapter } = await setupVault();134    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });135    const env = await adapter.getEncryptedEntries([a.id]);136    expect(Object.keys(env)).toEqual([a.id]);137    expect(env[a.id]).toMatch(/^[A-Za-z0-9+/]+=*$/);138    // Plaintext title must not be visible in the envelope.139    expect(env[a.id]).not.toContain("Alpha");140  });141142  it("getEncryptedEntries silently skips unknown ids (peer may have a manifest item we dropped)", async () => {143    const { adapter } = await setupVault();144    const env = await adapter.getEncryptedEntries(["does-not-exist"]);145    expect(env).toEqual({});146  });147148  it("encryption uses a fresh nonce per call — same entry yields different envelopes", async () => {149    const { vault, adapter } = await setupVault();150    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });151    const e1 = await adapter.getEncryptedEntries([a.id]);152    const e2 = await adapter.getEncryptedEntries([a.id]);153    expect(e1[a.id]).not.toBe(e2[a.id]);154  });155156  it("round-trips: encrypt on one adapter, apply on a fresh import of the same vault", async () => {157    const { vault, adapter } = await setupVault();158    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "secret", url: "https://a.example" });159    const envelopes = await adapter.getEncryptedEntries([a.id]);160    // Simulate a remote vault by bumping modifiedAt on the envelope's source161    // and then applying it back — we can't easily fork the module's storage,162    // so we just verify decrypt path by overwriting modifiedAt locally.163    // Delete the local entry first, then apply the envelope — applyMergedRemoteEntries164    // will re-add it because the local copy is tombstoned with an OLDER ts (since165    // we set modifiedAt forward by 1s in the new envelope payload).166    // Instead, simpler proof: apply the envelope as-is to a fresh adapter import.167    vault.lock();168    await vault.unlock("correct horse battery staple");169    const { createSyncVaultAdapter } = await import("./sync-vault-adapter");170    const adapter2 = createSyncVaultAdapter();171    // applyEntries should be a no-op when local mtime >= envelope mtime172    await adapter2.applyEntries(envelopes);173    expect(vault.getEntries().find((e) => e.id === a.id)?.title).toBe("Alpha");174  });175176  it("applyEntries decrypts and merges newer remote entries (last-write-wins)", async () => {177    const { vault, adapter } = await setupVault();178    const local = await vault.addEntry({ type: "login", title: "Original", password: "pw" });179    // Manually produce a fresher remote envelope by encrypting an updated entry shape.180    // We can't easily synthesise this without the entry key — so we use a second181    // adapter instance backed by the same vault, after mutating the underlying entry.182    await vault.updateEntry(local.id, { title: "Updated" });183    const newer = vault.getEntries().find((e) => e.id === local.id);184    expect(newer?.title).toBe("Updated");185    const envelopes = await adapter.getEncryptedEntries([local.id]);186    // Now revert the local entry to an older mtime by re-creating from scratch via187    // applyMergedRemoteEntries — but we'd loop. The most reliable proof of the188    // decrypt+merge path is that applyEntries on a fresher envelope keeps the189    // newer state, and on an older envelope is a no-op. We've covered the no-op190    // path above; for the apply path, simulate by replacing the in-memory entry191    // with an older copy and re-running applyEntries.192    const older: typeof local = { ...local, modifiedAt: local.modifiedAt - 1000, title: "Stale" };193    await vault.restoreEntries([older], "replace");194    expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Stale");195    await adapter.applyEntries(envelopes);196    expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Updated");197  });198199  it("applyEntries rejects envelopes whose decrypted id differs from the map key", async () => {200    const { vault, adapter } = await setupVault();201    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });202    const env = await adapter.getEncryptedEntries([a.id]);203    // Re-key the envelope under a different id — adapter must refuse to merge it.204    const swapped: Record<string, string> = { "wrong-id": env[a.id] };205    await adapter.applyEntries(swapped);206    // Local entry remains unchanged; no new entry under "wrong-id"207    expect(vault.getEntries().map((e) => e.id)).toEqual([a.id]);208  });209210  it("entry_envelope_roundtrips_with_separated_info (HKDF separator)", async () => {211    const { vault, adapter } = await setupVault();212    const a = await vault.addEntry({ type: "login", title: "Original", password: "pw" });213    await vault.updateEntry(a.id, { title: "Fresh" });214    const envelopes = await adapter.getEncryptedEntries([a.id]);215    // Roll local back to an older copy, then apply: encrypt+decrypt both use the216    // null-byte-separated info, so the round-trip must succeed.217    const stale = { ...a, modifiedAt: a.modifiedAt - 1000, title: "Stale" };218    await vault.restoreEntries([stale], "replace");219    await adapter.applyEntries(envelopes);220    expect(vault.getEntries().find((e) => e.id === a.id)?.title).toBe("Fresh");221  });222223  it("legacy_info_envelope_fails_closed (HKDF separator wire break)", async () => {224    // Mint an envelope under the OLD, unseparated info (`entryId + suffix`) and225    // assert the patched adapter cannot decrypt it — it drops silently. Locks in226    // the conscious wire break and serves as the fixture for any future migration.227    const { vault, adapter } = await setupVault();228    const { HKDF } = await import("@stablelib/hkdf");229    const { SHA256 } = await import("@stablelib/sha256");230231    const masterHex = vault.getRootKeyHex()!;232    const masterKey = Uint8Array.from(masterHex.match(/../g)!.map((b) => parseInt(b, 16)));233    const entryId = crypto.randomUUID();234    const legacyInfo = new TextEncoder().encode(entryId + "sync-entry-v1"); // no \x00235    const raw = new HKDF(SHA256, masterKey, new Uint8Array(0), legacyInfo).expand(32);236    const key = await crypto.subtle.importKey("raw", raw.buffer as ArrayBuffer, { name: "AES-GCM" }, false, ["encrypt"]);237238    const entry = { id: entryId, type: "login", title: "LegacyOnly", password: "pw", createdAt: Date.now(), modifiedAt: Date.now() };239    const nonce = crypto.getRandomValues(new Uint8Array(12));240    const aad = new TextEncoder().encode("peach-sync-entry-v1");241    const ct = new Uint8Array(242      await crypto.subtle.encrypt(243        { name: "AES-GCM", iv: nonce.buffer as ArrayBuffer, additionalData: aad.buffer as ArrayBuffer, tagLength: 128 },244        key,245        new TextEncoder().encode(JSON.stringify(entry)).buffer as ArrayBuffer,246      ),247    );248    const envelope = new Uint8Array(nonce.length + ct.length);249    envelope.set(nonce, 0);250    envelope.set(ct, nonce.length);251    const legacyB64 = Buffer.from(envelope).toString("base64");252253    await adapter.applyEntries({ [entryId]: legacyB64 });254    // Decrypt fails under the new separated info → envelope dropped, entry absent.255    expect(vault.getEntries().some((e) => e.id === entryId)).toBe(false);256  });257258  it("applyTombstones soft-deletes locally-live entries with newer deletedAt", async () => {259    const { vault, adapter } = await setupVault();260    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });261    await adapter.applyTombstones({ [a.id]: a.modifiedAt + 10_000 });262    expect(vault.getEntries().find((e) => e.id === a.id)).toBeUndefined();263    expect(vault.getDeletedEntries().find((e) => e.id === a.id)).toBeDefined();264  });265266  it("applyTombstones leaves entries alone when local modifiedAt is newer", async () => {267    const { vault, adapter } = await setupVault();268    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });269    await adapter.applyTombstones({ [a.id]: a.modifiedAt - 10_000 });270    expect(vault.getEntries().find((e) => e.id === a.id)).toBeDefined();271  });272273  // --- MV-3: sync receive bounds ---274275  it("MV-3: applyEntries throws when the batch exceeds MAX_ENTRY_COUNT", async () => {276    const { adapter } = await setupVault();277    const { SYNC_LIMITS } = await import("../shared/sync-limits");278    const tooMany: Record<string, string> = {};279    for (let i = 0; i <= SYNC_LIMITS.MAX_ENTRY_COUNT; i++) tooMany[`id-${i}`] = "AAAA";280    await expect(adapter.applyEntries(tooMany)).rejects.toThrow(/exceeds limit/);281  });282283  it("MV-3: applyEntries skips an oversized envelope but still applies valid ones", async () => {284    const { vault, adapter } = await setupVault();285    const { SYNC_LIMITS } = await import("../shared/sync-limits");286    const local = await vault.addEntry({ type: "login", title: "Original", password: "pw" });287    await vault.updateEntry(local.id, { title: "Updated" });288    const envelopes = await adapter.getEncryptedEntries([local.id]);289    // Make the local copy stale so the valid envelope would win on merge.290    const older = { ...local, modifiedAt: local.modifiedAt - 1000, title: "Stale" };291    await vault.restoreEntries([older], "replace");292    expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Stale");293294    const oversized = "A".repeat(295      Math.ceil((SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES * 4) / 3) + 128,296    );297    await adapter.applyEntries({ ...envelopes, "oversized-id": oversized });298299    // The valid envelope applied; the oversized one was skipped (never decrypted).300    expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Updated");301    expect(vault.getEntries().some((e) => e.id === "oversized-id")).toBe(false);302  });303304  it("MV-3: applyTombstones throws when the batch exceeds MAX_TOMBSTONE_COUNT", async () => {305    const { adapter } = await setupVault();306    const { SYNC_LIMITS } = await import("../shared/sync-limits");307    const tooMany: Record<string, number> = {};308    for (let i = 0; i <= SYNC_LIMITS.MAX_TOMBSTONE_COUNT; i++) tooMany[`id-${i}`] = i + 1;309    await expect(adapter.applyTombstones(tooMany)).rejects.toThrow(/exceeds limit/);310  });311312  it("buildOutgoingDeviceManifest signs manifestable paired devices and skips legacy entries without signing keys", async () => {313    const { adapter } = await setupVault();314    const { upsertPairedDevice } = await import("./paired-devices");315    await upsertPairedDevice({316      deviceId: "android-1",317      deviceName: "Pixel",318      deviceType: "android",319      longTermPublicKeyHex: "a".repeat(64),320      signingPublicKeyHex: await signingPubkeyHex("android-1"),321      wsPort: 49152,322      relayUrl: MESH_RELAY,323      pairedAt: 1_700_000_000_000,324      trustSource: "direct",325    });326    await upsertPairedDevice({327      deviceId: "legacy-android",328      deviceName: "Legacy Pixel",329      deviceType: "android",330      longTermPublicKeyHex: "b".repeat(64),331      pairedAt: 1_700_000_000_100,332      trustSource: "direct",333    });334335    const manifest = await adapter.buildOutgoingDeviceManifest?.();336    expect(manifest).toBeDefined();337    expect(manifest?.signatureHex).toMatch(/^[0-9a-f]{128}$/);338    expect(manifest?.body.devices).toHaveLength(1);339    expect(manifest?.body.devices[0]).toMatchObject({340      deviceId: "android-1",341      deviceName: "Pixel",342      deviceType: "android",343      longTermPublicKeyHex: "a".repeat(64),344      wsPort: 49152,345      relayUrl: MESH_RELAY,346    });347  });348349  it("v3 auto-admits same-vault manifest peers with an independent mesh route", async () => {350    const { vault, adapter } = await setupVault();351    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");352    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");353    const { pubkeyToHex } = await import("../shared/sync-identity");354    const {355      findPairedDeviceById,356      listPairedDevices,357      upsertPairedDevice,358    } = await import("./paired-devices");359    const { listPendingVouchedDevices } = await import(360      "./pending-vouched-devices"361    );362363    const issuerId = "extension-issuer";364    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x24), issuerId);365    await upsertPairedDevice({366      deviceId: issuerId,367      deviceName: "Firefox",368      deviceType: "extension",369      longTermPublicKeyHex: "c".repeat(64),370      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),371      pairedAt: 1_700_000_000_000,372      trustSource: "direct",373    });374    await upsertPairedDevice({375      deviceId: "android-existing",376      deviceName: "Existing Pixel",377      deviceType: "android",378      longTermPublicKeyHex: "d".repeat(64),379      signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),380      pairedAt: 1_700_000_000_010,381      trustSource: "direct",382    });383384    const manifest = await buildSignedDeviceManifest(385      issuerId,386      [387        {388          deviceId: "android-new",389          deviceName: "New Pixel",390          deviceType: "android",391          longTermPublicKeyHex: "e".repeat(64),392          signingPublicKeyHex: await signingPubkeyHex("android-new"),393          wsPort: 51234,394          relayUrl: MESH_RELAY,395          pairedAt: 1_700_000_000_020,396        },397        {398          deviceId: "android-existing",399          deviceName: "Existing Pixel renamed",400          deviceType: "android",401          longTermPublicKeyHex: "d".repeat(64),402          signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),403          wsPort: 52345,404          relayUrl: MESH_RELAY,405          pairedAt: 1_700_000_000_030,406        },407      ],408      issuerKp.privateKey,409    );410411    await adapter.applyIncomingDeviceManifest?.(412      manifest,413      new Uint8Array(32).fill(0xcc),414    );415416    expect(await findPairedDeviceById("android-new")).toMatchObject({417      deviceName: "New Pixel",418      trustSource: "vouched",419      relayUrl: MESH_RELAY,420    });421    // PB-26-213: the row carries no reusable secret; it resolves from the422    // encrypted pair-secret record instead.423    expect((await findPairedDeviceById("android-new"))?.rendezvousSecretHex).toBeUndefined();424    const { getPairSecret } = await import("./pair-secrets");425    await expect(getPairSecret("android-new", vault.getRootKeyHex())).resolves.toMatch(426      /^[0-9a-f]{64}$/,427    );428    const pending = await listPendingVouchedDevices();429    expect(pending).toEqual([]);430431    // Immutable identity binding rejects remote key rewrites; metadata and432    // routing fields from the signed manifest still update.433    const existing = await findPairedDeviceById("android-existing");434    expect(existing).toMatchObject({435      deviceName: "Existing Pixel",436      longTermPublicKeyHex: "d".repeat(64),437      trustSource: "direct",438      wsPort: 52345,439    });440    expect((await listPairedDevices()).map((d) => d.deviceId).sort()).toEqual([441      "android-existing",442      "android-new",443      "extension-issuer",444    ]);445  });446447  it("drops manifest key replacement for an existing vouched device", async () => {448    const { adapter } = await setupVault();449    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");450    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");451    const { pubkeyToHex } = await import("../shared/sync-identity");452    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");453    const issuerId = "extension-issuer";454    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x24), issuerId);455    await upsertPairedDevice({456      deviceId: issuerId,457      deviceName: "Firefox",458      deviceType: "extension",459      longTermPublicKeyHex: "c".repeat(64),460      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),461      pairedAt: 1,462      trustSource: "direct",463    });464    await upsertPairedDevice({465      deviceId: "android-existing",466      deviceName: "Pixel",467      deviceType: "android",468      longTermPublicKeyHex: "d".repeat(64),469      signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),470      pairedAt: 2,471      trustSource: "vouched",472    });473    const manifest = await buildSignedDeviceManifest(474      issuerId,475      [{476        deviceId: "android-existing",477        deviceName: "Pixel",478        deviceType: "android",479        longTermPublicKeyHex: "f".repeat(64),480        signingPublicKeyHex: await signingPubkeyHex("android-existing-new"),481        wsPort: 52345,482        pairedAt: 3,483      }],484      issuerKp.privateKey,485    );486    await adapter.applyIncomingDeviceManifest?.(manifest, new Uint8Array(32).fill(0xcc));487    await expect(findPairedDeviceById("android-existing")).resolves.toMatchObject({488      longTermPublicKeyHex: "d".repeat(64),489    });490  });491492  it("drops manifest replacement even when the device name changes", async () => {493    const { adapter } = await setupVault();494    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");495    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");496    const { pubkeyToHex } = await import("../shared/sync-identity");497    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");498    const issuerId = "hostile-issuer";499    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x26), issuerId);500    await upsertPairedDevice({501      deviceId: issuerId,502      deviceName: "Old Laptop",503      deviceType: "extension",504      longTermPublicKeyHex: "c".repeat(64),505      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),506      pairedAt: 1,507      trustSource: "direct",508    });509    await upsertPairedDevice({510      deviceId: "android-existing",511      deviceName: "Spare Tablet",512      deviceType: "android",513      longTermPublicKeyHex: "d".repeat(64),514      signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),515      pairedAt: 2,516      trustSource: "direct",517    });518    const manifest = await buildSignedDeviceManifest(519      issuerId,520      [{521        deviceId: "android-existing",522        deviceName: "June's Primary Phone",523        deviceType: "android",524        longTermPublicKeyHex: "f".repeat(64),525        signingPublicKeyHex: await signingPubkeyHex("android-existing-new"),526        wsPort: 52345,527        pairedAt: 3,528      }],529      issuerKp.privateKey,530    );531    await adapter.applyIncomingDeviceManifest?.(manifest, new Uint8Array(32).fill(0xcc));532    await expect(findPairedDeviceById("android-existing")).resolves.toMatchObject({533      deviceName: "Spare Tablet",534      longTermPublicKeyHex: "d".repeat(64),535    });536  });537538  it("§C: a vouched peer's revocation evicts the device and permanently blocks re-vouching", async () => {539    const { adapter } = await setupVault();540    const { buildSignedDeviceManifest, signDeviceRevocation } = await import("../shared/device-manifest");541    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");542    const { pubkeyToHex } = await import("../shared/sync-identity");543    const { findPairedDeviceById, isDeviceRevoked, upsertPairedDevice } =544      await import("./paired-devices");545546    const issuerId = "phone-issuer";547    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x27), issuerId);548    await upsertPairedDevice({549      deviceId: issuerId,550      deviceName: "Pixel",551      deviceType: "android",552      longTermPublicKeyHex: "c".repeat(64),553      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),554      pairedAt: 1,555      trustSource: "vouched",556    });557    await upsertPairedDevice({558      deviceId: "stolen-laptop",559      deviceName: "Old Laptop",560      deviceType: "extension",561      longTermPublicKeyHex: "d".repeat(64),562      signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),563      pairedAt: 2,564      trustSource: "direct",565    });566567    const signedRevocation = await signDeviceRevocation(568      {569        deviceId: "stolen-laptop",570        longTermPublicKeyHex: "d".repeat(64),571        revokedAt: Date.now(),572        revokedByDeviceId: issuerId,573      },574      issuerKp.privateKey,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    // The stolen device is now vouched back in by a later manifest carrying a591    // fresh pairedAt — exactly the resurrection a timestamp-ordered design592    // would allow. It must not come back.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 } = await import("../shared/legacy-identity-derivation.test-support");621    const { pubkeyToHex } = await import("../shared/sync-identity");622    const {623      isDeviceRevoked,624      revokeDeviceById,625      upsertPairedDevice,626    } = await import("./paired-devices");627    const { getOrCreateDeviceId } = await import("./device-identity");628629    const ourDeviceId = await getOrCreateDeviceId();630    const issuerId = "phone-issuer";631    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x28), issuerId);632    await upsertPairedDevice({633      deviceId: issuerId,634      deviceName: "Pixel",635      deviceType: "android",636      longTermPublicKeyHex: "c".repeat(64),637      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),638      pairedAt: 1,639      trustSource: "direct",640    });641642    // A compromised peer tries to sever the mesh by revoking this device.643    const selfRevoke = await buildSignedDeviceManifest(644      issuerId,645      [],646      issuerKp.privateKey,647      {648        revoked: [649          {650            deviceId: ourDeviceId,651            longTermPublicKeyHex: "e".repeat(64),652            revokedAt: Date.now(),653            revokedByDeviceId: issuerId,654          },655        ],656      },657    );658    await adapter.applyIncomingDeviceManifest?.(659      selfRevoke,660      new Uint8Array(32).fill(0xcc),661    );662    expect(await isDeviceRevoked(ourDeviceId)).toBe(false);663664    // Our own revocations ride out in the manifest we build, and the revoked665    // device is absent from the vouched list.666    await upsertPairedDevice({667      deviceId: "retired-tablet",668      deviceName: "Retired Tablet",669      deviceType: "android",670      longTermPublicKeyHex: "f".repeat(64),671      signingPublicKeyHex: await signingPubkeyHex("retired-tablet"),672      pairedAt: 3,673      trustSource: "direct",674    });675    await revokeDeviceById("retired-tablet", ourDeviceId);676677    const outgoing = await adapter.buildOutgoingDeviceManifest?.();678    expect(outgoing?.body.revoked.map((r) => r.deviceId)).toEqual(["retired-tablet"]);679    expect(outgoing?.body.devices.map((d) => d.deviceId)).not.toContain("retired-tablet");680  });681682  // PB-26-116: rows written before `trustSource` existed carry no provenance.683  // The manifest-apply path used to default them to "direct", which is the684  // opposite of the fail-closed rule PB-26-006 established for the mesh routing685  // gate — a legacy row became a dial target, manifest issuer, and revocation-686  // repair participant on the strength of a signed manifest alone.687  it("a legacy row with no trustSource is not upgraded to direct by a manifest apply", async () => {688    const { adapter } = await setupVault();689    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");690    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");691    const { pubkeyToHex } = await import("../shared/sync-identity");692    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");693    const { isRouteCapableMeshPeer } = await import("../shared/mesh-peer-role");694695    const issuerId = "android-legacy-issuer";696    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x25), issuerId);697    await upsertPairedDevice({698      deviceId: issuerId,699      deviceName: "Issuer Pixel",700      deviceType: "android",701      longTermPublicKeyHex: "1".repeat(64),702      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),703      pairedAt: 1_700_000_000_000,704      trustSource: "direct",705    });706707    // A row predating the field: present in the registry, no recorded708    // provenance. Seeded through storage so no writer stamps a default.709    const legacyId = "legacy-peer";710    const registry = local.peach_paired_devices_v3 as Array<Record<string, unknown>>;711    registry.push({712      deviceId: legacyId,713      deviceName: "Legacy Peer",714      deviceType: "android",715      longTermPublicKeyHex: "3".repeat(64),716      signingPublicKeyHex: await signingPubkeyHex(legacyId),717      rendezvousSecretHex: "9".repeat(64),718      relayUrl: MESH_RELAY,719      pairedAt: 1_700_000_000_000,720    });721722    const manifest = await buildSignedDeviceManifest(723      issuerId,724      [{725        deviceId: legacyId,726        deviceName: "Legacy Peer",727        deviceType: "android",728        longTermPublicKeyHex: "3".repeat(64),729        signingPublicKeyHex: await signingPubkeyHex(legacyId),730        relayUrl: MESH_RELAY,731        pairedAt: 1_700_000_000_000,732      }],733      issuerKp.privateKey,734    );735    await adapter.applyIncomingDeviceManifest?.(736      manifest,737      new Uint8Array(32).fill(0x11),738    );739740    const row = await findPairedDeviceById(legacyId);741    expect(row).not.toBeNull();742    // Not silently promoted: unknown provenance stays unknown.743    expect(row?.trustSource).toBeUndefined();744    expect(row?.trustSource).not.toBe("direct");745    // And therefore not a routing authority.746    expect(isRouteCapableMeshPeer(row!)).toBe(false);747  });748749  it("accepts a manifest from the phone it paired with — mesh introduction runs in that direction", async () => {750    // The browser can never listen, so it joins the mesh THROUGH a native peer;751    // that peer is the one holding the peer list. A phone-issued manifest must752    // therefore be honoured. MV-7 still applies: the introduced device lands in753    // the pending queue, not the registry.754    const { adapter } = await setupVault();755    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");756    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");757    const { pubkeyToHex } = await import("../shared/sync-identity");758    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");759    const { listPendingVouchedDevices } = await import("./pending-vouched-devices");760    const vault = await import("./vault");761762    const mobileIssuerId = "android-issuer";763    const mobileIssuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x25), mobileIssuerId);764    await upsertPairedDevice({765      deviceId: mobileIssuerId,766      deviceName: "Issuer Pixel",767      deviceType: "android",768      longTermPublicKeyHex: "1".repeat(64),769      signingPublicKeyHex: pubkeyToHex(mobileIssuerKp.publicKeyRaw),770      pairedAt: 1_700_000_000_000,771      trustSource: "direct",772    });773    const mobileManifest = await buildSignedDeviceManifest(774      mobileIssuerId,775      [{776        deviceId: "mesh-peer",777        deviceName: "Other Pixel",778        deviceType: "android",779        longTermPublicKeyHex: "2".repeat(64),780        signingPublicKeyHex: await signingPubkeyHex("mesh-peer"),781        relayUrl: MESH_RELAY,782        pairedAt: 1_700_000_000_010,783      }],784      mobileIssuerKp.privateKey,785    );786    await adapter.applyIncomingDeviceManifest?.(787      mobileManifest,788      new Uint8Array(32).fill(0x11),789    );790791    expect(await findPairedDeviceById("mesh-peer")).toMatchObject({792      trustSource: "vouched",793      relayUrl: MESH_RELAY,794    });795    expect((await findPairedDeviceById("mesh-peer"))?.rendezvousSecretHex).toBeUndefined();796    const { getPairSecret: getPairSecretMesh } = await import("./pair-secrets");797    await expect(getPairSecretMesh("mesh-peer", vault.getRootKeyHex())).resolves.toMatch(798      /^[0-9a-f]{64}$/,799    );800    expect(await listPendingVouchedDevices()).toEqual([]);801  });802803  it("applyIncomingDeviceManifest accepts vouched issuers but rejects unauthenticated and bad signatures", async () => {804    const { vault, adapter } = await setupVault();805    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");806    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");807    const { pubkeyToHex } = await import("../shared/sync-identity");808    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");809    const { listPendingVouchedDevices } = await import("./pending-vouched-devices");810811    // Once admitted, a peer propagates the pool without relying on the device812    // that introduced it. The Noise-authenticated key and stored signing key813    // still bind the manifest to this known mesh member.814    const vouchedIssuerId = "android-vouched-issuer";815    const vouchedKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x25), vouchedIssuerId);816    await upsertPairedDevice({817      deviceId: vouchedIssuerId,818      deviceName: "Second-hand Pixel",819      deviceType: "android",820      longTermPublicKeyHex: "1".repeat(64),821      signingPublicKeyHex: pubkeyToHex(vouchedKp.publicKeyRaw),822      pairedAt: 1_700_000_000_000,823      trustSource: "vouched",824    });825    const onward = await buildSignedDeviceManifest(826      vouchedIssuerId,827      [{828        deviceId: "onward-mesh-peer",829        deviceName: "Other Pixel",830        deviceType: "android",831        longTermPublicKeyHex: "2".repeat(64),832        signingPublicKeyHex: await signingPubkeyHex("onward-mesh-peer"),833        relayUrl: MESH_RELAY,834        pairedAt: 1_700_000_000_010,835      }],836      vouchedKp.privateKey,837    );838    await adapter.applyIncomingDeviceManifest?.(839      onward,840      new Uint8Array(32).fill(0x11),841    );842    expect(await findPairedDeviceById("onward-mesh-peer")).toMatchObject({843      trustSource: "vouched",844      relayUrl: MESH_RELAY,845    });846    expect((await findPairedDeviceById("onward-mesh-peer"))?.rendezvousSecretHex).toBeUndefined();847    const { getPairSecret: getPairSecretOnward } = await import("./pair-secrets");848    await expect(getPairSecretOnward("onward-mesh-peer", vault.getRootKeyHex())).resolves.toMatch(849      /^[0-9a-f]{64}$/,850    );851    expect(await listPendingVouchedDevices()).toEqual([]);852853    const extensionIssuerId = "extension-bad-sig";854    const extensionKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x26), extensionIssuerId);855    await upsertPairedDevice({856      deviceId: extensionIssuerId,857      deviceName: "Chrome",858      deviceType: "extension",859      longTermPublicKeyHex: "3".repeat(64),860      signingPublicKeyHex: pubkeyToHex(extensionKp.publicKeyRaw),861      pairedAt: 1_700_000_000_020,862      trustSource: "direct",863    });864    const good = await buildSignedDeviceManifest(865      extensionIssuerId,866      [{867        deviceId: "forged-add",868        deviceName: "Forged Pixel",869        deviceType: "android",870        longTermPublicKeyHex: "4".repeat(64),871        signingPublicKeyHex: await signingPubkeyHex("forged-add"),872        pairedAt: 1_700_000_000_030,873      }],874      extensionKp.privateKey,875    );876    await adapter.applyIncomingDeviceManifest?.(877      good,878      new Uint8Array(32).fill(0x44),879    );880    expect(await findPairedDeviceById("forged-add")).toBeNull();881882    const forged = {883      ...good,884      signatureHex:885        good.signatureHex.slice(0, 2) +886        ((parseInt(good.signatureHex.slice(2, 4), 16) ^ 0xff).toString(16).padStart(2, "0")) +887        good.signatureHex.slice(4),888    };889    await adapter.applyIncomingDeviceManifest?.(890      forged,891      new Uint8Array(32).fill(0x33),892    );893    expect(await findPairedDeviceById("forged-add")).toBeNull();894  });895896  it("rejects a manifest when the stored issuer signing key is stale", async () => {897    const { vault, adapter } = await setupVault();898    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");899    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");900    const { pubkeyToHex } = await import("../shared/sync-identity");901    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");902903    const issuerId = "stale-key-android";904    const rootHex = vault.getRootKeyHex()!;905    const root = Uint8Array.from(rootHex.match(/../g)!.map((b) => parseInt(b, 16)));906    const issuerKp = await deriveSyncSigningKeypair(root, issuerId);907908    await upsertPairedDevice({909      deviceId: issuerId,910      deviceName: "Pixel",911      deviceType: "android",912      longTermPublicKeyHex: "c".repeat(64),913      signingPublicKeyHex: "ff".repeat(32),914      pairedAt: 1_700_000_000_000,915      trustSource: "direct",916    });917918    const manifest = await buildSignedDeviceManifest(919      issuerId,920      [{921        deviceId: "onward-peer",922        deviceName: "Forwarded iPad",923        deviceType: "extension",924        longTermPublicKeyHex: "e".repeat(64),925        signingPublicKeyHex: pubkeyToHex(926          (await deriveSyncSigningKeypair(root, "onward-peer")).publicKeyRaw,927        ),928        relayUrl: MESH_RELAY,929        pairedAt: 1_700_000_000_010,930      }],931      issuerKp.privateKey,932    );933934    await adapter.applyIncomingDeviceManifest?.(manifest, new Uint8Array(32).fill(0xcc));935936    expect(await findPairedDeviceById("onward-peer")).toBeNull();937  });938939  it("S1: a manifest signed by one paired peer is refused over a session authenticated as another", async () => {940    const { adapter } = await setupVault();941    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");942    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");943    const { pubkeyToHex } = await import("../shared/sync-identity");944    const { upsertPairedDevice } = await import("./paired-devices");945    const { listPendingVouchedDevices } = await import("./pending-vouched-devices");946947    // Both peers are DIRECTLY paired, so neither the trustSource gate nor an948    // unknown-key lookup can be what rejects this — only the binding between949    // the Noise-authenticated static key and the manifest's claimed issuer.950    const alphaKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x51), "peer-alpha");951    const betaKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x52), "peer-beta");952    await upsertPairedDevice({953      deviceId: "peer-alpha",954      deviceName: "Alpha",955      deviceType: "android",956      longTermPublicKeyHex: "a".repeat(64),957      signingPublicKeyHex: pubkeyToHex(alphaKp.publicKeyRaw),958      pairedAt: 1,959      trustSource: "direct",960    });961    await upsertPairedDevice({962      deviceId: "peer-beta",963      deviceName: "Beta",964      deviceType: "android",965      longTermPublicKeyHex: "b".repeat(64),966      signingPublicKeyHex: pubkeyToHex(betaKp.publicKeyRaw),967      pairedAt: 2,968      trustSource: "direct",969    });970971    const fromBeta = await buildSignedDeviceManifest(972      "peer-beta",973      [{974        deviceId: "smuggled",975        deviceName: "Smuggled",976        deviceType: "android",977        longTermPublicKeyHex: "5".repeat(64),978        signingPublicKeyHex: await signingPubkeyHex("smuggled"),979        relayUrl: MESH_RELAY,980        pairedAt: 3,981      }],982      betaKp.privateKey,983    );984985    // Delivered over a session Noise-authenticated as ALPHA.986    await adapter.applyIncomingDeviceManifest?.(fromBeta, new Uint8Array(32).fill(0xaa));987    expect(await listPendingVouchedDevices()).toEqual([]);988989    // Same manifest, same devices, delivered over BETA's session: it must land.990    // Without this control the assertion above could pass for any reason.991    await adapter.applyIncomingDeviceManifest?.(fromBeta, new Uint8Array(32).fill(0xbb));992    const { findPairedDeviceById } = await import("./paired-devices");993    expect(await findPairedDeviceById("smuggled")).toMatchObject({994      trustSource: "vouched",995      relayUrl: MESH_RELAY,996    });997    expect(await listPendingVouchedDevices()).toEqual([]);998  });999  it("S1: a revoked long-term key cannot walk back in under a fresh deviceId", async () => {1000    const { adapter } = await setupVault();1001    const { buildSignedDeviceManifest, signDeviceRevocation } = await import("../shared/device-manifest");1002    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");1003    const { pubkeyToHex } = await import("../shared/sync-identity");1004    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");1005    const { listPendingVouchedDevices } = await import("./pending-vouched-devices");10061007    const issuerId = "phone-issuer";1008    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x53), issuerId);1009    const stolenKey = "d".repeat(64);1010    await upsertPairedDevice({1011      deviceId: issuerId,1012      deviceName: "Pixel",1013      deviceType: "android",1014      longTermPublicKeyHex: "c".repeat(64),1015      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),1016      pairedAt: 1,1017      trustSource: "direct",1018    });1019    await upsertPairedDevice({1020      deviceId: "stolen-laptop",1021      deviceName: "Old Laptop",1022      deviceType: "extension",1023      longTermPublicKeyHex: stolenKey,1024      signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),1025      pairedAt: 2,1026      trustSource: "direct",1027    });1028    const signedRevocation = await signDeviceRevocation({1029      deviceId: "stolen-laptop",1030      longTermPublicKeyHex: stolenKey,1031      revokedAt: Date.now(),1032      revokedByDeviceId: issuerId,1033    }, issuerKp.privateKey);1034    const revoke = await buildSignedDeviceManifest(issuerId, [], issuerKp.privateKey, {1035      revoked: [signedRevocation],1036    });1037    await adapter.applyIncomingDeviceManifest?.(revoke, new Uint8Array(32).fill(0xcc));1038    expect(await findPairedDeviceById("stolen-laptop")).toBeNull();10391040    // deviceId is the issuer's to choose, so re-vouching the same key under a1041    // new one is free. Terminality has to follow the key, not the label.1042    const renamed = await buildSignedDeviceManifest(1043      issuerId,1044      [{1045        deviceId: "stolen-laptop-mk2",1046        deviceName: "New Laptop",1047        deviceType: "extension",1048        longTermPublicKeyHex: stolenKey,1049        signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),1050        relayUrl: MESH_RELAY,1051        pairedAt: Date.now(),1052      }],1053      issuerKp.privateKey,1054    );1055    await adapter.applyIncomingDeviceManifest?.(renamed, new Uint8Array(32).fill(0xcc));1056    expect(await listPendingVouchedDevices()).toEqual([]);1057    expect(await findPairedDeviceById("stolen-laptop-mk2")).toBeNull();10581059    // Control: the same fresh id carrying a key that was never revoked queues1060    // normally, so the rejection above is the key check and not the id.1061    const clean = await buildSignedDeviceManifest(1062      issuerId,1063      [{1064        deviceId: "stolen-laptop-mk2",1065        deviceName: "New Laptop",1066        deviceType: "extension",1067        longTermPublicKeyHex: "9".repeat(64),1068        signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),1069        relayUrl: MESH_RELAY,1070        pairedAt: Date.now(),1071      }],1072      issuerKp.privateKey,1073    );1074    await adapter.applyIncomingDeviceManifest?.(clean, new Uint8Array(32).fill(0xcc));1075    expect(await findPairedDeviceById("stolen-laptop-mk2")).toMatchObject({1076      trustSource: "vouched",1077      relayUrl: MESH_RELAY,1078    });1079    expect(await listPendingVouchedDevices()).toEqual([]);1080  });10811082  it("S1: a revoked key cannot be written onto a device we still trust", async () => {1083    const { adapter } = await setupVault();1084    const { buildSignedDeviceManifest, signDeviceRevocation } = await import("../shared/device-manifest");1085    const { deriveSyncSigningKeypair } = await import("../shared/legacy-identity-derivation.test-support");1086    const { pubkeyToHex } = await import("../shared/sync-identity");1087    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");10881089    const issuerId = "phone-issuer";1090    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x54), issuerId);1091    const revokedKey = "d".repeat(64);1092    await upsertPairedDevice({1093      deviceId: issuerId,1094      deviceName: "Pixel",1095      deviceType: "android",1096      longTermPublicKeyHex: "c".repeat(64),1097      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),1098      pairedAt: 1,1099      trustSource: "direct",1100    });1101    await upsertPairedDevice({1102      deviceId: "trusted-tablet",1103      deviceName: "Tablet",1104      deviceType: "android",1105      longTermPublicKeyHex: "7".repeat(64),1106      signingPublicKeyHex: await signingPubkeyHex("trusted-tablet"),1107      pairedAt: 2,1108      trustSource: "direct",1109    });11101111    const signedRevocation = await signDeviceRevocation({1112      deviceId: "stolen-laptop",1113      longTermPublicKeyHex: revokedKey,1114      revokedAt: Date.now(),1115      revokedByDeviceId: issuerId,1116    }, issuerKp.privateKey);1117    const revoke = await buildSignedDeviceManifest(issuerId, [], issuerKp.privateKey, {1118      revoked: [signedRevocation],1119    });1120    await adapter.applyIncomingDeviceManifest?.(revoke, new Uint8Array(32).fill(0xcc));11211122    // The manifest rotates a device we already trust onto the revoked key —1123    // the same re-admission dressed as a key rotation.1124    const rotate = await buildSignedDeviceManifest(1125      issuerId,1126      [{1127        deviceId: "trusted-tablet",1128        deviceName: "Tablet",1129        deviceType: "android",1130        longTermPublicKeyHex: revokedKey,1131        signingPublicKeyHex: await signingPubkeyHex("trusted-tablet"),1132        pairedAt: 2,1133      }],1134      issuerKp.privateKey,1135    );1136    await adapter.applyIncomingDeviceManifest?.(rotate, new Uint8Array(32).fill(0xcc));1137    expect(await findPairedDeviceById("trusted-tablet")).toMatchObject({1138      longTermPublicKeyHex: "7".repeat(64),1139    });1140  });11411142  it("methods throw VaultLockedError when the vault is locked", async () => {1143    const { vault, adapter } = await setupVault();1144    vault.lock();1145    await expect(adapter.computeVaultId()).rejects.toMatchObject({ message: "vault_locked" });1146    await expect(adapter.buildEntryManifest()).rejects.toMatchObject({ message: "vault_locked" });1147    await expect(adapter.buildTombstoneManifest()).rejects.toMatchObject({ message: "vault_locked" });1148    await expect(adapter.getEncryptedEntries(["x"])).rejects.toMatchObject({ message: "vault_locked" });1149    await expect(adapter.applyEntries({ x: "AAAA" })).rejects.toMatchObject({ message: "vault_locked" });1150    await expect(adapter.applyTombstones({ x: 1 })).rejects.toMatchObject({ message: "vault_locked" });1151    await expect(adapter.buildOutgoingDeviceManifest?.()).rejects.toMatchObject({ message: "vault_locked" });1152  });1153});