doescap 1.0.0__py3-none-any.whl

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.
doescap/client.py ADDED
@@ -0,0 +1,670 @@
1
+ """Main client interface for DoesCap."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import base64
7
+ import json
8
+ import logging
9
+ import os
10
+ import random
11
+ import subprocess
12
+ import threading
13
+ import time
14
+ import urllib.request
15
+ from typing import Any, Callable, Dict, Optional
16
+
17
+ from .browser import find_browser, open_browser
18
+ from .cdp import (
19
+ CdpClient,
20
+ CDP_BOOT_SCRIPT,
21
+ CDP_RECT_SCRIPT,
22
+ CDP_TOKEN_SCRIPT,
23
+ CDP_USER_AGENT,
24
+ HAVE_WEBSOCKET,
25
+ )
26
+ from .config import RelayConfig, SolveResult
27
+ from .network import find_free_port, get_local_ip, setup_windows_firewall_rule
28
+ from .server import build_request_handler, ReusableThreadingServer
29
+
30
+ logger = logging.getLogger("doescap")
31
+
32
+
33
+ class DoesCap:
34
+ """Cross-platform hCaptcha relay orchestrator.
35
+
36
+ Supports zero-overhead Direct In-Browser verification (fast, native 60/120Hz),
37
+ Headless CDP Screencast mode, and custom developer webpage designs.
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ config: Optional[RelayConfig] = None,
43
+ *,
44
+ host: Optional[str] = None,
45
+ port: Optional[int] = None,
46
+ auto_open_browser: Optional[bool] = None,
47
+ browser_path: Optional[str] = None,
48
+ timeout: Optional[int] = None,
49
+ title: Optional[str] = None,
50
+ theme: Optional[str] = None,
51
+ custom_html: Optional[str] = None,
52
+ custom_html_path: Optional[str] = None,
53
+ custom_assets_dir: Optional[str] = None,
54
+ ):
55
+ if config is not None:
56
+ self.config = config
57
+ else:
58
+ self.config = RelayConfig()
59
+
60
+ if host is not None:
61
+ self.config.host = host
62
+ if port is not None:
63
+ self.config.port = port
64
+ if auto_open_browser is not None:
65
+ self.config.auto_open_browser = auto_open_browser
66
+ if browser_path is not None:
67
+ self.config.browser_path = browser_path
68
+ if timeout is not None:
69
+ self.config.timeout = timeout
70
+ if title is not None:
71
+ self.config.title = title
72
+ if theme is not None:
73
+ self.config.theme = theme
74
+ if custom_html is not None:
75
+ self.config.custom_html = custom_html
76
+ if custom_html_path is not None:
77
+ self.config.custom_html_path = custom_html_path
78
+ if custom_assets_dir is not None:
79
+ self.config.custom_assets_dir = custom_assets_dir
80
+
81
+ self._lock = threading.Lock()
82
+ self._server: Optional[ReusableThreadingServer] = None
83
+ self._server_thread: Optional[threading.Thread] = None
84
+ self._headless_proc: Optional[subprocess.Popen] = None
85
+ self._cdp: Optional[CdpClient] = None
86
+ self._active_port: int = self.config.port
87
+
88
+ self._state: Dict[str, Any] = {
89
+ "mode": "direct",
90
+ "sitekey": "",
91
+ "rqdata": "",
92
+ "task_name": "",
93
+ "promo_code": "",
94
+ "solved": False,
95
+ "claimed": False,
96
+ "token": "",
97
+ "frame": b"",
98
+ "rect": None,
99
+ "success_message": "",
100
+ "error": "",
101
+ }
102
+
103
+ @property
104
+ def relay_url(self) -> str:
105
+ """Get the network HTTP URL pointing to this relay server."""
106
+ ip = get_local_ip()
107
+ return f"http://{ip}:{self._active_port}/"
108
+
109
+ @property
110
+ def localhost_url(self) -> str:
111
+ """Get the localhost URL pointing to this relay server."""
112
+ return f"http://127.0.0.1:{self._active_port}/"
113
+
114
+ def get_public_status(self) -> Dict[str, Any]:
115
+ """Fetch read-only status dictionary for client polling."""
116
+ with self._lock:
117
+ return {
118
+ "mode": self._state["mode"],
119
+ "sitekey": self._state["sitekey"],
120
+ "rqdata": self._state["rqdata"],
121
+ "task_name": self._state["task_name"],
122
+ "promo_code": self._state["promo_code"],
123
+ "solved": self._state["solved"],
124
+ "claimed": self._state["claimed"],
125
+ "success_message": self._state["success_message"],
126
+ "error": self._state["error"],
127
+ "rect": self._state["rect"],
128
+ }
129
+
130
+ def get_current_frame(self) -> bytes:
131
+ """Get current screencast frame JPEG bytes."""
132
+ with self._lock:
133
+ return self._state.get("frame", b"")
134
+
135
+ def submit_token(self, token: str) -> None:
136
+ """Record a verified captcha token from web callback."""
137
+ with self._lock:
138
+ self._state["token"] = token
139
+ self._state["solved"] = True
140
+
141
+ def mark_completed(self, message: str = "Verification complete!") -> None:
142
+ """Update client UI with a success notice."""
143
+ with self._lock:
144
+ self._state["success_message"] = message
145
+
146
+ def mark_claimed(
147
+ self,
148
+ quest_name: str = "",
149
+ reward_name: str = "",
150
+ promo_code: str = "",
151
+ task_name: Optional[str] = None,
152
+ ) -> None:
153
+ """Notify the web UI that the reward or task was successfully processed."""
154
+ display_name = task_name or quest_name or reward_name
155
+ with self._lock:
156
+ self._state["claimed"] = True
157
+ if display_name:
158
+ self._state["task_name"] = display_name
159
+ if promo_code:
160
+ self._state["promo_code"] = promo_code
161
+ self._state["success_message"] = "Action completed and confirmed successfully."
162
+
163
+ # Schedule deferred cleanup after 25s so user can view/copy any promo code
164
+ threading.Thread(target=self._delayed_cleanup, args=(25,), daemon=True).start()
165
+
166
+ def mark_failed(self, error_msg: str) -> None:
167
+ """Notify the web UI that the server action failed."""
168
+ with self._lock:
169
+ self._state["error"] = error_msg
170
+ threading.Thread(target=self._delayed_cleanup, args=(10,), daemon=True).start()
171
+
172
+ def _delayed_cleanup(self, delay: int = 25) -> None:
173
+ time.sleep(delay)
174
+ self.close()
175
+
176
+ def handle_input_event(self, kind: str, x: float, y: float) -> None:
177
+ """Forward user input (mouse/touch) into headless CDP session."""
178
+ cdp = self._cdp
179
+ if not cdp:
180
+ return
181
+
182
+ with self._lock:
183
+ rect = self._state.get("rect")
184
+ if not rect:
185
+ return
186
+
187
+ px = float(rect.get("x", 0)) + x
188
+ py = float(rect.get("y", 0)) + y
189
+
190
+ try:
191
+ if kind == "move":
192
+ cdp.send("Input.dispatchMouseEvent", {
193
+ "type": "mouseMoved",
194
+ "x": px,
195
+ "y": py,
196
+ "button": "none",
197
+ "buttons": 0,
198
+ })
199
+ elif kind == "press":
200
+ cdp.send("Input.dispatchMouseEvent", {
201
+ "type": "mouseMoved",
202
+ "x": px,
203
+ "y": py,
204
+ "button": "none",
205
+ "buttons": 0,
206
+ })
207
+ cdp.send("Input.dispatchMouseEvent", {
208
+ "type": "mousePressed",
209
+ "x": px,
210
+ "y": py,
211
+ "button": "left",
212
+ "buttons": 1,
213
+ "clickCount": 1,
214
+ })
215
+ elif kind == "release":
216
+ cdp.send("Input.dispatchMouseEvent", {
217
+ "type": "mouseReleased",
218
+ "x": px,
219
+ "y": py,
220
+ "button": "left",
221
+ "buttons": 0,
222
+ "clickCount": 1,
223
+ })
224
+ except Exception as e:
225
+ logger.debug("Failed dispatching CDP input: %s", e)
226
+
227
+ def _start_http_server(self) -> None:
228
+ """Initialize and start background HTTP server."""
229
+ if self._server is not None:
230
+ return
231
+
232
+ self._active_port = find_free_port(self.config.port, self.config.host)
233
+ handler_cls = build_request_handler(self)
234
+
235
+ try:
236
+ self._server = ReusableThreadingServer((self.config.host, self._active_port), handler_cls)
237
+ except OSError:
238
+ self._active_port = find_free_port(0, self.config.host)
239
+ self._server = ReusableThreadingServer((self.config.host, self._active_port), handler_cls)
240
+
241
+ if self.config.allow_firewall_rule:
242
+ setup_windows_firewall_rule(self._active_port, "DoesCap Relay")
243
+
244
+ self._server_thread = threading.Thread(target=self._server.serve_forever, daemon=True)
245
+ self._server_thread.start()
246
+ logger.info("DoesCap Relay server listening on %s:%d", self.config.host, self._active_port)
247
+
248
+ def _stop_http_server(self) -> None:
249
+ """Shutdown background HTTP server."""
250
+ if self._server is not None:
251
+ try:
252
+ self._server.shutdown()
253
+ self._server.server_close()
254
+ except Exception:
255
+ pass
256
+ self._server = None
257
+ self._server_thread = None
258
+
259
+ def _mirror_screencast_loop(self, cdp: CdpClient) -> None:
260
+ """Background thread polling frames from CDP page."""
261
+ while True:
262
+ with self._lock:
263
+ if self._state.get("solved"):
264
+ break
265
+ try:
266
+ rect = cdp.evaluate(CDP_RECT_SCRIPT)
267
+ if rect and rect.get("w") and rect.get("h"):
268
+ with self._lock:
269
+ self._state["rect"] = rect
270
+ clip_x = max(0.0, float(rect["x"]))
271
+ clip_y = max(0.0, float(rect["y"]))
272
+ shot = cdp.send("Page.captureScreenshot", {
273
+ "format": "jpeg",
274
+ "quality": 82,
275
+ "clip": {
276
+ "x": clip_x,
277
+ "y": clip_y,
278
+ "width": float(rect["w"]),
279
+ "height": float(rect["h"]),
280
+ "scale": 1,
281
+ },
282
+ })
283
+ if shot and shot.get("data"):
284
+ with self._lock:
285
+ self._state["frame"] = base64.b64decode(shot["data"])
286
+ except Exception:
287
+ pass
288
+ time.sleep(0.20)
289
+
290
+ def _poll_cdp_token_loop(self, cdp: CdpClient, timeout: int) -> Optional[str]:
291
+ """Poll page runtime for solved hCaptcha token."""
292
+ deadline = time.time() + timeout
293
+ while time.time() < deadline:
294
+ with self._lock:
295
+ if self._state.get("solved") and self._state.get("token"):
296
+ return self._state["token"]
297
+ try:
298
+ token = cdp.evaluate(CDP_TOKEN_SCRIPT)
299
+ if token:
300
+ clean = str(token).strip().strip('"').strip("'")
301
+ if clean:
302
+ self.submit_token(clean)
303
+ return clean
304
+ except Exception:
305
+ pass
306
+ time.sleep(0.4)
307
+ return None
308
+
309
+ def solve(
310
+ self,
311
+ sitekey: str,
312
+ rqdata: Optional[str] = None,
313
+ *,
314
+ timeout: Optional[int] = None,
315
+ token: Optional[str] = None,
316
+ context_token: Optional[str] = None,
317
+ rqtoken: Optional[str] = None,
318
+ quest_name: Optional[str] = None,
319
+ task_name: Optional[str] = None,
320
+ custom_html: Optional[str] = None,
321
+ custom_html_path: Optional[str] = None,
322
+ **kwargs: Any,
323
+ ) -> Optional[SolveResult]:
324
+ """Solve an hCaptcha challenge synchronously.
325
+
326
+ Returns an instance of SolveResult which behaves identically to a string
327
+ containing the token, or None if cancelled/timed out.
328
+ """
329
+ start_time = time.time()
330
+ effective_timeout = timeout if timeout is not None else self.config.timeout
331
+ effective_task = task_name or quest_name or ""
332
+ auth_token = context_token or token
333
+
334
+ if custom_html is not None:
335
+ self.config.custom_html = custom_html
336
+ if custom_html_path is not None:
337
+ self.config.custom_html_path = custom_html_path
338
+
339
+ # Determine operating mode
340
+ use_screencast = False
341
+ browser_exe = None
342
+ browser_name = None
343
+
344
+ if self.config.browser_path and HAVE_WEBSOCKET:
345
+ browser_exe, browser_name = find_browser(self.config.browser_path)
346
+ if browser_exe:
347
+ use_screencast = True
348
+
349
+ with self._lock:
350
+ self._state = {
351
+ "mode": "screencast" if use_screencast else "direct",
352
+ "sitekey": sitekey,
353
+ "rqdata": rqdata or "",
354
+ "task_name": effective_task,
355
+ "promo_code": "",
356
+ "solved": False,
357
+ "claimed": False,
358
+ "token": "",
359
+ "frame": b"",
360
+ "rect": None,
361
+ "success_message": "",
362
+ "error": "",
363
+ }
364
+
365
+ # Start relay HTTP server
366
+ self._start_http_server()
367
+
368
+ # Launch default browser on client device
369
+ if self.config.auto_open_browser:
370
+ local_url = self.localhost_url
371
+ threading.Thread(target=open_browser, args=(local_url,), daemon=True).start()
372
+
373
+ # DIRECT MODE
374
+ if not use_screencast:
375
+ try:
376
+ deadline = time.time() + effective_timeout
377
+ while time.time() < deadline:
378
+ with self._lock:
379
+ if self._state["solved"] and self._state["token"]:
380
+ elapsed = time.time() - start_time
381
+ return SolveResult(
382
+ token=self._state["token"],
383
+ success=True,
384
+ elapsed_seconds=elapsed,
385
+ metadata={"mode": "direct", "port": self._active_port},
386
+ )
387
+ if self._state["error"]:
388
+ return None
389
+ time.sleep(0.3)
390
+
391
+ return None
392
+ finally:
393
+ with self._lock:
394
+ was_solved = self._state["solved"]
395
+ if not was_solved:
396
+ self.close()
397
+
398
+ # SCREENCAST MODE (via headless Chromium CDP)
399
+ cdp_port = random.randint(20000, 60000)
400
+ temp_dir = os.path.join(
401
+ os.environ.get("TEMP", os.environ.get("TMP", os.getcwd())),
402
+ f"doescap_relay_{cdp_port}",
403
+ )
404
+
405
+ launch_args = [
406
+ browser_exe,
407
+ f"--remote-debugging-port={cdp_port}",
408
+ "--remote-allow-origins=*",
409
+ f"--user-data-dir={temp_dir}",
410
+ "--no-first-run",
411
+ "--window-size=1280,900",
412
+ "--headless=new",
413
+ "--disable-gpu",
414
+ "--hide-scrollbars",
415
+ "--mute-audio",
416
+ "--no-sandbox",
417
+ "--disable-extensions",
418
+ "--disable-background-networking",
419
+ f"--user-agent={CDP_USER_AGENT}",
420
+ "--disable-blink-features=AutomationControlled",
421
+ "about:blank",
422
+ ]
423
+
424
+ try:
425
+ self._headless_proc = subprocess.Popen(
426
+ launch_args,
427
+ stdout=subprocess.DEVNULL,
428
+ stderr=subprocess.DEVNULL,
429
+ )
430
+ except Exception as e:
431
+ logger.warning("Failed launching headless browser '%s': %s. Falling back to Direct Mode.", browser_name, e)
432
+ with self._lock:
433
+ self._state["mode"] = "direct"
434
+ return self.solve(
435
+ sitekey,
436
+ rqdata,
437
+ timeout=effective_timeout,
438
+ token=auth_token,
439
+ task_name=effective_task,
440
+ )
441
+
442
+ # Await CDP readiness
443
+ cdp_http = f"http://127.0.0.1:{cdp_port}"
444
+ cdp_ready = False
445
+ for _ in range(35):
446
+ try:
447
+ with urllib.request.urlopen(f"{cdp_http}/json/version", timeout=2) as resp:
448
+ resp.read()
449
+ cdp_ready = True
450
+ break
451
+ except Exception:
452
+ time.sleep(0.3)
453
+
454
+ if not cdp_ready:
455
+ logger.warning("Headless CDP port timed out. Falling back to Direct Mode.")
456
+ self._kill_headless()
457
+ with self._lock:
458
+ self._state["mode"] = "direct"
459
+ return self.solve(
460
+ sitekey,
461
+ rqdata,
462
+ timeout=effective_timeout,
463
+ token=auth_token,
464
+ task_name=effective_task,
465
+ )
466
+
467
+ try:
468
+ new_tab_url = f"{cdp_http}/json/new?about:blank"
469
+ try:
470
+ req = urllib.request.Request(new_tab_url, method="PUT")
471
+ with urllib.request.urlopen(req, timeout=10) as r:
472
+ tab_info = json.loads(r.read())
473
+ except Exception:
474
+ with urllib.request.urlopen(new_tab_url, timeout=10) as r:
475
+ tab_info = json.loads(r.read())
476
+
477
+ self._cdp = CdpClient(tab_info["webSocketDebuggerUrl"])
478
+ self._cdp.send("Page.enable")
479
+ self._cdp.send("Runtime.enable")
480
+ self._cdp.send("Network.enable")
481
+
482
+ stealth_js = (
483
+ "Object.defineProperty(navigator, 'webdriver', {get: () => undefined});"
484
+ "window.chrome = { runtime: {} };"
485
+ )
486
+ if auth_token:
487
+ stealth_js += f"; try {{ window.localStorage.setItem('token', JSON.stringify({json.dumps(auth_token)})); }} catch(e) {{}}"
488
+
489
+ self._cdp.send("Page.addScriptToEvaluateOnNewDocument", {"source": stealth_js})
490
+ self._cdp.send("Page.navigate", {"url": "about:blank"})
491
+ time.sleep(1.0)
492
+
493
+ self._cdp.evaluate(CDP_BOOT_SCRIPT.format(
494
+ sitekey=json.dumps(sitekey),
495
+ rqdata=json.dumps(rqdata),
496
+ ))
497
+
498
+ threading.Thread(target=self._mirror_screencast_loop, args=(self._cdp,), daemon=True).start()
499
+
500
+ solved = self._poll_cdp_token_loop(self._cdp, effective_timeout)
501
+ elapsed = time.time() - start_time
502
+ if solved:
503
+ return SolveResult(
504
+ token=solved,
505
+ success=True,
506
+ elapsed_seconds=elapsed,
507
+ metadata={"mode": "screencast", "browser": browser_name},
508
+ )
509
+ return None
510
+ except Exception as err:
511
+ logger.warning("CDP session encountered error: %s. Falling back to Direct Mode.", err)
512
+ with self._lock:
513
+ self._state["mode"] = "direct"
514
+ return self.solve(
515
+ sitekey,
516
+ rqdata,
517
+ timeout=effective_timeout,
518
+ token=auth_token,
519
+ task_name=effective_task,
520
+ )
521
+ finally:
522
+ self._kill_headless()
523
+ with self._lock:
524
+ was_solved = self._state["solved"]
525
+ if not was_solved:
526
+ self.close()
527
+
528
+ # Drop-in compatibility alias
529
+ solve_relay = solve
530
+
531
+ async def async_solve(
532
+ self,
533
+ sitekey: str,
534
+ rqdata: Optional[str] = None,
535
+ *,
536
+ timeout: Optional[int] = None,
537
+ token: Optional[str] = None,
538
+ context_token: Optional[str] = None,
539
+ rqtoken: Optional[str] = None,
540
+ quest_name: Optional[str] = None,
541
+ task_name: Optional[str] = None,
542
+ custom_html: Optional[str] = None,
543
+ custom_html_path: Optional[str] = None,
544
+ **kwargs: Any,
545
+ ) -> Optional[SolveResult]:
546
+ """Solve an hCaptcha challenge asynchronously without blocking the event loop."""
547
+ loop = asyncio.get_running_loop()
548
+ return await loop.run_in_executor(
549
+ None,
550
+ lambda: self.solve(
551
+ sitekey=sitekey,
552
+ rqdata=rqdata,
553
+ timeout=timeout,
554
+ token=token,
555
+ context_token=context_token,
556
+ rqtoken=rqtoken,
557
+ quest_name=quest_name,
558
+ task_name=task_name,
559
+ custom_html=custom_html,
560
+ custom_html_path=custom_html_path,
561
+ **kwargs,
562
+ ),
563
+ )
564
+
565
+ def _kill_headless(self) -> None:
566
+ """Terminate headless browser subprocess and CDP connection."""
567
+ if self._cdp:
568
+ try:
569
+ self._cdp.close()
570
+ except Exception:
571
+ pass
572
+ self._cdp = None
573
+
574
+ if self._headless_proc:
575
+ try:
576
+ self._headless_proc.terminate()
577
+ self._headless_proc.wait(timeout=2)
578
+ except Exception:
579
+ try:
580
+ self._headless_proc.kill()
581
+ except Exception:
582
+ pass
583
+ self._headless_proc = None
584
+
585
+ def close(self) -> None:
586
+ """Tear down all server and process resources."""
587
+ self._kill_headless()
588
+ self._stop_http_server()
589
+
590
+ def cleanup(self) -> None:
591
+ """Alias for close()."""
592
+ self.close()
593
+
594
+ def __enter__(self) -> "DoesCap":
595
+ return self
596
+
597
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
598
+ self.close()
599
+
600
+
601
+ # Backward-compatible alias
602
+ HCaptchaRelay = DoesCap
603
+
604
+
605
+ def solve_captcha(
606
+ sitekey: str,
607
+ rqdata: Optional[str] = None,
608
+ *,
609
+ port: int = 8787,
610
+ host: str = "0.0.0.0",
611
+ auto_open_browser: bool = True,
612
+ browser_path: Optional[str] = None,
613
+ timeout: int = 300,
614
+ title: str = "DoesCap Relay",
615
+ custom_html: Optional[str] = None,
616
+ custom_html_path: Optional[str] = None,
617
+ custom_assets_dir: Optional[str] = None,
618
+ **kwargs: Any,
619
+ ) -> Optional[str]:
620
+ """Convenience functional helper to solve hCaptcha in a single call."""
621
+ config = RelayConfig(
622
+ host=host,
623
+ port=port,
624
+ auto_open_browser=auto_open_browser,
625
+ browser_path=browser_path,
626
+ timeout=timeout,
627
+ title=title,
628
+ custom_html=custom_html,
629
+ custom_html_path=custom_html_path,
630
+ custom_assets_dir=custom_assets_dir,
631
+ )
632
+ with DoesCap(config=config) as relay:
633
+ result = relay.solve(sitekey=sitekey, rqdata=rqdata, **kwargs)
634
+ return str(result) if result else None
635
+
636
+
637
+ async def async_solve_captcha(
638
+ sitekey: str,
639
+ rqdata: Optional[str] = None,
640
+ *,
641
+ port: int = 8787,
642
+ host: str = "0.0.0.0",
643
+ auto_open_browser: bool = True,
644
+ browser_path: Optional[str] = None,
645
+ timeout: int = 300,
646
+ title: str = "DoesCap Relay",
647
+ custom_html: Optional[str] = None,
648
+ custom_html_path: Optional[str] = None,
649
+ custom_assets_dir: Optional[str] = None,
650
+ **kwargs: Any,
651
+ ) -> Optional[str]:
652
+ """Convenience asynchronous helper to solve hCaptcha in a single call."""
653
+ loop = asyncio.get_running_loop()
654
+ return await loop.run_in_executor(
655
+ None,
656
+ lambda: solve_captcha(
657
+ sitekey=sitekey,
658
+ rqdata=rqdata,
659
+ port=port,
660
+ host=host,
661
+ auto_open_browser=auto_open_browser,
662
+ browser_path=browser_path,
663
+ timeout=timeout,
664
+ title=title,
665
+ custom_html=custom_html,
666
+ custom_html_path=custom_html_path,
667
+ custom_assets_dir=custom_assets_dir,
668
+ **kwargs,
669
+ ),
670
+ )