dsh-cookie-cleaner 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,125 @@
1
+ /**
2
+ * dsh-cookie-cleaner — 卡片到宿主的桥路由(四个端点,全部 POST-only)。
3
+ *
4
+ * 为什么走 `/api` 而不是 typert RPC:第三方卡片的宿主侧数据面在 perm-gate/free-search 上
5
+ * 已跑通这一形态(`webServer.register({kind:'exact'})` + fetch POST),且面板只需几个
6
+ * 幂等动作,不值得为它引入 remote 服务面。
7
+ *
8
+ * 路由派生式与 `src/client/routes.ts` **必须逐字符一致**,由 `tests/api-routes.test.js`
9
+ * 用同一段字面量在两份源里双向核对——两半各持一份派生式而测试不钉,是 URL 漂移的老坑。
10
+ */
11
+
12
+ /** 命名空间 = npm 包名(settings ns、卡 id、桥路径三处同串)。 */
13
+ export const NS = 'dsh-cookie-cleaner'
14
+
15
+ /** 四条路由:体检 / 修复 / 应用端口 / 回滚。 */
16
+ export function bridgeRoutesFor(ns = NS) {
17
+ return Object.freeze({
18
+ check: `/api/${ns}/patch/check`,
19
+ fix: `/api/${ns}/patch/fix`,
20
+ port: `/api/${ns}/patch/port`,
21
+ revert: `/api/${ns}/patch/revert`,
22
+ })
23
+ }
24
+
25
+ const MAX_BODY_BYTES = 64 * 1024
26
+
27
+ function sendJson(res, code, body) {
28
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
29
+ res.end(JSON.stringify(body))
30
+ }
31
+
32
+ /** 读 JSON body(有上限,超限直接拒——面板不该发大东西)。 */
33
+ function readJsonBody(req) {
34
+ return new Promise((resolve, reject) => {
35
+ const chunks = []
36
+ let size = 0
37
+ req.on('data', (chunk) => {
38
+ size += chunk.length
39
+ if (size > MAX_BODY_BYTES) {
40
+ reject(new Error('body too large'))
41
+ return
42
+ }
43
+ chunks.push(chunk)
44
+ })
45
+ req.on('end', () => {
46
+ if (chunks.length === 0) { resolve({}); return }
47
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))) }
48
+ catch (e) { reject(new Error(`invalid json body: ${e.message}`)) }
49
+ })
50
+ req.on('error', reject)
51
+ })
52
+ }
53
+
54
+ /**
55
+ * cookie 库现状只留卡片需要看的字段(运行期必然 busy,不能谎报条数)。
56
+ * @param {() => any} [stat]
57
+ */
58
+ function cookieBrief(stat) {
59
+ if (typeof stat !== 'function') return undefined
60
+ try {
61
+ const s = stat()
62
+ if (s === undefined || s === null) return undefined
63
+ return {
64
+ verdict: s.verdict,
65
+ reason: s.reason,
66
+ path: s.path,
67
+ authCookies: s.authCookies,
68
+ totalCookies: s.totalCookies,
69
+ bytes: s.bytes,
70
+ }
71
+ } catch { return undefined }
72
+ }
73
+
74
+ /**
75
+ * 注册路由。
76
+ * @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] 宿主设置里的默认档
79
+ * @returns {Array<() => void>} 注销函数
80
+ */
81
+ export function registerPatchRoutes(webServer, guard, defaults = {}) {
82
+ const register = typeof webServer?.register === 'function' ? webServer.register.bind(webServer) : undefined
83
+ if (register === undefined) return []
84
+ const routes = bridgeRoutesFor(defaults.ns ?? NS)
85
+ const offs = []
86
+
87
+ /** 统一的一跳:POST-only、参数从 body 取、异常包成结构化错误。 */
88
+ const endpoint = (path, run) => {
89
+ offs.push(register({
90
+ kind: 'exact',
91
+ path,
92
+ handler: (rawReq, rawRes) => {
93
+ const req = rawReq
94
+ const res = rawRes
95
+ if (req.method !== 'POST') {
96
+ sendJson(res, 405, { ok: false, code: 'method-not-allowed' })
97
+ return
98
+ }
99
+ readJsonBody(req).then(async (body) => {
100
+ const options = {
101
+ targetDays: Number.isInteger(body?.targetDays) && body.targetDays >= 1 ? body.targetDays : defaults.targetDays,
102
+ guardMode: body?.guardMode === 'expression' ? 'expression' : defaults.guardMode,
103
+ 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
+ }
107
+ const value = await run(options)
108
+ sendJson(res, 200, { ok: true, value })
109
+ }).catch((e) => {
110
+ sendJson(res, 200, { ok: false, code: 'internal', message: String(e && e.message ? e.message : e) })
111
+ })
112
+ },
113
+ }))
114
+ }
115
+
116
+ endpoint(routes.check, (options) => {
117
+ const result = guard.check(options)
118
+ const cookie = cookieBrief(defaults.cookie)
119
+ return cookie === undefined ? result : { ...result, cookie }
120
+ })
121
+ endpoint(routes.fix, (options) => guard.fix(options))
122
+ endpoint(routes.port, (options) => guard.applyPort(options))
123
+ endpoint(routes.revert, () => guard.revert())
124
+ return offs
125
+ }
package/src/cli.js CHANGED
@@ -9,10 +9,19 @@
9
9
  * 包是 ESM(宿主装载与 npm bin 都走 ESM),core 只有一份实现,两边共用。
