one-model-router 0.0.13 → 0.0.15
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 +11 -6
- package/bin/omr.js +96 -14
- package/package.json +2 -1
- package/src/admin.js +200 -31
- package/src/boot.js +14 -3
- 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/install-forms.js +238 -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 +134 -59
- package/web/app.js +494 -81
- package/web/index.html +2 -2
- package/web/style.css +26 -6
|
@@ -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
|
+
}
|