@masstensor/diagnose 0.5.0 → 0.7.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 (78) 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 +12 -4
  5. package/USER_GUIDE.md +178 -31
  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 +19 -8
  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 +12 -5
  18. package/dist/knowledge-cli.d.ts +2 -0
  19. package/dist/knowledge-cli.js +164 -0
  20. package/dist/knowledge-drafts.d.ts +47 -0
  21. package/dist/knowledge-drafts.js +76 -0
  22. package/dist/knowledge-mcp.d.ts +5 -0
  23. package/dist/knowledge-mcp.js +65 -0
  24. package/dist/mcp.d.ts +1 -1
  25. package/dist/mcp.js +27 -8
  26. package/dist/operator.d.ts +2 -0
  27. package/dist/operator.js +16 -3
  28. package/dist/peer.d.ts +9 -0
  29. package/dist/peer.js +78 -9
  30. package/dist/relay-main.js +1 -1
  31. package/dist/relay.d.ts +1 -0
  32. package/dist/relay.js +27 -4
  33. package/dist/short-pairing.d.ts +25 -0
  34. package/dist/short-pairing.js +73 -0
  35. package/dist/skill-library.d.ts +27 -0
  36. package/dist/skill-library.js +226 -0
  37. package/dist/skill.d.ts +1 -0
  38. package/dist/skill.js +1 -0
  39. package/dist/util.js +1 -0
  40. package/dist/vault-crypto.d.ts +11 -0
  41. package/dist/vault-crypto.js +30 -0
  42. package/dist/vault-server.d.ts +10 -0
  43. package/dist/vault-server.js +156 -0
  44. package/dist/vault.d.ts +19 -0
  45. package/dist/vault.js +72 -0
  46. package/npm-shrinkwrap.json +12 -2
  47. package/package.json +6 -2
  48. package/src/agent.ts +12 -5
  49. package/src/cases.ts +74 -0
  50. package/src/cli.ts +11 -7
  51. package/src/crypto.ts +14 -1
  52. package/src/discover.ts +1 -1
  53. package/src/engine.ts +9 -3
  54. package/src/knowledge-cli.ts +67 -0
  55. package/src/knowledge-drafts.ts +55 -0
  56. package/src/knowledge-mcp.ts +35 -0
  57. package/src/mcp.ts +12 -6
  58. package/src/operator.ts +10 -3
  59. package/src/peer.ts +38 -12
  60. package/src/relay-main.ts +1 -1
  61. package/src/relay.ts +18 -6
  62. package/src/short-pairing.ts +57 -0
  63. package/src/skill-library.ts +162 -0
  64. package/src/skill.ts +2 -1
  65. package/src/util.ts +1 -0
  66. package/src/vault-crypto.ts +25 -0
  67. package/src/vault-server.ts +72 -0
  68. package/src/vault.ts +51 -0
  69. package/test/agent.test.ts +26 -1
  70. package/test/cli.test.ts +3 -3
  71. package/test/knowledge-mcp.test.ts +37 -0
  72. package/test/knowledge.test.ts +112 -0
  73. package/test/mcp.test.ts +1 -1
  74. package/test/pairing.test.ts +2 -2
  75. package/test/review.test.ts +1 -0
  76. package/test/short-pairing.test.ts +100 -0
  77. package/test/skill-library.test.ts +62 -0
  78. package/test/skill.test.ts +1 -1
package/src/peer.ts CHANGED
@@ -1,10 +1,11 @@
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';
6
7
 
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 };
8
+ 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
9
  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
