@mrrisega/dsh-remote 0.6.3 → 0.6.4-beta.10

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote-web",
3
- "version": "0.6.3",
3
+ "version": "0.6.4-beta.10",
4
4
  "description": "公网远程控制 DeepSeek Harness(dsh web):安装即得专属加密地址,人在外面也能用手机访问电脑上的 dsh——无需同一局域网/WiFi、无需公网 IP 与内网穿透,全程加密;手机端 100% 还原电脑体验(对话/工具/审批/设置)。技术用户可选自建服务,流量走自己的服务器。Remote control DeepSeek Harness (dsh web) from anywhere over the public internet — install, get an encrypted URL, use it from your phone on any network (dual-half cordis plugin: Settings panel + same-origin /dsh-remote routes). (2026-09 由 dsh-remote-ui 更名 / renamed from dsh-remote-ui; dsh-remote 的 dsh web 插件半,不是纯 UI/皮肤插件)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -0,0 +1,303 @@
1
+ // 【自动化】「自动重启 dsh web」的安全回归(浏览器半,0.6.4)。
2
+ //
3
+ // 目标:**确实需要重启时**,用户不必自己点按钮 —— 面板发现待重启后自己倒计时重启,重启后自动恢复页面
4
+ // (复用既有 restartHarness + waitHarnessBack:轮询到 harness 回来即自动刷新)。
5
+ //
6
+ // ⚠️ 0.6.4-beta.9 起:kind="refresh"(插件被运行时改写 → 只需刷新页面)**不再自动重启**,
7
+ // 因为刷新是零风险动作、重启会打断用户正在进行的会话。因此本用例用 kind="update"
8
+ // (非 refresh)来构造"确实需要重启"的场景,以覆盖倒计时链路。
9
+ // 但「自动重启进程」是危险动作,本用例锁死四条安全阀:
10
+ // ① 只在面板可见时计时(用户没在看就不动);
11
+ // ② 15 秒倒计时内可一键取消,取消标记按本次事件(restart.at)持久化,同一事件不再自动重启;
12
+ // ③ 面板上有其他操作在跑(busy≠"")时暂停计时,不打断用户正在做的事;
13
+ // ④ 只重启一次(重启后 pending 结清即停);无待重启时一个请求都不发。
14
+ import assert from "node:assert/strict";
15
+ import { readFileSync } from "node:fs";
16
+ import test from "node:test";
17
+ import vm from "node:vm";
18
+
19
+ const SOURCE = readFileSync(new URL("../lib/client.js", import.meta.url), "utf8");
20
+
21
+ function walk(node, visit) {
22
+ if (node == null) return;
23
+ if (Array.isArray(node)) { for (const item of node) walk(item, visit); return; }
24
+ if (typeof node !== "object") return;
25
+ visit(node);
26
+ for (const child of node.children || []) walk(child, visit);
27
+ }
28
+ function find(tree, predicate) {
29
+ let match;
30
+ walk(tree, (node) => { if (!match && predicate(node)) match = node; });
31
+ return match;
32
+ }
33
+ function textHas(tree, substr) {
34
+ return !!find(tree, (node) => (node.children || []).some((c) => typeof c === "string" && c.includes(substr)));
35
+ }
36
+ function nodeWithText(tree, substr) {
37
+ return find(tree, (node) => typeof node.props?.onClick === "function" && (node.children || []).some((c) => typeof c === "string" && c.includes(substr)));
38
+ }
39
+
40
+ const flush = () => new Promise((resolve) => setImmediate(resolve));
41
+
42
+ const NOT_LOGGED = { ok: true, config: { phone: "", hasPhone: false, mode: "saas", deviceId: "" }, service: { running: false }, remoteUrl: "https://app.test/" };
43
+ const LOGGED = { ok: true, config: { phone: "138****0000", hasPhone: true, mode: "saas", deviceId: "dev-x" }, service: { running: true }, remoteUrl: "https://app.test/" };
44
+ const KEY_URL = "https://app.test/a/K1";
45
+ const SESSIONS = [{ id: "ms_1", label: "iPhone 15", os: "iOS", browser: "Safari", created_at: 1700000000000, last_seen_at: 1700000600000, revoked_at: null }];
46
+ function statusWithRestart(pending, at) {
47
+ // kind 用 "update"(非 refresh):只有这一路才走自动重启倒计时;
48
+ // kind="refresh" 的面板只提示刷新页面(见 harness-restart.test.mjs)。
49
+ return Object.assign({}, LOGGED, { restart: { pending: !!pending, kind: "update", reason: "需要重启 dsh web 才能载入新插件", at: at || 0 } });
50
+ }
51
+
52
+ function loadPlugin(opts = {}) {
53
+ let moduleFactory;
54
+ const registered = new Map();
55
+ const injects = new Map();
56
+ const requests = [];
57
+ const clipboard = [];
58
+ const states = [];
59
+ let hook = 0;
60
+ let effectCursor = 0;
61
+ let effectSlots = [];
62
+ let pending = [];
63
+ const listeners = new Map();
64
+
65
+ let clock = 0;
66
+ let timerSeq = 1;
67
+ const timers = new Map();
68
+ const job = (fn) => { try { fn(); } catch (e) { /* 内部错误由断言暴露 */ } };
69
+ const fakeSetTimeout = (fn, ms) => { const id = timerSeq++; timers.set(id, { at: clock + (Number(ms) || 0), fn, every: 0 }); return id; };
70
+ const fakeSetInterval = (fn, ms) => { const id = timerSeq++; const every = Math.max(1, Number(ms) || 1); timers.set(id, { at: clock + every, fn, every }); return id; };
71
+ const fakeClear = (id) => { timers.delete(id); };
72
+ async function advance(ms) {
73
+ const target = clock + ms;
74
+ for (let guard = 0; guard < 2000; guard++) {
75
+ let due = null;
76
+ for (const [id, t] of timers) if (t.at <= target && (!due || t.at < due[1].at)) due = [id, t];
77
+ if (!due) break;
78
+ const [id, t] = due;
79
+ clock = t.at;
80
+ if (t.every) t.at = clock + t.every; else timers.delete(id);
81
+ job(t.fn);
82
+ await flush();
83
+ }
84
+ clock = target;
85
+ await flush(); await flush();
86
+ }
87
+
88
+ const react = {
89
+ createElement(type, props, ...children) { return { type, props: props || {}, children }; },
90
+ useState(initial) {
91
+ const index = hook++;
92
+ if (!(index in states)) states[index] = typeof initial === "function" ? initial() : initial;
93
+ return [states[index], (value) => { states[index] = typeof value === "function" ? value(states[index]) : value; }];
94
+ },
95
+ useEffect(fn, deps) {
96
+ const index = effectCursor++;
97
+ const prev = effectSlots[index];
98
+ const changed = !prev || !deps || deps.length !== prev.deps.length || deps.some((d, i) => !Object.is(d, prev.deps[i]));
99
+ if (changed) pending.push({ index, fn, deps: deps ? [...deps] : deps });
100
+ },
101
+ useCallback(fn) { return fn; },
102
+ useSyncExternalStore(_subscribe, getSnapshot) { return getSnapshot(); },
103
+ };
104
+
105
+ const response = (status, body) => Promise.resolve({
106
+ ok: status >= 200 && status < 300,
107
+ status,
108
+ text: async () => JSON.stringify(body),
109
+ });
110
+
111
+ let statusBody = opts.status || NOT_LOGGED;
112
+ let restartCalls = 0;
113
+ const connBody = null;
114
+ let connCalls = 0;
115
+ let keyCalls = 0;
116
+ let sessCalls = 0;
117
+
118
+ const makeEl = () => ({
119
+ tag: "div", children: [], style: {}, className: "", attributes: {}, textContent: "",
120
+ setAttribute(k, v) { this.attributes[k] = v; },
121
+ getAttribute(k) { return this.attributes[k] ?? null; },
122
+ appendChild(c) { this.children.push(c); },
123
+ addEventListener(type, fn) { if (!listeners.has(type)) listeners.set(type, []); listeners.get(type).push(fn); },
124
+ removeEventListener(type, fn) {
125
+ const list = listeners.get(type) || [];
126
+ const i = list.indexOf(fn);
127
+ if (i >= 0) list.splice(i, 1);
128
+ },
129
+ });
130
+ const doc = {
131
+ hidden: false,
132
+ createElement: makeEl,
133
+ head: makeEl(),
134
+ body: makeEl(),
135
+ querySelector() { return null; },
136
+ querySelectorAll() { return []; },
137
+ getElementById() { return null; },
138
+ addEventListener(type, fn) { if (!listeners.has(type)) listeners.set(type, []); listeners.get(type).push(fn); },
139
+ removeEventListener(type, fn) {
140
+ const list = listeners.get(type) || [];
141
+ const i = list.indexOf(fn);
142
+ if (i >= 0) list.splice(i, 1);
143
+ },
144
+ };
145
+ class MutationObserverMock { constructor() {} observe() {} disconnect() {} }
146
+ const localStorage = {
147
+ // 支持预置存储(验证「取消标记跨刷新生效」:getItem 走真实读取路径)
148
+ _s: new Map(Object.entries(opts.localStorage || {})),
149
+ getItem(k) { return this._s.has(k) ? this._s.get(k) : null; },
150
+ setItem(k, v) { this._s.set(k, String(v)); },
151
+ removeItem(k) { this._s.delete(k); },
152
+ };
153
+
154
+ const sandbox = {
155
+ window: { __ModuleLoader__: { load(spec) { moduleFactory = spec.factory; } }, open() { return null; } },
156
+ document: doc,
157
+ localStorage,
158
+ MutationObserver: MutationObserverMock,
159
+ navigator: { clipboard: { writeText: async (t) => { clipboard.push(String(t)); } } },
160
+ setTimeout: fakeSetTimeout,
161
+ clearTimeout: fakeClear,
162
+ setInterval: fakeSetInterval,
163
+ clearInterval: fakeClear,
164
+ fetch(path, options = {}) {
165
+ requests.push({ path, method: options.method || "GET", body: options.body ? JSON.parse(options.body) : null });
166
+ if (path === "/dsh-remote/status") return response(200, statusBody);
167
+ if (path === "/dsh-remote/bridge-status") { connCalls += 1; return response(200, { ok: true }); }
168
+ if (path === "/dsh-remote/harness/restart") {
169
+ restartCalls += 1;
170
+ // 重启后 harness 会带着新的 bootId 回来:模拟「待重启已结清」
171
+ statusBody = Object.assign({}, statusBody, { restart: { pending: false, kind: "", reason: "", at: statusBody.restart?.at || 0 } });
172
+ return response(200, Object.assign({}, statusBody, { ok: true, mode: "launchd" }));
173
+ }
174
+ if (path === "/dsh-remote/access-key") {
175
+ keyCalls += 1;
176
+ return response(200, { ok: true, url: KEY_URL, key: "K1", expires_at: Date.now() + 1800000, ttl_ms: 1800000, qr_data_url: "data:image/png;base64,AAAA" });
177
+ }
178
+ if (path === "/dsh-remote/mobile-sessions") {
179
+ sessCalls += 1;
180
+ return response(200, { ok: true, sessions: opts.sessions || SESSIONS });
181
+ }
182
+ if (path === "/dsh-remote/captcha") return response(200, { captcha_id: "cap-1", svg: "<svg></svg>" });
183
+ if (path === "/dsh-remote/register") return response(201, { ok: true, token: "jwt-reg" });
184
+ if (path === "/dsh-remote/config") return response(200, statusBody);
185
+ if (path === "/dsh-remote/account") return response(200, { ok: true, account: { phone: "138****0000", plan: "free", plan_source: "plan" } });
186
+ if (path === "/dsh-remote/quota") return response(200, { ok: true, quota: null });
187
+ if (path === "/dsh-remote/remote-url") return response(200, { ok: true, remoteUrl: "https://app.test/", publicConfig: {} });
188
+ return response(200, { ok: true });
189
+ },
190
+ Set, Symbol, Date, JSON, Math, Number, String, Object, Array, console,
191
+ };
192
+
193
+ vm.runInNewContext(SOURCE, sandbox);
194
+ const plugin = moduleFactory((name) => {
195
+ assert.equal(name, "react");
196
+ return react;
197
+ });
198
+ plugin.apply({
199
+ slots: {
200
+ inject(name, cb) { injects.set(name, cb); cb(); },
201
+ register(meta, component) { registered.set(meta.id, component); return () => {}; },
202
+ },
203
+ });
204
+
205
+ return {
206
+ requests, states, clipboard,
207
+ counts() { return { connCalls, keyCalls, sessCalls, restartCalls }; },
208
+ /** 改写状态响应(模拟 pending 被结清/用户取消后再次出现等)。 */
209
+ setStatus(body) { statusBody = body; },
210
+ /** 渲染一轮并执行本轮需要运行的 effects(含 cleanup)。 */
211
+ render() {
212
+ hook = 0; effectCursor = 0; pending = [];
213
+ const tree = registered.get("dsh-remote")({ close() {} });
214
+ const todos = pending; pending = [];
215
+ for (const t of todos) {
216
+ const prev = effectSlots[t.index];
217
+ if (prev && typeof prev.cleanup === "function") job(prev.cleanup);
218
+ const cleanup = t.fn();
219
+ effectSlots[t.index] = { deps: t.deps, cleanup: typeof cleanup === "function" ? cleanup : null };
220
+ }
221
+ return tree;
222
+ },
223
+ async settle(times = 3) {
224
+ for (let i = 0; i < times; i++) { this.render(); await flush(); await flush(); }
225
+ return this.render();
226
+ },
227
+ advance,
228
+ /** 登录成功(面板读到登录态)→ 登录态 effect 重跑,自动开始推进连接。 */
229
+ async login() {
230
+ statusBody = LOGGED;
231
+ await advance(30_000); // 等 30s 状态轮询把登录态带进面板
232
+ return this.settle();
233
+ },
234
+ /** 连接阶段推进(node 半短轮询的应答变化)。 */
235
+ setConnect(phase, extra) { connBody = connectPayload(phase, extra); },
236
+ setConnectRaw(body) { connBody = body; },
237
+ hide() { doc.hidden = true; },
238
+ show() { doc.hidden = false; for (const fn of listeners.get("visibilitychange") || []) job(fn); },
239
+ };
240
+ }
241
+
242
+
243
+
244
+ test("待重启 + 面板可见 → 15 秒后自动重启(用户零操作),重启后 pending 结清即停止", async () => {
245
+ const plugin = loadPlugin({ status: statusWithRestart(true, 1111) });
246
+ let tree = await plugin.settle();
247
+ assert.ok(textHas(tree, "需要重启 dsh web 才能载入新插件"), "应显示待重启横幅");
248
+ assert.ok(textHas(tree, "秒后自动重启"), "应显示自动重启倒计时文案");
249
+ assert.equal(plugin.counts().restartCalls, 0, "倒计时期间不得提前重启");
250
+
251
+ await plugin.advance(14000);
252
+ assert.equal(plugin.counts().restartCalls, 0, "14 秒时还没到点");
253
+ await plugin.advance(2000);
254
+ assert.equal(plugin.counts().restartCalls, 1, "15 秒到点应自动重启一次");
255
+
256
+ tree = await plugin.settle();
257
+ assert.ok(!textHas(tree, "秒后自动重启"), "重启后不应残留倒计时");
258
+ await plugin.advance(60000);
259
+ assert.equal(plugin.counts().restartCalls, 1, "pending 结清后不得反复重启");
260
+ });
261
+
262
+ test("点「取消自动重启」→ 不再自动重启,且标记按事件持久化(刷新后仍不自动重启)", async () => {
263
+ const plugin = loadPlugin({ status: statusWithRestart(true, 2222) });
264
+ const tree = await plugin.settle();
265
+ const cancelBtn = nodeWithText(tree, "取消自动重启");
266
+ assert.ok(cancelBtn, "倒计时期间必须提供取消入口");
267
+ cancelBtn.props.onClick();
268
+ assert.ok(textHas(plugin.render(), "已取消自动重启"), "取消后应有明确反馈");
269
+
270
+ await plugin.advance(120000);
271
+ assert.equal(plugin.counts().restartCalls, 0, "取消后不得自动重启");
272
+
273
+ // 模拟用户刷新页面:同一 pending 事件(at=2222)仍不自动重启
274
+ const plugin2 = loadPlugin({ status: statusWithRestart(true, 2222), localStorage: { "dsh-remote-auto-restart-cancelled": "2222" } });
275
+ await plugin2.settle();
276
+ await plugin2.advance(120000);
277
+ assert.equal(plugin2.counts().restartCalls, 0, "刷新后仍尊重取消标记");
278
+
279
+ // 但下一次安装/更新(新的 at)应重新自动触发
280
+ const plugin3 = loadPlugin({ status: statusWithRestart(true, 3333), localStorage: { "dsh-remote-auto-restart-cancelled": "2222" } });
281
+ await plugin3.settle();
282
+ await plugin3.advance(16000);
283
+ assert.equal(plugin3.counts().restartCalls, 1, "新的待重启事件应重新自动重启");
284
+ });
285
+
286
+ test("面板不可见 → 倒计时暂停;回到前台继续", async () => {
287
+ const plugin = loadPlugin({ status: statusWithRestart(true, 4444) });
288
+ await plugin.settle();
289
+ plugin.hide();
290
+ await plugin.advance(60000);
291
+ assert.equal(plugin.counts().restartCalls, 0, "页面隐藏时绝不能在用户没看到的情况下重启进程");
292
+ plugin.show();
293
+ await plugin.advance(16000);
294
+ assert.equal(plugin.counts().restartCalls, 1, "回到前台应继续倒计时并最终重启");
295
+ });
296
+
297
+ test("无待重启 → 一个请求都不发;横幅不出现", async () => {
298
+ const plugin = loadPlugin({ status: LOGGED });
299
+ const tree = await plugin.settle();
300
+ await plugin.advance(60000);
301
+ assert.equal(plugin.counts().restartCalls, 0);
302
+ assert.ok(!textHas(tree, "自动重启"), "无待重启时不应出现自动重启文案");
303
+ });