dsh-agent-team-ui-testing 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +327 -2
- package/annotation-capture.js +111 -0
- package/banner.png +0 -0
- package/banner_zh.png +0 -0
- package/browser-safety.js +293 -0
- package/capture-p0.js +910 -0
- package/client.js +11302 -0
- package/context-menu.js +134 -0
- package/cordis.patch.yml +3 -0
- package/core/clock.js +88 -0
- package/core/config-store.js +566 -0
- package/core/config.js +892 -0
- package/core/contracts.js +240 -0
- package/core/errors.js +156 -0
- package/core/evidence.js +141 -0
- package/core/geometry.js +217 -0
- package/core/identity.js +180 -0
- package/core/index.js +24 -0
- package/core/p0.js +1101 -0
- package/core/readiness.js +175 -0
- package/core/registry.js +239 -0
- package/core/tab-access.js +1350 -0
- package/docs/adapters.md +160 -0
- package/docs/architecture.md +146 -0
- package/docs/capability-tiers.md +80 -0
- package/docs/capture-p0.md +90 -0
- package/docs/diagnose-reason-codes.md +157 -0
- package/docs/element-picker.md +143 -0
- package/docs/getting-started.md +136 -0
- package/docs/index.md +36 -0
- package/docs/multi-tab.md +162 -0
- package/docs/network-p0.md +117 -0
- package/docs/panel-context-menu.md +41 -0
- package/docs/t2-structured-gui.md +68 -0
- package/docs/t3-vision.md +84 -0
- package/docs/t4-dynamic-behavior.md +135 -0
- package/docs/tools.md +174 -0
- package/docs/verification.md +131 -0
- package/docs/viewport-control.md +94 -0
- package/dynamic-t4.js +5699 -0
- package/frame-push.js +508 -0
- package/frame-source.js +162 -0
- package/icon.png +0 -0
- package/index.js +23028 -0
- package/integration/cross-environment.js +1535 -0
- package/integration/diagnose.js +945 -0
- package/integration/tab-principal.js +493 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/network-p0.js +4264 -0
- package/package.json +19 -4
- package/select-control.js +298 -0
- package/skills/ui-testing-common/SKILL.md +54 -0
- package/skills/ui-testing-fake/SKILL.md +43 -0
- package/skills/ui-testing-web/SKILL.md +520 -0
- package/skills/ui-testing-web/manifests/declared-capabilities.json +903 -0
- package/skills/ui-testing-web/references/contracts/capability.md +68 -0
- package/skills/ui-testing-web/references/contracts/evidence.md +41 -0
- package/skills/ui-testing-web/references/contracts/operation.md +44 -0
- package/skills/ui-testing-web/references/core/dynamic-visual.md +123 -0
- package/skills/ui-testing-web/references/core/fallback.md +83 -0
- package/skills/ui-testing-web/references/core/network-and-state.md +114 -0
- package/skills/ui-testing-web/references/core/page-identity.md +91 -0
- package/skills/ui-testing-web/references/core/report-template.md +144 -0
- package/skills/ui-testing-web/references/core/reporting.md +92 -0
- package/skills/ui-testing-web/references/core/safety.md +12 -0
- package/skills/ui-testing-web/references/core/selection.md +26 -0
- package/skills/ui-testing-web/references/core/tool-routing-and-limits.md +198 -0
- package/skills/ui-testing-web/references/core/verdict-examples.md +96 -0
- package/skills/ui-testing-web/references/core/verdict-gate.md +105 -0
- package/skills/ui-testing-web/references/core/verification.md +19 -0
- package/skills/ui-testing-web/references/core/workflow.md +16 -0
- package/skills/ui-testing-web/references/platforms/index.md +19 -0
- package/skills/ui-testing-web/references/platforms/web.md +17 -0
- package/skills/ui-testing-web/references/scenarios/annotations.md +104 -0
- package/skills/ui-testing-web/references/scenarios/functional.md +205 -0
- package/skills/ui-testing-web/references/scenarios/visual-motion.md +170 -0
- package/skills/ui-testing-web/references/tiers/t1-programmatic.md +25 -0
- package/skills/ui-testing-web/references/tiers/t2-structured.md +61 -0
- package/skills/ui-testing-web/references/tiers/t3-static-visual.md +45 -0
- package/skills/ui-testing-web/references/tiers/t4-dynamic-visual.md +58 -0
- package/skills/ui-testing-web/templates/capability-note.md +23 -0
- package/skills/ui-testing-web/templates/platform.md +30 -0
- package/skills/ui-testing-web/templates/regression-case.md +15 -0
- package/skills/ui-testing-web/templates/scenario.md +13 -0
- package/targets/fake/adapter.js +1163 -0
- package/targets/fake/fixtures.js +177 -0
- package/targets/web/adapter.js +1231 -0
- package/targets/web/provider.js +415 -0
- package/vision-baseline.js +1254 -0
- package/vision-t3.js +2657 -0
package/network-p0.js
ADDED
|
@@ -0,0 +1,4264 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* network-p0.js — WEB-P0 网络采集/分析/控制/证据的纯 JS 核心(零 npm 依赖)。
|
|
3
|
+
*
|
|
4
|
+
* 权威契约:docs/network-p0.md(§2 工具面 §3 采集 §4 事件模型与配额 §5 分析 §6 业务链路
|
|
5
|
+
* §7 控制 §8 证据/安全/隔离 §13 R1 review 裁决)。契约优先于本文任何注释。
|
|
6
|
+
*
|
|
7
|
+
* 设计约束(与 vision-t3.js 同级):
|
|
8
|
+
* - 只依赖 node 内置模块与既有 browser-safety.js(BrowserError/redactUrl/redactText)、
|
|
9
|
+
* capture-p0.js(publishCapture 的原子 no-clobber 提交点语义)。不启动浏览器、不 import CDP。
|
|
10
|
+
* - 失败一律抛 BrowserError(NET_*,§2.9 + §13 R1-5),不落 INTERNAL。
|
|
11
|
+
* - 纯函数(normalizeEvent / queryEvents / aggregateEvents / toJsonl / toHar / matchRule …)可
|
|
12
|
+
* 独立单测;NetworkStore 每个 Runtime(= 每个工作区 scope)一个实例,状态不跨 scope 共享。
|
|
13
|
+
* - 不伪造:body 读不到 → `available:false`;丢失/淘汰/截断全计数;时间相邻只能标
|
|
14
|
+
* `basis:"temporal"`,不得冒充因果。
|
|
15
|
+
*
|
|
16
|
+
* 实现固定约定(契约未逐字规定、此处固定并公开):
|
|
17
|
+
* - 内部请求键 = `(targetId, cdpSessionId, rawRequestId, hop)`(R1-10);`hop` 从 0 递增,
|
|
18
|
+
* 重定向每一跳 +1。对外 `requestId` 是 raw id,`hopId` 在事件里公开、detail 回 `hops[]`。
|
|
19
|
+
* - `ts.wallMs` 由采集器用**该 target 首次 `requestWillBeSent.wallTime` 锚点**推算(R1-11);
|
|
20
|
+
* store 提供 `wallMsFor(targetId, cdpSeconds)`,缺锚点才回退 `Date.now()`。
|
|
21
|
+
* - `maxTotalBytes` 的近似字节口径固定为
|
|
22
|
+
* `sum(JSON-UTF8(event)) + sum(JSON-UTF8(headers)) + sum(raw body bytes) + pin 预算 + 候选缓冲`
|
|
23
|
+
* (`estimateBytes()` 公开,R1-15);超限先淘汰 body(`bodyEvicted`),仍超限再淘汰最旧事件
|
|
24
|
+
* (`evicted`)。
|
|
25
|
+
* - `gaps` 同时包含淘汰与「因配额拒收」的 seq 洞(R1-15)。
|
|
26
|
+
* - 关联标识:每会话随机 HMAC 密钥,公开 `valueHash`(HMAC-SHA256 前 12 hex),内部
|
|
27
|
+
* `contentHash`(完整 hex,只用于同链路判等),原值不落库(R1-9)。`session.stop()` 清密钥。
|
|
28
|
+
* - URL 判等(重试/重复/轮询键)用**未脱敏 URL** 的 `urlHash`,不得用脱敏串(R1-9)。
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import { createHash, createHmac, randomBytes } from 'node:crypto';
|
|
32
|
+
import { mkdirSync, realpathSync, statSync } from 'node:fs';
|
|
33
|
+
import { isAbsolute, relative as relativePath, resolve as resolvePath, sep, dirname } from 'node:path';
|
|
34
|
+
|
|
35
|
+
import { BrowserError, redactText, redactUrl } from './browser-safety.js';
|
|
36
|
+
import { publishCapture } from './capture-p0.js';
|
|
37
|
+
|
|
38
|
+
/* ------------------------------------------------------------------ */
|
|
39
|
+
/* 常量 */
|
|
40
|
+
/* ------------------------------------------------------------------ */
|
|
41
|
+
|
|
42
|
+
export const NET_VERSION = 1;
|
|
43
|
+
export const NET_PROTOCOL_VERSION = 1;
|
|
44
|
+
|
|
45
|
+
export const NET_DEFAULTS = Object.freeze({
|
|
46
|
+
captureBodies: true,
|
|
47
|
+
captureWebSocket: true,
|
|
48
|
+
captureSse: true,
|
|
49
|
+
captureWorkers: true,
|
|
50
|
+
maxEvents: 5000,
|
|
51
|
+
maxBodyBytes: 262144,
|
|
52
|
+
maxTotalBytes: 8 * 1024 * 1024,
|
|
53
|
+
maxWsFrames: 2000,
|
|
54
|
+
businessStatusPath: null,
|
|
55
|
+
maskRules: Object.freeze([]),
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
export const NET_LIMITS = Object.freeze({
|
|
59
|
+
maxEvents: 20000,
|
|
60
|
+
maxBodyBytes: 1024 * 1024,
|
|
61
|
+
maxTotalBytes: 32 * 1024 * 1024,
|
|
62
|
+
maxWsFrames: 20000,
|
|
63
|
+
preSessionEvents: 200,
|
|
64
|
+
sessionsRetained: 4,
|
|
65
|
+
eventPageLimit: 200,
|
|
66
|
+
eventPageDefault: 50,
|
|
67
|
+
groupsLimit: 100,
|
|
68
|
+
detailBodyBytes: 1024 * 1024,
|
|
69
|
+
detailBodyMinBytes: 1024,
|
|
70
|
+
detailEvents: 50,
|
|
71
|
+
dependencyEdges: 50,
|
|
72
|
+
urlBytes: 2048,
|
|
73
|
+
headerCount: 64,
|
|
74
|
+
headerValueBytes: 1024,
|
|
75
|
+
errorTextBytes: 512,
|
|
76
|
+
searchTextBytes: 256,
|
|
77
|
+
wsPayloadBytes: 65536,
|
|
78
|
+
sseDataBytes: 65536,
|
|
79
|
+
initiatorStack: 10,
|
|
80
|
+
redirectChain: 20,
|
|
81
|
+
correlationRules: 32,
|
|
82
|
+
rules: 32,
|
|
83
|
+
held: 64,
|
|
84
|
+
holdTimeoutMs: 30000,
|
|
85
|
+
ruleBodyBytes: 65536,
|
|
86
|
+
replayCount: 10,
|
|
87
|
+
steps: 200,
|
|
88
|
+
stepLabels: 16,
|
|
89
|
+
objectRules: 16,
|
|
90
|
+
objectEvents: 50,
|
|
91
|
+
subscriptionMax: 16,
|
|
92
|
+
subscriptionPin: 1000,
|
|
93
|
+
subscriptionLimit: 200,
|
|
94
|
+
importDataBytes: 8 * 1024 * 1024,
|
|
95
|
+
importFileBytes: 64 * 1024 * 1024,
|
|
96
|
+
retryWindowMs: 10000,
|
|
97
|
+
pollWindowMs: 5000,
|
|
98
|
+
pollIntervalTolerance: 0.3,
|
|
99
|
+
networkWindowMs: 250,
|
|
100
|
+
networkWindowTailMs: 50,
|
|
101
|
+
networkWindowMax: 50,
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
export const NET_SESSION_ACTIONS = Object.freeze(['start', 'stop', 'status', 'reset']);
|
|
105
|
+
export const NET_SESSION_STATES = Object.freeze(['running', 'stopped', 'snapshot']);
|
|
106
|
+
export const NET_VIEWS = Object.freeze(['summary', 'full', 'timeline', 'aggregate']);
|
|
107
|
+
export const NET_KINDS = Object.freeze(['http', 'ws', 'sse', 'marker']);
|
|
108
|
+
export const NET_PHASES = Object.freeze([
|
|
109
|
+
'request', 'redirect', 'response', 'data', 'finished', 'failed', 'extra-info',
|
|
110
|
+
'ws-created', 'ws-handshake', 'ws-send', 'ws-receive', 'ws-error', 'ws-closed',
|
|
111
|
+
'sse-message', 'mark', 'step-begin', 'step-end', 'evidence-link', 'control', 'session-meta',
|
|
112
|
+
]);
|
|
113
|
+
export const NET_BODY_STATES = Object.freeze(['captured', 'empty', 'unavailable']);
|
|
114
|
+
export const NET_DETAIL_PARTS = Object.freeze([
|
|
115
|
+
'request', 'response', 'headers', 'body', 'timing', 'redirects', 'initiator', 'ws', 'sse',
|
|
116
|
+
'correlation', 'dependencies', 'business', 'events', 'failure',
|
|
117
|
+
]);
|
|
118
|
+
export const NET_TRAIL_ACTIONS = Object.freeze(['begin-step', 'end-step', 'mark', 'link', 'window', 'query', 'reset']);
|
|
119
|
+
export const NET_EVIDENCE_ACTIONS = Object.freeze(['export', 'import', 'index', 'search', 'link', 'integrity', 'clear', 'list']);
|
|
120
|
+
export const NET_EVIDENCE_FORMATS = Object.freeze(['jsonl', 'har', 'auto']);
|
|
121
|
+
export const NET_CONTROL_ACTIONS = Object.freeze([
|
|
122
|
+
'throttle', 'offline', 'intercept-add', 'intercept-remove', 'intercept-clear', 'intercept-list',
|
|
123
|
+
'hold', 'resume', 'replay', 'mock', 'reset',
|
|
124
|
+
]);
|
|
125
|
+
export const NET_RULE_KINDS = Object.freeze(['block', 'fail', 'modify-request', 'fulfill', 'delay', 'hold', 'modify-response']);
|
|
126
|
+
export const NET_THEN_KINDS = Object.freeze(['continue', 'fulfill', 'fail']);
|
|
127
|
+
export const NET_SUBSCRIBE_ACTIONS = Object.freeze(['create', 'poll', 'ack', 'close', 'list']);
|
|
128
|
+
export const NET_GROUP_KEYS = Object.freeze(['url', 'method', 'status', 'statusClass', 'resourceType', 'host', 'kind', 'step']);
|
|
129
|
+
export const NET_AGGREGATE_METRICS = Object.freeze(['count', 'bytes', 'duration', 'p50', 'p95', 'failures']);
|
|
130
|
+
export const NET_OBJECT_SOURCES = Object.freeze(['url-query', 'url-path', 'header', 'json-body', 'ws', 'sse']);
|
|
131
|
+
export const NET_CORRELATION_SOURCES = Object.freeze(['header', 'url-query', 'json-body']);
|
|
132
|
+
export const NET_MARK_KINDS = Object.freeze(['tool', 'note', 'action', 'state', 'evidence', 'replay', 'control', 'manual']);
|
|
133
|
+
export const NET_SEARCH_FIELDS = Object.freeze(['url', 'body', 'headers', 'ws', 'sse']);
|
|
134
|
+
export const NET_CAUSALITY_BASES = Object.freeze(['explicit', 'redirect', 'initiator', 'temporal']);
|
|
135
|
+
export const NET_ISSUES = Object.freeze([
|
|
136
|
+
'events-evicted', 'events-dropped', 'bodies-evicted', 'bodies-truncated', 'body-unavailable',
|
|
137
|
+
'subscriber-overflow', 'held-overflow', 'cdp-disconnected', 'import-partial',
|
|
138
|
+
'capture-disabled:websocket', 'capture-disabled:sse', 'capture-disabled:workers',
|
|
139
|
+
'workers-not-attributable', 'workers-shared-attribution', 'response-modification-unsupported',
|
|
140
|
+
]);
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* TOOL-P1-04:body 不可得原因码(稳定枚举,只做加法,不替换既有 `reason:"NET_BODY_UNAVAILABLE"`)。
|
|
144
|
+
*
|
|
145
|
+
* - `not-captured`:采集期 `captureBodies:false`,从未尝试读取(不是 CDP 失败)。
|
|
146
|
+
* - `cdp-no-resource`:CDP 里已没有该请求的资源(requestId 未知 / 跨 target / 生命周期已结束)。
|
|
147
|
+
* - `cdp-evicted`:资源还在但 body 缓冲已被 CDP 淘汰或本地配额淘汰(cache/重定向中途/超预算)。
|
|
148
|
+
* - `cdp-timeout`:受限时长的 CDP body 读取超时。
|
|
149
|
+
* - `cdp-invalid-params`:CDP 拒绝参数(requestId 形态不合法等)。
|
|
150
|
+
* - `cdp-disconnected`:CDP 连接或子会话已断开/关闭。
|
|
151
|
+
* - `cdp-error`:其它明确来自 CDP 协议的错误(不细分,避免自造原因)。
|
|
152
|
+
* - `cdp-unknown`:无法分类;不猜、不伪造、不回显错误原文。
|
|
153
|
+
*/
|
|
154
|
+
export const NET_BODY_REASON_CODES = Object.freeze([
|
|
155
|
+
'not-captured', 'cdp-no-resource', 'cdp-evicted', 'cdp-timeout',
|
|
156
|
+
'cdp-invalid-params', 'cdp-disconnected', 'cdp-error', 'cdp-unknown',
|
|
157
|
+
]);
|
|
158
|
+
|
|
159
|
+
/** §5.6 默认关联规则。 */
|
|
160
|
+
export const DEFAULT_CORRELATION_RULES = Object.freeze([
|
|
161
|
+
Object.freeze({ from: 'header', key: 'traceparent', path: null, name: 'traceparent' }),
|
|
162
|
+
Object.freeze({ from: 'header', key: 'x-request-id', path: null, name: 'x-request-id' }),
|
|
163
|
+
Object.freeze({ from: 'header', key: 'x-trace-id', path: null, name: 'x-trace-id' }),
|
|
164
|
+
Object.freeze({ from: 'header', key: 'request-id', path: null, name: 'request-id' }),
|
|
165
|
+
Object.freeze({ from: 'header', key: 'x-correlation-id', path: null, name: 'x-correlation-id' }),
|
|
166
|
+
Object.freeze({ from: 'url-query', key: 'traceparent', path: null, name: 'traceparent' }),
|
|
167
|
+
Object.freeze({ from: 'url-query', key: 'x-request-id', path: null, name: 'x-request-id' }),
|
|
168
|
+
Object.freeze({ from: 'url-query', key: 'requestId', path: null, name: 'requestId' }),
|
|
169
|
+
Object.freeze({ from: 'json-body', key: 'traceId', path: 'traceId', name: 'traceId' }),
|
|
170
|
+
Object.freeze({ from: 'json-body', key: 'requestId', path: 'requestId', name: 'requestId' }),
|
|
171
|
+
]);
|
|
172
|
+
|
|
173
|
+
/** §5.2 业务状态码默认路径。 */
|
|
174
|
+
export const DEFAULT_BUSINESS_PATHS = Object.freeze(['code', 'status', 'errno', 'bizCode', 'error.code']);
|
|
175
|
+
|
|
176
|
+
const SENSITIVE_KEY = /(token|secret|password|passwd|authorization|cookie|api[-_]?key|session|credential)/i;
|
|
177
|
+
// Correlation ids are echoed back by echo endpoints; they are masked like any other credential
|
|
178
|
+
// (R1-9: only the HMAC survives) so an exported body never carries the raw id.
|
|
179
|
+
const CORRELATION_KEY = /(^|[-_.])(x-)?(request|trace|correlation|span)[-_]?id$|traceparent|tracestate/i;
|
|
180
|
+
// Bare `auth` / `auth_*` / `*_auth` (a fixture constant like `var AUTH = 'Bearer …'`) is a credential
|
|
181
|
+
// even though it is neither `authorization` nor a `*token*` name.
|
|
182
|
+
const AUTH_KEY = /(^|[^a-z0-9])auth([^a-z0-9]|$)/i;
|
|
183
|
+
const SENSITIVE_HEADER = /(authorization|cookie|token|secret|password|passwd|api[-_]?key|auth|session|signature|credential)/i;
|
|
184
|
+
const HOP_BY_HOP_HEADERS = Object.freeze([
|
|
185
|
+
'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer',
|
|
186
|
+
'transfer-encoding', 'upgrade', 'content-length', 'content-encoding',
|
|
187
|
+
]);
|
|
188
|
+
|
|
189
|
+
/* ------------------------------------------------------------------ */
|
|
190
|
+
/* 通用小工具 */
|
|
191
|
+
/* ------------------------------------------------------------------ */
|
|
192
|
+
|
|
193
|
+
export function truncateBytes(value, maxBytes) {
|
|
194
|
+
const text = String(value ?? '');
|
|
195
|
+
if (!Number.isFinite(maxBytes) || maxBytes <= 0) return '';
|
|
196
|
+
if (Buffer.byteLength(text, 'utf8') <= maxBytes) return text;
|
|
197
|
+
let lo = 0;
|
|
198
|
+
let hi = text.length;
|
|
199
|
+
while (lo < hi) {
|
|
200
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
201
|
+
if (Buffer.byteLength(text.slice(0, mid), 'utf8') <= maxBytes) lo = mid; else hi = mid - 1;
|
|
202
|
+
}
|
|
203
|
+
return text.slice(0, lo);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function statusClass(status) {
|
|
207
|
+
if (!Number.isInteger(status) || status <= 0) return null;
|
|
208
|
+
if (status < 200) return '1xx';
|
|
209
|
+
if (status < 300) return '2xx';
|
|
210
|
+
if (status < 400) return '3xx';
|
|
211
|
+
if (status < 500) return '4xx';
|
|
212
|
+
return '5xx';
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** 12 hex 会话 HMAC(公开 valueHash);`full:true` 返回完整 hex(内部 contentHash)。 */
|
|
216
|
+
export function hmacHex(key, value, { full = false } = {}) {
|
|
217
|
+
const digest = createHmac('sha256', key || 'no-key').update(String(value), 'utf8').digest('hex');
|
|
218
|
+
return full ? digest : digest.slice(0, 12);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** 未脱敏 URL 的独立判等 hash(R1-9)。 */
|
|
222
|
+
export function urlHashOf(rawUrl) {
|
|
223
|
+
return createHash('sha256').update(String(rawUrl ?? ''), 'utf8').digest('hex').slice(0, 16);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function clampInt(value, min, max) {
|
|
227
|
+
if (!Number.isFinite(value)) return min;
|
|
228
|
+
return Math.max(min, Math.min(Math.round(value), max));
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** §5.3 分位数:线性插值;样本 <2 时等于 max。 */
|
|
232
|
+
export function percentile(sorted, ratio) {
|
|
233
|
+
if (!Array.isArray(sorted) || sorted.length === 0) return null;
|
|
234
|
+
if (sorted.length === 1) return sorted[0];
|
|
235
|
+
if (ratio <= 0) return sorted[0];
|
|
236
|
+
if (ratio >= 1) return sorted[sorted.length - 1];
|
|
237
|
+
const position = (sorted.length - 1) * ratio;
|
|
238
|
+
const low = Math.floor(position);
|
|
239
|
+
const high = Math.ceil(position);
|
|
240
|
+
if (low === high) return sorted[low];
|
|
241
|
+
const weight = position - low;
|
|
242
|
+
return Math.round((sorted[low] * (1 - weight) + sorted[high] * weight) * 1000) / 1000;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export function sanitizeUrl(raw, maxBytes = NET_LIMITS.urlBytes) {
|
|
246
|
+
const text = String(raw ?? '');
|
|
247
|
+
if (text === '') return { value: '', applied: false };
|
|
248
|
+
let value;
|
|
249
|
+
try { value = redactUrl(text); } catch { value = redactText(text); }
|
|
250
|
+
// Correlation ids in the query string are masked too (R1-9): an echo endpoint reflects them into
|
|
251
|
+
// its body, so leaving the raw id in `event.url` would leak it into every export.
|
|
252
|
+
value = maskQueryCorrelation(value);
|
|
253
|
+
return { value: truncateBytes(value, maxBytes), applied: value !== text };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function maskQueryCorrelation(url) {
|
|
257
|
+
const text = String(url || '');
|
|
258
|
+
const index = text.indexOf('?');
|
|
259
|
+
if (index === -1) return text;
|
|
260
|
+
const head = text.slice(0, index);
|
|
261
|
+
const tail = text.slice(index + 1);
|
|
262
|
+
let changed = false;
|
|
263
|
+
const masked = tail.split('&').map((pair) => {
|
|
264
|
+
const eq = pair.indexOf('=');
|
|
265
|
+
if (eq === -1) return pair;
|
|
266
|
+
const name = pair.slice(0, eq);
|
|
267
|
+
const value = pair.slice(eq + 1);
|
|
268
|
+
if (value === '' || value === '***') return pair;
|
|
269
|
+
if (CORRELATION_KEY.test(decodeOrSelf(name)) || AUTH_KEY.test(decodeOrSelf(name)) || SENSITIVE_KEY.test(decodeOrSelf(name))) {
|
|
270
|
+
changed = true;
|
|
271
|
+
return name + '=***';
|
|
272
|
+
}
|
|
273
|
+
return pair;
|
|
274
|
+
}).join('&');
|
|
275
|
+
return changed ? head + '?' + masked : text;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function decodeOrSelf(value) {
|
|
279
|
+
try { return decodeURIComponent(value); } catch { return String(value); }
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export function sanitizeHeaders(headers, { maxCount = NET_LIMITS.headerCount, maxValueBytes = NET_LIMITS.headerValueBytes } = {}) {
|
|
283
|
+
const out = {};
|
|
284
|
+
const applied = [];
|
|
285
|
+
if (!headers || typeof headers !== 'object') return { headers: out, applied, truncated: false };
|
|
286
|
+
const names = Object.keys(headers);
|
|
287
|
+
let truncated = names.length > maxCount;
|
|
288
|
+
for (const name of names.slice(0, maxCount)) {
|
|
289
|
+
const raw = headers[name];
|
|
290
|
+
const joined = Array.isArray(raw) ? raw.map((item) => String(item)).join(', ') : String(raw ?? '');
|
|
291
|
+
const lower = name.toLowerCase();
|
|
292
|
+
if (lower === 'set-cookie') {
|
|
293
|
+
out[lower] = truncateBytes(joined.replace(/=[^;]*/g, '=***'), maxValueBytes);
|
|
294
|
+
applied.push(lower);
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
if (SENSITIVE_HEADER.test(lower) || CORRELATION_KEY.test(lower) || AUTH_KEY.test(lower)) {
|
|
298
|
+
out[lower] = '***';
|
|
299
|
+
applied.push(lower);
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
const value = truncateBytes(joined, maxValueBytes);
|
|
303
|
+
if (value.length < joined.length) truncated = true;
|
|
304
|
+
out[lower] = value;
|
|
305
|
+
}
|
|
306
|
+
return { headers: out, applied, truncated };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** 剥离 hop-by-hop / 会与改写后 body 冲突的头(R1-8)。 */
|
|
310
|
+
export function stripHopByHopHeaders(headers) {
|
|
311
|
+
if (!headers || typeof headers !== 'object') return {};
|
|
312
|
+
const out = {};
|
|
313
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
314
|
+
if (HOP_BY_HOP_HEADERS.includes(name.toLowerCase())) continue;
|
|
315
|
+
out[name] = value;
|
|
316
|
+
}
|
|
317
|
+
return out;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* §8.4 body 脱敏。返回 `{kind, text, redacted:'fields|none'|'omitted', parseError, bytes, payloadOmitted}`。
|
|
322
|
+
* 二进制/无法安全解析的文本按 R1-9 标记 `omitted`(`available:true` 元数据仍可读)。
|
|
323
|
+
*/
|
|
324
|
+
export function sanitizeBody(raw, contentType, { maskRules = [] } = {}) {
|
|
325
|
+
const type = String(contentType || '').toLowerCase();
|
|
326
|
+
const base = { kind: 'text', text: '', redacted: 'none', parseError: false, bytes: 0, payloadOmitted: false };
|
|
327
|
+
if (raw === undefined || raw === null) return base;
|
|
328
|
+
const maskRulesList = Array.isArray(maskRules) ? maskRules : [];
|
|
329
|
+
const masked = (key) => SENSITIVE_KEY.test(key) || CORRELATION_KEY.test(String(key)) || AUTH_KEY.test(String(key))
|
|
330
|
+
|| maskRulesList.some((rule) => String(rule).length > 0 && String(key).toLowerCase().endsWith(String(rule).toLowerCase()));
|
|
331
|
+
if (Buffer.isBuffer(raw) || raw instanceof Uint8Array) {
|
|
332
|
+
const buffer = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
|
|
333
|
+
base.bytes = buffer.length;
|
|
334
|
+
if (!type || /json|urlencoded|text|xml|javascript|html/.test(type)) {
|
|
335
|
+
return sanitizeBody(buffer.toString('utf8'), contentType, { maskRules });
|
|
336
|
+
}
|
|
337
|
+
return { ...base, kind: 'binary', text: '', redacted: 'omitted', payloadOmitted: true };
|
|
338
|
+
}
|
|
339
|
+
const text = String(raw);
|
|
340
|
+
base.bytes = Buffer.byteLength(text, 'utf8');
|
|
341
|
+
if (/json/.test(type) || /^\s*[[{]/.test(text)) {
|
|
342
|
+
let parsed;
|
|
343
|
+
try { parsed = JSON.parse(text); } catch {
|
|
344
|
+
return { ...base, kind: 'json', text: '', redacted: 'omitted', parseError: true, payloadOmitted: true };
|
|
345
|
+
}
|
|
346
|
+
const walk = (value, depth = 0) => {
|
|
347
|
+
if (depth > 12) return value;
|
|
348
|
+
if (Array.isArray(value)) return value.map((item) => walk(item, depth + 1));
|
|
349
|
+
if (value && typeof value === 'object') {
|
|
350
|
+
const out = {};
|
|
351
|
+
for (const [key, item] of Object.entries(value)) out[key] = masked(key) ? '***' : walk(item, depth + 1);
|
|
352
|
+
return out;
|
|
353
|
+
}
|
|
354
|
+
return value;
|
|
355
|
+
};
|
|
356
|
+
return { ...base, kind: 'json', text: JSON.stringify(walk(parsed)), redacted: 'fields' };
|
|
357
|
+
}
|
|
358
|
+
if (/x-www-form-urlencoded/.test(type)) {
|
|
359
|
+
const pairs = text.split('&').filter((pair) => pair !== '');
|
|
360
|
+
let redacted = false;
|
|
361
|
+
const out = pairs.map((pair) => {
|
|
362
|
+
const index = pair.indexOf('=');
|
|
363
|
+
const key = index === -1 ? pair : pair.slice(0, index);
|
|
364
|
+
if (index !== -1 && masked(decodeURIComponent(key.replace(/\+/g, ' ')))) { redacted = true; return key + '=***'; }
|
|
365
|
+
return pair;
|
|
366
|
+
});
|
|
367
|
+
return { ...base, kind: 'urlencoded', text: out.join('&'), redacted: redacted ? 'fields' : 'none' };
|
|
368
|
+
}
|
|
369
|
+
if (/multipart\/form-data/.test(type)) {
|
|
370
|
+
const fields = [];
|
|
371
|
+
for (const part of text.split(/--[^\r\n]+/).slice(1)) {
|
|
372
|
+
const nameMatch = /name="([^"]*)"/.exec(part);
|
|
373
|
+
if (!nameMatch) continue;
|
|
374
|
+
const fileMatch = /filename="([^"]*)"/.exec(part);
|
|
375
|
+
const bodyStart = part.indexOf('\r\n\r\n');
|
|
376
|
+
fields.push({
|
|
377
|
+
name: nameMatch[1],
|
|
378
|
+
size: bodyStart === -1 ? 0 : Buffer.byteLength(part.slice(bodyStart + 4).replace(/\r\n$/, ''), 'utf8'),
|
|
379
|
+
...(fileMatch ? { filename: fileMatch[1] } : {}),
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
return { ...base, kind: 'multipart', text: JSON.stringify({ multipart: fields }), redacted: 'fields' };
|
|
383
|
+
}
|
|
384
|
+
if (/^text\/|xml|javascript|html|event-stream/.test(type) || type === '') {
|
|
385
|
+
// Text (HTML/JS/plain) cannot be field-parsed, but an inline `token: "…"` constant must still
|
|
386
|
+
// never leak (§8.4 / C45): scrub values that follow a sensitive-looking name.
|
|
387
|
+
const scrubbed = scrubTextSecrets(text, maskRules);
|
|
388
|
+
return {
|
|
389
|
+
...base,
|
|
390
|
+
kind: 'text',
|
|
391
|
+
text: truncateBytes(scrubbed.text, NET_LIMITS.detailBodyBytes),
|
|
392
|
+
redacted: scrubbed.applied ? 'fields' : 'none',
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
return { ...base, kind: 'binary', text: '', redacted: 'omitted', payloadOmitted: true };
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* 文本 body 的"字段名→值"脱敏:HTML/JS/纯文本无法结构化解析时,只替换**敏感字段名**后面的值
|
|
401
|
+
* (`name=…`、`name: …`、`"name":"…"`)。保守到不会碰普通词,避免 inline 常量泄漏(C45)。
|
|
402
|
+
*/
|
|
403
|
+
export function scrubTextSecrets(text, maskRules = []) {
|
|
404
|
+
const raw = String(text ?? '');
|
|
405
|
+
const extra = Array.isArray(maskRules) ? maskRules.map((rule) => String(rule)).filter(Boolean) : [];
|
|
406
|
+
const esc = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
407
|
+
const namePattern = '(?:[A-Za-z0-9_$.-]*(?:token|secret|password|passwd|authorization|auth|cookie|api[-_]?key|session|credential)[A-Za-z0-9_$.-]*'
|
|
408
|
+
+ '|(?:x-)?(?:request|trace|correlation|span)[-_]?id'
|
|
409
|
+
+ (extra.length ? '|' + extra.map(esc).join('|') : '') + ')';
|
|
410
|
+
const pattern = new RegExp('(' + namePattern + '\\s*[:=]\\s*)([\'"])([^\'"]{1,512})\\2', 'gi');
|
|
411
|
+
let applied = false;
|
|
412
|
+
const out = raw.replace(pattern, (match, prefix, quote) => {
|
|
413
|
+
applied = true;
|
|
414
|
+
return prefix + quote + '***' + quote;
|
|
415
|
+
});
|
|
416
|
+
return { text: out, applied };
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* TOOL-P1-04:把一次 body 读取失败(`cdp.send` 抛出的 BrowserError / CDP 协议错误 / 传输错误)
|
|
421
|
+
* 映射为稳定原因码。只读取 `code`/`message` 做匹配,返回值只有枚举本身,**不回显错误原文**;
|
|
422
|
+
* `reasonDetail` 由 `normalizeBodyReasonDetail` 单独脱敏。未知/空输入一律 `cdp-unknown`。
|
|
423
|
+
*/
|
|
424
|
+
export function classifyBodyFailure(error) {
|
|
425
|
+
if (error === undefined || error === null || error === '') return 'cdp-unknown';
|
|
426
|
+
const code = typeof error === 'string' ? '' : String(error.code || '').toUpperCase();
|
|
427
|
+
const message = typeof error === 'string' ? error : String(error.message || error || '');
|
|
428
|
+
if (code === 'CDP_TIMEOUT' || code === 'NET_CONTROL_TIMEOUT' || /(?:timed?\s*out|timeout)/i.test(message)) return 'cdp-timeout';
|
|
429
|
+
if (code === 'CDP_DISCONNECTED' || /(?:disconnect|connection (?:closed|lost)|not attached|target (?:closed|detached)|session (?:closed|detached))/i.test(message)) return 'cdp-disconnected';
|
|
430
|
+
// Order matters: "No data found for resource with given identifier" means the buffered body was
|
|
431
|
+
// dropped, not that the request id is unknown.
|
|
432
|
+
if (/(?:no data found for resource|data (?:is )?(?:not|no longer) available|resource (?:was )?evicted|buffer(?:s|ing)? (?:evicted|dropped)|body (?:evicted|dropped|discarded))/i.test(message)) return 'cdp-evicted';
|
|
433
|
+
if (/(?:no resource (?:with|for)|resource with given|request (?:id )?(?:not found|unknown)|unknown request)/i.test(message)) return 'cdp-no-resource';
|
|
434
|
+
if (code === 'INVALID_ARGUMENT' || code === 'NET_INVALID_ARGUMENT' || /(?:invalid (?:params|parameters|argument))/i.test(message)) return 'cdp-invalid-params';
|
|
435
|
+
if (typeof error.code === 'number') return error.code === -32602 ? 'cdp-invalid-params' : 'cdp-error';
|
|
436
|
+
if (code === 'INTERNAL' || code === 'CDP_ERROR' || /(?:cdp error|protocol error|\[internal\])/i.test(message)) return 'cdp-error';
|
|
437
|
+
return 'cdp-unknown';
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** `reasonCode` 归一化:省略/未知取值回落到 `cdp-unknown`,保持枚举稳定(不写入自造词)。 */
|
|
441
|
+
function normalizeBodyReasonCode(reasonCode) {
|
|
442
|
+
if (reasonCode === undefined || reasonCode === null || reasonCode === '') return 'cdp-unknown';
|
|
443
|
+
const value = String(reasonCode);
|
|
444
|
+
return NET_BODY_REASON_CODES.includes(value) ? value : 'cdp-unknown';
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* `reasonDetail`:单行、≤160 字节、脱敏(URL userinfo/敏感 query + 敏感字段值 + 控制字符)。
|
|
449
|
+
* 空值/全空白 → null(不伪造占位文本)。
|
|
450
|
+
*/
|
|
451
|
+
export function normalizeBodyReasonDetail(reasonDetail, maskRules = []) {
|
|
452
|
+
if (reasonDetail === undefined || reasonDetail === null) return null;
|
|
453
|
+
let text = String(reasonDetail);
|
|
454
|
+
if (text === '') return null;
|
|
455
|
+
text = text.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim();
|
|
456
|
+
if (text === '') return null;
|
|
457
|
+
const scrubbed = scrubTextSecrets(text, maskRules);
|
|
458
|
+
// Text bodies only scrub quoted `name:"…"` values; an error detail may also carry bare
|
|
459
|
+
// `name=value` pairs (e.g. `token=…` outside a URL), so mask those here too before bounding.
|
|
460
|
+
const masked = scrubbed.text.replace(
|
|
461
|
+
/((?:[A-Za-z0-9_$.-]*(?:token|secret|pass|passwd|authorization|auth|cookie|api[-_]?key|session|credential)[A-Za-z0-9_$.-]*)\s*[:=]\s*)([^\s,;&"']+)/gi,
|
|
462
|
+
'$1***',
|
|
463
|
+
);
|
|
464
|
+
const bounded = truncateBytes(redactText(masked), 160).trim();
|
|
465
|
+
return bounded === '' ? null : bounded;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
export function bodyKindOf(contentType) {
|
|
469
|
+
const type = String(contentType || '').toLowerCase();
|
|
470
|
+
if (/json/.test(type)) return 'json';
|
|
471
|
+
if (/x-www-form-urlencoded/.test(type)) return 'urlencoded';
|
|
472
|
+
if (/multipart\/form-data/.test(type)) return 'multipart';
|
|
473
|
+
if (/^text\/|xml|javascript|html/.test(type)) return 'text';
|
|
474
|
+
if (type === '') return 'unknown';
|
|
475
|
+
return 'binary';
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
export function parseQueryString(url) {
|
|
479
|
+
const out = [];
|
|
480
|
+
try {
|
|
481
|
+
const parsed = new URL(String(url || ''));
|
|
482
|
+
for (const [name, value] of parsed.searchParams.entries()) out.push({ name, value });
|
|
483
|
+
} catch { /* 非法 URL 没有 query */ }
|
|
484
|
+
return out;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
export function readJsonPath(value, path) {
|
|
488
|
+
if (typeof path !== 'string' || path === '') return { found: false, value: undefined };
|
|
489
|
+
const tokens = [];
|
|
490
|
+
const text = path.startsWith('$') ? path.slice(1) : path;
|
|
491
|
+
const pattern = /([^.[\]]+)|\[(\d+)\]/g;
|
|
492
|
+
let match;
|
|
493
|
+
while ((match = pattern.exec(text)) !== null) {
|
|
494
|
+
if (match[1] !== undefined) tokens.push(match[1]);
|
|
495
|
+
else tokens.push(Number(match[2]));
|
|
496
|
+
}
|
|
497
|
+
let cursor = value;
|
|
498
|
+
for (const token of tokens) {
|
|
499
|
+
if (cursor === null || cursor === undefined) return { found: false, value: undefined };
|
|
500
|
+
if (typeof token === 'number') {
|
|
501
|
+
if (!Array.isArray(cursor) || token >= cursor.length) return { found: false, value: undefined };
|
|
502
|
+
cursor = cursor[token];
|
|
503
|
+
} else {
|
|
504
|
+
if (typeof cursor !== 'object' || !(token in cursor)) return { found: false, value: undefined };
|
|
505
|
+
cursor = cursor[token];
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
return { found: true, value: cursor };
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
export function encodeCursor(seq) {
|
|
512
|
+
if (!Number.isInteger(seq) || seq < 0) return null;
|
|
513
|
+
return Buffer.from(JSON.stringify({ v: 1, seq }), 'utf8').toString('base64url');
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
export function decodeCursor(cursor) {
|
|
517
|
+
if (cursor === undefined || cursor === null || cursor === '') return null;
|
|
518
|
+
if (typeof cursor !== 'string' || cursor.length > 256) throw new BrowserError('NET_INVALID_ARGUMENT', 'cursor 不合法');
|
|
519
|
+
let parsed;
|
|
520
|
+
try { parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')); } catch { throw new BrowserError('NET_INVALID_ARGUMENT', 'cursor 不合法'); }
|
|
521
|
+
if (!parsed || parsed.v !== 1 || !Number.isInteger(parsed.seq) || parsed.seq < 0) throw new BrowserError('NET_INVALID_ARGUMENT', 'cursor 不合法');
|
|
522
|
+
return parsed.seq;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
export function matchUrlPattern(pattern, url) {
|
|
526
|
+
if (typeof pattern !== 'string' || pattern === '') return false;
|
|
527
|
+
const source = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.');
|
|
528
|
+
try { return new RegExp('^' + source + '$', 'i').test(String(url ?? '')); } catch { return false; }
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function assertKnownKeys(value, allowed, label, code = 'NET_INVALID_ARGUMENT') {
|
|
532
|
+
if (value === undefined || value === null) return {};
|
|
533
|
+
if (typeof value !== 'object' || Array.isArray(value)) throw new BrowserError(code, label + ' 必须是对象');
|
|
534
|
+
for (const key of Object.keys(value)) {
|
|
535
|
+
if (!allowed.includes(key)) throw new BrowserError(code, label + ' 含未知字段 ' + key, { field: key, allowed: [...allowed] });
|
|
536
|
+
}
|
|
537
|
+
return value;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** 事件 JSON 估算字节(R1-15 的固定口径之一)。 */
|
|
541
|
+
export function estimateEventBytes(event) {
|
|
542
|
+
try { return Buffer.byteLength(JSON.stringify(event), 'utf8'); } catch { return 0; }
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/* ------------------------------------------------------------------ */
|
|
546
|
+
/* 会话配置(§2.1 + R1-19) */
|
|
547
|
+
/* ------------------------------------------------------------------ */
|
|
548
|
+
|
|
549
|
+
const CONFIG_KEYS = Object.freeze(Object.keys(NET_DEFAULTS));
|
|
550
|
+
|
|
551
|
+
export function normalizeSessionConfig(input, base = NET_DEFAULTS) {
|
|
552
|
+
const config = { ...base, maskRules: Array.isArray(base.maskRules) ? [...base.maskRules] : [] };
|
|
553
|
+
if (input === undefined || input === null) return config;
|
|
554
|
+
if (typeof input !== 'object' || Array.isArray(input)) throw new BrowserError('NET_CONFIG_INVALID', 'config 必须是对象');
|
|
555
|
+
for (const key of Object.keys(input)) {
|
|
556
|
+
if (!CONFIG_KEYS.includes(key)) throw new BrowserError('NET_CONFIG_INVALID', '未知的 config 字段 ' + key, { field: key, allowed: [...CONFIG_KEYS] });
|
|
557
|
+
}
|
|
558
|
+
for (const key of ['captureBodies', 'captureWebSocket', 'captureSse', 'captureWorkers']) {
|
|
559
|
+
if (input[key] === undefined) continue;
|
|
560
|
+
if (typeof input[key] !== 'boolean') throw new BrowserError('NET_CONFIG_INVALID', `${key} 必须是布尔值`, { field: key });
|
|
561
|
+
config[key] = input[key];
|
|
562
|
+
}
|
|
563
|
+
for (const [key, min, max] of [
|
|
564
|
+
['maxEvents', 1, NET_LIMITS.maxEvents],
|
|
565
|
+
['maxBodyBytes', 1, NET_LIMITS.maxBodyBytes],
|
|
566
|
+
['maxTotalBytes', 1, NET_LIMITS.maxTotalBytes],
|
|
567
|
+
['maxWsFrames', 0, NET_LIMITS.maxWsFrames],
|
|
568
|
+
]) {
|
|
569
|
+
if (input[key] === undefined) continue;
|
|
570
|
+
if (!Number.isInteger(input[key])) throw new BrowserError('NET_CONFIG_INVALID', `${key} 必须是整数`, { field: key });
|
|
571
|
+
if (input[key] < min || input[key] > max) {
|
|
572
|
+
throw new BrowserError('NET_QUOTA_EXCEEDED', `${key} 超出允许上限 ${max}`, { field: key, min, max, value: input[key] });
|
|
573
|
+
}
|
|
574
|
+
config[key] = input[key];
|
|
575
|
+
}
|
|
576
|
+
if (input.businessStatusPath !== undefined && input.businessStatusPath !== null) {
|
|
577
|
+
if (typeof input.businessStatusPath !== 'string' || input.businessStatusPath.length === 0 || input.businessStatusPath.length > 256) {
|
|
578
|
+
throw new BrowserError('NET_CONFIG_INVALID', 'businessStatusPath 必须是 1–256 字符字符串', { field: 'businessStatusPath' });
|
|
579
|
+
}
|
|
580
|
+
config.businessStatusPath = input.businessStatusPath;
|
|
581
|
+
}
|
|
582
|
+
if (input.maskRules !== undefined && input.maskRules !== null) {
|
|
583
|
+
if (!Array.isArray(input.maskRules) || input.maskRules.length > 16) {
|
|
584
|
+
throw new BrowserError('NET_CONFIG_INVALID', 'maskRules 必须是最多 16 项的数组', { field: 'maskRules', max: 16 });
|
|
585
|
+
}
|
|
586
|
+
config.maskRules = input.maskRules.map((rule) => {
|
|
587
|
+
if (typeof rule !== 'string' || rule.length === 0 || rule.length > 64) {
|
|
588
|
+
throw new BrowserError('NET_CONFIG_INVALID', 'maskRules 每项必须是 1–64 字符字符串', { field: 'maskRules' });
|
|
589
|
+
}
|
|
590
|
+
return rule;
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
return config;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/* ------------------------------------------------------------------ */
|
|
597
|
+
/* 事件规范化(§4.1 + R1-1 / R1-9 / R1-10) */
|
|
598
|
+
/* ------------------------------------------------------------------ */
|
|
599
|
+
|
|
600
|
+
export const EVENT_FIELDS = Object.freeze([
|
|
601
|
+
'seq', 'sessionId', 'ts', 'kind', 'phase', 'requestId', 'parentRequestId', 'hopId',
|
|
602
|
+
'targetId', 'cdpSessionId', 'frameId', 'loaderId', 'navId',
|
|
603
|
+
'documentURL', 'url', 'urlHash', 'method', 'resourceType', 'protocol', 'fromCache',
|
|
604
|
+
'status', 'statusText', 'mimeType', 'redirect', 'initiator', 'timing', 'sizes',
|
|
605
|
+
'failed', 'errorText', 'errorCode', 'blockedReason', 'canceled', 'ws', 'sse', 'mark',
|
|
606
|
+
'correlationIds', 'business', 'stepIds', 'stepId', 'evidenceIds', 'redaction', 'preSession',
|
|
607
|
+
'attribution',
|
|
608
|
+
]);
|
|
609
|
+
|
|
610
|
+
/** 内部请求键 `(targetId, cdpSessionId, rawRequestId, hop)`(R1-10)。 */
|
|
611
|
+
export function requestKey(event) {
|
|
612
|
+
const source = event || {};
|
|
613
|
+
return [source.targetId ?? '', source.cdpSessionId ?? '', source.requestId ?? '', Number.isInteger(source.hopId) ? source.hopId : 0].join('\u0000');
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
function asString(value, maxBytes) {
|
|
617
|
+
return value === undefined || value === null ? null : truncateBytes(String(value), maxBytes);
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function asInt(value) {
|
|
621
|
+
return Number.isInteger(value) ? value : null;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
export function emptyTiming() {
|
|
625
|
+
return {
|
|
626
|
+
sendMs: null, waitMs: null, receiveMs: null, ttfbMs: null, totalMs: null,
|
|
627
|
+
dnsMs: null, connectMs: null, sslMs: null, requestTimeMs: null, responseTimeMs: null,
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* CDP `response.timing` → §4.1 `timing`(R1-11 逐项定义,全部毫秒;负数/缺失 → null)。
|
|
633
|
+
* `requestTime` 是 CDP 秒,`requestTimeMs = requestTime*1000`。
|
|
634
|
+
*/
|
|
635
|
+
export function normalizeTiming(timing, { responseSeconds = null } = {}) {
|
|
636
|
+
const out = emptyTiming();
|
|
637
|
+
// CDP 的 timing 各字段已是**毫秒**;`requestTime` 是**秒**(R1-11)。
|
|
638
|
+
const ms = (value) => (Number.isFinite(value) && value >= 0 ? Math.round(value * 1000) / 1000 : null);
|
|
639
|
+
const secondsToMs = (value) => (Number.isFinite(value) && value >= 0 ? Math.round(value * 1000 * 1000) / 1000 : null);
|
|
640
|
+
const diff = (a, b) => (Number.isFinite(a) && Number.isFinite(b) && a >= 0 && b >= 0 && b >= a ? ms(b - a) : null);
|
|
641
|
+
if (timing && typeof timing === 'object') {
|
|
642
|
+
if (Number.isFinite(timing.requestTime)) out.requestTimeMs = secondsToMs(timing.requestTime);
|
|
643
|
+
out.dnsMs = diff(timing.dnsStart, timing.dnsEnd);
|
|
644
|
+
out.connectMs = diff(timing.connectStart, timing.connectEnd);
|
|
645
|
+
out.sslMs = diff(timing.sslStart, timing.sslEnd);
|
|
646
|
+
out.sendMs = diff(timing.sendStart, timing.sendEnd);
|
|
647
|
+
const headersStart = Number.isFinite(timing.receiveHeadersStart) ? timing.receiveHeadersStart : null;
|
|
648
|
+
if (headersStart !== null) {
|
|
649
|
+
out.waitMs = diff(timing.sendEnd, headersStart);
|
|
650
|
+
out.receiveMs = diff(headersStart, timing.receiveHeadersEnd);
|
|
651
|
+
out.ttfbMs = ms(headersStart);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
if (Number.isFinite(responseSeconds)) {
|
|
655
|
+
out.responseTimeMs = secondsToMs(responseSeconds);
|
|
656
|
+
if (out.requestTimeMs !== null) out.totalMs = Math.round((out.responseTimeMs - out.requestTimeMs) * 1000) / 1000;
|
|
657
|
+
}
|
|
658
|
+
if (out.ttfbMs === null && out.waitMs !== null) out.ttfbMs = out.waitMs;
|
|
659
|
+
return out;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
export function normalizeSizes({ requestBody, responseBody, requestHeaders, responseHeaders, encoded, decoded } = {}) {
|
|
663
|
+
const int = (value) => (Number.isInteger(value) && value >= 0 ? value : null);
|
|
664
|
+
return {
|
|
665
|
+
requestBody: int(requestBody),
|
|
666
|
+
responseBody: int(responseBody),
|
|
667
|
+
requestHeaders: int(requestHeaders),
|
|
668
|
+
responseHeaders: int(responseHeaders),
|
|
669
|
+
encoded: int(encoded),
|
|
670
|
+
decoded: int(decoded),
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* §4.1 / §3.1 initiator. Chromium frequently leaves `initiator.url` empty (and the first stack frame
|
|
676
|
+
* url empty too) for inline page scripts, so the page document URL is used as the attribution for
|
|
677
|
+
* `type:"script"`-style initiators — that IS where the script ran. `source` records which fallback
|
|
678
|
+
* produced the url so nothing is invented silently.
|
|
679
|
+
*/
|
|
680
|
+
export function normalizeInitiator(initiator, { documentURL = null } = {}) {
|
|
681
|
+
if (!initiator || typeof initiator !== 'object') return null;
|
|
682
|
+
const frames = initiator.stack && Array.isArray(initiator.stack.callFrames)
|
|
683
|
+
? initiator.stack.callFrames.slice(0, NET_LIMITS.initiatorStack).map((frame) => ({
|
|
684
|
+
functionName: frame.functionName ? truncateBytes(frame.functionName, 128) : '',
|
|
685
|
+
url: frame.url ? sanitizeUrl(frame.url).value : '',
|
|
686
|
+
line: Number.isInteger(frame.lineNumber) ? frame.lineNumber : null,
|
|
687
|
+
column: Number.isInteger(frame.columnNumber) ? frame.columnNumber : null,
|
|
688
|
+
}))
|
|
689
|
+
: [];
|
|
690
|
+
const own = initiator.url ? sanitizeUrl(initiator.url).value : null;
|
|
691
|
+
const frameUrl = frames.find((frame) => frame.url) ? frames.find((frame) => frame.url).url : null;
|
|
692
|
+
const type = initiator.type ? String(initiator.type) : null;
|
|
693
|
+
const pageUrl = documentURL ? sanitizeUrl(documentURL).value : null;
|
|
694
|
+
let url = own;
|
|
695
|
+
let source = own ? 'cdp' : null;
|
|
696
|
+
if (!url && frameUrl) { url = frameUrl; source = 'stack'; }
|
|
697
|
+
if (!url && pageUrl && ['script', 'parser', 'preflight'].includes(type)) { url = pageUrl; source = 'document'; }
|
|
698
|
+
const firstFrame = frames[0] || null;
|
|
699
|
+
return {
|
|
700
|
+
type,
|
|
701
|
+
url,
|
|
702
|
+
line: Number.isInteger(initiator.lineNumber) ? initiator.lineNumber : (firstFrame ? firstFrame.line : null),
|
|
703
|
+
column: Number.isInteger(initiator.columnNumber) ? initiator.columnNumber : (firstFrame ? firstFrame.column : null),
|
|
704
|
+
requestId: initiator.requestId ? truncateBytes(String(initiator.requestId), 128) : null,
|
|
705
|
+
source,
|
|
706
|
+
stack: frames,
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function normalizeWs(ws) {
|
|
711
|
+
const payloadRaw = ws.payload === undefined || ws.payload === null ? null : String(ws.payload);
|
|
712
|
+
const payload = payloadRaw === null ? null : truncateBytes(payloadRaw, NET_LIMITS.wsPayloadBytes);
|
|
713
|
+
return {
|
|
714
|
+
direction: ws.direction === 'send' || ws.direction === 'receive' ? ws.direction : null,
|
|
715
|
+
opcode: Number.isInteger(ws.opcode) ? ws.opcode : null,
|
|
716
|
+
payload,
|
|
717
|
+
payloadBytes: Number.isInteger(ws.payloadBytes) ? ws.payloadBytes
|
|
718
|
+
: (payloadRaw === null ? null : Buffer.byteLength(payloadRaw, 'utf8')),
|
|
719
|
+
payloadTruncated: ws.payloadTruncated === true || (payloadRaw !== null && Buffer.byteLength(payloadRaw, 'utf8') > NET_LIMITS.wsPayloadBytes),
|
|
720
|
+
payloadOmitted: ws.payloadOmitted === true,
|
|
721
|
+
url: ws.url ? sanitizeUrl(ws.url).value : null,
|
|
722
|
+
protocol: ws.protocol ? truncateBytes(String(ws.protocol), 64) : null,
|
|
723
|
+
handshake: ws.handshake && typeof ws.handshake === 'object' ? {
|
|
724
|
+
status: asInt(ws.handshake.status),
|
|
725
|
+
statusText: asString(ws.handshake.statusText, 128),
|
|
726
|
+
headers: ws.handshake.headers ? sanitizeHeaders(ws.handshake.headers).headers : null,
|
|
727
|
+
} : null,
|
|
728
|
+
openedAt: Number.isFinite(ws.openedAt) ? ws.openedAt : null,
|
|
729
|
+
closedAt: Number.isFinite(ws.closedAt) ? ws.closedAt : null,
|
|
730
|
+
errorMessage: ws.errorMessage ? truncateBytes(redactText(String(ws.errorMessage)), NET_LIMITS.errorTextBytes) : null,
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
function normalizeSse(sse) {
|
|
735
|
+
const raw = sse.data === undefined || sse.data === null ? null : String(sse.data);
|
|
736
|
+
const data = raw === null ? null : truncateBytes(raw, NET_LIMITS.sseDataBytes);
|
|
737
|
+
return {
|
|
738
|
+
eventName: sse.eventName ? truncateBytes(String(sse.eventName), 64) : null,
|
|
739
|
+
eventId: sse.eventId ? truncateBytes(String(sse.eventId), 128) : null,
|
|
740
|
+
data,
|
|
741
|
+
dataBytes: raw === null ? null : Buffer.byteLength(raw, 'utf8'),
|
|
742
|
+
truncated: sse.truncated === true || (raw !== null && Buffer.byteLength(raw, 'utf8') > NET_LIMITS.sseDataBytes),
|
|
743
|
+
payloadOmitted: sse.payloadOmitted === true,
|
|
744
|
+
retryMs: Number.isInteger(sse.retry) ? sse.retry : (Number.isInteger(sse.retryMs) ? sse.retryMs : null),
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
function normalizeMark(mark) {
|
|
749
|
+
return {
|
|
750
|
+
kind: NET_MARK_KINDS.includes(mark.kind) ? mark.kind : 'note',
|
|
751
|
+
text: mark.text ? truncateBytes(String(mark.text), 256) : null,
|
|
752
|
+
tool: mark.tool ? truncateBytes(String(mark.tool), 64) : null,
|
|
753
|
+
actionId: mark.actionId ? truncateBytes(String(mark.actionId), 64) : null,
|
|
754
|
+
stepId: mark.stepId ? truncateBytes(String(mark.stepId), 64) : null,
|
|
755
|
+
labels: mark.labels && typeof mark.labels === 'object'
|
|
756
|
+
? Object.fromEntries(Object.entries(mark.labels).slice(0, NET_LIMITS.stepLabels).map(([key, value]) => [truncateBytes(key, 64), truncateBytes(String(value), 128)]))
|
|
757
|
+
: null,
|
|
758
|
+
revision: Number.isInteger(mark.revision) ? mark.revision : null,
|
|
759
|
+
url: mark.url ? sanitizeUrl(mark.url).value : null,
|
|
760
|
+
title: mark.title ? truncateBytes(String(mark.title), 256) : null,
|
|
761
|
+
wallMs: Number.isFinite(mark.wallMs) ? Math.round(mark.wallMs) : null,
|
|
762
|
+
fromSeq: Number.isInteger(mark.fromSeq) ? mark.fromSeq : null,
|
|
763
|
+
basis: mark.basis ? truncateBytes(String(mark.basis), 32) : null,
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/**
|
|
768
|
+
* 补齐 §4.1 主干。meta: `{seq, sessionId, wallMs, monotonicMs, preSession?, hmacKey?}`。
|
|
769
|
+
* `input.correlationIds[].contentHash` 只在本进程内用于同链路判等,不进事件本体(R1-9)。
|
|
770
|
+
*/
|
|
771
|
+
export function normalizeEvent(input, meta) {
|
|
772
|
+
const source = input && typeof input === 'object' ? input : {};
|
|
773
|
+
const replayTag = source.replay && typeof source.replay === 'object' ? { ...source.replay } : null;
|
|
774
|
+
const ts = source.ts && typeof source.ts === 'object' ? ts_of(source.ts) : {};
|
|
775
|
+
const url = sanitizeUrl(source.url);
|
|
776
|
+
const documentURL = sanitizeUrl(source.documentURL);
|
|
777
|
+
const applied = [];
|
|
778
|
+
if (url.applied) applied.push('url');
|
|
779
|
+
if (documentURL.applied) applied.push('documentURL');
|
|
780
|
+
const rules = [];
|
|
781
|
+
if (source.redaction && Array.isArray(source.redaction.rules)) rules.push(...source.redaction.rules.map((rule) => truncateBytes(String(rule), 64)));
|
|
782
|
+
const redirect = source.redirect && typeof source.redirect === 'object'
|
|
783
|
+
? {
|
|
784
|
+
from: sanitizeUrl(source.redirect.from).value,
|
|
785
|
+
to: sanitizeUrl(source.redirect.to).value,
|
|
786
|
+
status: asInt(source.redirect.status),
|
|
787
|
+
fromSeq: Number.isInteger(source.redirect.fromSeq) ? source.redirect.fromSeq : null,
|
|
788
|
+
toSeq: Number.isInteger(source.redirect.toSeq) ? source.redirect.toSeq : null,
|
|
789
|
+
}
|
|
790
|
+
: null;
|
|
791
|
+
const bodyMode = source.redaction && source.redaction.body
|
|
792
|
+
? (source.redaction.body === 'fields' ? 'fields' : source.redaction.body === 'omitted' ? 'omitted' : 'none')
|
|
793
|
+
: 'none';
|
|
794
|
+
const correlationKey = meta.hmacKey || 'no-key';
|
|
795
|
+
const correlationIds = Array.isArray(source.correlationIds)
|
|
796
|
+
? source.correlationIds.slice(0, NET_LIMITS.correlationRules).map((item) => {
|
|
797
|
+
const raw = item && item.value !== undefined && item.value !== null ? String(item.value) : null;
|
|
798
|
+
const contentHash = item && item.contentHash ? String(item.contentHash) : (raw === null ? null : hmacHex(correlationKey, raw, { full: true }));
|
|
799
|
+
return {
|
|
800
|
+
name: truncateBytes(String(item && item.name ? item.name : ''), 64),
|
|
801
|
+
// §5.6/R1-9: the raw correlation value never enters an event, an export or a search hit —
|
|
802
|
+
// only the per-session HMAC (`valueHash`, 12 hex) survives, which is enough to group a
|
|
803
|
+
// trace without leaking the id.
|
|
804
|
+
value: raw === null ? null : '***',
|
|
805
|
+
valueHash: contentHash === null ? null : contentHash.slice(0, 12),
|
|
806
|
+
source: item && item.source ? truncateBytes(String(item.source), 32) : null,
|
|
807
|
+
contentHash,
|
|
808
|
+
};
|
|
809
|
+
})
|
|
810
|
+
: [];
|
|
811
|
+
return {
|
|
812
|
+
...(replayTag ? { replay: replayTag } : {}),
|
|
813
|
+
seq: meta.seq,
|
|
814
|
+
sessionId: meta.sessionId === undefined ? null : meta.sessionId,
|
|
815
|
+
ts: {
|
|
816
|
+
wallMs: Number.isFinite(ts.wallMs) ? Math.round(ts.wallMs) : meta.wallMs,
|
|
817
|
+
monotonicMs: Number.isFinite(ts.monotonicMs) ? Math.round(ts.monotonicMs * 1000) / 1000 : meta.monotonicMs,
|
|
818
|
+
cdpSeconds: Number.isFinite(ts.cdpSeconds) ? ts.cdpSeconds : null,
|
|
819
|
+
},
|
|
820
|
+
kind: NET_KINDS.includes(source.kind) ? source.kind : 'http',
|
|
821
|
+
phase: NET_PHASES.includes(source.phase) ? source.phase : 'request',
|
|
822
|
+
requestId: asString(source.requestId, 128),
|
|
823
|
+
parentRequestId: asString(source.parentRequestId, 128),
|
|
824
|
+
hopId: Number.isInteger(source.hopId) ? source.hopId : null,
|
|
825
|
+
targetId: asString(source.targetId, 128),
|
|
826
|
+
cdpSessionId: asString(source.cdpSessionId, 128),
|
|
827
|
+
frameId: asString(source.frameId, 128),
|
|
828
|
+
loaderId: asString(source.loaderId, 128),
|
|
829
|
+
navId: Number.isInteger(source.navId) ? source.navId : null,
|
|
830
|
+
documentURL: documentURL.value || null,
|
|
831
|
+
url: url.value,
|
|
832
|
+
urlHash: source.urlHash ? truncateBytes(String(source.urlHash), 32) : urlHashOf(source.url),
|
|
833
|
+
method: source.method ? truncateBytes(String(source.method), 16) : null,
|
|
834
|
+
resourceType: source.resourceType ? truncateBytes(String(source.resourceType), 32) : null,
|
|
835
|
+
protocol: asString(source.protocol, 32),
|
|
836
|
+
fromCache: source.fromCache === true,
|
|
837
|
+
status: asInt(source.status),
|
|
838
|
+
statusText: asString(source.statusText, 128),
|
|
839
|
+
mimeType: asString(source.mimeType, 128),
|
|
840
|
+
redirect,
|
|
841
|
+
initiator: normalizeInitiator(source.initiator, { documentURL: documentURL.value || null }) || null,
|
|
842
|
+
timing: source.timing && typeof source.timing === 'object' ? { ...emptyTiming(), ...pickTiming(source.timing) } : null,
|
|
843
|
+
sizes: normalizeSizes(source.sizes || {}),
|
|
844
|
+
failed: source.failed === true,
|
|
845
|
+
errorText: source.errorText ? truncateBytes(redactText(String(source.errorText)), NET_LIMITS.errorTextBytes) : null,
|
|
846
|
+
errorCode: source.errorCode ? truncateBytes(String(source.errorCode), 64) : null,
|
|
847
|
+
blockedReason: source.blockedReason ? truncateBytes(String(source.blockedReason), 128) : null,
|
|
848
|
+
canceled: source.canceled === true,
|
|
849
|
+
ws: source.ws && typeof source.ws === 'object' ? normalizeWs(source.ws) : null,
|
|
850
|
+
sse: source.sse && typeof source.sse === 'object' ? normalizeSse(source.sse) : null,
|
|
851
|
+
mark: source.mark && typeof source.mark === 'object' ? normalizeMark(source.mark) : null,
|
|
852
|
+
correlationIds: correlationIds.map(({ contentHash, ...rest }) => rest),
|
|
853
|
+
business: source.business && typeof source.business === 'object' ? {
|
|
854
|
+
statusCode: asInt(source.business.statusCode),
|
|
855
|
+
businessCode: source.business.businessCode === undefined || source.business.businessCode === null
|
|
856
|
+
? null
|
|
857
|
+
: (Number.isFinite(source.business.businessCode) ? source.business.businessCode : truncateBytes(String(source.business.businessCode), 64)),
|
|
858
|
+
businessCodePath: asString(source.business.businessCodePath, 256),
|
|
859
|
+
} : null,
|
|
860
|
+
stepIds: Array.isArray(source.stepIds) ? source.stepIds.slice(0, 16).map((id) => truncateBytes(String(id), 64))
|
|
861
|
+
: (source.stepId ? [truncateBytes(String(source.stepId), 64)] : []),
|
|
862
|
+
stepId: source.stepId ? truncateBytes(String(source.stepId), 64) : null,
|
|
863
|
+
evidenceIds: Array.isArray(source.evidenceIds) ? source.evidenceIds.slice(0, 16).map((id) => truncateBytes(String(id), 128)) : [],
|
|
864
|
+
redaction: { applied, rules, body: bodyMode },
|
|
865
|
+
preSession: meta.preSession === true || source.preSession === true,
|
|
866
|
+
// R1-21: a child-target event proves its scope by being attached to *this* Runtime's page
|
|
867
|
+
// session. `null` for main-page events.
|
|
868
|
+
attribution: source.attribution ? truncateBytes(String(source.attribution), 32) : null,
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
function ts_of(ts) {
|
|
873
|
+
return { wallMs: ts.wallMs, monotonicMs: ts.monotonicMs, cdpSeconds: ts.cdpSeconds };
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
function pickTiming(timing) {
|
|
877
|
+
const out = {};
|
|
878
|
+
for (const key of Object.keys(emptyTiming())) {
|
|
879
|
+
const value = timing[key];
|
|
880
|
+
out[key] = Number.isFinite(value) && value >= 0 ? value : null;
|
|
881
|
+
}
|
|
882
|
+
return out;
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
/** 事件的 correlation contentHash 索引数据(normalizeEvent 会剥掉,store 单独保留)。 */
|
|
886
|
+
export function correlationContentHashes(input, hmacKey) {
|
|
887
|
+
const list = input && Array.isArray(input.correlationIds) ? input.correlationIds : [];
|
|
888
|
+
return list.map((item) => {
|
|
889
|
+
if (!item) return null;
|
|
890
|
+
if (item.contentHash) return String(item.contentHash);
|
|
891
|
+
if (item.value === undefined || item.value === null || item.value === '***') return null;
|
|
892
|
+
return hmacHex(hmacKey, String(item.value), { full: true });
|
|
893
|
+
}).filter(Boolean);
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/* ------------------------------------------------------------------ */
|
|
897
|
+
/* 存储(§4.2 / §4.3 + R1-2 / R1-10 / R1-15 / R1-16) */
|
|
898
|
+
/* ------------------------------------------------------------------ */
|
|
899
|
+
|
|
900
|
+
export function emptyCounters() {
|
|
901
|
+
return {
|
|
902
|
+
events: 0, http: 0, ws: 0, sse: 0, markers: 0,
|
|
903
|
+
failures: 0, httpErrors: 0, redirects: 0,
|
|
904
|
+
bodies: 0, bodiesUnavailable: 0, bodyEmpty: 0, bytes: 0,
|
|
905
|
+
evicted: 0, dropped: 0, bodyEvicted: 0, truncated: 0, wsFrames: 0, subscribers: 0,
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/** 归属字段的字符预算(id 截断而非猜测)。 */
|
|
910
|
+
const ATTRIBUTION_BYTES = 128;
|
|
911
|
+
|
|
912
|
+
function normalizeAttributionValue(value) {
|
|
913
|
+
if (value === undefined || value === null || value === '') return null;
|
|
914
|
+
const text = typeof value === 'string' ? value : (typeof value === 'number' && Number.isFinite(value) ? String(value) : null);
|
|
915
|
+
if (text === null) return null;
|
|
916
|
+
return truncateBytes(text, ATTRIBUTION_BYTES) || null;
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/**
|
|
920
|
+
* TOOL-P1-04 会话归属:`{scopeId, runtimeId, tabId}`。缺失字段一律 `null`;不从 cdpSessionId/
|
|
921
|
+
* targetId 反推 tabId(不猜)。构造器给了 `scopeId` 时它是已知事实,作为 attribution.scopeId 回传。
|
|
922
|
+
*/
|
|
923
|
+
function normalizeAttribution(input, scopeId = null) {
|
|
924
|
+
const out = { scopeId: normalizeAttributionValue(scopeId), runtimeId: null, tabId: null };
|
|
925
|
+
if (input && typeof input === 'object' && !Array.isArray(input)) {
|
|
926
|
+
for (const key of ['scopeId', 'runtimeId', 'tabId']) {
|
|
927
|
+
if (Object.prototype.hasOwnProperty.call(input, key)) out[key] = normalizeAttributionValue(input[key]);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
return out;
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
/** 只读投影:给 `#sessionView` / `status()` / `evidenceBlock` 共用,保证三处形状一致。 */
|
|
934
|
+
function attributionView(store) {
|
|
935
|
+
const source = store && store.attribution ? store.attribution : null;
|
|
936
|
+
if (source) return { scopeId: source.scopeId ?? null, runtimeId: source.runtimeId ?? null, tabId: source.tabId ?? null };
|
|
937
|
+
const scopeId = store && store.scopeId !== undefined && store.scopeId !== null ? normalizeAttributionValue(store.scopeId) : null;
|
|
938
|
+
return { scopeId, runtimeId: null, tabId: null };
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
export class NetworkStore {
|
|
942
|
+
constructor({ scopeId = null, now = () => Date.now(), monotonic, attribution = null } = {}) {
|
|
943
|
+
this.scopeId = scopeId;
|
|
944
|
+
this.attribution = normalizeAttribution(attribution, scopeId);
|
|
945
|
+
this.now = typeof now === 'function' ? now : () => Date.now();
|
|
946
|
+
this.monotonic = typeof monotonic === 'function' ? monotonic : () => Number(process.hrtime.bigint() / 1000n) / 1000;
|
|
947
|
+
this.config = normalizeSessionConfig(null);
|
|
948
|
+
this.state = null;
|
|
949
|
+
this.session = null;
|
|
950
|
+
this.sessions = [];
|
|
951
|
+
this.preSession = [];
|
|
952
|
+
this.seq = 0;
|
|
953
|
+
this.events = [];
|
|
954
|
+
this.chains = new Map();
|
|
955
|
+
this.hops = new Map();
|
|
956
|
+
this.bodies = new Map();
|
|
957
|
+
/** TOOL-P1-04:读不到 body 时的原因记录(与 `bodies` 分开,避免污染导出/计数/配额口径)。 */
|
|
958
|
+
this.bodyFailures = new Map();
|
|
959
|
+
this.headers = new Map();
|
|
960
|
+
this.bodyBytes = 0;
|
|
961
|
+
this.headerBytes = 0;
|
|
962
|
+
this.eventBytes = 0;
|
|
963
|
+
this.evictedSeqs = [];
|
|
964
|
+
this.dropRanges = [];
|
|
965
|
+
this.steps = new Map();
|
|
966
|
+
this.links = new Map();
|
|
967
|
+
this.artifacts = new Map();
|
|
968
|
+
this.subscriptions = new Map();
|
|
969
|
+
this.correlationIndex = new Map();
|
|
970
|
+
this.corrHashes = new Map();
|
|
971
|
+
this.anchors = new Map();
|
|
972
|
+
this.droppedByReason = Object.create(null);
|
|
973
|
+
this.counters = emptyCounters();
|
|
974
|
+
this.issues = [];
|
|
975
|
+
this.cdpDisconnected = false;
|
|
976
|
+
this.hmacKey = randomBytes(16).toString('hex');
|
|
977
|
+
this.everStarted = false;
|
|
978
|
+
this.sessionSeq = 0;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
/* ---------------- 时间锚点(R1-11) ---------------- */
|
|
982
|
+
|
|
983
|
+
/** 用 target 首次 `requestWillBeSent.wallTime` 锚点把 CDP 秒换算成墙钟毫秒。 */
|
|
984
|
+
setAnchor(targetId, cdpSeconds, wallMs) {
|
|
985
|
+
if (targetId === null || targetId === undefined || !Number.isFinite(cdpSeconds)) return;
|
|
986
|
+
if (this.anchors.has(targetId)) return;
|
|
987
|
+
this.anchors.set(targetId, { cdpSeconds, wallMs: Number.isFinite(wallMs) ? wallMs : this.now() });
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
wallMsFor(targetId, cdpSeconds) {
|
|
991
|
+
const anchor = this.anchors.get(targetId);
|
|
992
|
+
if (anchor && Number.isFinite(cdpSeconds)) return Math.round(anchor.wallMs + (cdpSeconds - anchor.cdpSeconds) * 1000);
|
|
993
|
+
if (anchor && Number.isFinite(anchor.wallMs)) return Math.round(anchor.wallMs);
|
|
994
|
+
return this.now();
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
/* ---------------- 会话 ---------------- */
|
|
998
|
+
|
|
999
|
+
start({ name = 'default', config = null } = {}) {
|
|
1000
|
+
const sessionName = truncateBytes(String(name ?? 'default'), 64) || 'default';
|
|
1001
|
+
if (this.state === 'running' && this.session) {
|
|
1002
|
+
if (this.session.name === sessionName) return { changed: false, session: this.#sessionView() };
|
|
1003
|
+
throw new BrowserError('NET_SESSION_ACTIVE', '另一个采集会话正在运行', { running: this.session.name, requested: sessionName });
|
|
1004
|
+
}
|
|
1005
|
+
this.config = normalizeSessionConfig(config);
|
|
1006
|
+
this.hmacKey = randomBytes(16).toString('hex');
|
|
1007
|
+
this.#beginSession('running', sessionName);
|
|
1008
|
+
// §3.4: events seen while no session was running live in the 200-entry candidate buffer and are
|
|
1009
|
+
// promoted on start with `preSession:true` (the new session still numbers its sequence from 1).
|
|
1010
|
+
this.sessionSeq = 0;
|
|
1011
|
+
const pending = this.preSession.splice(0, this.preSession.length);
|
|
1012
|
+
this.everStarted = true;
|
|
1013
|
+
for (const partial of pending) this.#append({ ...partial, preSession: true });
|
|
1014
|
+
return { changed: true, session: this.#sessionView() };
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
#beginSession(state, name, { source = null } = {}) {
|
|
1018
|
+
if (this.session) {
|
|
1019
|
+
this.session.state = 'stopped';
|
|
1020
|
+
this.session.stoppedAt = this.session.stoppedAt ?? this.now();
|
|
1021
|
+
this.session.retained = false;
|
|
1022
|
+
this.sessions.unshift({
|
|
1023
|
+
session: { ...this.session, counters: { ...this.counters } },
|
|
1024
|
+
retained: false,
|
|
1025
|
+
});
|
|
1026
|
+
while (this.sessions.length > NET_LIMITS.sessionsRetained) this.sessions.pop();
|
|
1027
|
+
}
|
|
1028
|
+
this.#clearData();
|
|
1029
|
+
this.state = state;
|
|
1030
|
+
this.session = {
|
|
1031
|
+
id: 'net-' + randomBytes(4).toString('hex'),
|
|
1032
|
+
name,
|
|
1033
|
+
state,
|
|
1034
|
+
startedAt: this.now(),
|
|
1035
|
+
stoppedAt: null,
|
|
1036
|
+
retained: true,
|
|
1037
|
+
source,
|
|
1038
|
+
config: { ...this.config },
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
#clearData() {
|
|
1043
|
+
this.seq = 0;
|
|
1044
|
+
this.events = [];
|
|
1045
|
+
this.chains.clear();
|
|
1046
|
+
this.hops.clear();
|
|
1047
|
+
this.bodies.clear();
|
|
1048
|
+
this.bodyFailures.clear();
|
|
1049
|
+
this.headers.clear();
|
|
1050
|
+
this.bodyBytes = 0;
|
|
1051
|
+
this.headerBytes = 0;
|
|
1052
|
+
this.eventBytes = 0;
|
|
1053
|
+
this.evictedSeqs = [];
|
|
1054
|
+
this.dropRanges = [];
|
|
1055
|
+
this.steps.clear();
|
|
1056
|
+
this.links.clear();
|
|
1057
|
+
this.correlationIndex.clear();
|
|
1058
|
+
this.corrHashes.clear();
|
|
1059
|
+
this.anchors.clear();
|
|
1060
|
+
this.droppedByReason = Object.create(null);
|
|
1061
|
+
this.counters = emptyCounters();
|
|
1062
|
+
this.issues = [];
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
stop() {
|
|
1066
|
+
if (this.state === 'running' && this.session) {
|
|
1067
|
+
this.state = 'stopped';
|
|
1068
|
+
this.session.state = 'stopped';
|
|
1069
|
+
this.session.stoppedAt = this.now();
|
|
1070
|
+
}
|
|
1071
|
+
// R1-9:会话关闭清零 HMAC 密钥(已写入的 hash 不再可逆用于关联)
|
|
1072
|
+
this.hmacKey = randomBytes(16).toString('hex');
|
|
1073
|
+
return { changed: false, session: this.session ? this.#sessionView() : null };
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
/** `reset`:清数据并关闭本 scope 全部订阅(R1-2),不删磁盘证据。 */
|
|
1077
|
+
reset() {
|
|
1078
|
+
const closed = this.subscriptions.size;
|
|
1079
|
+
this.subscriptions.clear();
|
|
1080
|
+
this.#clearData();
|
|
1081
|
+
return { reset: true, subscriptionsClosed: closed, session: this.session ? this.#sessionView() : null };
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
#sessionView() {
|
|
1085
|
+
return {
|
|
1086
|
+
id: this.session.id,
|
|
1087
|
+
name: this.session.name,
|
|
1088
|
+
state: this.state,
|
|
1089
|
+
// TOOL-P1-04:会话归属(缺失为 null,不从 cdpSessionId/targetId 反推 tabId)。
|
|
1090
|
+
attribution: attributionView(this),
|
|
1091
|
+
startedAt: this.session.startedAt,
|
|
1092
|
+
stoppedAt: this.session.stoppedAt,
|
|
1093
|
+
config: { ...this.config },
|
|
1094
|
+
counters: {
|
|
1095
|
+
...this.counters,
|
|
1096
|
+
// `seq` counts the events THIS session itself produced; promoted candidates keep their
|
|
1097
|
+
// stored seq but are not part of the new session's own numbering (they are reported by
|
|
1098
|
+
// `preSession`). `highWater` is the honest highest stored seq.
|
|
1099
|
+
seq: this.sessionSeq,
|
|
1100
|
+
highWater: this.seq,
|
|
1101
|
+
subscribers: this.subscriptions.size,
|
|
1102
|
+
// Promoted candidate events (§3.4) are counted here as well as in `events`.
|
|
1103
|
+
preSession: this.events.filter((event) => event.preSession === true).length,
|
|
1104
|
+
},
|
|
1105
|
+
integrity: this.integrity(),
|
|
1106
|
+
};
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
/**
|
|
1110
|
+
* TOOL-P1-04:更新会话归属 `{scopeId,runtimeId,tabId}`。
|
|
1111
|
+
* - `setAttribution(null)` 重置为 `{scopeId:构造器 scopeId, runtimeId:null, tabId:null}`;
|
|
1112
|
+
* - 传对象时只覆盖显式给出的字段(显式 `null`/`''` 清空该字段),缺失字段保持不变——供切 tab
|
|
1113
|
+
* 时只更新 `tabId`;任何字段都不推测。
|
|
1114
|
+
*/
|
|
1115
|
+
setAttribution(input = null) {
|
|
1116
|
+
if (input === null || input === undefined) {
|
|
1117
|
+
this.attribution = normalizeAttribution(null, this.scopeId);
|
|
1118
|
+
return { attribution: attributionView(this) };
|
|
1119
|
+
}
|
|
1120
|
+
const current = attributionView(this);
|
|
1121
|
+
const next = { ...current };
|
|
1122
|
+
if (typeof input === 'object' && !Array.isArray(input)) {
|
|
1123
|
+
for (const key of ['scopeId', 'runtimeId', 'tabId']) {
|
|
1124
|
+
if (Object.prototype.hasOwnProperty.call(input, key)) next[key] = normalizeAttributionValue(input[key]);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
this.attribution = next;
|
|
1128
|
+
return { attribution: attributionView(this) };
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
status() {
|
|
1132
|
+
return {
|
|
1133
|
+
// TOOL-P1-04:会话归属与当前会话视图同源,status.session.attribution 与顶层一致。
|
|
1134
|
+
attribution: attributionView(this),
|
|
1135
|
+
session: this.session ? this.#sessionView() : null,
|
|
1136
|
+
sessions: this.sessions.map((entry) => ({
|
|
1137
|
+
id: entry.session.id, name: entry.session.name, state: entry.session.state,
|
|
1138
|
+
startedAt: entry.session.startedAt, stoppedAt: entry.session.stoppedAt,
|
|
1139
|
+
counters: { ...entry.session.counters }, retained: entry.retained === true,
|
|
1140
|
+
})),
|
|
1141
|
+
limits: limitsView(),
|
|
1142
|
+
subscriptions: this.subscriptions.size,
|
|
1143
|
+
};
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
get running() { return this.state === 'running'; }
|
|
1147
|
+
get highWater() { return this.seq; }
|
|
1148
|
+
get sessionId() { return this.session ? this.session.id : null; }
|
|
1149
|
+
|
|
1150
|
+
/* ---------------- 摄入 ---------------- */
|
|
1151
|
+
|
|
1152
|
+
dropEvent(reason, count = 1) {
|
|
1153
|
+
this.counters.dropped += count;
|
|
1154
|
+
this.droppedByReason[reason] = (this.droppedByReason[reason] || 0) + count;
|
|
1155
|
+
this.dropRanges.push({ from: this.seq + 1, to: this.seq + count, count, reason });
|
|
1156
|
+
if (this.dropRanges.length > 256) this.dropRanges.shift();
|
|
1157
|
+
if (!this.issues.includes('events-dropped')) this.issues.push('events-dropped');
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
noteBodyUnavailable(count = 1) {
|
|
1161
|
+
this.counters.bodiesUnavailable += count;
|
|
1162
|
+
if (!this.issues.includes('body-unavailable')) this.issues.push('body-unavailable');
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
noteBodyEmpty(count = 1) { this.counters.bodyEmpty += count; }
|
|
1166
|
+
|
|
1167
|
+
add(input) {
|
|
1168
|
+
if (this.state !== 'running') {
|
|
1169
|
+
if (this.state === 'snapshot') return null;
|
|
1170
|
+
this.preSession.push(input);
|
|
1171
|
+
while (this.preSession.length > NET_LIMITS.preSessionEvents) this.preSession.shift();
|
|
1172
|
+
return null;
|
|
1173
|
+
}
|
|
1174
|
+
const kind = input && input.kind ? input.kind : 'http';
|
|
1175
|
+
if (kind === 'ws') {
|
|
1176
|
+
if (!this.config.captureWebSocket) { this.dropEvent('capture-disabled:websocket'); return null; }
|
|
1177
|
+
if (input.phase === 'ws-send' || input.phase === 'ws-receive') {
|
|
1178
|
+
if (this.counters.wsFrames >= this.config.maxWsFrames) { this.dropEvent('ws-frame-quota'); return null; }
|
|
1179
|
+
this.counters.wsFrames += 1;
|
|
1180
|
+
}
|
|
1181
|
+
} else if (kind === 'sse') {
|
|
1182
|
+
if (!this.config.captureSse) { this.dropEvent('capture-disabled:sse'); return null; }
|
|
1183
|
+
}
|
|
1184
|
+
return this.#append(input);
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
/** 重放窗口(control.replay 设置):同 URL 事件在窗口内带 `replay` 标记(C40)。 */
|
|
1188
|
+
replayWindow = null;
|
|
1189
|
+
|
|
1190
|
+
#append(rawInput) {
|
|
1191
|
+
if (rawInput && rawInput.replay === undefined && this.replayWindow
|
|
1192
|
+
&& Date.now() <= this.replayWindow.until && rawInput.url
|
|
1193
|
+
&& (String(rawInput.url) === String(this.replayWindow.url || '')
|
|
1194
|
+
|| String(rawInput.url).startsWith(String(this.replayWindow.prefix || '\u0000')))) {
|
|
1195
|
+
rawInput = { ...rawInput, replay: { by: this.replayWindow.by || 'control.replay', sinceMs: this.replayWindow.at, basis: 'observed' } };
|
|
1196
|
+
}
|
|
1197
|
+
const isPreSession = rawInput && rawInput.preSession === true;
|
|
1198
|
+
this.seq += 1;
|
|
1199
|
+
// Only this session's own events advance `sessionSeq` (C34 restart reads counters.seq).
|
|
1200
|
+
if (!isPreSession) this.sessionSeq = (this.sessionSeq || 0) + 1;
|
|
1201
|
+
const hashes = correlationContentHashes(rawInput, this.hmacKey);
|
|
1202
|
+
const event = normalizeEvent(rawInput, {
|
|
1203
|
+
seq: this.seq,
|
|
1204
|
+
sessionId: this.session ? this.session.id : null,
|
|
1205
|
+
wallMs: this.now(),
|
|
1206
|
+
monotonicMs: this.monotonic(),
|
|
1207
|
+
preSession: rawInput && rawInput.preSession === true,
|
|
1208
|
+
hmacKey: this.hmacKey,
|
|
1209
|
+
});
|
|
1210
|
+
this.events.push(event);
|
|
1211
|
+
this.eventBytes += estimateEventBytes(event);
|
|
1212
|
+
this.counters.events += 1;
|
|
1213
|
+
if (event.kind === 'http') this.counters.http += 1;
|
|
1214
|
+
if (event.failed) this.counters.failures += 1;
|
|
1215
|
+
if (Number.isInteger(event.status) && event.status >= 400) this.counters.httpErrors += 1;
|
|
1216
|
+
if (event.phase === 'redirect') this.counters.redirects += 1;
|
|
1217
|
+
else if (event.kind === 'ws') this.counters.ws += 1;
|
|
1218
|
+
else if (event.kind === 'sse') this.counters.sse += 1;
|
|
1219
|
+
else this.counters.markers += 1;
|
|
1220
|
+
if (hashes.length) this.corrHashes.set(event.seq, hashes);
|
|
1221
|
+
for (const hash of hashes) {
|
|
1222
|
+
const list = this.correlationIndex.get(hash) || [];
|
|
1223
|
+
list.push(event.seq);
|
|
1224
|
+
this.correlationIndex.set(hash, list);
|
|
1225
|
+
}
|
|
1226
|
+
this.#noteChain(event);
|
|
1227
|
+
this.#enforceQuota();
|
|
1228
|
+
if (event.preSession && !this.issues.includes('import-partial')) this.issues.push('import-partial');
|
|
1229
|
+
return event;
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
/** §4.2 淘汰:先 body(bodyEvicted),仍超预算再淘汰最旧事件(evicted)。 */
|
|
1233
|
+
#enforceQuota() {
|
|
1234
|
+
while (this.events.length > this.config.maxEvents) this.#evictOldestEvent('max-events');
|
|
1235
|
+
while (this.accountedBytes() > this.config.maxTotalBytes && this.bodies.size > 0) {
|
|
1236
|
+
const oldestKey = this.bodies.keys().next().value;
|
|
1237
|
+
const record = this.bodies.get(oldestKey);
|
|
1238
|
+
this.bodies.delete(oldestKey);
|
|
1239
|
+
this.bodyBytes -= record.buffer.length;
|
|
1240
|
+
this.counters.bodyEvicted += 1;
|
|
1241
|
+
if (!this.issues.includes('bodies-evicted')) this.issues.push('bodies-evicted');
|
|
1242
|
+
// TOOL-P1-04:淘汰后 detail 仍能回答"为什么读不到"——reasonCode 是 `cdp-evicted`(本地
|
|
1243
|
+
// 配额淘汰),而不是笼统的 unavailable。原因记录不占字节、不改事件保留。
|
|
1244
|
+
this.#rememberBodyFailure(oldestKey, { ...record, reasonCode: 'cdp-evicted', reasonDetail: null });
|
|
1245
|
+
}
|
|
1246
|
+
while (this.accountedBytes() > this.config.maxTotalBytes && this.events.length > 1) this.#evictOldestEvent('max-total-bytes');
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
#evictOldestEvent(reason) {
|
|
1250
|
+
const evicted = this.events.shift();
|
|
1251
|
+
if (!evicted) return;
|
|
1252
|
+
this.evictedSeqs.push(evicted.seq);
|
|
1253
|
+
if (this.evictedSeqs.length > 4096) this.evictedSeqs.shift();
|
|
1254
|
+
this.counters.evicted += 1;
|
|
1255
|
+
this.eventBytes -= estimateEventBytes(evicted);
|
|
1256
|
+
if (this.eventBytes < 0) this.eventBytes = 0;
|
|
1257
|
+
this.#dropFromChains(evicted);
|
|
1258
|
+
if (!this.issues.includes('events-evicted')) this.issues.push('events-evicted');
|
|
1259
|
+
void reason;
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
#noteChain(event) {
|
|
1263
|
+
if (!event.requestId) return;
|
|
1264
|
+
const key = requestKey(event);
|
|
1265
|
+
const chain = this.chains.get(key) || {
|
|
1266
|
+
key, requestId: event.requestId, hopId: Number.isInteger(event.hopId) ? event.hopId : 0,
|
|
1267
|
+
targetId: event.targetId, cdpSessionId: event.cdpSessionId,
|
|
1268
|
+
seqs: [], hops: [], firstSeq: event.seq, lastSeq: event.seq,
|
|
1269
|
+
method: null, url: null, status: null, failed: false, kind: event.kind,
|
|
1270
|
+
requestSeq: null, responseSeq: null, finishedSeq: null, endState: null,
|
|
1271
|
+
};
|
|
1272
|
+
chain.seqs.push(event.seq);
|
|
1273
|
+
chain.lastSeq = event.seq;
|
|
1274
|
+
if (event.method) chain.method = event.method;
|
|
1275
|
+
if (event.url) chain.url = event.url;
|
|
1276
|
+
if (Number.isInteger(event.status)) chain.status = event.status;
|
|
1277
|
+
if (event.failed) { chain.failed = true; chain.endState = 'failed'; }
|
|
1278
|
+
if (event.phase === 'request') chain.requestSeq = event.seq;
|
|
1279
|
+
if (event.phase === 'response') { chain.responseSeq = event.seq; chain.endState = 'response'; }
|
|
1280
|
+
if (event.phase === 'finished') { chain.finishedSeq = event.seq; chain.endState = 'finished'; }
|
|
1281
|
+
if (event.redirect) {
|
|
1282
|
+
chain.hops.push({
|
|
1283
|
+
hopId: chain.hopId, requestId: event.requestId, url: event.redirect.to,
|
|
1284
|
+
status: event.redirect.status, fromUrl: event.redirect.from, seq: event.seq,
|
|
1285
|
+
});
|
|
1286
|
+
if (chain.hops.length > NET_LIMITS.redirectChain) chain.hops = chain.hops.slice(-NET_LIMITS.redirectChain);
|
|
1287
|
+
}
|
|
1288
|
+
this.chains.set(key, chain);
|
|
1289
|
+
const hopList = this.hops.get(event.requestId) || [];
|
|
1290
|
+
if (!hopList.includes(key)) hopList.push(key);
|
|
1291
|
+
this.hops.set(event.requestId, hopList);
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
#dropFromChains(event) {
|
|
1295
|
+
if (!event.requestId) return;
|
|
1296
|
+
const key = requestKey(event);
|
|
1297
|
+
const chain = this.chains.get(key);
|
|
1298
|
+
if (!chain) return;
|
|
1299
|
+
chain.seqs = chain.seqs.filter((seq) => seq !== event.seq);
|
|
1300
|
+
if (chain.seqs.length === 0) {
|
|
1301
|
+
this.chains.delete(key);
|
|
1302
|
+
const hopList = (this.hops.get(event.requestId) || []).filter((item) => item !== key);
|
|
1303
|
+
if (hopList.length === 0) this.hops.delete(event.requestId); else this.hops.set(event.requestId, hopList);
|
|
1304
|
+
} else {
|
|
1305
|
+
chain.firstSeq = chain.seqs[0];
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
/** R1-15 近似字节口径(公开、固定)。 */
|
|
1310
|
+
estimateBytes() {
|
|
1311
|
+
return {
|
|
1312
|
+
events: this.eventBytes,
|
|
1313
|
+
headers: this.headerBytes,
|
|
1314
|
+
bodies: this.bodyBytes,
|
|
1315
|
+
pins: this.pinnedBytes(),
|
|
1316
|
+
preSession: this.preSession.length,
|
|
1317
|
+
formula: 'events(JSON utf8) + headers(JSON utf8) + bodies(raw) + pinnedEvents(count) + preSessionEvents(count)',
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
accountedBytes() {
|
|
1322
|
+
return this.eventBytes + this.headerBytes + this.bodyBytes + this.pinnedBytes() + this.preSession.length;
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
pinnedBytes() {
|
|
1326
|
+
let pinned = 0;
|
|
1327
|
+
for (const subscription of this.subscriptions.values()) {
|
|
1328
|
+
pinned += Math.min(Math.max(0, this.seq - subscription.ackedSeq), NET_LIMITS.subscriptionPin);
|
|
1329
|
+
}
|
|
1330
|
+
return pinned;
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
/** 淘汰后重建链与关联索引(导入 / 恢复用)。 */
|
|
1334
|
+
rebuildChains() {
|
|
1335
|
+
this.chains.clear();
|
|
1336
|
+
this.hops.clear();
|
|
1337
|
+
this.correlationIndex.clear();
|
|
1338
|
+
this.corrHashes.clear();
|
|
1339
|
+
this.eventBytes = 0;
|
|
1340
|
+
for (const event of this.events) {
|
|
1341
|
+
this.eventBytes += estimateEventBytes(event);
|
|
1342
|
+
this.#noteChain(event);
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
/* ---------------- headers / bodies ---------------- */
|
|
1347
|
+
|
|
1348
|
+
#key(kind, { targetId = null, cdpSessionId = null, requestId = null, hopId = null } = {}) {
|
|
1349
|
+
return [targetId ?? '', cdpSessionId ?? '', requestId ?? '', Number.isInteger(hopId) ? hopId : 0, kind].join('\u0000');
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
setHeaders({ targetId = null, cdpSessionId = null, requestId = null, hopId = null, kind = 'response', headers = {} } = {}) {
|
|
1353
|
+
if (!requestId) return null;
|
|
1354
|
+
const safe = sanitizeHeaders(headers);
|
|
1355
|
+
const key = this.#key(kind, { targetId, cdpSessionId, requestId, hopId });
|
|
1356
|
+
const previous = this.headers.get(key);
|
|
1357
|
+
if (previous) this.headerBytes -= previous.bytes;
|
|
1358
|
+
const bytes = Buffer.byteLength(JSON.stringify(safe.headers), 'utf8');
|
|
1359
|
+
this.headers.set(key, { ...safe, bytes, at: this.now() });
|
|
1360
|
+
this.headerBytes += bytes;
|
|
1361
|
+
return { names: Object.keys(safe.headers).length, applied: safe.applied };
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
readHeaders({ targetId = null, cdpSessionId = null, requestId = null, hopId = null, kind = 'response' } = {}) {
|
|
1365
|
+
const record = this.headers.get(this.#key(kind, { targetId, cdpSessionId, requestId, hopId }));
|
|
1366
|
+
return record
|
|
1367
|
+
? { headers: record.headers, applied: record.applied, truncated: record.truncated, at: record.at }
|
|
1368
|
+
: { headers: {}, applied: [], truncated: false, at: null };
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
/**
|
|
1372
|
+
* body 三态(R1-11):`captured`(有内容)/`empty`(合法空体,如 HEAD/204/304/GET 无 postData)/
|
|
1373
|
+
* `unavailable`(失败、缓存、重定向中途、已淘汰)。`payloadOmitted` 表示二进制或无法安全解析。
|
|
1374
|
+
*
|
|
1375
|
+
* TOOL-P1-04:`unavailable` 必须带稳定原因码(`reasonCode`,见 `NET_BODY_REASON_CODES`)与可选
|
|
1376
|
+
* 脱敏细节(`reasonDetail` ≤160 字节)。原因记录与真实 body 分表存储,不进入 body 配额/计数/
|
|
1377
|
+
* JSONL/HAR 口径;读取仍是纯只读(不补抓、不重试、不伪造)。
|
|
1378
|
+
*/
|
|
1379
|
+
addBody({ targetId = null, cdpSessionId = null, requestId = null, hopId = null, kind = 'response', state = 'captured', data = '', base64Encoded = false, contentType = null, redacted = 'none', payloadOmitted = false, reasonCode = null, reasonDetail = null } = {}) {
|
|
1380
|
+
if (!requestId) return null;
|
|
1381
|
+
const key = this.#key(kind, { targetId, cdpSessionId, requestId, hopId });
|
|
1382
|
+
if (state === 'unavailable') {
|
|
1383
|
+
this.noteBodyUnavailable();
|
|
1384
|
+
const code = normalizeBodyReasonCode(reasonCode);
|
|
1385
|
+
const detail = normalizeBodyReasonDetail(reasonDetail, this.config.maskRules);
|
|
1386
|
+
// The latest attempt is authoritative: an earlier captured/empty record for the same request
|
|
1387
|
+
// key must not outlive a later proven failure (otherwise the reason would be silently lost).
|
|
1388
|
+
const previous = this.bodies.get(key);
|
|
1389
|
+
if (previous) {
|
|
1390
|
+
this.bodies.delete(key);
|
|
1391
|
+
this.bodyBytes -= previous.buffer.length;
|
|
1392
|
+
}
|
|
1393
|
+
this.#rememberBodyFailure(key, {
|
|
1394
|
+
requestId, targetId, cdpSessionId, hopId, kind, reasonCode: code, reasonDetail: detail,
|
|
1395
|
+
});
|
|
1396
|
+
return { state: 'unavailable', bytes: null, reasonCode: code, reasonDetail: detail };
|
|
1397
|
+
}
|
|
1398
|
+
if (state === 'empty') {
|
|
1399
|
+
this.noteBodyEmpty();
|
|
1400
|
+
this.bodyFailures.delete(key);
|
|
1401
|
+
this.bodies.set(key, {
|
|
1402
|
+
requestId: String(requestId), targetId, cdpSessionId, hopId, kind, state: 'empty',
|
|
1403
|
+
buffer: Buffer.alloc(0), originalBytes: 0, truncated: false, base64Encoded: false,
|
|
1404
|
+
contentType, redacted: 'none', payloadOmitted: false, storedAt: this.now(),
|
|
1405
|
+
});
|
|
1406
|
+
if (this.state === 'running') this.counters.bodies += 1;
|
|
1407
|
+
return { state: 'empty', bytes: 0 };
|
|
1408
|
+
}
|
|
1409
|
+
if (!this.config.captureBodies) return null;
|
|
1410
|
+
let buffer = Buffer.isBuffer(data) ? data : Buffer.from(String(data ?? ''), base64Encoded ? 'base64' : 'utf8');
|
|
1411
|
+
const originalBytes = buffer.length;
|
|
1412
|
+
let truncated = false;
|
|
1413
|
+
if (buffer.length > this.config.maxBodyBytes) {
|
|
1414
|
+
buffer = buffer.subarray(0, this.config.maxBodyBytes);
|
|
1415
|
+
truncated = true;
|
|
1416
|
+
if (this.state === 'running') this.counters.truncated += 1;
|
|
1417
|
+
if (!this.issues.includes('bodies-truncated')) this.issues.push('bodies-truncated');
|
|
1418
|
+
}
|
|
1419
|
+
const previous = this.bodies.get(key);
|
|
1420
|
+
if (previous) this.bodyBytes -= previous.buffer.length;
|
|
1421
|
+
this.bodies.delete(key);
|
|
1422
|
+
this.bodyFailures.delete(key);
|
|
1423
|
+
this.bodies.set(key, {
|
|
1424
|
+
requestId: String(requestId), targetId, cdpSessionId, hopId, kind, state: 'captured',
|
|
1425
|
+
buffer, originalBytes, truncated, base64Encoded: base64Encoded === true, contentType,
|
|
1426
|
+
redacted: redacted === 'fields' ? 'fields' : redacted === 'omitted' ? 'omitted' : 'none',
|
|
1427
|
+
payloadOmitted: payloadOmitted === true, storedAt: this.now(),
|
|
1428
|
+
});
|
|
1429
|
+
this.bodyBytes += buffer.length;
|
|
1430
|
+
// `stop` freezes every session counter: a body recorded for a non-running session must not
|
|
1431
|
+
// move `bodies`/`bytes` (events buffered while stopped are counted by `preSession`).
|
|
1432
|
+
if (this.state === 'running') this.counters.bodies += 1;
|
|
1433
|
+
this.#enforceQuota();
|
|
1434
|
+
if (this.state === 'running') this.counters.bytes = this.bodyBytes;
|
|
1435
|
+
return { state: 'captured', bytes: buffer.length, originalBytes, truncated, payloadOmitted: payloadOmitted === true };
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
bodyRecord({ targetId = null, cdpSessionId = null, requestId = null, hopId = null, kind = 'response' } = {}) {
|
|
1439
|
+
const key = this.#key(kind, { targetId, cdpSessionId, requestId, hopId });
|
|
1440
|
+
return this.bodies.get(key) || this.bodyFailures.get(key) || null;
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
/** 只读(不补抓、不启动 CDP,§2.3 / R1-11)。不可得时回放原因码,仍不读取页面/网络。 */
|
|
1444
|
+
readBody(options = {}, { maxBytes = NET_LIMITS.detailBodyBytes } = {}) {
|
|
1445
|
+
const record = this.bodyRecord(options);
|
|
1446
|
+
if (!record) return null;
|
|
1447
|
+
if (record.state === 'unavailable') {
|
|
1448
|
+
return {
|
|
1449
|
+
kind: record.kind,
|
|
1450
|
+
state: 'unavailable',
|
|
1451
|
+
available: false,
|
|
1452
|
+
encoding: null,
|
|
1453
|
+
bytes: null,
|
|
1454
|
+
originalBytes: null,
|
|
1455
|
+
truncated: null,
|
|
1456
|
+
base64Encoded: false,
|
|
1457
|
+
redacted: null,
|
|
1458
|
+
payloadOmitted: null,
|
|
1459
|
+
contentType: null,
|
|
1460
|
+
storedAt: record.storedAt,
|
|
1461
|
+
data: null,
|
|
1462
|
+
reason: 'NET_BODY_UNAVAILABLE',
|
|
1463
|
+
reasonCode: record.reasonCode || 'cdp-unknown',
|
|
1464
|
+
reasonDetail: record.reasonDetail ?? null,
|
|
1465
|
+
};
|
|
1466
|
+
}
|
|
1467
|
+
const limit = clampInt(maxBytes, NET_LIMITS.detailBodyMinBytes, NET_LIMITS.detailBodyBytes);
|
|
1468
|
+
const slice = record.buffer.subarray(0, limit);
|
|
1469
|
+
return {
|
|
1470
|
+
kind: record.kind,
|
|
1471
|
+
state: record.state,
|
|
1472
|
+
available: true,
|
|
1473
|
+
encoding: record.base64Encoded ? 'base64' : 'utf8',
|
|
1474
|
+
bytes: slice.length,
|
|
1475
|
+
originalBytes: record.originalBytes,
|
|
1476
|
+
truncated: record.truncated || slice.length < record.buffer.length,
|
|
1477
|
+
base64Encoded: record.base64Encoded,
|
|
1478
|
+
redacted: record.redacted,
|
|
1479
|
+
payloadOmitted: record.payloadOmitted,
|
|
1480
|
+
contentType: record.contentType,
|
|
1481
|
+
storedAt: record.storedAt,
|
|
1482
|
+
data: record.payloadOmitted ? '' : (record.base64Encoded ? slice.toString('base64') : slice.toString('utf8')),
|
|
1483
|
+
reason: null,
|
|
1484
|
+
reasonCode: null,
|
|
1485
|
+
reasonDetail: null,
|
|
1486
|
+
};
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
/**
|
|
1490
|
+
* 三态 + 原因:`captured`/`empty` 保持原语义(`reason:null`);`unavailable` 保留兼容字段
|
|
1491
|
+
* `reason:"NET_BODY_UNAVAILABLE"`,并给出 `reasonCode`/`reasonDetail`。
|
|
1492
|
+
* `captureBodies:false` 且无任何记录时明确 `reasonCode:"not-captured"`(不是 CDP 错误);
|
|
1493
|
+
* 采集中但没有任何失败记录的缺失(如导入的历史事件)保持 `reasonCode:null`——不猜测。
|
|
1494
|
+
*/
|
|
1495
|
+
bodyState(event) {
|
|
1496
|
+
const options = { targetId: event.targetId, cdpSessionId: event.cdpSessionId, requestId: event.requestId, hopId: event.hopId };
|
|
1497
|
+
const fallbackCode = this.config.captureBodies === true ? null : 'not-captured';
|
|
1498
|
+
const state = {};
|
|
1499
|
+
for (const kind of ['request', 'response']) {
|
|
1500
|
+
const record = this.bodyRecord({ ...options, kind });
|
|
1501
|
+
if (!record) {
|
|
1502
|
+
state[kind] = {
|
|
1503
|
+
state: 'unavailable', available: false, bytes: null, originalBytes: null,
|
|
1504
|
+
truncated: null, payloadOmitted: null,
|
|
1505
|
+
reason: 'NET_BODY_UNAVAILABLE', reasonCode: fallbackCode, reasonDetail: null,
|
|
1506
|
+
};
|
|
1507
|
+
} else if (record.state === 'unavailable') {
|
|
1508
|
+
state[kind] = {
|
|
1509
|
+
state: 'unavailable', available: false, bytes: null, originalBytes: null,
|
|
1510
|
+
truncated: null, payloadOmitted: null,
|
|
1511
|
+
reason: 'NET_BODY_UNAVAILABLE',
|
|
1512
|
+
reasonCode: record.reasonCode || 'cdp-unknown',
|
|
1513
|
+
reasonDetail: record.reasonDetail ?? null,
|
|
1514
|
+
};
|
|
1515
|
+
} else {
|
|
1516
|
+
state[kind] = {
|
|
1517
|
+
state: record.state, available: true, bytes: record.buffer.length,
|
|
1518
|
+
originalBytes: record.originalBytes, truncated: record.truncated,
|
|
1519
|
+
payloadOmitted: record.payloadOmitted,
|
|
1520
|
+
reason: null, reasonCode: null, reasonDetail: null,
|
|
1521
|
+
};
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
return state;
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
/**
|
|
1528
|
+
* TOOL-P1-04:记录一条 body 不可得原因。独立于 `bodies` 的 FIFO 表(容量 = 2 × 本次会话
|
|
1529
|
+
* maxEvents,每个事件最多 request/response 两条),只保留原因码/脱敏细节,不占 body 配额、
|
|
1530
|
+
* 不进入 JSONL/HAR、不影响 integrity 的 body 计数口径。
|
|
1531
|
+
*/
|
|
1532
|
+
#rememberBodyFailure(key, record) {
|
|
1533
|
+
this.bodyFailures.set(key, {
|
|
1534
|
+
requestId: String(record.requestId),
|
|
1535
|
+
targetId: record.targetId ?? null,
|
|
1536
|
+
cdpSessionId: record.cdpSessionId ?? null,
|
|
1537
|
+
hopId: record.hopId ?? null,
|
|
1538
|
+
kind: record.kind || 'response',
|
|
1539
|
+
state: 'unavailable',
|
|
1540
|
+
reasonCode: normalizeBodyReasonCode(record.reasonCode),
|
|
1541
|
+
reasonDetail: record.reasonDetail ?? null,
|
|
1542
|
+
storedAt: this.now(),
|
|
1543
|
+
});
|
|
1544
|
+
const maxEvents = Number.isInteger(this.config.maxEvents) ? this.config.maxEvents : NET_LIMITS.maxEvents;
|
|
1545
|
+
const capacity = Math.max(64, 2 * maxEvents);
|
|
1546
|
+
while (this.bodyFailures.size > capacity) this.bodyFailures.delete(this.bodyFailures.keys().next().value);
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
/* ---------------- markers / steps / links ---------------- */
|
|
1550
|
+
|
|
1551
|
+
mark({ kind = 'tool', text = null, tool = null, actionId = null, stepId = null, labels = null, revision = null, url = null, title = null, fromSeq = null } = {}) {
|
|
1552
|
+
return this.add({
|
|
1553
|
+
kind: 'marker', phase: 'mark',
|
|
1554
|
+
mark: { kind, text, tool, actionId, stepId, labels, revision, url, title, wallMs: this.now(), fromSeq, basis: 'temporal' },
|
|
1555
|
+
stepId,
|
|
1556
|
+
});
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
beginStep({ name = null, labels = null, window = null, businessStatusPath = null, objectRules = null, correlationRules = null, stepId = null } = {}) {
|
|
1560
|
+
if (name !== null && [...this.steps.values()].some((step) => step.name === String(name) && step.open)) {
|
|
1561
|
+
throw new BrowserError('NET_RULE_CONFLICT', '同名步骤已在运行: ' + String(name), { name: String(name) });
|
|
1562
|
+
}
|
|
1563
|
+
if (stepId && this.steps.has(String(stepId))) {
|
|
1564
|
+
throw new BrowserError('NET_RULE_CONFLICT', 'stepId 不可复用: ' + String(stepId), { stepId: String(stepId) });
|
|
1565
|
+
}
|
|
1566
|
+
if (this.steps.size >= NET_LIMITS.steps) {
|
|
1567
|
+
throw new BrowserError('NET_QUOTA_EXCEEDED', '步骤数超出上限 ' + NET_LIMITS.steps, { max: NET_LIMITS.steps });
|
|
1568
|
+
}
|
|
1569
|
+
const id = stepId ? truncateBytes(String(stepId), 64) : 'step-' + (this.steps.size + 1);
|
|
1570
|
+
const fromWallMs = window && Number.isFinite(window.fromWallMs) ? window.fromWallMs : this.now();
|
|
1571
|
+
const step = {
|
|
1572
|
+
stepId: id,
|
|
1573
|
+
name: name === null ? null : truncateBytes(String(name), 128),
|
|
1574
|
+
labels: labels && typeof labels === 'object'
|
|
1575
|
+
? Object.fromEntries(Object.entries(labels).slice(0, NET_LIMITS.stepLabels).map(([key, value]) => [truncateBytes(key, 64), truncateBytes(String(value), 128)]))
|
|
1576
|
+
: null,
|
|
1577
|
+
businessStatusPath: businessStatusPath ? truncateBytes(String(businessStatusPath), 256) : this.config.businessStatusPath,
|
|
1578
|
+
objectRules: objectRules ? validateObjectRules(objectRules) : [],
|
|
1579
|
+
correlationRules: correlationRules ? validateCorrelationRules(correlationRules) : [...DEFAULT_CORRELATION_RULES],
|
|
1580
|
+
window: { fromWallMs, toWallMs: window && Number.isFinite(window.toWallMs) ? window.toWallMs : null },
|
|
1581
|
+
fromSeq: this.seq + 1,
|
|
1582
|
+
toSeq: null,
|
|
1583
|
+
open: true,
|
|
1584
|
+
createdAt: this.now(),
|
|
1585
|
+
};
|
|
1586
|
+
this.steps.set(id, step);
|
|
1587
|
+
this.add({ kind: 'marker', phase: 'step-begin', mark: { kind: 'note', stepId: id, text: step.name, wallMs: this.now() }, stepId: id });
|
|
1588
|
+
return step;
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
endStep({ stepId, window = null } = {}) {
|
|
1592
|
+
const step = this.steps.get(String(stepId));
|
|
1593
|
+
if (!step) throw new BrowserError('NET_EVENT_NOT_FOUND', '步骤不存在: ' + String(stepId), { stepId: String(stepId) });
|
|
1594
|
+
if (step.open) {
|
|
1595
|
+
step.open = false;
|
|
1596
|
+
step.toSeq = this.seq;
|
|
1597
|
+
step.window.toWallMs = window && Number.isFinite(window.toWallMs) ? window.toWallMs : this.now();
|
|
1598
|
+
this.add({ kind: 'marker', phase: 'step-end', mark: { kind: 'note', stepId: step.stepId, text: step.name, wallMs: this.now() }, stepId: step.stepId });
|
|
1599
|
+
}
|
|
1600
|
+
return step;
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
/**
|
|
1604
|
+
* 显式链接(R1-1 / §4.1「事件入店后不改写」):链接只写进 `links` 索引,**不修改已入库事件**;
|
|
1605
|
+
* `stepIds`/`evidenceIds` 在查询期按索引投影。幂等。
|
|
1606
|
+
*/
|
|
1607
|
+
link({ seq = null, requestId = null, stepId = null, evidenceId = null } = {}) {
|
|
1608
|
+
const event = resolveEvent(this, { seq, requestId });
|
|
1609
|
+
if (stepId && !this.steps.has(String(stepId))) {
|
|
1610
|
+
throw new BrowserError('NET_EVENT_NOT_FOUND', '步骤不存在: ' + String(stepId), { stepId: String(stepId) });
|
|
1611
|
+
}
|
|
1612
|
+
const list = this.links.get(event.seq) || [];
|
|
1613
|
+
const normalizedEvidence = evidenceId ? truncateBytes(String(evidenceId), 128) : null;
|
|
1614
|
+
const normalizedStep = stepId ? String(stepId) : null;
|
|
1615
|
+
if (!list.some((item) => item.evidenceId === normalizedEvidence && item.stepId === normalizedStep)) {
|
|
1616
|
+
list.push({ evidenceId: normalizedEvidence, stepId: normalizedStep, linkedAt: this.now() });
|
|
1617
|
+
this.links.set(event.seq, list);
|
|
1618
|
+
}
|
|
1619
|
+
return { seq: event.seq, ...this.linkProjection(event) };
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
/** 查询期投影:事件自带的 stepIds/evidenceIds + 链接索引。 */
|
|
1623
|
+
linkProjection(event) {
|
|
1624
|
+
const linked = this.links.get(event.seq) || [];
|
|
1625
|
+
const stepIds = [...event.stepIds];
|
|
1626
|
+
const evidenceIds = [...event.evidenceIds];
|
|
1627
|
+
for (const item of linked) {
|
|
1628
|
+
if (item.stepId && !stepIds.includes(item.stepId)) stepIds.push(item.stepId);
|
|
1629
|
+
if (item.evidenceId && !evidenceIds.includes(item.evidenceId)) evidenceIds.push(item.evidenceId);
|
|
1630
|
+
}
|
|
1631
|
+
return { stepIds, evidenceIds };
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
/* ---------------- window / integrity ---------------- */
|
|
1635
|
+
|
|
1636
|
+
/**
|
|
1637
|
+
* §3.3 / R1-16 截图时间窗:`fromSeq` = `[startMs-250, captureEndMs+50]` 内最早现存事件,
|
|
1638
|
+
* `toSeq` = 截图开始时的会话 highWater(不含之后新产生的事件),`nearest` 可为 null。
|
|
1639
|
+
*/
|
|
1640
|
+
window({ frameTimeMs, captureEndMs = null, highWater = null } = {}) {
|
|
1641
|
+
const start = Number.isFinite(frameTimeMs) ? frameTimeMs : this.now();
|
|
1642
|
+
const end = Number.isFinite(captureEndMs) ? captureEndMs : start;
|
|
1643
|
+
const limit = Number.isInteger(highWater) ? highWater : this.seq;
|
|
1644
|
+
const candidates = this.events.filter((event) => event.seq <= limit
|
|
1645
|
+
&& event.ts.wallMs >= start - NET_LIMITS.networkWindowMs
|
|
1646
|
+
&& event.ts.wallMs <= end + NET_LIMITS.networkWindowTailMs);
|
|
1647
|
+
const picked = candidates.slice(0, NET_LIMITS.networkWindowMax);
|
|
1648
|
+
let nearest = null;
|
|
1649
|
+
let nearestAny = null;
|
|
1650
|
+
for (const event of this.events) {
|
|
1651
|
+
if (event.seq > limit) continue;
|
|
1652
|
+
const delta = Math.abs(event.ts.wallMs - start);
|
|
1653
|
+
if (nearestAny === null || delta < nearestAny.delta) nearestAny = { event, delta };
|
|
1654
|
+
// Prefer a real request/response event; a marker carries no url/status to correlate with.
|
|
1655
|
+
if (!event.requestId) continue;
|
|
1656
|
+
if (nearest === null || delta < nearest.delta) nearest = { event, delta };
|
|
1657
|
+
}
|
|
1658
|
+
if (nearest === null) nearest = nearestAny;
|
|
1659
|
+
return {
|
|
1660
|
+
sessionId: this.session ? this.session.id : null,
|
|
1661
|
+
fromSeq: picked.length ? picked[0].seq : null,
|
|
1662
|
+
toSeq: this.session ? limit : null,
|
|
1663
|
+
frameTimeMs: start,
|
|
1664
|
+
captureEndMs: end,
|
|
1665
|
+
nearest: nearest ? {
|
|
1666
|
+
seq: nearest.event.seq,
|
|
1667
|
+
requestId: nearest.event.requestId,
|
|
1668
|
+
hopId: nearest.event.hopId,
|
|
1669
|
+
url: nearest.event.url,
|
|
1670
|
+
method: nearest.event.method,
|
|
1671
|
+
status: nearest.event.status,
|
|
1672
|
+
deltaMs: nearest.event.ts.wallMs - start,
|
|
1673
|
+
} : null,
|
|
1674
|
+
count: picked.length,
|
|
1675
|
+
};
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
integrity() {
|
|
1679
|
+
const gaps = [];
|
|
1680
|
+
if (this.counters.evicted > 0 && this.events.length > 0) {
|
|
1681
|
+
gaps.push({ from: this.events[0].seq - this.counters.evicted, to: this.events[0].seq - 1, count: this.counters.evicted, reason: 'evicted' });
|
|
1682
|
+
}
|
|
1683
|
+
for (const range of this.dropRanges) gaps.push({ ...range });
|
|
1684
|
+
const issues = [...new Set(this.issues)];
|
|
1685
|
+
if (this.counters.dropped > 0 && !issues.includes('events-dropped')) issues.push('events-dropped');
|
|
1686
|
+
if (this.counters.evicted > 0 && !issues.includes('events-evicted')) issues.push('events-evicted');
|
|
1687
|
+
if (this.counters.bodyEvicted > 0 && !issues.includes('bodies-evicted')) issues.push('bodies-evicted');
|
|
1688
|
+
if (this.counters.truncated > 0 && !issues.includes('bodies-truncated')) issues.push('bodies-truncated');
|
|
1689
|
+
if (!this.config.captureWebSocket) issues.push('capture-disabled:websocket');
|
|
1690
|
+
if (!this.config.captureSse) issues.push('capture-disabled:sse');
|
|
1691
|
+
if (!this.config.captureWorkers) issues.push('capture-disabled:workers');
|
|
1692
|
+
if (this.cdpDisconnected) issues.push('cdp-disconnected');
|
|
1693
|
+
const overflow = [...this.subscriptions.values()].some((subscription) => subscription.droppedPinned > 0);
|
|
1694
|
+
if (overflow) issues.push('subscriber-overflow');
|
|
1695
|
+
const unique = [...new Set(issues)].filter((issue) => NET_ISSUES.includes(issue));
|
|
1696
|
+
const complete = this.counters.dropped === 0 && this.counters.evicted === 0
|
|
1697
|
+
&& this.counters.truncated === 0 && this.counters.bodyEvicted === 0 && gaps.length === 0
|
|
1698
|
+
&& !unique.includes('cdp-disconnected') && !unique.includes('import-partial');
|
|
1699
|
+
return {
|
|
1700
|
+
complete,
|
|
1701
|
+
dropped: this.counters.dropped,
|
|
1702
|
+
evicted: this.counters.evicted,
|
|
1703
|
+
truncated: this.counters.truncated,
|
|
1704
|
+
bodyEvicted: this.counters.bodyEvicted,
|
|
1705
|
+
gaps,
|
|
1706
|
+
issues: unique,
|
|
1707
|
+
firstSeq: this.events.length ? this.events[0].seq : null,
|
|
1708
|
+
lastSeq: this.events.length ? this.events[this.events.length - 1].seq : null,
|
|
1709
|
+
sessionId: this.session ? this.session.id : null,
|
|
1710
|
+
state: this.state,
|
|
1711
|
+
estimate: this.estimateBytes(),
|
|
1712
|
+
};
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
export function limitsView() {
|
|
1717
|
+
return {
|
|
1718
|
+
maxEvents: NET_LIMITS.maxEvents,
|
|
1719
|
+
maxBodyBytes: NET_LIMITS.maxBodyBytes,
|
|
1720
|
+
maxTotalBytes: NET_LIMITS.maxTotalBytes,
|
|
1721
|
+
maxWsFrames: NET_LIMITS.maxWsFrames,
|
|
1722
|
+
subscriptionMax: NET_LIMITS.subscriptionMax,
|
|
1723
|
+
subscriptionPin: NET_LIMITS.subscriptionPin,
|
|
1724
|
+
eventPageLimit: NET_LIMITS.eventPageLimit,
|
|
1725
|
+
holdTimeoutMs: NET_LIMITS.holdTimeoutMs,
|
|
1726
|
+
rules: NET_LIMITS.rules,
|
|
1727
|
+
held: NET_LIMITS.held,
|
|
1728
|
+
steps: NET_LIMITS.steps,
|
|
1729
|
+
preSessionEvents: NET_LIMITS.preSessionEvents,
|
|
1730
|
+
importDataBytes: NET_LIMITS.importDataBytes,
|
|
1731
|
+
importFileBytes: NET_LIMITS.importFileBytes,
|
|
1732
|
+
redirectChain: NET_LIMITS.redirectChain,
|
|
1733
|
+
// §5.1 fixed bounds — every limit has to be discoverable (§8.7).
|
|
1734
|
+
headerCount: NET_LIMITS.headerCount,
|
|
1735
|
+
headerValueBytes: NET_LIMITS.headerValueBytes,
|
|
1736
|
+
wsPayloadBytes: NET_LIMITS.wsPayloadBytes,
|
|
1737
|
+
sseDataBytes: NET_LIMITS.sseDataBytes,
|
|
1738
|
+
detailBodyBytes: NET_LIMITS.detailBodyBytes,
|
|
1739
|
+
detailBodyMinBytes: NET_LIMITS.detailBodyMinBytes,
|
|
1740
|
+
searchTextBytes: NET_LIMITS.searchTextBytes,
|
|
1741
|
+
initiatorStack: NET_LIMITS.initiatorStack,
|
|
1742
|
+
groupsLimit: NET_LIMITS.groupsLimit,
|
|
1743
|
+
correlationRules: NET_LIMITS.correlationRules,
|
|
1744
|
+
objectRules: NET_LIMITS.objectRules,
|
|
1745
|
+
retryWindowMs: NET_LIMITS.retryWindowMs,
|
|
1746
|
+
pollWindowMs: NET_LIMITS.pollWindowMs,
|
|
1747
|
+
// 控制类数值上限:`limits.network.<name>` 直接可读(C38),不再只藏在子对象里。
|
|
1748
|
+
throttleLimits: { latencyMsMax: 60000, downloadKbpsMax: 1000000, uploadKbpsMax: 1000000, unit: 'Kbps = 1024 bit/s' },
|
|
1749
|
+
latencyMsMax: 60000,
|
|
1750
|
+
downloadKbpsMax: 1000000,
|
|
1751
|
+
uploadKbpsMax: 1000000,
|
|
1752
|
+
holdLimits: { maxHeld: NET_LIMITS.held, timeoutMs: NET_LIMITS.holdTimeoutMs },
|
|
1753
|
+
ruleLimits: { max: NET_LIMITS.rules, kinds: [...NET_RULE_KINDS] },
|
|
1754
|
+
};
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
/* ------------------------------------------------------------------ */
|
|
1758
|
+
/* 查询:events(§2.2)/ detail(§2.3) */
|
|
1759
|
+
/* ------------------------------------------------------------------ */
|
|
1760
|
+
|
|
1761
|
+
const FILTER_KEYS = Object.freeze([
|
|
1762
|
+
'method', 'status', 'statusClass', 'resourceType', 'urlIncludes', 'failed', 'kind', 'phase',
|
|
1763
|
+
'targetId', 'stepId', 'sinceMs', 'untilMs', 'minDurationMs', 'maxDurationMs',
|
|
1764
|
+
]);
|
|
1765
|
+
|
|
1766
|
+
function asArray(value) {
|
|
1767
|
+
if (value === undefined || value === null) return null;
|
|
1768
|
+
return Array.isArray(value) ? value : [value];
|
|
1769
|
+
}
|
|
1770
|
+
|
|
1771
|
+
function matchScalar(fieldValue, wanted, normalizer = (value) => String(value).toLowerCase()) {
|
|
1772
|
+
const list = asArray(wanted);
|
|
1773
|
+
if (list === null) return true;
|
|
1774
|
+
if (fieldValue === null || fieldValue === undefined) return false;
|
|
1775
|
+
return list.some((item) => normalizer(fieldValue) === normalizer(item));
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
/**
|
|
1779
|
+
* R1-1:`stepId` 是查询期按窗口派生的归属(`stepIds` 是显式链接)。
|
|
1780
|
+
*
|
|
1781
|
+
* A step window has two bounds and membership needs both: the wall-clock window
|
|
1782
|
+
* (`fromWallMs`/`toWallMs`) and the sequence window (`fromSeq`/`toSeq`). Wall clock alone is not
|
|
1783
|
+
* enough — an event that was already in the store when the step opened can carry a *later*
|
|
1784
|
+
* `ts.wallMs` (its response/finish phase is stamped after `begin-step` raced past it), and a
|
|
1785
|
+
* wall-only test then counts pre-step traffic as in-step. The seq bounds are exact, so they decide.
|
|
1786
|
+
*/
|
|
1787
|
+
export function stepMembership(store, event, step) {
|
|
1788
|
+
if (!step) return false;
|
|
1789
|
+
const fromWall = step.window?.fromWallMs;
|
|
1790
|
+
const toWall = step.window?.toWallMs === null || step.window?.toWallMs === undefined
|
|
1791
|
+
? Number.POSITIVE_INFINITY
|
|
1792
|
+
: step.window.toWallMs;
|
|
1793
|
+
const wallOk = Number.isFinite(fromWall) ? event.ts.wallMs >= fromWall && event.ts.wallMs <= toWall : true;
|
|
1794
|
+
const fromSeq = Number.isInteger(step.fromSeq) ? step.fromSeq : null;
|
|
1795
|
+
const toSeq = Number.isInteger(step.toSeq) ? step.toSeq : null;
|
|
1796
|
+
const seqOk = (fromSeq === null || event.seq >= fromSeq) && (toSeq === null || event.seq <= toSeq);
|
|
1797
|
+
return wallOk && seqOk;
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
export function derivedStepId(store, event) {
|
|
1801
|
+
if (event.stepId) return event.stepId;
|
|
1802
|
+
if (event.stepIds.length) return event.stepIds[0];
|
|
1803
|
+
for (const step of store.steps.values()) {
|
|
1804
|
+
if (stepMembership(store, event, step)) return step.stepId;
|
|
1805
|
+
}
|
|
1806
|
+
return null;
|
|
1807
|
+
}
|
|
1808
|
+
|
|
1809
|
+
export function inStepWindow(store, event, stepId) {
|
|
1810
|
+
if (event.stepId === stepId || event.stepIds.includes(String(stepId))) return true;
|
|
1811
|
+
return stepMembership(store, event, store.steps.get(String(stepId)));
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
export function matchesFilter(store, event, filter) {
|
|
1815
|
+
if (!filter) return true;
|
|
1816
|
+
if (!matchScalar(event.method, filter.method)) return false;
|
|
1817
|
+
if (!matchScalar(event.status, filter.status, (value) => String(value))) return false;
|
|
1818
|
+
if (!matchScalar(statusClass(event.status), filter.statusClass)) return false;
|
|
1819
|
+
if (!matchScalar(event.resourceType, filter.resourceType)) return false;
|
|
1820
|
+
if (!matchScalar(event.kind, filter.kind)) return false;
|
|
1821
|
+
if (!matchScalar(event.phase, filter.phase)) return false;
|
|
1822
|
+
if (!matchScalar(event.targetId, filter.targetId, (value) => String(value))) return false;
|
|
1823
|
+
if (filter.urlIncludes !== undefined && filter.urlIncludes !== null) {
|
|
1824
|
+
const needles = asArray(filter.urlIncludes).map((item) => String(item).toLowerCase());
|
|
1825
|
+
const haystack = String(event.url || '').toLowerCase();
|
|
1826
|
+
if (!needles.some((needle) => haystack.includes(needle))) return false;
|
|
1827
|
+
}
|
|
1828
|
+
if (filter.failed !== undefined && filter.failed !== null && (event.failed === true) !== (filter.failed === true)) return false;
|
|
1829
|
+
if (filter.stepId !== undefined && filter.stepId !== null) {
|
|
1830
|
+
const ids = asArray(filter.stepId).map((item) => String(item));
|
|
1831
|
+
if (!ids.some((id) => inStepWindow(store, event, id))) return false;
|
|
1832
|
+
}
|
|
1833
|
+
if (Number.isFinite(filter.sinceMs) && event.ts.wallMs < filter.sinceMs) return false;
|
|
1834
|
+
if (Number.isFinite(filter.untilMs) && event.ts.wallMs > filter.untilMs) return false;
|
|
1835
|
+
const duration = durationOf(store, event);
|
|
1836
|
+
if (Number.isFinite(filter.minDurationMs) && (duration === null || duration < filter.minDurationMs)) return false;
|
|
1837
|
+
if (Number.isFinite(filter.maxDurationMs) && (duration === null || duration > filter.maxDurationMs)) return false;
|
|
1838
|
+
return true;
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
export function durationOf(store, event) {
|
|
1842
|
+
if (event.timing && Number.isFinite(event.timing.totalMs)) return event.timing.totalMs;
|
|
1843
|
+
if (!event.requestId) return null;
|
|
1844
|
+
const chain = store.chains.get(requestKey(event));
|
|
1845
|
+
if (!chain || !Number.isInteger(chain.requestSeq) || !Number.isInteger(chain.finishedSeq)) return null;
|
|
1846
|
+
const first = store.events.find((item) => item.seq === chain.requestSeq);
|
|
1847
|
+
const last = store.events.find((item) => item.seq === chain.finishedSeq);
|
|
1848
|
+
if (!first || !last) return null;
|
|
1849
|
+
return Math.max(0, Math.round((last.ts.monotonicMs - first.ts.monotonicMs) * 1000) / 1000);
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1852
|
+
function searchableText(store, event, fields) {
|
|
1853
|
+
const wanted = fields && fields.length ? fields : ['url', 'body', 'headers', 'ws', 'sse'];
|
|
1854
|
+
const parts = [];
|
|
1855
|
+
if (wanted.includes('url')) parts.push(event.url, event.documentURL);
|
|
1856
|
+
if (wanted.includes('headers')) {
|
|
1857
|
+
for (const kind of ['request', 'response']) {
|
|
1858
|
+
const record = store.readHeaders({ targetId: event.targetId, cdpSessionId: event.cdpSessionId, requestId: event.requestId, hopId: event.hopId, kind });
|
|
1859
|
+
for (const [name, value] of Object.entries(record.headers)) parts.push(name + ': ' + value);
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
if (wanted.includes('body')) {
|
|
1863
|
+
for (const kind of ['request', 'response']) {
|
|
1864
|
+
const body = store.readBody({ targetId: event.targetId, cdpSessionId: event.cdpSessionId, requestId: event.requestId, hopId: event.hopId, kind });
|
|
1865
|
+
if (body && body.state !== 'unavailable' && !body.payloadOmitted) parts.push(body.data);
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
if (wanted.includes('ws') && event.ws && !event.ws.payloadOmitted) parts.push(event.ws.payload);
|
|
1869
|
+
if (wanted.includes('sse') && event.sse && !event.sse.payloadOmitted) parts.push(event.sse.data);
|
|
1870
|
+
return parts.filter((part) => part !== null && part !== undefined).join('\n');
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
export function matchesSearch(store, event, search) {
|
|
1874
|
+
if (!search) return null;
|
|
1875
|
+
const text = search.text;
|
|
1876
|
+
if (text === undefined || text === null || text === '') return null;
|
|
1877
|
+
const fields = Array.isArray(search.in) && search.in.length ? search.in : ['url', 'body', 'headers', 'ws', 'sse'];
|
|
1878
|
+
const caseSensitive = search.caseSensitive === true;
|
|
1879
|
+
const needle = caseSensitive ? String(text) : String(text).toLowerCase();
|
|
1880
|
+
const haystack = searchableText(store, event, fields);
|
|
1881
|
+
if (haystack === '') return { matched: false };
|
|
1882
|
+
const target = caseSensitive ? haystack : haystack.toLowerCase();
|
|
1883
|
+
const index = target.indexOf(needle);
|
|
1884
|
+
if (index === -1) return { matched: false };
|
|
1885
|
+
const start = Math.max(0, index - 40);
|
|
1886
|
+
return {
|
|
1887
|
+
matched: true,
|
|
1888
|
+
match: { field: fields[0], preview: truncateBytes(redactText(haystack.slice(start, start + 120)), 120) },
|
|
1889
|
+
};
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
/** §2.2 summary 投影(`failed` 布尔;`stepId` 派生;不内联 headers/body)。 */
|
|
1893
|
+
export function projectSummary(store, event) {
|
|
1894
|
+
return {
|
|
1895
|
+
seq: event.seq,
|
|
1896
|
+
ts: { wallMs: event.ts.wallMs, monotonicMs: event.ts.monotonicMs },
|
|
1897
|
+
wallMs: event.ts.wallMs,
|
|
1898
|
+
kind: event.kind,
|
|
1899
|
+
phase: event.phase,
|
|
1900
|
+
requestId: event.requestId,
|
|
1901
|
+
hopId: event.hopId,
|
|
1902
|
+
method: event.method,
|
|
1903
|
+
url: event.url,
|
|
1904
|
+
status: event.status,
|
|
1905
|
+
statusClass: statusClass(event.status),
|
|
1906
|
+
statusText: event.statusText,
|
|
1907
|
+
resourceType: event.resourceType,
|
|
1908
|
+
mimeType: event.mimeType,
|
|
1909
|
+
durationMs: durationOf(store, event),
|
|
1910
|
+
size: { encoded: event.sizes.encoded, decoded: event.sizes.decoded },
|
|
1911
|
+
failed: event.failed,
|
|
1912
|
+
errorText: event.errorText,
|
|
1913
|
+
targetId: event.targetId,
|
|
1914
|
+
frameId: event.frameId,
|
|
1915
|
+
loaderId: event.loaderId,
|
|
1916
|
+
navId: event.navId,
|
|
1917
|
+
documentURL: event.documentURL,
|
|
1918
|
+
attribution: event.attribution,
|
|
1919
|
+
stepId: derivedStepId(store, event),
|
|
1920
|
+
// Flat aliases: `totalMs` (request duration) and the marker kind/tool/text at top level.
|
|
1921
|
+
totalMs: durationOf(store, event),
|
|
1922
|
+
...(event.redirect ? { redirect: { from: event.redirect.from, to: event.redirect.to, status: event.redirect.status } } : {}),
|
|
1923
|
+
...(event.replay ? { replay: event.replay } : {}),
|
|
1924
|
+
...(event.mark ? {
|
|
1925
|
+
mark: event.mark,
|
|
1926
|
+
markKind: event.mark.kind || null,
|
|
1927
|
+
markTool: event.mark.tool || null,
|
|
1928
|
+
markText: event.mark.text || null,
|
|
1929
|
+
} : {}),
|
|
1930
|
+
};
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
function groupOf(event, key, store) {
|
|
1934
|
+
switch (key) {
|
|
1935
|
+
case 'url': return event.url;
|
|
1936
|
+
case 'method': return event.method;
|
|
1937
|
+
case 'status': return event.status === null ? null : String(event.status);
|
|
1938
|
+
case 'statusClass': return statusClass(event.status);
|
|
1939
|
+
case 'resourceType': return event.resourceType;
|
|
1940
|
+
case 'kind': return event.kind;
|
|
1941
|
+
case 'step': return derivedStepId(store, event);
|
|
1942
|
+
case 'host': {
|
|
1943
|
+
if (!event.url) return null;
|
|
1944
|
+
try { return new URL(event.url).host; } catch { return null; }
|
|
1945
|
+
}
|
|
1946
|
+
default: return null;
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
|
|
1950
|
+
/** §2.2 / §5.3 聚合。 */
|
|
1951
|
+
export function aggregateEvents(store, events, groupBy = 'url') {
|
|
1952
|
+
const keys = (Array.isArray(groupBy) ? groupBy : [groupBy]).filter(Boolean);
|
|
1953
|
+
if (keys.length === 0) throw new BrowserError('NET_INVALID_ARGUMENT', 'groupBy 至少需要一个字段');
|
|
1954
|
+
for (const key of keys) {
|
|
1955
|
+
if (!NET_GROUP_KEYS.includes(key)) throw new BrowserError('NET_INVALID_ARGUMENT', 'groupBy 不支持 ' + String(key), { field: 'groupBy', allowed: [...NET_GROUP_KEYS] });
|
|
1956
|
+
}
|
|
1957
|
+
const groups = new Map();
|
|
1958
|
+
for (const event of events) {
|
|
1959
|
+
if (!['http', 'ws', 'sse'].includes(event.kind)) continue;
|
|
1960
|
+
const values = keys.map((key) => groupOf(event, key, store));
|
|
1961
|
+
const id = JSON.stringify(values);
|
|
1962
|
+
let group = groups.get(id);
|
|
1963
|
+
if (!group) {
|
|
1964
|
+
group = {
|
|
1965
|
+
key: keys.length === 1 ? values[0] : Object.fromEntries(keys.map((key, index) => [key, values[index]])),
|
|
1966
|
+
count: 0, bytes: 0, failures: 0, statuses: {}, durations: [], seqs: [],
|
|
1967
|
+
};
|
|
1968
|
+
groups.set(id, group);
|
|
1969
|
+
}
|
|
1970
|
+
group.count += 1;
|
|
1971
|
+
if (event.sizes && Number.isInteger(event.sizes.encoded)) group.bytes += event.sizes.encoded;
|
|
1972
|
+
if (event.failed || (Number.isInteger(event.status) && event.status >= 400)) group.failures += 1;
|
|
1973
|
+
if (Number.isInteger(event.status)) group.statuses[String(event.status)] = (group.statuses[String(event.status)] || 0) + 1;
|
|
1974
|
+
const duration = durationOf(store, event);
|
|
1975
|
+
if (Number.isFinite(duration)) group.durations.push(duration);
|
|
1976
|
+
if (group.seqs.length < 50) group.seqs.push(event.seq);
|
|
1977
|
+
}
|
|
1978
|
+
const list = [...groups.values()].map((group) => {
|
|
1979
|
+
const sorted = [...group.durations].sort((left, right) => left - right);
|
|
1980
|
+
const sum = sorted.reduce((total, value) => total + value, 0);
|
|
1981
|
+
return {
|
|
1982
|
+
key: group.key,
|
|
1983
|
+
count: group.count,
|
|
1984
|
+
bytes: group.bytes,
|
|
1985
|
+
durationMs: {
|
|
1986
|
+
min: sorted.length ? sorted[0] : null,
|
|
1987
|
+
max: sorted.length ? sorted[sorted.length - 1] : null,
|
|
1988
|
+
avg: sorted.length ? Math.round((sum / sorted.length) * 1000) / 1000 : null,
|
|
1989
|
+
p50: percentile(sorted, 0.5),
|
|
1990
|
+
p95: percentile(sorted, 0.95),
|
|
1991
|
+
},
|
|
1992
|
+
failures: group.failures,
|
|
1993
|
+
statuses: group.statuses,
|
|
1994
|
+
seqs: group.seqs,
|
|
1995
|
+
};
|
|
1996
|
+
}).sort((left, right) => right.count - left.count);
|
|
1997
|
+
return { groups: list.slice(0, NET_LIMITS.groupsLimit), truncated: list.length > NET_LIMITS.groupsLimit, groupCount: list.length };
|
|
1998
|
+
}
|
|
1999
|
+
|
|
2000
|
+
function assertSession(store, sessionId) {
|
|
2001
|
+
if (sessionId === undefined || sessionId === null) return;
|
|
2002
|
+
const current = store.session ? store.session.id : null;
|
|
2003
|
+
if (String(sessionId) !== String(current)) {
|
|
2004
|
+
throw new BrowserError('NET_SESSION_NOT_FOUND', '网络会话不存在或不属于本 scope', { sessionId: String(sessionId), current });
|
|
2005
|
+
}
|
|
2006
|
+
}
|
|
2007
|
+
|
|
2008
|
+
/** §8.6 证据块。 */
|
|
2009
|
+
export function evidenceBlock(store, operation, extra = {}) {
|
|
2010
|
+
const integrity = store.integrity();
|
|
2011
|
+
const applied = [...new Set(store.events.slice(-200).flatMap((event) => event.redaction.applied))];
|
|
2012
|
+
const rules = [...new Set(store.events.slice(-200).flatMap((event) => event.redaction.rules))];
|
|
2013
|
+
return {
|
|
2014
|
+
version: NET_VERSION,
|
|
2015
|
+
operation,
|
|
2016
|
+
sessionId: store.session ? store.session.id : null,
|
|
2017
|
+
// TOOL-P1-04:证据块回传同一份归属投影(缺失为 null,不推断)。
|
|
2018
|
+
attribution: attributionView(store),
|
|
2019
|
+
fromSeq: Number.isInteger(extra.fromSeq) ? extra.fromSeq : (integrity.firstSeq === null ? 0 : integrity.firstSeq),
|
|
2020
|
+
toSeq: Number.isInteger(extra.toSeq) ? extra.toSeq : (integrity.lastSeq === null ? 0 : integrity.lastSeq),
|
|
2021
|
+
counters: { events: store.counters.events, bodies: store.counters.bodies, bytes: store.counters.bytes, ...(extra.counters || {}) },
|
|
2022
|
+
integrity: {
|
|
2023
|
+
complete: integrity.complete, dropped: integrity.dropped, evicted: integrity.evicted,
|
|
2024
|
+
truncated: integrity.truncated, bodyEvicted: integrity.bodyEvicted,
|
|
2025
|
+
},
|
|
2026
|
+
redaction: { applied, rules, body: store.config.captureBodies ? 'fields' : 'none' },
|
|
2027
|
+
truncated: extra.truncated === true,
|
|
2028
|
+
incomplete: [...new Set([...(extra.incomplete || []), ...integrity.issues.filter((issue) => ['cdp-disconnected', 'import-partial', 'workers-not-attributable'].includes(issue))])],
|
|
2029
|
+
};
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
/**
|
|
2033
|
+
* R1-22:retry / duplicate / polling 模式投影。
|
|
2034
|
+
* `{retry:[{groupKey,count,seqs}], duplicate:[…], polling:[{groupKey,count,intervalMs,firstSeq,lastSeq}]}`
|
|
2035
|
+
*/
|
|
2036
|
+
export function buildPatterns(events, retries = null) {
|
|
2037
|
+
const patterns = retries || detectRetries(events);
|
|
2038
|
+
return {
|
|
2039
|
+
retry: patterns.filter((item) => item.pattern === 'retry').map((item) => ({ groupKey: item.groupKey, count: item.count, seqs: item.seqs })),
|
|
2040
|
+
duplicate: patterns.filter((item) => item.pattern === 'duplicate').map((item) => ({ groupKey: item.groupKey, count: item.count, seqs: item.seqs })),
|
|
2041
|
+
polling: detectPolling(events),
|
|
2042
|
+
};
|
|
2043
|
+
}
|
|
2044
|
+
|
|
2045
|
+
/** 聚合总量(§2.2 aggregate.totals)。 */
|
|
2046
|
+
export function aggregatedTotals(events) {
|
|
2047
|
+
return {
|
|
2048
|
+
count: events.length,
|
|
2049
|
+
bytes: events.reduce((sum, event) => sum + (event.sizes && Number.isInteger(event.sizes.encoded) ? event.sizes.encoded : 0), 0),
|
|
2050
|
+
failures: events.filter((event) => event.failed || (Number.isInteger(event.status) && event.status >= 400)).length,
|
|
2051
|
+
};
|
|
2052
|
+
}
|
|
2053
|
+
|
|
2054
|
+
/** `browser_network_events` 执行体(只读,不启动浏览器,§2.2)。 */
|
|
2055
|
+
export function queryEvents(store, params = {}) {
|
|
2056
|
+
assertKnownKeys(params, ['sessionId', 'sinceSeq', 'untilSeq', 'cursor', 'limit', 'order', 'view', 'filter', 'search', 'groupBy', 'aggregate'], 'events');
|
|
2057
|
+
assertSession(store, params.sessionId);
|
|
2058
|
+
const view = params.view === undefined ? 'summary' : params.view;
|
|
2059
|
+
if (!NET_VIEWS.includes(view)) throw new BrowserError('NET_INVALID_ARGUMENT', 'view 不合法: ' + String(view), { field: 'view', allowed: [...NET_VIEWS] });
|
|
2060
|
+
const order = params.order === undefined ? 'asc' : params.order;
|
|
2061
|
+
if (!['asc', 'desc'].includes(order)) throw new BrowserError('NET_INVALID_ARGUMENT', 'order 必须是 asc 或 desc', { field: 'order' });
|
|
2062
|
+
const limit = params.limit === undefined ? NET_LIMITS.eventPageDefault : params.limit;
|
|
2063
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > NET_LIMITS.eventPageLimit) {
|
|
2064
|
+
throw new BrowserError('NET_INVALID_ARGUMENT', `limit 必须是 1–${NET_LIMITS.eventPageLimit} 的整数`, { field: 'limit', max: NET_LIMITS.eventPageLimit });
|
|
2065
|
+
}
|
|
2066
|
+
const filter = assertKnownKeys(params.filter, FILTER_KEYS, 'filter');
|
|
2067
|
+
const search = params.search === undefined || params.search === null
|
|
2068
|
+
? null
|
|
2069
|
+
: assertKnownKeys(params.search, ['text', 'in', 'caseSensitive'], 'search');
|
|
2070
|
+
if (search && search.in !== undefined) {
|
|
2071
|
+
if (!Array.isArray(search.in)) throw new BrowserError('NET_INVALID_ARGUMENT', 'search.in 必须是数组');
|
|
2072
|
+
for (const field of search.in) {
|
|
2073
|
+
if (!NET_SEARCH_FIELDS.includes(field)) throw new BrowserError('NET_INVALID_ARGUMENT', 'search.in 含未知字段 ' + String(field), { allowed: [...NET_SEARCH_FIELDS] });
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
if (params.aggregate !== undefined && params.aggregate !== null) {
|
|
2077
|
+
if (!Array.isArray(params.aggregate)) throw new BrowserError('NET_INVALID_ARGUMENT', 'aggregate 必须是数组');
|
|
2078
|
+
for (const metric of params.aggregate) {
|
|
2079
|
+
if (!NET_AGGREGATE_METRICS.includes(metric)) throw new BrowserError('NET_INVALID_ARGUMENT', 'aggregate 含未知指标 ' + String(metric), { allowed: [...NET_AGGREGATE_METRICS] });
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
const cursorSeq = decodeCursor(params.cursor);
|
|
2083
|
+
const requestedFrom = cursorSeq !== null ? cursorSeq : (Number.isInteger(params.sinceSeq) ? params.sinceSeq : 0);
|
|
2084
|
+
const untilSeq = Number.isInteger(params.untilSeq) ? params.untilSeq : null;
|
|
2085
|
+
const firstSeq = store.events.length ? store.events[0].seq : 0;
|
|
2086
|
+
const gaps = [];
|
|
2087
|
+
if (requestedFrom > 0 && store.events.length > 0 && requestedFrom < firstSeq - 1) {
|
|
2088
|
+
gaps.push({ from: requestedFrom + 1, to: firstSeq - 1, count: firstSeq - 1 - requestedFrom });
|
|
2089
|
+
}
|
|
2090
|
+
const matched = [];
|
|
2091
|
+
// Paging defaults to the NEWEST window: an unpaged query (`{filter, limit:50}`) must show recent
|
|
2092
|
+
// traffic, not the first 50 events of a long session. `order:'asc'` keeps forward paging for
|
|
2093
|
+
// explicit cursor walks; `sinceSeq`/`cursor` still work in both directions.
|
|
2094
|
+
const forward = order === 'asc' || requestedFrom > 0 || cursorSeq !== null;
|
|
2095
|
+
const source = forward ? store.events : [...store.events].reverse();
|
|
2096
|
+
for (const event of source) {
|
|
2097
|
+
if (event.seq <= requestedFrom) continue;
|
|
2098
|
+
if (untilSeq !== null && event.seq > untilSeq) continue;
|
|
2099
|
+
if (!matchesFilter(store, event, filter)) continue;
|
|
2100
|
+
const searchResult = matchesSearch(store, event, search);
|
|
2101
|
+
if (searchResult && !searchResult.matched) continue;
|
|
2102
|
+
matched.push({ event, match: searchResult && searchResult.match ? searchResult.match : null });
|
|
2103
|
+
}
|
|
2104
|
+
const truncated = matched.length > limit;
|
|
2105
|
+
const page = matched.slice(0, limit);
|
|
2106
|
+
const ordered = forward ? page : [...page].sort((a, b) => a.event.seq - b.event.seq);
|
|
2107
|
+
const lastSeq = page.length ? page[page.length - 1].event.seq : null;
|
|
2108
|
+
const seqsOfPage = page.map((item) => item.event.seq);
|
|
2109
|
+
const base = {
|
|
2110
|
+
ok: true,
|
|
2111
|
+
sessionId: store.session ? store.session.id : null,
|
|
2112
|
+
view,
|
|
2113
|
+
fromSeq: seqsOfPage.length ? Math.min(...seqsOfPage) : (requestedFrom || 0),
|
|
2114
|
+
toSeq: seqsOfPage.length ? Math.max(...seqsOfPage) : (untilSeq === null ? store.seq : untilSeq),
|
|
2115
|
+
total: matched.length,
|
|
2116
|
+
returned: page.length,
|
|
2117
|
+
dropped: store.counters.dropped,
|
|
2118
|
+
evicted: store.counters.evicted,
|
|
2119
|
+
truncated,
|
|
2120
|
+
cursor: { next: truncated && lastSeq !== null ? encodeCursor(lastSeq) : null },
|
|
2121
|
+
...(gaps.length ? { gap: gaps[0] } : {}),
|
|
2122
|
+
groups: [],
|
|
2123
|
+
integrity: store.integrity(),
|
|
2124
|
+
};
|
|
2125
|
+
if (view === 'aggregate') {
|
|
2126
|
+
const groupBy = params.groupBy === undefined ? 'url' : params.groupBy;
|
|
2127
|
+
// Aggregate over *all* matched events, not just the first page: an aggregate that silently
|
|
2128
|
+
// ignored matches beyond `limit` would report a false empty `patterns`/`groups` (C20/C22).
|
|
2129
|
+
const aggregateInput = matched.map((item) => item.event);
|
|
2130
|
+
const aggregated = aggregateEvents(store, aggregateInput, groupBy);
|
|
2131
|
+
// R1-22: retry/duplicate/polling patterns are exposed here so C22 does not need trace.query.
|
|
2132
|
+
const retries = detectRetries(aggregateInput);
|
|
2133
|
+
return {
|
|
2134
|
+
...base,
|
|
2135
|
+
events: [],
|
|
2136
|
+
groups: aggregated.groups,
|
|
2137
|
+
patterns: buildPatterns(aggregateInput, retries),
|
|
2138
|
+
aggregate: {
|
|
2139
|
+
groupBy, truncated: aggregated.truncated, groupCount: aggregated.groupCount,
|
|
2140
|
+
incomplete: !store.integrity().complete, groups: aggregated.groups,
|
|
2141
|
+
totals: aggregatedTotals(aggregateInput),
|
|
2142
|
+
},
|
|
2143
|
+
evidence: evidenceBlock(store, 'events', { truncated: truncated || aggregated.truncated }),
|
|
2144
|
+
};
|
|
2145
|
+
}
|
|
2146
|
+
if (view === 'timeline') {
|
|
2147
|
+
const sorted = page.map((item) => item.event).sort((left, right) => left.ts.monotonicMs - right.ts.monotonicMs);
|
|
2148
|
+
const finalOrder = order === 'asc' ? sorted : [...sorted].reverse();
|
|
2149
|
+
return {
|
|
2150
|
+
...base,
|
|
2151
|
+
events: finalOrder.map((event) => ({ ...projectSummary(store, event), basis: 'temporal' })),
|
|
2152
|
+
evidence: evidenceBlock(store, 'events', { truncated }),
|
|
2153
|
+
};
|
|
2154
|
+
}
|
|
2155
|
+
if (view === 'full') {
|
|
2156
|
+
return {
|
|
2157
|
+
...base,
|
|
2158
|
+
events: ordered.map((item) => {
|
|
2159
|
+
const event = item.event;
|
|
2160
|
+
// `full` must stay BYTE-STABLE for a stored event (C10 / §4.1): only stored fields plus the
|
|
2161
|
+
// derived step id. Headers and cross-event durations are query-time state that legitimately
|
|
2162
|
+
// fills in later (ExtraInfo, response timing), so they live in `browser_network_detail`
|
|
2163
|
+
// instead of making the projection mutate.
|
|
2164
|
+
return {
|
|
2165
|
+
...event,
|
|
2166
|
+
stepId: derivedStepId(store, event),
|
|
2167
|
+
durationMs: event.timing && Number.isFinite(event.timing.totalMs) ? event.timing.totalMs : null,
|
|
2168
|
+
failure: event.failed ? {
|
|
2169
|
+
errorText: event.errorText, errorCode: event.errorCode,
|
|
2170
|
+
blockedReason: event.blockedReason, canceled: event.canceled,
|
|
2171
|
+
} : null,
|
|
2172
|
+
headersIn: 'detail',
|
|
2173
|
+
...(item.match ? { match: item.match } : {}),
|
|
2174
|
+
};
|
|
2175
|
+
}),
|
|
2176
|
+
evidence: evidenceBlock(store, 'events', { truncated }),
|
|
2177
|
+
};
|
|
2178
|
+
}
|
|
2179
|
+
return {
|
|
2180
|
+
...base,
|
|
2181
|
+
events: ordered.map((item) => ({ ...projectSummary(store, item.event), ...(item.match ? { match: item.match } : {}) })),
|
|
2182
|
+
evidence: evidenceBlock(store, 'events', { truncated }),
|
|
2183
|
+
};
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
/** §2.3 / R1-10 事件定位。 */
|
|
2187
|
+
export function resolveEvent(store, { seq = null, requestId = null, hopId = null, targetId = null } = {}) {
|
|
2188
|
+
if (Number.isInteger(seq)) {
|
|
2189
|
+
const event = store.events.find((item) => item.seq === seq);
|
|
2190
|
+
if (!event) throw new BrowserError('NET_EVENT_NOT_FOUND', '事件不存在或已淘汰: seq=' + String(seq), { seq });
|
|
2191
|
+
return event;
|
|
2192
|
+
}
|
|
2193
|
+
if (requestId !== undefined && requestId !== null) {
|
|
2194
|
+
const candidates = store.events.filter((event) => event.requestId === String(requestId)
|
|
2195
|
+
&& (targetId === null || targetId === undefined || event.targetId === targetId)
|
|
2196
|
+
&& (hopId === null || hopId === undefined || event.hopId === hopId));
|
|
2197
|
+
if (candidates.length === 0) {
|
|
2198
|
+
throw new BrowserError('NET_EVENT_NOT_FOUND', '事件不存在或已淘汰: requestId=' + String(requestId), { requestId: String(requestId) });
|
|
2199
|
+
}
|
|
2200
|
+
const targets = new Set(candidates.map((event) => event.targetId));
|
|
2201
|
+
if (targets.size > 1) {
|
|
2202
|
+
throw new BrowserError('NET_EVENT_NOT_FOUND', 'requestId 在多个 target 下重复,请改用 seq 定位', {
|
|
2203
|
+
requestId: String(requestId), targetIds: [...targets],
|
|
2204
|
+
});
|
|
2205
|
+
}
|
|
2206
|
+
const preference = ['finished', 'failed', 'response', 'request', 'redirect', 'ws-handshake', 'ws-created'];
|
|
2207
|
+
let best = null;
|
|
2208
|
+
for (const event of candidates) {
|
|
2209
|
+
const rank = preference.indexOf(event.phase);
|
|
2210
|
+
if (best === null || (rank !== -1 && (best.rank === -1 || rank < best.rank))) best = { event, rank };
|
|
2211
|
+
}
|
|
2212
|
+
return best.event;
|
|
2213
|
+
}
|
|
2214
|
+
throw new BrowserError('NET_INVALID_ARGUMENT', 'detail 需要 requestId 或 seq(恰好一个)');
|
|
2215
|
+
}
|
|
2216
|
+
|
|
2217
|
+
function normalizeInclude(include) {
|
|
2218
|
+
if (include === undefined || include === null) return new Set(NET_DETAIL_PARTS.filter((part) => part !== 'body'));
|
|
2219
|
+
if (!Array.isArray(include) || include.length === 0) throw new BrowserError('NET_INVALID_ARGUMENT', 'include 必须是非空数组');
|
|
2220
|
+
const set = new Set();
|
|
2221
|
+
for (const part of include) {
|
|
2222
|
+
if (!NET_DETAIL_PARTS.includes(part)) {
|
|
2223
|
+
throw new BrowserError('NET_INVALID_ARGUMENT', 'include 含未知取值 ' + String(part), { field: 'include', allowed: [...NET_DETAIL_PARTS] });
|
|
2224
|
+
}
|
|
2225
|
+
set.add(part);
|
|
2226
|
+
}
|
|
2227
|
+
return set;
|
|
2228
|
+
}
|
|
2229
|
+
|
|
2230
|
+
/** 采集配置决定的"从未尝试采集"原因码;采集开启但无记录 → null(无证据,不猜)。 */
|
|
2231
|
+
function bodyFallbackCode(store) {
|
|
2232
|
+
return store && store.config && store.config.captureBodies === true ? null : 'not-captured';
|
|
2233
|
+
}
|
|
2234
|
+
|
|
2235
|
+
/**
|
|
2236
|
+
* §2.3 body 块:三态 + 不伪造(detail 不补读、不重试)。
|
|
2237
|
+
* TOOL-P1-04:不可得时保留 `reason:"NET_BODY_UNAVAILABLE"` 兼容字段,并回传
|
|
2238
|
+
* `reasonCode`/`reasonDetail`;`fallbackReasonCode` 用于"从未尝试采集"(`captureBodies:false`
|
|
2239
|
+
* → `not-captured`)或调用方已知的缺失原因,`null` 表示无证据、不猜测。
|
|
2240
|
+
*/
|
|
2241
|
+
function bodyBlock(body, fallbackReasonCode = null) {
|
|
2242
|
+
if (!body || body.state === 'unavailable') {
|
|
2243
|
+
return {
|
|
2244
|
+
available: false, state: 'unavailable', encoding: null, bytes: null, originalBytes: null,
|
|
2245
|
+
truncated: null, redacted: null, source: 'unavailable', payloadOmitted: null, data: null,
|
|
2246
|
+
reason: 'NET_BODY_UNAVAILABLE',
|
|
2247
|
+
reasonCode: (body && body.reasonCode) || fallbackReasonCode || null,
|
|
2248
|
+
reasonDetail: body && body.reasonDetail !== undefined ? body.reasonDetail : null,
|
|
2249
|
+
};
|
|
2250
|
+
}
|
|
2251
|
+
return {
|
|
2252
|
+
available: true,
|
|
2253
|
+
state: body.state,
|
|
2254
|
+
encoding: body.encoding,
|
|
2255
|
+
bytes: body.bytes,
|
|
2256
|
+
originalBytes: body.originalBytes,
|
|
2257
|
+
truncated: body.truncated,
|
|
2258
|
+
redacted: body.redacted,
|
|
2259
|
+
source: 'captured',
|
|
2260
|
+
payloadOmitted: body.payloadOmitted,
|
|
2261
|
+
contentType: body.contentType,
|
|
2262
|
+
data: body.data,
|
|
2263
|
+
reason: null,
|
|
2264
|
+
reasonCode: null,
|
|
2265
|
+
reasonDetail: null,
|
|
2266
|
+
};
|
|
2267
|
+
}
|
|
2268
|
+
|
|
2269
|
+
/** `browser_network_detail` 执行体(纯只读,§2.3)。 */
|
|
2270
|
+
export function detailEvent(store, params = {}) {
|
|
2271
|
+
assertKnownKeys(params, ['sessionId', 'requestId', 'seq', 'hopId', 'targetId', 'include', 'maxBodyBytes'], 'detail');
|
|
2272
|
+
assertSession(store, params.sessionId);
|
|
2273
|
+
const hasSeq = Number.isInteger(params.seq);
|
|
2274
|
+
const hasRequestId = params.requestId !== undefined && params.requestId !== null;
|
|
2275
|
+
if (hasSeq === hasRequestId) throw new BrowserError('NET_INVALID_ARGUMENT', 'requestId 与 seq 必须恰好给一个');
|
|
2276
|
+
const include = normalizeInclude(params.include);
|
|
2277
|
+
const maxBytes = params.maxBodyBytes === undefined
|
|
2278
|
+
? NET_LIMITS.detailBodyBytes
|
|
2279
|
+
: clampInt(params.maxBodyBytes, NET_LIMITS.detailBodyMinBytes, NET_LIMITS.detailBodyBytes);
|
|
2280
|
+
const event = resolveEvent(store, { seq: params.seq, requestId: params.requestId, hopId: params.hopId, targetId: params.targetId });
|
|
2281
|
+
const options = { targetId: event.targetId, cdpSessionId: event.cdpSessionId, requestId: event.requestId, hopId: event.hopId };
|
|
2282
|
+
const chain = store.chains.get(requestKey(event)) || null;
|
|
2283
|
+
const result = {
|
|
2284
|
+
ok: true,
|
|
2285
|
+
sessionId: store.session ? store.session.id : null,
|
|
2286
|
+
seq: event.seq,
|
|
2287
|
+
requestId: event.requestId,
|
|
2288
|
+
hopId: event.hopId,
|
|
2289
|
+
targetId: event.targetId,
|
|
2290
|
+
cdpSessionId: event.cdpSessionId,
|
|
2291
|
+
include: [...include],
|
|
2292
|
+
event,
|
|
2293
|
+
stepIds: [...event.stepIds],
|
|
2294
|
+
evidenceIds: [...event.evidenceIds],
|
|
2295
|
+
};
|
|
2296
|
+
// `trace.link`/`evidence.link` may target any event of the same request chain; report the union so
|
|
2297
|
+
// detail answers "which evidence covers this request" (C33/C44).
|
|
2298
|
+
const chainOptions = { targetId: event.targetId, cdpSessionId: event.cdpSessionId, requestId: event.requestId };
|
|
2299
|
+
const chainEvents = store.events.filter((item) => item.requestId === chainOptions.requestId
|
|
2300
|
+
&& item.targetId === chainOptions.targetId && item.cdpSessionId === chainOptions.cdpSessionId);
|
|
2301
|
+
for (const item of chainEvents) {
|
|
2302
|
+
const projection = store.linkProjection ? store.linkProjection(item) : { stepIds: item.stepIds, evidenceIds: item.evidenceIds };
|
|
2303
|
+
for (const evidenceId of projection.evidenceIds) if (!result.evidenceIds.includes(evidenceId)) result.evidenceIds.push(evidenceId);
|
|
2304
|
+
for (const stepId of projection.stepIds) if (!result.stepIds.includes(stepId)) result.stepIds.push(stepId);
|
|
2305
|
+
}
|
|
2306
|
+
// Contract §2.3 exposes the parsed query at `queryString` on the detail (C18 asserts it).
|
|
2307
|
+
result.queryString = parseQueryString(event.url);
|
|
2308
|
+
result.failure = {
|
|
2309
|
+
errorText: event.errorText, errorCode: event.errorCode,
|
|
2310
|
+
blockedReason: event.blockedReason, canceled: event.canceled, failed: event.failed,
|
|
2311
|
+
};
|
|
2312
|
+
if (include.has('request')) {
|
|
2313
|
+
const requestBody = store.readBody({ ...options, kind: 'request' }, { maxBytes });
|
|
2314
|
+
result.request = {
|
|
2315
|
+
requestId: event.requestId,
|
|
2316
|
+
hopId: event.hopId,
|
|
2317
|
+
method: event.method,
|
|
2318
|
+
url: event.url,
|
|
2319
|
+
queryString: parseQueryString(event.url),
|
|
2320
|
+
headers: store.readHeaders({ ...options, kind: 'request' }).headers,
|
|
2321
|
+
resourceType: event.resourceType,
|
|
2322
|
+
// TOOL-P1-04:不可得(含带原因码的失败记录)时 postData 仍是 available:false,并回传原因码。
|
|
2323
|
+
postData: requestBody && requestBody.state !== 'unavailable'
|
|
2324
|
+
? { kind: bodyKindOf(requestBody.contentType), bytes: requestBody.originalBytes, state: requestBody.state, parseError: false }
|
|
2325
|
+
: {
|
|
2326
|
+
kind: 'unknown', bytes: null, state: 'unavailable', available: false,
|
|
2327
|
+
reason: 'NET_BODY_UNAVAILABLE',
|
|
2328
|
+
reasonCode: (requestBody && requestBody.reasonCode) || bodyFallbackCode(store),
|
|
2329
|
+
reasonDetail: requestBody ? (requestBody.reasonDetail ?? null) : null,
|
|
2330
|
+
},
|
|
2331
|
+
};
|
|
2332
|
+
}
|
|
2333
|
+
if (include.has('response')) {
|
|
2334
|
+
result.response = {
|
|
2335
|
+
status: event.status,
|
|
2336
|
+
statusClass: statusClass(event.status),
|
|
2337
|
+
statusText: event.statusText,
|
|
2338
|
+
mimeType: event.mimeType,
|
|
2339
|
+
protocol: event.protocol,
|
|
2340
|
+
fromCache: event.fromCache,
|
|
2341
|
+
headers: store.readHeaders({ ...options, kind: 'response' }).headers,
|
|
2342
|
+
sizes: event.sizes,
|
|
2343
|
+
failure: {
|
|
2344
|
+
errorText: event.errorText, errorCode: event.errorCode,
|
|
2345
|
+
blockedReason: event.blockedReason, canceled: event.canceled,
|
|
2346
|
+
},
|
|
2347
|
+
};
|
|
2348
|
+
}
|
|
2349
|
+
if (include.has('headers')) {
|
|
2350
|
+
result.headers = {
|
|
2351
|
+
request: store.readHeaders({ ...options, kind: 'request' }).headers,
|
|
2352
|
+
response: store.readHeaders({ ...options, kind: 'response' }).headers,
|
|
2353
|
+
redacted: {
|
|
2354
|
+
request: store.readHeaders({ ...options, kind: 'request' }).applied,
|
|
2355
|
+
response: store.readHeaders({ ...options, kind: 'response' }).applied,
|
|
2356
|
+
},
|
|
2357
|
+
};
|
|
2358
|
+
}
|
|
2359
|
+
if (include.has('body')) {
|
|
2360
|
+
const fallback = bodyFallbackCode(store);
|
|
2361
|
+
result.requestBody = bodyBlock(store.readBody({ ...options, kind: 'request' }, { maxBytes }), fallback);
|
|
2362
|
+
result.responseBody = bodyBlock(store.readBody({ ...options, kind: 'response' }, { maxBytes }), fallback);
|
|
2363
|
+
// Contract §2.3 names the parts `body.requestBody`/`body.responseBody`; the flat aliases above
|
|
2364
|
+
// are kept for callers that read them directly.
|
|
2365
|
+
result.body = { request: result.requestBody, response: result.responseBody };
|
|
2366
|
+
}
|
|
2367
|
+
if (include.has('timing')) {
|
|
2368
|
+
const timing = event.timing || emptyTiming();
|
|
2369
|
+
result.timing = {
|
|
2370
|
+
requestTimeMs: timing.requestTimeMs,
|
|
2371
|
+
responseTimeMs: timing.responseTimeMs,
|
|
2372
|
+
ttfbMs: timing.ttfbMs,
|
|
2373
|
+
totalMs: durationOf(store, event),
|
|
2374
|
+
dnsMs: timing.dnsMs,
|
|
2375
|
+
connectMs: timing.connectMs,
|
|
2376
|
+
sslMs: timing.sslMs,
|
|
2377
|
+
sendMs: timing.sendMs,
|
|
2378
|
+
waitMs: timing.waitMs,
|
|
2379
|
+
receiveMs: timing.receiveMs,
|
|
2380
|
+
};
|
|
2381
|
+
}
|
|
2382
|
+
if (include.has('redirects')) {
|
|
2383
|
+
const hopKeys = store.hops.get(event.requestId) || [];
|
|
2384
|
+
const hops = [];
|
|
2385
|
+
for (const key of hopKeys) {
|
|
2386
|
+
const hopChain = store.chains.get(key);
|
|
2387
|
+
if (!hopChain) continue;
|
|
2388
|
+
hops.push({
|
|
2389
|
+
hopId: hopChain.hopId,
|
|
2390
|
+
seq: hopChain.seqs.length ? hopChain.seqs[0] : null,
|
|
2391
|
+
requestId: hopChain.requestId,
|
|
2392
|
+
url: hopChain.url,
|
|
2393
|
+
status: hopChain.status,
|
|
2394
|
+
location: hopChain.hops.length ? hopChain.hops[hopChain.hops.length - 1].url : null,
|
|
2395
|
+
});
|
|
2396
|
+
}
|
|
2397
|
+
if (hops.length === 0) {
|
|
2398
|
+
// Fallback: derive hops from the stored events of this request (fetch/XHR redirects whose
|
|
2399
|
+
// chain was never registered). One row per hop, in hop order (C25).
|
|
2400
|
+
const byHop = new Map();
|
|
2401
|
+
for (const item of store.events) {
|
|
2402
|
+
if (item.requestId !== event.requestId) continue;
|
|
2403
|
+
const hopId = item.hopId ?? 0;
|
|
2404
|
+
const existing = byHop.get(hopId);
|
|
2405
|
+
if (!existing || (item.phase === 'redirect' && existing.status === null)) {
|
|
2406
|
+
byHop.set(hopId, {
|
|
2407
|
+
hopId,
|
|
2408
|
+
seq: existing && existing.seq !== null ? existing.seq : item.seq,
|
|
2409
|
+
requestId: item.requestId,
|
|
2410
|
+
url: item.redirect ? item.redirect.from : item.url,
|
|
2411
|
+
status: item.status,
|
|
2412
|
+
location: item.redirect ? item.redirect.to : (existing ? existing.location : null),
|
|
2413
|
+
});
|
|
2414
|
+
} else if (item.redirect && existing && existing.location === null) {
|
|
2415
|
+
existing.location = item.redirect.to;
|
|
2416
|
+
existing.status = item.status;
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
for (const hopId of [...byHop.keys()].sort((a, b) => a - b)) hops.push(byHop.get(hopId));
|
|
2420
|
+
}
|
|
2421
|
+
result.hops = hops;
|
|
2422
|
+
result.redirects = hops.filter((hop) => hop.hopId !== (chain ? chain.hopId : 0) || hop.location !== null);
|
|
2423
|
+
if (hops.length === 0 && event.redirect) {
|
|
2424
|
+
result.redirects = [{ requestId: event.requestId, url: event.redirect.to, status: event.redirect.status, location: event.redirect.to }];
|
|
2425
|
+
}
|
|
2426
|
+
}
|
|
2427
|
+
if (include.has('initiator')) result.initiator = event.initiator;
|
|
2428
|
+
if (include.has('ws')) {
|
|
2429
|
+
const frames = store.events
|
|
2430
|
+
.filter((item) => item.kind === 'ws' && item.requestId === event.requestId && (item.phase === 'ws-send' || item.phase === 'ws-receive'))
|
|
2431
|
+
.slice(0, NET_LIMITS.eventPageLimit)
|
|
2432
|
+
.map((item) => ({
|
|
2433
|
+
seq: item.seq, direction: item.ws ? item.ws.direction : null, opcode: item.ws ? item.ws.opcode : null,
|
|
2434
|
+
payload: item.ws ? item.ws.payload : null, payloadTruncated: item.ws ? item.ws.payloadTruncated : null,
|
|
2435
|
+
payloadOmitted: item.ws ? item.ws.payloadOmitted : null, wallMs: item.ts.wallMs,
|
|
2436
|
+
}));
|
|
2437
|
+
result.ws = event.kind === 'ws' || frames.length > 0 ? {
|
|
2438
|
+
url: (event.ws && event.ws.url) || event.url,
|
|
2439
|
+
protocol: event.ws ? event.ws.protocol : null,
|
|
2440
|
+
handshake: event.ws ? event.ws.handshake : null,
|
|
2441
|
+
openedAt: event.ws ? event.ws.openedAt : null,
|
|
2442
|
+
closedAt: event.ws ? event.ws.closedAt : null,
|
|
2443
|
+
frames,
|
|
2444
|
+
counts: {
|
|
2445
|
+
sent: frames.filter((frame) => frame.direction === 'send').length,
|
|
2446
|
+
received: frames.filter((frame) => frame.direction === 'receive').length,
|
|
2447
|
+
truncated: store.counters.wsFrames >= store.config.maxWsFrames,
|
|
2448
|
+
},
|
|
2449
|
+
} : null;
|
|
2450
|
+
}
|
|
2451
|
+
if (include.has('sse')) {
|
|
2452
|
+
const messages = store.events
|
|
2453
|
+
.filter((item) => item.kind === 'sse' && item.requestId === event.requestId)
|
|
2454
|
+
.slice(0, NET_LIMITS.eventPageLimit)
|
|
2455
|
+
.map((item) => ({
|
|
2456
|
+
seq: item.seq, eventName: item.sse ? item.sse.eventName : null,
|
|
2457
|
+
eventId: item.sse ? item.sse.eventId : null, data: item.sse ? item.sse.data : null,
|
|
2458
|
+
wallMs: item.ts.wallMs,
|
|
2459
|
+
}));
|
|
2460
|
+
result.sse = event.kind === 'sse' || messages.length ? { url: event.url, events: messages, counts: { messages: messages.length } } : null;
|
|
2461
|
+
}
|
|
2462
|
+
if (include.has('correlation')) {
|
|
2463
|
+
const contentHashes = store.corrHashes.get(event.seq) || [];
|
|
2464
|
+
result.correlation = {
|
|
2465
|
+
ids: event.correlationIds.map((id) => ({
|
|
2466
|
+
name: id.name, value: id.value, valueHash: id.valueHash,
|
|
2467
|
+
source: { kind: id.source || null, seq: event.seq },
|
|
2468
|
+
})),
|
|
2469
|
+
sameGroup: contentHashes.length
|
|
2470
|
+
? Math.max(...contentHashes.map((hash) => (store.correlationIndex.get(hash) || []).length))
|
|
2471
|
+
: 0,
|
|
2472
|
+
};
|
|
2473
|
+
}
|
|
2474
|
+
if (include.has('dependencies')) {
|
|
2475
|
+
const parents = [];
|
|
2476
|
+
const children = [];
|
|
2477
|
+
if (event.initiator && event.initiator.requestId) {
|
|
2478
|
+
const parent = store.events.find((item) => item.requestId === event.initiator.requestId);
|
|
2479
|
+
if (parent) parents.push({ requestId: parent.requestId, url: parent.url, relation: 'initiator' });
|
|
2480
|
+
}
|
|
2481
|
+
if (chain) for (const hop of chain.hops) parents.push({ requestId: hop.requestId, url: hop.fromUrl, relation: 'redirect' });
|
|
2482
|
+
// Redirect edges derived from the stored chain (works for fetch/XHR redirects too, where CDP
|
|
2483
|
+
// does not always deliver `redirectResponse` on this connection): a lower hop of the same
|
|
2484
|
+
// request is the parent of this hop.
|
|
2485
|
+
for (const item of store.events) {
|
|
2486
|
+
if (item.requestId !== event.requestId) continue;
|
|
2487
|
+
if (item.phase !== 'redirect') continue;
|
|
2488
|
+
if ((item.hopId ?? 0) >= (event.hopId ?? 0)) continue;
|
|
2489
|
+
parents.push({ requestId: item.requestId, url: item.url, relation: 'redirect', hopId: item.hopId, status: item.status ?? null });
|
|
2490
|
+
}
|
|
2491
|
+
for (const item of store.events) {
|
|
2492
|
+
if (item.seq >= event.seq) break;
|
|
2493
|
+
if (item.initiator && item.initiator.requestId === event.requestId) children.push({ requestId: item.requestId, url: item.url, relation: 'initiator' });
|
|
2494
|
+
if (item.url && event.url && item.url === event.url && item.requestId !== event.requestId) {
|
|
2495
|
+
parents.push({ requestId: item.requestId, url: item.url, relation: 'same-url' });
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
result.dependencies = {
|
|
2499
|
+
parents: dedupeEdges(parents).slice(0, NET_LIMITS.dependencyEdges),
|
|
2500
|
+
children: dedupeEdges(children).slice(0, NET_LIMITS.dependencyEdges),
|
|
2501
|
+
basis: 'observed',
|
|
2502
|
+
};
|
|
2503
|
+
}
|
|
2504
|
+
if (include.has('business')) {
|
|
2505
|
+
const step = event.stepId ? store.steps.get(event.stepId) : null;
|
|
2506
|
+
const path = (event.business && event.business.businessCodePath) || (step && step.businessStatusPath) || store.config.businessStatusPath || null;
|
|
2507
|
+
// Business code is derived from the captured response body at query time, so `detail` reports
|
|
2508
|
+
// it even when the body was captured after the `finished` event was written (R1-11).
|
|
2509
|
+
let businessCode = event.business ? event.business.businessCode : null;
|
|
2510
|
+
if (businessCode === null) {
|
|
2511
|
+
const stored = store.readBody({ ...options, kind: 'response' }, { maxBytes });
|
|
2512
|
+
if (stored && stored.state === 'captured' && !stored.payloadOmitted) {
|
|
2513
|
+
let parsed = null;
|
|
2514
|
+
try { parsed = JSON.parse(stored.data); } catch { parsed = null; }
|
|
2515
|
+
businessCode = extractBusinessCode(parsed, path).businessCode;
|
|
2516
|
+
}
|
|
2517
|
+
}
|
|
2518
|
+
result.business = {
|
|
2519
|
+
statusCode: event.status,
|
|
2520
|
+
businessCode,
|
|
2521
|
+
businessCodePath: path,
|
|
2522
|
+
objects: extractObjects(store, { objectRules: objectRulesFor(store, event) }, [event]).map((object) => ({
|
|
2523
|
+
name: object.name, value: object.value, source: { seq: object.firstSeq, from: object.from, path: object.path },
|
|
2524
|
+
})),
|
|
2525
|
+
};
|
|
2526
|
+
}
|
|
2527
|
+
if (include.has('events')) {
|
|
2528
|
+
result.events = store.events
|
|
2529
|
+
.filter((item) => item.requestId === event.requestId && item.targetId === event.targetId && item.cdpSessionId === event.cdpSessionId)
|
|
2530
|
+
.slice(0, NET_LIMITS.detailEvents)
|
|
2531
|
+
.map((item) => projectSummary(store, item));
|
|
2532
|
+
}
|
|
2533
|
+
// R1-22: per-request retry/duplicate analysis over the events sharing this request's identity
|
|
2534
|
+
// key (method + un-sanitized urlHash), so `detail` answers it without a separate trace query.
|
|
2535
|
+
const identityKey = (item) => (item.method || 'GET') + ' ' + (item.urlHash || item.url);
|
|
2536
|
+
const siblings = store.events.filter((item) => item.kind === 'http' && item.phase === 'response'
|
|
2537
|
+
&& (item.urlHash ? item.urlHash === event.urlHash : identityKey(item) === identityKey(event)));
|
|
2538
|
+
const siblingPatterns = detectRetries(siblings.length ? siblings : [event]);
|
|
2539
|
+
const selfPattern = siblingPatterns.find((item) => identityKey(event) === item.groupKey || (item.seqs || []).includes(event.seq));
|
|
2540
|
+
result.analysis = {
|
|
2541
|
+
pattern: selfPattern ? selfPattern.pattern : null,
|
|
2542
|
+
groupKey: selfPattern ? selfPattern.groupKey : identityKey(event),
|
|
2543
|
+
occurrences: siblings.length,
|
|
2544
|
+
// §5.4 observable classifications only — never a guess.
|
|
2545
|
+
issues: observableIssues(event),
|
|
2546
|
+
basis: 'observed',
|
|
2547
|
+
};
|
|
2548
|
+
result.integrity = store.integrity();
|
|
2549
|
+
result.evidence = evidenceBlock(store, 'detail', { fromSeq: event.seq, toSeq: event.seq });
|
|
2550
|
+
return result;
|
|
2551
|
+
}
|
|
2552
|
+
|
|
2553
|
+
|
|
2554
|
+
/** §5.4 错误/异常分类(只基于可观测事实,`cors` 仅 suspect)。 */
|
|
2555
|
+
export function observableIssues(event) {
|
|
2556
|
+
const issues = [];
|
|
2557
|
+
if (!event) return issues;
|
|
2558
|
+
if (event.failed) issues.push('loading-failed');
|
|
2559
|
+
if (Number.isInteger(event.status) && event.status >= 400) issues.push('http-error');
|
|
2560
|
+
const text = String(event.errorText || '');
|
|
2561
|
+
if (/TIMED_OUT|ERR_TIMEOUT/i.test(text)) issues.push('timeout');
|
|
2562
|
+
if (/CORS/i.test(text)) issues.push('cors-suspect');
|
|
2563
|
+
if (event.canceled === true) issues.push('aborted');
|
|
2564
|
+
if (event.blockedReason) issues.push('blocked');
|
|
2565
|
+
return issues;
|
|
2566
|
+
}
|
|
2567
|
+
|
|
2568
|
+
function dedupeEdges(edges) {
|
|
2569
|
+
const seen = new Set();
|
|
2570
|
+
const out = [];
|
|
2571
|
+
for (const edge of edges) {
|
|
2572
|
+
const key = edge.relation + '\u0000' + edge.requestId;
|
|
2573
|
+
if (seen.has(key)) continue;
|
|
2574
|
+
seen.add(key);
|
|
2575
|
+
out.push(edge);
|
|
2576
|
+
}
|
|
2577
|
+
return out;
|
|
2578
|
+
}
|
|
2579
|
+
|
|
2580
|
+
/* ------------------------------------------------------------------ */
|
|
2581
|
+
/* 业务链路:trace(§2.4 / §5.6 / §6) */
|
|
2582
|
+
/* ------------------------------------------------------------------ */
|
|
2583
|
+
|
|
2584
|
+
export function validateObjectRules(rules) {
|
|
2585
|
+
if (!Array.isArray(rules)) throw new BrowserError('NET_RULE_INVALID', 'objectRules 必须是数组');
|
|
2586
|
+
if (rules.length > NET_LIMITS.objectRules) {
|
|
2587
|
+
throw new BrowserError('NET_QUOTA_EXCEEDED', 'objectRules 最多 ' + NET_LIMITS.objectRules + ' 条', { max: NET_LIMITS.objectRules });
|
|
2588
|
+
}
|
|
2589
|
+
return rules.map((rule, index) => {
|
|
2590
|
+
assertKnownKeys(rule, ['from', 'key', 'path', 'name', 'propagate'], `objectRules[${index}]`, 'NET_RULE_INVALID');
|
|
2591
|
+
if (!NET_OBJECT_SOURCES.includes(rule.from)) {
|
|
2592
|
+
throw new BrowserError('NET_RULE_INVALID', `objectRules[${index}].from 不合法`, { allowed: [...NET_OBJECT_SOURCES] });
|
|
2593
|
+
}
|
|
2594
|
+
if (!rule.key && !rule.path) throw new BrowserError('NET_RULE_INVALID', `objectRules[${index}] 需要 key 或 path`);
|
|
2595
|
+
return {
|
|
2596
|
+
from: rule.from,
|
|
2597
|
+
key: rule.key ? truncateBytes(String(rule.key), 128) : null,
|
|
2598
|
+
path: rule.path ? truncateBytes(String(rule.path), 256) : null,
|
|
2599
|
+
name: rule.name ? truncateBytes(String(rule.name), 128) : truncateBytes(String(rule.key || rule.path), 128),
|
|
2600
|
+
propagate: rule.propagate === true,
|
|
2601
|
+
};
|
|
2602
|
+
});
|
|
2603
|
+
}
|
|
2604
|
+
|
|
2605
|
+
export function validateCorrelationRules(rules) {
|
|
2606
|
+
if (!Array.isArray(rules)) throw new BrowserError('NET_RULE_INVALID', 'correlationRules 必须是数组');
|
|
2607
|
+
if (rules.length > NET_LIMITS.correlationRules) {
|
|
2608
|
+
throw new BrowserError('NET_QUOTA_EXCEEDED', 'correlationRules 最多 ' + NET_LIMITS.correlationRules + ' 条', { max: NET_LIMITS.correlationRules });
|
|
2609
|
+
}
|
|
2610
|
+
return rules.map((rule, index) => {
|
|
2611
|
+
assertKnownKeys(rule, ['from', 'key', 'path', 'name'], `correlationRules[${index}]`, 'NET_RULE_INVALID');
|
|
2612
|
+
if (!NET_CORRELATION_SOURCES.includes(rule.from)) {
|
|
2613
|
+
throw new BrowserError('NET_RULE_INVALID', `correlationRules[${index}].from 不合法`, { allowed: [...NET_CORRELATION_SOURCES] });
|
|
2614
|
+
}
|
|
2615
|
+
if (!rule.key) throw new BrowserError('NET_RULE_INVALID', `correlationRules[${index}].key 必填`);
|
|
2616
|
+
return {
|
|
2617
|
+
from: rule.from,
|
|
2618
|
+
key: truncateBytes(String(rule.key), 128),
|
|
2619
|
+
path: rule.path ? truncateBytes(String(rule.path), 256) : null,
|
|
2620
|
+
name: rule.name ? truncateBytes(String(rule.name), 128) : truncateBytes(String(rule.key), 128),
|
|
2621
|
+
};
|
|
2622
|
+
});
|
|
2623
|
+
}
|
|
2624
|
+
|
|
2625
|
+
/**
|
|
2626
|
+
* §5.6 / R1-9 提取关联标识(默认规则 + 步骤追加规则)。返回 `{name, value, contentHash, source}`,
|
|
2627
|
+
* `value` 是脱敏显示值(原值只在内存里算 hash,不落库)。
|
|
2628
|
+
*/
|
|
2629
|
+
export function extractCorrelationIds(event, { headers = null, bodyText = null, extraRules = [], hmacKey = null } = {}) {
|
|
2630
|
+
const rules = [...DEFAULT_CORRELATION_RULES, ...extraRules];
|
|
2631
|
+
const ids = [];
|
|
2632
|
+
const push = (name, raw, source) => {
|
|
2633
|
+
if (raw === undefined || raw === null || String(raw) === '') return;
|
|
2634
|
+
const text = String(raw);
|
|
2635
|
+
const display = /^traceparent$/i.test(name) || text.length > 32 ? truncateBytes(text, 64) : text;
|
|
2636
|
+
ids.push({
|
|
2637
|
+
name,
|
|
2638
|
+
value: SENSITIVE_KEY.test(name) ? '***' : display,
|
|
2639
|
+
contentHash: hmacHex(hmacKey || store_hmac_fallback(), text, { full: true }),
|
|
2640
|
+
source,
|
|
2641
|
+
});
|
|
2642
|
+
};
|
|
2643
|
+
for (const rule of rules) {
|
|
2644
|
+
if (rule.from === 'header') {
|
|
2645
|
+
if (!headers) continue;
|
|
2646
|
+
const found = Object.entries(headers).find(([key]) => key.toLowerCase() === String(rule.key).toLowerCase());
|
|
2647
|
+
if (!found) continue;
|
|
2648
|
+
let value = found[1];
|
|
2649
|
+
if (String(rule.key).toLowerCase() === 'traceparent') {
|
|
2650
|
+
const parts = String(value).split('-');
|
|
2651
|
+
if (parts.length >= 4) value = parts[1];
|
|
2652
|
+
}
|
|
2653
|
+
push(rule.name, value, 'header');
|
|
2654
|
+
} else if (rule.from === 'url-query') {
|
|
2655
|
+
for (const pair of parseQueryString(event.url)) {
|
|
2656
|
+
if (pair.name.toLowerCase() === String(rule.key).toLowerCase()) push(rule.name, pair.value, 'query');
|
|
2657
|
+
}
|
|
2658
|
+
} else if (rule.from === 'json-body') {
|
|
2659
|
+
if (!bodyText) continue;
|
|
2660
|
+
let parsed;
|
|
2661
|
+
try { parsed = JSON.parse(bodyText); } catch { continue; }
|
|
2662
|
+
const found = readJsonPath(parsed, rule.path || rule.key);
|
|
2663
|
+
if (found.found) push(rule.name, found.value, 'jsonPath');
|
|
2664
|
+
}
|
|
2665
|
+
}
|
|
2666
|
+
const seen = new Set();
|
|
2667
|
+
return ids.filter((id) => {
|
|
2668
|
+
const key = id.name + '\u0000' + id.contentHash;
|
|
2669
|
+
if (seen.has(key)) return false;
|
|
2670
|
+
seen.add(key);
|
|
2671
|
+
return true;
|
|
2672
|
+
}).slice(0, NET_LIMITS.correlationRules);
|
|
2673
|
+
}
|
|
2674
|
+
|
|
2675
|
+
function store_hmac_fallback() { return 'no-key'; }
|
|
2676
|
+
|
|
2677
|
+
/** §5.2 业务状态码。 */
|
|
2678
|
+
export function extractBusinessCode(parsedBody, explicitPath = null) {
|
|
2679
|
+
if (parsedBody === null || parsedBody === undefined || typeof parsedBody !== 'object') return { businessCode: null, businessCodePath: null };
|
|
2680
|
+
if (explicitPath) {
|
|
2681
|
+
const found = readJsonPath(parsedBody, explicitPath);
|
|
2682
|
+
if (found.found && found.value !== null && found.value !== undefined) {
|
|
2683
|
+
return { businessCode: Number.isFinite(Number(found.value)) ? Number(found.value) : String(found.value), businessCodePath: explicitPath };
|
|
2684
|
+
}
|
|
2685
|
+
return { businessCode: null, businessCodePath: explicitPath };
|
|
2686
|
+
}
|
|
2687
|
+
for (const path of DEFAULT_BUSINESS_PATHS) {
|
|
2688
|
+
const found = readJsonPath(parsedBody, path);
|
|
2689
|
+
if (found.found && typeof found.value === 'number' && Number.isFinite(found.value)) return { businessCode: found.value, businessCodePath: path };
|
|
2690
|
+
}
|
|
2691
|
+
return { businessCode: null, businessCodePath: null };
|
|
2692
|
+
}
|
|
2693
|
+
|
|
2694
|
+
function objectRulesFor(store, event) {
|
|
2695
|
+
if (event && event.stepId) {
|
|
2696
|
+
const step = store.steps.get(event.stepId);
|
|
2697
|
+
if (step && step.objectRules.length) return step.objectRules;
|
|
2698
|
+
}
|
|
2699
|
+
for (const step of store.steps.values()) if (step.open && step.objectRules.length) return step.objectRules;
|
|
2700
|
+
return [];
|
|
2701
|
+
}
|
|
2702
|
+
|
|
2703
|
+
function stepEvents(store, step, allEvents = null) {
|
|
2704
|
+
const events = allEvents || store.events;
|
|
2705
|
+
const to = step.window.toWallMs === null || step.window.toWallMs === undefined ? Number.POSITIVE_INFINITY : step.window.toWallMs;
|
|
2706
|
+
return events.filter((event) => event.ts.wallMs >= step.window.fromWallMs && event.ts.wallMs <= to);
|
|
2707
|
+
}
|
|
2708
|
+
|
|
2709
|
+
function readObjectValue(store, event, rule) {
|
|
2710
|
+
const bodyOptions = { targetId: event.targetId, cdpSessionId: event.cdpSessionId, requestId: event.requestId, hopId: event.hopId };
|
|
2711
|
+
switch (rule.from) {
|
|
2712
|
+
case 'url-query': {
|
|
2713
|
+
for (const pair of parseQueryString(event.url)) {
|
|
2714
|
+
if (pair.name.toLowerCase() === String(rule.key || '').toLowerCase()) return truncateBytes(pair.value, 256);
|
|
2715
|
+
}
|
|
2716
|
+
return null;
|
|
2717
|
+
}
|
|
2718
|
+
case 'url-path': {
|
|
2719
|
+
let pathname = '';
|
|
2720
|
+
try { pathname = new URL(String(event.url || '')).pathname; } catch { return null; }
|
|
2721
|
+
const segments = pathname.split('/').filter((segment) => segment !== '');
|
|
2722
|
+
if (rule.path && /^\d+$/.test(rule.path)) {
|
|
2723
|
+
const segment = segments[Number(rule.path)];
|
|
2724
|
+
return segment === undefined ? null : truncateBytes(segment, 256);
|
|
2725
|
+
}
|
|
2726
|
+
if (rule.key) {
|
|
2727
|
+
const index = segments.findIndex((segment) => segment.toLowerCase() === String(rule.key).toLowerCase());
|
|
2728
|
+
if (index !== -1 && segments[index + 1] !== undefined) return truncateBytes(segments[index + 1], 256);
|
|
2729
|
+
}
|
|
2730
|
+
return null;
|
|
2731
|
+
}
|
|
2732
|
+
case 'header': {
|
|
2733
|
+
if (!rule.key || !event.requestId) return null;
|
|
2734
|
+
const record = store.readHeaders({ ...bodyOptions, kind: 'request' });
|
|
2735
|
+
const found = Object.entries(record.headers).find(([key]) => key.toLowerCase() === String(rule.key).toLowerCase());
|
|
2736
|
+
return found ? truncateBytes(found[1], 256) : null;
|
|
2737
|
+
}
|
|
2738
|
+
case 'json-body': {
|
|
2739
|
+
if (!event.requestId) return null;
|
|
2740
|
+
for (const kind of ['response', 'request']) {
|
|
2741
|
+
const body = store.readBody({ ...bodyOptions, kind });
|
|
2742
|
+
if (!body || body.state === 'unavailable' || body.payloadOmitted || body.originalBytes === 0) continue;
|
|
2743
|
+
let parsed;
|
|
2744
|
+
try { parsed = JSON.parse(body.data); } catch { continue; }
|
|
2745
|
+
const found = readJsonPath(parsed, rule.path || rule.key);
|
|
2746
|
+
if (found.found && found.value !== null && typeof found.value !== 'object') return truncateBytes(String(found.value), 256);
|
|
2747
|
+
}
|
|
2748
|
+
return null;
|
|
2749
|
+
}
|
|
2750
|
+
case 'ws': {
|
|
2751
|
+
if (!event.ws || !event.ws.payload) return null;
|
|
2752
|
+
let parsed;
|
|
2753
|
+
try { parsed = JSON.parse(event.ws.payload); } catch { return null; }
|
|
2754
|
+
const found = readJsonPath(parsed, rule.path || rule.key);
|
|
2755
|
+
return found.found && found.value !== null && typeof found.value !== 'object' ? truncateBytes(String(found.value), 256) : null;
|
|
2756
|
+
}
|
|
2757
|
+
case 'sse': {
|
|
2758
|
+
if (!event.sse || !event.sse.data) return null;
|
|
2759
|
+
let parsed;
|
|
2760
|
+
try { parsed = JSON.parse(event.sse.data); } catch { return null; }
|
|
2761
|
+
const found = readJsonPath(parsed, rule.path || rule.key);
|
|
2762
|
+
return found.found && found.value !== null && typeof found.value !== 'object' ? truncateBytes(String(found.value), 256) : null;
|
|
2763
|
+
}
|
|
2764
|
+
default: return null;
|
|
2765
|
+
}
|
|
2766
|
+
}
|
|
2767
|
+
|
|
2768
|
+
function objectAppearsIn(store, event, value) {
|
|
2769
|
+
if (!value) return null;
|
|
2770
|
+
if (event.url && event.url.includes(value)) return 'url';
|
|
2771
|
+
if (!event.requestId) return null;
|
|
2772
|
+
const options = { targetId: event.targetId, cdpSessionId: event.cdpSessionId, requestId: event.requestId, hopId: event.hopId };
|
|
2773
|
+
const headers = store.readHeaders({ ...options, kind: 'request' });
|
|
2774
|
+
if (Object.values(headers.headers).some((headerValue) => String(headerValue).includes(value))) return 'header';
|
|
2775
|
+
for (const kind of ['request', 'response']) {
|
|
2776
|
+
const body = store.readBody({ ...options, kind });
|
|
2777
|
+
if (body && body.state !== 'unavailable' && !body.payloadOmitted && body.data.includes(value)) return 'body';
|
|
2778
|
+
}
|
|
2779
|
+
return null;
|
|
2780
|
+
}
|
|
2781
|
+
|
|
2782
|
+
/**
|
|
2783
|
+
* §6.2 对象提取(只按显式规则)。规则名/键/路径命中敏感词的,值一律投影为 `***`(R1-9 / §8.4),
|
|
2784
|
+
* 避免把 token 类值经业务对象再次写出;事件本体不含 objects(只在 trace/detail 查询期投影)。
|
|
2785
|
+
*/
|
|
2786
|
+
export function extractObjects(store, step, events) {
|
|
2787
|
+
const rules = (step && step.objectRules) || [];
|
|
2788
|
+
if (!rules.length) return [];
|
|
2789
|
+
const objects = [];
|
|
2790
|
+
const maskRules = (store && store.config && Array.isArray(store.config.maskRules)) ? store.config.maskRules : [];
|
|
2791
|
+
for (const event of events) {
|
|
2792
|
+
for (const rule of rules) {
|
|
2793
|
+
const sensitive = SENSITIVE_KEY.test([rule.name, rule.key, rule.path].filter(Boolean).join(' '))
|
|
2794
|
+
|| maskRules.some((mask) => String(mask).length > 0 && String(rule.name || '').toLowerCase().endsWith(String(mask).toLowerCase()));
|
|
2795
|
+
const value = sensitive ? (readObjectValue(store, event, rule) === null ? null : '***') : readObjectValue(store, event, rule);
|
|
2796
|
+
if (value === null) continue;
|
|
2797
|
+
const id = rule.name + ':' + value;
|
|
2798
|
+
let object = objects.find((item) => item.id === id);
|
|
2799
|
+
if (!object) {
|
|
2800
|
+
object = {
|
|
2801
|
+
id, key: rule.key, name: rule.name, from: rule.from, path: rule.path, value,
|
|
2802
|
+
firstSeq: event.seq, lastSeq: event.seq, events: [], propagate: rule.propagate === true, propagation: [],
|
|
2803
|
+
};
|
|
2804
|
+
objects.push(object);
|
|
2805
|
+
}
|
|
2806
|
+
object.lastSeq = event.seq;
|
|
2807
|
+
if (!object.events.includes(event.seq)) object.events.push(event.seq);
|
|
2808
|
+
if (object.events.length > NET_LIMITS.objectEvents) object.events = object.events.slice(-NET_LIMITS.objectEvents);
|
|
2809
|
+
}
|
|
2810
|
+
}
|
|
2811
|
+
for (const object of objects) {
|
|
2812
|
+
if (!object.propagate) continue;
|
|
2813
|
+
for (const event of store.events) {
|
|
2814
|
+
if (event.seq <= object.lastSeq) continue;
|
|
2815
|
+
const where = objectAppearsIn(store, event, object.value);
|
|
2816
|
+
if (where) object.propagation.push({ fromSeq: object.lastSeq, toSeq: event.seq, where, basis: 'observed' });
|
|
2817
|
+
if (object.propagation.length >= 20) break;
|
|
2818
|
+
}
|
|
2819
|
+
}
|
|
2820
|
+
return objects;
|
|
2821
|
+
}
|
|
2822
|
+
|
|
2823
|
+
function businessStates(store, step, events) {
|
|
2824
|
+
const states = [];
|
|
2825
|
+
let previous = null;
|
|
2826
|
+
const path = (step && step.businessStatusPath) || (store && store.config ? store.config.businessStatusPath : null) || null;
|
|
2827
|
+
for (const event of events) {
|
|
2828
|
+
if (event.kind !== 'http' || !['response', 'finished', 'failed'].includes(event.phase)) continue;
|
|
2829
|
+
let code = event.business ? event.business.businessCode : null;
|
|
2830
|
+
if (code === null && store && event.requestId) {
|
|
2831
|
+
// The body is captured after `finished` was written, so derive the business code at query time.
|
|
2832
|
+
const stored = store.readBody({
|
|
2833
|
+
targetId: event.targetId, cdpSessionId: event.cdpSessionId, requestId: event.requestId, hopId: event.hopId, kind: 'response',
|
|
2834
|
+
});
|
|
2835
|
+
if (stored && stored.state === 'captured' && !stored.payloadOmitted) {
|
|
2836
|
+
let parsed = null;
|
|
2837
|
+
try { parsed = JSON.parse(stored.data); } catch { parsed = null; }
|
|
2838
|
+
code = extractBusinessCode(parsed, path).businessCode;
|
|
2839
|
+
}
|
|
2840
|
+
}
|
|
2841
|
+
const current = { status: event.status, code };
|
|
2842
|
+
if (previous && (previous.status !== current.status || previous.code !== current.code)) {
|
|
2843
|
+
states.push({
|
|
2844
|
+
atWallMs: event.ts.wallMs, seq: event.seq,
|
|
2845
|
+
from: previous.code !== null ? previous.code : previous.status,
|
|
2846
|
+
to: current.code !== null ? current.code : current.status,
|
|
2847
|
+
field: previous.code !== current.code ? 'businessCode' : 'httpStatus',
|
|
2848
|
+
basis: 'observed',
|
|
2849
|
+
});
|
|
2850
|
+
}
|
|
2851
|
+
previous = current;
|
|
2852
|
+
}
|
|
2853
|
+
return states;
|
|
2854
|
+
}
|
|
2855
|
+
|
|
2856
|
+
/** §5.5/§6.4 轮询:键 = method + origin+path + bodyHash(query 不计),R1-17。 */
|
|
2857
|
+
export function detectPolling(events) {
|
|
2858
|
+
const groups = new Map();
|
|
2859
|
+
for (const event of events) {
|
|
2860
|
+
if (event.kind !== 'http' || !event.url || event.phase !== 'request') continue;
|
|
2861
|
+
let key;
|
|
2862
|
+
try {
|
|
2863
|
+
const parsed = new URL(event.url);
|
|
2864
|
+
key = (event.method || 'GET') + ' ' + parsed.origin + parsed.pathname;
|
|
2865
|
+
} catch { key = (event.method || 'GET') + ' ' + event.url; }
|
|
2866
|
+
const list = groups.get(key) || [];
|
|
2867
|
+
list.push(event);
|
|
2868
|
+
groups.set(key, list);
|
|
2869
|
+
}
|
|
2870
|
+
const polling = [];
|
|
2871
|
+
for (const [groupKey, list] of groups.entries()) {
|
|
2872
|
+
if (list.length < 3) continue;
|
|
2873
|
+
const sorted = [...list].sort((left, right) => left.ts.wallMs - right.ts.wallMs);
|
|
2874
|
+
const intervals = [];
|
|
2875
|
+
for (let index = 1; index < sorted.length; index += 1) intervals.push(sorted[index].ts.wallMs - sorted[index - 1].ts.wallMs);
|
|
2876
|
+
const average = intervals.reduce((sum, value) => sum + value, 0) / intervals.length;
|
|
2877
|
+
if (average > NET_LIMITS.pollWindowMs || average <= 0) continue;
|
|
2878
|
+
if (!intervals.every((value) => Math.abs(value - average) <= average * NET_LIMITS.pollIntervalTolerance)) continue;
|
|
2879
|
+
polling.push({ groupKey, count: sorted.length, intervalMs: Math.round(average), firstSeq: sorted[0].seq, lastSeq: sorted[sorted.length - 1].seq });
|
|
2880
|
+
}
|
|
2881
|
+
return polling.slice(0, 20);
|
|
2882
|
+
}
|
|
2883
|
+
|
|
2884
|
+
/** §5.5 重试/重复:键用未脱敏 URL 的 urlHash(R1-9)。 */
|
|
2885
|
+
export function detectRetries(events) {
|
|
2886
|
+
const groups = new Map();
|
|
2887
|
+
for (const event of events) {
|
|
2888
|
+
if (event.kind !== 'http' || event.phase !== 'response' || !event.url) continue;
|
|
2889
|
+
const key = (event.method || 'GET') + ' ' + (event.urlHash || event.url);
|
|
2890
|
+
const list = groups.get(key) || [];
|
|
2891
|
+
list.push(event);
|
|
2892
|
+
groups.set(key, list);
|
|
2893
|
+
}
|
|
2894
|
+
const patterns = [];
|
|
2895
|
+
for (const [groupKey, list] of groups.entries()) {
|
|
2896
|
+
if (list.length < 2) continue;
|
|
2897
|
+
const sorted = [...list].sort((left, right) => left.ts.wallMs - right.ts.wallMs);
|
|
2898
|
+
let pattern = null;
|
|
2899
|
+
for (let index = 1; index < sorted.length; index += 1) {
|
|
2900
|
+
const previous = sorted[index - 1];
|
|
2901
|
+
const current = sorted[index];
|
|
2902
|
+
if (current.ts.wallMs - previous.ts.wallMs > NET_LIMITS.retryWindowMs) continue;
|
|
2903
|
+
if (previous.failed || (Number.isInteger(previous.status) && previous.status >= 500)) pattern = 'retry';
|
|
2904
|
+
else if (pattern === null) pattern = 'duplicate';
|
|
2905
|
+
}
|
|
2906
|
+
if (pattern) patterns.push({ groupKey, pattern, count: sorted.length, seqs: sorted.map((event) => event.seq).slice(0, 20) });
|
|
2907
|
+
}
|
|
2908
|
+
return patterns.slice(0, 20);
|
|
2909
|
+
}
|
|
2910
|
+
|
|
2911
|
+
function buildCausality(store, events, { includeTemporal = false } = {}) {
|
|
2912
|
+
const causality = [];
|
|
2913
|
+
const seqSet = new Set(events.map((event) => event.seq));
|
|
2914
|
+
for (const event of events) {
|
|
2915
|
+
for (const link of (store.links.get(event.seq) || [])) {
|
|
2916
|
+
if (link.stepId) causality.push({ seq: event.seq, parentSeq: null, basis: 'explicit', stepId: link.stepId });
|
|
2917
|
+
}
|
|
2918
|
+
if (event.redirect) causality.push({ seq: event.seq, parentSeq: null, basis: 'redirect', url: event.redirect.from });
|
|
2919
|
+
if (event.initiator && event.initiator.requestId) {
|
|
2920
|
+
const parent = store.events.find((item) => item.requestId === event.initiator.requestId);
|
|
2921
|
+
if (parent && seqSet.has(parent.seq)) causality.push({ seq: event.seq, parentSeq: parent.seq, basis: 'initiator' });
|
|
2922
|
+
}
|
|
2923
|
+
}
|
|
2924
|
+
if (includeTemporal) {
|
|
2925
|
+
const ordered = [...events].sort((left, right) => left.seq - right.seq);
|
|
2926
|
+
for (let index = 1; index < ordered.length; index += 1) {
|
|
2927
|
+
causality.push({ seq: ordered[index].seq, parentSeq: ordered[index - 1].seq, basis: 'temporal' });
|
|
2928
|
+
}
|
|
2929
|
+
}
|
|
2930
|
+
return causality;
|
|
2931
|
+
}
|
|
2932
|
+
|
|
2933
|
+
|
|
2934
|
+
/** §6.3 观察序列(`states` 只记变化;这里给出每一步的可观测状态,便于断言与排错)。 */
|
|
2935
|
+
function businessObservations(store, step, events) {
|
|
2936
|
+
const path = (step && step.businessStatusPath) || (store && store.config ? store.config.businessStatusPath : null) || null;
|
|
2937
|
+
const out = [];
|
|
2938
|
+
for (const event of events) {
|
|
2939
|
+
if (event.kind !== 'http' || !['response', 'finished', 'failed'].includes(event.phase)) continue;
|
|
2940
|
+
let code = event.business ? event.business.businessCode : null;
|
|
2941
|
+
if (code === null && store && event.requestId) {
|
|
2942
|
+
const stored = store.readBody({
|
|
2943
|
+
targetId: event.targetId, cdpSessionId: event.cdpSessionId, requestId: event.requestId, hopId: event.hopId, kind: 'response',
|
|
2944
|
+
});
|
|
2945
|
+
if (stored && stored.state === 'captured' && !stored.payloadOmitted) {
|
|
2946
|
+
let parsed = null;
|
|
2947
|
+
try { parsed = JSON.parse(stored.data); } catch { parsed = null; }
|
|
2948
|
+
code = extractBusinessCode(parsed, path).businessCode;
|
|
2949
|
+
}
|
|
2950
|
+
}
|
|
2951
|
+
out.push({ seq: event.seq, wallMs: event.ts.wallMs, status: event.status, businessCode: code, businessCodePath: path });
|
|
2952
|
+
if (out.length >= NET_LIMITS.objectEvents) break;
|
|
2953
|
+
}
|
|
2954
|
+
return out;
|
|
2955
|
+
}
|
|
2956
|
+
|
|
2957
|
+
function stepView(store, step) {
|
|
2958
|
+
const events = stepEvents(store, step);
|
|
2959
|
+
return {
|
|
2960
|
+
// `stepId` is the canonical key; `id` is kept as an alias for callers that use it.
|
|
2961
|
+
stepId: step.stepId,
|
|
2962
|
+
id: step.stepId,
|
|
2963
|
+
name: step.name,
|
|
2964
|
+
labels: step.labels,
|
|
2965
|
+
state: step.open ? 'open' : 'closed',
|
|
2966
|
+
window: { ...step.window },
|
|
2967
|
+
fromSeq: step.fromSeq,
|
|
2968
|
+
toSeq: step.toSeq,
|
|
2969
|
+
objectRules: step.objectRules,
|
|
2970
|
+
businessStatusPath: step.businessStatusPath,
|
|
2971
|
+
objects: extractObjects(store, step, events),
|
|
2972
|
+
states: businessStates(store, step, events),
|
|
2973
|
+
observations: businessObservations(store, step, events),
|
|
2974
|
+
counters: { events: events.length },
|
|
2975
|
+
};
|
|
2976
|
+
}
|
|
2977
|
+
|
|
2978
|
+
/** `browser_network_trace` 执行体(§2.4)。 */
|
|
2979
|
+
export function traceNetwork(store, params = {}) {
|
|
2980
|
+
assertKnownKeys(params, ['sessionId', 'action', 'stepId', 'name', 'labels', 'window', 'objectRules',
|
|
2981
|
+
'correlationRules', 'businessStatusPath', 'mark', 'link', 'query', 'includeTemporal',
|
|
2982
|
+
'seq', 'requestId', 'evidenceId',
|
|
2983
|
+
// §2.4 also allows the query knobs at the top level (`{action:'query', limit, sinceMs}`).
|
|
2984
|
+
'limit', 'sinceMs'], 'trace');
|
|
2985
|
+
assertSession(store, params.sessionId);
|
|
2986
|
+
const action = params.action;
|
|
2987
|
+
if (!NET_TRAIL_ACTIONS.includes(action)) {
|
|
2988
|
+
throw new BrowserError('NET_INVALID_ARGUMENT', 'trace.action 不合法: ' + String(action), { field: 'action', allowed: [...NET_TRAIL_ACTIONS] });
|
|
2989
|
+
}
|
|
2990
|
+
const base = { ok: true, action, sessionId: store.session ? store.session.id : null };
|
|
2991
|
+
if (action === 'begin-step') {
|
|
2992
|
+
const step = store.beginStep({
|
|
2993
|
+
stepId: params.stepId, name: params.name, labels: params.labels, window: params.window,
|
|
2994
|
+
businessStatusPath: params.businessStatusPath, objectRules: params.objectRules, correlationRules: params.correlationRules,
|
|
2995
|
+
});
|
|
2996
|
+
return { ...base, steps: [stepView(store, step)], events: [], objects: [], states: [], causality: [],
|
|
2997
|
+
evidence: evidenceBlock(store, 'trace', { fromSeq: step.fromSeq, toSeq: store.seq }) };
|
|
2998
|
+
}
|
|
2999
|
+
if (action === 'end-step') {
|
|
3000
|
+
if (!params.stepId) throw new BrowserError('NET_INVALID_ARGUMENT', 'end-step 需要 stepId');
|
|
3001
|
+
const existing = store.steps.get(String(params.stepId));
|
|
3002
|
+
if (existing && params.objectRules && existing.objectRules.length === 0) existing.objectRules = validateObjectRules(params.objectRules);
|
|
3003
|
+
if (existing && params.businessStatusPath) existing.businessStatusPath = truncateBytes(String(params.businessStatusPath), 256);
|
|
3004
|
+
const step = store.endStep({ stepId: params.stepId, window: params.window });
|
|
3005
|
+
const stepEventsList = stepEvents(store, step);
|
|
3006
|
+
const view = stepView(store, step);
|
|
3007
|
+
return {
|
|
3008
|
+
...base,
|
|
3009
|
+
steps: [view],
|
|
3010
|
+
// The closed step's own events/objects/states are returned inline so a caller does not have
|
|
3011
|
+
// to issue a second `query` (C26).
|
|
3012
|
+
events: stepEventsList.slice(0, NET_LIMITS.eventPageLimit).map((event) => projectSummary(store, event)),
|
|
3013
|
+
objects: view.objects,
|
|
3014
|
+
states: view.states,
|
|
3015
|
+
observations: view.observations,
|
|
3016
|
+
causality: buildCausality(store, stepEventsList, { includeTemporal: params.includeTemporal === true }),
|
|
3017
|
+
evidence: evidenceBlock(store, 'trace', { fromSeq: step.fromSeq, toSeq: step.toSeq || store.seq }),
|
|
3018
|
+
};
|
|
3019
|
+
}
|
|
3020
|
+
if (action === 'mark') {
|
|
3021
|
+
const mark = params.mark || {};
|
|
3022
|
+
const event = store.mark({
|
|
3023
|
+
kind: mark.kind || 'note', text: mark.text, tool: mark.tool, actionId: mark.actionId,
|
|
3024
|
+
stepId: mark.stepId || params.stepId,
|
|
3025
|
+
});
|
|
3026
|
+
return { ...base, events: event ? [projectSummary(store, event)] : [], steps: [], objects: [], states: [], causality: [],
|
|
3027
|
+
evidence: evidenceBlock(store, 'trace', { fromSeq: event ? event.seq : store.seq, toSeq: store.seq }) };
|
|
3028
|
+
}
|
|
3029
|
+
if (action === 'link') {
|
|
3030
|
+
// §2.4 lists both a nested `link` object and top-level `seq`/`requestId`; accept either form.
|
|
3031
|
+
const link = params.link || {};
|
|
3032
|
+
const linked = store.link({
|
|
3033
|
+
seq: Number.isInteger(link.seq) ? link.seq : (Number.isInteger(params.seq) ? params.seq : null),
|
|
3034
|
+
requestId: link.requestId || params.requestId || null,
|
|
3035
|
+
stepId: link.stepId || params.stepId || null,
|
|
3036
|
+
evidenceId: link.evidenceId || params.evidenceId || null,
|
|
3037
|
+
});
|
|
3038
|
+
const event = store.events.find((item) => item.seq === linked.seq);
|
|
3039
|
+
return { ...base, link: linked, events: event ? [projectSummary(store, event)] : [], steps: [], objects: [], states: [], causality: [],
|
|
3040
|
+
evidence: evidenceBlock(store, 'trace', { fromSeq: linked.seq, toSeq: linked.seq }) };
|
|
3041
|
+
}
|
|
3042
|
+
if (action === 'window') {
|
|
3043
|
+
const range = params.window && typeof params.window === 'object' ? params.window : null;
|
|
3044
|
+
const events = range
|
|
3045
|
+
? store.events.filter((event) => (Number.isFinite(range.fromWallMs) ? event.ts.wallMs >= range.fromWallMs : true)
|
|
3046
|
+
&& (Number.isFinite(range.toWallMs) ? event.ts.wallMs <= range.toWallMs : true))
|
|
3047
|
+
: [];
|
|
3048
|
+
return {
|
|
3049
|
+
...base,
|
|
3050
|
+
windows: [...store.steps.values()].map((step) => ({
|
|
3051
|
+
stepId: step.stepId, name: step.name, open: step.open, window: { ...step.window }, fromSeq: step.fromSeq, toSeq: step.toSeq,
|
|
3052
|
+
})),
|
|
3053
|
+
window: range ? { fromWallMs: range.fromWallMs ?? null, toWallMs: range.toWallMs ?? null, matched: events.length } : null,
|
|
3054
|
+
steps: [...store.steps.values()].map((step) => stepView(store, step)),
|
|
3055
|
+
events: events.slice(0, NET_LIMITS.eventPageLimit).map((event) => projectSummary(store, event)),
|
|
3056
|
+
evidence: evidenceBlock(store, 'trace'),
|
|
3057
|
+
};
|
|
3058
|
+
}
|
|
3059
|
+
if (action === 'reset') {
|
|
3060
|
+
store.steps.clear();
|
|
3061
|
+
store.links.clear();
|
|
3062
|
+
return { ...base, reset: true, evidence: evidenceBlock(store, 'trace') };
|
|
3063
|
+
}
|
|
3064
|
+
const query = params.query || {};
|
|
3065
|
+
assertKnownKeys(query, ['stepId', 'sinceMs', 'limit'], 'query');
|
|
3066
|
+
const requestedLimit = query.limit === undefined ? params.limit : query.limit;
|
|
3067
|
+
const limit = clampInt(requestedLimit === undefined ? NET_LIMITS.eventPageDefault : requestedLimit, 1, NET_LIMITS.eventPageLimit);
|
|
3068
|
+
const onlyStep = query.stepId ? String(query.stepId) : (params.stepId ? String(params.stepId) : null);
|
|
3069
|
+
const sinceMs = Number.isFinite(query.sinceMs) ? query.sinceMs : (Number.isFinite(params.sinceMs) ? params.sinceMs : null);
|
|
3070
|
+
const steps = onlyStep ? [store.steps.get(onlyStep)].filter(Boolean) : [...store.steps.values()];
|
|
3071
|
+
if (onlyStep && steps.length === 0) throw new BrowserError('NET_EVENT_NOT_FOUND', '步骤不存在: ' + onlyStep, { stepId: onlyStep });
|
|
3072
|
+
const views = [];
|
|
3073
|
+
let truncated = false;
|
|
3074
|
+
for (const step of steps) {
|
|
3075
|
+
const events = stepEvents(store, step).filter((event) => sinceMs === null || event.ts.wallMs >= sinceMs);
|
|
3076
|
+
const objects = extractObjects(store, step, events);
|
|
3077
|
+
const states = businessStates(store, step, events);
|
|
3078
|
+
const evidence = events
|
|
3079
|
+
.flatMap((event) => {
|
|
3080
|
+
const projection = store.linkProjection ? store.linkProjection(event) : { evidenceIds: event.evidenceIds };
|
|
3081
|
+
return projection.evidenceIds.map((evidenceId) => ({ evidenceId, seqs: [event.seq], kind: 'event' }));
|
|
3082
|
+
});
|
|
3083
|
+
const causality = buildCausality(store, events, { includeTemporal: params.includeTemporal === true });
|
|
3084
|
+
const closedAt = step.open || !Number.isFinite(step.window.toWallMs) ? null : step.window.toWallMs;
|
|
3085
|
+
const inStepUrls = new Set(events.map((event) => event.url).filter(Boolean));
|
|
3086
|
+
const afterClose = closedAt === null ? 0
|
|
3087
|
+
: store.events.filter((event) => event.ts.wallMs > closedAt && event.url && inStepUrls.has(event.url)).length;
|
|
3088
|
+
if (events.length > limit) truncated = true;
|
|
3089
|
+
views.push({
|
|
3090
|
+
stepId: step.stepId,
|
|
3091
|
+
id: step.stepId,
|
|
3092
|
+
name: step.name,
|
|
3093
|
+
state: step.open ? 'open' : 'closed',
|
|
3094
|
+
window: { ...step.window },
|
|
3095
|
+
fromSeq: step.fromSeq,
|
|
3096
|
+
toSeq: step.toSeq,
|
|
3097
|
+
counters: {
|
|
3098
|
+
events: events.length,
|
|
3099
|
+
http: events.filter((event) => event.kind === 'http').length,
|
|
3100
|
+
ws: events.filter((event) => event.kind === 'ws').length,
|
|
3101
|
+
sse: events.filter((event) => event.kind === 'sse').length,
|
|
3102
|
+
failures: events.filter((event) => event.failed).length,
|
|
3103
|
+
asyncAfterClose: afterClose,
|
|
3104
|
+
},
|
|
3105
|
+
objects: objects.map((object) => ({
|
|
3106
|
+
name: object.name,
|
|
3107
|
+
value: object.value,
|
|
3108
|
+
source: { seq: object.firstSeq, requestId: (store.events.find((event) => event.seq === object.firstSeq) || {}).requestId || null, from: object.from, path: object.path },
|
|
3109
|
+
propagation: object.propagation,
|
|
3110
|
+
})),
|
|
3111
|
+
states,
|
|
3112
|
+
observations: businessObservations(store, step, events),
|
|
3113
|
+
evidence,
|
|
3114
|
+
causality,
|
|
3115
|
+
events: events.slice(0, limit).map((event) => projectSummary(store, event)),
|
|
3116
|
+
});
|
|
3117
|
+
}
|
|
3118
|
+
const allEvents = steps.flatMap((step) => stepEvents(store, step));
|
|
3119
|
+
return {
|
|
3120
|
+
...base,
|
|
3121
|
+
steps: views,
|
|
3122
|
+
events: allEvents.slice(0, limit).map((event) => projectSummary(store, event)),
|
|
3123
|
+
objects: views.flatMap((view) => view.objects),
|
|
3124
|
+
states: views.flatMap((view) => view.states),
|
|
3125
|
+
causality: views.flatMap((view) => view.causality),
|
|
3126
|
+
polling: detectPolling(allEvents),
|
|
3127
|
+
patterns: detectRetries(allEvents),
|
|
3128
|
+
async: views.flatMap((view) => {
|
|
3129
|
+
const step = store.steps.get(view.id);
|
|
3130
|
+
if (!step || step.open || !Number.isFinite(step.window.toWallMs)) return [];
|
|
3131
|
+
const closedAt = step.window.toWallMs;
|
|
3132
|
+
const urls = new Set(view.events.map((event) => event.url).filter(Boolean));
|
|
3133
|
+
return store.events
|
|
3134
|
+
.filter((event) => event.ts.wallMs > closedAt && event.url && urls.has(event.url))
|
|
3135
|
+
.slice(0, 20)
|
|
3136
|
+
.map((event) => ({ seq: event.seq, stepId: view.id, delayMs: Math.round(event.ts.wallMs - closedAt) }));
|
|
3137
|
+
}),
|
|
3138
|
+
truncated,
|
|
3139
|
+
limits: { steps: NET_LIMITS.steps, objects: NET_LIMITS.objectRules, events: limit },
|
|
3140
|
+
evidence: evidenceBlock(store, 'trace', { truncated }),
|
|
3141
|
+
};
|
|
3142
|
+
}
|
|
3143
|
+
|
|
3144
|
+
/* ------------------------------------------------------------------ */
|
|
3145
|
+
/* 控制:规则 / 网络条件 / hold(§2.5 / §7 + R1-7 / R1-8 / R1-13) */
|
|
3146
|
+
/* ------------------------------------------------------------------ */
|
|
3147
|
+
|
|
3148
|
+
const RULE_FIELDS = Object.freeze(['id', 'pattern', 'behavior']);
|
|
3149
|
+
const RULE_BEHAVIOR_FIELDS = Object.freeze(['kind', 'headers', 'body', 'status', 'delayMs', 'fromRequestId', 'errorReason', 'url']);
|
|
3150
|
+
|
|
3151
|
+
export function validateRule(input) {
|
|
3152
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new BrowserError('NET_RULE_INVALID', 'rule 必须是对象');
|
|
3153
|
+
assertKnownKeys(input, RULE_FIELDS, 'rule', 'NET_RULE_INVALID');
|
|
3154
|
+
const pattern = input.pattern;
|
|
3155
|
+
if (!pattern || typeof pattern !== 'object' || Array.isArray(pattern)) throw new BrowserError('NET_RULE_INVALID', 'rule 缺少 pattern');
|
|
3156
|
+
assertKnownKeys(pattern, ['urlPattern', 'resourceType', 'method'], 'rule.pattern', 'NET_RULE_INVALID');
|
|
3157
|
+
if (typeof pattern.urlPattern !== 'string' || pattern.urlPattern.trim() === '' || pattern.urlPattern.length > 512) {
|
|
3158
|
+
throw new BrowserError('NET_RULE_INVALID', 'rule.pattern.urlPattern 必填且 ≤512 字符');
|
|
3159
|
+
}
|
|
3160
|
+
const behavior = input.behavior;
|
|
3161
|
+
if (!behavior || typeof behavior !== 'object' || Array.isArray(behavior)) throw new BrowserError('NET_RULE_INVALID', 'rule 缺少 behavior');
|
|
3162
|
+
assertKnownKeys(behavior, RULE_BEHAVIOR_FIELDS, 'rule.behavior', 'NET_RULE_INVALID');
|
|
3163
|
+
if (!NET_RULE_KINDS.includes(behavior.kind)) {
|
|
3164
|
+
throw new BrowserError('NET_RULE_INVALID', 'rule.behavior.kind 不合法: ' + String(behavior.kind), { allowed: [...NET_RULE_KINDS] });
|
|
3165
|
+
}
|
|
3166
|
+
if (behavior.kind === 'delay' && (!Number.isInteger(behavior.delayMs) || behavior.delayMs < 0 || behavior.delayMs > 60000)) {
|
|
3167
|
+
throw new BrowserError('NET_RULE_INVALID', 'delay 规则需要 delayMs(0–60000 整数)');
|
|
3168
|
+
}
|
|
3169
|
+
if (['fulfill', 'modify-response'].includes(behavior.kind) && behavior.status !== undefined && behavior.status !== null
|
|
3170
|
+
&& (!Number.isInteger(behavior.status) || behavior.status < 100 || behavior.status > 599)) {
|
|
3171
|
+
throw new BrowserError('NET_RULE_INVALID', 'status 必须是 100–599 整数');
|
|
3172
|
+
}
|
|
3173
|
+
if (behavior.kind === 'modify-request' && behavior.url !== undefined && behavior.url !== null
|
|
3174
|
+
&& (typeof behavior.url !== 'string' || !/^https?:\/\//i.test(behavior.url))) {
|
|
3175
|
+
throw new BrowserError('NET_RULE_INVALID', 'modify-request.url 必须是 http(s) 绝对地址');
|
|
3176
|
+
}
|
|
3177
|
+
let headers = null;
|
|
3178
|
+
if (behavior.headers !== undefined && behavior.headers !== null) {
|
|
3179
|
+
if (typeof behavior.headers !== 'object' || Array.isArray(behavior.headers)) throw new BrowserError('NET_RULE_INVALID', 'behavior.headers 必须是对象');
|
|
3180
|
+
const entries = Object.entries(behavior.headers);
|
|
3181
|
+
if (entries.length > 32) throw new BrowserError('NET_RULE_INVALID', 'behavior.headers 最多 32 项');
|
|
3182
|
+
headers = {};
|
|
3183
|
+
for (const [name, value] of entries) {
|
|
3184
|
+
if (!/^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/.test(name)) throw new BrowserError('NET_RULE_INVALID', '头部名不合法: ' + name);
|
|
3185
|
+
const text = String(value);
|
|
3186
|
+
if (Buffer.byteLength(text, 'utf8') > 4096) throw new BrowserError('NET_RULE_INVALID', '头部值超过 4096 字节: ' + name);
|
|
3187
|
+
headers[name] = text;
|
|
3188
|
+
}
|
|
3189
|
+
}
|
|
3190
|
+
let body = null;
|
|
3191
|
+
if (behavior.body !== undefined && behavior.body !== null) {
|
|
3192
|
+
if (typeof behavior.body !== 'string') throw new BrowserError('NET_RULE_INVALID', 'behavior.body 必须是字符串');
|
|
3193
|
+
if (Buffer.byteLength(behavior.body, 'utf8') > NET_LIMITS.ruleBodyBytes) {
|
|
3194
|
+
throw new BrowserError('NET_RULE_INVALID', 'behavior.body 超过 ' + NET_LIMITS.ruleBodyBytes + ' 字节');
|
|
3195
|
+
}
|
|
3196
|
+
body = behavior.body;
|
|
3197
|
+
}
|
|
3198
|
+
return {
|
|
3199
|
+
id: input.id ? truncateBytes(String(input.id), 64) : null,
|
|
3200
|
+
pattern: {
|
|
3201
|
+
urlPattern: pattern.urlPattern,
|
|
3202
|
+
resourceType: pattern.resourceType ? truncateBytes(String(pattern.resourceType), 32) : null,
|
|
3203
|
+
method: pattern.method ? truncateBytes(String(pattern.method).toUpperCase(), 16) : null,
|
|
3204
|
+
},
|
|
3205
|
+
behavior: {
|
|
3206
|
+
kind: behavior.kind,
|
|
3207
|
+
headers,
|
|
3208
|
+
body,
|
|
3209
|
+
url: behavior.url ? truncateBytes(String(behavior.url), NET_LIMITS.urlBytes) : null,
|
|
3210
|
+
status: Number.isInteger(behavior.status) ? behavior.status : null,
|
|
3211
|
+
delayMs: Number.isInteger(behavior.delayMs) ? behavior.delayMs : null,
|
|
3212
|
+
fromRequestId: behavior.fromRequestId ? truncateBytes(String(behavior.fromRequestId), 128) : null,
|
|
3213
|
+
errorReason: behavior.errorReason ? truncateBytes(String(behavior.errorReason), 32) : null,
|
|
3214
|
+
},
|
|
3215
|
+
};
|
|
3216
|
+
}
|
|
3217
|
+
|
|
3218
|
+
export function validateThen(then) {
|
|
3219
|
+
if (then === undefined || then === null) return { kind: 'continue', headers: null, body: null, status: null, errorReason: null };
|
|
3220
|
+
assertKnownKeys(then, ['kind', 'headers', 'body', 'status', 'errorReason'], 'then', 'NET_RULE_INVALID');
|
|
3221
|
+
const kind = then.kind === undefined ? 'continue' : then.kind;
|
|
3222
|
+
if (!NET_THEN_KINDS.includes(kind)) throw new BrowserError('NET_RULE_INVALID', 'then.kind 不合法: ' + String(kind), { allowed: [...NET_THEN_KINDS] });
|
|
3223
|
+
return {
|
|
3224
|
+
kind,
|
|
3225
|
+
headers: then.headers && typeof then.headers === 'object'
|
|
3226
|
+
? Object.fromEntries(Object.entries(then.headers).slice(0, 32).map(([key, value]) => [String(key), truncateBytes(String(value), 4096)]))
|
|
3227
|
+
: null,
|
|
3228
|
+
body: typeof then.body === 'string' ? truncateBytes(then.body, NET_LIMITS.ruleBodyBytes) : null,
|
|
3229
|
+
status: Number.isInteger(then.status) ? then.status : null,
|
|
3230
|
+
errorReason: then.errorReason ? truncateBytes(String(then.errorReason), 32) : null,
|
|
3231
|
+
};
|
|
3232
|
+
}
|
|
3233
|
+
|
|
3234
|
+
/**
|
|
3235
|
+
* `fetch()` from page script is reported by Chromium as `XHR`, while humans (and the docs) call it
|
|
3236
|
+
* `Fetch`. Both names match each other so a rule written either way behaves the same; any other
|
|
3237
|
+
* resource type is still strict. A pattern may also list an array of accepted types.
|
|
3238
|
+
*/
|
|
3239
|
+
const RESOURCE_TYPE_ALIASES = Object.freeze({
|
|
3240
|
+
fetch: ['fetch', 'xhr'],
|
|
3241
|
+
xhr: ['xhr', 'fetch'],
|
|
3242
|
+
});
|
|
3243
|
+
|
|
3244
|
+
function resourceTypeMatches(patternType, actualType) {
|
|
3245
|
+
if (patternType === undefined || patternType === null || patternType === '') return true;
|
|
3246
|
+
const wanted = Array.isArray(patternType) ? patternType.map((item) => String(item).toLowerCase()) : [String(patternType).toLowerCase()];
|
|
3247
|
+
const actual = String(actualType || '').toLowerCase();
|
|
3248
|
+
for (const name of wanted) {
|
|
3249
|
+
const accepted = RESOURCE_TYPE_ALIASES[name] || [name];
|
|
3250
|
+
if (accepted.includes(actual)) return true;
|
|
3251
|
+
}
|
|
3252
|
+
return false;
|
|
3253
|
+
}
|
|
3254
|
+
|
|
3255
|
+
export function matchRule(rule, { url, resourceType, method } = {}) {
|
|
3256
|
+
if (!rule || !rule.pattern) return false;
|
|
3257
|
+
if (!matchUrlPattern(rule.pattern.urlPattern, url || '')) return false;
|
|
3258
|
+
if (!resourceTypeMatches(rule.pattern.resourceType, resourceType)) return false;
|
|
3259
|
+
if (rule.pattern.method && String(rule.pattern.method).toUpperCase() !== String(method || '').toUpperCase()) return false;
|
|
3260
|
+
return true;
|
|
3261
|
+
}
|
|
3262
|
+
|
|
3263
|
+
export function firstMatchingRule(rules, target) {
|
|
3264
|
+
for (const rule of rules) if (matchRule(rule, target)) return rule;
|
|
3265
|
+
return null;
|
|
3266
|
+
}
|
|
3267
|
+
|
|
3268
|
+
/** §7.3 / R1-8:唯一一份 `Fetch.enable` patterns(Document 守卫 + 活动规则)。 */
|
|
3269
|
+
export function buildFetchPatterns({ documentPatterns = [{ urlPattern: '*', resourceType: 'Document', requestStage: 'Request' }], rules = [] } = {}) {
|
|
3270
|
+
const patterns = [];
|
|
3271
|
+
const seen = new Set();
|
|
3272
|
+
const push = (urlPattern, resourceType, requestStage = 'Request') => {
|
|
3273
|
+
const key = String(urlPattern) + '\u0000' + String(resourceType || '') + '\u0000' + requestStage;
|
|
3274
|
+
if (seen.has(key)) return;
|
|
3275
|
+
seen.add(key);
|
|
3276
|
+
patterns.push({ urlPattern, resourceType, requestStage });
|
|
3277
|
+
};
|
|
3278
|
+
for (const pattern of documentPatterns) push(pattern.urlPattern, pattern.resourceType, pattern.requestStage || 'Request');
|
|
3279
|
+
for (const rule of rules) {
|
|
3280
|
+
push(rule.pattern.urlPattern, rule.pattern.resourceType || undefined,
|
|
3281
|
+
rule.behavior.kind === 'modify-response' ? 'Response' : 'Request');
|
|
3282
|
+
}
|
|
3283
|
+
return patterns;
|
|
3284
|
+
}
|
|
3285
|
+
|
|
3286
|
+
/** §7.3 / R1-8 分流决策:Document 守卫优先,其次首条命中规则,最后 continue。 */
|
|
3287
|
+
export function decidePausedAction({ resourceType, request, rules } = {}) {
|
|
3288
|
+
if (String(resourceType || '') === 'Document') return { action: 'guard' };
|
|
3289
|
+
const rule = firstMatchingRule(rules || [], { url: request && request.url, method: request && request.method, resourceType });
|
|
3290
|
+
if (!rule) return { action: 'continue' };
|
|
3291
|
+
return rule.behavior.kind === 'hold' ? { action: 'hold', rule } : { action: 'rule', rule };
|
|
3292
|
+
}
|
|
3293
|
+
|
|
3294
|
+
/** R1-13:throttle/offline 组合状态 → `Network.emulateNetworkConditions`(Kbps = 1024 bit/s)。 */
|
|
3295
|
+
export function conditionParams({ offline = false, latencyMs = 0, downloadKbps = 0, uploadKbps = 0 } = {}) {
|
|
3296
|
+
if (!Number.isFinite(latencyMs) || latencyMs < 0 || latencyMs > 60000) {
|
|
3297
|
+
throw new BrowserError('NET_INVALID_ARGUMENT', 'latencyMs 必须在 0–60000', { field: 'latencyMs' });
|
|
3298
|
+
}
|
|
3299
|
+
const toBps = (kbps, label) => {
|
|
3300
|
+
if (!Number.isFinite(kbps) || kbps < 0 || kbps > 1000000) {
|
|
3301
|
+
throw new BrowserError('NET_INVALID_ARGUMENT', label + ' 必须在 0–1000000', { field: label });
|
|
3302
|
+
}
|
|
3303
|
+
return kbps === 0 ? -1 : Math.round((kbps * 1024) / 8);
|
|
3304
|
+
};
|
|
3305
|
+
if (offline) {
|
|
3306
|
+
return { offline: true, latency: Math.round(latencyMs), downloadThroughput: 0, uploadThroughput: 0 };
|
|
3307
|
+
}
|
|
3308
|
+
return {
|
|
3309
|
+
offline: false,
|
|
3310
|
+
latency: Math.round(latencyMs),
|
|
3311
|
+
downloadThroughput: toBps(downloadKbps, 'downloadKbps'),
|
|
3312
|
+
uploadThroughput: toBps(uploadKbps, 'uploadKbps'),
|
|
3313
|
+
};
|
|
3314
|
+
}
|
|
3315
|
+
|
|
3316
|
+
export const NETWORK_UNTHROTTLED = Object.freeze({ offline: false, latency: 0, downloadThroughput: -1, uploadThroughput: -1 });
|
|
3317
|
+
|
|
3318
|
+
/** 控制面状态(每个 Runtime 一个)。定时器由 Host 驱动(`expiredHolds`)。 */
|
|
3319
|
+
export class ControlState {
|
|
3320
|
+
constructor({ now = () => Date.now(), holdTimeoutMs = NET_LIMITS.holdTimeoutMs } = {}) {
|
|
3321
|
+
this.now = now;
|
|
3322
|
+
this.holdTimeoutMs = holdTimeoutMs;
|
|
3323
|
+
this.rules = [];
|
|
3324
|
+
this.nextId = 1;
|
|
3325
|
+
this.held = new Map();
|
|
3326
|
+
this.condition = { offline: false, latencyMs: 0, downloadKbps: 0, uploadKbps: 0 };
|
|
3327
|
+
this.hits = new Map();
|
|
3328
|
+
this.resumed = 0;
|
|
3329
|
+
this.holdTimeouts = 0;
|
|
3330
|
+
this.heldOverflow = 0;
|
|
3331
|
+
this.responseModification = null;
|
|
3332
|
+
this.applyFailures = [];
|
|
3333
|
+
}
|
|
3334
|
+
|
|
3335
|
+
addRule(input) {
|
|
3336
|
+
const rule = validateRule(input);
|
|
3337
|
+
if (rule.id === null) {
|
|
3338
|
+
let candidate;
|
|
3339
|
+
do { candidate = 'rule-' + this.nextId; this.nextId += 1; } while (this.rules.some((item) => item.id === candidate));
|
|
3340
|
+
rule.id = candidate;
|
|
3341
|
+
}
|
|
3342
|
+
if (this.rules.some((item) => item.id === rule.id)) {
|
|
3343
|
+
throw new BrowserError('NET_RULE_CONFLICT', '规则 id 已存在: ' + rule.id, { ruleId: rule.id });
|
|
3344
|
+
}
|
|
3345
|
+
if (this.rules.length >= NET_LIMITS.rules) {
|
|
3346
|
+
throw new BrowserError('NET_QUOTA_EXCEEDED', '规则数超出上限 ' + NET_LIMITS.rules, { max: NET_LIMITS.rules });
|
|
3347
|
+
}
|
|
3348
|
+
if (rule.behavior.kind === 'modify-response' && this.responseModification === false) {
|
|
3349
|
+
throw new BrowserError('NET_CONTROL_UNAVAILABLE', '当前 CDP 不支持 Fetch.continueResponse,无法做响应修改', { capability: 'responseModification' });
|
|
3350
|
+
}
|
|
3351
|
+
this.rules.push(rule);
|
|
3352
|
+
return rule;
|
|
3353
|
+
}
|
|
3354
|
+
|
|
3355
|
+
removeRule(id) {
|
|
3356
|
+
const index = this.rules.findIndex((item) => item.id === String(id));
|
|
3357
|
+
if (index === -1) throw new BrowserError('NET_RULE_INVALID', '规则不存在: ' + String(id), { ruleId: String(id) });
|
|
3358
|
+
const [rule] = this.rules.splice(index, 1);
|
|
3359
|
+
this.hits.delete(rule.id);
|
|
3360
|
+
return rule;
|
|
3361
|
+
}
|
|
3362
|
+
|
|
3363
|
+
clearRules() {
|
|
3364
|
+
const count = this.rules.length;
|
|
3365
|
+
this.rules = [];
|
|
3366
|
+
this.hits.clear();
|
|
3367
|
+
return { cleared: count };
|
|
3368
|
+
}
|
|
3369
|
+
|
|
3370
|
+
noteHit(ruleId) { if (ruleId) this.hits.set(ruleId, (this.hits.get(ruleId) || 0) + 1); }
|
|
3371
|
+
|
|
3372
|
+
listRules() { return this.rules.map((rule) => ({ ...rule, hits: this.hits.get(rule.id) || 0 })); }
|
|
3373
|
+
|
|
3374
|
+
/** 组合状态:throttle 与 offline 互不覆盖(R1-13)。 */
|
|
3375
|
+
setThrottle({ latencyMs = 0, downloadKbps = 0, uploadKbps = 0 } = {}) {
|
|
3376
|
+
this.condition = { ...this.condition, latencyMs, downloadKbps, uploadKbps };
|
|
3377
|
+
return this.conditions();
|
|
3378
|
+
}
|
|
3379
|
+
|
|
3380
|
+
setOffline(offline) {
|
|
3381
|
+
this.condition = { ...this.condition, offline: offline === true };
|
|
3382
|
+
return this.conditions();
|
|
3383
|
+
}
|
|
3384
|
+
|
|
3385
|
+
conditions() { return conditionParams(this.condition); }
|
|
3386
|
+
|
|
3387
|
+
resetConditions() {
|
|
3388
|
+
this.condition = { offline: false, latencyMs: 0, downloadKbps: 0, uploadKbps: 0 };
|
|
3389
|
+
return this.conditions();
|
|
3390
|
+
}
|
|
3391
|
+
|
|
3392
|
+
holdRequest({ requestId, url = null, method = null, resourceType = null, ruleId = null } = {}) {
|
|
3393
|
+
if (!requestId) throw new BrowserError('NET_INVALID_ARGUMENT', 'hold 需要 requestId');
|
|
3394
|
+
if (this.held.size >= NET_LIMITS.held) {
|
|
3395
|
+
this.heldOverflow += 1;
|
|
3396
|
+
throw new BrowserError('NET_QUOTA_EXCEEDED', '同时 hold 的请求超出上限 ' + NET_LIMITS.held, { max: NET_LIMITS.held });
|
|
3397
|
+
}
|
|
3398
|
+
const entry = {
|
|
3399
|
+
requestId: String(requestId), url: url ? sanitizeUrl(url).value : null,
|
|
3400
|
+
method: method ? String(method) : null, resourceType: resourceType ? String(resourceType) : null,
|
|
3401
|
+
ruleId, heldAt: this.now(), expiresAt: this.now() + this.holdTimeoutMs,
|
|
3402
|
+
};
|
|
3403
|
+
this.held.set(entry.requestId, entry);
|
|
3404
|
+
return entry;
|
|
3405
|
+
}
|
|
3406
|
+
|
|
3407
|
+
releaseHold(requestId, { timedOut = false } = {}) {
|
|
3408
|
+
const entry = this.held.get(String(requestId));
|
|
3409
|
+
if (!entry) return null;
|
|
3410
|
+
this.held.delete(String(requestId));
|
|
3411
|
+
if (timedOut) this.holdTimeouts += 1; else this.resumed += 1;
|
|
3412
|
+
return { ...entry, timedOut };
|
|
3413
|
+
}
|
|
3414
|
+
|
|
3415
|
+
listHeld() { return [...this.held.values()].map((entry) => ({ ...entry })); }
|
|
3416
|
+
|
|
3417
|
+
expiredHolds(nowMs = this.now()) {
|
|
3418
|
+
return [...this.held.values()].filter((entry) => entry.expiresAt <= nowMs).map((entry) => ({ ...entry }));
|
|
3419
|
+
}
|
|
3420
|
+
|
|
3421
|
+
snapshot() {
|
|
3422
|
+
return {
|
|
3423
|
+
rules: this.listRules(),
|
|
3424
|
+
condition: { ...this.condition },
|
|
3425
|
+
params: this.conditions(),
|
|
3426
|
+
held: this.listHeld(),
|
|
3427
|
+
responseModification: this.responseModification,
|
|
3428
|
+
counters: { resumed: this.resumed, holdTimeouts: this.holdTimeouts, heldOverflow: this.heldOverflow },
|
|
3429
|
+
applyFailures: [...this.applyFailures].slice(-10),
|
|
3430
|
+
limits: { rules: NET_LIMITS.rules, held: NET_LIMITS.held, holdTimeoutMs: this.holdTimeoutMs },
|
|
3431
|
+
};
|
|
3432
|
+
}
|
|
3433
|
+
}
|
|
3434
|
+
|
|
3435
|
+
/* ------------------------------------------------------------------ */
|
|
3436
|
+
/* 证据:JSONL / HAR / 索引(§2.6 §8.1 §8.2 §8.3 + R1-3 / R1-4 / R1-14) */
|
|
3437
|
+
/* ------------------------------------------------------------------ */
|
|
3438
|
+
|
|
3439
|
+
function pathFail(reason, message, extra = {}) {
|
|
3440
|
+
return { ok: false, code: 'NET_OUTPUT_PATH_INVALID', message, details: { reason, ...extra } };
|
|
3441
|
+
}
|
|
3442
|
+
|
|
3443
|
+
/**
|
|
3444
|
+
* 证据路径解析(R1-4 / §8.1):必须落在持久根内、相对路径、禁 `..`/反斜杠/NUL、限长、
|
|
3445
|
+
* 目录 realpath 复验;扩展名 `.jsonl`/`.har`。**不允许暂存导出**。
|
|
3446
|
+
*/
|
|
3447
|
+
export function resolveEvidencePath({ root, out, defaultName, extensions = ['.jsonl', '.har'] } = {}) {
|
|
3448
|
+
if (typeof root !== 'string' || root.trim() === '' || !isAbsolute(root)) return pathFail('root_not_absolute', '证据根必须是绝对路径');
|
|
3449
|
+
let canonicalRoot;
|
|
3450
|
+
try {
|
|
3451
|
+
const info = statSync(root);
|
|
3452
|
+
if (!info.isDirectory()) return pathFail('root_not_directory', '证据根不是目录');
|
|
3453
|
+
canonicalRoot = realpathSync(root);
|
|
3454
|
+
} catch {
|
|
3455
|
+
return pathFail('root_unavailable', '证据根不可用');
|
|
3456
|
+
}
|
|
3457
|
+
const requested = out === undefined || out === null ? defaultName : out;
|
|
3458
|
+
if (typeof requested !== 'string' || requested.trim() === '') return pathFail('out_missing', '证据输出路径不能为空');
|
|
3459
|
+
if (requested.includes('\0')) return pathFail('out_nul', '证据输出路径不能含 NUL');
|
|
3460
|
+
if (requested.includes('\\')) return pathFail('out_backslash', '证据输出路径必须使用 POSIX 分隔符');
|
|
3461
|
+
if (/^[A-Za-z]:/.test(requested) || isAbsolute(requested) || requested.startsWith('//')) {
|
|
3462
|
+
return pathFail('out_absolute', '证据输出路径必须是持久根内的相对路径');
|
|
3463
|
+
}
|
|
3464
|
+
if (Buffer.byteLength(requested, 'utf8') > 200) return pathFail('out_too_long', '证据输出路径超过 200 字节');
|
|
3465
|
+
const segments = requested.split('/');
|
|
3466
|
+
for (const segment of segments) {
|
|
3467
|
+
if (segment === '' || segment === '.' || segment === '..') return pathFail('out_segment', '证据输出路径不能含空段、"." 或 ".."');
|
|
3468
|
+
if (Buffer.byteLength(segment, 'utf8') > 100) return pathFail('out_segment_too_long', '证据输出路径单段超过 100 字节');
|
|
3469
|
+
}
|
|
3470
|
+
const name = segments[segments.length - 1];
|
|
3471
|
+
if (!extensions.some((extension) => name.endsWith(extension))) {
|
|
3472
|
+
return pathFail('out_extension', '证据文件扩展名必须是 ' + extensions.join(' / '), { extensions });
|
|
3473
|
+
}
|
|
3474
|
+
const inside = (parent, child) => {
|
|
3475
|
+
const rel = relativePath(parent, child);
|
|
3476
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
3477
|
+
};
|
|
3478
|
+
const targetAbsolute = resolvePath(canonicalRoot, requested);
|
|
3479
|
+
if (!inside(canonicalRoot, targetAbsolute)) return pathFail('out_escape', '证据输出路径逃出持久根');
|
|
3480
|
+
let dir;
|
|
3481
|
+
try {
|
|
3482
|
+
mkdirSync(dirname(targetAbsolute), { recursive: true });
|
|
3483
|
+
dir = realpathSync(dirname(targetAbsolute));
|
|
3484
|
+
} catch (error) {
|
|
3485
|
+
return pathFail('dir_create_failed', '证据输出目录创建失败', { code: error && error.code ? String(error.code) : null });
|
|
3486
|
+
}
|
|
3487
|
+
if (!inside(canonicalRoot, dir) && dir !== canonicalRoot) return pathFail('dir_escape', '证据输出目录解析到根之外');
|
|
3488
|
+
const absolutePath = resolvePath(dir, name);
|
|
3489
|
+
const rel = relativePath(canonicalRoot, absolutePath).split(sep).join('/');
|
|
3490
|
+
if (rel === '' || rel.startsWith('../') || rel === '..' || isAbsolute(rel)) return pathFail('out_escape', '证据输出路径逃出持久根');
|
|
3491
|
+
return { ok: true, root: canonicalRoot, dir, relativePath: rel, absolutePath };
|
|
3492
|
+
}
|
|
3493
|
+
|
|
3494
|
+
/** 原子 no-clobber 写(复用 capture-p0 提交点语义)。 */
|
|
3495
|
+
export function publishEvidence(dir, absolutePath, bytes, { mode = 0o600 } = {}) {
|
|
3496
|
+
const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
|
|
3497
|
+
return publishCapture(dir, absolutePath, buffer, { mode });
|
|
3498
|
+
}
|
|
3499
|
+
|
|
3500
|
+
/** R1-3 / §8.1:JSONL 每行一条标准化事件(无 `type` 外壳);`seq:0` 是 session-meta marker。 */
|
|
3501
|
+
export function toJsonl(store, { includeBodies = false } = {}) {
|
|
3502
|
+
const lines = [];
|
|
3503
|
+
const metaMarker = {
|
|
3504
|
+
seq: 0,
|
|
3505
|
+
sessionId: store.session ? store.session.id : null,
|
|
3506
|
+
kind: 'marker',
|
|
3507
|
+
phase: 'session-meta',
|
|
3508
|
+
version: NET_VERSION,
|
|
3509
|
+
session: store.session ? { ...store.session, state: store.state } : null,
|
|
3510
|
+
config: { ...store.config },
|
|
3511
|
+
limits: limitsView(),
|
|
3512
|
+
createdAt: store.now(),
|
|
3513
|
+
counters: { ...store.counters },
|
|
3514
|
+
integrity: store.integrity(),
|
|
3515
|
+
};
|
|
3516
|
+
lines.push(JSON.stringify(metaMarker));
|
|
3517
|
+
const lastEventOfChain = new Map();
|
|
3518
|
+
for (const event of store.events) {
|
|
3519
|
+
if (!event.requestId) continue;
|
|
3520
|
+
const key = requestKey(event);
|
|
3521
|
+
const chain = store.chains.get(key);
|
|
3522
|
+
if (chain && chain.lastSeq === event.seq) lastEventOfChain.set(key, event.seq);
|
|
3523
|
+
}
|
|
3524
|
+
for (const event of store.events) {
|
|
3525
|
+
const record = { ...event };
|
|
3526
|
+
if (includeBodies && event.requestId && lastEventOfChain.get(requestKey(event)) === event.seq) {
|
|
3527
|
+
const options = { targetId: event.targetId, cdpSessionId: event.cdpSessionId, requestId: event.requestId, hopId: event.hopId };
|
|
3528
|
+
const request = store.readBody({ ...options, kind: 'request' });
|
|
3529
|
+
const response = store.readBody({ ...options, kind: 'response' });
|
|
3530
|
+
// TOOL-P1-04:不把 `unavailable` 原因记录写成占用 body 行(否则导入端会把它误读成
|
|
3531
|
+
// captured/empty 的 body)。JSONL 只内联真实 captured/empty body,保持既有格式。
|
|
3532
|
+
const inlineBody = (body) => (body && body.state !== 'unavailable'
|
|
3533
|
+
? { state: body.state, encoding: body.encoding, bytes: body.bytes, truncated: body.truncated, payloadOmitted: body.payloadOmitted, redacted: body.redacted, data: body.data }
|
|
3534
|
+
: null);
|
|
3535
|
+
const requestInline = inlineBody(request);
|
|
3536
|
+
const responseInline = inlineBody(response);
|
|
3537
|
+
const inline = {
|
|
3538
|
+
...(requestInline ? { request: requestInline } : {}),
|
|
3539
|
+
...(responseInline ? { response: responseInline } : {}),
|
|
3540
|
+
};
|
|
3541
|
+
if (Object.keys(inline).length) record.body = inline;
|
|
3542
|
+
}
|
|
3543
|
+
lines.push(JSON.stringify(record));
|
|
3544
|
+
const projection = store.linkProjection ? store.linkProjection(event) : { evidenceIds: event.evidenceIds };
|
|
3545
|
+
for (const evidenceId of projection.evidenceIds) {
|
|
3546
|
+
lines.push(JSON.stringify({ kind: 'marker', phase: 'evidence-link', seq: event.seq, evidenceId }));
|
|
3547
|
+
}
|
|
3548
|
+
}
|
|
3549
|
+
return Buffer.from(lines.join('\n') + '\n', 'utf8');
|
|
3550
|
+
}
|
|
3551
|
+
|
|
3552
|
+
/**
|
|
3553
|
+
* R1-3 / §8.1 JSONL 导入:必须存在 `seq:0` 的 session-meta marker(`version:1`);坏行计
|
|
3554
|
+
* `skippedLines` 并保留 seq 空洞;重复 seq 保留首条并计 `duplicates`;**不重排**。
|
|
3555
|
+
*/
|
|
3556
|
+
export function fromJsonl(bytes, { maxBytes = NET_LIMITS.importFileBytes } = {}) {
|
|
3557
|
+
const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(String(bytes ?? ''), 'utf8');
|
|
3558
|
+
if (buffer.length === 0) throw new BrowserError('NET_IMPORT_FAILED', '证据内容为空');
|
|
3559
|
+
if (buffer.length > maxBytes) throw new BrowserError('NET_QUOTA_EXCEEDED', '证据内容超过导入上限', { max: maxBytes, bytes: buffer.length });
|
|
3560
|
+
const lines = buffer.toString('utf8').split('\n').filter((line) => line.trim() !== '');
|
|
3561
|
+
if (lines.length === 0) throw new BrowserError('NET_IMPORT_FAILED', '证据内容没有可解析的行');
|
|
3562
|
+
let meta = null;
|
|
3563
|
+
const events = [];
|
|
3564
|
+
const bodies = [];
|
|
3565
|
+
const links = [];
|
|
3566
|
+
let skippedLines = 0;
|
|
3567
|
+
let duplicates = 0;
|
|
3568
|
+
const seenSeq = new Set();
|
|
3569
|
+
for (const line of lines) {
|
|
3570
|
+
let record;
|
|
3571
|
+
try { record = JSON.parse(line); } catch { skippedLines += 1; continue; }
|
|
3572
|
+
if (!record || typeof record !== 'object') { skippedLines += 1; continue; }
|
|
3573
|
+
// Accept the documented `{version, kind:'session-meta', …}` marker *and* a bare
|
|
3574
|
+
// `{version, sessionId, config, limits}` header line (no phase/seq), which is what hand-written
|
|
3575
|
+
// fixtures and third-party dumps emit (§8.6 is about ordering, not about the marker's shape).
|
|
3576
|
+
const looksMeta = record.phase === 'session-meta'
|
|
3577
|
+
|| (record.seq === 0 && record.session)
|
|
3578
|
+
|| (record.version === 1 && record.phase === undefined && record.kind === undefined && record.seq === undefined
|
|
3579
|
+
&& (record.sessionId !== undefined || record.config !== undefined || record.limits !== undefined));
|
|
3580
|
+
if (looksMeta) {
|
|
3581
|
+
if (!Number.isInteger(record.version) || record.version !== NET_VERSION) {
|
|
3582
|
+
throw new BrowserError('NET_IMPORT_FAILED', 'session-meta marker 的 version 必须是 1', { version: record.version });
|
|
3583
|
+
}
|
|
3584
|
+
meta = record;
|
|
3585
|
+
continue;
|
|
3586
|
+
}
|
|
3587
|
+
if (record.phase === 'evidence-link' && record.evidenceId) {
|
|
3588
|
+
links.push({ seq: record.seq, evidenceId: record.evidenceId });
|
|
3589
|
+
continue;
|
|
3590
|
+
}
|
|
3591
|
+
if (!Number.isInteger(record.seq) || record.seq <= 0) { skippedLines += 1; continue; }
|
|
3592
|
+
if (seenSeq.has(record.seq)) { duplicates += 1; continue; }
|
|
3593
|
+
seenSeq.add(record.seq);
|
|
3594
|
+
const { body, ...event } = record;
|
|
3595
|
+
events.push(event);
|
|
3596
|
+
if (body) {
|
|
3597
|
+
for (const kind of ['request', 'response']) {
|
|
3598
|
+
if (!body[kind] || typeof body[kind].data !== 'string') continue;
|
|
3599
|
+
bodies.push({
|
|
3600
|
+
requestId: event.requestId, targetId: event.targetId, cdpSessionId: event.cdpSessionId, hopId: event.hopId,
|
|
3601
|
+
kind, seq: event.seq, state: body[kind].state === 'empty' ? 'empty' : 'captured',
|
|
3602
|
+
base64Encoded: body[kind].encoding === 'base64', truncated: body[kind].truncated === true,
|
|
3603
|
+
payloadOmitted: body[kind].payloadOmitted === true, data: body[kind].data,
|
|
3604
|
+
});
|
|
3605
|
+
}
|
|
3606
|
+
}
|
|
3607
|
+
}
|
|
3608
|
+
if (meta === null) throw new BrowserError('NET_IMPORT_FAILED', '缺少 seq:0 的 session-meta marker');
|
|
3609
|
+
if (events.length === 0) throw new BrowserError('NET_IMPORT_FAILED', '没有可解析的事件行', { skippedLines });
|
|
3610
|
+
return { meta, events, bodies, links, skippedLines, duplicates, version: meta.version };
|
|
3611
|
+
}
|
|
3612
|
+
|
|
3613
|
+
/** 把导入结果装载为一个离线会话(`state:"snapshot"`;不可 control/replay)。 */
|
|
3614
|
+
export function loadImported(store, imported, { name = null, source = null } = {}) {
|
|
3615
|
+
store.config = normalizeSessionConfig(imported.meta && imported.meta.config ? imported.meta.config : null);
|
|
3616
|
+
store.sessions = store.sessions || [];
|
|
3617
|
+
store.state = 'snapshot';
|
|
3618
|
+
store.session = {
|
|
3619
|
+
id: 'net-' + randomBytes(4).toString('hex'),
|
|
3620
|
+
name: truncateBytes(String(name || (imported.meta && imported.meta.session && imported.meta.session.name) || 'imported'), 64),
|
|
3621
|
+
state: 'snapshot',
|
|
3622
|
+
startedAt: store.now(),
|
|
3623
|
+
stoppedAt: null,
|
|
3624
|
+
retained: true,
|
|
3625
|
+
source,
|
|
3626
|
+
config: { ...store.config },
|
|
3627
|
+
};
|
|
3628
|
+
store.seq = 0;
|
|
3629
|
+
store.events = [];
|
|
3630
|
+
store.chains.clear();
|
|
3631
|
+
store.hops.clear();
|
|
3632
|
+
store.bodies.clear();
|
|
3633
|
+
if (store.bodyFailures) store.bodyFailures.clear();
|
|
3634
|
+
store.headers.clear();
|
|
3635
|
+
store.bodyBytes = 0;
|
|
3636
|
+
store.headerBytes = 0;
|
|
3637
|
+
store.eventBytes = 0;
|
|
3638
|
+
store.evictedSeqs = [];
|
|
3639
|
+
store.dropRanges = [];
|
|
3640
|
+
store.steps.clear();
|
|
3641
|
+
store.links.clear();
|
|
3642
|
+
store.correlationIndex.clear();
|
|
3643
|
+
store.counters = emptyCounters();
|
|
3644
|
+
store.issues = ['import-partial'];
|
|
3645
|
+
let previousSeq = 0;
|
|
3646
|
+
for (const event of imported.events) {
|
|
3647
|
+
if (event.seq > previousSeq + 1) store.dropRanges.push({ from: previousSeq + 1, to: event.seq - 1, count: event.seq - previousSeq - 1, reason: 'import-gap' });
|
|
3648
|
+
previousSeq = event.seq;
|
|
3649
|
+
store.seq = Math.max(store.seq, event.seq);
|
|
3650
|
+
const normalized = normalizeEvent(event, {
|
|
3651
|
+
seq: event.seq,
|
|
3652
|
+
sessionId: store.session.id,
|
|
3653
|
+
wallMs: store.now(),
|
|
3654
|
+
monotonicMs: store.monotonic(),
|
|
3655
|
+
preSession: event.preSession === true,
|
|
3656
|
+
hmacKey: store.hmacKey,
|
|
3657
|
+
});
|
|
3658
|
+
store.events.push(normalized);
|
|
3659
|
+
store.counters.events += 1;
|
|
3660
|
+
if (normalized.kind === 'http') store.counters.http += 1;
|
|
3661
|
+
else if (normalized.kind === 'ws') store.counters.ws += 1;
|
|
3662
|
+
else if (normalized.kind === 'sse') store.counters.sse += 1;
|
|
3663
|
+
else store.counters.markers += 1;
|
|
3664
|
+
}
|
|
3665
|
+
for (const body of imported.bodies) {
|
|
3666
|
+
store.addBody({
|
|
3667
|
+
targetId: body.targetId, cdpSessionId: body.cdpSessionId, requestId: body.requestId, hopId: body.hopId,
|
|
3668
|
+
kind: body.kind, state: body.state, data: body.data, base64Encoded: body.base64Encoded === true,
|
|
3669
|
+
payloadOmitted: body.payloadOmitted === true,
|
|
3670
|
+
});
|
|
3671
|
+
}
|
|
3672
|
+
for (const link of imported.links) {
|
|
3673
|
+
const event = store.events.find((item) => item.seq === link.seq);
|
|
3674
|
+
if (event && link.evidenceId && !event.evidenceIds.includes(link.evidenceId)) event.evidenceIds.push(truncateBytes(String(link.evidenceId), 128));
|
|
3675
|
+
}
|
|
3676
|
+
store.rebuildChains();
|
|
3677
|
+
return {
|
|
3678
|
+
sessionId: store.session.id,
|
|
3679
|
+
events: store.events.length,
|
|
3680
|
+
bodies: store.bodies.size,
|
|
3681
|
+
skippedLines: imported.skippedLines || 0,
|
|
3682
|
+
duplicates: imported.duplicates || 0,
|
|
3683
|
+
snapshot: true,
|
|
3684
|
+
};
|
|
3685
|
+
}
|
|
3686
|
+
|
|
3687
|
+
const HAR_CREATOR = Object.freeze({ name: 'dsh-agent-team-ui-testing', version: '0.1.0' });
|
|
3688
|
+
|
|
3689
|
+
function harEntryFor(store, chain) {
|
|
3690
|
+
const events = chain.seqs.map((seq) => store.events.find((event) => event.seq === seq)).filter(Boolean);
|
|
3691
|
+
const request = events.find((event) => event.phase === 'request');
|
|
3692
|
+
const response = events.find((event) => event.phase === 'response');
|
|
3693
|
+
if (!request || !response) return null;
|
|
3694
|
+
const options = { targetId: request.targetId, cdpSessionId: request.cdpSessionId, requestId: request.requestId, hopId: request.hopId };
|
|
3695
|
+
const toHarHeaders = (record) => Object.entries(record.headers).map(([name, value]) => ({ name, value }));
|
|
3696
|
+
const timing = response.timing || emptyTiming();
|
|
3697
|
+
const num = (value) => (Number.isFinite(value) && value >= 0 ? value : -1);
|
|
3698
|
+
const entry = {
|
|
3699
|
+
pageref: store.session ? store.session.id : 'net',
|
|
3700
|
+
startedDateTime: new Date(request.ts.wallMs).toISOString(),
|
|
3701
|
+
time: Number.isFinite(timing.totalMs) ? timing.totalMs : 0,
|
|
3702
|
+
request: {
|
|
3703
|
+
method: request.method || 'GET',
|
|
3704
|
+
url: request.url,
|
|
3705
|
+
httpVersion: response.protocol || '',
|
|
3706
|
+
headers: toHarHeaders(store.readHeaders({ ...options, kind: 'request' })),
|
|
3707
|
+
queryString: parseQueryString(request.url),
|
|
3708
|
+
cookies: [],
|
|
3709
|
+
headersSize: Number.isInteger(request.sizes.requestHeaders) ? request.sizes.requestHeaders : -1,
|
|
3710
|
+
bodySize: Number.isInteger(request.sizes.requestBody) ? request.sizes.requestBody : -1,
|
|
3711
|
+
},
|
|
3712
|
+
response: {
|
|
3713
|
+
status: Number.isInteger(response.status) ? response.status : 0,
|
|
3714
|
+
statusText: response.statusText || '',
|
|
3715
|
+
httpVersion: response.protocol || '',
|
|
3716
|
+
headers: toHarHeaders(store.readHeaders({ ...options, kind: 'response' })),
|
|
3717
|
+
cookies: [],
|
|
3718
|
+
content: {
|
|
3719
|
+
size: Number.isInteger(response.sizes.decoded) ? response.sizes.decoded : (Number.isInteger(response.sizes.encoded) ? response.sizes.encoded : 0),
|
|
3720
|
+
mimeType: response.mimeType || '',
|
|
3721
|
+
},
|
|
3722
|
+
redirectURL: chain.hops.length ? chain.hops[chain.hops.length - 1].url : '',
|
|
3723
|
+
headersSize: Number.isInteger(response.sizes.responseHeaders) ? response.sizes.responseHeaders : -1,
|
|
3724
|
+
bodySize: Number.isInteger(response.sizes.encoded) ? response.sizes.encoded : -1,
|
|
3725
|
+
},
|
|
3726
|
+
cache: {},
|
|
3727
|
+
timings: {
|
|
3728
|
+
blocked: -1,
|
|
3729
|
+
dns: num(timing.dnsMs),
|
|
3730
|
+
connect: num(timing.connectMs),
|
|
3731
|
+
send: Number.isFinite(timing.sendMs) ? timing.sendMs : 0,
|
|
3732
|
+
wait: Number.isFinite(timing.waitMs) ? timing.waitMs : 0,
|
|
3733
|
+
receive: Number.isFinite(timing.receiveMs) ? timing.receiveMs : 0,
|
|
3734
|
+
ssl: num(timing.sslMs),
|
|
3735
|
+
},
|
|
3736
|
+
_networkP0: {
|
|
3737
|
+
seq: request.seq, kind: request.kind, phase: request.phase,
|
|
3738
|
+
targetId: request.targetId, frameId: request.frameId, stepId: request.stepId, hopId: request.hopId,
|
|
3739
|
+
},
|
|
3740
|
+
};
|
|
3741
|
+
return { entry, options };
|
|
3742
|
+
}
|
|
3743
|
+
|
|
3744
|
+
/** §8.2 / R1-14 HAR 1.2 子集导出(必需字段齐全;未知数值用 -1)。 */
|
|
3745
|
+
export function toHar(store, { includeBodies = false } = {}) {
|
|
3746
|
+
const entries = [];
|
|
3747
|
+
for (const chain of store.chains.values()) {
|
|
3748
|
+
const built = harEntryFor(store, chain);
|
|
3749
|
+
if (!built) continue;
|
|
3750
|
+
const { entry, options } = built;
|
|
3751
|
+
if (includeBodies) {
|
|
3752
|
+
const body = store.readBody({ ...options, kind: 'response' });
|
|
3753
|
+
if (body && body.state === 'captured' && !body.payloadOmitted) {
|
|
3754
|
+
entry.response.content = {
|
|
3755
|
+
...entry.response.content,
|
|
3756
|
+
text: body.data,
|
|
3757
|
+
...(body.encoding === 'base64' ? { encoding: 'base64' } : {}),
|
|
3758
|
+
size: Number.isFinite(body.originalBytes) ? body.originalBytes : entry.response.content.size,
|
|
3759
|
+
};
|
|
3760
|
+
}
|
|
3761
|
+
}
|
|
3762
|
+
entries.push(entry);
|
|
3763
|
+
}
|
|
3764
|
+
// WS / SSE 扩展条目(JSONL 才是保真格式)
|
|
3765
|
+
const byRequestId = new Map();
|
|
3766
|
+
for (const chain of store.chains.values()) byRequestId.set(chain.requestId, chain);
|
|
3767
|
+
for (const [requestId, chain] of byRequestId.entries()) {
|
|
3768
|
+
const frames = store.events
|
|
3769
|
+
.filter((event) => event.kind === 'ws' && event.requestId === requestId && (event.phase === 'ws-send' || event.phase === 'ws-receive'))
|
|
3770
|
+
.map((event) => ({ type: event.ws && event.ws.direction ? event.ws.direction : 'receive', time: event.ts.wallMs, opcode: event.ws ? event.ws.opcode : null, data: event.ws ? event.ws.payload : null }));
|
|
3771
|
+
if (frames.length) {
|
|
3772
|
+
const target = entries.find((entry) => entry._networkP0 && entry._networkP0.seq === chain.seqs[0]);
|
|
3773
|
+
if (target) target._webSocketMessages = frames;
|
|
3774
|
+
else entries.push({
|
|
3775
|
+
pageref: store.session ? store.session.id : 'net',
|
|
3776
|
+
startedDateTime: new Date(frames[0].time).toISOString(),
|
|
3777
|
+
time: 0,
|
|
3778
|
+
request: { method: 'GET', url: chain.url || '', httpVersion: '', headers: [], queryString: [], cookies: [], headersSize: -1, bodySize: -1 },
|
|
3779
|
+
response: { status: 101, statusText: 'Switching Protocols', httpVersion: '', headers: [], cookies: [], content: { size: 0, mimeType: '' }, redirectURL: '', headersSize: -1, bodySize: -1 },
|
|
3780
|
+
cache: {},
|
|
3781
|
+
timings: { blocked: -1, dns: -1, connect: -1, send: 0, wait: 0, receive: 0, ssl: -1 },
|
|
3782
|
+
_webSocketMessages: frames,
|
|
3783
|
+
_networkP0: { kind: 'ws', requestId, hopId: chain.hopId },
|
|
3784
|
+
});
|
|
3785
|
+
}
|
|
3786
|
+
const messages = store.events
|
|
3787
|
+
.filter((event) => event.kind === 'sse' && event.requestId === requestId)
|
|
3788
|
+
.map((event) => ({ eventName: event.sse ? event.sse.eventName : null, eventId: event.sse ? event.sse.eventId : null, data: event.sse ? event.sse.data : null, time: event.ts.wallMs }));
|
|
3789
|
+
if (messages.length) {
|
|
3790
|
+
const target = entries.find((entry) => entry._networkP0 && entry._networkP0.seq === chain.seqs[0]);
|
|
3791
|
+
if (target) target._eventSourceMessages = messages;
|
|
3792
|
+
}
|
|
3793
|
+
}
|
|
3794
|
+
entries.sort((left, right) => (left.startedDateTime < right.startedDateTime ? -1 : left.startedDateTime > right.startedDateTime ? 1 : 0));
|
|
3795
|
+
return {
|
|
3796
|
+
log: {
|
|
3797
|
+
version: '1.2',
|
|
3798
|
+
creator: { ...HAR_CREATOR },
|
|
3799
|
+
pages: [{
|
|
3800
|
+
startedDateTime: entries.length ? entries[0].startedDateTime : new Date(store.now()).toISOString(),
|
|
3801
|
+
id: store.session ? store.session.id : 'net',
|
|
3802
|
+
title: store.session && store.session.name ? store.session.name : 'network session',
|
|
3803
|
+
pageTimings: { onContentLoad: -1, onLoad: -1 },
|
|
3804
|
+
}],
|
|
3805
|
+
entries,
|
|
3806
|
+
_networkP0: {
|
|
3807
|
+
version: NET_VERSION,
|
|
3808
|
+
sessionId: store.session ? store.session.id : null,
|
|
3809
|
+
config: { ...store.config },
|
|
3810
|
+
counters: { ...store.counters },
|
|
3811
|
+
integrity: store.integrity(),
|
|
3812
|
+
exportedAt: store.now(),
|
|
3813
|
+
},
|
|
3814
|
+
},
|
|
3815
|
+
};
|
|
3816
|
+
}
|
|
3817
|
+
|
|
3818
|
+
function harTimingsToTiming(timings, requestSeconds, responseSeconds) {
|
|
3819
|
+
const timing = {
|
|
3820
|
+
requestTime: Number.isFinite(requestSeconds) ? requestSeconds : -1,
|
|
3821
|
+
dnsStart: Number.isFinite(timings.dns) && timings.dns >= 0 ? 0 : -1,
|
|
3822
|
+
dnsEnd: Number.isFinite(timings.dns) && timings.dns >= 0 ? timings.dns : -1,
|
|
3823
|
+
connectStart: Number.isFinite(timings.connect) && timings.connect >= 0 ? 0 : -1,
|
|
3824
|
+
connectEnd: Number.isFinite(timings.connect) && timings.connect >= 0 ? timings.connect : -1,
|
|
3825
|
+
sendStart: 0,
|
|
3826
|
+
sendEnd: Number.isFinite(timings.send) && timings.send >= 0 ? timings.send : 0,
|
|
3827
|
+
receiveHeadersStart: (Number.isFinite(timings.send) ? timings.send : 0) + (Number.isFinite(timings.wait) ? timings.wait : 0),
|
|
3828
|
+
receiveHeadersEnd: (Number.isFinite(timings.send) ? timings.send : 0) + (Number.isFinite(timings.wait) ? timings.wait : 0) + (Number.isFinite(timings.receive) ? timings.receive : 0),
|
|
3829
|
+
sslStart: Number.isFinite(timings.ssl) && timings.ssl >= 0 ? 0 : -1,
|
|
3830
|
+
sslEnd: Number.isFinite(timings.ssl) && timings.ssl >= 0 ? timings.ssl : -1,
|
|
3831
|
+
};
|
|
3832
|
+
return normalizeTiming(timing, { responseSeconds });
|
|
3833
|
+
}
|
|
3834
|
+
|
|
3835
|
+
/** §8.2 HAR 导入(HTTP 条目;WS/SSE 扩展尽力还原)。 */
|
|
3836
|
+
export function fromHar(har, { now = Date.now() } = {}) {
|
|
3837
|
+
if (!har || typeof har !== 'object' || !har.log || typeof har.log !== 'object') throw new BrowserError('NET_HAR_INVALID', 'HAR 缺少 log 对象');
|
|
3838
|
+
const log = har.log;
|
|
3839
|
+
if (typeof log.version !== 'string' || !log.version.startsWith('1.')) throw new BrowserError('NET_HAR_INVALID', 'HAR log.version 必须是 1.x', { version: log.version });
|
|
3840
|
+
if (!Array.isArray(log.entries)) throw new BrowserError('NET_HAR_INVALID', 'HAR log.entries 必须是数组');
|
|
3841
|
+
const events = [];
|
|
3842
|
+
const bodies = [];
|
|
3843
|
+
let seq = 0;
|
|
3844
|
+
for (const [index, entry] of log.entries.entries()) {
|
|
3845
|
+
if (!entry || typeof entry !== 'object' || !entry.request || !entry.response) {
|
|
3846
|
+
throw new BrowserError('NET_HAR_INVALID', 'HAR entry 缺少 request/response', { index });
|
|
3847
|
+
}
|
|
3848
|
+
const requestId = (entry._networkP0 && entry._networkP0.requestId) || 'har-' + (index + 1);
|
|
3849
|
+
const targetId = (entry._networkP0 && entry._networkP0.targetId) || null;
|
|
3850
|
+
const hopId = entry._networkP0 && Number.isInteger(entry._networkP0.hopId) ? entry._networkP0.hopId : 0;
|
|
3851
|
+
const wall = Date.parse(entry.startedDateTime);
|
|
3852
|
+
const wallMs = Number.isFinite(wall) ? wall : now;
|
|
3853
|
+
const timeMs = Number.isFinite(entry.time) ? entry.time : 0;
|
|
3854
|
+
const timing = harTimingsToTiming(entry.timings || {}, wallMs / 1000, (wallMs + timeMs) / 1000);
|
|
3855
|
+
seq += 1;
|
|
3856
|
+
events.push({
|
|
3857
|
+
seq, kind: 'http', phase: 'request', requestId, targetId, hopId,
|
|
3858
|
+
ts: { wallMs, monotonicMs: 0, cdpSeconds: null },
|
|
3859
|
+
url: entry.request.url, method: entry.request.method, resourceType: 'Other',
|
|
3860
|
+
sizes: {
|
|
3861
|
+
requestHeaders: Number.isInteger(entry.request.headersSize) && entry.request.headersSize >= 0 ? entry.request.headersSize : null,
|
|
3862
|
+
requestBody: Number.isInteger(entry.request.bodySize) && entry.request.bodySize >= 0 ? entry.request.bodySize : null,
|
|
3863
|
+
},
|
|
3864
|
+
correlationIds: [],
|
|
3865
|
+
});
|
|
3866
|
+
seq += 1;
|
|
3867
|
+
events.push({
|
|
3868
|
+
seq, kind: 'http', phase: 'response', requestId, targetId, hopId,
|
|
3869
|
+
ts: { wallMs: wallMs + Math.round(timeMs), monotonicMs: 0, cdpSeconds: null },
|
|
3870
|
+
url: entry.response.redirectURL || entry.request.url,
|
|
3871
|
+
status: Number.isInteger(entry.response.status) ? entry.response.status : null,
|
|
3872
|
+
statusText: entry.response.statusText || null,
|
|
3873
|
+
mimeType: entry.response.content ? entry.response.content.mimeType || null : null,
|
|
3874
|
+
protocol: entry.response.httpVersion || null,
|
|
3875
|
+
timing,
|
|
3876
|
+
sizes: {
|
|
3877
|
+
encoded: Number.isInteger(entry.response.bodySize) && entry.response.bodySize >= 0 ? entry.response.bodySize : null,
|
|
3878
|
+
decoded: entry.response.content && Number.isInteger(entry.response.content.size) ? entry.response.content.size : null,
|
|
3879
|
+
},
|
|
3880
|
+
redirect: entry.response.redirectURL
|
|
3881
|
+
? { from: entry.request.url, to: entry.response.redirectURL, status: Number.isInteger(entry.response.status) ? entry.response.status : null }
|
|
3882
|
+
: null,
|
|
3883
|
+
correlationIds: [],
|
|
3884
|
+
});
|
|
3885
|
+
const content = entry.response.content || {};
|
|
3886
|
+
if (typeof content.text === 'string' && content.text !== '') {
|
|
3887
|
+
bodies.push({
|
|
3888
|
+
requestId, targetId, hopId, kind: 'response', seq, state: 'captured',
|
|
3889
|
+
base64Encoded: content.encoding === 'base64', truncated: false,
|
|
3890
|
+
data: content.encoding === 'base64' ? content.text : Buffer.from(content.text, 'utf8').toString('base64'),
|
|
3891
|
+
});
|
|
3892
|
+
}
|
|
3893
|
+
seq += 1;
|
|
3894
|
+
events.push({
|
|
3895
|
+
seq, kind: 'http', phase: 'finished', requestId, targetId, hopId,
|
|
3896
|
+
ts: { wallMs: wallMs + Math.round(timeMs), monotonicMs: 0, cdpSeconds: null },
|
|
3897
|
+
url: entry.request.url, timing: { ...timing, totalMs: timeMs }, correlationIds: [],
|
|
3898
|
+
});
|
|
3899
|
+
}
|
|
3900
|
+
return { events, bodies, meta: log._networkP0 || null, links: [], skippedLines: 0, duplicates: 0, version: NET_VERSION };
|
|
3901
|
+
}
|
|
3902
|
+
|
|
3903
|
+
export function detectEvidenceFormat(text) {
|
|
3904
|
+
const trimmed = String(text ?? '').trim();
|
|
3905
|
+
if (trimmed === '') return null;
|
|
3906
|
+
if (trimmed.startsWith('{')) {
|
|
3907
|
+
try {
|
|
3908
|
+
const parsed = JSON.parse(trimmed);
|
|
3909
|
+
if (parsed && parsed.log && Array.isArray(parsed.log.entries)) return 'har';
|
|
3910
|
+
} catch { /* 多行 JSONL 不是单对象 */ }
|
|
3911
|
+
return 'jsonl';
|
|
3912
|
+
}
|
|
3913
|
+
return 'jsonl';
|
|
3914
|
+
}
|
|
3915
|
+
|
|
3916
|
+
export function parseImportedEvidence(text, { format = 'auto' } = {}) {
|
|
3917
|
+
const chosen = format === 'auto' || !format ? detectEvidenceFormat(text) : format;
|
|
3918
|
+
if (chosen === 'har') {
|
|
3919
|
+
let parsed;
|
|
3920
|
+
try { parsed = typeof text === 'string' ? JSON.parse(text) : text; } catch (error) {
|
|
3921
|
+
throw new BrowserError('NET_HAR_INVALID', 'HAR 不是合法 JSON', { reason: String(error && error.message || error) });
|
|
3922
|
+
}
|
|
3923
|
+
return { format: 'har', ...fromHar(parsed) };
|
|
3924
|
+
}
|
|
3925
|
+
if (chosen === 'jsonl') return { format: 'jsonl', ...fromJsonl(text) };
|
|
3926
|
+
throw new BrowserError('NET_IMPORT_FAILED', '无法判定的证据格式');
|
|
3927
|
+
}
|
|
3928
|
+
|
|
3929
|
+
/* ---------------- 索引 / 检索 / 链接 ---------------- */
|
|
3930
|
+
|
|
3931
|
+
export function registerArtifact(store, artifact) {
|
|
3932
|
+
const id = artifact.evidenceId
|
|
3933
|
+
? truncateBytes(String(artifact.evidenceId), 128)
|
|
3934
|
+
: 'ev-' + randomBytes(5).toString('hex');
|
|
3935
|
+
const record = {
|
|
3936
|
+
evidenceId: id,
|
|
3937
|
+
format: artifact.format === 'har' ? 'har' : 'jsonl',
|
|
3938
|
+
sessionId: artifact.sessionId === undefined ? (store.session ? store.session.id : null) : artifact.sessionId,
|
|
3939
|
+
createdAt: Number.isFinite(artifact.createdAt) ? artifact.createdAt : store.now(),
|
|
3940
|
+
seqs: Array.isArray(artifact.seqs) ? artifact.seqs.slice(0, 20000) : [],
|
|
3941
|
+
bytes: Number.isInteger(artifact.bytes) ? artifact.bytes : null,
|
|
3942
|
+
sha256: typeof artifact.sha256 === 'string' ? artifact.sha256 : null,
|
|
3943
|
+
pathKind: 'persist',
|
|
3944
|
+
persistence: 'root',
|
|
3945
|
+
relativePath: typeof artifact.relativePath === 'string' ? artifact.relativePath : null,
|
|
3946
|
+
absolutePath: typeof artifact.absolutePath === 'string' ? artifact.absolutePath : null,
|
|
3947
|
+
includeBodies: artifact.includeBodies === true,
|
|
3948
|
+
events: Number.isInteger(artifact.events) ? artifact.events : null,
|
|
3949
|
+
integrity: store.integrity(),
|
|
3950
|
+
};
|
|
3951
|
+
store.artifacts.set(id, record);
|
|
3952
|
+
return record;
|
|
3953
|
+
}
|
|
3954
|
+
|
|
3955
|
+
export function listArtifacts(store) {
|
|
3956
|
+
return [...store.artifacts.values()].map((record) => ({
|
|
3957
|
+
evidenceId: record.evidenceId, format: record.format, sessionId: record.sessionId,
|
|
3958
|
+
relativePath: record.relativePath, pathKind: record.pathKind, persistence: record.persistence,
|
|
3959
|
+
bytes: record.bytes, createdAt: record.createdAt, events: record.events,
|
|
3960
|
+
seqs: record.seqs.slice(0, 50), includeBodies: record.includeBodies, integrity: record.integrity,
|
|
3961
|
+
}));
|
|
3962
|
+
}
|
|
3963
|
+
|
|
3964
|
+
export function searchArtifacts(store, query = {}) {
|
|
3965
|
+
assertKnownKeys(query, ['text', 'urlIncludes', 'status', 'stepId', 'seqs'], 'query');
|
|
3966
|
+
const results = [];
|
|
3967
|
+
const seqs = Array.isArray(query.seqs) ? query.seqs.filter((seq) => Number.isInteger(seq)) : null;
|
|
3968
|
+
for (const event of store.events) {
|
|
3969
|
+
if (seqs && !seqs.includes(event.seq)) continue;
|
|
3970
|
+
if (Number.isInteger(query.status) && event.status !== query.status) continue;
|
|
3971
|
+
if (query.urlIncludes && !String(event.url || '').toLowerCase().includes(String(query.urlIncludes).toLowerCase())) continue;
|
|
3972
|
+
if (query.stepId && !inStepWindow(store, event, query.stepId)) continue;
|
|
3973
|
+
if (query.text) {
|
|
3974
|
+
const hit = matchesSearch(store, event, { text: query.text, in: ['url', 'headers', 'body', 'ws', 'sse'] });
|
|
3975
|
+
if (!hit || !hit.matched) continue;
|
|
3976
|
+
}
|
|
3977
|
+
results.push({
|
|
3978
|
+
sessionId: store.session ? store.session.id : null,
|
|
3979
|
+
seq: event.seq, url: event.url, method: event.method, status: event.status,
|
|
3980
|
+
wallMs: event.ts.wallMs, stepId: derivedStepId(store, event), file: null,
|
|
3981
|
+
});
|
|
3982
|
+
if (results.length >= NET_LIMITS.eventPageLimit) break;
|
|
3983
|
+
}
|
|
3984
|
+
const files = listArtifacts(store)
|
|
3985
|
+
.filter((artifact) => (seqs ? seqs.some((seq) => artifact.seqs.includes(seq)) : true))
|
|
3986
|
+
.map((artifact) => ({ evidenceId: artifact.evidenceId, relativePath: artifact.relativePath, format: artifact.format, sessionId: artifact.sessionId }));
|
|
3987
|
+
return { ok: true, results, files, truncated: results.length >= NET_LIMITS.eventPageLimit };
|
|
3988
|
+
}
|
|
3989
|
+
|
|
3990
|
+
export function indexView(store) {
|
|
3991
|
+
const artifacts = listArtifacts(store);
|
|
3992
|
+
const links = [];
|
|
3993
|
+
for (const [seq, list] of store.links.entries()) {
|
|
3994
|
+
for (const link of list) links.push({ seq, evidenceId: link.evidenceId, stepId: link.stepId, linkedAt: link.linkedAt });
|
|
3995
|
+
}
|
|
3996
|
+
for (const event of store.events) {
|
|
3997
|
+
for (const evidenceId of event.evidenceIds) {
|
|
3998
|
+
if (!links.some((link) => link.seq === event.seq && link.evidenceId === evidenceId)) {
|
|
3999
|
+
links.push({ seq: event.seq, evidenceId, stepId: event.stepId, linkedAt: null });
|
|
4000
|
+
}
|
|
4001
|
+
}
|
|
4002
|
+
}
|
|
4003
|
+
return {
|
|
4004
|
+
version: NET_VERSION,
|
|
4005
|
+
sessions: [{ id: store.session ? store.session.id : null, name: store.session ? store.session.name : null, state: store.state }],
|
|
4006
|
+
files: artifacts.map((artifact) => ({
|
|
4007
|
+
relativePath: artifact.relativePath, format: artifact.format, bytes: artifact.bytes,
|
|
4008
|
+
sessionId: artifact.sessionId, createdAt: artifact.createdAt, integrity: artifact.integrity,
|
|
4009
|
+
})),
|
|
4010
|
+
entries: { events: store.events.length, requests: store.chains.size, steps: store.steps.size },
|
|
4011
|
+
links: links.slice(0, 200),
|
|
4012
|
+
};
|
|
4013
|
+
}
|
|
4014
|
+
|
|
4015
|
+
export function clearArtifacts(store) {
|
|
4016
|
+
const count = store.artifacts.size;
|
|
4017
|
+
const files = [...store.artifacts.values()];
|
|
4018
|
+
store.artifacts.clear();
|
|
4019
|
+
return { cleared: count, files };
|
|
4020
|
+
}
|
|
4021
|
+
|
|
4022
|
+
/* ------------------------------------------------------------------ */
|
|
4023
|
+
/* 订阅(§2.7 + R1-2) */
|
|
4024
|
+
/* ------------------------------------------------------------------ */
|
|
4025
|
+
|
|
4026
|
+
function subscriptionOf(store, subscriptionId, ownerSessionId) {
|
|
4027
|
+
const record = store.subscriptions.get(String(subscriptionId));
|
|
4028
|
+
if (!record) throw new BrowserError('NET_SUBSCRIPTION_NOT_FOUND', '订阅不存在: ' + String(subscriptionId), { subscriptionId: String(subscriptionId) });
|
|
4029
|
+
if (record.ownerSessionId !== ownerSessionId) {
|
|
4030
|
+
throw new BrowserError('NET_SUBSCRIPTION_FORBIDDEN', '该订阅属于其他会话', { subscriptionId: record.id });
|
|
4031
|
+
}
|
|
4032
|
+
return record;
|
|
4033
|
+
}
|
|
4034
|
+
|
|
4035
|
+
export function subscriptionCreate(store, { ownerSessionId, kinds = null, afterSeq = null } = {}) {
|
|
4036
|
+
if (!ownerSessionId) throw new BrowserError('NET_SUBSCRIPTION_FORBIDDEN', '缺少调用方身份');
|
|
4037
|
+
if (store.subscriptions.size >= NET_LIMITS.subscriptionMax) {
|
|
4038
|
+
throw new BrowserError('NET_QUOTA_EXCEEDED', '订阅数超出上限 ' + NET_LIMITS.subscriptionMax, { max: NET_LIMITS.subscriptionMax });
|
|
4039
|
+
}
|
|
4040
|
+
let normalizedKinds = null;
|
|
4041
|
+
if (kinds !== null && kinds !== undefined) {
|
|
4042
|
+
if (!Array.isArray(kinds) || kinds.length === 0) throw new BrowserError('NET_INVALID_ARGUMENT', 'kinds 必须是非空数组');
|
|
4043
|
+
for (const kind of kinds) {
|
|
4044
|
+
if (!NET_KINDS.includes(kind)) throw new BrowserError('NET_INVALID_ARGUMENT', 'kinds 含未知取值 ' + String(kind), { allowed: [...NET_KINDS] });
|
|
4045
|
+
}
|
|
4046
|
+
normalizedKinds = [...new Set(kinds)];
|
|
4047
|
+
}
|
|
4048
|
+
const from = Number.isInteger(afterSeq) ? afterSeq : store.seq;
|
|
4049
|
+
const record = {
|
|
4050
|
+
id: 'sub-' + randomBytes(4).toString('hex'),
|
|
4051
|
+
ownerSessionId: String(ownerSessionId),
|
|
4052
|
+
sessionId: store.session ? store.session.id : null,
|
|
4053
|
+
kinds: normalizedKinds,
|
|
4054
|
+
fromSeq: from,
|
|
4055
|
+
deliveredSeq: from,
|
|
4056
|
+
ackedSeq: from,
|
|
4057
|
+
createdAt: store.now(),
|
|
4058
|
+
polls: 0,
|
|
4059
|
+
delivered: 0,
|
|
4060
|
+
droppedPinned: 0,
|
|
4061
|
+
pinned: false,
|
|
4062
|
+
closed: false,
|
|
4063
|
+
};
|
|
4064
|
+
store.subscriptions.set(record.id, record);
|
|
4065
|
+
return {
|
|
4066
|
+
id: record.id, createdAt: record.createdAt,
|
|
4067
|
+
cursor: { next: encodeCursor(record.deliveredSeq) }, ackedSeq: record.ackedSeq,
|
|
4068
|
+
counters: { delivered: 0, pending: Math.max(0, store.seq - record.ackedSeq), pinned: 0, dropped: 0 },
|
|
4069
|
+
};
|
|
4070
|
+
}
|
|
4071
|
+
|
|
4072
|
+
/**
|
|
4073
|
+
* poll:`cursor`/`afterSeq` 不得低于已投递水位(R1-2);pin 是硬上限,超出给 `gap`/`dropped`。
|
|
4074
|
+
*/
|
|
4075
|
+
export function subscriptionPoll(store, { subscriptionId, ownerSessionId, cursor = null, afterSeq = null, limit = null, kinds = null } = {}) {
|
|
4076
|
+
const record = subscriptionOf(store, subscriptionId, ownerSessionId);
|
|
4077
|
+
if (record.closed) throw new BrowserError('NET_SUBSCRIPTION_NOT_FOUND', '订阅已关闭', { subscriptionId: record.id });
|
|
4078
|
+
const size = limit === null || limit === undefined ? NET_LIMITS.subscriptionLimit : limit;
|
|
4079
|
+
if (!Number.isInteger(size) || size < 1 || size > NET_LIMITS.subscriptionLimit) {
|
|
4080
|
+
throw new BrowserError('NET_INVALID_ARGUMENT', `limit 必须是 1–${NET_LIMITS.subscriptionLimit} 的整数`, { field: 'limit' });
|
|
4081
|
+
}
|
|
4082
|
+
const explicit = Number.isInteger(afterSeq) ? afterSeq : decodeCursor(cursor);
|
|
4083
|
+
let from = explicit === null || explicit === undefined ? record.deliveredSeq : explicit;
|
|
4084
|
+
if (from < record.deliveredSeq) {
|
|
4085
|
+
throw new BrowserError('NET_RULE_INVALID', 'poll 游标不得低于已投递水位(防重复投递)', {
|
|
4086
|
+
cursor: from, deliveredSeq: record.deliveredSeq,
|
|
4087
|
+
});
|
|
4088
|
+
}
|
|
4089
|
+
// pin 硬上限:未 ack 的窗口最多 subscriptionPin 条
|
|
4090
|
+
const floor = Math.max(record.ackedSeq, store.seq - NET_LIMITS.subscriptionPin);
|
|
4091
|
+
let gap = null;
|
|
4092
|
+
if (from < floor) {
|
|
4093
|
+
gap = { from: from + 1, to: floor, dropped: floor - from };
|
|
4094
|
+
record.droppedPinned += floor - from;
|
|
4095
|
+
record.pinned = true;
|
|
4096
|
+
from = floor;
|
|
4097
|
+
}
|
|
4098
|
+
const filterKinds = kinds === null || kinds === undefined ? record.kinds : kinds;
|
|
4099
|
+
const events = [];
|
|
4100
|
+
let lastSeq = from;
|
|
4101
|
+
let more = false;
|
|
4102
|
+
for (const event of store.events) {
|
|
4103
|
+
if (event.seq <= from) continue;
|
|
4104
|
+
if (filterKinds && !filterKinds.includes(event.kind)) { lastSeq = event.seq; continue; }
|
|
4105
|
+
if (events.length >= size) { more = true; break; }
|
|
4106
|
+
events.push(projectSummary(store, event));
|
|
4107
|
+
lastSeq = event.seq;
|
|
4108
|
+
}
|
|
4109
|
+
record.deliveredSeq = Math.max(record.deliveredSeq, lastSeq);
|
|
4110
|
+
record.polls += 1;
|
|
4111
|
+
record.delivered += events.length;
|
|
4112
|
+
record.pinned = store.seq - record.ackedSeq > NET_LIMITS.subscriptionPin;
|
|
4113
|
+
return {
|
|
4114
|
+
ok: true,
|
|
4115
|
+
subscriptionId: record.id,
|
|
4116
|
+
events,
|
|
4117
|
+
cursor: { next: encodeCursor(record.deliveredSeq) },
|
|
4118
|
+
deliveredSeq: record.deliveredSeq,
|
|
4119
|
+
ackedSeq: record.ackedSeq,
|
|
4120
|
+
hasMore: more,
|
|
4121
|
+
...(gap ? { gap } : {}),
|
|
4122
|
+
counters: {
|
|
4123
|
+
delivered: record.delivered,
|
|
4124
|
+
pending: Math.max(0, store.seq - record.ackedSeq),
|
|
4125
|
+
pinned: Math.min(Math.max(0, store.seq - record.ackedSeq), NET_LIMITS.subscriptionPin),
|
|
4126
|
+
dropped: record.droppedPinned,
|
|
4127
|
+
},
|
|
4128
|
+
integrity: store.integrity(),
|
|
4129
|
+
};
|
|
4130
|
+
}
|
|
4131
|
+
|
|
4132
|
+
/** ack:只能确认已交付边界(R1-2)。 */
|
|
4133
|
+
export function subscriptionAck(store, { subscriptionId, ownerSessionId, ackSeq = null } = {}) {
|
|
4134
|
+
const record = subscriptionOf(store, subscriptionId, ownerSessionId);
|
|
4135
|
+
const target = Number.isInteger(ackSeq) ? ackSeq : record.deliveredSeq;
|
|
4136
|
+
if (target > record.deliveredSeq) {
|
|
4137
|
+
throw new BrowserError('NET_RULE_INVALID', 'ackSeq 不能超过已交付水位', { ackSeq: target, deliveredSeq: record.deliveredSeq });
|
|
4138
|
+
}
|
|
4139
|
+
if (target < record.ackedSeq) {
|
|
4140
|
+
throw new BrowserError('NET_RULE_INVALID', 'ackSeq 不能小于当前 ack', { ackSeq: target, ackedSeq: record.ackedSeq });
|
|
4141
|
+
}
|
|
4142
|
+
record.ackedSeq = target;
|
|
4143
|
+
record.pinned = store.seq - record.ackedSeq > NET_LIMITS.subscriptionPin;
|
|
4144
|
+
return {
|
|
4145
|
+
ok: true, subscriptionId: record.id, ackedSeq: record.ackedSeq,
|
|
4146
|
+
cursor: { next: encodeCursor(record.deliveredSeq) },
|
|
4147
|
+
counters: {
|
|
4148
|
+
delivered: record.delivered,
|
|
4149
|
+
pending: Math.max(0, store.seq - record.ackedSeq),
|
|
4150
|
+
pinned: Math.min(Math.max(0, store.seq - record.ackedSeq), NET_LIMITS.subscriptionPin),
|
|
4151
|
+
dropped: record.droppedPinned,
|
|
4152
|
+
},
|
|
4153
|
+
};
|
|
4154
|
+
}
|
|
4155
|
+
|
|
4156
|
+
export function subscriptionClose(store, { subscriptionId, ownerSessionId } = {}) {
|
|
4157
|
+
const record = subscriptionOf(store, subscriptionId, ownerSessionId);
|
|
4158
|
+
record.closed = true;
|
|
4159
|
+
store.subscriptions.delete(record.id);
|
|
4160
|
+
return { ok: true, subscriptionId: record.id, closed: true };
|
|
4161
|
+
}
|
|
4162
|
+
|
|
4163
|
+
export function subscriptionList(store, { ownerSessionId } = {}) {
|
|
4164
|
+
return {
|
|
4165
|
+
ok: true,
|
|
4166
|
+
subscriptions: [...store.subscriptions.values()]
|
|
4167
|
+
.filter((record) => record.ownerSessionId === ownerSessionId)
|
|
4168
|
+
.map((record) => ({
|
|
4169
|
+
subscriptionId: record.id, kinds: record.kinds, cursor: { next: encodeCursor(record.deliveredSeq) },
|
|
4170
|
+
ackedSeq: record.ackedSeq, createdAt: record.createdAt, polls: record.polls,
|
|
4171
|
+
delivered: record.delivered, pinned: record.pinned, droppedPinned: record.droppedPinned,
|
|
4172
|
+
})),
|
|
4173
|
+
};
|
|
4174
|
+
}
|
|
4175
|
+
|
|
4176
|
+
/* ------------------------------------------------------------------ */
|
|
4177
|
+
/* 能力报告(§8.8) */
|
|
4178
|
+
/* ------------------------------------------------------------------ */
|
|
4179
|
+
|
|
4180
|
+
export const NETWORK_TOOL_NAMES = Object.freeze([
|
|
4181
|
+
'browser_network_session', 'browser_network_events', 'browser_network_detail',
|
|
4182
|
+
'browser_network_trace', 'browser_network_control', 'browser_network_evidence',
|
|
4183
|
+
'browser_network_subscribe',
|
|
4184
|
+
]);
|
|
4185
|
+
|
|
4186
|
+
/** §8.8 `capabilities.network` 段。`observed` 只来自真实调用(由 Host 写入 store.observed)。 */
|
|
4187
|
+
export function networkCapabilities(store, { control = null, subTargets = null } = {}) {
|
|
4188
|
+
const status = store.status();
|
|
4189
|
+
const observed = store.observed && typeof store.observed === 'object'
|
|
4190
|
+
? {
|
|
4191
|
+
lastCallAt: Number.isFinite(store.observed.lastCallAt) ? store.observed.lastCallAt : null,
|
|
4192
|
+
lastOperation: typeof store.observed.lastOperation === 'string' ? store.observed.lastOperation : null,
|
|
4193
|
+
}
|
|
4194
|
+
: null;
|
|
4195
|
+
return {
|
|
4196
|
+
version: NET_VERSION,
|
|
4197
|
+
tools: [...NETWORK_TOOL_NAMES],
|
|
4198
|
+
session: status.session
|
|
4199
|
+
? {
|
|
4200
|
+
id: status.session.id,
|
|
4201
|
+
state: status.session.state,
|
|
4202
|
+
counters: { ...status.session.counters },
|
|
4203
|
+
integrity: {
|
|
4204
|
+
complete: status.session.integrity.complete,
|
|
4205
|
+
dropped: status.session.integrity.dropped,
|
|
4206
|
+
evicted: status.session.integrity.evicted,
|
|
4207
|
+
truncated: status.session.integrity.truncated,
|
|
4208
|
+
bodyEvicted: status.session.integrity.bodyEvicted,
|
|
4209
|
+
},
|
|
4210
|
+
}
|
|
4211
|
+
: { id: null, state: null, counters: null, integrity: null },
|
|
4212
|
+
limits: {
|
|
4213
|
+
...limitsView(),
|
|
4214
|
+
network: {
|
|
4215
|
+
capture: true,
|
|
4216
|
+
bodies: true,
|
|
4217
|
+
websocket: true,
|
|
4218
|
+
sse: true,
|
|
4219
|
+
workers: true,
|
|
4220
|
+
interception: true,
|
|
4221
|
+
responseModification: control ? control.responseModification === true : false,
|
|
4222
|
+
throttle: true,
|
|
4223
|
+
offline: true,
|
|
4224
|
+
replay: true,
|
|
4225
|
+
mock: true,
|
|
4226
|
+
har: true,
|
|
4227
|
+
jsonl: true,
|
|
4228
|
+
subscriptions: true,
|
|
4229
|
+
responseModification: control ? control.responseModification === true : false,
|
|
4230
|
+
// §8.8 scalar fields read at `capabilities.network.limits.network.<field>`; the numeric
|
|
4231
|
+
// bounds live in `throttleLimits` so the capability flags stay booleans as specified.
|
|
4232
|
+
https: 'mechanism-identical',
|
|
4233
|
+
throttleLimits: { latencyMsMax: 60000, downloadKbpsMax: 1000000, uploadKbpsMax: 1000000, unit: 'Kbps = 1024 bit/s' },
|
|
4234
|
+
holdLimits: { maxHeld: NET_LIMITS.held, timeoutMs: NET_LIMITS.holdTimeoutMs },
|
|
4235
|
+
ruleLimits: { max: NET_LIMITS.rules, kinds: [...NET_RULE_KINDS] },
|
|
4236
|
+
...(subTargets && typeof subTargets === 'object' ? { subTargets: { ...subTargets } } : {}),
|
|
4237
|
+
},
|
|
4238
|
+
// Also mirrored one level up: the acceptance suite reads `capabilities.network.limits.<field>`.
|
|
4239
|
+
https: 'mechanism-identical',
|
|
4240
|
+
...(subTargets && typeof subTargets === 'object' ? { subTargets: { ...subTargets } } : {}),
|
|
4241
|
+
throttleLimits: { latencyMsMax: 60000, downloadKbpsMax: 1000000, uploadKbpsMax: 1000000, unit: 'Kbps = 1024 bit/s' },
|
|
4242
|
+
holdLimits: { maxHeld: NET_LIMITS.held, timeoutMs: NET_LIMITS.holdTimeoutMs },
|
|
4243
|
+
ruleLimits: { max: NET_LIMITS.rules, kinds: [...NET_RULE_KINDS] },
|
|
4244
|
+
},
|
|
4245
|
+
observed,
|
|
4246
|
+
};
|
|
4247
|
+
}
|
|
4248
|
+
|
|
4249
|
+
export default {
|
|
4250
|
+
NetworkStore, ControlState, NET_VERSION, NET_LIMITS, NET_DEFAULTS,
|
|
4251
|
+
NET_BODY_REASON_CODES, classifyBodyFailure, normalizeBodyReasonDetail,
|
|
4252
|
+
queryEvents, detailEvent, traceNetwork, evidenceBlock, networkCapabilities,
|
|
4253
|
+
toJsonl, fromJsonl, toHar, fromHar, loadImported, parseImportedEvidence,
|
|
4254
|
+
resolveEvidencePath, publishEvidence, registerArtifact, listArtifacts, searchArtifacts,
|
|
4255
|
+
indexView, clearArtifacts, subscriptionCreate, subscriptionPoll, subscriptionAck,
|
|
4256
|
+
subscriptionClose, subscriptionList, validateRule, validateThen, matchRule,
|
|
4257
|
+
firstMatchingRule, buildFetchPatterns, decidePausedAction, conditionParams,
|
|
4258
|
+
NETWORK_UNTHROTTLED, extractCorrelationIds, extractBusinessCode, detectPolling,
|
|
4259
|
+
detectRetries, normalizeEvent, normalizeSessionConfig, normalizeTiming, sanitizeBody,
|
|
4260
|
+
sanitizeHeaders, sanitizeUrl, parseQueryString, readJsonPath, percentile, statusClass,
|
|
4261
|
+
truncateBytes, matchUrlPattern, encodeCursor, decodeCursor, requestKey, limitsView,
|
|
4262
|
+
estimateEventBytes, urlHashOf, hmacHex, validateObjectRules, validateCorrelationRules,
|
|
4263
|
+
extractObjects, emptyTiming, emptyCounters,
|
|
4264
|
+
};
|