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/dsh.plugin.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "id": "dsh-cookie-cleaner",
3
- "version": "0.2.3",
3
+ "version": "0.6.4",
4
4
  "main": "./src/index.js",
5
5
  "description": "Cookie 清理器:解决桌面客户端启动报 `desktop welcome: Web authentication failed`(HTTP 431,随机端口致 dsh-auth-* cookie 堆积溢出请求头上限)的现象。只读播报 cookie 库里残留的本地登录凭据(dsh-auth-*,含请求头占用水位与距 431 阈值余量),随包分发「客户端完全退出后」可执行的清理命令(独占写锁 + .bak 备份,账号凭据/会话/插件配置不受影响);设置面可体检 profile 的 cordis.patch.yml 并一键修复 `connection.cookieMaxAgeDays`(cookie 有效期,可回滚)。",
6
6
  "engines": {
7
- "dsh": ">=0.2.1 <0.3.0"
7
+ "dsh": ">=0.1.0-rc.2 <0.3.0-0"
8
8
  },
9
9
  "contributes": {}
10
10
  }
package/lib/client.js CHANGED
@@ -109,7 +109,9 @@ window.__ModuleLoader__.load({
109
109
  noService: t$1("本机宿主没有 config-editor 服务(老线或未装配),体检无法在线进行", "this host has no config-editor service (older line or not assembled), so an online check is impossible", "この宿主に config-editor サービスが無いため(旧ライン/未装配)、オンライン検査は不可", "이 호스트에 config-editor 서비스가 없음(구 라인/미조립) → 온라인 점검 불가", "cet hôte n'a pas de service config-editor (ancienne ligne ou non assemblé), contrôle en ligne impossible", "dieser Host hat keinen config-editor-Dienst (ältere Zeile oder nicht montiert), Online-Prüfung unmöglich", "questo host non ha il servizio config-editor (linea vecchia o non assemblato), controllo online impossibile", "у этого хоста нет сервиса config-editor (старая линия или не собран), онлайн-проверка невозможна", "este host no tiene el servicio config-editor (línea antigua o no ensamblado), control en línea imposible"),
110
110
  missingProfile: t$1("该 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"),
111
111
  offlineNote: t$1("(离线档)只能看到文件层;运行态与 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"),
112
- editedExternally: t$1("(提示)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")
112
+ editedExternally: t$1("(提示)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"),
113
+ guardOn: t$1("运行期守护:开(监听器预算 {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)"),
114
+ guardOff: t$1("运行期守护:关(默认;本插件仅走离线 --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)")
113
115
  });
114
116
  // src/client/locales.ts
