captchakraken 5.0.0 → 5.2.0-beta.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,15 +8,17 @@ touch mode that dispatches no motion between taps still has to say where the nex
8
8
 
9
9
  from __future__ import annotations
10
10
 
11
+ import copy
12
+ import dataclasses
11
13
  import math
12
14
  import os
13
15
  import random
14
16
  import time
15
- from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
17
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple
16
18
 
17
- from cursory import generate_trajectory
19
+ from myuri import Vector, generate_random_seed, make_rng, plan_move, plan_type, profile_from_seed
18
20
 
19
- from .kinds import HumanizationMode, PauseKind
21
+ from .kinds import HumanizationMode, PauseKind, Speed
20
22
 
21
23
  Point = Tuple[float, float]
22
24
 
@@ -26,6 +28,15 @@ PAUSE_KINDS = tuple(PauseKind)
26
28
  # How often a held press looks at the widget, in ms: a frame hash per look, so not every frame.
27
29
  HOLD_POLL_MS = (180.0, 320.0)
28
30
 
31
+ # What each speed changes. `settings` is laid under the caller's `humanize_settings` (theirs win, key by key);
32
+ # `pauses` scales every wait between gestures. FAST is a person who has done this captcha a hundred times: the
33
+ # reach is myuri's recorded human path played 2.5x faster, which is still a path and still one event per mouse
34
+ # report. On a three-icon Yidun board it took the mouse from 1.9-3.3s to 1.0-1.2s.
35
+ SPEEDS: Dict[Speed, Dict[str, Any]] = {
36
+ Speed.HUMAN: {"settings": {}, "pauses": 1.0},
37
+ Speed.FAST: {"settings": {"mouse": {"speed_factor": 2.5}, "typing": {"wpm": 110}}, "pauses": 0.5},
38
+ }
39
+
29
40
 
30
41
  def _delay(ms: float) -> None:
31
42
  if ms > 0:
@@ -41,13 +52,14 @@ def _same_point(a: Point, b: Point) -> bool:
41
52
  return abs(float(a[0]) - float(b[0])) < 1e-6 and abs(float(a[1]) - float(b[1])) < 1e-6
42
53
 
43
54
 
44
- # What one mouse event may cover. cursory's samples are up to 250 ms and 560 px apart, which the page sees as a
45
- # cursor that vanishes and reappears: a teleport. A real mouse reports every 8 ms (125 Hz).
46
- MAX_EVENT_GAP_MS = 8.0
47
- MAX_EVENT_STEP_PX = 16.0
55
+ # What one mouse event may cover. myuri plays one sample per recorded report, but a recording's reports can be 70 ms
56
+ # and 230 px apart, which the page sees as a cursor that vanishes and reappears: a teleport. A real mouse reports
57
+ # every 8 ms (125 Hz).
58
+ MAX_EVENT_GAP_MS = 8
59
+ MAX_EVENT_STEP_PX = 16
48
60
  # How far a reach may swing off the straight line between its endpoints: a fraction of its length, at least a few
49
- # pixels. cursory morphs a long recorded movement onto any pair of points, so a 5 px move swung 61 px wide and a
50
- # 140 px one 300 px.
61
+ # pixels. cursory (under myuri) morphs a long recorded movement onto any pair of points, so a 5 px move swung 61 px
62
+ # wide and a 140 px one 300 px.
51
63
  MAX_DEVIATION = 0.15
52
64
  MIN_DEVIATION_PX = 3.0
53
65
 
@@ -75,23 +87,68 @@ def _tame(points: List[Point], start: Point, end: Point) -> List[Point]:
75
87
  def _densify(points: List[Point], timings: List[float]) -> Tuple[List[Point], List[float]]:
76
88
  """Fill every gap wider than one mouse report with evenly timed samples along it."""
77
89
  out_p, out_t = points[:1], timings[:1]
