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 { setupSaveDetection } from "./save";30import { contentMLDetector } from "./content-ml-detector";31import { detectPasswordPolicy } from "./policy";32import type { FieldPrediction } from "../shared/ml";33import type { SavedIdentity, VaultEntry } from "../shared/types";343536373839const processedInputs = new WeakMap<HTMLInputElement, () => void>();40const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);4142let currentDismiss: (() => void) | null = null;4344let currentAnchorField: HTMLInputElement | null = null;4546const pendingInteractions = new WeakSet<HTMLInputElement>();47484950let lastDismissedField: HTMLInputElement | null = null;51525354555657const DISMISS_LOCK_MS = 800;58let dismissLock = false;59let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;60616263let passkeySummonActive = false;64656667let passkeyToastActive = false;68function startDismissLock(): void {69 dismissLock = true;70 if (dismissLockTimer) clearTimeout(dismissLockTimer);71 dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);72}73function canOpen(): boolean { return !dismissLock; }7475767778798081828384858687const filledForms = new WeakSet<HTMLFormElement>();88let pageFilledAt: number | null = null;89const PAGE_FILL_GRACE_MS = 3000;9091function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {92 for (const f of fields) {93 if (!f) continue;94 const form = f.closest("form");95 if (form) filledForms.add(form);96 }97 pageFilledAt = Date.now();98}99100function wasAlreadyFilled(field: HTMLInputElement): boolean {101 const form = field.closest("form");102 if (form && filledForms.has(form)) return true;103 if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;104 return false;105}106107function clearFillStateForExplicitSummon(field: HTMLInputElement): void {108 const form = field.closest("form");109 if (form) filledForms.delete(form);110 pageFilledAt = null;111}112113114115116117function isSubmitButton(el: EventTarget | null): boolean {118 if (!(el instanceof HTMLElement)) return false;119 if (el instanceof HTMLButtonElement && el.type !== "button") return true;120 if (el instanceof HTMLInputElement && el.type === "submit") return true;121 if (el.getAttribute("type") === "submit") return true;122 const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();123 if (!text || text.length > 24) return false;124 return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);125}126127function debounce<T extends (...args: unknown[]) => void>(128 fn: T,129 ms: number130): (...args: Parameters<T>) => void {131 let timer: ReturnType<typeof setTimeout>;132 return (...args: Parameters<T>) => {133 clearTimeout(timer);134 timer = setTimeout(() => fn(...args), ms);135 };136}137138function showToast(message: string): void {139 const toast = document.createElement("div");140 toast.style.cssText = `141 position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);142 background: #131109; color: #F0E8D8; padding: 8px 16px;143 border-radius: 8px; font-family: 'IBM Plex Mono', monospace;144 font-size: 11px; z-index: 2147483647; opacity: 0;145 transition: opacity 200ms ease;146 border: 1px solid rgba(240,232,216,0.07);147 pointer-events: none;148 `;149 toast.textContent = message;150 document.body.appendChild(toast);151 requestAnimationFrame(() => { toast.style.opacity = "1"; });152 setTimeout(() => {153 toast.style.opacity = "0";154 setTimeout(() => toast.remove(), 200);155 }, 2000);156}157158function showSearchPalette(): void {159 const host = document.createElement("div");160 host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";161 document.body.appendChild(host);162 const shadow = host.attachShadow({ mode: "closed" });163164 const style = document.createElement("style");165 style.textContent = `166 .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;167 font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;168 box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}169 .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);170 font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}171 .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}172 .s{padding:8px 12px}173 .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);174 border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;175 padding:6px 8px;font-family:inherit;font-size:12px;outline:none}176 .l{max-height:220px;overflow-y:auto}177 .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}178 .e:hover{background:rgba(240,232,216,.06)}179 .et{font-size:12px}180 .eu{font-size:10px;color:rgba(240,232,216,.45)}181 .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}182 `;183184 let allEntries: SelectorEntry[] = [];185 let query = "";186187 const panel = document.createElement("div");188 panel.className = "p";189190 const hdr = document.createElement("div");191 hdr.className = "h";192 const hdrText = document.createElement("span");193 hdrText.textContent = "No form detected — search your vault";194 const closeBtn = document.createElement("button");195 closeBtn.className = "x";196 closeBtn.textContent = "✕";197 hdr.appendChild(hdrText);198 hdr.appendChild(closeBtn);199200 const searchWrap = document.createElement("div");201 searchWrap.className = "s";202 const searchInput = document.createElement("input");203 searchInput.placeholder = "search...";204 searchWrap.appendChild(searchInput);205206 const list = document.createElement("div");207 list.className = "l";208209 panel.appendChild(hdr);210 panel.appendChild(searchWrap);211 panel.appendChild(list);212 shadow.appendChild(style);213 shadow.appendChild(panel);214215 function close() { host.remove(); }216217 closeBtn.onclick = close;218219 function onKeyDown(e: KeyboardEvent) {220 if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }221 }222 document.addEventListener("keydown", onKeyDown, true);223224 function render() {225 const q = query.toLowerCase();226 const filtered = q227 ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))228 : allEntries;229 list.innerHTML = "";230 if (filtered.length === 0) {231 const em = document.createElement("div");232 em.className = "em";233 em.textContent = query ? "no matches" : "vault is empty";234 list.appendChild(em);235 return;236 }237 for (const entry of filtered.slice(0, 20)) {238 const row = document.createElement("div");239 row.className = "e";240 const title = document.createElement("div");241 title.className = "et";242 title.textContent = entry.title;243 row.appendChild(title);244 if (entry.username) {245 const user = document.createElement("div");246 user.className = "eu";247 user.textContent = entry.username;248 row.appendChild(user);249 }250 row.onclick = async () => {251 const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });252 const r = resp as { ok: boolean; data?: { password?: string } };253 if (r.ok && r.data?.password) {254 let alreadyWritten = false;255 try {256 await navigator.clipboard.writeText(r.data.password);257 alreadyWritten = true;258 } catch (err) {259 console.warn("[Peach] clipboard write denied:", err);260 }261 const copyResp = await chrome.runtime.sendMessage({262 type: "COPY",263 payload: { text: r.data.password, label: "Password", alreadyWritten },264 }) as { ok?: boolean } | undefined;265 if (alreadyWritten || copyResp?.ok) {266 showToast("Password copied");267 } else {268 showToast("Could not copy password — clipboard blocked");269 }270 } else {271 showToast("Could not copy password");272 }273 close();274 document.removeEventListener("keydown", onKeyDown, true);275 };276 list.appendChild(row);277 }278 }279280 searchInput.oninput = () => { query = searchInput.value; render(); };281282 fetchAutofillEntries(getPageDomain(), true).then(result => {283 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }284 allEntries = result.entries;285 render();286 searchInput.focus();287 });288}289290function findTOTPField(root: Document | Element = document): HTMLInputElement | null {291 const inputs = root.querySelectorAll<HTMLInputElement>("input");292 for (const input of inputs) {293 if (isTOTPField(input)) return input;294 }295 return null;296}297298function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {299 const form = passwordEl.closest("form");300 return findTOTPField(form ?? document);301}302303304async function handleAutofill(305 _field: HTMLInputElement,306 usernameEl: HTMLInputElement | null,307 passwordEl: HTMLInputElement | null,308 entry: VaultEntry309): Promise<HTMLInputElement | null> {310 if (!entry.username && !entry.password) return null;311 const pageDomain = getPageDomain();312 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;313 fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);314 let filledTOTPField: HTMLInputElement | null = null;315316 if (entry.canary) {317 chrome.runtime.sendMessage({318 type: "FIRE_CANARY_PING",319 payload: {320 webhookUrl: entry.canary.webhookUrl,321 entryTitle: entry.title,322 trigger: "autofilled",323 },324 }).catch(() => {});325 chrome.runtime.sendMessage({326 type: "UPDATE_ENTRY",327 payload: {328 id: entry.id,329 patch: {330 canary: {331 ...entry.canary,332 lastPinged: Date.now(),333 pingCount: (entry.canary.pingCount ?? 0) + 1,334 },335 },336 },337 }).catch(() => {});338 }339340 341 342 const totpCode = (entry as { totpCode?: string }).totpCode;343 if (totpCode) {344 const code = totpCode;345 const totpField = passwordEl ? findSameLoginTOTPField(passwordEl) : null;346 if (fillTOTPCode(totpField, code)) {347 filledTOTPField = totpField;348 }349 let alreadyWritten = false;350 try {351 await navigator.clipboard.writeText(code);352 alreadyWritten = true;353 } catch (err) {354 console.warn("[Peach] clipboard write denied:", err);355 }356 const response = await chrome.runtime.sendMessage({357 type: "COPY",358 payload: { text: code, label: "TOTP", alreadyWritten },359 });360 if (filledTOTPField) {361 showToast("2FA code filled");362 } else if (alreadyWritten || (response as { ok?: boolean }).ok) {363 showToast("TOTP copied · " + code);364 } else {365 showToast("Could not copy TOTP — clipboard blocked");366 }367 }368369 return filledTOTPField;370}371372async function fetchAutofillEntries(373 domain: string,374 includeAll = false375): Promise<{ entries: SelectorEntry[]; locked: boolean }> {376 const response = await chrome.runtime.sendMessage({377 type: "AUTOFILL_QUERY",378 payload: { domain, includeAll },379 });380 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };381 if (!res.ok && res.error === "vault_locked") {382 return { entries: [], locked: true };383 }384 return { entries: res.data ?? [], locked: false };385}386387async function fetchTOTPEntries(388 domain: string389): Promise<{ entries: SelectorEntry[]; locked: boolean }> {390 const response = await chrome.runtime.sendMessage({391 type: "AUTOFILL_QUERY",392 payload: { domain, kind: "totp" },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}400401402function resolveAutofillFieldType(403 el: HTMLInputElement,404 predictedType?: FieldPrediction["type"] | null405): "password" | "username" | "email" | null {406 if (407 predictedType === "password" ||408 predictedType === "username" ||409 predictedType === "email"410 ) {411 return predictedType;412 }413414 const detected = detectLoginFields().find((field) => field.el === el)?.type;415 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {416 return detected;417 }418419 const htmlType = el.type.toLowerCase();420 if (htmlType === "password") return "password";421 if (htmlType === "email") return "email";422 return null;423}424425async function openAutofillSelector(426 anchorField: HTMLInputElement,427 usernameEl: HTMLInputElement | null,428 passwordEl: HTMLInputElement | null,429 domainEntries: SelectorEntry[],430 searchableEntries: SelectorEntry[],431 domain: string432): Promise<void> {433 434 435 436 const isSignup = domainEntries.length === 0;437 let savedIdentities: SavedIdentity[] | undefined;438 let confirmEl: HTMLInputElement | null = null;439 if (isSignup) {440 try {441 const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as442 { ok: boolean; data?: SavedIdentity[] } | null;443 if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;444 } catch { }445446 const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body;447 const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));448 confirmEl = allPwInputs.find(449 (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)450 ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);451 }452453 currentDismiss?.();454 currentAnchorField = anchorField;455 currentDismiss = showAutofillSelector(456 anchorField,457 domainEntries,458 async (id: string) => {459 currentDismiss = null;460 currentAnchorField = null;461 const entryResponse = await chrome.runtime.sendMessage({462 type: "GET_ENTRY_FOR_FILL",463 payload: { id },464 });465 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;466 if (entry) {467 const filledTOTPField = await handleAutofill(anchorField, usernameEl, passwordEl, entry);468 recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);469 470 471 472 const pageDomain = location.hostname.replace(/^www\./, "");473 const entryDomains = new Set<string>();474 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {475 try {476 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));477 } catch { }478 }479 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {480 showRememberSiteToast(pageDomain, entry.id);481 }482 }483 },484 {485 domain,486 searchableEntries,487 isSignup,488 savedIdentities,489 onFillFields: (username, password) => {490 const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;491 fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());492 if (password && confirmEl) setNativeValue(confirmEl, password);493 recordFillSuccess(anchorField, usernameEl, passwordEl);494 },495 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },496 }497 );498}499500async function openTOTPSelector(anchorField: HTMLInputElement, otpDigitBoxes?: HTMLInputElement[]): Promise<void> {501 if (!canOpen()) return;502 if (currentDismiss && currentAnchorField === anchorField) return;503 if (anchorField !== lastDismissedField) lastDismissedField = null;504 if (anchorField === lastDismissedField) return;505 if (wasAlreadyFilled(anchorField)) return;506507 const domain = getPageDomain();508 const result = await fetchTOTPEntries(domain);509510 if (result.locked) {511 currentDismiss?.();512 currentAnchorField = anchorField;513 currentDismiss = showAutofillSelector(514 anchorField,515 [],516 () => {},517 {518 domain,519 locked: true,520 onUnlocked: () => void openTOTPSelector(anchorField),521 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },522 }523 );524 return;525 }526527 if (result.entries.length === 0) {528 lastDismissedField = anchorField;529 startDismissLock();530 showToast("No 2FA entries for this site — add a code in Peach first");531 return;532 }533534 currentDismiss?.();535 currentAnchorField = anchorField;536 currentDismiss = showTOTPSelector(537 anchorField,538 result.entries,539 async (id: string) => {540 try {541 const entryResponse = await chrome.runtime.sendMessage({542 type: "GET_ENTRY_FOR_FILL",543 payload: { id },544 }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;545 const entry = entryResponse?.ok ? entryResponse.data : undefined;546 const code = (entry as { totpCode?: string } | undefined)?.totpCode;547 if (!code) 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}571572573async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {574 const field = anchorField ?? getDeepActiveInput();575 if (!field) return;576 if (!isVisible(field)) return;577578 579 if (passkeyToastActive) return;580581 582 583 if (!canOpen()) return;584585 586 if (currentDismiss && currentAnchorField === field) return;587588 589 590 if (field !== lastDismissedField) lastDismissedField = null;591 592 593 if (field === lastDismissedField) return;594595 596 597 598 599 if (wasAlreadyFilled(field)) return;600601 602 603 if (pendingInteractions.has(field)) return;604 pendingInteractions.add(field);605606 try {607 608 609 const otpGroup = findOTPDigitBoxGroup(field);610 if (otpGroup) {611 await openTOTPSelector(otpGroup[0]!, otpGroup);612 return;613 }614615 if (isTOTPField(field)) {616 const formFields = detectLoginFields();617 if (!isLoginForm(formFields) && !isSignupForm(formFields)) {618 await openTOTPSelector(field);619 return;620 }621 }622623 const fieldType = field.type.toLowerCase();624625 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {626 return preds[0] ?? null;627 });628629 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {630 const timeout = setTimeout(() => resolve(null), 150);631 mlPromise.then((pred) => {632 clearTimeout(timeout);633 resolve(pred);634 });635 });636637 if (passkeyToastActive) return;638639 if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {640 return;641 }642643 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);644 if (autofillFieldType) {645 reattachListeners(field, autofillFieldType);646 }647648 let fields = detectLoginFields();649 if (!isAnyCredentialForm(fields)) {650 return;651 }652653 const domain = getPageDomain();654 const firstResult = await fetchAutofillEntries(domain);655 if (passkeyToastActive) return;656657 658 659 660 if (firstResult.locked) {661 currentDismiss?.();662 currentAnchorField = field;663 currentDismiss = showAutofillSelector(664 field,665 [],666 () => {},667 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }668 );669 return;670 }671672 const entries = firstResult.entries;673 674 675 676 677 const allEntries = (await fetchAutofillEntries(domain, true)).entries;678679 if (passkeyToastActive) return;680681 let usernameEl: HTMLInputElement | null = null;682 const userField = fields.find((f) => f.type === "username" || f.type === "email");683 if (userField) usernameEl = userField.el;684 const pwField = fields.find((f) => f.type === "password");685 686 if (!pwField && !isEmailFirstForm(fields)) return;687 const passwordEl = pwField?.el ?? null;688689 await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);690 } finally {691 pendingInteractions.delete(field);692 }693}694695async function onFocusIn(e: Event): Promise<void> {696 697 698 699 700 701 if (isSubmitButton(e.target)) return;702 await handleFieldInteraction();703}704705function reattachListeners(706 el: HTMLInputElement,707 detectedType?: "password" | "username" | "email",708 contextFields?: ReturnType<typeof detectLoginFields>709): void {710 if (processedInputs.has(el)) return;711 if (!resolveAutofillFieldType(el, detectedType)) return;712 713 const fields = contextFields ?? detectLoginFields();714 if (!isAnyCredentialForm(fields)) return;715716 const cleanup = injectFieldIcon(el, () => {717 currentDismiss?.();718 currentDismiss = null;719 lastDismissedField = null; 720 dismissLock = false; 721 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }722 clearFillStateForExplicitSummon(el);723 el.focus({ preventScroll: true });724 void handleFieldInteraction(el);725 });726 processedInputs.set(el, cleanup);727}728729const debouncedReattach = debounce(() => {730 const allFields = detectLoginFields();731 if (!isAnyCredentialForm(allFields)) return;732 const newFields = allFields.filter(733 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)734 );735 for (const f of newFields) {736 reattachListeners(f.el, f.type, allFields);737 }738 739 740 741}, 200);742743function setupMutationObserver(): void {744 const observer = new MutationObserver(debouncedReattach);745 observer.observe(document.body, {746 childList: true,747 subtree: true,748 attributes: true,749 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],750 });751}752753function initialScan(aggressionLevel = 0, isFinalPass = false) {754 const allFields = detectLoginFields();755 const hasKnownForm = isAnyCredentialForm(allFields);756757 if (aggressionLevel === 0 && !hasKnownForm) return;758759 const newFields = allFields.filter(760 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)761 );762763 for (const f of newFields) {764 reattachListeners(f.el, f.type, allFields);765 }766767 768 769 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {770 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');771 for (const el of pwInputs) {772 if (isVisible(el) && !processedInputs.has(el)) {773 const cleanup = injectFieldIcon(el, () => {774 currentDismiss?.();775 currentDismiss = null;776 lastDismissedField = null;777 dismissLock = false;778 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }779 clearFillStateForExplicitSummon(el);780 el.focus({ preventScroll: true });781 void handleFieldInteraction(el);782 });783 processedInputs.set(el, cleanup);784 }785 }786 }787}788789790791792793const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();794795function hasLoginOrSignupForm(): boolean {796 const fields = detectLoginFields();797 return isAnyCredentialForm(fields);798}799800function injectTOTPFieldIcon(field: HTMLInputElement): void {801 if (processedTOTPInputs.has(field)) return;802 const cleanup = injectFieldIcon(field, () => {803 currentDismiss?.();804 currentDismiss = null;805 currentAnchorField = null;806 lastDismissedField = null;807 dismissLock = false;808 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }809 clearFillStateForExplicitSummon(field);810 field.focus({ preventScroll: true });811 void openTOTPSelector(field);812 });813 processedTOTPInputs.set(field, cleanup);814}815816function scanTOTPFields(): void {817 if (hasLoginOrSignupForm()) return;818 const inputs = document.querySelectorAll<HTMLInputElement>("input");819 for (const input of inputs) {820 if (!isTOTPField(input)) continue;821 injectTOTPFieldIcon(input);822 }823}824825function setupTOTPAutofill(): void {826 setTimeout(scanTOTPFields, 0);827 setTimeout(scanTOTPFields, 500);828 setTimeout(scanTOTPFields, 1500);829830 const debouncedScan = debounce(scanTOTPFields, 200);831 new MutationObserver(debouncedScan).observe(document.body, {832 childList: true,833 subtree: true,834 attributes: true,835 attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],836 });837838 document.addEventListener("focusin", (e) => {839 const target = e.target;840 if (!(target instanceof HTMLInputElement)) return;841 if (hasLoginOrSignupForm()) return;842 if (!isTOTPField(target)) return;843 injectTOTPFieldIcon(target);844 }, true);845}846847document.addEventListener("focusin", onFocusIn);848849setupMutationObserver();850setupTOTPAutofill();851setupSaveDetection();852setupCardAutofill();853854855856857858859860861let lastObservedUrl = location.href;862new MutationObserver(() => {863 if (location.href !== lastObservedUrl) {864 lastObservedUrl = location.href;865 pageFilledAt = null;866 }867}).observe(document.body, { childList: true, subtree: false });868869870871(async () => {872 let aggressionLevel = 0;873 try {874 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });875 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;876 const domain = getPageDomain();877 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;878 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;879 } catch { }880881 setTimeout(() => initialScan(aggressionLevel, false), 0);882 setTimeout(() => initialScan(aggressionLevel, false), 500);883 setTimeout(() => initialScan(aggressionLevel, true), 1500);884})();885886887888889890891const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();892let currentCardDismiss: (() => void) | null = null;893let currentCardAnchor: HTMLInputElement | null = null;894let lastDismissedCardField: HTMLInputElement | null = null;895896async function fetchSavedCards(): Promise<CardSelectorEntry[]> {897 const resp = await chrome.runtime.sendMessage({898 type: "AUTOFILL_QUERY",899 payload: { domain: getPageDomain(), kind: "card" },900 }).catch(() => null);901 const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;902 return r?.ok ? (r.data ?? []) : [];903}904905async function openCardSelector(anchor: HTMLInputElement): Promise<void> {906 if (!canOpen()) return;907 if (currentCardDismiss && currentCardAnchor === anchor) return;908 if (anchor === lastDismissedCardField) return;909 if (anchor !== lastDismissedCardField) lastDismissedCardField = null;910 if (wasAlreadyFilled(anchor)) return;911912 const cards = await fetchSavedCards();913 if (cards.length === 0) return; 914915 const cardForm = detectCardForm();916 if (!cardForm?.number) return;917918 currentCardDismiss?.();919 currentCardAnchor = anchor;920 currentCardDismiss = showCardSelector(921 anchor,922 cards,923 {924 domain: getPageDomain(),925 onFill: (entry) => {926 if (!cardForm) return;927 fillCardForm(cardForm, {928 cardNumber: entry.cardNumber ?? "",929 expMonth: entry.expMonth ?? "",930 expYear: entry.expYear ?? "",931 cvc: entry.cvc ?? "",932 cardholderName: entry.cardholderName ?? "",933 });934 935 936 937 recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);938 currentCardDismiss = null;939 currentCardAnchor = null;940 },941 onDismiss: () => {942 lastDismissedCardField = anchor;943 startDismissLock();944 currentCardDismiss = null;945 currentCardAnchor = null;946 },947 }948 );949}950951function injectCardIcon(field: HTMLInputElement): void {952 if (processedCardInputs.has(field)) return;953 const cleanup = injectFieldIcon(field, () => {954 currentCardDismiss?.();955 currentCardDismiss = null;956 lastDismissedCardField = null;957 dismissLock = false;958 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }959 clearFillStateForExplicitSummon(field);960 field.focus({ preventScroll: true });961 void openCardSelector(field);962 });963 processedCardInputs.set(field, cleanup);964}965966function setupCardAutofill(): void {967 function scan() {968 const cardForm = detectCardForm();969 if (!cardForm?.number) return;970 if (!isVisible(cardForm.number)) return;971 injectCardIcon(cardForm.number);972 }973974 975 976 setTimeout(scan, 0);977 setTimeout(scan, 500);978 setTimeout(scan, 1500);979980 981 982 983 let pending = false;984 new MutationObserver(() => {985 if (pending) return;986 pending = true;987 setTimeout(() => { pending = false; scan(); }, 200);988 }).observe(document.body, { childList: true, subtree: true });989990 991 992 993 document.addEventListener("focusin", (e) => {994 const target = e.target;995 if (!(target instanceof HTMLInputElement)) return;996 const cardForm = detectCardForm();997 if (cardForm?.number === target) {998 injectCardIcon(target);999 }1000 }, true);1001}10021003chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {1004 1005 if (sender.id !== chrome.runtime.id) return;1006 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {1007 const policy = detectPasswordPolicy();1008 sendResponse({ ok: true, data: policy });1009 return true;1010 }1011 if (msg?.type === "PING") {1012 sendResponse({ ok: true });1013 return true;1014 }1015 if (msg?.type === "SUMMON_AUTOFILL") {1016 const source = (msg as { type: string; source?: string }).source;1017 const isShortcut = source === "shortcut";1018 const isPasskeyUnlock = source === "passkey-unlock";10191020 const activeInput = getDeepActiveInput();1021 const fields = detectLoginFields();1022 const hasForm = isAnyCredentialForm(fields);10231024 if (hasForm) {1025 1026 1027 const inForm = activeInput && fields.some(f => f.el === activeInput);1028 const target = inForm1029 ? activeInput1030 : (fields.find(f => f.type === "password")?.el1031 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1032 if (target) {1033 1034 1035 clearFillStateForExplicitSummon(target);1036 dismissLock = false;1037 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1038 lastDismissedField = null;1039 void handleFieldInteraction(target);1040 }1041 } else if (isPasskeyUnlock) {1042 1043 1044 1045 const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1046 ? document.activeElement as unknown as HTMLInputElement1047 : null;1048 if (anchor) {1049 currentDismiss?.();1050 currentAnchorField = null;1051 passkeySummonActive = true;1052 currentDismiss = showAutofillSelector(anchor, [], () => {}, {1053 domain: getPageDomain(),1054 locked: true,1055 onDismiss: () => { passkeySummonActive = false; },1056 });1057 }1058 } else if (isShortcut) {1059 1060 showSearchPalette();1061 }10621063 1064 if (isShortcut) {1065 const domain = getPageDomain();1066 if (domain) {1067 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1068 }1069 }10701071 sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });1072 return true;1073 }1074 if (msg?.type === "PASSKEY_PRO_GATE") {1075 1076 1077 showPasskeyProGate();1078 sendResponse({ ok: true });1079 return true;1080 }1081 if (msg?.type === "SHOW_PASSKEY_TOAST") {1082 1083 passkeyToastActive = true;1084 if (currentDismiss) {1085 currentDismiss();1086 currentDismiss = null;1087 currentAnchorField = null;1088 }1089 return false; 1090 }1091 if (msg?.type === "DISMISS_PASSKEY_TOAST") {1092 passkeyToastActive = false;1093 return false; 1094 }1095 if (msg?.type === "VAULT_UNLOCKED") {1096 if (passkeySummonActive) {1097 1098 1099 passkeySummonActive = false;1100 if (currentDismiss) {1101 currentDismiss();1102 currentDismiss = null;1103 currentAnchorField = null;1104 }1105 sendResponse({ ok: true });1106 return true;1107 }1108 1109 1110 const savedField = currentAnchorField;1111 if (currentDismiss) {1112 currentDismiss();1113 currentDismiss = null;1114 currentAnchorField = null;1115 }1116 void handleFieldInteraction(savedField ?? undefined);1117 sendResponse({ ok: true });1118 return true;1119 }1120 return true;1121});1122112311241125window.addEventListener("message", (e: MessageEvent) => {1126 1127 1128 if (e.source !== window) return;1129 const d = e.data as { source?: string; type?: string } | undefined;1130 if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {1131 passkeyToastActive = false;1132 }1133});1134113511361137113811391140114111421143114411451146if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {1147 let lastPasskeyOfferAt = 0;1148 const PASSKEY_OFFER_COOLDOWN_MS = 30_000;11491150 window.addEventListener("message", (event: MessageEvent) => {1151 if (event.source !== window) return;1152 const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;1153 if (!data || data.source !== "peach-passkey-firefox") return;1154 if (detectBrowser() !== "firefox") return;1155 if (data.type !== "create") return;11561157 1158 1159 const now = Date.now();1160 if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1161 lastPasskeyOfferAt = now;11621163 const domain = location.hostname.replace(/^www\./, "");1164 chrome.runtime.sendMessage({1165 type: "GET_PASSKEY_OFFER_DECLINED",1166 payload: { domain },1167 }).then((res: { ok: boolean; data?: boolean } | undefined) => {1168 if (res?.data === true) return;1169 const rpId = data.rpId ?? domain;1170 showPasskeyRegistrationOffer({1171 rpId,1172 rpName: data.rpName,1173 userName: data.userName,1174 userDisplayName: data.userDisplayName,1175 });1176 }).catch(() => {});1177 });1178}117911801181118211831184118511861187118811891190119111921193{1194 function checkPasskeyAvailability() {1195 const domain = location.hostname.replace(/^www\./, "");1196 if (!domain) return;1197 const sessionKey = `peach_state11_shown:${domain}`;1198 chrome.storage.session?.get(sessionKey).then((stored) => {1199 if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1200 chrome.runtime.sendMessage({1201 type: "GET_PASSKEY_FOR_DOMAIN",1202 payload: { domain },1203 }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1204 const data = res?.data;1205 if (!data) return;1206 const current = detectBrowser();1207 const isCrossBrowser =1208 data.browser && current !== "unknown" && data.browser !== current;1209 const valuableOnFirefox = current === "firefox";1210 if (!isCrossBrowser && !valuableOnFirefox) return;1211 chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1212 showPasskeyAvailable({1213 rpId: data.rpId,1214 userName: data.userName,1215 fromBrowser: data.browser,1216 currentBrowser: current,1217 });1218 }).catch(() => {});1219 }).catch(() => {});1220 }12211222 1223 1224 1225 if (document.readyState === "loading") {1226 document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1227 } else {1228 setTimeout(checkPasskeyAvailability, 800);1229 }1230}