import { detectCardForm, detectLoginFields, findOTPDigitBoxGroup, findOtpSignalingGroup, getDeepActiveInput, getPageDomain, isAnyCredentialForm, isEmailFirstForm, isLoginForm, isSignupForm, isTOTPField, isVisible, } from "./detect"; import { type CardSelectorEntry, injectFieldIcon, type SelectorEntry, showAutofillSelector, showCardSelector, showPasskeyAvailable, showPasskeyProGate, showRememberSiteToast, showTotpCopyToast, showTOTPSelector, } from "./inject"; import { detectBrowser } from "../shared/browser"; import { fillAllowed, fillCardForm, fillFields, fillOTPDigitBoxes, fillTOTPCode, setNativeValue } from "./fill"; import { resolveAutofillInteractionTargets } from "./interaction"; import { setupSaveDetection } from "./save"; import { contentMLDetector } from "./content-ml-detector"; import { detectPasswordPolicy } from "./policy"; import type { FieldPrediction } from "../shared/ml"; import type { VaultEntry } from "../shared/types"; import { setPasskeyToastClosedListener } from "./passkey-toast/lifecycle"; // WeakMap (not WeakSet) — we keep the per-input cleanup callback as the value // so we can tear down listeners if we ever need to re-process the same field. // When the input is GC'd (SPA nav, React re-render), the map entry goes with // it and we can re-inject without leaking the old handler. const processedInputs = new WeakMap void>(); const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]); let currentDismiss: (() => void) | null = null; // Field whose selector is currently open — used to avoid dismiss+reopen flicker let currentAnchorField: HTMLInputElement | null = null; // Prevents two concurrent handleFieldInteraction calls for the same field const pendingInteractions = new WeakSet(); // Tracks the last field the user explicitly dismissed (Escape / click-outside / Tab). // Suppresses spurious reopens until focus moves to a different field. Layer 1 // of the dismissal model — see Projects.md §4.12. let lastDismissedField: HTMLInputElement | null = null; // ── Dismissal lock (Layer 2) ──────────────────────────────────────── // After any user-initiated dismiss, briefly block ALL reopens regardless of // which field is focused. Catches the case where a page rapidly moves focus // between fields after Escape — without this, focus moving to a SECOND field // in <100ms would re-trigger the popup before the user finished dismissing. const DISMISS_LOCK_MS = 800; let dismissLock = false; let dismissLockTimer: ReturnType | null = null; // Set when the inline popup was summoned specifically for a passkey-unlock // flow. The VAULT_UNLOCKED handler checks this to skip re-triggering autofill // (the passkey toast handles the next step instead). let passkeySummonActive = false; // Set while the passkey approval toast is visible. Prevents handleFieldInteraction // from opening the autofill selector alongside it. Cleared by the isolated-world // toast lifecycle channel when the toast closes (and by DISMISS_PASSKEY_TOAST). let passkeyToastActive = false; let passkeyToastToken: string | null = null; function startDismissLock(): void { dismissLock = true; if (dismissLockTimer) clearTimeout(dismissLockTimer); dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS); } function canOpen(): boolean { return !dismissLock; } // ── Fill-success lock ─────────────────────────────────────────────── // After Peach autofills a form, the popup must NOT reappear on the filled // fields, on the submit button (some sites refocus it briefly), or on any // field in that form — even when host-page DOM mutations or the form's own // validation flow refocus an input. Implemented as a WeakSet of forms plus // a page-level timestamp: // - filledForms: every form Peach has filled this page session. Survives // until the form leaves the DOM (WeakSet GC). // - pageFilledAt: timestamp of last fill. Used as a 3s belt-and-suspenders // window for fields that aren't inside a
element (some SPAs). // SPA navigation resets pageFilledAt via the urlObserver below; filledForms // self-empties as old form elements get GC'd. const filledForms = new WeakSet(); let pageFilledAt: number | null = null; const PAGE_FILL_GRACE_MS = 3000; function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void { for (const f of fields) { if (!f) continue; const form = f.closest("form"); if (form) filledForms.add(form); } pageFilledAt = Date.now(); } export /* @testable */ function wasAlreadyFilled(field: HTMLInputElement): boolean { const form = field.closest("form"); if (form && filledForms.has(form)) return true; if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true; return false; } function clearFillStateForExplicitSummon(field: HTMLInputElement): void { const form = field.closest("form"); if (form) filledForms.delete(form); pageFilledAt = null; } // Some sites briefly focus the submit button when the user clicks it (visual // feedback, blur/focus dance for validation animations). Catch those at the // focusin layer so we don't re-trigger handleFieldInteraction for an event // target that was never going to be a credential field anyway. function isSubmitButton(el: EventTarget | null): boolean { if (!(el instanceof HTMLElement)) return false; if (el instanceof HTMLButtonElement && el.type !== "button") return true; if (el instanceof HTMLInputElement && el.type === "submit") return true; if (el.getAttribute("type") === "submit") return true; const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase(); if (!text || text.length > 24) return false; return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text); } function debounce void>( fn: T, ms: number ): (...args: Parameters) => void { let timer: ReturnType; return (...args: Parameters) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), ms); }; } function showToast(message: string): void { const toast = document.createElement("div"); toast.style.cssText = ` position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); background: #131109; color: #F0E8D8; padding: 8px 16px; border-radius: 8px; font-family: 'IBM Plex Mono', monospace; font-size: 11px; z-index: 2147483647; opacity: 0; transition: opacity 200ms ease; border: 1px solid rgba(240,232,216,0.07); pointer-events: none; `; toast.textContent = message; document.body.appendChild(toast); requestAnimationFrame(() => { toast.style.opacity = "1"; }); setTimeout(() => { toast.style.opacity = "0"; setTimeout(() => toast.remove(), 200); }, 2000); } function showSearchPalette(capability?: string): void { const host = document.createElement("div"); host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;"; document.body.appendChild(host); const shadow = host.attachShadow({ mode: "closed" }); const style = document.createElement("style"); style.textContent = ` .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px; font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8; box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden} .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08); font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center} .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1} .s{padding:8px 12px} .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06); border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8; padding:6px 8px;font-family:inherit;font-size:12px;outline:none} .l{max-height:220px;overflow-y:auto} .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px} .e:hover{background:rgba(240,232,216,.06)} .et{font-size:12px} .eu{font-size:10px;color:rgba(240,232,216,.45)} .em{padding:12px;color:rgba(240,232,216,.4);text-align:center} `; let allEntries: SelectorEntry[] = []; let query = ""; const panel = document.createElement("div"); panel.className = "p"; const hdr = document.createElement("div"); hdr.className = "h"; const hdrText = document.createElement("span"); hdrText.textContent = "No form detected — search your vault"; const closeBtn = document.createElement("button"); closeBtn.className = "x"; closeBtn.textContent = "✕"; hdr.appendChild(hdrText); hdr.appendChild(closeBtn); const searchWrap = document.createElement("div"); searchWrap.className = "s"; const searchInput = document.createElement("input"); searchInput.placeholder = "search..."; searchWrap.appendChild(searchInput); const list = document.createElement("div"); list.className = "l"; panel.appendChild(hdr); panel.appendChild(searchWrap); panel.appendChild(list); shadow.appendChild(style); shadow.appendChild(panel); function close() { host.remove(); } closeBtn.onclick = close; function onKeyDown(e: KeyboardEvent) { if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); } } document.addEventListener("keydown", onKeyDown, true); function render() { const q = query.toLowerCase(); const filtered = q ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q)) : allEntries; list.innerHTML = ""; if (filtered.length === 0) { const em = document.createElement("div"); em.className = "em"; em.textContent = query ? "no matches" : "vault is empty"; list.appendChild(em); return; } for (const entry of filtered.slice(0, 20)) { const row = document.createElement("div"); row.className = "e"; const title = document.createElement("div"); title.className = "et"; title.textContent = entry.title; row.appendChild(title); if (entry.username) { const user = document.createElement("div"); user.className = "eu"; user.textContent = entry.username; row.appendChild(user); } row.onclick = async () => { // MV-1: vault-wide search list is a cross-domain summon — the user // explicitly picked this entry to fill on this page. const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability } }); const r = resp as { ok: boolean; data?: { password?: string } }; if (r.ok && r.data?.password) { let alreadyWritten = false; try { await navigator.clipboard.writeText(r.data.password); alreadyWritten = true; } catch (err) { console.warn("[Peach] clipboard write denied:", err); } const copyResp = await chrome.runtime.sendMessage({ type: "COPY", payload: { text: r.data.password, label: "Password", alreadyWritten }, }) as { ok?: boolean } | undefined; if (alreadyWritten || copyResp?.ok) { showToast("Password copied"); } else { showToast("Could not copy password — clipboard blocked"); } } else { showToast("Could not copy password"); } close(); document.removeEventListener("keydown", onKeyDown, true); }; list.appendChild(row); } } searchInput.oninput = () => { query = searchInput.value; render(); }; // The browser-issued command capability, not page UI state, authorizes the // vault-wide inventory. fetchAutofillEntries(getPageDomain(), true, capability).then(result => { if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; } allEntries = result.entries; render(); searchInput.focus(); }); } function findTOTPField(root: Document | Element = document): HTMLInputElement | null { const inputs = root.querySelectorAll("input"); for (const input of inputs) { if (isTOTPField(input)) return input; } return null; } function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null { const form = passwordEl.closest("form"); return findTOTPField(form ?? document); } async function handleAutofill( _field: HTMLInputElement, usernameEl: HTMLInputElement | null, passwordEl: HTMLInputElement | null, entry: VaultEntry, emailEl?: HTMLInputElement | null ): Promise<{ filledTOTPField: HTMLInputElement | null; gatePassed: boolean }> { if (!entry.username && !entry.password && !entry.email) return { filledTOTPField: null, gatePassed: false }; const pageDomain = getPageDomain(); const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null; // Fill the email field with entry.email if set; fall back to entry.username when // it looks like an email address (sites that store email-as-username and have a // separate email field on signup forms). const emailValue = entry.email ?? (entry.username?.includes("@") ? entry.username : ""); const gatePassed = fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain, emailEl, emailValue); let filledTOTPField: HTMLInputElement | null = null; if (entry.canary && gatePassed) { chrome.runtime.sendMessage({ type: "FIRE_CANARY_PING", payload: { webhookUrl: entry.canary.webhookUrl, entryTitle: entry.title, trigger: "autofilled", }, }).catch(() => {}); chrome.runtime.sendMessage({ type: "UPDATE_ENTRY", payload: { id: entry.id, patch: { canary: { ...entry.canary, lastPinged: Date.now(), pingCount: (entry.canary.pingCount ?? 0) + 1, }, }, }, }).catch(() => {}); } // The background sends a freshly-generated 6-digit code (totpCode), never the // base32 seed (SEV-3-C). Fill the code straight in. const totpCode = (entry as { totpCode?: string }).totpCode; if (totpCode && gatePassed) { const code = totpCode; const totpField = passwordEl ? findSameLoginTOTPField(passwordEl) : null; if (fillTOTPCode(totpField, code, form, pageDomain)) { filledTOTPField = totpField; } let alreadyWritten = false; try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch (err) { console.warn("[Peach] clipboard write denied:", err); } const response = await chrome.runtime.sendMessage({ type: "COPY", payload: { text: code, label: "TOTP", alreadyWritten }, }); const res = response as { ok?: boolean; clearSeconds?: number }; if (filledTOTPField) { showToast("2FA code filled"); } else if (alreadyWritten || res.ok) { // Don't render the live code into the toast — the page can read it from the // DOM and consume the one-time code (audit LOW). The code is already on the // clipboard; the toast confirms the copy and shows how long until the // clipboard self-clears (Addendum 2). 30 mirrors DEFAULT_CLEAR_SECONDS. showTotpCopyToast(res.clearSeconds ?? 30); } else { showToast("Could not copy TOTP — clipboard blocked"); } } return { filledTOTPField, gatePassed }; } async function fetchAutofillEntries( domain: string, includeAll = false, capability?: string ): Promise<{ entries: SelectorEntry[]; locked: boolean }> { const response = await chrome.runtime.sendMessage({ type: "AUTOFILL_QUERY", payload: { domain, includeAll, capability }, }); const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string }; if (!res.ok && res.error === "vault_locked") { return { entries: [], locked: true }; } return { entries: res.data ?? [], locked: false }; } async function fetchTOTPEntries( domain: string, capability?: string, ): Promise<{ entries: SelectorEntry[]; locked: boolean }> { const response = await chrome.runtime.sendMessage({ type: "AUTOFILL_QUERY", payload: { domain, kind: "totp", capability }, }); const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string }; if (!res.ok && res.error === "vault_locked") { return { entries: [], locked: true }; } return { entries: res.data ?? [], locked: false }; } function resolveAutofillFieldType( el: HTMLInputElement, predictedType?: FieldPrediction["type"] | null ): "password" | "username" | "email" | null { if ( predictedType === "password" || predictedType === "username" || predictedType === "email" ) { return predictedType; } const detected = detectLoginFields().find((field) => field.el === el)?.type; if (detected && AUTOFILL_FIELD_TYPES.has(detected)) { return detected; } const htmlType = el.type.toLowerCase(); if (htmlType === "password") return "password"; if (htmlType === "email") return "email"; return null; } async function openAutofillSelector( anchorField: HTMLInputElement, usernameEl: HTMLInputElement | null, passwordEl: HTMLInputElement | null, domainEntries: SelectorEntry[], loadSearchableEntries: () => Promise, domain: string, identityKind: "email" | "username", emailEl?: HTMLInputElement | null, capability?: string, ): Promise { // No saved entries for this site → signup/new-account mode. // Locate the confirm-password field so "Copy & fill" can populate it too. const isSignup = domainEntries.length === 0; let confirmEl: HTMLInputElement | null = null; if (isSignup) { const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body; const allPwInputs = Array.from(form.querySelectorAll("input[type='password']")); confirmEl = allPwInputs.find( (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder) ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null); } currentDismiss?.(); currentAnchorField = anchorField; currentDismiss = showAutofillSelector( anchorField, domainEntries, async (id: string) => { currentDismiss = null; currentAnchorField = null; const entryResponse = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id, capability }, }); const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data; if (entry) { const { filledTOTPField, gatePassed } = await handleAutofill(anchorField, usernameEl, passwordEl, entry, emailEl); if (gatePassed) recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField); // Offer to remember the current site for this entry only if none of // its known domains (primary + additional) match — otherwise the // user already mapped it and the prompt would be noise. const pageDomain = location.hostname.replace(/^www\./, ""); const entryDomains = new Set(); for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) { try { if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, "")); } catch { /* ignore unparseable */ } } if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) { showRememberSiteToast(pageDomain, entry.id); } } }, { domain, capability, loadSearchableEntries, isSignup, identityKind, hasEmailField: !!emailEl, onFillFields: (username, password, email) => { const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null; if (!fillFields(usernameEl, passwordEl, username, password, form, getPageDomain(), emailEl, email)) return; if (password && confirmEl) setNativeValue(confirmEl, password); recordFillSuccess(anchorField, usernameEl, passwordEl); }, onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); }, } ); } async function openTOTPSelector( anchorField: HTMLInputElement, otpDigitBoxes?: HTMLInputElement[], capability?: string, ): Promise { if (!canOpen()) return; if (currentDismiss && currentAnchorField === anchorField) return; if (anchorField !== lastDismissedField) lastDismissedField = null; if (anchorField === lastDismissedField) return; if (wasAlreadyFilled(anchorField)) return; const domain = getPageDomain(); const result = await fetchTOTPEntries(domain, capability); if (result.locked) { currentDismiss?.(); currentAnchorField = anchorField; currentDismiss = showAutofillSelector( anchorField, [], () => {}, { domain, locked: true, onUnlocked: () => void openTOTPSelector(anchorField), onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); }, } ); return; } if (result.entries.length === 0) { lastDismissedField = anchorField; startDismissLock(); showToast("No 2FA entries for this site — add a code in Peach first"); return; } currentDismiss?.(); currentAnchorField = anchorField; currentDismiss = showTOTPSelector( anchorField, result.entries, async (id: string) => { try { const entryResponse = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id, capability }, }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null; const entry = entryResponse?.ok ? entryResponse.data : undefined; const code = (entry as { totpCode?: string } | undefined)?.totpCode; if (!code) return; if (!fillAllowed(anchorField.closest("form"), getPageDomain())) return; if (otpDigitBoxes && otpDigitBoxes.length > 1) { fillOTPDigitBoxes(otpDigitBoxes, code); } else { setNativeValue(anchorField, code); } recordFillSuccess(anchorField); showToast("2FA code filled"); } finally { currentDismiss = null; currentAnchorField = null; } }, { domain, onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); currentDismiss = null; currentAnchorField = null; }, } ); } export /* @testable */ async function handleFieldInteraction( anchorField?: HTMLInputElement | null, explicitSummon = false, capability?: string ): Promise { const field = anchorField ?? getDeepActiveInput(); if (!field) return; if (!isVisible(field)) return; // Passkey toast is visible — don't open the credential selector alongside it. if (passkeyToastActive) return; // Layer 2: post-dismiss global lock. Catches rapid focus moves between // fields immediately after Escape/click-outside. if (!canOpen()) return; // If a selector is already open for this exact field, don't flicker it. if (currentDismiss && currentAnchorField === field) return; // If focus moved to a different field, the previous per-field dismiss lock // no longer applies. if (field !== lastDismissedField) lastDismissedField = null; // Layer 1: the user explicitly dismissed this field's selector — don't // reopen it until focus has genuinely moved away and come back. if (field === lastDismissedField) return; // Fill-success lock: Peach already filled this form (or fired a fill // anywhere on the page within the grace window). Sites often refocus an // input on submit click, on validation, or on a transition to a success // state — none of those should re-open the popup. if (wasAlreadyFilled(field)) return; // Prevent two concurrent calls for the same field (e.g. focusin + icon click // firing simultaneously — the second call would dismiss the first's selector). if (pendingInteractions.has(field)) return; pendingInteractions.add(field); try { // Multi-digit OTP entry: a group of digit boxes opens one selector anchored // on the first box and fills every box at once — never one icon per box. // findOTPDigitBoxGroup covers maxlength=1 boxes; findOtpSignalingGroup // covers boxes that carry OTP signaling (autocomplete=one-time-code, // name/id/label matches otp/totp/2fa) but lack maxlength="1". const otpGroup = findOTPDigitBoxGroup(field) ?? findOtpSignalingGroup(field); if (otpGroup) { await openTOTPSelector(otpGroup[0]!, otpGroup, capability); return; } if (isTOTPField(field)) { const formFields = detectLoginFields(); if (!isLoginForm(formFields) && !isSignupForm(formFields)) { await openTOTPSelector(field, undefined, capability); return; } } const fieldType = field.type.toLowerCase(); const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => { return preds[0] ?? null; }); const mlPrediction = await new Promise((resolve) => { const timeout = setTimeout(() => resolve(null), 150); mlPromise.then((pred) => { clearTimeout(timeout); resolve(pred); }); }); if (passkeyToastActive) return; if (!explicitSummon && fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") { return; } const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type); if (autofillFieldType) { reattachListeners(field, autofillFieldType); } const fields = detectLoginFields(); const targets = resolveAutofillInteractionTargets(field, fields, explicitSummon); if (!targets.shouldOpen) { return; } const domain = getPageDomain(); const commandAuthorized = explicitSummon && capability !== undefined; const firstResult = await fetchAutofillEntries( domain, commandAuthorized, commandAuthorized ? capability : undefined, ); if (passkeyToastActive) return; // Vault is locked — show an inline unlock prompt. // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so // there is no double-trigger race between onUnlocked and the broadcast. if (firstResult.locked) { currentDismiss?.(); currentAnchorField = field; currentDismiss = showAutofillSelector( field, [], () => {}, { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } } ); return; } const entries = firstResult.entries; // MV-2: the vault-wide list is NOT fetched here. It is loaded lazily, // only when the user activates the search affordance inside the inline // popup (an explicit gesture), via the thunk below. Passive form focus // never ships the full account inventory into the page's content-script // world — and never hands out the entry ids that made MV-1 a full-vault // primitive. const loadSearchableEntries = async (): Promise => commandAuthorized ? entries : (await fetchAutofillEntries(domain)).entries; if (passkeyToastActive) return; const pwField = fields.find((f) => f.type === "password"); // For email-first flows there is no password field on this step — that is expected. if (!explicitSummon && !pwField && !isEmailFirstForm(fields)) return; const usernameEl = targets.usernameEl; const passwordEl = targets.passwordEl; const emailEl = targets.emailEl; await openAutofillSelector( field, usernameEl, passwordEl, entries, loadSearchableEntries, domain, autofillFieldType === "email" ? "email" : "username", emailEl, commandAuthorized ? capability : undefined, ); } finally { pendingInteractions.delete(field); } } async function onFocusIn(e: Event): Promise { // Submit-button focus: catch the brief refocus some sites do when the // user clicks the login/submit button. Without this guard, that focus // event reaches handleFieldInteraction → getDeepActiveInput, and on // pages where the button is also a labelled we briefly attempt // to open the popup over the very button the user just clicked. if (isSubmitButton(e.target)) return; const field = e.target instanceof HTMLInputElement ? e.target : null; if (field) { const fields = detectLoginFields(); if (isAnyCredentialForm(fields)) { const detected = fields.find((candidate) => candidate.el === field)?.type; reattachListeners(field, detected, fields); } } await handleFieldInteraction(); } function reattachListeners( el: HTMLInputElement, detectedType?: "password" | "username" | "email", contextFields?: ReturnType ): void { if (processedInputs.has(el)) return; if (!resolveAutofillFieldType(el, detectedType)) return; // Only inject icon when a credential form is present on the page const fields = contextFields ?? detectLoginFields(); if (!isAnyCredentialForm(fields)) return; const cleanup = injectFieldIcon(el, () => { currentDismiss?.(); currentDismiss = null; lastDismissedField = null; // icon click is an explicit user open — clear per-field lock dismissLock = false; // ...and the global lock if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; } clearFillStateForExplicitSummon(el); el.focus({ preventScroll: true }); void handleFieldInteraction(el, true); }); processedInputs.set(el, cleanup); } const debouncedReattach = debounce(() => { const allFields = detectLoginFields(); if (!isAnyCredentialForm(allFields)) return; const newFields = allFields.filter( (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el) ); for (const f of newFields) { reattachListeners(f.el, f.type, allFields); } // 200ms debounce — below this, Peach and the host page's reactive layer // fight over the same layout properties every frame on React/Vue/Angular // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower. }, 200); function setupMutationObserver(): void { const observer = new MutationObserver(debouncedReattach); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"], }); } export /* @testable */ function initialScan(aggressionLevel = 0, isFinalPass = false) { const allFields = detectLoginFields(); const hasKnownForm = isAnyCredentialForm(allFields); if (aggressionLevel === 0 && !hasKnownForm) return; const newFields = allFields.filter( (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el) ); for (const f of newFields) { reattachListeners(f.el, f.type, allFields); } // Level 2, final pass: inject icon on any visible password field even if // the form-context gate in reattachListeners would normally skip it. if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) { const pwInputs = document.querySelectorAll('input[type="password"]'); for (const el of pwInputs) { if (isVisible(el) && !processedInputs.has(el)) { const cleanup = injectFieldIcon(el, () => { currentDismiss?.(); currentDismiss = null; lastDismissedField = null; dismissLock = false; if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; } clearFillStateForExplicitSummon(el); el.focus({ preventScroll: true }); void handleFieldInteraction(el, true); }); processedInputs.set(el, cleanup); } } } } // @testable seam — gives unit tests read/write access to module-private state // without exposing it in the production API surface. export const _testSeam = { getLastDismissedField(): HTMLInputElement | null { return lastDismissedField; }, setLastDismissedField(f: HTMLInputElement | null): void { lastDismissedField = f; }, isDismissLocked(): boolean { return dismissLock; }, DISMISS_LOCK_MS, } as const; // ── TOTP-only fields ─────────────────────────────────────────────────────── // After a username/password submission, many sites swap the whole form for a // lone "verification code" input. The credential selector intentionally gates // on login/signup forms, so TOTP fields need a narrow path of their own. const processedTOTPInputs = new WeakMap void>(); function hasLoginOrSignupForm(): boolean { const fields = detectLoginFields(); return isAnyCredentialForm(fields); } function injectTOTPFieldIcon( field: HTMLInputElement, otpDigitBoxes?: HTMLInputElement[] ): void { if (processedTOTPInputs.has(field)) return; const cleanup = injectFieldIcon(field, () => { currentDismiss?.(); currentDismiss = null; currentAnchorField = null; lastDismissedField = null; dismissLock = false; if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; } clearFillStateForExplicitSummon(field); field.focus({ preventScroll: true }); void openTOTPSelector(field, otpDigitBoxes); }); processedTOTPInputs.set(field, cleanup); } // A split-OTP group (4+ OTP-signaling boxes lacking maxlength="1") shows one // icon on the first box, not one per box. Returns the anchor to inject on // (group[0]) and its full group, or just the field itself when it's a lone // TOTP input. function resolveTOTPIconTarget( field: HTMLInputElement ): { anchor: HTMLInputElement; group?: HTMLInputElement[] } { const group = findOtpSignalingGroup(field); if (group) return { anchor: group[0]!, group }; return { anchor: field }; } export /* @testable */ function scanTOTPFields(): void { if (hasLoginOrSignupForm()) return; const inputs = document.querySelectorAll("input"); for (const input of inputs) { if (!isTOTPField(input)) continue; const { anchor, group } = resolveTOTPIconTarget(input); injectTOTPFieldIcon(anchor, group); } } function setupTOTPAutofill(): void { setTimeout(scanTOTPFields, 0); setTimeout(scanTOTPFields, 500); setTimeout(scanTOTPFields, 1500); const debouncedScan = debounce(scanTOTPFields, 200); new MutationObserver(debouncedScan).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"], }); document.addEventListener("focusin", (e) => { const target = e.target; if (!(target instanceof HTMLInputElement)) return; if (hasLoginOrSignupForm()) return; if (!isTOTPField(target)) return; const { anchor, group } = resolveTOTPIconTarget(target); injectTOTPFieldIcon(anchor, group); }, true); } document.addEventListener("focusin", onFocusIn); setupMutationObserver(); setupTOTPAutofill(); setupSaveDetection(); setupCardAutofill(); // SPA navigation reset: the content script does not reload across in-app // route changes (history.pushState, hash navigation, framework routers). // When the URL changes we clear the page-level fill timestamp so the next // page works normally; filledForms (a WeakSet) self-empties as old form // elements leave the DOM. subtree:false because route swaps reliably // mutate document.body's direct children — subtree:true would fire on // every internal DOM update and cost us a re-check per mutation. let lastObservedUrl = globalThis.location.href; new MutationObserver(() => { const currentUrl = globalThis.location?.href; if (!currentUrl || currentUrl === lastObservedUrl) return; lastObservedUrl = currentUrl; pageFilledAt = null; }).observe(document.body, { childList: true, subtree: false }); // Async init: check recall map before running the initial scans so we can // apply the right aggression level for domains the user has needed before. (async () => { let aggressionLevel = 0; try { const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" }); const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record } }).data; const domain = getPageDomain(); const record = domain ? s?.manualSummonDomains?.[domain] : undefined; aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1; } catch { /* SW may be starting up; proceed with normal scan */ } setTimeout(() => initialScan(aggressionLevel, false), 0); setTimeout(() => initialScan(aggressionLevel, false), 500); setTimeout(() => initialScan(aggressionLevel, true), 1500); })(); // ── Card autofill (State 7) ───────────────────────────────────────── // Card forms get a parallel injection path. The login icon-injection gate // in reattachListeners deliberately skips non-text fields, so we wire // cards independently rather than retrofit AUTOFILL_FIELD_TYPES — keeping // card detection contained makes the boundary easy to follow. const processedCardInputs = new WeakMap void>(); let currentCardDismiss: (() => void) | null = null; let currentCardAnchor: HTMLInputElement | null = null; let lastDismissedCardField: HTMLInputElement | null = null; async function fetchSavedCards(capability?: string): Promise { const resp = await chrome.runtime.sendMessage({ type: "AUTOFILL_QUERY", payload: { domain: getPageDomain(), kind: "card", capability }, }).catch(() => null); const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null; return r?.ok ? (r.data ?? []) : []; } async function openCardSelector(anchor: HTMLInputElement, capability?: string): Promise { if (!canOpen()) return; if (currentCardDismiss && currentCardAnchor === anchor) return; if (anchor === lastDismissedCardField) return; if (anchor !== lastDismissedCardField) lastDismissedCardField = null; if (wasAlreadyFilled(anchor)) return; const cards = await fetchSavedCards(capability); if (cards.length === 0) return; // no saved cards → nothing to offer const cardForm = detectCardForm(); if (!cardForm?.number) return; currentCardDismiss?.(); currentCardAnchor = anchor; currentCardDismiss = showCardSelector( anchor, cards, { domain: getPageDomain(), capability, onFill: (entry) => { if (!cardForm) return; fillCardForm(cardForm, { cardNumber: entry.cardNumber ?? "", expMonth: entry.expMonth ?? "", expYear: entry.expYear ?? "", cvc: entry.cvc ?? "", cardholderName: entry.cardholderName ?? "", }); // All four card field types share the same form — recording the // number field's form is sufficient to suppress reopens on any of // them via wasAlreadyFilled(). recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name); currentCardDismiss = null; currentCardAnchor = null; }, onDismiss: () => { lastDismissedCardField = anchor; startDismissLock(); currentCardDismiss = null; currentCardAnchor = null; }, } ); } function injectCardIcon(field: HTMLInputElement): void { if (processedCardInputs.has(field)) return; const cleanup = injectFieldIcon(field, () => { currentCardDismiss?.(); currentCardDismiss = null; lastDismissedCardField = null; dismissLock = false; if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; } clearFillStateForExplicitSummon(field); field.focus({ preventScroll: true }); void openCardSelector(field); }); processedCardInputs.set(field, cleanup); } function setupCardAutofill(): void { function scan() { const cardForm = detectCardForm(); if (!cardForm?.number) return; if (!isVisible(cardForm.number)) return; injectCardIcon(cardForm.number); } // Initial detection sweep — same retry cadence as login fields so // late-hydrating SPA checkout pages get caught. setTimeout(scan, 0); setTimeout(scan, 500); setTimeout(scan, 1500); // Re-scan on DOM mutation (separate from the login MutationObserver // because card forms typically appear on a single navigation event, // not field-by-field — coarser observation is sufficient here). let pending = false; new MutationObserver(() => { if (pending) return; pending = true; setTimeout(() => { pending = false; scan(); }, 200); }).observe(document.body, { childList: true, subtree: true }); // Field-focus path: on focus of a cc-number input, ensure icon is // present and consider opening the selector when the user explicitly // clicks into the card number field. document.addEventListener("focusin", (e) => { const target = e.target; if (!(target instanceof HTMLInputElement)) return; const cardForm = detectCardForm(); if (cardForm?.number === target) { injectCardIcon(target); } }, true); } chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { // Ignore anything not originating from our own background/service worker. if (sender.id !== chrome.runtime.id) return; if (msg?.type === "GET_SITE_PASSWORD_POLICY") { const policy = detectPasswordPolicy(); sendResponse({ ok: true, data: policy }); return true; } if (msg?.type === "PING") { sendResponse({ ok: true }); return true; } if (msg?.type === "SUMMON_AUTOFILL") { const source = (msg as { type: string; source?: string; capability?: string }).source; const capability = (msg as { capability?: string }).capability; const isShortcut = source === "shortcut"; const isPasskeyUnlock = source === "passkey-unlock"; const activeInput = getDeepActiveInput(); const fields = detectLoginFields(); const hasForm = isAnyCredentialForm(fields); const cardForm = detectCardForm(); if (hasForm) { // Prefer the currently focused field if it's a login field, otherwise // fall back to the first password field, then username/email. const inForm = activeInput && fields.some(f => f.el === activeInput); const target = inForm ? activeInput : (fields.find(f => f.type === "password")?.el ?? fields.find(f => f.type === "username" || f.type === "email")?.el); if (target) { // Explicit user summon (shortcut or extension button) — bypass all // suppression layers. The user is asking for the popup right now. clearFillStateForExplicitSummon(target); dismissLock = false; if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; } lastDismissedField = null; void handleFieldInteraction(target, true, capability); } } else if (isShortcut && cardForm?.number) { clearFillStateForExplicitSummon(cardForm.number); dismissLock = false; if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; } lastDismissedCardField = null; void openCardSelector(cardForm.number, capability); } else if (isPasskeyUnlock) { // Vault is locked during a passkey GET request. Show the inline unlock // prompt anchored to whatever element is focused on the page (typically // the passkey/sign-in button the user just tapped). const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body) ? document.activeElement as unknown as HTMLInputElement : null; if (anchor) { currentDismiss?.(); currentAnchorField = null; passkeySummonActive = true; currentDismiss = showAutofillSelector(anchor, [], () => {}, { domain: getPageDomain(), locked: true, onDismiss: () => { passkeySummonActive = false; }, }); } } else if (isShortcut) { // Shortcut on a page with no login form — show clipboard-copy search mode. showSearchPalette(capability); } // Record this domain for the recall system when triggered via shortcut. if (isShortcut) { const domain = getPageDomain(); if (domain) { chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {}); } } sendResponse({ ok: hasForm || Boolean(cardForm?.number) || isShortcut || isPasskeyUnlock }); return true; } if (msg?.type === "PASSKEY_PRO_GATE") { // Background rejected a passkey request for a free user. Show State 11 // so they know what happened and can choose to upgrade. showPasskeyProGate(); sendResponse({ ok: true }); return true; } if (msg?.type === "SHOW_PASSKEY_TOAST") { // Block autofill selector for the lifetime of the toast and dismiss anything open. passkeyToastActive = true; passkeyToastToken = typeof (msg.payload as { toastToken?: unknown } | undefined)?.toastToken === "string" ? (msg.payload as { toastToken: string }).toastToken : null; if (currentDismiss) { currentDismiss(); currentDismiss = null; currentAnchorField = null; } return false; // inject.tsx owns the toast and calls sendResponse } if (msg?.type === "DISMISS_PASSKEY_TOAST") { passkeyToastActive = false; passkeyToastToken = null; return false; // inject.tsx handles the actual dismissal } if (msg?.type === "VAULT_UNLOCKED") { if (passkeySummonActive) { // This unlock was for a pending passkey GET request. Just dismiss the // inline popup — the passkey approval toast takes over from here. passkeySummonActive = false; if (currentDismiss) { currentDismiss(); currentDismiss = null; currentAnchorField = null; } sendResponse({ ok: true }); return true; } // Normal autofill path: close the locked-state prompt and re-open with // fresh entry data at the same anchor field. const savedField = currentAnchorField; if (currentDismiss) { currentDismiss(); currentDismiss = null; currentAnchorField = null; } void handleFieldInteraction(savedField ?? undefined); sendResponse({ ok: true }); return true; } return true; }); setPasskeyToastClosedListener((toastToken) => { if (toastToken === passkeyToastToken) { passkeyToastActive = false; passkeyToastToken = null; } }); // Surface State 11 (passkey-available) only when it adds value: // - Cross-browser entry: Chrome passkey on Firefox or vice versa — neither // browser will auto-route, so the banner explains the re-register need. // - Firefox + same-browser entry: Firefox has no equivalent of // webAuthenticationProxy, so without a banner the user has no signal that // Peach is the source. // On Chrome with a same-browser entry: skip — webAuthenticationProxy handles // the page's own credentials.get transparently and the popup approval view // already surfaces it. A banner here would just be noise. // // Dedupe across navigation: the "already shown" flag lives in trusted // background session storage behind MARK_PASSKEY_BANNER_SHOWN — content // scripts must not touch chrome.storage.session directly (PB-26-203), since // that API has to stay inaccessible to hostile-page-adjacent contexts. { function checkPasskeyAvailability() { const domain = location.hostname.replace(/^www\./, ""); if (!domain) return; chrome.runtime.sendMessage({ type: "GET_PASSKEY_FOR_DOMAIN", payload: { domain }, }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox"; bannerShown?: boolean } | null } | undefined) => { const data = res?.data; if (!data || data.bannerShown) return; const current = detectBrowser(); const isCrossBrowser = data.browser && current !== "unknown" && data.browser !== current; const valuableOnFirefox = current === "firefox"; if (!isCrossBrowser && !valuableOnFirefox) return; chrome.runtime.sendMessage({ type: "MARK_PASSKEY_BANNER_SHOWN", payload: { domain }, }).catch(() => {}); showPasskeyAvailable({ rpId: data.rpId, userName: data.userName, fromBrowser: data.browser, currentBrowser: current, }); }).catch(() => {}); } // Defer until DOM is interactive — content_scripts run at document_idle but // some pages still mutate visibly afterwards. A short delay also avoids // surfacing the State 11 toast while the user is in the middle of typing. if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800)); } else { setTimeout(checkPasskeyAvailability, 800); } }