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.
package/src/api-routes.js CHANGED
@@ -1,10 +1,13 @@
1
1
  /**
2
- * dsh-cookie-cleaner — 卡片到宿主的桥路由(四个端点,全部 POST-only)。
2
+ * dsh-cookie-cleaner — 卡片到宿主的桥路由(三个端点,全部 POST-only)。
3
3
  *
4
4
  * 为什么走 `/api` 而不是 typert RPC:第三方卡片的宿主侧数据面在 perm-gate/free-search 上
5
5
  * 已跑通这一形态(`webServer.register({kind:'exact'})` + fetch POST),且面板只需几个
6
6
  * 幂等动作,不值得为它引入 remote 服务面。
7
7
  *
8
+ * **没有端口写端点**(用户裁决 2026-11-05):本插件只改配置里的 cookie 有效期,
9
+ * 端口属启动行为面,面板与命令面都不再提供写入(面板不调它时留个写端点只是攻击面)。
10
+ *
8
11
  * 路由派生式与 `src/client/routes.ts` **必须逐字符一致**,由 `tests/api-routes.test.js`
9
12
  * 用同一段字面量在两份源里双向核对——两半各持一份派生式而测试不钉,是 URL 漂移的老坑。
10
13
  */
@@ -12,12 +15,11 @@
12
15
  /** 命名空间 = npm 包名(settings ns、卡 id、桥路径三处同串)。 */
13
16
  export const NS = 'dsh-cookie-cleaner'
14
17
 
15
- /** 四条路由:体检 / 修复 / 应用端口 / 回滚。 */
18
+ /** 三条路由:体检 / 修复 / 回滚。(端口写入只走命令面,面板不提供控件,所以不开写端点) */
16
19
  export function bridgeRoutesFor(ns = NS) {
17
20
  return Object.freeze({
18
21
  check: `/api/${ns}/patch/check`,
19
22
  fix: `/api/${ns}/patch/fix`,
20
- port: `/api/${ns}/patch/port`,
21
23
  revert: `/api/${ns}/patch/revert`,
22
24
  })
23
25
  }
@@ -52,10 +54,12 @@ function readJsonBody(req) {
52
54
  }
53
55
 
54
56
  /**
55
- * cookie 库现状只留卡片需要看的字段(运行期必然 busy,不能谎报条数)。
57
+ * cookie 库现状只留卡片需要看的字段。
58
+ * 读得到就带真实条数与请求头占用折算(`header`),并带出它是实时还是借句柄快照;
59
+ * 读不到才只给 verdict/reason,不能谎报条数。
56
60
  * @param {() => any} [stat]
57
61
  */
