dsh-mini-remote 0.1.0 → 0.1.3

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/client/verify.mjs DELETED
@@ -1,514 +0,0 @@
1
- // client/verify.mjs —— 手工验证 client/client.js 是否真的能用(零依赖、不需要测试框架)。
2
- //
3
- // 用法:node client/verify.mjs
4
- //
5
- // 做四件事:
6
- // 1. 伪造 window.__ModuleLoader__,把整个文件 eval 一遍,确认模块外壳被注册;
7
- // 2. 用 React 替身调用 factory,检查 exports(name / inject / apply);
8
- // 3. 用假的 ctx 调 apply,检查注册进 settings.section 的 def 和组件;
9
- // 4. 用替身 React 真渲染一遍组件:加载中 → ok:false → ok:true → 网络错误,
10
- // 并点一次「复制」按钮,确认文案临时变成「已复制」。
11
-
12
- import { readFileSync } from 'node:fs';
13
- import { dirname, join } from 'node:path';
14
- import { fileURLToPath } from 'node:url';
15
- import assert from 'node:assert/strict';
16
-
17
- const here = dirname(fileURLToPath(import.meta.url));
18
- const source = readFileSync(join(here, 'client.js'), 'utf8');
19
-
20
- // ---------------------------------------------------------------- 小工具
21
-
22
- const tick = () => new Promise((resolve) => setImmediate(resolve));
23
-
24
- const setGlobal = (name, value) =>
25
- Object.defineProperty(globalThis, name, { value, configurable: true, writable: true });
26
-
27
- /** 把渲染树摊平成纯文本,用来断言界面上出现了哪些字。 */
28
- function textOf(node) {
29
- if (node === null || node === undefined || typeof node === 'boolean') return '';
30
- if (typeof node === 'string' || typeof node === 'number') return String(node);
31
- if (Array.isArray(node)) return node.map(textOf).join(' ');
32
- return textOf(node.children);
33
- }
34
-
35
- /** 收集渲染树里所有元素节点(深度优先)。 */
36
- function walk(node, out = []) {
37
- if (node === null || node === undefined || typeof node !== 'object') return out;
38
- if (Array.isArray(node)) {
39
- for (const child of node) walk(child, out);
40
- return out;
41
- }
42
- out.push(node);
43
- walk(node.children, out);
44
- return out;
45
- }
46
-
47
- const byType = (tree, type) => walk(tree).filter((node) => node.type === type);
48
-
49
- /**
50
- * 最小 React 替身 + 最小渲染循环。
51
- * createElement 返回普通对象;useState 真的能改状态并触发重渲染;
52
- * useEffect 不在渲染时执行,由 runEffects() 显式跑一次(和 React 一致)。
53
- */
54
- function createHarness() {
55
- const cells = [];
56
- let cursor = 0;
57
- let pending = [];
58
- let cleanups = [];
59
- let onUpdate = null;
60
-
61
- const React = {
62
- createElement(type, props, ...children) {
63
- return { type, props: props || {}, children };
64
- },
65
- useState(initial) {
66
- const i = cursor++;
67
- if (i >= cells.length) cells.push(typeof initial === 'function' ? initial() : initial);
68
- const set = (next) => {
69
- cells[i] = typeof next === 'function' ? next(cells[i]) : next;
70
- if (onUpdate) onUpdate();
71
- };
72
- return [cells[i], set];
73
- },
74
- useEffect(fn) { pending.push(fn); },
75
- useRef(initial) { return { current: initial }; },
76
- };
77
-
78
- return {
79
- React,
80
- /** 渲染一次;重渲染会丢掉上一次登记的 effect(等价于依赖数组没变时不重跑)。 */
81
- draw(Comp) { cursor = 0; pending = []; return Comp({}); },
82
- runEffects() {
83
- const fns = pending;
84
- pending = [];
85
- for (const fn of fns) {
86
- const dispose = fn();
87
- if (typeof dispose === 'function') cleanups.push(dispose);
88
- }
89
- },
90
- unmount() { for (const dispose of cleanups) dispose(); cleanups = []; },
91
- onUpdate(fn) { onUpdate = fn; },
92
- };
93
- }
94
-
95
- /**
96
- * 组件在 factory 里就把 React.useState/useEffect 绑进了工厂闭包,所以替身必须是
97
- * 一个稳定的门面对象,内部转发给「当前这一套状态」——否则第二套 harness 永远不生效。
98
- */
99
- let active = null;
100
- const ReactFacade = {
101
- createElement: (type, props, ...children) => active.React.createElement(type, props, ...children),
102
- useState: (initial) => active.React.useState(initial),
103
- useEffect: (fn) => active.React.useEffect(fn),
104
- useRef: (initial) => active.React.useRef(initial),
105
- };
106
-
107
- /** 新建一套状态单元并设为当前(每个渲染用例一套,互不干扰)。 */
108
- function useHarness() {
109
- active = createHarness();
110
- return active;
111
- }
112
-
113
- /** 假的 fetch 响应。 */
114
- const jsonResponse = (status, body) => ({
115
- status,
116
- json: async () => body,
117
- });
118
-
119
- // ---------------------------------------------------------------- 断言运行器
120
-
121
- let passed = 0;
122
- const failures = [];
123
-
124
- async function check(label, fn) {
125
- try {
126
- await fn();
127
- passed += 1;
128
- console.log(` ✓ ${label}`);
129
- } catch (err) {
130
- failures.push({ label, err });
131
- console.log(` ✗ ${label}`);
132
- console.log(` ${err && err.message ? err.message : err}`);
133
- }
134
- }
135
-
136
- // ---------------------------------------------------------------- 1. 模块外壳
137
-
138
- let captured = null;
139
- setGlobal('window', { __ModuleLoader__: { load: (registration) => { captured = registration; } } });
140
- (0, eval)(source); // 间接 eval:在全局作用域执行,模拟浏览器加载这个脚本
141
-
142
- console.log('\n[1] 模块外壳 window.__ModuleLoader__.load');
143
-
144
- await check('文件执行后捕获到一次注册', () => {
145
- assert.ok(captured, '没有调用 window.__ModuleLoader__.load');
146
- });
147
- await check('id === "dsh-mini-remote"', () => {
148
- assert.equal(captured.id, 'dsh-mini-remote');
149
- });
150
- await check('factory 是函数', () => {
151
- assert.equal(typeof captured.factory, 'function');
152
- });
153
-
154
- // ---------------------------------------------------------------- 2. factory / exports
155
-
156
- const harness = useHarness();
157
- const required = [];
158
- const fakeRequire = (spec) => {
159
- required.push(spec);
160
- if (spec === 'react') return ReactFacade;
161
- throw new Error(`客户端模块只允许 require("react"),实际请求了 "${spec}"`);
162
- };
163
-
164
- let mod = null;
165
- console.log('\n[2] factory(require) 的返回值');
166
- await check('factory 不抛错并返回 exports', () => {
167
- mod = captured.factory(fakeRequire);
168
- assert.ok(mod && typeof mod === 'object');
169
- });
170
- await check('只 require 了 react(零运行时依赖)', () => {
171
- assert.deepEqual(required, ['react']);
172
- });
173
- await check('exports.name === "dsh-mini-remote"', () => {
174
- assert.equal(mod.name, 'dsh-mini-remote');
175
- });
176
- await check("exports.inject 深等于 ['slots']", () => {
177
- assert.deepEqual(mod.inject, ['slots']);
178
- });
179
- await check('exports.apply 是函数', () => {
180
- assert.equal(typeof mod.apply, 'function');
181
- });
182
-
183
- // ---------------------------------------------------------------- 3. apply / slots 注册
184
-
185
- const injected = [];
186
- const registered = [];
187
- const fakeCtx = {
188
- slots: {
189
- inject(name, callback) { injected.push(name); return callback(); },
190
- register(def, Comp) { registered.push({ def, Comp }); return () => {}; },
191
- },
192
- };
193
-
194
- let Comp = null;
195
- let def = null;
196
- console.log('\n[3] apply(ctx) 的 slots 注册');
197
- await check('apply(fakeCtx) 不抛错', () => {
198
- assert.doesNotThrow(() => mod.apply(fakeCtx));
199
- });
200
- await check('inject 的服务名是 "settings.section"', () => {
201
- assert.deepEqual(injected, ['settings.section']);
202
- });
203
- await check('register 只调用了一次', () => {
204
- assert.equal(registered.length, 1);
205
- });
206
- await check('def.name === "settings.section"', () => {
207
- def = registered[0].def;
208
- assert.equal(def.name, 'settings.section');
209
- });
210
- await check('def.id === "mini-remote"', () => {
211
- assert.equal(def.id, 'mini-remote');
212
- });
213
- await check('def.order === 2', () => {
214
- assert.equal(def.order, 2);
215
- });
216
- await check('def.label 是函数(typeof === "function")', () => {
217
- assert.equal(typeof def.label, 'function');
218
- });
219
- await check('def.label() === "手机遥控"', () => {
220
- assert.equal(def.label(), '手机遥控');
221
- });
222
- await check('第二个参数是组件函数', () => {
223
- Comp = registered[0].Comp;
224
- assert.equal(typeof Comp, 'function');
225
- });
226
-
227
- // ---------------------------------------------------------------- 4. 渲染组件
228
-
229
- const TOKEN = '0123456789abcdef0123456789abcdef';
230
- const URL_LAN = `http://192.168.1.2:3090/mini?token=${TOKEN}`;
231
- const URL_TS = `http://100.92.105.99:3090/mini?token=${TOKEN}`;
232
- const QR = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
233
-
234
- console.log('\n[4] 组件渲染');
235
-
236
- // 4a. 加载中
237
- let resolveFetch = null;
238
- setGlobal('fetch', () => new Promise((resolve) => { resolveFetch = resolve; }));
239
- {
240
- const h4 = useHarness();
241
- let tree = null;
242
- h4.onUpdate(() => { tree = h4.draw(Comp); });
243
- await check('挂载时不抛错,并显示「正在读取配对信息…」', () => {
244
- tree = h4.draw(Comp);
245
- assert.notEqual(tree, undefined);
246
- assert.match(textOf(tree), /正在读取配对信息…/);
247
- });
248
- await check('useEffect 里发起了同源 GET /mini-remote/pairing', () => {
249
- h4.runEffects();
250
- assert.equal(typeof resolveFetch, 'function', 'useEffect 里没有发起 fetch');
251
- });
252
- await check('顶部两句说明都在', () => {
253
- const text = textOf(tree);
254
- assert.match(text, /手机扫码就能用,不用输密码——密码已经编在二维码里了。/);
255
- assert.match(text, /这个页面带着密码,别截图发出去。/);
256
- });
257
- await check('HTTP 403 + {ok:false,error} → 显示 error 原文', async () => {
258
- resolveFetch(jsonResponse(403, { ok: false, error: '配对信息只能在这台电脑上看。' }));
259
- await tick();
260
- assert.match(textOf(tree), /配对信息只能在这台电脑上看。/);
261
- assert.doesNotMatch(textOf(tree), /正在读取配对信息…/);
262
- });
263
- }
264
-
265
- // 4b. 网络错误(fetch 直接失败)
266
- {
267
- const h4 = useHarness();
268
- setGlobal('fetch', () => Promise.reject(new Error('Failed to fetch')));
269
- let tree = null;
270
- h4.onUpdate(() => { tree = h4.draw(Comp); });
271
- await check('网络错误 → 显示失败原因,不吞掉', async () => {
272
- tree = h4.draw(Comp);
273
- h4.runEffects();
274
- await tick();
275
- assert.match(textOf(tree), /连不上这台电脑上的遥控服务:Failed to fetch/);
276
- });
277
- }
278
-
279
- // 4c. 成功:两条 entry(第二条没有二维码)
280
- {
281
- const h4 = useHarness();
282
- setGlobal('fetch', async () => jsonResponse(200, {
283
- ok: true,
284
- port: 3090,
285
- token: TOKEN,
286
- entries: [
287
- { kind: 'lan', label: '内网', hint: '手机连同一个 Wi-Fi 时用这个', url: URL_LAN, qr: QR },
288
- { kind: 'tailscale', label: 'Tailscale', hint: '在外面也能用', url: URL_TS, qr: null },
289
- ],
290
- }));
291
- let tree = null;
292
- h4.onUpdate(() => { tree = h4.draw(Comp); });
293
-
294
- await check('ok:true 时渲染两块 entry(label + hint)', async () => {
295
- tree = h4.draw(Comp);
296
- h4.runEffects();
297
- await tick();
298
- const text = textOf(tree);
299
- assert.match(text, /内网/);
300
- assert.match(text, /手机连同一个 Wi-Fi 时用这个/);
301
- assert.match(text, /Tailscale/);
302
- assert.match(text, /在外面也能用/);
303
- assert.doesNotMatch(text, /正在读取配对信息…/);
304
- });
305
-
306
- await check('二维码渲染成 <img src={entry.qr}>(宽 180)', () => {
307
- const imgs = byType(tree, 'img');
308
- assert.equal(imgs.length, 1, '有 qr 的只有一条,qr:null 的那条应退化成文字');
309
- assert.equal(imgs[0].props.src, QR);
310
- assert.equal(imgs[0].props.style.width, 180);
311
- });
312
-
313
- await check('两条 URL 都在只读 <input> 里,不是纯文本 div', () => {
314
- // 按内容找,不按位置也不数总数:面板上还有别的输入框(密码、改密码那两处),
315
- // 数总数的话,每加一个输入框这里都要误报一次。
316
- const urls = byType(tree, 'input').filter((n) => n.props.value === URL_LAN || n.props.value === URL_TS);
317
- assert.equal(urls.length, 2);
318
- assert.equal(urls[0].props.readOnly, true);
319
- assert.equal(urls[1].props.readOnly, true);
320
- });
321
-
322
- await check('点输入框会全选地址', () => {
323
- let selected = false;
324
- const lan = byType(tree, 'input').find((n) => n.props.value === URL_LAN);
325
- lan.props.onFocus({ target: { select() { selected = true; } } });
326
- assert.equal(selected, true);
327
- });
328
-
329
- await check('qr 为 null 时退化成文字,界面不崩', () => {
330
- assert.match(textOf(tree), /二维码没画出来/);
331
- });
332
-
333
- await check('每条链接各有一个「复制」按钮,初始文案是「复制」', () => {
334
- // 同样按文案找,不数总数:密码那一块也有「复制」。
335
- const copies = byType(tree, 'button').filter((b) => textOf(b) === '复制');
336
- assert.ok(copies.length >= 2, '两条链接各要有一个「复制」按钮');
337
- assert.equal(textOf(copies[0]), '复制');
338
- assert.equal(textOf(copies[1]), '复制');
339
- });
340
-
341
- // 2026-09-22 用户报:「手机遥控页面里似乎根本没有密码,也无法自定义密码」。
342
- // 配对接口一直返回着 token,只是没人渲染它——这三项钉住它真的露出来了。
343
- await check('密码默认打码显示,不是明文', () => {
344
- const masked = TOKEN.replace(/./g, '•');
345
- const pw = byType(tree, 'input').find((n) => n.props.value === masked);
346
- assert.ok(pw, '默认该显示打码后的密码');
347
- assert.equal(pw.props.readOnly, true, '密码框只能看,不能改——改要走保存那条路');
348
- assert.ok(!byType(tree, 'input').some((n) => n.props.value === TOKEN), '没点「显示」之前不该出现明文');
349
- });
350
-
351
- await check('点「显示」→ 明文,再点「藏起来」→ 又打码', async () => {
352
- const masked = TOKEN.replace(/./g, '•');
353
- const showBtn = byType(tree, 'button').find((b) => textOf(b) === '显示');
354
- assert.ok(showBtn, '要有一个「显示」按钮');
355
- showBtn.props.onClick();
356
- await tick();
357
- tree = h4.draw(Comp);
358
- assert.ok(byType(tree, 'input').some((n) => n.props.value === TOKEN), '点过之后应显示明文');
359
- const hideBtn = byType(tree, 'button').find((b) => textOf(b) === '藏起来');
360
- assert.ok(hideBtn, '显示之后按钮该变成「藏起来」');
361
- hideBtn.props.onClick();
362
- await tick();
363
- tree = h4.draw(Comp);
364
- assert.ok(byType(tree, 'input').some((n) => n.props.value === masked), '再点一次该变回打码');
365
- });
366
-
367
- await check('点密码旁边的「复制」→ 复制的是密码本身', async () => {
368
- const written = [];
369
- setGlobal('navigator', { clipboard: { writeText: async (text) => { written.push(text); } } });
370
- // 链接那两个「复制」在前,密码那个在最后
371
- const copies = byType(tree, 'button').filter((b) => textOf(b) === '复制');
372
- copies[copies.length - 1].props.onClick();
373
- await tick();
374
- assert.deepEqual(written, [TOKEN]);
375
- });
376
-
377
- await check('点「复制」→ navigator.clipboard.writeText(url),文案变「已复制」', async () => {
378
- const written = [];
379
- setGlobal('navigator', { clipboard: { writeText: async (text) => { written.push(text); } } });
380
- byType(tree, 'button')[0].props.onClick();
381
- await tick();
382
- assert.deepEqual(written, [URL_LAN]);
383
- const buttons = byType(tree, 'button');
384
- assert.equal(textOf(buttons[0]), '已复制');
385
- assert.equal(textOf(buttons[1]), '复制', '只改被点的那一个');
386
- });
387
-
388
- await check('复制失败时不谎报「已复制」', async () => {
389
- const h5 = useHarness();
390
- let tree5 = null;
391
- h5.onUpdate(() => { tree5 = h5.draw(Comp); });
392
- tree5 = h5.draw(Comp);
393
- h5.runEffects();
394
- await tick();
395
- setGlobal('navigator', { clipboard: { writeText: async () => { throw new Error('NotAllowedError'); } } });
396
- byType(tree5, 'button')[0].props.onClick();
397
- await tick();
398
- assert.equal(textOf(byType(tree5, 'button')[0]), '复制');
399
- });
400
- }
401
-
402
- // 4d. 公网访问:开关、状态、报错、以及 ok:false 时也要能关掉它
403
- {
404
- const withTunnel = (tunnel, extra) => Object.assign({
405
- ok: true,
406
- port: 3090,
407
- token: TOKEN,
408
- entries: [{ kind: 'lan', label: '内网', hint: '手机连同一个 Wi-Fi 时用这个', url: URL_LAN, qr: QR }],
409
- tunnel,
410
- }, extra || {});
411
-
412
- const h6 = useHarness();
413
- let tree6 = null;
414
- let posted = [];
415
- h6.onUpdate(() => { tree6 = h6.draw(Comp); });
416
-
417
- const mount = async (payload) => {
418
- setGlobal('fetch', async (url, init) => {
419
- if (init && init.method === 'POST') {
420
- posted.push({ url, body: JSON.parse(init.body) });
421
- return jsonResponse(200, withTunnel({ enabled: JSON.parse(init.body).enabled, up: false, starting: false, error: null }));
422
- }
423
- return jsonResponse(200, payload);
424
- });
425
- tree6 = h6.draw(Comp);
426
- h6.runEffects();
427
- await tick();
428
- };
429
-
430
- await check('公网没开时:开关是未选中的,并且说明「出门进不来」', async () => {
431
- await mount(withTunnel({ enabled: false, up: false, starting: false, error: null }));
432
- const boxes = byType(tree6, 'input').filter((n) => n.props.type === 'checkbox');
433
- assert.equal(boxes.length, 1, '要有一个公网开关');
434
- assert.equal(boxes[0].props.checked, false);
435
- const text = textOf(tree6);
436
- assert.match(text, /公网访问/);
437
- assert.match(text, /手机不连家里 Wi-Fi 的时候就进不来/);
438
- });
439
-
440
- await check('公网开着且有地址时:开关选中,提示去看「公网」那条', async () => {
441
- await mount(withTunnel({ enabled: true, up: true, starting: false, error: null }));
442
- const boxes = byType(tree6, 'input').filter((n) => n.props.type === 'checkbox');
443
- assert.equal(boxes[0].props.checked, true);
444
- const text = textOf(tree6);
445
- assert.match(text, /上面那条「公网」/);
446
- assert.match(text, /每次重启 DSH 都会换一个/, '要提前说清楚地址会变');
447
- assert.match(text, /挂在公网上/, '开了要提醒它现在暴露在公网');
448
- });
449
-
450
- await check('公网开着但连不上时:原文报错照登,不吞掉', async () => {
451
- await mount(withTunnel({ enabled: true, up: false, starting: false, error: '所有下载源都没成功:\n github.com — 超时' }));
452
- const text = textOf(tree6);
453
- assert.match(text, /开着,但公网那边连不上/, '要让用户知道这条路现在是死的');
454
- assert.match(text, /所有下载源都没成功/, '底层原因要透出来,否则没法排查');
455
- assert.match(text, /github\.com — 超时/);
456
- });
457
-
458
- // 2026-09-22 用户照着一个写着「已开启」的面板去扫码,扫出来是 Cloudflare 的 Error 1033。
459
- // 这两种情况必须分开说:**还在等地址**和**地址拿到过、后来断了**,用户的下一步动作不同。
460
- await check('公网开着、没有报错时:说的是「还没拿到地址」,不是「连不上」', async () => {
461
- await mount(withTunnel({ enabled: true, up: false, starting: false, error: null }));
462
- const text = textOf(tree6);
463
- assert.match(text, /已开启,但还没拿到公网地址/);
464
- assert.doesNotMatch(text, /公网那边连不上/, '还没报错就不该先吓唬人');
465
- });
466
-
467
- await check('正在打开时:开关禁用,避免连点起出好几条隧道', async () => {
468
- await mount(withTunnel({ enabled: true, up: false, starting: true, error: null }));
469
- const boxes = byType(tree6, 'input').filter((n) => n.props.type === 'checkbox');
470
- assert.equal(boxes[0].props.disabled, true);
471
- assert.match(textOf(tree6), /正在打开/);
472
- });
473
-
474
- await check('勾上开关 → POST /mini-remote/tunnel,body 是 {enabled:true}', async () => {
475
- posted = [];
476
- await mount(withTunnel({ enabled: false, up: false, starting: false, error: null }));
477
- const box = byType(tree6, 'input').filter((n) => n.props.type === 'checkbox')[0];
478
- box.props.onChange({ target: { checked: true } });
479
- await tick();
480
- assert.equal(posted.length, 1, '只该发一次请求');
481
- assert.equal(posted[0].url, '/mini-remote/tunnel');
482
- assert.deepEqual(posted[0].body, { enabled: true });
483
- });
484
-
485
- await check('关掉开关 → body 是 {enabled:false}', async () => {
486
- posted = [];
487
- await mount(withTunnel({ enabled: true, up: true, starting: false, error: null }));
488
- const box = byType(tree6, 'input').filter((n) => n.props.type === 'checkbox')[0];
489
- box.props.onChange({ target: { checked: false } });
490
- await tick();
491
- assert.equal(posted.length, 1);
492
- assert.deepEqual(posted[0].body, { enabled: false });
493
- });
494
-
495
- await check('整块面板报错时,公网开关仍然露得出来', async () => {
496
- // 否则「隧道起不来」会把面板变成一条报错,用户连关掉它的地方都找不到
497
- await mount(withTunnel(
498
- { enabled: true, up: false, starting: false, error: '找不到 cloudflared' },
499
- { ok: false, error: '公网访问没起来:找不到 cloudflared', entries: undefined },
500
- ));
501
- const boxes = byType(tree6, 'input').filter((n) => n.props.type === 'checkbox');
502
- assert.equal(boxes.length, 1, '报错时也得能点得动开关');
503
- assert.equal(boxes[0].props.checked, true);
504
- assert.match(textOf(tree6), /公网访问没起来/);
505
- });
506
- }
507
-
508
- // ---------------------------------------------------------------- 结果
509
-
510
- console.log(`\n通过 ${passed} 项,失败 ${failures.length} 项。`);
511
- if (failures.length) {
512
- for (const { label, err } of failures) console.log(` ✗ ${label}: ${err && err.stack ? err.stack : err}`);
513
- process.exitCode = 1;
514
- }