@liang-hz/agent-in-chrome 0.55.0

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.
Files changed (112) hide show
  1. package/.ext-id.txt +4 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/PRIVACY.md +86 -0
  5. package/README.en.md +419 -0
  6. package/README.md +406 -0
  7. package/bin/agent-in-chrome.mjs +97 -0
  8. package/commands/agent-in-chrome.md +18 -0
  9. package/commands/install-agent-in-chrome.md +22 -0
  10. package/docs/AGENTS.md +94 -0
  11. package/docs/CLI.md +297 -0
  12. package/docs/client-compat.json +23 -0
  13. package/extension/about-toc.js +25 -0
  14. package/extension/about.html +240 -0
  15. package/extension/about.js +44 -0
  16. package/extension/agent-window.html +100 -0
  17. package/extension/icons/icon-128.png +0 -0
  18. package/extension/icons/icon-16.png +0 -0
  19. package/extension/icons/icon-24.png +0 -0
  20. package/extension/icons/icon-32.png +0 -0
  21. package/extension/icons/icon-48.png +0 -0
  22. package/extension/icons/icon-64.png +0 -0
  23. package/extension/icons/icon-attention-128.png +0 -0
  24. package/extension/icons/icon-attention-16.png +0 -0
  25. package/extension/icons/icon-attention-24.png +0 -0
  26. package/extension/icons/icon-attention-32.png +0 -0
  27. package/extension/icons/icon-attention-48.png +0 -0
  28. package/extension/icons/icon-attention-64.png +0 -0
  29. package/extension/icons/icon-attention.svg +18 -0
  30. package/extension/icons/icon-failed-128.png +0 -0
  31. package/extension/icons/icon-failed-16.png +0 -0
  32. package/extension/icons/icon-failed-24.png +0 -0
  33. package/extension/icons/icon-failed-32.png +0 -0
  34. package/extension/icons/icon-failed-48.png +0 -0
  35. package/extension/icons/icon-failed-64.png +0 -0
  36. package/extension/icons/icon-failed.svg +18 -0
  37. package/extension/icons/icon-idle-128.png +0 -0
  38. package/extension/icons/icon-idle-16.png +0 -0
  39. package/extension/icons/icon-idle-24.png +0 -0
  40. package/extension/icons/icon-idle-32.png +0 -0
  41. package/extension/icons/icon-idle-48.png +0 -0
  42. package/extension/icons/icon-idle-64.png +0 -0
  43. package/extension/icons/icon-idle.svg +18 -0
  44. package/extension/icons/icon-mark.svg +10 -0
  45. package/extension/icons/icon-running-128.png +0 -0
  46. package/extension/icons/icon-running-16.png +0 -0
  47. package/extension/icons/icon-running-24.png +0 -0
  48. package/extension/icons/icon-running-32.png +0 -0
  49. package/extension/icons/icon-running-48.png +0 -0
  50. package/extension/icons/icon-running-64.png +0 -0
  51. package/extension/icons/icon-running.svg +18 -0
  52. package/extension/icons/icon.svg +18 -0
  53. package/extension/manifest.json +44 -0
  54. package/extension/popup-ui.js +38 -0
  55. package/extension/popup.html +350 -0
  56. package/extension/popup.js +741 -0
  57. package/extension/sw.js +11127 -0
  58. package/extension/update-check.js +66 -0
  59. package/extension/welcome.html +110 -0
  60. package/extension/welcome.js +18 -0
  61. package/mcp/agent-identity.mjs +1007 -0
  62. package/mcp/cdp/bridge.mjs +239 -0
  63. package/mcp/cdp/browser-launch.mjs +1127 -0
  64. package/mcp/cdp/chrome-shim.mjs +1124 -0
  65. package/mcp/cdp/client.mjs +443 -0
  66. package/mcp/cli-invocation.mjs +67 -0
  67. package/mcp/config.mjs +191 -0
  68. package/mcp/foreground-guard.mjs +295 -0
  69. package/mcp/proc-win.mjs +112 -0
  70. package/mcp/secret-shape.mjs +155 -0
  71. package/mcp/server.mjs +3437 -0
  72. package/mcp/session-id.mjs +281 -0
  73. package/mcp/token.mjs +260 -0
  74. package/mcp/tool-tiers.mjs +84 -0
  75. package/mcp/trace.mjs +528 -0
  76. package/mcp/update-cli.mjs +163 -0
  77. package/mcp/update-notice.mjs +194 -0
  78. package/native-host/host.mjs +356 -0
  79. package/native-host/mac-foreground/aic-fg.swift +114 -0
  80. package/native-host/mac-foreground/build.mjs +43 -0
  81. package/package.json +46 -0
  82. package/scripts/agents.mjs +921 -0
  83. package/scripts/borrow-login.mjs +935 -0
  84. package/scripts/cli-browser.mjs +148 -0
  85. package/scripts/e2e-sweep.mjs +192 -0
  86. package/scripts/e2e.mjs +3911 -0
  87. package/scripts/fixture-server.mjs +1419 -0
  88. package/scripts/guard-publish.mjs +175 -0
  89. package/scripts/install.mjs +1383 -0
  90. package/scripts/launcher-provenance.mjs +74 -0
  91. package/scripts/pack-crx.mjs +82 -0
  92. package/scripts/pick.mjs +114 -0
  93. package/scripts/test-agents.mjs +968 -0
  94. package/scripts/test-borrow.mjs +289 -0
  95. package/scripts/test-config.mjs +618 -0
  96. package/scripts/test-e2e-sweep.mjs +251 -0
  97. package/scripts/test-foreground-guard.mjs +383 -0
  98. package/scripts/test-identity.mjs +1141 -0
  99. package/scripts/test-install-skill.mjs +378 -0
  100. package/scripts/test-protocol.mjs +712 -0
  101. package/scripts/test-security.mjs +1360 -0
  102. package/scripts/test-sw.mjs +14526 -0
  103. package/scripts/test-update.mjs +301 -0
  104. package/skills/agent-in-chrome/SKILL.md +60 -0
  105. package/skills/agent-in-chrome/references/actions-and-waits.md +136 -0
  106. package/skills/agent-in-chrome/references/amap-dir-dropdown.md +66 -0
  107. package/skills/agent-in-chrome/references/geetest-click-captcha.md +55 -0
  108. package/skills/agent-in-chrome/references/network-debugging.md +20 -0
  109. package/skills/agent-in-chrome/references/reading-pages.md +30 -0
  110. package/skills/agent-in-chrome/references/recovery.md +25 -0
  111. package/skills/agent-in-chrome/references/tabs-and-sessions.md +34 -0
  112. package/skills/install-agent-in-chrome/SKILL.md +252 -0