78
- for (a, ta), (b, tb) in zip(zip(points, timings), zip(points[1:], timings[1:])):
79
- dist = ((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2) ** 0.5
80
- n = max(1, int(-(-(tb - ta) // MAX_EVENT_GAP_MS)), int(-(-dist // MAX_EVENT_STEP_PX)))
90
+ for j in range(1, len(points)):
91
+ (ax, ay), (bx, by), ta, tb = points[j - 1], points[j], timings[j - 1], timings[j]
92
+ n = max(1, math.ceil((tb - ta) / MAX_EVENT_GAP_MS), math.ceil(math.hypot(bx - ax, by - ay) / MAX_EVENT_STEP_PX))
81
93
  for i in range(1, n + 1):
82
94
  f = i / n
83
- out_p.append((a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f))
95
+ out_p.append((ax + (bx - ax) * f, ay + (by - ay) * f))
84
96
  out_t.append(ta + (tb - ta) * f)
85
97
  return out_p, out_t
86
98
 
87
99
 
88
- def trajectory(start: Point, end: Point, frequency: int = 60) -> Tuple[List[Point], List[float]]:
89
- """A recorded human movement morphed onto the endpoints, held near the line between them and sampled at
90
- least once per mouse report; timings are cumulative ms."""
91
- points, timings = generate_trajectory(start, end, frequency=frequency)
100
+ def _merge(under: Mapping[str, Any], over: Mapping[str, Any]) -> Dict[str, Any]:
101
+ out = copy.deepcopy(dict(under))
102
+ for key, value in over.items():
103
+ out[key] = _merge(out[key], value) if isinstance(value, Mapping) and isinstance(out.get(key), Mapping) else value
104
+ return out
105
+
106
+
107
+ class Motion:
108
+ """One person's hand: myuri's profile for a seed, and the random stream every path and keystroke draws from.
109
+
110
+ The seed draws the person (each speed within myuri's `variation` of the value set), so one solver moves like
111
+ one person throughout. An unknown settings key raises here, at construction, not mid-solve.
112
+ """
113
+
114
+ def __init__(self, settings: Optional[Mapping[str, Any]] = None, seed: Optional[int] = None,
115
+ speed: Speed = Speed.HUMAN) -> None:
116
+ if settings is not None and not isinstance(settings, Mapping):
117
+ raise ValueError(f"humanize_settings must be a dict of myuri settings, not {type(settings).__name__}")
118
+ self.speed = Speed(speed)
119
+ self.seed = int(seed) if seed is not None else int(generate_random_seed())
120
+ merged = _merge(SPEEDS[self.speed]["settings"], settings or {})
121
+ try:
122
+ profile = profile_from_seed(self.seed, merged)
123
+ except (KeyError, TypeError, ValueError) as exc:
124
+ raise ValueError(f"humanize_settings: {exc.args[0] if exc.args else exc}. See "
125
+ "https://github.com/JWriter20/Myuri#settings for every key") from None
126
+ self.profile = profile
127
+ self.settings: Dict[str, Any] = dataclasses.asdict(profile)
128
+ self.pause_scale = float(SPEEDS[self.speed]["pauses"])
129
+ self.rng = make_rng(self.seed)
130
+
131
+
132
+ def trajectory(start: Point, end: Point, motion: Optional[Motion] = None) -> Tuple[List[Point], List[float]]:
133
+ """myuri's human movement from `start` to `end`, held near the line between them and sampled at least once per
134
+ mouse report; timings are ms from the start of the move."""
135
+ motion = motion or Motion()
92
136
  start, end = (float(start[0]), float(start[1])), (float(end[0]), float(end[1]))
93
- pts = _tame([(float(x), float(y)) for x, y in points], start, end)
94
- return _densify(pts, [float(t) for t in timings])
137
+ if _same_point(start, end):
138
+ return [end], [0.0]
139
+ planned = plan_move(Vector(*start), Vector(*end), motion.rng, settings=motion.settings)
140
+ points = _tame([start] + [(float(p.x), float(p.y)) for p in planned], start, end)
141
+ points[-1] = end
142
+ return _densify(points, [0.0] + [float(p.t) for p in planned])
143
+
144
+
145
+ def resolve_speed(config: Any = None) -> Speed:
146
+ """`config.speed`, else CAPTCHA_SPEED, else human."""
147
+ raw = str(getattr(config, "speed", None) or os.getenv("CAPTCHA_SPEED") or Speed.HUMAN).strip().lower()
148
+ try:
149
+ return Speed(raw)
150
+ except ValueError:
151
+ raise ValueError(f"unknown speed {raw!r}; expected one of {', '.join(s.value for s in Speed)}") from None
95
152
 
96
153
 
97
154
  class Humanizer:
@@ -101,8 +158,9 @@ class Humanizer:
101
158
  hovers = False
102
159
  PAUSES: Dict[PauseKind, Tuple[float, float]] = {}
103
160
 
104
- def __init__(self, start: Point = (0.0, 0.0)) -> None:
161
+ def __init__(self, start: Point = (0.0, 0.0), *, motion: Optional[Motion] = None) -> None:
105
162
  self.at: Point = (float(start[0]), float(start[1]))
163
+ self.motion = motion or Motion()
106
164
 
107
165
  def reset(self, page: Any) -> None:
108
166
  pass
@@ -126,7 +184,8 @@ class Humanizer:
126
184
 
127
185
  def _pause_ms(self, kind: PauseKind) -> float:
128
186
  lo, hi = self.PAUSES.get(kind, (0.0, 0.0))
129
- return random.uniform(lo, hi)
187
+ motion = getattr(self, "motion", None)
188
+ return random.uniform(lo, hi) * (motion.pause_scale if motion is not None else 1.0)
130
189
 
131
190
  def pause(self, kind: PauseKind) -> None:
132
191
  _delay(self._pause_ms(kind))
@@ -183,9 +242,10 @@ class MouseHumanizer(Humanizer):
183
242
  PauseKind.DROP: (50.0, 100.0), PauseKind.PROBE: (40.0, 80.0), PauseKind.SETTLE: (90.0, 210.0),
184
243
  PauseKind.KEY: (45.0, 135.0)}
185
244
 
186
- def __init__(self, start: Point = (0.0, 0.0), frequency: int = 60) -> None:
187
- super().__init__(start)
188
- self._frequency = frequency
245
+ def __init__(self, start: Point = (0.0, 0.0), frequency: Optional[int] = None, *,
246
+ motion: Optional[Motion] = None) -> None:
247
+ # `frequency` is accepted and ignored since 5.2.0: myuri samples at the recording's own report rate.
248
+ super().__init__(start, motion=motion)
189
249
  self._viewport_cache: Optional[Dict[str, float]] = None
190
250
  self._down = False
191
251
  self._cursor_seeded = False
@@ -271,7 +331,7 @@ class MouseHumanizer(Humanizer):
271
331
  if self._browser_draws_path:
272
332
  self._trace(page, [to], [0.0])
273
333
  return
274
- points, timings = trajectory(self.at, to, self._frequency)
334
+ points, timings = trajectory(self.at, to, self.motion)
275
335
  self._trace(page, points, timings)
276
336
 
277
337
  def drift(self, page: Any, to: Point) -> None:
@@ -305,14 +365,23 @@ class MouseHumanizer(Humanizer):
305
365
  page.keyboard.press("Control+A")
306
366
  except Exception:
307
367
  pass
308
- # Per character, not `type(text, delay=…)`: a constant inter-key delay is itself a signal these vendors score.
309
- for ch in text:
368
+ # myuri's keystrokes, not `type(text, delay=…)`: a constant inter-key delay is itself a signal these vendors
369
+ # score. Each key is pressed and released at its planned time, rollover and the odd corrected typo included.
370
+ typing = self.motion.profile.typing
371
+ steps = plan_type(text, self.motion.rng, wpm=typing.wpm, mistake_multiplier=typing.mistake_multiplier,
372
+ pauses=typing.pauses)
373
+ start = time.monotonic() * 1000.0
374
+ keyboard = page.keyboard
375
+ for t, kind, key in steps:
376
+ _delay(start + t - time.monotonic() * 1000.0)
310
377
  try:
311
- page.keyboard.type(ch)
378
+ if kind == "insert":
379
+ keyboard.insert_text(key)
380
+ else:
381
+ getattr(keyboard, kind)(key)
312
382
  except Exception as exc:
313
383
  _log(f"could not type into the captcha field: {exc}")
314
384
  return False
315
- self.pause(PauseKind.KEY)
316
385
  return True
317
386
 
318
387
 
@@ -490,12 +559,12 @@ class MobileHumanizer(Humanizer):
490
559
  PauseKind.KEY: (110.0, 320.0)}
491
560
 
492
561
  def __init__(self, start: Point = (0.0, 0.0), backend: Any = None, driver: Any = None,
493
- frequency: int = 90, **backend_kwargs: Any) -> None:
494
- super().__init__(start)
562
+ frequency: Optional[int] = None, *, motion: Optional[Motion] = None, **backend_kwargs: Any) -> None:
563
+ # `frequency` is accepted and ignored since 5.2.0, as on MouseHumanizer.
564
+ super().__init__(start, motion=motion)
495
565
  self._backend: Optional[TouchBackend] = backend
496
566
  self._driver = driver
497
567
  self._backend_kwargs = backend_kwargs
498
- self._frequency = frequency
499
568
  self._down = False
500
569
 
501
570
  def reset(self, page: Any) -> None:
@@ -515,7 +584,7 @@ class MobileHumanizer(Humanizer):
515
584
  def move(self, page: Any, to: Point) -> None:
516
585
  to = (float(to[0]), float(to[1]))
517
586
  if self._down:
518
- points, timings = trajectory(self.at, to, self._frequency)
587
+ points, timings = trajectory(self.at, to, self.motion)
519
588
  self._touch(page).move([(x, y, timings[i] - (timings[i - 1] if i else 0.0))
520
589
  for i, (x, y) in enumerate(points)])
521
590
  self.at = to
@@ -631,7 +700,8 @@ def resolve(config: Any) -> Humanizer:
631
700
  raise ValueError(f"unknown humanization mode {raw!r}; expected one of {', '.join(sorted(MODES))}, "
632
701
  "or pass your own object as PageSolverConfig.humanizer") from None
633
702
  start = getattr(config, "starting_mouse_position", None) or (0.0, 0.0)
703
+ motion = Motion(getattr(config, "humanize_settings", None), speed=resolve_speed(config))
634
704
  if mode is HumanizationMode.MOBILE:
635
- return MobileHumanizer(start, driver=getattr(config, "touch_driver", None),
705
+ return MobileHumanizer(start, driver=getattr(config, "touch_driver", None), motion=motion,
636
706
  **(getattr(config, "touch_transform", None) or {}))
637
- return MODES[mode](start)
707
+ return MODES[mode](start, motion=motion)
@@ -102,6 +102,13 @@ class HumanizationMode(StrEnum):
102
102
  NONE = "none"
103
103
 
104
104
 
105
+ class Speed(StrEnum):
106
+ """How fast the hand goes. HUMAN is an ordinary person; FAST is one who has done this captcha a hundred times."""
107
+
108
+ HUMAN = "human"
109
+ FAST = "fast"
110
+
111
+
105
112
  class PauseKind(StrEnum):
106
113
  TAP = "tap"
107
114
  BETWEEN = "between"
@@ -178,6 +178,45 @@
178
178
  },
179
179
  "note": "Midnight V2 4B at bf16. The full-precision alternative to the default Q4 checkpoint."
180
180
  },
