@mindbricks/genesis-set 0.3.0 → 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 +19 -0
- package/README.md +39 -2
- package/bin/genesis-set.mjs +41 -0
- package/lib/init.mjs +25 -2
- package/lib/install.mjs +3 -0
- 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.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() : '';
|
package/mcp/key-tools.mjs
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
// genesis_listKeys every key: name, label, description, set / empty
|
|
8
8
|
// genesis_openKeyManager the page link, to manage every key
|
|
9
9
|
// genesis_writeKeyToEnvFile copy a stored value into a gitignored env file
|
|
10
|
+
// genesis_openBoard the project board (flow, documents, blueprint, keys)
|
|
10
11
|
//
|
|
11
12
|
// They work without a Genesis API key: the first one is how the user sets it.
|
|
12
13
|
|
|
@@ -15,13 +16,22 @@ import fs from 'node:fs';
|
|
|
15
16
|
import path from 'node:path';
|
|
16
17
|
|
|
17
18
|
import { genesisError } from './client.mjs';
|
|
19
|
+
import { ensureBoard } from './board.mjs';
|
|
18
20
|
import { ensureKeyPage } from './key-page.mjs';
|
|
19
|
-
import { BUILTIN_KEY, KeyStoreError, checkKeyName, findKey, keyValue, listKeys, requestKey } from './key-store.mjs';
|
|
21
|
+
import { BUILTIN_KEY, KeyStoreError, SCOPES, checkKeyName, findKey, keyValue, listKeys, requestKey } from './key-store.mjs';
|
|
22
|
+
import { findProject } from './project.mjs';
|
|
20
23
|
|
|
21
24
|
const KEY_NAME = {
|
|
22
25
|
type: 'string',
|
|
23
26
|
description: `The key's name: lowercase kebab-case, for example "stripe-secret-key". "${BUILTIN_KEY}" is the Genesis API key itself.`,
|
|
24
27
|
};
|
|
28
|
+
const SCOPE = {
|
|
29
|
+
type: 'string',
|
|
30
|
+
enum: SCOPES,
|
|
31
|
+
description:
|
|
32
|
+
'Where the key is stored: "project" (this genesis project only; the default inside a project, see genesis init) or "global" (every project of this user). ' +
|
|
33
|
+
'Both live in the user\'s home, never in the project folder.',
|
|
34
|
+
};
|
|
25
35
|
const OPEN = {
|
|
26
36
|
type: 'boolean',
|
|
27
37
|
description: "Also open the page in the user's default browser on this machine (default false). Only when the user agreed.",
|
|
@@ -44,6 +54,7 @@ export const KEY_TOOLS = [
|
|
|
44
54
|
type: 'string',
|
|
45
55
|
description: 'What the key is for and where the user gets it, shown on the page (for example "Stripe dashboard, Developers > API keys; a test-mode key starting sk_test_").',
|
|
46
56
|
},
|
|
57
|
+
scope: SCOPE,
|
|
47
58
|
open: OPEN,
|
|
48
59
|
},
|
|
49
60
|
required: ['name', 'label'],
|
|
@@ -54,7 +65,7 @@ export const KEY_TOOLS = [
|
|
|
54
65
|
{
|
|
55
66
|
name: 'genesis_listKeys',
|
|
56
67
|
title: 'List the keys of the local key store',
|
|
57
|
-
description: 'Every key
|
|
68
|
+
description: 'Every key this folder can use: the project\'s keys (inside a genesis project) and the global ones, each with its scope, label, description and status (set or empty). Values are never answered.',
|
|
58
69
|
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
59
70
|
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
60
71
|
},
|
|
@@ -77,12 +88,23 @@ export const KEY_TOOLS = [
|
|
|
77
88
|
name: KEY_NAME,
|
|
78
89
|
file: { type: 'string', description: 'The env file (absolute, or relative to the folder the agent was started in).' },
|
|
79
90
|
variable: { type: 'string', description: 'The variable name in the file, for example STRIPE_SECRET_KEY.' },
|
|
91
|
+
scope: { ...SCOPE, description: 'Read the key from this scope only. Default: the project\'s key when there is one, else the global key.' },
|
|
80
92
|
},
|
|
81
93
|
required: ['name', 'file', 'variable'],
|
|
82
94
|
additionalProperties: false,
|
|
83
95
|
},
|
|
84
96
|
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
85
97
|
},
|
|
98
|
+
{
|
|
99
|
+
name: 'genesis_openBoard',
|
|
100
|
+
title: 'Open the project board',
|
|
101
|
+
description:
|
|
102
|
+
'The link of the local project board for the genesis project of this folder: the design flow with the state and check of every document, the documents themselves, ' +
|
|
103
|
+
'the interview, the blueprint with its validation, and the project and global keys. Offer it when a design document is written or the user asks where to follow the work; ' +
|
|
104
|
+
'the user can also open it any time with "genesis board" in the project folder. Works on this machine only.',
|
|
105
|
+
inputSchema: { type: 'object', properties: { open: OPEN }, additionalProperties: false },
|
|
106
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
107
|
+
},
|
|
86
108
|
];
|
|
87
109
|
|
|
88
110
|
const KEY_TOOL_NAMES = new Set(KEY_TOOLS.map((t) => t.name));
|
|
@@ -177,40 +199,65 @@ async function pageLink(settings, open) {
|
|
|
177
199
|
return { ...link, opened };
|
|
178
200
|
}
|
|
179
201
|
|
|
202
|
+
/** The project board's links (the write link opens the Keys tab when `tab` says so). */
|
|
203
|
+
async function boardLink(settings, project, { open, tab } = {}) {
|
|
204
|
+
const b = await ensureBoard({ env: settings.env ?? process.env, project });
|
|
205
|
+
const hash = tab ? `#${tab}` : '';
|
|
206
|
+
const url = `${b.url}${hash}`;
|
|
207
|
+
const opened = open === true ? openInBrowser(url) : false;
|
|
208
|
+
return { url, readUrl: `${b.readUrl}${hash}`, port: b.port, opened, reopen: 'genesis board (in the project folder)' };
|
|
209
|
+
}
|
|
210
|
+
|
|
180
211
|
const HANDLERS = {
|
|
181
212
|
async genesis_requestKey(args, settings) {
|
|
182
213
|
const env = settings.env ?? process.env;
|
|
183
|
-
const
|
|
184
|
-
const
|
|
214
|
+
const project = findProject(settings.cwd ?? process.cwd());
|
|
215
|
+
const scope = args.name === BUILTIN_KEY ? 'global' : args.scope ?? (project ? 'project' : 'global');
|
|
216
|
+
const key = forAgent(requestKey(env, { name: args.name, label: args.label, description: args.description }, { scope, project }));
|
|
217
|
+
// Inside a project the keys are on the board (project and global); outside, on the global key page.
|
|
218
|
+
const link = project ? await boardLink(settings, project, { open: args.open, tab: 'keys' }) : await pageLink(settings, args.open);
|
|
185
219
|
return {
|
|
186
220
|
key,
|
|
221
|
+
...(project ? { project: { name: project.name, root: project.root } } : {}),
|
|
187
222
|
keyPage: link,
|
|
188
223
|
next:
|
|
189
224
|
key.status === 'set'
|
|
190
225
|
? `"${key.label}" is already set. Use it; the user can change it on the key page.`
|
|
191
226
|
: `Ask the user to open ${link.url} on this machine and save "${key.label}" there, then call genesis_listKeys to see it set. ` +
|
|
192
|
-
|
|
227
|
+
`Never ask for the value in the chat. Later the user can open it themselves with ${project ? '"genesis board" in the project folder' : '"genesis keys"'} in a terminal.`,
|
|
193
228
|
};
|
|
194
229
|
},
|
|
195
230
|
async genesis_listKeys(_args, settings) {
|
|
196
|
-
|
|
231
|
+
const project = findProject(settings.cwd ?? process.cwd());
|
|
232
|
+
return {
|
|
233
|
+
...(project ? { project: { name: project.name, root: project.root } } : { project: null }),
|
|
234
|
+
keys: listKeys(settings.env ?? process.env, { project }).map(forAgent),
|
|
235
|
+
};
|
|
197
236
|
},
|
|
198
237
|
async genesis_openKeyManager(args, settings) {
|
|
199
238
|
return { keyPage: await pageLink(settings, args.open) };
|
|
200
239
|
},
|
|
240
|
+
async genesis_openBoard(args, settings) {
|
|
241
|
+
const project = findProject(settings.cwd ?? process.cwd());
|
|
242
|
+
if (!project) {
|
|
243
|
+
throw new KeyStoreError('GENESIS_KEY_NO_PROJECT', 'this folder is not a genesis project; run "genesis init" in the project folder first', 409);
|
|
244
|
+
}
|
|
245
|
+
return { project: { name: project.name, root: project.root }, board: await boardLink(settings, project, { open: args.open }) };
|
|
246
|
+
},
|
|
201
247
|
async genesis_writeKeyToEnvFile(args, settings) {
|
|
202
248
|
const env = settings.env ?? process.env;
|
|
203
249
|
checkKeyName(args.name);
|
|
204
250
|
if (!VARIABLE.test(args.variable)) throw new KeyStoreError('GENESIS_KEY_BAD_INPUT', `"${args.variable}" is not an env variable name`);
|
|
205
|
-
const
|
|
206
|
-
|
|
207
|
-
|
|
251
|
+
const project = findProject(settings.cwd ?? process.cwd());
|
|
252
|
+
const row = findKey(env, args.name, { scope: args.scope, project });
|
|
253
|
+
if (!row) throw new KeyStoreError('GENESIS_KEY_NOT_FOUND', `no key named "${args.name}"${args.scope ? ` in the ${args.scope} scope` : ''}; register it with genesis_requestKey`, 404);
|
|
254
|
+
const value = args.scope === 'global' ? keyValue(env, args.name) : keyValue(env, args.name, { project: row.scope === 'project' ? project : null });
|
|
208
255
|
if (!value) throw new KeyStoreError('GENESIS_KEY_NOT_SET', `"${row.label}" has no value yet; ask the user to save it on the key page (genesis_openKeyManager)`, 409);
|
|
209
256
|
const file = path.resolve(settings.cwd ?? process.cwd(), args.file);
|
|
210
257
|
const refusal = envFileRefusal(file);
|
|
211
258
|
if (refusal) throw new KeyStoreError('GENESIS_ENV_FILE_REFUSED', refusal, 422);
|
|
212
259
|
const { created, replaced } = writeEnvVariable(file, args.variable, value);
|
|
213
|
-
return { written: true, key: args.name, file, variable: args.variable, created, replaced };
|
|
260
|
+
return { written: true, key: args.name, scope: row.scope, file, variable: args.variable, created, replaced };
|
|
214
261
|
},
|
|
215
262
|
};
|
|
216
263
|
|