@liang-hz/agent-in-chrome 0.55.2 → 0.56.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.
@@ -126,7 +126,11 @@ function firstExisting(cands) {
126
126
 
127
127
  /*
128
128
  * 找浏览器。优先级就是「越像用户日常那台越好」:
129
- * 正式版 Chrome → Beta/Canary → Chromium / Chrome for Testing(指纹会差,最后才用)。
129
+ * 正式版 Chrome → Beta/Canary → Chromium / Edge(指纹会差,最后才用)。
130
+ *
131
+ * Windows 的候选按安装范围排:系统级(Program Files)→ 32 位系统级(Program Files
132
+ * (x86),官方默认位置)→ 每用户(%LocalAppData%)。Beta/Canary/Dev 各有
133
+ * 自己的目录名(Chrome Beta / Chrome SxS / Chrome Dev),Canary 只发每用户安装。
130
134
  */
131
135
  export function findBrowser() {
132
136
  const explicit = process.env.AGENT_IN_CHROME_BIN;
@@ -136,6 +140,10 @@ export function findBrowser() {
136
140
  }
137
141
 
138
142
  const mac = process.platform === "darwin";
143
+ const win = process.platform === "win32";
144
+ const PF = process.env.ProgramFiles || "C:\\Program Files";
145
+ const PF86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
146
+ const LAD = process.env.LocalAppData || path.join(HOME, "AppData", "Local");
139
147
  const stableCands = mac
140
148
  ? [
141
149
  ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "正式版 Chrome"],
@@ -143,11 +151,21 @@ export function findBrowser() {
143
151
  ["/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta", "Chrome Beta"],
144
152
  ["/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary", "Chrome Canary"],
145
153
  ]
146
- : [
147
- ["/usr/bin/google-chrome", "正式版 Chrome"],
148
- ["/usr/bin/google-chrome-stable", "正式版 Chrome"],
149
- ["/opt/google/chrome/chrome", "正式版 Chrome"],
150
- ];
154
+ : win
155
+ ? [
156
+ [path.join(PF, "Google", "Chrome", "Application", "chrome.exe"), "正式版 Chrome"],
157
+ [path.join(PF86, "Google", "Chrome", "Application", "chrome.exe"), "正式版 Chrome"],
158
+ [path.join(LAD, "Google", "Chrome", "Application", "chrome.exe"), "正式版 Chrome"],
159
+ [path.join(PF, "Google", "Chrome Beta", "Application", "chrome.exe"), "Chrome Beta"],
160
+ [path.join(PF86, "Google", "Chrome Beta", "Application", "chrome.exe"), "Chrome Beta"],
161
+ [path.join(LAD, "Google", "Chrome Beta", "Application", "chrome.exe"), "Chrome Beta"],
162
+ [path.join(LAD, "Google", "Chrome SxS", "Application", "chrome.exe"), "Chrome Canary"],
163
+ ]
164
+ : [
165
+ ["/usr/bin/google-chrome", "正式版 Chrome"],
166
+ ["/usr/bin/google-chrome-stable", "正式版 Chrome"],
167
+ ["/opt/google/chrome/chrome", "正式版 Chrome"],
168
+ ];
151
169
  for (const [bin, kind] of stableCands) if (fs.existsSync(bin)) return { bin, kind, stable: true };
152
170
 
153
171
  const fallback = mac
@@ -158,22 +176,49 @@ export function findBrowser() {
158
176
  "Chrome for Testing",
159
177
  ],
160
178
  ]
161
- : [
162
- ["/usr/bin/chromium", "Chromium"],
163
- ["/usr/bin/chromium-browser", "Chromium"],
164
- ];
179
+ : win
180
+ ? [
181
+ [path.join(LAD, "Chromium", "Application", "chrome.exe"), "Chromium"],
182
+ [path.join(PF, "Chromium", "Application", "chrome.exe"), "Chromium"],
183
+ [path.join(PF86, "Microsoft", "Edge", "Application", "msedge.exe"), "Microsoft Edge"],
184
+ [path.join(PF, "Microsoft", "Edge", "Application", "msedge.exe"), "Microsoft Edge"],
185
+ [path.join(LAD, "Microsoft", "Edge", "Application", "msedge.exe"), "Microsoft Edge"],
186
+ ]
187
+ : [
188
+ ["/usr/bin/chromium", "Chromium"],
189
+ ["/usr/bin/chromium-browser", "Chromium"],
190
+ ];
165
191
  for (const [bin, kind] of fallback) if (fs.existsSync(bin)) return { bin, kind, stable: false };
166
192
 
167
193
  throw new Error(
168
194
  "找不到浏览器。CLI/headless 模式要用本机的 Chrome(指纹就该是它本来的样子):\n" +
169
195
  (mac
170
196
  ? " macOS:装 Google Chrome 到 /Applications 即可\n"
171
- : " Linux:apt install google-chrome-stable,或用 AGENT_IN_CHROME_BIN 指路径\n") +
197
+ : win
198
+ ? " Windows:装 Google Chrome(默认装到 Program Files 即可),或用 AGENT_IN_CHROME_BIN 指路径\n"
199
+ : " Linux:apt install google-chrome-stable,或用 AGENT_IN_CHROME_BIN 指路径\n") +
172
200
  "也可以用 AGENT_IN_CHROME_BIN 指定任意 Chromium 系二进制。"
173
201
  );