181
+ "CaptchaKraken/AbyssV2-q4": {
182
+ "availability": "licensed",
183
+ "prompt_version": "4",
184
+ "kind": "merged",
185
+ "base_model": "CaptchaKraken/AbyssV2-q4",
186
+ "lora_revision": "main",
187
+ "lora_name": "captcha-pointer",
188
+ "pixel_budget": {
189
+ "min": 4096,
190
+ "max": 518400
191
+ },
192
+ "note": "Abyss V2, the licensed pointer model, at Q4: the checkpoint `captchakraken fetch abyss` installs. Same architecture, heads and pixel band as Midnight V2 4B Q4, so it is served the same way. Its repo is gated and open to Abyss Licence holders."
193
+ },
194
+ "CaptchaKraken/AbyssV2": {
195
+ "availability": "licensed",
196
+ "prompt_version": "4",
197
+ "kind": "merged",
198
+ "base_model": "CaptchaKraken/AbyssV2",
199
+ "lora_revision": "main",
200
+ "lora_name": "captcha-pointer",
201
+ "pixel_budget": {
202
+ "min": 4096,
203
+ "max": 518400
204
+ },
205
+ "note": "Abyss V2 at bf16, the full-precision alternative to AbyssV2-q4. Gated like it."
206
+ },
207
+ "CaptchaKraken/CaptchaKraken-Custom-Yidun-Commision": {
208
+ "availability": "licensed",
209
+ "prompt_version": "4",
210
+ "kind": "merged",
211
+ "base_model": "CaptchaKraken/CaptchaKraken-Custom-Yidun-Commision",
212
+ "lora_revision": "main",
213
+ "lora_name": "captcha-pointer",
214
+ "pixel_budget": {
215
+ "min": 4096,
216
+ "max": 518400
217
+ },
218
+ "note": "A custom model for Yidun icon click-in-order boards: Abyss V2 tuned on them, at Q4. Same architecture, heads and pixel band as AbyssV2-q4, so it is served the same way. Sold separately: its gated repo opens by hand once a purchase is confirmed, and `captchakraken fetch custom-yidun` installs it."
219
+ },
181
220
  "CaptchaKraken/CaptchaKraken-Lora-v1.2": {
182
221
  "prompt_version": "2",
183
222
  "kind": "lora",
@@ -23,7 +23,7 @@ from . import config, planner
23
23
  from .action_types import CaptchaAction
24
24
  from .humanize import Humanizer, hold, resolve as resolve_humanizer
25
25
  from .kinds import (ActionKind, FrameRole, HumanizationMode, KeyframeMode, PauseKind, Phase, PromptFamily,
26
- RecaptchaBanner, RetryMode, SettleVerdict, Vendor, Verdict)
26
+ RecaptchaBanner, RetryMode, SettleVerdict, Speed, Vendor, Verdict)
27
27
  from .selectors import DEFAULT_CONFIG_PATH, DEFAULT_TABLE, SelectorTable, VendorSelectors, WidgetProbe
