1import {2 detectCardForm,3 detectLoginFields,4 findOTPDigitBoxGroup,5 getDeepActiveInput,6 getPageDomain,7 isAnyCredentialForm,8 isEmailFirstForm,9 isLoginForm,10 isSignupForm,11 isTOTPField,12 isVisible,13} from "./detect";14import {15 CardSelectorEntry,16 injectFieldIcon,17 SelectorEntry,18 showAutofillSelector,19 showCardSelector,20 showPasskeyAvailable,21 showPasskeyProGate,22 showPasskeyRegistrationOffer,23 showRememberSiteToast,24 showTOTPSelector,25} from "./inject";26import { detectBrowser } from "../shared/browser";27import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";28import { fillCardForm, fillFields, fillOTPDigitBoxes, fillTOTPCode, setNativeValue } from "./fill";29import { setupSaveDetection } from "./save";30import { contentMLDetector } from "./content-ml-detector";31import { detectPasswordPolicy } from "./policy";32import type { FieldPrediction } from "../shared/ml";33import type { SavedIdentity, VaultEntry } from "../shared/types";343536373839const processedInputs = new WeakMap<HTMLInputElement, () => void>();40const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);4142let currentDismiss: (() => void) | null = null;4344let currentAnchorField: HTMLInputElement | null = null;4546const pendingInteractions = new WeakSet<HTMLInputElement>();47484950let lastDismissedField: HTMLInputElement | null = null;51525354555657const DISMISS_LOCK_MS = 800;58let dismissLock = false;59let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;60616263let passkeySummonActive = false;64656667let passkeyToastActive = false;68function startDismissLock(): void {69 dismissLock = true;70 if (dismissLockTimer) clearTimeout(dismissLockTimer);71 dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);72}73function canOpen(): boolean { return !dismissLock; }7475767778798081828384858687const filledForms = new WeakSet<HTMLFormElement>();88let pageFilledAt: number | null = null;89const PAGE_FILL_GRACE_MS = 3000;9091function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {92 for (const f of fields) {93 if (!f) continue;94 const form = f.closest("form");95 if (form) filledForms.add(form);96 }97 pageFilledAt = Date.now();98}99100function wasAlreadyFilled(field: HTMLInputElement): boolean {101 const form = field.closest("form");102 if (form && filledForms.has(form)) return true;103 if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;104 return false;105}106107function clearFillStateForExplicitSummon(field: HTMLInputElement): void {108 const form = field.closest("form");109 if (form) filledForms.delete(form);110 pageFilledAt = null;111}112113114115116117function isSubmitButton(el: EventTarget | null): boolean {118 if (!(el instanceof HTMLElement)) return false;119 if (el instanceof HTMLButtonElement && el.type !== "button") return true;120 if (el instanceof HTMLInputElement && el.type === "submit") return true;121 if (el.getAttribute("type") === "submit") return true;122 const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();123 if (!text || text.length > 24) return false;124 return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);125}126127function debounce<T extends (...args: unknown[]) => void>(128 fn: T,129 ms: number130): (...args: Parameters<T>) => void {131 let timer: ReturnType<typeof setTimeout>;132 return (...args: Parameters<T>) => {133 clearTimeout(timer);134 timer = setTimeout(() => fn(...args), ms);135 };136}137138function showToast(message: string): void {139 const toast = document.createElement("div");140 toast.style.cssText = `141 position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);142 background: #131109; color: #F0E8D8; padding: 8px 16px;143 border-radius: 8px; font-family: 'IBM Plex Mono', monospace;144 font-size: 11px; z-index: 2147483647; opacity: 0;145 transition: opacity 200ms ease;146 border: 1px solid rgba(240,232,216,0.07);147 pointer-events: none;148 `;149 toast.textContent = message;150 document.body.appendChild(toast);151 requestAnimationFrame(() => { toast.style.opacity = "1"; });152 setTimeout(() => {153 toast.style.opacity = "0";154 setTimeout(() => toast.remove(), 200);155 }, 2000);156}157158function showSearchPalette(): void {159 const host = document.createElement("div");160 host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";161 document.body.appendChild(host);162 const shadow = host.attachShadow({ mode: "closed" });163164 const style = document.createElement("style");165 style.textContent = `166 .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;167 font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;168 box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}169 .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);170 font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}171 .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}172 .s{padding:8px 12px}173 .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);174 border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;175 padding:6px 8px;font-family:inherit;font-size:12px;outline:none}176 .l{max-height:220px;overflow-y:auto}177 .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}178 .e:hover{background:rgba(240,232,216,.06)}179 .et{font-size:12px}180 .eu{font-size:10px;color:rgba(240,232,216,.45)}181 .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}182 `;183184 let allEntries: SelectorEntry[] = [];185 let query = "";186187 const panel = document.createElement("div");188 panel.className = "p";189190 const hdr = document.createElement("div");191 hdr.className = "h";192 const hdrText = document.createElement("span");193 hdrText.textContent = "No form detected — search your vault";194 const closeBtn = document.createElement("button");195 closeBtn.className = "x";196 closeBtn.textContent = "✕";197 hdr.appendChild(hdrText);198 hdr.appendChild(closeBtn);199200 const searchWrap = document.createElement("div");201 searchWrap.className = "s";202 const searchInput = document.createElement("input");203 searchInput.placeholder = "search...";204 searchWrap.appendChild(searchInput);205206 const list = document.createElement("div");207 list.className = "l";208209 panel.appendChild(hdr);210 panel.appendChild(searchWrap);211 panel.appendChild(list);212 shadow.appendChild(style);213 shadow.appendChild(panel);214215 function close() { host.remove(); }216217 closeBtn.onclick = close;218219 function onKeyDown(e: KeyboardEvent) {220 if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }221 }222 document.addEventListener("keydown", onKeyDown, true);223224 function render() {225 const q = query.toLowerCase();226 const filtered = q227 ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))228 : allEntries;229 list.innerHTML = "";230 if (filtered.length === 0) {231 const em = document.createElement("div");232 em.className = "em";233 em.textContent = query ? "no matches" : "vault is empty";234 list.appendChild(em);235 return;236 }237 for (const entry of filtered.slice(0, 20)) {238 const row = document.createElement("div");239 row.className = "e";240 const title = document.createElement("div");241 title.className = "et";242 title.textContent = entry.title;243 row.appendChild(title);244 if (entry.username) {245 const user = document.createElement("div");246 user.className = "eu";247 user.textContent = entry.username;248 row.appendChild(user);249 }250 row.onclick = async () => {251 const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });252 const r = resp as { ok: boolean; data?: { password?: string } };253 if (r.ok && r.data?.password) {254 let alreadyWritten = false;255 try {256 await navigator.clipboard.writeText(r.data.password);257 alreadyWritten = true;258 } catch (err) {259 console.warn("[Peach] clipboard write denied:", err);260 }261 const copyResp = await chrome.runtime.sendMessage({262 type: "COPY",263 payload: { text: r.data.password, label: "Password", alreadyWritten },264 }) as { ok?: boolean } | undefined;265 if (alreadyWritten || copyResp?.ok) {266 showToast("Password copied");267 } else {268 showToast("Could not copy password — clipboard blocked");269 }270 } else {271 showToast("Could not copy password");272 }273 close();274 document.removeEventListener("keydown", onKeyDown, true);275 };276 list.appendChild(row);277 }278 }279280 searchInput.oninput = () => { query = searchInput.value; render(); };281282 fetchAutofillEntries(getPageDomain(), true).then(result => {283 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }284 allEntries = result.entries;285 render();286 searchInput.focus();287 });288}289290function findTOTPField(root: Document | Element = document): HTMLInputElement | null {291 const inputs = root.querySelectorAll<HTMLInputElement>("input");292 for (const input of inputs) {293 if (isTOTPField(input)) return input;294 }295 return null;296}297298function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {299 const form = passwordEl.closest("form");300 return findTOTPField(form ?? document);301}302303304async function handleAutofill(305 _field: HTMLInputElement,306 usernameEl: HTMLInputElement | null,307 passwordEl: HTMLInputElement | null,308 entry: VaultEntry309): Promise<HTMLInputElement | null> {310 if (!entry.username && !entry.password) return null;311 const pageDomain = getPageDomain();312 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;313 fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);314 let filledTOTPField: HTMLInputElement | null = null;315316 if (entry.canary) {317 chrome.runtime.sendMessage({318 type: "FIRE_CANARY_PING",319 payload: {320 webhookUrl: entry.canary.webhookUrl,321 entryTitle: entry.title,322 trigger: "autofilled",323 },324 }).catch(() => {});325 chrome.runtime.sendMessage({326 type: "UPDATE_ENTRY",327 payload: {328 id: entry.id,329 patch: {330 canary: {331 ...entry.canary,332 lastPinged: Date.now(),333 pingCount: (entry.canary.pingCount ?? 0) + 1,334 },335 },336 },337 }).catch(() => {});338 }339340 341 342 const totpCode = (entry as { totpCode?: string }).totpCode;343 if (totpCode) {344 const code = totpCode;345 const totpField = passwordEl ? findSameLoginTOTPField(passwordEl) : null;346 if (fillTOTPCode(totpField, code)) {347 filledTOTPField = totpField;348 }349 let alreadyWritten = false;350 try {351 await navigator.clipboard.writeText(code);352 alreadyWritten = true;353 } catch (err) {354 console.warn("[Peach] clipboard write denied:", err);355 }356 const response = await chrome.runtime.sendMessage({357 type: "COPY",358 payload: { text: code, label: "TOTP", alreadyWritten },359 });360 if (filledTOTPField) {361 showToast("2FA code filled");362 } else if (alreadyWritten || (response as { ok?: boolean }).ok) {363 364 365 366 showToast("2FA code copied");367 } else {368 showToast("Could not copy TOTP — clipboard blocked");369 }370 }371372 return filledTOTPField;373}374375async function fetchAutofillEntries(376 domain: string,377 includeAll = false378): Promise<{ entries: SelectorEntry[]; locked: boolean }> {379 const response = await chrome.runtime.sendMessage({380 type: "AUTOFILL_QUERY",381 payload: { domain, includeAll },382 });383 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };384 if (!res.ok && res.error === "vault_locked") {385 return { entries: [], locked: true };386 }387 return { entries: res.data ?? [], locked: false };388}389390async function fetchTOTPEntries(391 domain: string392): Promise<{ entries: SelectorEntry[]; locked: boolean }> {393 const response = await chrome.runtime.sendMessage({394 type: "AUTOFILL_QUERY",395 payload: { domain, kind: "totp" },396 });397 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };398 if (!res.ok && res.error === "vault_locked") {399 return { entries: [], locked: true };400 }401 return { entries: res.data ?? [], locked: false };402}403404405function resolveAutofillFieldType(406 el: HTMLInputElement,407 predictedType?: FieldPrediction["type"] | null408): "password" | "username" | "email" | null {409 if (410 predictedType === "password" ||411 predictedType === "username" ||412 predictedType === "email"413 ) {414 return predictedType;415 }416417 const detected = detectLoginFields().find((field) => field.el === el)?.type;418 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {419 return detected;420 }421422 const htmlType = el.type.toLowerCase();423 if (htmlType === "password") return "password";424 if (htmlType === "email") return "email";425 return null;426}427428async function openAutofillSelector(429 anchorField: HTMLInputElement,430 usernameEl: HTMLInputElement | null,431 passwordEl: HTMLInputElement | null,432 domainEntries: SelectorEntry[],433 searchableEntries: SelectorEntry[],434 domain: string435): Promise<void> {436 437 438 439 const isSignup = domainEntries.length === 0;440 let savedIdentities: SavedIdentity[] | undefined;441 let confirmEl: HTMLInputElement | null = null;442 if (isSignup) {443 try {444 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as445 { ok: boolean; data?: SavedIdentity[] } | null;446 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;447 } catch { }448449 const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body;450 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));451 confirmEl = allPwInputs.find(452 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)453 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);454 }455456 currentDismiss?.();457 currentAnchorField = anchorField;458 currentDismiss = showAutofillSelector(459 anchorField,460 domainEntries,461 async (id: string) => {462 currentDismiss = null;463 currentAnchorField = null;464 const entryResponse = await chrome.runtime.sendMessage({465 type: "GET_ENTRY_FOR_FILL",466 payload: { id },467 });468 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;469 if (entry) {470 const filledTOTPField = await handleAutofill(anchorField, usernameEl, passwordEl, entry);471 recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);472 473 474 475 const pageDomain = location.hostname.replace(/^www\./, "");476 const entryDomains = new Set<string>();477 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {478 try {479 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));480 } catch { }481 }482 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {483 showRememberSiteToast(pageDomain, entry.id);484 }485 }486 },487 {488 domain,489 searchableEntries,490 isSignup,491 savedIdentities,492 onFillFields: (username, password) => {493 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;494 fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());495 if (password && confirmEl) setNativeValue(confirmEl, password);496 recordFillSuccess(anchorField, usernameEl, passwordEl);497 },498 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },499 }500 );501}502503async function openTOTPSelector(anchorField: HTMLInputElement, otpDigitBoxes?: HTMLInputElement[]): Promise<void> {504 if (!canOpen()) return;505 if (currentDismiss && currentAnchorField === anchorField) return;506 if (anchorField !== lastDismissedField) lastDismissedField = null;507 if (anchorField === lastDismissedField) return;508 if (wasAlreadyFilled(anchorField)) return;509510 const domain = getPageDomain();511 const result = await fetchTOTPEntries(domain);512513 if (result.locked) {514 currentDismiss?.();515 currentAnchorField = anchorField;516 currentDismiss = showAutofillSelector(517 anchorField,518 [],519 () => {},520 {521 domain,522 locked: true,523 onUnlocked: () => void openTOTPSelector(anchorField),524 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },525 }526 );527 return;528 }529530 if (result.entries.length === 0) {531 lastDismissedField = anchorField;532 startDismissLock();533 showToast("No 2FA entries for this site — add a code in Peach first");534 return;535 }536537 currentDismiss?.();538 currentAnchorField = anchorField;539 currentDismiss = showTOTPSelector(540 anchorField,541 result.entries,542 async (id: string) => {543 try {544 const entryResponse = await chrome.runtime.sendMessage({545 type: "GET_ENTRY_FOR_FILL",546 payload: { id },547 }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;548 const entry = entryResponse?.ok ? entryResponse.data : undefined;549 const code = (entry as { totpCode?: string } | undefined)?.totpCode;550 if (!code) return;551 if (otpDigitBoxes && otpDigitBoxes.length > 1) {552 fillOTPDigitBoxes(otpDigitBoxes, code);553 } else {554 setNativeValue(anchorField, code);555 }556 recordFillSuccess(anchorField);557 showToast("2FA code filled");558 } finally {559 currentDismiss = null;560 currentAnchorField = null;561 }562 },563 {564 domain,565 onDismiss: () => {566 lastDismissedField = anchorField;567 startDismissLock();568 currentDismiss = null;569 currentAnchorField = null;570 },571 }572 );573}574575576async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {577 const field = anchorField ?? getDeepActiveInput();578 if (!field) return;579 if (!isVisible(field)) return;580581 582 if (passkeyToastActive) return;583584 585 586 if (!canOpen()) return;587588 589 if (currentDismiss && currentAnchorField === field) return;590591 592 593 if (field !== lastDismissedField) lastDismissedField = null;594 595 596 if (field === lastDismissedField) return;597598 599 600 601 602 if (wasAlreadyFilled(field)) return;603604 605 606 if (pendingInteractions.has(field)) return;607 pendingInteractions.add(field);608609 try {610 611 612 const otpGroup = findOTPDigitBoxGroup(field);613 if (otpGroup) {614 await openTOTPSelector(otpGroup[0]!, otpGroup);615 return;616 }617618 if (isTOTPField(field)) {619 const formFields = detectLoginFields();620 if (!isLoginForm(formFields) && !isSignupForm(formFields)) {621 await openTOTPSelector(field);622 return;623 }624 }625626 const fieldType = field.type.toLowerCase();627628 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {629 return preds[0] ?? null;630 });631632 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {633 const timeout = setTimeout(() => resolve(null), 150);634 mlPromise.then((pred) => {635 clearTimeout(timeout);636 resolve(pred);637 });638 });639640 if (passkeyToastActive) return;641642 if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {643 return;644 }645646 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);647 if (autofillFieldType) {648 reattachListeners(field, autofillFieldType);649 }650651 let fields = detectLoginFields();652 if (!isAnyCredentialForm(fields)) {653 return;654 }655656 const domain = getPageDomain();657 const firstResult = await fetchAutofillEntries(domain);658 if (passkeyToastActive) return;659660 661 662 663 if (firstResult.locked) {664 currentDismiss?.();665 currentAnchorField = field;666 currentDismiss = showAutofillSelector(667 field,668 [],669 () => {},670 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }671 );672 return;673 }674675 const entries = firstResult.entries;676 677 678 679 680 const allEntries = (await fetchAutofillEntries(domain, true)).entries;681682 if (passkeyToastActive) return;683684 let usernameEl: HTMLInputElement | null = null;685 const userField = fields.find((f) => f.type === "username" || f.type === "email");686 if (userField) usernameEl = userField.el;687 const pwField = fields.find((f) => f.type === "password");688 689 if (!pwField && !isEmailFirstForm(fields)) return;690 const passwordEl = pwField?.el ?? null;691692 await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);693 } finally {694 pendingInteractions.delete(field);695 }696}697698async function onFocusIn(e: Event): Promise<void> {699 700 701 702 703 704 if (isSubmitButton(e.target)) return;705 await handleFieldInteraction();706}707708function reattachListeners(709 el: HTMLInputElement,710 detectedType?: "password" | "username" | "email",711 contextFields?: ReturnType<typeof detectLoginFields>712): void {713 if (processedInputs.has(el)) return;714 if (!resolveAutofillFieldType(el, detectedType)) return;715 716 const fields = contextFields ?? detectLoginFields();717 if (!isAnyCredentialForm(fields)) return;718719 const cleanup = injectFieldIcon(el, () => {720 currentDismiss?.();721 currentDismiss = null;722 lastDismissedField = null; 723 dismissLock = false; 724 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }725 clearFillStateForExplicitSummon(el);726 el.focus({ preventScroll: true });727 void handleFieldInteraction(el);728 });729 processedInputs.set(el, cleanup);730}731732const debouncedReattach = debounce(() => {733 const allFields = detectLoginFields();734 if (!isAnyCredentialForm(allFields)) return;735 const newFields = allFields.filter(736 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)737 );738 for (const f of newFields) {739 reattachListeners(f.el, f.type, allFields);740 }741 742 743 744}, 200);745746function setupMutationObserver(): void {747 const observer = new MutationObserver(debouncedReattach);748 observer.observe(document.body, {749 childList: true,750 subtree: true,751 attributes: true,752 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],753 });754}755756function initialScan(aggressionLevel = 0, isFinalPass = false) {757 const allFields = detectLoginFields();758 const hasKnownForm = isAnyCredentialForm(allFields);759760 if (aggressionLevel === 0 && !hasKnownForm) return;761762 const newFields = allFields.filter(763 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)764 );765766 for (const f of newFields) {767 reattachListeners(f.el, f.type, allFields);768 }769770 771 772 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {773 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');774 for (const el of pwInputs) {775 if (isVisible(el) && !processedInputs.has(el)) {776 const cleanup = injectFieldIcon(el, () => {777 currentDismiss?.();778 currentDismiss = null;779 lastDismissedField = null;780 dismissLock = false;781 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }782 clearFillStateForExplicitSummon(el);783 el.focus({ preventScroll: true });784 void handleFieldInteraction(el);785 });786 processedInputs.set(el, cleanup);787 }788 }789 }790}791792793794795796const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();797798function hasLoginOrSignupForm(): boolean {799 const fields = detectLoginFields();800 return isAnyCredentialForm(fields);801}802803function injectTOTPFieldIcon(field: HTMLInputElement): void {804 if (processedTOTPInputs.has(field)) return;805 const cleanup = injectFieldIcon(field, () => {806 currentDismiss?.();807 currentDismiss = null;808 currentAnchorField = null;809 lastDismissedField = null;810 dismissLock = false;811 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }812 clearFillStateForExplicitSummon(field);813 field.focus({ preventScroll: true });814 void openTOTPSelector(field);815 });816 processedTOTPInputs.set(field, cleanup);817}818819function scanTOTPFields(): void {820 if (hasLoginOrSignupForm()) return;821 const inputs = document.querySelectorAll<HTMLInputElement>("input");822 for (const input of inputs) {823 if (!isTOTPField(input)) continue;824 injectTOTPFieldIcon(input);825 }826}827828function setupTOTPAutofill(): void {829 setTimeout(scanTOTPFields, 0);830 setTimeout(scanTOTPFields, 500);831 setTimeout(scanTOTPFields, 1500);832833 const debouncedScan = debounce(scanTOTPFields, 200);834 new MutationObserver(debouncedScan).observe(document.body, {835 childList: true,836 subtree: true,837 attributes: true,838 attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],839 });840841 document.addEventListener("focusin", (e) => {842 const target = e.target;843 if (!(target instanceof HTMLInputElement)) return;844 if (hasLoginOrSignupForm()) return;845 if (!isTOTPField(target)) return;846 injectTOTPFieldIcon(target);847 }, true);848}849850document.addEventListener("focusin", onFocusIn);851852setupMutationObserver();853setupTOTPAutofill();854setupSaveDetection();855setupCardAutofill();856857858859860861862863864let lastObservedUrl = location.href;865new MutationObserver(() => {866 if (location.href !== lastObservedUrl) {867 lastObservedUrl = location.href;868 pageFilledAt = null;869 }870}).observe(document.body, { childList: true, subtree: false });871872873874(async () => {875 let aggressionLevel = 0;876 try {877 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });878 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;879 const domain = getPageDomain();880 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;881 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;882 } catch { }883884 setTimeout(() => initialScan(aggressionLevel, false), 0);885 setTimeout(() => initialScan(aggressionLevel, false), 500);886 setTimeout(() => initialScan(aggressionLevel, true), 1500);887})();888889890891892893894const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();895let currentCardDismiss: (() => void) | null = null;896let currentCardAnchor: HTMLInputElement | null = null;897let lastDismissedCardField: HTMLInputElement | null = null;898899async function fetchSavedCards(): Promise<CardSelectorEntry[]> {900 const resp = await chrome.runtime.sendMessage({901 type: "AUTOFILL_QUERY",902 payload: { domain: getPageDomain(), kind: "card" },903 }).catch(() => null);904 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;905 return r?.ok ? (r.data ?? []) : [];906}907908async function openCardSelector(anchor: HTMLInputElement): Promise<void> {909 if (!canOpen()) return;910 if (currentCardDismiss && currentCardAnchor === anchor) return;911 if (anchor === lastDismissedCardField) return;912 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;913 if (wasAlreadyFilled(anchor)) return;914915 const cards = await fetchSavedCards();916 if (cards.length === 0) return; 917918 const cardForm = detectCardForm();919 if (!cardForm?.number) return;920921 currentCardDismiss?.();922 currentCardAnchor = anchor;923 currentCardDismiss = showCardSelector(924 anchor,925 cards,926 {927 domain: getPageDomain(),928 onFill: (entry) => {929 if (!cardForm) return;930 fillCardForm(cardForm, {931 cardNumber: entry.cardNumber ?? "",932 expMonth: entry.expMonth ?? "",933 expYear: entry.expYear ?? "",934 cvc: entry.cvc ?? "",935 cardholderName: entry.cardholderName ?? "",936 });937 938 939 940 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);941 currentCardDismiss = null;942 currentCardAnchor = null;943 },944 onDismiss: () => {945 lastDismissedCardField = anchor;946 startDismissLock();947 currentCardDismiss = null;948 currentCardAnchor = null;949 },950 }951 );952}953954function injectCardIcon(field: HTMLInputElement): void {955 if (processedCardInputs.has(field)) return;956 const cleanup = injectFieldIcon(field, () => {957 currentCardDismiss?.();958 currentCardDismiss = null;959 lastDismissedCardField = null;960 dismissLock = false;961 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }962 clearFillStateForExplicitSummon(field);963 field.focus({ preventScroll: true });964 void openCardSelector(field);965 });966 processedCardInputs.set(field, cleanup);967}968969function setupCardAutofill(): void {970 function scan() {971 const cardForm = detectCardForm();972 if (!cardForm?.number) return;973 if (!isVisible(cardForm.number)) return;974 injectCardIcon(cardForm.number);975 }976977 978 979 setTimeout(scan, 0);980 setTimeout(scan, 500);981 setTimeout(scan, 1500);982983 984 985 986 let pending = false;987 new MutationObserver(() => {988 if (pending) return;989 pending = true;990 setTimeout(() => { pending = false; scan(); }, 200);991 }).observe(document.body, { childList: true, subtree: true });992993 994 995 996 document.addEventListener("focusin", (e) => {997 const target = e.target;998 if (!(target instanceof HTMLInputElement)) return;999 const cardForm = detectCardForm();1000 if (cardForm?.number === target) {1001 injectCardIcon(target);1002 }1003 }, true);1004}10051006chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {1007 1008 if (sender.id !== chrome.runtime.id) return;1009 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {1010 const policy = detectPasswordPolicy();1011 sendResponse({ ok: true, data: policy });1012 return true;1013 }1014 if (msg?.type === "PING") {1015 sendResponse({ ok: true });1016 return true;1017 }1018 if (msg?.type === "SUMMON_AUTOFILL") {1019 const source = (msg as { type: string; source?: string }).source;1020 const isShortcut = source === "shortcut";1021 const isPasskeyUnlock = source === "passkey-unlock";10221023 const activeInput = getDeepActiveInput();1024 const fields = detectLoginFields();1025 const hasForm = isAnyCredentialForm(fields);10261027 if (hasForm) {1028 1029 1030 const inForm = activeInput && fields.some(f => f.el === activeInput);1031 const target = inForm1032 ? activeInput1033 : (fields.find(f => f.type === "password")?.el1034 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1035 if (target) {1036 1037 1038 clearFillStateForExplicitSummon(target);1039 dismissLock = false;1040 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1041 lastDismissedField = null;1042 void handleFieldInteraction(target);1043 }1044 } else if (isPasskeyUnlock) {1045 1046 1047 1048 const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1049 ? document.activeElement as unknown as HTMLInputElement1050 : null;1051 if (anchor) {1052 currentDismiss?.();1053 currentAnchorField = null;1054 passkeySummonActive = true;1055 currentDismiss = showAutofillSelector(anchor, [], () => {}, {1056 domain: getPageDomain(),1057 locked: true,1058 onDismiss: () => { passkeySummonActive = false; },1059 });1060 }1061 } else if (isShortcut) {1062 1063 showSearchPalette();1064 }10651066 1067 if (isShortcut) {1068 const domain = getPageDomain();1069 if (domain) {1070 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1071 }1072 }10731074 sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });1075 return true;1076 }1077 if (msg?.type === "PASSKEY_PRO_GATE") {1078 1079 1080 showPasskeyProGate();1081 sendResponse({ ok: true });1082 return true;1083 }1084 if (msg?.type === "SHOW_PASSKEY_TOAST") {1085 1086 passkeyToastActive = true;1087 if (currentDismiss) {1088 currentDismiss();1089 currentDismiss = null;1090 currentAnchorField = null;1091 }1092 return false; 1093 }1094 if (msg?.type === "DISMISS_PASSKEY_TOAST") {1095 passkeyToastActive = false;1096 return false; 1097 }1098 if (msg?.type === "VAULT_UNLOCKED") {1099 if (passkeySummonActive) {1100 1101 1102 passkeySummonActive = false;1103 if (currentDismiss) {1104 currentDismiss();1105 currentDismiss = null;1106 currentAnchorField = null;1107 }1108 sendResponse({ ok: true });1109 return true;1110 }1111 1112 1113 const savedField = currentAnchorField;1114 if (currentDismiss) {1115 currentDismiss();1116 currentDismiss = null;1117 currentAnchorField = null;1118 }1119 void handleFieldInteraction(savedField ?? undefined);1120 sendResponse({ ok: true });1121 return true;1122 }1123 return true;1124});1125112611271128window.addEventListener("message", (e: MessageEvent) => {1129 1130 1131 if (e.source !== window) return;1132 const d = e.data as { source?: string; type?: string } | undefined;1133 if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {1134 passkeyToastActive = false;1135 }1136});1137113811391140114111421143114411451146114711481149if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {1150 let lastPasskeyOfferAt = 0;1151 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;11521153 window.addEventListener("message", (event: MessageEvent) => {1154 if (event.source !== window) return;1155 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;1156 if (!data || data.source !== "peach-passkey-firefox") return;1157 if (detectBrowser() !== "firefox") return;1158 if (data.type !== "create") return;11591160 1161 1162 const now = Date.now();1163 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1164 lastPasskeyOfferAt = now;11651166 const domain = location.hostname.replace(/^www\./, "");1167 chrome.runtime.sendMessage({1168 type: "GET_PASSKEY_OFFER_DECLINED",1169 payload: { domain },1170 }).then((res: { ok: boolean; data?: boolean } | undefined) => {1171 if (res?.data === true) return;1172 const rpId = data.rpId ?? domain;1173 showPasskeyRegistrationOffer({1174 rpId,1175 rpName: data.rpName,1176 userName: data.userName,1177 userDisplayName: data.userDisplayName,1178 });1179 }).catch(() => {});1180 });1181}118211831184118511861187118811891190119111921193119411951196{1197 function checkPasskeyAvailability() {1198 const domain = location.hostname.replace(/^www\./, "");1199 if (!domain) return;1200 const sessionKey = `peach_state11_shown:${domain}`;1201 chrome.storage.session?.get(sessionKey).then((stored) => {1202 if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1203 chrome.runtime.sendMessage({1204 type: "GET_PASSKEY_FOR_DOMAIN",1205 payload: { domain },1206 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1207 const data = res?.data;1208 if (!data) return;1209 const current = detectBrowser();1210 const isCrossBrowser =1211 data.browser && current !== "unknown" && data.browser !== current;1212 const valuableOnFirefox = current === "firefox";1213 if (!isCrossBrowser && !valuableOnFirefox) return;1214 chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1215 showPasskeyAvailable({1216 rpId: data.rpId,1217 userName: data.userName,1218 fromBrowser: data.browser,1219 currentBrowser: current,1220 });1221 }).catch(() => {});1222 }).catch(() => {});1223 }12241225 1226 1227 1228 if (document.readyState === "loading") {1229 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1230 } else {1231 setTimeout(checkPasskeyAvailability, 800);1232 }1233}