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 showRememberSiteToast,24 showTotpCopyToast,25 showTOTPSelector,26} from "./inject";27import { detectBrowser } from "../shared/browser";28import { fillAllowed, fillCardForm, fillFields, fillOTPDigitBoxes, fillTOTPCode, setNativeValue } from "./fill";29import { resolveAutofillInteractionTargets } from "./interaction";30import { setupSaveDetection } from "./save";31import { contentMLDetector } from "./content-ml-detector";32import { detectPasswordPolicy } from "./policy";33import type { FieldPrediction } from "../shared/ml";34import type { VaultEntry } from "../shared/types";35import { setPasskeyToastClosedListener } from "./passkey-toast/lifecycle";363738394041const processedInputs = new WeakMap<HTMLInputElement, () => void>();42const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);4344let currentDismiss: (() => void) | null = null;4546let currentAnchorField: HTMLInputElement | null = null;4748const pendingInteractions = new WeakSet<HTMLInputElement>();49505152let lastDismissedField: HTMLInputElement | null = null;53545556575859const DISMISS_LOCK_MS = 800;60let dismissLock = false;61let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;62636465let passkeySummonActive = false;66676869let passkeyToastActive = false;70let passkeyToastToken: string | null = null;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) showToast("Could not access this entry. Open Peach to check it.");259 if (r.ok && r.data?.password) {260 let alreadyWritten = false;261 try {262 await navigator.clipboard.writeText(r.data.password);263 alreadyWritten = true;264 } catch (err) {265 console.warn("[Peach] clipboard write denied:", err);266 }267 const copyResp = await chrome.runtime.sendMessage({268 type: "COPY",269 payload: { text: r.data.password, label: "Password", alreadyWritten },270 }) as { ok?: boolean } | undefined;271 if (alreadyWritten || copyResp?.ok) {272 showToast("Password copied");273 } else {274 showToast("Could not copy password — clipboard blocked");275 }276 } else {277 showToast("Could not copy password");278 }279 close();280 document.removeEventListener("keydown", onKeyDown, true);281 };282 list.appendChild(row);283 }284 }285286 searchInput.oninput = () => { query = searchInput.value; render(); };287288 289 290 fetchAutofillEntries(getPageDomain(), true, capability).then(result => {291 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }292 allEntries = result.entries;293 render();294 searchInput.focus();295 });296}297298function findTOTPField(root: Document | Element = document): HTMLInputElement | null {299 const inputs = root.querySelectorAll<HTMLInputElement>("input");300 for (const input of inputs) {301 if (isTOTPField(input)) return input;302 }303 return null;304}305306function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {307 const form = passwordEl.closest("form");308 return findTOTPField(form ?? document);309}310311312async function handleAutofill(313 _field: HTMLInputElement,314 usernameEl: HTMLInputElement | null,315 passwordEl: HTMLInputElement | null,316 entry: VaultEntry,317 emailEl?: HTMLInputElement | null318): Promise<{ filledTOTPField: HTMLInputElement | null; gatePassed: boolean }> {319 if (!entry.username && !entry.password && !entry.email) return { filledTOTPField: null, gatePassed: false };320 const pageDomain = getPageDomain();321 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;322 323 324 325 const emailValue = entry.email ?? (entry.username?.includes("@") ? entry.username : "");326 const gatePassed = fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain, emailEl, emailValue);327 let filledTOTPField: HTMLInputElement | null = null;328329 330 331 const totpCode = (entry as { totpCode?: string }).totpCode;332 if (totpCode && gatePassed) {333 const code = totpCode;334 const totpField = passwordEl ? findSameLoginTOTPField(passwordEl) : null;335 if (fillTOTPCode(totpField, code, form, pageDomain)) {336 filledTOTPField = totpField;337 }338 let alreadyWritten = false;339 try {340 await navigator.clipboard.writeText(code);341 alreadyWritten = true;342 } catch (err) {343 console.warn("[Peach] clipboard write denied:", err);344 }345 const response = await chrome.runtime.sendMessage({346 type: "COPY",347 payload: { text: code, label: "TOTP", alreadyWritten },348 });349 const res = response as { ok?: boolean; clearSeconds?: number };350 if (filledTOTPField) {351 showToast("2FA code filled");352 } else if (alreadyWritten || res.ok) {353 354 355 356 357 showTotpCopyToast(res.clearSeconds ?? 30);358 } else {359 showToast("Could not copy TOTP — clipboard blocked");360 }361 }362363 return { filledTOTPField, gatePassed };364}365366async function fetchAutofillEntries(367 domain: string,368 includeAll = false,369 capability?: string370): Promise<{ entries: SelectorEntry[]; locked: boolean }> {371 const response = await chrome.runtime.sendMessage({372 type: "AUTOFILL_QUERY",373 payload: { domain, includeAll, capability },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: string,384 capability?: string,385): Promise<{ entries: SelectorEntry[]; locked: boolean }> {386 const response = await chrome.runtime.sendMessage({387 type: "AUTOFILL_QUERY",388 payload: { domain, kind: "totp", capability },389 });390 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };391 if (!res.ok && res.error === "vault_locked") {392 return { entries: [], locked: true };393 }394 return { entries: res.data ?? [], locked: false };395}396397398function resolveAutofillFieldType(399 el: HTMLInputElement,400 predictedType?: FieldPrediction["type"] | null401): "password" | "username" | "email" | null {402 if (403 predictedType === "password" ||404 predictedType === "username" ||405 predictedType === "email"406 ) {407 return predictedType;408 }409410 const detected = detectLoginFields().find((field) => field.el === el)?.type;411 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {412 return detected;413 }414415 const htmlType = el.type.toLowerCase();416 if (htmlType === "password") return "password";417 if (htmlType === "email") return "email";418 return null;419}420421async function openAutofillSelector(422 anchorField: HTMLInputElement,423 usernameEl: HTMLInputElement | null,424 passwordEl: HTMLInputElement | null,425 domainEntries: SelectorEntry[],426 loadSearchableEntries: () => Promise<SelectorEntry[]>,427 domain: string,428 identityKind: "email" | "username",429 emailEl?: HTMLInputElement | null,430 capability?: string,431): Promise<void> {432 433 434 const isSignup = domainEntries.length === 0;435 let confirmEl: HTMLInputElement | null = null;436 if (isSignup) {437 const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body;438 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));439 confirmEl = allPwInputs.find(440 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)441 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);442 }443444 currentDismiss?.();445 currentAnchorField = anchorField;446 currentDismiss = showAutofillSelector(447 anchorField,448 domainEntries,449 async (id: string) => {450 currentDismiss = null;451 currentAnchorField = null;452 const entryResponse = await chrome.runtime.sendMessage({453 type: "GET_ENTRY_FOR_FILL",454 payload: { id, capability },455 });456 if (!(entryResponse as { ok: boolean }).ok) showToast("Could not access this entry. Open Peach to check it.");457 const entry = (entryResponse as { ok: boolean }).ok ? (entryResponse as { data?: VaultEntry }).data : undefined;458 if (entry) {459 const { filledTOTPField, gatePassed } = await handleAutofill(anchorField, usernameEl, passwordEl, entry, emailEl);460 if (gatePassed) recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);461 462 463 464 const pageDomain = location.hostname.replace(/^www\./, "");465 const entryDomains = new Set<string>();466 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {467 try {468 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));469 } catch { }470 }471 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {472 showRememberSiteToast(location.origin, entry.id);473 }474 }475 },476 {477 domain,478 capability,479 loadSearchableEntries,480 isSignup,481 identityKind,482 hasEmailField: !!emailEl,483 onFillFields: (username, password, email) => {484 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;485 if (!fillFields(usernameEl, passwordEl, username, password, form, getPageDomain(), emailEl, email)) return;486 if (password && confirmEl) setNativeValue(confirmEl, password);487 recordFillSuccess(anchorField, usernameEl, passwordEl);488 },489 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },490 }491 );492}493494async function openTOTPSelector(495 anchorField: HTMLInputElement,496 otpDigitBoxes?: HTMLInputElement[],497 capability?: string,498): Promise<void> {499 if (!canOpen()) return;500 if (currentDismiss && currentAnchorField === anchorField) return;501 if (anchorField !== lastDismissedField) lastDismissedField = null;502 if (anchorField === lastDismissedField) return;503 if (wasAlreadyFilled(anchorField)) return;504505 const domain = getPageDomain();506 const result = await fetchTOTPEntries(domain, capability);507508 if (result.locked) {509 currentDismiss?.();510 currentAnchorField = anchorField;511 currentDismiss = showAutofillSelector(512 anchorField,513 [],514 () => {},515 {516 domain,517 locked: true,518 onUnlocked: () => void openTOTPSelector(anchorField),519 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },520 }521 );522 return;523 }524525 if (result.entries.length === 0) {526 lastDismissedField = anchorField;527 startDismissLock();528 showToast("No 2FA entries for this site — add a code in Peach first");529 return;530 }531532 currentDismiss?.();533 currentAnchorField = anchorField;534 currentDismiss = showTOTPSelector(535 anchorField,536 result.entries,537 async (id: string) => {538 try {539 const entryResponse = await chrome.runtime.sendMessage({540 type: "GET_ENTRY_FOR_FILL",541 payload: { id, capability },542 }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;543 if (!entryResponse?.ok) showToast("Could not access this entry. Open Peach to check it.");544 const entry = entryResponse?.ok ? entryResponse.data : undefined;545 const code = (entry as { totpCode?: string } | undefined)?.totpCode;546 if (!code) return;547 if (!fillAllowed(anchorField.closest("form"), getPageDomain())) return;548 if (otpDigitBoxes && otpDigitBoxes.length > 1) {549 fillOTPDigitBoxes(otpDigitBoxes, code);550 } else {551 setNativeValue(anchorField, code);552 }553 recordFillSuccess(anchorField);554 showToast("2FA code filled");555 } finally {556 currentDismiss = null;557 currentAnchorField = null;558 }559 },560 {561 domain,562 onDismiss: () => {563 lastDismissedField = anchorField;564 startDismissLock();565 currentDismiss = null;566 currentAnchorField = null;567 },568 }569 );570}571572573export async function handleFieldInteraction(574 anchorField?: HTMLInputElement | null,575 explicitSummon = false,576 capability?: string577): Promise<void> {578 const field = anchorField ?? getDeepActiveInput();579 if (!field) return;580 if (!isVisible(field)) return;581582 583 if (passkeyToastActive) return;584585 586 587 if (!canOpen()) return;588589 590 if (currentDismiss && currentAnchorField === field) return;591592 593 594 if (field !== lastDismissedField) lastDismissedField = null;595 596 597 if (field === lastDismissedField) return;598599 600 601 602 603 if (wasAlreadyFilled(field)) return;604605 606 607 if (pendingInteractions.has(field)) return;608 pendingInteractions.add(field);609610 try {611 612 613 614 615 616 const otpGroup = findOTPDigitBoxGroup(field) ?? findOtpSignalingGroup(field);617 if (otpGroup) {618 await openTOTPSelector(otpGroup[0]!, otpGroup, capability);619 return;620 }621622 if (isTOTPField(field)) {623 const formFields = detectLoginFields();624 if (!isLoginForm(formFields) && !isSignupForm(formFields)) {625 await openTOTPSelector(field, undefined, capability);626 return;627 }628 }629630 const fieldType = field.type.toLowerCase();631632 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {633 return preds[0] ?? null;634 });635636 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {637 const timeout = setTimeout(() => resolve(null), 150);638 mlPromise.then((pred) => {639 clearTimeout(timeout);640 resolve(pred);641 });642 });643644 if (passkeyToastActive) return;645646 if (!explicitSummon && fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {647 return;648 }649650 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);651 if (autofillFieldType) {652 reattachListeners(field, autofillFieldType);653 }654655 const fields = detectLoginFields();656 const targets = resolveAutofillInteractionTargets(field, fields, explicitSummon);657 if (!targets.shouldOpen) {658 return;659 }660661 const domain = getPageDomain();662 const commandAuthorized = explicitSummon && capability !== undefined;663 const firstResult = await fetchAutofillEntries(664 domain,665 commandAuthorized,666 commandAuthorized ? capability : undefined,667 );668 if (passkeyToastActive) return;669670 671 672 673 if (firstResult.locked) {674 currentDismiss?.();675 currentAnchorField = field;676 currentDismiss = showAutofillSelector(677 field,678 [],679 () => {},680 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }681 );682 return;683 }684685 const entries = firstResult.entries;686 687 688 689 690 691 692 const loadSearchableEntries = async (): Promise<SelectorEntry[]> =>693 commandAuthorized694 ? entries695 : (await fetchAutofillEntries(domain)).entries;696697 if (passkeyToastActive) return;698699 const pwField = fields.find((f) => f.type === "password");700 701 if (!explicitSummon && !pwField && !isEmailFirstForm(fields)) return;702 const usernameEl = targets.usernameEl;703 const passwordEl = targets.passwordEl;704 const emailEl = targets.emailEl;705706 await openAutofillSelector(707 field,708 usernameEl,709 passwordEl,710 entries,711 loadSearchableEntries,712 domain,713 autofillFieldType === "email" ? "email" : "username",714 emailEl,715 commandAuthorized ? capability : undefined,716 );717 } finally {718 pendingInteractions.delete(field);719 }720}721722async function onFocusIn(e: Event): Promise<void> {723 724 725 726 727 728 if (isSubmitButton(e.target)) return;729730 const field = e.target instanceof HTMLInputElement ? e.target : null;731 if (field) {732 const fields = detectLoginFields();733 if (isAnyCredentialForm(fields)) {734 const detected = fields.find((candidate) => candidate.el === field)?.type;735 reattachListeners(field, detected, fields);736 }737 }738739 await handleFieldInteraction();740}741742function reattachListeners(743 el: HTMLInputElement,744 detectedType?: "password" | "username" | "email",745 contextFields?: ReturnType<typeof detectLoginFields>746): void {747 if (processedInputs.has(el)) return;748 if (!resolveAutofillFieldType(el, detectedType)) return;749 750 const fields = contextFields ?? detectLoginFields();751 if (!isAnyCredentialForm(fields)) return;752753 const cleanup = injectFieldIcon(el, () => {754 currentDismiss?.();755 currentDismiss = null;756 lastDismissedField = null; 757 dismissLock = false; 758 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }759 clearFillStateForExplicitSummon(el);760 el.focus({ preventScroll: true });761 void handleFieldInteraction(el, true);762 });763 processedInputs.set(el, cleanup);764}765766const debouncedReattach = debounce(() => {767 const allFields = detectLoginFields();768 if (!isAnyCredentialForm(allFields)) return;769 const newFields = allFields.filter(770 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)771 );772 for (const f of newFields) {773 reattachListeners(f.el, f.type, allFields);774 }775 776 777 778}, 200);779780function setupMutationObserver(): void {781 const observer = new MutationObserver(debouncedReattach);782 observer.observe(document.body, {783 childList: true,784 subtree: true,785 attributes: true,786 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],787 });788}789790export function initialScan(aggressionLevel = 0, isFinalPass = false) {791 const allFields = detectLoginFields();792 const hasKnownForm = isAnyCredentialForm(allFields);793794 if (aggressionLevel === 0 && !hasKnownForm) return;795796 const newFields = allFields.filter(797 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)798 );799800 for (const f of newFields) {801 reattachListeners(f.el, f.type, allFields);802 }803804 805 806 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {807 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');808 for (const el of pwInputs) {809 if (isVisible(el) && !processedInputs.has(el)) {810 const cleanup = injectFieldIcon(el, () => {811 currentDismiss?.();812 currentDismiss = null;813 lastDismissedField = null;814 dismissLock = false;815 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }816 clearFillStateForExplicitSummon(el);817 el.focus({ preventScroll: true });818 void handleFieldInteraction(el, true);819 });820 processedInputs.set(el, cleanup);821 }822 }823 }824}825826827828export const _testSeam = {829 getLastDismissedField(): HTMLInputElement | null { return lastDismissedField; },830 setLastDismissedField(f: HTMLInputElement | null): void { lastDismissedField = f; },831 isDismissLocked(): boolean { return dismissLock; },832 DISMISS_LOCK_MS,833} as const;834835836837838839const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();840841function hasLoginOrSignupForm(): boolean {842 const fields = detectLoginFields();843 return isAnyCredentialForm(fields);844}845846function injectTOTPFieldIcon(847 field: HTMLInputElement,848 otpDigitBoxes?: HTMLInputElement[]849): void {850 if (processedTOTPInputs.has(field)) return;851 const cleanup = injectFieldIcon(field, () => {852 currentDismiss?.();853 currentDismiss = null;854 currentAnchorField = null;855 lastDismissedField = null;856 dismissLock = false;857 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }858 clearFillStateForExplicitSummon(field);859 field.focus({ preventScroll: true });860 void openTOTPSelector(field, otpDigitBoxes);861 });862 processedTOTPInputs.set(field, cleanup);863}864865866867868869function resolveTOTPIconTarget(870 field: HTMLInputElement871): { anchor: HTMLInputElement; group?: HTMLInputElement[] } {872 const group = findOtpSignalingGroup(field);873 if (group) return { anchor: group[0]!, group };874 return { anchor: field };875}876877export function scanTOTPFields(): void {878 if (hasLoginOrSignupForm()) return;879 const inputs = document.querySelectorAll<HTMLInputElement>("input");880 for (const input of inputs) {881 if (!isTOTPField(input)) continue;882 const { anchor, group } = resolveTOTPIconTarget(input);883 injectTOTPFieldIcon(anchor, group);884 }885}886887function setupTOTPAutofill(): void {888 setTimeout(scanTOTPFields, 0);889 setTimeout(scanTOTPFields, 500);890 setTimeout(scanTOTPFields, 1500);891892 const debouncedScan = debounce(scanTOTPFields, 200);893 new MutationObserver(debouncedScan).observe(document.body, {894 childList: true,895 subtree: true,896 attributes: true,897 attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],898 });899900 document.addEventListener("focusin", (e) => {901 const target = e.target;902 if (!(target instanceof HTMLInputElement)) return;903 if (hasLoginOrSignupForm()) return;904 if (!isTOTPField(target)) return;905 const { anchor, group } = resolveTOTPIconTarget(target);906 injectTOTPFieldIcon(anchor, group);907 }, true);908}909910document.addEventListener("focusin", onFocusIn);911912setupMutationObserver();913setupTOTPAutofill();914setupSaveDetection();915setupCardAutofill();916917918919920921922923924let lastObservedUrl = globalThis.location.href;925new MutationObserver(() => {926 const currentUrl = globalThis.location?.href;927 if (!currentUrl || currentUrl === lastObservedUrl) return;928 lastObservedUrl = currentUrl;929 pageFilledAt = null;930}).observe(document.body, { childList: true, subtree: false });931932933934(async () => {935 let aggressionLevel = 0;936 try {937 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });938 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;939 const domain = getPageDomain();940 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;941 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;942 } catch { }943944 setTimeout(() => initialScan(aggressionLevel, false), 0);945 setTimeout(() => initialScan(aggressionLevel, false), 500);946 setTimeout(() => initialScan(aggressionLevel, true), 1500);947})();948949950951952953954const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();955let currentCardDismiss: (() => void) | null = null;956let currentCardAnchor: HTMLInputElement | null = null;957let lastDismissedCardField: HTMLInputElement | null = null;958959async function fetchSavedCards(capability?: string): Promise<CardSelectorEntry[]> {960 const resp = await chrome.runtime.sendMessage({961 type: "AUTOFILL_QUERY",962 payload: { domain: getPageDomain(), kind: "card", capability },963 }).catch(() => null);964 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;965 return r?.ok ? (r.data ?? []) : [];966}967968async function openCardSelector(anchor: HTMLInputElement, capability?: string): Promise<void> {969 if (!canOpen()) return;970 if (currentCardDismiss && currentCardAnchor === anchor) return;971 if (anchor === lastDismissedCardField) return;972 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;973 if (wasAlreadyFilled(anchor)) return;974975 const cards = await fetchSavedCards(capability);976 if (cards.length === 0) return; 977978 const cardForm = detectCardForm();979 if (!cardForm?.number) return;980981 currentCardDismiss?.();982 currentCardAnchor = anchor;983 currentCardDismiss = showCardSelector(984 anchor,985 cards,986 {987 domain: getPageDomain(),988 capability,989 onFill: (entry) => {990 if (!cardForm) return;991 fillCardForm(cardForm, {992 cardNumber: entry.cardNumber ?? "",993 expMonth: entry.expMonth ?? "",994 expYear: entry.expYear ?? "",995 cvc: entry.cvc ?? "",996 cardholderName: entry.cardholderName ?? "",997 });998 999 1000 1001 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);1002 currentCardDismiss = null;1003 currentCardAnchor = null;1004 },1005 onDismiss: () => {1006 lastDismissedCardField = anchor;1007 startDismissLock();1008 currentCardDismiss = null;1009 currentCardAnchor = null;1010 },1011 }1012 );1013}10141015function injectCardIcon(field: HTMLInputElement): void {1016 if (processedCardInputs.has(field)) return;1017 const cleanup = injectFieldIcon(field, () => {1018 currentCardDismiss?.();1019 currentCardDismiss = null;1020 lastDismissedCardField = null;1021 dismissLock = false;1022 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1023 clearFillStateForExplicitSummon(field);1024 field.focus({ preventScroll: true });1025 void openCardSelector(field);1026 });1027 processedCardInputs.set(field, cleanup);1028}10291030function setupCardAutofill(): void {1031 function scan() {1032 const cardForm = detectCardForm();1033 if (!cardForm?.number) return;1034 if (!isVisible(cardForm.number)) return;1035 injectCardIcon(cardForm.number);1036 }10371038 1039 1040 setTimeout(scan, 0);1041 setTimeout(scan, 500);1042 setTimeout(scan, 1500);10431044 1045 1046 1047 let pending = false;1048 new MutationObserver(() => {1049 if (pending) return;1050 pending = true;1051 setTimeout(() => { pending = false; scan(); }, 200);1052 }).observe(document.body, { childList: true, subtree: true });10531054 1055 1056 1057 document.addEventListener("focusin", (e) => {1058 const target = e.target;1059 if (!(target instanceof HTMLInputElement)) return;1060 const cardForm = detectCardForm();1061 if (cardForm?.number === target) {1062 injectCardIcon(target);1063 }1064 }, true);1065}10661067chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {1068 1069 if (sender.id !== chrome.runtime.id) return;1070 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {1071 const policy = detectPasswordPolicy();1072 sendResponse({ ok: true, data: policy });1073 return true;1074 }1075 if (msg?.type === "PING") {1076 sendResponse({ ok: true });1077 return true;1078 }1079 if (msg?.type === "SUMMON_AUTOFILL") {1080 const source = (msg as { type: string; source?: string; capability?: string }).source;1081 const capability = (msg as { capability?: string }).capability;1082 const isShortcut = source === "shortcut";1083 const isPasskeyUnlock = source === "passkey-unlock";10841085 const activeInput = getDeepActiveInput();1086 const fields = detectLoginFields();1087 const hasForm = isAnyCredentialForm(fields);1088 const cardForm = detectCardForm();10891090 if (hasForm) {1091 1092 1093 const inForm = activeInput && fields.some(f => f.el === activeInput);1094 const target = inForm1095 ? activeInput1096 : (fields.find(f => f.type === "password")?.el1097 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1098 if (target) {1099 1100 1101 clearFillStateForExplicitSummon(target);1102 dismissLock = false;1103 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1104 lastDismissedField = null;1105 void handleFieldInteraction(target, true, capability);1106 }1107 } else if (isShortcut && cardForm?.number) {1108 clearFillStateForExplicitSummon(cardForm.number);1109 dismissLock = false;1110 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1111 lastDismissedCardField = null;1112 void openCardSelector(cardForm.number, capability);1113 } else if (isPasskeyUnlock) {1114 1115 1116 1117 const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1118 ? document.activeElement as unknown as HTMLInputElement1119 : null;1120 if (anchor) {1121 currentDismiss?.();1122 currentAnchorField = null;1123 passkeySummonActive = true;1124 currentDismiss = showAutofillSelector(anchor, [], () => {}, {1125 domain: getPageDomain(),1126 locked: true,1127 onDismiss: () => { passkeySummonActive = false; },1128 });1129 }1130 } else if (isShortcut) {1131 1132 showSearchPalette(capability);1133 }11341135 1136 if (isShortcut) {1137 const domain = getPageDomain();1138 if (domain) {1139 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1140 }1141 }11421143 sendResponse({ ok: hasForm || Boolean(cardForm?.number) || isShortcut || isPasskeyUnlock });1144 return true;1145 }1146 if (msg?.type === "PASSKEY_PRO_GATE") {1147 1148 1149 showPasskeyProGate();1150 sendResponse({ ok: true });1151 return true;1152 }1153 if (msg?.type === "SHOW_PASSKEY_TOAST") {1154 1155 passkeyToastActive = true;1156 passkeyToastToken = typeof (msg.payload as { toastToken?: unknown } | undefined)?.toastToken === "string"1157 ? (msg.payload as { toastToken: string }).toastToken1158 : null;1159 if (currentDismiss) {1160 currentDismiss();1161 currentDismiss = null;1162 currentAnchorField = null;1163 }1164 return false; 1165 }1166 if (msg?.type === "DISMISS_PASSKEY_TOAST") {1167 passkeyToastActive = false;1168 passkeyToastToken = null;1169 return false; 1170 }1171 if (msg?.type === "VAULT_UNLOCKED") {1172 if (passkeySummonActive) {1173 1174 1175 passkeySummonActive = false;1176 if (currentDismiss) {1177 currentDismiss();1178 currentDismiss = null;1179 currentAnchorField = null;1180 }1181 sendResponse({ ok: true });1182 return true;1183 }1184 1185 1186 const savedField = currentAnchorField;1187 if (currentDismiss) {1188 currentDismiss();1189 currentDismiss = null;1190 currentAnchorField = null;1191 }1192 void handleFieldInteraction(savedField ?? undefined);1193 sendResponse({ ok: true });1194 return true;1195 }1196 return true;1197});11981199setPasskeyToastClosedListener((toastToken) => {1200 if (toastToken === passkeyToastToken) {1201 passkeyToastActive = false;1202 passkeyToastToken = null;1203 }1204});1205120612071208120912101211121212131214121512161217121812191220{1221 function checkPasskeyAvailability() {1222 const domain = location.hostname.replace(/^www\./, "");1223 if (!domain) return;1224 chrome.runtime.sendMessage({1225 type: "GET_PASSKEY_FOR_DOMAIN",1226 payload: { domain },1227 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox"; bannerShown?: boolean } | null } | undefined) => {1228 const data = res?.data;1229 if (!data || data.bannerShown) return;1230 const current = detectBrowser();1231 const isCrossBrowser =1232 data.browser && current !== "unknown" && data.browser !== current;1233 const valuableOnFirefox = current === "firefox";1234 if (!isCrossBrowser && !valuableOnFirefox) return;1235 chrome.runtime.sendMessage({1236 type: "MARK_PASSKEY_BANNER_SHOWN",1237 payload: { domain },1238 }).catch(() => {});1239 showPasskeyAvailable({1240 rpId: data.rpId,1241 userName: data.userName,1242 fromBrowser: data.browser,1243 currentBrowser: current,1244 });1245 }).catch(() => {});1246 }12471248 1249 1250 1251 if (document.readyState === "loading") {1252 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1253 } else {1254 setTimeout(checkPasskeyAvailability, 800);1255 }1256}