@mindbricks/genesis-set 0.0.0-stage → 0.1.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 (41) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/LICENSE +202 -0
  3. package/README.md +147 -2
  4. package/bin/genesis-set.mjs +153 -0
  5. package/corpus/README.md +25 -0
  6. package/corpus/genesis/compile-results.md +246 -0
  7. package/corpus/genesis/compiler-api.md +265 -0
  8. package/corpus/genesis/custom-code.md +519 -0
  9. package/corpus/genesis/deploy.md +190 -0
  10. package/corpus/genesis/pitfalls.md +231 -0
  11. package/corpus/genesis/procedures/README.md +17 -0
  12. package/corpus/genesis/procedures/agent-hub-blueprint.md +13 -0
  13. package/corpus/genesis/procedures/auth-blueprint.md +14 -0
  14. package/corpus/genesis/procedures/bff-blueprint.md +16 -0
  15. package/corpus/genesis/procedures/blueprint-authoring.md +16 -0
  16. package/corpus/genesis/procedures/howto-mail-to-tasks.md +26 -0
  17. package/corpus/genesis/procedures/howto-payment-flow.md +112 -0
  18. package/corpus/genesis/procedures/howto-subscription.md +33 -0
  19. package/corpus/genesis/procedures/notifications-blueprint.md +13 -0
  20. package/corpus/genesis/procedures/patterns-catalog.md +12 -0
  21. package/corpus/genesis/procedures/project-lifecycle.md +27 -0
  22. package/corpus/genesis/run-locally.md +310 -0
  23. package/corpus/genesis/testing.md +532 -0
  24. package/lib/config-cli.mjs +179 -0
  25. package/lib/install.mjs +639 -0
  26. package/lib/mcp-config.mjs +220 -0
  27. package/lib/semver.mjs +94 -0
  28. package/mcp/blueprint.mjs +64 -0
  29. package/mcp/client.mjs +141 -0
  30. package/mcp/config.mjs +166 -0
  31. package/mcp/key-page-html.mjs +275 -0
  32. package/mcp/key-page.mjs +217 -0
  33. package/mcp/key-store.mjs +204 -0
  34. package/mcp/key-tools.mjs +225 -0
  35. package/mcp/server.mjs +164 -0
  36. package/mcp/tools.mjs +270 -0
  37. package/package.json +43 -4
  38. package/skills/genesis-compiler-api/SKILL.md +56 -0
  39. package/skills/genesis-deploy/SKILL.md +36 -0
  40. package/skills/genesis-generated-code/SKILL.md +48 -0
  41. package/skills/genesis-run-and-test/SKILL.md +43 -0
