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 } 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 currentDismiss?.();411 currentAnchorField = anchorField;412 currentDismiss = showAutofillSelector(413 anchorField,414 domainEntries,415 async (id: string) => {416 currentDismiss = null;417 currentAnchorField = null;418 const entryResponse = await chrome.runtime.sendMessage({419 type: "GET_ENTRY_FOR_FILL",420 payload: { id },421 });422 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;423 if (entry) {424 await handleAutofill(anchorField, usernameEl, passwordEl, entry);425 recordFillSuccess(anchorField, usernameEl, passwordEl);426 427 428 429 const pageDomain = location.hostname.replace(/^www\./, "");430 const entryDomains = new Set<string>();431 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {432 try {433 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));434 } catch { }435 }436 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {437 showRememberSiteToast(pageDomain, entry.id);438 }439 }440 },441 {442 domain,443 searchableEntries,444 445 446 447 448 449 onFillFields: (username, password) => {450 const form = passwordEl.closest("form") as HTMLFormElement | null;451 fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());452 recordFillSuccess(anchorField, usernameEl, passwordEl);453 },454 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },455 }456 );457}458459async function openSignupSelector(460 usernameEl: HTMLInputElement,461 passwordEl: HTMLInputElement | null,462 domainEntries: SelectorEntry[],463 allEntries: SelectorEntry[],464 domain: string465): Promise<void> {466 467 468 469 let savedIdentities: SavedIdentity[] = [];470 try {471 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as472 { ok: boolean; data?: SavedIdentity[] } | null;473 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;474 } catch { }475476 477 478 const form = passwordEl?.closest("form") ?? document.body;479 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));480 const confirmEl = allPwInputs.find(481 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)482 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);483484 currentDismiss?.();485 currentAnchorField = usernameEl;486 currentDismiss = showAutofillSelector(487 usernameEl,488 domainEntries,489 () => {},490 {491 domain,492 searchableEntries: allEntries,493 isSignup: true,494 savedIdentities,495 onFillFields: (username, password) => {496 if (username) setNativeValue(usernameEl, username);497 if (password && passwordEl) {498 setNativeValue(passwordEl, password);499 if (confirmEl) setNativeValue(confirmEl, password);500 }501 recordFillSuccess(usernameEl, passwordEl);502 },503 onDismiss: () => { lastDismissedField = usernameEl; startDismissLock(); },504 }505 );506}507508509async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {510 const field = anchorField ?? getDeepActiveInput();511 if (!field) return;512 if (!isVisible(field)) return;513514 515 516 if (!canOpen()) return;517518 519 if (currentDismiss && currentAnchorField === field) return;520521 522 523 if (field !== lastDismissedField) lastDismissedField = null;524 525 526 if (field === lastDismissedField) return;527528 529 530 531 532 if (wasAlreadyFilled(field)) return;533534 535 536 if (pendingInteractions.has(field)) return;537 pendingInteractions.add(field);538539 try {540 const fieldType = field.type.toLowerCase();541542 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {543 return preds[0] ?? null;544 });545546 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {547 const timeout = setTimeout(() => resolve(null), 150);548 mlPromise.then((pred) => {549 clearTimeout(timeout);550 resolve(pred);551 });552 });553554 if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {555 return;556 }557558 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);559 if (autofillFieldType) {560 reattachListeners(field, autofillFieldType);561 }562563 let fields = detectLoginFields();564 const loginForm = isLoginForm(fields);565 const signupForm = isSignupForm(fields);566 if (!loginForm && !signupForm) {567 return;568 }569570 const domain = getPageDomain();571 const firstResult = await fetchAutofillEntries(domain);572573 574 575 576 if (firstResult.locked) {577 currentDismiss?.();578 currentAnchorField = field;579 currentDismiss = showAutofillSelector(580 field,581 [],582 () => {},583 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }584 );585 return;586 }587588 const entries = firstResult.entries;589 const allEntries = entries.length === 0590 ? (await fetchAutofillEntries(domain, true)).entries591 : entries;592593 let usernameEl: HTMLInputElement | null = null;594 const userField = fields.find((f) => f.type === "username" || f.type === "email");595 if (userField) usernameEl = userField.el;596 const pwField = fields.find((f) => f.type === "password");597 if (!pwField) return;598 const passwordEl = pwField.el;599600 601 602 603 if (signupForm && usernameEl && field === usernameEl) {604 await openSignupSelector(usernameEl, passwordEl, entries, allEntries, domain);605 return;606 }607608 await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);609 } finally {610 pendingInteractions.delete(field);611 }612}613614async function onFocusIn(e: Event): Promise<void> {615 616 617 618 619 620 if (isSubmitButton(e.target)) return;621 await handleFieldInteraction();622}623624function reattachListeners(625 el: HTMLInputElement,626 detectedType?: "password" | "username" | "email",627 contextFields?: ReturnType<typeof detectLoginFields>628): void {629 if (processedInputs.has(el)) return;630 if (!resolveAutofillFieldType(el, detectedType)) return;631 632 const fields = contextFields ?? detectLoginFields();633 if (!isLoginForm(fields) && !isSignupForm(fields)) return;634635 const cleanup = injectFieldIcon(el, () => {636 currentDismiss?.();637 currentDismiss = null;638 lastDismissedField = null; 639 dismissLock = false; 640 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }641 clearFillStateForExplicitSummon(el);642 el.focus({ preventScroll: true });643 void handleFieldInteraction(el);644 });645 processedInputs.set(el, cleanup);646}647648const debouncedReattach = debounce(() => {649 const allFields = detectLoginFields();650 651 if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;652 const newFields = allFields.filter(653 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)654 );655 for (const f of newFields) {656 reattachListeners(f.el, f.type, allFields);657 }658 659 660 661}, 200);662663function setupMutationObserver(): void {664 const observer = new MutationObserver(debouncedReattach);665 observer.observe(document.body, {666 childList: true,667 subtree: true,668 attributes: true,669 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],670 });671}672673function initialScan(aggressionLevel = 0, isFinalPass = false) {674 const allFields = detectLoginFields();675 const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);676677 if (aggressionLevel === 0 && !hasKnownForm) return;678679 const newFields = allFields.filter(680 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)681 );682683 for (const f of newFields) {684 reattachListeners(f.el, f.type, allFields);685 }686687 688 689 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {690 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');691 for (const el of pwInputs) {692 if (isVisible(el) && !processedInputs.has(el)) {693 const cleanup = injectFieldIcon(el, () => {694 currentDismiss?.();695 currentDismiss = null;696 lastDismissedField = null;697 dismissLock = false;698 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }699 clearFillStateForExplicitSummon(el);700 el.focus({ preventScroll: true });701 void handleFieldInteraction(el);702 });703 processedInputs.set(el, cleanup);704 }705 }706 }707}708709document.addEventListener("focusin", onFocusIn);710711setupMutationObserver();712setupSaveDetection();713setupCardAutofill();714715716717718719720721722let lastObservedUrl = location.href;723new MutationObserver(() => {724 if (location.href !== lastObservedUrl) {725 lastObservedUrl = location.href;726 pageFilledAt = null;727 }728}).observe(document.body, { childList: true, subtree: false });729730731732(async () => {733 let aggressionLevel = 0;734 try {735 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });736 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;737 const domain = getPageDomain();738 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;739 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;740 } catch { }741742 setTimeout(() => initialScan(aggressionLevel, false), 0);743 setTimeout(() => initialScan(aggressionLevel, false), 500);744 setTimeout(() => initialScan(aggressionLevel, true), 1500);745})();746747748749750751752const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();753let currentCardDismiss: (() => void) | null = null;754let currentCardAnchor: HTMLInputElement | null = null;755let lastDismissedCardField: HTMLInputElement | null = null;756757async function fetchSavedCards(): Promise<CardSelectorEntry[]> {758 const resp = await chrome.runtime.sendMessage({759 type: "AUTOFILL_QUERY",760 payload: { domain: getPageDomain(), kind: "card" },761 }).catch(() => null);762 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;763 return r?.ok ? (r.data ?? []) : [];764}765766async function openCardSelector(anchor: HTMLInputElement): Promise<void> {767 if (!canOpen()) return;768 if (currentCardDismiss && currentCardAnchor === anchor) return;769 if (anchor === lastDismissedCardField) return;770 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;771 if (wasAlreadyFilled(anchor)) return;772773 const cards = await fetchSavedCards();774 if (cards.length === 0) return; 775776 const cardForm = detectCardForm();777 if (!cardForm?.number) return;778779 currentCardDismiss?.();780 currentCardAnchor = anchor;781 currentCardDismiss = showCardSelector(782 anchor,783 cards,784 {785 domain: getPageDomain(),786 onFill: (entry) => {787 if (!cardForm) return;788 fillCardForm(cardForm, {789 cardNumber: entry.cardNumber ?? "",790 expMonth: entry.expMonth ?? "",791 expYear: entry.expYear ?? "",792 cvc: entry.cvc ?? "",793 cardholderName: entry.cardholderName ?? "",794 });795 796 797 798 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);799 currentCardDismiss = null;800 currentCardAnchor = null;801 },802 onDismiss: () => {803 lastDismissedCardField = anchor;804 startDismissLock();805 currentCardDismiss = null;806 currentCardAnchor = null;807 },808 }809 );810}811812function injectCardIcon(field: HTMLInputElement): void {813 if (processedCardInputs.has(field)) return;814 const cleanup = injectFieldIcon(field, () => {815 currentCardDismiss?.();816 currentCardDismiss = null;817 lastDismissedCardField = null;818 dismissLock = false;819 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }820 clearFillStateForExplicitSummon(field);821 field.focus({ preventScroll: true });822 void openCardSelector(field);823 });824 processedCardInputs.set(field, cleanup);825}826827function setupCardAutofill(): void {828 function scan() {829 const cardForm = detectCardForm();830 if (!cardForm?.number) return;831 if (!isVisible(cardForm.number)) return;832 injectCardIcon(cardForm.number);833 }834835 836 837 setTimeout(scan, 0);838 setTimeout(scan, 500);839 setTimeout(scan, 1500);840841 842 843 844 let pending = false;845 new MutationObserver(() => {846 if (pending) return;847 pending = true;848 setTimeout(() => { pending = false; scan(); }, 200);849 }).observe(document.body, { childList: true, subtree: true });850851 852 853 854 document.addEventListener("focusin", (e) => {855 const target = e.target;856 if (!(target instanceof HTMLInputElement)) return;857 const cardForm = detectCardForm();858 if (cardForm?.number === target) {859 injectCardIcon(target);860 }861 }, true);862}863864chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {865 866 if (sender.id !== chrome.runtime.id) return;867 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {868 const policy = detectPasswordPolicy();869 sendResponse({ ok: true, data: policy });870 return true;871 }872 if (msg?.type === "PING") {873 sendResponse({ ok: true });874 return true;875 }876 if (msg?.type === "SUMMON_AUTOFILL") {877 const source = (msg as { type: string; source?: string }).source;878 const isShortcut = source === "shortcut";879880 const activeInput = getDeepActiveInput();881 const fields = detectLoginFields();882 const hasForm = isLoginForm(fields) || isSignupForm(fields);883884 if (hasForm) {885 886 887 const inForm = activeInput && fields.some(f => f.el === activeInput);888 const target = inForm889 ? activeInput890 : (fields.find(f => f.type === "password")?.el891 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);892 if (target) {893 894 895 clearFillStateForExplicitSummon(target);896 dismissLock = false;897 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }898 lastDismissedField = null;899 void handleFieldInteraction(target);900 }901 } else if (isShortcut) {902 903 showSearchPalette();904 }905906 907 if (isShortcut) {908 const domain = getPageDomain();909 if (domain) {910 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});911 }912 }913914 sendResponse({ ok: hasForm || isShortcut });915 return true;916 }917 if (msg?.type === "PASSKEY_PRO_GATE") {918 919 920 showPasskeyProGate();921 sendResponse({ ok: true });922 return true;923 }924 if (msg?.type === "VAULT_UNLOCKED") {925 926 927 928 const savedField = currentAnchorField;929 if (currentDismiss) {930 currentDismiss();931 currentDismiss = null;932 currentAnchorField = null;933 }934 void handleFieldInteraction(savedField ?? undefined);935 sendResponse({ ok: true });936 return true;937 }938 return true;939});940941942943944945946947948949950951952if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {953 let lastPasskeyOfferAt = 0;954 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;955956 window.addEventListener("message", (event: MessageEvent) => {957 if (event.source !== window) return;958 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;959 if (!data || data.source !== "peach-passkey-firefox") return;960 if (detectBrowser() !== "firefox") return;961 if (data.type !== "create") return;962963 964 965 const now = Date.now();966 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;967 lastPasskeyOfferAt = now;968969 const domain = location.hostname.replace(/^www\./, "");970 chrome.runtime.sendMessage({971 type: "GET_PASSKEY_OFFER_DECLINED",972 payload: { domain },973 }).then((res: { ok: boolean; data?: boolean } | undefined) => {974 if (res?.data === true) return;975 const rpId = data.rpId ?? domain;976 showPasskeyRegistrationOffer({977 rpId,978 rpName: data.rpName,979 userName: data.userName,980 userDisplayName: data.userDisplayName,981 });982 }).catch(() => {});983 });984}985986987988989990991992993994995996997998999{1000 function checkPasskeyAvailability() {1001 const domain = location.hostname.replace(/^www\./, "");1002 if (!domain) return;1003 const sessionKey = `peach_state11_shown:${domain}`;1004 chrome.storage.session?.get(sessionKey).then((stored) => {1005 if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1006 chrome.runtime.sendMessage({1007 type: "GET_PASSKEY_FOR_DOMAIN",1008 payload: { domain },1009 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1010 const data = res?.data;1011 if (!data) return;1012 const current = detectBrowser();1013 const isCrossBrowser =1014 data.browser && current !== "unknown" && data.browser !== current;1015 const valuableOnFirefox = current === "firefox";1016 if (!isCrossBrowser && !valuableOnFirefox) return;1017 chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1018 showPasskeyAvailable({1019 rpId: data.rpId,1020 userName: data.userName,1021 fromBrowser: data.browser,1022 currentBrowser: current,1023 });1024 }).catch(() => {});1025 }).catch(() => {});1026 }10271028 1029 1030 1031 if (document.readyState === "loading") {1032 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1033 } else {1034 setTimeout(checkPasskeyAvailability, 800);1035 }1036}