@masstensor/diagnose 0.5.0 → 0.8.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/DEVELOPMENT_PLAN.md +69 -0
- package/KNOWLEDGE_SECURITY.md +47 -0
- package/PAIRING_PROTOCOL.md +37 -0
- package/README.md +28 -6
- package/USER_GUIDE.md +250 -34
- package/deploy/Caddyfile +1 -1
- package/deploy/ecosystem.config.cjs +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +15 -5
- package/dist/cases.d.ts +118 -0
- package/dist/cases.js +115 -0
- package/dist/cli.js +61 -13
- package/dist/crypto.d.ts +7 -0
- package/dist/crypto.js +16 -1
- package/dist/discover.js +1 -1
- package/dist/engine.d.ts +1 -0
- package/dist/engine.js +21 -7
- package/dist/install-skill.d.ts +2 -0
- package/dist/install-skill.js +57 -0
- package/dist/knowledge-cli.d.ts +2 -0
- package/dist/knowledge-cli.js +164 -0
- package/dist/knowledge-drafts.d.ts +47 -0
- package/dist/knowledge-drafts.js +76 -0
- package/dist/knowledge-mcp.d.ts +5 -0
- package/dist/knowledge-mcp.js +65 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +38 -9
- package/dist/operator.d.ts +2 -0
- package/dist/operator.js +18 -3
- package/dist/peer.d.ts +9 -0
- package/dist/peer.js +90 -10
- package/dist/relay-main.js +1 -1
- package/dist/relay.d.ts +1 -0
- package/dist/relay.js +46 -10
- package/dist/schema.d.ts +4 -1
- package/dist/schema.js +2 -2
- package/dist/session-limits.d.ts +3 -0
- package/dist/session-limits.js +3 -0
- package/dist/short-pairing.d.ts +25 -0
- package/dist/short-pairing.js +73 -0
- package/dist/skill-library.d.ts +27 -0
- package/dist/skill-library.js +226 -0
- package/dist/skill-session.d.ts +1 -0
- package/dist/skill-session.js +257 -0
- package/dist/skill.d.ts +1 -0
- package/dist/skill.js +1 -0
- package/dist/util.js +1 -0
- package/dist/vault-crypto.d.ts +11 -0
- package/dist/vault-crypto.js +30 -0
- package/dist/vault-server.d.ts +10 -0
- package/dist/vault-server.js +156 -0
- package/dist/vault.d.ts +19 -0
- package/dist/vault.js +72 -0
- package/npm-shrinkwrap.json +12 -2
- package/package.json +7 -2
- package/skills/connect/SKILL.md +60 -0
- package/skills/connect/scripts/run.mjs +37 -0
- package/src/agent.ts +12 -5
- package/src/cases.ts +74 -0
- package/src/cli.ts +51 -13
- package/src/crypto.ts +14 -1
- package/src/discover.ts +1 -1
- package/src/engine.ts +17 -4
- package/src/install-skill.ts +57 -0
- package/src/knowledge-cli.ts +67 -0
- package/src/knowledge-drafts.ts +55 -0
- package/src/knowledge-mcp.ts +35 -0
- package/src/mcp.ts +21 -7
- package/src/operator.ts +12 -3
- package/src/peer.ts +51 -14
- package/src/relay-main.ts +1 -1
- package/src/relay.ts +35 -7
- package/src/schema.ts +4 -2
- package/src/session-limits.ts +3 -0
- package/src/short-pairing.ts +57 -0
- package/src/skill-library.ts +162 -0
- package/src/skill-session.ts +233 -0
- package/src/skill.ts +2 -1
- package/src/util.ts +1 -0
- package/src/vault-crypto.ts +25 -0
- package/src/vault-server.ts +72 -0
- package/src/vault.ts +51 -0
- package/test/agent.test.ts +26 -1
- package/test/cli.test.ts +58 -10
- package/test/install-skill.test.ts +37 -0
- package/test/knowledge-mcp.test.ts +37 -0
- package/test/knowledge.test.ts +112 -0
- package/test/mcp.test.ts +1 -1
- package/test/pairing.test.ts +8 -3
- package/test/review.test.ts +17 -0
- package/test/short-pairing.test.ts +142 -0
- package/test/skill-library.test.ts +62 -0
- package/test/skill-session.test.ts +79 -0
- package/test/skill.test.ts +1 -1
package/src/peer.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { EventEmitter } from 'node:events';
|
|
2
2
|
import { WebSocket } from 'ws';
|
|
3
|
-
import { Handshake, parseCode, type SecureCipher } from './crypto.js';
|
|
3
|
+
import { Handshake, parseCode, parseInvitation, INVITATION_MS, type SecureCipher } from './crypto.js';
|
|
4
4
|
import { CHUNK_SIZE, MAX_FRAME, parseMessage, type WireMessage } from './schema.js';
|
|
5
5
|
import { safeText } from './util.js';
|
|
6
|
+
import { InvitationHost, InvitationJoin } from './short-pairing.js';
|
|
7
|
+
import { LEGACY_RELAY_MAX_MS } from './session-limits.js';
|
|
6
8
|
|
|
7
|
-
export type PeerOptions = { role: 'host' | 'join'; code: string; relay: string; label?: string; remember?: boolean; provision?: () => string | undefined; accept?: (peer: { label: string; fingerprint: string; signal: AbortSignal; remember: boolean }) => Promise<boolean>; approvalTimeoutMs?: number; sessionMs?: number };
|
|
9
|
+
export type PeerOptions = { role: 'host' | 'join'; code: string; relay: string; label?: string; remember?: boolean; provision?: () => string | undefined; accept?: (peer: { label: string; fingerprint: string; signal: AbortSignal; remember: boolean }) => Promise<boolean>; approvalTimeoutMs?: number; sessionMs?: number; invitationMs?: number };
|
|
8
10
|
function deferred<T>() { let resolve!: (value: T) => void; let reject!: (error: Error) => void; const promise = new Promise<T>((a, b) => { resolve = a; reject = b; }); promise.catch(() => {}); return { promise, resolve, reject }; }
|
|
9
11
|
export function relayUrl(value: string): string {
|
|
10
12
|
const url = new URL(value);
|
|
@@ -38,17 +40,30 @@ export class Peer extends EventEmitter {
|
|
|
38
40
|
private heartbeat?: NodeJS.Timeout;
|
|
39
41
|
private connectionTimer: NodeJS.Timeout;
|
|
40
42
|
private handshakeTimer?: NodeJS.Timeout;
|
|
43
|
+
private short: boolean;
|
|
44
|
+
private invitationHost?: InvitationHost;
|
|
45
|
+
private invitationJoin?: InvitationJoin;
|
|
46
|
+
private pakeStage?: 'start' | 'finish' | 'response';
|
|
47
|
+
private invitationTimer?: NodeJS.Timeout;
|
|
48
|
+
private attempts = 0;
|
|
49
|
+
private joined = false;
|
|
41
50
|
fingerprint = '';
|
|
42
51
|
rememberedCode?: string;
|
|
43
52
|
|
|
44
53
|
constructor(private options: PeerOptions) {
|
|
45
54
|
super();
|
|
46
|
-
const { room, secret } =
|
|
55
|
+
const { room, secret, short } = parseInvitation(options.code); this.room = room; this.secret = secret; this.short = short;
|
|
56
|
+
if (short && options.role === 'host') this.invitationHost = new InvitationHost(room, secret);
|
|
47
57
|
this.ws = new WebSocket(relayUrl(options.relay), { maxPayload: MAX_FRAME, perMessageDeflate: false, handshakeTimeout: 10000 });
|
|
48
58
|
this.connectionTimer = setTimeout(() => this.close('Relay registration timeout'), 12000);
|
|
49
|
-
|
|
59
|
+
if (short && options.role === 'host') this.invitationTimer = setTimeout(() => this.close('Invitation expired; generate a new code'), Math.min(options.invitationMs ?? INVITATION_MS, INVITATION_MS));
|
|
60
|
+
this.ws.on('open', () => this.ws.send(JSON.stringify({ version: short ? 2 : 1, role: options.role, room })));
|
|
50
61
|
this.ws.on('error', () => this.close('Relay connection failed'));
|
|
51
|
-
this.ws.on('close', () =>
|
|
62
|
+
this.ws.on('close', (_code, reason) => {
|
|
63
|
+
const message = reason.toString();
|
|
64
|
+
this.close(message === 'Invitation locator occupied' ? 'Invitation locator occupied; generating a new code'
|
|
65
|
+
: message === 'Session expired' ? 'Relay session expired' : 'Relay disconnected');
|
|
66
|
+
});
|
|
52
67
|
this.ws.on('message', (bytes, binary) => {
|
|
53
68
|
try {
|
|
54
69
|
if (binary) this.receive(Buffer.from(bytes as Buffer));
|
|
@@ -65,23 +80,37 @@ export class Peer extends EventEmitter {
|
|
|
65
80
|
case 'registered': clearTimeout(this.connectionTimer); this.registered.resolve(); break;
|
|
66
81
|
case 'joined':
|
|
67
82
|
clearTimeout(this.connectionTimer); this.registered.resolve();
|
|
68
|
-
this.
|
|
69
|
-
this.
|
|
83
|
+
if (this.options.role !== 'join' || this.joined) throw new Error('Unexpected join');
|
|
84
|
+
this.joined = true;
|
|
85
|
+
if (this.short) { this.invitationJoin = new InvitationJoin(this.room, this.secret); this.pakeStage = 'response'; this.ws.send(this.invitationJoin.start()); }
|
|
86
|
+
else this.startNoise(this.secret);
|
|
70
87
|
this.handshakeTimer = setTimeout(() => this.close('Pairing or user approval timeout'), this.options.approvalTimeoutMs ?? 120000);
|
|
71
88
|
break;
|
|
72
89
|
case 'peer':
|
|
73
90
|
if (this.options.role !== 'host' || this.approved) throw new Error('Unexpected peer');
|
|
74
|
-
this.
|
|
75
|
-
|
|
91
|
+
if (this.short && ++this.attempts > 5) { this.close('Invitation attempt limit reached'); return; }
|
|
92
|
+
this.resetAttempt();
|
|
93
|
+
if (this.short) this.pakeStage = 'start';
|
|
94
|
+
else this.handshake = new Handshake(false, this.room, this.secret);
|
|
76
95
|
this.handshakeTimer = setTimeout(() => this.rejectAttempt(), 15000);
|
|
77
96
|
break;
|
|
78
97
|
case 'peer-left':
|
|
79
|
-
if (this.approved) this.close('Operator disconnected'); else this.resetAttempt();
|
|
98
|
+
if (this.approved) this.close('Operator disconnected'); else if (this.short && this.attempts >= 5) this.close('Invitation attempt limit reached'); else this.resetAttempt();
|
|
80
99
|
break;
|
|
81
100
|
default: throw new Error('Unexpected relay control');
|
|
82
101
|
}
|
|
83
102
|
}
|
|
103
|
+
private startNoise(secret: Buffer): void {
|
|
104
|
+
this.handshake = new Handshake(true, this.room, secret);
|
|
105
|
+
this.ws.send(this.handshake.send(Buffer.from(JSON.stringify({ role: 'operator', label: (this.options.label ?? 'Diagnostic operator').slice(0, 120), ...(this.options.remember ? { remember: true } : {}) }))));
|
|
106
|
+
}
|
|
84
107
|
private receive(bytes: Buffer): void {
|
|
108
|
+
if (this.pakeStage) {
|
|
109
|
+
if (this.pakeStage === 'start') { this.ws.send(this.invitationHost!.start(bytes)); this.pakeStage = 'finish'; }
|
|
110
|
+
else if (this.pakeStage === 'finish') { const secret = this.invitationHost!.finish(bytes); this.handshake = new Handshake(false, this.room, secret); secret.fill(0); this.pakeStage = undefined; }
|
|
111
|
+
else { const result = this.invitationJoin!.finish(bytes); this.ws.send(result.reply); this.pakeStage = undefined; this.startNoise(result.secret); result.secret.fill(0); this.invitationJoin!.destroy(); this.invitationJoin = undefined; }
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
85
114
|
if (!this.cipher) {
|
|
86
115
|
if (!this.handshake || bytes.length > 4096) throw new Error('Invalid handshake');
|
|
87
116
|
const hello = JSON.parse(this.handshake.receive(bytes).toString());
|
|
@@ -100,7 +129,9 @@ export class Peer extends EventEmitter {
|
|
|
100
129
|
clearTimeout(timer);
|
|
101
130
|
if (this.destroyed || generation !== this.generation) return;
|
|
102
131
|
if (!allowed || this.approval?.signal.aborted) { await this.send({ type: 'session.closed', reason: 'User declined pairing' }); this.close('User declined pairing'); return; }
|
|
103
|
-
this.ws.send(JSON.stringify(
|
|
132
|
+
this.ws.send(JSON.stringify(this.options.sessionMs
|
|
133
|
+
? { type: 'lock', ttlMs: this.options.sessionMs }
|
|
134
|
+
: { type: 'lock', sliding: true, ttlMs: LEGACY_RELAY_MAX_MS }));
|
|
104
135
|
this.approved = true;
|
|
105
136
|
await this.send({ type: 'session.accepted', label: safeText(this.options.label ?? 'User probe'), fingerprint: this.fingerprint, ...(hello.remember === true && this.options.provision?.() ? { credential: this.options.provision!() } : {}) });
|
|
106
137
|
this.activate();
|
|
@@ -124,12 +155,15 @@ export class Peer extends EventEmitter {
|
|
|
124
155
|
clearTimeout(this.handshakeTimer); this.approved = true; this.activate(); return;
|
|
125
156
|
}
|
|
126
157
|
if (!this.approved) throw new Error('Not authorized');
|
|
127
|
-
if (message.type === 'ping') {
|
|
158
|
+
if (message.type === 'ping') {
|
|
159
|
+
if (message.activity && this.options.role === 'host') this.emit('activity');
|
|
160
|
+
void this.send({ type: 'pong' }).catch(() => this.close('Heartbeat failed')); return;
|
|
161
|
+
}
|
|
128
162
|
if (message.type === 'pong') return;
|
|
129
163
|
this.emit('message', message);
|
|
130
164
|
}
|
|
131
165
|
private activate(): void {
|
|
132
|
-
this.secret.fill(0); this.lastSeen = Date.now(); this.accepted.resolve(); this.emit('active');
|
|
166
|
+
clearTimeout(this.invitationTimer); this.invitationHost?.destroy(); this.invitationHost = undefined; this.secret.fill(0); this.lastSeen = Date.now(); this.accepted.resolve(); this.emit('active');
|
|
133
167
|
this.heartbeat = setInterval(() => {
|
|
134
168
|
if (Date.now() - this.lastSeen > 25000) { this.close('Peer heartbeat timeout'); return; }
|
|
135
169
|
void this.send({ type: 'ping' }).catch(() => this.close('Heartbeat failed'));
|
|
@@ -150,6 +184,7 @@ export class Peer extends EventEmitter {
|
|
|
150
184
|
// Bound sustained traffic below the relay's shared per-room frame budget.
|
|
151
185
|
await new Promise(resolve => setTimeout(resolve, 10));
|
|
152
186
|
}
|
|
187
|
+
if (message.type.startsWith('task.') || message.type.startsWith('resource.')) this.emit('activity');
|
|
153
188
|
}).finally(() => { this.queuedBytes -= payload.length; });
|
|
154
189
|
this.queue = operation.catch(() => this.close('Encrypted transport failed'));
|
|
155
190
|
return operation;
|
|
@@ -159,16 +194,18 @@ export class Peer extends EventEmitter {
|
|
|
159
194
|
}
|
|
160
195
|
private resetAttempt(): void {
|
|
161
196
|
this.generation++; this.approval?.abort(); clearTimeout(this.handshakeTimer);
|
|
197
|
+
this.pakeStage = undefined; this.invitationHost?.reset(); this.invitationJoin?.destroy(); this.invitationJoin = undefined;
|
|
162
198
|
this.handshake?.destroy(); this.handshake = undefined; this.cipher?.destroy(); this.cipher = undefined;
|
|
163
199
|
this.parts = []; this.partialSize = 0;
|
|
164
200
|
}
|
|
165
201
|
private rejectAttempt(): void {
|
|
202
|
+
if (this.short && this.attempts >= 5) { this.close('Invitation attempt limit reached'); return; }
|
|
166
203
|
this.resetAttempt();
|
|
167
204
|
if (this.ws.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ type: 'reject' }));
|
|
168
205
|
}
|
|
169
206
|
close(reason = 'Session ended'): void {
|
|
170
207
|
if (this.destroyed) return;
|
|
171
|
-
this.destroyed = true; clearTimeout(this.connectionTimer); clearInterval(this.heartbeat); this.resetAttempt(); this.secret.fill(0);
|
|
208
|
+
this.destroyed = true; clearTimeout(this.invitationTimer); this.invitationHost?.destroy(); this.invitationHost = undefined; clearTimeout(this.connectionTimer); clearInterval(this.heartbeat); this.resetAttempt(); this.secret.fill(0);
|
|
172
209
|
const error = new Error(reason); this.registered.reject(error); this.accepted.reject(error); this.endedState.resolve(reason);
|
|
173
210
|
this.ws.close(1000, 'Session ended'); const kill = setTimeout(() => this.ws.terminate(), 1000); kill.unref();
|
|
174
211
|
this.emit('closed', reason);
|
package/src/relay-main.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
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 });
|
|
3
|
+
const relay = createRelay({ host: process.env.HOST ?? '127.0.0.1', port: Number(process.env.PORT ?? 8792), downloadPath: process.env.DOWNLOAD_PATH, vaultPath: process.env.VAULT_PATH });
|
|
4
4
|
relay.listen().then(() => console.log('diagnose-relay ready')).catch(() => { console.error('RELAY_START_FAILED'); process.exitCode = 1; });
|
|
5
5
|
for (const signal of ['SIGTERM', 'SIGINT']) process.once(signal, () => { void relay.close(); });
|
package/src/relay.ts
CHANGED
|
@@ -2,18 +2,29 @@ import http from 'node:http';
|
|
|
2
2
|
import { createReadStream, statSync } from 'node:fs';
|
|
3
3
|
import { WebSocket, WebSocketServer } from 'ws';
|
|
4
4
|
import { MAX_FRAME } from './schema.js';
|
|
5
|
+
import { INVITATION_MS } from './crypto.js';
|
|
6
|
+
import { VaultServer } from './vault-server.js';
|
|
7
|
+
import { DEFAULT_IDLE_MS, LEGACY_RELAY_MAX_MS } from './session-limits.js';
|
|
5
8
|
|
|
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 };
|
|
9
|
+
export type RelayOptions = { host?: string; port?: number; invitationMs?: number; sessionMs?: number; maxRooms?: number; downloadPath?: string; vaultPath?: string; observeCiphertext?: (bytes: Buffer) => void };
|
|
10
|
+
type Room = { short: boolean; host: WebSocket; peer?: WebSocket; locked: boolean; attempts: number; expires: number; renewMs?: number; frames: number; window: number };
|
|
8
11
|
const control = (ws: WebSocket, type: string, extra = {}): void => { if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type, ...extra })); };
|
|
9
12
|
|
|
10
13
|
export function createRelay(options: RelayOptions = {}) {
|
|
14
|
+
const vault = options.vaultPath ? new VaultServer(options.vaultPath) : undefined;
|
|
11
15
|
const rooms = new Map<string, Room>();
|
|
16
|
+
const expireRoom = (id: string, room: Room): void => {
|
|
17
|
+
rooms.delete(id);
|
|
18
|
+
room.host.close(1000, 'Session expired');
|
|
19
|
+
room.peer?.close(1000, 'Session expired');
|
|
20
|
+
};
|
|
12
21
|
const clients = new Map<WebSocket, { role?: 'host' | 'join'; room?: string; ip: string; alive: boolean }>();
|
|
13
22
|
const connectionsByIp = new Map<string, number>();
|
|
23
|
+
const connectionRates = new Map<string, { since: number; count: number }>();
|
|
14
24
|
const server = http.createServer((req, res) => {
|
|
15
25
|
res.setHeader('Cache-Control', 'no-store');
|
|
16
26
|
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
27
|
+
if (req.url?.startsWith('/v1/library') && vault) { void vault.handle(req, res); return; }
|
|
17
28
|
if (req.method === 'GET' && req.url === '/healthz') { res.setHeader('Content-Type', 'application/json'); res.end('{"ok":true,"protocol":1}'); return; }
|
|
18
29
|
if (req.method === 'GET' && req.url === '/downloads/diagnose-0.1.0.tgz' && options.downloadPath) {
|
|
19
30
|
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;
|
|
@@ -30,6 +41,11 @@ export function createRelay(options: RelayOptions = {}) {
|
|
|
30
41
|
wss.on('connection', (ws, req) => {
|
|
31
42
|
const direct = req.socket.remoteAddress ?? 'unknown';
|
|
32
43
|
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;
|
|
44
|
+
const now = Date.now();
|
|
45
|
+
for (const [key, rate] of connectionRates) if (now - rate.since > 60000) connectionRates.delete(key);
|
|
46
|
+
const rate = connectionRates.get(ip) ?? { since: now, count: 0 };
|
|
47
|
+
if ((!connectionRates.has(ip) && connectionRates.size >= 10000) || ++rate.count > 60) { ws.close(1008, 'Connection rate limit'); return; }
|
|
48
|
+
connectionRates.set(ip, rate);
|
|
33
49
|
if ((connectionsByIp.get(ip) ?? 0) >= 30) { ws.close(1008, 'Connection limit'); return; }
|
|
34
50
|
connectionsByIp.set(ip, (connectionsByIp.get(ip) ?? 0) + 1);
|
|
35
51
|
const state = { ip, alive: true } as { role?: 'host' | 'join'; room?: string; ip: string; alive: boolean };
|
|
@@ -43,14 +59,16 @@ export function createRelay(options: RelayOptions = {}) {
|
|
|
43
59
|
if (!state.role) {
|
|
44
60
|
if (binary || bytes.length > 256) throw new Error();
|
|
45
61
|
const msg = JSON.parse(bytes.toString());
|
|
46
|
-
|
|
62
|
+
const short = msg.version === 2 && /^S2\.[a-z]{2}$/.test(msg.room);
|
|
63
|
+
if (!(short || (msg.version === 1 && /^[A-Za-z0-9_-]{16}$/.test(msg.room))) || !['host', 'join'].includes(msg.role)) throw new Error();
|
|
47
64
|
if (msg.role === 'host') {
|
|
65
|
+
if (short && rooms.has(msg.room)) { ws.close(1008, 'Invitation locator occupied'); return; }
|
|
48
66
|
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() });
|
|
67
|
+
rooms.set(msg.room, { short, host: ws, locked: false, attempts: 0, expires: Date.now() + (short ? Math.min(options.invitationMs ?? INVITATION_MS, INVITATION_MS) : options.invitationMs ?? 600000), frames: 0, window: Date.now() });
|
|
50
68
|
state.role = 'host'; state.room = msg.room; control(ws, 'registered');
|
|
51
69
|
} else {
|
|
52
70
|
const room = rooms.get(msg.room);
|
|
53
|
-
if (!room || room.locked || room.peer || room.attempts >= 10 || room.expires < Date.now()) throw new Error();
|
|
71
|
+
if (!room || room.locked || room.peer || room.attempts >= (room.short ? 5 : 10) || room.expires < Date.now()) throw new Error();
|
|
54
72
|
state.role = 'join'; state.room = msg.room; room.peer = ws; room.attempts++;
|
|
55
73
|
control(room.host, 'peer'); control(ws, 'joined');
|
|
56
74
|
}
|
|
@@ -58,6 +76,7 @@ export function createRelay(options: RelayOptions = {}) {
|
|
|
58
76
|
}
|
|
59
77
|
const room = rooms.get(state.room!);
|
|
60
78
|
if (!room) throw new Error();
|
|
79
|
+
if (room.expires <= Date.now()) { expireRoom(state.room!, room); return; }
|
|
61
80
|
if (binary) {
|
|
62
81
|
if (Date.now() - room.window > 1000) { room.window = Date.now(); room.frames = 0; }
|
|
63
82
|
if (++room.frames > 250 || bytes.length > MAX_FRAME) throw new Error();
|
|
@@ -65,12 +84,21 @@ export function createRelay(options: RelayOptions = {}) {
|
|
|
65
84
|
if (!target || target.readyState !== WebSocket.OPEN || target.bufferedAmount > 1024 * 1024) throw new Error();
|
|
66
85
|
let buffered = 0; for (const client of clients.keys()) buffered += client.bufferedAmount;
|
|
67
86
|
if (buffered > 64 * 1024 * 1024) throw new Error();
|
|
87
|
+
// The relay can see ciphertext traffic, not diagnostic activity. The
|
|
88
|
+
// probe enforces the real idle timeout without counting heartbeats.
|
|
89
|
+
if (room.renewMs) room.expires = Date.now() + room.renewMs;
|
|
68
90
|
options.observeCiphertext?.(bytes);
|
|
69
91
|
target.send(bytes, { binary: true }); return;
|
|
70
92
|
}
|
|
71
93
|
if (bytes.length > 128 || state.role !== 'host') throw new Error();
|
|
72
94
|
const msg = JSON.parse(bytes.toString());
|
|
73
|
-
if (msg.type === 'lock' && !room.locked) {
|
|
95
|
+
if (msg.type === 'lock' && !room.locked) {
|
|
96
|
+
const requested = msg.ttlMs;
|
|
97
|
+
if (requested !== undefined && (!Number.isInteger(requested) || requested < 60000 || requested > LEGACY_RELAY_MAX_MS)) throw new Error();
|
|
98
|
+
room.locked = true;
|
|
99
|
+
if (msg.sliding === true) room.renewMs = options.sessionMs ?? DEFAULT_IDLE_MS;
|
|
100
|
+
room.expires = Date.now() + (room.renewMs ?? requested ?? options.sessionMs ?? DEFAULT_IDLE_MS);
|
|
101
|
+
}
|
|
74
102
|
else if (msg.type === 'reject' && !room.locked) { const peer = room.peer; room.peer = undefined; peer?.close(1008, 'Pairing rejected'); }
|
|
75
103
|
else throw new Error();
|
|
76
104
|
} catch { ws.close(1008, 'Protocol rejected'); }
|
|
@@ -85,7 +113,7 @@ export function createRelay(options: RelayOptions = {}) {
|
|
|
85
113
|
});
|
|
86
114
|
});
|
|
87
115
|
const sweep = setInterval(() => {
|
|
88
|
-
for (const [id, room] of rooms) if (room.expires
|
|
116
|
+
for (const [id, room] of rooms) if (room.expires <= Date.now()) expireRoom(id, room);
|
|
89
117
|
for (const [ws, state] of clients) { if (!state.alive) ws.terminate(); else { state.alive = false; ws.ping(); } }
|
|
90
118
|
}, 10000);
|
|
91
119
|
sweep.unref();
|
package/src/schema.ts
CHANGED
|
@@ -50,7 +50,8 @@ export type WireMessage =
|
|
|
50
50
|
| { type: 'resource.result'; requestId: string; value?: unknown; error?: string }
|
|
51
51
|
| { type: 'resource.request'; requestId: string; request: ResourceRequest }
|
|
52
52
|
| { type: 'resource.result'; requestId: string; value?: unknown; error?: string }
|
|
53
|
-
| { type: 'ping'
|
|
53
|
+
| { type: 'ping'; activity?: true }
|
|
54
|
+
| { type: 'pong' };
|
|
54
55
|
|
|
55
56
|
export function parseMessage(value: unknown): WireMessage {
|
|
56
57
|
const basic = z.object({ type: z.string() }).passthrough().parse(value);
|
|
@@ -59,7 +60,8 @@ export function parseMessage(value: unknown): WireMessage {
|
|
|
59
60
|
case 'task.cancel': return { type: basic.type, id: z.string().uuid().parse(basic.id) };
|
|
60
61
|
case 'resource.request': return { type: basic.type, requestId: z.string().uuid().parse(basic.requestId), request: resourceRequestSchema.parse(basic.request) };
|
|
61
62
|
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);
|
|
62
|
-
case 'ping':
|
|
63
|
+
case 'ping': return basic.activity === true ? { type: 'ping', activity: true } : { type: 'ping' };
|
|
64
|
+
case 'pong': return { type: 'pong' };
|
|
63
65
|
case 'session.accepted': return z.object({ type: z.literal('session.accepted'), label: z.string().max(120), fingerprint: z.string().max(100), credential: z.string().regex(/^D1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}$/).optional() }).strict().parse(value);
|
|
64
66
|
case 'session.closed': return z.object({ type: z.literal('session.closed'), reason: z.string().max(200) }).strict().parse(value);
|
|
65
67
|
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);
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import * as opaque from '@serenity-kit/opaque';
|
|
2
|
+
import { hkdfSync } from 'node:crypto';
|
|
3
|
+
|
|
4
|
+
// Registration runs entirely on the probe. The relay sees neither the password,
|
|
5
|
+
// registration record nor OPAQUE server setup. Both login roles are endpoints.
|
|
6
|
+
await opaque.ready;
|
|
7
|
+
const identifiers = (room: string) => ({ client: `diagnose/v2/operator/${room}`, server: `diagnose/v2/probe/${room}` });
|
|
8
|
+
const key = (sessionKey: string, room: string) => Buffer.from(hkdfSync('sha256', Buffer.from(sessionKey, 'base64url'), 'diagnose/opaque/v2', `noise-psk/${room}`, 32));
|
|
9
|
+
export function pakeMessage(stage: string, value: string): Buffer { return Buffer.from(JSON.stringify({ pake: stage, value })); }
|
|
10
|
+
export function pakeValue(bytes: Buffer, expected: string): string {
|
|
11
|
+
if (bytes.length > 4096) throw new Error('Oversized PAKE message');
|
|
12
|
+
const value = JSON.parse(bytes.toString());
|
|
13
|
+
if (value?.pake !== expected || typeof value.value !== 'string' || !/^[A-Za-z0-9_+/=-]{1,2048}$/.test(value.value) || Object.keys(value).length !== 2) throw new Error('Invalid PAKE message');
|
|
14
|
+
return value.value;
|
|
15
|
+
}
|
|
16
|
+
export class InvitationHost {
|
|
17
|
+
private setup: string;
|
|
18
|
+
private record: string;
|
|
19
|
+
private state?: string;
|
|
20
|
+
constructor(private room: string, password: Buffer) {
|
|
21
|
+
this.setup = opaque.server.createSetup();
|
|
22
|
+
const registration = opaque.client.startRegistration({ password: password.toString() });
|
|
23
|
+
const response = opaque.server.createRegistrationResponse({ serverSetup: this.setup, userIdentifier: room, registrationRequest: registration.registrationRequest });
|
|
24
|
+
this.record = opaque.client.finishRegistration({ clientRegistrationState: registration.clientRegistrationState, registrationResponse: response.registrationResponse, password: password.toString(), identifiers: identifiers(room), keyStretching: 'memory-constrained' }).registrationRecord;
|
|
25
|
+
}
|
|
26
|
+
start(bytes: Buffer): Buffer {
|
|
27
|
+
if (this.state) throw new Error('PAKE already started');
|
|
28
|
+
const response = opaque.server.startLogin({ serverSetup: this.setup, registrationRecord: this.record, userIdentifier: this.room, startLoginRequest: pakeValue(bytes, 'start'), identifiers: identifiers(this.room) });
|
|
29
|
+
this.state = response.serverLoginState;
|
|
30
|
+
return pakeMessage('response', response.loginResponse);
|
|
31
|
+
}
|
|
32
|
+
finish(bytes: Buffer): Buffer {
|
|
33
|
+
if (!this.state) throw new Error('PAKE not started');
|
|
34
|
+
const state = this.state; this.state = undefined;
|
|
35
|
+
const response = opaque.server.finishLogin({ serverLoginState: state, finishLoginRequest: pakeValue(bytes, 'finish'), identifiers: identifiers(this.room) });
|
|
36
|
+
return key(response.sessionKey, this.room);
|
|
37
|
+
}
|
|
38
|
+
reset(): void { this.state = undefined; }
|
|
39
|
+
destroy(): void { this.reset(); this.setup = ''; this.record = ''; }
|
|
40
|
+
}
|
|
41
|
+
export class InvitationJoin {
|
|
42
|
+
private state?: string;
|
|
43
|
+
constructor(private room: string, private password: Buffer) {}
|
|
44
|
+
start(): Buffer {
|
|
45
|
+
if (this.state) throw new Error('PAKE already started');
|
|
46
|
+
const response = opaque.client.startLogin({ password: this.password.toString() }); this.state = response.clientLoginState;
|
|
47
|
+
return pakeMessage('start', response.startLoginRequest);
|
|
48
|
+
}
|
|
49
|
+
finish(bytes: Buffer): { reply: Buffer; secret: Buffer } {
|
|
50
|
+
if (!this.state) throw new Error('PAKE not started');
|
|
51
|
+
const state = this.state; this.state = undefined;
|
|
52
|
+
const response = opaque.client.finishLogin({ clientLoginState: state, password: this.password.toString(), loginResponse: pakeValue(bytes, 'response'), identifiers: identifiers(this.room), keyStretching: 'memory-constrained' });
|
|
53
|
+
if (!response) throw new Error('Incorrect invitation');
|
|
54
|
+
return { reply: pakeMessage('finish', response.finishLoginRequest), secret: key(response.sessionKey, this.room) };
|
|
55
|
+
}
|
|
56
|
+
destroy(): void { this.state = undefined; }
|
|
57
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { lstat, mkdir, mkdtemp, open, readdir, rename, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
6
|
+
import { loadSkill, type SessionSkill } from './skill.js';
|
|
7
|
+
|
|
8
|
+
const MAX_BYTES = 8 * 1024 * 1024;
|
|
9
|
+
const MAX_FILES = 128;
|
|
10
|
+
const namePattern = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
11
|
+
const revisionPattern = /^[a-f0-9]{64}$/;
|
|
12
|
+
type Entry = { path: string; bytes: Buffer; executable: boolean };
|
|
13
|
+
export const skillsUsage = 'diagnose skills import NAME FILE.md|DIRECTORY\ndiagnose skills list\nLaunch: diagnose agent codex|claude|gemini --skill library:NAME@REVISION';
|
|
14
|
+
|
|
15
|
+
// Portable names only: reject separators, traversal, Windows aliases and device names.
|
|
16
|
+
function validPart(part: string): boolean {
|
|
17
|
+
return /^[a-zA-Z0-9_.-]+$/.test(part) && !['.', '..'].includes(part) && !/[. ]$/.test(part) && !/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function readBundle(input: string): Promise<Entry[]> {
|
|
21
|
+
const source = resolve(input), info = await lstat(source);
|
|
22
|
+
if (info.isSymbolicLink()) throw new Error('Skill bundles cannot contain symbolic links');
|
|
23
|
+
const entries: Entry[] = []; let total = 0, visited = 0;
|
|
24
|
+
const add = async (file: string, path: string) => {
|
|
25
|
+
if (entries.length >= MAX_FILES) throw new Error('Skill bundle exceeds 128 files');
|
|
26
|
+
const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
27
|
+
try {
|
|
28
|
+
const metadata = await handle.stat();
|
|
29
|
+
if (!metadata.isFile()) throw new Error('Skill bundles require regular files');
|
|
30
|
+
if (metadata.size > MAX_BYTES - total) throw new Error('Skill bundle exceeds 8 MiB');
|
|
31
|
+
const buffer = Buffer.alloc(MAX_BYTES - total + 1); let size = 0;
|
|
32
|
+
while (size < buffer.length) { const { bytesRead } = await handle.read(buffer, size, buffer.length - size, size); if (!bytesRead) break; size += bytesRead; }
|
|
33
|
+
total += size;
|
|
34
|
+
if (total > MAX_BYTES) throw new Error('Skill bundle exceeds 8 MiB');
|
|
35
|
+
entries.push({ path, bytes: Buffer.from(buffer.subarray(0, size)), executable: !!(metadata.mode & 0o111) });
|
|
36
|
+
} finally { await handle.close(); }
|
|
37
|
+
};
|
|
38
|
+
const walk = async (directory: string, prefix: string, depth: number): Promise<void> => {
|
|
39
|
+
if (depth > 16) throw new Error('Skill directory nesting exceeds 16 levels');
|
|
40
|
+
const names = await readdir(directory); const portable = new Set<string>();
|
|
41
|
+
for (const name of names.sort()) {
|
|
42
|
+
if (++visited > 256) throw new Error('Skill bundle exceeds 256 directory entries');
|
|
43
|
+
if (!validPart(name) || portable.has(name.toLowerCase())) throw new Error('Skill bundle contains a non-portable or duplicate path');
|
|
44
|
+
portable.add(name.toLowerCase());
|
|
45
|
+
const file = join(directory, name), path = prefix + name, item = await lstat(file);
|
|
46
|
+
if (item.isSymbolicLink()) throw new Error('Skill bundles cannot contain symbolic links');
|
|
47
|
+
if (item.isDirectory()) await walk(file, path + '/', depth + 1);
|
|
48
|
+
else if (item.isFile()) await add(file, path);
|
|
49
|
+
else throw new Error('Skill bundles require regular files');
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
if (info.isDirectory()) await walk(source, '', 0);
|
|
53
|
+
else { await loadSkill(source); await add(source, 'SKILL.md'); }
|
|
54
|
+
if (!entries.some(entry => entry.path === 'SKILL.md')) throw new Error('Skill directory requires SKILL.md');
|
|
55
|
+
await loadSkill(info.isDirectory() ? join(source, 'SKILL.md') : source);
|
|
56
|
+
return entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function digest(entries: Entry[]): string {
|
|
60
|
+
// Length-delimited canonical JSON avoids ambiguous path/content concatenation.
|
|
61
|
+
return createHash('sha256').update(JSON.stringify(entries.map(entry => [entry.path, entry.bytes.toString('base64')]))).digest('hex');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export class SkillLibrary {
|
|
65
|
+
constructor(readonly root = join(homedir(), '.diagnose', 'skills')) {}
|
|
66
|
+
|
|
67
|
+
async bundle(reference: string): Promise<{ reference: string; files: { path: string; data: string }[] }> {
|
|
68
|
+
const skill = await this.load(reference);
|
|
69
|
+
return { reference, files: (await readBundle(skill.baseDirectory)).map(entry => ({ path: entry.path, data: entry.bytes.toString('base64') })) };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async exportTo(reference: string, directory: string): Promise<void> {
|
|
73
|
+
const bundle = await this.bundle(reference);
|
|
74
|
+
await this.writeBundle(bundle.files, directory);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
private async writeBundle(files: { path: string; data: string }[], directory: string): Promise<void> {
|
|
78
|
+
if (!Array.isArray(files) || files.length > MAX_FILES) throw new Error('Invalid skill bundle');
|
|
79
|
+
let total = 0;
|
|
80
|
+
for (const entry of files) {
|
|
81
|
+
if (typeof entry.path !== 'string' || entry.path.length > 2048 || !entry.path.split('/').every(validPart) || typeof entry.data !== 'string') throw new Error('Invalid bundle path or content');
|
|
82
|
+
const bytes = Buffer.from(entry.data, 'base64'); total += bytes.length;
|
|
83
|
+
if (total > MAX_BYTES || bytes.toString('base64') !== entry.data) throw new Error('Invalid or oversized bundle content');
|
|
84
|
+
const parts = entry.path.split('/'), name = parts.pop()!;
|
|
85
|
+
const parent = join(directory, ...parts); await mkdir(parent, { recursive: true, mode: 0o700 });
|
|
86
|
+
await writeFile(join(parent, name), bytes, { flag: 'wx', mode: 0o600 });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async restore(bundle: { reference: string; files: { path: string; data: string }[] }): Promise<string> {
|
|
91
|
+
const match = /^library:([a-z0-9][a-z0-9-]{0,63})@([a-f0-9]{64})$/.exec(bundle.reference);
|
|
92
|
+
if (!match) throw new Error('Invalid bundle reference');
|
|
93
|
+
await mkdir(this.root, { recursive: true, mode: 0o700 });
|
|
94
|
+
const directory = await mkdtemp(join(this.root, '.restore-'));
|
|
95
|
+
try {
|
|
96
|
+
await this.writeBundle(bundle.files, directory);
|
|
97
|
+
if (digest(await readBundle(directory)) !== match[2]) throw new Error('Downloaded bundle failed integrity verification');
|
|
98
|
+
return await this.import(match[1], directory);
|
|
99
|
+
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async import(name: string, input: string): Promise<string> {
|
|
103
|
+
if (!namePattern.test(name) || !validPart(name)) throw new Error('Skill name must be a portable name of 1..64 lowercase letters, digits or hyphens, starting with a letter or digit');
|
|
104
|
+
const entries = await readBundle(input), revision = digest(entries), parent = join(this.root, name);
|
|
105
|
+
await mkdir(parent, { recursive: true, mode: 0o700 });
|
|
106
|
+
const reference = `library:${name}@${revision}`, destination = join(parent, revision);
|
|
107
|
+
try { await lstat(destination); await this.load(reference); return reference; }
|
|
108
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
|
|
109
|
+
const temporary = await mkdtemp(join(parent, '.import-'));
|
|
110
|
+
try {
|
|
111
|
+
for (const entry of entries) {
|
|
112
|
+
const parts = entry.path.split('/'); const filename = parts.pop()!;
|
|
113
|
+
const directory = join(temporary, ...parts);
|
|
114
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
115
|
+
await writeFile(join(directory, filename), entry.bytes, { flag: 'wx', mode: entry.executable ? 0o700 : 0o600 });
|
|
116
|
+
}
|
|
117
|
+
if (digest(await readBundle(temporary)) !== revision) throw new Error('Skill changed during import');
|
|
118
|
+
try { await rename(temporary, destination); }
|
|
119
|
+
catch (error) {
|
|
120
|
+
// Windows reports EPERM when another import already published this
|
|
121
|
+
// nonempty directory. Accept only a fully verified existing revision,
|
|
122
|
+
// never an error code alone (which could also mean real permission loss).
|
|
123
|
+
try { await this.load(reference); } catch { throw error; }
|
|
124
|
+
}
|
|
125
|
+
await this.load(reference);
|
|
126
|
+
return reference;
|
|
127
|
+
} finally { await rm(temporary, { recursive: true, force: true }); }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async load(reference: string): Promise<SessionSkill> {
|
|
131
|
+
const match = /^library:([^@]+)@([^@]+)$/.exec(reference);
|
|
132
|
+
if (!match || !namePattern.test(match[1]) || !validPart(match[1]) || !revisionPattern.test(match[2])) throw new Error('Use library:NAME@FULL_SHA256_REVISION from diagnose skills list');
|
|
133
|
+
const directory = join(this.root, match[1], match[2]);
|
|
134
|
+
if (digest(await readBundle(directory)) !== match[2]) throw new Error('Stored skill failed integrity verification; import a clean copy');
|
|
135
|
+
return { ...await loadSkill(directory), libraryReference: reference };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async list(): Promise<string[]> {
|
|
139
|
+
let names: string[];
|
|
140
|
+
try { names = await readdir(this.root); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; }
|
|
141
|
+
const references: string[] = [];
|
|
142
|
+
for (const name of names.sort()) {
|
|
143
|
+
if (!namePattern.test(name) || !(await lstat(join(this.root, name))).isDirectory()) continue;
|
|
144
|
+
for (const revision of (await readdir(join(this.root, name))).sort()) {
|
|
145
|
+
if (revisionPattern.test(revision)) references.push(`library:${name}@${revision}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return references;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export async function resolveSkill(input: string): Promise<SessionSkill> {
|
|
153
|
+
return input.startsWith('library:') ? new SkillLibrary().load(input) : loadSkill(input);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export async function skillsCommand(args: string[]): Promise<void> {
|
|
157
|
+
const library = new SkillLibrary();
|
|
158
|
+
if (args[0] === 'import' && args.length === 3) { console.log(await library.import(args[1], args[2])); return; }
|
|
159
|
+
if (args[0] === 'list' && args.length === 1) { console.log(JSON.stringify(await library.list(), null, 2)); return; }
|
|
160
|
+
if (args.length && !['--help', 'help'].includes(args[0])) throw new Error(skillsUsage);
|
|
161
|
+
console.log(skillsUsage);
|
|
162
|
+
}
|