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 setNativeValue(el: HTMLInputElement, value: string): void {279 const nativeSetter = Object.getOwnPropertyDescriptor(280 HTMLInputElement.prototype, "value"281 )!.set!;282 nativeSetter.call(el, value);283 el.dispatchEvent(new Event("input", { bubbles: true }));284 el.dispatchEvent(new Event("change", { bubbles: true }));285}286287function findTOTPField(): HTMLInputElement | null {288 const inputs = document.querySelectorAll<HTMLInputElement>("input");289 for (const input of inputs) {290 if (!isVisible(input)) continue;291 const autocomplete = input.autocomplete.toLowerCase();292 const nameId = (input.name + input.id).toLowerCase();293 const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();294 if (295 autocomplete === "one-time-code" ||296 /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)297 ) {298 return input;299 }300 const labelEl = input.closest("label");301 if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {302 return input;303 }304 }305 return null;306}307308async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {309 await new Promise((r) => setTimeout(r, 400));310 if (totpField.value === "" || totpField.value.trim() === "") {311 const { code } = generateTOTP(totpSecret);312 setNativeValue(totpField, code);313 showToast("TOTP autofilled");314 }315}316317318async function handleAutofill(319 field: HTMLInputElement,320 usernameEl: HTMLInputElement | null,321 passwordEl: HTMLInputElement,322 entry: VaultEntry323): Promise<void> {324 if (!entry.username && !entry.password) return;325 const pageDomain = getPageDomain();326 const form = passwordEl.closest("form") as HTMLFormElement | null;327 fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);328329 if (entry.canary) {330 chrome.runtime.sendMessage({331 type: "FIRE_CANARY_PING",332 payload: {333 webhookUrl: entry.canary.webhookUrl,334 entryTitle: entry.title,335 trigger: "autofilled",336 },337 }).catch(() => {});338 chrome.runtime.sendMessage({339 type: "UPDATE_ENTRY",340 payload: {341 id: entry.id,342 patch: {343 canary: {344 ...entry.canary,345 lastPinged: Date.now(),346 pingCount: (entry.canary.pingCount ?? 0) + 1,347 },348 },349 },350 }).catch(() => {});351 }352353 if (entry.totp) {354 const { code } = generateTOTP(entry.totp);355 let alreadyWritten = false;356 try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}357 const response = await chrome.runtime.sendMessage({358 type: "COPY",359 payload: { text: code, label: "TOTP", alreadyWritten },360 });361 if (alreadyWritten || (response as { ok?: boolean }).ok) {362 showToast("TOTP copied · " + code);363 }364 const totpField = findTOTPField();365 if (totpField) {366 autofillTOTP(totpField, entry.totp);367 }368 }369}370371async function fetchAutofillEntries(372 domain: string,373 includeAll = false374): Promise<{ entries: SelectorEntry[]; locked: boolean }> {375 const response = await chrome.runtime.sendMessage({376 type: "AUTOFILL_QUERY",377 payload: { domain, includeAll },378 });379 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };380 if (!res.ok && res.error === "VAULT_LOCKED") {381 return { entries: [], locked: true };382 }383 return { entries: res.data ?? [], locked: false };384}385386387function resolveAutofillFieldType(388 el: HTMLInputElement,389 predictedType?: FieldPrediction["type"] | null390): "password" | "username" | "email" | null {391 if (392 predictedType === "password" ||393 predictedType === "username" ||394 predictedType === "email"395 ) {396 return predictedType;397 }398399 const detected = detectLoginFields().find((field) => field.el === el)?.type;400 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {401 return detected;402 }403404 const htmlType = el.type.toLowerCase();405 if (htmlType === "password") return "password";406 if (htmlType === "email") return "email";407 return null;408}409410async function openAutofillSelector(411 anchorField: HTMLInputElement,412 usernameEl: HTMLInputElement | null,413 passwordEl: HTMLInputElement,414 domainEntries: SelectorEntry[],415 searchableEntries: SelectorEntry[],416 domain: string417): Promise<void> {418 419 420 421 const isSignup = domainEntries.length === 0;422 let savedIdentities: SavedIdentity[] | undefined;423 let confirmEl: HTMLInputElement | null = null;424 if (isSignup) {425 try {426 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as427 { ok: boolean; data?: SavedIdentity[] } | null;428 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;429 } catch { }430431 const form = passwordEl.closest("form") ?? document.body;432 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));433 confirmEl = allPwInputs.find(434 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)435 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);436 }437438 currentDismiss?.();439 currentAnchorField = anchorField;440 currentDismiss = showAutofillSelector(441 anchorField,442 domainEntries,443 async (id: string) => {444 currentDismiss = null;445 currentAnchorField = null;446 const entryResponse = await chrome.runtime.sendMessage({447 type: "GET_ENTRY_FOR_FILL",448 payload: { id },449 });450 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;451 if (entry) {452 await handleAutofill(anchorField, usernameEl, passwordEl, entry);453 recordFillSuccess(anchorField, usernameEl, passwordEl);454 455 456 457 const pageDomain = location.hostname.replace(/^www\./, "");458 const entryDomains = new Set<string>();459 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {460 try {461 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));462 } catch { }463 }464 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {465 showRememberSiteToast(pageDomain, entry.id);466 }467 }468 },469 {470 domain,471 searchableEntries,472 isSignup,473 savedIdentities,474 onFillFields: (username, password) => {475 const form = passwordEl.closest("form") as HTMLFormElement | null;476 fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());477 if (password && confirmEl) setNativeValue(confirmEl, password);478 recordFillSuccess(anchorField, usernameEl, passwordEl);479 },480 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },481 }482 );483}484485486async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {487 const field = anchorField ?? getDeepActiveInput();488 if (!field) return;489 if (!isVisible(field)) return;490491 492 if (passkeyToastActive) return;493494 495 496 if (!canOpen()) return;497498 499 if (currentDismiss && currentAnchorField === field) return;500501 502 503 if (field !== lastDismissedField) lastDismissedField = null;504 505 506 if (field === lastDismissedField) return;507508 509 510 511 512 if (wasAlreadyFilled(field)) return;513514 515 516 if (pendingInteractions.has(field)) return;517 pendingInteractions.add(field);518519 try {520 const fieldType = field.type.toLowerCase();521522 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {523 return preds[0] ?? null;524 });525526 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {527 const timeout = setTimeout(() => resolve(null), 150);528 mlPromise.then((pred) => {529 clearTimeout(timeout);530 resolve(pred);531 });532 });533534 if (passkeyToastActive) return;535536 if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {537 return;538 }539540 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);541 if (autofillFieldType) {542 reattachListeners(field, autofillFieldType);543 }544545 let fields = detectLoginFields();546 const loginForm = isLoginForm(fields);547 const signupForm = isSignupForm(fields);548 if (!loginForm && !signupForm) {549 return;550 }551552 const domain = getPageDomain();553 const firstResult = await fetchAutofillEntries(domain);554 if (passkeyToastActive) return;555556 557 558 559 if (firstResult.locked) {560 currentDismiss?.();561 currentAnchorField = field;562 currentDismiss = showAutofillSelector(563 field,564 [],565 () => {},566 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }567 );568 return;569 }570571 const entries = firstResult.entries;572 const allEntries = entries.length === 0573 ? (await fetchAutofillEntries(domain, true)).entries574 : entries;575576 if (passkeyToastActive) return;577578 let usernameEl: HTMLInputElement | null = null;579 const userField = fields.find((f) => f.type === "username" || f.type === "email");580 if (userField) usernameEl = userField.el;581 const pwField = fields.find((f) => f.type === "password");582 if (!pwField) return;583 const passwordEl = pwField.el;584585 await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);586 } finally {587 pendingInteractions.delete(field);588 }589}590591async function onFocusIn(e: Event): Promise<void> {592 593 594 595 596 597 if (isSubmitButton(e.target)) return;598 await handleFieldInteraction();599}600601function reattachListeners(602 el: HTMLInputElement,603 detectedType?: "password" | "username" | "email",604 contextFields?: ReturnType<typeof detectLoginFields>605): void {606 if (processedInputs.has(el)) return;607 if (!resolveAutofillFieldType(el, detectedType)) return;608 609 const fields = contextFields ?? detectLoginFields();610 if (!isLoginForm(fields) && !isSignupForm(fields)) return;611612 const cleanup = injectFieldIcon(el, () => {613 currentDismiss?.();614 currentDismiss = null;615 lastDismissedField = null; 616 dismissLock = false; 617 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }618 clearFillStateForExplicitSummon(el);619 el.focus({ preventScroll: true });620 void handleFieldInteraction(el);621 });622 processedInputs.set(el, cleanup);623}624625const debouncedReattach = debounce(() => {626 const allFields = detectLoginFields();627 628 if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;629 const newFields = allFields.filter(630 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)631 );632 for (const f of newFields) {633 reattachListeners(f.el, f.type, allFields);634 }635 636 637 638}, 200);639640function setupMutationObserver(): void {641 const observer = new MutationObserver(debouncedReattach);642 observer.observe(document.body, {643 childList: true,644 subtree: true,645 attributes: true,646 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],647 });648}649650function initialScan(aggressionLevel = 0, isFinalPass = false) {651 const allFields = detectLoginFields();652 const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);653654 if (aggressionLevel === 0 && !hasKnownForm) return;655656 const newFields = allFields.filter(657 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)658 );659660 for (const f of newFields) {661 reattachListeners(f.el, f.type, allFields);662 }663664 665 666 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {667 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');668 for (const el of pwInputs) {669 if (isVisible(el) && !processedInputs.has(el)) {670 const cleanup = injectFieldIcon(el, () => {671 currentDismiss?.();672 currentDismiss = null;673 lastDismissedField = null;674 dismissLock = false;675 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }676 clearFillStateForExplicitSummon(el);677 el.focus({ preventScroll: true });678 void handleFieldInteraction(el);679 });680 processedInputs.set(el, cleanup);681 }682 }683 }684}685686document.addEventListener("focusin", onFocusIn);687688setupMutationObserver();689setupSaveDetection();690setupCardAutofill();691692693694695696697698699let lastObservedUrl = location.href;700new MutationObserver(() => {701 if (location.href !== lastObservedUrl) {702 lastObservedUrl = location.href;703 pageFilledAt = null;704 }705}).observe(document.body, { childList: true, subtree: false });706707708709(async () => {710 let aggressionLevel = 0;711 try {712 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });713 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;714 const domain = getPageDomain();715 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;716 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;717 } catch { }718719 setTimeout(() => initialScan(aggressionLevel, false), 0);720 setTimeout(() => initialScan(aggressionLevel, false), 500);721 setTimeout(() => initialScan(aggressionLevel, true), 1500);722})();723724725726727728729const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();730let currentCardDismiss: (() => void) | null = null;731let currentCardAnchor: HTMLInputElement | null = null;732let lastDismissedCardField: HTMLInputElement | null = null;733734async function fetchSavedCards(): Promise<CardSelectorEntry[]> {735 const resp = await chrome.runtime.sendMessage({736 type: "AUTOFILL_QUERY",737 payload: { domain: getPageDomain(), kind: "card" },738 }).catch(() => null);739 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;740 return r?.ok ? (r.data ?? []) : [];741}742743async function openCardSelector(anchor: HTMLInputElement): Promise<void> {744 if (!canOpen()) return;745 if (currentCardDismiss && currentCardAnchor === anchor) return;746 if (anchor === lastDismissedCardField) return;747 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;748 if (wasAlreadyFilled(anchor)) return;749750 const cards = await fetchSavedCards();751 if (cards.length === 0) return; 752753 const cardForm = detectCardForm();754 if (!cardForm?.number) return;755756 currentCardDismiss?.();757 currentCardAnchor = anchor;758 currentCardDismiss = showCardSelector(759 anchor,760 cards,761 {762 domain: getPageDomain(),763 onFill: (entry) => {764 if (!cardForm) return;765 fillCardForm(cardForm, {766 cardNumber: entry.cardNumber ?? "",767 expMonth: entry.expMonth ?? "",768 expYear: entry.expYear ?? "",769 cvc: entry.cvc ?? "",770 cardholderName: entry.cardholderName ?? "",771 });772 773 774 775 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);776 currentCardDismiss = null;777 currentCardAnchor = null;778 },779 onDismiss: () => {780 lastDismissedCardField = anchor;781 startDismissLock();782 currentCardDismiss = null;783 currentCardAnchor = null;784 },785 }786 );787}788789function injectCardIcon(field: HTMLInputElement): void {790 if (processedCardInputs.has(field)) return;791 const cleanup = injectFieldIcon(field, () => {792 currentCardDismiss?.();793 currentCardDismiss = null;794 lastDismissedCardField = null;795 dismissLock = false;796 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }797 clearFillStateForExplicitSummon(field);798 field.focus({ preventScroll: true });799 void openCardSelector(field);800 });801 processedCardInputs.set(field, cleanup);802}803804function setupCardAutofill(): void {805 function scan() {806 const cardForm = detectCardForm();807 if (!cardForm?.number) return;808 if (!isVisible(cardForm.number)) return;809 injectCardIcon(cardForm.number);810 }811812 813 814 setTimeout(scan, 0);815 setTimeout(scan, 500);816 setTimeout(scan, 1500);817818 819 820 821 let pending = false;822 new MutationObserver(() => {823 if (pending) return;824 pending = true;825 setTimeout(() => { pending = false; scan(); }, 200);826 }).observe(document.body, { childList: true, subtree: true });827828 829 830 831 document.addEventListener("focusin", (e) => {832 const target = e.target;833 if (!(target instanceof HTMLInputElement)) return;834 const cardForm = detectCardForm();835 if (cardForm?.number === target) {836 injectCardIcon(target);837 }838 }, true);839}840841chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {842 843 if (sender.id !== chrome.runtime.id) return;844 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {845 const policy = detectPasswordPolicy();846 sendResponse({ ok: true, data: policy });847 return true;848 }849 if (msg?.type === "PING") {850 sendResponse({ ok: true });851 return true;852 }853 if (msg?.type === "SUMMON_AUTOFILL") {854 const source = (msg as { type: string; source?: string }).source;855 const isShortcut = source === "shortcut";856 const isPasskeyUnlock = source === "passkey-unlock";857858 const activeInput = getDeepActiveInput();859 const fields = detectLoginFields();860 const hasForm = isLoginForm(fields) || isSignupForm(fields);861862 if (hasForm) {863 864 865 const inForm = activeInput && fields.some(f => f.el === activeInput);866 const target = inForm867 ? activeInput868 : (fields.find(f => f.type === "password")?.el869 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);870 if (target) {871 872 873 clearFillStateForExplicitSummon(target);874 dismissLock = false;875 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }876 lastDismissedField = null;877 void handleFieldInteraction(target);878 }879 } else if (isPasskeyUnlock) {880 881 882 883 const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)884 ? document.activeElement as unknown as HTMLInputElement885 : null;886 if (anchor) {887 currentDismiss?.();888 currentAnchorField = null;889 passkeySummonActive = true;890 currentDismiss = showAutofillSelector(anchor, [], () => {}, {891 domain: getPageDomain(),892 locked: true,893 onDismiss: () => { passkeySummonActive = false; },894 });895 }896 } else if (isShortcut) {897 898 showSearchPalette();899 }900901 902 if (isShortcut) {903 const domain = getPageDomain();904 if (domain) {905 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});906 }907 }908909 sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });910 return true;911 }912 if (msg?.type === "PASSKEY_PRO_GATE") {913 914 915 showPasskeyProGate();916 sendResponse({ ok: true });917 return true;918 }919 if (msg?.type === "SHOW_PASSKEY_TOAST") {920 921 passkeyToastActive = true;922 if (currentDismiss) {923 currentDismiss();924 currentDismiss = null;925 currentAnchorField = null;926 }927 return false; 928 }929 if (msg?.type === "DISMISS_PASSKEY_TOAST") {930 passkeyToastActive = false;931 return false; 932 }933 if (msg?.type === "VAULT_UNLOCKED") {934 if (passkeySummonActive) {935 936 937 passkeySummonActive = false;938 if (currentDismiss) {939 currentDismiss();940 currentDismiss = null;941 currentAnchorField = null;942 }943 sendResponse({ ok: true });944 return true;945 }946 947 948 const savedField = currentAnchorField;949 if (currentDismiss) {950 currentDismiss();951 currentDismiss = null;952 currentAnchorField = null;953 }954 void handleFieldInteraction(savedField ?? undefined);955 sendResponse({ ok: true });956 return true;957 }958 return true;959});960961962963window.addEventListener("message", (e: MessageEvent) => {964 const d = e.data as { source?: string; type?: string } | undefined;965 if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {966 passkeyToastActive = false;967 }968});969970971972973974975976977978979980981if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {982 let lastPasskeyOfferAt = 0;983 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;984985 window.addEventListener("message", (event: MessageEvent) => {986 if (event.source !== window) return;987 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;988 if (!data || data.source !== "peach-passkey-firefox") return;989 if (detectBrowser() !== "firefox") return;990 if (data.type !== "create") return;991992 993 994 const now = Date.now();995 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;996 lastPasskeyOfferAt = now;997998 const domain = location.hostname.replace(/^www\./, "");999 chrome.runtime.sendMessage({1000 type: "GET_PASSKEY_OFFER_DECLINED",1001 payload: { domain },1002 }).then((res: { ok: boolean; data?: boolean } | undefined) => {1003 if (res?.data === true) return;1004 const rpId = data.rpId ?? domain;1005 showPasskeyRegistrationOffer({1006 rpId,1007 rpName: data.rpName,1008 userName: data.userName,1009 userDisplayName: data.userDisplayName,1010 });1011 }).catch(() => {});1012 });1013}101410151016101710181019102010211022102310241025102610271028{1029 function checkPasskeyAvailability() {1030 const domain = location.hostname.replace(/^www\./, "");1031 if (!domain) return;1032 const sessionKey = `peach_state11_shown:${domain}`;1033 chrome.storage.session?.get(sessionKey).then((stored) => {1034 if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1035 chrome.runtime.sendMessage({1036 type: "GET_PASSKEY_FOR_DOMAIN",1037 payload: { domain },1038 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1039 const data = res?.data;1040 if (!data) return;1041 const current = detectBrowser();1042 const isCrossBrowser =1043 data.browser && current !== "unknown" && data.browser !== current;1044 const valuableOnFirefox = current === "firefox";1045 if (!isCrossBrowser && !valuableOnFirefox) return;1046 chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1047 showPasskeyAvailable({1048 rpId: data.rpId,1049 userName: data.userName,1050 fromBrowser: data.browser,1051 currentBrowser: current,1052 });1053 }).catch(() => {});1054 }).catch(() => {});1055 }10561057 1058 1059 1060 if (document.readyState === "loading") {1061 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1062 } else {1063 setTimeout(checkPasskeyAvailability, 800);1064 }1065}