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/__init__.py +26 -0
- doescap/browser.py +187 -0
- doescap/cdp.py +156 -0
- doescap/cli.py +125 -0
- doescap/client.py +670 -0
- doescap/config.py +104 -0
- doescap/network.py +87 -0
- doescap/py.typed +1 -0
- doescap/server.py +199 -0
- doescap/templates.py +651 -0
- doescap-1.0.0.dist-info/METADATA +235 -0
- doescap-1.0.0.dist-info/RECORD +16 -0
- doescap-1.0.0.dist-info/WHEEL +5 -0
- doescap-1.0.0.dist-info/entry_points.txt +2 -0
- doescap-1.0.0.dist-info/licenses/LICENSE +21 -0
- doescap-1.0.0.dist-info/top_level.txt +1 -0
doescap/config.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Configuration models and data structures for DoesCap."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Dict, Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SolveResult(str):
|
|
9
|
+
"""String-compatible result returned after solving an hCaptcha challenge.
|
|
10
|
+
|
|
11
|
+
Inherits from str so it can be passed directly to HTTP headers, APIs,
|
|
12
|
+
and string functions without conversion, while also exposing metadata.
|
|
13
|
+
|
|
14
|
+
Attributes:
|
|
15
|
+
token: The verified hCaptcha response token (same as str value), or None.
|
|
16
|
+
success: True if a valid token was acquired.
|
|
17
|
+
elapsed_seconds: Total duration in seconds spent waiting for resolution.
|
|
18
|
+
error: Error description if solving failed.
|
|
19
|
+
metadata: Dictionary containing additional session details.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
token: Optional[str]
|
|
23
|
+
success: bool
|
|
24
|
+
elapsed_seconds: float
|
|
25
|
+
error: Optional[str]
|
|
26
|
+
metadata: Dict[str, Any]
|
|
27
|
+
|
|
28
|
+
def __new__(
|
|
29
|
+
cls,
|
|
30
|
+
token: Optional[str] = None,
|
|
31
|
+
success: bool = False,
|
|
32
|
+
elapsed_seconds: float = 0.0,
|
|
33
|
+
error: Optional[str] = None,
|
|
34
|
+
metadata: Optional[Dict[str, Any]] = None,
|
|
35
|
+
) -> "SolveResult":
|
|
36
|
+
value = str(token) if token else ""
|
|
37
|
+
instance = super().__new__(cls, value)
|
|
38
|
+
instance.token = token
|
|
39
|
+
instance.success = success
|
|
40
|
+
instance.elapsed_seconds = elapsed_seconds
|
|
41
|
+
instance.error = error
|
|
42
|
+
instance.metadata = metadata or {}
|
|
43
|
+
return instance
|
|
44
|
+
|
|
45
|
+
def __bool__(self) -> bool:
|
|
46
|
+
return self.success and bool(self.token)
|
|
47
|
+
|
|
48
|
+
def __repr__(self) -> str:
|
|
49
|
+
if self.success and self.token:
|
|
50
|
+
preview = f"{self.token[:20]}..." if len(self.token) > 20 else self.token
|
|
51
|
+
return f"<SolveResult success=True token='{preview}' elapsed={self.elapsed_seconds:.2f}s>"
|
|
52
|
+
return f"<SolveResult success=False error={self.error!r} elapsed={self.elapsed_seconds:.2f}s>"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class RelayConfig:
|
|
56
|
+
"""Configuration options for the DoesCap relay server and solver engine.
|
|
57
|
+
|
|
58
|
+
Attributes:
|
|
59
|
+
host: Host address to bind the HTTP relay server to. Defaults to "0.0.0.0".
|
|
60
|
+
port: Preferred TCP port to listen on. Defaults to 8787.
|
|
61
|
+
auto_open_browser: Automatically launches default browser on device. Defaults to True.
|
|
62
|
+
browser_path: Optional path for custom browser in headless screencast mode.
|
|
63
|
+
timeout: Maximum seconds to wait for resolution. Defaults to 300.
|
|
64
|
+
title: Title displayed on the web interface header.
|
|
65
|
+
theme: Web interface color scheme ("dark" or "light"). Defaults to "dark".
|
|
66
|
+
allow_firewall_rule: Attempts adding Windows Firewall rule on Windows. Defaults to True.
|
|
67
|
+
custom_html: Raw custom HTML template string to serve instead of default UI.
|
|
68
|
+
custom_html_path: Filepath pointing to a custom HTML file to serve.
|
|
69
|
+
custom_assets_dir: Filepath pointing to a directory containing static assets
|
|
70
|
+
(e.g., CSS, fonts, logos) served under `/assets/*`.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def __init__(
|
|
74
|
+
self,
|
|
75
|
+
host: str = "0.0.0.0",
|
|
76
|
+
port: int = 8787,
|
|
77
|
+
auto_open_browser: bool = True,
|
|
78
|
+
browser_path: Optional[str] = None,
|
|
79
|
+
timeout: int = 300,
|
|
80
|
+
title: str = "DoesCap Relay",
|
|
81
|
+
theme: str = "dark",
|
|
82
|
+
allow_firewall_rule: bool = True,
|
|
83
|
+
custom_html: Optional[str] = None,
|
|
84
|
+
custom_html_path: Optional[str] = None,
|
|
85
|
+
custom_assets_dir: Optional[str] = None,
|
|
86
|
+
):
|
|
87
|
+
self.host = host
|
|
88
|
+
self.port = port
|
|
89
|
+
self.auto_open_browser = auto_open_browser
|
|
90
|
+
self.browser_path = browser_path
|
|
91
|
+
self.timeout = timeout
|
|
92
|
+
self.title = title
|
|
93
|
+
self.theme = theme
|
|
94
|
+
self.allow_firewall_rule = allow_firewall_rule
|
|
95
|
+
self.custom_html = custom_html
|
|
96
|
+
self.custom_html_path = custom_html_path
|
|
97
|
+
self.custom_assets_dir = custom_assets_dir
|
|
98
|
+
|
|
99
|
+
def __repr__(self) -> str:
|
|
100
|
+
return (
|
|
101
|
+
f"RelayConfig(host={self.host!r}, port={self.port}, "
|
|
102
|
+
f"auto_open_browser={self.auto_open_browser}, timeout={self.timeout}, "
|
|
103
|
+
f"custom_html_path={self.custom_html_path!r})"
|
|
104
|
+
)
|
doescap/network.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Network and system utility helpers for DoesCap."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import socket
|
|
7
|
+
import subprocess
|
|
8
|
+
from typing import Tuple
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def get_local_ip() -> str:
|
|
12
|
+
"""Discover the primary local IPv4 address on the current network interface.
|
|
13
|
+
|
|
14
|
+
Returns:
|
|
15
|
+
A valid IPv4 string (e.g. '192.168.1.50') or '127.0.0.1' if disconnected.
|
|
16
|
+
"""
|
|
17
|
+
try:
|
|
18
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
19
|
+
sock.connect(("8.8.8.8", 80))
|
|
20
|
+
ip = sock.getsockname()[0]
|
|
21
|
+
sock.close()
|
|
22
|
+
if ip and not ip.startswith("127."):
|
|
23
|
+
return ip
|
|
24
|
+
except Exception:
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
try:
|
|
28
|
+
hostname = socket.gethostname()
|
|
29
|
+
ip = socket.gethostbyname(hostname)
|
|
30
|
+
if ip and not ip.startswith("127."):
|
|
31
|
+
return ip
|
|
32
|
+
except Exception:
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
return "127.0.0.1"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def find_free_port(preferred_port: int, host: str = "0.0.0.0") -> int:
|
|
39
|
+
"""Verify if the preferred port is open, or locate an ephemeral available port.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
preferred_port: Desired port number.
|
|
43
|
+
host: Host to test binding on.
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
An available integer port number.
|
|
47
|
+
"""
|
|
48
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
49
|
+
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
50
|
+
try:
|
|
51
|
+
s.bind((host, preferred_port))
|
|
52
|
+
return s.getsockname()[1]
|
|
53
|
+
except OSError:
|
|
54
|
+
pass
|
|
55
|
+
|
|
56
|
+
# Find ephemeral port
|
|
57
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
58
|
+
s.bind((host, 0))
|
|
59
|
+
return s.getsockname()[1]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def setup_windows_firewall_rule(port: int, rule_name: str = "DoesCap Relay") -> bool:
|
|
63
|
+
"""Optionally register a Windows Defender Firewall rule for the relay port.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
port: TCP port to permit inbound traffic on.
|
|
67
|
+
rule_name: Display name for the firewall rule.
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
True if successfully added or existing, False otherwise.
|
|
71
|
+
"""
|
|
72
|
+
if os.name != "nt":
|
|
73
|
+
return False
|
|
74
|
+
|
|
75
|
+
cmd = [
|
|
76
|
+
"netsh", "advfirewall", "firewall", "add", "rule",
|
|
77
|
+
f"name={rule_name} {port}",
|
|
78
|
+
"dir=in",
|
|
79
|
+
"action=allow",
|
|
80
|
+
"protocol=TCP",
|
|
81
|
+
f"localport={port}",
|
|
82
|
+
]
|
|
83
|
+
try:
|
|
84
|
+
res = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=3)
|
|
85
|
+
return res.returncode == 0
|
|
86
|
+
except Exception:
|
|
87
|
+
return False
|
doescap/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
doescap/server.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Lightweight, resilient HTTP relay server for DoesCap verification."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import mimetypes
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import urllib.parse
|
|
10
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
11
|
+
from typing import Any, Dict, Optional, TYPE_CHECKING
|
|
12
|
+
|
|
13
|
+
from .templates import render_html_page
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from .client import DoesCap
|
|
17
|
+
|
|
18
|
+
# Common MIME type fallbacks
|
|
19
|
+
MIME_MAP = {
|
|
20
|
+
".html": "text/html; charset=utf-8",
|
|
21
|
+
".css": "text/css; charset=utf-8",
|
|
22
|
+
".js": "application/javascript; charset=utf-8",
|
|
23
|
+
".json": "application/json",
|
|
24
|
+
".png": "image/png",
|
|
25
|
+
".jpg": "image/jpeg",
|
|
26
|
+
".jpeg": "image/jpeg",
|
|
27
|
+
".gif": "image/gif",
|
|
28
|
+
".svg": "image/svg+xml",
|
|
29
|
+
".ico": "image/x-icon",
|
|
30
|
+
".ttf": "font/ttf",
|
|
31
|
+
".woff": "font/woff",
|
|
32
|
+
".woff2": "font/woff2",
|
|
33
|
+
".otf": "font/otf",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ReusableThreadingServer(ThreadingHTTPServer):
|
|
38
|
+
"""Threading HTTPServer with SO_REUSEADDR enabled and error suppression."""
|
|
39
|
+
|
|
40
|
+
allow_reuse_address = True
|
|
41
|
+
daemon_threads = True
|
|
42
|
+
|
|
43
|
+
def handle_error(self, request, client_address) -> None:
|
|
44
|
+
err_type = sys.exc_info()[0]
|
|
45
|
+
if err_type in (ConnectionResetError, ConnectionAbortedError, BrokenPipeError):
|
|
46
|
+
return
|
|
47
|
+
super().handle_error(request, client_address)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build_request_handler(relay: "DoesCap") -> type[BaseHTTPRequestHandler]:
|
|
51
|
+
"""Create a RequestHandler class bound to the active DoesCap instance."""
|
|
52
|
+
|
|
53
|
+
class RelayHTTPHandler(BaseHTTPRequestHandler):
|
|
54
|
+
def log_message(self, *args) -> None:
|
|
55
|
+
# Suppress default console access logging
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
def _send_response(
|
|
59
|
+
self,
|
|
60
|
+
code: int,
|
|
61
|
+
body: Any,
|
|
62
|
+
content_type: str = "application/json",
|
|
63
|
+
) -> None:
|
|
64
|
+
try:
|
|
65
|
+
data = body if isinstance(body, bytes) else body.encode("utf-8")
|
|
66
|
+
self.send_response(code)
|
|
67
|
+
self.send_header("Content-Type", content_type)
|
|
68
|
+
self.send_header("Content-Length", str(len(data)))
|
|
69
|
+
self.send_header("Access-Control-Allow-Origin", "*")
|
|
70
|
+
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
|
71
|
+
self.send_header("Access-Control-Allow-Headers", "Content-Type, Accept")
|
|
72
|
+
self.end_headers()
|
|
73
|
+
self.wfile.write(data)
|
|
74
|
+
except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError):
|
|
75
|
+
pass
|
|
76
|
+
|
|
77
|
+
def do_OPTIONS(self) -> None:
|
|
78
|
+
try:
|
|
79
|
+
self.send_response(200)
|
|
80
|
+
self.send_header("Access-Control-Allow-Origin", "*")
|
|
81
|
+
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
|
82
|
+
self.send_header("Access-Control-Allow-Headers", "Content-Type, Accept")
|
|
83
|
+
self.send_header("Content-Length", "0")
|
|
84
|
+
self.end_headers()
|
|
85
|
+
except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError):
|
|
86
|
+
pass
|
|
87
|
+
|
|
88
|
+
def _resolve_custom_html(self) -> Optional[str]:
|
|
89
|
+
"""Retrieve custom HTML content if configured."""
|
|
90
|
+
if relay.config.custom_html:
|
|
91
|
+
return relay.config.custom_html
|
|
92
|
+
|
|
93
|
+
if relay.config.custom_html_path:
|
|
94
|
+
path = os.path.abspath(relay.config.custom_html_path)
|
|
95
|
+
if os.path.isfile(path):
|
|
96
|
+
try:
|
|
97
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
98
|
+
return f.read()
|
|
99
|
+
except Exception:
|
|
100
|
+
pass
|
|
101
|
+
return None
|
|
102
|
+
|
|
103
|
+
def _serve_static_asset(self, raw_path: str) -> bool:
|
|
104
|
+
"""Safely serve custom static assets preventing directory traversal."""
|
|
105
|
+
assets_dir = relay.config.custom_assets_dir
|
|
106
|
+
if not assets_dir or not os.path.isdir(assets_dir):
|
|
107
|
+
return False
|
|
108
|
+
|
|
109
|
+
base_dir = os.path.abspath(assets_dir)
|
|
110
|
+
clean_rel = urllib.parse.unquote(raw_path.split("?")[0]).lstrip("/\\")
|
|
111
|
+
if clean_rel.startswith("assets/"):
|
|
112
|
+
clean_rel = clean_rel[len("assets/"):].lstrip("/\\")
|
|
113
|
+
|
|
114
|
+
target_file = os.path.abspath(os.path.join(base_dir, clean_rel))
|
|
115
|
+
|
|
116
|
+
# Validate path containment
|
|
117
|
+
try:
|
|
118
|
+
common = os.path.commonpath([base_dir, target_file])
|
|
119
|
+
if common != base_dir or not os.path.isfile(target_file):
|
|
120
|
+
return False
|
|
121
|
+
except Exception:
|
|
122
|
+
return False
|
|
123
|
+
|
|
124
|
+
ext = os.path.splitext(target_file)[1].lower()
|
|
125
|
+
mime_type = MIME_MAP.get(ext) or mimetypes.guess_type(target_file)[0] or "application/octet-stream"
|
|
126
|
+
|
|
127
|
+
try:
|
|
128
|
+
with open(target_file, "rb") as f:
|
|
129
|
+
data = f.read()
|
|
130
|
+
self._send_response(200, data, mime_type)
|
|
131
|
+
return True
|
|
132
|
+
except Exception:
|
|
133
|
+
return False
|
|
134
|
+
|
|
135
|
+
def do_GET(self) -> None:
|
|
136
|
+
try:
|
|
137
|
+
if self.path.startswith("/frame.jpg"):
|
|
138
|
+
frame = relay.get_current_frame()
|
|
139
|
+
if frame:
|
|
140
|
+
self._send_response(200, frame, "image/jpeg")
|
|
141
|
+
else:
|
|
142
|
+
self._send_response(204, b"")
|
|
143
|
+
elif self.path.startswith("/status"):
|
|
144
|
+
status_info = relay.get_public_status()
|
|
145
|
+
self._send_response(200, json.dumps(status_info))
|
|
146
|
+
elif self.path.startswith("/assets/") and relay.config.custom_assets_dir:
|
|
147
|
+
if not self._serve_static_asset(self.path):
|
|
148
|
+
self._send_response(404, b"Asset Not Found", "text/plain")
|
|
149
|
+
else:
|
|
150
|
+
# Check for custom webpage template
|
|
151
|
+
custom_html = self._resolve_custom_html()
|
|
152
|
+
if custom_html is not None:
|
|
153
|
+
status = relay.get_public_status()
|
|
154
|
+
# Optional SSR placeholder interpolation
|
|
155
|
+
rendered = (
|
|
156
|
+
custom_html
|
|
157
|
+
.replace("{{ title }}", relay.config.title)
|
|
158
|
+
.replace("{{ theme }}", relay.config.theme)
|
|
159
|
+
.replace("{{ sitekey }}", status.get("sitekey", ""))
|
|
160
|
+
.replace("{{ rqdata }}", status.get("rqdata", ""))
|
|
161
|
+
)
|
|
162
|
+
self._send_response(200, rendered, "text/html; charset=utf-8")
|
|
163
|
+
else:
|
|
164
|
+
default_html = render_html_page(
|
|
165
|
+
title=relay.config.title,
|
|
166
|
+
theme=relay.config.theme,
|
|
167
|
+
)
|
|
168
|
+
self._send_response(200, default_html, "text/html; charset=utf-8")
|
|
169
|
+
except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError):
|
|
170
|
+
pass
|
|
171
|
+
|
|
172
|
+
def do_POST(self) -> None:
|
|
173
|
+
try:
|
|
174
|
+
if self.path.startswith("/input"):
|
|
175
|
+
length = int(self.headers.get("Content-Length", 0))
|
|
176
|
+
payload = json.loads(self.rfile.read(length).decode("utf-8"))
|
|
177
|
+
relay.handle_input_event(
|
|
178
|
+
kind=payload.get("t", "move"),
|
|
179
|
+
x=float(payload.get("x", 0)),
|
|
180
|
+
y=float(payload.get("y", 0)),
|
|
181
|
+
)
|
|
182
|
+
self._send_response(200, '{"ok":true}')
|
|
183
|
+
elif self.path.startswith("/solve"):
|
|
184
|
+
length = int(self.headers.get("Content-Length", 0))
|
|
185
|
+
payload = json.loads(self.rfile.read(length).decode("utf-8"))
|
|
186
|
+
token_val = payload.get("token")
|
|
187
|
+
if token_val:
|
|
188
|
+
relay.submit_token(str(token_val).strip())
|
|
189
|
+
self._send_response(200, '{"ok":true}')
|
|
190
|
+
else:
|
|
191
|
+
self._send_response(400, '{"error":"missing token"}')
|
|
192
|
+
else:
|
|
193
|
+
self._send_response(404, '{"error":"not found"}')
|
|
194
|
+
except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError):
|
|
195
|
+
pass
|
|
196
|
+
except Exception as e:
|
|
197
|
+
self._send_response(500, json.dumps({"error": str(e)}))
|
|
198
|
+
|
|
199
|
+
return RelayHTTPHandler
|