1import {2 detectCardForm,3 detectLoginFields,4 findOTPDigitBoxGroup,5 getDeepActiveInput,6 getPageDomain,7 isAnyCredentialForm,8 isEmailFirstForm,9 isLoginForm,10 isSignupForm,11 isTOTPField,12 isVisible,13} from "./detect";14import {15 CardSelectorEntry,16 injectFieldIcon,17 SelectorEntry,18 showAutofillSelector,19 showCardSelector,20 showPasskeyAvailable,21 showPasskeyProGate,22 showPasskeyRegistrationOffer,23 showRememberSiteToast,24 showTOTPSelector,25} from "./inject";26import { detectBrowser } from "../shared/browser";27import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";28import { fillCardForm, fillFields, fillOTPDigitBoxes, fillTOTPCode, setNativeValue } from "./fill";29import { resolveAutofillInteractionTargets } from "./interaction";30import { setupSaveDetection } from "./save";31import { contentMLDetector } from "./content-ml-detector";32import { detectPasswordPolicy } from "./policy";33import type { FieldPrediction } from "../shared/ml";34import type { SavedIdentity, VaultEntry } from "../shared/types";353637383940const processedInputs = new WeakMap<HTMLInputElement, () => void>();41const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);4243let currentDismiss: (() => void) | null = null;4445let currentAnchorField: HTMLInputElement | null = null;4647const pendingInteractions = new WeakSet<HTMLInputElement>();48495051let lastDismissedField: HTMLInputElement | null = null;52535455565758const DISMISS_LOCK_MS = 800;59let dismissLock = false;60let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;61626364let passkeySummonActive = false;65666768let passkeyToastActive = false;69function startDismissLock(): void {70 dismissLock = true;71 if (dismissLockTimer) clearTimeout(dismissLockTimer);72 dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);73}74function canOpen(): boolean { return !dismissLock; }7576777879808182838485868788const filledForms = new WeakSet<HTMLFormElement>();89let pageFilledAt: number | null = null;90const PAGE_FILL_GRACE_MS = 3000;9192function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {93 for (const f of fields) {94 if (!f) continue;95 const form = f.closest("form");96 if (form) filledForms.add(form);97 }98 pageFilledAt = Date.now();99}100101function wasAlreadyFilled(field: HTMLInputElement): boolean {102 const form = field.closest("form");103 if (form && filledForms.has(form)) return true;104 if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;105 return false;106}107108function clearFillStateForExplicitSummon(field: HTMLInputElement): void {109 const form = field.closest("form");110 if (form) filledForms.delete(form);111 pageFilledAt = null;112}113114115116117118function isSubmitButton(el: EventTarget | null): boolean {119 if (!(el instanceof HTMLElement)) return false;120 if (el instanceof HTMLButtonElement && el.type !== "button") return true;121 if (el instanceof HTMLInputElement && el.type === "submit") return true;122 if (el.getAttribute("type") === "submit") return true;123 const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();124 if (!text || text.length > 24) return false;125 return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);126}127128function debounce<T extends (...args: unknown[]) => void>(129 fn: T,130 ms: number131): (...args: Parameters<T>) => void {132 let timer: ReturnType<typeof setTimeout>;133 return (...args: Parameters<T>) => {134 clearTimeout(timer);135 timer = setTimeout(() => fn(...args), ms);136 };137}138139function showToast(message: string): void {140 const toast = document.createElement("div");141 toast.style.cssText = `142 position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);143 background: #131109; color: #F0E8D8; padding: 8px 16px;144 border-radius: 8px; font-family: 'IBM Plex Mono', monospace;145 font-size: 11px; z-index: 2147483647; opacity: 0;146 transition: opacity 200ms ease;147 border: 1px solid rgba(240,232,216,0.07);148 pointer-events: none;149 `;150 toast.textContent = message;151 document.body.appendChild(toast);152 requestAnimationFrame(() => { toast.style.opacity = "1"; });153 setTimeout(() => {154 toast.style.opacity = "0";155 setTimeout(() => toast.remove(), 200);156 }, 2000);157}158159function showSearchPalette(): void {160 const host = document.createElement("div");161 host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";162 document.body.appendChild(host);163 const shadow = host.attachShadow({ mode: "closed" });164165 const style = document.createElement("style");166 style.textContent = `167 .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;168 font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;169 box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}170 .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);171 font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}172 .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}173 .s{padding:8px 12px}174 .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);175 border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;176 padding:6px 8px;font-family:inherit;font-size:12px;outline:none}177 .l{max-height:220px;overflow-y:auto}178 .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}179 .e:hover{background:rgba(240,232,216,.06)}180 .et{font-size:12px}181 .eu{font-size:10px;color:rgba(240,232,216,.45)}182 .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}183 `;184185 let allEntries: SelectorEntry[] = [];186 let query = "";187188 const panel = document.createElement("div");189 panel.className = "p";190191 const hdr = document.createElement("div");192 hdr.className = "h";193 const hdrText = document.createElement("span");194 hdrText.textContent = "No form detected — search your vault";195 const closeBtn = document.createElement("button");196 closeBtn.className = "x";197 closeBtn.textContent = "✕";198 hdr.appendChild(hdrText);199 hdr.appendChild(closeBtn);200201 const searchWrap = document.createElement("div");202 searchWrap.className = "s";203 const searchInput = document.createElement("input");204 searchInput.placeholder = "search...";205 searchWrap.appendChild(searchInput);206207 const list = document.createElement("div");208 list.className = "l";209210 panel.appendChild(hdr);211 panel.appendChild(searchWrap);212 panel.appendChild(list);213 shadow.appendChild(style);214 shadow.appendChild(panel);215216 function close() { host.remove(); }217218 closeBtn.onclick = close;219220 function onKeyDown(e: KeyboardEvent) {221 if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }222 }223 document.addEventListener("keydown", onKeyDown, true);224225 function render() {226 const q = query.toLowerCase();227 const filtered = q228 ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))229 : allEntries;230 list.innerHTML = "";231 if (filtered.length === 0) {232 const em = document.createElement("div");233 em.className = "em";234 em.textContent = query ? "no matches" : "vault is empty";235 list.appendChild(em);236 return;237 }238 for (const entry of filtered.slice(0, 20)) {239 const row = document.createElement("div");240 row.className = "e";241 const title = document.createElement("div");242 title.className = "et";243 title.textContent = entry.title;244 row.appendChild(title);245 if (entry.username) {246 const user = document.createElement("div");247 user.className = "eu";248 user.textContent = entry.username;249 row.appendChild(user);250 }251 row.onclick = async () => {252 253 254 const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, explicitSummon: true } });255 const r = resp as { ok: boolean; data?: { password?: string } };256 if (r.ok && r.data?.password) {257 let alreadyWritten = false;258 try {259 await navigator.clipboard.writeText(r.data.password);260 alreadyWritten = true;261 } catch (err) {262 console.warn("[Peach] clipboard write denied:", err);263 }264 const copyResp = await chrome.runtime.sendMessage({265 type: "COPY",266 payload: { text: r.data.password, label: "Password", alreadyWritten },267 }) as { ok?: boolean } | undefined;268 if (alreadyWritten || copyResp?.ok) {269 showToast("Password copied");270 } else {271 showToast("Could not copy password — clipboard blocked");272 }273 } else {274 showToast("Could not copy password");275 }276 close();277 document.removeEventListener("keydown", onKeyDown, true);278 };279 list.appendChild(row);280 }281 }282283 searchInput.oninput = () => { query = searchInput.value; render(); };284285 286 287 fetchAutofillEntries(getPageDomain(), true, true).then(result => {288 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }289 allEntries = result.entries;290 render();291 searchInput.focus();292 });293}294295function findTOTPField(root: Document | Element = document): HTMLInputElement | null {296 const inputs = root.querySelectorAll<HTMLInputElement>("input");297 for (const input of inputs) {298 if (isTOTPField(input)) return input;299 }300 return null;301}302303function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {304 const form = passwordEl.closest("form");305 return findTOTPField(form ?? document);306}307308309async function handleAutofill(310 _field: HTMLInputElement,311 usernameEl: HTMLInputElement | null,312 passwordEl: HTMLInputElement | null,313 entry: VaultEntry,314 emailEl?: HTMLInputElement | null315): Promise<HTMLInputElement | null> {316 if (!entry.username && !entry.password && !entry.email) return null;317 const pageDomain = getPageDomain();318 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;319 320 321 322 const emailValue = entry.email ?? (entry.username?.includes("@") ? entry.username : "");323 fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain, emailEl, emailValue);324 let filledTOTPField: HTMLInputElement | null = null;325326 if (entry.canary) {327 chrome.runtime.sendMessage({328 type: "FIRE_CANARY_PING",329 payload: {330 webhookUrl: entry.canary.webhookUrl,331 entryTitle: entry.title,332 trigger: "autofilled",333 },334 }).catch(() => {});335 chrome.runtime.sendMessage({336 type: "UPDATE_ENTRY",337 payload: {338 id: entry.id,339 patch: {340 canary: {341 ...entry.canary,342 lastPinged: Date.now(),343 pingCount: (entry.canary.pingCount ?? 0) + 1,344 },345 },346 },347 }).catch(() => {});348 }349350 351 352 const totpCode = (entry as { totpCode?: string }).totpCode;353 if (totpCode) {354 const code = totpCode;355 const totpField = passwordEl ? findSameLoginTOTPField(passwordEl) : null;356 if (fillTOTPCode(totpField, code)) {357 filledTOTPField = totpField;358 }359 let alreadyWritten = false;360 try {361 await navigator.clipboard.writeText(code);362 alreadyWritten = true;363 } catch (err) {364 console.warn("[Peach] clipboard write denied:", err);365 }366 const response = await chrome.runtime.sendMessage({367 type: "COPY",368 payload: { text: code, label: "TOTP", alreadyWritten },369 });370 if (filledTOTPField) {371 showToast("2FA code filled");372 } else if (alreadyWritten || (response as { ok?: boolean }).ok) {373 374 375 376 showToast("2FA code copied");377 } else {378 showToast("Could not copy TOTP — clipboard blocked");379 }380 }381382 return filledTOTPField;383}384385async function fetchAutofillEntries(386 domain: string,387 includeAll = false,388 userGesture = false389): Promise<{ entries: SelectorEntry[]; locked: boolean }> {390 const response = await chrome.runtime.sendMessage({391 type: "AUTOFILL_QUERY",392 payload: { domain, includeAll, userGesture },393 });394 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };395 if (!res.ok && res.error === "vault_locked") {396 return { entries: [], locked: true };397 }398 return { entries: res.data ?? [], locked: false };399}400401async function fetchTOTPEntries(402 domain: string403): Promise<{ entries: SelectorEntry[]; locked: boolean }> {404 const response = await chrome.runtime.sendMessage({405 type: "AUTOFILL_QUERY",406 payload: { domain, kind: "totp" },407 });408 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };409 if (!res.ok && res.error === "vault_locked") {410 return { entries: [], locked: true };411 }412 return { entries: res.data ?? [], locked: false };413}414415416function resolveAutofillFieldType(417 el: HTMLInputElement,418 predictedType?: FieldPrediction["type"] | null419): "password" | "username" | "email" | null {420 if (421 predictedType === "password" ||422 predictedType === "username" ||423 predictedType === "email"424 ) {425 return predictedType;426 }427428 const detected = detectLoginFields().find((field) => field.el === el)?.type;429 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {430 return detected;431 }432433 const htmlType = el.type.toLowerCase();434 if (htmlType === "password") return "password";435 if (htmlType === "email") return "email";436 return null;437}438439async function openAutofillSelector(440 anchorField: HTMLInputElement,441 usernameEl: HTMLInputElement | null,442 passwordEl: HTMLInputElement | null,443 domainEntries: SelectorEntry[],444 loadSearchableEntries: () => Promise<SelectorEntry[]>,445 domain: string,446 identityKind: "email" | "username",447 emailEl?: HTMLInputElement | null448): Promise<void> {449 450 451 452 const isSignup = domainEntries.length === 0;453 let savedIdentities: SavedIdentity[] | undefined;454 let confirmEl: HTMLInputElement | null = null;455 if (isSignup) {456 try {457 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as458 { ok: boolean; data?: SavedIdentity[] } | null;459 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;460 } catch { }461462 const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body;463 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));464 confirmEl = allPwInputs.find(465 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)466 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);467 }468469 currentDismiss?.();470 currentAnchorField = anchorField;471 currentDismiss = showAutofillSelector(472 anchorField,473 domainEntries,474 async (id: string) => {475 currentDismiss = null;476 currentAnchorField = null;477 const entryResponse = await chrome.runtime.sendMessage({478 type: "GET_ENTRY_FOR_FILL",479 payload: { id },480 });481 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;482 if (entry) {483 const filledTOTPField = await handleAutofill(anchorField, usernameEl, passwordEl, entry, emailEl);484 recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);485 486 487 488 const pageDomain = location.hostname.replace(/^www\./, "");489 const entryDomains = new Set<string>();490 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {491 try {492 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));493 } catch { }494 }495 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {496 showRememberSiteToast(pageDomain, entry.id);497 }498 }499 },500 {501 domain,502 loadSearchableEntries,503 isSignup,504 identityKind,505 hasEmailField: !!emailEl,506 savedIdentities,507 onFillFields: (username, password, email) => {508 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;509 fillFields(usernameEl, passwordEl, username, password, form, getPageDomain(), emailEl, email);510 if (password && confirmEl) setNativeValue(confirmEl, password);511 recordFillSuccess(anchorField, usernameEl, passwordEl);512 },513 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },514 }515 );516}517518async function openTOTPSelector(anchorField: HTMLInputElement, otpDigitBoxes?: HTMLInputElement[]): Promise<void> {519 if (!canOpen()) return;520 if (currentDismiss && currentAnchorField === anchorField) return;521 if (anchorField !== lastDismissedField) lastDismissedField = null;522 if (anchorField === lastDismissedField) return;523 if (wasAlreadyFilled(anchorField)) return;524525 const domain = getPageDomain();526 const result = await fetchTOTPEntries(domain);527528 if (result.locked) {529 currentDismiss?.();530 currentAnchorField = anchorField;531 currentDismiss = showAutofillSelector(532 anchorField,533 [],534 () => {},535 {536 domain,537 locked: true,538 onUnlocked: () => void openTOTPSelector(anchorField),539 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },540 }541 );542 return;543 }544545 if (result.entries.length === 0) {546 lastDismissedField = anchorField;547 startDismissLock();548 showToast("No 2FA entries for this site — add a code in Peach first");549 return;550 }551552 currentDismiss?.();553 currentAnchorField = anchorField;554 currentDismiss = showTOTPSelector(555 anchorField,556 result.entries,557 async (id: string) => {558 try {559 const entryResponse = await chrome.runtime.sendMessage({560 type: "GET_ENTRY_FOR_FILL",561 payload: { id },562 }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;563 const entry = entryResponse?.ok ? entryResponse.data : undefined;564 const code = (entry as { totpCode?: string } | undefined)?.totpCode;565 if (!code) return;566 if (otpDigitBoxes && otpDigitBoxes.length > 1) {567 fillOTPDigitBoxes(otpDigitBoxes, code);568 } else {569 setNativeValue(anchorField, code);570 }571 recordFillSuccess(anchorField);572 showToast("2FA code filled");573 } finally {574 currentDismiss = null;575 currentAnchorField = null;576 }577 },578 {579 domain,580 onDismiss: () => {581 lastDismissedField = anchorField;582 startDismissLock();583 currentDismiss = null;584 currentAnchorField = null;585 },586 }587 );588}589590591async function handleFieldInteraction(592 anchorField?: HTMLInputElement | null,593 explicitSummon = false594): Promise<void> {595 const field = anchorField ?? getDeepActiveInput();596 if (!field) return;597 if (!isVisible(field)) return;598599 600 if (passkeyToastActive) return;601602 603 604 if (!canOpen()) return;605606 607 if (currentDismiss && currentAnchorField === field) return;608609 610 611 if (field !== lastDismissedField) lastDismissedField = null;612 613 614 if (field === lastDismissedField) return;615616 617 618 619 620 if (wasAlreadyFilled(field)) return;621622 623 624 if (pendingInteractions.has(field)) return;625 pendingInteractions.add(field);626627 try {628 629 630 const otpGroup = findOTPDigitBoxGroup(field);631 if (otpGroup) {632 await openTOTPSelector(otpGroup[0]!, otpGroup);633 return;634 }635636 if (isTOTPField(field)) {637 const formFields = detectLoginFields();638 if (!isLoginForm(formFields) && !isSignupForm(formFields)) {639 await openTOTPSelector(field);640 return;641 }642 }643644 const fieldType = field.type.toLowerCase();645646 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {647 return preds[0] ?? null;648 });649650 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {651 const timeout = setTimeout(() => resolve(null), 150);652 mlPromise.then((pred) => {653 clearTimeout(timeout);654 resolve(pred);655 });656 });657658 if (passkeyToastActive) return;659660 if (!explicitSummon && fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {661 return;662 }663664 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);665 if (autofillFieldType) {666 reattachListeners(field, autofillFieldType);667 }668669 let fields = detectLoginFields();670 const targets = resolveAutofillInteractionTargets(field, fields, explicitSummon);671 if (!targets.shouldOpen) {672 return;673 }674675 const domain = getPageDomain();676 const firstResult = await fetchAutofillEntries(domain);677 if (passkeyToastActive) return;678679 680 681 682 if (firstResult.locked) {683 currentDismiss?.();684 currentAnchorField = field;685 currentDismiss = showAutofillSelector(686 field,687 [],688 () => {},689 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }690 );691 return;692 }693694 const entries = firstResult.entries;695 696 697 698 699 700 701 const loadSearchableEntries = async (): Promise<SelectorEntry[]> =>702 (await fetchAutofillEntries(domain, true, true)).entries;703704 if (passkeyToastActive) return;705706 const pwField = fields.find((f) => f.type === "password");707 708 if (!explicitSummon && !pwField && !isEmailFirstForm(fields)) return;709 const usernameEl = targets.usernameEl;710 const passwordEl = targets.passwordEl;711 const emailEl = targets.emailEl;712713 await openAutofillSelector(714 field,715 usernameEl,716 passwordEl,717 entries,718 loadSearchableEntries,719 domain,720 autofillFieldType === "email" ? "email" : "username",721 emailEl,722 );723 } finally {724 pendingInteractions.delete(field);725 }726}727728async function onFocusIn(e: Event): Promise<void> {729 730 731 732 733 734 if (isSubmitButton(e.target)) return;735 await handleFieldInteraction();736}737738function reattachListeners(739 el: HTMLInputElement,740 detectedType?: "password" | "username" | "email",741 contextFields?: ReturnType<typeof detectLoginFields>742): void {743 if (processedInputs.has(el)) return;744 if (!resolveAutofillFieldType(el, detectedType)) return;745 746 const fields = contextFields ?? detectLoginFields();747 if (!isAnyCredentialForm(fields)) return;748749 const cleanup = injectFieldIcon(el, () => {750 currentDismiss?.();751 currentDismiss = null;752 lastDismissedField = null; 753 dismissLock = false; 754 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }755 clearFillStateForExplicitSummon(el);756 el.focus({ preventScroll: true });757 void handleFieldInteraction(el, true);758 });759 processedInputs.set(el, cleanup);760}761762const debouncedReattach = debounce(() => {763 const allFields = detectLoginFields();764 if (!isAnyCredentialForm(allFields)) return;765 const newFields = allFields.filter(766 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)767 );768 for (const f of newFields) {769 reattachListeners(f.el, f.type, allFields);770 }771 772 773 774}, 200);775776function setupMutationObserver(): void {777 const observer = new MutationObserver(debouncedReattach);778 observer.observe(document.body, {779 childList: true,780 subtree: true,781 attributes: true,782 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],783 });784}785786function initialScan(aggressionLevel = 0, isFinalPass = false) {787 const allFields = detectLoginFields();788 const hasKnownForm = isAnyCredentialForm(allFields);789790 if (aggressionLevel === 0 && !hasKnownForm) return;791792 const newFields = allFields.filter(793 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)794 );795796 for (const f of newFields) {797 reattachListeners(f.el, f.type, allFields);798 }799800 801 802 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {803 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');804 for (const el of pwInputs) {805 if (isVisible(el) && !processedInputs.has(el)) {806 const cleanup = injectFieldIcon(el, () => {807 currentDismiss?.();808 currentDismiss = null;809 lastDismissedField = null;810 dismissLock = false;811 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }812 clearFillStateForExplicitSummon(el);813 el.focus({ preventScroll: true });814 void handleFieldInteraction(el, true);815 });816 processedInputs.set(el, cleanup);817 }818 }819 }820}821822823824825826const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();827828function hasLoginOrSignupForm(): boolean {829 const fields = detectLoginFields();830 return isAnyCredentialForm(fields);831}832833function injectTOTPFieldIcon(field: HTMLInputElement): void {834 if (processedTOTPInputs.has(field)) return;835 const cleanup = injectFieldIcon(field, () => {836 currentDismiss?.();837 currentDismiss = null;838 currentAnchorField = null;839 lastDismissedField = null;840 dismissLock = false;841 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }842 clearFillStateForExplicitSummon(field);843 field.focus({ preventScroll: true });844 void openTOTPSelector(field);845 });846 processedTOTPInputs.set(field, cleanup);847}848849function scanTOTPFields(): void {850 if (hasLoginOrSignupForm()) return;851 const inputs = document.querySelectorAll<HTMLInputElement>("input");852 for (const input of inputs) {853 if (!isTOTPField(input)) continue;854 injectTOTPFieldIcon(input);855 }856}857858function setupTOTPAutofill(): void {859 setTimeout(scanTOTPFields, 0);860 setTimeout(scanTOTPFields, 500);861 setTimeout(scanTOTPFields, 1500);862863 const debouncedScan = debounce(scanTOTPFields, 200);864 new MutationObserver(debouncedScan).observe(document.body, {865 childList: true,866 subtree: true,867 attributes: true,868 attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],869 });870871 document.addEventListener("focusin", (e) => {872 const target = e.target;873 if (!(target instanceof HTMLInputElement)) return;874 if (hasLoginOrSignupForm()) return;875 if (!isTOTPField(target)) return;876 injectTOTPFieldIcon(target);877 }, true);878}879880document.addEventListener("focusin", onFocusIn);881882setupMutationObserver();883setupTOTPAutofill();884setupSaveDetection();885setupCardAutofill();886887888889890891892893894let lastObservedUrl = location.href;895new MutationObserver(() => {896 if (location.href !== lastObservedUrl) {897 lastObservedUrl = location.href;898 pageFilledAt = null;899 }900}).observe(document.body, { childList: true, subtree: false });901902903904(async () => {905 let aggressionLevel = 0;906 try {907 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });908 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;909 const domain = getPageDomain();910 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;911 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;912 } catch { }913914 setTimeout(() => initialScan(aggressionLevel, false), 0);915 setTimeout(() => initialScan(aggressionLevel, false), 500);916 setTimeout(() => initialScan(aggressionLevel, true), 1500);917})();918919920921922923924const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();925let currentCardDismiss: (() => void) | null = null;926let currentCardAnchor: HTMLInputElement | null = null;927let lastDismissedCardField: HTMLInputElement | null = null;928929async function fetchSavedCards(): Promise<CardSelectorEntry[]> {930 const resp = await chrome.runtime.sendMessage({931 type: "AUTOFILL_QUERY",932 payload: { domain: getPageDomain(), kind: "card" },933 }).catch(() => null);934 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;935 return r?.ok ? (r.data ?? []) : [];936}937938async function openCardSelector(anchor: HTMLInputElement): Promise<void> {939 if (!canOpen()) return;940 if (currentCardDismiss && currentCardAnchor === anchor) return;941 if (anchor === lastDismissedCardField) return;942 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;943 if (wasAlreadyFilled(anchor)) return;944945 const cards = await fetchSavedCards();946 if (cards.length === 0) return; 947948 const cardForm = detectCardForm();949 if (!cardForm?.number) return;950951 currentCardDismiss?.();952 currentCardAnchor = anchor;953 currentCardDismiss = showCardSelector(954 anchor,955 cards,956 {957 domain: getPageDomain(),958 onFill: (entry) => {959 if (!cardForm) return;960 fillCardForm(cardForm, {961 cardNumber: entry.cardNumber ?? "",962 expMonth: entry.expMonth ?? "",963 expYear: entry.expYear ?? "",964 cvc: entry.cvc ?? "",965 cardholderName: entry.cardholderName ?? "",966 });967 968 969 970 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);971 currentCardDismiss = null;972 currentCardAnchor = null;973 },974 onDismiss: () => {975 lastDismissedCardField = anchor;976 startDismissLock();977 currentCardDismiss = null;978 currentCardAnchor = null;979 },980 }981 );982}983984function injectCardIcon(field: HTMLInputElement): void {985 if (processedCardInputs.has(field)) return;986 const cleanup = injectFieldIcon(field, () => {987 currentCardDismiss?.();988 currentCardDismiss = null;989 lastDismissedCardField = null;990 dismissLock = false;991 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }992 clearFillStateForExplicitSummon(field);993 field.focus({ preventScroll: true });994 void openCardSelector(field);995 });996 processedCardInputs.set(field, cleanup);997}998999function setupCardAutofill(): void {1000 function scan() {1001 const cardForm = detectCardForm();1002 if (!cardForm?.number) return;1003 if (!isVisible(cardForm.number)) return;1004 injectCardIcon(cardForm.number);1005 }10061007 1008 1009 setTimeout(scan, 0);1010 setTimeout(scan, 500);1011 setTimeout(scan, 1500);10121013 1014 1015 1016 let pending = false;1017 new MutationObserver(() => {1018 if (pending) return;1019 pending = true;1020 setTimeout(() => { pending = false; scan(); }, 200);1021 }).observe(document.body, { childList: true, subtree: true });10221023 1024 1025 1026 document.addEventListener("focusin", (e) => {1027 const target = e.target;1028 if (!(target instanceof HTMLInputElement)) return;1029 const cardForm = detectCardForm();1030 if (cardForm?.number === target) {1031 injectCardIcon(target);1032 }1033 }, true);1034}10351036chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {1037 1038 if (sender.id !== chrome.runtime.id) return;1039 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {1040 const policy = detectPasswordPolicy();1041 sendResponse({ ok: true, data: policy });1042 return true;1043 }1044 if (msg?.type === "PING") {1045 sendResponse({ ok: true });1046 return true;1047 }1048 if (msg?.type === "SUMMON_AUTOFILL") {1049 const source = (msg as { type: string; source?: string }).source;1050 const isShortcut = source === "shortcut";1051 const isPasskeyUnlock = source === "passkey-unlock";10521053 const activeInput = getDeepActiveInput();1054 const fields = detectLoginFields();1055 const hasForm = isAnyCredentialForm(fields);10561057 if (hasForm) {1058 1059 1060 const inForm = activeInput && fields.some(f => f.el === activeInput);1061 const target = inForm1062 ? activeInput1063 : (fields.find(f => f.type === "password")?.el1064 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1065 if (target) {1066 1067 1068 clearFillStateForExplicitSummon(target);1069 dismissLock = false;1070 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1071 lastDismissedField = null;1072 void handleFieldInteraction(target);1073 }1074 } else if (isPasskeyUnlock) {1075 1076 1077 1078 const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1079 ? document.activeElement as unknown as HTMLInputElement1080 : null;1081 if (anchor) {1082 currentDismiss?.();1083 currentAnchorField = null;1084 passkeySummonActive = true;1085 currentDismiss = showAutofillSelector(anchor, [], () => {}, {1086 domain: getPageDomain(),1087 locked: true,1088 onDismiss: () => { passkeySummonActive = false; },1089 });1090 }1091 } else if (isShortcut) {1092 1093 showSearchPalette();1094 }10951096 1097 if (isShortcut) {1098 const domain = getPageDomain();1099 if (domain) {1100 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1101 }1102 }11031104 sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });1105 return true;1106 }1107 if (msg?.type === "PASSKEY_PRO_GATE") {1108 1109 1110 showPasskeyProGate();1111 sendResponse({ ok: true });1112 return true;1113 }1114 if (msg?.type === "SHOW_PASSKEY_TOAST") {1115 1116 passkeyToastActive = true;1117 if (currentDismiss) {1118 currentDismiss();1119 currentDismiss = null;1120 currentAnchorField = null;1121 }1122 return false; 1123 }1124 if (msg?.type === "DISMISS_PASSKEY_TOAST") {1125 passkeyToastActive = false;1126 return false; 1127 }1128 if (msg?.type === "VAULT_UNLOCKED") {1129 if (passkeySummonActive) {1130 1131 1132 passkeySummonActive = false;1133 if (currentDismiss) {1134 currentDismiss();1135 currentDismiss = null;1136 currentAnchorField = null;1137 }1138 sendResponse({ ok: true });1139 return true;1140 }1141 1142 1143 const savedField = currentAnchorField;1144 if (currentDismiss) {1145 currentDismiss();1146 currentDismiss = null;1147 currentAnchorField = null;1148 }1149 void handleFieldInteraction(savedField ?? undefined);1150 sendResponse({ ok: true });1151 return true;1152 }1153 return true;1154});1155115611571158window.addEventListener("message", (e: MessageEvent) => {1159 1160 1161 if (e.source !== window) return;1162 const d = e.data as { source?: string; type?: string } | undefined;1163 if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {1164 passkeyToastActive = false;1165 }1166});1167116811691170117111721173117411751176117711781179if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {1180 let lastPasskeyOfferAt = 0;1181 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;11821183 window.addEventListener("message", (event: MessageEvent) => {1184 if (event.source !== window) return;1185 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;1186 if (!data || data.source !== "peach-passkey-firefox") return;1187 if (detectBrowser() !== "firefox") return;1188 if (data.type !== "create") return;11891190 1191 1192 const now = Date.now();1193 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1194 lastPasskeyOfferAt = now;11951196 const domain = location.hostname.replace(/^www\./, "");1197 chrome.runtime.sendMessage({1198 type: "GET_PASSKEY_OFFER_DECLINED",1199 payload: { domain },1200 }).then((res: { ok: boolean; data?: boolean } | undefined) => {1201 if (res?.data === true) return;1202 const rpId = data.rpId ?? domain;1203 showPasskeyRegistrationOffer({1204 rpId,1205 rpName: data.rpName,1206 userName: data.userName,1207 userDisplayName: data.userDisplayName,1208 });1209 }).catch(() => {});1210 });1211}121212131214121512161217121812191220122112221223122412251226{1227 function checkPasskeyAvailability() {1228 const domain = location.hostname.replace(/^www\./, "");1229 if (!domain) return;1230 const sessionKey = `peach_state11_shown:${domain}`;1231 chrome.storage.session?.get(sessionKey).then((stored) => {1232 if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1233 chrome.runtime.sendMessage({1234 type: "GET_PASSKEY_FOR_DOMAIN",1235 payload: { domain },1236 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1237 const data = res?.data;1238 if (!data) return;1239 const current = detectBrowser();1240 const isCrossBrowser =1241 data.browser && current !== "unknown" && data.browser !== current;1242 const valuableOnFirefox = current === "firefox";1243 if (!isCrossBrowser && !valuableOnFirefox) return;1244 chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1245 showPasskeyAvailable({1246 rpId: data.rpId,1247 userName: data.userName,1248 fromBrowser: data.browser,1249 currentBrowser: current,1250 });1251 }).catch(() => {});1252 }).catch(() => {});1253 }12541255 1256 1257 1258 if (document.readyState === "loading") {1259 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1260 } else {1261 setTimeout(checkPasskeyAvailability, 800);1262 }1263}