dsh-cookie-cleaner 0.0.0-stage → 0.1.0
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 +12 -0
- package/LICENSE +21 -0
- package/README.md +89 -3
- package/cordis.patch.yml +5 -0
- package/dsh.plugin.json +10 -0
- package/package.json +91 -4
- package/scripts/hosts.mjs +40 -0
- package/scripts/sync-hosts.mjs +51 -0
- package/src/cli.js +97 -0
- package/src/core.js +334 -0
- package/src/index.js +138 -0
- package/src/report.js +69 -0
- package/src/settings-waist.js +37 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (2026-11-04)
|
|
4
|
+
|
|
5
|
+
- 首版:只读播报 + 包内独立清理脚本。
|
|
6
|
+
- `src/core.js`:cookie 库定位(win/mac/linux 惯例 + `DSH_USER_DATA` / `DSH_COOKIE_DB` / `--db` 覆盖)、
|
|
7
|
+
只读统计(条数/过期数/host_key 分布/过期跨度)、`BEGIN IMMEDIATE` 独占写锁闸、
|
|
8
|
+
`.bak` 备份 + 事务删除 + VACUUM,表结构自检不过即拒绝写入。
|
|
9
|
+
- `src/cli.js`(npm bin `dsh-cookie-cleaner`):`--clean` / `--expired-only` / `--dry-run` / `--no-backup` / `--no-vacuum` / `--db`。
|
|
10
|
+
- `src/index.js`:`/cookie-cleaner` 命令(只读,输出可直接复制的清理命令)+ 三代设置 waist + `volatile` 配置面。
|
|
11
|
+
- 关键事实入档:客户端运行期该库被 Chromium 独占,宿主插件无法在启动时清理;
|
|
12
|
+
因此写盘只可能落在客户端退出后的独立脚本里(本机 0.2.1-rc.5 实测)。
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dsh-preset-manager contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,89 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# dsh-cookie-cleaner
|
|
2
|
+
|
|
3
|
+
清理 DSH(DeepSeek Harness)**桌面客户端** cookie 库里堆积的本地登录凭据 cookie(`dsh-auth-*`),
|
|
4
|
+
并解释清楚「为什么只能在客户端关闭时清理」——不用每次再去问一遍 AI。
|
|
5
|
+
|
|
6
|
+
## 它是什么 / 为什么长这样
|
|
7
|
+
|
|
8
|
+
桌面客户端每次启动都会在 Electron 的 cookie 库(`%APPDATA%\@deepseek-ai\dsh-desktop\Network\Cookies`)
|
|
9
|
+
里留下一条 `dsh-auth-<base64url(sha256(host:port))>`。名字按 **host:port** 哈希,端口一变就多一条,
|
|
10
|
+
各带 30 天有效期,于是历史记录长期堆积。
|
|
11
|
+
|
|
12
|
+
这些记录**不影响登录**,也**不涉及账号凭据**:
|
|
13
|
+
|
|
14
|
+
- 主窗口的 HTTP/WS 请求走的是内存态凭据(宿主换发后由桌面层直接注入请求头),不经 cookie jar;
|
|
15
|
+
- 鉴权只按当前 authority 派生的**那一个名字**取值,其余同名前缀条目本就永远读不到;
|
|
16
|
+
- 每次启动都会用 launch token 重新换发。
|
|
17
|
+
|
|
18
|
+
**关键约束(实测,非猜测)**:这个库在客户端运行期间被 Chromium 独占。
|
|
19
|
+
宿主插件跑在 Electron 的纯 Node 模式子进程里,既拿不到 `session.cookies`,
|
|
20
|
+
也无法在运行期打开该库(只读打开都会失败)。所以:
|
|
21
|
+
|
|
22
|
+
> 清理动作不可能由「插件在启动时」完成——它只能发生在客户端已完全退出的时间窗里,
|
|
23
|
+
> 而那个时刻宿主插件本身并不存在。因此本仓库把执行体做成**包内独立脚本**,
|
|
24
|
+
> 插件半只做只读播报和命令指引,**永不写库**。
|
|
25
|
+
|
|
26
|
+
## 安装
|
|
27
|
+
|
|
28
|
+
```shell
|
|
29
|
+
# 作为 DSH 插件(提供 /cookie-cleaner 只读播报)
|
|
30
|
+
dsh plugin add dsh-cookie-cleaner
|
|
31
|
+
|
|
32
|
+
# 清理工具随包分发,装完即可在终端调用
|
|
33
|
+
npm i -g dsh-cookie-cleaner # 之后直接 `dsh-cookie-cleaner`
|
|
34
|
+
# 或不安装,用宿主装好的包体直接跑:
|
|
35
|
+
node "<包目录>/src/cli.js"
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## 用法
|
|
39
|
+
|
|
40
|
+
```text
|
|
41
|
+
dsh-cookie-cleaner 查看现状:库在哪、多少条 dsh-auth-*、多少已过期
|
|
42
|
+
dsh-cookie-cleaner --clean 删除回环域(127.0.0.1/localhost/[::1])下全部 dsh-auth-*
|
|
43
|
+
dsh-cookie-cleaner --clean --expired-only 保守档:只删已过期的
|
|
44
|
+
dsh-cookie-cleaner --clean --dry-run 只看会删几条,不写盘
|
|
45
|
+
dsh-cookie-cleaner --db=<完整路径> 手动指定 cookie 库
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
可选 `--no-backup`(不产出 `.bak` 副本)、`--no-vacuum`(不做 VACUUM 收缩)。
|
|
49
|
+
退出码:`0` 成功;`1` 库被占用 / 没找到 / 参数非法。
|
|
50
|
+
|
|
51
|
+
安全设计:
|
|
52
|
+
|
|
53
|
+
- **独占写锁即闸门**——`BEGIN IMMEDIATE` 拿不到就拒绝执行并给出人话处置,不做任何"也许能写"的尝试;
|
|
54
|
+
- 写盘前先 `copyFileSync` 落 `Cookies.bak-<时间戳>`,备份失败即放弃(全有或全无);
|
|
55
|
+
- 删除语句只由 `host_key` 白名单 + 名称前缀构成,两者都过字符校验,时间戳走 BigInt 绑定参数;
|
|
56
|
+
- 表结构自检:库里没有 `cookies` 表或缺关键列,一律拒绝,绝不对未知库执行写语句。
|
|
57
|
+
|
|
58
|
+
Node ≥ 22.19(用到 `node:sqlite`,Electron 44 内置的 Node 24 亦可)。
|
|
59
|
+
在 Node 22 上会打印一条 `ExperimentalWarning: SQLite`,可 `node --no-warnings` 消除。
|
|
60
|
+
|
|
61
|
+
## 插件面
|
|
62
|
+
|
|
63
|
+
- 命令 `/cookie-cleaner` `[status|clean]`:**只读**。输出当前统计 + 可直接复制执行的清理命令。
|
|
64
|
+
- 设置 `cookie-cleaner`:`userDataRoot`(覆盖 Electron userData 根,多实例/非默认安装用)、
|
|
65
|
+
`expiredOnly`(保守档,影响提示措辞)。
|
|
66
|
+
- 没有 client 卡片:这是一个运维工具,界面交给终端。
|
|
67
|
+
|
|
68
|
+
## 想让残留自动消失(不用手动清)
|
|
69
|
+
|
|
70
|
+
宿主内置一个寿命闸:把 `@deepseek-ai/dsh-client-connection` 的 `cookieMaxAgeDays`(默认 30,最小 1)
|
|
71
|
+
调到 1,Chromium 便会在启动时自行清掉过期行,历史条目不再堆积。代价是最后一次领取的 cookie
|
|
72
|
+
只有 1 天有效期,重启即续期。在 profile 的 `cordis.patch.yml` 追加:
|
|
73
|
+
|
|
74
|
+
```yaml
|
|
75
|
+
- id: connection
|
|
76
|
+
name: '@deepseek-ai/dsh-client-connection'
|
|
77
|
+
config:
|
|
78
|
+
cookieMaxAgeDays: 1
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## 兼容性
|
|
82
|
+
|
|
83
|
+
逐 rc 单列于 `scripts/hosts.mjs`(单一真源),`npm run sync-hosts` 同步进
|
|
84
|
+
`package.json#engines.dsh`、`package.json#dsh.compatibility.dshReleases`、`dsh.plugin.json#engines.dsh`;
|
|
85
|
+
`prepack` 会以 `--check` 拦截不一致。
|
|
86
|
+
|
|
87
|
+
## License
|
|
88
|
+
|
|
89
|
+
MIT
|
package/cordis.patch.yml
ADDED
package/dsh.plugin.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "dsh-external/dsh-cookie-cleaner",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"main": "./src/index.js",
|
|
5
|
+
"description": "Cookie 清理器:只读播报桌面客户端 cookie 库里残留的本地登录凭据(dsh-auth-*),并随包分发「客户端完全退出后」可执行的清理命令(独占写锁 + .bak 备份,账号凭据/会话/插件配置不受影响)。",
|
|
6
|
+
"engines": {
|
|
7
|
+
"dsh": "0.1.0-rc.2 || 0.1.0-rc.3 || 0.1.0-rc.6 || 0.1.0-rc.7 || 0.1.0-rc.8 || 0.1.1-rc.1 || 0.1.1-rc.2 || 0.1.2-rc.1 || 0.1.5-rc.1 || 0.1.5-rc.2 || 0.1.5-rc.3 || 0.1.7-rc.1 || 0.1.7-rc.2 || 0.2.0-rc.1 || 0.2.0-rc.2 || 0.2.1-rc.1 || 0.2.1-rc.2 || 0.2.1-rc.3 || 0.2.1-rc.4 || 0.2.1-rc.5"
|
|
8
|
+
},
|
|
9
|
+
"contributes": {}
|
|
10
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,93 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-cookie-cleaner",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Cookie cleaner for DeepSeek Harness: reports the local dsh-auth-* entries left in the desktop client's Chromium cookie store and ships a standalone command that purges them once the client is fully closed (backup + atomic transaction, credentials/sessions/plugin config untouched).",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/drscrewdriver/dsh-cookie-cleaner.git"
|
|
10
|
+
},
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"registry": "https://registry.npmjs.org",
|
|
13
|
+
"access": "public",
|
|
14
|
+
"tag": "latest"
|
|
15
|
+
},
|
|
16
|
+
"main": "src/index.js",
|
|
17
|
+
"bin": {
|
|
18
|
+
"dsh-cookie-cleaner": "src/cli.js"
|
|
19
|
+
},
|
|
20
|
+
"exports": {
|
|
21
|
+
".": "./src/index.js",
|
|
22
|
+
"./core": "./src/core.js",
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"dsh": {
|
|
26
|
+
"bundle": {
|
|
27
|
+
"patch": "./cordis.patch.yml"
|
|
28
|
+
},
|
|
29
|
+
"compatibility": {
|
|
30
|
+
"dshReleases": {
|
|
31
|
+
"0.1.0-rc.2": "compatible",
|
|
32
|
+
"0.1.0-rc.3": "compatible",
|
|
33
|
+
"0.1.0-rc.6": "compatible",
|
|
34
|
+
"0.1.0-rc.7": "compatible",
|
|
35
|
+
"0.1.0-rc.8": "compatible",
|
|
36
|
+
"0.1.1-rc.1": "compatible",
|
|
37
|
+
"0.1.1-rc.2": "compatible",
|
|
38
|
+
"0.1.2-rc.1": "compatible",
|
|
39
|
+
"0.1.5-rc.1": "compatible",
|
|
40
|
+
"0.1.5-rc.2": "compatible",
|
|
41
|
+
"0.1.5-rc.3": "compatible",
|
|
42
|
+
"0.1.7-rc.1": "compatible",
|
|
43
|
+
"0.1.7-rc.2": "compatible",
|
|
44
|
+
"0.2.0-rc.1": "compatible",
|
|
45
|
+
"0.2.0-rc.2": "compatible",
|
|
46
|
+
"0.2.1-rc.1": "compatible",
|
|
47
|
+
"0.2.1-rc.2": "compatible",
|
|
48
|
+
"0.2.1-rc.3": "compatible",
|
|
49
|
+
"0.2.1-rc.4": "compatible",
|
|
50
|
+
"0.2.1-rc.5": "compatible"
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"scripts": {
|
|
55
|
+
"sync-hosts": "node scripts/sync-hosts.mjs",
|
|
56
|
+
"test": "node --test \"tests/*.test.js\"",
|
|
57
|
+
"lint": "eslint .",
|
|
58
|
+
"gate": "node scripts/sync-hosts.mjs --check && npm run lint && npm test",
|
|
59
|
+
"prepack": "npm run gate"
|
|
60
|
+
},
|
|
61
|
+
"dependencies": {
|
|
62
|
+
"@deepseek-ai/schemastery": "^3.18.4"
|
|
63
|
+
},
|
|
64
|
+
"peerDependencies": {
|
|
65
|
+
"@deepseek-ai/cordis": ">=4.0.1 <5"
|
|
66
|
+
},
|
|
67
|
+
"devDependencies": {
|
|
68
|
+
"@eslint/js": "^10.0.1",
|
|
69
|
+
"eslint": "^10.11.0",
|
|
70
|
+
"globals": "^17.12.0"
|
|
71
|
+
},
|
|
72
|
+
"files": [
|
|
73
|
+
"src",
|
|
74
|
+
"scripts",
|
|
75
|
+
"cordis.patch.yml",
|
|
76
|
+
"dsh.plugin.json",
|
|
77
|
+
"README.md",
|
|
78
|
+
"CHANGELOG.md",
|
|
79
|
+
"LICENSE"
|
|
80
|
+
],
|
|
81
|
+
"engines": {
|
|
82
|
+
"node": "^22.19.0 || >=24.0.0",
|
|
83
|
+
"dsh": "0.1.0-rc.2 || 0.1.0-rc.3 || 0.1.0-rc.6 || 0.1.0-rc.7 || 0.1.0-rc.8 || 0.1.1-rc.1 || 0.1.1-rc.2 || 0.1.2-rc.1 || 0.1.5-rc.1 || 0.1.5-rc.2 || 0.1.5-rc.3 || 0.1.7-rc.1 || 0.1.7-rc.2 || 0.2.0-rc.1 || 0.2.0-rc.2 || 0.2.1-rc.1 || 0.2.1-rc.2 || 0.2.1-rc.3 || 0.2.1-rc.4 || 0.2.1-rc.5"
|
|
84
|
+
},
|
|
85
|
+
"keywords": [
|
|
86
|
+
"deepseek-harness",
|
|
87
|
+
"dsh",
|
|
88
|
+
"dsh-plugin",
|
|
89
|
+
"cookie",
|
|
90
|
+
"cleanup",
|
|
91
|
+
"privacy"
|
|
92
|
+
]
|
|
93
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-cookie-cleaner — 宿主兼容清单(单一真源)。
|
|
3
|
+
*
|
|
4
|
+
* `scripts/sync-hosts.mjs` 把这份清单同步进三处:package.json 的 `engines.dsh`、
|
|
5
|
+
* package.json 的 `dsh.compatibility.dshReleases`、dsh.plugin.json 的 `engines.dsh`。
|
|
6
|
+
* 三处必须逐串相等(判定闸门只读 engines.dsh,compatibility 供插件管理器展示),
|
|
7
|
+
* 手工改其中一处而漏掉其余 = 假兼容/假拒绝的直接来源。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** 已验证可装载的宿主线(逐 rc 单列,禁用 range 通配)。 */
|
|
11
|
+
export const HOSTS = [
|
|
12
|
+
'0.1.0-rc.2',
|
|
13
|
+
'0.1.0-rc.3',
|
|
14
|
+
'0.1.0-rc.6',
|
|
15
|
+
'0.1.0-rc.7',
|
|
16
|
+
'0.1.0-rc.8',
|
|
17
|
+
'0.1.1-rc.1',
|
|
18
|
+
'0.1.1-rc.2',
|
|
19
|
+
'0.1.2-rc.1',
|
|
20
|
+
'0.1.5-rc.1',
|
|
21
|
+
'0.1.5-rc.2',
|
|
22
|
+
'0.1.5-rc.3',
|
|
23
|
+
'0.1.7-rc.1',
|
|
24
|
+
'0.1.7-rc.2',
|
|
25
|
+
'0.2.0-rc.1',
|
|
26
|
+
'0.2.0-rc.2',
|
|
27
|
+
'0.2.1-rc.1',
|
|
28
|
+
'0.2.1-rc.2',
|
|
29
|
+
'0.2.1-rc.3',
|
|
30
|
+
'0.2.1-rc.4',
|
|
31
|
+
'0.2.1-rc.5',
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
/** 每个宿主线的兼容判定。 */
|
|
35
|
+
export const STATUS = 'compatible'
|
|
36
|
+
|
|
37
|
+
/** npm 语法的逐串 or-range:`0.1.0-rc.2 || 0.1.0-rc.3 || ...`。 */
|
|
38
|
+
export function orRange(hosts = HOSTS) {
|
|
39
|
+
return hosts.join(' || ')
|
|
40
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-cookie-cleaner — 双清单同步 / 校验。
|
|
3
|
+
*
|
|
4
|
+
* node scripts/sync-hosts.mjs 写入(幂等)
|
|
5
|
+
* node scripts/sync-hosts.mjs --check 只校验,不一致即 exit 1(prepack 门禁)
|
|
6
|
+
*/
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import path from 'node:path'
|
|
9
|
+
import { fileURLToPath } from 'node:url'
|
|
10
|
+
import { HOSTS, STATUS, orRange } from './hosts.mjs'
|
|
11
|
+
|
|
12
|
+
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
|
13
|
+
const check = process.argv.includes('--check')
|
|
14
|
+
const range = orRange(HOSTS)
|
|
15
|
+
const releases = Object.fromEntries(HOSTS.map((host) => [host, STATUS]))
|
|
16
|
+
const failures = []
|
|
17
|
+
|
|
18
|
+
const pkgPath = path.join(ROOT, 'package.json')
|
|
19
|
+
const manifestPath = path.join(ROOT, 'dsh.plugin.json')
|
|
20
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
|
|
21
|
+
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
|
|
22
|
+
|
|
23
|
+
function compare(label, actual, expected) {
|
|
24
|
+
if (actual === expected) return
|
|
25
|
+
if (JSON.stringify(actual) === JSON.stringify(expected)) return
|
|
26
|
+
failures.push(`${label}: 与 scripts/hosts.mjs 不一致\n 期望 ${JSON.stringify(expected)}\n 实际 ${JSON.stringify(actual)}`)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
compare('package.json#engines.dsh', pkg.engines?.dsh, range)
|
|
30
|
+
compare('package.json#dsh.compatibility.dshReleases', pkg.dsh?.compatibility?.dshReleases, releases)
|
|
31
|
+
compare('dsh.plugin.json#engines.dsh', manifest.engines?.dsh, range)
|
|
32
|
+
compare('dsh.plugin.json#version', manifest.version, pkg.version)
|
|
33
|
+
|
|
34
|
+
if (check) {
|
|
35
|
+
if (failures.length > 0) {
|
|
36
|
+
process.stderr.write('双清单校验失败:\n' + failures.map((f) => ' - ' + f).join('\n') + '\n运行 `node scripts/sync-hosts.mjs` 修复。\n')
|
|
37
|
+
process.exitCode = 1
|
|
38
|
+
} else {
|
|
39
|
+
process.stdout.write(`双清单一致(${HOSTS.length} 条宿主线)\n`)
|
|
40
|
+
}
|
|
41
|
+
} else if (failures.length > 0) {
|
|
42
|
+
pkg.engines = { ...pkg.engines, dsh: range }
|
|
43
|
+
pkg.dsh = { ...pkg.dsh, compatibility: { ...pkg.dsh?.compatibility, dshReleases: releases } }
|
|
44
|
+
manifest.engines = { ...manifest.engines, dsh: range }
|
|
45
|
+
manifest.version = pkg.version
|
|
46
|
+
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n', 'utf8')
|
|
47
|
+
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n', 'utf8')
|
|
48
|
+
process.stdout.write(`已同步 ${HOSTS.length} 条宿主线到 package.json / dsh.plugin.json\n`)
|
|
49
|
+
} else {
|
|
50
|
+
process.stdout.write(`已是最新(${HOSTS.length} 条宿主线)\n`)
|
|
51
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* dsh-cookie-cleaner — 独立清理脚本(可在 npm 全局/任意 shell 下直接执行)。
|
|
4
|
+
*
|
|
5
|
+
* 为什么独立成脚本:cookie 库在客户端运行期间被 Chromium 独占(实测连只读打开
|
|
6
|
+
* 都会失败),所以清理只能发生在「客户端已完全退出」的时刻——那时宿主插件
|
|
7
|
+
* 根本不存在,执行体必须是这个包里的脚本。
|
|
8
|
+
*
|
|
9
|
+
* 包是 ESM(宿主装载与 npm bin 都走 ESM),core 只有一份实现,两边共用。
|
|
10
|
+
*/
|
|
11
|
+
import path from 'node:path'
|
|
12
|
+
import * as core from './core.js'
|
|
13
|
+
|
|
14
|
+
const USAGE = `dsh-cookie-cleaner — 清理 DSH 客户端留在 cookie 库里的本地登录凭据(dsh-auth-*)
|
|
15
|
+
|
|
16
|
+
用法(务必先完全退出 DSH 客户端:托盘 → 退出,进程列表里不再有 DeepSeek Harness):
|
|
17
|
+
dsh-cookie-cleaner 查看现状:库在哪、有多少条 dsh-auth-*、多少已过期
|
|
18
|
+
dsh-cookie-cleaner --clean 删除回环域(127.0.0.1/localhost/[::1])下全部 dsh-auth-*
|
|
19
|
+
dsh-cookie-cleaner --clean --expired-only 只删已过期的(保守档)
|
|
20
|
+
dsh-cookie-cleaner --clean --dry-run 只看会删几条,不写盘
|
|
21
|
+
dsh-cookie-cleaner --db=<完整路径> 手动指定 cookie 库
|
|
22
|
+
|
|
23
|
+
可选:--no-backup 不产出 .bak 副本;--no-vacuum 不做 VACUUM 收缩
|
|
24
|
+
退出码:0 成功;1 失败(库被占用/没找到/参数非法)
|
|
25
|
+
`
|
|
26
|
+
|
|
27
|
+
function parseArgs(argv) {
|
|
28
|
+
const options = { clean: false, expiredOnly: false, dryRun: false, noBackup: false, noVacuum: false, db: '', help: false }
|
|
29
|
+
for (const arg of argv) {
|
|
30
|
+
if (arg === '--clean') options.clean = true
|
|
31
|
+
else if (arg === '--expired-only') options.expiredOnly = true
|
|
32
|
+
else if (arg === '--dry-run') options.dryRun = true
|
|
33
|
+
else if (arg === '--no-backup') options.noBackup = true
|
|
34
|
+
else if (arg === '--no-vacuum') options.noVacuum = true
|
|
35
|
+
else if (arg === '--help' || arg === '-h') options.help = true
|
|
36
|
+
else if (arg.startsWith('--db=')) options.db = arg.slice('--db='.length)
|
|
37
|
+
else {
|
|
38
|
+
process.stderr.write(`未知参数:${arg}\n\n${USAGE}`)
|
|
39
|
+
process.exitCode = 1
|
|
40
|
+
return undefined
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return options
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function main() {
|
|
47
|
+
const options = parseArgs(process.argv.slice(2))
|
|
48
|
+
if (options === undefined) return
|
|
49
|
+
if (options.help) {
|
|
50
|
+
process.stdout.write(USAGE)
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
const explicitPath = options.db ? path.resolve(options.db) : ''
|
|
54
|
+
const env = process.env
|
|
55
|
+
try {
|
|
56
|
+
if (!options.clean) {
|
|
57
|
+
const stat = core.statCookies({ explicitPath, env })
|
|
58
|
+
process.stdout.write(core.describeStat(stat) + '\n')
|
|
59
|
+
if (stat.verdict === 'warn' && stat.reason !== 'busy') {
|
|
60
|
+
process.stdout.write('下一步:完全退出 DSH 客户端后执行 `dsh-cookie-cleaner --clean`(默认会连未过期的一起删,不影响登录,见 README)。\n')
|
|
61
|
+
} else if (stat.reason === 'busy') {
|
|
62
|
+
process.stdout.write('下一步:完全退出 DSH 客户端后重跑本命令。\n')
|
|
63
|
+
}
|
|
64
|
+
process.exitCode = stat.reason === 'busy' || stat.verdict === 'skipped' ? 1 : 0
|
|
65
|
+
return
|
|
66
|
+
}
|
|
67
|
+
const result = core.cleanCookies({
|
|
68
|
+
expiredOnly: options.expiredOnly,
|
|
69
|
+
dryRun: options.dryRun,
|
|
70
|
+
noBackup: options.noBackup,
|
|
71
|
+
noVacuum: options.noVacuum,
|
|
72
|
+
explicitPath,
|
|
73
|
+
env,
|
|
74
|
+
})
|
|
75
|
+
if (result.ok === false) {
|
|
76
|
+
process.stderr.write(result.message + '\n')
|
|
77
|
+
process.exitCode = 1
|
|
78
|
+
return
|
|
79
|
+
}
|
|
80
|
+
if (result.dryRun) {
|
|
81
|
+
process.stdout.write(`[dry-run] 将删除 ${result.wouldDelete} 条:${result.path}\n未写盘。去掉 --dry-run 即可执行。\n`)
|
|
82
|
+
return
|
|
83
|
+
}
|
|
84
|
+
process.stdout.write(
|
|
85
|
+
`已删除 ${result.deleted} 条 dsh-auth-*(${result.expiredOnly ? '仅已过期' : '全部'})\n` +
|
|
86
|
+
` 库:${result.path} ${result.beforeBytes} B → ${result.afterBytes} B\n` +
|
|
87
|
+
(result.backup ? ` 备份:${result.backup}\n` : ' 备份:已按 --no-backup 跳过\n') +
|
|
88
|
+
' 账号凭据、会话、插件配置均未触碰;下次启动会重新换发本地 cookie。\n',
|
|
89
|
+
)
|
|
90
|
+
} catch (e) {
|
|
91
|
+
const busy = e && e.code === 'cookie-busy'
|
|
92
|
+
process.stderr.write((busy ? '' : '清理失败:') + (e && e.message ? e.message : String(e)) + '\n')
|
|
93
|
+
process.exitCode = 1
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
main()
|
package/src/core.js
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-cookie-cleaner — 核心逻辑(纯函数面,host 半与 CLI 共用)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么清理动作不能在插件运行期做(2026-11-04 对本机 0.2.1-rc.5 客户端实测):
|
|
5
|
+
* - Host 是 Electron 的纯 Node 模式子进程(`ELECTRON_RUN_AS_NODE=1`),拿不到
|
|
6
|
+
* `session.cookies`,只能落到磁盘上的 Chromium cookie 库;
|
|
7
|
+
* - 客户端在跑时该库被 Chromium 持有:Host runtime(Electron 44 / Node 24)连
|
|
8
|
+
* `readOnly` 打开都抛 `unable to open database file`,`fs.copyFileSync` 同样被拒;
|
|
9
|
+
* 而系统 node 22 在同一时刻却能读——**能否打开随时点漂移,绝不可依赖**。
|
|
10
|
+
* 因此本模块把「独占写锁」当作唯一的安全闸:拿不到锁就一律拒绝并给出人话处置,
|
|
11
|
+
* 拿到锁即意味着此刻没有其它写者,删除是原子的、不会留中间态。
|
|
12
|
+
*
|
|
13
|
+
* 删了会不会掉登录?不会(源码依据):
|
|
14
|
+
* - 主窗口 HTTP/WS 用的是内存态 `hostCookie`(desktop `main.ts` 换发后经
|
|
15
|
+
* `forwardWebRequest` / `onBeforeSendHeaders` 注入),不经 cookie jar;
|
|
16
|
+
* - `BrowserAuth.isAuthenticated` 按当前 authority 派生**唯一**名字取值
|
|
17
|
+
* (`dsh-auth-<base64url(sha256(host:port))>`),其余同名前缀条目本就永远读不到;
|
|
18
|
+
* - 每次启动都会用 launch token 重新换发(`authenticateWebHost`)。
|
|
19
|
+
* 账号凭据(`.credentials.yaml`)、会话、插件配置都不在这个库里。
|
|
20
|
+
*/
|
|
21
|
+
import fs from 'node:fs'
|
|
22
|
+
import os from 'node:os'
|
|
23
|
+
import path from 'node:path'
|
|
24
|
+
import { createRequire } from 'node:module'
|
|
25
|
+
|
|
26
|
+
/** Cookie 名前缀:宿主 client-connection 生成(`COOKIE_PREFIX + sha256(authority)`)。 */
|
|
27
|
+
export const AUTH_COOKIE_PREFIX = 'dsh-auth-'
|
|
28
|
+
|
|
29
|
+
/** 本地回环 host_key:一个端口一条记录,历史端口会长期堆积。 */
|
|
30
|
+
export const LOOPBACK_HOST_KEYS = Object.freeze(['127.0.0.1', 'localhost', '[::1]'])
|
|
31
|
+
|
|
32
|
+
/** Chromium 的 `expires_utc` 是自 1601-01-01 起的微秒数。 */
|
|
33
|
+
const WINDOWS_EPOCH_OFFSET_MICROSECONDS = 11_644_473_600_000_000
|
|
34
|
+
|
|
35
|
+
/** 打包的 desktop 应用名(Electron 由 package.json 的 name 派生 userData 目录)。 */
|
|
36
|
+
const PRODUCT_DIR_NAMES = Object.freeze(['@deepseek-ai/dsh-desktop', 'DSH Desktop', 'deepseek-harness'])
|
|
37
|
+
|
|
38
|
+
const require = createRequire(import.meta.url)
|
|
39
|
+
|
|
40
|
+
/** Windows epoch 下的「现在」,用于和 `expires_utc` 同量纲比较。 */
|
|
41
|
+
function windowsNowMicroseconds() {
|
|
42
|
+
return Date.now() * 1000 + WINDOWS_EPOCH_OFFSET_MICROSECONDS
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 微秒级时间戳超过 2^53,一律以 BigInt 进出(node:sqlite 的 readBigInts 语义)。 */
|
|
46
|
+
function toBigInt(value) {
|
|
47
|
+
return typeof value === 'bigint' ? value : BigInt(Math.round(Number(value) || 0))
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** COUNT(*) 之类的小整数:BigInt → Number(超安全范围只可能出现在损坏库上)。 */
|
|
51
|
+
function toCount(value) {
|
|
52
|
+
return typeof value === 'bigint' ? Number(value) : Number(value) || 0
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 把 Chromium 的微秒时间戳换成可读 UTC 时间(0/非法值给出对应文案)。 */
|
|
56
|
+
export function formatChromiumTimestamp(value) {
|
|
57
|
+
const microseconds = toBigInt(value)
|
|
58
|
+
if (microseconds <= 0n) return 'session / never'
|
|
59
|
+
const milliseconds = Number((microseconds - BigInt(WINDOWS_EPOCH_OFFSET_MICROSECONDS)) / 1000n)
|
|
60
|
+
if (!Number.isSafeInteger(milliseconds) || milliseconds < 0) return 'unknown'
|
|
61
|
+
return new Date(milliseconds).toISOString().slice(0, 16).replace('T', ' ') + ' UTC'
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 候选 cookie 库路径(按平台惯例派生;桌面客户端与 Web 共用同一 userData 布局)。 */
|
|
65
|
+
export function candidateCookieDbs(userDataRoot = '', platform = process.platform, env = process.env) {
|
|
66
|
+
// 分隔符跟随目标平台而不宿主:跨平台单测/多实例部署才不会拿到一身反斜杠的 posix 路径。
|
|
67
|
+
const pathModule = platform === 'win32' ? path.win32 : path.posix
|
|
68
|
+
// 显式给根 = 只要这个根(单测/多实例隔离),不得再把平台默认目录掺进来。
|
|
69
|
+
const explicit = String(userDataRoot || '').trim()
|
|
70
|
+
if (explicit) {
|
|
71
|
+
const out = []
|
|
72
|
+
for (const leaf of [pathModule.join('Network', 'Cookies'), 'Cookies']) {
|
|
73
|
+
out.push(pathModule.join(explicit, leaf))
|
|
74
|
+
}
|
|
75
|
+
return out
|
|
76
|
+
}
|
|
77
|
+
const roots = []
|
|
78
|
+
if (env.DSH_USER_DATA) roots.push(String(env.DSH_USER_DATA).trim())
|
|
79
|
+
if (env.DSH_COOKIE_DB) roots.push(pathModule.dirname(env.DSH_COOKIE_DB))
|
|
80
|
+
if (platform === 'win32') {
|
|
81
|
+
if (env.APPDATA) for (const name of PRODUCT_DIR_NAMES) roots.push(pathModule.join(env.APPDATA, name))
|
|
82
|
+
} else if (platform === 'darwin') {
|
|
83
|
+
for (const name of PRODUCT_DIR_NAMES) roots.push(pathModule.join(os.homedir(), 'Library', 'Application Support', name))
|
|
84
|
+
} else {
|
|
85
|
+
for (const name of PRODUCT_DIR_NAMES) roots.push(pathModule.join(env.XDG_CONFIG_HOME || pathModule.join(os.homedir(), '.config'), name))
|
|
86
|
+
}
|
|
87
|
+
const out = []
|
|
88
|
+
for (const root of roots) {
|
|
89
|
+
if (!root) continue
|
|
90
|
+
// Chromium ≥88 把网络状态收敛到 <userData>/Network/,更早的版本直接放根下。
|
|
91
|
+
for (const leaf of [pathModule.join('Network', 'Cookies'), 'Cookies']) {
|
|
92
|
+
const file = pathModule.join(root, leaf)
|
|
93
|
+
if (!out.includes(file)) out.push(file)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return out
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 存在性过滤:返回真实存在的候选库(带大小),一个都没有 → 空数组。 */
|
|
100
|
+
export function resolveCookieDbs({ userDataRoot = '', platform = process.platform, env = process.env } = {}) {
|
|
101
|
+
const found = []
|
|
102
|
+
for (const file of candidateCookieDbs(userDataRoot, platform, env)) {
|
|
103
|
+
const bytes = sizeOf(file)
|
|
104
|
+
if (bytes > 0) found.push({ path: file, bytes })
|
|
105
|
+
}
|
|
106
|
+
return found
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function sizeOf(file) {
|
|
110
|
+
try {
|
|
111
|
+
const stat = fs.statSync(file)
|
|
112
|
+
return stat.isFile() ? stat.size : 0
|
|
113
|
+
} catch { return 0 }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function loadSqlite(explicit) {
|
|
117
|
+
if (explicit) return explicit
|
|
118
|
+
try {
|
|
119
|
+
// Node ≥22.5 / Electron 44(Node 24)自带;缺失时上层降级为「只给处置文案」。
|
|
120
|
+
return require('node:sqlite')
|
|
121
|
+
} catch (e) {
|
|
122
|
+
throw new Error(`当前 Node 运行时无 node:sqlite(需要 Node ≥22.5):${e.message}`, { cause: e })
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** 打不开 = 库被占用或路径不对。统一带处置文案,避免用户回头找 AI 解析。 */
|
|
127
|
+
export class CookieBusyError extends Error {
|
|
128
|
+
constructor(filePath, cause) {
|
|
129
|
+
super(
|
|
130
|
+
`无法打开 cookie 库:${filePath}\n` +
|
|
131
|
+
` 原因:${cause && cause.message ? cause.message : String(cause)}\n` +
|
|
132
|
+
' 处置:这个库在客户端运行期间被 Chromium 独占。请完全退出 DSH 客户端' +
|
|
133
|
+
'(托盘图标 → 退出,并确认进程列表里已无 DeepSeek Harness),再执行本命令。',
|
|
134
|
+
{ cause },
|
|
135
|
+
)
|
|
136
|
+
this.name = 'CookieBusyError'
|
|
137
|
+
this.code = 'cookie-busy'
|
|
138
|
+
this.path = filePath
|
|
139
|
+
this.cause = cause
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* 打开数据库。`write:true` 会立刻 `BEGIN IMMEDIATE`——拿不到保留写锁即抛
|
|
145
|
+
* {@link CookieBusyError},这就是「必须关闭客户端」的机械实现。
|
|
146
|
+
* 统一开 `readBigInts`:真实的 `expires_utc`(~1.34e16 微秒)超过 2^53,
|
|
147
|
+
* 默认按 Number 读会直接 `ERR_OUT_OF_RANGE`。
|
|
148
|
+
*/
|
|
149
|
+
export function openDatabase(filePath, { write = false, sqlite, timeoutMs = 150 } = {}) {
|
|
150
|
+
const { DatabaseSync } = loadSqlite(sqlite)
|
|
151
|
+
if (!sizeOf(filePath)) {
|
|
152
|
+
throw new CookieBusyError(filePath, new Error('文件不存在(或被标记删除)'))
|
|
153
|
+
}
|
|
154
|
+
const options = { timeout: timeoutMs, readBigInts: true }
|
|
155
|
+
let handle
|
|
156
|
+
try {
|
|
157
|
+
handle = write ? new DatabaseSync(filePath, options) : new DatabaseSync(filePath, { ...options, readOnly: true })
|
|
158
|
+
} catch (e) {
|
|
159
|
+
// 老运行时可能不认 readBigInts:降级重试一次,仍失败才算占用。
|
|
160
|
+
if (!/readBigInts/.test(String(e && e.message))) throw new CookieBusyError(filePath, e)
|
|
161
|
+
try {
|
|
162
|
+
handle = write ? new DatabaseSync(filePath) : new DatabaseSync(filePath, { readOnly: true })
|
|
163
|
+
} catch (e2) {
|
|
164
|
+
throw new CookieBusyError(filePath, e2)
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (write) {
|
|
168
|
+
try {
|
|
169
|
+
handle.exec('BEGIN IMMEDIATE')
|
|
170
|
+
} catch (e) {
|
|
171
|
+
try { handle.close() } catch { /* 忽略二次错误 */ }
|
|
172
|
+
throw new CookieBusyError(filePath, e)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return handle
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** host_key 白名单 + name 前缀都过字符校验,杜绝把外部输入拼进语句。 */
|
|
179
|
+
function assertSafeIdentifiers(hostKeys, prefix) {
|
|
180
|
+
for (const key of hostKeys) {
|
|
181
|
+
if (!/^[A-Za-z0-9._:[\]-]{1,64}$/.test(key)) throw new Error(`非法 host_key:${key}`)
|
|
182
|
+
}
|
|
183
|
+
if (!/^[A-Za-z0-9._-]{1,64}$/.test(prefix)) throw new Error(`非法 cookie 名前缀:${prefix}`)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* 删除语句 + 绑定参数。`expiredOnly` 走参数绑定(时间戳不拼字符串),
|
|
188
|
+
* 且以 BigInt 绑定——微秒时间戳超出 2^53。
|
|
189
|
+
* @returns {{sql:string, values:Array<bigint|string>}}
|
|
190
|
+
*/
|
|
191
|
+
export function buildDeleteStatement({ expiredOnly = false, hostKeys = LOOPBACK_HOST_KEYS, prefix = AUTH_COOKIE_PREFIX } = {}) {
|
|
192
|
+
assertSafeIdentifiers(hostKeys, prefix)
|
|
193
|
+
const hosts = hostKeys.map((key) => `'${key}'`).join(', ')
|
|
194
|
+
const where = `host_key IN (${hosts}) AND name LIKE ?`
|
|
195
|
+
if (expiredOnly) {
|
|
196
|
+
return { sql: `DELETE FROM cookies WHERE ${where} AND expires_utc > 0 AND expires_utc <= ?`, values: [`${prefix}%`, BigInt(windowsNowMicroseconds())] }
|
|
197
|
+
}
|
|
198
|
+
return { sql: `DELETE FROM cookies WHERE ${where}`, values: [`${prefix}%`] }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** 表结构自检:不是 Chromium cookie 库就收手,绝不对未知库执行写语句。 */
|
|
202
|
+
function assertCookieSchema(handle) {
|
|
203
|
+
const table = handle.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'cookies'").get()
|
|
204
|
+
if (table === undefined) throw new Error('目标库里没有 cookies 表,可能不是 Chromium cookie 库')
|
|
205
|
+
const columns = new Set(handle.prepare('PRAGMA table_info(cookies)').all().map((row) => String(row.name)))
|
|
206
|
+
for (const need of ['host_key', 'name', 'expires_utc']) {
|
|
207
|
+
if (!columns.has(need)) throw new Error(`cookies 表缺少 ${need} 列,拒绝执行`)
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** 只读统计。客户端在跑时可能抛 CookieBusyError → 降级成 verdict:'warn'/busy。 */
|
|
212
|
+
export function statCookies({ userDataRoot = '', explicitPath = '', env = process.env, sqlite, timeoutMs } = {}) {
|
|
213
|
+
const candidates = explicitPath ? [{ path: explicitPath, bytes: sizeOf(explicitPath) }] : resolveCookieDbs({ userDataRoot, env })
|
|
214
|
+
if (candidates.length === 0) {
|
|
215
|
+
return { verdict: 'skipped', reason: 'not-found', candidates: candidateCookieDbs(userDataRoot, process.platform, env) }
|
|
216
|
+
}
|
|
217
|
+
const target = candidates[0]
|
|
218
|
+
let handle
|
|
219
|
+
try {
|
|
220
|
+
handle = openDatabase(target.path, { write: false, sqlite, timeoutMs })
|
|
221
|
+
} catch (e) {
|
|
222
|
+
if (e instanceof CookieBusyError) return { verdict: 'warn', reason: 'busy', ...target, candidates }
|
|
223
|
+
throw e
|
|
224
|
+
}
|
|
225
|
+
try {
|
|
226
|
+
assertCookieSchema(handle)
|
|
227
|
+
const total = toCount(handle.prepare('SELECT COUNT(*) AS c FROM cookies').get().c)
|
|
228
|
+
const byHost = handle.prepare('SELECT host_key, COUNT(*) AS c FROM cookies GROUP BY host_key ORDER BY c DESC').all()
|
|
229
|
+
const rows = handle.prepare('SELECT name, host_key, expires_utc FROM cookies WHERE name LIKE ? ORDER BY expires_utc DESC')
|
|
230
|
+
.all(`${AUTH_COOKIE_PREFIX}%`)
|
|
231
|
+
const now = BigInt(windowsNowMicroseconds())
|
|
232
|
+
let expired = 0
|
|
233
|
+
let live = 0
|
|
234
|
+
for (const row of rows) {
|
|
235
|
+
const microseconds = toBigInt(row.expires_utc)
|
|
236
|
+
if (microseconds > 0n && microseconds <= now) expired += 1
|
|
237
|
+
else live += 1
|
|
238
|
+
}
|
|
239
|
+
return {
|
|
240
|
+
verdict: rows.length === 0 ? 'ok' : 'warn',
|
|
241
|
+
reason: rows.length === 0 ? 'nothing-to-clean' : 'has-stale-entries',
|
|
242
|
+
...target,
|
|
243
|
+
candidates,
|
|
244
|
+
totalCookies: total,
|
|
245
|
+
authCookies: rows.length,
|
|
246
|
+
authExpired: expired,
|
|
247
|
+
authLive: live,
|
|
248
|
+
byHost: byHost.map((row) => ({ hostKey: String(row.host_key), count: toCount(row.c) })),
|
|
249
|
+
newestExpiry: rows.length > 0 ? formatChromiumTimestamp(rows[0].expires_utc) : '',
|
|
250
|
+
oldestExpiry: rows.length > 0 ? formatChromiumTimestamp(rows[rows.length - 1].expires_utc) : '',
|
|
251
|
+
}
|
|
252
|
+
} finally {
|
|
253
|
+
handle.close()
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* 执行清理。默认档删掉回环域下**全部** `dsh-auth-*`(含未过期,安全性见文件头);
|
|
259
|
+
* `expiredOnly` 为保守档。写盘前先落 `.bak-<ts>`,备份失败即放弃(全有或全无)。
|
|
260
|
+
* @param {{expiredOnly?:boolean,noBackup?:boolean,noVacuum?:boolean,dryRun?:boolean,explicitPath?:string,userDataRoot?:string,env?:object,sqlite?:object,timestamp?:() => string}} options
|
|
261
|
+
*/
|
|
262
|
+
export function cleanCookies(options = {}) {
|
|
263
|
+
const {
|
|
264
|
+
expiredOnly = false, noBackup = false, noVacuum = false, dryRun = false,
|
|
265
|
+
explicitPath = '', userDataRoot = '', env = process.env, sqlite,
|
|
266
|
+
timestamp = () => defaultTimestamp(),
|
|
267
|
+
} = options
|
|
268
|
+
const found = explicitPath ? [{ path: explicitPath, bytes: sizeOf(explicitPath) }] : resolveCookieDbs({ userDataRoot, env })
|
|
269
|
+
if (found.length === 0) {
|
|
270
|
+
return {
|
|
271
|
+
ok: false, code: 'not-found',
|
|
272
|
+
message: `没找到 cookie 库。候选路径:\n ${candidateCookieDbs(userDataRoot, process.platform, env).join('\n ')}\n可用 --db=<完整路径> 指定。`,
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
const target = found[0]
|
|
276
|
+
const { sql, values } = buildDeleteStatement({ expiredOnly })
|
|
277
|
+
const selectSql = sql.replace('DELETE FROM', 'SELECT COUNT(*) AS c FROM')
|
|
278
|
+
const handle = openDatabase(target.path, { write: true, sqlite })
|
|
279
|
+
try {
|
|
280
|
+
assertCookieSchema(handle)
|
|
281
|
+
const wouldDelete = Number(handle.prepare(selectSql).get(...values).c)
|
|
282
|
+
if (dryRun) {
|
|
283
|
+
handle.exec('ROLLBACK')
|
|
284
|
+
return { ok: true, dryRun: true, path: target.path, bytes: target.bytes, wouldDelete, sql, expiredOnly }
|
|
285
|
+
}
|
|
286
|
+
let backup = ''
|
|
287
|
+
if (!noBackup) {
|
|
288
|
+
backup = `${target.path}.bak-${timestamp()}`
|
|
289
|
+
try {
|
|
290
|
+
fs.copyFileSync(target.path, backup)
|
|
291
|
+
} catch (e) {
|
|
292
|
+
handle.exec('ROLLBACK')
|
|
293
|
+
throw new Error(`备份失败,已放弃写入(未做任何修改):${e.message}`, { cause: e })
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
const deleted = Number(handle.prepare(sql).run(...values).changes)
|
|
297
|
+
handle.exec('COMMIT')
|
|
298
|
+
let afterBytes = sizeOf(target.path)
|
|
299
|
+
if (!noVacuum) {
|
|
300
|
+
try {
|
|
301
|
+
handle.exec('VACUUM')
|
|
302
|
+
afterBytes = sizeOf(target.path)
|
|
303
|
+
} catch { /* VACUUM 失败不影响已提交的结果 */ }
|
|
304
|
+
}
|
|
305
|
+
return {
|
|
306
|
+
ok: true, dryRun: false, path: target.path, beforeBytes: target.bytes, afterBytes,
|
|
307
|
+
deleted, backup, sql, expiredOnly,
|
|
308
|
+
}
|
|
309
|
+
} catch (e) {
|
|
310
|
+
try { handle.exec('ROLLBACK') } catch { /* 事务已结束,忽略 */ }
|
|
311
|
+
throw e
|
|
312
|
+
} finally {
|
|
313
|
+
handle.close()
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function defaultTimestamp() {
|
|
318
|
+
return new Date().toISOString().replace(/[-:]/g, '').replace(/\..+/, '').replace('T', '-')
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** 给 CLI / 命令共用的「现在是什么状况」一句话(把处置说全,避免二次求助)。 */
|
|
322
|
+
export function describeStat(stat) {
|
|
323
|
+
if (stat.verdict === 'skipped') {
|
|
324
|
+
return '未定位到 cookie 库——如果你用的是 Web 版而非桌面客户端,浏览器自身的 cookie 不由本工具管理,无需清理。'
|
|
325
|
+
}
|
|
326
|
+
if (stat.reason === 'busy') {
|
|
327
|
+
return `无法读取(客户端正在运行,库被 Chromium 独占):${stat.path}`
|
|
328
|
+
}
|
|
329
|
+
if (stat.verdict === 'ok') {
|
|
330
|
+
return `干净:${stat.path}(共 ${stat.totalCookies} 条 cookie,无 dsh-auth-* 残留)`
|
|
331
|
+
}
|
|
332
|
+
return `发现 ${stat.authCookies} 条 dsh-auth-*(已过期 ${stat.authExpired} / 未过期 ${stat.authLive}),`
|
|
333
|
+
+ `分布在 ${stat.byHost.length} 个 host_key,库大小 ${stat.bytes} B:${stat.path}`
|
|
334
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-cookie-cleaner — 宿主半(只读播报 + 工具入口,绝不在运行期写库)。
|
|
3
|
+
*
|
|
4
|
+
* 装载即工作:注册 `/cookie-cleaner` 命令 + 三代设置 waist。命令只做**只读**统计,
|
|
5
|
+
* 并把「关闭客户端后自己跑一条命令」的处置直接打在聊天里——用户不必再找 AI 解析。
|
|
6
|
+
*
|
|
7
|
+
* 为什么不在这里执行清理(2026-11-04 对本机 0.2.1-rc.5 实测):
|
|
8
|
+
* - Host 是 Electron 的纯 Node 模式子进程,拿不到 `session.cookies`;
|
|
9
|
+
* - 客户端在跑时 cookie 库被 Chromium 独占,Host runtime 只读打开都会抛
|
|
10
|
+
* `unable to open database file`;能否打开随时点漂移,不可依赖。
|
|
11
|
+
* 因此写盘动作留在包内的独立脚本 `src/cli.js`(npm bin `dsh-cookie-cleaner`),
|
|
12
|
+
* 在客户端关闭、宿主插件不存在的那个时间窗里执行。
|
|
13
|
+
*/
|
|
14
|
+
import z from '@deepseek-ai/schemastery'
|
|
15
|
+
import { cookieCleanerCommandText, cleanCookies, statCookies } from './report.js'
|
|
16
|
+
import { installSettingsWaist } from './settings-waist.js'
|
|
17
|
+
|
|
18
|
+
/** Cordis 插件名(与 cordis.patch.yml 的 id 一致)。 */
|
|
19
|
+
export const name = 'cookie-cleaner'
|
|
20
|
+
export const inject = []
|
|
21
|
+
|
|
22
|
+
/** 默认配置(设置服务不可用时即用此值)。 */
|
|
23
|
+
export const DEFAULT_SETTINGS = Object.freeze({
|
|
24
|
+
userDataRoot: '', // 覆盖 Electron userData 根(多实例/非默认安装位置用)
|
|
25
|
+
expiredOnly: false, // 保守档:命令与脚本默认只把「已过期」当作可清理对象
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
export const Config = z.object({
|
|
29
|
+
userDataRoot: z.string().default(DEFAULT_SETTINGS.userDataRoot).volatile().description('覆盖 Electron userData 根目录(默认按平台惯例自动定位)'),
|
|
30
|
+
expiredOnly: z.boolean().default(DEFAULT_SETTINGS.expiredOnly).volatile().description('保守档:只统计/只提示已过期的 dsh-auth cookie'),
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
/** volatile 字段/字段级活引用解引出普通值。 */
|
|
34
|
+
export function resolveConfig(config) {
|
|
35
|
+
if (config === null || typeof config !== 'object') return {}
|
|
36
|
+
const out = {}
|
|
37
|
+
for (const [key, value] of Object.entries(config)) {
|
|
38
|
+
out[key] = value !== null && typeof value === 'object' && typeof value.get === 'function' ? value.get() : value
|
|
39
|
+
}
|
|
40
|
+
return out
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 已知键合并默认值(未知键丢弃)。 */
|
|
44
|
+
function readConfig(config) {
|
|
45
|
+
const resolved = resolveConfig(config)
|
|
46
|
+
const out = { ...DEFAULT_SETTINGS }
|
|
47
|
+
for (const key of Object.keys(out)) {
|
|
48
|
+
const value = resolved[key]
|
|
49
|
+
if (value !== undefined && value !== null) out[key] = value
|
|
50
|
+
}
|
|
51
|
+
return out
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* @param {object} ctx Cordis 上下文。
|
|
56
|
+
* @param {object} [config] patch 行下发的配置。
|
|
57
|
+
*/
|
|
58
|
+
export function apply(ctx, config = {}) {
|
|
59
|
+
let current = () => readConfig(config)
|
|
60
|
+
|
|
61
|
+
const log = (message) => {
|
|
62
|
+
try {
|
|
63
|
+
const logger = typeof ctx.logger === 'function' ? ctx.logger(name) : ctx.logger
|
|
64
|
+
;(logger?.info ?? logger?.log ?? console.log).call(logger ?? console, message)
|
|
65
|
+
} catch {
|
|
66
|
+
console.log(`[${name}]`, message)
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 只读现状 + 处置文案。overrides 可临时换档(`mode:'clean'` 只换措辞,仍不写盘)。 */
|
|
71
|
+
function status(overrides = {}) {
|
|
72
|
+
const cfg = { ...current(), ...overrides }
|
|
73
|
+
let stat
|
|
74
|
+
try {
|
|
75
|
+
stat = statCookies({ userDataRoot: cfg.userDataRoot })
|
|
76
|
+
} catch (e) {
|
|
77
|
+
stat = { verdict: 'error', message: e && e.message ? e.message : String(e) }
|
|
78
|
+
}
|
|
79
|
+
return { stat, text: cookieCleanerCommandText(stat, cfg) }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ── 三代设置 waist(0.1.2/0.1.5 installSection、0.1.0/0.1.1 register、0.1.7+ volatile 托管)──
|
|
83
|
+
installSettingsWaist(ctx, {
|
|
84
|
+
ns: name,
|
|
85
|
+
Config,
|
|
86
|
+
base: () => resolveConfig(config),
|
|
87
|
+
onSource: (source) => {
|
|
88
|
+
current = () => readConfig(typeof source === 'function' ? source() : source)
|
|
89
|
+
},
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
// ── /cookie-cleaner 命令(fail-open:commands 服务缺失只降级不 fatal)──
|
|
93
|
+
ctx.effect(() => registerCookieCleanerCommand(ctx, status), `${name}: command register`)
|
|
94
|
+
|
|
95
|
+
// ── 装载即播报一次(2s 延迟让宿主先起完;只读,绝不写盘)──
|
|
96
|
+
ctx.effect(() => {
|
|
97
|
+
const timer = setTimeout(() => {
|
|
98
|
+
try {
|
|
99
|
+
const { text } = status()
|
|
100
|
+
log(text)
|
|
101
|
+
} catch (e) {
|
|
102
|
+
log(`现状播报失败: ${e.message}`)
|
|
103
|
+
}
|
|
104
|
+
}, 2000)
|
|
105
|
+
return () => clearTimeout(timer)
|
|
106
|
+
}, `${name}: startup report`)
|
|
107
|
+
|
|
108
|
+
return { status, clean: cleanCookies }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* 注册 `/cookie-cleaner`。`commands` 服务只在 web/desktop 装配面存在,headless
|
|
113
|
+
* fiber 上读 `ctx.commands` 本身即 throw 且会被启动审计判失败,所以用 `ctx.get()`
|
|
114
|
+
* 探测(缺失返回 undefined、永不 throw),外罩窄域 try/catch 只吞代理拒绝文案。
|
|
115
|
+
*/
|
|
116
|
+
function registerCookieCleanerCommand(ctx, status) {
|
|
117
|
+
try {
|
|
118
|
+
const commands = typeof ctx.get === 'function' ? ctx.get('commands') : undefined
|
|
119
|
+
if (typeof commands?.register !== 'function') return undefined
|
|
120
|
+
return commands.register({
|
|
121
|
+
name: 'cookie-cleaner',
|
|
122
|
+
description: '查看 DSH 客户端 cookie 库里的本地登录凭据(dsh-auth-*)并给出清理命令。参数: status(默认)| clean(同样只读,只把措辞换成可直接执行的命令)',
|
|
123
|
+
input: { hint: '[status|clean]' },
|
|
124
|
+
handler: (invocation) => {
|
|
125
|
+
const mode = String(invocation?.rawInput ?? '').trim().split(/\s+/)[0] === 'clean' ? 'clean' : 'status'
|
|
126
|
+
try {
|
|
127
|
+
const { text } = status({ mode })
|
|
128
|
+
return { kind: 'text', text }
|
|
129
|
+
} catch (e) {
|
|
130
|
+
return { kind: 'error', text: `cookie-cleaner 失败: ${e.message}` }
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
})
|
|
134
|
+
} catch (e) {
|
|
135
|
+
if (!/cannot get property "commands" without inject/.test(String(e?.message ?? e))) throw e
|
|
136
|
+
return undefined
|
|
137
|
+
}
|
|
138
|
+
}
|
package/src/report.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-cookie-cleaner — 播报文案层(把处置说全,避免二次求助 AI)。
|
|
3
|
+
*
|
|
4
|
+
* core.js 只做机械动作,这里负责「现在是什么状况 + 下一步敲哪条命令」。
|
|
5
|
+
* 命令文案按平台给出:脚本随包分发(npm bin `dsh-cookie-cleaner`),
|
|
6
|
+
* 未全局安装时给出 `node <包>/src/cli.js` 的直跑形态。
|
|
7
|
+
*/
|
|
8
|
+
import path from 'node:path'
|
|
9
|
+
import { fileURLToPath } from 'node:url'
|
|
10
|
+
|
|
11
|
+
export * from './core.js'
|
|
12
|
+
|
|
13
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
|
14
|
+
|
|
15
|
+
/** 未经 npm 全局 link 时也能直接跑的调用形态。 */
|
|
16
|
+
export function directRunCommand() {
|
|
17
|
+
return `node "${path.join(HERE, 'cli.js')}"`
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 组装 `/cookie-cleaner` 的输出。
|
|
22
|
+
* @param {object} stat statCookies 结果(可能是 busy/skipped 降级形态)
|
|
23
|
+
* @param {{expiredOnly?:boolean, userDataRoot?:string, mode?:'status'|'clean'}} [cfg]
|
|
24
|
+
*/
|
|
25
|
+
export function cookieCleanerCommandText(stat, cfg = {}) {
|
|
26
|
+
const lines = []
|
|
27
|
+
const mode = cfg.mode === 'clean' ? 'clean' : 'status'
|
|
28
|
+
|
|
29
|
+
if (stat.verdict === 'skipped') {
|
|
30
|
+
lines.push('cookie 库:未定位到。')
|
|
31
|
+
lines.push(`候选路径:\n ${(stat.candidates ?? []).join('\n ')}`)
|
|
32
|
+
lines.push('若你用的是 Web 版(浏览器直连宿主),本地没有这个库,无需清理;桌面版可用 userDataRoot 覆盖根目录。')
|
|
33
|
+
return lines.join('\n')
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (stat.reason === 'busy') {
|
|
37
|
+
lines.push(`cookie 库此刻读不到(客户端正在运行,被 Chromium 独占):${stat.path}`)
|
|
38
|
+
lines.push('宿主插件无法在运行期清理这个库 —— 这是操作系统的文件占用,不是本工具的限制。')
|
|
39
|
+
lines.push('处置:完全退出 DSH 客户端(托盘 → 退出,确认进程列表里已无 DeepSeek Harness)后,在终端执行:')
|
|
40
|
+
lines.push(` ${directRunCommand()} --clean`)
|
|
41
|
+
return lines.join('\n')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (stat.verdict === 'error') {
|
|
45
|
+
lines.push(`cookie 库读取异常:${stat.message ?? '未知错误'}`)
|
|
46
|
+
return lines.join('\n')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
lines.push(`cookie 库:${stat.path}(${stat.bytes} B,共 ${stat.totalCookies} 条)`)
|
|
50
|
+
if (stat.verdict === 'ok') {
|
|
51
|
+
lines.push('状态:ok —— 没有 dsh-auth-* 残留,无需清理。')
|
|
52
|
+
return lines.join('\n')
|
|
53
|
+
}
|
|
54
|
+
lines.push(`状态:发现 ${stat.authCookies} 条 dsh-auth-*(已过期 ${stat.authExpired} / 未过期 ${stat.authLive})`)
|
|
55
|
+
lines.push(`过期时间跨度:${stat.oldestExpiry} ~ ${stat.newestExpiry}`)
|
|
56
|
+
lines.push('host_key 分布:' + stat.byHost.map((row) => `${row.hostKey}×${row.count}`).join(', '))
|
|
57
|
+
lines.push('说明:dsh-auth-* 的名字按 host:port 哈希,每换一次端口就留一条,未过期的会一直躺到 30 天到期;'
|
|
58
|
+
+ '它们不影响登录(主窗口用内存态凭据、鉴权只认当前端口那一条),也不涉及账号凭据/会话/插件配置。')
|
|
59
|
+
|
|
60
|
+
const flag = cfg.expiredOnly === true ? ' --expired-only' : ''
|
|
61
|
+
if (mode === 'status') {
|
|
62
|
+
lines.push('下一步:完全退出 DSH 客户端后,在终端执行(先看会删几条可加 --dry-run):')
|
|
63
|
+
} else {
|
|
64
|
+
lines.push('清理命令(务必先完全退出 DSH 客户端,运行期做不到):')
|
|
65
|
+
}
|
|
66
|
+
lines.push(` ${directRunCommand()} --clean${flag}`)
|
|
67
|
+
lines.push(' 默认档删全部 dsh-auth-*;--expired-only 只删已过期的;写盘前自动留 .bak 副本。')
|
|
68
|
+
return lines.join('\n')
|
|
69
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-cookie-cleaner — 三代宿主设置 waist(特性检测分派,禁止读版本号)。
|
|
3
|
+
*
|
|
4
|
+
* 检测点互斥、只用 settings 服务自身的方法:
|
|
5
|
+
* - 0.1.2-rc.1 / 0.1.5-rc.x:实例带 `installSection`(注册 ns + 原生表单挂账 +
|
|
6
|
+
* `setSource` 换绑配置源;base 必须传 resolveConfig 解包后的普通值,活引用直传
|
|
7
|
+
* 会 ValidationError 且 cordis 静默吞掉 inject 回调异常);
|
|
8
|
+
* - 0.1.0-rc.x / 0.1.1-rc.x:只有 `register/update/mutate/describe`(壳没有设置页,
|
|
9
|
+
* 注册 ns 即拿到持久化与桥读写,非缺陷);
|
|
10
|
+
* - 0.1.7-rc.1+ / 0.2.x:两个注册 API 都已移除,volatile Config 由 loader 托管
|
|
11
|
+
* 存储,本插件没有 client 卡,设置面即宿主自动表单。
|
|
12
|
+
* 任何线缺方法都只降级(走 patch 配置 + 默认值),绝不 fatal。
|
|
13
|
+
*/
|
|
14
|
+
export function installSettingsWaist(ctx, { ns, Config, base, onSource }) {
|
|
15
|
+
ctx.inject(['settings'], (sctx) => {
|
|
16
|
+
const svc = sctx.settings
|
|
17
|
+
if (typeof svc.installSection === 'function') {
|
|
18
|
+
try {
|
|
19
|
+
svc.installSection(ctx, ns, Config, base(), {
|
|
20
|
+
setSource: (source) => onSource(source),
|
|
21
|
+
onChange: () => {},
|
|
22
|
+
})
|
|
23
|
+
console.warn(`${ns}: settings via installSection (0.1.2/0.1.5 line)`)
|
|
24
|
+
} catch (e) {
|
|
25
|
+
console.warn(`${ns}: installSection FAILED:`, e?.stack ?? e)
|
|
26
|
+
}
|
|
27
|
+
} else if (typeof svc.register === 'function') {
|
|
28
|
+
try {
|
|
29
|
+
svc.register(ns, Config, { base: base() })
|
|
30
|
+
console.warn(`${ns}: settings via register (0.1.0/0.1.1 line)`)
|
|
31
|
+
} catch (e) {
|
|
32
|
+
console.warn(`${ns}: register FAILED:`, e?.stack ?? e)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// 其余代际:无需动作。
|
|
36
|
+
})
|
|
37
|
+
}
|