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.
@@ -7,11 +7,11 @@
7
7
  import fs from 'node:fs'
8
8
  import path from 'node:path'
9
9
  import { fileURLToPath } from 'node:url'
10
- import { HOSTS, STATUS, orRange } from './hosts.mjs'
10
+ import { HOSTS, STATUS, ENGINES_RANGE, PEER_RANGE } from './hosts.mjs'
11
11
 
12
12
  const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
13
13
  const check = process.argv.includes('--check')
14
- const range = orRange(HOSTS)
14
+ const range = PEER_RANGE
15
15
  const releases = Object.fromEntries(HOSTS.map((host) => [host, STATUS]))
16
16
  const failures = []
17
17
 
@@ -33,9 +33,9 @@ function compare(label, actual, expected) {
33
33
  failures.push(`${label}: 与 scripts/hosts.mjs 不一致\n 期望 ${JSON.stringify(expected)}\n 实际 ${JSON.stringify(actual)}`)
34
34
  }
35
35
 
36
- compare('package.json#engines.dsh', pkg.engines?.dsh, range)
36
+ compare('package.json#engines.dsh', pkg.engines?.dsh, ENGINES_RANGE)
37
37
  compare('package.json#dsh.compatibility.dshReleases', pkg.dsh?.compatibility?.dshReleases, releases)
38
- compare('dsh.plugin.json#engines.dsh', manifest.engines?.dsh, range)
38
+ compare('dsh.plugin.json#engines.dsh', manifest.engines?.dsh, ENGINES_RANGE)
39
39
  compare('dsh.plugin.json#version', manifest.version, pkg.version)
40
40
  // 兼容性闸门只读 @deepseek-ai/dsh* 前缀的 peer range(不读 engines.dsh),
41
41
  // 一个都不能漏:少了宿主换代时不会拒载,而是装载后运行期报错。
@@ -58,7 +58,7 @@ if (check) {
58
58
  }
59
59
  } else if (failures.length > 0) {
60
60
  // 版本号以 package.json 为源,把同号刷进 dsh.plugin.json(不然改版本必遗漏一处,V1 闸抓不到)
61
- pkg.engines = { ...pkg.engines, dsh: range }
61
+ pkg.engines = { ...pkg.engines, dsh: ENGINES_RANGE }
62
62
  pkg.dsh = { ...pkg.dsh, compatibility: { ...pkg.dsh?.compatibility, dshReleases: releases } }
63
63
  // peer 表重建:保留非 dsh-scope 的 peer(如 cordis),dsh* 项一律等于 client.inject 集合与同一 range
64
64
  const kept = Object.fromEntries(Object.entries(pkg.peerDependencies ?? {}).filter(([name]) => !name.startsWith('@deepseek-ai/dsh')))
@@ -67,7 +67,7 @@ if (check) {
67
67
  const meta = Object.fromEntries(Object.entries(pkg.peerDependenciesMeta ?? {}).filter(([name]) => !name.startsWith('@deepseek-ai/dsh')))
68
68
  for (const name of clientPeers) meta[name] = { ...meta[name], optional: true }
69
69
  pkg.peerDependenciesMeta = meta
70
- manifest.engines = { ...manifest.engines, dsh: range }
70
+ manifest.engines = { ...manifest.engines, dsh: ENGINES_RANGE }
71
71
  if (manifest.version !== pkg.version) {
72
72
  manifest.version = pkg.version
73
73
  process.stdout.write(`dsh.plugin.json#version 同步为 ${pkg.version}\n`)
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=<完整路径> 指向你自己那份库。',