@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.
Files changed (94) hide show
  1. package/DEVELOPMENT_PLAN.md +69 -0
  2. package/KNOWLEDGE_SECURITY.md +47 -0
  3. package/PAIRING_PROTOCOL.md +37 -0
  4. package/README.md +28 -6
  5. package/USER_GUIDE.md +250 -34
  6. package/deploy/Caddyfile +1 -1
  7. package/deploy/ecosystem.config.cjs +1 -1
  8. package/dist/agent.d.ts +1 -1
  9. package/dist/agent.js +15 -5
  10. package/dist/cases.d.ts +118 -0
  11. package/dist/cases.js +115 -0
  12. package/dist/cli.js +61 -13
  13. package/dist/crypto.d.ts +7 -0
  14. package/dist/crypto.js +16 -1
  15. package/dist/discover.js +1 -1
  16. package/dist/engine.d.ts +1 -0
  17. package/dist/engine.js +21 -7
  18. package/dist/install-skill.d.ts +2 -0
  19. package/dist/install-skill.js +57 -0
  20. package/dist/knowledge-cli.d.ts +2 -0
  21. package/dist/knowledge-cli.js +164 -0
  22. package/dist/knowledge-drafts.d.ts +47 -0
  23. package/dist/knowledge-drafts.js +76 -0
  24. package/dist/knowledge-mcp.d.ts +5 -0
  25. package/dist/knowledge-mcp.js +65 -0
  26. package/dist/mcp.d.ts +1 -1
  27. package/dist/mcp.js +38 -9
  28. package/dist/operator.d.ts +2 -0
  29. package/dist/operator.js +18 -3
  30. package/dist/peer.d.ts +9 -0
  31. package/dist/peer.js +90 -10
  32. package/dist/relay-main.js +1 -1
  33. package/dist/relay.d.ts +1 -0
  34. package/dist/relay.js +46 -10
  35. package/dist/schema.d.ts +4 -1
  36. package/dist/schema.js +2 -2
  37. package/dist/session-limits.d.ts +3 -0
  38. package/dist/session-limits.js +3 -0
  39. package/dist/short-pairing.d.ts +25 -0
  40. package/dist/short-pairing.js +73 -0
  41. package/dist/skill-library.d.ts +27 -0
  42. package/dist/skill-library.js +226 -0
  43. package/dist/skill-session.d.ts +1 -0
  44. package/dist/skill-session.js +257 -0
  45. package/dist/skill.d.ts +1 -0
  46. package/dist/skill.js +1 -0
  47. package/dist/util.js +1 -0
  48. package/dist/vault-crypto.d.ts +11 -0
  49. package/dist/vault-crypto.js +30 -0
  50. package/dist/vault-server.d.ts +10 -0
  51. package/dist/vault-server.js +156 -0
  52. package/dist/vault.d.ts +19 -0
  53. package/dist/vault.js +72 -0
  54. package/npm-shrinkwrap.json +12 -2
  55. package/package.json +7 -2
  56. package/skills/connect/SKILL.md +60 -0
  57. package/skills/connect/scripts/run.mjs +37 -0
  58. package/src/agent.ts +12 -5
  59. package/src/cases.ts +74 -0
  60. package/src/cli.ts +51 -13
  61. package/src/crypto.ts +14 -1
  62. package/src/discover.ts +1 -1
  63. package/src/engine.ts +17 -4
  64. package/src/install-skill.ts +57 -0
  65. package/src/knowledge-cli.ts +67 -0
  66. package/src/knowledge-drafts.ts +55 -0
  67. package/src/knowledge-mcp.ts +35 -0
  68. package/src/mcp.ts +21 -7
  69. package/src/operator.ts +12 -3
  70. package/src/peer.ts +51 -14
  71. package/src/relay-main.ts +1 -1
  72. package/src/relay.ts +35 -7
  73. package/src/schema.ts +4 -2
  74. package/src/session-limits.ts +3 -0
  75. package/src/short-pairing.ts +57 -0
  76. package/src/skill-library.ts +162 -0
  77. package/src/skill-session.ts +233 -0
  78. package/src/skill.ts +2 -1
  79. package/src/util.ts +1 -0
  80. package/src/vault-crypto.ts +25 -0
  81. package/src/vault-server.ts +72 -0
  82. package/src/vault.ts +51 -0
  83. package/test/agent.test.ts +26 -1
  84. package/test/cli.test.ts +58 -10
  85. package/test/install-skill.test.ts +37 -0
  86. package/test/knowledge-mcp.test.ts +37 -0
  87. package/test/knowledge.test.ts +112 -0
  88. package/test/mcp.test.ts +1 -1
  89. package/test/pairing.test.ts +8 -3
  90. package/test/review.test.ts +17 -0
  91. package/test/short-pairing.test.ts +142 -0
  92. package/test/skill-library.test.ts +62 -0
  93. package/test/skill-session.test.ts +79 -0
  94. package/test/skill.test.ts +1 -1
