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.
@@ -0,0 +1,199 @@
1
+ /**
2
+ * dsh-cookie-cleaner — profile patch 的**只读**解析器。
3
+ *
4
+ * 为什么手写而不引 YAML 库:插件要能在客户端关闭、宿主不存在的时候裸跑(npm bin),
5
+ * 引第三方 YAML 会把「多一个依赖就多一次装机风险」搬进一个清理工具。
6
+ * 代价被诚实地框住:这里只认 profile patch 层的**实际语法子集**——
7
+ * 顶层块序列 `- ` 在第 0 列;`- id:` 覆盖行 / `- insert:` 新增行;
8
+ * 条目字段 `id|name|config` 缩进 2;config 键缩进 4(靠「比 config: 更深」判定);
9
+ * 值形态只认 数字 / 布尔 / `'quoted'` / `[a, b]` / `[]` / `!!js 表达式`;行尾 ` #` 注释可剥。
10
+ * 遇到子集外的构造(多文档、锚点、行内 flow 映射、游离缩进)一律 `ok:false` + 原因,
11
+ * 由内核报 P11/skipped——**猜错的判定比不判定更坏**。
12
+ *
13
+ * 本模块只做数据,不判档、不写盘。
14
+ */
15
+ import fs from 'node:fs'
16
+
17
+ /** 行的字段/值识别(行首 `- ` 与深度都直接在本层处理,不另存正则)。 */
18
+ const KEY_VALUE = /^(\w+):\s*(.*)$/
19
+
20
+ /** 解析一个 YAML 标量(够用子集)。`!!js` 前缀转成内核认识的 {__jsExpr}。 */
21
+ function parseScalar(raw) {
22
+ const text = String(raw ?? '').trim()
23
+ if (text === '' || text === '~' || text === 'null') return undefined
24
+ if (text.startsWith('!!js ')) return { __jsExpr: text.slice(5).trim() }
25
+ if (text === '[]') return []
26
+ if (text.startsWith('[') && text.endsWith(']')) {
27
+ const inner = text.slice(1, -1).trim()
28
+ if (inner === '') return []
29
+ return inner.split(',').map((part) => stripQuotes(part.trim()))
30
+ }
31
+ if (/^[-+]?\d+$/.test(text)) return Number(text)
32
+ if (/^[-+]?\d*\.\d+$/.test(text)) return Number(text)
33
+ if (text === 'true' || text === 'false') return text === 'true'
34
+ return stripQuotes(text)
35
+ }
36
+
37
+ function stripQuotes(text) {
38
+ if (text.length >= 2 && ((text.startsWith("'") && text.endsWith("'")) || (text.startsWith('"') && text.endsWith('"')))) {
39
+ return text.slice(1, -1)
40
+ }
41
+ return text
42
+ }
43
+
44
+ /** 剥行尾注释(` #` 才算,行首 `#` 是整行注释,交给调用方跳过)。 */
45
+ function stripComment(line) {
46
+ const idx = line.indexOf(' #')
47
+ return idx === -1 ? line : line.slice(0, idx)
48
+ }
49
+
50
+ function indentOf(line) {
51
+ return line.match(/^\s*/)[0].length
52
+ }
53
+
54
+ function applyField(entry, key, raw) {
55
+ if (key === 'id') entry.id = String(parseScalar(raw) ?? '')
56
+ else if (key === 'name') entry.name = parseScalar(raw)
57
+ else if (key === 'config') entry.config = entry.config ?? {}
58
+ else entry[key] = parseScalar(raw)
59
+ }
60
+
61
+ /**
62
+ * 解析 patch 文本。
63
+ *
64
+ * 只读**本层需要看到的深度**:顶层行(indent 0)与它的 `id|name|config`(indent 2)、
65
+ * config 键(indent 4);insert 块的新增条目(indent 4 及其字段 indent 6)。
66
+ * **更深的嵌套(如 `providers:` 里的模型列表)直接跳过而不是判错**——真实 profile
67
+ * 大量存在这种结构,把它们当语法错误会误报“整层失效”(真机踩到)。
68
+ * @param {string} text
69
+ * @returns {{ok: boolean, reason?: string, rows: Array<object>, hadFlowRoot: boolean, skippedDeep: number}}
70
+ */
71
+ export function parsePatchText(text) {
72
+ const rows = []
73
+ let current = null // 当前顶层行
74
+ let entry = null // 当前正在填字段的条目(顶层行本身,或 insert 的子条目)
75
+ let fieldsIndent = 2 // 当前条目字段的缩进(顶层行 2;insert 子条目 6)
76
+ let inConfig = false
77
+ let configIndent = -1
78
+ let hadFlowRoot = false
79
+ let blockAfterFlowRoot = false
80
+ let skippedDeep = 0
81
+ const fail = (reason) => ({ ok: false, reason, rows, hadFlowRoot, skippedDeep })
82
+
83
+ for (const rawLine of String(text ?? '').split(/\r?\n/)) {
84
+ const line = stripComment(rawLine)
85
+ if (line.trim() === '' || /^\s*#/.test(line)) continue
86
+ if (/^\[\]\s*$/.test(line)) { hadFlowRoot = true; continue }
87
+ if (/^---/.test(line) || /^[^#]*&\w+/.test(line)) return fail('unsupported yaml construct')
88
+
89
+ const indent = indentOf(line)
90
+ const item = /^\s*-\s+(.*)$/.exec(line)
91
+
92
+ if (item !== null && indent === 0) {
93
+ if (hadFlowRoot) blockAfterFlowRoot = true
94
+ inConfig = false
95
+ configIndent = -1
96
+ fieldsIndent = 2
97
+ const content = item[1].trim()
98
+ current = { insert: /^insert:\s*$/.test(content), bareId: !/^id:/.test(content) }
99
+ rows.push(current)
100
+ entry = current
101
+ if (current.insert) continue
102
+ const kv = content.match(KEY_VALUE)
103
+ if (kv === null) return fail(`unparsable row header: ${content.slice(0, 40)}`)
104
+ if (kv[1] === 'config') {
105
+ if (/^\{.*\}$/.test(kv[2].trim())) return fail('inline flow map')
106
+ configIndent = fieldsIndent
107
+ inConfig = true
108
+ applyField(entry, 'config', kv[2])
109
+ }
110
+ else applyField(entry, kv[1], kv[2])
111
+ continue
112
+ }
113
+
114
+ if (item !== null && indent > 0) {
115
+ // insert 块的新增条目(indent 4);再深就是 config 里的嵌套列表 → 跳过不判
116
+ if (current !== null && current.insert === true && indent === 4) {
117
+ inConfig = false
118
+ configIndent = -1
119
+ fieldsIndent = indent + 2
120
+ entry = { insert: false, bareId: false }
121
+ current.entries = current.entries ?? []
122
+ current.entries.push(entry)
123
+ const kv = item[1].trim().match(KEY_VALUE)
124
+ if (kv !== null) applyField(entry, kv[1], kv[2])
125
+ continue
126
+ }
127
+ skippedDeep += 1
128
+ continue
129
+ }
130
+
131
+ const kv = line.trim().match(KEY_VALUE)
132
+ if (kv === null) { skippedDeep += 1; continue }
133
+ if (entry === null) return fail('unexpected top-level indentation')
134
+
135
+ // config 的键:深度必须恰好比 `config:` 本身多 2;更深的值是嵌套结构,不属于本次判定
136
+ if (inConfig && indent === configIndent + 2) {
137
+ if (/^\{.*\}$/.test(kv[2].trim())) return fail('inline flow map')
138
+ entry.config = entry.config ?? {}
139
+ entry.config[kv[1]] = parseScalar(kv[2])
140
+ continue
141
+ }
142
+ if (inConfig && indent > configIndent + 2) { skippedDeep += 1; continue }
143
+ inConfig = false
144
+ if (indent !== fieldsIndent) { skippedDeep += 1; continue }
145
+ if (kv[1] === 'config') {
146
+ if (/^\{.*\}$/.test(kv[2].trim())) return fail('inline flow map')
147
+ configIndent = indent
148
+ inConfig = kv[2].trim() === ''
149
+ applyField(entry, 'config', kv[2])
150
+ continue
151
+ }
152
+ applyField(entry, kv[1], kv[2])
153
+ }
154
+
155
+ if (hadFlowRoot && (blockAfterFlowRoot || rows.length > 0)) {
156
+ // P11 的真实成因:模板根 `[]` 是 flow 序列,其后再接分块行会让**整层**失效
157
+ return fail('flow root `[]` followed by block rows')
158
+ }
159
+ return { ok: true, rows, hadFlowRoot, skippedDeep }
160
+ }
161
+
162
+ /** insert 块新增的条目 id(覆盖行的判定用不到,留给报告「本层新增了哪些行」)。 */
163
+ export function insertedIds(rows) {
164
+ const out = []
165
+ for (const row of rows ?? []) {
166
+ if (row.insert !== true) continue
167
+ for (const item of row.entries ?? []) if (item.id) out.push(item.id)
168
+ }
169
+ return out
170
+ }
171
+
172
+ /**
173
+ * 读文件并解析。不存在 = `exists:false`(不算失败,交 P1 判缺);解析不了 = `ok:false`。
174
+ * @param {string} file
175
+ * @returns {{path:string, exists:boolean, text:string, parsed:ReturnType<typeof parsePatchText>}}
176
+ */
177
+ export function readPatchFile(file) {
178
+ try {
179
+ const text = fs.readFileSync(file, 'utf8')
180
+ return { path: file, exists: true, text, parsed: parsePatchText(text) }
181
+ } catch (e) {
182
+ const code = e && e.code
183
+ if (code === 'ENOENT') return { path: file, exists: false, text: '', parsed: { ok: true, rows: [], hadFlowRoot: false } }
184
+ return { path: file, exists: false, text: '', parsed: { ok: false, reason: String(code || (e && e.message)), rows: [], hadFlowRoot: false } }
185
+ }
186
+ }
187
+
188
+ /** 取某个 id 的覆盖行(后写的赢——与 applyEntryPatches 的顺序语义一致)。 */
189
+ export function findOverrideRow(parsed, id) {
190
+ if (!parsed || !Array.isArray(parsed.rows)) return undefined
191
+ const hits = parsed.rows.filter((row) => row.insert === false && row.id === id)
192
+ return hits.length === 0 ? undefined : hits[hits.length - 1]
193
+ }
194
+
195
+ /** 该 id 在本层是否被提到(覆盖行或 insert 的新条目)。 */
196
+ export function mentionsId(parsed, id) {
197
+ if (!parsed || !Array.isArray(parsed.rows)) return false
198
+ return parsed.rows.some((row) => (row.insert === false && row.id === id) || (row.insert === true && (row.entries ?? []).some((item) => item.id === id)))
199
+ }
package/src/report.js CHANGED
@@ -12,6 +12,7 @@ import { fileURLToPath } from 'node:url'
12
12
  export * from './core.js'
13
13
  import { activeLang, exitInstruction, setLang } from './core.js'
14
14
  import { detectLang, translator } from './i18n.js'
15
+ import { patchText } from './locales-patch.js'
15
16
 
16
17
  const HERE = path.dirname(fileURLToPath(import.meta.url))
17
18
 
@@ -26,6 +27,35 @@ export function useDetectedLang(explicit = '') {
26
27
  return setLang(lang)
27
28
  }
28
29
 
30
+ /**
31
+ * cookie 实时读数的一句(面板/命令面/CLI 共用)。
32
+ * 没折算结果就返回 undefined —— 绝不能拿“没读到”编一个 0%。
33
+ * 借句柄快照走 `cookieLiveSnapshot`:数字是真的,但不是实时,说成实时就是谎报。
34
+ * @param {{authCookies?:number,totalCookies?:number,header?:object,snapshot?:boolean}} [stat]
35
+ * @param {string} [lang]
36
+ */
37
+ export function cookieLiveText(stat, lang) {
38
+ if (stat === undefined || stat.header === undefined) return undefined
39
+ return patchText('text', stat.snapshot === true ? 'cookieLiveSnapshot' : 'cookieLive', lang ?? activeLang(), {
40
+ count: String(stat.authCookies ?? 0),
41
+ total: String(stat.totalCookies ?? 0),
42
+ bytes: String(stat.header.bytes),
43
+ max: String(stat.header.maxHeaderBytes),
44
+ pct: String(stat.header.pct),
45
+ remaining: String(stat.header.remaining),
46
+ })
47
+ }
48
+
49
+ /**
50
+ * 读不到的分档文案。三者不能共用一句:把“路径没找到/权限不够”说成“被 Chromium 占”是误引导。
51
+ * @param {string} [reason] statCookies 的 reason
52
+ * @param {string} [lang]
53
+ */
54
+ export function cookieUnreadableText(reason, lang) {
55
+ const key = reason === 'missing' ? 'cookieMissing' : reason === 'permission' ? 'cookiePermission' : 'cookieBusy'
56
+ return patchText('text', key, lang ?? activeLang())
57
+ }
58
+
29
59
  /**
30
60
  * 组装 `/cookie-cleaner` 的输出。
31
61
  * @param {object} stat statCookies 结果(可能是 busy/permission/skipped 降级形态)
@@ -68,13 +98,17 @@ export function cookieCleanerCommandText(stat, cfg = {}) {
68
98
  }
69
99
 
70
100
  lines.push(t('dbLine', { path: stat.path, bytes: stat.bytes, total: stat.totalCookies }))
101
+ // 占用折算与面板/命令面共用同一个 `cookieLive`(同一张 9 语表),两边不得各自拼一套句式。
102
+ const liveLine = cookieLiveText(stat, lang)
71
103
  if (stat.verdict === 'ok') {
72
104
  lines.push(t('ok'))
105
+ if (liveLine !== undefined) lines.push(liveLine)
73
106
  return lines.join('\n')
74
107
  }
75
108
  lines.push(t('found', { count: stat.authCookies, expired: stat.authExpired, live: stat.authLive }))
76
109
  lines.push(t('span', { oldest: stat.oldestExpiry, newest: stat.newestExpiry }))
77
110
  lines.push(t('hostLine') + stat.byHost.map((row) => `${row.hostKey}×${row.count}`).join(', '))
111
+ if (liveLine !== undefined) lines.push(liveLine)
78
112
  lines.push(t('note'))
79
113
 
80
114
  const flag = cfg.expiredOnly === true ? ' --expired-only' : ''
@@ -83,3 +117,113 @@ export function cookieCleanerCommandText(stat, cfg = {}) {
83
117
  lines.push(t('cleanFooter'))
84
118
  return lines.join('\n')
85
119
  }
120
+
121
+ const VERDICT_KEY = Object.freeze({ ok: 'vOk', warn: 'vWarn', fail: 'vFail', skipped: 'vSkipped' })
122
+
123
+ /**
124
+ * 组装 patch 体检结果(命令面与面板共用同一份渲染,保证「按按钮」与「敲命令」不同案)。
125
+ * @param {object} result patch-guard check/plan 的返回
126
+ * @param {{lang?:string, platform?:string, outcome?:object, withPlan?:boolean}} [cfg]
127
+ */
128
+ export function patchReportText(result, cfg = {}) {
129
+ if (cfg.lang) setLang(cfg.lang)
130
+ const lang = cfg.lang ?? activeLang()
131
+ const L = (key, params) => patchText('text', key, lang, params)
132
+ const C = (code, params) => patchText('code', code, lang, params)
133
+ const lines = []
134
+
135
+ if (result.reason === 'no-config-editor') {
136
+ lines.push(L('title'))
137
+ lines.push(L('noService'))
138
+ return lines.join('\n')
139
+ }
140
+
141
+ // 无据档单独渲染:不能把「profile 不存在」混进「有偏差」的叙事里(也不给 nextFix 这种误导下一步)。
142
+ if (result.reason === 'missing-profile') {
143
+ lines.push(`${L('title')} — ${L('vSkipped')}`)
144
+ if (result.documentPath) lines.push(result.documentPath)
145
+ lines.push(L('missingProfile'))
146
+ return lines.join('\n')
147
+ }
148
+
149
+ lines.push(`${L('title')} — ${L(VERDICT_KEY[result.level] ?? 'vSkipped')}`)
150
+ if (result.documentPath) lines.push(result.documentPath)
151
+ if (result.offline === true) lines.push(L('offlineNote'))
152
+
153
+ const rows = result.rows ?? []
154
+ if (result.level === 'ok') {
155
+ // 结构无差异:一句话给肯定结论,不逐行刷「结构健康」(真机口径:用户要的是「注入正常」这个判定)。
156
+ lines.push(`\u2713 ${L('injectOk')}`)
157
+ }
158
+ else {
159
+ for (const row of rows) {
160
+ const label = row.rowId === 'connection' ? 'rowConnection' : 'rowWebserver'
161
+ lines.push(`\u25aa ${L(label)}: ${L(VERDICT_KEY[row.level] ?? 'vSkipped')}`)
162
+ for (const finding of row.findings ?? []) lines.push(` \u00b7 ${C(finding.code, finding.params)}`)
163
+ }
164
+ }
165
+
166
+ if (result.blocks !== undefined && result.blocks.length > 0) {
167
+ for (const block of result.blocks) {
168
+ lines.push('')
169
+ lines.push(L('planFor', { file: result.documentPath ?? 'cordis.patch.yml' }))
170
+ lines.push(block.block)
171
+ // 表达式被抄成字面量不在体检里刷屏,但处方里必须说清:哪些键原本会跟随上游、怎么拿回跟随形态。
172
+ if ((block.exprFrozen ?? []).length > 0) {
173
+ lines.push('')
174
+ lines.push(C('P9', { rowId: block.rowId, keys: block.exprFrozen }))
175
+ lines.push(L('exprFrozenHint'))
176
+ }
177
+ }
178
+ }
179
+
180
+ if ((result.rows ?? []).some((row) => row.rowId === 'webserver' && (row.findings ?? []).length > 0)) {
181
+ lines.push('')
182
+ lines.push(L('webserverNote'))
183
+ }
184
+ const conn = (result.rows ?? []).find((row) => row.rowId === 'connection')
185
+ // 真正有效的那一项先说明自已是哪个值:面板隐藏了端口控件后,用户得看得到
186
+ // 「修复」到底写什么。行上没带时退到顶层 targetDays(两侧任一侧有就能说清)。
187
+ const targetDays = result.targetDays ?? conn?.targetDays
188
+ if (Number.isInteger(targetDays) && targetDays >= 1) {
189
+ lines.push('')
190
+ lines.push(patchText('text', 'targetDaysLine', lang ?? activeLang(), { days: String(targetDays) }))
191
+ }
192
+ if (conn?.actionable === true && cfg.outcome === undefined) {
193
+ lines.push('')
194
+ lines.push(L('nextFix'))
195
+ }
196
+ // cookie 读数与面板同构:同一个折算函数出同一句话。
197
+ if (result.cookie !== undefined) {
198
+ const c = result.cookie
199
+ const readable = c.verdict !== 'skipped' && c.reason !== 'busy' && c.reason !== 'permission'
200
+ lines.push('')
201
+ if (!readable) lines.push(cookieUnreadableText(c.reason, lang))
202
+ else {
203
+ const live = cookieLiveText(c, lang)
204
+ lines.push(live ?? `${String(c.authCookies ?? '?')} dsh-auth-* / ${String(c.totalCookies ?? '?')} total`)
205
+ }
206
+ }
207
+ if (cfg.outcome !== undefined) lines.push('', patchOutcomeText(cfg.outcome, { lang }))
208
+ return lines.join('\n')
209
+ }
210
+
211
+ /** 修复/回滚结果的固定句式(kind 来自 patch-guard,不在此处二次判定)。 */
212
+ export function patchOutcomeText(outcome, cfg = {}) {
213
+ const lang = cfg.lang ?? activeLang()
214
+ const L = (key, params) => patchText('text', key, lang, params)
215
+ switch (outcome.kind) {
216
+ case 'fixed': return L('fixed', { changed: (outcome.changed ?? []).join(', ') })
217
+ + (outcome.retried === true ? ` (${L('vWarn')}: P12)` : '')
218
+ case 'noop': return L('noop')
219
+ case 'blocked': return L('blocked', { codes: (outcome.codes ?? []).join(', ') })
220
+ case 'failed': return L('failed', { message: outcome.message ?? 'unknown' })
221
+ case 'unverified': return L('failed', { message: `effective=${String(outcome.effective)}` })
222
+ case 'reverted': return L('reverted', { changed: (outcome.changed ?? []).join(', ') })
223
+ + ((outcome.rows ?? []).length > 1 ? ` (${(outcome.rows ?? []).join(', ')})` : '')
224
+ + ((outcome.failed ?? []).length > 0 ? ` (${L('failed', { message: (outcome.failed ?? []).map((f) => f.rowId).join(', ') })})` : '')
225
+ case 'no-snapshot': return L('noSnapshot')
226
+ case 'no-editor': return L('noService')
227
+ default: return L('failed', { message: outcome.kind ?? 'unknown' })
228
+ }
229
+ }