115
117
  /**
@@ -158,7 +160,14 @@ window.__ModuleLoader__.load({
158
160
  "fix.blocked": t("判定为不可动作({codes}):需按提示手工修文件", "judged not actionable ({codes}): fix the file by hand as suggested", "動作不可と判定({codes}):表示どおり手動でファイルを修正", "조치 불가({codes}): 안내대로 파일을 직접 수정", "jugé non exécutable ({codes}) : corrigez le fichier à la main", "als nicht ausführbar eingestuft ({codes}): Datei wie vorgeschlagen von Hand korrigieren", "giudicato non eseguibile ({codes}): correggere a mano il file come suggerito", "признано невыполнимым ({codes}): правьте файл вручную по подсказке", "juzgado no accionable ({codes}): corrige el archivo a mano como se sugiere"),
159
161
  "revert.done": t("已回滚:{changed}", "rolled back: {changed}", "ロールバック済み:{changed}", "되돌림: {changed}", "annulé : {changed}", "zurückgerollt: {changed}", "ripristinato: {changed}", "откатлено: {changed}", "revertido: {changed}"),
160
162
  "revert.none": t("没有可回滚的快照(修复一次才会留一份)", "no snapshot to roll back (a successful fix keeps one)", "回滚用スナップショット無し(修復成功時に 1 件保存)", "롤백 스냅샷 없음(복구 성공 시 1개 보관)", "aucun instantané à restaurer (une réparation réussie en garde un)", "kein Snapshot zum Zurückrollen (ein erfolgreicher Fix hinterlässt einen)", "nessuno snapshot da ripristinare (una correzione riuscita ne conserva uno)", "нет снимка для отката (успешное исправление сохраняет один)", "no hay instantánea a la que volver (una reparación correcta guarda una)"),
161
- "lastCheck": t("最近体检:{at}", "last check: {at}", "最近の点検:{at}", "마지막 점검: {at}", "dernier contrôle : {at}", "letzte Prüfung: {at}", "ultimo controllo: {at}", "последняя проверка: {at}", "última revisión: {at}")
163
+ "lastCheck": t("最近体检:{at}", "last check: {at}", "最近の点検:{at}", "마지막 점검: {at}", "dernier contrôle : {at}", "letzte Prüfung: {at}", "ultimo controllo: {at}", "последняя проверка: {at}", "última revisión: {at}"),
164
+ "guard.title": t("运行期守护(Set-Cookie 退休旧 cookie)", "Runtime guard (retire stale cookies via Set-Cookie)", "ランタイム守護(Set-Cookie で古い cookie を引退)", "런타임 가드 (Set-Cookie 로 오래된 cookie 정리)", "Garde en direct (retirer les vieux cookies via Set-Cookie)", "Laufzeit-Wächter (alte Cookies via Set-Cookie entfernen)", "Guardia runtime (ritira i cookie vecchi via Set-Cookie)", "Страж (удаление старых cookie через Set-Cookie)", "Guardia en ejecución (retirar cookies viejas vía Set-Cookie)"),
165
+ "guard.enable": t("启用运行期守护", "Enable runtime guard", "ランタイム守護を有効化", "런타임 가드 켜기", "Activer la garde en direct", "Laufzeit-Wächter aktivieren", "Abilita la guardia runtime", "Включить стража", "Activar guardia en ejecución"),
166
+ "guard.retireAbove": t("触发阈值(条数 > 此值才退休,0=不设阈值)", "Trigger threshold (retire only when count > this; 0 = no threshold)", "発動しきい値(件数 > この値で引退、0=なし)", "발동 임계값(개수 > 이 값이면 정리, 0=없음)", "Seuil de déclenchement (retirer si nombre > cette valeur ; 0 = aucun)", "Auslöseschwelle (erst wenn Anzahl > dieser Wert; 0 = keine)", "Soglia di attivazione (ritira se conteggio > valore; 0 = nessuna)", "Порог срабатывания (удалять если число > значения; 0 = нет)", "Umbral de disparo (retirar si cantidad > valor; 0 = ninguno)"),
167
+ "guard.keep": t("保留尾部条数(keep)", "Keep tail count (keep)", "末尾保持件数(keep)", "꼬리 유지 개수(keep)", "Nombre conservé en queue (keep)", "Anzahl am Ende behalten (keep)", "Numero mantenuto in coda (keep)", "Держать в хвосте (keep)", "Cantidad retenida en cola (keep)"),
168
+ "guard.saved": t("已写入守护设置(HMR 热生效)", "guard settings written (applies via HMR)", "守護設定を書き込みました(HMR で反映)", "가드 설정 기록됨(HMR 적용)", "réglages de la garde écrits (appliqués par HMR)", "Wächter-Einstellungen geschrieben (via HMR)", "impostazioni della guardia scritte (via HMR)", "настройки стража записаны (через HMR)", "ajustes de la guardia escritos (vía HMR)"),
169
+ "guard.noop": t("无变化,未写入", "no change, nothing written", "変更なし、書き込みなし", "변경 없음, 기록 안 함", "aucun changement", "keine Änderung", "nessun cambiamento", "без изменений", "sin cambios"),
170
+ "guard.unavailable": t("当前宿主拿不到本插件配置行(无 config-editor),无法在面板改守护设置", "the host exposes no editable row for this plugin; cannot change guard settings here", "このホストでは本プラグインの設定行を取得できず、パネルでは変更不可", "이 호스트에서 플러그인 설정 행을 얻을 수 없어 패널에서 변경 불가", "cet hôte n'expose pas de ligne éditable pour ce plugin", "dieser Host hat keine editierbare Zeile für dieses Plugin", "questo host non espone una riga modificabile per il plugin", "этот хост не даёт редактируемую строку плагина", "este host no expone una fila editable para este plugin")
162
171
  };
163
172
  /** 把共享判定表压平成 `p.P5` 形态的键(宿主只回 code,语言由界面决定)。 */
