@hao0311/dsh-toolbox 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js ADDED
@@ -0,0 +1,484 @@
1
+ /**
2
+ * dsh-toolbox — 注入式「工具箱」插件(宿主端)。
3
+ *
4
+ * 三件事:
5
+ * 1. 通过官方 webserver/index-inject 把 client.css / client.js 内联进 index.html;
6
+ * 2. 通过 ctx.connection.fetch.register 注册 /api/toolbox 下的测速路由;
7
+ * 3. 提供 /api/toolbox/net/status:把「连接情况」汇总成一份 JSON
8
+ * (客户端来源分类 / 本机地址 / WLAN 频段·速率·信号 / 公网出口 IP)。
9
+ *
10
+ * apply 永不抛:插件坏了最坏是面板不出现,不会把整页 index.html 打挂。
11
+ */
12
+ import { readFileSync, statSync } from 'node:fs';
13
+ import { dirname, join } from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { randomBytes } from 'node:crypto';
16
+ import { execFile } from 'node:child_process';
17
+ import os from 'node:os';
18
+ import dns from 'node:dns';
19
+
20
+ const HERE = dirname(fileURLToPath(import.meta.url));
21
+ const PREFIX = '/api/toolbox';
22
+
23
+ /** 1 MiB 随机块:随机数据不可压缩,避免任何中间层压缩把测速数字抬上去。 */
24
+ const CHUNK = 1 << 20;
25
+ const NOISE = randomBytes(CHUNK);
26
+
27
+ const MAX_MB = 4096;
28
+ const DEFAULT_MB = 50;
29
+ const MAX_UPLOAD_MB = 256;
30
+
31
+ /** 最近一次 /api 请求的来源地址(浏览器看不到这个,只能由宿主记录)。 */
32
+ const peer = { ip: '', port: 0, at: 0 };
33
+
34
+ /** 服务端侧计时结果:sid → { bytes, ms }(数字由电脑算,不依赖手机浏览器)。 */
35
+ const statStore = new Map();
36
+
37
+ function putStat(sid, value) {
38
+ if (!sid) return;
39
+ statStore.set(String(sid), { ...value, at: Date.now() });
40
+ if (statStore.size > 64) {
41
+ const now = Date.now();
42
+ for (const [key, item] of statStore) {
43
+ if (now - item.at > 120000) statStore.delete(key);
44
+ }
45
+ }
46
+ }
47
+
48
+ const fileCache = new Map();
49
+
50
+ function readFresh(name) {
51
+ const path = join(HERE, name);
52
+ const info = statSync(path);
53
+ const hit = fileCache.get(path);
54
+ if (hit !== undefined && hit.mtimeMs === info.mtimeMs && hit.size === info.size) return hit.text;
55
+ const text = readFileSync(path, 'utf8');
56
+ fileCache.set(path, { mtimeMs: info.mtimeMs, size: info.size, text });
57
+ return text;
58
+ }
59
+
60
+ function intParam(value, fallback, min, max) {
61
+ const n = Number.parseInt(String(value ?? ''), 10);
62
+ if (!Number.isFinite(n)) return fallback;
63
+ return Math.min(Math.max(n, min), max);
64
+ }
65
+
66
+ function json(status, body) {
67
+ return new Response(JSON.stringify(body), {
68
+ status,
69
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
70
+ });
71
+ }
72
+
73
+ /* ------------------------------------------------------------------ 连接情况 */
74
+
75
+ let wlanCache = { at: 0, value: null };
76
+ let wanCache = { at: 0, value: null };
77
+
78
+ function decodeOut(buf) {
79
+ if (!buf || buf.length === 0) return '';
80
+ const utf8 = new TextDecoder('utf-8', { fatal: false }).decode(buf);
81
+ if (!utf8.includes('\uFFFD')) return utf8;
82
+ try {
83
+ return new TextDecoder('gbk', { fatal: false }).decode(buf);
84
+ } catch {
85
+ return utf8;
86
+ }
87
+ }
88
+
89
+ function run(cmd, args, timeout = 1800) {
90
+ return new Promise((resolve) => {
91
+ try {
92
+ execFile(cmd, args, { timeout, windowsHide: true, maxBuffer: 1 << 20, encoding: 'buffer' }, (error, stdout) => {
93
+ resolve(error ? { ok: false, error: String(error.message ?? error), out: '' } : { ok: true, out: decodeOut(stdout) });
94
+ });
95
+ } catch (error) {
96
+ resolve({ ok: false, error: String(error?.message ?? error), out: '' });
97
+ }
98
+ });
99
+ }
100
+
101
+ /** netsh wlan show interfaces → { ssid, band, channel, radio, rxMbps, txMbps, signal, rssi }
102
+ * 注意:这台机器上 netsh 的界面语言会随调用上下文变化(PowerShell 里是英文、
103
+ * 从 node 子进程里是中文),所以中英文标签都要认,冒号还要认全角。 */
104
+ function parseWlan(text) {
105
+ const pick = (...labels) => {
106
+ for (const label of labels) {
107
+ // 允许标签后面跟 "(Mbps)" 这类括号单位,再跟半角/全角冒号
108
+ const m = new RegExp(`^\\s*${label}\\s*(?:\\([^)]*\\))?\\s*[::]\\s*(.+)$`, 'm').exec(text);
109
+ if (m) return m[1].trim();
110
+ }
111
+ return '';
112
+ };
113
+ const band = pick('Band', '波段');
114
+ const channel = pick('Channel', '通道', '信道');
115
+ const radio = pick('Radio type', '无线电类型');
116
+ const rx = pick('Receive rate \\(Mbps\\)', '接收速率');
117
+ const tx = pick('Transmit rate \\(Mbps\\)', '传输速率');
118
+ const signal = pick('Signal', '信号');
119
+ const rssi = pick('Rssi');
120
+ const ssid = pick('SSID');
121
+ if (!radio && !band) return null;
122
+ return {
123
+ ssid,
124
+ band,
125
+ channel,
126
+ radio,
127
+ rxMbps: Number(rx) || null,
128
+ txMbps: Number(tx) || null,
129
+ signal,
130
+ rssi: Number(rssi) || null,
131
+ };
132
+ }
133
+
134
+ async function wlanInfo() {
135
+ if (Date.now() - wlanCache.at < 8000) return wlanCache.value;
136
+ const res = await run('netsh', ['wlan', 'show', 'interfaces']);
137
+ const value = res.ok ? parseWlan(res.out) : { error: res.error };
138
+ wlanCache = { at: Date.now(), value };
139
+ return value;
140
+ }
141
+
142
+ /** 公网出口(3 秒超时,10 分钟缓存;失败返回 null,不影响其它字段)。
143
+ * 国内环境 api.ipify.org 经常直接空响应,所以主用 myip.ipip.net(还能带运营商/归属地)。 */
144
+ async function wanInfo() {
145
+ if (Date.now() - wanCache.at < 600000) return wanCache.value;
146
+ const timeout = (ms) => {
147
+ const ctrl = new AbortController();
148
+ const timer = setTimeout(() => ctrl.abort(), ms);
149
+ return { signal: ctrl.signal, done: () => clearTimeout(timer) };
150
+ };
151
+ let value = null;
152
+ {
153
+ const t = timeout(3000);
154
+ try {
155
+ const res = await fetch('https://myip.ipip.net', { signal: t.signal, cache: 'no-store' });
156
+ const text = String(await res.text());
157
+ const m = /(\d{1,3}(?:\.\d{1,3}){3})/.exec(text);
158
+ if (m) {
159
+ const where = text.replace(/当前\s*IP[::]\s*\d{1,3}(?:\.\d{1,3}){3}/, '').replace(/来自于[::]?/, '').trim();
160
+ value = { publicIp: m[1], isp: where || '' };
161
+ }
162
+ } catch { /* 忽略 */ } finally { t.done(); }
163
+ }
164
+ if (value === null) {
165
+ const t = timeout(2500);
166
+ try {
167
+ const res = await fetch('http://ip-api.com/json/?fields=query,isp,country', { signal: t.signal, cache: 'no-store' });
168
+ const body = await res.json();
169
+ if (body && body.query) value = { publicIp: String(body.query), isp: [body.country, body.isp].filter(Boolean).join(' ') };
170
+ } catch { /* 忽略 */ } finally { t.done(); }
171
+ }
172
+ wanCache = { at: Date.now(), value };
173
+ return value;
174
+ }
175
+
176
+ function ipv4Of() {
177
+ const out = [];
178
+ for (const [iface, addrs] of Object.entries(os.networkInterfaces())) {
179
+ if (!addrs) continue;
180
+ for (const a of addrs) {
181
+ if (a.family === 'IPv4' && !a.internal) out.push({ iface, address: a.address, netmask: a.netmask });
182
+ }
183
+ }
184
+ return out;
185
+ }
186
+
187
+ function classify(clientIp, hostAddrs) {
188
+ if (!clientIp) return { scope: 'unknown', label: '未知' };
189
+ const ip = clientIp.replace(/^::ffff:/, '');
190
+ if (ip === '127.0.0.1' || ip === '::1' || ip.startsWith('127.')) {
191
+ return { scope: 'loopback', label: '本机回环', note: '浏览器就在这台电脑上' };
192
+ }
193
+ if (hostAddrs.some((a) => a.address === ip)) {
194
+ return { scope: 'loopback', label: '本机(经局域网地址回来)', note: '仍是同一台电脑' };
195
+ }
196
+ if (ip.startsWith('100.')) {
197
+ const second = Number(ip.split('.')[1]);
198
+ if (second >= 64 && second <= 127) {
199
+ return { scope: 'tailnet', label: 'Tailscale 隧道', note: '不是局域网直连,速度受隧道限制' };
200
+ }
201
+ }
202
+ const sameSubnet = hostAddrs.some((a) => {
203
+ if (!a.netmask) return false;
204
+ const [c1, c2, c3, c4] = ip.split('.').map(Number);
205
+ const [h1, h2, h3, h4] = a.address.split('.').map(Number);
206
+ const [m1, m2, m3, m4] = a.netmask.split('.').map(Number);
207
+ if ([c1, c2, c3, c4, h1, h2, h3, h4, m1, m2, m3, m4].some((v) => !Number.isFinite(v))) return false;
208
+ const c = ((c1 << 24) | (c2 << 16) | (c3 << 8) | c4) >>> 0;
209
+ const h = ((h1 << 24) | (h2 << 16) | (h3 << 8) | h4) >>> 0;
210
+ const m = ((m1 << 24) | (m2 << 16) | (m3 << 8) | m4) >>> 0;
211
+ return (c & m) === (h & m);
212
+ });
213
+ if (sameSubnet) return { scope: 'lan', label: '局域网直连', note: '同一网段,走路由器/AP' };
214
+ return { scope: 'wan', label: '外网', note: '跨网段,可能经代理或公网回源' };
215
+ }
216
+
217
+ async function handleStatus() {
218
+ const addrs = ipv4Of();
219
+ const [wlan, wan] = await Promise.all([wlanInfo().catch(() => null), wanInfo().catch(() => null)]);
220
+ return json(200, {
221
+ ok: true,
222
+ client: { ip: peer.ip, port: peer.port, seenAt: peer.at, ...classify(peer.ip, addrs) },
223
+ host: { hostname: os.hostname(), addresses: addrs, platform: process.platform, uptimeSec: Math.round(os.uptime()) },
224
+ wlan,
225
+ wan: wan || { publicIp: null, isp: '' },
226
+ serverTime: new Date().toISOString(),
227
+ });
228
+ }
229
+
230
+ /* ------------------------------------------------------------------ 测速路由 */
231
+
232
+ function noiseStream(total, sid) {
233
+ let sent = 0;
234
+ let startedAt = 0;
235
+ return new ReadableStream({
236
+ pull(controller) {
237
+ if (sent >= total) {
238
+ if (sid && startedAt > 0) putStat(sid, { bytes: total, ms: Date.now() - startedAt, kind: "download" });
239
+ controller.close();
240
+ return;
241
+ }
242
+ if (startedAt === 0) startedAt = Date.now();
243
+ const n = Math.min(CHUNK, total - sent);
244
+ sent += n;
245
+ controller.enqueue(NOISE.slice(0, n));
246
+ },
247
+ });
248
+ }
249
+
250
+ /** 按时长持续发送(不限总字节,客户端读到流结束为止)——用于「实时」持续测速。 */
251
+ function timedNoiseStream(durationMs, sid) {
252
+ const deadline = Date.now() + durationMs;
253
+ let sent = 0;
254
+ let startedAt = 0;
255
+ return new ReadableStream({
256
+ pull(controller) {
257
+ if (Date.now() >= deadline) {
258
+ if (sid && startedAt > 0) putStat(sid, { bytes: sent, ms: Date.now() - startedAt, kind: "download" });
259
+ controller.close();
260
+ return;
261
+ }
262
+ if (startedAt === 0) startedAt = Date.now();
263
+ sent += CHUNK;
264
+ controller.enqueue(NOISE.slice(0, CHUNK));
265
+ },
266
+ });
267
+ }
268
+
269
+ function handleDownload(request) {
270
+ const url = new URL(request.url);
271
+ const sid = url.searchParams.get('sid');
272
+ const seconds = Number.parseFloat(String(url.searchParams.get('seconds') ?? ''));
273
+ if (Number.isFinite(seconds) && seconds > 0) {
274
+ const ms = Math.min(Math.max(seconds, 1), 120) * 1000;
275
+ const headers = {
276
+ 'content-type': 'application/octet-stream',
277
+ 'cache-control': 'no-store',
278
+ 'x-content-type-options': 'nosniff',
279
+ 'x-dsh-toolbox-seconds': String(ms / 1000),
280
+ };
281
+ if (request.method === 'HEAD') return new Response(null, { status: 200, headers });
282
+ return new Response(timedNoiseStream(ms, sid), { status: 200, headers });
283
+ }
284
+ const mb = intParam(url.searchParams.get('mb'), DEFAULT_MB, 1, MAX_MB);
285
+ const total = mb * CHUNK;
286
+ const headers = {
287
+ 'content-type': 'application/octet-stream',
288
+ 'content-length': String(total),
289
+ 'cache-control': 'no-store',
290
+ 'x-content-type-options': 'nosniff',
291
+ };
292
+ if (request.method === 'HEAD') return new Response(null, { status: 200, headers });
293
+ return new Response(noiseStream(total, sid), { status: 200, headers });
294
+ }
295
+
296
+ async function handleUpload(request) {
297
+ const t0 = Date.now();
298
+ const sid = new URL(request.url).searchParams.get('sid');
299
+ const cap = MAX_UPLOAD_MB * CHUNK;
300
+ let bytes = 0;
301
+ let firstByteAt = 0;
302
+ try {
303
+ if (request.body !== null) {
304
+ const reader = request.body.getReader();
305
+ for (;;) {
306
+ const { done, value } = await reader.read();
307
+ if (done) break;
308
+ if (firstByteAt === 0) firstByteAt = Date.now();
309
+ bytes += value.byteLength;
310
+ if (bytes > cap) {
311
+ try { await reader.cancel(); } catch { /* 忽略 */ }
312
+ return json(413, { ok: false, error: 'too large', bytes, limitMb: MAX_UPLOAD_MB });
313
+ }
314
+ }
315
+ }
316
+ } catch (error) {
317
+ return json(400, { ok: false, error: String(error?.message ?? error) });
318
+ }
319
+ const end = Date.now();
320
+ putStat(sid, { bytes, ms: firstByteAt > 0 ? end - firstByteAt : 0, kind: "upload" });
321
+ return json(200, {
322
+ ok: true,
323
+ bytes,
324
+ serverMs: end - t0,
325
+ // 服务端侧计时:首字节→最后一字节,不依赖浏览器 performance.now()
326
+ transferMs: firstByteAt > 0 ? end - firstByteAt : 0,
327
+ sid: sid || null,
328
+ });
329
+ }
330
+
331
+ function handleInfo(request) {
332
+ const url = new URL(request.url);
333
+ return json(200, {
334
+ ok: true,
335
+ ip: peer.ip,
336
+ port: peer.port,
337
+ at: peer.at,
338
+ host: request.headers.get('host') ?? '',
339
+ serverTime: new Date().toISOString(),
340
+ pingToken: url.searchParams.get('t') ?? '',
341
+ });
342
+ }
343
+
344
+
345
+ /* ------------------------------------------------------------------ 自检 */
346
+
347
+ function parsePing(text) {
348
+ // 不依赖语言:丢包取括号里的百分比,时延取统计行里按 最小/最大/平均 顺序出现的 "= N ms"。
349
+ const loss = /\((\d+)%/.exec(text);
350
+ const all = [];
351
+ const re = /=\s*(\d+)\s*ms/gi;
352
+ let m;
353
+ while ((m = re.exec(text)) !== null) all.push(Number(m[1]));
354
+ const times = all.slice(-3); // 统计块在最后:最小/最大/平均 或 Minimum/Maximum/Average
355
+ return {
356
+ lossPct: loss ? Number(loss[1]) : null,
357
+ minMs: times.length > 0 ? times[0] : null,
358
+ maxMs: times.length > 1 ? times[1] : null,
359
+ avgMs: times.length > 2 ? times[2] : null,
360
+ };
361
+ }
362
+
363
+ async function findGateway() {
364
+ const res = await run('route', ['print', '-4']);
365
+ if (!res.ok) return '';
366
+ const m = /^\s*0\.0\.0\.0\s+0\.0\.0\.0\s+(\d{1,3}(?:\.\d{1,3}){3})/m.exec(res.out);
367
+ return m ? m[1] : '';
368
+ }
369
+
370
+ async function handleDiag() {
371
+ const addrs = ipv4Of();
372
+ const gateway = await findGateway().catch(() => '');
373
+ const [wlan, wan] = await Promise.all([wlanInfo().catch(() => null), wanInfo().catch(() => null)]);
374
+
375
+ let ping = null;
376
+ if (gateway) {
377
+ const res = await run('ping', ['-n', '4', '-w', '1000', gateway], 6000);
378
+ if (res.ok) ping = parsePing(res.out);
379
+ }
380
+
381
+ const dnsStart = Date.now();
382
+ let dnsOk = true;
383
+ await new Promise((resolve) => {
384
+ dns.lookup('www.baidu.com', (err) => { if (err) dnsOk = false; resolve(); });
385
+ });
386
+ const dnsMs = Date.now() - dnsStart;
387
+
388
+ return json(200, {
389
+ ok: true,
390
+ client: { ip: peer.ip, ...classify(peer.ip, addrs) },
391
+ host: { hostname: os.hostname(), addresses: addrs },
392
+ gateway: { ip: gateway, ping },
393
+ dns: { ok: dnsOk, ms: dnsMs },
394
+ wlan,
395
+ wan,
396
+ load: { loadavg: os.loadavg(), cpus: os.cpus().length, freeMemMB: Math.round(os.freemem() / 1048576), totalMemMB: Math.round(os.totalmem() / 1048576) },
397
+ uptimeSec: Math.round(os.uptime()),
398
+ serverTime: new Date().toISOString(),
399
+ });
400
+ }
401
+
402
+ const ROUTES = [
403
+ { path: `${PREFIX}/net/download`, methods: ['GET', 'HEAD'], requestBody: 'buffered', fetch: handleDownload },
404
+ { path: `${PREFIX}/net/upload`, methods: ['POST'], requestBody: 'streaming', fetch: handleUpload },
405
+ { path: `${PREFIX}/net/info`, methods: ['GET'], requestBody: 'buffered', fetch: handleInfo },
406
+ { path: `${PREFIX}/net/diag`, methods: ['GET'], requestBody: 'buffered', fetch: () => handleDiag() },
407
+ { path: `${PREFIX}/net/stat`, methods: ['GET'], requestBody: 'buffered', fetch: (request) => json(200, statStore.get(String(new URL(request.url).searchParams.get('sid') || '')) ?? { pending: true }) },
408
+ { path: `${PREFIX}/net/status`, methods: ['GET'], requestBody: 'buffered', fetch: () => handleStatus() },
409
+ ];
410
+
411
+ function registerRoutes(ctx, state) {
412
+ if (state.routes) return true;
413
+ try {
414
+ const fetcher = ctx.connection?.fetch;
415
+ if (!fetcher || typeof fetcher.register !== 'function') {
416
+ state.reason = 'connection.fetch not ready';
417
+ return false;
418
+ }
419
+ for (const route of ROUTES) {
420
+ ctx.effect(() => fetcher.register(route), `dsh-toolbox: ${route.path}`);
421
+ }
422
+ state.routes = true;
423
+ state.reason = 'ok';
424
+ try { ctx.logger?.info?.('dsh-toolbox: /api/toolbox 路由已注册'); } catch { /* 忽略 */ }
425
+ return true;
426
+ } catch (error) {
427
+ state.reason = `register failed: ${error?.message ?? String(error)}`;
428
+ try { ctx.logger?.warn?.(`dsh-toolbox: ${state.reason}`); } catch { /* 忽略 */ }
429
+ return false;
430
+ }
431
+ }
432
+
433
+ /** 记录来源地址。waterfall 事件,必须把 next() 继续传下去,否则 /api 整条链路会卡住。 */
434
+ function watchPeer(ctx) {
435
+ try {
436
+ ctx.on('connection/request', (req, res, next) => {
437
+ try {
438
+ peer.ip = req?.socket?.remoteAddress ?? '';
439
+ peer.port = req?.socket?.remotePort ?? 0;
440
+ peer.at = Date.now();
441
+ } catch { /* 忽略 */ }
442
+ return next();
443
+ });
444
+ } catch { /* 忽略 */ }
445
+ }
446
+
447
+ function apply(ctx) {
448
+ const state = { routes: false, rows: 0, reason: 'not attempted' };
449
+ watchPeer(ctx);
450
+ try {
451
+ ctx.on('webserver/index-inject', (table) => {
452
+ try {
453
+ const rows = [];
454
+ try {
455
+ rows.push({ kind: 'style', text: readFresh('client.css') });
456
+ } catch (error) {
457
+ state.reason = `css: ${error?.message ?? error}`;
458
+ }
459
+ try {
460
+ rows.push({ kind: 'script', placement: 'head', text: readFresh('client.js') });
461
+ } catch (error) {
462
+ state.reason = `js: ${error?.message ?? error}`;
463
+ }
464
+ state.rows = rows.length;
465
+ for (const row of rows) table.push(row);
466
+ table.push({ kind: 'global', name: '__DSH_TOOLBOX__', value: { rows: state.rows, routes: state.routes, reason: state.reason } });
467
+ registerRoutes(ctx, state);
468
+ } catch (error) {
469
+ state.reason = `inject failed: ${error?.message ?? String(error)}`;
470
+ }
471
+ }, { prepend: true });
472
+ } catch (error) {
473
+ state.reason = `ctx.on failed: ${error?.message ?? String(error)}`;
474
+ }
475
+ try {
476
+ registerRoutes(ctx, state);
477
+ } catch (error) {
478
+ state.reason = `register (apply) threw: ${error?.message ?? String(error)}`;
479
+ }
480
+ }
481
+
482
+ export { apply, handleDownload, handleUpload, handleInfo, handleStatus, handleDiag, parseWlan, classify, PREFIX, CHUNK };
483
+ export const inject = ['connection'];
484
+ apply.inject = ['connection'];
package/install.ps1 ADDED
@@ -0,0 +1,114 @@
1
+ # install.ps1 - sync dsh-toolbox into the web profile and register it in cordis.patch.yml.
2
+ # ASCII-only on purpose (Windows PowerShell 5.1 reads BOM-less .ps1 as ANSI).
3
+ #
4
+ # powershell -NoProfile -File install.ps1 # install / update
5
+ # powershell -NoProfile -File install.ps1 -Uninstall # remove files + patch block
6
+ #
7
+ # The plugin is loaded at DSH boot, so a restart is required afterwards:
8
+ # powershell -NoProfile -File D:\Workspaces\DSH\tools\dsh-restart-safe.ps1
9
+
10
+ param(
11
+ [switch]$Uninstall
12
+ )
13
+
14
+ $ErrorActionPreference = 'Stop'
15
+
16
+ $Src = $PSScriptRoot # this script lives in the plugin dir; no machine-specific path
17
+ $ProfileDir = Join-Path $env:USERPROFILE '.dsh\profiles\web'
18
+ $Dest = Join-Path $ProfileDir 'node_modules\dsh-toolbox'
19
+ $PatchFile = Join-Path $ProfileDir 'cordis.patch.yml'
20
+ $Begin = '# >>> dsh-toolbox (managed by install.ps1)'
21
+ $End = '# <<< dsh-toolbox'
22
+
23
+ $Block = @"
24
+ $Begin
25
+ # Injected toolbox: right-side drawer / mobile fullscreen panel - connection info, diagnostics, speed test, quality monitor, history, auto patrol.
26
+ # Must use 'insert:' - a patch entry with id+name only OVERRIDES an existing row;
27
+ # a new plugin row written that way is silently skipped (same trap as dsh-mobile-console).
28
+ - insert:
29
+ - id: toolbox
30
+ name: 'dsh-toolbox'
31
+ $End
32
+ "@
33
+
34
+ function Read-Patch {
35
+ if (-not (Test-Path -LiteralPath $PatchFile)) { throw "patch file not found: $PatchFile" }
36
+ return Get-Content -LiteralPath $PatchFile -Raw -Encoding UTF8
37
+ }
38
+
39
+ function Write-Patch([string]$text) {
40
+ $dir = Split-Path -Parent $PatchFile
41
+ $tmp = Join-Path $dir ('.cordis.patch.yml.tmp-' + [guid]::NewGuid().ToString('N'))
42
+ # MUST be UTF-8 without BOM: Windows PowerShell 5.1 Set-Content -Encoding UTF8 adds a BOM,
43
+ # and DSH chokes on a BOM in package.json / patch files (2026-11-02: plugin silently disabled).
44
+ [System.IO.File]::WriteAllText($tmp, $text, (New-Object System.Text.UTF8Encoding($false)))
45
+ Move-Item -LiteralPath $tmp -Destination $PatchFile -Force
46
+ }
47
+
48
+ function Strip-Block([string]$text) {
49
+ $pattern = '(?s)\r?\n?' + [regex]::Escape($Begin) + '.*?' + [regex]::Escape($End) + '\r?\n?'
50
+ return [regex]::Replace($text, $pattern, "`n")
51
+ }
52
+
53
+ if ($Uninstall) {
54
+ if (Test-Path -LiteralPath $Dest) {
55
+ # 安全修复(2026-11-06 审计 P0/删除纪律):$Dest 可能是 junction(node_modules 链接)。
56
+ # PS5.1 的 Remove-Item -Recurse 会跟随联接删掉目标真实内容;链接只删链接本体。
57
+ $item = Get-Item -LiteralPath $Dest -Force
58
+ if ($item.LinkType) {
59
+ [System.IO.Directory]::Delete($Dest, $false)
60
+ Write-Host "removed link $Dest (target kept)"
61
+ } else {
62
+ Remove-Item -LiteralPath $Dest -Recurse -Force
63
+ Write-Host "removed $Dest"
64
+ }
65
+ }
66
+ $text = Read-Patch
67
+ $next = (Strip-Block $text).TrimEnd() + "`n"
68
+ if ($next -ne $text) { Write-Patch $next; Write-Host 'patch block removed' }
69
+ Write-Host 'uninstall done. Restart DSH to unload the plugin.'
70
+ exit 0
71
+ }
72
+
73
+ # 1) files
74
+ if (-not (Test-Path -LiteralPath $Src)) { throw "source not found: $Src" }
75
+ New-Item -ItemType Directory -Force -Path $Dest | Out-Null
76
+ $files = @('package.json', 'index.js', 'client.js', 'client.css', 'README.md')
77
+ foreach ($name in $files) {
78
+ $from = Join-Path $Src $name
79
+ if (-not (Test-Path -LiteralPath $from)) { throw "missing source file: $from" }
80
+ Copy-Item -LiteralPath $from -Destination (Join-Path $Dest $name) -Force
81
+ }
82
+ # Defensive: a BOM in package.json makes DSH fail its plugin validation and silently disable the plugin.
83
+ # The source files are BOM-free; this pass just guards against editors/scripts putting it back.
84
+ $pkg = Join-Path $Dest 'package.json'
85
+ $bytes = [System.IO.File]::ReadAllBytes($pkg)
86
+ if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) {
87
+ $t = [System.IO.File]::ReadAllText($pkg, [System.Text.Encoding]::UTF8)
88
+ if ($t.Length -gt 0 -and $t[0] -eq [char]0xFEFF) { $t = $t.Substring(1) }
89
+ [System.IO.File]::WriteAllText($pkg, $t, (New-Object System.Text.UTF8Encoding($false)))
90
+ Write-Host 'stripped BOM from package.json'
91
+ }
92
+ Write-Host "synced $($files.Count) files -> $Dest"
93
+
94
+ # 2) patch entry (idempotent)
95
+ $text = Read-Patch
96
+ if ($text.Contains($Begin)) {
97
+ $next = [regex]::Replace(
98
+ $text,
99
+ '(?s)' + [regex]::Escape($Begin) + '.*?' + [regex]::Escape($End),
100
+ [System.Text.RegularExpressions.MatchEvaluator]{ param($m) $Block })
101
+ } else {
102
+ $next = $text.TrimEnd() + "`n`n" + $Block + "`n"
103
+ }
104
+ if ($next -ne $text) {
105
+ Copy-Item -LiteralPath $PatchFile -Destination ($PatchFile + '.bak-toolbox') -Force
106
+ Write-Patch $next
107
+ Write-Host "patch entry written: $PatchFile"
108
+ } else {
109
+ Write-Host 'patch entry already current'
110
+ }
111
+
112
+ Write-Host ''
113
+ Write-Host 'Next: restart DSH, then reload the page.'
114
+ Write-Host ' powershell -NoProfile -File D:\Workspaces\DSH\tools\dsh-restart-safe.ps1'
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@hao0311/dsh-toolbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.1",
4
+ "type": "module",
5
+ "main": "index.js",
6
+ "exports": {
7
+ ".": "./index.js"
8
+ },
9
+ "description": "Toolbox panel for the DeepSeek Harness Web GUI: a right-side drawer (full screen on phones) with connection information, one-click diagnostics, a speed test, a quality monitor, history and auto patrol.",
10
+ "keywords": [
11
+ "dsh",
12
+ "dsh-plugin",
13
+ "deepseek-harness",
14
+ "toolbox",
15
+ "diagnostics",
16
+ "speed-test",
17
+ "ui"
18
+ ],
19
+ "license": "MIT",
20
+ "homepage": "https://awesome-dsh-plugin.com/p/Hao0311/dsh-toolbox/",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/Hao0311/dsh-toolbox.git"
24
+ },
25
+ "bugs": {
26
+ "url": "https://github.com/Hao0311/dsh-toolbox/issues"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ }
31
+ }