dsh-cookie-cleaner 0.2.3 → 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.
@@ -0,0 +1,137 @@
1
+ /**
2
+ * dsh-cookie-cleaner — 历史注入残留的识别与清理(纯函数面,可单测)。
3
+ *
4
+ * 为什么需要这个模块:
5
+ * 0.2.1 之前,本插件曾在面板/命令面上提供过「应用端口」动作,把 `webserver` 行的
6
+ * `port` 改写成表达式 `ctx.webStartup.port ?? +<用户填的数>`(见 556e37b 及更早)。
7
+ * 2026-11-05 的裁决把端口写入能力整体删除(端口属启动行为面,不在本工具职责内),
8
+ * 但**已经写进用户 profile 的那一行不会自己消失**——它留在 `cordis.patch.yml` 里继续生效。
9
+ *
10
+ * 这一行的危害不是"插件又写端口了",而是:
11
+ * 1. 用户以为本工具已经不碰端口,实际 profile 里还钉着当年填的数;
12
+ * 2. 该表达式与 bundle 层原值可能已经不同(用户后来改过启动参数/升级过宿主),
13
+ * 表现为「启动层没传 --port 时落在旧数字上」这种难以归因的行为;
14
+ * 3. 卸载插件后残留仍在,用户找不到是谁写的。
15
+ *
16
+ * 清理原则(为什么只在 0.2.2-rc.2+ 执行):
17
+ * - 0.2.2-rc.2 起桌面外壳自带 `removeLegacyHostCookies`,cookie 侧的历史包袱由官方接管,
18
+ * 插件不再需要用"钉端口"这条侧路去压 cookie 增长;此时回收旧注入是纯收益。
19
+ * - 更早的宿主上,钉端口仍是上游 discussions 给的可选缓解之一,贸然回收可能让用户
20
+ * 重新落回"每次启动随机端口 → cookie 累积"的老路,所以那一段只**报告不清理**。
21
+ *
22
+ * 安全边界(这条最重要):**只删本插件自己写过的那一种形态**。
23
+ * 判定必须同时满足:值是指向 `webStartup.port` 的 `!!js` 表达式。用户自己手写的
24
+ * 字面量端口(P8 报的那类)、用户自己写的别的表达式,一律不碰——"看到但不替你改"。
25
+ */
26
+ import { isExpression } from './patch-model.js'
27
+
28
+ /** 本插件历史版本写过的端口表达式形态:`ctx.webStartup.port ?? <fallback>`。 */
29
+ const LEGACY_PORT_EXPRESSION = /^\s*ctx\.webStartup\.port\s*\?\?\s*(\+?\s*\d+)\s*$/
30
+
31
+ /**
32
+ * 判断一个 `!!js` 表达式值是否为本插件历史注入的端口表达式。
33
+ * @param {unknown} value 运行态配置里的值(表达式已被内核转成 `{__jsExpr}`)
34
+ * @returns {{ legacy: boolean, fallback?: number, expression?: string }}
35
+ */
36
+ export function classifyLegacyPort(value) {
37
+ if (!isExpression(value)) return { legacy: false }
38
+ const expression = value.__jsExpr
39
+ const hit = LEGACY_PORT_EXPRESSION.exec(expression)
40
+ if (hit === null) return { legacy: false, expression }
41
+ const fallback = Number(hit[1].replace(/[+\s]/g, ''))
42
+ return {
43
+ legacy: true,
44
+ fallback: Number.isInteger(fallback) ? fallback : undefined,
45
+ expression,
46
+ }
47
+ }
48
+
49
+ /**
50
+ * 扫描一行 config,找出本插件历史注入的残留。
51
+ *
52
+ * @param {{rowId?: string, current?: Record<string, unknown>, inherited?: Record<string, unknown>}} input
53
+ * `current` = 运行时组合后的配置;`inherited` = bundle 层原值(用于给出「还原成什么」)
54
+ * @returns {{ found: boolean, rowId: string, key: string, expression?: string, fallback?: number, restoreTo?: unknown }}
55
+ */
56
+ export function findLegacyInjection(input = {}) {
57
+ const rowId = String(input.rowId ?? 'webserver')
58
+ const current = input.current ?? {}
59
+ const inherited = input.inherited ?? {}
60
+ const classified = classifyLegacyPort(current.port)
61
+ if (!classified.legacy) {
62
+ return { found: false, rowId, key: 'port' }
63
+ }
64
+ const bundleValue = inherited.port
65
+ return {
66
+ found: true,
67
+ rowId,
68
+ key: 'port',
69
+ expression: classified.expression,
70
+ fallback: classified.fallback,
71
+ // 还原目标:bundle 层原值(通常是另一个表达式,也可能是字面量)。
72
+ // 拿不到 bundle 值时给 undefined,调用方据此只删覆盖行、不猜值。
73
+ restoreTo: isExpression(bundleValue) || typeof bundleValue === 'number' ? bundleValue : undefined,
74
+ }
75
+ }
76
+
77
+ /**
78
+ * 产出去掉历史注入后的 config。
79
+ *
80
+ * 语义选择:**删除该键**而不是写回 bundle 原值。
81
+ * 理由:覆盖行里少一个键 = 该键回落到 bundle 层默认,这正是"清理掉插件写的东西"该有的结果;
82
+ * 把 bundle 表达式抄进 profile 反而把上游实现细节固化进了用户配置(上游一改就脱节)。
83
+ *
84
+ * @param {{current: Record<string, unknown>, key?: string}} input
85
+ * @returns {{ next: Record<string, unknown>, changed: string[] }}
86
+ */
87
+ export function withoutLegacyInjection(input) {
88
+ const current = input.current ?? {}
89
+ const key = String(input.key ?? 'port')
90
+ if (!(key in current)) return { next: { ...current }, changed: [] }
91
+ const next = { ...current }
92
+ delete next[key]
93
+ return { next, changed: [key] }
94
+ }
95
+
96
+ /**
97
+ * 清理是否可执行 —— **以官方清理能力为准**,而不是版本号字符串。
98
+ *
99
+ * 为什么不判版本号:宿主 `ctx` 并不暴露版本(已核对 cordis/core 的 ctx 面),
100
+ * 插件能拿到的只有"外壳里有没有 `removeLegacyHostCookies`"这个**事实**。
101
+ * 而它恰好就是 0.2.2-rc.2 那条线的分界——官方接管了 cookie 清理,
102
+ * 插件才不需要再用钉端口去压 cookie 增长,回收旧注入才是纯收益。
103
+ *
104
+ * @param {{nativeCleanup?: boolean}} input
105
+ * @returns {boolean}
106
+ */
107
+ export function canCleanLegacy(input = {}) {
108
+ return input.nativeCleanup === true
109
+ }
110
+
111
+ /**
112
+ * 宿主版本是否达到「可以安全回收旧注入」的线(0.2.2-rc.2+)。
113
+ *
114
+ * 不引入 semver 依赖:本插件只判这一条线,手写比较足够,且规则显式可测。
115
+ * 版本串形态(上游实际发布):`0.2.2-rc.2` / `0.2.2` / `0.2.1-rc.5`。
116
+ *
117
+ * @param {string} version 宿主版本(如 `0.2.2-rc.3`)
118
+ * @returns {boolean}
119
+ */
120
+ export function supportsLegacyCleanup(version) {
121
+ const parsed = parseVersion(version)
122
+ if (parsed === undefined) return false
123
+ const [major, minor, patch, rc] = parsed
124
+ if (major !== 0) return major > 0
125
+ if (minor !== 2) return minor > 2
126
+ if (patch !== 2) return patch > 2
127
+ // 0.2.2 线:正式版(rc === null)或 rc >= 2 都可以;rc.0/rc.1 不行。
128
+ return rc === null || rc >= 2
129
+ }
130
+
131
+ /** 解析 `x.y.z[-rc.n]`;解析不了返回 undefined(调用方按「不支持」处理,fail-safe)。 */
132
+ function parseVersion(version) {
133
+ if (typeof version !== 'string') return undefined
134
+ const m = /^(\d+)\.(\d+)\.(\d+)(?:-rc\.(\d+))?$/.exec(version.trim())
135
+ if (m === null) return undefined
136
+ return [Number(m[1]), Number(m[2]), Number(m[3]), m[4] === undefined ? null : Number(m[4])]
137
+ }
@@ -37,6 +37,7 @@ registerDictionary('en', {
37
37
  deleted: 'Deleted {count} dsh-auth-* entries ({scope})',
38
38
  scopeAll: 'all',
39
39
  scopeExpired: 'expired only',
40
+ scopeOlderThan: 'older than {hours}h',
40
41
  dbSize: ' Database: {path} {before} B → {after} B',
41
42
  backup: ' Backup: {backup}',
42
43
  backupWith: ' (incl. {sidecars})',
@@ -91,6 +92,7 @@ registerDictionary('ja', {
91
92
  deleted: 'dsh-auth-* を {count} 件削除しました({scope})',
92
93
  scopeAll: 'すべて',
93
94
  scopeExpired: '期限切れのみ',
95
+ scopeOlderThan: '{hours} 時間より古い',
94
96
  dbSize: ' データベース:{path} {before} B → {after} B',
95
97
  backup: ' バックアップ:{backup}',
96
98
  backupWith: '({sidecars} を含む)',
@@ -142,6 +144,7 @@ registerDictionary('ko', {
142
144
  deleted: 'dsh-auth-* {count} 개 삭제({scope})',
143
145
  scopeAll: '전체',
144
146
  scopeExpired: '만료분만',
147
+ scopeOlderThan: '{hours}시간 초과',
145
148
  dbSize: ' 데이터베이스: {path} {before} B → {after} B',
146
149
  backup: ' 백업: {backup}',
147
150
  backupWith: ' ({sidecars} 포함)',
@@ -193,6 +196,7 @@ registerDictionary('fr', {
193
196
  deleted: '{count} entrées dsh-auth-* supprimées ({scope})',
194
197
  scopeAll: 'toutes',
195
198
  scopeExpired: 'expirées uniquement',
199
+ scopeOlderThan: 'plus de {hours} h',
196
200
  dbSize: ' Base : {path} {before} o → {after} o',
197
201
  backup: ' Sauvegarde : {backup}',
198
202
  backupWith: ' (dont {sidecars})',
@@ -34,6 +34,7 @@ registerDictionary('de', {
34
34
  deleted: '{count} dsh-auth-* Einträge gelöscht ({scope})',
35
35
  scopeAll: 'alle',
36
36
  scopeExpired: 'nur abgelaufene',
37
+ scopeOlderThan: 'älter als {hours} h',
37
38
  dbSize: ' Datenbank: {path} {before} B → {after} B',
38
39
  backup: ' Sicherung: {backup}',
39
40
  backupWith: ' (inkl. {sidecars})',
@@ -85,6 +86,7 @@ registerDictionary('it', {
85
86
  deleted: 'Cancellate {count} voci dsh-auth-* ({scope})',
86
87
  scopeAll: 'tutte',
87
88
  scopeExpired: 'solo scadute',
89
+ scopeOlderThan: 'più vecchi di {hours} h',
88
90
  dbSize: ' Database: {path} {before} B → {after} B',
89
91
  backup: ' Backup: {backup}',
90
92
  backupWith: ' (inclusi {sidecars})',
@@ -136,6 +138,7 @@ registerDictionary('ru', {
136
138
  deleted: 'Удалено {count} записей dsh-auth-* ({scope})',
137
139
  scopeAll: 'все',
138
140
  scopeExpired: 'только просроченные',
141
+ scopeOlderThan: 'старше {hours} ч',
139
142
  dbSize: ' База: {path} {before} Б → {after} Б',
140
143
  backup: ' Резервная копия: {backup}',
141
144
  backupWith: ' (включая {sidecars})',
@@ -187,6 +190,7 @@ registerDictionary('es', {
187
190
  deleted: 'Se borraron {count} entradas dsh-auth-* ({scope})',
188
191
  scopeAll: 'todas',
189
192
  scopeExpired: 'solo vencidas',
193
+ scopeOlderThan: 'más antiguas que {hours} h',
190
194
  dbSize: ' Base: {path} {before} B → {after} B',
191
195
  backup: ' Copia de seguridad: {backup}',
192
196
  backupWith: ' (incluidos {sidecars})',
@@ -181,6 +181,10 @@ export const PATCH_TEXT = Object.freeze({
181
181
  missingProfile: t('该 profile 不存在(目录里没有 cordis.patch.yml 且上级目录也不在)——无据可判,不是配置有问题', 'that profile does not exist (no cordis.patch.yml and its parent directory is missing) — nothing to judge, not a config defect', 'その profile は存在しません(cordis.patch.yml 無く、親ディレクトリも無い)——判定根拠無し、設定不備ではない', '해당 프로필이 존재하지 않습니다(cordis.patch.yml 없음, 상위 디렉터리도 없음) — 판단 근거 없음, 설정 결함이 아님', 'ce profil n\'existe pas (pas de cordis.patch.yml et le dossier parent manque) — rien à juger, pas un défaut de config', 'dieses Profil existiert nicht (kein cordis.patch.yml, auch das Elternverzeichnis fehlt) — keine Grundlage, kein Konfigurationsfehler', 'quel profilo non esiste (nessun cordis.patch.yml e manca la cartella superiore) — nulla da giudicare, non un difetto di config', 'этот профиль не существует (нет cordis.patch.yml и отсутствует родительский каталог) — нечего судить, это не дефект конфигурации', 'ese perfil no existe (no hay cordis.patch.yml y falta el directorio padre) — nada que juzgar, no es un defecto de configuración'),
182
182
  offlineNote: t('(离线档)只能看到文件层;运行态与 bundle 层的对比(P5/P7/P9)需要启动客户端后面板/命令来查', '(offline mode) only the file layer is visible; the runtime/bundle-layer comparisons (P5/P7/P9) need the panel or command while the client runs', '(オフライン档)ファイル層のみ閲覧可。実行状態と bundle 層の比較(P5/P7/P9)はクライアント起動後にパネル/コマンドで', '(오프라인 모드) 파일 레이어만 보입니다. 런타임/bundle 레이어 비교(P5/P7/P9)는 클라이언트 실행 후 패널/명령으로', '(mode hors ligne) seule la couche fichier est visible ; les comparaisons runtime/bundle (P5/P7/P9) exigent le panneau ou la commande avec le client lancé', '(Offline-Modus) nur die Dateiebene ist sichtbar; die Vergleiche Laufzeit/Bundle-Ebene (P5/P7/P9) brauchen Panel oder Befehl bei laufendem Client', '(modalità offline) si vede solo il layer file; i confronti runtime/layer bundle (P5/P7/P9) richiedono pannello o comando a client attivo', '(офлайн-режим) виден только слой файла; сравнения рантайма и слоя bundle (P5/P7/P9) нужны панель или команда при запущенном клиенте', '(modo sin conexión) solo se ve la capa de archivo; las comparaciones runtime/capa bundle (P5/P7/P9) necesitan el panel o el comando con el cliente activo'),
183
183
  editedExternally: t('(提示)profile patch 也可被宿主插件管理器或手改变更,体检以当前运行树为准', '(note) the profile patch may also change via the host plugin manager or hand edits; the check reports the current running tree', '(参考)profile patch は宿主のプラグインマネージャーや手編集でも変わります。体検は現在の実行中ツリーを基準にします', '(참고) profile patch는 호스트 플러그인 관리자나 수동 편집으로도 바뀜. 점검은 현재 실행 트리를 기준으로 함', '(note) le patch de profil peut aussi évoluer via le gestionnaire de plugins ou à la main ; le contrôle rend l\'arbre courant', '(Hinweis) der Profil-Patch kann sich auch über den Plugin-Manager oder per Hand ändern; die Prüfung meldet den laufenden Baum', '(nota) il patch del profilo può cambiare anche tramite il gestore plugin o a mano; il controllo riporta l\'albero in esecuzione', '(примечание) патч профиля может меняться через менеджер плагинов или вручную; проверка даёт текущее дерево', '(nota) el patch del perfil también cambia vía el gestor de plugins o a mano; la revisión reporta el árbol en ejecución'),
184
+ // 运行期守护状态行(薄整合自 dsh-auth-cookie-guard):开关两个档位,面板与命令面共用。
185
+ // 只走 HTTP 响应头,本插件仍不直接写 SQLite——语义与默认档保持一致。
186
+ guardOn: t('运行期守护:开(监听器预算 {budget} B,保留尾部 {keep} 条 + 当前端口保底,单响应最多 {cap} 条删除行)', 'runtime guard: ON (listener budget {budget} B, retaining tail {keep} + current authority, up to {cap} deletions per response)', 'ランタイム守護:オン(リッサーバジェット {budget} B、末尾 {keep} 件+現在の authority を保証、1 レスポンド最大 {cap} 件削除)', '런타임 가드: 켜힘(리스너 예산 {budget}B, 꼬리 {keep}개 + 현재 authority 보장, 응답당 최대 {cap}개 삭제)', 'garde en direct : activée (budget écouteur {budget} B, conserve les {keep} derniers + l\'autorité courante, jusqu\'à {cap} suppressions par réponse)', 'Laufzeit-Wächter: AN (Listener-Budget {budget} B, hält die letzten {keep} + aktuelle Autorität, bis zu {cap} Löschungen pro Antwort)', 'guardia runtime: ON (budget listener {budget} B, trattiene la coda {keep} + autorità corrente, fino a {cap} cancellazioni per risposta)', 'страж во время работы: ВКЛ (бюджет слушателя {budget} Б, держит хвост {keep} + текущий authority, до {cap} удалений на ответ)', 'guardia en ejecución: ACTIVADA (presupuesto del listener {budget} B, retiene cola {keep} + autoridad actual, hasta {cap} borrados por respuesta)'),
187
+ guardOff: t('运行期守护:关(默认;本插件仅走离线 --clean + patch fix,不碰运行期响应头,也不直连 SQLite)', 'runtime guard: OFF (default; this plugin only runs offline --clean + patch fix, it does not touch runtime response headers nor open SQLite directly)', 'ランタイム守護:オフ(デフォルト;本プラグインはオフライン --clean + patch fix のみで、実行時ヘッダも SQLite 直結も触らない)', '런타임 가드: 꺼짐(기본; 이 플러그인은 오프라인 --clean + patch fix 만 실행하며 런타임 헤더도 SQLite 직접도 건드리지 않음)', 'garde en direct : désactivée (par défaut ; ce plugin ne fait que --clean/patch fix hors ligne, ne touche ni les en-têtes ni SQLite)', 'Laufzeit-Wächter: AUS (Standard; dieses Plugin nutzt nur Offline-`--clean` + `patch fix` – weder Runtime-Header noch SQLite direkt)', 'guardia runtime: OFF (predefinita; questo plugin esegue solo --clean/patch fix offline, non tocca header runtime né SQLite direttamente)', 'страж: ВЫКЛ (по умолчанию; этот плагин работает только офлайн --clean + patch fix, не трогает заголовки и не открывает SQLite)', 'guardia en ejecución: DESACTIVADA (predeterminada; este plugin solo ejecuta --clean/patch fix sin runtime, no toca cabeceras ni abre SQLite)'),
184
188
  })
185
189
 
186
190
  /**