askrobots / dbbasic-browser
Public
A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.
danq9
site icons (favicons) in tabs, address bar suggestions and the bookmarks panel
7249579
15 hours, 50 minutes ago
History
page-tools.ts · 11.7 KB · 214 lines
| 1 | /** |
| 2 | * In-page helpers for the form and find methods. They run inside the page (as source text sent to the tab), |
| 3 | * so they are plain strings, and the only thing this module does is build them. Elements are named by short |
| 4 | * refs ("e1", "e2"…) kept in a non-enumerable registry on the page's window; a ref whose element has left the |
| 5 | * document no longer resolves, so a stale ref is an error and never a wrong click. |
| 6 | * |
| 7 | * Values that must not leave the page (passwords, card details, one-time codes, hidden fields, files) are never |
| 8 | * reported: the field is listed with `sensitive: true`, a reason, and whether it is filled, and nothing else. |
| 9 | */ |
| 10 | |
| 11 | /** Shared helpers, as source text. */ |
| 12 | const LIB = ` |
| 13 | const registry = () => { |
| 14 | let r = window.__dbbRefs; |
| 15 | if (!r) { r = { map: new Map(), back: new WeakMap(), n: 0 }; Object.defineProperty(window, "__dbbRefs", { value: r, enumerable: false }); } |
| 16 | return r; |
| 17 | }; |
| 18 | const refOf = (el) => { |
| 19 | const r = registry(); |
| 20 | let k = r.back.get(el); |
| 21 | if (!k) { k = "e" + (++r.n); r.back.set(el, k); r.map.set(k, new WeakRef(el)); } |
| 22 | return k; |
| 23 | }; |
| 24 | const byRef = (k) => { const w = registry().map.get(String(k)); const el = w && w.deref(); return el && el.isConnected ? el : null; }; |
| 25 | const clean = (s, n) => String(s == null ? "" : s).replace(/\\s+/g, " ").trim().slice(0, n || 200); |
| 26 | const visible = (el) => { |
| 27 | const r = el.getBoundingClientRect(); |
| 28 | if (!(r.width > 0 && r.height > 0)) return false; |
| 29 | const cs = getComputedStyle(el); |
| 30 | return cs.visibility !== "hidden" && cs.display !== "none"; |
| 31 | }; |
| 32 | const labelOf = (el) => { |
| 33 | const out = []; |
| 34 | if (el.labels) for (const l of el.labels) out.push(l.innerText || l.textContent); |
| 35 | const al = el.getAttribute("aria-label"); if (al) out.push(al); |
| 36 | const lb = el.getAttribute("aria-labelledby"); |
| 37 | if (lb) for (const id of lb.split(/\\s+/)) { const n = document.getElementById(id); if (n) out.push(n.innerText || n.textContent); } |
| 38 | if (!out.length && el.getAttribute("title")) out.push(el.getAttribute("title")); |
| 39 | return clean(out.join(" ")); |
| 40 | }; |
| 41 | `; |
| 42 | |
| 43 | /** The element a call names: by ref when given, else by CSS selector. Evaluates to the element or null. */ |
| 44 | export function elementExpr(p: { ref?: unknown; selector?: unknown }): string { |
| 45 | if (p.ref != null) return `(() => { ${LIB} return byRef(${JSON.stringify(String(p.ref))}); })()`; |
| 46 | return `document.querySelector(${JSON.stringify(String(p.selector))})`; |
| 47 | } |
| 48 | |
| 49 | /** Scroll an element into view and return the centre of it, in page coordinates, or null. */ |
| 50 | export function pointOf(p: { ref?: unknown; selector?: unknown }): string { |
| 51 | return `(() => { const e = ${elementExpr(p)}; if (!e) return null; e.scrollIntoView({block:"center", inline:"center"}); const r = e.getBoundingClientRect(); return { x: Math.round(r.left + r.width/2), y: Math.round(r.top + r.height/2) }; })()`; |
| 52 | } |
| 53 | |
| 54 | /** Why a field's value is not reported, or null when it may be. */ |
| 55 | const SENSITIVE = ` |
| 56 | const sensitiveReason = (el) => { |
| 57 | const type = (el.getAttribute("type") || "").toLowerCase(); |
| 58 | if (type === "password") return "password"; |
| 59 | if (type === "hidden") return "hidden"; |
| 60 | if (type === "file") return "file"; |
| 61 | const ac = (el.getAttribute("autocomplete") || "").toLowerCase(); |
| 62 | if (/(^|\\s)(cc-[a-z-]+|one-time-code|current-password|new-password)(\\s|$)/.test(ac)) return ac.includes("password") ? "password" : ac.includes("one-time") ? "one-time code" : "card"; |
| 63 | const hint = [el.name, el.id].join(" ").toLowerCase(); |
| 64 | if (/(passw|passcode|cvv|cvc|card.?num|cardnumber|ccnum|iban|routing|ssn|social.?sec|\\botp\\b|2fa|pin\\b)/.test(hint)) return "looks sensitive"; |
| 65 | return null; |
| 66 | }; |
| 67 | `; |
| 68 | |
| 69 | export const FORMS_JS = (opts: { includeHidden: boolean; limit: number }): string => `(() => { |
| 70 | ${LIB} |
| 71 | ${SENSITIVE} |
| 72 | const limit = ${Math.max(1, Math.min(500, Math.floor(opts.limit)))}; |
| 73 | const includeHidden = ${opts.includeHidden ? "true" : "false"}; |
| 74 | const forms = [...document.forms]; |
| 75 | const formIndex = (el) => { const f = el.form; if (!f) return null; const i = forms.indexOf(f); return i < 0 ? null : i; }; |
| 76 | const fields = [], buttons = []; |
| 77 | let skippedHidden = 0, truncated = false; |
| 78 | const all = document.querySelectorAll('input, select, textarea, [contenteditable=""], [contenteditable="true"], [role="textbox"], [role="combobox"], button, [role="button"]'); |
| 79 | for (const el of all) { |
| 80 | const tag = el.tagName.toLowerCase(); |
| 81 | const type = (el.getAttribute("type") || (tag === "input" ? "text" : "")).toLowerCase(); |
| 82 | const isButton = tag === "button" || el.getAttribute("role") === "button" || (tag === "input" && ["submit", "button", "reset", "image"].includes(type)); |
| 83 | const vis = visible(el); |
| 84 | if (!vis && !includeHidden && type !== "hidden") { skippedHidden++; continue; } |
| 85 | if (type === "hidden" && !includeHidden) { skippedHidden++; continue; } |
| 86 | if (fields.length + buttons.length >= limit) { truncated = true; break; } |
| 87 | if (isButton) { |
| 88 | buttons.push({ ref: refOf(el), text: clean(el.innerText || el.value || el.getAttribute("aria-label") || el.title, 120), type: type || null, form: formIndex(el), visible: vis, disabled: !!el.disabled }); |
| 89 | continue; |
| 90 | } |
| 91 | const f = { |
| 92 | ref: refOf(el), |
| 93 | kind: tag === "input" || tag === "select" || tag === "textarea" ? tag : "editable", |
| 94 | type: type || null, |
| 95 | name: el.getAttribute("name") || null, |
| 96 | id: el.id || null, |
| 97 | label: labelOf(el) || null, |
| 98 | group: (() => { const fs = el.closest("fieldset"); return fs ? clean((fs.querySelector("legend") || {}).textContent, 120) || null : null; })(), |
| 99 | placeholder: el.getAttribute("placeholder") || null, |
| 100 | autocomplete: el.getAttribute("autocomplete") || null, |
| 101 | required: !!el.required || el.getAttribute("aria-required") === "true", |
| 102 | disabled: !!el.disabled, |
| 103 | readOnly: !!el.readOnly, |
| 104 | visible: vis, |
| 105 | form: formIndex(el), |
| 106 | }; |
| 107 | const why = sensitiveReason(el); |
| 108 | if (why) { |
| 109 | f.sensitive = true; f.reason = why; |
| 110 | f.filled = tag === "select" ? !!el.value : !!(el.value || el.textContent || "").length; |
| 111 | } else if (tag === "select") { |
| 112 | f.options = [...el.options].slice(0, 100).map((o) => ({ value: o.value, label: clean(o.label || o.textContent, 80), selected: o.selected })); |
| 113 | f.value = el.multiple ? [...el.selectedOptions].map((o) => o.value) : el.value; |
| 114 | } else if (type === "checkbox" || type === "radio") { |
| 115 | f.checked = !!el.checked; f.value = el.value; |
| 116 | } else if (tag === "input" || tag === "textarea") { |
| 117 | f.value = String(el.value || "").slice(0, 500); |
| 118 | if ((el.value || "").length > 500) f.valueTruncated = true; |
| 119 | } else { |
| 120 | f.value = clean(el.textContent, 500); |
| 121 | } |
| 122 | fields.push(f); |
| 123 | } |
| 124 | const frames = [...document.querySelectorAll("iframe, frame")]; |
| 125 | let sameOrigin = 0; |
| 126 | for (const fr of frames) { try { if (fr.contentDocument) sameOrigin++; } catch {} } |
| 127 | return { |
| 128 | url: location.href, |
| 129 | title: document.title, |
| 130 | forms: forms.map((f, i) => { let a = null; try { const u = new URL(f.action, location.href); a = u.origin + u.pathname; } catch {} return { index: i, id: f.id || null, name: f.getAttribute("name") || null, method: (f.method || "get").toLowerCase(), action: a }; }), |
| 131 | fields, buttons, skippedHidden, truncated, |
| 132 | // Fields inside frames are not listed: only the top document is read. This says how many frames there are. |
| 133 | frames: { count: frames.length, sameOrigin }, |
| 134 | }; |
| 135 | })()`; |
| 136 | |
| 137 | export const FIND_JS = (q: { text?: string; label?: string; role?: string; includeHidden: boolean; limit: number }): string => `(() => { |
| 138 | ${LIB} |
| 139 | const needle = ${JSON.stringify((q.text ?? q.label ?? "").toLowerCase())}; |
| 140 | const onlyLabel = ${q.label != null && q.text == null ? "true" : "false"}; |
| 141 | const role = ${JSON.stringify((q.role ?? "").toLowerCase())}; |
| 142 | const includeHidden = ${q.includeHidden ? "true" : "false"}; |
| 143 | const limit = ${Math.max(1, Math.min(50, Math.floor(q.limit)))}; |
| 144 | const sel = 'a[href], button, input, select, textarea, summary, label, [role], [onclick], [tabindex], [contenteditable=""], [contenteditable="true"]'; |
| 145 | const roleOf = (el) => { |
| 146 | const r = el.getAttribute("role"); if (r) return r; |
| 147 | const t = el.tagName.toLowerCase(), ty = (el.getAttribute("type") || "").toLowerCase(); |
| 148 | if (t === "a") return "link"; |
| 149 | if (t === "button" || (t === "input" && ["submit", "button", "reset", "image"].includes(ty))) return "button"; |
| 150 | if (t === "select") return "combobox"; |
| 151 | if (t === "textarea" || (t === "input" && !["checkbox", "radio", "hidden"].includes(ty))) return "textbox"; |
| 152 | if (t === "input") return ty; |
| 153 | return t; |
| 154 | }; |
| 155 | const out = []; |
| 156 | let total = 0; |
| 157 | for (const el of document.querySelectorAll(sel)) { |
| 158 | const vis = visible(el); |
| 159 | if (!vis && !includeHidden) continue; |
| 160 | const rl = roleOf(el); |
| 161 | if (role && rl !== role) continue; |
| 162 | const text = clean(el.innerText || el.value || "", 120); |
| 163 | const label = labelOf(el); |
| 164 | const hay = onlyLabel ? [label] : [text, label, el.getAttribute("placeholder"), el.getAttribute("title"), el.getAttribute("name"), el.id]; |
| 165 | let score = 0; |
| 166 | if (!needle) score = 1; |
| 167 | else for (const h of hay) { const s = clean(h).toLowerCase(); if (!s) continue; if (s === needle) { score = 3; break; } if (s.startsWith(needle)) score = Math.max(score, 2); else if (s.includes(needle)) score = Math.max(score, 1); } |
| 168 | if (!score) continue; |
| 169 | total++; |
| 170 | const r = el.getBoundingClientRect(); |
| 171 | out.push({ score, ref: refOf(el), role: rl, tag: el.tagName.toLowerCase(), type: el.getAttribute("type") || null, text, label: label || null, href: el.tagName === "A" ? el.href : null, visible: vis, inViewport: r.bottom > 0 && r.right > 0 && r.top < innerHeight && r.left < innerWidth, rect: { x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.width), h: Math.round(r.height) } }); |
| 172 | } |
| 173 | out.sort((a, b) => b.score - a.score); |
| 174 | return { total, matches: out.slice(0, limit).map(({ score, ...m }) => m) }; |
| 175 | })()`; |
| 176 | |
| 177 | /** What a ref points at, so a person can be told what is about to be clicked or typed into (and so secrets are refused). */ |
| 178 | export const REF_INFO_JS = (ref: string): string => `(() => { |
| 179 | ${LIB} |
| 180 | ${SENSITIVE} |
| 181 | const el = byRef(${JSON.stringify(ref)}); |
| 182 | if (!el) return { found: false }; |
| 183 | const tag = el.tagName.toLowerCase(); |
| 184 | const type = (el.getAttribute("type") || "").toLowerCase(); |
| 185 | const inForm = !!el.form; |
| 186 | const submits = (tag === "button" && (type === "" || type === "submit") && inForm) || (tag === "input" && (type === "submit" || type === "image")); |
| 187 | return { |
| 188 | found: true, tag, type: type || null, |
| 189 | role: el.getAttribute("role") || null, |
| 190 | text: clean(el.innerText || el.value || "", 120), |
| 191 | label: labelOf(el) || null, |
| 192 | name: el.getAttribute("name") || null, |
| 193 | sensitive: sensitiveReason(el), |
| 194 | submits, |
| 195 | link: tag === "a" ? el.href : null, |
| 196 | }; |
| 197 | })()`; |
| 198 | |
| 199 | /** Choose an option of a <select> by its value or its visible words, with the events a page expects. */ |
| 200 | export const CHOOSE_JS = (ref: string, want: string): string => `(() => { |
| 201 | ${LIB} |
| 202 | const el = byRef(${JSON.stringify(ref)}); |
| 203 | if (!el) return { ok: false, why: "not-found" }; |
| 204 | if (el.tagName !== "SELECT") return { ok: false, why: "not-a-select" }; |
| 205 | const w = ${JSON.stringify(want)}.trim().toLowerCase(); |
| 206 | const opts = [...el.options]; |
| 207 | const hit = opts.find((o) => o.value.toLowerCase() === w) || opts.find((o) => clean(o.label || o.textContent).toLowerCase() === w) || opts.find((o) => clean(o.label || o.textContent).toLowerCase().includes(w)); |
| 208 | if (!hit || hit.disabled) return { ok: false, why: "no-such-option", options: opts.slice(0, 40).map((o) => clean(o.label || o.textContent, 60)) }; |
| 209 | el.focus(); |
| 210 | el.value = hit.value; |
| 211 | el.dispatchEvent(new Event("input", { bubbles: true })); |
| 212 | el.dispatchEvent(new Event("change", { bubbles: true })); |
| 213 | return { ok: true, chosen: clean(hit.label || hit.textContent, 80), value: hit.value }; |
| 214 | })()`; |