28
28
  from .server_manager import ensure_server
29
29
  from .solver import AnimatedRecording, CaptchaSolver, UnsupportedCaptchaError, cut_recording
@@ -130,6 +130,22 @@ def _viewport_of(page: Any) -> Dict[str, float]:
130
130
  return page.viewport_size or page.evaluate(_VIEWPORT_JS)
131
131
 
132
132
 
133
+ # Gecko answers with a number and Chromium/WebKit have no such property. Camoufox spoofs the user agent, not this.
134
+ _GECKO_JS = "() => typeof mozInnerScreenX === 'number'"
135
+
136
+
137
+ def _draws_clips_offscreen(page: Any) -> bool:
138
+ """Is this Firefox, whose clipped capture renders the rect offscreen (`drawSnapshot`) and repaints nothing?
139
+
140
+ Chromium is the engine that flashes on a clip, and the reason every other capture is viewport-and-crop. On Firefox
141
+ the full viewport costs ~420ms to the clip's ~100ms; a still Yidun board took 8 of them, 2.6s of its solve.
142
+ """
143
+ try:
144
+ return page.evaluate(_GECKO_JS) is True
145
+ except Exception:
146
+ return False
147
+
148
+
133
149
  def _layout_is_the_viewport(page: Any, view: Dict[str, float]) -> bool:
