1import {2 detectCardForm,3 detectLoginFields,4 getDeepActiveInput,5 getPageDomain,6 isLoginForm,7 isSignupForm,8 isTOTPField,9 isVisible,10} from "./detect";11import {12 CardSelectorEntry,13 injectFieldIcon,14 SelectorEntry,15 showAutofillSelector,16 showCardSelector,17 showPasskeyAvailable,18 showPasskeyProGate,19 showPasskeyRegistrationOffer,20 showRememberSiteToast,21 showTOTPSelector,22} from "./inject";23import { detectBrowser } from "../shared/browser";24import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";25import { fillCardForm, fillFields, fillTOTPCode, setNativeValue } from "./fill";26import { setupSaveDetection } from "./save";27import { contentMLDetector } from "./content-ml-detector";28import { detectPasswordPolicy } from "./policy";29import type { FieldPrediction } from "../shared/ml";30import { generateTOTP } from "../crypto/totp";31import type { SavedIdentity, VaultEntry } from "../shared/types";323334353637const processedInputs = new WeakMap<HTMLInputElement, () => void>();38const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);3940let currentDismiss: (() => void) | null = null;4142let currentAnchorField: HTMLInputElement | null = null;4344const pendingInteractions = new WeakSet<HTMLInputElement>();45464748let lastDismissedField: HTMLInputElement | null = null;49505152535455const DISMISS_LOCK_MS = 800;56let dismissLock = false;57let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;58596061let passkeySummonActive = false;62636465let passkeyToastActive = false;66function startDismissLock(): void {67 dismissLock = true;68 if (dismissLockTimer) clearTimeout(dismissLockTimer);69 dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);70}71function canOpen(): boolean { return !dismissLock; }7273747576777879808182838485const filledForms = new WeakSet<HTMLFormElement>();86let pageFilledAt: number | null = null;87const PAGE_FILL_GRACE_MS = 3000;8889function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {90 for (const f of fields) {91 if (!f) continue;92 const form = f.closest("form");93 if (form) filledForms.add(form);94 }95 pageFilledAt = Date.now();96}9798function wasAlreadyFilled(field: HTMLInputElement): boolean {99 const form = field.closest("form");100 if (form && filledForms.has(form)) return true;101 if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;102 return false;103}104105function clearFillStateForExplicitSummon(field: HTMLInputElement): void {106 const form = field.closest("form");107 if (form) filledForms.delete(form);108 pageFilledAt = null;109}110111112113114115function isSubmitButton(el: EventTarget | null): boolean {116 if (!(el instanceof HTMLElement)) return false;117 if (el instanceof HTMLButtonElement && el.type !== "button") return true;118 if (el instanceof HTMLInputElement && el.type === "submit") return true;119 if (el.getAttribute("type") === "submit") return true;120 const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();121 if (!text || text.length > 24) return false;122 return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);123}124125function debounce<T extends (...args: unknown[]) => void>(126 fn: T,127 ms: number128): (...args: Parameters<T>) => void {129 let timer: ReturnType<typeof setTimeout>;130 return (...args: Parameters<T>) => {131 clearTimeout(timer);132 timer = setTimeout(() => fn(...args), ms);133 };134}135136function showToast(message: string): void {137 const toast = document.createElement("div");138 toast.style.cssText = `139 position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);140 background: #131109; color: #F0E8D8; padding: 8px 16px;141 border-radius: 8px; font-family: 'IBM Plex Mono', monospace;142 font-size: 11px; z-index: 2147483647; opacity: 0;143 transition: opacity 200ms ease;144 border: 1px solid rgba(240,232,216,0.07);145 pointer-events: none;146 `;147 toast.textContent = message;148 document.body.appendChild(toast);149 requestAnimationFrame(() => { toast.style.opacity = "1"; });150 setTimeout(() => {151 toast.style.opacity = "0";152 setTimeout(() => toast.remove(), 200);153 }, 2000);154}155156function showSearchPalette(): void {157 const host = document.createElement("div");158 host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";159 document.body.appendChild(host);160 const shadow = host.attachShadow({ mode: "closed" });161162 const style = document.createElement("style");163 style.textContent = `164 .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;165 font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;166 box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}167 .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);168 font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}169 .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}170 .s{padding:8px 12px}171 .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);172 border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;173 padding:6px 8px;font-family:inherit;font-size:12px;outline:none}174 .l{max-height:220px;overflow-y:auto}175 .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}176 .e:hover{background:rgba(240,232,216,.06)}177 .et{font-size:12px}178 .eu{font-size:10px;color:rgba(240,232,216,.45)}179 .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}180 `;181182 let allEntries: SelectorEntry[] = [];183 let query = "";184185 const panel = document.createElement("div");186 panel.className = "p";187188 const hdr = document.createElement("div");189 hdr.className = "h";190 const hdrText = document.createElement("span");191 hdrText.textContent = "No form detected — search your vault";192 const closeBtn = document.createElement("button");193 closeBtn.className = "x";194 closeBtn.textContent = "✕";195 hdr.appendChild(hdrText);196 hdr.appendChild(closeBtn);197198 const searchWrap = document.createElement("div");199 searchWrap.className = "s";200 const searchInput = document.createElement("input");201 searchInput.placeholder = "search...";202 searchWrap.appendChild(searchInput);203204 const list = document.createElement("div");205 list.className = "l";206207 panel.appendChild(hdr);208 panel.appendChild(searchWrap);209 panel.appendChild(list);210 shadow.appendChild(style);211 shadow.appendChild(panel);212213 function close() { host.remove(); }214215 closeBtn.onclick = close;216217 function onKeyDown(e: KeyboardEvent) {218 if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }219 }220 document.addEventListener("keydown", onKeyDown, true);221222 function render() {223 const q = query.toLowerCase();224 const filtered = q225 ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))226 : allEntries;227 list.innerHTML = "";228 if (filtered.length === 0) {229 const em = document.createElement("div");230 em.className = "em";231 em.textContent = query ? "no matches" : "vault is empty";232 list.appendChild(em);233 return;234 }235 for (const entry of filtered.slice(0, 20)) {236 const row = document.createElement("div");237 row.className = "e";238 const title = document.createElement("div");239 title.className = "et";240 title.textContent = entry.title;241 row.appendChild(title);242 if (entry.username) {243 const user = document.createElement("div");244 user.className = "eu";245 user.textContent = entry.username;246 row.appendChild(user);247 }248 row.onclick = async () => {249 const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });250 const r = resp as { ok: boolean; data?: { password?: string } };251 if (r.ok && r.data?.password) {252 let alreadyWritten = false;253 try {254 await navigator.clipboard.writeText(r.data.password);255 alreadyWritten = true;256 } catch (err) {257 console.warn("[Peach] clipboard write denied:", err);258 }259 const copyResp = await chrome.runtime.sendMessage({260 type: "COPY",261 payload: { text: r.data.password, label: "Password", alreadyWritten },262 }) as { ok?: boolean } | undefined;263 if (alreadyWritten || copyResp?.ok) {264 showToast("Password copied");265 } else {266 showToast("Could not copy password — clipboard blocked");267 }268 } else {269 showToast("Could not copy password");270 }271 close();272 document.removeEventListener("keydown", onKeyDown, true);273 };274 list.appendChild(row);275 }276 }277278 searchInput.oninput = () => { query = searchInput.value; render(); };279280 fetchAutofillEntries(getPageDomain(), true).then(result => {281 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }282 allEntries = result.entries;283 render();284 searchInput.focus();285 });286}287288function findTOTPField(root: Document | Element = document): HTMLInputElement | null {289 const inputs = root.querySelectorAll<HTMLInputElement>("input");290 for (const input of inputs) {291 if (isTOTPField(input)) return input;292 }293 return null;294}295296function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {297 const form = passwordEl.closest("form");298 return findTOTPField(form ?? document);299}300301302async function handleAutofill(303 _field: HTMLInputElement,304 usernameEl: HTMLInputElement | null,305 passwordEl: HTMLInputElement,306 entry: VaultEntry307): Promise<HTMLInputElement | null> {308 if (!entry.username && !entry.password) return null;309 const pageDomain = getPageDomain();310 const form = passwordEl.closest("form") as HTMLFormElement | null;311 fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);312 let filledTOTPField: HTMLInputElement | null = null;313314 if (entry.canary) {315 chrome.runtime.sendMessage({316 type: "FIRE_CANARY_PING",317 payload: {318 webhookUrl: entry.canary.webhookUrl,319 entryTitle: entry.title,320 trigger: "autofilled",321 },322 }).catch(() => {});323 chrome.runtime.sendMessage({324 type: "UPDATE_ENTRY",325 payload: {326 id: entry.id,327 patch: {328 canary: {329 ...entry.canary,330 lastPinged: Date.now(),331 pingCount: (entry.canary.pingCount ?? 0) + 1,332 },333 },334 },335 }).catch(() => {});336 }337338 if (entry.totp) {339 const { code } = generateTOTP(entry.totp);340 const totpField = findSameLoginTOTPField(passwordEl);341 if (fillTOTPCode(totpField, code)) {342 filledTOTPField = totpField;343 }344 let alreadyWritten = false;345 try {346 await navigator.clipboard.writeText(code);347 alreadyWritten = true;348 } catch (err) {349 console.warn("[Peach] clipboard write denied:", err);350 }351 const response = await chrome.runtime.sendMessage({352 type: "COPY",353 payload: { text: code, label: "TOTP", alreadyWritten },354 });355 if (filledTOTPField) {356 showToast("2FA code filled");357 } else if (alreadyWritten || (response as { ok?: boolean }).ok) {358 showToast("TOTP copied · " + code);359 } else {360 showToast("Could not copy TOTP — clipboard blocked");361 }362 }363364 return filledTOTPField;365}366367async function fetchAutofillEntries(368 domain: string,369 includeAll = false370): Promise<{ entries: SelectorEntry[]; locked: boolean }> {371 const response = await chrome.runtime.sendMessage({372 type: "AUTOFILL_QUERY",373 payload: { domain, includeAll },374 });375 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };376 if (!res.ok && res.error === "vault_locked") {377 return { entries: [], locked: true };378 }379 return { entries: res.data ?? [], locked: false };380}381382async function fetchTOTPEntries(383 domain: string384): Promise<{ entries: SelectorEntry[]; locked: boolean }> {385 const response = await chrome.runtime.sendMessage({386 type: "AUTOFILL_QUERY",387 payload: { domain, kind: "totp" },388 });389 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };390 if (!res.ok && res.error === "vault_locked") {391 return { entries: [], locked: true };392 }393 return { entries: res.data ?? [], locked: false };394}395396397function resolveAutofillFieldType(398 el: HTMLInputElement,399 predictedType?: FieldPrediction["type"] | null400): "password" | "username" | "email" | null {401 if (402 predictedType === "password" ||403 predictedType === "username" ||404 predictedType === "email"405 ) {406 return predictedType;407 }408409 const detected = detectLoginFields().find((field) => field.el === el)?.type;410 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {411 return detected;412 }413414 const htmlType = el.type.toLowerCase();415 if (htmlType === "password") return "password";416 if (htmlType === "email") return "email";417 return null;418}419420async function openAutofillSelector(421 anchorField: HTMLInputElement,422 usernameEl: HTMLInputElement | null,423 passwordEl: HTMLInputElement,424 domainEntries: SelectorEntry[],425 searchableEntries: SelectorEntry[],426 domain: string427): Promise<void> {428 429 430 431 const isSignup = domainEntries.length === 0;432 let savedIdentities: SavedIdentity[] | undefined;433 let confirmEl: HTMLInputElement | null = null;434 if (isSignup) {435 try {436 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as437 { ok: boolean; data?: SavedIdentity[] } | null;438 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;439 } catch { }440441 const form = passwordEl.closest("form") ?? document.body;442 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));443 confirmEl = allPwInputs.find(444 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)445 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);446 }447448 currentDismiss?.();449 currentAnchorField = anchorField;450 currentDismiss = showAutofillSelector(451 anchorField,452 domainEntries,453 async (id: string) => {454 currentDismiss = null;455 currentAnchorField = null;456 const entryResponse = await chrome.runtime.sendMessage({457 type: "GET_ENTRY_FOR_FILL",458 payload: { id },459 });460 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;461 if (entry) {462 const filledTOTPField = await handleAutofill(anchorField, usernameEl, passwordEl, entry);463 recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);464 465 466 467 const pageDomain = location.hostname.replace(/^www\./, "");468 const entryDomains = new Set<string>();469 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {470 try {471 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));472 } catch { }473 }474 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {475 showRememberSiteToast(pageDomain, entry.id);476 }477 }478 },479 {480 domain,481 searchableEntries,482 isSignup,483 savedIdentities,484 onFillFields: (username, password) => {485 const form = passwordEl.closest("form") as HTMLFormElement | null;486 fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());487 if (password && confirmEl) setNativeValue(confirmEl, password);488 recordFillSuccess(anchorField, usernameEl, passwordEl);489 },490 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },491 }492 );493}494495async function openTOTPSelector(anchorField: HTMLInputElement): Promise<void> {496 if (!canOpen()) return;497 if (currentDismiss && currentAnchorField === anchorField) return;498 if (anchorField !== lastDismissedField) lastDismissedField = null;499 if (anchorField === lastDismissedField) return;500 if (wasAlreadyFilled(anchorField)) return;501502 const domain = getPageDomain();503 const result = await fetchTOTPEntries(domain);504505 if (result.locked) {506 currentDismiss?.();507 currentAnchorField = anchorField;508 currentDismiss = showAutofillSelector(509 anchorField,510 [],511 () => {},512 {513 domain,514 locked: true,515 onUnlocked: () => void openTOTPSelector(anchorField),516 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },517 }518 );519 return;520 }521522 if (result.entries.length === 0) return;523524 currentDismiss?.();525 currentAnchorField = anchorField;526 currentDismiss = showTOTPSelector(527 anchorField,528 result.entries,529 async (id: string) => {530 try {531 const entryResponse = await chrome.runtime.sendMessage({532 type: "GET_ENTRY_FOR_FILL",533 payload: { id },534 }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;535 const entry = entryResponse?.ok ? entryResponse.data : undefined;536 if (!entry?.totp) return;537 const { code } = generateTOTP(entry.totp);538 setNativeValue(anchorField, code);539 recordFillSuccess(anchorField);540 showToast("2FA code filled");541 } finally {542 currentDismiss = null;543 currentAnchorField = null;544 }545 },546 {547 domain,548 onDismiss: () => {549 lastDismissedField = anchorField;550 startDismissLock();551 currentDismiss = null;552 currentAnchorField = null;553 },554 }555 );556}557558559async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {560 const field = anchorField ?? getDeepActiveInput();561 if (!field) return;562 if (!isVisible(field)) return;563564 565 if (passkeyToastActive) return;566567 568 569 if (!canOpen()) return;570571 572 if (currentDismiss && currentAnchorField === field) return;573574 575 576 if (field !== lastDismissedField) lastDismissedField = null;577 578 579 if (field === lastDismissedField) return;580581 582 583 584 585 if (wasAlreadyFilled(field)) return;586587 588 589 if (pendingInteractions.has(field)) return;590 pendingInteractions.add(field);591592 try {593 if (isTOTPField(field)) {594 const formFields = detectLoginFields();595 if (!isLoginForm(formFields) && !isSignupForm(formFields)) {596 await openTOTPSelector(field);597 return;598 }599 }600601 const fieldType = field.type.toLowerCase();602603 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {604 return preds[0] ?? null;605 });606607 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {608 const timeout = setTimeout(() => resolve(null), 150);609 mlPromise.then((pred) => {610 clearTimeout(timeout);611 resolve(pred);612 });613 });614615 if (passkeyToastActive) return;616617 if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {618 return;619 }620621 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);622 if (autofillFieldType) {623 reattachListeners(field, autofillFieldType);624 }625626 let fields = detectLoginFields();627 const loginForm = isLoginForm(fields);628 const signupForm = isSignupForm(fields);629 if (!loginForm && !signupForm) {630 return;631 }632633 const domain = getPageDomain();634 const firstResult = await fetchAutofillEntries(domain);635 if (passkeyToastActive) return;636637 638 639 640 if (firstResult.locked) {641 currentDismiss?.();642 currentAnchorField = field;643 currentDismiss = showAutofillSelector(644 field,645 [],646 () => {},647 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }648 );649 return;650 }651652 const entries = firstResult.entries;653 const allEntries = entries.length === 0654 ? (await fetchAutofillEntries(domain, true)).entries655 : entries;656657 if (passkeyToastActive) return;658659 let usernameEl: HTMLInputElement | null = null;660 const userField = fields.find((f) => f.type === "username" || f.type === "email");661 if (userField) usernameEl = userField.el;662 const pwField = fields.find((f) => f.type === "password");663 if (!pwField) return;664 const passwordEl = pwField.el;665666 await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);667 } finally {668 pendingInteractions.delete(field);669 }670}671672async function onFocusIn(e: Event): Promise<void> {673 674 675 676 677 678 if (isSubmitButton(e.target)) return;679 await handleFieldInteraction();680}681682function reattachListeners(683 el: HTMLInputElement,684 detectedType?: "password" | "username" | "email",685 contextFields?: ReturnType<typeof detectLoginFields>686): void {687 if (processedInputs.has(el)) return;688 if (!resolveAutofillFieldType(el, detectedType)) return;689 690 const fields = contextFields ?? detectLoginFields();691 if (!isLoginForm(fields) && !isSignupForm(fields)) return;692693 const cleanup = injectFieldIcon(el, () => {694 currentDismiss?.();695 currentDismiss = null;696 lastDismissedField = null; 697 dismissLock = false; 698 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }699 clearFillStateForExplicitSummon(el);700 el.focus({ preventScroll: true });701 void handleFieldInteraction(el);702 });703 processedInputs.set(el, cleanup);704}705706const debouncedReattach = debounce(() => {707 const allFields = detectLoginFields();708 709 if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;710 const newFields = allFields.filter(711 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)712 );713 for (const f of newFields) {714 reattachListeners(f.el, f.type, allFields);715 }716 717 718 719}, 200);720721function setupMutationObserver(): void {722 const observer = new MutationObserver(debouncedReattach);723 observer.observe(document.body, {724 childList: true,725 subtree: true,726 attributes: true,727 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],728 });729}730731function initialScan(aggressionLevel = 0, isFinalPass = false) {732 const allFields = detectLoginFields();733 const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);734735 if (aggressionLevel === 0 && !hasKnownForm) return;736737 const newFields = allFields.filter(738 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)739 );740741 for (const f of newFields) {742 reattachListeners(f.el, f.type, allFields);743 }744745 746 747 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {748 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');749 for (const el of pwInputs) {750 if (isVisible(el) && !processedInputs.has(el)) {751 const cleanup = injectFieldIcon(el, () => {752 currentDismiss?.();753 currentDismiss = null;754 lastDismissedField = null;755 dismissLock = false;756 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }757 clearFillStateForExplicitSummon(el);758 el.focus({ preventScroll: true });759 void handleFieldInteraction(el);760 });761 processedInputs.set(el, cleanup);762 }763 }764 }765}766767768769770771const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();772773function hasLoginOrSignupForm(): boolean {774 const fields = detectLoginFields();775 return isLoginForm(fields) || isSignupForm(fields);776}777778function injectTOTPFieldIcon(field: HTMLInputElement): void {779 if (processedTOTPInputs.has(field)) return;780 const cleanup = injectFieldIcon(field, () => {781 currentDismiss?.();782 currentDismiss = null;783 currentAnchorField = null;784 lastDismissedField = null;785 dismissLock = false;786 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }787 clearFillStateForExplicitSummon(field);788 field.focus({ preventScroll: true });789 void openTOTPSelector(field);790 });791 processedTOTPInputs.set(field, cleanup);792}793794function scanTOTPFields(): void {795 if (hasLoginOrSignupForm()) return;796 const inputs = document.querySelectorAll<HTMLInputElement>("input");797 for (const input of inputs) {798 if (!isTOTPField(input)) continue;799 injectTOTPFieldIcon(input);800 }801}802803function setupTOTPAutofill(): void {804 setTimeout(scanTOTPFields, 0);805 setTimeout(scanTOTPFields, 500);806 setTimeout(scanTOTPFields, 1500);807808 const debouncedScan = debounce(scanTOTPFields, 200);809 new MutationObserver(debouncedScan).observe(document.body, {810 childList: true,811 subtree: true,812 attributes: true,813 attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],814 });815816 document.addEventListener("focusin", (e) => {817 const target = e.target;818 if (!(target instanceof HTMLInputElement)) return;819 if (hasLoginOrSignupForm()) return;820 if (!isTOTPField(target)) return;821 injectTOTPFieldIcon(target);822 }, true);823}824825document.addEventListener("focusin", onFocusIn);826827setupMutationObserver();828setupTOTPAutofill();829setupSaveDetection();830setupCardAutofill();831832833834835836837838839let lastObservedUrl = location.href;840new MutationObserver(() => {841 if (location.href !== lastObservedUrl) {842 lastObservedUrl = location.href;843 pageFilledAt = null;844 }845}).observe(document.body, { childList: true, subtree: false });846847848849(async () => {850 let aggressionLevel = 0;851 try {852 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });853 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;854 const domain = getPageDomain();855 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;856 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;857 } catch { }858859 setTimeout(() => initialScan(aggressionLevel, false), 0);860 setTimeout(() => initialScan(aggressionLevel, false), 500);861 setTimeout(() => initialScan(aggressionLevel, true), 1500);862})();863864865866867868869const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();870let currentCardDismiss: (() => void) | null = null;871let currentCardAnchor: HTMLInputElement | null = null;872let lastDismissedCardField: HTMLInputElement | null = null;873874async function fetchSavedCards(): Promise<CardSelectorEntry[]> {875 const resp = await chrome.runtime.sendMessage({876 type: "AUTOFILL_QUERY",877 payload: { domain: getPageDomain(), kind: "card" },878 }).catch(() => null);879 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;880 return r?.ok ? (r.data ?? []) : [];881}882883async function openCardSelector(anchor: HTMLInputElement): Promise<void> {884 if (!canOpen()) return;885 if (currentCardDismiss && currentCardAnchor === anchor) return;886 if (anchor === lastDismissedCardField) return;887 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;888 if (wasAlreadyFilled(anchor)) return;889890 const cards = await fetchSavedCards();891 if (cards.length === 0) return; 892893 const cardForm = detectCardForm();894 if (!cardForm?.number) return;895896 currentCardDismiss?.();897 currentCardAnchor = anchor;898 currentCardDismiss = showCardSelector(899 anchor,900 cards,901 {902 domain: getPageDomain(),903 onFill: (entry) => {904 if (!cardForm) return;905 fillCardForm(cardForm, {906 cardNumber: entry.cardNumber ?? "",907 expMonth: entry.expMonth ?? "",908 expYear: entry.expYear ?? "",909 cvc: entry.cvc ?? "",910 cardholderName: entry.cardholderName ?? "",911 });912 913 914 915 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);916 currentCardDismiss = null;917 currentCardAnchor = null;918 },919 onDismiss: () => {920 lastDismissedCardField = anchor;921 startDismissLock();922 currentCardDismiss = null;923 currentCardAnchor = null;924 },925 }926 );927}928929function injectCardIcon(field: HTMLInputElement): void {930 if (processedCardInputs.has(field)) return;931 const cleanup = injectFieldIcon(field, () => {932 currentCardDismiss?.();933 currentCardDismiss = null;934 lastDismissedCardField = null;935 dismissLock = false;936 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }937 clearFillStateForExplicitSummon(field);938 field.focus({ preventScroll: true });939 void openCardSelector(field);940 });941 processedCardInputs.set(field, cleanup);942}943944function setupCardAutofill(): void {945 function scan() {946 const cardForm = detectCardForm();947 if (!cardForm?.number) return;948 if (!isVisible(cardForm.number)) return;949 injectCardIcon(cardForm.number);950 }951952 953 954 setTimeout(scan, 0);955 setTimeout(scan, 500);956 setTimeout(scan, 1500);957958 959 960 961 let pending = false;962 new MutationObserver(() => {963 if (pending) return;964 pending = true;965 setTimeout(() => { pending = false; scan(); }, 200);966 }).observe(document.body, { childList: true, subtree: true });967968 969 970 971 document.addEventListener("focusin", (e) => {972 const target = e.target;973 if (!(target instanceof HTMLInputElement)) return;974 const cardForm = detectCardForm();975 if (cardForm?.number === target) {976 injectCardIcon(target);977 }978 }, true);979}980981chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {982 983 if (sender.id !== chrome.runtime.id) return;984 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {985 const policy = detectPasswordPolicy();986 sendResponse({ ok: true, data: policy });987 return true;988 }989 if (msg?.type === "PING") {990 sendResponse({ ok: true });991 return true;992 }993 if (msg?.type === "SUMMON_AUTOFILL") {994 const source = (msg as { type: string; source?: string }).source;995 const isShortcut = source === "shortcut";996 const isPasskeyUnlock = source === "passkey-unlock";997998 const activeInput = getDeepActiveInput();999 const fields = detectLoginFields();1000 const hasForm = isLoginForm(fields) || isSignupForm(fields);10011002 if (hasForm) {1003 1004 1005 const inForm = activeInput && fields.some(f => f.el === activeInput);1006 const target = inForm1007 ? activeInput1008 : (fields.find(f => f.type === "password")?.el1009 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1010 if (target) {1011 1012 1013 clearFillStateForExplicitSummon(target);1014 dismissLock = false;1015 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1016 lastDismissedField = null;1017 void handleFieldInteraction(target);1018 }1019 } else if (isPasskeyUnlock) {1020 1021 1022 1023 const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1024 ? document.activeElement as unknown as HTMLInputElement1025 : null;1026 if (anchor) {1027 currentDismiss?.();1028 currentAnchorField = null;1029 passkeySummonActive = true;1030 currentDismiss = showAutofillSelector(anchor, [], () => {}, {1031 domain: getPageDomain(),1032 locked: true,1033 onDismiss: () => { passkeySummonActive = false; },1034 });1035 }1036 } else if (isShortcut) {1037 1038 showSearchPalette();1039 }10401041 1042 if (isShortcut) {1043 const domain = getPageDomain();1044 if (domain) {1045 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1046 }1047 }10481049 sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });1050 return true;1051 }1052 if (msg?.type === "PASSKEY_PRO_GATE") {1053 1054 1055 showPasskeyProGate();1056 sendResponse({ ok: true });1057 return true;1058 }1059 if (msg?.type === "SHOW_PASSKEY_TOAST") {1060 1061 passkeyToastActive = true;1062 if (currentDismiss) {1063 currentDismiss();1064 currentDismiss = null;1065 currentAnchorField = null;1066 }1067 return false; 1068 }1069 if (msg?.type === "DISMISS_PASSKEY_TOAST") {1070 passkeyToastActive = false;1071 return false; 1072 }1073 if (msg?.type === "VAULT_UNLOCKED") {1074 if (passkeySummonActive) {1075 1076 1077 passkeySummonActive = false;1078 if (currentDismiss) {1079 currentDismiss();1080 currentDismiss = null;1081 currentAnchorField = null;1082 }1083 sendResponse({ ok: true });1084 return true;1085 }1086 1087 1088 const savedField = currentAnchorField;1089 if (currentDismiss) {1090 currentDismiss();1091 currentDismiss = null;1092 currentAnchorField = null;1093 }1094 void handleFieldInteraction(savedField ?? undefined);1095 sendResponse({ ok: true });1096 return true;1097 }1098 return true;1099});1100110111021103window.addEventListener("message", (e: MessageEvent) => {1104 1105 1106 if (e.source !== window) return;1107 const d = e.data as { source?: string; type?: string } | undefined;1108 if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {1109 passkeyToastActive = false;1110 }1111});1112111311141115111611171118111911201121112211231124if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {1125 let lastPasskeyOfferAt = 0;1126 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;11271128 window.addEventListener("message", (event: MessageEvent) => {1129 if (event.source !== window) return;1130 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;1131 if (!data || data.source !== "peach-passkey-firefox") return;1132 if (detectBrowser() !== "firefox") return;1133 if (data.type !== "create") return;11341135 1136 1137 const now = Date.now();1138 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1139 lastPasskeyOfferAt = now;11401141 const domain = location.hostname.replace(/^www\./, "");1142 chrome.runtime.sendMessage({1143 type: "GET_PASSKEY_OFFER_DECLINED",1144 payload: { domain },1145 }).then((res: { ok: boolean; data?: boolean } | undefined) => {1146 if (res?.data === true) return;1147 const rpId = data.rpId ?? domain;1148 showPasskeyRegistrationOffer({1149 rpId,1150 rpName: data.rpName,1151 userName: data.userName,1152 userDisplayName: data.userDisplayName,1153 });1154 }).catch(() => {});1155 });1156}115711581159116011611162116311641165116611671168116911701171{1172 function checkPasskeyAvailability() {1173 const domain = location.hostname.replace(/^www\./, "");1174 if (!domain) return;1175 const sessionKey = `peach_state11_shown:${domain}`;1176 chrome.storage.session?.get(sessionKey).then((stored) => {1177 if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1178 chrome.runtime.sendMessage({1179 type: "GET_PASSKEY_FOR_DOMAIN",1180 payload: { domain },1181 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1182 const data = res?.data;1183 if (!data) return;1184 const current = detectBrowser();1185 const isCrossBrowser =1186 data.browser && current !== "unknown" && data.browser !== current;1187 const valuableOnFirefox = current === "firefox";1188 if (!isCrossBrowser && !valuableOnFirefox) return;1189 chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1190 showPasskeyAvailable({1191 rpId: data.rpId,1192 userName: data.userName,1193 fromBrowser: data.browser,1194 currentBrowser: current,1195 });1196 }).catch(() => {});1197 }).catch(() => {});1198 }11991200 1201 1202 1203 if (document.readyState === "loading") {1204 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1205 } else {1206 setTimeout(checkPasskeyAvailability, 800);1207 }1208}