dsh-lan-peers 0.3.0 → 0.4.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/client/cli.mjs CHANGED
@@ -1,201 +1,351 @@
1
- #!/usr/bin/env node
2
- // dsh-lan-peers — client half CLI.
3
- // node cli.mjs code [--host http://127.0.0.1:7788]
4
- // node cli.mjs pair --url http://PEER:7788 --code 123456 [--name 本机名] [--peer-name 对端名]
5
- // node cli.mjs peers [--probe]
6
- // node cli.mjs ask --peer <peerId|name> "prompt" [--timeout 300]
7
- import crypto from 'node:crypto';
8
- import { execFileSync } from 'node:child_process';
9
- import fs from 'node:fs';
10
- import os from 'node:os';
11
- import path from 'node:path';
12
- import { fileURLToPath } from 'node:url';
13
- import { newSecret } from './protocol.mjs';
14
- import { callPeer } from './peer-call.mjs';
15
-
16
- const DEFAULT_STATE_DIR = path.join(os.homedir(), '.dsh', 'lan-peers');
17
-
18
- function parseArgs(argv) {
19
- const out = { _: [] };
20
- for (let i = 0; i < argv.length; i++) {
21
- const arg = argv[i];
22
- if (arg.startsWith('--')) {
23
- const key = arg.slice(2);
24
- const next = argv[i + 1];
25
- if (next === undefined || next.startsWith('--')) out[key] = true;
26
- else {
27
- out[key] = next;
28
- i++;
29
- }
30
- } else out._.push(arg);
31
- }
32
- return out;
33
- }
34
-
35
- const stateDir = (args) => path.resolve(args['state-dir'] || DEFAULT_STATE_DIR);
36
- const readJson = (file, fallback) => {
37
- try {
38
- return JSON.parse(fs.readFileSync(file, 'utf8'));
39
- } catch {
40
- return fallback;
41
- }
42
- };
43
- const writeJson = (file, value) => {
44
- fs.mkdirSync(path.dirname(file), { recursive: true });
45
- const tmp = `${file}.${process.pid}.tmp`;
46
- fs.writeFileSync(tmp, JSON.stringify(value, null, 2), { mode: 0o600 });
47
- fs.renameSync(tmp, file);
48
- };
49
-
50
- function identity(dir) {
51
- const file = path.join(dir, 'state.json');
52
- const state = readJson(file, {});
53
- if (!state.instanceId) {
54
- state.instanceId = crypto.randomUUID();
55
- state.name = state.name || os.hostname();
56
- state.createdAt = new Date().toISOString();
57
- writeJson(file, state);
58
- }
59
- return state;
60
- }
61
-
62
- async function signedCall({ baseUrl, secret, senderId, method = 'GET', apiPath, body }) {
63
- return callPeer({ baseUrl, secret, senderId, method, apiPath, body, timeoutMs: 60_000 });
64
- }
65
-
66
- async function cmdCode(args) {
67
- // The code lives in state.json, which the host process re-reads; issuing it via
68
- // the host CLI keeps one writer instead of racing the running server.
69
- const pkgRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
70
- const out = execFileSync(process.execPath, [
71
- path.join(pkgRoot, 'host', 'server.mjs'),
72
- '--code',
73
- '--state-dir',
74
- stateDir(args),
75
- ], { encoding: 'utf8' });
76
- const match = /(\d{6})/.exec(out);
77
- if (!match) throw new Error(out.trim() || 'no pairing code');
78
- console.log(`配对码: ${match[1]} 有效期: 10 分钟,一次性`);
79
- console.log(`对方把它填进「添加伙伴」里即可配对(地址填本机 http://<ip>:7788)`);
80
- }
81
-
82
- async function cmdPair(args) {
83
- const dir = stateDir(args);
84
- const me = identity(dir);
85
- const url = String(args.url || '').replace(/\/$/, '');
86
- const code = String(args.code || '');
87
- const name = String(args.name || me.name || os.hostname());
88
- if (!url || !code) throw new Error('用法: pair --url http://PEER:7788 --code 123456 [--name 本机名]');
89
-
90
- const secret = newSecret();
91
- const res = await fetch(`${url}/v1/pair`, {
92
- method: 'POST',
93
- headers: { 'Content-Type': 'application/json' },
94
- body: JSON.stringify({ code, peerId: me.instanceId, peerName: name, secret }),
95
- });
96
- const body = await res.json();
97
- if (!res.ok) throw new Error(`配对失败: ${res.status} ${body.error || ''}`.trim());
98
-
99
- const peersFile = path.join(dir, 'peers.json');
100
- const store = readJson(peersFile, { peers: {} });
101
- const previous = store.peers[body.peerId] || {};
102
- // Two secrets per peer: `secret` is what the peer issued to us (we sign with
103
- // it), `inboundSecret` is what we issued to the peer (we verify with it).
104
- // Keeping both is what makes the pairing mutual in both directions.
105
- store.peers[body.peerId] = {
106
- ...previous,
107
- name: args['peer-name'] || body.peerName || body.peerId,
108
- baseUrl: url,
109
- secret: body.secret,
110
- inboundSecret: secret,
111
- addedAt: previous.addedAt || new Date().toISOString(),
112
- };
113
- writeJson(peersFile, store);
114
- console.log(`已配对: ${store.peers[body.peerId].name} (${body.peerId})`);
115
- }
116
-
117
- async function cmdPeers(args) {
118
- const dir = stateDir(args);
119
- const store = readJson(path.join(dir, 'peers.json'), { peers: {} });
120
- const entries = Object.entries(store.peers || {});
121
- if (entries.length === 0) {
122
- console.log('(尚未配对任何对端)');
123
- return;
124
- }
125
- for (const [peerId, peer] of entries) {
126
- let status = 'unknown';
127
- if (args.probe) {
128
- try {
129
- const res = await fetch(`${peer.baseUrl}/v1/health`, { signal: AbortSignal.timeout(2000) });
130
- status = res.ok ? 'online' : `http ${res.status}`;
131
- } catch {
132
- status = 'offline';
133
- }
134
- }
135
- console.log(`${peer.name}\t${peer.baseUrl}\t${peerId}\t${status}`);
136
- }
137
- }
138
-
139
- async function cmdAsk(args) {
140
- const dir = stateDir(args);
141
- const me = identity(dir);
142
- const prompt = args._.join(' ').trim();
143
- if (!args.peer || !prompt) throw new Error('用法: ask --peer <peerId|name> "prompt"');
144
- const store = readJson(path.join(dir, 'peers.json'), { peers: {} });
145
- const match = Object.entries(store.peers || {}).find(
146
- ([peerId, peer]) => peerId === args.peer || peer.name === args.peer,
147
- );
148
- if (!match) throw new Error(`未知对端: ${args.peer}`);
149
- const [peerId, peer] = match;
150
-
151
- const requestId = `req-${crypto.randomUUID()}`;
152
- const accepted = await signedCall({
153
- baseUrl: peer.baseUrl,
154
- secret: peer.secret,
155
- senderId: me.instanceId,
156
- method: 'POST',
157
- apiPath: '/v1/ask',
158
- body: { requestId, prompt, timeoutSec: Number(args.timeout || 300) },
159
- });
160
- const sessionId = accepted.sessionId;
161
- process.stderr.write(`已派单 → ${peer.name} (session ${sessionId})\n`);
162
-
163
- const deadline = Date.now() + Number(args.timeout || 300) * 1000;
164
- const started = Date.now();
165
- while (Date.now() < deadline) {
166
- await new Promise((r) => setTimeout(r, 1500));
167
- const answer = await signedCall({
168
- baseUrl: peer.baseUrl,
169
- secret: peer.secret,
170
- senderId: me.instanceId,
171
- method: 'GET',
172
- apiPath: `/v1/answer?sessionId=${encodeURIComponent(sessionId)}`,
173
- });
174
- process.stderr.write('.');
175
- if (answer.status === 'done') {
176
- process.stderr.write('\n');
177
- console.log(answer.reply);
178
- return;
179
- }
180
- if (answer.status === 'error') {
181
- process.stderr.write('\n');
182
- throw new Error(`对端返回错误: ${answer.error}`);
183
- }
184
- }
185
- console.log(`timeout after ${Math.round((Date.now() - started) / 1000)}s`);
186
- process.exitCode = 2;
187
- }
188
-
189
- const commands = { code: cmdCode, pair: cmdPair, peers: cmdPeers, ask: cmdAsk };
190
-
191
- const args = parseArgs(process.argv.slice(2));
192
- const command = commands[args._[0]];
193
- if (!command) {
194
- console.error('用法: cli.mjs <code|pair|peers|ask> [options]');
195
- process.exit(1);
196
- }
197
- args._ = args._.slice(1);
198
- command(args).catch((error) => {
199
- console.error(String(error.message || error));
200
- process.exit(1);
201
- });
1
+ #!/usr/bin/env node
2
+ // dsh-lan-peers — client half CLI.
3
+ // node cli.mjs code [--state-dir <dir>]
4
+ // node cli.mjs pair --url http://PEER:7788 --code 123456 [--name 本机名] [--peer-name 对端名] [--legacy-pair]
5
+ // node cli.mjs peers [--probe]
6
+ // node cli.mjs ask --peer <peerId|name> "prompt" [--timeout 300] [--legacy-poll]
7
+ // node cli.mjs events --peer <peerId|name> --session <sessionId> [--duration 300] [--verbose]
8
+ import crypto from 'node:crypto';
9
+ import { execFileSync } from 'node:child_process';
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+ import {
15
+ DEFAULT_ANSWER_WAIT_MS,
16
+ MAX_ANSWER_WAIT_MS,
17
+ awaitPeerAnswer,
18
+ callPeer,
19
+ capabilityOf,
20
+ pairingEcdhAvailable,
21
+ pairPeer,
22
+ probePeer,
23
+ } from './peer-call.mjs';
24
+ import { readPeerEvents } from './sse.mjs';
25
+
26
+ const DEFAULT_STATE_DIR = path.join(os.homedir(), '.dsh', 'lan-peers');
27
+
28
+ const USAGE = [
29
+ 'dsh-lan-peers — 局域网伙伴 CLI',
30
+ '',
31
+ '用法: dsh-lan-peers <子命令> [选项]',
32
+ '',
33
+ '子命令:',
34
+ ' code 生成一次性配对码(6 位,10 分钟,一次性)',
35
+ ' pair 用配对码与对端互认(ECDH 两轮,自动回退旧明文)',
36
+ ' peers 列出已配对伙伴',
37
+ ' ask 向伙伴派单并等待回复',
38
+ ' events 订阅伙伴 /v1/events 事件流(排障)',
39
+ ' help 显示本帮助',
40
+ '',
41
+ '全局选项:',
42
+ ' --state-dir <路径> 状态目录(默认 ~/.dsh/lan-peers)',
43
+ ' --help 查看子命令用法',
44
+ ].join('\n');
45
+
46
+ const CODE_USAGE = [
47
+ '用法: dsh-lan-peers code [--state-dir <目录>]',
48
+ '',
49
+ '生成一次性配对码,同时写入 state.json(10 分钟有效,用后即焚)。',
50
+ ].join('\n');
51
+
52
+ const PAIR_USAGE = [
53
+ '用法: dsh-lan-peers pair --url http://PEER:7788 --code 123456 [--name 本机名] [--peer-name 对端名] [--legacy-pair]',
54
+ '',
55
+ '默认自适应:对端 /v1/health 的 capability 含 "pair-ecdh" 时走 ECDH 两轮',
56
+ '(/v1/pair 交换临时公钥 → /v1/pair/confirm 用派生密钥包裹初始密钥),',
57
+ '否则回退 0.3.1 的明文 /v1/pair。',
58
+ '',
59
+ ' --legacy-pair 强制旧明文路径(对端 0.3.1 或排障用)',
60
+ ' --ecdh-pair 强制 ECDH,对端不支持则报错',
61
+ ].join('\n');
62
+
63
+ const PEERS_USAGE = [
64
+ '用法: dsh-lan-peers peers [--probe] [--state-dir <目录>]',
65
+ '',
66
+ ' --probe 逐个探活(GET /v1/health,2 秒超时)',
67
+ ].join('\n');
68
+
69
+ const ASK_USAGE = [
70
+ '用法: dsh-lan-peers ask --peer <peerId|名字> "prompt" [--timeout 300] [--legacy-poll] [--wait-ms 25000]',
71
+ '',
72
+ '对端声明 "stream" 时走 /v1/events(SSE),否则 /v1/answer 长轮询;',
73
+ '--legacy-poll 强制 0.3.1 的 1.5 秒轮询(不带 waitMs)。',
74
+ ].join('\n');
75
+
76
+ const EVENTS_USAGE = [
77
+ '用法: dsh-lan-peers events --peer <peerId|名字> --session <sessionId> [--duration 300] [--verbose]',
78
+ '',
79
+ '订阅对端 /v1/events:每条事件独立加密,此处解密后逐条打印。',
80
+ '对端 capability 不含 "stream" 时直接报错(0.3.1 没有该端点)。',
81
+ '',
82
+ ' --duration <秒> 最长订阅时间(默认 300)',
83
+ ' --verbose 同时打印 ping 心跳',
84
+ ].join('\n');
85
+
86
+ function parseArgs(argv) {
87
+ const out = { _: [] };
88
+ for (let i = 0; i < argv.length; i++) {
89
+ const arg = argv[i];
90
+ if (arg.startsWith('--')) {
91
+ const key = arg.slice(2);
92
+ const next = argv[i + 1];
93
+ if (next === undefined || next.startsWith('--')) out[key] = true;
94
+ else {
95
+ out[key] = next;
96
+ i++;
97
+ }
98
+ } else out._.push(arg);
99
+ }
100
+ return out;
101
+ }
102
+
103
+ const stateDir = (args) => path.resolve(args['state-dir'] || DEFAULT_STATE_DIR);
104
+ const readJson = (file, fallback) => {
105
+ try {
106
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
107
+ } catch {
108
+ return fallback;
109
+ }
110
+ };
111
+ const writeJson = (file, value) => {
112
+ fs.mkdirSync(path.dirname(file), { recursive: true });
113
+ const tmp = file + '.' + process.pid + '.tmp';
114
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2), { mode: 0o600 });
115
+ fs.renameSync(tmp, file);
116
+ };
117
+
118
+ function identity(dir) {
119
+ const file = path.join(dir, 'state.json');
120
+ const state = readJson(file, {});
121
+ if (!state.instanceId) {
122
+ state.instanceId = crypto.randomUUID();
123
+ state.name = state.name || os.hostname();
124
+ state.createdAt = new Date().toISOString();
125
+ writeJson(file, state);
126
+ }
127
+ return state;
128
+ }
129
+
130
+ function findPeer(dir, wanted) {
131
+ const store = readJson(path.join(dir, 'peers.json'), { peers: {} });
132
+ const match = Object.entries(store.peers || {}).find(
133
+ ([peerId, peer]) => peerId === wanted || peer.name === wanted,
134
+ );
135
+ if (!match) throw new Error('未知对端: ' + wanted);
136
+ return { store, peerId: match[0], peer: match[1] };
137
+ }
138
+
139
+ async function signedCall({ baseUrl, secret, senderId, method = 'GET', apiPath, body }) {
140
+ return callPeer({ baseUrl, secret, senderId, method, apiPath, body, timeoutMs: 60_000 });
141
+ }
142
+
143
+ async function cmdCode(args) {
144
+ // The code lives in state.json, which the host process re-reads; issuing it via
145
+ // the host CLI keeps one writer instead of racing the running server.
146
+ const pkgRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
147
+ const out = execFileSync(process.execPath, [
148
+ path.join(pkgRoot, 'host', 'server.mjs'),
149
+ '--code',
150
+ '--state-dir',
151
+ stateDir(args),
152
+ ], { encoding: 'utf8' });
153
+ const match = /(\d{6})/.exec(out);
154
+ if (!match) throw new Error(out.trim() || 'no pairing code');
155
+ console.log('配对码: ' + match[1] + ' 有效期: 10 分钟,一次性');
156
+ console.log('对方把它填进「添加伙伴」里即可配对(地址填本机 http://<ip>:7788)');
157
+ }
158
+
159
+ async function cmdPair(args) {
160
+ const dir = stateDir(args);
161
+ const me = identity(dir);
162
+ const url = String(args.url || '').replace(/\/$/, '');
163
+ const code = String(args.code || '');
164
+ const name = String(args.name || me.name || os.hostname());
165
+ if (!url || !code) throw new Error(PAIR_USAGE);
166
+
167
+ const mode = args['legacy-pair'] ? 'legacy' : (args['ecdh-pair'] ? 'ecdh' : 'auto');
168
+ const paired = await pairPeer({
169
+ url,
170
+ code,
171
+ peerId: me.instanceId,
172
+ peerName: name,
173
+ mode,
174
+ });
175
+
176
+ const peersFile = path.join(dir, 'peers.json');
177
+ const store = readJson(peersFile, { peers: {} });
178
+ const previous = store.peers[paired.peerId] || {};
179
+ // Two secrets per peer: `secret` is what the peer issued to us (we sign with
180
+ // it), `inboundSecret` is what we issued to the peer (we verify with it).
181
+ // Keeping both is what makes the pairing mutual in both directions.
182
+ store.peers[paired.peerId] = {
183
+ ...previous,
184
+ name: args['peer-name'] || paired.peerName || paired.peerId,
185
+ baseUrl: url,
186
+ secret: paired.secret,
187
+ inboundSecret: paired.inboundSecret,
188
+ transport: paired.transport,
189
+ addedAt: previous.addedAt || new Date().toISOString(),
190
+ };
191
+ writeJson(peersFile, store);
192
+
193
+ const label = store.peers[paired.peerId].name;
194
+ const how = paired.transport === 'ecdh' ? 'ECDH 两轮' : '旧明文路径';
195
+ console.log('已配对: ' + label + ' (' + paired.peerId + ') · ' + how);
196
+ if (paired.transport === 'legacy') {
197
+ const ecdhReady = await pairingEcdhAvailable();
198
+ console.log(ecdhReady
199
+ ? '提示: 对端未声明 pair-ecdh,已回退旧明文配对(初始密钥明文传输)'
200
+ : '提示: 本构建缺少 lib/pairing-ecdh.mjs,已回退旧明文配对(初始密钥明文传输)');
201
+ }
202
+ }
203
+
204
+ async function cmdPeers(args) {
205
+ const dir = stateDir(args);
206
+ const store = readJson(path.join(dir, 'peers.json'), { peers: {} });
207
+ const entries = Object.entries(store.peers || {});
208
+ if (entries.length === 0) {
209
+ console.log('(尚未配对任何对端)');
210
+ return;
211
+ }
212
+ for (const [peerId, peer] of entries) {
213
+ let status = 'unknown';
214
+ if (args.probe) {
215
+ try {
216
+ const res = await fetch(peer.baseUrl + '/v1/health', { signal: AbortSignal.timeout(2000) });
217
+ status = res.ok ? 'online' : 'http ' + res.status;
218
+ } catch {
219
+ status = 'offline';
220
+ }
221
+ }
222
+ console.log(peer.name + '\t' + peer.baseUrl + '\t' + peerId + '\t' + status);
223
+ }
224
+ }
225
+
226
+ async function cmdAsk(args) {
227
+ const dir = stateDir(args);
228
+ const me = identity(dir);
229
+ const prompt = args._.join(' ').trim();
230
+ if (!args.peer || !prompt) throw new Error(ASK_USAGE);
231
+ const { peer } = findPeer(dir, args.peer);
232
+
233
+ const requestId = 'req-' + crypto.randomUUID();
234
+ const accepted = await signedCall({
235
+ baseUrl: peer.baseUrl,
236
+ secret: peer.secret,
237
+ senderId: me.instanceId,
238
+ method: 'POST',
239
+ apiPath: '/v1/ask',
240
+ body: { requestId, prompt, timeoutSec: Number(args.timeout || 300) },
241
+ });
242
+ const sessionId = accepted.sessionId;
243
+ process.stderr.write('已派单 → ' + peer.name + ' (session ' + sessionId + ')\n');
244
+
245
+ // Capability decides the wire shape: a 0.3.1 peer has no "stream", so it keeps
246
+ // the old 1.5s answer polling (waitMs is never sent to it).
247
+ const health = await probePeer({ baseUrl: peer.baseUrl, timeoutMs: 2000 });
248
+ const streamCapable = capabilityOf(health).includes('stream');
249
+ const mode = args['legacy-poll'] ? 'legacy' : (streamCapable ? 'auto' : 'legacy');
250
+ const waitMs = Math.min(Math.max(1000, Number(args['wait-ms']) || DEFAULT_ANSWER_WAIT_MS), MAX_ANSWER_WAIT_MS);
251
+
252
+ const settled = await awaitPeerAnswer({
253
+ baseUrl: peer.baseUrl,
254
+ secret: peer.secret,
255
+ senderId: me.instanceId,
256
+ sessionId,
257
+ timeoutMs: Number(args.timeout || 300) * 1000,
258
+ waitMs,
259
+ mode,
260
+ onProgress: (info) => process.stderr.write(info.transport === 'sse' ? '·' : '.'),
261
+ });
262
+ process.stderr.write('\n');
263
+ if (settled.status === 'done') {
264
+ console.log(settled.reply);
265
+ return;
266
+ }
267
+ if (settled.status === 'error') throw new Error('对端返回错误: ' + settled.error);
268
+ console.log('timeout after ' + Math.round((settled.elapsedMs || 0) / 1000) + 's');
269
+ process.exitCode = 2;
270
+ }
271
+
272
+ async function cmdEvents(args) {
273
+ const dir = stateDir(args);
274
+ const me = identity(dir);
275
+ const sessionId = String(args.session || args['session-id'] || '');
276
+ // Arguments first: a missing --session must not fall through to a peer lookup.
277
+ if (!args.peer || !sessionId) throw new Error(EVENTS_USAGE);
278
+ const { peer } = findPeer(dir, args.peer);
279
+
280
+ const health = await probePeer({ baseUrl: peer.baseUrl, timeoutMs: 3000, fresh: true });
281
+ if (!capabilityOf(health).includes('stream')) {
282
+ process.stderr.write('对端 /v1/health 未声明 "stream" 能力(0.3.1 无该端点),无法订阅事件\n');
283
+ process.exitCode = 2;
284
+ return;
285
+ }
286
+
287
+ const durationMs = Math.max(1000, Number(args.duration || 300) * 1000);
288
+ process.stderr.write('订阅 ' + peer.name + ' 的 /v1/events (session ' + sessionId + ')\n');
289
+ const out = await readPeerEvents({
290
+ baseUrl: peer.baseUrl,
291
+ secret: peer.secret,
292
+ senderId: me.instanceId,
293
+ sessionId,
294
+ timeoutMs: durationMs,
295
+ onEvent: (info) => {
296
+ if (info.type === 'ping') {
297
+ if (args.verbose) console.log('[ping]');
298
+ return;
299
+ }
300
+ const body = info.reply !== undefined ? String(info.reply) : String(info.error ?? '');
301
+ console.log('[' + (info.status || info.type) + '] elapsedMs=' + (info.elapsedMs ?? '?') + (body ? ' ' + body : ''));
302
+ },
303
+ });
304
+ if (!out.ok) {
305
+ process.stderr.write('订阅结束: ' + out.reason + '\n');
306
+ process.exitCode = 1;
307
+ return;
308
+ }
309
+ process.stderr.write('终态: ' + out.status + '\n');
310
+ }
311
+
312
+ const commands = {
313
+ code: cmdCode,
314
+ pair: cmdPair,
315
+ peers: cmdPeers,
316
+ ask: cmdAsk,
317
+ events: cmdEvents,
318
+ };
319
+ const helpFor = {
320
+ code: CODE_USAGE,
321
+ pair: PAIR_USAGE,
322
+ peers: PEERS_USAGE,
323
+ ask: ASK_USAGE,
324
+ events: EVENTS_USAGE,
325
+ };
326
+
327
+ const args = parseArgs(process.argv.slice(2));
328
+ const name = args._[0];
329
+ if (!name) {
330
+ console.log(USAGE);
331
+ process.exit(args.help || args.h ? 0 : 1);
332
+ }
333
+ if (name === 'help') {
334
+ console.log(USAGE);
335
+ process.exit(0);
336
+ }
337
+ const command = commands[name];
338
+ if (!command) {
339
+ console.error('未知子命令: ' + name);
340
+ console.error(USAGE);
341
+ process.exit(1);
342
+ }
343
+ if (args.help || args.h) {
344
+ console.log(helpFor[name] || USAGE);
345
+ process.exit(0);
346
+ }
347
+ args._ = args._.slice(1);
348
+ command(args).catch((error) => {
349
+ console.error(String(error.message || error));
350
+ process.exit(1);
351
+ });
@@ -0,0 +1,51 @@
1
+ // dsh-lan-peers · CLI surface tests (help is part of the contract).
2
+ import test from 'node:test';
3
+ import assert from 'node:assert/strict';
4
+ import { execFileSync } from 'node:child_process';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const CLI = path.join(path.dirname(fileURLToPath(import.meta.url)), 'cli.mjs');
9
+
10
+ function run(args) {
11
+ return execFileSync(process.execPath, [CLI, ...args], { encoding: 'utf8' });
12
+ }
13
+
14
+ test('root --help lists every subcommand', () => {
15
+ const out = run(['--help']);
16
+ for (const command of ['code', 'pair', 'peers', 'ask', 'events', 'help']) {
17
+ assert.match(out, new RegExp('\\b' + command + '\\b'));
18
+ }
19
+ assert.match(out, /--state-dir/);
20
+ });
21
+
22
+ test('pair --help documents the two-round flow and the forced legacy switch', () => {
23
+ const out = run(['pair', '--help']);
24
+ assert.match(out, /--url/);
25
+ assert.match(out, /--code/);
26
+ assert.match(out, /--legacy-pair/);
27
+ assert.match(out, /--ecdh-pair/);
28
+ assert.match(out, /confirm/);
29
+ });
30
+
31
+ test('events --help documents the subscription options', () => {
32
+ const out = run(['events', '--help']);
33
+ assert.match(out, /--peer/);
34
+ assert.match(out, /--session/);
35
+ assert.match(out, /--duration/);
36
+ assert.match(out, /events/);
37
+ });
38
+
39
+ test('an unknown subcommand fails with usage on stderr', () => {
40
+ assert.throws(
41
+ () => execFileSync(process.execPath, [CLI, 'nope'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }),
42
+ (error) => error.status === 1 && /未知子命令/.test(String(error.stderr)),
43
+ );
44
+ });
45
+
46
+ test('events without --session fails with usage instead of hanging', () => {
47
+ assert.throws(
48
+ () => execFileSync(process.execPath, [CLI, 'events', '--peer', 'x'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }),
49
+ (error) => error.status === 1 && /--session/.test(String(error.message) + String(error.stderr)),
50
+ );
51
+ });