10
  export function relayUrl(value: string): string {
10
11
  const url = new URL(value);
@@ -38,17 +39,26 @@ export class Peer extends EventEmitter {
38
39
  private heartbeat?: NodeJS.Timeout;
39
40
  private connectionTimer: NodeJS.Timeout;
40
41
  private handshakeTimer?: NodeJS.Timeout;
42
+ private short: boolean;
43
+ private invitationHost?: InvitationHost;
44
+ private invitationJoin?: InvitationJoin;
45
+ private pakeStage?: 'start' | 'finish' | 'response';
46
+ private invitationTimer?: NodeJS.Timeout;
47
+ private attempts = 0;
48
+ private joined = false;
41
49
  fingerprint = '';
42
50
  rememberedCode?: string;
43
51
 
44
52
  constructor(private options: PeerOptions) {
45
53
  super();
46
- const { room, secret } = parseCode(options.code); this.room = room; this.secret = secret;
54
+ const { room, secret, short } = parseInvitation(options.code); this.room = room; this.secret = secret; this.short = short;
55
+ if (short && options.role === 'host') this.invitationHost = new InvitationHost(room, secret);
47
56
  this.ws = new WebSocket(relayUrl(options.relay), { maxPayload: MAX_FRAME, perMessageDeflate: false, handshakeTimeout: 10000 });
48
57
  this.connectionTimer = setTimeout(() => this.close('Relay registration timeout'), 12000);
49
- this.ws.on('open', () => this.ws.send(JSON.stringify({ version: 1, role: options.role, room })));
58
+ if (short && options.role === 'host') this.invitationTimer = setTimeout(() => this.close('Invitation expired; generate a new code'), Math.min(options.invitationMs ?? INVITATION_MS, INVITATION_MS));
59
+ this.ws.on('open', () => this.ws.send(JSON.stringify({ version: short ? 2 : 1, role: options.role, room })));
50
60
  this.ws.on('error', () => this.close('Relay connection failed'));
51
- this.ws.on('close', () => this.close('Relay disconnected'));
61
+ this.ws.on('close', (_code, reason) => this.close(reason.toString() === 'Invitation locator occupied' ? 'Invitation locator occupied; generating a new code' : 'Relay disconnected'));
52
62
  this.ws.on('message', (bytes, binary) => {
53
63
  try {
54
64
  if (binary) this.receive(Buffer.from(bytes as Buffer));
@@ -65,23 +75,37 @@ export class Peer extends EventEmitter {
65
75
  case 'registered': clearTimeout(this.connectionTimer); this.registered.resolve(); break;
66
76
  case 'joined':
67
77
  clearTimeout(this.connectionTimer); this.registered.resolve();
68
- this.handshake = new Handshake(true, this.room, this.secret);
69
- 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 } : {}) }))));
78
+ if (this.options.role !== 'join' || this.joined) throw new Error('Unexpected join');
79
+ this.joined = true;
80
+ if (this.short) { this.invitationJoin = new InvitationJoin(this.room, this.secret); this.pakeStage = 'response'; this.ws.send(this.invitationJoin.start()); }
81
+ else this.startNoise(this.secret);
70
82
  this.handshakeTimer = setTimeout(() => this.close('Pairing or user approval timeout'), this.options.approvalTimeoutMs ?? 120000);
71
83
  break;
72
84
  case 'peer':
73
85
  if (this.options.role !== 'host' || this.approved) throw new Error('Unexpected peer');
74
- this.handshake?.destroy(); this.handshake = new Handshake(false, this.room, this.secret);
75
- clearTimeout(this.handshakeTimer);
86
+ if (this.short && ++this.attempts > 5) { this.close('Invitation attempt limit reached'); return; }
87
+ this.resetAttempt();
88
+ if (this.short) this.pakeStage = 'start';
89
+ else this.handshake = new Handshake(false, this.room, this.secret);
76
90
  this.handshakeTimer = setTimeout(() => this.rejectAttempt(), 15000);
77
91
  break;
78
92
  case 'peer-left':
79
- if (this.approved) this.close('Operator disconnected'); else this.resetAttempt();
93
+ if (this.approved) this.close('Operator disconnected'); else if (this.short && this.attempts >= 5) this.close('Invitation attempt limit reached'); else this.resetAttempt();
80
94
  break;
