@masstensor/diagnose 0.1.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.
- package/README.md +86 -6
- package/dist/cli.js +252 -25
- package/dist/discover.d.ts +1 -0
- package/dist/discover.js +23 -0
- package/dist/engine.d.ts +20 -3
- package/dist/engine.js +172 -35
- package/dist/executor.d.ts +2 -2
- package/dist/executor.js +53 -5
- package/dist/forward.d.ts +10 -0
- package/dist/forward.js +115 -0
- package/dist/journal.d.ts +32 -0
- package/dist/journal.js +81 -0
- package/dist/mcp.js +69 -4
- package/dist/operator.d.ts +3 -1
- package/dist/operator.js +30 -3
- package/dist/peer.d.ts +1 -0
- package/dist/peer.js +1 -1
- package/dist/prepare-pty.d.ts +1 -0
- package/dist/prepare-pty.js +26 -0
- package/dist/relay.js +5 -2
- package/dist/resources.d.ts +28 -0
- package/dist/resources.js +427 -0
- package/dist/schema.d.ts +675 -1
- package/dist/schema.js +20 -1
- package/dist/transfers.d.ts +19 -0
- package/dist/transfers.js +118 -0
- package/npm-shrinkwrap.json +21 -3
- package/package.json +4 -2
- package/src/cli.ts +104 -19
- package/src/discover.ts +17 -0
- package/src/engine.ts +124 -34
- package/src/executor.ts +26 -7
- package/src/forward.ts +50 -0
- package/src/journal.ts +48 -0
- package/src/mcp.ts +34 -4
- package/src/operator.ts +15 -3
- package/src/peer.ts +2 -2
- package/src/prepare-pty.ts +15 -0
- package/src/relay.ts +1 -1
- package/src/resources.ts +180 -0
- package/src/schema.ts +27 -1
- package/src/transfers.ts +48 -0
- package/test/batch.test.ts +132 -0
- package/test/cli.test.ts +57 -1
- package/test/mcp.test.ts +13 -1
- package/test/resources.test.ts +146 -0
package/dist/schema.js
CHANGED
|
@@ -4,18 +4,37 @@ export const CHUNK_SIZE = 12 * 1024;
|
|
|
4
4
|
export const MAX_OUTPUT = 10 * 1024 * 1024;
|
|
5
5
|
const path = z.string().min(1).max(4096);
|
|
6
6
|
const common = { id: z.string().uuid(), reason: z.string().min(1).max(1000) };
|
|
7
|
-
export const
|
|
7
|
+
export const atomicOperationNames = ['system.inspect', 'file.read', 'file.write', 'file.stat', 'file.list', 'file.mkdir', 'file.remove', 'file.rename', 'file.chmod', 'file.transfer', 'process.run', 'process.script', 'process.open', 'resource.resume', 'net.forward', 'serial.capture', 'serial.exchange'];
|
|
8
|
+
export const batchOperationNames = ['system.inspect', 'file.read', 'file.write', 'file.stat', 'file.list', 'file.mkdir', 'file.remove', 'file.rename', 'file.chmod', 'process.run', 'process.script', 'serial.capture', 'serial.exchange'];
|
|
9
|
+
const environment = z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), z.string().max(65536)).optional();
|
|
10
|
+
export const atomicTaskSchema = z.discriminatedUnion('operation', [
|
|
8
11
|
z.object({ ...common, operation: z.literal('system.inspect'), arguments: z.object({}).strict() }).strict(),
|
|
9
12
|
z.object({ ...common, operation: z.literal('file.read'), arguments: z.object({ path, offset: z.number().int().min(0).default(0), length: z.number().int().min(1).max(1024 * 1024).default(65536) }).strict() }).strict(),
|
|
10
13
|
z.object({ ...common, operation: z.literal('file.write'), arguments: z.object({ path, content: z.string().max(1024 * 1024), expectedSha256: z.string().regex(/^[a-f0-9]{64}$/).optional() }).strict() }).strict(),
|
|
14
|
+
z.object({ ...common, operation: z.literal('file.stat'), arguments: z.object({ path }).strict() }).strict(),
|
|
15
|
+
z.object({ ...common, operation: z.literal('file.list'), arguments: z.object({ path, offset: z.number().int().min(0).default(0), limit: z.number().int().min(1).max(200).default(50) }).strict() }).strict(),
|
|
16
|
+
z.object({ ...common, operation: z.literal('file.mkdir'), arguments: z.object({ path, recursive: z.boolean().default(false) }).strict() }).strict(),
|
|
17
|
+
z.object({ ...common, operation: z.literal('file.remove'), arguments: z.object({ path, recursive: z.boolean().default(false) }).strict() }).strict(),
|
|
18
|
+
z.object({ ...common, operation: z.literal('file.rename'), arguments: z.object({ path, destination: path, overwrite: z.boolean().default(false) }).strict() }).strict(),
|
|
19
|
+
z.object({ ...common, operation: z.literal('file.chmod'), arguments: z.object({ path, mode: z.number().int().min(0).max(0o777) }).strict() }).strict(),
|
|
20
|
+
z.object({ ...common, operation: z.literal('file.transfer'), arguments: z.object({ path, direction: z.enum(['upload', 'download']), size: z.number().int().min(0).max(1024 ** 4).optional(), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(), overwrite: z.boolean().default(false), retainOnDisconnect: z.boolean().default(true) }).strict() }).strict(),
|
|
21
|
+
z.object({ ...common, operation: z.literal('process.open'), arguments: z.object({ executable: path.optional(), args: z.array(z.string().max(65536)).max(128).default([]), cwd: path.optional(), env: environment, pty: z.boolean().default(false), cols: z.number().int().min(20).max(500).default(100), rows: z.number().int().min(5).max(200).default(30), timeoutMs: z.number().int().min(0).max(86400000).default(3600000), retainOnDisconnect: z.boolean().default(false), maxOutputBytes: z.number().int().min(1024).max(1024 ** 3).default(64 * 1024 ** 2) }).strict() }).strict(),
|
|
22
|
+
z.object({ ...common, operation: z.literal('resource.resume'), arguments: z.object({ id: z.string().uuid(), resumeToken: z.string().regex(/^[A-Za-z0-9_-]{43}$/) }).strict() }).strict(),
|
|
23
|
+
z.object({ ...common, operation: z.literal('net.forward'), arguments: z.object({ direction: z.enum(['local', 'remote', 'socks']), host: z.string().min(1).max(253).default('127.0.0.1'), port: z.number().int().min(0).max(65535).default(0), bindHost: z.enum(['127.0.0.1', '::1']).default('127.0.0.1'), bindPort: z.number().int().min(0).max(65535).default(0), allowedHosts: z.array(z.string().min(1).max(253)).min(1).max(100).default(['*']) }).strict() }).strict(),
|
|
11
24
|
z.object({ ...common, operation: z.literal('process.run'), arguments: z.object({ executable: path, args: z.array(z.string().max(65536)).max(128).default([]), cwd: path.optional(), timeoutMs: z.number().int().min(100).max(300000).default(60000) }).strict() }).strict(),
|
|
25
|
+
z.object({ ...common, operation: z.literal('process.script'), arguments: z.object({ interpreter: path, script: z.string().min(1).max(256 * 1024), args: z.array(z.string().max(65536)).max(128).default([]), cwd: path.optional(), timeoutMs: z.number().int().min(100).max(300000).default(60000) }).strict() }).strict(),
|
|
12
26
|
...['serial.capture', 'serial.exchange'].map(operation => z.object({ ...common, operation: z.literal(operation), arguments: z.object({ path, baudRate: z.number().int().min(300).max(3000000).default(115200), durationMs: z.number().int().min(100).max(300000).default(20000), dataHex: z.string().regex(/^(?:[a-fA-F0-9]{2})*$/).max(65536).optional() }).strict() }).strict()),
|
|
13
27
|
]);
|
|
28
|
+
export const batchTaskSchema = z.object({ ...common, operation: z.literal('batch.run'), arguments: z.object({ steps: z.array(atomicTaskSchema).min(1).max(32), stopOnError: z.boolean().default(true), timeoutMs: z.number().int().min(100).max(300000).default(300000) }).strict() }).strict().refine(task => new Set([task.id, ...task.arguments.steps.map(step => step.id)]).size === task.arguments.steps.length + 1, 'Batch task IDs must be unique');
|
|
29
|
+
export const taskSchema = z.union([atomicTaskSchema, batchTaskSchema]);
|
|
30
|
+
export const resourceRequestSchema = z.object({ id: z.string().uuid().optional(), action: z.enum(['list', 'read', 'input', 'resize', 'signal', 'status', 'close', 'commit', 'connect', 'accept']), cursor: z.number().int().min(0).default(0), limit: z.number().int().min(1).max(65536).default(65536), data: z.string().max(90000).optional(), eof: z.boolean().default(false), cols: z.number().int().min(20).max(500).optional(), rows: z.number().int().min(5).max(200).optional(), signal: z.enum(['SIGINT', 'SIGTERM', 'SIGKILL', 'SIGHUP', 'SIGQUIT']).optional(), host: z.string().min(1).max(253).optional(), port: z.number().int().min(1).max(65535).optional() }).strict();
|
|
14
31
|
export function parseMessage(value) {
|
|
15
32
|
const basic = z.object({ type: z.string() }).passthrough().parse(value);
|
|
16
33
|
switch (basic.type) {
|
|
17
34
|
case 'task.request': return { type: basic.type, task: taskSchema.parse(basic.task) };
|
|
18
35
|
case 'task.cancel': return { type: basic.type, id: z.string().uuid().parse(basic.id) };
|
|
36
|
+
case 'resource.request': return { type: basic.type, requestId: z.string().uuid().parse(basic.requestId), request: resourceRequestSchema.parse(basic.request) };
|
|
37
|
+
case 'resource.result': return z.object({ type: z.literal('resource.result'), requestId: z.string().uuid(), value: z.unknown().optional(), error: z.string().max(2000).optional() }).strict().parse(value);
|
|
19
38
|
case 'ping':
|
|
20
39
|
case 'pong': return { type: basic.type };
|
|
21
40
|
case 'session.accepted': return z.object({ type: z.literal('session.accepted'), label: z.string().max(120), fingerprint: z.string().max(100) }).strict().parse(value);
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Operator } from './operator.js';
|
|
2
|
+
export type TransferProgress = {
|
|
3
|
+
state: string;
|
|
4
|
+
bytes: number;
|
|
5
|
+
size: number;
|
|
6
|
+
resourceId?: string;
|
|
7
|
+
resumeToken?: string;
|
|
8
|
+
sha256?: string;
|
|
9
|
+
error?: string;
|
|
10
|
+
};
|
|
11
|
+
export type TransferOptions = {
|
|
12
|
+
resumeId?: string;
|
|
13
|
+
resumeToken?: string;
|
|
14
|
+
overwrite?: boolean;
|
|
15
|
+
signal?: AbortSignal;
|
|
16
|
+
progress?: (progress: TransferProgress) => void;
|
|
17
|
+
};
|
|
18
|
+
export declare function upload(operator: Operator, localPath: string, remotePath: string, reason: string, options?: TransferOptions): Promise<TransferProgress>;
|
|
19
|
+
export declare function download(operator: Operator, remotePath: string, localPath: string, reason: string, options?: TransferOptions): Promise<TransferProgress>;
|
|
@@ -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
|
+
}
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@masstensor/diagnose",
|
|
3
|
-
"version": "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.
|
|
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.
|
|
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,39 +8,118 @@ 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
|
|
14
|
-
const
|
|
15
|
-
if (
|
|
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
|
-
const shutdown = new AbortController(); let peer: Peer | undefined;
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
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;
|
|
43
|
+
let localCommand: (value: string) => boolean = () => false;
|
|
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);
|
|
46
|
+
rl.once('close', () => { shutdown.abort(); peer?.close('User terminal closed'); });
|
|
47
|
+
const ask = async (text: string, signal = shutdown.signal, taskApproval = false): Promise<boolean> => {
|
|
48
|
+
while (true) {
|
|
49
|
+
let answer: string; promptActive = true; try { answer = (await rl.question(safeText(text) + ' [y/N] ', { signal })).trim(); } finally { promptActive = false; }
|
|
50
|
+
if (!localCommand(answer)) return answer.toLowerCase() === 'y';
|
|
51
|
+
signal.throwIfAborted();
|
|
52
|
+
if (taskApproval && engine?.permissionMode === 'auto') return true;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
24
55
|
try {
|
|
25
56
|
if (command === 'start') {
|
|
26
|
-
const
|
|
27
|
-
|
|
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 }) => {
|
|
28
61
|
console.log(`\nRequested by: ${safeText(label)} (self-asserted identity)\nFingerprint: ${fingerprint}\nResults will be available to the diagnostician and their AI provider.`);
|
|
29
|
-
|
|
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.');
|
|
63
|
+
const answer = (await rl.question('Allow this temporary diagnostic session? [y / a=auto / N] ', { signal })).trim().toLowerCase();
|
|
64
|
+
const allowed = answer === 'y' || answer === 'a';
|
|
65
|
+
if (answer === 'a') engine!.setPermissionMode('auto');
|
|
30
66
|
audit.record('session.pairing-decision', { allowed, fingerprint }); return allowed;
|
|
31
67
|
} });
|
|
32
|
-
new ProbeEngine(peer, async request => {
|
|
68
|
+
engine = new ProbeEngine(peer, async request => {
|
|
33
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`);
|
|
34
|
-
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);
|
|
35
|
-
}, audit, message => console.log(safeText(message)));
|
|
36
|
-
|
|
37
|
-
console.log(`
|
|
38
|
-
|
|
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);
|
|
71
|
+
}, audit, message => console.log(safeText(message)), { resources, idleMs: idleMinutes * 60000, lifetimeMs: sessionMinutes * 60000 });
|
|
72
|
+
let active = false, autoRequestedAt = 0;
|
|
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.`); });
|
|
74
|
+
localCommand = value => {
|
|
75
|
+
if (!active && !['jobs', 'cancel', 'exit', 'permissions ask'].includes(value) && !value.startsWith('recover ') && !value.startsWith('secret ')) return false;
|
|
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; }
|
|
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; }
|
|
78
|
+
if (value === 'permissions allow-auto') {
|
|
79
|
+
if (autoRequestedAt && Date.now() - autoRequestedAt < 60000) { engine!.setPermissionMode('auto'); autoRequestedAt = 0; }
|
|
80
|
+
else console.log('No pending grant. First type "permissions auto" and read its explanation.');
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
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
|
+
}
|
|
99
|
+
if (value === 'exit') { stop(); return true; }
|
|
100
|
+
return false;
|
|
101
|
+
};
|
|
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
|
+
}
|
|
39
113
|
} else {
|
|
40
114
|
const code = (await rl.question('Pairing code: ', { signal: shutdown.signal })).trim();
|
|
41
115
|
const label = await rl.question('Your label / AI provider: ', { signal: shutdown.signal });
|
|
42
116
|
peer = new Peer({ role: 'join', code, relay, label }); const operator = new Operator(peer);
|
|
43
|
-
|
|
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.`);
|
|
44
123
|
peer.ended.then(() => stop());
|
|
45
124
|
while (!shutdown.signal.aborted) {
|
|
46
125
|
const line = (await rl.question('diagnose> ', { signal: shutdown.signal })).trim();
|
|
@@ -48,10 +127,16 @@ async function main(): Promise<void> {
|
|
|
48
127
|
try {
|
|
49
128
|
if (line.startsWith('cancel ')) { await operator.cancel(line.slice(7).trim()); console.log('Cancellation requested'); }
|
|
50
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))); }
|
|
51
136
|
else if (line) console.log(`Task: ${await operator.start(JSON.parse(line) as TaskInput)}`);
|
|
52
137
|
} catch (error) { console.error(safeText((error as Error).message)); }
|
|
53
138
|
}
|
|
54
139
|
}
|
|
55
|
-
} finally { stop(); }
|
|
140
|
+
} finally { for (const value of forwards.values()) await value.close(); stop(); await resources?.revoke(); }
|
|
56
141
|
}
|
|
57
142
|
main().catch(error => { console.error(safeText((error as Error).name === 'AbortError' ? 'Session ended' : (error as Error).message)); process.exitCode = 1; });
|
package/src/discover.ts
ADDED
|
@@ -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
|
+
}
|