123456789101112import { vi } from "vitest";131415const { predictBatch, dismissSpy } = vi.hoisted(() => ({16 predictBatch: vi.fn(() => Promise.resolve([] as unknown[])),17 dismissSpy: vi.fn(),18}));192021vi.mock("./inject", () => ({22 injectFieldIcon: vi.fn(() => vi.fn()),23 showAutofillSelector: vi.fn(() => dismissSpy),24 showTOTPSelector: vi.fn(() => dismissSpy),25 showCardSelector: vi.fn(() => dismissSpy),26 showRememberSiteToast: vi.fn(),27 showPasskeyAvailable: vi.fn(),28 showPasskeyProGate: vi.fn(),29 showPasskeyRegistrationOffer: vi.fn(),30}));313233vi.mock("./content-ml-detector", () => ({34 contentMLDetector: { predictBatch },35}));3637import { afterEach, beforeEach, describe, expect, it } from "vitest";38import "./_setup";39import { setMessageResponder, resetChromeMock, sentMessages, messageListeners, makeInput, createLoginForm, createEmailFirstForm } from "./_setup";40import { handleFieldInteraction } from "./index";41import { showAutofillSelector, showRememberSiteToast, showTOTPSelector } from "./inject";4243const showSelector = showAutofillSelector as unknown as ReturnType<typeof vi.fn>;44const showTOTP = showTOTPSelector as unknown as ReturnType<typeof vi.fn>;45const showRememberToast = showRememberSiteToast as unknown as ReturnType<typeof vi.fn>;464748495051beforeEach(() => {52 document.body.innerHTML = "";53 resetChromeMock();54 showSelector.mockClear();55 showTOTP.mockClear();56 predictBatch.mockReset();57 predictBatch.mockReturnValue(Promise.resolve([]));58});5960afterEach(async () => {61 vi.useRealTimers();62 63 64 65 66 await new Promise((r) => setTimeout(r, 0));67});686970function lastSelectorOptions(): any {71 const calls = showSelector.mock.calls;72 return calls.length ? calls[calls.length - 1]![3] : undefined;73}7475describe("T-F01–T-F02: ML predict timeout race (150ms)", () => {76 77 78 it("T-F02: ML resolves fast with a suppressing prediction → no selector", async () => {79 const { username } = createLoginForm();80 predictBatch.mockReturnValue(Promise.resolve([{ type: "search", confidence: 0.9 }]));81 await handleFieldInteraction(username); 82 83 await new Promise((r) => setTimeout(r, 20));84 expect(showSelector).not.toHaveBeenCalled();85 });8687 88 89 90 91 it("T-F01: ML slower than 150ms → timeout path taken, selector still opens", async () => {92 const { username } = createLoginForm();93 predictBatch.mockReturnValue(94 new Promise((resolve) => setTimeout(() => resolve([{ type: "search", confidence: 0.9 }]), 250))95 );96 setMessageResponder((msg) =>97 msg.type === "AUTOFILL_QUERY" ? { ok: true, data: [{ id: "e1", title: "Acme", username: "alice" }] } : { ok: true, data: null }98 );99 await handleFieldInteraction(username);100 await vi.waitFor(() => expect(showSelector).toHaveBeenCalled(), { timeout: 1000 });101 });102});103104describe("T-F03–T-F05: vault state + form shape", () => {105 106 107 it("T-F03: locked vault → selector opened in locked mode", async () => {108 const { password } = createLoginForm();109 setMessageResponder((msg) =>110 msg.type === "AUTOFILL_QUERY" ? { ok: false, error: "vault_locked" } : { ok: true, data: null }111 );112 await handleFieldInteraction(password);113 await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());114 expect(lastSelectorOptions()?.locked).toBe(true);115 });116117 118 119 it("T-F04: no domain entries → signup/identity surface", async () => {120 const { password } = createLoginForm();121 setMessageResponder((msg) =>122 msg.type === "AUTOFILL_QUERY" ? { ok: true, data: [] } : { ok: true, data: null }123 );124 await handleFieldInteraction(password);125 await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());126 expect(lastSelectorOptions()?.isSignup).toBe(true);127 expect(lastSelectorOptions()?.locked).toBeFalsy();128 expect(sentMessages.some((msg) => msg.type === "GET_IDENTITIES")).toBe(false);129 });130131 132 133 it("T-F05: email-first form opens on the email field", async () => {134 const { email } = createEmailFirstForm();135 setMessageResponder((msg) =>136 msg.type === "AUTOFILL_QUERY" ? { ok: true, data: [{ id: "e1", title: "Acme", username: "alice" }] } : { ok: true, data: null }137 );138 await handleFieldInteraction(email);139 await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());140 });141});142143describe("T-F07: TOTP field path", () => {144 145 146 it("T-F07: standalone one-time-code field → TOTP selector", async () => {147 const totp = makeInput({ type: "text", autocomplete: "one-time-code", name: "otp" });148 setMessageResponder((msg) =>149 msg.type === "AUTOFILL_QUERY" ? { ok: true, data: [{ id: "t1", title: "Acme 2FA" }] } : { ok: true, data: null }150 );151 await handleFieldInteraction(totp);152 await vi.waitFor(() => expect(showTOTP).toHaveBeenCalled());153 expect(showSelector).not.toHaveBeenCalled();154 });155});156157describe("T-F09: Peach respects the user, not the page's autocomplete=off", () => {158 159 160 it("T-F09: form with autocomplete=off still offers", async () => {161 const form = document.createElement("form");162 form.setAttribute("autocomplete", "off");163 document.body.appendChild(form);164 makeInput({ type: "text", name: "username", autocomplete: "username" }, form);165 const password = makeInput({ type: "password", autocomplete: "current-password" }, form);166 setMessageResponder((msg) =>167 msg.type === "AUTOFILL_QUERY" ? { ok: true, data: [{ id: "e1", title: "Acme", username: "alice" }] } : { ok: true, data: null }168 );169 await handleFieldInteraction(password);170 await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());171 });172});173174describe("T-F10–T-F12: robustness", () => {175 176 177 178 it("T-F10/T-F12: detached field mid-interaction → clean abort, no throw, no selector", async () => {179 const detached = document.createElement("input");180 detached.type = "password"; 181 await expect(handleFieldInteraction(detached)).resolves.toBeUndefined();182 expect(showSelector).not.toHaveBeenCalled();183 });184185 186 187 it("T-F11: concurrent calls for the same field → selector opens at most once", async () => {188 const { password } = createLoginForm();189 setMessageResponder((msg) =>190 msg.type === "AUTOFILL_QUERY" ? { ok: true, data: [{ id: "e1", title: "Acme", username: "alice" }] } : { ok: true, data: null }191 );192 await Promise.all([handleFieldInteraction(password), handleFieldInteraction(password)]);193 await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());194 expect(showSelector).toHaveBeenCalledTimes(1);195 });196});197198describe("PB-26-201: browser-command capability propagation", () => {199 it("passes the capability through form inventory and the selected fill", async () => {200 const { password } = createLoginForm();201 setMessageResponder((msg) => {202 if (msg.type === "AUTOFILL_QUERY") {203 return { ok: true, data: [{ id: "foreign-entry", title: "Foreign", username: "alice" }] };204 }205 if (msg.type === "GET_ENTRY_FOR_FILL") {206 return { ok: true, data: { id: "foreign-entry", title: "Foreign", username: "alice", password: "secret" } };207 }208 return { ok: true, data: null };209 });210211 await handleFieldInteraction(password, true, "form-capability");212 await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());213214 expect(sentMessages.find((msg) => msg.type === "AUTOFILL_QUERY")).toMatchObject({215 payload: { includeAll: true, capability: "form-capability" },216 });217 const onSelect = showSelector.mock.calls.at(-1)![2] as (id: string) => Promise<void>;218 await onSelect("foreign-entry");219 expect(sentMessages.find((msg) => msg.type === "GET_ENTRY_FOR_FILL")).toMatchObject({220 payload: { id: "foreign-entry", capability: "form-capability" },221 });222 });223224 it("passes the capability through TOTP inventory and the selected fill", async () => {225 const totp = makeInput({ type: "text", autocomplete: "one-time-code", name: "otp" });226 setMessageResponder((msg) => {227 if (msg.type === "AUTOFILL_QUERY") return { ok: true, data: [{ id: "totp-entry", title: "Foreign 2FA" }] };228 if (msg.type === "GET_ENTRY_FOR_FILL") return { ok: true, data: { id: "totp-entry", totpCode: "123456" } };229 return { ok: true, data: null };230 });231232 await handleFieldInteraction(totp, true, "totp-capability");233 await vi.waitFor(() => expect(showTOTP).toHaveBeenCalled());234 expect(sentMessages.find((msg) => msg.type === "AUTOFILL_QUERY")).toMatchObject({235 payload: { kind: "totp", capability: "totp-capability" },236 });237238 const onSelect = showTOTP.mock.calls.at(-1)![2] as (id: string) => Promise<void>;239 await onSelect("totp-entry");240 expect(sentMessages.find((msg) => msg.type === "GET_ENTRY_FOR_FILL")).toMatchObject({241 payload: { id: "totp-entry", capability: "totp-capability" },242 });243 });244});245246247248249250describe("PB-26-949: selector fill consumes only the allowlisted reply", () => {251 it("fills username, password and TOTP from an allowlist-only reply", async () => {252 const { form, username, password } = createLoginForm();253 254 255 form.action = "https://localhost/login";256 const totp = makeInput({ type: "text", autocomplete: "one-time-code", name: "otp" }, form);257 setMessageResponder((msg) => {258 if (msg.type === "AUTOFILL_QUERY") {259 return { ok: true, data: [{ id: "acme", title: "Acme", username: "alice" }] };260 }261 if (msg.type === "GET_ENTRY_FOR_FILL") {262 return {263 ok: true,264 data: {265 id: "acme",266 title: "Acme",267 username: "alice",268 email: "[email protected]",269 password: "s3cret",270 url: "https://acme.test",271 additionalUrls: ["https://login.acme.test"],272 totpCode: "123456",273 totpRemaining: 24,274 },275 };276 }277 return { ok: true, data: null };278 });279280 281 282 283 for (const listener of messageListeners) {284 listener({ type: "SUMMON_AUTOFILL", source: "shortcut" }, { id: chrome.runtime.id }, () => {});285 }286 await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());287 const onSelect = showSelector.mock.calls.at(-1)![2] as (id: string) => Promise<void>;288 await onSelect("acme");289290 expect(username.value).toBe("alice");291 expect(password.value).toBe("s3cret");292 expect(totp.value).toBe("123456");293 });294295 it("offers to save the same-domain login after a fill", async () => {296 const { form, username, password } = createLoginForm();297 298 299 form.action = "https://localhost/login";300 showRememberToast.mockClear();301 setMessageResponder((msg) => {302 if (msg.type === "AUTOFILL_QUERY") {303 return { ok: true, data: [{ id: "acme", title: "Acme", username: "alice" }] };304 }305 if (msg.type === "GET_ENTRY_FOR_FILL") {306 return {307 ok: true,308 data: {309 id: "acme",310 title: "Acme",311 username: "alice",312 password: "s3cret",313 url: "http://localhost",314 },315 };316 }317 return { ok: true, data: null };318 });319320 for (const listener of messageListeners) {321 listener({ type: "SUMMON_AUTOFILL", source: "shortcut" }, { id: chrome.runtime.id }, () => {});322 }323 await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());324 const onSelect = showSelector.mock.calls.at(-1)![2] as (id: string) => Promise<void>;325 await onSelect("acme");326327 expect(username.value).toBe("alice");328 expect(password.value).toBe("s3cret");329 330 331 expect(showRememberToast).not.toHaveBeenCalled();332 });333334 it("stays quiet when an additional URL covers the page", async () => {335 const { form, username } = createLoginForm();336 form.action = "https://localhost/login";337 showRememberToast.mockClear();338 setMessageResponder((msg) => {339 if (msg.type === "AUTOFILL_QUERY") {340 return { ok: true, data: [{ id: "acme", title: "Acme", username: "alice" }] };341 }342 if (msg.type === "GET_ENTRY_FOR_FILL") {343 return {344 ok: true,345 data: {346 id: "acme",347 title: "Acme",348 username: "alice",349 password: "s3cret",350 url: "https://elsewhere.test",351 additionalUrls: ["http://localhost:3000/login"],352 },353 };354 }355 return { ok: true, data: null };356 });357358 for (const listener of messageListeners) {359 listener({ type: "SUMMON_AUTOFILL", source: "shortcut" }, { id: chrome.runtime.id }, () => {});360 }361 await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());362 const onSelect = showSelector.mock.calls.at(-1)![2] as (id: string) => Promise<void>;363 await onSelect("acme");364365 expect(username.value).toBe("alice");366 367 expect(showRememberToast).not.toHaveBeenCalled();368 });369370 it("offers to save a login that covers neither URL nor additional URLs", async () => {371 const { form, username } = createLoginForm();372 form.action = "https://localhost/login";373 showRememberToast.mockClear();374 setMessageResponder((msg) => {375 if (msg.type === "AUTOFILL_QUERY") {376 return { ok: true, data: [{ id: "acme", title: "Acme", username: "alice" }] };377 }378 if (msg.type === "GET_ENTRY_FOR_FILL") {379 return {380 ok: true,381 data: {382 id: "acme",383 title: "Acme",384 username: "alice",385 password: "s3cret",386 url: "https://elsewhere.test",387 additionalUrls: ["https://login.elsewhere.test"],388 },389 };390 }391 return { ok: true, data: null };392 });393394 for (const listener of messageListeners) {395 listener({ type: "SUMMON_AUTOFILL", source: "shortcut" }, { id: chrome.runtime.id }, () => {});396 }397 await vi.waitFor(() => expect(showSelector).toHaveBeenCalled());398 const onSelect = showSelector.mock.calls.at(-1)![2] as (id: string) => Promise<void>;399 await onSelect("acme");400401 expect(username.value).toBe("alice");402 expect(showRememberToast).toHaveBeenCalledWith("http://localhost:3000", "acme");403 });404});