@mindbricks/genesis-set 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/README.md +69 -1
- package/bin/genesis-set.mjs +58 -0
- package/lib/init.mjs +206 -0
- package/lib/install.mjs +5 -1
- package/mcp/board-data.mjs +267 -0
- package/mcp/board-html.mjs +329 -0
- package/mcp/board-md.mjs +123 -0
- package/mcp/board.mjs +316 -0
- package/mcp/key-store.mjs +56 -22
- package/mcp/key-tools.mjs +57 -10
- package/mcp/project.mjs +90 -0
- package/mcp/server.mjs +3 -1
- package/package.json +1 -1
- package/skills/genesis-compiler-api/SKILL.md +3 -0
package/mcp/board-md.mjs
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// A small Markdown renderer for the project board (#9386). The design documents
|
|
2
|
+
// are written by an agent in the user's own folder; the board shows them read-only.
|
|
3
|
+
// Everything is HTML-escaped first, then a fixed subset is turned into markup:
|
|
4
|
+
// headings, paragraphs, lists, fenced code, tables, block quotes, rules, inline
|
|
5
|
+
// code, bold, italic and http(s) / relative links. No raw HTML passes through,
|
|
6
|
+
// no image is loaded, and nothing else is interpreted.
|
|
7
|
+
|
|
8
|
+
const ESC = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
|
9
|
+
export function escapeHtml(text) {
|
|
10
|
+
return String(text).replace(/[&<>"']/g, (c) => ESC[c]);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Inline markup of one already-escaped line. */
|
|
14
|
+
function inline(escaped) {
|
|
15
|
+
const codes = [];
|
|
16
|
+
let s = escaped.replace(/`([^`]+)`/g, (_m, c) => {
|
|
17
|
+
codes.push(c);
|
|
18
|
+
return `\u0000${codes.length - 1}\u0000`;
|
|
19
|
+
});
|
|
20
|
+
s = s
|
|
21
|
+
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
|
|
22
|
+
.replace(/(^|[^*\w])\*([^*\s][^*]*)\*(?![*\w])/g, '$1<em>$2</em>')
|
|
23
|
+
.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (m, label, href) => {
|
|
24
|
+
// The href is escaped text: only http(s) and relative links become links.
|
|
25
|
+
if (/^(https?:\/\/|#|\.{0,2}\/|[A-Za-z0-9_-]+\.md)/.test(href) && !/^javascript:/i.test(href)) {
|
|
26
|
+
const external = /^https?:\/\//.test(href);
|
|
27
|
+
return `<a href="${href}"${external ? ' target="_blank" rel="noopener noreferrer"' : ''}>${label}</a>`;
|
|
28
|
+
}
|
|
29
|
+
return m;
|
|
30
|
+
});
|
|
31
|
+
return s.replace(/\u0000(\d+)\u0000/g, (_m, i) => `<code>${codes[Number(i)]}</code>`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function tableRow(line) {
|
|
35
|
+
return line.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Markdown text to a safe HTML fragment. */
|
|
39
|
+
export function renderMarkdown(text) {
|
|
40
|
+
const lines = String(text).replace(/\r\n?/g, '\n').split('\n');
|
|
41
|
+
const out = [];
|
|
42
|
+
let i = 0;
|
|
43
|
+
const para = [];
|
|
44
|
+
const flush = () => {
|
|
45
|
+
if (para.length) out.push(`<p>${inline(escapeHtml(para.join(' ')))}</p>`);
|
|
46
|
+
para.length = 0;
|
|
47
|
+
};
|
|
48
|
+
while (i < lines.length) {
|
|
49
|
+
const line = lines[i];
|
|
50
|
+
const fence = line.match(/^\s*(```|~~~)\s*([\w-]*)/);
|
|
51
|
+
if (fence) {
|
|
52
|
+
flush();
|
|
53
|
+
const body = [];
|
|
54
|
+
i++;
|
|
55
|
+
while (i < lines.length && !lines[i].trimStart().startsWith(fence[1])) body.push(lines[i++]);
|
|
56
|
+
i++;
|
|
57
|
+
out.push(`<pre><code${fence[2] ? ` data-lang="${escapeHtml(fence[2])}"` : ''}>${escapeHtml(body.join('\n'))}</code></pre>`);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const h = line.match(/^(#{1,6})\s+(.*)$/);
|
|
61
|
+
if (h) {
|
|
62
|
+
flush();
|
|
63
|
+
const level = Math.min(h[1].length + 1, 6); // the page owns <h1>
|
|
64
|
+
out.push(`<h${level}>${inline(escapeHtml(h[2].replace(/\s*#+\s*$/, '')))}</h${level}>`);
|
|
65
|
+
i++;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(line)) {
|
|
69
|
+
flush();
|
|
70
|
+
out.push('<hr>');
|
|
71
|
+
i++;
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (/^\s*\|.*\|\s*$/.test(line) && i + 1 < lines.length && /^\s*\|?\s*:?-{2,}/.test(lines[i + 1])) {
|
|
75
|
+
flush();
|
|
76
|
+
const head = tableRow(line);
|
|
77
|
+
i += 2;
|
|
78
|
+
const rows = [];
|
|
79
|
+
while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) rows.push(tableRow(lines[i++]));
|
|
80
|
+
out.push(
|
|
81
|
+
`<div class="table"><table><thead><tr>${head.map((c) => `<th>${inline(escapeHtml(c))}</th>`).join('')}</tr></thead><tbody>` +
|
|
82
|
+
rows.map((r) => `<tr>${r.map((c) => `<td>${inline(escapeHtml(c))}</td>`).join('')}</tr>`).join('') +
|
|
83
|
+
'</tbody></table></div>',
|
|
84
|
+
);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const li = line.match(/^(\s*)([-*+]|\d+[.)])\s+(.*)$/);
|
|
88
|
+
if (li) {
|
|
89
|
+
flush();
|
|
90
|
+
const ordered = /\d/.test(li[2]);
|
|
91
|
+
const items = [];
|
|
92
|
+
while (i < lines.length) {
|
|
93
|
+
const m = lines[i].match(/^(\s*)([-*+]|\d+[.)])\s+(.*)$/);
|
|
94
|
+
if (m) {
|
|
95
|
+
items.push({ depth: Math.floor(m[1].replace(/\t/g, ' ').length / 2), text: m[3] });
|
|
96
|
+
i++;
|
|
97
|
+
} else if (lines[i].trim() && /^\s{2,}/.test(lines[i]) && items.length) {
|
|
98
|
+
items[items.length - 1].text += ` ${lines[i].trim()}`;
|
|
99
|
+
i++;
|
|
100
|
+
} else break;
|
|
101
|
+
}
|
|
102
|
+
const tag = ordered ? 'ol' : 'ul';
|
|
103
|
+
out.push(`<${tag}>${items.map((it) => `<li${it.depth ? ` class="d${Math.min(it.depth, 4)}"` : ''}>${inline(escapeHtml(it.text))}</li>`).join('')}</${tag}>`);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (/^\s*>/.test(line)) {
|
|
107
|
+
flush();
|
|
108
|
+
const quote = [];
|
|
109
|
+
while (i < lines.length && /^\s*>/.test(lines[i])) quote.push(lines[i++].replace(/^\s*>\s?/, ''));
|
|
110
|
+
out.push(`<blockquote>${inline(escapeHtml(quote.join(' ')))}</blockquote>`);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (!line.trim()) {
|
|
114
|
+
flush();
|
|
115
|
+
i++;
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
para.push(line.trim());
|
|
119
|
+
i++;
|
|
120
|
+
}
|
|
121
|
+
flush();
|
|
122
|
+
return out.join('\n');
|
|
123
|
+
}
|
package/mcp/board.mjs
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
// The project board server (#9386, epic #9384): one local page per genesis
|
|
2
|
+
// project with its design flow, documents, interview, blueprint and keys.
|
|
3
|
+
//
|
|
4
|
+
// - 127.0.0.1 on a fixed default port (BOARD_PORT, or GENESIS_BOARD_PORT; then the next ones), so the
|
|
5
|
+
// board can be bookmarked. A second `genesis board` (or the agent) for the same
|
|
6
|
+
// project finds the running board through /api/whoami and reuses it.
|
|
7
|
+
// - Reading needs no token: the page and /api/* GETs answer anyone on this
|
|
8
|
+
// machine who uses the board's own address (Host check against DNS rebinding;
|
|
9
|
+
// no CORS, so another site cannot read the answers).
|
|
10
|
+
// - Writing (keys) needs the run's write cookie, set when the board is opened
|
|
11
|
+
// with its write link (`genesis board`, the agent's link): HttpOnly,
|
|
12
|
+
// SameSite=Strict, named per port. Every write also needs the board's own
|
|
13
|
+
// Origin and a JSON body.
|
|
14
|
+
// - The run's token sits in <data>/board/<port>.json (0600) while the board runs,
|
|
15
|
+
// so a second process can hand out a write link to the running board.
|
|
16
|
+
// - The board closes after IDLE_MS without a request (an open page polls, so it
|
|
17
|
+
// stays up while someone looks at it) and when its process ends.
|
|
18
|
+
|
|
19
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
20
|
+
import fs from 'node:fs';
|
|
21
|
+
import http from 'node:http';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
|
|
24
|
+
import { dataDirOf } from './config.mjs';
|
|
25
|
+
import { boardState, designDoc } from './board-data.mjs';
|
|
26
|
+
import { renderBoardPage } from './board-html.mjs';
|
|
27
|
+
import { renderMarkdown } from './board-md.mjs';
|
|
28
|
+
import { KeyStoreError, SCOPES, clearKeyValue, deleteKey, requestKey, setKeyValue } from './key-store.mjs';
|
|
29
|
+
|
|
30
|
+
export const BOARD_PORT = 4747;
|
|
31
|
+
const PORT_TRIES = 20;
|
|
32
|
+
export const BOARD_IDLE_MS = 60 * 60 * 1000;
|
|
33
|
+
const MAX_BODY = 32 * 1024;
|
|
34
|
+
|
|
35
|
+
let current = null; // { server, port, token, project, env, idleMs, timer, tokenFile, closed, resolveClosed }
|
|
36
|
+
|
|
37
|
+
function sameToken(a, b) {
|
|
38
|
+
if (typeof a !== 'string' || typeof b !== 'string') return false;
|
|
39
|
+
const x = Buffer.from(a);
|
|
40
|
+
const y = Buffer.from(b);
|
|
41
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const cookieName = (port) => `genesis_board_${port}`;
|
|
45
|
+
|
|
46
|
+
function cookieOf(req, port) {
|
|
47
|
+
const header = String(req.headers.cookie ?? '');
|
|
48
|
+
for (const part of header.split(';')) {
|
|
49
|
+
const [k, ...v] = part.trim().split('=');
|
|
50
|
+
if (k === cookieName(port)) return v.join('=');
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function headers(res, nonce) {
|
|
56
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
57
|
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
58
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
59
|
+
res.setHeader('X-Frame-Options', 'DENY');
|
|
60
|
+
res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
|
|
61
|
+
res.setHeader(
|
|
62
|
+
'Content-Security-Policy',
|
|
63
|
+
`default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; ` +
|
|
64
|
+
"img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function sendJson(res, status, body) {
|
|
69
|
+
res.statusCode = status;
|
|
70
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
71
|
+
res.end(JSON.stringify(body));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const sendError = (res, status, code, message) => sendJson(res, status, { error: { code, message } });
|
|
75
|
+
|
|
76
|
+
function readJson(req) {
|
|
77
|
+
return new Promise((resolve, reject) => {
|
|
78
|
+
let size = 0;
|
|
79
|
+
const chunks = [];
|
|
80
|
+
req.on('data', (c) => {
|
|
81
|
+
size += c.length;
|
|
82
|
+
if (size > MAX_BODY) {
|
|
83
|
+
reject(new KeyStoreError('GENESIS_KEY_BAD_INPUT', 'the request body is too large', 413));
|
|
84
|
+
req.destroy();
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
chunks.push(c);
|
|
88
|
+
});
|
|
89
|
+
req.on('end', () => {
|
|
90
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
91
|
+
if (!text) return resolve({});
|
|
92
|
+
try {
|
|
93
|
+
const v = JSON.parse(text);
|
|
94
|
+
resolve(v && typeof v === 'object' && !Array.isArray(v) ? v : {});
|
|
95
|
+
} catch {
|
|
96
|
+
reject(new KeyStoreError('GENESIS_KEY_BAD_INPUT', 'the request body is not JSON'));
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
req.on('error', reject);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const ownHosts = (port) => new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
|
|
104
|
+
|
|
105
|
+
function touch(board) {
|
|
106
|
+
clearTimeout(board.timer);
|
|
107
|
+
board.timer = setTimeout(() => closeBoard(), board.idleMs);
|
|
108
|
+
board.timer.unref?.();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function handle(board, req, res) {
|
|
112
|
+
const nonce = randomBytes(16).toString('base64');
|
|
113
|
+
headers(res, nonce);
|
|
114
|
+
const hosts = ownHosts(board.port);
|
|
115
|
+
if (!hosts.has(String(req.headers.host ?? '').toLowerCase())) {
|
|
116
|
+
return sendError(res, 421, 'GENESIS_BOARD_HOST', 'the board answers only on its own local address');
|
|
117
|
+
}
|
|
118
|
+
touch(board);
|
|
119
|
+
const url = new URL(req.url ?? '/', `http://127.0.0.1:${board.port}`);
|
|
120
|
+
const canWrite = sameToken(cookieOf(req, board.port), board.token);
|
|
121
|
+
|
|
122
|
+
if (req.method === 'GET' && url.pathname === '/') {
|
|
123
|
+
const t = url.searchParams.get('t');
|
|
124
|
+
if (t !== null) {
|
|
125
|
+
// The write link: set the write cookie when the token is right, then drop the token from the address.
|
|
126
|
+
if (sameToken(t, board.token)) {
|
|
127
|
+
res.setHeader('Set-Cookie', `${cookieName(board.port)}=${board.token}; HttpOnly; SameSite=Strict; Path=/`);
|
|
128
|
+
}
|
|
129
|
+
res.statusCode = 303;
|
|
130
|
+
res.setHeader('Location', `/${url.hash}`);
|
|
131
|
+
return res.end();
|
|
132
|
+
}
|
|
133
|
+
res.statusCode = 200;
|
|
134
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
135
|
+
return res.end(renderBoardPage({ nonce, projectName: board.project.name }));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (req.method === 'GET' && url.pathname === '/api/whoami') {
|
|
139
|
+
return sendJson(res, 200, { app: 'genesis-board', projectId: board.project.id, dataDir: dataDirOf(board.env) });
|
|
140
|
+
}
|
|
141
|
+
if (req.method === 'GET' && url.pathname === '/api/state') {
|
|
142
|
+
const state = await boardState({ env: board.env, project: board.project });
|
|
143
|
+
return sendJson(res, 200, { ...state, canWrite });
|
|
144
|
+
}
|
|
145
|
+
if (req.method === 'GET' && url.pathname === '/api/doc') {
|
|
146
|
+
const name = url.searchParams.get('name') ?? '';
|
|
147
|
+
const text = designDoc(board.project, name);
|
|
148
|
+
if (text === null) return sendError(res, 404, 'GENESIS_BOARD_NO_DOC', 'no such design document');
|
|
149
|
+
return sendJson(res, 200, { name, html: renderMarkdown(text) });
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (url.pathname.startsWith('/api/keys')) {
|
|
153
|
+
if (req.method === 'GET') return sendError(res, 405, 'GENESIS_BOARD_METHOD', 'read the keys from /api/state');
|
|
154
|
+
if (!canWrite) return sendError(res, 403, 'GENESIS_BOARD_READ_ONLY', 'this board is read-only here; open it with "genesis board" to change keys');
|
|
155
|
+
const origin = String(req.headers.origin ?? '').toLowerCase();
|
|
156
|
+
if (!origin || !hosts.has(origin.replace(/^http:\/\//, ''))) {
|
|
157
|
+
return sendError(res, 403, 'GENESIS_BOARD_ORIGIN', 'writes are accepted only from the board itself');
|
|
158
|
+
}
|
|
159
|
+
if (req.method !== 'DELETE' && !String(req.headers['content-type'] ?? '').toLowerCase().startsWith('application/json')) {
|
|
160
|
+
return sendError(res, 415, 'GENESIS_KEY_BAD_INPUT', 'send JSON');
|
|
161
|
+
}
|
|
162
|
+
const parts = url.pathname.split('/').filter(Boolean).map(decodeURIComponent); // api, keys, scope?, name?, value?
|
|
163
|
+
const [, , scope, name, sub] = parts;
|
|
164
|
+
const where = { scope, project: board.project };
|
|
165
|
+
try {
|
|
166
|
+
if (req.method === 'POST' && !scope) {
|
|
167
|
+
const b = await readJson(req);
|
|
168
|
+
const s = SCOPES.includes(b.scope) ? b.scope : 'project';
|
|
169
|
+
return sendJson(res, 200, { key: requestKey(board.env, { name: b.name, label: b.label, description: b.description }, { scope: s, project: board.project }) });
|
|
170
|
+
}
|
|
171
|
+
if (!SCOPES.includes(scope) || !name) return sendError(res, 404, 'GENESIS_BOARD_NOT_FOUND', 'no such key path');
|
|
172
|
+
if (sub === 'value' && req.method === 'PUT') {
|
|
173
|
+
const b = await readJson(req);
|
|
174
|
+
return sendJson(res, 200, { key: setKeyValue(board.env, name, b.value, where) });
|
|
175
|
+
}
|
|
176
|
+
if (sub === 'value' && req.method === 'DELETE') return sendJson(res, 200, { key: clearKeyValue(board.env, name, where) });
|
|
177
|
+
if (!sub && req.method === 'DELETE') {
|
|
178
|
+
deleteKey(board.env, name, where);
|
|
179
|
+
return sendJson(res, 200, { deleted: name, scope });
|
|
180
|
+
}
|
|
181
|
+
if (!sub && req.method === 'PATCH') {
|
|
182
|
+
const b = await readJson(req);
|
|
183
|
+
return sendJson(res, 200, { key: requestKey(board.env, { name, label: b.label, description: b.description }, where) });
|
|
184
|
+
}
|
|
185
|
+
return sendError(res, 405, 'GENESIS_BOARD_METHOD', 'not supported');
|
|
186
|
+
} catch (err) {
|
|
187
|
+
if (err instanceof KeyStoreError) return sendError(res, err.status, err.code, err.message);
|
|
188
|
+
throw err;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return sendError(res, 404, 'GENESIS_BOARD_NOT_FOUND', 'no such page');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function tokenFileOf(env, port) {
|
|
195
|
+
return path.join(dataDirOf(env), 'board', `${port}.json`);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Asks a running board on `port` who it is; null when nothing (or something else) answers. */
|
|
199
|
+
function whoami(port) {
|
|
200
|
+
return new Promise((resolve) => {
|
|
201
|
+
const req = http.get({ host: '127.0.0.1', port, path: '/api/whoami', headers: { host: `127.0.0.1:${port}` }, timeout: 1500 }, (res) => {
|
|
202
|
+
let text = '';
|
|
203
|
+
res.setEncoding('utf8');
|
|
204
|
+
res.on('data', (c) => (text += c));
|
|
205
|
+
res.on('end', () => {
|
|
206
|
+
try {
|
|
207
|
+
const j = JSON.parse(text);
|
|
208
|
+
resolve(j && j.app === 'genesis-board' ? j : null);
|
|
209
|
+
} catch {
|
|
210
|
+
resolve(null);
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
req.on('error', () => resolve(null));
|
|
215
|
+
req.on('timeout', () => {
|
|
216
|
+
req.destroy();
|
|
217
|
+
resolve(null);
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function linksOf(port, token) {
|
|
223
|
+
return {
|
|
224
|
+
url: token ? `http://127.0.0.1:${port}/?t=${token}` : `http://127.0.0.1:${port}/`,
|
|
225
|
+
readUrl: `http://127.0.0.1:${port}/`,
|
|
226
|
+
port,
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function listen(server, port) {
|
|
231
|
+
return new Promise((resolve) => {
|
|
232
|
+
const onError = (e) => {
|
|
233
|
+
server.off('listening', onListening);
|
|
234
|
+
resolve(e.code === 'EADDRINUSE' || e.code === 'EACCES' ? false : Promise.reject(e));
|
|
235
|
+
};
|
|
236
|
+
const onListening = () => {
|
|
237
|
+
server.off('error', onError);
|
|
238
|
+
resolve(true);
|
|
239
|
+
};
|
|
240
|
+
server.once('error', onError);
|
|
241
|
+
server.once('listening', onListening);
|
|
242
|
+
server.listen(port, '127.0.0.1');
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* The board of `project`: this process's running one, a running one of another
|
|
248
|
+
* process (found on the ports), or a new one. Answers `{ url, readUrl, port,
|
|
249
|
+
* reused, idleMinutes }`; `url` carries the write token when it is known.
|
|
250
|
+
*/
|
|
251
|
+
export async function ensureBoard({ env = process.env, project, idleMs = BOARD_IDLE_MS, basePort } = {}) {
|
|
252
|
+
basePort = basePort ?? (Number.parseInt(env.GENESIS_BOARD_PORT ?? '', 10) || BOARD_PORT);
|
|
253
|
+
if (!project) throw new Error('the board needs a genesis project ("genesis init" makes one)');
|
|
254
|
+
if (current && current.server.listening && current.project.id === project.id && current.env === env) {
|
|
255
|
+
touch(current);
|
|
256
|
+
return { ...linksOf(current.port, current.token), reused: true, idleMinutes: Math.round(current.idleMs / 60000) };
|
|
257
|
+
}
|
|
258
|
+
if (current) await closeBoard();
|
|
259
|
+
const board = { token: randomBytes(24).toString('base64url'), env, project, idleMs, port: 0, timer: null, server: null };
|
|
260
|
+
board.closed = new Promise((r) => {
|
|
261
|
+
board.resolveClosed = r;
|
|
262
|
+
});
|
|
263
|
+
board.server = http.createServer((req, res) => {
|
|
264
|
+
handle(board, req, res).catch(() => {
|
|
265
|
+
if (!res.headersSent) sendError(res, 500, 'GENESIS_BOARD_ERROR', 'the board could not complete the request');
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
board.server.keepAliveTimeout = 1000;
|
|
269
|
+
for (let port = basePort; port < basePort + PORT_TRIES; port++) {
|
|
270
|
+
if (await listen(board.server, port)) {
|
|
271
|
+
board.port = port;
|
|
272
|
+
break;
|
|
273
|
+
}
|
|
274
|
+
const other = await whoami(port);
|
|
275
|
+
if (other && other.projectId === project.id && other.dataDir === dataDirOf(env)) {
|
|
276
|
+
let token = null;
|
|
277
|
+
try {
|
|
278
|
+
token = JSON.parse(fs.readFileSync(tokenFileOf(env, port), 'utf8')).token ?? null;
|
|
279
|
+
} catch {
|
|
280
|
+
// the running board did not leave its token: the link is read-only
|
|
281
|
+
}
|
|
282
|
+
return { ...linksOf(port, token), reused: true, idleMinutes: null };
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if (!board.port) throw new Error(`no free port for the board between ${basePort} and ${basePort + PORT_TRIES - 1}`);
|
|
286
|
+
board.server.unref();
|
|
287
|
+
board.tokenFile = tokenFileOf(env, board.port);
|
|
288
|
+
try {
|
|
289
|
+
fs.mkdirSync(path.dirname(board.tokenFile), { recursive: true, mode: 0o700 });
|
|
290
|
+
fs.writeFileSync(board.tokenFile, JSON.stringify({ token: board.token, pid: process.pid, projectId: project.id }), { mode: 0o600 });
|
|
291
|
+
} catch {
|
|
292
|
+
board.tokenFile = null; // the board still works; another process just cannot hand out its write link
|
|
293
|
+
}
|
|
294
|
+
current = board;
|
|
295
|
+
touch(board);
|
|
296
|
+
return { ...linksOf(board.port, board.token), reused: false, idleMinutes: Math.round(idleMs / 60000) };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Closes this process's board; its links stop working and its token file goes. */
|
|
300
|
+
export async function closeBoard() {
|
|
301
|
+
const board = current;
|
|
302
|
+
current = null;
|
|
303
|
+
if (!board) return;
|
|
304
|
+
clearTimeout(board.timer);
|
|
305
|
+
if (board.tokenFile) fs.rmSync(board.tokenFile, { force: true });
|
|
306
|
+
await new Promise((resolve) => {
|
|
307
|
+
board.server.close(() => resolve());
|
|
308
|
+
board.server.closeAllConnections?.();
|
|
309
|
+
});
|
|
310
|
+
board.resolveClosed();
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Resolves when this process's board closes; at once when none runs. */
|
|
314
|
+
export function boardClosed() {
|
|
315
|
+
return current ? current.closed : Promise.resolve();
|
|
316
|
+
}
|
package/mcp/key-store.mjs
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
// uses a key (writing a gitignored env file), never for a tool answer.
|
|
14
14
|
|
|
15
15
|
import { API_KEY_ENV, configPathOf, maskSecret, readConfigFile, writeConfigFile } from './config.mjs';
|
|
16
|
+
import { projectKeysFile } from './project.mjs';
|
|
16
17
|
|
|
17
18
|
export const BUILTIN_KEY = 'genesis-api-key';
|
|
18
19
|
const BUILTIN_LABEL = 'Genesis API key';
|
|
@@ -38,17 +39,32 @@ function now() {
|
|
|
38
39
|
return new Date().toISOString();
|
|
39
40
|
}
|
|
40
41
|
|
|
41
|
-
|
|
42
|
-
|
|
42
|
+
/**
|
|
43
|
+
* Where a scope's keys live. `global`: the genesis-set config file. `project`:
|
|
44
|
+
* the project's keys file under the user's home (never the project folder);
|
|
45
|
+
* it needs the project (`findProject`).
|
|
46
|
+
*/
|
|
47
|
+
export const SCOPES = ['project', 'global'];
|
|
48
|
+
|
|
49
|
+
function checkScope(scope, project) {
|
|
50
|
+
if (!SCOPES.includes(scope)) throw new KeyStoreError('GENESIS_KEY_BAD_INPUT', `scope must be one of: ${SCOPES.join(', ')}`);
|
|
51
|
+
if (scope === 'project' && !project) {
|
|
52
|
+
throw new KeyStoreError('GENESIS_KEY_NO_PROJECT', 'this folder is not a genesis project; run "genesis init" here, or use the global scope', 409);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function load(env, scope = 'global', project = null) {
|
|
57
|
+
checkScope(scope, project);
|
|
58
|
+
const file = scope === 'project' ? projectKeysFile(env, project.id) : configPathOf(env);
|
|
43
59
|
const cfg = readConfigFile(file);
|
|
44
60
|
if (cfg.__error) throw new KeyStoreError('GENESIS_KEY_STORE_UNREADABLE', `${cfg.__error}; fix or delete it first`, 500);
|
|
45
61
|
const keys = cfg.keys && typeof cfg.keys === 'object' && !Array.isArray(cfg.keys) ? { ...cfg.keys } : {};
|
|
46
|
-
return { file, cfg, keys };
|
|
62
|
+
return { file, cfg, keys, scope };
|
|
47
63
|
}
|
|
48
64
|
|
|
49
|
-
function save({ file, cfg, keys }) {
|
|
65
|
+
function save({ file, cfg, keys, scope }) {
|
|
50
66
|
const next = { ...cfg, keys };
|
|
51
|
-
if (Object.keys(keys).length === 0) delete next.keys;
|
|
67
|
+
if (Object.keys(keys).length === 0 && scope !== 'project') delete next.keys;
|
|
52
68
|
for (const [k, v] of Object.entries(next)) if (v === undefined) delete next[k];
|
|
53
69
|
writeConfigFile(file, next);
|
|
54
70
|
}
|
|
@@ -80,7 +96,7 @@ function checkValue(value) {
|
|
|
80
96
|
return v;
|
|
81
97
|
}
|
|
82
98
|
|
|
83
|
-
function row(name, entry, { builtin = false, envOverride = false, envValue = null } = {}) {
|
|
99
|
+
function row(name, entry, { builtin = false, envOverride = false, envValue = null, scope = 'global' } = {}) {
|
|
84
100
|
const value = typeof entry.value === 'string' && entry.value ? entry.value : null;
|
|
85
101
|
// The key in effect: for the Genesis API key the environment variable wins over the file.
|
|
86
102
|
return {
|
|
@@ -88,6 +104,7 @@ function row(name, entry, { builtin = false, envOverride = false, envValue = nul
|
|
|
88
104
|
label: entry.label || name,
|
|
89
105
|
description: entry.description || '',
|
|
90
106
|
builtin,
|
|
107
|
+
scope,
|
|
91
108
|
status: value || envOverride ? 'set' : 'empty',
|
|
92
109
|
...(envOverride ? { source: API_KEY_ENV } : {}),
|
|
93
110
|
masked: maskSecret(envOverride ? envValue : value),
|
|
@@ -99,7 +116,7 @@ function row(name, entry, { builtin = false, envOverride = false, envValue = nul
|
|
|
99
116
|
* Every key, the built-in Genesis API key first. `masked` (the type prefix and
|
|
100
117
|
* the last four characters, see maskSecret) is for the page; the tools drop it.
|
|
101
118
|
*/
|
|
102
|
-
export function listKeys(env = process.env) {
|
|
119
|
+
export function listKeys(env = process.env, { project = null } = {}) {
|
|
103
120
|
const { cfg, keys } = load(env);
|
|
104
121
|
const envKey = typeof env[API_KEY_ENV] === 'string' && env[API_KEY_ENV].trim() !== '';
|
|
105
122
|
const rows = [
|
|
@@ -109,6 +126,14 @@ export function listKeys(env = process.env) {
|
|
|
109
126
|
{ builtin: true, envOverride: envKey, envValue: envKey ? env[API_KEY_ENV] : null },
|
|
110
127
|
),
|
|
111
128
|
];
|
|
129
|
+
if (project) {
|
|
130
|
+
const p = load(env, 'project', project);
|
|
131
|
+
for (const name of Object.keys(p.keys).sort()) {
|
|
132
|
+
if (!KEY_NAME_PATTERN.test(name) || name === BUILTIN_KEY) continue;
|
|
133
|
+
const e = p.keys[name];
|
|
134
|
+
if (e && typeof e === 'object') rows.push(row(name, e, { scope: 'project' }));
|
|
135
|
+
}
|
|
136
|
+
}
|
|
112
137
|
for (const name of Object.keys(keys).sort()) {
|
|
113
138
|
if (!KEY_NAME_PATTERN.test(name) || name === BUILTIN_KEY) continue;
|
|
114
139
|
const e = keys[name];
|
|
@@ -117,20 +142,23 @@ export function listKeys(env = process.env) {
|
|
|
117
142
|
return rows;
|
|
118
143
|
}
|
|
119
144
|
|
|
120
|
-
|
|
121
|
-
|
|
145
|
+
/** A key's row: in `scope` when given, else the project's first, then the global one. */
|
|
146
|
+
export function findKey(env, name, { scope, project = null } = {}) {
|
|
147
|
+
const rows = listKeys(env, { project }).filter((k) => k.name === name);
|
|
148
|
+
if (scope) return rows.find((k) => k.scope === scope) ?? null;
|
|
149
|
+
return rows.find((k) => k.scope === 'project') ?? rows.find((k) => k.scope === 'global') ?? null;
|
|
122
150
|
}
|
|
123
151
|
|
|
124
152
|
/**
|
|
125
153
|
* Registers a key (or updates its label and description); an existing value is
|
|
126
154
|
* kept. The built-in key is only reported.
|
|
127
155
|
*/
|
|
128
|
-
export function requestKey(env, { name, label, description }) {
|
|
156
|
+
export function requestKey(env, { name, label, description }, { scope = 'global', project = null } = {}) {
|
|
129
157
|
checkKeyName(name);
|
|
130
|
-
if (name === BUILTIN_KEY) return findKey(env, name);
|
|
158
|
+
if (name === BUILTIN_KEY) return findKey(env, name, { scope: 'global', project });
|
|
131
159
|
const l = cleanText(label, MAX_LABEL, 'label');
|
|
132
160
|
const d = cleanText(description, MAX_DESCRIPTION, 'description');
|
|
133
|
-
const store = load(env);
|
|
161
|
+
const store = load(env, scope, project);
|
|
134
162
|
const prev = store.keys[name] && typeof store.keys[name] === 'object' ? store.keys[name] : null;
|
|
135
163
|
const at = now();
|
|
136
164
|
store.keys[name] = {
|
|
@@ -141,13 +169,14 @@ export function requestKey(env, { name, label, description }) {
|
|
|
141
169
|
updatedAt: prev ? prev.updatedAt ?? at : at,
|
|
142
170
|
};
|
|
143
171
|
save(store);
|
|
144
|
-
return findKey(env, name);
|
|
172
|
+
return findKey(env, name, { scope, project });
|
|
145
173
|
}
|
|
146
174
|
|
|
147
|
-
export function setKeyValue(env, name, value) {
|
|
175
|
+
export function setKeyValue(env, name, value, { scope = 'global', project = null } = {}) {
|
|
148
176
|
checkKeyName(name);
|
|
149
177
|
const v = checkValue(value);
|
|
150
|
-
|
|
178
|
+
if (name === BUILTIN_KEY) scope = 'global';
|
|
179
|
+
const store = load(env, scope, project);
|
|
151
180
|
const at = now();
|
|
152
181
|
if (name === BUILTIN_KEY) {
|
|
153
182
|
if (/\s/.test(v)) throw new KeyStoreError('GENESIS_KEY_BAD_INPUT', 'the Genesis API key must not contain whitespace');
|
|
@@ -158,12 +187,13 @@ export function setKeyValue(env, name, value) {
|
|
|
158
187
|
store.keys[name] = { ...prev, value: v, updatedAt: at };
|
|
159
188
|
}
|
|
160
189
|
save(store);
|
|
161
|
-
return findKey(env, name);
|
|
190
|
+
return findKey(env, name, { scope, project });
|
|
162
191
|
}
|
|
163
192
|
|
|
164
|
-
export function clearKeyValue(env, name) {
|
|
193
|
+
export function clearKeyValue(env, name, { scope = 'global', project = null } = {}) {
|
|
165
194
|
checkKeyName(name);
|
|
166
|
-
|
|
195
|
+
if (name === BUILTIN_KEY) scope = 'global';
|
|
196
|
+
const store = load(env, scope, project);
|
|
167
197
|
if (name === BUILTIN_KEY) {
|
|
168
198
|
store.cfg = { ...store.cfg, apiKey: undefined, apiKeyUpdatedAt: undefined };
|
|
169
199
|
} else {
|
|
@@ -173,23 +203,27 @@ export function clearKeyValue(env, name) {
|
|
|
173
203
|
store.keys[name] = { ...rest, updatedAt: now() };
|
|
174
204
|
}
|
|
175
205
|
save(store);
|
|
176
|
-
return findKey(env, name);
|
|
206
|
+
return findKey(env, name, { scope, project });
|
|
177
207
|
}
|
|
178
208
|
|
|
179
|
-
export function deleteKey(env, name) {
|
|
209
|
+
export function deleteKey(env, name, { scope = 'global', project = null } = {}) {
|
|
180
210
|
checkKeyName(name);
|
|
181
211
|
if (name === BUILTIN_KEY) {
|
|
182
212
|
throw new KeyStoreError('GENESIS_KEY_BUILTIN', 'the Genesis API key cannot be deleted; clear its value instead');
|
|
183
213
|
}
|
|
184
|
-
const store = load(env);
|
|
214
|
+
const store = load(env, scope, project);
|
|
185
215
|
if (!(name in store.keys)) throw new KeyStoreError('GENESIS_KEY_NOT_FOUND', `no key named "${name}"`, 404);
|
|
186
216
|
delete store.keys[name];
|
|
187
217
|
save(store);
|
|
188
218
|
}
|
|
189
219
|
|
|
190
220
|
/** A stored value, for the code that uses the key. Never put it in a tool answer. */
|
|
191
|
-
export function keyValue(env, name) {
|
|
221
|
+
export function keyValue(env, name, { project = null } = {}) {
|
|
192
222
|
checkKeyName(name);
|
|
223
|
+
if (project && name !== BUILTIN_KEY) {
|
|
224
|
+
const p = load(env, 'project', project).keys[name];
|
|
225
|
+
if (p && typeof p === 'object' && typeof p.value === 'string' && p.value) return p.value;
|
|
226
|
+
}
|
|
193
227
|
const { cfg, keys } = load(env);
|
|
194
228
|
if (name === BUILTIN_KEY) {
|
|
195
229
|
const fromEnv = typeof env[API_KEY_ENV] === 'string' ? env[API_KEY_ENV].trim() : '';
|