captchakraken 5.0.0-beta.50 → 5.0.0-beta.51

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.
@@ -67,6 +67,7 @@ export interface PlaywrightResponse {
67
67
  request?(): {
68
68
  resourceType?(): string;
69
69
  };
70
+ headers?(): Record<string, string>;
70
71
  }
71
72
  /**
72
73
  * Structural on purpose: the package depends on no browser library, and the version skew between
package/dist/solver.js CHANGED
@@ -886,14 +886,23 @@ class CaptchaKrakenSolver {
886
886
  const filmable = puzzleSource !== kinds_1.Vendor.RECAPTCHA && !textMode;
887
887
  if (filmable && !this.knownAnimated)
888
888
  await this.stepOffTheBoard(page, captchaElement);
889
+ // What the vendor's network said about this board (verdicts.ts MOTION_SIGNALS); null films it to find out.
890
+ const dealtMotion = filmable && this.verdicts ? await this.verdicts.boardMotion(puzzleSource) : null;
889
891
  let isAnimated = false;
890
892
  if (filmable && cfg.videoSolveEnabled === false) {
891
- if (await this.ph(kinds_1.Phase.SETTLE, () => this.waitForElementSettled(captchaElement)) === kinds_1.SettleVerdict.ANIMATED) {
893
+ if (dealtMotion === true
894
+ || await this.ph(kinds_1.Phase.SETTLE, () => this.waitForElementSettled(captchaElement)) === kinds_1.SettleVerdict.ANIMATED) {
892
895
  const e = new Error('ANIMATED_CHALLENGE: the challenge never settles and videoSolveEnabled is off.');
893
896
  e.animated = true;
894
897
  throw e;
895
898
  }
896
899
  }
900
+ else if (filmable && dealtMotion === true && !this.knownAnimated) {
901
+ // The vendor dealt this board as a video: waiting for it to settle would only wait out a cycle.
902
+ console.log('[animated] the vendor dealt this board as a video — filming it');
903
+ await this.releasePendingBurst();
904
+ isAnimated = this.knownAnimated = true;
905
+ }
897
906
  else if (filmable) {
898
907
  isAnimated = await this.classifyByRecording(captchaElement) === kinds_1.SettleVerdict.ANIMATED;
899
908
  }
@@ -1038,7 +1047,7 @@ class CaptchaKrakenSolver {
1038
1047
  }
1039
1048
  }
1040
1049
  }
1041
- if (!response && this.shouldSpeculate(puzzleSource, textMode)) {
1050
+ if (!response && this.shouldSpeculate(puzzleSource, textMode, dealtMotion)) {
1042
1051
  // Ask the still and film at once. No idle wander: a moving cursor reads as new screens.
1043
1052
  const rec = this.pendingBurst ?? this.startKeyframeBurst(captchaElement);
1044
1053
  this.pendingBurst = null;
@@ -2600,7 +2609,7 @@ class CaptchaKrakenSolver {
2600
2609
  if (rec)
2601
2610
  await rec.abandon();
2602
2611
  }
2603
- shouldSpeculate(puzzleSource, textMode) {
2612
+ shouldSpeculate(puzzleSource, textMode, dealtMotion = null) {
2604
2613
  if (this.config.videoSolveEnabled === false)
2605
2614
  return false;
2606
2615
  if (this.config.speculativeBurstEnabled === false)
@@ -2616,6 +2625,9 @@ class CaptchaKrakenSolver {
2616
2625
  // budget (measured on the 5.0 Tier 3 run), and a still answer that fails earns the film next round.
2617
2626
  if (this.sel.selectors[puzzleSource]?.stillsOnly)
2618
2627
  return false;
2628
+ // So is a board its vendor dealt as a still file; the burst stays for every board no network has described.
2629
+ if (dealtMotion === false)
2630
+ return false;
2619
2631
  return true;
2620
2632
  }
2621
2633
  /** One second look per solve: a repeated answer arms it, and the recording it takes spends it. */
@@ -24,6 +24,30 @@ export declare function endpointFor(url: string): {
24
24
  endpoint: VerdictEndpoint;
25
25
  } | null;
