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;57585960let passkeySummonActive = false;61626364let passkeyToastActive = false;65function startDismissLock(): void {66 dismissLock = true;67 if (dismissLockTimer) clearTimeout(dismissLockTimer);68 dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);69}70function canOpen(): boolean { return !dismissLock; }7172737475767778798081828384const filledForms = new WeakSet<HTMLFormElement>();85let pageFilledAt: number | null = null;86const PAGE_FILL_GRACE_MS = 3000;8788function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {89 for (const f of fields) {90 if (!f) continue;91 const form = f.closest("form");92 if (form) filledForms.add(form);93 }94 pageFilledAt = Date.now();95}9697function wasAlreadyFilled(field: HTMLInputElement): boolean {98 const form = field.closest("form");99 if (form && filledForms.has(form)) return true;100 if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;101 return false;102}103104function clearFillStateForExplicitSummon(field: HTMLInputElement): void {105 const form = field.closest("form");106 if (form) filledForms.delete(form);107 pageFilledAt = null;108}109110111112113114function isSubmitButton(el: EventTarget | null): boolean {115 if (!(el instanceof HTMLElement)) return false;116 if (el instanceof HTMLButtonElement && el.type !== "button") return true;117 if (el instanceof HTMLInputElement && el.type === "submit") return true;118 if (el.getAttribute("type") === "submit") return true;119 const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();120 if (!text || text.length > 24) return false;121 return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);122}123124function debounce<T extends (...args: unknown[]) => void>(125 fn: T,126 ms: number127): (...args: Parameters<T>) => void {128 let timer: ReturnType<typeof setTimeout>;129 return (...args: Parameters<T>) => {130 clearTimeout(timer);131 timer = setTimeout(() => fn(...args), ms);132 };133}134135function showToast(message: string): void {136 const toast = document.createElement("div");137 toast.style.cssText = `138 position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);139 background: #131109; color: #F0E8D8; padding: 8px 16px;140 border-radius: 8px; font-family: 'IBM Plex Mono', monospace;141 font-size: 11px; z-index: 2147483647; opacity: 0;142 transition: opacity 200ms ease;143 border: 1px solid rgba(240,232,216,0.07);144 pointer-events: none;145 `;146 toast.textContent = message;147 document.body.appendChild(toast);148 requestAnimationFrame(() => { toast.style.opacity = "1"; });149 setTimeout(() => {150 toast.style.opacity = "0";151 setTimeout(() => toast.remove(), 200);152 }, 2000);153}154155function showSearchPalette(): void {156 const host = document.createElement("div");157 host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";158 document.body.appendChild(host);159 const shadow = host.attachShadow({ mode: "closed" });160161 const style = document.createElement("style");162 style.textContent = `163 .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;164 font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;165 box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}166 .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);167 font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}168 .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}169 .s{padding:8px 12px}170 .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);171 border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;172 padding:6px 8px;font-family:inherit;font-size:12px;outline:none}173 .l{max-height:220px;overflow-y:auto}174 .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}175 .e:hover{background:rgba(240,232,216,.06)}176 .et{font-size:12px}177 .eu{font-size:10px;color:rgba(240,232,216,.45)}178 .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}179 `;180181 let allEntries: SelectorEntry[] = [];182 let query = "";183184 const panel = document.createElement("div");185 panel.className = "p";186187 const hdr = document.createElement("div");188 hdr.className = "h";189 const hdrText = document.createElement("span");190 hdrText.textContent = "No form detected — search your vault";191 const closeBtn = document.createElement("button");192 closeBtn.className = "x";193 closeBtn.textContent = "✕";194 hdr.appendChild(hdrText);195 hdr.appendChild(closeBtn);196197 const searchWrap = document.createElement("div");198 searchWrap.className = "s";199 const searchInput = document.createElement("input");200 searchInput.placeholder = "search...";201 searchWrap.appendChild(searchInput);202203 const list = document.createElement("div");204 list.className = "l";205206 panel.appendChild(hdr);207 panel.appendChild(searchWrap);208 panel.appendChild(list);209 shadow.appendChild(style);210 shadow.appendChild(panel);211212 function close() { host.remove(); }213214 closeBtn.onclick = close;215216 function onKeyDown(e: KeyboardEvent) {217 if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }218 }219 document.addEventListener("keydown", onKeyDown, true);220221 function render() {222 const q = query.toLowerCase();223 const filtered = q224 ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))225 : allEntries;226 list.innerHTML = "";227 if (filtered.length === 0) {228 const em = document.createElement("div");229 em.className = "em";230 em.textContent = query ? "no matches" : "vault is empty";231 list.appendChild(em);232 return;233 }234 for (const entry of filtered.slice(0, 20)) {235 const row = document.createElement("div");236 row.className = "e";237 const title = document.createElement("div");238 title.className = "et";239 title.textContent = entry.title;240 row.appendChild(title);241 if (entry.username) {242 const user = document.createElement("div");243 user.className = "eu";244 user.textContent = entry.username;245 row.appendChild(user);246 }247 row.onclick = async () => {248 const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });249 const r = resp as { ok: boolean; data?: { password?: string } };250 if (r.ok && r.data?.password) {251 let alreadyWritten = false;252 try { await navigator.clipboard.writeText(r.data.password); alreadyWritten = true; } catch {}253 await chrome.runtime.sendMessage({254 type: "COPY",255 payload: { text: r.data.password, label: "Password", alreadyWritten },256 });257 showToast("Password copied");258 } else {259 showToast("Could not copy password");260 }261 close();262 document.removeEventListener("keydown", onKeyDown, true);263 };264 list.appendChild(row);265 }266 }267268 searchInput.oninput = () => { query = searchInput.value; render(); };269270 fetchAutofillEntries(getPageDomain(), true).then(result => {271 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }272 allEntries = result.entries;273 render();274 searchInput.focus();275 });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 410 411 412 const isSignup = domainEntries.length === 0;413 let savedIdentities: SavedIdentity[] | undefined;414 let confirmEl: HTMLInputElement | null = null;415 if (isSignup) {416 try {417 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as418 { ok: boolean; data?: SavedIdentity[] } | null;419 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;420 } catch { }421422 const form = passwordEl.closest("form") ?? document.body;423 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));424 confirmEl = allPwInputs.find(425 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)426 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);427 }428429 currentDismiss?.();430 currentAnchorField = anchorField;431 currentDismiss = showAutofillSelector(432 anchorField,433 domainEntries,434 async (id: string) => {435 currentDismiss = null;436 currentAnchorField = null;437 const entryResponse = await chrome.runtime.sendMessage({438 type: "GET_ENTRY_FOR_FILL",439 payload: { id },440 });441 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;442 if (entry) {443 await handleAutofill(anchorField, usernameEl, passwordEl, entry);444 recordFillSuccess(anchorField, usernameEl, passwordEl);445 446 447 448 const pageDomain = location.hostname.replace(/^www\./, "");449 const entryDomains = new Set<string>();450 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {451 try {452 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));453 } catch { }454 }455 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {456 showRememberSiteToast(pageDomain, entry.id);457 }458 }459 },460 {461 domain,462 searchableEntries,463 isSignup,464 savedIdentities,465 onFillFields: (username, password) => {466 const form = passwordEl.closest("form") as HTMLFormElement | null;467 fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());468 if (password && confirmEl) setNativeValue(confirmEl, password);469 recordFillSuccess(anchorField, usernameEl, passwordEl);470 },471 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },472 }473 );474}475476477async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {478 const field = anchorField ?? getDeepActiveInput();479 if (!field) return;480 if (!isVisible(field)) return;481482 483 if (passkeyToastActive) return;484485 486 487 if (!canOpen()) return;488489 490 if (currentDismiss && currentAnchorField === field) return;491492 493 494 if (field !== lastDismissedField) lastDismissedField = null;495 496 497 if (field === lastDismissedField) return;498499 500 501 502 503 if (wasAlreadyFilled(field)) return;504505 506 507 if (pendingInteractions.has(field)) return;508 pendingInteractions.add(field);509510 try {511 const fieldType = field.type.toLowerCase();512513 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {514 return preds[0] ?? null;515 });516517 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {518 const timeout = setTimeout(() => resolve(null), 150);519 mlPromise.then((pred) => {520 clearTimeout(timeout);521 resolve(pred);522 });523 });524525 if (passkeyToastActive) return;526527 if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {528 return;529 }530531 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);532 if (autofillFieldType) {533 reattachListeners(field, autofillFieldType);534 }535536 let fields = detectLoginFields();537 const loginForm = isLoginForm(fields);538 const signupForm = isSignupForm(fields);539 if (!loginForm && !signupForm) {540 return;541 }542543 const domain = getPageDomain();544 const firstResult = await fetchAutofillEntries(domain);545 if (passkeyToastActive) return;546547 548 549 550 if (firstResult.locked) {551 currentDismiss?.();552 currentAnchorField = field;553 currentDismiss = showAutofillSelector(554 field,555 [],556 () => {},557 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }558 );559 return;560 }561562 const entries = firstResult.entries;563 const allEntries = entries.length === 0564 ? (await fetchAutofillEntries(domain, true)).entries565 : entries;566567 if (passkeyToastActive) return;568569 let usernameEl: HTMLInputElement | null = null;570 const userField = fields.find((f) => f.type === "username" || f.type === "email");571 if (userField) usernameEl = userField.el;572 const pwField = fields.find((f) => f.type === "password");573 if (!pwField) return;574 const passwordEl = pwField.el;575576 await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);577 } finally {578 pendingInteractions.delete(field);579 }580}581582async function onFocusIn(e: Event): Promise<void> {583 584 585 586 587 588 if (isSubmitButton(e.target)) return;589 await handleFieldInteraction();590}591592function reattachListeners(593 el: HTMLInputElement,594 detectedType?: "password" | "username" | "email",595 contextFields?: ReturnType<typeof detectLoginFields>596): void {597 if (processedInputs.has(el)) return;598 if (!resolveAutofillFieldType(el, detectedType)) return;599 600 const fields = contextFields ?? detectLoginFields();601 if (!isLoginForm(fields) && !isSignupForm(fields)) return;602603 const cleanup = injectFieldIcon(el, () => {604 currentDismiss?.();605 currentDismiss = null;606 lastDismissedField = null; 607 dismissLock = false; 608 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }609 clearFillStateForExplicitSummon(el);610 el.focus({ preventScroll: true });611 void handleFieldInteraction(el);612 });613 processedInputs.set(el, cleanup);614}615616const debouncedReattach = debounce(() => {617 const allFields = detectLoginFields();618 619 if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;620 const newFields = allFields.filter(621 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)622 );623 for (const f of newFields) {624 reattachListeners(f.el, f.type, allFields);625 }626 627 628 629}, 200);630631function setupMutationObserver(): void {632 const observer = new MutationObserver(debouncedReattach);633 observer.observe(document.body, {634 childList: true,635 subtree: true,636 attributes: true,637 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],638 });639}640641function initialScan(aggressionLevel = 0, isFinalPass = false) {642 const allFields = detectLoginFields();643 const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);644645 if (aggressionLevel === 0 && !hasKnownForm) return;646647 const newFields = allFields.filter(648 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)649 );650651 for (const f of newFields) {652 reattachListeners(f.el, f.type, allFields);653 }654655 656 657 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {658 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');659 for (const el of pwInputs) {660 if (isVisible(el) && !processedInputs.has(el)) {661 const cleanup = injectFieldIcon(el, () => {662 currentDismiss?.();663 currentDismiss = null;664 lastDismissedField = null;665 dismissLock = false;666 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }667 clearFillStateForExplicitSummon(el);668 el.focus({ preventScroll: true });669 void handleFieldInteraction(el);670 });671 processedInputs.set(el, cleanup);672 }673 }674 }675}676677document.addEventListener("focusin", onFocusIn);678679setupMutationObserver();680setupSaveDetection();681setupCardAutofill();682683684685686687688689690let lastObservedUrl = location.href;691new MutationObserver(() => {692 if (location.href !== lastObservedUrl) {693 lastObservedUrl = location.href;694 pageFilledAt = null;695 }696}).observe(document.body, { childList: true, subtree: false });697698699700(async () => {701 let aggressionLevel = 0;702 try {703 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });704 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;705 const domain = getPageDomain();706 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;707 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;708 } catch { }709710 setTimeout(() => initialScan(aggressionLevel, false), 0);711 setTimeout(() => initialScan(aggressionLevel, false), 500);712 setTimeout(() => initialScan(aggressionLevel, true), 1500);713})();714715716717718719720const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();721let currentCardDismiss: (() => void) | null = null;722let currentCardAnchor: HTMLInputElement | null = null;723let lastDismissedCardField: HTMLInputElement | null = null;724725async function fetchSavedCards(): Promise<CardSelectorEntry[]> {726 const resp = await chrome.runtime.sendMessage({727 type: "AUTOFILL_QUERY",728 payload: { domain: getPageDomain(), kind: "card" },729 }).catch(() => null);730 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;731 return r?.ok ? (r.data ?? []) : [];732}733734async function openCardSelector(anchor: HTMLInputElement): Promise<void> {735 if (!canOpen()) return;736 if (currentCardDismiss && currentCardAnchor === anchor) return;737 if (anchor === lastDismissedCardField) return;738 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;739 if (wasAlreadyFilled(anchor)) return;740741 const cards = await fetchSavedCards();742 if (cards.length === 0) return; 743744 const cardForm = detectCardForm();745 if (!cardForm?.number) return;746747 currentCardDismiss?.();748 currentCardAnchor = anchor;749 currentCardDismiss = showCardSelector(750 anchor,751 cards,752 {753 domain: getPageDomain(),754 onFill: (entry) => {755 if (!cardForm) return;756 fillCardForm(cardForm, {757 cardNumber: entry.cardNumber ?? "",758 expMonth: entry.expMonth ?? "",759 expYear: entry.expYear ?? "",760 cvc: entry.cvc ?? "",761 cardholderName: entry.cardholderName ?? "",762 });763 764 765 766 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);767 currentCardDismiss = null;768 currentCardAnchor = null;769 },770 onDismiss: () => {771 lastDismissedCardField = anchor;772 startDismissLock();773 currentCardDismiss = null;774 currentCardAnchor = null;775 },776 }777 );778}779780function injectCardIcon(field: HTMLInputElement): void {781 if (processedCardInputs.has(field)) return;782 const cleanup = injectFieldIcon(field, () => {783 currentCardDismiss?.();784 currentCardDismiss = null;785 lastDismissedCardField = null;786 dismissLock = false;787 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }788 clearFillStateForExplicitSummon(field);789 field.focus({ preventScroll: true });790 void openCardSelector(field);791 });792 processedCardInputs.set(field, cleanup);793}794795function setupCardAutofill(): void {796 function scan() {797 const cardForm = detectCardForm();798 if (!cardForm?.number) return;799 if (!isVisible(cardForm.number)) return;800 injectCardIcon(cardForm.number);801 }802803 804 805 setTimeout(scan, 0);806 setTimeout(scan, 500);807 setTimeout(scan, 1500);808809 810 811 812 let pending = false;813 new MutationObserver(() => {814 if (pending) return;815 pending = true;816 setTimeout(() => { pending = false; scan(); }, 200);817 }).observe(document.body, { childList: true, subtree: true });818819 820 821 822 document.addEventListener("focusin", (e) => {823 const target = e.target;824 if (!(target instanceof HTMLInputElement)) return;825 const cardForm = detectCardForm();826 if (cardForm?.number === target) {827 injectCardIcon(target);828 }829 }, true);830}831832chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {833 834 if (sender.id !== chrome.runtime.id) return;835 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {836 const policy = detectPasswordPolicy();837 sendResponse({ ok: true, data: policy });838 return true;839 }840 if (msg?.type === "PING") {841 sendResponse({ ok: true });842 return true;843 }844 if (msg?.type === "SUMMON_AUTOFILL") {845 const source = (msg as { type: string; source?: string }).source;846 const isShortcut = source === "shortcut";847 const isPasskeyUnlock = source === "passkey-unlock";848849 const activeInput = getDeepActiveInput();850 const fields = detectLoginFields();851 const hasForm = isLoginForm(fields) || isSignupForm(fields);852853 if (hasForm) {854 855 856 const inForm = activeInput && fields.some(f => f.el === activeInput);857 const target = inForm858 ? activeInput859 : (fields.find(f => f.type === "password")?.el860 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);861 if (target) {862 863 864 clearFillStateForExplicitSummon(target);865 dismissLock = false;866 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }867 lastDismissedField = null;868 void handleFieldInteraction(target);869 }870 } else if (isPasskeyUnlock) {871 872 873 874 const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)875 ? document.activeElement as unknown as HTMLInputElement876 : null;877 if (anchor) {878 currentDismiss?.();879 currentAnchorField = null;880 passkeySummonActive = true;881 currentDismiss = showAutofillSelector(anchor, [], () => {}, {882 domain: getPageDomain(),883 locked: true,884 onDismiss: () => { passkeySummonActive = false; },885 });886 }887 } else if (isShortcut) {888 889 showSearchPalette();890 }891892 893 if (isShortcut) {894 const domain = getPageDomain();895 if (domain) {896 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});897 }898 }899900 sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });901 return true;902 }903 if (msg?.type === "PASSKEY_PRO_GATE") {904 905 906 showPasskeyProGate();907 sendResponse({ ok: true });908 return true;909 }910 if (msg?.type === "SHOW_PASSKEY_TOAST") {911 912 passkeyToastActive = true;913 if (currentDismiss) {914 currentDismiss();915 currentDismiss = null;916 currentAnchorField = null;917 }918 return false; 919 }920 if (msg?.type === "DISMISS_PASSKEY_TOAST") {921 passkeyToastActive = false;922 return false; 923 }924 if (msg?.type === "VAULT_UNLOCKED") {925 if (passkeySummonActive) {926 927 928 passkeySummonActive = false;929 if (currentDismiss) {930 currentDismiss();931 currentDismiss = null;932 currentAnchorField = null;933 }934 sendResponse({ ok: true });935 return true;936 }937 938 939 const savedField = currentAnchorField;940 if (currentDismiss) {941 currentDismiss();942 currentDismiss = null;943 currentAnchorField = null;944 }945 void handleFieldInteraction(savedField ?? undefined);946 sendResponse({ ok: true });947 return true;948 }949 return true;950});951952953954window.addEventListener("message", (e: MessageEvent) => {955 const d = e.data as { source?: string; type?: string } | undefined;956 if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {957 passkeyToastActive = false;958 }959});960961962963964965966967968969970971972if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {973 let lastPasskeyOfferAt = 0;974 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;975976 window.addEventListener("message", (event: MessageEvent) => {977 if (event.source !== window) return;978 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;979 if (!data || data.source !== "peach-passkey-firefox") return;980 if (detectBrowser() !== "firefox") return;981 if (data.type !== "create") return;982983 984 985 const now = Date.now();986 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;987 lastPasskeyOfferAt = now;988989 const domain = location.hostname.replace(/^www\./, "");990 chrome.runtime.sendMessage({991 type: "GET_PASSKEY_OFFER_DECLINED",992 payload: { domain },993 }).then((res: { ok: boolean; data?: boolean } | undefined) => {994 if (res?.data === true) return;995 const rpId = data.rpId ?? domain;996 showPasskeyRegistrationOffer({997 rpId,998 rpName: data.rpName,999 userName: data.userName,1000 userDisplayName: data.userDisplayName,1001 });1002 }).catch(() => {});1003 });1004}100510061007100810091010101110121013101410151016101710181019{1020 function checkPasskeyAvailability() {1021 const domain = location.hostname.replace(/^www\./, "");1022 if (!domain) return;1023 const sessionKey = `peach_state11_shown:${domain}`;1024 chrome.storage.session?.get(sessionKey).then((stored) => {1025 if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1026 chrome.runtime.sendMessage({1027 type: "GET_PASSKEY_FOR_DOMAIN",1028 payload: { domain },1029 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1030 const data = res?.data;1031 if (!data) return;1032 const current = detectBrowser();1033 const isCrossBrowser =1034 data.browser && current !== "unknown" && data.browser !== current;1035 const valuableOnFirefox = current === "firefox";1036 if (!isCrossBrowser && !valuableOnFirefox) return;1037 chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1038 showPasskeyAvailable({1039 rpId: data.rpId,1040 userName: data.userName,1041 fromBrowser: data.browser,1042 currentBrowser: current,1043 });1044 }).catch(() => {});1045 }).catch(() => {});1046 }10471048 1049 1050 1051 if (document.readyState === "loading") {1052 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1053 } else {1054 setTimeout(checkPasskeyAvailability, 800);1055 }1056}