58
- function cookieBrief(stat) {
62
+ export function cookieBrief(stat) {
59
63
  if (typeof stat !== 'function') return undefined
60
64
  try {
61
65
  const s = stat()
@@ -67,6 +71,11 @@ function cookieBrief(stat) {
67
71
  authCookies: s.authCookies,
68
72
  totalCookies: s.totalCookies,
69
73
  bytes: s.bytes,
74
+ header: s.header,
75
+ source: s.source,
76
+ snapshot: s.snapshot === true,
77
+ liveUnavailable: s.liveUnavailable === true,
78
+ liveReason: s.liveReason,
70
79
  }
71
80
  } catch { return undefined }
72
81
  }
@@ -74,8 +83,8 @@ function cookieBrief(stat) {
74
83
  /**
75
84
  * 注册路由。
76
85
  * @param {unknown} webServer `webServer` 服务实例(只要求有 register)
77
- * @param {{check:(o:object)=>object, plan:(o:object)=>object, fix:(o:object)=>Promise<object>, applyPort:(o:object)=>Promise<object>, revert:()=>Promise<object>}} guard
78
- * @param {{lang?:string, targetDays?:number, guardMode?:string, port?:number, cookie?:() => any}} [defaults] 宿主设置里的默认档
86
+ * @param {{check:(o:object)=>object, plan:(o:object)=>object, fix:(o:object)=>Promise<object>, revert:()=>Promise<object>}} guard
87
+ * @param {{lang?:string, targetDays?:number, guardMode?:string, cookie?:() => any}} [defaults] 宿主设置里的默认档
79
88
  * @returns {Array<() => void>} 注销函数
80
89
  */
81
90
  export function registerPatchRoutes(webServer, guard, defaults = {}) {
@@ -101,8 +110,6 @@ export function registerPatchRoutes(webServer, guard, defaults = {}) {
101
110
  targetDays: Number.isInteger(body?.targetDays) && body.targetDays >= 1 ? body.targetDays : defaults.targetDays,
102
111
  guardMode: body?.guardMode === 'expression' ? 'expression' : defaults.guardMode,
103
112
  lang: typeof body?.lang === 'string' ? body.lang : defaults.lang,
104
- // 端口不预填:body 没给就回退到设置值(可能是 0=未设定),合法/非法的取舍在守卫里做
105
- port: Number.isInteger(body?.port) && body.port >= 1 ? body.port : defaults.port,
106
113
  }
107
114
  const value = await run(options)
108
115
  sendJson(res, 200, { ok: true, value })
@@ -116,10 +123,11 @@ export function registerPatchRoutes(webServer, guard, defaults = {}) {
116
123
  endpoint(routes.check, (options) => {
117
124
  const result = guard.check(options)
118
125
  const cookie = cookieBrief(defaults.cookie)
119
- return cookie === undefined ? result : { ...result, cookie }
126
+ // 目标寿命跟结果同屏:面板要说清「修复按钮写的是哪个值」,不让用户去猜设置里那一格
127
+ const withTarget = { ...result, targetDays: options.targetDays ?? defaults.targetDays }
128
+ return cookie === undefined ? withTarget : { ...withTarget, cookie }
120
129
  })
121
130
  endpoint(routes.fix, (options) => guard.fix(options))
122
- endpoint(routes.port, (options) => guard.applyPort(options))
123
131
  endpoint(routes.revert, () => guard.revert())
124
132
  return offs
125
133
  }
package/src/cli.js CHANGED
@@ -19,7 +19,7 @@ import { LANGS, detectLang, normalize, translator } from './i18n.js'
19
19
  import { offlineCheck } from './patch-guard.js'
20
20
  import { renderPlanBlock } from './patch-model.js'
21
21
  import { findOverrideRow, readPatchFile } from './patch-read.js'
22
- import { patchReportText } from './report.js'
22
+ import { cookieLiveText, patchReportText } from './report.js'
23
23
 
24
24
  const HERE = path.dirname(fileURLToPath(import.meta.url))
25
25
 
@@ -154,8 +154,13 @@ function main() {
154
154
  }
155
155
  try {
156
156
  if (!options.clean) {
157
+ // CLI 不借句柄:它是独立进程,镜像名与桌面端不同(目标进程匹配不上),
158
+ // 而且一个命令行工具不该去扫全机句柄表。要运行期水位就看面板。
157
159
  const stat = core.statCookies({ explicitPath, env })
158
160
  process.stdout.write(core.describeStat(stat) + '\n')
161
+ // 占用折算单独一句:describeStat 保持「一句话」契约,但数字不能缺席(与面板同一函数同一句)。
162
+ const live = cookieLiveText(stat)
163
+ if (live !== undefined) process.stdout.write(live + '\n')
159
164
  const exit = core.exitInstruction()
160
165
  if (stat.reason === 'busy') {
161
166
  process.stdout.write(nextLine('nextCliRerun', { exit }) + '\n')
@@ -46,12 +46,46 @@ function Row({ row, t }: { row: RowView; t: (key: string) => string }) {
46
46
  )
47
47
  }
48
48
 
49
+ /**
50
+ * cookie 读数行。四档不得混用一句:
51
+ * - 普通只读打开成功 → 实时值(条数 / 百分比 / 余量),过半转告警色、达阈值转危险色;
52
+ * - 借宿主句柄拿的快照 → 同一组数字但明说「非实时」(说成实时就是谎报);
53
+ * - 读得到但无折算(旧宿主半)→ 只给条数,不编造百分比;
54
+ * - 读不到 → 按原因分档:占用 / 权限 / 没找到。把后两者说成“被 Chromium 占”是误引导。
55
+ */
56
+ function CookieLine({ cookie, t }: { cookie?: CheckView['cookie']; t: (key: string) => string }) {
57
+ if (cookie === undefined) return null
58
+ const muted = { fontSize: '0.85em', color: 'var(--dsw-color-muted)' } as const
59
+ const unreadable = cookie.verdict === 'skipped' || cookie.reason === 'busy' || cookie.reason === 'permission' || cookie.reason === 'missing'
60
+ if (unreadable) {
61
+ const key = cookie.reason === 'missing' ? 'x.cookieMissing' : cookie.reason === 'permission' ? 'x.cookiePermission' : 'x.cookieBusy'
62
+ return <div style={muted}>{t(key)}</div>
63
+ }
64
+ const occupancy = cookie.header
65
+ if (occupancy === undefined) {
66
+ return <div style={muted}>{`${String(cookie.authCookies ?? '?')} dsh-auth-* / ${String(cookie.totalCookies ?? '?')} total`}</div>
67
+ }
68
+ const color = occupancy.over || occupancy.remaining <= 0
69
+ ? 'var(--dsw-color-danger)'
70
+ : occupancy.pct >= 50 ? 'var(--dsw-color-warning)' : 'var(--dsw-color-muted)'
71
+ return (
72
+ <div style={{ fontSize: '0.85em', color, lineHeight: 1.5 }}>
73
+ {render(t(cookie.snapshot === true ? 'x.cookieLiveSnapshot' : 'x.cookieLive'), {
74
+ count: String(cookie.authCookies ?? '?'),
75
+ total: String(cookie.totalCookies ?? '?'),
76
+ bytes: String(occupancy.bytes),
77
+ max: String(occupancy.maxHeaderBytes),
78
+ pct: String(occupancy.pct),
79
+ remaining: String(occupancy.remaining),
80
+ })}
81
+ </div>
82
+ )
83
+ }
84
+
49
85
  export function PatchCard({ t }: CardProps): React.ReactElement {
50
86
  const [state, setState] = React.useState<CheckView | undefined>(undefined)
51
- const [busy, setBusy] = React.useState<'' | 'check' | 'fix' | 'revert' | 'port'>('')
87
+ const [busy, setBusy] = React.useState<'' | 'check' | 'fix' | 'revert'>('')
52
88
  const [note, setNote] = React.useState('')
53
- // 端口不预填任何默认值:输入框开局为空,用户写了什么就写什么进表达式。
54
- const [portInput, setPortInput] = React.useState('')
55
89
  const mounted = React.useRef(true)
56
90
 
57
91
  React.useEffect(() => {
@@ -60,7 +94,7 @@ export function PatchCard({ t }: CardProps): React.ReactElement {
60
94
  return () => { mounted.current = false }
61
95
  }, [])
62
96
 
63
- async function run(action: 'check' | 'fix' | 'revert' | 'port'): Promise<void> {
97
+ async function run(action: 'check' | 'fix' | 'revert'): Promise<void> {
64
98
  setBusy(action)
65
99
  setNote('')
66
100
  try {
@@ -68,24 +102,6 @@ export function PatchCard({ t }: CardProps): React.ReactElement {
68
102
  const value = await postJson<CheckView>(routes.check, {})
69
103
  if (mounted.current) setState(value)
70
104
  }
71
- else if (action === 'port') {
72
- const value = await postJson<ActionView>(routes.port, { port: Number(portInput) })
73
- const fail = (message: string) => render(t('state.failed'), { message })
74
- // 结果文案全部取自 `x.*`(与宿主/CLI 同一张表),卡片不留第二份翻译。
75
- const outcome = value.kind === 'port-applied'
76
- ? `${render(t('x.portApplied'), { port: String(value.port ?? portInput), expr: value.expr ?? '' })}\n`
77
- + t(value.hotApplied === true ? 'x.portHot' : value.hotApplied === false ? 'x.portRestart' : 'x.portUnknown')
78
- + `\n${t('x.portSwitchWarn')}`
79
- : value.kind === 'port-busy' ? render(t('x.portBusy'), { port: String(value.port ?? portInput) })
80
- : value.kind === 'invalid-port' ? t('x.portInvalid')
81
- : value.kind === 'noop' ? t('fix.noop')
82
- : value.kind === 'blocked' ? render(t('fix.blocked'), { codes: value.codes ?? [] })
83
- : fail(value.message ?? value.kind)
84
- if (!mounted.current) return
85
- setNote(outcome)
86
- const after = value.result ?? await postJson<CheckView>(routes.check, {})
87
- if (mounted.current) setState(after)
88
- }
89
105
  else {
90
106
  const path = action === 'fix' ? routes.fix : routes.revert
91
107
  const value = await postJson<ActionView>(path, {})
@@ -116,21 +132,16 @@ export function PatchCard({ t }: CardProps): React.ReactElement {
116
132
  // 曾把这句写成 `rows.some(row => row.rowId==='connection' && row.actionable !== true) !== true`:
117
133
  // actionable 为真时 some() 本身就是 false,再取反反而把按钮锁死了(真机看到)。
118
134
  const conn = state?.rows?.find((row) => row.rowId === 'connection')
119
- const web = state?.rows?.find((row) => row.rowId === 'webserver')
120
135
  const canFix = offline !== true && conn?.actionable === true
121
136
  const canRevert = offline !== true
122
- // 端口:用户真填了合法值、且 webserver 行没有“写了也没用”的硬闸(P2/P6/P10/P11)才能点。
123
- const portNumber = Number(portInput)
124
- const portValid = /^\d+$/.test(portInput.trim()) && Number.isInteger(portNumber) && portNumber >= 1 && portNumber <= 65535
125
- const canPort = offline !== true && portValid && web?.blocked !== true
126
- const button = (action: 'check' | 'fix' | 'revert' | 'port', disabled = false) => (
137
+ const button = (action: 'check' | 'fix' | 'revert', disabled = false) => (
127
138
  <button
128
139
  type="button"
129
140
  disabled={busy !== '' || disabled}
130
141
  onClick={() => void run(action)}
131
142
  style={{ padding: '4px 10px', borderRadius: 6, border: '1px solid var(--dsw-color-border)', background: 'var(--dsw-color-surface)', color: 'var(--dsw-color-text)', cursor: busy === '' && !disabled ? 'pointer' : 'default' }}
132
143
  >
133
- {busy === action ? t('state.busy') : t(action === 'port' ? 'action.port' : `action.${action}`)}
144
+ {busy === action ? t('state.busy') : t(`action.${action}`)}
134
145
  </button>
135
146
  )
136
147
 
@@ -153,28 +164,13 @@ export function PatchCard({ t }: CardProps): React.ReactElement {
153
164
  {(state?.rows ?? []).some((row) => row.rowId === 'webserver' && (row.findings ?? []).length > 0)
154
165
  ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{t('note.webserver')}</div>
155
166
  : null}
156
- {/* 端口写入面:放在启动面(webserver)检查下方——它属于启动行为面,与 cookie 寿命(connection)无关。
157
- 只在“显式输入 + 显式点击”时动 webserver 行;写进去的是表达式 `ctx.webStartup.port ?? +<值>`,`--port` 仍优先。 */}
158
- <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap', marginTop: 4 }}>
159
- <input
160
- type="text"
161
- inputMode="numeric"
162
- placeholder={t('port.input')}
163
- aria-label={t('port.input')}
164
- value={portInput}
165
- onChange={(event) => setPortInput(event.target.value)}
166
- style={{ width: 110, padding: '5px 9px', borderRadius: 6, border: '1px solid var(--dsw-color-border)', background: 'var(--dsw-color-bg, var(--dsw-color-surface))', color: 'var(--dsw-color-text)', fontFamily: 'var(--dsw-font-mono, monospace)' }}
167
- />
168
- {button('port', !canPort)}
169
- </div>
170
- <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{t('port.help')}</div>
171
- {/* 常驻警告:端口热生效会把旧端口的当前页面踢下线,不提醒就会把用户锁在门外。 */}
172
- <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-warning, var(--dsw-color-muted))', lineHeight: 1.5 }}>{t('x.portSwitchWarn')}</div>
173
- {/* cookie 库读得到就给真实条数(客户端关着时就是这种);读不到才说 busy。
174
- 不能两者共用一句“需关客户端跑 CLI”——那会在已经显示条数时自相矛盾。 */}
175
- {state?.cookie && state.cookie.verdict !== 'skipped' && state.cookie.reason !== 'busy' && state.cookie.reason !== 'permission'
176
- ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{`${String(state.cookie.authCookies ?? '?')} dsh-auth-* / ${String(state.cookie.totalCookies ?? '?')} total`}</div>
177
- : <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{t('x.cookieBusy')}</div>}
167
+ {/* 真正有效的那一项:修复按钮写入的目标寿命(宿主设置里的 guardDays),跟结果同屏回显。
168
+ 面板不再提供端口控件:端口属启动行为面,需要时用命令面 `patch port <n>` 显式改。 */}
169
+ {state?.targetDays !== undefined
170
+ ? <div style={{ fontSize: '0.9em', color: 'var(--dsw-color-text)' }}>{render(t('x.targetDaysLine'), { days: String(state.targetDays) })}</div>
171
+ : null}
172
+ {/* cookie 库读数(见 CookieLine:读得到就给实时值,读不到才说 busy) */}
173
+ <CookieLine cookie={state?.cookie} t={t} />
178
174
  {/* 审计行:修复前根本没有覆盖行时(快照里无旧值),不能说“修复前 ?”——
179
175
  那是把“无据”伪装成一个值;改说“此前无覆盖行”。 */}
180
176
  {state?.lastFix
@@ -184,11 +180,6 @@ export function PatchCard({ t }: CardProps): React.ReactElement {
184
180
  : render(t('x.auditLine'), { at: state.lastFix.at ?? '?', before: state.lastFix.beforeDays, after: state.lastFix.targetDays ?? '?' })}
185
181
  </div>
186
182
  : null}
187
- {state?.lastPort
188
- ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>
189
- {render(t('port.audit'), { at: state.lastPort.at ?? '?', before: String(state.lastPort.before ?? '?'), port: String(state.lastPort.port ?? '?') })}
190
- </div>
191
- : null}
192
183
  {state?.checkedAt ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{render(t('lastCheck'), { at: state.checkedAt })}</div> : null}
193
184
  </div>
194
185
  )
@@ -26,11 +26,8 @@ const CHROME: Record<string, Record<PatchLang, string>> = {
26
26
  'action.check': t('体检', 'Check', '点検', '점검', 'Contrôler', 'Prüfen', 'Controlla', 'Проверить', 'Revisar'),
27
27
  'action.fix': t('修复', 'Fix', '修復', '복구', 'Réparer', 'Korrigieren', 'Correggi', 'Исправить', 'Reparar'),
28
28
  'action.revert': t('回滚', 'Revert', '戻す', '되돌리기', 'Annuler', 'Rückgängig', 'Ripristina', 'Отменить', 'Revertir'),
29
- 'action.port': t('应用端口', 'Apply port', 'ポート適用', '포트 적용', 'Appliquer le port', 'Port anwenden', 'Applica porta', 'Применить порт', 'Aplicar puerto'),
30
- 'port.input': t('目标端口', 'target port', '対象ポート', '대상 포트', 'port cible', 'Ziel-Port', 'porta di destinazione', 'целевой порт', 'puerto de destino'),
31
- // 不预填默认端口:这里只说“要填一个”,不说“默认是几”。
32
- 'port.help': t('留空则不改;填一个 1-65535 的端口后点「应用端口」,只改 webserver 行的 port 表达式(`--port` 仍优先)', 'leave empty to change nothing; type a port 1-65535 and press Apply port - only the webserver row\'s port expression is rewritten (`--port` still wins)', '空なら変更なし。1-65535 のポートを入れて「ポート適用」を押すと webserver 行の port 式のみ書き換わります(`--port` 優先)', '비워두면 변경 없음. 1-65535 포트를 넣고 "포트 적용"을 누르면 webserver 행의 port 표현식만 다시 씁니다(`--port` 우선)', 'laissez vide pour ne rien changer ; saisissez un port 1-65535 puis « Appliquer le port » - seule l\'expression du port de la ligne webserver est réécrite (`--port` gagne)', 'leer lassen ändert nichts; Port 1-65535 eingeben und „Port anwenden“ - nur der port-Ausdruck der webserver-Zeile wird umgeschrieben (`--port` bleibt oben)', 'lasciare vuoto per non cambiare nulla; inserire una porta 1-65535 e premere Applica porta - viene riscritta solo l\'espressione port della riga webserver (`--port` vince)', 'оставьте пустым чтобы не менять; введите порт 1-65535 и нажмите Применить порт — переписывается только выражение port строки webserver (`--port` важнее)', 'deje vacío para no cambiar nada; escriba un puerto 1-65535 y pulse Aplicar puerto: solo se reescribe la expresión port de la fila webserver (`--port` gana)'),
33
- 'port.audit': t('上次端口:{at}({before} → 现在 {port})', 'last port: {at} ({before} → now {port})', '前回のポート:{at}({before} → 現在 {port})', '마지막 포트: {at}({before} → 현재 {port})', 'dernier port : {at} ({before} → maintenant {port})', 'letzter Port: {at} ({before} → jetzt {port})', 'ultima porta: {at} ({before} → ora {port})', 'последний порт: {at} ({before} → теперь {port})', 'último puerto: {at} ({before} → ahora {port})'),
29
+ // 端口控件已从面板移除(真正有效的是 cookie 寿命注入),所以这里不再有 port.* 文案;
30
+ // 端口相关句子统一走 `x.*`(与宿主/CLI 同一张表)。
34
31
  'state.busy': t('进行中…', 'working…', '処理中…', '처리 중…', 'en cours…', 'läuft…', 'in corso…', 'выполняется…', 'en curso…'),
35
32
  'state.failed': t('动作失败:{message}', 'action failed: {message}', 'アクション失敗:{message}', '동작 실패: {message}', 'échec de l\'action : {message}', 'Aktion fehlgeschlagen: {message}', 'azione fallita: {message}', 'действие не удалось: {message}', 'acción falló: {message}'),
36
33
  'state.offline': t('宿主未提供 config-editor(老线或未装配),本面板无法在线体检/修复', 'the host exposes no config-editor (older line or not assembled); this panel cannot check or fix online', '宿主に config-editor が無く(旧ライン/未装配)、本パネルではオンライン点検・修復不可', '호스트에 config-editor가 없음(구 라인/미조립) → 이 패널에서 온라인 점검·복구 불가', 'l\'hôte n\'expose pas de config-editor (ancienne ligne ou non assemblé) ; ce panneau ne peut ni contrôler ni réparer', 'der Host stellt keinen config-editor bereit (ältere Zeile oder nicht montiert); dieses Panel kann nicht online prüfen oder korrigieren', 'l\'host non espone config-editor (linea vecchia o non assemblato); questo pannello non può controllare né correggere online', 'хост не даёт config-editor (старая линия или не собран); эта панель не может проверять или исправлять онлайн', 'el host no expone config-editor (línea antigua o no ensamblado); este panel no puede revisar ni reparar en línea'),
@@ -1,8 +1,10 @@
1
1
  /**
2
- * 卡片的数据臂:四条 POST 路由。
2
+ * 卡片的数据臂:三条 POST 路由。
3
3
  *
4
4
  * URL 与宿主侧 `src/api-routes.js` 的派生式**必须逐字符一致**——两半各写一份是事实,
5
5
  * 但一致性由 `tests/api-routes.test.js` 读两份源码比对钉住(漂移表现为卡片永远 404)。
6
+ *
7
+ * 没有 port:本插件只改 cookie 有效期,端口写入能力已整体删除(面板与命令面都不做)。
6
8
  */
7
9
 
8
10
  export const NS = 'dsh-cookie-cleaner'
@@ -10,7 +12,6 @@ export const NS = 'dsh-cookie-cleaner'
10
12
  export const routes = {
11
13
  check: '/api/dsh-cookie-cleaner/patch/check',
12
14
  fix: '/api/dsh-cookie-cleaner/patch/fix',
13
- port: '/api/dsh-cookie-cleaner/patch/port',
14
15
  revert: '/api/dsh-cookie-cleaner/patch/revert',
15
16
  } as const
16
17
 
@@ -47,12 +48,36 @@ export interface CheckView {
47
48
  documentPath?: string
48
49
  checkedAt?: string
49
50
  offline?: boolean
51
+ /** 修复按钮要写入的目标寿命(宿主设置里那个值,跟结果同屏回显) */
52
+ targetDays?: number
50
53
  /** 上次成功修复的留痕(面板重开也看得到,不只在这一瞬) */
51
54
  lastFix?: { at?: string | null; beforeDays?: number; targetDays?: number }
52
55
  /** 上次端口动作的留痕(写前值/目标值) */
53
56
  lastPort?: { at?: string | null; before?: unknown; port?: number }
54
- /** cookie 库现状:运行期必然 busy,卡片得把它说出来而不是隐掉 */
55
- cookie?: { verdict?: string; reason?: string; path?: string; authCookies?: number; totalCookies?: number; bytes?: number }
57
+ /** cookie 库现状:读得到就给条数与占用折算,读不到才给 reason */
58
+ cookie?: {
59
+ verdict?: string
60
+ reason?: string
61
+ path?: string
62
+ authCookies?: number
63
+ totalCookies?: number
64
+ bytes?: number
65
+ /** 读数来源:普通只读打开还是借句柄快照 */
66
+ source?: string
67
+ snapshot?: boolean
68
+ liveUnavailable?: boolean
69
+ liveReason?: string
70
+ header?: {
71
+ bytes: number
72
+ pct: number
73
+ rawPct: number
74
+ maxHeaderBytes: number
75
+ basis: string
76
+ threshold: number
77
+ remaining: number
78
+ over: boolean
79
+ }
80
+ }
56
81
  }
57
82
 
58
83
  export interface ActionView {
@@ -61,10 +86,6 @@ export interface ActionView {
61
86
  codes?: string[]
62
87
  message?: string
63
88
  effective?: number
64
- /** 端口动作:写进去的表达式与实际监听到了什么 */
65
- port?: number
66
- expr?: string
67
- hotApplied?: boolean
68
89
  result?: CheckView
69
90
  }
70
91
 
package/src/core.js CHANGED
@@ -24,6 +24,7 @@ import os from 'node:os'
24
24
  import path from 'node:path'
25
25
  import { createRequire } from 'node:module'
26
26
  import { exitFor, translator } from './i18n.js'
27
+ import { snapshotThroughHandle } from './jar-live.js'
27
28
  import './locales-dict.js'
28
29
 
29
30
  /** Cookie 名前缀:宿主 client-connection 生成(`COOKIE_PREFIX + sha256(authority)`)。 */
@@ -35,6 +36,44 @@ export const LOOPBACK_HOST_KEYS = Object.freeze(['127.0.0.1', 'localhost', '[::1
35
36
  /** Chromium 的 `expires_utc` 是自 1601-01-01 起的微秒数。 */
36
37
  const WINDOWS_EPOCH_OFFSET_MICROSECONDS = 11_644_473_600_000_000
37
38
 
39
+ /**
40
+ * 请求头占用折算:把「条数」翻成用户能直接判断的余量。
41
+ *
42
+ * 三个数各有出处,不是把上游报告的 228/229 当常数直接乘:
43
+ * - 上限 `16384` 是 Node `--max-http-header-size` 默认值(头顶过即 431,见上游 #11366 / #11410 / #11650);
44
+ * - `name` 列在 Chromium 库里是**明文**,所以 `SUM(LENGTH(name))` 是实测值;每条还多 `'='` 与 `'; '` 共 3 个分隔字节;
45
+ * - `value` 列存的是 OS 加密后的**密文**(比真正进请求头的明文长),拿它算体积会高估,
46
+ * 所以明文部分按上游三份报告一致的 173 B/条作估算,结果里带 `basis:'estimated'` 说清这不是精确值。
47
+ */
48
+ export const MAX_HEADER_BYTES = 16384
49
+ // 每条在 Cookie 头里的格式是 `name=value; ` → '=' 一个字节 + '; ' 两个字节 = 3。
50
+ // 上游三份报告的实测均为 52 + 1 + 173 + 2 = 228 B/条(#11366: 71 条 = 16,188 B),这里按同一口径对齐。
51
+ const HEADER_SEPARATOR_BYTES = 3
52
+ const VALUE_BYTES_ESTIMATE = 173
53
+ const NAME_LENGTH_FALLBACK = 52 // 'dsh-auth-' + base64url(sha256) 实测长度,仅在拿不到 SUM 时兜底
54
+
55
+ /** @param {{count:number, nameBytes?:number}} input @returns {{bytes:number,pct:number,rawPct:number,maxHeaderBytes:number,basis:string,threshold:number,remaining:number,over:boolean}} */
56
+ export function headerOccupancy({ count = 0, nameBytes }) {
57
+ const safeCount = Number.isFinite(count) && count > 0 ? Math.floor(count) : 0
58
+ const names = Number.isFinite(nameBytes) && nameBytes >= 0
59
+ ? nameBytes
60
+ : safeCount * NAME_LENGTH_FALLBACK
61
+ const bytes = names + (HEADER_SEPARATOR_BYTES + VALUE_BYTES_ESTIMATE) * safeCount
62
+ const rawPct = Math.round((bytes / MAX_HEADER_BYTES) * 1000) / 10
63
+ const average = safeCount > 0 ? bytes / safeCount : HEADER_SEPARATOR_BYTES + NAME_LENGTH_FALLBACK + VALUE_BYTES_ESTIMATE
64
+ const threshold = Math.floor(MAX_HEADER_BYTES / Math.max(1, average))
65
+ return {
66
+ bytes,
67
+ pct: Math.min(100, rawPct),
68
+ rawPct,
69
+ maxHeaderBytes: MAX_HEADER_BYTES,
70
+ basis: 'estimated',
71
+ threshold,
72
+ remaining: Math.max(0, threshold - safeCount),
73
+ over: bytes >= MAX_HEADER_BYTES,
74
+ }
75
+ }
76
+
38
77
  /** 打包的 desktop 应用名(Electron 由 package.json 的 name 派生 userData 目录)。 */
39
78
  const PRODUCT_DIR_NAMES = Object.freeze(['@deepseek-ai/dsh-desktop', 'DSH Desktop', 'deepseek-harness'])
40
79
 
@@ -295,6 +334,8 @@ export function statCookies({ userDataRoot = '', explicitPath = '', env = proces
295
334
  assertCookieSchema(handle)
296
335
  const total = toCount(handle.prepare('SELECT COUNT(*) AS c FROM cookies').get().c)
297
336
  const byHost = handle.prepare('SELECT host_key, COUNT(*) AS c FROM cookies GROUP BY host_key ORDER BY c DESC').all()
337
+ // 名字长度是实测部分(明文),所以单独聚一次给占用折算用
338
+ const nameAgg = handle.prepare('SELECT COALESCE(SUM(LENGTH(name)), 0) AS n FROM cookies WHERE name LIKE ?').get(`${AUTH_COOKIE_PREFIX}%`)
298
339
  const rows = handle.prepare('SELECT name, host_key, expires_utc FROM cookies WHERE name LIKE ? ORDER BY expires_utc DESC')
299
340
  .all(`${AUTH_COOKIE_PREFIX}%`)
300
341
  const now = BigInt(windowsNowMicroseconds())
@@ -315,6 +356,7 @@ export function statCookies({ userDataRoot = '', explicitPath = '', env = proces
315
356
  authExpired: expired,
316
357
  authLive: live,
317
358
  byHost: byHost.map((row) => ({ hostKey: String(row.host_key), count: toCount(row.c) })),
359
+ header: headerOccupancy({ count: rows.length, nameBytes: toCount(nameAgg.n) }),
318
360
  newestExpiry: rows.length > 0 ? formatChromiumTimestamp(rows[0].expires_utc) : '',
319
361
  oldestExpiry: rows.length > 0 ? formatChromiumTimestamp(rows[rows.length - 1].expires_utc) : '',
320
362
  }
@@ -405,6 +447,62 @@ function defaultTimestamp() {
405
447
  return new Date().toISOString().replace(/[-:]/g, '').replace(/\..+/, '').replace('T', '-')
406
448
  }
407
449
 
450
+ /** 借句柄快照的节流窗口(扫全机句柄表不免费)。 */
451
+ const LIVE_CACHE_MS = 60_000
452
+ const LIVE_MIN_GAP_MS = 5_000
453
+ /** 只缓存“哪个库的快照结果”,不缓存 cookie 内容本身。测试可传入自己的 store 隔离。 */
454
+ const liveCache = { at: Number.NEGATIVE_INFINITY, path: '', outcome: undefined }
455
+
456
+ /**
457
+ * 读数阶梯:先普通只读打开;只有因占用而读不到时,才去借目标进程已打开的句柄拿快照。
458
+ *
459
+ * 三条约束:
460
+ * - 快照结果必须带 `source:'borrowed-handle'` 与 `snapshot:true`,界面得说“不是实时”;
461
+ * - 借不到就原样返回 busy,**绝不把“没读到”洗成 0 条**;
462
+ * - 扫全机句柄表不免费:同一个库 60 秒内复用上一次结果,失败也至少隔 5 秒再试。
463
+ * @param {{read?:Function, snapshot?:Function, now?:()=>number, cacheMs?:number, minGapMs?:number, platform?:string, cache?:object}} [options] 余下选项透给读数函数
464
+ */
465
+ export function statCookiesLive(options = {}) {
466
+ const {
467
+ read = statCookies, snapshot = snapshotThroughHandle, now = () => Date.now(),
468
+ cacheMs = LIVE_CACHE_MS, minGapMs = LIVE_MIN_GAP_MS, platform = process.platform,
469
+ cache = liveCache,
470
+ ...stat
471
+ } = options
472
+ const plain = read(stat)
473
+ if (plain.reason !== 'busy' || typeof plain.path !== 'string' || platform !== 'win32') return plain
474
+ const stamp = now()
475
+ if (cache !== null && cache.path === plain.path && cache.outcome !== undefined) {
476
+ const fresh = stamp - cache.at < cacheMs && cache.outcome.snapshot === true
477
+ const cooling = stamp - cache.at < minGapMs
478
+ if (fresh || cooling) return { ...plain, ...cache.outcome }
479
+ }
480
+ let outcome
481
+ if (typeof snapshot !== 'function') {
482
+ outcome = { snapshot: false, liveUnavailable: true, liveReason: 'no-snapshotter' }
483
+ } else {
484
+ const borrowed = snapshot({ filePath: plain.path, now })
485
+ if (borrowed?.ok !== true) {
486
+ outcome = { snapshot: false, liveUnavailable: true, liveReason: borrowed?.reason ?? 'borrow-failed' }
487
+ } else {
488
+ try {
489
+ const snapStat = read({ ...stat, explicitPath: borrowed.snapshotPath })
490
+ outcome = snapStat.reason === 'busy' || snapStat.verdict === 'skipped'
491
+ ? { snapshot: false, liveUnavailable: true, liveReason: 'snapshot-unreadable' }
492
+ : { ...snapStat, path: plain.path, source: 'borrowed-handle', snapshot: true, snapshotBytes: borrowed.bytes }
493
+ } catch (e) {
494
+ outcome = { snapshot: false, liveUnavailable: true, liveReason: `snapshot-error-${String(e && e.code ? e.code : e.message)}` }
495
+ } finally {
496
+ try { fs.rmSync(borrowed.snapshotPath, { force: true }) } catch { /* 临时快照残留不影响读数 */ }
497
+ }
498
+ }
499
+ }
500
+ cache.at = stamp
501
+ cache.path = plain.path
502
+ cache.outcome = outcome
503
+ return { ...plain, ...outcome }
504
+ }
505
+
408
506
  /** 给 CLI / 命令共用的「现在是什么状况」一句话(把处置说全,避免二次求助)。 */
409
507
  export function describeStat(stat) {
410
508
  const t = translator(lang)
package/src/index.js CHANGED
@@ -12,11 +12,11 @@
12
12
  * 在客户端关闭、宿主插件不存在的那个时间窗里执行。
13
13
  */
14
14
  import z from '@deepseek-ai/schemastery'
15
- import { cookieCleanerCommandText, cleanCookies, patchOutcomeText, patchReportText, setLang, statCookies } from './report.js'
15
+ import { cookieCleanerCommandText, cleanCookies, patchOutcomeText, patchReportText, setLang, statCookies, statCookiesLive } from './report.js'
16
16
  import { LANGS, detectLang, normalize } from './i18n.js'
17
17
  import { installSettingsWaist } from './settings-waist.js'
18
18
  import { createPatchGuard } from './patch-guard.js'
19
- import { registerPatchRoutes } from './api-routes.js'
19
+ import { cookieBrief, registerPatchRoutes } from './api-routes.js'
20
20
 
21
21
  /** Cordis 插件名(与 cordis.patch.yml 的 id 一致)。 */
22
22
  export const name = 'cookie-cleaner'
@@ -29,18 +29,16 @@ export const DEFAULT_SETTINGS = Object.freeze({
29
29
  lang: '', // 输出语言(zh/en/ja/ko/fr/de/it/ru/es);空=跟环境探测,探不到则 zh
30
30
  guardDays: 1, // patch 体检的目标cookie 绝对寿命(宿主 schema 要求 ≥1)
31
31
  guardMode: 'literal', // 'literal'=只动目标键 | 'expression'=把 bundle 层的 !!js 表达式还原回去
32
- // 面板「应用端口」要写的回落端口。**0 = 未设定**:插件不预填任何具体端口值(不把哪个官方默认写进代码),
33
- // 没填就不会写。
34
- guardPort: 0,
32
+ // 没有 guardPort 设置项,也没有任何端口写入路径(用户裁决 2026-11-05):
33
+ // 本插件只改配置里的 cookie 有效期;端口属启动行为面,不在职责内。
35
34
  })
36
35
 
37
36
  export const Config = z.object({
38
37
  userDataRoot: z.string().default(DEFAULT_SETTINGS.userDataRoot).volatile().description('覆盖 Electron userData 根目录(默认按平台惯例自动定位)'),
39
38
  expiredOnly: z.boolean().default(DEFAULT_SETTINGS.expiredOnly).volatile().description('保守档:只统计/只提示已过期的 dsh-auth cookie'),
40
39
  lang: z.string().default(DEFAULT_SETTINGS.lang).volatile().description(`输出语言:${LANGS.join('/')}(留空=自动探测)`),
41
- guardDays: z.natural().min(1).default(DEFAULT_SETTINGS.guardDays).volatile().description('cookie 体检的目标绝对寿命(天);修复按钮就写这个值'),
40
+ guardDays: z.natural().min(1).default(DEFAULT_SETTINGS.guardDays).volatile().description('cookie 体检与修复写入的目标绝对寿命(天)——这是防 431 真正有效的那一项'),
42
41
  guardMode: z.string().default(DEFAULT_SETTINGS.guardMode).volatile().description("patch 修复形态:'literal' 只动目标键,'expression' 同时把 bundle 层的 !!js 表达式还原回去"),
43
- guardPort: z.natural().max(65535).default(DEFAULT_SETTINGS.guardPort).volatile().description('面板「应用端口」写入的回落端口(1-65535;0=未设定,不预填也不写)。写入形式是表达式,所以 `--port` 仍然优先'),
44
42
  })
45
43
 
46
44
  /** volatile 字段/字段级活引用解引出普通值。 */
@@ -106,7 +104,7 @@ export function apply(ctx, config = {}) {
106
104
  })
107
105
 
108
106
  // ── patch 体检/修复守卫(只在 configEditor 就绪后存在;老线回调不触发,插件其余面照常)──
109
- /** @type {{check:Function, plan:Function, fix:Function, revert:Function, applyPort:Function} | undefined} */
107
+ /** @type {{check:Function, plan:Function, fix:Function, revert:Function} | undefined} */
110
108
  let guard
111
109
  ctx.inject(['configEditor', 'webServer'], (sctx) => {
112
110
  const editor = typeof sctx.get === 'function' ? sctx.get('configEditor') : undefined
@@ -118,20 +116,31 @@ export function apply(ctx, config = {}) {
118
116
  const offs = registerPatchRoutes(server, guard, {
119
117
  targetDays: cfg.guardDays,
120
118
  guardMode: cfg.guardMode,
121
- // 端口不预填:用户没设就是 0(未设定),面板写时会被拒并提示先填
122
- port: cfg.guardPort,
119
+ // 端口不预填:面板不再提供控件,命令面必须当场给数(没给则由守卫拒写)
123
120
  lang: cfg.lang ? normalize(cfg.lang) : undefined,
124
- // cookie 库现状随体检一起回:运行期必然 busy,卡片要诚实呈现而不是隐掉
125
- cookie: () => statCookies({ userDataRoot: current().userDataRoot }),
121
+ // cookie 库现状随体检一起回:只有面板这条走阶梯(普通只读打开不行时才试借句柄快照)。
122
+ cookie: () => statCookiesLive({ userDataRoot: current().userDataRoot }),
126
123
  })
127
124
  if (offs.length === 0) return
128
125
  sctx.effect(() => () => offs.forEach((off) => { try { off() } catch { /* 已回收 */ } }), `${name}: patch routes`)
129
126
  })
130
127
 
128
+ /**
129
+ * cookie 读数(命令面专用):**只走普通只读打开,不借句柄**。
130
+ *
131
+ * 为什么不跟面板共用阶梯:扫一次全机句柄表只在“用户显式点了体检”时才值得,
132
+ * 而命令面/启动播报会被测试与脚本反复调用,拿它去做系统级扫描会直接卡住
133
+ * (真机实测:`patch check` 在命令面触发借句柄后整个测试文件超时)。
134
+ * 而且独立进程的镜像名与桌面端不同,目标进程本来就匹配不上——诚实回 busy。
135
+ */
136
+ function cookieBriefForCommand() {
137
+ return cookieBrief(() => statCookies({ userDataRoot: current().userDataRoot }))
138
+ }
139
+
131
140
  /** patch 子命令的统一入口(写只发生在这里——用户触发的回调链,不在 HMR 事务内)。 */
132
- async function runPatch(sub, overrides = {}) {
133
- const cfg = { ...current(), ...overrides }
134
- const opts = { targetDays: cfg.guardDays, guardMode: cfg.guardMode, port: cfg.guardPort }
141
+ async function runPatch(sub) {
142
+ const cfg = current()
143
+ const opts = { targetDays: cfg.guardDays, guardMode: cfg.guardMode }
135
144
  if (guard === undefined) {
136
145
  return { text: patchReportText({ reason: 'no-config-editor', rows: [] }, { lang: undefined }) }
137
146
  }
@@ -139,17 +148,13 @@ export function apply(ctx, config = {}) {
139
148
  const outcome = await guard.fix(opts)
140
149
  return { text: patchReportText(outcome.result ?? guard.check(opts), { outcome }) }
141
150
  }
142
- if (sub === 'port') {
143
- // 启动行为面:端口必须用户当场给出,不拿设置里的默认值当“没填也写”的借口。
144
- const outcome = await guard.applyPort(opts)
145
- return { text: patchReportText(outcome.result ?? guard.check(opts), { outcome }) }
146
- }
147
151
  if (sub === 'revert') {
148
152
  const outcome = await guard.revert()
149
153
  return { text: patchOutcomeText(outcome) }
150
154
  }
151
155
  if (sub === 'plan') return { text: patchReportText(guard.plan(opts)) }
152
- return { text: patchReportText(guard.check(opts)) }
156
+ // check 与面板同构:同一个 headerOccupancy 折算结果,两边不得各自算一套。
157
+ return { text: patchReportText({ ...guard.check(opts), cookie: cookieBriefForCommand() }) }
153
158
  }
154
159
 
155
160
  // ── /cookie-cleaner 命令(fail-open:commands 服务缺失只降级不 fatal)──
@@ -188,16 +193,15 @@ function registerCookieCleanerCommand(ctx, status, runPatch) {
188
193
  if (typeof commands?.register !== 'function') return undefined
189
194
  return commands.register({
190
195
  name: 'cookie-cleaner',
191
- description: '查看 DSH 客户端 cookie 库里的本地登录凭据(dsh-auth-*)并给出清理命令;`patch check|fix|revert|plan|port <n>` 体检/修复 profile 的 cordis.patch.yml。',
192
- input: { hint: '[status|clean] | patch [check|fix|revert|plan|port <n>]' },
196
+ description: '查看 DSH 客户端 cookie 库里的本地登录凭据(dsh-auth-*)并给出清理命令;`patch check|fix|revert|plan` 体检/修复 profile 的 cordis.patch.yml(只改 cookie 有效期)。',
197
+ input: { hint: '[status|clean] | patch [check|fix|revert|plan]' },
193
198
  handler: async (invocation) => {
194
199
  const tokens = String(invocation?.rawInput ?? '').trim().split(/\s+/).filter(Boolean)
195
200
  try {
196
201
  if (tokens[0] === 'patch') {
197
- const sub = ['check', 'fix', 'revert', 'plan', 'port'].includes(tokens[1]) ? tokens[1] : 'check'
198
- // `patch port 4300`:端口只从参数走,没给就交给守卫拒写(插件不代用户定端口)。
199
- const overrides = sub === 'port' && tokens[2] !== undefined ? { guardPort: Number(tokens[2]) } : {}
200
- const { text } = await runPatch(sub, overrides)
202
+ // 没有 `port` 子命令:本插件不写端口(启动行为面不在职责内)。
203
+ const sub = ['check', 'fix', 'revert', 'plan'].includes(tokens[1]) ? tokens[1] : 'check'
204
+ const { text } = await runPatch(sub)
201
205
  return { kind: 'success', text }
202
206
  }
203
207
  const mode = tokens[0] === 'clean' ? 'clean' : 'status'