81
95
  default: throw new Error('Unexpected relay control');
82
96
  }
83
97
  }
98
+ private startNoise(secret: Buffer): void {
99
+ this.handshake = new Handshake(true, this.room, secret);
100
+ 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
+ }
84
102
  private receive(bytes: Buffer): void {
103
+ if (this.pakeStage) {
104
+ if (this.pakeStage === 'start') { this.ws.send(this.invitationHost!.start(bytes)); this.pakeStage = 'finish'; }
105
+ 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; }
106
+ 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; }
107
+ return;
108
+ }
85
109
  if (!this.cipher) {
86
110
  if (!this.handshake || bytes.length > 4096) throw new Error('Invalid handshake');
87
111
  const hello = JSON.parse(this.handshake.receive(bytes).toString());
@@ -129,7 +153,7 @@ export class Peer extends EventEmitter {
129
153
  this.emit('message', message);
130
154
  }
131
155
  private activate(): void {
132
- this.secret.fill(0); this.lastSeen = Date.now(); this.accepted.resolve(); this.emit('active');
156
+ clearTimeout(this.invitationTimer); this.invitationHost?.destroy(); this.invitationHost = undefined; this.secret.fill(0); this.lastSeen = Date.now(); this.accepted.resolve(); this.emit('active');
133
157
  this.heartbeat = setInterval(() => {
134
158
  if (Date.now() - this.lastSeen > 25000) { this.close('Peer heartbeat timeout'); return; }
135
159
  void this.send({ type: 'ping' }).catch(() => this.close('Heartbeat failed'));
@@ -159,16 +183,18 @@ export class Peer extends EventEmitter {
159
183
  }
160
184
  private resetAttempt(): void {
161
185
  this.generation++; this.approval?.abort(); clearTimeout(this.handshakeTimer);
186
+ this.pakeStage = undefined; this.invitationHost?.reset(); this.invitationJoin?.destroy(); this.invitationJoin = undefined;
162
187
  this.handshake?.destroy(); this.handshake = undefined; this.cipher?.destroy(); this.cipher = undefined;
163
188
  this.parts = []; this.partialSize = 0;
164
189
  }
165
190
  private rejectAttempt(): void {
191
+ if (this.short && this.attempts >= 5) { this.close('Invitation attempt limit reached'); return; }
166
192
  this.resetAttempt();
167
193
  if (this.ws.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ type: 'reject' }));
168
194
  }
169
195
  close(reason = 'Session ended'): void {
170
196
  if (this.destroyed) return;
171
- this.destroyed = true; clearTimeout(this.connectionTimer); clearInterval(this.heartbeat); this.resetAttempt(); this.secret.fill(0);
197
+ 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
198
  const error = new Error(reason); this.registered.reject(error); this.accepted.reject(error); this.endedState.resolve(reason);
173
199
  this.ws.close(1000, 'Session ended'); const kill = setTimeout(() => this.ws.terminate(), 1000); kill.unref();
174
200
  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,23 @@ 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';
5
7
 
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
+ export type RelayOptions = { host?: string; port?: number; invitationMs?: number; sessionMs?: number; maxRooms?: number; downloadPath?: string; vaultPath?: string; observeCiphertext?: (bytes: Buffer) => void };
9
+ type Room = { short: boolean; host: WebSocket; peer?: WebSocket; locked: boolean; attempts: number; expires: number; frames: number; window: number };
8
10
  const control = (ws: WebSocket, type: string, extra = {}): void => { if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type, ...extra })); };
9
11
 
