dsh-device-auth 0.0.0-stage → 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 ADDED
@@ -0,0 +1,69 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project uses
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [0.2.1] - 2026-11-21
8
+
9
+ ### Added
10
+
11
+ - `.github/workflows/release.yml`: publishing on `v*` tags with the npm
12
+ provenance attestation (GitHub OIDC), version/tag consistency check, and the
13
+ same checks as CI. Authenticated with the `NPM_TOKEN` repository secret; the
14
+ README documents how to switch to npm trusted publishing once the publisher is
15
+ registered on npmjs.com.
16
+
17
+ ## [0.2.0] - 2026-11-21
18
+
19
+ ### Added
20
+
21
+ - **Immediate revocation (R3)**: the plugin records a SHA-256 hash of every
22
+ cookie minted during a device exchange, keyed by device id
23
+ (`remote-auth-sessions.json`, `0600`, hashes only), and wraps `admit` plus
24
+ `authorizeIndex`. Revoking a device now rejects its already-minted cookie on
25
+ the next request, for both `/api` and the browser page — not only the next
26
+ token exchange.
27
+ - Session index keyed by `(cookieHash, deviceId)`, pruned by expiry, capped and
28
+ written atomically; the index is rejection-only and degrades to the original
29
+ authentication when missing or unreadable.
30
+ - `dsh-auth purge` also drops session entries of purged device records;
31
+ `revoke` keeps them, because the mapping is what identifies the cookie.
32
+
33
+ ### Changed
34
+
35
+ - `apply` now also requires `connection.admit`; activation fails loudly when it
36
+ is absent.
37
+ - Unit tests 9 → 13; sandbox acceptance T1–T12 → T1–T14 (adds API-cookie and
38
+ browser-cookie revocation checks).
39
+
40
+ ### Notes
41
+
42
+ - Cookies minted with the real launch token, and cookies minted before this
43
+ plugin existed, carry no device mapping and remain valid until expiry.
44
+
45
+ ## [0.1.0] - 2026-11-21
46
+
47
+ Initial release.
48
+
49
+ ### Added
50
+
51
+ - Host plugin that wraps `connection.authorizeConnect` / `authorizeIndex` so
52
+ durable `dsh_dev_…` device tokens are exchanged for the process launch token
53
+ and the original 302/303 + signed-cookie flow runs unchanged.
54
+ - Device credential store (`$DSH_HOME/remote-auth.json`, `0700`/`0600`): SHA-256
55
+ hashes only, constant-time comparison, atomic writes, cross-process lock for
56
+ mutations; the plugin itself never writes the store.
57
+ - `dsh-auth` CLI: `add`, `rotate` (in-place rotation for the same label),
58
+ `revoke` (one or all), `list`, `purge`, with `--store`, `--origin`, `--json`.
59
+ - Bundle layer that inserts the plugin and turns off `web-runtime.printUrl`, so
60
+ no usable credential is printed into the log at startup.
61
+ - Unit tests (`npm test`) and an isolated sandbox acceptance suite
62
+ (`test/acceptance.sh`, T1–T12) that never touches the production instance.
63
+
64
+ ### Verified
65
+
66
+ - `dsh 0.2.2-rc.1` on Node 24: unit tests 9/9; sandbox acceptance 29/29
67
+ (lead) and an independent re-run 12/12; production live checks for device
68
+ token exchange, rotation, revocation, browser cookie flow, Host fence, and
69
+ launch-token regression.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nypyp
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.en.md ADDED
@@ -0,0 +1,134 @@
1
+ # dsh-device-auth
2
+
3
+ > Stable, revocable per-device login tokens for the DeepSeek Harness Web UI — paired clients survive restarts instead of copying the rotating 43-character launch token again.
4
+
5
+ [![ci](https://github.com/nypyp/dsh-device-auth/actions/workflows/ci.yml/badge.svg)](https://github.com/nypyp/dsh-device-auth/actions/workflows/ci.yml)
6
+ [![npm version](https://img.shields.io/npm/v/dsh-device-auth)](https://www.npmjs.com/package/dsh-device-auth)
7
+ ![license](https://img.shields.io/badge/license-MIT-2e8b57)
8
+ ![dsh](https://img.shields.io/badge/dsh-%3E%3D0.2.2--rc.1%20%3C0.3.0--0-4d6bfe)
9
+ [中文](README.md)
10
+
11
+ ## Why
12
+
13
+ DeepSeek Harness mints one random Web launch token per process and prints it once in the startup log. Every remote client (DSH Go, scripts, other machines) has to store it, so every restart invalidates all paired clients, forces a manual copy of a 43-character secret from `journalctl`, and leaves the credential in plaintext logs. There is no supported way to pin, rotate, or revoke it per device.
14
+
15
+ `dsh-device-auth` adds that layer **in the profile**, without modifying any installed DSH package and without losing it on `dsh` upgrades.
16
+
17
+ ## Features
18
+
19
+ - **Stable**: one long-lived token per device; survives `dsh web` restarts, reboots, and `npm i -g @deepseek-ai/dsh@<next>`.
20
+ - **Rotatable**: re-issuing for the same device rotates in place; the old token receives 401 on its next request.
21
+ - **Per device and immediately revoked**: `dsh-auth list / revoke`; one credential per device, and a revoked device's **already-minted cookie is rejected on its next request**, not only when it tries to exchange again.
22
+ - **No credentials in logs**: the bundle layer turns off the printed launch URL; a token is shown once, only by an explicit `dsh-auth add|rotate`.
23
+ - **Zero regression**: a device token is swapped for the process launch token and handed to the original implementation. `/?token=`, 302/303 redirects, the 30-day signed cookie, the Host/Origin fence, `--trusted-host` and `--public-url` all behave exactly as before.
24
+ - **Self-contained**: no runtime dependencies and no build step; the server stores only SHA-256 hashes.
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ # from npm (available since 0.2.0)
30
+ dsh plugin --profile web add -w dsh-device-auth
31
+
32
+ # update
33
+ dsh plugin --profile web update dsh-device-auth@latest
34
+
35
+ # from a local checkout (development)
36
+ dsh plugin --profile web add -w file:/absolute/path/to/dsh-device-auth
37
+ ```
38
+
39
+ Installing or updating reloads the plugin through the normal loader path; restart `dsh web` only if the profile asks for it.
40
+
41
+ The bundle patch also sets `web-runtime.printUrl: false`, so the startup log no longer contains a usable launch token. You can also install it from the Web GUI's **Plugins → Add plugin** search once the package is published.
42
+
43
+ ## Usage
44
+
45
+ ```sh
46
+ dsh-auth add phone --kind dsh-go # mint for a phone (the token is shown once)
47
+ dsh-auth add laptop --kind browser # mint for a browser
48
+ dsh-auth list # label / id / status / dates
49
+ dsh-auth rotate phone # rotate: the previous token stops working immediately
50
+ dsh-auth revoke phone # revoke one device
51
+ dsh-auth revoke --all # revoke everything
52
+ dsh-auth purge # drop revoked records
53
+ ```
54
+
55
+ `add` / `rotate` print a token and two links:
56
+
57
+ ```
58
+ token (shown once): dsh_dev_…
59
+ app connect link: http://127.0.0.1:3080/connect?token=dsh_dev_…
60
+ browser login link: http://127.0.0.1:3080/?token=dsh_dev_…
61
+ ```
62
+
63
+ - **DSH Go / SSH-tunnel client**: paste `dsh_dev_…` into the host's launch-token field. A changing tunnel port does not matter: each reconnect exchanges the same token for a fresh cookie.
64
+ - **Browser**: open the browser login link with your public origin (for example `https://dsh.example.com/?token=dsh_dev_…`); the normal 30-day cookie takes over afterwards.
65
+
66
+ The CLI reads and writes `$DSH_HOME/remote-auth.json` (default `~/.dsh/remote-auth.json`); `--store` and `--origin` override that path and the origin used in printed links.
67
+
68
+ ## How it works
69
+
70
+ ```
71
+ client ──► GET /connect?token=dsh_dev_<43>
72
+ │
73
+ ├─ not in the device store ──► delegate untouched (launch token / wrong token behaviour unchanged)
74
+ │
75
+ └─ match ──► substitute the process launch token
76
+ └─► original authorizeConnect: 302 + 30-day signed cookie (authority-bound, Host/Origin fence intact)
77
+ ```
78
+
79
+ The plugin wraps `connection.authorizeConnect` / `authorizeIndex`, which are called dynamically per request. It only acts on `dsh_dev_` tokens present in the store; the real launch token is obtained through the documented `authenticatedUrl()` service method and is never modified.
80
+
81
+ The store is read-only for the plugin. Rotation and revocation are performed by the CLI under a cross-process lock and written atomically, so a stale in-process snapshot can never resurrect a revoked device.
82
+
83
+ A separate session index records a hash of every cookie minted during a device exchange, with the device id. The plugin wraps `admit` and `authorizeIndex` so a cookie whose device was revoked is refused on its very next request; launch-token cookies have no entry and are delegated to the original check.
84
+
85
+ See [docs/DESIGN.md](docs/DESIGN.md) for the threat model, OpenChamber mapping, and upgrade strategy.
86
+
87
+ ## Compatibility
88
+
89
+ | | |
90
+ |---|---|
91
+ | DSH | `>=0.2.2-rc.1 <0.3.0-0` (tested on `0.2.2-rc.1`) |
92
+ | Node | `>=24.9.0` (the DSH Web runtime) |
93
+ | Surface | Web / Desktop profile (Host plugin, no client UI) |
94
+
95
+ Activation probes the required service methods; on a future DSH version that renames them the plugin **fails loudly** instead of silently leaving authentication open.
96
+
97
+ ## Known limits
98
+
99
+ 1. **Scope of immediate revocation**: the plugin indexes every cookie minted by a device exchange (SHA-256 of the cookie pair + device id) and rejects those cookies on the next request once the device is revoked. Two kinds of cookies cannot be attributed: owner sessions minted with the real launch token, and cookies minted before this plugin was installed/updated. Those keep working until they expire. If the session index is lost, such cookies fall back to the original authentication (no false rejection, but the corresponding device is not evicted either).
100
+ 2. Every device is an owner: DSH has no per-device permission model, so "per device" here means credential-level only.
101
+ 3. Device tokens are stored in plaintext on the client (secure storage / DSH Go config); the server keeps only hashes.
102
+ 4. One-time pairing codes are not implemented (DSH Go only exchanges `token=`).
103
+
104
+ ## Development
105
+
106
+ ```sh
107
+ npm test # unit tests (no dependencies, no DSH needed)
108
+ npm run check # node --check + bash -n
109
+ ./test/acceptance.sh # isolated end-to-end sandbox (own DSH_HOME, :3099, production untouched)
110
+ ```
111
+
112
+ ## Rollback
113
+
114
+ ```sh
115
+ dsh plugin --profile web remove dsh-device-auth # or plugin_manager remove_bundle
116
+ ```
117
+
118
+ Remove the bundle selection from the profile as well, then restart `dsh web`. Baseline behaviour (random launch token, startup URL printed) returns.
119
+
120
+ ## Releasing (maintainers)
121
+
122
+ Pushing a `v*` tag runs [`.github/workflows/release.yml`](.github/workflows/release.yml): checks, unit tests, `npm pack` verification, then `npm publish --provenance` (signed with GitHub OIDC provenance). Authentication uses the `NPM_TOKEN` repository secret (a granular npm token scoped to publishing `dsh-device-auth`).
123
+
124
+ ### Optional, preferred: trusted publishing (OIDC, no long-lived token)
125
+
126
+ Enable it on `https://www.npmjs.com/package/dsh-device-auth/settings` → **Trusted publishing** → GitHub Actions: repository `nypyp/dsh-device-auth`, workflow `release.yml`. Once registered, delete the `NPM_TOKEN` secret and the workflow publishes through OIDC (it already has `id-token: write`).
127
+
128
+ ## Credits
129
+
130
+ The credential model is inspired by [OpenChamber](https://github.com/openchamber/openchamber): an opaque random bearer stored server-side as SHA-256, in-place rotation for the same device, and per-device revocation.
131
+
132
+ ## License
133
+
134
+ [MIT](LICENSE)
package/README.md CHANGED
@@ -1,3 +1,170 @@
1
- # Temporary Holding Version
1
+ # dsh-device-auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > 给 DeepSeek Harness Web UI 增加**稳定、可按设备撤销**的登录令牌:`dsh web` 重启后,已配对客户端不用再复制一次 43 位随机 launch token。
4
+
5
+ [![ci](https://github.com/nypyp/dsh-device-auth/actions/workflows/ci.yml/badge.svg)](https://github.com/nypyp/dsh-device-auth/actions/workflows/ci.yml)
6
+ [![npm version](https://img.shields.io/npm/v/dsh-device-auth)](https://www.npmjs.com/package/dsh-device-auth)
7
+ ![license](https://img.shields.io/badge/license-MIT-2e8b57)
8
+ ![dsh](https://img.shields.io/badge/dsh-%3E%3D0.2.2--rc.1%20%3C0.3.0--0-4d6bfe)
9
+ [English](README.en.md)
10
+
11
+ ## 为什么
12
+
13
+ DeepSeek Harness 的 Web 启动令牌(launch token)由进程在每次启动时随机生成,只通过启动日志打印一次。任何第三方远程客户端(DSH Go、脚本、其它设备)都必须保存它,因此每次重启或开机后:
14
+
15
+ - 所有已配对客户端立即失效,只能人工从 `journalctl` 重新复制一串 43 位随机字符;
16
+ - 没有"固定、轮换、按设备撤销"这一层,也无法避免令牌明文进日志。
17
+
18
+ `dsh-device-auth` 在 **profile 层**补上这一层,**不修改任何 DSH 安装包**,也不会在 `dsh` 升级时丢失。
19
+
20
+ ## 特性
21
+
22
+ - **稳定**:每台设备一条长期令牌,`dsh web` 重启、机器重启、`npm i -g @deepseek-ai/dsh@新版本` 都不需要重配。
23
+ - **可轮换**:同一设备重新签发即原地轮换,旧令牌下一个请求立即 401。
24
+ - **按设备、撤销即生效**:`dsh-auth list / revoke`,一台设备一个凭据;撤销后该设备**已经拿到的 cookie 也在下一次请求被拒绝**(不只是不能再换取)。
25
+ - **不落日志**:bundle 层关闭启动 URL 打印;令牌只在显式 `dsh-auth add|rotate` 时显示一次。
26
+ - **零回归**:只在设备令牌命中时把请求交回原实现;原 `/?token=`、302/303、30 天签名 cookie、Host/Origin fence、`--trusted-host`、`--public-url` 全部保持原行为。
27
+ - **自包含**:没有运行时依赖、没有构建步骤;服务端只保存 SHA-256 哈希。
28
+
29
+ ## 安装
30
+
31
+ ### 插件管理(Web / Desktop)
32
+
33
+ 在 **插件 → 添加插件** 里搜索 `dsh-device-auth` 并安装,然后重启 `dsh web`。
34
+
35
+ ### 命令行
36
+
37
+ ```sh
38
+ # 从 npm 安装(0.2.0 起可用)
39
+ dsh plugin --profile web add -w dsh-device-auth
40
+
41
+ # 更新
42
+ dsh plugin --profile web update dsh-device-auth@latest
43
+
44
+ # 从本地目录安装(开发调试)
45
+ dsh plugin --profile web add -w file:/absolute/path/to/dsh-device-auth
46
+ ```
47
+
48
+ 安装/更新后 `dsh web` 会按新模块重新加载;若界面提示需要重启,重启一次即可。
49
+
50
+ 安装后插件所在的 bundle 层会同时把 `web-runtime.printUrl` 设为 `false`:启动日志不再出现带真实令牌的 URL。
51
+
52
+ ## 使用
53
+
54
+ ```sh
55
+ dsh-auth add phone --kind dsh-go # 给手机签发(令牌只显示一次)
56
+ dsh-auth add laptop --kind browser # 给浏览器签发
57
+ dsh-auth list # 设备清单:label / id / 状态 / 时间
58
+ dsh-auth rotate phone # 轮换:旧令牌立即失效
59
+ dsh-auth revoke phone # 撤销单设备
60
+ dsh-auth revoke --all # 撤销全部
61
+ dsh-auth purge # 清理已撤销记录
62
+ ```
63
+
64
+ `add` / `rotate` 会打印三种形式,按客户端类型选一种:
65
+
66
+ ```
67
+ token (shown once): dsh_dev_…
68
+ app connect link: http://127.0.0.1:3080/connect?token=dsh_dev_…
69
+ browser login link: http://127.0.0.1:3080/?token=dsh_dev_…
70
+ ```
71
+
72
+ - **DSH Go / SSH 隧道客户端**:把 `dsh_dev_…` 填进主机配置的「DSH 登录令牌」。隧道本地端口变化不影响,客户端每次重连都用同一令牌换新 cookie。
73
+ - **浏览器**:直接打开 `browser login link`(把 origin 换成你的公网地址,例如 `https://dsh.example.com/?token=dsh_dev_…`),之后走正常的 30 天 cookie。
74
+
75
+ CLI 默认读写 `$DSH_HOME/remote-auth.json`(未设置时为 `~/.dsh/remote-auth.json`),可用 `--store` 指定;`--origin` 只影响打印出来的链接。
76
+
77
+ ## 工作原理
78
+
79
+ ```
80
+ 客户端 ──► GET /connect?token=dsh_dev_<43>
81
+ │
82
+ ├─ 命中设备表?── 否 ──► 原样交给 client-connection(真实 launch token / 错误令牌行为不变)
83
+ │
84
+ └─ 是 ──► 把 token 换成本进程真实 launch token
85
+ └─► 原 authorizeConnect:302 + 30 天签名 cookie(authority 绑定、Host/Origin fence 不变)
86
+ ```
87
+
88
+ - 插件包装 `connection` 服务的 `authorizeConnect` / `authorizeIndex`(两者在请求时被动态调用),只对以 `dsh_dev_` 开头且命中设备表的令牌生效;
89
+ - 真实 launch token 通过公开服务方法 `authenticatedUrl()` 读取,不改造、不替换;
90
+ - 设备表只读:插件不写文件,轮换/撤销由 CLI 在跨进程锁下原子写入,因此不存在"旧快照复活已撤销设备";
91
+ - 撤销即时生效:插件把设备交换签发的 cookie 以 SHA-256 记入 `remote-auth-sessions.json`(同样 0600、只存哈希),并包装 `admit` / `authorizeIndex`——命中已撤销设备的 cookie 直接 401;真实 launch token 的 cookie 不在索引里,原样委托(零回归)。
92
+
93
+ 更细的机制、威胁模型与升级策略见 [docs/DESIGN.md](docs/DESIGN.md)。
94
+
95
+ ## 配置
96
+
97
+ ```yaml
98
+ # 在 profile 的 cordis.patch.yml(或你的 bundle patch)中
99
+ - id: device-auth
100
+ config:
101
+ storePath: !!js dshHomePath('remote-auth.json') # 必填:设备表路径
102
+ prefix: dsh_dev_ # 可选:令牌前缀
103
+ ```
104
+
105
+ ## 兼容性
106
+
107
+ | 项 | 值 |
108
+ |---|---|
109
+ | DSH | `>=0.2.2-rc.1 <0.3.0-0`(已在 `0.2.2-rc.1` 实测) |
110
+ | Node | `>=24.9.0`(跟随 DSH Web 运行时) |
111
+ | 平台 | Web / Desktop profile(Host 插件,无客户端 UI) |
112
+
113
+ 插件会在激活时显式探测所需服务方法;未来 DSH 若改动这两个方法,**插件会启动失败并报错**,而不是静默放行。升级前请查看 [CHANGELOG.md](CHANGELOG.md) 与本仓库 CI。
114
+
115
+ ## 已知边界
116
+
117
+ 1. **撤销即时生效的范围**:插件把「设备交换时签发的 cookie」以哈希建立了索引,撤销后这些 cookie 的下一次请求即 401(`/api` 与浏览器页面都覆盖)。但有两类 cookie 无法归属到设备:① 用真实 launch token 登录的 owner 会话;② 插件安装/升级前就已签发的旧 cookie。它们不受设备撤销影响,直到过期。若会话索引文件丢失,上述 cookie 会退回"交给原鉴权"的行为(不会误拒合法会话,但也不会踢掉对应设备)。
118
+ 2. 所有设备都是 owner 级权限——DSH 没有 per-device 权限模型,本插件的"按设备"只到凭据维度。
119
+ 3. 设备令牌在客户端侧明文保存(手机安全存储 / DSH Go 配置);服务端只存哈希。
120
+ 4. 未实现一次性配对码(DSH Go 只会用 `token=` 换取,没有配对码消费者)。
121
+
122
+ ## 开发与测试
123
+
124
+ ```sh
125
+ npm test # 单元测试(无依赖,不需要 DSH)
126
+ npm run check # node --check + bash -n
127
+ ./test/acceptance.sh # 隔离沙箱端到端验收(自建临时 DSH_HOME,:3099,不碰生产)
128
+ ```
129
+
130
+ `test/acceptance.sh` 会复制一份最小 `$HOME/.dsh` 到 `/tmp`,用 `--patch` overlay 把本插件挂进临时 `dsh web`,验证 T1–T12(未授权、设备令牌、cookie、轮换、撤销、重启保持、Host fence、日志卫生、`printUrl:false` 等)。它**绝不** stop/restart 生产服务,也**绝不**写 `~/.dsh`。
131
+
132
+ ## 回滚
133
+
134
+ ```sh
135
+ dsh plugin --profile web remove dsh-device-auth # 或 plugin_manager remove_bundle
136
+ # 同时删除 profile 里的 bundle 选择项,然后重启 dsh web
137
+ ```
138
+
139
+ 回滚后行为回到基线(随机 launch token、启动 URL 照常打印);`~/.dsh/remote-auth.json` 可保留或删除。
140
+
141
+ ## 发布(维护者)
142
+
143
+ 推送 `v*` tag 触发 [`.github/workflows/release.yml`](.github/workflows/release.yml):
144
+
145
+ ```sh
146
+ # 1) 确认 package.json 版本与 tag 一致
147
+ npm version 0.2.2 --no-git-tag-version # 或手改
148
+ git commit -am "release: v0.2.2"
149
+ git tag -a v0.2.2 -m "v0.2.2"
150
+ git push origin main --tags
151
+ ```
152
+
153
+ 工作流会跑 check/单测/npm pack,然后 `npm publish --provenance`,在 npm 上生成可验证的 provenance 证明。发布认证使用仓库 secret `NPM_TOKEN`(npm granular token,仅授权 `dsh-device-auth` 的 publish 权限)。
154
+
155
+ ### 可选的更优方案:Trusted Publishing(OIDC,无长期 token)
156
+
157
+ npm 官方推荐用 OIDC 代替长期 token。账号需要能在 npmjs.com 上完成 2FA:
158
+
159
+ 1. 登录 npmjs.com(账号 `nypyp`),打开 `https://www.npmjs.com/package/dsh-device-auth/settings`;
160
+ 2. **Trusted publishing** → 添加 GitHub Actions:仓库 `nypyp/dsh-device-auth`、workflow 文件名 `release.yml`(可留环境名空);
161
+ 3. 或者在本机执行 `npm trust github dsh-device-auth --repo nypyp/dsh-device-auth --file release.yml --allow-publish -y`(需要交互式 2FA/邮箱验证码);
162
+ 4. 配置完成后可以删除仓库 secret `NPM_TOKEN`,release workflow 会自动使用 OIDC(`id-token: write` 已就绪)。
163
+
164
+ ## 参考与致谢
165
+
166
+ 设计参考了 [OpenChamber](https://github.com/openchamber/openchamber) 的设备凭据模型(不透明 bearer、服务端只存 SHA-256、同设备重发即轮换、按设备撤销)。感谢其 MIT 开源实现为这套方案提供了可直接对照的工程先例。
167
+
168
+ ## License
169
+
170
+ [MIT](LICENSE)
@@ -0,0 +1,260 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsh-auth — manage per-device credentials for the DSH Web UI.
4
+ *
5
+ * The token printed by `add` / `rotate` is shown exactly once: the store keeps
6
+ * only its SHA-256 digest, so a lost token is rotated, never recovered.
7
+ *
8
+ * Usage:
9
+ * dsh-auth add <label> [--kind <name>] [--ttl-days <n>] [--origin <url>] [--json]
10
+ * dsh-auth rotate <label|id> [--ttl-days <n>] [--origin <url>] [--json]
11
+ * dsh-auth revoke <label|id> [--json]
12
+ * dsh-auth revoke --all [--json]
13
+ * dsh-auth list [--json]
14
+ * dsh-auth purge [--json]
15
+ *
16
+ * Global options:
17
+ * --store <path> store file (default: $DSH_HOME/remote-auth.json, else ~/.dsh/remote-auth.json)
18
+ * --json machine-readable output
19
+ * --origin <url> URL origin printed in the login links (default: http://127.0.0.1:3080)
20
+ */
21
+ import { realpathSync } from 'node:fs'
22
+ import { fileURLToPath } from 'node:url'
23
+
24
+ import {
25
+ findDevice,
26
+ mintDevice,
27
+ normalizeStore,
28
+ publicDevice,
29
+ purgeRevokedDevices,
30
+ readStoreFile,
31
+ resolveStorePath,
32
+ revokeAllDevices,
33
+ revokeDevice,
34
+ withStoreLock,
35
+ writeStoreFile,
36
+ } from '../lib/store.mjs'
37
+ import {
38
+ readSessionsFile,
39
+ removeSessionsForDevice,
40
+ resolveSessionsPath,
41
+ pruneSessions,
42
+ writeSessionsFile,
43
+ } from '../lib/sessions.mjs'
44
+
45
+ const HELP = `dsh-auth — manage per-device credentials for the DSH Web UI
46
+
47
+ Commands:
48
+ add <label> mint a durable token for one device (re-pair rotates it)
49
+ rotate <label|id> mint a fresh token for an existing device
50
+ revoke <label|id> revoke one device immediately
51
+ revoke --all revoke every device
52
+ list show devices (label, status, dates)
53
+ purge drop revoked records from the store
54
+
55
+ Options:
56
+ --store <path> store file (default $DSH_HOME/remote-auth.json)
57
+ --origin <url> origin used in printed login links (default http://127.0.0.1:3080)
58
+ --kind <name> free-form client kind recorded with the device
59
+ --ttl-days <n> optional lifetime; the token expires after n days
60
+ --json machine-readable output
61
+ -h, --help show this help
62
+
63
+ The token is printed once and stored only as a SHA-256 digest. To recover a
64
+ lost token, run "dsh-auth rotate <label>".`
65
+
66
+ function parseArgs(argv) {
67
+ const options = { origin: 'http://127.0.0.1:3080', json: false, kind: undefined, ttlDays: undefined, store: undefined, all: false }
68
+ const positional = []
69
+ for (let index = 0; index < argv.length; index += 1) {
70
+ const arg = argv[index]
71
+ const next = () => {
72
+ index += 1
73
+ if (index >= argv.length) throw new Error(`missing value for ${arg}`)
74
+ return argv[index]
75
+ }
76
+ if (arg === '--json') options.json = true
77
+ else if (arg === '--all') options.all = true
78
+ else if (arg === '--store') options.store = next()
79
+ else if (arg === '--origin') options.origin = next()
80
+ else if (arg === '--kind') options.kind = next()
81
+ else if (arg === '--ttl-days') {
82
+ const value = Number(next())
83
+ if (!Number.isFinite(value) || value <= 0) throw new Error('--ttl-days must be a positive number')
84
+ options.ttlDays = value
85
+ } else if (arg === '-h' || arg === '--help') return { help: true, options }
86
+ else if (arg.startsWith('-')) throw new Error(`unknown option: ${arg}`)
87
+ else positional.push(arg)
88
+ }
89
+ return { command: positional[0], args: positional.slice(1), options }
90
+ }
91
+
92
+ function block(label, token, origin) {
93
+ const base = origin.replace(/\/+$/u, '')
94
+ return {
95
+ token,
96
+ connectUrl: `${base}/connect?token=${encodeURIComponent(token)}`,
97
+ browserUrl: `${base}/?token=${encodeURIComponent(token)}`,
98
+ label,
99
+ }
100
+ }
101
+
102
+ function printMint(device, token, origin, json) {
103
+ const value = publicDevice(device)
104
+ const links = block(value.label, token, origin)
105
+ if (json) {
106
+ console.log(JSON.stringify({ device: value, ...links }, null, 2))
107
+ return
108
+ }
109
+ console.log(`device: ${value.label} (${value.id}) status=${value.status}`)
110
+ console.log(`token (shown once): ${token}`)
111
+ console.log(`app connect link: ${links.connectUrl}`)
112
+ console.log(`browser login link: ${links.browserUrl}`)
113
+ if (value.expiresAt !== null) console.log(`expires: ${value.expiresAt}`)
114
+ }
115
+
116
+ function printList(devices, json) {
117
+ const values = devices.map((device) => publicDevice(device))
118
+ if (json) {
119
+ console.log(JSON.stringify({ devices: values }, null, 2))
120
+ return
121
+ }
122
+ if (values.length === 0) {
123
+ console.log('no devices registered; run "dsh-auth add <label>"')
124
+ return
125
+ }
126
+ for (const device of values) {
127
+ const expires = device.expiresAt === null ? '' : ` expires=${device.expiresAt}`
128
+ const revoked = device.revokedAt === null ? '' : ` revoked=${device.revokedAt}`
129
+ console.log(`${device.label}\t${device.id}\t${device.status}\tcreated=${device.createdAt}${expires}${revoked}`)
130
+ }
131
+ }
132
+
133
+ /** Remove the session entries belonging to one device (or all when deviceId is undefined). */
134
+ function pruneSessionIndex(storePath, deviceId) {
135
+ const sessionsPath = resolveSessionsPath(storePath)
136
+ let current
137
+ try {
138
+ current = readSessionsFile(sessionsPath).sessions
139
+ } catch {
140
+ return 0
141
+ }
142
+ if (current.length === 0) return 0
143
+ const before = current.length
144
+ if (deviceId === undefined) {
145
+ writeSessionsFile(sessionsPath, [])
146
+ return before
147
+ }
148
+ const removed = removeSessionsForDevice(current, deviceId)
149
+ if (removed > 0) writeSessionsFile(sessionsPath, pruneSessions(current))
150
+ return removed
151
+ }
152
+
153
+ async function main(argv) {
154
+ const parsed = parseArgs(argv)
155
+ if (parsed.help === true) {
156
+ console.log(HELP)
157
+ return 0
158
+ }
159
+ const storePath = resolveStorePath(parsed.options.store)
160
+ const { command, args, options } = parsed
161
+ if (command === undefined) throw new Error(`missing command\n\n${HELP}`)
162
+
163
+ if (command === 'list') {
164
+ const { store } = readStoreFile(storePath)
165
+ printList(store.devices, options.json)
166
+ return 0
167
+ }
168
+
169
+ if (command === 'purge') {
170
+ const removed = await withStoreLock(storePath, async () => {
171
+ const { store } = readStoreFile(storePath)
172
+ const purged = store.devices.filter((device) => device.revokedAt !== null).map((device) => device.id)
173
+ const count = purgeRevokedDevices(store)
174
+ if (count > 0) writeStoreFile(storePath, store)
175
+ for (const deviceId of purged) pruneSessionIndex(storePath, deviceId)
176
+ return count
177
+ })
178
+ if (options.json) console.log(JSON.stringify({ removed }))
179
+ else console.log(`removed ${String(removed)} revoked record(s) from ${storePath}`)
180
+ return 0
181
+ }
182
+
183
+ if (command === 'revoke') {
184
+ if (options.all === true) {
185
+ const count = await withStoreLock(storePath, async () => {
186
+ const { store } = readStoreFile(storePath)
187
+ const changed = revokeAllDevices(store)
188
+ if (changed > 0) writeStoreFile(storePath, store)
189
+ return changed
190
+ })
191
+ if (options.json) console.log(JSON.stringify({ revoked: count }))
192
+ else console.log(`revoked ${String(count)} device(s)`)
193
+ return 0
194
+ }
195
+ }
196
+
197
+ const label = args[0]
198
+
199
+ if (command === 'add') {
200
+ if (label === undefined || label.trim() === '') throw new Error('add requires a label, e.g. "dsh-auth add phone"')
201
+ const created = await withStoreLock(storePath, async () => {
202
+ const { store } = readStoreFile(storePath)
203
+ const minted = mintDevice(store, label, { clientKind: options.kind, ttlDays: options.ttlDays })
204
+ writeStoreFile(storePath, store)
205
+ return minted
206
+ })
207
+ printMint(created.device, created.token, options.origin, options.json)
208
+ return 0
209
+ }
210
+
211
+ if (command === 'rotate') {
212
+ if (label === undefined || label.trim() === '') throw new Error('rotate requires a device label or id')
213
+ const rotated = await withStoreLock(storePath, async () => {
214
+ const { store } = readStoreFile(storePath)
215
+ const existing = findDevice(store, label)
216
+ if (existing === undefined) throw new Error(`no device matches ${JSON.stringify(label)}`)
217
+ const minted = mintDevice(store, existing.label, { clientKind: options.kind ?? existing.clientKind ?? undefined, ttlDays: options.ttlDays })
218
+ writeStoreFile(storePath, store)
219
+ return minted
220
+ })
221
+ printMint(rotated.device, rotated.token, options.origin, options.json)
222
+ return 0
223
+ }
224
+
225
+ if (command === 'revoke') {
226
+ if (label === undefined || label.trim() === '') throw new Error('revoke requires a device label, id, or --all')
227
+ const revoked = await withStoreLock(storePath, async () => {
228
+ const { store } = readStoreFile(storePath)
229
+ const device = revokeDevice(store, label)
230
+ if (device === undefined) throw new Error(`no device matches ${JSON.stringify(label)}`)
231
+ writeStoreFile(storePath, store)
232
+ return device
233
+ })
234
+ if (options.json) console.log(JSON.stringify({ device: publicDevice(revoked) }))
235
+ else console.log(`revoked ${revoked.label} (${revoked.id}); its next request is rejected immediately`)
236
+ return 0
237
+ }
238
+
239
+ throw new Error(`unknown command ${JSON.stringify(command)}\n\n${HELP}`)
240
+ }
241
+
242
+ const invokedDirectly = (() => {
243
+ if (process.argv[1] === undefined) return false
244
+ try {
245
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))
246
+ } catch {
247
+ return false
248
+ }
249
+ })()
250
+ if (invokedDirectly) {
251
+ main(process.argv.slice(2)).then(
252
+ (code) => { process.exitCode = code },
253
+ (error) => {
254
+ console.error(`dsh-auth: ${error instanceof Error ? error.message : String(error)}`)
255
+ process.exitCode = 1
256
+ },
257
+ )
258
+ }
259
+
260
+ export { main }