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 { resolveAutofillInteractionTargets } from "./interaction";30import { setupSaveDetection } from "./save";31import { contentMLDetector } from "./content-ml-detector";32import { detectPasswordPolicy } from "./policy";33import type { FieldPrediction } from "../shared/ml";34import type { SavedIdentity, VaultEntry } from "../shared/types";353637383940const processedInputs = new WeakMap<HTMLInputElement, () => void>();41const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);4243let currentDismiss: (() => void) | null = null;4445let currentAnchorField: HTMLInputElement | null = null;4647const pendingInteractions = new WeakSet<HTMLInputElement>();48495051let lastDismissedField: HTMLInputElement | null = null;52535455565758const DISMISS_LOCK_MS = 800;59let dismissLock = false;60let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;61626364let passkeySummonActive = false;65666768let passkeyToastActive = false;69function startDismissLock(): void {70 dismissLock = true;71 if (dismissLockTimer) clearTimeout(dismissLockTimer);72 dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);73}74function canOpen(): boolean { return !dismissLock; }7576777879808182838485868788const filledForms = new WeakSet<HTMLFormElement>();89let pageFilledAt: number | null = null;90const PAGE_FILL_GRACE_MS = 3000;9192function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {93 for (const f of fields) {94 if (!f) continue;95 const form = f.closest("form");96 if (form) filledForms.add(form);97 }98 pageFilledAt = Date.now();99}100101function wasAlreadyFilled(field: HTMLInputElement): boolean {102 const form = field.closest("form");103 if (form && filledForms.has(form)) return true;104 if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;105 return false;106}107108function clearFillStateForExplicitSummon(field: HTMLInputElement): void {109 const form = field.closest("form");110 if (form) filledForms.delete(form);111 pageFilledAt = null;112}113114115116117118function isSubmitButton(el: EventTarget | null): boolean {119 if (!(el instanceof HTMLElement)) return false;120 if (el instanceof HTMLButtonElement && el.type !== "button") return true;121 if (el instanceof HTMLInputElement && el.type === "submit") return true;122 if (el.getAttribute("type") === "submit") return true;123 const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();124 if (!text || text.length > 24) return false;125 return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);126}127128function debounce<T extends (...args: unknown[]) => void>(129 fn: T,130 ms: number131): (...args: Parameters<T>) => void {132 let timer: ReturnType<typeof setTimeout>;133 return (...args: Parameters<T>) => {134 clearTimeout(timer);135 timer = setTimeout(() => fn(...args), ms);136 };137}138139function showToast(message: string): void {140 const toast = document.createElement("div");141 toast.style.cssText = `142 position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);143 background: #131109; color: #F0E8D8; padding: 8px 16px;144 border-radius: 8px; font-family: 'IBM Plex Mono', monospace;145 font-size: 11px; z-index: 2147483647; opacity: 0;146 transition: opacity 200ms ease;147 border: 1px solid rgba(240,232,216,0.07);148 pointer-events: none;149 `;150 toast.textContent = message;151 document.body.appendChild(toast);152 requestAnimationFrame(() => { toast.style.opacity = "1"; });153 setTimeout(() => {154 toast.style.opacity = "0";155 setTimeout(() => toast.remove(), 200);156 }, 2000);157}158159function showSearchPalette(): void {160 const host = document.createElement("div");161 host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";162 document.body.appendChild(host);163 const shadow = host.attachShadow({ mode: "closed" });164165 const style = document.createElement("style");166 style.textContent = `167 .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;168 font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;169 box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}170 .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);171 font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}172 .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}173 .s{padding:8px 12px}174 .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);175 border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;176 padding:6px 8px;font-family:inherit;font-size:12px;outline:none}177 .l{max-height:220px;overflow-y:auto}178 .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}179 .e:hover{background:rgba(240,232,216,.06)}180 .et{font-size:12px}181 .eu{font-size:10px;color:rgba(240,232,216,.45)}182 .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}183 `;184185 let allEntries: SelectorEntry[] = [];186 let query = "";187188 const panel = document.createElement("div");189 panel.className = "p";190191 const hdr = document.createElement("div");192 hdr.className = "h";193 const hdrText = document.createElement("span");194 hdrText.textContent = "No form detected — search your vault";195 const closeBtn = document.createElement("button");196 closeBtn.className = "x";197 closeBtn.textContent = "✕";198 hdr.appendChild(hdrText);199 hdr.appendChild(closeBtn);200201 const searchWrap = document.createElement("div");202 searchWrap.className = "s";203 const searchInput = document.createElement("input");204 searchInput.placeholder = "search...";205 searchWrap.appendChild(searchInput);206207 const list = document.createElement("div");208 list.className = "l";209210 panel.appendChild(hdr);211 panel.appendChild(searchWrap);212 panel.appendChild(list);213 shadow.appendChild(style);214 shadow.appendChild(panel);215216 function close() { host.remove(); }217218 closeBtn.onclick = close;219220 function onKeyDown(e: KeyboardEvent) {221 if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }222 }223 document.addEventListener("keydown", onKeyDown, true);224225 function render() {226 const q = query.toLowerCase();227 const filtered = q228 ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))229 : allEntries;230 list.innerHTML = "";231 if (filtered.length === 0) {232 const em = document.createElement("div");233 em.className = "em";234 em.textContent = query ? "no matches" : "vault is empty";235 list.appendChild(em);236 return;237 }238 for (const entry of filtered.slice(0, 20)) {239 const row = document.createElement("div");240 row.className = "e";241 const title = document.createElement("div");242 title.className = "et";243 title.textContent = entry.title;244 row.appendChild(title);245 if (entry.username) {246 const user = document.createElement("div");247 user.className = "eu";248 user.textContent = entry.username;249 row.appendChild(user);250 }251 row.onclick = async () => {252 const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });253 const r = resp as { ok: boolean; data?: { password?: string } };254 if (r.ok && r.data?.password) {255 let alreadyWritten = false;256 try {257 await navigator.clipboard.writeText(r.data.password);258 alreadyWritten = true;259 } catch (err) {260 console.warn("[Peach] clipboard write denied:", err);261 }262 const copyResp = await chrome.runtime.sendMessage({263 type: "COPY",264 payload: { text: r.data.password, label: "Password", alreadyWritten },265 }) as { ok?: boolean } | undefined;266 if (alreadyWritten || copyResp?.ok) {267 showToast("Password copied");268 } else {269 showToast("Could not copy password — clipboard blocked");270 }271 } else {272 showToast("Could not copy password");273 }274 close();275 document.removeEventListener("keydown", onKeyDown, true);276 };277 list.appendChild(row);278 }279 }280281 searchInput.oninput = () => { query = searchInput.value; render(); };282283 fetchAutofillEntries(getPageDomain(), true).then(result => {284 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }285 allEntries = result.entries;286 render();287 searchInput.focus();288 });289}290291function findTOTPField(root: Document | Element = document): HTMLInputElement | null {292 const inputs = root.querySelectorAll<HTMLInputElement>("input");293 for (const input of inputs) {294 if (isTOTPField(input)) return input;295 }296 return null;297}298299function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {300 const form = passwordEl.closest("form");301 return findTOTPField(form ?? document);302}303304305async function handleAutofill(306 _field: HTMLInputElement,307 usernameEl: HTMLInputElement | null,308 passwordEl: HTMLInputElement | null,309 entry: VaultEntry310): Promise<HTMLInputElement | null> {311 if (!entry.username && !entry.password) return null;312 const pageDomain = getPageDomain();313 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;314 fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);315 let filledTOTPField: HTMLInputElement | null = null;316317 if (entry.canary) {318 chrome.runtime.sendMessage({319 type: "FIRE_CANARY_PING",320 payload: {321 webhookUrl: entry.canary.webhookUrl,322 entryTitle: entry.title,323 trigger: "autofilled",324 },325 }).catch(() => {});326 chrome.runtime.sendMessage({327 type: "UPDATE_ENTRY",328 payload: {329 id: entry.id,330 patch: {331 canary: {332 ...entry.canary,333 lastPinged: Date.now(),334 pingCount: (entry.canary.pingCount ?? 0) + 1,335 },336 },337 },338 }).catch(() => {});339 }340341 342 343 const totpCode = (entry as { totpCode?: string }).totpCode;344 if (totpCode) {345 const code = totpCode;346 const totpField = passwordEl ? findSameLoginTOTPField(passwordEl) : null;347 if (fillTOTPCode(totpField, code)) {348 filledTOTPField = totpField;349 }350 let alreadyWritten = false;351 try {352 await navigator.clipboard.writeText(code);353 alreadyWritten = true;354 } catch (err) {355 console.warn("[Peach] clipboard write denied:", err);356 }357 const response = await chrome.runtime.sendMessage({358 type: "COPY",359 payload: { text: code, label: "TOTP", alreadyWritten },360 });361 if (filledTOTPField) {362 showToast("2FA code filled");363 } else if (alreadyWritten || (response as { ok?: boolean }).ok) {364 365 366 367 showToast("2FA code copied");368 } else {369 showToast("Could not copy TOTP — clipboard blocked");370 }371 }372373 return filledTOTPField;374}375376async function fetchAutofillEntries(377 domain: string,378 includeAll = false379): Promise<{ entries: SelectorEntry[]; locked: boolean }> {380 const response = await chrome.runtime.sendMessage({381 type: "AUTOFILL_QUERY",382 payload: { domain, includeAll },383 });384 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };385 if (!res.ok && res.error === "vault_locked") {386 return { entries: [], locked: true };387 }388 return { entries: res.data ?? [], locked: false };389}390391async function fetchTOTPEntries(392 domain: string393): Promise<{ entries: SelectorEntry[]; locked: boolean }> {394 const response = await chrome.runtime.sendMessage({395 type: "AUTOFILL_QUERY",396 payload: { domain, kind: "totp" },397 });398 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };399 if (!res.ok && res.error === "vault_locked") {400 return { entries: [], locked: true };401 }402 return { entries: res.data ?? [], locked: false };403}404405406function resolveAutofillFieldType(407 el: HTMLInputElement,408 predictedType?: FieldPrediction["type"] | null409): "password" | "username" | "email" | null {410 if (411 predictedType === "password" ||412 predictedType === "username" ||413 predictedType === "email"414 ) {415 return predictedType;416 }417418 const detected = detectLoginFields().find((field) => field.el === el)?.type;419 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {420 return detected;421 }422423 const htmlType = el.type.toLowerCase();424 if (htmlType === "password") return "password";425 if (htmlType === "email") return "email";426 return null;427}428429async function openAutofillSelector(430 anchorField: HTMLInputElement,431 usernameEl: HTMLInputElement | null,432 passwordEl: HTMLInputElement | null,433 domainEntries: SelectorEntry[],434 searchableEntries: SelectorEntry[],435 domain: string436): Promise<void> {437 438 439 440 const isSignup = domainEntries.length === 0;441 let savedIdentities: SavedIdentity[] | undefined;442 let confirmEl: HTMLInputElement | null = null;443 if (isSignup) {444 try {445 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as446 { ok: boolean; data?: SavedIdentity[] } | null;447 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;448 } catch { }449450 const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body;451 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));452 confirmEl = allPwInputs.find(453 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)454 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);455 }456457 currentDismiss?.();458 currentAnchorField = anchorField;459 currentDismiss = showAutofillSelector(460 anchorField,461 domainEntries,462 async (id: string) => {463 currentDismiss = null;464 currentAnchorField = null;465 const entryResponse = await chrome.runtime.sendMessage({466 type: "GET_ENTRY_FOR_FILL",467 payload: { id },468 });469 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;470 if (entry) {471 const filledTOTPField = await handleAutofill(anchorField, usernameEl, passwordEl, entry);472 recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);473 474 475 476 const pageDomain = location.hostname.replace(/^www\./, "");477 const entryDomains = new Set<string>();478 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {479 try {480 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));481 } catch { }482 }483 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {484 showRememberSiteToast(pageDomain, entry.id);485 }486 }487 },488 {489 domain,490 searchableEntries,491 isSignup,492 savedIdentities,493 onFillFields: (username, password) => {494 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;495 fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());496 if (password && confirmEl) setNativeValue(confirmEl, password);497 recordFillSuccess(anchorField, usernameEl, passwordEl);498 },499 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },500 }501 );502}503504async function openTOTPSelector(anchorField: HTMLInputElement, otpDigitBoxes?: HTMLInputElement[]): Promise<void> {505 if (!canOpen()) return;506 if (currentDismiss && currentAnchorField === anchorField) return;507 if (anchorField !== lastDismissedField) lastDismissedField = null;508 if (anchorField === lastDismissedField) return;509 if (wasAlreadyFilled(anchorField)) return;510511 const domain = getPageDomain();512 const result = await fetchTOTPEntries(domain);513514 if (result.locked) {515 currentDismiss?.();516 currentAnchorField = anchorField;517 currentDismiss = showAutofillSelector(518 anchorField,519 [],520 () => {},521 {522 domain,523 locked: true,524 onUnlocked: () => void openTOTPSelector(anchorField),525 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },526 }527 );528 return;529 }530531 if (result.entries.length === 0) {532 lastDismissedField = anchorField;533 startDismissLock();534 showToast("No 2FA entries for this site — add a code in Peach first");535 return;536 }537538 currentDismiss?.();539 currentAnchorField = anchorField;540 currentDismiss = showTOTPSelector(541 anchorField,542 result.entries,543 async (id: string) => {544 try {545 const entryResponse = await chrome.runtime.sendMessage({546 type: "GET_ENTRY_FOR_FILL",547 payload: { id },548 }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;549 const entry = entryResponse?.ok ? entryResponse.data : undefined;550 const code = (entry as { totpCode?: string } | undefined)?.totpCode;551 if (!code) return;552 if (otpDigitBoxes && otpDigitBoxes.length > 1) {553 fillOTPDigitBoxes(otpDigitBoxes, code);554 } else {555 setNativeValue(anchorField, code);556 }557 recordFillSuccess(anchorField);558 showToast("2FA code filled");559 } finally {560 currentDismiss = null;561 currentAnchorField = null;562 }563 },564 {565 domain,566 onDismiss: () => {567 lastDismissedField = anchorField;568 startDismissLock();569 currentDismiss = null;570 currentAnchorField = null;571 },572 }573 );574}575576577async function handleFieldInteraction(578 anchorField?: HTMLInputElement | null,579 explicitSummon = false580): Promise<void> {581 const field = anchorField ?? getDeepActiveInput();582 if (!field) return;583 if (!isVisible(field)) return;584585 586 if (passkeyToastActive) return;587588 589 590 if (!canOpen()) return;591592 593 if (currentDismiss && currentAnchorField === field) return;594595 596 597 if (field !== lastDismissedField) lastDismissedField = null;598 599 600 if (field === lastDismissedField) return;601602 603 604 605 606 if (wasAlreadyFilled(field)) return;607608 609 610 if (pendingInteractions.has(field)) return;611 pendingInteractions.add(field);612613 try {614 615 616 const otpGroup = findOTPDigitBoxGroup(field);617 if (otpGroup) {618 await openTOTPSelector(otpGroup[0]!, otpGroup);619 return;620 }621622 if (isTOTPField(field)) {623 const formFields = detectLoginFields();624 if (!isLoginForm(formFields) && !isSignupForm(formFields)) {625 await openTOTPSelector(field);626 return;627 }628 }629630 const fieldType = field.type.toLowerCase();631632 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {633 return preds[0] ?? null;634 });635636 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {637 const timeout = setTimeout(() => resolve(null), 150);638 mlPromise.then((pred) => {639 clearTimeout(timeout);640 resolve(pred);641 });642 });643644 if (passkeyToastActive) return;645646 if (!explicitSummon && fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {647 return;648 }649650 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);651 if (autofillFieldType) {652 reattachListeners(field, autofillFieldType);653 }654655 let fields = detectLoginFields();656 const targets = resolveAutofillInteractionTargets(field, fields, explicitSummon);657 if (!targets.shouldOpen) {658 return;659 }660661 const domain = getPageDomain();662 const firstResult = await fetchAutofillEntries(domain);663 if (passkeyToastActive) return;664665 666 667 668 if (firstResult.locked) {669 currentDismiss?.();670 currentAnchorField = field;671 currentDismiss = showAutofillSelector(672 field,673 [],674 () => {},675 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }676 );677 return;678 }679680 const entries = firstResult.entries;681 682 683 684 685 const allEntries = (await fetchAutofillEntries(domain, true)).entries;686687 if (passkeyToastActive) return;688689 const pwField = fields.find((f) => f.type === "password");690 691 if (!explicitSummon && !pwField && !isEmailFirstForm(fields)) return;692 const usernameEl = targets.usernameEl;693 const passwordEl = targets.passwordEl;694695 await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);696 } finally {697 pendingInteractions.delete(field);698 }699}700701async function onFocusIn(e: Event): Promise<void> {702 703 704 705 706 707 if (isSubmitButton(e.target)) return;708 await handleFieldInteraction();709}710711function reattachListeners(712 el: HTMLInputElement,713 detectedType?: "password" | "username" | "email",714 contextFields?: ReturnType<typeof detectLoginFields>715): void {716 if (processedInputs.has(el)) return;717 if (!resolveAutofillFieldType(el, detectedType)) return;718 719 const fields = contextFields ?? detectLoginFields();720 if (!isAnyCredentialForm(fields)) return;721722 const cleanup = injectFieldIcon(el, () => {723 currentDismiss?.();724 currentDismiss = null;725 lastDismissedField = null; 726 dismissLock = false; 727 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }728 clearFillStateForExplicitSummon(el);729 el.focus({ preventScroll: true });730 void handleFieldInteraction(el, true);731 });732 processedInputs.set(el, cleanup);733}734735const debouncedReattach = debounce(() => {736 const allFields = detectLoginFields();737 if (!isAnyCredentialForm(allFields)) return;738 const newFields = allFields.filter(739 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)740 );741 for (const f of newFields) {742 reattachListeners(f.el, f.type, allFields);743 }744 745 746 747}, 200);748749function setupMutationObserver(): void {750 const observer = new MutationObserver(debouncedReattach);751 observer.observe(document.body, {752 childList: true,753 subtree: true,754 attributes: true,755 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],756 });757}758759function initialScan(aggressionLevel = 0, isFinalPass = false) {760 const allFields = detectLoginFields();761 const hasKnownForm = isAnyCredentialForm(allFields);762763 if (aggressionLevel === 0 && !hasKnownForm) return;764765 const newFields = allFields.filter(766 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)767 );768769 for (const f of newFields) {770 reattachListeners(f.el, f.type, allFields);771 }772773 774 775 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {776 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');777 for (const el of pwInputs) {778 if (isVisible(el) && !processedInputs.has(el)) {779 const cleanup = injectFieldIcon(el, () => {780 currentDismiss?.();781 currentDismiss = null;782 lastDismissedField = null;783 dismissLock = false;784 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }785 clearFillStateForExplicitSummon(el);786 el.focus({ preventScroll: true });787 void handleFieldInteraction(el, true);788 });789 processedInputs.set(el, cleanup);790 }791 }792 }793}794795796797798799const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();800801function hasLoginOrSignupForm(): boolean {802 const fields = detectLoginFields();803 return isAnyCredentialForm(fields);804}805806function injectTOTPFieldIcon(field: HTMLInputElement): void {807 if (processedTOTPInputs.has(field)) return;808 const cleanup = injectFieldIcon(field, () => {809 currentDismiss?.();810 currentDismiss = null;811 currentAnchorField = null;812 lastDismissedField = null;813 dismissLock = false;814 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }815 clearFillStateForExplicitSummon(field);816 field.focus({ preventScroll: true });817 void openTOTPSelector(field);818 });819 processedTOTPInputs.set(field, cleanup);820}821822function scanTOTPFields(): void {823 if (hasLoginOrSignupForm()) return;824 const inputs = document.querySelectorAll<HTMLInputElement>("input");825 for (const input of inputs) {826 if (!isTOTPField(input)) continue;827 injectTOTPFieldIcon(input);828 }829}830831function setupTOTPAutofill(): void {832 setTimeout(scanTOTPFields, 0);833 setTimeout(scanTOTPFields, 500);834 setTimeout(scanTOTPFields, 1500);835836 const debouncedScan = debounce(scanTOTPFields, 200);837 new MutationObserver(debouncedScan).observe(document.body, {838 childList: true,839 subtree: true,840 attributes: true,841 attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],842 });843844 document.addEventListener("focusin", (e) => {845 const target = e.target;846 if (!(target instanceof HTMLInputElement)) return;847 if (hasLoginOrSignupForm()) return;848 if (!isTOTPField(target)) return;849 injectTOTPFieldIcon(target);850 }, true);851}852853document.addEventListener("focusin", onFocusIn);854855setupMutationObserver();856setupTOTPAutofill();857setupSaveDetection();858setupCardAutofill();859860861862863864865866867let lastObservedUrl = location.href;868new MutationObserver(() => {869 if (location.href !== lastObservedUrl) {870 lastObservedUrl = location.href;871 pageFilledAt = null;872 }873}).observe(document.body, { childList: true, subtree: false });874875876877(async () => {878 let aggressionLevel = 0;879 try {880 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });881 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;882 const domain = getPageDomain();883 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;884 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;885 } catch { }886887 setTimeout(() => initialScan(aggressionLevel, false), 0);888 setTimeout(() => initialScan(aggressionLevel, false), 500);889 setTimeout(() => initialScan(aggressionLevel, true), 1500);890})();891892893894895896897const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();898let currentCardDismiss: (() => void) | null = null;899let currentCardAnchor: HTMLInputElement | null = null;900let lastDismissedCardField: HTMLInputElement | null = null;901902async function fetchSavedCards(): Promise<CardSelectorEntry[]> {903 const resp = await chrome.runtime.sendMessage({904 type: "AUTOFILL_QUERY",905 payload: { domain: getPageDomain(), kind: "card" },906 }).catch(() => null);907 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;908 return r?.ok ? (r.data ?? []) : [];909}910911async function openCardSelector(anchor: HTMLInputElement): Promise<void> {912 if (!canOpen()) return;913 if (currentCardDismiss && currentCardAnchor === anchor) return;914 if (anchor === lastDismissedCardField) return;915 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;916 if (wasAlreadyFilled(anchor)) return;917918 const cards = await fetchSavedCards();919 if (cards.length === 0) return; 920921 const cardForm = detectCardForm();922 if (!cardForm?.number) return;923924 currentCardDismiss?.();925 currentCardAnchor = anchor;926 currentCardDismiss = showCardSelector(927 anchor,928 cards,929 {930 domain: getPageDomain(),931 onFill: (entry) => {932 if (!cardForm) return;933 fillCardForm(cardForm, {934 cardNumber: entry.cardNumber ?? "",935 expMonth: entry.expMonth ?? "",936 expYear: entry.expYear ?? "",937 cvc: entry.cvc ?? "",938 cardholderName: entry.cardholderName ?? "",939 });940 941 942 943 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);944 currentCardDismiss = null;945 currentCardAnchor = null;946 },947 onDismiss: () => {948 lastDismissedCardField = anchor;949 startDismissLock();950 currentCardDismiss = null;951 currentCardAnchor = null;952 },953 }954 );955}956957function injectCardIcon(field: HTMLInputElement): void {958 if (processedCardInputs.has(field)) return;959 const cleanup = injectFieldIcon(field, () => {960 currentCardDismiss?.();961 currentCardDismiss = null;962 lastDismissedCardField = null;963 dismissLock = false;964 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }965 clearFillStateForExplicitSummon(field);966 field.focus({ preventScroll: true });967 void openCardSelector(field);968 });969 processedCardInputs.set(field, cleanup);970}971972function setupCardAutofill(): void {973 function scan() {974 const cardForm = detectCardForm();975 if (!cardForm?.number) return;976 if (!isVisible(cardForm.number)) return;977 injectCardIcon(cardForm.number);978 }979980 981 982 setTimeout(scan, 0);983 setTimeout(scan, 500);984 setTimeout(scan, 1500);985986 987 988 989 let pending = false;990 new MutationObserver(() => {991 if (pending) return;992 pending = true;993 setTimeout(() => { pending = false; scan(); }, 200);994 }).observe(document.body, { childList: true, subtree: true });995996 997 998 999 document.addEventListener("focusin", (e) => {1000 const target = e.target;1001 if (!(target instanceof HTMLInputElement)) return;1002 const cardForm = detectCardForm();1003 if (cardForm?.number === target) {1004 injectCardIcon(target);1005 }1006 }, true);1007}10081009chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {1010 1011 if (sender.id !== chrome.runtime.id) return;1012 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {1013 const policy = detectPasswordPolicy();1014 sendResponse({ ok: true, data: policy });1015 return true;1016 }1017 if (msg?.type === "PING") {1018 sendResponse({ ok: true });1019 return true;1020 }1021 if (msg?.type === "SUMMON_AUTOFILL") {1022 const source = (msg as { type: string; source?: string }).source;1023 const isShortcut = source === "shortcut";1024 const isPasskeyUnlock = source === "passkey-unlock";10251026 const activeInput = getDeepActiveInput();1027 const fields = detectLoginFields();1028 const hasForm = isAnyCredentialForm(fields);10291030 if (hasForm) {1031 1032 1033 const inForm = activeInput && fields.some(f => f.el === activeInput);1034 const target = inForm1035 ? activeInput1036 : (fields.find(f => f.type === "password")?.el1037 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1038 if (target) {1039 1040 1041 clearFillStateForExplicitSummon(target);1042 dismissLock = false;1043 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1044 lastDismissedField = null;1045 void handleFieldInteraction(target);1046 }1047 } else if (isPasskeyUnlock) {1048 1049 1050 1051 const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1052 ? document.activeElement as unknown as HTMLInputElement1053 : null;1054 if (anchor) {1055 currentDismiss?.();1056 currentAnchorField = null;1057 passkeySummonActive = true;1058 currentDismiss = showAutofillSelector(anchor, [], () => {}, {1059 domain: getPageDomain(),1060 locked: true,1061 onDismiss: () => { passkeySummonActive = false; },1062 });1063 }1064 } else if (isShortcut) {1065 1066 showSearchPalette();1067 }10681069 1070 if (isShortcut) {1071 const domain = getPageDomain();1072 if (domain) {1073 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1074 }1075 }10761077 sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });1078 return true;1079 }1080 if (msg?.type === "PASSKEY_PRO_GATE") {1081 1082 1083 showPasskeyProGate();1084 sendResponse({ ok: true });1085 return true;1086 }1087 if (msg?.type === "SHOW_PASSKEY_TOAST") {1088 1089 passkeyToastActive = true;1090 if (currentDismiss) {1091 currentDismiss();1092 currentDismiss = null;1093 currentAnchorField = null;1094 }1095 return false; 1096 }1097 if (msg?.type === "DISMISS_PASSKEY_TOAST") {1098 passkeyToastActive = false;1099 return false; 1100 }1101 if (msg?.type === "VAULT_UNLOCKED") {1102 if (passkeySummonActive) {1103 1104 1105 passkeySummonActive = false;1106 if (currentDismiss) {1107 currentDismiss();1108 currentDismiss = null;1109 currentAnchorField = null;1110 }1111 sendResponse({ ok: true });1112 return true;1113 }1114 1115 1116 const savedField = currentAnchorField;1117 if (currentDismiss) {1118 currentDismiss();1119 currentDismiss = null;1120 currentAnchorField = null;1121 }1122 void handleFieldInteraction(savedField ?? undefined);1123 sendResponse({ ok: true });1124 return true;1125 }1126 return true;1127});1128112911301131window.addEventListener("message", (e: MessageEvent) => {1132 1133 1134 if (e.source !== window) return;1135 const d = e.data as { source?: string; type?: string } | undefined;1136 if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {1137 passkeyToastActive = false;1138 }1139});1140114111421143114411451146114711481149115011511152if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {1153 let lastPasskeyOfferAt = 0;1154 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;11551156 window.addEventListener("message", (event: MessageEvent) => {1157 if (event.source !== window) return;1158 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;1159 if (!data || data.source !== "peach-passkey-firefox") return;1160 if (detectBrowser() !== "firefox") return;1161 if (data.type !== "create") return;11621163 1164 1165 const now = Date.now();1166 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1167 lastPasskeyOfferAt = now;11681169 const domain = location.hostname.replace(/^www\./, "");1170 chrome.runtime.sendMessage({1171 type: "GET_PASSKEY_OFFER_DECLINED",1172 payload: { domain },1173 }).then((res: { ok: boolean; data?: boolean } | undefined) => {1174 if (res?.data === true) return;1175 const rpId = data.rpId ?? domain;1176 showPasskeyRegistrationOffer({1177 rpId,1178 rpName: data.rpName,1179 userName: data.userName,1180 userDisplayName: data.userDisplayName,1181 });1182 }).catch(() => {});1183 });1184}118511861187118811891190119111921193119411951196119711981199{1200 function checkPasskeyAvailability() {1201 const domain = location.hostname.replace(/^www\./, "");1202 if (!domain) return;1203 const sessionKey = `peach_state11_shown:${domain}`;1204 chrome.storage.session?.get(sessionKey).then((stored) => {1205 if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1206 chrome.runtime.sendMessage({1207 type: "GET_PASSKEY_FOR_DOMAIN",1208 payload: { domain },1209 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1210 const data = res?.data;1211 if (!data) return;1212 const current = detectBrowser();1213 const isCrossBrowser =1214 data.browser && current !== "unknown" && data.browser !== current;1215 const valuableOnFirefox = current === "firefox";1216 if (!isCrossBrowser && !valuableOnFirefox) return;1217 chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1218 showPasskeyAvailable({1219 rpId: data.rpId,1220 userName: data.userName,1221 fromBrowser: data.browser,1222 currentBrowser: current,1223 });1224 }).catch(() => {});1225 }).catch(() => {});1226 }12271228 1229 1230 1231 if (document.readyState === "loading") {1232 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1233 } else {1234 setTimeout(checkPasskeyAvailability, 800);1235 }1236}