clavarium 0.2.236-next.1 → 0.2.237-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.
Files changed (104) hide show
  1. package/config/launch/claude-code.sh +40 -19
  2. package/config/launch/codex.sh +37 -0
  3. package/config/launch/json-set.mjs +5 -2
  4. package/config/launch/mcp-relay.mjs +98 -0
  5. package/config/launch/mcp-sock.sh +31 -0
  6. package/config/launch/screen-watch.mjs +173 -0
  7. package/config/launch/toml-block.mjs +26 -0
  8. package/config/launch/tools-host.mjs +93 -0
  9. package/config/launch/vibe.sh +40 -0
  10. package/config/machine/clavarium-beat +44 -0
  11. package/config/machine/clavarium-beat-one +40 -0
  12. package/config/machine/clavarium-enter +60 -0
  13. package/config/tools.json +170 -12
  14. package/deploy/clavarium-host +385 -31
  15. package/deploy/clavarium-tunnel +14 -3
  16. package/deploy/clavarium.mjs +4 -0
  17. package/deploy/git-read +57 -5
  18. package/deploy/install.sh +11 -5
  19. package/deploy/maintenance.html +5 -2
  20. package/deploy/online.mjs +251 -8
  21. package/deploy/relay.sh +53 -27
  22. package/deploy/tunnel.mjs +7 -5
  23. package/deploy/updater.mjs +168 -25
  24. package/npm-shrinkwrap.json +245 -19
  25. package/package.json +9 -6
  26. package/server/agenda.mjs +140 -0
  27. package/server/api.mjs +392 -28
  28. package/server/apikeys.mjs +1372 -0
  29. package/server/beat.mjs +189 -0
  30. package/server/binders.mjs +42 -0
  31. package/server/boxcollect.mjs +276 -0
  32. package/server/boxes.mjs +348 -29
  33. package/server/bridge.mjs +13 -4
  34. package/server/browsers.mjs +364 -0
  35. package/server/capacity.mjs +37 -10
  36. package/server/carry.mjs +143 -0
  37. package/server/catalog.mjs +48 -0
  38. package/server/contactview.mjs +122 -0
  39. package/server/conversations.mjs +1122 -46
  40. package/server/copywork.mjs +34 -0
  41. package/server/demandes.mjs +251 -0
  42. package/server/desktop.mjs +102 -0
  43. package/server/devices.mjs +1 -0
  44. package/server/dictation-engines.mjs +91 -0
  45. package/server/dockets.mjs +49 -6
  46. package/server/door.mjs +19 -5
  47. package/server/events.mjs +3 -0
  48. package/server/features.mjs +366 -0
  49. package/server/files.mjs +43 -1
  50. package/server/gitaccess.mjs +12 -3
  51. package/server/gitchecks.mjs +17 -3
  52. package/server/gitkeeper.mjs +45 -10
  53. package/server/gitpush.mjs +286 -71
  54. package/server/gitrunner.mjs +144 -10
  55. package/server/grants.mjs +47 -11
  56. package/server/guide.mjs +31 -10
  57. package/server/health.mjs +138 -12
  58. package/server/jobs.mjs +138 -0
  59. package/server/linkguard.mjs +191 -0
  60. package/server/machinelist.mjs +58 -0
  61. package/server/mailref.mjs +90 -0
  62. package/server/mailview.mjs +204 -0
  63. package/server/main.mjs +425 -47
  64. package/server/mcpoauth.mjs +338 -0
  65. package/server/mcpx.mjs +175 -0
  66. package/server/network.mjs +125 -13
  67. package/server/profile.mjs +129 -0
  68. package/server/relayjoin.mjs +67 -0
  69. package/server/resources.mjs +6 -0
  70. package/server/revive.mjs +70 -0
  71. package/server/rooms.mjs +462 -0
  72. package/server/secrets.mjs +25 -12
  73. package/server/serverlogs.mjs +30 -4
  74. package/server/settingswords.mjs +375 -0
  75. package/server/signinhelp.mjs +239 -0
  76. package/server/speech.mjs +40 -4
  77. package/server/spoken.mjs +60 -0
  78. package/server/sshconsole.mjs +99 -0
  79. package/server/sshmachine.mjs +76 -0
  80. package/server/store.mjs +15 -1
  81. package/server/suggest.mjs +66 -0
  82. package/server/talk.mjs +228 -55
  83. package/server/tethers.mjs +223 -13
  84. package/server/toolbox.mjs +30 -7
  85. package/server/tools.mjs +38 -6
  86. package/server/updates.mjs +7 -2
  87. package/server/vm.mjs +215 -46
  88. package/server/vmwatch.mjs +82 -23
  89. package/server/voice.mjs +183 -51
  90. package/server/wakelearn.mjs +214 -0
  91. package/server/wakeups.mjs +42 -2
  92. package/server/watchdog.mjs +102 -0
  93. package/web/app.js +5590 -1237
  94. package/web/desk.js +531 -0
  95. package/web/device.html +15 -2
  96. package/web/features.js +480 -0
  97. package/web/index.html +874 -490
  98. package/web/kit.js +1142 -0
  99. package/web/links.js +2 -2
  100. package/web/mail-view.js +386 -0
  101. package/web/manifest.webmanifest +4 -0
  102. package/web/style.css +1592 -268
  103. package/web/voice-core.js +48 -0
  104. package/web/voice.js +13 -5
