unbrowse 3.0.2 → 3.1.0-experiments.548e04c
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.
- package/dist/cli.js +641 -116
- package/dist/mcp.js +710 -73
- package/package.json +1 -1
- package/runtime-src/api/browse-index.ts +30 -4
- package/runtime-src/api/routes.ts +43 -10
- package/runtime-src/browser/index.ts +2 -2
- package/runtime-src/build-info.generated.ts +5 -5
- package/runtime-src/capture/index.ts +140 -5
- package/runtime-src/cli.ts +190 -2
- package/runtime-src/client/index.ts +43 -15
- package/runtime-src/execution/index.ts +48 -26
- package/runtime-src/execution/token-resolver.ts +135 -0
- package/runtime-src/graph/index.ts +14 -6
- package/runtime-src/impact-log.ts +227 -0
- package/runtime-src/kuri/client.ts +5 -1
- package/runtime-src/marketplace/index.ts +9 -1
- package/runtime-src/mcp.ts +247 -34
- package/runtime-src/orchestrator/browser-agent.ts +2 -2
- package/runtime-src/orchestrator/index.ts +7 -3
- package/runtime-src/payments/lobster-pay.ts +182 -0
- package/runtime-src/reverse-engineer/token-sources.ts +379 -0
- package/runtime-src/types/skill.ts +19 -0
- package/vendor/kuri/darwin-arm64/kuri +0 -0
- package/vendor/kuri/darwin-x64/kuri +0 -0
- package/vendor/kuri/linux-arm64/kuri +0 -0
- package/vendor/kuri/linux-x64/kuri +0 -0
- package/vendor/kuri/manifest.json +6 -6
package/package.json
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { nanoid } from "nanoid";
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
|
-
import {
|
|
3
|
+
import { log } from "../logger.js";
|
|
4
|
+
import { extractEndpoints, extractAuthHeaders } from "../reverse-engineer/index.js";
|
|
5
|
+
import { enrichEndpointsWithTokenSources } from "../reverse-engineer/token-sources.js";
|
|
4
6
|
import { buildSkillOperationGraph, inferEndpointSemantic } from "../graph/index.js";
|
|
5
7
|
import { validateExtractionQuality } from "../execution/index.js";
|
|
6
8
|
import { assessIntentResult } from "../intent-match.js";
|
|
@@ -10,6 +12,8 @@ import type { RawRequest } from "../capture/index.js";
|
|
|
10
12
|
import { cachePublishedSkill, findExistingSkillForDomain } from "../client/index.js";
|
|
11
13
|
import { mergeEndpoints } from "../marketplace/index.js";
|
|
12
14
|
import { upsertDagEdgesFromOperationGraph } from "../orchestrator/dag-feedback.js";
|
|
15
|
+
import { storeCredential } from "../vault/index.js";
|
|
16
|
+
import { getRegistrableDomain } from "../domain.js";
|
|
13
17
|
import {
|
|
14
18
|
buildResolveCacheKey,
|
|
15
19
|
domainSkillCache,
|
|
@@ -151,14 +155,25 @@ export async function cacheBrowseRequests(params: {
|
|
|
151
155
|
sessionDomain: string;
|
|
152
156
|
requests: RawRequest[];
|
|
153
157
|
getPageHtml?: () => Promise<string>;
|
|
158
|
+
jsBundles?: Map<string, string>;
|
|
154
159
|
intent?: string;
|
|
155
160
|
}): Promise<BrowseIndexResult> {
|
|
156
|
-
const { sessionUrl, sessionDomain, requests, getPageHtml } = params;
|
|
161
|
+
const { sessionUrl, sessionDomain, requests, getPageHtml, jsBundles } = params;
|
|
157
162
|
let domain: string;
|
|
158
163
|
try { domain = new URL(sessionUrl).hostname; } catch { domain = sessionDomain; }
|
|
159
164
|
const intent = params.intent ?? `browse ${domain}`;
|
|
160
165
|
|
|
161
166
|
const rawEndpoints = extractEndpoints(requests, undefined, { pageUrl: sessionUrl, finalUrl: sessionUrl });
|
|
167
|
+
|
|
168
|
+
// Extract and persist auth headers (authorization, csrf, bearer tokens)
|
|
169
|
+
// so serverFetch can replay them. Use registrable domain for vault key
|
|
170
|
+
// so ads.x.com and ads-api.x.com share the same session.
|
|
171
|
+
const capturedAuthHeaders = extractAuthHeaders(requests);
|
|
172
|
+
if (Object.keys(capturedAuthHeaders).length > 0) {
|
|
173
|
+
const sessionKey = `${getRegistrableDomain(domain)}-session`;
|
|
174
|
+
await storeCredential(sessionKey, JSON.stringify({ headers: capturedAuthHeaders })).catch(() => {});
|
|
175
|
+
}
|
|
176
|
+
|
|
162
177
|
if (rawEndpoints.length > 0) {
|
|
163
178
|
const existingSkill = findExistingSkillForDomain(domain);
|
|
164
179
|
let allExisting = existingSkill?.endpoints ?? [];
|
|
@@ -182,8 +197,8 @@ export async function cacheBrowseRequests(params: {
|
|
|
182
197
|
if (!existingSkill || mergedEndpoints.length >= existingSkill.endpoints.length) {
|
|
183
198
|
for (const endpoint of mergedEndpoints) {
|
|
184
199
|
if (!endpoint.description) endpoint.description = generateLocalDescription(endpoint);
|
|
200
|
+
if (!endpoint.semantic) endpoint.semantic = inferEndpointSemantic(endpoint);
|
|
185
201
|
}
|
|
186
|
-
|
|
187
202
|
const quickSkill: SkillManifest = {
|
|
188
203
|
skill_id: existingSkill?.skill_id ?? nanoid(),
|
|
189
204
|
version: "1.0.0",
|
|
@@ -202,6 +217,18 @@ export async function cacheBrowseRequests(params: {
|
|
|
202
217
|
intents: Array.from(new Set([...(existingSkill?.intents ?? []), intent])),
|
|
203
218
|
};
|
|
204
219
|
|
|
220
|
+
// Token source discovery: scan live HTML for tokens used in captured
|
|
221
|
+
// request headers and attach AuthTokenBinding entries so serverFetch
|
|
222
|
+
// can rescrape fresh tokens on replay.
|
|
223
|
+
try {
|
|
224
|
+
const html = getPageHtml ? await getPageHtml() : undefined;
|
|
225
|
+
if (html && html.startsWith("<")) {
|
|
226
|
+
const preCheck = requests.filter(r => r.request_headers["authorization"] || r.request_headers["x-csrf-token"]).length;
|
|
227
|
+
const enriched = enrichEndpointsWithTokenSources(quickSkill.endpoints, requests, html, jsBundles);
|
|
228
|
+
log("browse-index", `token enrichment: ${enriched} bindings, ${preCheck} auth-reqs pre-call, ${quickSkill.endpoints.length} eps`);
|
|
229
|
+
}
|
|
230
|
+
} catch (e) { log("browse-index", `token enrichment failed: ${e}`); }
|
|
231
|
+
|
|
205
232
|
const cacheKey = buildResolveCacheKey(domain, intent, sessionUrl);
|
|
206
233
|
const scopedKey = scopedCacheKey("global", cacheKey);
|
|
207
234
|
writeSkillSnapshot(scopedKey, quickSkill);
|
|
@@ -294,7 +321,6 @@ export async function cacheBrowseRequests(params: {
|
|
|
294
321
|
operation_graph: buildSkillOperationGraph(allEndpoints),
|
|
295
322
|
intents: [...new Set([...(existing?.intents ?? []), intent])],
|
|
296
323
|
};
|
|
297
|
-
|
|
298
324
|
const cacheKey = buildResolveCacheKey(domain, intent, sessionUrl);
|
|
299
325
|
const scopedKey = scopedCacheKey("global", cacheKey);
|
|
300
326
|
writeSkillSnapshot(scopedKey, skill);
|
|
@@ -2,15 +2,15 @@ import type { FastifyInstance } from "fastify";
|
|
|
2
2
|
import * as kuri from "../kuri/client.js";
|
|
3
3
|
import type { KuriHarEntry } from "../kuri/client.js";
|
|
4
4
|
import { extractEndpoints, extractAuthHeaders } from "../reverse-engineer/index.js";
|
|
5
|
-
import { INTERCEPTOR_SCRIPT, enrichPassiveCaptureRequests, injectInterceptor } from "../capture/index.js";
|
|
5
|
+
import { INTERCEPTOR_SCRIPT, enrichPassiveCaptureRequests, injectInterceptor, collectInterceptedRequests } from "../capture/index.js";
|
|
6
6
|
import { indexSkillLocally, mergeAgentReview, publishIndexedSkill, queueBackgroundIndex } from "../indexer/index.js";
|
|
7
7
|
import { nanoid } from "nanoid";
|
|
8
8
|
import type { ExecutionTrace, OrchestrationTiming, ProjectionOptions, SkillManifest } from "../types/index.js";
|
|
9
9
|
import { mergeEndpoints } from "../marketplace/index.js";
|
|
10
10
|
import { buildSkillOperationGraph, getEndpointDescriptionMetadata, getSkillChunk, toAgentSkillChunkView } from "../graph/index.js";
|
|
11
|
-
import { augmentEndpointsWithAgent } from "../graph/agent-augment.js";
|
|
12
11
|
import { findExistingSkillForDomain, cachePublishedSkill } from "../client/index.js";
|
|
13
12
|
import { storeCredential } from "../vault/index.js";
|
|
13
|
+
import { getRegistrableDomain } from "../domain.js";
|
|
14
14
|
import { generateLocalDescription, writeSkillSnapshot, buildResolveCacheKey, getDomainReuseKey, domainSkillCache, persistDomainCache, scopedCacheKey, snapshotPathForCacheKey, invalidateRouteCacheForDomain, summarizeSchema, extractSampleValues } from "../orchestrator/index.js";
|
|
15
15
|
import { TRACE_VERSION, CODE_HASH, DEFAULT_BACKEND_URL, GIT_SHA, PACKAGE_VERSION } from "../version.js";
|
|
16
16
|
import { promoteExplicitExecution, resolveAndExecute, type OrchestratorResult } from "../orchestrator/index.js";
|
|
@@ -135,7 +135,7 @@ function passiveIndexFromRequests(
|
|
|
135
135
|
// 2. Extract and store auth credentials (cookies + sensitive headers)
|
|
136
136
|
const capturedAuthHeaders = extractAuthHeaders(requests);
|
|
137
137
|
if (Object.keys(capturedAuthHeaders).length > 0) {
|
|
138
|
-
const authKey = `${domain}-session`;
|
|
138
|
+
const authKey = `${getRegistrableDomain(domain)}-session`;
|
|
139
139
|
await storeCredential(authKey, JSON.stringify({ headers: capturedAuthHeaders }));
|
|
140
140
|
}
|
|
141
141
|
|
|
@@ -1178,11 +1178,9 @@ export async function registerRoutes(app: FastifyInstance) {
|
|
|
1178
1178
|
|
|
1179
1179
|
async function restartBrowseCapture(session: BrowseSession): Promise<void> {
|
|
1180
1180
|
const broker = brokerForSession(session);
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
return;
|
|
1185
|
-
}
|
|
1181
|
+
// Start HAR + interceptor regardless of page load state — the page will load
|
|
1182
|
+
// and HAR records all traffic from the moment it starts.
|
|
1183
|
+
await broker.waitForLoad(session.tabId, 2_000).catch(() => null);
|
|
1186
1184
|
await broker.networkEnable(session.tabId).catch(() => {});
|
|
1187
1185
|
await broker.harStart(session.tabId).catch(() => {});
|
|
1188
1186
|
await broker.scriptInject(session.tabId, INTERCEPTOR_SCRIPT).catch(() => {});
|
|
@@ -1234,11 +1232,23 @@ export async function registerRoutes(app: FastifyInstance) {
|
|
|
1234
1232
|
harEntries,
|
|
1235
1233
|
intent: `browse ${session.domain || profileName(session.url)}`,
|
|
1236
1234
|
});
|
|
1235
|
+
|
|
1236
|
+
// Collect JS bundle bodies for token source scanning
|
|
1237
|
+
const jsBundles = new Map<string, string>();
|
|
1238
|
+
try {
|
|
1239
|
+
const intercepted = await collectInterceptedRequests(session.tabId).catch(() => []);
|
|
1240
|
+
for (const entry of intercepted) {
|
|
1241
|
+
if (entry.is_js && entry.response_body && jsBundles.size < 20) {
|
|
1242
|
+
jsBundles.set(entry.url, entry.response_body);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
} catch { /* best-effort */ }
|
|
1237
1246
|
const syncResult = await cacheBrowseRequests({
|
|
1238
1247
|
sessionUrl: session.url,
|
|
1239
1248
|
sessionDomain: session.domain,
|
|
1240
1249
|
requests: allRequests,
|
|
1241
1250
|
getPageHtml: () => brokerForSession(session).getPageHtml(session.tabId),
|
|
1251
|
+
jsBundles: jsBundles.size > 0 ? jsBundles : undefined,
|
|
1242
1252
|
intent: `browse ${session.domain || profileName(session.url)}`,
|
|
1243
1253
|
});
|
|
1244
1254
|
|
|
@@ -1325,12 +1335,35 @@ export async function registerRoutes(app: FastifyInstance) {
|
|
|
1325
1335
|
|
|
1326
1336
|
let cookiesInjected = 0;
|
|
1327
1337
|
if (newDomain && newDomain !== session.domain) {
|
|
1328
|
-
|
|
1329
|
-
|
|
1338
|
+
// Check if the browser already has fresh session cookies for this domain.
|
|
1339
|
+
// If so, skip vault/profile cookie injection — browser cookies are fresher
|
|
1340
|
+
// and injecting stale vault cookies (e.g. JSESSIONID) causes HTTP 400 on
|
|
1341
|
+
// sites like LinkedIn that validate CSRF alignment.
|
|
1342
|
+
const browserHasFreshSession = await (async () => {
|
|
1343
|
+
try {
|
|
1344
|
+
const { extractBrowserCookies } = await import("../auth/browser-cookies.js");
|
|
1345
|
+
const { cookies } = extractBrowserCookies(newDomain);
|
|
1346
|
+
// Consider the session fresh if we have session-like cookies that aren't expired
|
|
1347
|
+
const now = Date.now() / 1000;
|
|
1348
|
+
return cookies.some((c) =>
|
|
1349
|
+
(c.httpOnly || c.secure) && (!c.expires || c.expires > now),
|
|
1350
|
+
);
|
|
1351
|
+
} catch { return false; }
|
|
1352
|
+
})();
|
|
1353
|
+
|
|
1354
|
+
if (browserHasFreshSession) {
|
|
1355
|
+
// Import browser cookies via CDP (they're fresh from Chrome's jar)
|
|
1356
|
+
cookiesInjected = await importBrowserCookiesIntoTab(session.tabId, newDomain);
|
|
1357
|
+
} else {
|
|
1358
|
+
// No fresh browser cookies — load from vault/auth profile
|
|
1359
|
+
cookiesInjected = await importBrowserCookiesIntoTab(session.tabId, newDomain);
|
|
1360
|
+
await loadAuthProfileBestEffort(session.tabId, newDomain, "browse_go");
|
|
1361
|
+
}
|
|
1330
1362
|
}
|
|
1331
1363
|
|
|
1332
1364
|
await restartBrowseCapture(session);
|
|
1333
1365
|
|
|
1366
|
+
await broker.navigate(session.tabId, url);
|
|
1334
1367
|
await broker.navigate(session.tabId, url);
|
|
1335
1368
|
const finalUrl = await broker.getCurrentUrl(session.tabId).catch(() => url);
|
|
1336
1369
|
session.url = typeof finalUrl === "string" && finalUrl.startsWith("http") ? finalUrl : url;
|
|
@@ -7,9 +7,9 @@ import type { RawRequest } from "../capture/index.js";
|
|
|
7
7
|
import { queueBackgroundIndex } from "../indexer/index.js";
|
|
8
8
|
import { mergeEndpoints } from "../marketplace/index.js";
|
|
9
9
|
import { buildSkillOperationGraph } from "../graph/index.js";
|
|
10
|
-
import { augmentEndpointsWithAgent } from "../graph/agent-augment.js";
|
|
11
10
|
import { findExistingSkillForDomain, cachePublishedSkill } from "../client/index.js";
|
|
12
11
|
import { storeCredential } from "../vault/index.js";
|
|
12
|
+
import { getRegistrableDomain } from "../domain.js";
|
|
13
13
|
import {
|
|
14
14
|
importBrowserCookiesIntoTab,
|
|
15
15
|
loadAuthProfileBestEffort,
|
|
@@ -83,7 +83,7 @@ function passiveIndexHar(entries: KuriHarEntry[], pageUrl: string): void {
|
|
|
83
83
|
// Store auth credentials
|
|
84
84
|
const capturedAuthHeaders = extractAuthHeaders(requests);
|
|
85
85
|
if (Object.keys(capturedAuthHeaders).length > 0) {
|
|
86
|
-
await storeCredential(`${domain}-session`, JSON.stringify({ headers: capturedAuthHeaders }));
|
|
86
|
+
await storeCredential(`${getRegistrableDomain(domain)}-session`, JSON.stringify({ headers: capturedAuthHeaders }));
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
// Merge with existing skill (never reduce endpoint count)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export const BUILD_RELEASE_VERSION = "3.0.
|
|
2
|
-
export const BUILD_GIT_SHA = "
|
|
1
|
+
export const BUILD_RELEASE_VERSION = "3.1.0-experiments.548e04c";
|
|
2
|
+
export const BUILD_GIT_SHA = "548e04c0d988";
|
|
3
3
|
export const BUILD_CODE_HASH = "1488fc1d92b7";
|
|
4
|
-
export const BUILD_RELEASE_MANIFEST_BASE64 = "
|
|
5
|
-
export const BUILD_RELEASE_MANIFEST_SIGNATURE = "
|
|
6
|
-
export const BUILD_DEFAULT_BACKEND_URL = "https://
|
|
4
|
+
export const BUILD_RELEASE_MANIFEST_BASE64 = "eyJzY2hlbWFfdmVyc2lvbiI6MSwicmVsZWFzZV92ZXJzaW9uIjoiMy4xLjAtZXhwZXJpbWVudHMuNTQ4ZTA0YyIsImdpdF9zaGEiOiI1NDhlMDRjMGQ5ODgiLCJjb2RlX2hhc2giOiIxNDg4ZmMxZDkyYjciLCJ0cmFjZV92ZXJzaW9uIjoiMTQ4OGZjMWQ5MmI3QDU0OGUwNGMwZDk4OCIsImlzc3VlZF9hdCI6IjIwMjYtMDQtMDZUMDA6MTM6MzQuNTMxWiJ9";
|
|
5
|
+
export const BUILD_RELEASE_MANIFEST_SIGNATURE = "4WHKeltVN_91YrjkahaNoChnZaws3sxgOhxEJmX8zQU";
|
|
6
|
+
export const BUILD_DEFAULT_BACKEND_URL = "https://unbrowse-backend-experiments.lewis-6d8.workers.dev";
|
|
@@ -30,6 +30,114 @@ const activeTabRegistry = new Set<string>();
|
|
|
30
30
|
// Tracks tabs where scriptInject has been registered (persistent across navigations)
|
|
31
31
|
const interceptorInjectedTabs = new Set<string>();
|
|
32
32
|
|
|
33
|
+
// Tracks tabs where CDP-level document-start injection has been registered
|
|
34
|
+
const cdpDocStartTabs = new Set<string>();
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Register a script via Chrome's Page.addScriptToEvaluateOnNewDocument CDP method directly.
|
|
38
|
+
* This runs BEFORE any page JS on every navigation — critical for catching early fetch() calls.
|
|
39
|
+
* Falls back silently if CDP is unavailable.
|
|
40
|
+
*/
|
|
41
|
+
export async function registerDocumentStartScript(tabId: string, source: string): Promise<boolean> {
|
|
42
|
+
if (cdpDocStartTabs.has(tabId)) return true;
|
|
43
|
+
const cdpPort = kuri.getCdpPort();
|
|
44
|
+
if (!cdpPort) return false;
|
|
45
|
+
|
|
46
|
+
try {
|
|
47
|
+
// Get the WebSocket URL for this tab
|
|
48
|
+
const resp = await fetch(`http://127.0.0.1:${cdpPort}/json`);
|
|
49
|
+
const targets = await resp.json() as Array<{ id: string; webSocketDebuggerUrl?: string }>;
|
|
50
|
+
const target = targets.find((t) => t.id === tabId);
|
|
51
|
+
if (!target?.webSocketDebuggerUrl) return false;
|
|
52
|
+
|
|
53
|
+
// Connect via WebSocket and send CDP command
|
|
54
|
+
const ws = new WebSocket(target.webSocketDebuggerUrl);
|
|
55
|
+
const result = await new Promise<boolean>((resolve) => {
|
|
56
|
+
const timeout = setTimeout(() => { ws.close(); resolve(false); }, 3000);
|
|
57
|
+
ws.onopen = () => {
|
|
58
|
+
ws.send(JSON.stringify({
|
|
59
|
+
id: 1,
|
|
60
|
+
method: "Page.addScriptToEvaluateOnNewDocument",
|
|
61
|
+
params: { source },
|
|
62
|
+
}));
|
|
63
|
+
};
|
|
64
|
+
ws.onmessage = (event) => {
|
|
65
|
+
try {
|
|
66
|
+
const msg = JSON.parse(String(event.data));
|
|
67
|
+
if (msg.id === 1) {
|
|
68
|
+
clearTimeout(timeout);
|
|
69
|
+
ws.close();
|
|
70
|
+
resolve(!msg.error);
|
|
71
|
+
}
|
|
72
|
+
} catch { /* ignore parse errors */ }
|
|
73
|
+
};
|
|
74
|
+
ws.onerror = () => { clearTimeout(timeout); ws.close(); resolve(false); };
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
if (result) {
|
|
78
|
+
cdpDocStartTabs.add(tabId);
|
|
79
|
+
log("capture", `document-start interceptor registered via direct CDP for tab ${tabId}`);
|
|
80
|
+
}
|
|
81
|
+
return result;
|
|
82
|
+
} catch {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Tracks captured request headers from CDP Network events
|
|
88
|
+
const cdpCapturedHeaders = new Map<string, Map<string, Record<string, string>>>();
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Enable CDP Network.requestWillBeSent listener to capture full request headers
|
|
92
|
+
* including auth headers that HAR/interceptor miss. Stores headers indexed by URL.
|
|
93
|
+
*/
|
|
94
|
+
export async function enableNetworkHeaderCapture(tabId: string): Promise<void> {
|
|
95
|
+
const cdpPort = kuri.getCdpPort();
|
|
96
|
+
if (!cdpPort) return;
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
const resp = await fetch(`http://127.0.0.1:${cdpPort}/json`);
|
|
100
|
+
const targets = await resp.json() as Array<{ id: string; webSocketDebuggerUrl?: string }>;
|
|
101
|
+
const target = targets.find((t) => t.id === tabId);
|
|
102
|
+
if (!target?.webSocketDebuggerUrl) return;
|
|
103
|
+
|
|
104
|
+
const headers = new Map<string, Record<string, string>>();
|
|
105
|
+
cdpCapturedHeaders.set(tabId, headers);
|
|
106
|
+
|
|
107
|
+
const ws = new WebSocket(target.webSocketDebuggerUrl);
|
|
108
|
+
ws.onopen = () => {
|
|
109
|
+
// Enable network domain (may already be enabled, that's OK)
|
|
110
|
+
ws.send(JSON.stringify({ id: 1, method: "Network.enable", params: {} }));
|
|
111
|
+
};
|
|
112
|
+
ws.onmessage = (event) => {
|
|
113
|
+
try {
|
|
114
|
+
const msg = JSON.parse(String(event.data));
|
|
115
|
+
if (msg.method === "Network.requestWillBeSent") {
|
|
116
|
+
const req = msg.params?.request;
|
|
117
|
+
if (req?.url && req?.headers) {
|
|
118
|
+
// Only capture headers for API-like URLs
|
|
119
|
+
if (/\/(api|graphql|v\d+)\b/i.test(req.url) || /ads-api|voyager/i.test(req.url)) {
|
|
120
|
+
headers.set(req.url, req.headers);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
} catch { /* ignore */ }
|
|
125
|
+
};
|
|
126
|
+
// Keep ws alive — it will be cleaned up when tab closes
|
|
127
|
+
ws.onerror = () => { cdpCapturedHeaders.delete(tabId); };
|
|
128
|
+
|
|
129
|
+
log("capture", `CDP network header capture enabled for tab ${tabId}`);
|
|
130
|
+
} catch { /* best-effort */ }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Get captured request headers for a tab. Returns a map of URL → headers.
|
|
135
|
+
* These come from CDP Network.requestWillBeSent which includes auth headers
|
|
136
|
+
* that HAR and the JS interceptor miss.
|
|
137
|
+
*/
|
|
138
|
+
export function getCapturedNetworkHeaders(tabId: string): Map<string, Record<string, string>> {
|
|
139
|
+
return cdpCapturedHeaders.get(tabId) ?? new Map();
|
|
140
|
+
}
|
|
33
141
|
// Hard timeout per capture: 90s prevents stuck tabs from holding slots forever
|
|
34
142
|
const CAPTURE_TIMEOUT_MS = 90_000;
|
|
35
143
|
const CAPTURE_NAV_TIMEOUT_MS = 20_000;
|
|
@@ -376,6 +484,11 @@ export const INTERCEPTOR_SCRIPT = `(function() {
|
|
|
376
484
|
var method = (opts.method || 'GET').toUpperCase();
|
|
377
485
|
var reqBody = opts.body ? String(opts.body).substring(0, MAX_BODY) : undefined;
|
|
378
486
|
var reqHeaders = {};
|
|
487
|
+
// Extract headers from Request object (first arg)
|
|
488
|
+
if (args[0] && typeof args[0] === 'object' && args[0].headers && typeof args[0].headers.forEach === 'function') {
|
|
489
|
+
args[0].headers.forEach(function(v, k) { reqHeaders[k] = v; });
|
|
490
|
+
}
|
|
491
|
+
// Override/merge with explicit opts.headers (second arg)
|
|
379
492
|
if (opts.headers) {
|
|
380
493
|
if (typeof opts.headers.forEach === 'function') {
|
|
381
494
|
opts.headers.forEach(function(v, k) { reqHeaders[k] = v; });
|
|
@@ -557,13 +670,21 @@ export function mergePassiveCaptureData(
|
|
|
557
670
|
});
|
|
558
671
|
}
|
|
559
672
|
|
|
560
|
-
// Priority 3: Extension entries (
|
|
673
|
+
// Priority 3: Extension entries (chrome.webRequest — has full auth headers HAR strips)
|
|
561
674
|
for (const entry of extensionEntries) {
|
|
562
|
-
if (seen.has(entry.url)) continue;
|
|
563
675
|
const reqHeaders: Record<string, string> = {};
|
|
564
676
|
for (const h of entry.requestHeaders ?? []) reqHeaders[h.name] = h.value;
|
|
565
677
|
const respHeaders: Record<string, string> = {};
|
|
566
678
|
for (const h of entry.responseHeaders ?? []) respHeaders[h.name] = h.value;
|
|
679
|
+
|
|
680
|
+
const existing = seen.get(entry.url);
|
|
681
|
+
if (existing) {
|
|
682
|
+
// Merge auth headers from extension into existing entry (HAR strips them)
|
|
683
|
+
for (const [k, v] of Object.entries(reqHeaders)) {
|
|
684
|
+
if (!existing.request_headers[k]) existing.request_headers[k] = v;
|
|
685
|
+
}
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
567
688
|
seen.set(entry.url, {
|
|
568
689
|
url: entry.url,
|
|
569
690
|
method: entry.method,
|
|
@@ -823,22 +944,36 @@ export async function enrichPassiveCaptureRequests(params: {
|
|
|
823
944
|
...request,
|
|
824
945
|
url: normalizeCapturedUrl(request.url, captureUrl),
|
|
825
946
|
}));
|
|
947
|
+
|
|
948
|
+
// HAR strips auth headers. Infer their presence from cookies so
|
|
949
|
+
// enrichEndpointsWithTokenSources can create DAG bindings.
|
|
950
|
+
if (extensionEntries.length === 0) {
|
|
951
|
+
const tabCookies = await kuri.getCookies(tabId).catch(() => []) as Array<{ name: string; value: string }>;
|
|
952
|
+
const hasAuthCookie = tabCookies.some((c) => /^(ct0|csrf_token|_csrf|csrftoken|XSRF-TOKEN|auth_token)$/i.test(c.name));
|
|
953
|
+
if (hasAuthCookie) {
|
|
954
|
+
for (const req of requests) {
|
|
955
|
+
if (/\/(api|graphql|v\d+)\b/i.test(req.url) || /ads-api|voyager/i.test(req.url)) {
|
|
956
|
+
if (!req.request_headers["authorization"]) req.request_headers["authorization"] = "[REDACTED]";
|
|
957
|
+
if (!req.request_headers["x-csrf-token"]) req.request_headers["x-csrf-token"] = "[REDACTED]";
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
|
|
826
963
|
log("capture", `browse-checkpoint tracked ${harEntries.length} HAR, ${intercepted.length} intercepted, ${extensionEntries.length} extension, ${responseBodies.size} bodies → ${requests.length} merged`);
|
|
827
964
|
return requests;
|
|
828
965
|
}
|
|
829
|
-
|
|
830
966
|
/**
|
|
831
967
|
* Collect network requests observed by kuri's builtin extension (chrome.webRequest).
|
|
832
968
|
* Gracefully returns [] if the extension relay is not yet wired.
|
|
833
969
|
*/
|
|
834
970
|
async function collectExtensionRequests(tabId: string): Promise<ExtensionEntry[]> {
|
|
835
971
|
try {
|
|
836
|
-
// Query the builtin extension's network log via the agent bridge
|
|
837
972
|
const raw = await kuri.evaluate(tabId, `
|
|
838
973
|
(function() {
|
|
839
974
|
if (!window.__kuri || !window.__kuri._networkLog) return '[]';
|
|
840
975
|
var log = window.__kuri._networkLog;
|
|
841
|
-
window.__kuri._networkLog = [];
|
|
976
|
+
window.__kuri._networkLog = [];
|
|
842
977
|
return JSON.stringify(log);
|
|
843
978
|
})()
|
|
844
979
|
`);
|