134
150
  """Does a viewport capture speak the bounding box's coordinates? Not on a page laid out wider than the device and zoomed out to fit, which is every mobile layout of a desktop page: there the box is in layout pixels and the capture is not."""
135
151
  frame = page.evaluate(_FRAME_JS)
@@ -321,6 +337,11 @@ HOLD_MAX_MS = 12000
321
337
  class PageSolverConfig:
322
338
  humanization: Optional[HumanizationMode] = None
323
339
  humanizer: Optional[Humanizer] = None
340
+ # "human" (default) or "fast": fast plays myuri's recorded paths 2.5x faster and halves the waits between
341
+ # gestures. CAPTCHA_SPEED sets it when this is None.
342
+ speed: Optional[Speed] = None
343
+ # myuri settings laid over the speed's, e.g. {"mouse": {"speed_factor": 3}}; an unknown key raises at construction.
344
+ humanize_settings: Optional[Dict[str, Any]] = None
324
345
  # Every URL pattern and selector the solver detects and drives with: a path to a config file of the shape of the
325
346
  # repository's `captchakraken.config.json`, or the parsed object. What it gives is laid over the shipped default,
326
347
  # so a file holding only a `custom` entry adds that entry and keeps every built-in vendor.
@@ -418,6 +439,9 @@ VENDORS_WITH_BESPOKE_HANDLING: frozenset[Vendor] = frozenset({Vendor.HCAPTCHA, V
418
439
 
419
440
  # Long enough to resolve a locator `all()` just returned, short enough that a widget gone in between reads as stale, not hung.
420
441
  HANDLE_TIMEOUT_MS = 1000
442
+ # How many frames deep a widget is looked for. Imperva's block page wrapping hCaptcha's enclave is two; the rest is room
443
+ # for a site that frames such a page. Mirrors solver.ts FRAME_DEPTH.
444
+ FRAME_DEPTH = 4
421
445
 
422
446
 
423
447
  def _visible(scope: Any, selectors: Sequence[str]) -> List[Any]:
@@ -478,10 +502,26 @@ def _still_shown(element: Any) -> bool:
478
502
  return False
479
503
 
480
504
 
481
- def _host_scopes(page: Any, enclaves: Sequence[str]) -> List[Any]:
482
- """Where the host-page selectors are read: the page, then the inside of every VISIBLE vendor enclave. A hidden enclave
483
- is skipped because Playwright judges an element visible within its own document, whatever its frame's visibility."""
484
- return [page, *(f for f in map(_frame_of, _visible(page, enclaves)) if f is not None)]
505
+ def _holds_any(scope: Any, selector: str) -> bool:
506
+ """The scope holds a match of `selector`. A scope that cannot be asked is kept: dropping it could hide a widget."""
507
+ try:
508
+ return scope.locator(selector).count() > 0
509
+ except Exception:
510
+ return True
511
+
512
+
513
+ def _host_scopes(page: Any, sel: SelectorTable) -> List[Any]:
514
+ """Where the host-page selectors are read: the page, then the inside of every VISIBLE frame a widget may sit in, a
515
+ level at a time, to FRAME_DEPTH levels. A hidden frame is not entered because Playwright judges an element visible
516
+ within its own document, whatever its frame's visibility. A frame holding nothing of any vendor's is walked through
517
+ but not kept, so a page of ads costs a count per frame, not every probe per frame."""
518
+ scopes, level = [page], [page]
519
+ for _ in range(FRAME_DEPTH):
520
+ level = [f for scope in level for f in map(_frame_of, _visible(scope, sel.frames)) if f is not None]
521
+ if not level:
522
+ break
523
+ scopes.extend(f for f in level if _holds_any(f, sel.markers))
524
+ return scopes
485
525
 
486
526
 
487
527
  def _visible_in(scopes: Sequence[Any], selectors: Sequence[str]) -> List[Any]:
@@ -653,6 +693,8 @@ class PageSolver:
653
693
 
654
694
  def _reset_animated_state(self) -> None:
655
695
  self._acted_on_board = False
696
+ # (page, is Firefox), asked once per page: see _draws_clips_offscreen.
697
+ self._gecko: Optional[Tuple[Any, bool]] = None
656
698
  self._submitted_on_board = False
657
699
  self._known_animated = False
658
700
  self._animated_probe_armed = False
@@ -1539,7 +1581,7 @@ class PageSolver:
1539
1581
 
1540
1582
  def detect_captcha(self, page: Any) -> Optional[Widget]:
1541
1583
  """Open challenges first, then unsolved checkboxes, then the inline vendors."""
1542
- scopes = _host_scopes(page, self._sel.enclave)
1584
+ scopes = _host_scopes(page, self._sel)
1543
1585
  for probe in self._sel.widget_probes:
1544
1586
  at = next(iter(_visible_in(scopes, (probe.selector,))), None)
1545
1587
  if at is None or self._already_accepted(scopes, at, probe):
@@ -1567,7 +1609,7 @@ class PageSolver:
1567
1609
  def _unmatched_vendor_frames(self, page: Any) -> List[Vendor]:
1568
1610
  """Vendors showing a frame no selector names. Only asked once detection has found nothing, and a passive frame
1569
1611
  (an invisible badge, an enclave) is not a widget, so what is left is markup the table no longer matches."""
1570
- scopes = _host_scopes(page, self._sel.enclave)
1612
+ scopes = _host_scopes(page, self._sel)
1571
1613
  return [vendor for vendor, s in self._sel.vendors if s.hosts and len(_visible_in(scopes, [f'iframe[src*="{h}"]' for h in s.hosts]))
1572
1614
  > len(_visible_in(scopes, s.passive))]
1573
1615
 
@@ -1600,7 +1642,7 @@ class PageSolver:
1600
1642
 
1601
1643
  def _is_blocked(self, page: Any) -> bool:
1602
1644
  """The vendor showing its refusal screen: rate-limited or flagged, with no board to answer."""
1603
- scopes = _host_scopes(page, self._sel.enclave)
1645
+ scopes = _host_scopes(page, self._sel)
1604
1646
  for probe in self._sel.widget_probes:
1605
1647
  blocked = self._sel.selectors[probe.vendor].blocked
1606
1648
  if probe.role != FrameRole.CHALLENGE or not blocked:
@@ -1619,7 +1661,7 @@ class PageSolver:
1619
1661
  def is_captcha_solved(self, page: Any) -> bool:
1620
1662
  """The vendor's own done signal: a response token, a painted success state, or a checked box."""
1621
1663
  try:
1622
- scopes = _host_scopes(page, self._sel.enclave)
1664
+ scopes = _host_scopes(page, self._sel)
1623
1665
  if any(self._has_value(scopes, s) for s in self._sel.response) or _visible_in(scopes, self._sel.accepted):
1624
1666
  return True
1625
1667
  for probe in self._sel.widget_probes:
@@ -1642,7 +1684,7 @@ class PageSolver:
1642
1684
  def _is_challenge_freshly_rendered(self, page: Any) -> bool:
1643
1685
  """A next round has painted, as opposed to the answered frame animating closed."""
1644
1686
  try:
1645
- scopes = _host_scopes(page, self._sel.enclave)
1687
+ scopes = _host_scopes(page, self._sel)
1646
1688
  for probe in self._sel.widget_probes:
1647
1689
  fresh = self._sel.selectors[probe.vendor].fresh
1648
1690
  if probe.role != FrameRole.CHALLENGE or not fresh:
@@ -1663,7 +1705,7 @@ class PageSolver:
1663
1705
  def _banner_kind(self, page: Any) -> Optional[RecaptchaBanner]:
1664
1706
  """Which verdict banner the open challenge shows; `dynamic-more` is the dynamic board's normal flow, not an error."""
1665
1707
  try:
1666
- scopes = _host_scopes(page, self._sel.enclave)
1708
+ scopes = _host_scopes(page, self._sel)
1667
1709
  for probe in self._sel.widget_probes:
1668
1710
  banners = self._sel.selectors[probe.vendor].banners
1669
1711
  if probe.role != FrameRole.CHALLENGE or not banners:
@@ -1783,9 +1825,10 @@ class PageSolver:
1783
1825
  animations: str = "disabled", style: Optional[str] = None, scale: str = "device") -> None:
1784
1826
  """Every capture the driver takes: the whole viewport, cropped here to the element.
1785
1827
 
1786
- Never a clipped capture. An element screenshot, or any `clip`, makes a headed Chromium repaint the page at
1787
- the clip's size for that frame, which the user watches as the page flashing and jumping; a viewport
1788
- capture repaints nothing, and measured twice as fast. Short timeout; `disabled` freezes CSS animation,
1828
+ Never a clipped capture on Chromium. An element screenshot, or any `clip`, makes a headed Chromium repaint
1829
+ the page at the clip's size for that frame, which the user watches as the page flashing and jumping; a
1830
+ viewport capture repaints nothing, and measured twice as fast. Firefox is the exception: it draws a clip
1831
+ offscreen, and there the clip is four times faster than the viewport (see `_draws_clips_offscreen`). Short timeout; `disabled` freezes CSS animation,
1789
1832
  so bursts and the keyframe gate pass `allow`. `style` is CSS applied for this capture only. `scale="css"`
1790
1833
  takes one pixel per CSS pixel: the slide loop's choice, since on a phone (DPR 2.6) a device-pixel frame is
1791
1834
  seven times the pixels and its tracking took 4.7 s of an 11.6 s solve.
@@ -1801,8 +1844,13 @@ class PageSolver:
1801
1844
  # coordinates, so the element photographs itself.
1802
1845
  _shot(element.screenshot, style, path=path, timeout=timeout, animations=animations, **kw)
1803
1846
  return
1804
- png = crop_png(_shot(page.screenshot, style, timeout=timeout, animations=animations, **kw), rect,
1805
- view["width"])
1847
+ if self._gecko is None or self._gecko[0] is not page:
1848
+ self._gecko = (page, _draws_clips_offscreen(page))
1849
+ if self._gecko[1]:
1850
+ png = _shot(page.screenshot, style, timeout=timeout, animations=animations, clip=rect._asdict(), **kw)
1851
+ else:
1852
+ png = crop_png(_shot(page.screenshot, style, timeout=timeout, animations=animations, **kw), rect,
1853
+ view["width"])
1806
1854
  with open(path, "wb") as fh:
1807
1855
  fh.write(png)
1808
1856
 
@@ -263,8 +263,17 @@ class SelectorTable:
263
263
  for vendor, s in self.vendors
264
264
  for selector in getattr(s, key))
265
265
  self.enclave: Sequence[str] = self._of_every_vendor("enclave")
266
+ # The frames a widget may sit inside: a vendor's enclave, or any frame no vendor serves (a block page, a modal,
267
+ # an embed). A vendor's own frame is its widget, read through the probes, never searched as a page.
268
+ self.frames: Sequence[str] = (
269
+ *self.enclave, "iframe" + "".join(f':not([src*="{h}"])' for _, v in self.vendors for h in v.hosts))
266
270
  self.response: Sequence[str] = tuple(s.response for _, s in self.vendors if s.response)
267
271
  self.accepted: Sequence[str] = tuple(s.accepted for _, s in self.vendors if s.accepted)
272
+ # Anything of a vendor's a document can hold. A frame walked into that holds none of it (an ad, a login button) is
273
+ # passed through to the frames inside it, but no probe is read in it: every probe costs a round trip per frame.
274
+ self.markers: str = ", ".join(dict.fromkeys((
275
+ *(p.selector for p in self.widget_probes), *self.response, *self.accepted, *self.enclave,
276
+ *self._of_every_vendor("passive"), *(f'iframe[src*="{h}"]' for _, v in self.vendors for h in v.hosts))))
268
277
  # A real Verify/Next/Submit/Skip/Confirm first; the vendor-named controls are fallbacks.
269
278
  self.submit_vendor: Sequence[str] = self._of_every_vendor("submit")
270
279
  self.submit: Sequence[str] = (*map(submit_by_text, loaded.generic["submit_text"]), *self.submit_vendor)
@@ -289,6 +298,7 @@ DEFAULT_TABLE = SelectorTable(config=DEFAULT_CONFIG)
289
298
  VENDORS = DEFAULT_TABLE.vendors
290
299
  WIDGET_PROBES = DEFAULT_TABLE.widget_probes
291
300
  ENCLAVE_SELECTORS = DEFAULT_TABLE.enclave
301
+ FRAME_SELECTORS = DEFAULT_TABLE.frames
292
302
  RESPONSE_SELECTORS = DEFAULT_TABLE.response
293
303
  ACCEPTED_SELECTORS = DEFAULT_TABLE.accepted
294
304
  SUBMIT_SELECTORS = DEFAULT_TABLE.submit