10
10
  * 输出语言:--lang > DSH_COOKIE_LANG/DSH_LANG > LC_ALL/LANG > 系统 locale > zh。
11
11
  */
12
+ import os from 'node:os'
12
13
  import path from 'node:path'
13
14
  import process from 'node:process'
15
+ import { readFileSync } from 'node:fs'
16
+ import { fileURLToPath } from 'node:url'
14
17
  import * as core from './core.js'
15
18
  import { LANGS, detectLang, normalize, translator } from './i18n.js'
19
+ import { offlineCheck } from './patch-guard.js'
20
+ import { renderPlanBlock } from './patch-model.js'
21
+ import { findOverrideRow, readPatchFile } from './patch-read.js'
22
+ import { patchReportText } from './report.js'
23
+
24
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
16
25
 
17
26
  function usage() {
18
27
  return `dsh-cookie-cleaner — 清理 DSH 客户端留在 cookie 库里的本地登录凭据(dsh-auth-*)
@@ -30,13 +39,27 @@ function usage() {
30
39
  Linux ~/.config/@deepseek-ai/dsh-desktop/Network/Cookies
31
40
 
32
41
  其它:--no-backup 不产出 .bak 副本;--no-vacuum 不做 VACUUM 收缩;
33
- --lang <${LANGS.join('|')}> 指定输出语言(缺省跟随系统 locale)
34
- 退出码:0 成功;1 失败(库被占用/无权限/没找到/参数非法)
42
+ --lang <${LANGS.join('|')}> 指定输出语言(缺省跟随系统 locale);--version 只报包名与版本
43
+
44
+ patch 体检(profile 的 cordis.patch.yml 结构,不碰 cookie 库):
45
+ dsh-cookie-cleaner patch [check] 离线体检:行在不在、name 对不对、值合不合法、home 层影子
46
+ dsh-cookie-cleaner patch plan 输出可直接粘贴的覆盖行(目标值已就位)
47
+ --profile <name> 体检哪个 profile(默认 desktop)
48
+ --patch-file <路径> 直接指定 patch 文件(优先于 --profile)
49
+ --target-days <N> 目标 cookie 绝对寿命(≥ 1,默认 1)
50
+
51
+ 退出码:0 成功;1 失败(库被占用/无权限/没找到/参数非法/结构会失效)
35
52
  `
36
53
  }
37
54
 