@@ -0,0 +1,275 @@
1
+ // The HTML of the local key page (#9352), served by ./key-page.mjs. One
2
+ // self-contained document: no external script, style, font or image (the
3
+ // page's Content-Security-Policy allows only its own nonce'd script and style
4
+ // and requests to itself). Every text from the store is set with textContent.
5
+ // A value is sent once when the user saves it and never comes back: the page
6
+ // shows set / empty and, for a long value, its last four characters.
7
+
8
+ const STYLE = `
9
+ :root {
10
+ --bg: #f6f7f9; --panel: #ffffff; --text: #16181d; --muted: #5c6370; --line: #e2e5ea;
11
+ --accent: #3b5bdb; --accent-text: #ffffff; --ok: #1f7a4d; --ok-bg: #e6f4ec; --warn: #8a5a00; --warn-bg: #fdf3dc;
12
+ --danger: #b42318; --field: #ffffff; --focus: rgba(59, 91, 219, .35);
13
+ }
14
+ @media (prefers-color-scheme: dark) {
15
+ :root {
16
+ --bg: #111317; --panel: #1a1d23; --text: #e7e9ee; --muted: #9aa1ad; --line: #2b2f37;
17
+ --accent: #7d97ff; --accent-text: #0d1020; --ok: #6fd3a0; --ok-bg: #16301f; --warn: #f0c060; --warn-bg: #33280f;
18
+ --danger: #ff8a7a; --field: #14161a; --focus: rgba(125, 151, 255, .35);
19
+ }
20
+ }
21
+ * { box-sizing: border-box; }
22
+ body { margin: 0; background: var(--bg); color: var(--text); font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
23
+ main { max-width: 760px; margin: 0 auto; padding: 32px 16px 64px; }
24
+ h1 { font-size: 22px; margin: 0 0 4px; }
25
+ .lead { color: var(--muted); margin: 0 0 24px; }
26
+ .card { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 18px 18px 16px; margin: 0 0 14px; }
27
+ .head { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
28
+ .head h2 { font-size: 16px; margin: 0; }
29
+ code { font: 12.5px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--muted); }
30
+ .badge { font-size: 12px; font-weight: 600; border-radius: 999px; padding: 1px 9px; margin-left: auto; }
31
+ .badge.set { color: var(--ok); background: var(--ok-bg); }
32
+ .badge.empty { color: var(--warn); background: var(--warn-bg); }
33
+ .desc { color: var(--muted); margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; }
34
+ .meta { color: var(--muted); font-size: 13px; margin: 6px 0 0; }
35
+ .row { display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap; }
36
+ .field { position: relative; flex: 1 1 220px; min-width: 0; display: flex; }
37
+ .field input { flex: 1 1 auto; padding-right: 64px; }
38
+ .field .peek { position: absolute; right: 4px; top: 50%; transform: translateY(-50%); padding: 3px 9px; font-size: 13px; font-weight: 600; border: none; background: transparent; color: var(--muted); }
39
+ .field .peek:hover { color: var(--text); }
40
+ input, textarea { flex: 1 1 220px; min-width: 0; font: inherit; color: var(--text); background: var(--field); border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; }
41
+ textarea { min-height: 64px; resize: vertical; }
42
+ input:focus, textarea:focus, button:focus-visible { outline: 3px solid var(--focus); outline-offset: 1px; }
43
+ button { font: inherit; font-weight: 600; border-radius: 8px; padding: 8px 14px; border: 1px solid var(--line); background: var(--panel); color: var(--text); cursor: pointer; }
44
+ button.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
45
+ button.danger { color: var(--danger); }
46
+ button:disabled { opacity: .55; cursor: default; }
47
+ .links { display: flex; gap: 14px; margin-top: 10px; }
48
+ .links button { background: none; border: none; padding: 0; color: var(--muted); font-weight: 500; text-decoration: underline; }
49
+ .links button.danger { color: var(--danger); }
50
+ .edit { display: none; margin-top: 10px; }
51
+ .edit.open { display: block; }
52
+ .edit .row { margin-top: 8px; }
53
+ .note { font-size: 13px; color: var(--warn); margin: 6px 0 0; }
54
+ .add h2 { font-size: 16px; margin: 0 0 4px; }
55
+ .add p { color: var(--muted); margin: 0; font-size: 14px; }
56
+ #flash { position: sticky; top: 0; z-index: 2; display: none; margin: 0 0 14px; padding: 10px 14px; border-radius: 8px; font-weight: 600; }
57
+ #flash.ok { display: block; color: var(--ok); background: var(--ok-bg); }
58
+ #flash.err { display: block; color: var(--danger); background: var(--panel); border: 1px solid var(--danger); }
59
+ footer { color: var(--muted); font-size: 13px; margin-top: 24px; }
60
+ .expired { text-align: center; padding-top: 80px; }
61
+ `;
62
+
63
+ const SCRIPT = `
64
+ (() => {
65
+ const qs = new URLSearchParams(location.search);
66
+ let token = qs.get('t');
67
+ try {
68
+ if (token) sessionStorage.setItem('genesis-key-token', token);
69
+ else token = sessionStorage.getItem('genesis-key-token');
70
+ } catch {}
71
+ if (qs.has('t')) history.replaceState(null, '', location.pathname);
72
+ const list = document.getElementById('keys');
73
+ const flash = document.getElementById('flash');
74
+
75
+ function say(text, kind) {
76
+ flash.textContent = text;
77
+ flash.className = kind;
78
+ clearTimeout(say.t);
79
+ say.t = setTimeout(() => { flash.className = ''; }, kind === 'err' ? 8000 : 3500);
80
+ }
81
+
82
+ async function api(method, path, body) {
83
+ const res = await fetch(path, {
84
+ method,
85
+ headers: { 'X-Genesis-Key-Token': token || '', ...(body ? { 'Content-Type': 'application/json' } : {}) },
86
+ body: body ? JSON.stringify(body) : undefined,
87
+ cache: 'no-store',
88
+ });
89
+ let data = {};
90
+ try { data = await res.json(); } catch {}
91
+ if (!res.ok) throw new Error((data.error && data.error.message) || ('the page answered ' + res.status));
92
+ return data;
93
+ }
94
+
95
+ function el(tag, cls, text) {
96
+ const e = document.createElement(tag);
97
+ if (cls) e.className = cls;
98
+ if (text !== undefined) e.textContent = text;
99
+ return e;
100
+ }
101
+
102
+ function when(iso) {
103
+ if (!iso) return '';
104
+ const d = new Date(iso);
105
+ return isNaN(d) ? '' : d.toLocaleString();
106
+ }
107
+
108
+ function card(k) {
109
+ const c = el('section', 'card');
110
+ const head = el('div', 'head');
111
+ head.append(el('h2', '', k.label), el('code', '', k.name), el('span', 'badge ' + k.status, k.status === 'set' ? 'Set' : 'Empty'));
112
+ c.append(head);
113
+ if (k.description) c.append(el('p', 'desc', k.description));
114
+ const meta = [];
115
+ if (k.tail) meta.push('ends with ' + k.tail);
116
+ if (k.status === 'set' && k.updatedAt) meta.push('saved ' + when(k.updatedAt));
117
+ if (meta.length) c.append(el('p', 'meta', meta.join(' · ')));
118
+ if (k.source) c.append(el('p', 'note', 'The environment variable ' + k.source + ' is set and wins over a value saved here.'));
119
+
120
+ const row = el('div', 'row');
121
+ const input = el('input');
122
+ input.type = 'password';
123
+ input.autocomplete = 'off';
124
+ input.spellcheck = false;
125
+ input.placeholder = k.status === 'set' ? 'Paste a new value to replace it' : 'Paste the value';
126
+ input.setAttribute('aria-label', 'Value of ' + k.label);
127
+ const save = el('button', 'primary', k.status === 'set' ? 'Replace' : 'Save');
128
+ save.type = 'button';
129
+ const doSave = async () => {
130
+ const v = input.value.trim();
131
+ if (!v) { say('Paste the value first.', 'err'); input.focus(); return; }
132
+ save.disabled = true;
133
+ try {
134
+ await api('PUT', '/api/keys/' + encodeURIComponent(k.name) + '/value', { value: v });
135
+ input.value = '';
136
+ input.type = 'password';
137
+ say(k.label + ' saved.', 'ok');
138
+ await load({ force: true });
139
+ } catch (e) { say(e.message, 'err'); } finally { save.disabled = false; }
140
+ };
141
+ save.addEventListener('click', doSave);
142
+ input.addEventListener('keydown', (ev) => { if (ev.key === 'Enter') doSave(); });
143
+ const peek = el('button', 'peek', 'Show');
144
+ peek.type = 'button';
145
+ peek.setAttribute('aria-pressed', 'false');
146
+ peek.setAttribute('aria-label', 'Show the value of ' + k.label);
147
+ peek.addEventListener('click', () => {
148
+ const show = input.type === 'password';
149
+ input.type = show ? 'text' : 'password';
150
+ peek.textContent = show ? 'Hide' : 'Show';
151
+ peek.setAttribute('aria-pressed', String(show));
152
+ peek.setAttribute('aria-label', (show ? 'Hide' : 'Show') + ' the value of ' + k.label);
153
+ input.focus();
154
+ });
155
+ const field = el('div', 'field');
156
+ field.append(input, peek);
157
+ row.append(field, save);
158
+ c.append(row);
159
+
160
+ const links = el('div', 'links');
161
+ if (k.status === 'set' && !k.source) {
162
+ const clear = el('button', '', 'Clear value');
163
+ clear.type = 'button';
164
+ clear.addEventListener('click', async () => {
165
+ if (!confirm('Clear the value of ' + k.label + '?')) return;
166
+ try { await api('DELETE', '/api/keys/' + encodeURIComponent(k.name) + '/value'); say(k.label + ' cleared.', 'ok'); await load({ force: true }); }
167
+ catch (e) { say(e.message, 'err'); }
168
+ });
169
+ links.append(clear);
170
+ }
171
+ if (!k.builtin) {
172
+ const edit = el('button', '', 'Edit details');
173
+ edit.type = 'button';
174
+ const box = el('div', 'edit');
175
+ const l = el('input'); l.value = k.label; l.setAttribute('aria-label', 'Label');
176
+ const d = el('textarea'); d.value = k.description; d.setAttribute('aria-label', 'Description');
177
+ const ok = el('button', 'primary', 'Save details'); ok.type = 'button';
178
+ ok.addEventListener('click', async () => {
179
+ try { await api('PATCH', '/api/keys/' + encodeURIComponent(k.name), { label: l.value, description: d.value }); say('Details saved.', 'ok'); await load({ force: true }); }
180
+ catch (e) { say(e.message, 'err'); }
181
+ });
182
+ const r1 = el('div', 'row'); r1.append(l);
183
+ const r2 = el('div', 'row'); r2.append(d);
184
+ const r3 = el('div', 'row'); r3.append(ok);
185
+ box.append(r1, r2, r3);
186
+ edit.addEventListener('click', () => box.classList.toggle('open'));
187
+ const del = el('button', 'danger', 'Delete key');
188
+ del.type = 'button';
189
+ del.addEventListener('click', async () => {
190
+ if (!confirm('Delete ' + k.label + ' and its value? The agent will have to ask for it again.')) return;
191
+ try { await api('DELETE', '/api/keys/' + encodeURIComponent(k.name)); say(k.label + ' deleted.', 'ok'); await load({ force: true }); }
192
+ catch (e) { say(e.message, 'err'); }
193
+ });
194
+ links.append(edit, del);
195
+ c.append(links, box);
196
+ } else if (links.childNodes.length) {
197
+ c.append(links);
198
+ }
199
+ return c;
200
+ }
201
+
202
+ // A refresh rebuilds the cards only when the keys changed, and never while the user is
203
+ // typing into one (a rebuild would drop what they typed).
204
+ let shown = '';
205
+ function typing() {
206
+ const a = document.activeElement;
207
+ if (a && list.contains(a) && (a.tagName === 'INPUT' || a.tagName === 'TEXTAREA')) return true;
208
+ return [...list.querySelectorAll('input, textarea')].some((e) => e.value && e.defaultValue !== e.value);
209
+ }
210
+
211
+ async function load({ force = false } = {}) {
212
+ try {
213
+ const { keys } = await api('GET', '/api/keys');
214
+ const sig = JSON.stringify(keys);
215
+ if (sig === shown && !force) return;
216
+ if (!force && shown && typing()) return;
217
+ shown = sig;
218
+ list.replaceChildren(...keys.map(card));
219
+ } catch (e) {
220
+ say(e.message, 'err');
221
+ }
222
+ }
223
+
224
+ const form = document.getElementById('add');
225
+ form.addEventListener('submit', async (ev) => {
226
+ ev.preventDefault();
227
+ const f = new FormData(form);
228
+ try {
229
+ await api('POST', '/api/keys', { name: String(f.get('name') || '').trim(), label: String(f.get('label') || ''), description: String(f.get('description') || '') });
230
+ form.reset();
231
+ say('Key added. Paste its value in the card above.', 'ok');
232
+ await load({ force: true });
233
+ } catch (e) { say(e.message, 'err'); }
234
+ });
235
+
236
+ window.addEventListener('focus', load);
237
+ load();
238
+ })();
239
+ `;
240
+
241
+ /** The key page, or its "link expired" page. `nonce` is the request's CSP nonce. */
242
+ export function renderKeyPage({ nonce, idleMinutes = 15, expired = false }) {
243
+ const head =
244
+ '<!doctype html><html lang="en"><head><meta charset="utf-8">' +
245
+ '<meta name="viewport" content="width=device-width, initial-scale=1">' +
246
+ '<meta name="referrer" content="no-referrer">' +
247
+ '<title>Genesis keys</title>' +
248
+ `<style nonce="${nonce}">${STYLE}</style></head>`;
249
+ if (expired) {
250
+ return (
251
+ head +
252
+ '<body><main class="expired"><h1>This link has expired</h1>' +
253
+ '<p class="lead">The key page closes when it is idle or when the agent session ends. Run <code>genesis-set keys</code> in a terminal for a new one, or ask the agent.</p>' +
254
+ '</main></body></html>'
255
+ );
256
+ }
257
+ return (
258
+ head +
259
+ '<body><main>' +
260
+ '<h1>Genesis keys</h1>' +
261
+ '<p class="lead">Keys your coding agent needs, stored on this machine only (~/.genesis-set/config.json, readable only by you). ' +
262
+ 'Paste a value here, never in the chat. The agent sees whether a key is set, not its value.</p>' +
263
+ '<div id="flash" role="status" aria-live="polite"></div>' +
264
+ '<div id="keys"></div>' +
265
+ '<section class="card add"><h2>Add a key</h2><p>The agent usually adds the keys it needs; you can add one yourself.</p>' +
266
+ '<form id="add" autocomplete="off">' +
267
+ '<div class="row"><input name="name" required pattern="[a-z][a-z0-9-]{1,63}" placeholder="name, e.g. stripe-secret-key" aria-label="Name">' +
268
+ '<input name="label" placeholder="Label, e.g. Stripe secret key" aria-label="Label"></div>' +
269
+ '<div class="row"><textarea name="description" placeholder="What it is for and where to get it" aria-label="Description"></textarea></div>' +
270
+ '<div class="row"><button class="primary" type="submit">Add key</button></div>' +
271
+ '</form></section>' +
272
+ `<footer>This page runs on 127.0.0.1 inside genesis-set and closes after ${idleMinutes} idle minutes. Open it again any time with <code>genesis-set keys</code> in a terminal.</footer>` +
273
+ `</main><script nonce="${nonce}">${SCRIPT}</script></body></html>`
274
+ );
275
+ }
@@ -0,0 +1,217 @@
1
+ // The local key manager page (#9352): a small HTTP server inside the MCP
2
+ // server process where the user enters, changes and deletes the keys of the
3
+ // genesis-set key store. The agent never sees a value; it only hands the user
4
+ // the page's link.
5
+ //
6
+ // - Bound to 127.0.0.1 on a random port; nothing else can reach it.
7
+ // - Every request carries the page's random token (the `t` query of the link,
8
+ // then the X-Genesis-Key-Token header); the token dies with the page.
9
+ // - The Host header must be this page's own address (DNS rebinding), and every
10
+ // write must come from the page itself (Origin) with a JSON body (CSRF).
11
+ // - The page closes after IDLE_MS without a request, and when the MCP server
12
+ // ends; the next key tool call opens a new one with a new link.
13
+
14
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
15
+ import http from 'node:http';
16
+
17
+ import { KeyStoreError, clearKeyValue, deleteKey, listKeys, requestKey, setKeyValue } from './key-store.mjs';
18
+ import { renderKeyPage } from './key-page-html.mjs';
19
+
20
+ export const IDLE_MS = 15 * 60 * 1000;
21
+ const MAX_BODY = 32 * 1024;
22
+ const TOKEN_HEADER = 'x-genesis-key-token';
23
+
24
+ let current = null; // { server, port, token, timer, env, idleMs, closed, resolveClosed }
25
+
26
+ function sameToken(a, b) {
27
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
28
+ const x = Buffer.from(a);
29
+ const y = Buffer.from(b);
30
+ return x.length === y.length && timingSafeEqual(x, y);
31
+ }
32
+
33
+ function securityHeaders(res, nonce) {
34
+ res.setHeader('Cache-Control', 'no-store');
35
+ res.setHeader('Referrer-Policy', 'no-referrer');
36
+ res.setHeader('X-Content-Type-Options', 'nosniff');
37
+ res.setHeader('X-Frame-Options', 'DENY');
38
+ res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
39
+ res.setHeader(
40
+ 'Content-Security-Policy',
41
+ `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; ` +
42
+ "img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",
43
+ );
44
+ }
45
+
46
+ function sendJson(res, status, body) {
47
+ res.statusCode = status;
48
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
49
+ res.end(JSON.stringify(body));
50
+ }
51
+
52
+ function sendError(res, status, code, message) {
53
+ sendJson(res, status, { error: { code, message } });
54
+ }
55
+
56
+ function readJson(req) {
57
+ return new Promise((resolve, reject) => {
58
+ let size = 0;
59
+ const chunks = [];
60
+ req.on('data', (c) => {
61
+ size += c.length;
62
+ if (size > MAX_BODY) {
63
+ reject(new KeyStoreError('GENESIS_KEY_BAD_INPUT', 'the request body is too large', 413));
64
+ req.destroy();
65
+ return;
66
+ }
67
+ chunks.push(c);
68
+ });
69
+ req.on('end', () => {
70
+ const text = Buffer.concat(chunks).toString('utf8');
71
+ if (!text) return resolve({});
72
+ try {
73
+ const v = JSON.parse(text);
74
+ resolve(v && typeof v === 'object' && !Array.isArray(v) ? v : {});
75
+ } catch {
76
+ reject(new KeyStoreError('GENESIS_KEY_BAD_INPUT', 'the request body is not JSON'));
77
+ }
78
+ });
79
+ req.on('error', reject);
80
+ });
81
+ }
82
+
83
+ /** The page's own addresses: what Host and Origin may say. */
84
+ function ownHosts(port) {
85
+ return new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
86
+ }
87
+
88
+ async function handle(page, req, res) {
89
+ const nonce = randomBytes(16).toString('base64');
90
+ securityHeaders(res, nonce);
91
+ const hosts = ownHosts(page.port);
92
+ if (!hosts.has(String(req.headers.host ?? '').toLowerCase())) {
93
+ sendError(res, 421, 'GENESIS_KEY_PAGE_HOST', 'this page answers only on its own local address');
94
+ return;
95
+ }
96
+ const url = new URL(req.url ?? '/', `http://127.0.0.1:${page.port}`);
97
+ const isPage = req.method === 'GET' && url.pathname === '/';
98
+ const token = isPage ? url.searchParams.get('t') : req.headers[TOKEN_HEADER];
99
+ if (!sameToken(token, page.token)) {
100
+ if (isPage) {
101
+ res.statusCode = 403;
102
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
103
+ res.end(renderKeyPage({ nonce, expired: true }));
104
+ return;
105
+ }
106
+ sendError(res, 403, 'GENESIS_KEY_PAGE_TOKEN', 'the page link has expired; ask the agent for a new one');
107
+ return;
108
+ }
109
+ touch(page);
110
+ if (isPage) {
111
+ res.statusCode = 200;
112
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
113
+ res.end(renderKeyPage({ nonce, idleMinutes: Math.round(page.idleMs / 60000) }));
114
+ return;
115
+ }
116
+ if (req.method !== 'GET') {
117
+ const origin = String(req.headers.origin ?? '').toLowerCase();
118
+ if (!origin || !hosts.has(origin.replace(/^http:\/\//, ''))) {
119
+ sendError(res, 403, 'GENESIS_KEY_PAGE_ORIGIN', 'writes are accepted only from the key page itself');
120
+ return;
121
+ }
122
+ if (req.method !== 'DELETE' && !String(req.headers['content-type'] ?? '').toLowerCase().startsWith('application/json')) {
123
+ sendError(res, 415, 'GENESIS_KEY_BAD_INPUT', 'send JSON');
124
+ return;
125
+ }
126
+ }
127
+ const parts = url.pathname.split('/').filter(Boolean).map(decodeURIComponent);
128
+ try {
129
+ if (parts[0] !== 'api' || parts[1] !== 'keys') return sendError(res, 404, 'GENESIS_KEY_PAGE_NOT_FOUND', 'no such page');
130
+ const [, , name, sub] = parts;
131
+ if (req.method === 'GET' && !name) return sendJson(res, 200, { keys: listKeys(page.env) });
132
+ if (req.method === 'POST' && !name) {
133
+ const b = await readJson(req);
134
+ return sendJson(res, 200, { key: requestKey(page.env, { name: b.name, label: b.label, description: b.description }) });
135
+ }
136
+ if (name && sub === 'value' && req.method === 'PUT') {
137
+ const b = await readJson(req);
138
+ return sendJson(res, 200, { key: setKeyValue(page.env, name, b.value) });
139
+ }
140
+ if (name && sub === 'value' && req.method === 'DELETE') return sendJson(res, 200, { key: clearKeyValue(page.env, name) });
141
+ if (name && !sub && req.method === 'DELETE') {
142
+ deleteKey(page.env, name);
143
+ return sendJson(res, 200, { deleted: name });
144
+ }
145
+ if (name && !sub && req.method === 'PATCH') {
146
+ const b = await readJson(req);
147
+ return sendJson(res, 200, { key: requestKey(page.env, { name, label: b.label, description: b.description }) });
148
+ }
149
+ return sendError(res, 405, 'GENESIS_KEY_PAGE_METHOD', 'not supported');
150
+ } catch (err) {
151
+ if (err instanceof KeyStoreError) return sendError(res, err.status, err.code, err.message);
152
+ return sendError(res, 500, 'GENESIS_KEY_PAGE_ERROR', 'the key page could not complete the request');
153
+ }
154
+ }
155
+
156
+ function touch(page) {
157
+ clearTimeout(page.timer);
158
+ page.timer = setTimeout(() => closeKeyPage(), page.idleMs);
159
+ page.timer.unref?.();
160
+ }
161
+
162
+ /**
163
+ * The running page, or a new one. Answers `{ url, port, expiresAfterIdleMinutes }`.
164
+ * `env` is the environment the store resolves its file from (tests).
165
+ */
166
+ export async function ensureKeyPage({ env = process.env, idleMs = IDLE_MS } = {}) {
167
+ if (current && current.server.listening && current.env === env) {
168
+ touch(current);
169
+ return linkOf(current);
170
+ }
171
+ if (current) await closeKeyPage();
172
+ const page = { token: randomBytes(24).toString('base64url'), env, idleMs, port: 0, timer: null, server: null };
173
+ page.closed = new Promise((r) => {
174
+ page.resolveClosed = r;
175
+ });
176
+ page.server = http.createServer((req, res) => {
177
+ handle(page, req, res).catch(() => {
178
+ if (!res.headersSent) sendError(res, 500, 'GENESIS_KEY_PAGE_ERROR', 'the key page could not complete the request');
179
+ });
180
+ });
181
+ page.server.keepAliveTimeout = 1000;
182
+ await new Promise((resolve, reject) => {
183
+ page.server.once('error', reject);
184
+ page.server.listen(0, '127.0.0.1', resolve);
185
+ });
186
+ page.server.unref();
187
+ page.port = page.server.address().port;
188
+ current = page;
189
+ touch(page);
190
+ return linkOf(page);
191
+ }
192
+
193
+ function linkOf(page) {
194
+ return {
195
+ url: `http://127.0.0.1:${page.port}/?t=${page.token}`,
196
+ port: page.port,
197
+ expiresAfterIdleMinutes: Math.round(page.idleMs / 60000),
198
+ };
199
+ }
200
+
201
+ /** Closes the page; its link stops working. */
202
+ export async function closeKeyPage() {
203
+ const page = current;
204
+ current = null;
205
+ if (!page) return;
206
+ clearTimeout(page.timer);
207
+ await new Promise((resolve) => {
208
+ page.server.close(() => resolve());
209
+ page.server.closeAllConnections?.();
210
+ });
211
+ page.resolveClosed();
212
+ }
213
+
214
+ /** Resolves when the running page closes (idle, or closeKeyPage); at once when none runs. */
215
+ export function keyPageClosed() {
216
+ return current ? current.closed : Promise.resolve();
217
+ }