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 { fillCardForm, fillFields } from "./fill";24import { setupSaveDetection } from "./save";25import { contentMLDetector } from "./content-ml-detector";26import { detectPasswordPolicy } from "./policy";27import type { FieldPrediction } from "../shared/ml";28import { generateTOTP } from "../crypto/totp";29import type { SavedIdentity, VaultEntry } from "../shared/types";303132333435const processedInputs = new WeakMap<HTMLInputElement, () => void>();36const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);3738let currentDismiss: (() => void) | null = null;3940let currentAnchorField: HTMLInputElement | null = null;4142const pendingInteractions = new WeakSet<HTMLInputElement>();43444546let lastDismissedField: HTMLInputElement | null = null;47484950515253const DISMISS_LOCK_MS = 800;54let dismissLock = false;55let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;56function startDismissLock(): void {57 dismissLock = true;58 if (dismissLockTimer) clearTimeout(dismissLockTimer);59 dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);60}61function canOpen(): boolean { return !dismissLock; }6263646566676869707172737475const filledForms = new WeakSet<HTMLFormElement>();76let pageFilledAt: number | null = null;77const PAGE_FILL_GRACE_MS = 3000;7879function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {80 for (const f of fields) {81 if (!f) continue;82 const form = f.closest("form");83 if (form) filledForms.add(form);84 }85 pageFilledAt = Date.now();86}8788function wasAlreadyFilled(field: HTMLInputElement): boolean {89 const form = field.closest("form");90 if (form && filledForms.has(form)) return true;91 if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;92 return false;93}9495function clearFillStateForExplicitSummon(field: HTMLInputElement): void {96 const form = field.closest("form");97 if (form) filledForms.delete(form);98 pageFilledAt = null;99}100101102103104105function isSubmitButton(el: EventTarget | null): boolean {106 if (!(el instanceof HTMLElement)) return false;107 if (el instanceof HTMLButtonElement && el.type !== "button") return true;108 if (el instanceof HTMLInputElement && el.type === "submit") return true;109 if (el.getAttribute("type") === "submit") return true;110 const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();111 if (!text || text.length > 24) return false;112 return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);113}114115function debounce<T extends (...args: unknown[]) => void>(116 fn: T,117 ms: number118): (...args: Parameters<T>) => void {119 let timer: ReturnType<typeof setTimeout>;120 return (...args: Parameters<T>) => {121 clearTimeout(timer);122 timer = setTimeout(() => fn(...args), ms);123 };124}125126function showToast(message: string): void {127 const toast = document.createElement("div");128 toast.style.cssText = `129 position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);130 background: #131109; color: #F0E8D8; padding: 8px 16px;131 border-radius: 8px; font-family: 'IBM Plex Mono', monospace;132 font-size: 11px; z-index: 2147483647; opacity: 0;133 transition: opacity 200ms ease;134 border: 1px solid rgba(240,232,216,0.07);135 pointer-events: none;136 `;137 toast.textContent = message;138 document.body.appendChild(toast);139 requestAnimationFrame(() => { toast.style.opacity = "1"; });140 setTimeout(() => {141 toast.style.opacity = "0";142 setTimeout(() => toast.remove(), 200);143 }, 2000);144}145146function showSearchPalette(): void {147 const host = document.createElement("div");148 host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";149 document.body.appendChild(host);150 const shadow = host.attachShadow({ mode: "closed" });151152 const style = document.createElement("style");153 style.textContent = `154 .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;155 font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;156 box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}157 .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);158 font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}159 .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}160 .s{padding:8px 12px}161 .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);162 border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;163 padding:6px 8px;font-family:inherit;font-size:12px;outline:none}164 .l{max-height:220px;overflow-y:auto}165 .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}166 .e:hover{background:rgba(240,232,216,.06)}167 .et{font-size:12px}168 .eu{font-size:10px;color:rgba(240,232,216,.45)}169 .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}170 `;171172 let allEntries: SelectorEntry[] = [];173 let query = "";174175 const panel = document.createElement("div");176 panel.className = "p";177178 const hdr = document.createElement("div");179 hdr.className = "h";180 const hdrText = document.createElement("span");181 hdrText.textContent = "No form detected — search your vault";182 const closeBtn = document.createElement("button");183 closeBtn.className = "x";184 closeBtn.textContent = "✕";185 hdr.appendChild(hdrText);186 hdr.appendChild(closeBtn);187188 const searchWrap = document.createElement("div");189 searchWrap.className = "s";190 const searchInput = document.createElement("input");191 searchInput.placeholder = "search...";192 searchWrap.appendChild(searchInput);193194 const list = document.createElement("div");195 list.className = "l";196197 panel.appendChild(hdr);198 panel.appendChild(searchWrap);199 panel.appendChild(list);200 shadow.appendChild(style);201 shadow.appendChild(panel);202203 function close() { host.remove(); }204205 closeBtn.onclick = close;206207 function onKeyDown(e: KeyboardEvent) {208 if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }209 }210 document.addEventListener("keydown", onKeyDown, true);211212 function render() {213 const q = query.toLowerCase();214 const filtered = q215 ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))216 : allEntries;217 list.innerHTML = "";218 if (filtered.length === 0) {219 const em = document.createElement("div");220 em.className = "em";221 em.textContent = query ? "no matches" : "vault is empty";222 list.appendChild(em);223 return;224 }225 for (const entry of filtered.slice(0, 20)) {226 const row = document.createElement("div");227 row.className = "e";228 const title = document.createElement("div");229 title.className = "et";230 title.textContent = entry.title;231 row.appendChild(title);232 if (entry.username) {233 const user = document.createElement("div");234 user.className = "eu";235 user.textContent = entry.username;236 row.appendChild(user);237 }238 row.onclick = async () => {239 const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });240 const r = resp as { ok: boolean; data?: { password?: string } };241 if (r.ok && r.data?.password) {242 let alreadyWritten = false;243 try { await navigator.clipboard.writeText(r.data.password); alreadyWritten = true; } catch {}244 await chrome.runtime.sendMessage({245 type: "COPY",246 payload: { text: r.data.password, label: "Password", alreadyWritten },247 });248 showToast("Password copied");249 } else {250 showToast("Could not copy password");251 }252 close();253 document.removeEventListener("keydown", onKeyDown, true);254 };255 list.appendChild(row);256 }257 }258259 searchInput.oninput = () => { query = searchInput.value; render(); };260261 fetchAutofillEntries(getPageDomain(), true).then(result => {262 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }263 allEntries = result.entries;264 render();265 searchInput.focus();266 });267}268269function setNativeValue(el: HTMLInputElement, value: string): void {270 const nativeSetter = Object.getOwnPropertyDescriptor(271 HTMLInputElement.prototype, "value"272 )!.set!;273 nativeSetter.call(el, value);274 el.dispatchEvent(new Event("input", { bubbles: true }));275 el.dispatchEvent(new Event("change", { bubbles: true }));276}277278function findTOTPField(): HTMLInputElement | null {279 const inputs = document.querySelectorAll<HTMLInputElement>("input");280 for (const input of inputs) {281 if (!isVisible(input)) continue;282 const autocomplete = input.autocomplete.toLowerCase();283 const nameId = (input.name + input.id).toLowerCase();284 const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();285 if (286 autocomplete === "one-time-code" ||287 /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)288 ) {289 return input;290 }291 const labelEl = input.closest("label");292 if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {293 return input;294 }295 }296 return null;297}298299async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {300 await new Promise((r) => setTimeout(r, 400));301 if (totpField.value === "" || totpField.value.trim() === "") {302 const { code } = generateTOTP(totpSecret);303 setNativeValue(totpField, code);304 showToast("TOTP autofilled");305 }306}307308309async function handleAutofill(310 field: HTMLInputElement,311 usernameEl: HTMLInputElement | null,312 passwordEl: HTMLInputElement,313 entry: VaultEntry314): Promise<void> {315 if (!entry.username && !entry.password) return;316 const pageDomain = getPageDomain();317 const form = passwordEl.closest("form") as HTMLFormElement | null;318 fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);319320 if (entry.canary) {321 chrome.runtime.sendMessage({322 type: "FIRE_CANARY_PING",323 payload: {324 webhookUrl: entry.canary.webhookUrl,325 entryTitle: entry.title,326 trigger: "autofilled",327 },328 }).catch(() => {});329 chrome.runtime.sendMessage({330 type: "UPDATE_ENTRY",331 payload: {332 id: entry.id,333 patch: {334 canary: {335 ...entry.canary,336 lastPinged: Date.now(),337 pingCount: (entry.canary.pingCount ?? 0) + 1,338 },339 },340 },341 }).catch(() => {});342 }343344 if (entry.totp) {345 const { code } = generateTOTP(entry.totp);346 let alreadyWritten = false;347 try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}348 const response = await chrome.runtime.sendMessage({349 type: "COPY",350 payload: { text: code, label: "TOTP", alreadyWritten },351 });352 if (alreadyWritten || (response as { ok?: boolean }).ok) {353 showToast("TOTP copied · " + code);354 }355 const totpField = findTOTPField();356 if (totpField) {357 autofillTOTP(totpField, entry.totp);358 }359 }360}361362async function fetchAutofillEntries(363 domain: string,364 includeAll = false365): Promise<{ entries: SelectorEntry[]; locked: boolean }> {366 const response = await chrome.runtime.sendMessage({367 type: "AUTOFILL_QUERY",368 payload: { domain, includeAll },369 });370 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };371 if (!res.ok && res.error === "VAULT_LOCKED") {372 return { entries: [], locked: true };373 }374 return { entries: res.data ?? [], locked: false };375}376377378function resolveAutofillFieldType(379 el: HTMLInputElement,380 predictedType?: FieldPrediction["type"] | null381): "password" | "username" | "email" | null {382 if (383 predictedType === "password" ||384 predictedType === "username" ||385 predictedType === "email"386 ) {387 return predictedType;388 }389390 const detected = detectLoginFields().find((field) => field.el === el)?.type;391 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {392 return detected;393 }394395 const htmlType = el.type.toLowerCase();396 if (htmlType === "password") return "password";397 if (htmlType === "email") return "email";398 return null;399}400401async function openAutofillSelector(402 anchorField: HTMLInputElement,403 usernameEl: HTMLInputElement | null,404 passwordEl: HTMLInputElement,405 domainEntries: SelectorEntry[],406 searchableEntries: SelectorEntry[],407 domain: string408): Promise<void> {409 currentDismiss?.();410 currentAnchorField = anchorField;411 currentDismiss = showAutofillSelector(412 anchorField,413 domainEntries,414 async (id: string) => {415 currentDismiss = null;416 currentAnchorField = null;417 const entryResponse = await chrome.runtime.sendMessage({418 type: "GET_ENTRY_FOR_FILL",419 payload: { id },420 });421 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;422 if (entry) {423 await handleAutofill(anchorField, usernameEl, passwordEl, entry);424 recordFillSuccess(anchorField, usernameEl, passwordEl);425 426 427 428 const pageDomain = location.hostname.replace(/^www\./, "");429 const entryDomains = new Set<string>();430 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {431 try {432 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));433 } catch { }434 }435 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {436 showRememberSiteToast(pageDomain, entry.id);437 }438 }439 },440 {441 domain,442 searchableEntries,443 444 445 446 447 448 onFillFields: (username, password) => {449 const form = passwordEl.closest("form") as HTMLFormElement | null;450 fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());451 recordFillSuccess(anchorField, usernameEl, passwordEl);452 },453 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },454 }455 );456}457458async function openSignupSelector(459 usernameEl: HTMLInputElement,460 passwordEl: HTMLInputElement | null,461 domainEntries: SelectorEntry[],462 allEntries: SelectorEntry[],463 domain: string464): Promise<void> {465 466 467 468 let savedIdentities: SavedIdentity[] = [];469 try {470 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as471 { ok: boolean; data?: SavedIdentity[] } | null;472 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;473 } catch { }474475 476 477 const form = passwordEl?.closest("form") ?? document.body;478 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));479 const confirmEl = allPwInputs.find(480 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)481 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);482483 currentDismiss?.();484 currentAnchorField = usernameEl;485 currentDismiss = showAutofillSelector(486 usernameEl,487 domainEntries,488 () => {},489 {490 domain,491 searchableEntries: allEntries,492 isSignup: true,493 savedIdentities,494 onFillFields: (username, password) => {495 if (username) setNativeValue(usernameEl, username);496 if (password && passwordEl) {497 setNativeValue(passwordEl, password);498 if (confirmEl) setNativeValue(confirmEl, password);499 }500 recordFillSuccess(usernameEl, passwordEl);501 },502 onDismiss: () => { lastDismissedField = usernameEl; startDismissLock(); },503 }504 );505}506507508async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {509 const field = anchorField ?? getDeepActiveInput();510 if (!field) return;511 if (!isVisible(field)) return;512513 514 515 if (!canOpen()) return;516517 518 if (currentDismiss && currentAnchorField === field) return;519520 521 522 if (field !== lastDismissedField) lastDismissedField = null;523 524 525 if (field === lastDismissedField) return;526527 528 529 530 531 if (wasAlreadyFilled(field)) return;532533 534 535 if (pendingInteractions.has(field)) return;536 pendingInteractions.add(field);537538 try {539 const fieldType = field.type.toLowerCase();540541 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {542 return preds[0] ?? null;543 });544545 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {546 const timeout = setTimeout(() => resolve(null), 150);547 mlPromise.then((pred) => {548 clearTimeout(timeout);549 resolve(pred);550 });551 });552553 if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {554 return;555 }556557 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);558 if (autofillFieldType) {559 reattachListeners(field, autofillFieldType);560 }561562 let fields = detectLoginFields();563 const loginForm = isLoginForm(fields);564 const signupForm = isSignupForm(fields);565 if (!loginForm && !signupForm) {566 return;567 }568569 const domain = getPageDomain();570 const firstResult = await fetchAutofillEntries(domain);571572 573 574 575 if (firstResult.locked) {576 currentDismiss?.();577 currentAnchorField = field;578 currentDismiss = showAutofillSelector(579 field,580 [],581 () => {},582 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }583 );584 return;585 }586587 const entries = firstResult.entries;588 const allEntries = entries.length === 0589 ? (await fetchAutofillEntries(domain, true)).entries590 : entries;591592 let usernameEl: HTMLInputElement | null = null;593 const userField = fields.find((f) => f.type === "username" || f.type === "email");594 if (userField) usernameEl = userField.el;595 const pwField = fields.find((f) => f.type === "password");596 if (!pwField) return;597 const passwordEl = pwField.el;598599 if (signupForm && usernameEl && field === usernameEl) {600 await openSignupSelector(usernameEl, passwordEl, entries, allEntries, domain);601 return;602 }603604 await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);605 } finally {606 pendingInteractions.delete(field);607 }608}609610async function onFocusIn(e: Event): Promise<void> {611 612 613 614 615 616 if (isSubmitButton(e.target)) return;617 await handleFieldInteraction();618}619620function reattachListeners(621 el: HTMLInputElement,622 detectedType?: "password" | "username" | "email",623 contextFields?: ReturnType<typeof detectLoginFields>624): void {625 if (processedInputs.has(el)) return;626 if (!resolveAutofillFieldType(el, detectedType)) return;627 628 const fields = contextFields ?? detectLoginFields();629 if (!isLoginForm(fields) && !isSignupForm(fields)) return;630631 const cleanup = injectFieldIcon(el, () => {632 currentDismiss?.();633 currentDismiss = null;634 lastDismissedField = null; 635 dismissLock = false; 636 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }637 clearFillStateForExplicitSummon(el);638 el.focus({ preventScroll: true });639 void handleFieldInteraction(el);640 });641 processedInputs.set(el, cleanup);642}643644const debouncedReattach = debounce(() => {645 const allFields = detectLoginFields();646 647 if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;648 const newFields = allFields.filter(649 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)650 );651 for (const f of newFields) {652 reattachListeners(f.el, f.type, allFields);653 }654 655 656 657}, 200);658659function setupMutationObserver(): void {660 const observer = new MutationObserver(debouncedReattach);661 observer.observe(document.body, {662 childList: true,663 subtree: true,664 attributes: true,665 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],666 });667}668669function initialScan(aggressionLevel = 0, isFinalPass = false) {670 const allFields = detectLoginFields();671 const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);672673 if (aggressionLevel === 0 && !hasKnownForm) return;674675 const newFields = allFields.filter(676 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)677 );678679 for (const f of newFields) {680 reattachListeners(f.el, f.type, allFields);681 }682683 684 685 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {686 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');687 for (const el of pwInputs) {688 if (isVisible(el) && !processedInputs.has(el)) {689 const cleanup = injectFieldIcon(el, () => {690 currentDismiss?.();691 currentDismiss = null;692 lastDismissedField = null;693 dismissLock = false;694 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }695 clearFillStateForExplicitSummon(el);696 el.focus({ preventScroll: true });697 void handleFieldInteraction(el);698 });699 processedInputs.set(el, cleanup);700 }701 }702 }703}704705document.addEventListener("focusin", onFocusIn);706707setupMutationObserver();708setupSaveDetection();709setupCardAutofill();710711712713714715716717718let lastObservedUrl = location.href;719new MutationObserver(() => {720 if (location.href !== lastObservedUrl) {721 lastObservedUrl = location.href;722 pageFilledAt = null;723 }724}).observe(document.body, { childList: true, subtree: false });725726727728(async () => {729 let aggressionLevel = 0;730 try {731 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });732 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;733 const domain = getPageDomain();734 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;735 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;736 } catch { }737738 setTimeout(() => initialScan(aggressionLevel, false), 0);739 setTimeout(() => initialScan(aggressionLevel, false), 500);740 setTimeout(() => initialScan(aggressionLevel, true), 1500);741})();742743744745746747748const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();749let currentCardDismiss: (() => void) | null = null;750let currentCardAnchor: HTMLInputElement | null = null;751let lastDismissedCardField: HTMLInputElement | null = null;752753async function fetchSavedCards(): Promise<CardSelectorEntry[]> {754 const resp = await chrome.runtime.sendMessage({755 type: "AUTOFILL_QUERY",756 payload: { domain: getPageDomain(), kind: "card" },757 }).catch(() => null);758 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;759 return r?.ok ? (r.data ?? []) : [];760}761762async function openCardSelector(anchor: HTMLInputElement): Promise<void> {763 if (!canOpen()) return;764 if (currentCardDismiss && currentCardAnchor === anchor) return;765 if (anchor === lastDismissedCardField) return;766 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;767 if (wasAlreadyFilled(anchor)) return;768769 const cards = await fetchSavedCards();770 if (cards.length === 0) return; 771772 const cardForm = detectCardForm();773 if (!cardForm?.number) return;774775 currentCardDismiss?.();776 currentCardAnchor = anchor;777 currentCardDismiss = showCardSelector(778 anchor,779 cards,780 {781 domain: getPageDomain(),782 onFill: (entry) => {783 if (!cardForm) return;784 fillCardForm(cardForm, {785 cardNumber: entry.cardNumber ?? "",786 expMonth: entry.expMonth ?? "",787 expYear: entry.expYear ?? "",788 cvc: entry.cvc ?? "",789 cardholderName: entry.cardholderName ?? "",790 });791 792 793 794 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);795 currentCardDismiss = null;796 currentCardAnchor = null;797 },798 onDismiss: () => {799 lastDismissedCardField = anchor;800 startDismissLock();801 currentCardDismiss = null;802 currentCardAnchor = null;803 },804 }805 );806}807808function injectCardIcon(field: HTMLInputElement): void {809 if (processedCardInputs.has(field)) return;810 const cleanup = injectFieldIcon(field, () => {811 currentCardDismiss?.();812 currentCardDismiss = null;813 lastDismissedCardField = null;814 dismissLock = false;815 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }816 clearFillStateForExplicitSummon(field);817 field.focus({ preventScroll: true });818 void openCardSelector(field);819 });820 processedCardInputs.set(field, cleanup);821}822823function setupCardAutofill(): void {824 function scan() {825 const cardForm = detectCardForm();826 if (!cardForm?.number) return;827 if (!isVisible(cardForm.number)) return;828 injectCardIcon(cardForm.number);829 }830831 832 833 setTimeout(scan, 0);834 setTimeout(scan, 500);835 setTimeout(scan, 1500);836837 838 839 840 let pending = false;841 new MutationObserver(() => {842 if (pending) return;843 pending = true;844 setTimeout(() => { pending = false; scan(); }, 200);845 }).observe(document.body, { childList: true, subtree: true });846847 848 849 850 document.addEventListener("focusin", (e) => {851 const target = e.target;852 if (!(target instanceof HTMLInputElement)) return;853 const cardForm = detectCardForm();854 if (cardForm?.number === target) {855 injectCardIcon(target);856 }857 }, true);858}859860chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {861 862 if (sender.id !== chrome.runtime.id) return;863 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {864 const policy = detectPasswordPolicy();865 sendResponse({ ok: true, data: policy });866 return true;867 }868 if (msg?.type === "PING") {869 sendResponse({ ok: true });870 return true;871 }872 if (msg?.type === "SUMMON_AUTOFILL") {873 const source = (msg as { type: string; source?: string }).source;874 const isShortcut = source === "shortcut";875876 const activeInput = getDeepActiveInput();877 const fields = detectLoginFields();878 const hasForm = isLoginForm(fields) || isSignupForm(fields);879880 if (hasForm) {881 882 883 const inForm = activeInput && fields.some(f => f.el === activeInput);884 const target = inForm885 ? activeInput886 : (fields.find(f => f.type === "password")?.el887 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);888 if (target) {889 890 891 clearFillStateForExplicitSummon(target);892 dismissLock = false;893 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }894 lastDismissedField = null;895 void handleFieldInteraction(target);896 }897 } else if (isShortcut) {898 899 showSearchPalette();900 }901902 903 if (isShortcut) {904 const domain = getPageDomain();905 if (domain) {906 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});907 }908 }909910 sendResponse({ ok: hasForm || isShortcut });911 return true;912 }913 if (msg?.type === "PASSKEY_PRO_GATE") {914 915 916 showPasskeyProGate();917 sendResponse({ ok: true });918 return true;919 }920 if (msg?.type === "VAULT_UNLOCKED") {921 922 923 924 const savedField = currentAnchorField;925 if (currentDismiss) {926 currentDismiss();927 currentDismiss = null;928 currentAnchorField = null;929 }930 void handleFieldInteraction(savedField ?? undefined);931 sendResponse({ ok: true });932 return true;933 }934 return true;935});936937938939940941942943944945{946 let lastPasskeyOfferAt = 0;947 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;948949 window.addEventListener("message", (event: MessageEvent) => {950 if (event.source !== window) return;951 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;952 if (!data || data.source !== "peach-passkey-firefox") return;953 if (detectBrowser() !== "firefox") return;954 if (data.type !== "create") return;955956 957 958 const now = Date.now();959 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;960 lastPasskeyOfferAt = now;961962 const domain = location.hostname.replace(/^www\./, "");963 chrome.runtime.sendMessage({964 type: "GET_PASSKEY_OFFER_DECLINED",965 payload: { domain },966 }).then((res: { ok: boolean; data?: boolean } | undefined) => {967 if (res?.data === true) return;968 const rpId = data.rpId ?? domain;969 showPasskeyRegistrationOffer({970 rpId,971 rpName: data.rpName,972 userName: data.userName,973 userDisplayName: data.userDisplayName,974 });975 }).catch(() => {});976 });977}978979980981982983{984 let availabilityChecked = false;985986 function checkPasskeyAvailability() {987 if (availabilityChecked) return;988 availabilityChecked = true;989 const domain = location.hostname.replace(/^www\./, "");990 if (!domain) return;991 chrome.runtime.sendMessage({992 type: "GET_PASSKEY_FOR_DOMAIN",993 payload: { domain },994 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {995 const data = res?.data;996 if (!data) return;997 showPasskeyAvailable({998 rpId: data.rpId,999 userName: data.userName,1000 fromBrowser: data.browser,1001 currentBrowser: detectBrowser(),1002 });1003 }).catch(() => {});1004 }10051006 1007 1008 1009 if (document.readyState === "loading") {1010 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1011 } else {1012 setTimeout(checkPasskeyAvailability, 800);1013 }1014}