@masstensor/diagnose 0.0.0-stage → 0.2.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 (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +123 -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 +145 -0
  8. package/dist/crypto.d.ts +25 -0
  9. package/dist/crypto.js +60 -0
  10. package/dist/engine.d.ts +27 -0
  11. package/dist/engine.js +245 -0
  12. package/dist/executor.d.ts +18 -0
  13. package/dist/executor.js +208 -0
  14. package/dist/mcp.d.ts +1 -0
  15. package/dist/mcp.js +38 -0
  16. package/dist/operator.d.ts +21 -0
  17. package/dist/operator.js +69 -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 +298 -0
  25. package/dist/schema.js +32 -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 +86 -0
  31. package/src/crypto.ts +54 -0
  32. package/src/engine.ts +156 -0
  33. package/src/executor.ts +131 -0
  34. package/src/mcp.ts +27 -0
  35. package/src/operator.ts +46 -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 +50 -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/batch.test.ts +132 -0
  44. package/test/cli.test.ts +60 -0
  45. package/test/mcp.test.ts +32 -0
  46. package/test/noise-vector.json +40 -0
  47. package/test/probe.test.ts +131 -0
  48. package/test/serial.test.ts +24 -0
  49. package/test/vector.test.ts +32 -0
  50. package/tsconfig.json +8 -0
package/dist/peer.js ADDED
@@ -0,0 +1,253 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { WebSocket } from 'ws';
3
+ import { Handshake, parseCode } from './crypto.js';
4
+ import { CHUNK_SIZE, MAX_FRAME, parseMessage } from './schema.js';
5
+ import { safeText } from './util.js';
6
+ function deferred() { let resolve; let reject; const promise = new Promise((a, b) => { resolve = a; reject = b; }); promise.catch(() => { }); return { promise, resolve, reject }; }
7
+ export function relayUrl(value) {
8
+ const url = new URL(value);
9
+ if (url.protocol === 'https:')
10
+ url.protocol = 'wss:';
11
+ if (url.protocol === 'http:')
12
+ url.protocol = 'ws:';
13
+ if (url.username || url.password || url.search || url.hash || !['wss:', 'ws:'].includes(url.protocol))
14
+ throw new Error('Invalid relay URL');
15
+ if (url.protocol === 'ws:' && !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
16
+ throw new Error('Remote relays require TLS');
17
+ url.pathname = '/v1/connect';
18
+ return url.href;
19
+ }
20
+ export class Peer extends EventEmitter {
21
+ options;
22
+ ws;
23
+ secret;
24
+ room;
25
+ handshake;
26
+ cipher;
27
+ registered = deferred();
28
+ accepted = deferred();
29
+ endedState = deferred();
30
+ active = this.accepted.promise;
31
+ ended = this.endedState.promise;
32
+ approved = false;
33
+ destroyed = false;
34
+ generation = 0;
35
+ approval;
36
+ queue = Promise.resolve();
37
+ queuedBytes = 0;
38
+ parts = [];
39
+ partialSize = 0;
40
+ lastSeen = Date.now();
41
+ heartbeat;
42
+ connectionTimer;
43
+ handshakeTimer;
44
+ fingerprint = '';
45
+ constructor(options) {
46
+ super();
47
+ this.options = options;
48
+ const { room, secret } = parseCode(options.code);
49
+ this.room = room;
50
+ this.secret = secret;
51
+ this.ws = new WebSocket(relayUrl(options.relay), { maxPayload: MAX_FRAME, perMessageDeflate: false, handshakeTimeout: 10000 });
52
+ this.connectionTimer = setTimeout(() => this.close('Relay registration timeout'), 12000);
53
+ this.ws.on('open', () => this.ws.send(JSON.stringify({ version: 1, role: options.role, room })));
54
+ this.ws.on('error', () => this.close('Relay connection failed'));
55
+ this.ws.on('close', () => this.close('Relay disconnected'));
56
+ this.ws.on('message', (bytes, binary) => {
57
+ try {
58
+ if (binary)
59
+ this.receive(Buffer.from(bytes));
60
+ else
61
+ this.control(JSON.parse(bytes.toString()));
62
+ }
63
+ catch {
64
+ if (options.role === 'host' && !this.approved)
65
+ this.rejectAttempt();
66
+ else
67
+ this.close('Authentication or protocol check failed');
68
+ }
69
+ });
70
+ }
71
+ async open() { await this.registered.promise; if (this.options.role === 'join')
72
+ await this.active; return this; }
73
+ control(message) {
74
+ switch (message.type) {
75
+ case 'registered':
76
+ clearTimeout(this.connectionTimer);
77
+ this.registered.resolve();
78
+ break;
79
+ case 'joined':
80
+ clearTimeout(this.connectionTimer);
81
+ this.registered.resolve();
82
+ this.handshake = new Handshake(true, this.room, this.secret);
83
+ this.ws.send(this.handshake.send(Buffer.from(JSON.stringify({ role: 'operator', label: (this.options.label ?? 'Diagnostic operator').slice(0, 120) }))));
84
+ this.handshakeTimer = setTimeout(() => this.close('Pairing or user approval timeout'), this.options.approvalTimeoutMs ?? 120000);
85
+ break;
86
+ case 'peer':
87
+ if (this.options.role !== 'host' || this.approved)
88
+ throw new Error('Unexpected peer');
89
+ this.handshake?.destroy();
90
+ this.handshake = new Handshake(false, this.room, this.secret);
91
+ clearTimeout(this.handshakeTimer);
92
+ this.handshakeTimer = setTimeout(() => this.rejectAttempt(), 15000);
93
+ break;
94
+ case 'peer-left':
95
+ if (this.approved)
96
+ this.close('Operator disconnected');
97
+ else
98
+ this.resetAttempt();
99
+ break;
100
+ default: throw new Error('Unexpected relay control');
101
+ }
102
+ }
103
+ receive(bytes) {
104
+ if (!this.cipher) {
105
+ if (!this.handshake || bytes.length > 4096)
106
+ throw new Error('Invalid handshake');
107
+ const hello = JSON.parse(this.handshake.receive(bytes).toString());
108
+ if (typeof hello.label !== 'string' || hello.label.length > 120 || hello.role !== (this.options.role === 'host' ? 'operator' : 'probe'))
109
+ throw new Error('Invalid peer hello');
110
+ if (this.options.role === 'host') {
111
+ const reply = this.handshake.send(Buffer.from(JSON.stringify({ role: 'probe', label: (this.options.label ?? 'User probe').slice(0, 120) })));
112
+ this.cipher = this.handshake.split();
113
+ this.handshake = undefined;
114
+ this.fingerprint = this.cipher.fingerprint;
115
+ this.ws.send(reply);
116
+ clearTimeout(this.handshakeTimer);
117
+ const generation = ++this.generation;
118
+ this.approval = new AbortController();
119
+ const timer = setTimeout(() => { this.approval?.abort(); this.close('Pairing approval timeout'); }, this.options.approvalTimeoutMs ?? 120000);
120
+ this.handshakeTimer = timer;
121
+ void (async () => {
122
+ const allowed = await this.options.accept?.({ label: safeText(hello.label), fingerprint: this.fingerprint, signal: this.approval.signal });
123
+ clearTimeout(timer);
124
+ if (this.destroyed || generation !== this.generation)
125
+ return;
126
+ if (!allowed || this.approval?.signal.aborted) {
127
+ await this.send({ type: 'session.closed', reason: 'User declined pairing' });
128
+ this.close('User declined pairing');
129
+ return;
130
+ }
131
+ this.ws.send(JSON.stringify({ type: 'lock' }));
132
+ this.approved = true;
133
+ await this.send({ type: 'session.accepted', label: safeText(this.options.label ?? 'User probe'), fingerprint: this.fingerprint });
134
+ this.activate();
135
+ })().catch(() => this.close('Pairing approval failed'));
136
+ }
137
+ else {
138
+ this.cipher = this.handshake.split();
139
+ this.handshake = undefined;
140
+ this.fingerprint = this.cipher.fingerprint;
141
+ }
142
+ return;
143
+ }
144
+ const frame = this.cipher.decrypt(bytes);
145
+ if (frame.length < 1 || frame[0] > 1)
146
+ throw new Error('Bad encrypted frame');
147
+ this.parts.push(frame.subarray(1));
148
+ this.partialSize += frame.length - 1;
149
+ if (this.partialSize > 2 * 1024 * 1024)
150
+ throw new Error('Message too large');
151
+ if (frame[0] === 0)
152
+ return;
153
+ const message = parseMessage(JSON.parse(Buffer.concat(this.parts).toString()));
154
+ this.parts = [];
155
+ this.partialSize = 0;
156
+ this.lastSeen = Date.now();
157
+ if (message.type === 'session.closed') {
158
+ this.close(message.reason);
159
+ return;
160
+ }
161
+ if (message.type === 'session.accepted' && this.options.role === 'join' && !this.approved) {
162
+ if (message.fingerprint !== this.fingerprint)
163
+ throw new Error('Channel binding mismatch');
164
+ clearTimeout(this.handshakeTimer);
165
+ this.approved = true;
166
+ this.activate();
167
+ return;
168
+ }
169
+ if (!this.approved)
170
+ throw new Error('Not authorized');
171
+ if (message.type === 'ping') {
172
+ void this.send({ type: 'pong' }).catch(() => this.close('Heartbeat failed'));
173
+ return;
174
+ }
175
+ if (message.type === 'pong')
176
+ return;
177
+ this.emit('message', message);
178
+ }
179
+ activate() {
180
+ this.secret.fill(0);
181
+ this.lastSeen = Date.now();
182
+ this.accepted.resolve();
183
+ this.emit('active');
184
+ this.heartbeat = setInterval(() => {
185
+ if (Date.now() - this.lastSeen > 25000) {
186
+ this.close('Peer heartbeat timeout');
187
+ return;
188
+ }
189
+ void this.send({ type: 'ping' }).catch(() => this.close('Heartbeat failed'));
190
+ }, 5000);
191
+ this.heartbeat.unref();
192
+ }
193
+ send(message) {
194
+ if (!this.cipher || this.destroyed)
195
+ return Promise.reject(new Error('Encrypted connection unavailable'));
196
+ const payload = Buffer.from(JSON.stringify(message));
197
+ if (payload.length > 2 * 1024 * 1024 || this.queuedBytes + payload.length > 4 * 1024 * 1024)
198
+ return Promise.reject(new Error('Send queue exceeded'));
199
+ this.queuedBytes += payload.length;
200
+ const operation = this.queue.then(async () => {
201
+ for (let offset = 0; offset < payload.length; offset += CHUNK_SIZE) {
202
+ if (this.destroyed || !this.cipher)
203
+ throw new Error('Connection closed');
204
+ const part = payload.subarray(offset, offset + CHUNK_SIZE);
205
+ const frame = Buffer.concat([Buffer.from([offset + part.length === payload.length ? 1 : 0]), part]);
206
+ await this.writeRaw(this.cipher.encrypt(frame));
207
+ // Bound sustained traffic below the relay's shared per-room frame budget.
208
+ await new Promise(resolve => setTimeout(resolve, 10));
209
+ }
210
+ }).finally(() => { this.queuedBytes -= payload.length; });
211
+ this.queue = operation.catch(() => this.close('Encrypted transport failed'));
212
+ return operation;
213
+ }
214
+ writeRaw(bytes) {
215
+ return new Promise((resolve, reject) => { if (this.ws.readyState !== WebSocket.OPEN) {
216
+ reject(new Error('Socket closed'));
217
+ return;
218
+ } this.ws.send(bytes, { binary: true }, error => error ? reject(error) : resolve()); });
219
+ }
220
+ resetAttempt() {
221
+ this.generation++;
222
+ this.approval?.abort();
223
+ clearTimeout(this.handshakeTimer);
224
+ this.handshake?.destroy();
225
+ this.handshake = undefined;
226
+ this.cipher?.destroy();
227
+ this.cipher = undefined;
228
+ this.parts = [];
229
+ this.partialSize = 0;
230
+ }
231
+ rejectAttempt() {
232
+ this.resetAttempt();
233
+ if (this.ws.readyState === WebSocket.OPEN)
234
+ this.ws.send(JSON.stringify({ type: 'reject' }));
235
+ }
236
+ close(reason = 'Session ended') {
237
+ if (this.destroyed)
238
+ return;
239
+ this.destroyed = true;
240
+ clearTimeout(this.connectionTimer);
241
+ clearInterval(this.heartbeat);
242
+ this.resetAttempt();
243
+ this.secret.fill(0);
244
+ const error = new Error(reason);
245
+ this.registered.reject(error);
246
+ this.accepted.reject(error);
247
+ this.endedState.resolve(reason);
248
+ this.ws.close(1000, 'Session ended');
249
+ const kill = setTimeout(() => this.ws.terminate(), 1000);
250
+ kill.unref();
251
+ this.emit('closed', reason);
252
+ }
253
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,6 @@
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'])
6
+ process.once(signal, () => { void relay.close(); });
@@ -0,0 +1,15 @@
1
+ import http from 'node:http';
2
+ export type RelayOptions = {
3
+ host?: string;
4
+ port?: number;
5
+ invitationMs?: number;
6
+ sessionMs?: number;
7
+ maxRooms?: number;
8
+ downloadPath?: string;
9
+ observeCiphertext?: (bytes: Buffer) => void;
10
+ };
11
+ export declare function createRelay(options?: RelayOptions): {
12
+ server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
13
+ listen(): Promise<number>;
14
+ close(): Promise<void>;
15
+ };
package/dist/relay.js ADDED
@@ -0,0 +1,176 @@
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
+ const control = (ws, type, extra = {}) => { if (ws.readyState === WebSocket.OPEN)
6
+ ws.send(JSON.stringify({ type, ...extra })); };
7
+ export function createRelay(options = {}) {
8
+ const rooms = new Map();
9
+ const clients = new Map();
10
+ const connectionsByIp = new Map();
11
+ const server = http.createServer((req, res) => {
12
+ res.setHeader('Cache-Control', 'no-store');
13
+ res.setHeader('X-Content-Type-Options', 'nosniff');
14
+ if (req.method === 'GET' && req.url === '/healthz') {
15
+ res.setHeader('Content-Type', 'application/json');
16
+ res.end('{"ok":true,"protocol":1}');
17
+ return;
18
+ }
19
+ if (req.method === 'GET' && req.url === '/downloads/diagnose-0.1.0.tgz' && options.downloadPath) {
20
+ try {
21
+ const size = statSync(options.downloadPath).size;
22
+ res.setHeader('Content-Type', 'application/octet-stream');
23
+ res.setHeader('Content-Length', size);
24
+ createReadStream(options.downloadPath).on('error', () => res.destroy()).pipe(res);
25
+ }
26
+ catch {
27
+ res.writeHead(404);
28
+ res.end();
29
+ }
30
+ return;
31
+ }
32
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
33
+ res.writeHead(req.url === '/' ? 200 : 404);
34
+ res.end(req.url === '/' ? 'Diagnose blind relay v1. User-approved, end-to-end encrypted diagnostics.\n' : 'Not found\n');
35
+ });
36
+ const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME, perMessageDeflate: false });
37
+ server.on('upgrade', (req, socket, head) => {
38
+ if (req.url !== '/v1/connect' || clients.size >= 400) {
39
+ socket.destroy();
40
+ return;
41
+ }
42
+ wss.handleUpgrade(req, socket, head, ws => wss.emit('connection', ws, req));
43
+ });
44
+ wss.on('connection', (ws, req) => {
45
+ const direct = req.socket.remoteAddress ?? 'unknown';
46
+ 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;
47
+ if ((connectionsByIp.get(ip) ?? 0) >= 30) {
48
+ ws.close(1008, 'Connection limit');
49
+ return;
50
+ }
51
+ connectionsByIp.set(ip, (connectionsByIp.get(ip) ?? 0) + 1);
52
+ const state = { ip, alive: true };
53
+ clients.set(ws, state);
54
+ const registration = setTimeout(() => { if (!state.role)
55
+ ws.close(1008, 'Registration timeout'); }, 5000);
56
+ ws.on('pong', () => { state.alive = true; });
57
+ ws.on('error', () => ws.terminate());
58
+ ws.on('message', (raw, binary) => {
59
+ try {
60
+ const bytes = Buffer.from(raw);
61
+ if (!state.role) {
62
+ if (binary || bytes.length > 256)
63
+ throw new Error();
64
+ const msg = JSON.parse(bytes.toString());
65
+ if (msg.version !== 1 || !/^[A-Za-z0-9_-]{16}$/.test(msg.room) || !['host', 'join'].includes(msg.role))
66
+ throw new Error();
67
+ if (msg.role === 'host') {
68
+ if (rooms.has(msg.room) || rooms.size >= (options.maxRooms ?? 100))
69
+ throw new Error();
70
+ rooms.set(msg.room, { host: ws, locked: false, attempts: 0, expires: Date.now() + (options.invitationMs ?? 600000), frames: 0, window: Date.now() });
71
+ state.role = 'host';
72
+ state.room = msg.room;
73
+ control(ws, 'registered');
74
+ }
75
+ else {
76
+ const room = rooms.get(msg.room);
77
+ if (!room || room.locked || room.peer || room.attempts >= 10 || room.expires < Date.now())
78
+ throw new Error();
79
+ state.role = 'join';
80
+ state.room = msg.room;
81
+ room.peer = ws;
82
+ room.attempts++;
83
+ control(room.host, 'peer');
84
+ control(ws, 'joined');
85
+ }
86
+ clearTimeout(registration);
87
+ return;
88
+ }
89
+ const room = rooms.get(state.room);
90
+ if (!room)
91
+ throw new Error();
92
+ if (binary) {
93
+ if (Date.now() - room.window > 1000) {
94
+ room.window = Date.now();
95
+ room.frames = 0;
96
+ }
97
+ if (++room.frames > 250 || bytes.length > MAX_FRAME)
98
+ throw new Error();
99
+ const target = state.role === 'host' ? room.peer : room.host;
100
+ if (!target || target.readyState !== WebSocket.OPEN || target.bufferedAmount > 1024 * 1024)
101
+ throw new Error();
102
+ let buffered = 0;
103
+ for (const client of clients.keys())
104
+ buffered += client.bufferedAmount;
105
+ if (buffered > 64 * 1024 * 1024)
106
+ throw new Error();
107
+ options.observeCiphertext?.(bytes);
108
+ target.send(bytes, { binary: true });
109
+ return;
110
+ }
111
+ if (bytes.length > 128 || state.role !== 'host')
112
+ throw new Error();
113
+ const msg = JSON.parse(bytes.toString());
114
+ if (msg.type === 'lock') {
115
+ room.locked = true;
116
+ room.expires = Date.now() + (options.sessionMs ?? 3600000);
117
+ }
118
+ else if (msg.type === 'reject' && !room.locked) {
119
+ const peer = room.peer;
120
+ room.peer = undefined;
121
+ peer?.close(1008, 'Pairing rejected');
122
+ }
123
+ else
124
+ throw new Error();
125
+ }
126
+ catch {
127
+ ws.close(1008, 'Protocol rejected');
128
+ }
129
+ });
130
+ ws.on('close', () => {
131
+ clearTimeout(registration);
132
+ clients.delete(ws);
133
+ const count = (connectionsByIp.get(ip) ?? 1) - 1;
134
+ if (count > 0)
135
+ connectionsByIp.set(ip, count);
136
+ else
137
+ connectionsByIp.delete(ip);
138
+ const room = rooms.get(state.room);
139
+ if (!room)
140
+ return;
141
+ if (state.role === 'host') {
142
+ rooms.delete(state.room);
143
+ room.peer?.close(1000, 'Session ended');
144
+ }
145
+ else if (room.peer === ws) {
146
+ room.peer = undefined;
147
+ control(room.host, 'peer-left');
148
+ if (room.locked)
149
+ room.host.close(1000, 'Peer disconnected');
150
+ }
151
+ });
152
+ });
153
+ const sweep = setInterval(() => {
154
+ for (const [id, room] of rooms)
155
+ if (room.expires < Date.now()) {
156
+ rooms.delete(id);
157
+ room.host.close(1000, 'Session expired');
158
+ room.peer?.close(1000, 'Session expired');
159
+ }
160
+ for (const [ws, state] of clients) {
161
+ if (!state.alive)
162
+ ws.terminate();
163
+ else {
164
+ state.alive = false;
165
+ ws.ping();
166
+ }
167
+ }
168
+ }, 10000);
169
+ sweep.unref();
170
+ return {
171
+ server,
172
+ async listen() { await new Promise((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().port; },
173
+ async close() { clearInterval(sweep); for (const ws of wss.clients)
174
+ ws.terminate(); await new Promise(resolve => wss.close(() => resolve())); await new Promise(resolve => server.close(() => resolve())); },
175
+ };
176
+ }