@duke-dsh-plugins/dsh-remote-control 0.0.0-stage → 1.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +90 -2
- package/client.js +747 -0
- package/cordis.patch.yml +12 -0
- package/icon.svg +20 -0
- package/index.js +731 -0
- package/lib/config.mjs +270 -0
- package/lib/host-bridge.mjs +2848 -0
- package/lib/images.mjs +458 -0
- package/lib/pairing.mjs +266 -0
- package/lib/protocol.mjs +390 -0
- package/lib/push.mjs +229 -0
- package/lib/qr.mjs +439 -0
- package/lib/relay-client.mjs +741 -0
- package/lib/relay-supervisor.mjs +798 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/market/index.json +95 -0
- package/package.json +77 -4
- package/typert.host.js +243 -0
- package/vendor/relay/server.js +777 -0
package/index.js
ADDED
|
@@ -0,0 +1,731 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-remote-control — Host half(契约 §8.1;v1.1.x 配对入口搬进设置面板)。
|
|
3
|
+
*
|
|
4
|
+
* Cordis **类插件**(`export default class RemoteControlService extends TypertRemoteService`):
|
|
5
|
+
* DSH 装载器把本包作为类插件挂载,服务名 `remoteControl`;Typert 网关把它
|
|
6
|
+
* 标记为 Remote 的方法暴露给浏览器端(`ctx.remote.remoteControl.*`)——
|
|
7
|
+
* 桌面端「设置 → DSH Pocket」分区即通过这三个 Remote 方法驱动:
|
|
8
|
+
*
|
|
9
|
+
* - getPairing() → {relayUrl, channel, hidden, qrSvg}(二维码内联进设置页)
|
|
10
|
+
* - rotateSecret()→ 轮换 channel/secret(旧二维码立即失效)
|
|
11
|
+
* - setHidden(b) → 隐藏/恢复配对展示
|
|
12
|
+
*
|
|
13
|
+
* 插件同时保留函数式入口 `apply(ctx, config)`(等价于类插件的初始化路径),
|
|
14
|
+
* 供按函数插件方式挂载的宿主使用;两条路径共用 `startRemoteHost()`。
|
|
15
|
+
*
|
|
16
|
+
* 宿主侧能力(原有,全部保留):
|
|
17
|
+
* - 会话遥控:list / create / prompt / cancel / rename(§5.1,经 sessionController)
|
|
18
|
+
* - 事件桥接:session.added/removed/status/activity、assistant.delta
|
|
19
|
+
* (按会话节流 ≤8 条/秒)、turn.end(§5.2)
|
|
20
|
+
* - 审批/提问拦截:`approval/request` 与 `user-questions/request` 瀑布以
|
|
21
|
+
* {prepend:true} 抢占在桌面答案器之前;**仅当手机在线且开关打开**才拦截,
|
|
22
|
+
* 超时(默认 120s)/出错/取消一律 next() 放行——绝不 fail-closed(§5.5)
|
|
23
|
+
* - Push Kit 旁路:审批/提问/任务完成推送通知(§6;未配置 AGC 时优雅禁用)
|
|
24
|
+
*
|
|
25
|
+
* E2E 加密(§3/§7):HKDF-SHA256 派生 + AES-256-GCM,AAD 绑定发送方 role 与
|
|
26
|
+
* seq;启动时跑契约 KAT 自测,**失败即禁用连接**(打日志,绝不带病连中继)。
|
|
27
|
+
*
|
|
28
|
+
* 配对(§3):首次启用在插件自有 config.json 生成 channel(16 位 base32)与
|
|
29
|
+
* secret(base64url 24 字节);**二维码在设置面板展示**(v1.1.x 起不再有
|
|
30
|
+
* /remote-pairing 命令)。手机扫码后凭 URI 里的 relayUrl/channel/secret 配对。
|
|
31
|
+
*
|
|
32
|
+
* 写入范围:仅本包目录。运行时数据(config.json)在 DSH_HOME/remote-control/。
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
import { Service } from "@deepseek-ai/cordis";
|
|
36
|
+
import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
37
|
+
import { assertKat } from "./lib/protocol.mjs";
|
|
38
|
+
import { loadConfig, saveConfig, dataDir, bumpSelfEpoch, readEpoch, savePeerEpoch } from "./lib/config.mjs";
|
|
39
|
+
import { RelayClient } from "./lib/relay-client.mjs";
|
|
40
|
+
import { RelaySupervisor, shouldTickWatchdog } from "./lib/relay-supervisor.mjs";
|
|
41
|
+
import { PushSender, pushConfigured, pushUnavailableReason } from "./lib/push.mjs";
|
|
42
|
+
import { HostBridge } from "./lib/host-bridge.mjs";
|
|
43
|
+
import {
|
|
44
|
+
buildPairingUri,
|
|
45
|
+
renderPairing,
|
|
46
|
+
writePairingSvg,
|
|
47
|
+
rotatePairingIdentity,
|
|
48
|
+
setPairingHidden,
|
|
49
|
+
loopbackWarning,
|
|
50
|
+
} from "./lib/pairing.mjs";
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 标记一个实例方法为 Remote 导出——不依赖装饰器语法(Node ESM 在此不支持
|
|
54
|
+
* 提案装饰器),而是手动驱动同一个 `Remote(name)` 装饰器:构造一个合成装饰器
|
|
55
|
+
* 上下文,把注册进来的 initializer 对实例执行一遍(标记落在原型上)。
|
|
56
|
+
*
|
|
57
|
+
* @param {object} instance - 活的 Service 实例。
|
|
58
|
+
* @param {string} method - 公开实例方法名。
|
|
59
|
+
* @param {string} [exportName] - wire 导出名;默认与方法名相同。
|
|
60
|
+
*/
|
|
61
|
+
function markRemoteMethod(instance, method, exportName = method) {
|
|
62
|
+
const decorator = Remote(exportName, undefined);
|
|
63
|
+
const initializers = [];
|
|
64
|
+
decorator(undefined, {
|
|
65
|
+
kind: "method",
|
|
66
|
+
name: method,
|
|
67
|
+
static: false,
|
|
68
|
+
private: false,
|
|
69
|
+
addInitializer: (fn) => initializers.push(fn),
|
|
70
|
+
});
|
|
71
|
+
for (const fn of initializers) fn.call(instance);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 已启动的宿主链路状态(按 ctx 记账)——保证同一条链路只启动一次。
|
|
76
|
+
* @type {WeakMap<object, {cfg:any, configPath:string, log:Function, relay:any, katOk:boolean, running:boolean}>}
|
|
77
|
+
*/
|
|
78
|
+
const HOST_STATES = new WeakMap();
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 启动宿主侧链路(KAT → 配置 → Push → 中继客户端 + Host 桥接)。
|
|
82
|
+
*
|
|
83
|
+
* 任何一步的早退都**不抛**:配置缺失/被禁用/KAT 失败时插件空转,但状态句柄
|
|
84
|
+
* 仍然返回——设置面板据此回答「未配置 relayUrl」等可操作提示。
|
|
85
|
+
*
|
|
86
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
87
|
+
* @param {Record<string, unknown>} rowConfig Cordis 行 config(紧急覆盖开关)。
|
|
88
|
+
* @returns {{cfg:any, configPath:string, log:Function, relay:any, katOk:boolean, running:boolean}}
|
|
89
|
+
*/
|
|
90
|
+
export function startRemoteHost(ctx, rowConfig) {
|
|
91
|
+
// 幂等:同一个 ctx 只启动一次(类插件的 [Service.init] 与函数式 apply 共存时
|
|
92
|
+
// 不会起两条中继链路、不会重复注册监听)。
|
|
93
|
+
const existing = HOST_STATES.get(ctx);
|
|
94
|
+
// **N2**:已 dispose 的旧 state 不能复用——插件二次加载时若拿到它,
|
|
95
|
+
// 托管会永久失效(supervisor 的 disposed 是单向闩锁)。丢掉重建。
|
|
96
|
+
if (existing && existing.supervisor && existing.supervisor.disposed === true) {
|
|
97
|
+
HOST_STATES.delete(ctx);
|
|
98
|
+
} else if (existing) {
|
|
99
|
+
return existing;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const log = (level, message, extra) => {
|
|
103
|
+
const line = "[dsh-remote-control] " + message + (extra ? " " + JSON.stringify(extra) : "");
|
|
104
|
+
try {
|
|
105
|
+
if (level === "error") ctx.logger?.error?.(line);
|
|
106
|
+
else if (level === "warn") ctx.logger?.warn?.(line);
|
|
107
|
+
else ctx.logger?.info?.(line);
|
|
108
|
+
} catch {
|
|
109
|
+
/* 日志失败不影响主流程 */
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
// ---- 1. 协议 KAT 自测(契约 §7;失败禁用连接)---------------------------
|
|
114
|
+
let katOk = true;
|
|
115
|
+
try {
|
|
116
|
+
assertKat();
|
|
117
|
+
log("info", "protocol KAT self-test passed (HKDF/AES-256-GCM/AAD binding)");
|
|
118
|
+
} catch (e) {
|
|
119
|
+
katOk = false;
|
|
120
|
+
log("error", "protocol KAT self-test FAILED — relay connection DISABLED", { error: String(e && e.message) });
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ---- 2. 配置(§3.1:首次启动生成 channel/secret)------------------------
|
|
124
|
+
let loaded;
|
|
125
|
+
try {
|
|
126
|
+
loaded = loadConfig();
|
|
127
|
+
} catch (e) {
|
|
128
|
+
log("error", "config load failed — remote control disabled", { error: String(e && e.message) });
|
|
129
|
+
const failed = { cfg: null, configPath: "", log, relay: null, katOk: false, running: false };
|
|
130
|
+
HOST_STATES.set(ctx, failed);
|
|
131
|
+
return failed;
|
|
132
|
+
}
|
|
133
|
+
const { config: cfg, generated, repaired, path: configPath } = loaded;
|
|
134
|
+
if (repaired) log("warn", "config was corrupt; regenerated pairing identity", { path: configPath });
|
|
135
|
+
if (generated) log("info", "generated new pairing identity (channel/secret)", { channel: cfg.channel });
|
|
136
|
+
|
|
137
|
+
// 行 config 紧急覆盖:enabled / relayUrl / intercept* / approvalTimeoutMs
|
|
138
|
+
const rowCfg = rowConfig && typeof rowConfig === "object" ? rowConfig : {};
|
|
139
|
+
if (typeof rowCfg.enabled === "boolean") cfg.enabled = rowCfg.enabled;
|
|
140
|
+
if (typeof rowCfg.relayUrl === "string" && rowCfg.relayUrl !== "") cfg.relayUrl = rowCfg.relayUrl;
|
|
141
|
+
if (typeof rowCfg.interceptApprovals === "boolean") cfg.interceptApprovals = rowCfg.interceptApprovals;
|
|
142
|
+
if (typeof rowCfg.interceptQuestions === "boolean") cfg.interceptQuestions = rowCfg.interceptQuestions;
|
|
143
|
+
if (typeof rowCfg.approvalTimeoutMs === "number") cfg.approvalTimeoutMs = rowCfg.approvalTimeoutMs;
|
|
144
|
+
|
|
145
|
+
const state = {
|
|
146
|
+
cfg,
|
|
147
|
+
configPath,
|
|
148
|
+
log,
|
|
149
|
+
relay: null,
|
|
150
|
+
katOk,
|
|
151
|
+
running: false,
|
|
152
|
+
/** 启动/热更换中继链路(设置页改中继地址时复用)。 */
|
|
153
|
+
startLink: null,
|
|
154
|
+
/** 停止并释放当前链路(清空中继地址时用)。 */
|
|
155
|
+
stopLink: null,
|
|
156
|
+
/** 中继进程托管器(v1.1.1:本机中继随插件启动/停止)。 */
|
|
157
|
+
supervisor: null,
|
|
158
|
+
/** 托管状态快照(设置页展示)。 */
|
|
159
|
+
relayProcess: null,
|
|
160
|
+
/** 看门狗定时器(托管进程意外退出后自动重拉)。 */
|
|
161
|
+
relayWatchdog: null,
|
|
162
|
+
};
|
|
163
|
+
HOST_STATES.set(ctx, state);
|
|
164
|
+
|
|
165
|
+
// ---- 3. Push Kit(§6;未配置时优雅禁用,不影响主链路)--------------------
|
|
166
|
+
// 提前创建:设置页改中继地址后要能立刻起链路,push 发送器得先备好。
|
|
167
|
+
const push = new PushSender(cfg.push, log);
|
|
168
|
+
if (!pushConfigured(cfg.push)) {
|
|
169
|
+
log("info", "push.state disabled: " + pushUnavailableReason(cfg.push), { hint: "configure push.* in " + configPath });
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// ---- 4. 链路控制(启动 / 热更换 / 停止)------------------------------------
|
|
173
|
+
/** 停止并释放当前链路(幂等;未在跑时是 no-op)。 */
|
|
174
|
+
function stopLink() {
|
|
175
|
+
const currentRelay = state.relay;
|
|
176
|
+
const detach = state.detachBridge;
|
|
177
|
+
state.relay = null;
|
|
178
|
+
state.bridge = null;
|
|
179
|
+
state.detachBridge = null;
|
|
180
|
+
state.running = false;
|
|
181
|
+
try {
|
|
182
|
+
currentRelay?.close();
|
|
183
|
+
} catch {
|
|
184
|
+
/* ignore */
|
|
185
|
+
}
|
|
186
|
+
try {
|
|
187
|
+
detach?.();
|
|
188
|
+
} catch {
|
|
189
|
+
/* ignore */
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// ---- 4b. 中继进程托管(v1.1.1)--------------------------------------------
|
|
194
|
+
// 中继是本方案的服务端,不该靠人手起:插件启动时把**本机**中继拉起来,
|
|
195
|
+
// 插件卸载/DSH 退出时收掉(只按 child handle 停自己起的那个进程)。
|
|
196
|
+
const supervisor = new RelaySupervisor({
|
|
197
|
+
log: (level, msg, extra) => log(level, "relay supervisor: " + msg, extra),
|
|
198
|
+
// 状态一变就刷新宿主快照(审计 S2):子进程崩溃时由 supervisor 主动通知,
|
|
199
|
+
// 否则设置页会一直显示「运行中(已死的 pid)」。
|
|
200
|
+
onStatus: (snapshot) => {
|
|
201
|
+
state.relayProcess = snapshot;
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
state.supervisor = supervisor;
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* 确保本机中继在跑(幂等)。中继没起来时链路客户端会自己退避重连,
|
|
208
|
+
* 所以这里不阻塞插件启动。
|
|
209
|
+
*/
|
|
210
|
+
async function ensureRelayProcess() {
|
|
211
|
+
try {
|
|
212
|
+
const snapshot = await supervisor.ensure(state.cfg.relayUrl, {
|
|
213
|
+
// **N1:`cfg.enabled` 必须折进 autoStart**——插件被禁用时绝不能拉起中继
|
|
214
|
+
// (审计实测:enabled=false 时看门狗仍把 0.0.0.0 的中继拉了起来)。
|
|
215
|
+
autoStart: state.cfg.enabled === true && state.cfg.autoStartRelay !== false,
|
|
216
|
+
relayToken: state.cfg.relayToken,
|
|
217
|
+
// v1.1.3:托管中继的 TLS(契约 §3.4.2)——两个路径都填才起 wss://。
|
|
218
|
+
tls: { cert: state.cfg.relayTlsCert, key: state.cfg.relayTlsKey },
|
|
219
|
+
});
|
|
220
|
+
state.relayProcess = snapshot;
|
|
221
|
+
if (snapshot.managed) {
|
|
222
|
+
log("info", snapshot.detail, { pid: snapshot.pid, port: snapshot.port });
|
|
223
|
+
} else if (snapshot.detail) {
|
|
224
|
+
log("info", snapshot.detail, { port: snapshot.port });
|
|
225
|
+
}
|
|
226
|
+
} catch (e) {
|
|
227
|
+
log("error", "relay supervisor failed", { error: String(e && e.message) });
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// 看门狗:托管的中继意外退出(例如被外部杀掉)后自动重拉。
|
|
232
|
+
// 15s 一次;**判定走 shouldRestartRelay()**(纯函数,有单测覆盖)——
|
|
233
|
+
// 审计指出:原来读 ensure() 时刻的静态快照 → 子进程退出后快照仍是 running=true
|
|
234
|
+
// → 永不重拉,设置页还显示「运行中(已死的 pid)」。
|
|
235
|
+
state.relayWatchdog = setInterval(() => {
|
|
236
|
+
// 判定走纯函数 shouldTickWatchdog()(有单测覆盖):
|
|
237
|
+
// ① 插件被禁用 → 一律不碰中继(N1:否则「用户关了插件」反而把中继拉起来);
|
|
238
|
+
// ② 其余按 supervisor 的实时状态决定(含 external 重探、崩溃重拉)。
|
|
239
|
+
if (!shouldTickWatchdog(supervisor.status, state.cfg)) return;
|
|
240
|
+
void ensureRelayProcess();
|
|
241
|
+
}, 15_000);
|
|
242
|
+
if (typeof state.relayWatchdog.unref === "function") state.relayWatchdog.unref();
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* 建立中继链路:已有客户端 → 热更换(换地址立即重连);没有 → 新建客户端 + 桥接。
|
|
246
|
+
* @returns {{ok:boolean, mode?:string, message?:string}}
|
|
247
|
+
*/
|
|
248
|
+
function startLink() {
|
|
249
|
+
if (!state.katOk) {
|
|
250
|
+
return { ok: false, message: "协议 KAT 自测未通过,已禁用连接。" };
|
|
251
|
+
}
|
|
252
|
+
if (state.cfg.enabled !== true) {
|
|
253
|
+
return { ok: false, message: "插件已被配置禁用(config.json 的 enabled=false)。" };
|
|
254
|
+
}
|
|
255
|
+
const url = typeof state.cfg.relayUrl === "string" ? state.cfg.relayUrl.trim() : "";
|
|
256
|
+
if (url === "") {
|
|
257
|
+
return { ok: false, message: "未配置中继地址。" };
|
|
258
|
+
}
|
|
259
|
+
if (state.relay) {
|
|
260
|
+
// 已有客户端:热更换(地址/凭据立即生效,旧连接作废)
|
|
261
|
+
state.relay.reload({
|
|
262
|
+
relayUrl: url,
|
|
263
|
+
channel: state.cfg.channel,
|
|
264
|
+
secret: state.cfg.secret,
|
|
265
|
+
relayToken: state.cfg.relayToken,
|
|
266
|
+
});
|
|
267
|
+
return { ok: true, mode: "reload" };
|
|
268
|
+
}
|
|
269
|
+
// 新建客户端 + Host 桥接
|
|
270
|
+
const client = new RelayClient({
|
|
271
|
+
relayUrl: url,
|
|
272
|
+
channel: state.cfg.channel,
|
|
273
|
+
secret: state.cfg.secret,
|
|
274
|
+
relayToken: state.cfg.relayToken,
|
|
275
|
+
role: "host",
|
|
276
|
+
log,
|
|
277
|
+
// v1.1.3 会话纪元(契约 §3.4.1):抗重放的持久化锚点。
|
|
278
|
+
// nextSelfEpoch —— 自纪元 +1,**先落盘再使用**(崩溃也不得复用纪元);
|
|
279
|
+
// peerState/savePeerEpoch —— 已接受的对端纪元 + 钉扎 sid(回退检测)。
|
|
280
|
+
// 落盘失败时 relay-client 会拒绝开链路(纪元不可持久化 = 重放窗口)。
|
|
281
|
+
epoch: {
|
|
282
|
+
nextSelfEpoch: () => bumpSelfEpoch(),
|
|
283
|
+
peerState: () => readEpoch(),
|
|
284
|
+
savePeerEpoch: (peer, peerSid) => savePeerEpoch(peer, peerSid),
|
|
285
|
+
},
|
|
286
|
+
onStatus: (s, detail) => {
|
|
287
|
+
log("info", "relay " + s + (detail ? ": " + detail : ""), {
|
|
288
|
+
relayUrl: state.cfg.relayUrl,
|
|
289
|
+
channel: state.cfg.channel,
|
|
290
|
+
});
|
|
291
|
+
if (s === "ready") state.bridge?.sendPushState();
|
|
292
|
+
},
|
|
293
|
+
onPeer: (joined, role) => {
|
|
294
|
+
log("info", "peer " + (joined ? "joined" : "left"), { role });
|
|
295
|
+
},
|
|
296
|
+
onFatal: (code, message) => {
|
|
297
|
+
// bad-hello / channel-full:协议级拒绝,重连无意义——停掉链路并大声说明
|
|
298
|
+
log("error", "relay rejected connection (fatal); disconnecting", { code, message, channel: state.cfg.channel });
|
|
299
|
+
stopLink();
|
|
300
|
+
},
|
|
301
|
+
onMessage: (plain) => {
|
|
302
|
+
state.bridge?.onPlainMessage(plain);
|
|
303
|
+
},
|
|
304
|
+
});
|
|
305
|
+
const hostBridge = new HostBridge({ ctx, relay: client, push, config: state.cfg, log });
|
|
306
|
+
const detachHostBridge = hostBridge.attach();
|
|
307
|
+
client.start();
|
|
308
|
+
state.relay = client;
|
|
309
|
+
state.bridge = hostBridge;
|
|
310
|
+
state.detachBridge = detachHostBridge;
|
|
311
|
+
state.running = true;
|
|
312
|
+
return { ok: true, mode: "start" };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
state.startLink = startLink;
|
|
316
|
+
state.stopLink = stopLink;
|
|
317
|
+
state.ensureRelayProcess = ensureRelayProcess;
|
|
318
|
+
|
|
319
|
+
// ---- 5. 卸载清理(插件热卸载时释放 socket/定时器/监听)-------------------
|
|
320
|
+
// 无论当前是否在跑链路都要注册:设置页稍后起链路时同样要能收回资源。
|
|
321
|
+
ctx.effect(() => () => {
|
|
322
|
+
stopLink();
|
|
323
|
+
// v1.1.1:收掉**自己起的**中继子进程(只按 child handle 停,不按名字/端口杀)
|
|
324
|
+
if (state.relayWatchdog) {
|
|
325
|
+
clearInterval(state.relayWatchdog);
|
|
326
|
+
state.relayWatchdog = null;
|
|
327
|
+
}
|
|
328
|
+
// **dispose 而非 stop**(审计 S4):dispose 置位「永久停用」,
|
|
329
|
+
// 在途的 ensure 完成后不会再把中继拉起来(原来 stop 后在途 ensure 仍会 spawn → 孤儿)。
|
|
330
|
+
void supervisor.dispose();
|
|
331
|
+
// **N2:必须把 ctx 的状态从 HOST_STATES 里摘掉**——
|
|
332
|
+
// 否则插件二次加载(DSH `set_plugin` 关→开走 cordis `Fiber.restart()`,**复用同一个 ctx**)
|
|
333
|
+
// 会拿到这份「已 dispose 的旧 state」→ 托管永久失效(实测:端口再也不监听、看门狗也没了)。
|
|
334
|
+
HOST_STATES.delete(ctx);
|
|
335
|
+
log("info", "unloaded");
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
if (!katOk) {
|
|
339
|
+
log("error", "KAT failure takes precedence: not connecting", { channel: cfg.channel });
|
|
340
|
+
return state;
|
|
341
|
+
}
|
|
342
|
+
if (cfg.enabled !== true) {
|
|
343
|
+
log("info", "plugin disabled by config; not connecting", { path: configPath });
|
|
344
|
+
return state;
|
|
345
|
+
}
|
|
346
|
+
if (typeof cfg.relayUrl !== "string" || cfg.relayUrl === "") {
|
|
347
|
+
// 未配置 relayUrl:优雅空转——不连接、不拦截(瀑布照常 next()),
|
|
348
|
+
// 等用户在设置页填写中继地址(v1.1.x:setRelayUrl 会现场把链路拉起来)。
|
|
349
|
+
log(
|
|
350
|
+
"info",
|
|
351
|
+
"relayUrl not configured — idling (no connection, no interception). " +
|
|
352
|
+
"Set the relay address in the DSH settings panel (\"DSH Pocket\"), then pair the phone app. channel=" +
|
|
353
|
+
cfg.channel,
|
|
354
|
+
);
|
|
355
|
+
return state;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const started = startLink();
|
|
359
|
+
if (started.ok) {
|
|
360
|
+
log("info", "remote control active", {
|
|
361
|
+
channel: cfg.channel,
|
|
362
|
+
relayUrl: cfg.relayUrl,
|
|
363
|
+
interceptApprovals: cfg.interceptApprovals,
|
|
364
|
+
interceptQuestions: cfg.interceptQuestions,
|
|
365
|
+
approvalTimeoutMs: cfg.approvalTimeoutMs,
|
|
366
|
+
dataDir: dataDir(),
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// v1.1.1:中继进程随插件启动(不阻塞上面的链路建立——中继没起来时
|
|
371
|
+
// 链路客户端会自己退避重连,中继一上线就能连上)。
|
|
372
|
+
void ensureRelayProcess();
|
|
373
|
+
|
|
374
|
+
return state;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* 函数式插件入口(与类插件共用 startRemoteHost)。
|
|
379
|
+
*
|
|
380
|
+
* 注意:DSH 装载器对模块做 `unwrapExports`——**default 导出优先**,
|
|
381
|
+
* 因此在 DSH 里生效的是下面的 `RemoteControlService` 类插件;本函数供
|
|
382
|
+
* 以函数插件方式挂载本包的宿主使用(两条路径不会同时生效)。
|
|
383
|
+
*
|
|
384
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
385
|
+
* @param {Record<string, unknown>} config Cordis 行 config。
|
|
386
|
+
*/
|
|
387
|
+
export function apply(ctx, config) {
|
|
388
|
+
startRemoteHost(ctx, config);
|
|
389
|
+
// 配置热保存钩子占位:配对信息的写回由 lib/pairing.mjs 负责(rotate/hide)。
|
|
390
|
+
void saveConfig;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Host 侧 Remote 服务:桌面端「设置 → DSH Pocket」分区的唯一入口。
|
|
395
|
+
*
|
|
396
|
+
* 服务名 `remoteControl`(= Typert wire namespace)。
|
|
397
|
+
*/
|
|
398
|
+
export class RemoteControlService extends TypertRemoteService {
|
|
399
|
+
/** 无硬服务依赖:sessionController 等由 HostBridge 自己按需 ctx.get。 */
|
|
400
|
+
static inject = [];
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Cordis 类插件用 `new Callback(ctx, config)` 构造——第二个参数是**插件配置**,
|
|
404
|
+
* 不是服务名;服务名必须传给 super()。
|
|
405
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
406
|
+
* @param {Record<string, unknown>} config
|
|
407
|
+
*/
|
|
408
|
+
constructor(ctx, config) {
|
|
409
|
+
super(ctx, "remoteControl");
|
|
410
|
+
this._rowConfig = config && typeof config === "object" ? config : {};
|
|
411
|
+
/** @type {any} 宿主链路状态(startRemoteHost 的返回值)。 */
|
|
412
|
+
this._host = null;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Cordis 类插件初始化器:构造之后、服务发布之前运行。
|
|
417
|
+
* 启动宿主链路并标记 Remote 方法;每一步独立兜底——失败只降级,不让插件激活失败。
|
|
418
|
+
*/
|
|
419
|
+
[Service.init]() {
|
|
420
|
+
try {
|
|
421
|
+
this._host = startRemoteHost(this.ctx, this._rowConfig);
|
|
422
|
+
} catch (e) {
|
|
423
|
+
this._host = null;
|
|
424
|
+
// eslint-disable-next-line no-console
|
|
425
|
+
(typeof console !== "undefined" && console.warn ? console.warn : () => {})(
|
|
426
|
+
"[dsh-remote-control] host startup failed:",
|
|
427
|
+
e,
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
for (const method of ["getPairing", "rotateSecret", "setHidden", "setRelayUrl", "setRelayToken"]) {
|
|
431
|
+
try {
|
|
432
|
+
markRemoteMethod(this, method, method);
|
|
433
|
+
} catch (e) {
|
|
434
|
+
// eslint-disable-next-line no-console
|
|
435
|
+
(typeof console !== "undefined" && console.warn ? console.warn : () => {})(
|
|
436
|
+
"[dsh-remote-control] Remote method not published: " + method,
|
|
437
|
+
e,
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* 当前配对信息(设置面板渲染用)。
|
|
445
|
+
* @returns {Promise<{ok:true,value:object}|{ok:false,error:{code:string,message:string}}>}
|
|
446
|
+
*/
|
|
447
|
+
async getPairing() {
|
|
448
|
+
const host = this._host;
|
|
449
|
+
if (!host || !host.cfg) {
|
|
450
|
+
return { ok: false, error: { code: "not-ready", message: "插件尚未初始化。" } };
|
|
451
|
+
}
|
|
452
|
+
const cfg = host.cfg;
|
|
453
|
+
if (cfg.hidden === true) {
|
|
454
|
+
return {
|
|
455
|
+
ok: true,
|
|
456
|
+
value: withRelayProcess(pairingValue(cfg, "配对已隐藏:手机端请使用此前扫码保存的配对信息。", false), host),
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
// 未配置 relayUrl:给出明确指引(**不返回 URI/secret**)
|
|
460
|
+
try {
|
|
461
|
+
buildPairingUri(cfg);
|
|
462
|
+
} catch (e) {
|
|
463
|
+
return {
|
|
464
|
+
ok: false,
|
|
465
|
+
error: { code: "pairing-unavailable", message: String(e && e.message) },
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
return { ok: true, value: withRelayProcess(pairingValue(cfg, "", true), host) };
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* 轮换配对信息:换 channel+secret 并落盘,旧二维码立即失效。
|
|
473
|
+
* @returns {Promise<{ok:true,value:object}|{ok:false,error:{code:string,message:string}}>}
|
|
474
|
+
*/
|
|
475
|
+
async rotateSecret() {
|
|
476
|
+
const host = this._host;
|
|
477
|
+
if (!host || !host.cfg) {
|
|
478
|
+
return { ok: false, error: { code: "not-ready", message: "插件尚未初始化。" } };
|
|
479
|
+
}
|
|
480
|
+
const res = rotatePairingIdentity({
|
|
481
|
+
config: host.cfg,
|
|
482
|
+
configPath: host.configPath,
|
|
483
|
+
log: host.log,
|
|
484
|
+
getRelay: () => host.relay,
|
|
485
|
+
});
|
|
486
|
+
if (!res.ok) {
|
|
487
|
+
return { ok: false, error: { code: "pairing-rotate-failed", message: String(res.error) } };
|
|
488
|
+
}
|
|
489
|
+
const pairing = await this.getPairing();
|
|
490
|
+
if (!pairing.ok) return pairing;
|
|
491
|
+
pairing.value.note = res.note ?? "";
|
|
492
|
+
return pairing;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* 隐藏 / 恢复配对展示。
|
|
497
|
+
* @param {boolean} hidden
|
|
498
|
+
* @returns {Promise<{ok:true,value:object}|{ok:false,error:{code:string,message:string}}>}
|
|
499
|
+
*/
|
|
500
|
+
async setHidden(hidden) {
|
|
501
|
+
const host = this._host;
|
|
502
|
+
if (!host || !host.cfg) {
|
|
503
|
+
return { ok: false, error: { code: "not-ready", message: "插件尚未初始化。" } };
|
|
504
|
+
}
|
|
505
|
+
const res = setPairingHidden(hidden === true, { config: host.cfg, log: host.log });
|
|
506
|
+
if (!res.ok) {
|
|
507
|
+
return { ok: false, error: { code: "pairing-hide-failed", message: String(res.error) } };
|
|
508
|
+
}
|
|
509
|
+
const pairing = await this.getPairing();
|
|
510
|
+
if (!pairing.ok) return pairing;
|
|
511
|
+
pairing.value.note = res.hidden === true ? "配对二维码已隐藏。" : "配对二维码已恢复显示。";
|
|
512
|
+
return pairing;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* 设置中继地址(设置页输入框直改,v1.1.x)。
|
|
517
|
+
*
|
|
518
|
+
* 校验 → 落盘 → 热切换链路 → 回新的配对信息。
|
|
519
|
+
* 空串 = 清除中继地址(插件回到空转状态,不再连接中继)。
|
|
520
|
+
*
|
|
521
|
+
* @param {string} url 中继地址,如 ws://192.168.1.10:8788;空串 = 清除
|
|
522
|
+
* @returns {Promise<{ok:true,value:object}|{ok:false,error:{code:string,message:string}}>}
|
|
523
|
+
*/
|
|
524
|
+
async setRelayUrl(url) {
|
|
525
|
+
const host = this._host;
|
|
526
|
+
if (!host || !host.cfg) {
|
|
527
|
+
return { ok: false, error: { code: "not-ready", message: "插件尚未初始化。" } };
|
|
528
|
+
}
|
|
529
|
+
if (typeof url !== "string") {
|
|
530
|
+
return { ok: false, error: { code: "bad-params", message: "中继地址必须是字符串。" } };
|
|
531
|
+
}
|
|
532
|
+
const raw = url.trim();
|
|
533
|
+
if (raw.length > 512) {
|
|
534
|
+
return { ok: false, error: { code: "bad-params", message: "中继地址过长(上限 512 字符)。" } };
|
|
535
|
+
}
|
|
536
|
+
if (raw !== "") {
|
|
537
|
+
if (!/^wss?:\/\//i.test(raw)) {
|
|
538
|
+
return {
|
|
539
|
+
ok: false,
|
|
540
|
+
error: { code: "bad-params", message: "中继地址必须以 ws:// 或 wss:// 开头(例如 ws://192.168.1.10:8788)。" },
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
let parsed = null;
|
|
544
|
+
try {
|
|
545
|
+
parsed = new URL(raw);
|
|
546
|
+
} catch {
|
|
547
|
+
parsed = null;
|
|
548
|
+
}
|
|
549
|
+
if (!parsed || !parsed.host) {
|
|
550
|
+
return {
|
|
551
|
+
ok: false,
|
|
552
|
+
error: { code: "bad-params", message: "中继地址不是合法的 URL(缺少主机名,例如 ws://192.168.1.10:8788)。" },
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// 落盘(只把 relayUrl 写回磁盘配置;行内紧急覆盖不动)
|
|
558
|
+
try {
|
|
559
|
+
const fresh = loadConfig().config;
|
|
560
|
+
fresh.relayUrl = raw;
|
|
561
|
+
saveConfig(fresh);
|
|
562
|
+
} catch (e) {
|
|
563
|
+
return {
|
|
564
|
+
ok: false,
|
|
565
|
+
error: { code: "config-save-failed", message: "保存中继地址失败:" + String(e && e.message) },
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
// 内存同步 + 链路热切换
|
|
569
|
+
host.cfg.relayUrl = raw;
|
|
570
|
+
host.log("info", "relay address updated", { relayUrl: raw, cleared: raw === "" });
|
|
571
|
+
|
|
572
|
+
let note = "";
|
|
573
|
+
if (raw === "") {
|
|
574
|
+
// 清除:停掉链路,插件回到空转(不连接、不拦截)
|
|
575
|
+
host.stopLink?.();
|
|
576
|
+
// v1.1.1:地址清空 → 收掉托管的中继进程(否则会留一个没人用的中继)
|
|
577
|
+
void host.supervisor?.stop();
|
|
578
|
+
host.relayProcess = null;
|
|
579
|
+
note = "中继地址已清除,插件已停止连接中继(空转)。填写地址后可立即重新连接。";
|
|
580
|
+
} else {
|
|
581
|
+
const link = host.startLink ? host.startLink() : { ok: false, message: "链路控制不可用。" };
|
|
582
|
+
note = link.ok
|
|
583
|
+
? link.mode === "reload"
|
|
584
|
+
? "中继地址已更新,链路已用新地址重连。"
|
|
585
|
+
: "中继地址已更新,链路已启动。"
|
|
586
|
+
: "中继地址已保存,但链路未启动:" + (link.message || "未知原因");
|
|
587
|
+
// v1.1.1:地址变了 → 托管进程要跟着换(端口可能也变了)
|
|
588
|
+
void host.ensureRelayProcess?.();
|
|
589
|
+
}
|
|
590
|
+
const warn = loopbackWarning(raw);
|
|
591
|
+
if (warn) note = (note ? note + " " : "") + warn;
|
|
592
|
+
|
|
593
|
+
const value = pairingValue(host.cfg, note, raw !== "");
|
|
594
|
+
return { ok: true, value: withRelayProcess(value, host) };
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* 设置页直改**中继鉴权令牌**(v1.1.3,契约 §3.4.2 / §3.5 的 `t=` 参数)。
|
|
599
|
+
*
|
|
600
|
+
* 令牌会出现在 transport hello 里(**明文可读**)——所以:
|
|
601
|
+
* - 返回体里**没有令牌明文**,只有 `relayTokenSet`(是否已设置);
|
|
602
|
+
* - 令牌由用户自己填(须与中继的 RELAY_TOKEN 一致),配对二维码会自动带上它。
|
|
603
|
+
*
|
|
604
|
+
* 改令牌必须**重连链路**(transport hello 的内容变了)。
|
|
605
|
+
*
|
|
606
|
+
* @param {string} token 令牌;空串 = 清除
|
|
607
|
+
* @returns {Promise<{ok:true,value:object}|{ok:false,error:{code:string,message:string}}>}
|
|
608
|
+
*/
|
|
609
|
+
async setRelayToken(token) {
|
|
610
|
+
const host = this._host;
|
|
611
|
+
if (!host || !host.cfg) {
|
|
612
|
+
return { ok: false, error: { code: "not-ready", message: "插件尚未初始化。" } };
|
|
613
|
+
}
|
|
614
|
+
if (typeof token !== "string") {
|
|
615
|
+
return { ok: false, error: { code: "bad-params", message: "中继令牌必须是字符串。" } };
|
|
616
|
+
}
|
|
617
|
+
const raw = token.trim();
|
|
618
|
+
if (raw.length > 512) {
|
|
619
|
+
return { ok: false, error: { code: "bad-params", message: "中继令牌过长(上限 512 字符)。" } };
|
|
620
|
+
}
|
|
621
|
+
if (raw !== "" && !/^[\x21-\x7e]+$/.test(raw)) {
|
|
622
|
+
// 只接受可打印 ASCII(不含空格/控制符):令牌走 JSON 与 query 参数,
|
|
623
|
+
// 空白与控制字符会引出「配对串对不上」的玄学问题。
|
|
624
|
+
return {
|
|
625
|
+
ok: false,
|
|
626
|
+
error: {
|
|
627
|
+
code: "bad-params",
|
|
628
|
+
message: "中继令牌只能包含可打印 ASCII 字符(不能有空格或控制字符)。",
|
|
629
|
+
},
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
try {
|
|
633
|
+
const fresh = loadConfig().config;
|
|
634
|
+
fresh.relayToken = raw;
|
|
635
|
+
saveConfig(fresh);
|
|
636
|
+
} catch (e) {
|
|
637
|
+
return {
|
|
638
|
+
ok: false,
|
|
639
|
+
error: { code: "config-save-failed", message: "保存中继令牌失败:" + String(e && e.message) },
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
host.cfg.relayToken = raw;
|
|
643
|
+
host.log("info", "relay token updated", { cleared: raw === "" });
|
|
644
|
+
|
|
645
|
+
let note = "";
|
|
646
|
+
if (raw === "") {
|
|
647
|
+
host.stopLink?.();
|
|
648
|
+
} else {
|
|
649
|
+
const link = host.startLink ? host.startLink() : { ok: false, message: "链路控制不可用。" };
|
|
650
|
+
note = link.ok
|
|
651
|
+
? link.mode === "reload"
|
|
652
|
+
? "中继令牌已更新,链路已重连。"
|
|
653
|
+
: "中继令牌已更新,链路已启动。"
|
|
654
|
+
: "中继令牌已保存,但链路未启动:" + (link.message || "未知原因");
|
|
655
|
+
}
|
|
656
|
+
const value = pairingValue(host.cfg, note, host.cfg.relayUrl !== "" && host.cfg.hidden !== true);
|
|
657
|
+
return { ok: true, value: withRelayProcess(value, host) };
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* 组装配对信息(**不含 secret 明文**——secret 只存在于二维码图像里)。
|
|
663
|
+
*
|
|
664
|
+
* @param {any} cfg 插件配置
|
|
665
|
+
* @param {string} note 提示文案
|
|
666
|
+
* @param {boolean} withQr 是否产出二维码(无中继地址或已隐藏时不产出)
|
|
667
|
+
* @returns {{relayUrl:string, channel:string, hidden:boolean, qrSvg:string, note:string}}
|
|
668
|
+
*/
|
|
669
|
+
function pairingValue(cfg, note, withQr) {
|
|
670
|
+
const value = {
|
|
671
|
+
relayUrl: typeof cfg?.relayUrl === "string" ? cfg.relayUrl : "",
|
|
672
|
+
channel: typeof cfg?.channel === "string" ? cfg.channel : "",
|
|
673
|
+
hidden: cfg?.hidden === true,
|
|
674
|
+
qrSvg: "",
|
|
675
|
+
note: typeof note === "string" ? note : "",
|
|
676
|
+
/** v1.1.1:中继进程托管状态(设置页展示;老客户端忽略即可)。 */
|
|
677
|
+
relayProcess: null,
|
|
678
|
+
/**
|
|
679
|
+
* v1.1.3:中继令牌**是否已设置**(**没有明文**——令牌会出现在 transport hello 里,
|
|
680
|
+
* 明文回显等于把门口钥匙挂墙上)。设置页据此显示「已设置 / 未设置」。
|
|
681
|
+
*/
|
|
682
|
+
relayTokenSet: typeof cfg?.relayToken === "string" && cfg.relayToken.length > 0,
|
|
683
|
+
};
|
|
684
|
+
if (!withQr || value.hidden) return value;
|
|
685
|
+
try {
|
|
686
|
+
const rendered = renderPairing(buildPairingUri(cfg));
|
|
687
|
+
value.qrSvg = rendered.svg;
|
|
688
|
+
// 落盘一份(供外部工具/备份使用);失败不致命——设置页直接用内联 SVG。
|
|
689
|
+
try {
|
|
690
|
+
writePairingSvg(rendered.svg);
|
|
691
|
+
} catch {
|
|
692
|
+
/* ignore */
|
|
693
|
+
}
|
|
694
|
+
} catch (e) {
|
|
695
|
+
value.note = (value.note ? value.note + " " : "") + String(e && e.message);
|
|
696
|
+
}
|
|
697
|
+
return value;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* 给配对信息挂上**中继进程托管状态**(v1.1.1)。
|
|
702
|
+
*
|
|
703
|
+
* 设置页据此显示「中继进程:由插件托管 · 运行中(pid 1234)」之类的一行,
|
|
704
|
+
* 让用户知道中继是谁在管。快照取自 supervisor 的内存状态——不含任何敏感信息。
|
|
705
|
+
*
|
|
706
|
+
* @param {any} value pairingValue() 的结果
|
|
707
|
+
* @param {any} host 插件宿主状态
|
|
708
|
+
* @returns {any} 同一个 value(就地补字段)
|
|
709
|
+
*/
|
|
710
|
+
function withRelayProcess(value, host) {
|
|
711
|
+
const snap = host?.relayProcess;
|
|
712
|
+
value.relayProcess = {
|
|
713
|
+
/** 是否由插件托管(配置允许 + relayUrl 指向本机 + 找到中继程序)。 */
|
|
714
|
+
managed: snap?.managed === true,
|
|
715
|
+
/** 中继是否在跑(托管的子进程活着,或端口上已有服务)。 */
|
|
716
|
+
running: snap?.running === true,
|
|
717
|
+
/** 托管子进程 pid(未运行时 0)。 */
|
|
718
|
+
pid: typeof snap?.pid === "number" ? snap.pid : 0,
|
|
719
|
+
/** 监听端口(未托管时 0)。 */
|
|
720
|
+
port: typeof snap?.port === "number" ? snap.port : 0,
|
|
721
|
+
/** 人类可读的一句话状态。 */
|
|
722
|
+
detail: typeof snap?.detail === "string" ? snap.detail : "",
|
|
723
|
+
/** 端口上是不是**别人**的服务(N11:不透传的话设置页无法区分「外部中继」)。 */
|
|
724
|
+
external: snap?.external === true,
|
|
725
|
+
/** 状态原因(not-configured/disabled/remote/no-entry/external/managed)。 */
|
|
726
|
+
reason: typeof snap?.reason === "string" ? snap.reason : "",
|
|
727
|
+
};
|
|
728
|
+
return value;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
export default RemoteControlService;
|