sync-vault-adapter.test.ts

48.1 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, pubkeyToHex } = await import("../shared/sync-identity");53    const kp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x42), deviceId);54    return pubkeyToHex(kp.publicKeyRaw);55  }5657  it("computeVaultId returns a stable 64-char hex string for the same masterKey", async () => {58    const { adapter } = await setupVault();59    const id1 = await adapter.computeVaultId();60    const id2 = await adapter.computeVaultId();61    expect(id1).toBe(id2);62    expect(id1).toMatch(/^[0-9a-f]{64}$/);63  });6465  it("vault_id and sync signing key are unchanged after a password change (SEV-2-B)", async () => {66    const { vault, adapter } = await setupVault();67    const deviceId = await adapter.getOurDeviceId();68    const vaultIdBefore = await adapter.computeVaultId();6970    const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");71    const rootBefore = vault.getRootKeyHex()!;72    const unhex = (h: string) => Uint8Array.from(h.match(/../g)!.map((b) => parseInt(b, 16)));73    const signBefore = pubkeyToHex(74      (await deriveSyncSigningKeypair(unhex(rootBefore), deviceId)).publicKeyRaw,75    );7677    expect(await vault.changePassword("correct horse battery staple", "a different passphrase")).toBe(true);78    vault.lock();79    expect(await vault.unlock("a different passphrase")).toBe(true);8081    // vault_id derives from the stable root key, so it must not move.82    expect(await adapter.computeVaultId()).toBe(vaultIdBefore);83    const rootAfter = vault.getRootKeyHex()!;84    expect(rootAfter).toBe(rootBefore);85    const signAfter = pubkeyToHex(86      (await deriveSyncSigningKeypair(unhex(rootAfter), deviceId)).publicKeyRaw,87    );88    expect(signAfter).toBe(signBefore);89  });9091  it("getOurDeviceId is stable across calls and a fresh UUID v4 on first call", async () => {92    const { adapter } = await setupVault();93    const id1 = await adapter.getOurDeviceId();94    const id2 = await adapter.getOurDeviceId();95    expect(id1).toBe(id2);96    expect(id1).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);97  });9899  it("buildEntryManifest reports {id: modifiedAt} for live entries only", async () => {100    const { vault, adapter } = await setupVault();101    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });102    const b = await vault.addEntry({ type: "login", title: "Beta", password: "pw" });103    await vault.deleteEntry(b.id);104    const m = await adapter.buildEntryManifest();105    expect(Object.keys(m).sort()).toEqual([a.id]);106    expect(m[a.id]).toBe(a.modifiedAt);107  });108109  it("buildTombstoneManifest reports {id: deletedAt} for soft-deleted entries", async () => {110    const { vault, adapter } = await setupVault();111    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });112    await vault.deleteEntry(a.id);113    const t = await adapter.buildTombstoneManifest();114    expect(Object.keys(t)).toEqual([a.id]);115    expect(typeof t[a.id]).toBe("number");116    expect(t[a.id]).toBeGreaterThan(0);117  });118119  it("buildTombstoneManifest retains ids after a full-entry purge", async () => {120    const { vault, adapter } = await setupVault();121    const entry = await vault.addEntry({ type: "login", title: "Purged", password: "pw" });122    await vault.deleteEntry(entry.id);123    const deletedAt = vault.getDeletedEntries().find((item) => item.id === entry.id)!.deletedAt!;124125    await vault.purgeEntry(entry.id);126127    expect(await adapter.buildTombstoneManifest()).toEqual({ [entry.id]: deletedAt });128  });129130  it("getEncryptedEntries returns opaque base64 strings keyed by id", async () => {131    const { vault, adapter } = await setupVault();132    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });133    const env = await adapter.getEncryptedEntries([a.id]);134    expect(Object.keys(env)).toEqual([a.id]);135    expect(env[a.id]).toMatch(/^[A-Za-z0-9+/]+=*$/);136    // Plaintext title must not be visible in the envelope.137    expect(env[a.id]).not.toContain("Alpha");138  });139140  it("getEncryptedEntries silently skips unknown ids (peer may have a manifest item we dropped)", async () => {141    const { adapter } = await setupVault();142    const env = await adapter.getEncryptedEntries(["does-not-exist"]);143    expect(env).toEqual({});144  });145146  it("encryption uses a fresh nonce per call — same entry yields different envelopes", async () => {147    const { vault, adapter } = await setupVault();148    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });149    const e1 = await adapter.getEncryptedEntries([a.id]);150    const e2 = await adapter.getEncryptedEntries([a.id]);151    expect(e1[a.id]).not.toBe(e2[a.id]);152  });153154  it("round-trips: encrypt on one adapter, apply on a fresh import of the same vault", async () => {155    const { vault, adapter } = await setupVault();156    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "secret", url: "https://a.example" });157    const envelopes = await adapter.getEncryptedEntries([a.id]);158    // Simulate a remote vault by bumping modifiedAt on the envelope's source159    // and then applying it back — we can't easily fork the module's storage,160    // so we just verify decrypt path by overwriting modifiedAt locally.161    // Delete the local entry first, then apply the envelope — applyMergedRemoteEntries162    // will re-add it because the local copy is tombstoned with an OLDER ts (since163    // we set modifiedAt forward by 1s in the new envelope payload).164    // Instead, simpler proof: apply the envelope as-is to a fresh adapter import.165    vault.lock();166    await vault.unlock("correct horse battery staple");167    const { createSyncVaultAdapter } = await import("./sync-vault-adapter");168    const adapter2 = createSyncVaultAdapter();169    // applyEntries should be a no-op when local mtime >= envelope mtime170    await adapter2.applyEntries(envelopes);171    expect(vault.getEntries().find((e) => e.id === a.id)?.title).toBe("Alpha");172  });173174  it("applyEntries decrypts and merges newer remote entries (last-write-wins)", async () => {175    const { vault, adapter } = await setupVault();176    const local = await vault.addEntry({ type: "login", title: "Original", password: "pw" });177    // Manually produce a fresher remote envelope by encrypting an updated entry shape.178    // We can't easily synthesise this without the entry key — so we use a second179    // adapter instance backed by the same vault, after mutating the underlying entry.180    await vault.updateEntry(local.id, { title: "Updated" });181    const newer = vault.getEntries().find((e) => e.id === local.id);182    expect(newer?.title).toBe("Updated");183    const envelopes = await adapter.getEncryptedEntries([local.id]);184    // Now revert the local entry to an older mtime by re-creating from scratch via185    // applyMergedRemoteEntries — but we'd loop. The most reliable proof of the186    // decrypt+merge path is that applyEntries on a fresher envelope keeps the187    // newer state, and on an older envelope is a no-op. We've covered the no-op188    // path above; for the apply path, simulate by replacing the in-memory entry189    // with an older copy and re-running applyEntries.190    const older: typeof local = { ...local, modifiedAt: local.modifiedAt - 1000, title: "Stale" };191    await vault.restoreEntries([older], "replace");192    expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Stale");193    await adapter.applyEntries(envelopes);194    expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Updated");195  });196197  it("applyEntries rejects envelopes whose decrypted id differs from the map key", async () => {198    const { vault, adapter } = await setupVault();199    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });200    const env = await adapter.getEncryptedEntries([a.id]);201    // Re-key the envelope under a different id — adapter must refuse to merge it.202    const swapped: Record<string, string> = { "wrong-id": env[a.id] };203    await adapter.applyEntries(swapped);204    // Local entry remains unchanged; no new entry under "wrong-id"205    expect(vault.getEntries().map((e) => e.id)).toEqual([a.id]);206  });207208  it("entry_envelope_roundtrips_with_separated_info (HKDF separator)", async () => {209    const { vault, adapter } = await setupVault();210    const a = await vault.addEntry({ type: "login", title: "Original", password: "pw" });211    await vault.updateEntry(a.id, { title: "Fresh" });212    const envelopes = await adapter.getEncryptedEntries([a.id]);213    // Roll local back to an older copy, then apply: encrypt+decrypt both use the214    // null-byte-separated info, so the round-trip must succeed.215    const stale = { ...a, modifiedAt: a.modifiedAt - 1000, title: "Stale" };216    await vault.restoreEntries([stale], "replace");217    await adapter.applyEntries(envelopes);218    expect(vault.getEntries().find((e) => e.id === a.id)?.title).toBe("Fresh");219  });220221  it("legacy_info_envelope_fails_closed (HKDF separator wire break)", async () => {222    // Mint an envelope under the OLD, unseparated info (`entryId + suffix`) and223    // assert the patched adapter cannot decrypt it — it drops silently. Locks in224    // the conscious wire break and serves as the fixture for any future migration.225    const { vault, adapter } = await setupVault();226    const { HKDF } = await import("@stablelib/hkdf");227    const { SHA256 } = await import("@stablelib/sha256");228229    const masterHex = vault.getRootKeyHex()!;230    const masterKey = Uint8Array.from(masterHex.match(/../g)!.map((b) => parseInt(b, 16)));231    const entryId = crypto.randomUUID();232    const legacyInfo = new TextEncoder().encode(entryId + "sync-entry-v1"); // no \x00233    const raw = new HKDF(SHA256, masterKey, new Uint8Array(0), legacyInfo).expand(32);234    const key = await crypto.subtle.importKey("raw", raw.buffer as ArrayBuffer, { name: "AES-GCM" }, false, ["encrypt"]);235236    const entry = { id: entryId, type: "login", title: "LegacyOnly", password: "pw", createdAt: Date.now(), modifiedAt: Date.now() };237    const nonce = crypto.getRandomValues(new Uint8Array(12));238    const aad = new TextEncoder().encode("peach-sync-entry-v1");239    const ct = new Uint8Array(240      await crypto.subtle.encrypt(241        { name: "AES-GCM", iv: nonce.buffer as ArrayBuffer, additionalData: aad.buffer as ArrayBuffer, tagLength: 128 },242        key,243        new TextEncoder().encode(JSON.stringify(entry)).buffer as ArrayBuffer,244      ),245    );246    const envelope = new Uint8Array(nonce.length + ct.length);247    envelope.set(nonce, 0);248    envelope.set(ct, nonce.length);249    const legacyB64 = Buffer.from(envelope).toString("base64");250251    await adapter.applyEntries({ [entryId]: legacyB64 });252    // Decrypt fails under the new separated info → envelope dropped, entry absent.253    expect(vault.getEntries().some((e) => e.id === entryId)).toBe(false);254  });255256  it("applyTombstones soft-deletes locally-live entries with newer deletedAt", async () => {257    const { vault, adapter } = await setupVault();258    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });259    await adapter.applyTombstones({ [a.id]: a.modifiedAt + 10_000 });260    expect(vault.getEntries().find((e) => e.id === a.id)).toBeUndefined();261    expect(vault.getDeletedEntries().find((e) => e.id === a.id)).toBeDefined();262  });263264  it("applyTombstones leaves entries alone when local modifiedAt is newer", async () => {265    const { vault, adapter } = await setupVault();266    const a = await vault.addEntry({ type: "login", title: "Alpha", password: "pw" });267    await adapter.applyTombstones({ [a.id]: a.modifiedAt - 10_000 });268    expect(vault.getEntries().find((e) => e.id === a.id)).toBeDefined();269  });270271  // --- MV-3: sync receive bounds ---272273  it("MV-3: applyEntries throws when the batch exceeds MAX_ENTRY_COUNT", async () => {274    const { adapter } = await setupVault();275    const { SYNC_LIMITS } = await import("../shared/sync-limits");276    const tooMany: Record<string, string> = {};277    for (let i = 0; i <= SYNC_LIMITS.MAX_ENTRY_COUNT; i++) tooMany[`id-${i}`] = "AAAA";278    await expect(adapter.applyEntries(tooMany)).rejects.toThrow(/exceeds limit/);279  });280281  it("MV-3: applyEntries skips an oversized envelope but still applies valid ones", async () => {282    const { vault, adapter } = await setupVault();283    const { SYNC_LIMITS } = await import("../shared/sync-limits");284    const local = await vault.addEntry({ type: "login", title: "Original", password: "pw" });285    await vault.updateEntry(local.id, { title: "Updated" });286    const envelopes = await adapter.getEncryptedEntries([local.id]);287    // Make the local copy stale so the valid envelope would win on merge.288    const older = { ...local, modifiedAt: local.modifiedAt - 1000, title: "Stale" };289    await vault.restoreEntries([older], "replace");290    expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Stale");291292    const oversized = "A".repeat(293      Math.ceil((SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES * 4) / 3) + 128,294    );295    await adapter.applyEntries({ ...envelopes, "oversized-id": oversized });296297    // The valid envelope applied; the oversized one was skipped (never decrypted).298    expect(vault.getEntries().find((e) => e.id === local.id)?.title).toBe("Updated");299    expect(vault.getEntries().some((e) => e.id === "oversized-id")).toBe(false);300  });301302  it("MV-3: applyTombstones throws when the batch exceeds MAX_TOMBSTONE_COUNT", async () => {303    const { adapter } = await setupVault();304    const { SYNC_LIMITS } = await import("../shared/sync-limits");305    const tooMany: Record<string, number> = {};306    for (let i = 0; i <= SYNC_LIMITS.MAX_TOMBSTONE_COUNT; i++) tooMany[`id-${i}`] = i + 1;307    await expect(adapter.applyTombstones(tooMany)).rejects.toThrow(/exceeds limit/);308  });309310  it("buildOutgoingDeviceManifest signs manifestable paired devices and skips legacy entries without signing keys", async () => {311    const { adapter } = await setupVault();312    const { upsertPairedDevice } = await import("./paired-devices");313    await upsertPairedDevice({314      deviceId: "android-1",315      deviceName: "Pixel",316      deviceType: "android",317      longTermPublicKeyHex: "a".repeat(64),318      signingPublicKeyHex: await signingPubkeyHex("android-1"),319      wsPort: 49152,320      relayUrl: MESH_RELAY,321      pairedAt: 1_700_000_000_000,322      trustSource: "direct",323    });324    await upsertPairedDevice({325      deviceId: "legacy-android",326      deviceName: "Legacy Pixel",327      deviceType: "android",328      longTermPublicKeyHex: "b".repeat(64),329      pairedAt: 1_700_000_000_100,330      trustSource: "direct",331    });332333    const manifest = await adapter.buildOutgoingDeviceManifest?.();334    expect(manifest).toBeDefined();335    expect(manifest?.signatureHex).toMatch(/^[0-9a-f]{128}$/);336    expect(manifest?.body.devices).toHaveLength(1);337    expect(manifest?.body.devices[0]).toMatchObject({338      deviceId: "android-1",339      deviceName: "Pixel",340      deviceType: "android",341      longTermPublicKeyHex: "a".repeat(64),342      wsPort: 49152,343      relayUrl: MESH_RELAY,344    });345  });346347  it("v3 auto-admits same-vault manifest peers with an independent mesh route", async () => {348    const { adapter } = await setupVault();349    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");350    const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");351    const {352      findPairedDeviceById,353      listPairedDevices,354      upsertPairedDevice,355    } = await import("./paired-devices");356    const { listPendingVouchedDevices } = await import(357      "./pending-vouched-devices"358    );359360    const issuerId = "extension-issuer";361    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x24), issuerId);362    await upsertPairedDevice({363      deviceId: issuerId,364      deviceName: "Firefox",365      deviceType: "extension",366      longTermPublicKeyHex: "c".repeat(64),367      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),368      pairedAt: 1_700_000_000_000,369      trustSource: "direct",370    });371    await upsertPairedDevice({372      deviceId: "android-existing",373      deviceName: "Existing Pixel",374      deviceType: "android",375      longTermPublicKeyHex: "d".repeat(64),376      signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),377      pairedAt: 1_700_000_000_010,378      trustSource: "direct",379    });380381    const manifest = await buildSignedDeviceManifest(382      issuerId,383      [384        {385          deviceId: "android-new",386          deviceName: "New Pixel",387          deviceType: "android",388          longTermPublicKeyHex: "e".repeat(64),389          signingPublicKeyHex: await signingPubkeyHex("android-new"),390          wsPort: 51234,391          relayUrl: MESH_RELAY,392          pairedAt: 1_700_000_000_020,393        },394        {395          deviceId: "android-existing",396          deviceName: "Existing Pixel renamed",397          deviceType: "android",398          longTermPublicKeyHex: "f".repeat(64),399          signingPublicKeyHex: await signingPubkeyHex("android-existing-new"),400          wsPort: 52345,401          relayUrl: MESH_RELAY,402          pairedAt: 1_700_000_000_030,403        },404      ],405      issuerKp.privateKey,406    );407408    await adapter.applyIncomingDeviceManifest?.(409      manifest,410      new Uint8Array(32).fill(0xcc),411    );412413    expect(await findPairedDeviceById("android-new")).toMatchObject({414      deviceName: "New Pixel",415      trustSource: "vouched",416      relayUrl: MESH_RELAY,417      rendezvousSecretHex: expect.stringMatching(/^[0-9a-f]{64}$/),418    });419    const pending = await listPendingVouchedDevices();420    expect(pending).toEqual([]);421422    // The already-paired device is still updated in place — but S5: the423    // third-party issuer does NOT get to rename it. Keys and ports propagate;424    // the locally-known name is what the user recognises and it stands.425    const existing = await findPairedDeviceById("android-existing");426    expect(existing).toMatchObject({427      deviceName: "Existing Pixel",428      longTermPublicKeyHex: "f".repeat(64),429      trustSource: "direct",430      wsPort: 52345,431    });432    expect((await listPairedDevices()).map((d) => d.deviceId).sort()).toEqual([433      "android-existing",434      "android-new",435      "extension-issuer",436    ]);437  });438439  it("MV-8d: records a DEVICE_KEY_ROTATED alert when an existing device's key changes in a manifest", async () => {440    const { adapter } = await setupVault();441    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");442    const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");443    const { upsertPairedDevice } = await import("./paired-devices");444    const { getPendingSyncAlerts } = await import("./sync-alerts");445446    const issuerId = "extension-issuer";447    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x24), issuerId);448    await upsertPairedDevice({449      deviceId: issuerId,450      deviceName: "Firefox",451      deviceType: "extension",452      longTermPublicKeyHex: "c".repeat(64),453      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),454      pairedAt: 1,455      trustSource: "direct",456    });457    await upsertPairedDevice({458      deviceId: "android-existing",459      deviceName: "Pixel",460      deviceType: "android",461      longTermPublicKeyHex: "d".repeat(64),462      signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),463      pairedAt: 2,464      trustSource: "direct",465    });466467    const manifest = await buildSignedDeviceManifest(468      issuerId,469      [470        {471          deviceId: "android-existing",472          deviceName: "Pixel",473          deviceType: "android",474          longTermPublicKeyHex: "f".repeat(64),475          signingPublicKeyHex: await signingPubkeyHex("android-existing-new"),476          wsPort: 52345,477          pairedAt: 3,478        },479      ],480      issuerKp.privateKey,481    );482483    await adapter.applyIncomingDeviceManifest?.(484      manifest,485      new Uint8Array(32).fill(0xcc),486    );487    // recordSyncAlerts is fire-and-forget — flush microtasks.488    for (let i = 0; i < 25; i++) await Promise.resolve();489490    const alerts = await getPendingSyncAlerts();491    expect(492      alerts.some(493        (a) => a.type === "DEVICE_KEY_ROTATED" && a.deviceName === "Pixel",494      ),495    ).toBe(true);496  });497498  it("S5: a rotation alert names the device from local state, not from the manifest", async () => {499    // A paired-but-hostile issuer relabels a device it is vouching for, hoping500    // the rotation alert reads as coming from a device the user trusts more.501    // The alert must show the name the user already knows, and the relabel502    // must not stick in the registry either.503    const { adapter } = await setupVault();504    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");505    const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");506    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");507    const { getPendingSyncAlerts } = await import("./sync-alerts");508509    const issuerId = "hostile-issuer";510    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x26), issuerId);511    await upsertPairedDevice({512      deviceId: issuerId,513      deviceName: "Old Laptop",514      deviceType: "extension",515      longTermPublicKeyHex: "c".repeat(64),516      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),517      pairedAt: 1,518      trustSource: "direct",519    });520    await upsertPairedDevice({521      deviceId: "android-existing",522      deviceName: "Spare Tablet",523      deviceType: "android",524      longTermPublicKeyHex: "d".repeat(64),525      signingPublicKeyHex: await signingPubkeyHex("android-existing-old"),526      pairedAt: 2,527      trustSource: "direct",528    });529530    const manifest = await buildSignedDeviceManifest(531      issuerId,532      [533        {534          deviceId: "android-existing",535          deviceName: "June's Primary Phone",536          deviceType: "android",537          longTermPublicKeyHex: "f".repeat(64),538          signingPublicKeyHex: await signingPubkeyHex("android-existing-new"),539          wsPort: 52345,540          pairedAt: 3,541        },542      ],543      issuerKp.privateKey,544    );545546    await adapter.applyIncomingDeviceManifest?.(547      manifest,548      new Uint8Array(32).fill(0xcc),549    );550    for (let i = 0; i < 25; i++) await Promise.resolve();551552    const alerts = await getPendingSyncAlerts();553    const rotation = alerts.find((a) => a.type === "DEVICE_KEY_ROTATED");554    expect(rotation?.deviceName).toBe("Spare Tablet");555    expect(rotation?.entryTitle).toBe("Spare Tablet");556    expect(alerts.some((a) => a.deviceName === "June's Primary Phone")).toBe(false);557558    // The key rotation itself still lands; only the name is refused.559    const stored = await findPairedDeviceById("android-existing");560    expect(stored).toMatchObject({561      deviceName: "Spare Tablet",562      longTermPublicKeyHex: "f".repeat(64),563    });564  });565566  it("§C: a vouched peer's revocation evicts the device and permanently blocks re-vouching", async () => {567    const { adapter } = await setupVault();568    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");569    const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");570    const { findPairedDeviceById, isDeviceRevoked, upsertPairedDevice } =571      await import("./paired-devices");572573    const issuerId = "phone-issuer";574    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x27), issuerId);575    await upsertPairedDevice({576      deviceId: issuerId,577      deviceName: "Pixel",578      deviceType: "android",579      longTermPublicKeyHex: "c".repeat(64),580      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),581      pairedAt: 1,582      trustSource: "vouched",583    });584    await upsertPairedDevice({585      deviceId: "stolen-laptop",586      deviceName: "Old Laptop",587      deviceType: "extension",588      longTermPublicKeyHex: "d".repeat(64),589      signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),590      pairedAt: 2,591      trustSource: "direct",592    });593594    const revocation = await buildSignedDeviceManifest(595      issuerId,596      [],597      issuerKp.privateKey,598      {599        revoked: [600          {601            deviceId: "stolen-laptop",602            longTermPublicKeyHex: "d".repeat(64),603            revokedAt: Date.now(),604            revokedByDeviceId: issuerId,605          },606        ],607      },608    );609    await adapter.applyIncomingDeviceManifest?.(610      revocation,611      new Uint8Array(32).fill(0xcc),612    );613614    expect(await findPairedDeviceById("stolen-laptop")).toBeNull();615    expect(await isDeviceRevoked("stolen-laptop")).toBe(true);616617    // The stolen device is now vouched back in by a later manifest carrying a618    // fresh pairedAt — exactly the resurrection a timestamp-ordered design619    // would allow. It must not come back.620    const revouch = await buildSignedDeviceManifest(621      issuerId,622      [623        {624          deviceId: "stolen-laptop",625          deviceName: "Old Laptop",626          deviceType: "extension",627          longTermPublicKeyHex: "d".repeat(64),628          signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),629          pairedAt: Date.now() + 60_000,630        },631      ],632      issuerKp.privateKey,633    );634    await adapter.applyIncomingDeviceManifest?.(635      revouch,636      new Uint8Array(32).fill(0xcc),637    );638639    expect(await findPairedDeviceById("stolen-laptop")).toBeNull();640    const { listPendingVouchedDevices } = await import("./pending-vouched-devices");641    expect(await listPendingVouchedDevices()).toHaveLength(0);642  });643644  it("§C: a peer cannot revoke US, and our outgoing manifest carries our revocations", async () => {645    const { adapter } = await setupVault();646    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");647    const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");648    const {649      isDeviceRevoked,650      revokeDeviceById,651      upsertPairedDevice,652    } = await import("./paired-devices");653    const { getOrCreateDeviceId } = await import("./device-identity");654655    const ourDeviceId = await getOrCreateDeviceId();656    const issuerId = "phone-issuer";657    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x28), issuerId);658    await upsertPairedDevice({659      deviceId: issuerId,660      deviceName: "Pixel",661      deviceType: "android",662      longTermPublicKeyHex: "c".repeat(64),663      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),664      pairedAt: 1,665      trustSource: "direct",666    });667668    // A compromised peer tries to sever the mesh by revoking this device.669    const selfRevoke = await buildSignedDeviceManifest(670      issuerId,671      [],672      issuerKp.privateKey,673      {674        revoked: [675          {676            deviceId: ourDeviceId,677            longTermPublicKeyHex: "e".repeat(64),678            revokedAt: Date.now(),679            revokedByDeviceId: issuerId,680          },681        ],682      },683    );684    await adapter.applyIncomingDeviceManifest?.(685      selfRevoke,686      new Uint8Array(32).fill(0xcc),687    );688    expect(await isDeviceRevoked(ourDeviceId)).toBe(false);689690    // Our own revocations ride out in the manifest we build, and the revoked691    // device is absent from the vouched list.692    await upsertPairedDevice({693      deviceId: "retired-tablet",694      deviceName: "Retired Tablet",695      deviceType: "android",696      longTermPublicKeyHex: "f".repeat(64),697      signingPublicKeyHex: await signingPubkeyHex("retired-tablet"),698      pairedAt: 3,699      trustSource: "direct",700    });701    await revokeDeviceById("retired-tablet", ourDeviceId);702703    const outgoing = await adapter.buildOutgoingDeviceManifest?.();704    expect(outgoing?.body.revoked.map((r) => r.deviceId)).toEqual(["retired-tablet"]);705    expect(outgoing?.body.devices.map((d) => d.deviceId)).not.toContain("retired-tablet");706  });707708  // PB-26-116: rows written before `trustSource` existed carry no provenance.709  // The manifest-apply path used to default them to "direct", which is the710  // opposite of the fail-closed rule PB-26-006 established for the mesh routing711  // gate — a legacy row became a dial target, manifest issuer, and revocation-712  // repair participant on the strength of a signed manifest alone.713  it("a legacy row with no trustSource is not upgraded to direct by a manifest apply", async () => {714    const { adapter } = await setupVault();715    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");716    const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");717    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");718    const { isRouteCapableMeshPeer } = await import("../shared/mesh-peer-role");719720    const issuerId = "android-legacy-issuer";721    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x25), issuerId);722    await upsertPairedDevice({723      deviceId: issuerId,724      deviceName: "Issuer Pixel",725      deviceType: "android",726      longTermPublicKeyHex: "1".repeat(64),727      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),728      pairedAt: 1_700_000_000_000,729      trustSource: "direct",730    });731732    // A row predating the field: present in the registry, no recorded733    // provenance. Seeded through storage so no writer stamps a default.734    const legacyId = "legacy-peer";735    const registry = local.peach_paired_devices_v3 as Array<Record<string, unknown>>;736    registry.push({737      deviceId: legacyId,738      deviceName: "Legacy Peer",739      deviceType: "android",740      longTermPublicKeyHex: "3".repeat(64),741      signingPublicKeyHex: await signingPubkeyHex(legacyId),742      rendezvousSecretHex: "9".repeat(64),743      relayUrl: MESH_RELAY,744      pairedAt: 1_700_000_000_000,745    });746747    const manifest = await buildSignedDeviceManifest(748      issuerId,749      [{750        deviceId: legacyId,751        deviceName: "Legacy Peer",752        deviceType: "android",753        longTermPublicKeyHex: "3".repeat(64),754        signingPublicKeyHex: await signingPubkeyHex(legacyId),755        relayUrl: MESH_RELAY,756        pairedAt: 1_700_000_000_000,757      }],758      issuerKp.privateKey,759    );760    await adapter.applyIncomingDeviceManifest?.(761      manifest,762      new Uint8Array(32).fill(0x11),763    );764765    const row = await findPairedDeviceById(legacyId);766    expect(row).not.toBeNull();767    // Not silently promoted: unknown provenance stays unknown.768    expect(row?.trustSource).toBeUndefined();769    expect(row?.trustSource).not.toBe("direct");770    // And therefore not a routing authority.771    expect(isRouteCapableMeshPeer(row!)).toBe(false);772  });773774  it("accepts a manifest from the phone it paired with — mesh introduction runs in that direction", async () => {775    // The browser can never listen, so it joins the mesh THROUGH a native peer;776    // that peer is the one holding the peer list. A phone-issued manifest must777    // therefore be honoured. MV-7 still applies: the introduced device lands in778    // the pending queue, not the registry.779    const { adapter } = await setupVault();780    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");781    const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");782    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");783    const { listPendingVouchedDevices } = await import("./pending-vouched-devices");784785    const mobileIssuerId = "android-issuer";786    const mobileIssuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x25), mobileIssuerId);787    await upsertPairedDevice({788      deviceId: mobileIssuerId,789      deviceName: "Issuer Pixel",790      deviceType: "android",791      longTermPublicKeyHex: "1".repeat(64),792      signingPublicKeyHex: pubkeyToHex(mobileIssuerKp.publicKeyRaw),793      pairedAt: 1_700_000_000_000,794      trustSource: "direct",795    });796    const mobileManifest = await buildSignedDeviceManifest(797      mobileIssuerId,798      [{799        deviceId: "mesh-peer",800        deviceName: "Other Pixel",801        deviceType: "android",802        longTermPublicKeyHex: "2".repeat(64),803        signingPublicKeyHex: await signingPubkeyHex("mesh-peer"),804        relayUrl: MESH_RELAY,805        pairedAt: 1_700_000_000_010,806      }],807      mobileIssuerKp.privateKey,808    );809    await adapter.applyIncomingDeviceManifest?.(810      mobileManifest,811      new Uint8Array(32).fill(0x11),812    );813814    expect(await findPairedDeviceById("mesh-peer")).toMatchObject({815      trustSource: "vouched",816      relayUrl: MESH_RELAY,817      rendezvousSecretHex: expect.stringMatching(/^[0-9a-f]{64}$/),818    });819    expect(await listPendingVouchedDevices()).toEqual([]);820  });821822  it("applyIncomingDeviceManifest accepts vouched issuers but rejects unauthenticated and bad signatures", async () => {823    const { adapter } = await setupVault();824    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");825    const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");826    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");827    const { listPendingVouchedDevices } = await import("./pending-vouched-devices");828829    // Once admitted, a peer propagates the pool without relying on the device830    // that introduced it. The Noise-authenticated key and stored signing key831    // still bind the manifest to this known mesh member.832    const vouchedIssuerId = "android-vouched-issuer";833    const vouchedKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x25), vouchedIssuerId);834    await upsertPairedDevice({835      deviceId: vouchedIssuerId,836      deviceName: "Second-hand Pixel",837      deviceType: "android",838      longTermPublicKeyHex: "1".repeat(64),839      signingPublicKeyHex: pubkeyToHex(vouchedKp.publicKeyRaw),840      pairedAt: 1_700_000_000_000,841      trustSource: "vouched",842    });843    const onward = await buildSignedDeviceManifest(844      vouchedIssuerId,845      [{846        deviceId: "onward-mesh-peer",847        deviceName: "Other Pixel",848        deviceType: "android",849        longTermPublicKeyHex: "2".repeat(64),850        signingPublicKeyHex: await signingPubkeyHex("onward-mesh-peer"),851        relayUrl: MESH_RELAY,852        pairedAt: 1_700_000_000_010,853      }],854      vouchedKp.privateKey,855    );856    await adapter.applyIncomingDeviceManifest?.(857      onward,858      new Uint8Array(32).fill(0x11),859    );860    expect(await findPairedDeviceById("onward-mesh-peer")).toMatchObject({861      trustSource: "vouched",862      relayUrl: MESH_RELAY,863      rendezvousSecretHex: expect.stringMatching(/^[0-9a-f]{64}$/),864    });865    expect(await listPendingVouchedDevices()).toEqual([]);866867    const extensionIssuerId = "extension-bad-sig";868    const extensionKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x26), extensionIssuerId);869    await upsertPairedDevice({870      deviceId: extensionIssuerId,871      deviceName: "Chrome",872      deviceType: "extension",873      longTermPublicKeyHex: "3".repeat(64),874      signingPublicKeyHex: pubkeyToHex(extensionKp.publicKeyRaw),875      pairedAt: 1_700_000_000_020,876      trustSource: "direct",877    });878    const good = await buildSignedDeviceManifest(879      extensionIssuerId,880      [{881        deviceId: "forged-add",882        deviceName: "Forged Pixel",883        deviceType: "android",884        longTermPublicKeyHex: "4".repeat(64),885        signingPublicKeyHex: await signingPubkeyHex("forged-add"),886        pairedAt: 1_700_000_000_030,887      }],888      extensionKp.privateKey,889    );890    await adapter.applyIncomingDeviceManifest?.(891      good,892      new Uint8Array(32).fill(0x44),893    );894    expect(await findPairedDeviceById("forged-add")).toBeNull();895896    const forged = {897      ...good,898      signatureHex:899        good.signatureHex.slice(0, 2) +900        ((parseInt(good.signatureHex.slice(2, 4), 16) ^ 0xff).toString(16).padStart(2, "0")) +901        good.signatureHex.slice(4),902    };903    await adapter.applyIncomingDeviceManifest?.(904      forged,905      new Uint8Array(32).fill(0x33),906    );907    expect(await findPairedDeviceById("forged-add")).toBeNull();908  });909910  it("falls back to derived signing key when stored issuer key is stale", async () => {911    const { vault, adapter } = await setupVault();912    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");913    const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");914    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");915    const { listPendingVouchedDevices } = await import("./pending-vouched-devices");916917    const issuerId = "stale-key-android";918    const rootHex = vault.getRootKeyHex()!;919    const root = Uint8Array.from(rootHex.match(/../g)!.map((b) => parseInt(b, 16)));920    const issuerKp = await deriveSyncSigningKeypair(root, issuerId);921922    await upsertPairedDevice({923      deviceId: issuerId,924      deviceName: "Pixel",925      deviceType: "android",926      longTermPublicKeyHex: "c".repeat(64),927      // Stale: an older build persisted this at first-pair under a now-bad928      // seed. The fallback must recover from this without trusting the row.929      signingPublicKeyHex: "ff".repeat(32),930      pairedAt: 1_700_000_000_000,931      trustSource: "direct",932    });933934    const manifest = await buildSignedDeviceManifest(935      issuerId,936      [{937        deviceId: "onward-peer",938        deviceName: "Forwarded iPad",939        deviceType: "extension",940        longTermPublicKeyHex: "e".repeat(64),941        signingPublicKeyHex: pubkeyToHex(942          (await deriveSyncSigningKeypair(root, "onward-peer")).publicKeyRaw,943        ),944        relayUrl: MESH_RELAY,945        pairedAt: 1_700_000_000_010,946      }],947      issuerKp.privateKey,948    );949950    await adapter.applyIncomingDeviceManifest?.(951      manifest,952      new Uint8Array(32).fill(0xcc),953    );954955    expect(await findPairedDeviceById("onward-peer")).toMatchObject({956      trustSource: "vouched",957      relayUrl: MESH_RELAY,958      rendezvousSecretHex: expect.stringMatching(/^[0-9a-f]{64}$/),959    });960    expect(await listPendingVouchedDevices()).toEqual([]);961  });962963  it("S1: a manifest signed by one paired peer is refused over a session authenticated as another", async () => {964    const { adapter } = await setupVault();965    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");966    const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");967    const { upsertPairedDevice } = await import("./paired-devices");968    const { listPendingVouchedDevices } = await import("./pending-vouched-devices");969970    // Both peers are DIRECTLY paired, so neither the trustSource gate nor an971    // unknown-key lookup can be what rejects this — only the binding between972    // the Noise-authenticated static key and the manifest's claimed issuer.973    const alphaKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x51), "peer-alpha");974    const betaKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x52), "peer-beta");975    await upsertPairedDevice({976      deviceId: "peer-alpha",977      deviceName: "Alpha",978      deviceType: "android",979      longTermPublicKeyHex: "a".repeat(64),980      signingPublicKeyHex: pubkeyToHex(alphaKp.publicKeyRaw),981      pairedAt: 1,982      trustSource: "direct",983    });984    await upsertPairedDevice({985      deviceId: "peer-beta",986      deviceName: "Beta",987      deviceType: "android",988      longTermPublicKeyHex: "b".repeat(64),989      signingPublicKeyHex: pubkeyToHex(betaKp.publicKeyRaw),990      pairedAt: 2,991      trustSource: "direct",992    });993994    const fromBeta = await buildSignedDeviceManifest(995      "peer-beta",996      [{997        deviceId: "smuggled",998        deviceName: "Smuggled",999        deviceType: "android",1000        longTermPublicKeyHex: "5".repeat(64),1001        signingPublicKeyHex: await signingPubkeyHex("smuggled"),1002        relayUrl: MESH_RELAY,1003        pairedAt: 3,1004      }],1005      betaKp.privateKey,1006    );10071008    // Delivered over a session Noise-authenticated as ALPHA.1009    await adapter.applyIncomingDeviceManifest?.(fromBeta, new Uint8Array(32).fill(0xaa));1010    expect(await listPendingVouchedDevices()).toEqual([]);10111012    // Same manifest, same devices, delivered over BETA's session: it must land.1013    // Without this control the assertion above could pass for any reason.1014    await adapter.applyIncomingDeviceManifest?.(fromBeta, new Uint8Array(32).fill(0xbb));1015    const { findPairedDeviceById } = await import("./paired-devices");1016    expect(await findPairedDeviceById("smuggled")).toMatchObject({1017      trustSource: "vouched",1018      relayUrl: MESH_RELAY,1019    });1020    expect(await listPendingVouchedDevices()).toEqual([]);1021  });10221023  it("S1: a revoked long-term key cannot walk back in under a fresh deviceId", async () => {1024    const { adapter } = await setupVault();1025    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");1026    const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");1027    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");1028    const { listPendingVouchedDevices } = await import("./pending-vouched-devices");10291030    const issuerId = "phone-issuer";1031    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x53), issuerId);1032    const stolenKey = "d".repeat(64);1033    await upsertPairedDevice({1034      deviceId: issuerId,1035      deviceName: "Pixel",1036      deviceType: "android",1037      longTermPublicKeyHex: "c".repeat(64),1038      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),1039      pairedAt: 1,1040      trustSource: "direct",1041    });1042    await upsertPairedDevice({1043      deviceId: "stolen-laptop",1044      deviceName: "Old Laptop",1045      deviceType: "extension",1046      longTermPublicKeyHex: stolenKey,1047      signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),1048      pairedAt: 2,1049      trustSource: "direct",1050    });10511052    const revoke = await buildSignedDeviceManifest(issuerId, [], issuerKp.privateKey, {1053      revoked: [{1054        deviceId: "stolen-laptop",1055        longTermPublicKeyHex: stolenKey,1056        revokedAt: Date.now(),1057        revokedByDeviceId: issuerId,1058      }],1059    });1060    await adapter.applyIncomingDeviceManifest?.(revoke, new Uint8Array(32).fill(0xcc));1061    expect(await findPairedDeviceById("stolen-laptop")).toBeNull();10621063    // deviceId is the issuer's to choose, so re-vouching the same key under a1064    // new one is free. Terminality has to follow the key, not the label.1065    const renamed = await buildSignedDeviceManifest(1066      issuerId,1067      [{1068        deviceId: "stolen-laptop-mk2",1069        deviceName: "New Laptop",1070        deviceType: "extension",1071        longTermPublicKeyHex: stolenKey,1072        signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),1073        relayUrl: MESH_RELAY,1074        pairedAt: Date.now(),1075      }],1076      issuerKp.privateKey,1077    );1078    await adapter.applyIncomingDeviceManifest?.(renamed, new Uint8Array(32).fill(0xcc));1079    expect(await listPendingVouchedDevices()).toEqual([]);1080    expect(await findPairedDeviceById("stolen-laptop-mk2")).toBeNull();10811082    // Control: the same fresh id carrying a key that was never revoked queues1083    // normally, so the rejection above is the key check and not the id.1084    const clean = await buildSignedDeviceManifest(1085      issuerId,1086      [{1087        deviceId: "stolen-laptop-mk2",1088        deviceName: "New Laptop",1089        deviceType: "extension",1090        longTermPublicKeyHex: "9".repeat(64),1091        signingPublicKeyHex: await signingPubkeyHex("stolen-laptop"),1092        relayUrl: MESH_RELAY,1093        pairedAt: Date.now(),1094      }],1095      issuerKp.privateKey,1096    );1097    await adapter.applyIncomingDeviceManifest?.(clean, new Uint8Array(32).fill(0xcc));1098    expect(await findPairedDeviceById("stolen-laptop-mk2")).toMatchObject({1099      trustSource: "vouched",1100      relayUrl: MESH_RELAY,1101    });1102    expect(await listPendingVouchedDevices()).toEqual([]);1103  });11041105  it("S1: a revoked key cannot be written onto a device we still trust", async () => {1106    const { adapter } = await setupVault();1107    const { buildSignedDeviceManifest } = await import("../shared/device-manifest");1108    const { deriveSyncSigningKeypair, pubkeyToHex } = await import("../shared/sync-identity");1109    const { findPairedDeviceById, upsertPairedDevice } = await import("./paired-devices");11101111    const issuerId = "phone-issuer";1112    const issuerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x54), issuerId);1113    const revokedKey = "d".repeat(64);1114    await upsertPairedDevice({1115      deviceId: issuerId,1116      deviceName: "Pixel",1117      deviceType: "android",1118      longTermPublicKeyHex: "c".repeat(64),1119      signingPublicKeyHex: pubkeyToHex(issuerKp.publicKeyRaw),1120      pairedAt: 1,1121      trustSource: "direct",1122    });1123    await upsertPairedDevice({1124      deviceId: "trusted-tablet",1125      deviceName: "Tablet",1126      deviceType: "android",1127      longTermPublicKeyHex: "7".repeat(64),1128      signingPublicKeyHex: await signingPubkeyHex("trusted-tablet"),1129      pairedAt: 2,1130      trustSource: "direct",1131    });11321133    const revoke = await buildSignedDeviceManifest(issuerId, [], issuerKp.privateKey, {1134      revoked: [{1135        deviceId: "stolen-laptop",1136        longTermPublicKeyHex: revokedKey,1137        revokedAt: Date.now(),1138        revokedByDeviceId: issuerId,1139      }],1140    });1141    await adapter.applyIncomingDeviceManifest?.(revoke, new Uint8Array(32).fill(0xcc));11421143    // The manifest rotates a device we already trust onto the revoked key —1144    // the same re-admission dressed as a key rotation.1145    const rotate = await buildSignedDeviceManifest(1146      issuerId,1147      [{1148        deviceId: "trusted-tablet",1149        deviceName: "Tablet",1150        deviceType: "android",1151        longTermPublicKeyHex: revokedKey,1152        signingPublicKeyHex: await signingPubkeyHex("trusted-tablet"),1153        pairedAt: 2,1154      }],1155      issuerKp.privateKey,1156    );1157    await adapter.applyIncomingDeviceManifest?.(rotate, new Uint8Array(32).fill(0xcc));1158    expect(await findPairedDeviceById("trusted-tablet")).toMatchObject({1159      longTermPublicKeyHex: "7".repeat(64),1160    });1161  });11621163  it("methods throw VaultLockedError when the vault is locked", async () => {1164    const { vault, adapter } = await setupVault();1165    vault.lock();1166    await expect(adapter.computeVaultId()).rejects.toMatchObject({ message: "vault_locked" });1167    await expect(adapter.buildEntryManifest()).rejects.toMatchObject({ message: "vault_locked" });1168    await expect(adapter.buildTombstoneManifest()).rejects.toMatchObject({ message: "vault_locked" });1169    await expect(adapter.getEncryptedEntries(["x"])).rejects.toMatchObject({ message: "vault_locked" });1170    await expect(adapter.applyEntries({ x: "AAAA" })).rejects.toMatchObject({ message: "vault_locked" });1171    await expect(adapter.applyTombstones({ x: 1 })).rejects.toMatchObject({ message: "vault_locked" });1172    await expect(adapter.buildOutgoingDeviceManifest?.()).rejects.toMatchObject({ message: "vault_locked" });1173  });1174});