@masstensor/diagnose 0.2.0 → 0.3.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.
@@ -0,0 +1,118 @@
1
+ import { open, stat, rename, writeFile, readFile, unlink } from 'node:fs/promises';
2
+ import { createHash } from 'node:crypto';
3
+ import { resolve } from 'node:path';
4
+ async function hash(path) { const file = await open(path, 'r'); try {
5
+ const value = createHash('sha256');
6
+ for await (const bytes of file.createReadStream({ autoClose: false }))
7
+ value.update(bytes);
8
+ return value.digest('hex');
9
+ }
10
+ finally {
11
+ await file.close();
12
+ } }
13
+ async function grant(operator, input, options) {
14
+ options.signal?.throwIfAborted();
15
+ const id = await operator.start(options.resumeId ? { operation: 'resource.resume', arguments: { id: options.resumeId, resumeToken: options.resumeToken }, reason: input.reason } : input);
16
+ const abort = () => { void operator.cancel(id).catch(() => { }); };
17
+ options.signal?.addEventListener('abort', abort, { once: true });
18
+ try {
19
+ while (true) {
20
+ if (options.signal?.aborted) {
21
+ abort();
22
+ options.signal.throwIfAborted();
23
+ }
24
+ const result = await operator.wait(id, 1000);
25
+ if (!('pending' in result)) {
26
+ if (result.result.status !== 'ok')
27
+ throw new Error(result.result.error ?? result.result.status);
28
+ return result.result.data;
29
+ }
30
+ }
31
+ }
32
+ finally {
33
+ options.signal?.removeEventListener('abort', abort);
34
+ operator.release(id);
35
+ }
36
+ }
37
+ export async function upload(operator, localPath, remotePath, reason, options = {}) {
38
+ const size = (await stat(localPath)).size, checksum = await hash(localPath);
39
+ const resource = await grant(operator, { operation: 'file.transfer', arguments: { direction: 'upload', path: remotePath, size, sha256: checksum, overwrite: options.overwrite ?? false }, reason }, options);
40
+ if (resource.size !== size || resource.sha256 !== checksum)
41
+ throw new Error('Resume target does not match the selected local file');
42
+ const progress = { state: 'uploading', bytes: resource.offset, size, resourceId: resource.id, resumeToken: resource.resumeToken ?? options.resumeToken, sha256: checksum };
43
+ options.progress?.({ ...progress });
44
+ const file = await open(localPath, 'r');
45
+ try {
46
+ const buffer = Buffer.alloc(65536);
47
+ while (progress.bytes < size) {
48
+ options.signal?.throwIfAborted();
49
+ const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, size - progress.bytes), progress.bytes);
50
+ if (!bytesRead)
51
+ throw new Error('Local upload source changed');
52
+ await operator.resource({ id: resource.id, action: 'input', data: buffer.subarray(0, bytesRead).toString('base64') });
53
+ progress.bytes += bytesRead;
54
+ options.progress?.({ ...progress });
55
+ }
56
+ options.signal?.throwIfAborted();
57
+ await operator.resource({ id: resource.id, action: 'commit' });
58
+ progress.state = 'completed';
59
+ options.progress?.({ ...progress });
60
+ return progress;
61
+ }
62
+ finally {
63
+ await file.close();
64
+ }
65
+ }
66
+ export async function download(operator, remotePath, localPath, reason, options = {}) {
67
+ const destination = resolve(localPath), partial = destination + '.diagnose.part', sidecar = destination + '.diagnose.json';
68
+ try {
69
+ await stat(destination);
70
+ if (!options.overwrite)
71
+ throw new Error('Local target exists; explicit overwrite is required');
72
+ }
73
+ catch (error) {
74
+ if (error.code !== 'ENOENT')
75
+ throw error;
76
+ }
77
+ let saved;
78
+ try {
79
+ saved = JSON.parse(await readFile(sidecar, 'utf8'));
80
+ }
81
+ catch (error) {
82
+ if (error.code !== 'ENOENT')
83
+ throw error;
84
+ }
85
+ const effective = options.resumeId ? options : saved ? { ...options, resumeId: saved.resourceId, resumeToken: saved.resumeToken } : options;
86
+ const resource = await grant(operator, { operation: 'file.transfer', arguments: { direction: 'download', path: remotePath }, reason }, effective);
87
+ if (saved && saved.sha256 !== resource.sha256)
88
+ throw new Error('Partial download belongs to a different source');
89
+ const file = await open(partial, 'a+', 0o600), bytes = (await file.stat()).size;
90
+ const progress = { state: 'downloading', bytes, size: resource.size, resourceId: resource.id, resumeToken: resource.resumeToken ?? effective.resumeToken, sha256: resource.sha256 };
91
+ await writeFile(sidecar, JSON.stringify(progress), { mode: 0o600 });
92
+ options.progress?.({ ...progress });
93
+ try {
94
+ while (progress.bytes < resource.size) {
95
+ options.signal?.throwIfAborted();
96
+ const result = await operator.resource({ id: resource.id, action: 'read', cursor: progress.bytes });
97
+ const block = Buffer.from(result.data, 'base64');
98
+ if (!block.length || result.nextOffset !== progress.bytes + block.length)
99
+ throw new Error('Invalid download response');
100
+ await file.writeFile(block);
101
+ progress.bytes += block.length;
102
+ options.progress?.({ ...progress });
103
+ }
104
+ await file.sync();
105
+ }
106
+ finally {
107
+ await file.close();
108
+ }
109
+ if (progress.bytes !== resource.size || await hash(partial) !== resource.sha256)
110
+ throw new Error('Download integrity mismatch; destination untouched');
111
+ options.signal?.throwIfAborted();
112
+ await rename(partial, destination);
113
+ await unlink(sidecar);
114
+ await operator.resource({ id: resource.id, action: 'close' });
115
+ progress.state = 'completed';
116
+ options.progress?.({ ...progress });
117
+ return progress;
118
+ }
@@ -1,15 +1,16 @@
1
1
  {
2
2
  "name": "@masstensor/diagnose",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@masstensor/diagnose",
9
- "version": "0.2.0",
9
+ "version": "0.3.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@modelcontextprotocol/sdk": "1.32.2",
13
+ "node-pty": "1.1.0",
13
14
  "noise-handshake": "4.2.1",
14
15
  "serialport": "13.0.0",
15
16
  "ws": "8.23.0",
@@ -26,7 +27,8 @@
26
27
  },
27
28
  "engines": {
28
29
  "node": ">=22.18.0"
29
- }
30
+ },
31
+ "hasInstallScript": true
30
32
  },
31
33
  "node_modules/@hono/node-server": {
32
34
  "version": "2.1.8",
@@ -1603,6 +1605,22 @@
1603
1605
  "node-gyp-build-test": "build-test.js"
1604
1606
  }
