import { getBrowserWindowId, assertOwnedTab } from './window-context'; import { inspectAutocomplete } from './autocomplete'; import { captureScheduled } from './screenshot-capture'; import { writeRedditDraft } from './reddit-editor'; import { PageFormSummary, FormElementDescriptor, FormFillResult, UserDocument } from '../types'; import { loadGlobalMemories, loadTabMemories, getActiveSessionIdState } from '../services/storage'; import { tryLoadFileFromLocalPath, extractTextWithVlm } from '../services/pdf-parser'; import { attemptVisibleCaptcha } from './captcha-auto'; import { injectFileIntoTab, resolveFileSource, type FileSource } from './file-injection'; export interface TabInfo { id: number; title: string; url: string; active: boolean; favIconUrl?: string; } const myExtensionId = typeof chrome !== 'undefined' ? chrome.runtime?.id || '' : ''; export function isExtensionPage(tab?: chrome.tabs.Tab | null): boolean { if (!tab) return true; const url = tab.url || tab.pendingUrl || ''; if (!url) return false; return ( url.startsWith('chrome-extension://') && (url.includes(myExtensionId) || url.includes('sidepanel.html')) ); } export async function getActiveTab(timeoutMs = 1500): Promise { if (typeof chrome === 'undefined' || !chrome.tabs) { return null; } const windowId = getBrowserWindowId(); if (windowId !== undefined) { return Promise.race([chrome.tabs.query({ windowId, active: true }).then(tabs => tabs.find(t => !isExtensionPage(t)) || null).catch(() => null), new Promise(resolve => setTimeout(() => resolve(null), timeoutMs))]); } return new Promise((resolve) => { const timer = setTimeout(() => { resolve(null); }, timeoutMs); const safeResolve = (tab: chrome.tabs.Tab | null) => { clearTimeout(timer); resolve(tab); }; // 1. In Side Panel (Chrome), lastFocusedWindow targets the main browser window tab chrome.tabs.query({ active: true, lastFocusedWindow: true }, (tabs) => { const validLast = (tabs || []).find((t) => !isExtensionPage(t)); if (validLast) { return safeResolve(validLast); } // 2. In Arc Browser or floating window mode, query normal browser windows chrome.tabs.query({ active: true, windowType: 'normal' }, (normalTabs) => { const validNormal = (normalTabs || []).find((t) => !isExtensionPage(t)); if (validNormal) { return safeResolve(validNormal); } // 3. Fallback: query any active non-extension tab chrome.tabs.query({ active: true }, (tabs3) => { const validAnyActive = (tabs3 || []).find((t) => !isExtensionPage(t)); if (validAnyActive) { return safeResolve(validAnyActive); } // 4. Last resort: any non-extension tab in the browser chrome.tabs.query({}, (allTabs) => { const anyValid = (allTabs || []).find((t) => !isExtensionPage(t)); safeResolve(anyValid || null); }); }); }); }); }); } export async function ensureContentScriptInjected(tabId: number, timeoutMs = 2500): Promise { if (typeof chrome === 'undefined' || !chrome.scripting) { return false; } return Promise.race([ (async () => { try { const check = await chrome.scripting.executeScript({ target: { tabId }, func: () => Boolean((window as any).__OPENBUA_CONTENT_SCRIPT_INITIALIZED__), }); if (check && check[0] && check[0].result) { return true; // Already alive; avoid duplicate injection } await chrome.scripting.executeScript({ target: { tabId }, files: ['content.js'], }); await new Promise((r) => setTimeout(r, 100)); return true; } catch (e: any) { console.warn('[OpenBUA] Content script injection notice:', e?.message || e); return false; } })(), new Promise((resolve) => setTimeout(() => resolve(false), timeoutMs)), ]); } export async function sendMessageToTab(tabId: number, message: any, timeoutMs = 3000): Promise { if (typeof chrome === 'undefined' || !chrome.tabs) { throw new Error('Chrome extension APIs not available in current environment'); } await assertOwnedTab(tabId); return new Promise((resolve, reject) => { let settled = false; const cleanup = () => { settled = true; clearTimeout(timer); }; const timer = setTimeout(() => { if (!settled) { cleanup(); reject(new Error(`Timeout waiting for response from tab ${tabId} (${timeoutMs}ms)`)); } }, timeoutMs); try { chrome.tabs.sendMessage(tabId, message, async (response) => { if (settled) return; if (chrome.runtime.lastError) { // Tab might not have content script yet; try injecting once try { const injected = await ensureContentScriptInjected(tabId, 2000); if (injected && !settled) { chrome.tabs.sendMessage(tabId, message, (retryResponse) => { if (settled) return; cleanup(); if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(retryResponse); } }); return; } } catch { // ignore } if (!settled) { cleanup(); reject(new Error(chrome.runtime.lastError.message)); } } else { cleanup(); resolve(response); } }); } catch (e: any) { if (!settled) { cleanup(); reject(e); } } }); } // In-page fallback script for direct DOM inspection without relying on message ports function inPageInspectForm(containerSelector?: string): PageFormSummary { function createDomQuery(root: ParentNode = document) { function roots(node: ParentNode): ParentNode[] { const result: ParentNode[] = [node]; if (node instanceof Element && node.shadowRoot) result.push(...roots(node.shadowRoot)); for (const host of Array.from(node.querySelectorAll('*'))) { if (host.shadowRoot) result.push(...roots(host.shadowRoot)); } return result; } return { querySelectorAll(selector: string): T[] { return [...new Set(roots(root).flatMap(scope => Array.from(scope.querySelectorAll(selector))))]; }, querySelector(selector: string): T | null { for (const scope of roots(root)) { const element = scope.querySelector(selector); if (element) return element; } return null; }, shadowText(): string { const text = roots(root).filter(scope => scope instanceof ShadowRoot).flatMap(scope => Array.from(scope.querySelectorAll('h1,h2,h3,h4,label,p,button,input,textarea,[role="dialog"],[role="button"]')) .filter(el => el.getClientRects().length && getComputedStyle(el).visibility !== 'hidden' && getComputedStyle(el).display !== 'none') .map(el => el.innerText?.trim() || el.getAttribute('aria-label') || el.getAttribute('placeholder') || '') .filter(Boolean)); return [...new Set(text)].join('\n').slice(0, 8000); }, }; } const dom = createDomQuery(); // Self-contained because this function is serialized into the page. function generateRefId(el: HTMLElement): string { const existing = el.getAttribute('data-autoform-ref'); if (existing && /^af_(?:btn_)?\d+$/.test(existing) && dom.querySelector(`[data-autoform-ref="${existing}"]`) === el) return existing; let counter = Number(document.documentElement.getAttribute('data-autoform-counter')) || 0; dom.querySelectorAll('[data-autoform-ref]').forEach(node => { counter = Math.max(counter, Number(node.getAttribute('data-autoform-ref')?.match(/(\d+)$/)?.[1]) || 0); }); const refId = `af_${counter + 1}`; document.documentElement.setAttribute('data-autoform-counter', String(counter + 1)); el.setAttribute('data-autoform-ref', refId); return refId; } let root: ParentNode = document; if (containerSelector) { const customRoot = dom.querySelector(containerSelector); if (customRoot) root = customRoot; } const scopedDom = createDomQuery(root); const rawElements = Array.from(scopedDom.querySelectorAll( 'input:not([type="hidden"]), textarea, select, [contenteditable="true"], [contenteditable=""], [role="textbox"], [role="combobox"], [role="checkbox"]' )); // Prioritize active dialogs / modals const elements = rawElements.sort((a, b) => { const aInDialog = a.closest('[role="dialog"], dialog, .M9, [aria-modal="true"], .modal') ? 1000 : 0; const bInDialog = b.closest('[role="dialog"], dialog, .M9, [aria-modal="true"], .modal') ? 1000 : 0; const aIsText = a.tagName === 'TEXTAREA' || a.isContentEditable || a.getAttribute('role') === 'textbox' ? 100 : 0; const bIsText = b.tagName === 'TEXTAREA' || b.isContentEditable || b.getAttribute('role') === 'textbox' ? 100 : 0; return (bInDialog + bIsText) - (aInDialog + aIsText); }); const fields: FormElementDescriptor[] = []; elements.forEach((elem) => { const tagName = elem.tagName.toLowerCase(); const type = (elem.getAttribute('type') || (tagName === 'textarea' ? 'textarea' : tagName === 'select' ? 'select' : elem.isContentEditable ? 'contenteditable' : 'text')).toLowerCase(); if (['submit', 'reset', 'button', 'image'].includes(type)) return; const refId = generateRefId(elem); // Label lookup let label = ''; for (let parent = elem.parentElement, depth = 0; parent && depth < 5; parent = parent.parentElement, depth++) { if (parent.querySelectorAll('input:not([type="hidden"]), textarea, select, [contenteditable="true"]').length !== 1) break; const question = Array.from(parent.querySelectorAll('label, h2, h3, h4, h5, p, [class*="label"], [class*="title"]')) .find(node => node !== elem && !node.contains(elem) && Boolean(node.compareDocumentPosition(elem) & Node.DOCUMENT_POSITION_FOLLOWING) && Boolean(node.textContent?.trim())); const text = question?.textContent?.trim(); if (text && text.length <= 300) { label = text; break; } } const labelledBy = elem.getAttribute('aria-labelledby'); if (!label && labelledBy) { const l = document.getElementById(labelledBy); if (l) label = l.textContent?.trim() || ''; } if (!label && elem.getAttribute('aria-label')) { label = elem.getAttribute('aria-label') || ''; } if (!label && elem.id) { try { const l = dom.querySelector(`label[for="${CSS.escape(elem.id)}"]`); if (l) label = l.textContent?.trim() || ''; } catch { // ignore invalid selector syntax } } if (!label) { const parentLabel = elem.closest('label'); if (parentLabel) label = parentLabel.textContent?.replace(elem.textContent || '', '').trim() || ''; } if (!label && elem.previousElementSibling) { const prev = elem.previousElementSibling; if (['LABEL', 'SPAN', 'DIV', 'P'].includes(prev.tagName)) { label = prev.textContent?.trim().slice(0, 80) || ''; } } let value = ''; let checked: boolean | undefined = undefined; let options: Array<{ value: string; label: string; selected: boolean }> | undefined = undefined; if (tagName === 'input') { const inp = elem as HTMLInputElement; if (type === 'checkbox' || type === 'radio') { checked = inp.checked; value = inp.value || (inp.checked ? 'true' : 'false'); } else { value = inp.value || ''; } } else if (tagName === 'textarea') { value = (elem as HTMLTextAreaElement).value || ''; } else if (tagName === 'select') { const sel = elem as HTMLSelectElement; value = sel.value || ''; options = Array.from(sel.options).map((o) => ({ value: o.value, label: o.text.trim(), selected: o.selected, })); } else if (elem.isContentEditable) { value = elem.innerText || elem.textContent || ''; } let visible = false; if (elem.offsetWidth > 0 || elem.offsetHeight > 0 || elem.getClientRects().length > 0) { try { visible = window.getComputedStyle(elem).display !== 'none'; } catch { visible = true; } } fields.push({ refId, tagName, type, id: elem.id || '', name: elem.getAttribute('name') || '', label, placeholder: elem.getAttribute('placeholder') || '', value, checked, required: elem.hasAttribute('required') || elem.getAttribute('aria-required') === 'true', disabled: (elem as HTMLInputElement).disabled || false, readonly: (elem as HTMLInputElement).readOnly || false, isVisible: visible, accept: type === 'file' ? elem.getAttribute('accept') || '*/*' : undefined, selector: `[data-autoform-ref="${refId}"]`, options, }); }); const buttons: Array<{ refId: string; text: string; type: string; isSubmit: boolean; isNext: boolean; isPrevious: boolean }> = []; const rawButtons = Array.from(dom.querySelectorAll( 'button, input[type="submit"], input[type="button"], a[role="button"], [role="button"], [role="tab"], tp-yt-paper-tab, yt-tab-shape, ytd-button-renderer, yt-button-shape' )).filter((el) => { if (el.closest('.sbdd_a, .sbsb_a, [role="listbox"], #complete-list')) return false; if (el.closest('.message-in, .message-out, [data-id*="false_"], [data-id*="true_"], [data-pre-plain-text], .chat-message, [role="row"] .copyable-text')) return false; const t = (el.textContent || '').trim(); if (/^\d{1,2}:\d{2}(?:\s*(?:am|pm))?$/i.test(t)) return false; if (t.startsWith('reaction ') && t.includes('View reactions')) return false; return true; }); rawButtons.forEach((btn) => { const text = (btn.textContent || (btn as HTMLInputElement).value || btn.getAttribute('aria-label') || '').trim(); if (!text || text.length > 50) return; const lower = `${text} ${btn.getAttribute('aria-label') || ''}`.toLowerCase(); const refId = generateRefId(btn); const isTab = btn.getAttribute('role') === 'tab' || btn.tagName.toLowerCase() === 'tp-yt-paper-tab' || btn.tagName.toLowerCase() === 'yt-tab-shape' || lower.includes('popular') || lower.includes('latest') || lower.includes('videos'); buttons.push({ refId, text, type: isTab ? 'tab' : (btn.getAttribute('type') || 'button'), isSubmit: lower.includes('submit') || lower.includes('send') || lower.includes('finish') || lower.includes('complete'), isNext: lower.includes('next') || lower.includes('continue') || lower.includes('proceed'), isPrevious: lower.includes('back') || lower.includes('prev'), }); }); const stepIndicators: string[] = []; dom.querySelectorAll('[class*="step"], [class*="progress"]').forEach((el) => { const t = el.textContent?.replace(/\s+/g, ' ').trim(); if (t && t.length > 3 && t.length < 80 && !stepIndicators.includes(t)) { stepIndicators.push(t); } }); return { title: document.title, url: window.location.href, fields, stepIndicators: stepIndicators.slice(0, 5), buttons: buttons.slice(0, 30), }; } // In-page fallback script for directly setting field values in tab function inPageFillForm( assignments: Array<{ refId?: string; selector?: string; value: string; pressEnter?: boolean }>, pressEnterAll?: boolean ): { successCount: number; errors: string[]; verifications: Array<{ refId: string; selector?: string; requestedValue: string; actualValue: string; verified: boolean; elementFound: boolean; }>; } { function createDomQuery(root: ParentNode = document) { function roots(node: ParentNode): ParentNode[] { const result: ParentNode[] = [node]; if (node instanceof Element && node.shadowRoot) result.push(...roots(node.shadowRoot)); for (const host of Array.from(node.querySelectorAll('*'))) { if (host.shadowRoot) result.push(...roots(host.shadowRoot)); } return result; } return { querySelectorAll(selector: string): T[] { return [...new Set(roots(root).flatMap(scope => Array.from(scope.querySelectorAll(selector))))]; }, querySelector(selector: string): T | null { for (const scope of roots(root)) { const element = scope.querySelector(selector); if (element) return element; } return null; }, shadowText(): string { const text = roots(root).filter(scope => scope instanceof ShadowRoot).flatMap(scope => Array.from(scope.querySelectorAll('h1,h2,h3,h4,label,p,button,input,textarea,[role="dialog"],[role="button"]')) .filter(el => el.getClientRects().length && getComputedStyle(el).visibility !== 'hidden' && getComputedStyle(el).display !== 'none') .map(el => el.innerText?.trim() || el.getAttribute('aria-label') || el.getAttribute('placeholder') || '') .filter(Boolean)); return [...new Set(text)].join('\n').slice(0, 8000); }, }; } const dom = createDomQuery(); let successCount = 0; const errors: string[] = []; const verifications: Array<{ refId: string; selector?: string; requestedValue: string; actualValue: string; verified: boolean; elementFound: boolean; }> = []; for (const item of assignments) { let target: HTMLElement | null = null; if (item.refId) { target = dom.querySelector(`[data-autoform-ref="${CSS.escape(item.refId)}"]`); if (!target) { target = document.getElementById(item.refId); } if (!target) { target = dom.querySelector(`[name="${CSS.escape(item.refId)}"]`); } } if (!target && item.selector) { target = dom.querySelector(item.selector); } if (!target) { errors.push(`Field not found: ${item.refId || item.selector}`); verifications.push({ refId: item.refId || '', selector: item.selector, requestedValue: item.value, actualValue: '', verified: false, elementFound: false, }); continue; } try { const tagName = target.tagName.toLowerCase(); const isContentEditable = target.isContentEditable || target.getAttribute('contenteditable') === 'true' || target.getAttribute('role') === 'textbox'; // Rich text placeholder activation (YouTube, etc.) if (isContentEditable || tagName === 'div') { const parentBox = target.closest('ytd-commentbox, ytd-comments-header-renderer, #simple-box, .comment-simplebox') || target.parentElement; if (parentBox) { const placeholder = parentBox.querySelector('#simplebox-placeholder, #placeholder, [id*="placeholder"]'); if (placeholder && placeholder !== target) { placeholder.click(); placeholder.focus(); } } } target.focus(); if (tagName === 'input') { const input = target as HTMLInputElement; const type = (input.getAttribute('type') || 'text').toLowerCase(); if (type === 'file') { try { let fileObj: File | null = null; const fileData = (item as any).fileData; if (fileData?.dataUrl) { const parts = fileData.dataUrl.split(','); const mime = fileData.mimeType || 'application/octet-stream'; const bstr = atob(parts[1] || ''); let n = bstr.length; const u8arr = new Uint8Array(n); while (n--) u8arr[n] = bstr.charCodeAt(n); const defaultName = mime.startsWith('video/') ? 'video.mp4' : mime.startsWith('image/') ? 'image.png' : 'upload.pdf'; fileObj = new File([u8arr], fileData.fileName || defaultName, { type: mime }); } else if (item.value && item.value.startsWith('data:')) { const parts = item.value.split(','); const mimeMatch = parts[0]?.match(/:(.*?);/); const mime = mimeMatch ? mimeMatch[1] : 'application/octet-stream'; const bstr = atob(parts[1] || ''); let n = bstr.length; const u8arr = new Uint8Array(n); while (n--) u8arr[n] = bstr.charCodeAt(n); const defaultName = mime.startsWith('video/') ? 'video.mp4' : mime.startsWith('image/') ? 'image.png' : 'upload.pdf'; fileObj = new File([u8arr], fileData?.fileName || defaultName, { type: mime }); } if (fileObj) { const dt = new DataTransfer(); dt.items.add(fileObj); input.files = dt.files; input.dispatchEvent(new Event('input', { bubbles: true, composed: true })); input.dispatchEvent(new Event('change', { bubbles: true, composed: true })); const dropzone = input.closest('.dropzone, [data-testid="dropzone"], [class*="upload"], [class*="drop"], [role="button"]') || dom.querySelector('[data-testid="dropzone"], div[data-dropzone="true"]') || input.parentElement; if (dropzone && dropzone !== input) { try { dropzone.dispatchEvent(new DragEvent('dragenter', { bubbles: true, cancelable: true, composed: true, dataTransfer: dt })); dropzone.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, composed: true, dataTransfer: dt })); dropzone.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, composed: true, dataTransfer: dt })); } catch {} } } } catch (fileErr) { console.warn('[AutoForm AI] Error attaching file in fallback:', fileErr); } } else if (type === 'checkbox' || type === 'radio') { const boolVal = item.value === 'true' || item.value === '1' || item.value === 'yes' || item.value === 'on'; const desc = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'checked'); if (desc?.set) desc.set.call(input, boolVal); else input.checked = boolVal; } else { const desc = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value'); if (desc?.set) desc.set.call(input, item.value); else input.value = item.value; } } else if (tagName === 'textarea') { const desc = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value'); if (desc?.set) desc.set.call(target, item.value); else (target as HTMLTextAreaElement).value = item.value; } else if (tagName === 'select') { const sel = target as HTMLSelectElement; const valLower = item.value.toLowerCase().trim(); let idx = -1; for (let i = 0; i < sel.options.length; i++) { const opt = sel.options[i]; if (opt.value.toLowerCase().trim() === valLower || opt.text.toLowerCase().trim() === valLower || opt.text.toLowerCase().includes(valLower)) { idx = i; break; } } if (idx >= 0) { sel.selectedIndex = idx; const desc = Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype, 'value'); if (desc?.set) desc.set.call(sel, sel.options[idx].value); else sel.value = sel.options[idx].value; } else { sel.value = item.value; } } else if (isContentEditable) { // Selection replacement and insertText for rich text editors target.focus(); // 1. Clear any existing content cleanly const editorRoot = target.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null }; const sel = editorRoot.getSelection?.() || window.getSelection(); if (sel) { const range = document.createRange(); range.selectNodeContents(target); sel.removeAllRanges(); sel.addRange(range); } try { document.execCommand('delete', false, undefined); } catch {} if ((target.innerText || target.textContent || '').trim()) { throw new Error('Editor did not clear. No replacement text inserted; inspect the exact editor before retrying.'); } // 2. Insert text via browser's native text insertion command (single clean execution) let inserted = false; try { inserted = document.execCommand('insertText', false, item.value); } catch {} // Fallback only if execCommand completely failed and element has no children if (!inserted && !target.hasChildNodes()) { target.textContent = item.value; } // Always dispatch standard input/change events once target.dispatchEvent(new InputEvent('input', { bubbles: true, composed: true, inputType: 'insertText', data: item.value })); target.dispatchEvent(new Event('change', { bubbles: true, composed: true })); } else { target.textContent = item.value; } // Event dispatching if (!isContentEditable) { target.dispatchEvent(new Event('focus', { bubbles: true })); target.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true })); target.dispatchEvent(new InputEvent('input', { bubbles: true, composed: true, inputType: 'insertText', data: item.value })); target.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true, cancelable: true })); target.dispatchEvent(new Event('change', { bubbles: true, composed: true })); target.dispatchEvent(new Event('blur', { bubbles: true })); } // Some Reddit composers update their dirty state only after an editor // transaction. Wake this editor once without Enter or a submit shortcut. if (/reddit\.com$/i.test(location.hostname) && /\/comments\//.test(location.pathname) && item.value.trim() && (tagName === 'textarea' || isContentEditable)) { let scope: Element = target; for (let depth = 0; depth < 6; depth++) { const parent = scope.parentElement || (scope.getRootNode() as ShadowRoot).host; if (!parent) break; scope = parent; if (scope.matches('form,shreddit-comment-composer,shreddit-composer')) break; } const buttons = (root: ParentNode): Element[] => Array.from(root.querySelectorAll('button,input[type="submit"]')).concat( Array.from(root.querySelectorAll('*')).flatMap(el => el.shadowRoot ? buttons(el.shadowRoot) : []) ); const ready = buttons(scope).some(button => /^(comment|reply|post)$/i.test((button.textContent || button.getAttribute('value') || '').trim()) && button.getClientRects().length && !button.hasAttribute('disabled') && button.getAttribute('aria-disabled') !== 'true'); if (!ready) { target.focus(); const event = (key: string, type: string) => target!.dispatchEvent(new KeyboardEvent(type, { key, code: key === ' ' ? 'Space' : 'Backspace', bubbles: true, composed: true })); if (tagName === 'textarea') { const field = target as HTMLTextAreaElement; const end = field.value.length; field.setSelectionRange(end, end); event(' ', 'keydown'); field.setRangeText(' ', end, end, 'end'); field.dispatchEvent(new InputEvent('input', { bubbles: true, composed: true, inputType: 'insertText', data: ' ' })); event(' ', 'keyup'); event('Backspace', 'keydown'); field.setRangeText('', end, end + 1, 'end'); field.dispatchEvent(new InputEvent('input', { bubbles: true, composed: true, inputType: 'deleteContentBackward' })); event('Backspace', 'keyup'); } else { const root = target.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null }; const selection = root.getSelection?.() || window.getSelection(); if (selection) { const range = document.createRange(); range.selectNodeContents(target); range.collapse(false); selection.removeAllRanges(); selection.addRange(range); event(' ', 'keydown'); const inserted = document.execCommand('insertText', false, ' '); event(' ', 'keyup'); if (inserted) { event('Backspace', 'keydown'); document.execCommand('delete', false); event('Backspace', 'keyup'); } } } } } // Visual flash highlight target.style.outline = '2px solid #22c55e'; setTimeout(() => { target!.style.outline = ''; }, 1500); // Verify DOM actual value let actualVal = ''; if (tagName === 'input') { const inp = target as HTMLInputElement; if (inp.type === 'file') { actualVal = Array.from(inp.files || []).map((f) => f.name).join(', ') || inp.value || ''; } else if (inp.type === 'checkbox' || inp.type === 'radio') { actualVal = String(inp.checked); } else { actualVal = inp.value; } } else if (tagName === 'textarea') { actualVal = (target as HTMLTextAreaElement).value; } else if (tagName === 'select') { const sel = target as HTMLSelectElement; const curOpt = sel.options[sel.selectedIndex]; actualVal = curOpt?.text || sel.value || ''; } else { actualVal = target.innerText || target.textContent || ''; if (!actualVal && (isContentEditable || target.getAttribute('role') === 'textbox')) { const innerP = target.querySelector('p, span, .selectable-text'); if (innerP) actualVal = (innerP.textContent || '').trim(); } } const cleanActual = actualVal.toLowerCase().trim(); const cleanRequested = item.value.toLowerCase().trim(); // Check digits equality for formatted phone numbers, SSNs, credit cards, dates, zip codes const digitsActual = cleanActual.replace(/\D/g, ''); const digitsRequested = cleanRequested.replace(/\D/g, ''); const isDigitsMatch = digitsActual.length > 2 && digitsRequested.length > 2 && digitsActual === digitsRequested; // Select element verification: match by value, label, or valid selection let isSelectMatch = false; if (tagName === 'select') { const sel = target as HTMLSelectElement; const curOpt = sel.options[sel.selectedIndex]; const curVal = (curOpt?.value || sel.value || '').toLowerCase().trim(); const curText = (curOpt?.text || '').toLowerCase().trim(); isSelectMatch = curVal === cleanRequested || curText === cleanRequested || curText.includes(cleanRequested) || cleanRequested.includes(curText) || curVal.includes(cleanRequested) || cleanRequested.includes(curVal) || (sel.selectedIndex > 0 && !cleanRequested.includes('select')); } const isFileInput = target.tagName.toLowerCase() === 'input' && (target as HTMLInputElement).type === 'file'; const isFileAttached = isFileInput && ((target as HTMLInputElement).files?.length ?? 0) > 0; const verified = isContentEditable || tagName === 'textarea' ? actualVal.replace(/\r\n/g, '\n').trim() === item.value.replace(/\r\n/g, '\n').trim() : isFileAttached || isDigitsMatch || isSelectMatch || (cleanActual.length > 0 && ( cleanActual.includes(cleanRequested.slice(0, 15)) || cleanRequested.includes(cleanActual.slice(0, 15)) || cleanActual === cleanRequested || (target as HTMLInputElement).type === 'checkbox' || (target as HTMLInputElement).type === 'radio' )); verifications.push({ refId: item.refId || '', selector: item.selector, requestedValue: item.value, actualValue: actualVal, verified, elementFound: true, }); if (verified) { successCount++; if (item.pressEnter || pressEnterAll) { try { target.focus(); const eventInit: KeyboardEventInit = { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true, composed: true, }; target.dispatchEvent(new KeyboardEvent('keydown', eventInit)); target.dispatchEvent(new KeyboardEvent('keypress', eventInit)); target.dispatchEvent(new KeyboardEvent('keyup', eventInit)); setTimeout(() => { // 1. If target text is already cleared, Enter already sent the message! Never click anything. const remaining = ( (target as HTMLInputElement).value !== undefined ? (target as HTMLInputElement).value : (target.innerText || target.textContent || '') ).replace(/[\u200B-\u200D\uFEFF]/g, '').trim(); if (remaining.length === 0) { return; // Message already sent and compose box cleared } // 2. Only look for genuine Send buttons (NEVER match data-tab="11" or voice buttons) const sendBtn = dom.querySelector( 'button[aria-label*="Send" i], span[data-icon="send"], [data-icon="send"], button[data-testid*="send" i]' ); if (!sendBtn) return; // 3. Absolute safety: NEVER click microphone, voice note, or PTT buttons! const isVoiceOrMic = Boolean(sendBtn.querySelector('[data-icon="ptt"], [data-icon="mic"], [aria-label*="voice" i], [aria-label*="record" i]')) || sendBtn.matches('[data-icon="ptt"], [data-icon="mic"]') || /\b(voice|record|ptt|mic|microphone)\b/i.test(sendBtn.getAttribute('aria-label') || ''); if (isVoiceOrMic) return; const clickTarget = sendBtn.closest('button') || sendBtn; clickTarget.click(); }, 100); } catch {} } } else { errors.push(`Field ${item.refId || item.selector} DOM value remained empty or mismatch`); } } catch (e: any) { errors.push(`Error filling ${item.refId}: ${e?.message || e}`); verifications.push({ refId: item.refId || '', selector: item.selector, requestedValue: item.value, actualValue: '', verified: false, elementFound: true, }); } } return { successCount, errors, verifications }; } // In-page fallback script for clicking buttons function inPageClickElement(refId?: string, selector?: string, text?: string): { success: boolean; message: string } { function createDomQuery(root: ParentNode = document) { function roots(node: ParentNode): ParentNode[] { const result: ParentNode[] = [node]; if (node instanceof Element && node.shadowRoot) result.push(...roots(node.shadowRoot)); for (const host of Array.from(node.querySelectorAll('*'))) { if (host.shadowRoot) result.push(...roots(host.shadowRoot)); } return result; } return { querySelectorAll(selector: string): T[] { return [...new Set(roots(root).flatMap(scope => Array.from(scope.querySelectorAll(selector))))]; }, querySelector(selector: string): T | null { for (const scope of roots(root)) { const element = scope.querySelector(selector); if (element) return element; } return null; }, shadowText(): string { const text = roots(root).filter(scope => scope instanceof ShadowRoot).flatMap(scope => Array.from(scope.querySelectorAll('h1,h2,h3,h4,label,p,button,input,textarea,[role="dialog"],[role="button"]')) .filter(el => el.getClientRects().length && getComputedStyle(el).visibility !== 'hidden' && getComputedStyle(el).display !== 'none') .map(el => el.innerText?.trim() || el.getAttribute('aria-label') || el.getAttribute('placeholder') || '') .filter(Boolean)); return [...new Set(text)].join('\n').slice(0, 8000); }, }; } const dom = createDomQuery(); let target: HTMLElement | null = null; if (refId) { target = dom.querySelector(`[data-autoform-ref="${CSS.escape(refId)}"]`); } if (!target && selector) { try { target = dom.querySelector(selector); } catch {} // If selector had an absolute URL e.g. a[href="https://www.youtube.com/@MrBeast"], also try relative pathname if (!target && /href=["']https?:\/\/[^/]+(\/[^"']+)["']/i.test(selector)) { const pathMatch = selector.match(/href=["']https?:\/\/[^/]+(\/[^"']+)["']/i); if (pathMatch) { try { target = dom.querySelector(`a[href="${pathMatch[1]}"], a[href*="${pathMatch[1]}"]`); } catch {} } } } if (!target && text) { const rawCandidates = Array.from(dom.querySelectorAll( 'button, a, input[type="submit"], input[type="button"], [role="button"], [role="link"], [role="tab"], [role="listitem"], [role="row"], [role="treeitem"], [role="menuitem"], [role="option"], [role="menuitemradio"], [role="combobox"], [aria-haspopup], mat-select, bard-mode-switcher, tp-yt-paper-tab, yt-tab-shape, [contenteditable="true"], [role="textbox"], yt-formatted-string, #video-title, #placeholder-area, #simplebox-placeholder, ytd-channel-name, [data-tooltip], [data-testid*="cell"], [data-testid*="list-item"], [data-testid*="chat-list-item"], span[title], div[title], [aria-label], #pane-side div[tabindex="-1"], #pane-side span' )); // Filter out search prediction dropdowns / hidden autocomplete popups so we never accidentally click search suggestions const candidates = rawCandidates.filter((c) => { const inSearchDropdown = c.closest('.sbdd_a, .sbsb_a, #complete-list'); return !inSearchDropdown && c.getClientRects().length > 0 && getComputedStyle(c).visibility !== 'hidden'; }); const tLower = text.toLowerCase().trim(); const tNormalized = tLower.replace(/\s+/g, ''); const getElemText = (c: HTMLElement): string => { return ( c.innerText || c.textContent || (c as HTMLInputElement).value || c.getAttribute('aria-label') || c.getAttribute('data-tooltip') || c.getAttribute('title') || '' ).toLowerCase().trim(); }; // 1. Exact match (highest priority) target = candidates.find((c) => { const val = getElemText(c); const valNorm = val.replace(/\s+/g, ''); return val === tLower || valNorm === tNormalized; }) || null; // 2. Exact word boundary match if (!target) { try { const wordRegex = new RegExp(`(^|\\s|[^a-zA-Z0-9])${tLower.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}($|\\s|[^a-zA-Z0-9])`, 'i'); target = candidates.find((c) => { const val = getElemText(c); return wordRegex.test(val); }) || null; } catch {} } // 3. Substring match, sorted by shortest length (most specific leaf element first) if (!target) { const matches = candidates .map((c) => { const val = getElemText(c); const valNorm = val.replace(/\s+/g, ''); return { elem: c, val, valNorm, len: val.length }; }) .filter((item) => item.val.includes(tLower) || item.valNorm.includes(tNormalized)) .sort((a, b) => a.len - b.len); if (matches.length > 0) { target = matches[0].elem; } } } if (!target) { return { success: false, message: `Button or element not found: ${refId || selector || text}` }; } const container = target.closest( 'a[href], button, [role="button"], [role="tab"], [role="listitem"], [role="row"], [role="menuitem"], [role="option"], [role="treeitem"], div[data-testid*="cell"], div[data-testid*="list-item"], div[data-testid*="chat-list-item"], tp-yt-paper-tab, yt-tab-shape, ytd-compact-video-renderer, ytd-video-renderer, #pane-side div[tabindex="-1"], [contenteditable="true"]' ); // If target itself is an outer row or list item container, resolve its inner primary interactive leaf (contact name, title, button) let leafTarget = target; if (target.matches('[role="listitem"], [role="row"], div[data-testid*="cell"], div[data-testid*="list-item"], #pane-side div[tabindex="-1"]')) { const innerLeaf = target.querySelector( 'span[title], div[title], [title], a[href], button, [role="button"], [role="gridcell"], .title, [class*="title" i], [class*="name" i]' ); if (innerLeaf) { leafTarget = innerLeaf; } } const primary = container || target; try { primary.scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch {} // Inset visual outline and glowing shadow on container try { const prevOutline = primary.style.outline; const prevOffset = primary.style.outlineOffset; const prevShadow = primary.style.boxShadow; const prevTransition = primary.style.transition; primary.style.transition = 'all 0.2s cubic-bezier(0.16, 1, 0.3, 1)'; primary.style.outline = '3px solid #22c55e'; primary.style.outlineOffset = '-2px'; primary.style.boxShadow = '0 0 0 2px #22c55e, 0 0 16px rgba(34, 197, 94, 0.7)'; setTimeout(() => { primary.style.outline = prevOutline; primary.style.outlineOffset = prevOffset; primary.style.boxShadow = prevShadow; primary.style.transition = prevTransition; }, 1200); } catch {} // Dispatch full pointer and mouse sequence to trigger React synthetic events const rect = leafTarget.getBoundingClientRect(); const fallbackRect = primary.getBoundingClientRect(); const effectiveRect = (rect.width > 0 && rect.height > 0) ? rect : fallbackRect; const clientX = Math.round(effectiveRect.left + (effectiveRect.width > 0 ? effectiveRect.width / 2 : 10)); const clientY = Math.round(effectiveRect.top + (effectiveRect.height > 0 ? effectiveRect.height / 2 : 10)); const mouseInit: MouseEventInit = { bubbles: true, cancelable: true, composed: true, view: window, detail: 1, screenX: window.screenX + clientX, screenY: window.screenY + clientY, clientX, clientY, button: 0, buttons: 0, }; const pointerInit: PointerEventInit = { ...mouseInit, pointerId: 1, pointerType: 'mouse', isPrimary: true, width: 1, height: 1, pressure: 0, }; const dispatchTarget = leafTarget || primary; // 1. Hover try { dispatchTarget.dispatchEvent(new PointerEvent('pointerover', { ...pointerInit, buttons: 0 })); dispatchTarget.dispatchEvent(new MouseEvent('mouseover', { ...mouseInit, buttons: 0 })); dispatchTarget.dispatchEvent(new PointerEvent('pointerenter', { ...pointerInit, bubbles: false, buttons: 0 })); } catch {} // 2. Press try { dispatchTarget.dispatchEvent(new PointerEvent('pointerdown', { ...pointerInit, buttons: 1, pressure: 0.5 })); dispatchTarget.dispatchEvent(new MouseEvent('mousedown', { ...mouseInit, buttons: 1 })); } catch {} // 3. Focus interactive container try { primary.focus(); } catch {} // 4. Release try { dispatchTarget.dispatchEvent(new PointerEvent('pointerup', { ...pointerInit, buttons: 0, pressure: 0 })); dispatchTarget.dispatchEvent(new MouseEvent('mouseup', { ...mouseInit, buttons: 0 })); } catch {} // 5. Single atomic click activation // Calling primary.click() triggers the browser's native activation behavior AND fires a single bubbling click event. // We NEVER dispatch a synthetic click event before or after calling primary.click(), because that would fire 2-3 clicks, // causing toggle dropdowns (such as Gemini's model switcher) to immediately open and close! let activated = false; try { if (typeof primary.click === 'function') { primary.click(); activated = true; } } catch {} if (!activated) { try { dispatchTarget.dispatchEvent(new MouseEvent('click', { ...mouseInit, buttons: 0 })); } catch {} } const label = (primary.textContent || primary.getAttribute('aria-label') || target.getAttribute('title') || '').trim().slice(0, 30); return { success: true, message: `Clicked element "${label}"` }; } // --- Audio Alerts for Human-in-the-Loop Intercept Gate --- export function playCaptchaAlertSound() { try { const AudioContextClass = window.AudioContext || (window as any).webkitAudioContext; if (!AudioContextClass) return; const ctx = new AudioContextClass(); if (ctx.state === 'suspended') { ctx.resume().catch(() => {}); } const osc = ctx.createOscillator(); const gain = ctx.createGain(); osc.type = 'sine'; const now = ctx.currentTime; osc.frequency.setValueAtTime(698.46, now); // F5 osc.frequency.setValueAtTime(880, now + 0.15); // A5 gain.gain.setValueAtTime(0.25, now); gain.gain.exponentialRampToValueAtTime(0.01, now + 0.4); osc.connect(gain); gain.connect(ctx.destination); osc.start(now); osc.stop(now + 0.42); } catch {} } export function playCaptchaSuccessSound() { try { const AudioContextClass = window.AudioContext || (window as any).webkitAudioContext; if (!AudioContextClass) return; const ctx = new AudioContextClass(); if (ctx.state === 'suspended') { ctx.resume().catch(() => {}); } const now = ctx.currentTime; const notes = [523.25, 659.25, 783.99]; // C5 -> E5 -> G5 notes.forEach((freq, idx) => { const osc = ctx.createOscillator(); const gain = ctx.createGain(); osc.type = 'triangle'; osc.frequency.setValueAtTime(freq, now + idx * 0.1); gain.gain.setValueAtTime(0.2, now + idx * 0.1); gain.gain.exponentialRampToValueAtTime(0.01, now + idx * 0.1 + 0.18); osc.connect(gain); gain.connect(ctx.destination); osc.start(now + idx * 0.1); osc.stop(now + idx * 0.1 + 0.2); }); } catch {} } // In-page fallback CAPTCHA detection for direct script execution function inPageCheckCaptcha(): { detected: boolean; type?: string; selector?: string } { const isElementVisible = (el: Element | null): boolean => { if (!el) return false; if (!(el instanceof HTMLElement)) return true; const style = window.getComputedStyle(el); if ( style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0' || style.visibility === 'collapse' ) { return false; } const rect = el.getBoundingClientRect(); if (rect.width <= 5 || rect.height <= 5) return false; return true; }; const isInvisibleBadge = (el: Element | null): boolean => { if (!el) return false; if (el.closest('.grecaptcha-badge, [data-size="invisible"]')) return true; if (el.getAttribute('data-size') === 'invisible') return true; return false; }; const title = (document.title || '').trim().toLowerCase(); const bodyText = (document.body ? document.body.innerText || '' : '').toLowerCase().slice(0, 3000); // 1. Cloudflare Turnstile & Interactive Challenge const cfChallengeRunning = document.querySelector('#challenge-running, #challenge-stage'); const cfTurnstileFrame = document.querySelector('iframe[src*="challenges.cloudflare.com"]'); if ( title.includes('just a moment...') || title.includes('attention required! | cloudflare') || (cfChallengeRunning && isElementVisible(cfChallengeRunning)) || (cfTurnstileFrame && isElementVisible(cfTurnstileFrame)) || (bodyText.includes('checking your browser') && bodyText.includes('cloudflare') && bodyText.length < 1000) ) { return { detected: true, type: 'cloudflare', selector: '#challenge-form, #challenge-stage, iframe[src*="challenges.cloudflare.com"]', }; } // 2. Google reCAPTCHA (only active challenge bframe or visible checkbox, never invisible v3 badges) const recaptchaBframe = document.querySelector('iframe[src*="recaptcha/api2/bframe"], iframe[src*="recaptcha/enterprise/bframe"]'); const recaptchaAnchor = document.querySelector('iframe[src*="recaptcha/api2/anchor"], iframe[src*="recaptcha/enterprise/anchor"]'); if ( (recaptchaBframe && isElementVisible(recaptchaBframe)) || (recaptchaAnchor && isElementVisible(recaptchaAnchor) && !isInvisibleBadge(recaptchaAnchor)) ) { return { detected: true, type: 'recaptcha', selector: 'iframe[src*="recaptcha"]', }; } // 3. hCaptcha const hcaptchaBox = document.querySelector('iframe[src*="hcaptcha.com/box"], iframe[src*="hcaptcha.com"][title*="challenge" i]'); const hcaptchaAnchor = document.querySelector('iframe[src*="hcaptcha.com"]'); if ( (hcaptchaBox && isElementVisible(hcaptchaBox)) || (hcaptchaAnchor && isElementVisible(hcaptchaAnchor) && !isInvisibleBadge(hcaptchaAnchor)) ) { return { detected: true, type: 'hcaptcha', selector: 'iframe[src*="hcaptcha.com"]', }; } // 4. Arkose Labs / FunCaptcha const arkoseFrame = document.querySelector('#fc-iframe-wrap iframe, iframe[src*="arkoselabs"]'); if (arkoseFrame && isElementVisible(arkoseFrame)) { return { detected: true, type: 'arkose', selector: '#fc-iframe-wrap iframe, iframe[src*="arkoselabs"]', }; } // 5. Bing Bot Challenge (visible challenge only, no generic challenge form actions) const bingCaptcha = document.querySelector('#b_captcha'); if ( (bingCaptcha && isElementVisible(bingCaptcha)) || (bodyText.includes('please solve this puzzle') && bodyText.includes('person') && bodyText.length < 800) || (bodyText.includes('verify that you are human') && (bodyText.includes('bing') || title.includes('bing')) && bodyText.length < 800) ) { return { detected: true, type: 'bing_bot', selector: '#b_captcha', }; } // 6. Generic Anti-Bot Challenge (must be dedicated interstitial page with short content) if ( title === 'robot check' || title.includes('robot check') || title === 'security check' || title === 'human verification' || title === 'bot verification' || ((bodyText.includes('verify you are human') || bodyText.includes('confirm you are not a robot')) && bodyText.length < 500 && !document.querySelector('main, article')) ) { return { detected: true, type: 'generic', selector: 'body', }; } return { detected: false }; } async function normalizeCaptchaDetection(tabId:number, check:{detected:boolean;type?:string;selector?:string}) { if(!check.detected || !['recaptcha','hcaptcha','cloudflare'].includes(check.type || '')) return check; try { const proof=await chrome.scripting.executeScript({target:{tabId},args:[check.type || ''],func:(type:string)=>{ const selectors:Record={recaptcha:'[name="g-recaptcha-response"]',hcaptcha:'[name="h-captcha-response"]',cloudflare:'[name="cf-turnstile-response"]'}; const hasResponse=Array.from(document.querySelectorAll(selectors[type])).some(el=>Boolean((el as HTMLInputElement).value?.trim())); const puzzle=Array.from(document.querySelectorAll('iframe[src*="/bframe"], iframe[title*="challenge" i], #challenge-stage')) .some(el=>el.getClientRects().length>0 && getComputedStyle(el).visibility!=='hidden'); return hasResponse && !puzzle; }}); return proof[0]?.result ? {detected:false} : check; } catch {return check;} } export async function checkActiveTabCaptcha(tabId?: number): Promise<{ detected: boolean; type?: string; selector?: string }> { let targetTabId = tabId; if (!targetTabId) { const activeTab = await getActiveTab(); targetTabId = activeTab?.id; } if (!targetTabId || typeof chrome === 'undefined' || !chrome.tabs) { return { detected: false }; } // 1. Try sendMessageToTab first try { const res = await sendMessageToTab<{ success: boolean; data: { detected: boolean; type?: string; selector?: string } }>( targetTabId, { action: 'CHECK_CAPTCHA' }, 1000 ); if (res && res.success && res.data) { return normalizeCaptchaDetection(targetTabId, res.data); } } catch { // Fall back to direct executeScript } // 2. Direct executeScript fallback if (chrome.scripting) { try { const results = await chrome.scripting.executeScript({ target: { tabId: targetTabId }, func: inPageCheckCaptcha, }); if (results && results[0] && results[0].result) { return normalizeCaptchaDetection(targetTabId, results[0].result as { detected: boolean; type?: string; selector?: string }); } } catch { // Ignore } } return { detected: false }; } // Route visible CAPTCHA clicks into their frame instead of clicking the iframe // element in the parent page. No challenge scripts or response tokens are altered. async function clickVisibleCaptchaPoint(tabId:number,x:number,y:number):Promise { try { const hit=await chrome.scripting.executeScript({target:{tabId},args:[x,y],func:(x:number,y:number)=>{ const d=window.devicePixelRatio||1,el=document.elementFromPoint(x/d,y/d); if(!(el instanceof HTMLIFrameElement)) return null; const r=el.getBoundingClientRect(); return {src:el.src,x:x/d-r.x,y:y/d-r.y,width:r.width,height:r.height}; }}); const frame=hit[0]?.result; if(!frame) return (await clickAtPosition({tabId,x,y})).success; const frames=await chrome.scripting.executeScript({target:{tabId,allFrames:true},func:()=>({url:location.href,width:innerWidth,height:innerHeight})}); const matches=frames.filter(entry=>entry.frameId!==0 && entry.result?.url===frame.src); if(matches.length!==1 || !frame.width || !frame.height) return false; const selected=matches[0]; const result=await chrome.scripting.executeScript({target:{tabId,frameIds:[selected.frameId]},func:inPageClickAtPoint, args:[frame.x*selected.result!.width/frame.width,frame.y*selected.result!.height/frame.height,1,0,false]}); return Boolean(result[0]?.result?.success); } catch {return false;} } // Failed automatic attempts are not repeated for the same page in a tight loop. const captchaAutoAttempts = new Map}>(); async function tryCaptchaBeforeHumanGate(tabId:number, url:string):Promise { const key = `${tabId}:${url}`; const previous = captchaAutoAttempts.get(key); if(previous && Date.now()-previous.at<120000) return previous.result; for(const [id,entry] of captchaAutoAttempts) if(Date.now()-entry.at>=120000) captchaAutoAttempts.delete(id); const result = attemptVisibleCaptcha({ current: async()=>{ const tab=await getActiveTab();return tab?.id===tabId && tab.url===url; }, detected: async()=> (await checkActiveTabCaptcha(tabId)).detected, snapshot: async()=>{ const check=await checkActiveTabCaptcha(tabId); const results=await chrome.scripting.executeScript({target:{tabId},args:[check.selector || ''],func:(selector:string)=>{ if(!selector) return []; return Array.from(document.querySelectorAll(selector)).filter(el=>el.getClientRects().length && getComputedStyle(el).visibility!=='hidden') .map(el=>{const r=el.getBoundingClientRect(),d=window.devicePixelRatio||1;return {x:r.x*d,y:r.y*d,width:r.width*d,height:r.height*d};}); }}); return {image:await captureTabScreenshot(),boxes:results[0]?.result || []}; }, vision:(image,prompt,signal)=>extractTextWithVlm(image,'image/jpeg',prompt,signal), click:(x,y)=>clickVisibleCaptchaPoint(tabId,x,y), }); captchaAutoAttempts.set(key,{at:Date.now(),result}); const solved=await result; if(solved) captchaAutoAttempts.delete(key); return solved; } // --- Human-in-the-Loop (HITL) 10-Second CAPTCHA Intercept Gate Manager --- export interface CaptchaState { isActive: boolean; isManualSolving?: boolean; type: string; url: string; remainingSeconds: number; } type CaptchaListener = (state: CaptchaState) => void; class CaptchaGateManager { private activeState: CaptchaState = { isActive: false, isManualSolving: false, type: '', url: '', remainingSeconds: 0, }; private listeners = new Set(); private activeResolver: ((value: { solved: boolean; message: string }) => void) | null = null; private countdownTimer: any = null; private pollInterval: any = null; public getState(): CaptchaState { return { ...this.activeState }; } public subscribe(cb: CaptchaListener): () => void { this.listeners.add(cb); cb(this.getState()); return () => this.listeners.delete(cb); } private notify() { const state = this.getState(); this.listeners.forEach((cb) => cb(state)); if (typeof window !== 'undefined') { window.dispatchEvent(new CustomEvent('openbua_captcha_state', { detail: state })); } } public pauseForManualSolving() { if (!this.activeState.isActive) return; if (this.countdownTimer) { clearInterval(this.countdownTimer); this.countdownTimer = null; } this.activeState.isManualSolving = true; this.notify(); } private gateSafetyTimer: ReturnType | null = null; public resolveActiveGate(solved: boolean, customMessage?: string) { if (!this.activeState.isActive || !this.activeResolver) return; if (this.countdownTimer) clearInterval(this.countdownTimer); if (this.pollInterval) clearInterval(this.pollInterval); if (this.gateSafetyTimer) clearTimeout(this.gateSafetyTimer); this.gateSafetyTimer = null; this.countdownTimer = null; this.pollInterval = null; if (solved) { playCaptchaSuccessSound(); } const resolver = this.activeResolver; this.activeResolver = null; this.activeState = { isActive: false, isManualSolving: false, type: '', url: '', remainingSeconds: 0, }; this.notify(); resolver({ solved, message: customMessage || (solved ? 'CAPTCHA was resolved by user. Resuming automation.' : 'CAPTCHA challenge skipped by user. ABORT this domain immediately and pivot to an alternate source/query.'), }); } public async runGate(tabId: number, type: string, url: string): Promise<{ solved: boolean; message: string }> { if (this.activeState.isActive) { return { solved: false, message: 'CAPTCHA gate already active.' }; } if (await tryCaptchaBeforeHumanGate(tabId, url)) { return {solved:true,message:'CAPTCHA cleared after the automatic visible challenge attempt. Resuming automation.'}; } const currentTab = await getActiveTab(); if (currentTab?.id !== tabId || currentTab.url !== url) { return {solved:false,message:'CAPTCHA attempt stopped because the active page changed. Inspect the current tab before continuing.'}; } if (this.activeState.isActive) return {solved:false,message:'CAPTCHA gate already active.'}; playCaptchaAlertSound(); this.activeState = { isActive: true, isManualSolving: false, type: type || 'bot_challenge', url, remainingSeconds: 10, }; this.notify(); return new Promise<{ solved: boolean; message: string }>((resolve) => { this.activeResolver = resolve; // Absolute hard safety timeout (12s) to prevent any possibility of indefinite freezing const hardTimeout = setTimeout(() => { if (this.activeState.isActive) { this.resolveActiveGate(false, 'CAPTCHA challenge timed out after safety period. Resuming automation.'); } }, 12000); this.gateSafetyTimer = hardTimeout; // 1. Tick countdown every 1 second this.countdownTimer = setInterval(() => { if (!this.activeState.isActive) { clearTimeout(hardTimeout); return; } const nextRemaining = this.activeState.remainingSeconds - 1; if (nextRemaining <= 0) { clearTimeout(hardTimeout); // Timer expired: do a final check to see if human solved it right before expiry checkActiveTabCaptcha(tabId) .then((check) => { if (!check.detected) { this.resolveActiveGate(true, 'CAPTCHA challenge solved before 10s timeout expired. Resuming automation.'); } else { this.resolveActiveGate( false, 'CAPTCHA challenge timed out after 10s. Human was unable to solve it or chose to pivot. Workaround activated: ABORT current domain/URL immediately and pivot to an alternate source (e.g. Google X-Ray search, web search snippet, or alternate URL). Do NOT attempt to reload this blocked URL.' ); } }) .catch(() => { this.resolveActiveGate(false, 'CAPTCHA check failed. Resuming automation.'); }); } else { this.activeState.remainingSeconds = nextRemaining; this.notify(); } }, 1000); // 2. Poll every 600ms for DOM detachment / human solving this.pollInterval = setInterval(async () => { if (!this.activeState.isActive) return; try { const check = await checkActiveTabCaptcha(tabId); if (!check.detected) { clearTimeout(hardTimeout); this.resolveActiveGate(true, 'CAPTCHA challenge solved by human in browser (DOM challenge cleared). Resuming automation.'); } } catch { // ignore transient poll errors } }, 600); }); } } export const captchaManager = new CaptchaGateManager(); // Inspect Form on Active Tab export async function inspectActiveTabForm(selector?: string): Promise { const activeTab = await getActiveTab(); if (!activeTab || !activeTab.id) { return getMockFormSummary(); } if (activeTab.url && (activeTab.url.startsWith('chrome://') || activeTab.url.startsWith('chrome-extension://') || activeTab.url.startsWith('edge://') || activeTab.url.startsWith('about:'))) { throw new Error(`Chrome restricts extensions from accessing internal pages (${activeTab.url}). Please open a regular webpage or form (such as test-form.html) in your browser!`); } // Check for CAPTCHA challenge before inspecting form const captcha = await checkActiveTabCaptcha(activeTab.id); if (captcha.detected) { const gate = await captchaManager.runGate(activeTab.id, captcha.type || 'bot_challenge', activeTab.url || ''); if (!gate.solved) { throw new Error(`[BLOCKED BY CAPTCHA]: ${gate.message}`); } } // 1. Try sendMessageToTab first with generous 4-second timeout for rich SPAs try { const response = await sendMessageToTab(activeTab.id, { action: 'INSPECT_PAGE_FORM', selector }, 4000); if (response && response.success && response.data) { return response.data; } } catch (err: any) { console.warn('[OpenBUA] sendMessageToTab failed, falling back to direct executeScript:', err?.message || err); } // 2. Direct executeScript fallback (never hangs, 100% reliable) if (typeof chrome !== 'undefined' && chrome.scripting) { try { const results = await chrome.scripting.executeScript({ target: { tabId: activeTab.id }, func: inPageInspectForm, args: selector ? [selector] : [], }); if (results && results[0] && results[0].result) { return results[0].result as PageFormSummary; } } catch (scriptErr: any) { const msg = scriptErr?.message || String(scriptErr); if (msg.includes('Cannot access contents of url') || msg.includes('file:')) { throw new Error(`Permission needed: To allow OpenBUA to inspect local files (file:///...), please open chrome://extensions -> OpenBUA Details -> toggle ON "Allow access to file URLs". Alternatively, test on any http:// or https:// webpage!`); } throw scriptErr; } } throw new Error('Failed to inspect form fields on the active tab.'); } async function verifyAutocompleteFill(tabId:number, assignments:Array<{refId?:string;selector?:string;value:string}>, result:FormFillResult):Promise { if(typeof chrome==='undefined' || !chrome.scripting) return result; let observations; try {observations=await inspectAutocomplete(tabId,assignments,true);} catch { // Filling already dispatched. A verification failure must not replay it. for(const verification of result.verifications) {verification.verified=false;verification.status='not-inspected';} result.successCount=0; result.errors.push('Could not inspect selection/validation after filling. Inspect the current field before retrying; the text may already be present.'); return result; } for(const observed of observations) { if(!observed.autocomplete && !observed.invalid) continue; const verification=result.verifications.find(v=>observed.refId ? v.refId===observed.refId : v.selector===observed.selector); if(!verification) continue; const verified=observed.autocomplete ? Boolean(observed.selected) : !observed.invalid; if(verification.verified && !verified) result.successCount--; if(!verification.verified && verified) result.successCount++; verification.verified=verified; verification.actualValue=observed.value; verification.status=verified ? 'selected-option' : 'selection-required'; if(!verified) result.errors.push(`${observed.label || observed.refId}: ${observed.message || 'Autocomplete text is not a selected option'}. Select a matching dropdown option before Next; do not dismiss the popup and repeat Next.`); } return result; } // Fill fields on active tab export async function fillActiveTabFields( assignments: Array<{ refId?: string; selector?: string; value: string; pressEnter?: boolean; fileData?: { fileName: string; mimeType: string; dataUrl: string }; }>, pressEnterAll?: boolean ): Promise { const activeTab = await getActiveTab(); if (!activeTab || !activeTab.id) { console.log('[Dev Mock] Filled fields:', assignments); return { successCount: assignments.length, errors: [], verifications: assignments.map(a => ({ refId: a.refId || '', selector: a.selector, requestedValue: a.value, actualValue: a.value, verified: true, elementFound: true, })), }; } if (activeTab.url && (activeTab.url.startsWith('chrome://') || activeTab.url.startsWith('chrome-extension://') || activeTab.url.startsWith('edge://') || activeTab.url.startsWith('about:'))) { throw new Error(`Chrome restricts extensions from accessing internal pages (${activeTab.url}). Please open a regular webpage or form (such as test-form.html) in your browser!`); } // Pre-fetch stored documents to automatically attach raw file binary if assignment targets a file or references a stored file/resume if (/^https:\/\/(?:www\.|old\.|new\.)?reddit\.com\/r\/[^/]+\/submit\/?(?:\?|$)/i.test(activeTab.url || '')) { const draft = await writeRedditDraft(activeTab.id, assignments); if (!('mode' in draft) || !['file-input', 'native-form'].includes(draft.mode)) return draft; } const tabKey = getActiveSessionIdState(); const [globalDocs, tabDocs] = await Promise.all([ loadGlobalMemories().catch(() => []), loadTabMemories(tabKey).catch(() => []), ]); const allStoredDocs = [...tabDocs, ...globalDocs].filter(doc => doc.isActiveForContext); const cleanAssignments = (assignments || []).map((a) => { let fileData = a.fileData; if (!fileData) { const valLower = String(a.value ?? '').toLowerCase().trim(); const selLower = String(a.selector ?? '').toLowerCase(); const refLower = String(a.refId ?? '').toLowerCase(); const isFileField = selLower.includes('file') || selLower.includes('upload') || selLower.includes('resume') || selLower.includes('cv') || refLower.includes('file') || refLower.includes('upload'); const isFileVal = valLower.endsWith('.pdf') || valLower.endsWith('.png') || valLower.endsWith('.jpg') || valLower.endsWith('.jpeg') || valLower.endsWith('.webp') || valLower === 'resume' || valLower === 'my resume' || valLower === 'cv'; if (isFileField || isFileVal) { const genericResume = !valLower || ['resume', 'my resume', 'cv'].includes(valLower); const match = allStoredDocs.find(d => d.dataUrl && (d.fileName?.toLowerCase() === valLower || d.id.toLowerCase() === valLower || d.title.toLowerCase() === valLower)) || (genericResume ? allStoredDocs.find(d => d.dataUrl && (d.fileCategory === 'resume' || d.tags?.includes('resume') || /resume|cv/i.test(d.fileName || d.title))) : undefined); if (match && match.dataUrl) { fileData = { fileName: match.fileName || `${match.title}.${match.type === 'pdf' ? 'pdf' : 'png'}`, mimeType: match.mimeType || (match.type === 'pdf' ? 'application/pdf' : 'application/octet-stream'), dataUrl: match.dataUrl, }; if (!a.value || a.value === 'resume' || a.value === 'my resume') { a.value = fileData.fileName; } } } } return { refId: a.refId || '', selector: a.selector || '', value: String(a.value ?? ''), pressEnter: Boolean(a.pressEnter), fileData, }; }); // Generous timeout for large forms (e.g. 40+ fields on test pages) const fillTimeoutMs = Math.max(12000, cleanAssignments.length * 300); // 1. Try sendMessageToTab try { const response = await sendMessageToTab(activeTab.id, { action: 'FILL_FORM_FIELDS', assignments: cleanAssignments, pressEnter: Boolean(pressEnterAll), }, fillTimeoutMs); if (response && response.success && response.data) { return await verifyAutocompleteFill(activeTab.id, cleanAssignments, response.data as FormFillResult); } } catch (err: any) { console.warn('[OpenBUA] sendMessageToTab failed, falling back to direct executeScript:', err?.message || err); } // 2. Direct executeScript fallback if (typeof chrome !== 'undefined' && chrome.scripting) { try { const results = await chrome.scripting.executeScript({ target: { tabId: activeTab.id }, func: inPageFillForm, args: [cleanAssignments, Boolean(pressEnterAll)], }); if (results && results[0] && results[0].result) { return await verifyAutocompleteFill(activeTab.id, cleanAssignments, results[0].result as FormFillResult); } } catch (scriptErr: any) { const msg = scriptErr?.message || String(scriptErr); if (msg.includes('Cannot access contents of url') || msg.includes('file:')) { throw new Error(`Permission needed: Please enable "Allow access to file URLs" in chrome://extensions -> OpenBUA Details to interact with local files.`); } throw scriptErr; } } throw new Error('Failed to fill form fields on active tab'); } // Programmatically upload a stored raw file (resume, image, PDF, video) to a file input or dropzone on active tab /** A stored document counts as usable when its raw bytes are reachable. */ function hasRawBytes(m: UserDocument): boolean { return Boolean(m.blobKey || m.dataUrl || m.filePath); } export interface ResolvedStoredFile { doc: UserDocument; source: FileSource; fileName: string; mimeType: string; } /** * Find the stored document the user means and turn it into bytes we can inject. * Videos and other large media come from the blob store, so nothing large is * ever held as a base64 string. */ export async function resolveStoredFile(options: { fileName?: string; /** Current tab URL, used to bias toward media when nothing was named. */ tabUrl?: string; }): Promise { const tabKey = getActiveSessionIdState(); const [globalMems, tabMems] = await Promise.all([ loadGlobalMemories().catch(() => []), loadTabMemories(tabKey).catch(() => []), ]); const allMems = [...tabMems, ...globalMems].filter(m => m.isActiveForContext) .sort((a, b) => Number(Boolean(b.tabUrlPattern === tabKey)) - Number(Boolean(a.tabUrlPattern === tabKey)) || b.createdAt - a.createdAt); const requestedName = (options.fileName || '').toLowerCase().trim(); const isVideoDoc = (m: UserDocument) => hasRawBytes(m) && (m.fileCategory === 'video' || m.type === 'video' || m.tags?.includes('video')); let match: UserDocument | undefined; if (requestedName) { // A named attachment must never fall back to a different resume or video. match = allMems.find(m => hasRawBytes(m) && (m.id.toLowerCase() === requestedName || m.fileName?.toLowerCase() === requestedName)) || allMems.find(m => hasRawBytes(m) && (m.title.toLowerCase() === requestedName || m.filePath?.toLowerCase() === requestedName)); if (!match) return null; } else { const isApplication = /linkedin\.com\/jobs|apply|application|careers/i.test(options.tabUrl || ''); if (!isApplication && SOCIAL_MEDIA_HOST_HINTS.some(hint => (options.tabUrl || '').includes(hint))) { match = allMems.find(isVideoDoc); } match ||= allMems.find(m => hasRawBytes(m) && (m.fileCategory === 'resume' || m.tags?.includes('resume') || /resume|cv/i.test(m.fileName || m.title))); match ||= allMems.find(hasRawBytes); } if (!match) return null; // Last resort for documents that only have a local path on disk. if (!match.blobKey && !match.dataUrl && match.filePath) { const loaded = await tryLoadFileFromLocalPath(match.filePath); if (loaded) { match = { ...match, dataUrl: loaded.dataUrl, mimeType: loaded.mimeType, fileName: match.fileName || loaded.fileName, }; } } const source = await resolveFileSource(match); if (!source) return null; return { doc: match, source, fileName: match.fileName || `${match.title}.${extensionForDoc(match)}`, mimeType: match.mimeType || (match.type === 'pdf' ? 'application/pdf' : match.type === 'video' ? 'video/mp4' : match.type === 'image' ? 'image/png' : 'application/octet-stream'), }; } function extensionForDoc(doc: UserDocument): string { if (doc.type === 'pdf') return 'pdf'; if (doc.type === 'video') return 'mp4'; if (doc.type === 'image') return 'png'; if (doc.type === 'markdown') return 'md'; if (doc.type === 'json') return 'json'; return 'txt'; } /** Hosts where a stored video is the media the user most likely means. */ const SOCIAL_MEDIA_HOST_HINTS = [ 'reddit.com', 'twitter.com', 'x.com', 'linkedin.com', 'facebook.com', 'instagram.com', 'threads.net', 'youtube.com', 'tiktok.com', 'bsky.app', 'mastodon.social', 'pinterest.com', 'tumblr.com', ]; export async function uploadFileToActiveTab(options: { refId?: string; selector?: string; fileName?: string; fileData?: { fileName: string; mimeType: string; dataUrl: string }; }): Promise<{ success: boolean; message: string; fileName?: string }> { const activeTab = await getActiveTab(); if (!activeTab || !activeTab.id) { return { success: false, message: 'No active browser tab found to upload file to.' }; } // Legacy inline payload from fill_form_fields. if (options.fileData?.dataUrl) { const result = await injectFileIntoTab( activeTab.id, { fileName: options.fileData.fileName, mimeType: options.fileData.mimeType || 'application/octet-stream', source: { kind: 'dataUrl', dataUrl: options.fileData.dataUrl }, refId: options.refId, selector: options.selector, }, sendMessageToTab ); return { ...result, fileName: options.fileData.fileName }; } const requestedName = (options.fileName || '').toLowerCase().trim(); const resolved = await resolveStoredFile({ fileName: options.fileName, tabUrl: activeTab.url }); if (!resolved) { return { success: false, message: `No stored document with raw file attachment or file path was found in Memory${ requestedName ? ` matching "${requestedName}"` : '' }. Please upload your video, resume, or file in the Memory tab first!`, }; } const result = await injectFileIntoTab( activeTab.id, { fileName: resolved.fileName, mimeType: resolved.mimeType, source: resolved.source, refId: options.refId, selector: options.selector, }, sendMessageToTab ); return { ...result, success: result.success, message: result.success ? `${result.message} Source: stored memory "${resolved.doc.title}".` : `${result.message} (Tried stored memory "${resolved.doc.title}".)`, fileName: resolved.fileName, }; } // Click element on active tab export async function clickActiveTabElement(options: { refId?: string; selector?: string; text?: string; }): Promise<{ success: boolean; message: string }> { const activeTab = await getActiveTab(); if (!activeTab || !activeTab.id) { return { success: true, message: `[Dev Mock] Clicked element: ${JSON.stringify(options)}` }; } // 1. Try sendMessageToTab try { const response = await sendMessageToTab(activeTab.id, { action: 'CLICK_ELEMENT', ...options, }, 2000); if (response && response.success) { return response; } } catch (err) { // Fall back to direct script } // 2. Direct executeScript fallback if (typeof chrome !== 'undefined' && chrome.scripting) { try { const results = await chrome.scripting.executeScript({ target: { tabId: activeTab.id }, func: inPageClickElement, args: [options.refId || '', options.selector || '', options.text || ''], }); if (results && results[0] && results[0].result) { return results[0].result as { success: boolean; message: string }; } } catch { // Fall through } } return { success: false, message: 'Could not click element on active tab' }; } // --------------------------------------------------------------------------- // Canvas-editor input (Google Docs, Sheets, Figma, Canva, Word Online) // // These editors paint text onto a and consume a trusted `beforeinput` // on a hidden same-origin iframe. The normal element tools cannot reach either, // so caret placement is done with a real mouse sequence at coordinates and // typing is done through execCommand('insertText'). // // The inPage* fallbacks below are shipped via chrome.scripting.executeScript, // which serializes exactly one function: every helper they need is declared // inside their own body. Do not hoist anything out of them. // --------------------------------------------------------------------------- /* eslint-disable @typescript-eslint/no-explicit-any */ function inPageClickAtPoint( x: number, y: number, clickCount: number, button: number, shiftKey: boolean ): { success: boolean; message: string; element: string; viewport?: { width: number; height: number; devicePixelRatio: number } } { const count = Math.max(1, clickCount || 1); const btn = button ?? 0; // Always report the viewport so a miss is diagnosable without guessing. const viewport = { width: window.innerWidth, height: window.innerHeight, devicePixelRatio: window.devicePixelRatio || 1, }; const target = document.elementFromPoint(x, y) as HTMLElement | null; if (!target) { return { success: false, message: `Nothing at (${Math.round(x)}, ${Math.round(y)}) in CSS pixels. ` + `The viewport is only ${viewport.width}x${viewport.height} CSS px at devicePixelRatio ${viewport.devicePixelRatio}. ` + `If you read these coordinates from a screenshot, remember screenshots are ${viewport.devicePixelRatio}x larger. ` + `Either re-read the coordinate and retry, or scroll the target into the visible area first.`, element: 'none', viewport, }; } const common = { bubbles: true, cancelable: true, composed: true, view: window, clientX: x, clientY: y, screenX: window.screenX + x, screenY: window.screenY + y, button: btn, detail: count, // Shift-click extends the selection, the only way to select a range in a // canvas editor where there is no element to target. shiftKey: Boolean(shiftKey), ctrlKey: false, altKey: false, metaKey: false, }; try { target.dispatchEvent( new PointerEvent('pointerdown', { ...common, pointerId: 1, pointerType: 'mouse', isPrimary: true, buttons: btn === 2 ? 2 : 1, }) ); } catch { /* PointerEvent unsupported */ } target.dispatchEvent(new MouseEvent('mousedown', { ...common, buttons: btn === 2 ? 2 : 1 })); if (count > 1) { target.dispatchEvent(new MouseEvent('mouseup', common)); target.dispatchEvent(new MouseEvent('mousedown', { ...common, detail: 1, buttons: 1 })); } target.dispatchEvent(new MouseEvent('mouseup', common)); target.dispatchEvent(new MouseEvent('click', common)); if (count > 1) target.dispatchEvent(new MouseEvent('dblclick', { ...common, detail: 2 })); const tag = target.tagName.toLowerCase(); return { success: true, message: `Clicked at (${Math.round(x)}, ${Math.round(y)}) CSS px on <${tag}>${count > 1 ? ` (${count} clicks)` : ''}` + `${shiftKey ? ' with Shift held, extending the selection' : ''}. Click dispatched. A click alone does not confirm navigation or establish a text caret; use the actual link/control when the page has not changed.`, element: tag, viewport, }; } function inPageTypeText( text: string, pressEnterForNewlines: boolean, clearFirst = false ): { success: boolean; message: string; lines: number; chars: number } { // Resolve the surface that actually receives keystrokes. Canvas editors route // input through a hidden same-origin iframe, so events sent at the top-level // activeElement land on the