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,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-cookie-cleaner — client 半的界面文案(9 语)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么在浏览器侧自己渲染文本,而不是显示宿主算好的句子:
|
|
5
|
+
* 浏览器语言与宿主进程语言可以不同(宿主跟 LANG 走,UI 跟设置走),
|
|
6
|
+
* 面板显示服务端文案会让「中文宿主 + 英文界面」这种常见组合输出半中英。
|
|
7
|
+
* 所以宿主只回 `{code, params}`,卡片按 `locale` 服务的当前语言渲染。
|
|
8
|
+
*
|
|
9
|
+
* P1-P12 判定码复用 `src/locales-patch.js`(宿主半与 CLI 同源),这里只加界面 chrome
|
|
10
|
+
* 并把两张表压平成 `locale.register` 需要的 key→string 形态——加规则时不用改两处。
|
|
11
|
+
*/
|
|
12
|
+
import { PATCH_CODES, PATCH_LANGS, PATCH_TEXT } from '../locales-patch.js'
|
|
13
|
+
|
|
14
|
+
export type PatchLang = typeof PATCH_LANGS[number]
|
|
15
|
+
|
|
16
|
+
/** 字典命名空间 = npm 包名(与卡 id、桥路径同串)。 */
|
|
17
|
+
export const NS = 'dsh-cookie-cleaner'
|
|
18
|
+
|
|
19
|
+
/** 界面 chrome 文案(9 语并排,顺序同 PATCH_LANGS)。 */
|
|
20
|
+
const t = (zh: string, en: string, ja: string, ko: string, fr: string, de: string, it: string, ru: string, es: string) =>
|
|
21
|
+
({ zh, en, ja, ko, fr, de, it, ru, es }) as Record<PatchLang, string>
|
|
22
|
+
|
|
23
|
+
const CHROME: Record<string, Record<PatchLang, string>> = {
|
|
24
|
+
'section.title': t('Cookie 清理器', 'Cookie Cleaner', 'Cookie クリーナー', 'Cookie 청소기', 'Nettoyeur de cookies', 'Cookie-Reiniger', 'Pulitore cookie', 'Очистка cookie', 'Limpiador de cookies'),
|
|
25
|
+
'card.title': t('profile patch 体检与修复', 'Profile patch check & fix', 'profile patch の点検と修復', 'profile patch 점검 및 복구', 'Contrôle et réparation du patch de profil', 'Prüfung & Korrektur des Profil-Patches', 'Controllo e correzione del patch del profilo', 'Проверка и исправление патча профиля', 'Revisión y reparación del patch de perfil'),
|
|
26
|
+
'action.check': t('体检', 'Check', '点検', '점검', 'Contrôler', 'Prüfen', 'Controlla', 'Проверить', 'Revisar'),
|
|
27
|
+
'action.fix': t('修复', 'Fix', '修復', '복구', 'Réparer', 'Korrigieren', 'Correggi', 'Исправить', 'Reparar'),
|
|
28
|
+
'action.revert': t('回滚', 'Revert', '戻す', '되돌리기', 'Annuler', 'Rückgängig', 'Ripristina', 'Отменить', 'Revertir'),
|
|
29
|
+
// 端口控件已从面板移除(真正有效的是 cookie 寿命注入),所以这里不再有 port.* 文案;
|
|
30
|
+
// 端口相关句子统一走 `x.*`(与宿主/CLI 同一张表)。
|
|
31
|
+
'state.busy': t('进行中…', 'working…', '処理中…', '처리 중…', 'en cours…', 'läuft…', 'in corso…', 'выполняется…', 'en curso…'),
|
|
32
|
+
'state.failed': t('动作失败:{message}', 'action failed: {message}', 'アクション失敗:{message}', '동작 실패: {message}', 'échec de l\'action : {message}', 'Aktion fehlgeschlagen: {message}', 'azione fallita: {message}', 'действие не удалось: {message}', 'acción falló: {message}'),
|
|
33
|
+
'state.offline': t('宿主未提供 config-editor(老线或未装配),本面板无法在线体检/修复', 'the host exposes no config-editor (older line or not assembled); this panel cannot check or fix online', '宿主に config-editor が無く(旧ライン/未装配)、本パネルではオンライン点検・修復不可', '호스트에 config-editor가 없음(구 라인/미조립) → 이 패널에서 온라인 점검·복구 불가', 'l\'hôte n\'expose pas de config-editor (ancienne ligne ou non assemblé) ; ce panneau ne peut ni contrôler ni réparer', 'der Host stellt keinen config-editor bereit (ältere Zeile oder nicht montiert); dieses Panel kann nicht online prüfen oder korrigieren', 'l\'host non espone config-editor (linea vecchia o non assemblato); questo pannello non può controllare né correggere online', 'хост не даёт config-editor (старая линия или не собран); эта панель не может проверять или исправлять онлайн', 'el host no expone config-editor (línea antigua o no ensamblado); este panel no puede revisar ni reparar en línea'),
|
|
34
|
+
'row.connection': t('connection(cookie 寿命)', 'connection (cookie lifetime)', 'connection(cookie 寿命)', 'connection(cookie 수명)', 'connection (durée de vie des cookies)', 'connection (Cookie-Lebensdauer)', 'connection (durata cookie)', 'connection (срок жизни cookie)', 'connection (duración de cookies)'),
|
|
35
|
+
'row.webserver': t('webserver(启动面)', 'webserver (launch surface)', 'webserver(起動面)', 'webserver(시작 면)', 'webserver (surface de lancement)', 'webserver (Startebene)', 'webserver (livello di avvio)', 'webserver (слой запуска)', 'webserver (capa de arranque)'),
|
|
36
|
+
'level.ok': t('结构健康', 'structurally sound', '構造は健全', '구조 정상', 'structure saine', 'strukturell in Ordnung', 'struttura integra', 'структура здорова', 'estructura sana'),
|
|
37
|
+
'level.warn': t('有偏差', 'deviates', '偏差あり', '편차 있음', 'dérive', 'Abweichung', 'in deviazione', 'отклонение', 'desviación'),
|
|
38
|
+
'level.fail': t('会失效', 'will not take effect', '効きません', '적용 안 됨', 'sans effet', 'wirkt nicht', 'non avrà effetto', 'не сработает', 'no surtirá efecto'),
|
|
39
|
+
'level.skipped': t('无法判定', 'cannot decide', '判定不能', '판단 불가', 'indécidable', 'nicht bestimmbar', 'indecidibile', 'нельзя определить', 'indecidible'),
|
|
40
|
+
'note.webserver': t('webserver 行只体检不自动写(端口钉死属启动行为面)', 'the webserver row is checked but never auto-written (pinning the port is a launch-behaviour decision)', 'webserver 行は体検のみ・自動書き込みなし(ポート固定は起動挙動の話)', 'webserver 행은 점검만, 자동 기록 없음(포트 고정은 시작 동작 판단)', 'la ligne webserver est contrôlée mais jamais écrite (figer le port relève du lancement)', 'die webserver-Zeile wird nur geprüft, nie geschrieben (Portfestlegung ist Startverhalten)', 'la riga webserver è solo controllata, mai scritta (fissare la porta riguarda l\'avvio)', 'строка webserver только проверяется, не пишется (фиксация порта — вопрос запуска)', 'la fila webserver solo se revisa, nunca se escribe (fijar el puerto concierne al arranque)'),
|
|
41
|
+
'fix.done': t('已写入:{changed}', 'written: {changed}', '書き込み完了:{changed}', '기록됨: {changed}', 'écrit : {changed}', 'geschrieben: {changed}', 'scritto: {changed}', 'записано: {changed}', 'escrito: {changed}'),
|
|
42
|
+
'fix.noop': t('无需写入(已在目标档)', 'nothing to write (already on target)', '書き込み不要(目標達成済み)', '기록 불필요(이미 목표)', 'rien à écrire (déjà à la cible)', 'nichts zu schreiben (bereits am Ziel)', 'nulla da scrivere (già all\'obiettivo)', 'нечего писать (уже в цели)', 'nada que escribir (ya en el objetivo)'),
|
|
43
|
+
'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'),
|
|
44
|
+
'revert.done': t('已回滚:{changed}', 'rolled back: {changed}', 'ロールバック済み:{changed}', '되돌림: {changed}', 'annulé : {changed}', 'zurückgerollt: {changed}', 'ripristinato: {changed}', 'откатлено: {changed}', 'revertido: {changed}'),
|
|
45
|
+
'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)'),
|
|
46
|
+
'lastCheck': t('最近体检:{at}', 'last check: {at}', '最近の点検:{at}', '마지막 점검: {at}', 'dernier contrôle : {at}', 'letzte Prüfung: {at}', 'ultimo controllo: {at}', 'последняя проверка: {at}', 'última revisión: {at}'),
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 把共享判定表压平成 `p.P5` 形态的键(宿主只回 code,语言由界面决定)。 */
|
|
50
|
+
function flatten(bucket: Record<string, Record<PatchLang, string>>, prefix: string) {
|
|
51
|
+
const out: Record<string, Record<PatchLang, string>> = {}
|
|
52
|
+
for (const [code, entry] of Object.entries(bucket)) out[`${prefix}${code}`] = entry
|
|
53
|
+
return out
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const MERGED: Record<string, Record<PatchLang, string>> = {
|
|
57
|
+
...CHROME,
|
|
58
|
+
...flatten(PATCH_CODES, 'p.'),
|
|
59
|
+
...flatten(PATCH_TEXT, 'x.'),
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 界面用到的全部键(测试用它核对 9 语逐键相等)。 */
|
|
63
|
+
export const UI_KEYS: readonly string[] = Object.keys(MERGED)
|
|
64
|
+
|
|
65
|
+
/** `locale.register(NS, dictionaries)` 的入参。 */
|
|
66
|
+
export const dictionaries = Object.fromEntries(
|
|
67
|
+
PATCH_LANGS.map((lang) => [lang, Object.fromEntries(UI_KEYS.map((key) => [key, MERGED[key][lang]]))]),
|
|
68
|
+
) as Record<PatchLang, Record<string, string>>
|
|
69
|
+
|
|
70
|
+
/** 本地插值(`{name}` 形态,与宿主字典同规则;缺参原样留形便于发现漏参)。 */
|
|
71
|
+
export function render(text: string, params: Record<string, unknown> = {}): string {
|
|
72
|
+
return text.replace(/\{(\w+)\}/g, (_m, name: string) => {
|
|
73
|
+
const value = params[name]
|
|
74
|
+
if (value === undefined) return `{${name}}`
|
|
75
|
+
return Array.isArray(value) ? value.join(', ') : String(value)
|
|
76
|
+
})
|
|
77
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 卡片的数据臂:三条 POST 路由。
|
|
3
|
+
*
|
|
4
|
+
* URL 与宿主侧 `src/api-routes.js` 的派生式**必须逐字符一致**——两半各写一份是事实,
|
|
5
|
+
* 但一致性由 `tests/api-routes.test.js` 读两份源码比对钉住(漂移表现为卡片永远 404)。
|
|
6
|
+
*
|
|
7
|
+
* 没有 port:本插件只改 cookie 有效期,端口写入能力已整体删除(面板与命令面都不做)。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const NS = 'dsh-cookie-cleaner'
|
|
11
|
+
|
|
12
|
+
export const routes = {
|
|
13
|
+
check: '/api/dsh-cookie-cleaner/patch/check',
|
|
14
|
+
fix: '/api/dsh-cookie-cleaner/patch/fix',
|
|
15
|
+
revert: '/api/dsh-cookie-cleaner/patch/revert',
|
|
16
|
+
} as const
|
|
17
|
+
|
|
18
|
+
/** 宿主统一信封:`{ok, value}` 或 `{ok:false, code, message}`。 */
|
|
19
|
+
export interface BridgeReply<T> {
|
|
20
|
+
ok?: boolean
|
|
21
|
+
code?: string
|
|
22
|
+
message?: string
|
|
23
|
+
value?: T
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface Finding {
|
|
27
|
+
code: string
|
|
28
|
+
level: 'ok' | 'warn' | 'fail' | 'skipped'
|
|
29
|
+
params?: Record<string, unknown>
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface RowView {
|
|
33
|
+
rowId: string
|
|
34
|
+
writable?: boolean
|
|
35
|
+
level: 'ok' | 'warn' | 'fail' | 'skipped'
|
|
36
|
+
actionable?: boolean
|
|
37
|
+
/** 写了也没用的硬闸(P2/P4/P6/P10/P11):面板据此禁用动作 */
|
|
38
|
+
blocked?: boolean
|
|
39
|
+
/** 表达式被抄成字面量(或根本没写)的键:不进档位,只在处方里提 */
|
|
40
|
+
exprFrozen?: string[]
|
|
41
|
+
findings?: Finding[]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface CheckView {
|
|
45
|
+
level: 'ok' | 'warn' | 'fail' | 'skipped'
|
|
46
|
+
reason?: string
|
|
47
|
+
rows?: RowView[]
|
|
48
|
+
documentPath?: string
|
|
49
|
+
checkedAt?: string
|
|
50
|
+
offline?: boolean
|
|
51
|
+
/** 修复按钮要写入的目标寿命(宿主设置里那个值,跟结果同屏回显) */
|
|
52
|
+
targetDays?: number
|
|
53
|
+
/** 上次成功修复的留痕(面板重开也看得到,不只在这一瞬) */
|
|
54
|
+
lastFix?: { at?: string | null; beforeDays?: number; targetDays?: number }
|
|
55
|
+
/** 上次端口动作的留痕(写前值/目标值) */
|
|
56
|
+
lastPort?: { at?: string | null; before?: unknown; port?: number }
|
|
57
|
+
/** cookie 库现状:读得到就给条数与占用折算,读不到才给 reason */
|
|
58
|
+
cookie?: {
|
|
59
|
+
verdict?: string
|
|
60
|
+
reason?: string
|
|
61
|
+
path?: string
|
|
62
|
+
authCookies?: number
|
|
63
|
+
totalCookies?: number
|
|
64
|
+
bytes?: number
|
|
65
|
+
/** 读数来源:普通只读打开还是借句柄快照 */
|
|
66
|
+
source?: string
|
|
67
|
+
snapshot?: boolean
|
|
68
|
+
liveUnavailable?: boolean
|
|
69
|
+
liveReason?: string
|
|
70
|
+
header?: {
|
|
71
|
+
bytes: number
|
|
72
|
+
pct: number
|
|
73
|
+
rawPct: number
|
|
74
|
+
maxHeaderBytes: number
|
|
75
|
+
basis: string
|
|
76
|
+
threshold: number
|
|
77
|
+
remaining: number
|
|
78
|
+
over: boolean
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface ActionView {
|
|
84
|
+
kind: string
|
|
85
|
+
changed?: string[]
|
|
86
|
+
codes?: string[]
|
|
87
|
+
message?: string
|
|
88
|
+
effective?: number
|
|
89
|
+
result?: CheckView
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** POST 一跳;网络/解析失败都归成结构化错误,不让卡片白屏。 */
|
|
93
|
+
export async function postJson<T>(path: string, body: Record<string, unknown> = {}): Promise<T> {
|
|
94
|
+
const response = await fetch(path, {
|
|
95
|
+
method: 'POST',
|
|
96
|
+
headers: { 'content-type': 'application/json' },
|
|
97
|
+
body: JSON.stringify(body),
|
|
98
|
+
})
|
|
99
|
+
if (!response.ok) throw new Error(`HTTP ${String(response.status)}`)
|
|
100
|
+
const reply = (await response.json()) as BridgeReply<T>
|
|
101
|
+
if (reply.ok !== true) throw new Error(`${reply.code ?? 'unknown'} ${reply.message ?? ''}`.trim())
|
|
102
|
+
if (reply.value === undefined) throw new Error('empty reply value')
|
|
103
|
+
return reply.value
|
|
104
|
+
}
|
package/src/core.js
CHANGED
|
@@ -24,6 +24,7 @@ import os from 'node:os'
|
|
|
24
24
|
import path from 'node:path'
|
|
25
25
|
import { createRequire } from 'node:module'
|
|
26
26
|
import { exitFor, translator } from './i18n.js'
|
|
27
|
+
import { snapshotThroughHandle } from './jar-live.js'
|
|
27
28
|
import './locales-dict.js'
|
|
28
29
|
|
|
29
30
|
/** Cookie 名前缀:宿主 client-connection 生成(`COOKIE_PREFIX + sha256(authority)`)。 */
|
|
@@ -35,6 +36,44 @@ export const LOOPBACK_HOST_KEYS = Object.freeze(['127.0.0.1', 'localhost', '[::1
|
|
|
35
36
|
/** Chromium 的 `expires_utc` 是自 1601-01-01 起的微秒数。 */
|
|
36
37
|
const WINDOWS_EPOCH_OFFSET_MICROSECONDS = 11_644_473_600_000_000
|
|
37
38
|
|
|
39
|
+
/**
|
|
40
|
+
* 请求头占用折算:把「条数」翻成用户能直接判断的余量。
|
|
41
|
+
*
|
|
42
|
+
* 三个数各有出处,不是把上游报告的 228/229 当常数直接乘:
|
|
43
|
+
* - 上限 `16384` 是 Node `--max-http-header-size` 默认值(头顶过即 431,见上游 #11366 / #11410 / #11650);
|
|
44
|
+
* - `name` 列在 Chromium 库里是**明文**,所以 `SUM(LENGTH(name))` 是实测值;每条还多 `'='` 与 `'; '` 共 3 个分隔字节;
|
|
45
|
+
* - `value` 列存的是 OS 加密后的**密文**(比真正进请求头的明文长),拿它算体积会高估,
|
|
46
|
+
* 所以明文部分按上游三份报告一致的 173 B/条作估算,结果里带 `basis:'estimated'` 说清这不是精确值。
|
|
47
|
+
*/
|
|
48
|
+
export const MAX_HEADER_BYTES = 16384
|
|
49
|
+
// 每条在 Cookie 头里的格式是 `name=value; ` → '=' 一个字节 + '; ' 两个字节 = 3。
|
|
50
|
+
// 上游三份报告的实测均为 52 + 1 + 173 + 2 = 228 B/条(#11366: 71 条 = 16,188 B),这里按同一口径对齐。
|
|
51
|
+
const HEADER_SEPARATOR_BYTES = 3
|
|
52
|
+
const VALUE_BYTES_ESTIMATE = 173
|
|
53
|
+
const NAME_LENGTH_FALLBACK = 52 // 'dsh-auth-' + base64url(sha256) 实测长度,仅在拿不到 SUM 时兜底
|
|
54
|
+
|
|
55
|
+
/** @param {{count:number, nameBytes?:number}} input @returns {{bytes:number,pct:number,rawPct:number,maxHeaderBytes:number,basis:string,threshold:number,remaining:number,over:boolean}} */
|
|
56
|
+
export function headerOccupancy({ count = 0, nameBytes }) {
|
|
57
|
+
const safeCount = Number.isFinite(count) && count > 0 ? Math.floor(count) : 0
|
|
58
|
+
const names = Number.isFinite(nameBytes) && nameBytes >= 0
|
|
59
|
+
? nameBytes
|
|
60
|
+
: safeCount * NAME_LENGTH_FALLBACK
|
|
61
|
+
const bytes = names + (HEADER_SEPARATOR_BYTES + VALUE_BYTES_ESTIMATE) * safeCount
|
|
62
|
+
const rawPct = Math.round((bytes / MAX_HEADER_BYTES) * 1000) / 10
|
|
63
|
+
const average = safeCount > 0 ? bytes / safeCount : HEADER_SEPARATOR_BYTES + NAME_LENGTH_FALLBACK + VALUE_BYTES_ESTIMATE
|
|
64
|
+
const threshold = Math.floor(MAX_HEADER_BYTES / Math.max(1, average))
|
|
65
|
+
return {
|
|
66
|
+
bytes,
|
|
67
|
+
pct: Math.min(100, rawPct),
|
|
68
|
+
rawPct,
|
|
69
|
+
maxHeaderBytes: MAX_HEADER_BYTES,
|
|
70
|
+
basis: 'estimated',
|
|
71
|
+
threshold,
|
|
72
|
+
remaining: Math.max(0, threshold - safeCount),
|
|
73
|
+
over: bytes >= MAX_HEADER_BYTES,
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
38
77
|
/** 打包的 desktop 应用名(Electron 由 package.json 的 name 派生 userData 目录)。 */
|
|
39
78
|
const PRODUCT_DIR_NAMES = Object.freeze(['@deepseek-ai/dsh-desktop', 'DSH Desktop', 'deepseek-harness'])
|
|
40
79
|
|
|
@@ -295,6 +334,8 @@ export function statCookies({ userDataRoot = '', explicitPath = '', env = proces
|
|
|
295
334
|
assertCookieSchema(handle)
|
|
296
335
|
const total = toCount(handle.prepare('SELECT COUNT(*) AS c FROM cookies').get().c)
|
|
297
336
|
const byHost = handle.prepare('SELECT host_key, COUNT(*) AS c FROM cookies GROUP BY host_key ORDER BY c DESC').all()
|
|
337
|
+
// 名字长度是实测部分(明文),所以单独聚一次给占用折算用
|
|
338
|
+
const nameAgg = handle.prepare('SELECT COALESCE(SUM(LENGTH(name)), 0) AS n FROM cookies WHERE name LIKE ?').get(`${AUTH_COOKIE_PREFIX}%`)
|
|
298
339
|
const rows = handle.prepare('SELECT name, host_key, expires_utc FROM cookies WHERE name LIKE ? ORDER BY expires_utc DESC')
|
|
299
340
|
.all(`${AUTH_COOKIE_PREFIX}%`)
|
|
300
341
|
const now = BigInt(windowsNowMicroseconds())
|
|
@@ -315,6 +356,7 @@ export function statCookies({ userDataRoot = '', explicitPath = '', env = proces
|
|
|
315
356
|
authExpired: expired,
|
|
316
357
|
authLive: live,
|
|
317
358
|
byHost: byHost.map((row) => ({ hostKey: String(row.host_key), count: toCount(row.c) })),
|
|
359
|
+
header: headerOccupancy({ count: rows.length, nameBytes: toCount(nameAgg.n) }),
|
|
318
360
|
newestExpiry: rows.length > 0 ? formatChromiumTimestamp(rows[0].expires_utc) : '',
|
|
319
361
|
oldestExpiry: rows.length > 0 ? formatChromiumTimestamp(rows[rows.length - 1].expires_utc) : '',
|
|
320
362
|
}
|
|
@@ -405,6 +447,62 @@ function defaultTimestamp() {
|
|
|
405
447
|
return new Date().toISOString().replace(/[-:]/g, '').replace(/\..+/, '').replace('T', '-')
|
|
406
448
|
}
|
|
407
449
|
|
|
450
|
+
/** 借句柄快照的节流窗口(扫全机句柄表不免费)。 */
|
|
451
|
+
const LIVE_CACHE_MS = 60_000
|
|
452
|
+
const LIVE_MIN_GAP_MS = 5_000
|
|
453
|
+
/** 只缓存“哪个库的快照结果”,不缓存 cookie 内容本身。测试可传入自己的 store 隔离。 */
|
|
454
|
+
const liveCache = { at: Number.NEGATIVE_INFINITY, path: '', outcome: undefined }
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* 读数阶梯:先普通只读打开;只有因占用而读不到时,才去借目标进程已打开的句柄拿快照。
|
|
458
|
+
*
|
|
459
|
+
* 三条约束:
|
|
460
|
+
* - 快照结果必须带 `source:'borrowed-handle'` 与 `snapshot:true`,界面得说“不是实时”;
|
|
461
|
+
* - 借不到就原样返回 busy,**绝不把“没读到”洗成 0 条**;
|
|
462
|
+
* - 扫全机句柄表不免费:同一个库 60 秒内复用上一次结果,失败也至少隔 5 秒再试。
|
|
463
|
+
* @param {{read?:Function, snapshot?:Function, now?:()=>number, cacheMs?:number, minGapMs?:number, platform?:string, cache?:object}} [options] 余下选项透给读数函数
|
|
464
|
+
*/
|
|
465
|
+
export function statCookiesLive(options = {}) {
|
|
466
|
+
const {
|
|
467
|
+
read = statCookies, snapshot = snapshotThroughHandle, now = () => Date.now(),
|
|
468
|
+
cacheMs = LIVE_CACHE_MS, minGapMs = LIVE_MIN_GAP_MS, platform = process.platform,
|
|
469
|
+
cache = liveCache,
|
|
470
|
+
...stat
|
|
471
|
+
} = options
|
|
472
|
+
const plain = read(stat)
|
|
473
|
+
if (plain.reason !== 'busy' || typeof plain.path !== 'string' || platform !== 'win32') return plain
|
|
474
|
+
const stamp = now()
|
|
475
|
+
if (cache !== null && cache.path === plain.path && cache.outcome !== undefined) {
|
|
476
|
+
const fresh = stamp - cache.at < cacheMs && cache.outcome.snapshot === true
|
|
477
|
+
const cooling = stamp - cache.at < minGapMs
|
|
478
|
+
if (fresh || cooling) return { ...plain, ...cache.outcome }
|
|
479
|
+
}
|
|
480
|
+
let outcome
|
|
481
|
+
if (typeof snapshot !== 'function') {
|
|
482
|
+
outcome = { snapshot: false, liveUnavailable: true, liveReason: 'no-snapshotter' }
|
|
483
|
+
} else {
|
|
484
|
+
const borrowed = snapshot({ filePath: plain.path, now })
|
|
485
|
+
if (borrowed?.ok !== true) {
|
|
486
|
+
outcome = { snapshot: false, liveUnavailable: true, liveReason: borrowed?.reason ?? 'borrow-failed' }
|
|
487
|
+
} else {
|
|
488
|
+
try {
|
|
489
|
+
const snapStat = read({ ...stat, explicitPath: borrowed.snapshotPath })
|
|
490
|
+
outcome = snapStat.reason === 'busy' || snapStat.verdict === 'skipped'
|
|
491
|
+
? { snapshot: false, liveUnavailable: true, liveReason: 'snapshot-unreadable' }
|
|
492
|
+
: { ...snapStat, path: plain.path, source: 'borrowed-handle', snapshot: true, snapshotBytes: borrowed.bytes }
|
|
493
|
+
} catch (e) {
|
|
494
|
+
outcome = { snapshot: false, liveUnavailable: true, liveReason: `snapshot-error-${String(e && e.code ? e.code : e.message)}` }
|
|
495
|
+
} finally {
|
|
496
|
+
try { fs.rmSync(borrowed.snapshotPath, { force: true }) } catch { /* 临时快照残留不影响读数 */ }
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
cache.at = stamp
|
|
501
|
+
cache.path = plain.path
|
|
502
|
+
cache.outcome = outcome
|
|
503
|
+
return { ...plain, ...outcome }
|
|
504
|
+
}
|
|
505
|
+
|
|
408
506
|
/** 给 CLI / 命令共用的「现在是什么状况」一句话(把处置说全,避免二次求助)。 */
|
|
409
507
|
export function describeStat(stat) {
|
|
410
508
|
const t = translator(lang)
|
package/src/index.js
CHANGED
|
@@ -12,9 +12,11 @@
|
|
|
12
12
|
* 在客户端关闭、宿主插件不存在的那个时间窗里执行。
|
|
13
13
|
*/
|
|
14
14
|
import z from '@deepseek-ai/schemastery'
|
|
15
|
-
import { cookieCleanerCommandText, cleanCookies, setLang, statCookies } from './report.js'
|
|
15
|
+
import { cookieCleanerCommandText, cleanCookies, patchOutcomeText, patchReportText, setLang, statCookies, statCookiesLive } from './report.js'
|
|
16
16
|
import { LANGS, detectLang, normalize } from './i18n.js'
|
|
17
17
|
import { installSettingsWaist } from './settings-waist.js'
|
|
18
|
+
import { createPatchGuard } from './patch-guard.js'
|
|
19
|
+
import { cookieBrief, registerPatchRoutes } from './api-routes.js'
|
|
18
20
|
|
|
19
21
|
/** Cordis 插件名(与 cordis.patch.yml 的 id 一致)。 */
|
|
20
22
|
export const name = 'cookie-cleaner'
|
|
@@ -25,12 +27,18 @@ export const DEFAULT_SETTINGS = Object.freeze({
|
|
|
25
27
|
userDataRoot: '', // 覆盖 Electron userData 根(多实例/非默认安装位置用)
|
|
26
28
|
expiredOnly: false, // 保守档:命令与脚本默认只把「已过期」当作可清理对象
|
|
27
29
|
lang: '', // 输出语言(zh/en/ja/ko/fr/de/it/ru/es);空=跟环境探测,探不到则 zh
|
|
30
|
+
guardDays: 1, // patch 体检的目标cookie 绝对寿命(宿主 schema 要求 ≥1)
|
|
31
|
+
guardMode: 'literal', // 'literal'=只动目标键 | 'expression'=把 bundle 层的 !!js 表达式还原回去
|
|
32
|
+
// 没有 guardPort 设置项,也没有任何端口写入路径(用户裁决 2026-11-05):
|
|
33
|
+
// 本插件只改配置里的 cookie 有效期;端口属启动行为面,不在职责内。
|
|
28
34
|
})
|
|
29
35
|
|
|
30
36
|
export const Config = z.object({
|
|
31
37
|
userDataRoot: z.string().default(DEFAULT_SETTINGS.userDataRoot).volatile().description('覆盖 Electron userData 根目录(默认按平台惯例自动定位)'),
|
|
32
38
|
expiredOnly: z.boolean().default(DEFAULT_SETTINGS.expiredOnly).volatile().description('保守档:只统计/只提示已过期的 dsh-auth cookie'),
|
|
33
39
|
lang: z.string().default(DEFAULT_SETTINGS.lang).volatile().description(`输出语言:${LANGS.join('/')}(留空=自动探测)`),
|
|
40
|
+
guardDays: z.natural().min(1).default(DEFAULT_SETTINGS.guardDays).volatile().description('cookie 体检与修复写入的目标绝对寿命(天)——这是防 431 真正有效的那一项'),
|
|
41
|
+
guardMode: z.string().default(DEFAULT_SETTINGS.guardMode).volatile().description("patch 修复形态:'literal' 只动目标键,'expression' 同时把 bundle 层的 !!js 表达式还原回去"),
|
|
34
42
|
})
|
|
35
43
|
|
|
36
44
|
/** volatile 字段/字段级活引用解引出普通值。 */
|
|
@@ -95,8 +103,62 @@ export function apply(ctx, config = {}) {
|
|
|
95
103
|
},
|
|
96
104
|
})
|
|
97
105
|
|
|
106
|
+
// ── patch 体检/修复守卫(只在 configEditor 就绪后存在;老线回调不触发,插件其余面照常)──
|
|
107
|
+
/** @type {{check:Function, plan:Function, fix:Function, revert:Function} | undefined} */
|
|
108
|
+
let guard
|
|
109
|
+
ctx.inject(['configEditor', 'webServer'], (sctx) => {
|
|
110
|
+
const editor = typeof sctx.get === 'function' ? sctx.get('configEditor') : undefined
|
|
111
|
+
if (editor === undefined) return
|
|
112
|
+
guard = createPatchGuard({ getEditor: () => editor })
|
|
113
|
+
// 面板按钮的数据臂:两个服务都就绪才挂(缺任何一个都无法写)
|
|
114
|
+
const server = typeof sctx.get === 'function' ? sctx.get('webServer') : undefined
|
|
115
|
+
const cfg = current()
|
|
116
|
+
const offs = registerPatchRoutes(server, guard, {
|
|
117
|
+
targetDays: cfg.guardDays,
|
|
118
|
+
guardMode: cfg.guardMode,
|
|
119
|
+
// 端口不预填:面板不再提供控件,命令面必须当场给数(没给则由守卫拒写)
|
|
120
|
+
lang: cfg.lang ? normalize(cfg.lang) : undefined,
|
|
121
|
+
// cookie 库现状随体检一起回:只有面板这条走阶梯(普通只读打开不行时才试借句柄快照)。
|
|
122
|
+
cookie: () => statCookiesLive({ userDataRoot: current().userDataRoot }),
|
|
123
|
+
})
|
|
124
|
+
if (offs.length === 0) return
|
|
125
|
+
sctx.effect(() => () => offs.forEach((off) => { try { off() } catch { /* 已回收 */ } }), `${name}: patch routes`)
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* cookie 读数(命令面专用):**只走普通只读打开,不借句柄**。
|
|
130
|
+
*
|
|
131
|
+
* 为什么不跟面板共用阶梯:扫一次全机句柄表只在“用户显式点了体检”时才值得,
|
|
132
|
+
* 而命令面/启动播报会被测试与脚本反复调用,拿它去做系统级扫描会直接卡住
|
|
133
|
+
* (真机实测:`patch check` 在命令面触发借句柄后整个测试文件超时)。
|
|
134
|
+
* 而且独立进程的镜像名与桌面端不同,目标进程本来就匹配不上——诚实回 busy。
|
|
135
|
+
*/
|
|
136
|
+
function cookieBriefForCommand() {
|
|
137
|
+
return cookieBrief(() => statCookies({ userDataRoot: current().userDataRoot }))
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** patch 子命令的统一入口(写只发生在这里——用户触发的回调链,不在 HMR 事务内)。 */
|
|
141
|
+
async function runPatch(sub) {
|
|
142
|
+
const cfg = current()
|
|
143
|
+
const opts = { targetDays: cfg.guardDays, guardMode: cfg.guardMode }
|
|
144
|
+
if (guard === undefined) {
|
|
145
|
+
return { text: patchReportText({ reason: 'no-config-editor', rows: [] }, { lang: undefined }) }
|
|
146
|
+
}
|
|
147
|
+
if (sub === 'fix') {
|
|
148
|
+
const outcome = await guard.fix(opts)
|
|
149
|
+
return { text: patchReportText(outcome.result ?? guard.check(opts), { outcome }) }
|
|
150
|
+
}
|
|
151
|
+
if (sub === 'revert') {
|
|
152
|
+
const outcome = await guard.revert()
|
|
153
|
+
return { text: patchOutcomeText(outcome) }
|
|
154
|
+
}
|
|
155
|
+
if (sub === 'plan') return { text: patchReportText(guard.plan(opts)) }
|
|
156
|
+
// check 与面板同构:同一个 headerOccupancy 折算结果,两边不得各自算一套。
|
|
157
|
+
return { text: patchReportText({ ...guard.check(opts), cookie: cookieBriefForCommand() }) }
|
|
158
|
+
}
|
|
159
|
+
|
|
98
160
|
// ── /cookie-cleaner 命令(fail-open:commands 服务缺失只降级不 fatal)──
|
|
99
|
-
ctx.effect(() => registerCookieCleanerCommand(ctx, status), `${name}: command register`)
|
|
161
|
+
ctx.effect(() => registerCookieCleanerCommand(ctx, status, runPatch), `${name}: command register`)
|
|
100
162
|
|
|
101
163
|
// ── 装载即播报一次(2s 延迟让宿主先起完;只读,绝不写盘)──
|
|
102
164
|
ctx.effect(() => {
|
|
@@ -111,29 +173,42 @@ export function apply(ctx, config = {}) {
|
|
|
111
173
|
return () => clearTimeout(timer)
|
|
112
174
|
}, `${name}: startup report`)
|
|
113
175
|
|
|
114
|
-
return { status, clean: cleanCookies }
|
|
176
|
+
return { status, clean: cleanCookies, runPatch, patch: () => guard }
|
|
115
177
|
}
|
|
116
178
|
|
|
117
179
|
/**
|
|
118
180
|
* 注册 `/cookie-cleaner`。`commands` 服务只在 web/desktop 装配面存在,headless
|
|
119
181
|
* fiber 上读 `ctx.commands` 本身即 throw 且会被启动审计判失败,所以用 `ctx.get()`
|
|
120
182
|
* 探测(缺失返回 undefined、永不 throw),外罩窄域 try/catch 只吞代理拒绝文案。
|
|
183
|
+
*
|
|
184
|
+
* 返回体必须是 `CommandResult`:宿主在注册边界上做硬校验
|
|
185
|
+
* (`interaction/commands/src/index.ts:228-255`),`kind` 只认 `'success' | 'error'`,
|
|
186
|
+
* 其它值直接 `throw unknown result kind`——这就是 0.1.x 的 `/cookie-cleaner` 在真宿主里
|
|
187
|
+
* 每次调用都报错的原因(桅测只记了返回值、没校契约)。现在由
|
|
188
|
+
* `tests/command-contract.test.js` 把这条规则钉住。
|
|
121
189
|
*/
|
|
122
|
-
function registerCookieCleanerCommand(ctx, status) {
|
|
190
|
+
function registerCookieCleanerCommand(ctx, status, runPatch) {
|
|
123
191
|
try {
|
|
124
192
|
const commands = typeof ctx.get === 'function' ? ctx.get('commands') : undefined
|
|
125
193
|
if (typeof commands?.register !== 'function') return undefined
|
|
126
194
|
return commands.register({
|
|
127
195
|
name: 'cookie-cleaner',
|
|
128
|
-
description: '查看 DSH 客户端 cookie 库里的本地登录凭据(dsh-auth
|
|
129
|
-
input: { hint: '[status|clean]' },
|
|
130
|
-
handler: (invocation) => {
|
|
131
|
-
const
|
|
196
|
+
description: '查看 DSH 客户端 cookie 库里的本地登录凭据(dsh-auth-*)并给出清理命令;`patch check|fix|revert|plan` 体检/修复 profile 的 cordis.patch.yml(只改 cookie 有效期)。',
|
|
197
|
+
input: { hint: '[status|clean] | patch [check|fix|revert|plan]' },
|
|
198
|
+
handler: async (invocation) => {
|
|
199
|
+
const tokens = String(invocation?.rawInput ?? '').trim().split(/\s+/).filter(Boolean)
|
|
132
200
|
try {
|
|
201
|
+
if (tokens[0] === 'patch') {
|
|
202
|
+
// 没有 `port` 子命令:本插件不写端口(启动行为面不在职责内)。
|
|
203
|
+
const sub = ['check', 'fix', 'revert', 'plan'].includes(tokens[1]) ? tokens[1] : 'check'
|
|
204
|
+
const { text } = await runPatch(sub)
|
|
205
|
+
return { kind: 'success', text }
|
|
206
|
+
}
|
|
207
|
+
const mode = tokens[0] === 'clean' ? 'clean' : 'status'
|
|
133
208
|
const { text } = status({ mode })
|
|
134
|
-
return { kind: '
|
|
209
|
+
return { kind: 'success', text }
|
|
135
210
|
} catch (e) {
|
|
136
|
-
return { kind: 'error', text: `cookie-cleaner 失败: ${e.message}` }
|
|
211
|
+
return { kind: 'error', text: `cookie-cleaner 失败: ${e && e.message ? e.message : String(e)}` }
|
|
137
212
|
}
|
|
138
213
|
},
|
|
139
214
|
})
|