1605
1607
  },
1608
+ "node_modules/node-pty": {
1609
+ "version": "1.1.0",
1610
+ "resolved": "https://registry.npmjs.org/node-pty/-/node-pty-1.1.0.tgz",
1611
+ "integrity": "sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg==",
1612
+ "hasInstallScript": true,
1613
+ "license": "MIT",
1614
+ "dependencies": {
1615
+ "node-addon-api": "^7.1.0"
1616
+ }
1617
+ },
1618
+ "node_modules/node-pty/node_modules/node-addon-api": {
1619
+ "version": "7.1.1",
1620
+ "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz",
1621
+ "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==",
1622
+ "license": "MIT"
1623
+ },
1606
1624
  "node_modules/noise-handshake": {
1607
1625
  "version": "4.2.1",
1608
1626
  "resolved": "https://registry.npmjs.org/noise-handshake/-/noise-handshake-4.2.1.tgz",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@masstensor/diagnose",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "End-to-end encrypted, user-approved remote diagnostics over a blind relay",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -31,10 +31,12 @@
31
31
  "build": "tsc",
32
32
  "check": "tsc --noEmit",
33
33
  "test": "npm run build && node --experimental-strip-types --test --test-concurrency=1 test/*.test.ts",
34
- "prepack": "npm run build"
34
+ "prepack": "npm run build",
35
+ "postinstall": "node --input-type=module -e \"import { existsSync } from 'node:fs'; if (existsSync('dist/prepare-pty.js')) await (await import('./dist/prepare-pty.js')).preparePty();\""
35
36
  },
36
37
  "dependencies": {
37
38
  "@modelcontextprotocol/sdk": "1.32.2",
39
+ "node-pty": "1.1.0",
38
40
  "noise-handshake": "4.2.1",
39
41
  "serialport": "13.0.0",
40
42
  "ws": "8.23.0",
package/src/cli.ts CHANGED
@@ -8,23 +8,45 @@ import { Operator } from './operator.js';
8
8
  import { Audit, safeText } from './util.js';
9
9
  import { serveMcp } from './mcp.js';
10
10
  import type { TaskInput } from './schema.js';
11
+ import { SessionResources } from './resources.js';
12
+ import { homedir } from 'node:os';
13
+ import { join } from 'node:path';
14
+ import { upload, download, type TransferOptions } from './transfers.js';
15
+ import { forward, type Forward } from './forward.js';
16
+ import { spawn } from 'node:child_process';
17
+ import { parseArgs } from 'node:util';
18
+ import { setTimeout as delay } from 'node:timers/promises';
19
+
20
+ async function attachTerminal(operator: Operator, id: string): Promise<void> {
21
+ let done = false, cursor = 0; const wasRaw = stdin.isRaw;
22
+ const input = (bytes: Buffer) => { const escape = bytes.indexOf(0x1d); if (escape >= 0) { done = true; bytes = bytes.subarray(0, escape); } if (bytes.length) void operator.resource({ id, action: 'input', data: bytes.toString('base64') }).catch(() => { done = true; }); };
23
+ const resize = () => { void operator.resource({ id, action: 'resize', cols: Math.max(20, Math.min(500, stdout.columns ?? 100)), rows: Math.max(5, Math.min(200, stdout.rows ?? 30)) }).catch(() => {}); };
24
+ stdin.setRawMode(true); stdin.on('data', input); stdin.resume(); stdout.on('resize', resize); resize();
25
+ stdout.write('\r\n[Ctrl+] detaches; Ctrl+C is sent to the remote terminal]\r\n');
26
+ try { while (!done) { const value = await operator.resource({ id, action: 'read', cursor }) as { cursor: number; records: { data: string }[]; ended: boolean }; cursor = value.cursor; for (const record of value.records) stdout.write(Buffer.from(record.data, 'base64')); if (value.ended) break; await new Promise(resolve => setTimeout(resolve, 25)); } }
27
+ finally { stdin.off('data', input); stdout.off('resize', resize); stdin.setRawMode(wasRaw); stdin.pause(); stdout.write('\r\n'); }
28
+ }
11
29
 
12
30
  async function main(): Promise<void> {
13
- const [command = 'help', ...args] = process.argv.slice(2);
14
- const relay = args[0] ?? 'https://diagnose.fenginwind.com';
15
- if (args.length > 1) throw new Error('Usage: diagnose start|connect|mcp [relay-url]');
31
+ const { positionals, values } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { 'session-minutes': { type: 'string', default: '60' }, 'idle-minutes': { type: 'string', default: '10' } } });
32
+ const [command = 'help', relay = 'https://diagnose.fenginwind.com'] = positionals;
33
+ if (positionals.length > 2) throw new Error('Usage: diagnose start|connect|terminal|mcp [relay-url]');
34
+ const sessionMinutes = Number(values['session-minutes']), idleMinutes = Number(values['idle-minutes']);
35
+ if (![sessionMinutes, idleMinutes].every(value => Number.isInteger(value) && value >= 0 && value <= 10080)) throw new Error('Timeouts must be 0..10080 minutes; 0 disables endpoint timeout (relay maximum 7 days)');
16
36
  if (command === 'mcp') { await serveMcp(relay); return; }
17
- if (!['start', 'connect'].includes(command)) { console.log('diagnose start|connect|mcp [relay-url]\nNode.js >=22.18. Pairing codes are entered interactively, never as arguments.'); return; }
37
+ if (!['start', 'connect', 'terminal'].includes(command)) { console.log('diagnose start|connect|terminal|mcp [relay-url]\nNode.js >=22.18. Pairing codes are entered interactively, never as arguments.'); return; }
18
38
  if (!stdin.isTTY || !stdout.isTTY) throw new Error('Interactive terminal required. AI clients should use diagnose mcp.');
19
39
  const rl = createInterface({ input: stdin, output: stdout });
20
40
  const shutdown = new AbortController(); let peer: Peer | undefined, engine: ProbeEngine | undefined;
41
+ const forwards = new Map<string, Forward>();
42
+ let resources: SessionResources | undefined, promptActive = false, secretPending: Promise<void> | undefined;
21
43
  let localCommand: (value: string) => boolean = () => false;
22
- const stop = () => { shutdown.abort(); peer?.close('User ended session'); rl.close(); };
23
- rl.on('SIGINT', stop); process.once('SIGTERM', stop);
44
+ const stop = () => { shutdown.abort(); peer?.close('User ended session'); void resources?.revoke().catch(() => {}); rl.close(); };
45
+ rl.on('SIGINT', stop); process.once('SIGINT', stop); process.once('SIGTERM', stop);
24
46
  rl.once('close', () => { shutdown.abort(); peer?.close('User terminal closed'); });
