Skip to content

Stealth Chromium that passes every bot detection test. Drop-in Playwright replacement with source-level fingerprint patches. 50+ tests passed.

fix(humanize): restore get_by_* selectors and harden isolated-world reads

CloakHQ1164eca33247
diff --git a/cloakbrowser/human/__init__.py b/cloakbrowser/human/__init__.py
index 76e1c47..242dbb0 100644
--- a/cloakbrowser/human/__init__.py
+++ b/cloakbrowser/human/__init__.py
@@ -1030,10 +1030,11 @@ def patch_page(page: Any, cfg: HumanConfig, cursor: _CursorState) -> None:
human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)
cursor.x = target.x
cursor.y = target.y
- check_pointer_events(
- page, selector, box.get("targetId"), target.x, target.y,
- stealth, timeout=_remaining_ms(), force=force,
- )
+ if not force:
+ check_pointer_events(
+ page, selector, box.get("targetId"), box.get("gen"),
+ target.x, target.y, stealth, timeout=_remaining_ms(),
+ )
human_click(raw_mouse, is_input, call_cfg)
def _human_dblclick(selector: str, **kwargs: Any) -> None:
@@ -1070,10 +1071,11 @@ def patch_page(page: Any, cfg: HumanConfig, cursor: _CursorState) -> None:
human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)
cursor.x = target.x
cursor.y = target.y
- check_pointer_events(
- page, selector, box.get("targetId"), target.x, target.y,
- stealth, timeout=_remaining_ms(), force=force,
- )
+ if not force:
+ check_pointer_events(
+ page, selector, box.get("targetId"), box.get("gen"),
+ target.x, target.y, stealth, timeout=_remaining_ms(),
+ )
raw_mouse.down(click_count=2)
sleep_ms(rand(30, 60))
raw_mouse.up(click_count=2)
@@ -1112,10 +1114,11 @@ def patch_page(page: Any, cfg: HumanConfig, cursor: _CursorState) -> None:
human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)
cursor.x = target.x
cursor.y = target.y
- check_pointer_events(
- page, selector, box.get("targetId"), target.x, target.y,
- stealth, timeout=_remaining_ms(), force=force,
- )
+ if not force:
+ check_pointer_events(
+ page, selector, box.get("targetId"), box.get("gen"),
+ target.x, target.y, stealth, timeout=_remaining_ms(),
+ )
def _human_type(selector: str, text: str, **kwargs: Any) -> None:
call_cfg = merge_config(cfg, kwargs.get("human_config"))
@@ -2116,10 +2119,11 @@ def patch_page_async(page: Any, cfg: HumanConfig, cursor: _CursorState) -> None:
await async_human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)
cursor.x = target.x
cursor.y = target.y
- await async_check_pointer_events(
- page, selector, box.get("targetId"), target.x, target.y,
- stealth, timeout=_remaining_ms(), force=force,
- )
+ if not force:
+ await async_check_pointer_events(
+ page, selector, box.get("targetId"), box.get("gen"),
+ target.x, target.y, stealth, timeout=_remaining_ms(),
+ )
await async_human_click(raw_mouse, is_input, call_cfg)
async def _human_dblclick(selector: str, **kwargs: Any) -> None:
@@ -2155,10 +2159,11 @@ def patch_page_async(page: Any, cfg: HumanConfig, cursor: _CursorState) -> None:
await async_human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)
cursor.x = target.x
cursor.y = target.y
- await async_check_pointer_events(
- page, selector, box.get("targetId"), target.x, target.y,
- stealth, timeout=_remaining_ms(), force=force,
- )
+ if not force:
+ await async_check_pointer_events(
+ page, selector, box.get("targetId"), box.get("gen"),
+ target.x, target.y, stealth, timeout=_remaining_ms(),
+ )
await raw_mouse.down(click_count=2)
await async_sleep_ms(rand(30, 60))
await raw_mouse.up(click_count=2)
@@ -2196,10 +2201,11 @@ def patch_page_async(page: Any, cfg: HumanConfig, cursor: _CursorState) -> None:
await async_human_move(raw_mouse, cursor.x, cursor.y, target.x, target.y, call_cfg)
cursor.x = target.x
cursor.y = target.y
- await async_check_pointer_events(
- page, selector, box.get("targetId"), target.x, target.y,
- stealth, timeout=_remaining_ms(), force=force,
- )
+ if not force:
+ await async_check_pointer_events(
+ page, selector, box.get("targetId"), box.get("gen"),
+ target.x, target.y, stealth, timeout=_remaining_ms(),
+ )
async def _human_type(selector: str, text: str, **kwargs: Any) -> None:
call_cfg = merge_config(cfg, kwargs.get("human_config"))
diff --git a/cloakbrowser/human/actionability.py b/cloakbrowser/human/actionability.py
index 5787c32..3890fc6 100644
--- a/cloakbrowser/human/actionability.py
+++ b/cloakbrowser/human/actionability.py
@@ -249,25 +249,29 @@ def check_pointer_events(
page: Any,
selector: str,
target_id: int,
+ gen: int,
x: float,
y: float,
stealth: Any = None,
timeout: float = 5000,
- force: bool = False,
) -> None:
- """Revalidate exact identity; force skips only receives-events rejection."""
+ """Revalidate that the click point still hits the same resolved element.
+
+ Callers skip this entirely when ``force=True`` (matching Playwright, where
+ ``force`` bypasses all actionability checks).
+ """
deadline = time.monotonic() + timeout / 1000.0
attempt = 0
last_miss: Optional[str] = None
world = stealth if stealth is not None else getattr(page, "_stealth_world", None)
if world is None:
raise StealthWorldUnavailableError()
- if not isinstance(target_id, int):
+ if not isinstance(target_id, int) or not isinstance(gen, int):
raise StealthEvaluationError(selector)
while True:
status, data = eval_parsed(
- world, build_validate_js(selector, target_id, x, y)
+ world, build_validate_js(selector, target_id, gen, x, y)
)
if status == UNSUPPORTED:
raise UnsupportedHumanizeSelectorError(selector)
@@ -278,7 +282,7 @@ def check_pointer_events(
if status == EVALUATION_FAILED:
if time.monotonic() >= deadline:
raise StealthEvaluationError(selector)
- elif force or data.get("hit", False):
+ elif data.get("hit", False):
return
else:
last_miss = data.get("covering", "unknown")
diff --git a/cloakbrowser/human/actionability_async.py b/cloakbrowser/human/actionability_async.py
index 3407093..b64e7ce 100644
--- a/cloakbrowser/human/actionability_async.py
+++ b/cloakbrowser/human/actionability_async.py
@@ -159,11 +159,11 @@ async def async_check_pointer_events(
page: Any,
selector: str,
target_id: int,
+ gen: int,
x: float,
y: float,
stealth: Any = None,
timeout: float = 5000,
- force: bool = False,
) -> None:
deadline = time.monotonic() + timeout / 1000.0
attempt = 0
@@ -171,12 +171,12 @@ async def async_check_pointer_events(
world = stealth if stealth is not None else getattr(page, "_stealth_world", None)
if world is None:
raise StealthWorldUnavailableError()
- if not isinstance(target_id, int):
+ if not isinstance(target_id, int) or not isinstance(gen, int):
raise StealthEvaluationError(selector)
while True:
status, data = await async_eval_parsed(
- world, build_validate_js(selector, target_id, x, y)
+ world, build_validate_js(selector, target_id, gen, x, y)
)
if status == UNSUPPORTED:
raise UnsupportedHumanizeSelectorError(selector)
@@ -187,7 +187,7 @@ async def async_check_pointer_events(
if status == EVALUATION_FAILED:
if time.monotonic() >= deadline:
raise StealthEvaluationError(selector)
- elif force or data.get("hit", False):
+ elif data.get("hit", False):
return
else:
last_miss = data.get("covering", "unknown")
diff --git a/cloakbrowser/human/scroll.py b/cloakbrowser/human/scroll.py
index 267b954..4b15652 100644
--- a/cloakbrowser/human/scroll.py
+++ b/cloakbrowser/human/scroll.py
@@ -37,6 +37,7 @@ def _get_element_box(page: Any, selector: str, timeout: float = 30000) -> Option
if status == OK:
box = dict(data["box"])
box["targetId"] = data["targetId"]
+ box["gen"] = data["gen"]
return box
if status == NOT_FOUND:
return None
diff --git a/cloakbrowser/human/scroll_async.py b/cloakbrowser/human/scroll_async.py
index 57633da..901ea27 100644
--- a/cloakbrowser/human/scroll_async.py
+++ b/cloakbrowser/human/scroll_async.py
@@ -37,6 +37,7 @@ async def _get_element_box_async(
if status == OK:
box = dict(data["box"])
box["targetId"] = data["targetId"]
+ box["gen"] = data["gen"]
return box
if status == NOT_FOUND:
return None
diff --git a/cloakbrowser/human/stealth_dom.py b/cloakbrowser/human/stealth_dom.py
index 9c423c6..1084ca3 100644
--- a/cloakbrowser/human/stealth_dom.py
+++ b/cloakbrowser/human/stealth_dom.py
@@ -13,12 +13,19 @@ humanize layer commonly receives:
* plain CSS / ``css=`` — including the ``:has-text("...")`` pseudo
* ``text=`` engine (quoted = exact, unquoted = case-insensitive substring)
* ``xpath=`` / leading ``//``
+ * ``internal:testid=`` / ``internal:attr=`` (``get_by_test_id``,
+ ``get_by_placeholder``, ``get_by_alt_text``, ``get_by_title``)
+ * ``internal:text=`` / ``internal:label=`` (``get_by_text``, ``get_by_label``)
* a trailing ``>> nth=N`` (what ``.first`` / ``.nth(k)`` / ``.last`` append)
-Anything richer (``>>`` chaining, ``internal:*`` engines from ``get_by_*``,
-``:visible``, ``:nth-match``, layout pseudos, …) returns ``unsupported`` and the
-caller raises a typed error. Correctness and stealth win on ties: uncertain grammar
-never falls back to Playwright DOM reads.
+Anything richer returns ``unsupported`` and the caller raises a typed error:
+``>>`` chaining (so ``.filter()``, ``.and_()``, ``.or_()`` and chained locators),
+``internal:role=`` (``get_by_role`` — a faithful port needs Playwright's whole
+accessible-name algorithm), ``internal:has*``, ``internal:control=``
+(``frame_locator``), ``:visible``, ``:nth-match``, and layout pseudos.
+Correctness and stealth win on ties: uncertain grammar never falls back to
+Playwright DOM reads, because a mis-resolved element means clicking the wrong
+coordinates.
The JS builders and :func:`parse_result` are pure and shared by the sync and
async call sites; only the ``world.evaluate`` await differs.
@@ -30,7 +37,7 @@ import json
from typing import Any, Optional, Tuple
# Versioned protocol returned by the isolated-world DOM helper.
-PROTOCOL_VERSION = 1
+PROTOCOL_VERSION = 2
# Status returned to callers.
OK = "ok"
@@ -45,9 +52,23 @@ class StealthDomError(RuntimeError):
class UnsupportedHumanizeSelectorError(StealthDomError):
+ """Raised for selector grammar the isolated-world resolver cannot resolve.
+
+ The humanize layer resolves selectors inside the isolated world so page
+ scripts cannot observe the read. Grammar it cannot resolve is refused rather
+ than handed back to Playwright, whose locator predicates run in the page's
+ main world and are observable.
+ """
+
def __init__(self, selector: str):
super().__init__(
- f"Humanized selector {selector!r} is not supported by the isolated-world resolver"
+ f"Humanized selector {selector!r} is not supported by the isolated-world "
+ f"resolver. Supported: CSS, text=, xpath=, get_by_test_id, "
+ f"get_by_placeholder, get_by_alt_text, get_by_title, get_by_text, "
+ f"get_by_label, and a trailing .first/.nth()/.last. Not supported: "
+ f"get_by_role, chained locators (a >> b, .filter(), .and_(), .or_()), "
+ f"frame_locator, :visible and :nth-match. Use a CSS or text= selector "
+ f"for this action, or humanize=False to fall back to Playwright."
)
@@ -69,16 +90,23 @@ class StealthEvaluationError(StealthDomError):
_RESOLVER_BODY = r"""
const __UNS = 'UNSUPPORTED';
-const __V = 1;
+const __V = 2;
const __STATE_KEY = '__cloakHumanDomV1';
function __state(){
let s = globalThis[__STATE_KEY];
if (!s) {
- s = { ids: new WeakMap(), nextId: 1 };
+ // Element ids restart at 1 in every new world, and the world is recreated on
+ // navigation (#507), so an id alone can name a different element after a nav.
+ // The generation makes that cross-world reuse detectable as 'stale'.
+ // 11 bits of wall clock + 20 bits of randomness. The maximum is exactly
+ // Int32.MaxValue, because the .NET wrapper carries the value as an Int32.
+ s = { ids: new WeakMap(), nextId: 1,
+ gen: (Date.now() & 2047) * 1048576 + Math.floor(Math.random() * 1048576) };
Object.defineProperty(globalThis, __STATE_KEY, { value: s, configurable: false, enumerable: false });
}
return s;
}
+function __gen(){ return __state().gen; }
function __targetId(el){
const s = __state();
let id = s.ids.get(el);
@@ -244,13 +272,11 @@ function __elementText(el, cache){
continue;
} else {
if (immediate) { fragments.push(immediate); immediate = ''; }
- if (child.nodeType === 1) {
- full += __elementText(child, cache).full;
- if (child.tagName && child.tagName.toLowerCase() === 'br') full += '\n';
- }
+ if (child.nodeType === 1) full += __elementText(child, cache).full;
}
}
if (immediate) fragments.push(immediate);
+ if (el.shadowRoot) full += __elementText(el.shadowRoot, cache).full;
out = { full: full, normalized: __normWS(full), immediate: fragments };
cache.set(el, out);
return out;
@@ -288,21 +314,224 @@ function __parseTextMatcher(arg){
}
return { kind: 'lax', value: __normWS(arg).toLowerCase() };
}
-function __matchText(el, matcher, cache){
- const text = __elementText(el, cache);
+function __matchTextValue(text, matcher){
if (matcher.kind === 'regex') { matcher.regex.lastIndex = 0; return matcher.regex.test(text.full); }
+ // The public engine's exact rule compares immediate text-node runs, unlike
+ // internal:text which compares the full normalized subtree text.
if (matcher.kind === 'exact') return text.immediate.some(x => __normWS(x) === matcher.value);
return text.normalized.toLowerCase().includes(matcher.value);
}
+function __matchText(el, matcher, cache){
+ return __matchTextValue(__elementText(el, cache), matcher);
+}
+function __publicTextMatches(el, matcher, cache){
+ // Playwright's elementMatchesText for the public text= engine.
+ if (__skipText(el)) return 'none';
+ if (!__matchText(el, matcher, cache)) return 'none';
+ for (const child of el.children || []) {
+ if (__matchText(child, matcher, cache)) return 'selfAndChildren';
+ }
+ // A host whose shadow content also matches is not the smallest match. This
+ // cannot be expressed with contains(), which does not pierce shadow roots.
+ if (el.shadowRoot && __matchTextValue(__elementText(el.shadowRoot, cache), matcher))
+ return 'selfAndChildren';
+ return 'self';
+}
function __byText(arg){
const matcher = __parseTextMatcher(arg);
if (matcher === __UNS) return __UNS;
- const matches = [], cache = new Map();
- const all = __allElements();
- for (const el of all) { if (__matchText(el, matcher, cache)) matches.push(el); }
- // Playwright's text engine targets the smallest matching element: drop any
- // element that has a descendant which also matches.
- return matches.filter(el => !matches.some(o => o !== el && el.contains(o)));
+ const out = [], cache = new Map();
+ let lastMiss = null;
+ for (const el of __allElements()) {
+ // Nothing under a non-matching ancestor can match in lax mode.
+ if (matcher.kind === 'lax' && lastMiss && lastMiss.contains(el)) continue;
+ const m = __publicTextMatches(el, matcher, cache);
+ if (m === 'none') lastMiss = el;
+ // The public engine also keeps an ancestor when the match is exact.
+ if (m === 'self' || (m === 'selfAndChildren' && matcher.kind === 'exact')) out.push(el);
+ }
+ return out;
+}
+function __attrUnquote(s, i){
+ // parseAttributeSelector.readQuotedString: a backslash is dropped and the next
+ // character taken verbatim -- NOT JSON escapes, so "a\\nb" decodes to 'anb'.
+ const quote = s.charAt(i);
+ if (quote !== '"' && quote !== "'") return __UNS;
+ let out = '';
+ i++;
+ while (i < s.length && s.charAt(i) !== quote) {
+ if (s.charAt(i) === '\\') {
+ i++;
+ if (i >= s.length) return __UNS;
+ }
+ out += s.charAt(i++);
+ }
+ if (s.charAt(i) !== quote) return __UNS;
+ return { value: out, end: i + 1 };
+}
+function __parseAttrBody(body){
+ // [name="value"i] | [name="value"s] | [name=/re/flags]
+ body = body.trim();
+ if (body.charAt(0) !== '[' || body.charAt(body.length - 1) !== ']') return __UNS;
+ const inner = body.slice(1, -1);
+ const eq = inner.indexOf('=');
+ if (eq <= 0) return __UNS;
+ let name = inner.slice(0, eq).trim();
+ if (name.charAt(0) === '"' || name.charAt(0) === "'") {
+ const un = __attrUnquote(name, 0);
+ if (un === __UNS || un.end !== name.length) return __UNS;
+ name = un.value;
+ }
+ // isCSSNameChar, plus ',' for the comma-joined test-id name list. Also rejects
+ // the *= ^= $= |= ~= operators, whose extra character lands in the name.
+ if (!/^[\w\u0080-\uFFFF,-]+$/.test(name)) return __UNS;
+ const rest = inner.slice(eq + 1);
+ let j = 0;
+ while (j < rest.length && /\s/.test(rest.charAt(j))) j++;
+ if (rest.charAt(j) === '/') {
+ const end = rest.lastIndexOf('/');
+ if (end <= j) return __UNS;
+ const flags = rest.slice(end + 1).trim();
+ if (!/^[dgimsuvy]*$/.test(flags)) return __UNS;
+ try { return { name: name, regex: new RegExp(rest.slice(j + 1, end), flags), value: null, caseSensitive: true }; }
+ catch (e) { return __UNS; }
+ }
+ const un = __attrUnquote(rest, j);
+ if (un === __UNS) return __UNS;
+ let k = un.end, caseSensitive = true;
+ const flag = rest.charAt(k);
+ if (flag === 'i' || flag === 'I') { caseSensitive = false; k++; }
+ else if (flag === 's' || flag === 'S') { caseSensitive = true; k++; }
+ while (k < rest.length && /\s/.test(rest.charAt(k))) k++;
+ if (k !== rest.length) return __UNS;
+ return { name: name, regex: null, value: un.value, caseSensitive: caseSensitive };
+}
+function __byAttr(body){
+ // Serves internal:attr (placeholder/alt/title) AND internal:testid -- the
+ // attribute name comes from the selector. The 'i' flag means case-insensitive
+ // SUBSTRING, and the RAW attribute value is compared: no trim, no whitespace
+ // normalization. get_by_test_id always emits 's', so it is strict equality.
+ const parsed = __parseAttrBody(body);
+ if (parsed === __UNS) return __UNS;
+ const names = parsed.name.split(',');
+ const lower = (parsed.regex || parsed.caseSensitive) ? null : parsed.value.toLowerCase();
+ const out = [];
+ try {
+ for (const el of __allElements()) {
+ if (!el.getAttribute) continue;
+ for (const name of names) {
+ const actual = el.getAttribute(name);
+ if (actual === null || actual === undefined) continue;
+ let hit;
+ if (parsed.regex) { parsed.regex.lastIndex = 0; hit = !!String(actual).match(parsed.regex); }
+ else if (parsed.caseSensitive) hit = actual === parsed.value;
+ else hit = String(actual).toLowerCase().indexOf(lower) !== -1;
+ if (hit) { out.push(el); break; }
+ }
+ }
+ } catch (e) { return __UNS; }
+ return out;
+}
+function __parseInternalTextMatcher(arg){
+ // createTextMatcher(selector, internal=true). Playwright does not trim here.
+ if (arg.charAt(0) === '/' && arg.lastIndexOf('/') > 0) {
+ const end = arg.lastIndexOf('/');
+ try { return { kind: 'regex', regex: new RegExp(arg.slice(1, end), arg.slice(end + 1)) }; }
+ catch (e) { return __UNS; }
+ }
+ if (arg.length > 1 && arg.charAt(0) === '"') {
+ let body = null, strict = false;
+ const last = arg.charAt(arg.length - 1);
+ if (last === '"') { body = arg; strict = true; }
+ else if (arg.charAt(arg.length - 2) === '"' && (last === 's' || last === 'i')) {
+ body = arg.slice(0, -1); strict = last === 's';
+ } else return __UNS;
+ let value;
+ try { value = JSON.parse(body); } catch (e) { return __UNS; }
+ if (typeof value !== 'string') return __UNS;
+ const norm = __normWS(value);
+ return strict ? { kind: 'strict', value: norm } : { kind: 'lax', value: norm.toLowerCase() };
+ }
+ // A single-quoted body reaches unquote=JSON.parse in Playwright and throws.
+ if (arg.length > 1 && arg.charAt(0) === "'" && arg.charAt(arg.length - 1) === "'") return __UNS;
+ return { kind: 'lax', value: __normWS(arg).toLowerCase() };
+}
+function __matchInternalText(text, matcher){
+ if (matcher.kind === 'regex') { matcher.regex.lastIndex = 0; return matcher.regex.test(text.full); }
+ // strict compares the FULL normalized subtree text. The public text= engine
+ // compares immediate fragments instead (__matchText) -- genuinely different.
+ if (matcher.kind === 'strict') return text.normalized === matcher.value;
+ return text.normalized.toLowerCase().indexOf(matcher.value) !== -1;
+}
+function __internalTextMatches(el, matcher, cache){
+ if (__skipText(el)) return 'none';
+ if (!__matchInternalText(__elementText(el, cache), matcher)) return 'none';
+ // Direct children only, plus the shadow-root probe -- NOT contains() over the
+ // match set, which would drop an outer element matched only via a grandchild.
+ for (const child of el.children || []) {
+ if (__matchInternalText(__elementText(child, cache), matcher)) return 'selfAndChildren';
+ }
+ if (el.shadowRoot && __matchInternalText(__elementText(el.shadowRoot, cache), matcher)) return 'selfAndChildren';
+ return 'self';
+}
+function __byInternalText(arg){
+ const matcher = __parseInternalTextMatcher(arg);
+ if (matcher === __UNS) return __UNS;
+ const cache = new Map(), out = [];
+ let lastMiss = null;
+ for (const el of __allElements()) {
+ // lastDidNotMatchSelf: in lax mode nothing under a non-matching ancestor matches.
+ if (matcher.kind === 'lax' && lastMiss && lastMiss.contains(el)) continue;
+ const m = __internalTextMatches(el, matcher, cache);
+ if (m === 'none') lastMiss = el;
+ if (m === 'self') out.push(el);
+ }
+ return out;
+}
+function __idRefRoot(el){
+ const root = el.getRootNode ? el.getRootNode() : null;
+ return (root && typeof root.getElementById === 'function') ? root : document;
+}
+function __labelledByElements(el){
+ const ref = el.getAttribute ? el.getAttribute('aria-labelledby') : null;
+ if (ref === null || ref === undefined) return null;
+ const root = __idRefRoot(el), out = [];
+ for (const id of ref.split(/\s+/)) {
+ if (!id) continue;
+ const target = root.getElementById(id);
+ if (target && out.indexOf(target) === -1) out.push(target);
+ }
+ return out.length ? out : null;
+}
+function __elementLabels(el, cache){
+ // First non-empty source wins: aria-labelledby, then aria-label, then .labels.
+ const refs = __labelledByElements(el);
+ if (refs) return refs.map(function(x){ return __elementText(x, cache); });
+ const aria = el.getAttribute ? el.getAttribute('aria-label') : null;
+ if (aria !== null && aria !== undefined && aria.trim())
+ return [{ full: aria, normalized: __normWS(aria), immediate: [aria] }];
+ const tag = el.tagName ? el.tagName.toUpperCase() : '';
+ const nonHiddenInput = tag === 'INPUT' && String(el.type || '').toLowerCase() !== 'hidden';
+ if (nonHiddenInput || ['BUTTON','METER','OUTPUT','PROGRESS','SELECT','TEXTAREA'].indexOf(tag) !== -1) {
+ // Native .labels already resolves both for/id and a wrapping <label>.
+ const labels = el.labels;
+ if (labels) return Array.prototype.slice.call(labels).map(function(x){ return __elementText(x, cache); });
+ }
+ return [];
+}
+function __byLabel(arg){
+ const matcher = __parseInternalTextMatcher(arg);
+ if (matcher === __UNS) return __UNS;
+ const cache = new Map(), out = [];
+ try {
+ for (const el of __allElements()) {
+ const labels = __elementLabels(el, cache);
+ for (const label of labels) {
+ if (__matchInternalText(label, matcher)) { out.push(el); break; }
+ }
+ }
+ } catch (e) { return __UNS; }
+ return out;
}
function __allElements(){
if (!document.children && document.querySelectorAll)
@@ -520,9 +749,15 @@ function __resolve(sel){
const m = sel.match(/^([\s\S]*?)\s*>>\s*nth=(-?\d+)\s*$/);
if (m) { sel = m[1].trim(); nth = parseInt(m[2], 10); hasNth = true; }
if (sel.indexOf('>>') !== -1) return __UNS; // chaining we don't reimplement
- if (sel.indexOf('internal:') !== -1) return __UNS; // get_by_* engines
let list;
- if (sel.indexOf('xpath=') === 0) { list = __byXPath(sel.slice(6)); }
+ // get_by_* engines we reimplement. Anything else under internal: (role, has,
+ // has-text, and, or, chain, control, describe) stays unsupported.
+ if (sel.indexOf('internal:testid=') === 0) { list = __byAttr(sel.slice(16)); }
+ else if (sel.indexOf('internal:attr=') === 0) { list = __byAttr(sel.slice(14)); }
+ else if (sel.indexOf('internal:text=') === 0) { list = __byInternalText(sel.slice(14)); }
+ else if (sel.indexOf('internal:label=') === 0) { list = __byLabel(sel.slice(15)); }
+ else if (sel.indexOf('internal:') !== -1) return __UNS;
+ else if (sel.indexOf('xpath=') === 0) { list = __byXPath(sel.slice(6)); }
else if (sel.indexOf('//') === 0 || sel.indexOf('(//') === 0 || sel.indexOf('..') === 0) { list = __byXPath(sel); }
else if (sel.indexOf('text=') === 0) { list = __byText(sel.slice(5)); }
else {
@@ -554,6 +789,7 @@ return {
v: __V,
r: 'ok',
targetId: __targetId(__el),
+ gen: __gen(),
attached: __el.isConnected === true,
visible: __isVisible(__el),
enabled: __enabled,
@@ -565,11 +801,6 @@ return {
};
"""
-_BOX_OP = _SNAPSHOT_OP + r"""
-"""
-
-_ACTIONABLE_OP = _SNAPSHOT_OP
-
_VIEWPORT_JS = "(() => ({ width: window.innerWidth, height: window.innerHeight }))()"
@@ -601,20 +832,29 @@ def build_actionable_js(selector: str) -> str:
return build_snapshot_js(selector)
-def build_validate_js(selector: str, target_id: int, x: float, y: float) -> str:
- """Revalidate the same isolated-world element identity at a click point."""
+def build_validate_js(
+ selector: str, target_id: int, gen: int, x: float, y: float
+) -> str:
+ """Revalidate the same isolated-world element identity at a click point.
+
+ ``gen`` pins the isolated world the ``target_id`` was minted in. The world is
+ recreated on navigation and its id counter restarts at 1, so without this a
+ *different* element could answer to the same id and pass the identity check.
+ """
op = (
"const __el = __resolve(__SEL);\n"
"if (__el === 'UNSUPPORTED') return { v: __V, r: 'unsupported' };\n"
"if (!__el) return { v: __V, r: 'not_found' };\n"
+ "const __g = __gen();\n"
"const __id = __targetId(__el);\n"
- "if (__id !== " + repr(int(target_id)) + ") return { v: __V, r: 'stale', targetId: __id };\n"
- "if (__el.isConnected !== true) return { v: __V, r: 'stale', targetId: __id };\n"
+ "if (__g !== " + repr(int(gen)) + ") return { v: __V, r: 'stale', targetId: __id, gen: __g };\n"
+ "if (__id !== " + repr(int(target_id)) + ") return { v: __V, r: 'stale', targetId: __id, gen: __g };\n"
+ "if (__el.isConnected !== true) return { v: __V, r: 'stale', targetId: __id, gen: __g };\n"
"const __t = __deepElementFromPoint(" + repr(float(x)) + ", " + repr(float(y)) + ");\n"
"let __n = __t;\n"
- "while (__n) { if (__n === __el) return { v: __V, r: 'ok', targetId: __id, hit: true }; __n = __composedParent(__n); }\n"
- "if (__t && __el.contains(__t)) return { v: __V, r: 'ok', targetId: __id, hit: true };\n"
- "return { v: __V, r: 'ok', targetId: __id, hit: false, covering: __t ? (__t.tagName || 'unknown') : 'none' };\n"
+ "while (__n) { if (__n === __el) return { v: __V, r: 'ok', targetId: __id, gen: __g, hit: true }; __n = __composedParent(__n); }\n"
+ "if (__t && __el.contains(__t)) return { v: __V, r: 'ok', targetId: __id, gen: __g, hit: true };\n"
+ "return { v: __V, r: 'ok', targetId: __id, gen: __g, hit: false, covering: __t ? (__t.tagName || 'unknown') : 'none' };\n"
)
return _wrap(selector, op)
@@ -632,11 +872,11 @@ def build_pointer_js(selector: str, x: float, y: float) -> str:
"if (!__el) return { v: __V, r: 'not_found' };\n"
"const __id = __targetId(__el);\n"
"const __t = __deepElementFromPoint(" + repr(float(x)) + ", " + repr(float(y)) + ");\n"
- "if (!__t) return { v: __V, r: 'ok', targetId: __id, hit: false, covering: 'none' };\n"
+ "if (!__t) return { v: __V, r: 'ok', targetId: __id, gen: __gen(), hit: false, covering: 'none' };\n"
"let __n = __t;\n"
- "while (__n) { if (__n === __el) return { v: __V, r: 'ok', targetId: __id, hit: true }; __n = __composedParent(__n); }\n"
- "if (__el.contains(__t)) return { v: __V, r: 'ok', targetId: __id, hit: true };\n"
- "return { v: __V, r: 'ok', targetId: __id, hit: false, covering: __t.tagName || 'unknown' };\n"
+ "while (__n) { if (__n === __el) return { v: __V, r: 'ok', targetId: __id, gen: __gen(), hit: true }; __n = __composedParent(__n); }\n"
+ "if (__el.contains(__t)) return { v: __V, r: 'ok', targetId: __id, gen: __gen(), hit: true };\n"
+ "return { v: __V, r: 'ok', targetId: __id, gen: __gen(), hit: false, covering: __t.tagName || 'unknown' };\n"
)
return _wrap(selector, op)
@@ -647,13 +887,13 @@ def parse_result(raw: Any) -> Tuple[str, Optional[dict]]:
return (EVALUATION_FAILED, None)
r = raw.get("r")
if r == OK:
- if not isinstance(raw.get("targetId"), int):
+ if not isinstance(raw.get("targetId"), int) or not isinstance(raw.get("gen"), int):
return (EVALUATION_FAILED, None)
return (OK, raw)
if r == NOT_FOUND:
return (NOT_FOUND, None)
if r == STALE:
- if not isinstance(raw.get("targetId"), int):
+ if not isinstance(raw.get("targetId"), int) or not isinstance(raw.get("gen"), int):
return (EVALUATION_FAILED, None)
return (STALE, raw)
if r == UNSUPPORTED:
diff --git a/dotnet/src/CloakBrowser/Human/Actionability.cs b/dotnet/src/CloakBrowser/Human/Actionability.cs
index ad4b963..945cf12 100644
--- a/dotnet/src/CloakBrowser/Human/Actionability.cs
+++ b/dotnet/src/CloakBrowser/Human/Actionability.cs
@@ -306,37 +306,37 @@ public static class Actionability
double x,
double y,
double timeoutMs = 5000,
- IsolatedWorld? stealth = null,
- bool force = false)
+ IsolatedWorld? stealth = null)
{
if (stealth == null)
throw new StealthWorldUnavailableError();
var (status, snapshot) = await StealthDom.SnapshotAsync(stealth, selector).ConfigureAwait(false);
- int targetId = status switch
+ var resolved = status switch
{
- StealthStatus.Ok when snapshot != null => snapshot.Value.TargetId,
+ StealthStatus.Ok when snapshot != null => snapshot.Value,
StealthStatus.NotFound => throw new ElementNotAttachedError(selector),
StealthStatus.Unsupported => throw new UnsupportedHumanizeSelectorError(selector),
_ => throw new StealthEvaluationError(selector),
};
await CheckPointerEventsAsync(
- page, selector, targetId, x, y, timeoutMs, stealth, force).ConfigureAwait(false);
+ page, selector, resolved.TargetId, resolved.Gen, x, y, timeoutMs, stealth).ConfigureAwait(false);
}
/// <summary>
- /// Revalidate exact selector identity and pointer coverage after mouse movement.
- /// Force skips only coverage rejection; identity is always enforced.
+ /// Revalidate that the click point still hits the same resolved element.
+ /// Callers skip this entirely when force is set (matching Playwright, where
+ /// force bypasses all actionability checks).
/// </summary>
public static async Task CheckPointerEventsAsync(
IPage page,
string selector,
int targetId,
+ int gen,
double x,
double y,
double timeoutMs = 5000,
- IsolatedWorld? stealth = null,
- bool force = false)
+ IsolatedWorld? stealth = null)
{
if (stealth == null)
throw new StealthWorldUnavailableError();
@@ -347,7 +347,7 @@ public static class Actionability
while (true)
{
var (status, hit, covering, _) = await StealthDom.ValidateAsync(
- stealth, selector, targetId, x, y).ConfigureAwait(false);
+ stealth, selector, targetId, gen, x, y).ConfigureAwait(false);
if (status == StealthStatus.Unsupported)
throw new UnsupportedHumanizeSelectorError(selector);
@@ -360,7 +360,7 @@ public static class Actionability
if (NowMs() >= deadline)
throw new StealthEvaluationError(selector);
}
- else if (status == StealthStatus.Ok && (force || hit))
+ else if (status == StealthStatus.Ok && hit)
{
return;
}
diff --git a/dotnet/src/CloakBrowser/Human/HumanPage.cs b/dotnet/src/CloakBrowser/Human/HumanPage.cs
index b5799aa..ba63e0d 100644
--- a/dotnet/src/CloakBrowser/Human/HumanPage.cs
+++ b/dotnet/src/CloakBrowser/Human/HumanPage.cs
@@ -197,11 +197,13 @@ public sealed class HumanPage
}
private async Task CheckPointerEventsWorldAsync(
- string selector, int targetId, double x, double y, double timeoutMs, bool force)
+ string selector, int targetId, int gen, double x, double y, double timeoutMs, bool force)
{
+ if (force)
+ return;
var world = await GetStealthRequiredAsync().ConfigureAwait(false);
await Actionability.CheckPointerEventsAsync(
- _page, selector, targetId, x, y, timeoutMs, world, force).ConfigureAwait(false);
+ _page, selector, targetId, gen, x, y, timeoutMs, world).ConfigureAwait(false);
}
// -----------------------------------------------------------------------
@@ -263,10 +265,8 @@ public sealed class HumanPage
_rawMouse, _cursor.X, _cursor.Y, target.X, target.Y, callCfg).ConfigureAwait(false);
_cursor.X = target.X;
_cursor.Y = target.Y;
- // Identity is always revalidated after movement and before mouse-down.
- // force skips only coverage rejection, never exact-target validation.
await CheckPointerEventsWorldAsync(
- selector, snapshot.TargetId, target.X, target.Y,
+ selector, snapshot.TargetId, snapshot.Gen, target.X, target.Y,
RemainingMs(deadline), force).ConfigureAwait(false);
await HumanMouse.HumanClickAsync(_rawMouse, snapshot.IsInput, callCfg).ConfigureAwait(false);
}
@@ -316,7 +316,7 @@ public sealed class HumanPage
_cursor.X = target.X;
_cursor.Y = target.Y;
await CheckPointerEventsWorldAsync(
- selector, snapshot.TargetId, target.X, target.Y,
+ selector, snapshot.TargetId, snapshot.Gen, target.X, target.Y,
RemainingMs(deadline), force).ConfigureAwait(false);
// Two presses for a double-click via Playwright IMouse click count.
await _page.Mouse.DownAsync(new MouseDownOptions { ClickCount = 2 }).ConfigureAwait(false);
@@ -372,7 +372,7 @@ public sealed class HumanPage
_cursor.X = target.X;
_cursor.Y = target.Y;
await CheckPointerEventsWorldAsync(
- selector, snapshot.TargetId, target.X, target.Y,
+ selector, snapshot.TargetId, snapshot.Gen, target.X, target.Y,
RemainingMs(deadline), force).ConfigureAwait(false);
}
diff --git a/dotnet/src/CloakBrowser/Human/StealthDom.cs b/dotnet/src/CloakBrowser/Human/StealthDom.cs
index 6371f09..1316534 100644
--- a/dotnet/src/CloakBrowser/Human/StealthDom.cs
+++ b/dotnet/src/CloakBrowser/Human/StealthDom.cs
@@ -5,11 +5,11 @@ using System.Threading.Tasks;
namespace CloakBrowser.Human;
public enum StealthStatus { Ok, NotFound, Unsupported, Stale, EvaluationFailed }
public class StealthDomError : Exception { public StealthDomError(string m):base(m){} }
-public sealed class UnsupportedHumanizeSelectorError : StealthDomError { public UnsupportedHumanizeSelectorError(string s):base($"Humanized selector '{s}' is not supported by the isolated-world resolver"){} }
+public sealed class UnsupportedHumanizeSelectorError : StealthDomError { public UnsupportedHumanizeSelectorError(string s):base($"Humanized selector '{s}' is not supported by the isolated-world resolver. Supported: CSS, text=, xpath=, GetByTestId, GetByPlaceholder, GetByAltText, GetByTitle, GetByText, GetByLabel, and a trailing First/Nth/Last. Not supported: GetByRole, chained locators (a >> b, Filter, And, Or), FrameLocator, :visible and :nth-match. Use a CSS or text= selector for this action, or disable humanize to fall back to Playwright."){} }
public sealed class StealthWorldUnavailableError : StealthDomError { public StealthWorldUnavailableError():base("Humanized DOM read requires an active isolated world"){} }
public sealed class StealthEvaluationError : StealthDomError { public StealthEvaluationError(string s):base($"Isolated-world DOM evaluation failed for '{s}'"){} }
-internal readonly record struct StealthSnapshot(int TargetId,bool Attached,bool Visible,bool Enabled,bool Editable,bool IsInput,bool Focused,bool? Checked,BoundingBox? Box);
-internal readonly record struct StealthTargetBox(BoundingBox Box,int TargetId);
+internal readonly record struct StealthSnapshot(int TargetId,int Gen,bool Attached,bool Visible,bool Enabled,bool Editable,bool IsInput,bool Focused,bool? Checked,BoundingBox? Box);
+internal readonly record struct StealthTargetBox(BoundingBox Box,int TargetId,int Gen);
internal readonly record struct StealthBoxRead(StealthStatus Status,StealthTargetBox? Target)
{
public BoundingBox? Box => Target?.Box;
@@ -23,18 +23,24 @@ internal readonly record struct StealthActionableRead(StealthStatus Status,Steal
internal readonly record struct StealthValidateRead(StealthStatus Status,bool Hit,string Covering,int? CurrentTargetId);
internal static class StealthDom {
private const string ResolverBody = """
-
const __UNS = 'UNSUPPORTED';
-const __V = 1;
+const __V = 2;
const __STATE_KEY = '__cloakHumanDomV1';
function __state(){
let s = globalThis[__STATE_KEY];
if (!s) {
- s = { ids: new WeakMap(), nextId: 1 };
+ // Element ids restart at 1 in every new world, and the world is recreated on
+ // navigation (#507), so an id alone can name a different element after a nav.
+ // The generation makes that cross-world reuse detectable as 'stale'.
+ // 11 bits of wall clock + 20 bits of randomness. The maximum is exactly
+ // Int32.MaxValue, because the .NET wrapper carries the value as an Int32.
+ s = { ids: new WeakMap(), nextId: 1,
+ gen: (Date.now() & 2047) * 1048576 + Math.floor(Math.random() * 1048576) };
Object.defineProperty(globalThis, __STATE_KEY, { value: s, configurable: false, enumerable: false });
}
return s;
}
+function __gen(){ return __state().gen; }
function __targetId(el){
const s = __state();
let id = s.ids.get(el);
@@ -200,13 +206,11 @@ function __elementText(el, cache){
continue;
} else {
if (immediate) { fragments.push(immediate); immediate = ''; }
- if (child.nodeType === 1) {
- full += __elementText(child, cache).full;
- if (child.tagName && child.tagName.toLowerCase() === 'br') full += '\n';
- }
+ if (child.nodeType === 1) full += __elementText(child, cache).full;
}
}
if (immediate) fragments.push(immediate);
+ if (el.shadowRoot) full += __elementText(el.shadowRoot, cache).full;
out = { full: full, normalized: __normWS(full), immediate: fragments };
cache.set(el, out);
return out;
@@ -244,21 +248,224 @@ function __parseTextMatcher(arg){
}
return { kind: 'lax', value: __normWS(arg).toLowerCase() };
}
-function __matchText(el, matcher, cache){
- const text = __elementText(el, cache);
+function __matchTextValue(text, matcher){
if (matcher.kind === 'regex') { matcher.regex.lastIndex = 0; return matcher.regex.test(text.full); }
+ // The public engine's exact rule compares immediate text-node runs, unlike
+ // internal:text which compares the full normalized subtree text.
if (matcher.kind === 'exact') return text.immediate.some(x => __normWS(x) === matcher.value);
return text.normalized.toLowerCase().includes(matcher.value);
}
+function __matchText(el, matcher, cache){
+ return __matchTextValue(__elementText(el, cache), matcher);
+}
+function __publicTextMatches(el, matcher, cache){
+ // Playwright's elementMatchesText for the public text= engine.
+ if (__skipText(el)) return 'none';
+ if (!__matchText(el, matcher, cache)) return 'none';
+ for (const child of el.children || []) {
+ if (__matchText(child, matcher, cache)) return 'selfAndChildren';
+ }
+ // A host whose shadow content also matches is not the smallest match. This
+ // cannot be expressed with contains(), which does not pierce shadow roots.
+ if (el.shadowRoot && __matchTextValue(__elementText(el.shadowRoot, cache), matcher))
+ return 'selfAndChildren';
+ return 'self';
+}
function __byText(arg){
const matcher = __parseTextMatcher(arg);
if (matcher === __UNS) return __UNS;
- const matches = [], cache = new Map();
- const all = __allElements();
- for (const el of all) { if (__matchText(el, matcher, cache)) matches.push(el); }
- // Playwright's text engine targets the smallest matching element: drop any
- // element that has a descendant which also matches.
- return matches.filter(el => !matches.some(o => o !== el && el.contains(o)));
+ const out = [], cache = new Map();
+ let lastMiss = null;
+ for (const el of __allElements()) {
+ // Nothing under a non-matching ancestor can match in lax mode.
+ if (matcher.kind === 'lax' && lastMiss && lastMiss.contains(el)) continue;
+ const m = __publicTextMatches(el, matcher, cache);
+ if (m === 'none') lastMiss = el;
+ // The public engine also keeps an ancestor when the match is exact.
+ if (m === 'self' || (m === 'selfAndChildren' && matcher.kind === 'exact')) out.push(el);
+ }
+ return out;
+}
+function __attrUnquote(s, i){
+ // parseAttributeSelector.readQuotedString: a backslash is dropped and the next
+ // character taken verbatim -- NOT JSON escapes, so "a\\nb" decodes to 'anb'.
+ const quote = s.charAt(i);
+ if (quote !== '"' && quote !== "'") return __UNS;
+ let out = '';
+ i++;
+ while (i < s.length && s.charAt(i) !== quote) {
+ if (s.charAt(i) === '\\') {
+ i++;
+ if (i >= s.length) return __UNS;
+ }
+ out += s.charAt(i++);
+ }
+ if (s.charAt(i) !== quote) return __UNS;
+ return { value: out, end: i + 1 };
+}
+function __parseAttrBody(body){
+ // [name="value"i] | [name="value"s] | [name=/re/flags]
+ body = body.trim();
+ if (body.charAt(0) !== '[' || body.charAt(body.length - 1) !== ']') return __UNS;
+ const inner = body.slice(1, -1);
+ const eq = inner.indexOf('=');
+ if (eq <= 0) return __UNS;
+ let name = inner.slice(0, eq).trim();
+ if (name.charAt(0) === '"' || name.charAt(0) === "'") {
+ const un = __attrUnquote(name, 0);
+ if (un === __UNS || un.end !== name.length) return __UNS;
+ name = un.value;
+ }
+ // isCSSNameChar, plus ',' for the comma-joined test-id name list. Also rejects
+ // the *= ^= $= |= ~= operators, whose extra character lands in the name.
+ if (!/^[\w\u0080-\uFFFF,-]+$/.test(name)) return __UNS;
+ const rest = inner.slice(eq + 1);
+ let j = 0;
+ while (j < rest.length && /\s/.test(rest.charAt(j))) j++;
+ if (rest.charAt(j) === '/') {
+ const end = rest.lastIndexOf('/');
+ if (end <= j) return __UNS;
+ const flags = rest.slice(end + 1).trim();
+ if (!/^[dgimsuvy]*$/.test(flags)) return __UNS;
+ try { return { name: name, regex: new RegExp(rest.slice(j + 1, end), flags), value: null, caseSensitive: true }; }
+ catch (e) { return __UNS; }
+ }
+ const un = __attrUnquote(rest, j);
+ if (un === __UNS) return __UNS;
+ let k = un.end, caseSensitive = true;
+ const flag = rest.charAt(k);
+ if (flag === 'i' || flag === 'I') { caseSensitive = false; k++; }
+ else if (flag === 's' || flag === 'S') { caseSensitive = true; k++; }
+ while (k < rest.length && /\s/.test(rest.charAt(k))) k++;
+ if (k !== rest.length) return __UNS;
+ return { name: name, regex: null, value: un.value, caseSensitive: caseSensitive };
+}
+function __byAttr(body){
+ // Serves internal:attr (placeholder/alt/title) AND internal:testid -- the
+ // attribute name comes from the selector. The 'i' flag means case-insensitive
+ // SUBSTRING, and the RAW attribute value is compared: no trim, no whitespace
+ // normalization. get_by_test_id always emits 's', so it is strict equality.
+ const parsed = __parseAttrBody(body);
+ if (parsed === __UNS) return __UNS;
+ const names = parsed.name.split(',');
+ const lower = (parsed.regex || parsed.caseSensitive) ? null : parsed.value.toLowerCase();
+ const out = [];
+ try {
+ for (const el of __allElements()) {
+ if (!el.getAttribute) continue;
+ for (const name of names) {
+ const actual = el.getAttribute(name);
+ if (actual === null || actual === undefined) continue;
+ let hit;
+ if (parsed.regex) { parsed.regex.lastIndex = 0; hit = !!String(actual).match(parsed.regex); }
+ else if (parsed.caseSensitive) hit = actual === parsed.value;
+ else hit = String(actual).toLowerCase().indexOf(lower) !== -1;
+ if (hit) { out.push(el); break; }
+ }
+ }
+ } catch (e) { return __UNS; }
+ return out;
+}
+function __parseInternalTextMatcher(arg){
+ // createTextMatcher(selector, internal=true). Playwright does not trim here.
+ if (arg.charAt(0) === '/' && arg.lastIndexOf('/') > 0) {
+ const end = arg.lastIndexOf('/');
+ try { return { kind: 'regex', regex: new RegExp(arg.slice(1, end), arg.slice(end + 1)) }; }
+ catch (e) { return __UNS; }
+ }
+ if (arg.length > 1 && arg.charAt(0) === '"') {
+ let body = null, strict = false;
+ const last = arg.charAt(arg.length - 1);
+ if (last === '"') { body = arg; strict = true; }
+ else if (arg.charAt(arg.length - 2) === '"' && (last === 's' || last === 'i')) {
+ body = arg.slice(0, -1); strict = last === 's';
+ } else return __UNS;
+ let value;
+ try { value = JSON.parse(body); } catch (e) { return __UNS; }
+ if (typeof value !== 'string') return __UNS;
+ const norm = __normWS(value);
+ return strict ? { kind: 'strict', value: norm } : { kind: 'lax', value: norm.toLowerCase() };
+ }
+ // A single-quoted body reaches unquote=JSON.parse in Playwright and throws.
+ if (arg.length > 1 && arg.charAt(0) === "'" && arg.charAt(arg.length - 1) === "'") return __UNS;
+ return { kind: 'lax', value: __normWS(arg).toLowerCase() };
+}
+function __matchInternalText(text, matcher){
+ if (matcher.kind === 'regex') { matcher.regex.lastIndex = 0; return matcher.regex.test(text.full); }
+ // strict compares the FULL normalized subtree text. The public text= engine
+ // compares immediate fragments instead (__matchText) -- genuinely different.
+ if (matcher.kind === 'strict') return text.normalized === matcher.value;
+ return text.normalized.toLowerCase().indexOf(matcher.value) !== -1;
+}
+function __internalTextMatches(el, matcher, cache){
+ if (__skipText(el)) return 'none';
+ if (!__matchInternalText(__elementText(el, cache), matcher)) return 'none';
+ // Direct children only, plus the shadow-root probe -- NOT contains() over the
+ // match set, which would drop an outer element matched only via a grandchild.
+ for (const child of el.children || []) {
+ if (__matchInternalText(__elementText(child, cache), matcher)) return 'selfAndChildren';
+ }
+ if (el.shadowRoot && __matchInternalText(__elementText(el.shadowRoot, cache), matcher)) return 'selfAndChildren';
+ return 'self';
+}
+function __byInternalText(arg){
+ const matcher = __parseInternalTextMatcher(arg);
+ if (matcher === __UNS) return __UNS;
+ const cache = new Map(), out = [];
+ let lastMiss = null;
+ for (const el of __allElements()) {
+ // lastDidNotMatchSelf: in lax mode nothing under a non-matching ancestor matches.
+ if (matcher.kind === 'lax' && lastMiss && lastMiss.contains(el)) continue;
+ const m = __internalTextMatches(el, matcher, cache);
+ if (m === 'none') lastMiss = el;
+ if (m === 'self') out.push(el);
+ }
+ return out;
+}
+function __idRefRoot(el){
+ const root = el.getRootNode ? el.getRootNode() : null;
+ return (root && typeof root.getElementById === 'function') ? root : document;
+}
+function __labelledByElements(el){
+ const ref = el.getAttribute ? el.getAttribute('aria-labelledby') : null;
+ if (ref === null || ref === undefined) return null;
+ const root = __idRefRoot(el), out = [];
+ for (const id of ref.split(/\s+/)) {
+ if (!id) continue;
+ const target = root.getElementById(id);
+ if (target && out.indexOf(target) === -1) out.push(target);
+ }
+ return out.length ? out : null;
+}
+function __elementLabels(el, cache){
+ // First non-empty source wins: aria-labelledby, then aria-label, then .labels.
+ const refs = __labelledByElements(el);
+ if (refs) return refs.map(function(x){ return __elementText(x, cache); });
+ const aria = el.getAttribute ? el.getAttribute('aria-label') : null;
+ if (aria !== null && aria !== undefined && aria.trim())
+ return [{ full: aria, normalized: __normWS(aria), immediate: [aria] }];
+ const tag = el.tagName ? el.tagName.toUpperCase() : '';
+ const nonHiddenInput = tag === 'INPUT' && String(el.type || '').toLowerCase() !== 'hidden';
+ if (nonHiddenInput || ['BUTTON','METER','OUTPUT','PROGRESS','SELECT','TEXTAREA'].indexOf(tag) !== -1) {
+ // Native .labels already resolves both for/id and a wrapping <label>.
+ const labels = el.labels;
+ if (labels) return Array.prototype.slice.call(labels).map(function(x){ return __elementText(x, cache); });
+ }
+ return [];
+}
+function __byLabel(arg){
+ const matcher = __parseInternalTextMatcher(arg);
+ if (matcher === __UNS) return __UNS;
+ const cache = new Map(), out = [];
+ try {
+ for (const el of __allElements()) {
+ const labels = __elementLabels(el, cache);
+ for (const label of labels) {
+ if (__matchInternalText(label, matcher)) { out.push(el); break; }
+ }
+ }
+ } catch (e) { return __UNS; }
+ return out;
}
function __allElements(){
if (!document.children && document.querySelectorAll)
@@ -476,9 +683,15 @@ function __resolve(sel){
const m = sel.match(/^([\s\S]*?)\s*>>\s*nth=(-?\d+)\s*$/);
if (m) { sel = m[1].trim(); nth = parseInt(m[2], 10); hasNth = true; }
if (sel.indexOf('>>') !== -1) return __UNS; // chaining we don't reimplement
- if (sel.indexOf('internal:') !== -1) return __UNS; // get_by_* engines
let list;
- if (sel.indexOf('xpath=') === 0) { list = __byXPath(sel.slice(6)); }
+ // get_by_* engines we reimplement. Anything else under internal: (role, has,
+ // has-text, and, or, chain, control, describe) stays unsupported.
+ if (sel.indexOf('internal:testid=') === 0) { list = __byAttr(sel.slice(16)); }
+ else if (sel.indexOf('internal:attr=') === 0) { list = __byAttr(sel.slice(14)); }
+ else if (sel.indexOf('internal:text=') === 0) { list = __byInternalText(sel.slice(14)); }
+ else if (sel.indexOf('internal:label=') === 0) { list = __byLabel(sel.slice(15)); }
+ else if (sel.indexOf('internal:') !== -1) return __UNS;
+ else if (sel.indexOf('xpath=') === 0) { list = __byXPath(sel.slice(6)); }
else if (sel.indexOf('//') === 0 || sel.indexOf('(//') === 0 || sel.indexOf('..') === 0) { list = __byXPath(sel); }
else if (sel.indexOf('text=') === 0) { list = __byText(sel.slice(5)); }
else {
@@ -493,18 +706,18 @@ function __resolve(sel){
}
""";
private const string SnapshotOp = """
-const __el=__resolve(__SEL);if(__el==='UNSUPPORTED')return {v:__V,r:'unsupported'};if(!__el)return {v:__V,r:'not_found'};const __box=__visBox(__el),__hasBox=__box!==null,__tag=__el.tagName.toLowerCase(),__enabled=__isEnabled(__el),__editable=__isEditable(__el,__enabled);return {v:__V,r:'ok',targetId:__targetId(__el),attached:__el.isConnected===true,visible:__isVisible(__el),enabled:__enabled,editable:__editable,isInput:__tag==='input'||__tag==='textarea'||__el.isContentEditable===true,focused:__deepActiveElement()===__el,checked:typeof __el.checked==='boolean'?__el.checked:null,box:__box};
+const __el=__resolve(__SEL);if(__el==='UNSUPPORTED')return {v:__V,r:'unsupported'};if(!__el)return {v:__V,r:'not_found'};const __box=__visBox(__el),__hasBox=__box!==null,__tag=__el.tagName.toLowerCase(),__enabled=__isEnabled(__el),__editable=__isEditable(__el,__enabled);return {v:__V,r:'ok',targetId:__targetId(__el),gen:__gen(),attached:__el.isConnected===true,visible:__isVisible(__el),enabled:__enabled,editable:__editable,isInput:__tag==='input'||__tag==='textarea'||__el.isContentEditable===true,focused:__deepActiveElement()===__el,checked:typeof __el.checked==='boolean'?__el.checked:null,box:__box};
""";
public const string ViewportJs="(() => ({ width: window.innerWidth, height: window.innerHeight }))()";
private static string Wrap(string s,string op)=>"(() => {\nconst __SEL = "+IsolatedWorld.JsonEncode(s)+";\n"+ResolverBody+"\n"+op+"\n})()";
public static string BuildSnapshotJs(string s)=>Wrap(s,SnapshotOp); public static string BuildBoxJs(string s)=>Wrap(s,SnapshotOp.Replace("r:'ok'","r:__hasBox?'ok':'not_found'",StringComparison.Ordinal)); public static string BuildActionableJs(string s)=>BuildSnapshotJs(s);
-private static string Pointer(string s,int id,double x,double y,bool validate){var c=validate?"if(__id!=="+id.ToString(CultureInfo.InvariantCulture)+")return {v:__V,r:'stale',targetId:__id};if(__el.isConnected!==true)return {v:__V,r:'stale',targetId:__id};":"";return Wrap(s,"const __el=__resolve(__SEL);if(__el==='UNSUPPORTED')return {v:__V,r:'unsupported'};if(!__el)return {v:__V,r:'not_found'};const __id=__targetId(__el);"+c+"const __t=__deepElementFromPoint("+x.ToString(CultureInfo.InvariantCulture)+", "+y.ToString(CultureInfo.InvariantCulture)+");let __n=__t;while(__n){if(__n===__el)return {v:__V,r:'ok',targetId:__id,hit:true};__n=__composedParent(__n);}if(__t&&__el.contains(__t))return {v:__V,r:'ok',targetId:__id,hit:true};return {v:__V,r:'ok',targetId:__id,hit:false,covering:__t?(__t.tagName||'unknown'):'none'};");} public static string BuildValidateJs(string s,int id,double x,double y)=>Pointer(s,id,x,y,true); public static string BuildPointerJs(string s,double x,double y)=>Pointer(s,0,x,y,false);
+private static string Pointer(string s,int id,int gen,double x,double y,bool validate){var c=validate?"if(__g!=="+gen.ToString(CultureInfo.InvariantCulture)+")return {v:__V,r:'stale',targetId:__id,gen:__g};if(__id!=="+id.ToString(CultureInfo.InvariantCulture)+")return {v:__V,r:'stale',targetId:__id,gen:__g};if(__el.isConnected!==true)return {v:__V,r:'stale',targetId:__id,gen:__g};":"";return Wrap(s,"const __el=__resolve(__SEL);if(__el==='UNSUPPORTED')return {v:__V,r:'unsupported'};if(!__el)return {v:__V,r:'not_found'};const __g=__gen();const __id=__targetId(__el);"+c+"const __t=__deepElementFromPoint("+x.ToString(CultureInfo.InvariantCulture)+", "+y.ToString(CultureInfo.InvariantCulture)+");let __n=__t;while(__n){if(__n===__el)return {v:__V,r:'ok',targetId:__id,gen:__g,hit:true};__n=__composedParent(__n);}if(__t&&__el.contains(__t))return {v:__V,r:'ok',targetId:__id,gen:__g,hit:true};return {v:__V,r:'ok',targetId:__id,gen:__g,hit:false,covering:__t?(__t.tagName||'unknown'):'none'};");} public static string BuildValidateJs(string s,int id,int gen,double x,double y)=>Pointer(s,id,gen,x,y,true); public static string BuildPointerJs(string s,double x,double y)=>Pointer(s,0,0,x,y,false);
internal static (StealthStatus Status, JsonElement? Data) ParseResult(JsonElement? raw)
{
if (raw is not { ValueKind: JsonValueKind.Object } data
|| !data.TryGetProperty("v", out var version)
|| !version.TryGetInt32(out var versionNumber)
- || versionNumber != 1
+ || versionNumber != 2
|| !data.TryGetProperty("r", out var result)
|| result.ValueKind != JsonValueKind.String)
return (StealthStatus.EvaluationFailed, null);
@@ -520,7 +733,10 @@ internal static (StealthStatus Status, JsonElement? Data) ParseResult(JsonElemen
if ((status is StealthStatus.Ok or StealthStatus.Stale)
&& (!data.TryGetProperty("targetId", out var targetId)
|| targetId.ValueKind != JsonValueKind.Number
- || !targetId.TryGetInt32(out _)))
+ || !targetId.TryGetInt32(out _)
+ || !data.TryGetProperty("gen", out var generation)
+ || generation.ValueKind != JsonValueKind.Number
+ || !generation.TryGetInt32(out _)))
return (StealthStatus.EvaluationFailed, null);
return (status, status is StealthStatus.Ok or StealthStatus.Stale ? data : null);
@@ -542,9 +758,9 @@ private static bool B(JsonElement data, string name, out bool value)
return true;
}
-private static bool Snap(JsonElement d,out StealthSnapshot? s){s=null;if(!d.TryGetProperty("targetId",out var i)||!i.TryGetInt32(out var id)||!B(d,"attached",out var a)||!B(d,"visible",out var v)||!B(d,"enabled",out var e)||!B(d,"editable",out var ed)||!B(d,"isInput",out var inp)||!B(d,"focused",out var f)||!d.TryGetProperty("checked",out var ch)||ch.ValueKind is not(JsonValueKind.Null or JsonValueKind.True or JsonValueKind.False)||!d.TryGetProperty("box",out var z))return false;BoundingBox? box=null;if(z.ValueKind!=JsonValueKind.Null){if(z.ValueKind!=JsonValueKind.Object||!z.TryGetProperty("x",out var x)||!z.TryGetProperty("y",out var y)||!z.TryGetProperty("width",out var w)||!z.TryGetProperty("height",out var h)||x.ValueKind!=JsonValueKind.Number||y.ValueKind!=JsonValueKind.Number||w.ValueKind!=JsonValueKind.Number||h.ValueKind!=JsonValueKind.Number)return false;box=new(x.GetDouble(),y.GetDouble(),w.GetDouble(),h.GetDouble());}s=new(id,a,v,e,ed,inp,f,ch.ValueKind==JsonValueKind.Null?null:ch.GetBoolean(),box);return true;}
-public static async Task<(StealthStatus Status,StealthSnapshot? Snapshot)> SnapshotAsync(IsolatedWorld w,string s){var(r,d)=await Eval(w,BuildSnapshotJs(s));return r==StealthStatus.Ok&&Snap(d!.Value,out var p)?(r,p):r==StealthStatus.Ok?(StealthStatus.EvaluationFailed,null):(r,null);} public static async Task<StealthBoxRead> BoxAsync(IsolatedWorld w,string s){var(r,d)=await Eval(w,BuildBoxJs(s));return r==StealthStatus.Ok&&Snap(d!.Value,out var p)&&p!.Value.Box != null?new(r,new StealthTargetBox(p.Value.Box.Value,p.Value.TargetId)):new(r==StealthStatus.Ok?StealthStatus.EvaluationFailed:r,null);} public static async Task<StealthActionableRead> ActionableAsync(IsolatedWorld w,string s){var r=await SnapshotAsync(w,s);return new(r.Status,r.Snapshot);}
+private static bool Snap(JsonElement d,out StealthSnapshot? s){s=null;if(!d.TryGetProperty("targetId",out var i)||!i.TryGetInt32(out var id)||!d.TryGetProperty("gen",out var gj)||!gj.TryGetInt32(out var gen)||!B(d,"attached",out var a)||!B(d,"visible",out var v)||!B(d,"enabled",out var e)||!B(d,"editable",out var ed)||!B(d,"isInput",out var inp)||!B(d,"focused",out var f)||!d.TryGetProperty("checked",out var ch)||ch.ValueKind is not(JsonValueKind.Null or JsonValueKind.True or JsonValueKind.False)||!d.TryGetProperty("box",out var z))return false;BoundingBox? box=null;if(z.ValueKind!=JsonValueKind.Null){if(z.ValueKind!=JsonValueKind.Object||!z.TryGetProperty("x",out var x)||!z.TryGetProperty("y",out var y)||!z.TryGetProperty("width",out var w)||!z.TryGetProperty("height",out var h)||x.ValueKind!=JsonValueKind.Number||y.ValueKind!=JsonValueKind.Number||w.ValueKind!=JsonValueKind.Number||h.ValueKind!=JsonValueKind.Number)return false;box=new(x.GetDouble(),y.GetDouble(),w.GetDouble(),h.GetDouble());}s=new(id,gen,a,v,e,ed,inp,f,ch.ValueKind==JsonValueKind.Null?null:ch.GetBoolean(),box);return true;}
+public static async Task<(StealthStatus Status,StealthSnapshot? Snapshot)> SnapshotAsync(IsolatedWorld w,string s){var(r,d)=await Eval(w,BuildSnapshotJs(s));return r==StealthStatus.Ok&&Snap(d!.Value,out var p)?(r,p):r==StealthStatus.Ok?(StealthStatus.EvaluationFailed,null):(r,null);} public static async Task<StealthBoxRead> BoxAsync(IsolatedWorld w,string s){var(r,d)=await Eval(w,BuildBoxJs(s));return r==StealthStatus.Ok&&Snap(d!.Value,out var p)&&p!.Value.Box != null?new(r,new StealthTargetBox(p.Value.Box.Value,p.Value.TargetId,p.Value.Gen)):new(r==StealthStatus.Ok?StealthStatus.EvaluationFailed:r,null);} public static async Task<StealthActionableRead> ActionableAsync(IsolatedWorld w,string s){var r=await SnapshotAsync(w,s);return new(r.Status,r.Snapshot);}
public static async Task<(StealthStatus Status,bool Value)> IsInputAsync(IsolatedWorld w,string s){var r=await SnapshotAsync(w,s);return(r.Status,r.Snapshot?.IsInput??false);} public static async Task<(StealthStatus Status,bool Value)> IsFocusedAsync(IsolatedWorld w,string s){var r=await SnapshotAsync(w,s);return(r.Status,r.Snapshot?.Focused??false);} public static async Task<(StealthStatus Status,bool Value)> IsCheckedAsync(IsolatedWorld w,string s){var r=await SnapshotAsync(w,s);return(r.Status,r.Snapshot?.Checked??false);}
-public static async Task<StealthValidateRead> ValidateAsync(IsolatedWorld w,string s,int id,double x,double y){var(r,d)=await Eval(w,BuildValidateJs(s,id,x,y));if(r is not(StealthStatus.Ok or StealthStatus.Stale))return new(r,false,"unknown",null);var e=d!.Value;if(!e.GetProperty("targetId").TryGetInt32(out var actual))return new(StealthStatus.EvaluationFailed,false,"unknown",null);if(r==StealthStatus.Stale)return new(r,false,"unknown",actual);if(!e.TryGetProperty("hit",out var hit)||(hit.ValueKind is not(JsonValueKind.True or JsonValueKind.False)))return new(StealthStatus.EvaluationFailed,false,"unknown",null);return new(r,hit.GetBoolean(),e.TryGetProperty("covering",out var c)&&c.ValueKind==JsonValueKind.String?c.GetString()!:"unknown",actual);}
+public static async Task<StealthValidateRead> ValidateAsync(IsolatedWorld w,string s,int id,int gen,double x,double y){var(r,d)=await Eval(w,BuildValidateJs(s,id,gen,x,y));if(r is not(StealthStatus.Ok or StealthStatus.Stale))return new(r,false,"unknown",null);var e=d!.Value;if(!e.GetProperty("targetId").TryGetInt32(out var actual))return new(StealthStatus.EvaluationFailed,false,"unknown",null);if(r==StealthStatus.Stale)return new(r,false,"unknown",actual);if(!e.TryGetProperty("hit",out var hit)||(hit.ValueKind is not(JsonValueKind.True or JsonValueKind.False)))return new(StealthStatus.EvaluationFailed,false,"unknown",null);return new(r,hit.GetBoolean(),e.TryGetProperty("covering",out var c)&&c.ValueKind==JsonValueKind.String?c.GetString()!:"unknown",actual);}
public static async Task<(StealthStatus Status,bool Hit,string Covering)> PointerAsync(IsolatedWorld w,string s,double x,double y){var(r,d)=await Eval(w,BuildPointerJs(s,x,y));if(r!=StealthStatus.Ok)return(r,false,"unknown");var e=d!.Value;if(!e.TryGetProperty("hit",out var hit)||(hit.ValueKind is not(JsonValueKind.True or JsonValueKind.False)))return(StealthStatus.EvaluationFailed,false,"unknown");return(r,hit.GetBoolean(),e.TryGetProperty("covering",out var c)&&c.ValueKind==JsonValueKind.String?c.GetString()!:"unknown");}
}
diff --git a/dotnet/src/CloakBrowser/Wrappers/LocatorHumanizer.cs b/dotnet/src/CloakBrowser/Wrappers/LocatorHumanizer.cs
index f5fc8ac..8240010 100644
--- a/dotnet/src/CloakBrowser/Wrappers/LocatorHumanizer.cs
+++ b/dotnet/src/CloakBrowser/Wrappers/LocatorHumanizer.cs
@@ -131,9 +131,11 @@ internal static class LocatorHumanizer
var target = HumanMouse.ClickTarget(box, snapshot.IsInput, cfg);
await HumanMouse.HumanMoveAsync(cursor.RawMouse, cursor.X, cursor.Y, target.X, target.Y, cfg).ConfigureAwait(false);
cursor.Set(target.X, target.Y);
- // Validate identity after motion and immediately before the caller's mouse-down.
- await Actionability.CheckPointerEventsAsync(cursor.Page, selector, snapshot.TargetId, target.X, target.Y,
- RemainingMs(deadline), world, force).ConfigureAwait(false);
+ // Validate the click point after motion, immediately before the caller's mouse-down.
+ // force bypasses it entirely, matching Playwright.
+ if (!force)
+ await Actionability.CheckPointerEventsAsync(cursor.Page, selector, snapshot.TargetId, snapshot.Gen,
+ target.X, target.Y, RemainingMs(deadline), world).ConfigureAwait(false);
return (target.X, target.Y, snapshot.IsInput);
}
diff --git a/dotnet/tests/CloakBrowser.Tests/Human/PointerEventsFailOpenTests.cs b/dotnet/tests/CloakBrowser.Tests/Human/PointerEventsFailOpenTests.cs
index 6424c54..95be65f 100644
--- a/dotnet/tests/CloakBrowser.Tests/Human/PointerEventsFailOpenTests.cs
+++ b/dotnet/tests/CloakBrowser.Tests/Human/PointerEventsFailOpenTests.cs
@@ -27,7 +27,7 @@ public class PointerEventsFailOpenTests
await Assert.ThrowsAsync<StealthWorldUnavailableError>(
() => Actionability.CheckPointerEventsAsync(
- page, "#x", targetId: 1, x: 100, y: 100, timeoutMs: 0));
+ page, "#x", targetId: 1, gen: 1, x: 100, y: 100, timeoutMs: 0));
Assert.False(pageRec.WasCalled("Locator"));
}
diff --git a/dotnet/tests/CloakBrowser.Tests/Human/StealthDomTests.cs b/dotnet/tests/CloakBrowser.Tests/Human/StealthDomTests.cs
index addc125..5794a39 100644
--- a/dotnet/tests/CloakBrowser.Tests/Human/StealthDomTests.cs
+++ b/dotnet/tests/CloakBrowser.Tests/Human/StealthDomTests.cs
@@ -27,23 +27,26 @@ public class StealthDomTests
public void ParseResult_strictly_validates_protocol_and_target_identity()
{
Assert.Equal(StealthStatus.Ok, StealthDom.ParseResult(
- JsonSerializer.SerializeToElement(new { v = 1, r = "ok", targetId = 7 })).Status);
+ JsonSerializer.SerializeToElement(new { v = 2, r = "ok", targetId = 7, gen = 3 })).Status);
Assert.Equal(StealthStatus.Stale, StealthDom.ParseResult(
- JsonSerializer.SerializeToElement(new { v = 1, r = "stale", targetId = 8 })).Status);
+ JsonSerializer.SerializeToElement(new { v = 2, r = "stale", targetId = 8, gen = 3 })).Status);
Assert.Equal(StealthStatus.NotFound, StealthDom.ParseResult(
- JsonSerializer.SerializeToElement(new { v = 1, r = "not_found" })).Status);
+ JsonSerializer.SerializeToElement(new { v = 2, r = "not_found" })).Status);
Assert.Equal(StealthStatus.Unsupported, StealthDom.ParseResult(
- JsonSerializer.SerializeToElement(new { v = 1, r = "unsupported" })).Status);
+ JsonSerializer.SerializeToElement(new { v = 2, r = "unsupported" })).Status);
JsonElement?[] malformed =
{
null,
JsonSerializer.SerializeToElement(new { }),
+ JsonSerializer.SerializeToElement(new { v = 1, r = "ok", targetId = 1, gen = 3 }),
+ JsonSerializer.SerializeToElement(new { v = 2, r = "ok" }),
+ JsonSerializer.SerializeToElement(new { v = 2, r = "ok", targetId = 1.5, gen = 3 }),
+ JsonSerializer.SerializeToElement(new { v = 2, r = "stale", gen = 3 }),
+ JsonSerializer.SerializeToElement(new { v = 2, r = "unknown", targetId = 1, gen = 3 }),
+ // identity without the world generation is not trustworthy
JsonSerializer.SerializeToElement(new { v = 2, r = "ok", targetId = 1 }),
- JsonSerializer.SerializeToElement(new { v = 1, r = "ok" }),
- JsonSerializer.SerializeToElement(new { v = 1, r = "ok", targetId = 1.5 }),
- JsonSerializer.SerializeToElement(new { v = 1, r = "stale" }),
- JsonSerializer.SerializeToElement(new { v = 1, r = "unknown", targetId = 1 }),
+ JsonSerializer.SerializeToElement(new { v = 2, r = "stale", targetId = 1 }),
};
foreach (var value in malformed)
Assert.Equal(StealthStatus.EvaluationFailed, StealthDom.ParseResult(value).Status);
diff --git a/dotnet/tests/CloakBrowser.Tests/Wrappers/PageWrapperTests.cs b/dotnet/tests/CloakBrowser.Tests/Wrappers/PageWrapperTests.cs
index ed3be42..c86b439 100644
--- a/dotnet/tests/CloakBrowser.Tests/Wrappers/PageWrapperTests.cs
+++ b/dotnet/tests/CloakBrowser.Tests/Wrappers/PageWrapperTests.cs
@@ -51,7 +51,7 @@ public class PageWrapperTests
? new { width = 1280, height = 720 }
: new
{
- v = 1, r = "ok", targetId = 1, attached = true,
+ v = 2, r = "ok", targetId = 1, gen = 3, attached = true,
visible = true, enabled = true, editable = true,
isInput = false, focused = false, @checked = false, hit = true,
box = new { x = 100, y = 200, width = 80, height = 30 },
diff --git a/js/src/human/actionability.ts b/js/src/human/actionability.ts
index 92bd5d5..b66e873 100644
--- a/js/src/human/actionability.ts
+++ b/js/src/human/actionability.ts
@@ -241,11 +241,11 @@ export async function checkPointerEvents(
pageOrFrame: Page | Frame,
selector: string,
targetId: number,
+ gen: number,
x: number,
y: number,
stealth?: StealthWorld | null,
timeout: number = 5000,
- force: boolean = false,
): Promise<void> {
const deadline = Date.now() + timeout;
let attempt = 0;
@@ -253,12 +253,12 @@ export async function checkPointerEvents(
const world = stealth ?? getWorld(pageOrFrame);
if (!world) throw new StealthWorldUnavailableError();
- if (!Number.isInteger(targetId)) throw new StealthEvaluationError(selector);
+ if (!Number.isInteger(targetId) || !Number.isInteger(gen)) throw new StealthEvaluationError(selector);
while (true) {
const { status, data } = await evalParsed(
world,
- buildValidateJs(selector, targetId, x, y),
+ buildValidateJs(selector, targetId, gen, x, y),
);
if (status === UNSUPPORTED) throw new UnsupportedHumanizeSelectorError(selector);
@@ -266,7 +266,7 @@ export async function checkPointerEvents(
if (status === NOT_FOUND) throw new ElementNotAttachedError(selector);
if (status === EVALUATION_FAILED) {
if (Date.now() >= deadline) throw new StealthEvaluationError(selector);
- } else if (status === OK && data && (force || data.hit)) {
+ } else if (status === OK && data && data.hit) {
return;
} else if (status === OK && data) {
lastMiss = data.covering ?? 'unknown';
diff --git a/js/src/human/index.ts b/js/src/human/index.ts
index a9c71a8..d00b348 100644
--- a/js/src/human/index.ts
+++ b/js/src/human/index.ts
@@ -308,12 +308,12 @@ function patchPage(page: Page, cfg: HumanConfig, cursor: CursorState): void {
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);
cursor.x = target.x;
cursor.y = target.y;
- // Identity is always revalidated after movement and before mouse-down.
- // force skips only coverage rejection, never exact-target validation.
- await checkPointerEvents(
- page, selector, finalBox.targetId, target.x, target.y,
- stealth, remainingMs(), force,
- );
+ if (!force) {
+ await checkPointerEvents(
+ page, selector, finalBox.targetId, finalBox.gen, target.x, target.y,
+ stealth, remainingMs(),
+ );
+ }
await humanClick(raw, isInput, callCfg);
};
@@ -349,10 +349,12 @@ function patchPage(page: Page, cfg: HumanConfig, cursor: CursorState): void {
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);
cursor.x = target.x;
cursor.y = target.y;
- await checkPointerEvents(
- page, selector, finalBox.targetId, target.x, target.y,
- stealth, remainingMs(), force,
- );
+ if (!force) {
+ await checkPointerEvents(
+ page, selector, finalBox.targetId, finalBox.gen, target.x, target.y,
+ stealth, remainingMs(),
+ );
+ }
await raw.down({ clickCount: 2 });
await sleep(rand(30, 60));
await raw.up({ clickCount: 2 });
@@ -390,10 +392,12 @@ function patchPage(page: Page, cfg: HumanConfig, cursor: CursorState): void {
await humanMove(raw, cursor.x, cursor.y, target.x, target.y, callCfg);
cursor.x = target.x;
cursor.y = target.y;
- await checkPointerEvents(
- page, selector, finalBox.targetId, target.x, target.y,
- stealth, remainingMs(), force,
- );
+ if (!force) {
+ await checkPointerEvents(
+ page, selector, finalBox.targetId, finalBox.gen, target.x, target.y,
+ stealth, remainingMs(),
+ );
+ }
};
// --- type ---
diff --git a/js/src/human/scroll.ts b/js/src/human/scroll.ts
index 95fa2c1..37921b5 100644
--- a/js/src/human/scroll.ts
+++ b/js/src/human/scroll.ts
@@ -24,6 +24,7 @@ export interface ElementBounds {
export interface SelectorBounds extends ElementBounds {
targetId: number;
+ gen: number;
}
function isInViewport(
@@ -217,8 +218,8 @@ export async function getElementBox(
}
const { status, data } = result;
- if (status === OK && data?.box && Number.isInteger(data.targetId)) {
- return { ...data.box, targetId: data.targetId };
+ if (status === OK && data?.box && Number.isInteger(data.targetId) && Number.isInteger(data.gen)) {
+ return { ...data.box, targetId: data.targetId, gen: data.gen };
}
if (status === NOT_FOUND) return null;
if (status === UNSUPPORTED) throw new UnsupportedHumanizeSelectorError(selector);
diff --git a/js/src/human/stealthDom.ts b/js/src/human/stealthDom.ts
index 1d41440..232aedc 100644
--- a/js/src/human/stealthDom.ts
+++ b/js/src/human/stealthDom.ts
@@ -1,5 +1,5 @@
/** Versioned isolated-world DOM selector protocol; mirrors stealth_dom.py. */
-export const PROTOCOL_VERSION = 1;
+export const PROTOCOL_VERSION = 2;
export const OK = 'ok';
export const NOT_FOUND = 'not_found';
export const UNSUPPORTED = 'unsupported';
@@ -8,31 +8,38 @@ export const EVALUATION_FAILED = 'evaluation_failed';
export type StealthStatus = typeof OK | typeof NOT_FOUND | typeof UNSUPPORTED | typeof STALE | typeof EVALUATION_FAILED;
export class StealthDomError extends Error { constructor(message: string) { super(message); this.name = new.target.name; } }
-export class UnsupportedHumanizeSelectorError extends StealthDomError { constructor(selector: string) { super(`Humanized selector ${JSON.stringify(selector)} is not supported by the isolated-world resolver`); } }
+export class UnsupportedHumanizeSelectorError extends StealthDomError { constructor(selector: string) { super(`Humanized selector ${JSON.stringify(selector)} is not supported by the isolated-world resolver. Supported: CSS, text=, xpath=, getByTestId, getByPlaceholder, getByAltText, getByTitle, getByText, getByLabel, and a trailing .first()/.nth()/.last(). Not supported: getByRole, chained locators (a >> b, .filter(), .and(), .or()), frameLocator, :visible and :nth-match. Use a CSS or text= selector for this action, or humanize:false to fall back to Playwright.`); } }
export class StealthWorldUnavailableError extends StealthDomError { constructor() { super('Humanized DOM read requires an active isolated world'); } }
export class StealthEvaluationError extends StealthDomError { constructor(selector: string) { super(`Isolated-world DOM evaluation failed for ${JSON.stringify(selector)}`); } }
export interface StealthWorld { evaluate(expression: string): Promise<any>; }
export function getWorld(pageOrFrame: unknown): StealthWorld | null { return (pageOrFrame as any)?._stealth ?? null; }
export interface StealthBox { x: number; y: number; width: number; height: number; }
-export interface StealthSnapshot { v: typeof PROTOCOL_VERSION; r: typeof OK; targetId: number; attached: boolean; visible: boolean; enabled: boolean; editable: boolean; isInput: boolean; focused: boolean; checked: boolean | null; box: StealthBox | null; }
+export interface StealthSnapshot { v: typeof PROTOCOL_VERSION; r: typeof OK; targetId: number; gen: number; attached: boolean; visible: boolean; enabled: boolean; editable: boolean; isInput: boolean; focused: boolean; checked: boolean | null; box: StealthBox | null; }
/** Compatibility name used by the humanized action layer. */
export type SnapshotPayload = StealthSnapshot;
-export interface StealthPointerPayload { v: typeof PROTOCOL_VERSION; r: typeof OK; targetId: number; hit: boolean; covering?: string; }
+export interface StealthPointerPayload { v: typeof PROTOCOL_VERSION; r: typeof OK; targetId: number; gen: number; hit: boolean; covering?: string; }
export interface ParsedResult { status: StealthStatus; data?: any; }
const RESOLVER_BODY = String.raw`
const __UNS = 'UNSUPPORTED';
-const __V = 1;
+const __V = 2;
const __STATE_KEY = '__cloakHumanDomV1';
function __state(){
let s = globalThis[__STATE_KEY];
if (!s) {
- s = { ids: new WeakMap(), nextId: 1 };
+ // Element ids restart at 1 in every new world, and the world is recreated on
+ // navigation (#507), so an id alone can name a different element after a nav.
+ // The generation makes that cross-world reuse detectable as 'stale'.
+ // 11 bits of wall clock + 20 bits of randomness. The maximum is exactly
+ // Int32.MaxValue, because the .NET wrapper carries the value as an Int32.
+ s = { ids: new WeakMap(), nextId: 1,
+ gen: (Date.now() & 2047) * 1048576 + Math.floor(Math.random() * 1048576) };
Object.defineProperty(globalThis, __STATE_KEY, { value: s, configurable: false, enumerable: false });
}
return s;
}
+function __gen(){ return __state().gen; }
function __targetId(el){
const s = __state();
let id = s.ids.get(el);
@@ -198,13 +205,11 @@ function __elementText(el, cache){
continue;
} else {
if (immediate) { fragments.push(immediate); immediate = ''; }
- if (child.nodeType === 1) {
- full += __elementText(child, cache).full;
- if (child.tagName && child.tagName.toLowerCase() === 'br') full += '\n';
- }
+ if (child.nodeType === 1) full += __elementText(child, cache).full;
}
}
if (immediate) fragments.push(immediate);
+ if (el.shadowRoot) full += __elementText(el.shadowRoot, cache).full;
out = { full: full, normalized: __normWS(full), immediate: fragments };
cache.set(el, out);
return out;
@@ -242,21 +247,224 @@ function __parseTextMatcher(arg){
}
return { kind: 'lax', value: __normWS(arg).toLowerCase() };
}
-function __matchText(el, matcher, cache){
- const text = __elementText(el, cache);
+function __matchTextValue(text, matcher){
if (matcher.kind === 'regex') { matcher.regex.lastIndex = 0; return matcher.regex.test(text.full); }
+ // The public engine's exact rule compares immediate text-node runs, unlike
+ // internal:text which compares the full normalized subtree text.
if (matcher.kind === 'exact') return text.immediate.some(x => __normWS(x) === matcher.value);
return text.normalized.toLowerCase().includes(matcher.value);
}
+function __matchText(el, matcher, cache){
+ return __matchTextValue(__elementText(el, cache), matcher);
+}
+function __publicTextMatches(el, matcher, cache){
+ // Playwright's elementMatchesText for the public text= engine.
+ if (__skipText(el)) return 'none';
+ if (!__matchText(el, matcher, cache)) return 'none';
+ for (const child of el.children || []) {
+ if (__matchText(child, matcher, cache)) return 'selfAndChildren';
+ }
+ // A host whose shadow content also matches is not the smallest match. This
+ // cannot be expressed with contains(), which does not pierce shadow roots.
+ if (el.shadowRoot && __matchTextValue(__elementText(el.shadowRoot, cache), matcher))
+ return 'selfAndChildren';
+ return 'self';
+}
function __byText(arg){
const matcher = __parseTextMatcher(arg);
if (matcher === __UNS) return __UNS;
- const matches = [], cache = new Map();
- const all = __allElements();
- for (const el of all) { if (__matchText(el, matcher, cache)) matches.push(el); }
- // Playwright's text engine targets the smallest matching element: drop any
- // element that has a descendant which also matches.
- return matches.filter(el => !matches.some(o => o !== el && el.contains(o)));
+ const out = [], cache = new Map();
+ let lastMiss = null;
+ for (const el of __allElements()) {
+ // Nothing under a non-matching ancestor can match in lax mode.
+ if (matcher.kind === 'lax' && lastMiss && lastMiss.contains(el)) continue;
+ const m = __publicTextMatches(el, matcher, cache);
+ if (m === 'none') lastMiss = el;
+ // The public engine also keeps an ancestor when the match is exact.
+ if (m === 'self' || (m === 'selfAndChildren' && matcher.kind === 'exact')) out.push(el);
+ }
+ return out;
+}
+function __attrUnquote(s, i){
+ // parseAttributeSelector.readQuotedString: a backslash is dropped and the next
+ // character taken verbatim -- NOT JSON escapes, so "a\\nb" decodes to 'anb'.
+ const quote = s.charAt(i);
+ if (quote !== '"' && quote !== "'") return __UNS;
+ let out = '';
+ i++;
+ while (i < s.length && s.charAt(i) !== quote) {
+ if (s.charAt(i) === '\\') {
+ i++;
+ if (i >= s.length) return __UNS;
+ }
+ out += s.charAt(i++);
+ }
+ if (s.charAt(i) !== quote) return __UNS;
+ return { value: out, end: i + 1 };
+}
+function __parseAttrBody(body){
+ // [name="value"i] | [name="value"s] | [name=/re/flags]
+ body = body.trim();
+ if (body.charAt(0) !== '[' || body.charAt(body.length - 1) !== ']') return __UNS;
+ const inner = body.slice(1, -1);
+ const eq = inner.indexOf('=');
+ if (eq <= 0) return __UNS;
+ let name = inner.slice(0, eq).trim();
+ if (name.charAt(0) === '"' || name.charAt(0) === "'") {
+ const un = __attrUnquote(name, 0);
+ if (un === __UNS || un.end !== name.length) return __UNS;
+ name = un.value;
+ }
+ // isCSSNameChar, plus ',' for the comma-joined test-id name list. Also rejects
+ // the *= ^= $= |= ~= operators, whose extra character lands in the name.
+ if (!/^[\w\u0080-\uFFFF,-]+$/.test(name)) return __UNS;
+ const rest = inner.slice(eq + 1);
+ let j = 0;
+ while (j < rest.length && /\s/.test(rest.charAt(j))) j++;
+ if (rest.charAt(j) === '/') {
+ const end = rest.lastIndexOf('/');
+ if (end <= j) return __UNS;
+ const flags = rest.slice(end + 1).trim();
+ if (!/^[dgimsuvy]*$/.test(flags)) return __UNS;
+ try { return { name: name, regex: new RegExp(rest.slice(j + 1, end), flags), value: null, caseSensitive: true }; }
+ catch (e) { return __UNS; }
+ }
+ const un = __attrUnquote(rest, j);
+ if (un === __UNS) return __UNS;
+ let k = un.end, caseSensitive = true;
+ const flag = rest.charAt(k);
+ if (flag === 'i' || flag === 'I') { caseSensitive = false; k++; }
+ else if (flag === 's' || flag === 'S') { caseSensitive = true; k++; }
+ while (k < rest.length && /\s/.test(rest.charAt(k))) k++;
+ if (k !== rest.length) return __UNS;
+ return { name: name, regex: null, value: un.value, caseSensitive: caseSensitive };
+}
+function __byAttr(body){
+ // Serves internal:attr (placeholder/alt/title) AND internal:testid -- the
+ // attribute name comes from the selector. The 'i' flag means case-insensitive
+ // SUBSTRING, and the RAW attribute value is compared: no trim, no whitespace
+ // normalization. get_by_test_id always emits 's', so it is strict equality.
+ const parsed = __parseAttrBody(body);
+ if (parsed === __UNS) return __UNS;
+ const names = parsed.name.split(',');
+ const lower = (parsed.regex || parsed.caseSensitive) ? null : parsed.value.toLowerCase();
+ const out = [];
+ try {
+ for (const el of __allElements()) {
+ if (!el.getAttribute) continue;
+ for (const name of names) {
+ const actual = el.getAttribute(name);
+ if (actual === null || actual === undefined) continue;
+ let hit;
+ if (parsed.regex) { parsed.regex.lastIndex = 0; hit = !!String(actual).match(parsed.regex); }
+ else if (parsed.caseSensitive) hit = actual === parsed.value;
+ else hit = String(actual).toLowerCase().indexOf(lower) !== -1;
+ if (hit) { out.push(el); break; }
+ }
+ }
+ } catch (e) { return __UNS; }
+ return out;
+}
+function __parseInternalTextMatcher(arg){
+ // createTextMatcher(selector, internal=true). Playwright does not trim here.
+ if (arg.charAt(0) === '/' && arg.lastIndexOf('/') > 0) {
+ const end = arg.lastIndexOf('/');
+ try { return { kind: 'regex', regex: new RegExp(arg.slice(1, end), arg.slice(end + 1)) }; }
+ catch (e) { return __UNS; }
+ }
+ if (arg.length > 1 && arg.charAt(0) === '"') {
+ let body = null, strict = false;
+ const last = arg.charAt(arg.length - 1);
+ if (last === '"') { body = arg; strict = true; }
+ else if (arg.charAt(arg.length - 2) === '"' && (last === 's' || last === 'i')) {
+ body = arg.slice(0, -1); strict = last === 's';
+ } else return __UNS;
+ let value;
+ try { value = JSON.parse(body); } catch (e) { return __UNS; }
+ if (typeof value !== 'string') return __UNS;
+ const norm = __normWS(value);
+ return strict ? { kind: 'strict', value: norm } : { kind: 'lax', value: norm.toLowerCase() };
+ }
+ // A single-quoted body reaches unquote=JSON.parse in Playwright and throws.
+ if (arg.length > 1 && arg.charAt(0) === "'" && arg.charAt(arg.length - 1) === "'") return __UNS;
+ return { kind: 'lax', value: __normWS(arg).toLowerCase() };
+}
+function __matchInternalText(text, matcher){
+ if (matcher.kind === 'regex') { matcher.regex.lastIndex = 0; return matcher.regex.test(text.full); }
+ // strict compares the FULL normalized subtree text. The public text= engine
+ // compares immediate fragments instead (__matchText) -- genuinely different.
+ if (matcher.kind === 'strict') return text.normalized === matcher.value;
+ return text.normalized.toLowerCase().indexOf(matcher.value) !== -1;
+}
+function __internalTextMatches(el, matcher, cache){
+ if (__skipText(el)) return 'none';
+ if (!__matchInternalText(__elementText(el, cache), matcher)) return 'none';
+ // Direct children only, plus the shadow-root probe -- NOT contains() over the
+ // match set, which would drop an outer element matched only via a grandchild.
+ for (const child of el.children || []) {
+ if (__matchInternalText(__elementText(child, cache), matcher)) return 'selfAndChildren';
+ }
+ if (el.shadowRoot && __matchInternalText(__elementText(el.shadowRoot, cache), matcher)) return 'selfAndChildren';
+ return 'self';
+}
+function __byInternalText(arg){
+ const matcher = __parseInternalTextMatcher(arg);
+ if (matcher === __UNS) return __UNS;
+ const cache = new Map(), out = [];
+ let lastMiss = null;
+ for (const el of __allElements()) {
+ // lastDidNotMatchSelf: in lax mode nothing under a non-matching ancestor matches.
+ if (matcher.kind === 'lax' && lastMiss && lastMiss.contains(el)) continue;
+ const m = __internalTextMatches(el, matcher, cache);
+ if (m === 'none') lastMiss = el;
+ if (m === 'self') out.push(el);
+ }
+ return out;
+}
+function __idRefRoot(el){
+ const root = el.getRootNode ? el.getRootNode() : null;
+ return (root && typeof root.getElementById === 'function') ? root : document;
+}
+function __labelledByElements(el){
+ const ref = el.getAttribute ? el.getAttribute('aria-labelledby') : null;
+ if (ref === null || ref === undefined) return null;
+ const root = __idRefRoot(el), out = [];
+ for (const id of ref.split(/\s+/)) {
+ if (!id) continue;
+ const target = root.getElementById(id);
+ if (target && out.indexOf(target) === -1) out.push(target);
+ }
+ return out.length ? out : null;
+}
+function __elementLabels(el, cache){
+ // First non-empty source wins: aria-labelledby, then aria-label, then .labels.
+ const refs = __labelledByElements(el);
+ if (refs) return refs.map(function(x){ return __elementText(x, cache); });
+ const aria = el.getAttribute ? el.getAttribute('aria-label') : null;
+ if (aria !== null && aria !== undefined && aria.trim())
+ return [{ full: aria, normalized: __normWS(aria), immediate: [aria] }];
+ const tag = el.tagName ? el.tagName.toUpperCase() : '';
+ const nonHiddenInput = tag === 'INPUT' && String(el.type || '').toLowerCase() !== 'hidden';
+ if (nonHiddenInput || ['BUTTON','METER','OUTPUT','PROGRESS','SELECT','TEXTAREA'].indexOf(tag) !== -1) {
+ // Native .labels already resolves both for/id and a wrapping <label>.
+ const labels = el.labels;
+ if (labels) return Array.prototype.slice.call(labels).map(function(x){ return __elementText(x, cache); });
+ }
+ return [];
+}
+function __byLabel(arg){
+ const matcher = __parseInternalTextMatcher(arg);
+ if (matcher === __UNS) return __UNS;
+ const cache = new Map(), out = [];
+ try {
+ for (const el of __allElements()) {
+ const labels = __elementLabels(el, cache);
+ for (const label of labels) {
+ if (__matchInternalText(label, matcher)) { out.push(el); break; }
+ }
+ }
+ } catch (e) { return __UNS; }
+ return out;
}
function __allElements(){
if (!document.children && document.querySelectorAll)
@@ -474,9 +682,15 @@ function __resolve(sel){
const m = sel.match(/^([\s\S]*?)\s*>>\s*nth=(-?\d+)\s*$/);
if (m) { sel = m[1].trim(); nth = parseInt(m[2], 10); hasNth = true; }
if (sel.indexOf('>>') !== -1) return __UNS; // chaining we don't reimplement
- if (sel.indexOf('internal:') !== -1) return __UNS; // get_by_* engines
let list;
- if (sel.indexOf('xpath=') === 0) { list = __byXPath(sel.slice(6)); }
+ // get_by_* engines we reimplement. Anything else under internal: (role, has,
+ // has-text, and, or, chain, control, describe) stays unsupported.
+ if (sel.indexOf('internal:testid=') === 0) { list = __byAttr(sel.slice(16)); }
+ else if (sel.indexOf('internal:attr=') === 0) { list = __byAttr(sel.slice(14)); }
+ else if (sel.indexOf('internal:text=') === 0) { list = __byInternalText(sel.slice(14)); }
+ else if (sel.indexOf('internal:label=') === 0) { list = __byLabel(sel.slice(15)); }
+ else if (sel.indexOf('internal:') !== -1) return __UNS;
+ else if (sel.indexOf('xpath=') === 0) { list = __byXPath(sel.slice(6)); }
else if (sel.indexOf('//') === 0 || sel.indexOf('(//') === 0 || sel.indexOf('..') === 0) { list = __byXPath(sel); }
else if (sel.indexOf('text=') === 0) { list = __byText(sel.slice(5)); }
else {
@@ -491,15 +705,14 @@ function __resolve(sel){
}
`;
const SNAPSHOT_OP=String.raw`
-const __el=__resolve(__SEL);if(__el==='UNSUPPORTED')return {v:__V,r:'unsupported'};if(!__el)return {v:__V,r:'not_found'};const __box=__visBox(__el),__hasBox=__box!==null,__tag=__el.tagName.toLowerCase(),__enabled=__isEnabled(__el),__editable=__isEditable(__el,__enabled);return {v:__V,r:'ok',targetId:__targetId(__el),attached:__el.isConnected===true,visible:__isVisible(__el),enabled:__enabled,editable:__editable,isInput:__tag==='input'||__tag==='textarea'||__el.isContentEditable===true,focused:__deepActiveElement()===__el,checked:typeof __el.checked==='boolean'?__el.checked:null,box:__box};`;
+const __el=__resolve(__SEL);if(__el==='UNSUPPORTED')return {v:__V,r:'unsupported'};if(!__el)return {v:__V,r:'not_found'};const __box=__visBox(__el),__hasBox=__box!==null,__tag=__el.tagName.toLowerCase(),__enabled=__isEnabled(__el),__editable=__isEditable(__el,__enabled);return {v:__V,r:'ok',targetId:__targetId(__el),gen:__gen(),attached:__el.isConnected===true,visible:__isVisible(__el),enabled:__enabled,editable:__editable,isInput:__tag==='input'||__tag==='textarea'||__el.isContentEditable===true,focused:__deepActiveElement()===__el,checked:typeof __el.checked==='boolean'?__el.checked:null,box:__box};`;
export const VIEWPORT_JS='(() => ({ width: window.innerWidth, height: window.innerHeight }))()';
function wrap(selector:string,op:string){return `(() => {\nconst __SEL = ${JSON.stringify(selector)};\n${RESOLVER_BODY}\n${op}\n})()`;}
export function buildSnapshotJs(selector:string){return wrap(selector,SNAPSHOT_OP);}
export function buildBoxJs(selector:string){return wrap(selector,SNAPSHOT_OP.replace("r:'ok'","r:__hasBox?'ok':'not_found'"));}
export function buildActionableJs(selector:string){return buildSnapshotJs(selector);}
-function pointer(selector:string,targetId:number|undefined,x:number,y:number,validate:boolean){const check=validate?`if(__id!==${Math.trunc(targetId!)})return {v:__V,r:'stale',targetId:__id};if(__el.isConnected!==true)return {v:__V,r:'stale',targetId:__id};`:'';return wrap(selector,`const __el=__resolve(__SEL);if(__el==='UNSUPPORTED')return {v:__V,r:'unsupported'};if(!__el)return {v:__V,r:'not_found'};const __id=__targetId(__el);${check}const __t=__deepElementFromPoint(${Number(x)},${Number(y)});let __n=__t;while(__n){if(__n===__el)return {v:__V,r:'ok',targetId:__id,hit:true};__n=__composedParent(__n);}if(__t&&__el.contains(__t))return {v:__V,r:'ok',targetId:__id,hit:true};return {v:__V,r:'ok',targetId:__id,hit:false,covering:__t?(__t.tagName||'unknown'):'none'};`);}
-export function buildValidateJs(selector:string,targetId:number,x:number,y:number){return pointer(selector,targetId,x,y,true);}
-export function buildPointerJs(selector:string,x:number,y:number){return pointer(selector,undefined,x,y,false);}
-export function parseResult(raw:any):ParsedResult{if(!raw||typeof raw!=='object'||Array.isArray(raw)||raw.v!==PROTOCOL_VERSION)return{status:EVALUATION_FAILED};if(raw.r===OK)return Number.isInteger(raw.targetId)?{status:OK,data:raw}:{status:EVALUATION_FAILED};if(raw.r===NOT_FOUND)return{status:NOT_FOUND};if(raw.r===STALE)return Number.isInteger(raw.targetId)?{status:STALE,data:raw}:{status:EVALUATION_FAILED};if(raw.r===UNSUPPORTED)return{status:UNSUPPORTED};return{status:EVALUATION_FAILED};}
+function pointer(selector:string,targetId:number|undefined,gen:number|undefined,x:number,y:number,validate:boolean){const check=validate?`if(__g!==${Math.trunc(gen!)})return {v:__V,r:'stale',targetId:__id,gen:__g};if(__id!==${Math.trunc(targetId!)})return {v:__V,r:'stale',targetId:__id,gen:__g};if(__el.isConnected!==true)return {v:__V,r:'stale',targetId:__id,gen:__g};`:'';return wrap(selector,`const __el=__resolve(__SEL);if(__el==='UNSUPPORTED')return {v:__V,r:'unsupported'};if(!__el)return {v:__V,r:'not_found'};const __g=__gen();const __id=__targetId(__el);${check}const __t=__deepElementFromPoint(${Number(x)},${Number(y)});let __n=__t;while(__n){if(__n===__el)return {v:__V,r:'ok',targetId:__id,gen:__g,hit:true};__n=__composedParent(__n);}if(__t&&__el.contains(__t))return {v:__V,r:'ok',targetId:__id,gen:__g,hit:true};return {v:__V,r:'ok',targetId:__id,gen:__g,hit:false,covering:__t?(__t.tagName||'unknown'):'none'};`);}
+export function buildValidateJs(selector:string,targetId:number,gen:number,x:number,y:number){return pointer(selector,targetId,gen,x,y,true);}
+export function buildPointerJs(selector:string,x:number,y:number){return pointer(selector,undefined,undefined,x,y,false);}
+export function parseResult(raw:any):ParsedResult{if(!raw||typeof raw!=='object'||Array.isArray(raw)||raw.v!==PROTOCOL_VERSION)return{status:EVALUATION_FAILED};if(raw.r===OK)return Number.isInteger(raw.targetId)&&Number.isInteger(raw.gen)?{status:OK,data:raw}:{status:EVALUATION_FAILED};if(raw.r===NOT_FOUND)return{status:NOT_FOUND};if(raw.r===STALE)return Number.isInteger(raw.targetId)&&Number.isInteger(raw.gen)?{status:STALE,data:raw}:{status:EVALUATION_FAILED};if(raw.r===UNSUPPORTED)return{status:UNSUPPORTED};return{status:EVALUATION_FAILED};}
export async function evalParsed(world:StealthWorld,expression:string):Promise<ParsedResult>{try{return parseResult(await world.evaluate(expression));}catch{return{status:EVALUATION_FAILED};}}
-export async function readSnapshot(world:StealthWorld|null|undefined,selector:string):Promise<StealthSnapshot>{if(!world)throw new StealthWorldUnavailableError();const r=await evalParsed(world,buildSnapshotJs(selector));if(r.status===OK)return r.data as StealthSnapshot;if(r.status===UNSUPPORTED)throw new UnsupportedHumanizeSelectorError(selector);throw new StealthEvaluationError(selector);}
diff --git a/js/tests/humanize.test.ts b/js/tests/humanize.test.ts
index ac53ac2..d70a414 100644
--- a/js/tests/humanize.test.ts
+++ b/js/tests/humanize.test.ts
@@ -867,7 +867,7 @@ function buildMockPage(overrides: Record<string, any> = {}): any {
if (method === 'Page.createIsolatedWorld') return { executionContextId: 42 };
if (method === 'Runtime.evaluate') {
return { result: { value: {
- v: 1, r: 'ok', targetId: 1, attached: true, visible: true,
+ v: 2, r: 'ok', targetId: 1, gen: 1, attached: true, visible: true,
enabled: true, editable: true, isInput: false,
focused: overrides.snapshotFocused ?? false,
checked: overrides.snapshotChecked ??
@@ -1378,9 +1378,9 @@ describe("page.click(selector, { timeout }) forwards timeout to scroll", () => {
locator: vi.fn(),
_stealth: { evaluate: vi.fn(async () => {
evaluations++;
- if (evaluations < 3) return { v: 1, r: "not_found" };
+ if (evaluations < 3) return { v: 2, r: "not_found" };
return {
- v: 1, r: "ok", targetId: 7,
+ v: 2, r: "ok", targetId: 7, gen: 1,
box: { x: 100, y: 200, width: 50, height: 30 },
};
}) },
@@ -1400,7 +1400,7 @@ describe("page.click(selector, { timeout }) forwards timeout to scroll", () => {
const { getElementBox } = await import("../src/human/scroll.js");
const page: any = {
locator: vi.fn(),
- _stealth: { evaluate: vi.fn(async () => ({ v: 1, r: "not_found" })) },
+ _stealth: { evaluate: vi.fn(async () => ({ v: 2, r: "not_found" })) },
};
const started = Date.now();
@@ -1804,7 +1804,7 @@ describe("selector reads stay isolated", () => {
const { ensureActionable, CHECKS_CLICK } = await import("../src/human/actionability.js");
const { UnsupportedHumanizeSelectorError } = await import("../src/human/stealthDom.js");
const page = {
- _stealth: { evaluate: vi.fn().mockResolvedValue({ v: 1, r: "unsupported" }) },
+ _stealth: { evaluate: vi.fn().mockResolvedValue({ v: 2, r: "unsupported" }) },
locator: vi.fn(),
};
@@ -1818,11 +1818,11 @@ describe("selector reads stay isolated", () => {
const { getElementBox } = await import("../src/human/scroll.js");
const { UnsupportedHumanizeSelectorError } = await import("../src/human/stealthDom.js");
const page = {
- _stealth: { evaluate: vi.fn().mockResolvedValue({ v: 1, r: "unsupported" }) },
+ _stealth: { evaluate: vi.fn().mockResolvedValue({ v: 2, r: "unsupported" }) },
locator: vi.fn(),
};
- await expect(getElementBox(page as any, "internal:text=save", 100))
+ await expect(getElementBox(page as any, "internal:role=button", 100))
.rejects.toBeInstanceOf(UnsupportedHumanizeSelectorError);
expect(page.locator).not.toHaveBeenCalled();
});
@@ -1849,7 +1849,7 @@ describe("pointer-events failure semantics", () => {
const world = { evaluate: vi.fn().mockRejectedValue(new Error("execution context destroyed")) };
await expect(
- checkPointerEvents(page as any, "#x", 1, 100, 100, world, 0),
+ checkPointerEvents(page as any, "#x", 1, 1, 100, 100, world, 0),
).rejects.toBeInstanceOf(StealthEvaluationError);
expect(page.locator).not.toHaveBeenCalled();
});
diff --git a/js/tests/stealth.test.ts b/js/tests/stealth.test.ts
index c86b5f2..fa5b35d 100644
--- a/js/tests/stealth.test.ts
+++ b/js/tests/stealth.test.ts
@@ -115,7 +115,7 @@ function buildMockCDP(overrides: Record<string, any> = {}): any {
}
if (method === "Runtime.evaluate") {
return { result: { value: {
- v: 1, r: "ok", targetId: 1, attached: true, visible: true,
+ v: 2, r: "ok", targetId: 1, gen: 1, attached: true, visible: true,
enabled: true, editable: true, isInput: false, focused: false,
checked: false, hit: true,
box: { x: 100, y: 300, width: 200, height: 30 },
@@ -699,7 +699,7 @@ describe("isInputElement stealth integration via patchPage", () => {
if (method === "Runtime.evaluate") {
stealthEvaluateCalls.push(params.expression);
return { result: { value: {
- v: 1, r: "ok", targetId: 1, attached: true, visible: true,
+ v: 2, r: "ok", targetId: 1, gen: 1, attached: true, visible: true,
enabled: true, editable: true, isInput: false, focused: false,
checked: false, hit: true,
box: { x: 100, y: 300, width: 200, height: 30 },
@@ -771,7 +771,7 @@ describe("isSelectorFocused stealth integration via patchPage", () => {
if (method === "Runtime.evaluate") {
stealthEvaluateCalls.push(params.expression);
return { result: { value: {
- v: 1, r: "ok", targetId: 1, attached: true, visible: true,
+ v: 2, r: "ok", targetId: 1, gen: 1, attached: true, visible: true,
enabled: true, editable: true, isInput: true, focused: true,
checked: false, hit: true,
box: { x: 100, y: 300, width: 200, height: 30 },
diff --git a/js/tests/stealthDom.test.ts b/js/tests/stealthDom.test.ts
index b90521e..4dfa218 100644
--- a/js/tests/stealthDom.test.ts
+++ b/js/tests/stealthDom.test.ts
@@ -11,8 +11,106 @@ function node(tag:string, text='', cls=''):E {
let doc:any;
function append(p:E,c:E){const prev=p.childNodes.at(-1);if(prev)prev.nextSibling=c;c.nextSibling=null;c.parentElement=p;c.previousElementSibling=p.children.at(-1)??null;p.children.push(c);p.childNodes.push(c);p.firstChild=p.childNodes[0]??null;}
function wireOwner(n:E){n.ownerDocument=doc;for(const child of n.childNodes??[])wireOwner(child);}
-function run(js:string, roots:E[], point?:E, active?:E){let selected:any=null;doc={children:roots,head:{contains:()=>false},activeElement:active??null,querySelectorAll:()=>[],elementFromPoint:()=>point??null,evaluate:()=>({snapshotLength:0,snapshotItem:()=>null}),createRange:()=>({selectNode:(n:any)=>{selected=n;},getBoundingClientRect:()=>selected?.rect??{x:0,y:0,width:0,height:0}})};for(const r of roots){r.getRootNode=()=>doc;wireOwner(r);}const f=new Function('document','XPathResult','getComputedStyle','globalThis','return '+js);return f(doc,{ORDERED_NODE_SNAPSHOT_TYPE:7},(e:E)=>e.style??{display:'block',visibility:'visible'},{});}
+function run(js:string, roots:E[], point?:E, active?:E, store:any={}){let selected:any=null;doc={children:roots,head:{contains:()=>false},getElementById:(id:string)=>{let hit:any=null;const walk=(n:any)=>{if(n.attrs&&n.attrs.id===id)hit=n;for(const c of n.children??[])walk(c);};for(const r of roots)walk(r);return hit;},activeElement:active??null,querySelectorAll:()=>[],elementFromPoint:()=>point??null,evaluate:()=>({snapshotLength:0,snapshotItem:()=>null}),createRange:()=>({selectNode:(n:any)=>{selected=n;},getBoundingClientRect:()=>selected?.rect??{x:0,y:0,width:0,height:0}})};for(const r of roots){r.getRootNode=()=>doc;wireOwner(r);}const f=new Function('document','XPathResult','getComputedStyle','globalThis','return '+js);return f(doc,{ORDERED_NODE_SNAPSHOT_TYPE:7},(e:E)=>e.style??{display:'block',visibility:'visible'},store);}
-describe('protocol',()=>{it('strictly rejects malformed payloads and evaluator failures',async()=>{expect(parseResult({v:1,r:OK,targetId:1})).toMatchObject({status:OK});for(const x of [null,{}, {v:2,r:OK,targetId:1},{v:1,r:OK},{v:1,r:STALE,targetId:1.5}])expect(parseResult(x)).toEqual({status:EVALUATION_FAILED});expect(parseResult({v:1,r:NOT_FOUND})).toEqual({status:NOT_FOUND});expect(parseResult({v:1,r:UNSUPPORTED})).toEqual({status:UNSUPPORTED});expect(await evalParsed({evaluate:async()=>{throw Error()}},'x')).toEqual({status:EVALUATION_FAILED});});});
+describe('protocol',()=>{it('strictly rejects malformed payloads and evaluator failures',async()=>{expect(parseResult({v:2,r:OK,targetId:1,gen:5})).toMatchObject({status:OK});for(const x of [null,{}, {v:1,r:OK,targetId:1,gen:5},{v:2,r:OK},{v:2,r:OK,targetId:1},{v:2,r:STALE,targetId:1.5,gen:5},{v:2,r:STALE,targetId:1,gen:1.5}])expect(parseResult(x)).toEqual({status:EVALUATION_FAILED});expect(parseResult({v:2,r:NOT_FOUND})).toEqual({status:NOT_FOUND});expect(parseResult({v:2,r:UNSUPPORTED})).toEqual({status:UNSUPPORTED});expect(await evalParsed({evaluate:async()=>{throw Error()}},'x')).toEqual({status:EVALUATION_FAILED});});});
-describe('shipped resolver',()=>{it('unions only visible display:contents geometry, including nested content',()=>{const target=node('li','Hoy','target');target.style.display='contents';target.rect={x:0,y:0,width:0,height:0};target.childNodes[0].rect={x:5,y:6,width:25,height:10};const targetResult=run(buildSnapshotJs('.target'),[target]);expect(targetResult).toMatchObject({r:OK,visible:true,box:{x:5,y:6,width:25,height:10}});const union=node('div','','union');union.style.display='contents';union.rect={x:0,y:0,width:0,height:0};const left=node('span','left');left.rect={x:10,y:20,width:20,height:10};const right=node('span','right');right.rect={x:40,y:20,width:30,height:10};const nested=node('span','','nested');nested.style.display='contents';nested.rect={x:0,y:0,width:0,height:0};const nestedChild=node('span','nested');nestedChild.rect={x:75,y:20,width:25,height:10};append(nested,nestedChild);const hidden=node('span','hidden');hidden.style.visibility='hidden';hidden.rect={x:1000,y:1000,width:100,height:100};append(union,left);append(union,right);append(union,nested);append(union,hidden);expect(run(buildSnapshotJs('.union'),[union])).toMatchObject({r:OK,visible:true,box:{x:10,y:20,width:90,height:10}});const hiddenText=node('div','hidden text','hidden-text');hiddenText.style={display:'contents',visibility:'hidden'};hiddenText.rect={x:0,y:0,width:0,height:0};hiddenText.childNodes[0].rect={x:5,y:6,width:50,height:10};expect(run(buildSnapshotJs('.hidden-text'),[hiddenText])).toMatchObject({r:OK,visible:false,box:null});});it('executes descendant, child, adjacent, sibling, lists and structural has-text',()=>{const root=node('div');const a=node('span','one','a'), b=node('button','Save','b'), c=node('button','Other','c');append(root,a);append(root,b);append(root,c);for(const s of ['div button','div > button','.a + button','.a ~ button','.no, button:has-text("Save")'])expect(run(buildSnapshotJs(s),[root]).r).toBe(OK);});it('executes exact/lax/regex text and excludes script text (#512)',()=>{const r=node('div'), s=node('span',' Hello World '), script=node('script','secret');append(r,s);append(r,script);expect(run(buildSnapshotJs('text="Hello World"'),[r]).r).toBe(OK);expect(run(buildSnapshotJs('text=hello world'),[r]).r).toBe(OK);expect(run(buildSnapshotJs('text=/world/i'),[r]).r).toBe(OK);expect(run(buildSnapshotJs('text=secret'),[r]).r).toBe(NOT_FOUND);});it('executes native and ARIA state',()=>{const root=node('div'),disabled=node('button','','disabled'),ariaDisabled=node('button','','aria-disabled'),readonly=node('div','','readonly');disabled.attrs.disabled='';ariaDisabled.attrs.role='button';ariaDisabled.attrs['aria-disabled']='true';readonly.attrs.role='textbox';readonly.attrs['aria-readonly']='true';append(root,disabled);append(root,ariaDisabled);append(root,readonly);expect(run(buildSnapshotJs('.disabled'),[root]).enabled).toBe(false);expect(run(buildSnapshotJs('.aria-disabled'),[root]).enabled).toBe(false);expect(run(buildSnapshotJs('.readonly'),[root]).editable).toBe(false);});it('executes deep shadow ordering, focus, hit testing and stale validation',()=>{const host=node('div'), light=node('button','light'), shadow=node('button','shadow');append(host,light);const disabled=node('button');disabled.attrs.disabled='';append(host,disabled);host.shadowRoot={children:[shadow],elementFromPoint:()=>shadow,activeElement:shadow};shadow.getRootNode=()=>host.shadowRoot;shadow.parentElement=null;expect(run(buildSnapshotJs('button >> nth=2'),[host],host,host).focused).toBe(true);expect(run(buildSnapshotJs('button >> nth=1'),[host]).enabled).toBe(false);expect(run(buildSnapshotJs('button'),[host],host,host).focused).toBe(false);expect(run(buildPointerJs('button >> nth=2',1,2),[host],host).hit).toBe(true);expect(run(buildValidateJs('button',999,1,2),[host]).r).toBe(STALE);});});
+describe('shipped resolver',()=>{it('unions only visible display:contents geometry, including nested content',()=>{const target=node('li','Hoy','target');target.style.display='contents';target.rect={x:0,y:0,width:0,height:0};target.childNodes[0].rect={x:5,y:6,width:25,height:10};const targetResult=run(buildSnapshotJs('.target'),[target]);expect(targetResult).toMatchObject({r:OK,visible:true,box:{x:5,y:6,width:25,height:10}});const union=node('div','','union');union.style.display='contents';union.rect={x:0,y:0,width:0,height:0};const left=node('span','left');left.rect={x:10,y:20,width:20,height:10};const right=node('span','right');right.rect={x:40,y:20,width:30,height:10};const nested=node('span','','nested');nested.style.display='contents';nested.rect={x:0,y:0,width:0,height:0};const nestedChild=node('span','nested');nestedChild.rect={x:75,y:20,width:25,height:10};append(nested,nestedChild);const hidden=node('span','hidden');hidden.style.visibility='hidden';hidden.rect={x:1000,y:1000,width:100,height:100};append(union,left);append(union,right);append(union,nested);append(union,hidden);expect(run(buildSnapshotJs('.union'),[union])).toMatchObject({r:OK,visible:true,box:{x:10,y:20,width:90,height:10}});const hiddenText=node('div','hidden text','hidden-text');hiddenText.style={display:'contents',visibility:'hidden'};hiddenText.rect={x:0,y:0,width:0,height:0};hiddenText.childNodes[0].rect={x:5,y:6,width:50,height:10};expect(run(buildSnapshotJs('.hidden-text'),[hiddenText])).toMatchObject({r:OK,visible:false,box:null});});it('executes descendant, child, adjacent, sibling, lists and structural has-text',()=>{const root=node('div');const a=node('span','one','a'), b=node('button','Save','b'), c=node('button','Other','c');append(root,a);append(root,b);append(root,c);for(const s of ['div button','div > button','.a + button','.a ~ button','.no, button:has-text("Save")'])expect(run(buildSnapshotJs(s),[root]).r).toBe(OK);});it('executes exact/lax/regex text and excludes script text (#512)',()=>{const r=node('div'), s=node('span',' Hello World '), script=node('script','secret');append(r,s);append(r,script);expect(run(buildSnapshotJs('text="Hello World"'),[r]).r).toBe(OK);expect(run(buildSnapshotJs('text=hello world'),[r]).r).toBe(OK);expect(run(buildSnapshotJs('text=/world/i'),[r]).r).toBe(OK);expect(run(buildSnapshotJs('text=secret'),[r]).r).toBe(NOT_FOUND);});it('executes native and ARIA state',()=>{const root=node('div'),disabled=node('button','','disabled'),ariaDisabled=node('button','','aria-disabled'),readonly=node('div','','readonly');disabled.attrs.disabled='';ariaDisabled.attrs.role='button';ariaDisabled.attrs['aria-disabled']='true';readonly.attrs.role='textbox';readonly.attrs['aria-readonly']='true';append(root,disabled);append(root,ariaDisabled);append(root,readonly);expect(run(buildSnapshotJs('.disabled'),[root]).enabled).toBe(false);expect(run(buildSnapshotJs('.aria-disabled'),[root]).enabled).toBe(false);expect(run(buildSnapshotJs('.readonly'),[root]).editable).toBe(false);});it('executes deep shadow ordering, focus, hit testing and stale validation',()=>{const host=node('div'), light=node('button','light'), shadow=node('button','shadow');append(host,light);const disabled=node('button');disabled.attrs.disabled='';append(host,disabled);host.shadowRoot={children:[shadow],elementFromPoint:()=>shadow,activeElement:shadow};shadow.getRootNode=()=>host.shadowRoot;shadow.parentElement=null;expect(run(buildSnapshotJs('button >> nth=2'),[host],host,host).focused).toBe(true);expect(run(buildSnapshotJs('button >> nth=1'),[host]).enabled).toBe(false);expect(run(buildSnapshotJs('button'),[host],host,host).focused).toBe(false);expect(run(buildPointerJs('button >> nth=2',1,2),[host],host).hit).toBe(true);const world:any={};const snap=run(buildSnapshotJs('button'),[host],host,host,world);expect(run(buildValidateJs('button',snap.targetId,snap.gen,1,2),[host],host,host,world).r).toBe(OK);expect(run(buildValidateJs('button',999,snap.gen,1,2),[host],host,host,world).r).toBe(STALE);expect(run(buildValidateJs('button',snap.targetId,snap.gen+1,1,2),[host],host,host,world).r).toBe(STALE);expect(run(buildValidateJs('button',snap.targetId,snap.gen,1,2),[host],host,host,{}).r).toBe(STALE);});});
+
+describe('internal engines',()=>{
+ const id=(r:any)=>r.box?.x; // distinct rects identify WHICH element matched
+
+ it('internal:attr i-flag is case-insensitive SUBSTRING on the raw value',()=>{
+ const root=node('div');
+ const p1=node('input');p1.attrs.placeholder='Your Email';p1.rect={x:11,y:0,width:5,height:5};
+ const t1=node('span');t1.attrs.title=' Go ';t1.rect={x:22,y:0,width:5,height:5};
+ append(root,p1);append(root,t1);
+ // 'mail' matches 'Your Email' -- substring, not equality
+ expect(id(run(buildSnapshotJs('internal:attr=[placeholder="mail"i]'),[root]))).toBe(11);
+ // raw value: no trim, no whitespace normalization
+ expect(run(buildSnapshotJs('internal:attr=[title="Go"s]'),[root]).r).toBe(NOT_FOUND);
+ expect(id(run(buildSnapshotJs('internal:attr=[title=" Go "s]'),[root]))).toBe(22);
+ expect(id(run(buildSnapshotJs('internal:attr=[title="go"i]'),[root]))).toBe(22);
+ });
+
+ it('internal:testid is strict equality, never a prefix match',()=>{
+ const root=node('div');
+ const a=node('button');a.attrs['data-testid']='submit-button';a.rect={x:31,y:0,width:5,height:5};
+ const b=node('button');b.attrs['data-testid']='submit';b.rect={x:32,y:0,width:5,height:5};
+ append(root,a);append(root,b);
+ expect(id(run(buildSnapshotJs('internal:testid=[data-testid="submit"s]'),[root]))).toBe(32);
+ expect(run(buildSnapshotJs('internal:testid=[data-testid="sub"s]'),[root]).r).toBe(NOT_FOUND);
+ });
+
+ it('internal:attr supports a regex value and rejects unsupported grammar',()=>{
+ const root=node('div');
+ const el=node('span');el.attrs.title='Go42';el.rect={x:41,y:0,width:5,height:5};
+ append(root,el);
+ expect(id(run(buildSnapshotJs('internal:attr=[title=/^Go\\d+$/]'),[root]))).toBe(41);
+ for(const bad of ['internal:attr=[title]','internal:attr=[title*="Go"]',
+ 'internal:attr=[title=Go]','internal:attr=title="Go"'])
+ expect(run(buildSnapshotJs(bad),[root]).r).toBe(UNSUPPORTED);
+ });
+
+ it('internal:text exact is the full subtree, unlike the public text= engine',()=>{
+ const root=node('div');
+ const btn=node('button','Hello');btn.rect={x:51,y:0,width:5,height:5};
+ const span=node('span','World');span.rect={x:52,y:0,width:5,height:5};
+ append(btn,span);append(root,btn);
+ expect(id(run(buildSnapshotJs('internal:text="HelloWorld"s'),[root]))).toBe(51);
+ // the public engine compares immediate fragments, so it does NOT match
+ expect(run(buildSnapshotJs('text="HelloWorld"'),[root]).r).toBe(NOT_FOUND);
+ });
+
+ it('internal:text keeps the smallest match via direct children only',()=>{
+ const root=node('div');
+ const gp=node('div','X');gp.rect={x:61,y:0,width:5,height:5};
+ const sect=node('section');sect.rect={x:62,y:0,width:5,height:5};
+ const deep=node('span','X');deep.rect={x:63,y:0,width:5,height:5};
+ append(sect,deep);append(gp,sect);append(root,gp);
+ // section's own text matches too, so the innermost element wins
+ expect(id(run(buildSnapshotJs('internal:text="X"s'),[root]))).toBe(63);
+ });
+
+ it('internal:label resolves labelledby, then aria-label, then native labels',()=>{
+ const root=node('div');
+ const ref=node('span','Referenced');ref.attrs.id='lbref';ref.rect={x:71,y:0,width:5,height:5};
+ const byRef=node('input');byRef.attrs['aria-labelledby']='lbref';byRef.rect={x:72,y:0,width:5,height:5};
+ const fallback=node('input');fallback.attrs['aria-labelledby']='missing';
+ fallback.attrs['aria-label']='Fallback';fallback.rect={x:73,y:0,width:5,height:5};
+ const native=node('input');native.rect={x:74,y:0,width:5,height:5};
+ const lbl=node('label','Password');native.labels=[lbl];
+ const divLabel=node('div','x');divLabel.attrs['aria-label']='Div Label';divLabel.rect={x:75,y:0,width:5,height:5};
+ const hidden=node('input');hidden.type='hidden';hidden.rect={x:76,y:0,width:5,height:5};
+ hidden.labels=[node('label','HiddenLabel')];
+ for(const e of [ref,byRef,fallback,native,divLabel,hidden])append(root,e);
+ expect(id(run(buildSnapshotJs('internal:label="Referenced"i'),[root]))).toBe(72);
+ expect(id(run(buildSnapshotJs('internal:label="Fallback"i'),[root]))).toBe(73);
+ expect(id(run(buildSnapshotJs('internal:label="Password"i'),[root]))).toBe(74);
+ expect(id(run(buildSnapshotJs('internal:label="Div Label"i'),[root]))).toBe(75);
+ // a hidden input contributes no native label
+ expect(run(buildSnapshotJs('internal:label="HiddenLabel"i'),[root]).r).toBe(NOT_FOUND);
+ });
+
+ it('public text= excludes a shadow host whose shadow content also matches',()=>{
+ // Regression: __elementText concatenates shadow text into the host, so the
+ // host matches too. contains() cannot see into a shadow root, so the old
+ // smallest-element filter kept the host and (being light DOM) returned it
+ // first. Playwright returns the shadow child.
+ const host=node('div','','host');host.rect={x:81,y:0,width:5,height:5};
+ const shadowChild=node('button','ShadowText');shadowChild.rect={x:82,y:0,width:5,height:5};
+ host.shadowRoot={children:[shadowChild],childNodes:[shadowChild],
+ elementFromPoint:()=>shadowChild,activeElement:null};
+ shadowChild.getRootNode=()=>host.shadowRoot;shadowChild.parentElement=null;
+ expect(id(run(buildSnapshotJs('text=ShadowText'),[host]))).toBe(82);
+ expect(id(run(buildSnapshotJs('internal:text="ShadowText"i'),[host]))).toBe(82);
+ });
+
+ it('leaves role, chaining and single-quoted bodies unsupported',()=>{
+ const root=node('div','x');
+ for(const sel of ['internal:role=button[name="Go"i]','internal:has-text="Go"i',
+ 'internal:control=enter-frame','#a >> #b',
+ "internal:text='Go'"])
+ expect(run(buildSnapshotJs(sel),[root]).r).toBe(UNSUPPORTED);
+ });
+});
diff --git a/tests/test_humanize_unit.py b/tests/test_humanize_unit.py
index 6d3acc9..0387c63 100644
--- a/tests/test_humanize_unit.py
+++ b/tests/test_humanize_unit.py
@@ -16,6 +16,8 @@ import asyncio
import pytest
from unittest.mock import MagicMock
+from cloakbrowser.human.stealth_dom import PROTOCOL_VERSION
+
def _mock_el_evaluate(is_input=False):
"""Mock evaluate that returns is_input for tagName checks and {hit: True} for pointer events."""
@@ -2461,7 +2463,7 @@ class TestPointerEventsFailurePolicy:
page = _no_locator_page(_FakeWorld(None))
start = time.monotonic()
with pytest.raises(StealthEvaluationError):
- check_pointer_events(page, "#x", 1, 100, 100, timeout=1)
+ check_pointer_events(page, "#x", 1, 1, 100, 100, timeout=1)
elapsed_ms = (time.monotonic() - start) * 1000
assert elapsed_ms < 500
@@ -2497,9 +2499,10 @@ def _versioned_fake_payload(response):
if not isinstance(response, dict):
return response
payload = dict(response)
- payload.setdefault("v", 1)
+ payload.setdefault("v", PROTOCOL_VERSION)
if payload.get("r") in ("ok", "stale"):
payload.setdefault("targetId", 1)
+ payload.setdefault("gen", 1)
return payload
@@ -2557,7 +2560,7 @@ class TestStealthDomBuilders:
def test_validate_js_requires_same_target_at_point(self):
from cloakbrowser.human.stealth_dom import build_validate_js
- js = build_validate_js("#x", 7, 1.5, 2.5)
+ js = build_validate_js("#x", 7, 3, 1.5, 2.5)
assert "__id !== 7" in js
assert "r: 'stale'" in js
assert "__deepElementFromPoint(1.5, 2.5)" in js
@@ -2571,12 +2574,15 @@ class TestStealthDomBuilders:
from cloakbrowser.human.stealth_dom import (
parse_result, EVALUATION_FAILED, NOT_FOUND, OK, STALE, UNSUPPORTED,
)
- ok = {"v": 1, "r": "ok", "targetId": 4, "box": {"x": 1}}
+ ok = {"v": 2, "r": "ok", "targetId": 4, "gen": 3, "box": {"x": 1}}
assert parse_result(ok) == (OK, ok)
- assert parse_result({"v": 1, "r": "not_found"}) == (NOT_FOUND, None)
- stale = {"v": 1, "r": "stale", "targetId": 9}
+ assert parse_result({"v": 2, "r": "not_found"}) == (NOT_FOUND, None)
+ stale = {"v": 2, "r": "stale", "targetId": 9, "gen": 3}
assert parse_result(stale) == (STALE, stale)
- assert parse_result({"v": 1, "r": "unsupported"}) == (UNSUPPORTED, None)
+ assert parse_result({"v": 2, "r": "unsupported"}) == (UNSUPPORTED, None)
+ # A payload without the world generation cannot be trusted for identity.
+ assert parse_result({"v": 2, "r": "ok", "targetId": 4}) == (EVALUATION_FAILED, None)
+ assert parse_result({"v": 2, "r": "stale", "targetId": 4}) == (EVALUATION_FAILED, None)
# Malformed/empty evaluation results are explicit failures, never fallback signals.
assert parse_result(None) == (EVALUATION_FAILED, None)
assert parse_result("UNSUPPORTED") == (EVALUATION_FAILED, None)
@@ -2666,8 +2672,8 @@ class TestGetElementBoxStealth:
def test_ok_returns_box_without_playwright(self):
from cloakbrowser.human.scroll import _get_element_box
box = {"x": 10.0, "y": 20.0, "width": 30.0, "height": 40.0}
- page = _no_locator_page(_FakeWorld({"r": "ok", "targetId": 7, "box": box}))
- assert _get_element_box(page, "#x") == {**box, "targetId": 7}
+ page = _no_locator_page(_FakeWorld({"r": "ok", "targetId": 7, "gen": 3, "box": box}))
+ assert _get_element_box(page, "#x") == {**box, "targetId": 7, "gen": 3}
def test_not_found_returns_none_stays_in_world(self):
from cloakbrowser.human.scroll import _get_element_box
@@ -2719,22 +2725,48 @@ class TestCheckPointerEventsStealth:
from cloakbrowser.human.actionability import check_pointer_events
world = _FakeWorld({"r": "ok", "hit": True})
page = _no_locator_page(world)
- check_pointer_events(page, "#x", 1, 5, 5, stealth=world, timeout=200)
+ check_pointer_events(page, "#x", 1, 1, 5, 5, stealth=world, timeout=200)
def test_miss_raises(self):
from cloakbrowser.human.actionability import check_pointer_events, ElementNotReceivingEventsError
world = _FakeWorld({"r": "ok", "hit": False, "covering": "DIV"})
page = _no_locator_page(world)
with pytest.raises(ElementNotReceivingEventsError):
- check_pointer_events(page, "#x", 1, 5, 5, stealth=world, timeout=200)
+ check_pointer_events(page, "#x", 1, 1, 5, 5, stealth=world, timeout=200)
- def test_force_allows_covered_unchanged_target(self):
- from cloakbrowser.human.actionability import check_pointer_events
- world = _FakeWorld({"r": "ok", "hit": False, "covering": "DIV"})
- page = _no_locator_page(world)
- check_pointer_events(
- page, "#x", 1, 5, 5, stealth=world, timeout=200, force=True,
- )
+ def test_force_skips_the_check_entirely(self):
+ """force=True bypasses the pointer check, matching Playwright, where
+ force skips all actionability rather than only coverage rejection."""
+ from unittest.mock import patch
+
+ import cloakbrowser.human as h
+ from cloakbrowser.human.config import resolve_config
+
+ cfg = resolve_config("default")
+ cursor = h._CursorState()
+ cursor.initialized = True
+ cursor.x = 100
+ cursor.y = 100
+
+ page = MagicMock()
+ page.viewport_size = {"width": 1280, "height": 720}
+ page.context.new_cdp_session = MagicMock(side_effect=Exception("no cdp"))
+ page.main_frame = MagicMock()
+ page.main_frame.child_frames = []
+
+ def fake_scroll(page_arg, raw, selector, cx, cy, cfg_arg, timeout=30000):
+ return ({"x": 10, "y": 10, "width": 50, "height": 30, "targetId": 1}, cx, cy, False)
+
+ with patch.object(h, "scroll_to_element", side_effect=fake_scroll), \
+ patch.object(h, "ensure_actionable"), \
+ patch.object(h, "_is_input_element", return_value=False), \
+ patch.object(h, "check_pointer_events") as checked:
+ h.patch_page(page, cfg, cursor)
+ page.click("#x", force=True)
+ assert not checked.called, "force=True must not run the pointer check"
+
+ page.click("#x")
+ assert checked.called, "force=False must still run the pointer check"
def test_stale_target_raises(self):
from cloakbrowser.human.actionability import (
@@ -2743,7 +2775,7 @@ class TestCheckPointerEventsStealth:
world = _FakeWorld({"r": "stale", "targetId": 2})
page = _no_locator_page(world)
with pytest.raises(ElementTargetChangedError):
- check_pointer_events(page, "#x", 1, 5, 5, stealth=world, timeout=200)
+ check_pointer_events(page, "#x", 1, 1, 5, 5, stealth=world, timeout=200)
def test_unsupported_raises_without_fallback(self):
from cloakbrowser.human.actionability import check_pointer_events
@@ -2752,7 +2784,7 @@ class TestCheckPointerEventsStealth:
page = _no_locator_page(world)
with pytest.raises(UnsupportedHumanizeSelectorError):
check_pointer_events(
- page, "internal:role=button", 1, 5, 5,
+ page, "internal:role=button", 1, 1, 5, 5,
stealth=world, timeout=200,
)
@@ -2769,8 +2801,8 @@ class TestStealthAsync:
def test_async_get_element_box_ok(self):
from cloakbrowser.human.scroll_async import _get_element_box_async
box = {"x": 1.0, "y": 2.0, "width": 3.0, "height": 4.0}
- page = _no_locator_page(_AsyncFakeWorld({"r": "ok", "targetId": 9, "box": box}))
- assert asyncio.run(_get_element_box_async(page, "#x")) == {**box, "targetId": 9}
+ page = _no_locator_page(_AsyncFakeWorld({"r": "ok", "targetId": 9, "gen": 3, "box": box}))
+ assert asyncio.run(_get_element_box_async(page, "#x")) == {**box, "targetId": 9, "gen": 3}
# =========================================================================
diff --git a/tests/test_resolver_sources_match.py b/tests/test_resolver_sources_match.py
new file mode 100644
index 0000000..e1591bc
--- /dev/null
+++ b/tests/test_resolver_sources_match.py
@@ -0,0 +1,70 @@
+"""The isolated-world resolver JS is hand-copied into three wrappers.
+
+``cloakbrowser/human/stealth_dom.py``, ``js/src/human/stealthDom.ts`` and
+``dotnet/src/CloakBrowser/Human/StealthDom.cs`` each embed the same resolver as a
+string literal. Nothing generates them, so they can silently drift: a fix landed in
+one wrapper and forgotten in another means that wrapper resolves a *different*
+element and clicks the wrong coordinates, with no test failing.
+
+These tests assert the three literals stay byte-identical, and that the shared JS
+never grows a character that would terminate or corrupt one of the three host
+literals (a backtick or ``${`` breaks the TS ``String.raw``; ``\"\"\"`` breaks the
+Python and C# raw strings).
+"""
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent
+
+PY_SRC = ROOT / "cloakbrowser" / "human" / "stealth_dom.py"
+TS_SRC = ROOT / "js" / "src" / "human" / "stealthDom.ts"
+CS_SRC = ROOT / "dotnet" / "src" / "CloakBrowser" / "Human" / "StealthDom.cs"
+
+_TRIPLE = '"' * 3
+
+
+def _extract(path: Path, pattern: str) -> str:
+ m = re.search(pattern, path.read_text(encoding="utf-8"), re.S)
+ assert m, f"could not find the resolver literal in {path}"
+ return m.group(1)
+
+
+def _resolvers() -> dict[str, str]:
+ return {
+ "python": _extract(PY_SRC, r'_RESOLVER_BODY = r"""(.*?)"""'),
+ "typescript": _extract(TS_SRC, r"RESOLVER_BODY\s*=\s*String\.raw`(.*?)`"),
+ "dotnet": _extract(CS_SRC, r'ResolverBody = """(.*?)"""'),
+ }
+
+
+def test_resolver_bodies_are_byte_identical():
+ bodies = _resolvers()
+ py = bodies["python"]
+ for name, body in bodies.items():
+ if body != py:
+ # Surface the first differing line rather than dumping 17k chars.
+ for i, (a, b) in enumerate(zip(py.splitlines(), body.splitlines()), 1):
+ if a != b:
+ pytest.fail(
+ f"{name} resolver diverges from python at line {i}:\n"
+ f" python: {a!r}\n {name}: {b!r}"
+ )
+ pytest.fail(
+ f"{name} resolver differs from python in length only "
+ f"({len(body)} vs {len(py)} chars)"
+ )
+
+
[email protected]("name", ["python", "typescript", "dotnet"])
+def test_resolver_has_no_host_literal_hazards(name):
+ body = _resolvers()[name]
+ assert "`" not in body, "a backtick terminates the TypeScript String.raw literal"
+ assert "${" not in body, "'${' interpolates inside the TypeScript String.raw literal"
+ assert _TRIPLE not in body, "a triple quote terminates the Python and C# raw strings"
+ assert "\r" not in body, "CR would make the three copies differ by line ending"
+ for i, line in enumerate(body.splitlines(), 1):
+ assert line == line.rstrip(), f"line {i} has trailing whitespace (invisible drift)"
diff --git a/tests/test_stealth_dom_browser.py b/tests/test_stealth_dom_browser.py
index dabd294..84726f4 100644
--- a/tests/test_stealth_dom_browser.py
+++ b/tests/test_stealth_dom_browser.py
@@ -553,3 +553,109 @@ async def test_async_click_rejects_replacement_after_mouse_movement(monkeypatch)
) == "0"
finally:
await browser.close()
+
+
+def test_get_by_engines_match_playwright():
+ """The reimplemented ``internal:*`` engines must resolve the SAME element
+ Playwright's own locator resolves.
+
+ Under-matching yields a typed error; over-matching silently clicks the wrong
+ coordinates. Every case below is one where a plausible-but-wrong shortcut
+ diverges from Playwright:
+
+ * ``get_by_test_id`` is strict equality, so "submit" must NOT match
+ "submit-button", while ``get_by_placeholder``'s ``i`` flag is a
+ case-insensitive SUBSTRING, so "mail" MUST match "Your Email".
+ * attribute values are compared raw, so a padded ``title`` does not match
+ its trimmed form.
+ * ``internal:text`` exact compares the full normalized subtree text, unlike
+ the public ``text=`` engine which compares immediate fragments.
+ * ``<br>`` contributes nothing and shadow-root text is concatenated into
+ the host's text (both are ``__elementText`` parity fixes).
+ * label resolution order is aria-labelledby, aria-label, then ``.labels``,
+ with an unresolvable ``aria-labelledby`` falling through.
+ """
+ import re
+
+ from cloakbrowser import launch
+
+ browser = launch(headless=True, humanize=True, geoip=False)
+ try:
+ page = browser.new_page()
+ page.goto("https://example.com", wait_until="domcontentloaded")
+ page.evaluate(
+ """() => {
+ document.head.innerHTML = '';
+ document.body.innerHTML = `
+ <button id="b1" data-testid="submit-button">Go</button>
+ <button id="b2" data-testid="submit">Go Now</button>
+ <input id="p1" placeholder="Your Email">
+ <img id="a1" alt="Company Logo">
+ <span id="t1" title=" Go ">titled</span>
+ <button id="b3">Hello<span>World</span></button>
+ <div id="brdiv">a<br>b</div>
+ <div id="gp">X<section><span id="deep">X</span></section></div>
+ <label for="in1">Password</label><input id="in1">
+ <label>Wrapped<input id="in2"></label>
+ <input id="in3" aria-label="Aria Labelled">
+ <span id="lbref">Referenced Label</span>
+ <input id="in4" aria-labelledby="lbref">
+ <input id="in5" aria-labelledby="missing-id" aria-label="Fallback Label">
+ <div id="host"></div>`;
+ document.getElementById('host')
+ .attachShadow({mode: 'open'}).innerHTML =
+ '<button id="shadowbtn">DeepShadow</button>';
+ }"""
+ )
+
+ cases = [
+ (page.get_by_test_id("submit"), "b2"),
+ (page.get_by_test_id("submit-button"), "b1"),
+ (page.get_by_placeholder("mail"), "p1"),
+ (page.get_by_placeholder("Your Email", exact=True), "p1"),
+ (page.get_by_alt_text("Company Logo"), "a1"),
+ (page.get_by_title("Go"), "t1"),
+ (page.get_by_text("Go Now"), "b2"),
+ (page.get_by_text("HelloWorld", exact=True), "b3"),
+ (page.get_by_text("X", exact=True), "deep"),
+ (page.get_by_text("ab", exact=True), "brdiv"),
+ (page.get_by_text("DeepShadow"), "shadowbtn"),
+ (page.get_by_text(re.compile(r"^Go Now$")), "b2"),
+ (page.get_by_label("Password"), "in1"),
+ (page.get_by_label("Wrapped"), "in2"),
+ (page.get_by_label("Aria Labelled"), "in3"),
+ (page.get_by_label("Referenced Label"), "in4"),
+ (page.get_by_label("Fallback Label"), "in5"),
+ ]
+ for locator, expected_id in cases:
+ selector = locator._impl_obj._selector
+ playwright_identity = locator.first.evaluate(
+ "el => ({status: 'ok', id: el.id, tag: el.tagName})"
+ )
+ isolated_identity = page._stealth_world.evaluate(
+ _resolve_identity_js(selector)
+ )
+ assert playwright_identity["id"] == expected_id, selector
+ assert isolated_identity == playwright_identity, selector
+
+ # A strict test id must not match by prefix, and a raw attribute value is
+ # never trimmed -- both would be silent over-matches.
+ assert page.get_by_test_id("submit").count() == 1
+ assert page.get_by_title("Go", exact=True).count() == 0
+ assert page._stealth_world.evaluate(
+ _resolve_identity_js(
+ page.get_by_title("Go", exact=True)._impl_obj._selector
+ )
+ ) == {"status": "not_found"}
+
+ # End-to-end: a humanized click through a reimplemented engine.
+ page.get_by_test_id("submit").click()
+
+ # get_by_role is deliberately still unsupported.
+ role_selector = page.get_by_role("button", name="Go Now")._impl_obj._selector
+ assert page._stealth_world.evaluate(
+ _resolve_identity_js(role_selector)
+ ) == {"status": "unsupported"}
+ finally:
+ browser.close()
diff --git a/tests/test_stealth_resolver_js.py b/tests/test_stealth_resolver_js.py
index 374ca4c..bfee2ce 100644
--- a/tests/test_stealth_resolver_js.py
+++ b/tests/test_stealth_resolver_js.py
@@ -96,9 +96,31 @@ eq('mixed shadow first', r.text, 'normal');
r = run('button >> nth=1', [shadowHost, normalButton]);
eq('mixed shadow second', r.text, 'shadow');
-// chaining and get_by_* engines are unsupported
+// chaining and the get_by_* engines we do NOT reimplement stay unsupported
eq('chaining', run('a >> b', [el('A')]).cls, 'unsupported');
eq('internal role', run('internal:role=button', []).cls, 'unsupported');
+for (const sel of ['internal:has-text="Go"i', 'internal:has="x"', 'internal:and="x"',
+ 'internal:or="x"', 'internal:chain="x"', 'internal:control=enter-frame'])
+ eq('unsupported ' + sel, run(sel, []).cls, 'unsupported');
+
+// Engines we DO reimplement route to their engine rather than bailing out.
+// (Semantics live in the browser/stub tiers; el() has no childNodes, so text
+// comparisons here cannot distinguish full-subtree from immediate fragments.)
+eq('internal text routes', run('internal:text="Submit"s', [el('BUTTON','Submit')]).cls, 'ok');
+eq('internal text lax routes', run('internal:text=submit', [el('BUTTON','Submit')]).cls, 'ok');
+eq('internal text no match', run('internal:text="Nope"s', [el('BUTTON','Submit')]).cls, 'not_found');
+// A single-quoted internal body reaches JSON.parse in Playwright and throws.
+eq('internal text single quotes', run("internal:text='Submit'", [el('BUTTON','Submit')]).cls, 'unsupported');
+// Malformed attribute bodies and unsupported operators are refused, not guessed.
+for (const sel of ['internal:attr=[placeholder]', 'internal:attr=[placeholder*="a"]',
+ 'internal:attr=[placeholder=a]', 'internal:attr=placeholder="a"'])
+ eq('bad attr body ' + sel, run(sel, []).cls, 'unsupported');
+// The '>>' guard runs first, so a quoted argument containing '>>' is refused
+// (a documented, deliberate under-match) while a trailing nth= still works.
+eq('internal text with >> in arg', run('internal:text="a >> b"i', []).cls, 'unsupported');
+eq('internal chained', run('internal:text="a"i >> internal:text="b"i', []).cls, 'unsupported');
+eq('internal text keeps nth', run('internal:text=submit >> nth=1',
+ [el('BUTTON','Submit'), el('BUTTON','Submit two')]).cls, 'ok');
// xpath (explicit prefix and leading //)
r = run('xpath=//button', [], [ el('BUTTON','x') ]); eq('xpath= cls', r.cls, 'ok'); eq('xpath= arg', r.calls.xpath, '//button');
@@ -136,6 +158,20 @@ r = run('button, a', [ el('A','first'), el('BUTTON','second') ]);
eq('selector list cls', r.cls, 'ok'); eq('selector list DOM order', r.tag, 'A');
eq('not found', run('button', []).cls, 'not_found');
+// The world generation must fit an Int32: the .NET wrapper carries it as one,
+// and an out-of-range value makes every .NET snapshot fail to parse (Snap()
+// uses TryGetInt32, so an overflowing gen breaks every humanized .NET action).
+const genOnce = new Function(RESOLVER + '\nreturn __state().gen;');
+for (let i = 0; i < 200; i++) {
+ delete globalThis['__cloakHumanDomV1'];
+ const g = genOnce();
+ if (!(Number.isInteger(g) && g >= 0 && g <= 2147483647)) {
+ fails++; console.log('FAIL gen out of Int32 range | got ' + g);
+ break;
+ }
+}
+delete globalThis['__cloakHumanDomV1'];
+
if (fails) { console.log(fails + ' FAILED'); process.exit(1); }
console.log('ALL PASS');
"""
diff --git a/tests/test_stealth_unit.py b/tests/test_stealth_unit.py
index 3ce1e1b..224141c 100644
--- a/tests/test_stealth_unit.py
+++ b/tests/test_stealth_unit.py
@@ -20,6 +20,7 @@ import time
import pytest
from unittest.mock import MagicMock, AsyncMock, patch as mock_patch, call
+from cloakbrowser.human.stealth_dom import PROTOCOL_VERSION
# =========================================================================
@@ -312,7 +313,7 @@ class TestAsyncIsolatedWorld:
def _snapshot_payload(**overrides):
payload = {
- "v": 1, "r": "ok", "targetId": 1,
+ "v": PROTOCOL_VERSION, "r": "ok", "targetId": 1, "gen": 1,
"isInput": False, "focused": False,
}
payload.update(overrides)