1import {2 detectCardForm,3 detectLoginFields,4 findOTPDigitBoxGroup,5 findOtpSignalingGroup,6 getDeepActiveInput,7 getPageDomain,8 isAnyCredentialForm,9 isEmailFirstForm,10 isLoginForm,11 isSignupForm,12 isTOTPField,13 isVisible,14} from "./detect";15import {16 type CardSelectorEntry,17 injectFieldIcon,18 type SelectorEntry,19 showAutofillSelector,20 showCardSelector,21 showPasskeyAvailable,22 showPasskeyProGate,23 showPasskeyRegistrationOffer,24 showRememberSiteToast,25 showTotpCopyToast,26 showTOTPSelector,27} from "./inject";28import { detectBrowser } from "../shared/browser";29import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";30import { fillAllowed, fillCardForm, fillFields, fillOTPDigitBoxes, fillTOTPCode, setNativeValue } from "./fill";31import { resolveAutofillInteractionTargets } from "./interaction";32import { setupSaveDetection } from "./save";33import { contentMLDetector } from "./content-ml-detector";34import { detectPasswordPolicy } from "./policy";35import type { FieldPrediction } from "../shared/ml";36import type { VaultEntry } from "../shared/types";373839404142const processedInputs = new WeakMap<HTMLInputElement, () => void>();43const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);4445let currentDismiss: (() => void) | null = null;4647let currentAnchorField: HTMLInputElement | null = null;4849const pendingInteractions = new WeakSet<HTMLInputElement>();50515253let lastDismissedField: HTMLInputElement | null = null;54555657585960const DISMISS_LOCK_MS = 800;61let dismissLock = false;62let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;63646566let passkeySummonActive = false;67686970let passkeyToastActive = false;71function startDismissLock(): void {72 dismissLock = true;73 if (dismissLockTimer) clearTimeout(dismissLockTimer);74 dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);75}76function canOpen(): boolean { return !dismissLock; }7778798081828384858687888990const filledForms = new WeakSet<HTMLFormElement>();91let pageFilledAt: number | null = null;92const PAGE_FILL_GRACE_MS = 3000;9394function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {95 for (const f of fields) {96 if (!f) continue;97 const form = f.closest("form");98 if (form) filledForms.add(form);99 }100 pageFilledAt = Date.now();101}102103export function wasAlreadyFilled(field: HTMLInputElement): boolean {104 const form = field.closest("form");105 if (form && filledForms.has(form)) return true;106 if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;107 return false;108}109110function clearFillStateForExplicitSummon(field: HTMLInputElement): void {111 const form = field.closest("form");112 if (form) filledForms.delete(form);113 pageFilledAt = null;114}115116117118119120function isSubmitButton(el: EventTarget | null): boolean {121 if (!(el instanceof HTMLElement)) return false;122 if (el instanceof HTMLButtonElement && el.type !== "button") return true;123 if (el instanceof HTMLInputElement && el.type === "submit") return true;124 if (el.getAttribute("type") === "submit") return true;125 const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();126 if (!text || text.length > 24) return false;127 return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);128}129130function debounce<T extends (...args: unknown[]) => void>(131 fn: T,132 ms: number133): (...args: Parameters<T>) => void {134 let timer: ReturnType<typeof setTimeout>;135 return (...args: Parameters<T>) => {136 clearTimeout(timer);137 timer = setTimeout(() => fn(...args), ms);138 };139}140141function showToast(message: string): void {142 const toast = document.createElement("div");143 toast.style.cssText = `144 position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);145 background: #131109; color: #F0E8D8; padding: 8px 16px;146 border-radius: 8px; font-family: 'IBM Plex Mono', monospace;147 font-size: 11px; z-index: 2147483647; opacity: 0;148 transition: opacity 200ms ease;149 border: 1px solid rgba(240,232,216,0.07);150 pointer-events: none;151 `;152 toast.textContent = message;153 document.body.appendChild(toast);154 requestAnimationFrame(() => { toast.style.opacity = "1"; });155 setTimeout(() => {156 toast.style.opacity = "0";157 setTimeout(() => toast.remove(), 200);158 }, 2000);159}160161function showSearchPalette(capability?: string): void {162 const host = document.createElement("div");163 host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";164 document.body.appendChild(host);165 const shadow = host.attachShadow({ mode: "closed" });166167 const style = document.createElement("style");168 style.textContent = `169 .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;170 font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;171 box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}172 .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);173 font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}174 .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}175 .s{padding:8px 12px}176 .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);177 border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;178 padding:6px 8px;font-family:inherit;font-size:12px;outline:none}179 .l{max-height:220px;overflow-y:auto}180 .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}181 .e:hover{background:rgba(240,232,216,.06)}182 .et{font-size:12px}183 .eu{font-size:10px;color:rgba(240,232,216,.45)}184 .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}185 `;186187 let allEntries: SelectorEntry[] = [];188 let query = "";189190 const panel = document.createElement("div");191 panel.className = "p";192193 const hdr = document.createElement("div");194 hdr.className = "h";195 const hdrText = document.createElement("span");196 hdrText.textContent = "No form detected — search your vault";197 const closeBtn = document.createElement("button");198 closeBtn.className = "x";199 closeBtn.textContent = "✕";200 hdr.appendChild(hdrText);201 hdr.appendChild(closeBtn);202203 const searchWrap = document.createElement("div");204 searchWrap.className = "s";205 const searchInput = document.createElement("input");206 searchInput.placeholder = "search...";207 searchWrap.appendChild(searchInput);208209 const list = document.createElement("div");210 list.className = "l";211212 panel.appendChild(hdr);213 panel.appendChild(searchWrap);214 panel.appendChild(list);215 shadow.appendChild(style);216 shadow.appendChild(panel);217218 function close() { host.remove(); }219220 closeBtn.onclick = close;221222 function onKeyDown(e: KeyboardEvent) {223 if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }224 }225 document.addEventListener("keydown", onKeyDown, true);226227 function render() {228 const q = query.toLowerCase();229 const filtered = q230 ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))231 : allEntries;232 list.innerHTML = "";233 if (filtered.length === 0) {234 const em = document.createElement("div");235 em.className = "em";236 em.textContent = query ? "no matches" : "vault is empty";237 list.appendChild(em);238 return;239 }240 for (const entry of filtered.slice(0, 20)) {241 const row = document.createElement("div");242 row.className = "e";243 const title = document.createElement("div");244 title.className = "et";245 title.textContent = entry.title;246 row.appendChild(title);247 if (entry.username) {248 const user = document.createElement("div");249 user.className = "eu";250 user.textContent = entry.username;251 row.appendChild(user);252 }253 row.onclick = async () => {254 255 256 const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability } });257 const r = resp as { ok: boolean; data?: { password?: string } };258 if (r.ok && r.data?.password) {259 let alreadyWritten = false;260 try {261 await navigator.clipboard.writeText(r.data.password);262 alreadyWritten = true;263 } catch (err) {264 console.warn("[Peach] clipboard write denied:", err);265 }266 const copyResp = await chrome.runtime.sendMessage({267 type: "COPY",268 payload: { text: r.data.password, label: "Password", alreadyWritten },269 }) as { ok?: boolean } | undefined;270 if (alreadyWritten || copyResp?.ok) {271 showToast("Password copied");272 } else {273 showToast("Could not copy password — clipboard blocked");274 }275 } else {276 showToast("Could not copy password");277 }278 close();279 document.removeEventListener("keydown", onKeyDown, true);280 };281 list.appendChild(row);282 }283 }284285 searchInput.oninput = () => { query = searchInput.value; render(); };286287 288 289 fetchAutofillEntries(getPageDomain(), true, capability).then(result => {290 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }291 allEntries = result.entries;292 render();293 searchInput.focus();294 });295}296297function findTOTPField(root: Document | Element = document): HTMLInputElement | null {298 const inputs = root.querySelectorAll<HTMLInputElement>("input");299 for (const input of inputs) {300 if (isTOTPField(input)) return input;301 }302 return null;303}304305function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {306 const form = passwordEl.closest("form");307 return findTOTPField(form ?? document);308}309310311async function handleAutofill(312 _field: HTMLInputElement,313 usernameEl: HTMLInputElement | null,314 passwordEl: HTMLInputElement | null,315 entry: VaultEntry,316 emailEl?: HTMLInputElement | null317): Promise<{ filledTOTPField: HTMLInputElement | null; gatePassed: boolean }> {318 if (!entry.username && !entry.password && !entry.email) return { filledTOTPField: null, gatePassed: false };319 const pageDomain = getPageDomain();320 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;321 322 323 324 const emailValue = entry.email ?? (entry.username?.includes("@") ? entry.username : "");325 const gatePassed = fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain, emailEl, emailValue);326 let filledTOTPField: HTMLInputElement | null = null;327328 if (entry.canary && gatePassed) {329 chrome.runtime.sendMessage({330 type: "FIRE_CANARY_PING",331 payload: {332 webhookUrl: entry.canary.webhookUrl,333 entryTitle: entry.title,334 trigger: "autofilled",335 },336 }).catch(() => {});337 chrome.runtime.sendMessage({338 type: "UPDATE_ENTRY",339 payload: {340 id: entry.id,341 patch: {342 canary: {343 ...entry.canary,344 lastPinged: Date.now(),345 pingCount: (entry.canary.pingCount ?? 0) + 1,346 },347 },348 },349 }).catch(() => {});350 }351352 353 354 const totpCode = (entry as { totpCode?: string }).totpCode;355 if (totpCode && gatePassed) {356 const code = totpCode;357 const totpField = passwordEl ? findSameLoginTOTPField(passwordEl) : null;358 if (fillTOTPCode(totpField, code, form, pageDomain)) {359 filledTOTPField = totpField;360 }361 let alreadyWritten = false;362 try {363 await navigator.clipboard.writeText(code);364 alreadyWritten = true;365 } catch (err) {366 console.warn("[Peach] clipboard write denied:", err);367 }368 const response = await chrome.runtime.sendMessage({369 type: "COPY",370 payload: { text: code, label: "TOTP", alreadyWritten },371 });372 const res = response as { ok?: boolean; clearSeconds?: number };373 if (filledTOTPField) {374 showToast("2FA code filled");375 } else if (alreadyWritten || res.ok) {376 377 378 379 380 showTotpCopyToast(res.clearSeconds ?? 30);381 } else {382 showToast("Could not copy TOTP — clipboard blocked");383 }384 }385386 return { filledTOTPField, gatePassed };387}388389async function fetchAutofillEntries(390 domain: string,391 includeAll = false,392 capability?: string393): Promise<{ entries: SelectorEntry[]; locked: boolean }> {394 const response = await chrome.runtime.sendMessage({395 type: "AUTOFILL_QUERY",396 payload: { domain, includeAll, capability },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}404405async function fetchTOTPEntries(406 domain: string,407 capability?: string,408): Promise<{ entries: SelectorEntry[]; locked: boolean }> {409 const response = await chrome.runtime.sendMessage({410 type: "AUTOFILL_QUERY",411 payload: { domain, kind: "totp", capability },412 });413 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };414 if (!res.ok && res.error === "vault_locked") {415 return { entries: [], locked: true };416 }417 return { entries: res.data ?? [], locked: false };418}419420421function resolveAutofillFieldType(422 el: HTMLInputElement,423 predictedType?: FieldPrediction["type"] | null424): "password" | "username" | "email" | null {425 if (426 predictedType === "password" ||427 predictedType === "username" ||428 predictedType === "email"429 ) {430 return predictedType;431 }432433 const detected = detectLoginFields().find((field) => field.el === el)?.type;434 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {435 return detected;436 }437438 const htmlType = el.type.toLowerCase();439 if (htmlType === "password") return "password";440 if (htmlType === "email") return "email";441 return null;442}443444async function openAutofillSelector(445 anchorField: HTMLInputElement,446 usernameEl: HTMLInputElement | null,447 passwordEl: HTMLInputElement | null,448 domainEntries: SelectorEntry[],449 loadSearchableEntries: () => Promise<SelectorEntry[]>,450 domain: string,451 identityKind: "email" | "username",452 emailEl?: HTMLInputElement | null,453 capability?: string,454): Promise<void> {455 456 457 const isSignup = domainEntries.length === 0;458 let confirmEl: HTMLInputElement | null = null;459 if (isSignup) {460 const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body;461 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));462 confirmEl = allPwInputs.find(463 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)464 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);465 }466467 currentDismiss?.();468 currentAnchorField = anchorField;469 currentDismiss = showAutofillSelector(470 anchorField,471 domainEntries,472 async (id: string) => {473 currentDismiss = null;474 currentAnchorField = null;475 const entryResponse = await chrome.runtime.sendMessage({476 type: "GET_ENTRY_FOR_FILL",477 payload: { id, capability },478 });479 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;480 if (entry) {481 const { filledTOTPField, gatePassed } = await handleAutofill(anchorField, usernameEl, passwordEl, entry, emailEl);482 if (gatePassed) recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);483 484 485 486 const pageDomain = location.hostname.replace(/^www\./, "");487 const entryDomains = new Set<string>();488 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {489 try {490 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));491 } catch { }492 }493 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {494 showRememberSiteToast(pageDomain, entry.id);495 }496 }497 },498 {499 domain,500 capability,501 loadSearchableEntries,502 isSignup,503 identityKind,504 hasEmailField: !!emailEl,505 onFillFields: (username, password, email) => {506 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;507 if (!fillFields(usernameEl, passwordEl, username, password, form, getPageDomain(), emailEl, email)) return;508 if (password && confirmEl) setNativeValue(confirmEl, password);509 recordFillSuccess(anchorField, usernameEl, passwordEl);510 },511 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },512 }513 );514}515516async function openTOTPSelector(517 anchorField: HTMLInputElement,518 otpDigitBoxes?: HTMLInputElement[],519 capability?: string,520): Promise<void> {521 if (!canOpen()) return;522 if (currentDismiss && currentAnchorField === anchorField) return;523 if (anchorField !== lastDismissedField) lastDismissedField = null;524 if (anchorField === lastDismissedField) return;525 if (wasAlreadyFilled(anchorField)) return;526527 const domain = getPageDomain();528 const result = await fetchTOTPEntries(domain, capability);529530 if (result.locked) {531 currentDismiss?.();532 currentAnchorField = anchorField;533 currentDismiss = showAutofillSelector(534 anchorField,535 [],536 () => {},537 {538 domain,539 locked: true,540 onUnlocked: () => void openTOTPSelector(anchorField),541 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },542 }543 );544 return;545 }546547 if (result.entries.length === 0) {548 lastDismissedField = anchorField;549 startDismissLock();550 showToast("No 2FA entries for this site — add a code in Peach first");551 return;552 }553554 currentDismiss?.();555 currentAnchorField = anchorField;556 currentDismiss = showTOTPSelector(557 anchorField,558 result.entries,559 async (id: string) => {560 try {561 const entryResponse = await chrome.runtime.sendMessage({562 type: "GET_ENTRY_FOR_FILL",563 payload: { id, capability },564 }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;565 const entry = entryResponse?.ok ? entryResponse.data : undefined;566 const code = (entry as { totpCode?: string } | undefined)?.totpCode;567 if (!code) return;568 if (!fillAllowed(anchorField.closest("form"), getPageDomain())) return;569 if (otpDigitBoxes && otpDigitBoxes.length > 1) {570 fillOTPDigitBoxes(otpDigitBoxes, code);571 } else {572 setNativeValue(anchorField, code);573 }574 recordFillSuccess(anchorField);575 showToast("2FA code filled");576 } finally {577 currentDismiss = null;578 currentAnchorField = null;579 }580 },581 {582 domain,583 onDismiss: () => {584 lastDismissedField = anchorField;585 startDismissLock();586 currentDismiss = null;587 currentAnchorField = null;588 },589 }590 );591}592593594export async function handleFieldInteraction(595 anchorField?: HTMLInputElement | null,596 explicitSummon = false,597 capability?: string598): Promise<void> {599 const field = anchorField ?? getDeepActiveInput();600 if (!field) return;601 if (!isVisible(field)) return;602603 604 if (passkeyToastActive) return;605606 607 608 if (!canOpen()) return;609610 611 if (currentDismiss && currentAnchorField === field) return;612613 614 615 if (field !== lastDismissedField) lastDismissedField = null;616 617 618 if (field === lastDismissedField) return;619620 621 622 623 624 if (wasAlreadyFilled(field)) return;625626 627 628 if (pendingInteractions.has(field)) return;629 pendingInteractions.add(field);630631 try {632 633 634 635 636 637 const otpGroup = findOTPDigitBoxGroup(field) ?? findOtpSignalingGroup(field);638 if (otpGroup) {639 await openTOTPSelector(otpGroup[0]!, otpGroup, capability);640 return;641 }642643 if (isTOTPField(field)) {644 const formFields = detectLoginFields();645 if (!isLoginForm(formFields) && !isSignupForm(formFields)) {646 await openTOTPSelector(field, undefined, capability);647 return;648 }649 }650651 const fieldType = field.type.toLowerCase();652653 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {654 return preds[0] ?? null;655 });656657 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {658 const timeout = setTimeout(() => resolve(null), 150);659 mlPromise.then((pred) => {660 clearTimeout(timeout);661 resolve(pred);662 });663 });664665 if (passkeyToastActive) return;666667 if (!explicitSummon && fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {668 return;669 }670671 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);672 if (autofillFieldType) {673 reattachListeners(field, autofillFieldType);674 }675676 const fields = detectLoginFields();677 const targets = resolveAutofillInteractionTargets(field, fields, explicitSummon);678 if (!targets.shouldOpen) {679 return;680 }681682 const domain = getPageDomain();683 const commandAuthorized = explicitSummon && capability !== undefined;684 const firstResult = await fetchAutofillEntries(685 domain,686 commandAuthorized,687 commandAuthorized ? capability : undefined,688 );689 if (passkeyToastActive) return;690691 692 693 694 if (firstResult.locked) {695 currentDismiss?.();696 currentAnchorField = field;697 currentDismiss = showAutofillSelector(698 field,699 [],700 () => {},701 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }702 );703 return;704 }705706 const entries = firstResult.entries;707 708 709 710 711 712 713 const loadSearchableEntries = async (): Promise<SelectorEntry[]> =>714 commandAuthorized715 ? entries716 : (await fetchAutofillEntries(domain)).entries;717718 if (passkeyToastActive) return;719720 const pwField = fields.find((f) => f.type === "password");721 722 if (!explicitSummon && !pwField && !isEmailFirstForm(fields)) return;723 const usernameEl = targets.usernameEl;724 const passwordEl = targets.passwordEl;725 const emailEl = targets.emailEl;726727 await openAutofillSelector(728 field,729 usernameEl,730 passwordEl,731 entries,732 loadSearchableEntries,733 domain,734 autofillFieldType === "email" ? "email" : "username",735 emailEl,736 commandAuthorized ? capability : undefined,737 );738 } finally {739 pendingInteractions.delete(field);740 }741}742743async function onFocusIn(e: Event): Promise<void> {744 745 746 747 748 749 if (isSubmitButton(e.target)) return;750 await handleFieldInteraction();751}752753function reattachListeners(754 el: HTMLInputElement,755 detectedType?: "password" | "username" | "email",756 contextFields?: ReturnType<typeof detectLoginFields>757): void {758 if (processedInputs.has(el)) return;759 if (!resolveAutofillFieldType(el, detectedType)) return;760 761 const fields = contextFields ?? detectLoginFields();762 if (!isAnyCredentialForm(fields)) return;763764 const cleanup = injectFieldIcon(el, () => {765 currentDismiss?.();766 currentDismiss = null;767 lastDismissedField = null; 768 dismissLock = false; 769 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }770 clearFillStateForExplicitSummon(el);771 el.focus({ preventScroll: true });772 void handleFieldInteraction(el, true);773 });774 processedInputs.set(el, cleanup);775}776777const debouncedReattach = debounce(() => {778 const allFields = detectLoginFields();779 if (!isAnyCredentialForm(allFields)) return;780 const newFields = allFields.filter(781 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)782 );783 for (const f of newFields) {784 reattachListeners(f.el, f.type, allFields);785 }786 787 788 789}, 200);790791function setupMutationObserver(): void {792 const observer = new MutationObserver(debouncedReattach);793 observer.observe(document.body, {794 childList: true,795 subtree: true,796 attributes: true,797 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],798 });799}800801export function initialScan(aggressionLevel = 0, isFinalPass = false) {802 const allFields = detectLoginFields();803 const hasKnownForm = isAnyCredentialForm(allFields);804805 if (aggressionLevel === 0 && !hasKnownForm) return;806807 const newFields = allFields.filter(808 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)809 );810811 for (const f of newFields) {812 reattachListeners(f.el, f.type, allFields);813 }814815 816 817 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {818 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');819 for (const el of pwInputs) {820 if (isVisible(el) && !processedInputs.has(el)) {821 const cleanup = injectFieldIcon(el, () => {822 currentDismiss?.();823 currentDismiss = null;824 lastDismissedField = null;825 dismissLock = false;826 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }827 clearFillStateForExplicitSummon(el);828 el.focus({ preventScroll: true });829 void handleFieldInteraction(el, true);830 });831 processedInputs.set(el, cleanup);832 }833 }834 }835}836837838839export const _testSeam = {840 getLastDismissedField(): HTMLInputElement | null { return lastDismissedField; },841 setLastDismissedField(f: HTMLInputElement | null): void { lastDismissedField = f; },842 isDismissLocked(): boolean { return dismissLock; },843 DISMISS_LOCK_MS,844} as const;845846847848849850const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();851852function hasLoginOrSignupForm(): boolean {853 const fields = detectLoginFields();854 return isAnyCredentialForm(fields);855}856857function injectTOTPFieldIcon(858 field: HTMLInputElement,859 otpDigitBoxes?: HTMLInputElement[]860): void {861 if (processedTOTPInputs.has(field)) return;862 const cleanup = injectFieldIcon(field, () => {863 currentDismiss?.();864 currentDismiss = null;865 currentAnchorField = null;866 lastDismissedField = null;867 dismissLock = false;868 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }869 clearFillStateForExplicitSummon(field);870 field.focus({ preventScroll: true });871 void openTOTPSelector(field, otpDigitBoxes);872 });873 processedTOTPInputs.set(field, cleanup);874}875876877878879880function resolveTOTPIconTarget(881 field: HTMLInputElement882): { anchor: HTMLInputElement; group?: HTMLInputElement[] } {883 const group = findOtpSignalingGroup(field);884 if (group) return { anchor: group[0]!, group };885 return { anchor: field };886}887888export function scanTOTPFields(): void {889 if (hasLoginOrSignupForm()) return;890 const inputs = document.querySelectorAll<HTMLInputElement>("input");891 for (const input of inputs) {892 if (!isTOTPField(input)) continue;893 const { anchor, group } = resolveTOTPIconTarget(input);894 injectTOTPFieldIcon(anchor, group);895 }896}897898function setupTOTPAutofill(): void {899 setTimeout(scanTOTPFields, 0);900 setTimeout(scanTOTPFields, 500);901 setTimeout(scanTOTPFields, 1500);902903 const debouncedScan = debounce(scanTOTPFields, 200);904 new MutationObserver(debouncedScan).observe(document.body, {905 childList: true,906 subtree: true,907 attributes: true,908 attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],909 });910911 document.addEventListener("focusin", (e) => {912 const target = e.target;913 if (!(target instanceof HTMLInputElement)) return;914 if (hasLoginOrSignupForm()) return;915 if (!isTOTPField(target)) return;916 const { anchor, group } = resolveTOTPIconTarget(target);917 injectTOTPFieldIcon(anchor, group);918 }, true);919}920921document.addEventListener("focusin", onFocusIn);922923setupMutationObserver();924setupTOTPAutofill();925setupSaveDetection();926setupCardAutofill();927928929930931932933934935let lastObservedUrl = globalThis.location.href;936new MutationObserver(() => {937 const currentUrl = globalThis.location?.href;938 if (!currentUrl || currentUrl === lastObservedUrl) return;939 lastObservedUrl = currentUrl;940 pageFilledAt = null;941}).observe(document.body, { childList: true, subtree: false });942943944945(async () => {946 let aggressionLevel = 0;947 try {948 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });949 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;950 const domain = getPageDomain();951 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;952 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;953 } catch { }954955 setTimeout(() => initialScan(aggressionLevel, false), 0);956 setTimeout(() => initialScan(aggressionLevel, false), 500);957 setTimeout(() => initialScan(aggressionLevel, true), 1500);958})();959960961962963964965const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();966let currentCardDismiss: (() => void) | null = null;967let currentCardAnchor: HTMLInputElement | null = null;968let lastDismissedCardField: HTMLInputElement | null = null;969970async function fetchSavedCards(capability?: string): Promise<CardSelectorEntry[]> {971 const resp = await chrome.runtime.sendMessage({972 type: "AUTOFILL_QUERY",973 payload: { domain: getPageDomain(), kind: "card", capability },974 }).catch(() => null);975 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;976 return r?.ok ? (r.data ?? []) : [];977}978979async function openCardSelector(anchor: HTMLInputElement, capability?: string): Promise<void> {980 if (!canOpen()) return;981 if (currentCardDismiss && currentCardAnchor === anchor) return;982 if (anchor === lastDismissedCardField) return;983 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;984 if (wasAlreadyFilled(anchor)) return;985986 const cards = await fetchSavedCards(capability);987 if (cards.length === 0) return; 988989 const cardForm = detectCardForm();990 if (!cardForm?.number) return;991992 currentCardDismiss?.();993 currentCardAnchor = anchor;994 currentCardDismiss = showCardSelector(995 anchor,996 cards,997 {998 domain: getPageDomain(),999 capability,1000 onFill: (entry) => {1001 if (!cardForm) return;1002 fillCardForm(cardForm, {1003 cardNumber: entry.cardNumber ?? "",1004 expMonth: entry.expMonth ?? "",1005 expYear: entry.expYear ?? "",1006 cvc: entry.cvc ?? "",1007 cardholderName: entry.cardholderName ?? "",1008 });1009 1010 1011 1012 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);1013 currentCardDismiss = null;1014 currentCardAnchor = null;1015 },1016 onDismiss: () => {1017 lastDismissedCardField = anchor;1018 startDismissLock();1019 currentCardDismiss = null;1020 currentCardAnchor = null;1021 },1022 }1023 );1024}10251026function injectCardIcon(field: HTMLInputElement): void {1027 if (processedCardInputs.has(field)) return;1028 const cleanup = injectFieldIcon(field, () => {1029 currentCardDismiss?.();1030 currentCardDismiss = null;1031 lastDismissedCardField = null;1032 dismissLock = false;1033 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1034 clearFillStateForExplicitSummon(field);1035 field.focus({ preventScroll: true });1036 void openCardSelector(field);1037 });1038 processedCardInputs.set(field, cleanup);1039}10401041function setupCardAutofill(): void {1042 function scan() {1043 const cardForm = detectCardForm();1044 if (!cardForm?.number) return;1045 if (!isVisible(cardForm.number)) return;1046 injectCardIcon(cardForm.number);1047 }10481049 1050 1051 setTimeout(scan, 0);1052 setTimeout(scan, 500);1053 setTimeout(scan, 1500);10541055 1056 1057 1058 let pending = false;1059 new MutationObserver(() => {1060 if (pending) return;1061 pending = true;1062 setTimeout(() => { pending = false; scan(); }, 200);1063 }).observe(document.body, { childList: true, subtree: true });10641065 1066 1067 1068 document.addEventListener("focusin", (e) => {1069 const target = e.target;1070 if (!(target instanceof HTMLInputElement)) return;1071 const cardForm = detectCardForm();1072 if (cardForm?.number === target) {1073 injectCardIcon(target);1074 }1075 }, true);1076}10771078chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {1079 1080 if (sender.id !== chrome.runtime.id) return;1081 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {1082 const policy = detectPasswordPolicy();1083 sendResponse({ ok: true, data: policy });1084 return true;1085 }1086 if (msg?.type === "PING") {1087 sendResponse({ ok: true });1088 return true;1089 }1090 if (msg?.type === "SUMMON_AUTOFILL") {1091 const source = (msg as { type: string; source?: string; capability?: string }).source;1092 const capability = (msg as { capability?: string }).capability;1093 const isShortcut = source === "shortcut";1094 const isPasskeyUnlock = source === "passkey-unlock";10951096 const activeInput = getDeepActiveInput();1097 const fields = detectLoginFields();1098 const hasForm = isAnyCredentialForm(fields);1099 const cardForm = detectCardForm();11001101 if (hasForm) {1102 1103 1104 const inForm = activeInput && fields.some(f => f.el === activeInput);1105 const target = inForm1106 ? activeInput1107 : (fields.find(f => f.type === "password")?.el1108 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1109 if (target) {1110 1111 1112 clearFillStateForExplicitSummon(target);1113 dismissLock = false;1114 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1115 lastDismissedField = null;1116 void handleFieldInteraction(target, true, capability);1117 }1118 } else if (isShortcut && cardForm?.number) {1119 clearFillStateForExplicitSummon(cardForm.number);1120 dismissLock = false;1121 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1122 lastDismissedCardField = null;1123 void openCardSelector(cardForm.number, capability);1124 } else if (isPasskeyUnlock) {1125 1126 1127 1128 const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1129 ? document.activeElement as unknown as HTMLInputElement1130 : null;1131 if (anchor) {1132 currentDismiss?.();1133 currentAnchorField = null;1134 passkeySummonActive = true;1135 currentDismiss = showAutofillSelector(anchor, [], () => {}, {1136 domain: getPageDomain(),1137 locked: true,1138 onDismiss: () => { passkeySummonActive = false; },1139 });1140 }1141 } else if (isShortcut) {1142 1143 showSearchPalette(capability);1144 }11451146 1147 if (isShortcut) {1148 const domain = getPageDomain();1149 if (domain) {1150 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1151 }1152 }11531154 sendResponse({ ok: hasForm || Boolean(cardForm?.number) || isShortcut || isPasskeyUnlock });1155 return true;1156 }1157 if (msg?.type === "PASSKEY_PRO_GATE") {1158 1159 1160 showPasskeyProGate();1161 sendResponse({ ok: true });1162 return true;1163 }1164 if (msg?.type === "SHOW_PASSKEY_TOAST") {1165 1166 passkeyToastActive = true;1167 if (currentDismiss) {1168 currentDismiss();1169 currentDismiss = null;1170 currentAnchorField = null;1171 }1172 return false; 1173 }1174 if (msg?.type === "DISMISS_PASSKEY_TOAST") {1175 passkeyToastActive = false;1176 return false; 1177 }1178 if (msg?.type === "VAULT_UNLOCKED") {1179 if (passkeySummonActive) {1180 1181 1182 passkeySummonActive = false;1183 if (currentDismiss) {1184 currentDismiss();1185 currentDismiss = null;1186 currentAnchorField = null;1187 }1188 sendResponse({ ok: true });1189 return true;1190 }1191 1192 1193 const savedField = currentAnchorField;1194 if (currentDismiss) {1195 currentDismiss();1196 currentDismiss = null;1197 currentAnchorField = null;1198 }1199 void handleFieldInteraction(savedField ?? undefined);1200 sendResponse({ ok: true });1201 return true;1202 }1203 return true;1204});1205120612071208window.addEventListener("message", (e: MessageEvent) => {1209 1210 1211 if (e.source !== window) return;1212 const d = e.data as { source?: string; type?: string } | undefined;1213 if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {1214 passkeyToastActive = false;1215 }1216});1217121812191220122112221223122412251226122712281229if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {1230 let lastPasskeyOfferAt = 0;1231 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;12321233 window.addEventListener("message", (event: MessageEvent) => {1234 if (event.source !== window) return;1235 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;1236 if (!data || data.source !== "peach-passkey-firefox") return;1237 if (detectBrowser() !== "firefox") return;1238 if (data.type !== "create") return;12391240 1241 1242 const now = Date.now();1243 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1244 lastPasskeyOfferAt = now;12451246 const domain = location.hostname.replace(/^www\./, "");1247 chrome.runtime.sendMessage({1248 type: "GET_PASSKEY_OFFER_DECLINED",1249 payload: { domain },1250 }).then((res: { ok: boolean; data?: boolean } | undefined) => {1251 if (res?.data === true) return;1252 const rpId = data.rpId ?? domain;1253 showPasskeyRegistrationOffer({1254 rpId,1255 rpName: data.rpName,1256 userName: data.userName,1257 userDisplayName: data.userDisplayName,1258 });1259 }).catch(() => {});1260 });1261}1262126312641265126612671268126912701271127212731274127512761277{1278 function checkPasskeyAvailability() {1279 const domain = location.hostname.replace(/^www\./, "");1280 if (!domain) return;1281 chrome.runtime.sendMessage({1282 type: "GET_PASSKEY_FOR_DOMAIN",1283 payload: { domain },1284 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox"; bannerShown?: boolean } | null } | undefined) => {1285 const data = res?.data;1286 if (!data || data.bannerShown) return;1287 const current = detectBrowser();1288 const isCrossBrowser =1289 data.browser && current !== "unknown" && data.browser !== current;1290 const valuableOnFirefox = current === "firefox";1291 if (!isCrossBrowser && !valuableOnFirefox) return;1292 chrome.runtime.sendMessage({1293 type: "MARK_PASSKEY_BANNER_SHOWN",1294 payload: { domain },1295 }).catch(() => {});1296 showPasskeyAvailable({1297 rpId: data.rpId,1298 userName: data.userName,1299 fromBrowser: data.browser,1300 currentBrowser: current,1301 });1302 }).catch(() => {});1303 }13041305 1306 1307 1308 if (document.readyState === "loading") {1309 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1310 } else {1311 setTimeout(checkPasskeyAvailability, 800);1312 }1313}