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 showPasskeyAvailable,18 showPasskeyProGate,19 showPasskeyRegistrationOffer,20 showRememberSiteToast,21} from "./inject";22import { detectBrowser } from "../shared/browser";23import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";24import { fillCardForm, fillFields, setNativeValue } from "./fill";25import { setupSaveDetection } from "./save";26import { contentMLDetector } from "./content-ml-detector";27import { detectPasswordPolicy } from "./policy";28import type { FieldPrediction } from "../shared/ml";29import { generateTOTP } from "../crypto/totp";30import type { SavedIdentity, VaultEntry } from "../shared/types";313233343536const processedInputs = new WeakMap<HTMLInputElement, () => void>();37const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);3839let currentDismiss: (() => void) | null = null;4041let currentAnchorField: HTMLInputElement | null = null;4243const pendingInteractions = new WeakSet<HTMLInputElement>();44454647let lastDismissedField: HTMLInputElement | null = null;48495051525354const DISMISS_LOCK_MS = 800;55let dismissLock = false;56let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;57function startDismissLock(): void {58 dismissLock = true;59 if (dismissLockTimer) clearTimeout(dismissLockTimer);60 dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);61}62function canOpen(): boolean { return !dismissLock; }6364656667686970717273747576const filledForms = new WeakSet<HTMLFormElement>();77let pageFilledAt: number | null = null;78const PAGE_FILL_GRACE_MS = 3000;7980function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {81 for (const f of fields) {82 if (!f) continue;83 const form = f.closest("form");84 if (form) filledForms.add(form);85 }86 pageFilledAt = Date.now();87}8889function wasAlreadyFilled(field: HTMLInputElement): boolean {90 const form = field.closest("form");91 if (form && filledForms.has(form)) return true;92 if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;93 return false;94}9596function clearFillStateForExplicitSummon(field: HTMLInputElement): void {97 const form = field.closest("form");98 if (form) filledForms.delete(form);99 pageFilledAt = null;100}101102103104105106function isSubmitButton(el: EventTarget | null): boolean {107 if (!(el instanceof HTMLElement)) return false;108 if (el instanceof HTMLButtonElement && el.type !== "button") return true;109 if (el instanceof HTMLInputElement && el.type === "submit") return true;110 if (el.getAttribute("type") === "submit") return true;111 const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();112 if (!text || text.length > 24) return false;113 return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);114}115116function debounce<T extends (...args: unknown[]) => void>(117 fn: T,118 ms: number119): (...args: Parameters<T>) => void {120 let timer: ReturnType<typeof setTimeout>;121 return (...args: Parameters<T>) => {122 clearTimeout(timer);123 timer = setTimeout(() => fn(...args), ms);124 };125}126127function showToast(message: string): void {128 const toast = document.createElement("div");129 toast.style.cssText = `130 position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);131 background: #131109; color: #F0E8D8; padding: 8px 16px;132 border-radius: 8px; font-family: 'IBM Plex Mono', monospace;133 font-size: 11px; z-index: 2147483647; opacity: 0;134 transition: opacity 200ms ease;135 border: 1px solid rgba(240,232,216,0.07);136 pointer-events: none;137 `;138 toast.textContent = message;139 document.body.appendChild(toast);140 requestAnimationFrame(() => { toast.style.opacity = "1"; });141 setTimeout(() => {142 toast.style.opacity = "0";143 setTimeout(() => toast.remove(), 200);144 }, 2000);145}146147function showSearchPalette(): void {148 const host = document.createElement("div");149 host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";150 document.body.appendChild(host);151 const shadow = host.attachShadow({ mode: "closed" });152153 const style = document.createElement("style");154 style.textContent = `155 .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;156 font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;157 box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}158 .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);159 font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}160 .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}161 .s{padding:8px 12px}162 .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);163 border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;164 padding:6px 8px;font-family:inherit;font-size:12px;outline:none}165 .l{max-height:220px;overflow-y:auto}166 .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}167 .e:hover{background:rgba(240,232,216,.06)}168 .et{font-size:12px}169 .eu{font-size:10px;color:rgba(240,232,216,.45)}170 .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}171 `;172173 let allEntries: SelectorEntry[] = [];174 let query = "";175176 const panel = document.createElement("div");177 panel.className = "p";178179 const hdr = document.createElement("div");180 hdr.className = "h";181 const hdrText = document.createElement("span");182 hdrText.textContent = "No form detected — search your vault";183 const closeBtn = document.createElement("button");184 closeBtn.className = "x";185 closeBtn.textContent = "✕";186 hdr.appendChild(hdrText);187 hdr.appendChild(closeBtn);188189 const searchWrap = document.createElement("div");190 searchWrap.className = "s";191 const searchInput = document.createElement("input");192 searchInput.placeholder = "search...";193 searchWrap.appendChild(searchInput);194195 const list = document.createElement("div");196 list.className = "l";197198 panel.appendChild(hdr);199 panel.appendChild(searchWrap);200 panel.appendChild(list);201 shadow.appendChild(style);202 shadow.appendChild(panel);203204 function close() { host.remove(); }205206 closeBtn.onclick = close;207208 function onKeyDown(e: KeyboardEvent) {209 if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }210 }211 document.addEventListener("keydown", onKeyDown, true);212213 function render() {214 const q = query.toLowerCase();215 const filtered = q216 ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))217 : allEntries;218 list.innerHTML = "";219 if (filtered.length === 0) {220 const em = document.createElement("div");221 em.className = "em";222 em.textContent = query ? "no matches" : "vault is empty";223 list.appendChild(em);224 return;225 }226 for (const entry of filtered.slice(0, 20)) {227 const row = document.createElement("div");228 row.className = "e";229 const title = document.createElement("div");230 title.className = "et";231 title.textContent = entry.title;232 row.appendChild(title);233 if (entry.username) {234 const user = document.createElement("div");235 user.className = "eu";236 user.textContent = entry.username;237 row.appendChild(user);238 }239 row.onclick = async () => {240 const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });241 const r = resp as { ok: boolean; data?: { password?: string } };242 if (r.ok && r.data?.password) {243 let alreadyWritten = false;244 try { await navigator.clipboard.writeText(r.data.password); alreadyWritten = true; } catch {}245 await chrome.runtime.sendMessage({246 type: "COPY",247 payload: { text: r.data.password, label: "Password", alreadyWritten },248 });249 showToast("Password copied");250 } else {251 showToast("Could not copy password");252 }253 close();254 document.removeEventListener("keydown", onKeyDown, true);255 };256 list.appendChild(row);257 }258 }259260 searchInput.oninput = () => { query = searchInput.value; render(); };261262 fetchAutofillEntries(getPageDomain(), true).then(result => {263 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }264 allEntries = result.entries;265 render();266 searchInput.focus();267 });268}269270function setNativeValue(el: HTMLInputElement, value: string): void {271 const nativeSetter = Object.getOwnPropertyDescriptor(272 HTMLInputElement.prototype, "value"273 )!.set!;274 nativeSetter.call(el, value);275 el.dispatchEvent(new Event("input", { bubbles: true }));276 el.dispatchEvent(new Event("change", { bubbles: true }));277}278279function findTOTPField(): HTMLInputElement | null {280 const inputs = document.querySelectorAll<HTMLInputElement>("input");281 for (const input of inputs) {282 if (!isVisible(input)) continue;283 const autocomplete = input.autocomplete.toLowerCase();284 const nameId = (input.name + input.id).toLowerCase();285 const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();286 if (287 autocomplete === "one-time-code" ||288 /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)289 ) {290 return input;291 }292 const labelEl = input.closest("label");293 if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {294 return input;295 }296 }297 return null;298}299300async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {301 await new Promise((r) => setTimeout(r, 400));302 if (totpField.value === "" || totpField.value.trim() === "") {303 const { code } = generateTOTP(totpSecret);304 setNativeValue(totpField, code);305 showToast("TOTP autofilled");306 }307}308309310async function handleAutofill(311 field: HTMLInputElement,312 usernameEl: HTMLInputElement | null,313 passwordEl: HTMLInputElement,314 entry: VaultEntry315): Promise<void> {316 if (!entry.username && !entry.password) return;317 const pageDomain = getPageDomain();318 const form = passwordEl.closest("form") as HTMLFormElement | null;319 fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);320321 if (entry.canary) {322 chrome.runtime.sendMessage({323 type: "FIRE_CANARY_PING",324 payload: {325 webhookUrl: entry.canary.webhookUrl,326 entryTitle: entry.title,327 trigger: "autofilled",328 },329 }).catch(() => {});330 chrome.runtime.sendMessage({331 type: "UPDATE_ENTRY",332 payload: {333 id: entry.id,334 patch: {335 canary: {336 ...entry.canary,337 lastPinged: Date.now(),338 pingCount: (entry.canary.pingCount ?? 0) + 1,339 },340 },341 },342 }).catch(() => {});343 }344345 if (entry.totp) {346 const { code } = generateTOTP(entry.totp);347 let alreadyWritten = false;348 try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}349 const response = await chrome.runtime.sendMessage({350 type: "COPY",351 payload: { text: code, label: "TOTP", alreadyWritten },352 });353 if (alreadyWritten || (response as { ok?: boolean }).ok) {354 showToast("TOTP copied · " + code);355 }356 const totpField = findTOTPField();357 if (totpField) {358 autofillTOTP(totpField, entry.totp);359 }360 }361}362363async function fetchAutofillEntries(364 domain: string,365 includeAll = false366): Promise<{ entries: SelectorEntry[]; locked: boolean }> {367 const response = await chrome.runtime.sendMessage({368 type: "AUTOFILL_QUERY",369 payload: { domain, includeAll },370 });371 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };372 if (!res.ok && res.error === "VAULT_LOCKED") {373 return { entries: [], locked: true };374 }375 return { entries: res.data ?? [], locked: false };376}377378379function resolveAutofillFieldType(380 el: HTMLInputElement,381 predictedType?: FieldPrediction["type"] | null382): "password" | "username" | "email" | null {383 if (384 predictedType === "password" ||385 predictedType === "username" ||386 predictedType === "email"387 ) {388 return predictedType;389 }390391 const detected = detectLoginFields().find((field) => field.el === el)?.type;392 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {393 return detected;394 }395396 const htmlType = el.type.toLowerCase();397 if (htmlType === "password") return "password";398 if (htmlType === "email") return "email";399 return null;400}401402async function openAutofillSelector(403 anchorField: HTMLInputElement,404 usernameEl: HTMLInputElement | null,405 passwordEl: HTMLInputElement,406 domainEntries: SelectorEntry[],407 searchableEntries: SelectorEntry[],408 domain: string409): Promise<void> {410 411 412 413 const isSignup = domainEntries.length === 0;414 let savedIdentities: SavedIdentity[] | undefined;415 let confirmEl: HTMLInputElement | null = null;416 if (isSignup) {417 try {418 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as419 { ok: boolean; data?: SavedIdentity[] } | null;420 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;421 } catch { }422423 const form = passwordEl.closest("form") ?? document.body;424 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));425 confirmEl = allPwInputs.find(426 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)427 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);428 }429430 currentDismiss?.();431 currentAnchorField = anchorField;432 currentDismiss = showAutofillSelector(433 anchorField,434 domainEntries,435 async (id: string) => {436 currentDismiss = null;437 currentAnchorField = null;438 const entryResponse = await chrome.runtime.sendMessage({439 type: "GET_ENTRY_FOR_FILL",440 payload: { id },441 });442 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;443 if (entry) {444 await handleAutofill(anchorField, usernameEl, passwordEl, entry);445 recordFillSuccess(anchorField, usernameEl, passwordEl);446 447 448 449 const pageDomain = location.hostname.replace(/^www\./, "");450 const entryDomains = new Set<string>();451 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {452 try {453 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));454 } catch { }455 }456 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {457 showRememberSiteToast(pageDomain, entry.id);458 }459 }460 },461 {462 domain,463 searchableEntries,464 isSignup,465 savedIdentities,466 onFillFields: (username, password) => {467 const form = passwordEl.closest("form") as HTMLFormElement | null;468 fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());469 if (password && confirmEl) setNativeValue(confirmEl, password);470 recordFillSuccess(anchorField, usernameEl, passwordEl);471 },472 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },473 }474 );475}476477478async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {479 const field = anchorField ?? getDeepActiveInput();480 if (!field) return;481 if (!isVisible(field)) return;482483 484 485 if (!canOpen()) return;486487 488 if (currentDismiss && currentAnchorField === field) return;489490 491 492 if (field !== lastDismissedField) lastDismissedField = null;493 494 495 if (field === lastDismissedField) return;496497 498 499 500 501 if (wasAlreadyFilled(field)) return;502503 504 505 if (pendingInteractions.has(field)) return;506 pendingInteractions.add(field);507508 try {509 const fieldType = field.type.toLowerCase();510511 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {512 return preds[0] ?? null;513 });514515 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {516 const timeout = setTimeout(() => resolve(null), 150);517 mlPromise.then((pred) => {518 clearTimeout(timeout);519 resolve(pred);520 });521 });522523 if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {524 return;525 }526527 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);528 if (autofillFieldType) {529 reattachListeners(field, autofillFieldType);530 }531532 let fields = detectLoginFields();533 const loginForm = isLoginForm(fields);534 const signupForm = isSignupForm(fields);535 if (!loginForm && !signupForm) {536 return;537 }538539 const domain = getPageDomain();540 const firstResult = await fetchAutofillEntries(domain);541542 543 544 545 if (firstResult.locked) {546 currentDismiss?.();547 currentAnchorField = field;548 currentDismiss = showAutofillSelector(549 field,550 [],551 () => {},552 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }553 );554 return;555 }556557 const entries = firstResult.entries;558 const allEntries = entries.length === 0559 ? (await fetchAutofillEntries(domain, true)).entries560 : entries;561562 let usernameEl: HTMLInputElement | null = null;563 const userField = fields.find((f) => f.type === "username" || f.type === "email");564 if (userField) usernameEl = userField.el;565 const pwField = fields.find((f) => f.type === "password");566 if (!pwField) return;567 const passwordEl = pwField.el;568569 await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);570 } finally {571 pendingInteractions.delete(field);572 }573}574575async function onFocusIn(e: Event): Promise<void> {576 577 578 579 580 581 if (isSubmitButton(e.target)) return;582 await handleFieldInteraction();583}584585function reattachListeners(586 el: HTMLInputElement,587 detectedType?: "password" | "username" | "email",588 contextFields?: ReturnType<typeof detectLoginFields>589): void {590 if (processedInputs.has(el)) return;591 if (!resolveAutofillFieldType(el, detectedType)) return;592 593 const fields = contextFields ?? detectLoginFields();594 if (!isLoginForm(fields) && !isSignupForm(fields)) return;595596 const cleanup = injectFieldIcon(el, () => {597 currentDismiss?.();598 currentDismiss = null;599 lastDismissedField = null; 600 dismissLock = false; 601 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }602 clearFillStateForExplicitSummon(el);603 el.focus({ preventScroll: true });604 void handleFieldInteraction(el);605 });606 processedInputs.set(el, cleanup);607}608609const debouncedReattach = debounce(() => {610 const allFields = detectLoginFields();611 612 if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;613 const newFields = allFields.filter(614 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)615 );616 for (const f of newFields) {617 reattachListeners(f.el, f.type, allFields);618 }619 620 621 622}, 200);623624function setupMutationObserver(): void {625 const observer = new MutationObserver(debouncedReattach);626 observer.observe(document.body, {627 childList: true,628 subtree: true,629 attributes: true,630 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],631 });632}633634function initialScan(aggressionLevel = 0, isFinalPass = false) {635 const allFields = detectLoginFields();636 const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);637638 if (aggressionLevel === 0 && !hasKnownForm) return;639640 const newFields = allFields.filter(641 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)642 );643644 for (const f of newFields) {645 reattachListeners(f.el, f.type, allFields);646 }647648 649 650 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {651 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');652 for (const el of pwInputs) {653 if (isVisible(el) && !processedInputs.has(el)) {654 const cleanup = injectFieldIcon(el, () => {655 currentDismiss?.();656 currentDismiss = null;657 lastDismissedField = null;658 dismissLock = false;659 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }660 clearFillStateForExplicitSummon(el);661 el.focus({ preventScroll: true });662 void handleFieldInteraction(el);663 });664 processedInputs.set(el, cleanup);665 }666 }667 }668}669670document.addEventListener("focusin", onFocusIn);671672setupMutationObserver();673setupSaveDetection();674setupCardAutofill();675676677678679680681682683let lastObservedUrl = location.href;684new MutationObserver(() => {685 if (location.href !== lastObservedUrl) {686 lastObservedUrl = location.href;687 pageFilledAt = null;688 }689}).observe(document.body, { childList: true, subtree: false });690691692693(async () => {694 let aggressionLevel = 0;695 try {696 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });697 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;698 const domain = getPageDomain();699 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;700 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;701 } catch { }702703 setTimeout(() => initialScan(aggressionLevel, false), 0);704 setTimeout(() => initialScan(aggressionLevel, false), 500);705 setTimeout(() => initialScan(aggressionLevel, true), 1500);706})();707708709710711712713const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();714let currentCardDismiss: (() => void) | null = null;715let currentCardAnchor: HTMLInputElement | null = null;716let lastDismissedCardField: HTMLInputElement | null = null;717718async function fetchSavedCards(): Promise<CardSelectorEntry[]> {719 const resp = await chrome.runtime.sendMessage({720 type: "AUTOFILL_QUERY",721 payload: { domain: getPageDomain(), kind: "card" },722 }).catch(() => null);723 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;724 return r?.ok ? (r.data ?? []) : [];725}726727async function openCardSelector(anchor: HTMLInputElement): Promise<void> {728 if (!canOpen()) return;729 if (currentCardDismiss && currentCardAnchor === anchor) return;730 if (anchor === lastDismissedCardField) return;731 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;732 if (wasAlreadyFilled(anchor)) return;733734 const cards = await fetchSavedCards();735 if (cards.length === 0) return; 736737 const cardForm = detectCardForm();738 if (!cardForm?.number) return;739740 currentCardDismiss?.();741 currentCardAnchor = anchor;742 currentCardDismiss = showCardSelector(743 anchor,744 cards,745 {746 domain: getPageDomain(),747 onFill: (entry) => {748 if (!cardForm) return;749 fillCardForm(cardForm, {750 cardNumber: entry.cardNumber ?? "",751 expMonth: entry.expMonth ?? "",752 expYear: entry.expYear ?? "",753 cvc: entry.cvc ?? "",754 cardholderName: entry.cardholderName ?? "",755 });756 757 758 759 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);760 currentCardDismiss = null;761 currentCardAnchor = null;762 },763 onDismiss: () => {764 lastDismissedCardField = anchor;765 startDismissLock();766 currentCardDismiss = null;767 currentCardAnchor = null;768 },769 }770 );771}772773function injectCardIcon(field: HTMLInputElement): void {774 if (processedCardInputs.has(field)) return;775 const cleanup = injectFieldIcon(field, () => {776 currentCardDismiss?.();777 currentCardDismiss = null;778 lastDismissedCardField = null;779 dismissLock = false;780 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }781 clearFillStateForExplicitSummon(field);782 field.focus({ preventScroll: true });783 void openCardSelector(field);784 });785 processedCardInputs.set(field, cleanup);786}787788function setupCardAutofill(): void {789 function scan() {790 const cardForm = detectCardForm();791 if (!cardForm?.number) return;792 if (!isVisible(cardForm.number)) return;793 injectCardIcon(cardForm.number);794 }795796 797 798 setTimeout(scan, 0);799 setTimeout(scan, 500);800 setTimeout(scan, 1500);801802 803 804 805 let pending = false;806 new MutationObserver(() => {807 if (pending) return;808 pending = true;809 setTimeout(() => { pending = false; scan(); }, 200);810 }).observe(document.body, { childList: true, subtree: true });811812 813 814 815 document.addEventListener("focusin", (e) => {816 const target = e.target;817 if (!(target instanceof HTMLInputElement)) return;818 const cardForm = detectCardForm();819 if (cardForm?.number === target) {820 injectCardIcon(target);821 }822 }, true);823}824825chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {826 827 if (sender.id !== chrome.runtime.id) return;828 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {829 const policy = detectPasswordPolicy();830 sendResponse({ ok: true, data: policy });831 return true;832 }833 if (msg?.type === "PING") {834 sendResponse({ ok: true });835 return true;836 }837 if (msg?.type === "SUMMON_AUTOFILL") {838 const source = (msg as { type: string; source?: string }).source;839 const isShortcut = source === "shortcut";840841 const activeInput = getDeepActiveInput();842 const fields = detectLoginFields();843 const hasForm = isLoginForm(fields) || isSignupForm(fields);844845 if (hasForm) {846 847 848 const inForm = activeInput && fields.some(f => f.el === activeInput);849 const target = inForm850 ? activeInput851 : (fields.find(f => f.type === "password")?.el852 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);853 if (target) {854 855 856 clearFillStateForExplicitSummon(target);857 dismissLock = false;858 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }859 lastDismissedField = null;860 void handleFieldInteraction(target);861 }862 } else if (isShortcut) {863 864 showSearchPalette();865 }866867 868 if (isShortcut) {869 const domain = getPageDomain();870 if (domain) {871 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});872 }873 }874875 sendResponse({ ok: hasForm || isShortcut });876 return true;877 }878 if (msg?.type === "PASSKEY_PRO_GATE") {879 880 881 showPasskeyProGate();882 sendResponse({ ok: true });883 return true;884 }885 if (msg?.type === "VAULT_UNLOCKED") {886 887 888 889 const savedField = currentAnchorField;890 if (currentDismiss) {891 currentDismiss();892 currentDismiss = null;893 currentAnchorField = null;894 }895 void handleFieldInteraction(savedField ?? undefined);896 sendResponse({ ok: true });897 return true;898 }899 return true;900});901902903904905906907908909910911912913if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {914 let lastPasskeyOfferAt = 0;915 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;916917 window.addEventListener("message", (event: MessageEvent) => {918 if (event.source !== window) return;919 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;920 if (!data || data.source !== "peach-passkey-firefox") return;921 if (detectBrowser() !== "firefox") return;922 if (data.type !== "create") return;923924 925 926 const now = Date.now();927 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;928 lastPasskeyOfferAt = now;929930 const domain = location.hostname.replace(/^www\./, "");931 chrome.runtime.sendMessage({932 type: "GET_PASSKEY_OFFER_DECLINED",933 payload: { domain },934 }).then((res: { ok: boolean; data?: boolean } | undefined) => {935 if (res?.data === true) return;936 const rpId = data.rpId ?? domain;937 showPasskeyRegistrationOffer({938 rpId,939 rpName: data.rpName,940 userName: data.userName,941 userDisplayName: data.userDisplayName,942 });943 }).catch(() => {});944 });945}946947948949950951952953954955956957958959960{961 function checkPasskeyAvailability() {962 const domain = location.hostname.replace(/^www\./, "");963 if (!domain) return;964 const sessionKey = `peach_state11_shown:${domain}`;965 chrome.storage.session?.get(sessionKey).then((stored) => {966 if (stored && (stored as Record<string, unknown>)[sessionKey]) return;967 chrome.runtime.sendMessage({968 type: "GET_PASSKEY_FOR_DOMAIN",969 payload: { domain },970 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {971 const data = res?.data;972 if (!data) return;973 const current = detectBrowser();974 const isCrossBrowser =975 data.browser && current !== "unknown" && data.browser !== current;976 const valuableOnFirefox = current === "firefox";977 if (!isCrossBrowser && !valuableOnFirefox) return;978 chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});979 showPasskeyAvailable({980 rpId: data.rpId,981 userName: data.userName,982 fromBrowser: data.browser,983 currentBrowser: current,984 });985 }).catch(() => {});986 }).catch(() => {});987 }988989 990 991 992 if (document.readyState === "loading") {993 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));994 } else {995 setTimeout(checkPasskeyAvailability, 800);996 }997}