@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
@@ -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>;
@@ -0,0 +1,226 @@
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 } from './skill.js';
7
+ const MAX_BYTES = 8 * 1024 * 1024;
8
+ const MAX_FILES = 128;
9
+ const namePattern = /^[a-z0-9][a-z0-9-]{0,63}$/;
10
+ const revisionPattern = /^[a-f0-9]{64}$/;
11
+ export const skillsUsage = 'diagnose skills import NAME FILE.md|DIRECTORY\ndiagnose skills list\nLaunch: diagnose agent codex|claude|gemini --skill library:NAME@REVISION';
12
+ // Portable names only: reject separators, traversal, Windows aliases and device names.
13
+ function validPart(part) {
14
+ return /^[a-zA-Z0-9_.-]+$/.test(part) && !['.', '..'].includes(part) && !/[. ]$/.test(part) && !/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part);
15
+ }
16
+ async function readBundle(input) {
17
+ const source = resolve(input), info = await lstat(source);
18
+ if (info.isSymbolicLink())
19
+ throw new Error('Skill bundles cannot contain symbolic links');
20
+ const entries = [];
21
+ let total = 0, visited = 0;
22
+ const add = async (file, path) => {
23
+ if (entries.length >= MAX_FILES)
24
+ throw new Error('Skill bundle exceeds 128 files');
25
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
26
+ try {
27
+ const metadata = await handle.stat();
28
+ if (!metadata.isFile())
29
+ throw new Error('Skill bundles require regular files');
30
+ if (metadata.size > MAX_BYTES - total)
31
+ throw new Error('Skill bundle exceeds 8 MiB');
32
+ const buffer = Buffer.alloc(MAX_BYTES - total + 1);
33
+ let size = 0;
34
+ while (size < buffer.length) {
35
+ const { bytesRead } = await handle.read(buffer, size, buffer.length - size, size);
36
+ if (!bytesRead)
37
+ break;
38
+ size += bytesRead;
39
+ }
40
+ total += size;
41
+ if (total > MAX_BYTES)
42
+ throw new Error('Skill bundle exceeds 8 MiB');
43
+ entries.push({ path, bytes: Buffer.from(buffer.subarray(0, size)), executable: !!(metadata.mode & 0o111) });
44
+ }
45
+ finally {
46
+ await handle.close();
47
+ }
48
+ };
49
+ const walk = async (directory, prefix, depth) => {
50
+ if (depth > 16)
51
+ throw new Error('Skill directory nesting exceeds 16 levels');
52
+ const names = await readdir(directory);
53
+ const portable = new Set();
54
+ for (const name of names.sort()) {
55
+ if (++visited > 256)
56
+ throw new Error('Skill bundle exceeds 256 directory entries');
57
+ if (!validPart(name) || portable.has(name.toLowerCase()))
58
+ throw new Error('Skill bundle contains a non-portable or duplicate path');
59
+ portable.add(name.toLowerCase());
60
+ const file = join(directory, name), path = prefix + name, item = await lstat(file);
61
+ if (item.isSymbolicLink())
62
+ throw new Error('Skill bundles cannot contain symbolic links');
63
+ if (item.isDirectory())
64
+ await walk(file, path + '/', depth + 1);
65
+ else if (item.isFile())
66
+ await add(file, path);
67
+ else
68
+ throw new Error('Skill bundles require regular files');
69
+ }
70
+ };
71
+ if (info.isDirectory())
72
+ await walk(source, '', 0);
73
+ else {
74
+ await loadSkill(source);
75
+ await add(source, 'SKILL.md');
76
+ }
77
+ if (!entries.some(entry => entry.path === 'SKILL.md'))
78
+ throw new Error('Skill directory requires SKILL.md');
79
+ await loadSkill(info.isDirectory() ? join(source, 'SKILL.md') : source);
80
+ return entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
81
+ }
82
+ function digest(entries) {
83
+ // Length-delimited canonical JSON avoids ambiguous path/content concatenation.
84
+ return createHash('sha256').update(JSON.stringify(entries.map(entry => [entry.path, entry.bytes.toString('base64')]))).digest('hex');
85
+ }
86
+ export class SkillLibrary {
87
+ root;
88
+ constructor(root = join(homedir(), '.diagnose', 'skills')) {
89
+ this.root = root;
90
+ }
91
+ async bundle(reference) {
92
+ const skill = await this.load(reference);
93
+ return { reference, files: (await readBundle(skill.baseDirectory)).map(entry => ({ path: entry.path, data: entry.bytes.toString('base64') })) };
94
+ }
95
+ async exportTo(reference, directory) {
96
+ const bundle = await this.bundle(reference);
97
+ await this.writeBundle(bundle.files, directory);
98
+ }
99
+ async writeBundle(files, directory) {
100
+ if (!Array.isArray(files) || files.length > MAX_FILES)
101
+ throw new Error('Invalid skill bundle');
102
+ let total = 0;
103
+ for (const entry of files) {
104
+ if (typeof entry.path !== 'string' || entry.path.length > 2048 || !entry.path.split('/').every(validPart) || typeof entry.data !== 'string')
105
+ throw new Error('Invalid bundle path or content');
106
+ const bytes = Buffer.from(entry.data, 'base64');
107
+ total += bytes.length;
108
+ if (total > MAX_BYTES || bytes.toString('base64') !== entry.data)
109
+ throw new Error('Invalid or oversized bundle content');
110
+ const parts = entry.path.split('/'), name = parts.pop();
111
+ const parent = join(directory, ...parts);
112
+ await mkdir(parent, { recursive: true, mode: 0o700 });
113
+ await writeFile(join(parent, name), bytes, { flag: 'wx', mode: 0o600 });
114
+ }
115
+ }
116
+ async restore(bundle) {
117
+ const match = /^library:([a-z0-9][a-z0-9-]{0,63})@([a-f0-9]{64})$/.exec(bundle.reference);
118
+ if (!match)
119
+ throw new Error('Invalid bundle reference');
120
+ await mkdir(this.root, { recursive: true, mode: 0o700 });
121
+ const directory = await mkdtemp(join(this.root, '.restore-'));
122
+ try {
123
+ await this.writeBundle(bundle.files, directory);
124
+ if (digest(await readBundle(directory)) !== match[2])
125
+ throw new Error('Downloaded bundle failed integrity verification');
126
+ return await this.import(match[1], directory);
127
+ }
128
+ finally {
129
+ await rm(directory, { recursive: true, force: true });
130
+ }
131
+ }
132
+ async import(name, input) {
133
+ if (!namePattern.test(name) || !validPart(name))
134
+ throw new Error('Skill name must be a portable name of 1..64 lowercase letters, digits or hyphens, starting with a letter or digit');
135
+ const entries = await readBundle(input), revision = digest(entries), parent = join(this.root, name);
136
+ await mkdir(parent, { recursive: true, mode: 0o700 });
137
+ const reference = `library:${name}@${revision}`, destination = join(parent, revision);
138
+ try {
139
+ await lstat(destination);
140
+ await this.load(reference);
141
+ return reference;
142
+ }
143
+ catch (error) {
144
+ if (error.code !== 'ENOENT')
145
+ throw error;
146
+ }
147
+ const temporary = await mkdtemp(join(parent, '.import-'));
148
+ try {
149
+ for (const entry of entries) {
150
+ const parts = entry.path.split('/');
151
+ const filename = parts.pop();
152
+ const directory = join(temporary, ...parts);
153
+ await mkdir(directory, { recursive: true, mode: 0o700 });
154
+ await writeFile(join(directory, filename), entry.bytes, { flag: 'wx', mode: entry.executable ? 0o700 : 0o600 });
155
+ }
156
+ if (digest(await readBundle(temporary)) !== revision)
157
+ throw new Error('Skill changed during import');
158
+ try {
159
+ await rename(temporary, destination);
160
+ }
161
+ catch (error) {
162
+ // Windows reports EPERM when another import already published this
163
+ // nonempty directory. Accept only a fully verified existing revision,
164
+ // never an error code alone (which could also mean real permission loss).
165
+ try {
166
+ await this.load(reference);
167
+ }
168
+ catch {
169
+ throw error;
170
+ }
171
+ }
172
+ await this.load(reference);
173
+ return reference;
174
+ }
175
+ finally {
176
+ await rm(temporary, { recursive: true, force: true });
177
+ }
178
+ }
179
+ async load(reference) {
180
+ const match = /^library:([^@]+)@([^@]+)$/.exec(reference);
181
+ if (!match || !namePattern.test(match[1]) || !validPart(match[1]) || !revisionPattern.test(match[2]))
182
+ throw new Error('Use library:NAME@FULL_SHA256_REVISION from diagnose skills list');
183
+ const directory = join(this.root, match[1], match[2]);
184
+ if (digest(await readBundle(directory)) !== match[2])
185
+ throw new Error('Stored skill failed integrity verification; import a clean copy');
186
+ return { ...await loadSkill(directory), libraryReference: reference };
187
+ }
188
+ async list() {
189
+ let names;
190
+ try {
191
+ names = await readdir(this.root);
192
+ }
193
+ catch (error) {
194
+ if (error.code === 'ENOENT')
195
+ return [];
196
+ throw error;
197
+ }
198
+ const references = [];
199
+ for (const name of names.sort()) {
200
+ if (!namePattern.test(name) || !(await lstat(join(this.root, name))).isDirectory())
201
+ continue;
202
+ for (const revision of (await readdir(join(this.root, name))).sort()) {
203
+ if (revisionPattern.test(revision))
204
+ references.push(`library:${name}@${revision}`);
205
+ }
206
+ }
207
+ return references;
208
+ }
209
+ }
210
+ export async function resolveSkill(input) {
211
+ return input.startsWith('library:') ? new SkillLibrary().load(input) : loadSkill(input);
212
+ }
213
+ export async function skillsCommand(args) {
214
+ const library = new SkillLibrary();
215
+ if (args[0] === 'import' && args.length === 3) {
216
+ console.log(await library.import(args[1], args[2]));
217
+ return;
218
+ }
219
+ if (args[0] === 'list' && args.length === 1) {
220
+ console.log(JSON.stringify(await library.list(), null, 2));
221
+ return;
222
+ }
223
+ if (args.length && !['--help', 'help'].includes(args[0]))
224
+ throw new Error(skillsUsage);
225
+ console.log(skillsUsage);
226
+ }
package/dist/skill.d.ts CHANGED
@@ -3,6 +3,7 @@ export type SessionSkill = {
3
3
  baseDirectory: string;
4
4
  sha256: string;
5
5
  instructions: string;
6
+ libraryReference?: string;
6
7
  };