package/dist/peer.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { EventEmitter } from 'node:events';
2
2
  import { WebSocket } from 'ws';
3
- import { Handshake, parseCode } from './crypto.js';
3
+ import { Handshake, parseCode, parseInvitation, INVITATION_MS } from './crypto.js';
4
4
  import { CHUNK_SIZE, MAX_FRAME, parseMessage } 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
  function deferred() { let resolve; let reject; const promise = new Promise((a, b) => { resolve = a; reject = b; }); promise.catch(() => { }); return { promise, resolve, reject }; }
7
9
  export function relayUrl(value) {
8
10
  const url = new URL(value);
@@ -41,19 +43,35 @@ export class Peer extends EventEmitter {
41
43
  heartbeat;
42
44
  connectionTimer;
43
45
  handshakeTimer;
46
+ short;
47
+ invitationHost;
48
+ invitationJoin;
49
+ pakeStage;
50
+ invitationTimer;
51
+ attempts = 0;
52
+ joined = false;
44
53
  fingerprint = '';
45
54
  rememberedCode;
46
55
  constructor(options) {
47
56
  super();
48
57
  this.options = options;
49
- const { room, secret } = parseCode(options.code);
58
+ const { room, secret, short } = parseInvitation(options.code);
50
59
  this.room = room;
51
60
  this.secret = secret;
61
+ this.short = short;
62
+ if (short && options.role === 'host')
63
+ this.invitationHost = new InvitationHost(room, secret);
52
64
  this.ws = new WebSocket(relayUrl(options.relay), { maxPayload: MAX_FRAME, perMessageDeflate: false, handshakeTimeout: 10000 });
53
65
  this.connectionTimer = setTimeout(() => this.close('Relay registration timeout'), 12000);
54
- this.ws.on('open', () => this.ws.send(JSON.stringify({ version: 1, role: options.role, room })));
66
+ if (short && options.role === 'host')
67
+ this.invitationTimer = setTimeout(() => this.close('Invitation expired; generate a new code'), Math.min(options.invitationMs ?? INVITATION_MS, INVITATION_MS));
68
+ this.ws.on('open', () => this.ws.send(JSON.stringify({ version: short ? 2 : 1, role: options.role, room })));
55
69
  this.ws.on('error', () => this.close('Relay connection failed'));
56
- this.ws.on('close', () => this.close('Relay disconnected'));
70
+ this.ws.on('close', (_code, reason) => {
71
+ const message = reason.toString();
72
+ this.close(message === 'Invitation locator occupied' ? 'Invitation locator occupied; generating a new code'
73
+ : message === 'Session expired' ? 'Relay session expired' : 'Relay disconnected');
74
+ });
57
75
  this.ws.on('message', (bytes, binary) => {
58
76
  try {
59
77
  if (binary)
@@ -80,28 +98,70 @@ export class Peer extends EventEmitter {
80
98
  case 'joined':
81
99
  clearTimeout(this.connectionTimer);
82
100
  this.registered.resolve();
83
- this.handshake = new Handshake(true, this.room, this.secret);
84
- 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 } : {}) }))));
101
+ if (this.options.role !== 'join' || this.joined)
102
+ throw new Error('Unexpected join');
103
+ this.joined = true;
104
+ if (this.short) {
105
+ this.invitationJoin = new InvitationJoin(this.room, this.secret);
106
+ this.pakeStage = 'response';
107
+ this.ws.send(this.invitationJoin.start());
108
+ }
109
+ else
110
+ this.startNoise(this.secret);
85
111
  this.handshakeTimer = setTimeout(() => this.close('Pairing or user approval timeout'), this.options.approvalTimeoutMs ?? 120000);
