1import {2 detectLoginFields,3 getDeepActiveInput,4 getPageDomain,5 isLoginForm,6 isSignupForm,7 isVisible,8} from "./detect";9import {10 injectFieldIcon,11 observeAnchorPosition,12 SelectorEntry,13 showAutofillSelector,14 showRememberSiteToast,15} from "./inject";16import { fillFields } from "./fill";17import { setupSaveDetection } from "./save";18import { contentMLDetector } from "./content-ml-detector";19import { detectPasswordPolicy } from "./policy";20import type { FieldPrediction } from "../shared/ml";21import { generateTOTP } from "../crypto/totp";22import type { VaultEntry } from "../shared/types";232425262728const processedInputs = new WeakMap<HTMLInputElement, () => void>();29const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);3031let currentDismiss: (() => void) | null = null;3233let currentAnchorField: HTMLInputElement | null = null;3435const pendingInteractions = new WeakSet<HTMLInputElement>();36373839let lastDismissedField: HTMLInputElement | null = null;40414243444546const DISMISS_LOCK_MS = 800;47let dismissLock = false;48let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;49function startDismissLock(): void {50 dismissLock = true;51 if (dismissLockTimer) clearTimeout(dismissLockTimer);52 dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);53}54function canOpen(): boolean { return !dismissLock; }5556575859606162636465666768const filledForms = new WeakSet<HTMLFormElement>();69let pageFilledAt: number | null = null;70const PAGE_FILL_GRACE_MS = 3000;7172function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {73 for (const f of fields) {74 if (!f) continue;75 const form = f.closest("form");76 if (form) filledForms.add(form);77 }78 pageFilledAt = Date.now();79}8081function wasAlreadyFilled(field: HTMLInputElement): boolean {82 const form = field.closest("form");83 if (form && filledForms.has(form)) return true;84 if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;85 return false;86}8788function clearFillStateForExplicitSummon(field: HTMLInputElement): void {89 const form = field.closest("form");90 if (form) filledForms.delete(form);91 pageFilledAt = null;92}939495969798function isSubmitButton(el: EventTarget | null): boolean {99 if (!(el instanceof HTMLElement)) return false;100 if (el instanceof HTMLButtonElement && el.type !== "button") return true;101 if (el instanceof HTMLInputElement && el.type === "submit") return true;102 if (el.getAttribute("type") === "submit") return true;103 const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();104 if (!text || text.length > 24) return false;105 return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);106}107108function debounce<T extends (...args: unknown[]) => void>(109 fn: T,110 ms: number111): (...args: Parameters<T>) => void {112 let timer: ReturnType<typeof setTimeout>;113 return (...args: Parameters<T>) => {114 clearTimeout(timer);115 timer = setTimeout(() => fn(...args), ms);116 };117}118119function showToast(message: string): void {120 const toast = document.createElement("div");121 toast.style.cssText = `122 position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);123 background: #131109; color: #F0E8D8; padding: 8px 16px;124 border-radius: 8px; font-family: 'IBM Plex Mono', monospace;125 font-size: 11px; z-index: 2147483647; opacity: 0;126 transition: opacity 200ms ease;127 border: 1px solid rgba(240,232,216,0.07);128 pointer-events: none;129 `;130 toast.textContent = message;131 document.body.appendChild(toast);132 requestAnimationFrame(() => { toast.style.opacity = "1"; });133 setTimeout(() => {134 toast.style.opacity = "0";135 setTimeout(() => toast.remove(), 200);136 }, 2000);137}138139function showSearchPalette(): void {140 const host = document.createElement("div");141 host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";142 document.body.appendChild(host);143 const shadow = host.attachShadow({ mode: "closed" });144145 const style = document.createElement("style");146 style.textContent = `147 .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;148 font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;149 box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}150 .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);151 font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}152 .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}153 .s{padding:8px 12px}154 .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);155 border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;156 padding:6px 8px;font-family:inherit;font-size:12px;outline:none}157 .l{max-height:220px;overflow-y:auto}158 .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}159 .e:hover{background:rgba(240,232,216,.06)}160 .et{font-size:12px}161 .eu{font-size:10px;color:rgba(240,232,216,.45)}162 .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}163 `;164165 let allEntries: SelectorEntry[] = [];166 let query = "";167168 const panel = document.createElement("div");169 panel.className = "p";170171 const hdr = document.createElement("div");172 hdr.className = "h";173 const hdrText = document.createElement("span");174 hdrText.textContent = "No form detected — search your vault";175 const closeBtn = document.createElement("button");176 closeBtn.className = "x";177 closeBtn.textContent = "✕";178 hdr.appendChild(hdrText);179 hdr.appendChild(closeBtn);180181 const searchWrap = document.createElement("div");182 searchWrap.className = "s";183 const searchInput = document.createElement("input");184 searchInput.placeholder = "search...";185 searchWrap.appendChild(searchInput);186187 const list = document.createElement("div");188 list.className = "l";189190 panel.appendChild(hdr);191 panel.appendChild(searchWrap);192 panel.appendChild(list);193 shadow.appendChild(style);194 shadow.appendChild(panel);195196 function close() { host.remove(); }197198 closeBtn.onclick = close;199200 function onKeyDown(e: KeyboardEvent) {201 if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }202 }203 document.addEventListener("keydown", onKeyDown, true);204205 function render() {206 const q = query.toLowerCase();207 const filtered = q208 ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))209 : allEntries;210 list.innerHTML = "";211 if (filtered.length === 0) {212 const em = document.createElement("div");213 em.className = "em";214 em.textContent = query ? "no matches" : "vault is empty";215 list.appendChild(em);216 return;217 }218 for (const entry of filtered.slice(0, 20)) {219 const row = document.createElement("div");220 row.className = "e";221 const title = document.createElement("div");222 title.className = "et";223 title.textContent = entry.title;224 row.appendChild(title);225 if (entry.username) {226 const user = document.createElement("div");227 user.className = "eu";228 user.textContent = entry.username;229 row.appendChild(user);230 }231 row.onclick = async () => {232 const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });233 const r = resp as { ok: boolean; data?: { password?: string } };234 if (r.ok && r.data?.password) {235 let alreadyWritten = false;236 try { await navigator.clipboard.writeText(r.data.password); alreadyWritten = true; } catch {}237 await chrome.runtime.sendMessage({238 type: "COPY",239 payload: { text: r.data.password, label: "Password", alreadyWritten },240 });241 showToast("Password copied");242 } else {243 showToast("Could not copy password");244 }245 close();246 document.removeEventListener("keydown", onKeyDown, true);247 };248 list.appendChild(row);249 }250 }251252 searchInput.oninput = () => { query = searchInput.value; render(); };253254 fetchAutofillEntries(getPageDomain(), true).then(result => {255 if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }256 allEntries = result.entries;257 render();258 searchInput.focus();259 });260}261262function setNativeValue(el: HTMLInputElement, value: string): void {263 const nativeSetter = Object.getOwnPropertyDescriptor(264 HTMLInputElement.prototype, "value"265 )!.set!;266 nativeSetter.call(el, value);267 el.dispatchEvent(new Event("input", { bubbles: true }));268 el.dispatchEvent(new Event("change", { bubbles: true }));269}270271function findTOTPField(): HTMLInputElement | null {272 const inputs = document.querySelectorAll<HTMLInputElement>("input");273 for (const input of inputs) {274 if (!isVisible(input)) continue;275 const autocomplete = input.autocomplete.toLowerCase();276 const nameId = (input.name + input.id).toLowerCase();277 const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();278 if (279 autocomplete === "one-time-code" ||280 /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)281 ) {282 return input;283 }284 const labelEl = input.closest("label");285 if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {286 return input;287 }288 }289 return null;290}291292async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {293 await new Promise((r) => setTimeout(r, 400));294 if (totpField.value === "" || totpField.value.trim() === "") {295 const { code } = generateTOTP(totpSecret);296 setNativeValue(totpField, code);297 showToast("TOTP autofilled");298 }299}300301302async function handleAutofill(303 field: HTMLInputElement,304 usernameEl: HTMLInputElement | null,305 passwordEl: HTMLInputElement,306 entry: VaultEntry307): Promise<void> {308 if (!entry.username && !entry.password) return;309 const pageDomain = getPageDomain();310 const form = passwordEl.closest("form") as HTMLFormElement | null;311 fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);312313 if (entry.canary) {314 chrome.runtime.sendMessage({315 type: "FIRE_CANARY_PING",316 payload: {317 webhookUrl: entry.canary.webhookUrl,318 entryTitle: entry.title,319 trigger: "autofilled",320 },321 }).catch(() => {});322 chrome.runtime.sendMessage({323 type: "UPDATE_ENTRY",324 payload: {325 id: entry.id,326 patch: {327 canary: {328 ...entry.canary,329 lastPinged: Date.now(),330 pingCount: (entry.canary.pingCount ?? 0) + 1,331 },332 },333 },334 }).catch(() => {});335 }336337 if (entry.totp) {338 const { code } = generateTOTP(entry.totp);339 let alreadyWritten = false;340 try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}341 const response = await chrome.runtime.sendMessage({342 type: "COPY",343 payload: { text: code, label: "TOTP", alreadyWritten },344 });345 if (alreadyWritten || (response as { ok?: boolean }).ok) {346 showToast("TOTP copied · " + code);347 }348 const totpField = findTOTPField();349 if (totpField) {350 autofillTOTP(totpField, entry.totp);351 }352 }353}354355async function fetchAutofillEntries(356 domain: string,357 includeAll = false358): Promise<{ entries: SelectorEntry[]; locked: boolean }> {359 const response = await chrome.runtime.sendMessage({360 type: "AUTOFILL_QUERY",361 payload: { domain, includeAll },362 });363 const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };364 if (!res.ok && res.error === "VAULT_LOCKED") {365 return { entries: [], locked: true };366 }367 return { entries: res.data ?? [], locked: false };368}369370371function resolveAutofillFieldType(372 el: HTMLInputElement,373 predictedType?: FieldPrediction["type"] | null374): "password" | "username" | "email" | null {375 if (376 predictedType === "password" ||377 predictedType === "username" ||378 predictedType === "email"379 ) {380 return predictedType;381 }382383 const detected = detectLoginFields().find((field) => field.el === el)?.type;384 if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {385 return detected;386 }387388 const htmlType = el.type.toLowerCase();389 if (htmlType === "password") return "password";390 if (htmlType === "email") return "email";391 return null;392}393394async function openAutofillSelector(395 anchorField: HTMLInputElement,396 usernameEl: HTMLInputElement | null,397 passwordEl: HTMLInputElement,398 domainEntries: SelectorEntry[],399 searchableEntries: SelectorEntry[],400 domain: string401): Promise<void> {402 currentDismiss?.();403 currentAnchorField = anchorField;404 currentDismiss = showAutofillSelector(405 anchorField,406 domainEntries,407 async (id: string) => {408 currentDismiss = null;409 currentAnchorField = null;410 const entryResponse = await chrome.runtime.sendMessage({411 type: "GET_ENTRY_FOR_FILL",412 payload: { id },413 });414 const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;415 if (entry) {416 await handleAutofill(anchorField, usernameEl, passwordEl, entry);417 recordFillSuccess(anchorField, usernameEl, passwordEl);418 419 420 421 const pageDomain = location.hostname.replace(/^www\./, "");422 const entryDomains = new Set<string>();423 for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {424 try {425 if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));426 } catch { }427 }428 if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {429 showRememberSiteToast(pageDomain, entry.id);430 }431 }432 },433 {434 domain,435 searchableEntries,436 onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },437 }438 );439}440441async function openSignupSelector(442 usernameEl: HTMLInputElement,443 passwordEl: HTMLInputElement | null,444 domainEntries: SelectorEntry[],445 allEntries: SelectorEntry[],446 domain: string447): Promise<void> {448 currentDismiss?.();449 currentAnchorField = usernameEl;450 currentDismiss = showAutofillSelector(451 usernameEl,452 domainEntries,453 () => {}, 454 {455 domain,456 searchableEntries: allEntries,457 isSignup: true,458 onFillFields: (username, password) => {459 if (username) setNativeValue(usernameEl, username);460 if (password && passwordEl) setNativeValue(passwordEl, password);461 recordFillSuccess(usernameEl, passwordEl);462 },463 onDismiss: () => { lastDismissedField = usernameEl; startDismissLock(); },464 }465 );466}467468469async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {470 const field = anchorField ?? getDeepActiveInput();471 if (!field) return;472 if (!isVisible(field)) return;473474 475 476 if (!canOpen()) return;477478 479 if (currentDismiss && currentAnchorField === field) return;480481 482 483 if (field !== lastDismissedField) lastDismissedField = null;484 485 486 if (field === lastDismissedField) return;487488 489 490 491 492 if (wasAlreadyFilled(field)) return;493494 495 496 if (pendingInteractions.has(field)) return;497 pendingInteractions.add(field);498499 try {500 const fieldType = field.type.toLowerCase();501502 const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {503 return preds[0] ?? null;504 });505506 const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {507 const timeout = setTimeout(() => resolve(null), 150);508 mlPromise.then((pred) => {509 clearTimeout(timeout);510 resolve(pred);511 });512 });513514 if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {515 return;516 }517518 const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);519 if (autofillFieldType) {520 reattachListeners(field, autofillFieldType);521 }522523 let fields = detectLoginFields();524 const loginForm = isLoginForm(fields);525 const signupForm = isSignupForm(fields);526 if (!loginForm && !signupForm) {527 return;528 }529530 const domain = getPageDomain();531 const firstResult = await fetchAutofillEntries(domain);532533 534 535 536 if (firstResult.locked) {537 currentDismiss?.();538 currentAnchorField = field;539 currentDismiss = showAutofillSelector(540 field,541 [],542 () => {},543 { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }544 );545 return;546 }547548 const entries = firstResult.entries;549 const allEntries = entries.length === 0550 ? (await fetchAutofillEntries(domain, true)).entries551 : entries;552553 let usernameEl: HTMLInputElement | null = null;554 const userField = fields.find((f) => f.type === "username" || f.type === "email");555 if (userField) usernameEl = userField.el;556 const pwField = fields.find((f) => f.type === "password");557 if (!pwField) return;558 const passwordEl = pwField.el;559560 if (signupForm && usernameEl && field === usernameEl) {561 await openSignupSelector(usernameEl, passwordEl, entries, allEntries, domain);562 return;563 }564565 await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);566 } finally {567 pendingInteractions.delete(field);568 }569}570571async function onFocusIn(e: Event): Promise<void> {572 573 574 575 576 577 if (isSubmitButton(e.target)) return;578 await handleFieldInteraction();579}580581function reattachListeners(582 el: HTMLInputElement,583 detectedType?: "password" | "username" | "email",584 contextFields?: ReturnType<typeof detectLoginFields>585): void {586 if (processedInputs.has(el)) return;587 if (!resolveAutofillFieldType(el, detectedType)) return;588 589 const fields = contextFields ?? detectLoginFields();590 if (!isLoginForm(fields) && !isSignupForm(fields)) return;591592 const cleanup = injectFieldIcon(el, () => {593 currentDismiss?.();594 currentDismiss = null;595 lastDismissedField = null; 596 dismissLock = false; 597 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }598 clearFillStateForExplicitSummon(el);599 el.focus({ preventScroll: true });600 void handleFieldInteraction(el);601 });602 processedInputs.set(el, cleanup);603}604605const debouncedReattach = debounce(() => {606 const allFields = detectLoginFields();607 608 if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;609 const newFields = allFields.filter(610 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)611 );612 for (const f of newFields) {613 reattachListeners(f.el, f.type, allFields);614 }615 616 617 618}, 200);619620function setupMutationObserver(): void {621 const observer = new MutationObserver(debouncedReattach);622 observer.observe(document.body, {623 childList: true,624 subtree: true,625 attributes: true,626 attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],627 });628}629630function initialScan(aggressionLevel = 0, isFinalPass = false) {631 const allFields = detectLoginFields();632 const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);633634 if (aggressionLevel === 0 && !hasKnownForm) return;635636 const newFields = allFields.filter(637 (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)638 );639640 for (const f of newFields) {641 reattachListeners(f.el, f.type, allFields);642 }643644 645 646 if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {647 const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');648 for (const el of pwInputs) {649 if (isVisible(el) && !processedInputs.has(el)) {650 const cleanup = injectFieldIcon(el, () => {651 currentDismiss?.();652 currentDismiss = null;653 lastDismissedField = null;654 dismissLock = false;655 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }656 clearFillStateForExplicitSummon(el);657 el.focus({ preventScroll: true });658 void handleFieldInteraction(el);659 });660 processedInputs.set(el, cleanup);661 }662 }663 }664}665666document.addEventListener("focusin", onFocusIn);667668setupMutationObserver();669setupSaveDetection();670671672673674675676677678let lastObservedUrl = location.href;679new MutationObserver(() => {680 if (location.href !== lastObservedUrl) {681 lastObservedUrl = location.href;682 pageFilledAt = null;683 }684}).observe(document.body, { childList: true, subtree: false });685686687688(async () => {689 let aggressionLevel = 0;690 try {691 const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });692 const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;693 const domain = getPageDomain();694 const record = domain ? s?.manualSummonDomains?.[domain] : undefined;695 aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;696 } catch { }697698 setTimeout(() => initialScan(aggressionLevel, false), 0);699 setTimeout(() => initialScan(aggressionLevel, false), 500);700 setTimeout(() => initialScan(aggressionLevel, true), 1500);701})();702703chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {704 705 if (sender.id !== chrome.runtime.id) return;706 if (msg?.type === "GET_SITE_PASSWORD_POLICY") {707 const policy = detectPasswordPolicy();708 sendResponse({ ok: true, data: policy });709 return true;710 }711 if (msg?.type === "PING") {712 sendResponse({ ok: true });713 return true;714 }715 if (msg?.type === "SUMMON_AUTOFILL") {716 const source = (msg as { type: string; source?: string }).source;717 const isShortcut = source === "shortcut";718719 const activeInput = getDeepActiveInput();720 const fields = detectLoginFields();721 const hasForm = isLoginForm(fields) || isSignupForm(fields);722723 if (hasForm) {724 725 726 const inForm = activeInput && fields.some(f => f.el === activeInput);727 const target = inForm728 ? activeInput729 : (fields.find(f => f.type === "password")?.el730 ?? fields.find(f => f.type === "username" || f.type === "email")?.el);731 if (target) {732 733 734 clearFillStateForExplicitSummon(target);735 dismissLock = false;736 if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }737 lastDismissedField = null;738 void handleFieldInteraction(target);739 }740 } else if (isShortcut) {741 742 showSearchPalette();743 }744745 746 if (isShortcut) {747 const domain = getPageDomain();748 if (domain) {749 chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});750 }751 }752753 sendResponse({ ok: hasForm || isShortcut });754 return true;755 }756 if (msg?.type === "VAULT_UNLOCKED") {757 758 759 760 const savedField = currentAnchorField;761 if (currentDismiss) {762 currentDismiss();763 currentDismiss = null;764 currentAnchorField = null;765 }766 void handleFieldInteraction(savedField ?? undefined);767 sendResponse({ ok: true });768 return true;769 }770 return true;771});