clavarium 0.2.23 → 0.2.24-next.2
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/npm-shrinkwrap.json +6 -6
- package/package.json +2 -2
- package/server/api.mjs +7 -2
- package/server/events.mjs +2 -0
- package/server/gitchecks.mjs +3 -1
- package/server/gitkeeper.mjs +7 -2
- package/server/guide.mjs +1 -1
- package/server/health.mjs +13 -1
- package/server/main.mjs +15 -2
- package/server/secrets.mjs +86 -16
- package/server/talk.mjs +2 -2
- package/web/app.js +217 -46
- package/web/index.html +2 -1
- package/web/links.js +164 -114
- package/web/style.css +74 -52
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.24-next.2",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "clavarium",
|
|
9
|
-
"version": "0.2.
|
|
9
|
+
"version": "0.2.24-next.2",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
|
13
13
|
"@xterm/xterm": "^6.0.0",
|
|
14
14
|
"clavarium-docket": "0.1.0",
|
|
15
|
-
"clavarium-parley": "0.
|
|
15
|
+
"clavarium-parley": "0.15.0-next.2",
|
|
16
16
|
"mermaid": "11.17.2",
|
|
17
17
|
"node-pty": "^1.1.0",
|
|
18
18
|
"pdfjs-dist": "6.4.299",
|
|
@@ -700,9 +700,9 @@
|
|
|
700
700
|
}
|
|
701
701
|
},
|
|
702
702
|
"node_modules/clavarium-parley": {
|
|
703
|
-
"version": "0.
|
|
704
|
-
"resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.
|
|
705
|
-
"integrity": "sha512-
|
|
703
|
+
"version": "0.15.0-next.2",
|
|
704
|
+
"resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.15.0-next.2.tgz",
|
|
705
|
+
"integrity": "sha512-rOH6fyC52iE6XLZI+EqSbJxQdzZIyvdHHAl3224JV/x/6xr6+S0tPuKy3Y/bUZM8M6+pnZ+5hyPacCH9pykoVA==",
|
|
706
706
|
"license": "MIT",
|
|
707
707
|
"bin": {
|
|
708
708
|
"parley": "bin/parley.mjs",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.24-next.2",
|
|
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.",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"@xterm/addon-fit": "^0.11.0",
|
|
46
46
|
"@xterm/xterm": "^6.0.0",
|
|
47
47
|
"clavarium-docket": "0.1.0",
|
|
48
|
-
"clavarium-parley": "0.
|
|
48
|
+
"clavarium-parley": "0.15.0-next.2",
|
|
49
49
|
"mermaid": "11.17.2",
|
|
50
50
|
"node-pty": "^1.1.0",
|
|
51
51
|
"pdfjs-dist": "6.4.299",
|
package/server/api.mjs
CHANGED
|
@@ -66,7 +66,8 @@
|
|
|
66
66
|
* GET /api/conversations/<name>/signin {available, configured, host, user, items}
|
|
67
67
|
* POST /api/conversations/<name>/signin {host, port?, user, password}; empty host removes
|
|
68
68
|
* GET /api/secrets names only: a value never comes back
|
|
69
|
-
* POST /api/secrets {name, value} create or replace
|
|
69
|
+
* POST /api/secrets {name, value, expires?} create or replace; expires YYYY-MM-DD
|
|
70
|
+
* POST /api/secrets/<NAME>/replace {value?, expires?}: in place, its name and grants kept; '' removes the expiry
|
|
70
71
|
* POST /api/secrets/<NAME>/remove
|
|
71
72
|
* POST /api/secrets/<NAME>/rename {name}: its value and where it is handed go with it
|
|
72
73
|
* GET /api/conversations/<name>/health-react POST the same {on?, message?, command?}: what it does when its machine is short
|
|
@@ -415,6 +416,9 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
415
416
|
}
|
|
416
417
|
const renaming = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/rename$/.exec(pathname);
|
|
417
418
|
if (renaming && secrets) return send(200, secrets.rename(renaming[1], String(body.name ?? '').trim())), true;
|
|
419
|
+
/* A new value (never sent back) and/or a new expiry, in place. */
|
|
420
|
+
const replacing = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/replace$/.exec(pathname);
|
|
421
|
+
if (replacing && secrets) return send(200, secrets.replace(replacing[1], { value: body.value, expires: body.expires })), true;
|
|
418
422
|
const dropped = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/remove$/.exec(pathname);
|
|
419
423
|
if (dropped && secrets) { secrets.remove(dropped[1]); return send(200, { ok: true }), true; }
|
|
420
424
|
if (pathname === '/api/alerts' && alerts) return send(201, alerts.add(body.subscription, body.label)), true;
|
|
@@ -437,7 +441,8 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
437
441
|
if (talking[2] === '/remind') return send(200, await talk.remind(conversation)), true;
|
|
438
442
|
if (talking[2] === '/react') return send(200, await talk.react(conversation, body.to, body.reaction ?? null)), true;
|
|
439
443
|
if (typeof body.on === 'boolean') { const now = await talk.set(conversation, body.on); retell(conversation); return send(200, now), true; }
|
|
440
|
-
|
|
444
|
+
/* What the chat may add to an answer: the choices ticked, the answers of a group, the zone of a picture it is about (Parley checks each). */
|
|
445
|
+
return send(201, await talk.say(conversation, body.text, body.answers, body.files, body.via, { picked: body.picked, replies: body.replies, about: body.about })), true;
|
|
441
446
|
}
|
|
442
447
|
const docketed = /^\/api\/conversations\/([^/]+)\/docket(\/cancel)?$/.exec(pathname);
|
|
443
448
|
if (docketed && wakeups) {
|
package/server/events.mjs
CHANGED
|
@@ -42,6 +42,8 @@ const SAID = [
|
|
|
42
42
|
[/^\/api\/resources\/([^/]+)\/remove$/, 'asset', (m) => `${clip(decodeURIComponent(m[1]), 40)} removed (its content put aside)`],
|
|
43
43
|
[/^\/api\/secrets$/, 'asset', (m, b) => `Secret ${clip(b.name, 40)} set`],
|
|
44
44
|
[/^\/api\/secrets\/([^/]+)\/remove$/, 'asset', (m) => `Secret ${clip(m[1], 40)} removed`],
|
|
45
|
+
/* Never the value: only that it was replaced, and the expiry. */
|
|
46
|
+
[/^\/api\/secrets\/([^/]+)\/replace$/, 'asset', (m, b) => `Secret ${clip(m[1], 40)}: ${[...(b.value ? ['value replaced'] : []), ...(b.expires === undefined ? [] : [b.expires ? `expires ${clip(b.expires, 10)}` : 'no expiry'])].join(', ') || 'unchanged'}`],
|
|
45
47
|
[/^\/api\/secrets\/([^/]+)\/rename$/, 'asset', (m, b) => `Secret ${clip(m[1], 40)} renamed ${clip(b.name, 40)}`],
|
|
46
48
|
[/^\/api\/git\/([^/]+)\/push$/, 'asset', (m, b) => `${clip(decodeURIComponent(m[1]), 40)}: a commit sent${b.target ? ` to ${clip(b.target, 40)}` : ''}`],
|
|
47
49
|
[/^\/api\/mailboxes$/, 'asset', (m, b) => `Mailbox ${clip(b.name, 40)} added`],
|
package/server/gitchecks.mjs
CHANGED
|
@@ -142,11 +142,13 @@ export class GitChecks {
|
|
|
142
142
|
if (!hook && !command) return { ...base, status: 'none', output: 'No check is set: no pre-push hook asked for, no check command.' };
|
|
143
143
|
const machine = wanted === undefined ? await this.machineFor(repository) : (await this.runs(wanted, repository) ? wanted : undefined);
|
|
144
144
|
if (!machine) return { ...base, status: 'unavailable', output: 'No machine that has this repository attached is running: the checks could not run. Open a conversation it is attached to, then look again.' };
|
|
145
|
+
const began = Date.now();
|
|
145
146
|
const line = `refs/heads/${branch} ${head} refs/heads/${target} ${remoteTip ?? ZERO}`;
|
|
146
147
|
const r = await this.#vms.exec(machine, ['timeout', '-k', '10', String(seconds), 'sh', '-c', SCRIPT, 'clavarium-check', `/resources/${repository}`, head, line, String(remote ?? ''), command, hook ? 'yes' : 'no'],
|
|
147
148
|
{ timeoutMs: (seconds + 60) * 1000 }).catch((error) => ({ code: -1, stdout: '', stderr: String(error?.message ?? error) }));
|
|
148
149
|
const output = printable(`${r.stdout ?? ''}${r.stderr ?? ''}`).trim();
|
|
149
|
-
|
|
150
|
+
/* `ms`: how long they ran, so that the next run can say about how long it takes. */
|
|
151
|
+
const said = (status, why) => ({ ...base, machine, status, ms: Date.now() - began, output: why ? `${why}${output ? `\n${output}` : ''}` : output });
|
|
150
152
|
if (r.code === 0) return said('passed');
|
|
151
153
|
if (r.code === NOTHING) return said('none', 'Nothing was checked: this repository has no pre-push hook, and no check command is set.');
|
|
152
154
|
if (r.code === TIMED_OUT || r.code === 137) return said('failed', `Stopped after ${seconds} seconds, the time limit.`);
|
package/server/gitkeeper.mjs
CHANGED
|
@@ -270,6 +270,7 @@ export class GitKeeper {
|
|
|
270
270
|
/* The newest checks of the repository, whatever their target. */
|
|
271
271
|
checks: [...(this.#results.get(r.name)?.values() ?? [])].sort((x, y) => String(y.at ?? '').localeCompare(String(x.at ?? '')))[0] ?? null,
|
|
272
272
|
last: this.lastChecks(r.name),
|
|
273
|
+
running: this.runningChecks(r.name),
|
|
273
274
|
read: record.lastRead ?? null,
|
|
274
275
|
blocked: Object.keys(record.blocked ?? {}),
|
|
275
276
|
log: record.log ?? [],
|
|
@@ -497,7 +498,7 @@ export class GitKeeper {
|
|
|
497
498
|
const key = `${name}\n${seen.head}\n${seen.target ?? ''}`;
|
|
498
499
|
let entry = this.#inFlight.get(key);
|
|
499
500
|
if (!entry || (entry.done && !join)) {
|
|
500
|
-
const made = { done: false };
|
|
501
|
+
const made = { done: false, since: this.#now().toISOString(), head: seen.head, target: seen.target ?? '' };
|
|
501
502
|
made.run = this.#check(name, seen).finally(() => { made.done = true; setTimeout(() => { if (this.#inFlight.get(key) === made) this.#inFlight.delete(key); }, CHECK_KEEP_MS).unref?.(); });
|
|
502
503
|
this.#inFlight.set(key, made);
|
|
503
504
|
entry = made;
|
|
@@ -526,11 +527,15 @@ export class GitKeeper {
|
|
|
526
527
|
#keepLast(name, result) {
|
|
527
528
|
if (!this.#last) return;
|
|
528
529
|
const target = typeof result.target === 'string' ? result.target : '';
|
|
529
|
-
const kept = { status: result.status, head: result.head ?? null, branch: result.branch ?? null, target: target || null, at: result.at, machine: result.machine ?? null, output: String(result.output ?? '').slice(-LAST_OUTPUT_MAX) };
|
|
530
|
+
const kept = { status: result.status, head: result.head ?? null, branch: result.branch ?? null, target: target || null, at: result.at, machine: result.machine ?? null, ...(Number.isFinite(result.ms) ? { ms: result.ms } : {}), output: String(result.output ?? '').slice(-LAST_OUTPUT_MAX) };
|
|
530
531
|
const before = Object.entries(this.#last.get(name)?.targets ?? {}).filter(([t]) => t !== target);
|
|
531
532
|
const targets = Object.fromEntries([...before, [target, kept]].sort((a, b) => String(b[1].at).localeCompare(String(a[1].at))).slice(0, LAST_TARGETS));
|
|
532
533
|
try { this.#last.put({ name, targets }); } catch { /* kept in memory still: a full disk does not stop the checks */ }
|
|
533
534
|
}
|
|
535
|
+
/* The checks running now for this repository: [{ head, target, since }] (a page that comes back follows them). */
|
|
536
|
+
runningChecks(name) {
|
|
537
|
+
return [...this.#inFlight.entries()].filter(([key, e]) => key.startsWith(`${name}\n`) && !e.done).map(([, e]) => ({ head: e.head, target: e.target, since: e.since }));
|
|
538
|
+
}
|
|
534
539
|
/* [{ status, head, branch, target, at, machine, output, outdated }], the newest first. */
|
|
535
540
|
lastChecks(name) {
|
|
536
541
|
const targets = this.#last?.get(name)?.targets ?? {};
|
package/server/guide.mjs
CHANGED
|
@@ -207,7 +207,7 @@ export class Guide {
|
|
|
207
207
|
const type = this.#resources.get(r.name)?.type ?? 'folder';
|
|
208
208
|
return { name: r.name, access: r.access, type, origin: type === 'git' && this.#resources.hasOrigin?.(r.name) ? originFolder(r.name) : undefined };
|
|
209
209
|
});
|
|
210
|
-
return ownText({ name, tool: this.#tool(c)?.label ?? c.tool, workKept: c.work === 'kept', resources, chat: Boolean(this.#chat(name)), online: c.offline !== true, secrets: this.#secrets?.of(name) ?? [], lines: this.lines(name) });
|
|
210
|
+
return ownText({ name, tool: this.#tool(c)?.label ?? c.tool, workKept: c.work === 'kept', resources, chat: Boolean(this.#chat(name)), online: c.offline !== true, secrets: (this.#secrets?.given ?? this.#secrets?.of)?.call(this.#secrets, name) ?? [], lines: this.lines(name) });
|
|
211
211
|
}
|
|
212
212
|
|
|
213
213
|
/* What the page shows: the exact texts, where each is, and the line in the tool's own file. */
|
package/server/health.mjs
CHANGED
|
@@ -23,6 +23,10 @@
|
|
|
23
23
|
/* The command run inside the machine. Its arguments are the paths that
|
|
24
24
|
should be mounted; they are passed as arguments, never parsed by the
|
|
25
25
|
shell. It prints one fact per line; the server reads only these lines. */
|
|
26
|
+
import { SHARING_STEP } from './vm.mjs';
|
|
27
|
+
|
|
28
|
+
/* How long installing the shared-folder helper in a machine may take (it comes from the snap store). */
|
|
29
|
+
export const SHARING_MS = 180_000;
|
|
26
30
|
export const PROBE = [
|
|
27
31
|
'awk \'/^MemTotal:/{t=$2} /^MemAvailable:/{a=$2} END{print "memory", t+0, a+0}\' /proc/meminfo',
|
|
28
32
|
'awk \'$1=="oom_kill"{n=$2} END{print "oom", n+0}\' /proc/vmstat',
|
|
@@ -188,8 +192,16 @@ export class Health {
|
|
|
188
192
|
/* Looked at again just before acting: never on a machine that went to sleep meanwhile. */
|
|
189
193
|
const still = loose();
|
|
190
194
|
if (still.length > 0 && this.#conversations.get(name)?.phase === 'ready' && (await this.#vms.state(name).catch(() => undefined)) === 'Running') {
|
|
195
|
+
/* A machine whose shared-folder helper went missing (the VM manager says to install
|
|
196
|
+
multipass-sshfs in it): installed once, as at its start, then the folder tried again. */
|
|
197
|
+
let helped = false;
|
|
191
198
|
for (const path of still) {
|
|
192
|
-
|
|
199
|
+
let why = await this.#resources.repair(name, path).catch((error) => error.message);
|
|
200
|
+
if (why && /multipass-sshfs/.test(why) && !helped) {
|
|
201
|
+
helped = true;
|
|
202
|
+
const put = await this.#vms.exec(name, [...SHARING_STEP], { timeoutMs: SHARING_MS }).catch(() => ({ code: -1 }));
|
|
203
|
+
if (put.code === 0) why = await this.#resources.repair(name, path).catch((error) => error.message);
|
|
204
|
+
}
|
|
193
205
|
if (why) failed.push({ path, why });
|
|
194
206
|
}
|
|
195
207
|
facts = (await this.#probe(name, paths)) ?? facts;
|
package/server/main.mjs
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* node server/main.mjs --command "your-tool" --cwd /path/to/work
|
|
13
13
|
* no VM: one tool on this machine, at /?c=<name>. For development.
|
|
14
14
|
*/
|
|
15
|
-
import { readFileSync } from 'node:fs';
|
|
15
|
+
import { readFileSync, readdirSync } from 'node:fs';
|
|
16
16
|
import { createHash } from 'node:crypto';
|
|
17
17
|
import { createServer } from 'node:http';
|
|
18
18
|
import { readFile } from 'node:fs/promises';
|
|
@@ -107,6 +107,14 @@ export const FILES = {
|
|
|
107
107
|
'/vendor/prism.js': [['web/prism-manual.js', ...['core', 'clike', 'markup', 'css', 'javascript', 'typescript', 'json', 'python', 'bash', 'markup-templating', 'php', 'sql', 'yaml', 'diff', 'markdown', 'ini', 'apacheconf']
|
|
108
108
|
.map((l) => packageFile('prismjs', `components/prism-${l}.min.js`))], 'text/javascript; charset=utf-8'],
|
|
109
109
|
};
|
|
110
|
+
/* Formulas in the chat are drawn by Parley with its own copy of KaTeX, loaded on the first formula
|
|
111
|
+
(the page tells it where: /vendor/katex/katex.mjs): served as Parley ships it, fonts included. */
|
|
112
|
+
try {
|
|
113
|
+
const katex = packageFile(PARLEY, 'ui/vendor/katex');
|
|
114
|
+
FILES['/vendor/katex/katex.mjs'] = [`${katex}/katex.mjs`, 'text/javascript; charset=utf-8'];
|
|
115
|
+
FILES['/vendor/katex/katex.min.css'] = [`${katex}/katex.min.css`, 'text/css; charset=utf-8'];
|
|
116
|
+
for (const font of readdirSync(`${katex}/fonts`)) if (/^[\w.-]+\.woff2$/.test(font)) FILES[`/vendor/katex/fonts/${font}`] = [`${katex}/fonts/${font}`, 'font/woff2'];
|
|
117
|
+
} catch { /* a Parley without it: formulas shown as their text */ }
|
|
110
118
|
/* The device door serves the same files under /c/: that prefix is the only
|
|
111
119
|
one the edge lets through without sign-on. Its page differs; nothing else. */
|
|
112
120
|
const DEVICE_FILES = Object.fromEntries(Object.entries(FILES).filter(([path]) => path !== '/').map(([path, file]) => [`/c${path}`, file]));
|
|
@@ -292,6 +300,10 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
292
300
|
const secrets = new Secrets({ store: new Store(`${dataDir}/secrets.json`), vault, vms, grants });
|
|
293
301
|
/* A secret renamed: what names it follows (the key of dictation). `voice` is made below. */
|
|
294
302
|
secrets.renamed = (from, to) => voice.secretRenamed(from, to);
|
|
303
|
+
/* Expired: kept, no longer delivered; said once in What happened. */
|
|
304
|
+
secrets.expired = (name, users) => { events.add({ kind: 'asset', text: `Secret ${name} expired: no longer given${users.length ? ` to ${users.join(', ')}` : ''}` }); };
|
|
305
|
+
secrets.check();
|
|
306
|
+
const expiryTimer = setInterval(() => secrets.check(), 10 * 60_000); expiryTimer.unref();
|
|
295
307
|
const signin = new SignInMailboxes({ store: new Store(`${dataDir}/signin.json`), vault, rules: (name) => all.signinRules(name) });
|
|
296
308
|
/* Each opening: the runner and the attached secrets are put in the VM,
|
|
297
309
|
and the tool is started through the runner. */
|
|
@@ -316,6 +328,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
316
328
|
const parleySaid = new Map();
|
|
317
329
|
all.prepare = async (name, woke) => {
|
|
318
330
|
await hostReady;
|
|
331
|
+
secrets.check();
|
|
319
332
|
const wanted = secrets.signature(name);
|
|
320
333
|
const rules = network.apply();
|
|
321
334
|
if (woke || delivered.get(name) !== wanted) {
|
|
@@ -467,7 +480,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
467
480
|
const watching = setInterval(() => { void team.watch().catch(() => {}); }, 60_000); watching.unref?.();
|
|
468
481
|
}
|
|
469
482
|
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, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
|
|
470
|
-
server.on('close', () => { closing = true; clearInterval(historyTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
|
|
483
|
+
server.on('close', () => { closing = true; clearInterval(historyTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
|
|
471
484
|
let closing = false;
|
|
472
485
|
bridge = attachBridge(server, {
|
|
473
486
|
onRejoin: (name) => all.rejoin(name),
|
package/server/secrets.mjs
CHANGED
|
@@ -12,6 +12,10 @@
|
|
|
12
12
|
* never in a log, never back to a browser: once saved, a value cannot be
|
|
13
13
|
* read again from the page, only replaced.
|
|
14
14
|
*
|
|
15
|
+
* EXPIRY (optional, a day, like a token's): from that day on the secret is
|
|
16
|
+
* kept -- never deleted by itself -- but no longer delivered; WARN_DAYS
|
|
17
|
+
* before, the page says it is near. Days are those of this server's clock.
|
|
18
|
+
*
|
|
15
19
|
* WHAT IT IS NOT: protected from the tool. The agent is root in its VM and
|
|
16
20
|
* can read and send anywhere whatever is delivered there. A secret the host
|
|
17
21
|
* should use on the agent's behalf (a push key, a mailbox password) does not
|
|
@@ -25,6 +29,9 @@ import { VM_USER } from './vm.mjs';
|
|
|
25
29
|
export const SECRETS_DIR = '/run/secrets';
|
|
26
30
|
export const RUNNER = '/usr/local/bin/clv-run';
|
|
27
31
|
export const VALUE_MAX = 8 * 1024;
|
|
32
|
+
export const WARN_DAYS = 7;
|
|
33
|
+
const DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
34
|
+
const DAY_MS = 86_400_000;
|
|
28
35
|
const NAME = /^[A-Z][A-Z0-9_]{0,39}$/;
|
|
29
36
|
/* Names the tool's own start depends on must not be replaced by a secret. */
|
|
30
37
|
const RESERVED = new Set(['PATH', 'HOME', 'USER', 'SHELL', 'TERM', 'LANG', 'PWD', 'IFS', 'LD_PRELOAD', 'LD_LIBRARY_PATH']);
|
|
@@ -45,15 +52,29 @@ done
|
|
|
45
52
|
exec "$@"
|
|
46
53
|
`;
|
|
47
54
|
|
|
55
|
+
/* A day as YYYY-MM-DD, or '' / null for none; anything else is refused. */
|
|
56
|
+
export function expiryOf(value) {
|
|
57
|
+
if (value === undefined || value === null || value === '') return null;
|
|
58
|
+
const m = DAY.exec(String(value));
|
|
59
|
+
const d = m && new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
|
|
60
|
+
if (!d || d.toISOString().slice(0, 10) !== value || Number(m[1]) < 2000) throw new Refusal(400, 'An expiry is a day, as YYYY-MM-DD.');
|
|
61
|
+
return value;
|
|
62
|
+
}
|
|
63
|
+
/* Whole days from today (this server's local day) to that day: 0 or less, expired. */
|
|
64
|
+
export function daysTo(day, now = new Date()) {
|
|
65
|
+
const m = DAY.exec(day);
|
|
66
|
+
return Math.round((Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])) - Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())) / DAY_MS);
|
|
67
|
+
}
|
|
68
|
+
|
|
48
69
|
const firstLine = (text) => String(text ?? '').trim().split('\n').filter(Boolean).pop()?.slice(0, 200) ?? '';
|
|
49
70
|
|
|
50
71
|
export class Secrets {
|
|
51
|
-
#store; #vault; #vms; #grants;
|
|
72
|
+
#store; #vault; #vms; #grants; #now;
|
|
52
73
|
|
|
53
74
|
/* `grants`: the one table of rights. "Handed to a conversation" is a
|
|
54
75
|
line of it: the conversation may USE the secret. */
|
|
55
|
-
constructor({ store, vault, vms, grants = new Grants() }) {
|
|
56
|
-
this.#store = store; this.#vault = vault; this.#vms = vms; this.#grants = grants;
|
|
76
|
+
constructor({ store, vault, vms, grants = new Grants(), now = () => new Date() }) {
|
|
77
|
+
this.#store = store; this.#vault = vault; this.#vms = vms; this.#grants = grants; this.#now = now;
|
|
57
78
|
for (const s of store.all()) {
|
|
58
79
|
if (s.attachments === undefined) continue;
|
|
59
80
|
for (const conversation of Object.keys(s.attachments)) this.#grants.give(conversationSubject(conversation), `secret:${s.name}`, 'x');
|
|
@@ -61,25 +82,74 @@ export class Secrets {
|
|
|
61
82
|
}
|
|
62
83
|
}
|
|
63
84
|
#handed(conversation, name) { return this.#grants.can(conversationSubject(conversation), `secret:${name}`, 'x'); }
|
|
85
|
+
#expired(s) { return Boolean(s.expires) && daysTo(s.expires, this.#now()) <= 0; }
|
|
86
|
+
#users(name) { return this.#grants.on(`secret:${name}`).map((g) => g.subject.slice('conversation:'.length)); }
|
|
87
|
+
/* What is delivered to this conversation: handed, and not expired. */
|
|
88
|
+
#given(conversation) { return this.#store.all().filter((s) => this.#handed(conversation, s.name) && !this.#expired(s)); }
|
|
64
89
|
|
|
65
|
-
/* Names
|
|
66
|
-
|
|
90
|
+
/* Names, where they are attached, the expiry. Never a value. `days`: whole
|
|
91
|
+
days left (null without an expiry); `expired`: no longer delivered. */
|
|
92
|
+
list() {
|
|
93
|
+
return this.#store.all().map((s) => ({ name: s.name, conversations: this.#users(s.name), createdAt: s.createdAt,
|
|
94
|
+
expires: s.expires ?? null, days: s.expires ? daysTo(s.expires, this.#now()) : null, expired: this.#expired(s) }));
|
|
95
|
+
}
|
|
96
|
+
/* Handed to it, expired or not (its Assets show both). */
|
|
67
97
|
of(conversation) { return this.#store.all().filter((s) => this.#handed(conversation, s.name)).map((s) => s.name); }
|
|
98
|
+
/* Delivered to it at its next start. */
|
|
99
|
+
given(conversation) { return this.#given(conversation).map((s) => s.name); }
|
|
68
100
|
|
|
69
101
|
/* The value, for this server's own use only (the key of the dictation
|
|
70
102
|
engine, put in a request's header): never returned by any route. */
|
|
71
103
|
reveal(name) { const s = this.#store.get(name); return s ? this.#vault.open(s.sealed) : undefined; }
|
|
72
104
|
|
|
73
|
-
/* Creates, or replaces the value of, a secret.
|
|
74
|
-
|
|
105
|
+
/* Creates, or replaces the value of, a secret. `expires`: a day, '' for
|
|
106
|
+
none, left out to keep the one it had. */
|
|
107
|
+
set({ name, value, expires }) {
|
|
75
108
|
if (!isSecretName(name)) throw new Refusal(400, 'A secret is named like a variable: capitals, digits and underscores, starting with a letter.');
|
|
76
|
-
|
|
77
|
-
|
|
109
|
+
const sealed = this.#seal(value);
|
|
110
|
+
const day = expires === undefined ? undefined : expiryOf(expires);
|
|
78
111
|
const before = this.#store.get(name);
|
|
79
|
-
this.#
|
|
112
|
+
this.#write({ ...before, name, sealed, createdAt: before?.createdAt ?? new Date().toISOString() }, day);
|
|
80
113
|
return { name };
|
|
81
114
|
}
|
|
82
115
|
|
|
116
|
+
/* REPLACED in place, without being seen: a new value (empty keeps the
|
|
117
|
+
one it has) and/or a new expiry ('' removes it). Its name and the
|
|
118
|
+
conversations it is handed to stay; they get it at their next start. */
|
|
119
|
+
replace(name, { value, expires } = {}) {
|
|
120
|
+
const before = this.#store.get(name);
|
|
121
|
+
if (!before) throw new Refusal(404, 'No such secret.');
|
|
122
|
+
const keep = value === undefined || value === null || value === '';
|
|
123
|
+
const day = expires === undefined ? undefined : expiryOf(expires);
|
|
124
|
+
if (keep && day === undefined) throw new Refusal(400, 'Nothing to change: a new value or an expiry.');
|
|
125
|
+
this.#write({ ...before, sealed: keep ? before.sealed : this.#seal(value) }, day);
|
|
126
|
+
return { name, expires: this.#store.get(name).expires ?? null };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
#seal(value) {
|
|
130
|
+
if (typeof value !== 'string' || value === '' || Buffer.byteLength(value) > VALUE_MAX) throw new Refusal(400, `A value is between 1 byte and ${VALUE_MAX / 1024} KB.`);
|
|
131
|
+
if (value.includes('\0')) throw new Refusal(400, 'A value cannot contain a null byte.');
|
|
132
|
+
return this.#vault.seal(value);
|
|
133
|
+
}
|
|
134
|
+
/* `day`: undefined keeps the expiry, null removes it. */
|
|
135
|
+
#write(record, day) {
|
|
136
|
+
const next = { ...record };
|
|
137
|
+
if (day !== undefined) { if (day) next.expires = day; else delete next.expires; }
|
|
138
|
+
this.#store.put(next);
|
|
139
|
+
this.check();
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/* Said once, when it expires (`expired(name, conversations)`): remembered
|
|
143
|
+
with the day said, so a new expiry is said again when it comes. */
|
|
144
|
+
check() {
|
|
145
|
+
for (const s of this.#store.all()) {
|
|
146
|
+
if (!this.#expired(s) || s.expiredSaid === s.expires) continue;
|
|
147
|
+
this.#store.patch(s.name, { expiredSaid: s.expires });
|
|
148
|
+
try { this.expired(s.name, this.#users(s.name)); } catch { /* said nowhere: never a reason to fail */ }
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
expired = () => {};
|
|
152
|
+
|
|
83
153
|
/* RENAMED: its value (still sealed, never opened) and the conversations it is handed to go with
|
|
84
154
|
it; `renamed(from, to)` tells what else names it (dictation's key). Delivered under its new
|
|
85
155
|
name at each conversation's next start. */
|
|
@@ -118,12 +188,13 @@ export class Secrets {
|
|
|
118
188
|
/* What a delivery to this conversation would contain, as one string that
|
|
119
189
|
changes whenever a delivery would differ: names and sealed values. */
|
|
120
190
|
signature(conversation) {
|
|
121
|
-
return this.#
|
|
191
|
+
return this.#given(conversation).map((s) => `${s.name}=${s.sealed}`).sort().join('|');
|
|
122
192
|
}
|
|
123
193
|
|
|
124
|
-
/* Puts in the VM exactly the secrets attached NOW, and the
|
|
125
|
-
each time the conversation is opened: a detached
|
|
126
|
-
the VM, a new one appears, and a
|
|
194
|
+
/* Puts in the VM exactly the secrets attached NOW and not expired, and the
|
|
195
|
+
runner. Called each time the conversation is opened: a detached or
|
|
196
|
+
expired secret disappears from the VM, a new one appears, and a
|
|
197
|
+
restarted VM gets them back. */
|
|
127
198
|
async deliver(conversation) {
|
|
128
199
|
const run = async (argv, input) => {
|
|
129
200
|
const r = await this.#vms.exec(conversation, argv, { input });
|
|
@@ -132,8 +203,7 @@ export class Secrets {
|
|
|
132
203
|
await run(['sudo', '-n', 'install', '-m', '0755', '/dev/stdin', RUNNER], RUNNER_SCRIPT);
|
|
133
204
|
await run(['sudo', '-n', 'install', '-d', '-m', '0755', SECRETS_DIR]);
|
|
134
205
|
await run(['sudo', '-n', 'find', SECRETS_DIR, '-mindepth', '1', '-delete']);
|
|
135
|
-
for (const secret of this.#
|
|
136
|
-
if (!this.#handed(conversation, secret.name)) continue;
|
|
206
|
+
for (const secret of this.#given(conversation)) {
|
|
137
207
|
await run(['sudo', '-n', 'install', '-m', '0600', '-o', VM_USER, '-g', VM_USER, '/dev/stdin', `${SECRETS_DIR}/${secret.name}`], this.#vault.open(secret.sealed));
|
|
138
208
|
}
|
|
139
209
|
}
|
package/server/talk.mjs
CHANGED
|
@@ -371,7 +371,7 @@ export class Talk {
|
|
|
371
371
|
return { ...this.of(name), invited: text };
|
|
372
372
|
}
|
|
373
373
|
|
|
374
|
-
async say(name, text, answers, files, via) {
|
|
374
|
+
async say(name, text, answers, files, via, extra) {
|
|
375
375
|
if (!this.of(name).on) throw new Refusal(409, 'Talking through the app is not turned on for this conversation.');
|
|
376
376
|
const given = files === undefined || files === null ? [] : files;
|
|
377
377
|
if (!Array.isArray(given) || given.length > FILES_MAX) throw new Refusal(400, `A message has ${FILES_MAX} files at most.`);
|
|
@@ -386,7 +386,7 @@ export class Talk {
|
|
|
386
386
|
const note = item && typeof item === 'object' && typeof item.note === 'string' ? item.note : '';
|
|
387
387
|
return { path, name: m[2], size: info.size, ...(note ? { note } : {}) };
|
|
388
388
|
});
|
|
389
|
-
try { this.#parley(name).say(text ?? '', answers, attached, { via: via === 'voice' ? 'voice' : undefined }); } catch (error) { if (error instanceof RangeError) throw new Refusal(400, error.message); throw error; }
|
|
389
|
+
try { this.#parley(name).say(text ?? '', answers, attached, { via: via === 'voice' ? 'voice' : undefined, ...(extra && typeof extra === 'object' ? { picked: extra.picked, replies: extra.replies, about: extra.about } : {}) }); } catch (error) { if (error instanceof RangeError) throw new Refusal(400, error.message); throw error; }
|
|
390
390
|
const told = await this.#wake(name);
|
|
391
391
|
return { ...this.of(name), told };
|
|
392
392
|
}
|