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 const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });253 const r = resp as { ok: boolean; data?: { password?: string } };254 if (r.ok && r.data?.password) {255 let alreadyWritten = false;256 try {257 await navigator.clipboard.writeText(r.data.password);258 alreadyWritten = true;259 } catch (err) {260 console.warn("[Peach] clipboard write denied:", err);261 }262 const copyResp = await chrome.runtime.sendMessage({263 type: "COPY",264 payload: { text: r.data.password, label: "Password", alreadyWritten },265 }) as { ok?: boolean } | undefined;266 if (alreadyWritten || copyResp?.ok) {267 showToast("Password copied");268 } else {269 showToast("Could not copy password — clipboard blocked");270 }271 } else {272 showToast("Could not copy password");273 }274 close();275 document.removeEventListener("keydown", onKeyDown, true);276 };277 list.appendChild(row);278 }279 }280281 searchInput.oninput = () => { query = searchInput.value; render(); };282283 fetchAutofillEntries(getPageDomain(), true).then(result => {284 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }285 allEntries = result.entries;286 render();287 searchInput.focus();288 });289}290291function findTOTPField(root: Document | Element = document): HTMLInputElement | null {292 const inputs = root.querySelectorAll<HTMLInputElement>("input");293 for (const input of inputs) {294 if (isTOTPField(input)) return input;295 }296 return null;297}298299function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {300 const form = passwordEl.closest("form");301 return findTOTPField(form ?? document);302}303304305async function handleAutofill(306 _field: HTMLInputElement,307 usernameEl: HTMLInputElement | null,308 passwordEl: HTMLInputElement | null,309 entry: VaultEntry,310 emailEl?: HTMLInputElement | null311): Promise<HTMLInputElement | null> {312 if (!entry.username && !entry.password && !entry.email) return null;313 const pageDomain = getPageDomain();314 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;315 316 317 318 const emailValue = entry.email ?? (entry.username?.includes("@") ? entry.username : "");319 fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain, emailEl, emailValue);320 let filledTOTPField: HTMLInputElement | null = null;321322 if (entry.canary) {323 chrome.runtime.sendMessage({324 type: "FIRE_CANARY_PING",325 payload: {326 webhookUrl: entry.canary.webhookUrl,327 entryTitle: entry.title,328 trigger: "autofilled",329 },330 }).catch(() => {});331 chrome.runtime.sendMessage({332 type: "UPDATE_ENTRY",333 payload: {334 id: entry.id,335 patch: {336 canary: {337 ...entry.canary,338 lastPinged: Date.now(),339 pingCount: (entry.canary.pingCount ?? 0) + 1,340 },341 },342 },343 }).catch(() => {});344 }345346 347 348 const totpCode = (entry as { totpCode?: string }).totpCode;349 if (totpCode) {350 const code = totpCode;351 const totpField = passwordEl ? findSameLoginTOTPField(passwordEl) : null;352 if (fillTOTPCode(totpField, code)) {353 filledTOTPField = totpField;354 }355 let alreadyWritten = false;356 try {357 await navigator.clipboard.writeText(code);358 alreadyWritten = true;359 } catch (err) {360 console.warn("[Peach] clipboard write denied:", err);361 }362 const response = await chrome.runtime.sendMessage({363 type: "COPY",364 payload: { text: code, label: "TOTP", alreadyWritten },365 });366 if (filledTOTPField) {367 showToast("2FA code filled");368 } else if (alreadyWritten || (response as { ok?: boolean }).ok) {369 370 371 372 showToast("2FA code copied");373 } else {374 showToast("Could not copy TOTP — clipboard blocked");375 }376 }377378 return filledTOTPField;379}380381async function fetchAutofillEntries(382 domain: string,383 includeAll = false384): Promise<{ entries: SelectorEntry[]; locked: boolean }> {385 const response = await chrome.runtime.sendMessage({386 type: "AUTOFILL_QUERY",387 payload: { domain, includeAll },388 });389 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };390 if (!res.ok && res.error === "vault_locked") {391 return { entries: [], locked: true };392 }393 return { entries: res.data ?? [], locked: false };394}395396async function fetchTOTPEntries(397 domain: string398): Promise<{ entries: SelectorEntry[]; locked: boolean }> {399 const response = await chrome.runtime.sendMessage({400 type: "AUTOFILL_QUERY",401 payload: { domain, kind: "totp" },402 });403 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };404 if (!res.ok && res.error === "vault_locked") {405 return { entries: [], locked: true };406 }407 return { entries: res.data ?? [], locked: false };408}409410411function resolveAutofillFieldType(412 el: HTMLInputElement,413 predictedType?: FieldPrediction["type"] | null414): "password" | "username" | "email" | null {415 if (416 predictedType === "password" ||417 predictedType === "username" ||418 predictedType === "email"419 ) {420 return predictedType;421 }422423 const detected = detectLoginFields().find((field) => field.el === el)?.type;424 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {425 return detected;426 }427428 const htmlType = el.type.toLowerCase();429 if (htmlType === "password") return "password";430 if (htmlType === "email") return "email";431 return null;432}433434async function openAutofillSelector(435 anchorField: HTMLInputElement,436 usernameEl: HTMLInputElement | null,437 passwordEl: HTMLInputElement | null,438 domainEntries: SelectorEntry[],439 searchableEntries: SelectorEntry[],440 domain: string,441 identityKind: "email" | "username",442 emailEl?: HTMLInputElement | null443): Promise<void> {444 445 446 447 const isSignup = domainEntries.length === 0;448 let savedIdentities: SavedIdentity[] | undefined;449 let confirmEl: HTMLInputElement | null = null;450 if (isSignup) {451 try {452 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as453 { ok: boolean; data?: SavedIdentity[] } | null;454 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;455 } catch { }456457 const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body;458 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));459 confirmEl = allPwInputs.find(460 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)461 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);462 }463464 currentDismiss?.();465 currentAnchorField = anchorField;466 currentDismiss = showAutofillSelector(467 anchorField,468 domainEntries,469 async (id: string) => {470 currentDismiss = null;471 currentAnchorField = null;472 const entryResponse = await chrome.runtime.sendMessage({473 type: "GET_ENTRY_FOR_FILL",474 payload: { id },475 });476 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;477 if (entry) {478 const filledTOTPField = await handleAutofill(anchorField, usernameEl, passwordEl, entry, emailEl);479 recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);480 481 482 483 const pageDomain = location.hostname.replace(/^www\./, "");484 const entryDomains = new Set<string>();485 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {486 try {487 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));488 } catch { }489 }490 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {491 showRememberSiteToast(pageDomain, entry.id);492 }493 }494 },495 {496 domain,497 searchableEntries,498 isSignup,499 identityKind,500 savedIdentities,501 onFillFields: (username, password, email) => {502 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;503 fillFields(usernameEl, passwordEl, username, password, form, getPageDomain(), emailEl, email);504 if (password && confirmEl) setNativeValue(confirmEl, password);505 recordFillSuccess(anchorField, usernameEl, passwordEl);506 },507 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },508 }509 );510}511512async function openTOTPSelector(anchorField: HTMLInputElement, otpDigitBoxes?: HTMLInputElement[]): Promise<void> {513 if (!canOpen()) return;514 if (currentDismiss && currentAnchorField === anchorField) return;515 if (anchorField !== lastDismissedField) lastDismissedField = null;516 if (anchorField === lastDismissedField) return;517 if (wasAlreadyFilled(anchorField)) return;518519 const domain = getPageDomain();520 const result = await fetchTOTPEntries(domain);521522 if (result.locked) {523 currentDismiss?.();524 currentAnchorField = anchorField;525 currentDismiss = showAutofillSelector(526 anchorField,527 [],528 () => {},529 {530 domain,531 locked: true,532 onUnlocked: () => void openTOTPSelector(anchorField),533 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },534 }535 );536 return;537 }538539 if (result.entries.length === 0) {540 lastDismissedField = anchorField;541 startDismissLock();542 showToast("No 2FA entries for this site — add a code in Peach first");543 return;544 }545546 currentDismiss?.();547 currentAnchorField = anchorField;548 currentDismiss = showTOTPSelector(549 anchorField,550 result.entries,551 async (id: string) => {552 try {553 const entryResponse = await chrome.runtime.sendMessage({554 type: "GET_ENTRY_FOR_FILL",555 payload: { id },556 }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;557 const entry = entryResponse?.ok ? entryResponse.data : undefined;558 const code = (entry as { totpCode?: string } | undefined)?.totpCode;559 if (!code) return;560 if (otpDigitBoxes && otpDigitBoxes.length > 1) {561 fillOTPDigitBoxes(otpDigitBoxes, code);562 } else {563 setNativeValue(anchorField, code);564 }565 recordFillSuccess(anchorField);566 showToast("2FA code filled");567 } finally {568 currentDismiss = null;569 currentAnchorField = null;570 }571 },572 {573 domain,574 onDismiss: () => {575 lastDismissedField = anchorField;576 startDismissLock();577 currentDismiss = null;578 currentAnchorField = null;579 },580 }581 );582}583584585async function handleFieldInteraction(586 anchorField?: HTMLInputElement | null,587 explicitSummon = false588): Promise<void> {589 const field = anchorField ?? getDeepActiveInput();590 if (!field) return;591 if (!isVisible(field)) return;592593 594 if (passkeyToastActive) return;595596 597 598 if (!canOpen()) return;599600 601 if (currentDismiss && currentAnchorField === field) return;602603 604 605 if (field !== lastDismissedField) lastDismissedField = null;606 607 608 if (field === lastDismissedField) return;609610 611 612 613 614 if (wasAlreadyFilled(field)) return;615616 617 618 if (pendingInteractions.has(field)) return;619 pendingInteractions.add(field);620621 try {622 623 624 const otpGroup = findOTPDigitBoxGroup(field);625 if (otpGroup) {626 await openTOTPSelector(otpGroup[0]!, otpGroup);627 return;628 }629630 if (isTOTPField(field)) {631 const formFields = detectLoginFields();632 if (!isLoginForm(formFields) && !isSignupForm(formFields)) {633 await openTOTPSelector(field);634 return;635 }636 }637638 const fieldType = field.type.toLowerCase();639640 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {641 return preds[0] ?? null;642 });643644 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {645 const timeout = setTimeout(() => resolve(null), 150);646 mlPromise.then((pred) => {647 clearTimeout(timeout);648 resolve(pred);649 });650 });651652 if (passkeyToastActive) return;653654 if (!explicitSummon && fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {655 return;656 }657658 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);659 if (autofillFieldType) {660 reattachListeners(field, autofillFieldType);661 }662663 let fields = detectLoginFields();664 const targets = resolveAutofillInteractionTargets(field, fields, explicitSummon);665 if (!targets.shouldOpen) {666 return;667 }668669 const domain = getPageDomain();670 const firstResult = await fetchAutofillEntries(domain);671 if (passkeyToastActive) return;672673 674 675 676 if (firstResult.locked) {677 currentDismiss?.();678 currentAnchorField = field;679 currentDismiss = showAutofillSelector(680 field,681 [],682 () => {},683 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }684 );685 return;686 }687688 const entries = firstResult.entries;689 690 691 692 693 const allEntries = (await fetchAutofillEntries(domain, true)).entries;694695 if (passkeyToastActive) return;696697 const pwField = fields.find((f) => f.type === "password");698 699 if (!explicitSummon && !pwField && !isEmailFirstForm(fields)) return;700 const usernameEl = targets.usernameEl;701 const passwordEl = targets.passwordEl;702 const emailEl = targets.emailEl;703704 await openAutofillSelector(705 field,706 usernameEl,707 passwordEl,708 entries,709 allEntries,710 domain,711 autofillFieldType === "email" ? "email" : "username",712 emailEl,713 );714 } finally {715 pendingInteractions.delete(field);716 }717}718719async function onFocusIn(e: Event): Promise<void> {720 721 722 723 724 725 if (isSubmitButton(e.target)) return;726 await handleFieldInteraction();727}728729function reattachListeners(730 el: HTMLInputElement,731 detectedType?: "password" | "username" | "email",732 contextFields?: ReturnType<typeof detectLoginFields>733): void {734 if (processedInputs.has(el)) return;735 if (!resolveAutofillFieldType(el, detectedType)) return;736 737 const fields = contextFields ?? detectLoginFields();738 if (!isAnyCredentialForm(fields)) return;739740 const cleanup = injectFieldIcon(el, () => {741 currentDismiss?.();742 currentDismiss = null;743 lastDismissedField = null; 744 dismissLock = false; 745 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }746 clearFillStateForExplicitSummon(el);747 el.focus({ preventScroll: true });748 void handleFieldInteraction(el, true);749 });750 processedInputs.set(el, cleanup);751}752753const debouncedReattach = debounce(() => {754 const allFields = detectLoginFields();755 if (!isAnyCredentialForm(allFields)) return;756 const newFields = allFields.filter(757 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)758 );759 for (const f of newFields) {760 reattachListeners(f.el, f.type, allFields);761 }762 763 764 765}, 200);766767function setupMutationObserver(): void {768 const observer = new MutationObserver(debouncedReattach);769 observer.observe(document.body, {770 childList: true,771 subtree: true,772 attributes: true,773 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],774 });775}776777function initialScan(aggressionLevel = 0, isFinalPass = false) {778 const allFields = detectLoginFields();779 const hasKnownForm = isAnyCredentialForm(allFields);780781 if (aggressionLevel === 0 && !hasKnownForm) return;782783 const newFields = allFields.filter(784 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)785 );786787 for (const f of newFields) {788 reattachListeners(f.el, f.type, allFields);789 }790791 792 793 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {794 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');795 for (const el of pwInputs) {796 if (isVisible(el) && !processedInputs.has(el)) {797 const cleanup = injectFieldIcon(el, () => {798 currentDismiss?.();799 currentDismiss = null;800 lastDismissedField = null;801 dismissLock = false;802 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }803 clearFillStateForExplicitSummon(el);804 el.focus({ preventScroll: true });805 void handleFieldInteraction(el, true);806 });807 processedInputs.set(el, cleanup);808 }809 }810 }811}812813814815816817const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();818819function hasLoginOrSignupForm(): boolean {820 const fields = detectLoginFields();821 return isAnyCredentialForm(fields);822}823824function injectTOTPFieldIcon(field: HTMLInputElement): void {825 if (processedTOTPInputs.has(field)) return;826 const cleanup = injectFieldIcon(field, () => {827 currentDismiss?.();828 currentDismiss = null;829 currentAnchorField = null;830 lastDismissedField = null;831 dismissLock = false;832 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }833 clearFillStateForExplicitSummon(field);834 field.focus({ preventScroll: true });835 void openTOTPSelector(field);836 });837 processedTOTPInputs.set(field, cleanup);838}839840function scanTOTPFields(): void {841 if (hasLoginOrSignupForm()) return;842 const inputs = document.querySelectorAll<HTMLInputElement>("input");843 for (const input of inputs) {844 if (!isTOTPField(input)) continue;845 injectTOTPFieldIcon(input);846 }847}848849function setupTOTPAutofill(): void {850 setTimeout(scanTOTPFields, 0);851 setTimeout(scanTOTPFields, 500);852 setTimeout(scanTOTPFields, 1500);853854 const debouncedScan = debounce(scanTOTPFields, 200);855 new MutationObserver(debouncedScan).observe(document.body, {856 childList: true,857 subtree: true,858 attributes: true,859 attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],860 });861862 document.addEventListener("focusin", (e) => {863 const target = e.target;864 if (!(target instanceof HTMLInputElement)) return;865 if (hasLoginOrSignupForm()) return;866 if (!isTOTPField(target)) return;867 injectTOTPFieldIcon(target);868 }, true);869}870871document.addEventListener("focusin", onFocusIn);872873setupMutationObserver();874setupTOTPAutofill();875setupSaveDetection();876setupCardAutofill();877878879880881882883884885let lastObservedUrl = location.href;886new MutationObserver(() => {887 if (location.href !== lastObservedUrl) {888 lastObservedUrl = location.href;889 pageFilledAt = null;890 }891}).observe(document.body, { childList: true, subtree: false });892893894895(async () => {896 let aggressionLevel = 0;897 try {898 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });899 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;900 const domain = getPageDomain();901 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;902 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;903 } catch { }904905 setTimeout(() => initialScan(aggressionLevel, false), 0);906 setTimeout(() => initialScan(aggressionLevel, false), 500);907 setTimeout(() => initialScan(aggressionLevel, true), 1500);908})();909910911912913914915const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();916let currentCardDismiss: (() => void) | null = null;917let currentCardAnchor: HTMLInputElement | null = null;918let lastDismissedCardField: HTMLInputElement | null = null;919920async function fetchSavedCards(): Promise<CardSelectorEntry[]> {921 const resp = await chrome.runtime.sendMessage({922 type: "AUTOFILL_QUERY",923 payload: { domain: getPageDomain(), kind: "card" },924 }).catch(() => null);925 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;926 return r?.ok ? (r.data ?? []) : [];927}928929async function openCardSelector(anchor: HTMLInputElement): Promise<void> {930 if (!canOpen()) return;931 if (currentCardDismiss && currentCardAnchor === anchor) return;932 if (anchor === lastDismissedCardField) return;933 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;934 if (wasAlreadyFilled(anchor)) return;935936 const cards = await fetchSavedCards();937 if (cards.length === 0) return; 938939 const cardForm = detectCardForm();940 if (!cardForm?.number) return;941942 currentCardDismiss?.();943 currentCardAnchor = anchor;944 currentCardDismiss = showCardSelector(945 anchor,946 cards,947 {948 domain: getPageDomain(),949 onFill: (entry) => {950 if (!cardForm) return;951 fillCardForm(cardForm, {952 cardNumber: entry.cardNumber ?? "",953 expMonth: entry.expMonth ?? "",954 expYear: entry.expYear ?? "",955 cvc: entry.cvc ?? "",956 cardholderName: entry.cardholderName ?? "",957 });958 959 960 961 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);962 currentCardDismiss = null;963 currentCardAnchor = null;964 },965 onDismiss: () => {966 lastDismissedCardField = anchor;967 startDismissLock();968 currentCardDismiss = null;969 currentCardAnchor = null;970 },971 }972 );973}974975function injectCardIcon(field: HTMLInputElement): void {976 if (processedCardInputs.has(field)) return;977 const cleanup = injectFieldIcon(field, () => {978 currentCardDismiss?.();979 currentCardDismiss = null;980 lastDismissedCardField = null;981 dismissLock = false;982 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }983 clearFillStateForExplicitSummon(field);984 field.focus({ preventScroll: true });985 void openCardSelector(field);986 });987 processedCardInputs.set(field, cleanup);988}989990function setupCardAutofill(): void {991 function scan() {992 const cardForm = detectCardForm();993 if (!cardForm?.number) return;994 if (!isVisible(cardForm.number)) return;995 injectCardIcon(cardForm.number);996 }997998 999 1000 setTimeout(scan, 0);1001 setTimeout(scan, 500);1002 setTimeout(scan, 1500);10031004 1005 1006 1007 let pending = false;1008 new MutationObserver(() => {1009 if (pending) return;1010 pending = true;1011 setTimeout(() => { pending = false; scan(); }, 200);1012 }).observe(document.body, { childList: true, subtree: true });10131014 1015 1016 1017 document.addEventListener("focusin", (e) => {1018 const target = e.target;1019 if (!(target instanceof HTMLInputElement)) return;1020 const cardForm = detectCardForm();1021 if (cardForm?.number === target) {1022 injectCardIcon(target);1023 }1024 }, true);1025}10261027chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {1028 1029 if (sender.id !== chrome.runtime.id) return;1030 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {1031 const policy = detectPasswordPolicy();1032 sendResponse({ ok: true, data: policy });1033 return true;1034 }1035 if (msg?.type === "PING") {1036 sendResponse({ ok: true });1037 return true;1038 }1039 if (msg?.type === "SUMMON_AUTOFILL") {1040 const source = (msg as { type: string; source?: string }).source;1041 const isShortcut = source === "shortcut";1042 const isPasskeyUnlock = source === "passkey-unlock";10431044 const activeInput = getDeepActiveInput();1045 const fields = detectLoginFields();1046 const hasForm = isAnyCredentialForm(fields);10471048 if (hasForm) {1049 1050 1051 const inForm = activeInput && fields.some(f => f.el === activeInput);1052 const target = inForm1053 ? activeInput1054 : (fields.find(f => f.type === "password")?.el1055 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1056 if (target) {1057 1058 1059 clearFillStateForExplicitSummon(target);1060 dismissLock = false;1061 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1062 lastDismissedField = null;1063 void handleFieldInteraction(target);1064 }1065 } else if (isPasskeyUnlock) {1066 1067 1068 1069 const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1070 ? document.activeElement as unknown as HTMLInputElement1071 : null;1072 if (anchor) {1073 currentDismiss?.();1074 currentAnchorField = null;1075 passkeySummonActive = true;1076 currentDismiss = showAutofillSelector(anchor, [], () => {}, {1077 domain: getPageDomain(),1078 locked: true,1079 onDismiss: () => { passkeySummonActive = false; },1080 });1081 }1082 } else if (isShortcut) {1083 1084 showSearchPalette();1085 }10861087 1088 if (isShortcut) {1089 const domain = getPageDomain();1090 if (domain) {1091 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1092 }1093 }10941095 sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });1096 return true;1097 }1098 if (msg?.type === "PASSKEY_PRO_GATE") {1099 1100 1101 showPasskeyProGate();1102 sendResponse({ ok: true });1103 return true;1104 }1105 if (msg?.type === "SHOW_PASSKEY_TOAST") {1106 1107 passkeyToastActive = true;1108 if (currentDismiss) {1109 currentDismiss();1110 currentDismiss = null;1111 currentAnchorField = null;1112 }1113 return false; 1114 }1115 if (msg?.type === "DISMISS_PASSKEY_TOAST") {1116 passkeyToastActive = false;1117 return false; 1118 }1119 if (msg?.type === "VAULT_UNLOCKED") {1120 if (passkeySummonActive) {1121 1122 1123 passkeySummonActive = false;1124 if (currentDismiss) {1125 currentDismiss();1126 currentDismiss = null;1127 currentAnchorField = null;1128 }1129 sendResponse({ ok: true });1130 return true;1131 }1132 1133 1134 const savedField = currentAnchorField;1135 if (currentDismiss) {1136 currentDismiss();1137 currentDismiss = null;1138 currentAnchorField = null;1139 }1140 void handleFieldInteraction(savedField ?? undefined);1141 sendResponse({ ok: true });1142 return true;1143 }1144 return true;1145});1146114711481149window.addEventListener("message", (e: MessageEvent) => {1150 1151 1152 if (e.source !== window) return;1153 const d = e.data as { source?: string; type?: string } | undefined;1154 if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {1155 passkeyToastActive = false;1156 }1157});1158115911601161116211631164116511661167116811691170if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {1171 let lastPasskeyOfferAt = 0;1172 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;11731174 window.addEventListener("message", (event: MessageEvent) => {1175 if (event.source !== window) return;1176 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;1177 if (!data || data.source !== "peach-passkey-firefox") return;1178 if (detectBrowser() !== "firefox") return;1179 if (data.type !== "create") return;11801181 1182 1183 const now = Date.now();1184 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1185 lastPasskeyOfferAt = now;11861187 const domain = location.hostname.replace(/^www\./, "");1188 chrome.runtime.sendMessage({1189 type: "GET_PASSKEY_OFFER_DECLINED",1190 payload: { domain },1191 }).then((res: { ok: boolean; data?: boolean } | undefined) => {1192 if (res?.data === true) return;1193 const rpId = data.rpId ?? domain;1194 showPasskeyRegistrationOffer({1195 rpId,1196 rpName: data.rpName,1197 userName: data.userName,1198 userDisplayName: data.userDisplayName,1199 });1200 }).catch(() => {});1201 });1202}120312041205120612071208120912101211121212131214121512161217{1218 function checkPasskeyAvailability() {1219 const domain = location.hostname.replace(/^www\./, "");1220 if (!domain) return;1221 const sessionKey = `peach_state11_shown:${domain}`;1222 chrome.storage.session?.get(sessionKey).then((stored) => {1223 if (stored && (stored as Record<string, unknown>)[sessionKey]) 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" } | null } | undefined) => {1228 const data = res?.data;1229 if (!data) 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.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1236 showPasskeyAvailable({1237 rpId: data.rpId,1238 userName: data.userName,1239 fromBrowser: data.browser,1240 currentBrowser: current,1241 });1242 }).catch(() => {});1243 }).catch(() => {});1244 }12451246 1247 1248 1249 if (document.readyState === "loading") {1250 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1251 } else {1252 setTimeout(checkPasskeyAvailability, 800);1253 }1254}