55
+ /** DSH home(与 patch-guard 同式,不重复一套平台规则)。 */
56
+ function dshHomeOf(env) {
57
+ const explicit = String(env.DSH_HOME ?? '').trim()
58
+ return explicit !== '' ? explicit : path.join(os.homedir(), '.dsh')
59
+ }
60
+
38
61
  function parseArgs(argv) {
39
- const options = { clean: false, expiredOnly: false, dryRun: false, noBackup: false, noVacuum: false, db: '', lang: '', help: false }
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 }
40
63
  for (let i = 0; i < argv.length; i++) {
41
64
  const arg = argv[i]
42
65
  if (arg === '--clean') options.clean = true
@@ -45,9 +68,27 @@ function parseArgs(argv) {
45
68
  else if (arg === '--no-backup') options.noBackup = true
46
69
  else if (arg === '--no-vacuum') options.noVacuum = true
47
70
  else if (arg === '--help' || arg === '-h') options.help = true
71
+ else if (arg === '--version' || arg === '-v') options.version = true
48
72
  else if (arg.startsWith('--db=')) options.db = arg.slice('--db='.length)
49
73
  else if (arg === '--lang') options.lang = normalize(argv[++i] ?? '')
50
74
  else if (arg.startsWith('--lang=')) options.lang = normalize(arg.slice('--lang='.length))
75
+ else if (arg === '--profile') options.profile = String(argv[++i] ?? 'desktop')
76
+ else if (arg.startsWith('--profile=')) options.profile = arg.slice('--profile='.length)
77
+ else if (arg === '--patch-file') options.patchFile = String(argv[++i] ?? '')
78
+ else if (arg.startsWith('--patch-file=')) options.patchFile = arg.slice('--patch-file='.length)
79
+ else if (arg === '--target-days') options.targetDays = Number(argv[++i])
80
+ else if (arg.startsWith('--target-days=')) options.targetDays = Number(arg.slice('--target-days='.length))
81
+ else if (!arg.startsWith('-') && options.command === '' && !options.clean) {
82
+ // 位置参数只认 `patch`(cookie 面保持无子命令的原样,不破坏 0.1.x 用法习惯)
83
+ if (arg !== 'patch') {
84
+ process.stderr.write(`未知参数:${arg}\n\n${usage()}`)
85
+ process.exitCode = 1
86
+ return undefined
87
+ }
88
+ options.command = 'patch'
89
+ const next = argv[i + 1]
90
+ if (next === 'check' || next === 'plan') { options.sub = next; i += 1 }
91
+ }
51
92
  else {
52
93
  process.stderr.write(`未知参数:${arg}\n\n${usage()}`)
53
94
  process.exitCode = 1
@@ -57,6 +98,34 @@ function parseArgs(argv) {
57
98
  return options
58
99
  }
59
100
 
101
+ /** patch 子命令的离线路径:只读文件,**绝不写 profile**(写只属于面板/宿主命令)。 */
102
+ function runPatch(options) {
103
+ const file = options.patchFile !== ''
104
+ ? path.resolve(options.patchFile)
105
+ : path.join(dshHomeOf(process.env), 'profiles', options.profile, 'cordis.patch.yml')
106
+ if (!Number.isInteger(options.targetDays) || options.targetDays < 1) {
107
+ process.stderr.write(`--target-days 必须是 ≥ 1 的整数,实际:${String(options.targetDays)}\n`)
108
+ process.exitCode = 1
109
+ return
110
+ }
111
+ const result = offlineCheck({ profileFile: file, targetDays: options.targetDays })
112
+ if (options.sub === 'plan') {
113
+ const parsed = readPatchFile(file).parsed
114
+ const conn = findOverrideRow(parsed, 'connection')
115
+ process.stdout.write(renderPlanBlock({
116
+ rowId: 'connection',
117
+ inherited: {},
118
+ current: conn?.config ?? { trustedHosts: [], maxRequestBodyBytes: 314572800 },
119
+ targetDays: options.targetDays,
120
+ }) + '\n')
121
+ process.exitCode = parsed.ok ? 0 : 1
122
+ return
123
+ }
124
+ process.stdout.write(patchReportText(result) + '\n')
125
+ // 退出码黑名单:只有真读到且结构不是「会失效」的才算成功
126
+ process.exitCode = result.level === 'fail' || result.level === 'skipped' ? 1 : 0
127
+ }
128
+
60
129
  function main() {
61
130
  const options = parseArgs(process.argv.slice(2))
62
131
  if (options === undefined) return
@@ -66,8 +135,23 @@ function main() {
66
135
  process.stdout.write(usage())
67
136
  return
68
137
  }
138
+ if (options.version) {
139
+ // 版本号只从包内 package.json 读:装机别名报的号必须与包体同号(V1 闸的运行态对拍)
140
+ try {
141
+ const pkg = JSON.parse(readFileSync(path.join(HERE, '..', 'package.json'), 'utf8'))
142
+ process.stdout.write(`${pkg.name}@${pkg.version}\n`)
143
+ } catch (e) {
144
+ process.stderr.write(`读不到 package.json:${String(e && e.message ? e.message : e)}\n`)
145
+ process.exitCode = 1
146
+ }
147
+ return
148
+ }
69
149
  const explicitPath = options.db ? path.resolve(options.db) : ''
70
150
  const env = process.env
151
+ if (options.command === 'patch') {
152
+ runPatch(options)
153
+ return
154
+ }
71
155
  try {
72
156
  if (!options.clean) {
73
157
  const stat = core.statCookies({ explicitPath, env })
@@ -0,0 +1,195 @@
1
+ /**
2
+ * 面板卡片:体检 / 修复 / 回滚三个按钮 + P1-P12 明细。
3
+ *
4
+ * 三条纪律:
5
+ * 1. 文本全部走注入进来的 `t`(宿主 locale 服务),卡片自己不留一份语言常量;
6
+ * 2. 颜色/字号只用宿主主题令牌(`--dsw-*`),不写死色值——宿主换肤时卡片必须跟着变;
7
+ * 3. 动作结果一律**重跑体检回显**,不信「按钮点了=改好了」:修复后档位仍偏,就如实显示。
8
+ */
9
+ import * as React from 'react'
10
+
11
+ import { render } from './locales'
12
+ import { postJson, routes } from './routes'
13
+ import type { ActionView, CheckView, Finding, RowView } from './routes'
14
+
15
+ export interface CardProps {
16
+ /** 当前语言的取词函数(跟着宿主 locale 走,卡片不缓存旧值)。 */
17
+ t: (key: string) => string
18
+ }
19
+
20
+ const LEVEL_COLOR: Record<string, string> = {
21
+ ok: 'var(--dsw-color-success, var(--dsw-color-primary))',
22
+ warn: 'var(--dsw-color-warning)',
23
+ fail: 'var(--dsw-color-danger)',
24
+ skipped: 'var(--dsw-color-muted)',
25
+ }
26
+
27
+ function FindingLine({ finding, t }: { finding: Finding; t: (key: string) => string }) {
28
+ // 宿主只回 `{code, params}`,语言由界面定;占位符必须在卡片侧填——
29
+ // 直接显示 t('p.P1') 会把 `{current}` 这种半成品词交给用户(真机看到过)。
30
+ return <div style={{ marginLeft: 14, fontSize: '0.9em', lineHeight: 1.5 }}>· {render(t(`p.${finding.code}`), finding.params ?? {})}</div>
31
+ }
32
+
33
+ function Row({ row, t }: { row: RowView; t: (key: string) => string }) {
34
+ const label = row.rowId === 'connection' ? 'row.connection' : 'row.webserver'
35
+ return (
36
+ <div style={{ marginTop: 8 }}>
37
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
38
+ <span aria-label="verdict" style={{ width: 8, height: 8, borderRadius: 4, background: LEVEL_COLOR[row.level] ?? LEVEL_COLOR.skipped }} />
39
+ <b>{t(label)}</b>
40
+ <span style={{ color: LEVEL_COLOR[row.level] }}>{t(`level.${row.level}`)}</span>
41
+ </div>
42
+ {(row.findings ?? []).map((finding, index) => (
43
+ <FindingLine key={`${finding.code}-${String(index)}`} finding={finding} t={t} />
44
+ ))}
45
+ </div>
46
+ )
47
+ }
48
+
49
+ export function PatchCard({ t }: CardProps): React.ReactElement {
50
+ const [state, setState] = React.useState<CheckView | undefined>(undefined)
51
+ const [busy, setBusy] = React.useState<'' | 'check' | 'fix' | 'revert' | 'port'>('')
52
+ const [note, setNote] = React.useState('')
53
+ // 端口不预填任何默认值:输入框开局为空,用户写了什么就写什么进表达式。
54
+ const [portInput, setPortInput] = React.useState('')
55
+ const mounted = React.useRef(true)
56
+
57
+ React.useEffect(() => {
58
+ mounted.current = true
59
+ void run('check')
60
+ return () => { mounted.current = false }
61
+ }, [])
62
+
63
+ async function run(action: 'check' | 'fix' | 'revert' | 'port'): Promise<void> {
64
+ setBusy(action)
65
+ setNote('')
66
+ try {
67
+ if (action === 'check') {
68
+ const value = await postJson<CheckView>(routes.check, {})
69
+ if (mounted.current) setState(value)
70
+ }
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
+ else {
90
+ const path = action === 'fix' ? routes.fix : routes.revert
91
+ const value = await postJson<ActionView>(path, {})
92
+ const fail = (message: string) => render(t('state.failed'), { message })
93
+ const outcome = action === 'fix'
94
+ ? value.kind === 'fixed' ? render(t('fix.done'), { changed: value.changed ?? [] })
95
+ : value.kind === 'noop' ? t('fix.noop')
96
+ : value.kind === 'blocked' ? render(t('fix.blocked'), { codes: value.codes ?? [] })
97
+ : fail(value.message ?? value.kind)
98
+ : value.kind === 'reverted' ? render(t('revert.done'), { changed: value.changed ?? [] })
99
+ : value.kind === 'no-snapshot' ? t('revert.none')
100
+ : fail(value.message ?? value.kind)
101
+ if (!mounted.current) return
102
+ setNote(outcome)
103
+ // 动作后一律重读,不信单次返回值
104
+ const after = value.result ?? await postJson<CheckView>(routes.check, {})
105
+ if (mounted.current) setState(after)
106
+ }
107
+ } catch (error) {
108
+ if (mounted.current) setNote(render(t('state.failed'), { message: String((error as Error).message ?? error) }))
109
+ } finally {
110
+ if (mounted.current) setBusy('')
111
+ }
112
+ }
113
+
114
+ const offline = state?.reason === 'no-config-editor'
115
+ // 启用条件 = 体检已回来 & connection 行真的可动作。
116
+ // 曾把这句写成 `rows.some(row => row.rowId==='connection' && row.actionable !== true) !== true`:
117
+ // actionable 为真时 some() 本身就是 false,再取反反而把按钮锁死了(真机看到)。
118
+ const conn = state?.rows?.find((row) => row.rowId === 'connection')
119
+ const web = state?.rows?.find((row) => row.rowId === 'webserver')
120
+ const canFix = offline !== true && conn?.actionable === true
121
+ 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) => (
127
+ <button
128
+ type="button"
129
+ disabled={busy !== '' || disabled}
130
+ onClick={() => void run(action)}
131
+ 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
+ >
133
+ {busy === action ? t('state.busy') : t(action === 'port' ? 'action.port' : `action.${action}`)}
134
+ </button>
135
+ )
136
+
137
+ return (
138
+ <div style={{ display: 'grid', gap: 6, padding: '4px 0' }}>
139
+ <div style={{ fontWeight: 600 }}>{t('card.title')}</div>
140
+ {state?.documentPath ? <code style={{ fontSize: '0.85em', wordBreak: 'break-all' }}>{state.documentPath}</code> : null}
141
+ <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
142
+ {button('check')}
143
+ {button('fix', !canFix)}
144
+ {button('revert', !canRevert)}
145
+ </div>
146
+ {note !== '' ? <div style={{ color: 'var(--dsw-color-primary)', whiteSpace: 'pre-line' }}>{note}</div> : null}
147
+ {offline ? <div>{t('state.offline')}</div> : null}
148
+ {/* 结构无差异:一句话给肯定结论,不逐行刷档位(用户要的就是「注入正常」这个判定)。
149
+ 表达式被抄成字面量(P9)不在这里刷屏:它不改档位,只在 patch plan 的处方里提。 */}
150
+ {state?.level === 'ok'
151
+ ? <div style={{ color: LEVEL_COLOR.ok }}>{t('x.injectOk')}</div>
152
+ : (state?.rows ?? []).map((row) => <Row key={row.rowId} row={row} t={t} />)}
153
+ {(state?.rows ?? []).some((row) => row.rowId === 'webserver' && (row.findings ?? []).length > 0)
154
+ ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{t('note.webserver')}</div>
155
+ : 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>}
178
+ {/* 审计行:修复前根本没有覆盖行时(快照里无旧值),不能说“修复前 ?”——
179
+ 那是把“无据”伪装成一个值;改说“此前无覆盖行”。 */}
180
+ {state?.lastFix
181
+ ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>
182
+ {state.lastFix.beforeDays === undefined || state.lastFix.beforeDays === null
183
+ ? render(t('x.auditLineNew'), { at: state.lastFix.at ?? '?', after: state.lastFix.targetDays ?? '?' })
184
+ : render(t('x.auditLine'), { at: state.lastFix.at ?? '?', before: state.lastFix.beforeDays, after: state.lastFix.targetDays ?? '?' })}
185
+ </div>
186
+ : 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
+ {state?.checkedAt ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{render(t('lastCheck'), { at: state.checkedAt })}</div> : null}
193
+ </div>
194
+ )
195
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * dsh-cookie-cleaner — 浏览器半。
3
+ *
4
+ * 装载契约(三条都是事故换来的):
5
+ * - bundle id 必须 = **npm 包名**(`client/modules/src/index.ts:1040` 用 `graphRow(packageName,…)`),
6
+ * 注册 id 与宿主图不一致时 client 半从不加载;
7
+ * - 注册必须发生在 apply 顶层:关在任何 inject 回调里的注册两代都会静默失活;
8
+ * - 每个面单独 `safe()`:未知槽名在个别宿主线上同步抛错,而 cordis 会吞掉 inject 回调的
9
+ * 异常,一个面失败会带走同一回调里的其它面。
10
+ *
11
+ * `configForms`(0.1.7+)/`settingsScope`(≤0.1.5)是代际互斥服务,绝不写进插件级 inject——
12
+ * 那会让整个 client fiber 在另一代上停在 pending。这里只依赖 `slots` + `locale`(三代齐)。
13
+ */
14
+ import { dictionaries, NS, UI_KEYS } from './locales'
15
+ import { PatchCard } from './card'
16
+
17
+ /** 宿主 locale 服务的最小面(不引宿主类型包:client bundle 只按运行时形状用)。 */
18
+ interface LocaleService {
19
+ register(ns: string, dicts: Record<string, Record<string, string>>): unknown
20
+ bind?(ns: string): (key: string) => string
21
+ on?(event: string, listener: () => void): unknown
22
+ }
23
+
24
+ interface SlotEntry {
25
+ name: string
26
+ id?: string
27
+ /** keyed 槽必填(`ui-slots/src/index.ts:1222`:缺 key 直接 throw)。 */
28
+ key?: string
29
+ order?: number
30
+ label?: () => string
31
+ locale?: string
32
+ inject?: () => Record<string, unknown>
33
+ }
34
+
35
+ interface SlotsService {
36
+ inject(name: string, factory: () => Generator<unknown, void, unknown>): unknown
37
+ register(entry: SlotEntry, component: unknown): unknown
38
+ }
39
+
40
+ interface ClientContext {
41
+ get?(name: string): unknown
42
+ inject(deps: readonly string[], fn: (ctx: ClientContext) => void): unknown
43
+ effect(fn: () => unknown, label?: string): unknown
44
+ slots?: SlotsService
45
+ locale?: LocaleService
46
+ }
47
+
48
+ /** 插件级 inject 只声明三代都存在的服务。 */
49
+ export const inject = ['slots', 'locale'] as const
50
+
51
+ /** 当前语言的取词函数(注册后由 locale 服务提供;拿不到 bind 时回落 zh 字典)。 */
52
+ let currentT: (key: string) => string = (key) => {
53
+ const zh = (dictionaries as Record<string, Record<string, string>>).zh
54
+ return zh[key] ?? key
55
+ }
56
+
57
+ /** 每个面的独立 try/catch:一面抛错不带走其它面。 */
58
+ function safe(ctx: ClientContext, tag: string, fn: () => void): void {
59
+ try {
60
+ fn()
61
+ } catch (error) {
62
+ // 农场/真机拿不到 console 时也要留痕:失败面写进 window,供探针直接读取。
63
+ const surface = ((globalThis as Record<string, unknown>).__dccSurf ??= []) as string[]
64
+ surface.push(`${tag}: ${String((error as Error)?.message ?? error)}`)
65
+ const logger = typeof ctx.get === 'function' ? ctx.get('logger') as { warn?(msg: string): void } : undefined
66
+ if (typeof logger?.warn === 'function') logger.warn(`[dsh-cookie-cleaner] ${tag} failed: ${String((error as Error)?.message ?? error)}`)
67
+ }
68
+ }
69
+
70
+ /**
71
+ * 浏览器半入口。
72
+ * @param ctx client context。
73
+ */
74
+ export function apply(ctx: ClientContext): void {
75
+ // 字典注册:一次调用带 9 语(map 式注册要求宿主 locale 服务接受任意语言码)。
76
+ safe(ctx, 'locale.register', () => {
77
+ if (typeof ctx.locale?.register !== 'function') throw new Error('locale service unavailable')
78
+ ctx.locale.register(NS, dictionaries)
79
+ const bind = ctx.locale.bind?.(NS)
80
+ if (typeof bind === 'function') {
81
+ // bind 是活的取值器:换语言后重渲染即跟上新值,卡片不自存语言副本。
82
+ currentT = (key: string) => bind(key)
83
+ }
84
+ })
85
+
86
+ // 席位 A:设置页顶级独立节(范式 A,不参与家族 tab 选举)。
87
+ safe(ctx, 'settings.section', () => {
88
+ const slots = ctx.slots
89
+ if (slots?.inject === undefined || slots.register === undefined) throw new Error('slots service unavailable')
90
+ slots.inject('settings.section', function* () {
91
+ yield slots.register({
92
+ name: 'settings.section',
93
+ id: NS,
94
+ order: 45,
95
+ label: () => currentT('section.title'),
96
+ locale: NS,
97
+ inject: () => ({ t: (key: string) => currentT(key) }),
98
+ }, PatchCard)
99
+ })
100
+ })
101
+
102
+ // 席位 B:插件页配置卡(0.2.x 上「导出 Config 自动出表单」不成立,必须显式挂)。
103
+ // 这个槽是 **keyed** 形态,key = bundle 的包名(真机报错:keyed slot requires options.key)。
104
+ safe(ctx, 'plugins.bundle.config', () => {
105
+ const slots = ctx.slots
106
+ if (slots?.inject === undefined || slots.register === undefined) throw new Error('slots service unavailable')
107
+ slots.inject('plugins.bundle.config', function* () {
108
+ yield slots.register({
109
+ name: 'plugins.bundle.config',
110
+ key: NS,
111
+ order: 45,
112
+ label: () => currentT('section.title'),
113
+ locale: NS,
114
+ inject: () => ({ t: (key: string) => currentT(key) }),
115
+ }, PatchCard)
116
+ })
117
+ })
118
+
119
+ // 装载自检:键集没注册全就是构建坏了,立刻留痕而不是等用户点开空卡。
120
+ safe(ctx, 'dictionary sanity', () => {
121
+ const langs = Object.keys(dictionaries)
122
+ if (langs.length !== 9) throw new Error(`expected 9 languages, got ${String(langs.length)}`)
123
+ const missing = langs.filter((lang) => {
124
+ const dict = (dictionaries as Record<string, Record<string, string>>)[lang]
125
+ return UI_KEYS.some((key) => typeof dict[key] !== 'string' || dict[key] === '')
126
+ })
127
+ if (missing.length > 0) throw new Error(`empty keys for ${missing.join(', ')}`)
128
+ })
129
+ }