1import {2 detectCardForm,3 detectLoginFields,4 getDeepActiveInput,5 getPageDomain,6 isLoginForm,7 isSignupForm,8 isVisible,9} from "./detect";10import {11 CardSelectorEntry,12 injectFieldIcon,13 SelectorEntry,14 showAutofillSelector,15 showCardSelector,16 showPasskeyAvailable,17 showPasskeyProGate,18 showPasskeyRegistrationOffer,19 showRememberSiteToast,20} from "./inject";21import { detectBrowser } from "../shared/browser";22import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";23import { fillCardForm, fillFields, setNativeValue } from "./fill";24import { setupSaveDetection } from "./save";25import { contentMLDetector } from "./content-ml-detector";26import { detectPasswordPolicy } from "./policy";27import type { FieldPrediction } from "../shared/ml";28import { generateTOTP } from "../crypto/totp";29import type { SavedIdentity, VaultEntry } from "../shared/types";303132333435const processedInputs = new WeakMap<HTMLInputElement, () => void>();36const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);3738let currentDismiss: (() => void) | null = null;3940let currentAnchorField: HTMLInputElement | null = null;4142const pendingInteractions = new WeakSet<HTMLInputElement>();43444546let lastDismissedField: HTMLInputElement | null = null;47484950515253const DISMISS_LOCK_MS = 800;54let dismissLock = false;55let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;56575859let passkeySummonActive = false;60616263let passkeyToastActive = false;64function startDismissLock(): void {65 dismissLock = true;66 if (dismissLockTimer) clearTimeout(dismissLockTimer);67 dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);68}69function canOpen(): boolean { return !dismissLock; }7071727374757677787980818283const filledForms = new WeakSet<HTMLFormElement>();84let pageFilledAt: number | null = null;85const PAGE_FILL_GRACE_MS = 3000;8687function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {88 for (const f of fields) {89 if (!f) continue;90 const form = f.closest("form");91 if (form) filledForms.add(form);92 }93 pageFilledAt = Date.now();94}9596function wasAlreadyFilled(field: HTMLInputElement): boolean {97 const form = field.closest("form");98 if (form && filledForms.has(form)) return true;99 if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;100 return false;101}102103function clearFillStateForExplicitSummon(field: HTMLInputElement): void {104 const form = field.closest("form");105 if (form) filledForms.delete(form);106 pageFilledAt = null;107}108109110111112113function isSubmitButton(el: EventTarget | null): boolean {114 if (!(el instanceof HTMLElement)) return false;115 if (el instanceof HTMLButtonElement && el.type !== "button") return true;116 if (el instanceof HTMLInputElement && el.type === "submit") return true;117 if (el.getAttribute("type") === "submit") return true;118 const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();119 if (!text || text.length > 24) return false;120 return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);121}122123function debounce<T extends (...args: unknown[]) => void>(124 fn: T,125 ms: number126): (...args: Parameters<T>) => void {127 let timer: ReturnType<typeof setTimeout>;128 return (...args: Parameters<T>) => {129 clearTimeout(timer);130 timer = setTimeout(() => fn(...args), ms);131 };132}133134function showToast(message: string): void {135 const toast = document.createElement("div");136 toast.style.cssText = `137 position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);138 background: #131109; color: #F0E8D8; padding: 8px 16px;139 border-radius: 8px; font-family: 'IBM Plex Mono', monospace;140 font-size: 11px; z-index: 2147483647; opacity: 0;141 transition: opacity 200ms ease;142 border: 1px solid rgba(240,232,216,0.07);143 pointer-events: none;144 `;145 toast.textContent = message;146 document.body.appendChild(toast);147 requestAnimationFrame(() => { toast.style.opacity = "1"; });148 setTimeout(() => {149 toast.style.opacity = "0";150 setTimeout(() => toast.remove(), 200);151 }, 2000);152}153154function showSearchPalette(): void {155 const host = document.createElement("div");156 host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";157 document.body.appendChild(host);158 const shadow = host.attachShadow({ mode: "closed" });159160 const style = document.createElement("style");161 style.textContent = `162 .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;163 font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;164 box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}165 .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);166 font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}167 .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}168 .s{padding:8px 12px}169 .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);170 border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;171 padding:6px 8px;font-family:inherit;font-size:12px;outline:none}172 .l{max-height:220px;overflow-y:auto}173 .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}174 .e:hover{background:rgba(240,232,216,.06)}175 .et{font-size:12px}176 .eu{font-size:10px;color:rgba(240,232,216,.45)}177 .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}178 `;179180 let allEntries: SelectorEntry[] = [];181 let query = "";182183 const panel = document.createElement("div");184 panel.className = "p";185186 const hdr = document.createElement("div");187 hdr.className = "h";188 const hdrText = document.createElement("span");189 hdrText.textContent = "No form detected — search your vault";190 const closeBtn = document.createElement("button");191 closeBtn.className = "x";192 closeBtn.textContent = "✕";193 hdr.appendChild(hdrText);194 hdr.appendChild(closeBtn);195196 const searchWrap = document.createElement("div");197 searchWrap.className = "s";198 const searchInput = document.createElement("input");199 searchInput.placeholder = "search...";200 searchWrap.appendChild(searchInput);201202 const list = document.createElement("div");203 list.className = "l";204205 panel.appendChild(hdr);206 panel.appendChild(searchWrap);207 panel.appendChild(list);208 shadow.appendChild(style);209 shadow.appendChild(panel);210211 function close() { host.remove(); }212213 closeBtn.onclick = close;214215 function onKeyDown(e: KeyboardEvent) {216 if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }217 }218 document.addEventListener("keydown", onKeyDown, true);219220 function render() {221 const q = query.toLowerCase();222 const filtered = q223 ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))224 : allEntries;225 list.innerHTML = "";226 if (filtered.length === 0) {227 const em = document.createElement("div");228 em.className = "em";229 em.textContent = query ? "no matches" : "vault is empty";230 list.appendChild(em);231 return;232 }233 for (const entry of filtered.slice(0, 20)) {234 const row = document.createElement("div");235 row.className = "e";236 const title = document.createElement("div");237 title.className = "et";238 title.textContent = entry.title;239 row.appendChild(title);240 if (entry.username) {241 const user = document.createElement("div");242 user.className = "eu";243 user.textContent = entry.username;244 row.appendChild(user);245 }246 row.onclick = async () => {247 const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });248 const r = resp as { ok: boolean; data?: { password?: string } };249 if (r.ok && r.data?.password) {250 let alreadyWritten = false;251 try {252 await navigator.clipboard.writeText(r.data.password);253 alreadyWritten = true;254 } catch (err) {255 console.warn("[Peach] clipboard write denied:", err);256 }257 const copyResp = await chrome.runtime.sendMessage({258 type: "COPY",259 payload: { text: r.data.password, label: "Password", alreadyWritten },260 }) as { ok?: boolean } | undefined;261 if (alreadyWritten || copyResp?.ok) {262 showToast("Password copied");263 } else {264 showToast("Could not copy password — clipboard blocked");265 }266 } else {267 showToast("Could not copy password");268 }269 close();270 document.removeEventListener("keydown", onKeyDown, true);271 };272 list.appendChild(row);273 }274 }275276 searchInput.oninput = () => { query = searchInput.value; render(); };277278 fetchAutofillEntries(getPageDomain(), true).then(result => {279 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }280 allEntries = result.entries;281 render();282 searchInput.focus();283 });284}285286function findTOTPField(): HTMLInputElement | null {287 const inputs = document.querySelectorAll<HTMLInputElement>("input");288 for (const input of inputs) {289 if (!isVisible(input)) continue;290 const autocomplete = input.autocomplete.toLowerCase();291 const nameId = (input.name + input.id).toLowerCase();292 const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();293 if (294 autocomplete === "one-time-code" ||295 /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)296 ) {297 return input;298 }299 const labelEl = input.closest("label");300 if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {301 return input;302 }303 }304 return null;305}306307async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {308 await new Promise((r) => setTimeout(r, 400));309 if (totpField.value === "" || totpField.value.trim() === "") {310 const { code } = generateTOTP(totpSecret);311 setNativeValue(totpField, code);312 showToast("TOTP autofilled");313 }314}315316317async function handleAutofill(318 _field: HTMLInputElement,319 usernameEl: HTMLInputElement | null,320 passwordEl: HTMLInputElement,321 entry: VaultEntry322): Promise<void> {323 if (!entry.username && !entry.password) return;324 const pageDomain = getPageDomain();325 const form = passwordEl.closest("form") as HTMLFormElement | null;326 fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);327328 if (entry.canary) {329 chrome.runtime.sendMessage({330 type: "FIRE_CANARY_PING",331 payload: {332 webhookUrl: entry.canary.webhookUrl,333 entryTitle: entry.title,334 trigger: "autofilled",335 },336 }).catch(() => {});337 chrome.runtime.sendMessage({338 type: "UPDATE_ENTRY",339 payload: {340 id: entry.id,341 patch: {342 canary: {343 ...entry.canary,344 lastPinged: Date.now(),345 pingCount: (entry.canary.pingCount ?? 0) + 1,346 },347 },348 },349 }).catch(() => {});350 }351352 if (entry.totp) {353 const { code } = generateTOTP(entry.totp);354 let alreadyWritten = false;355 try {356 await navigator.clipboard.writeText(code);357 alreadyWritten = true;358 } catch (err) {359 console.warn("[Peach] clipboard write denied:", err);360 }361 const response = await chrome.runtime.sendMessage({362 type: "COPY",363 payload: { text: code, label: "TOTP", alreadyWritten },364 });365 if (alreadyWritten || (response as { ok?: boolean }).ok) {366 showToast("TOTP copied · " + code);367 } else {368 showToast("Could not copy TOTP — clipboard blocked");369 }370 const totpField = findTOTPField();371 if (totpField) {372 autofillTOTP(totpField, entry.totp);373 }374 }375}376377async function fetchAutofillEntries(378 domain: string,379 includeAll = false380): Promise<{ entries: SelectorEntry[]; locked: boolean }> {381 const response = await chrome.runtime.sendMessage({382 type: "AUTOFILL_QUERY",383 payload: { domain, includeAll },384 });385 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };386 if (!res.ok && res.error === "VAULT_LOCKED") {387 return { entries: [], locked: true };388 }389 return { entries: res.data ?? [], locked: false };390}391392393function resolveAutofillFieldType(394 el: HTMLInputElement,395 predictedType?: FieldPrediction["type"] | null396): "password" | "username" | "email" | null {397 if (398 predictedType === "password" ||399 predictedType === "username" ||400 predictedType === "email"401 ) {402 return predictedType;403 }404405 const detected = detectLoginFields().find((field) => field.el === el)?.type;406 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {407 return detected;408 }409410 const htmlType = el.type.toLowerCase();411 if (htmlType === "password") return "password";412 if (htmlType === "email") return "email";413 return null;414}415416async function openAutofillSelector(417 anchorField: HTMLInputElement,418 usernameEl: HTMLInputElement | null,419 passwordEl: HTMLInputElement,420 domainEntries: SelectorEntry[],421 searchableEntries: SelectorEntry[],422 domain: string423): Promise<void> {424 425 426 427 const isSignup = domainEntries.length === 0;428 let savedIdentities: SavedIdentity[] | undefined;429 let confirmEl: HTMLInputElement | null = null;430 if (isSignup) {431 try {432 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as433 { ok: boolean; data?: SavedIdentity[] } | null;434 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;435 } catch { }436437 const form = passwordEl.closest("form") ?? document.body;438 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));439 confirmEl = allPwInputs.find(440 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)441 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);442 }443444 currentDismiss?.();445 currentAnchorField = anchorField;446 currentDismiss = showAutofillSelector(447 anchorField,448 domainEntries,449 async (id: string) => {450 currentDismiss = null;451 currentAnchorField = null;452 const entryResponse = await chrome.runtime.sendMessage({453 type: "GET_ENTRY_FOR_FILL",454 payload: { id },455 });456 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;457 if (entry) {458 await handleAutofill(anchorField, usernameEl, passwordEl, entry);459 recordFillSuccess(anchorField, usernameEl, passwordEl);460 461 462 463 const pageDomain = location.hostname.replace(/^www\./, "");464 const entryDomains = new Set<string>();465 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {466 try {467 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));468 } catch { }469 }470 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {471 showRememberSiteToast(pageDomain, entry.id);472 }473 }474 },475 {476 domain,477 searchableEntries,478 isSignup,479 savedIdentities,480 onFillFields: (username, password) => {481 const form = passwordEl.closest("form") as HTMLFormElement | null;482 fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());483 if (password && confirmEl) setNativeValue(confirmEl, password);484 recordFillSuccess(anchorField, usernameEl, passwordEl);485 },486 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },487 }488 );489}490491492async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {493 const field = anchorField ?? getDeepActiveInput();494 if (!field) return;495 if (!isVisible(field)) return;496497 498 if (passkeyToastActive) return;499500 501 502 if (!canOpen()) return;503504 505 if (currentDismiss && currentAnchorField === field) return;506507 508 509 if (field !== lastDismissedField) lastDismissedField = null;510 511 512 if (field === lastDismissedField) return;513514 515 516 517 518 if (wasAlreadyFilled(field)) return;519520 521 522 if (pendingInteractions.has(field)) return;523 pendingInteractions.add(field);524525 try {526 const fieldType = field.type.toLowerCase();527528 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {529 return preds[0] ?? null;530 });531532 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {533 const timeout = setTimeout(() => resolve(null), 150);534 mlPromise.then((pred) => {535 clearTimeout(timeout);536 resolve(pred);537 });538 });539540 if (passkeyToastActive) return;541542 if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {543 return;544 }545546 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);547 if (autofillFieldType) {548 reattachListeners(field, autofillFieldType);549 }550551 let fields = detectLoginFields();552 const loginForm = isLoginForm(fields);553 const signupForm = isSignupForm(fields);554 if (!loginForm && !signupForm) {555 return;556 }557558 const domain = getPageDomain();559 const firstResult = await fetchAutofillEntries(domain);560 if (passkeyToastActive) return;561562 563 564 565 if (firstResult.locked) {566 currentDismiss?.();567 currentAnchorField = field;568 currentDismiss = showAutofillSelector(569 field,570 [],571 () => {},572 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }573 );574 return;575 }576577 const entries = firstResult.entries;578 const allEntries = entries.length === 0579 ? (await fetchAutofillEntries(domain, true)).entries580 : entries;581582 if (passkeyToastActive) return;583584 let usernameEl: HTMLInputElement | null = null;585 const userField = fields.find((f) => f.type === "username" || f.type === "email");586 if (userField) usernameEl = userField.el;587 const pwField = fields.find((f) => f.type === "password");588 if (!pwField) return;589 const passwordEl = pwField.el;590591 await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);592 } finally {593 pendingInteractions.delete(field);594 }595}596597async function onFocusIn(e: Event): Promise<void> {598 599 600 601 602 603 if (isSubmitButton(e.target)) return;604 await handleFieldInteraction();605}606607function reattachListeners(608 el: HTMLInputElement,609 detectedType?: "password" | "username" | "email",610 contextFields?: ReturnType<typeof detectLoginFields>611): void {612 if (processedInputs.has(el)) return;613 if (!resolveAutofillFieldType(el, detectedType)) return;614 615 const fields = contextFields ?? detectLoginFields();616 if (!isLoginForm(fields) && !isSignupForm(fields)) return;617618 const cleanup = injectFieldIcon(el, () => {619 currentDismiss?.();620 currentDismiss = null;621 lastDismissedField = null; 622 dismissLock = false; 623 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }624 clearFillStateForExplicitSummon(el);625 el.focus({ preventScroll: true });626 void handleFieldInteraction(el);627 });628 processedInputs.set(el, cleanup);629}630631const debouncedReattach = debounce(() => {632 const allFields = detectLoginFields();633 634 if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;635 const newFields = allFields.filter(636 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)637 );638 for (const f of newFields) {639 reattachListeners(f.el, f.type, allFields);640 }641 642 643 644}, 200);645646function setupMutationObserver(): void {647 const observer = new MutationObserver(debouncedReattach);648 observer.observe(document.body, {649 childList: true,650 subtree: true,651 attributes: true,652 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],653 });654}655656function initialScan(aggressionLevel = 0, isFinalPass = false) {657 const allFields = detectLoginFields();658 const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);659660 if (aggressionLevel === 0 && !hasKnownForm) return;661662 const newFields = allFields.filter(663 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)664 );665666 for (const f of newFields) {667 reattachListeners(f.el, f.type, allFields);668 }669670 671 672 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {673 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');674 for (const el of pwInputs) {675 if (isVisible(el) && !processedInputs.has(el)) {676 const cleanup = injectFieldIcon(el, () => {677 currentDismiss?.();678 currentDismiss = null;679 lastDismissedField = null;680 dismissLock = false;681 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }682 clearFillStateForExplicitSummon(el);683 el.focus({ preventScroll: true });684 void handleFieldInteraction(el);685 });686 processedInputs.set(el, cleanup);687 }688 }689 }690}691692document.addEventListener("focusin", onFocusIn);693694setupMutationObserver();695setupSaveDetection();696setupCardAutofill();697698699700701702703704705let lastObservedUrl = location.href;706new MutationObserver(() => {707 if (location.href !== lastObservedUrl) {708 lastObservedUrl = location.href;709 pageFilledAt = null;710 }711}).observe(document.body, { childList: true, subtree: false });712713714715(async () => {716 let aggressionLevel = 0;717 try {718 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });719 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;720 const domain = getPageDomain();721 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;722 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;723 } catch { }724725 setTimeout(() => initialScan(aggressionLevel, false), 0);726 setTimeout(() => initialScan(aggressionLevel, false), 500);727 setTimeout(() => initialScan(aggressionLevel, true), 1500);728})();729730731732733734735const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();736let currentCardDismiss: (() => void) | null = null;737let currentCardAnchor: HTMLInputElement | null = null;738let lastDismissedCardField: HTMLInputElement | null = null;739740async function fetchSavedCards(): Promise<CardSelectorEntry[]> {741 const resp = await chrome.runtime.sendMessage({742 type: "AUTOFILL_QUERY",743 payload: { domain: getPageDomain(), kind: "card" },744 }).catch(() => null);745 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;746 return r?.ok ? (r.data ?? []) : [];747}748749async function openCardSelector(anchor: HTMLInputElement): Promise<void> {750 if (!canOpen()) return;751 if (currentCardDismiss && currentCardAnchor === anchor) return;752 if (anchor === lastDismissedCardField) return;753 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;754 if (wasAlreadyFilled(anchor)) return;755756 const cards = await fetchSavedCards();757 if (cards.length === 0) return; 758759 const cardForm = detectCardForm();760 if (!cardForm?.number) return;761762 currentCardDismiss?.();763 currentCardAnchor = anchor;764 currentCardDismiss = showCardSelector(765 anchor,766 cards,767 {768 domain: getPageDomain(),769 onFill: (entry) => {770 if (!cardForm) return;771 fillCardForm(cardForm, {772 cardNumber: entry.cardNumber ?? "",773 expMonth: entry.expMonth ?? "",774 expYear: entry.expYear ?? "",775 cvc: entry.cvc ?? "",776 cardholderName: entry.cardholderName ?? "",777 });778 779 780 781 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);782 currentCardDismiss = null;783 currentCardAnchor = null;784 },785 onDismiss: () => {786 lastDismissedCardField = anchor;787 startDismissLock();788 currentCardDismiss = null;789 currentCardAnchor = null;790 },791 }792 );793}794795function injectCardIcon(field: HTMLInputElement): void {796 if (processedCardInputs.has(field)) return;797 const cleanup = injectFieldIcon(field, () => {798 currentCardDismiss?.();799 currentCardDismiss = null;800 lastDismissedCardField = null;801 dismissLock = false;802 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }803 clearFillStateForExplicitSummon(field);804 field.focus({ preventScroll: true });805 void openCardSelector(field);806 });807 processedCardInputs.set(field, cleanup);808}809810function setupCardAutofill(): void {811 function scan() {812 const cardForm = detectCardForm();813 if (!cardForm?.number) return;814 if (!isVisible(cardForm.number)) return;815 injectCardIcon(cardForm.number);816 }817818 819 820 setTimeout(scan, 0);821 setTimeout(scan, 500);822 setTimeout(scan, 1500);823824 825 826 827 let pending = false;828 new MutationObserver(() => {829 if (pending) return;830 pending = true;831 setTimeout(() => { pending = false; scan(); }, 200);832 }).observe(document.body, { childList: true, subtree: true });833834 835 836 837 document.addEventListener("focusin", (e) => {838 const target = e.target;839 if (!(target instanceof HTMLInputElement)) return;840 const cardForm = detectCardForm();841 if (cardForm?.number === target) {842 injectCardIcon(target);843 }844 }, true);845}846847chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {848 849 if (sender.id !== chrome.runtime.id) return;850 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {851 const policy = detectPasswordPolicy();852 sendResponse({ ok: true, data: policy });853 return true;854 }855 if (msg?.type === "PING") {856 sendResponse({ ok: true });857 return true;858 }859 if (msg?.type === "SUMMON_AUTOFILL") {860 const source = (msg as { type: string; source?: string }).source;861 const isShortcut = source === "shortcut";862 const isPasskeyUnlock = source === "passkey-unlock";863864 const activeInput = getDeepActiveInput();865 const fields = detectLoginFields();866 const hasForm = isLoginForm(fields) || isSignupForm(fields);867868 if (hasForm) {869 870 871 const inForm = activeInput && fields.some(f => f.el === activeInput);872 const target = inForm873 ? activeInput874 : (fields.find(f => f.type === "password")?.el875 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);876 if (target) {877 878 879 clearFillStateForExplicitSummon(target);880 dismissLock = false;881 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }882 lastDismissedField = null;883 void handleFieldInteraction(target);884 }885 } else if (isPasskeyUnlock) {886 887 888 889 const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)890 ? document.activeElement as unknown as HTMLInputElement891 : null;892 if (anchor) {893 currentDismiss?.();894 currentAnchorField = null;895 passkeySummonActive = true;896 currentDismiss = showAutofillSelector(anchor, [], () => {}, {897 domain: getPageDomain(),898 locked: true,899 onDismiss: () => { passkeySummonActive = false; },900 });901 }902 } else if (isShortcut) {903 904 showSearchPalette();905 }906907 908 if (isShortcut) {909 const domain = getPageDomain();910 if (domain) {911 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});912 }913 }914915 sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });916 return true;917 }918 if (msg?.type === "PASSKEY_PRO_GATE") {919 920 921 showPasskeyProGate();922 sendResponse({ ok: true });923 return true;924 }925 if (msg?.type === "SHOW_PASSKEY_TOAST") {926 927 passkeyToastActive = true;928 if (currentDismiss) {929 currentDismiss();930 currentDismiss = null;931 currentAnchorField = null;932 }933 return false; 934 }935 if (msg?.type === "DISMISS_PASSKEY_TOAST") {936 passkeyToastActive = false;937 return false; 938 }939 if (msg?.type === "VAULT_UNLOCKED") {940 if (passkeySummonActive) {941 942 943 passkeySummonActive = false;944 if (currentDismiss) {945 currentDismiss();946 currentDismiss = null;947 currentAnchorField = null;948 }949 sendResponse({ ok: true });950 return true;951 }952 953 954 const savedField = currentAnchorField;955 if (currentDismiss) {956 currentDismiss();957 currentDismiss = null;958 currentAnchorField = null;959 }960 void handleFieldInteraction(savedField ?? undefined);961 sendResponse({ ok: true });962 return true;963 }964 return true;965});966967968969window.addEventListener("message", (e: MessageEvent) => {970 971 972 if (e.source !== window) return;973 const d = e.data as { source?: string; type?: string } | undefined;974 if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {975 passkeyToastActive = false;976 }977});978979980981982983984985986987988989990if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {991 let lastPasskeyOfferAt = 0;992 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;993994 window.addEventListener("message", (event: MessageEvent) => {995 if (event.source !== window) return;996 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;997 if (!data || data.source !== "peach-passkey-firefox") return;998 if (detectBrowser() !== "firefox") return;999 if (data.type !== "create") return;10001001 1002 1003 const now = Date.now();1004 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1005 lastPasskeyOfferAt = now;10061007 const domain = location.hostname.replace(/^www\./, "");1008 chrome.runtime.sendMessage({1009 type: "GET_PASSKEY_OFFER_DECLINED",1010 payload: { domain },1011 }).then((res: { ok: boolean; data?: boolean } | undefined) => {1012 if (res?.data === true) return;1013 const rpId = data.rpId ?? domain;1014 showPasskeyRegistrationOffer({1015 rpId,1016 rpName: data.rpName,1017 userName: data.userName,1018 userDisplayName: data.userDisplayName,1019 });1020 }).catch(() => {});1021 });1022}102310241025102610271028102910301031103210331034103510361037{1038 function checkPasskeyAvailability() {1039 const domain = location.hostname.replace(/^www\./, "");1040 if (!domain) return;1041 const sessionKey = `peach_state11_shown:${domain}`;1042 chrome.storage.session?.get(sessionKey).then((stored) => {1043 if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1044 chrome.runtime.sendMessage({1045 type: "GET_PASSKEY_FOR_DOMAIN",1046 payload: { domain },1047 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1048 const data = res?.data;1049 if (!data) return;1050 const current = detectBrowser();1051 const isCrossBrowser =1052 data.browser && current !== "unknown" && data.browser !== current;1053 const valuableOnFirefox = current === "firefox";1054 if (!isCrossBrowser && !valuableOnFirefox) return;1055 chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1056 showPasskeyAvailable({1057 rpId: data.rpId,1058 userName: data.userName,1059 fromBrowser: data.browser,1060 currentBrowser: current,1061 });1062 }).catch(() => {});1063 }).catch(() => {});1064 }10651066 1067 1068 1069 if (document.readyState === "loading") {1070 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1071 } else {1072 setTimeout(checkPasskeyAvailability, 800);1073 }1074}