dsh-cookie-cleaner 0.2.3 → 0.6.4
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 +242 -158
- package/README.md +442 -309
- package/dsh.plugin.json +2 -2
- package/lib/client.js +164 -3
- package/lib/client.js.map +1 -1
- package/package.json +4 -4
- package/scripts/hosts.mjs +15 -7
- package/scripts/sync-hosts.mjs +2 -2
- package/src/api-routes.js +7 -2
- package/src/cli.js +14 -2
- package/src/client/card.tsx +68 -1
- package/src/client/locales.ts +7 -0
- package/src/client/routes.ts +14 -0
- package/src/core.js +21 -8
- package/src/i18n.js +3 -2
- package/src/index.js +194 -19
- package/src/locales-dict.js +4 -0
- package/src/locales-dict2.js +4 -0
- package/src/locales-patch.js +4 -0
- package/src/patch-guard.js +42 -1
- package/src/report.js +14 -0
- package/src/runtime-guard.js +269 -0
package/src/locales-dict.js
CHANGED
|
@@ -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})',
|
package/src/locales-dict2.js
CHANGED
|
@@ -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})',
|
package/src/locales-patch.js
CHANGED
|
@@ -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
|
/**
|
package/src/patch-guard.js
CHANGED
|
@@ -291,7 +291,48 @@ export function createPatchGuard(deps) {
|
|
|
291
291
|
}
|
|
292
292
|
}
|
|
293
293
|
|
|
294
|
-
|
|
294
|
+
/**
|
|
295
|
+
* 本插件自己的配置行(patch id = 'cookie-cleaner')——运行期守护开关与阈值都在这行。
|
|
296
|
+
* 读写都走同一个 configEditor.edit(目标插件 Config schema 校验 + 原子写 + HMR 热应用)。
|
|
297
|
+
*/
|
|
298
|
+
const OWN_ROW_ID = 'cookie-cleaner'
|
|
299
|
+
const GUARD_KEYS = ['runtimeGuard', 'maxHeaderBytes', 'keep', 'retireAbove']
|
|
300
|
+
function guardEntry() {
|
|
301
|
+
const ce = getEditor()
|
|
302
|
+
if (ce === undefined || typeof ce.entries !== 'function') return undefined
|
|
303
|
+
return ce.entries().find((row) => row.options.id === OWN_ROW_ID || row.options.name === 'dsh-cookie-cleaner')
|
|
304
|
+
}
|
|
305
|
+
/** 读当前生效的守护配置(拿不到行就 available:false,不编造默认值当生效态)。 */
|
|
306
|
+
function readGuard() {
|
|
307
|
+
const entry = guardEntry()
|
|
308
|
+
if (entry === undefined) return { available: false, runtimeGuard: false, maxHeaderBytes: 65536, keep: 4, retireAbove: 0 }
|
|
309
|
+
const c = entry.options.config ?? {}
|
|
310
|
+
return {
|
|
311
|
+
available: true,
|
|
312
|
+
runtimeGuard: c.runtimeGuard === true,
|
|
313
|
+
maxHeaderBytes: Number.isInteger(c.maxHeaderBytes) ? c.maxHeaderBytes : 65536,
|
|
314
|
+
keep: Number.isInteger(c.keep) ? c.keep : 4,
|
|
315
|
+
retireAbove: Number.isInteger(c.retireAbove) ? c.retireAbove : 0,
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
/** 写守护配置(只动白名单四键,其余 config 原样保留;无变化不写)。 */
|
|
319
|
+
async function writeGuard(patch = {}) {
|
|
320
|
+
const entry = guardEntry()
|
|
321
|
+
if (entry === undefined) return { kind: 'no-entry' }
|
|
322
|
+
const current = entry.options.config ?? {}
|
|
323
|
+
const next = { ...current }
|
|
324
|
+
if (patch.runtimeGuard !== undefined) next.runtimeGuard = patch.runtimeGuard === true
|
|
325
|
+
if (patch.maxHeaderBytes !== undefined) next.maxHeaderBytes = Math.trunc(Number(patch.maxHeaderBytes))
|
|
326
|
+
if (patch.keep !== undefined) next.keep = Math.trunc(Number(patch.keep))
|
|
327
|
+
if (patch.retireAbove !== undefined) next.retireAbove = Math.trunc(Number(patch.retireAbove))
|
|
328
|
+
const changed = GUARD_KEYS.filter((key) => JSON.stringify(current[key]) !== JSON.stringify(next[key]))
|
|
329
|
+
if (changed.length === 0) return { kind: 'noop', value: readGuard() }
|
|
330
|
+
const written = await attemptEdit(entry, next)
|
|
331
|
+
if (!written.ok) return { kind: 'failed', message: written.message }
|
|
332
|
+
return { kind: 'saved', changed, value: readGuard(), retried: written.retried === true }
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
return { check, plan, fix, revert, readGuard, writeGuard, state }
|
|
295
336
|
}
|
|
296
337
|
|
|
297
338
|
/**
|
package/src/report.js
CHANGED
|
@@ -204,6 +204,20 @@ export function patchReportText(result, cfg = {}) {
|
|
|
204
204
|
lines.push(live ?? `${String(c.authCookies ?? '?')} dsh-auth-* / ${String(c.totalCookies ?? '?')} total`)
|
|
205
205
|
}
|
|
206
206
|
}
|
|
207
|
+
// 运行期守护状态行(面板与命令面共用):runtimeGuard 字段存在才渲染,旧行为不受影响。
|
|
208
|
+
if (result.runtimeGuard !== undefined) {
|
|
209
|
+
lines.push('')
|
|
210
|
+
if (result.runtimeGuard === true) {
|
|
211
|
+
lines.push(patchText('text', 'guardOn', lang, {
|
|
212
|
+
budget: String(result.maxHeaderBytes ?? 65536),
|
|
213
|
+
keep: String(result.keep ?? 4),
|
|
214
|
+
cap: '96',
|
|
215
|
+
}))
|
|
216
|
+
} else {
|
|
217
|
+
lines.push(patchText('text', 'guardOff', lang))
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
207
221
|
if (cfg.outcome !== undefined) lines.push('', patchOutcomeText(cfg.outcome, { lang }))
|
|
208
222
|
return lines.join('\n')
|
|
209
223
|
}
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-cookie-cleaner — 运行期守护模块(薄整合自第三方 dsh-auth-cookie-guard)。
|
|
3
|
+
*
|
|
4
|
+
* 语义边界(本模块**只走 HTTP**,绝不打开 SQLite 写盘):
|
|
5
|
+
*
|
|
6
|
+
* 1. 抬 webServer 监听器的 `server.maxHeaderSize`(默认 64 KiB)——431 在 Node 解析层就抛,
|
|
7
|
+
* 不进 'request' 事件;不抬这个,退休逻辑根本没机会跑。Node 是**每 accept 一条新连接建
|
|
8
|
+
* parser 时**读该属性,所以运行时赋值即可对**新连接**当场生效(README 里那句"无需重启桌面端"
|
|
9
|
+
* 的物理依据;对已建立的 keep-alive socket 无效,但 DSH 桌面每次启动都新建 TCP)。
|
|
10
|
+
* 2. prepend 'request' 监听 `retire`:只解析 Cookie 头里的**名字**(形状 `dsh-auth-<43 base64url>`),
|
|
11
|
+
* 浏览器 jar 按 creation-time 旧→新发送(RFC 6265 §5.4),所有启动 cookie 都是 Path=/,
|
|
12
|
+
* 故尾部 keep 条 = 最新 keep 条;再加上"当前 host:port 派生的那条"保底,其余下发
|
|
13
|
+
* `Set-Cookie: name=; Max-Age=0; Path=/; Expires=...` 让浏览器自己从 jar 与磁盘库里退休。
|
|
14
|
+
* 3. 每响应最多 96 条删除行(≈ 12 KiB),留在 Node HTTP 客户端 16 KiB 响应头预算之内;
|
|
15
|
+
* 大 jar 分批多轮删完。
|
|
16
|
+
* 4. 不解 cookie 值(值是签名会话载荷)、不写日志、不新增依赖(只用 node:crypto)。
|
|
17
|
+
*
|
|
18
|
+
* 与 dsh-auth-cookie-guard 的差异:本模块**由 dsh-cookie-cleaner 装载并在 config.runtimeGuard
|
|
19
|
+
* 为 true 时才挂**;默认关,保持"离线 SQLite 清理 + 只读播报"的原语义。若与 dsh-auth-cookie-guard
|
|
20
|
+
* 同时启用,二者语义不冲突但会双份下发删除行、日志重复——同一 profile 建议二选一。
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { createHash } from 'node:crypto'
|
|
24
|
+
|
|
25
|
+
/** 上游 mint 的启动 cookie 前缀(dsh-client-connection 里 sha256(host:port) 的 base64url)。 */
|
|
26
|
+
const PREFIX = 'dsh-auth-'
|
|
27
|
+
|
|
28
|
+
/** 精确形状:前缀 + 43 字符 base64url 摘要。名字不合此形状一律不动(避免越界)。 */
|
|
29
|
+
const MINTED = /^dsh-auth-[A-Za-z0-9_-]{43}$/
|
|
30
|
+
|
|
31
|
+
/** 让浏览器删掉本条 cookie 的属性组合。Path=/ 必须匹配 mint 时的路径,不然命中不到。 */
|
|
32
|
+
const EXPIRATION = 'Max-Age=0; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT'
|
|
33
|
+
|
|
34
|
+
/** 单响应携带上限;~125 B/条 → ~12 KiB,稳在 undici/Node 默认 16 KiB 响应头预算之下。 */
|
|
35
|
+
const MAX_RETIRE_PER_RESPONSE = 96
|
|
36
|
+
|
|
37
|
+
/** 默认档位;可被 config 覆盖,但夹在 LIMITS 之间。 */
|
|
38
|
+
export const DEFAULTS = Object.freeze({ maxHeaderBytes: 64 * 1024, keep: 4, retireAbove: 0 })
|
|
39
|
+
|
|
40
|
+
/** 配置边界——防止误配把守护自己变成 431/内存杀手。 */
|
|
41
|
+
export const LIMITS = Object.freeze({
|
|
42
|
+
maxHeaderBytes: [16 * 1024, 1024 * 1024],
|
|
43
|
+
keep: [1, 64],
|
|
44
|
+
retireAbove: [0, 10_000],
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 计算某 authority 对应的启动 cookie 名(与上游 mint 路径一致)。
|
|
49
|
+
* http: 走 url.host(含端口),https: 走 url.origin。
|
|
50
|
+
* @param {'http:'|'https:'} protocol
|
|
51
|
+
* @param {string|undefined} host 形如 `127.0.0.1:34568` 的 authority
|
|
52
|
+
* @returns {string|undefined} MINTED 名字;authority 不可读时 undefined
|
|
53
|
+
*/
|
|
54
|
+
export function cookieNameOf(protocol, host) {
|
|
55
|
+
if (typeof host !== 'string' || host === '') return undefined
|
|
56
|
+
try {
|
|
57
|
+
const url = new URL(`${protocol}//${host}`)
|
|
58
|
+
const authority = protocol === 'https:' ? url.origin : url.host
|
|
59
|
+
return PREFIX + createHash('sha256').update(authority).digest('base64url')
|
|
60
|
+
} catch {
|
|
61
|
+
return undefined
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 从 webServer 服务的 origin 读出协议与绑定 host,作为无 Host 头请求的兜底。
|
|
67
|
+
* @param {{getOrigin?: () => string}} webServer
|
|
68
|
+
* @returns {{protocol: string, boundName: string | undefined}}
|
|
69
|
+
*/
|
|
70
|
+
function listenerIdentity(webServer) {
|
|
71
|
+
try {
|
|
72
|
+
const url = new URL(webServer.getOrigin())
|
|
73
|
+
return { protocol: url.protocol, boundName: cookieNameOf(url.protocol, url.host) }
|
|
74
|
+
} catch {
|
|
75
|
+
return { protocol: 'http:', boundName: undefined }
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 配置夹位;非法回退到默认。 */
|
|
80
|
+
function bounded(value, fallback, [min, max]) {
|
|
81
|
+
const n = Number(value)
|
|
82
|
+
if (value === undefined || value === null || !Number.isFinite(n)) return fallback
|
|
83
|
+
return Math.min(max, Math.max(min, Math.trunc(n)))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 队列 Set-Cookie 删除行到当次响应的 writeHead 时刻,避免被应用层对象头 set-cookie 键整体替换吃掉。
|
|
88
|
+
*
|
|
89
|
+
* 真实握手是 `res.writeHead(303, { 'set-cookie': 会话 })` 的对象形态——Node 会**整块替换**同名键,
|
|
90
|
+
* 提前 `res.setHeader('set-cookie', ...)` 会被覆盖掉。这里拦截 writeHead,把 pending 与
|
|
91
|
+
* 应用层自己的 set-cookie 合并后再交给原方法,三种调用形态(对象、三参数、平铺数组)都覆盖。
|
|
92
|
+
*
|
|
93
|
+
* @param {import('node:http').ServerResponse} res
|
|
94
|
+
* @param {string[]} lines `name=; Max-Age=0; Path=/; Expires=...` 序列化
|
|
95
|
+
*/
|
|
96
|
+
function armCookies(res, lines) {
|
|
97
|
+
if (lines.length === 0) return
|
|
98
|
+
const state = res[COOKIES] ?? (res[COOKIES] = { lines: [], armed: false })
|
|
99
|
+
state.lines.push(...lines)
|
|
100
|
+
if (state.armed) return
|
|
101
|
+
state.armed = true
|
|
102
|
+
|
|
103
|
+
const writeHead = res.writeHead
|
|
104
|
+
res.writeHead = function (statusCode, statusMessage, headers) {
|
|
105
|
+
const pending = state.lines
|
|
106
|
+
let message
|
|
107
|
+
if (typeof statusMessage === 'string') message = statusMessage
|
|
108
|
+
else headers = statusMessage
|
|
109
|
+
|
|
110
|
+
if (Array.isArray(headers)) {
|
|
111
|
+
headers = [...headers, ...pending.flatMap((line) => ['set-cookie', line])]
|
|
112
|
+
} else if (headers !== undefined && headers !== null) {
|
|
113
|
+
const copy = {}
|
|
114
|
+
const cookies = []
|
|
115
|
+
for (const key of Object.keys(headers)) {
|
|
116
|
+
if (key.toLowerCase() === 'set-cookie') cookies.push(...normalizeCookieValues(headers[key]))
|
|
117
|
+
else copy[key] = headers[key]
|
|
118
|
+
}
|
|
119
|
+
copy['set-cookie'] = [...cookies, ...pending]
|
|
120
|
+
headers = copy
|
|
121
|
+
} else {
|
|
122
|
+
res.setHeader('set-cookie', [...normalizeCookieValues(res.getHeader('set-cookie')), ...pending])
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return message === undefined
|
|
126
|
+
? writeHead.call(res, statusCode, headers)
|
|
127
|
+
: writeHead.call(res, statusCode, message, headers)
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const COOKIES = Symbol('cookie-cleaner.runtime-guard.cookies')
|
|
132
|
+
|
|
133
|
+
/** 把 set-cookie 现值归一到数组形态,方便合并。 */
|
|
134
|
+
function normalizeCookieValues(value) {
|
|
135
|
+
if (value === undefined) return []
|
|
136
|
+
return Array.isArray(value) ? value : [value]
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* 装配运行期守护:抬 maxHeaderSize、挂 retire 监听;返回 dispose。
|
|
141
|
+
*
|
|
142
|
+
* @param {import('node:http').Server} server 原生 http.Server 引用(ctx.webServer.server)
|
|
143
|
+
* @param {{
|
|
144
|
+
* maxHeaderBytes?: number,
|
|
145
|
+
* keep?: number,
|
|
146
|
+
* webServer?: { getOrigin?: () => string },
|
|
147
|
+
* onRetire?: (info: { total:number, retained:number, stale:number, emitted:number }) => void,
|
|
148
|
+
* }} [opts]
|
|
149
|
+
* @returns {() => void} dispose;再次调用无副作用
|
|
150
|
+
*/
|
|
151
|
+
export function installRuntimeGuard(server, opts = {}) {
|
|
152
|
+
if (server === undefined || server === null) return () => {}
|
|
153
|
+
|
|
154
|
+
const maxHeaderBytes = bounded(opts.maxHeaderBytes, DEFAULTS.maxHeaderBytes, LIMITS.maxHeaderBytes)
|
|
155
|
+
const keep = bounded(opts.keep, DEFAULTS.keep, LIMITS.keep)
|
|
156
|
+
// 阈值触发:条目数 > retireAbove 才开始退休;0 = 不设阈值(每次按 keep 收敛,现状)
|
|
157
|
+
const retireAbove = bounded(opts.retireAbove, DEFAULTS.retireAbove, LIMITS.retireAbove)
|
|
158
|
+
|
|
159
|
+
// ① 抬预算:Node 每 accept 时读该属性,运行时赋值对新连接立即生效。
|
|
160
|
+
const previous = server.maxHeaderSize
|
|
161
|
+
server.maxHeaderSize = maxHeaderBytes
|
|
162
|
+
|
|
163
|
+
// 无 Host 头的请求兜底用监听器自己的 origin(webServer 有 getOrigin 就用;否则 http:)
|
|
164
|
+
const { protocol, boundName } = listenerIdentity(opts.webServer ?? {})
|
|
165
|
+
|
|
166
|
+
// ② 挂 retire:只匹配 MINTED 形状,保留 tail-keep ∪ current;每响应最多 96 条。
|
|
167
|
+
function retire(req, res) {
|
|
168
|
+
const header = req.headers.cookie
|
|
169
|
+
if (typeof header !== 'string' || !header.includes(PREFIX)) return
|
|
170
|
+
|
|
171
|
+
const names = []
|
|
172
|
+
for (const segment of header.split(';')) {
|
|
173
|
+
const at = segment.indexOf('=')
|
|
174
|
+
if (at === -1) continue
|
|
175
|
+
const name = segment.slice(0, at).trim()
|
|
176
|
+
if (MINTED.test(name)) names.push(name)
|
|
177
|
+
}
|
|
178
|
+
if (names.length === 0) return
|
|
179
|
+
// 阈值触发:jar 里合法启动 cookie 数 ≤ retireAbove 时完全不动(连 Set-Cookie 都不发);
|
|
180
|
+
// 只有“攒到 N 条以上”才按尾部 keep 收敛,对齐“大于 40 条才开始删”的诉求。
|
|
181
|
+
if (retireAbove > 0 && names.length <= retireAbove) return
|
|
182
|
+
|
|
183
|
+
const retained = new Set(names.slice(-keep))
|
|
184
|
+
const current = cookieNameOf(protocol, req.headers.host) ?? boundName
|
|
185
|
+
if (current !== undefined) retained.add(current)
|
|
186
|
+
|
|
187
|
+
const stale = [...new Set(names)].filter((name) => !retained.has(name))
|
|
188
|
+
if (stale.length === 0) return // 稳态幂等:不包装 writeHead
|
|
189
|
+
|
|
190
|
+
const lines = stale.slice(0, MAX_RETIRE_PER_RESPONSE).map((name) => `${name}=; ${EXPIRATION}`)
|
|
191
|
+
armCookies(res, lines)
|
|
192
|
+
opts.onRetire?.({ total: names.length, retained: retained.size, stale: stale.length, emitted: lines.length })
|
|
193
|
+
}
|
|
194
|
+
server.prependListener('request', retire)
|
|
195
|
+
|
|
196
|
+
let disposed = false
|
|
197
|
+
return function dispose() {
|
|
198
|
+
if (disposed) return
|
|
199
|
+
disposed = true
|
|
200
|
+
server.removeListener('request', retire)
|
|
201
|
+
// 等值判断:防止有别的插件在我们之后又改过,dispose 别把新值踩回旧值。
|
|
202
|
+
if (server.maxHeaderSize === maxHeaderBytes) server.maxHeaderSize = previous
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* 只读解析 Cookie 头:条数、启动 cookie(MINTED 形状)条数、实测字节数。
|
|
208
|
+
* 不改任何东西、不下发 Set-Cookie。
|
|
209
|
+
* @param {string|string[]|undefined} header `req.headers.cookie`
|
|
210
|
+
* @returns {{total:number, minted:number, names:string[], headerBytes:number}}
|
|
211
|
+
*/
|
|
212
|
+
export function observeCookieHeader(header) {
|
|
213
|
+
const text = Array.isArray(header) ? header.join('; ') : typeof header === 'string' ? header : ''
|
|
214
|
+
const names = []
|
|
215
|
+
let total = 0
|
|
216
|
+
let headerBytes = text === '' ? 0 : Buffer.byteLength(text, 'utf8')
|
|
217
|
+
for (const segment of text.split(';')) {
|
|
218
|
+
const at = segment.indexOf('=')
|
|
219
|
+
if (at === -1) continue
|
|
220
|
+
const name = segment.slice(0, at).trim()
|
|
221
|
+
if (name === '') continue
|
|
222
|
+
total += 1
|
|
223
|
+
if (MINTED.test(name)) names.push(name)
|
|
224
|
+
}
|
|
225
|
+
return { total, minted: names.length, names, headerBytes }
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* 只读水位观测臂:挂 `request` 监听记录最近一次 Cookie 头的水位。
|
|
230
|
+
*
|
|
231
|
+
* 为什么必须与退休解耦:真正触发 431 的是**浏览器实际发出的 Cookie 头**(内存 jar),
|
|
232
|
+
* 而磁盘 jar 只在优雅退出时才落盘——强杀 / 崩溃后磁盘库会是旧的、甚至 0 条。
|
|
233
|
+
* 所以“水位”不能只在 `runtimeGuard` 开启时才有:守护关掉时也得看得见,否则面板/命令
|
|
234
|
+
* 只能报一个假的 0。
|
|
235
|
+
*
|
|
236
|
+
* @param {import('node:http').Server} server
|
|
237
|
+
* @param {{now?:() => number, onObserve?:(info:object)=>void}} [opts]
|
|
238
|
+
* @returns {{dispose:() => void, latest:() => object|undefined}}
|
|
239
|
+
*/
|
|
240
|
+
export function installCookieObserver(server, opts = {}) {
|
|
241
|
+
if (server === undefined || server === null) return { dispose: () => {}, latest: () => undefined }
|
|
242
|
+
const now = opts.now ?? Date.now
|
|
243
|
+
let last
|
|
244
|
+
function observe(req) {
|
|
245
|
+
const parsed = observeCookieHeader(req?.headers?.cookie)
|
|
246
|
+
if (parsed.total === 0) return // 没带 cookie 的请求不覆盖已有读数
|
|
247
|
+
last = {
|
|
248
|
+
total: parsed.total,
|
|
249
|
+
minted: parsed.minted,
|
|
250
|
+
unique: new Set(parsed.names).size,
|
|
251
|
+
headerBytes: parsed.headerBytes,
|
|
252
|
+
at: now(),
|
|
253
|
+
}
|
|
254
|
+
try { opts.onObserve?.(last) } catch { /* 观测不得弄挂请求 */ }
|
|
255
|
+
}
|
|
256
|
+
server.on('request', observe)
|
|
257
|
+
let disposed = false
|
|
258
|
+
return {
|
|
259
|
+
dispose: () => {
|
|
260
|
+
if (disposed) return
|
|
261
|
+
disposed = true
|
|
262
|
+
server.removeListener('request', observe)
|
|
263
|
+
},
|
|
264
|
+
latest: () => last,
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** 单响应携带上限(导出给测试断言用)。 */
|
|
269
|
+
export { MAX_RETIRE_PER_RESPONSE }
|