@@ -14,41 +14,114 @@
14
14
  * (that is how its terminal and its folders work), and not the host's
15
15
  * name resolver, which would be a way to carry data out.
16
16
  *
17
+ * AND NO VM PASSES FOR ANOTHER: root in a VM can give itself another VM's
18
+ * address, or answer the host's ARP for it, and the server reaches each VM at
19
+ * its address (its terminal, its folders, its secrets). So every frame from a
20
+ * tap must carry that VM's own MAC (read from its qemu line, which the VM
21
+ * cannot change), be IPv4 or ARP only (no IPv6: nothing of ours uses it, the
22
+ * VM manager's network gives none), and come from that VM's own IPv4 address
23
+ * (the lease the VM manager's DHCP server gave that MAC, pinned for the life
24
+ * of its qemu process). Its DHCP must name its own MAC. While its address is
25
+ * not known yet (it boots), it may lease one, but never use an address known
26
+ * to be another VM's or the host's.
27
+ *
17
28
  * WHAT THIS DOES NOT CLOSE, and it is said rather than hidden: a tap is only
18
29
  * known once its VM runs, so a VM is filtered a moment AFTER it starts, not
19
- * before. The rules are applied before the tool is attached.
30
+ * before. The rules are applied before the tool is attached. A VM whose qemu
31
+ * line has no MAC we can read keeps its silo but no address check.
20
32
  */
21
33
  import { isConversationName } from './names.mjs';
22
34
 
23
35
  export const TABLE = 'clavarium';
24
36
  const TAP = /^tap-[0-9a-f]{1,12}$/;
37
+ const MAC = /^[0-9a-f]{2}(?::[0-9a-f]{2}){5}$/;
38
+ const ADDRESS = /^\d{1,3}(?:\.\d{1,3}){3}$/;
39
+
40
+ export const isMac = (v) => typeof v === 'string' && MAC.test(v) && (parseInt(v.slice(0, 2), 16) & 1) === 0; /* unicast */
41
+ export const isAddress = (v) => typeof v === 'string' && ADDRESS.test(v) && v.split('.').every((n) => Number(n) <= 255 && String(Number(n)) === n);
42
+ /* An address a VM may hold: not 0.0.0.0, not broadcast, not multicast. */
43
+ const isHostAddress = (v) => isAddress(v) && v.split('.')[0] !== '0' && Number(v.split('.')[0]) < 224;
25
44
 
26
- /* The taps of the running conversation VMs, read from the process list:
27
- { conversation: tap }. Anything that does not look exactly as expected is
28
- left out: a rule is never built from a string that was not checked. */
45
+ /* How often what runs is looked at, for the rules (see watch): three commands to the host each
46
+ time. Every opening applies them anyway, and so does every action on a machine and a machine
47
+ found running that was not (main.mjs): this is only for what nothing told. */
48
+ export const WATCH_MS = 120_000;
49
+ export const RELOAD_MS = 10 * 60_000;
50
+
51
+ /* The running conversation VMs, read from the process list:
52
+ { conversation: { tap, mac, pid } }. Anything that does not look exactly as
53
+ expected is left out (a bad tap: the VM; a bad or missing MAC: the MAC):
54
+ a rule is never built from a string that was not checked. */
29
55
  export function readTaps(processList) {
30
56
  const taps = {};
31
57
  for (const line of String(processList ?? '').split('\n')) {
32
58
  const name = /\/instances\/clv-([a-z0-9-]+)\//.exec(line)?.[1];
33
59
  const tap = /[ ,]ifname=([^, ]+)/.exec(line)?.[1];
34
- if (name && tap && isConversationName(name) && TAP.test(tap)) taps[name] = tap;
60
+ if (!(name && tap && isConversationName(name) && TAP.test(tap))) continue;
61
+ const mac = /[ ,]mac=([^, ]+)/.exec(line)?.[1];
62
+ const pid = /^\s*(\d{1,10}) /.exec(line)?.[1];
63
+ taps[name] = { tap, mac: isMac(mac) ? mac : undefined, pid };
35
64
  }
36
65
  return taps;
37
66
  }
38
67
 
68
+ /* The leases of the VM manager's DHCP server, as the host program prints them
69
+ ("<mac> <ip>" per line): { mac: ip }. A MAC or an address seen twice is
70
+ ambiguous: left out, unknown. */
71
+ export function readLeases(text) {
72
+ const byMac = new Map(); const seen = new Map();
73
+ for (const line of String(text ?? '').split('\n')) {
74
+ const [mac, ip, extra] = line.trim().split(/\s+/);
75
+ if (extra !== undefined || !isMac(mac) || !isHostAddress(ip)) continue;
76
+ byMac.set(mac, byMac.has(mac) && byMac.get(mac) !== ip ? null : ip);
77
+ seen.set(ip, (seen.get(ip) ?? new Set()).add(mac));
78
+ }
79
+ const leases = {};
80
+ for (const [mac, ip] of byMac) if (ip && seen.get(ip).size === 1) leases[mac] = ip;
81
+ return leases;
82
+ }
83
+
39
84
  export function readBridgeAddress(text) {
40
85
  const address = /\binet (\d{1,3}(?:\.\d{1,3}){3})\//.exec(String(text ?? ''))?.[1];
41
86
  return address && address.split('.').every((n) => Number(n) <= 255) ? address : undefined;
42
87
  }
43
88
 
44
- /* The whole table, as text for the firewall. Replaced atomically. */
45
- export function ruleset(taps, offline, bridgeAddress) {
46
- const all = Object.values(taps);
89
+ /* What a frame from one VM must be. `known` is every address held by another
90
+ VM, and the host's, for a VM whose own is not known yet. */
91
+ function guard(tap, mac, ip, known) {
92
+ const at = ` iifname "${tap}"`;
93
+ const lines = [
94
+ `${at} ether saddr != ${mac} drop`,
95
+ `${at} ether type != { ip, arp } drop`, /* IPv6, VLAN tags, the rest */
96
+ `${at} arp saddr ether != ${mac} drop`,
97
+ `${at} udp dport 67 @th,288,48 != 0x${mac.replaceAll(':', '')} drop`, /* DHCP: its own MAC (chaddr) */
98
+ `${at} ip saddr 0.0.0.0 ip daddr 255.255.255.255 udp dport 67 accept`, /* its lease, before it has one */
99
+ ];
100
+ if (ip) {
101
+ lines.push(`${at} ip saddr != ${ip} drop`);
102
+ lines.push(`${at} arp saddr ip != { 0.0.0.0, ${ip} } drop`);
103
+ } else if (known.length) {
104
+ lines.push(`${at} ip saddr { ${known.join(', ')} } drop`);
105
+ lines.push(`${at} arp saddr ip { ${known.join(', ')} } drop`);
106
+ }
107
+ return lines;
108
+ }
109
+
110
+ /* The whole table, as text for the firewall. Replaced atomically.
111
+ `vms`: { conversation: { tap, mac?, ip? } } (mac and ip already checked). */
112
+ export function ruleset(vms, offline, bridgeAddress) {
113
+ const all = Object.values(vms);
47
114
  const lines = [`table bridge ${TABLE}`, `delete table bridge ${TABLE}`, `table bridge ${TABLE} {`];
48
115
  lines.push(' chain between_vms {', ' type filter hook forward priority 0;');
49
- for (const tap of all) lines.push(` iifname "${tap}" drop`);
116
+ for (const { tap } of all) lines.push(` iifname "${tap}" drop`);
50
117
  lines.push(' }', ' chain from_vm {', ' type filter hook input priority 0;');
51
- for (const [name, tap] of Object.entries(taps)) {
118
+ const held = [...new Set([...all.map((v) => v.ip).filter(isHostAddress), ...(isHostAddress(bridgeAddress) ? [bridgeAddress] : [])])].sort();
119
+ for (const { tap, mac, ip } of all) {
120
+ if (!isMac(mac)) continue;
121
+ const own = isHostAddress(ip) ? ip : undefined;
122
+ lines.push(...guard(tap, mac, own, held));
123
+ }
124
+ for (const [name, { tap }] of Object.entries(vms)) {
52
125
  if (!offline.includes(name)) continue;
53
126
  lines.push(` iifname "${tap}" udp dport 67 accept`); /* its address lease */
54
127
  lines.push(` iifname "${tap}" ether type arp accept`);
@@ -62,6 +135,12 @@ export function ruleset(taps, offline, bridgeAddress) {
62
135
 
63
136
  export class Network {
64
137
  #host; #offline;
138
+ /* The table last loaded, and whether it was: the same table is not loaded again. */
139
+ #last = null;
140
+ /* PINNED: the address first leased to a VM, kept for the life of its qemu
141
+ process (its pid, tap and MAC). A lease that changes while it runs is
142
+ the VM asking for another address by itself: not followed. */
143
+ #pins = new Map();
65
144
 
66
145
  /* `host(argv)` reaches the host program;
67
146
  `offline()` returns the names of the conversations switched offline. */
@@ -72,14 +151,47 @@ export class Network {
72
151
  async apply() {
73
152
  const taps = readTaps((await this.#host(['net', 'taps'])).stdout);
74
153
  const bridge = readBridgeAddress((await this.#host(['net', 'bridge'])).stdout);
154
+ const leased = await this.#host(['net', 'leases']);
155
+ const vms = this.#addresses(taps, leased.code === 0 ? readLeases(leased.stdout) : {});
75
156
  const wanted = this.#offline().filter((name) => taps[name]);
76
157
  /* Without the host's address the "offline" rules cannot be written
77
158
  safely; the silo rule still can, and is. */
78
159
  /* As ONE argument, not on standard input: this firewall tool refuses
79
160
  a pipe as its input file (measured), and nothing in the rules is
80
- secret. Every name in them was checked by readTaps, and the host
161
+ secret. Every name, MAC and address in them was checked here, and the host
81
162
  program checks every line again before loading it. */
82
- const r = await this.#host(['net', 'apply', ruleset(taps, bridge ? wanted : [], bridge ?? '0.0.0.0')]);
83
- return r.code === 0 && (bridge !== undefined || wanted.length === 0);
163
+ const text = ruleset(vms, bridge ? wanted : [], bridge ?? '0.0.0.0');
164
+ const ok = bridge !== undefined || wanted.length === 0;
165
+ /* Loaded again anyway now and then: a table taken off by someone else comes back. */
166
+ if (this.#last?.text === text && this.#last.loaded && Date.now() - this.#last.at < RELOAD_MS) return ok;
167
+ const r = await this.#host(['net', 'apply', text]);
168
+ this.#last = { text, loaded: r.code === 0, at: Date.now() };
169
+ return r.code === 0 && ok;
170
+ }
171
+
172
+ /* Each VM's address: its pin, else its lease if no other VM holds it. */
173
+ #addresses(taps, leases) {
174
+ const keyOf = ({ pid, tap, mac }) => `${pid} ${tap} ${mac}`;
175
+ const running = new Set(Object.values(taps).filter((v) => v.mac && v.pid).map(keyOf));
176
+ for (const key of this.#pins.keys()) if (!running.has(key)) this.#pins.delete(key);
177
+ const vms = {};
178
+ for (const [name, v] of Object.entries(taps)) {
179
+ let ip = v.mac && v.pid ? this.#pins.get(keyOf(v)) : undefined;
180
+ const lease = v.mac ? leases[v.mac] : undefined;
181
+ if (!ip && lease && v.pid && ![...this.#pins.values()].includes(lease)) { ip = lease; this.#pins.set(keyOf(v), ip); }
182
+ vms[name] = { tap: v.tap, mac: v.mac, ip };
183
+ }
184
+ return vms;
185
+ }
186
+
187
+ /* KEPT UP TO DATE (04-11): a machine started by the VM manager itself -- after the server
188
+ restarted -- has a new tap that no opening told: looked at every `everyMs`, the table loaded
189
+ again only when what runs changed. Returns the stop. */
190
+ /* `quietMs`: none that soon after a start of the server (main.mjs, quietStartMs; it applies them once anyway). */
191
+ watch(everyMs = WATCH_MS, { quietMs = 0 } = {}) {
192
+ const quietUntil = Date.now() + quietMs;
193
+ const timer = setInterval(() => { if (Date.now() >= quietUntil) void this.apply().catch(() => {}); }, everyMs);
194
+ timer.unref?.();
195
+ return () => clearInterval(timer);
84
196
  }
85
197
  }
@@ -0,0 +1,129 @@
1
+ /* WHAT HOLDS THIS SERVER, measured (18-11: the owner's server waited about a second at every turn of its
2
+ * event loop, with little CPU seen -- Settings, Load): a few seconds of this server sampled by its own
3
+ * V8 profiler (node:inspector, in-process: no port opened), then said in short, the functions that
4
+ * took the most time themselves and with what they called. Text only, nothing kept.
5
+ *
6
+ * profile(seconds) { seconds, sampledMs, idleMs, gcMs, programMs, self: [{ fn, at, ms }], total: [...] }
7
+ * one at a time: asked again while one runs, the same one
8
+ */
9
+ import { Session } from 'node:inspector/promises';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ export const PROFILE_MIN_S = 2;
13
+ export const PROFILE_MAX_S = 30;
14
+ export const PROFILE_TOP = 15;
15
+ export const SAMPLE_US = 10_000;
16
+ const APP = fileURLToPath(new URL('..', import.meta.url));
17
+
18
+ /* Where a function is, short: within the application from its folder, a package by its name, else the file's name. */
19
+ export function placeOf(url, line) {
20
+ let path = String(url ?? '');
21
+ if (!path) return '';
22
+ if (path.startsWith('file://')) { try { path = fileURLToPath(path); } catch { /* left as it is */ } }
23
+ const inModules = path.lastIndexOf('/node_modules/');
24
+ if (inModules >= 0) path = path.slice(inModules + '/node_modules/'.length);
25
+ else if (path.startsWith(APP)) path = path.slice(APP.length);
26
+ else if (path.startsWith('/')) path = path.split('/').pop();
27
+ return line >= 0 ? `${path}:${line + 1}` : path;
28
+ }
29
+
30
+ /* A V8 CPU profile told in short: each sample's time to its node, then by function. */
31
+ export function summarize(profile, seconds, top = PROFILE_TOP) {
32
+ const nodes = new Map((profile.nodes ?? []).map((n) => [n.id, n]));
33
+ const selfUs = new Map();
34
+ const samples = profile.samples ?? []; const deltas = profile.timeDeltas ?? [];
35
+ for (let i = 0; i < samples.length; i++) selfUs.set(samples[i], (selfUs.get(samples[i]) ?? 0) + Math.max(0, deltas[i] ?? 0));
36
+ const parent = new Map();
37
+ for (const n of nodes.values()) for (const c of n.children ?? []) parent.set(c, n.id);
38
+ const special = { '(idle)': 0, '(garbage collector)': 0, '(program)': 0, '(root)': 0 };
39
+ const self = new Map(); const total = new Map();
40
+ const keyOf = (n) => { const f = n.callFrame ?? {}; return `${f.functionName || '(anonymous)'}\t${placeOf(f.url, f.lineNumber)}`; };
41
+ for (const [id, us] of selfUs) {
42
+ const n = nodes.get(id); if (!n) continue;
43
+ const name = n.callFrame?.functionName ?? '';
44
+ if (name in special && !n.callFrame?.url) { special[name] += us; continue; }
45
+ const k = keyOf(n); self.set(k, (self.get(k) ?? 0) + us);
46
+ /* Its time counted once to every function above it (a recursive one once). */
47
+ const seen = new Set();
48
+ for (let at = id; at !== undefined; at = parent.get(at)) {
49
+ const up = nodes.get(at); if (!up || (up.callFrame?.functionName === '(root)' && !up.callFrame?.url)) break;
50
+ const uk = keyOf(up); if (seen.has(uk)) continue; seen.add(uk);
51
+ total.set(uk, (total.get(uk) ?? 0) + us);
52
+ }
53
+ }
54
+ const list = (m) => [...m].sort((a, b) => b[1] - a[1]).slice(0, top).map(([k, us]) => { const [fn, at] = k.split('\t'); return { fn, at, ms: Math.round(us / 1000) }; });
55
+ const all = [...selfUs.values()].reduce((a, b) => a + b, 0);
56
+ return {
57
+ seconds, sampledMs: Math.round(all / 1000), idleMs: Math.round(special['(idle)'] / 1000),
58
+ gcMs: Math.round(special['(garbage collector)'] / 1000), programMs: Math.round(special['(program)'] / 1000),
59
+ self: list(self), total: list(total),
60
+ };
61
+ }
62
+
63
+ export class Profiler {
64
+ #running = null; #session; #wait;
65
+ constructor({ session = () => new Session(), wait = (ms) => new Promise((ok) => { setTimeout(ok, ms); }) } = {}) { this.#session = session; this.#wait = wait; }
66
+ profile(seconds = 10) {
67
+ const s = Math.min(PROFILE_MAX_S, Math.max(PROFILE_MIN_S, Math.round(Number(seconds) || 10)));
68
+ if (this.#running) return this.#running;
69
+ this.#running = (async () => {
70
+ const session = this.#session();
71
+ session.connect();
72
+ try {
73
+ await session.post('Profiler.enable');
74
+ /* 100 samples a second: light on a busy server (18-11: at 1000 a second, the owner's busy server stopped answering). */
75
+ await session.post('Profiler.setSamplingInterval', { interval: SAMPLE_US });
76
+ await session.post('Profiler.start');
77
+ const began = process.cpuUsage();
78
+ await this.#wait(s * 1000);
79
+ const { profile } = await session.post('Profiler.stop');
80
+ const cpu = process.cpuUsage(began);
81
+ return { ...summarize(profile, s), cpuMs: Math.round((cpu.user + cpu.system) / 1000) };
82
+ } finally {
83
+ try { await session.post('Profiler.disable'); } catch { /* closing anyway */ }
84
+ session.disconnect();
85
+ }
86
+ })().finally(() => { this.#running = null; });
87
+ return this.#running;
88
+ }
89
+ }
90
+
91
+ /* MEASURED BY ITSELF (18-11, the owner: an intermittent stall needs nobody before the screen): every
92
+ WATCH_EVERY_MS the event loop's delay of the last minute is looked at; past SLOW_P50_MS, a measure is
93
+ taken (as Measure 10 s), at most once in AUTO_EVERY_MS (a measure costs a little itself), the last
94
+ AUTO_KEPT kept with when and why, in `file` (JsonFile: they outlive a restart). */
95
+ export const WATCH_EVERY_MS = 60_000;
96
+ export const SLOW_P50_MS = 200;
97
+ export const AUTO_EVERY_MS = 30 * 60_000;
98
+ export const AUTO_KEPT = 5;
99
+ export const AUTO_SECONDS = 10;
100
+ /* Never in its first minutes (18-11: 0.2.232 measured itself during the updater's health watch on the owner's slow
101
+ server, and did not answer in time: put back). */
102
+ export const AUTO_AFTER_START_MS = 15 * 60_000;
103
+ export class AutoProfile {
104
+ #profiler; #file; #now; #delay; #log; #last = 0; #timer = null; #started;
105
+ /* `delay()`: the loop's delay of the last minute, { p50, p99 } in ms, then started again (a histogram of its own). */
106
+ constructor({ profiler, file, now = () => Date.now(), delay, log = (line) => console.log(line) }) {
107
+ this.#profiler = profiler; this.#file = file; this.#now = now; this.#delay = delay; this.#log = log; this.#started = now();
108
+ const kept = this.kept(); this.#last = kept[0] ? Date.parse(kept[0].at) || 0 : 0;
109
+ }
110
+ kept() { const v = this.#file?.get(); return Array.isArray(v?.profiles) ? v.profiles : []; }
111
+ start(everyMs = WATCH_EVERY_MS) { this.#timer = setInterval(() => { void this.check(); }, everyMs); this.#timer.unref?.(); return this; }
112
+ stop() { clearInterval(this.#timer); }
113
+ async check() {
114
+ const d = this.#delay();
115
+ if (this.#now() - this.#started < AUTO_AFTER_START_MS) return null;
116
+ if (!d || !(d.p50 > SLOW_P50_MS)) return null;
117
+ if (this.#now() - this.#last < AUTO_EVERY_MS) return null;
118
+ this.#last = this.#now();
119
+ const why = `loop p50 ${d.p50} ms, p99 ${d.p99} ms over the last minute`;
120
+ this.#log(`profile: measuring ${AUTO_SECONDS} s by itself (${why})`);
121
+ try {
122
+ const p = await this.#profiler.profile(AUTO_SECONDS);
123
+ const entry = { at: new Date(this.#last).toISOString(), why, ...p };
124
+ this.#file?.set({ profiles: [entry, ...this.kept()].slice(0, AUTO_KEPT) });
125
+ this.#log(`profile: ${p.self.slice(0, 5).map((f) => `${f.fn} ${f.ms}ms ${f.at}`).join('; ')}`);
126
+ return entry;
127
+ } catch (error) { this.#log(`profile: not measured (${error?.message ?? error})`); return null; }
128
+ }
129
+ }
@@ -0,0 +1,67 @@
1
+ /* ANOTHER HOME JOINS THIS MACHINE'S RELAY: POST /c/relay-join, with no sign-in (the front lets /c/
2
+ * through), the one-time code being the right. See deploy/online.mjs ("SEVERAL HOMES ON ONE RELAY").
3
+ *
4
+ * POST /c/relay-join {"code": "ABCD-EFGH", "key": "ssh-ed25519 AAAA..."}
5
+ * 200 {"name", "relay": {"host", "port", "fingerprint"}, "ports": {"tls", "http"}}
6
+ * 400 not this shape; 403 not a valid code (wrong, used or expired); 429 too many tries; 502 the relay did not add it
7
+ *
8
+ * The server only carries it: the code is checked, spent and acted on by root (host program, "relay
9
+ * join"), where the server cannot read the codes. Here: a body of exactly these two fields, a code of
10
+ * the right shape, a PUBLIC ed25519 key (its comment dropped) and nothing else; at most PER_MINUTE
11
+ * tries a minute, from everybody together (behind the relay, every caller has the same address). The
12
+ * answer is rebuilt field by field from what root printed: nothing else can go out.
13
+ */
14
+ import { Refusal } from './conversations.mjs';
15
+
16
+ export const RELAY_JOIN_PATH = '/c/relay-join';
17
+ export const PER_MINUTE = 6;
18
+ const CODE = /^[A-HJKMNP-Z2-9]{8}$/;
19
+ const KEY = /^ssh-ed25519 ([A-Za-z0-9+/]{68})( [A-Za-z0-9@._-]{1,64})?$/;
20
+ const HOST = /^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,24}$|^([0-9]{1,3}\.){3}[0-9]{1,3}$/;
21
+ const PRINT = /^SHA256:[A-Za-z0-9+/]{43}$/;
22
+ const NOT_VALID = 'This code is not valid: wrong, used or expired. Ask the owner of that Clavarium for a new one.';
23
+
24
+ export class RelayJoin {
25
+ #host; #now; #tries = [];
26
+ /* `host(argv)`: the host program (vm.mjs, runner) -> { code, stdout, stderr }. */
27
+ constructor({ host, now = Date.now }) { this.#host = host; this.#now = now; }
28
+
29
+ /* -> { status, body }. `text`: the request's body. */
30
+ async join(text) {
31
+ const now = this.#now();
32
+ this.#tries = this.#tries.filter((t) => t > now - 60_000);
33
+ if (this.#tries.length >= PER_MINUTE) return { status: 429, body: { error: 'Too many tries: wait a minute.' } };
34
+ this.#tries.push(now);
35
+ let given;
36
+ try { given = JSON.parse(text); } catch { return { status: 400, body: { error: 'Not JSON.' } }; }
37
+ if (!given || typeof given !== 'object' || Array.isArray(given) || Object.keys(given).sort().join(',') !== 'code,key') return { status: 400, body: { error: 'Send {"code", "key"} and nothing else.' } };
38
+ const code = String(given.code).toUpperCase().replace(/[\s-]/g, '');
39
+ const key = KEY.exec(typeof given.key === 'string' ? given.key.trim() : '');
40
+ if (typeof given.code !== 'string' || !CODE.test(code)) return { status: 403, body: { error: NOT_VALID } };
41
+ if (!key) return { status: 400, body: { error: 'The key is the PUBLIC tunnel key: one line, ssh-ed25519 and the key.' } };
42
+ const r = await this.#host(['relay', 'join', code, 'ssh-ed25519', key[1]], { timeoutMs: 120_000 });
43
+ if (r.code === 78) return { status: 403, body: { error: NOT_VALID } };
44
+ if (r.code !== 0) return { status: 502, body: { error: 'The relay did not add this home just now: try again, or ask the owner of that Clavarium.' } };
45
+ let a;
46
+ try { a = JSON.parse(String(r.stdout).trim().split('\n').pop()); } catch { a = null; }
47
+ const port = (v, lo) => Number.isInteger(v) && v >= lo && v <= 65535;
48
+ if (!a || typeof a.name !== 'string' || !HOST.test(a.name) || !HOST.test(a.relay?.host ?? '') || !port(a.relay?.port, 1) || !PRINT.test(a.relay?.fingerprint ?? '')
49
+ || !port(a.ports?.tls, 1024) || !port(a.ports?.http, 1024)) return { status: 502, body: { error: 'The relay did not answer as expected.' } };
50
+ return { status: 200, body: { name: a.name, relay: { host: a.relay.host, port: a.relay.port, fingerprint: a.relay.fingerprint }, ports: { tls: a.ports.tls, http: a.ports.http } } };
51
+ }
52
+ }
53
+
54
+ /* The route, answered here when it is this one (true). */
55
+ export async function handleRelayJoin(request, response, join, headers = {}) {
56
+ const say = (status, body) => { response.writeHead(status, { ...headers, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }).end(JSON.stringify(body)); return true; };
57
+ if (request.method !== 'POST') return say(405, { error: 'Call this address with POST.' });
58
+ let text = '';
59
+ for await (const piece of request) { text += piece; if (text.length > 2048) return say(413, { error: 'Too long.' }); }
60
+ try {
61
+ const { status, body } = await join.join(text);
62
+ return say(status, body);
63
+ } catch (error) {
64
+ if (error instanceof Refusal) return say(error.status, { error: error.message });
65
+ return say(502, { error: 'The relay did not add this home just now.' });
66
+ }
67
+ }
@@ -140,6 +140,12 @@ export class Resources {
140
140
  }
141
141
  get(name) { return this.#store.get(name); }
142
142
 
143
+ /* The conversations a folder is attached to. */
144
+ attachedTo(name) {
145
+ const resource = this.#store.get(name);
146
+ return resource ? Object.keys(this.#attachments(resource)) : [];
147
+ }
148
+
143
149
  /* What one conversation has attached: [{ name, access }]. */
144
150
  of(conversation) {
145
151
  return this.#store.all().map((r) => ({ name: r.name, access: this.#attachments(r)[conversation] })).filter((r) => r.access !== undefined);
@@ -0,0 +1,70 @@
1
+ /* ITS TOOL STARTED AGAIN WHEN A FOLDER IT WAS IN CAME LOOSE (16-11).
2
+ *
3
+ * Seen in production: /work of a conversation came loose ("socket is not connected"). Putting the
4
+ * folder back (health.mjs, resources.mjs repair) makes a NEW mount; its tool, and every program it
5
+ * started (its shell, Parley, Docket), stays in the old one, dead, until it is started again. It cannot
6
+ * even ask to be restarted: that request is a file in /work. Its owner typed exit by hand; this does it.
7
+ *
8
+ * Told by health.mjs, each look (`judged`):
9
+ * - `stale`: a program of its tool's session is in a folder that cannot be entered;
10
+ * - `restartAsked`: its tool asked from outside /work (health.mjs, RESTART_OUTSIDE);
11
+ * - `stuckWork`: its work folder cannot be mounted again (health.mjs, STUCK_MOUNT): its MACHINE is restarted
12
+ * (`restartMachine`), the one thing that mounts it again; it outranks the others.
13
+ * Then, at the next tick: its tool only is restarted (conversations.mjs restartTool, never its
14
+ * machine), once its turn has ended -- or after WAIT_MS anyway when stale: a tool stuck in a dead
15
+ * folder cannot say its turn ended (its pulse is in /work). Never a loop: not again within AGAIN_MS.
16
+ * Its tool told through its docket before it starts again, its owner through What happened.
17
+ */
18
+ export const WAIT_MS = 5 * 60_000;
19
+ export const AGAIN_MS = 30 * 60_000;
20
+
21
+ export class Revive {
22
+ #restart; #restartMachine; #busy; #tell; #taken; #now; #wanted = new Map(); #lastAt = new Map(); #going = new Set();
23
+
24
+ /* `restart(name)`: its tool restarted, resolves with whether it was. `busy(name)`: its turn goes on.
25
+ `tell(name, why, step)`: said where it should be, step 'before' (its docket), then 'done' or 'failed' (main.mjs).
26
+ `taken(name)`: the request outside /work removed (in its machine). */
27
+ constructor({ restart, restartMachine = async () => false, busy = () => false, tell = () => {}, taken = async () => {}, now = Date.now }) {
28
+ this.#restart = restart; this.#restartMachine = restartMachine; this.#busy = busy; this.#tell = tell; this.#taken = taken; this.#now = now;
29
+ }
30
+
31
+ /* What one look found. A look that finds it well forgets a stale one not yet acted on. */
32
+ judged(name, record) {
33
+ if (!record || record.state !== 'Running' || record.answering !== true) return;
34
+ if (record.restartAsked) { void Promise.resolve().then(() => this.#taken(name)).catch(() => {}); this.#want(name, 'asked'); }
35
+ if (record.stuckWork) this.#want(name, 'stuck');
36
+ else if (record.stale) this.#want(name, 'stale');
37
+ else if (['stale', 'stuck'].includes(this.#wanted.get(name)?.why)) this.#wanted.delete(name);
38
+ }
39
+
40
+ #want(name, why) {
41
+ const had = this.#wanted.get(name);
42
+ /* stuck over stale over a plain request: the stronger is acted on, even while it looks busy. */
43
+ const rank = { asked: 0, stale: 1, stuck: 2 };
44
+ if (!had || rank[why] > rank[had.why]) this.#wanted.set(name, { why, since: had?.since ?? this.#now() });
45
+ }
46
+
47
+ wanted(name) { return this.#wanted.get(name)?.why ?? null; }
48
+ forget(name) { this.#wanted.delete(name); this.#lastAt.delete(name); }
49
+
50
+ /* One pass: each one wanted, restarted when it may be. Resolves with the names restarted. */
51
+ async tick() {
52
+ const done = [];
53
+ for (const [name, { why, since }] of [...this.#wanted]) {
54
+ if (this.#going.has(name)) continue;
55
+ const busy = (() => { try { return this.#busy(name); } catch { return false; } })();
56
+ if (busy && !(why !== 'asked' && this.#now() - since >= WAIT_MS)) continue;
57
+ this.#wanted.delete(name);
58
+ if (this.#now() - (this.#lastAt.get(name) ?? -Infinity) < AGAIN_MS) continue;
59
+ this.#lastAt.set(name, this.#now());
60
+ this.#going.add(name);
61
+ try {
62
+ try { this.#tell(name, why, 'before'); } catch { /* told, nothing more */ }
63
+ const ok = await (why === 'stuck' ? this.#restartMachine(name) : this.#restart(name)).catch(() => false);
64
+ if (ok) done.push(name);
65
+ try { this.#tell(name, why, ok ? 'done' : 'failed'); } catch { /* told, nothing more */ }
66
+ } finally { this.#going.delete(name); }
67
+ }
68
+ return done;
69
+ }
70
+ }