dsh-cookie-cleaner 0.2.2 → 0.6.4
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/CHANGELOG.md +242 -158
- package/README.md +442 -309
- package/dsh.plugin.json +2 -2
- package/lib/client.js +164 -3
- package/lib/client.js.map +1 -1
- package/package.json +4 -4
- package/scripts/hosts.mjs +19 -4
- package/scripts/sync-hosts.mjs +6 -6
- package/src/api-routes.js +7 -2
- package/src/cli.js +14 -2
- package/src/client/card.tsx +68 -1
- package/src/client/locales.ts +7 -0
- package/src/client/routes.ts +14 -0
- package/src/core.js +21 -8
- package/src/i18n.js +3 -2
- package/src/index.js +194 -19
- package/src/locales-dict.js +4 -0
- package/src/locales-dict2.js +4 -0
- package/src/locales-patch.js +4 -0
- package/src/patch-guard.js +42 -1
- package/src/report.js +14 -0
- package/src/runtime-guard.js +269 -0
package/src/index.js
CHANGED
|
@@ -17,6 +17,8 @@ import { LANGS, detectLang, normalize } from './i18n.js'
|
|
|
17
17
|
import { installSettingsWaist } from './settings-waist.js'
|
|
18
18
|
import { createPatchGuard } from './patch-guard.js'
|
|
19
19
|
import { cookieBrief, registerPatchRoutes } from './api-routes.js'
|
|
20
|
+
import { installCookieObserver, installRuntimeGuard, DEFAULTS as GUARD_DEFAULTS, LIMITS as GUARD_LIMITS } from './runtime-guard.js'
|
|
21
|
+
import { MAX_HEADER_BYTES } from './core.js'
|
|
20
22
|
|
|
21
23
|
/** Cordis 插件名(与 cordis.patch.yml 的 id 一致)。 */
|
|
22
24
|
export const name = 'cookie-cleaner'
|
|
@@ -29,6 +31,11 @@ export const DEFAULT_SETTINGS = Object.freeze({
|
|
|
29
31
|
lang: '', // 输出语言(zh/en/ja/ko/fr/de/it/ru/es);空=跟环境探测,探不到则 zh
|
|
30
32
|
guardDays: 1, // patch 体检的目标cookie 绝对寿命(宿主 schema 要求 ≥1)
|
|
31
33
|
guardMode: 'literal', // 'literal'=只动目标键 | 'expression'=把 bundle 层的 !!js 表达式还原回去
|
|
34
|
+
// 运行期守护(薄整合自 dsh-auth-cookie-guard):默认关,开启后插件只发响应头,仍然不碰 SQLite。
|
|
35
|
+
runtimeGuard: false,
|
|
36
|
+
maxHeaderBytes: GUARD_DEFAULTS.maxHeaderBytes,
|
|
37
|
+
keep: GUARD_DEFAULTS.keep,
|
|
38
|
+
retireAbove: GUARD_DEFAULTS.retireAbove,
|
|
32
39
|
// 没有 guardPort 设置项,也没有任何端口写入路径(用户裁决 2026-11-05):
|
|
33
40
|
// 本插件只改配置里的 cookie 有效期;端口属启动行为面,不在职责内。
|
|
34
41
|
})
|
|
@@ -39,6 +46,10 @@ export const Config = z.object({
|
|
|
39
46
|
lang: z.string().default(DEFAULT_SETTINGS.lang).volatile().description(`输出语言:${LANGS.join('/')}(留空=自动探测)`),
|
|
40
47
|
guardDays: z.natural().min(1).default(DEFAULT_SETTINGS.guardDays).volatile().description('cookie 体检与修复写入的目标绝对寿命(天)——这是防 431 真正有效的那一项'),
|
|
41
48
|
guardMode: z.string().default(DEFAULT_SETTINGS.guardMode).volatile().description("patch 修复形态:'literal' 只动目标键,'expression' 同时把 bundle 层的 !!js 表达式还原回去"),
|
|
49
|
+
runtimeGuard: z.boolean().default(DEFAULT_SETTINGS.runtimeGuard).volatile().description('运行期守护(默认关):开启后抬 server.maxHeaderSize,并在握手响应里下发 Set-Cookie Max-Age=0 让浏览器自己退休陈旧启动 cookie;仍不直接写 SQLite'),
|
|
50
|
+
maxHeaderBytes: z.natural().default(DEFAULT_SETTINGS.maxHeaderBytes).volatile().description(`运行期守护的监听器头部预算(夹到 ${GUARD_LIMITS.maxHeaderBytes[0]}–${GUARD_LIMITS.maxHeaderBytes[1]} 字节)`),
|
|
51
|
+
keep: z.natural().default(DEFAULT_SETTINGS.keep).volatile().description(`运行期守护保留的尾部 cookie 条数(夹到 ${GUARD_LIMITS.keep[0]}–${GUARD_LIMITS.keep[1]};当前端口那条另行保底)`),
|
|
52
|
+
retireAbove: z.natural().default(DEFAULT_SETTINGS.retireAbove).volatile().description(`阈值触发:启动 cookie 条数 > 此值才开始退休(0=不设阈值,每次按 keep 收敛;夹到 ${GUARD_LIMITS.retireAbove[0]}–${GUARD_LIMITS.retireAbove[1]})`),
|
|
42
53
|
})
|
|
43
54
|
|
|
44
55
|
/** volatile 字段/字段级活引用解引出普通值。 */
|
|
@@ -62,12 +73,31 @@ function readConfig(config) {
|
|
|
62
73
|
return out
|
|
63
74
|
}
|
|
64
75
|
|
|
76
|
+
/**
|
|
77
|
+
* 借句柄快照阶梯是否启用。
|
|
78
|
+
*
|
|
79
|
+
* 只有在宿主进程里才可能找到“真正持有 cookie 库”的兄弟进程:
|
|
80
|
+
* Electron 主进程(`process.type === 'browser'`)或以 Electron 为 node 的宿主子进程
|
|
81
|
+
* (`process.versions.electron` 存在)。独立 node(单测/脚本)扫了也匹配不上,直接关掉。
|
|
82
|
+
* `DSH_COOKIE_LIVE_LADDER=1|on` / `=0|off` 可显式覆盖(运维/定位用)。
|
|
83
|
+
* @param {Record<string,string|undefined>} [env]
|
|
84
|
+
* @param {{type?:string, versions?:Record<string,string|undefined>}} [proc]
|
|
85
|
+
*/
|
|
86
|
+
export function shouldUseLiveLadder(env = process.env, proc = process) {
|
|
87
|
+
const flag = String(env.DSH_COOKIE_LIVE_LADDER ?? '').trim().toLowerCase()
|
|
88
|
+
if (flag === '0' || flag === 'off') return false
|
|
89
|
+
if (flag === '1' || flag === 'on') return true
|
|
90
|
+
return proc.type === 'browser' || (proc.versions !== undefined && proc.versions.electron !== undefined)
|
|
91
|
+
}
|
|
92
|
+
|
|
65
93
|
/**
|
|
66
94
|
* @param {object} ctx Cordis 上下文。
|
|
67
95
|
* @param {object} [config] patch 行下发的配置。
|
|
68
96
|
*/
|
|
69
97
|
export function apply(ctx, config = {}) {
|
|
70
98
|
let current = () => readConfig(config)
|
|
99
|
+
/** 水位观测臂(只读);由 webServer 注入回调装配,未就绪时为 null。 */
|
|
100
|
+
let observer = null
|
|
71
101
|
|
|
72
102
|
const log = (message) => {
|
|
73
103
|
try {
|
|
@@ -78,19 +108,97 @@ export function apply(ctx, config = {}) {
|
|
|
78
108
|
}
|
|
79
109
|
}
|
|
80
110
|
|
|
111
|
+
/**
|
|
112
|
+
* cookie 读数(命令面 / 启动播报 / patch 共用):先普通只读;被 Chromium 独占时
|
|
113
|
+
* 走**和面板同一个内部 API**(`statCookiesLive`:借宿主自己持有的句柄做快照,
|
|
114
|
+
* 内置 5s 节流 + 60s 缓存)——否则运行期只能回“读不到”,面板有水位的命令面却没水位。
|
|
115
|
+
*
|
|
116
|
+
* 阶梯只在宿主进程内启用(见 `shouldUseLiveLadder`):独立 node(测试/脚本)
|
|
117
|
+
* 镜像名匹配不上持库进程,扫全机句柄表是空转(真机实测会让整个测试文件超时)。
|
|
118
|
+
*/
|
|
119
|
+
function readCookieStat(cfg) {
|
|
120
|
+
let stat
|
|
121
|
+
try {
|
|
122
|
+
stat = statCookies({ userDataRoot: cfg.userDataRoot })
|
|
123
|
+
} catch (e) {
|
|
124
|
+
return { stat: { verdict: 'error', message: e && e.message ? e.message : String(e) }, ladder: 'plain-error' }
|
|
125
|
+
}
|
|
126
|
+
if (stat.reason !== 'busy' || !shouldUseLiveLadder()) return { stat, ladder: 'plain' }
|
|
127
|
+
try {
|
|
128
|
+
const live = statCookiesLive({ userDataRoot: cfg.userDataRoot })
|
|
129
|
+
if (live && live.liveUnavailable !== true) return { stat: live, ladder: 'borrowed' }
|
|
130
|
+
return { stat, ladder: `borrowed-unavailable:${(live && live.liveReason) || 'unknown'}` }
|
|
131
|
+
} catch (e) {
|
|
132
|
+
return { stat, ladder: `borrowed-error:${(e && e.message) || String(e)}` }
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* 水位优先级:**请求头实时观测 > 借句柄快照 > 普通只读**。
|
|
138
|
+
*
|
|
139
|
+
* 观测臂拿到的就是浏览器实际发出的 Cookie 头(内存 jar),也就是真正会撞 431 的那一份;
|
|
140
|
+
* 磁盘读数只当辅证(它只在优雅退出时落盘,强杀后会是旧快照甚至 0 条)。
|
|
141
|
+
* 没观测到启动 cookie(minted ≤ 0)时完全退回磁盘档,不编造数据。
|
|
142
|
+
*/
|
|
143
|
+
function cookieWaterLevel(cfg) {
|
|
144
|
+
const disk = readCookieStat(cfg)
|
|
145
|
+
const observed = observer?.latest?.()
|
|
146
|
+
if (observed === undefined || !(observed.minted > 0)) return disk
|
|
147
|
+
const stat = disk.stat ?? {}
|
|
148
|
+
const bytes = Number(observed.headerBytes) || 0
|
|
149
|
+
const count = Number(observed.minted) || 0
|
|
150
|
+
const average = bytes / Math.max(1, Number(observed.total) || count)
|
|
151
|
+
return {
|
|
152
|
+
ladder: 'observed-header',
|
|
153
|
+
observed,
|
|
154
|
+
stat: {
|
|
155
|
+
...stat,
|
|
156
|
+
verdict: stat.verdict === 'error' ? stat.verdict : 'ok',
|
|
157
|
+
reason: 'observed-header',
|
|
158
|
+
authCookies: count,
|
|
159
|
+
authLive: count,
|
|
160
|
+
authExpired: 0,
|
|
161
|
+
totalCookies: Math.max(Number(stat.totalCookies) || 0, Number(observed.total) || 0),
|
|
162
|
+
header: {
|
|
163
|
+
bytes,
|
|
164
|
+
pct: Math.min(100, Math.round((bytes / MAX_HEADER_BYTES) * 1000) / 10),
|
|
165
|
+
rawPct: Math.round((bytes / MAX_HEADER_BYTES) * 1000) / 10,
|
|
166
|
+
maxHeaderBytes: MAX_HEADER_BYTES,
|
|
167
|
+
basis: 'measured-header',
|
|
168
|
+
threshold: Math.floor(MAX_HEADER_BYTES / Math.max(1, average)),
|
|
169
|
+
remaining: Math.max(0, Math.floor((MAX_HEADER_BYTES - bytes) / Math.max(1, average))),
|
|
170
|
+
over: bytes >= MAX_HEADER_BYTES,
|
|
171
|
+
},
|
|
172
|
+
source: 'request-header',
|
|
173
|
+
snapshot: false,
|
|
174
|
+
observedAt: observed.at,
|
|
175
|
+
diskSource: stat.source,
|
|
176
|
+
diskSnapshot: stat.snapshot === true,
|
|
177
|
+
},
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
81
181
|
/** 只读现状 + 处置文案。overrides 可临时换档(`mode:'clean'` 只换措辞,仍不写盘)。 */
|
|
82
182
|
function status(overrides = {}) {
|
|
83
183
|
const cfg = { ...current(), ...overrides }
|
|
84
184
|
// 设置里显式指定则优先,否则按环境探测(探不到落 zh)。
|
|
85
185
|
const lang = normalize(cfg.lang || '')
|
|
86
186
|
setLang(cfg.lang ? lang : detectLang())
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
187
|
+
const { stat, ladder, observed } = cookieWaterLevel(cfg)
|
|
188
|
+
const text = cookieCleanerCommandText(stat, { ...cfg, lang: undefined })
|
|
189
|
+
if (ladder === 'observed-header' && observed !== undefined) {
|
|
190
|
+
return {
|
|
191
|
+
stat,
|
|
192
|
+
ladder,
|
|
193
|
+
observed,
|
|
194
|
+
text: `${text}\n 水位 实时(请求头观测):${observed.minted}/${observed.total} 条,Cookie 头 ${observed.headerBytes} B,观测于 ${new Date(observed.at).toISOString()}`,
|
|
195
|
+
}
|
|
92
196
|
}
|
|
93
|
-
|
|
197
|
+
if (ladder === 'borrowed') {
|
|
198
|
+
const bytes = stat && stat.snapshotBytes
|
|
199
|
+
return { stat, ladder, text: `${text}\n 读数 借宿主句柄快照(非实时${bytes ? `,${bytes} B` : ''})` }
|
|
200
|
+
}
|
|
201
|
+
return { stat, ladder, text }
|
|
94
202
|
}
|
|
95
203
|
|
|
96
204
|
// ── 三代设置 waist(0.1.2/0.1.5 installSection、0.1.0/0.1.1 register、0.1.7+ volatile 托管)──
|
|
@@ -103,6 +211,37 @@ export function apply(ctx, config = {}) {
|
|
|
103
211
|
},
|
|
104
212
|
})
|
|
105
213
|
|
|
214
|
+
// ── 运行期守护(薄整合自 dsh-auth-cookie-guard)——与 configEditor 解耦:只需 webServer 就绪 ──
|
|
215
|
+
// 默认关;runtimeGuard=true 时抬监听器预算 + 在 'request' 事件上 prepend retire 下发 Set-Cookie 删除行。
|
|
216
|
+
// **不直接写 SQLite**,不开 session.cookies,只走 HTTP。
|
|
217
|
+
ctx.inject(['webServer'], (gctx) => {
|
|
218
|
+
const cfg = current()
|
|
219
|
+
const webServer = typeof gctx.get === 'function' ? gctx.get('webServer') : gctx.webServer
|
|
220
|
+
const server = webServer?.server
|
|
221
|
+
if (server === void 0) {
|
|
222
|
+
log('runtime guard 未启用:webServer 无 server 引用(headless/fiber 正常降级)')
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
// ① 水位观测臂:**无条件挂**(与退休开关无关)。
|
|
226
|
+
// 431 的真实水位来自浏览器实际发出的 Cookie 头(内存 jar);磁盘 jar 只在优雅退出时落盘,
|
|
227
|
+
// 强杀/崩溃后会一直是旧快照甚至 0 条——只读磁盘会把“守护关了”误报成“没有 cookie”。
|
|
228
|
+
observer = installCookieObserver(server, {
|
|
229
|
+
onObserve: (info) => { if (info.minted > 0) log(`cookie 水位:${info.minted} 条 dsh-auth-*(Cookie 头 ${info.headerBytes} B)`) },
|
|
230
|
+
})
|
|
231
|
+
gctx.effect(() => () => { observer?.dispose?.(); observer = null }, `${name}: cookie observer`)
|
|
232
|
+
if (cfg.runtimeGuard !== true) return
|
|
233
|
+
// ② 退休与抬预算:仍只在 runtimeGuard 开启时挂。
|
|
234
|
+
const dispose = installRuntimeGuard(server, {
|
|
235
|
+
maxHeaderBytes: cfg.maxHeaderBytes,
|
|
236
|
+
keep: cfg.keep,
|
|
237
|
+
retireAbove: cfg.retireAbove,
|
|
238
|
+
webServer,
|
|
239
|
+
onRetire: (info) => log(`runtime guard: retired ${info.emitted}/${info.stale}, retained ${info.retained} (total ${info.total})`),
|
|
240
|
+
})
|
|
241
|
+
log(`runtime guard ON:budget=${String(cfg.maxHeaderBytes)} B, keep=${String(cfg.keep)}, retireAbove=${String(cfg.retireAbove)}, cap=96/response`)
|
|
242
|
+
gctx.effect(() => () => { dispose(); log('runtime guard OFF (disposed)') }, `${name}: runtime guard`)
|
|
243
|
+
})
|
|
244
|
+
|
|
106
245
|
// ── patch 体检/修复守卫(只在 configEditor 就绪后存在;老线回调不触发,插件其余面照常)──
|
|
107
246
|
/** @type {{check:Function, plan:Function, fix:Function, revert:Function} | undefined} */
|
|
108
247
|
let guard
|
|
@@ -119,22 +258,21 @@ export function apply(ctx, config = {}) {
|
|
|
119
258
|
// 端口不预填:面板不再提供控件,命令面必须当场给数(没给则由守卫拒写)
|
|
120
259
|
lang: cfg.lang ? normalize(cfg.lang) : undefined,
|
|
121
260
|
// cookie 库现状随体检一起回:只有面板这条走阶梯(普通只读打开不行时才试借句柄快照)。
|
|
122
|
-
cookie: () =>
|
|
261
|
+
cookie: () => cookieWaterLevel(current()).stat,
|
|
262
|
+
// 运行期守护面板臂:读当前生效值 / 写白名单四键(都走本插件自己的 configEditor 行)
|
|
263
|
+
getGuard: () => guard.readGuard(),
|
|
264
|
+
setGuard: (patch) => guard.writeGuard(patch),
|
|
123
265
|
})
|
|
124
266
|
if (offs.length === 0) return
|
|
125
267
|
sctx.effect(() => () => offs.forEach((off) => { try { off() } catch { /* 已回收 */ } }), `${name}: patch routes`)
|
|
126
268
|
})
|
|
127
269
|
|
|
128
270
|
/**
|
|
129
|
-
* cookie
|
|
130
|
-
*
|
|
131
|
-
* 为什么不跟面板共用阶梯:扫一次全机句柄表只在“用户显式点了体检”时才值得,
|
|
132
|
-
* 而命令面/启动播报会被测试与脚本反复调用,拿它去做系统级扫描会直接卡住
|
|
133
|
-
* (真机实测:`patch check` 在命令面触发借句柄后整个测试文件超时)。
|
|
134
|
-
* 而且独立进程的镜像名与桌面端不同,目标进程本来就匹配不上——诚实回 busy。
|
|
271
|
+
* patch 体检里的 cookie 现状:与命令面 / 面板共用同一个阶梯(`readCookieStat`)。
|
|
272
|
+
* 旧版这里故意不借句柄,导致桌面端体检报“读不到”而面板有水位——接线不一致。
|
|
135
273
|
*/
|
|
136
274
|
function cookieBriefForCommand() {
|
|
137
|
-
return cookieBrief(() =>
|
|
275
|
+
return cookieBrief(() => cookieWaterLevel(current()).stat)
|
|
138
276
|
}
|
|
139
277
|
|
|
140
278
|
/** patch 子命令的统一入口(写只发生在这里——用户触发的回调链,不在 HMR 事务内)。 */
|
|
@@ -154,7 +292,14 @@ export function apply(ctx, config = {}) {
|
|
|
154
292
|
}
|
|
155
293
|
if (sub === 'plan') return { text: patchReportText(guard.plan(opts)) }
|
|
156
294
|
// check 与面板同构:同一个 headerOccupancy 折算结果,两边不得各自算一套。
|
|
157
|
-
|
|
295
|
+
// 同时把运行期守护开关一并带下去,面板与命令面共用 guardOn/guardOff 两档文案(旧行为不受影响)。
|
|
296
|
+
return { text: patchReportText({
|
|
297
|
+
...guard.check(opts),
|
|
298
|
+
cookie: cookieBriefForCommand(),
|
|
299
|
+
runtimeGuard: cfg.runtimeGuard === true,
|
|
300
|
+
maxHeaderBytes: cfg.maxHeaderBytes,
|
|
301
|
+
keep: cfg.keep,
|
|
302
|
+
}) }
|
|
158
303
|
}
|
|
159
304
|
|
|
160
305
|
// ── /cookie-cleaner 命令(fail-open:commands 服务缺失只降级不 fatal)──
|
|
@@ -197,18 +342,48 @@ function registerCookieCleanerCommand(ctx, status, runPatch) {
|
|
|
197
342
|
input: { hint: '[status|clean] | patch [check|fix|revert|plan]' },
|
|
198
343
|
handler: async (invocation) => {
|
|
199
344
|
const tokens = String(invocation?.rawInput ?? '').trim().split(/\s+/).filter(Boolean)
|
|
345
|
+
const wantsJson = tokens.includes('--json')
|
|
346
|
+
// 输出契约(dsh-tui notice 单块):单行 ≤100、总行 ≤40(超出给提示)。
|
|
347
|
+
const clipOut = (text) => {
|
|
348
|
+
const lines = String(text ?? '').split('\n').map((line) => line.replace(/\s+$/, ''))
|
|
349
|
+
const clipped = lines.map((line) => (line.length <= 100 ? line : `${line.slice(0, 99)}…`))
|
|
350
|
+
if (clipped.length <= 40) return clipped.join('\n')
|
|
351
|
+
return [...clipped.slice(0, 39), `… 还有 ${clipped.length - 39} 行`].join('\n')
|
|
352
|
+
}
|
|
353
|
+
const reply = (kind, sub, text, data) => {
|
|
354
|
+
const clipped = clipOut(text)
|
|
355
|
+
if (!wantsJson) return { kind, text: clipped }
|
|
356
|
+
const payload = kind === 'error'
|
|
357
|
+
? { ok: false, cmd: 'cookie-cleaner', sub, error: { message: clipped.split('\n')[0] ?? clipped } }
|
|
358
|
+
: { ok: true, cmd: 'cookie-cleaner', sub, data: data ?? { text: clipped } }
|
|
359
|
+
return { kind, text: JSON.stringify(payload) }
|
|
360
|
+
}
|
|
361
|
+
// 本命令全宿主接线(Desktop/TUI/CLI 都走真实逻辑):
|
|
362
|
+
// TUI/CLI 上能读到就报,读不到就报原因 —— 不做「不适用」短路,
|
|
363
|
+
// 否则桌面版的命令面就只剩提示、等于没接线。
|
|
200
364
|
try {
|
|
201
365
|
if (tokens[0] === 'patch') {
|
|
202
366
|
// 没有 `port` 子命令:本插件不写端口(启动行为面不在职责内)。
|
|
203
367
|
const sub = ['check', 'fix', 'revert', 'plan'].includes(tokens[1]) ? tokens[1] : 'check'
|
|
204
368
|
const { text } = await runPatch(sub)
|
|
205
|
-
return
|
|
369
|
+
return reply('success', `patch ${sub}`, text)
|
|
206
370
|
}
|
|
207
371
|
const mode = tokens[0] === 'clean' ? 'clean' : 'status'
|
|
208
|
-
const { text } = status({ mode })
|
|
209
|
-
|
|
372
|
+
const { text, stat, ladder, observed } = status({ mode })
|
|
373
|
+
// `--json` 把读数来源一并吐出:脚本能区分“实时观测 / 快照 / busy 回档”。
|
|
374
|
+
return reply('success', mode, text, {
|
|
375
|
+
text,
|
|
376
|
+
ladder,
|
|
377
|
+
source: (stat && stat.source) ?? 'plain-open',
|
|
378
|
+
snapshot: (stat && stat.snapshot) === true,
|
|
379
|
+
observed: observed ?? null,
|
|
380
|
+
verdict: stat && stat.verdict,
|
|
381
|
+
authCookies: stat && stat.authCookies,
|
|
382
|
+
totalCookies: stat && stat.totalCookies,
|
|
383
|
+
headerBytes: stat && stat.header && stat.header.bytes,
|
|
384
|
+
})
|
|
210
385
|
} catch (e) {
|
|
211
|
-
return
|
|
386
|
+
return reply('error', tokens[0] ?? 'status', `cookie-cleaner 失败: ${e && e.message ? e.message : String(e)}`)
|
|
212
387
|
}
|
|
213
388
|
},
|
|
214
389
|
})
|
package/src/locales-dict.js
CHANGED
|
@@ -37,6 +37,7 @@ registerDictionary('en', {
|
|
|
37
37
|
deleted: 'Deleted {count} dsh-auth-* entries ({scope})',
|
|
38
38
|
scopeAll: 'all',
|
|
39
39
|
scopeExpired: 'expired only',
|
|
40
|
+
scopeOlderThan: 'older than {hours}h',
|
|
40
41
|
dbSize: ' Database: {path} {before} B → {after} B',
|
|
41
42
|
backup: ' Backup: {backup}',
|
|
42
43
|
backupWith: ' (incl. {sidecars})',
|
|
@@ -91,6 +92,7 @@ registerDictionary('ja', {
|
|
|
91
92
|
deleted: 'dsh-auth-* を {count} 件削除しました({scope})',
|
|
92
93
|
scopeAll: 'すべて',
|
|
93
94
|
scopeExpired: '期限切れのみ',
|
|
95
|
+
scopeOlderThan: '{hours} 時間より古い',
|
|
94
96
|
dbSize: ' データベース:{path} {before} B → {after} B',
|
|
95
97
|
backup: ' バックアップ:{backup}',
|
|
96
98
|
backupWith: '({sidecars} を含む)',
|
|
@@ -142,6 +144,7 @@ registerDictionary('ko', {
|
|
|
142
144
|
deleted: 'dsh-auth-* {count} 개 삭제({scope})',
|
|
143
145
|
scopeAll: '전체',
|
|
144
146
|
scopeExpired: '만료분만',
|
|
147
|
+
scopeOlderThan: '{hours}시간 초과',
|
|
145
148
|
dbSize: ' 데이터베이스: {path} {before} B → {after} B',
|
|
146
149
|
backup: ' 백업: {backup}',
|
|
147
150
|
backupWith: ' ({sidecars} 포함)',
|
|
@@ -193,6 +196,7 @@ registerDictionary('fr', {
|
|
|
193
196
|
deleted: '{count} entrées dsh-auth-* supprimées ({scope})',
|
|
194
197
|
scopeAll: 'toutes',
|
|
195
198
|
scopeExpired: 'expirées uniquement',
|
|
199
|
+
scopeOlderThan: 'plus de {hours} h',
|
|
196
200
|
dbSize: ' Base : {path} {before} o → {after} o',
|
|
197
201
|
backup: ' Sauvegarde : {backup}',
|
|
198
202
|
backupWith: ' (dont {sidecars})',
|
package/src/locales-dict2.js
CHANGED
|
@@ -34,6 +34,7 @@ registerDictionary('de', {
|
|
|
34
34
|
deleted: '{count} dsh-auth-* Einträge gelöscht ({scope})',
|
|
35
35
|
scopeAll: 'alle',
|
|
36
36
|
scopeExpired: 'nur abgelaufene',
|
|
37
|
+
scopeOlderThan: 'älter als {hours} h',
|
|
37
38
|
dbSize: ' Datenbank: {path} {before} B → {after} B',
|
|
38
39
|
backup: ' Sicherung: {backup}',
|
|
39
40
|
backupWith: ' (inkl. {sidecars})',
|
|
@@ -85,6 +86,7 @@ registerDictionary('it', {
|
|
|
85
86
|
deleted: 'Cancellate {count} voci dsh-auth-* ({scope})',
|
|
86
87
|
scopeAll: 'tutte',
|
|
87
88
|
scopeExpired: 'solo scadute',
|
|
89
|
+
scopeOlderThan: 'più vecchi di {hours} h',
|
|
88
90
|
dbSize: ' Database: {path} {before} B → {after} B',
|
|
89
91
|
backup: ' Backup: {backup}',
|
|
90
92
|
backupWith: ' (inclusi {sidecars})',
|
|
@@ -136,6 +138,7 @@ registerDictionary('ru', {
|
|
|
136
138
|
deleted: 'Удалено {count} записей dsh-auth-* ({scope})',
|
|
137
139
|
scopeAll: 'все',
|
|
138
140
|
scopeExpired: 'только просроченные',
|
|
141
|
+
scopeOlderThan: 'старше {hours} ч',
|
|
139
142
|
dbSize: ' База: {path} {before} Б → {after} Б',
|
|
140
143
|
backup: ' Резервная копия: {backup}',
|
|
141
144
|
backupWith: ' (включая {sidecars})',
|
|
@@ -187,6 +190,7 @@ registerDictionary('es', {
|
|
|
187
190
|
deleted: 'Se borraron {count} entradas dsh-auth-* ({scope})',
|
|
188
191
|
scopeAll: 'todas',
|
|
189
192
|
scopeExpired: 'solo vencidas',
|
|
193
|
+
scopeOlderThan: 'más antiguas que {hours} h',
|
|
190
194
|
dbSize: ' Base: {path} {before} B → {after} B',
|
|
191
195
|
backup: ' Copia de seguridad: {backup}',
|
|
192
196
|
backupWith: ' (incluidos {sidecars})',
|
package/src/locales-patch.js
CHANGED
|
@@ -181,6 +181,10 @@ export const PATCH_TEXT = Object.freeze({
|
|
|
181
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'),
|
|
182
182
|
offlineNote: t('(离线档)只能看到文件层;运行态与 bundle 层的对比(P5/P7/P9)需要启动客户端后面板/命令来查', '(offline mode) only the file layer is visible; the runtime/bundle-layer comparisons (P5/P7/P9) need the panel or command while the client runs', '(オフライン档)ファイル層のみ閲覧可。実行状態と bundle 層の比較(P5/P7/P9)はクライアント起動後にパネル/コマンドで', '(오프라인 모드) 파일 레이어만 보입니다. 런타임/bundle 레이어 비교(P5/P7/P9)는 클라이언트 실행 후 패널/명령으로', '(mode hors ligne) seule la couche fichier est visible ; les comparaisons runtime/bundle (P5/P7/P9) exigent le panneau ou la commande avec le client lancé', '(Offline-Modus) nur die Dateiebene ist sichtbar; die Vergleiche Laufzeit/Bundle-Ebene (P5/P7/P9) brauchen Panel oder Befehl bei laufendem Client', '(modalità offline) si vede solo il layer file; i confronti runtime/layer bundle (P5/P7/P9) richiedono pannello o comando a client attivo', '(офлайн-режим) виден только слой файла; сравнения рантайма и слоя bundle (P5/P7/P9) нужны панель или команда при запущенном клиенте', '(modo sin conexión) solo se ve la capa de archivo; las comparaciones runtime/capa bundle (P5/P7/P9) necesitan el panel o el comando con el cliente activo'),
|
|
183
183
|
editedExternally: t('(提示)profile patch 也可被宿主插件管理器或手改变更,体检以当前运行树为准', '(note) the profile patch may also change via the host plugin manager or hand edits; the check reports the current running tree', '(参考)profile patch は宿主のプラグインマネージャーや手編集でも変わります。体検は現在の実行中ツリーを基準にします', '(참고) profile patch는 호스트 플러그인 관리자나 수동 편집으로도 바뀜. 점검은 현재 실행 트리를 기준으로 함', '(note) le patch de profil peut aussi évoluer via le gestionnaire de plugins ou à la main ; le contrôle rend l\'arbre courant', '(Hinweis) der Profil-Patch kann sich auch über den Plugin-Manager oder per Hand ändern; die Prüfung meldet den laufenden Baum', '(nota) il patch del profilo può cambiare anche tramite il gestore plugin o a mano; il controllo riporta l\'albero in esecuzione', '(примечание) патч профиля может меняться через менеджер плагинов или вручную; проверка даёт текущее дерево', '(nota) el patch del perfil también cambia vía el gestor de plugins o a mano; la revisión reporta el árbol en ejecución'),
|
|
184
|
+
// 运行期守护状态行(薄整合自 dsh-auth-cookie-guard):开关两个档位,面板与命令面共用。
|
|
185
|
+
// 只走 HTTP 响应头,本插件仍不直接写 SQLite——语义与默认档保持一致。
|
|
186
|
+
guardOn: t('运行期守护:开(监听器预算 {budget} B,保留尾部 {keep} 条 + 当前端口保底,单响应最多 {cap} 条删除行)', 'runtime guard: ON (listener budget {budget} B, retaining tail {keep} + current authority, up to {cap} deletions per response)', 'ランタイム守護:オン(リッサーバジェット {budget} B、末尾 {keep} 件+現在の authority を保証、1 レスポンド最大 {cap} 件削除)', '런타임 가드: 켜힘(리스너 예산 {budget}B, 꼬리 {keep}개 + 현재 authority 보장, 응답당 최대 {cap}개 삭제)', 'garde en direct : activée (budget écouteur {budget} B, conserve les {keep} derniers + l\'autorité courante, jusqu\'à {cap} suppressions par réponse)', 'Laufzeit-Wächter: AN (Listener-Budget {budget} B, hält die letzten {keep} + aktuelle Autorität, bis zu {cap} Löschungen pro Antwort)', 'guardia runtime: ON (budget listener {budget} B, trattiene la coda {keep} + autorità corrente, fino a {cap} cancellazioni per risposta)', 'страж во время работы: ВКЛ (бюджет слушателя {budget} Б, держит хвост {keep} + текущий authority, до {cap} удалений на ответ)', 'guardia en ejecución: ACTIVADA (presupuesto del listener {budget} B, retiene cola {keep} + autoridad actual, hasta {cap} borrados por respuesta)'),
|
|
187
|
+
guardOff: t('运行期守护:关(默认;本插件仅走离线 --clean + patch fix,不碰运行期响应头,也不直连 SQLite)', 'runtime guard: OFF (default; this plugin only runs offline --clean + patch fix, it does not touch runtime response headers nor open SQLite directly)', 'ランタイム守護:オフ(デフォルト;本プラグインはオフライン --clean + patch fix のみで、実行時ヘッダも SQLite 直結も触らない)', '런타임 가드: 꺼짐(기본; 이 플러그인은 오프라인 --clean + patch fix 만 실행하며 런타임 헤더도 SQLite 직접도 건드리지 않음)', 'garde en direct : désactivée (par défaut ; ce plugin ne fait que --clean/patch fix hors ligne, ne touche ni les en-têtes ni SQLite)', 'Laufzeit-Wächter: AUS (Standard; dieses Plugin nutzt nur Offline-`--clean` + `patch fix` – weder Runtime-Header noch SQLite direkt)', 'guardia runtime: OFF (predefinita; questo plugin esegue solo --clean/patch fix offline, non tocca header runtime né SQLite direttamente)', 'страж: ВЫКЛ (по умолчанию; этот плагин работает только офлайн --clean + patch fix, не трогает заголовки и не открывает SQLite)', 'guardia en ejecución: DESACTIVADA (predeterminada; este plugin solo ejecuta --clean/patch fix sin runtime, no toca cabeceras ni abre SQLite)'),
|
|
184
188
|
})
|
|
185
189
|
|
|
186
190
|
/**
|
package/src/patch-guard.js
CHANGED
|
@@ -291,7 +291,48 @@ export function createPatchGuard(deps) {
|
|
|
291
291
|
}
|
|
292
292
|
}
|
|
293
293
|
|
|
294
|
-
|
|
294
|
+
/**
|
|
295
|
+
* 本插件自己的配置行(patch id = 'cookie-cleaner')——运行期守护开关与阈值都在这行。
|
|
296
|
+
* 读写都走同一个 configEditor.edit(目标插件 Config schema 校验 + 原子写 + HMR 热应用)。
|
|
297
|
+
*/
|
|
298
|
+
const OWN_ROW_ID = 'cookie-cleaner'
|
|
299
|
+
const GUARD_KEYS = ['runtimeGuard', 'maxHeaderBytes', 'keep', 'retireAbove']
|
|
300
|
+
function guardEntry() {
|
|
301
|
+
const ce = getEditor()
|
|
302
|
+
if (ce === undefined || typeof ce.entries !== 'function') return undefined
|
|
303
|
+
return ce.entries().find((row) => row.options.id === OWN_ROW_ID || row.options.name === 'dsh-cookie-cleaner')
|
|
304
|
+
}
|
|
305
|
+
/** 读当前生效的守护配置(拿不到行就 available:false,不编造默认值当生效态)。 */
|
|
306
|
+
function readGuard() {
|
|
307
|
+
const entry = guardEntry()
|
|
308
|
+
if (entry === undefined) return { available: false, runtimeGuard: false, maxHeaderBytes: 65536, keep: 4, retireAbove: 0 }
|
|
309
|
+
const c = entry.options.config ?? {}
|
|
310
|
+
return {
|
|
311
|
+
available: true,
|
|
312
|
+
runtimeGuard: c.runtimeGuard === true,
|
|
313
|
+
maxHeaderBytes: Number.isInteger(c.maxHeaderBytes) ? c.maxHeaderBytes : 65536,
|
|
314
|
+
keep: Number.isInteger(c.keep) ? c.keep : 4,
|
|
315
|
+
retireAbove: Number.isInteger(c.retireAbove) ? c.retireAbove : 0,
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
/** 写守护配置(只动白名单四键,其余 config 原样保留;无变化不写)。 */
|
|
319
|
+
async function writeGuard(patch = {}) {
|
|
320
|
+
const entry = guardEntry()
|
|
321
|
+
if (entry === undefined) return { kind: 'no-entry' }
|
|
322
|
+
const current = entry.options.config ?? {}
|
|
323
|
+
const next = { ...current }
|
|
324
|
+
if (patch.runtimeGuard !== undefined) next.runtimeGuard = patch.runtimeGuard === true
|
|
325
|
+
if (patch.maxHeaderBytes !== undefined) next.maxHeaderBytes = Math.trunc(Number(patch.maxHeaderBytes))
|
|
326
|
+
if (patch.keep !== undefined) next.keep = Math.trunc(Number(patch.keep))
|
|
327
|
+
if (patch.retireAbove !== undefined) next.retireAbove = Math.trunc(Number(patch.retireAbove))
|
|
328
|
+
const changed = GUARD_KEYS.filter((key) => JSON.stringify(current[key]) !== JSON.stringify(next[key]))
|
|
329
|
+
if (changed.length === 0) return { kind: 'noop', value: readGuard() }
|
|
330
|
+
const written = await attemptEdit(entry, next)
|
|
331
|
+
if (!written.ok) return { kind: 'failed', message: written.message }
|
|
332
|
+
return { kind: 'saved', changed, value: readGuard(), retried: written.retried === true }
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
return { check, plan, fix, revert, readGuard, writeGuard, state }
|
|
295
336
|
}
|
|
296
337
|
|
|
297
338
|
/**
|
package/src/report.js
CHANGED
|
@@ -204,6 +204,20 @@ export function patchReportText(result, cfg = {}) {
|
|
|
204
204
|
lines.push(live ?? `${String(c.authCookies ?? '?')} dsh-auth-* / ${String(c.totalCookies ?? '?')} total`)
|
|
205
205
|
}
|
|
206
206
|
}
|
|
207
|
+
// 运行期守护状态行(面板与命令面共用):runtimeGuard 字段存在才渲染,旧行为不受影响。
|
|
208
|
+
if (result.runtimeGuard !== undefined) {
|
|
209
|
+
lines.push('')
|
|
210
|
+
if (result.runtimeGuard === true) {
|
|
211
|
+
lines.push(patchText('text', 'guardOn', lang, {
|
|
212
|
+
budget: String(result.maxHeaderBytes ?? 65536),
|
|
213
|
+
keep: String(result.keep ?? 4),
|
|
214
|
+
cap: '96',
|
|
215
|
+
}))
|
|
216
|
+
} else {
|
|
217
|
+
lines.push(patchText('text', 'guardOff', lang))
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
207
221
|
if (cfg.outcome !== undefined) lines.push('', patchOutcomeText(cfg.outcome, { lang }))
|
|
208
222
|
return lines.join('\n')
|
|
209
223
|
}
|