86
112
  break;
87
113
  case 'peer':
88
114
  if (this.options.role !== 'host' || this.approved)
89
115
  throw new Error('Unexpected peer');
90
- this.handshake?.destroy();
91
- this.handshake = new Handshake(false, this.room, this.secret);
92
- clearTimeout(this.handshakeTimer);
116
+ if (this.short && ++this.attempts > 5) {
117
+ this.close('Invitation attempt limit reached');
118
+ return;
119
+ }
120
+ this.resetAttempt();
121
+ if (this.short)
122
+ this.pakeStage = 'start';
123
+ else
124
+ this.handshake = new Handshake(false, this.room, this.secret);
93
125
  this.handshakeTimer = setTimeout(() => this.rejectAttempt(), 15000);
94
126
  break;
95
127
  case 'peer-left':
96
128
  if (this.approved)
97
129
  this.close('Operator disconnected');
130
+ else if (this.short && this.attempts >= 5)
131
+ this.close('Invitation attempt limit reached');
98
132
  else
99
133
  this.resetAttempt();
100
134
  break;
101
135
  default: throw new Error('Unexpected relay control');
102
136
  }
103
137
  }
138
+ startNoise(secret) {
139
+ this.handshake = new Handshake(true, this.room, secret);
140
+ 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 } : {}) }))));
141
+ }
104
142
  receive(bytes) {
143
+ if (this.pakeStage) {
144
+ if (this.pakeStage === 'start') {
145
+ this.ws.send(this.invitationHost.start(bytes));
146
+ this.pakeStage = 'finish';
147
+ }
148
+ else if (this.pakeStage === 'finish') {
149
+ const secret = this.invitationHost.finish(bytes);
150
+ this.handshake = new Handshake(false, this.room, secret);
151
+ secret.fill(0);
152
+ this.pakeStage = undefined;
153
+ }
154
+ else {
155
+ const result = this.invitationJoin.finish(bytes);
156
+ this.ws.send(result.reply);
157
+ this.pakeStage = undefined;
158
+ this.startNoise(result.secret);
159
+ result.secret.fill(0);
160
+ this.invitationJoin.destroy();
161
+ this.invitationJoin = undefined;
162
+ }
163
+ return;
164
+ }
105
165
  if (!this.cipher) {
106
166
  if (!this.handshake || bytes.length > 4096)
107
167
  throw new Error('Invalid handshake');
@@ -129,7 +189,9 @@ export class Peer extends EventEmitter {
129
189
  this.close('User declined pairing');
130
190
  return;
131
191
  }
132
- this.ws.send(JSON.stringify({ type: 'lock', ...(this.options.sessionMs === undefined ? {} : { ttlMs: this.options.sessionMs || 7 * 86400000 }) }));
192
+ this.ws.send(JSON.stringify(this.options.sessionMs
193
+ ? { type: 'lock', ttlMs: this.options.sessionMs }
194
+ : { type: 'lock', sliding: true, ttlMs: LEGACY_RELAY_MAX_MS }));
133
195
  this.approved = true;
134
196
  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() } : {}) });
135
197
  this.activate();
@@ -176,6 +238,8 @@ export class Peer extends EventEmitter {
176
238
  if (!this.approved)
177
239
  throw new Error('Not authorized');
178
240
  if (message.type === 'ping') {
241
+ if (message.activity && this.options.role === 'host')
242
+ this.emit('activity');
179
243
  void this.send({ type: 'pong' }).catch(() => this.close('Heartbeat failed'));
180
244
  return;
181
245
  }
@@ -184,6 +248,9 @@ export class Peer extends EventEmitter {
184
248
  this.emit('message', message);
185
249
  }
186
250
  activate() {
251
+ clearTimeout(this.invitationTimer);
252
+ this.invitationHost?.destroy();
253
+ this.invitationHost = undefined;
187
254
  this.secret.fill(0);
188
255
  this.lastSeen = Date.now();
189
256
  this.accepted.resolve();
@@ -214,6 +281,8 @@ export class Peer extends EventEmitter {
214
281
  // Bound sustained traffic below the relay's shared per-room frame budget.
215
282
  await new Promise(resolve => setTimeout(resolve, 10));
216
283
  }
284
+ if (message.type.startsWith('task.') || message.type.startsWith('resource.'))
285
+ this.emit('activity');
217
286
  }).finally(() => { this.queuedBytes -= payload.length; });
