clavarium 0.2.7 → 0.2.8-next.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/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/api.mjs +43 -4
- package/server/bundle.mjs +137 -0
- package/server/events.mjs +119 -0
- package/server/main.mjs +18 -6
- package/server/setup.mjs +14 -4
- package/web/app.js +31 -0
- package/web/index.html +17 -1
- package/web/links.js +31 -2
- package/web/style.css +13 -0
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.8-next.1",
|
|
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.8-next.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
package/package.json
CHANGED
package/server/api.mjs
CHANGED
|
@@ -70,6 +70,7 @@
|
|
|
70
70
|
* GET /api/machines/places GET /api/machines/moving POST /api/machines/move {to}: all the machines to another disk
|
|
71
71
|
* POST /api/machines/forget-old: the copy a move left behind, removed
|
|
72
72
|
* GET /api/machines/disks: every disk, whole POST /api/machines/mount {path} POST /api/machines/prepare {path, typed}: erased
|
|
73
|
+
* GET /api/events?kind=&conversation=&q=&before=&limit= what happened, newest first
|
|
73
74
|
* GET /api/history?of=server|<name>&span=1h|24h|7d the curves of memory, CPU and disk (and the reserve, for the server)
|
|
74
75
|
* GET /api/server/logs?source=&span= what the server's programs said POST /api/server/restart
|
|
75
76
|
* GET /api/operators who may sign in POST /api/operators {email} -> {email, password}: shown once
|
|
@@ -89,7 +90,9 @@
|
|
|
89
90
|
* POST /api/flows/name {around, name}: a flow named by the owner ('' gives it back its own)
|
|
90
91
|
* POST /api/setup/export {flow?} -> {name, text}: the configuration as one file, never the data
|
|
91
92
|
* POST /api/setup/preview {text, choices?}: what an import would do, said before anything is done
|
|
92
|
-
* POST /api/setup/import {text, choices?}: made in the background; GET says how far it is
|
|
93
|
+
* POST /api/setup/import {text, choices?, bundle?}: made in the background; GET says how far it is
|
|
94
|
+
* GET /api/setup/bundle?flow= the flow WITH the files of its folders, a .tar.gz (bundle.mjs) &stats=1: their sizes only
|
|
95
|
+
* POST /api/setup/bundle the body IS such a file -> {id, text, folders}: then preview and import with {bundle: id}
|
|
93
96
|
* POST /api/setup/pair {label}: what a device to pair will get (the code is made by /api/shares)
|
|
94
97
|
* POST /api/setup/drop {id}: something an import waits for, not wanted after all
|
|
95
98
|
* GET /api/files/download?c=...&r=...&p=<path> one file
|
|
@@ -125,10 +128,10 @@ function readBody(request, max = BODY_MAX) {
|
|
|
125
128
|
}
|
|
126
129
|
|
|
127
130
|
/* Returns true when the request was an API request (answered here). */
|
|
128
|
-
export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, 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) {
|
|
131
|
+
export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, 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) {
|
|
129
132
|
const { pathname } = new URL(request.url ?? '/', 'http://local');
|
|
130
133
|
if (!pathname.startsWith('/api/')) return false;
|
|
131
|
-
|
|
134
|
+
let send = (status, body) => {
|
|
132
135
|
response.writeHead(status, { ...headers, 'content-type': 'application/json; charset=utf-8' }).end(JSON.stringify(body));
|
|
133
136
|
};
|
|
134
137
|
/* Files are reached THROUGH a conversation: only a folder attached to it,
|
|
@@ -136,6 +139,8 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
136
139
|
const query = new URL(request.url ?? '/', 'http://local').searchParams;
|
|
137
140
|
/* Who asks (behind the edge; '' on this machine alone): see gate.mjs. */
|
|
138
141
|
const identity = String(request.headers['x-forwarded-email'] ?? '').trim().toLowerCase();
|
|
142
|
+
/* A sign-in, said once in a while for the same person (events.mjs). */
|
|
143
|
+
events?.seen(identity);
|
|
139
144
|
const attached = (need) => {
|
|
140
145
|
/* The conversation's own work folder, when the server keeps it. */
|
|
141
146
|
if (query.get('r') === WORK_TAB && resources) {
|
|
@@ -228,6 +233,15 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
228
233
|
/* Who may sign in (operators.mjs): none in local mode. */
|
|
229
234
|
const reactOf = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
|
|
230
235
|
if (reactOf && reacting) return send(200, reacting.settings(decodeURIComponent(reactOf[1]))), true;
|
|
236
|
+
if (pathname === '/api/events' && events) {
|
|
237
|
+
const ask = { kind: query.get('kind') ?? '', conversation: query.get('conversation') ?? '', q: query.get('q') ?? '', before: query.get('before') ?? '', limit: Math.min(1000, Number(query.get('limit')) || 200) };
|
|
238
|
+
const said = events.list(ask);
|
|
239
|
+
/* What the updater did is in its own history (updates.mjs): said here too, as it said it. */
|
|
240
|
+
const words = { done: 'done', failed: 'failed', 'rolled-back': 'did not work: went back' };
|
|
241
|
+
const updated = !ask.conversation && (!ask.kind || ask.kind === 'update') ? (updates?.about().history ?? []).map((h) => ({ at: h.at, kind: 'update', text: `${h.action === 'rollback' ? 'Back' : 'Update'} ${h.from ?? '?'} → ${h.to ?? '?'}: ${words[h.result] ?? h.result ?? ''}${h.why ? ` (${h.why})` : ''}` }))
|
|
242
|
+
.filter((e) => e.at && (!ask.before || e.at < ask.before) && (!ask.q || e.text.toLowerCase().includes(ask.q.toLowerCase()))) : [];
|
|
243
|
+
return send(200, [...said, ...updated].sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : 0)).slice(0, ask.limit)), true;
|
|
244
|
+
}
|
|
231
245
|
if (pathname === '/api/history' && history) {
|
|
232
246
|
const of = query.get('of') ?? 'server';
|
|
233
247
|
if (of !== 'server' && !conversations.list().some((c) => c.name === of)) throw new Refusal(404, 'No such conversation.');
|
|
@@ -255,6 +269,16 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
255
269
|
if (pathname === '/api/alerts' && alerts) return send(200, alerts.about()), true;
|
|
256
270
|
if (pathname === '/api/flows' && setup) return send(200, setup.graph()), true;
|
|
257
271
|
if (pathname === '/api/setup/import' && setup) return send(200, setup.job()), true;
|
|
272
|
+
if (pathname === '/api/setup/bundle' && setup && bundles) {
|
|
273
|
+
const flow = query.get('flow') || undefined;
|
|
274
|
+
const made = setup.exportText({ flow });
|
|
275
|
+
const folders = JSON.parse(made.text).nodes.filter((n) => n.kind === 'folder').map((n) => n.name);
|
|
276
|
+
if (query.get('stats') === '1') return send(200, { name: made.name, folders: bundles.folderStats(folders) }), true;
|
|
277
|
+
const file = `${(made.name || 'setup').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'setup'}.clavarium.tar.gz`;
|
|
278
|
+
response.writeHead(200, { ...headers, 'content-type': 'application/gzip', 'content-disposition': `attachment; filename="${file}"` });
|
|
279
|
+
await bundles.pack(made.text, folders, response).catch((error) => { console.error(`bundle: ${error.message}`); response.destroy(); });
|
|
280
|
+
return true;
|
|
281
|
+
}
|
|
258
282
|
const looked = /^\/api\/conversations\/([^/]+)\/health$/.exec(pathname);
|
|
259
283
|
if (looked && health) return send(200, health.of(decodeURIComponent(looked[1]))), true;
|
|
260
284
|
/* The words of the chat screen, for a screen whose language is `lang`; and the owner's choice of them. */
|
|
@@ -294,10 +318,18 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
294
318
|
if (!originOk(request.headers) || request.headers['content-type'] !== 'application/octet-stream') return send(403, { error: 'This request does not come from this site.' }), true;
|
|
295
319
|
return send(201, await talk.attach(decodeURIComponent(attaching[1]), query.get('name') ?? '', request)), true;
|
|
296
320
|
}
|
|
321
|
+
/* A flow with its files, sent from the page: the body is the .tar.gz. */
|
|
322
|
+
if (pathname === '/api/setup/bundle' && setup && bundles) {
|
|
323
|
+
if (!originOk(request.headers) || request.headers['content-type'] !== 'application/octet-stream') return send(403, { error: 'This request does not come from this site.' }), true;
|
|
324
|
+
const got = await bundles.receive(request);
|
|
325
|
+
try { return send(200, { id: got.id, bytes: got.bytes, ...bundles.open(got.id) }), true; } catch (error) { bundles.forget(got.id); throw error; }
|
|
326
|
+
}
|
|
297
327
|
if (!originOk(request.headers) || !String(request.headers['content-type'] ?? '').startsWith('application/json')) {
|
|
298
328
|
return send(403, { error: 'This request does not come from this site.' }), true;
|
|
299
329
|
}
|
|
300
330
|
const body = await readBody(request, pathname === '/api/setup/preview' || pathname === '/api/setup/import' ? SETUP_BODY_MAX : BODY_MAX);
|
|
331
|
+
/* What was done, once it was done: said in What happened (events.mjs), for those worth saying. */
|
|
332
|
+
if (events) { const answer = send; send = (status, out) => { if (status < 300) { try { events.fromRequest(pathname, body, identity, out); } catch { /* never in the way */ } } answer(status, out); }; }
|
|
301
333
|
if (pathname === '/api/conversations') { await conversations.admit?.(body); return send(201, conversations.create(body)), true; }
|
|
302
334
|
/* Who gets what, and a whole setup in one file: see setup.mjs. */
|
|
303
335
|
if (pathname.startsWith('/api/setup/') || pathname === '/api/flows/name') {
|
|
@@ -306,7 +338,14 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
306
338
|
if (pathname === '/api/flows/name') return send(200, setup.rename(body.around, body.name)), true;
|
|
307
339
|
if (pathname === '/api/setup/export') return send(200, setup.exportText({ flow: typeof body.flow === 'string' ? body.flow : undefined })), true;
|
|
308
340
|
if (pathname === '/api/setup/preview') return send(200, setup.preview(body.text, choices)), true;
|
|
309
|
-
if (pathname === '/api/setup/import')
|
|
341
|
+
if (pathname === '/api/setup/import') {
|
|
342
|
+
/* With the files of a flow sent before: each new folder gets its own, then the file sent goes. */
|
|
343
|
+
const id = typeof body.bundle === 'string' ? body.bundle : null;
|
|
344
|
+
const fill = id && bundles && resources ? (fileName, name) => bundles.fill(id, fileName, resources.folder(name)) : null;
|
|
345
|
+
const started = setup.start(body.text, choices, { fill });
|
|
346
|
+
if (id) void setup.done?.finally(() => bundles.forget(id));
|
|
347
|
+
return send(202, started), true;
|
|
348
|
+
}
|
|
310
349
|
if (pathname === '/api/setup/pair') return send(200, setup.toPair(body.label)), true;
|
|
311
350
|
if (pathname === '/api/setup/drop') { setup.drop(body.id); return send(200, { ok: true }), true; }
|
|
312
351
|
return send(404, { error: 'Not found.' }), true;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/* A FLOW WITH ITS FILES (Access, Flows, Export with the files): the setup file
|
|
2
|
+
* (setup.mjs) and the files of the flow's folders, in one .tar.gz -- and back.
|
|
3
|
+
*
|
|
4
|
+
* flow.json the setup, as Export makes it
|
|
5
|
+
* folders/<name>/... each folder's files
|
|
6
|
+
*
|
|
7
|
+
* Only regular files and folders go in, and only those come out: a link is
|
|
8
|
+
* never followed when packing (a tool may have made one pointing anywhere),
|
|
9
|
+
* and a file holding anything else (a link, a device, an absolute path, a
|
|
10
|
+
* "..") is refused whole before anything is unpacked. Packed and unpacked by
|
|
11
|
+
* GNU tar, never as root, never keeping owners or modes from the file.
|
|
12
|
+
*
|
|
13
|
+
* folderStats(names) [{ name, files, bytes }]: what Export would take
|
|
14
|
+
* pack(text, names, out) the .tar.gz written to the stream `out`
|
|
15
|
+
* receive(stream, maxBytes) a file uploaded, kept aside -> { id, bytes }
|
|
16
|
+
* open(id) -> { text, folders: [{ name, files, bytes }] }, or refused
|
|
17
|
+
* fill(id, name, target) that folder's files put in `target`, which must be empty -> files
|
|
18
|
+
* forget(id)
|
|
19
|
+
*/
|
|
20
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
21
|
+
import { mkdirSync, mkdtempSync, writeFileSync, rmSync, readdirSync, lstatSync, createWriteStream, existsSync, statSync } from 'node:fs';
|
|
22
|
+
import { join } from 'node:path';
|
|
23
|
+
import { randomBytes } from 'node:crypto';
|
|
24
|
+
import { pipeline } from 'node:stream/promises';
|
|
25
|
+
import { Refusal } from './conversations.mjs';
|
|
26
|
+
|
|
27
|
+
const NAME = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
28
|
+
const ID = /^[a-f0-9]{24}$/;
|
|
29
|
+
export const UPLOAD_MAX = 20 * 1024 ** 3;
|
|
30
|
+
const KEEP_MS = 24 * 3600_000;
|
|
31
|
+
|
|
32
|
+
/* Every regular file and folder under `root`, as paths relative to `base`; links and the rest left out. */
|
|
33
|
+
function walk(root, base, out, stats) {
|
|
34
|
+
let names;
|
|
35
|
+
try { names = readdirSync(root); } catch { return; }
|
|
36
|
+
for (const n of names) {
|
|
37
|
+
const at = join(root, n);
|
|
38
|
+
let st; try { st = lstatSync(at); } catch { continue; }
|
|
39
|
+
if (st.isDirectory()) { out.push(at.slice(base.length + 1)); walk(at, base, out, stats); } else if (st.isFile()) { out.push(at.slice(base.length + 1)); stats.files += 1; stats.bytes += st.size; }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export class Bundles {
|
|
44
|
+
#dir; #folder; #tar;
|
|
45
|
+
/* `dir`: where uploads wait (this server's data); `folder(name)`: a folder's directory. */
|
|
46
|
+
constructor({ dir, folder, tar = 'tar' }) { this.#dir = dir; this.#folder = folder; this.#tar = tar; }
|
|
47
|
+
|
|
48
|
+
folderStats(names) {
|
|
49
|
+
return names.filter((n) => NAME.test(n)).map((name) => { const s = { files: 0, bytes: 0 }; walk(this.#folder(name), this.#folder(name), [], s); return { name, ...s }; });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async pack(text, names, out) {
|
|
53
|
+
mkdirSync(this.#dir, { recursive: true, mode: 0o700 });
|
|
54
|
+
const stage = mkdtempSync(join(this.#dir, 'pack-'));
|
|
55
|
+
try {
|
|
56
|
+
writeFileSync(join(stage, 'flow.json'), text);
|
|
57
|
+
const args = ['--create', '--gzip', '--file=-', '--no-recursion', '--null', `--directory=${stage}`, 'flow.json'];
|
|
58
|
+
for (const name of names.filter((n) => NAME.test(n))) {
|
|
59
|
+
const dir = this.#folder(name); const parent = join(dir, '..');
|
|
60
|
+
const list = [name]; walk(dir, parent, list, { files: 0, bytes: 0 });
|
|
61
|
+
/* The folder's directory has its own name on the disk: named here as it is in the setup. */
|
|
62
|
+
const real = dir.slice(parent.length + 1);
|
|
63
|
+
const files = join(stage, `${name}.list`);
|
|
64
|
+
writeFileSync(files, list.map((p) => (p === name ? real : `${real}${p.slice(name.length)}`)).join('\0'));
|
|
65
|
+
args.push(`--directory=${parent}`, `--transform=s,^${real}\\(/\\|$\\),folders/${name}\\1,`, `--files-from=${files}`);
|
|
66
|
+
}
|
|
67
|
+
const child = spawn(this.#tar, args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
68
|
+
let said = ''; child.stderr.on('data', (d) => { said += d; });
|
|
69
|
+
const ended = new Promise((resolve) => child.on('close', resolve));
|
|
70
|
+
await pipeline(child.stdout, out);
|
|
71
|
+
const code = await ended;
|
|
72
|
+
if (code !== 0) throw new Error(`tar: ${said.trim().split('\n').pop()}`);
|
|
73
|
+
} finally { rmSync(stage, { recursive: true, force: true }); }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async receive(stream, maxBytes = UPLOAD_MAX) {
|
|
77
|
+
mkdirSync(this.#dir, { recursive: true, mode: 0o700 });
|
|
78
|
+
this.#tidy();
|
|
79
|
+
const id = randomBytes(12).toString('hex');
|
|
80
|
+
const file = join(this.#dir, `${id}.tar.gz`);
|
|
81
|
+
let bytes = 0;
|
|
82
|
+
stream.on('data', (d) => { bytes += d.length; if (bytes > maxBytes) stream.destroy(new Refusal(413, `The file is larger than ${Math.round(maxBytes / 1024 ** 3)} GB.`)); });
|
|
83
|
+
try { await pipeline(stream, createWriteStream(file, { mode: 0o600 })); } catch (error) { rmSync(file, { force: true }); throw error instanceof Refusal ? error : new Refusal(400, 'The file did not arrive whole.'); }
|
|
84
|
+
return { id, bytes };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/* What it holds, checked whole: refused at the first thing that is not a plain file or folder of ours. */
|
|
88
|
+
open(id) {
|
|
89
|
+
const file = this.#file(id);
|
|
90
|
+
const names = spawnSync(this.#tar, ['--list', '--gzip', '--quoting-style=escape', `--file=${file}`], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });
|
|
91
|
+
const kinds = spawnSync(this.#tar, ['--list', '--verbose', '--gzip', '--quoting-style=escape', `--file=${file}`], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });
|
|
92
|
+
if (names.status !== 0 || kinds.status !== 0) throw new Refusal(400, 'Not a file made by Export with the files (a .tar.gz).');
|
|
93
|
+
const list = names.stdout.split('\n').filter(Boolean); const types = kinds.stdout.split('\n').filter(Boolean);
|
|
94
|
+
if (list.length !== types.length) throw new Refusal(400, 'This file could not be read whole.');
|
|
95
|
+
const folders = new Map(); let hasFlow = false;
|
|
96
|
+
list.forEach((path, i) => {
|
|
97
|
+
const type = types[i][0];
|
|
98
|
+
const clean = path.replace(/\/$/, '');
|
|
99
|
+
if (type !== '-' && type !== 'd') throw new Refusal(400, `Refused: it holds something that is not a plain file or folder (${clean.slice(0, 120)}).`);
|
|
100
|
+
if (clean.startsWith('/') || clean.split('/').some((p) => p === '..' || p === '.' || p === '') || /\\/.test(clean)) throw new Refusal(400, `Refused: a path out of place (${clean.slice(0, 120)}).`);
|
|
101
|
+
if (clean === 'flow.json' && type === '-') { hasFlow = true; return; }
|
|
102
|
+
if (clean === 'folders' && type === 'd') return;
|
|
103
|
+
const m = /^folders\/([a-z0-9][a-z0-9-]{0,31})(\/.*)?$/.exec(clean);
|
|
104
|
+
if (!m) throw new Refusal(400, `Refused: something out of place (${clean.slice(0, 120)}).`);
|
|
105
|
+
const f = folders.get(m[1]) ?? { name: m[1], files: 0, bytes: 0 }; folders.set(m[1], f);
|
|
106
|
+
if (type === '-') { f.files += 1; f.bytes += Number(/^\S+\s+\S+\s+(\d+)\s/.exec(types[i])?.[1] ?? 0); }
|
|
107
|
+
});
|
|
108
|
+
if (!hasFlow) throw new Refusal(400, 'Not a file made by Export with the files: it has no flow.json.');
|
|
109
|
+
const text = spawnSync(this.#tar, ['--extract', '--gzip', '--to-stdout', `--file=${file}`, 'flow.json'], { encoding: 'utf8', maxBuffer: 2 * 1024 * 1024 });
|
|
110
|
+
if (text.status !== 0) throw new Refusal(400, 'Its flow.json could not be read.');
|
|
111
|
+
return { text: text.stdout, folders: [...folders.values()] };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/* Into `target`, only when it is empty: what is already there is never written over. */
|
|
115
|
+
fill(id, name, target) {
|
|
116
|
+
if (!NAME.test(name)) throw new Refusal(400, 'Not a folder name.');
|
|
117
|
+
const file = this.#file(id);
|
|
118
|
+
if (!existsSync(target) || readdirSync(target).length > 0) throw new Refusal(409, `${name} is not empty here: its files were not put in.`);
|
|
119
|
+
const r = spawnSync(this.#tar, ['--extract', '--gzip', `--file=${file}`, `--directory=${target}`, '--no-same-owner', '--no-same-permissions', '--no-overwrite-dir', '--strip-components=2', `folders/${name}`], { encoding: 'utf8' });
|
|
120
|
+
if (r.status !== 0) throw new Refusal(502, `Its files could not be put in: ${String(r.stderr).trim().split('\n').pop()}`);
|
|
121
|
+
const s = { files: 0, bytes: 0 }; walk(target, target, [], s);
|
|
122
|
+
return s.files;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
forget(id) { if (ID.test(id ?? '')) rmSync(join(this.#dir, `${id}.tar.gz`), { force: true }); }
|
|
126
|
+
|
|
127
|
+
#file(id) {
|
|
128
|
+
if (!ID.test(id ?? '')) throw new Refusal(400, 'Not a file sent here.');
|
|
129
|
+
const file = join(this.#dir, `${id}.tar.gz`);
|
|
130
|
+
if (!existsSync(file)) throw new Refusal(404, 'That file is no longer here: send it again.');
|
|
131
|
+
return file;
|
|
132
|
+
}
|
|
133
|
+
/* Uploads left over a day are dropped. */
|
|
134
|
+
#tidy() {
|
|
135
|
+
try { for (const n of readdirSync(this.#dir)) { const at = join(this.#dir, n); if (Date.now() - statSync(at).mtimeMs > KEEP_MS) rmSync(at, { recursive: true, force: true }); } } catch { /* none yet */ }
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/* WHAT HAPPENED (Settings, This server, What happened): the owner's actions and
|
|
2
|
+
* what the server did by itself, dated, in one list -- a conversation made or
|
|
3
|
+
* archived, a machine restarted, resized or put to sleep, a device paired or
|
|
4
|
+
* revoked, a secret set (its name, never its value), an update, a sign-in, the
|
|
5
|
+
* VM manager restarted... Each is one line of words, said once.
|
|
6
|
+
*
|
|
7
|
+
* Kept in a file of its own, one JSON line each, appended; when it grows past
|
|
8
|
+
* FILE_MAX it is cut to its newest half. Read back newest first.
|
|
9
|
+
*
|
|
10
|
+
* add({ kind, text, conversation?, who? })
|
|
11
|
+
* list({ kind?, conversation?, q?, before?, limit? }) newest first
|
|
12
|
+
* fromRequest(pathname, body, who, answer) an owner's request that succeeded,
|
|
13
|
+
* in words (only those worth saying: not a chat line, not a file)
|
|
14
|
+
* seen(who) a sign-in, said once in SEEN_MS for the same person
|
|
15
|
+
*/
|
|
16
|
+
import { appendFileSync, readFileSync, writeFileSync, renameSync, statSync, existsSync } from 'node:fs';
|
|
17
|
+
|
|
18
|
+
export const KINDS = ['conversation', 'machine', 'access', 'asset', 'update', 'server', 'sign-in'];
|
|
19
|
+
const FILE_MAX = 4 * 1024 * 1024;
|
|
20
|
+
const TEXT_MAX = 300;
|
|
21
|
+
const SEEN_MS = 8 * 3600_000;
|
|
22
|
+
const LIMIT_MAX = 1000;
|
|
23
|
+
|
|
24
|
+
const clip = (v, max = 80) => String(v ?? '').replace(/[\r\n\0]/g, ' ').slice(0, max);
|
|
25
|
+
|
|
26
|
+
/* The owner's requests worth saying: [pattern, kind, words(match, body, answer)]. */
|
|
27
|
+
const SAID = [
|
|
28
|
+
[/^\/api\/conversations$/, 'conversation', (m, b, a) => `Conversation "${clip(a?.title ?? b.title ?? b.name)}" made (${clip(a?.tool ?? b.tool, 30)})`],
|
|
29
|
+
[/^\/api\/conversations\/([^/]+)\/archive$/, 'conversation', (m) => `Conversation ${m[1]} archived`],
|
|
30
|
+
[/^\/api\/conversations\/([^/]+)\/title$/, 'conversation', (m, b) => `Conversation ${m[1]} renamed "${clip(b.title)}"`],
|
|
31
|
+
[/^\/api\/conversations\/([^/]+)\/restart$/, 'machine', (m) => `Machine of ${m[1]} restarted`],
|
|
32
|
+
[/^\/api\/conversations\/([^/]+)\/machine$/, 'machine', (m, b) => `Machine of ${m[1]} resized${b.memoryMb ? `: ${b.memoryMb} MB of memory` : ''}${b.diskGb ? `, ${b.diskGb} GB of disk` : ''}${b.cpus ? `, ${b.cpus} core${b.cpus > 1 ? 's' : ''}` : ''}`],
|
|
33
|
+
[/^\/api\/conversations\/([^/]+)\/sleep$/, 'machine', (m) => `Machine of ${m[1]} put to sleep`],
|
|
34
|
+
[/^\/api\/conversations\/([^/]+)\/rebuild$/, 'machine', (m) => `Machine of ${m[1]} built again`],
|
|
35
|
+
[/^\/api\/conversations\/([^/]+)\/network$/, 'machine', (m, b) => `${m[1]} ${b.online ? 'put online' : 'put offline'}`],
|
|
36
|
+
[/^\/api\/conversations\/([^/]+)\/share$/, 'access', (m) => `A pairing code made for ${m[1]}`],
|
|
37
|
+
[/^\/api\/devices\/([^/]+)\/revoke$/, 'access', (m) => `Device ${clip(m[1], 40)} revoked`],
|
|
38
|
+
[/^\/api\/conversations\/([^/]+)\/resources$/, 'access', (m, b) => (b.access === 'none' ? `${clip(b.resource, 40)} taken from ${m[1]}` : `${clip(b.resource, 40)} given to ${m[1]} (${b.access === 'write' ? 'write' : 'read'})`)],
|
|
39
|
+
[/^\/api\/conversations\/([^/]+)\/secrets$/, 'access', (m, b) => `Secret ${clip(b.secret, 40)} ${b.attached ? 'handed to' : 'taken from'} ${m[1]}`],
|
|
40
|
+
[/^\/api\/resources$/, 'asset', (m, b) => `${b.type === 'git' ? 'Repository' : 'Folder'} ${clip(b.name, 40)} added`],
|
|
41
|
+
[/^\/api\/resources\/([^/]+)\/remove$/, 'asset', (m) => `${clip(decodeURIComponent(m[1]), 40)} removed (its content put aside)`],
|
|
42
|
+
[/^\/api\/secrets$/, 'asset', (m, b) => `Secret ${clip(b.name, 40)} set`],
|
|
43
|
+
[/^\/api\/secrets\/([^/]+)\/remove$/, 'asset', (m) => `Secret ${clip(m[1], 40)} removed`],
|
|
44
|
+
[/^\/api\/secrets\/([^/]+)\/rename$/, 'asset', (m, b) => `Secret ${clip(m[1], 40)} renamed ${clip(b.name, 40)}`],
|
|
45
|
+
[/^\/api\/git\/([^/]+)\/push$/, 'asset', (m, b) => `${clip(decodeURIComponent(m[1]), 40)}: a commit sent${b.target ? ` to ${clip(b.target, 40)}` : ''}`],
|
|
46
|
+
[/^\/api\/mailboxes$/, 'asset', (m, b) => `Mailbox ${clip(b.name, 40)} added`],
|
|
47
|
+
[/^\/api\/updates\/apply$/, 'update', (m, b) => `Update to ${clip(b.version, 30)} asked`],
|
|
48
|
+
[/^\/api\/updates\/back$/, 'update', (m, b) => `Going back to ${clip(b.version, 30)} asked`],
|
|
49
|
+
[/^\/api\/updates\/settings$/, 'update', (m, b) => `Updates set: ${['mode', 'channel', 'window'].filter((k) => b[k]).map((k) => `${k} ${clip(b[k], 20)}`).join(', ')}`],
|
|
50
|
+
[/^\/api\/server\/restart$/, 'server', () => 'This server restarted'],
|
|
51
|
+
[/^\/api\/server\/reserve$/, 'server', (m, b) => `Reserve set${b.diskMb !== undefined ? `: disk ${b.diskMb} MB` : ''}${b.memoryMb !== undefined ? `, memory ${b.memoryMb} MB` : ''}`],
|
|
52
|
+
[/^\/api\/machines\/move$/, 'server', (m, b) => `All the machines moved to ${clip(b.to, 60)}`],
|
|
53
|
+
[/^\/api\/machines\/prepare$/, 'server', (m, b) => `Disk ${clip(b.path, 40)} erased and prepared for the machines`],
|
|
54
|
+
[/^\/api\/machines\/mount$/, 'server', (m, b) => `Disk ${clip(b.path, 40)} mounted`],
|
|
55
|
+
[/^\/api\/machines\/forget-old$/, 'server', () => 'The old copy of the machines removed'],
|
|
56
|
+
[/^\/api\/instance$/, 'server', (m, b) => `This Clavarium named "${clip(b.name, 40)}"`],
|
|
57
|
+
[/^\/api\/operators$/, 'sign-in', (m, b) => `Administrator ${clip(b.email, 80)} added`],
|
|
58
|
+
[/^\/api\/operators\/([^/]+)\/(password|disable|enable|remove)$/, 'sign-in', (m) => `Administrator ${clip(decodeURIComponent(m[1]), 80)}: ${{ password: 'new password', disable: 'disabled', enable: 'enabled', remove: 'removed' }[m[2]]}`],
|
|
59
|
+
[/^\/api\/setup\/import$/, 'conversation', () => 'A setup imported from a file'],
|
|
60
|
+
];
|
|
61
|
+
|
|
62
|
+
export class Events {
|
|
63
|
+
#file; #now; #seen = new Map();
|
|
64
|
+
constructor({ file = null, now = () => Date.now() } = {}) { this.#file = file; this.#now = now; }
|
|
65
|
+
|
|
66
|
+
add({ kind, text, conversation = null, who = null }) {
|
|
67
|
+
if (!KINDS.includes(kind) || !text) return null;
|
|
68
|
+
const e = { at: new Date(this.#now()).toISOString(), kind, text: clip(text, TEXT_MAX), ...(conversation ? { conversation: clip(conversation, 40) } : {}), ...(who ? { who: clip(who, 120) } : {}) };
|
|
69
|
+
if (this.#file) {
|
|
70
|
+
try {
|
|
71
|
+
appendFileSync(this.#file, `${JSON.stringify(e)}\n`, { mode: 0o600 });
|
|
72
|
+
if (statSync(this.#file).size > FILE_MAX) this.#cut();
|
|
73
|
+
} catch { /* said nowhere: never a reason to fail what was done */ }
|
|
74
|
+
}
|
|
75
|
+
return e;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/* Cut to its newest half. */
|
|
79
|
+
#cut() {
|
|
80
|
+
const lines = readFileSync(this.#file, 'utf8').split('\n').filter(Boolean);
|
|
81
|
+
writeFileSync(`${this.#file}.tmp`, `${lines.slice(Math.floor(lines.length / 2)).join('\n')}\n`, { mode: 0o600 });
|
|
82
|
+
renameSync(`${this.#file}.tmp`, this.#file);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
list({ kind = '', conversation = '', q = '', before = '', limit = 200 } = {}) {
|
|
86
|
+
if (!this.#file || !existsSync(this.#file)) return [];
|
|
87
|
+
const words = String(q).trim().toLowerCase();
|
|
88
|
+
const out = [];
|
|
89
|
+
const lines = readFileSync(this.#file, 'utf8').split('\n');
|
|
90
|
+
for (let i = lines.length - 1; i >= 0 && out.length < Math.min(LIMIT_MAX, Number(limit) || 200); i -= 1) {
|
|
91
|
+
let e; try { e = JSON.parse(lines[i]); } catch { continue; }
|
|
92
|
+
if (kind && e.kind !== kind) continue;
|
|
93
|
+
if (conversation && e.conversation !== conversation) continue;
|
|
94
|
+
if (before && !(e.at < before)) continue;
|
|
95
|
+
if (words && !`${e.text} ${e.who ?? ''}`.toLowerCase().includes(words)) continue;
|
|
96
|
+
out.push(e);
|
|
97
|
+
}
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
fromRequest(pathname, body = {}, who = '', answer = null) {
|
|
102
|
+
for (const [pattern, kind, words] of SAID) {
|
|
103
|
+
const m = pattern.exec(pathname);
|
|
104
|
+
if (!m) continue;
|
|
105
|
+
const match = m.map((x) => (x === undefined ? x : (() => { try { return decodeURIComponent(x); } catch { return x; } })()));
|
|
106
|
+
const conversation = /^\/api\/conversations\/([^/]+)\//.exec(pathname)?.[1] ?? (pattern.source === '^\\/api\\/conversations$' ? answer?.name : null);
|
|
107
|
+
return this.add({ kind, text: words(match, body ?? {}, answer), conversation: conversation ? decodeURIComponent(conversation) : null, who: who || null });
|
|
108
|
+
}
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
seen(who) {
|
|
113
|
+
if (!who) return null;
|
|
114
|
+
const last = this.#seen.get(who) ?? 0;
|
|
115
|
+
if (this.#now() - last < SEEN_MS) return null;
|
|
116
|
+
this.#seen.set(who, this.#now());
|
|
117
|
+
return this.add({ kind: 'sign-in', text: `${who} signed in`, who });
|
|
118
|
+
}
|
|
119
|
+
}
|
package/server/main.mjs
CHANGED
|
@@ -61,6 +61,8 @@ import { HealthReact } from './healthreact.mjs';
|
|
|
61
61
|
import { MachinesMove } from './machinesmove.mjs';
|
|
62
62
|
import { ServerLogs } from './serverlogs.mjs';
|
|
63
63
|
import { History, STEP_MS as HISTORY_STEP_MS } from './history.mjs';
|
|
64
|
+
import { Events } from './events.mjs';
|
|
65
|
+
import { Bundles } from './bundle.mjs';
|
|
64
66
|
import { migrateData } from './dataformat.mjs';
|
|
65
67
|
import { VmWatch } from './vmwatch.mjs';
|
|
66
68
|
|
|
@@ -122,7 +124,7 @@ const withoutTmux = (env) => Object.fromEntries(Object.entries(env).filter(([key
|
|
|
122
124
|
|
|
123
125
|
const REFUSED = 'This Clavarium belongs to someone else: your account is not one of its operators.\n';
|
|
124
126
|
|
|
125
|
-
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 } = {}) {
|
|
127
|
+
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 } = {}) {
|
|
126
128
|
/* Its manifest carries the name of this Clavarium, or the one a device chose (instance.mjs). */
|
|
127
129
|
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));
|
|
128
130
|
const sendFile = async (response, file) => {
|
|
@@ -160,7 +162,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
|
|
|
160
162
|
response.writeHead(403, { ...HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end(REFUSED);
|
|
161
163
|
return;
|
|
162
164
|
}
|
|
163
|
-
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)) return;
|
|
165
|
+
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)) return;
|
|
164
166
|
if (pathname === '/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
|
|
165
167
|
const file = FILES[pathname];
|
|
166
168
|
if (!file || (request.method !== 'GET' && request.method !== 'HEAD')) {
|
|
@@ -211,6 +213,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
211
213
|
const all = conversations ?? new Conversations({ store: new Store(`${dataDir}/conversations.json`), layout: new JsonFile(`${dataDir}/layout.json`, {}), vms, tools, ...(stopDelayMs === undefined ? {} : { stopDelayMs }) });
|
|
212
214
|
/* Who may do what with what: ONE table, shared by everything below. */
|
|
213
215
|
const grants = new Grants(new Store(`${dataDir}/grants.json`));
|
|
216
|
+
/* What happened, in one dated list (events.mjs): the owner's actions, and what the server did by itself. */
|
|
217
|
+
const events = new Events({ file: `${dataDir}/events.log` });
|
|
214
218
|
const vault = new Vault(vaultKey ?? `${dataDir}/vault.key`);
|
|
215
219
|
/* How private repositories are reached: keys and tokens kept and used here only (gitaccess.mjs).
|
|
216
220
|
`gitSsh`: a stand-in for the ssh program, for tests. */
|
|
@@ -373,7 +377,15 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
373
377
|
/* And what its owner chose that it does on top (healthreact.mjs): its agent told, or a command run. */
|
|
374
378
|
const reacting = new HealthReact({ store: new Store(`${dataDir}/health-react.json`), say: (name, line) => wakeups.say(name, line), exec: (name, argv, options) => vms.exec(name, argv, options),
|
|
375
379
|
isAgent: (name) => all.list().find((c) => c.name === name)?.ai === true, event: (name, line) => talk.event(name, line) });
|
|
376
|
-
|
|
380
|
+
/* A machine's problems worth keeping in What happened: said once, until they went away. */
|
|
381
|
+
const problemsSaid = new Map();
|
|
382
|
+
health.judged = (name, record) => {
|
|
383
|
+
talk.machine(name, record); void reacting.judged(name, record).catch(() => {});
|
|
384
|
+
const now = (record?.problems ?? []).filter((x) => x.level === 'bad' || (x.level === 'warn' && ['memory', 'disk'].includes(x.kind)));
|
|
385
|
+
const before = problemsSaid.get(name) ?? new Set();
|
|
386
|
+
for (const x of now) if (!before.has(x.key)) events.add({ kind: 'machine', text: `${name}: ${x.text}`, conversation: name });
|
|
387
|
+
problemsSaid.set(name, new Set(now.map((x) => x.key)));
|
|
388
|
+
};
|
|
377
389
|
/* A machine just started: its folders are mounted again (after a build,
|
|
378
390
|
a restart, a move) or looked at and put back if they came loose (after
|
|
379
391
|
a wake), before its tool starts in them. */
|
|
@@ -383,7 +395,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
383
395
|
may say otherwise: set by hand, or by an earlier version). Not waited for. */
|
|
384
396
|
void all.reconcileAll?.().catch(() => {});
|
|
385
397
|
/* The VM manager, watched: said to the pages when it does not answer, restarted once when stuck (vmwatch.mjs). */
|
|
386
|
-
const vmWatch = new VmWatch({ run: asHost, store: new Store(`${dataDir}/vm-manager.json`), alert: (payload) => { void alerts.tell(payload)?.catch?.(() => {}); } });
|
|
398
|
+
const vmWatch = new VmWatch({ run: asHost, store: new Store(`${dataDir}/vm-manager.json`), alert: (payload) => { events.add({ kind: 'server', text: `${payload.title}: ${payload.body ?? ''}`.trim() }); void alerts.tell(payload)?.catch?.(() => {}); } });
|
|
387
399
|
const stopVmWatch = vmWatch.start(vmWatchEveryMs);
|
|
388
400
|
const platform = { get machines() { return vmWatch.ok; }, answerer: answerer.about(), get operators() { return team ? team.allowed() : [...operators]; }, address: publicOrigin ?? null, version: JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version, get dictation() { return voice.current() ? (voice.model ?? 'set') : null; } };
|
|
389
401
|
/* Who gets what, and a whole setup in one file: see setup.mjs. */
|
|
@@ -394,7 +406,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
394
406
|
/* This server's disk and memory, and the reserve no machine may eat into: see capacity.mjs. */
|
|
395
407
|
const capacity = new Capacity({ run: asHost, store: new Store(`${dataDir}/server.json`), conversations: all, shelf, ...(serverRoomMs === undefined ? {} : { roomMs: serverRoomMs }),
|
|
396
408
|
/* Under the reserve: the machine that takes the most put to sleep, the owner told, and its chat. */
|
|
397
|
-
sleep: (name) => all.sleep(name), alert: (payload) => { void alerts.tell(payload); },
|
|
409
|
+
sleep: (name) => { events.add({ kind: 'machine', text: `Machine of ${name} put to sleep: this server was short of room`, conversation: name }); return all.sleep(name); }, alert: (payload) => { events.add({ kind: 'server', text: `${payload.title}: ${payload.body ?? ''}`.trim() }); void alerts.tell(payload); },
|
|
398
410
|
say: (name, text) => { try { talk.event(name, { kind: 'machine-problem', text, tone: 'warn', topic: 'Machine' }); } catch { /* its chat may be off */ } } });
|
|
399
411
|
all.room = (ask) => capacity.check(ask);
|
|
400
412
|
const stopWatch = capacity.start();
|
|
@@ -413,7 +425,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
413
425
|
void team.refresh().catch((error) => console.error(`operators: ${error.message}`));
|
|
414
426
|
const watching = setInterval(() => { void team.watch().catch(() => {}); }, 60_000); watching.unref?.();
|
|
415
427
|
}
|
|
416
|
-
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, repair: (name) => repairTerminal(name) });
|
|
428
|
+
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, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
|
|
417
429
|
server.on('close', () => { closing = true; clearInterval(historyTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(gitTimer); talk.stop(); });
|
|
418
430
|
let closing = false;
|
|
419
431
|
bridge = attachBridge(server, {
|
package/server/setup.mjs
CHANGED
|
@@ -262,7 +262,7 @@ function wakeWords(w) {
|
|
|
262
262
|
}
|
|
263
263
|
|
|
264
264
|
export class Setup {
|
|
265
|
-
#store; #p; #tools; #version; #job = null; #pollMs;
|
|
265
|
+
#store; #p; #tools; #version; #job = null; #pollMs; #fill = null;
|
|
266
266
|
|
|
267
267
|
/* `parts`: what keeps each thing (conversations, resources, secrets,
|
|
268
268
|
devices, shortcuts, wakeups, answerer, talk, gitKeeper, gitAccess,
|
|
@@ -557,8 +557,10 @@ export class Setup {
|
|
|
557
557
|
job() { return this.#job ? { ...this.#job, steps: this.#job.steps.map((s) => ({ ...s })) } : null; }
|
|
558
558
|
|
|
559
559
|
/* Starts making what the preview said; one import at a time. */
|
|
560
|
-
|
|
560
|
+
/* `fill(fileName, name)`: the files of a folder put in once it is made (bundle.mjs), -> how many; or none. */
|
|
561
|
+
start(text, choices = {}, { fill = null } = {}) {
|
|
561
562
|
if (this.#job?.running) throw new Refusal(409, 'An import is already being made.');
|
|
563
|
+
this.#fill = fill;
|
|
562
564
|
const plan = this.preview(text, choices);
|
|
563
565
|
if (!plan.ready) throw new Refusal(400, 'Some names are still to choose.');
|
|
564
566
|
const { doc } = readSetup(text, this.#tools());
|
|
@@ -584,8 +586,16 @@ export class Setup {
|
|
|
584
586
|
/* Assets first: folders and repositories made, the rest remembered. */
|
|
585
587
|
for (const i of items.filter((x) => ['folder', 'git', 'mailbox', 'secret'].includes(x.kind))) {
|
|
586
588
|
const n = node.get(i.id);
|
|
587
|
-
if (i.status === 'exists') continue;
|
|
588
|
-
if (i.kind === 'folder')
|
|
589
|
+
if (i.status === 'exists') { if (i.kind === 'folder' && this.#fill) this.#step(job, `Folder ${nm(i.id)} is here already: its files were not put in`, 'skipped'); continue; }
|
|
590
|
+
if (i.kind === 'folder') {
|
|
591
|
+
const fill = this.#fill;
|
|
592
|
+
await this.#try(job, fill ? `Folder ${nm(i.id)}: made, with its files` : `Folder ${nm(i.id)}: made, empty`, async () => {
|
|
593
|
+
await p.resources.create({ name: nm(i.id) });
|
|
594
|
+
if (!fill) return undefined;
|
|
595
|
+
const files = await fill(nameOf(i.id), nm(i.id));
|
|
596
|
+
return Number.isInteger(files) ? `${files} file${files === 1 ? '' : 's'}` : undefined;
|
|
597
|
+
});
|
|
598
|
+
}
|
|
589
599
|
else if (i.kind === 'git' && i.status === 'new') {
|
|
590
600
|
await this.#try(job, n.source ? `Repository ${nm(i.id)}: cloned from ${n.source}` : `Repository ${nm(i.id)}: made, empty`, async () => {
|
|
591
601
|
const made = await p.resources.create({ name: nm(i.id), type: 'git', from: n.source ?? undefined, ...(n.source && n.access === 'ssh-key' ? { via: { method: 'ssh-key', key: n.key } } : {}), ...(n.source && n.pin ? { pin: n.pin } : {}) });
|
package/web/app.js
CHANGED
|
@@ -3747,6 +3747,37 @@
|
|
|
3747
3747
|
if (!p.disks.some((d) => !d.system)) rows.append(el('p', 'hint', 'No other disk: plug one in (or add one to this server), then open this again.'));
|
|
3748
3748
|
}
|
|
3749
3749
|
$('move-machines-box').addEventListener('toggle', () => { if ($('move-machines-box').open) void paintMoveMachines(); });
|
|
3750
|
+
/* WHAT HAPPENED: newest first, a page at a time; chosen by kind, searched. */
|
|
3751
|
+
const EVENT_WORDS = { conversation: 'Conversation', machine: 'Machine', access: 'Access', asset: 'Asset', update: 'Update', server: 'Server', 'sign-in': 'Sign-in' };
|
|
3752
|
+
let eventsShown = []; let eventsAsk = 0;
|
|
3753
|
+
async function paintEvents({ more = false } = {}) {
|
|
3754
|
+
const ask = ++eventsAsk;
|
|
3755
|
+
const before = more && eventsShown.length ? eventsShown.at(-1).at : '';
|
|
3756
|
+
const q = new URLSearchParams({ kind: $('events-kind').value, q: $('events-q').value.trim(), limit: '100', ...(before ? { before } : {}) });
|
|
3757
|
+
const got = await fetch(`${API}/events?${q}`).then((r) => (r.ok ? r.json() : null)).catch(() => null);
|
|
3758
|
+
if (ask !== eventsAsk) return;
|
|
3759
|
+
if (!got) { $('events-said').textContent = 'What happened cannot be read just now.'; return; }
|
|
3760
|
+
eventsShown = more ? [...eventsShown, ...got] : got;
|
|
3761
|
+
const list = $('events-list'); if (!more) list.replaceChildren();
|
|
3762
|
+
for (const e of got) {
|
|
3763
|
+
const li = el('li', 'event'); li.dataset.kind = e.kind;
|
|
3764
|
+
const when = el('time', 'event-when', new Date(e.at).toLocaleString([], { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' })); when.dateTime = e.at;
|
|
3765
|
+
li.append(when, el('span', 'event-kind', EVENT_WORDS[e.kind] ?? e.kind), el('span', 'event-text', e.text));
|
|
3766
|
+
if (e.who && !e.text.includes(e.who)) li.append(el('span', 'event-who', e.who));
|
|
3767
|
+
list.append(li);
|
|
3768
|
+
}
|
|
3769
|
+
$('events-said').textContent = eventsShown.length ? '' : 'Nothing yet.';
|
|
3770
|
+
$('events-more').hidden = got.length < 100;
|
|
3771
|
+
}
|
|
3772
|
+
$('settings-events-top').addEventListener('toggle', () => { if ($('settings-events-top').open) void paintEvents(); });
|
|
3773
|
+
$('events-kind').addEventListener('change', () => { void paintEvents(); });
|
|
3774
|
+
let eventsTyping;
|
|
3775
|
+
$('events-q').addEventListener('input', () => { clearTimeout(eventsTyping); eventsTyping = setTimeout(() => { void paintEvents(); }, 250); });
|
|
3776
|
+
$('events-more').addEventListener('click', () => { void paintEvents({ more: true }); });
|
|
3777
|
+
$('events-copy').addEventListener('click', async () => {
|
|
3778
|
+
const text = eventsShown.map((e) => `${e.at}\t${e.kind}\t${e.text}${e.who ? `\t${e.who}` : ''}`).join('\n');
|
|
3779
|
+
try { await navigator.clipboard.writeText(text); $('events-said').textContent = `Copied: ${eventsShown.length} lines.`; } catch { $('events-said').textContent = 'The clipboard is not available here.'; }
|
|
3780
|
+
});
|
|
3750
3781
|
/* WHAT THE SERVER'S PROGRAMS SAID: one source over a span, to read, copy whole or keep as a file. */
|
|
3751
3782
|
let logsShown = null;
|
|
3752
3783
|
$('logs-show').addEventListener('click', async () => {
|
package/web/index.html
CHANGED
|
@@ -729,6 +729,22 @@
|
|
|
729
729
|
</div>
|
|
730
730
|
</div>
|
|
731
731
|
</details>
|
|
732
|
+
<!-- WHAT HAPPENED: the owner's actions and what the server did by itself, dated (server/events.mjs). -->
|
|
733
|
+
<details class="chapter" id="settings-events-top" data-chapter="s-events">
|
|
734
|
+
<summary><span class="chapter-title">What happened</span><span class="chapter-about">Conversations, machines, access, updates, sign-ins: dated.</span></summary>
|
|
735
|
+
<div class="chapter-body">
|
|
736
|
+
<div class="row events-pick">
|
|
737
|
+
<label>Show <select id="events-kind" class="pill">
|
|
738
|
+
<option value="">everything</option><option value="conversation">conversations</option><option value="machine">machines</option><option value="access">access and devices</option><option value="asset">folders, repositories, secrets</option><option value="update">updates</option><option value="server">this server</option><option value="sign-in">sign-ins and administrators</option>
|
|
739
|
+
</select></label>
|
|
740
|
+
<input type="search" id="events-q" placeholder="Search" aria-label="Search what happened" maxlength="60" autocomplete="off">
|
|
741
|
+
<button type="button" id="events-copy">Copy all</button>
|
|
742
|
+
</div>
|
|
743
|
+
<ol id="events-list" class="events-list" aria-live="polite"></ol>
|
|
744
|
+
<p class="hint" id="events-said" role="status"></p>
|
|
745
|
+
<button type="button" id="events-more" hidden>Show older</button>
|
|
746
|
+
</div>
|
|
747
|
+
</details>
|
|
732
748
|
<!-- WHAT THE SERVER'S PROGRAMS SAID, to read, copy whole or keep (server/serverlogs.mjs);
|
|
733
749
|
and this server started again. -->
|
|
734
750
|
<details class="chapter" id="settings-logs-top" data-chapter="s-logs">
|
|
@@ -764,7 +780,7 @@
|
|
|
764
780
|
<details class="chapter" id="settings-ch-backup" data-chapter="s-backup">
|
|
765
781
|
<summary><span class="chapter-title">Storage & backup</span><span class="chapter-about">Disk sizes, and how to back up.</span></summary>
|
|
766
782
|
<div class="chapter-body">
|
|
767
|
-
<div class="row"><span id="export-note" class="hint">Secrets are never exported, only their names.</span> <span class="row access-files"><button type="button" id="flows-export" title="Everything here, to a file: conversations, assets, devices, links; never a secret's value">Export</button><button type="button" id="flows-import" title="A setup from a file: shown whole before anything is made">Import...</button><input type="file" id="flows-file" accept=".json,application/json" hidden></span> <span id="flows-said" class="hint" role="status"></span></div>
|
|
783
|
+
<div class="row"><span id="export-note" class="hint">Secrets are never exported, only their names.</span> <label class="check" title="The files of the folders too, in a .tar.gz: to move a flow to another Clavarium with what it holds"><input type="checkbox" id="flows-with-files"> and the files of its folders</label> <span class="row access-files"><button type="button" id="flows-export" title="Everything here, to a file: conversations, assets, devices, links; never a secret's value">Export</button><button type="button" id="flows-import" title="A setup from a file: shown whole before anything is made">Import...</button><input type="file" id="flows-file" accept=".json,application/json,.gz,.tgz,application/gzip" hidden></span> <span id="flows-said" class="hint" role="status"></span></div>
|
|
768
784
|
<p class="hint">Each conversation works in a disk of a fixed size (10 GB unless the installation says otherwise). A backup is made on the machine itself, as two files -- the archive, and the key of the vault apart: <code>sudo deploy/backup.sh --to /a/folder</code>.</p>
|
|
769
785
|
</div>
|
|
770
786
|
</details>
|
package/web/links.js
CHANGED
|
@@ -856,9 +856,23 @@
|
|
|
856
856
|
if (traceOf === '*') islands(); else trace();
|
|
857
857
|
}
|
|
858
858
|
|
|
859
|
-
/* A setup to a file: the configuration, never the data
|
|
859
|
+
/* A setup to a file: the configuration, never the data -- or, with "and the files of its folders" ticked,
|
|
860
|
+
the configuration and those files, as a .tar.gz (server/bundle.mjs), told first how large. */
|
|
860
861
|
async function exportFile(flow) {
|
|
861
862
|
flowsErr('');
|
|
863
|
+
if ($('flows-with-files').checked) {
|
|
864
|
+
try {
|
|
865
|
+
const q = flow ? `flow=${encodeURIComponent(flow)}&` : '';
|
|
866
|
+
const r = await fetch(`${env.API()}/setup/bundle?${q}stats=1`); const s = await r.json();
|
|
867
|
+
if (!r.ok) throw new Error(s.error ?? 'The files could not be counted.');
|
|
868
|
+
const files = s.folders.reduce((a, x) => a + x.files, 0); const bytes = s.folders.reduce((a, x) => a + x.bytes, 0);
|
|
869
|
+
const size = bytes >= 1024 ** 3 ? `${(bytes / 1024 ** 3).toFixed(1)} GB` : `${Math.max(1, Math.round(bytes / 1024 ** 2))} MB`;
|
|
870
|
+
const a = h('a', { href: `${env.API()}/setup/bundle?${q.replace(/&$/, '')}`, download: `${(s.name || 'setup').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'setup'}.clavarium.tar.gz` });
|
|
871
|
+
document.body.append(a); a.click(); a.remove();
|
|
872
|
+
$('flows-said').textContent = `Exporting ${s.name} with ${files} file${files === 1 ? '' : 's'} from ${s.folders.length} folder${s.folders.length === 1 ? '' : 's'} (about ${size}): your browser saves it as it comes. Names of secrets only, no key, no password.`;
|
|
873
|
+
} catch (e) { flowsErr(e.message); }
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
862
876
|
try {
|
|
863
877
|
const made = await request('/setup/export', flow ? { flow } : {});
|
|
864
878
|
const a = h('a', { href: URL.createObjectURL(new Blob([made.text], { type: 'application/json' })), download: `${(made.name || 'setup').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'setup'}.clavarium.json` });
|
|
@@ -945,7 +959,7 @@
|
|
|
945
959
|
}
|
|
946
960
|
async function runImport() {
|
|
947
961
|
const box = $('flows-preview');
|
|
948
|
-
try { await request('/setup/import', { text: importing.text, choices: importing.choices }); } catch (e) { flowsErr(e.message); return; }
|
|
962
|
+
try { await request('/setup/import', { text: importing.text, choices: importing.choices, ...(importing.bundle ? { bundle: importing.bundle } : {}) }); } catch (e) { flowsErr(e.message); return; }
|
|
949
963
|
const steps = h('ol', { class: 'lk-job', id: 'flows-job' });
|
|
950
964
|
box.replaceChildren(h('h3', { text: `Importing ${importing.file}` }), h('p', { class: 'hint', text: 'Machines are built one at a time: a few minutes each. This can be closed; it goes on.' }), steps);
|
|
951
965
|
importing = null;
|
|
@@ -1000,6 +1014,21 @@
|
|
|
1000
1014
|
flowsErr('');
|
|
1001
1015
|
/* Imported from any tab: what it holds is shown in Flows. */
|
|
1002
1016
|
await env.toFlows();
|
|
1017
|
+
/* A flow with its files: sent whole first, checked there; what it holds is shown as for a setup. */
|
|
1018
|
+
if (/\.tar\.gz$|\.tgz$/i.test(file.name)) {
|
|
1019
|
+
$('flows-said').textContent = `Sending ${file.name}...`;
|
|
1020
|
+
try {
|
|
1021
|
+
const r = await fetch(`${env.API()}/setup/bundle`, { method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: file });
|
|
1022
|
+
const got = await r.json().catch(() => ({}));
|
|
1023
|
+
if (!r.ok) throw new Error(got.error ?? `It could not be sent (${r.status}).`);
|
|
1024
|
+
const files = got.folders.reduce((a, x) => a + x.files, 0);
|
|
1025
|
+
importing = { text: got.text, file: file.name, choices: {}, bundle: got.id };
|
|
1026
|
+
$('flows-said').textContent = `${file.name}: ${files} file${files === 1 ? '' : 's'} for ${got.folders.length} folder${got.folders.length === 1 ? '' : 's'}. A folder made new gets its files; one already here keeps its own.`;
|
|
1027
|
+
} catch (e) { $('flows-said').textContent = ''; flowsErr(e.message); return; }
|
|
1028
|
+
await previewFile();
|
|
1029
|
+
$('flows-preview').scrollIntoView({ block: 'start' });
|
|
1030
|
+
return;
|
|
1031
|
+
}
|
|
1003
1032
|
if (file.size > 512 * 1024) { flowsErr(`${file.name} is too large: a setup is at most 512 KB.`); return; }
|
|
1004
1033
|
importing = { text: await file.text(), file: file.name, choices: {} };
|
|
1005
1034
|
await previewFile();
|
package/web/style.css
CHANGED
|
@@ -1324,3 +1324,16 @@ select.pill { appearance: auto; }
|
|
|
1324
1324
|
.curve-tip { position: absolute; top: 0; right: 0; padding: 1px 6px; border-radius: 4px; background: var(--panel); border: 1px solid var(--line); font-size: .75rem; color: var(--ink); font-variant-numeric: tabular-nums; pointer-events: none; }
|
|
1325
1325
|
.curve-foot { display: flex; justify-content: space-between; font-size: .6875rem; color: var(--ink2); margin-top: 2px; }
|
|
1326
1326
|
.curve-legend { display: block; margin-top: 2px; font-size: .6875rem; }
|
|
1327
|
+
|
|
1328
|
+
/* Settings, What happened: one line each -- when, what kind, what; who when it is not said. */
|
|
1329
|
+
.events-pick { flex-wrap: wrap; gap: 8px 12px; align-items: center; }
|
|
1330
|
+
.events-pick input[type=search] { flex: 1 1 10rem; min-width: 0; }
|
|
1331
|
+
.events-list { list-style: none; margin: 8px 0; padding: 0; display: flex; flex-direction: column; gap: 2px; font-size: .875rem; }
|
|
1332
|
+
.event { display: grid; grid-template-columns: 7.5rem 6.5rem 1fr; gap: 2px 10px; padding: 4px 0; border-bottom: 1px solid var(--line); align-items: baseline; }
|
|
1333
|
+
.event-when { color: var(--ink2); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
|
1334
|
+
.event-kind { color: var(--ink2); font-size: .75rem; text-transform: uppercase; letter-spacing: .03em; }
|
|
1335
|
+
.event-text { min-width: 0; overflow-wrap: anywhere; }
|
|
1336
|
+
.event-who { grid-column: 3; color: var(--ink2); font-size: .75rem; }
|
|
1337
|
+
@media (max-width: 600px) { .event { grid-template-columns: 1fr auto; } .event-text, .event-who { grid-column: 1 / -1; } }
|
|
1338
|
+
/* The choices of Logs and What happened: as wide as their words, in the colours of the page. */
|
|
1339
|
+
.events-pick select, .logs-pick select { width: auto; max-width: 100%; background: var(--bg); color: var(--ink); border: 1px solid var(--line); border-radius: 8px; padding: 4px 8px; }
|