1import { beforeEach, describe, expect, it, vi } from "vitest";2import { decrypt } from "./aes";3import { deriveKey } from "../crypto/argon2";4import type { StoredVault } from "../shared/types";56type StorageShape = Record<string, unknown>;78function deferred(): { promise: Promise<void>; resolve: () => void } {9 let resolve!: () => void;10 const promise = new Promise<void>((done) => { resolve = done; });11 return { promise, resolve };12}1314describe("background vault", () => {15 let storage: StorageShape;16 let sessionStorage: StorageShape;17 let alarms = { created: [] as Array<{ name: string; delayInMinutes: number }>, cleared: [] as string[] };1819 beforeEach(() => {20 vi.resetModules();21 storage = {};22 sessionStorage = {};23 alarms = { created: [], cleared: [] };2425 const chromeMock = {26 storage: {27 local: {28 get: vi.fn(async (key?: string | string[]) => {29 if (!key) return storage;30 if (typeof key === "string") {31 return { [key]: storage[key] };32 }3334 return key.reduce<Record<string, unknown>>((result, entry) => {35 result[entry] = storage[entry];36 return result;37 }, {});38 }),39 set: vi.fn(async (next: Record<string, unknown>) => {40 Object.assign(storage, next);41 }),42 remove: vi.fn(async (keys: string | string[]) => {43 const list = Array.isArray(keys) ? keys : [keys];44 for (const key of list) {45 delete storage[key];46 }47 }),48 },49 session: {50 get: vi.fn(async (key?: string | string[]) => {51 if (!key) return sessionStorage;52 if (typeof key === "string") return { [key]: sessionStorage[key] };53 return key.reduce<Record<string, unknown>>((result, entry) => {54 result[entry] = sessionStorage[entry];55 return result;56 }, {});57 }),58 set: vi.fn(async (next: Record<string, unknown>) => {59 Object.assign(sessionStorage, next);60 }),61 remove: vi.fn(async (keys: string | string[]) => {62 const list = Array.isArray(keys) ? keys : [keys];63 for (const key of list) delete sessionStorage[key];64 }),65 clear: vi.fn(async () => {66 for (const key of Object.keys(sessionStorage)) delete sessionStorage[key];67 }),68 },69 },70 alarms: {71 clear: vi.fn((name: string) => {72 alarms.cleared.push(name);73 }),74 create: vi.fn((name: string, info: { delayInMinutes: number }) => {75 alarms.created.push({ name, delayInMinutes: info.delayInMinutes });76 }),77 onAlarm: { addListener: vi.fn() },78 },79 idle: {80 setDetectionInterval: vi.fn(),81 onStateChanged: { addListener: vi.fn() },82 },83 } as unknown as typeof chrome;8485 (globalThis as { chrome?: typeof chrome }).chrome = chromeMock;8687 88 vi.stubGlobal("fetch", vi.fn(async () => {89 throw new Error("network disabled in tests");90 }));91 });9293 it.each(["peach_vault_a", "peach_vault_b"].flatMap((slot) => [null, false, 0, {}, "broken"].map((value) => ({ slot, value }))))("refuses existing $slot value $value before deriving a password", async ({ slot, value }) => {94 storage[slot] = value;95 const argon = await import("../crypto/argon2");96 const derive = vi.spyOn(argon, "deriveKey");97 const vault = await import("./vault");98 await expect(vault.createVault("replacement-password")).rejects.toThrow("vault_already_exists");99 expect(derive).not.toHaveBeenCalled();100 expect(await vault.hasVault()).toBe(true);101 expect(storage[slot]).toEqual(value);102 derive.mockRestore();103 });104105 it("keeps the unlocked vault intact when a warned replacement commit fails", async () => {106 const vault = await import("./vault");107 await vault.createVault("original-password");108 await vault.addEntry({ type: "note", title: "Preserve me", notes: "original" });109 await vault.lock();110 await vault.unlock("original-password");111 const before = structuredClone(storage);112 const beforeSession = structuredClone(sessionStorage);113 const argon = await import("../crypto/argon2");114 const derive = argon.deriveKey;115 const stagedKeys: Uint8Array[] = [];116 const spy = vi.spyOn(argon, "deriveKey").mockImplementation(async (...args) => {117 const key = await derive(...args); stagedKeys.push(key); return key;118 });119 const root = vault.getRootKeyHex();120 const set = vi.mocked(chrome.storage.local.set);121 const write = set.getMockImplementation()!;122 set.mockImplementation(async (value) => {123 if ("peach_vault_a" in value) throw new Error("storage unavailable");124 return (write as (next: Record<string, unknown>) => Promise<void>)(value);125 });126 await expect(vault.createVault("replacement-password", "warned-import")).rejects.toThrow();127 for (const key of ["peach_vault_a", "peach_vault_b", "peach_vault_history", "peach_last_modified_at"]) expect(storage[key]).toEqual(before[key]);128 expect(vault.getEntries().map((entry) => entry.title)).toEqual(["Preserve me"]);129 expect(vault.getRootKeyHex()).toBe(root);130 expect(sessionStorage).toEqual(beforeSession);131 expect(stagedKeys).toHaveLength(1);132 expect(stagedKeys[0]!.every((byte) => byte === 0)).toBe(true);133 spy.mockRestore();134 });135136 it("reports saved-but-locked if auto-lock setup fails after the commit", async () => {137 const vault = await import("./vault");138 vi.mocked(chrome.alarms.create).mockImplementationOnce(() => { throw new Error("alarms unavailable"); });139 expect(await vault.createVault("new-password")).toEqual({ committed: true, unlocked: false });140 expect(vault.isUnlocked()).toBe(false);141 expect(storage.peach_vault_a).toBeDefined();142 expect(await vault.unlock("new-password")).toBe(true);143 });144145 it("commits warned replacement slots and their original snapshot together", async () => {146 const vault = await import("./vault");147 await vault.createVault("original-password");148 const oldA = JSON.stringify(storage.peach_vault_a);149 const oldB = JSON.stringify(storage.peach_vault_b);150 vi.mocked(chrome.storage.local.set).mockClear();151 await vault.createVault("replacement-password", "warned-import");152 const writes = vi.mocked(chrome.storage.local.set).mock.calls.filter(([value]) => "peach_vault_a" in value);153 expect(writes).toHaveLength(1);154 expect(writes[0]![0]).toMatchObject({155 peach_vault_b: expect.any(Object), peach_last_modified_at: expect.any(String),156 peach_vault_history: { snapshots: [expect.objectContaining({ vault_a: oldA, vault_b: oldB })] },157 });158 });159160 it.each(["ordinary", "adoption"])("excludes concurrent creation while %s creation owns the vault", async (kind) => {161 const vault = await import("./vault");162 const first = kind === "ordinary" ? vault.createVault("first-password") : vault.createVaultFromRootKey("first-password", "42".repeat(32));163 await expect(vault.createVault("second-password")).rejects.toThrow("vault_changed");164 await first;165 await vault.lock();166 expect(await vault.unlock("first-password")).toBe(true);167 expect(await vault.verifyMainPassword("second-password")).toBe(false);168 });169170 it("fails closed when the initial vault lookup fails", async () => {171 const vault = await import("./vault");172 vi.mocked(chrome.storage.local.get).mockRejectedValueOnce(new Error("storage unavailable"));173 await expect(vault.createVault("new-password")).rejects.toThrow("storage unavailable");174 expect(storage).toEqual({});175 expect(vault.isUnlocked()).toBe(false);176 });177178 it("excludes creation while an earlier password unlock is deriving", async () => {179 const vault = await import("./vault");180 await vault.createVault("original-password");181 await vault.lock();182 const argon = await import("../crypto/argon2");183 const started = deferred();184 const release = deferred();185 const derive = argon.deriveKey;186 const spy = vi.spyOn(argon, "deriveKey").mockImplementationOnce(async (...args) => {187 started.resolve(); await release.promise; return derive(...args);188 });189 const unlocking = vault.unlock("original-password");190 await started.promise;191 await expect(vault.createVault("replacement-password", "warned-import")).rejects.toThrow("vault_changed");192 release.resolve();193 expect(await unlocking).toBe(true);194 spy.mockRestore();195 });196197 it("reports a committed vault as locked when lock races its issued write", async () => {198 const vault = await import("./vault");199 const started = deferred();200 const release = deferred();201 vi.mocked(chrome.storage.local.set).mockImplementation(async (value) => {202 if ("peach_vault_a" in value) { started.resolve(); await release.promise; }203 Object.assign(storage, value);204 });205 const creating = vault.createVault("new-password");206 await started.promise;207 await vault.lock();208 release.resolve();209 expect(await creating).toEqual({ committed: true, unlocked: false });210 expect(vault.isUnlocked()).toBe(false);211 expect(await vault.unlock("new-password")).toBe(true);212 });213214 it("orders removal after an issued creation commit", async () => {215 const vault = await import("./vault");216 const started = deferred();217 const release = deferred();218 const set = vi.mocked(chrome.storage.local.set);219 set.mockImplementation(async (value) => {220 if ("peach_vault_a" in value) { started.resolve(); await release.promise; }221 Object.assign(storage, value);222 });223 const creating = vault.createVault("new-password").catch((error: Error) => error.message);224 await started.promise;225 let removed = false;226 const removing = vault.withVaultRemoval(async () => { storage = {}; removed = true; });227 await Promise.resolve();228 expect(removed).toBe(false);229 release.resolve();230 expect(await creating).toEqual({ committed: true, unlocked: false });231 await removing;232 expect(storage).toEqual({});233 expect(vault.isUnlocked()).toBe(false);234 });235236 it("excludes creation while an earlier entry write is staged", async () => {237 const vault = await import("./vault");238 await vault.createVault("original-password");239 const started = deferred();240 const release = deferred();241 const get = vi.mocked(chrome.storage.local.get);242 const read = get.getMockImplementation()!;243 get.mockImplementationOnce(async (...args) => { started.resolve(); await release.promise; return read(...args); });244 const writing = vault.addEntry({ type: "note", title: "Preserve me", notes: "original" });245 await started.promise;246 await expect(vault.createVault("replacement-password", "warned-import")).rejects.toThrow("vault_changed");247 release.resolve();248 await writing;249 expect(vault.getEntries()[0]?.title).toBe("Preserve me");250 });251252 it("rejects sibling entry mutations before they change a staged replacement session", async () => {253 const vault = await import("./vault");254 await vault.createVault("original-password");255 await vault.addEntry({ type: "note", title: "Original", notes: "original" });256 const originalEntries = structuredClone(vault.getEntries());257 const argon = await import("../crypto/argon2");258 const started = deferred();259 const release = deferred();260 const derive = argon.deriveKey;261 const spy = vi.spyOn(argon, "deriveKey").mockImplementationOnce(async (...args) => {262 started.resolve(); await release.promise; return derive(...args);263 });264 const creating = vault.createVault("new-password", "warned-import").catch((error: Error) => error.message);265 await started.promise;266 await expect(vault.restoreEntries([{ ...originalEntries[0]!, id: "replacement", title: "Wrong session" }], "replace")).rejects.toThrow();267 await expect(vault.addEntry({ type: "note", title: "Rejected", notes: "no" })).rejects.toThrow();268 expect(vault.getEntries()).toEqual(originalEntries);269 await vault.lock();270 release.resolve();271 expect(await creating).toBe("vault_changed");272 spy.mockRestore();273 });274275 it("prevents a rejected sibling write from restoring old entries after creation commits", async () => {276 const vault = await import("./vault");277 await vault.createVault("original-password");278 await vault.addEntry({ type: "note", title: "Old vault", notes: "original" });279 const started = deferred();280 const release = deferred();281 vi.mocked(chrome.storage.local.set).mockImplementation(async (value) => {282 if ("peach_vault_a" in value) { started.resolve(); await release.promise; }283 Object.assign(storage, value);284 });285 const creating = vault.createVault("new-password", "warned-import");286 await started.promise;287 release.resolve();288 const writing = vault.addEntry({ type: "note", title: "Rejected", notes: "no" }).catch((error: Error) => error.message);289 await creating;290 await writing;291 expect(vault.getEntries()).toEqual([]);292 });293294 it("removes an adopted vault when lock cancels its issued creation commit", async () => {295 const vault = await import("./vault");296 const started = deferred();297 const release = deferred();298 vi.mocked(chrome.storage.local.set).mockImplementation(async (value) => {299 if ("peach_vault_a" in value) { started.resolve(); await release.promise; }300 Object.assign(storage, value);301 });302 const creating = vault.createVaultFromRootKey("new-password", "42".repeat(32)).catch((error: Error) => error.message);303 await started.promise;304 await vault.lock();305 release.resolve();306 expect(await creating).toBe("vault_changed");307 expect(vault.isUnlocked()).toBe(false);308 expect(await vault.hasVault()).toBe(false);309 expect(storage.peach_last_modified_at).toBeUndefined();310 expect((await vault.createVaultFromRootKey("new-password", "42".repeat(32))).vaultId).toBeTruthy();311 });312313 it("reports a saved password change consistently when lock races the final stamp read", async () => {314 const vault = await import("./vault");315 await vault.createVault("original-password");316 const started = deferred();317 const release = deferred();318 const get = vi.mocked(chrome.storage.local.get);319 const read = get.getMockImplementation()!;320 get.mockImplementation(async (...args) => {321 if (args[0] === "peach_last_modified_at") { started.resolve(); await release.promise; }322 return read(...args);323 });324 const changing = vault.changePassword("original-password", "new-password");325 await started.promise;326 await vault.lock();327 release.resolve();328 expect(await changing).toBe(true);329 expect(vault.isUnlocked()).toBe(false);330 expect(await vault.unlock("new-password")).toBe(true);331 expect(await vault.verifyMainPassword("original-password")).toBe(false);332 });333334 it("creates a vault and stores encrypted payload", async () => {335 const vault = await import("./vault");336337 await vault.createVault("correct horse battery staple");338339 expect(storage.peach_vault_a).toBeDefined();340 expect((storage.peach_vault_a as StoredVault).ciphertext).toBeTruthy();341 expect(vault.getEntries()).toEqual([]);342 expect(alarms.created).toContainEqual({343 name: "autolock",344 delayInMinutes: 5,345 });346 });347348 it("writes both slots A and B on vault creation", async () => {349 const vault = await import("./vault");350 await vault.createVault("correct horse battery staple");351352 expect(storage.peach_vault_a).toBeDefined();353 expect(storage.peach_vault_b).toBeDefined();354 expect(storage.peach_duress).toBeUndefined();355 expect(storage.peach_vault).toBeUndefined();356 expect(storage.peach_decoy_vault).toBeUndefined();357 });358359 it("keeps the PIN wrapper in session storage and invalidates it on password change", async () => {360 const vault = await import("./vault");361 const password = "correct horse battery staple";362363 await vault.createVault(password);364 expect(await vault.setupPinUnlock(password, "123")).toBe(false);365 expect(await vault.setupPinUnlock(password, "1234567890123")).toBe(false);366 expect(await vault.setupPinUnlock(password, "1234")).toBe(true);367 expect((sessionStorage.peach_pin_wrap as { ciphertext: string }).ciphertext).toBeTruthy();368 expect(storage.peach_pin_wrap).toBeUndefined();369370 vault.lock();371 expect(await vault.unlockWithPin("000000")).toBe(false);372 expect(await vault.unlockWithPin("1234")).toBe(true);373374 expect(await vault.changePassword(password, "new correct horse battery"))375 .toBe(true);376 vault.lock();377 expect(await vault.unlockWithPin("1234")).toBe(false);378 expect(await vault.unlock("new correct horse battery")).toBe(true);379 });380381 it("requires the master password after three incorrect PIN attempts", async () => {382 const vault = await import("./vault");383 const password = "correct horse battery staple";384385 await vault.createVault(password);386 expect(await vault.setupPinUnlock(password, "1234")).toBe(true);387 vault.lock();388389 expect(await vault.unlockWithPin("0000")).toBe(false);390 expect(await vault.unlockWithPin("0000")).toBe(false);391 expect(await vault.unlockWithPin("0000")).toBe(false);392 expect(await vault.unlockWithPin("1234")).toBe(false);393 expect(await vault.unlock(password)).toBe(true);394395 vault.lock();396 expect(await vault.unlockWithPin("1234")).toBe(true);397 });398399 it("cannot unlock from a copied local-storage snapshot after session storage is cleared", async () => {400 const vault = await import("./vault");401 const password = "correct horse battery staple";402403 await vault.createVault(password);404 expect(await vault.setupPinUnlock(password, "1234")).toBe(true);405 const copiedLocalStorage = { ...storage };406 await (chrome.storage.session as typeof chrome.storage.session).clear();407 vault.lock();408409 expect(copiedLocalStorage.peach_pin_wrap).toBeUndefined();410 await expect(vault.unlockWithPin("1234")).resolves.toBe(false);411 await expect(vault.getPinUnlockStatus()).resolves.toMatchObject({412 configured: true,413 available: false,414 attemptsRemaining: 0,415 });416 });417418 it("slot A and slot B have matching ciphertext size at fresh install", async () => {419 const vault = await import("./vault");420 await vault.createVault("correct horse battery staple");421422 const a = storage.peach_vault_a as StoredVault;423 const b = storage.peach_vault_b as StoredVault;424 expect(a.ciphertext.length).toBe(b.ciphertext.length);425 });426427 it("does not expose a plaintext duress flag after setupDuress", async () => {428 const vault = await import("./vault");429 await vault.createVault("real-password-12345");430 await vault.setupDuress("decoy-password-67890");431432 expect(storage.peach_duress).toBeUndefined();433 expect(storage.peach_decoy_vault).toBeUndefined();434 const keys = Object.keys(storage).filter((k) => k.startsWith("peach_"));435 436 437 for (const key of keys) {438 expect(439 [440 "peach_vault_a",441 "peach_vault_b",442 "peach_settings",443 "peach_vault_history",444 "peach_last_modified_at",445 ]446 ).toContain(key);447 }448 expect(keys).toContain("peach_vault_a");449 expect(keys).toContain("peach_vault_b");450 });451452 it("unlocks with real password and loads real entries", async () => {453 const vault = await import("./vault");454 await vault.createVault("real-password-12345");455 await vault.addEntry({456 title: "GitHub",457 username: "june",458 password: "realsecret",459 url: "github.com",460 });461 vault.lock();462463 const ok = await vault.unlock("real-password-12345");464 expect(ok).toBe(true);465 expect(vault.getEntries()).toHaveLength(1);466 expect(vault.getEntries()[0].title).toBe("GitHub");467 });468469 it("unlocks with duress password and loads empty entries", async () => {470 const vault = await import("./vault");471 await vault.createVault("real-password-12345");472 await vault.addEntry({473 title: "GitHub",474 username: "june",475 password: "realsecret",476 url: "github.com",477 });478 await vault.setupDuress("decoy-password-67890");479 vault.lock();480481 const ok = await vault.unlock("decoy-password-67890");482 expect(ok).toBe(true);483 expect(vault.getEntries()).toEqual([]);484 });485486 it("HOLE 5: the duress vault has no sync identity and cannot sync", async () => {487 const vault = await import("./vault");488 await vault.createVault("real-password-12345");489 await vault.addEntry({ type: "login", title: "GitHub", password: "realsecret" });490 await vault.setupDuress("decoy-password-67890");491492 493 expect(vault.getRootKeyHex()).toBeTruthy();494 vault.lock();495496 expect(await vault.unlock("decoy-password-67890")).toBe(true);497 498 499 500 expect(vault.getRootKeyHex()).toBeNull();501502 503 504 const { createSyncVaultAdapter } = await import("./sync-vault-adapter");505 const adapter = createSyncVaultAdapter();506 await expect(adapter.computeVaultId()).rejects.toThrow();507 await expect(adapter.buildOutgoingDeviceManifest?.()).rejects.toThrow();508 vault.lock();509 });510511 it("runs both slot derivations in parallel for constant-time unlock (DUR-002)", async () => {512 513 514 515 516 const argon2 = await import("../crypto/argon2");517 const deriveSpy = vi.spyOn(argon2, "deriveKey");518519 const vault = await import("./vault");520 await vault.createVault("real-password-12345");521 await vault.setupDuress("decoy-password-67890");522 vault.lock();523524 deriveSpy.mockClear();525 await vault.unlock("real-password-12345");526 expect(deriveSpy).toHaveBeenCalledTimes(2);527 vault.lock();528529 deriveSpy.mockClear();530 await vault.unlock("decoy-password-67890");531 expect(deriveSpy).toHaveBeenCalledTimes(2);532 vault.lock();533534 deriveSpy.mockClear();535 await vault.unlock("wrong-password-xxxxx");536 expect(deriveSpy).toHaveBeenCalledTimes(2);537538 deriveSpy.mockRestore();539 });540541 it("rejects wrong passwords", async () => {542 const vault = await import("./vault");543 await vault.createVault("real-password-12345");544 vault.lock();545546 const ok = await vault.unlock("nope-nope-nope");547 expect(ok).toBe(false);548 });549550 it("persists duressConfigured across lock/unlock in encrypted payload", async () => {551 const vault = await import("./vault");552 await vault.createVault("real-password-12345");553 await vault.setupDuress("decoy-password-67890");554 vault.lock();555556 await vault.unlock("real-password-12345");557 expect(await vault.isDuressEnabled()).toBe(true);558559 await vault.disableDuress();560 expect(await vault.isDuressEnabled()).toBe(false);561 vault.lock();562563 await vault.unlock("real-password-12345");564 expect(await vault.isDuressEnabled()).toBe(false);565 });566567 it("soft deletes entries while keeping deletedAt in encrypted storage", async () => {568 const vault = await import("./vault");569570 await vault.createVault("correct horse battery staple");571 const entry = await vault.addEntry({572 title: "GitHub",573 username: "june",574 password: "secret123",575 url: "github.com",576 });577578 await vault.deleteEntry(entry.id);579580 expect(vault.getEntries()).toEqual([]);581582 const stored = storage.peach_vault_a as StoredVault;583 const salt = Uint8Array.from(584 stored.salt.match(/.{1,2}/g)!.map((value: string) => parseInt(value, 16))585 );586 const key = await deriveKey("correct horse battery staple", salt);587 const plain = await decrypt(key, stored.nonce, stored.ciphertext, stored.tag, "slot_a_v1");588 const parsed = JSON.parse(plain) as { entries: Array<{ id: string; deletedAt?: number }> };589590 expect(parsed.entries).toHaveLength(1);591 expect(parsed.entries[0].id).toBe(entry.id);592 expect(typeof parsed.entries[0].deletedAt).toBe("number");593 });594595 it("accepts imported entries without a username or url", async () => {596 const vault = await import("./vault");597598 await vault.createVault("correct horse battery staple");599 const entry = await vault.addEntry({600 title: "Imported Login",601 username: "",602 password: "secret123",603 url: "",604 notes: "migrated from another manager",605 });606607 expect(entry.username).toBe("");608 expect(entry.url).toBe("");609 expect(vault.getEntries()).toHaveLength(1);610 });611612 it("changePassword happy path — new password unlocks, old is rejected", async () => {613 const vault = await import("./vault");614615 await vault.createVault("old-pass-abc123");616 await vault.addEntry({ title: "GitHub", username: "june", password: "secret1", url: "github.com" });617 await vault.addEntry({ title: "Gmail", username: "june", password: "secret2", url: "mail.google.com" });618619 expect(await vault.changePassword("old-pass-abc123", "new-pass-xyz789")).toBe(true);620621 vault.lock();622 expect(await vault.unlock("new-pass-xyz789")).toBe(true);623 expect(vault.getEntries()).toHaveLength(2);624625 vault.lock();626 expect(await vault.unlock("old-pass-abc123")).toBe(false);627 });628629 it("stamps peach_last_modified_at on createVault", async () => {630 const vault = await import("./vault");631 const before = Date.now();632 await new Promise((resolve) => setTimeout(resolve, 1));633634 await vault.createVault("stamp-create-pass");635636 expect(Number(storage.peach_last_modified_at)).toBeGreaterThanOrEqual(before);637 });638639 it("rejects a slot A persist that races with lock", async () => {640 const vault = await import("./vault");641 await vault.createVault("persist-epoch-pass");642 const slotBefore = JSON.stringify(storage.peach_vault_a);643 const readStarted = deferred();644 const releaseRead = deferred();645 const localGet = chrome.storage.local.get as unknown as ReturnType<typeof vi.fn>;646 localGet.mockImplementation(async (key?: string | string[]) => {647 if (key === "peach_vault_a") {648 readStarted.resolve();649 await releaseRead.promise;650 }651 if (!key) return storage;652 const keys = Array.isArray(key) ? key : [key];653 return keys.reduce<StorageShape>((result, entry) => {654 result[entry] = storage[entry];655 return result;656 }, {});657 });658659 const saving = vault.addEntry({ title: "stale", username: "", password: "pw", url: "" });660 await readStarted.promise;661 await vault.lock();662 releaseRead.resolve();663664 await expect(saving).rejects.toThrow("vault_locked");665 expect(JSON.stringify(storage.peach_vault_a)).toBe(slotBefore);666 expect(vault.isUnlocked()).toBe(false);667 });668669 it("stamps peach_last_modified_at on entry mutations through persistEntries", async () => {670 const vault = await import("./vault");671 await vault.createVault("stamp-entry-pass");672 let previous = Number(storage.peach_last_modified_at);673 await new Promise((resolve) => setTimeout(resolve, 1));674 const entry = await vault.addEntry({675 title: "Stamp",676 username: "",677 password: "p",678 url: "",679 });680 expect(Number(storage.peach_last_modified_at)).toBeGreaterThan(previous);681682 previous = Number(storage.peach_last_modified_at);683 await new Promise((resolve) => setTimeout(resolve, 1));684 await vault.updateEntry(entry.id, { title: "Stamped" });685 expect(Number(storage.peach_last_modified_at)).toBeGreaterThan(previous);686687 previous = Number(storage.peach_last_modified_at);688 await new Promise((resolve) => setTimeout(resolve, 1));689 await vault.deleteEntry(entry.id);690 expect(Number(storage.peach_last_modified_at)).toBeGreaterThan(previous);691 });692693 it("stamps peach_last_modified_at on setupDuress and changePassword", async () => {694 const vault = await import("./vault");695 await vault.createVault("stamp-real-pass");696697 let previous = Number(storage.peach_last_modified_at);698 await new Promise((resolve) => setTimeout(resolve, 1));699 await vault.setupDuress("stamp-decoy-pass");700 expect(Number(storage.peach_last_modified_at)).toBeGreaterThan(previous);701702 previous = Number(storage.peach_last_modified_at);703 await new Promise((resolve) => setTimeout(resolve, 1));704 expect(await vault.changePassword("stamp-real-pass", "stamp-new-pass")).toBe(true);705 expect(Number(storage.peach_last_modified_at)).toBeGreaterThan(previous);706 });707708 it("changePassword with wrong current password returns false and leaves slot A unchanged", async () => {709 const vault = await import("./vault");710711 await vault.createVault("correct-pass-abcde");712 const slotABefore = JSON.stringify(storage.peach_vault_a);713714 expect(await vault.changePassword("wrong-pass", "new-pass")).toBe(false);715 expect(JSON.stringify(storage.peach_vault_a)).toBe(slotABefore);716717 vault.lock();718 expect(await vault.unlock("correct-pass-abcde")).toBe(true);719 });720721 it("changePassword with duress configured leaves slot B byte-identical", async () => {722 const vault = await import("./vault");723724 await vault.createVault("real-pass-abcde");725 await vault.setupDuress("duress-pass-xyzzz");726727 const slotBBefore = JSON.stringify(storage.peach_vault_b);728 expect(await vault.changePassword("real-pass-abcde", "new-real-pass-fghij")).toBe(true);729 expect(JSON.stringify(storage.peach_vault_b)).toBe(slotBBefore);730731 732 vault.lock();733 expect(await vault.unlock("duress-pass-xyzzz")).toBe(true);734 expect(vault.getEntries()).toEqual([]);735 });736737 it("restoreEntries with mode 'replace' and empty incoming throws and leaves entries intact", async () => {738 const vault = await import("./vault");739740 await vault.createVault("pass-abcdef");741 await vault.addEntry({ title: "One", username: "", password: "1", url: "" });742 await vault.addEntry({ title: "Two", username: "", password: "2", url: "" });743 await vault.addEntry({ title: "Three", username: "", password: "3", url: "" });744745 await expect(vault.restoreEntries([], "replace")).rejects.toThrow(746 /refuse to replace with empty entry set/i747 );748 expect(vault.getEntries()).toHaveLength(3);749 });750751 it("changePassword swaps the active key before Slot B is regenerated", async () => {752 const vault = await import("./vault");753754 await vault.createVault("correct-pass-12345");755 const entry = await vault.addEntry({756 title: "GitHub",757 username: "june",758 password: "secret123",759 url: "https://github.com",760 });761762 const setMock = chrome.storage.local.set as unknown as ReturnType<typeof vi.fn>;763 const originalSet = setMock.getMockImplementation();764 let injectedDuringSlotBWrite = false;765766 setMock.mockImplementation(async (next: Record<string, unknown>) => {767 Object.assign(storage, next);768769 if (!injectedDuringSlotBWrite && "peach_vault_b" in next) {770 injectedDuringSlotBWrite = true;771 await vault.updateEntry(entry.id, { notes: "updated during password change" });772 }773 });774775 expect(await vault.changePassword("correct-pass-12345", "new-pass-67890")).toBe(true);776777 setMock.mockImplementation(originalSet ?? (async (next: Record<string, unknown>) => {778 Object.assign(storage, next);779 }));780781 vault.lock();782 expect(await vault.unlock("new-pass-67890")).toBe(true);783 expect(vault.getEntryById(entry.id)?.notes).toBe("updated during password change");784785 vault.lock();786 expect(await vault.unlock("correct-pass-12345")).toBe(false);787 });788789 it("restoreEntries replace mode replaces existing entries", async () => {790 const vault = await import("./vault");791792 await vault.createVault("replace-pass-12345");793 await vault.addEntry({ title: "A", username: "june", password: "one", url: "https://a.test" });794 await vault.addEntry({ title: "B", username: "june", password: "two", url: "https://b.test" });795796 const incoming = [797 {798 id: "entry-c",799 type: "login" as const,800 title: "C",801 username: "june",802 password: "three",803 url: "https://c.test",804 createdAt: 10,805 modifiedAt: 10,806 },807 {808 id: "entry-d",809 type: "login" as const,810 title: "D",811 username: "june",812 password: "four",813 url: "https://d.test",814 createdAt: 20,815 modifiedAt: 20,816 },817 ];818819 await expect(vault.restoreEntries(incoming, "replace")).resolves.toEqual({820 added: 2,821 updated: 0,822 skipped: 0,823 });824825 expect(vault.getEntries().map((entry) => entry.id)).toEqual(["entry-c", "entry-d"]);826 });827828 it("restoreEntries merge mode lets newer incoming entries win", async () => {829 const vault = await import("./vault");830831 await vault.createVault("merge-pass-12345");832 const existing = await vault.addEntry({833 title: "GitHub",834 username: "june",835 password: "old-secret",836 url: "https://github.com",837 });838839 await expect(840 vault.restoreEntries(841 [842 {843 ...existing,844 password: "new-secret",845 modifiedAt: existing.modifiedAt + 100,846 },847 ],848 "merge"849 )850 ).resolves.toEqual({ added: 0, updated: 1, skipped: 0 });851852 expect(vault.getEntryById(existing.id)?.password).toBe("new-secret");853 });854855 it("restoreEntries merge mode keeps newer local entries when incoming is older", async () => {856 const vault = await import("./vault");857858 await vault.createVault("merge-pass-67890");859 const existing = await vault.addEntry({860 title: "GitHub",861 username: "june",862 password: "current-secret",863 url: "https://github.com",864 });865866 await expect(867 vault.restoreEntries(868 [869 {870 ...existing,871 password: "stale-secret",872 modifiedAt: existing.modifiedAt - 100,873 },874 ],875 "merge"876 )877 ).resolves.toEqual({ added: 0, updated: 0, skipped: 1 });878879 expect(vault.getEntryById(existing.id)?.password).toBe("current-secret");880 });881882 it("clearVaultEntries without explicit confirmation throws", async () => {883 const vault = await import("./vault");884885 await vault.createVault("clear-pass-12345");886 await vault.addEntry({ title: "A", username: "", password: "one", url: "" });887888 const clearVaultEntries = vault.clearVaultEntries as unknown as (889 confirmation?: unknown890 ) => Promise<void>;891892 await expect(clearVaultEntries()).rejects.toThrow(/explicit confirmation/i);893 await expect(clearVaultEntries("wrong")).rejects.toThrow(/explicit confirmation/i);894 expect(vault.getEntries()).toHaveLength(1);895 });896897 it("clearVaultEntries with REPLACE_ALL soft-deletes all entries", async () => {898 const vault = await import("./vault");899900 await vault.createVault("clear-pass-67890");901 await vault.addEntry({ title: "A", username: "", password: "one", url: "" });902 await vault.addEntry({ title: "B", username: "", password: "two", url: "" });903 await vault.addEntry({ title: "C", username: "", password: "three", url: "" });904905 await vault.clearVaultEntries("REPLACE_ALL");906907 expect(vault.getEntries()).toEqual([]);908 expect(vault.getDeletedEntries()).toHaveLength(3);909 expect(vault.getDeletedEntries().every((entry) => typeof entry.deletedAt === "number")).toBe(true);910 });911912 it("deduplicateEntries throws in decoy mode", async () => {913 const vault = await import("./vault");914915 await vault.createVault("real-pass-12345");916 await vault.addEntry({917 title: "GitHub",918 username: "june",919 password: "secret123",920 url: "https://github.com",921 });922 await vault.setupDuress("duress-pass-12345");923 vault.lock();924925 expect(await vault.unlock("duress-pass-12345")).toBe(true);926 await expect(vault.deduplicateEntries()).rejects.toThrow(/decoy mode/i);927 });928929 it("deduplicateEntries removes older duplicates in real mode", async () => {930 const vault = await import("./vault");931932 await vault.createVault("dedupe-pass-12345");933 await vault.addEntry({934 title: "GitHub",935 username: "june",936 password: "old-secret",937 url: "https://github.com",938 });939 await new Promise<void>((resolve) => setTimeout(resolve, 5));940 const newer = await vault.addEntry({941 title: "GitHub",942 username: "june",943 password: "new-secret",944 url: "https://github.com",945 });946947 expect(await vault.deduplicateEntries()).toBe(1);948 expect(vault.getEntries()).toHaveLength(1);949 expect(vault.getEntries()[0].id).toBe(newer.id);950 expect(vault.getDeletedEntries()).toHaveLength(1);951 });952953 it("updateEntry with an empty password on a login entry clears the password", async () => {954 const vault = await import("./vault");955956 await vault.createVault("update-pass-12345");957 const entry = await vault.addEntry({958 title: "GitHub",959 username: "june",960 password: "secret123",961 url: "https://github.com",962 });963964 await expect(vault.updateEntry(entry.id, { password: "" })).resolves.toBeUndefined();965 expect(vault.getEntryById(entry.id)?.password).toBeUndefined();966 });967968 it("updateEntry with an empty password on a note entry is allowed", async () => {969 const vault = await import("./vault");970971 await vault.createVault("note-pass-12345");972 const entry = await vault.addEntry({973 type: "note",974 title: "Secure note",975 notes: "keep me",976 });977978 await expect(vault.updateEntry(entry.id, { password: "", notes: "updated" })).resolves.toBeUndefined();979 expect(vault.getEntryById(entry.id)).toMatchObject({980 type: "note",981 notes: "updated",982 });983 });984985 it("lock zeroes the derived key and resets unlock state", async () => {986 const aes = await import("./aes");987 const zeroKeySpy = vi.spyOn(aes, "zeroKey");988 const vault = await import("./vault");989990 await vault.createVault("lock-pass-12345");991 expect(vault.isUnlocked()).toBe(true);992993 vault.lock();994995 expect(zeroKeySpy).toHaveBeenCalled();996 expect(vault.isUnlocked()).toBe(false);997 zeroKeySpy.mockRestore();998 });9991000 it("lock clears in-memory entries", async () => {1001 const vault = await import("./vault");10021003 await vault.createVault("lock-pass-67890");1004 const entry = await vault.addEntry({1005 title: "GitHub",1006 username: "june",1007 password: "secret123",1008 url: "https://github.com",1009 });10101011 expect(vault.getEntryById(entry.id)?.title).toBe("GitHub");1012 vault.lock();1013 expect(vault.getEntryById(entry.id)).toBeUndefined();1014 });10151016 it("unlock with neither slot decryptable returns false and leaves the vault locked", async () => {1017 const vault = await import("./vault");10181019 await vault.createVault("real-pass-67890");1020 vault.lock();10211022 expect(await vault.unlock("totally-wrong-password")).toBe(false);1023 expect(vault.isUnlocked()).toBe(false);1024 });10251026 it("isUnlocked tracks the full lock lifecycle", async () => {1027 const vault = await import("./vault");10281029 expect(vault.isUnlocked()).toBe(false);1030 await vault.createVault("unlock-pass-12345");1031 expect(vault.isUnlocked()).toBe(true);1032 vault.lock();1033 expect(vault.isUnlocked()).toBe(false);1034 expect(await vault.unlock("unlock-pass-12345")).toBe(true);1035 expect(vault.isUnlocked()).toBe(true);1036 vault.lock();1037 expect(vault.isUnlocked()).toBe(false);1038 });10391040 it("persistEntries surfaces STORAGE_QUOTA_EXCEEDED when slot writes hit quota", async () => {1041 const vault = await import("./vault");10421043 await vault.createVault("quota-pass-12345");10441045 const setMock = chrome.storage.local.set as unknown as ReturnType<typeof vi.fn>;1046 setMock.mockImplementation(async (next: Record<string, unknown>) => {1047 if ("peach_vault_a" in next || "peach_vault_b" in next) {1048 throw new Error("QUOTA_BYTES quota reached");1049 }1050 Object.assign(storage, next);1051 });10521053 await expect(1054 vault.addEntry({1055 title: "GitHub",1056 username: "june",1057 password: "secret123",1058 url: "https://github.com",1059 })1060 ).rejects.toThrow("STORAGE_QUOTA_EXCEEDED");1061 });10621063 it("persistSettings surfaces STORAGE_QUOTA_EXCEEDED when settings writes hit quota", async () => {1064 const vault = await import("./vault");10651066 await vault.createVault("settings-pass-12345");10671068 const setMock = chrome.storage.local.set as unknown as ReturnType<typeof vi.fn>;1069 setMock.mockImplementation(async (next: Record<string, unknown>) => {1070 if ("peach_settings" in next) {1071 throw new Error("QUOTA_BYTES quota reached");1072 }1073 Object.assign(storage, next);1074 });10751076 await expect(vault.updateSettings({ autoLockMinutes: 10 })).rejects.toThrow(1077 "STORAGE_QUOTA_EXCEEDED"1078 );1079 });10801081 it("card entry round-trips through vault — all fields preserved", async () => {1082 const vault = await import("./vault");10831084 await vault.createVault("card-test-pass-12345");1085 const entry = await vault.addEntry({1086 type: "card",1087 title: "Personal Visa",1088 cardholderName: "Jane Smith",1089 cardNumber: "4111111111111111",1090 expMonth: "05",1091 expYear: "2028",1092 cvc: "123",1093 cardNickname: "Personal Visa",1094 network: "visa",1095 last4: "1111",1096 });10971098 expect(entry.type).toBe("card");1099 expect(entry.cardholderName).toBe("Jane Smith");1100 expect(entry.cardNumber).toBe("4111111111111111");1101 expect(entry.expMonth).toBe("05");1102 expect(entry.expYear).toBe("2028");1103 expect(entry.cvc).toBe("123");1104 expect(entry.network).toBe("visa");1105 expect(entry.last4).toBe("1111");11061107 vault.lock();1108 await vault.unlock("card-test-pass-12345");1109 const entries = vault.getEntries();1110 expect(entries).toHaveLength(1);1111 expect(entries[0].cardNumber).toBe("4111111111111111");1112 expect(entries[0].cvc).toBe("123");1113 });11141115 it("updateEntry — cannot clear card number on card entry", async () => {1116 const vault = await import("./vault");11171118 await vault.createVault("card-guard-pass-12345");1119 const entry = await vault.addEntry({1120 type: "card",1121 title: "My Card",1122 cardholderName: "Jane Smith",1123 cardNumber: "4111111111111111",1124 expMonth: "05",1125 expYear: "2028",1126 cvc: "123",1127 });11281129 await expect(1130 vault.updateEntry(entry.id, { cardNumber: "" })1131 ).rejects.toThrow("card number is required for card entries");11321133 const entries = vault.getEntries();1134 expect(entries[0].cardNumber).toBe("4111111111111111");1135 });11361137 it("declineCardSaveOffer — stores fingerprint in settings", async () => {1138 const vault = await import("./vault");11391140 await vault.createVault("decline-pass-12345");1141 await vault.declineCardSaveOffer("1111", "05", "2028");11421143 const settings = vault.getSettings();1144 expect(settings.declinedCardFingerprints).toHaveLength(1);1145 });11461147 it("isCardDeclined — returns true for previously declined card", async () => {1148 const vault = await import("./vault");11491150 await vault.createVault("declined-check-pass-12345");1151 await vault.declineCardSaveOffer("1111", "05", "2028");11521153 expect(await vault.isCardDeclined("1111", "05", "2028")).toBe(true);1154 });11551156 it("isCardDeclined — returns false for card with same last4 but different expiry", async () => {1157 const vault = await import("./vault");11581159 await vault.createVault("declined-diff-pass-12345");1160 await vault.declineCardSaveOffer("1111", "05", "2028");11611162 expect(await vault.isCardDeclined("1111", "06", "2028")).toBe(false);1163 });11641165 it("queryDomain matches an entry against its additionalUrls", async () => {1166 const vault = await import("./vault");11671168 await vault.createVault("multi-domain-pass-12345");1169 const entry = await vault.addEntry({1170 type: "login",1171 title: "Foo",1172 username: "june",1173 password: "secret",1174 url: "https://foo.com",1175 additionalUrls: ["https://bar.io", "https://baz.org"],1176 });11771178 1179 1180 expect(vault.queryDomain("foo.com").map((e) => e.id)).toContain(entry.id);1181 expect(vault.queryDomain("bar.io").map((e) => e.id)).toContain(entry.id);1182 expect(vault.queryDomain("baz.org").map((e) => e.id)).toContain(entry.id);1183 expect(vault.queryDomain("unrelated.com")).toEqual([]);1184 });11851186 it("updateEntry trims, dedupes, and clears empty additionalUrls", async () => {1187 const vault = await import("./vault");11881189 await vault.createVault("dedupe-additional-pass-12345");1190 const entry = await vault.addEntry({1191 type: "login",1192 title: "Foo",1193 username: "june",1194 password: "secret",1195 url: "https://foo.com",1196 });11971198 await vault.updateEntry(entry.id, {1199 additionalUrls: [1200 " https://login.foo.com ",1201 "https://login.foo.com",1202 "",1203 " ",1204 "https://accounts.foo.com",1205 ],1206 });12071208 const stored = vault.getEntryById(entry.id);1209 expect(stored?.additionalUrls).toEqual([1210 "https://login.foo.com",1211 "https://accounts.foo.com",1212 ]);12131214 await vault.updateEntry(entry.id, { additionalUrls: ["", " "] });1215 expect(vault.getEntryById(entry.id)?.additionalUrls).toBeUndefined();1216 });12171218 it("preserves email field through lock/unlock cycle", async () => {1219 const vault = await import("./vault");1220 await vault.createVault("preserve-email-pass-12345");1221 await vault.addEntry({1222 type: "login",1223 title: "GitHub",1224 username: "june",1225 email: "[email protected]",1226 password: "secret",1227 url: "https://github.com",1228 });1229 vault.lock();12301231 const ok = await vault.unlock("preserve-email-pass-12345");1232 expect(ok).toBe(true);1233 const entry = vault.getEntries().find((e) => e.title === "GitHub");1234 expect(entry?.email).toBe("[email protected]");1235 });12361237 it("preserves additionalUrls through lock/unlock cycle", async () => {1238 const vault = await import("./vault");1239 await vault.createVault("preserve-urls-pass-12345");1240 await vault.addEntry({1241 type: "login",1242 title: "Example",1243 username: "june",1244 password: "secret",1245 url: "https://example.com",1246 additionalUrls: [1247 "https://beta.example.com",1248 "https://staging.example.com",1249 ],1250 });1251 vault.lock();12521253 const ok = await vault.unlock("preserve-urls-pass-12345");1254 expect(ok).toBe(true);1255 const entry = vault.getEntries().find((e) => e.title === "Example");1256 expect(entry?.additionalUrls).toEqual([1257 "https://beta.example.com",1258 "https://staging.example.com",1259 ]);1260 });12611262 it("normalizeEntry preserves passwordChangedAt through lock/unlock", async () => {1263 const vault = await import("./vault");1264 await vault.createVault("pwchanged-preserve-pass");1265 const entry = await vault.addEntry({1266 title: "Aged",1267 username: "june",1268 password: "secret",1269 url: "https://aged.test",1270 });1271 1272 1273 const ts = entry.passwordChangedAt;1274 expect(typeof ts).toBe("number");1275 vault.lock();12761277 expect(await vault.unlock("pwchanged-preserve-pass")).toBe(true);1278 const restored = vault.getEntries().find((e) => e.id === entry.id);1279 expect(restored?.passwordChangedAt).toBe(ts);1280 });12811282 it("normalizeEntry handles entries without passwordChangedAt", async () => {1283 const vault = await import("./vault");1284 await vault.createVault("pwchanged-absent-pass");1285 1286 const note = await vault.addEntry({ type: "note", title: "Memo", notes: "x" });1287 vault.lock();12881289 expect(await vault.unlock("pwchanged-absent-pass")).toBe(true);1290 const restored = vault.getEntries().find((e) => e.id === note.id);1291 expect(restored?.passwordChangedAt).toBeUndefined();1292 });12931294 it("applyMergedRemoteEntries does not advance the vault version", async () => {1295 const vault = await import("./vault");1296 await vault.createVault("syncver-pass-aaaaa");1297 await vault.addEntry({ title: "Local", username: "june", password: "p", url: "https://l.test" });12981299 const before = await vault.getVaultVersion();1300 await new Promise((r) => setTimeout(r, 2));1301 await vault.applyMergedRemoteEntries(1302 [1303 {1304 id: "remote-1",1305 type: "login",1306 title: "Remote",1307 username: "r",1308 password: "x",1309 url: "https://r.test",1310 createdAt: Date.now(),1311 modifiedAt: Date.now(),1312 },1313 ],1314 {},1315 );13161317 expect(await vault.getVaultVersion()).toBe(before);1318 });13191320 it("addEntry advances the vault version", async () => {1321 const vault = await import("./vault");1322 await vault.createVault("syncver-pass-bbbbb");13231324 const before = await vault.getVaultVersion();1325 await new Promise((r) => setTimeout(r, 2));1326 await vault.addEntry({ title: "Local", username: "june", password: "p", url: "https://l.test" });13271328 expect(await vault.getVaultVersion()).toBeGreaterThan(before);1329 });13301331 it("modifiedAt is monotonic even when the wall clock regresses (SEV-2-E)", async () => {1332 const vault = await import("./vault");1333 await vault.createVault("monotonic-pass-aaaaa");1334 const e1 = await vault.addEntry({ title: "M", username: "june", password: "p1", url: "https://m.test" });1335 const before = vault.getEntryById(e1.id)!.modifiedAt;13361337 1338 const spy = vi.spyOn(Date, "now").mockReturnValue(before - 10_000);1339 await vault.updateEntry(e1.id, { password: "p2" });1340 const after = vault.getEntryById(e1.id)!.modifiedAt;1341 expect(after).toBeGreaterThan(before);1342 spy.mockRestore();1343 });13441345 it("deletedAt is strictly greater than the entry's modifiedAt", async () => {1346 const vault = await import("./vault");1347 await vault.createVault("monotonic-pass-bbbbb");1348 const e = await vault.addEntry({ title: "D", username: "june", password: "p", url: "https://d.test" });1349 const modAt = vault.getEntryById(e.id)!.modifiedAt;1350 await vault.deleteEntry(e.id);1351 const tomb = vault.getDeletedEntries().find((t) => t.id === e.id)!;1352 expect(tomb.deletedAt!).toBeGreaterThan(modAt);1353 });13541355 it("updateEntry rolls back in-memory state when the disk write fails (SEV-3-A)", async () => {1356 const vault = await import("./vault");1357 await vault.createVault("rollback-pass-aaaaa");1358 const e = await vault.addEntry({ title: "R", username: "june", password: "original", url: "https://r.test" });13591360 const setSpy = chrome.storage.local.set as unknown as ReturnType<typeof vi.fn>;1361 1362 setSpy.mockImplementation(async (next: Record<string, unknown>) => {1363 if ("peach_vault_a" in next) throw new Error("QUOTA_BYTES quota exceeded");1364 Object.assign(storage, next);1365 });13661367 await expect(vault.updateEntry(e.id, { password: "changed" })).rejects.toThrow();13681369 setSpy.mockImplementation(async (next: Record<string, unknown>) => { Object.assign(storage, next); });1370 1371 expect(vault.getEntryById(e.id)!.password).toBe("original");1372 });13731374 it("getRootKeyHex is stable across a password change (SEV-2-B)", async () => {1375 const vault = await import("./vault");1376 await vault.createVault("rootkey-pass-aaaaa");1377 const before = vault.getRootKeyHex();1378 expect(before).toMatch(/^[0-9a-f]{64}$/);13791380 expect(await vault.changePassword("rootkey-pass-aaaaa", "rootkey-pass-bbbbb")).toBe(true);1381 expect(vault.getRootKeyHex()).toBe(before);13821383 1384 vault.lock();1385 expect(await vault.unlock("rootkey-pass-bbbbb")).toBe(true);1386 expect(vault.getRootKeyHex()).toBe(before);1387 });13881389 it("getRootKeyHex returns null when the vault is locked", async () => {1390 const vault = await import("./vault");1391 await vault.createVault("rootkey-pass-ccccc");1392 vault.lock();1393 expect(vault.getRootKeyHex()).toBeNull();1394 });13951396 it("unlock_with_key_rehydrates_root_key (PCH-01-009)", async () => {1397 const vault = await import("./vault");1398 await vault.createVault("biometric-pass-12345");1399 const rootBefore = vault.getRootKeyHex();1400 const keyHex = vault.getDerivedKeyHex();1401 expect(rootBefore).not.toBeNull();1402 vault.lock();1403 1404 const r = await vault.unlockWithKey(keyHex);1405 expect(r.ok).toBe(true);1406 expect(vault.getRootKeyHex()).toBe(rootBefore);1407 });14081409 it("duress keeps both slots equal length at rest, even as the real vault grows (audit MEDIUM)", async () => {1410 const vault = await import("./vault");1411 await vault.createVault("duress-real-pass-aaaa");1412 await vault.setupDuress("duress-decoy-pass-bbbb");14131414 const lenA = () => (storage.peach_vault_a as StoredVault).ciphertext.length;1415 const lenB = () => (storage.peach_vault_b as StoredVault).ciphertext.length;14161417 1418 expect(lenA()).toBe(lenB());14191420 1421 1422 await vault.addEntry({ title: "One", username: "u", password: "p", url: "https://a.test" });1423 await vault.addEntry({ title: "Two", username: "u", password: "p", url: "https://b.test" });1424 expect(lenA()).toBe(lenB());1425 });14261427 it("deleteEntry rolls back the tombstone when the disk write fails (SEV-3-A)", async () => {1428 const vault = await import("./vault");1429 await vault.createVault("rollback-pass-bbbbb");1430 const e = await vault.addEntry({ title: "R", username: "june", password: "p", url: "https://r.test" });14311432 const setSpy = chrome.storage.local.set as unknown as ReturnType<typeof vi.fn>;1433 setSpy.mockImplementation(async (next: Record<string, unknown>) => {1434 if ("peach_vault_a" in next) throw new Error("QUOTA_BYTES quota exceeded");1435 Object.assign(storage, next);1436 });14371438 await expect(vault.deleteEntry(e.id)).rejects.toThrow();14391440 setSpy.mockImplementation(async (next: Record<string, unknown>) => { Object.assign(storage, next); });1441 1442 expect(vault.getEntryById(e.id)).toBeDefined();1443 expect(vault.getDeletedEntries().find((t) => t.id === e.id)).toBeUndefined();1444 });14451446 describe("password history", () => {1447 it("captures the old password on change, newest first", async () => {1448 const vault = await import("./vault");1449 await vault.createVault("history-pass-12345");1450 const e = await vault.addEntry({ title: "H", username: "june", password: "first", url: "https://h.test" });1451 expect(vault.getEntryById(e.id)?.passwordHistory).toBeUndefined();14521453 await vault.updateEntry(e.id, { password: "second" });1454 await vault.updateEntry(e.id, { password: "third" });14551456 const hist = vault.getEntryById(e.id)?.passwordHistory ?? [];1457 expect(hist.map((h) => h.password)).toEqual(["second", "first"]);1458 expect(vault.getEntryById(e.id)?.password).toBe("third");1459 });14601461 it("does not record history on a metadata-only update", async () => {1462 const vault = await import("./vault");1463 await vault.createVault("history-meta-12345");1464 const e = await vault.addEntry({ title: "M", username: "june", password: "keepme", url: "https://m.test" });14651466 await vault.updateEntry(e.id, { title: "Renamed" });1467 await vault.updateEntry(e.id, { username: "newuser" });14681469 expect(vault.getEntryById(e.id)?.passwordHistory).toBeUndefined();1470 });14711472 it("records each history item with the age the password carried", async () => {1473 const vault = await import("./vault");1474 await vault.createVault("history-stamp-12345");1475 const e = await vault.addEntry({ title: "S", username: "june", password: "v1", url: "https://s.test" });1476 const firstChangedAt = vault.getEntryById(e.id)!.passwordChangedAt;1477 expect(firstChangedAt).toBeGreaterThan(0);14781479 await new Promise((resolve) => setTimeout(resolve, 2));1480 await vault.updateEntry(e.id, { password: "v2" });14811482 const hist = vault.getEntryById(e.id)!.passwordHistory!;1483 1484 expect(hist[0].changedAt).toBe(firstChangedAt);1485 });14861487 it("skips capture when re-saving the identical password", async () => {1488 const vault = await import("./vault");1489 await vault.createVault("history-noop-12345");1490 const e = await vault.addEntry({ title: "N", username: "june", password: "same", url: "https://n.test" });14911492 await vault.updateEntry(e.id, { password: "same" });14931494 expect(vault.getEntryById(e.id)?.passwordHistory).toBeUndefined();1495 });14961497 it("does not capture an empty prior password (clear then set)", async () => {1498 const vault = await import("./vault");1499 await vault.createVault("history-empty-12345");1500 const e = await vault.addEntry({ title: "E", username: "june", password: "", url: "https://e.test" });15011502 await vault.updateEntry(e.id, { password: "now-has-one" });15031504 1505 expect(vault.getEntryById(e.id)?.passwordHistory ?? []).toHaveLength(0);1506 });15071508 it("restoring an old password re-records the swapped-out current one", async () => {1509 const vault = await import("./vault");1510 await vault.createVault("history-restore-12345");1511 const e = await vault.addEntry({ title: "R", username: "june", password: "old", url: "https://r.test" });1512 await vault.updateEntry(e.id, { password: "new" });15131514 1515 await vault.updateEntry(e.id, { password: "old" });15161517 const hist = vault.getEntryById(e.id)!.passwordHistory!;1518 expect(vault.getEntryById(e.id)?.password).toBe("old");1519 expect(hist.map((h) => h.password)).toEqual(["new", "old"]);1520 });15211522 it("preserves history across lock/unlock (normalizeEntry whitelist)", async () => {1523 const vault = await import("./vault");1524 await vault.createVault("history-persist-12345");1525 const e = await vault.addEntry({ title: "P", username: "june", password: "p1", url: "https://p.test" });1526 await vault.updateEntry(e.id, { password: "p2" });15271528 vault.lock();1529 expect(await vault.unlock("history-persist-12345")).toBe(true);15301531 const hist = vault.getEntryById(e.id)?.passwordHistory ?? [];1532 expect(hist.map((h) => h.password)).toEqual(["p1"]);1533 });15341535 it("caps history at 50 entries, dropping the oldest", async () => {1536 const vault = await import("./vault");1537 await vault.createVault("history-cap-12345");1538 const e = await vault.addEntry({ title: "C", username: "june", password: "pw-0", url: "https://c.test" });15391540 for (let i = 1; i <= 55; i++) {1541 await vault.updateEntry(e.id, { password: `pw-${i}` });1542 }15431544 const hist = vault.getEntryById(e.id)!.passwordHistory!;1545 expect(hist).toHaveLength(50);1546 1547 expect(hist[0].password).toBe("pw-54");1548 expect(hist[hist.length - 1].password).toBe("pw-5");1549 });1550 });15511552 describe("MV-6 import field whitelist (sanitizeRestoredEntry)", () => {1553 it("drops unknown/attacker keys from a restored entry", async () => {1554 const vault = await import("./vault");1555 await vault.createVault("correct horse battery staple");1556 await vault.restoreEntries(1557 [1558 {1559 id: "e1",1560 type: "login",1561 title: "Bank",1562 username: "june",1563 password: "pw",1564 createdAt: 1,1565 modifiedAt: 2,1566 evil: "payload",1567 isAdmin: true,1568 nested: { junk: 1 },1569 } as unknown as import("../shared/types").VaultEntry,1570 ],1571 "replace",1572 );1573 const restored = vault.getEntries().find((e) => e.id === "e1")!;1574 expect(restored.password).toBe("pw");1575 expect((restored as unknown as Record<string, unknown>).evil).toBeUndefined();1576 expect((restored as unknown as Record<string, unknown>).isAdmin).toBeUndefined();1577 expect((restored as unknown as Record<string, unknown>).nested).toBeUndefined();1578 });15791580 it("strips a non-HTTPS canary webhook but keeps the entry", async () => {1581 const vault = await import("./vault");1582 await vault.createVault("correct horse battery staple");1583 await vault.restoreEntries(1584 [1585 {1586 id: "e2",1587 type: "login",1588 title: "Bank",1589 password: "pw",1590 createdAt: 1,1591 modifiedAt: 2,1592 canary: { webhookUrl: "http://attacker.example.com/x" },1593 } as unknown as import("../shared/types").VaultEntry,1594 ],1595 "replace",1596 );1597 const restored = vault.getEntries().find((e) => e.id === "e2")!;1598 expect(restored).toBeDefined();1599 expect(restored.canary).toBeUndefined();1600 });16011602 it("preserves a well-formed HTTPS canary webhook", async () => {1603 const vault = await import("./vault");1604 await vault.createVault("correct horse battery staple");1605 await vault.restoreEntries(1606 [1607 {1608 id: "e3",1609 type: "login",1610 title: "Bank",1611 password: "pw",1612 createdAt: 1,1613 modifiedAt: 2,1614 canary: { webhookUrl: "https://hooks.example.com/x", label: "watch" },1615 } as unknown as import("../shared/types").VaultEntry,1616 ],1617 "replace",1618 );1619 const restored = vault.getEntries().find((e) => e.id === "e3")!;1620 expect(restored.canary?.webhookUrl).toBe("https://hooks.example.com/x");1621 expect(restored.canary?.label).toBe("watch");1622 });16231624 it("rejects an entry whose passkey shape is malformed (missing credentialId)", async () => {1625 const vault = await import("./vault");1626 await vault.createVault("correct horse battery staple");1627 await vault.restoreEntries(1628 [1629 {1630 id: "e4",1631 type: "login",1632 title: "Has bad passkey",1633 createdAt: 1,1634 modifiedAt: 2,1635 passkey: { rpId: "example.com", publicKeyCose: "x" },1636 } as unknown as import("../shared/types").VaultEntry,1637 ],1638 "replace",1639 );1640 expect(vault.getEntries().some((e) => e.id === "e4")).toBe(false);1641 });16421643 });16441645 describe("MV-8 rotateSyncIdentity", () => {1646 it("re-keys the root, clears paired devices, and keeps entries unlockable with the same password", async () => {1647 const vault = await import("./vault");1648 await vault.createVault("correct horse battery staple");1649 const e = await vault.addEntry({ type: "login", title: "Bank", password: "pw" });1650 const { upsertPairedDevice, listPairedDevices } = await import(1651 "./paired-devices"1652 );1653 await upsertPairedDevice({1654 deviceId: "d1",1655 deviceName: "Phone",1656 deviceType: "android",1657 longTermPublicKeyHex: "a".repeat(64),1658 signingPublicKeyHex: "b".repeat(64),1659 pairedAt: 1,1660 trustSource: "direct",1661 });16621663 const rootBefore = vault.getRootKeyHex();1664 const res = await vault.rotateSyncIdentity();1665 expect(res.ok).toBe(true);1666 expect(vault.getRootKeyHex()).not.toBe(rootBefore);1667 expect(await listPairedDevices()).toHaveLength(0);1668 1669 expect(vault.getEntries().find((x) => x.id === e.id)?.title).toBe("Bank");16701671 vault.lock();1672 expect(await vault.unlock("correct horse battery staple")).toBe(true);1673 expect(vault.getEntries().find((x) => x.id === e.id)?.title).toBe("Bank");1674 });16751676 it("invalidates the old recovery words and flags recovery-pending", async () => {1677 const vault = await import("./vault");1678 await vault.createVault("correct horse battery staple");1679 const wordsBefore = (await vault.getRecoveryWords()).join(" ");16801681 await vault.rotateSyncIdentity();16821683 const wordsAfter = (await vault.getRecoveryWords()).join(" ");1684 expect(wordsAfter).not.toBe(wordsBefore);1685 const { isRecoveryConfirmPending } = await import("./recovery-pending");1686 expect(await isRecoveryConfirmPending()).toBe(true);1687 });16881689 it("changes the derived sync vault_id so an old device fails the vault-id gate", async () => {1690 const vault = await import("./vault");1691 await vault.createVault("correct horse battery staple");1692 const { createSyncVaultAdapter } = await import(1693 "./sync-vault-adapter"1694 );1695 const adapter = createSyncVaultAdapter();1696 const vidBefore = await adapter.computeVaultId();16971698 await vault.rotateSyncIdentity();16991700 const vidAfter = await adapter.computeVaultId();1701 expect(vidAfter).not.toBe(vidBefore);1702 });1703 });17041705 describe("LV-1 NFC master password normalization", () => {1706 const CAFE_BASE = "café";1707 const PW_NFD = `${CAFE_BASE.normalize("NFD")}-pw-12345`;1708 const PW_NFC = `${CAFE_BASE.normalize("NFC")}-pw-12345`;17091710 it("a vault created with the NFD form unlocks with the NFC form", async () => {1711 const vault = await import("./vault");1712 expect(PW_NFD).not.toBe(PW_NFC);1713 await vault.createVault(PW_NFD);1714 vault.lock();1715 expect(await vault.unlock(PW_NFC)).toBe(true);1716 });17171718 });17191720 describe("LV-7 updateSettings proto-pollution filter", () => {1721 it("strips __proto__/constructor/prototype keys while persisting real settings", async () => {1722 const vault = await import("./vault");1723 await vault.createVault("correct horse battery staple");17241725 await vault.updateSettings({1726 theme: "dark",1727 ["__proto__"]: { polluted: true },1728 constructor: { polluted: true },1729 } as never);17301731 expect(({} as Record<string, unknown>).polluted).toBeUndefined();1732 expect((Object.prototype as Record<string, unknown>).polluted).toBeUndefined();1733 expect(vault.getSettings().theme).toBe("dark");1734 });1735 });17361737 1738 1739 1740 1741 describe("PB-26-011 url scheme allow-list", () => {1742 let vault: typeof import("./vault");17431744 beforeEach(async () => {1745 vault = await import("./vault");1746 await vault.createVault("correct horse battery staple");1747 });17481749 it("drops a javascript: url on addEntry", async () => {1750 const entry = await vault.addEntry({1751 title: "Evil",1752 username: "june",1753 password: "secret1",1754 url: "javascript:alert(1)",1755 });1756 const stored = vault.getEntryById(entry.id);1757 expect(stored?.url).toBe("");1758 });17591760 it("drops non-http(s) schemes from additionalUrls", async () => {1761 const entry = await vault.addEntry({1762 title: "Evil",1763 username: "june",1764 password: "secret1",1765 url: "https://ok.test",1766 additionalUrls: [1767 "javascript:alert(1)",1768 "data:text/html,<b>x</b>",1769 "https://also-ok.test",1770 ],1771 });1772 const stored = vault.getEntryById(entry.id);1773 expect(stored?.additionalUrls).toEqual(["https://also-ok.test"]);1774 });17751776 it("drops a data: url on UPDATE_ENTRY patch", async () => {1777 const entry = await vault.addEntry({1778 title: "Ok",1779 username: "june",1780 password: "secret1",1781 url: "https://ok.test",1782 });1783 await vault.updateEntry(entry.id, { url: "data:text/html,<b>x</b>" });1784 const stored = vault.getEntryById(entry.id);1785 expect(stored?.url).toBe("");1786 });17871788 it("keeps https and schemeless urls", async () => {1789 const entry = await vault.addEntry({1790 title: "Ok",1791 username: "june",1792 password: "secret1",1793 url: "https://github.com",1794 additionalUrls: ["github.com"],1795 });1796 const stored = vault.getEntryById(entry.id);1797 expect(stored?.url).toBe("https://github.com");1798 expect(stored?.additionalUrls).toEqual(["github.com"]);1799 });1800 });1801});