one-model-router 0.0.13 → 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.
@@ -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
+ }
@@ -0,0 +1,448 @@
1
+ /**
2
+ * WPS 灵犀本地凭据提取(自动续期用)。
3
+ *
4
+ * 来源与 dsh-connect-lingxi 的 refresh-lingxi-cred.ps1 相同:灵犀是 Chromium 桌面端,
5
+ * 登录 Cookie(kso_sid / wps_sid / uid)加密存在 `%APPDATA%\WPS 灵犀` 的 Cookies
6
+ * 库里,密钥在 `Local State` 里由 Windows DPAPI 保护。
7
+ *
8
+ * 本模块把那条 PowerShell 路径移植到 Node,避免要求用户手工运行脚本:
9
+ * 1. 复制 Cookie 库(优先 business 分区,其次 passport / default);
10
+ * 2. PowerShell 调 CryptUnprotectData 解出 AES-256 密钥;
11
+ * 3. Node 用 AES-256-GCM 解 Cookie(Chromium v10/v11 格式);
12
+ * 4. 读取 kso_sid / wps_sid / uid 与 kso_sid 的真实过期时间。
13
+ *
14
+ * 依赖(不满足时返回结构化失败,由调用方决定降级):
15
+ * - Windows + 与灵犀客户端同一 Windows 用户(DPAPI 限制);
16
+ * - 本机安装并登录过 WPS 灵犀(存在 Cookie 库);
17
+ * - 读取 SQLite 需要 Node 22.5+ 的 node:sqlite,或本机 Python 3。
18
+ *
19
+ * 说明:参考项目的 lingxi-rpc 走 account/login/start,只消费 wps_sid,
20
+ * 不产出 kso_sid,不能作为续期来源;这里只复用其离线 Cookie 库解密路径。
21
+ *
22
+ * 注意:只读、只写临时文件,成功/失败都会清理;不会把 Cookie 明文落盘。
23
+ */
24
+
25
+ import { createDecipheriv, createHash } from 'node:crypto'
26
+ import { spawn } from 'node:child_process'
27
+ import {
28
+ copyFileSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync,
29
+ } from 'node:fs'
30
+ import { homedir, tmpdir } from 'node:os'
31
+ import { basename, join } from 'node:path'
32
+
33
+ const COOKIE_NAMES = ['kso_sid', 'wps_sid', 'uid']
34
+ const COOKIE_NAME_SET = new Set(COOKIE_NAMES)
35
+ const CHROME_EPOCH_OFFSET_MS = 11_644_473_600_000
36
+
37
+ /** 允许用环境变量覆盖,便于测试与自定义安装位置。 */
38
+ export function lingxiHome() {
39
+ if (process.env.OMR_LINGXI_HOME) return process.env.OMR_LINGXI_HOME
40
+ const appData = process.env.APPDATA || join(homedir(), 'AppData', 'Roaming')
41
+ return join(appData, 'WPS 灵犀')
42
+ }
43
+
44
+ /** 自动续期是否具备最基本的本机条件(平台 + 灵犀目录)。 */
45
+ export function isAutoRefreshSupported() {
46
+ if (process.platform !== 'win32') return false
47
+ const root = lingxiHome()
48
+ return existsSync(root) && existsSync(join(root, 'Local State'))
49
+ }
50
+
51
+ // ── DPAPI(PowerShell 调用 crypt32)──────────────────────────────────────────
52
+
53
+ const DPAPI_PS1 = `param([string]$In,[string]$Out)
54
+ $ErrorActionPreference = 'Stop'
55
+ Add-Type -TypeDefinition @'
56
+ using System;
57
+ using System.Runtime.InteropServices;
58
+ public class LingxiDpapi {
59
+ [DllImport("crypt32.dll", SetLastError=true)]
60
+ public static extern bool CryptUnprotectData(ref DATA_BLOB pDataIn, IntPtr ppszDataDescr, IntPtr pOptionalEntropy, IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DATA_BLOB pDataOut);
61
+ [StructLayout(LayoutKind.Sequential)] public struct DATA_BLOB { public int cbData; public IntPtr pbData; }
62
+ public static byte[] Unprotect(byte[] data){
63
+ DATA_BLOB inBlob = new DATA_BLOB(); DATA_BLOB outBlob = new DATA_BLOB();
64
+ inBlob.cbData = data.Length; inBlob.pbData = Marshal.AllocHGlobal(data.Length);
65
+ Marshal.Copy(data, 0, inBlob.pbData, data.Length);
66
+ bool ok = CryptUnprotectData(ref inBlob, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, ref outBlob);
67
+ Marshal.FreeHGlobal(inBlob.pbData);
68
+ if(!ok) throw new Exception("CryptUnprotectData failed: " + Marshal.GetLastWin32Error());
69
+ byte[] result = new byte[outBlob.cbData];
70
+ Marshal.Copy(outBlob.pbData, result, 0, outBlob.cbData);
71
+ return result;
72
+ }
73
+ }
74
+ '@
75
+ $data = [IO.File]::ReadAllBytes($In)
76
+ $key = [LingxiDpapi]::Unprotect($data)
77
+ [IO.File]::WriteAllBytes($Out, $key)
78
+ `
79
+
80
+ function runProcess(command, args, timeoutMs) {
81
+ return new Promise((resolve, reject) => {
82
+ let child
83
+ try {
84
+ child = spawn(command, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
85
+ } catch (error) {
86
+ reject(error)
87
+ return
88
+ }
89
+ let stdout = ''
90
+ let stderr = ''
91
+ let settled = false
92
+ const finish = (error, value) => {
93
+ if (settled) return
94
+ settled = true
95
+ clearTimeout(timer)
96
+ if (error) reject(error)
97
+ else resolve(value)
98
+ }
99
+ const timer = setTimeout(() => {
100
+ try { child.kill() } catch { /* 已退出 */ }
101
+ finish(new Error(`进程超时(${timeoutMs}ms):${command}`))
102
+ }, timeoutMs)
103
+ timer.unref?.()
104
+ child.stdout?.on('data', chunk => { stdout += chunk.toString('utf8') })
105
+ child.stderr?.on('data', chunk => { stderr += chunk.toString('utf8') })
106
+ child.on('error', error => finish(error))
107
+ child.on('close', code => {
108
+ if (code === 0) finish(null, { stdout, stderr })
109
+ else finish(new Error(stderr.trim() || `${command} 退出码 ${code}`))
110
+ })
111
+ })
112
+ }
113
+
114
+ async function dpapiUnprotect(blob) {
115
+ const dir = mkdtempSync(join(tmpdir(), 'omr-lingxi-dpapi-'))
116
+ const inPath = join(dir, 'in.bin')
117
+ const outPath = join(dir, 'out.bin')
118
+ const ps1Path = join(dir, 'unprotect.ps1')
119
+ try {
120
+ writeFileSync(inPath, blob)
121
+ writeFileSync(ps1Path, DPAPI_PS1, 'utf8')
122
+ await runProcess('powershell.exe', [
123
+ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
124
+ '-File', ps1Path, '-In', inPath, '-Out', outPath,
125
+ ], 20_000)
126
+ const key = readFileSync(outPath)
127
+ if (key.length !== 32) throw new Error(`DPAPI 返回的密钥长度异常:${key.length}`)
128
+ return key
129
+ } finally {
130
+ try { rmSync(dir, { recursive: true, force: true }) } catch { /* 系统稍后清理 */ }
131
+ }
132
+ }
133
+
134
+ // ── Cookie 库定位与读取 ─────────────────────────────────────────────────────
135
+
136
+ function cookieDbCandidates(root) {
137
+ const out = []
138
+ const partitions = join(root, 'Partitions')
139
+ if (existsSync(partitions)) {
140
+ for (const name of readdirSync(partitions)) {
141
+ const path = join(partitions, name, 'Network', 'Cookies')
142
+ if (existsSync(path)) out.push({ name, path })
143
+ }
144
+ }
145
+ // business 分区里 kso_sid 最全,优先;其余按名称排序,保证稳定。
146
+ out.sort((a, b) => {
147
+ const score = item => item.name.includes('business') ? 0 : item.name.includes('passport') ? 1 : 2
148
+ return score(a) - score(b) || a.name.localeCompare(b.name)
149
+ })
150
+ const fallback = join(root, 'Network', 'Cookies')
151
+ if (existsSync(fallback)) out.push({ name: 'default', path: fallback })
152
+ return out
153
+ }
154
+
155
+ function stageCookieDb(candidate, dir) {
156
+ const safe = basename(candidate.name).replace(/[^a-zA-Z0-9._-]/g, '_') || 'cookies'
157
+ const target = join(dir, `${safe}.db`)
158
+ try {
159
+ copyFileSync(candidate.path, target)
160
+ for (const suffix of ['-wal', '-shm']) {
161
+ const from = candidate.path + suffix
162
+ if (existsSync(from)) {
163
+ try { copyFileSync(from, target + suffix) } catch { /* 可选文件,失败不影响 */ }
164
+ }
165
+ }
166
+ return { name: candidate.name, path: target, readOnly: false }
167
+ } catch {
168
+ // 客户端可能在运行时独占 Cookie 库:退而用只读方式打开原库。
169
+ return { name: candidate.name, path: candidate.path, readOnly: true }
170
+ }
171
+ }
172
+
173
+ let nodeSqlitePromise
174
+ function loadNodeSqlite() {
175
+ if (nodeSqlitePromise !== undefined) return nodeSqlitePromise
176
+ if (process.env.OMR_LINGXI_DISABLE_NODE_SQLITE === '1') {
177
+ nodeSqlitePromise = Promise.resolve(null)
178
+ return nodeSqlitePromise
179
+ }
180
+ nodeSqlitePromise = import('node:sqlite')
181
+ .then(mod => mod.DatabaseSync ?? null)
182
+ .catch(() => null)
183
+ return nodeSqlitePromise
184
+ }
185
+
186
+ async function readRowsWithNodeSqlite(dbPath, readOnly) {
187
+ const DatabaseSync = await loadNodeSqlite()
188
+ if (!DatabaseSync) return null
189
+ const db = readOnly
190
+ ? new DatabaseSync(dbPath, { readOnly: true })
191
+ : new DatabaseSync(dbPath)
192
+ try {
193
+ return db.prepare('SELECT host_key, name, encrypted_value, CAST(expires_utc AS TEXT) AS expires_utc FROM cookies').all()
194
+ .map(row => ({
195
+ host: String(row.host_key ?? ''),
196
+ name: String(row.name ?? ''),
197
+ encrypted: Buffer.from(row.encrypted_value ?? []),
198
+ expiresUtc: Number(row.expires_utc ?? 0) || 0,
199
+ }))
200
+ } finally {
201
+ try { db.close() } catch { /* 已关闭 */ }
202
+ }
203
+ }
204
+
205
+ const PY_SCRIPT = `import sqlite3, sys, json, base64
206
+ from pathlib import Path
207
+ p = sys.argv[1]
208
+ ro = len(sys.argv) > 2 and sys.argv[2] == "1"
209
+ uri = Path(p).resolve().as_uri() + ("?mode=ro" if ro else "")
210
+ con = sqlite3.connect(uri, uri=True)
211
+ try:
212
+ rows = [[h, n, base64.b64encode(bytes(v or b"")).decode("ascii"), int(e or 0)]
213
+ for h, n, v, e in con.execute("select host_key,name,encrypted_value,expires_utc from cookies")]
214
+ finally:
215
+ con.close()
216
+ print(json.dumps(rows))
217
+ `
218
+
219
+ function pythonCandidates() {
220
+ const out = []
221
+ if (process.env.OMR_PYTHON) out.push({ command: process.env.OMR_PYTHON, args: [] })
222
+ const bundled = join(lingxiHome(), 'python-env', 'python.exe')
223
+ if (existsSync(bundled)) out.push({ command: bundled, args: [] })
224
+ out.push({ command: 'python', args: [] })
225
+ out.push({ command: 'py', args: ['-3'] })
226
+ return out
227
+ }
228
+
229
+ async function readRowsWithPython(dbPath, readOnly) {
230
+ let lastError = null
231
+ for (const candidate of pythonCandidates()) {
232
+ try {
233
+ const { stdout } = await runProcess(
234
+ candidate.command,
235
+ [...candidate.args, '-c', PY_SCRIPT, dbPath, readOnly ? '1' : '0'],
236
+ 20_000,
237
+ )
238
+ const rows = JSON.parse(stdout)
239
+ if (!Array.isArray(rows)) throw new Error('Python 未返回 Cookie 数组')
240
+ return rows.map(([host, name, b64, expiresUtc]) => ({
241
+ host: String(host ?? ''),
242
+ name: String(name ?? ''),
243
+ encrypted: Buffer.from(String(b64 ?? ''), 'base64'),
244
+ expiresUtc: Number(expiresUtc) || 0,
245
+ }))
246
+ } catch (error) {
247
+ lastError = error
248
+ if (error?.code === 'ENOENT') continue
249
+ // Python 已找到但读取失败(锁定 / 不是 SQLite):不再换解释器。
250
+ throw error
251
+ }
252
+ }
253
+ throw lastError ?? new Error('未找到可用的 Python 解释器')
254
+ }
255
+
256
+ async function readCookieRows(dbPath, readOnly) {
257
+ try {
258
+ const rows = await readRowsWithNodeSqlite(dbPath, readOnly)
259
+ if (rows) return rows
260
+ } catch (error) {
261
+ // node:sqlite 不可用或读失败时交给 Python;两者都失败再由调用方归类。
262
+ if (!/not a database|no such table|unable to open|locked|busy/i.test(String(error?.message ?? error))) throw error
263
+ }
264
+ return readRowsWithPython(dbPath, readOnly)
265
+ }
266
+
267
+ // ── 解密 ────────────────────────────────────────────────────────────────────
268
+
269
+ function decryptCookie(encrypted, key, hostKey) {
270
+ const buf = Buffer.isBuffer(encrypted) ? encrypted : Buffer.from(encrypted)
271
+ if (buf.length === 0) return ''
272
+ const prefix = buf.subarray(0, 3).toString('latin1')
273
+ if (prefix !== 'v10' && prefix !== 'v11') {
274
+ if (prefix === 'v20') throw new Error('app-bound cookie(v20)不支持')
275
+ // 旧版明文 Cookie
276
+ return buf.toString('utf8')
277
+ }
278
+ if (buf.length < 3 + 12 + 16) throw new Error('Cookie 密文长度异常')
279
+ const nonce = buf.subarray(3, 15)
280
+ const tag = buf.subarray(buf.length - 16)
281
+ const data = buf.subarray(15, buf.length - 16)
282
+ const decipher = createDecipheriv('aes-256-gcm', key, nonce)
283
+ decipher.setAuthTag(tag)
284
+ const plain = Buffer.concat([decipher.update(data), decipher.final()])
285
+ const hostHash = createHash('sha256').update(hostKey).digest()
286
+ if (plain.length >= 32 && plain.subarray(0, 32).equals(hostHash)) {
287
+ return plain.subarray(32).toString('utf8')
288
+ }
289
+ return plain.toString('utf8')
290
+ }
291
+
292
+ /** Chromium expires_utc(1601 起微秒)→ Unix 毫秒;0/非法值返回 0。 */
293
+ function chromeTimeToMs(utc) {
294
+ const value = Number(utc)
295
+ if (!Number.isFinite(value) || value <= 0) return 0
296
+ return Math.round(value / 1000 - CHROME_EPOCH_OFFSET_MS)
297
+ }
298
+
299
+ // ── 主流程 ──────────────────────────────────────────────────────────────────
300
+
301
+ let inflight = null
302
+
303
+ /**
304
+ * 读取本机灵犀登录 Cookie。
305
+ * @returns {Promise<{ok:true, credential:object, source:string} | {ok:false, code:string, reason:string}>}
306
+ */
307
+ export function readLocalCredential() {
308
+ if (inflight) return inflight
309
+ inflight = doReadLocalCredential().finally(() => { inflight = null })
310
+ return inflight
311
+ }
312
+
313
+ async function doReadLocalCredential() {
314
+ if (process.platform !== 'win32') {
315
+ return { ok: false, code: 'unsupported-platform', reason: '自动续期仅支持 Windows(依赖 DPAPI 解密灵犀 Cookie)' }
316
+ }
317
+ const root = lingxiHome()
318
+ if (!existsSync(root)) {
319
+ return { ok: false, code: 'no-client', reason: `未找到灵犀配置目录:${root}` }
320
+ }
321
+ const localStatePath = join(root, 'Local State')
322
+ if (!existsSync(localStatePath)) {
323
+ return { ok: false, code: 'no-client', reason: '未找到灵犀 Local State,客户端可能未启动过' }
324
+ }
325
+
326
+ const candidates = cookieDbCandidates(root)
327
+ if (candidates.length === 0) {
328
+ return { ok: false, code: 'no-cookie-db', reason: '未找到灵犀 Cookie 库(Network/Cookies)' }
329
+ }
330
+
331
+ let localState
332
+ try {
333
+ localState = JSON.parse(readFileSync(localStatePath, 'utf8'))
334
+ } catch (error) {
335
+ return { ok: false, code: 'bad-local-state', reason: `Local State 解析失败:${error?.message ?? error}` }
336
+ }
337
+ const encryptedKey = localState?.os_crypt?.encrypted_key
338
+ if (typeof encryptedKey !== 'string' || encryptedKey === '') {
339
+ return { ok: false, code: 'no-encrypted-key', reason: 'Local State 缺少 os_crypt.encrypted_key' }
340
+ }
341
+ let keyBlob
342
+ try {
343
+ keyBlob = Buffer.from(encryptedKey, 'base64')
344
+ } catch (error) {
345
+ return { ok: false, code: 'bad-encrypted-key', reason: `encrypted_key 不是合法 Base64:${error?.message ?? error}` }
346
+ }
347
+ if (keyBlob.subarray(0, 5).toString('latin1') !== 'DPAPI') {
348
+ return { ok: false, code: 'bad-encrypted-key', reason: 'encrypted_key 不是 DPAPI 格式(可能被其他用户/机器加密)' }
349
+ }
350
+
351
+ let key
352
+ try {
353
+ key = await dpapiUnprotect(keyBlob.subarray(5))
354
+ } catch (error) {
355
+ return {
356
+ ok: false,
357
+ code: 'dpapi-failed',
358
+ reason: `DPAPI 解密失败:${error?.message ?? error}。需与灵犀客户端使用同一 Windows 用户运行`,
359
+ }
360
+ }
361
+
362
+ const work = mkdtempSync(join(tmpdir(), 'omr-lingxi-cookies-'))
363
+ try {
364
+ const staged = candidates.map(candidate => stageCookieDb(candidate, work))
365
+ const found = new Map()
366
+ const fallback = new Map()
367
+ let readError = null
368
+ let rowsRead = 0
369
+ let sawAppBound = false
370
+ for (const db of staged) {
371
+ let rows
372
+ try {
373
+ rows = await readCookieRows(db.path, db.readOnly)
374
+ } catch (error) {
375
+ readError = error
376
+ continue
377
+ }
378
+ rowsRead += rows.length
379
+ for (const row of rows) {
380
+ if (!COOKIE_NAME_SET.has(row.name) || found.has(row.name)) continue
381
+ let value
382
+ try {
383
+ value = decryptCookie(row.encrypted, key, row.host)
384
+ } catch (error) {
385
+ if (/v20|app-bound/i.test(String(error?.message ?? error))) sawAppBound = true
386
+ continue
387
+ }
388
+ if (!value) continue
389
+ const entry = { value, expiresUtc: row.expiresUtc, host: row.host }
390
+ // 优先 wps.cn 域,避免同名 Cookie 混入其他站点。
391
+ if (row.host.includes('wps.cn')) found.set(row.name, entry)
392
+ else if (!fallback.has(row.name)) fallback.set(row.name, entry)
393
+ }
394
+ }
395
+ for (const [name, entry] of fallback) if (!found.has(name)) found.set(name, entry)
396
+
397
+ const missing = COOKIE_NAMES.filter(name => !found.has(name))
398
+ if (missing.length > 0) {
399
+ if (sawAppBound) {
400
+ return {
401
+ ok: false,
402
+ code: 'app-bound-cookie',
403
+ reason: '灵犀 Cookie 使用了 v20 app-bound 加密,无法离线解密;请在灵犀客户端重新登录后重试,或手动粘贴凭据',
404
+ }
405
+ }
406
+ if (rowsRead === 0 && readError) {
407
+ const message = String(readError?.message ?? readError)
408
+ const locked = /locked|unable to open|sharing violation|EBUSY|EPERM|database is locked|SQLITE_BUSY/i.test(message)
409
+ return {
410
+ ok: false,
411
+ code: locked ? 'client-running' : 'cookie-read-failed',
412
+ reason: locked
413
+ ? `灵犀可能正在运行并锁定 Cookie 库:${message}。完全退出灵犀(含托盘)后会自动重试`
414
+ : `读取灵犀 Cookie 库失败:${message}(需要 Node 22.5+ 的 node:sqlite,或本机 Python 3)`,
415
+ }
416
+ }
417
+ return {
418
+ ok: false,
419
+ code: 'cookies-missing',
420
+ reason: `本地 Cookie 库缺少 ${missing.join(' / ')},请确认灵犀已登录,或完全退出灵犀后重试`,
421
+ }
422
+ }
423
+
424
+ const kso = found.get('kso_sid')
425
+ const expiresAt = chromeTimeToMs(kso.expiresUtc)
426
+ if (expiresAt > 0 && expiresAt <= Date.now()) {
427
+ return {
428
+ ok: false,
429
+ code: 'cookie-expired',
430
+ reason: `本机 kso_sid 已过期(${new Date(expiresAt).toLocaleString()}),请启动灵犀客户端刷新登录态后重试`,
431
+ }
432
+ }
433
+
434
+ return {
435
+ ok: true,
436
+ source: 'local-cookie-db',
437
+ credential: {
438
+ kso_sid: found.get('kso_sid').value,
439
+ wps_sid: found.get('wps_sid').value,
440
+ uid: found.get('uid').value,
441
+ captured_at: new Date().toISOString(),
442
+ ...(expiresAt > 0 ? { expires_at: new Date(expiresAt).toISOString() } : {}),
443
+ },
444
+ }
445
+ } finally {
446
+ try { rmSync(work, { recursive: true, force: true }) } catch { /* 系统稍后清理 */ }
447
+ }
448
+ }