dsh-cookie-cleaner 0.7.1 → 0.7.2

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/src/jar-live.js CHANGED
@@ -1,365 +1,365 @@
1
- /**
2
- * dsh-cookie-cleaner — 借「已经打开这个文件的句柄」读被独占锁定的 cookie 库(Windows)。
3
- *
4
- * 为什么需要它:桌面端 Chromium 打开 `Network/Cookies` 时不给共享读,普通只读打开、
5
- * 复制到临时库、`?immutable=1` 全部失败(本机实测:`EBUSY` / `ERR_SQLITE_ERROR`)。
6
- * 但目标进程自己手里就有一个可用句柄 —— 把它 `DuplicateHandle` 过来就能读到字节。
7
- *
8
- * 本机(Windows 11 26H2 + Node 22 + 宿主自带 koffi)实测到的四条硬事实,全部写在这里而不是散在调用处:
9
- * 1. `NtQuerySystemInformation(SystemExtendedHandleInformation=64)` 一次约 27 万条,扫完约 9ms;
10
- * 2. x64 条目布局:`stride=40`,`Object@0 / UniqueProcessId@8 / HandleValue@16 / GrantedAccess@24 / ObjectTypeIndex@30`,表头 16 字节;
11
- * 3. `OpenProcess` 必须带 **PROCESS_QUERY_INFORMATION(0x40)**;只给 PROCESS_DUP_HANDLE(0x20) 或
12
- * PROCESS_QUERY_LIMITED_INFORMATION(0x1000) 会被 `ERROR_ACCESS_DENIED(5)` 拒;`0x400|0x1000` 互斥混传也失败;
13
- * 4. 非可复制类型的句柄返回 err 50(ERROR_NOT_SUPPORTED),属正常,跳过即可。
14
- *
15
- * 纪律:整模块是**可选增强**。koffi 找不到、平台不是 win32、没匹配到句柄、读出来打不开
16
- * —— 一律返回 `{ok:false, reason}`,由调用方退回「读不到」档。**绝不猜数**。
17
- */
18
- import fs from 'node:fs'
19
- import os from 'node:os'
20
- import path from 'node:path'
21
- import process from 'node:process'
22
- import { createRequire } from 'node:module'
23
-
24
- export const EXTENDED_HANDLE_CLASS = 64
25
- export const HANDLE_STRIDE = 40
26
- export const HANDLE_TABLE_BASE = 16
27
- export const PID_FIELD_OFFSET = 8
28
- export const HANDLE_FIELD_OFFSET = 16
29
- /** 唯一实测可用的 OpenProcess 权限位(见文件头第 3 条)。 */
30
- export const PROCESS_QUERY_INFORMATION = 0x0040
31
- export const DUPLICATE_SAME_ACCESS = 0x0002
32
- export const TH32CS_SNAPPROCESS = 0x00000002
33
- /** 进程条目:PROCESSENTRY32W 的 x64 布局(dwSize@0,th32ProcessID@8,szExeFile@44)。 */
34
- export const PROCESS_ENTRY_SIZE = 568
35
- export const PROCESS_ENTRY_PID_OFFSET = 8
36
- export const PROCESS_ENTRY_NAME_OFFSET = 44
37
- export const PROCESS_ENTRY_NAME_BYTES = 520
38
- /** 单次快照读取上限:cookie 库实测 20–53 KB,给足余量但绝不无界。 */
39
- export const MAX_SNAPSHOT_BYTES = 32 << 20
40
- /** 分块读的大小:一次读到底比重复调用系统调用便宜。 */
41
- const READ_CHUNK_BYTES = 1 << 20
42
-
43
- /**
44
- * koffi 的候选位置。它**不在** profile 的依赖树里,只能扫宿主自己的安装位置;
45
- * 顺序即优先级,`DSH_KOFFI_PATH` 给运维留一个显式入口。
46
- * @param {{platform?:string, execPath?:string, env?:Record<string,string|undefined>, homedir?:string, exists?:(p:string)=>boolean}} [input]
47
- * @returns {string[]}
48
- */
49
- export function koffiCandidates(input = {}) {
50
- const {
51
- platform = process.platform,
52
- execPath = process.execPath,
53
- env = process.env,
54
- homedir = os.homedir(),
55
- exists = (p) => { try { return fs.existsSync(p) } catch { return false } },
56
- } = input
57
- if (platform !== 'win32') return []
58
- const appDir = path.dirname(execPath)
59
- const candidates = [
60
- // Electron 桌面端:原生模块解包在 app.asar.unpacked 下
61
- path.join(appDir, 'resources', 'app.asar.unpacked', 'dsh', 'node_modules', 'koffi'),
62
- path.join(appDir, 'resources', 'app.asar.unpacked', 'node_modules', 'koffi'),
63
- path.join(appDir, 'node_modules', 'koffi'),
64
- // CLI 全局安装树:宿主包自己的嵌套依赖
65
- path.join(path.dirname(appDir), 'node_modules', '@deepseek-ai', 'dsh', 'node_modules', 'koffi'),
66
- path.join(appDir, 'node_modules', '@deepseek-ai', 'dsh', 'node_modules', 'koffi'),
67
- // 用户级 DSH home(非标准安装/便携版)
68
- path.join(homedir, '.dsh', 'vendor', 'koffi'),
69
- ]
70
- const explicit = String(env.DSH_KOFFI_PATH ?? '').trim()
71
- const list = explicit === '' ? candidates : [explicit, ...candidates]
72
- return list.filter((p) => exists(p))
73
- }
74
-
75
- /**
76
- * 解析出可用的 koffi。任何异常都吞掉返回 undefined —— 调用方据此退回「读不到」。
77
- * @param {string[]} candidates
78
- * @param {(spec:string)=>any} [requireImpl]
79
- */
80
- export function loadKoffi(candidates, requireImpl = createRequire(import.meta.url)) {
81
- for (const spec of candidates) {
82
- try {
83
- const mod = requireImpl(spec)
84
- // 注意:`func` 是 `koffi.load(...)` 返回的库句柄上的方法,koffi 顶层只有 `load`——
85
- // 拿 `func` 当顶层形状条件会把可用的 koffi 误判成没有(真机踩到)。
86
- const shape = (value) => value !== null && typeof value === 'object' && typeof value.load === 'function'
87
- const koffi = shape(mod) ? mod : shape(mod?.default) ? mod.default : undefined
88
- if (koffi !== undefined) return koffi
89
- } catch { /* 下一个候选 */ }
90
- }
91
- return undefined
92
- }
93
-
94
- /** 绑定需要的 Win32 入口。失败返回 undefined(不抛)。 */
95
- export function openApi(koffi) {
96
- if (koffi === undefined) return undefined
97
- try {
98
- const k32 = koffi.load('kernel32.dll')
99
- const ntdll = koffi.load('ntdll.dll')
100
- return {
101
- koffi,
102
- NtQuerySystemInformation: ntdll.func('int32_t NtQuerySystemInformation(uint32_t, void *, uint32_t, uint32_t *)'),
103
- CreateToolhelp32Snapshot: k32.func('void *CreateToolhelp32Snapshot(uint32_t, uint32_t)'),
104
- Process32FirstW: k32.func('int32_t Process32FirstW(void *, void *)'),
105
- Process32NextW: k32.func('int32_t Process32NextW(void *, void *)'),
106
- OpenProcess: k32.func('void *OpenProcess(uint32_t, int32_t, uint32_t)'),
107
- GetCurrentProcess: k32.func('void *GetCurrentProcess()'),
108
- DuplicateHandle: k32.func('int32_t DuplicateHandle(void *, void *, void *, void *, uint32_t, int32_t, uint32_t)'),
109
- GetFinalPathNameByHandleW: k32.func('uint32_t GetFinalPathNameByHandleW(void *, void *, uint32_t, uint32_t)'),
110
- SetFilePointerEx: k32.func('int32_t SetFilePointerEx(void *, int64_t, void *, uint32_t)'),
111
- GetFileSizeEx: k32.func('int32_t GetFileSizeEx(void *, void *)'),
112
- ReadFile: k32.func('int32_t ReadFile(void *, void *, uint32_t, void *, void *)'),
113
- CloseHandle: k32.func('int32_t CloseHandle(void *)'),
114
- }
115
- } catch {
116
- return undefined
117
- }
118
- }
119
-
120
- /**
121
- * 从进程条目里取 PID 与可执行文件名(纯函数,便于脱离 FFI 单测)。
122
- * @param {Buffer} entry PROCESSENTRY32W 缓冲区
123
- */
124
- export function readProcessEntry(entry) {
125
- if (entry === undefined || entry.length < PROCESS_ENTRY_SIZE) return undefined
126
- const pid = entry.readUInt32LE(PROCESS_ENTRY_PID_OFFSET)
127
- const raw = entry.toString('utf16le', PROCESS_ENTRY_NAME_OFFSET, PROCESS_ENTRY_NAME_OFFSET + PROCESS_ENTRY_NAME_BYTES)
128
- const exe = raw.split('\u0000')[0] ?? ''
129
- return { pid, exe }
130
- }
131
-
132
- /**
133
- * 取映像基名。**两种分隔符都切**:Win32 给的路带 `\`,而在非 win32 上跑单测时
134
- * `path.basename` 不认反斜杠,会把整串当一个名字(真机两侧红过)。
135
- */
136
- export function imageBaseName(exe) {
137
- return String(exe ?? '').split(/[\\/]/).filter(Boolean).pop() ?? ''
138
- }
139
-
140
- /**
141
- * 目标进程判定:**同一镜像名**或**父进程**,不写死品牌名。
142
- *
143
- * 真机坑:`PROCESSENTRY32W.szExeFile` 只是**映像基名**(`node.exe`、`DeepSeek Harness.exe`),
144
- * 不是完整路径 —— 拿它去比目录会永远不匹配(集成测试当场拓出来的)。
145
- * 桌面端主进程/渲染进程/GPU/工具子进程共用同一个镜像名,正好就是我们要找的那批。
146
- * @param {{pid:number, exe:string}} processEntry
147
- * @param {{selfPid:number, selfExe:string, ppid?:number}} scope
148
- */
149
- export function isTargetProcess(processEntry, scope) {
150
- const { pid, exe } = processEntry
151
- if (pid === undefined || pid === scope.selfPid) return false
152
- if (scope.ppid !== undefined && pid === scope.ppid) return true
153
- const name = String(exe ?? '')
154
- if (name === '') return false
155
- return imageBaseName(name).toLowerCase() === String(scope.selfExe ?? '').toLowerCase()
156
- }
157
-
158
- /** 枚举目标 PID(快照失败返回空数组,绝不抛)。 */
159
- export function targetPids(api, scope = {}) {
160
- const {
161
- selfPid = process.pid, ppid = process.ppid,
162
- selfExe = imageBaseName(process.execPath),
163
- } = scope
164
- const found = new Set()
165
- if (typeof ppid === 'number' && ppid > 0 && ppid !== selfPid) found.add(ppid)
166
- let snapshot
167
- try {
168
- snapshot = api.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
169
- if (snapshot === null || snapshot === undefined || snapshot === 0n) return [...found]
170
- const entry = Buffer.alloc(PROCESS_ENTRY_SIZE)
171
- entry.writeUInt32LE(PROCESS_ENTRY_SIZE, 0)
172
- let more = api.Process32FirstW(snapshot, entry)
173
- let guard = 0
174
- while (more === 1 && guard < 65536) {
175
- const info = readProcessEntry(entry)
176
- if (info !== undefined && isTargetProcess(info, { selfPid, ppid, selfExe })) found.add(info.pid)
177
- more = api.Process32NextW(snapshot, entry)
178
- guard += 1
179
- }
180
- api.CloseHandle(snapshot)
181
- } catch {
182
- /* 快照不可用就只靠 ppid,仍然可能借到 */
183
- }
184
- return [...found]
185
- }
186
-
187
- /**
188
- * 解析句柄表,取目标进程持有的句柄值(纯函数:给定 Buffer 就能测)。
189
- * @param {Buffer} table NtQuerySystemInformation 的原始输出
190
- * @param {Iterable<number>} pids 目标 PID 集合
191
- * @param {{limit?:number}} [options]
192
- * @returns {Array<{pid:number, handle:bigint}>}
193
- */
194
- export function handleEntriesFor(table, pids, options = {}) {
195
- const { limit = 2_000_000 } = options
196
- const wanted = new Set(pids)
197
- const out = []
198
- if (table === undefined || table.length < HANDLE_TABLE_BASE + HANDLE_STRIDE) return out
199
- const total = Number(table.readBigUInt64LE(0))
200
- const scan = Math.min(total, limit)
201
- for (let i = 0; i < scan; i++) {
202
- const base = HANDLE_TABLE_BASE + i * HANDLE_STRIDE
203
- if (base + HANDLE_STRIDE > table.length) break
204
- const pid = Number(table.readBigUInt64LE(base + PID_FIELD_OFFSET))
205
- if (!wanted.has(pid)) continue
206
- out.push({ pid, handle: table.readBigUInt64LE(base + HANDLE_FIELD_OFFSET) })
207
- }
208
- return out
209
- }
210
-
211
- /** `\\?\C:\dir\file` 这类 DOS 设备前缀要去掉再比;大小写不敏感。 */
212
- export function normalizeHandlePath(name) {
213
- const text = String(name ?? '')
214
- const stripped = text.startsWith('\\\\?\\') ? text.slice(4) : text
215
- return stripped.toLowerCase()
216
- }
217
-
218
- /** 句柄表查询:容量不足时按返回长度重试。返回 Buffer 或 {error}。 */
219
- function queryHandleTable(api) {
220
- const needed = Buffer.alloc(4)
221
- let size = 1 << 22
222
- for (let attempt = 0; attempt < 5; attempt++) {
223
- const table = Buffer.alloc(size)
224
- const status = api.NtQuerySystemInformation(EXTENDED_HANDLE_CLASS, table, size, needed) >>> 0
225
- if (status === 0) return table
226
- // STATUS_INFO_LENGTH_MISMATCH:按系统要求的长度再来一次
227
- if (status === 0xc0000004) {
228
- size = Math.max(needed.readUInt32LE(0) + (4 << 20), size * 2)
229
- continue
230
- }
231
- return { error: `ntstatus=0x${status.toString(16)}` }
232
- }
233
- return { error: 'handle table too large' }
234
- }
235
-
236
- /**
237
- * 借句柄读出文件字节。成功返回 Buffer,失败返回 `{ok:false, reason}`。
238
- * 只做读:不写、不改共享模式、不关闭别人的句柄(只关自己 dup 出来的那份)。
239
- *
240
- * 预算不是装饰:按基名匹配时目标可能是几十个同名进程 × 上百句柄,每次 dup+取路径都是 FFI 调用。
241
- * 所以:每个 PID 只 `OpenProcess` 一次(不是每句柄一次)、按 pids 给定的优先级逐个试、
242
- * 命中即返回,并有时间/次数两道上限。超预算就明说 `scan-budget`,不拿“读不到”伪装成偶然。
243
- * @param {object} api openApi() 的结果
244
- * @param {{filePath:string, pids:number[], maxBytes?:number, maxAttempts?:number, budgetMs?:number, now?:()=>number}} input
245
- */
246
- export function borrowBytes(api, input) {
247
- const { filePath, pids } = input
248
- const maxBytes = input.maxBytes ?? MAX_SNAPSHOT_BYTES
249
- const maxAttempts = input.maxAttempts ?? 20000
250
- const budgetMs = input.budgetMs ?? 1200
251
- const now = input.now ?? Date.now
252
- if (api === undefined) return { ok: false, reason: 'no-ffi' }
253
- if (!Array.isArray(pids) || pids.length === 0) return { ok: false, reason: 'no-target-pids' }
254
- const table = queryHandleTable(api)
255
- if (!Buffer.isBuffer(table)) return { ok: false, reason: table.error }
256
- const wanted = normalizeHandlePath(filePath)
257
- const self = api.GetCurrentProcess()
258
- const outHandle = Buffer.alloc(8)
259
- const nameBuf = Buffer.alloc(4096 * 2)
260
- const sizeBuf = Buffer.alloc(8)
261
- const readBuf = Buffer.alloc(4)
262
- const started = now()
263
- const order = new Map()
264
- for (const entry of handleEntriesFor(table, pids)) {
265
- const list = order.get(entry.pid) ?? []
266
- list.push(entry.handle)
267
- order.set(entry.pid, list)
268
- }
269
- let attempts = 0
270
- for (const pid of pids) {
271
- const handles = order.get(pid)
272
- if (handles === undefined || handles.length === 0) continue
273
- const processHandle = api.OpenProcess(PROCESS_QUERY_INFORMATION, 0, pid)
274
- const opened = processHandle !== null && processHandle !== undefined && processHandle !== 0n
275
- if (!opened) continue
276
- for (const handle of handles) {
277
- attempts += 1
278
- if (attempts > maxAttempts || now() - started > budgetMs) {
279
- api.CloseHandle(processHandle)
280
- return { ok: false, reason: 'scan-budget', attempts }
281
- }
282
- let copied
283
- try {
284
- copied = api.DuplicateHandle(processHandle, handle, self, outHandle, 0, 0, DUPLICATE_SAME_ACCESS)
285
- } catch {
286
- copied = 0
287
- }
288
- if (copied !== 1) continue
289
- const duplicate = outHandle.readBigUInt64LE(0)
290
- const length = api.GetFinalPathNameByHandleW(duplicate, nameBuf, 4096, 0)
291
- const name = length > 0 ? normalizeHandlePath(nameBuf.toString('utf16le', 0, Number(length) * 2).split('\u0000')[0]) : ''
292
- if (name !== wanted || name.includes('partitions')) {
293
- api.CloseHandle(duplicate)
294
- continue
295
- }
296
- api.CloseHandle(processHandle)
297
- if (api.GetFileSizeEx(duplicate, sizeBuf) !== 1) { api.CloseHandle(duplicate); return { ok: false, reason: 'size-unknown' } }
298
- const bytes = Number(sizeBuf.readBigUInt64LE(0))
299
- if (!Number.isInteger(bytes) || bytes <= 0) { api.CloseHandle(duplicate); return { ok: false, reason: 'size-invalid' } }
300
- if (bytes > maxBytes) { api.CloseHandle(duplicate); return { ok: false, reason: 'too-large' } }
301
- if (api.SetFilePointerEx(duplicate, 0, null, 0) !== 1) { api.CloseHandle(duplicate); return { ok: false, reason: 'seek-failed' } }
302
- const chunks = []
303
- let done = 0
304
- let broken = false
305
- const chunk = Buffer.alloc(Math.min(bytes, READ_CHUNK_BYTES))
306
- while (done < bytes) {
307
- const want = Math.min(chunk.length, bytes - done)
308
- readBuf.writeUInt32LE(0, 0)
309
- const ok = api.ReadFile(duplicate, chunk, want, readBuf, null)
310
- const got = readBuf.readUInt32LE(0)
311
- if (ok !== 1 || got === 0) { broken = true; break }
312
- chunks.push(Buffer.from(chunk.subarray(0, got)))
313
- done += got
314
- }
315
- api.CloseHandle(duplicate)
316
- if (broken || done !== bytes) return { ok: false, reason: 'read-incomplete' }
317
- return { ok: true, buffer: Buffer.concat(chunks, bytes), pid, bytes: done, attempts }
318
- }
319
- api.CloseHandle(processHandle)
320
- }
321
- return { ok: false, reason: 'handle-not-found', attempts }
322
- }
323
-
324
- /**
325
- * 一站式:解析 koffi → 找目标进程 → 借句柄 → 落临时快照。
326
- * 只读;临时文件在返回前写完,删除交给调用方(`statCookies` 读完再删)。
327
- * @param {{filePath:string, candidates?:string[], pids?:number[], requireImpl?:Function, now?:()=>number, tmpDir?:string, exists?:(p:string)=>boolean}} [input]
328
- * @returns {{ok:boolean, snapshotPath?:string, reason?:string, bytes?:number, source:'borrowed-handle'}}
329
- */
330
- export function snapshotThroughHandle(input = {}) {
331
- const {
332
- filePath,
333
- requireImpl,
334
- now = () => Date.now(),
335
- tmpDir = os.tmpdir(),
336
- } = input
337
- const candidates = input.candidates ?? koffiCandidates(input)
338
- if (candidates.length === 0) return { ok: false, reason: 'koffi-not-found', source: 'borrowed-handle' }
339
- const koffi = loadKoffi(candidates, requireImpl)
340
- if (koffi === undefined) return { ok: false, reason: 'koffi-unsupported', source: 'borrowed-handle' }
341
- const api = openApi(koffi)
342
- if (api === undefined) return { ok: false, reason: 'ffi-bindings-failed', source: 'borrowed-handle' }
343
- // 显式 pids 优先(测试与定向排查用);没给才去扫进程快照,并把父进程排第一位(真实场景里就是宿主本体)
344
- const pids = Array.isArray(input.pids) && input.pids.length > 0 ? input.pids : prioritizeParent(targetPids(api), process.ppid)
345
- const borrowed = borrowBytes(api, { filePath, pids, now })
346
- if (borrowed.ok !== true) return { ok: false, reason: borrowed.reason ?? 'borrow-failed', source: 'borrowed-handle' }
347
- const snapshotPath = path.join(tmpDir, `dcc-jar-${String(now())}.sqlite`)
348
- try {
349
- fs.writeFileSync(snapshotPath, borrowed.buffer)
350
- } catch (e) {
351
- return { ok: false, reason: `snapshot-write-${String(e && e.code ? e.code : e.message)}`, source: 'borrowed-handle' }
352
- }
353
- return { ok: true, snapshotPath, bytes: borrowed.bytes, source: 'borrowed-handle' }
354
- }
355
-
356
- /** 父进程优先:真实场景里 cookie 库就被宿主自己的进程持着,先试它能少扫很多。 */
357
- export function prioritizePids(pids, first) {
358
- const list = [...new Set(pids.filter((pid) => typeof pid === 'number' && pid > 0))]
359
- if (typeof first !== 'number' || first <= 0) return list
360
- return [first, ...list.filter((pid) => pid !== first)]
361
- }
362
-
363
- function prioritizeParent(pids, parentPid) {
364
- return prioritizePids(pids, parentPid)
365
- }
1
+ /**
2
+ * dsh-cookie-cleaner — 借「已经打开这个文件的句柄」读被独占锁定的 cookie 库(Windows)。
3
+ *
4
+ * 为什么需要它:桌面端 Chromium 打开 `Network/Cookies` 时不给共享读,普通只读打开、
5
+ * 复制到临时库、`?immutable=1` 全部失败(本机实测:`EBUSY` / `ERR_SQLITE_ERROR`)。
6
+ * 但目标进程自己手里就有一个可用句柄 —— 把它 `DuplicateHandle` 过来就能读到字节。
7
+ *
8
+ * 本机(Windows 11 26H2 + Node 22 + 宿主自带 koffi)实测到的四条硬事实,全部写在这里而不是散在调用处:
9
+ * 1. `NtQuerySystemInformation(SystemExtendedHandleInformation=64)` 一次约 27 万条,扫完约 9ms;
10
+ * 2. x64 条目布局:`stride=40`,`Object@0 / UniqueProcessId@8 / HandleValue@16 / GrantedAccess@24 / ObjectTypeIndex@30`,表头 16 字节;
11
+ * 3. `OpenProcess` 必须带 **PROCESS_QUERY_INFORMATION(0x40)**;只给 PROCESS_DUP_HANDLE(0x20) 或
12
+ * PROCESS_QUERY_LIMITED_INFORMATION(0x1000) 会被 `ERROR_ACCESS_DENIED(5)` 拒;`0x400|0x1000` 互斥混传也失败;
13
+ * 4. 非可复制类型的句柄返回 err 50(ERROR_NOT_SUPPORTED),属正常,跳过即可。
14
+ *
15
+ * 纪律:整模块是**可选增强**。koffi 找不到、平台不是 win32、没匹配到句柄、读出来打不开
16
+ * —— 一律返回 `{ok:false, reason}`,由调用方退回「读不到」档。**绝不猜数**。
17
+ */
18
+ import fs from 'node:fs'
19
+ import os from 'node:os'
20
+ import path from 'node:path'
21
+ import process from 'node:process'
22
+ import { createRequire } from 'node:module'
23
+
24
+ export const EXTENDED_HANDLE_CLASS = 64
25
+ export const HANDLE_STRIDE = 40
26
+ export const HANDLE_TABLE_BASE = 16
27
+ export const PID_FIELD_OFFSET = 8
28
+ export const HANDLE_FIELD_OFFSET = 16
29
+ /** 唯一实测可用的 OpenProcess 权限位(见文件头第 3 条)。 */
30
+ export const PROCESS_QUERY_INFORMATION = 0x0040
31
+ export const DUPLICATE_SAME_ACCESS = 0x0002
32
+ export const TH32CS_SNAPPROCESS = 0x00000002
33
+ /** 进程条目:PROCESSENTRY32W 的 x64 布局(dwSize@0,th32ProcessID@8,szExeFile@44)。 */
34
+ export const PROCESS_ENTRY_SIZE = 568
35
+ export const PROCESS_ENTRY_PID_OFFSET = 8
36
+ export const PROCESS_ENTRY_NAME_OFFSET = 44
37
+ export const PROCESS_ENTRY_NAME_BYTES = 520
38
+ /** 单次快照读取上限:cookie 库实测 20–53 KB,给足余量但绝不无界。 */
39
+ export const MAX_SNAPSHOT_BYTES = 32 << 20
40
+ /** 分块读的大小:一次读到底比重复调用系统调用便宜。 */
41
+ const READ_CHUNK_BYTES = 1 << 20
42
+
43
+ /**
44
+ * koffi 的候选位置。它**不在** profile 的依赖树里,只能扫宿主自己的安装位置;
45
+ * 顺序即优先级,`DSH_KOFFI_PATH` 给运维留一个显式入口。
46
+ * @param {{platform?:string, execPath?:string, env?:Record<string,string|undefined>, homedir?:string, exists?:(p:string)=>boolean}} [input]
47
+ * @returns {string[]}
48
+ */
49
+ export function koffiCandidates(input = {}) {
50
+ const {
51
+ platform = process.platform,
52
+ execPath = process.execPath,
53
+ env = process.env,
54
+ homedir = os.homedir(),
55
+ exists = (p) => { try { return fs.existsSync(p) } catch { return false } },
56
+ } = input
57
+ if (platform !== 'win32') return []
58
+ const appDir = path.dirname(execPath)
59
+ const candidates = [
60
+ // Electron 桌面端:原生模块解包在 app.asar.unpacked 下
61
+ path.join(appDir, 'resources', 'app.asar.unpacked', 'dsh', 'node_modules', 'koffi'),
62
+ path.join(appDir, 'resources', 'app.asar.unpacked', 'node_modules', 'koffi'),
63
+ path.join(appDir, 'node_modules', 'koffi'),
64
+ // CLI 全局安装树:宿主包自己的嵌套依赖
65
+ path.join(path.dirname(appDir), 'node_modules', '@deepseek-ai', 'dsh', 'node_modules', 'koffi'),
66
+ path.join(appDir, 'node_modules', '@deepseek-ai', 'dsh', 'node_modules', 'koffi'),
67
+ // 用户级 DSH home(非标准安装/便携版)
68
+ path.join(homedir, '.dsh', 'vendor', 'koffi'),
69
+ ]
70
+ const explicit = String(env.DSH_KOFFI_PATH ?? '').trim()
71
+ const list = explicit === '' ? candidates : [explicit, ...candidates]
72
+ return list.filter((p) => exists(p))
73
+ }
74
+
75
+ /**
76
+ * 解析出可用的 koffi。任何异常都吞掉返回 undefined —— 调用方据此退回「读不到」。
77
+ * @param {string[]} candidates
78
+ * @param {(spec:string)=>any} [requireImpl]
79
+ */
80
+ export function loadKoffi(candidates, requireImpl = createRequire(import.meta.url)) {
81
+ for (const spec of candidates) {
82
+ try {
83
+ const mod = requireImpl(spec)
84
+ // 注意:`func` 是 `koffi.load(...)` 返回的库句柄上的方法,koffi 顶层只有 `load`——
85
+ // 拿 `func` 当顶层形状条件会把可用的 koffi 误判成没有(真机踩到)。
86
+ const shape = (value) => value !== null && typeof value === 'object' && typeof value.load === 'function'
87
+ const koffi = shape(mod) ? mod : shape(mod?.default) ? mod.default : undefined
88
+ if (koffi !== undefined) return koffi
89
+ } catch { /* 下一个候选 */ }
90
+ }
91
+ return undefined
92
+ }
93
+
94
+ /** 绑定需要的 Win32 入口。失败返回 undefined(不抛)。 */
95
+ export function openApi(koffi) {
96
+ if (koffi === undefined) return undefined
97
+ try {
98
+ const k32 = koffi.load('kernel32.dll')
99
+ const ntdll = koffi.load('ntdll.dll')
100
+ return {
101
+ koffi,
102
+ NtQuerySystemInformation: ntdll.func('int32_t NtQuerySystemInformation(uint32_t, void *, uint32_t, uint32_t *)'),
103
+ CreateToolhelp32Snapshot: k32.func('void *CreateToolhelp32Snapshot(uint32_t, uint32_t)'),
104
+ Process32FirstW: k32.func('int32_t Process32FirstW(void *, void *)'),
105
+ Process32NextW: k32.func('int32_t Process32NextW(void *, void *)'),
106
+ OpenProcess: k32.func('void *OpenProcess(uint32_t, int32_t, uint32_t)'),
107
+ GetCurrentProcess: k32.func('void *GetCurrentProcess()'),
108
+ DuplicateHandle: k32.func('int32_t DuplicateHandle(void *, void *, void *, void *, uint32_t, int32_t, uint32_t)'),
109
+ GetFinalPathNameByHandleW: k32.func('uint32_t GetFinalPathNameByHandleW(void *, void *, uint32_t, uint32_t)'),
110
+ SetFilePointerEx: k32.func('int32_t SetFilePointerEx(void *, int64_t, void *, uint32_t)'),
111
+ GetFileSizeEx: k32.func('int32_t GetFileSizeEx(void *, void *)'),
112
+ ReadFile: k32.func('int32_t ReadFile(void *, void *, uint32_t, void *, void *)'),
113
+ CloseHandle: k32.func('int32_t CloseHandle(void *)'),
114
+ }
115
+ } catch {
116
+ return undefined
117
+ }
118
+ }
119
+
120
+ /**
121
+ * 从进程条目里取 PID 与可执行文件名(纯函数,便于脱离 FFI 单测)。
122
+ * @param {Buffer} entry PROCESSENTRY32W 缓冲区
123
+ */
124
+ export function readProcessEntry(entry) {
125
+ if (entry === undefined || entry.length < PROCESS_ENTRY_SIZE) return undefined
126
+ const pid = entry.readUInt32LE(PROCESS_ENTRY_PID_OFFSET)
127
+ const raw = entry.toString('utf16le', PROCESS_ENTRY_NAME_OFFSET, PROCESS_ENTRY_NAME_OFFSET + PROCESS_ENTRY_NAME_BYTES)
128
+ const exe = raw.split('\u0000')[0] ?? ''
129
+ return { pid, exe }
130
+ }
131
+
132
+ /**
133
+ * 取映像基名。**两种分隔符都切**:Win32 给的路带 `\`,而在非 win32 上跑单测时
134
+ * `path.basename` 不认反斜杠,会把整串当一个名字(真机两侧红过)。
135
+ */
136
+ export function imageBaseName(exe) {
137
+ return String(exe ?? '').split(/[\\/]/).filter(Boolean).pop() ?? ''
138
+ }
139
+
140
+ /**
141
+ * 目标进程判定:**同一镜像名**或**父进程**,不写死品牌名。
142
+ *
143
+ * 真机坑:`PROCESSENTRY32W.szExeFile` 只是**映像基名**(`node.exe`、`DeepSeek Harness.exe`),
144
+ * 不是完整路径 —— 拿它去比目录会永远不匹配(集成测试当场拓出来的)。
145
+ * 桌面端主进程/渲染进程/GPU/工具子进程共用同一个镜像名,正好就是我们要找的那批。
146
+ * @param {{pid:number, exe:string}} processEntry
147
+ * @param {{selfPid:number, selfExe:string, ppid?:number}} scope
148
+ */
149
+ export function isTargetProcess(processEntry, scope) {
150
+ const { pid, exe } = processEntry
151
+ if (pid === undefined || pid === scope.selfPid) return false
152
+ if (scope.ppid !== undefined && pid === scope.ppid) return true
153
+ const name = String(exe ?? '')
154
+ if (name === '') return false
155
+ return imageBaseName(name).toLowerCase() === String(scope.selfExe ?? '').toLowerCase()
156
+ }
157
+
158
+ /** 枚举目标 PID(快照失败返回空数组,绝不抛)。 */
159
+ export function targetPids(api, scope = {}) {
160
+ const {
161
+ selfPid = process.pid, ppid = process.ppid,
162
+ selfExe = imageBaseName(process.execPath),
163
+ } = scope
164
+ const found = new Set()
165
+ if (typeof ppid === 'number' && ppid > 0 && ppid !== selfPid) found.add(ppid)
166
+ let snapshot
167
+ try {
168
+ snapshot = api.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
169
+ if (snapshot === null || snapshot === undefined || snapshot === 0n) return [...found]
170
+ const entry = Buffer.alloc(PROCESS_ENTRY_SIZE)
171
+ entry.writeUInt32LE(PROCESS_ENTRY_SIZE, 0)
172
+ let more = api.Process32FirstW(snapshot, entry)
173
+ let guard = 0
174
+ while (more === 1 && guard < 65536) {
175
+ const info = readProcessEntry(entry)
176
+ if (info !== undefined && isTargetProcess(info, { selfPid, ppid, selfExe })) found.add(info.pid)
177
+ more = api.Process32NextW(snapshot, entry)
178
+ guard += 1
179
+ }
180
+ api.CloseHandle(snapshot)
181
+ } catch {
182
+ /* 快照不可用就只靠 ppid,仍然可能借到 */
183
+ }
184
+ return [...found]
185
+ }
186
+
187
+ /**
188
+ * 解析句柄表,取目标进程持有的句柄值(纯函数:给定 Buffer 就能测)。
189
+ * @param {Buffer} table NtQuerySystemInformation 的原始输出
190
+ * @param {Iterable<number>} pids 目标 PID 集合
191
+ * @param {{limit?:number}} [options]
192
+ * @returns {Array<{pid:number, handle:bigint}>}
193
+ */
194
+ export function handleEntriesFor(table, pids, options = {}) {
195
+ const { limit = 2_000_000 } = options
196
+ const wanted = new Set(pids)
197
+ const out = []
198
+ if (table === undefined || table.length < HANDLE_TABLE_BASE + HANDLE_STRIDE) return out
199
+ const total = Number(table.readBigUInt64LE(0))
200
+ const scan = Math.min(total, limit)
201
+ for (let i = 0; i < scan; i++) {
202
+ const base = HANDLE_TABLE_BASE + i * HANDLE_STRIDE
203
+ if (base + HANDLE_STRIDE > table.length) break
204
+ const pid = Number(table.readBigUInt64LE(base + PID_FIELD_OFFSET))
205
+ if (!wanted.has(pid)) continue
206
+ out.push({ pid, handle: table.readBigUInt64LE(base + HANDLE_FIELD_OFFSET) })
207
+ }
208
+ return out
209
+ }
210
+
211
+ /** `\\?\C:\dir\file` 这类 DOS 设备前缀要去掉再比;大小写不敏感。 */
212
+ export function normalizeHandlePath(name) {
213
+ const text = String(name ?? '')
214
+ const stripped = text.startsWith('\\\\?\\') ? text.slice(4) : text
215
+ return stripped.toLowerCase()
216
+ }
217
+
218
+ /** 句柄表查询:容量不足时按返回长度重试。返回 Buffer 或 {error}。 */
219
+ function queryHandleTable(api) {
220
+ const needed = Buffer.alloc(4)
221
+ let size = 1 << 22
222
+ for (let attempt = 0; attempt < 5; attempt++) {
223
+ const table = Buffer.alloc(size)
224
+ const status = api.NtQuerySystemInformation(EXTENDED_HANDLE_CLASS, table, size, needed) >>> 0
225
+ if (status === 0) return table
226
+ // STATUS_INFO_LENGTH_MISMATCH:按系统要求的长度再来一次
227
+ if (status === 0xc0000004) {
228
+ size = Math.max(needed.readUInt32LE(0) + (4 << 20), size * 2)
229
+ continue
230
+ }
231
+ return { error: `ntstatus=0x${status.toString(16)}` }
232
+ }
233
+ return { error: 'handle table too large' }
234
+ }
235
+
236
+ /**
237
+ * 借句柄读出文件字节。成功返回 Buffer,失败返回 `{ok:false, reason}`。
238
+ * 只做读:不写、不改共享模式、不关闭别人的句柄(只关自己 dup 出来的那份)。
239
+ *
240
+ * 预算不是装饰:按基名匹配时目标可能是几十个同名进程 × 上百句柄,每次 dup+取路径都是 FFI 调用。
241
+ * 所以:每个 PID 只 `OpenProcess` 一次(不是每句柄一次)、按 pids 给定的优先级逐个试、
242
+ * 命中即返回,并有时间/次数两道上限。超预算就明说 `scan-budget`,不拿“读不到”伪装成偶然。
243
+ * @param {object} api openApi() 的结果
244
+ * @param {{filePath:string, pids:number[], maxBytes?:number, maxAttempts?:number, budgetMs?:number, now?:()=>number}} input
245
+ */
246
+ export function borrowBytes(api, input) {
247
+ const { filePath, pids } = input
248
+ const maxBytes = input.maxBytes ?? MAX_SNAPSHOT_BYTES
249
+ const maxAttempts = input.maxAttempts ?? 20000
250
+ const budgetMs = input.budgetMs ?? 1200
251
+ const now = input.now ?? Date.now
252
+ if (api === undefined) return { ok: false, reason: 'no-ffi' }
253
+ if (!Array.isArray(pids) || pids.length === 0) return { ok: false, reason: 'no-target-pids' }
254
+ const table = queryHandleTable(api)
255
+ if (!Buffer.isBuffer(table)) return { ok: false, reason: table.error }
256
+ const wanted = normalizeHandlePath(filePath)
257
+ const self = api.GetCurrentProcess()
258
+ const outHandle = Buffer.alloc(8)
259
+ const nameBuf = Buffer.alloc(4096 * 2)
260
+ const sizeBuf = Buffer.alloc(8)
261
+ const readBuf = Buffer.alloc(4)
262
+ const started = now()
263
+ const order = new Map()
264
+ for (const entry of handleEntriesFor(table, pids)) {
265
+ const list = order.get(entry.pid) ?? []
266
+ list.push(entry.handle)
267
+ order.set(entry.pid, list)
268
+ }
269
+ let attempts = 0
270
+ for (const pid of pids) {
271
+ const handles = order.get(pid)
272
+ if (handles === undefined || handles.length === 0) continue
273
+ const processHandle = api.OpenProcess(PROCESS_QUERY_INFORMATION, 0, pid)
274
+ const opened = processHandle !== null && processHandle !== undefined && processHandle !== 0n
275
+ if (!opened) continue
276
+ for (const handle of handles) {
277
+ attempts += 1
278
+ if (attempts > maxAttempts || now() - started > budgetMs) {
279
+ api.CloseHandle(processHandle)
280
+ return { ok: false, reason: 'scan-budget', attempts }
281
+ }
282
+ let copied
283
+ try {
284
+ copied = api.DuplicateHandle(processHandle, handle, self, outHandle, 0, 0, DUPLICATE_SAME_ACCESS)
285
+ } catch {
286
+ copied = 0
287
+ }
288
+ if (copied !== 1) continue
289
+ const duplicate = outHandle.readBigUInt64LE(0)
290
+ const length = api.GetFinalPathNameByHandleW(duplicate, nameBuf, 4096, 0)
291
+ const name = length > 0 ? normalizeHandlePath(nameBuf.toString('utf16le', 0, Number(length) * 2).split('\u0000')[0]) : ''
292
+ if (name !== wanted || name.includes('partitions')) {
293
+ api.CloseHandle(duplicate)
294
+ continue
295
+ }
296
+ api.CloseHandle(processHandle)
297
+ if (api.GetFileSizeEx(duplicate, sizeBuf) !== 1) { api.CloseHandle(duplicate); return { ok: false, reason: 'size-unknown' } }
298
+ const bytes = Number(sizeBuf.readBigUInt64LE(0))
299
+ if (!Number.isInteger(bytes) || bytes <= 0) { api.CloseHandle(duplicate); return { ok: false, reason: 'size-invalid' } }
300
+ if (bytes > maxBytes) { api.CloseHandle(duplicate); return { ok: false, reason: 'too-large' } }
301
+ if (api.SetFilePointerEx(duplicate, 0, null, 0) !== 1) { api.CloseHandle(duplicate); return { ok: false, reason: 'seek-failed' } }
302
+ const chunks = []
303
+ let done = 0
304
+ let broken = false
305
+ const chunk = Buffer.alloc(Math.min(bytes, READ_CHUNK_BYTES))
306
+ while (done < bytes) {
307
+ const want = Math.min(chunk.length, bytes - done)
308
+ readBuf.writeUInt32LE(0, 0)
309
+ const ok = api.ReadFile(duplicate, chunk, want, readBuf, null)
310
+ const got = readBuf.readUInt32LE(0)
311
+ if (ok !== 1 || got === 0) { broken = true; break }
312
+ chunks.push(Buffer.from(chunk.subarray(0, got)))
313
+ done += got
314
+ }
315
+ api.CloseHandle(duplicate)
316
+ if (broken || done !== bytes) return { ok: false, reason: 'read-incomplete' }
317
+ return { ok: true, buffer: Buffer.concat(chunks, bytes), pid, bytes: done, attempts }
318
+ }
319
+ api.CloseHandle(processHandle)
320
+ }
321
+ return { ok: false, reason: 'handle-not-found', attempts }
322
+ }
323
+
324
+ /**
325
+ * 一站式:解析 koffi → 找目标进程 → 借句柄 → 落临时快照。
326
+ * 只读;临时文件在返回前写完,删除交给调用方(`statCookies` 读完再删)。
327
+ * @param {{filePath:string, candidates?:string[], pids?:number[], requireImpl?:Function, now?:()=>number, tmpDir?:string, exists?:(p:string)=>boolean}} [input]
328
+ * @returns {{ok:boolean, snapshotPath?:string, reason?:string, bytes?:number, source:'borrowed-handle'}}
329
+ */
330
+ export function snapshotThroughHandle(input = {}) {
331
+ const {
332
+ filePath,
333
+ requireImpl,
334
+ now = () => Date.now(),
335
+ tmpDir = os.tmpdir(),
336
+ } = input
337
+ const candidates = input.candidates ?? koffiCandidates(input)
338
+ if (candidates.length === 0) return { ok: false, reason: 'koffi-not-found', source: 'borrowed-handle' }
339
+ const koffi = loadKoffi(candidates, requireImpl)
340
+ if (koffi === undefined) return { ok: false, reason: 'koffi-unsupported', source: 'borrowed-handle' }
341
+ const api = openApi(koffi)
342
+ if (api === undefined) return { ok: false, reason: 'ffi-bindings-failed', source: 'borrowed-handle' }
343
+ // 显式 pids 优先(测试与定向排查用);没给才去扫进程快照,并把父进程排第一位(真实场景里就是宿主本体)
344
+ const pids = Array.isArray(input.pids) && input.pids.length > 0 ? input.pids : prioritizeParent(targetPids(api), process.ppid)
345
+ const borrowed = borrowBytes(api, { filePath, pids, now })
346
+ if (borrowed.ok !== true) return { ok: false, reason: borrowed.reason ?? 'borrow-failed', source: 'borrowed-handle' }
347
+ const snapshotPath = path.join(tmpDir, `dcc-jar-${String(now())}.sqlite`)
348
+ try {
349
+ fs.writeFileSync(snapshotPath, borrowed.buffer)
350
+ } catch (e) {
351
+ return { ok: false, reason: `snapshot-write-${String(e && e.code ? e.code : e.message)}`, source: 'borrowed-handle' }
352
+ }
353
+ return { ok: true, snapshotPath, bytes: borrowed.bytes, source: 'borrowed-handle' }
354
+ }
355
+
356
+ /** 父进程优先:真实场景里 cookie 库就被宿主自己的进程持着,先试它能少扫很多。 */
357
+ export function prioritizePids(pids, first) {
358
+ const list = [...new Set(pids.filter((pid) => typeof pid === 'number' && pid > 0))]
359
+ if (typeof first !== 'number' || first <= 0) return list
360
+ return [first, ...list.filter((pid) => pid !== first)]
361
+ }
362
+
363
+ function prioritizeParent(pids, parentPid) {
364
+ return prioritizePids(pids, parentPid)
365
+ }