26
26
  export declare function readVerdict(url: string, status: number, body: string): RoundVerdict | null;
27
+ export interface MotionSignal {
28
+ /** A URL substring naming the response that carries the board, or names its kind. */
29
+ marker: string;
30
+ read: (contentType: string, body: string) => boolean | null;
31
+ needsBody: boolean;
32
+ }
33
+ export declare const MOTION_SIGNALS: Partial<Record<Vendor, readonly MotionSignal[]>>;
34
+ export declare const TIMELINE_JS = "() => {\n const all = performance.getEntriesByType('resource');\n return {full: all.length >= 250, entries: all.map(e => [e.initiatorType, e.name])};\n}";
35
+ export interface Timeline {
36
+ full?: boolean;
37
+ entries?: [string, string][];
38
+ }
39
+ interface TimelineBoard {
40
+ deal: string;
41
+ board: string;
42
+ read: (initiator: string, url: string) => boolean | null;
43
+ }
44
+ export declare const TIMELINE_BOARDS: Partial<Record<Vendor, TimelineBoard>>;
45
+ /** What one frame's resource timeline says about the vendor's latest board, or null. */
46
+ export declare function motionFromTimeline(vendor: Vendor, timeline: Timeline | null | undefined): boolean | null;
47
+ export declare function motionSignalFor(url: string): {
48
+ vendor: Vendor;
49
+ signal: MotionSignal;
50
+ } | null;
27
51
  /**
28
52
  * Every verdict the page's network carries while a solve runs.
29
53
  *
@@ -39,6 +63,12 @@ export declare class VerdictLog {
39
63
  private read;
40
64
  private pending;
41
65
  private readonly listener;
66
+ /** What each vendor's network said about its current board: true moves, false is still. */
67
+ private readonly motion;
68
+ private readonly deals;
69
+ private noteMotion;
70
+ /** Whether the vendor dealt its current board as a moving one; null when its network has not said. */
71
+ boardMotion(vendor: Vendor): Promise<boolean | null>;
42
72
  constructor(page: PlaywrightPage);
43
73
  /** The verdicts that arrived since the last call, once every body already on the wire has been read. */
44
74
  fresh(): Promise<RoundVerdict[]>;
@@ -46,3 +76,4 @@ export declare class VerdictLog {
46
76
  decisive(): Verdict | null;
47
77
  close(): Promise<void>;
48
78
  }
79
+ export {};
package/dist/verdicts.js CHANGED
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.VerdictLog = exports.VERDICT_ENDPOINTS = void 0;
3
+ exports.VerdictLog = exports.TIMELINE_BOARDS = exports.TIMELINE_JS = exports.MOTION_SIGNALS = exports.VERDICT_ENDPOINTS = void 0;
4
4
  exports.endpointFor = endpointFor;
5
5
  exports.readVerdict = readVerdict;
