dsh-phone-link 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 +14 -0
- package/LICENSE +21 -0
- package/README.md +93 -2
- package/catalog.json +19 -0
- package/cordis.patch.yml +11 -0
- package/docs/BACKEND-API.md +103 -0
- package/docs/PUBLISHING.md +80 -0
- package/lib/bridge.js +141 -0
- package/lib/crypto.js +82 -0
- package/lib/index.js +91 -0
- package/lib/pairing.js +158 -0
- package/lib/transport.js +235 -0
- package/package.json +65 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
- 首个可安装版本。
|
|
6
|
+
- 中文显示名「远程助手」:`displayName`、`dsh.displayName.zh`、双语描述。
|
|
7
|
+
- `catalog.json`:供 dsh-plugin-manager 显示中文名与分类。
|
|
8
|
+
- `data/plugins/mostcat1992-code__dsh-phone-link.yml`:awesome-dsh-plugin 收录条目。
|
|
9
|
+
- 市场收录与中文名显示说明。
|
|
10
|
+
- 出站 WSS 中继客户端:hello、心跳、指数退避重连、配对握手。
|
|
11
|
+
- 本机配对页:二维码、8 位验证码人工确认、凭证持久化(0600)。
|
|
12
|
+
- X25519 + HKDF-SHA256 + AES-256-GCM 端到端加密与 counter 重放保护。
|
|
13
|
+
- 通过 DSH 官方扩展点桥接:会话列表、历史、发消息、工具审批(超时默认拒绝)。
|
|
14
|
+
- npm 包结构与 `cordis.patch.yml`,支持 `dsh plugin --profile <profile> add dsh-phone-link`。
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dsh-phone-link 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,94 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-phone-link(远程助手)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/dsh-phone-link)
|
|
4
|
+
[](./LICENSE)
|
|
5
|
+
|
|
6
|
+
**中文显示名:远程助手** · 包名:`dsh-phone-link`
|
|
7
|
+
|
|
8
|
+
> 收录说明:可按 [docs/PUBLISHING.md](./docs/PUBLISHING.md) 提交到 DSH Plugin Hub(https://dsh-plugin.org/)与 awesome-dsh-plugin 目录;提交动作由维护者完成。
|
|
9
|
+
|
|
10
|
+
把手机 App 安全地接到本机正在运行的 DeepSeek Harness(DSH)会话:手机看会话、发消息、处理工具审批;插件只做进程内桥接,不新增端口、不启动子进程、不需要 Tailscale 或额外运行时。
|
|
11
|
+
|
|
12
|
+
> 这是第三方社区插件,不是 DeepSeek 官方产品。DSH 仍处于 developer preview,内部 API 可能变化。
|
|
13
|
+
|
|
14
|
+
## 安装
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
dsh plugin --profile web add dsh-phone-link
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
桌面版请用你的实际 profile,例如:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
dsh plugin --profile desktop add dsh-phone-link
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
安装后**重启 DSH / 对应 profile** 才会加载 bundle。
|
|
27
|
+
|
|
28
|
+
### 在 DSH 里显示中文名「远程助手」
|
|
29
|
+
|
|
30
|
+
DSH 原生插件列表只显示英文模块名,没有官方的本地化显示名字段。中文名由社区插件提供,本包已备好目录源文件:
|
|
31
|
+
|
|
32
|
+
- 安装 [dsh-plugin-manager](https://github.com/2768651338/dsh-plugin-manager) 后,把本仓库的 `catalog.json` 注册到 `~/.dsh/plugin-manager/catalog-sources.json`:
|
|
33
|
+
|
|
34
|
+
```json
|
|
35
|
+
{
|
|
36
|
+
"version": 1,
|
|
37
|
+
"sources": [
|
|
38
|
+
{
|
|
39
|
+
"id": "phone-link",
|
|
40
|
+
"url": "https://raw.githubusercontent.com/mostcat1992-code/dsh-phone-link/main/catalog.json"
|
|
41
|
+
}
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
重启 DSH 后,在「设置 → 插件 → 插件管家」中即显示为 **远程助手**(English: Phone Link)。也可以在该插件卡片里点「编辑备注」自行改名。装了 `dsh-gui-hanhua` 或 `dsh-harness-zh-cn` 的用户也会得到中文界面。
|
|
47
|
+
|
|
48
|
+
卸载:
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
dsh plugin --profile web remove dsh-phone-link
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## 配置
|
|
55
|
+
|
|
56
|
+
在插件配置里至少设置 `serverUrl` 为你自己的后端地址,默认是占位符 `https://api.example.com`,未修改时配对页会拒绝工作。
|
|
57
|
+
|
|
58
|
+
| 配置项 | 默认值 | 说明 |
|
|
59
|
+
|---|---|---|
|
|
60
|
+
| `serverUrl` | `https://api.example.com` | 你的后端 HTTPS 地址 |
|
|
61
|
+
| `relayPath` | `/ws/v1/connect` | 中继 WebSocket 路径 |
|
|
62
|
+
| `pairPath` | `/phone-link/pair` | 本机配对页路径(挂在 DSH 自带 Web 服务上) |
|
|
63
|
+
| `deviceName` | `DSH desktop` | 配对页显示的电脑名称 |
|
|
64
|
+
| `heartbeatMs` | `30000` | 心跳间隔 |
|
|
65
|
+
| `reconnectMinMs` / `reconnectMaxMs` | `1000` / `30000` | 断线退避区间 |
|
|
66
|
+
| `approvalTimeoutMs` | `60000` | 等待手机审批的超时,超时默认拒绝 |
|
|
67
|
+
| `autoConnect` | `true` | 有凭证时自动连接中继 |
|
|
68
|
+
|
|
69
|
+
## 使用
|
|
70
|
+
|
|
71
|
+
1. 在 DSH 插件配置中填好 `serverUrl`。
|
|
72
|
+
2. 重启 DSH,浏览器打开 `http://127.0.0.1:<DSH端口>/phone-link/pair`。
|
|
73
|
+
3. 用手机 App 扫描页面上的二维码,确认服务器域名和本机公钥指纹。
|
|
74
|
+
4. 手机显示 8 位验证码后,**在电脑这个页面上**输入并确认。
|
|
75
|
+
5. 配对完成后插件自动连接中继,手机即可看到会话并发消息。
|
|
76
|
+
|
|
77
|
+
## 它做了什么
|
|
78
|
+
|
|
79
|
+
- 出站 WSS 连接你的中继,转发端到端加密的业务帧;电脑不需要公网 IP 或端口映射。
|
|
80
|
+
- 通过 DSH 官方扩展点 `agents` / `sessions` / `sessionPersistence` / `tools/pre-execute` 读写会话、投递消息、转发工具审批。
|
|
81
|
+
- 会话内容不经过你的后端落库;后端只做账号、配额计量和密文路由。
|
|
82
|
+
|
|
83
|
+
## 权限与风险
|
|
84
|
+
|
|
85
|
+
- 本插件拥有**本机 DSH 会话的完整控制能力**,包括发消息和批准工具调用。请只从可信来源安装,并给 pairing 验证码设置短有效期。
|
|
86
|
+
- 插件需要网络访问你的 `serverUrl`;不需要本地额外监听端口。
|
|
87
|
+
- 凭证与 X25519 私钥保存在 `~/.dsh/phone-link/state.json`,文件权限 0600。
|
|
88
|
+
- 工具审批默认超时拒绝,不提供持久授权(`allow-always`)。
|
|
89
|
+
|
|
90
|
+
后端接口契约见 [docs/BACKEND-API.md](./docs/BACKEND-API.md),发布流程见 [docs/PUBLISHING.md](./docs/PUBLISHING.md)。
|
|
91
|
+
|
|
92
|
+
## License
|
|
93
|
+
|
|
94
|
+
MIT
|
package/catalog.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"format": "dsh-plugin-manager-catalog-source",
|
|
3
|
+
"version": 1,
|
|
4
|
+
"entries": [
|
|
5
|
+
{
|
|
6
|
+
"key": "dsh-phone-link",
|
|
7
|
+
"aliases": ["phone-link", "远程助手"],
|
|
8
|
+
"name": {
|
|
9
|
+
"zh": "远程助手",
|
|
10
|
+
"en": "Phone Link"
|
|
11
|
+
},
|
|
12
|
+
"description": {
|
|
13
|
+
"zh": "把手机 App 经自建中继连接到本机 DSH 会话,支持会话列表、历史、发消息与工具审批。",
|
|
14
|
+
"en": "Bridge a phone app to local DSH sessions through your own relay: session list, history, prompts and tool approvals."
|
|
15
|
+
},
|
|
16
|
+
"category": "other"
|
|
17
|
+
}
|
|
18
|
+
]
|
|
19
|
+
}
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
- id: phone-link
|
|
2
|
+
name: dsh-phone-link
|
|
3
|
+
config:
|
|
4
|
+
serverUrl: https://api.example.com
|
|
5
|
+
relayPath: /ws/v1/connect
|
|
6
|
+
pairPath: /phone-link/pair
|
|
7
|
+
heartbeatMs: 30000
|
|
8
|
+
reconnectMinMs: 1000
|
|
9
|
+
reconnectMaxMs: 30000
|
|
10
|
+
approvalTimeoutMs: 60000
|
|
11
|
+
autoConnect: true
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# 后端接口契约 v1
|
|
2
|
+
|
|
3
|
+
插件只依赖下面这些接口。所有 URL 都基于插件配置中的 `serverUrl`,请求体为 JSON,时间字段为 Unix 毫秒。
|
|
4
|
+
|
|
5
|
+
## 1. 创建配对会话
|
|
6
|
+
|
|
7
|
+
`POST /api/v1/pairing/sessions`
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
{
|
|
11
|
+
"v": 1,
|
|
12
|
+
"device": {
|
|
13
|
+
"deviceId": "UUID",
|
|
14
|
+
"name": "DSH desktop",
|
|
15
|
+
"role": "host",
|
|
16
|
+
"platform": "desktop",
|
|
17
|
+
"identityKey": "32字节 X25519 公钥的 base64url",
|
|
18
|
+
"clientVersion": "0.1.0"
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
响应:
|
|
24
|
+
|
|
25
|
+
```json
|
|
26
|
+
{
|
|
27
|
+
"v": 1,
|
|
28
|
+
"sessionId": "UUID",
|
|
29
|
+
"expiresAt": 1790000000000,
|
|
30
|
+
"ticket": "32 随机字节的 base64url",
|
|
31
|
+
"qrUrl": "https://api.example.com/pair#v1.<ticket>",
|
|
32
|
+
"host": { "deviceId": "...", "identityKey": "..." }
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
要求:ticket 至少 256 bit 熵、TTL 建议 180 秒、单次消费、服务端只存摘要;响应 `Cache-Control: no-store`。
|
|
37
|
+
|
|
38
|
+
## 2. 手机领取验证码
|
|
39
|
+
|
|
40
|
+
手机端实现(不属于本插件):扫码后 `resolve` ticket、`claim` 设备、展示 8 位验证码。验证码只在手机安全界面显示,电脑端查询接口不得返回。
|
|
41
|
+
|
|
42
|
+
## 3. 电脑端确认绑定
|
|
43
|
+
|
|
44
|
+
`POST /api/v1/pairing/sessions/{sessionId}/host/confirm`
|
|
45
|
+
|
|
46
|
+
```json
|
|
47
|
+
{ "v": 1, "verificationCode": "00123456" }
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
成功响应至少包含:
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{
|
|
54
|
+
"device": { "deviceId": "...", "identityKey": "..." },
|
|
55
|
+
"peer": { "deviceId": "...", "identityKey": "手机 X25519 公钥" },
|
|
56
|
+
"tokens": {
|
|
57
|
+
"accessToken": "...",
|
|
58
|
+
"accessTokenExpiresAt": 1790000000000,
|
|
59
|
+
"refreshToken": "...",
|
|
60
|
+
"refreshTokenExpiresAt": 1790003000000
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
要求:完整有效格式的最终提交只允许一次;正确或错误都先持久化结果;错误码 `PAIRING_ATTEMPT_USED` 时不允许改码重试。
|
|
66
|
+
|
|
67
|
+
## 4. 中继 WebSocket
|
|
68
|
+
|
|
69
|
+
地址:`relayPath`,默认 `/ws/v1/connect`。使用 `Authorization: Bearer <accessToken>` 建连。
|
|
70
|
+
|
|
71
|
+
帧信封:
|
|
72
|
+
|
|
73
|
+
```json
|
|
74
|
+
{ "v": 1, "id": "UUID", "type": "hello", "timestamp": 1790000000000, "payload": {} }
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
插件发送的帧类型:
|
|
78
|
+
|
|
79
|
+
- `hello`:角色、deviceId、identityKey、协议版本、能力。
|
|
80
|
+
- `ping` / `pong`:心跳。
|
|
81
|
+
- `connect.accepted`:确认连接并携带 `grantId`。
|
|
82
|
+
- `data`:加密业务帧,外层含 `connectionId`、`counter`、`sealed`、`kind`。
|
|
83
|
+
|
|
84
|
+
插件接收的帧类型:
|
|
85
|
+
|
|
86
|
+
- `hello.ack`:`connectionId`、心跳间隔、能力。
|
|
87
|
+
- `connect.incoming`:`connectionId`、`peerIdentityKey`、`grantId`。
|
|
88
|
+
- `data`:加密业务帧。
|
|
89
|
+
- `rpc.response` / `rpc.error`:RPC 结果。
|
|
90
|
+
- `error`:可重试或致命错误。
|
|
91
|
+
|
|
92
|
+
## 5. 加密
|
|
93
|
+
|
|
94
|
+
当前 v1 使用 X25519 + HKDF-SHA256 + AES-256-GCM(不是 Noise IK,后续可升级):
|
|
95
|
+
|
|
96
|
+
- 双方静态 X25519 私钥只存在设备本地;公钥在配对时交换。
|
|
97
|
+
- 会话密钥:`HKDF-SHA256(shared, salt=connectionId, info="dsh-phone-link/v1", 32)`。
|
|
98
|
+
- 每个方向独立递增 `counter`,AAD 绑定 `connectionId:counter`,重复或乱序帧直接丢弃。
|
|
99
|
+
- 外层明文 `kind=prompt` 与 `grant_id` 仅供中继计量,不包含对话内容。
|
|
100
|
+
|
|
101
|
+
## 6. 配额
|
|
102
|
+
|
|
103
|
+
插件不判断会员等级。App 每次发消息前向后端 `/quota/consume` 取签名 grant;中继验签、单次消费并计数,超限直接不转发。后端应保证 fork 本插件也无法绕过中继计量。
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# 发布指南
|
|
2
|
+
|
|
3
|
+
目标:用户执行 `dsh plugin --profile web add dsh-phone-link` 即可按名称安装,同时被插件市场收录。
|
|
4
|
+
|
|
5
|
+
## 1. 先锁定名称
|
|
6
|
+
|
|
7
|
+
npm 上的 `dsh-phone-link` 目前未被占用。尽快发布 `0.1.0` 占住名字:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm whoami
|
|
11
|
+
npm publish --access public
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
发布后验证:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm view dsh-phone-link version
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
推荐改用 GitHub Actions + npm Trusted Publishing,避免长期 token:在 npm 包页面 Settings → Trusted publishing 选择 GitHub Actions,填 owner / repo / workflow filename `release.yml`,勾选允许 `npm publish`。推送 `v*` 标签即自动发布。
|
|
21
|
+
|
|
22
|
+
## 2. GitHub 仓库
|
|
23
|
+
|
|
24
|
+
1. 新建公开仓库 `dsh-phone-link`(默认分支 `main`)。
|
|
25
|
+
2. 本工作区代码填入正确的 `repository` / `homepage` / `bugs` 字段后再推送。
|
|
26
|
+
3. 仓库 About:
|
|
27
|
+
- 描述里包含 `DeepSeek Harness` 或 `dsh`,例如:`Link a phone app to a local DeepSeek Harness session through your own relay`.
|
|
28
|
+
- Topics 必须包含:`dsh-plugin`、`deepseek-harness`、`dsh`、`cordis`、`remote`、`harmonyos`。
|
|
29
|
+
4. README 已包含可复制安装命令、权限说明、许可证和收录声明。
|
|
30
|
+
|
|
31
|
+
## 3. 发布前检查
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
npm run verify
|
|
35
|
+
npm pack --dry-run
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
确认 tarball 只包含 `lib/`、`cordis.patch.yml`、`README.md`、`CHANGELOG.md`、`LICENSE`、`docs/`,没有本地路径与凭据。
|
|
39
|
+
|
|
40
|
+
## 4. 中文显示名「远程助手」
|
|
41
|
+
|
|
42
|
+
DSH 原生插件列表**没有**官方的中文显示名字段,只显示英文模块名。中文名由社区生态提供,本仓库已备好三处声明:
|
|
43
|
+
|
|
44
|
+
1. `package.json`:`displayName: "远程助手"`、`dsh.displayName.zh/en`、`description` 中英双语。
|
|
45
|
+
2. `catalog.json`:`dsh-plugin-manager` 的 v1 目录源,用户注册后显示「远程助手」。注册方法见 README。
|
|
46
|
+
3. `data/plugins/mostcat1992-code__dsh-phone-link.yml`:awesome-dsh-plugin 收录条目,描述以「远程助手」开头。
|
|
47
|
+
- 注意:文件名 = GitHub owner + `__` + 仓库名。若你的 GitHub 用户名不是 `mostcat1992-code`,改文件名与 `name` / `url` 字段。
|
|
48
|
+
- 收录后市场卡片显示中文描述,但卡片标题仍是包名 `dsh-phone-link`(这是市场规则,不能改)。
|
|
49
|
+
|
|
50
|
+
## 5. 插件市场收录(真正的上架步骤)
|
|
51
|
+
|
|
52
|
+
`dshmarket` 只是市场界面,**不是投稿入口**。目录在 `awesome-dsh-plugin`,收录后站点、dshmarket、DSH 0.2.1+ 的 Discover 标签会同步出现。
|
|
53
|
+
|
|
54
|
+
1. GitHub 建公开仓库 `dsh-phone-link`,加 topic `dsh-plugin`,推送代码。
|
|
55
|
+
2. 仓库需**创建满 24 小时**才能被投稿 CI 接受。
|
|
56
|
+
3. Fork `awesome-dsh-plugin/awesome-dsh-plugin`,新建分支。
|
|
57
|
+
4. 只新增一个文件 `data/plugins/mostcat1992-code__dsh-phone-link.yml`(内容已在本仓库备好,按实际 owner 改名)。不要改 README,它由数据文件生成。
|
|
58
|
+
5. 提交 PR,标题 `Add dsh-phone-link`。CI 会检查 `dsh.bundle.patch`、仓库年龄、`dsh-plugin` topic、双语描述与站点构建。
|
|
59
|
+
6. 合并后通常当天或次日生效;后续发版无需重复提交。
|
|
60
|
+
7. 如果要进 Curated 列表,再单独向 `cccakeee/awesome-dsh-plugins` 的 `data/verified-plugins.csv` 提 PR。
|
|
61
|
+
|
|
62
|
+
其他目录(如 dsh-plugin.org)按各自模板提交即可。
|
|
63
|
+
|
|
64
|
+
## 6. pnpm 24 小时观察期(重要)
|
|
65
|
+
|
|
66
|
+
DSH 插件安装走 profile 内的 pnpm。pnpm 11 默认 `minimumReleaseAge = 1440` 分钟:
|
|
67
|
+
|
|
68
|
+
- npm 发布后 24 小时内,`dsh plugin add dsh-phone-link`(不带版本)可能装到旧版本或解析失败。
|
|
69
|
+
- 精确版本 `dsh plugin add dsh-phone-link@0.1.0` 不受限制。
|
|
70
|
+
- 插件市场的一键安装是不带版本的,因此发布后 24 小时内验证到旧版属于预期行为,不是发布失败。
|
|
71
|
+
|
|
72
|
+
## 7. 版本号策略
|
|
73
|
+
|
|
74
|
+
- PATCH:修复、文档、内部重构。
|
|
75
|
+
- MINOR:新增功能、新增配置键、新增存储键。
|
|
76
|
+
- MAJOR:删除/重命名存储键、改变默认行为或最低 DSH 版本。
|
|
77
|
+
|
|
78
|
+
## 8. 回滚
|
|
79
|
+
|
|
80
|
+
保留 GitHub Release 与历史 tag;用户可安装指定版本。npm 发布 72 小时内可 unpublish,或直接发布修复版本。配置键只增不减,避免回滚时需要迁移。
|
package/lib/bridge.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
async function makeUserMessage(text) {
|
|
4
|
+
try {
|
|
5
|
+
const llm = await import('@deepseek-ai/dsh-llm')
|
|
6
|
+
if (typeof llm.createUserMessage === 'function') {
|
|
7
|
+
return llm.createUserMessage({
|
|
8
|
+
content: [{ type: 'text', text }],
|
|
9
|
+
source: { kind: 'user' },
|
|
10
|
+
})
|
|
11
|
+
}
|
|
12
|
+
} catch {
|
|
13
|
+
// Fall back to the structural shape used by current DSH builds.
|
|
14
|
+
}
|
|
15
|
+
return { role: 'user', content: [{ type: 'text', text }], source: { kind: 'user' } }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function listSessions(ctx) {
|
|
19
|
+
const s = ctx.sessions
|
|
20
|
+
if (!s) return []
|
|
21
|
+
if (typeof s.list === 'function') return s.list()
|
|
22
|
+
if (typeof s.getAll === 'function') return s.getAll()
|
|
23
|
+
if (typeof s.values === 'function') return [...s.values()]
|
|
24
|
+
return []
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function readHistory(ctx, sessionId, limit = 50) {
|
|
28
|
+
const sp = ctx.sessionPersistence
|
|
29
|
+
if (!sp) return []
|
|
30
|
+
if (typeof sp.page === 'function') return sp.page(sessionId, { limit })
|
|
31
|
+
if (typeof sp.read === 'function') return sp.read(sessionId)
|
|
32
|
+
return []
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function createBridge({ ctx, transport, config, log }) {
|
|
36
|
+
const pendingApprovals = new Map()
|
|
37
|
+
|
|
38
|
+
function onEvent(type, payload) {
|
|
39
|
+
transport.sendSecure('event', { kind: type, ...payload })
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function installEventBridge() {
|
|
43
|
+
ctx.on?.('session/event', (_session, event) => {
|
|
44
|
+
if (!event) return
|
|
45
|
+
onEvent('session.event', {
|
|
46
|
+
eventType: event.type,
|
|
47
|
+
sessionId: _session?.id ?? null,
|
|
48
|
+
at: Date.now(),
|
|
49
|
+
})
|
|
50
|
+
})
|
|
51
|
+
ctx.on?.('agent/assistant-stream', ({ frame }) => {
|
|
52
|
+
if (frame?.type !== 'chunk' || frame.chunk?.type !== 'text-delta') return
|
|
53
|
+
onEvent('assistant.delta', { text: frame.chunk.text })
|
|
54
|
+
})
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function installApprovalGate() {
|
|
58
|
+
ctx.on?.('tools/pre-execute', async (exec, next) => {
|
|
59
|
+
const approvalId = randomUUID()
|
|
60
|
+
const detail = {
|
|
61
|
+
approvalId,
|
|
62
|
+
tool: exec?.tool?.name ?? exec?.name ?? 'unknown',
|
|
63
|
+
arguments: exec?.arguments ?? exec?.input ?? null,
|
|
64
|
+
at: Date.now(),
|
|
65
|
+
}
|
|
66
|
+
transport.sendSecure('approval.request', detail)
|
|
67
|
+
const decision = await new Promise((resolve) => {
|
|
68
|
+
const timer = setTimeout(() => {
|
|
69
|
+
pendingApprovals.delete(approvalId)
|
|
70
|
+
resolve({ allow: false, reason: 'timeout' })
|
|
71
|
+
}, config.approvalTimeoutMs)
|
|
72
|
+
pendingApprovals.set(approvalId, { resolve, timer })
|
|
73
|
+
})
|
|
74
|
+
if (!decision.allow) {
|
|
75
|
+
return { kind: 'deny', reason: decision.reason || 'denied on phone' }
|
|
76
|
+
}
|
|
77
|
+
return next()
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function handleRpc(method, params) {
|
|
82
|
+
switch (method) {
|
|
83
|
+
case 'harness.ping':
|
|
84
|
+
return { ok: true, at: Date.now() }
|
|
85
|
+
|
|
86
|
+
case 'harness.session.list': {
|
|
87
|
+
const sessions = await listSessions(ctx)
|
|
88
|
+
return {
|
|
89
|
+
sessions: (Array.isArray(sessions) ? sessions : []).map((s) => ({
|
|
90
|
+
id: s.id ?? s.sessionId ?? null,
|
|
91
|
+
title: s.title ?? s.name ?? null,
|
|
92
|
+
updatedAt: s.updatedAt ?? s.lastActivity ?? null,
|
|
93
|
+
})),
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
case 'harness.session.history': {
|
|
98
|
+
const messages = await readHistory(ctx, params.sessionId, params.limit)
|
|
99
|
+
return { sessionId: params.sessionId, messages }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
case 'harness.prompt': {
|
|
103
|
+
if (typeof params.text !== 'string' || !params.text.trim()) {
|
|
104
|
+
throw Object.assign(new Error('text is required'), { code: 'INVALID_PROMPT' })
|
|
105
|
+
}
|
|
106
|
+
const agent = (params.sessionId && ctx.agents?.get?.(params.sessionId)) || ctx.agents?.create?.()
|
|
107
|
+
if (!agent?.followup) {
|
|
108
|
+
throw Object.assign(new Error('agents service unavailable'), { code: 'AGENTS_UNAVAILABLE' })
|
|
109
|
+
}
|
|
110
|
+
const receipt = await agent.followup(await makeUserMessage(params.text))
|
|
111
|
+
return { ok: true, receipt: receipt ?? null, sessionId: params.sessionId ?? null }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
case 'harness.approval.respond': {
|
|
115
|
+
const pending = pendingApprovals.get(params.approvalId)
|
|
116
|
+
if (!pending) return { ok: false, reason: 'UNKNOWN_APPROVAL' }
|
|
117
|
+
clearTimeout(pending.timer)
|
|
118
|
+
pendingApprovals.delete(params.approvalId)
|
|
119
|
+
pending.resolve({ allow: params.allow === true, reason: params.reason })
|
|
120
|
+
return { ok: true }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
case 'harness.cancel': {
|
|
124
|
+
const agent = params.sessionId && ctx.agents?.get?.(params.sessionId)
|
|
125
|
+
if (!agent?.cancel) return { ok: false, reason: 'UNSUPPORTED' }
|
|
126
|
+
await agent.cancel()
|
|
127
|
+
return { ok: true }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
default:
|
|
131
|
+
throw Object.assign(new Error(`unknown method: ${method}`), { code: 'UNKNOWN_METHOD' })
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function dispose() {
|
|
136
|
+
for (const p of pendingApprovals.values()) clearTimeout(p.timer)
|
|
137
|
+
pendingApprovals.clear()
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return { installEventBridge, installApprovalGate, handleRpc, onEvent, dispose }
|
|
141
|
+
}
|
package/lib/crypto.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createCipheriv,
|
|
3
|
+
createDecipheriv,
|
|
4
|
+
createPrivateKey,
|
|
5
|
+
createPublicKey,
|
|
6
|
+
createHash,
|
|
7
|
+
diffieHellman,
|
|
8
|
+
generateKeyPairSync,
|
|
9
|
+
hkdfSync,
|
|
10
|
+
randomBytes,
|
|
11
|
+
} from 'node:crypto'
|
|
12
|
+
|
|
13
|
+
const X25519_SPKI_PREFIX = Buffer.from('302a300506032b656e032100', 'hex')
|
|
14
|
+
const CONTEXT = 'dsh-phone-link/v1'
|
|
15
|
+
|
|
16
|
+
export function b64u(buf) {
|
|
17
|
+
return Buffer.from(buf).toString('base64url')
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function unb64u(str) {
|
|
21
|
+
return Buffer.from(str, 'base64url')
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function sha256(buf) {
|
|
25
|
+
return createHash('sha256').update(buf).digest()
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function fingerprint(publicKeyB64u) {
|
|
29
|
+
return sha256(unb64u(publicKeyB64u)).toString('hex')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function generateIdentity() {
|
|
33
|
+
const { publicKey, privateKey } = generateKeyPairSync('x25519')
|
|
34
|
+
const raw = publicKey.export({ format: 'der', type: 'spki' }).subarray(-32)
|
|
35
|
+
return {
|
|
36
|
+
publicKey: b64u(raw),
|
|
37
|
+
privateKeyPem: privateKey.export({ format: 'pem', type: 'pkcs8' }).toString(),
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function publicKeyFromRaw(rawB64u) {
|
|
42
|
+
const raw = unb64u(rawB64u)
|
|
43
|
+
if (raw.length !== 32) throw new Error('identityKey must be 32 bytes')
|
|
44
|
+
return createPublicKey({
|
|
45
|
+
key: Buffer.concat([X25519_SPKI_PREFIX, raw]),
|
|
46
|
+
format: 'der',
|
|
47
|
+
type: 'spki',
|
|
48
|
+
})
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function deriveSessionKey(privateKeyPem, peerPublicKeyB64u, connectionId) {
|
|
52
|
+
const privateKey = createPrivateKey(privateKeyPem)
|
|
53
|
+
const publicKey = publicKeyFromRaw(peerPublicKeyB64u)
|
|
54
|
+
const shared = diffieHellman({ privateKey, publicKey })
|
|
55
|
+
const salt = Buffer.from(connectionId, 'utf8')
|
|
56
|
+
const info = Buffer.from(CONTEXT, 'utf8')
|
|
57
|
+
return Buffer.from(hkdfSync('sha256', shared, salt, info, 32))
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function encrypt(key, counter, plaintext, aad = '') {
|
|
61
|
+
const iv = randomBytes(12)
|
|
62
|
+
const tag = Buffer.alloc(16)
|
|
63
|
+
const cipher = createCipheriv('aes-256-gcm', key, iv, { authTagLength: 16 })
|
|
64
|
+
const fullAad = Buffer.from(`${aad}:${counter}`, 'utf8')
|
|
65
|
+
cipher.setAAD(fullAad)
|
|
66
|
+
const body = Buffer.concat([cipher.update(Buffer.from(plaintext, 'utf8')), cipher.final()])
|
|
67
|
+
cipher.getAuthTag().copy(tag)
|
|
68
|
+
return b64u(Buffer.concat([iv, tag, body]))
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function decrypt(key, counter, sealed, aad = '') {
|
|
72
|
+
const packed = unb64u(sealed)
|
|
73
|
+
if (packed.length < 28) throw new Error('ciphertext too short')
|
|
74
|
+
const iv = packed.subarray(0, 12)
|
|
75
|
+
const tag = packed.subarray(12, 28)
|
|
76
|
+
const body = packed.subarray(28)
|
|
77
|
+
const decipher = createDecipheriv('aes-256-gcm', key, iv, { authTagLength: 16 })
|
|
78
|
+
const fullAad = Buffer.from(`${aad}:${counter}`, 'utf8')
|
|
79
|
+
decipher.setAAD(fullAad)
|
|
80
|
+
decipher.setAuthTag(tag)
|
|
81
|
+
return Buffer.concat([decipher.update(body), decipher.final()]).toString('utf8')
|
|
82
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { createBridge } from './bridge.js'
|
|
2
|
+
import { ensureState, registerRoutes, saveState } from './pairing.js'
|
|
3
|
+
import { RelayTransport } from './transport.js'
|
|
4
|
+
|
|
5
|
+
export const name = 'phone-link'
|
|
6
|
+
export const inject = []
|
|
7
|
+
|
|
8
|
+
let SchemaFallback = null
|
|
9
|
+
try {
|
|
10
|
+
const mod = await import('@deepseek-ai/schemastery')
|
|
11
|
+
SchemaFallback = mod.default ?? mod
|
|
12
|
+
} catch {
|
|
13
|
+
SchemaFallback = null
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const Config = SchemaFallback
|
|
17
|
+
? SchemaFallback.object({
|
|
18
|
+
serverUrl: SchemaFallback.string().default('https://api.example.com'),
|
|
19
|
+
relayPath: SchemaFallback.string().default('/ws/v1/connect'),
|
|
20
|
+
pairPath: SchemaFallback.string().default('/phone-link/pair'),
|
|
21
|
+
deviceName: SchemaFallback.string().default('DSH desktop'),
|
|
22
|
+
heartbeatMs: SchemaFallback.number().default(30000),
|
|
23
|
+
reconnectMinMs: SchemaFallback.number().default(1000),
|
|
24
|
+
reconnectMaxMs: SchemaFallback.number().default(30000),
|
|
25
|
+
approvalTimeoutMs: SchemaFallback.number().default(60000),
|
|
26
|
+
autoConnect: SchemaFallback.boolean().default(true),
|
|
27
|
+
})
|
|
28
|
+
: {
|
|
29
|
+
serverUrl: 'https://api.example.com',
|
|
30
|
+
relayPath: '/ws/v1/connect',
|
|
31
|
+
pairPath: '/phone-link/pair',
|
|
32
|
+
deviceName: 'DSH desktop',
|
|
33
|
+
heartbeatMs: 30000,
|
|
34
|
+
reconnectMinMs: 1000,
|
|
35
|
+
reconnectMaxMs: 30000,
|
|
36
|
+
approvalTimeoutMs: 60000,
|
|
37
|
+
autoConnect: true,
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function apply(ctx, config = {}) {
|
|
41
|
+
const log = ctx.logger ?? console
|
|
42
|
+
const state = await ensureState()
|
|
43
|
+
let currentSession = null
|
|
44
|
+
|
|
45
|
+
const transport = new RelayTransport({
|
|
46
|
+
config,
|
|
47
|
+
identity: state.identity,
|
|
48
|
+
device: state.device,
|
|
49
|
+
log,
|
|
50
|
+
onRpc: (method, params) => bridge.handleRpc(method, params),
|
|
51
|
+
onEvent: (type, payload) => {
|
|
52
|
+
if (type === 'connected') log?.info?.('phone connected: %s', payload.connectionId)
|
|
53
|
+
},
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
const bridge = createBridge({ ctx, transport, config, log })
|
|
57
|
+
bridge.installEventBridge()
|
|
58
|
+
bridge.installApprovalGate()
|
|
59
|
+
|
|
60
|
+
registerRoutes(ctx, config, {
|
|
61
|
+
setState: (s) => {
|
|
62
|
+
state.deviceId = s.deviceId
|
|
63
|
+
state.identity = s.identity
|
|
64
|
+
},
|
|
65
|
+
setSession: (s) => {
|
|
66
|
+
currentSession = s
|
|
67
|
+
},
|
|
68
|
+
getSession: () => currentSession,
|
|
69
|
+
onPaired: async (result) => {
|
|
70
|
+
state.device = {
|
|
71
|
+
deviceId: result.device?.deviceId ?? state.deviceId,
|
|
72
|
+
tokens: result.tokens,
|
|
73
|
+
phoneIdentityKey: result.peer?.identityKey ?? result.phone?.identityKey ?? null,
|
|
74
|
+
}
|
|
75
|
+
await saveState(state)
|
|
76
|
+
transport.device = state.device
|
|
77
|
+
if (config.autoConnect !== false) transport.start()
|
|
78
|
+
},
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
if (config.autoConnect !== false && state.device?.tokens?.accessToken) {
|
|
82
|
+
transport.start()
|
|
83
|
+
} else if (config.serverUrl?.includes('example.com')) {
|
|
84
|
+
log?.warn?.('[phone-link] set serverUrl in plugin config before pairing')
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
ctx.effect(() => () => {
|
|
88
|
+
transport.stop()
|
|
89
|
+
bridge.dispose()
|
|
90
|
+
})
|
|
91
|
+
}
|
package/lib/pairing.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { homedir } from 'node:os'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { randomUUID } from 'node:crypto'
|
|
5
|
+
import { fingerprint, generateIdentity } from './crypto.js'
|
|
6
|
+
|
|
7
|
+
export function stateDir() {
|
|
8
|
+
return path.join(homedir(), '.dsh', 'phone-link')
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function ensureState() {
|
|
12
|
+
const dir = stateDir()
|
|
13
|
+
await mkdir(dir, { recursive: true, mode: 0o700 })
|
|
14
|
+
const file = path.join(dir, 'state.json')
|
|
15
|
+
let state = {}
|
|
16
|
+
try {
|
|
17
|
+
state = JSON.parse(await readFile(file, 'utf8'))
|
|
18
|
+
} catch {
|
|
19
|
+
state = {}
|
|
20
|
+
}
|
|
21
|
+
if (!state.deviceId) state.deviceId = randomUUID()
|
|
22
|
+
if (!state.identity) {
|
|
23
|
+
state.identity = generateIdentity()
|
|
24
|
+
state.identity.fingerprint = fingerprint(state.identity.publicKey)
|
|
25
|
+
}
|
|
26
|
+
await saveState(state)
|
|
27
|
+
return state
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function saveState(state) {
|
|
31
|
+
const file = path.join(stateDir(), 'state.json')
|
|
32
|
+
await writeFile(file, JSON.stringify(state, null, 2), { mode: 0o600, encoding: 'utf8' })
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function api(config, p) {
|
|
36
|
+
return new URL(p, config.serverUrl).toString()
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function createPairing(config, state) {
|
|
40
|
+
const res = await fetch(api(config, '/api/v1/pairing/sessions'), {
|
|
41
|
+
method: 'POST',
|
|
42
|
+
headers: { 'content-type': 'application/json' },
|
|
43
|
+
body: JSON.stringify({
|
|
44
|
+
v: 1,
|
|
45
|
+
device: {
|
|
46
|
+
deviceId: state.deviceId,
|
|
47
|
+
name: config.deviceName || 'DSH desktop',
|
|
48
|
+
role: 'host',
|
|
49
|
+
platform: 'desktop',
|
|
50
|
+
identityKey: state.identity.publicKey,
|
|
51
|
+
clientVersion: '0.1.0',
|
|
52
|
+
},
|
|
53
|
+
}),
|
|
54
|
+
})
|
|
55
|
+
if (!res.ok) throw new Error(`create pairing failed: HTTP ${res.status}`)
|
|
56
|
+
return res.json()
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function confirmPairing(config, sessionId, code) {
|
|
60
|
+
const clean = String(code || '').replace(/\D/g, '')
|
|
61
|
+
if (clean.length !== 8) throw new Error('验证码必须是 8 位数字')
|
|
62
|
+
const res = await fetch(api(config, `/api/v1/pairing/sessions/${encodeURIComponent(sessionId)}/host/confirm`), {
|
|
63
|
+
method: 'POST',
|
|
64
|
+
headers: { 'content-type': 'application/json' },
|
|
65
|
+
body: JSON.stringify({ v: 1, verificationCode: clean }),
|
|
66
|
+
})
|
|
67
|
+
if (!res.ok) throw new Error(`confirm failed: HTTP ${res.status}`)
|
|
68
|
+
return res.json()
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function pairPage(session, config) {
|
|
72
|
+
const qr = session.qrUrl || session.ticketUrl || `https://${new URL(config.serverUrl).host}/pair#v1.${session.ticket}`
|
|
73
|
+
const { default: QRCode } = await import('qrcode')
|
|
74
|
+
const svg = await QRCode.toString(qr, { type: 'svg', width: 240, margin: 1 })
|
|
75
|
+
return `<!doctype html>
|
|
76
|
+
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
77
|
+
<title>dsh-phone-link 配对</title>
|
|
78
|
+
<style>
|
|
79
|
+
body{font-family:system-ui,sans-serif;max-width:520px;margin:40px auto;padding:0 20px;color:#222}
|
|
80
|
+
code{background:#f2f2f2;padding:2px 6px;border-radius:4px}
|
|
81
|
+
.qr{border:1px solid #ddd;padding:12px;border-radius:8px;display:inline-block}
|
|
82
|
+
input{font-size:20px;letter-spacing:4px;padding:8px;width:220px}
|
|
83
|
+
button{padding:9px 18px;font-size:15px;cursor:pointer}
|
|
84
|
+
.msg{margin-top:14px;color:#b00;min-height:20px}
|
|
85
|
+
</style></head><body>
|
|
86
|
+
<h2>dsh-phone-link 配对</h2>
|
|
87
|
+
<p>用手机 App 扫描下方二维码,确认服务器域名与主机指纹后,在手机上领取验证码。</p>
|
|
88
|
+
<div class="qr">${svg}</div>
|
|
89
|
+
<p>服务器:<code>${escapeHtml(config.serverUrl)}</code></p>
|
|
90
|
+
<p>本机指纹:<code>${escapeHtml(session.host?.identityKey ? fingerprint(session.host.identityKey) : '未提供')}</code></p>
|
|
91
|
+
<h3>在电脑上输入手机显示的 8 位验证码</h3>
|
|
92
|
+
<form id="f"><input id="code" inputmode="numeric" maxlength="8" placeholder="00000000" autocomplete="off"><button type="submit">确认绑定</button></form>
|
|
93
|
+
<div class="msg" id="msg"></div>
|
|
94
|
+
<script>
|
|
95
|
+
document.getElementById('f').addEventListener('submit', async (e) => {
|
|
96
|
+
e.preventDefault()
|
|
97
|
+
const msg = document.getElementById('msg')
|
|
98
|
+
msg.textContent = '提交中…'
|
|
99
|
+
const res = await fetch(location.pathname + '/confirm', {
|
|
100
|
+
method: 'POST', headers: {'content-type':'application/json'},
|
|
101
|
+
body: JSON.stringify({sessionId: ${JSON.stringify(session.sessionId)}, code: document.getElementById('code').value})
|
|
102
|
+
})
|
|
103
|
+
const data = await res.json().catch(() => ({}))
|
|
104
|
+
msg.textContent = data.ok ? '绑定成功,可以关闭此页面。' : (data.error || '绑定失败,请重新扫码。')
|
|
105
|
+
})
|
|
106
|
+
</script></body></html>`
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function escapeHtml(s) {
|
|
110
|
+
return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]))
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function registerRoutes(ctx, config, handlers) {
|
|
114
|
+
const prefix = config.pairPath || '/phone-link/pair'
|
|
115
|
+
ctx.inject({ webServer: {} }, (child) => {
|
|
116
|
+
child.effect(() => child.webServer.register({
|
|
117
|
+
kind: 'exact',
|
|
118
|
+
path: prefix,
|
|
119
|
+
handler: async (_req, res) => {
|
|
120
|
+
res.setHeader('content-type', 'text/html; charset=utf-8')
|
|
121
|
+
res.setHeader('cache-control', 'no-store')
|
|
122
|
+
try {
|
|
123
|
+
if (config.serverUrl.includes('example.com')) throw new Error('请先在插件配置中设置 serverUrl')
|
|
124
|
+
const state = await ensureState()
|
|
125
|
+
handlers.setState(state)
|
|
126
|
+
const session = await createPairing(config, state)
|
|
127
|
+
handlers.setSession(session)
|
|
128
|
+
res.end(await pairPage(session, config))
|
|
129
|
+
} catch (err) {
|
|
130
|
+
res.statusCode = 500
|
|
131
|
+
res.end(`<pre>${escapeHtml(err.message)}</pre>`)
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
}))
|
|
135
|
+
|
|
136
|
+
child.effect(() => child.webServer.register({
|
|
137
|
+
kind: 'exact',
|
|
138
|
+
path: `${prefix}/confirm`,
|
|
139
|
+
handler: async (req, res) => {
|
|
140
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
141
|
+
res.setHeader('cache-control', 'no-store')
|
|
142
|
+
try {
|
|
143
|
+
const chunks = []
|
|
144
|
+
for await (const c of req) chunks.push(c)
|
|
145
|
+
const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')
|
|
146
|
+
const sessionId = body.sessionId || handlers.getSession()?.sessionId
|
|
147
|
+
if (!sessionId) throw new Error('配对会话不存在,请重新打开配对页')
|
|
148
|
+
const result = await confirmPairing(config, sessionId, body.code)
|
|
149
|
+
handlers.onPaired(result)
|
|
150
|
+
res.end(JSON.stringify({ ok: true }))
|
|
151
|
+
} catch (err) {
|
|
152
|
+
res.statusCode = 400
|
|
153
|
+
res.end(JSON.stringify({ ok: false, error: err.message }))
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
}))
|
|
157
|
+
})
|
|
158
|
+
}
|
package/lib/transport.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { deriveSessionKey, decrypt, encrypt } from './crypto.js'
|
|
3
|
+
|
|
4
|
+
let WebSocketImpl = null
|
|
5
|
+
async function getWebSocket() {
|
|
6
|
+
if (!WebSocketImpl) {
|
|
7
|
+
const mod = await import('ws')
|
|
8
|
+
WebSocketImpl = mod.default ?? mod.WebSocket ?? mod
|
|
9
|
+
}
|
|
10
|
+
return WebSocketImpl
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function nextDelay(min, max, attempt) {
|
|
14
|
+
const base = Math.min(max, min * 2 ** Math.min(attempt, 10))
|
|
15
|
+
return Math.round(base * (0.5 + Math.random() * 0.5))
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export class RelayTransport {
|
|
19
|
+
constructor({ config, identity, device, log, onRpc, onEvent }) {
|
|
20
|
+
this.config = config
|
|
21
|
+
this.identity = identity
|
|
22
|
+
this.device = device
|
|
23
|
+
this.log = log
|
|
24
|
+
this.onRpc = onRpc
|
|
25
|
+
this.onEvent = onEvent
|
|
26
|
+
this.ws = null
|
|
27
|
+
this.stopped = false
|
|
28
|
+
this.attempt = 0
|
|
29
|
+
this.timer = null
|
|
30
|
+
this.heartbeat = null
|
|
31
|
+
this.sessionKey = null
|
|
32
|
+
this.connectionId = null
|
|
33
|
+
this.sendCounter = 0
|
|
34
|
+
this.recvCounter = 0
|
|
35
|
+
this.pending = new Map()
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
start() {
|
|
39
|
+
this.stopped = false
|
|
40
|
+
this.attempt = 0
|
|
41
|
+
this._open()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
stop() {
|
|
45
|
+
this.stopped = true
|
|
46
|
+
clearTimeout(this.timer)
|
|
47
|
+
clearInterval(this.heartbeat)
|
|
48
|
+
for (const p of this.pending.values()) clearTimeout(p.timer)
|
|
49
|
+
this.pending.clear()
|
|
50
|
+
this.ws?.close()
|
|
51
|
+
this.ws = null
|
|
52
|
+
this.sessionKey = null
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async _open() {
|
|
56
|
+
if (this.stopped) return
|
|
57
|
+
const WebSocket = await getWebSocket()
|
|
58
|
+
const url = new URL(this.config.relayPath, this.config.serverUrl)
|
|
59
|
+
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
|
|
60
|
+
const token = this.device?.tokens?.accessToken
|
|
61
|
+
if (token) url.searchParams.set('access_token', token)
|
|
62
|
+
|
|
63
|
+
const ws = new WebSocket(url.toString(), {
|
|
64
|
+
headers: token ? { authorization: `Bearer ${token}` } : {},
|
|
65
|
+
handshakeTimeout: 15000,
|
|
66
|
+
})
|
|
67
|
+
this.ws = ws
|
|
68
|
+
|
|
69
|
+
ws.on('open', () => {
|
|
70
|
+
this.attempt = 0
|
|
71
|
+
this._send({
|
|
72
|
+
v: 1,
|
|
73
|
+
id: randomUUID(),
|
|
74
|
+
type: 'hello',
|
|
75
|
+
timestamp: Date.now(),
|
|
76
|
+
payload: {
|
|
77
|
+
role: 'host',
|
|
78
|
+
deviceId: this.device.deviceId,
|
|
79
|
+
identityKey: this.identity.publicKey,
|
|
80
|
+
protocols: [1],
|
|
81
|
+
capabilities: ['transport.relay', 'rpc.v1', 'event.v1'],
|
|
82
|
+
clientVersion: '0.1.0',
|
|
83
|
+
},
|
|
84
|
+
})
|
|
85
|
+
clearInterval(this.heartbeat)
|
|
86
|
+
this.heartbeat = setInterval(() => this._send({ v: 1, id: randomUUID(), type: 'ping', timestamp: Date.now(), payload: {} }), this.config.heartbeatMs)
|
|
87
|
+
this.log?.info?.('relay connected')
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
ws.on('message', (raw) => {
|
|
91
|
+
let frame
|
|
92
|
+
try {
|
|
93
|
+
frame = JSON.parse(raw.toString())
|
|
94
|
+
} catch {
|
|
95
|
+
return
|
|
96
|
+
}
|
|
97
|
+
this._onFrame(frame)
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
ws.on('close', () => this._scheduleReconnect('closed'))
|
|
101
|
+
ws.on('error', (err) => {
|
|
102
|
+
this.log?.warn?.('relay error: %s', err.message)
|
|
103
|
+
})
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
_scheduleReconnect(reason) {
|
|
107
|
+
clearInterval(this.heartbeat)
|
|
108
|
+
this.ws = null
|
|
109
|
+
this.sessionKey = null
|
|
110
|
+
if (this.stopped) return
|
|
111
|
+
const delay = nextDelay(this.config.reconnectMinMs, this.config.reconnectMaxMs, this.attempt++)
|
|
112
|
+
this.log?.warn?.('relay %s, reconnect in %dms', reason, delay)
|
|
113
|
+
this.timer = setTimeout(() => this._open(), delay)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
_send(frame) {
|
|
117
|
+
if (this.ws?.readyState !== 1) return false
|
|
118
|
+
this.ws.send(JSON.stringify(frame))
|
|
119
|
+
return true
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
send(type, payload) {
|
|
123
|
+
return this._send({ v: 1, id: randomUUID(), type, timestamp: Date.now(), payload })
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
sendSecure(type, payload) {
|
|
127
|
+
if (!this.sessionKey) return false
|
|
128
|
+
const counter = ++this.sendCounter
|
|
129
|
+
const body = JSON.stringify({ type, payload, counter })
|
|
130
|
+
const sealed = encrypt(this.sessionKey, counter, body, this.connectionId)
|
|
131
|
+
return this.send('data', {
|
|
132
|
+
connectionId: this.connectionId,
|
|
133
|
+
counter,
|
|
134
|
+
sealed,
|
|
135
|
+
kind: type === 'prompt' ? 'prompt' : 'event',
|
|
136
|
+
})
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async rpc(method, params, timeoutMs = 15000) {
|
|
140
|
+
const id = randomUUID()
|
|
141
|
+
return new Promise((resolve, reject) => {
|
|
142
|
+
const timer = setTimeout(() => {
|
|
143
|
+
this.pending.delete(id)
|
|
144
|
+
reject(new Error(`RPC timeout: ${method}`))
|
|
145
|
+
}, timeoutMs)
|
|
146
|
+
this.pending.set(id, { resolve, reject, timer })
|
|
147
|
+
if (!this.sendSecure('rpc.request', { method, params, requestId: id })) {
|
|
148
|
+
clearTimeout(timer)
|
|
149
|
+
this.pending.delete(id)
|
|
150
|
+
reject(new Error('relay not connected'))
|
|
151
|
+
}
|
|
152
|
+
})
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
_resolveRpc(id, result, error) {
|
|
156
|
+
const p = this.pending.get(id)
|
|
157
|
+
if (!p) return
|
|
158
|
+
clearTimeout(p.timer)
|
|
159
|
+
this.pending.delete(id)
|
|
160
|
+
if (error) p.reject(new Error(`${error.code || 'RPC_ERROR'}: ${error.message || 'unknown'}`))
|
|
161
|
+
else p.resolve(result)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
_onFrame(frame) {
|
|
165
|
+
if (!frame || frame.v !== 1 || typeof frame.type !== 'string') return
|
|
166
|
+
const p = frame.payload || {}
|
|
167
|
+
|
|
168
|
+
switch (frame.type) {
|
|
169
|
+
case 'hello.ack':
|
|
170
|
+
this.connectionId = p.connectionId
|
|
171
|
+
break
|
|
172
|
+
case 'connect.incoming': {
|
|
173
|
+
if (!p.peerIdentityKey || !p.connectionId) return
|
|
174
|
+
try {
|
|
175
|
+
this.sessionKey = deriveSessionKey(this.identity.privateKeyPem, p.peerIdentityKey, p.connectionId)
|
|
176
|
+
this.connectionId = p.connectionId
|
|
177
|
+
this.sendCounter = 0
|
|
178
|
+
this.recvCounter = 0
|
|
179
|
+
this.send('connect.accepted', { connectionId: p.connectionId, grantId: p.grantId })
|
|
180
|
+
this.onEvent?.('connected', { connectionId: p.connectionId })
|
|
181
|
+
} catch (err) {
|
|
182
|
+
this.log?.error?.('secure channel failed: %s', err.message)
|
|
183
|
+
}
|
|
184
|
+
break
|
|
185
|
+
}
|
|
186
|
+
case 'data': {
|
|
187
|
+
if (!this.sessionKey || p.connectionId !== this.connectionId) return
|
|
188
|
+
const counter = Number(p.counter)
|
|
189
|
+
if (!Number.isSafeInteger(counter) || counter <= this.recvCounter) return
|
|
190
|
+
this.recvCounter = counter
|
|
191
|
+
try {
|
|
192
|
+
const plain = decrypt(this.sessionKey, counter, p.sealed, this.connectionId)
|
|
193
|
+
const msg = JSON.parse(plain)
|
|
194
|
+
this._dispatch(msg)
|
|
195
|
+
} catch (err) {
|
|
196
|
+
this.log?.warn?.('dropped invalid frame: %s', err.message)
|
|
197
|
+
}
|
|
198
|
+
break
|
|
199
|
+
}
|
|
200
|
+
case 'rpc.response':
|
|
201
|
+
this._resolveRpc(frame.id, p.result, null)
|
|
202
|
+
break
|
|
203
|
+
case 'rpc.error':
|
|
204
|
+
this._resolveRpc(frame.id, null, p)
|
|
205
|
+
break
|
|
206
|
+
case 'error':
|
|
207
|
+
if (p.retryable === false) this.stop()
|
|
208
|
+
else this._scheduleReconnect(p.message || 'server error')
|
|
209
|
+
break
|
|
210
|
+
case 'pong':
|
|
211
|
+
break
|
|
212
|
+
default:
|
|
213
|
+
break
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
_dispatch(msg) {
|
|
218
|
+
const { type, payload, requestId } = msg
|
|
219
|
+
if (type === 'rpc.request') {
|
|
220
|
+
Promise.resolve(this.onRpc?.(payload?.method, payload?.params || {}, requestId))
|
|
221
|
+
.then((result) => this.sendSecure('rpc.response', { requestId, result }))
|
|
222
|
+
.catch((err) => this.sendSecure('rpc.error', { requestId, code: err.code || 'RPC_FAILED', message: err.message }))
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
if (type === 'rpc.response') {
|
|
226
|
+
this._resolveRpc(requestId, payload?.result, null)
|
|
227
|
+
return
|
|
228
|
+
}
|
|
229
|
+
if (type === 'rpc.error') {
|
|
230
|
+
this._resolveRpc(requestId, null, payload)
|
|
231
|
+
return
|
|
232
|
+
}
|
|
233
|
+
this.onEvent?.(type, payload || {})
|
|
234
|
+
}
|
|
235
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,67 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-phone-link",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"displayName": "远程助手",
|
|
5
|
+
"description": "远程助手 — Link a phone app to a local DeepSeek Harness session through your own relay and backend. · 把手机 App 经自建中继接到本机 DSH 会话。",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./lib/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./lib/index.js",
|
|
10
|
+
"./package.json": "./package.json",
|
|
11
|
+
"./cordis.patch.yml": "./cordis.patch.yml"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"lib",
|
|
15
|
+
"cordis.patch.yml",
|
|
16
|
+
"README.md",
|
|
17
|
+
"CHANGELOG.md",
|
|
18
|
+
"LICENSE",
|
|
19
|
+
"docs",
|
|
20
|
+
"catalog.json"
|
|
21
|
+
],
|
|
22
|
+
"dsh": {
|
|
23
|
+
"displayName": {
|
|
24
|
+
"zh": "远程助手",
|
|
25
|
+
"en": "Phone Link"
|
|
26
|
+
},
|
|
27
|
+
"bundle": {
|
|
28
|
+
"patch": "./cordis.patch.yml"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"keywords": [
|
|
32
|
+
"dsh",
|
|
33
|
+
"dsh-plugin",
|
|
34
|
+
"dsh-plugin-hub",
|
|
35
|
+
"deepseek-harness",
|
|
36
|
+
"cordis",
|
|
37
|
+
"remote",
|
|
38
|
+
"phone",
|
|
39
|
+
"harmonyos",
|
|
40
|
+
"android",
|
|
41
|
+
"ios"
|
|
42
|
+
],
|
|
43
|
+
"license": "MIT",
|
|
44
|
+
"engines": {
|
|
45
|
+
"node": ">=18"
|
|
46
|
+
},
|
|
47
|
+
"scripts": {
|
|
48
|
+
"test": "node --test test/*.test.js",
|
|
49
|
+
"verify": "node --check lib/index.js && node --check lib/crypto.js && node --check lib/transport.js && node --check lib/bridge.js && node --check lib/pairing.js && node --test test/*.test.js",
|
|
50
|
+
"pack:check": "npm pack --dry-run"
|
|
51
|
+
},
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"qrcode": "^1.5.4",
|
|
54
|
+
"ws": "^8.18.0"
|
|
55
|
+
},
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"@deepseek-ai/schemastery": "*"
|
|
58
|
+
},
|
|
59
|
+
"repository": {
|
|
60
|
+
"type": "git",
|
|
61
|
+
"url": "git+https://github.com/mostcat1992-code/dsh-phone-link.git"
|
|
62
|
+
},
|
|
63
|
+
"homepage": "https://github.com/mostcat1992-code/dsh-phone-link#readme",
|
|
64
|
+
"bugs": {
|
|
65
|
+
"url": "https://github.com/mostcat1992-code/dsh-phone-link/issues"
|
|
66
|
+
}
|
|
67
|
+
}
|