@masstensor/diagnose 0.0.0-stage → 0.1.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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +80 -2
  3. package/deploy/Caddyfile +3 -0
  4. package/deploy/ecosystem.config.cjs +1 -0
  5. package/deploy/start-relay.sh +4 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +82 -0
  8. package/dist/crypto.d.ts +25 -0
  9. package/dist/crypto.js +60 -0
  10. package/dist/engine.d.ts +19 -0
  11. package/dist/engine.js +145 -0
  12. package/dist/executor.d.ts +18 -0
  13. package/dist/executor.js +203 -0
  14. package/dist/mcp.d.ts +1 -0
  15. package/dist/mcp.js +36 -0
  16. package/dist/operator.d.ts +21 -0
  17. package/dist/operator.js +68 -0
  18. package/dist/peer.d.ts +51 -0
  19. package/dist/peer.js +253 -0
  20. package/dist/relay-main.d.ts +2 -0
  21. package/dist/relay-main.js +6 -0
  22. package/dist/relay.d.ts +15 -0
  23. package/dist/relay.js +176 -0
  24. package/dist/schema.d.ts +102 -0
  25. package/dist/schema.js +28 -0
  26. package/dist/util.d.ts +11 -0
  27. package/dist/util.js +46 -0
  28. package/npm-shrinkwrap.json +2229 -0
  29. package/package.json +46 -4
  30. package/src/cli.ts +57 -0
  31. package/src/crypto.ts +54 -0
  32. package/src/engine.ts +87 -0
  33. package/src/executor.ts +129 -0
  34. package/src/mcp.ts +25 -0
  35. package/src/operator.ts +45 -0
  36. package/src/peer.ts +174 -0
  37. package/src/relay-main.ts +5 -0
  38. package/src/relay.ts +97 -0
  39. package/src/schema.ts +44 -0
  40. package/src/util.ts +39 -0
  41. package/src/vendor.d.ts +22 -0
  42. package/test/CACOPHONY-LICENSE +24 -0
  43. package/test/cli.test.ts +33 -0
  44. package/test/mcp.test.ts +29 -0
  45. package/test/noise-vector.json +40 -0
  46. package/test/probe.test.ts +131 -0
  47. package/test/serial.test.ts +24 -0
  48. package/test/vector.test.ts +32 -0
  49. package/tsconfig.json +8 -0
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import { createRelay } from './relay.js';
3
+ const relay = createRelay({ host: process.env.HOST ?? '127.0.0.1', port: Number(process.env.PORT ?? 8792), downloadPath: process.env.DOWNLOAD_PATH });
4
+ relay.listen().then(() => console.log('diagnose-relay ready')).catch(() => { console.error('RELAY_START_FAILED'); process.exitCode = 1; });
5
+ for (const signal of ['SIGTERM', 'SIGINT']) process.once(signal, () => { void relay.close(); });
package/src/relay.ts ADDED
@@ -0,0 +1,97 @@
1
+ import http from 'node:http';
2
+ import { createReadStream, statSync } from 'node:fs';
3
+ import { WebSocket, WebSocketServer } from 'ws';
4
+ import { MAX_FRAME } from './schema.js';
5
+
6
+ export type RelayOptions = { host?: string; port?: number; invitationMs?: number; sessionMs?: number; maxRooms?: number; downloadPath?: string; observeCiphertext?: (bytes: Buffer) => void };
7
+ type Room = { host: WebSocket; peer?: WebSocket; locked: boolean; attempts: number; expires: number; frames: number; window: number };
8
+ const control = (ws: WebSocket, type: string, extra = {}): void => { if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type, ...extra })); };
9
+
10
+ export function createRelay(options: RelayOptions = {}) {
11
+ const rooms = new Map<string, Room>();
12
+ const clients = new Map<WebSocket, { role?: 'host' | 'join'; room?: string; ip: string; alive: boolean }>();
13
+ const connectionsByIp = new Map<string, number>();
14
+ const server = http.createServer((req, res) => {
15
+ res.setHeader('Cache-Control', 'no-store');
16
+ res.setHeader('X-Content-Type-Options', 'nosniff');
17
+ if (req.method === 'GET' && req.url === '/healthz') { res.setHeader('Content-Type', 'application/json'); res.end('{"ok":true,"protocol":1}'); return; }
18
+ if (req.method === 'GET' && req.url === '/downloads/diagnose-0.1.0.tgz' && options.downloadPath) {
19
+ try { const size = statSync(options.downloadPath).size; res.setHeader('Content-Type', 'application/octet-stream'); res.setHeader('Content-Length', size); createReadStream(options.downloadPath).on('error', () => res.destroy()).pipe(res); } catch { res.writeHead(404); res.end(); } return;
20
+ }
21
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
22
+ res.writeHead(req.url === '/' ? 200 : 404);
23
+ res.end(req.url === '/' ? 'Diagnose blind relay v1. User-approved, end-to-end encrypted diagnostics.\n' : 'Not found\n');
24
+ });
25
+ const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME, perMessageDeflate: false });
26
+ server.on('upgrade', (req, socket, head) => {
27
+ if (req.url !== '/v1/connect' || clients.size >= 400) { socket.destroy(); return; }
28
+ wss.handleUpgrade(req, socket, head, ws => wss.emit('connection', ws, req));
29
+ });
30
+ wss.on('connection', (ws, req) => {
31
+ const direct = req.socket.remoteAddress ?? 'unknown';
32
+ const ip = ['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(direct) ? String(req.headers['x-forwarded-for'] ?? direct).split(',')[0].trim() : direct;
33
+ if ((connectionsByIp.get(ip) ?? 0) >= 30) { ws.close(1008, 'Connection limit'); return; }
34
+ connectionsByIp.set(ip, (connectionsByIp.get(ip) ?? 0) + 1);
35
+ const state = { ip, alive: true } as { role?: 'host' | 'join'; room?: string; ip: string; alive: boolean };
36
+ clients.set(ws, state);
37
+ const registration = setTimeout(() => { if (!state.role) ws.close(1008, 'Registration timeout'); }, 5000);
38
+ ws.on('pong', () => { state.alive = true; });
39
+ ws.on('error', () => ws.terminate());
40
+ ws.on('message', (raw, binary) => {
41
+ try {
42
+ const bytes = Buffer.from(raw as Buffer);
43
+ if (!state.role) {
44
+ if (binary || bytes.length > 256) throw new Error();
45
+ const msg = JSON.parse(bytes.toString());
46
+ if (msg.version !== 1 || !/^[A-Za-z0-9_-]{16}$/.test(msg.room) || !['host', 'join'].includes(msg.role)) throw new Error();
47
+ if (msg.role === 'host') {
48
+ if (rooms.has(msg.room) || rooms.size >= (options.maxRooms ?? 100)) throw new Error();
49
+ rooms.set(msg.room, { host: ws, locked: false, attempts: 0, expires: Date.now() + (options.invitationMs ?? 600000), frames: 0, window: Date.now() });
50
+ state.role = 'host'; state.room = msg.room; control(ws, 'registered');
51
+ } else {
52
+ const room = rooms.get(msg.room);
53
+ if (!room || room.locked || room.peer || room.attempts >= 10 || room.expires < Date.now()) throw new Error();
54
+ state.role = 'join'; state.room = msg.room; room.peer = ws; room.attempts++;
55
+ control(room.host, 'peer'); control(ws, 'joined');
56
+ }
57
+ clearTimeout(registration); return;
58
+ }
59
+ const room = rooms.get(state.room!);
60
+ if (!room) throw new Error();
61
+ if (binary) {
62
+ if (Date.now() - room.window > 1000) { room.window = Date.now(); room.frames = 0; }
63
+ if (++room.frames > 250 || bytes.length > MAX_FRAME) throw new Error();
64
+ const target = state.role === 'host' ? room.peer : room.host;
65
+ if (!target || target.readyState !== WebSocket.OPEN || target.bufferedAmount > 1024 * 1024) throw new Error();
66
+ let buffered = 0; for (const client of clients.keys()) buffered += client.bufferedAmount;
67
+ if (buffered > 64 * 1024 * 1024) throw new Error();
68
+ options.observeCiphertext?.(bytes);
69
+ target.send(bytes, { binary: true }); return;
70
+ }
71
+ if (bytes.length > 128 || state.role !== 'host') throw new Error();
72
+ const msg = JSON.parse(bytes.toString());
73
+ if (msg.type === 'lock') { room.locked = true; room.expires = Date.now() + (options.sessionMs ?? 3600000); }
74
+ else if (msg.type === 'reject' && !room.locked) { const peer = room.peer; room.peer = undefined; peer?.close(1008, 'Pairing rejected'); }
75
+ else throw new Error();
76
+ } catch { ws.close(1008, 'Protocol rejected'); }
77
+ });
78
+ ws.on('close', () => {
79
+ clearTimeout(registration); clients.delete(ws);
80
+ const count = (connectionsByIp.get(ip) ?? 1) - 1;
81
+ if (count > 0) connectionsByIp.set(ip, count); else connectionsByIp.delete(ip);
82
+ const room = rooms.get(state.room!); if (!room) return;
83
+ if (state.role === 'host') { rooms.delete(state.room!); room.peer?.close(1000, 'Session ended'); }
84
+ else if (room.peer === ws) { room.peer = undefined; control(room.host, 'peer-left'); if (room.locked) room.host.close(1000, 'Peer disconnected'); }
85
+ });
86
+ });
87
+ const sweep = setInterval(() => {
88
+ for (const [id, room] of rooms) if (room.expires < Date.now()) { rooms.delete(id); room.host.close(1000, 'Session expired'); room.peer?.close(1000, 'Session expired'); }
89
+ for (const [ws, state] of clients) { if (!state.alive) ws.terminate(); else { state.alive = false; ws.ping(); } }
90
+ }, 10000);
91
+ sweep.unref();
92
+ return {
93
+ server,
94
+ async listen(): Promise<number> { await new Promise<void>((resolve, reject) => { server.once('error', reject); server.listen(options.port ?? 8792, options.host ?? '127.0.0.1', () => { server.off('error', reject); resolve(); }); }); return (server.address() as import('node:net').AddressInfo).port; },
95
+ async close(): Promise<void> { clearInterval(sweep); for (const ws of wss.clients) ws.terminate(); await new Promise<void>(resolve => wss.close(() => resolve())); await new Promise<void>(resolve => server.close(() => resolve())); },
96
+ };
97
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,44 @@
1
+ import { z } from 'zod';
2
+
3
+ export const MAX_FRAME = 64 * 1024;
4
+ export const CHUNK_SIZE = 12 * 1024;
5
+ export const MAX_OUTPUT = 10 * 1024 * 1024;
6
+ const path = z.string().min(1).max(4096);
7
+ const common = { id: z.string().uuid(), reason: z.string().min(1).max(1000) };
8
+ export const taskSchema = z.discriminatedUnion('operation', [
9
+ z.object({ ...common, operation: z.literal('system.inspect'), arguments: z.object({}).strict() }).strict(),
10
+ 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(),
11
+ 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(),
12
+ 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(),
13
+ ...(['serial.capture', 'serial.exchange'] as const).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()),
14
+ ]);
15
+ export type Task = z.infer<typeof taskSchema>;
16
+ export type TaskInput = { operation: Task['operation']; arguments: Record<string, unknown>; reason: string };
17
+ export type ApprovalStage = 'execute' | 'send';
18
+ export type Approval = { stage: ApprovalStage; task: Task; digest: string; preview: string; bytes?: number; signal?: AbortSignal };
19
+ export type ApprovalHandler = (request: Approval) => Promise<boolean>;
20
+ export type Result = { status: 'ok' | 'error' | 'denied' | 'cancelled' | 'duplicate'; data?: unknown; error?: string; exitCode?: number | null; truncated?: boolean };
21
+ export type WireMessage =
22
+ | { type: 'session.accepted'; label: string; fingerprint: string }
23
+ | { type: 'session.closed'; reason: string }
24
+ | { type: 'task.request'; task: Task }
25
+ | { type: 'task.started'; id: string; digest: string }
26
+ | { type: 'task.output'; id: string; stream: string; chunk: string; index: number }
27
+ | { type: 'task.result'; id: string; result: Result }
28
+ | { type: 'task.cancel'; id: string }
29
+ | { type: 'ping' | 'pong' };
30
+
31
+ export function parseMessage(value: unknown): WireMessage {
32
+ const basic = z.object({ type: z.string() }).passthrough().parse(value);
33
+ switch (basic.type) {
34
+ case 'task.request': return { type: basic.type, task: taskSchema.parse(basic.task) };
35
+ case 'task.cancel': return { type: basic.type, id: z.string().uuid().parse(basic.id) };
36
+ case 'ping': case 'pong': return { type: basic.type };
37
+ case 'session.accepted': return z.object({ type: z.literal('session.accepted'), label: z.string().max(120), fingerprint: z.string().max(100) }).strict().parse(value);
38
+ case 'session.closed': return z.object({ type: z.literal('session.closed'), reason: z.string().max(200) }).strict().parse(value);
39
+ case 'task.started': return z.object({ type: z.literal('task.started'), id: z.string().uuid(), digest: z.string().regex(/^[a-f0-9]{64}$/) }).strict().parse(value);
40
+ case 'task.output': return z.object({ type: z.literal('task.output'), id: z.string().uuid(), stream: z.string().max(20), chunk: z.string().max(CHUNK_SIZE * 2), index: z.number().int().min(0) }).strict().parse(value);
41
+ case 'task.result': return z.object({ type: z.literal('task.result'), id: z.string().uuid(), result: z.object({ status: z.enum(['ok', 'error', 'denied', 'cancelled', 'duplicate']), data: z.unknown().optional(), error: z.string().max(2000).optional(), exitCode: z.number().int().nullable().optional(), truncated: z.boolean().optional() }).strict() }).strict().parse(value);
42
+ default: throw new Error('Unsupported message type');
43
+ }
44
+ }
package/src/util.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { appendFileSync, mkdirSync, openSync, closeSync, realpathSync } from 'node:fs';
3
+ import { dirname, resolve, relative, isAbsolute } from 'node:path';
4
+ import os from 'node:os';
5
+
6
+ export function safeText(text: string): string {
7
+ return text.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '').replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
8
+ }
9
+ export function redact(text: string): string {
10
+ return safeText(text)
11
+ .replace(/("?(?:password|passwd|pswd|secret|token|session|authorization|api[_-]?key)"?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,}\r\n]+)/gi, '$1[REDACTED]')
12
+ .replace(/\bD1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}\b/g, '[PAIRING CODE]')
13
+ .replace(/\b[a-f0-9]{32,}\b/gi, '[REDACTED]')
14
+ .replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g, '[PRIVATE KEY]');
15
+ }
16
+ export function canonical(value: unknown): string {
17
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
18
+ if (value !== null && typeof value === 'object') return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;
19
+ return JSON.stringify(value);
20
+ }
21
+ export const digest = (value: unknown): string => createHash('sha256').update(canonical(value)).digest('hex');
22
+ export const sha256 = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex');
23
+ export function inside(root: string, path: string): boolean {
24
+ try { const diff = relative(realpathSync(root), realpathSync(path)); return diff === '' || (!diff.startsWith('..') && !isAbsolute(diff)); } catch { return false; }
25
+ }
26
+
27
+ export class Audit {
28
+ readonly path: string;
29
+ constructor(path = resolve(os.homedir(), '.diagnose', `audit-${Date.now()}.jsonl`)) {
30
+ this.path = path;
31
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
32
+ const fd = openSync(path, 'ax', 0o600); closeSync(fd);
33
+ this.record('session.created', {});
34
+ }
35
+ record(event: string, details: Record<string, unknown>): void {
36
+ // No command text, payload, credentials, or file contents are persisted by default.
37
+ appendFileSync(this.path, JSON.stringify({ at: new Date().toISOString(), event, ...details }) + '\n', { mode: 0o600, flush: true });
38
+ }
39
+ }
@@ -0,0 +1,22 @@
1
+ declare module 'noise-handshake' {
2
+ export default class Noise {
3
+ constructor(pattern: string, initiator: boolean, staticKeypair?: unknown, options?: Record<string, unknown>);
4
+ initialise(prologue: Buffer): void;
5
+ send(payload?: Buffer): Buffer;
6
+ recv(message: Buffer): Buffer;
7
+ complete: boolean;
8
+ tx: Buffer;
9
+ rx: Buffer;
10
+ hash: Buffer;
11
+ e: { publicKey: Buffer; secretKey: Buffer } | null;
12
+ psk: Buffer | null;
13
+ }
14
+ }
15
+ declare module 'noise-handshake/cipher.js' {
16
+ export default class Cipher {
17
+ constructor(key: Buffer);
18
+ encrypt(plaintext: Buffer, ad?: Buffer): Buffer;
19
+ decrypt(ciphertext: Buffer, ad?: Buffer): Buffer;
20
+ _clear(): void;
21
+ }
22
+ }
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <http://unlicense.org>
@@ -0,0 +1,33 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { spawn } from 'node:child_process';
4
+ import { resolve } from 'node:path';
5
+ import { mkdtempSync } from 'node:fs';
6
+ import { tmpdir } from 'node:os';
7
+ import { createRelay } from '../dist/relay.js';
8
+ import { Peer } from '../dist/peer.js';
9
+ import { Operator } from '../dist/operator.js';
10
+
11
+ test('actual host CLI displays and enforces pairing, execution and transfer prompts', { skip: process.platform !== 'darwin', timeout: 15000 }, async () => {
12
+ const relay = createRelay({ port: 0 }); const url = `ws://127.0.0.1:${await relay.listen()}`;
13
+ // macOS script accepts a POSIX pipe, but not Node's socketpair-backed stdin.
14
+ const child = spawn('/bin/sh', ['-c', 'cat | /usr/bin/script -q /dev/null "$@"', 'diagnose-cli-test', process.execPath, resolve('dist/cli.js'), 'start', url], { detached: true, env: { ...process.env, HOME: mkdtempSync(tmpdir() + '/diagnose-cli-') }, stdio: ['pipe', 'pipe', 'pipe'] });
15
+ let text = '', pairing = false, executing = false, sending = false;
16
+ let stderr = ''; child.stderr.on('data', bytes => { stderr += bytes.toString(); });
17
+ let codeResolve!: (value: string) => void;
18
+ const code = new Promise<string>(resolve => { codeResolve = resolve; });
19
+ child.stdout.on('data', bytes => {
20
+ text += bytes.toString(); const match = /D1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}/.exec(text); if (match) codeResolve(match[0]);
21
+ if (!pairing && text.includes('Allow this temporary diagnostic session?')) { pairing = true; child.stdin.write('y\n'); }
22
+ if (!executing && text.includes('Allow exactly this operation?')) { executing = true; child.stdin.write('y\n'); }
23
+ if (!sending && text.includes('Send these results (')) { sending = true; child.stdin.write('y\n'); }
24
+ });
25
+ const timer = setTimeout(() => child.kill('SIGKILL'), 12000);
26
+ let peer: Peer | undefined;
27
+ try {
28
+ const pairCode = await Promise.race([code, new Promise<never>((_, reject) => child.once('exit', () => reject(new Error('CLI exited before registration: ' + stderr))))]);
29
+ peer = new Peer({ role: 'join', code: pairCode, relay: url }); const operator = new Operator(peer); await peer.open();
30
+ const result = await operator.run({ operation: 'system.inspect', arguments: {}, reason: 'Verify terminal approvals' });
31
+ assert.equal(result.result.status, 'ok'); assert.ok(pairing && executing && sending); assert.ok(text.includes('TRANSFER APPROVAL'));
32
+ } finally { clearTimeout(timer); peer?.close(); child.stdin.end('\x03'); if (child.pid) { try { process.kill(-child.pid, 'SIGTERM'); } catch {} } await relay.close(); }
33
+ });
@@ -0,0 +1,29 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
4
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
5
+ import { createRelay } from '../dist/relay.js';
6
+ import { createCode } from '../dist/crypto.js';
7
+ import { Peer } from '../dist/peer.js';
8
+ import { ProbeEngine } from '../dist/engine.js';
9
+ import { Audit } from '../dist/util.js';
10
+ import { mkdtempSync } from 'node:fs';
11
+ import { tmpdir } from 'node:os';
12
+ import { join, resolve } from 'node:path';
13
+
14
+ test('real stdio MCP client pairs, starts, waits and disconnects', async () => {
15
+ const relay = createRelay({ port: 0 }); const url = `ws://127.0.0.1:${await relay.listen()}`;
16
+ const code = createCode(); const host = new Peer({ role: 'host', code, relay: url, accept: async () => true });
17
+ new ProbeEngine(host, async () => true, new Audit(join(mkdtempSync(join(tmpdir(), 'diagnose-mcp-')), 'audit.jsonl'))); await host.open();
18
+ const transport = new StdioClientTransport({ command: process.execPath, args: [process.env.DIAGNOSE_TEST_CLI ?? resolve('dist/cli.js'), 'mcp', url], stderr: 'pipe' });
19
+ const client = new Client({ name: 'acceptance', version: '1.0.0' });
20
+ const text = (result: any) => { assert.ok(!result.isError, JSON.stringify(result)); return JSON.parse(result.content[0].text); };
21
+ try {
22
+ await client.connect(transport); assert.deepEqual((await client.listTools()).tools.map(tool => tool.name).sort(), ['diagnose_cancel', 'diagnose_disconnect', 'diagnose_pair', 'diagnose_start', 'diagnose_wait']);
23
+ assert.equal(text(await client.callTool({ name: 'diagnose_pair', arguments: { code, label: 'MCP test' } })).connected, true);
24
+ const { id } = text(await client.callTool({ name: 'diagnose_start', arguments: { operation: 'system.inspect', arguments: {}, reason: 'Verify MCP execution' } }));
25
+ const result = text(await client.callTool({ name: 'diagnose_wait', arguments: { id, timeoutMs: 5000, release: true } }));
26
+ assert.equal(result.result.status, 'ok'); assert.equal(result.result.data.platform, process.platform);
27
+ assert.equal(text(await client.callTool({ name: 'diagnose_disconnect', arguments: {} })).disconnected, true);
28
+ } finally { await client.close(); host.close(); await relay.close(); }
29
+ });
@@ -0,0 +1,40 @@
1
+ {
2
+ "protocol_name": "Noise_NNpsk0_25519_ChaChaPoly_BLAKE2b",
3
+ "init_prologue": "4a6f686e2047616c74",
4
+ "init_psks": [
5
+ "54686973206973206d7920417573747269616e20706572737065637469766521"
6
+ ],
7
+ "init_ephemeral": "893e28b9dc6ca8d611ab664754b8ceb7bac5117349a4439a6b0569da977c464a",
8
+ "resp_prologue": "4a6f686e2047616c74",
9
+ "resp_psks": [
10
+ "54686973206973206d7920417573747269616e20706572737065637469766521"
11
+ ],
12
+ "resp_ephemeral": "bbdb4cdbd309f1a1f2e1456967fe288cadd6f712d65dc7b7793d5e63da6b375b",
13
+ "handshake_hash": "ed5e9692d0ab507b6c2beec3f584fd5b127817a9d20b26cd50aa72c507260fa31aa7d88dd3723316338af37ce0b4cfb2923aeb848bbf2b934911306f01ffc963",
14
+ "messages": [
15
+ {
16
+ "payload": "4c756477696720766f6e204d69736573",
17
+ "ciphertext": "ca35def5ae56cec33dc2036731ab14896bc4c75dbb07a61f879f8e3afa4c7944ed63df2f5a12aee1185ee9c50305f2ecf12421dcb53c047a63b784cf7c54a105"
18
+ },
19
+ {
20
+ "payload": "4d757272617920526f746862617264",
21
+ "ciphertext": "95ebc60d2b1fa672c1f46a8aa265ef51bfe38e7ccb39ec5be34069f1448088430e0fe7d5c0c9b92f7478716c8852f1b4f389edb75e3ebe546fafafd5b6f0f7"
22
+ },
23
+ {
24
+ "payload": "462e20412e20486179656b",
25
+ "ciphertext": "0fe04b26dcfbb69f8a6a94c61f1a26ef88769218d32f5d17c068a6"
26
+ },
27
+ {
28
+ "payload": "4361726c204d656e676572",
29
+ "ciphertext": "2239e0c540c01f09eb1f4cc5258fd5acfefff18a5a3773f21b7bfe"
30
+ },
31
+ {
32
+ "payload": "4a65616e2d426170746973746520536179",
33
+ "ciphertext": "f216cb03d30fb8af1e561fe02a07552d09b416e27a75e62c77d193718b0bdaae9f"
34
+ },
35
+ {
36
+ "payload": "457567656e2042f6686d20766f6e2042617765726b",
37
+ "ciphertext": "6e8baf98b944184dd7dc5ef14d8108cbeca626de118a5460f3308e294d61e17238bce29bd9"
38
+ }
39
+ ]
40
+ }
@@ -0,0 +1,131 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtempSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { createRelay } from '../dist/relay.js';
8
+ import { createCode, parseCode, Handshake } from '../dist/crypto.js';
9
+ import { Peer } from '../dist/peer.js';
10
+ import { ProbeEngine } from '../dist/engine.js';
11
+ import { Operator } from '../dist/operator.js';
12
+ import { Audit } from '../dist/util.js';
13
+ import { execute, prepareWrite } from '../dist/executor.js';
14
+ import { taskSchema, type ApprovalHandler } from '../dist/schema.js';
15
+
16
+ const dir = mkdtempSync(join(tmpdir(), 'diagnose-test-'));
17
+ async function session(approve: ApprovalHandler = async () => true) {
18
+ const frames: Buffer[] = [];
19
+ const relay = createRelay({ port: 0, observeCiphertext: bytes => frames.push(Buffer.from(bytes)) });
20
+ const url = `ws://127.0.0.1:${await relay.listen()}`; const code = createCode();
21
+ const host = new Peer({ role: 'host', code, relay: url, accept: async () => true });
22
+ const audit = new Audit(join(dir, randomUUID() + '.jsonl'));
23
+ new ProbeEngine(host, approve, audit); await host.open();
24
+ const peer = new Peer({ role: 'join', code, relay: url }); const operator = new Operator(peer);
25
+ await peer.open(); await host.active;
26
+ return { host, peer, operator, audit, frames, code, async close() { peer.close(); host.close(); await relay.close(); } };
27
+ }
28
+
29
+ test('Noise authentication, channel binding, tampering and replay', () => {
30
+ const { room, secret } = parseCode(createCode());
31
+ const a = new Handshake(true, room, secret), b = new Handshake(false, room, secret);
32
+ assert.equal(b.receive(a.send(Buffer.from('hello'))).toString(), 'hello');
33
+ assert.equal(a.receive(b.send(Buffer.from('world'))).toString(), 'world');
34
+ const ac = a.split(), bc = b.split(); assert.equal(ac.fingerprint, bc.fingerprint);
35
+ const frame = ac.encrypt(Buffer.from('private')); assert.equal(bc.decrypt(frame).toString(), 'private');
36
+ assert.throws(() => bc.decrypt(frame));
37
+ const changed = ac.encrypt(Buffer.from('tamper')); changed[4] ^= 1; assert.throws(() => bc.decrypt(changed));
38
+ ac.destroy(); bc.destroy();
39
+ const bad = new Handshake(false, room, Buffer.alloc(32)); const fresh = new Handshake(true, room, secret);
40
+ assert.throws(() => bad.receive(fresh.send(Buffer.alloc(0)))); bad.destroy(); fresh.destroy();
41
+ const other = new Handshake(false, 'wrong-route', secret); const correct = new Handshake(true, room, secret);
42
+ assert.throws(() => other.receive(correct.send(Buffer.alloc(0)))); other.destroy(); correct.destroy();
43
+ });
44
+
45
+ test('encrypted commands, large chunks, audit collection vs transfer, no relay plaintext', async () => {
46
+ const s = await session();
47
+ try {
48
+ const value = 'PRIVATE_DIAGNOSTIC_MARKER';
49
+ const result = await s.operator.run({ operation: 'process.run', arguments: { executable: process.execPath, args: ['-e', `process.stdout.write('${value}'.repeat(10000))`] }, reason: 'Verify chunked diagnostics' });
50
+ assert.equal(result.result.status, 'ok'); assert.equal(result.outputs.stdout, value.repeat(10000));
51
+ const wire = Buffer.concat(s.frames);
52
+ assert.equal(wire.includes(Buffer.from(value)), false); assert.equal(wire.includes(Buffer.from(parseCode(s.code).secret)), false);
53
+ const audit = readFileSync(s.audit.path, 'utf8'); assert.ok(audit.indexOf('task.collected') < audit.indexOf('task.transfer-approved')); assert.ok(audit.includes('task.chunk-sending')); assert.equal(audit.includes(value), false);
54
+ } finally { await s.close(); }
55
+ });
56
+
57
+ test('execution refusal and transfer refusal are enforced locally', async () => {
58
+ const target = join(dir, 'must-not-exist');
59
+ let mode = 'deny'; const s = await session(async request => mode === 'send-deny' && request.stage === 'execute');
60
+ try {
61
+ const denied = await s.operator.run({ operation: 'file.write', arguments: { path: target, content: 'never' }, reason: 'Test denial' });
62
+ assert.equal(denied.result.status, 'denied'); assert.equal(existsSync(target), false);
63
+ mode = 'send-deny';
64
+ const local = await s.operator.run({ operation: 'process.run', arguments: { executable: process.execPath, args: ['-e', 'console.log("LOCAL_ONLY_CONTENT")'] }, reason: 'Test transfer denial' });
65
+ assert.equal(local.result.status, 'denied'); assert.deepEqual(local.outputs, {}); assert.equal(Buffer.concat(s.frames).includes(Buffer.from('LOCAL_ONLY_CONTENT')), false);
66
+ } finally { await s.close(); }
67
+ });
68
+
69
+ test('cancellation, timeouts, file writes, and stale preview rejection', async () => {
70
+ const s = await session();
71
+ try {
72
+ const id = await s.operator.start({ operation: 'process.run', arguments: { executable: process.execPath, args: ['-e', 'setInterval(()=>{},1000)'] }, reason: 'Cancel test process' });
73
+ await new Promise(resolve => setTimeout(resolve, 150)); await s.operator.cancel(id);
74
+ const outcome = await s.operator.wait(id, 5000); assert.equal('result' in outcome && outcome.result.status, 'cancelled');
75
+ await new Promise(resolve => setTimeout(resolve, 50));
76
+ const timeout = await s.operator.run({ operation: 'process.run', arguments: { executable: process.execPath, args: ['-e', 'setInterval(()=>{},1000)'], timeoutMs: 100 }, reason: 'Timeout test' });
77
+ assert.equal(timeout.result.error, 'Task timeout');
78
+ const target = join(dir, 'write-test');
79
+ const written = await s.operator.run({ operation: 'file.write', arguments: { path: target, content: 'test' }, reason: 'Write only temporary test file' }); assert.equal(written.result.status, 'ok'); assert.equal(readFileSync(target, 'utf8'), 'test');
80
+ const read = await s.operator.run({ operation: 'file.read', arguments: { path: target }, reason: 'Read temporary test file' }); assert.equal(read.outputs.file, 'test');
81
+ const task = taskSchema.parse({ id: randomUUID(), operation: 'file.write', arguments: { path: target, content: 'replacement' }, reason: 'Race test' });
82
+ const snapshot = prepareWrite(task); writeFileSync(target, 'changed');
83
+ await assert.rejects(execute(task, new AbortController().signal, snapshot), /changed/); assert.equal(readFileSync(target, 'utf8'), 'changed');
84
+ } finally { await s.close(); }
85
+ });
86
+
87
+ test('wrong secret cannot consume invitation; host confirmation gates activation', async () => {
88
+ const relay = createRelay({ port: 0 }); const url = `ws://127.0.0.1:${await relay.listen()}`; const code = createCode();
89
+ let accept!: (value: boolean) => void; const decision = new Promise<boolean>(resolve => { accept = resolve; });
90
+ const host = new Peer({ role: 'host', code, relay: url, accept: () => decision }); await host.open();
91
+ const wrong = new Peer({ role: 'join', relay: url, code: `D1.${parseCode(code).room}.${Buffer.alloc(32).toString('base64url')}` });
92
+ await assert.rejects(wrong.open()); await new Promise(resolve => setTimeout(resolve, 50));
93
+ const peer = new Peer({ role: 'join', code, relay: url }); let active = false; peer.active.then(() => { active = true; });
94
+ try { await new Promise(resolve => setTimeout(resolve, 100)); assert.equal(active, false); accept(true); await peer.open(); assert.equal(active, true); }
95
+ finally { peer.close(); wrong.close(); host.close(); await relay.close(); }
96
+ });
97
+
98
+ test('expired invitations and stalled local confirmation cannot activate a session', async () => {
99
+ const relay = createRelay({ port: 0, invitationMs: 30 }); const url = `ws://127.0.0.1:${await relay.listen()}`;
100
+ const code = createCode(); const host = new Peer({ role: 'host', code, relay: url, accept: async () => true }); await host.open();
101
+ await new Promise(resolve => setTimeout(resolve, 60)); const late = new Peer({ role: 'join', code, relay: url });
102
+ try { await assert.rejects(late.open()); } finally { late.close(); host.close(); await relay.close(); }
103
+ const other = createRelay({ port: 0 }); const otherUrl = `ws://127.0.0.1:${await other.listen()}`; const fresh = createCode();
104
+ const waiting = new Peer({ role: 'host', code: fresh, relay: otherUrl, approvalTimeoutMs: 30, accept: () => new Promise(() => {}) }); await waiting.open();
105
+ const joining = new Peer({ role: 'join', code: fresh, relay: otherUrl });
106
+ try { await assert.rejects(joining.open()); assert.match(await waiting.ended, /timeout/); }
107
+ finally { joining.close(); waiting.close(); await other.close(); }
108
+ });
109
+
110
+ test('disconnect terminates running diagnostics and output collection is bounded', async () => {
111
+ const s = await session(); const pidPath = join(dir, randomUUID() + '.pid');
112
+ try {
113
+ await s.operator.start({ operation: 'process.run', arguments: { executable: process.execPath, args: ['-e', `require('fs').writeFileSync(${JSON.stringify(pidPath)},String(process.pid));setInterval(()=>{},1000)`] }, reason: 'Verify disconnect cleanup' });
114
+ for (let i = 0; i < 50 && !existsSync(pidPath); i++) await new Promise(resolve => setTimeout(resolve, 20));
115
+ assert.ok(existsSync(pidPath)); const pid = Number(readFileSync(pidPath, 'utf8')); s.peer.close();
116
+ await new Promise(resolve => setTimeout(resolve, 300)); assert.throws(() => process.kill(pid, 0), { code: 'ESRCH' });
117
+ } finally { await s.close(); }
118
+ const task = taskSchema.parse({ id: randomUUID(), operation: 'process.run', arguments: { executable: process.execPath, args: ['-e', 'process.stdout.write("x".repeat(12*1024*1024));setInterval(()=>{},1000)'] }, reason: 'Output limit acceptance' });
119
+ const result = await execute(task, new AbortController().signal);
120
+ assert.equal(result.result.truncated, true); assert.equal(result.result.status, 'error'); assert.ok(result.outputs.reduce((sum, output) => sum + output.bytes.length, 0) <= 10 * 1024 * 1024);
121
+ });
122
+
123
+ test('replayed task IDs never repeat execution', async () => {
124
+ const s = await session(); const path = join(dir, randomUUID() + '.once');
125
+ const task = taskSchema.parse({ id: randomUUID(), operation: 'process.run', arguments: { executable: process.execPath, args: ['-e', `require('fs').appendFileSync(${JSON.stringify(path)},'x')`] }, reason: 'Replay acceptance' });
126
+ const result = () => new Promise<any>(resolve => { const listener = (message: any) => { if (message.type === 'task.result' && message.id === task.id) { s.peer.off('message', listener); resolve(message.result); } }; s.peer.on('message', listener); });
127
+ try {
128
+ const first = result(); await s.peer.send({ type: 'task.request', task }); assert.equal((await first).status, 'ok');
129
+ const second = result(); await s.peer.send({ type: 'task.request', task }); assert.equal((await second).status, 'duplicate'); assert.equal(readFileSync(path, 'utf8'), 'x');
130
+ } finally { await s.close(); }
131
+ });
@@ -0,0 +1,24 @@
1
+ import { test, mock } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { SerialPort, SerialPortMock } from 'serialport';
5
+ import { execute } from '../dist/executor.js';
6
+ import { taskSchema } from '../dist/schema.js';
7
+
8
+ test('serial capture never transmits; explicit exchange transmits exact bytes and closes', async () => {
9
+ const binding = SerialPortMock.binding; binding.reset();
10
+ binding.createPort('/virtual/diagnose', { echo: true, record: true, readyData: Buffer.from('password=hidden\nready\n') });
11
+ let current: any;
12
+ mock.method(SerialPort.binding, 'open', async options => { current = await binding.open(options); return current; });
13
+ const make = (operation: string, extra = {}) => taskSchema.parse({ id: randomUUID(), operation, arguments: { path: '/virtual/diagnose', durationMs: 100, ...extra }, reason: 'Virtual serial acceptance' });
14
+ try {
15
+ const captured = await execute(make('serial.capture'), new AbortController().signal);
16
+ assert.equal(captured.result.status, 'ok'); assert.equal(current.recording.length, 0); assert.equal(current.isOpen, false);
17
+ assert.equal(captured.outputs[0].bytes.includes(Buffer.from('hidden')), false); assert.ok(captured.outputs[0].bytes.includes(Buffer.from('ready')));
18
+ const exchanged = await execute(make('serial.exchange', { dataHex: '010203ff' }), new AbortController().signal);
19
+ assert.equal(exchanged.result.status, 'ok'); assert.equal(current.recording.toString('hex'), '010203ff'); assert.equal(current.isOpen, false);
20
+ const controller = new AbortController(); const running = execute(make('serial.capture', { durationMs: 5000 }), controller.signal);
21
+ setTimeout(() => controller.abort(), 50); assert.equal((await running).result.status, 'cancelled'); assert.equal(current.isOpen, false);
22
+ await assert.rejects(execute(make('serial.capture', { dataHex: '01' }), new AbortController().signal), /does not accept/);
23
+ } finally { mock.restoreAll(); binding.reset(); }
24
+ });
@@ -0,0 +1,32 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { readFileSync } from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ const require = createRequire(import.meta.url);
6
+ const Noise = require('noise-handshake');
7
+ const Cipher = require('noise-handshake/cipher.js');
8
+ const { generateKeyPair } = require('noise-handshake/dh.js');
9
+
10
+ // Public cross-implementation fixture, unmodified:
11
+ // https://github.com/centromere/cacophony/blob/master/vectors/cacophony.txt
12
+ test('published Cacophony NNpsk0/25519/ChaChaPoly/BLAKE2b vector', () => {
13
+ const v = JSON.parse(readFileSync(new URL('./noise-vector.json', import.meta.url), 'utf8'));
14
+ const hex = (value: string) => Buffer.from(value, 'hex');
15
+ const a = new Noise('NNpsk0', true, undefined, { psk: hex(v.init_psks[0]) });
16
+ const b = new Noise('NNpsk0', false, undefined, { psk: hex(v.resp_psks[0]) });
17
+ a.initialise(hex(v.init_prologue)); b.initialise(hex(v.resp_prologue));
18
+ a.e = generateKeyPair(hex(v.init_ephemeral)); b.e = generateKeyPair(hex(v.resp_ephemeral));
19
+ for (let i = 0; i < 2; i++) {
20
+ const sender = i === 0 ? a : b, receiver = i === 0 ? b : a;
21
+ const frame = sender.send(hex(v.messages[i].payload));
22
+ assert.equal(frame.toString('hex'), v.messages[i].ciphertext);
23
+ assert.equal(receiver.recv(frame).toString('hex'), v.messages[i].payload);
24
+ }
25
+ assert.equal(a.hash.toString('hex'), v.handshake_hash); assert.equal(b.hash.toString('hex'), v.handshake_hash);
26
+ const at = new Cipher(a.tx), ar = new Cipher(a.rx), bt = new Cipher(b.tx), br = new Cipher(b.rx);
27
+ for (let i = 2; i < v.messages.length; i++) {
28
+ const sender = i % 2 === 0 ? at : bt, receiver = i % 2 === 0 ? br : ar;
29
+ const frame = sender.encrypt(hex(v.messages[i].payload)); assert.equal(frame.toString('hex'), v.messages[i].ciphertext);
30
+ assert.equal(receiver.decrypt(frame).toString('hex'), v.messages[i].payload);
31
+ }
32
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext",
4
+ "strict": true, "skipLibCheck": true, "rootDir": "src", "outDir": "dist",
5
+ "declaration": true, "sourceMap": false, "rewriteRelativeImportExtensions": true
6
+ },
7
+ "include": ["src/**/*.ts"]
8
+ }