25
47
  const ask = async (text: string, signal = shutdown.signal, taskApproval = false): Promise<boolean> => {
26
48
  while (true) {
27
- const answer = (await rl.question(safeText(text) + ' [y/N] ', { signal })).trim();
49
+ let answer: string; promptActive = true; try { answer = (await rl.question(safeText(text) + ' [y/N] ', { signal })).trim(); } finally { promptActive = false; }
28
50
  if (!localCommand(answer)) return answer.toLowerCase() === 'y';
29
51
  signal.throwIfAborted();
30
52
  if (taskApproval && engine?.permissionMode === 'auto') return true;
@@ -32,10 +54,12 @@ async function main(): Promise<void> {
32
54
  };
33
55
  try {
34
56
  if (command === 'start') {
35
- const audit = new Audit(); const code = createCode();
36
- peer = new Peer({ role: 'host', code, relay, accept: async ({ label, fingerprint, signal }) => {
57
+ const firstAudit = new Audit(); resources = new SessionResources(join(homedir(), '.diagnose', 'resources'), firstAudit); let sessions = 0;
58
+ while (!shutdown.signal.aborted) {
59
+ const audit = sessions++ === 0 ? firstAudit : new Audit(); const code = createCode();
60
+ peer = new Peer({ role: 'host', code, relay, sessionMs: sessionMinutes * 60000, accept: async ({ label, fingerprint, signal }) => {
37
61
  console.log(`\nRequested by: ${safeText(label)} (self-asserted identity)\nFingerprint: ${fingerprint}\nResults will be available to the diagnostician and their AI provider.`);
38
- console.log('Choose y: approve each task/batch and its transfer.\nChoose a: grant automatic execution AND transmission for this temporary session.\nAUTO: commands have your OS permissions; results go to the diagnostician and their AI without further prompts. Text redaction is best-effort; binary data is not redacted.\nRevoke locally with "permissions ask", cancel with "cancel", or end with Ctrl+C. Already transmitted data cannot be recalled.');
62
+ console.log('Choose y: approve each task/batch and its transfer.\nChoose a: grant automatic execution AND transmission for this temporary session.\nAUTO: commands have your OS permissions; results go to the diagnostician and their AI without further prompts. Raw terminal, file and tunnel channels are NOT redacted. A channel grant includes continuing input/output within its scope.\nRevoke locally with "permissions ask", cancel with "cancel", or end with Ctrl+C. Already transmitted data cannot be recalled.');
39
63
  const answer = (await rl.question('Allow this temporary diagnostic session? [y / a=auto / N] ', { signal })).trim().toLowerCase();
40
64
  const allowed = answer === 'y' || answer === 'a';
41
65
  if (answer === 'a') engine!.setPermissionMode('auto');
@@ -44,11 +68,11 @@ async function main(): Promise<void> {
44
68
  engine = new ProbeEngine(peer, async request => {
45
69
  console.log(`\n[${request.stage === 'execute' ? 'EXECUTION APPROVAL' : 'TRANSFER APPROVAL'}] ${request.task.operation}\nTask: ${request.task.id}\nSHA256: ${request.digest}\n${safeText(request.preview)}\n`);
46
70
  return ask(request.stage === 'execute' ? 'Allow exactly this operation? Commands run with your OS permissions.' : `Send these results (${request.bytes ?? 0} output bytes plus metadata)?`, request.signal, true);
47
- }, audit, message => console.log(safeText(message)));
71
+ }, audit, message => console.log(safeText(message)), { resources, idleMs: idleMinutes * 60000, lifetimeMs: sessionMinutes * 60000 });
48
72
  let active = false, autoRequestedAt = 0;
49
- peer.on('active', () => { active = true; console.log(`Session permissions: ${engine!.permissionMode}. Local commands: permissions, permissions auto, permissions ask, cancel, exit.`); });
73
+ peer.on('active', () => { active = true; console.log(`Session permissions: ${engine!.permissionMode}. Local commands: permissions, permissions auto, permissions ask, jobs, recover <id>, secret <id>, cancel, exit.`); });
50
74
  localCommand = value => {
51
- if (!active) return false;
75
+ if (!active && !['jobs', 'cancel', 'exit', 'permissions ask'].includes(value) && !value.startsWith('recover ') && !value.startsWith('secret ')) return false;
52
76
  if (value === 'permissions') { console.log(`Permission mode: ${engine!.permissionMode}. AUTO means automatic execution AND transmission to the diagnostician/AI. Use permissions ask to revoke and cancel active work.`); return true; }
53
77
  if (value === 'permissions auto') { autoRequestedAt = Date.now(); console.log('AUTO grants this session automatic execution with your OS permissions AND automatic result transmission. Binary output is not redacted. Type "permissions allow-auto" within 60 seconds to grant, or "permissions ask" to decline.'); return true; }
54
78
  if (value === 'permissions allow-auto') {
@@ -56,20 +80,46 @@ async function main(): Promise<void> {
56
80
  else console.log('No pending grant. First type "permissions auto" and read its explanation.');
57
81
  return true;
58
82
  }
59
- if (value === 'permissions ask') { autoRequestedAt = 0; engine!.setPermissionMode('ask'); console.log('Approval required. Automatic permissions revoked; any active work is cancelled.'); return true; }
60
- if (value === 'cancel') { engine!.cancelAll(); console.log('Cancellation requested for the current task/batch.'); return true; }
83
+ if (value === 'permissions ask') { autoRequestedAt = 0; engine!.setPermissionMode('ask'); void resources!.revoke().catch(error => console.error(safeText((error as Error).message))); console.log('Approval required. Automatic permissions revoked; any active work is cancelled.'); return true; }
84
+ if (value === 'cancel') { engine!.cancelAll(); void resources!.revoke().catch(error => console.error(safeText((error as Error).message))); console.log('Cancellation requested for the current task/batch and retained resources.'); return true; }
85
+ if (value === 'jobs') { console.log(safeText(JSON.stringify(resources!.listLocal(), null, 2))); return true; }
86
+ if (value.startsWith('recover ')) { const id = value.slice(8).trim(); console.log(`Resource: ${id}\nNew recovery credential (share privately): ${resources!.renewCredential(id)}`); return true; }
87
+ if (value.startsWith('secret ')) {
88
+ if (promptActive || secretPending) { console.log('Finish the current approval before local hidden input.'); return true; }
89
+ if (process.platform === 'win32') { console.log('Hidden local input is not yet validated on Windows; use native local OS authentication.'); return true; }
90
+ const id = value.slice(7).trim();
91
+ secretPending = (async () => {
92
+ console.log('Local input goes directly to the approved process. Use only a trusted foreground program; its output can still be transmitted.');
93
+ const wasRaw = stdin.isRaw; rl.pause(); stdin.setRawMode(false);
94
+ try { const value = await new Promise<Buffer>((resolveInput, reject) => { const chunks: Buffer[] = []; const child = spawn('/bin/bash', ['-c', 'IFS= read -r -s -p "Hidden local input: " v; printf "%s" "$v"'], { stdio: ['inherit', 'pipe', 'inherit'] }); child.stdout.on('data', bytes => chunks.push(bytes)); child.on('error', reject); child.on('close', code => code === 0 ? resolveInput(Buffer.concat(chunks)) : reject(new Error('Local input cancelled'))); }); await resources!.localInput(id, Buffer.concat([value, Buffer.from('\n')])); value.fill(0); stdout.write('\nLocal input sent.\n'); }
95
+ finally { stdin.setRawMode(wasRaw); rl.resume(); }
96
+ })().catch(error => console.error(safeText((error as Error).message))).finally(() => { secretPending = undefined; });
97
+ return true;
98
+ }
61
99
  if (value === 'exit') { stop(); return true; }
62
100
  return false;
63
101
  };
64
- rl.on('line', value => { try { if (active && !localCommand(value.trim())) console.log('Local commands: permissions, permissions auto, permissions ask, cancel, exit.'); } catch (error) { console.error(safeText((error as Error).message)); stop(); } });
65
- await peer.open();
66
- console.log(`Relay: ${relay}\nAudit: ${audit.path}\nPairing code (10 minutes, share privately):\n${code}\nCtrl+C ends the session and cancels active tasks.`);
67
- console.log(`Session ended: ${safeText(await peer.ended)}`);
102
+ const onLocalLine = (value: string) => { try { if (!localCommand(value.trim())) console.log('Local commands: permissions, permissions auto, permissions ask, jobs, recover <id>, secret <id>, cancel, exit.'); } catch (error) { console.error(safeText((error as Error).message)); stop(); } };
103
+ rl.on('line', onLocalLine);
104
+ try {
105
+ await peer.open();
106
+ console.log(`Relay: ${relay}\nAudit: ${audit.path}\nPairing code (10 minutes, share privately):\n${code}\nCtrl+C ends the session and cancels active tasks.`);
107
+ console.log(`Session ended: ${safeText(await peer.ended)}`);
108
+ } catch (error) { if (!shutdown.signal.aborted) console.log(`Relay unavailable: ${safeText((error as Error).message)}. Retained work remains local; retrying in 3 seconds.`); await delay(3000, undefined, { signal: shutdown.signal }).catch(() => {}); }
109
+ finally { rl.off('line', onLocalLine); }
110
+ active = false; if (secretPending) await secretPending;
111
+ if (!shutdown.signal.aborted) console.log('Probe is still running. Retained resources can be resumed after a NEW pairing and local authorization; commands are never replayed. Ctrl+C closes all resources.');
112
+ }
68
113
  } else {
69
114
  const code = (await rl.question('Pairing code: ', { signal: shutdown.signal })).trim();
70
115
  const label = await rl.question('Your label / AI provider: ', { signal: shutdown.signal });
71
116
  peer = new Peer({ role: 'join', code, relay, label }); const operator = new Operator(peer);
72
- await peer.open(); console.log(`Connected. Fingerprint: ${peer.fingerprint}\nEnter task JSON. Use batch.run with {steps:[{operation,arguments}],stopOnError:true}; or process.script with {interpreter,script,args?,cwd?,timeoutMs?}.\nExample: {"operation":"system.inspect","arguments":{},"reason":"Inspect environment"}\nOther commands: cancel <task-id>, wait <task-id>, exit. Requests return immediately. Both endpoints need v0.2+ for batches/scripts.`);
117
+ if (command === 'terminal') {
118
+ await peer.open(); const result = await operator.run({ operation: 'process.open', arguments: { pty: true }, reason: 'Open an interactive terminal with continuing raw input/output and persistent shell context' });
119
+ if (result.result.status !== 'ok') throw new Error(result.result.error ?? result.result.status);
120
+ rl.removeAllListeners('SIGINT'); rl.removeAllListeners('close'); rl.close(); await attachTerminal(operator, (result.result.data as { id: string }).id); return;
121
+ }
122
+ await peer.open(); console.log(`Connected. Fingerprint: ${peer.fingerprint}\nEnter task JSON: batch.run, process.script, process.open (pty/stdin), file.transfer, net.forward, resource.resume.\nCommands: cancel <task>, wait <task>, resources, read <resource> [cursor], input <resource> <JSON string>, resize <resource> <cols> <rows>, signal <resource> <SIGINT>, close <resource>, forward <resource> [localPort], upload/download <JSON>, exit.\nLive resources require v0.3+ on both endpoints. diagnose terminal opens a native terminal.`);
73
123
  peer.ended.then(() => stop());
74
124
  while (!shutdown.signal.aborted) {
75
125
  const line = (await rl.question('diagnose> ', { signal: shutdown.signal })).trim();
@@ -77,10 +127,16 @@ async function main(): Promise<void> {
77
127
  try {
78
128
  if (line.startsWith('cancel ')) { await operator.cancel(line.slice(7).trim()); console.log('Cancellation requested'); }
79
129
  else if (line.startsWith('wait ')) console.log(safeText(JSON.stringify(await operator.wait(line.slice(5).trim(), 1000), null, 2)));
130
+ else if (line === 'resources') console.log(JSON.stringify(await operator.resource({ action: 'list' }), null, 2));
131
+ else if (line.startsWith('read ')) { const [, id, cursor] = line.split(/\s+/); const value = await operator.resource({ id, action: 'read', cursor: Number(cursor ?? 0) }) as { records?: { stream: string; data: string }[] }; console.log(safeText(JSON.stringify({ ...value, ...(value.records ? { records: value.records.map(record => ({ stream: record.stream, text: Buffer.from(record.data, 'base64').toString() })) } : {}) }, null, 2))); }
132
+ else if (line.startsWith('input ')) { const match = /^input (\S+) (.+)$/.exec(line); if (!match) throw new Error('input <id> <JSON string>'); console.log(await operator.resource({ id: match[1], action: 'input', data: Buffer.from(JSON.parse(match[2]) as string).toString('base64') })); }
133
+ else if (/^(resize|signal|close) /.test(line)) { const [action, id, a, b] = line.split(/\s+/); if (action === 'close' && forwards.has(id)) { await forwards.get(id)!.close(); forwards.delete(id); } else console.log(await operator.resource({ id, action: action as 'resize' | 'signal' | 'close', ...(action === 'resize' ? { cols: Number(a), rows: Number(b) } : action === 'signal' ? { signal: (a ?? 'SIGINT') as 'SIGINT' } : {}) })); }
134
+ else if (line.startsWith('forward ')) { const [, id, port] = line.split(/\s+/); if (forwards.has(id) && !forwards.get(id)!.closed) throw new Error('Forward already open'); const listener = await forward(operator, id, Number(port ?? 0)); forwards.set(id, listener); console.log(`Forward active: ${listener.direction} ${listener.host}:${listener.port}; close ${id} releases both endpoints.`); }
135
+ else if (/^(upload|download) /.test(line)) { const separator = line.indexOf(' '), action = line.slice(0, separator), options = JSON.parse(line.slice(separator + 1)) as TransferOptions & { localPath: string; remotePath: string; reason: string }; const settings = { ...options, signal: shutdown.signal, progress: (value: unknown) => console.log(safeText(JSON.stringify(value))) }; console.log(await (action === 'upload' ? upload(operator, options.localPath, options.remotePath, options.reason, settings) : download(operator, options.remotePath, options.localPath, options.reason, settings))); }
80
136
  else if (line) console.log(`Task: ${await operator.start(JSON.parse(line) as TaskInput)}`);
81
137
  } catch (error) { console.error(safeText((error as Error).message)); }
82
138
  }
83
139
  }
84
- } finally { stop(); }
140
+ } finally { for (const value of forwards.values()) await value.close(); stop(); await resources?.revoke(); }
85
141
  }
86
142
  main().catch(error => { console.error(safeText((error as Error).name === 'AbortError' ? 'Session ended' : (error as Error).message)); process.exitCode = 1; });
@@ -0,0 +1,17 @@
1
+ import os from 'node:os';
2
+ import { access } from 'node:fs/promises';
3
+ import { constants } from 'node:fs';
4
+ import { delimiter, join } from 'node:path';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { SerialPort } from 'serialport';
7
+ export async function inspectSystem(): Promise<Record<string, unknown>> {
8
+ const commands: Record<string, string> = {};
9
+ for (const name of ['node', 'sh', 'bash', 'zsh', 'pwsh', 'powershell', 'cmd', 'python3', 'git', 'curl', 'sudo', 'ssh']) {
10
+ outer: for (const directory of (process.env.PATH ?? '').split(delimiter)) for (const suffix of process.platform === 'win32' ? ['', '.exe', '.cmd', '.bat'] : ['']) {
11
+ const path = join(directory, name + suffix);
12
+ try { await access(path, process.platform === 'win32' ? constants.F_OK : constants.X_OK); commands[name] = path; break outer; } catch {}
13
+ }
14
+ }
15
+ const elevated = process.platform === 'win32' ? /S-1-16-(12288|16384)/.test(spawnSync('whoami', ['/groups'], { encoding: 'utf8', timeout: 3000, windowsHide: true }).stdout ?? '') : process.geteuid?.() === 0;
16
+ return { platform: process.platform, arch: process.arch, release: os.release(), node: process.version, hostname: os.hostname(), cwd: process.cwd(), home: os.homedir(), username: os.userInfo().username, elevated, shell: process.platform === 'win32' ? process.env.ComSpec ?? 'cmd.exe' : process.env.SHELL ?? '/bin/sh', commands, serialPorts: await SerialPort.list(), protocol: 1, version: '0.3.0', capabilities: ['batch', 'script', 'process-stdin', 'pty', 'terminal-resize', 'signals', 'concurrent-jobs', 'encrypted-output-journal', 'resource-resume', 'binary-transfer', 'filesystem', 'local-forward', 'remote-forward', 'socks5'] };
17
+ }
package/src/engine.ts CHANGED
@@ -2,6 +2,9 @@ import { Peer } from './peer.js';
2
2
  import { execute, prepareWrite, type Execution } from './executor.js';
3
3
  import { CHUNK_SIZE, MAX_OUTPUT, type Approval, type ApprovalHandler, type AtomicTask, type BatchTask, type Result, type Task, type WireMessage } from './schema.js';
4
4
  import { Audit, digest, redact, safeText } from './util.js';
5
+ import { SessionResources, resourceOperation } from './resources.js';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { dirname, join, basename } from 'node:path';
5
8
 
6
9
  export type PermissionMode = 'ask' | 'auto';
7
10
  function aborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
@@ -16,9 +19,12 @@ function aborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
16
19
  export class ProbeEngine {
17
20
  private jobs = new Map<string, AbortController>();
18
21
  private seen = new Set<string>();
19
- private idle: NodeJS.Timeout;
20
- private lifetime: NodeJS.Timeout;
22
+ private idle?: NodeJS.Timeout;
23
+ private lifetime?: NodeJS.Timeout;
21
24
  private mode: PermissionMode = 'ask';
25
+ private owner = randomUUID();
26
+ readonly resources: SessionResources;
27
+ private approvalQueue: Promise<void> = Promise.resolve();
22
28
  get permissionMode(): PermissionMode { return this.mode; }
23
29
  // Local API only. No wire message or task argument can change permission mode.
24
30
  setPermissionMode(mode: PermissionMode): void {
@@ -27,29 +33,38 @@ export class ProbeEngine {
27
33
  this.audit.record('permissions.changed', { from: this.mode, to: mode, automaticExecution: mode === 'auto', automaticTransfer: mode === 'auto' });
28
34
  this.mode = mode;
29
35
  if (mode === 'ask') this.cancelAll();
36
+ if (mode === 'ask') void this.resources.revoke().catch(() => this.peer.close('Resource cleanup failed'));
30
37
  this.notice(`Permission mode: ${mode}${mode === 'auto' ? ' (automatic execution AND transmission)' : ' (active work cancelled; approval required)'}`);
31
38
  }
32
39
  cancelAll(): void {
33
40
  for (const [id, controller] of this.jobs) { this.audit.record('task.cancel-requested', { id, source: 'local' }); controller.abort(); }
41
+ void this.resources.revoke(this.owner).catch(() => this.peer.close('Resource cleanup failed'));
34
42
  }
35
- constructor(private peer: Peer, private approve: ApprovalHandler, readonly audit: Audit, private notice: (message: string) => void = () => {}) {
36
- this.idle = setTimeout(() => peer.close('Idle timeout'), 600000);
37
- this.lifetime = setTimeout(() => peer.close('Session lifetime exceeded'), 3600000);
43
+ constructor(private peer: Peer, private approve: ApprovalHandler, readonly audit: Audit, private notice: (message: string) => void = () => {}, options: { resources?: SessionResources; idleMs?: number; lifetimeMs?: number } = {}) {
44
+ this.resources = options.resources ?? new SessionResources(join(dirname(audit.path), basename(audit.path) + '.resources'), audit);
45
+ this.resources.setAudit(audit);
46
+ if (options.idleMs !== 0) this.idle = setTimeout(() => peer.close('Idle timeout'), options.idleMs ?? 600000);
47
+ if (options.lifetimeMs !== 0) this.lifetime = setTimeout(() => peer.close('Session lifetime exceeded'), options.lifetimeMs ?? 3600000);
38
48
  peer.on('message', (message: WireMessage) => {
39
- this.idle.refresh();
40
- if (message.type === 'task.cancel') { try { audit.record('task.cancel-requested', { id: message.id, source: 'operator' }); this.jobs.get(message.id)?.abort(); } catch { peer.close('Audit unavailable'); } return; }
49
+ this.idle?.refresh();
50
+ if (message.type === 'resource.request') { void this.resources.control(this.owner, message.request).then(value => this.peer.send({ type: 'resource.result', requestId: message.requestId, value }), error => this.peer.send({ type: 'resource.result', requestId: message.requestId, error: redact((error as Error).message).slice(0, 2000) })).catch(() => {}); return; }
51
+ if (message.type === 'task.cancel') { try { audit.record('task.cancel-requested', { id: message.id, source: 'operator' }); this.jobs.get(message.id)?.abort(); void this.resources.control(this.owner, { id: message.id, action: 'close', cursor: 0, limit: 65536, eof: false }).catch(() => {}); } catch { peer.close('Audit unavailable'); } return; }
41
52
  if (message.type !== 'task.request') { peer.close('Unexpected operator message'); return; }
42
53
  const task = message.task;
43
54
  if (this.seen.has(task.id)) { void this.reply(task.id, { status: 'duplicate' }); return; }
44
- if (this.jobs.size || this.seen.size >= 1000) { void this.reply(task.id, { status: 'error', error: 'Probe busy or session task limit reached; submit related operations as batch.run' }); return; }
55
+ if (this.jobs.size >= 4 || this.seen.size >= 1000) { void this.reply(task.id, { status: 'error', error: 'Four concurrent task slots or session task limit reached; wait or close unused work' }); return; }
45
56
  const controller = new AbortController(); this.jobs.set(task.id, controller); this.seen.add(task.id);
46
57
  void this.run(task, controller);
47
58
  });
48
- peer.on('closed', () => { clearTimeout(this.idle); clearTimeout(this.lifetime); for (const controller of this.jobs.values()) controller.abort(); try { audit.record('session.closed', {}); } catch { /* Session is already closed. */ } });
59
+ peer.on('closed', () => { clearTimeout(this.idle); clearTimeout(this.lifetime); for (const controller of this.jobs.values()) controller.abort(); void this.resources.disconnect(this.owner).catch(() => {}); try { audit.record('session.closed', {}); } catch { /* Session is already closed. */ } });
49
60
  }
50
61
  private async reply(id: string, result: Result): Promise<void> { await this.peer.send({ type: 'task.result', id, result }).catch(() => {}); }
51
62
  private async finish(id: string, result: Result): Promise<void> { this.jobs.delete(id); await this.reply(id, result); }
52
- private async permission(request: Approval): Promise<boolean> {
63
+ private permission(request: Approval): Promise<boolean> {
64
+ const result = this.approvalQueue.then(() => this.decidePermission(request));
65
+ this.approvalQueue = result.then(() => {}, () => {}); return result;
66
+ }
67
+ private async decidePermission(request: Approval): Promise<boolean> {
53
68
  request.signal!.throwIfAborted();
54
69
  if (this.mode === 'auto') {
55
70
  this.audit.record('task.auto-approved', { id: request.task.id, stage: request.stage, digest: request.digest, ...(request.bytes === undefined ? {} : { bytes: request.bytes }) });
@@ -69,9 +84,10 @@ export class ProbeEngine {
69
84
  signal.throwIfAborted();
70
85
  this.audit.record('task.executing', { id: task.id, ...(parentId ? { parentId } : {}) });
71
86
  this.notice(`Executing ${task.operation} ${task.id}`);
72
- const execution = await execute(task, signal, write);
87
+ const execution: Execution = resourceOperation(task.operation) ? { result: { status: 'ok', data: await this.resources.open(task, this.owner, signal) }, outputs: [] } : await execute(task, signal, write);
73
88
  if (execution.outputs.some(item => item.truncated)) execution.result.truncated = true;
74
89
  if (task.operation === 'file.write' && execution.result.status === 'ok') this.audit.record('task.file-changed', { id: task.id, ...(parentId ? { parentId } : {}), ...(execution.result.data as Record<string, unknown>) });
90
+ if (['file.mkdir', 'file.remove', 'file.rename', 'file.chmod'].includes(task.operation) && execution.result.status === 'ok') this.audit.record('task.filesystem-changed', { id: task.id, operation: task.operation, ...(parentId ? { parentId } : {}), ...task.arguments });
75
91
  this.audit.record('task.collected', { id: task.id, ...(parentId ? { parentId } : {}), bytes: execution.outputs.reduce((n, item) => n + item.bytes.length, 0), status: execution.result.status, streams: execution.outputs.map(item => ({ stream: item.stream, bytes: item.bytes.length, encoding: item.encoding })) });
76
92
  return execution;
77
93
  }
@@ -116,6 +132,7 @@ export class ProbeEngine {
116
132
  const { signal } = controller; const hash = digest(task);
117
133
  try {
118
134
  const steps = task.operation === 'batch.run' ? task.arguments.steps : [task];
135
+ if (task.operation === 'batch.run' && steps.some(step => resourceOperation(step.operation))) throw new Error('Open interactive/transfer/forward resources separately; their subsequent actions share one approved scope');
119
136
  if (task.operation === 'batch.run') this.audit.record('task.requested', { id: task.id, operation: task.operation, digest: hash, steps: steps.length });
120
137
  for (const step of steps) this.recordRequest(step, task.operation === 'batch.run' ? task.id : undefined);
121
138
  const writes = new Map(steps.map(step => [step.id, prepareWrite(step)]));
@@ -123,6 +140,9 @@ export class ProbeEngine {
123
140
  const preview = safeText(JSON.stringify(task, null, 2) + details) + (steps.some(step => step.operation.startsWith('serial.')) ? '\nSerial control lines may reset the device.' : '');
124
141
  if (!await this.permission({ stage: 'execute', task, digest: hash, preview, signal })) { this.audit.record('task.denied', { id: task.id }); await this.finish(task.id, { status: 'denied' }); return; }
125
142
  signal.throwIfAborted(); if (digest(task) !== hash) throw new Error('Task parameters changed after approval');
143
+ const continuous = resourceOperation(task.operation);
144
+ if (continuous && !await this.permission({ stage: 'send', task, digest: hash, preview: `${preview}\nThis grants continuing raw bidirectional input/output, file bytes or tunnel traffic for this resource. No automatic redaction. Further input/actions within the approved handle do not prompt again. retainOnDisconnect keeps the resource alive while this host CLI remains running.`, signal })) { await this.finish(task.id, { status: 'denied' }); return; }
145
+ signal.throwIfAborted(); if (digest(task) !== hash) throw new Error('Task parameters changed after approval');
126
146
  this.audit.record('task.approved', { id: task.id, digest: hash, mode: this.mode });
127
147
  await this.peer.send({ type: 'task.started', id: task.id, digest: hash });
128
148
  const execution = task.operation === 'batch.run' ? await this.runBatch(task, signal, writes, hash) : await this.runAtomic(task, signal, writes.get(task.id));
@@ -130,12 +150,13 @@ export class ProbeEngine {
130
150
  if (task.operation === 'batch.run') this.audit.record('task.collected', { id: task.id, bytes: count, status: execution.result.status });
131
151
  signal.throwIfAborted();
132
152
  const outputPreview = execution.outputs.map(item => `[${item.stream}/${item.encoding}; ${item.bytes.length} bytes]\n${item.encoding === 'utf8' ? item.bytes.toString('utf8') : `BINARY: no automatic redaction. Preview shows first 256 bytes; approval sends all ${item.bytes.length} bytes.\n${item.bytes.subarray(0, 256).toString('hex')}`}`).join('\n');
133
- if (!await this.permission({ stage: 'send', task, digest: hash, preview: JSON.stringify(execution.result) + '\n' + outputPreview, bytes: count, signal })) { this.audit.record('task.send-denied', { id: task.id }); await this.finish(task.id, { status: 'denied', error: 'Collected locally; user declined transfer' }); return; }
153
+ if (!continuous && !await this.permission({ stage: 'send', task, digest: hash, preview: JSON.stringify(execution.result) + '\n' + outputPreview, bytes: count, signal })) { this.audit.record('task.send-denied', { id: task.id }); await this.finish(task.id, { status: 'denied', error: 'Collected locally; user declined transfer' }); return; }
134
154
  signal.throwIfAborted(); this.audit.record('task.transfer-approved', { id: task.id, bytes: count, mode: this.mode });
135
155
  await this.transfer(task.id, execution, signal);
136
156
  this.audit.record('task.completed', { id: task.id, status: execution.result.status });
137
157
  } catch (error) {
138
158
  const status = signal.aborted ? 'cancelled' : 'error';
159
+ if (signal.aborted && task.operation !== 'batch.run' && resourceOperation(task.operation)) await this.resources.abandon(task, this.owner).catch(() => {});
139
160
  try { this.audit.record('task.failed', { id: task.id, status }); } catch { this.peer.close('Audit unavailable'); }
140
161
  await this.finish(task.id, { status, error: signal.aborted ? 'Cancelled' : redact((error as Error).message).slice(0, 2000) });
141
162
  } finally { this.jobs.delete(task.id); }
package/src/executor.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { spawn, type ChildProcess } from 'node:child_process';
2
2
  import { constants, lstatSync, readFileSync, realpathSync } from 'node:fs';
3
- import { open, rename, unlink } from 'node:fs/promises';
3
+ import { open, rename, unlink, lstat, opendir, mkdir, rm, chmod, readlink } from 'node:fs/promises';
4
4
  import { dirname, basename, resolve, join } from 'node:path';
5
5
  import { randomUUID } from 'node:crypto';
6
6
  import { isUtf8 } from 'node:buffer';
7
- import os from 'node:os';
7
+ import { inspectSystem } from './discover.js';
8
8
  import { SerialPort } from 'serialport';
9
9
  import { MAX_OUTPUT, type AtomicTask, type Task, type Result } from './schema.js';
10
10
  import { redact, sha256 } from './util.js';
@@ -25,7 +25,23 @@ function output(stream: string, bytes: Buffer): Execution['outputs'][number] {
25
25
  export async function execute(task: AtomicTask, signal: AbortSignal, write?: ReturnType<typeof prepareWrite>): Promise<Execution> {
26
26
  signal.throwIfAborted();
27
27
  switch (task.operation) {
28
- case 'system.inspect': return { result: { status: 'ok', data: { platform: process.platform, arch: process.arch, release: os.release(), node: process.version, serialPorts: await SerialPort.list() } }, outputs: [] };
28
+ case 'system.inspect': return { result: { status: 'ok', data: await inspectSystem() }, outputs: [] };
29
+ case 'file.stat': {
30
+ const stat = await lstat(task.arguments.path);
31
+ return { result: { status: 'ok', data: { size: stat.size, mode: stat.mode & 0o777, modifiedAt: stat.mtime.toISOString(), type: stat.isDirectory() ? 'directory' : stat.isSymbolicLink() ? 'symlink' : stat.isFile() ? 'file' : 'other', ...(stat.isSymbolicLink() ? { target: await readlink(task.arguments.path) } : {}) } }, outputs: [] };
32
+ }
33
+ case 'file.list': {
34
+ const directory = await opendir(task.arguments.path); const entries: { name: string; type: string }[] = []; let index = 0, more = false;
35
+ for await (const entry of directory) { signal.throwIfAborted(); if (index++ < task.arguments.offset) continue; if (entries.length >= task.arguments.limit) { more = true; break; } entries.push({ name: entry.name, type: entry.isDirectory() ? 'directory' : entry.isSymbolicLink() ? 'symlink' : entry.isFile() ? 'file' : 'other' }); }
36
+ return { result: { status: 'ok', data: { entries, nextOffset: task.arguments.offset + entries.length, hasMore: more } }, outputs: [] };
37
+ }
38
+ case 'file.mkdir': await mkdir(task.arguments.path, { recursive: task.arguments.recursive, mode: 0o700 }); return { result: { status: 'ok' }, outputs: [] };
39
+ case 'file.remove': await rm(task.arguments.path, { recursive: task.arguments.recursive, force: false }); return { result: { status: 'ok' }, outputs: [] };
40
+ case 'file.rename': {
41
+ try { await lstat(task.arguments.destination); if (!task.arguments.overwrite) throw new Error('Destination exists; explicit overwrite is required'); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
42
+ await rename(task.arguments.path, task.arguments.destination); return { result: { status: 'ok' }, outputs: [] };
43
+ }
44
+ case 'file.chmod': await chmod(task.arguments.path, task.arguments.mode); return { result: { status: 'ok' }, outputs: [] };
29
45
  case 'file.read': {
30
46
  const path = resolve(task.arguments.path);
31
47
  const file = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
@@ -57,6 +73,7 @@ export async function execute(task: AtomicTask, signal: AbortSignal, write?: Ret
57
73
  case 'process.run': return runProcess(task.arguments, signal);
58
74
  case 'process.script': return runProcess({ ...task.arguments, executable: task.arguments.interpreter }, signal, task.arguments.script);
59
75
  case 'serial.capture': case 'serial.exchange': return capture(task, signal);
76
+ default: throw new Error('This operation requires the session resource manager');
60
77
  }
61
78
  }
62
79
 
package/src/forward.ts ADDED
@@ -0,0 +1,50 @@
1
+ import net from 'node:net';
2
+ import type { Operator } from './operator.js';
3
+ export type Forward = { id: string; direction: string; host: string; port: number; readonly closed: boolean; close: () => Promise<void> };
4
+ async function write(socket: net.Socket, bytes: Buffer): Promise<void> { await new Promise<void>((resolve, reject) => socket.write(bytes, error => error ? reject(error) : resolve())); }
5
+ export async function forward(operator: Operator, id: string, localPort = 0): Promise<Forward> {
6
+ const meta = await operator.resource({ id, action: 'status' }) as { kind: string; direction: string; host: string; port: number; bindHost?: string; listeningPort?: number };
7
+ if (meta.kind !== 'forward') throw new Error('First authorize a net.forward resource');
8
+ let closed = false, server: net.Server | undefined; const sockets = new Set<net.Socket>();
9
+ const attach = (socket: net.Socket, connectionId: string): void => {
10
+ sockets.add(socket); socket.on('error', () => socket.destroy());
11
+ socket.on('data', bytes => { socket.pause(); void (async () => { for (let offset = 0; offset < bytes.length; offset += 65536) await operator.resource({ id: connectionId, action: 'input', data: bytes.subarray(offset, offset + 65536).toString('base64') }); socket.resume(); })().catch(() => socket.destroy()); });
12
+ socket.on('end', () => { void operator.resource({ id: connectionId, action: 'input', data: '', eof: true }).catch(() => socket.destroy()); });
13
+ socket.on('close', () => { sockets.delete(socket); void operator.resource({ id: connectionId, action: 'close' }).catch(() => {}); });
14
+ void (async () => { while (!closed && !socket.destroyed) { const result = await operator.resource({ id: connectionId, action: 'read' }) as { data: string; ended: boolean }; if (result.data) await write(socket, Buffer.from(result.data, 'base64')); if (result.ended) { socket.end(); break; } if (!result.data) await new Promise(resolve => setTimeout(resolve, 25)); } })().catch(() => socket.destroy());
15
+ socket.resume();
16
+ };
17
+ const connect = async (socket: net.Socket, host?: string, port?: number): Promise<void> => { const connection = await operator.resource({ id, action: 'connect', host, port }) as { id: string }; attach(socket, connection.id); };
18
+ const stop = async (): Promise<void> => { if (closed) return; closed = true; server?.close(); for (const socket of sockets) socket.destroy(); await operator.resource({ id, action: 'close' }).catch(() => {}); };
19
+ operator.peer.once('closed', () => { void stop(); });
20
+ if (meta.direction === 'remote') {
21
+ void (async () => {
22
+ while (!closed) {
23
+ const result = await operator.resource({ id, action: 'accept' }) as { connections: string[] };
24
+ for (const connectionId of result.connections) { const socket = net.createConnection({ host: meta.host, port: meta.port, allowHalfOpen: true }); socket.pause(); socket.once('connect', () => attach(socket, connectionId)); socket.once('error', () => { void operator.resource({ id: connectionId, action: 'close' }).catch(() => {}); }); }
25
+ await new Promise(resolve => setTimeout(resolve, 50));
26
+ }
27
+ })().catch(() => { void stop(); });
28
+ return { id, direction: meta.direction, host: meta.bindHost ?? '127.0.0.1', port: meta.listeningPort!, get closed() { return closed; }, close: stop };
29
+ }
30
+ server = net.createServer({ allowHalfOpen: true }, socket => {
31
+ socket.pause(); socket.on('error', () => socket.destroy());
32
+ if (meta.direction !== 'socks') { void connect(socket).catch(() => socket.destroy()); return; }
33
+ let buffer = Buffer.alloc(0), greeted = false;
34
+ const handshake = (bytes: Buffer): void => {
35
+ buffer = Buffer.concat([buffer, bytes]); if (buffer.length > 4096) { socket.destroy(); return; }
36
+ if (!greeted) { if (buffer.length < 2 || buffer.length < 2 + buffer[1]) return; if (buffer[0] !== 5 || !buffer.subarray(2, 2 + buffer[1]).includes(0)) { socket.end(Buffer.from([5, 255])); return; } const count = 2 + buffer[1]; buffer = buffer.subarray(count); greeted = true; socket.write(Buffer.from([5, 0])); }
37
+ if (buffer.length < 5) return; if (buffer[0] !== 5 || buffer[1] !== 1) { socket.end(Buffer.from([5, 7, 0, 1, 0, 0, 0, 0, 0, 0])); return; }
38
+ let host: string, end: number;
39
+ if (buffer[3] === 1) { end = 8; if (buffer.length < end + 2) return; host = [...buffer.subarray(4, 8)].join('.'); }
40
+ else if (buffer[3] === 3) { end = 5 + buffer[4]; if (buffer.length < end + 2) return; host = buffer.subarray(5, end).toString('utf8'); }
41
+ else if (buffer[3] === 4) { end = 20; if (buffer.length < end + 2) return; host = Array.from({ length: 8 }, (_, i) => buffer.readUInt16BE(4 + 2 * i).toString(16)).join(':'); }
42
+ else { socket.destroy(); return; }
43
+ const port = buffer.readUInt16BE(end), remainder = buffer.subarray(end + 2); socket.pause(); socket.off('data', handshake);
44
+ void (async () => { const connection = await operator.resource({ id, action: 'connect', host, port }) as { id: string }; await write(socket, Buffer.from([5, 0, 0, 1, 0, 0, 0, 0, 0, 0])); if (remainder.length) socket.unshift(remainder); attach(socket, connection.id); })().catch(() => socket.end(Buffer.from([5, 5, 0, 1, 0, 0, 0, 0, 0, 0])));
45
+ };
46
+ socket.on('data', handshake); socket.resume();
47
+ });
48
+ await new Promise<void>((resolveListen, reject) => { server!.once('error', reject); server!.listen(localPort, '127.0.0.1', () => { server!.off('error', reject); resolveListen(); }); });
49
+ return { id, direction: meta.direction, host: '127.0.0.1', port: (server.address() as net.AddressInfo).port, get closed() { return closed; }, close: stop };
50
+ }