10
12
  export function createRelay(options: RelayOptions = {}) {
13
+ const vault = options.vaultPath ? new VaultServer(options.vaultPath) : undefined;
11
14
  const rooms = new Map<string, Room>();
12
15
  const clients = new Map<WebSocket, { role?: 'host' | 'join'; room?: string; ip: string; alive: boolean }>();
13
16
  const connectionsByIp = new Map<string, number>();
17
+ const connectionRates = new Map<string, { since: number; count: number }>();
14
18
  const server = http.createServer((req, res) => {
15
19
  res.setHeader('Cache-Control', 'no-store');
16
20
  res.setHeader('X-Content-Type-Options', 'nosniff');
21
+ if (req.url?.startsWith('/v1/library') && vault) { void vault.handle(req, res); return; }
17
22
  if (req.method === 'GET' && req.url === '/healthz') { res.setHeader('Content-Type', 'application/json'); res.end('{"ok":true,"protocol":1}'); return; }
18
23
  if (req.method === 'GET' && req.url === '/downloads/diagnose-0.1.0.tgz' && options.downloadPath) {
19
24
  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 +35,11 @@ export function createRelay(options: RelayOptions = {}) {
30
35
  wss.on('connection', (ws, req) => {
31
36
  const direct = req.socket.remoteAddress ?? 'unknown';
32
37
  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;
38
+ const now = Date.now();
39
+ for (const [key, rate] of connectionRates) if (now - rate.since > 60000) connectionRates.delete(key);
40
+ const rate = connectionRates.get(ip) ?? { since: now, count: 0 };
41
+ if ((!connectionRates.has(ip) && connectionRates.size >= 10000) || ++rate.count > 60) { ws.close(1008, 'Connection rate limit'); return; }
42
+ connectionRates.set(ip, rate);
33
43
  if ((connectionsByIp.get(ip) ?? 0) >= 30) { ws.close(1008, 'Connection limit'); return; }
34
44
  connectionsByIp.set(ip, (connectionsByIp.get(ip) ?? 0) + 1);
35
45
  const state = { ip, alive: true } as { role?: 'host' | 'join'; room?: string; ip: string; alive: boolean };
@@ -43,21 +53,23 @@ export function createRelay(options: RelayOptions = {}) {
43
53
  if (!state.role) {
44
54
  if (binary || bytes.length > 256) throw new Error();
45
55
  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();
56
+ const short = msg.version === 2 && /^S2\.[a-z]{2}$/.test(msg.room);
57
+ if (!(short || (msg.version === 1 && /^[A-Za-z0-9_-]{16}$/.test(msg.room))) || !['host', 'join'].includes(msg.role)) throw new Error();
47
58
  if (msg.role === 'host') {
59
+ if (short && rooms.has(msg.room)) { ws.close(1008, 'Invitation locator occupied'); return; }
48
60
  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() });
61
+ 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
62
  state.role = 'host'; state.room = msg.room; control(ws, 'registered');
51
63
  } else {
52
64
  const room = rooms.get(msg.room);
53
- if (!room || room.locked || room.peer || room.attempts >= 10 || room.expires < Date.now()) throw new Error();
65
+ if (!room || room.locked || room.peer || room.attempts >= (room.short ? 5 : 10) || room.expires < Date.now()) throw new Error();
54
66
  state.role = 'join'; state.room = msg.room; room.peer = ws; room.attempts++;
55
67
  control(room.host, 'peer'); control(ws, 'joined');
56
68
  }
57
69
  clearTimeout(registration); return;
58
70
  }
59
71
  const room = rooms.get(state.room!);
60
- if (!room) throw new Error();
72
+ if (!room || room.expires < Date.now()) throw new Error();
61
73
  if (binary) {
62
74
  if (Date.now() - room.window > 1000) { room.window = Date.now(); room.frames = 0; }
63
75
  if (++room.frames > 250 || bytes.length > MAX_FRAME) throw new Error();
@@ -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
+ }
package/src/skill.ts CHANGED
@@ -3,7 +3,7 @@ import { dirname, extname, join, resolve } from 'node:path';
3
3
  import { isUtf8 } from 'node:buffer';
4
4
  import { createHash } from 'node:crypto';
5
5
 
6
- export type SessionSkill = { sourceFile: string; baseDirectory: string; sha256: string; instructions: string };
6
+ export type SessionSkill = { sourceFile: string; baseDirectory: string; sha256: string; instructions: string; libraryReference?: string };
7
7
  const MAX_SKILL = 256 * 1024;
8
8
 
9
9
  export async function loadSkill(input: string): Promise<SessionSkill> {
@@ -37,6 +37,7 @@ export function skillPrompt(snapshot: string): string {
37
37
  'Resolve relative references and scripts against baseDirectory in the snapshot. It is a Markdown task or skill entry, not a globally installed agent skill. Read referenced material only as needed. Bundled scripts are task resources, not startup hooks; run them only as required by the task and existing permissions.',
38
38
  'Referenced files and scripts are initially on the diagnostician computer. For a remote script, explicitly submit its contents or transfer it with authorization; do not assume the same path exists remotely.',
39
39
  'Use diagnose_* MCP tools for actions on the remote user computer. Your ordinary shell and file tools operate on the diagnostician computer; do not confuse the two.',
40
+ 'Use diagnose_capabilities to inspect argument schemas. Use diagnose_case status/show to find an existing case. If none exists, create one for the actual external target and goal before remote tasks; if the snapshot has libraryReference, record it as the case skill. Confirm target identity and interface before repairs. Keep before/after evidence IDs and finish the case with a supported outcome. If reusable knowledge emerged, propose diagnose_skill_draft for human review; never run draft acceptance or vault upload on the diagnostician behalf.',
40
41
  'If a pairing code, target identity, or necessary detail is missing, ask the diagnostician for it, then continue. Keep pairing codes and credentials out of command arguments and reports.',
41
42
  'Pair and obtain the remote user approval before remote actions. Respect the existing user and agent permission modes; this task does not grant permissions or authorize bypassing them.',
42
43
  'Investigate, explain the proposed repair and its impact, apply only authorized changes, repeat the original failing check, and report evidence, changes, and remaining issues. Do not claim success without verification.'
package/src/util.ts CHANGED
@@ -11,6 +11,7 @@ export function safeText(text: string): string {
11
11
  export function redact(text: string): string {
12
12
  return safeText(text)
13
13
  .replace(/("?(?:password|passwd|pswd|secret|token|session|authorization|api[_-]?key)"?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,}\r\n]+)/gi, '$1[REDACTED]')
14
+ .replace(/\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/gi, '[INVITATION CODE]')
14
15
  .replace(/\bD1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}\b/g, '[PAIRING CODE]')
15
16
  .replace(/\b[a-f0-9]{32,}\b/gi, '[REDACTED]')
16
17
  .replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g, '[PRIVATE KEY]');
@@ -0,0 +1,25 @@
1
+ import { createHash, createHmac, hkdfSync, randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
2
+ export const MAX_VAULT_OBJECT = 12 * 1024 * 1024;
3
+ export function newRecovery(): string { return 'K1.' + randomBytes(32).toString('base64url'); }
4
+ export function vaultKeys(recovery: string) {
5
+ if (!/^K1\.[A-Za-z0-9_-]{43}$/.test(recovery)) throw new Error('Invalid library recovery key');
6
+ const root = Buffer.from(recovery.slice(3), 'base64url');
7
+ if (root.toString('base64url') !== recovery.slice(3)) throw new Error('Noncanonical recovery key');
8
+ const derive = (purpose: string) => Buffer.from(hkdfSync('sha256', root, 'diagnose-library-v1', purpose, 32));
9
+ const auth = derive('authentication').toString('base64url');
10
+ return { auth, namespace: createHash('sha256').update(auth).digest('hex'), encryption: derive('encryption'), index: derive('object-names') };
11
+ }
12
+ export function objectId(recovery: string, reference: string): string { return createHmac('sha256', vaultKeys(recovery).index).update(reference).digest('hex'); }
13
+ export function sealBundle(recovery: string, id: string, bytes: Buffer): Buffer {
14
+ const keys = vaultKeys(recovery), nonce = randomBytes(12), cipher = createCipheriv('aes-256-gcm', keys.encryption, nonce);
15
+ cipher.setAAD(Buffer.from(`diagnose-library-v1:${keys.namespace}:${id}`));
16
+ const sealed = Buffer.concat([Buffer.from([1]), nonce, cipher.update(bytes), cipher.final(), cipher.getAuthTag()]);
17
+ if (sealed.length > MAX_VAULT_OBJECT) throw new Error('Encrypted bundle exceeds 12 MiB');
18
+ return sealed;
19
+ }
20
+ export function openBundle(recovery: string, id: string, sealed: Buffer): Buffer {
21
+ if (sealed.length < 29 || sealed.length > MAX_VAULT_OBJECT || sealed[0] !== 1) throw new Error('Invalid encrypted library object');
22
+ const keys = vaultKeys(recovery), decipher = createDecipheriv('aes-256-gcm', keys.encryption, sealed.subarray(1, 13));
23
+ decipher.setAAD(Buffer.from(`diagnose-library-v1:${keys.namespace}:${id}`)); decipher.setAuthTag(sealed.subarray(-16));
24
+ return Buffer.concat([decipher.update(sealed.subarray(13, -16)), decipher.final()]);
25
+ }
@@ -0,0 +1,72 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { mkdirSync, readdirSync, statSync, existsSync, readFileSync, writeFileSync, renameSync, rmSync, unlinkSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { MAX_VAULT_OBJECT } from './vault-crypto.js';
6
+
7
+ // Opaque capability-authenticated immutable objects. No encryption key reaches
8
+ // this module. One relay process owns the store; do not use PM2 cluster mode.
9
+ export class VaultServer {
10
+ private activeUploads = 0;
11
+ private requests = new Map<string, { since: number; count: number }>();
12
+ constructor(readonly root: string, readonly maxTotalBytes = 1024 ** 3) {
13
+ mkdirSync(root, { recursive: true, mode: 0o700 });
14
+ // No interrupted request is published: abandoned staging files are disposable.
15
+ for (const name of readdirSync(root)) if (/^[a-f0-9]{64}$/.test(name)) for (const file of readdirSync(join(root, name))) if (file.startsWith('.upload-')) rmSync(join(root, name, file), { force: true });
16
+ }
17
+ private inventory(directory: string): { id: string; bytes: number }[] {
18
+ if (!existsSync(directory)) return [];
19
+ return readdirSync(directory).filter(name => /^[a-f0-9]{64}$/.test(name)).map(id => ({ id, bytes: statSync(join(directory, id)).size }));
20
+ }
21
+ async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
22
+ const send = (status: number, value: unknown) => { res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value)); };
23
+ try {
24
+ const direct = req.socket.remoteAddress ?? 'unknown';
25
+ 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;
26
+ for (const [key, rate] of this.requests) if (Date.now() - rate.since > 60000) this.requests.delete(key);
27
+ if (!this.requests.has(ip) && this.requests.size >= 10000) { send(429, { error: 'Rate limit' }); return; }
28
+ const rate = this.requests.get(ip) ?? { since: Date.now(), count: 0 }; this.requests.set(ip, rate);
29
+ if (++rate.count > 600) { send(429, { error: 'Rate limit' }); return; }
30
+ const auth = /^Bearer ([A-Za-z0-9_-]{43})$/.exec(req.headers.authorization ?? '');
31
+ if (!auth) { send(401, { error: 'Library capability required' }); return; }
32
+ const namespace = createHash('sha256').update(auth[1]).digest('hex'), directory = join(this.root, namespace);
33
+ if (existsSync(join(this.root, namespace + '.revoked'))) { send(403, { error: 'Library revoked' }); return; }
34
+ const match = /^\/v1\/library(?:\/([a-f0-9]{64}))?$/.exec(req.url ?? '');
35
+ if (!match) { send(404, { error: 'Not found' }); return; }
36
+ const id = match[1];
37
+ if (req.method === 'GET') {
38
+ if (!id) { send(200, { objects: this.inventory(directory) }); return; }
39
+ const path = join(directory, id);
40
+ if (!existsSync(path)) { send(404, { error: 'Not found' }); return; }
41
+ const bytes = readFileSync(path); res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Content-Length': bytes.length }); res.end(bytes); return;
42
+ }
43
+ if (req.method === 'DELETE' && !id) {
44
+ if (!existsSync(directory)) { send(404, { error: 'Library not found' }); return; }
45
+ writeFileSync(join(this.root, namespace + '.revoked'), '', { mode: 0o600, flush: true }); rmSync(directory, { recursive: true, force: true }); send(200, { revoked: true }); return;
46
+ }
47
+ if (req.method !== 'PUT' || !id) { send(405, { error: 'Use GET, PUT object or DELETE library' }); return; }
48
+ const length = Number(req.headers['content-length']);
49
+ if (!Number.isInteger(length) || length < 29 || length > MAX_VAULT_OBJECT) { send(413, { error: 'Content-Length required, 29 bytes..12 MiB' }); return; }
50
+ if (this.activeUploads >= 2) { send(429, { error: 'Upload capacity reached' }); return; }
51
+ if (existsSync(join(directory, id))) { send(409, { error: 'Immutable object already exists' }); return; }
52
+ this.activeUploads++;
53
+ const deadline = setTimeout(() => req.destroy(), 30000);
54
+ try {
55
+ const chunks: Buffer[] = []; let size = 0;
56
+ for await (const chunk of req) { size += chunk.length; if (size > length) throw new Error('Size mismatch'); chunks.push(Buffer.from(chunk)); }
57
+ if (size !== length) throw new Error('Incomplete upload');
58
+ // Commit checks are synchronous so concurrent requests cannot overrun quota.
59
+ if (existsSync(join(this.root, namespace + '.revoked'))) { send(403, { error: 'Library revoked' }); return; }
60
+ const own = this.inventory(directory), names = readdirSync(this.root).filter(name => /^[a-f0-9]{64}(?:\.revoked)?$/.test(name));
61
+ const total = names.filter(name => !name.endsWith('.revoked')).reduce((sum, name) => sum + this.inventory(join(this.root, name)).reduce((n, item) => n + item.bytes, 0), 0);
62
+ if (own.length >= 128 || own.reduce((n, item) => n + item.bytes, 0) + size > 128 * 1024 ** 2 || total + size > this.maxTotalBytes || (!existsSync(directory) && names.length >= 1000)) { send(507, { error: 'Library storage quota reached' }); return; }
63
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
64
+ if (existsSync(join(directory, id))) { send(409, { error: 'Immutable object already exists' }); return; }
65
+ const path = join(directory, '.upload-' + randomUUID());
66
+ try { writeFileSync(path, Buffer.concat(chunks), { flag: 'wx', mode: 0o600, flush: true }); renameSync(path, join(directory, id)); }
67
+ finally { if (existsSync(path)) unlinkSync(path); }
68
+ send(201, { stored: true });
69
+ } finally { clearTimeout(deadline); this.activeUploads--; }
70
+ } catch { if (!res.headersSent && !res.destroyed) send(400, { error: 'Library request failed' }); else res.destroy(); }
71
+ }
72
+ }
package/src/vault.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { readFile, writeFile, mkdir, rm } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { SkillLibrary } from './skill-library.js';
5
+ import { MAX_VAULT_OBJECT, newRecovery, vaultKeys, objectId, sealBundle, openBundle } from './vault-crypto.js';
6
+
7
+ export class Vault {
8
+ constructor(readonly library = new SkillLibrary(), readonly root = join(homedir(), '.diagnose', 'vault'), readonly relay = 'https://diagnose.fenginwind.com') {
9
+ const url = new URL(relay);
10
+ if (url.username || url.password || url.search || url.hash || !['', '/'].includes(url.pathname) || !(url.protocol === 'https:' || (url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)))) throw new Error('Library relay must be an HTTPS origin (HTTP allowed only for loopback tests)');
11
+ }
12
+ private async key(): Promise<string> { const value = (await readFile(join(this.root, 'recovery'), 'utf8')).trim(); vaultKeys(value); return value; }
13
+ async initialize(recovery = newRecovery()): Promise<void> {
14
+ vaultKeys(recovery); await mkdir(this.root, { recursive: true, mode: 0o700 });
15
+ await writeFile(join(this.root, 'recovery'), recovery + '\n', { flag: 'wx', mode: 0o600, flush: true });
16
+ }
17
+ async backup(path: string): Promise<void> { await writeFile(path, await this.key() + '\n', { flag: 'wx', mode: 0o600, flush: true }); }
18
+ private async request(method: string, suffix = '', body?: Buffer): Promise<Buffer> {
19
+ const auth = vaultKeys(await this.key()).auth;
20
+ const response = await fetch(new URL('/v1/library' + suffix, this.relay), { method, headers: { Authorization: 'Bearer ' + auth, ...(body ? { 'Content-Type': 'application/octet-stream', 'Content-Length': String(body.length) } : {}) }, body: body ? new Uint8Array(body) : undefined, redirect: 'error', signal: AbortSignal.timeout(45000) });
21
+ if (!response.ok) { await response.body?.cancel(); throw new Error(`Library ${method} failed (${response.status}); no action was retried`); }
22
+ const chunks: Buffer[] = []; let total = 0;
23
+ if (response.body) for await (const chunk of response.body) { total += chunk.length; if (total > MAX_VAULT_OBJECT) throw new Error('Library response too large'); chunks.push(Buffer.from(chunk)); }
24
+ return Buffer.concat(chunks);
25
+ }
26
+ async list(): Promise<{ id: string; bytes: number }[]> {
27
+ const response = JSON.parse((await this.request('GET')).toString());
28
+ if (!Array.isArray(response.objects) || response.objects.length > 128 || response.objects.some((item: { id?: unknown; bytes?: number }) => typeof item.id !== 'string' || !/^[a-f0-9]{64}$/.test(item.id) || !Number.isInteger(item.bytes) || item.bytes! > MAX_VAULT_OBJECT || item.bytes! < 29)) throw new Error('Invalid library inventory');
29
+ return response.objects;
30
+ }
31
+ async push(reference: string): Promise<void> {
32
+ const recovery = await this.key(), bundle = await this.library.bundle(reference), id = objectId(recovery, reference);
33
+ const existing = (await this.list()).some(item => item.id === id);
34
+ if (existing) {
35
+ const bytes = openBundle(recovery, id, await this.request('GET', '/' + id));
36
+ if (bytes.toString() !== JSON.stringify(bundle)) throw new Error('Remote immutable version conflicts with local bundle'); return;
37
+ }
38
+ await this.request('PUT', '/' + id, sealBundle(recovery, id, Buffer.from(JSON.stringify(bundle))));
39
+ }
40
+ async pull(): Promise<string[]> {
41
+ const recovery = await this.key(), references: string[] = [];
42
+ for (const { id } of await this.list()) {
43
+ const bundle = JSON.parse(openBundle(recovery, id, await this.request('GET', '/' + id)).toString());
44
+ if (typeof bundle.reference !== 'string' || objectId(recovery, bundle.reference) !== id) throw new Error('Library object identity mismatch');
45
+ references.push(await this.library.restore(bundle));
46
+ }
47
+ return references;
48
+ }
49
+ async revoke(): Promise<void> { await this.request('DELETE'); }
50
+ async forget(): Promise<void> { await rm(join(this.root, 'recovery')); }
51
+ }