one-model-router 0.0.12 → 0.0.14
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/README.md +12 -11
- package/bin/omr.js +90 -11
- package/package.json +9 -8
- package/src/admin.js +131 -7
- package/src/boot.js +10 -1
- package/src/bun-bootstrap.js +115 -0
- package/src/channels/index.js +8 -4
- package/src/channels/lingxi-browser-login.js +231 -0
- package/src/channels/lingxi-cred.js +448 -0
- package/src/channels/lingxi.js +1481 -0
- package/src/channels/loomy.js +140 -31
- package/src/default-group.js +142 -0
- package/src/free-models.js +9 -0
- package/src/probe.js +55 -25
- package/src/providers/opencode/bun-fetch.js +6 -26
- package/src/sync/index.js +150 -19
- package/src/sync/qr-mobile.js +141 -0
- package/src/sync/remote-login.js +28 -130
- package/src/sync/snapshot.js +2 -0
- package/src/update.js +7 -2
- package/web/app.js +472 -77
- package/web/index.html +2 -2
- package/web/style.css +26 -6
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bun 引导:检测本机 Bun(OpenCode 免费车道推理依赖,见 src/providers/opencode/bun-fetch.js),
|
|
3
|
+
* 缺失时以分离进程自动补装。对齐官网安装方法(https://bun.sh/docs/installation):
|
|
4
|
+
* Windows powershell -c "irm bun.sh/install.ps1 | iex"(装到 %USERPROFILE%\.bun\bin 并写入用户 PATH)
|
|
5
|
+
* macOS/Linux curl -fsSL https://bun.sh/install | bash(装到 ~/.bun/bin)
|
|
6
|
+
* 兜底 npm install -g bun
|
|
7
|
+
*
|
|
8
|
+
* 只依赖 Node 内置模块,供网页版升级(src/update.js)与桌面端升级(electron/self-update.js)共用。
|
|
9
|
+
* ensureBunDetached 在升级完成后调用:检测在本进程内做(口径与运行时 findBunExecutable 一致),
|
|
10
|
+
* 缺失才拉起分离的平台 shell 子进程安装(不 import 本模块——打包态 electron 的 asar 路径在
|
|
11
|
+
* ELECTRON_RUN_AS_NODE 下不可读),安装不阻塞升级流程与服务重启;输出追加到
|
|
12
|
+
* <数据目录>/logs/bun-install.log。装完后运行时按路径候选自动识别,无需重启服务。
|
|
13
|
+
* 安装失败不影响本体(仅 OpenCode 免费车道不可用)。
|
|
14
|
+
*
|
|
15
|
+
* @module src/bun-bootstrap
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { accessSync, closeSync, constants, mkdirSync, openSync, statSync } from 'node:fs'
|
|
19
|
+
import { homedir } from 'node:os'
|
|
20
|
+
import { delimiter, join, resolve } from 'node:path'
|
|
21
|
+
import { spawn } from 'node:child_process'
|
|
22
|
+
|
|
23
|
+
/** 定位原生 Bun 可执行文件(永不执行 .cmd/.ps1 壳)。不安装、不下载。 */
|
|
24
|
+
export function findBunExecutable() {
|
|
25
|
+
const name = process.platform === 'win32' ? 'bun.exe' : 'bun'
|
|
26
|
+
const candidates = [
|
|
27
|
+
process.env.OMR_OPENCODE_BUN,
|
|
28
|
+
process.env.OUR_FREE_MODEL_BUN,
|
|
29
|
+
process.env.BUN_INSTALL && join(process.env.BUN_INSTALL, 'bin', name),
|
|
30
|
+
join(homedir(), '.bun', 'bin', name),
|
|
31
|
+
...(process.env.PATH || '').split(delimiter).filter(Boolean).map(p => join(p.replace(/^"|"$/g, ''), name)),
|
|
32
|
+
process.env.APPDATA && join(process.env.APPDATA, 'npm', 'node_modules', 'bun', 'bin', name),
|
|
33
|
+
]
|
|
34
|
+
for (const candidate of candidates.filter(Boolean)) {
|
|
35
|
+
try {
|
|
36
|
+
const path = resolve(candidate)
|
|
37
|
+
if (process.platform === 'win32' && !path.toLowerCase().endsWith('.exe')) continue
|
|
38
|
+
if (!statSync(path).isFile()) continue
|
|
39
|
+
accessSync(path, constants.X_OK)
|
|
40
|
+
return path
|
|
41
|
+
} catch { /* 试下一个候选 */ }
|
|
42
|
+
}
|
|
43
|
+
return undefined
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Windows 补装脚本:官方 install.ps1(经 scriptblock 执行,与官网 irm|iex 等效)→ npm 兜底。
|
|
48
|
+
* 只认官方脚本的落盘位置(BUN_INSTALL 覆盖时同规则),装不上不影响本体。
|
|
49
|
+
*/
|
|
50
|
+
const INSTALL_PS1 = [
|
|
51
|
+
'$ProgressPreference = "SilentlyContinue"',
|
|
52
|
+
'$bun = Join-Path $env:USERPROFILE ".bun\\bin\\bun.exe"',
|
|
53
|
+
'if ($env:BUN_INSTALL) { $bun = Join-Path $env:BUN_INSTALL "bin\\bun.exe" }',
|
|
54
|
+
'if (-not (Test-Path -LiteralPath $bun -PathType Leaf)) {',
|
|
55
|
+
' Write-Host "[bun] 官方脚本安装:https://bun.sh/install.ps1"',
|
|
56
|
+
' try { & ([scriptblock]::Create((Invoke-WebRequest -UseBasicParsing -Uri "https://bun.sh/install.ps1").Content)) } catch { Write-Host "[bun] 官方脚本失败:$($_.Exception.Message)" }',
|
|
57
|
+
'}',
|
|
58
|
+
'if (-not (Test-Path -LiteralPath $bun -PathType Leaf) -and Get-Command npm -ErrorAction SilentlyContinue) {',
|
|
59
|
+
' Write-Host "[bun] 改用 npm i -g bun"',
|
|
60
|
+
' npm i -g bun',
|
|
61
|
+
'}',
|
|
62
|
+
'if (Test-Path -LiteralPath $bun -PathType Leaf) { Write-Host "[bun] 安装完成:$bun" } else { Write-Host "[bun] 自动安装失败,请手动安装:https://bun.sh" }',
|
|
63
|
+
].join('\n')
|
|
64
|
+
|
|
65
|
+
/** macOS / Linux 补装脚本:官方 install(bash)→ npm 兜底;与 INSTALL_PS1 同口径。 */
|
|
66
|
+
const INSTALL_SH = [
|
|
67
|
+
'if [ ! -x "$HOME/.bun/bin/bun" ] && ! command -v bun >/dev/null 2>&1; then',
|
|
68
|
+
' echo "[bun] 官方脚本安装:https://bun.sh/install"',
|
|
69
|
+
' curl -fsSL https://bun.sh/install | bash || echo "[bun] 官方脚本失败"',
|
|
70
|
+
'fi',
|
|
71
|
+
'if [ ! -x "$HOME/.bun/bin/bun" ] && ! command -v bun >/dev/null 2>&1 && command -v npm >/dev/null 2>&1; then',
|
|
72
|
+
' echo "[bun] 改用 npm i -g bun"',
|
|
73
|
+
' npm i -g bun || echo "[bun] npm 安装失败"',
|
|
74
|
+
'fi',
|
|
75
|
+
'if [ -x "$HOME/.bun/bin/bun" ] || command -v bun >/dev/null 2>&1; then echo "[bun] 安装完成"; else echo "[bun] 自动安装失败,请手动安装:https://bun.sh"; fi',
|
|
76
|
+
].join('\n')
|
|
77
|
+
|
|
78
|
+
/** 安装日志路径:<数据目录>/logs/bun-install.log(数据目录约定与 src/paths.js / electron/data-dir.cjs 一致)。 */
|
|
79
|
+
function bunInstallLogFile() {
|
|
80
|
+
const dataDir = process.env.OMR_DATA_DIR || join(homedir(), '.OneModelRouter', 'data')
|
|
81
|
+
return join(dataDir, 'logs', 'bun-install.log')
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 升级完成后的 Bun 检查与补装(分离进程,不阻塞调用方)。
|
|
86
|
+
* 已安装则只记日志返回 already;缺失则拉起平台 shell 子进程安装并立即返回 started。
|
|
87
|
+
* 任何异常都消化在返回值/日志里,绝不影响升级流程本身。
|
|
88
|
+
*/
|
|
89
|
+
export function ensureBunDetached({ log = () => {} } = {}) {
|
|
90
|
+
try {
|
|
91
|
+
const found = findBunExecutable()
|
|
92
|
+
if (found) {
|
|
93
|
+
log(`Bun 已安装(${found}),OpenCode 免费车道可用`)
|
|
94
|
+
return { status: 'already', path: found }
|
|
95
|
+
}
|
|
96
|
+
let logFile = ''
|
|
97
|
+
let fd = 'ignore'
|
|
98
|
+
try {
|
|
99
|
+
logFile = bunInstallLogFile()
|
|
100
|
+
mkdirSync(join(logFile, '..'), { recursive: true })
|
|
101
|
+
fd = openSync(logFile, 'a')
|
|
102
|
+
} catch { /* 日志目录不可写:子进程输出丢弃 */ }
|
|
103
|
+
const child = process.platform === 'win32'
|
|
104
|
+
? spawn('powershell', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', INSTALL_PS1], { detached: true, stdio: ['ignore', fd, fd], windowsHide: true })
|
|
105
|
+
: spawn('/bin/sh', ['-c', INSTALL_SH], { detached: true, stdio: ['ignore', fd, fd] })
|
|
106
|
+
child.on('error', error => log(`Bun 后台安装进程启动失败:${error?.message ?? error}`))
|
|
107
|
+
child.unref()
|
|
108
|
+
if (typeof fd === 'number') closeSync(fd)
|
|
109
|
+
log(`未检测到 Bun(OpenCode 免费车道依赖),已后台开始安装${logFile ? `,日志:${logFile}` : ''}`)
|
|
110
|
+
return { status: 'started', logFile }
|
|
111
|
+
} catch (error) {
|
|
112
|
+
log(`Bun 检查/补装异常(不影响本体):${error?.message ?? error}`)
|
|
113
|
+
return { status: 'failed', error: String(error?.message ?? error) }
|
|
114
|
+
}
|
|
115
|
+
}
|
package/src/channels/index.js
CHANGED
|
@@ -39,6 +39,7 @@ import * as tabbit from './tabbit.js'
|
|
|
39
39
|
import * as doubaowork from './doubaowork.js'
|
|
40
40
|
import * as miaoshou from './miaoshou.js'
|
|
41
41
|
import { joycodeChannel } from './joycode.js'
|
|
42
|
+
import * as lingxi from './lingxi.js'
|
|
42
43
|
|
|
43
44
|
/** 账号轮换游标:catalogRowId -> cursor(按模型记忆,同 opencode 槽轮换)。 */
|
|
44
45
|
const cursors = new Map()
|
|
@@ -69,6 +70,7 @@ export const CHANNELS = [
|
|
|
69
70
|
doubaowork.meta && doubaowork,
|
|
70
71
|
miaoshou.meta && miaoshou,
|
|
71
72
|
joycodeChannel.meta && joycodeChannel,
|
|
73
|
+
lingxi.meta && lingxi,
|
|
72
74
|
].filter(Boolean)
|
|
73
75
|
|
|
74
76
|
export function channelById(id) {
|
|
@@ -248,12 +250,14 @@ export async function sweepRefresh() {
|
|
|
248
250
|
// 只对已启用的渠道做后台续期:停用的渠道不刷新凭据,避免无谓出网与记账噪音。
|
|
249
251
|
if (!state.enabled) continue
|
|
250
252
|
for (const account of state.accounts) {
|
|
251
|
-
//
|
|
252
|
-
//
|
|
253
|
-
|
|
254
|
-
|
|
253
|
+
// 渠道新增/恢复自动续期能力后,旧账号可能在上一版本被标成 refreshable=false。
|
|
254
|
+
// 以渠道当前声明为准:只有「明确不可续期」或鉴权已终态时才允许自愈。
|
|
255
|
+
const described = ch.describeCredential?.(account.credential)
|
|
256
|
+
if (account.refreshable === false && described?.refreshable === true &&
|
|
257
|
+
(account.authDead === true || /不可自动续期|自动续期不可用|不支持自动续期/.test(account.lastError ?? ''))) {
|
|
255
258
|
account.refreshable = true
|
|
256
259
|
account.lastError = ''
|
|
260
|
+
account.authDead = false
|
|
257
261
|
account.updatedAt = Date.now()
|
|
258
262
|
saveChannelState(id, state)
|
|
259
263
|
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WPS 灵犀免客户端登录:起一个独立浏览器窗口,登录后经 CDP 读取 Cookie。
|
|
3
|
+
*
|
|
4
|
+
* 为什么不用「解本机浏览器 Cookie 库」:
|
|
5
|
+
* - Chrome / Edge 127+ 的 Cookie 用 app-bound(v20)加密,密钥由系统级服务
|
|
6
|
+
* 保护,单纯 DPAPI + AES-GCM 解不开;
|
|
7
|
+
* - 日常浏览器运行时独占 Cookie 库,复制都会失败;
|
|
8
|
+
* - 读取用户日常浏览器的全部 Cookie 也超出了必要范围。
|
|
9
|
+
*
|
|
10
|
+
* 因此这里用参考项目 dsh-connect-lingxi 的做法:`--user-data-dir` 指向临时
|
|
11
|
+
* profile,打开 WPS 统一登录页,用户自己完成登录;再用 DevTools Protocol 的
|
|
12
|
+
* `Storage.getCookies` / `Network.getAllCookies` 读 HttpOnly 的
|
|
13
|
+
* kso_sid / wps_sid / uid。独立 profile 不碰日常浏览器,也不受文件锁影响。
|
|
14
|
+
*
|
|
15
|
+
* 依赖:本机有 Edge / Chrome;Node 22+(内置 WebSocket)。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { spawn } from 'node:child_process'
|
|
19
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
|
|
20
|
+
import { tmpdir } from 'node:os'
|
|
21
|
+
import { join } from 'node:path'
|
|
22
|
+
|
|
23
|
+
const LOGIN_URL = 'https://account.wps.cn/'
|
|
24
|
+
const DEFAULT_TIMEOUT_MS = Math.max(30_000, Number(process.env.OMR_LINGXI_LOGIN_TIMEOUT_MS) || 5 * 60_000)
|
|
25
|
+
const POLL_INTERVAL_MS = 2_000
|
|
26
|
+
const DEVTOOLS_READY_MS = 20_000
|
|
27
|
+
|
|
28
|
+
function sleep(ms) {
|
|
29
|
+
return new Promise(resolve => setTimeout(resolve, ms))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 常见安装位置;按 Edge → Chrome 顺序,找不到返回 null。 */
|
|
33
|
+
export function findBrowser() {
|
|
34
|
+
const candidates = []
|
|
35
|
+
if (process.platform === 'win32') {
|
|
36
|
+
const pf = process.env.ProgramFiles
|
|
37
|
+
const pf86 = process.env['ProgramFiles(x86)']
|
|
38
|
+
const local = process.env.LOCALAPPDATA
|
|
39
|
+
if (pf86) candidates.push(join(pf86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'))
|
|
40
|
+
if (pf) candidates.push(join(pf, 'Microsoft', 'Edge', 'Application', 'msedge.exe'))
|
|
41
|
+
if (pf) candidates.push(join(pf, 'Google', 'Chrome', 'Application', 'chrome.exe'))
|
|
42
|
+
if (pf86) candidates.push(join(pf86, 'Google', 'Chrome', 'Application', 'chrome.exe'))
|
|
43
|
+
if (local) candidates.push(join(local, 'Google', 'Chrome', 'Application', 'chrome.exe'))
|
|
44
|
+
} else if (process.platform === 'darwin') {
|
|
45
|
+
candidates.push('/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge')
|
|
46
|
+
candidates.push('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome')
|
|
47
|
+
if (process.env.HOME) candidates.push(join(process.env.HOME, 'Applications', 'Google Chrome.app', 'Contents', 'MacOS', 'Google Chrome'))
|
|
48
|
+
} else {
|
|
49
|
+
for (const dir of (process.env.PATH ?? '').split(':')) {
|
|
50
|
+
if (!dir) continue
|
|
51
|
+
for (const name of ['microsoft-edge', 'google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser']) {
|
|
52
|
+
candidates.push(join(dir, name))
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return candidates.find(path => existsSync(path)) ?? null
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 极简 CDP 客户端:发送命令、等响应,够读 Cookie 用。 */
|
|
60
|
+
class CdpSession {
|
|
61
|
+
constructor(wsUrl) {
|
|
62
|
+
this.ws = new WebSocket(wsUrl)
|
|
63
|
+
this.seq = 0
|
|
64
|
+
this.pending = new Map()
|
|
65
|
+
this.closed = false
|
|
66
|
+
this.opened = new Promise((resolve, reject) => {
|
|
67
|
+
this.ws.addEventListener('open', resolve, { once: true })
|
|
68
|
+
this.ws.addEventListener('error', () => reject(new Error('CDP 连接失败')), { once: true })
|
|
69
|
+
})
|
|
70
|
+
this.ws.addEventListener('message', event => {
|
|
71
|
+
let message
|
|
72
|
+
try { message = JSON.parse(event.data) } catch { return }
|
|
73
|
+
const slot = message.id && this.pending.get(message.id)
|
|
74
|
+
if (!slot) return
|
|
75
|
+
this.pending.delete(message.id)
|
|
76
|
+
if (message.error) slot.reject(new Error(String(message.error.message ?? JSON.stringify(message.error))))
|
|
77
|
+
else slot.resolve(message.result)
|
|
78
|
+
})
|
|
79
|
+
this.ws.addEventListener('close', () => {
|
|
80
|
+
this.closed = true
|
|
81
|
+
for (const slot of this.pending.values()) slot.reject(new Error('登录窗口已关闭'))
|
|
82
|
+
this.pending.clear()
|
|
83
|
+
})
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async send(method, params = {}, timeoutMs = 15_000) {
|
|
87
|
+
await this.opened
|
|
88
|
+
if (this.closed) throw new Error('登录窗口已关闭')
|
|
89
|
+
const id = ++this.seq
|
|
90
|
+
return new Promise((resolve, reject) => {
|
|
91
|
+
this.pending.set(id, { resolve, reject })
|
|
92
|
+
this.ws.send(JSON.stringify({ id, method, params }))
|
|
93
|
+
setTimeout(() => {
|
|
94
|
+
if (this.pending.delete(id)) reject(new Error(`CDP 超时:${method}`))
|
|
95
|
+
}, timeoutMs)
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
close() {
|
|
100
|
+
try { this.ws.close() } catch { /* 已关闭 */ }
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** 读取 Chromium 写入临时 profile 的 DevTools 端口。 */
|
|
105
|
+
async function waitForDevToolsPort(profileDir, exitState) {
|
|
106
|
+
const file = join(profileDir, 'DevToolsActivePort')
|
|
107
|
+
const deadline = Date.now() + DEVTOOLS_READY_MS
|
|
108
|
+
while (Date.now() < deadline) {
|
|
109
|
+
if (exitState.exited) throw new Error(exitState.error ? `登录窗口启动失败:${exitState.error.message}` : '登录窗口已关闭')
|
|
110
|
+
try {
|
|
111
|
+
const port = Number(readFileSync(file, 'utf8').split(/\r?\n/)[0])
|
|
112
|
+
if (Number.isInteger(port) && port > 0) return port
|
|
113
|
+
} catch { /* 还没写入 */ }
|
|
114
|
+
await sleep(150)
|
|
115
|
+
}
|
|
116
|
+
throw new Error('登录窗口启动超时(未拿到调试端口;若浏览器受企业策略管控,远程调试可能被禁用)')
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function pickPageTarget(port, exitState) {
|
|
120
|
+
const deadline = Date.now() + DEVTOOLS_READY_MS
|
|
121
|
+
while (Date.now() < deadline) {
|
|
122
|
+
if (exitState.exited) throw new Error('登录窗口已关闭')
|
|
123
|
+
try {
|
|
124
|
+
const list = await fetch(`http://127.0.0.1:${port}/json/list`).then(response => response.json())
|
|
125
|
+
const page = list.find(target => target.type === 'page' && target.webSocketDebuggerUrl)
|
|
126
|
+
if (page) return page
|
|
127
|
+
} catch { /* 端口还没就绪 */ }
|
|
128
|
+
await sleep(250)
|
|
129
|
+
}
|
|
130
|
+
throw new Error('登录窗口未就绪(没有可用的页面目标)')
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function readAllCookies(cdp) {
|
|
134
|
+
try {
|
|
135
|
+
return (await cdp.send('Storage.getCookies')).cookies ?? []
|
|
136
|
+
} catch {
|
|
137
|
+
return (await cdp.send('Network.getAllCookies')).cookies ?? []
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** 从 CDP Cookie 里挑出灵犀需要的三项(kso_sid 为 HttpOnly)。 */
|
|
142
|
+
function pickCredential(cookies) {
|
|
143
|
+
const now = Date.now()
|
|
144
|
+
const find = name => cookies.find(cookie => {
|
|
145
|
+
if (cookie.name !== name) return false
|
|
146
|
+
if (!String(cookie.domain ?? '').includes('wps.cn')) return false
|
|
147
|
+
if (typeof cookie.expires === 'number' && cookie.expires > 0 && cookie.expires * 1000 <= now) return false
|
|
148
|
+
return Boolean(cookie.value)
|
|
149
|
+
})
|
|
150
|
+
const kso = find('kso_sid')
|
|
151
|
+
const wps = find('wps_sid')
|
|
152
|
+
const uid = find('uid')
|
|
153
|
+
if (!kso || !wps || !uid) return null
|
|
154
|
+
return {
|
|
155
|
+
kso_sid: kso.value,
|
|
156
|
+
wps_sid: wps.value,
|
|
157
|
+
uid: uid.value,
|
|
158
|
+
captured_at: new Date().toISOString(),
|
|
159
|
+
...(kso.expires > 0 ? { expires_at: new Date(kso.expires * 1000).toISOString() } : {}),
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function killBrowser(child) {
|
|
164
|
+
if (!child?.pid) return
|
|
165
|
+
try {
|
|
166
|
+
if (process.platform === 'win32') {
|
|
167
|
+
// Chrome / Edge 会拉起子进程,taskkill /T 才能一起收掉。
|
|
168
|
+
spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true })
|
|
169
|
+
} else {
|
|
170
|
+
child.kill('SIGTERM')
|
|
171
|
+
}
|
|
172
|
+
} catch { /* 已退出 */ }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* 打开独立浏览器窗口等待用户登录,返回 kso_sid / wps_sid / uid。
|
|
177
|
+
*
|
|
178
|
+
* @param {object} options
|
|
179
|
+
* @param {(credential:object)=>Promise<boolean|void>} [options.verify]
|
|
180
|
+
* 拿到三项 Cookie 后的校验钩子:返回 false 表示登录态还没生效、继续等;
|
|
181
|
+
* 抛错表示终止;返回其它值表示接受。
|
|
182
|
+
* @param {number} [options.timeoutMs]
|
|
183
|
+
*/
|
|
184
|
+
export async function loginViaBrowser({ verify, timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
|
|
185
|
+
const browserPath = findBrowser()
|
|
186
|
+
if (!browserPath) throw new Error('未找到 Edge / Chrome,无法打开登录窗口')
|
|
187
|
+
if (typeof WebSocket !== 'function') throw new Error('当前 Node 运行时不支持 WebSocket(需要 Node 22 及以上)')
|
|
188
|
+
|
|
189
|
+
const profileDir = mkdtempSync(join(tmpdir(), 'omr-lingxi-login-'))
|
|
190
|
+
const exitState = { exited: false, error: null }
|
|
191
|
+
const child = spawn(browserPath, [
|
|
192
|
+
'--remote-debugging-port=0',
|
|
193
|
+
`--user-data-dir=${profileDir}`,
|
|
194
|
+
'--no-first-run',
|
|
195
|
+
'--no-default-browser-check',
|
|
196
|
+
'--disable-features=Translate,MediaRouter',
|
|
197
|
+
LOGIN_URL,
|
|
198
|
+
], { stdio: 'ignore', windowsHide: false })
|
|
199
|
+
child.once('exit', () => { exitState.exited = true })
|
|
200
|
+
child.once('error', error => { exitState.error = error; exitState.exited = true })
|
|
201
|
+
|
|
202
|
+
let cdp = null
|
|
203
|
+
try {
|
|
204
|
+
const port = await waitForDevToolsPort(profileDir, exitState)
|
|
205
|
+
const target = await pickPageTarget(port, exitState)
|
|
206
|
+
cdp = new CdpSession(target.webSocketDebuggerUrl)
|
|
207
|
+
await cdp.send('Network.enable')
|
|
208
|
+
|
|
209
|
+
const deadline = Date.now() + timeoutMs
|
|
210
|
+
let sawCookies = false
|
|
211
|
+
while (Date.now() < deadline) {
|
|
212
|
+
if (exitState.exited) throw new Error('登录窗口已关闭,未完成登录')
|
|
213
|
+
let credential = null
|
|
214
|
+
try { credential = pickCredential(await readAllCookies(cdp)) } catch { /* 页面切换时短暂失败,继续等 */ }
|
|
215
|
+
if (credential) {
|
|
216
|
+
sawCookies = true
|
|
217
|
+
const accepted = typeof verify === 'function' ? await verify(credential) : true
|
|
218
|
+
if (accepted !== false) return credential
|
|
219
|
+
}
|
|
220
|
+
await sleep(POLL_INTERVAL_MS)
|
|
221
|
+
}
|
|
222
|
+
throw new Error(sawCookies
|
|
223
|
+
? `已读取登录 Cookie,但灵犀接口未放行(等待 ${Math.round(timeoutMs / 1000)} 秒);请确认账号状态后重试`
|
|
224
|
+
: `等待登录超时(${Math.round(timeoutMs / 1000)} 秒),请重新点击「添加账号」`)
|
|
225
|
+
} finally {
|
|
226
|
+
try { cdp?.close() } catch { /* 已关闭 */ }
|
|
227
|
+
killBrowser(child)
|
|
228
|
+
// 浏览器退出后再删临时 profile;删不掉交给系统清理。
|
|
229
|
+
setTimeout(() => { try { rmSync(profileDir, { recursive: true, force: true }) } catch { /* 占用中 */ } }, 3_000).unref?.()
|
|
230
|
+
}
|
|
231
|
+
}
|