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 {253 await navigator.clipboard.writeText(r.data.password);254 alreadyWritten = true;255 } catch (err) {256 console.warn("[Peach] clipboard write denied:", err);257 }258 const copyResp = await chrome.runtime.sendMessage({259 type: "COPY",260 payload: { text: r.data.password, label: "Password", alreadyWritten },261 }) as { ok?: boolean } | undefined;262 if (alreadyWritten || copyResp?.ok) {263 showToast("Password copied");264 } else {265 showToast("Could not copy password — clipboard blocked");266 }267 } else {268 showToast("Could not copy password");269 }270 close();271 document.removeEventListener("keydown", onKeyDown, true);272 };273 list.appendChild(row);274 }275 }276277 searchInput.oninput = () => { query = searchInput.value; render(); };278279 fetchAutofillEntries(getPageDomain(), true).then(result => {280 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }281 allEntries = result.entries;282 render();283 searchInput.focus();284 });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 {357 await navigator.clipboard.writeText(code);358 alreadyWritten = true;359 } catch (err) {360 console.warn("[Peach] clipboard write denied:", err);361 }362 const response = await chrome.runtime.sendMessage({363 type: "COPY",364 payload: { text: code, label: "TOTP", alreadyWritten },365 });366 if (alreadyWritten || (response as { ok?: boolean }).ok) {367 showToast("TOTP copied · " + code);368 } else {369 showToast("Could not copy TOTP — clipboard blocked");370 }371 const totpField = findTOTPField();372 if (totpField) {373 autofillTOTP(totpField, entry.totp);374 }375 }376}377378async function fetchAutofillEntries(379 domain: string,380 includeAll = false381): Promise<{ entries: SelectorEntry[]; locked: boolean }> {382 const response = await chrome.runtime.sendMessage({383 type: "AUTOFILL_QUERY",384 payload: { domain, includeAll },385 });386 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };387 if (!res.ok && res.error === "VAULT_LOCKED") {388 return { entries: [], locked: true };389 }390 return { entries: res.data ?? [], locked: false };391}392393394function resolveAutofillFieldType(395 el: HTMLInputElement,396 predictedType?: FieldPrediction["type"] | null397): "password" | "username" | "email" | null {398 if (399 predictedType === "password" ||400 predictedType === "username" ||401 predictedType === "email"402 ) {403 return predictedType;404 }405406 const detected = detectLoginFields().find((field) => field.el === el)?.type;407 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {408 return detected;409 }410411 const htmlType = el.type.toLowerCase();412 if (htmlType === "password") return "password";413 if (htmlType === "email") return "email";414 return null;415}416417async function openAutofillSelector(418 anchorField: HTMLInputElement,419 usernameEl: HTMLInputElement | null,420 passwordEl: HTMLInputElement,421 domainEntries: SelectorEntry[],422 searchableEntries: SelectorEntry[],423 domain: string424): Promise<void> {425 426 427 428 const isSignup = domainEntries.length === 0;429 let savedIdentities: SavedIdentity[] | undefined;430 let confirmEl: HTMLInputElement | null = null;431 if (isSignup) {432 try {433 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as434 { ok: boolean; data?: SavedIdentity[] } | null;435 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;436 } catch { }437438 const form = passwordEl.closest("form") ?? document.body;439 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));440 confirmEl = allPwInputs.find(441 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)442 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);443 }444445 currentDismiss?.();446 currentAnchorField = anchorField;447 currentDismiss = showAutofillSelector(448 anchorField,449 domainEntries,450 async (id: string) => {451 currentDismiss = null;452 currentAnchorField = null;453 const entryResponse = await chrome.runtime.sendMessage({454 type: "GET_ENTRY_FOR_FILL",455 payload: { id },456 });457 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;458 if (entry) {459 await handleAutofill(anchorField, usernameEl, passwordEl, entry);460 recordFillSuccess(anchorField, usernameEl, passwordEl);461 462 463 464 const pageDomain = location.hostname.replace(/^www\./, "");465 const entryDomains = new Set<string>();466 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {467 try {468 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));469 } catch { }470 }471 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {472 showRememberSiteToast(pageDomain, entry.id);473 }474 }475 },476 {477 domain,478 searchableEntries,479 isSignup,480 savedIdentities,481 onFillFields: (username, password) => {482 const form = passwordEl.closest("form") as HTMLFormElement | null;483 fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());484 if (password && confirmEl) setNativeValue(confirmEl, password);485 recordFillSuccess(anchorField, usernameEl, passwordEl);486 },487 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },488 }489 );490}491492493async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {494 const field = anchorField ?? getDeepActiveInput();495 if (!field) return;496 if (!isVisible(field)) return;497498 499 if (passkeyToastActive) return;500501 502 503 if (!canOpen()) return;504505 506 if (currentDismiss && currentAnchorField === field) return;507508 509 510 if (field !== lastDismissedField) lastDismissedField = null;511 512 513 if (field === lastDismissedField) return;514515 516 517 518 519 if (wasAlreadyFilled(field)) return;520521 522 523 if (pendingInteractions.has(field)) return;524 pendingInteractions.add(field);525526 try {527 const fieldType = field.type.toLowerCase();528529 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {530 return preds[0] ?? null;531 });532533 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {534 const timeout = setTimeout(() => resolve(null), 150);535 mlPromise.then((pred) => {536 clearTimeout(timeout);537 resolve(pred);538 });539 });540541 if (passkeyToastActive) return;542543 if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {544 return;545 }546547 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);548 if (autofillFieldType) {549 reattachListeners(field, autofillFieldType);550 }551552 let fields = detectLoginFields();553 const loginForm = isLoginForm(fields);554 const signupForm = isSignupForm(fields);555 if (!loginForm && !signupForm) {556 return;557 }558559 const domain = getPageDomain();560 const firstResult = await fetchAutofillEntries(domain);561 if (passkeyToastActive) return;562563 564 565 566 if (firstResult.locked) {567 currentDismiss?.();568 currentAnchorField = field;569 currentDismiss = showAutofillSelector(570 field,571 [],572 () => {},573 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }574 );575 return;576 }577578 const entries = firstResult.entries;579 const allEntries = entries.length === 0580 ? (await fetchAutofillEntries(domain, true)).entries581 : entries;582583 if (passkeyToastActive) return;584585 let usernameEl: HTMLInputElement | null = null;586 const userField = fields.find((f) => f.type === "username" || f.type === "email");587 if (userField) usernameEl = userField.el;588 const pwField = fields.find((f) => f.type === "password");589 if (!pwField) return;590 const passwordEl = pwField.el;591592 await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);593 } finally {594 pendingInteractions.delete(field);595 }596}597598async function onFocusIn(e: Event): Promise<void> {599 600 601 602 603 604 if (isSubmitButton(e.target)) return;605 await handleFieldInteraction();606}607608function reattachListeners(609 el: HTMLInputElement,610 detectedType?: "password" | "username" | "email",611 contextFields?: ReturnType<typeof detectLoginFields>612): void {613 if (processedInputs.has(el)) return;614 if (!resolveAutofillFieldType(el, detectedType)) return;615 616 const fields = contextFields ?? detectLoginFields();617 if (!isLoginForm(fields) && !isSignupForm(fields)) return;618619 const cleanup = injectFieldIcon(el, () => {620 currentDismiss?.();621 currentDismiss = null;622 lastDismissedField = null; 623 dismissLock = false; 624 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }625 clearFillStateForExplicitSummon(el);626 el.focus({ preventScroll: true });627 void handleFieldInteraction(el);628 });629 processedInputs.set(el, cleanup);630}631632const debouncedReattach = debounce(() => {633 const allFields = detectLoginFields();634 635 if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;636 const newFields = allFields.filter(637 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)638 );639 for (const f of newFields) {640 reattachListeners(f.el, f.type, allFields);641 }642 643 644 645}, 200);646647function setupMutationObserver(): void {648 const observer = new MutationObserver(debouncedReattach);649 observer.observe(document.body, {650 childList: true,651 subtree: true,652 attributes: true,653 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],654 });655}656657function initialScan(aggressionLevel = 0, isFinalPass = false) {658 const allFields = detectLoginFields();659 const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);660661 if (aggressionLevel === 0 && !hasKnownForm) return;662663 const newFields = allFields.filter(664 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)665 );666667 for (const f of newFields) {668 reattachListeners(f.el, f.type, allFields);669 }670671 672 673 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {674 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');675 for (const el of pwInputs) {676 if (isVisible(el) && !processedInputs.has(el)) {677 const cleanup = injectFieldIcon(el, () => {678 currentDismiss?.();679 currentDismiss = null;680 lastDismissedField = null;681 dismissLock = false;682 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }683 clearFillStateForExplicitSummon(el);684 el.focus({ preventScroll: true });685 void handleFieldInteraction(el);686 });687 processedInputs.set(el, cleanup);688 }689 }690 }691}692693document.addEventListener("focusin", onFocusIn);694695setupMutationObserver();696setupSaveDetection();697setupCardAutofill();698699700701702703704705706let lastObservedUrl = location.href;707new MutationObserver(() => {708 if (location.href !== lastObservedUrl) {709 lastObservedUrl = location.href;710 pageFilledAt = null;711 }712}).observe(document.body, { childList: true, subtree: false });713714715716(async () => {717 let aggressionLevel = 0;718 try {719 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });720 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;721 const domain = getPageDomain();722 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;723 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;724 } catch { }725726 setTimeout(() => initialScan(aggressionLevel, false), 0);727 setTimeout(() => initialScan(aggressionLevel, false), 500);728 setTimeout(() => initialScan(aggressionLevel, true), 1500);729})();730731732733734735736const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();737let currentCardDismiss: (() => void) | null = null;738let currentCardAnchor: HTMLInputElement | null = null;739let lastDismissedCardField: HTMLInputElement | null = null;740741async function fetchSavedCards(): Promise<CardSelectorEntry[]> {742 const resp = await chrome.runtime.sendMessage({743 type: "AUTOFILL_QUERY",744 payload: { domain: getPageDomain(), kind: "card" },745 }).catch(() => null);746 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;747 return r?.ok ? (r.data ?? []) : [];748}749750async function openCardSelector(anchor: HTMLInputElement): Promise<void> {751 if (!canOpen()) return;752 if (currentCardDismiss && currentCardAnchor === anchor) return;753 if (anchor === lastDismissedCardField) return;754 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;755 if (wasAlreadyFilled(anchor)) return;756757 const cards = await fetchSavedCards();758 if (cards.length === 0) return; 759760 const cardForm = detectCardForm();761 if (!cardForm?.number) return;762763 currentCardDismiss?.();764 currentCardAnchor = anchor;765 currentCardDismiss = showCardSelector(766 anchor,767 cards,768 {769 domain: getPageDomain(),770 onFill: (entry) => {771 if (!cardForm) return;772 fillCardForm(cardForm, {773 cardNumber: entry.cardNumber ?? "",774 expMonth: entry.expMonth ?? "",775 expYear: entry.expYear ?? "",776 cvc: entry.cvc ?? "",777 cardholderName: entry.cardholderName ?? "",778 });779 780 781 782 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);783 currentCardDismiss = null;784 currentCardAnchor = null;785 },786 onDismiss: () => {787 lastDismissedCardField = anchor;788 startDismissLock();789 currentCardDismiss = null;790 currentCardAnchor = null;791 },792 }793 );794}795796function injectCardIcon(field: HTMLInputElement): void {797 if (processedCardInputs.has(field)) return;798 const cleanup = injectFieldIcon(field, () => {799 currentCardDismiss?.();800 currentCardDismiss = null;801 lastDismissedCardField = null;802 dismissLock = false;803 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }804 clearFillStateForExplicitSummon(field);805 field.focus({ preventScroll: true });806 void openCardSelector(field);807 });808 processedCardInputs.set(field, cleanup);809}810811function setupCardAutofill(): void {812 function scan() {813 const cardForm = detectCardForm();814 if (!cardForm?.number) return;815 if (!isVisible(cardForm.number)) return;816 injectCardIcon(cardForm.number);817 }818819 820 821 setTimeout(scan, 0);822 setTimeout(scan, 500);823 setTimeout(scan, 1500);824825 826 827 828 let pending = false;829 new MutationObserver(() => {830 if (pending) return;831 pending = true;832 setTimeout(() => { pending = false; scan(); }, 200);833 }).observe(document.body, { childList: true, subtree: true });834835 836 837 838 document.addEventListener("focusin", (e) => {839 const target = e.target;840 if (!(target instanceof HTMLInputElement)) return;841 const cardForm = detectCardForm();842 if (cardForm?.number === target) {843 injectCardIcon(target);844 }845 }, true);846}847848chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {849 850 if (sender.id !== chrome.runtime.id) return;851 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {852 const policy = detectPasswordPolicy();853 sendResponse({ ok: true, data: policy });854 return true;855 }856 if (msg?.type === "PING") {857 sendResponse({ ok: true });858 return true;859 }860 if (msg?.type === "SUMMON_AUTOFILL") {861 const source = (msg as { type: string; source?: string }).source;862 const isShortcut = source === "shortcut";863 const isPasskeyUnlock = source === "passkey-unlock";864865 const activeInput = getDeepActiveInput();866 const fields = detectLoginFields();867 const hasForm = isLoginForm(fields) || isSignupForm(fields);868869 if (hasForm) {870 871 872 const inForm = activeInput && fields.some(f => f.el === activeInput);873 const target = inForm874 ? activeInput875 : (fields.find(f => f.type === "password")?.el876 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);877 if (target) {878 879 880 clearFillStateForExplicitSummon(target);881 dismissLock = false;882 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }883 lastDismissedField = null;884 void handleFieldInteraction(target);885 }886 } else if (isPasskeyUnlock) {887 888 889 890 const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)891 ? document.activeElement as unknown as HTMLInputElement892 : null;893 if (anchor) {894 currentDismiss?.();895 currentAnchorField = null;896 passkeySummonActive = true;897 currentDismiss = showAutofillSelector(anchor, [], () => {}, {898 domain: getPageDomain(),899 locked: true,900 onDismiss: () => { passkeySummonActive = false; },901 });902 }903 } else if (isShortcut) {904 905 showSearchPalette();906 }907908 909 if (isShortcut) {910 const domain = getPageDomain();911 if (domain) {912 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});913 }914 }915916 sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });917 return true;918 }919 if (msg?.type === "PASSKEY_PRO_GATE") {920 921 922 showPasskeyProGate();923 sendResponse({ ok: true });924 return true;925 }926 if (msg?.type === "SHOW_PASSKEY_TOAST") {927 928 passkeyToastActive = true;929 if (currentDismiss) {930 currentDismiss();931 currentDismiss = null;932 currentAnchorField = null;933 }934 return false; 935 }936 if (msg?.type === "DISMISS_PASSKEY_TOAST") {937 passkeyToastActive = false;938 return false; 939 }940 if (msg?.type === "VAULT_UNLOCKED") {941 if (passkeySummonActive) {942 943 944 passkeySummonActive = false;945 if (currentDismiss) {946 currentDismiss();947 currentDismiss = null;948 currentAnchorField = null;949 }950 sendResponse({ ok: true });951 return true;952 }953 954 955 const savedField = currentAnchorField;956 if (currentDismiss) {957 currentDismiss();958 currentDismiss = null;959 currentAnchorField = null;960 }961 void handleFieldInteraction(savedField ?? undefined);962 sendResponse({ ok: true });963 return true;964 }965 return true;966});967968969970window.addEventListener("message", (e: MessageEvent) => {971 const d = e.data as { source?: string; type?: string } | undefined;972 if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {973 passkeyToastActive = false;974 }975});976977978979980981982983984985986987988if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {989 let lastPasskeyOfferAt = 0;990 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;991992 window.addEventListener("message", (event: MessageEvent) => {993 if (event.source !== window) return;994 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;995 if (!data || data.source !== "peach-passkey-firefox") return;996 if (detectBrowser() !== "firefox") return;997 if (data.type !== "create") return;998999 1000 1001 const now = Date.now();1002 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1003 lastPasskeyOfferAt = now;10041005 const domain = location.hostname.replace(/^www\./, "");1006 chrome.runtime.sendMessage({1007 type: "GET_PASSKEY_OFFER_DECLINED",1008 payload: { domain },1009 }).then((res: { ok: boolean; data?: boolean } | undefined) => {1010 if (res?.data === true) return;1011 const rpId = data.rpId ?? domain;1012 showPasskeyRegistrationOffer({1013 rpId,1014 rpName: data.rpName,1015 userName: data.userName,1016 userDisplayName: data.userDisplayName,1017 });1018 }).catch(() => {});1019 });1020}102110221023102410251026102710281029103010311032103310341035{1036 function checkPasskeyAvailability() {1037 const domain = location.hostname.replace(/^www\./, "");1038 if (!domain) return;1039 const sessionKey = `peach_state11_shown:${domain}`;1040 chrome.storage.session?.get(sessionKey).then((stored) => {1041 if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1042 chrome.runtime.sendMessage({1043 type: "GET_PASSKEY_FOR_DOMAIN",1044 payload: { domain },1045 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1046 const data = res?.data;1047 if (!data) return;1048 const current = detectBrowser();1049 const isCrossBrowser =1050 data.browser && current !== "unknown" && data.browser !== current;1051 const valuableOnFirefox = current === "firefox";1052 if (!isCrossBrowser && !valuableOnFirefox) return;1053 chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1054 showPasskeyAvailable({1055 rpId: data.rpId,1056 userName: data.userName,1057 fromBrowser: data.browser,1058 currentBrowser: current,1059 });1060 }).catch(() => {});1061 }).catch(() => {});1062 }10631064 1065 1066 1067 if (document.readyState === "loading") {1068 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1069 } else {1070 setTimeout(checkPasskeyAvailability, 800);1071 }1072}