1import {2 detectCardForm,3 detectLoginFields,4 getDeepActiveInput,5 getPageDomain,6 isLoginForm,7 isSignupForm,8 isVisible,9} from "./detect";10import {11 CardSelectorEntry,12 injectFieldIcon,13 observeAnchorPosition,14 SelectorEntry,15 showAutofillSelector,16 showCardSelector,17 showRememberSiteToast,18} from "./inject";19import { fillCardForm, fillFields } from "./fill";20import { setupSaveDetection } from "./save";21import { contentMLDetector } from "./content-ml-detector";22import { detectPasswordPolicy } from "./policy";23import type { FieldPrediction } from "../shared/ml";24import { generateTOTP } from "../crypto/totp";25import type { SavedIdentity, VaultEntry } from "../shared/types";262728293031const processedInputs = new WeakMap<HTMLInputElement, () => void>();32const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);3334let currentDismiss: (() => void) | null = null;3536let currentAnchorField: HTMLInputElement | null = null;3738const pendingInteractions = new WeakSet<HTMLInputElement>();39404142let lastDismissedField: HTMLInputElement | null = null;43444546474849const DISMISS_LOCK_MS = 800;50let dismissLock = false;51let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;52function startDismissLock(): void {53 dismissLock = true;54 if (dismissLockTimer) clearTimeout(dismissLockTimer);55 dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);56}57function canOpen(): boolean { return !dismissLock; }5859606162636465666768697071const filledForms = new WeakSet<HTMLFormElement>();72let pageFilledAt: number | null = null;73const PAGE_FILL_GRACE_MS = 3000;7475function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {76 for (const f of fields) {77 if (!f) continue;78 const form = f.closest("form");79 if (form) filledForms.add(form);80 }81 pageFilledAt = Date.now();82}8384function wasAlreadyFilled(field: HTMLInputElement): boolean {85 const form = field.closest("form");86 if (form && filledForms.has(form)) return true;87 if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;88 return false;89}9091function clearFillStateForExplicitSummon(field: HTMLInputElement): void {92 const form = field.closest("form");93 if (form) filledForms.delete(form);94 pageFilledAt = null;95}96979899100101function isSubmitButton(el: EventTarget | null): boolean {102 if (!(el instanceof HTMLElement)) return false;103 if (el instanceof HTMLButtonElement && el.type !== "button") return true;104 if (el instanceof HTMLInputElement && el.type === "submit") return true;105 if (el.getAttribute("type") === "submit") return true;106 const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();107 if (!text || text.length > 24) return false;108 return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);109}110111function debounce<T extends (...args: unknown[]) => void>(112 fn: T,113 ms: number114): (...args: Parameters<T>) => void {115 let timer: ReturnType<typeof setTimeout>;116 return (...args: Parameters<T>) => {117 clearTimeout(timer);118 timer = setTimeout(() => fn(...args), ms);119 };120}121122function showToast(message: string): void {123 const toast = document.createElement("div");124 toast.style.cssText = `125 position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);126 background: #131109; color: #F0E8D8; padding: 8px 16px;127 border-radius: 8px; font-family: 'IBM Plex Mono', monospace;128 font-size: 11px; z-index: 2147483647; opacity: 0;129 transition: opacity 200ms ease;130 border: 1px solid rgba(240,232,216,0.07);131 pointer-events: none;132 `;133 toast.textContent = message;134 document.body.appendChild(toast);135 requestAnimationFrame(() => { toast.style.opacity = "1"; });136 setTimeout(() => {137 toast.style.opacity = "0";138 setTimeout(() => toast.remove(), 200);139 }, 2000);140}141142function showSearchPalette(): void {143 const host = document.createElement("div");144 host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";145 document.body.appendChild(host);146 const shadow = host.attachShadow({ mode: "closed" });147148 const style = document.createElement("style");149 style.textContent = `150 .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;151 font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;152 box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}153 .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);154 font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}155 .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}156 .s{padding:8px 12px}157 .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);158 border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;159 padding:6px 8px;font-family:inherit;font-size:12px;outline:none}160 .l{max-height:220px;overflow-y:auto}161 .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}162 .e:hover{background:rgba(240,232,216,.06)}163 .et{font-size:12px}164 .eu{font-size:10px;color:rgba(240,232,216,.45)}165 .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}166 `;167168 let allEntries: SelectorEntry[] = [];169 let query = "";170171 const panel = document.createElement("div");172 panel.className = "p";173174 const hdr = document.createElement("div");175 hdr.className = "h";176 const hdrText = document.createElement("span");177 hdrText.textContent = "No form detected — search your vault";178 const closeBtn = document.createElement("button");179 closeBtn.className = "x";180 closeBtn.textContent = "✕";181 hdr.appendChild(hdrText);182 hdr.appendChild(closeBtn);183184 const searchWrap = document.createElement("div");185 searchWrap.className = "s";186 const searchInput = document.createElement("input");187 searchInput.placeholder = "search...";188 searchWrap.appendChild(searchInput);189190 const list = document.createElement("div");191 list.className = "l";192193 panel.appendChild(hdr);194 panel.appendChild(searchWrap);195 panel.appendChild(list);196 shadow.appendChild(style);197 shadow.appendChild(panel);198199 function close() { host.remove(); }200201 closeBtn.onclick = close;202203 function onKeyDown(e: KeyboardEvent) {204 if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }205 }206 document.addEventListener("keydown", onKeyDown, true);207208 function render() {209 const q = query.toLowerCase();210 const filtered = q211 ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))212 : allEntries;213 list.innerHTML = "";214 if (filtered.length === 0) {215 const em = document.createElement("div");216 em.className = "em";217 em.textContent = query ? "no matches" : "vault is empty";218 list.appendChild(em);219 return;220 }221 for (const entry of filtered.slice(0, 20)) {222 const row = document.createElement("div");223 row.className = "e";224 const title = document.createElement("div");225 title.className = "et";226 title.textContent = entry.title;227 row.appendChild(title);228 if (entry.username) {229 const user = document.createElement("div");230 user.className = "eu";231 user.textContent = entry.username;232 row.appendChild(user);233 }234 row.onclick = async () => {235 const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });236 const r = resp as { ok: boolean; data?: { password?: string } };237 if (r.ok && r.data?.password) {238 let alreadyWritten = false;239 try { await navigator.clipboard.writeText(r.data.password); alreadyWritten = true; } catch {}240 await chrome.runtime.sendMessage({241 type: "COPY",242 payload: { text: r.data.password, label: "Password", alreadyWritten },243 });244 showToast("Password copied");245 } else {246 showToast("Could not copy password");247 }248 close();249 document.removeEventListener("keydown", onKeyDown, true);250 };251 list.appendChild(row);252 }253 }254255 searchInput.oninput = () => { query = searchInput.value; render(); };256257 fetchAutofillEntries(getPageDomain(), true).then(result => {258 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }259 allEntries = result.entries;260 render();261 searchInput.focus();262 });263}264265function setNativeValue(el: HTMLInputElement, value: string): void {266 const nativeSetter = Object.getOwnPropertyDescriptor(267 HTMLInputElement.prototype, "value"268 )!.set!;269 nativeSetter.call(el, value);270 el.dispatchEvent(new Event("input", { bubbles: true }));271 el.dispatchEvent(new Event("change", { bubbles: true }));272}273274function findTOTPField(): HTMLInputElement | null {275 const inputs = document.querySelectorAll<HTMLInputElement>("input");276 for (const input of inputs) {277 if (!isVisible(input)) continue;278 const autocomplete = input.autocomplete.toLowerCase();279 const nameId = (input.name + input.id).toLowerCase();280 const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();281 if (282 autocomplete === "one-time-code" ||283 /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)284 ) {285 return input;286 }287 const labelEl = input.closest("label");288 if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {289 return input;290 }291 }292 return null;293}294295async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {296 await new Promise((r) => setTimeout(r, 400));297 if (totpField.value === "" || totpField.value.trim() === "") {298 const { code } = generateTOTP(totpSecret);299 setNativeValue(totpField, code);300 showToast("TOTP autofilled");301 }302}303304305async function handleAutofill(306 field: HTMLInputElement,307 usernameEl: HTMLInputElement | null,308 passwordEl: HTMLInputElement,309 entry: VaultEntry310): Promise<void> {311 if (!entry.username && !entry.password) return;312 const pageDomain = getPageDomain();313 const form = passwordEl.closest("form") as HTMLFormElement | null;314 fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);315316 if (entry.canary) {317 chrome.runtime.sendMessage({318 type: "FIRE_CANARY_PING",319 payload: {320 webhookUrl: entry.canary.webhookUrl,321 entryTitle: entry.title,322 trigger: "autofilled",323 },324 }).catch(() => {});325 chrome.runtime.sendMessage({326 type: "UPDATE_ENTRY",327 payload: {328 id: entry.id,329 patch: {330 canary: {331 ...entry.canary,332 lastPinged: Date.now(),333 pingCount: (entry.canary.pingCount ?? 0) + 1,334 },335 },336 },337 }).catch(() => {});338 }339340 if (entry.totp) {341 const { code } = generateTOTP(entry.totp);342 let alreadyWritten = false;343 try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}344 const response = await chrome.runtime.sendMessage({345 type: "COPY",346 payload: { text: code, label: "TOTP", alreadyWritten },347 });348 if (alreadyWritten || (response as { ok?: boolean }).ok) {349 showToast("TOTP copied · " + code);350 }351 const totpField = findTOTPField();352 if (totpField) {353 autofillTOTP(totpField, entry.totp);354 }355 }356}357358async function fetchAutofillEntries(359 domain: string,360 includeAll = false361): Promise<{ entries: SelectorEntry[]; locked: boolean }> {362 const response = await chrome.runtime.sendMessage({363 type: "AUTOFILL_QUERY",364 payload: { domain, includeAll },365 });366 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };367 if (!res.ok && res.error === "VAULT_LOCKED") {368 return { entries: [], locked: true };369 }370 return { entries: res.data ?? [], locked: false };371}372373374function resolveAutofillFieldType(375 el: HTMLInputElement,376 predictedType?: FieldPrediction["type"] | null377): "password" | "username" | "email" | null {378 if (379 predictedType === "password" ||380 predictedType === "username" ||381 predictedType === "email"382 ) {383 return predictedType;384 }385386 const detected = detectLoginFields().find((field) => field.el === el)?.type;387 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {388 return detected;389 }390391 const htmlType = el.type.toLowerCase();392 if (htmlType === "password") return "password";393 if (htmlType === "email") return "email";394 return null;395}396397async function openAutofillSelector(398 anchorField: HTMLInputElement,399 usernameEl: HTMLInputElement | null,400 passwordEl: HTMLInputElement,401 domainEntries: SelectorEntry[],402 searchableEntries: SelectorEntry[],403 domain: string404): Promise<void> {405 currentDismiss?.();406 currentAnchorField = anchorField;407 currentDismiss = showAutofillSelector(408 anchorField,409 domainEntries,410 async (id: string) => {411 currentDismiss = null;412 currentAnchorField = null;413 const entryResponse = await chrome.runtime.sendMessage({414 type: "GET_ENTRY_FOR_FILL",415 payload: { id },416 });417 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;418 if (entry) {419 await handleAutofill(anchorField, usernameEl, passwordEl, entry);420 recordFillSuccess(anchorField, usernameEl, passwordEl);421 422 423 424 const pageDomain = location.hostname.replace(/^www\./, "");425 const entryDomains = new Set<string>();426 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {427 try {428 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));429 } catch { }430 }431 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {432 showRememberSiteToast(pageDomain, entry.id);433 }434 }435 },436 {437 domain,438 searchableEntries,439 440 441 442 443 444 onFillFields: (username, password) => {445 const form = passwordEl.closest("form") as HTMLFormElement | null;446 fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());447 recordFillSuccess(anchorField, usernameEl, passwordEl);448 },449 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },450 }451 );452}453454async function openSignupSelector(455 usernameEl: HTMLInputElement,456 passwordEl: HTMLInputElement | null,457 domainEntries: SelectorEntry[],458 allEntries: SelectorEntry[],459 domain: string460): Promise<void> {461 462 463 464 let savedIdentities: SavedIdentity[] = [];465 try {466 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as467 { ok: boolean; data?: SavedIdentity[] } | null;468 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;469 } catch { }470471 472 473 const form = passwordEl?.closest("form") ?? document.body;474 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));475 const confirmEl = allPwInputs.find(476 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)477 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);478479 currentDismiss?.();480 currentAnchorField = usernameEl;481 currentDismiss = showAutofillSelector(482 usernameEl,483 domainEntries,484 () => {},485 {486 domain,487 searchableEntries: allEntries,488 isSignup: true,489 savedIdentities,490 onFillFields: (username, password) => {491 if (username) setNativeValue(usernameEl, username);492 if (password && passwordEl) {493 setNativeValue(passwordEl, password);494 if (confirmEl) setNativeValue(confirmEl, password);495 }496 recordFillSuccess(usernameEl, passwordEl);497 },498 onDismiss: () => { lastDismissedField = usernameEl; startDismissLock(); },499 }500 );501}502503504async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {505 const field = anchorField ?? getDeepActiveInput();506 if (!field) return;507 if (!isVisible(field)) return;508509 510 511 if (!canOpen()) return;512513 514 if (currentDismiss && currentAnchorField === field) return;515516 517 518 if (field !== lastDismissedField) lastDismissedField = null;519 520 521 if (field === lastDismissedField) return;522523 524 525 526 527 if (wasAlreadyFilled(field)) return;528529 530 531 if (pendingInteractions.has(field)) return;532 pendingInteractions.add(field);533534 try {535 const fieldType = field.type.toLowerCase();536537 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {538 return preds[0] ?? null;539 });540541 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {542 const timeout = setTimeout(() => resolve(null), 150);543 mlPromise.then((pred) => {544 clearTimeout(timeout);545 resolve(pred);546 });547 });548549 if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {550 return;551 }552553 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);554 if (autofillFieldType) {555 reattachListeners(field, autofillFieldType);556 }557558 let fields = detectLoginFields();559 const loginForm = isLoginForm(fields);560 const signupForm = isSignupForm(fields);561 if (!loginForm && !signupForm) {562 return;563 }564565 const domain = getPageDomain();566 const firstResult = await fetchAutofillEntries(domain);567568 569 570 571 if (firstResult.locked) {572 currentDismiss?.();573 currentAnchorField = field;574 currentDismiss = showAutofillSelector(575 field,576 [],577 () => {},578 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }579 );580 return;581 }582583 const entries = firstResult.entries;584 const allEntries = entries.length === 0585 ? (await fetchAutofillEntries(domain, true)).entries586 : entries;587588 let usernameEl: HTMLInputElement | null = null;589 const userField = fields.find((f) => f.type === "username" || f.type === "email");590 if (userField) usernameEl = userField.el;591 const pwField = fields.find((f) => f.type === "password");592 if (!pwField) return;593 const passwordEl = pwField.el;594595 if (signupForm && usernameEl && field === usernameEl) {596 await openSignupSelector(usernameEl, passwordEl, entries, allEntries, domain);597 return;598 }599600 await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);601 } finally {602 pendingInteractions.delete(field);603 }604}605606async function onFocusIn(e: Event): Promise<void> {607 608 609 610 611 612 if (isSubmitButton(e.target)) return;613 await handleFieldInteraction();614}615616function reattachListeners(617 el: HTMLInputElement,618 detectedType?: "password" | "username" | "email",619 contextFields?: ReturnType<typeof detectLoginFields>620): void {621 if (processedInputs.has(el)) return;622 if (!resolveAutofillFieldType(el, detectedType)) return;623 624 const fields = contextFields ?? detectLoginFields();625 if (!isLoginForm(fields) && !isSignupForm(fields)) return;626627 const cleanup = injectFieldIcon(el, () => {628 currentDismiss?.();629 currentDismiss = null;630 lastDismissedField = null; 631 dismissLock = false; 632 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }633 clearFillStateForExplicitSummon(el);634 el.focus({ preventScroll: true });635 void handleFieldInteraction(el);636 });637 processedInputs.set(el, cleanup);638}639640const debouncedReattach = debounce(() => {641 const allFields = detectLoginFields();642 643 if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;644 const newFields = allFields.filter(645 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)646 );647 for (const f of newFields) {648 reattachListeners(f.el, f.type, allFields);649 }650 651 652 653}, 200);654655function setupMutationObserver(): void {656 const observer = new MutationObserver(debouncedReattach);657 observer.observe(document.body, {658 childList: true,659 subtree: true,660 attributes: true,661 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],662 });663}664665function initialScan(aggressionLevel = 0, isFinalPass = false) {666 const allFields = detectLoginFields();667 const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);668669 if (aggressionLevel === 0 && !hasKnownForm) return;670671 const newFields = allFields.filter(672 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)673 );674675 for (const f of newFields) {676 reattachListeners(f.el, f.type, allFields);677 }678679 680 681 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {682 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');683 for (const el of pwInputs) {684 if (isVisible(el) && !processedInputs.has(el)) {685 const cleanup = injectFieldIcon(el, () => {686 currentDismiss?.();687 currentDismiss = null;688 lastDismissedField = null;689 dismissLock = false;690 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }691 clearFillStateForExplicitSummon(el);692 el.focus({ preventScroll: true });693 void handleFieldInteraction(el);694 });695 processedInputs.set(el, cleanup);696 }697 }698 }699}700701document.addEventListener("focusin", onFocusIn);702703setupMutationObserver();704setupSaveDetection();705setupCardAutofill();706707708709710711712713714let lastObservedUrl = location.href;715new MutationObserver(() => {716 if (location.href !== lastObservedUrl) {717 lastObservedUrl = location.href;718 pageFilledAt = null;719 }720}).observe(document.body, { childList: true, subtree: false });721722723724(async () => {725 let aggressionLevel = 0;726 try {727 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });728 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;729 const domain = getPageDomain();730 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;731 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;732 } catch { }733734 setTimeout(() => initialScan(aggressionLevel, false), 0);735 setTimeout(() => initialScan(aggressionLevel, false), 500);736 setTimeout(() => initialScan(aggressionLevel, true), 1500);737})();738739740741742743744const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();745let currentCardDismiss: (() => void) | null = null;746let currentCardAnchor: HTMLInputElement | null = null;747let lastDismissedCardField: HTMLInputElement | null = null;748749async function fetchSavedCards(): Promise<CardSelectorEntry[]> {750 const resp = await chrome.runtime.sendMessage({751 type: "AUTOFILL_QUERY",752 payload: { domain: getPageDomain(), kind: "card" },753 }).catch(() => null);754 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;755 return r?.ok ? (r.data ?? []) : [];756}757758async function openCardSelector(anchor: HTMLInputElement): Promise<void> {759 if (!canOpen()) return;760 if (currentCardDismiss && currentCardAnchor === anchor) return;761 if (anchor === lastDismissedCardField) return;762 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;763 if (wasAlreadyFilled(anchor)) return;764765 const cards = await fetchSavedCards();766 if (cards.length === 0) return; 767768 const cardForm = detectCardForm();769 if (!cardForm?.number) return;770771 currentCardDismiss?.();772 currentCardAnchor = anchor;773 currentCardDismiss = showCardSelector(774 anchor,775 cards,776 {777 domain: getPageDomain(),778 onFill: (entry) => {779 if (!cardForm) return;780 fillCardForm(cardForm, {781 cardNumber: entry.cardNumber ?? "",782 expMonth: entry.expMonth ?? "",783 expYear: entry.expYear ?? "",784 cvc: entry.cvc ?? "",785 cardholderName: entry.cardholderName ?? "",786 });787 788 789 790 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);791 currentCardDismiss = null;792 currentCardAnchor = null;793 },794 onDismiss: () => {795 lastDismissedCardField = anchor;796 startDismissLock();797 currentCardDismiss = null;798 currentCardAnchor = null;799 },800 }801 );802}803804function injectCardIcon(field: HTMLInputElement): void {805 if (processedCardInputs.has(field)) return;806 const cleanup = injectFieldIcon(field, () => {807 currentCardDismiss?.();808 currentCardDismiss = null;809 lastDismissedCardField = null;810 dismissLock = false;811 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }812 clearFillStateForExplicitSummon(field);813 field.focus({ preventScroll: true });814 void openCardSelector(field);815 });816 processedCardInputs.set(field, cleanup);817}818819function setupCardAutofill(): void {820 function scan() {821 const cardForm = detectCardForm();822 if (!cardForm?.number) return;823 if (!isVisible(cardForm.number)) return;824 injectCardIcon(cardForm.number);825 }826827 828 829 setTimeout(scan, 0);830 setTimeout(scan, 500);831 setTimeout(scan, 1500);832833 834 835 836 let pending = false;837 new MutationObserver(() => {838 if (pending) return;839 pending = true;840 setTimeout(() => { pending = false; scan(); }, 200);841 }).observe(document.body, { childList: true, subtree: true });842843 844 845 846 document.addEventListener("focusin", (e) => {847 const target = e.target;848 if (!(target instanceof HTMLInputElement)) return;849 const cardForm = detectCardForm();850 if (cardForm?.number === target) {851 injectCardIcon(target);852 }853 }, true);854}855856chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {857 858 if (sender.id !== chrome.runtime.id) return;859 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {860 const policy = detectPasswordPolicy();861 sendResponse({ ok: true, data: policy });862 return true;863 }864 if (msg?.type === "PING") {865 sendResponse({ ok: true });866 return true;867 }868 if (msg?.type === "SUMMON_AUTOFILL") {869 const source = (msg as { type: string; source?: string }).source;870 const isShortcut = source === "shortcut";871872 const activeInput = getDeepActiveInput();873 const fields = detectLoginFields();874 const hasForm = isLoginForm(fields) || isSignupForm(fields);875876 if (hasForm) {877 878 879 const inForm = activeInput && fields.some(f => f.el === activeInput);880 const target = inForm881 ? activeInput882 : (fields.find(f => f.type === "password")?.el883 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);884 if (target) {885 886 887 clearFillStateForExplicitSummon(target);888 dismissLock = false;889 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }890 lastDismissedField = null;891 void handleFieldInteraction(target);892 }893 } else if (isShortcut) {894 895 showSearchPalette();896 }897898 899 if (isShortcut) {900 const domain = getPageDomain();901 if (domain) {902 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});903 }904 }905906 sendResponse({ ok: hasForm || isShortcut });907 return true;908 }909 if (msg?.type === "VAULT_UNLOCKED") {910 911 912 913 const savedField = currentAnchorField;914 if (currentDismiss) {915 currentDismiss();916 currentDismiss = null;917 currentAnchorField = null;918 }919 void handleFieldInteraction(savedField ?? undefined);920 sendResponse({ ok: true });921 return true;922 }923 return true;924});