dsh-cookie-cleaner 0.1.2 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +158 -50
- package/README.md +314 -179
- package/dsh.plugin.json +2 -2
- package/lib/client.js +530 -0
- package/lib/client.js.map +1 -0
- package/locale/de.json +1 -1
- package/locale/en.json +1 -1
- package/locale/es.json +1 -1
- package/locale/fr.json +1 -1
- package/locale/it.json +1 -1
- package/locale/ja.json +1 -1
- package/locale/ko.json +1 -1
- package/locale/ru.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +26 -7
- package/scripts/gen-locales.mjs +9 -9
- package/scripts/sync-hosts.mjs +24 -4
- package/src/api-routes.js +133 -0
- package/src/cli.js +92 -3
- package/src/client/card.tsx +186 -0
- package/src/client/index.ts +129 -0
- package/src/client/locales.ts +77 -0
- package/src/client/routes.ts +104 -0
- package/src/core.js +98 -0
- package/src/index.js +85 -10
- package/src/jar-live.js +365 -0
- package/src/locales-patch.js +203 -0
- package/src/patch-guard.js +375 -0
- package/src/patch-model.js +271 -0
- package/src/patch-read.js +199 -0
- package/src/report.js +144 -0
|
@@ -0,0 +1,133 @@
|
|
|
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
|
+
* **没有端口写端点**(用户裁决 2026-11-05):本插件只改配置里的 cookie 有效期,
|
|
9
|
+
* 端口属启动行为面,面板与命令面都不再提供写入(面板不调它时留个写端点只是攻击面)。
|
|
10
|
+
*
|
|
11
|
+
* 路由派生式与 `src/client/routes.ts` **必须逐字符一致**,由 `tests/api-routes.test.js`
|
|
12
|
+
* 用同一段字面量在两份源里双向核对——两半各持一份派生式而测试不钉,是 URL 漂移的老坑。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** 命名空间 = npm 包名(settings ns、卡 id、桥路径三处同串)。 */
|
|
16
|
+
export const NS = 'dsh-cookie-cleaner'
|
|
17
|
+
|
|
18
|
+
/** 三条路由:体检 / 修复 / 回滚。(端口写入只走命令面,面板不提供控件,所以不开写端点) */
|
|
19
|
+
export function bridgeRoutesFor(ns = NS) {
|
|
20
|
+
return Object.freeze({
|
|
21
|
+
check: `/api/${ns}/patch/check`,
|
|
22
|
+
fix: `/api/${ns}/patch/fix`,
|
|
23
|
+
revert: `/api/${ns}/patch/revert`,
|
|
24
|
+
})
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const MAX_BODY_BYTES = 64 * 1024
|
|
28
|
+
|
|
29
|
+
function sendJson(res, code, body) {
|
|
30
|
+
res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
|
|
31
|
+
res.end(JSON.stringify(body))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 读 JSON body(有上限,超限直接拒——面板不该发大东西)。 */
|
|
35
|
+
function readJsonBody(req) {
|
|
36
|
+
return new Promise((resolve, reject) => {
|
|
37
|
+
const chunks = []
|
|
38
|
+
let size = 0
|
|
39
|
+
req.on('data', (chunk) => {
|
|
40
|
+
size += chunk.length
|
|
41
|
+
if (size > MAX_BODY_BYTES) {
|
|
42
|
+
reject(new Error('body too large'))
|
|
43
|
+
return
|
|
44
|
+
}
|
|
45
|
+
chunks.push(chunk)
|
|
46
|
+
})
|
|
47
|
+
req.on('end', () => {
|
|
48
|
+
if (chunks.length === 0) { resolve({}); return }
|
|
49
|
+
try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))) }
|
|
50
|
+
catch (e) { reject(new Error(`invalid json body: ${e.message}`)) }
|
|
51
|
+
})
|
|
52
|
+
req.on('error', reject)
|
|
53
|
+
})
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* cookie 库现状只留卡片需要看的字段。
|
|
58
|
+
* 读得到就带真实条数与请求头占用折算(`header`),并带出它是实时还是借句柄快照;
|
|
59
|
+
* 读不到才只给 verdict/reason,不能谎报条数。
|
|
60
|
+
* @param {() => any} [stat]
|
|
61
|
+
*/
|
|
62
|
+
export function cookieBrief(stat) {
|
|
63
|
+
if (typeof stat !== 'function') return undefined
|
|
64
|
+
try {
|
|
65
|
+
const s = stat()
|
|
66
|
+
if (s === undefined || s === null) return undefined
|
|
67
|
+
return {
|
|
68
|
+
verdict: s.verdict,
|
|
69
|
+
reason: s.reason,
|
|
70
|
+
path: s.path,
|
|
71
|
+
authCookies: s.authCookies,
|
|
72
|
+
totalCookies: s.totalCookies,
|
|
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,
|
|
79
|
+
}
|
|
80
|
+
} catch { return undefined }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* 注册路由。
|
|
85
|
+
* @param {unknown} webServer `webServer` 服务实例(只要求有 register)
|
|
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] 宿主设置里的默认档
|
|
88
|
+
* @returns {Array<() => void>} 注销函数
|
|
89
|
+
*/
|
|
90
|
+
export function registerPatchRoutes(webServer, guard, defaults = {}) {
|
|
91
|
+
const register = typeof webServer?.register === 'function' ? webServer.register.bind(webServer) : undefined
|
|
92
|
+
if (register === undefined) return []
|
|
93
|
+
const routes = bridgeRoutesFor(defaults.ns ?? NS)
|
|
94
|
+
const offs = []
|
|
95
|
+
|
|
96
|
+
/** 统一的一跳:POST-only、参数从 body 取、异常包成结构化错误。 */
|
|
97
|
+
const endpoint = (path, run) => {
|
|
98
|
+
offs.push(register({
|
|
99
|
+
kind: 'exact',
|
|
100
|
+
path,
|
|
101
|
+
handler: (rawReq, rawRes) => {
|
|
102
|
+
const req = rawReq
|
|
103
|
+
const res = rawRes
|
|
104
|
+
if (req.method !== 'POST') {
|
|
105
|
+
sendJson(res, 405, { ok: false, code: 'method-not-allowed' })
|
|
106
|
+
return
|
|
107
|
+
}
|
|
108
|
+
readJsonBody(req).then(async (body) => {
|
|
109
|
+
const options = {
|
|
110
|
+
targetDays: Number.isInteger(body?.targetDays) && body.targetDays >= 1 ? body.targetDays : defaults.targetDays,
|
|
111
|
+
guardMode: body?.guardMode === 'expression' ? 'expression' : defaults.guardMode,
|
|
112
|
+
lang: typeof body?.lang === 'string' ? body.lang : defaults.lang,
|
|
113
|
+
}
|
|
114
|
+
const value = await run(options)
|
|
115
|
+
sendJson(res, 200, { ok: true, value })
|
|
116
|
+
}).catch((e) => {
|
|
117
|
+
sendJson(res, 200, { ok: false, code: 'internal', message: String(e && e.message ? e.message : e) })
|
|
118
|
+
})
|
|
119
|
+
},
|
|
120
|
+
}))
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
endpoint(routes.check, (options) => {
|
|
124
|
+
const result = guard.check(options)
|
|
125
|
+
const cookie = cookieBrief(defaults.cookie)
|
|
126
|
+
// 目标寿命跟结果同屏:面板要说清「修复按钮写的是哪个值」,不让用户去猜设置里那一格
|
|
127
|
+
const withTarget = { ...result, targetDays: options.targetDays ?? defaults.targetDays }
|
|
128
|
+
return cookie === undefined ? withTarget : { ...withTarget, cookie }
|
|
129
|
+
})
|
|
130
|
+
endpoint(routes.fix, (options) => guard.fix(options))
|
|
131
|
+
endpoint(routes.revert, () => guard.revert())
|
|
132
|
+
return offs
|
|
133
|
+
}
|
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 { cookieLiveText, 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
|
-
|
|
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,12 +135,32 @@ 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) {
|
|
157
|
+
// CLI 不借句柄:它是独立进程,镜像名与桌面端不同(目标进程匹配不上),
|
|
158
|
+
// 而且一个命令行工具不该去扫全机句柄表。要运行期水位就看面板。
|
|
73
159
|
const stat = core.statCookies({ explicitPath, env })
|
|
74
160
|
process.stdout.write(core.describeStat(stat) + '\n')
|
|
161
|
+
// 占用折算单独一句:describeStat 保持「一句话」契约,但数字不能缺席(与面板同一函数同一句)。
|
|
162
|
+
const live = cookieLiveText(stat)
|
|
163
|
+
if (live !== undefined) process.stdout.write(live + '\n')
|
|
75
164
|
const exit = core.exitInstruction()
|
|
76
165
|
if (stat.reason === 'busy') {
|
|
77
166
|
process.stdout.write(nextLine('nextCliRerun', { exit }) + '\n')
|
|
@@ -0,0 +1,186 @@
|
|
|
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
|
+
/**
|
|
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
|
+
|
|
85
|
+
export function PatchCard({ t }: CardProps): React.ReactElement {
|
|
86
|
+
const [state, setState] = React.useState<CheckView | undefined>(undefined)
|
|
87
|
+
const [busy, setBusy] = React.useState<'' | 'check' | 'fix' | 'revert'>('')
|
|
88
|
+
const [note, setNote] = React.useState('')
|
|
89
|
+
const mounted = React.useRef(true)
|
|
90
|
+
|
|
91
|
+
React.useEffect(() => {
|
|
92
|
+
mounted.current = true
|
|
93
|
+
void run('check')
|
|
94
|
+
return () => { mounted.current = false }
|
|
95
|
+
}, [])
|
|
96
|
+
|
|
97
|
+
async function run(action: 'check' | 'fix' | 'revert'): Promise<void> {
|
|
98
|
+
setBusy(action)
|
|
99
|
+
setNote('')
|
|
100
|
+
try {
|
|
101
|
+
if (action === 'check') {
|
|
102
|
+
const value = await postJson<CheckView>(routes.check, {})
|
|
103
|
+
if (mounted.current) setState(value)
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
const path = action === 'fix' ? routes.fix : routes.revert
|
|
107
|
+
const value = await postJson<ActionView>(path, {})
|
|
108
|
+
const fail = (message: string) => render(t('state.failed'), { message })
|
|
109
|
+
const outcome = action === 'fix'
|
|
110
|
+
? value.kind === 'fixed' ? render(t('fix.done'), { changed: value.changed ?? [] })
|
|
111
|
+
: value.kind === 'noop' ? t('fix.noop')
|
|
112
|
+
: value.kind === 'blocked' ? render(t('fix.blocked'), { codes: value.codes ?? [] })
|
|
113
|
+
: fail(value.message ?? value.kind)
|
|
114
|
+
: value.kind === 'reverted' ? render(t('revert.done'), { changed: value.changed ?? [] })
|
|
115
|
+
: value.kind === 'no-snapshot' ? t('revert.none')
|
|
116
|
+
: fail(value.message ?? value.kind)
|
|
117
|
+
if (!mounted.current) return
|
|
118
|
+
setNote(outcome)
|
|
119
|
+
// 动作后一律重读,不信单次返回值
|
|
120
|
+
const after = value.result ?? await postJson<CheckView>(routes.check, {})
|
|
121
|
+
if (mounted.current) setState(after)
|
|
122
|
+
}
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (mounted.current) setNote(render(t('state.failed'), { message: String((error as Error).message ?? error) }))
|
|
125
|
+
} finally {
|
|
126
|
+
if (mounted.current) setBusy('')
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const offline = state?.reason === 'no-config-editor'
|
|
131
|
+
// 启用条件 = 体检已回来 & connection 行真的可动作。
|
|
132
|
+
// 曾把这句写成 `rows.some(row => row.rowId==='connection' && row.actionable !== true) !== true`:
|
|
133
|
+
// actionable 为真时 some() 本身就是 false,再取反反而把按钮锁死了(真机看到)。
|
|
134
|
+
const conn = state?.rows?.find((row) => row.rowId === 'connection')
|
|
135
|
+
const canFix = offline !== true && conn?.actionable === true
|
|
136
|
+
const canRevert = offline !== true
|
|
137
|
+
const button = (action: 'check' | 'fix' | 'revert', disabled = false) => (
|
|
138
|
+
<button
|
|
139
|
+
type="button"
|
|
140
|
+
disabled={busy !== '' || disabled}
|
|
141
|
+
onClick={() => void run(action)}
|
|
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' }}
|
|
143
|
+
>
|
|
144
|
+
{busy === action ? t('state.busy') : t(`action.${action}`)}
|
|
145
|
+
</button>
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
return (
|
|
149
|
+
<div style={{ display: 'grid', gap: 6, padding: '4px 0' }}>
|
|
150
|
+
<div style={{ fontWeight: 600 }}>{t('card.title')}</div>
|
|
151
|
+
{state?.documentPath ? <code style={{ fontSize: '0.85em', wordBreak: 'break-all' }}>{state.documentPath}</code> : null}
|
|
152
|
+
<div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
|
|
153
|
+
{button('check')}
|
|
154
|
+
{button('fix', !canFix)}
|
|
155
|
+
{button('revert', !canRevert)}
|
|
156
|
+
</div>
|
|
157
|
+
{note !== '' ? <div style={{ color: 'var(--dsw-color-primary)', whiteSpace: 'pre-line' }}>{note}</div> : null}
|
|
158
|
+
{offline ? <div>{t('state.offline')}</div> : null}
|
|
159
|
+
{/* 结构无差异:一句话给肯定结论,不逐行刷档位(用户要的就是「注入正常」这个判定)。
|
|
160
|
+
表达式被抄成字面量(P9)不在这里刷屏:它不改档位,只在 patch plan 的处方里提。 */}
|
|
161
|
+
{state?.level === 'ok'
|
|
162
|
+
? <div style={{ color: LEVEL_COLOR.ok }}>{t('x.injectOk')}</div>
|
|
163
|
+
: (state?.rows ?? []).map((row) => <Row key={row.rowId} row={row} t={t} />)}
|
|
164
|
+
{(state?.rows ?? []).some((row) => row.rowId === 'webserver' && (row.findings ?? []).length > 0)
|
|
165
|
+
? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{t('note.webserver')}</div>
|
|
166
|
+
: null}
|
|
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} />
|
|
174
|
+
{/* 审计行:修复前根本没有覆盖行时(快照里无旧值),不能说“修复前 ?”——
|
|
175
|
+
那是把“无据”伪装成一个值;改说“此前无覆盖行”。 */}
|
|
176
|
+
{state?.lastFix
|
|
177
|
+
? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>
|
|
178
|
+
{state.lastFix.beforeDays === undefined || state.lastFix.beforeDays === null
|
|
179
|
+
? render(t('x.auditLineNew'), { at: state.lastFix.at ?? '?', after: state.lastFix.targetDays ?? '?' })
|
|
180
|
+
: render(t('x.auditLine'), { at: state.lastFix.at ?? '?', before: state.lastFix.beforeDays, after: state.lastFix.targetDays ?? '?' })}
|
|
181
|
+
</div>
|
|
182
|
+
: null}
|
|
183
|
+
{state?.checkedAt ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{render(t('lastCheck'), { at: state.checkedAt })}</div> : null}
|
|
184
|
+
</div>
|
|
185
|
+
)
|
|
186
|
+
}
|
|
@@ -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
|
+
}
|