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 if (signupForm && usernameEl && field === usernameEl) {601 await openSignupSelector(usernameEl, passwordEl, entries, allEntries, domain);602 return;603 }604605 await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);606 } finally {607 pendingInteractions.delete(field);608 }609}610611async function onFocusIn(e: Event): Promise<void> {612 613 614 615 616 617 if (isSubmitButton(e.target)) return;618 await handleFieldInteraction();619}620621function reattachListeners(622 el: HTMLInputElement,623 detectedType?: "password" | "username" | "email",624 contextFields?: ReturnType<typeof detectLoginFields>625): void {626 if (processedInputs.has(el)) return;627 if (!resolveAutofillFieldType(el, detectedType)) return;628 629 const fields = contextFields ?? detectLoginFields();630 if (!isLoginForm(fields) && !isSignupForm(fields)) return;631632 const cleanup = injectFieldIcon(el, () => {633 currentDismiss?.();634 currentDismiss = null;635 lastDismissedField = null; 636 dismissLock = false; 637 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }638 clearFillStateForExplicitSummon(el);639 el.focus({ preventScroll: true });640 void handleFieldInteraction(el);641 });642 processedInputs.set(el, cleanup);643}644645const debouncedReattach = debounce(() => {646 const allFields = detectLoginFields();647 648 if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;649 const newFields = allFields.filter(650 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)651 );652 for (const f of newFields) {653 reattachListeners(f.el, f.type, allFields);654 }655 656 657 658}, 200);659660function setupMutationObserver(): void {661 const observer = new MutationObserver(debouncedReattach);662 observer.observe(document.body, {663 childList: true,664 subtree: true,665 attributes: true,666 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],667 });668}669670function initialScan(aggressionLevel = 0, isFinalPass = false) {671 const allFields = detectLoginFields();672 const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);673674 if (aggressionLevel === 0 && !hasKnownForm) return;675676 const newFields = allFields.filter(677 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)678 );679680 for (const f of newFields) {681 reattachListeners(f.el, f.type, allFields);682 }683684 685 686 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {687 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');688 for (const el of pwInputs) {689 if (isVisible(el) && !processedInputs.has(el)) {690 const cleanup = injectFieldIcon(el, () => {691 currentDismiss?.();692 currentDismiss = null;693 lastDismissedField = null;694 dismissLock = false;695 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }696 clearFillStateForExplicitSummon(el);697 el.focus({ preventScroll: true });698 void handleFieldInteraction(el);699 });700 processedInputs.set(el, cleanup);701 }702 }703 }704}705706document.addEventListener("focusin", onFocusIn);707708setupMutationObserver();709setupSaveDetection();710setupCardAutofill();711712713714715716717718719let lastObservedUrl = location.href;720new MutationObserver(() => {721 if (location.href !== lastObservedUrl) {722 lastObservedUrl = location.href;723 pageFilledAt = null;724 }725}).observe(document.body, { childList: true, subtree: false });726727728729(async () => {730 let aggressionLevel = 0;731 try {732 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });733 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;734 const domain = getPageDomain();735 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;736 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;737 } catch { }738739 setTimeout(() => initialScan(aggressionLevel, false), 0);740 setTimeout(() => initialScan(aggressionLevel, false), 500);741 setTimeout(() => initialScan(aggressionLevel, true), 1500);742})();743744745746747748749const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();750let currentCardDismiss: (() => void) | null = null;751let currentCardAnchor: HTMLInputElement | null = null;752let lastDismissedCardField: HTMLInputElement | null = null;753754async function fetchSavedCards(): Promise<CardSelectorEntry[]> {755 const resp = await chrome.runtime.sendMessage({756 type: "AUTOFILL_QUERY",757 payload: { domain: getPageDomain(), kind: "card" },758 }).catch(() => null);759 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;760 return r?.ok ? (r.data ?? []) : [];761}762763async function openCardSelector(anchor: HTMLInputElement): Promise<void> {764 if (!canOpen()) return;765 if (currentCardDismiss && currentCardAnchor === anchor) return;766 if (anchor === lastDismissedCardField) return;767 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;768 if (wasAlreadyFilled(anchor)) return;769770 const cards = await fetchSavedCards();771 if (cards.length === 0) return; 772773 const cardForm = detectCardForm();774 if (!cardForm?.number) return;775776 currentCardDismiss?.();777 currentCardAnchor = anchor;778 currentCardDismiss = showCardSelector(779 anchor,780 cards,781 {782 domain: getPageDomain(),783 onFill: (entry) => {784 if (!cardForm) return;785 fillCardForm(cardForm, {786 cardNumber: entry.cardNumber ?? "",787 expMonth: entry.expMonth ?? "",788 expYear: entry.expYear ?? "",789 cvc: entry.cvc ?? "",790 cardholderName: entry.cardholderName ?? "",791 });792 793 794 795 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);796 currentCardDismiss = null;797 currentCardAnchor = null;798 },799 onDismiss: () => {800 lastDismissedCardField = anchor;801 startDismissLock();802 currentCardDismiss = null;803 currentCardAnchor = null;804 },805 }806 );807}808809function injectCardIcon(field: HTMLInputElement): void {810 if (processedCardInputs.has(field)) return;811 const cleanup = injectFieldIcon(field, () => {812 currentCardDismiss?.();813 currentCardDismiss = null;814 lastDismissedCardField = null;815 dismissLock = false;816 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }817 clearFillStateForExplicitSummon(field);818 field.focus({ preventScroll: true });819 void openCardSelector(field);820 });821 processedCardInputs.set(field, cleanup);822}823824function setupCardAutofill(): void {825 function scan() {826 const cardForm = detectCardForm();827 if (!cardForm?.number) return;828 if (!isVisible(cardForm.number)) return;829 injectCardIcon(cardForm.number);830 }831832 833 834 setTimeout(scan, 0);835 setTimeout(scan, 500);836 setTimeout(scan, 1500);837838 839 840 841 let pending = false;842 new MutationObserver(() => {843 if (pending) return;844 pending = true;845 setTimeout(() => { pending = false; scan(); }, 200);846 }).observe(document.body, { childList: true, subtree: true });847848 849 850 851 document.addEventListener("focusin", (e) => {852 const target = e.target;853 if (!(target instanceof HTMLInputElement)) return;854 const cardForm = detectCardForm();855 if (cardForm?.number === target) {856 injectCardIcon(target);857 }858 }, true);859}860861chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {862 863 if (sender.id !== chrome.runtime.id) return;864 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {865 const policy = detectPasswordPolicy();866 sendResponse({ ok: true, data: policy });867 return true;868 }869 if (msg?.type === "PING") {870 sendResponse({ ok: true });871 return true;872 }873 if (msg?.type === "SUMMON_AUTOFILL") {874 const source = (msg as { type: string; source?: string }).source;875 const isShortcut = source === "shortcut";876877 const activeInput = getDeepActiveInput();878 const fields = detectLoginFields();879 const hasForm = isLoginForm(fields) || isSignupForm(fields);880881 if (hasForm) {882 883 884 const inForm = activeInput && fields.some(f => f.el === activeInput);885 const target = inForm886 ? activeInput887 : (fields.find(f => f.type === "password")?.el888 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);889 if (target) {890 891 892 clearFillStateForExplicitSummon(target);893 dismissLock = false;894 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }895 lastDismissedField = null;896 void handleFieldInteraction(target);897 }898 } else if (isShortcut) {899 900 showSearchPalette();901 }902903 904 if (isShortcut) {905 const domain = getPageDomain();906 if (domain) {907 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});908 }909 }910911 sendResponse({ ok: hasForm || isShortcut });912 return true;913 }914 if (msg?.type === "PASSKEY_PRO_GATE") {915 916 917 showPasskeyProGate();918 sendResponse({ ok: true });919 return true;920 }921 if (msg?.type === "VAULT_UNLOCKED") {922 923 924 925 const savedField = currentAnchorField;926 if (currentDismiss) {927 currentDismiss();928 currentDismiss = null;929 currentAnchorField = null;930 }931 void handleFieldInteraction(savedField ?? undefined);932 sendResponse({ ok: true });933 return true;934 }935 return true;936});937938939940941942943944945946947948949if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {950 let lastPasskeyOfferAt = 0;951 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;952953 window.addEventListener("message", (event: MessageEvent) => {954 if (event.source !== window) return;955 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;956 if (!data || data.source !== "peach-passkey-firefox") return;957 if (detectBrowser() !== "firefox") return;958 if (data.type !== "create") return;959960 961 962 const now = Date.now();963 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;964 lastPasskeyOfferAt = now;965966 const domain = location.hostname.replace(/^www\./, "");967 chrome.runtime.sendMessage({968 type: "GET_PASSKEY_OFFER_DECLINED",969 payload: { domain },970 }).then((res: { ok: boolean; data?: boolean } | undefined) => {971 if (res?.data === true) return;972 const rpId = data.rpId ?? domain;973 showPasskeyRegistrationOffer({974 rpId,975 rpName: data.rpName,976 userName: data.userName,977 userDisplayName: data.userDisplayName,978 });979 }).catch(() => {});980 });981}982983984985986987988989990991992993994995996{997 function checkPasskeyAvailability() {998 const domain = location.hostname.replace(/^www\./, "");999 if (!domain) return;1000 const sessionKey = `peach_state11_shown:${domain}`;1001 chrome.storage.session?.get(sessionKey).then((stored) => {1002 if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1003 chrome.runtime.sendMessage({1004 type: "GET_PASSKEY_FOR_DOMAIN",1005 payload: { domain },1006 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1007 const data = res?.data;1008 if (!data) return;1009 const current = detectBrowser();1010 const isCrossBrowser =1011 data.browser && current !== "unknown" && data.browser !== current;1012 const valuableOnFirefox = current === "firefox";1013 if (!isCrossBrowser && !valuableOnFirefox) return;1014 chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1015 showPasskeyAvailable({1016 rpId: data.rpId,1017 userName: data.userName,1018 fromBrowser: data.browser,1019 currentBrowser: current,1020 });1021 }).catch(() => {});1022 }).catch(() => {});1023 }10241025 1026 1027 1028 if (document.readyState === "loading") {1029 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1030 } else {1031 setTimeout(checkPasskeyAvailability, 800);1032 }1033}