vault.test.ts

28.7 KB · raw

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>;78describe("background vault", () => {9  let storage: StorageShape;10  let alarms = { created: [] as Array<{ name: string; delayInMinutes: number }>, cleared: [] as string[] };1112  beforeEach(() => {13    vi.resetModules();14    storage = {};15    alarms = { created: [], cleared: [] };1617    const chromeMock = {18      storage: {19        local: {20          get: vi.fn(async (key?: string | string[]) => {21            if (!key) return storage;22            if (typeof key === "string") {23              return { [key]: storage[key] };24            }2526            return key.reduce<Record<string, unknown>>((result, entry) => {27              result[entry] = storage[entry];28              return result;29            }, {});30          }),31          set: vi.fn(async (next: Record<string, unknown>) => {32            Object.assign(storage, next);33          }),34          remove: vi.fn(async (keys: string | string[]) => {35            const list = Array.isArray(keys) ? keys : [keys];36            for (const key of list) {37              delete storage[key];38            }39          }),40        },41      },42      alarms: {43        clear: vi.fn((name: string) => {44          alarms.cleared.push(name);45        }),46        create: vi.fn((name: string, info: { delayInMinutes: number }) => {47          alarms.created.push({ name, delayInMinutes: info.delayInMinutes });48        }),49        onAlarm: { addListener: vi.fn() },50      },51      idle: {52        setDetectionInterval: vi.fn(),53        onStateChanged: { addListener: vi.fn() },54      },55    } as unknown as typeof chrome;5657    (globalThis as { chrome?: typeof chrome }).chrome = chromeMock;5859    // Prevent fire-and-forget breach-check fetches from leaking into other tests.60    vi.stubGlobal("fetch", vi.fn(async () => {61      throw new Error("network disabled in tests");62    }));63  });6465  it("creates a vault and stores encrypted payload", async () => {66    const vault = await import("./vault");6768    await vault.createVault("correct horse battery staple");6970    expect(storage.peach_vault_a).toBeDefined();71    expect((storage.peach_vault_a as StoredVault).ciphertext).toBeTruthy();72    expect(vault.getEntries()).toEqual([]);73    expect(alarms.created).toContainEqual({74      name: "autolock",75      delayInMinutes: 5,76    });77  });7879  it("writes both slots A and B on vault creation", async () => {80    const vault = await import("./vault");81    await vault.createVault("correct horse battery staple");8283    expect(storage.peach_vault_a).toBeDefined();84    expect(storage.peach_vault_b).toBeDefined();85    expect(storage.peach_duress).toBeUndefined();86    expect(storage.peach_vault).toBeUndefined();87    expect(storage.peach_decoy_vault).toBeUndefined();88  });8990  it("slot A and slot B have matching ciphertext size at fresh install", async () => {91    const vault = await import("./vault");92    await vault.createVault("correct horse battery staple");9394    const a = storage.peach_vault_a as StoredVault;95    const b = storage.peach_vault_b as StoredVault;96    expect(a.ciphertext.length).toBe(b.ciphertext.length);97  });9899  it("does not expose a plaintext duress flag after setupDuress", async () => {100    const vault = await import("./vault");101    await vault.createVault("real-password-12345");102    await vault.setupDuress("decoy-password-67890");103104    expect(storage.peach_duress).toBeUndefined();105    expect(storage.peach_decoy_vault).toBeUndefined();106    const keys = Object.keys(storage).filter((k) => k.startsWith("peach_"));107    // Slot-neutral keys + optional settings + vault history (snapshot of the108    // pre-setupDuress real-mode blob). No exposed duress flag.109    for (const key of keys) {110      expect(111        [112          "peach_vault_a",113          "peach_vault_b",114          "peach_settings",115          "peach_vault_history",116          "peach_last_modified_at",117        ]118      ).toContain(key);119    }120    expect(keys).toContain("peach_vault_a");121    expect(keys).toContain("peach_vault_b");122  });123124  it("unlocks with real password and loads real entries", async () => {125    const vault = await import("./vault");126    await vault.createVault("real-password-12345");127    await vault.addEntry({128      title: "GitHub",129      username: "june",130      password: "realsecret",131      url: "github.com",132    });133    vault.lock();134135    const ok = await vault.unlock("real-password-12345");136    expect(ok).toBe(true);137    expect(vault.getEntries()).toHaveLength(1);138    expect(vault.getEntries()[0].title).toBe("GitHub");139  });140141  it("unlocks with duress password and loads empty entries", async () => {142    const vault = await import("./vault");143    await vault.createVault("real-password-12345");144    await vault.addEntry({145      title: "GitHub",146      username: "june",147      password: "realsecret",148      url: "github.com",149    });150    await vault.setupDuress("decoy-password-67890");151    vault.lock();152153    const ok = await vault.unlock("decoy-password-67890");154    expect(ok).toBe(true);155    expect(vault.getEntries()).toEqual([]);156  });157158  it("runs both slot derivations in parallel for constant-time unlock (DUR-002)", async () => {159    // The unlock path must derive keys for both slots unconditionally so a160    // real-mode unlock and a decoy-mode unlock both spend roughly the same161    // wall-clock time. Verified here by spying on deriveKey and asserting it162    // is called twice (once per slot) on every unlock attempt.163    const argon2 = await import("../crypto/argon2");164    const deriveSpy = vi.spyOn(argon2, "deriveKey");165166    const vault = await import("./vault");167    await vault.createVault("real-password-12345");168    await vault.setupDuress("decoy-password-67890");169    vault.lock();170171    deriveSpy.mockClear();172    await vault.unlock("real-password-12345");173    expect(deriveSpy).toHaveBeenCalledTimes(2);174    vault.lock();175176    deriveSpy.mockClear();177    await vault.unlock("decoy-password-67890");178    expect(deriveSpy).toHaveBeenCalledTimes(2);179    vault.lock();180181    deriveSpy.mockClear();182    await vault.unlock("wrong-password-xxxxx");183    expect(deriveSpy).toHaveBeenCalledTimes(2);184185    deriveSpy.mockRestore();186  });187188  it("rejects wrong passwords", async () => {189    const vault = await import("./vault");190    await vault.createVault("real-password-12345");191    vault.lock();192193    const ok = await vault.unlock("nope-nope-nope");194    expect(ok).toBe(false);195  });196197  it("persists duressConfigured across lock/unlock in encrypted payload", async () => {198    const vault = await import("./vault");199    await vault.createVault("real-password-12345");200    await vault.setupDuress("decoy-password-67890");201    vault.lock();202203    await vault.unlock("real-password-12345");204    expect(await vault.isDuressEnabled()).toBe(true);205206    await vault.disableDuress();207    expect(await vault.isDuressEnabled()).toBe(false);208    vault.lock();209210    await vault.unlock("real-password-12345");211    expect(await vault.isDuressEnabled()).toBe(false);212  });213214  it("migrates legacy peach_vault / peach_decoy_vault / peach_duress schema", async () => {215    // Arrange: set up storage as if from pre-A-2 (v1.4.24 and earlier).216    const firstVault = await import("./vault");217    await firstVault.createVault("legacy-password-abcde");218    const legacySlotA = storage.peach_vault_a as StoredVault;219    storage.peach_vault = legacySlotA;220    delete storage.peach_vault_a;221    delete storage.peach_vault_b;222    storage.peach_duress = { enabled: true };223    storage.peach_decoy_vault = legacySlotA; // reuse shape for test224    vi.resetModules();225226    // Act: fresh module load triggers migration on next vault access.227    const vault = await import("./vault");228    await vault.hasVault();229230    // Assert: legacy keys removed, new keys present.231    expect(storage.peach_vault).toBeUndefined();232    expect(storage.peach_decoy_vault).toBeUndefined();233    expect(storage.peach_duress).toBeUndefined();234    expect(storage.peach_vault_a).toBeDefined();235    expect(storage.peach_vault_b).toBeDefined();236  });237238  it("soft deletes entries while keeping deletedAt in encrypted storage", async () => {239    const vault = await import("./vault");240241    await vault.createVault("correct horse battery staple");242    const entry = await vault.addEntry({243      title: "GitHub",244      username: "june",245      password: "secret123",246      url: "github.com",247    });248249    await vault.deleteEntry(entry.id);250251    expect(vault.getEntries()).toEqual([]);252253    const stored = storage.peach_vault_a as StoredVault;254    const salt = Uint8Array.from(255      stored.salt.match(/.{1,2}/g)!.map((value: string) => parseInt(value, 16))256    );257    const key = await deriveKey("correct horse battery staple", salt);258    const plain = await decrypt(key, stored.nonce, stored.ciphertext, stored.tag, "slot_a_v1");259    const parsed = JSON.parse(plain) as { entries: Array<{ id: string; deletedAt?: number }> };260261    expect(parsed.entries).toHaveLength(1);262    expect(parsed.entries[0].id).toBe(entry.id);263    expect(typeof parsed.entries[0].deletedAt).toBe("number");264  });265266  it("accepts imported entries without a username or url", async () => {267    const vault = await import("./vault");268269    await vault.createVault("correct horse battery staple");270    const entry = await vault.addEntry({271      title: "Imported Login",272      username: "",273      password: "secret123",274      url: "",275      notes: "migrated from another manager",276    });277278    expect(entry.username).toBe("");279    expect(entry.url).toBe("");280    expect(vault.getEntries()).toHaveLength(1);281  });282283  it("changePassword happy path — new password unlocks, old is rejected", async () => {284    const vault = await import("./vault");285286    await vault.createVault("old-pass-abc123");287    await vault.addEntry({ title: "GitHub", username: "june", password: "secret1", url: "github.com" });288    await vault.addEntry({ title: "Gmail", username: "june", password: "secret2", url: "mail.google.com" });289290    expect(await vault.changePassword("old-pass-abc123", "new-pass-xyz789")).toBe(true);291292    vault.lock();293    expect(await vault.unlock("new-pass-xyz789")).toBe(true);294    expect(vault.getEntries()).toHaveLength(2);295296    vault.lock();297    expect(await vault.unlock("old-pass-abc123")).toBe(false);298  });299300  it("stamps peach_last_modified_at on createVault", async () => {301    const vault = await import("./vault");302    const before = Date.now();303    await new Promise((resolve) => setTimeout(resolve, 1));304305    await vault.createVault("stamp-create-pass");306307    expect(Number(storage.peach_last_modified_at)).toBeGreaterThanOrEqual(before);308  });309310  it("stamps peach_last_modified_at on entry mutations through persistEntries", async () => {311    const vault = await import("./vault");312    await vault.createVault("stamp-entry-pass");313314    let previous = Number(storage.peach_last_modified_at);315    await new Promise((resolve) => setTimeout(resolve, 1));316    const entry = await vault.addEntry({317      title: "Stamp",318      username: "",319      password: "p",320      url: "",321    });322    expect(Number(storage.peach_last_modified_at)).toBeGreaterThan(previous);323324    previous = Number(storage.peach_last_modified_at);325    await new Promise((resolve) => setTimeout(resolve, 1));326    await vault.updateEntry(entry.id, { title: "Stamped" });327    expect(Number(storage.peach_last_modified_at)).toBeGreaterThan(previous);328329    previous = Number(storage.peach_last_modified_at);330    await new Promise((resolve) => setTimeout(resolve, 1));331    await vault.deleteEntry(entry.id);332    expect(Number(storage.peach_last_modified_at)).toBeGreaterThan(previous);333  });334335  it("stamps peach_last_modified_at on setupDuress and changePassword", async () => {336    const vault = await import("./vault");337    await vault.createVault("stamp-real-pass");338339    let previous = Number(storage.peach_last_modified_at);340    await new Promise((resolve) => setTimeout(resolve, 1));341    await vault.setupDuress("stamp-decoy-pass");342    expect(Number(storage.peach_last_modified_at)).toBeGreaterThan(previous);343344    previous = Number(storage.peach_last_modified_at);345    await new Promise((resolve) => setTimeout(resolve, 1));346    expect(await vault.changePassword("stamp-real-pass", "stamp-new-pass")).toBe(true);347    expect(Number(storage.peach_last_modified_at)).toBeGreaterThan(previous);348  });349350  it("changePassword with wrong current password returns false and leaves slot A unchanged", async () => {351    const vault = await import("./vault");352353    await vault.createVault("correct-pass-abcde");354    const slotABefore = JSON.stringify(storage.peach_vault_a);355356    expect(await vault.changePassword("wrong-pass", "new-pass")).toBe(false);357    expect(JSON.stringify(storage.peach_vault_a)).toBe(slotABefore);358359    vault.lock();360    expect(await vault.unlock("correct-pass-abcde")).toBe(true);361  });362363  it("changePassword with duress configured leaves slot B byte-identical", async () => {364    const vault = await import("./vault");365366    await vault.createVault("real-pass-abcde");367    await vault.setupDuress("duress-pass-xyzzz");368369    const slotBBefore = JSON.stringify(storage.peach_vault_b);370    expect(await vault.changePassword("real-pass-abcde", "new-real-pass-fghij")).toBe(true);371    expect(JSON.stringify(storage.peach_vault_b)).toBe(slotBBefore);372373    // Duress path still works with the old decoy password.374    vault.lock();375    expect(await vault.unlock("duress-pass-xyzzz")).toBe(true);376    expect(vault.getEntries()).toEqual([]);377  });378379  it("restoreEntries with mode 'replace' and empty incoming throws and leaves entries intact", async () => {380    const vault = await import("./vault");381382    await vault.createVault("pass-abcdef");383    await vault.addEntry({ title: "One", username: "", password: "1", url: "" });384    await vault.addEntry({ title: "Two", username: "", password: "2", url: "" });385    await vault.addEntry({ title: "Three", username: "", password: "3", url: "" });386387    await expect(vault.restoreEntries([], "replace")).rejects.toThrow(388      /refuse to replace with empty entry set/i389    );390    expect(vault.getEntries()).toHaveLength(3);391  });392393  it("changePassword swaps the active key before Slot B is regenerated", async () => {394    const vault = await import("./vault");395396    await vault.createVault("correct-pass-12345");397    const entry = await vault.addEntry({398      title: "GitHub",399      username: "june",400      password: "secret123",401      url: "https://github.com",402    });403404    const setMock = chrome.storage.local.set as unknown as ReturnType<typeof vi.fn>;405    const originalSet = setMock.getMockImplementation();406    let injectedDuringSlotBWrite = false;407408    setMock.mockImplementation(async (next: Record<string, unknown>) => {409      Object.assign(storage, next);410411      if (!injectedDuringSlotBWrite && "peach_vault_b" in next) {412        injectedDuringSlotBWrite = true;413        await vault.updateEntry(entry.id, { notes: "updated during password change" });414      }415    });416417    expect(await vault.changePassword("correct-pass-12345", "new-pass-67890")).toBe(true);418419    setMock.mockImplementation(originalSet ?? (async (next: Record<string, unknown>) => {420      Object.assign(storage, next);421    }));422423    vault.lock();424    expect(await vault.unlock("new-pass-67890")).toBe(true);425    expect(vault.getEntryById(entry.id)?.notes).toBe("updated during password change");426427    vault.lock();428    expect(await vault.unlock("correct-pass-12345")).toBe(false);429  });430431  it("restoreEntries replace mode replaces existing entries", async () => {432    const vault = await import("./vault");433434    await vault.createVault("replace-pass-12345");435    await vault.addEntry({ title: "A", username: "june", password: "one", url: "https://a.test" });436    await vault.addEntry({ title: "B", username: "june", password: "two", url: "https://b.test" });437438    const incoming = [439      {440        id: "entry-c",441        type: "login" as const,442        title: "C",443        username: "june",444        password: "three",445        url: "https://c.test",446        createdAt: 10,447        modifiedAt: 10,448      },449      {450        id: "entry-d",451        type: "login" as const,452        title: "D",453        username: "june",454        password: "four",455        url: "https://d.test",456        createdAt: 20,457        modifiedAt: 20,458      },459    ];460461    await expect(vault.restoreEntries(incoming, "replace")).resolves.toEqual({462      added: 2,463      updated: 0,464      skipped: 0,465    });466467    expect(vault.getEntries().map((entry) => entry.id)).toEqual(["entry-c", "entry-d"]);468  });469470  it("restoreEntries merge mode lets newer incoming entries win", async () => {471    const vault = await import("./vault");472473    await vault.createVault("merge-pass-12345");474    const existing = await vault.addEntry({475      title: "GitHub",476      username: "june",477      password: "old-secret",478      url: "https://github.com",479    });480481    await expect(482      vault.restoreEntries(483        [484          {485            ...existing,486            password: "new-secret",487            modifiedAt: existing.modifiedAt + 100,488          },489        ],490        "merge"491      )492    ).resolves.toEqual({ added: 0, updated: 1, skipped: 0 });493494    expect(vault.getEntryById(existing.id)?.password).toBe("new-secret");495  });496497  it("restoreEntries merge mode keeps newer local entries when incoming is older", async () => {498    const vault = await import("./vault");499500    await vault.createVault("merge-pass-67890");501    const existing = await vault.addEntry({502      title: "GitHub",503      username: "june",504      password: "current-secret",505      url: "https://github.com",506    });507508    await expect(509      vault.restoreEntries(510        [511          {512            ...existing,513            password: "stale-secret",514            modifiedAt: existing.modifiedAt - 100,515          },516        ],517        "merge"518      )519    ).resolves.toEqual({ added: 0, updated: 0, skipped: 1 });520521    expect(vault.getEntryById(existing.id)?.password).toBe("current-secret");522  });523524  it("clearVaultEntries without explicit confirmation throws", async () => {525    const vault = await import("./vault");526527    await vault.createVault("clear-pass-12345");528    await vault.addEntry({ title: "A", username: "", password: "one", url: "" });529530    const clearVaultEntries = vault.clearVaultEntries as unknown as (531      confirmation?: unknown532    ) => Promise<void>;533534    await expect(clearVaultEntries()).rejects.toThrow(/explicit confirmation/i);535    await expect(clearVaultEntries("wrong")).rejects.toThrow(/explicit confirmation/i);536    expect(vault.getEntries()).toHaveLength(1);537  });538539  it("clearVaultEntries with REPLACE_ALL soft-deletes all entries", async () => {540    const vault = await import("./vault");541542    await vault.createVault("clear-pass-67890");543    await vault.addEntry({ title: "A", username: "", password: "one", url: "" });544    await vault.addEntry({ title: "B", username: "", password: "two", url: "" });545    await vault.addEntry({ title: "C", username: "", password: "three", url: "" });546547    await vault.clearVaultEntries("REPLACE_ALL");548549    expect(vault.getEntries()).toEqual([]);550    expect(vault.getDeletedEntries()).toHaveLength(3);551    expect(vault.getDeletedEntries().every((entry) => typeof entry.deletedAt === "number")).toBe(true);552  });553554  it("deduplicateEntries throws in decoy mode", async () => {555    const vault = await import("./vault");556557    await vault.createVault("real-pass-12345");558    await vault.addEntry({559      title: "GitHub",560      username: "june",561      password: "secret123",562      url: "https://github.com",563    });564    await vault.setupDuress("duress-pass-12345");565    vault.lock();566567    expect(await vault.unlock("duress-pass-12345")).toBe(true);568    await expect(vault.deduplicateEntries()).rejects.toThrow(/decoy mode/i);569  });570571  it("deduplicateEntries removes older duplicates in real mode", async () => {572    const vault = await import("./vault");573574    await vault.createVault("dedupe-pass-12345");575    await vault.addEntry({576      title: "GitHub",577      username: "june",578      password: "old-secret",579      url: "https://github.com",580    });581    await new Promise<void>((resolve) => setTimeout(resolve, 5));582    const newer = await vault.addEntry({583      title: "GitHub",584      username: "june",585      password: "new-secret",586      url: "https://github.com",587    });588589    expect(await vault.deduplicateEntries()).toBe(1);590    expect(vault.getEntries()).toHaveLength(1);591    expect(vault.getEntries()[0].id).toBe(newer.id);592    expect(vault.getDeletedEntries()).toHaveLength(1);593  });594595  it("updateEntry with an empty password on a login entry throws and rolls back", async () => {596    const vault = await import("./vault");597598    await vault.createVault("update-pass-12345");599    const entry = await vault.addEntry({600      title: "GitHub",601      username: "june",602      password: "secret123",603      url: "https://github.com",604    });605606    await expect(vault.updateEntry(entry.id, { password: "" })).rejects.toThrow(607      /password or passkey required/i608    );609    expect(vault.getEntryById(entry.id)?.password).toBe("secret123");610  });611612  it("updateEntry with an empty password on a note entry is allowed", async () => {613    const vault = await import("./vault");614615    await vault.createVault("note-pass-12345");616    const entry = await vault.addEntry({617      type: "note",618      title: "Secure note",619      notes: "keep me",620    });621622    await expect(vault.updateEntry(entry.id, { password: "", notes: "updated" })).resolves.toBeUndefined();623    expect(vault.getEntryById(entry.id)).toMatchObject({624      type: "note",625      notes: "updated",626    });627  });628629  it("lock zeroes the derived key and resets unlock state", async () => {630    const aes = await import("./aes");631    const zeroKeySpy = vi.spyOn(aes, "zeroKey");632    const vault = await import("./vault");633634    await vault.createVault("lock-pass-12345");635    expect(vault.isUnlocked()).toBe(true);636637    vault.lock();638639    expect(zeroKeySpy).toHaveBeenCalled();640    expect(vault.isUnlocked()).toBe(false);641    zeroKeySpy.mockRestore();642  });643644  it("lock clears in-memory entries", async () => {645    const vault = await import("./vault");646647    await vault.createVault("lock-pass-67890");648    const entry = await vault.addEntry({649      title: "GitHub",650      username: "june",651      password: "secret123",652      url: "https://github.com",653    });654655    expect(vault.getEntryById(entry.id)?.title).toBe("GitHub");656    vault.lock();657    expect(vault.getEntryById(entry.id)).toBeUndefined();658  });659660  it("unlock with neither slot decryptable returns false and leaves the vault locked", async () => {661    const vault = await import("./vault");662663    await vault.createVault("real-pass-67890");664    vault.lock();665666    expect(await vault.unlock("totally-wrong-password")).toBe(false);667    expect(vault.isUnlocked()).toBe(false);668  });669670  it("isUnlocked tracks the full lock lifecycle", async () => {671    const vault = await import("./vault");672673    expect(vault.isUnlocked()).toBe(false);674    await vault.createVault("unlock-pass-12345");675    expect(vault.isUnlocked()).toBe(true);676    vault.lock();677    expect(vault.isUnlocked()).toBe(false);678    expect(await vault.unlock("unlock-pass-12345")).toBe(true);679    expect(vault.isUnlocked()).toBe(true);680    vault.lock();681    expect(vault.isUnlocked()).toBe(false);682  });683684  it("persistEntries surfaces STORAGE_QUOTA_EXCEEDED when slot writes hit quota", async () => {685    const vault = await import("./vault");686687    await vault.createVault("quota-pass-12345");688689    const setMock = chrome.storage.local.set as unknown as ReturnType<typeof vi.fn>;690    setMock.mockImplementation(async (next: Record<string, unknown>) => {691      if ("peach_vault_a" in next || "peach_vault_b" in next) {692        throw new Error("QUOTA_BYTES quota reached");693      }694      Object.assign(storage, next);695    });696697    await expect(698      vault.addEntry({699        title: "GitHub",700        username: "june",701        password: "secret123",702        url: "https://github.com",703      })704    ).rejects.toThrow("STORAGE_QUOTA_EXCEEDED");705  });706707  it("persistSettings surfaces STORAGE_QUOTA_EXCEEDED when settings writes hit quota", async () => {708    const vault = await import("./vault");709710    await vault.createVault("settings-pass-12345");711712    const setMock = chrome.storage.local.set as unknown as ReturnType<typeof vi.fn>;713    setMock.mockImplementation(async (next: Record<string, unknown>) => {714      if ("peach_settings" in next) {715        throw new Error("QUOTA_BYTES quota reached");716      }717      Object.assign(storage, next);718    });719720    await expect(vault.updateSettings({ autoLockMinutes: 10 })).rejects.toThrow(721      "STORAGE_QUOTA_EXCEEDED"722    );723  });724725  it("card entry round-trips through vault — all fields preserved", async () => {726    const vault = await import("./vault");727728    await vault.createVault("card-test-pass-12345");729    const entry = await vault.addEntry({730      type: "card",731      title: "Personal Visa",732      cardholderName: "Jane Smith",733      cardNumber: "4111111111111111",734      expMonth: "05",735      expYear: "2028",736      cvc: "123",737      cardNickname: "Personal Visa",738      network: "visa",739      last4: "1111",740    });741742    expect(entry.type).toBe("card");743    expect(entry.cardholderName).toBe("Jane Smith");744    expect(entry.cardNumber).toBe("4111111111111111");745    expect(entry.expMonth).toBe("05");746    expect(entry.expYear).toBe("2028");747    expect(entry.cvc).toBe("123");748    expect(entry.network).toBe("visa");749    expect(entry.last4).toBe("1111");750751    vault.lock();752    await vault.unlock("card-test-pass-12345");753    const entries = vault.getEntries();754    expect(entries).toHaveLength(1);755    expect(entries[0].cardNumber).toBe("4111111111111111");756    expect(entries[0].cvc).toBe("123");757  });758759  it("updateEntry — cannot clear card number on card entry", async () => {760    const vault = await import("./vault");761762    await vault.createVault("card-guard-pass-12345");763    const entry = await vault.addEntry({764      type: "card",765      title: "My Card",766      cardholderName: "Jane Smith",767      cardNumber: "4111111111111111",768      expMonth: "05",769      expYear: "2028",770      cvc: "123",771    });772773    await expect(774      vault.updateEntry(entry.id, { cardNumber: "" })775    ).rejects.toThrow("card number is required for card entries");776777    const entries = vault.getEntries();778    expect(entries[0].cardNumber).toBe("4111111111111111");779  });780781  it("declineCardSaveOffer — stores fingerprint in settings", async () => {782    const vault = await import("./vault");783784    await vault.createVault("decline-pass-12345");785    await vault.declineCardSaveOffer("1111", "05", "2028");786787    const settings = vault.getSettings();788    expect(settings.declinedCardFingerprints).toHaveLength(1);789  });790791  it("isCardDeclined — returns true for previously declined card", async () => {792    const vault = await import("./vault");793794    await vault.createVault("declined-check-pass-12345");795    await vault.declineCardSaveOffer("1111", "05", "2028");796797    expect(await vault.isCardDeclined("1111", "05", "2028")).toBe(true);798  });799800  it("isCardDeclined — returns false for card with same last4 but different expiry", async () => {801    const vault = await import("./vault");802803    await vault.createVault("declined-diff-pass-12345");804    await vault.declineCardSaveOffer("1111", "05", "2028");805806    expect(await vault.isCardDeclined("1111", "06", "2028")).toBe(false);807  });808809  it("queryDomain matches an entry against its additionalUrls", async () => {810    const vault = await import("./vault");811812    await vault.createVault("multi-domain-pass-12345");813    const entry = await vault.addEntry({814      type: "login",815      title: "Foo",816      username: "june",817      password: "secret",818      url: "https://foo.com",819      additionalUrls: ["https://bar.io", "https://baz.org"],820    });821822    // Vault index keys by eTLD+1 (tldts.getDomain), so additionalUrls only823    // add new buckets when the eTLD+1 is genuinely different from the primary.824    expect(vault.queryDomain("foo.com").map((e) => e.id)).toContain(entry.id);825    expect(vault.queryDomain("bar.io").map((e) => e.id)).toContain(entry.id);826    expect(vault.queryDomain("baz.org").map((e) => e.id)).toContain(entry.id);827    expect(vault.queryDomain("unrelated.com")).toEqual([]);828  });829830  it("updateEntry trims, dedupes, and clears empty additionalUrls", async () => {831    const vault = await import("./vault");832833    await vault.createVault("dedupe-additional-pass-12345");834    const entry = await vault.addEntry({835      type: "login",836      title: "Foo",837      username: "june",838      password: "secret",839      url: "https://foo.com",840    });841842    await vault.updateEntry(entry.id, {843      additionalUrls: [844        "  https://login.foo.com  ",845        "https://login.foo.com",846        "",847        "  ",848        "https://accounts.foo.com",849      ],850    });851852    const stored = vault.getEntryById(entry.id);853    expect(stored?.additionalUrls).toEqual([854      "https://login.foo.com",855      "https://accounts.foo.com",856    ]);857858    await vault.updateEntry(entry.id, { additionalUrls: ["", "   "] });859    expect(vault.getEntryById(entry.id)?.additionalUrls).toBeUndefined();860  });861});