webrev 0.2.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.
- webrev/__init__.py +54 -0
- webrev/crypto.py +153 -0
- webrev/har.py +85 -0
- webrev/js_scan.py +84 -0
- webrev/pro/__init__.py +41 -0
- webrev/pro/browser.py +130 -0
- webrev/pro/graphql.py +80 -0
- webrev/pro/session.py +186 -0
- webrev/probe.py +114 -0
- webrev/tokens.py +61 -0
- webrev-0.2.0.dist-info/METADATA +150 -0
- webrev-0.2.0.dist-info/RECORD +15 -0
- webrev-0.2.0.dist-info/WHEEL +5 -0
- webrev-0.2.0.dist-info/licenses/LICENSE +21 -0
- webrev-0.2.0.dist-info/top_level.txt +1 -0
webrev/__init__.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""webrev — toolkit for reverse-engineering the hidden APIs behind web pages.
|
|
2
|
+
|
|
3
|
+
Core modules (no heavy dependencies):
|
|
4
|
+
crypto AES-CBC/AES-GCM + PBKDF2 helpers and JWT payload decoding.
|
|
5
|
+
js_scan Find endpoints, crypto constants and token flows in JS bundles.
|
|
6
|
+
har Parse DevTools HAR captures and list the API calls inside.
|
|
7
|
+
tokens Expiring-token cache with refresh-on-401 behaviour.
|
|
8
|
+
probe Replay HTTP requests with retries and structured results.
|
|
9
|
+
|
|
10
|
+
Pro extras (``pip install webrev[pro]``), in ``webrev.pro``:
|
|
11
|
+
session Cookie-aware HTTP session + CSRF token handling.
|
|
12
|
+
graphql GraphQL queries, introspection and schema summaries.
|
|
13
|
+
browser A real Chromium (Playwright) that records the API calls a
|
|
14
|
+
page actually makes, including ones plain HTTP cannot see.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
__version__ = "0.2.0"
|
|
18
|
+
|
|
19
|
+
from .crypto import (
|
|
20
|
+
aes_cbc_decrypt,
|
|
21
|
+
aes_cbc_encrypt,
|
|
22
|
+
aes_gcm_decrypt,
|
|
23
|
+
aes_gcm_decrypt_text,
|
|
24
|
+
aes_gcm_encrypt,
|
|
25
|
+
aes_gcm_encrypt_text,
|
|
26
|
+
derive_key_pbkdf2,
|
|
27
|
+
generate_nonce,
|
|
28
|
+
jwt_payload,
|
|
29
|
+
)
|
|
30
|
+
from .har import HarEntry, list_api_calls, load_har
|
|
31
|
+
from .js_scan import scan_js
|
|
32
|
+
from .probe import ProbeResult, fetch_text, probe
|
|
33
|
+
from .tokens import TokenCache
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"__version__",
|
|
37
|
+
"aes_cbc_decrypt",
|
|
38
|
+
"aes_cbc_encrypt",
|
|
39
|
+
"aes_gcm_decrypt",
|
|
40
|
+
"aes_gcm_decrypt_text",
|
|
41
|
+
"aes_gcm_encrypt",
|
|
42
|
+
"aes_gcm_encrypt_text",
|
|
43
|
+
"derive_key_pbkdf2",
|
|
44
|
+
"generate_nonce",
|
|
45
|
+
"jwt_payload",
|
|
46
|
+
"HarEntry",
|
|
47
|
+
"list_api_calls",
|
|
48
|
+
"load_har",
|
|
49
|
+
"scan_js",
|
|
50
|
+
"ProbeResult",
|
|
51
|
+
"fetch_text",
|
|
52
|
+
"probe",
|
|
53
|
+
"TokenCache",
|
|
54
|
+
]
|
webrev/crypto.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Crypto helpers for the payloads web apps actually use.
|
|
2
|
+
|
|
3
|
+
Web front-ends routinely encrypt request/response bodies with AES-CBC and
|
|
4
|
+
derive the key with PBKDF2, keeping the constants (passphrase, salt, IV) in
|
|
5
|
+
their own public JS bundle. These helpers do the primitive operations; the
|
|
6
|
+
constants themselves are inputs, never hard-coded here.
|
|
7
|
+
|
|
8
|
+
Requires the ``cryptography`` package.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import binascii
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
|
|
18
|
+
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
|
19
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
20
|
+
from cryptography.hazmat.primitives.padding import PKCS7
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _b64_or_hex(value: str) -> bytes:
|
|
24
|
+
"""Decode a Base64 (or hex) encoded string to raw bytes."""
|
|
25
|
+
try:
|
|
26
|
+
return base64.b64decode(value, validate=False)
|
|
27
|
+
except binascii.Error:
|
|
28
|
+
return bytes.fromhex(value)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def derive_key_pbkdf2(
|
|
32
|
+
passphrase: str,
|
|
33
|
+
salt: str,
|
|
34
|
+
iterations: int = 1000,
|
|
35
|
+
key_bits: int = 128,
|
|
36
|
+
hash_name: str = "sha1",
|
|
37
|
+
) -> bytes:
|
|
38
|
+
"""Derive an AES key with PBKDF2-HMAC.
|
|
39
|
+
|
|
40
|
+
Defaults mirror CryptoJS's ``PBKDF2`` defaults (SHA-1, 1000 iterations,
|
|
41
|
+
128-bit key), which is what many web bundles use. ``salt`` may be a hex
|
|
42
|
+
string (decoded as hex) or plain text.
|
|
43
|
+
"""
|
|
44
|
+
try:
|
|
45
|
+
salt_bytes = bytes.fromhex(salt)
|
|
46
|
+
except ValueError:
|
|
47
|
+
salt_bytes = salt.encode("utf-8")
|
|
48
|
+
return hashlib.pbkdf2_hmac(
|
|
49
|
+
hash_name,
|
|
50
|
+
passphrase.encode("utf-8"),
|
|
51
|
+
salt_bytes,
|
|
52
|
+
iterations,
|
|
53
|
+
dklen=key_bits // 8,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def aes_cbc_decrypt(ciphertext_b64: str, key: bytes, iv: str | bytes) -> bytes:
|
|
58
|
+
"""Decrypt Base64 AES-CBC ciphertext (PKCS7 padded) to raw bytes."""
|
|
59
|
+
iv_bytes = bytes.fromhex(iv) if isinstance(iv, str) else iv
|
|
60
|
+
cipher = Cipher(algorithms.AES(key), modes.CBC(iv_bytes))
|
|
61
|
+
decryptor = cipher.decryptor()
|
|
62
|
+
padded = decryptor.update(_b64_or_hex(ciphertext_b64)) + decryptor.finalize()
|
|
63
|
+
unpadder = PKCS7(128).unpadder()
|
|
64
|
+
return unpadder.update(padded) + unpadder.finalize()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def aes_cbc_decrypt_text(ciphertext_b64: str, key: bytes, iv: str | bytes) -> str:
|
|
68
|
+
"""Decrypt Base64 AES-CBC ciphertext to UTF-8 text."""
|
|
69
|
+
return aes_cbc_decrypt(ciphertext_b64, key, iv).decode("utf-8")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def aes_cbc_encrypt(plaintext: bytes | str, key: bytes, iv: str | bytes) -> str:
|
|
73
|
+
"""Encrypt bytes/str with AES-CBC (PKCS7) and return Base64 ciphertext."""
|
|
74
|
+
data = plaintext.encode("utf-8") if isinstance(plaintext, str) else plaintext
|
|
75
|
+
iv_bytes = bytes.fromhex(iv) if isinstance(iv, str) else iv
|
|
76
|
+
padder = PKCS7(128).padder()
|
|
77
|
+
padded = padder.update(data) + padder.finalize()
|
|
78
|
+
cipher = Cipher(algorithms.AES(key), modes.CBC(iv_bytes))
|
|
79
|
+
encryptor = cipher.encryptor()
|
|
80
|
+
return base64.b64encode(encryptor.update(padded) + encryptor.finalize()).decode("ascii")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def generate_nonce(nbytes: int = 12) -> bytes:
|
|
84
|
+
"""Generate a random nonce (12 bytes is the WebCrypto default for AES-GCM)."""
|
|
85
|
+
import os
|
|
86
|
+
|
|
87
|
+
return os.urandom(nbytes)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def aes_gcm_encrypt(
|
|
91
|
+
plaintext: bytes | str,
|
|
92
|
+
key: bytes,
|
|
93
|
+
nonce: bytes,
|
|
94
|
+
associated_data: bytes | None = None,
|
|
95
|
+
) -> bytes:
|
|
96
|
+
"""Encrypt with AES-GCM (the WebCrypto default). Returns ciphertext+tag.
|
|
97
|
+
|
|
98
|
+
``nonce`` is usually 12 random bytes (see :func:`generate_nonce`).
|
|
99
|
+
``associated_data`` is authenticated but not encrypted, when the app
|
|
100
|
+
uses it (often the string ``"AES-GCM"`` or an empty value).
|
|
101
|
+
"""
|
|
102
|
+
data = plaintext.encode("utf-8") if isinstance(plaintext, str) else plaintext
|
|
103
|
+
return AESGCM(key).encrypt(nonce, data, associated_data)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def aes_gcm_decrypt(
|
|
107
|
+
ciphertext_and_tag: bytes,
|
|
108
|
+
key: bytes,
|
|
109
|
+
nonce: bytes,
|
|
110
|
+
associated_data: bytes | None = None,
|
|
111
|
+
) -> bytes:
|
|
112
|
+
"""Decrypt AES-GCM ciphertext+tag. Raises if the tag does not verify."""
|
|
113
|
+
return AESGCM(key).decrypt(nonce, ciphertext_and_tag, associated_data)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def aes_gcm_encrypt_text(
|
|
117
|
+
plaintext: str,
|
|
118
|
+
key: bytes,
|
|
119
|
+
nonce: bytes,
|
|
120
|
+
associated_data: bytes | None = None,
|
|
121
|
+
) -> str:
|
|
122
|
+
"""AES-GCM encrypt to a Base64 string (ciphertext+tag)."""
|
|
123
|
+
return base64.b64encode(
|
|
124
|
+
aes_gcm_encrypt(plaintext, key, nonce, associated_data)
|
|
125
|
+
).decode("ascii")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def aes_gcm_decrypt_text(
|
|
129
|
+
ciphertext_b64: str,
|
|
130
|
+
key: bytes,
|
|
131
|
+
nonce: str | bytes,
|
|
132
|
+
associated_data: bytes | None = None,
|
|
133
|
+
) -> str:
|
|
134
|
+
"""Decrypt Base64 AES-GCM ciphertext+tag to UTF-8 text."""
|
|
135
|
+
nonce_bytes = bytes.fromhex(nonce) if isinstance(nonce, str) else nonce
|
|
136
|
+
return aes_gcm_decrypt(
|
|
137
|
+
_b64_or_hex(ciphertext_b64), key, nonce_bytes, associated_data
|
|
138
|
+
).decode("utf-8")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def jwt_payload(token: str) -> dict:
|
|
142
|
+
"""Decode the payload of a JWT (or JWT-like ``header.payload`` token).
|
|
143
|
+
|
|
144
|
+
No signature verification: this is for *reading* the claims (``exp``,
|
|
145
|
+
``iat``, fingerprints, ...) that tell you how a token behaves, exactly
|
|
146
|
+
what you need when reverse-engineering a token flow.
|
|
147
|
+
"""
|
|
148
|
+
parts = token.split(".")
|
|
149
|
+
if len(parts) < 2:
|
|
150
|
+
raise ValueError("not a JWT-like token")
|
|
151
|
+
segment = parts[1]
|
|
152
|
+
segment += "=" * (-len(segment) % 4)
|
|
153
|
+
return json.loads(base64.urlsafe_b64decode(segment).decode("utf-8"))
|
webrev/har.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Parse DevTools HAR captures and list the API calls inside.
|
|
2
|
+
|
|
3
|
+
A HAR file (DevTools → Network → Export HAR) is the ground truth of what a
|
|
4
|
+
web app actually requests: method, URL, headers, bodies, status and timing.
|
|
5
|
+
These helpers turn it into a short list of candidate API calls so you can
|
|
6
|
+
replay the interesting ones instead of re-reading the whole capture.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import json
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class HarEntry:
|
|
18
|
+
"""One HTTP exchange from a HAR capture."""
|
|
19
|
+
|
|
20
|
+
method: str
|
|
21
|
+
url: str
|
|
22
|
+
status: int
|
|
23
|
+
mime_type: str = ""
|
|
24
|
+
request_headers: dict = field(default_factory=dict)
|
|
25
|
+
request_body: str = ""
|
|
26
|
+
response_body: str = ""
|
|
27
|
+
time_ms: float = 0.0
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def is_api(self) -> bool:
|
|
31
|
+
return "/api/" in self.url or "application/json" in self.mime_type
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def host(self) -> str:
|
|
35
|
+
return self.url.split("/")[2] if "://" in self.url else ""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _text_of(content: dict | None) -> str:
|
|
39
|
+
if not content:
|
|
40
|
+
return ""
|
|
41
|
+
text = content.get("text") or ""
|
|
42
|
+
if content.get("encoding") == "base64" and text:
|
|
43
|
+
try:
|
|
44
|
+
return base64.b64decode(text).decode("utf-8", "replace")
|
|
45
|
+
except Exception:
|
|
46
|
+
return ""
|
|
47
|
+
return text
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def load_har(path: str) -> list[HarEntry]:
|
|
51
|
+
"""Load a HAR file and return every recorded exchange."""
|
|
52
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
53
|
+
har = json.load(f)
|
|
54
|
+
entries = []
|
|
55
|
+
for raw in har.get("log", {}).get("entries", []):
|
|
56
|
+
req, res = raw.get("request", {}), raw.get("response", {})
|
|
57
|
+
entries.append(
|
|
58
|
+
HarEntry(
|
|
59
|
+
method=req.get("method", ""),
|
|
60
|
+
url=req.get("url", ""),
|
|
61
|
+
status=res.get("status", 0),
|
|
62
|
+
mime_type=res.get("content", {}).get("mimeType", ""),
|
|
63
|
+
request_headers={
|
|
64
|
+
h.get("name", ""): h.get("value", "")
|
|
65
|
+
for h in req.get("headers", [])
|
|
66
|
+
},
|
|
67
|
+
request_body=(req.get("postData") or {}).get("text", ""),
|
|
68
|
+
response_body=_text_of(res.get("content")),
|
|
69
|
+
time_ms=float(raw.get("time", 0.0)),
|
|
70
|
+
)
|
|
71
|
+
)
|
|
72
|
+
return entries
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def list_api_calls(entries: list[HarEntry], only_api: bool = True) -> list[HarEntry]:
|
|
76
|
+
"""Filter HAR entries down to the API calls (JSON or /api/ URLs)."""
|
|
77
|
+
return [e for e in entries if (e.is_api if only_api else True)]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def group_by_host(entries: list[HarEntry]) -> dict[str, list[HarEntry]]:
|
|
81
|
+
"""Group entries by host so you can see which back-ends a page uses."""
|
|
82
|
+
grouped: dict[str, list[HarEntry]] = {}
|
|
83
|
+
for entry in entries:
|
|
84
|
+
grouped.setdefault(entry.host, []).append(entry)
|
|
85
|
+
return grouped
|
webrev/js_scan.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Find API endpoints and crypto constants in a site's JS bundles.
|
|
2
|
+
|
|
3
|
+
When a web app talks to a hidden API, the evidence is in its own JavaScript:
|
|
4
|
+
endpoint paths, ``fetch``/XHR calls, custom headers, and the constants used
|
|
5
|
+
to encrypt payloads or obtain tokens. ``scan_js`` extracts those signals so
|
|
6
|
+
you can reconstruct the API without guessing.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
|
|
14
|
+
_URL_RE = re.compile(r"""https?://[A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=%]+""")
|
|
15
|
+
_PATH_RE = re.compile(r"""["'`](/(?:api|v\d|auth|core|pay|q|resource)[A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=%]*)["'`]""")
|
|
16
|
+
_FETCH_RE = re.compile(r"""\b(?:fetch|axios\.(?:get|post|put|delete|patch)|(?:\w+\.)?(?:get|post)\s*\()\s*\(\s*["'`]([^"'`]{1,200})["'`]""")
|
|
17
|
+
_HEADER_RE = re.compile(r"""["'`]([xX]-[A-Za-z0-9\-]{2,40}|[Aa]uthorization|[Xx]-[A-Za-z0-9\-]{2,40})["'`]\s*:""")
|
|
18
|
+
_HEX32_RE = re.compile(r"""["'`]([0-9a-fA-F]{32,64})["'`]""")
|
|
19
|
+
_PASSPHRASE_RE = re.compile(
|
|
20
|
+
r"""(?:passPhrase|passphrase|password|secret|salt|iv)\s*[:=]\s*["'`]([^"'`]{4,64})["'`]""",
|
|
21
|
+
re.IGNORECASE,
|
|
22
|
+
)
|
|
23
|
+
_CRYPTO_KW_RE = re.compile(
|
|
24
|
+
r"""\b(AES|CryptoJS|PBKDF2|createCipheriv|createDecipheriv|getRandomValues|btoa|atob)\b"""
|
|
25
|
+
)
|
|
26
|
+
_TOKEN_RE = re.compile(
|
|
27
|
+
r"""["'`]([^"'`]{0,80}(?:token|auth|login|sso|otp)[^"'`]{0,80})["'`]""",
|
|
28
|
+
re.IGNORECASE,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class JsFindings:
|
|
34
|
+
"""What a JS bundle reveals about the site's hidden API."""
|
|
35
|
+
|
|
36
|
+
urls: list[str] = field(default_factory=list)
|
|
37
|
+
api_paths: list[str] = field(default_factory=list)
|
|
38
|
+
fetch_calls: list[str] = field(default_factory=list)
|
|
39
|
+
headers: list[str] = field(default_factory=list)
|
|
40
|
+
hex_strings: list[str] = field(default_factory=list)
|
|
41
|
+
passphrases: dict[str, str] = field(default_factory=dict)
|
|
42
|
+
crypto_keywords: list[str] = field(default_factory=list)
|
|
43
|
+
token_strings: list[str] = field(default_factory=list)
|
|
44
|
+
|
|
45
|
+
def summary(self) -> str:
|
|
46
|
+
lines = [
|
|
47
|
+
f"urls: {len(self.urls)}",
|
|
48
|
+
f"api paths: {len(self.api_paths)}",
|
|
49
|
+
f"fetch calls: {len(self.fetch_calls)}",
|
|
50
|
+
f"custom headers: {sorted(set(self.headers))}",
|
|
51
|
+
f"crypto keywords: {sorted(set(self.crypto_keywords))}",
|
|
52
|
+
f"hex strings (possible keys/IVs): {len(self.hex_strings)}",
|
|
53
|
+
f"passphrase-like values: {len(self.passphrases)}",
|
|
54
|
+
f"token-related strings: {len(self.token_strings)}",
|
|
55
|
+
]
|
|
56
|
+
return "\n".join(lines)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _dedup(seq):
|
|
60
|
+
seen, out = set(), []
|
|
61
|
+
for item in seq:
|
|
62
|
+
if item not in seen:
|
|
63
|
+
seen.add(item)
|
|
64
|
+
out.append(item)
|
|
65
|
+
return out
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def scan_js(source: str) -> JsFindings:
|
|
69
|
+
"""Scan JS source text and return the API-relevant signals in it."""
|
|
70
|
+
findings = JsFindings(
|
|
71
|
+
urls=_dedup(_URL_RE.findall(source)),
|
|
72
|
+
api_paths=_dedup(_PATH_RE.findall(source)),
|
|
73
|
+
fetch_calls=_dedup(_FETCH_RE.findall(source)),
|
|
74
|
+
headers=_dedup(_HEADER_RE.findall(source)),
|
|
75
|
+
hex_strings=_dedup(_HEX32_RE.findall(source)),
|
|
76
|
+
crypto_keywords=_dedup(_CRYPTO_KW_RE.findall(source)),
|
|
77
|
+
)
|
|
78
|
+
for match in _PASSPHRASE_RE.finditer(source):
|
|
79
|
+
key = match.group(0).split(":", 1)[0].split("=", 1)[0].strip().strip("\"'`")
|
|
80
|
+
findings.passphrases[key] = match.group(1)
|
|
81
|
+
findings.token_strings = _dedup(
|
|
82
|
+
s for s in _TOKEN_RE.findall(source) if len(s) <= 120
|
|
83
|
+
)[:50]
|
|
84
|
+
return findings
|
webrev/pro/__init__.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""webrev.pro — optional "pro" extras for the modern web.
|
|
2
|
+
|
|
3
|
+
These modules are installed separately so the core stays light:
|
|
4
|
+
|
|
5
|
+
pip install webrev[pro]
|
|
6
|
+
|
|
7
|
+
What lives here:
|
|
8
|
+
|
|
9
|
+
session Cookie-aware HTTP session + CSRF token handling.
|
|
10
|
+
graphql GraphQL queries, introspection and schema summaries.
|
|
11
|
+
browser A real Chromium (Playwright) that records the API calls a
|
|
12
|
+
page actually makes, including ones plain HTTP cannot see.
|
|
13
|
+
|
|
14
|
+
``session`` and ``graphql`` need nothing beyond the core dependencies.
|
|
15
|
+
``browser`` needs Playwright and a Chromium binary (``playwright install
|
|
16
|
+
chromium``); importing it without Playwright raises a clear error instead
|
|
17
|
+
of breaking the rest of the package.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from .graphql import graphql_query, introspect, schema_summary
|
|
23
|
+
from .session import Session
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"Session",
|
|
27
|
+
"graphql_query",
|
|
28
|
+
"introspect",
|
|
29
|
+
"schema_summary",
|
|
30
|
+
"capture_page",
|
|
31
|
+
"capture_api_calls",
|
|
32
|
+
"run_js",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def __getattr__(name: str):
|
|
37
|
+
if name in {"capture_page", "capture_api_calls", "run_js"}:
|
|
38
|
+
from . import browser
|
|
39
|
+
|
|
40
|
+
return getattr(browser, name)
|
|
41
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
webrev/pro/browser.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Record what a page really does, using a real Chromium (Playwright).
|
|
2
|
+
|
|
3
|
+
Plain HTTP cannot see what JavaScript does in the browser: dynamic tokens,
|
|
4
|
+
requests fired after render, cookies set by scripts. This module opens the
|
|
5
|
+
page in a real Chromium, records every network request/response, and hands
|
|
6
|
+
you the API calls as :class:`~webrev.har.HarEntry` objects — the same shape
|
|
7
|
+
the core ``har`` module produces from a DevTools capture.
|
|
8
|
+
|
|
9
|
+
Requires the pro extra:
|
|
10
|
+
|
|
11
|
+
pip install webrev[pro]
|
|
12
|
+
playwright install chromium
|
|
13
|
+
|
|
14
|
+
Playwright is imported lazily, so importing ``webrev`` never requires it.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
|
|
21
|
+
from ..har import HarEntry, list_api_calls
|
|
22
|
+
|
|
23
|
+
_MAX_BODY = 1_000_000
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _require_playwright():
|
|
27
|
+
try:
|
|
28
|
+
from playwright.sync_api import sync_playwright
|
|
29
|
+
|
|
30
|
+
return sync_playwright
|
|
31
|
+
except ImportError as exc:
|
|
32
|
+
raise RuntimeError(
|
|
33
|
+
"webrev.pro.browser needs Playwright: "
|
|
34
|
+
"pip install webrev[pro] && playwright install chromium"
|
|
35
|
+
) from exc
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class BrowserCapture:
|
|
40
|
+
"""Everything a page load produced."""
|
|
41
|
+
|
|
42
|
+
url: str
|
|
43
|
+
title: str = ""
|
|
44
|
+
entries: list[HarEntry] = field(default_factory=list)
|
|
45
|
+
cookies: list[dict] = field(default_factory=list)
|
|
46
|
+
html: str = ""
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def api_calls(self) -> list[HarEntry]:
|
|
50
|
+
return list_api_calls(self.entries)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def capture_page(
|
|
54
|
+
url: str,
|
|
55
|
+
wait_ms: int = 3000,
|
|
56
|
+
headless: bool = True,
|
|
57
|
+
extra_headers: dict | None = None,
|
|
58
|
+
user_agent: str | None = None,
|
|
59
|
+
) -> BrowserCapture:
|
|
60
|
+
"""Open ``url`` in Chromium and record its network traffic.
|
|
61
|
+
|
|
62
|
+
Waits ``wait_ms`` after the page loads so JavaScript has time to fire
|
|
63
|
+
its API calls, then returns the capture.
|
|
64
|
+
"""
|
|
65
|
+
sync_playwright = _require_playwright()
|
|
66
|
+
entries: list[HarEntry] = []
|
|
67
|
+
with sync_playwright() as pw:
|
|
68
|
+
browser = pw.chromium.launch(headless=headless)
|
|
69
|
+
context = browser.new_context(
|
|
70
|
+
extra_http_headers=extra_headers or {},
|
|
71
|
+
user_agent=user_agent,
|
|
72
|
+
)
|
|
73
|
+
page = context.new_page()
|
|
74
|
+
|
|
75
|
+
def on_response(response):
|
|
76
|
+
try:
|
|
77
|
+
body = ""
|
|
78
|
+
ctype = response.headers.get("content-type", "")
|
|
79
|
+
if "json" in ctype or "text" in ctype:
|
|
80
|
+
raw = response.body()
|
|
81
|
+
if len(raw) <= _MAX_BODY:
|
|
82
|
+
body = raw.decode("utf-8", "replace")
|
|
83
|
+
entries.append(
|
|
84
|
+
HarEntry(
|
|
85
|
+
method=response.request.method,
|
|
86
|
+
url=response.url,
|
|
87
|
+
status=response.status,
|
|
88
|
+
mime_type=ctype,
|
|
89
|
+
request_headers=dict(response.request.headers),
|
|
90
|
+
request_body=response.request.post_data or "",
|
|
91
|
+
response_body=body,
|
|
92
|
+
)
|
|
93
|
+
)
|
|
94
|
+
except Exception:
|
|
95
|
+
pass
|
|
96
|
+
|
|
97
|
+
page.on("response", on_response)
|
|
98
|
+
page.goto(url, wait_until="load", timeout=30000)
|
|
99
|
+
page.wait_for_timeout(wait_ms)
|
|
100
|
+
title = page.title()
|
|
101
|
+
html = page.content()
|
|
102
|
+
cookies = context.cookies()
|
|
103
|
+
browser.close()
|
|
104
|
+
return BrowserCapture(
|
|
105
|
+
url=url, title=title, entries=entries, cookies=cookies, html=html
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def capture_api_calls(
|
|
110
|
+
url: str, wait_ms: int = 3000, **kwargs
|
|
111
|
+
) -> list[HarEntry]:
|
|
112
|
+
"""Open ``url`` in Chromium and return only its API calls."""
|
|
113
|
+
return capture_page(url, wait_ms=wait_ms, **kwargs).api_calls
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def run_js(url: str, expression: str, wait_ms: int = 2000, **kwargs) -> object:
|
|
117
|
+
"""Open ``url`` in Chromium, evaluate ``expression`` and return the result.
|
|
118
|
+
|
|
119
|
+
Useful for reading values JavaScript computes at runtime (tokens,
|
|
120
|
+
fingerprints, config objects) that never appear in the static bundle.
|
|
121
|
+
"""
|
|
122
|
+
sync_playwright = _require_playwright()
|
|
123
|
+
with sync_playwright() as pw:
|
|
124
|
+
browser = pw.chromium.launch(headless=kwargs.pop("headless", True))
|
|
125
|
+
page = browser.new_page(**kwargs)
|
|
126
|
+
page.goto(url, wait_until="load", timeout=30000)
|
|
127
|
+
page.wait_for_timeout(wait_ms)
|
|
128
|
+
result = page.evaluate(expression)
|
|
129
|
+
browser.close()
|
|
130
|
+
return result
|
webrev/pro/graphql.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""GraphQL helpers: run queries and read a schema via introspection.
|
|
2
|
+
|
|
3
|
+
Many modern front-ends talk to a single ``/graphql`` endpoint instead of
|
|
4
|
+
many REST routes. These helpers POST the query (reusing the core ``probe``),
|
|
5
|
+
run the standard introspection query, and summarize the schema so you can
|
|
6
|
+
see which queries and mutations exist without reading the whole schema.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from ..probe import probe
|
|
12
|
+
|
|
13
|
+
INTROSPECTION_QUERY = """
|
|
14
|
+
query IntrospectionQuery {
|
|
15
|
+
__schema {
|
|
16
|
+
queryType { name }
|
|
17
|
+
mutationType { name }
|
|
18
|
+
types {
|
|
19
|
+
name
|
|
20
|
+
kind
|
|
21
|
+
fields { name }
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def graphql_query(
|
|
29
|
+
endpoint: str,
|
|
30
|
+
query: str,
|
|
31
|
+
variables: dict | None = None,
|
|
32
|
+
headers: dict | None = None,
|
|
33
|
+
operation_name: str | None = None,
|
|
34
|
+
) -> dict:
|
|
35
|
+
"""POST a GraphQL query/mutation and return the parsed JSON response.
|
|
36
|
+
|
|
37
|
+
Raises :class:`RuntimeError` when the endpoint answers with a non-200
|
|
38
|
+
status or with a top-level ``errors`` entry and no ``data``.
|
|
39
|
+
"""
|
|
40
|
+
payload: dict = {"query": query}
|
|
41
|
+
if variables:
|
|
42
|
+
payload["variables"] = variables
|
|
43
|
+
if operation_name:
|
|
44
|
+
payload["operationName"] = operation_name
|
|
45
|
+
result = probe("POST", endpoint, headers=headers, json_body=payload)
|
|
46
|
+
data = result.json
|
|
47
|
+
if result.status != 200:
|
|
48
|
+
raise RuntimeError(
|
|
49
|
+
f"GraphQL endpoint returned HTTP {result.status}: {result.text[:300]}"
|
|
50
|
+
)
|
|
51
|
+
if data is None:
|
|
52
|
+
raise RuntimeError(f"GraphQL endpoint returned non-JSON: {result.text[:300]}")
|
|
53
|
+
if data.get("errors") and not data.get("data"):
|
|
54
|
+
raise RuntimeError(f"GraphQL errors: {data['errors']}")
|
|
55
|
+
return data
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def introspect(endpoint: str, headers: dict | None = None) -> dict:
|
|
59
|
+
"""Run the introspection query against ``endpoint`` and return the schema."""
|
|
60
|
+
return graphql_query(endpoint, INTROSPECTION_QUERY, headers=headers)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def schema_summary(schema_response: dict) -> dict:
|
|
64
|
+
"""Summarize an introspection result: root fields and type names."""
|
|
65
|
+
schema = schema_response.get("data", {}).get("__schema", {})
|
|
66
|
+
types = schema.get("types") or []
|
|
67
|
+
by_name = {t.get("name"): t for t in types if t.get("name")}
|
|
68
|
+
|
|
69
|
+
def root_fields(kind_key: str) -> list[str]:
|
|
70
|
+
root = schema.get(kind_key) or {}
|
|
71
|
+
root_type = by_name.get(root.get("name") or "")
|
|
72
|
+
if not root_type:
|
|
73
|
+
return []
|
|
74
|
+
return [f.get("name") for f in (root_type.get("fields") or [])]
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
"query_fields": root_fields("queryType"),
|
|
78
|
+
"mutation_fields": root_fields("mutationType"),
|
|
79
|
+
"type_names": sorted(by_name),
|
|
80
|
+
}
|
webrev/pro/session.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Cookie-aware HTTP session with CSRF handling (stdlib only).
|
|
2
|
+
|
|
3
|
+
Most modern web apps keep state in cookies and require a CSRF token on
|
|
4
|
+
state-changing requests: you GET a page, the server sets a session cookie
|
|
5
|
+
and embeds a token in the HTML, then you POST the form with that token.
|
|
6
|
+
``Session`` does that round trip for you, keeping the cookies between
|
|
7
|
+
requests. It returns :class:`~webrev.probe.ProbeResult` like the core
|
|
8
|
+
``probe`` helper, so results look the same everywhere.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import http.cookiejar
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.parse
|
|
18
|
+
import urllib.request
|
|
19
|
+
|
|
20
|
+
from ..probe import ProbeResult
|
|
21
|
+
|
|
22
|
+
_META_CSRF_RE = re.compile(
|
|
23
|
+
r"""<meta[^>]+name=["']csrf-token["'][^>]+content=["']([^"']+)["']""",
|
|
24
|
+
re.IGNORECASE,
|
|
25
|
+
)
|
|
26
|
+
_META_CSRF_RE2 = re.compile(
|
|
27
|
+
r"""<meta[^>]+content=["']([^"']+)["'][^>]+name=["']csrf-token["']""",
|
|
28
|
+
re.IGNORECASE,
|
|
29
|
+
)
|
|
30
|
+
_INPUT_CSRF_RE = re.compile(
|
|
31
|
+
r"""<input[^>]+name=["']([^"']*(?:csrf|authenticity)[^"']*)["'][^>]+value=["']([^"']+)["']""",
|
|
32
|
+
re.IGNORECASE,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Session:
|
|
37
|
+
"""A stateful HTTP client: cookies persist, CSRF tokens are extracted."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, headers: dict | None = None):
|
|
40
|
+
self.jar = http.cookiejar.CookieJar()
|
|
41
|
+
self.opener = urllib.request.build_opener(
|
|
42
|
+
urllib.request.HTTPCookieProcessor(self.jar)
|
|
43
|
+
)
|
|
44
|
+
self.headers = dict(headers or {})
|
|
45
|
+
|
|
46
|
+
def _do(
|
|
47
|
+
self, method: str, url: str, data: bytes | None, headers: dict
|
|
48
|
+
) -> ProbeResult:
|
|
49
|
+
req = urllib.request.Request(url, data=data, method=method)
|
|
50
|
+
merged = dict(self.headers)
|
|
51
|
+
merged.update(headers)
|
|
52
|
+
for key, value in merged.items():
|
|
53
|
+
req.add_header(key, value)
|
|
54
|
+
try:
|
|
55
|
+
with self.opener.open(req, timeout=15) as resp:
|
|
56
|
+
return ProbeResult(
|
|
57
|
+
status=resp.status,
|
|
58
|
+
headers=dict(resp.headers),
|
|
59
|
+
body=resp.read(),
|
|
60
|
+
url=url,
|
|
61
|
+
)
|
|
62
|
+
except urllib.error.HTTPError as e:
|
|
63
|
+
return ProbeResult(
|
|
64
|
+
status=e.code,
|
|
65
|
+
headers=dict(e.headers or {}),
|
|
66
|
+
body=e.read(),
|
|
67
|
+
url=url,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def request(
|
|
71
|
+
self,
|
|
72
|
+
method: str,
|
|
73
|
+
url: str,
|
|
74
|
+
headers: dict | None = None,
|
|
75
|
+
json_body: dict | None = None,
|
|
76
|
+
form_body: dict | None = None,
|
|
77
|
+
raw_body: bytes | str | None = None,
|
|
78
|
+
) -> ProbeResult:
|
|
79
|
+
data: bytes | None = None
|
|
80
|
+
headers = dict(headers or {})
|
|
81
|
+
if json_body is not None:
|
|
82
|
+
data = json.dumps(json_body).encode("utf-8")
|
|
83
|
+
headers.setdefault("Content-Type", "application/json")
|
|
84
|
+
elif form_body is not None:
|
|
85
|
+
data = urllib.parse.urlencode(form_body).encode("utf-8")
|
|
86
|
+
headers.setdefault(
|
|
87
|
+
"Content-Type", "application/x-www-form-urlencoded"
|
|
88
|
+
)
|
|
89
|
+
elif raw_body is not None:
|
|
90
|
+
data = (
|
|
91
|
+
raw_body.encode("utf-8")
|
|
92
|
+
if isinstance(raw_body, str)
|
|
93
|
+
else raw_body
|
|
94
|
+
)
|
|
95
|
+
return self._do(method, url, data, headers)
|
|
96
|
+
|
|
97
|
+
def get(self, url: str, headers: dict | None = None) -> ProbeResult:
|
|
98
|
+
return self.request("GET", url, headers=headers)
|
|
99
|
+
|
|
100
|
+
def post(
|
|
101
|
+
self,
|
|
102
|
+
url: str,
|
|
103
|
+
headers: dict | None = None,
|
|
104
|
+
json_body: dict | None = None,
|
|
105
|
+
form_body: dict | None = None,
|
|
106
|
+
raw_body: bytes | str | None = None,
|
|
107
|
+
) -> ProbeResult:
|
|
108
|
+
return self.request(
|
|
109
|
+
"POST",
|
|
110
|
+
url,
|
|
111
|
+
headers=headers,
|
|
112
|
+
json_body=json_body,
|
|
113
|
+
form_body=form_body,
|
|
114
|
+
raw_body=raw_body,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
def cookies(self) -> dict[str, str]:
|
|
118
|
+
"""Current cookies as a plain dict."""
|
|
119
|
+
return {c.name: c.value for c in self.jar}
|
|
120
|
+
|
|
121
|
+
def save_cookies(self, path: str) -> None:
|
|
122
|
+
jar = http.cookiejar.MozillaCookieJar(path)
|
|
123
|
+
for cookie in self.jar:
|
|
124
|
+
jar.set_cookie(cookie)
|
|
125
|
+
jar.save(ignore_discard=True, ignore_expires=True)
|
|
126
|
+
|
|
127
|
+
def load_cookies(self, path: str) -> None:
|
|
128
|
+
jar = http.cookiejar.MozillaCookieJar(path)
|
|
129
|
+
jar.load(ignore_discard=True, ignore_expires=True)
|
|
130
|
+
for cookie in jar:
|
|
131
|
+
self.jar.set_cookie(cookie)
|
|
132
|
+
|
|
133
|
+
@staticmethod
|
|
134
|
+
def extract_csrf(html: str) -> tuple[str, str] | None:
|
|
135
|
+
"""Find a CSRF token in HTML.
|
|
136
|
+
|
|
137
|
+
Returns ``(field_name, token)``: from a ``<meta name="csrf-token">``
|
|
138
|
+
tag (field name ``"X-CSRF-Token"``) or from a hidden ``<input>``
|
|
139
|
+
whose name contains ``csrf`` or ``authenticity``. Returns ``None``
|
|
140
|
+
when no token is found.
|
|
141
|
+
"""
|
|
142
|
+
for pattern in (_META_CSRF_RE, _META_CSRF_RE2):
|
|
143
|
+
match = pattern.search(html)
|
|
144
|
+
if match:
|
|
145
|
+
return ("X-CSRF-Token", match.group(1))
|
|
146
|
+
match = _INPUT_CSRF_RE.search(html)
|
|
147
|
+
if match:
|
|
148
|
+
return (match.group(1), match.group(2))
|
|
149
|
+
return None
|
|
150
|
+
|
|
151
|
+
def get_csrf(self, page_url: str) -> tuple[str, str] | None:
|
|
152
|
+
"""GET a page and extract its CSRF token (if any)."""
|
|
153
|
+
result = self.get(page_url)
|
|
154
|
+
if result.status != 200:
|
|
155
|
+
return None
|
|
156
|
+
return self.extract_csrf(result.text)
|
|
157
|
+
|
|
158
|
+
def submit_form(
|
|
159
|
+
self,
|
|
160
|
+
page_url: str,
|
|
161
|
+
form_url: str,
|
|
162
|
+
fields: dict,
|
|
163
|
+
token_field: str | None = None,
|
|
164
|
+
token_header: str | None = None,
|
|
165
|
+
) -> ProbeResult:
|
|
166
|
+
"""GET ``page_url`` for its CSRF token, then POST ``fields`` to ``form_url``.
|
|
167
|
+
|
|
168
|
+
By default the token goes into the form fields under its own field
|
|
169
|
+
name (hidden input) or, when the page used a ``<meta>`` tag, as the
|
|
170
|
+
``X-CSRF-Token`` header. Pass ``token_field`` to force a field name
|
|
171
|
+
or ``token_header`` to force a header name.
|
|
172
|
+
"""
|
|
173
|
+
found = self.get_csrf(page_url)
|
|
174
|
+
headers: dict[str, str] = {}
|
|
175
|
+
body = dict(fields)
|
|
176
|
+
if found is not None:
|
|
177
|
+
name, token = found
|
|
178
|
+
if token_header is not None:
|
|
179
|
+
headers[token_header] = token
|
|
180
|
+
elif token_field is not None:
|
|
181
|
+
body[token_field] = token
|
|
182
|
+
elif name == "X-CSRF-Token":
|
|
183
|
+
headers[name] = token
|
|
184
|
+
else:
|
|
185
|
+
body[name] = token
|
|
186
|
+
return self.post(form_url, headers=headers, form_body=body)
|
webrev/probe.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Replay HTTP requests against a discovered API, with retries.
|
|
2
|
+
|
|
3
|
+
Once you know an endpoint exists, the next step is probing it: send the
|
|
4
|
+
request the web app sends, see what comes back, and iterate. ``probe`` is a
|
|
5
|
+
thin wrapper over ``urllib`` that returns a structured result (never raising
|
|
6
|
+
for HTTP error statuses), retries on 429/5xx, and can carry a
|
|
7
|
+
:class:`~webrev.tokens.TokenCache` so a 401 triggers one token refresh and
|
|
8
|
+
one retry.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import time
|
|
15
|
+
import urllib.error
|
|
16
|
+
import urllib.request
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
|
|
19
|
+
from .tokens import TokenCache
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class ProbeResult:
|
|
24
|
+
status: int
|
|
25
|
+
headers: dict = field(default_factory=dict)
|
|
26
|
+
body: bytes = b""
|
|
27
|
+
url: str = ""
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def text(self) -> str:
|
|
31
|
+
return self.body.decode("utf-8", "replace")
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def json(self):
|
|
35
|
+
try:
|
|
36
|
+
return json.loads(self.body.decode("utf-8"))
|
|
37
|
+
except (ValueError, UnicodeDecodeError):
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _do(method: str, url: str, headers: dict, data: bytes | None, timeout: float) -> ProbeResult:
|
|
42
|
+
req = urllib.request.Request(url, data=data, method=method)
|
|
43
|
+
for key, value in headers.items():
|
|
44
|
+
req.add_header(key, value)
|
|
45
|
+
try:
|
|
46
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
47
|
+
return ProbeResult(
|
|
48
|
+
status=resp.status,
|
|
49
|
+
headers=dict(resp.headers),
|
|
50
|
+
body=resp.read(),
|
|
51
|
+
url=url,
|
|
52
|
+
)
|
|
53
|
+
except urllib.error.HTTPError as e:
|
|
54
|
+
return ProbeResult(
|
|
55
|
+
status=e.code,
|
|
56
|
+
headers=dict(e.headers or {}),
|
|
57
|
+
body=e.read(),
|
|
58
|
+
url=url,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def probe(
|
|
63
|
+
method: str,
|
|
64
|
+
url: str,
|
|
65
|
+
headers: dict | None = None,
|
|
66
|
+
json_body: dict | None = None,
|
|
67
|
+
form_body: dict | None = None,
|
|
68
|
+
raw_body: bytes | str | None = None,
|
|
69
|
+
timeout: float = 15.0,
|
|
70
|
+
retries: int = 2,
|
|
71
|
+
retry_statuses: tuple[int, ...] = (429, 500, 502, 503, 504),
|
|
72
|
+
retry_delay: float = 2.0,
|
|
73
|
+
token_cache: TokenCache | None = None,
|
|
74
|
+
token_header: str = "Authorization",
|
|
75
|
+
token_prefix: str = "Bearer ",
|
|
76
|
+
) -> ProbeResult:
|
|
77
|
+
"""Send one request, retrying on ``retry_statuses`` and on 401 (once, with a fresh token)."""
|
|
78
|
+
headers = dict(headers or {})
|
|
79
|
+
data: bytes | None = None
|
|
80
|
+
if json_body is not None:
|
|
81
|
+
data = json.dumps(json_body).encode("utf-8")
|
|
82
|
+
headers.setdefault("Content-Type", "application/json")
|
|
83
|
+
elif form_body is not None:
|
|
84
|
+
from urllib.parse import urlencode
|
|
85
|
+
|
|
86
|
+
data = urlencode(form_body).encode("utf-8")
|
|
87
|
+
headers.setdefault("Content-Type", "application/x-www-form-urlencoded")
|
|
88
|
+
elif raw_body is not None:
|
|
89
|
+
data = raw_body.encode("utf-8") if isinstance(raw_body, str) else raw_body
|
|
90
|
+
|
|
91
|
+
refreshed = False
|
|
92
|
+
attempts = 0
|
|
93
|
+
while True:
|
|
94
|
+
if token_cache is not None:
|
|
95
|
+
headers[token_header] = token_prefix + token_cache.get()
|
|
96
|
+
result = _do(method, url, headers, data, timeout)
|
|
97
|
+
if result.status == 401 and token_cache is not None and not refreshed:
|
|
98
|
+
# Fresh token, one retry: does not consume a status retry.
|
|
99
|
+
token_cache.invalidate()
|
|
100
|
+
refreshed = True
|
|
101
|
+
continue
|
|
102
|
+
if result.status in retry_statuses and attempts < retries:
|
|
103
|
+
attempts += 1
|
|
104
|
+
time.sleep(retry_delay)
|
|
105
|
+
continue
|
|
106
|
+
return result
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def fetch_text(url: str, headers: dict | None = None, timeout: float = 15.0) -> str:
|
|
110
|
+
"""GET a URL (typically a JS bundle) and return its text."""
|
|
111
|
+
result = probe("GET", url, headers=headers, timeout=timeout, retries=1)
|
|
112
|
+
if result.status != 200:
|
|
113
|
+
raise RuntimeError(f"GET {url} returned HTTP {result.status}")
|
|
114
|
+
return result.text
|
webrev/tokens.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Token flows: fetch once, cache, refresh before expiry.
|
|
2
|
+
|
|
3
|
+
Many web APIs gate queries behind a short-lived token (often 5 minutes)
|
|
4
|
+
obtained from a dedicated endpoint and sent as a header. The pattern is
|
|
5
|
+
always the same: request a token, cache it while it has life left, renew it
|
|
6
|
+
when it is about to expire, and retry once with a fresh token on 401.
|
|
7
|
+
``TokenCache`` implements exactly that; the site-specific parts (how to ask
|
|
8
|
+
for a token, which header carries it) are callables you supply.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import time
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class Token:
|
|
19
|
+
value: str
|
|
20
|
+
expires_in: float # seconds of life the issuer reported
|
|
21
|
+
obtained_at: float = field(default=0.0, repr=False) # stamped by TokenCache
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def expires_at(self) -> float:
|
|
25
|
+
return self.obtained_at + self.expires_in
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TokenCache:
|
|
29
|
+
"""Cache for one short-lived token with proactive renewal.
|
|
30
|
+
|
|
31
|
+
``fetcher`` is a zero-argument callable returning a ``Token`` (or a
|
|
32
|
+
``(value, expires_in)`` tuple). The cached token is reused while more
|
|
33
|
+
than ``refresh_margin`` seconds of life remain; otherwise a fresh one is
|
|
34
|
+
fetched. Call ``invalidate()`` after a 401 so the next ``get()`` refetches.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, fetcher, refresh_margin: float = 15.0):
|
|
38
|
+
self._fetcher = fetcher
|
|
39
|
+
self._margin = refresh_margin
|
|
40
|
+
self._token: Token | None = None
|
|
41
|
+
|
|
42
|
+
def get(self, force: bool = False) -> str:
|
|
43
|
+
now = time.time()
|
|
44
|
+
if (
|
|
45
|
+
not force
|
|
46
|
+
and self._token is not None
|
|
47
|
+
and self._token.expires_at - now > self._margin
|
|
48
|
+
):
|
|
49
|
+
return self._token.value
|
|
50
|
+
result = self._fetcher()
|
|
51
|
+
if isinstance(result, Token):
|
|
52
|
+
token = result
|
|
53
|
+
else:
|
|
54
|
+
value, expires_in = result
|
|
55
|
+
token = Token(value=value, expires_in=float(expires_in))
|
|
56
|
+
token.obtained_at = now
|
|
57
|
+
self._token = token
|
|
58
|
+
return token.value
|
|
59
|
+
|
|
60
|
+
def invalidate(self) -> None:
|
|
61
|
+
self._token = None
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: webrev
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Toolkit for reverse-engineering the hidden APIs behind web pages: find endpoints and crypto constants in JS bundles, decrypt payloads, handle token flows, replay requests, and mine HAR captures. Optional pro extras (webrev[pro]) add cookie sessions, CSRF, GraphQL and a real Chromium browser.
|
|
5
|
+
Author: webrev contributors
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: reverse-engineering,api-discovery,har,aes,scraping
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Requires-Dist: cryptography>=42
|
|
15
|
+
Provides-Extra: dev
|
|
16
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
17
|
+
Provides-Extra: pro
|
|
18
|
+
Requires-Dist: playwright>=1.40; extra == "pro"
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# webrev
|
|
22
|
+
|
|
23
|
+
Toolkit for reverse-engineering the hidden APIs behind web pages: find the
|
|
24
|
+
endpoints and crypto constants in a site's JS bundles, decrypt its payloads,
|
|
25
|
+
handle its token flows, replay its requests, and mine DevTools HAR captures.
|
|
26
|
+
|
|
27
|
+
It is a **general-purpose** toolkit. It ships no provider credentials, no
|
|
28
|
+
phone numbers, and no hard-coded endpoints — you point it at a site and it
|
|
29
|
+
helps you discover how that site's own front-end talks to its back-end.
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install webrev
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
For development:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install -e ".[dev]"
|
|
41
|
+
pytest
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Quickstart
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from webrev import scan_js, fetch_text, derive_key_pbkdf2, aes_cbc_decrypt_text
|
|
48
|
+
|
|
49
|
+
# 1. Grab the site's JS bundle and scan it for endpoints and crypto constants.
|
|
50
|
+
js = fetch_text("https://example.com/static/main.js")
|
|
51
|
+
findings = scan_js(js)
|
|
52
|
+
print(findings.summary())
|
|
53
|
+
# urls: 12
|
|
54
|
+
# api paths: 4
|
|
55
|
+
# custom headers: ['x-ord-service', 'X-Query-Token']
|
|
56
|
+
# crypto keywords: ['AES', 'PBKDF2']
|
|
57
|
+
# hex strings (possible keys/IVs): 3
|
|
58
|
+
|
|
59
|
+
# 2. Derive the key the way the bundle does and decrypt a captured payload.
|
|
60
|
+
key = derive_key_pbkdf2(passphrase="...", salt="...", iterations=1000)
|
|
61
|
+
plain = aes_cbc_decrypt_text(ciphertext_b64="...", key=key, iv="...")
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Token flows (fetch once, reuse, refresh before expiry, retry once on 401):
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from webrev import TokenCache, probe
|
|
68
|
+
|
|
69
|
+
def fetch_token():
|
|
70
|
+
r = probe("POST", "https://example.com/api/token", json_body={})
|
|
71
|
+
data = r.json
|
|
72
|
+
return (data["token"], data["expires_in"])
|
|
73
|
+
|
|
74
|
+
cache = TokenCache(fetch_token, refresh_margin=15)
|
|
75
|
+
r = probe("GET", "https://example.com/api/data", token_cache=cache)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
HAR captures (DevTools → Network → Export HAR):
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
from webrev import load_har, list_api_calls
|
|
82
|
+
|
|
83
|
+
entries = load_har("capture.har")
|
|
84
|
+
for e in list_api_calls(entries):
|
|
85
|
+
print(e.method, e.status, e.url)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Modules
|
|
89
|
+
|
|
90
|
+
| Module | What it does |
|
|
91
|
+
| --- | --- |
|
|
92
|
+
| `webrev.crypto` | AES-CBC and AES-GCM encrypt/decrypt, PBKDF2 key derivation, JWT payload decoding |
|
|
93
|
+
| `webrev.js_scan` | Endpoints, custom headers, crypto constants and token flows in JS bundles |
|
|
94
|
+
| `webrev.har` | Parse HAR captures, list/filter the API calls inside |
|
|
95
|
+
| `webrev.tokens` | Expiring-token cache with proactive renewal and 401 invalidation |
|
|
96
|
+
| `webrev.probe` | Replay HTTP requests with retries, structured results, token support |
|
|
97
|
+
|
|
98
|
+
## Pro extras — `webrev[pro]`
|
|
99
|
+
|
|
100
|
+
The core stays light (only `cryptography`). The modern-web tools live in
|
|
101
|
+
`webrev.pro` and are installed separately:
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
pip install "webrev[pro]"
|
|
105
|
+
playwright install chromium
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from webrev.pro import Session, graphql_query, introspect, schema_summary
|
|
110
|
+
from webrev.pro import capture_page, run_js
|
|
111
|
+
|
|
112
|
+
# 1. Cookie session + CSRF: GET the page, POST the form with its token.
|
|
113
|
+
s = Session()
|
|
114
|
+
r = s.submit_form("https://example.com/login", "https://example.com/login",
|
|
115
|
+
{"username": "me", "password": "secret"})
|
|
116
|
+
|
|
117
|
+
# 2. GraphQL: run a query, or introspect the schema to see what exists.
|
|
118
|
+
data = graphql_query("https://example.com/graphql", "{ balance }")
|
|
119
|
+
summary = schema_summary(introspect("https://example.com/graphql"))
|
|
120
|
+
# summary["query_fields"] -> ["user", "balance", ...]
|
|
121
|
+
|
|
122
|
+
# 3. Real Chromium: record the API calls JavaScript fires after render.
|
|
123
|
+
cap = capture_page("https://example.com/app", wait_ms=3000)
|
|
124
|
+
for call in cap.api_calls:
|
|
125
|
+
print(call.method, call.status, call.url)
|
|
126
|
+
|
|
127
|
+
# 4. Read a value JavaScript computes at runtime.
|
|
128
|
+
cfg = run_js("https://example.com/app", "window.__config")
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Honest note: the browser gets you much further — a real Chromium looks
|
|
132
|
+
like a real user, runs the JavaScript, and keeps cookies — but it is not a
|
|
133
|
+
skeleton key. A Turnstile or reCAPTCHA challenge can still stop you, and
|
|
134
|
+
that is a different problem from API discovery.
|
|
135
|
+
|
|
136
|
+
## Notes
|
|
137
|
+
|
|
138
|
+
- Everything here operates on what a site already sends to its own users'
|
|
139
|
+
browsers. Endpoints discovered this way are unofficial and can change or
|
|
140
|
+
break at any time; treat every finding as unverified until you replay it
|
|
141
|
+
live.
|
|
142
|
+
- Only query services and accounts you are authorized to use, and only with
|
|
143
|
+
identifiers that belong to you or that you have permission to use.
|
|
144
|
+
- `webrev` is a toolkit, not a scraper for any specific site: if a provider
|
|
145
|
+
adds a token, a CAPTCHA, or an IP block, that is the provider closing a
|
|
146
|
+
door — work with it, not around it.
|
|
147
|
+
|
|
148
|
+
## License
|
|
149
|
+
|
|
150
|
+
MIT
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
webrev/__init__.py,sha256=pAqF0pyO1W9oDwdwsG_VdQ9HK8YcBUVPow9eKqFb6-o,1608
|
|
2
|
+
webrev/crypto.py,sha256=uclc6Pg8S7odewvyUDqsRcvnJc7En_c0KeRJyw-fi1E,5205
|
|
3
|
+
webrev/har.py,sha256=6pIeadEQon-tJd8GSdshPjZsvDwLdbcZLfCMu7R_O4c,2787
|
|
4
|
+
webrev/js_scan.py,sha256=6UL8WijimrOX-8RXo9i4w0fsirBdOXJu08fMSQhHdps,3408
|
|
5
|
+
webrev/probe.py,sha256=xj0V9PwV33ohgaRhAcSxjmLwAixuNuI0YejmbOrEvp8,3799
|
|
6
|
+
webrev/tokens.py,sha256=aKfnN-gxiGI33lpH6oc9ogZ5cdpTwbnW3-hEXnU4GXk,2062
|
|
7
|
+
webrev/pro/__init__.py,sha256=h5yzzEqLBXSEaLpADuW_CIUZrAFJ8v0CMbvQr4VPkO4,1225
|
|
8
|
+
webrev/pro/browser.py,sha256=Nqkn-PsV4JNdaYQreWtJi6dUqc5SYLXl13YYJCGpaU8,4277
|
|
9
|
+
webrev/pro/graphql.py,sha256=sYOjQNBuTGxfHOkaU7XtDeigvgeL_VWgwRuxKKGg_-I,2624
|
|
10
|
+
webrev/pro/session.py,sha256=6FJl7bFkPTnGJsw2yfmZoGaCartzJw7aHyXyCS6pquQ,6419
|
|
11
|
+
webrev-0.2.0.dist-info/licenses/LICENSE,sha256=oRRZhDtfSLX5wiC6gcrBYvHG0gEooczkkqqo-EdF-pw,1080
|
|
12
|
+
webrev-0.2.0.dist-info/METADATA,sha256=OobW3uIsQQ4pkOqactIb7KFINzu0pxtGtXn5hcEO8YY,5237
|
|
13
|
+
webrev-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
14
|
+
webrev-0.2.0.dist-info/top_level.txt,sha256=Bpapv_o0BgoMJXvRWINitOjtOc6gupxWeitLvfdUmr8,7
|
|
15
|
+
webrev-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Aldo Alfonso Gutiérrez
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
webrev
|