magpie-plugin-doubao-cli-acp 0.0.0-stage → 0.2.5

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.
@@ -0,0 +1,431 @@
1
+ // 调起浏览器完成豆包网页登录,并用 CDP 把 Cookie 读回来。
2
+ //
3
+ // 为什么走 CDP 而不是读浏览器 Cookie 数据库:浏览器运行时用独占锁占住
4
+ // Cookies 文件,复制/流式读都会 EBUSY。CDP 直接问浏览器要,不碰文件。
5
+ //
6
+ // 三个刻意的选择:
7
+ // · 临时 profile:每次登录一个全新目录,登录完删掉。绝不使用用户现有 profile,
8
+ // 也绝不删除任何传进来的目录。
9
+ // · 随机端口:固定 9222 会和别的工具撞车,而且是个谁都能连的入口。
10
+ // · 只监听 127.0.0.1,用完即关。
11
+
12
+ import crypto from "node:crypto"
13
+ import fs from "node:fs"
14
+ import net from "node:net"
15
+ import os from "node:os"
16
+ import path from "node:path"
17
+ import { spawn } from "node:child_process"
18
+
19
+ export const LOGIN_URL = "https://www.doubao.com/chat/"
20
+
21
+ // 插件选项 browserPath 由 index.mjs 写入这里;没有就用环境变量 / 自动发现
22
+ let browserPathOption = ""
23
+ export function setBrowserPath(value) {
24
+ browserPathOption = typeof value === "string" ? value.trim() : ""
25
+ }
26
+ function settingsBrowserPath() {
27
+ return browserPathOption
28
+ }
29
+
30
+ const IS_WIN = process.platform === "win32"
31
+
32
+ /** 各平台可用的 Chromium 系浏览器(含 Tabbit) */
33
+ export function browserCandidates() {
34
+ if (IS_WIN) {
35
+ const local = process.env.LOCALAPPDATA || ""
36
+ const pf = process.env.PROGRAMFILES || "C:\\Program Files"
37
+ const pf86 = process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)"
38
+ return [
39
+ { name: "Edge", path: `${pf86}\\Microsoft\\Edge\\Application\\msedge.exe` },
40
+ { name: "Edge", path: `${pf}\\Microsoft\\Edge\\Application\\msedge.exe` },
41
+ { name: "Chrome", path: `${pf}\\Google\\Chrome\\Application\\chrome.exe` },
42
+ { name: "Chrome", path: `${local}\\Google\\Chrome\\Application\\chrome.exe` },
43
+ { name: "Tabbit", path: `${local}\\TabbitBrowser\\Application\\Tabbit.exe` },
44
+ ]
45
+ }
46
+ if (process.platform === "darwin") {
47
+ const home = os.homedir()
48
+ // bundle 里的可执行文件名不一定是产品名(Tabbit 的 /Applications 副本叫 launcher),
49
+ // 所以每个 bundle 都把 Contents/MacOS 下的可执行文件全列出来。
50
+ const bundles = [
51
+ { name: "Tabbit", dir: "/Applications/Tabbit Browser.app" },
52
+ { name: "Tabbit", dir: path.join(home, "Applications", "Tabbit Browser.app") },
53
+ { name: "Chrome", dir: "/Applications/Google Chrome.app" },
54
+ { name: "Chrome", dir: path.join(home, "Applications", "Google Chrome.app") },
55
+ { name: "Edge", dir: "/Applications/Microsoft Edge.app" },
56
+ { name: "Chromium", dir: "/Applications/Chromium.app" },
57
+ { name: "Brave", dir: "/Applications/Brave Browser.app" },
58
+ { name: "Arc", dir: "/Applications/Arc.app" },
59
+ ]
60
+ const out = []
61
+ for (const bundle of bundles) {
62
+ const macos = path.join(bundle.dir, "Contents", "MacOS")
63
+ let entries = []
64
+ try {
65
+ entries = fs.readdirSync(macos)
66
+ } catch {
67
+ continue
68
+ }
69
+ // "launcher" 这类壳程序会把参数转给已在运行的实例,调试端口起不来;
70
+ // 优先选和 bundle 同名的可执行文件,其次排除已知的壳名。
71
+ const shells = /^(launcher|spawn|stub|helper|update)$/i
72
+ const usable = []
73
+ for (const entry of entries) {
74
+ const full = path.join(macos, entry)
75
+ try {
76
+ const st = fs.statSync(full)
77
+ if (!st.isFile()) continue
78
+ fs.accessSync(full, fs.constants.X_OK)
79
+ usable.push(entry)
80
+ const sameName = entry.toLowerCase() === bundle.name.toLowerCase() ||
81
+ entry.toLowerCase().startsWith(bundle.name.toLowerCase())
82
+ if (sameName) {
83
+ out.push({ name: bundle.name, path: full })
84
+ usable.length = 0
85
+ break
86
+ }
87
+ } catch {
88
+ // 不是可执行文件
89
+ }
90
+ }
91
+ if (usable.length) {
92
+ const pick = usable.find((e) => !shells.test(path.parse(e).name))
93
+ if (pick) out.push({ name: bundle.name, path: path.join(macos, pick) })
94
+ }
95
+ }
96
+ return out
97
+ }
98
+ return [
99
+ { name: "Chrome", path: "/usr/bin/google-chrome" },
100
+ { name: "Chromium", path: "/usr/bin/chromium" },
101
+ { name: "Chromium", path: "/usr/bin/chromium-browser" },
102
+ { name: "Edge", path: "/usr/bin/microsoft-edge" },
103
+ ]
104
+ }
105
+
106
+ export function findBrowser(explicit = process.env.MAGPIE_DOUBAO_BROWSER || "") {
107
+ if (explicit) {
108
+ try {
109
+ if (fs.statSync(explicit).isFile()) return { name: path.basename(explicit), path: explicit }
110
+ } catch {
111
+ // 显式路径不可用,继续找
112
+ }
113
+ }
114
+ for (const candidate of browserCandidates()) {
115
+ try {
116
+ if (fs.statSync(candidate.path).isFile()) return candidate
117
+ } catch {
118
+ // 下一个
119
+ }
120
+ }
121
+ return null
122
+ }
123
+
124
+ /** 让系统挑一个空闲端口 */
125
+ export function freePort() {
126
+ return new Promise((resolve, reject) => {
127
+ const server = net.createServer()
128
+ server.unref()
129
+ server.once("error", reject)
130
+ server.listen(0, "127.0.0.1", () => {
131
+ const { port } = server.address()
132
+ server.close(() => resolve(port))
133
+ })
134
+ })
135
+ }
136
+
137
+ async function probePort(port, timeoutMs = 1200) {
138
+ try {
139
+ const res = await fetch(`http://127.0.0.1:${port}/json/version`, {
140
+ signal: AbortSignal.timeout(timeoutMs),
141
+ })
142
+ if (!res.ok) return null
143
+ const info = await res.json()
144
+ return info?.webSocketDebuggerUrl ? info : null
145
+ } catch {
146
+ return null
147
+ }
148
+ }
149
+
150
+ /** 极简 CDP 会话:只用到 Network.getCookies */
151
+ function connect(wsUrl, { timeoutMs = 8_000 } = {}) {
152
+ return new Promise((resolve, reject) => {
153
+ let socket
154
+ try {
155
+ socket = new WebSocket(wsUrl)
156
+ } catch (error) {
157
+ reject(error)
158
+ return
159
+ }
160
+ const pending = new Map()
161
+ let nextId = 1
162
+ const timer = setTimeout(() => {
163
+ try { socket.close() } catch {}
164
+ reject(new Error("连接浏览器调试端口超时"))
165
+ }, timeoutMs)
166
+ timer.unref?.()
167
+
168
+ socket.addEventListener("open", () => {
169
+ clearTimeout(timer)
170
+ resolve({
171
+ send(method, params) {
172
+ const id = nextId++
173
+ return new Promise((res, rej) => {
174
+ const t = setTimeout(() => {
175
+ pending.delete(id)
176
+ rej(new Error(`${method} 超时`))
177
+ }, 10_000)
178
+ t.unref?.()
179
+ pending.set(id, { res, rej, t })
180
+ socket.send(JSON.stringify({ id, method, params }))
181
+ })
182
+ },
183
+ close() { try { socket.close() } catch {} },
184
+ })
185
+ })
186
+ socket.addEventListener("message", (event) => {
187
+ let msg
188
+ try { msg = JSON.parse(String(event.data)) } catch { return }
189
+ const slot = msg.id ? pending.get(msg.id) : undefined
190
+ if (!slot) return
191
+ pending.delete(msg.id)
192
+ clearTimeout(slot.t)
193
+ if (msg.error) slot.rej(new Error(msg.error.message || "CDP 调用失败"))
194
+ else slot.res(msg.result)
195
+ })
196
+ socket.addEventListener("error", () => {
197
+ clearTimeout(timer)
198
+ reject(new Error("连不上浏览器调试端口"))
199
+ })
200
+ })
201
+ }
202
+
203
+ /** 在调试端口上找 page target,读 doubao.com 的 Cookie */
204
+ export async function readCookiesViaCdp(port, domain = "doubao.com") {
205
+ const info = await probePort(port)
206
+ if (!info) throw new Error("浏览器调试端口没有响应")
207
+ let target = info.webSocketDebuggerUrl
208
+ try {
209
+ const list = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(2_000) }).then((r) => r.json())
210
+ const page = Array.isArray(list) ? list.find((t) => t.type === "page" && t.webSocketDebuggerUrl) : undefined
211
+ if (page) target = page.webSocketDebuggerUrl
212
+ } catch {
213
+ // 用浏览器级连接兜底
214
+ }
215
+ const session = await connect(target)
216
+ try {
217
+ const result = await session.send("Network.getCookies", {
218
+ urls: [`https://${domain}/`, `https://www.${domain}/`],
219
+ })
220
+ const list = Array.isArray(result?.cookies) ? result.cookies : []
221
+ return list.map((c) => ({
222
+ name: c.name,
223
+ value: c.value,
224
+ domain: String(c.domain || domain).replace(/^\./, ""),
225
+ path: c.path || "/",
226
+ expires: Math.floor(Number(c.expires) || 0),
227
+ secure: Boolean(c.secure),
228
+ httpOnly: Boolean(c.httpOnly),
229
+ }))
230
+ } finally {
231
+ session.close()
232
+ }
233
+ }
234
+
235
+ function hasSession(cookies) {
236
+ return (Array.isArray(cookies) ? cookies : []).some(
237
+ (c) => (c?.name === "sessionid" || c?.name === "sessionid_ss") && c?.value,
238
+ )
239
+ }
240
+
241
+ async function rmDir(dir) {
242
+ for (let i = 0; i < 8; i++) {
243
+ try {
244
+ fs.rmSync(dir, { recursive: true, force: true })
245
+ return
246
+ } catch {
247
+ await new Promise((r) => setTimeout(r, 400))
248
+ }
249
+ }
250
+ }
251
+
252
+
253
+ // 插件宿主被 SIGKILL(magpie 更新、强杀)时,进程内钩子跑不到,
254
+ // 所以另起一个极小的看护进程:宿主没了就把浏览器和临时目录一起收掉。
255
+ const REAPER = `
256
+ const [hostPid, browserPid, dir] = process.argv.slice(1)
257
+ const alive = (pid) => { try { process.kill(Number(pid), 0); return true } catch { return false } }
258
+ const fs = require("node:fs")
259
+ const kill = () => {
260
+ try { process.kill(Number(browserPid), "SIGKILL") } catch {}
261
+ try { fs.rmSync(dir, { recursive: true, force: true }) } catch {}
262
+ }
263
+ setInterval(() => {
264
+ if (!alive(hostPid)) { kill(); process.exit(0) }
265
+ if (!alive(browserPid)) {
266
+ try { fs.rmSync(dir, { recursive: true, force: true }) } catch {}
267
+ process.exit(0)
268
+ }
269
+ }, 1500)
270
+ `
271
+
272
+ function startReaper(browserPid, dir) {
273
+ try {
274
+ const child = spawn(process.execPath, ["-e", REAPER, String(process.pid), String(browserPid), dir], {
275
+ detached: true,
276
+ stdio: "ignore",
277
+ windowsHide: true,
278
+ })
279
+ child.unref()
280
+ } catch {
281
+ // 看护起不来就靠退出钩子和陈旧目录回收
282
+ }
283
+ }
284
+
285
+ // 插件进程被杀(magpie 重启、更新、崩溃)时 finally 不一定会跑,
286
+ // 所以把打开着的窗口登记下来,进程退出前统一收掉。
287
+ const live = new Set()
288
+
289
+ function sweepSync() {
290
+ for (const item of live) {
291
+ try { item.child.kill("SIGKILL") } catch {}
292
+ try { fs.rmSync(item.dir, { recursive: true, force: true }) } catch {}
293
+ }
294
+ live.clear()
295
+ }
296
+
297
+ let sweepHooked = false
298
+ function hookSweep() {
299
+ if (sweepHooked) return
300
+ sweepHooked = true
301
+ process.once("exit", sweepSync)
302
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
303
+ process.once(signal, () => {
304
+ sweepSync()
305
+ process.exit(0)
306
+ })
307
+ }
308
+ }
309
+
310
+ /** 清掉上次崩溃/强杀留下的临时 profile(30 分钟前的才算陈旧) */
311
+ export function sweepStaleProfiles(maxAgeMs = 30 * 60_000) {
312
+ const dir = os.tmpdir()
313
+ let entries = []
314
+ try { entries = fs.readdirSync(dir) } catch { return }
315
+ const cutoff = Date.now() - maxAgeMs
316
+ for (const name of entries) {
317
+ if (!name.startsWith("magpie-doubao-web-")) continue
318
+ const full = path.join(dir, name)
319
+ try {
320
+ const st = fs.statSync(full)
321
+ if (st.mtimeMs > cutoff) continue
322
+ fs.rmSync(full, { recursive: true, force: true })
323
+ } catch {
324
+ // 还在用或没权限,下次再说
325
+ }
326
+ }
327
+ }
328
+
329
+ /**
330
+ * 开一个临时浏览器窗口让用户登录豆包。
331
+ * 返回 { port, name, close, read };close 会杀掉浏览器并删掉临时 profile。
332
+ */
333
+ export async function launchLoginBrowser({ url = LOGIN_URL, port, profileDir, executable } = {}) {
334
+ sweepStaleProfiles()
335
+ const browser = findBrowser(executable || settingsBrowserPath())
336
+ if (!browser) {
337
+ throw new Error("没找到可用的浏览器(Chrome / Edge / Chromium / Tabbit)。可以改用「粘贴网页 Cookie」。")
338
+ }
339
+ const actualPort = port ?? await freePort()
340
+ const dir = profileDir || path.join(os.tmpdir(), `magpie-doubao-web-${crypto.randomBytes(6).toString("hex")}`)
341
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
342
+
343
+ const child = spawn(browser.path, [
344
+ `--remote-debugging-port=${actualPort}`,
345
+ "--remote-debugging-address=127.0.0.1",
346
+ `--user-data-dir=${dir}`,
347
+ "--no-first-run",
348
+ "--no-default-browser-check",
349
+ "--disable-extensions",
350
+ "--disable-sync",
351
+ url,
352
+ ], { detached: true, stdio: "ignore", windowsHide: true })
353
+ child.unref()
354
+ hookSweep()
355
+ startReaper(child.pid, dir)
356
+ const entry = { child, dir }
357
+ live.add(entry)
358
+
359
+ const close = async () => {
360
+ if (IS_WIN && child.pid) {
361
+ try {
362
+ await new Promise((resolve) => {
363
+ const k = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true })
364
+ k.once("close", resolve)
365
+ k.once("error", resolve)
366
+ })
367
+ } catch {}
368
+ }
369
+ try { child.kill() } catch {}
370
+ await new Promise((r) => setTimeout(r, 600))
371
+ try { child.kill("SIGKILL") } catch {}
372
+ await rmDir(dir)
373
+ live.delete(entry)
374
+ }
375
+
376
+ // 等调试端口起来;进程先退要报清楚
377
+ let exited = false
378
+ child.once("exit", () => { exited = true })
379
+ const deadline = Date.now() + 30_000
380
+ for (;;) {
381
+ if (await probePort(actualPort)) break
382
+ if (exited) {
383
+ await close()
384
+ throw new Error(`登录窗口刚打开就关掉了(${browser.name} 可能已在运行并接管了新窗口)。改用「粘贴网页 Cookie」也可以。`)
385
+ }
386
+ if (Date.now() > deadline) {
387
+ await close()
388
+ throw new Error("登录窗口打开了,但 30 秒内连不上它的调试端口。改用「粘贴网页 Cookie」也可以。")
389
+ }
390
+ await new Promise((r) => setTimeout(r, 400))
391
+ }
392
+
393
+ return {
394
+ port: actualPort,
395
+ name: browser.name,
396
+ close,
397
+ read: () => readCookiesViaCdp(actualPort),
398
+ }
399
+ }
400
+
401
+ /**
402
+ * 等用户在浏览器里登录完成(出现 sessionid)。
403
+ * 超时或取消都会关掉浏览器。
404
+ */
405
+ export async function waitForLoginCookies(handle, { signal, timeoutMs = 10 * 60_000, intervalMs = 1_500 } = {}) {
406
+ const deadline = Date.now() + timeoutMs
407
+ try {
408
+ for (;;) {
409
+ if (signal?.aborted) throw new Error("浏览器登录已取消")
410
+ try {
411
+ const cookies = await handle.read()
412
+ if (hasSession(cookies)) return cookies
413
+ } catch (error) {
414
+ if (signal?.aborted) throw error
415
+ }
416
+ if (Date.now() > deadline) return []
417
+ await new Promise((resolve) => {
418
+ let timer = null
419
+ const done = () => {
420
+ if (timer) clearTimeout(timer)
421
+ signal?.removeEventListener?.("abort", done)
422
+ resolve()
423
+ }
424
+ timer = setTimeout(done, intervalMs)
425
+ signal?.addEventListener?.("abort", done, { once: true })
426
+ })
427
+ }
428
+ } finally {
429
+ await handle.close?.().catch?.(() => {})
430
+ }
431
+ }