1import { beforeEach, describe, expect, it, vi } from "vitest";2import type { Mock } from "vitest";3import { generateKeyPairFromSeed } from "@stablelib/x25519";45678910111213141516type StorageShape = Record<string, unknown>;17const IDENTITY_KEY = "peach_local_identity_v4";18const LEGACY_IDENTITY_KEY = "peach_local_identity_v2";19const LEGACY_INFO = "peach-local-identity-v2";20const DEVICE_ID_KEY = "peach_device_id";2122let local: StorageShape;23let sync: StorageShape;24let session: StorageShape;25let localSet: Mock;26let syncSet: Mock;27let sessionSet: Mock;2829function installChromeStorageMock(): void {30 const makeArea = (store: StorageShape, set: Mock) => ({31 get: vi.fn(async (key?: string | string[]) => {32 if (!key) return store;33 if (typeof key === "string") return { [key]: store[key] };34 return key.reduce<Record<string, unknown>>((r, k) => {35 r[k] = store[k];36 return r;37 }, {});38 }),39 set,40 remove: vi.fn(async (key: string | string[]) => {41 for (const k of Array.isArray(key) ? key : [key]) delete store[k];42 }),43 });44 local = {};45 sync = {};46 session = {};47 localSet = vi.fn(async (next: Record<string, unknown>) => {48 Object.assign(local, next);49 });50 syncSet = vi.fn(async (next: Record<string, unknown>) => {51 Object.assign(sync, next);52 });53 sessionSet = vi.fn(async (next: Record<string, unknown>) => {54 Object.assign(session, next);55 });56 (globalThis as { chrome?: typeof chrome }).chrome = {57 storage: {58 local: makeArea(local, localSet),59 sync: makeArea(sync, syncSet),60 session: makeArea(session, sessionSet),61 },62 } as unknown as typeof chrome;63}6465function hexToBytes(hex: string): Uint8Array {66 const out = new Uint8Array(hex.length / 2);67 for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);68 return out;69}707172async function writeLegacyIdentity(payload: unknown): Promise<void> {73 const vault = await import("./vault");74 const aes = await import("./aes");75 const rootHex = vault.getRootKeyHex();76 if (!rootHex) throw new Error("unlocked vault required");77 const root = hexToBytes(rootHex);78 try {79 local[LEGACY_IDENTITY_KEY] = {80 v: 3,81 ...(await aes.encrypt(root, JSON.stringify(payload), LEGACY_INFO)),82 };83 } finally {84 root.fill(0);85 }86}8788interface StoredEnvelope {89 v: number;90 blob: { nonce: string; ciphertext: string; tag: string };91 ik: { root?: unknown; local?: unknown; pending?: unknown; pendingSalt?: string };92}9394function storedEnvelope(): StoredEnvelope {95 return local[IDENTITY_KEY] as StoredEnvelope;96}979899async function currentKeys(): Promise<{100 deviceId: string;101 longTermPublicKeyHex: string | undefined;102 signingPublicKeyHex: string | undefined;103 derivedPublicHex: string;104}> {105 const { getLocalPairingIdentity } = await import("./device-identity");106 const { identity, privateKey } = await getLocalPairingIdentity();107 return {108 deviceId: identity.deviceId,109 longTermPublicKeyHex: identity.longTermPublicKeyHex,110 signingPublicKeyHex: identity.signingPublicKeyHex,111 derivedPublicHex: Array.from(generateKeyPairFromSeed(privateKey).publicKey, (b) =>112 b.toString(16).padStart(2, "0"),113 ).join(""),114 };115}116117beforeEach(() => {118 vi.resetModules();119 installChromeStorageMock();120});121122describe("device-identity getOrCreateDeviceId (PCH-01-004)", () => {123 it("existing-only loaders refuse missing identity without probing or minting trust", async () => {124 const vault = await import("./vault");125 await vault.createVault("identity-test-password");126 const identity = await import("./device-identity");127 delete local[IDENTITY_KEY];128 delete local.peach_local_identity_initialized;129 delete session.peach_local_identity_session;130 local.peach_revocation_issuers_v1 = "corrupt";131 localSet.mockClear();132 await expect(identity.getExistingDeviceId()).rejects.toThrow("identity_migration_required");133 await expect(identity.getLocalPairingIdentity({ existingOnly: true })).rejects.toThrow("identity_migration_required");134 expect(localSet).not.toHaveBeenCalled();135 });136137 it("does not mint an identity over a corrupt verification archive", async () => {138 const vault = await import("./vault");139 await vault.createVault("identity-test-password");140 delete local[IDENTITY_KEY];141 delete local.peach_local_identity_initialized;142 delete session.peach_local_identity_session;143 local.peach_revocation_issuers_v1 = "corrupt";144 localSet.mockClear();145 const identity = await import("./device-identity");146 await expect(identity.getOrCreateDeviceId()).rejects.toThrow("trust_data_corrupted");147 expect(localSet).not.toHaveBeenCalled();148 });149150 it("raw secure-reset identity rotation does not recreate cleared issuer trust", async () => {151 const vault = await import("./vault");152 await vault.createVault("identity-test-password");153 const identity = await import("./device-identity");154 await identity.getOrCreateDeviceId();155 const { REVOCATION_ISSUERS_KEY, REVOCATIONS_KEY } = await import("./paired-devices");156 local[REVOCATION_ISSUERS_KEY] = [{ deviceId: "old", longTermPublicKeyHex: "a".repeat(64), signingPublicKeys: ["b".repeat(64)] }];157 local[REVOCATIONS_KEY] = [];158 const { browserGenerationIo } = await import("./sync-generation");159 expect(await browserGenerationIo.clearLegacyTrustState()).toBe(true);160 await identity.rotateDeviceId();161 expect(local[REVOCATION_ISSUERS_KEY]).toBeUndefined();162 expect(local[REVOCATIONS_KEY]).toBeUndefined();163 });164165 it("fresh_install_writes_id_to_local_only", async () => {166 const vault = await import("./vault");167 await vault.createVault("identity-test-password");168 const { getOrCreateDeviceId } = await import("./device-identity");169170 const id = await getOrCreateDeviceId();171 expect(typeof id).toBe("string");172 expect(id.length).toBeGreaterThan(0);173 expect(local[DEVICE_ID_KEY]).toBeUndefined();174 expect(local[IDENTITY_KEY]).toBeDefined();175 expect(syncSet).not.toHaveBeenCalled();176 });177178 it("returns_a_stable_id_across_calls", async () => {179 const vault = await import("./vault");180 await vault.createVault("identity-test-password");181 const { getOrCreateDeviceId } = await import("./device-identity");182183 const first = await getOrCreateDeviceId();184 const second = await getOrCreateDeviceId();185 expect(second).toBe(first);186 });187188 it("replaces_a_copied_local_id_when_adoption_reports_a_collision", async () => {189 const vault = await import("./vault");190 await vault.createVault("identity-test-password");191 const { getOrCreateDeviceId, rotateDeviceId } = await import("./device-identity");192193 const original = await getOrCreateDeviceId();194 const fresh = await rotateDeviceId();195 expect(fresh).not.toBe(original);196 expect(local[IDENTITY_KEY]).toBeDefined();197 expect(await getOrCreateDeviceId()).toBe(fresh);198 expect(syncSet).not.toHaveBeenCalled();199 });200});201202describe("device-identity frozen schema (campaign task 2.1)", () => {203 it("persists every frozen field with public values matching the private material", async () => {204 const vault = await import("./vault");205 await vault.createVault("identity-test-password");206 const { getOrCreateDeviceId } = await import("./device-identity");207208 const deviceId = await getOrCreateDeviceId();209 const keys = await currentKeys();210 expect(keys.deviceId).toBe(deviceId);211 212 213 expect(keys.longTermPublicKeyHex).toBe(keys.derivedPublicHex);214 expect(keys.longTermPublicKeyHex).toMatch(/^[0-9a-f]{64}$/);215 expect(keys.signingPublicKeyHex).toMatch(/^[0-9a-f]{64}$/);216 });217218 it("seals the private material instead of storing it in the clear", async () => {219 const vault = await import("./vault");220 await vault.createVault("identity-test-password");221 const { getOrCreateDeviceId, getLocalPairingIdentity } = await import("./device-identity");222 await getOrCreateDeviceId();223224 const { privateKey } = await getLocalPairingIdentity();225 const privateHex = Array.from(privateKey, (b) => b.toString(16).padStart(2, "0")).join("");226 const envelope = storedEnvelope();227 expect(envelope.v).toBe(4);228 expect(envelope.ik.root).toBeDefined();229 expect(envelope.ik.local).toBeDefined();230 expect(envelope.ik.pending).toBeUndefined();231 expect(JSON.stringify(envelope)).not.toContain(privateHex);232 });233234 it("completes a legacy random record in place instead of regenerating it", async () => {235 const vault = await import("./vault");236 await vault.createVault("identity-test-password");237 await writeLegacyIdentity({238 v: 2,239 deviceId: "legacy-device-id",240 x25519PrivateKeyHex: "11".repeat(32),241 ed25519SeedHex: "22".repeat(32),242 });243244 const { getOrCreateDeviceId } = await import("./device-identity");245 expect(await getOrCreateDeviceId()).toBe("legacy-device-id");246 247 248 expect(storedEnvelope().v).toBe(4);249 expect(local[LEGACY_IDENTITY_KEY]).toBeUndefined();250 const keys = await currentKeys();251 expect(keys.deviceId).toBe("legacy-device-id");252 expect(keys.longTermPublicKeyHex).toBe(253 Array.from(generateKeyPairFromSeed(hexToBytes("11".repeat(32))).publicKey, (b) =>254 b.toString(16).padStart(2, "0"),255 ).join(""),256 );257 });258259 it("rejects a frozen record whose stored public key does not match its private key", async () => {260 const vault = await import("./vault");261 await vault.createVault("identity-test-password");262 await writeLegacyIdentity({263 v: 3,264 deviceId: "tampered",265 x25519PrivateKeyHex: "11".repeat(32),266 x25519PublicKeyHex: "33".repeat(32),267 ed25519SeedHex: "22".repeat(32),268 ed25519PublicKeyHex: "44".repeat(32),269 createdAt: Date.now(),270 });271272 const { getOrCreateDeviceId } = await import("./device-identity");273 await expect(getOrCreateDeviceId()).rejects.toThrow("identity_migration_required");274 275 expect(local[IDENTITY_KEY]).toBeUndefined();276 });277278 it("rejects a frozen record that is missing fields rather than defaulting them", async () => {279 const vault = await import("./vault");280 await vault.createVault("identity-test-password");281 await writeLegacyIdentity({282 v: 3,283 deviceId: "missing-fields",284 x25519PrivateKeyHex: "11".repeat(32),285 ed25519SeedHex: "22".repeat(32),286 });287288 const { getOrCreateDeviceId } = await import("./device-identity");289 await expect(getOrCreateDeviceId()).rejects.toThrow("identity_migration_required");290 expect(local[IDENTITY_KEY]).toBeUndefined();291 });292293 it("rejects a partial legacy record instead of minting a replacement", async () => {294 const vault = await import("./vault");295 await vault.createVault("identity-test-password");296 await writeLegacyIdentity({297 v: 2,298 deviceId: "partial",299 x25519PrivateKeyHex: "11".repeat(32),300 });301302 const { getOrCreateDeviceId } = await import("./device-identity");303 await expect(getOrCreateDeviceId()).rejects.toThrow("identity_migration_required");304 expect(local[IDENTITY_KEY]).toBeUndefined();305 });306});307308describe("device-identity pre-vault wallet (adoption v2 prerequisite)", () => {309 it("mints and reads a durable identity with no vault present", async () => {310 const { preparePreVaultIdentity, readPreVaultIdentity } = await import("./device-identity");311 expect((await import("./vault")).isUnlocked()).toBe(false);312313 await preparePreVaultIdentity("local-password");314 const first = await readPreVaultIdentity("local-password");315 expect(first.deviceId.length).toBeGreaterThan(0);316 expect(first.longTermPublicKeyHex).toMatch(/^[0-9a-f]{64}$/);317318 319 const envelope = storedEnvelope();320 expect(envelope.ik.pending).toBeDefined();321 expect(envelope.ik.root).toBeUndefined();322 expect(envelope.ik.local).toBeUndefined();323 });324325 it("survives a browser restart that drops the session cache", async () => {326 const { preparePreVaultIdentity, readPreVaultIdentity } = await import("./device-identity");327 await preparePreVaultIdentity("local-password");328 const before = await readPreVaultIdentity("local-password");329330 331 for (const key of Object.keys(session)) delete session[key];332 vi.resetModules();333 const restarted = await import("./device-identity");334 const after = await restarted.readPreVaultIdentity("local-password");335336 expect(after.deviceId).toBe(before.deviceId);337 expect(after.longTermPublicKeyHex).toBe(before.longTermPublicKeyHex);338 expect(after.signingPublicKeyHex).toBe(before.signingPublicKeyHex);339 });340341 it("refuses the wrong password rather than minting a replacement", async () => {342 const { preparePreVaultIdentity, readPreVaultIdentity } = await import("./device-identity");343 await preparePreVaultIdentity("local-password");344 345 346 for (const key of Object.keys(session)) delete session[key];347348 await expect(readPreVaultIdentity("not-the-password")).rejects.toThrow(349 "identity_migration_required",350 );351 expect(storedEnvelope().ik.pending).toBeDefined();352 });353354 it("promotes the pre-vault identity to the vault wraps once the vault exists", async () => {355 const { preparePreVaultIdentity, readPreVaultIdentity, getOrCreateDeviceId } = await import(356 "./device-identity"357 );358 await preparePreVaultIdentity("local-password");359 const before = await readPreVaultIdentity("local-password");360361 const vault = await import("./vault");362 await vault.createVault("local-password");363 await readPreVaultIdentity("local-password");364365 const envelope = storedEnvelope();366 expect(envelope.ik.pending).toBeUndefined();367 expect(envelope.ik.root).toBeDefined();368 expect(envelope.ik.local).toBeDefined();369370 371 const after = await getOrCreateDeviceId();372 expect(after).toBe(before.deviceId);373 const keys = await currentKeys();374 expect(keys.longTermPublicKeyHex).toBe(before.longTermPublicKeyHex);375 expect(keys.signingPublicKeyHex).toBe(before.signingPublicKeyHex);376 });377378 it("refuses to regenerate the identity when no wrapping key is available", async () => {379 const vault = await import("./vault");380 await vault.createVault("identity-test-password");381 const { getOrCreateDeviceId } = await import("./device-identity");382 const real = await getOrCreateDeviceId();383384 385 386 delete storedEnvelope().ik.root;387 delete storedEnvelope().ik.local;388 for (const key of Object.keys(session)) delete session[key];389 await expect(getOrCreateDeviceId()).rejects.toThrow("identity_migration_required");390 expect(local[IDENTITY_KEY]).toBeDefined();391 expect(real.length).toBeGreaterThan(0);392 });393});394395describe("device-identity lifecycle (key rotation and duress)", () => {396 it("survives a password change followed by a sync-identity rotation", async () => {397 const vault = await import("./vault");398 await vault.createVault("first-password");399 const { getOrCreateDeviceId, getLocalPairingIdentity } = await import("./device-identity");400 const before = await getOrCreateDeviceId();401 const beforeKeys = await getLocalPairingIdentity();402403 expect(await vault.changePassword("first-password", "second-password")).toBe(true);404 expect((await vault.rotateSyncIdentity()).ok).toBe(true);405406 407 408 for (const key of Object.keys(session)) delete session[key];409 expect(await getOrCreateDeviceId()).toBe(before);410 const afterKeys = await getLocalPairingIdentity();411 expect(afterKeys.identity.longTermPublicKeyHex).toBe(beforeKeys.identity.longTermPublicKeyHex);412 expect(afterKeys.identity.signingPublicKeyHex).toBe(beforeKeys.identity.signingPublicKeyHex);413 });414415 it("does not serve the cached identity inside a duress session", async () => {416 const vault = await import("./vault");417 await vault.createVault("real-password");418 const { getOrCreateDeviceId, buildLocalIdentity } = await import("./device-identity");419 const real = await getOrCreateDeviceId();420 await vault.setupDuress("duress-password");421422 423 424 expect(await vault.unlock("duress-password")).toBe(true);425 expect(vault.isDecoyMode()).toBe(true);426 await expect(buildLocalIdentity()).rejects.toThrow("identity_migration_required");427 expect(real.length).toBeGreaterThan(0);428 });429430 it("refuses to mint a replacement when the record is missing but a vault exists", async () => {431 const vault = await import("./vault");432 await vault.createVault("identity-test-password");433 const { getOrCreateDeviceId } = await import("./device-identity");434 await getOrCreateDeviceId();435436 delete local[IDENTITY_KEY];437 for (const key of Object.keys(session)) delete session[key];438 await expect(getOrCreateDeviceId()).rejects.toThrow("identity_migration_required");439 expect(local[IDENTITY_KEY]).toBeUndefined();440 });441});