clavarium 0.2.164-beta.1 → 0.2.165-beta.1

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/deploy/install.sh CHANGED
@@ -553,9 +553,10 @@ skip_provider_button = true
553
553
  approval_prompt = "auto"
554
554
  http_address = "127.0.0.1:4180"
555
555
  upstreams = ["http://127.0.0.1:$PORT/"]
556
- # A paired device does not sign in: its own door (/c/) checks its key. The
556
+ # A paired device does not sign in: its own door (/c/) checks its key; nor
557
+ # does a program with an API key (/api/ext/, server/apikeys.mjs). The
557
558
  # identity headers are stripped there, so nobody can claim to be an operator.
558
- skip_auth_routes = ["^/c/"]
559
+ skip_auth_routes = ["^/c/", "^/api/ext/"]
559
560
  skip_auth_strip_headers = true
560
561
  # Two sign-ins at once (two tabs, a reload during it) each have their own CSRF
561
562
  # cookie; and there is time to type a password (deploy/updater.mjs, PROXY_LINES).
@@ -101,14 +101,33 @@ export const DROP_IN_TEXT = '# Written by the Clavarium updater: a crash loop ne
101
101
  during it, the installed app and the browser) shared one CSRF cookie, and the first to come back
102
102
  was refused ("Unable to find a valid CSRF token", found 20-10). One cookie per sign-in, and time
103
103
  to type a password. Added to a file that lacks them, the proxy restarted; nothing else touched. */