@@ -0,0 +1,295 @@
1
+ // 本机侧「因果归还前台」:agent 引出的新页会让 Chrome 把**整个 app** 抢到前台(那一下写死
2
+ // 在浏览器进程里,扩展层拦不住),这一层只做一件事——**我们抢走的,当场还回去**。
3
+ // 两条缺一不可:`callBrowser()` 下发时 `arm()` 记下此刻的前台 app;扩展凭因果认领新页时
4
+ // 回一帧 `foreground-restore` → `confirm()`;两条同时成立才 activate 回去。判据全是因果,
5
+ // 这里一个字都不认「Chrome」。失败方向是宁可不还、也不硬拽:非 macOS / helper 起不来 /
6
+ // 采样工具都没有 → 整个特性静默不生效,不报错、不影响任何工具调用。
7
+
8
+ import { spawn as nodeSpawn } from "node:child_process";
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+
13
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
14
+
15
+ /*
16
+ * 武装的有效期。
17
+ *
18
+ * 要罩住扩展那侧的 `SPAWN_ACTION_WINDOW_MS`(5s:「点了按钮 → 发一次请求拿到跳转
19
+ * 地址 → 再 window.open」这种慢接口形态)。放长不危险——真正把闸打开的是 confirm,
20
+ * 而 confirm 本身就是因果信号;武装只负责「记下用户当时在哪」。
21
+ */
22
+ export const ARM_TTL_MS = 5500;
23
+
24
+ const SAMPLE_FRESH_MS = 2000;
25
+ const SAMPLE_THROTTLE_MS = 250;
26
+
27
+ export function helperCandidates(base = HERE) {
28
+ return [
29
+ process.env.AGENT_IN_CHROME_FG_HELPER,
30
+ path.join(base, "mac-foreground", "aic-fg"),
31
+ path.join(base, "..", "native-host", "mac-foreground", "aic-fg"),
32
+ ].filter(Boolean);
33
+ }
34
+
35
+ function findHelper(base, exists) {
36
+ for (const c of helperCandidates(base)) {
37
+ try {
38
+ if (exists(c)) return c;
39
+ } catch {}
40
+ }
41
+ return null;
42
+ }
43
+
44
+ const defaultExists = (p) => {
45
+ try {
46
+ fs.accessSync(p, fs.constants.X_OK);
47
+ return true;
48
+ } catch {
49
+ return false;
50
+ }
51
+ };
52
+
53
+ /*
54
+ * 建一个守护。**惰性**:不 `arm()` 就一个子进程都不起(Chrome 开着但没 agent 干活
55
+ * 是一天里的大多数时间,那段时间这里应当零成本)。
56
+ *
57
+ * 依赖全部可注入,测试用假 helper 子进程 / 假 spawn 跑完整条路,不碰真的窗口系统。
58
+ */
59
+ export function createForegroundGuard({
60
+ platform = process.platform,
61
+ spawn = nodeSpawn,
62
+ base = HERE,
63
+ exists = defaultExists,
64
+ now = Date.now,
65
+ armTtlMs = ARM_TTL_MS,
66
+ log = () => {},
67
+ enabled = process.env.AGENT_IN_CHROME_NO_FG_GUARD !== "1",
68
+ } = {}) {
69
+ const stats = {
70
+ mode: "off",
71
+ spawns: 0,
72
+ arms: 0,
73
+ confirms: 0,
74
+ restores: 0,
75
+ skips: 0,
76
+ lastEvent: null,
77
+ lastSkip: null,
78
+ };
79
+ const inert = platform !== "darwin" || !enabled;
80
+
81
+ let child = null;
82
+ let started = false;
83
+ let helperPath = null;
84
+ let stdoutBuf = "";
85
+ const events = [];
86
+
87
+ let sample = null;
88
+ let sampling = false;
89
+ let lastSampleAt = 0;
90
+ let armedUntil = 0;
91
+ let armBase = null;
92
+
93
+ function sampleFront(cb) {
94
+ if (sampling) return;
95
+ const t = now();
96
+ if (t - lastSampleAt < SAMPLE_THROTTLE_MS && sample) return cb?.(sample);
97
+ sampling = true;
98
+ lastSampleAt = t;
99
+ let out = "";
100
+ let p;
101
+ try {
102
+ p = spawn("/usr/bin/lsappinfo", ["list"], { stdio: ["ignore", "pipe", "ignore"] });
103
+ } catch {
104
+ sampling = false;
105
+ return;
106
+ }
107
+ p.stdout?.on("data", (d) => {
108
+ out += d;
109
+ });
110
+ p.on("error", () => {
111
+ sampling = false;
112
+ });
113
+ p.on("close", () => {
114
+ sampling = false;
115
+ const i = out.indexOf("(in front)");
116
+ if (i < 0) return;
117
+ const m = /bundleID="([^"]+)"/.exec(out.slice(i, i + 400));
118
+ if (!m) return;
119
+ sample = { bundleId: m[1], at: now() };
120
+ cb?.(sample);
121
+ });
122
+ }
123
+
124
+ function fallbackConfirm() {
125
+ const t = now();
126
+ const b = armBase;
127
+ if (t > armedUntil) return note("skip", { why: "not-armed" });
128
+ if (!b || t - b.at > SAMPLE_FRESH_MS) return note("skip", { why: "no-base" });
129
+ sampling = false;
130
+ lastSampleAt = 0;
131
+ sampleFront((s) => {
132
+ if (!s || s.bundleId === b.bundleId) return note("skip", { why: "no-steal" });
133
+ if (now() > armedUntil) return note("skip", { why: "not-armed" });
134
+ try {
135
+ const p = spawn("/usr/bin/open", ["-b", b.bundleId], { stdio: "ignore" });
136
+ p.on("error", () => {});
137
+ } catch {
138
+ return note("skip", { why: "open-failed" });
139
+ }
140
+ note("restore", { to: b.bundleId, via: "open -b", exposureMs: null });
141
+ });
142
+ }
143
+
144
+ function note(t, extra) {
145
+ const ev = { t, ms: now(), ...extra };
146
+ stats.lastEvent = ev;
147
+ if (t === "restore") stats.restores++;
148
+ if (t === "skip") {
149
+ stats.skips++;
150
+ stats.lastSkip = ev.why || null;
151
+ }
152
+ events.push(ev);
153
+ if (events.length > 64) events.shift();
154
+ log(ev);
155
+ return ev;
156
+ }
157
+
158
+ function ensureChild() {
159
+ if (started) return;
160
+ started = true;
161
+ helperPath = findHelper(base, exists);
162
+ if (!helperPath) {
163
+ stats.mode = "fallback";
164
+ log({ t: "mode", mode: "fallback", why: "没找到 aic-fg helper" });
165
+ return;
166
+ }
167
+ try {
168
+ child = spawn(helperPath, [], { stdio: ["pipe", "pipe", "ignore"] });
169
+ } catch (e) {
170
+ child = null;
171
+ stats.mode = "fallback";
172
+ log({ t: "mode", mode: "fallback", why: `helper 起不来:${e?.message || e}` });
173
+ return;
174
+ }
175
+ stats.spawns++;
176
+ stats.mode = "helper";
177
+ child.unref?.();
178
+ child.stdin?.on("error", () => {});
179
+ child.stdout?.setEncoding("utf8");
180
+ child.stdout?.on("data", (d) => {
181
+ stdoutBuf += d;
182
+ let i;
183
+ while ((i = stdoutBuf.indexOf("\n")) >= 0) {
184
+ const line = stdoutBuf.slice(0, i).trim();
185
+ stdoutBuf = stdoutBuf.slice(i + 1);
186
+ if (!line) continue;
187
+ let ev;
188
+ try {
189
+ ev = JSON.parse(line);
190
+ } catch {
191
+ continue;
192
+ }
193
+ note(ev.t, ev);
194
+ }
195
+ });
196
+ child.on("error", () => {});
197
+ child.on("exit", () => {
198
+ child = null;
199
+ stats.mode = "fallback";
200
+ });
201
+ }
202
+
203
+ function toHelper(line) {
204
+ if (!child || !child.stdin || child.stdin.destroyed) return false;
205
+ try {
206
+ return child.stdin.write(line + "\n");
207
+ } catch {
208
+ return false;
209
+ }
210
+ }
211
+
212
+ return {
213
+ stats: () => ({ ...stats }),
214
+ events: () => events.slice(),
215
+ helperPath: () => helperPath,
216
+
217
+ /*
218
+ * 一次工具下发。记下「此刻用户在哪」。绝不阻塞调用方。
219
+ * @returns {boolean} 有没有真的武装(非 macOS / 关掉了 → false)
220
+ */
221
+ arm() {
222
+ if (inert) return false;
223
+ ensureChild();
224
+ stats.arms++;
225
+ log({ t: "arm", mode: stats.mode, ttlMs: armTtlMs });
226
+ if (child) return toHelper(`arm ${armTtlMs}`);
227
+ armedUntil = now() + armTtlMs;
228
+ armBase = null;
229
+ sampleFront((s) => {
230
+ if (now() <= armedUntil) armBase = s;
231
+ });
232
+ return true;
233
+ },
234
+
235
+ /* 结果因到了:扩展凭因果认领了这一动作引出的新页 */
236
+ confirm(info = {}) {
237
+ if (inert) return false;
238
+ if (!started) return false;
239
+ stats.confirms++;
240
+ log({ t: "confirm", mode: stats.mode, tabId: info?.tabId, sid: info?.sid });
241
+ if (child) return toHelper("confirm");
242
+ fallbackConfirm();
243
+ return true;
244
+ },
245
+
246
+ disarm() {
247
+ if (inert) return false;
248
+ log({ t: "disarm", mode: stats.mode });
249
+ armedUntil = 0;
250
+ armBase = null;
251
+ if (child) return toHelper("disarm");
252
+ return true;
253
+ },
254
+
255
+ stop() {
256
+ armedUntil = 0;
257
+ armBase = null;
258
+ const c = child;
259
+ child = null;
260
+ if (!c) return;
261
+ try {
262
+ c.stdin?.write("quit\n");
263
+ } catch {}
264
+ try {
265
+ c.kill();
266
+ } catch {}
267
+ },
268
+ };
269
+ }
270
+
271
+ /* 可开关的取证日志:`AGENT_IN_CHROME_FG_TRACE=<文件>` 一开,每一次 arm / confirm / disarm
272
+ * 和 helper 回上来的每一条事件(armed / steal / restore / skip)都按 JSONL 追加,带 pid 和
273
+ * 毫秒时刻。默认关闭,写不出文件就当没有,绝不影响调用。 */
274
+ function traceLogger() {
275
+ const f = process.env.AGENT_IN_CHROME_FG_TRACE;
276
+ if (!f) return () => {};
277
+ return (ev) => {
278
+ try {
279
+ fs.appendFileSync(f, JSON.stringify({ pid: process.pid, at: Date.now(), ...ev }) + "\n");
280
+ } catch {}
281
+ };
282
+ }
283
+
284
+ /* 进程级单例。server.mjs 只用这一个 */
285
+ let singleton = null;
286
+ export function foregroundGuard() {
287
+ if (!singleton) singleton = createForegroundGuard({ log: traceLogger() });
288
+ return singleton;
289
+ }
290
+ export function resetForegroundGuard() {
291
+ try {
292
+ singleton?.stop();
293
+ } catch {}
294
+ singleton = null;
295
+ }
@@ -0,0 +1,112 @@
1
+ // 对外只有 winProc() / makeWinProcSource(),形状与 POSIX 版 procSource 相同:`.get(pid)`
2
+ // 回 {ppid, tty, command, name, start}。两个模块共用它——agent-identity 认「谁在开这一组」,
3
+ // session-id 认「是不是同一个客户端」;单开一个文件是因为 agent-identity 已经 import
4
+ // session-id,放进任何一边都会绕成循环依赖。取法与 POSIX 那边正好相反:一次把整条祖先链
5
+ // 取回来记住,全程只付一次 PowerShell 启动费。
6
+
7
+ import { execFileSync } from "node:child_process";
8
+
9
+ const MAX_HOPS = 12;
10
+
11
+ const TERMINALS = new Set([
12
+ "cmd.exe", "powershell.exe", "pwsh.exe", "windowsterminal.exe", "openconsole.exe",
13
+ "conhost.exe", "bash.exe", "sh.exe", "zsh.exe", "mintty.exe", "wsl.exe", "wslhost.exe",
14
+ "git-bash.exe", "alacritty.exe", "wezterm-gui.exe", "hyper.exe", "cygwin.exe",
15
+ ]);
16
+
17
+ const ROOTS = new Set(["explorer.exe", "services.exe", "wininit.exe", "winlogon.exe", "userinit.exe", "svchost.exe", "system", "idle"]);
18
+
19
+ export function isWinTerminal(name) {
20
+ return !!name && TERMINALS.has(String(name).toLowerCase());
21
+ }
22
+
23
+ export function isWinRoot(name) {
24
+ return !!name && ROOTS.has(String(name).toLowerCase());
25
+ }
26
+
27
+ function chainScript(pid, maxHops) {
28
+ return [
29
+ "$ErrorActionPreference='SilentlyContinue'",
30
+ "$m=@{}",
31
+ "foreach($p in Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,CreationDate,CommandLine,Name){$m[[uint32]$p.ProcessId]=$p}",
32
+ `$id=[uint32]${pid}`,
33
+ "$o=@()",
34
+ `for($i=0;$i -lt ${maxHops};$i++){`,
35
+ "$p=$m[$id]; if(-not $p){break}",
36
+ "$s=''; if($p.CreationDate){$s=[string]$p.CreationDate.ToFileTimeUtc()}",
37
+ "$o+=[pscustomobject]@{pid=[int]$p.ProcessId;ppid=[int]$p.ParentProcessId;name=[string]$p.Name;cmd=[string]$p.CommandLine;start=$s}",
38
+ "$id=[uint32]$p.ParentProcessId; if($id -le 0){break}}",
39
+ "ConvertTo-Json -Compress -Depth 3 -InputObject @($o)",
40
+ ].join(";");
41
+ }
42
+
43
+ function runChain(pid, exec, maxHops) {
44
+ const b64 = Buffer.from(chainScript(pid, maxHops), "utf16le").toString("base64");
45
+ const out = exec("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", b64], {
46
+ encoding: "utf8",
47
+ timeout: 8000,
48
+ windowsHide: true,
49
+ maxBuffer: 4 * 1024 * 1024,
50
+ stdio: ["ignore", "pipe", "ignore"],
51
+ });
52
+ const rows = JSON.parse(String(out || "[]").trim() || "[]");
53
+ return Array.isArray(rows) ? rows : [rows];
54
+ }
55
+
56
+ /*
57
+ * 和 POSIX 版 procSource 同形状的快照源:只需要 `.get(pid)`。
58
+ *
59
+ * 记忆化的是**整条链**:第一次 get() 把从那个 pid 往上的每一跳都填进 memo,
60
+ * 之后同一条链上的查询一次子进程都不再起。要查的 pid 不在 memo 里(链断了、
61
+ * 或调用方从别处拿了个 pid)才会再起一次,且总次数封顶——一个 server 进程里
62
+ * 起三次 PowerShell 已经说明链有问题,再起下去只是拖慢握手。
63
+ */
64
+ export function makeWinProcSource(exec = execFileSync, { maxHops = MAX_HOPS, maxQueries = 3 } = {}) {
65
+ const memo = new Map();
66
+ let queries = 0;
67
+ const load = (pid) => {
68
+ if (queries >= maxQueries) return;
69
+ queries++;
70
+ let rows = [];
71
+ try {
72
+ rows = runChain(pid, exec, maxHops);
73
+ } catch {
74
+ }
75
+ if (!memo.has(pid)) memo.set(pid, null);
76
+ for (const r of rows) {
77
+ const id = Number(r?.pid);
78
+ if (!Number.isInteger(id) || id <= 0) continue;
79
+ memo.set(id, {
80
+ ppid: Number.isInteger(Number(r.ppid)) ? Number(r.ppid) : null,
81
+ tty: null,
82
+ command: String(r.cmd || r.name || "").trim(),
83
+ name: String(r.name || "").trim(),
84
+ start: String(r.start || "") || null,
85
+ });
86
+ }
87
+ };
88
+ return {
89
+ get(pid) {
90
+ if (!Number.isInteger(pid) || pid <= 1) return null;
91
+ if (!memo.has(pid)) load(pid);
92
+ return memo.get(pid) || null;
93
+ },
94
+ };
95
+ }
96
+
97
+ /*
98
+ * 进程内共享的那一份:agent-identity 的 procSource 和 session-id 的
99
+ * processInfo / parentStartToken 认的必须是**同一张快照**——不只是省下两次
100
+ * PowerShell 启动,更是因为两边各查一次会看到两个时刻的进程表,锚点和身份指纹
101
+ * 对不上时的排查成本远高于这点开销。
102
+ */
103
+ let shared = null;
104
+ export function winProc(exec = execFileSync) {
105
+ if (!shared) shared = makeWinProcSource(exec || execFileSync);
106
+ return shared;
107
+ }
108
+
109
+ /* 只给测试用:换掉共享快照(传 null 恢复成真机的那一份) */
110
+ export function setWinProc(src) {
111
+ shared = src;
112
+ }
@@ -0,0 +1,155 @@
1
+ // 按**内容形状**认凭据——补上「按字段名认」认不出的那一类。
2
+ // 所以这里认的是**值长什么样**和**要的是什么**,与字段名无关:
3
+ // · JWT —— `eyJ` 开头的三段式。`eyJ` 是 base64 的 `{"`,加上两个点几乎不可能误命中
4
+ // · cookie 串 —— `a=1; b=2` 这种整串都是键值对的形状,要求 ≥2 对且整串匹配
5
+ // · 意图 —— eval 的表达式提到 document.cookie / localStorage 之类,
6
+ // 或 cdp 调的是取 cookie 的命令。这一路是零误报的,而且能盖住
7
+ // 「只有一个 cookie,凑不满两对」这种内容判据够不着的情形
8
+ // 打码不是抹掉:`describe()` 会把**形状**如实说清楚(是什么、多长、cookie 有哪些名字),
9
+ // 因为「这个站有没有 sessionid」是正当问题,而回答它不需要值。
10
+
11
+ const JWT = /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}\b/;
12
+
13
+ const COOKIE_JAR = /^[A-Za-z0-9_\-.~%]+=[^;=]*(?:;\s*[A-Za-z0-9_\-.~%]+=[^;=]*)+$/;
14
+
15
+ const TOKENISH = /^[A-Za-z0-9_\-.%~+/=]{16,}$/;
16
+
17
+ function hasOpaqueValue(s) {
18
+ return s.split(/;\s*/).some((p) => TOKENISH.test(p.slice(p.indexOf("=") + 1)));
19
+ }
20
+
21
+ const CRED_EXPR = /document\s*\.\s*cookie|(?:local|session)Storage/i;
22
+
23
+ /*
24
+ * 意图判据触发打码的最短长度:短到装不下一个会话凭据的返回值一律放行——
25
+ * 宁可漏掉 `sid=x` 这种玩具值,也不能把正常的状态字符串打成码。
26
+ * 内容判据(JWT / cookie 串)不受这条限制,它认的是形状,本来就自带长度要求。
27
+ */
28
+ export const INTENT_MIN = 16;
29
+
30
+ const CRED_CDP = /^(?:Storage\.getCookies|Network\.get(?:All)?Cookies|Storage\.setCookies)$/;
31
+
32
+ /*
33
+ * 这个字符串本身像不像凭据。
34
+ * 只认前面说的两种形状——宁可漏,不可把正常数据打成码。
35
+ */
36
+ export function looksLikeSecret(s) {
37
+ if (typeof s !== "string") return false;
38
+ if (s.length < 24) return false;
39
+ if (JWT.test(s)) return true;
40
+ const t = s.trim();
41
+ return COOKIE_JAR.test(t) && hasOpaqueValue(t);
42
+ }
43
+
44
+ /*
45
+ * eval 的表达式是不是在要凭据。
46
+ * 这一路**看意图不看结果**,所以 `document.cookie` 只返回一个 cookie(凑不满两对)
47
+ * 时照样拦得住。
48
+ */
49
+ export function exprWantsSecrets(expression) {
50
+ return typeof expression === "string" && CRED_EXPR.test(expression);
51
+ }
52
+
53
+ export function methodWantsSecrets(method) {
54
+ return typeof method === "string" && CRED_CDP.test(method);
55
+ }
56
+
57
+ /*
58
+ * 把一个凭据值描述成「说得清形状、给不出值」的字符串。
59
+ *
60
+ * cookie 串会把**名字**列出来:「这个站登录了吗」「有没有 csrftoken」是正当问题,
61
+ * 回答它不需要值。名字最多列 12 个,免得一个塞了几十个 cookie 的站把摘要撑爆。
62
+ */
63
+ export function describe(v) {
64
+ if (typeof v !== "string") return `<凭据已隐去(${typeof v})>`;
65
+ const s = v.trim();
66
+ if (COOKIE_JAR.test(s) && hasOpaqueValue(s)) {
67
+ const names = s.split(/;\s*/).map((p) => p.split("=")[0]).filter(Boolean);
68
+ const shown = names.slice(0, 12).join("、");
69
+ const more = names.length > 12 ? `…等 ${names.length} 项` : "";
70
+ return `<cookie 串,${names.length} 项:${shown}${more};值已隐去,共 ${v.length} 字符>`;
71
+ }
72
+ if (JWT.test(v)) return `<含 JWT,值已隐去,共 ${v.length} 字符>`;
73
+ return `<凭据已隐去,共 ${v.length} 字符>`;
74
+ }
75
+
76
+ export function redactSecrets(node, depth = 0) {
77
+ let hit = false;
78
+ const walk = (n, d) => {
79
+ if (d > 6 || n == null) return n;
80
+ if (typeof n === "string") {
81
+ if (looksLikeSecret(n)) {
82
+ hit = true;
83
+ return describe(n);
84
+ }
85
+ return n;
86
+ }
87
+ if (Array.isArray(n)) return n.map((x) => walk(x, d + 1));
88
+ if (typeof n === "object") {
89
+ const out = {};
90
+ for (const [k, v] of Object.entries(n)) out[k] = walk(v, d + 1);
91
+ return out;
92
+ }
93
+ return n;
94
+ };
95
+ const value = walk(node, depth);
96
+ return { value, hit };
97
+ }
98
+
99
+ /*
100
+ * 把 cookie **对象**里的值隐去,名字/域名/属性照留。
101
+ *
102
+ * `Storage.getCookies` 回的是 `[{name,value,domain,httpOnly,…}]`——值是结构化的,
103
+ * 上面那套按字符串形状认的判据够不着它(单个 cookie value 就是一串随机字符,
104
+ * 和普通 id 长得一样,认它必然误报一片)。所以这条按**结构**认:
105
+ * 一个对象同时有 name 和 value,且 value 是字符串,那它就是一条 cookie。
106
+ *
107
+ * 保留 name/domain 是刻意的,和 browser_cookies_export 的默认返回值一个口径:
108
+ * 「这个站登录了吗、有几条、哪些是 httpOnly」都答得上来,唯独值给不出去。
109
+ */
110
+ export function redactCookieObjects(node, depth = 0) {
111
+ let hit = false;
112
+ const walk = (n, d) => {
113
+ if (d > 6 || n == null) return n;
114
+ if (Array.isArray(n)) return n.map((x) => walk(x, d + 1));
115
+ if (typeof n !== "object") return n;
116
+ const isCookie = typeof n.name === "string" && typeof n.value === "string";
117
+ const out = {};
118
+ for (const [k, v] of Object.entries(n)) {
119
+ if (isCookie && k === "value") {
120
+ hit = true;
121
+ out[k] = `<值已隐去,${v.length} 字符>`;
122
+ } else out[k] = walk(v, d + 1);
123
+ }
124
+ return out;
125
+ };
126
+ const value = walk(node, depth);
127
+ return { value, hit };
128
+ }
129
+
130
+ /*
131
+ * 「有没有」和「换掉」分开:`hasSecrets` / `hasCookieObjects` 只判有没有,不重建结构;
132
+ * 两个 redact 函数才做替换。判据完全复用同一套规则,两处只有「命中之后做什么」不同——
133
+ * 判据本身绝不能在这里另写一套,否则总有一天它们会认得不一样。
134
+ */
135
+ export function hasSecrets(node, depth = 0) {
136
+ const walk = (n, d) => {
137
+ if (d > 6 || n == null) return false;
138
+ if (typeof n === "string") return looksLikeSecret(n);
139
+ if (Array.isArray(n)) return n.some((x) => walk(x, d + 1));
140
+ if (typeof n === "object") return Object.values(n).some((v) => walk(v, d + 1));
141
+ return false;
142
+ };
143
+ return walk(node, depth);
144
+ }
145
+
146
+ export function hasCookieObjects(node, depth = 0) {
147
+ const walk = (n, d) => {
148
+ if (d > 6 || n == null) return false;
149
+ if (Array.isArray(n)) return n.some((x) => walk(x, d + 1));
150
+ if (typeof n !== "object") return false;
151
+ if (typeof n.name === "string" && typeof n.value === "string") return true;
152
+ return Object.values(n).some((v) => walk(v, d + 1));
153
+ };
154
+ return walk(node, depth);
155
+ }