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 { SavedIdentity, 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 458 const isSignup = domainEntries.length === 0;459 let savedIdentities: SavedIdentity[] | undefined;460 let confirmEl: HTMLInputElement | null = null;461 if (isSignup) {462 try {463 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as464 { ok: boolean; data?: SavedIdentity[] } | null;465 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;466 } catch { }467468 const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body;469 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));470 confirmEl = allPwInputs.find(471 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)472 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);473 }474475 currentDismiss?.();476 currentAnchorField = anchorField;477 currentDismiss = showAutofillSelector(478 anchorField,479 domainEntries,480 async (id: string) => {481 currentDismiss = null;482 currentAnchorField = null;483 const entryResponse = await chrome.runtime.sendMessage({484 type: "GET_ENTRY_FOR_FILL",485 payload: { id, capability },486 });487 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;488 if (entry) {489 const { filledTOTPField, gatePassed } = await handleAutofill(anchorField, usernameEl, passwordEl, entry, emailEl);490 if (gatePassed) recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);491 492 493 494 const pageDomain = location.hostname.replace(/^www\./, "");495 const entryDomains = new Set<string>();496 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {497 try {498 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));499 } catch { }500 }501 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {502 showRememberSiteToast(pageDomain, entry.id);503 }504 }505 },506 {507 domain,508 capability,509 loadSearchableEntries,510 isSignup,511 identityKind,512 hasEmailField: !!emailEl,513 savedIdentities,514 onFillFields: (username, password, email) => {515 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;516 if (!fillFields(usernameEl, passwordEl, username, password, form, getPageDomain(), emailEl, email)) return;517 if (password && confirmEl) setNativeValue(confirmEl, password);518 recordFillSuccess(anchorField, usernameEl, passwordEl);519 },520 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },521 }522 );523}524525async function openTOTPSelector(526 anchorField: HTMLInputElement,527 otpDigitBoxes?: HTMLInputElement[],528 capability?: string,529): Promise<void> {530 if (!canOpen()) return;531 if (currentDismiss && currentAnchorField === anchorField) return;532 if (anchorField !== lastDismissedField) lastDismissedField = null;533 if (anchorField === lastDismissedField) return;534 if (wasAlreadyFilled(anchorField)) return;535536 const domain = getPageDomain();537 const result = await fetchTOTPEntries(domain, capability);538539 if (result.locked) {540 currentDismiss?.();541 currentAnchorField = anchorField;542 currentDismiss = showAutofillSelector(543 anchorField,544 [],545 () => {},546 {547 domain,548 locked: true,549 onUnlocked: () => void openTOTPSelector(anchorField),550 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },551 }552 );553 return;554 }555556 if (result.entries.length === 0) {557 lastDismissedField = anchorField;558 startDismissLock();559 showToast("No 2FA entries for this site — add a code in Peach first");560 return;561 }562563 currentDismiss?.();564 currentAnchorField = anchorField;565 currentDismiss = showTOTPSelector(566 anchorField,567 result.entries,568 async (id: string) => {569 try {570 const entryResponse = await chrome.runtime.sendMessage({571 type: "GET_ENTRY_FOR_FILL",572 payload: { id, capability },573 }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;574 const entry = entryResponse?.ok ? entryResponse.data : undefined;575 const code = (entry as { totpCode?: string } | undefined)?.totpCode;576 if (!code) return;577 if (!fillAllowed(anchorField.closest("form"), getPageDomain())) return;578 if (otpDigitBoxes && otpDigitBoxes.length > 1) {579 fillOTPDigitBoxes(otpDigitBoxes, code);580 } else {581 setNativeValue(anchorField, code);582 }583 recordFillSuccess(anchorField);584 showToast("2FA code filled");585 } finally {586 currentDismiss = null;587 currentAnchorField = null;588 }589 },590 {591 domain,592 onDismiss: () => {593 lastDismissedField = anchorField;594 startDismissLock();595 currentDismiss = null;596 currentAnchorField = null;597 },598 }599 );600}601602603export async function handleFieldInteraction(604 anchorField?: HTMLInputElement | null,605 explicitSummon = false,606 capability?: string607): Promise<void> {608 const field = anchorField ?? getDeepActiveInput();609 if (!field) return;610 if (!isVisible(field)) return;611612 613 if (passkeyToastActive) return;614615 616 617 if (!canOpen()) return;618619 620 if (currentDismiss && currentAnchorField === field) return;621622 623 624 if (field !== lastDismissedField) lastDismissedField = null;625 626 627 if (field === lastDismissedField) return;628629 630 631 632 633 if (wasAlreadyFilled(field)) return;634635 636 637 if (pendingInteractions.has(field)) return;638 pendingInteractions.add(field);639640 try {641 642 643 644 645 646 const otpGroup = findOTPDigitBoxGroup(field) ?? findOtpSignalingGroup(field);647 if (otpGroup) {648 await openTOTPSelector(otpGroup[0]!, otpGroup, capability);649 return;650 }651652 if (isTOTPField(field)) {653 const formFields = detectLoginFields();654 if (!isLoginForm(formFields) && !isSignupForm(formFields)) {655 await openTOTPSelector(field, undefined, capability);656 return;657 }658 }659660 const fieldType = field.type.toLowerCase();661662 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {663 return preds[0] ?? null;664 });665666 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {667 const timeout = setTimeout(() => resolve(null), 150);668 mlPromise.then((pred) => {669 clearTimeout(timeout);670 resolve(pred);671 });672 });673674 if (passkeyToastActive) return;675676 if (!explicitSummon && fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {677 return;678 }679680 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);681 if (autofillFieldType) {682 reattachListeners(field, autofillFieldType);683 }684685 const fields = detectLoginFields();686 const targets = resolveAutofillInteractionTargets(field, fields, explicitSummon);687 if (!targets.shouldOpen) {688 return;689 }690691 const domain = getPageDomain();692 const commandAuthorized = explicitSummon && capability !== undefined;693 const firstResult = await fetchAutofillEntries(694 domain,695 commandAuthorized,696 commandAuthorized ? capability : undefined,697 );698 if (passkeyToastActive) return;699700 701 702 703 if (firstResult.locked) {704 currentDismiss?.();705 currentAnchorField = field;706 currentDismiss = showAutofillSelector(707 field,708 [],709 () => {},710 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }711 );712 return;713 }714715 const entries = firstResult.entries;716 717 718 719 720 721 722 const loadSearchableEntries = async (): Promise<SelectorEntry[]> =>723 commandAuthorized724 ? entries725 : (await fetchAutofillEntries(domain)).entries;726727 if (passkeyToastActive) return;728729 const pwField = fields.find((f) => f.type === "password");730 731 if (!explicitSummon && !pwField && !isEmailFirstForm(fields)) return;732 const usernameEl = targets.usernameEl;733 const passwordEl = targets.passwordEl;734 const emailEl = targets.emailEl;735736 await openAutofillSelector(737 field,738 usernameEl,739 passwordEl,740 entries,741 loadSearchableEntries,742 domain,743 autofillFieldType === "email" ? "email" : "username",744 emailEl,745 commandAuthorized ? capability : undefined,746 );747 } finally {748 pendingInteractions.delete(field);749 }750}751752async function onFocusIn(e: Event): Promise<void> {753 754 755 756 757 758 if (isSubmitButton(e.target)) return;759 await handleFieldInteraction();760}761762function reattachListeners(763 el: HTMLInputElement,764 detectedType?: "password" | "username" | "email",765 contextFields?: ReturnType<typeof detectLoginFields>766): void {767 if (processedInputs.has(el)) return;768 if (!resolveAutofillFieldType(el, detectedType)) return;769 770 const fields = contextFields ?? detectLoginFields();771 if (!isAnyCredentialForm(fields)) return;772773 const cleanup = injectFieldIcon(el, () => {774 currentDismiss?.();775 currentDismiss = null;776 lastDismissedField = null; 777 dismissLock = false; 778 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }779 clearFillStateForExplicitSummon(el);780 el.focus({ preventScroll: true });781 void handleFieldInteraction(el, true);782 });783 processedInputs.set(el, cleanup);784}785786const debouncedReattach = debounce(() => {787 const allFields = detectLoginFields();788 if (!isAnyCredentialForm(allFields)) return;789 const newFields = allFields.filter(790 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)791 );792 for (const f of newFields) {793 reattachListeners(f.el, f.type, allFields);794 }795 796 797 798}, 200);799800function setupMutationObserver(): void {801 const observer = new MutationObserver(debouncedReattach);802 observer.observe(document.body, {803 childList: true,804 subtree: true,805 attributes: true,806 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],807 });808}809810export function initialScan(aggressionLevel = 0, isFinalPass = false) {811 const allFields = detectLoginFields();812 const hasKnownForm = isAnyCredentialForm(allFields);813814 if (aggressionLevel === 0 && !hasKnownForm) return;815816 const newFields = allFields.filter(817 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)818 );819820 for (const f of newFields) {821 reattachListeners(f.el, f.type, allFields);822 }823824 825 826 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {827 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');828 for (const el of pwInputs) {829 if (isVisible(el) && !processedInputs.has(el)) {830 const cleanup = injectFieldIcon(el, () => {831 currentDismiss?.();832 currentDismiss = null;833 lastDismissedField = null;834 dismissLock = false;835 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }836 clearFillStateForExplicitSummon(el);837 el.focus({ preventScroll: true });838 void handleFieldInteraction(el, true);839 });840 processedInputs.set(el, cleanup);841 }842 }843 }844}845846847848export const _testSeam = {849 getLastDismissedField(): HTMLInputElement | null { return lastDismissedField; },850 setLastDismissedField(f: HTMLInputElement | null): void { lastDismissedField = f; },851 isDismissLocked(): boolean { return dismissLock; },852 DISMISS_LOCK_MS,853} as const;854855856857858859const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();860861function hasLoginOrSignupForm(): boolean {862 const fields = detectLoginFields();863 return isAnyCredentialForm(fields);864}865866function injectTOTPFieldIcon(867 field: HTMLInputElement,868 otpDigitBoxes?: HTMLInputElement[]869): void {870 if (processedTOTPInputs.has(field)) return;871 const cleanup = injectFieldIcon(field, () => {872 currentDismiss?.();873 currentDismiss = null;874 currentAnchorField = null;875 lastDismissedField = null;876 dismissLock = false;877 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }878 clearFillStateForExplicitSummon(field);879 field.focus({ preventScroll: true });880 void openTOTPSelector(field, otpDigitBoxes);881 });882 processedTOTPInputs.set(field, cleanup);883}884885886887888889function resolveTOTPIconTarget(890 field: HTMLInputElement891): { anchor: HTMLInputElement; group?: HTMLInputElement[] } {892 const group = findOtpSignalingGroup(field);893 if (group) return { anchor: group[0]!, group };894 return { anchor: field };895}896897export function scanTOTPFields(): void {898 if (hasLoginOrSignupForm()) return;899 const inputs = document.querySelectorAll<HTMLInputElement>("input");900 for (const input of inputs) {901 if (!isTOTPField(input)) continue;902 const { anchor, group } = resolveTOTPIconTarget(input);903 injectTOTPFieldIcon(anchor, group);904 }905}906907function setupTOTPAutofill(): void {908 setTimeout(scanTOTPFields, 0);909 setTimeout(scanTOTPFields, 500);910 setTimeout(scanTOTPFields, 1500);911912 const debouncedScan = debounce(scanTOTPFields, 200);913 new MutationObserver(debouncedScan).observe(document.body, {914 childList: true,915 subtree: true,916 attributes: true,917 attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],918 });919920 document.addEventListener("focusin", (e) => {921 const target = e.target;922 if (!(target instanceof HTMLInputElement)) return;923 if (hasLoginOrSignupForm()) return;924 if (!isTOTPField(target)) return;925 const { anchor, group } = resolveTOTPIconTarget(target);926 injectTOTPFieldIcon(anchor, group);927 }, true);928}929930document.addEventListener("focusin", onFocusIn);931932setupMutationObserver();933setupTOTPAutofill();934setupSaveDetection();935setupCardAutofill();936937938939940941942943944let lastObservedUrl = globalThis.location.href;945new MutationObserver(() => {946 const currentUrl = globalThis.location?.href;947 if (!currentUrl || currentUrl === lastObservedUrl) return;948 lastObservedUrl = currentUrl;949 pageFilledAt = null;950}).observe(document.body, { childList: true, subtree: false });951952953954(async () => {955 let aggressionLevel = 0;956 try {957 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });958 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;959 const domain = getPageDomain();960 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;961 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;962 } catch { }963964 setTimeout(() => initialScan(aggressionLevel, false), 0);965 setTimeout(() => initialScan(aggressionLevel, false), 500);966 setTimeout(() => initialScan(aggressionLevel, true), 1500);967})();968969970971972973974const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();975let currentCardDismiss: (() => void) | null = null;976let currentCardAnchor: HTMLInputElement | null = null;977let lastDismissedCardField: HTMLInputElement | null = null;978979async function fetchSavedCards(capability?: string): Promise<CardSelectorEntry[]> {980 const resp = await chrome.runtime.sendMessage({981 type: "AUTOFILL_QUERY",982 payload: { domain: getPageDomain(), kind: "card", capability },983 }).catch(() => null);984 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;985 return r?.ok ? (r.data ?? []) : [];986}987988async function openCardSelector(anchor: HTMLInputElement, capability?: string): Promise<void> {989 if (!canOpen()) return;990 if (currentCardDismiss && currentCardAnchor === anchor) return;991 if (anchor === lastDismissedCardField) return;992 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;993 if (wasAlreadyFilled(anchor)) return;994995 const cards = await fetchSavedCards(capability);996 if (cards.length === 0) return; 997998 const cardForm = detectCardForm();999 if (!cardForm?.number) return;10001001 currentCardDismiss?.();1002 currentCardAnchor = anchor;1003 currentCardDismiss = showCardSelector(1004 anchor,1005 cards,1006 {1007 domain: getPageDomain(),1008 capability,1009 onFill: (entry) => {1010 if (!cardForm) return;1011 fillCardForm(cardForm, {1012 cardNumber: entry.cardNumber ?? "",1013 expMonth: entry.expMonth ?? "",1014 expYear: entry.expYear ?? "",1015 cvc: entry.cvc ?? "",1016 cardholderName: entry.cardholderName ?? "",1017 });1018 1019 1020 1021 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);1022 currentCardDismiss = null;1023 currentCardAnchor = null;1024 },1025 onDismiss: () => {1026 lastDismissedCardField = anchor;1027 startDismissLock();1028 currentCardDismiss = null;1029 currentCardAnchor = null;1030 },1031 }1032 );1033}10341035function injectCardIcon(field: HTMLInputElement): void {1036 if (processedCardInputs.has(field)) return;1037 const cleanup = injectFieldIcon(field, () => {1038 currentCardDismiss?.();1039 currentCardDismiss = null;1040 lastDismissedCardField = null;1041 dismissLock = false;1042 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1043 clearFillStateForExplicitSummon(field);1044 field.focus({ preventScroll: true });1045 void openCardSelector(field);1046 });1047 processedCardInputs.set(field, cleanup);1048}10491050function setupCardAutofill(): void {1051 function scan() {1052 const cardForm = detectCardForm();1053 if (!cardForm?.number) return;1054 if (!isVisible(cardForm.number)) return;1055 injectCardIcon(cardForm.number);1056 }10571058 1059 1060 setTimeout(scan, 0);1061 setTimeout(scan, 500);1062 setTimeout(scan, 1500);10631064 1065 1066 1067 let pending = false;1068 new MutationObserver(() => {1069 if (pending) return;1070 pending = true;1071 setTimeout(() => { pending = false; scan(); }, 200);1072 }).observe(document.body, { childList: true, subtree: true });10731074 1075 1076 1077 document.addEventListener("focusin", (e) => {1078 const target = e.target;1079 if (!(target instanceof HTMLInputElement)) return;1080 const cardForm = detectCardForm();1081 if (cardForm?.number === target) {1082 injectCardIcon(target);1083 }1084 }, true);1085}10861087chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {1088 1089 if (sender.id !== chrome.runtime.id) return;1090 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {1091 const policy = detectPasswordPolicy();1092 sendResponse({ ok: true, data: policy });1093 return true;1094 }1095 if (msg?.type === "PING") {1096 sendResponse({ ok: true });1097 return true;1098 }1099 if (msg?.type === "SUMMON_AUTOFILL") {1100 const source = (msg as { type: string; source?: string; capability?: string }).source;1101 const capability = (msg as { capability?: string }).capability;1102 const isShortcut = source === "shortcut";1103 const isPasskeyUnlock = source === "passkey-unlock";11041105 const activeInput = getDeepActiveInput();1106 const fields = detectLoginFields();1107 const hasForm = isAnyCredentialForm(fields);1108 const cardForm = detectCardForm();11091110 if (hasForm) {1111 1112 1113 const inForm = activeInput && fields.some(f => f.el === activeInput);1114 const target = inForm1115 ? activeInput1116 : (fields.find(f => f.type === "password")?.el1117 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1118 if (target) {1119 1120 1121 clearFillStateForExplicitSummon(target);1122 dismissLock = false;1123 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1124 lastDismissedField = null;1125 void handleFieldInteraction(target, true, capability);1126 }1127 } else if (isShortcut && cardForm?.number) {1128 clearFillStateForExplicitSummon(cardForm.number);1129 dismissLock = false;1130 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1131 lastDismissedCardField = null;1132 void openCardSelector(cardForm.number, capability);1133 } else if (isPasskeyUnlock) {1134 1135 1136 1137 const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1138 ? document.activeElement as unknown as HTMLInputElement1139 : null;1140 if (anchor) {1141 currentDismiss?.();1142 currentAnchorField = null;1143 passkeySummonActive = true;1144 currentDismiss = showAutofillSelector(anchor, [], () => {}, {1145 domain: getPageDomain(),1146 locked: true,1147 onDismiss: () => { passkeySummonActive = false; },1148 });1149 }1150 } else if (isShortcut) {1151 1152 showSearchPalette(capability);1153 }11541155 1156 if (isShortcut) {1157 const domain = getPageDomain();1158 if (domain) {1159 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1160 }1161 }11621163 sendResponse({ ok: hasForm || Boolean(cardForm?.number) || isShortcut || isPasskeyUnlock });1164 return true;1165 }1166 if (msg?.type === "PASSKEY_PRO_GATE") {1167 1168 1169 showPasskeyProGate();1170 sendResponse({ ok: true });1171 return true;1172 }1173 if (msg?.type === "SHOW_PASSKEY_TOAST") {1174 1175 passkeyToastActive = true;1176 if (currentDismiss) {1177 currentDismiss();1178 currentDismiss = null;1179 currentAnchorField = null;1180 }1181 return false; 1182 }1183 if (msg?.type === "DISMISS_PASSKEY_TOAST") {1184 passkeyToastActive = false;1185 return false; 1186 }1187 if (msg?.type === "VAULT_UNLOCKED") {1188 if (passkeySummonActive) {1189 1190 1191 passkeySummonActive = false;1192 if (currentDismiss) {1193 currentDismiss();1194 currentDismiss = null;1195 currentAnchorField = null;1196 }1197 sendResponse({ ok: true });1198 return true;1199 }1200 1201 1202 const savedField = currentAnchorField;1203 if (currentDismiss) {1204 currentDismiss();1205 currentDismiss = null;1206 currentAnchorField = null;1207 }1208 void handleFieldInteraction(savedField ?? undefined);1209 sendResponse({ ok: true });1210 return true;1211 }1212 return true;1213});1214121512161217window.addEventListener("message", (e: MessageEvent) => {1218 1219 1220 if (e.source !== window) return;1221 const d = e.data as { source?: string; type?: string } | undefined;1222 if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {1223 passkeyToastActive = false;1224 }1225});1226122712281229123012311232123312341235123612371238if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {1239 let lastPasskeyOfferAt = 0;1240 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;12411242 window.addEventListener("message", (event: MessageEvent) => {1243 if (event.source !== window) return;1244 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;1245 if (!data || data.source !== "peach-passkey-firefox") return;1246 if (detectBrowser() !== "firefox") return;1247 if (data.type !== "create") return;12481249 1250 1251 const now = Date.now();1252 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1253 lastPasskeyOfferAt = now;12541255 const domain = location.hostname.replace(/^www\./, "");1256 chrome.runtime.sendMessage({1257 type: "GET_PASSKEY_OFFER_DECLINED",1258 payload: { domain },1259 }).then((res: { ok: boolean; data?: boolean } | undefined) => {1260 if (res?.data === true) return;1261 const rpId = data.rpId ?? domain;1262 showPasskeyRegistrationOffer({1263 rpId,1264 rpName: data.rpName,1265 userName: data.userName,1266 userDisplayName: data.userDisplayName,1267 });1268 }).catch(() => {});1269 });1270}127112721273127412751276127712781279128012811282128312841285{1286 function checkPasskeyAvailability() {1287 const domain = location.hostname.replace(/^www\./, "");1288 if (!domain) return;1289 const sessionKey = `peach_state11_shown:${domain}`;1290 chrome.storage.session?.get(sessionKey).then((stored) => {1291 if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1292 chrome.runtime.sendMessage({1293 type: "GET_PASSKEY_FOR_DOMAIN",1294 payload: { domain },1295 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1296 const data = res?.data;1297 if (!data) return;1298 const current = detectBrowser();1299 const isCrossBrowser =1300 data.browser && current !== "unknown" && data.browser !== current;1301 const valuableOnFirefox = current === "firefox";1302 if (!isCrossBrowser && !valuableOnFirefox) return;1303 chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1304 showPasskeyAvailable({1305 rpId: data.rpId,1306 userName: data.userName,1307 fromBrowser: data.browser,1308 currentBrowser: current,1309 });1310 }).catch(() => {});1311 }).catch(() => {});1312 }13131314 1315 1316 1317 if (document.readyState === "loading") {1318 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1319 } else {1320 setTimeout(checkPasskeyAvailability, 800);1321 }1322}