6
+ exports.motionFromTimeline = motionFromTimeline;
7
+ exports.motionSignalFor = motionSignalFor;
6
8
  /**
7
9
  * The vendor's own answer to each submitted round, read off the wire. Mirrors python/src/captchakraken/verdicts.py.
8
10
  *
@@ -113,6 +115,89 @@ function readVerdict(url, status, body) {
113
115
  const verdict = status >= 200 && status < 300 ? found.endpoint.read(body) : null;
114
116
  return verdict ? { vendor: found.vendor, verdict } : null;
115
117
  }
118
+ // ── whether a board moves, read off the file it is dealt as ──────────────────
119
+ // Measured 2026-11-14 on the live demos. hCaptcha (46 deals over three sitekeys) loads each board from
120
+ // imgs*.hcaptcha.com/tip/: image/jpeg for every still deal, video/webm for every animated one. GeeTest v4's /load names
121
+ // its challenge in plain JSONP, and only the two svg types moved (22 deals over seven demo pages). A vendor, file or
122
+ // type not listed here gives no hint, and the driver films the board to find out, as it always has.
123
+ const GEETEST_MOVING = new Set(['svg_icon', 'svg_seed']);
124
+ const GEETEST_STILL = new Set(['slide', 'icon', 'nine', 'match', 'winlinze']);
125
+ const mediaMoves = (contentType) => {
126
+ // A GIF may move, so it says nothing either way; every still hCaptcha board measured was a jpeg or a png.
127
+ const type = contentType.split(';', 1)[0].trim().toLowerCase();
128
+ if (type === 'image/gif')
129
+ return null;
130
+ const kind = type.split('/', 1)[0];
131
+ return kind === 'video' ? true : kind === 'image' ? false : null;
132
+ };
133
+ // GenerateCaptcha names the board's file in HtmlFormate; every one measured (4 deals) was a GIF that moved.
134
+ const cybersiaraBoardMoves = (_contentType, body) => {
135
+ const board = parse(body)?.HtmlFormate;
136
+ return typeof board === 'string' && board.toLowerCase().split('?', 1)[0].endsWith('.gif') ? true : null;
137
+ };
138
+ const geetestTypeMoves = (_contentType, body) => {
139
+ const start = body.indexOf('(');
140
+ const end = body.lastIndexOf(')');
141
+ const data = (start >= 0 && start < end ? parse(body.slice(start + 1, end)) : null);
142
+ const kind = data?.data?.captcha_type;
143
+ if (typeof kind !== 'string')
144
+ return null;
145
+ return GEETEST_MOVING.has(kind) ? true : GEETEST_STILL.has(kind) ? false : null;
146
+ };
147
+ exports.MOTION_SIGNALS = {
148
+ [kinds_1.Vendor.HCAPTCHA]: [{ marker: 'hcaptcha.com/tip/', read: mediaMoves, needsBody: false }],
149
+ [kinds_1.Vendor.GEETEST]: [{ marker: 'geetest.com/load', read: geetestTypeMoves, needsBody: true }],
150
+ [kinds_1.Vendor.CYBERSIARA]: [{ marker: 'mycybersiara.com/api/GenerateCaptcha', read: cybersiaraBoardMoves, needsBody: true }],
151
+ };
152
+ // ── the same, read back from a frame's performance timeline ──────────────────
153
+ // The listener hears only what loads after solve() starts. A widget the caller opened first, or a board the browser
154
+ // served from its cache, was dealt before then, and each frame's resource timeline still lists what it loaded and what
155
+ // loaded it. Only entries after the vendor's latest deal count, and a full buffer (where new entries are dropped and the
156
+ // latest deal may be missing) says nothing. Measured 2026-11-14: GeeTest's board files sit under
157
+ // static.geetest.com/captcha_v4/policy/<id>/<captcha_type>/, hCaptcha's under /tip/ loaded by an img, CyberSiara's as
158
+ // a GIF under embed.mycybersiara.com/CyberSiara/.
159
+ exports.TIMELINE_JS = `() => {
160
+ const all = performance.getEntriesByType('resource');
161
+ return {full: all.length >= 250, entries: all.map(e => [e.initiatorType, e.name])};
162
+ }`;
163
+ const hcaptchaTipMoves = (initiator) => ['video', 'audio', 'source'].includes(initiator) ? true : initiator === 'img' ? false : null;
164
+ const geetestPathMoves = (_initiator, url) => {
165
+ const kind = url.split('captcha_v4/policy/').slice(-1)[0].split('/')[1];
166
+ return kind === undefined ? null : GEETEST_MOVING.has(kind) ? true : GEETEST_STILL.has(kind) ? false : null;
167
+ };
168
+ const cybersiaraFileMoves = (_initiator, url) => url.toLowerCase().split('?', 1)[0].endsWith('.gif') ? true : null;
169
+ exports.TIMELINE_BOARDS = {
170
+ [kinds_1.Vendor.HCAPTCHA]: { deal: 'hcaptcha.com/getcaptcha/', board: 'hcaptcha.com/tip/', read: hcaptchaTipMoves },
171
+ [kinds_1.Vendor.GEETEST]: { deal: 'geetest.com/load', board: 'static.geetest.com/captcha_v4/policy/', read: geetestPathMoves },
172
+ [kinds_1.Vendor.CYBERSIARA]: {
173
+ deal: 'mycybersiara.com/api/GenerateCaptcha', board: 'mycybersiara.com/CyberSiara/', read: cybersiaraFileMoves,
174
+ },
175
+ };
176
+ const combine = (reads) => reads.includes(true) ? true : reads.includes(false) ? false : null;
177
+ /** What one frame's resource timeline says about the vendor's latest board, or null. */
178
+ function motionFromTimeline(vendor, timeline) {
179
+ const spec = exports.TIMELINE_BOARDS[vendor];
180
+ if (!spec || !timeline || timeline.full)
181
+ return null;
182
+ const entries = (timeline.entries ?? []).filter((e) => Array.isArray(e) && e.length === 2);
183
+ let lastDeal = -1;
184
+ entries.forEach(([, url], i) => { if (String(url).includes(spec.deal))
185
+ lastDeal = i; });
186
+ if (lastDeal < 0)
187
+ return null;
188
+ return combine(entries.slice(lastDeal + 1).filter(([, url]) => String(url).includes(spec.board))
189
+ .map(([kind, url]) => spec.read(String(kind), String(url))));
190
+ }
191
+ function motionSignalFor(url) {
192
+ return Object.entries(exports.MOTION_SIGNALS)
193
+ .flatMap(([vendor, signals]) => signals.map((signal) => ({ vendor, signal })))
194
+ .find(({ signal }) => url.includes(signal.marker)) ?? null;
195
+ }
196
+ /** The vendor whose deal endpoint this is: what it said about the last board no longer holds. */
197
+ function dealsABoard(url) {
198
+ const found = endpointFor(url);
199
+ return found && found.endpoint.read === urlOnly ? found.vendor : null;
200
+ }
116
201
  const SCRIPTED_REQUESTS = new Set(['xhr', 'fetch', 'script']);
