/** * Deterministic credential entry + login for the DEBUG browser (2026-10). * * The debug/MCP browser (`browser_open` / `browser_action`) is an agent-driven * QA/automation browser. It historically refused to touch any password field * (`LOGIN_BLOCKED`), which made QA tasks that need a sign-in impossible. This * module is the explicit, OPT-IN escape hatch (`allowCredentials`), authored so * the LLM never has to type a secret itself: * * - `findLoginFields(page)` locates the username / password / submit / OTP * controls with DOM heuristics. It scopes the search to the TOPMOST OPEN * DIALOG when one exists, because a login opened in a modal must not be * confused with a footer newsletter field or the page's nav "Login" button. * - `performLogin(page, { username, password, otp? })` clears every field, * fills it, verifies the exact value, submits, and follows the site's real * flow: email → password, email → OTP, email → password → OTP, password → * OTP, OTP only. It NEVER reports success while an OTP field is visible. * - `fillFieldVerified(page, control, value)` always clears first (select-all * + Backspace + native value setter), verifies the field is EMPTY, then * types and verifies the value EXACTLY. The old version compared only the * length, so an autofilled value plus the typed text could pass as * "filled" - or fail forever. * - `typeTextVerified(page, text)` is the same verification for the generic * `type` action; `clearFirst` makes it replace instead of append. * * The auto-answer loop (`browse --auto-answer`) is a DIFFERENT code path and * still never touches credentials - see `personal-fields.ts`. * * NO secret is ever logged here. */ import { type CdpPage } from './cdp'; export interface LoginControl { x: number; y: number; /** name/id/autocomplete of the control, for diagnostics only (never a value). */ hint?: string; /** Stable role tag written into the DOM (`data-ts-login`). */ role?: 'username' | 'password' | 'otp' | 'submit'; } export interface LoginFields { username: LoginControl | null; password: LoginControl | null; submit: LoginControl | null; /** True when a one-time-code / OTP challenge field is on screen. */ otp: LoginControl | null; /** True when the fields were found inside an open dialog/modal. */ modal: boolean; } export type LoginError = 'LOGIN_FIELD_NOT_FOUND' | 'CREDENTIAL_FILL_FAILED' | 'MFA_REQUIRED' | 'LOGIN_REJECTED' | 'LOGIN_NO_SESSION'; export type LoginPhase = 'username' | 'password' | 'otp' | 'submitted' | 'unknown'; export interface LoginResult { ok: boolean; usernameFilled: boolean; passwordFilled: boolean; otpFilled: boolean; submitted: boolean; twoStep: boolean; /** Where in the flow the result stopped. */ phase: LoginPhase; /** True when a one-time-code challenge is waiting for a human/code. */ mfaRequired: boolean; /** Visible site error (validation / invalid credentials), never a secret. */ visibleError?: string; error?: LoginError; detail?: string; } export interface PerformLoginOptions { username?: string; /** * Password. OPTIONAL for an email-only (`email_otp`) or OTP-only step: a * password is only required when a password field is actually on screen. */ password?: string; /** * One-time code (OTP). When an OTP field is on screen and a code is * supplied, it is filled and submitted. The code arrives from a resumed * ask_human answer or a QA mailbox - never invent one. */ otp?: string; /** Click the submit/continue control (default true). */ submit?: boolean; /** Max time to wait for the next login step (default 6000ms). */ stepTimeoutMs?: number; /** Max form steps (default 4: email -> password -> otp -> settle). */ maxSteps?: number; } /** DOM heuristic: locate the login controls, scoped to the topmost modal. */ export declare const FIND_LOGIN_FIELDS_JS = "(() => {\n const vis = (el) => {\n if (!el) return false;\n const r = el.getBoundingClientRect();\n if (r.width === 0 || r.height === 0) return false;\n const cs = getComputedStyle(el);\n return cs.visibility !== 'hidden' && cs.display !== 'none' && cs.opacity !== '0';\n };\n const hintOf = (el) => [el.getAttribute('name'), el.id, el.getAttribute('autocomplete')].filter(Boolean).join('/');\n const lowerType = (el) => (el.type || '').toLowerCase();\n const autocomplete = (el) => (el.getAttribute('autocomplete') || '').toLowerCase();\n\n // MODAL SCOPE (2026-10): a login opened in a dialog must win over a footer\n // newsletter input or the page's nav Login button. Prefer the first visible\n // dialog/frame that actually contains a login-ish field; otherwise the last\n // visible dialog; otherwise the document.\n const dialogSel = 'dialog[open],[role=\"dialog\"],[aria-modal=\"true\"],' +\n '[class*=\"modal\"],[class*=\"Modal\"],[class*=\"dialog\"],[class*=\"Dialog\"]';\n const dialogEls = [...document.querySelectorAll(dialogSel)].filter(vis);\n const hasStrongLogin = (d) => !!d.querySelector('input[type=\"password\"],input[autocomplete=\"username\"],input[autocomplete=\"current-password\"],input[autocomplete=\"new-password\"],input[autocomplete=\"one-time-code\"]');\n const hasEmailAndContinue = (d) => {\n if (!d.querySelector('input[type=\"email\"],input[autocomplete=\"email\"]')) return false;\n return [...d.querySelectorAll('button,[role=\"button\"],input[type=\"submit\"]')].some((el) =>\n /continue|next|sign|log\\s?in|verify|submit/i.test((el.innerText || el.textContent || el.value || '').trim()),\n );\n };\n let scope =\n dialogEls.find(hasStrongLogin) ||\n dialogEls.find(hasEmailAndContinue) ||\n dialogEls.find((d) => d.querySelector('input,textarea')) ||\n null;\n if (!scope && dialogEls.length) scope = dialogEls[dialogEls.length - 1];\n const root = scope || document;\n\n // Clear the previous scan's tags so a re-rendered modal cannot be addressed\n // through a stale element.\n document.querySelectorAll('[data-ts-login]').forEach((e) => e.removeAttribute('data-ts-login'));\n\n const inputs = [...root.querySelectorAll('input,textarea')]\n .filter(vis)\n .filter((el) => lowerType(el) !== 'hidden' && !el.disabled && !el.readOnly);\n\n const pw =\n inputs.find((el) => lowerType(el) === 'password') ||\n inputs.find((el) => ['current-password', 'new-password'].includes(autocomplete(el))) ||\n null;\n\n let user =\n inputs.find((el) => autocomplete(el) === 'username') ||\n inputs.find((el) => lowerType(el) === 'email') ||\n null;\n if (!user) {\n const textish = inputs.filter((el) => ['', 'text', 'email', 'tel'].includes(lowerType(el)));\n if (pw) {\n user = textish.find((el) => (el.compareDocumentPosition(pw) & Node.DOCUMENT_POSITION_PRECEDING)) || null;\n }\n if (!user && textish.length) user = textish[0];\n }\n\n const otp =\n inputs.find((el) => autocomplete(el) === 'one-time-code') ||\n inputs.find((el) => /otp|one[- ]?time|verif|code/i.test(hintOf(el) || '')) ||\n null;\n\n // The same element can match several heuristics; one role wins.\n if (user && otp && user === otp) user = null;\n if (user && pw && user === pw) user = null;\n\n const submitRe = /sign\\s?in|log\\s?in|login|continue|next|submit|log\\s?on|enter|proceed|verify|confirm/i;\n const clickable = [...root.querySelectorAll('button,input[type=submit],input[type=button],[role=button],a')]\n .filter(vis)\n .filter((el) => el.disabled !== true && el.getAttribute('aria-disabled') !== 'true');\n let submit =\n clickable.find((el) => (el.getAttribute('type') || '').toLowerCase() === 'submit') ||\n clickable.find((el) => submitRe.test((el.innerText || el.textContent || el.value || '').trim())) ||\n clickable.find((el) => /submit/i.test(hintOf(el) || '')) ||\n null;\n\n const box = (el, hint, role) => {\n el.setAttribute('data-ts-login', role);\n const r = el.getBoundingClientRect();\n return {\n x: Math.round(r.x + r.width / 2),\n y: Math.round(r.y + r.height / 2),\n hint: hint || '',\n role: role,\n };\n };\n\n return {\n username: user && vis(user) ? box(user, hintOf(user), 'username') : null,\n password: pw && vis(pw) ? box(pw, hintOf(pw), 'password') : null,\n submit: submit ? box(submit, (submit.innerText || submit.textContent || submit.value || '').trim().slice(0, 40), 'submit') : null,\n otp: otp && vis(otp) ? box(otp, hintOf(otp), 'otp') : null,\n modal: !!scope,\n };\n})()"; export declare function findLoginFields(page: CdpPage): Promise; /** * The login phase a `waitFor {for:"loginStep"}` caller can wait for. Password * wins over OTP (a password+OTP screen is still the password step), then OTP, * then username; no fields means the step is finished. */ export declare function loginStepOf(fields: LoginFields): 'username' | 'password' | 'otp' | 'done'; /** * Observed outcome of a verified typing attempt. Lengths only, never the * value itself — the result crosses the bridge to the hub and must be safe * to log next to a run that may hold credentials. */ export interface TypeResult { ok: boolean; beforeLength: number | null; afterLength: number | null; /** Tag + label of the focused element (never its value), or null. */ focused: string | null; /** True when the focused element is contentEditable. */ contentEditable: boolean; } /** * Type text into the currently focused control and VERIFY it landed. * With `clearFirst`, the field is emptied and verified empty BEFORE the insert. * Success is an EXACT value match (never a length comparison), and a field * that cannot be read back is a FAILURE — never a silent success. The ladder: * native insert → native value setter (React-controlled inputs) → clear + * per-character key events. Returns lengths, never the value itself. */ export declare function typeTextVerified(page: CdpPage, text: string, opts?: { clearFirst?: boolean; }): Promise; /** * Fill a specific login control with a value and verify it EXACTLY. * * ALWAYS clears first (the old version only selected), verifies the field is * empty, inserts, and compares the observed value to the expected one. If the * site/autofill fights the insert, it retries with key events and finally with * the native value setter. Returns false when the value could not be made to * stick. */ export declare function fillFieldVerified(page: CdpPage, control: LoginControl, value: string): Promise; /** * Deterministic login. Clears and fills every credential field, submits, and * follows the real multi-step flow (including a modal): * * email → password * email → OTP * email → password → OTP * password → OTP * OTP only * magic link (email only — the agent opens the link; login only gets to the email step) * * It NEVER reports ok while an OTP field is visible. It returns the visible * site error on a rejection and a `phase` on every outcome, so the agent knows * where it stopped instead of improvising with raw `evaluate`. */ export declare function performLogin(page: CdpPage, opts: PerformLoginOptions): Promise; /** True when the currently focused element is a password/credential control. */ export declare function isCredentialFocused(page: CdpPage): Promise;