dsh-cookie-cleaner 0.2.0 → 0.2.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.
@@ -0,0 +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
+ }
@@ -154,6 +154,14 @@ export const PATCH_TEXT = Object.freeze({
154
154
  fixed: t('已写入:{changed}', 'written: {changed}', '書き込み完了:{changed}', '기록됨: {changed}', 'écrit : {changed}', 'geschrieben: {changed}', 'scritto: {changed}', 'записано: {changed}', 'escrito: {changed}'),
155
155
  auditLine: t('上次修复:{at}(修复前 {before} → 现在 {after})', 'last fix: {at} (was {before} → now {after})', '前回修復:{at}(修復前 {before} → 現在 {after})', '마지막 복구: {at}(복구 전 {before} → 현재 {after})', 'dernière réparation : {at} (de {before} à {after})', 'letzte Korrektur: {at} (vorher {before} → jetzt {after})', 'ultima correzione: {at} (da {before} a {after})', 'последнее исправление: {at} (было {before} → стало {after})', 'última reparación: {at} (de {before} a {after})'),
156
156
  auditLineNew: t('上次修复:{at}(此前无覆盖行 → 现在 {after})', 'last fix: {at} (there was no override row before → now {after})', '前回修復:{at}(それまでカバー行無し → 現在 {after})', '마지막 복구: {at}(그전엔 덮어쓰기 행 없음 → 현재 {after})', 'dernière réparation : {at} (aucune ligne de couverture avant → maintenant {after})', 'letzte Korrektur: {at} (vorher keine Override-Zeile → jetzt {after})', 'ultima correzione: {at} (prima nessuna riga di override → ora {after})', 'последнее исправление: {at} (раньше строки переопределения не было → теперь {after})', 'última reparación: {at} (antes no había fila de anulación → ahora {after})'),
157
+ // 实时读数(读得到才给):条数、折算的请求头字节、占用百分比、距 431 阈值的余量。
158
+ // 百分比是估算(value 列存的是密文,明文长度按上游报告一致值),文案里用「约」不假装精确。
159
+ cookieLive: t('cookie 库实时读数:{count} 条 dsh-auth-*(共 {total} 条),请求头约 {bytes} B / 上限 {max} B({pct}%),距 431 阈值还剩约 {remaining} 条', 'live cookie reading: {count} dsh-auth-* rows ({total} total), request header ~{bytes} B of {max} B ({pct}%), roughly {remaining} more rows before 431', 'cookie ライブ读数:dsh-auth-* {count} 件(合計 {total} 件)、リクエストヘッダ約 {bytes} B / 上限 {max} B({pct}%)、431 まであと約 {remaining} 件', 'cookie 실시간 수치: dsh-auth-* {count}건(총 {total}건), 요청 헤더 약 {bytes}B / 상한 {max}B({pct}%), 431까지 약 {remaining}건 남음', 'lecture en direct des cookies : {count} entrées dsh-auth-* ({total} au total), en-tête ~{bytes} B sur {max} B ({pct} %), environ {remaining} entrées avant 431', 'Live-Ableseung der Cookies: {count} dsh-auth-* Einträge ({total} gesamt), Header ~{bytes} B von {max} B ({pct} %), noch ~{remaining} Einträge bis 431', 'lettura live dei cookie: {count} voci dsh-auth-* ({total} totali), header ~{bytes} B su {max} B ({pct}%), ancora ~{remaining} voci prima di 431', 'текущее чтение cookie: {count} записей dsh-auth-* (всего {total}), заголовок ~{bytes} Б из {max} Б ({pct}%), до 431 остаётся ~{remaining} записей', 'lectura en vivo de cookies: {count} filas dsh-auth-* ({total} en total), cabecera ~{bytes} B de {max} B ({pct} %), quedan ~{remaining} filas para 431'),
160
+ // 借宿主已打开的句柄拿到的快照:数字是真的,但不是实时。说成实时就是谎报。
161
+ cookieLiveSnapshot: t('cookie 库快照读数(借宿主句柄,非实时):{count} 条 dsh-auth-*(共 {total} 条),请求头约 {bytes} B / 上限 {max} B({pct}%),距 431 阈值还剩约 {remaining} 条', 'cookie reading via a borrowed host handle (not live): {count} dsh-auth-* rows ({total} total), request header ~{bytes} B of {max} B ({pct}%), roughly {remaining} more rows before 431', 'スナップショット读数(宿主のハンドル借用、非实时):dsh-auth-* {count} 件(合計 {total} 件)、ヘッダ約 {bytes} B / 上限 {max} B({pct}%)、431 まであと約 {remaining} 件', '스냅샷 수치(호스트 핸들 빌림, 비실시간): dsh-auth-* {count}건(총 {total}건), 헤더 약 {bytes}B / 상한 {max}B({pct}%), 431까지 약 {remaining}건', 'lecture par instantané (poignée prêtée à l\'hôte, non temps réel) : {count} entrées dsh-auth-* ({total} au total), en-tête ~{bytes} B sur {max} B ({pct} %), ~{remaining} entrées avant 431', 'Schnappschuss-Ableseung (geliehener Host-Handle, nicht live): {count} dsh-auth-* Einträge ({total} gesamt), Header ~{bytes} B von {max} B ({pct} %), noch ~{remaining} Einträge bis 431', 'lettura da istantanea (maniglia host prestata, non live): {count} voci dsh-auth-* ({total} totali), header ~{bytes} B su {max} B ({pct}%), ancora ~{remaining} voci prima di 431', 'снимок (одалживаемый дескриптор хоста, не в реальном времени): {count} записей dsh-auth-* (всего {total}), заголовок ~{bytes} Б из {max} Б ({pct}%), до 431 остаётся ~{remaining} записей', 'lectura por instantánea (asa del host prestada, no en vivo): {count} filas dsh-auth-* ({total} en total), cabecera ~{bytes} B de {max} B ({pct} %), quedan ~{remaining} filas para 431'),
162
+ // 读不到的三种原因必须分开:把“路径没找到/权限不够”说成“被 Chromium 占”会误引导。
163
+ cookieMissing: t('cookie 库现状:没在预期位置找到库(安装方式可能不同),可用 --db=<完整路径> 指定', 'cookie store: no database found at the expected locations (the install may differ); pass --db=<full path>', 'cookie 庫:期待する場所に見つかりません(インストール形態の違いかも)。--db=<完全パス> で指定可', 'cookie 저장소: 예상 위치에서 파일을 찾지 못함(설치 형태 차이 가능) → --db=<전체 경로> 로 지정', 'base de cookies : aucune base aux emplacements attendus (installation différente ?) ; utilisez --db=<chemin complet>', 'Cookie-Speicher: keine Datenbank an den erwarteten Orten (ggf. andere Installation) — --db=<vollständiger Pfad> verwenden', 'archivio cookie: nessun database nei percorsi attesi (installazione diversa?) ; usare --db=<percorso completo>', 'хранилище cookie: база не найдена в ожидаемых местах (возможно, другая установка) — укажите --db=<полный путь>', 'almacén de cookies: no se encontró la base en las rutas esperadas (instalación distinta) ; use --db=<ruta completa>'),
164
+ cookiePermission: t('cookie 库现状:当前用户读不了这个文件(权限/属主问题),不是客户端占用', 'cookie store: the current user cannot read this file (permissions/owner), the client is not holding it', 'cookie 庫:現ユーザーはこのファイルを読めません(権限/所有者の問題)で、クライアント占有ではない', 'cookie 저장소: 현재 사용자 권한으로 읽을 수 없음(권한/소유자 문제), 클라이언트 점유 아님)', 'base de cookies : l\'utilisateur actuel ne peut pas lire ce fichier (permissions/propriétaire), ce n\'est pas le client qui le retient', 'Cookie-Speicher: dieser Benutzer kann die Datei nicht lesen (Rechte/Besitzer), nicht der Client hält sie', 'archivio cookie: l\'utente corrente non può leggere il file (permessi/proprietario), non lo trattiene il client', 'хранилище cookie: текущий пользователь не может прочитать файл (права/владелец), это не блокировка клиентом', 'almacén de cookies: el usuario actual no puede leer este archivo (permisos/propietario), no lo retiene el cliente'),
157
165
  cookieBusy: t('cookie 库现状:客户端运行期读不到(被 Chromium 独占),条数需关闭客户端后跑 CLI', 'cookie store: unreadable while the client runs (Chromium holds it exclusively); count needs the CLI with the client closed', 'cookie 庫の現状:クライアント起動中は読めません(Chromium が排他保持)、件数は終了後に CLI で', 'cookie 저장소: 클라이언트 실행 중 읽기 불가(Chromium 배타 점유), 수는 종료 후 CLI로', 'base de cookies : illisible pendant que le client tourne (Chromium la retient) ; le nombre exige la CLI client fermé', 'Cookie-Speicher: während des Client-Laufs nicht lesbar (Chromium hält ihn exklusiv); die Zahl braucht die CLI bei geschlossenem Client', 'archivio cookie: illeggibile mentre il client è attivo (Chromium lo trattiene); il conteggio richiede la CLI a client chiuso', 'хранилище cookie: недоступно для чтения при запущенном клиенте (Chromium держит эксклюзивно); число требует CLI при закрытом клиенте', 'almacén de cookies: ilegible mientras el cliente corre (Chromium lo retiene); el conteo requiere la CLI con el cliente cerrado'),
158
166
  noop: t('无需写入(已在目标档)', 'nothing to write (already on target)', '書き込み不要(目標達成済み)', '기록 불필요(이미 목표)', 'rien à écrire (déjà à la cible)', 'nichts zu schreiben (bereits am Ziel)', 'nulla da scrivere (già all\'obiettivo)', 'нечего писать (уже в цели)', 'nada que escribir (ya en el objetivo)'),
159
167
  blocked: t('判定为不可动作,未写入({codes})', 'judged not actionable; nothing written ({codes})', '動作不可と判定、書き込みなし({codes})', '조치 불가로 판정, 기록 없음({codes})', 'jugé non exécutable ; rien écrit ({codes})', 'als nicht ausführbar eingestuft; nichts geschrieben ({codes})', 'giudicato non eseguibile; nulla scritto ({codes})', 'признано невыполнимым; ничего не записано ({codes})', 'juzgado no accionable; nada escrito ({codes})'),
@@ -163,16 +171,11 @@ export const PATCH_TEXT = Object.freeze({
163
171
  planFor: t('把下面这段手工放进 {file}(若根是 flow `[]`,要先删掉那一行):', 'paste this block into {file} (if the root is a flow `[]`, delete that line first):', '以下のブロックを {file} に手動で置いてください(根が flow `[]` ならその行を削除):', '아래 블록을 {file}에 직접 넣으세요(루트가 flow `[]`면 그 줄을 먼저 삭제):', 'collez ce bloc dans {file} (si la racine est un `[]` en flux, supprimez d\'abord cette ligne) :', 'fügen Sie diesen Block in {file} ein (falls die Wurzel ein Fluss-`[]` ist, erst diese Zeile löschen):', 'incolla questo blocco in {file} (se la radice è un `[]` in forma flow, prima cancella quella riga):', 'вставьте этот блок в {file} (если корень — поток `[]`, сначала удалите эту строку):', 'pega este bloque en {file} (si la raíz es un `[]` en flujo, borra primero esa línea):'),
164
172
  // 表达式被抄成字面量(P9)不再进体检结论,只在处方里提一句;这里给的是“拿到跟随形态”的动作。
165
173
  exprFrozenHint: t('要拿到跟随形态的粘贴块:把本插件设置里的 guardMode 切到 expression,再跑一次 patch plan', 'to get a paste block in the following form: set guardMode to expression in this plugin\'s settings, then run patch plan again', '追随形态の貼り付け块が欲しい場合:本プラグイン設定の guardMode を expression に切り、patch plan を再実行', '추종 형태 블록을 받으려면: 이 플러그인 설정에서 guardMode를 expression으로 바꾸고 patch plan을 다시 실행', 'pour obtenir un bloc au forme suiveuse : passez guardMode à expression dans les réglages de ce plugin, puis relancez patch plan', 'für ein Block in Folgsamkeitsform: guardMode in den Einstellungen dieses Plugins auf expression setzen und patch plan erneut ausführen', 'per ottenere un blocco in forma seguace: imposta guardMode su expression nelle impostazioni di questo plugin, poi riesegui patch plan', 'чтобы получить блок в следящей форме: переведите guardMode в expression в настройках этого плагина и снова выполните patch plan', 'para obtener un bloque en forma de seguimiento: pon guardMode en expression en los ajustes de este plugin y vuelve a ejecutar patch plan'),
166
- // 端口动作的结果句式。三档热生效状态由探针给出,无据就明说无据,不拿配置猜。
167
- portApplied: t('已写入端口表达式:port = !!js {expr}', 'wrote the port expression: port = !!js {expr}', 'ポート式を書き込みました:port = !!js {expr}', '포트 표현식을 기록함: port = !!js {expr}', 'expression de port écrite : port = !!js {expr}', 'Port-Ausdruck geschrieben: port = !!js {expr}', 'espressione della porta scritta: port = !!js {expr}', 'выражение порта записано: port = !!js {expr}', 'expresión de puerto escrita: port = !!js {expr}'),
168
- portHot: t('新端口已在监听(本次已热生效)', 'the new port is already listening (applied live)', '新しいポートが既に受信しています(今回ホット反映)', '새 포트가 이미 수신 중(이번에 열반영)', 'le nouveau port écoute déjà (appliqué à chaud)', 'der neue Port lauscht bereits (heiß angewendet)', 'la nuova porta è già in ascolto (applicata a caldo)', 'новый порт уже слушает (применено сразу)', 'el nuevo puerto ya está escuchando (aplicado en caliente)'),
169
- portRestart: t('配置已写但监听仍在旧端口 → 下次启动生效', 'config written, the live listener is still on the old port → takes effect at next launch', '設定は書き込みましたがまだ旧ポートで受信しています → 次回起動時に有効', '설정은 기록됐지만 아직 옛 포트에서 수신 중 → 다음 시작 때 적용', 'config écrite, l\'écoute est encore sur l\'ancien port → effet au prochain lancement', 'Konfiguration geschrieben, das Lauschen bleibt am alten Port → wirksam beim nächsten Start', 'config scritta, l\'ascolto resta sulla porta vecchia → effettivo al prossimo avvio', 'конфигурация записана, но слушает старый порт → вступит в силу при следующем запуске', 'config escrita, pero sigue escuchando el puerto viejo → efectivo en el próximo arranque'),
170
- portUnknown: t('是否热生效无据(探针未能定论),新值会在下次启动生效', 'whether it applied live is undetermined (the probe was inconclusive); the new value takes effect at next launch', 'ホット反映されたかは判定不能(プローブが結論できず)。新値は次回起動時に有効', '열반영 여부는 판단 불가(프로브가 결론 못 냄), 새 값은 다음 시작 때 적용', 'l\'effet à chaud est indécidable (sonde non concluante) ; la nouvelle valeur s\'applique au prochain lancement', 'ob heiß angewendet ist unklar (Sonde nicht eindeutig); der neue Wert gilt beim nächsten Start', 'se sia applicata a caldo è indecidibile (sonda inconcludente); il nuovo valore vale al prossimo avvio', 'применено ли горячо — не определено (зонд не дал ответа); новое значение вступит в силу при следующем запуске', 'si se aplicó en caliente es indecidible (la sonda no fue concluyente); el nuevo valor rige en el próximo arranque'),
171
- portBusy: t('目标端口 {port} 在本机已被占用(探针看到有人监听),未写入——换一个端口再试', 'the target port {port} is already occupied on this host (the probe saw a listener), nothing was written — pick another port', '対象ポート {port} はこのマシンで使用中(プローブが受信者を検知)。書き込みません — 別のポートで再試行', '대상 포트 {port}가 이 기기에서 사용 중(프로브가 수신자 감지) → 기록하지 않음, 다른 포트으로 다시 시도', 'le port cible {port} est déjà occupé sur cette machine (la sonde a vu un écouteur), rien n\'a été écrit — choisissez un autre port', 'der Ziel-Port {port} ist auf diesem Rechner belegt (Sonde sah einen Lauscher), nichts geschrieben — anderen Port wählen', 'la porta di destinazione {port} è già occupata su questa macchina (la sonda ha visto un ascoltatore), nulla scritto — scegli un\'altra porta', 'целевой порт {port} на этой машине уже занят (зонд увидел слушателя), ничего не записано — выберите другой порт', 'el puerto de destino {port} ya está ocupado en esta máquina (la sonda vio un oyente), no se escribió nada — elija otro puerto'),
172
- portInvalid: t('端口必须是 {minimum}-{maximum} 的整数,收到 {got};本插件不替你定默认端口', 'the port must be an integer {minimum}-{maximum}, got {got}; this plugin does not pick a default port for you', 'ポートは {minimum}-{maximum} の整数が必要、受信 {got};本プラグインは既定ポートを決めません', '포트는 {minimum}-{maximum} 정수여 함, 입력 {got}; 이 플러그인은 기본 포트를 정하지 않음', 'le port doit être un entier {minimum}-{maximum}, reçu {got} ; ce plugin ne choisit pas de port par défaut', 'der Port muss eine Ganzzahl {minimum}-{maximum} sein, erhalten {got}; dieses Plugin setzt keinen Standardport für Sie', 'la porta deve essere un intero {minimum}-{maximum}, ricevuto {got}; questo plugin non sceglie una porta predefinita', 'порт должен быть целым {minimum}-{maximum}, получено {got}; этот плагин не выбирает порт по умолчанию', 'el puerto debe ser un entero {minimum}-{maximum}, se recibió {got}; este plugin no elige un puerto predeterminado'),
173
- // 端口热生效会立刻把旧端口页面踢下线:必须在输入框旁常驻提醒,否则用户会被自己锁在门外。
174
- portSwitchWarn: t('⚠ 端口改完立即生效:旧端口的当前页面会失联,必须马上用新端口地址重新访问(或重启客户端),server 与 browser 的端口号要同步改', '⚠ the port takes effect immediately: this page on the old port will drop, so re-open it at the new port right away (or restart the client) — keep the server and browser ports in sync', '⚠ ポートは即座に有効化:旧ポートの現ページは切断されます。直ちに新ポート地址で開き直すかクライアントを再起動してください(server と browser のポートを揃える)', '⚠ 포트가 즉시 반영됨: 옛 포트의 현재 페이지가 끊깁니다. 새 포트 주소로 즉시 다시 열거나 클라이언트를 재시작하세요(server와 browser 포트 동기화)', '⚠ le port prend effet immédiatement : cette page sur l\'ancien port se déconnecte, rouvrez-la tout de suite sur le nouveau port (ou redémarrez le client) — alignez les ports server et browser', '⚠ der Port wirkt sofort: diese Seite am alten Port trennt sich — öffnen Sie sie sogleich über den neuen Port (oder starten Sie den Client neu), server- und Browser-Port müssen übereinstimmen', '⚠ la porta ha effetto immediato: questa pagina sulla porta vecchia si disconnette; riapritela subito al nuovo port (o riavvia il client) — allinea le porte di server e browser', '⚠ порт применяется сразу: эта страница на старом порту отвалится — немедленно откройте по новому порту (или перезапустите клиент); порты server и browser должны совпадать', '⚠ el puerto surte efecto de inmediato: esta página en el puerto viejo se desconecta; ábrala de nuevo en el puerto nuevo (o reinicie el cliente) — alinee los puertos de server y navegador'),
175
- webserverNote: t('webserver 行不被「修复」自动改写:端口属启动行为面,要改请用面板的「应用端口」(只写表达式形式,`--port` 仍优先)', 'the webserver row is never auto-written by Fix: the port is a launch-behaviour decision - use the panel\'s Apply port instead (written as an expression, so `--port` still wins)', 'webserver 行は「修復」で自動改写されません:ポートは起動挙動の話、パネルの「ポート適用」を使ってください(表达式形式のみ、`--port` が優先されます)', 'webserver 행은 "복구"로 자동 기록되지 않음: 포트는 시작 동작 판단이니 패널의 "포트 적용"을 쓰세요(표현식 형태만 기록, `--port` 우선)', 'la ligne webserver n\'est jamais écrite par Réparer : le port relève du lancement, utilisez « Appliquer le port » du panneau (écrit en expression, `--port` gagne toujours)', 'die webserver-Zeile wird durch Fixen nie automatisch geschrieben: der Port ist Startverhalten, nutzen Sie „Port anwenden" im Panel (als Ausdruck geschrieben, `--port` bleibt oben)', 'la riga webserver non è mai scritta da Correggi: la porta riguarda l\'avvio, usa «Applica porta» nel pannello (scritta come espressione, `--port` continua a vincere)', 'строка webserver не пишется кнопкой «Исправить»: порт — вопрос запуска, используйте «Применить порт» в панели (пишется выражением, `--port` по-прежнему важнее)', 'la fila webserver nunca la escribe Reparar: el puerto concierne al arranque, usa «Aplicar puerto» en el panel (se escribe como expresión, `--port` sigue ganando)'),
174
+ // 真正有效的那一项:修复按钮要写入的目标寿命。面板与命令面共用这一句。
175
+ targetDaysLine: t('目标 cookie 绝对寿命:{days} 天(「修复」就写这个值;它是防 431 真正有效的一项)', 'target cookie lifetime: {days} day(s) — what Fix writes; this is the part that actually prevents 431', '目標 cookie 絶対寿命:{days} 日(「修復」が書く値。431 防止に本当に効くのはここ)', '목표 cookie 절대 수명: {days}일 — "복구"가 쓰는 값이며, 431 방지에 실제로 효력이 있는 항목', 'durée cible des cookies : {days} jour(s) — valeur écrite par Réparer ; c\'est ce qui empêche vraiment 431', 'Ziel-Lebensdauer der Cookies: {days} Tag(e) — der von Fix geschriebene Wert; das ist der Teil, der 431 wirklich verhindert', 'durata target dei cookie: {days} giorno/i — il valore scritto da Correggi; è la cosa che evita davvero 431', 'целевой срок cookie: {days} дн. — значение, которое пишет «Исправить»; именно это реально предотвращает 431', 'vida útil objetivo de las cookies: {days} día(s) — el valor que escribe Reparar; es la parte que de verdad evita 431'),
176
+ // 端口不再在本插件职责内(既不写也不提供子命令),但 P8 仍作为只读判定报出来:
177
+ // 这一句负责说清“我们看到但不动”,不让用户以为面板会处它。
178
+ webserverNote: t('webserver 行只参与只读判定:本插件只改 cookie 有效期,端口属启动行为面,不由本工具改写', 'the webserver row is read-only here: this plugin only changes the cookie lifetime - the port is a launch-behaviour decision we do not rewrite', 'webserver 行は読み取り専用判定のみ:本プラグインは cookie 有効期だけ変更し、ポートは起動挙動の話で本ツールの対象外', 'webserver 행은 읽기 전용 판정만: 이 플러그인은 cookie 유효기간만 변경하며 포트는 시작 동작 판단이라 본 도구가 바꾸지 않음', 'la ligne webserver est en lecture seule ici : ce plugin ne change que la durée de vie des cookies - le port relève du lancement, nous ne le réécrivons pas', 'die webserver-Zeile wird hier nur lesend geprüft: dieses Plugin ändert nur die Cookie-Lebensdauer — der Port ist Startverhalten, das wir nicht umschreiben', 'la riga webserver qui è solo in lettura: questo plugin cambia soltanto la durata dei cookie - la porta riguarda l\'avvio e non la riscriviamo', 'строка webserver здесь только для чтения: этот плагин меняет лишь срок cookie — порт относится к запуску и нами не переписывается', 'la fila webserver aquí es solo lectura: este plugin solo cambia la vida útil de las cookies - el puerto concierne al arranque y no lo reescribimos'),
176
179
  nextFix: t('下一步:面板点「修复」,或执行 /cookie-cleaner patch fix', 'next: press Fix in the panel, or run /cookie-cleaner patch fix', '次の一手:パネルの「修復」を押すか /cookie-cleaner patch fix を実行', '다음: 패널에서 "복구"를 누르거나 /cookie-cleaner patch fix 실행', 'étape suivante : « Réparer » dans le panneau, ou /cookie-cleaner patch fix', 'nächster Schritt: im Panel „Fixen“, oder /cookie-cleaner patch fix', 'passo successivo: «Correggi» nel pannello, oppure /cookie-cleaner patch fix', 'следующий шаг: «Исправить» в панели или /cookie-cleaner patch fix', 'siguiente paso: «Reparar» en el panel, o /cookie-cleaner patch fix'),
177
180
  noService: t('本机宿主没有 config-editor 服务(老线或未装配),体检无法在线进行', 'this host has no config-editor service (older line or not assembled), so an online check is impossible', 'この宿主に config-editor サービスが無いため(旧ライン/未装配)、オンライン検査は不可', '이 호스트에 config-editor 서비스가 없음(구 라인/미조립) → 온라인 점검 불가', 'cet hôte n\'a pas de service config-editor (ancienne ligne ou non assemblé), contrôle en ligne impossible', 'dieser Host hat keinen config-editor-Dienst (ältere Zeile oder nicht montiert), Online-Prüfung unmöglich', 'questo host non ha il servizio config-editor (linea vecchia o non assemblato), controllo online impossibile', 'у этого хоста нет сервиса config-editor (старая линия или не собран), онлайн-проверка невозможна', 'este host no tiene el servicio config-editor (línea antigua o no ensamblado), control en línea imposible'),
178
181
  missingProfile: t('该 profile 不存在(目录里没有 cordis.patch.yml 且上级目录也不在)——无据可判,不是配置有问题', 'that profile does not exist (no cordis.patch.yml and its parent directory is missing) — nothing to judge, not a config defect', 'その profile は存在しません(cordis.patch.yml 無く、親ディレクトリも無い)——判定根拠無し、設定不備ではない', '해당 프로필이 존재하지 않습니다(cordis.patch.yml 없음, 상위 디렉터리도 없음) — 판단 근거 없음, 설정 결함이 아님', 'ce profil n\'existe pas (pas de cordis.patch.yml et le dossier parent manque) — rien à juger, pas un défaut de config', 'dieses Profil existiert nicht (kein cordis.patch.yml, auch das Elternverzeichnis fehlt) — keine Grundlage, kein Konfigurationsfehler', 'quel profilo non esiste (nessun cordis.patch.yml e manca la cartella superiore) — nulla da giudicare, non un difetto di config', 'этот профиль не существует (нет cordis.patch.yml и отсутствует родительский каталог) — нечего судить, это не дефект конфигурации', 'ese perfil no existe (no hay cordis.patch.yml y falta el directorio padre) — nada que juzgar, no es un defecto de configuración'),
@@ -13,10 +13,9 @@
13
13
  * 3. 写后 HMR 会热应用,无需重启;但必须回读 effective 才算「修好了」。
14
14
  */
15
15
  import fs from 'node:fs'
16
- import net from 'node:net'
17
16
  import os from 'node:os'
18
17
  import path from 'node:path'
19
- import { MANAGED_ROWS, PORT_WRITE, aggregateAll, assessRow, isValidPort, nextConfigFor, nextPortConfig } from './patch-model.js'
18
+ import { MANAGED_ROWS, aggregateAll, assessRow, nextConfigFor } from './patch-model.js'
20
19
  import { findOverrideRow, parsePatchText, readPatchFile } from './patch-read.js'
21
20
 
22
21
  /** 嵌套事务错误:热重载期间的正常现象,不是配置问题。 */
@@ -29,29 +28,6 @@ export function dshHome(env = process.env, homedir = os.homedir()) {
29
28
  return explicit !== '' ? explicit : path.join(homedir, '.dsh')
30
29
  }
31
30
 
32
- /**
33
- * 端口占用探针。**只探不占**:用 `connect` 看有人应答就算在用(而不是 bind 一个测试监听
34
- * 去抢端口)。目的是把“与你代理/科学上网工具常用端口撞车”这句话变成数据而不是猜测。
35
- * @returns {'busy'|'free'|'unknown'}
36
- */
37
- export function probePort(port, host = '127.0.0.1', timeoutMs = 700) {
38
- return new Promise((resolve) => {
39
- if (!isValidPort(port)) return resolve('unknown')
40
- let settled = false
41
- const done = (value) => { if (!settled) { settled = true; resolve(value) } }
42
- const socket = net.connect({ host, port })
43
- const timer = setTimeout(() => { socket.destroy(); done('free') }, timeoutMs)
44
- socket.once('connect', () => { clearTimeout(timer); socket.destroy(); done('busy') })
45
- // 拒连/网络不可达 = 没人听;其余(权限、沙箱限制等)是无据,不假装知道
46
- socket.once('error', (e) => {
47
- clearTimeout(timer)
48
- const code = String(e && e.code)
49
- done(code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'ECONNRESET' ? 'free' : 'unknown')
50
- })
51
- socket.once('timeout', () => { socket.destroy(); done('free') })
52
- })
53
- }
54
-
55
31
  /**
56
32
  * 快照的 profile 身份。**必须按 profile 隔离**:
57
33
  * 真机串台过一次——在隔离格跑的那次 fix 把快照留在全局单文件里,
@@ -125,7 +101,6 @@ export function createPatchGuard(deps) {
125
101
  homeDir = dshHome(env),
126
102
  wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
127
103
  now = () => Date.now(),
128
- probe = (port) => probePort(port),
129
104
  } = deps
130
105
  /** 可覆盖的目标档位由调用方(命令/路由)每次传入,避免守卫里存状态。 */
131
106
  const state = { homeDir }
@@ -183,14 +158,8 @@ export function createPatchGuard(deps) {
183
158
  beforeDays: connSnap.config?.cookieMaxAgeDays,
184
159
  targetDays: connSnap.targetDays,
185
160
  }
186
- // 端口同理:面板重开也该看得“上次把端口改成了什么、现在听的是哪个”,不能只在点完那一瞬存在。
187
- const portSnap = snap?.rows?.webserver
188
- const lastPort = portSnap === undefined ? undefined : {
189
- at: portSnap.generatedAt ?? null,
190
- before: portSnap.config?.port,
191
- port: portSnap.port,
192
- }
193
- return { ...aggregateAll(rows), documentPath, rows, lastFix, lastPort, checkedAt: new Date(now()).toISOString() }
161
+ // 端口留痕已随端口写入能力一并删除(本插件不写端口,快照里不再开 webserver 行)。
162
+ return { ...aggregateAll(rows), documentPath, rows, lastFix, checkedAt: new Date(now()).toISOString() }
194
163
  }
195
164
 
196
165
  /** 只给用户看的粘贴块(webserver 行、以及 CLI 侧无法写时的处方)。 */
@@ -288,62 +257,6 @@ export function createPatchGuard(deps) {
288
257
  return { kind: applied ? 'fixed' : 'unverified', changed, before, beforeValue: before?.cookieMaxAgeDays, effective, applied, retried: written.retried === true, snapshotFile: snapFile(), snapshotAt: new Date(now()).toISOString(), result: fresh }
289
258
  }
290
259
 
291
- /**
292
- * 应用端口:只改 webserver 行的 `port`,且**永远写成表达式**(带数字字面量就是把 P8 自己造出来)。
293
- * 不并进「修复」:端口属启动行为面,必须用户显式点。目标值不存默认:非法/未给就拒。
294
- * 写前用探针看目标端口在本机是不是已经被占(与代理工具撞车就是这个场景),占用就不写;
295
- * 写后“运行中听到的是哪个端口”也用探针回答,不拿配置猜热生效。
296
- */
297
- async function applyPort(options = {}) {
298
- const port = Number(options.port)
299
- if (!isValidPort(port)) return { kind: 'invalid-port', got: options.port, minimum: PORT_WRITE.minimum, maximum: PORT_WRITE.maximum }
300
- const result = check(options)
301
- const row = result.rows.find((item) => item.rowId === PORT_WRITE.rowId)
302
- if (row === undefined) return { kind: 'blocked', reason: 'no-webserver-row', result }
303
- if (row.blocked === true) return { kind: 'blocked', codes: row.findings.map((f) => f.code), level: row.level, result }
304
- const ce = getEditor()
305
- const entry = ce.entries().find((item) => item.options.id === PORT_WRITE.rowId)
306
- if (entry === undefined) return { kind: 'blocked', codes: ['P10'], result }
307
-
308
- const configuration = (ce.configuration() ?? []).find((item) => item.entry.options.id === PORT_WRITE.rowId)
309
- const { next, changed, expr } = nextPortConfig({ current: entry.options.config ?? {}, inherited: configuration?.inherited ?? {}, port })
310
- if (changed.length === 0) return { kind: 'noop', port, expr, result }
311
-
312
- const state = await probe(port)
313
- if (state === 'busy') return { kind: 'port-busy', port, expr, probe: state, result }
314
-
315
- const before = plain(entry.options.config ?? {})
316
- const beforePort = typeof before?.[PORT_WRITE.key] === 'number' ? before[PORT_WRITE.key] : undefined
317
- const written = await attemptEdit(entry, next)
318
- if (!written.ok) return { kind: 'failed', message: written.message, nested: written.nested === true, result }
319
-
320
- try {
321
- keepSnapshotRow(snapFile(), PORT_WRITE.rowId, { name: PORT_WRITE.name, profile: snapshotKey(ce.documentPath ?? ''), config: before, at: now(), generatedAt: new Date(now()).toISOString(), port }, fsModule)
322
- } catch { /* 同上:快照失败不谎报写入失败 */ }
323
-
324
- const after = ce.entries().find((item) => item.options.id === PORT_WRITE.rowId)
325
- const live = after?.options?.config?.[PORT_WRITE.key]
326
- // 热生效与否看监听,不看配置:新端口有人听 = 已切;只有旧端口有人听 = 下次启动生效。
327
- const nowListening = await probe(port)
328
- const oldListening = beforePort === undefined ? 'unknown' : await probe(beforePort)
329
- const hotApplied = nowListening === 'busy' ? true : oldListening === 'busy' ? false : undefined
330
- return {
331
- kind: 'port-applied',
332
- port,
333
- expr,
334
- changed,
335
- before,
336
- beforePort,
337
- live,
338
- hotApplied,
339
- probeState: state,
340
- retried: written.retried === true,
341
- snapshotFile: snapFile(),
342
- snapshotAt: new Date(now()).toISOString(),
343
- result: check(options),
344
- }
345
- }
346
-
347
260
  /** 回到写之前的配置(快照按行存,一次回滚把各行各自回前值;缺失就明说,不猜)。 */
348
261
  async function revert() {
349
262
  const ce = getEditor()
@@ -378,7 +291,7 @@ export function createPatchGuard(deps) {
378
291
  }
379
292
  }
380
293
 
381
- return { check, plan, fix, revert, applyPort, state }
294
+ return { check, plan, fix, revert, state }
382
295
  }
383
296
 
384
297
  /**