dsh-cookie-cleaner 0.2.3 → 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/src/api-routes.js CHANGED
@@ -15,12 +15,14 @@
15
15
  /** 命名空间 = npm 包名(settings ns、卡 id、桥路径三处同串)。 */
16
16
  export const NS = 'dsh-cookie-cleaner'
17
17
 
18
- /** 三条路由:体检 / 修复 / 回滚。(端口写入只走命令面,面板不提供控件,所以不开写端点) */
18
+ /** 桥路由:体检 / 修复 / 回滚 + 运行期守护读/写。(端口写入面板不提供,不开端点) */
19
19
  export function bridgeRoutesFor(ns = NS) {
20
20
  return Object.freeze({
21
21
  check: `/api/${ns}/patch/check`,
22
22
  fix: `/api/${ns}/patch/fix`,
23
23
  revert: `/api/${ns}/patch/revert`,
24
+ guardGet: `/api/${ns}/guard/get`,
25
+ guardSet: `/api/${ns}/guard/set`,
24
26
  })
25
27
  }
26
28
 
@@ -111,7 +113,7 @@ export function registerPatchRoutes(webServer, guard, defaults = {}) {
111
113
  guardMode: body?.guardMode === 'expression' ? 'expression' : defaults.guardMode,
112
114
  lang: typeof body?.lang === 'string' ? body.lang : defaults.lang,
113
115
  }
114
- const value = await run(options)
116
+ const value = await run(options, body)
115
117
  sendJson(res, 200, { ok: true, value })
116
118
  }).catch((e) => {
117
119
  sendJson(res, 200, { ok: false, code: 'internal', message: String(e && e.message ? e.message : e) })
@@ -129,5 +131,8 @@ export function registerPatchRoutes(webServer, guard, defaults = {}) {
129
131
  })
130
132
  endpoint(routes.fix, (options) => guard.fix(options))
131
133
  endpoint(routes.revert, () => guard.revert())
134
+ // 运行期守护:读当前生效值 / 写入白名单四键(走 guard 的 configEditor 编辑通道)
135
+ endpoint(routes.guardGet, () => (typeof defaults.getGuard === 'function' ? defaults.getGuard() : { available: false }))
136
+ endpoint(routes.guardSet, (_options, body) => (typeof defaults.setGuard === 'function' ? defaults.setGuard(body ?? {}) : { kind: 'no-entry' }))
132
137
  return offs
133
138
  }