104
+ /* THE DOOR FOR PROGRAMS (server/apikeys.mjs, API keys): /api/ext/ goes through without sign-on, as the
105
+ devices' /c/ does -- the key in each call is the right, and the server never looks at an identity
106
+ there (the proxy strips those headers on these routes). Added to the one-line list of routes the
107
+ proxy skips, beside "^/c/"; a file with no such line, or a list over several lines, is left as it is. */
108
+ export const EXT_ROUTE = '^/api/ext/';
109
+ const EXT_COMMENT = '# /api/ext/: programs with an API key; the server checks the key (added by the Clavarium updater).';
110
+ export function withExtRoute(text) {
111
+ const lines = text.split('\n');
112
+ const i = lines.findIndex((l) => /^\s*skip_auth_routes\s*=/.test(l));
113
+ if (i < 0 || lines[i].includes(`"${EXT_ROUTE}"`)) return text;
114
+ const m = /^(\s*skip_auth_routes\s*=\s*\[)([^\]]*)\](\s*(#.*)?)$/.exec(lines[i]);
115
+ if (!m) return text;
116
+ const inner = m[2].trim().replace(/,\s*$/, '');
117
+ lines[i] = `${m[1]}${inner ? `${inner}, ` : ''}"${EXT_ROUTE}"]${m[3]}`;
118
+ if (lines[i - 1] !== EXT_COMMENT) lines.splice(i, 0, EXT_COMMENT);
119
+ return lines.join('\n');
120
+ }
104
121
  export const PROXY_CFG = '/etc/oauth2-proxy/oauth2-proxy.cfg';
105
122
  export const PROXY_LINES = ['cookie_csrf_per_request = true', 'cookie_csrf_expire = "30m"'];
106
123
  export async function ensureProxySettings({ file = PROXY_CFG, run = runCommand } = {}) {
107
124
  let text;
108
125
  try { text = readFileSync(file, 'utf8'); } catch { return false; }
109
126
  const missing = PROXY_LINES.filter((l) => !text.split('\n').some((x) => x.trim().startsWith(l.split(' =')[0])));
110
- if (!missing.length) return false;
111
- writeFileSync(`${file}.new`, `${text.replace(/\n*$/, '\n')}# Added by the Clavarium updater: one CSRF cookie per sign-in.\n${missing.join('\n')}\n`, { mode: 0o600 });
127
+ let next = withExtRoute(text);
128
+ if (missing.length) next = `${next.replace(/\n*$/, '\n')}# Added by the Clavarium updater: one CSRF cookie per sign-in.\n${missing.join('\n')}\n`;
129
+ if (next === text) return false;
130
+ writeFileSync(`${file}.new`, next, { mode: 0o600 });
112
131
  renameSync(`${file}.new`, file);
113
132
  if (process.getuid?.() === 0) await run(['systemctl', 'try-restart', 'oauth2-proxy.service'], { timeoutMs: 60_000 });
114
133
  return true;
@@ -961,7 +980,7 @@ async function main(argv) {
961
980
  try { if (await u.ensureDropIn()) console.error('updater: the drop-in of the server\'s unit written'); } catch (error) { console.error(`updater: the drop-in could not be written: ${error.message}`); }
962
981
  try { if (await ensureFfmpeg()) console.error('updater: ffmpeg installed, for the sounds the voice boxes play'); } catch (error) { console.error(`updater: ffmpeg could not be installed: ${error.message}`); }
963
982
  try { if (await ensureQuietSudo()) console.error('updater: sudo no longer logs the host program\'s probes'); } catch (error) { console.error(`updater: sudo could not be made quiet: ${error.message}`); }
964
- try { if (await ensureProxySettings()) console.error('updater: the sign-in proxy takes one CSRF cookie per sign-in'); } catch (error) { console.error(`updater: the sign-in proxy could not be set: ${error.message}`); }
983
+ try { if (await ensureProxySettings()) console.error('updater: the sign-in proxy set (one CSRF cookie per sign-in; /api/ext/ for API keys)'); } catch (error) { console.error(`updater: the sign-in proxy could not be set: ${error.message}`); }
965
984
  try { const c = await ensureGenericClientId({ run: runCommand }); if (c.changed.length) console.error('updater: the sign-in client id was made generic (nothing names the product in the open)'); } catch (error) { console.error(`updater: the sign-in client id could not be made generic: ${error.message}`); }
966
985
  try { if (await ensureTunnel({ run: runCommand })) console.error('updater: the tunnel to the relay notices a cut sooner'); } catch (error) { console.error(`updater: the tunnel could not be set: ${error.message}`); }
967
986
  /* What became of the relay is kept beside the state, for Settings (server/updates.mjs: relay). */
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.164-beta.1",
3
+ "version": "0.2.165-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.164-beta.1",
9
+ "version": "0.2.165-beta.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.164-beta.1",
3
+ "version": "0.2.165-beta.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
@@ -0,0 +1,351 @@
1
+ /* API KEYS: what a program elsewhere (an assistant, an automation) may ask of
2
+ * this Clavarium, and the door it asks through.
3
+ *
4
+ * A key is a named USE ("home automation", "steering AI"), global to this
5
+ * Clavarium, never tied to a person. It is a third kind of subject in the one
6
+ * table of rights (grants.mjs, "apikey:<id>"): what it may do is lines of
7
+ * that table, and a new key has none. Step 1 has one scope:
8
+ *
9
+ * status read the state: the server's memory, disk and CPU, the
10
+ * conversations (their free name and state, never what they
11
+ * say), the versions server:status r
12
+ *
13
+ * THE SECRET IS SHOWN ONCE. It is made here (32 random bytes, "clv_" before
14
+ * them), given back by `create` and never again: only its sha256 is kept, as
15
+ * a pairing's session is (devices.mjs). A 256-bit random secret needs no salt
16
+ * nor slow hash: nobody guesses it, and a copy of the store opens nothing.
17
+ * Compared in constant time, with every key looked at.
18
+ *
19
+ * REVOKED IS AT ONCE: the record and its lines of rights go; the next call is
20
+ * refused. EXPIRED is refused the same way (90 days unless chosen otherwise).
21
+ *
22
+ * EVERY USE IS JOURNALED: the key's id, the route, the answer, the time --
23
+ * never the secret, nor anything of it. Its own file, one JSON line each,
24
+ * cut to its newest half past JOURNAL_MAX. Each key is limited to
25
+ * RATE_PER_MIN calls a minute; calls with a key nobody has are limited too,
26
+ * all together, so that they cannot flood the journal.
27
+ *
28
+ * Who manages keys: whoever passes the gate (an administrator), from
29
+ * Settings, Access. A device (/c/) never reaches these routes; a key never
30
+ * makes a key.
31
+ *
32
+ * GET /api/apikeys {keys, scopes, defaultDays}
33
+ * POST /api/apikeys {label, scopes, days|null} -> {key, secret}: the secret this once
34
+ * POST /api/apikeys/<id>/revoke
35
+ * GET /api/apikeys/<id>/journal its last uses
36
+ *
37
+ * GET /api/ext/v1/status Authorization: Bearer clv_... the state, as JSON
38
+ * POST /api/ext/mcp the same, as one MCP tool (clavarium_status), JSON-RPC over HTTP
39
+ *
40
+ * The front lets /api/ext/ through without sign-on, as it does /c/
41
+ * (deploy/install.sh, skip_auth_routes; deploy/updater.mjs for installs made
42
+ * before), and strips the identity headers there: nothing under /api/ext/
43
+ * ever looks at who the operator is, only at the key.
44
+ */
45
+ import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
46
+ import { appendFileSync, readFileSync, writeFileSync, renameSync, statSync } from 'node:fs';
47
+ import { Refusal } from './conversations.mjs';
48
+ import { Grants, apiKeySubject } from './grants.mjs';
49
+
50
+ export const KEY_PREFIX = 'clv_';
51
+ export const DEFAULT_DAYS = 90;
52
+ export const DAYS_MAX = 3650;
53
+ export const KEYS_MAX = 50;
54
+ export const LABEL_MAX = 40;
55
+ export const RATE_PER_MIN = 60;
56
+ /* All calls with a key nobody has, together. */
57
+ export const UNKNOWN_PER_MIN = 60;
58
+ const JOURNAL_MAX = 1024 * 1024;
59
+ const JOURNAL_SHOWN = 200;
60
+ /* The time a key was last used is written at most this often (it is known at once in memory). */
61
+ const USED_SAVE_MS = 60_000;
62
+ export const EXT_PREFIX = '/api/ext/';
63
+
64
+ /* The scopes a key may be given: [asset, rights] in the table. */
65
+ export const SCOPES = Object.freeze({ status: { asset: 'server:status', rights: 'r', label: 'Status (read)' } });
66
+
67
+ const digest = (text) => createHash('sha256').update(text).digest();
68
+ const oneLine = (value) => typeof value === 'string' && value.trim() !== '' && value.trim().length <= LABEL_MAX
69
+ && ![...value].some((c) => { const p = c.codePointAt(0); return p < 0x20 || (p >= 0x7f && p < 0xa0) || (p >= 0x200b && p <= 0x200f) || (p >= 0x202a && p <= 0x202e); });
70
+ const SECRET = /^clv_[A-Za-z0-9_-]{43}$/;
71
+
72
+ export class ApiKeys {
73
+ #store; #grants; #now; #journal;
74
+ #used = new Map(); /* id -> { at, savedAt } */
75
+ #calls = new Map(); /* id ('' for unknown keys) -> [times of the last minute] */
76
+
77
+ constructor({ store, grants = new Grants(), journal = null, now = () => Date.now() }) {
78
+ this.#store = store; this.#grants = grants; this.#journal = journal; this.#now = now;
79
+ }
80
+
81
+ #scopesOf(id) { return Object.entries(SCOPES).filter(([, s]) => this.#grants.can(apiKeySubject(id), s.asset, s.rights)).map(([name]) => name); }
82
+ #shown(k) {
83
+ const used = this.#used.get(k.name)?.at ?? k.usedAt ?? null;
84
+ return { id: k.name, label: k.label, scopes: this.#scopesOf(k.name), createdBy: k.createdBy ?? null, createdAt: k.createdAt, expiresAt: k.expiresAt ?? null,
85
+ usedAt: used, expired: Boolean(k.expiresAt && Date.parse(k.expiresAt) <= this.#now()) };
86
+ }
87
+
88
+ /* Every key, newest first: never a secret, nor its hash. */
89
+ list() { return this.#store.all().map((k) => this.#shown(k)).sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt))); }
90
+ scopes() { return Object.entries(SCOPES).map(([id, s]) => ({ id, label: s.label })); }
91
+
92
+ /* A new key: its secret is in the answer, this once. `days`: its life (null: it does not expire). */
93
+ create({ label, scopes = [], days = DEFAULT_DAYS } = {}, who = '') {
94
+ if (!oneLine(label)) throw new Refusal(400, `A key has a name: one line, ${LABEL_MAX} characters at most.`);
95
+ if (!Array.isArray(scopes) || scopes.some((s) => !Object.hasOwn(SCOPES, s))) throw new Refusal(400, `Scopes are among: ${Object.keys(SCOPES).join(', ')}.`);
96
+ if (days !== null && !(Number.isInteger(days) && days >= 1 && days <= DAYS_MAX)) throw new Refusal(400, `A key lasts 1 to ${DAYS_MAX} days, or does not expire.`);
97
+ if (this.#store.all().length >= KEYS_MAX) throw new Refusal(409, `At most ${KEYS_MAX} keys: revoke one first.`);
98
+ const name = label.trim();
99
+ if (this.#store.all().some((k) => k.label.toLowerCase() === name.toLowerCase())) throw new Refusal(409, 'A key has this name already: one name per use.');
100
+ const id = randomUUID();
101
+ const secret = `${KEY_PREFIX}${randomBytes(32).toString('base64url')}`;
102
+ const now = this.#now();
103
+ const record = { name: id, label: name, hash: digest(secret).toString('hex'), createdAt: new Date(now).toISOString(),
104
+ ...(who ? { createdBy: String(who).slice(0, 120) } : {}), expiresAt: days === null ? null : new Date(now + days * 86_400_000).toISOString() };
105
+ this.#store.put(record);
106
+ for (const s of new Set(scopes)) this.#grants.give(apiKeySubject(id), SCOPES[s].asset, SCOPES[s].rights);
107
+ return { key: this.#shown(record), secret };
108
+ }
109
+
110
+ /* At once: the next call with it is refused. */
111
+ revoke(id) {
112
+ if (typeof id !== 'string' || !this.#store.get(id)) throw new Refusal(404, 'No such key.');
113
+ this.#store.remove(id);
114
+ this.#grants.forgetSubject(apiKeySubject(id));
115
+ this.#used.delete(id); this.#calls.delete(id);
116
+ }
117
+
118
+ get(id) { const k = this.#store.get(id); return k ? this.#shown(k) : undefined; }
119
+
120
+ /* The key a secret is, or undefined -- every key compared, in constant time each. */
121
+ #find(secret) {
122
+ if (typeof secret !== 'string' || !SECRET.test(secret)) return undefined;
123
+ const asked = digest(secret);
124
+ let found;
125
+ for (const k of this.#store.all()) {
126
+ if (typeof k.hash !== 'string' || !/^[0-9a-f]{64}$/.test(k.hash)) continue;
127
+ if (timingSafeEqual(Buffer.from(k.hash, 'hex'), asked) && found === undefined) found = k;
128
+ }
129
+ return found;
130
+ }
131
+
132
+ #counted(who, max) {
133
+ const now = this.#now();
134
+ const recent = (this.#calls.get(who) ?? []).filter((t) => now - t < 60_000);
135
+ if (recent.length >= max) { this.#calls.set(who, recent); return Math.max(1, Math.ceil((recent[0] + 60_000 - now) / 1000)); }
136
+ recent.push(now); this.#calls.set(who, recent);
137
+ return 0;
138
+ }
139
+
140
+ /* WHO ASKS, from the Authorization header, and may it read `scope`? Returns the key's id, or throws:
141
+ 401 no key, or one nobody has (unknown, revoked, expired); 429 too many calls; 403 not this scope. */
142
+ check(authorization, scope) {
143
+ const m = /^Bearer\s+(\S+)\s*$/i.exec(String(authorization ?? ''));
144
+ if (!m) throw Object.assign(new Refusal(401, 'An API key is needed: Authorization: Bearer clv_...'), { key: null });
145
+ const k = this.#find(m[1]);
146
+ if (!k || (k.expiresAt && Date.parse(k.expiresAt) <= this.#now())) {
147
+ const wait = this.#counted('', UNKNOWN_PER_MIN);
148
+ if (wait) throw Object.assign(new Refusal(429, 'Too many calls with keys that are not valid. Wait a minute.'), { key: null, retry: wait });
149
+ throw Object.assign(new Refusal(401, 'This API key is not valid: unknown, revoked or expired.'), { key: k?.name ?? null });
150
+ }
151
+ const wait = this.#counted(k.name, RATE_PER_MIN);
152
+ if (wait) throw Object.assign(new Refusal(429, `Too many calls: ${RATE_PER_MIN} a minute per key.`), { key: k.name, retry: wait });
153
+ this.#seen(k.name);
154
+ if (scope !== undefined && !this.#scopesOf(k.name).includes(scope)) throw Object.assign(new Refusal(403, `This key was not given the scope "${SCOPES[scope]?.label ?? scope}".`), { key: k.name });
155
+ return k.name;
156
+ }
157
+
158
+ /* Whether a key (already checked) has a scope. */
159
+ may(id, scope) { return this.#scopesOf(id).includes(scope); }
160
+
161
+ #seen(id) {
162
+ const now = this.#now();
163
+ const u = this.#used.get(id) ?? { at: null, savedAt: 0 };
164
+ u.at = new Date(now).toISOString();
165
+ if (now - u.savedAt >= USED_SAVE_MS) { u.savedAt = now; this.#store.patch(id, { usedAt: u.at }); }
166
+ this.#used.set(id, u);
167
+ }
168
+
169
+ /* One line of the journal: never the secret -- only the id of the key, if it is one. */
170
+ note({ key = null, route, status, method = 'GET' }) {
171
+ if (!this.#journal) return;
172
+ const line = { at: new Date(this.#now()).toISOString(), key: typeof key === 'string' ? key : null, method: String(method).slice(0, 8), route: String(route ?? '').replace(/[^\x20-\x7e]/g, '?').slice(0, 120), status };
173
+ try {
174
+ appendFileSync(this.#journal, `${JSON.stringify(line)}\n`, { mode: 0o600 });
175
+ if (statSync(this.#journal).size > JOURNAL_MAX) {
176
+ const lines = readFileSync(this.#journal, 'utf8').split('\n').filter(Boolean);
177
+ writeFileSync(`${this.#journal}.tmp`, `${lines.slice(Math.floor(lines.length / 2)).join('\n')}\n`, { mode: 0o600 });
178
+ renameSync(`${this.#journal}.tmp`, this.#journal);
179
+ }
180
+ } catch { /* said nowhere: never a reason to fail the call */ }
181
+ }
182
+
183
+ /* The last uses of one key, newest first. */
184
+ journal(id) {
185
+ if (!this.#store.get(id)) throw new Refusal(404, 'No such key.');
186
+ if (!this.#journal) return [];
187
+ let text = '';
188
+ try { text = readFileSync(this.#journal, 'utf8'); } catch { return []; }
189
+ const out = [];
190
+ for (const l of text.split('\n').reverse()) {
191
+ if (!l) continue;
192
+ try { const e = JSON.parse(l); if (e.key === id) out.push({ at: e.at, method: e.method, route: e.route, status: e.status }); } catch { /* a torn line */ }
193
+ if (out.length >= JOURNAL_SHOWN) break;
194
+ }
195
+ return out;
196
+ }
197
+ }
198
+
199
+ /* THE STATE, as a key with "status" reads it. Only what is picked here, field by field: never what a
200
+ conversation says (its messages, its last words), nor a secret, a file or an address. */
201
+ export async function statusOf({ conversations, talk, health, answerer, capacity, history, platform, updates, components = {} }) {
202
+ const needs = (c) => {
203
+ const t = talk?.brief(c.name);
204
+ const asks = Boolean(t && (t.needs ?? (t.waiting > 0 || t.state === 'waiting')));
205
+ const h = health?.of(c.name);
206
+ const unwell = c.phase === 'ready' && (h?.problems ?? []).some((p) => p.level === 'bad' && !(h.seen ?? []).includes(p.key));
207
+ return { asks: asks || Boolean(answerer?.of(c.name)?.needs) || c.phase === 'failed' || unwell, working: t?.state === 'working' };
208
+ };
209
+ const list = (conversations?.list() ?? []).map((c) => {
210
+ const n = needs(c);
211
+ const state = c.asleep === true ? 'asleep' : n.asks ? 'needs-you' : n.working ? 'working' : 'awake';
212
+ return { id: c.name, name: typeof c.title === 'string' && c.title ? c.title : c.name, state, phase: String(c.phase ?? ''), tool: String(c.toolLabel ?? c.tool ?? '') };
213
+ });
214
+ const brief = capacity ? await capacity.brief().catch(() => null) : null;
215
+ const room = capacity ? await capacity.room().catch(() => null) : null;
216
+ const cpu = (() => { const v = history?.series('server', '1h').cpu ?? []; for (let i = v.length - 1; i >= 0; i -= 1) if (v[i] !== null && v[i] !== undefined) return v[i]; return null; })();
217
+ const part = (x) => (x ? { usedPercent: x.usedPercent ?? null, freeMb: x.freeMb ?? null, high: Boolean(x.high) } : null);
218
+ let update = null;
219
+ try { const u = updates?.about(); if (u?.installed) update = { channel: u.channel ?? null, available: u.available ?? null }; } catch { /* not said */ }
220
+ return {
221
+ at: new Date().toISOString(),
222
+ server: { known: Boolean(brief?.known), memory: part(brief?.memory), disk: part(brief?.disk), cpu: { usedPercent: cpu, cores: room?.cpu?.cores ?? null } },
223
+ conversations: list,
224
+ counts: Object.fromEntries(['awake', 'working', 'needs-you', 'asleep'].map((s) => [s, list.filter((c) => c.state === s).length])),
225
+ versions: { clavarium: platform?.version ?? null, ...components, ...(update ? { update } : {}) },
226
+ };
227
+ }
228
+
229
+ /* ---- the door for programs: /api/ext/ ---- */
230
+
231
+ const MCP_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
232
+ const MCP_BODY_MAX = 64 * 1024;
233
+ export const STATUS_TOOL = {
234
+ name: 'clavarium_status',
235
+ title: 'Clavarium status',
236
+ description: 'Read-only state of this Clavarium: server memory, disk and CPU; each conversation with its name and state (asleep, awake, working, needs-you); versions. No conversation content.',
237
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
238
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
239
+ };
240
+
241
+ /* Returns true when the request was under /api/ext/ (answered here). `status()`: the state, as statusOf
242
+ makes it. `originOk(headers)`: whether an Origin is this site's (gate.mjs); a call from a page of
243
+ another site is refused. */
244
+ export async function handleExternal(request, response, { keys, status, headers = {}, originOk = () => false, version = null }) {
245
+ const { pathname } = new URL(request.url ?? '/', 'http://local');
246
+ if (!pathname.startsWith(EXT_PREFIX) && pathname !== EXT_PREFIX.slice(0, -1)) return false;
247
+ const route = pathname.slice(EXT_PREFIX.length - 1);
248
+ const send = (code, body, more = {}) => {
249
+ response.writeHead(code, { ...headers, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...more });
250
+ response.end(body === undefined ? undefined : JSON.stringify(body));
251
+ return true;
252
+ };
253
+ const note = (key, code, what = route) => keys.note({ key, route: what, status: code, method: request.method });
254
+ /* A browser on another site: never (MCP asks servers to look at Origin). Programs send none. */
255
+ const origin = request.headers.origin;
256
+ if (typeof origin === 'string' && !originOk(request.headers)) { note(null, 403); return send(403, { error: 'Not from another site.' }); }
257
+ const refused = (error, what) => {
258
+ if (!(error instanceof Refusal)) throw error;
259
+ note(error.key ?? null, error.status, what);
260
+ const more = error.status === 401 ? { 'www-authenticate': 'Bearer realm="clavarium"' } : error.status === 429 ? { 'retry-after': String(error.retry ?? 60) } : {};
261
+ return send(error.status, { error: error.message }, more);
262
+ };
263
+ try {
264
+ if (route === '/v1/status') {
265
+ if (request.method !== 'GET') return send(405, { error: 'Call this address with GET.' }, { allow: 'GET' });
266
+ let id;
267
+ try { id = keys.check(request.headers.authorization, 'status'); } catch (error) { return refused(error); }
268
+ const body = await status();
269
+ note(id, 200);
270
+ return send(200, body);
271
+ }
272
+ if (route === '/mcp') {
273
+ if (request.method !== 'POST') return send(405, { error: 'MCP is spoken with POST here (no event stream).' }, { allow: 'POST' });
274
+ let id;
275
+ try { id = keys.check(request.headers.authorization); } catch (error) { return refused(error, '/mcp'); }
276
+ let text = '';
277
+ for await (const piece of request) { text += piece; if (text.length > MCP_BODY_MAX) { note(id, 413, '/mcp'); return send(413, { error: 'Too long.' }); } }
278
+ let msg;
279
+ try { msg = JSON.parse(text); } catch { note(id, 400, '/mcp'); return send(400, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); }
280
+ if (!msg || typeof msg !== 'object' || Array.isArray(msg) || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
281
+ note(id, 400, '/mcp'); return send(400, { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } });
282
+ }
283
+ const what = `/mcp ${msg.method.slice(0, 40)}${msg.method === 'tools/call' ? ` ${String(msg.params?.name ?? '').slice(0, 40)}` : ''}`;
284
+ /* A notification (no id) is taken, never answered. */
285
+ if (msg.id === undefined || msg.id === null) { note(id, 202, what); response.writeHead(202, { ...headers, 'cache-control': 'no-store' }).end(); return true; }
286
+ const answer = (result) => { note(id, 200, what); return send(200, { jsonrpc: '2.0', id: msg.id, result }); };
287
+ const fail = (code, message, http = 200) => { note(id, http === 200 ? 400 : http, what); return send(http, { jsonrpc: '2.0', id: msg.id, error: { code, message } }); };
288
+ switch (msg.method) {
289
+ case 'initialize': {
290
+ const asked = String(msg.params?.protocolVersion ?? '');
291
+ return answer({ protocolVersion: MCP_VERSIONS.includes(asked) ? asked : MCP_VERSIONS[0], capabilities: { tools: { listChanged: false } },
292
+ serverInfo: { name: 'clavarium', title: 'Clavarium', version: version ?? '0' }, instructions: 'Read-only state of this Clavarium. One tool: clavarium_status.' });
293
+ }
294
+ case 'ping': return answer({});
295
+ case 'tools/list': return answer({ tools: [STATUS_TOOL] });
296
+ case 'tools/call': {
297
+ if (msg.params?.name !== STATUS_TOOL.name) return fail(-32602, `Unknown tool: ${String(msg.params?.name ?? '').slice(0, 60)}`);
298
+ if (!keys.may(id, 'status')) {
299
+ note(id, 403, what);
300
+ return send(403, { jsonrpc: '2.0', id: msg.id, error: { code: -32001, message: `This key was not given the scope "${SCOPES.status.label}".` } });
301
+ }
302
+ const body = await status();
303
+ return answer({ content: [{ type: 'text', text: JSON.stringify(body) }], structuredContent: body, isError: false });
304
+ }
305
+ default: return fail(-32601, 'Method not found');
306
+ }
307
+ }
308
+ note(null, 404);
309
+ return send(404, { error: 'Not found. GET /api/ext/v1/status, or MCP at /api/ext/mcp.' });
310
+ } catch (error) {
311
+ if (error instanceof Refusal) return refused(error);
312
+ return send(500, { error: 'Something failed on the server.' });
313
+ }
314
+ }
315
+
316
+ /* Settings, Access, "API keys": for whoever passed the gate. */
317
+ export async function handleApiKeys(request, response, keys, originOk, headers = {}, events = null) {
318
+ const { pathname } = new URL(request.url ?? '/', 'http://local');
319
+ if (pathname !== '/api/apikeys' && !pathname.startsWith('/api/apikeys/')) return false;
320
+ const send = (status, body) => { response.writeHead(status, { ...headers, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }).end(JSON.stringify(body)); return true; };
321
+ const who = String(request.headers['x-forwarded-email'] ?? '').trim().toLowerCase();
322
+ try {
323
+ if (request.method === 'GET' && pathname === '/api/apikeys') return send(200, { keys: keys.list(), scopes: keys.scopes(), defaultDays: DEFAULT_DAYS, me: who || null });
324
+ const journal = /^\/api\/apikeys\/([0-9a-f-]{36})\/journal$/.exec(pathname);
325
+ if (request.method === 'GET' && journal) return send(200, { uses: keys.journal(journal[1]) });
326
+ if (request.method !== 'POST') return false;
327
+ if (!originOk(request.headers) || !String(request.headers['content-type'] ?? '').startsWith('application/json')) return send(403, { error: 'This request does not come from this site.' });
328
+ let text = '';
329
+ for await (const piece of request) { text += piece; if (text.length > 4096) return send(413, { error: 'Too long.' }); }
330
+ let body;
331
+ try { body = text ? JSON.parse(text) : {}; } catch { return send(400, { error: 'The request is not JSON.' }); }
332
+ if (!body || typeof body !== 'object') body = {};
333
+ if (pathname === '/api/apikeys') {
334
+ const made = keys.create({ label: body.label, scopes: body.scopes ?? [], days: body.days === undefined ? DEFAULT_DAYS : body.days }, who);
335
+ /* Its name and scopes; never the secret. */
336
+ events?.add({ kind: 'access', text: `API key "${made.key.label}" made${made.key.scopes.length ? ` (${made.key.scopes.join(', ')})` : ' (no scope)'}`, who: who || null });
337
+ return send(201, made);
338
+ }
339
+ const revoke = /^\/api\/apikeys\/([0-9a-f-]{36})\/revoke$/.exec(pathname);
340
+ if (revoke) {
341
+ const label = keys.get(revoke[1])?.label;
342
+ keys.revoke(revoke[1]);
343
+ events?.add({ kind: 'access', text: `API key "${label}" revoked`, who: who || null });
344
+ return send(200, { ok: true });
345
+ }
346
+ return false;
347
+ } catch (error) {
348
+ if (error instanceof Refusal) return send(error.status, { error: error.message });
349
+ return send(500, { error: 'Something failed on the server.' });
350
+ }
351
+ }
@@ -108,6 +108,7 @@ export class Devices {
108
108
  for (const g of asked) {
109
109
  const rights = readRights(g?.asset, g?.rights);
110
110
  if (typeOf(g.asset) === 'secret') throw new Refusal(400, 'A secret is handed to a conversation, never shared with a device.');
111
+ if (typeOf(g.asset) === 'server') throw new Refusal(400, 'The state of the server is given to an API key, not to a device.');
111
112
  given.set(g.asset, rights);
112
113
  }
113
114
  for (const asset of given.keys()) {
package/server/grants.mjs CHANGED
@@ -19,10 +19,16 @@
19
19
  * mailbox read the messages (send, file: not built) -
20
20
  * git see the files change them -
21
21
  * secret never - be handed to a conversation
22
+ * server read its state - -
22
23
  *
23
- * Two kinds of subject: a CONVERSATION (what is attached to it reaches its
24
- * machine) and a PAIRING (what a device was given by a code). The owner is
25
- * not in the table: the owner may do everything, always.
24
+ * Three kinds of subject: a CONVERSATION (what is attached to it reaches its
25
+ * machine), a PAIRING (what a device was given by a code) and an API KEY
26
+ * (what a program elsewhere may ask with it: apikeys.mjs). The owner is not
27
+ * in the table: the owner may do everything, always.
28
+ *
29
+ * An API key is not a device and not a conversation: it is given only what
30
+ * its scopes name ("server:status", read), never a secret, a conversation or
31
+ * a folder in this version; and nothing else is ever given "server:".
26
32
  *
27
33
  * No groups, no inheritance. One rule sits on top, in the door: whoever was
28
34
  * given a conversation, its terminal or its chat, sees the files of that
@@ -41,14 +47,15 @@
41
47
  */
42
48
  import { Refusal } from './conversations.mjs';
43
49
 
44
- export const RIGHTS = Object.freeze({ conversation: 'rwx', folder: 'rw', mailbox: 'r', git: 'rw', secret: 'x' });
45
- const SUBJECT = /^(conversation:[a-z]([a-z0-9-]{0,30}[a-z0-9])?|pairing:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
46
- const ASSET = /^(conversation|folder|mailbox|git):[a-z]([a-z0-9-]{0,30}[a-z0-9])?$|^secret:[A-Z][A-Z0-9_]{0,39}$/;
50
+ export const RIGHTS = Object.freeze({ conversation: 'rwx', folder: 'rw', mailbox: 'r', git: 'rw', secret: 'x', server: 'r' });
51
+ const SUBJECT = /^(conversation:[a-z]([a-z0-9-]{0,30}[a-z0-9])?|(pairing|apikey):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
52
+ const ASSET = /^(conversation|folder|mailbox|git):[a-z]([a-z0-9-]{0,30}[a-z0-9])?$|^secret:[A-Z][A-Z0-9_]{0,39}$|^server:status$/;
47
53
 
48
54
  export const typeOf = (asset) => String(asset).split(':')[0];
49
55
  export const nameOf = (asset) => String(asset).slice(String(asset).indexOf(':') + 1);
50
56
  export const conversationSubject = (name) => `conversation:${name}`;
51
57
  export const pairingSubject = (id) => `pairing:${id}`;
58
+ export const apiKeySubject = (id) => `apikey:${id}`;
52
59
 
53
60
  /* The rights asked for, in the one order they are written, or a refusal:
54
61
  only letters this type of asset takes, at least one, none twice. */
@@ -86,6 +93,8 @@ export class Grants {
86
93
  would be a way to read it. */
87
94
  if (typeOf(asset) === 'secret' && !subject.startsWith('conversation:')) throw new Refusal(400, 'A secret is handed to a conversation, never shared with a device.');
88
95
  if (typeOf(asset) === 'conversation' && !subject.startsWith('pairing:')) throw new Refusal(400, 'A conversation is shared with a device, not with another conversation.');
96
+ /* The state of the server is given to an API key, and an API key is given nothing else (yet). */
97
+ if ((typeOf(asset) === 'server') !== subject.startsWith('apikey:')) throw new Refusal(400, 'An API key is given the state of the server, and only that.');
89
98
  this.#store.put({ name: this.#key(subject, asset), subject, asset, rights: clean });
90
99
  return clean;
91
100
  }
package/server/main.mjs CHANGED
@@ -83,6 +83,7 @@ import { Boxes, handleBoxes, voiceboxConnector, syncTargets, PAIR_PATH as BOX_PA
83
83
  import { Pocket } from './pocket.mjs';
84
84
  import { Speech } from './speech.mjs';
85
85
  import { Features, handleFeatures, cached } from './features.mjs';
86
+ import { ApiKeys, handleExternal, handleApiKeys, statusOf } from './apikeys.mjs';
86
87
  import { WebSocketServer } from 'ws';
87
88
 
88
89
  const ROOT = fileURLToPath(new URL('..', import.meta.url));
@@ -180,7 +181,7 @@ const withoutTmux = (env) => Object.fromEntries(Object.entries(env).filter(([key
180
181
 
181
182
  const REFUSED = 'This Clavarium belongs to someone else: your account is not one of its operators.\n';
182
183
 
183
- function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, features } = {}) {
184
+ function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, features, apikeys } = {}) {
184
185
  /* Its manifest carries the name of this Clavarium, or the one a device chose (instance.mjs). */
185
186
  const sendManifest = (response, url) => response.writeHead(200, { ...HEADERS, 'content-type': 'application/manifest+json' }).end(instance.manifest(new URL(url ?? '/', 'http://local').searchParams.get('name') ?? undefined));
186
187
  const sendFile = async (response, file) => {
@@ -194,7 +195,8 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
194
195
  every page hears it at its next question, whatever it asks. */
195
196
  try { const notice = updates?.notice(); if (notice) response.setHeader('x-clavarium-update', notice); } catch { /* never in the way of an answer */ }
196
197
  /* The version that answers, to the page's own questions: a page loaded before an update starts again (app.js). */
197
- if (platform?.version && (pathname.startsWith('/api/') || pathname.startsWith('/c/api/'))) response.setHeader('x-clavarium-version', platform.version);
198
+ /* Not to a program at /api/ext/: what it may read, its key says (apikeys.mjs). */
199
+ if (platform?.version && ((pathname.startsWith('/api/') && !pathname.startsWith('/api/ext/')) || pathname.startsWith('/c/api/'))) response.setHeader('x-clavarium-version', platform.version);
198
200
  /* The device door first, and apart: it never consults the gate. */
199
201
  /* An address that wakes a tool, called from outside by what its owner
200
202
  runs elsewhere: the address is the right. Nothing else is looked at,
@@ -227,6 +229,12 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
227
229
  try { say(200, boxes.pair(JSON.parse(text || '{}'))); } catch (error) { say(error.status ?? 400, { error: error instanceof SyntaxError ? 'Not JSON.' : error.message }); }
228
230
  return;
229
231
  }
232
+ /* THE DOOR FOR PROGRAMS (apikeys.mjs): an API key is the right, never the gate -- the front lets
233
+ /api/ext/ through without sign-on, and strips the identity headers there. */
234
+ if (apikeys && (pathname === '/api/ext' || pathname.startsWith('/api/ext/'))) {
235
+ await handleExternal(request, response, { keys: apikeys.keys, status: apikeys.status, headers: HEADERS, originOk, version: platform?.version ?? null });
236
+ return;
237
+ }
230
238
  if (door && pathname.startsWith('/c/')) {
231
239
  if (await handleDoor(request, response, door)) return;
232
240
  if (pathname === '/c/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
@@ -243,6 +251,8 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
243
251
  /* What this Clavarium can do and its next step (features.mjs); an export of the setup is its backup's day. */
244
252
  if (features && pathname.startsWith('/api/features') && await handleFeatures(request, response, features, originOk, HEADERS)) return;
245
253
  if (features && ((request.method === 'POST' && pathname === '/api/setup/export') || (request.method === 'GET' && pathname === '/api/setup/bundle' && !request.url.includes('stats=1')))) response.once('finish', () => { if (response.statusCode === 200) features.exported(); });
254
+ /* Settings, Access, API keys: made and revoked by an administrator only (past the gate). */
255
+ if (apikeys && pathname.startsWith('/api/apikeys') && await handleApiKeys(request, response, apikeys.keys, originOk, HEADERS, events)) return;
246
256
  if (boxes && pathname.startsWith('/api/boxes') && await handleBoxes(request, response, boxes, originOk, HEADERS, (text) => QRCode.toString(text, { type: 'svg', margin: 1, errorCorrectionLevel: 'M' }))) return;
247
257
  if (conversations && await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, catalogue, rooms)) return;
248
258
  if (pathname === '/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
@@ -678,6 +688,15 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
678
688
  catalogue are slow to ask: kept a while, and never waited for long. */
679
689
  const screenNow = cached(() => meshcentral.status().catch(() => null), 60_000);
680
690
  const quick = (p, ms, fallback) => Promise.race([p, new Promise((done) => { setTimeout(() => done(fallback), ms).unref?.(); })]);
691
+ /* API KEYS (apikeys.mjs): a third kind of subject in the table of rights; their door, /api/ext/. */
692
+ const components = {};
693
+ for (const name of ['clavarium-parley', 'clavarium-tether', 'clavarium-binder', 'clavarium-docket']) {
694
+ try { components[name.slice('clavarium-'.length)] = JSON.parse(readFileSync(packageFile(name, 'package.json'), 'utf8')).version; } catch { /* not installed here */ }
695
+ }
696
+ const apiKeys = new ApiKeys({ store: new Store(`${dataDir}/apikeys.json`), grants, journal: `${dataDir}/apikeys.log` });
697
+ /* What the host program says of the server is never waited for long: a key gets what is known. */
698
+ const briefly = { brief: () => quick(capacity.brief(), 3000, null), room: () => quick(capacity.room(), 3000, null) };
699
+ const apikeys = { keys: apiKeys, status: () => statusOf({ conversations: all, talk, health, answerer, capacity: briefly, history, platform, updates, components }) };
681
700
  const features = new Features({ file: new JsonFile(`${dataDir}/features.json`, {}), context: async () => ({
682
701
  secrets: secrets.list(), dictation: voice.about(), boxes: boxes.all(), alerts: alerts.about().devices.length,
683
702
  conversations: all.list().map((c) => ({ tool: c.tool })), tools: all.tools().map((t) => t.id),
@@ -685,7 +704,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
685
704
  answerer: answererConfig(env)?.models.length ?? 0, updates: updates.about(), team: team ? team.list().length : null,
686
705
  screen: await quick(screenNow(), 1500, null), catalogue: await quick(catalogue.providers().catch(() => []), 1500, []),
687
706
  }) });
688
- const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, features, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
707
+ const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, features, apikeys, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
689
708
  server.on('close', () => { closing = true; stopBinders(); stopTethers(); clearInterval(historyTimer); clearInterval(secretsTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopNetworkWatch(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(restartTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
690
709
  let closing = false;
691
710
  boxes.attach(server, WebSocketServer);
@@ -54,5 +54,15 @@ export const SETTINGS_WORDS_FR = {
54
54
  'set-mail-gone': 'Ce mail n\'est plus dans la boîte.', 'set-mail-not-yours': 'Vous n\'avez pas accès à cette boîte.',
55
55
  'set-mail-old-ref': 'Réf. ancienne : demandez à l\'IA de la rattacher.', 'set-mail-unreachable': 'Boîte injoignable pour le moment.',
56
56
  'set-mail-cut': 'Mail tronqué : pièces jointes incomplètes.',
57
+ 'set-ch-s-apikeys': 'Clés d\'API', 'set-apikeys-about': 'Pour un programme ou une IA.', 'set-apikeys-n1': '1 clé', 'set-apikeys-n': '{n} clés',
58
+ 'set-apikeys-once': 'Copiez-la : elle ne sera plus affichée.', 'set-apikeys-copy': 'Copier', 'set-apikeys-copied': 'Copiée',
59
+ 'set-apikeys-select': 'Sélectionnée : copiez-la', 'set-apikeys-done': 'Fait', 'set-apikeys-none': 'Aucune clé.', 'set-apikeys-name': 'Nom',
60
+ 'set-apikeys-name-hint': 'À quoi elle sert', 'set-apikeys-scopes': 'Portées', 'set-apikeys-scopes-hint': 'Aucune tant que rien n\'est coché',
61
+ 'set-apikeys-expires': 'Expire', 'set-apikeys-30': 'Dans 30 jours', 'set-apikeys-90': 'Dans 90 jours', 'set-apikeys-365': 'Dans un an',
62
+ 'set-apikeys-never': 'Jamais', 'set-apikeys-cancel': 'Annuler', 'set-apikeys-create': 'Créer', 'set-apikeys-new': 'Nouvelle clé',
63
+ 'set-apikeys-never-by-key': 'Jamais par clé : secrets, clés, comptes, serveur', 'set-apikeys-scope-status': 'État (lecture)',
64
+ 'set-apikeys-no-scope': 'Aucune portée', 'set-apikeys-by-you': 'par vous', 'set-apikeys-used': 'Utilisée {when}', 'set-apikeys-unused': 'Jamais utilisée',
65
+ 'set-apikeys-expired': 'Expirée', 'set-apikeys-expires-on': 'Expire le {date}', 'set-apikeys-no-expiry': 'N\'expire pas',
66
+ 'set-apikeys-created': 'Créée le {date}', 'set-apikeys-revoke': 'Révoquer', 'set-apikeys-revoke-q': 'Révoquer maintenant ?',
57
67
  };
58
68
  export const settingsWords = (lang) => (String(lang ?? '').toLowerCase().split('-')[0] === 'fr' ? { ...SETTINGS_WORDS_FR } : {});
package/web/app.js CHANGED
@@ -6142,6 +6142,82 @@
6142
6142
  rows.append(row);
6143
6143
  }
6144
6144
  }
6145
+ /* API KEYS (server/apikeys.mjs): what a program or an AI elsewhere may read with a key. Made with no
6146
+ scope until one is ticked; its secret shown this once, then never; revoked at once, confirmed in place.
6147
+ Administrators only: hidden on a device, and where the server does not answer it. */
6148
+ const shortDate = (t) => new Date(t).toLocaleDateString([], { day: 'numeric', month: 'short', year: 'numeric' });
6149
+ async function paintApiKeys() {
6150
+ const got = DEVICE ? null : await fetch(`${API}/apikeys`).then((r) => (r.ok ? r.json() : null)).catch(() => null);
6151
+ $('settings-ch-apikeys').hidden = !got || !Array.isArray(got.keys);
6152
+ if (!got || !Array.isArray(got.keys)) return;
6153
+ const scopeWord = (id) => uiSaid(`set-apikeys-scope-${id}`, got.scopes.find((x) => x.id === id)?.label ?? id);
6154
+ const live = got.keys.filter((k) => !k.expired).length;
6155
+ chapterNow('s-apikeys', got.keys.length ? uiSaid(live === 1 ? 'set-apikeys-n1' : 'set-apikeys-n', live === 1 ? '1 key' : '{n} keys', { n: live }) : uiSaid('set-apikeys-about', 'For a program or an AI.'));
6156
+ $('apikeys-where').textContent = `MCP: ${location.origin}/api/ext/mcp`;
6157
+ const scopes = $('apikeys-scopes');
6158
+ if (!scopes.childElementCount) {
6159
+ for (const sc of got.scopes) {
6160
+ const l = el('label', 'check'); const box = document.createElement('input'); box.type = 'checkbox'; box.value = sc.id; box.name = 'apikeys-scope';
6161
+ l.append(box, ' ', el('span', '', scopeWord(sc.id))); scopes.append(l);
6162
+ }
6163
+ }
6164
+ const rows = $('apikeys-rows'); rows.replaceChildren();
6165
+ $('apikeys-empty').hidden = got.keys.length > 0;
6166
+ for (const k of got.keys) {
6167
+ const row = el('div', 'list-item apikey'); row.dataset.id = k.id;
6168
+ const what = el('div', 'set-what');
6169
+ const head = el('b', '', k.label);
6170
+ what.append(head);
6171
+ const tags = el('span', 'apikey-scopes');
6172
+ if (k.scopes.length) for (const sc of k.scopes) tags.append(el('span', 'chip', scopeWord(sc)));
6173
+ else tags.append(el('span', 'chip', uiSaid('set-apikeys-no-scope', 'No scope')));
6174
+ what.append(tags);
6175
+ const by = k.createdBy ? (k.createdBy === got.me ? uiSaid('set-apikeys-by-you', 'by you') : k.createdBy) : '';
6176
+ const facts = [
6177
+ k.usedAt ? uiSaid('set-apikeys-used', 'Used {when}', { when: agoSaid(k.usedAt) }) : uiSaid('set-apikeys-unused', 'Never used'),
6178
+ k.expired ? uiSaid('set-apikeys-expired', 'Expired') : k.expiresAt ? uiSaid('set-apikeys-expires-on', 'Expires {date}', { date: shortDate(k.expiresAt) }) : uiSaid('set-apikeys-no-expiry', 'No expiry'),
6179
+ `${uiSaid('set-apikeys-created', 'Created {date}', { date: shortDate(k.createdAt) })}${by ? ` ${by}` : ''}`,
6180
+ ];
6181
+ what.append(el('small', k.expired ? 'bad' : '', facts.join(' · ')));
6182
+ const acts = el('div', 'set-control');
6183
+ const revoke = el('button', 'danger', uiSaid('set-apikeys-revoke', 'Revoke')); revoke.type = 'button'; revoke.dataset.act = 'revoke';
6184
+ revoke.addEventListener('click', () => {
6185
+ KIT.InlineConfirm(revoke, { question: uiSaid('set-apikeys-revoke-q', 'Revoke now?'), yes: uiSaid('set-apikeys-revoke', 'Revoke'), onYes: async () => {
6186
+ $('apikeys-error').hidden = true;
6187
+ try { await post(`${API}/apikeys/${k.id}/revoke`, {}); } catch (error) { $('apikeys-error').textContent = error.message; $('apikeys-error').hidden = false; $('apikeys-form').hidden = false; }
6188
+ await paintApiKeys();
6189
+ } });
6190
+ });
6191
+ acts.append(revoke);
6192
+ row.append(what, acts);
6193
+ rows.append(row);
6194
+ }
6195
+ }
6196
+ const apiKeyFormShown = (on) => {
6197
+ $('apikeys-form').hidden = !on; $('apikeys-new-row').hidden = on; $('apikeys-error').hidden = true;
6198
+ if (on) { $('apikeys-label').value = ''; $('apikeys-days').value = '90'; for (const b of $('apikeys-scopes').querySelectorAll('input')) b.checked = false; $('apikeys-label').focus(); }
6199
+ };
6200
+ $('apikeys-new').addEventListener('click', () => apiKeyFormShown(true));
6201
+ $('apikeys-cancel').addEventListener('click', () => apiKeyFormShown(false));
6202
+ $('apikeys-form').addEventListener('submit', async (event) => {
6203
+ event.preventDefault();
6204
+ $('apikeys-error').hidden = true;
6205
+ const days = $('apikeys-days').value;
6206
+ try {
6207
+ const r = await post(`${API}/apikeys`, { label: $('apikeys-label').value.trim(), scopes: [...$('apikeys-scopes').querySelectorAll('input:checked')].map((b) => b.value), days: days === 'never' ? null : Number(days) });
6208
+ apiKeyFormShown(false);
6209
+ $('apikeys-secret').value = r.secret; $('apikeys-once').hidden = false;
6210
+ } catch (error) { $('apikeys-error').textContent = error.message; $('apikeys-error').hidden = false; return; }
6211
+ await paintApiKeys();
6212
+ });
6213
+ $('apikeys-copy').addEventListener('click', async () => {
6214
+ const b = $('apikeys-copy'); const f = $('apikeys-secret');
6215
+ try { await navigator.clipboard.writeText(f.value); b.textContent = uiSaid('set-apikeys-copied', 'Copied'); }
6216
+ catch { f.focus(); f.select(); b.textContent = uiSaid('set-apikeys-select', 'Selected: copy it'); }
6217
+ setTimeout(() => { b.textContent = uiSaid('set-apikeys-copy', 'Copy'); }, 2500);
6218
+ });
6219
+ /* Done: the secret leaves the page too. */
6220
+ $('apikeys-done').addEventListener('click', () => { $('apikeys-secret').value = ''; $('apikeys-once').hidden = true; });
6145
6221
  function showPassword(email, password) {
6146
6222
  $('operators-password-for').textContent = email; $('operators-password-value').value = password; $('operators-password').hidden = false;
6147
6223
  }
@@ -6358,6 +6434,7 @@
6358
6434
  }
6359
6435
  void paintDictation();
6360
6436
  void paintOperators();
6437
+ void paintApiKeys();
6361
6438
  /* With no shortcut, one line: how to add one (this is the only place to remove them). */
6362
6439
  $('settings-shortcuts-hint').textContent = saved.length ? 'Added under the terminal, with "+ Shortcut".' : 'No shortcut yet · add one under the terminal, with "+ Shortcut".';
6363
6440
  $('settings-people').textContent = (platform.operators ?? []).length
package/web/index.html CHANGED
@@ -1027,6 +1027,24 @@
1027
1027
  <p class="error" id="operators-error" role="alert" hidden></p>
1028
1028
  </div>
1029
1029
  </details>
1030
+ <!-- API KEYS (server/apikeys.mjs): what a program or an AI elsewhere may read, by a key; its secret
1031
+ shown once. Administrators only: never on a device (app.js, paintApiKeys). -->
1032
+ <details class="chapter" id="settings-ch-apikeys" data-chapter="s-apikeys" hidden>
1033
+ <summary><span class="chapter-title" data-said="set-ch-s-apikeys">API keys</span><span class="chapter-about" id="apikeys-about">For a program or an AI.</span></summary>
1034
+ <div class="chapter-body">
1035
+ <div id="apikeys-once" class="callout apikeys-once" role="status" hidden><p><b data-said="set-apikeys-once">Copy it now: it won't be shown again.</b></p><div class="row"><input id="apikeys-secret" readonly spellcheck="false" aria-label="API key"><button type="button" id="apikeys-copy" class="primary" data-said="set-apikeys-copy">Copy</button><button type="button" id="apikeys-done" data-said="set-apikeys-done">Done</button></div></div>
1036
+ <div id="apikeys-rows"></div>
1037
+ <p class="hint" id="apikeys-empty" data-said="set-apikeys-none" hidden>No key yet.</p>
1038
+ <form id="apikeys-form" class="set-rows" autocomplete="off" hidden>
1039
+ <div class="set-row"><div class="set-what"><label for="apikeys-label" data-said="set-apikeys-name">Name</label><small data-said="set-apikeys-name-hint">What it is for</small></div><div class="set-control"><input id="apikeys-label" maxlength="40" spellcheck="false" required></div></div>
1040
+ <div class="set-row"><div class="set-what"><span data-said="set-apikeys-scopes">Scopes</span><small data-said="set-apikeys-scopes-hint">None until ticked</small></div><div class="set-control" id="apikeys-scopes"></div></div>
1041
+ <div class="set-row"><div class="set-what"><label for="apikeys-days" data-said="set-apikeys-expires">Expires</label></div><div class="set-control"><select id="apikeys-days"><option value="30" data-said="set-apikeys-30">In 30 days</option><option value="90" data-said="set-apikeys-90" selected>In 90 days</option><option value="365" data-said="set-apikeys-365">In a year</option><option value="never" data-said="set-apikeys-never">Never</option></select></div></div>
1042
+ <div class="action-row"><span class="error" id="apikeys-error" role="alert" hidden></span><button type="button" id="apikeys-cancel" data-said="set-apikeys-cancel">Cancel</button><button type="submit" class="primary" data-said="set-apikeys-create">Create</button></div>
1043
+ </form>
1044
+ <div class="action-row" id="apikeys-new-row"><span class="hint" id="apikeys-where"></span><button type="button" id="apikeys-new" class="primary" data-said="set-apikeys-new">New key</button></div>
1045
+ <p class="hint" data-said="set-apikeys-never-by-key">Never by key: secrets, keys, accounts, server</p>
1046
+ </div>
1047
+ </details>
1030
1048
  <!-- NETWORK: this server's Wi-Fi (server/wifi.mjs; done as root by the host program,
1031
1049
  through NetworkManager). A switch goes back by itself when the new network does not work. -->
1032
1050
  <details class="chapter" id="settings-wifi-top" data-chapter="s-network">
package/web/kit.js CHANGED
@@ -118,6 +118,8 @@
118
118
  member says only what waits for you (tone 'need' or 'count').
119
119
  `tag`: 'button' (opens it: `onOpen`) or 'div' (a member: its gestures are `actions`). `cls`: the
120
120
  page's own classes, kept for its rules and tests. */
121
+ /* A line of a message as plain words: Markdown's marks taken off (**, __, `, #, > , links' addresses). */
122
+ const plainLine = (t) => String(t ?? '').replace(/\[([^\]\n]+)\]\([^)\s]+\)/g, '$1').replace(/(\*\*|__|\*|_|`+|~~)(?=\S)([^\n]*?\S)\1/g, '$2').replace(/^\s*(#{1,6}|>|[-*+]|\d+\.)\s+/gm, '').replace(/\*\*|`/g, '').replace(/\s+/g, ' ').trim();
121
123
  function ConvCard(m, { size = 'row', tag, cls = '', onOpen = null, actions = [] } = {}) {
122
124
  const t = tag ?? (size === 'member' ? 'div' : 'button');
123
125
  const root = node(t, `kit-conv kit-conv-${size}${cls ? ` ${cls}` : ''}`);
@@ -142,9 +144,10 @@
142
144
  else if (marks) lines.push(marks);
143
145
  else lines.push(...sub);
144
146
  } else if (size === 'card') {
145
- if (m.last) lines.push(node('small', 'last', m.last));
146
- const what = [m.now, m.who].filter(Boolean).join(' · ');
147
- if (what) lines.push(node('small', 'kit-conv-now', what));
147
+ /* 06-11 (the owner's review): its last words without their Markdown marks; what it does now only when it
148
+ says something the point does not (asleep: the grey point says it); its tool in the details, not here. */
149
+ if (m.last) lines.push(node('small', 'last', plainLine(m.last)));
150
+ if (m.now && state !== 'sleep') lines.push(node('small', 'kit-conv-now', m.now));
148
151
  } else {
149
152
  const what = [m.who, m.now].filter(Boolean).join(' · ');
150
153
  if (what) lines.push(node('small', 'kit-conv-now', what));
package/web/style.css CHANGED
@@ -1864,7 +1864,17 @@ button.tip-btn:hover, button.tip-btn[aria-expanded="true"] { color: var(--brass-
1864
1864
  .list-item > .set-what > b { font-size: .875rem; overflow-wrap: anywhere; }
1865
1865
  .list-item > .set-what > small { font-size: .75rem; color: var(--ink2); }
1866
1866
  .list-item > :is(button, .set-control) { justify-self: end; }
1867
- :is(#settings, #panel) .chapter-body > :is(#settings-shortcuts, #operators-rows, #git-hosts) { padding: 0; }
1867
+ :is(#settings, #panel) .chapter-body > :is(#settings-shortcuts, #operators-rows, #git-hosts, #apikeys-rows) { padding: 0; }
1868
+ /* API keys (Settings, Access): its scopes as chips; the secret shown once, in a field as wide as it can be. */
1869
+ .apikey-scopes { display: flex; flex-wrap: wrap; gap: 4px; margin: 2px 0; }
1870
+ .list-item.apikey > .set-what > small.bad { color: var(--danger); }
1871
+ .apikeys-once > p { margin: 0 0 6px; }
1872
+ .apikeys-once input { flex: 1 1 14rem; min-width: 0; font-family: ui-monospace, Menlo, Consolas, monospace; }
1873
+ #apikeys-scopes { display: flex; flex-wrap: wrap; gap: 8px; }
1874
+ /* Revoke confirmed in place: the question and its buttons under the key, never squeezing its name. */
1875
+ .list-item.apikey:has(.kit-confirm) { grid-template-columns: minmax(0, 1fr); }
1876
+ @media (max-width: 520px) { .apikeys-once input { flex-basis: 100%; } }
1877
+ #apikeys-where { flex: 1 1 auto; min-width: 0; overflow-wrap: anywhere; font-family: ui-monospace, Menlo, Consolas, monospace; font-size: .75rem; }
1868
1878
  .mono-cut { font-family: ui-monospace, Menlo, Consolas, monospace; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1869
1879
  #settings #export-note { max-width: none; text-align: left; margin: 0; order: 0; flex: none; }
1870
1880
  /* Several settings in one block: one line between them too. */
@@ -2288,7 +2298,8 @@ body.as-dragging #assets-rows .as-row { touch-action: none; }
2288
2298
  /* THE CONVERSATIONS AS CARDS (02-11): playing cards, one per conversation, and one to add. */
2289
2299
  #list-title { cursor: pointer; }
2290
2300
  #deck { overflow-y: auto; }
2291
- .deck { display: grid; grid-template-columns: repeat(auto-fill, minmax(176px, 1fr)); gap: 14px; padding: 14px 16px 24px; }
2301
+ /* 06-11 (the owner's tablet: 7 narrow columns, names cut): wider cards, fewer columns. */
2302
+ .deck { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 248px), 1fr)); gap: 14px; padding: 14px 16px 24px; }
2292
2303
  .conv-card { position: relative; min-height: 120px; display: flex; flex-direction: column; gap: 6px; padding: 12px; border-radius: 14px; border: 1px solid var(--line); background: linear-gradient(160deg, var(--bar), var(--panel)); color: var(--ink); text-align: left; font: inherit; box-shadow: 0 6px 18px rgba(0, 0, 0, .18); cursor: pointer; transition: transform .15s, border-color .15s; }
2293
2304
  .conv-card:hover, .conv-card:focus-visible { transform: translateY(-3px); border-color: var(--brass); }
2294
2305
  .conv-card-new { align-items: center; justify-content: center; border-style: dashed; border-width: 1.5px; background: transparent; box-shadow: none; color: var(--ink2); }
@@ -2732,7 +2743,10 @@ button.kit-switch[aria-checked="true"]::after { left: 18px; background: var(--ok
2732
2743
  .kit-conv-card .kit-conv-main > small { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--ink2); font-size: .8125rem; }
2733
2744
  .kit-conv-card .kit-conv-main > .last { color: var(--ink); opacity: .9; }
2734
2745
  .kit-conv-card .kit-conv-main > .last { white-space: normal; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
2735
- .kit-conv-card .kit-conv-head > b { font-size: .9375rem; white-space: normal; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow-wrap: anywhere; line-height: 1.25; }
2746
+ /* A name wraps between its words only (06-11: « Assistant / s » was cut anywhere); a word too long for the card is hyphenated where the language allows, else cut. */
2747
+ .kit-conv-card .kit-conv-head > b { font-size: .9375rem; white-space: normal; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: normal; word-break: normal; hyphens: auto; line-height: 1.25; }
2748
+ .kit-conv-card .kit-chips { flex-wrap: nowrap; overflow: hidden; }
2749
+ .kit-conv-card .kit-chip { flex: 0 1 auto; min-width: 0; }
2736
2750
  .kit-conv-member { --kc-ring: var(--panel); align-items: center; padding: 8px 12px; }
2737
2751
  .kit-conv-member .kit-conv-head > b { font-size: .8125rem; }
2738
2752
  .kit-conv-member .kit-conv-main > small { font-size: .75rem; }