117
202
  /**
118
203
  * Every verdict the page's network carries while a solve runs.
@@ -121,6 +206,34 @@ const SCRIPTED_REQUESTS = new Set(['xhr', 'fetch', 'script']);
121
206
  * records nothing, and the driver then judges every round by the DOM, as it always has.
122
207
  */
123
208
  class VerdictLog {
209
+ noteMotion(vendor, moves) {
210
+ // One moving file makes the board a moving one: a board may also load a still example.
211
+ if (moves !== null && !this.motion.get(vendor))
212
+ this.motion.set(vendor, moves);
213
+ }
214
+ /** Whether the vendor dealt its current board as a moving one; null when its network has not said. */
215
+ async boardMotion(vendor) {
216
+ await Promise.all([...this.pending]);
217
+ const heard = this.motion.get(vendor);
218
+ if (heard !== undefined || !exports.TIMELINE_BOARDS[vendor])
219
+ return heard ?? null;
220
+ let frames = [];
221
+ try {
222
+ frames = this.page.frames?.() ?? [];
223
+ }
224
+ catch {
225
+ return null;
226
+ }
227
+ const reads = await Promise.all(frames.map(async (frame) => {
228
+ try {
229
+ return motionFromTimeline(vendor, (await frame.evaluate?.(exports.TIMELINE_JS)));
230
+ }
231
+ catch {
232
+ return null;
233
+ }
234
+ }));
235
+ return combine(reads);
236
+ }
124
237
  constructor(page) {
125
238
  this.page = page;
126
239
  this.verdicts = [];
@@ -133,15 +246,42 @@ class VerdictLog {
133
246
  const status = response.status();
134
247
  if (SCRIPTED_REQUESTS.has(response.request?.().resourceType?.() ?? ''))
135
248
  this.exchanges++;
136
- if (!endpointFor(url))
249
+ const dealt = dealsABoard(url);
250
+ // At once, not when the body lands: the new board's own file can arrive first.
251
+ if (dealt) {
252
+ this.motion.delete(dealt);
253
+ this.deals.set(dealt, (this.deals.get(dealt) ?? 0) + 1);
254
+ }
255
+ const found = motionSignalFor(url);
256
+ const judged = endpointFor(url) !== null;
257
+ if (!judged && !found)
258
+ return;
259
+ if (found && status >= 200 && status < 300 && !found.signal.needsBody) {
260
+ let contentType = '';
261
+ try {
262
+ contentType = response.headers?.()['content-type'] ?? '';
263
+ }
264
+ catch { /* no header, no hint */ }
265
+ this.noteMotion(found.vendor, found.signal.read(contentType, ''));
266
+ }
267
+ const needsBody = judged || (found?.signal.needsBody ?? false);
268
+ // A body read for an earlier deal must not describe a board that has since been replaced.
269
+ const deal = found ? this.deals.get(found.vendor) ?? 0 : 0;
270
+ if (!needsBody)
137
271
  return;
138
272
  const body = status === TOO_MANY_REQUESTS ? Promise.resolve('') : response.text();
139
273
  this.pending.push(body.then((text) => {
274
+ if (found?.signal.needsBody && status >= 200 && status < 300 && (this.deals.get(found.vendor) ?? 0) === deal) {
275
+ this.noteMotion(found.vendor, found.signal.read('', text));
276
+ }
140
277
  const verdict = readVerdict(url, status, text);
141
278
  if (verdict)
142
279
  this.verdicts.push(verdict);
143
280
  }).catch(() => { }));
144
281
  };
282
+ /** What each vendor's network said about its current board: true moves, false is still. */
283
+ this.motion = new Map();
284
+ this.deals = new Map();
145
285
  this.listening = typeof page.on === 'function';
146
286
  page.on?.('response', this.listener);
147
287
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "captchakraken",
3
- "version": "5.0.0-beta.50",
3
+ "version": "5.0.0-beta.51",
4
4
  "description": "Captcha solver for Playwright and Puppeteer. Finds the captcha, reads it with the v2 pointer model, and clicks, drags, slides or types through to a token — reCAPTCHA, GeeTest, NetEase Yidun, Tencent, Lemin, Prosopo, Turnstile and distorted text. Hosted API or self-hosted.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "captchakraken"
7
- version = "5.0.0b50"
7
+ version = "5.0.0b51"
8
8
  description = "Captcha-solving engine and CLI: a v2 pointer model for image grids, click and drag puzzles, sliders, distorted text and animated challenges. Hosted API or self-hosted on vLLM."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -100,4 +100,4 @@ __all__ = [
100
100
  "PauseKind",
101
101
  ]
102
102
 
103
- __version__ = "5.0.0b50"
103
+ __version__ = "5.0.0b51"
@@ -2043,6 +2043,16 @@ class PageSolver:
2043
2043
  _log("[animated] challenge is animated — solving it from keyframes")
2044
2044
  return True
2045
2045
 
2046
+ def _dealt_as_video(self, vendor: Vendor) -> bool:
2047
+ """The vendor dealt this board as a video: waiting for it to settle would only wait out a cycle."""
2048
+ if self._known_animated or self._board_motion(vendor) is not True:
2049
+ return False
2050
+ if not self.config.video_solve_enabled:
2051
+ raise AnimatedChallengeError("the board was dealt as a video and video_solve_enabled is off")
2052
+ _log("[animated] the vendor dealt this board as a video — filming it")
2053
+ self._known_animated = True
2054
+ return True
2055
+
2046
2056
  def _arm_animated_probe(self) -> None:
2047
2057
  if self.config.animated_probe_enabled and not self._animated_probe_done:
2048
2058
  self._animated_probe_armed = True
@@ -2052,11 +2062,17 @@ class PageSolver:
2052
2062
  # it a cycle. A text round has nothing to film.
2053
2063
  # A vendor whose boards are all stills is asked at once: filming it cost every slider and hold 4s of a
2054
2064
  # 15s budget (measured on the 5.0 Tier 3 run), and a still answer that fails earns the film next round.
2065
+ # So is a board its vendor dealt as a still file; the burst stays for every board no network has described.
2055
2066
  cfg = self.config
2056
2067
  entry = self._sel.selectors.get(puzzle_source)
2057
2068
  return (cfg.video_solve_enabled and cfg.speculative_burst_enabled and not self._acted_on_board
2058
2069
  and puzzle_source != Vendor.RECAPTCHA and not text_mode
2059
- and not (entry is not None and entry.stills_only))
2070
+ and not (entry is not None and entry.stills_only)
2071
+ and self._board_motion(puzzle_source) is not False)
2072
+
2073
+ def _board_motion(self, vendor: Optional[Vendor]) -> Optional[bool]:
2074
+ """What the vendor's network said about the current board (verdicts.MOTION_SIGNALS), or None."""
2075
+ return self._verdicts.board_motion(vendor) if self._verdicts is not None and vendor is not None else None
2060
2076
 
2061
2077
  def _burst(self, element: Any, known: AbstractSet[str] = frozenset(),
2062
2078
  max_ms: Optional[float] = None) -> Tuple[List[Any], List[str], bool, float, bool]:
@@ -2585,7 +2601,7 @@ class PageSolver:
2585
2601
  filmable = puzzle_source != Vendor.RECAPTCHA and not text_mode
2586
2602
  if filmable and not self._known_animated:
2587
2603
  self._step_off_the_board(page, element)
2588
- is_animated = filmable and self._settle_or_animated(element)
2604
+ is_animated = filmable and (self._dealt_as_video(puzzle_source) or self._settle_or_animated(element))
2589
2605
  # hCaptcha keeps its challenge iframe visible ~2s after the final submit; read as a fresh puzzle it burned ~18s.
2590
2606
  if role == FrameRole.CHALLENGE and self.is_captcha_solved(page):
2591
2607
  _log("solved while waiting for the next round; skipping inference.")
@@ -9,7 +9,7 @@ from __future__ import annotations
9
9
 
10
10
  import json
11
11
  from dataclasses import dataclass
12
- from typing import Any, Callable, List, Mapping, Optional, Sequence, Tuple
12
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple
13
13
 
14
14
  from .kinds import Verdict, Vendor
15
15
 
@@ -141,6 +141,118 @@ def read_verdict(url: str, status: int, body: str) -> Optional[RoundVerdict]:
141
141
  return RoundVerdict(vendor, verdict) if verdict is not None else None
142
142
 
143
143
 
144
+ # ── whether a board moves, read off the file it is dealt as ─────────────────
145
+ # Measured 2026-11-14 on the live demos. hCaptcha (46 deals over three sitekeys) loads each board from
146
+ # imgs*.hcaptcha.com/tip/: image/jpeg for every still deal, video/webm for every animated one. GeeTest v4's /load names
147
+ # its challenge in plain JSONP, and only the two svg types moved (22 deals over seven demo pages). A vendor, file or
148
+ # type not listed here gives no hint, and the driver films the board to find out, as it always has.
149
+ _GEETEST_MOVING = frozenset({"svg_icon", "svg_seed"})
150
+ _GEETEST_STILL = frozenset({"slide", "icon", "nine", "match", "winlinze"})
151
+
152
+
153
+ def _media_moves(content_type: str, _body: str) -> Optional[bool]:
154
+ # A GIF may move, so it says nothing either way; every still hCaptcha board measured was a jpeg or a png.
155
+ kind = content_type.split(";", 1)[0].strip().lower()
156
+ if kind == "image/gif":
157
+ return None
158
+ return {"video": True, "image": False}.get(kind.split("/", 1)[0])
159
+
160
+
161
+ def _cybersiara_board_moves(_content_type: str, body: str) -> Optional[bool]:
162
+ # GenerateCaptcha names the board's file in HtmlFormate; every one measured (4 deals) was a GIF that moved.
163
+ data = _json(body)
164
+ board = data.get("HtmlFormate") if isinstance(data, dict) else None
165
+ return True if isinstance(board, str) and board.lower().split("?", 1)[0].endswith(".gif") else None
166
+
167
+
168
+ def _geetest_type_moves(_content_type: str, body: str) -> Optional[bool]:
169
+ start, end = body.find("("), body.rfind(")")
170
+ data = _json(body[start + 1:end]) if 0 <= start < end else None
171
+ kind = (data.get("data") or {}).get("captcha_type") if isinstance(data, dict) else None
172
+ return True if kind in _GEETEST_MOVING else False if kind in _GEETEST_STILL else None
173
+
174
+
175
+ @dataclass(frozen=True)
176
+ class MotionSignal:
177
+ # A URL substring naming the response that carries the board, or names its kind.
178
+ marker: str
179
+ read: Callable[[str, str], Optional[bool]]
180
+ needs_body: bool
181
+
182
+
183
+ MOTION_SIGNALS: Mapping[Vendor, Sequence[MotionSignal]] = {
184
+ Vendor.HCAPTCHA: (MotionSignal("hcaptcha.com/tip/", _media_moves, needs_body=False),),
185
+ Vendor.GEETEST: (MotionSignal("geetest.com/load", _geetest_type_moves, needs_body=True),),
186
+ Vendor.CYBERSIARA: (MotionSignal("mycybersiara.com/api/GenerateCaptcha", _cybersiara_board_moves,
187
+ needs_body=True),),
188
+ }
189
+
190
+
191
+ # ── the same, read back from a frame's performance timeline ──────────────────
192
+ # The listener hears only what loads after solve() starts. A widget the caller opened first, or a board the browser
193
+ # served from its cache, was dealt before then, and each frame's resource timeline still lists what it loaded and what
194
+ # loaded it. Only entries after the vendor's latest deal count, and a full buffer (where new entries are dropped and the
195
+ # latest deal may be missing) says nothing. Measured 2026-11-14: GeeTest's board files sit under
196
+ # static.geetest.com/captcha_v4/policy/<id>/<captcha_type>/, hCaptcha's under /tip/ loaded by an img, CyberSiara's as
197
+ # a GIF under embed.mycybersiara.com/CyberSiara/.
198
+ TIMELINE_JS = """() => {
199
+ const all = performance.getEntriesByType('resource');
200
+ return {full: all.length >= 250, entries: all.map(e => [e.initiatorType, e.name])};
201
+ }"""
202
+
203
+
204
+ def _hcaptcha_tip_moves(initiator: str, _url: str) -> Optional[bool]:
205
+ return True if initiator in ("video", "audio", "source") else False if initiator == "img" else None
206
+
207
+
208
+ def _geetest_path_moves(_initiator: str, url: str) -> Optional[bool]:
209
+ parts = url.split("captcha_v4/policy/", 1)[-1].split("/")
210
+ kind = parts[1] if len(parts) > 1 else None
211
+ return True if kind in _GEETEST_MOVING else False if kind in _GEETEST_STILL else None
212
+
213
+
214
+ def _cybersiara_file_moves(_initiator: str, url: str) -> Optional[bool]:
215
+ return True if url.lower().split("?", 1)[0].endswith(".gif") else None
216
+
217
+
218
+ @dataclass(frozen=True)
219
+ class TimelineBoard:
220
+ deal: str
221
+ board: str
222
+ read: Callable[[str, str], Optional[bool]]
223
+
224
+
225
+ TIMELINE_BOARDS: Mapping[Vendor, TimelineBoard] = {
226
+ Vendor.HCAPTCHA: TimelineBoard("hcaptcha.com/getcaptcha/", "hcaptcha.com/tip/", _hcaptcha_tip_moves),
227
+ Vendor.GEETEST: TimelineBoard("geetest.com/load", "static.geetest.com/captcha_v4/policy/", _geetest_path_moves),
228
+ Vendor.CYBERSIARA: TimelineBoard("mycybersiara.com/api/GenerateCaptcha", "mycybersiara.com/CyberSiara/",
229
+ _cybersiara_file_moves),
230
+ }
231
+
232
+
233
+ def motion_from_timeline(vendor: Vendor, timeline: Any) -> Optional[bool]:
234
+ """What one frame's resource timeline says about the vendor's latest board, or None."""
235
+ spec = TIMELINE_BOARDS.get(vendor)
236
+ if spec is None or not isinstance(timeline, dict) or timeline.get("full"):
237
+ return None
238
+ entries = [e for e in timeline.get("entries") or () if isinstance(e, (list, tuple)) and len(e) == 2]
239
+ last_deal = max((i for i, (_kind, url) in enumerate(entries) if spec.deal in str(url)), default=None)
240
+ if last_deal is None:
241
+ return None
242
+ reads = [spec.read(str(kind), str(url)) for kind, url in entries[last_deal + 1:] if spec.board in str(url)]
243
+ return True if True in reads else False if False in reads else None
244
+
245
+
246
+ def motion_signal_for(url: str) -> Optional[Tuple[Vendor, MotionSignal]]:
247
+ return next(((vendor, s) for vendor, signals in MOTION_SIGNALS.items() for s in signals if s.marker in url), None)
248
+
249
+
250
+ def _deals_a_board(url: str) -> Optional[Vendor]:
251
+ """The vendor whose deal endpoint this is: what it said about the last board no longer holds."""
252
+ found = endpoint_for(url)
253
+ return found[0] if found is not None and found[1].read is _url_only else None
254
+
255
+
144
256
  def _is_a_scripted_request(response: Any) -> bool:
145
257
  try:
146
258
  return response.request.resource_type in _SCRIPTED_REQUESTS
@@ -160,6 +272,9 @@ class VerdictLog:
160
272
  #: Requests the page's scripts have made. A board that answers a press with none has refused nothing.
161
273
  self.exchanges = 0
162
274
  self._read = 0
275
+ #: What each vendor's network said about its current board: True moves, False is still.
276
+ self._motion: Dict[Vendor, bool] = {}
277
+ self._deals: Dict[Vendor, int] = {}
163
278
  self._page = page
164
279
  self._attached = False
165
280
  try:
@@ -173,17 +288,52 @@ class VerdictLog:
173
288
  url, status = response.url, response.status
174
289
  if _is_a_scripted_request(response):
175
290
  self.exchanges += 1
176
- if endpoint_for(url) is None:
291
+ dealt = _deals_a_board(url)
292
+ if dealt is not None:
293
+ # Before the body is read: the new board's own file can arrive while it is.
294
+ self._motion.pop(dealt, None)
295
+ self._deals[dealt] = self._deals.get(dealt, 0) + 1
296
+ signal = motion_signal_for(url)
297
+ # A body read for an earlier deal must not describe a board that has since been replaced.
298
+ deal = self._deals.get(signal[0], 0) if signal is not None else 0
299
+ if endpoint_for(url) is None and signal is None:
177
300
  return
178
301
  # Decoded leniently, as a browser's text() is: one deal endpoint answers in ciphertext, and its URL alone
179
302
  # is the signal.
180
- body = response.body().decode("utf-8", "replace") if status != _TOO_MANY_REQUESTS else ""
303
+ needs_body = endpoint_for(url) is not None or (signal is not None and signal[1].needs_body)
304
+ body = response.body().decode("utf-8", "replace") if needs_body and status != _TOO_MANY_REQUESTS else ""
305
+ content_type = (response.headers or {}).get("content-type", "") if signal is not None else ""
181
306
  except Exception:
182
307
  return
308
+ if signal is not None and 200 <= status < 300 and self._deals.get(signal[0], 0) == deal:
309
+ self._note_motion(signal[0], signal[1].read(content_type, body))
183
310
  verdict = read_verdict(url, status, body)
184
311
  if verdict is not None:
185
312
  self.verdicts.append(verdict)
186
313
 
314
+ def _note_motion(self, vendor: Vendor, moves: Optional[bool]) -> None:
315
+ # One moving file makes the board a moving one: a board may also load a still example.
316
+ if moves is not None and not self._motion.get(vendor):
317
+ self._motion[vendor] = moves
318
+
319
+ def board_motion(self, vendor: Vendor) -> Optional[bool]:
320
+ """Whether the vendor dealt its current board as a moving one; None when neither its network nor a frame's
321
+ timeline has said."""
322
+ heard = self._motion.get(vendor)
323
+ if heard is not None or vendor not in TIMELINE_BOARDS:
324
+ return heard
325
+ try:
326
+ frames = list(self._page.frames)
327
+ except Exception:
328
+ return None
329
+ reads = []
330
+ for frame in frames:
331
+ try:
332
+ reads.append(motion_from_timeline(vendor, frame.evaluate(TIMELINE_JS)))
333
+ except Exception:
334
+ continue
335
+ return True if True in reads else False if False in reads else None
336
+
187
337
  @property
188
338
  def listening(self) -> bool:
189
339
  return self._attached