164
173
  function flatten(bucket, prefix) {
@@ -187,7 +196,9 @@ window.__ModuleLoader__.load({
187
196
  const routes = {
188
197
  check: "/api/dsh-cookie-cleaner/patch/check",
189
198
  fix: "/api/dsh-cookie-cleaner/patch/fix",
190
- revert: "/api/dsh-cookie-cleaner/patch/revert"
199
+ revert: "/api/dsh-cookie-cleaner/patch/revert",
200
+ guardGet: "/api/dsh-cookie-cleaner/guard/get",
201
+ guardSet: "/api/dsh-cookie-cleaner/guard/set"
191
202
  };
192
203
  /** POST 一跳;网络/解析失败都归成结构化错误,不让卡片白屏。 */
193
204
  async function postJson(path, body = {}) {
@@ -301,6 +312,155 @@ window.__ModuleLoader__.load({
301
312
  })
302
313
  });
303
314
  }
315
+ /**
316
+ * 运行期守护面板:一个开关(runtimeGuard)+ 两个阈值(retireAbove / keep)。
317
+ * 读写都走后端桥(configEditor 写本插件自己那行),写后回显生效值——不凭手写 YAML。
318
+ */
319
+ function GuardPanel({ t }) {
320
+ const [g, setG] = react.useState(void 0);
321
+ const [busy, setBusy] = react.useState(false);
322
+ const [note, setNote] = react.useState("");
323
+ const mounted = react.useRef(true);
324
+ react.useEffect(() => {
325
+ mounted.current = true;
326
+ postJson(routes.guardGet, {}).then((v) => {
327
+ if (mounted.current) setG(v);
328
+ }).catch(() => {});
329
+ return () => {
330
+ mounted.current = false;
331
+ };
332
+ }, []);
333
+ if (g === void 0) return null;
334
+ if (g.available === false) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
335
+ style: {
336
+ fontSize: "0.85em",
337
+ color: "var(--dsw-color-muted)"
338
+ },
339
+ children: t("guard.unavailable")
340
+ });
341
+ const toInt = (e) => {
342
+ const n = Math.trunc(Number(e.target.value));
343
+ return Number.isFinite(n) ? n : 0;
344
+ };
345
+ const commit = async (next) => {
346
+ const prev = g;
347
+ setG(next);
348
+ setBusy(true);
349
+ setNote("");
350
+ try {
351
+ const v = await postJson(routes.guardSet, {
352
+ runtimeGuard: next.runtimeGuard,
353
+ maxHeaderBytes: next.maxHeaderBytes,
354
+ keep: next.keep,
355
+ retireAbove: next.retireAbove
356
+ });
357
+ if (!mounted.current) return;
358
+ setG(v);
359
+ setNote(v.kind === "noop" ? t("guard.noop") : t("guard.saved"));
360
+ } catch (error) {
361
+ if (mounted.current) {
362
+ setG(prev);
363
+ setNote(render(t("state.failed"), { message: String(error.message ?? error) }));
364
+ }
365
+ } finally {
366
+ if (mounted.current) setBusy(false);
367
+ }
368
+ };
369
+ const inputStyle = {
370
+ width: 72,
371
+ padding: "2px 6px",
372
+ border: "1px solid var(--dsw-color-border)",
373
+ borderRadius: 6,
374
+ background: "var(--dsw-color-surface)",
375
+ color: "var(--dsw-color-text)"
376
+ };
377
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
378
+ style: {
379
+ display: "grid",
380
+ gap: 6,
381
+ marginTop: 8,
382
+ paddingTop: 8,
383
+ borderTop: "1px solid var(--dsw-color-border)"
384
+ },
385
+ children: [
386
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
387
+ style: { fontWeight: 600 },
388
+ children: t("guard.title")
389
+ }),
390
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
391
+ style: {
392
+ display: "flex",
393
+ alignItems: "center",
394
+ gap: 6
395
+ },
396
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
397
+ type: "checkbox",
398
+ checked: g.runtimeGuard,
399
+ disabled: busy,
400
+ onChange: (e) => void commit({
401
+ ...g,
402
+ runtimeGuard: e.target.checked
403
+ })
404
+ }), t("guard.enable")]
405
+ }),
406
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
407
+ style: {
408
+ display: "flex",
409
+ alignItems: "center",
410
+ gap: 8,
411
+ fontSize: "0.9em"
412
+ },
413
+ children: [t("guard.retireAbove"), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
414
+ type: "number",
415
+ min: 0,
416
+ max: 1e4,
417
+ value: g.retireAbove,
418
+ disabled: busy,
419
+ onChange: (e) => setG({
420
+ ...g,
421
+ retireAbove: toInt(e)
422
+ }),
423
+ onBlur: () => void commit(g),
424
+ onKeyDown: (e) => {
425
+ if (e.key === "Enter") commit(g);
426
+ },
427
+ style: inputStyle
428
+ })]
429
+ }),
430
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
431
+ style: {
432
+ display: "flex",
433
+ alignItems: "center",
434
+ gap: 8,
435
+ fontSize: "0.9em"
436
+ },
437
+ children: [t("guard.keep"), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
438
+ type: "number",
439
+ min: 1,
440
+ max: 64,
441
+ value: g.keep,
442
+ disabled: busy,
443
+ onChange: (e) => setG({
444
+ ...g,
445
+ keep: toInt(e)
446
+ }),
447
+ onBlur: () => void commit(g),
448
+ onKeyDown: (e) => {
449
+ if (e.key === "Enter") commit(g);
450
+ },
451
+ style: inputStyle
452
+ })]
453
+ }),
454
+ busy || note !== "" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
455
+ style: {
456
+ fontSize: "0.85em",
457
+ color: busy ? "var(--dsw-color-muted)" : "var(--dsw-color-primary)"
458
+ },
459
+ children: busy ? t("state.busy") : note
460
+ }) : null
461
+ ]
462
+ });
463
+ }
304
464
  function PatchCard({ t }) {
305
465
  const [state, setState] = react.useState(void 0);
306
466
  const [busy, setBusy] = react.useState("");
@@ -417,6 +577,7 @@ window.__ModuleLoader__.load({
417
577
  cookie: state?.cookie,
418
578
  t
419
579
  }),
580
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GuardPanel, { t }),
420
581
  state?.lastFix ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
421
582
  style: {
422
583
  fontSize: "0.85em",