218
287
  this.queue = operation.catch(() => this.close('Encrypted transport failed'));
219
288
  return operation;
@@ -228,6 +297,10 @@ export class Peer extends EventEmitter {
228
297
  this.generation++;
229
298
  this.approval?.abort();
230
299
  clearTimeout(this.handshakeTimer);
300
+ this.pakeStage = undefined;
301
+ this.invitationHost?.reset();
302
+ this.invitationJoin?.destroy();
303
+ this.invitationJoin = undefined;
231
304
  this.handshake?.destroy();
232
305
  this.handshake = undefined;
233
306
  this.cipher?.destroy();
@@ -236,6 +309,10 @@ export class Peer extends EventEmitter {
236
309
  this.partialSize = 0;
237
310
  }
238
311
  rejectAttempt() {
312
+ if (this.short && this.attempts >= 5) {
313
+ this.close('Invitation attempt limit reached');
314
+ return;
315
+ }
239
316
  this.resetAttempt();
240
317
  if (this.ws.readyState === WebSocket.OPEN)
241
318
  this.ws.send(JSON.stringify({ type: 'reject' }));
@@ -244,6 +321,9 @@ export class Peer extends EventEmitter {
244
321
  if (this.destroyed)
245
322
  return;
246
323
  this.destroyed = true;
324
+ clearTimeout(this.invitationTimer);
325
+ this.invitationHost?.destroy();
326
+ this.invitationHost = undefined;
247
327
  clearTimeout(this.connectionTimer);
248
328
  clearInterval(this.heartbeat);
249
329
  this.resetAttempt();
@@ -1,6 +1,6 @@
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'])
6
6
  process.once(signal, () => { void relay.close(); });
package/dist/relay.d.ts CHANGED
@@ -6,6 +6,7 @@ export type RelayOptions = {
6
6
  sessionMs?: number;
7
7
  maxRooms?: number;
8
8
  downloadPath?: string;
9
+ vaultPath?: string;
9
10
  observeCiphertext?: (bytes: Buffer) => void;
10
11
  };
11
12
  export declare function createRelay(options?: RelayOptions): {
package/dist/relay.js CHANGED
@@ -2,15 +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
  const control = (ws, type, extra = {}) => { if (ws.readyState === WebSocket.OPEN)
6
9
  ws.send(JSON.stringify({ type, ...extra })); };
7
10
  export function createRelay(options = {}) {
11
+ const vault = options.vaultPath ? new VaultServer(options.vaultPath) : undefined;
8
12
  const rooms = new Map();
13
+ const expireRoom = (id, room) => {
14
+ rooms.delete(id);
15
+ room.host.close(1000, 'Session expired');
16
+ room.peer?.close(1000, 'Session expired');
17
+ };
9
18
  const clients = new Map();
10
19
  const connectionsByIp = new Map();
20
+ const connectionRates = new Map();
11
21
  const server = http.createServer((req, res) => {
12
22
  res.setHeader('Cache-Control', 'no-store');
13
23
  res.setHeader('X-Content-Type-Options', 'nosniff');
24
+ if (req.url?.startsWith('/v1/library') && vault) {
25
+ void vault.handle(req, res);
26
+ return;
27
+ }
14
28
  if (req.method === 'GET' && req.url === '/healthz') {
15
29
  res.setHeader('Content-Type', 'application/json');
16
30
  res.end('{"ok":true,"protocol":1}');
@@ -44,6 +58,16 @@ export function createRelay(options = {}) {
44
58
  wss.on('connection', (ws, req) => {
45
59
  const direct = req.socket.remoteAddress ?? 'unknown';
46
60
  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;
61
+ const now = Date.now();
62
+ for (const [key, rate] of connectionRates)
63
+ if (now - rate.since > 60000)
64
+ connectionRates.delete(key);
65
+ const rate = connectionRates.get(ip) ?? { since: now, count: 0 };
66
+ if ((!connectionRates.has(ip) && connectionRates.size >= 10000) || ++rate.count > 60) {
67
+ ws.close(1008, 'Connection rate limit');
68
+ return;
69
+ }
70
+ connectionRates.set(ip, rate);
47
71
  if ((connectionsByIp.get(ip) ?? 0) >= 30) {
48
72
  ws.close(1008, 'Connection limit');
49
73
  return;
@@ -62,19 +86,24 @@ export function createRelay(options = {}) {
62
86
  if (binary || bytes.length > 256)
63
87
  throw new Error();
64
88
  const msg = JSON.parse(bytes.toString());
65
- if (msg.version !== 1 || !/^[A-Za-z0-9_-]{16}$/.test(msg.room) || !['host', 'join'].includes(msg.role))
89
+ const short = msg.version === 2 && /^S2\.[a-z]{2}$/.test(msg.room);
90
+ if (!(short || (msg.version === 1 && /^[A-Za-z0-9_-]{16}$/.test(msg.room))) || !['host', 'join'].includes(msg.role))
66
91
  throw new Error();
67
92
  if (msg.role === 'host') {
93
+ if (short && rooms.has(msg.room)) {
94
+ ws.close(1008, 'Invitation locator occupied');
95
+ return;
96
+ }
68
97
  if (rooms.has(msg.room) || rooms.size >= (options.maxRooms ?? 100))
69
98
  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() });
99
+ 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() });
71
100
  state.role = 'host';
72
101
  state.room = msg.room;
73
102
  control(ws, 'registered');
74
103
  }
75
104
  else {
76
105
  const room = rooms.get(msg.room);
77
- if (!room || room.locked || room.peer || room.attempts >= 10 || room.expires < Date.now())
106
+ if (!room || room.locked || room.peer || room.attempts >= (room.short ? 5 : 10) || room.expires < Date.now())
78
107
  throw new Error();
79
108
  state.role = 'join';
80
109
  state.room = msg.room;
@@ -89,6 +118,10 @@ export function createRelay(options = {}) {
89
118
  const room = rooms.get(state.room);
90
119
  if (!room)
91
120
  throw new Error();
121
+ if (room.expires <= Date.now()) {
122
+ expireRoom(state.room, room);
123
+ return;
124
+ }
92
125
  if (binary) {
93
126
  if (Date.now() - room.window > 1000) {
94
127
  room.window = Date.now();
@@ -104,6 +137,10 @@ export function createRelay(options = {}) {
104
137
  buffered += client.bufferedAmount;
105
138
  if (buffered > 64 * 1024 * 1024)
106
139
  throw new Error();
140
+ // The relay can see ciphertext traffic, not diagnostic activity. The
141
+ // probe enforces the real idle timeout without counting heartbeats.
142
+ if (room.renewMs)
143
+ room.expires = Date.now() + room.renewMs;
107
144
  options.observeCiphertext?.(bytes);
108
145
  target.send(bytes, { binary: true });
109
146
  return;
@@ -113,10 +150,12 @@ export function createRelay(options = {}) {
113
150
  const msg = JSON.parse(bytes.toString());
114
151
  if (msg.type === 'lock' && !room.locked) {
115
152
  const requested = msg.ttlMs;
116
- if (requested !== undefined && (!Number.isInteger(requested) || requested < 60000 || requested > 7 * 86400000))
153
+ if (requested !== undefined && (!Number.isInteger(requested) || requested < 60000 || requested > LEGACY_RELAY_MAX_MS))
117
154
  throw new Error();
118
155
  room.locked = true;
119
- room.expires = Date.now() + (requested ?? options.sessionMs ?? 3600000);
156
+ if (msg.sliding === true)
157
+ room.renewMs = options.sessionMs ?? DEFAULT_IDLE_MS;
158
+ room.expires = Date.now() + (room.renewMs ?? requested ?? options.sessionMs ?? DEFAULT_IDLE_MS);
120
159
  }
121
160
  else if (msg.type === 'reject' && !room.locked) {
122
161
  const peer = room.peer;
@@ -155,11 +194,8 @@ export function createRelay(options = {}) {
155
194
  });
156
195
  const sweep = setInterval(() => {
157
196
  for (const [id, room] of rooms)
158
- if (room.expires < Date.now()) {
159
- rooms.delete(id);
160
- room.host.close(1000, 'Session expired');
161
- room.peer?.close(1000, 'Session expired');
162
- }
197
+ if (room.expires <= Date.now())
198
+ expireRoom(id, room);
163
199
  for (const [ws, state] of clients) {
164
200
  if (!state.alive)
165
201
  ws.terminate();
package/dist/schema.d.ts CHANGED
@@ -773,6 +773,9 @@ export type WireMessage = {
773
773
  value?: unknown;
774
774
  error?: string;
775
775
  } | {
776
- type: 'ping' | 'pong';
776
+ type: 'ping';
777
+ activity?: true;
778
+ } | {
779
+ type: 'pong';
777
780
  };
778
781
  export declare function parseMessage(value: unknown): WireMessage;
package/dist/schema.js CHANGED
@@ -35,8 +35,8 @@ export function parseMessage(value) {
35
35
  case 'task.cancel': return { type: basic.type, id: z.string().uuid().parse(basic.id) };
36
36
  case 'resource.request': return { type: basic.type, requestId: z.string().uuid().parse(basic.requestId), request: resourceRequestSchema.parse(basic.request) };
37
37
  case 'resource.result': return z.object({ type: z.literal('resource.result'), requestId: z.string().uuid(), value: z.unknown().optional(), error: z.string().max(2000).optional() }).strict().parse(value);
38
- case 'ping':
39
- case 'pong': return { type: basic.type };
38
+ case 'ping': return basic.activity === true ? { type: 'ping', activity: true } : { type: 'ping' };
39
+ case 'pong': return { type: 'pong' };
40
40
  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);
41
41
  case 'session.closed': return z.object({ type: z.literal('session.closed'), reason: z.string().max(200) }).strict().parse(value);
42
42
  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,3 @@
1
+ /** Default inactivity window after a temporary diagnostic connection is approved. */
2
+ export declare const DEFAULT_IDLE_MS: number;
3
+ export declare const LEGACY_RELAY_MAX_MS: number;
@@ -0,0 +1,3 @@
1
+ /** Default inactivity window after a temporary diagnostic connection is approved. */
2
+ export const DEFAULT_IDLE_MS = 6 * 60 * 60_000;
3
+ export const LEGACY_RELAY_MAX_MS = 7 * 24 * 60 * 60_000;
@@ -0,0 +1,25 @@
1
+ export declare function pakeMessage(stage: string, value: string): Buffer;
2
+ export declare function pakeValue(bytes: Buffer, expected: string): string;
3
+ export declare class InvitationHost {
4
+ private room;
5
+ private setup;
6
+ private record;
7
+ private state?;
8
+ constructor(room: string, password: Buffer);
9
+ start(bytes: Buffer): Buffer;
10
+ finish(bytes: Buffer): Buffer;
11
+ reset(): void;
12
+ destroy(): void;
13
+ }
14
+ export declare class InvitationJoin {
15
+ private room;
16
+ private password;
17
+ private state?;
18
+ constructor(room: string, password: Buffer);
19
+ start(): Buffer;
20
+ finish(bytes: Buffer): {
21
+ reply: Buffer;
22
+ secret: Buffer;
23
+ };
24
+ destroy(): void;
25
+ }
@@ -0,0 +1,73 @@
1
+ import * as opaque from '@serenity-kit/opaque';
2
+ import { hkdfSync } from 'node:crypto';
3
+ // Registration runs entirely on the probe. The relay sees neither the password,
4
+ // registration record nor OPAQUE server setup. Both login roles are endpoints.
5
+ await opaque.ready;
6
+ const identifiers = (room) => ({ client: `diagnose/v2/operator/${room}`, server: `diagnose/v2/probe/${room}` });
7
+ const key = (sessionKey, room) => Buffer.from(hkdfSync('sha256', Buffer.from(sessionKey, 'base64url'), 'diagnose/opaque/v2', `noise-psk/${room}`, 32));
8
+ export function pakeMessage(stage, value) { return Buffer.from(JSON.stringify({ pake: stage, value })); }
9
+ export function pakeValue(bytes, expected) {
10
+ if (bytes.length > 4096)
11
+ 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)
14
+ throw new Error('Invalid PAKE message');
15
+ return value.value;
16
+ }
17
+ export class InvitationHost {
18
+ room;
19
+ setup;
20
+ record;
21
+ state;
22
+ constructor(room, password) {
23
+ this.room = room;
24
+ this.setup = opaque.server.createSetup();
25
+ const registration = opaque.client.startRegistration({ password: password.toString() });
26
+ const response = opaque.server.createRegistrationResponse({ serverSetup: this.setup, userIdentifier: room, registrationRequest: registration.registrationRequest });
27
+ this.record = opaque.client.finishRegistration({ clientRegistrationState: registration.clientRegistrationState, registrationResponse: response.registrationResponse, password: password.toString(), identifiers: identifiers(room), keyStretching: 'memory-constrained' }).registrationRecord;
28
+ }
29
+ start(bytes) {
30
+ if (this.state)
31
+ throw new Error('PAKE already started');
32
+ const response = opaque.server.startLogin({ serverSetup: this.setup, registrationRecord: this.record, userIdentifier: this.room, startLoginRequest: pakeValue(bytes, 'start'), identifiers: identifiers(this.room) });
33
+ this.state = response.serverLoginState;
34
+ return pakeMessage('response', response.loginResponse);
35
+ }
36
+ finish(bytes) {
37
+ if (!this.state)
38
+ throw new Error('PAKE not started');
39
+ const state = this.state;
40
+ this.state = undefined;
41
+ const response = opaque.server.finishLogin({ serverLoginState: state, finishLoginRequest: pakeValue(bytes, 'finish'), identifiers: identifiers(this.room) });
42
+ return key(response.sessionKey, this.room);
43
+ }
44
+ reset() { this.state = undefined; }
45
+ destroy() { this.reset(); this.setup = ''; this.record = ''; }
46
+ }
47
+ export class InvitationJoin {
48
+ room;
49
+ password;
50
+ state;
51
+ constructor(room, password) {
52
+ this.room = room;
53
+ this.password = password;
54
+ }
55
+ start() {
56
+ if (this.state)
57
+ throw new Error('PAKE already started');
58
+ const response = opaque.client.startLogin({ password: this.password.toString() });
59
+ this.state = response.clientLoginState;
60
+ return pakeMessage('start', response.startLoginRequest);
61
+ }
62
+ finish(bytes) {
63
+ if (!this.state)
64
+ throw new Error('PAKE not started');
65
+ const state = this.state;
66
+ this.state = undefined;
67
+ const response = opaque.client.finishLogin({ clientLoginState: state, password: this.password.toString(), loginResponse: pakeValue(bytes, 'response'), identifiers: identifiers(this.room), keyStretching: 'memory-constrained' });
68
+ if (!response)
69
+ throw new Error('Incorrect invitation');
70
+ return { reply: pakeMessage('finish', response.finishLoginRequest), secret: key(response.sessionKey, this.room) };
71
+ }
72
+ destroy() { this.state = undefined; }
73
+ }
@@ -0,0 +1,27 @@
1
+ import { type SessionSkill } from './skill.js';
2
+ export declare const skillsUsage = "diagnose skills import NAME FILE.md|DIRECTORY\ndiagnose skills list\nLaunch: diagnose agent codex|claude|gemini --skill library:NAME@REVISION";
3
+ export declare class SkillLibrary {
4
+ readonly root: string;
5
+ constructor(root?: string);
6
+ bundle(reference: string): Promise<{
7
+ reference: string;
8
+ files: {
9
+ path: string;
10
+ data: string;
11
+ }[];
12
+ }>;
13
+ exportTo(reference: string, directory: string): Promise<void>;
14
+ private writeBundle;
15
+ restore(bundle: {
16
+ reference: string;
17
+ files: {
18
+ path: string;
19
+ data: string;
20
+ }[];
21
+ }): Promise<string>;
22
+ import(name: string, input: string): Promise<string>;
23
+ load(reference: string): Promise<SessionSkill>;
24
+ list(): Promise<string[]>;
25
+ }
26
+ export declare function resolveSkill(input: string): Promise<SessionSkill>;
27
+ export declare function skillsCommand(args: string[]): Promise<void>;