dsh-cookie-cleaner 0.6.4 → 0.7.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.
@@ -1,253 +1,310 @@
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, GuardView, 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
- /**
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
-
150
- export function PatchCard({ t }: CardProps): React.ReactElement {
151
- const [state, setState] = React.useState<CheckView | undefined>(undefined)
152
- const [busy, setBusy] = React.useState<'' | 'check' | 'fix' | 'revert'>('')
153
- const [note, setNote] = React.useState('')
154
- const mounted = React.useRef(true)
155
-
156
- React.useEffect(() => {
157
- mounted.current = true
158
- void run('check')
159
- return () => { mounted.current = false }
160
- }, [])
161
-
162
- async function run(action: 'check' | 'fix' | 'revert'): Promise<void> {
163
- setBusy(action)
164
- setNote('')
165
- try {
166
- if (action === 'check') {
167
- const value = await postJson<CheckView>(routes.check, {})
168
- if (mounted.current) setState(value)
169
- }
170
- else {
171
- const path = action === 'fix' ? routes.fix : routes.revert
172
- const value = await postJson<ActionView>(path, {})
173
- const fail = (message: string) => render(t('state.failed'), { message })
174
- const outcome = action === 'fix'
175
- ? value.kind === 'fixed' ? render(t('fix.done'), { changed: value.changed ?? [] })
176
- : value.kind === 'noop' ? t('fix.noop')
177
- : value.kind === 'blocked' ? render(t('fix.blocked'), { codes: value.codes ?? [] })
178
- : fail(value.message ?? value.kind)
179
- : value.kind === 'reverted' ? render(t('revert.done'), { changed: value.changed ?? [] })
180
- : value.kind === 'no-snapshot' ? t('revert.none')
181
- : fail(value.message ?? value.kind)
182
- if (!mounted.current) return
183
- setNote(outcome)
184
- // 动作后一律重读,不信单次返回值
185
- const after = value.result ?? await postJson<CheckView>(routes.check, {})
186
- if (mounted.current) setState(after)
187
- }
188
- } catch (error) {
189
- if (mounted.current) setNote(render(t('state.failed'), { message: String((error as Error).message ?? error) }))
190
- } finally {
191
- if (mounted.current) setBusy('')
192
- }
193
- }
194
-
195
- const offline = state?.reason === 'no-config-editor'
196
- // 启用条件 = 体检已回来 & connection 行真的可动作。
197
- // 曾把这句写成 `rows.some(row => row.rowId==='connection' && row.actionable !== true) !== true`:
198
- // actionable 为真时 some() 本身就是 false,再取反反而把按钮锁死了(真机看到)。
199
- const conn = state?.rows?.find((row) => row.rowId === 'connection')
200
- const canFix = offline !== true && conn?.actionable === true
201
- const canRevert = offline !== true
202
- const button = (action: 'check' | 'fix' | 'revert', disabled = false) => (
203
- <button
204
- type="button"
205
- disabled={busy !== '' || disabled}
206
- onClick={() => void run(action)}
207
- 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' }}
208
- >
209
- {busy === action ? t('state.busy') : t(`action.${action}`)}
210
- </button>
211
- )
212
-
213
- return (
214
- <div style={{ display: 'grid', gap: 6, padding: '4px 0' }}>
215
- <div style={{ fontWeight: 600 }}>{t('card.title')}</div>
216
- {state?.documentPath ? <code style={{ fontSize: '0.85em', wordBreak: 'break-all' }}>{state.documentPath}</code> : null}
217
- <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
218
- {button('check')}
219
- {button('fix', !canFix)}
220
- {button('revert', !canRevert)}
221
- </div>
222
- {note !== '' ? <div style={{ color: 'var(--dsw-color-primary)', whiteSpace: 'pre-line' }}>{note}</div> : null}
223
- {offline ? <div>{t('state.offline')}</div> : null}
224
- {/* 结构无差异:一句话给肯定结论,不逐行刷档位(用户要的就是「注入正常」这个判定)。
225
- 表达式被抄成字面量(P9)不在这里刷屏:它不改档位,只在 patch plan 的处方里提。 */}
226
- {state?.level === 'ok'
227
- ? <div style={{ color: LEVEL_COLOR.ok }}>{t('x.injectOk')}</div>
228
- : (state?.rows ?? []).map((row) => <Row key={row.rowId} row={row} t={t} />)}
229
- {(state?.rows ?? []).some((row) => row.rowId === 'webserver' && (row.findings ?? []).length > 0)
230
- ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{t('note.webserver')}</div>
231
- : null}
232
- {/* 真正有效的那一项:修复按钮写入的目标寿命(宿主设置里的 guardDays),跟结果同屏回显。
233
- 面板不再提供端口控件:端口属启动行为面,需要时用命令面 `patch port <n>` 显式改。 */}
234
- {state?.targetDays !== undefined
235
- ? <div style={{ fontSize: '0.9em', color: 'var(--dsw-color-text)' }}>{render(t('x.targetDaysLine'), { days: String(state.targetDays) })}</div>
236
- : null}
237
- {/* cookie 库读数(见 CookieLine:读得到就给实时值,读不到才说 busy) */}
238
- <CookieLine cookie={state?.cookie} t={t} />
239
- {/* 运行期守护:开关 + 两个阈值(写本插件自己那行,写后回显生效值) */}
240
- <GuardPanel t={t} />
241
- {/* 审计行:修复前根本没有覆盖行时(快照里无旧值),不能说“修复前 ?”——
242
- 那是把“无据”伪装成一个值;改说“此前无覆盖行”。 */}
243
- {state?.lastFix
244
- ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>
245
- {state.lastFix.beforeDays === undefined || state.lastFix.beforeDays === null
246
- ? render(t('x.auditLineNew'), { at: state.lastFix.at ?? '?', after: state.lastFix.targetDays ?? '?' })
247
- : render(t('x.auditLine'), { at: state.lastFix.at ?? '?', before: state.lastFix.beforeDays, after: state.lastFix.targetDays ?? '?' })}
248
- </div>
249
- : null}
250
- {state?.checkedAt ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{render(t('lastCheck'), { at: state.checkedAt })}</div> : null}
251
- </div>
252
- )
253
- }
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, GuardView, LegacyView, 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
+ /**
86
+ * 运行期守护面板:两个独立开关(retireStale 清理 / raiseHeaderBudget 抬预算)+ 两个阈值(retireAbove / keep)。
87
+ * v0.7.0 之前是一个 runtimeGuard 全包——用户为了清 cookie 被迫放宽 431 阈值,故拆开。
88
+ * 读写都走后端桥(configEditor 写本插件自己那行),写后回显生效值——不凭手写 YAML。
89
+ */
90
+ /**
91
+ * 历史注入残留面板(v0.7.1):旧版插件写进 profile 的 `port` 表达式还在不在。
92
+ *
93
+ * 为什么单独一块而不是塞进体检结果:这不是"配置对不对",是"插件自己留下的东西还在不在",
94
+ * 与 cookie 寿命无关。清理只在官方已接管 cookie 清理的宿主(0.2.2-rc.2+)上开放,
95
+ * 更早的宿主仍需要钉端口这条缓解,所以那里只显示不提供按钮。
96
+ */
97
+ function LegacyPanel({ t }: { t: (key: string) => string }): React.ReactElement | null {
98
+ const [v, setV] = React.useState<LegacyView | undefined>(undefined)
99
+ const [busy, setBusy] = React.useState(false)
100
+ const [note, setNote] = React.useState('')
101
+ const mounted = React.useRef(true)
102
+ React.useEffect(() => {
103
+ mounted.current = true
104
+ postJson<LegacyView>(routes.legacyGet, {}).then((next) => { if (mounted.current) setV(next) }).catch(() => { /* 无 config-editor 时静默 */ })
105
+ return () => { mounted.current = false }
106
+ }, [])
107
+ if (v === undefined) return null
108
+ if (v.available === false || v.found !== true) return null
109
+ const clean = async () => {
110
+ setBusy(true); setNote('')
111
+ try {
112
+ const next = await postJson<LegacyView>(routes.legacyClean, {})
113
+ if (!mounted.current) return
114
+ setV(next.state ?? v)
115
+ setNote(next.kind === 'cleaned' ? t('legacy.cleaned') : t('legacy.noop'))
116
+ } catch (error) {
117
+ if (mounted.current) setNote(render(t('state.failed'), { message: String((error as Error).message ?? error) }))
118
+ } finally {
119
+ if (mounted.current) setBusy(false)
120
+ }
121
+ }
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('legacy.title')}</div>
125
+ <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{render(t('legacy.found'), { expr: v.expression ?? '?' })}</div>
126
+ {v.cleanupSupported === true
127
+ ? <button type="button" disabled={busy} onClick={() => void clean()} style={{ justifySelf: 'start', padding: '3px 10px', borderRadius: 6, border: '1px solid var(--dsw-color-border)', background: 'var(--dsw-color-surface)', color: 'var(--dsw-color-text)', cursor: busy ? 'default' : 'pointer' }}>{t('legacy.clean')}</button>
128
+ : <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{t('legacy.unsupported')}</div>}
129
+ {note !== '' ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-text)' }}>{note}</div> : null}
130
+ </div>
131
+ )
132
+ }
133
+
134
+ function GuardPanel({ t }: { t: (key: string) => string }): React.ReactElement | null {
135
+ const [g, setG] = React.useState<GuardView | undefined>(undefined)
136
+ const [busy, setBusy] = React.useState(false)
137
+ const [note, setNote] = React.useState('')
138
+ const mounted = React.useRef(true)
139
+ React.useEffect(() => {
140
+ mounted.current = true
141
+ postJson<GuardView>(routes.guardGet, {}).then((v) => { if (mounted.current) setG(v) }).catch(() => { /* 无 config-editor 时静默,不刷红 */ })
142
+ return () => { mounted.current = false }
143
+ }, [])
144
+ if (g === undefined) return null
145
+ if (g.available === false) return <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{t('guard.unavailable')}</div>
146
+ const toInt = (e: React.ChangeEvent<HTMLInputElement>) => { const n = Math.trunc(Number(e.target.value)); return Number.isFinite(n) ? n : 0 }
147
+ // 改完即存(无保存按钮):先乐观更新本地态,后端失败则回滚到服务端值
148
+ const commit = async (next: GuardView) => {
149
+ const prev = g
150
+ setG(next)
151
+ setBusy(true); setNote('')
152
+ try {
153
+ const v = await postJson<GuardView>(routes.guardSet, {
154
+ retireStale: next.retireStale,
155
+ raiseHeaderBudget: next.raiseHeaderBudget,
156
+ maxHeaderBytes: next.maxHeaderBytes,
157
+ keep: next.keep,
158
+ retireAbove: next.retireAbove,
159
+ })
160
+ if (!mounted.current) return
161
+ setG(v)
162
+ setNote(v.kind === 'noop' ? t('guard.noop') : t('guard.saved'))
163
+ } catch (error) {
164
+ if (mounted.current) {
165
+ setG(prev)
166
+ setNote(render(t('state.failed'), { message: String((error as Error).message ?? error) }))
167
+ }
168
+ } finally {
169
+ if (mounted.current) setBusy(false)
170
+ }
171
+ }
172
+ 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
173
+ return (
174
+ <div style={{ display: 'grid', gap: 6, marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--dsw-color-border)' }}>
175
+ <div style={{ fontWeight: 600 }}>{t('guard.title')}</div>
176
+ <label style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
177
+ <input type="checkbox" checked={g.retireStale} disabled={busy} onChange={(e) => void commit({ ...g, retireStale: e.target.checked })} />
178
+ {t('guard.enableRetire')}
179
+ </label>
180
+ <label style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
181
+ <input type="checkbox" checked={g.raiseHeaderBudget} disabled={busy} onChange={(e) => void commit({ ...g, raiseHeaderBudget: e.target.checked })} />
182
+ {t('guard.enableBudget')}
183
+ </label>
184
+ <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: '0.9em' }}>
185
+ {t('guard.retireAbove')}
186
+ <input type="number" min={0} max={10000} value={g.retireAbove} disabled={busy}
187
+ onChange={(e) => setG({ ...g, retireAbove: toInt(e) })}
188
+ onBlur={() => void commit(g)}
189
+ onKeyDown={(e) => { if (e.key === 'Enter') void commit(g) }}
190
+ style={inputStyle} />
191
+ </label>
192
+ <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: '0.9em' }}>
193
+ {t('guard.keep')}
194
+ <input type="number" min={1} max={64} value={g.keep} disabled={busy}
195
+ onChange={(e) => setG({ ...g, keep: toInt(e) })}
196
+ onBlur={() => void commit(g)}
197
+ onKeyDown={(e) => { if (e.key === 'Enter') void commit(g) }}
198
+ style={inputStyle} />
199
+ </label>
200
+ {busy || note !== '' ? <div style={{ fontSize: '0.85em', color: busy ? 'var(--dsw-color-muted)' : 'var(--dsw-color-primary)' }}>{busy ? t('state.busy') : note}</div> : null}
201
+ </div>
202
+ )
203
+ }
204
+
205
+ export function PatchCard({ t }: CardProps): React.ReactElement {
206
+ const [state, setState] = React.useState<CheckView | undefined>(undefined)
207
+ const [busy, setBusy] = React.useState<'' | 'check' | 'fix' | 'revert'>('')
208
+ const [note, setNote] = React.useState('')
209
+ const mounted = React.useRef(true)
210
+
211
+ React.useEffect(() => {
212
+ mounted.current = true
213
+ void run('check')
214
+ return () => { mounted.current = false }
215
+ }, [])
216
+
217
+ async function run(action: 'check' | 'fix' | 'revert'): Promise<void> {
218
+ setBusy(action)
219
+ setNote('')
220
+ try {
221
+ if (action === 'check') {
222
+ const value = await postJson<CheckView>(routes.check, {})
223
+ if (mounted.current) setState(value)
224
+ }
225
+ else {
226
+ const path = action === 'fix' ? routes.fix : routes.revert
227
+ const value = await postJson<ActionView>(path, {})
228
+ const fail = (message: string) => render(t('state.failed'), { message })
229
+ const outcome = action === 'fix'
230
+ ? value.kind === 'fixed' ? render(t('fix.done'), { changed: value.changed ?? [] })
231
+ : value.kind === 'noop' ? t('fix.noop')
232
+ : value.kind === 'blocked' ? render(t('fix.blocked'), { codes: value.codes ?? [] })
233
+ : fail(value.message ?? value.kind)
234
+ : value.kind === 'reverted' ? render(t('revert.done'), { changed: value.changed ?? [] })
235
+ : value.kind === 'no-snapshot' ? t('revert.none')
236
+ : fail(value.message ?? value.kind)
237
+ if (!mounted.current) return
238
+ setNote(outcome)
239
+ // 动作后一律重读,不信单次返回值
240
+ const after = value.result ?? await postJson<CheckView>(routes.check, {})
241
+ if (mounted.current) setState(after)
242
+ }
243
+ } catch (error) {
244
+ if (mounted.current) setNote(render(t('state.failed'), { message: String((error as Error).message ?? error) }))
245
+ } finally {
246
+ if (mounted.current) setBusy('')
247
+ }
248
+ }
249
+
250
+ const offline = state?.reason === 'no-config-editor'
251
+ // 启用条件 = 体检已回来 & connection 行真的可动作。
252
+ // 曾把这句写成 `rows.some(row => row.rowId==='connection' && row.actionable !== true) !== true`:
253
+ // actionable 为真时 some() 本身就是 false,再取反反而把按钮锁死了(真机看到)。
254
+ const conn = state?.rows?.find((row) => row.rowId === 'connection')
255
+ const canFix = offline !== true && conn?.actionable === true
256
+ const canRevert = offline !== true
257
+ const button = (action: 'check' | 'fix' | 'revert', disabled = false) => (
258
+ <button
259
+ type="button"
260
+ disabled={busy !== '' || disabled}
261
+ onClick={() => void run(action)}
262
+ 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' }}
263
+ >
264
+ {busy === action ? t('state.busy') : t(`action.${action}`)}
265
+ </button>
266
+ )
267
+
268
+ return (
269
+ <div style={{ display: 'grid', gap: 6, padding: '4px 0' }}>
270
+ <div style={{ fontWeight: 600 }}>{t('card.title')}</div>
271
+ {state?.documentPath ? <code style={{ fontSize: '0.85em', wordBreak: 'break-all' }}>{state.documentPath}</code> : null}
272
+ <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
273
+ {button('check')}
274
+ {button('fix', !canFix)}
275
+ {button('revert', !canRevert)}
276
+ </div>
277
+ {note !== '' ? <div style={{ color: 'var(--dsw-color-primary)', whiteSpace: 'pre-line' }}>{note}</div> : null}
278
+ {offline ? <div>{t('state.offline')}</div> : null}
279
+ {/* 结构无差异:一句话给肯定结论,不逐行刷档位(用户要的就是「注入正常」这个判定)。
280
+ 表达式被抄成字面量(P9)不在这里刷屏:它不改档位,只在 patch plan 的处方里提。 */}
281
+ {state?.level === 'ok'
282
+ ? <div style={{ color: LEVEL_COLOR.ok }}>{t('x.injectOk')}</div>
283
+ : (state?.rows ?? []).map((row) => <Row key={row.rowId} row={row} t={t} />)}
284
+ {(state?.rows ?? []).some((row) => row.rowId === 'webserver' && (row.findings ?? []).length > 0)
285
+ ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{t('note.webserver')}</div>
286
+ : null}
287
+ {/* 真正有效的那一项:修复按钮写入的目标寿命(宿主设置里的 guardDays),跟结果同屏回显。
288
+ 面板不再提供端口控件:端口属启动行为面,需要时用命令面 `patch port <n>` 显式改。 */}
289
+ {state?.targetDays !== undefined
290
+ ? <div style={{ fontSize: '0.9em', color: 'var(--dsw-color-text)' }}>{render(t('x.targetDaysLine'), { days: String(state.targetDays) })}</div>
291
+ : null}
292
+ {/* cookie 库读数(见 CookieLine:读得到就给实时值,读不到才说 busy) */}
293
+ <CookieLine cookie={state?.cookie} t={t} />
294
+ {/* 运行期守护:开关 + 两个阈值(写本插件自己那行,写后回显生效值) */}
295
+ <GuardPanel t={t} />
296
+ {/* 历史注入残留:旧版「应用端口」写进 profile 的表达式(有才显示) */}
297
+ <LegacyPanel t={t} />
298
+ {/* 审计行:修复前根本没有覆盖行时(快照里无旧值),不能说“修复前 ?”——
299
+ 那是把“无据”伪装成一个值;改说“此前无覆盖行”。 */}
300
+ {state?.lastFix
301
+ ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>
302
+ {state.lastFix.beforeDays === undefined || state.lastFix.beforeDays === null
303
+ ? render(t('x.auditLineNew'), { at: state.lastFix.at ?? '?', after: state.lastFix.targetDays ?? '?' })
304
+ : render(t('x.auditLine'), { at: state.lastFix.at ?? '?', before: state.lastFix.beforeDays, after: state.lastFix.targetDays ?? '?' })}
305
+ </div>
306
+ : null}
307
+ {state?.checkedAt ? <div style={{ fontSize: '0.85em', color: 'var(--dsw-color-muted)' }}>{render(t('lastCheck'), { at: state.checkedAt })}</div> : null}
308
+ </div>
309
+ )
310
+ }