174
202
  }
175
203
 
176
204
  const versionCache = new Map();
205
+ function winMajorFromSiblingDir(bin) {
206
+ try {
207
+ const dirs = fs
208
+ .readdirSync(path.dirname(bin), { withFileTypes: true })
209
+ .filter((d) => d.isDirectory() && /^\d+\.\d+\.\d+\.\d+$/.test(d.name))
210
+ .map((d) => d.name)
211
+ .sort((a, b) => {
212
+ const pa = a.split(".").map(Number);
213
+ const pb = b.split(".").map(Number);
214
+ for (let i = 0; i < 4; i++) if (pa[i] !== pb[i]) return pb[i] - pa[i];
215
+ return 0;
216
+ });
217
+ return (dirs[0] || "").split(".")[0] || "";
218
+ } catch {
219
+ return "";
220
+ }
221
+ }
177
222
  function browserMajorVersion(bin) {
178
223
  let key = bin;
179
224
  try {
@@ -181,10 +226,14 @@ function browserMajorVersion(bin) {
181
226
  } catch {}
182
227
  if (versionCache.has(key)) return versionCache.get(key);
183
228
  let major = "";
184
- try {
185
- const out = execFileSync(bin, ["--version"], { encoding: "utf8" });
186
- major = (out.match(/(\d+)\.\d+\.\d+\.\d+/) || [])[1] || "";
187
- } catch {}
229
+ if (process.platform === "win32") {
230
+ major = winMajorFromSiblingDir(bin);
231
+ } else {
232
+ try {
233
+ const out = execFileSync(bin, ["--version"], { encoding: "utf8" });
234
+ major = (out.match(/(\d+)\.\d+\.\d+\.\d+/) || [])[1] || "";
235
+ } catch {}
236
+ }
188
237
  versionCache.set(key, major);
189
238
  return major;
190
239
  }
@@ -207,19 +256,15 @@ function headedUserAgent(bin) {
207
256
  */
208
257
  export const OWNER_FLAG = "--aic-owner";
209
258
 
210
- /*
211
- * 从浏览器进程的命令行里读出它的 `--user-data-dir`,读不到给 null。
212
- *
213
- * 值一直取到下一个 ` --` 开头的旗标为止:路径里带空格(macOS 的
214
- * `Application Support` 之流)不能把它截成半截。我们自己 spawn 的命令行里
215
- * user-data-dir 后面永远还有别的旗标(--remote-debugging-port 紧跟其后),
216
- * 所以这个边界总是存在。
217
- */
218
259
  export function profileDirFrom(cmd) {
219
- const m = /--user-data-dir=(.+?)(?=\s--|$)/.exec(String(cmd || ""));
220
- return m ? m[1] : null;
260
+ const m = /--user-data-dir=(.+?)(?=\s--|$)/.exec(String(cmd || "").trim());
261
+ return m ? m[1].replace(/^"|"$/g, "") : null;
221
262
  }
222
263
 
264
+ /* 目录等:Windows 的路径不分大小写(agent-identity 同款判据),POSIX 按字面 */
265
+ const dirEq = (a, b) =>
266
+ process.platform === "win32" ? String(a).toLowerCase() === String(b).toLowerCase() : a === b;
267
+
223
268
  /*
224
269
  * 从进程列表里挑出「我们起的、而且**没人要了**」的浏览器,返回它们的 pid。
225
270
  *
@@ -245,7 +290,7 @@ export function orphansFrom(procs, isAlive, { readRecord = null, excludeProfile
245
290
  if (!Number.isInteger(owner) || owner <= 0) continue;
246
291
  if (isAlive(owner)) continue;
247
292
  const profile = profileDirFrom(cmd);
248
- if (excludeProfile && profile === excludeProfile) continue;
293
+ if (excludeProfile && profile && dirEq(profile, excludeProfile)) continue;
249
294
  if (readRecord && profile) {
250
295
  const rec = readRecord(profile);
251
296
  if (rec && Number(rec.pid) === Number(p.pid)) {
@@ -260,6 +305,36 @@ export function orphansFrom(procs, isAlive, { readRecord = null, excludeProfile
260
305
 
261
306
  /* 本机进程快照,只取 pid + 完整命令行 */
262
307
  export function psSnapshot() {
308
+ if (process.platform === "win32") {
309
+ const tmp = path.join(os.tmpdir(), `aic-ps-${process.pid}-${Math.random().toString(36).slice(2)}.txt`);
310
+ const ps = path.join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
311
+ const script =
312
+ `$ProgressPreference = 'SilentlyContinue'\n` +
313
+ `Get-CimInstance Win32_Process -Property ProcessId,CommandLine | ForEach-Object {\n` +
314
+ ` if ($_.CommandLine) { $_.ProcessId.ToString() + "\`t" + ($_.CommandLine -replace "[\`r\`n]", " ") }\n` +
315
+ `} | Out-File -FilePath ${JSON.stringify(tmp)} -Encoding utf8`;
316
+ try {
317
+ execFileSync(ps, ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], {
318
+ stdio: ["ignore", "ignore", "ignore"],
319
+ timeout: 30_000,
320
+ windowsHide: true,
321
+ });
322
+ return fs
323
+ .readFileSync(tmp, "utf8")
324
+ .replace(/^/, "")
325
+ .split("\n")
326
+ .map((l) => /^(\d+)\t(.*)$/.exec(l.trim()))
327
+ .filter(Boolean)
328
+ .map((m) => ({ pid: Number(m[1]), cmd: m[2] }));
329
+ } catch (e) {
330
+ log(`Windows 进程表取不到(${String(e?.message || e).split("\n")[0].slice(0, 120)}):` + "孤儿清扫和认领这一拍看不到别的进程");
331
+ return [];
332
+ } finally {
333
+ try {
334
+ fs.unlinkSync(tmp);
335
+ } catch {}
336
+ }
337
+ }
263
338
  try {
264
339
  const out = execFileSync("/bin/ps", ["-eo", "pid=,command="], { encoding: "utf8", maxBuffer: 8 << 20 });
265
340
  return out
@@ -376,6 +451,7 @@ export async function sweepOrphansAsync({
376
451
  }
377
452
 
378
453
  function canGroupKill(pid, procs) {
454
+ if (process.platform === "win32") return false;
379
455
  const cmd = (procs || []).find((p) => Number(p?.pid) === Number(pid))?.cmd;
380
456
  const profile = cmd ? profileDirFrom(String(cmd)) : null;
381
457
  if (!profile) return true;
@@ -596,14 +672,6 @@ function clearPid() {
596
672
  dropLegacyIfOurs();
597
673
  }
598
674
 
599
- /*
600
- * 这个 pid 此刻是不是一个正跑着**本 profile** 的浏览器。
601
- *
602
- * 两道都必要:pid 会被系统复用(`kill(pid,0)` 只说明「有个进程」,不说明是哪个),
603
- * 而认 `--user-data-dir=<本 profile>` 才说明是「跑我们这个 profile 的」。
604
- * 这是所有「要不要把信号发给它」的最后一道闸——别的 profile 的浏览器命令行里写的是
605
- * 别的目录,过不了这一道,所以一份写错/别人的记录也带不动我们去杀它。
606
- */
607
675
  function pidRunsThisProfile(pid, procs = null) {
608
676
  if (!pid) return false;
609
677
  try {
@@ -611,18 +679,44 @@ function pidRunsThisProfile(pid, procs = null) {
611
679
  } catch {
612
680
  return false;
613
681
  }
682
+ const mine = (cmd) => {
683
+ const dir = profileDirFrom(cmd);
684
+ return !!dir && dirEq(dir, PROFILE_DIR);
685
+ };
614
686
  if (procs) {
615
687
  const hit = procs.find((x) => x.pid === Number(pid));
616
- return !!hit && hit.cmd.includes(`--user-data-dir=${PROFILE_DIR}`);
688
+ return !!hit && mine(hit.cmd);
689
+ }
690
+ if (process.platform === "win32") {
691
+ const cmd = winProcCmd(pid);
692
+ return cmd != null && mine(cmd);
617
693
  }
618
694
  try {
619
695
  const cmd = execFileSync("/bin/ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
620
- return cmd.includes(`--user-data-dir=${PROFILE_DIR}`);
696
+ return mine(cmd);
621
697
  } catch {
622
698
  return false;
623
699
  }
624
700
  }
625
701
 
702
+ function winProcCmd(pid) {
703
+ const ps = path.join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
704
+ const script =
705
+ `$ErrorActionPreference='SilentlyContinue';` +
706
+ `$c=(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").CommandLine;` +
707
+ `ConvertTo-Json -Compress -InputObject @($c)`;
708
+ const out = execFileSync(ps, ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], {
709
+ encoding: "utf8",
710
+ timeout: 8000,
711
+ windowsHide: true,
712
+ maxBuffer: 4 * 1024 * 1024,
713
+ stdio: ["ignore", "pipe", "ignore"],
714
+ });
715
+ const rows = JSON.parse(String(out || "[]").trim() || "[]");
716
+ const cmd = Array.isArray(rows) ? rows[0] : rows;
717
+ return typeof cmd === "string" && cmd ? cmd : null;
718
+ }
719
+
626
720
  /*
627
721
  * **我们给这个 profile 起的**那个浏览器还活着吗;活着就返回它的记录(pid 已核对过)。
628
722
  *
@@ -643,13 +737,29 @@ export function aliveBrowser() {
643
737
 
644
738
  /*
645
739
  * 谁正占着这个 profile(返回它的 pid,没人占返回 null)。
646
- * **Chrome 自己按 profile 记的,不是我们记的**:读 `<profile>/SingletonLock` 这个
647
- * 指向「主机名-pid」的符号链接。Chrome 一个 `--user-data-dir` 只准一个实例,
648
- * 第二个起来会输掉 ProcessSingleton 当场自杀。
740
+ * **macOS/Linux 上 Chrome 自己按 profile 记的,不是我们记的**:读
741
+ * `<profile>/SingletonLock` 这个指向「主机名-pid」的符号链接。Chrome 一个
742
+ * `--user-data-dir` 只准一个实例,第二个起来会输掉 ProcessSingleton 当场自杀。
649
743
  * 这里只探活,**不核对是不是我们起的**——它要回答的是「被谁占着」,答案得包括
650
744
  * 用户自己开的那种。拿它当发信号的目标时,核对由调用方补。
745
+ *
746
+ * Windows 上没有这个符号链接:Chrome 的 ProcessSingleton 在那边是一个命名 mutex +
747
+ * 隐藏窗口,pid 从外面查不出来(process_singleton_win.cc)。改从进程表认:谁的
748
+ * 命令行里带着 `--user-data-dir=<本 profile>`,谁就是占用者;优先挑没有 `--type=`
749
+ * 的——Chrome 的子进程(renderer/gpu/crashpad)命令行里同样带着这个旗标,只有
750
+ * 主进程没有。快照由调用方传(ensureBrowser 本来就拉了一拍)或现拉一拍。
651
751
  */
652
- function profileOwnerPid() {
752
+ function profileOwnerPid(procs = null) {
753
+ if (process.platform === "win32") {
754
+ const snap = procs || psSnapshot();
755
+ const hits = snap
756
+ .filter((p) => {
757
+ const dir = profileDirFrom(p.cmd);
758
+ return dir && dirEq(dir, PROFILE_DIR) && pidAlive(p.pid);
759
+ })
760
+ .sort((a, b) => Number(/(^|\s)--type=/.test(a.cmd)) - Number(/(^|\s)--type=/.test(b.cmd)));
761
+ return hits[0]?.pid ?? null;
762
+ }
653
763
  let target = null;
654
764
  try {
655
765
  target = fs.readlinkSync(path.join(PROFILE_DIR, "SingletonLock"));
@@ -675,7 +785,7 @@ function profileOwnerPid() {
675
785
  * 本人用 GUID 确认身份。**于是「认领到别的 profile 的浏览器」从结构上不成立**。
676
786
  */
677
787
  async function adoptRunning({ headless, procs = null }) {
678
- const owner = profileOwnerPid();
788
+ const owner = profileOwnerPid(procs);
679
789
  const ep0 = readEndpoint();
680
790
  if (!owner && !ep0) return null;
681
791
 
@@ -809,8 +919,8 @@ export async function ensureBrowser({ headless = HEADLESS } = {}) {
809
919
  );
810
920
  }
811
921
  try {
812
- const holder = profileOwnerPid();
813
- if (holder && pidRunsThisProfile(holder))
922
+ const holder = profileOwnerPid(procs0);
923
+ if (holder && pidRunsThisProfile(holder, procs0))
814
924
  throw new Error(
815
925
  `这个 profile 已经被另一个浏览器实例占着(pid=${holder}):${PROFILE_DIR}\n` +
816
926
  `而当前是管道传输,它的 CDP 只有起它的那个进程用得上——认领不了,也不能另起一个\n` +
@@ -942,15 +1052,17 @@ async function coldStart({ headless }) {
942
1052
  rotateIfBig(BROWSER_LOG);
943
1053
  const out = fs.openSync(BROWSER_LOG, "a");
944
1054
  const child = USE_PIPE
945
- ? spawn(bin, browserArgs({ headless, bin }), { stdio: ["ignore", out, out, "pipe", "pipe"] })
946
- : spawn(bin, browserArgs({ headless, bin }), { stdio: ["ignore", out, out], detached: true });
1055
+ ? spawn(bin, browserArgs({ headless, bin }), { stdio: ["ignore", out, out, "pipe", "pipe"], windowsHide: true })
1056
+ : spawn(bin, browserArgs({ headless, bin }), { stdio: ["ignore", out, out], detached: true, windowsHide: true });
947
1057
  if (!USE_PIPE) child.unref();
948
1058
  try {
949
1059
  fs.closeSync(out);
950
1060
  } catch {}
951
1061
 
952
1062
  const ep = USE_PIPE ? await pipeEndpoint(child) : await waitForEndpoint();
953
- if (!pidRunsThisProfile(child.pid)) {
1063
+ const childRuns =
1064
+ process.platform === "win32" ? child.exitCode === null && child.signalCode === null : pidRunsThisProfile(child.pid);
1065
+ if (!childRuns) {
954
1066
  log(`冷启动的孩子 pid=${child.pid} 已不在(输掉了 ProcessSingleton),转认领真正的占用者`);
955
1067
  const winner = await adoptRunning({ headless });
956
1068
  if (winner) return winner;
@@ -1012,7 +1124,7 @@ export function stopBrowser({ force = false } = {}) {
1012
1124
  log(`不收浏览器 pid=${rec.pid}:它归 pid=${mgr} 管,那个进程还活着`);
1013
1125
  return false;
1014
1126
  }
1015
- const groupKill = rec.transport !== "pipe";
1127
+ const groupKill = process.platform !== "win32" && rec.transport !== "pipe";
1016
1128
  try {
1017
1129
  if (groupKill) process.kill(-rec.pid, "SIGTERM");
1018
1130
  else process.kill(rec.pid, "SIGTERM");
@@ -1085,7 +1197,7 @@ export async function stopBrowserGracefully({ timeoutMs = 10_000, force = true }
1085
1197
  if (stillAlive) {
1086
1198
  log(`pid=${pid} 没理 SIGTERM,升级到 SIGKILL`);
1087
1199
  try {
1088
- if (rec.transport !== "pipe") process.kill(-pid, "SIGKILL");
1200
+ if (process.platform !== "win32" && rec.transport !== "pipe") process.kill(-pid, "SIGKILL");
1089
1201
  else process.kill(pid, "SIGKILL");
1090
1202
  } catch {
1091
1203
  try {
@@ -45,9 +45,16 @@ export function looksLikeSecret(s) {
45
45
  * eval 的表达式是不是在要凭据。
46
46
  * 这一路**看意图不看结果**,所以 `document.cookie` 只返回一个 cookie(凑不满两对)
47
47
  * 时照样拦得住。
48
+ * 只剥离枚举 storage 键名/长度的只读元信息模式(不含 Object.values/entries/JSON.stringify);
49
+ * 返回值自身仍受 hasSecrets/redactSecrets 内容形状扫描保护。
48
50
  */
51
+ const SAFE_STORAGE_META =
52
+ /\bObject\s*\.\s*(?:keys|getOwnPropertyNames)\s*\(\s*(?:(?:window|globalThis)\s*\.\s*)?(?:local|session)Storage\s*\)|\b(?:(?:window|globalThis)\s*\.\s*)?(?:local|session)Storage\s*\.\s*length\b/g;
53
+
49
54
  export function exprWantsSecrets(expression) {
50
- return typeof expression === "string" && CRED_EXPR.test(expression);
55
+ if (typeof expression !== "string") return false;
56
+ const stripped = expression.replace(SAFE_STORAGE_META, "");
57
+ return CRED_EXPR.test(stripped);
51
58
  }
52
59
 
53
60
  export function methodWantsSecrets(method) {