package/src/cli.js CHANGED
@@ -30,6 +30,7 @@ function usage() {
30
30
  dsh-cookie-cleaner 查看现状:库在哪、多少条 dsh-auth-*、多少已过期
31
31
  dsh-cookie-cleaner --clean 删除回环域(127.0.0.1/localhost/[::1])下全部 dsh-auth-*
32
32
  dsh-cookie-cleaner --clean --expired-only 保守档:只删已过期的
33
+ dsh-cookie-cleaner --clean --older-than=24 只删创建超过 24 小时的(可小数,如 0.5=30 分钟)
33
34
  dsh-cookie-cleaner --clean --dry-run 只看会删几条,不写盘
34
35
  dsh-cookie-cleaner --db=<完整路径> 手动指定 cookie 库(非默认安装/flatpak/snap 用)
35
36
 
@@ -59,11 +60,13 @@ function dshHomeOf(env) {
59
60
  }
60
61
 
61
62
  function parseArgs(argv) {
62
- const options = { clean: false, expiredOnly: false, dryRun: false, noBackup: false, noVacuum: false, db: '', lang: '', help: false, version: false, command: '', sub: 'check', profile: 'desktop', patchFile: '', targetDays: 1 }
63
+ const options = { clean: false, expiredOnly: false, olderThan: 0, dryRun: false, noBackup: false, noVacuum: false, db: '', lang: '', help: false, version: false, command: '', sub: 'check', profile: 'desktop', patchFile: '', targetDays: 1 }
63
64
  for (let i = 0; i < argv.length; i++) {
64
65
  const arg = argv[i]
65
66
  if (arg === '--clean') options.clean = true
66
67
  else if (arg === '--expired-only') options.expiredOnly = true
68
+ else if (arg === '--older-than') options.olderThan = Number(argv[++i])
69
+ else if (arg.startsWith('--older-than=')) options.olderThan = Number(arg.slice('--older-than='.length))
67
70
  else if (arg === '--dry-run') options.dryRun = true
68
71
  else if (arg === '--no-backup') options.noBackup = true
69
72
  else if (arg === '--no-vacuum') options.noVacuum = true
@@ -177,8 +180,14 @@ function main() {
177
180
  process.exitCode = okReason ? 0 : 1
178
181
  return
179
182
  }
183
+ if (!Number.isFinite(options.olderThan) || options.olderThan < 0) {
184
+ process.stderr.write(`--older-than 必须是 ≥ 0 的小时数,实际:${String(options.olderThan)}\n`)
185
+ process.exitCode = 1
186
+ return
187
+ }
180
188
  const result = core.cleanCookies({
181
189
  expiredOnly: options.expiredOnly,
190
+ olderThanHours: options.olderThan,
182
191
  dryRun: options.dryRun,
183
192
  noBackup: options.noBackup,
184
193
  noVacuum: options.noVacuum,
@@ -194,8 +203,11 @@ function main() {
194
203
  process.stdout.write(msg('dryRun', { count: result.wouldDelete, path: result.path }) + '\n' + msg('dryRunTail', {}) + '\n')
195
204
  return
196
205
  }
206
+ const scope = result.olderThanHours > 0
207
+ ? msg('scopeOlderThan', { hours: result.olderThanHours })
208
+ : result.expiredOnly ? msg('scopeExpired', {}) : msg('scopeAll', {})
197
209
  const lines = [
198
- msg('deleted', { count: result.deleted, scope: result.expiredOnly ? msg('scopeExpired', {}) : msg('scopeAll', {}) }),
210
+ msg('deleted', { count: result.deleted, scope }),
199
211
  msg('dbSize', { path: result.path, before: result.beforeBytes, after: result.afterBytes }),
200
212
  ]
201
213
  if (result.backup) {
@@ -10,7 +10,7 @@ import * as React from 'react'
10
10
 
11
11
  import { render } from './locales'
12
12
  import { postJson, routes } from './routes'
13
- import type { ActionView, CheckView, Finding, RowView } from './routes'
13
+ import type { ActionView, CheckView, Finding, GuardView, RowView } from './routes'
14
14
 
15
15
  export interface CardProps {
16
16
  /** 当前语言的取词函数(跟着宿主 locale 走,卡片不缓存旧值)。 */
@@ -82,6 +82,71 @@ function CookieLine({ cookie, t }: { cookie?: CheckView['cookie']; t: (key: stri
82
82
  )
83
83
  }
84
84
 
85
+ /**
86
+ * 运行期守护面板:一个开关(runtimeGuard)+ 两个阈值(retireAbove / keep)。
87
+ * 读写都走后端桥(configEditor 写本插件自己那行),写后回显生效值——不凭手写 YAML。
88
+ */
89
+ function GuardPanel({ t }: { t: (key: string) => string }): React.ReactElement | null {
90
+ const [g, setG] = React.useState<GuardView | undefined>(undefined)
91
+ const [busy, setBusy] = React.useState(false)
92
+ const [note, setNote] = React.useState('')
93
+ const mounted = React.useRef(true)
94
+ React.useEffect(() => {
95
+ mounted.current = true
96
+ postJson<GuardView>(routes.guardGet, {}).then((v) => { if (mounted.current) setG(v) }).catch(() => { /* 无 config-editor 时静默,不刷红 */ })
97
+ return () => { mounted.current = false }
98
+ }, [])
99
+ if (g === undefined) return null
100
+ if (g.available === false) return <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{t('guard.unavailable')}</div>
101
+ const toInt = (e: React.ChangeEvent<HTMLInputElement>) => { const n = Math.trunc(Number(e.target.value)); return Number.isFinite(n) ? n : 0 }
102
+ // 改完即存(无保存按钮):先乐观更新本地态,后端失败则回滚到服务端值
103
+ const commit = async (next: GuardView) => {
104
+ const prev = g
105
+ setG(next)
106
+ setBusy(true); setNote('')
107
+ try {
108
+ const v = await postJson<GuardView>(routes.guardSet, { runtimeGuard: next.runtimeGuard, maxHeaderBytes: next.maxHeaderBytes, keep: next.keep, retireAbove: next.retireAbove })
109
+ if (!mounted.current) return
110
+ setG(v)
111
+ setNote(v.kind === 'noop' ? t('guard.noop') : t('guard.saved'))
112
+ } catch (error) {
113
+ if (mounted.current) {
114
+ setG(prev)
115
+ setNote(render(t('state.failed'), { message: String((error as Error).message ?? error) }))
116
+ }
117
+ } finally {
118
+ if (mounted.current) setBusy(false)
119
+ }
120
+ }
121
+ const inputStyle = { width: 72, padding: '2px 6px', border: '1px solid var(--dsw-color-border)', borderRadius: 6, background: 'var(--dsw-color-surface)', color: 'var(--dsw-color-text)' } as const
122
+ return (
123
+ <div style={{ display: 'grid', gap: 6, marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--dsw-color-border)' }}>
124
+ <div style={{ fontWeight: 600 }}>{t('guard.title')}</div>
125
+ <label style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
126
+ <input type="checkbox" checked={g.runtimeGuard} disabled={busy} onChange={(e) => void commit({ ...g, runtimeGuard: e.target.checked })} />
127
+ {t('guard.enable')}
128
+ </label>
129
+ <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: '0.9em' }}>
130
+ {t('guard.retireAbove')}
131
+ <input type="number" min={0} max={10000} value={g.retireAbove} disabled={busy}
132
+ onChange={(e) => setG({ ...g, retireAbove: toInt(e) })}
133
+ onBlur={() => void commit(g)}
134
+ onKeyDown={(e) => { if (e.key === 'Enter') void commit(g) }}
135
+ style={inputStyle} />
136
+ </label>
137
+ <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: '0.9em' }}>
138
+ {t('guard.keep')}
139
+ <input type="number" min={1} max={64} value={g.keep} disabled={busy}
140
+ onChange={(e) => setG({ ...g, keep: toInt(e) })}
141
+ onBlur={() => void commit(g)}
142
+ onKeyDown={(e) => { if (e.key === 'Enter') void commit(g) }}
143
+ style={inputStyle} />
144
+ </label>
145
+ {busy || note !== '' ? <div style={{ fontSize: '0.85em', color: busy ? 'var(--dsw-color-muted)' : 'var(--dsw-color-primary)' }}>{busy ? t('state.busy') : note}</div> : null}
146
+ </div>
147
+ )
148
+ }
149
+
85
150
  export function PatchCard({ t }: CardProps): React.ReactElement {
86
151
  const [state, setState] = React.useState<CheckView | undefined>(undefined)
87
152
  const [busy, setBusy] = React.useState<'' | 'check' | 'fix' | 'revert'>('')
@@ -171,6 +236,8 @@ export function PatchCard({ t }: CardProps): React.ReactElement {
171
236
  : null}
172
237
  {/* cookie 库读数(见 CookieLine:读得到就给实时值,读不到才说 busy) */}
173
238
  <CookieLine cookie={state?.cookie} t={t} />
239
+ {/* 运行期守护:开关 + 两个阈值(写本插件自己那行,写后回显生效值) */}
240
+ <GuardPanel t={t} />
174
241
  {/* 审计行:修复前根本没有覆盖行时(快照里无旧值),不能说“修复前 ?”——
175
242
  那是把“无据”伪装成一个值;改说“此前无覆盖行”。 */}
176
243
  {state?.lastFix
@@ -44,6 +44,13 @@ const CHROME: Record<string, Record<PatchLang, string>> = {
44
44
  'revert.done': t('已回滚:{changed}', 'rolled back: {changed}', 'ロールバック済み:{changed}', '되돌림: {changed}', 'annulé : {changed}', 'zurückgerollt: {changed}', 'ripristinato: {changed}', 'откатлено: {changed}', 'revertido: {changed}'),
45
45
  'revert.none': t('没有可回滚的快照(修复一次才会留一份)', 'no snapshot to roll back (a successful fix keeps one)', '回滚用スナップショット無し(修復成功時に 1 件保存)', '롤백 스냅샷 없음(복구 성공 시 1개 보관)', 'aucun instantané à restaurer (une réparation réussie en garde un)', 'kein Snapshot zum Zurückrollen (ein erfolgreicher Fix hinterlässt einen)', 'nessuno snapshot da ripristinare (una correzione riuscita ne conserva uno)', 'нет снимка для отката (успешное исправление сохраняет один)', 'no hay instantánea a la que volver (una reparación correcta guarda una)'),
46
46
  'lastCheck': t('最近体检:{at}', 'last check: {at}', '最近の点検:{at}', '마지막 점검: {at}', 'dernier contrôle : {at}', 'letzte Prüfung: {at}', 'ultimo controllo: {at}', 'последняя проверка: {at}', 'última revisión: {at}'),
47
+ 'guard.title': t('运行期守护(Set-Cookie 退休旧 cookie)', 'Runtime guard (retire stale cookies via Set-Cookie)', 'ランタイム守護(Set-Cookie で古い cookie を引退)', '런타임 가드 (Set-Cookie 로 오래된 cookie 정리)', 'Garde en direct (retirer les vieux cookies via Set-Cookie)', 'Laufzeit-Wächter (alte Cookies via Set-Cookie entfernen)', 'Guardia runtime (ritira i cookie vecchi via Set-Cookie)', 'Страж (удаление старых cookie через Set-Cookie)', 'Guardia en ejecución (retirar cookies viejas vía Set-Cookie)'),
48
+ 'guard.enable': t('启用运行期守护', 'Enable runtime guard', 'ランタイム守護を有効化', '런타임 가드 켜기', 'Activer la garde en direct', 'Laufzeit-Wächter aktivieren', 'Abilita la guardia runtime', 'Включить стража', 'Activar guardia en ejecución'),
49
+ 'guard.retireAbove': t('触发阈值(条数 > 此值才退休,0=不设阈值)', 'Trigger threshold (retire only when count > this; 0 = no threshold)', '発動しきい値(件数 > この値で引退、0=なし)', '발동 임계값(개수 > 이 값이면 정리, 0=없음)', 'Seuil de déclenchement (retirer si nombre > cette valeur ; 0 = aucun)', 'Auslöseschwelle (erst wenn Anzahl > dieser Wert; 0 = keine)', 'Soglia di attivazione (ritira se conteggio > valore; 0 = nessuna)', 'Порог срабатывания (удалять если число > значения; 0 = нет)', 'Umbral de disparo (retirar si cantidad > valor; 0 = ninguno)'),
50
+ 'guard.keep': t('保留尾部条数(keep)', 'Keep tail count (keep)', '末尾保持件数(keep)', '꼬리 유지 개수(keep)', 'Nombre conservé en queue (keep)', 'Anzahl am Ende behalten (keep)', 'Numero mantenuto in coda (keep)', 'Держать в хвосте (keep)', 'Cantidad retenida en cola (keep)'),
51
+ 'guard.saved': t('已写入守护设置(HMR 热生效)', 'guard settings written (applies via HMR)', '守護設定を書き込みました(HMR で反映)', '가드 설정 기록됨(HMR 적용)', 'réglages de la garde écrits (appliqués par HMR)', 'Wächter-Einstellungen geschrieben (via HMR)', 'impostazioni della guardia scritte (via HMR)', 'настройки стража записаны (через HMR)', 'ajustes de la guardia escritos (vía HMR)'),
52
+ 'guard.noop': t('无变化,未写入', 'no change, nothing written', '変更なし、書き込みなし', '변경 없음, 기록 안 함', 'aucun changement', 'keine Änderung', 'nessun cambiamento', 'без изменений', 'sin cambios'),
53
+ 'guard.unavailable': t('当前宿主拿不到本插件配置行(无 config-editor),无法在面板改守护设置', 'the host exposes no editable row for this plugin; cannot change guard settings here', 'このホストでは本プラグインの設定行を取得できず、パネルでは変更不可', '이 호스트에서 플러그인 설정 행을 얻을 수 없어 패널에서 변경 불가', 'cet hôte n\'expose pas de ligne éditable pour ce plugin', 'dieser Host hat keine editierbare Zeile für dieses Plugin', 'questo host non espone una riga modificabile per il plugin', 'этот хост не даёт редактируемую строку плагина', 'este host no expone una fila editable para este plugin'),
47
54
  }
48
55
 
49
56
  /** 把共享判定表压平成 `p.P5` 形态的键(宿主只回 code,语言由界面决定)。 */
@@ -13,8 +13,22 @@ export const routes = {
13
13
  check: '/api/dsh-cookie-cleaner/patch/check',
14
14
  fix: '/api/dsh-cookie-cleaner/patch/fix',
15
15
  revert: '/api/dsh-cookie-cleaner/patch/revert',
16
+ guardGet: '/api/dsh-cookie-cleaner/guard/get',
17
+ guardSet: '/api/dsh-cookie-cleaner/guard/set',
16
18
  } as const
17
19
 
20
+ /** 运行期守护当前生效值(面板开关 + 两个阈值)。 */
21
+ export interface GuardView {
22
+ available?: boolean
23
+ runtimeGuard: boolean
24
+ maxHeaderBytes: number
25
+ keep: number
26
+ retireAbove: number
27
+ kind?: string
28
+ changed?: string[]
29
+ message?: string
30
+ }
31
+
18
32
  /** 宿主统一信封:`{ok, value}` 或 `{ok:false, code, message}`。 */
19
33
  export interface BridgeReply<T> {
20
34
  ok?: boolean
package/src/core.js CHANGED
@@ -291,16 +291,29 @@ function assertSafeIdentifiers(hostKeys, prefix) {
291
291
  /**
292
292
  * 删除语句 + 绑定参数。`expiredOnly` 走参数绑定(时间戳不拼字符串),
293
293
  * 且以 BigInt 绑定——微秒时间戳超出 2^53。
294
+ *
295
+ * `olderThanHours`:只删 `creation_utc` 早于“现在 - N 小时”的条目(按**创建时间**清理,
296
+ * 不是按过期时间)。这条路径只有离线 CLI 能跑——它直连 SQLite 读得到 `creation_utc`;
297
+ * 运行期守护走 HTTP 读不到创建时间,所以守护侧没有这个开关。
298
+ * 可与 `expiredOnly` 叠加(AND,更保守)。
294
299
  * @returns {{sql:string, values:Array<bigint|string>}}
295
300
  */
296
- export function buildDeleteStatement({ expiredOnly = false, hostKeys = LOOPBACK_HOST_KEYS, prefix = AUTH_COOKIE_PREFIX } = {}) {
301
+ export function buildDeleteStatement({ expiredOnly = false, olderThanHours = 0, hostKeys = LOOPBACK_HOST_KEYS, prefix = AUTH_COOKIE_PREFIX } = {}) {
297
302
  assertSafeIdentifiers(hostKeys, prefix)
298
303
  const hosts = hostKeys.map((key) => `'${key}'`).join(', ')
299
- const where = `host_key IN (${hosts}) AND name LIKE ?`
304
+ const conds = [`host_key IN (${hosts})`, 'name LIKE ?']
305
+ const values = [`${prefix}%`]
300
306
  if (expiredOnly) {
301
- return { sql: `DELETE FROM cookies WHERE ${where} AND expires_utc > 0 AND expires_utc <= ?`, values: [`${prefix}%`, BigInt(windowsNowMicroseconds())] }
307
+ conds.push('expires_utc > 0', 'expires_utc <= ?')
308
+ values.push(BigInt(windowsNowMicroseconds()))
309
+ }
310
+ const hours = Number(olderThanHours)
311
+ if (Number.isFinite(hours) && hours > 0) {
312
+ // creation_utc 也是 Chromium 微秒时间戳;阈值 = 现在 - N 小时(Number 在 1e16 量级误差仅微秒级)
313
+ conds.push('creation_utc > 0', 'creation_utc <= ?')
314
+ values.push(BigInt(windowsNowMicroseconds() - Math.round(hours * 3_600_000_000)))
302
315
  }
303
- return { sql: `DELETE FROM cookies WHERE ${where}`, values: [`${prefix}%`] }
316
+ return { sql: `DELETE FROM cookies WHERE ${conds.join(' AND ')}`, values }
304
317
  }
305
318
 
306
319
  /** 表结构自检:不是 Chromium cookie 库就收手,绝不对未知库执行写语句。 */
@@ -373,7 +386,7 @@ export function statCookies({ userDataRoot = '', explicitPath = '', env = proces
373
386
  */
374
387
  export function cleanCookies(options = {}) {
375
388
  const {
376
- expiredOnly = false, noBackup = false, noVacuum = false, dryRun = false,
389
+ expiredOnly = false, olderThanHours = 0, noBackup = false, noVacuum = false, dryRun = false,
377
390
  explicitPath = '', userDataRoot = '', env = process.env, sqlite,
378
391
  timestamp = () => defaultTimestamp(), platform = process.platform,
379
392
  copyFile = (from, to) => fs.copyFileSync(from, to),
@@ -386,7 +399,7 @@ export function cleanCookies(options = {}) {
386
399
  }
387
400
  }
388
401
  const target = found[0]
389
- const { sql, values } = buildDeleteStatement({ expiredOnly })
402
+ const { sql, values } = buildDeleteStatement({ expiredOnly, olderThanHours })
390
403
  const selectSql = sql.replace('DELETE FROM', 'SELECT COUNT(*) AS c FROM')
391
404
  const handle = openDatabase(target.path, { write: true, sqlite, platform })
392
405
  try {
@@ -394,7 +407,7 @@ export function cleanCookies(options = {}) {
394
407
  const wouldDelete = Number(handle.prepare(selectSql).get(...values).c)
395
408
  if (dryRun) {
396
409
  handle.exec('ROLLBACK')
397
- return { ok: true, dryRun: true, path: target.path, bytes: target.bytes, wouldDelete, sql, expiredOnly }
410
+ return { ok: true, dryRun: true, path: target.path, bytes: target.bytes, wouldDelete, sql, expiredOnly, olderThanHours }
398
411
  }
399
412
  let backup = ''
400
413
  const backupSidecars = []
@@ -433,7 +446,7 @@ export function cleanCookies(options = {}) {
433
446
  }
434
447
  return {
435
448
  ok: true, dryRun: false, path: target.path, beforeBytes: target.bytes, afterBytes,
436
- deleted, backup, backupSidecars, skippedSidecars, sql, expiredOnly,
449
+ deleted, backup, backupSidecars, skippedSidecars, sql, expiredOnly, olderThanHours,
437
450
  }
438
451
  } catch (e) {
439
452
  try { handle.exec('ROLLBACK') } catch { /* 事务已结束,忽略 */ }
package/src/i18n.js CHANGED
@@ -39,13 +39,14 @@ const zh = Object.freeze({
39
39
  cleanFooter: ' 默认档删全部 dsh-auth-*;--expired-only 只删已过期的;写盘前自动留 .bak 副本。',
40
40
  statClean: '干净:{path}(共 {total} 条 cookie,无 dsh-auth-* 残留)',
41
41
  statBusy: '无法读取(客户端正在运行,库被 Chromium 独占):{path}',
42
-
42
+
43
43
  statMissing: 'cookie 库不在这个位置(客户端从未起过、或装在了别处):{path}',
44
44
  statPermission: '无权限读取 cookie 库(目录位置不对或文件不属于当前用户):{path}',
45
45
  statFound: '发现 {count} 条 dsh-auth-*(已过期 {expired} / 未过期 {live}),分布在 {hosts} 个 host_key,库大小 {bytes} B:{path}',
46
46
  deleted: '已删除 {count} 条 dsh-auth-*({scope})',
47
47
  scopeAll: '全部',
48
48
  scopeExpired: '仅已过期',
49
+ scopeOlderThan: '创建超过 {hours} 小时',
49
50
  dbSize: ' 库:{path} {before} B → {after} B',
50
51
  backup: ' 备份:{backup}',
51
52
  backupWith: '(含 {sidecars})',
@@ -61,7 +62,7 @@ const zh = Object.freeze({
61
62
  openFailed: '无法打开 cookie 库:{path}',
62
63
  reason: ' 原因:{reason}',
63
64
  adviseBusy: ' 处置:这个库在客户端运行期间被 Chromium 独占。请{exit},再执行本命令。',
64
-
65
+
65
66
  adviseMissing: ' 处置:文件不在这里(可能路径变了、客户端从未起过、或被标记删除)。用 --db=<完整路径> 指向实际的 cookie 库。',
66
67
  advisePermission: ' 处置:当前用户读不了这个文件(权限或属主问题)。确认它属于跑本命令的账号;flatpak/snap 安装的库不在常规位置,用 --db=<完整路径> 指出。',
67
68
  adviseOwner: ' 处置:这个文件属于另一个用户(不是跑本命令的你)。用那个账号跑,或用 --db=<完整路径> 指向你自己那份库。',
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
- let stat
88
- try {
89
- stat = statCookies({ userDataRoot: cfg.userDataRoot })
90
- } catch (e) {
91
- stat = { verdict: 'error', message: e && e.message ? e.message : String(e) }
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
- return { stat, text: cookieCleanerCommandText(stat, { ...cfg, lang: undefined }) }
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: () => statCookiesLive({ userDataRoot: current().userDataRoot }),
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(() => statCookies({ userDataRoot: current().userDataRoot }))
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
- return { text: patchReportText({ ...guard.check(opts), cookie: cookieBriefForCommand() }) }
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 { kind: 'success', text }
369
+ return reply('success', `patch ${sub}`, text)
206
370
  }
207
371
  const mode = tokens[0] === 'clean' ? 'clean' : 'status'
208
- const { text } = status({ mode })
209
- return { kind: 'success', text }
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 { kind: 'error', text: `cookie-cleaner 失败: ${e && e.message ? e.message : String(e)}` }
386
+ return reply('error', tokens[0] ?? 'status', `cookie-cleaner 失败: ${e && e.message ? e.message : String(e)}`)
212
387
  }
213
388
  },
214
389
  })