7
8
  export declare function loadSkill(input: string): Promise<SessionSkill>;
8
9
  export declare function skillPrompt(snapshot: string): string;
package/dist/skill.js CHANGED
@@ -51,6 +51,7 @@ export function skillPrompt(snapshot) {
51
51
  '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.',
52
52
  '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.',
53
53
  '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.',
54
+ '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.',
54
55
  '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.',
55
56
  '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.',
56
57
  '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/dist/util.js CHANGED
@@ -10,6 +10,7 @@ export function safeText(text) {
10
10
  export function redact(text) {
11
11
  return safeText(text)
12
12
  .replace(/("?(?:password|passwd|pswd|secret|token|session|authorization|api[_-]?key)"?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,}\r\n]+)/gi, '$1[REDACTED]')
13
+ .replace(/\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/gi, '[INVITATION CODE]')
13
14
  .replace(/\bD1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}\b/g, '[PAIRING CODE]')
14
15
  .replace(/\b[a-f0-9]{32,}\b/gi, '[REDACTED]')
15
16
  .replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g, '[PRIVATE KEY]');
@@ -0,0 +1,11 @@
1
+ export declare const MAX_VAULT_OBJECT: number;
2
+ export declare function newRecovery(): string;
3
+ export declare function vaultKeys(recovery: string): {
4
+ auth: string;
5
+ namespace: string;
6
+ encryption: Buffer<ArrayBuffer>;
7
+ index: Buffer<ArrayBuffer>;
8
+ };
9
+ export declare function objectId(recovery: string, reference: string): string;
10
+ export declare function sealBundle(recovery: string, id: string, bytes: Buffer): Buffer;
11
+ export declare function openBundle(recovery: string, id: string, sealed: Buffer): Buffer;
@@ -0,0 +1,30 @@
1
+ import { createHash, createHmac, hkdfSync, randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
2
+ export const MAX_VAULT_OBJECT = 12 * 1024 * 1024;
3
+ export function newRecovery() { return 'K1.' + randomBytes(32).toString('base64url'); }
4
+ export function vaultKeys(recovery) {
5
+ if (!/^K1\.[A-Za-z0-9_-]{43}$/.test(recovery))
6
+ throw new Error('Invalid library recovery key');
7
+ const root = Buffer.from(recovery.slice(3), 'base64url');
8
+ if (root.toString('base64url') !== recovery.slice(3))
9
+ throw new Error('Noncanonical recovery key');
10
+ const derive = (purpose) => Buffer.from(hkdfSync('sha256', root, 'diagnose-library-v1', purpose, 32));
11
+ const auth = derive('authentication').toString('base64url');
12
+ return { auth, namespace: createHash('sha256').update(auth).digest('hex'), encryption: derive('encryption'), index: derive('object-names') };
13
+ }
14
+ export function objectId(recovery, reference) { return createHmac('sha256', vaultKeys(recovery).index).update(reference).digest('hex'); }
15
+ export function sealBundle(recovery, id, bytes) {
16
+ const keys = vaultKeys(recovery), nonce = randomBytes(12), cipher = createCipheriv('aes-256-gcm', keys.encryption, nonce);
17
+ cipher.setAAD(Buffer.from(`diagnose-library-v1:${keys.namespace}:${id}`));
18
+ const sealed = Buffer.concat([Buffer.from([1]), nonce, cipher.update(bytes), cipher.final(), cipher.getAuthTag()]);
19
+ if (sealed.length > MAX_VAULT_OBJECT)
20
+ throw new Error('Encrypted bundle exceeds 12 MiB');
21
+ return sealed;
22
+ }
23
+ export function openBundle(recovery, id, sealed) {
24
+ if (sealed.length < 29 || sealed.length > MAX_VAULT_OBJECT || sealed[0] !== 1)
25
+ throw new Error('Invalid encrypted library object');
26
+ const keys = vaultKeys(recovery), decipher = createDecipheriv('aes-256-gcm', keys.encryption, sealed.subarray(1, 13));
27
+ decipher.setAAD(Buffer.from(`diagnose-library-v1:${keys.namespace}:${id}`));
28
+ decipher.setAuthTag(sealed.subarray(-16));
29
+ return Buffer.concat([decipher.update(sealed.subarray(13, -16)), decipher.final()]);
30
+ }
@@ -0,0 +1,10 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ export declare class VaultServer {
3
+ readonly root: string;
4
+ readonly maxTotalBytes: number;
5
+ private activeUploads;
6
+ private requests;
7
+ constructor(root: string, maxTotalBytes?: number);
8
+ private inventory;
9
+ handle(req: IncomingMessage, res: ServerResponse): Promise<void>;
10
+ }
@@ -0,0 +1,156 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdirSync, readdirSync, statSync, existsSync, readFileSync, writeFileSync, renameSync, rmSync, unlinkSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { MAX_VAULT_OBJECT } from './vault-crypto.js';
5
+ // Opaque capability-authenticated immutable objects. No encryption key reaches
6
+ // this module. One relay process owns the store; do not use PM2 cluster mode.
7
+ export class VaultServer {
8
+ root;
9
+ maxTotalBytes;
10
+ activeUploads = 0;
11
+ requests = new Map();
12
+ constructor(root, maxTotalBytes = 1024 ** 3) {
13
+ this.root = root;
14
+ this.maxTotalBytes = maxTotalBytes;
15
+ mkdirSync(root, { recursive: true, mode: 0o700 });
16
+ // No interrupted request is published: abandoned staging files are disposable.
17
+ for (const name of readdirSync(root))
18
+ if (/^[a-f0-9]{64}$/.test(name))
19
+ for (const file of readdirSync(join(root, name)))
20
+ if (file.startsWith('.upload-'))
21
+ rmSync(join(root, name, file), { force: true });
22
+ }
23
+ inventory(directory) {
24
+ if (!existsSync(directory))
25
+ return [];
26
+ return readdirSync(directory).filter(name => /^[a-f0-9]{64}$/.test(name)).map(id => ({ id, bytes: statSync(join(directory, id)).size }));
27
+ }
28
+ async handle(req, res) {
29
+ const send = (status, value) => { res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value)); };
30
+ try {
31
+ const direct = req.socket.remoteAddress ?? 'unknown';
32
+ const ip = ['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(direct) ? String(req.headers['x-forwarded-for'] ?? direct).split(',')[0].trim() : direct;
33
+ for (const [key, rate] of this.requests)
34
+ if (Date.now() - rate.since > 60000)
35
+ this.requests.delete(key);
36
+ if (!this.requests.has(ip) && this.requests.size >= 10000) {
37
+ send(429, { error: 'Rate limit' });
38
+ return;
39
+ }
40
+ const rate = this.requests.get(ip) ?? { since: Date.now(), count: 0 };
41
+ this.requests.set(ip, rate);
42
+ if (++rate.count > 600) {
43
+ send(429, { error: 'Rate limit' });
44
+ return;
45
+ }
46
+ const auth = /^Bearer ([A-Za-z0-9_-]{43})$/.exec(req.headers.authorization ?? '');
47
+ if (!auth) {
48
+ send(401, { error: 'Library capability required' });
49
+ return;
50
+ }
51
+ const namespace = createHash('sha256').update(auth[1]).digest('hex'), directory = join(this.root, namespace);
52
+ if (existsSync(join(this.root, namespace + '.revoked'))) {
53
+ send(403, { error: 'Library revoked' });
54
+ return;
55
+ }
56
+ const match = /^\/v1\/library(?:\/([a-f0-9]{64}))?$/.exec(req.url ?? '');
57
+ if (!match) {
58
+ send(404, { error: 'Not found' });
59
+ return;
60
+ }
61
+ const id = match[1];
62
+ if (req.method === 'GET') {
63
+ if (!id) {
64
+ send(200, { objects: this.inventory(directory) });
65
+ return;
66
+ }
67
+ const path = join(directory, id);
68
+ if (!existsSync(path)) {
69
+ send(404, { error: 'Not found' });
70
+ return;
71
+ }
72
+ const bytes = readFileSync(path);
73
+ res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Content-Length': bytes.length });
74
+ res.end(bytes);
75
+ return;
76
+ }
77
+ if (req.method === 'DELETE' && !id) {
78
+ if (!existsSync(directory)) {
79
+ send(404, { error: 'Library not found' });
80
+ return;
81
+ }
82
+ writeFileSync(join(this.root, namespace + '.revoked'), '', { mode: 0o600, flush: true });
83
+ rmSync(directory, { recursive: true, force: true });
84
+ send(200, { revoked: true });
85
+ return;
86
+ }
87
+ if (req.method !== 'PUT' || !id) {
88
+ send(405, { error: 'Use GET, PUT object or DELETE library' });
89
+ return;
90
+ }
91
+ const length = Number(req.headers['content-length']);
92
+ if (!Number.isInteger(length) || length < 29 || length > MAX_VAULT_OBJECT) {
93
+ send(413, { error: 'Content-Length required, 29 bytes..12 MiB' });
94
+ return;
95
+ }
96
+ if (this.activeUploads >= 2) {
97
+ send(429, { error: 'Upload capacity reached' });
98
+ return;
99
+ }
100
+ if (existsSync(join(directory, id))) {
101
+ send(409, { error: 'Immutable object already exists' });
102
+ return;
103
+ }
104
+ this.activeUploads++;
105
+ const deadline = setTimeout(() => req.destroy(), 30000);
106
+ try {
107
+ const chunks = [];
108
+ let size = 0;
109
+ for await (const chunk of req) {
110
+ size += chunk.length;
111
+ if (size > length)
112
+ throw new Error('Size mismatch');
113
+ chunks.push(Buffer.from(chunk));
114
+ }
115
+ if (size !== length)
116
+ throw new Error('Incomplete upload');
117
+ // Commit checks are synchronous so concurrent requests cannot overrun quota.
118
+ if (existsSync(join(this.root, namespace + '.revoked'))) {
119
+ send(403, { error: 'Library revoked' });
120
+ return;
121
+ }
122
+ const own = this.inventory(directory), names = readdirSync(this.root).filter(name => /^[a-f0-9]{64}(?:\.revoked)?$/.test(name));
123
+ 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);
124
+ 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)) {
125
+ send(507, { error: 'Library storage quota reached' });
126
+ return;
127
+ }
128
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
129
+ if (existsSync(join(directory, id))) {
130
+ send(409, { error: 'Immutable object already exists' });
131
+ return;
132
+ }
133
+ const path = join(directory, '.upload-' + randomUUID());
134
+ try {
135
+ writeFileSync(path, Buffer.concat(chunks), { flag: 'wx', mode: 0o600, flush: true });
136
+ renameSync(path, join(directory, id));
137
+ }
138
+ finally {
139
+ if (existsSync(path))
140
+ unlinkSync(path);
141
+ }
142
+ send(201, { stored: true });
143
+ }
144
+ finally {
145
+ clearTimeout(deadline);
146
+ this.activeUploads--;
147
+ }
148
+ }
149
+ catch {
150
+ if (!res.headersSent && !res.destroyed)
151
+ send(400, { error: 'Library request failed' });
152
+ else
153
+ res.destroy();
154
+ }
155
+ }
156
+ }
@@ -0,0 +1,19 @@
1
+ import { SkillLibrary } from './skill-library.js';
2
+ export declare class Vault {
3
+ readonly library: SkillLibrary;
4
+ readonly root: string;
5
+ readonly relay: string;
6
+ constructor(library?: SkillLibrary, root?: string, relay?: string);
7
+ private key;
8
+ initialize(recovery?: string): Promise<void>;
9
+ backup(path: string): Promise<void>;
10
+ private request;
11
+ list(): Promise<{
12
+ id: string;
13
+ bytes: number;
14
+ }[]>;
15
+ push(reference: string): Promise<void>;
16
+ pull(): Promise<string[]>;
17
+ revoke(): Promise<void>;
18
+ forget(): Promise<void>;
19
+ }
package/dist/vault.js ADDED
@@ -0,0 +1,72 @@
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
+ export class Vault {
7
+ library;
8
+ root;
9
+ relay;
10
+ constructor(library = new SkillLibrary(), root = join(homedir(), '.diagnose', 'vault'), relay = 'https://diagnose.fenginwind.com') {
11
+ this.library = library;
12
+ this.root = root;
13
+ this.relay = relay;
14
+ const url = new URL(relay);
15
+ 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))))
16
+ throw new Error('Library relay must be an HTTPS origin (HTTP allowed only for loopback tests)');
17
+ }
18
+ async key() { const value = (await readFile(join(this.root, 'recovery'), 'utf8')).trim(); vaultKeys(value); return value; }
19
+ async initialize(recovery = newRecovery()) {
20
+ vaultKeys(recovery);
21
+ await mkdir(this.root, { recursive: true, mode: 0o700 });
22
+ await writeFile(join(this.root, 'recovery'), recovery + '\n', { flag: 'wx', mode: 0o600, flush: true });
23
+ }
24
+ async backup(path) { await writeFile(path, await this.key() + '\n', { flag: 'wx', mode: 0o600, flush: true }); }
25
+ async request(method, suffix = '', body) {
26
+ const auth = vaultKeys(await this.key()).auth;
27
+ 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) });
28
+ if (!response.ok) {
29
+ await response.body?.cancel();
30
+ throw new Error(`Library ${method} failed (${response.status}); no action was retried`);
31
+ }
32
+ const chunks = [];
33
+ let total = 0;
34
+ if (response.body)
35
+ for await (const chunk of response.body) {
36
+ total += chunk.length;
37
+ if (total > MAX_VAULT_OBJECT)
38
+ throw new Error('Library response too large');
39
+ chunks.push(Buffer.from(chunk));
40
+ }
41
+ return Buffer.concat(chunks);
42
+ }
43
+ async list() {
44
+ const response = JSON.parse((await this.request('GET')).toString());
45
+ if (!Array.isArray(response.objects) || response.objects.length > 128 || response.objects.some((item) => typeof item.id !== 'string' || !/^[a-f0-9]{64}$/.test(item.id) || !Number.isInteger(item.bytes) || item.bytes > MAX_VAULT_OBJECT || item.bytes < 29))
46
+ throw new Error('Invalid library inventory');
47
+ return response.objects;
48
+ }
49
+ async push(reference) {
50
+ const recovery = await this.key(), bundle = await this.library.bundle(reference), id = objectId(recovery, reference);
51
+ const existing = (await this.list()).some(item => item.id === id);
52
+ if (existing) {
53
+ const bytes = openBundle(recovery, id, await this.request('GET', '/' + id));
54
+ if (bytes.toString() !== JSON.stringify(bundle))
55
+ throw new Error('Remote immutable version conflicts with local bundle');
56
+ return;
57
+ }
58
+ await this.request('PUT', '/' + id, sealBundle(recovery, id, Buffer.from(JSON.stringify(bundle))));
59
+ }
60
+ async pull() {
61
+ const recovery = await this.key(), references = [];
62
+ for (const { id } of await this.list()) {
63
+ const bundle = JSON.parse(openBundle(recovery, id, await this.request('GET', '/' + id)).toString());
64
+ if (typeof bundle.reference !== 'string' || objectId(recovery, bundle.reference) !== id)
65
+ throw new Error('Library object identity mismatch');
66
+ references.push(await this.library.restore(bundle));
67
+ }
68
+ return references;
69
+ }
70
+ async revoke() { await this.request('DELETE'); }
71
+ async forget() { await rm(join(this.root, 'recovery')); }
72
+ }