webrev 0.2.0__tar.gz

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-0.2.0/LICENSE ADDED
@@ -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.
webrev-0.2.0/PKG-INFO ADDED
@@ -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
webrev-0.2.0/README.md ADDED
@@ -0,0 +1,130 @@
1
+ # webrev
2
+
3
+ Toolkit for reverse-engineering the hidden APIs behind web pages: find the
4
+ endpoints and crypto constants in a site's JS bundles, decrypt its payloads,
5
+ handle its token flows, replay its requests, and mine DevTools HAR captures.
6
+
7
+ It is a **general-purpose** toolkit. It ships no provider credentials, no
8
+ phone numbers, and no hard-coded endpoints — you point it at a site and it
9
+ helps you discover how that site's own front-end talks to its back-end.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install webrev
15
+ ```
16
+
17
+ For development:
18
+
19
+ ```bash
20
+ pip install -e ".[dev]"
21
+ pytest
22
+ ```
23
+
24
+ ## Quickstart
25
+
26
+ ```python
27
+ from webrev import scan_js, fetch_text, derive_key_pbkdf2, aes_cbc_decrypt_text
28
+
29
+ # 1. Grab the site's JS bundle and scan it for endpoints and crypto constants.
30
+ js = fetch_text("https://example.com/static/main.js")
31
+ findings = scan_js(js)
32
+ print(findings.summary())
33
+ # urls: 12
34
+ # api paths: 4
35
+ # custom headers: ['x-ord-service', 'X-Query-Token']
36
+ # crypto keywords: ['AES', 'PBKDF2']
37
+ # hex strings (possible keys/IVs): 3
38
+
39
+ # 2. Derive the key the way the bundle does and decrypt a captured payload.
40
+ key = derive_key_pbkdf2(passphrase="...", salt="...", iterations=1000)
41
+ plain = aes_cbc_decrypt_text(ciphertext_b64="...", key=key, iv="...")
42
+ ```
43
+
44
+ Token flows (fetch once, reuse, refresh before expiry, retry once on 401):
45
+
46
+ ```python
47
+ from webrev import TokenCache, probe
48
+
49
+ def fetch_token():
50
+ r = probe("POST", "https://example.com/api/token", json_body={})
51
+ data = r.json
52
+ return (data["token"], data["expires_in"])
53
+
54
+ cache = TokenCache(fetch_token, refresh_margin=15)
55
+ r = probe("GET", "https://example.com/api/data", token_cache=cache)
56
+ ```
57
+
58
+ HAR captures (DevTools → Network → Export HAR):
59
+
60
+ ```python
61
+ from webrev import load_har, list_api_calls
62
+
63
+ entries = load_har("capture.har")
64
+ for e in list_api_calls(entries):
65
+ print(e.method, e.status, e.url)
66
+ ```
67
+
68
+ ## Modules
69
+
70
+ | Module | What it does |
71
+ | --- | --- |
72
+ | `webrev.crypto` | AES-CBC and AES-GCM encrypt/decrypt, PBKDF2 key derivation, JWT payload decoding |
73
+ | `webrev.js_scan` | Endpoints, custom headers, crypto constants and token flows in JS bundles |
74
+ | `webrev.har` | Parse HAR captures, list/filter the API calls inside |
75
+ | `webrev.tokens` | Expiring-token cache with proactive renewal and 401 invalidation |
76
+ | `webrev.probe` | Replay HTTP requests with retries, structured results, token support |
77
+
78
+ ## Pro extras — `webrev[pro]`
79
+
80
+ The core stays light (only `cryptography`). The modern-web tools live in
81
+ `webrev.pro` and are installed separately:
82
+
83
+ ```bash
84
+ pip install "webrev[pro]"
85
+ playwright install chromium
86
+ ```
87
+
88
+ ```python
89
+ from webrev.pro import Session, graphql_query, introspect, schema_summary
90
+ from webrev.pro import capture_page, run_js
91
+
92
+ # 1. Cookie session + CSRF: GET the page, POST the form with its token.
93
+ s = Session()
94
+ r = s.submit_form("https://example.com/login", "https://example.com/login",
95
+ {"username": "me", "password": "secret"})
96
+
97
+ # 2. GraphQL: run a query, or introspect the schema to see what exists.
98
+ data = graphql_query("https://example.com/graphql", "{ balance }")
99
+ summary = schema_summary(introspect("https://example.com/graphql"))
100
+ # summary["query_fields"] -> ["user", "balance", ...]
101
+
102
+ # 3. Real Chromium: record the API calls JavaScript fires after render.
103
+ cap = capture_page("https://example.com/app", wait_ms=3000)
104
+ for call in cap.api_calls:
105
+ print(call.method, call.status, call.url)
106
+
107
+ # 4. Read a value JavaScript computes at runtime.
108
+ cfg = run_js("https://example.com/app", "window.__config")
109
+ ```
110
+
111
+ Honest note: the browser gets you much further — a real Chromium looks
112
+ like a real user, runs the JavaScript, and keeps cookies — but it is not a
113
+ skeleton key. A Turnstile or reCAPTCHA challenge can still stop you, and
114
+ that is a different problem from API discovery.
115
+
116
+ ## Notes
117
+
118
+ - Everything here operates on what a site already sends to its own users'
119
+ browsers. Endpoints discovered this way are unofficial and can change or
120
+ break at any time; treat every finding as unverified until you replay it
121
+ live.
122
+ - Only query services and accounts you are authorized to use, and only with
123
+ identifiers that belong to you or that you have permission to use.
124
+ - `webrev` is a toolkit, not a scraper for any specific site: if a provider
125
+ adds a token, a CAPTCHA, or an IP block, that is the provider closing a
126
+ door — work with it, not around it.
127
+
128
+ ## License
129
+
130
+ MIT
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "webrev"
7
+ version = "0.2.0"
8
+ description = "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."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "webrev contributors" }]
13
+ keywords = ["reverse-engineering", "api-discovery", "har", "aes", "scraping"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Topic :: Internet :: WWW/HTTP",
18
+ ]
19
+ dependencies = [
20
+ "cryptography>=42",
21
+ ]
22
+
23
+ [project.optional-dependencies]
24
+ dev = ["pytest>=8"]
25
+ pro = ["playwright>=1.40"]
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
29
+
30
+ [tool.pytest.ini_options]
31
+ testpaths = ["tests"]
webrev-0.2.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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
+ ]
@@ -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"))
@@ -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