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,375 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-cookie-cleaner — patch 体检/修复的宿主半适配层。
|
|
3
|
+
*
|
|
4
|
+
* 职责边界:这里只做「取数 + 调官方 configEditor + 落快照」,判定全在 `patch-model.js`,
|
|
5
|
+
* 文案全在 `report.js` + `locales-patch.js`。写动作**一律走 `configEditor.edit()`**,
|
|
6
|
+
* 不自己拼 YAML——官方通道自带文件锁、目标插件 Config schema 校验、home 影子检查、
|
|
7
|
+
* 原子写与 reconcile 失败回滚(源码依据见 `.agents/plans/cookie-patch-guard/findings.md` §6)。
|
|
8
|
+
*
|
|
9
|
+
* 三条实测约束(0.2.1-rc.5,全部踩过):
|
|
10
|
+
* 1. 冷启动 `ctx.get('configEditor')` 是 undefined ⇒ 只能靠 scoped inject 的回调时机;
|
|
11
|
+
* 2. 在 apply 执行链上直接 `edit()` 抛 `HMR transactions cannot be nested` ⇒ 写只能发生在
|
|
12
|
+
* 用户触发的请求/命令回调链上,并对该错误做**一次退避重试**(P12),不硬失败;
|
|
13
|
+
* 3. 写后 HMR 会热应用,无需重启;但必须回读 effective 才算「修好了」。
|
|
14
|
+
*/
|
|
15
|
+
import fs from 'node:fs'
|
|
16
|
+
import os from 'node:os'
|
|
17
|
+
import path from 'node:path'
|
|
18
|
+
import { MANAGED_ROWS, aggregateAll, assessRow, nextConfigFor } from './patch-model.js'
|
|
19
|
+
import { findOverrideRow, parsePatchText, readPatchFile } from './patch-read.js'
|
|
20
|
+
|
|
21
|
+
/** 嵌套事务错误:热重载期间的正常现象,不是配置问题。 */
|
|
22
|
+
const NESTED_ERROR = /HMR transactions cannot be nested/i
|
|
23
|
+
const SNAPSHOT_DIR = 'cookie-cleaner'
|
|
24
|
+
|
|
25
|
+
/** DSH home(快照落这里,与 profile 目录解耦,删格不丢回滚能力)。 */
|
|
26
|
+
export function dshHome(env = process.env, homedir = os.homedir()) {
|
|
27
|
+
const explicit = String(env.DSH_HOME ?? '').trim()
|
|
28
|
+
return explicit !== '' ? explicit : path.join(homedir, '.dsh')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 快照的 profile 身份。**必须按 profile 隔离**:
|
|
33
|
+
* 真机串台过一次——在隔离格跑的那次 fix 把快照留在全局单文件里,
|
|
34
|
+
* 另一个 profile 的面板于是显示了别人的「上次修复」,更糟的是点「回滚」
|
|
35
|
+
* 会把**别的 profile** 的旧 config 写进当前 profile。所有一旧的全局快照不再读。
|
|
36
|
+
* 判据取 profile 目录名(`<home>/profiles/<name>/cordis.patch.yml`),推不出就用父目录名。
|
|
37
|
+
*/
|
|
38
|
+
export function snapshotKey(profileFile = '') {
|
|
39
|
+
const parts = String(profileFile).split(/[\\/]+/).filter(Boolean)
|
|
40
|
+
const at = parts.lastIndexOf('profiles')
|
|
41
|
+
if (at >= 0 && parts[at + 1] !== undefined) return String(parts[at + 1])
|
|
42
|
+
return parts.length > 1 ? String(parts[parts.length - 2]) : 'default'
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function snapshotFile(homeDir = dshHome(), profileFile = '') {
|
|
46
|
+
return path.join(homeDir, SNAPSHOT_DIR, `patch-snapshot--${snapshotKey(profileFile)}.json`)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 深拷贝成 JSON 安全形态(`{__jsExpr}` 是普通对象,能直接过 JSON)。 */
|
|
50
|
+
function plain(value) {
|
|
51
|
+
if (value === undefined) return undefined
|
|
52
|
+
try { return JSON.parse(JSON.stringify(value)) } catch { return undefined }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function readSnapshot(file, fsModule) {
|
|
56
|
+
try {
|
|
57
|
+
const raw = JSON.parse(fsModule.readFileSync(file, 'utf8'))
|
|
58
|
+
if (raw === null || typeof raw !== 'object') return undefined
|
|
59
|
+
// v2:`{rows: {<rowId>: {config…}}}`;v1(旧形式):单行 `{rowId, config…}`。
|
|
60
|
+
if (raw.rows !== null && typeof raw.rows === 'object') return raw
|
|
61
|
+
if (raw.config !== null && typeof raw.config === 'object') {
|
|
62
|
+
const rowId = typeof raw.rowId === 'string' ? raw.rowId : 'connection'
|
|
63
|
+
return { version: 2, profile: raw.profile, generatedAt: raw.generatedAt, rows: { [rowId]: raw } }
|
|
64
|
+
}
|
|
65
|
+
return undefined
|
|
66
|
+
} catch { return undefined }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 把新一次的“写前值”并写入快照(cookie 寿命与端口是两个独立动作,各自回到各自的前值)。 */
|
|
70
|
+
function keepSnapshotRow(file, rowId, data, fsModule) {
|
|
71
|
+
const base = readSnapshot(file, fsModule) ?? { version: 2, rows: {} }
|
|
72
|
+
base.rows = { ...base.rows, [rowId]: data }
|
|
73
|
+
base.profile = data.profile ?? base.profile
|
|
74
|
+
base.generatedAt = data.generatedAt ?? base.generatedAt
|
|
75
|
+
writeSnapshot(file, base, fsModule)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function writeSnapshot(file, data, fsModule) {
|
|
79
|
+
fsModule.mkdirSync(path.dirname(file), { recursive: true })
|
|
80
|
+
fsModule.writeFileSync(file, JSON.stringify(data, null, 2), 'utf8')
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* 造一个守卫。所有外部依赖都注入,方便单测与 CLI 侧共用判定。
|
|
85
|
+
* @param {{
|
|
86
|
+
* getEditor: () => any,
|
|
87
|
+
* fs?: typeof import('node:fs'),
|
|
88
|
+
* env?: Record<string,string|undefined>,
|
|
89
|
+
* homeDir?: string,
|
|
90
|
+
* targetDays?: number,
|
|
91
|
+
* guardMode?: 'literal'|'expression',
|
|
92
|
+
* wait?: (ms:number) => Promise<void>,
|
|
93
|
+
* now?: () => number,
|
|
94
|
+
* }} deps
|
|
95
|
+
*/
|
|
96
|
+
export function createPatchGuard(deps) {
|
|
97
|
+
const {
|
|
98
|
+
getEditor,
|
|
99
|
+
fs: fsModule = fs,
|
|
100
|
+
env = process.env,
|
|
101
|
+
homeDir = dshHome(env),
|
|
102
|
+
wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
103
|
+
now = () => Date.now(),
|
|
104
|
+
} = deps
|
|
105
|
+
/** 可覆盖的目标档位由调用方(命令/路由)每次传入,避免守卫里存状态。 */
|
|
106
|
+
const state = { homeDir }
|
|
107
|
+
/** 快照路径按**当前 profile** 算(documentPath 只有 editor 就绪后才知道,不能构造时定死)。 */
|
|
108
|
+
function snapFile() {
|
|
109
|
+
const ce = getEditor()
|
|
110
|
+
const doc = ce !== undefined && typeof ce.documentPath === 'string' ? ce.documentPath : ''
|
|
111
|
+
return snapshotFile(homeDir, doc)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 组合 configEditor 的运行态与 profile 文件的字面态,喂给内核。 */
|
|
115
|
+
function buildInput(rowId, ce, options) {
|
|
116
|
+
const spec = MANAGED_ROWS[rowId]
|
|
117
|
+
const entry = ce.entries().find((item) => item.options.id === spec.id)
|
|
118
|
+
const configuration = (typeof ce.configuration === 'function' ? ce.configuration() : []).find((row) => row.entry.options.id === spec.id)
|
|
119
|
+
const profileFile = ce.documentPath
|
|
120
|
+
const profileRead = readPatchFileWith(fsModule, profileFile)
|
|
121
|
+
const homeRead = readPatchFileWith(fsModule, path.join(state.homeDir, 'cordis.patch.yml'))
|
|
122
|
+
|
|
123
|
+
// 覆盖行以**文件**为准:name 写错的行会被宿主静默跳过,此时 configuration().override 是空的,
|
|
124
|
+
// 只有文件里看得到那行——P2 的价值恰恰在于「把看不见的失效说出来」。
|
|
125
|
+
const fileRow = profileRead.parsed.ok ? findOverrideRow(profileRead.parsed, spec.id) : undefined
|
|
126
|
+
const overrideRow = fileRow !== undefined
|
|
127
|
+
? { name: fileRow.name, config: fileRow.config ?? {} }
|
|
128
|
+
: (configuration !== undefined && Object.keys(configuration.override ?? {}).length > 0
|
|
129
|
+
? { name: configuration.entry.options.name, config: configuration.override }
|
|
130
|
+
: undefined)
|
|
131
|
+
|
|
132
|
+
return {
|
|
133
|
+
rowId: spec.id,
|
|
134
|
+
entryFound: entry !== undefined,
|
|
135
|
+
overrideRow,
|
|
136
|
+
inherited: configuration?.inherited ?? {},
|
|
137
|
+
effective: entry?.options?.config ?? configuration?.entry?.options?.config ?? {},
|
|
138
|
+
targetDays: spec.id === 'connection' ? options.targetDays : undefined,
|
|
139
|
+
shadowedBy: homeRead.exists && homeRead.parsed.ok && findOverrideRow(homeRead.parsed, spec.id) !== undefined ? 'home' : null,
|
|
140
|
+
// 整层合法性:profile 层解析不了就是 P11;home 层解析不了只是看不见影子(不谎报)
|
|
141
|
+
fileParse: profileRead.exists ? profileRead.parsed : { ok: true, rows: [], hadFlowRoot: false },
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function check(options = {}) {
|
|
146
|
+
const ce = getEditor()
|
|
147
|
+
if (ce === undefined || typeof ce.entries !== 'function') {
|
|
148
|
+
return { level: 'skipped', reason: 'no-config-editor', rows: [], documentPath: '' }
|
|
149
|
+
}
|
|
150
|
+
const opts = { targetDays: options.targetDays ?? 1, ...options }
|
|
151
|
+
const rows = Object.keys(MANAGED_ROWS).map((rowId) => assessRow(buildInput(rowId, ce, opts)))
|
|
152
|
+
const documentPath = typeof ce.documentPath === 'string' ? ce.documentPath : ''
|
|
153
|
+
// 上次修复的可审计信息:面板重开也该看得到,不能只在点完按钮那一瞬存在
|
|
154
|
+
const snap = readSnapshot(snapFile(), fsModule)
|
|
155
|
+
const connSnap = snap?.rows?.connection
|
|
156
|
+
const lastFix = connSnap === undefined ? undefined : {
|
|
157
|
+
at: connSnap.generatedAt ?? null,
|
|
158
|
+
beforeDays: connSnap.config?.cookieMaxAgeDays,
|
|
159
|
+
targetDays: connSnap.targetDays,
|
|
160
|
+
}
|
|
161
|
+
// 端口留痕已随端口写入能力一并删除(本插件不写端口,快照里不再开 webserver 行)。
|
|
162
|
+
return { ...aggregateAll(rows), documentPath, rows, lastFix, checkedAt: new Date(now()).toISOString() }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** 只给用户看的粘贴块(webserver 行、以及 CLI 侧无法写时的处方)。 */
|
|
166
|
+
function plan(options = {}) {
|
|
167
|
+
const result = check(options)
|
|
168
|
+
const ce = getEditor()
|
|
169
|
+
if (ce === undefined) return { ...result, blocks: [] }
|
|
170
|
+
// 有偏差的行要给粘贴块;**表达式被抄成字面量**的行也算(它不改档位,但只有这里能提)。
|
|
171
|
+
const blocks = result.rows
|
|
172
|
+
.filter((row) => row.findings.length > 0 || (row.exprFrozen ?? []).length > 0)
|
|
173
|
+
.map((row) => {
|
|
174
|
+
const spec = MANAGED_ROWS[row.rowId]
|
|
175
|
+
const entry = ce.entries().find((item) => item.options.id === spec.id)
|
|
176
|
+
const configuration = (ce.configuration() ?? []).find((item) => item.entry.options.id === spec.id)
|
|
177
|
+
return {
|
|
178
|
+
rowId: row.rowId,
|
|
179
|
+
writable: spec.writable,
|
|
180
|
+
exprFrozen: row.exprFrozen ?? [],
|
|
181
|
+
block: nextBlockFor(row.rowId, configuration?.inherited ?? {}, entry?.options?.config ?? {}, options),
|
|
182
|
+
}
|
|
183
|
+
})
|
|
184
|
+
return { ...result, documentPath: ce.documentPath ?? '', blocks }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function nextBlockFor(rowId, inherited, current, options) {
|
|
188
|
+
// 表达式档:把 bundle 层原有的表达式还原回去(表达式串取自 inherited,绝不硬编码)
|
|
189
|
+
const merged = { ...inherited, ...current }
|
|
190
|
+
if (options.guardMode === 'expression') {
|
|
191
|
+
for (const [key, value] of Object.entries(inherited)) {
|
|
192
|
+
if (value !== null && typeof value === 'object' && typeof value.__jsExpr === 'string') merged[key] = value
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (rowId === 'connection' && options.targetDays !== undefined) merged.cookieMaxAgeDays = options.targetDays
|
|
196
|
+
return renderBlock(rowId, merged)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function attemptEdit(entry, next) {
|
|
200
|
+
const ce = getEditor()
|
|
201
|
+
try {
|
|
202
|
+
await ce.edit(entry, () => next)
|
|
203
|
+
return { ok: true, nested: false }
|
|
204
|
+
} catch (e) {
|
|
205
|
+
const message = String(e && e.message ? e.message : e)
|
|
206
|
+
if (!NESTED_ERROR.test(message)) return { ok: false, message, nested: false }
|
|
207
|
+
// P12:热重载正在进行,退避一次再试;仍失败就如实报「稍后再点」,不谎报成功
|
|
208
|
+
await wait(400)
|
|
209
|
+
try {
|
|
210
|
+
await ce.edit(ce.entries().find((row) => row.options.id === entry.options.id), () => next)
|
|
211
|
+
return { ok: true, nested: true, retried: true }
|
|
212
|
+
} catch (e2) {
|
|
213
|
+
return { ok: false, message: String(e2 && e2.message ? e2.message : e2), nested: true }
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* 修复:把 connection 行的 cookieMaxAgeDays 拉到目标档,其余键按运行态原样保留。
|
|
220
|
+
* 判定为不可动作(P2/P4/P6/P10/P11)时**一次都不写**。
|
|
221
|
+
*/
|
|
222
|
+
async function fix(options = {}) {
|
|
223
|
+
const result = check(options)
|
|
224
|
+
const target = result.rows.find((row) => row.rowId === MANAGED_ROWS.connection.id)
|
|
225
|
+
if (target === undefined) return { kind: 'blocked', reason: 'no-connection-row', result }
|
|
226
|
+
if (!target.actionable) {
|
|
227
|
+
return { kind: 'blocked', codes: target.findings.map((f) => f.code), level: target.level, result }
|
|
228
|
+
}
|
|
229
|
+
const ce = getEditor()
|
|
230
|
+
const entry = ce.entries().find((row) => row.options.id === MANAGED_ROWS.connection.id)
|
|
231
|
+
if (entry === undefined) return { kind: 'blocked', codes: ['P10'], result }
|
|
232
|
+
|
|
233
|
+
const before = plain(entry.options.config ?? {})
|
|
234
|
+
const spec = MANAGED_ROWS.connection
|
|
235
|
+
const configuration = (ce.configuration() ?? []).find((row) => row.entry.options.id === spec.id)
|
|
236
|
+
const { next, changed } = nextConfigFor({
|
|
237
|
+
current: entry.options.config ?? {},
|
|
238
|
+
targetDays: options.targetDays ?? 1,
|
|
239
|
+
guardMode: options.guardMode,
|
|
240
|
+
inherited: configuration?.inherited ?? {},
|
|
241
|
+
})
|
|
242
|
+
if (changed.length === 0) return { kind: 'noop', result, before }
|
|
243
|
+
|
|
244
|
+
const written = await attemptEdit(entry, next)
|
|
245
|
+
if (!written.ok) return { kind: 'failed', message: written.message, nested: written.nested === true, result }
|
|
246
|
+
|
|
247
|
+
try {
|
|
248
|
+
keepSnapshotRow(snapFile(), spec.id, { name: spec.name, profile: snapshotKey(ce.documentPath ?? ''), config: before, at: now(), generatedAt: new Date(now()).toISOString(), targetDays: options.targetDays ?? 1 }, fsModule)
|
|
249
|
+
} catch { /* 快照失败不影响已落盘的修复,只是少了回滚 */ }
|
|
250
|
+
|
|
251
|
+
const after = ce.entries().find((row) => row.options.id === spec.id)
|
|
252
|
+
const effective = after?.options?.config?.cookieMaxAgeDays
|
|
253
|
+
const applied = effective === (options.targetDays ?? 1)
|
|
254
|
+
// 写成功后回传**重新体检**的结果:把写前的 `result` 丢给面板会让它显示“已写入”同时
|
|
255
|
+
// 又挂着“缺行・有偏差”(真机看到的就是这个矛盾)。
|
|
256
|
+
const fresh = check(options)
|
|
257
|
+
return { kind: applied ? 'fixed' : 'unverified', changed, before, beforeValue: before?.cookieMaxAgeDays, effective, applied, retried: written.retried === true, snapshotFile: snapFile(), snapshotAt: new Date(now()).toISOString(), result: fresh }
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** 回到写之前的配置(快照按行存,一次回滚把各行各自回前值;缺失就明说,不猜)。 */
|
|
261
|
+
async function revert() {
|
|
262
|
+
const ce = getEditor()
|
|
263
|
+
if (ce === undefined || typeof ce.edit !== 'function') return { kind: 'no-editor' }
|
|
264
|
+
const snapshot = readSnapshot(snapFile(), fsModule)
|
|
265
|
+
if (snapshot === undefined || Object.keys(snapshot.rows ?? {}).length === 0) return { kind: 'no-snapshot', snapshotFile: snapFile() }
|
|
266
|
+
|
|
267
|
+
const restored = []
|
|
268
|
+
const failed = []
|
|
269
|
+
let lastChanged = []
|
|
270
|
+
let connEffective
|
|
271
|
+
for (const [rowId, saved] of Object.entries(snapshot.rows)) {
|
|
272
|
+
const entry = ce.entries().find((row) => row.options.id === rowId)
|
|
273
|
+
if (entry === undefined) { failed.push({ rowId, code: 'P10' }); continue }
|
|
274
|
+
const current = plain(entry.options.config ?? {})
|
|
275
|
+
const written = await attemptEdit(entry, saved.config)
|
|
276
|
+
if (!written.ok) { failed.push({ rowId, message: written.message }); continue }
|
|
277
|
+
restored.push(rowId)
|
|
278
|
+
lastChanged = diffKeys(current, saved.config)
|
|
279
|
+
if (rowId === MANAGED_ROWS.connection.id) {
|
|
280
|
+
connEffective = ce.entries().find((row) => row.options.id === rowId)?.options?.config?.cookieMaxAgeDays
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (restored.length === 0) return { kind: 'failed', message: failed[0]?.message ?? 'nothing restored', failed }
|
|
284
|
+
return {
|
|
285
|
+
kind: 'reverted',
|
|
286
|
+
changed: lastChanged,
|
|
287
|
+
rows: restored,
|
|
288
|
+
failed,
|
|
289
|
+
effective: connEffective,
|
|
290
|
+
restoredFrom: snapshot.generatedAt ?? null,
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
return { check, plan, fix, revert, state }
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* 离线(客户端已关、宿主不存在)只能查**文件层**:运行态与 bundle 层都读不到,
|
|
299
|
+
* 所以 P5/P7/P9 这三类需要 bundle/运行态对比的规则不参与判定。宁缺毋滥:
|
|
300
|
+
* 能定死的是「行在不在、name 对不对、值合不合法、有没有被 home 层盖住、整层语法能不能解」。
|
|
301
|
+
* 与面板共用同一个 `assessRow`,绝不另开一套判定。
|
|
302
|
+
* @param {{profileFile:string, homeFile?:string, targetDays?:number, fs?:typeof import('node:fs')}} options
|
|
303
|
+
*/
|
|
304
|
+
export function offlineCheck(options) {
|
|
305
|
+
const { profileFile, homeFile = path.join(dshHome(), 'cordis.patch.yml'), targetDays = 1, fs: fsModule = fs } = options
|
|
306
|
+
const profile = readPatchFileWith(fsModule, profileFile)
|
|
307
|
+
// 「profile 根本不在这个位置」与「profile 在、但没这一行」是两回事:前者**无据**(skipped),
|
|
308
|
+
// 后者才是真偏差(P1)。把前者判成缺行会把「用户敲错 profile 名」变成一条误导性的
|
|
309
|
+
// 「cookie 会一直存活」异常,还会让退出码假绿(黑名单纪律:没真读到内容就不许 0)。
|
|
310
|
+
// 目录在、仅文件缺(新建 profile 还没写过 patch)仍走 P1——那是可修的真缺陷。
|
|
311
|
+
if (profile.exists === false && !fsModule.existsSync(path.dirname(profileFile))) {
|
|
312
|
+
return {
|
|
313
|
+
level: 'skipped',
|
|
314
|
+
rows: [],
|
|
315
|
+
actionable: false,
|
|
316
|
+
reason: 'missing-profile',
|
|
317
|
+
documentPath: profileFile,
|
|
318
|
+
homePath: homeFile,
|
|
319
|
+
offline: true,
|
|
320
|
+
checkedAt: new Date().toISOString(),
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
const home = readPatchFileWith(fsModule, homeFile)
|
|
324
|
+
const rows = Object.keys(MANAGED_ROWS).map((rowId) => {
|
|
325
|
+
const spec = MANAGED_ROWS[rowId]
|
|
326
|
+
const fileRow = profile.parsed.ok ? findOverrideRow(profile.parsed, spec.id) : undefined
|
|
327
|
+
return assessRow({
|
|
328
|
+
rowId: spec.id,
|
|
329
|
+
overrideRow: fileRow === undefined ? undefined : { name: fileRow.name, config: fileRow.config ?? {} },
|
|
330
|
+
inherited: {},
|
|
331
|
+
effective: {},
|
|
332
|
+
targetDays: spec.id === 'connection' ? targetDays : undefined,
|
|
333
|
+
shadowedBy: home.exists && home.parsed.ok && findOverrideRow(home.parsed, spec.id) !== undefined ? 'home' : null,
|
|
334
|
+
fileParse: profile.exists ? profile.parsed : { ok: true, rows: [], hadFlowRoot: false },
|
|
335
|
+
})
|
|
336
|
+
})
|
|
337
|
+
return { ...aggregateAll(rows), documentPath: profileFile, homePath: homeFile, offline: true, checkedAt: new Date().toISOString() }
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function diffKeys(a, b) {
|
|
341
|
+
const keys = new Set([...Object.keys(a ?? {}), ...Object.keys(b ?? {})])
|
|
342
|
+
return [...keys].filter((key) => JSON.stringify(a?.[key]) !== JSON.stringify(b?.[key]))
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function readPatchFileWith(fsModule, file) {
|
|
346
|
+
if (typeof file !== 'string' || file === '') {
|
|
347
|
+
return { path: file, exists: false, text: '', parsed: { ok: true, rows: [], hadFlowRoot: false } }
|
|
348
|
+
}
|
|
349
|
+
if (fsModule === fs) return readPatchFile(file)
|
|
350
|
+
// 注入替身(单测/多实例)时走等价路径,**同一份** parsePatchText,不另开一套解析
|
|
351
|
+
let text = ''
|
|
352
|
+
let exists = true
|
|
353
|
+
try {
|
|
354
|
+
text = fsModule.readFileSync(file, 'utf8')
|
|
355
|
+
} catch (e) {
|
|
356
|
+
if (e && e.code === 'ENOENT') { exists = false } else {
|
|
357
|
+
return { path: file, exists: false, text: '', parsed: { ok: false, reason: String((e && e.code) || (e && e.message)), rows: [], hadFlowRoot: false } }
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return { path: file, exists, text, parsed: exists ? parsePatchText(text) : { ok: true, rows: [], hadFlowRoot: false } }
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** 把合并后的配置渲染成 YAML 块(与 patch-model 的 renderPlanBlock 同语义,此处避免循环依赖)。 */
|
|
364
|
+
function renderBlock(rowId, merged) {
|
|
365
|
+
const spec = MANAGED_ROWS[rowId]
|
|
366
|
+
const lines = [`- id: ${spec.id}`, ` name: '${spec.name}'`, ' config:']
|
|
367
|
+
for (const [key, value] of Object.entries(merged)) {
|
|
368
|
+
if (value === undefined) continue
|
|
369
|
+
if (value !== null && typeof value === 'object' && typeof value.__jsExpr === 'string') lines.push(` ${key}: !!js ${value.__jsExpr}`)
|
|
370
|
+
else if (Array.isArray(value)) lines.push(` ${key}: ${value.length === 0 ? '[]' : JSON.stringify(value)}`)
|
|
371
|
+
else if (typeof value === 'string') lines.push(` ${key}: '${value}'`)
|
|
372
|
+
else lines.push(` ${key}: ${value}`)
|
|
373
|
+
}
|
|
374
|
+
return lines.join('\n')
|
|
375
|
+
}
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-cookie-cleaner — patch 结构判定内核(纯函数,零 IO)。
|
|
3
|
+
*
|
|
4
|
+
* 存在的理由:profile 的 `cordis.patch.yml` 是**补丁层**而不是条目列表,它的语义有三个
|
|
5
|
+
* 反直觉的坑(全部有源码依据,见 `.agents/plans/cookie-patch-guard/findings.md`):
|
|
6
|
+
*
|
|
7
|
+
* 1. patch 行按**顶层键浅赋值**(`cordis-plugin-include/src/index.ts:120-123`),所以
|
|
8
|
+
* `config:` 是整块替换而非深合并——漏写的键落回该插件的 **schema 默认**,不是落回
|
|
9
|
+
* bundle 层的值(`webserver.compression` 默认就是 `none`);
|
|
10
|
+
* 2. `name` 与宿主 bundle 行不一致时**整行静默跳过**,只在启动日志留一行 warn;
|
|
11
|
+
* 3. 层顺序是 bundle layers → profile → **home** → `--patch` overlay,home 里同 id 行会把
|
|
12
|
+
* profile 的写盖掉(官方 `configEditor` 写前检查的正是这一条)。
|
|
13
|
+
*
|
|
14
|
+
* 本模块只吃数据、只出结构化判定(code/level/params),**不碰文件系统、不取宿主服务、
|
|
15
|
+
* 不出文案**:文案由 `report.js` 经 i18n 字典渲染,IO 由 `patch-guard.js`(宿主半)与
|
|
16
|
+
* `cli.js`(只读行解析)各自负责。这样宿主半与 CLI 共用一份判定,不可能各说一套。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** @typedef {'ok'|'warn'|'fail'|'skipped'} Level */
|
|
20
|
+
|
|
21
|
+
/** 受管行:`writable` = 「修复」按钮可动(**只给 cookie 寿命**);webserver 行只参与只读判定,本插件不写它。 */
|
|
22
|
+
export const MANAGED_ROWS = Object.freeze({
|
|
23
|
+
connection: Object.freeze({
|
|
24
|
+
id: 'connection',
|
|
25
|
+
name: '@deepseek-ai/dsh-client-connection',
|
|
26
|
+
writable: true,
|
|
27
|
+
/** cookie 寿命的唯一杠杆(`connection/src/index.ts:113` 为 `natural().min(1).default(30)`)。 */
|
|
28
|
+
key: 'cookieMaxAgeDays',
|
|
29
|
+
minimum: 1,
|
|
30
|
+
}),
|
|
31
|
+
webserver: Object.freeze({
|
|
32
|
+
id: 'webserver',
|
|
33
|
+
name: '@deepseek-ai/dsh-host-webserver',
|
|
34
|
+
writable: false,
|
|
35
|
+
key: 'port',
|
|
36
|
+
}),
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 本插件**不写端口**(用户裁决 2026-11-05):防 431 真正有效的是 cookie 寿命注入,
|
|
41
|
+
* 端口只是上游给的另一条可选缓解。原先的 `PORT_WRITE` / `isValidPort` /
|
|
42
|
+
* `portExpressionFor` / `nextPortConfig` 已全部删除;`webserver` 行仍参与只读判定(P8)。
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/** 档位优先级:聚合时取最高;`skipped` 中性,永不冒充异常。 */
|
|
46
|
+
const LEVEL_RANK = Object.freeze({ fail: 3, warn: 2, ok: 1, skipped: 0 })
|
|
47
|
+
|
|
48
|
+
/** `!!js` 表达式在 configEditor 往返里的表示形态(VERIFIED@0.2.1-rc.5)。 */
|
|
49
|
+
export function isExpression(value) {
|
|
50
|
+
return value !== null && typeof value === 'object' && typeof value.__jsExpr === 'string' && Object.keys(value).length === 1
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function nonNegativeInt(value) {
|
|
54
|
+
return typeof value === 'number' && Number.isInteger(value)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 结构比较(值都是 JSON 安全形态:标量/数组/对象/`{__jsExpr}`)。 */
|
|
58
|
+
function sameValue(a, b) {
|
|
59
|
+
if (a === b) return true
|
|
60
|
+
try { return JSON.stringify(a) === JSON.stringify(b) } catch { return false }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 值是否“有料”:空对象/空数组/空串/false/0 都视为默认形态(拿不出行为差异)。
|
|
65
|
+
* 真机教训:`webserver.tls` 在 bundle 层与运行态之间只是 `{}` 与缺省形态的区别,
|
|
66
|
+
* 却被告知「有偏差」——两边都空就没什么可报的。
|
|
67
|
+
*/
|
|
68
|
+
function isMaterial(value) {
|
|
69
|
+
if (value === null || value === undefined) return false
|
|
70
|
+
if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') return value !== false && value !== 0 && value !== ''
|
|
71
|
+
if (Array.isArray(value)) return value.length > 0 && value.some(isMaterial)
|
|
72
|
+
if (typeof value === 'object') return Object.values(value).some(isMaterial)
|
|
73
|
+
return true
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 非表达式键:只有「运行态与 bundle 层不同值、且至少一边真有内容」才算**可证明的丢**。
|
|
78
|
+
* 真机噪声源:`webserver.tls` 这类 schema 默认键——浅赋值下它没写进覆盖行,
|
|
79
|
+
* 但两边都只有默认形态(`{}` vs 缺省),行为上什么都没变,却被报成「有偏差」。
|
|
80
|
+
* 运行态根本没有这个键 → 无从判定,中性,不编造结论。
|
|
81
|
+
*/
|
|
82
|
+
function isProvenLoss(key, inheritedValue, effective) {
|
|
83
|
+
if (!(key in effective)) return false
|
|
84
|
+
if (sameValue(inheritedValue, effective[key])) return false
|
|
85
|
+
return isMaterial(inheritedValue) || isMaterial(effective[key])
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 判定单行。参数全部是**已经读好的数据**:
|
|
90
|
+
* @param {{
|
|
91
|
+
* rowId: 'connection'|'webserver',
|
|
92
|
+
* entryFound: boolean, // 宿主树里是否存在该 id 的可寻址条目
|
|
93
|
+
* overrideRow?: {name?:string, config?:Record<string,unknown>}, // profile 层的那一行
|
|
94
|
+
* inherited?: Record<string, unknown>, // bundle 层配置(可能含 {__jsExpr})
|
|
95
|
+
* effective?: Record<string, unknown>, // 运行时组合后的配置
|
|
96
|
+
* targetDays?: number, // connection 的目标寿命;webserver 忽略
|
|
97
|
+
* shadowedBy?: 'home'|'overlay'|null,
|
|
98
|
+
* fileParse?: {ok: boolean, reason?: string},
|
|
99
|
+
* }} input
|
|
100
|
+
* @returns {{rowId:string, writable:boolean, level:Level, findings:Array<{code:string, level:Level, params:object}>}}
|
|
101
|
+
*/
|
|
102
|
+
export function assessRow(input) {
|
|
103
|
+
const spec = MANAGED_ROWS[input.rowId]
|
|
104
|
+
const findings = []
|
|
105
|
+
const push = (code, level, params = {}) => findings.push({ code, level, params })
|
|
106
|
+
const out = { rowId: input.rowId, writable: spec !== undefined && spec.writable === true, level: 'ok', findings, exprFrozen: [] }
|
|
107
|
+
|
|
108
|
+
if (spec === undefined) {
|
|
109
|
+
push('P00', 'skipped', { rowId: String(input.rowId) })
|
|
110
|
+
return aggregate(out)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// P11:整层 YAML 非法(典型成因是模板根 `[]` 后面又追了分块行)——所有覆盖一起失效
|
|
114
|
+
if (input.fileParse !== undefined && input.fileParse.ok === false) {
|
|
115
|
+
push('P11', 'fail', { reason: input.fileParse.reason ?? 'invalid yaml' })
|
|
116
|
+
return aggregate(out)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const { overrideRow, inherited = {}, effective = {} } = input
|
|
120
|
+
const shadow = input.shadowedBy ?? null
|
|
121
|
+
|
|
122
|
+
// P6:home 层或命令行 overlay 含同 id 行 → profile 的写会被盖掉(configEditor 也会拒写)
|
|
123
|
+
if (shadow !== null) {
|
|
124
|
+
push('P6', 'fail', { shadow, rowId: spec.id })
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// P10:该 id 在当前宿主树里不存在 → 裸覆盖行静默跳过(`patch: entry "x" not found`)
|
|
128
|
+
if (input.entryFound === false) {
|
|
129
|
+
push('P10', 'fail', { rowId: spec.id, name: String(overrideRow?.name ?? spec.name) })
|
|
130
|
+
return aggregate(out)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (overrideRow === undefined) {
|
|
134
|
+
// P1:没有覆盖行,且运行值确实不在目标档
|
|
135
|
+
if (spec.id === 'connection') {
|
|
136
|
+
const live = effective[spec.key]
|
|
137
|
+
if (live !== input.targetDays) push('P1', 'warn', { current: live ?? '默认 30', target: input.targetDays })
|
|
138
|
+
}
|
|
139
|
+
return aggregate(out)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// P2:name 不一致 → 整行被静默跳过,配置实际未生效(最阴的一类:用户以为配上了)
|
|
143
|
+
if (overrideRow.name !== undefined && overrideRow.name !== spec.name) {
|
|
144
|
+
push('P2', 'fail', { got: String(overrideRow.name), expected: spec.name })
|
|
145
|
+
return aggregate(out)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const config = overrideRow.config ?? {}
|
|
149
|
+
|
|
150
|
+
if (spec.id === 'connection') {
|
|
151
|
+
const value = config[spec.key]
|
|
152
|
+
// P4:非法值(<1 / 非整数)。schema 会在落盘前挡住,所以这里是「别去试写」的硬闸
|
|
153
|
+
if (value !== undefined && (!nonNegativeInt(value) || value < spec.minimum)) {
|
|
154
|
+
push('P4', 'fail', { key: spec.key, got: String(value), minimum: spec.minimum })
|
|
155
|
+
}
|
|
156
|
+
// P3:合法但偏档
|
|
157
|
+
else if (typeof value === 'number' && input.targetDays !== undefined && value > input.targetDays) {
|
|
158
|
+
push('P3', 'warn', { key: spec.key, current: value, target: input.targetDays })
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// P5:只报**可证明的丢**(运行态与 bundle 层不同值且至少一边有内容)。键名清单不是证据。
|
|
163
|
+
const dropped = Object.keys(inherited).filter((key) => !(key in config))
|
|
164
|
+
const lostExpr = dropped.filter((key) => isExpression(inherited[key]))
|
|
165
|
+
const provenLost = dropped.filter((key) => !isExpression(inherited[key]) && isProvenLoss(key, inherited[key], effective))
|
|
166
|
+
if (provenLost.length > 0) {
|
|
167
|
+
push('P5', 'warn', { rowId: spec.id, dropped: provenLost })
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// P7:文件里的值与运行时组合值不一致 → 上层覆盖或热应用未跟上
|
|
171
|
+
if (spec.id === 'connection' && config[spec.key] !== undefined && effective[spec.key] !== undefined
|
|
172
|
+
&& config[spec.key] !== effective[spec.key] && shadow === null) {
|
|
173
|
+
push('P7', 'fail', { file: config[spec.key], effective: effective[spec.key] })
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (spec.id === 'webserver') {
|
|
177
|
+
// P8:port 写成字面量会夺走 `--port` 旗标权(cmdline 文档原话「a flag beats the value written beside it」)
|
|
178
|
+
const port = config[spec.key]
|
|
179
|
+
if (port !== undefined && !isExpression(port)) {
|
|
180
|
+
push('P8', 'warn', { port })
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// P9(表达式没保住形态)**不再进体检结论**:我们无权求值那个表达式,拿不出“现状有变化”的证据。
|
|
185
|
+
// 两种形态都在这里:`frozen`(覆盖层抄成了字面量)与 `lostExpr`(根本没写,表达式整块被打掉)。
|
|
186
|
+
// 数据留在 row.exprFrozen,由 plan/粘贴块那里说(那里同时能给回跟随形态的写法)。
|
|
187
|
+
const frozen = Object.keys(inherited).filter((key) => isExpression(inherited[key]) && key in config && !isExpression(config[key]))
|
|
188
|
+
const exprGone = [...frozen, ...lostExpr].sort()
|
|
189
|
+
if (exprGone.length > 0) out.exprFrozen = exprGone
|
|
190
|
+
|
|
191
|
+
return aggregate(out)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** 聚合档位(fail > warn > ok;全为 skipped 才是 skipped,中性结论不得被当成 ok 或异常)。 */
|
|
195
|
+
export function aggregate(result) {
|
|
196
|
+
const meaningful = result.findings.filter((f) => f.level !== 'skipped')
|
|
197
|
+
if (result.findings.length === 0) result.level = 'ok'
|
|
198
|
+
else if (meaningful.length === 0) result.level = 'skipped'
|
|
199
|
+
else {
|
|
200
|
+
const levels = meaningful.map((f) => f.level)
|
|
201
|
+
result.level = levels.reduce((acc, level) => (LEVEL_RANK[level] > LEVEL_RANK[acc] ? level : acc), levels[0])
|
|
202
|
+
}
|
|
203
|
+
// 可动作 = writable 且有非中性结论,且没有「写了也没用」的硬因:
|
|
204
|
+
// P2 name 不对(要改的是文件里的字)、P4 非法值(schema 会拒)、P6 上层影子(盖不住)、
|
|
205
|
+
// P10 id 不存在(写了也白写)、P11 整层非法(先修 YAML)。
|
|
206
|
+
const blocked = ['P2', 'P4', 'P6', 'P10', 'P11']
|
|
207
|
+
result.blocked = meaningful.some((f) => blocked.includes(f.code))
|
|
208
|
+
result.actionable = result.writable === true
|
|
209
|
+
&& (result.level === 'warn' || result.level === 'fail')
|
|
210
|
+
&& !result.blocked
|
|
211
|
+
return result
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** 整体聚合:任一 fail 即 fail;全 ok 才 ok。 */
|
|
215
|
+
export function aggregateAll(rows) {
|
|
216
|
+
const usable = rows.filter((row) => row.level !== 'skipped')
|
|
217
|
+
if (usable.length === 0) return { level: 'skipped', rows }
|
|
218
|
+
const level = usable.some((row) => row.level === 'fail') ? 'fail' : usable.some((row) => row.level === 'warn') ? 'warn' : 'ok'
|
|
219
|
+
return { level, rows }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* 产出写意图。**关键性质(VERIFIED@0.2.1-rc.5)**:`current` 来自运行时组合配置,
|
|
224
|
+
* 其中表达式键已是 `{__jsExpr}` 形态,所以展开即保留——用户改过的 port、既有的表达式
|
|
225
|
+
* 都不会被刷掉;我们只动要求的那一键。
|
|
226
|
+
* @param {{current:Record<string,unknown>, targetDays?:number, guardMode?:'literal'|'expression', inherited?:Record<string,unknown>}} input
|
|
227
|
+
* @returns {{next:Record<string,unknown>, changed:string[]}}
|
|
228
|
+
*/
|
|
229
|
+
export function nextConfigFor(input) {
|
|
230
|
+
const current = input.current ?? {}
|
|
231
|
+
const next = { ...current }
|
|
232
|
+
const changed = []
|
|
233
|
+
|
|
234
|
+
if (input.targetDays !== undefined && next.cookieMaxAgeDays !== input.targetDays) {
|
|
235
|
+
next.cookieMaxAgeDays = input.targetDays
|
|
236
|
+
changed.push('cookieMaxAgeDays')
|
|
237
|
+
}
|
|
238
|
+
// 表达式档:把 bundle 层本来就是表达式的键还原成 `{__jsExpr}`(表达式串取自 inherited,绝不硬编码)
|
|
239
|
+
if (input.guardMode === 'expression' && input.inherited !== undefined) {
|
|
240
|
+
for (const [key, value] of Object.entries(input.inherited)) {
|
|
241
|
+
if (isExpression(value) && !isExpression(next[key])) {
|
|
242
|
+
next[key] = value
|
|
243
|
+
changed.push(key)
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return { next, changed }
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* 生成可直接粘贴的 patch 块(用于只读面:webserver 行、以及 CLI 无法写时的处方)。
|
|
252
|
+
* 输出块序列形态,并提示 flow `[]` 根的坑(P11)。
|
|
253
|
+
* @param {{rowId:'connection'|'webserver', inherited:Record<string,unknown>, current?:Record<string,unknown>, targetDays?:number, guardMode?:'literal'|'expression'}} input
|
|
254
|
+
*/
|
|
255
|
+
export function renderPlanBlock(input) {
|
|
256
|
+
const spec = MANAGED_ROWS[input.rowId]
|
|
257
|
+
const source = { ...(input.inherited ?? {}), ...(input.current ?? {}) }
|
|
258
|
+
// 目标值在合成时就写进表里,避开「生成后再正则回改」这条脆路
|
|
259
|
+
if (spec.id === 'connection' && input.targetDays !== undefined) source[spec.key] = input.targetDays
|
|
260
|
+
const lines = [`- id: ${spec.id}`, ` name: '${spec.name}'`, ' config:']
|
|
261
|
+
for (const [key, value] of Object.entries(source)) {
|
|
262
|
+
if (isExpression(value)) {
|
|
263
|
+
lines.push(` ${key}: !!js ${value.__jsExpr}`)
|
|
264
|
+
}
|
|
265
|
+
else if (value === undefined) continue
|
|
266
|
+
else if (Array.isArray(value)) lines.push(` ${key}: ${value.length === 0 ? '[]' : JSON.stringify(value)}`)
|
|
267
|
+
else if (typeof value === 'string') lines.push(` ${key}: '${value}'`)
|
|
268
|
+
else lines.push(` ${key}: ${value}`)
|
|
269
|
+
}
|
|
270
|
+
return lines.join('\n')
|
|
271
|
+
}
|