clavarium 0.2.535-next.1 → 0.2.537-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.
@@ -963,11 +963,9 @@ case "$AREA $VERB" in
963
963
  [ $# -le 1 ] || usage
964
964
  if [ $# -eq 1 ]; then
965
965
  [ "$1" = "hard" ] || refuse "vm revive [hard]"
966
- if [ "$SAY" = "yes" ]; then echo "snap stop multipass.multipassd; pkill -KILL -x multipassd; snap start multipass.multipassd"; exit 0; fi
967
- timeout 120 snap stop multipass.multipassd || true
968
- pkill -KILL -x multipassd 2>/dev/null || true
969
- sleep 2
970
- run timeout 120 snap start multipass.multipassd
966
+ unstick="$CODE/current/app/deploy/multipass-unstick.sh"
967
+ if [ "$SAY" = "yes" ]; then echo "$unstick (daemon stopped, its old dnsmasq ended, failed starts reset, started)"; exit 0; fi
968
+ run timeout 300 bash "$unstick"
971
969
  else
972
970
  run timeout 170 snap restart multipass.multipassd
973
971
  fi ;;
@@ -1,3 +1,4 @@
1
+ import { fileURLToPath } from 'node:url';
1
2
  /* MULTIPASS UPDATED IN CLAVARIUM'S OWN WINDOW (23-11, its owner's ask, after a morning on a real server: snap
2
3
  * updated Multipass by itself at 06:08, every machine was left suspended, nothing could be reached).
3
4
  *
@@ -16,6 +17,8 @@ const BACK_TRIES = 36;
16
17
  const BACK_EVERY_MS = 5_000;
17
18
  export const TRY_EVERY_MS = 20 * 3600_000;
18
19
  /* In the data folder while it runs: the server's watch leaves Multipass alone (vmwatch.mjs, `paused`). */
20
+ /* Its daemon stopped, its old dnsmasq ended, systemd's failed starts reset, started (multipass-unstick.sh, 25-11). */
21
+ export const UNSTICK = fileURLToPath(new URL('multipass-unstick.sh', import.meta.url));
19
22
  export const MULTIPASS_UPDATING = 'multipass-updating';
20
23
 
21
24
  const first = (r) => String(r?.stderr || r?.stdout || '').trim().split('\n').filter(Boolean).pop()?.slice(0, 200) || `exit ${r?.code}`;
@@ -68,7 +71,7 @@ export async function multipassTurn({ run, mode, inWindow, busy, state, save, lo
68
71
  for (const [what, argv] of steps) {
69
72
  log(`multipass: it does not answer: ${what}`);
70
73
  if (argv) await sh(argv, REFRESH_MS);
71
- else { await sh(['snap', 'stop', 'multipass.multipassd'], SNAP_MS); await sh(['pkill', '-KILL', '-x', 'multipassd'], 30_000); await sleep(2_000); await sh(['snap', 'start', 'multipass.multipassd'], SNAP_MS); }
74
+ else await sh(['bash', UNSTICK], 300_000);
72
75
  if (await answers()) { log(`multipass: it answers again (${what})`); return true; }
73
76
  }
74
77
  return false;
@@ -0,0 +1,53 @@
1
+ #!/bin/bash
2
+ # MULTIPASS STOPPED AND STARTED FOR SURE (25-11, on a real server: after its update its daemon restarted, but its
3
+ # old dnsmasq -- the small server giving its machines their addresses -- stayed alive, still holding port 53; each new
4
+ # daemon died starting its own ("Address already in use"), systemd gave up ("Start request repeated too quickly"),
5
+ # and only a restart of the whole server freed it). Its daemon stopped; what stays of its dnsmasq in its control
6
+ # group ended; systemd's count of failed starts reset; started.
7
+ # Its machines left running by a daemon that died (qemu in its group, 25-11 on test-c: the new daemon cannot take
8
+ # them back -- "Failed to get shared write lock" on their disks -- and stays mute) are stopped too, step by step as
9
+ # a forced stop is (the host program's vm halt): asked to shut down from inside (with the VM manager's own key, a
10
+ # minute), then asked to end (10 s), then ended. Each step said; the server's watch then starts again those that ran.
11
+ # Run as root, by the host program (vm revive hard) and the updater (deploy/multipass-refresh.mjs).
12
+ set -u
13
+ UNIT=snap.multipass.multipassd.service
14
+ # Where the VM manager keeps its data (moved to another disk: its MULTIPASS_STORAGE), for its leases and its key.
15
+ DATA="/var/snap/multipass/common/data/multipassd"
16
+ MOVED_TO="$(sed -n 's/^Environment=MULTIPASS_STORAGE=\(\/[A-Za-z0-9/._-]*\)$/\1/p' /etc/systemd/system/$UNIT.d/override.conf 2>/dev/null | head -1)"
17
+ [ -n "$MOVED_TO" ] && [ -d "$MOVED_TO/data" ] && DATA="$MOVED_TO/data"
18
+ gone() { ! kill -0 "$1" 2>/dev/null; }
19
+ # A machine whose daemon died: shut down from inside, then asked to end, then ended.
20
+ halt_orphan() {
21
+ local pid="$1" name="$2" ip i
22
+ ip="$(awk -v n="$name" '$4 == n {print $3}' "$DATA/network/dnsmasq.leases" 2>/dev/null | tail -1)"
23
+ if [ -n "$ip" ] && [ -r "$DATA/ssh-keys/id_rsa" ] && timeout 20 ssh -i "$DATA/ssh-keys/id_rsa" -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=8 "ubuntu@$ip" sudo shutdown -h now >/dev/null 2>&1; then
24
+ # Its system shuts down (about 20 s on a test machine); its qemu then waits, paused (Multipass starts it
25
+ # with -no-shutdown): ended once its system is down.
26
+ for i in $(seq 1 45); do gone "$pid" && break; ping -c 1 -W 1 "$ip" >/dev/null 2>&1 || { [ "$i" -ge 5 ] && break; }; sleep 1; done
27
+ gone "$pid" || sleep 8 # its network goes before its disks are done
28
+ kill -TERM "$pid" 2>/dev/null || true
29
+ for i in $(seq 1 10); do gone "$pid" && break; sleep 1; done
30
+ gone "$pid" || kill -KILL "$pid" 2>/dev/null || true
31
+ echo " $name: shut down from inside"; return
32
+ fi
33
+ kill -TERM "$pid" 2>/dev/null || true
34
+ for i in $(seq 1 10); do gone "$pid" && { echo " $name: asked to end"; return; }; sleep 1; done
35
+ kill -KILL "$pid" 2>/dev/null || true
36
+ echo " $name: ended"
37
+ }
38
+ timeout 120 snap stop multipass.multipassd >/dev/null 2>&1 || true
39
+ for procs in "/sys/fs/cgroup/system.slice/$UNIT/cgroup.procs" "/sys/fs/cgroup/systemd/system.slice/$UNIT/cgroup.procs"; do
40
+ [ -r "$procs" ] || continue
41
+ for pid in $(cat "$procs" 2>/dev/null); do
42
+ comm="$(cat "/proc/$pid/comm" 2>/dev/null)"
43
+ case "$comm" in
44
+ dnsmasq) echo "its old dnsmasq ended ($pid)"; kill -KILL "$pid" 2>/dev/null || true ;;
45
+ qemu-system-*) name="$(tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null | grep -o 'instances/[a-z0-9-]*' | head -1 | cut -d/ -f2)"
46
+ echo "a machine left by the dead daemon, stopped: ${name:-?} ($pid)"; halt_orphan "$pid" "${name:-?}" ;;
47
+ esac
48
+ done
49
+ done
50
+ pkill -KILL -x multipassd 2>/dev/null || true
51
+ systemctl reset-failed "$UNIT" 2>/dev/null || true
52
+ sleep 2
53
+ timeout 120 snap start multipass.multipassd
@@ -667,6 +667,15 @@ export class Updater {
667
667
  const live = busy.filter((c) => !stale.includes(c));
668
668
  return live.length ? `a machine is being built or restarted (${names(live)}): the update waits` : '';
669
669
  }
670
+ /* MEMBERS AND AN OLDER RELEASE (#419). A release from before accounts and rights takes every account for an
671
+ administrator: once accounts and rights were used here (people.json written, at the first member), going back to
672
+ one is refused, by hand and by the watchdog -- as for a release that cannot read the data. Undefined: allowed. */
673
+ #membersBlock(to) {
674
+ /* A release that reads the lists of today (0.2.526-next.1 wrote another form: refused too). */
675
+ try { if (readFileSync(join(to.app, 'server', 'people.mjs'), 'utf8').includes('export const PEOPLE_LISTS')) return undefined; } catch { /* none: from before accounts */ }
676
+ const file = join(this.#o.data, 'people.json');
677
+ return existsSync(file) || existsSync(`${file}.bak`) ? `${to.version} does not know these members: it would not read who is an administrator` : undefined;
678
+ }
670
679
  #dataFormat() { try { return JSON.parse(readFileSync(join(this.#o.data, 'data-format.json'), 'utf8')).format; } catch { return undefined; } }
671
680
 
672
681
  /* Whether the lock is held by a process alive now -- of THIS start of the machine (25-11, on a test machine: frozen
@@ -722,6 +731,9 @@ export class Updater {
722
731
  this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: error.message, ...(fetched ? { fetch: true } : {}), ...(typeof error.log === 'string' && error.log ? { log: error.log.slice(-LOG_MAX) } : {}) });
723
732
  throw error;
724
733
  }
734
+ /* Members here, and a release that would not read them (a newer number cut without them, say): not installed. */
735
+ const blocked = this.#membersBlock(release);
736
+ if (blocked) { rmSync(release.dir, { recursive: true, force: true }); this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: blocked }); throw new Refused(blocked); }
725
737
  const before = this.#dataFormat();
726
738
  let archive;
727
739
  try {
@@ -763,6 +775,7 @@ export class Updater {
763
775
  if (to.current) throw new Refused(`${id} is the release that runs`);
764
776
  const format = this.#dataFormat();
765
777
  if (format !== undefined && to.dataFormat < format) throw new Refused(`${to.version} cannot read the data of this version (format ${format}; it reads ${to.dataFormat})`);
778
+ const members = this.#membersBlock(to); if (members) throw new Refused(members);
766
779
  const why = await this.busy(); if (why) throw new Refused(why);
767
780
  const unlock = this.#lock();
768
781
  try {
@@ -891,7 +904,7 @@ export class Updater {
891
904
  const recent = failed && current && last && last.action === 'update' && last.result === 'done' && last.to === current.version && now - new Date(last.at) < WATCH_RECENT_MS;
892
905
  const previous = recent ? this.releases().find((r) => !r.current && r.version === last.from) : undefined;
893
906
  const format = this.#dataFormat();
894
- if (previous && (format === undefined || previous.dataFormat >= format)) {
907
+ if (previous && (format === undefined || previous.dataFormat >= format) && !this.#membersBlock(previous)) {
895
908
  let why = `${current.version} did not stay up (its service ${state === 'active' ? 'did not answer' : `was ${state}`}) nor came back after a restart (${failed}): back to ${previous.version}`;
896
909
  this.#o.log(`watchdog: ${why}`);
897
910
  this.#step('update', current.version, 'Going back');
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.535-next.1",
3
+ "version": "0.2.537-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.535-next.1",
9
+ "version": "0.2.537-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.535-next.1",
3
+ "version": "0.2.537-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
package/server/api.mjs CHANGED
@@ -493,7 +493,8 @@ export async function handleApi(request, response, conversations, headers, resou
493
493
  if (pathname === '/api/wifi' && wifi) return send(200, await wifi.status()), true;
494
494
  if (pathname === '/api/wifi/scan' && wifi) return send(200, await wifi.scan()), true;
495
495
  if (pathname === '/api/meshcentral' && meshcentral) return send(200, await meshcentral.status()), true;
496
- if (pathname === '/api/operators') return send(200, team ? { operators: team.list(), me: identity } : { local: true }), true;
496
+ /* Each account with its role and, for a member, the conversations it was given (#419). */
497
+ if (pathname === '/api/operators') return send(200, team ? { operators: team.list().map((o) => ({ ...o, role: team.people?.roleOf(o.email) ?? 'admin', ...(team.people?.roleOf(o.email) === 'member' ? { given: team.grants?.of(`person:${o.email}`, 'conversation').map((g) => ({ name: g.name, rights: g.rights })) ?? [] } : {}) })), me: identity, defaultRole: team.people?.defaultRole?.() ?? 'admin' } : { local: true }), true;
497
498
  if (pathname === '/api/binder/people' && binders) return send(200, { people: binders.people(identity), changes: `${BOOT}:${binders.changes()}` }), true;
498
499
  if (pathname === '/api/certificate' && certificate) return send(200, await certificate.about({ fresh: query.get('fresh') === '1' })), true;
499
500
  /* This server's disk and memory (capacity.mjs): everything for Settings; only whether it is high for the list. */
@@ -591,6 +592,7 @@ export async function handleApi(request, response, conversations, headers, resou
591
592
  return send(403, { error: 'This request does not come from this site.' }), true;
592
593
  }
593
594
  const body = await readBody(request, pathname === '/api/setup/preview' || pathname === '/api/setup/import' ? SETUP_BODY_MAX : BODY_MAX);
595
+ if (request.stillAllowed && !request.stillAllowed()) throw new Refusal(403, 'Your account changed: sign in again.');
594
596
  /* A SIGN-IN CODE (#405): answered before anything below can see this body (the journal, say). */
595
597
  const codeOf = /^\/api\/conversations\/([^/]+)\/signin-code$/.exec(pathname);
596
598
  if (codeOf && conversations.signinHelp) return send(200, await conversations.signinHelp.enterCode(decodeURIComponent(codeOf[1]), body?.code)), true;
@@ -791,13 +793,53 @@ export async function handleApi(request, response, conversations, headers, resou
791
793
  if (pathname === '/api/wifi/handover' && wifi) return send(202, await wifi.handover()), true;
792
794
  if (pathname === '/api/meshcentral/enable' && meshcentral) return send(202, await meshcentral.enable()), true;
793
795
  if (pathname === '/api/meshcentral/disable' && meshcentral) return send(200, await meshcentral.disable()), true;
794
- if (pathname === '/api/operators' && team) return send(201, await team.add(body.email)), true;
796
+ if (pathname === '/api/operators' && team) {
797
+ /* Its role said at once (#419): an account removed and added again does not come back as it was. */
798
+ const role = body.role === 'member' ? 'member' : body.role === 'admin' ? 'admin' : (team.people?.defaultRole?.() ?? 'admin');
799
+ const adding = String(body.email ?? '').trim().toLowerCase();
800
+ /* An account there already keeps its role: changed by its own way, with its checks (audit 6, 24-11). */
801
+ if (team.list().some((o) => o.email === adding)) throw new Refusal(409, 'This account exists already.');
802
+ /* Nothing of a past account of that address comes back with the new one. */
803
+ team.grants?.forgetSubject(`person:${adding}`);
804
+ const undo = team.people?.adding(adding, role);
805
+ let made;
806
+ try { made = await team.add(body.email); } catch (error) { undo?.(); throw error; }
807
+ return send(201, { ...made, role: team.people?.roleOf(made.email) ?? 'admin' }), true;
808
+ }
809
+ /* An account made an administrator or a member (#419): never oneself, never the last administrator. */
810
+ const roleOf = /^\/api\/operators\/([^/]{3,200})\/role$/.exec(pathname);
811
+ if (roleOf && team?.people) {
812
+ const email = decodeURIComponent(roleOf[1]).trim().toLowerCase();
813
+ if (email === identity) throw new Refusal(409, 'You cannot change your own role: ask another administrator.');
814
+ const changed = team.people.setRole(email, String(body.role ?? ''));
815
+ /* Made an administrator: what it was given as a member is forgotten, not given back if it is a member again (audit 13). */
816
+ if (team.people.roleOf(email) === 'admin') team.grants?.forgetSubject(`person:${email}`);
817
+ return send(200, { operators: changed }), true;
818
+ }
819
+ /* A conversation given to a member, or taken back: its chat (read or write) and/or its terminal (#419). */
820
+ const giving = /^\/api\/operators\/([^/]{3,200})\/(give|take)$/.exec(pathname);
821
+ if (giving && team?.people && team.grants) {
822
+ const email = decodeURIComponent(giving[1]).trim().toLowerCase();
823
+ if (!team.list().some((o) => o.email === email)) throw new Refusal(404, 'No such account.');
824
+ if (team.people.roleOf(email) !== 'member') throw new Refusal(409, 'Only a member is given conversations: an administrator has them all.');
825
+ const name = String(body.conversation ?? '');
826
+ if (!conversations.list().some((c) => c.name === name)) throw new Refusal(404, 'No such conversation.');
827
+ const rights = giving[2] === 'take' ? '' : `${body.chat === 'write' ? 'rw' : body.chat === 'read' ? 'r' : ''}${body.terminal === true ? 'x' : ''}`;
828
+ if (rights === '') team.grants.take(`person:${email}`, `conversation:${name}`);
829
+ else team.grants.give(`person:${email}`, `conversation:${name}`, rights);
830
+ team.people.changed?.();
831
+ return send(200, { given: team.grants.of(`person:${email}`, 'conversation').map((g) => ({ name: g.name, rights: g.rights })) }), true;
832
+ }
795
833
  const op = /^\/api\/operators\/([^/]{3,200})\/(password|disable|enable|remove)$/.exec(pathname);
796
834
  if (op && team) {
797
- const email = decodeURIComponent(op[1]);
835
+ const email = decodeURIComponent(op[1]).trim().toLowerCase();
798
836
  /* Not oneself out: another operator does it, or nobody would see it was a mistake. */
799
837
  if (op[2] !== 'password' && op[2] !== 'enable' && email.toLowerCase() === identity) throw new Refusal(409, 'You cannot do that to your own account: ask another operator.');
800
- return send(200, op[2] === 'password' ? await team.password(email) : { operators: await team[op[2]](email) }), true;
838
+ const done = op[2] === 'password' ? await team.password(email) : { operators: await team[op[2]](email) };
839
+ /* Removed: its role and what it was given go with it (#419). */
840
+ if (op[2] === 'remove') { team.people?.removed(email); team.grants?.forgetSubject(`person:${email.toLowerCase()}`); }
841
+ team.people?.changed?.();
842
+ return send(200, done), true;
801
843
  }
802
844
  const renaming = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/rename$/.exec(pathname);
803
845
  /* Its machines that run get the new name or value now, as a secret given to them does. */
@@ -1320,6 +1320,8 @@ export async function handleApiKeys(request, response, keys, originOk, headers =
1320
1320
  for await (const piece of request) { text += piece; if (text.length > 16_384) return send(413, { error: 'Too long.' }); }
1321
1321
  let body;
1322
1322
  try { body = text ? JSON.parse(text) : {}; } catch { return send(400, { error: 'The request is not JSON.' }); }
1323
+ /* One made a member or disabled while its request came makes no key (audit 8). */
1324
+ if (request.stillAllowed && !request.stillAllowed()) return send(403, { error: 'Your account changed: sign in again.' });
1323
1325
  if (!body || typeof body !== 'object') body = {};
1324
1326
  if (pathname === '/api/apikeys') {
1325
1327
  const made = keys.create({ label: body.label, scopes: body.scopes ?? [], conversations: body.conversations ?? {}, rooms: body.rooms ?? {}, boxes: body.boxes ?? {}, binders: body.binders ?? {}, days: body.days === undefined ? DEFAULT_DAYS : body.days }, who);
package/server/bridge.mjs CHANGED
@@ -90,7 +90,9 @@ export const sameOrigin = makeOriginCheck();
90
90
  const BY_ITSELF = /\x1b\[[IO]|\x1b\[\??[>=]?[\d;]*c|\x1b\[\d+;\d+R|\x1b\][\d;]*(?:rgb:[0-9a-fA-F/]+)?(?:\x07|\x1b\\)|\x1bP[^\x1b]*\x1b\\/g;
91
91
  export const byHand = (typed) => String(typed ?? '').replace(BY_ITSELF, '').length > 0;
92
92
 
93
- export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () => {}, originOk = sameOrigin, gate = () => 'local', deviceName = () => undefined, onRejoin = () => {}, onTyped = () => {}, asleep = () => false }) {
93
+ export const MEMBER_PATH = '/m/terminal';
94
+
95
+ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () => {}, originOk = sameOrigin, gate = () => 'local', deviceName = () => undefined, memberName = () => undefined, onRejoin = () => {}, onTyped = () => {}, asleep = () => false }) {
94
96
  const sockets = new WebSocketServer({ noServer: true });
95
97
  const seats = new Seats();
96
98
  /* THE DEVICES AT A TERMINAL, each with what lets it stay: asked again when the owner changes
@@ -98,6 +100,8 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
98
100
  back used to end only at the next connection -- an open terminal went on (found 19-10). */
99
101
  const deviceSeats = new Map(); /* viewer -> () => still allowed */
100
102
  const revoked = new WeakSet();
103
+ /* Who a screen is, for What happened: a paired device, a member (#419), else the page of an administrator. */
104
+ const fromDevice = new WeakSet(); const fromMember = new WeakSet();
101
105
  const allowed = (viewer) => {
102
106
  if (revoked.has(viewer)) return false;
103
107
  const still = deviceSeats.get(viewer);
@@ -120,9 +124,18 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
120
124
  name = ask();
121
125
  if (!isConversationName(name) || !originOk(request.headers)) { socket.destroy(); return; }
122
126
  still = () => ask() === name;
127
+ } else if (url.pathname === MEMBER_PATH) {
128
+ /* A member (people.mjs, #419): the sign-in names it; the terminal of a conversation it was given, only. */
129
+ const wanted = url.searchParams.get('c') ?? '';
130
+ const ask = () => memberName(request.headers, wanted) ?? '';
131
+ name = ask();
132
+ if (!isConversationName(name) || !originOk(request.headers)) { socket.destroy(); return; }
133
+ still = () => ask() === name;
123
134
  } else if (url.pathname === PATH) {
124
135
  name = url.searchParams.get('c') ?? '';
125
136
  if (!isConversationName(name) || !originOk(request.headers) || gate(request.headers) === undefined) { socket.destroy(); return; }
137
+ /* An administrator made a member, or an account disabled: its open terminals end too (#419). */
138
+ still = () => gate(request.headers) !== undefined;
126
139
  } else return;
127
140
  const cols = Number(url.searchParams.get('cols'));
128
141
  const rows = Number(url.searchParams.get('rows'));
@@ -130,6 +143,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
130
143
  const resume = url.searchParams.get('resume') === '1';
131
144
  sockets.handleUpgrade(request, socket, head, (viewer) => {
132
145
  if (still) { deviceSeats.set(viewer, still); viewer.on('close', () => deviceSeats.delete(viewer)); }
146
+ if (url.pathname === DEVICE_PATH) fromDevice.add(viewer); else if (url.pathname === MEMBER_PATH) fromMember.add(viewer);
133
147
  seat(viewer, name, within(cols, COLS) ? cols : 80, within(rows, ROWS) ? rows : 24, resume);
134
148
  });
135
149
  });
@@ -186,7 +200,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
186
200
  }
187
201
  async function openNow(name, cols, rows, sink, say) {
188
202
  /* Who opens it, for What happened when it wakes a sleeper: a screen, or this server (warm). */
189
- const who = sink ? (deviceSeats.has(sink) ? 'a paired device' : 'a page') : undefined;
203
+ const who = sink ? (fromDevice.has(sink) ? 'a paired device' : fromMember.has(sink) ? 'a member' : 'a page') : undefined;
190
204
  const terminal = await spawn(name, cols, rows, say, who);
191
205
  /* While it was being opened another one may have been: the newest wins. */
192
206
  if (live.has(name)) close(name);
@@ -22,8 +22,11 @@ import { join } from 'node:path';
22
22
  export const DATA_FORMAT = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).clavarium?.dataFormat ?? 1;
23
23
  export const FORMAT_FILE = 'data-format.json';
24
24
 
25
- /* None yet: format 1 is the only one. The next one adds its step here. */
25
+ /* No migration yet. FORMAT 2 IS NOT TO BE USED: 0.2.527-next.1 wrote it for a day (accounts and rights, #419) with
26
+ nothing changed in the files, which blocked going back; it is read as 1 and written back as 1. The next real
27
+ change of format is 3. (Going back to a release from before accounts once members exist: refused, deploy/updater.mjs.) */
26
28
  export const MIGRATIONS = {};
29
+ const SAME_AS_1 = 2;
27
30
 
28
31
  export function dataFormat(dataDir) {
29
32
  try { return JSON.parse(readFileSync(join(dataDir, FORMAT_FILE), 'utf8')).format; } catch { return undefined; }
@@ -37,6 +40,7 @@ export function migrateData(dataDir, { format = DATA_FORMAT, migrations = MIGRAT
37
40
  try { existing = readdirSync(dataDir).some((f) => f.endsWith('.json')); } catch { /* a new directory */ }
38
41
  found = existing ? 1 : format;
39
42
  }
43
+ if (found === SAME_AS_1 && format === 1) { write(dataDir, 1); found = 1; }
40
44
  if (!Number.isInteger(found) || found < 1) throw new Error(`${join(dataDir, FORMAT_FILE)} does not hold a format number`);
41
45
  if (found > format) throw new Error(`The data in ${dataDir} is in format ${found}, written by a newer Clavarium; this one reads format ${format} at most. Go back to the newer version (Settings, Updates; or deploy/updater.mjs), or restore the backup made before the update.`);
42
46
  const ran = [];
package/server/door.mjs CHANGED
@@ -87,13 +87,18 @@ export function devicePairing(devices, headers, pairing) {
87
87
  }
88
88
 
89
89
  /* Returns true when the request was under /c/api/ (answered here). */
90
- export async function handleDoor(request, response, { devices, conversations, resources, shortcuts, voice, originOk, headers, secure, talk, repair, tethers, mailboxes, signinCode }) {
90
+ export async function handleDoor(request, response, { devices, conversations, resources, shortcuts, voice, originOk, headers, secure, talk, repair, tethers, mailboxes, signinCode, person }) {
91
91
  const url = new URL(request.url ?? '/', 'http://local');
92
- if (!url.pathname.startsWith('/c/api/')) return false;
92
+ /* A MEMBER (people.mjs, #419) comes through the same door, at /m/api/, as the person the sign-in names: no
93
+ pairing, no code, no key, no session of its own -- who it is comes from the gate alone, never from the address.
94
+ What it was given is read from the same table as a device's, under `person:<email>`. */
95
+ const base = person ? '/m/api' : '/c/api';
96
+ if (!url.pathname.startsWith(`${base}/`)) return false;
93
97
  /* "/<pairing>/me" -> the pairing and "/me"; "/pair" has no pairing yet. */
94
- const named = /^\/([0-9a-f-]{36})(\/.*)$/.exec(url.pathname.slice('/c/api'.length));
95
- const pairing = named?.[1];
96
- const route = named ? named[2] : url.pathname.slice('/c/api'.length);
98
+ const named = person ? null : /^\/([0-9a-f-]{36})(\/.*)$/.exec(url.pathname.slice(base.length));
99
+ const pairing = person ? person.key : named?.[1];
100
+ const route = named ? named[2] : url.pathname.slice(base.length);
101
+ const given_ = person ?? devices;
97
102
  const send = (status, body, extra = {}) => {
98
103
  response.writeHead(status, { ...headers, ...extra, 'content-type': 'application/json; charset=utf-8' }).end(JSON.stringify(body));
99
104
  return true;
@@ -101,7 +106,8 @@ export async function handleDoor(request, response, { devices, conversations, re
101
106
  try {
102
107
  if (request.method === 'POST' && !originOk(request.headers)) return send(403, { error: 'This request does not come from this site.' });
103
108
 
104
- /* ---- pairing: no session yet ---- */
109
+ /* ---- pairing: no session yet (never for a member: 404) ---- */
110
+ if (person && ['/pair', '/challenge', '/session', '/leave'].includes(route)) return send(404, { error: 'Not found.' });
105
111
  if (request.method === 'POST' && route === '/pair') return send(201, devices.pair(await readJson(request)));
106
112
  if (request.method === 'POST' && route === '/challenge') return send(200, devices.challenge(String((await readJson(request)).device ?? '')));
107
113
  if (request.method === 'POST' && route === '/session') {
@@ -111,17 +117,21 @@ export async function handleDoor(request, response, { devices, conversations, re
111
117
  }
112
118
 
113
119
  /* ---- everything else: a device session, and its one conversation ---- */
114
- if (devicePairing(devices, request.headers, pairing) === undefined) return send(401, { error: 'This device has no open session.' });
120
+ if (!person && devicePairing(devices, request.headers, pairing) === undefined) return send(401, { error: 'This device has no open session.' });
115
121
  /* What this pairing was given: conversations to use, and things of its own to read or write. */
116
- const given = devices.grantsOf(pairing);
122
+ const given = given_.grantsOf(pairing);
117
123
  const names = given.filter((g) => g.type === 'conversation').map((g) => g.name);
118
124
  const own = given.filter((g) => g.type !== 'conversation').filter((g) => resources.get(g.name))
119
125
  .map((g) => ({ name: g.name, type: g.type, access: g.rights.includes('w') ? 'write' : 'read' }));
120
- const name = deviceConversation(devices, request.headers, pairing, url.searchParams.get('c') ?? undefined);
126
+ const name = person ? person.conversationOf(url.searchParams.get('c') ?? undefined) : deviceConversation(devices, request.headers, pairing, url.searchParams.get('c') ?? undefined);
121
127
  const mine = name === undefined ? undefined : conversations.list().find((c) => c.name === name);
122
128
  /* The parts of that conversation this pairing was given. */
123
- const rights = name === undefined ? '' : devices.rightsOn(pairing, name);
129
+ const rights = name === undefined ? '' : given_.rightsOn(pairing, name);
124
130
  const part = { terminal: rights.includes('x'), chat: rights.includes('r') ? (rights.includes('w') ? 'write' : 'read') : null };
131
+ /* A member, once a body is read: still let in, still given that right (audits 8 and 10). A device: as before. */
132
+ const stillMay = (right) => !person || (person.still() && given_.rightsOn(pairing, name).includes(right));
133
+ /* A member writing in a folder, once what it sends has come: still let in, still given it (audit 11). */
134
+ const writesStill = () => { if (person && !person.still()) throw new Refusal(403, 'This conversation is not shared with you any more.'); if (person && !given_.rightsOn(pairing, name).includes('x')) throw new Refusal(403, 'This conversation is not shared with you any more.'); };
125
135
  const need = (ok, what) => { if (!ok) throw new Refusal(403, `This device was not given ${what} of this conversation.`); };
126
136
  /* Its chat alone: what is reached through the conversation is only what its chat holds. */
127
137
  const chatOnly = mine !== undefined && !part.terminal;
@@ -183,20 +193,38 @@ export async function handleDoor(request, response, { devices, conversations, re
183
193
  if (request.method === 'GET' && talking[1] === '/search') return send(200, talk.search(name, url.searchParams.get('q') ?? ''));
184
194
  /* Reminding the tool and writing to it: a chat given to write in. Nothing else (turning it on, inviting the tool) is a device's. */
185
195
  if (request.method === 'POST' && (talking[1] === undefined || talking[1] === '/remind' || talking[1] === '/file' || talking[1] === '/react')) need(part.chat === 'write', 'the chat to write in');
196
+ /* A reaction or an answer to a question reaches the tool as its owner's choice: not a member's (audit 6). */
197
+ if (person && request.method === 'POST' && talking[1] === '/react') throw new Refusal(403, 'A member writes; it does not react for the owner.');
186
198
  if (request.method === 'POST' && talking[1] === '/react') { const body = await readJson(request); return send(200, await talk.react(name, body.to, body.reaction ?? null)); }
187
199
  if (request.method === 'POST' && talking[1] === '/remind') return send(200, await talk.remind(name));
188
200
  if (request.method === 'POST' && talking[1] === '/file') {
189
201
  if (request.headers['content-type'] !== 'application/octet-stream') return send(400, { error: 'An attachment is a file.' });
190
- return send(201, await talk.attach(name, url.searchParams.get('name') ?? '', request));
202
+ const attached = await talk.attach(name, url.searchParams.get('name') ?? '', request);
203
+ /* A member disabled while its file came: not given back to it (audit 10). */
204
+ if (!stillMay('w')) throw new Refusal(403, 'This conversation is not shared with you any more.');
205
+ return send(201, attached);
191
206
  }
192
- if (request.method === 'POST' && talking[1] === undefined) { const body = await readJson(request); if (part.terminal && signinCode && conversations.signinHelp?.codeInChat(name, body.text, body.files)) return send(201, { ...(await signinCode(name, body.text)), told: 'signin' }); return send(201, await talk.say(name, body.text, body.answers, body.files, body.via, { quick: body.quick === true })); }
207
+ if (request.method === 'POST' && talking[1] === undefined) { const body = await readJson(request);
208
+ /* Its right looked at again once the message is read: taken back meanwhile, nothing said (audit 8). */
209
+ if (!stillMay('w')) throw new Refusal(403, 'This conversation is not shared with you any more.'); if (part.terminal && signinCode && conversations.signinHelp?.codeInChat(name, body.text, body.files)) return send(201, { ...(await signinCode(name, body.text)), told: 'signin' }); /* A member's words (#419): said as theirs, so that the tool never takes them for its owner's. */
210
+ if (person) {
211
+ /* Every word of a member said as a member's: its text (a line of its own starting "[" cannot pass for
212
+ another mark), the notes of its files; no answer to a question, no way through (audit 6). */
213
+ const mark = `[${person.email}, a member]`;
214
+ const clean = (t) => String(t ?? '').replace(/[\u200B-\u200F\u2060\uFEFF]/g, '').replace(/[[\uFF3B]/g, '(');
215
+ const files = Array.isArray(body.files) ? body.files.map((f) => (f && typeof f === 'object' ? { ...f, note: `${mark} ${clean(f.note)}`.trim() } : f)) : body.files;
216
+ return send(201, await talk.say(name, `${mark} ${clean(body.text)}`.trim(), undefined, files, undefined, { quick: false }));
217
+ }
218
+ return send(201, await talk.say(name, body.text, body.answers, body.files, body.via, { quick: body.quick === true })); }
193
219
  }
194
220
  /* A sign-in code (#405): a device given its terminal could type it there; no other. Named twice, never guessed. */
195
221
  const codeFor = /^\/conversations\/([^/]+)\/signin-code$/.exec(route);
196
222
  if (request.method === 'POST' && codeFor && signinCode) {
197
223
  need(part.terminal, 'the terminal');
198
224
  if (decodeURIComponent(codeFor[1]) !== name) throw new Refusal(403, 'This device was not given the terminal of this conversation.');
199
- return send(200, await signinCode(name, (await readJson(request)).code));
225
+ const code = (await readJson(request)).code;
226
+ if (!stillMay('x')) throw new Refusal(403, 'This conversation is not shared with you any more.');
227
+ return send(200, await signinCode(name, code));
200
228
  }
201
229
  /* Its terminal does not come: only a device given it asks for it to be repaired. */
202
230
  if (request.method === 'POST' && route === '/terminal/repair') { need(part.terminal, 'the terminal'); return send(200, await repair(name)); }
@@ -228,7 +256,7 @@ export async function handleDoor(request, response, { devices, conversations, re
228
256
  }
229
257
  /* A mail cited by its reference (mailref.mjs): only a mailbox this device was given to read. */
230
258
  if (request.method === 'GET' && (route === '/mail/open' || route === '/mail/page')) {
231
- return await mailRoute(route, url.searchParams, response, { tethers, headers, who: { id: `pairing:${pairing}`, name: 'A device' }, may: (t) => deviceMayRead(t, own, mailboxes), offline: mine?.offline === true });
259
+ return await mailRoute(route, url.searchParams, response, { tethers, headers, who: person ? { id: `person:${person.email}`, name: person.email } : { id: `pairing:${pairing}`, name: 'A device' }, may: (t) => deviceMayRead(t, own, mailboxes), offline: mine?.offline === true });
232
260
  }
233
261
  if (request.method === 'GET' && route === '/files/download') {
234
262
  const file = await download(attached('read', 'open'), url.searchParams.get('p') ?? '');
@@ -240,13 +268,13 @@ export async function handleDoor(request, response, { devices, conversations, re
240
268
  if (request.method === 'POST' && route === '/files/import') {
241
269
  if (request.headers['content-type'] !== 'application/octet-stream') return send(400, { error: 'An import is a file.' });
242
270
  return send(201, await importFile(attached('write'), url.searchParams.get('p') ?? '', url.searchParams.get('name') ?? '', request,
243
- { exists: url.searchParams.get('exists') ?? 'keep', dir: url.searchParams.get('dir') ?? '', batch: url.searchParams.get('batch') ?? undefined }));
271
+ { exists: url.searchParams.get('exists') ?? 'keep', dir: url.searchParams.get('dir') ?? '', batch: url.searchParams.get('batch') ?? undefined, ok: writesStill }));
244
272
  }
245
273
  /* Thumbnails, editing, making, renaming, moving, removing: as listing
246
274
  and importing are. A device given the chat alone has none of them
247
275
  (`attached` refuses all but opening a file of the chat). */
248
276
  /* A thumbnail is the file read, as opening it is: a device given the chat alone sees the pictures of its chat. */
249
- const answer = await changeRoute(request.method, route, url.searchParams, request, (need) => attached(need, route === '/files/thumb' ? 'open' : undefined));
277
+ const answer = await changeRoute(request.method, route, url.searchParams, request, (need) => { if (need === 'write') writesStill(); return attached(need, route === '/files/thumb' ? 'open' : undefined); }, writesStill);
250
278
  if (answer?.picture) {
251
279
  response.writeHead(200, { ...headers, ...IMAGE_HEADERS, 'content-type': answer.picture.type, 'content-length': answer.picture.bytes.length });
252
280
  response.end(answer.picture.bytes);
package/server/files.mjs CHANGED
@@ -154,7 +154,8 @@ export async function mailFile(root, relative) {
154
154
  is replaced; a folder never is), 'skip' (nothing written).
155
155
  `dir`: subfolders under `relative` to make first (a folder dropped whole).
156
156
  `batch`: an id the page gives one drop, bounded as a whole (see BATCH_MAX). */
157
- export async function importFile(root, relative, name, request, { exists = 'keep', dir = '', batch } = {}) {
157
+ /* `ok()`: looked at once the file has come, before it is put in place (it throws when the sender lost its right). */
158
+ export async function importFile(root, relative, name, request, { exists = 'keep', dir = '', batch, ok = () => {} } = {}) {
158
159
  if (!isFileName(name)) throw new Refusal(400, 'A file name has no slash, does not start with a dot, and is at most 120 characters.');
159
160
  if (!['keep', 'replace', 'skip'].includes(exists)) throw new Refusal(400, 'A name already taken is kept beside, replaced or skipped.');
160
161
  const declared = Number(request.headers['content-length']);
@@ -187,6 +188,7 @@ export async function importFile(root, relative, name, request, { exists = 'keep
187
188
  const [stem, ext] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ''];
188
189
  for (let i = 2; await lstat(join(folderPath, final)).then(() => true, () => false); i++) final = `${stem} (${i})${ext}`;
189
190
  } else if ((await lstat(join(folderPath, name)).catch(() => undefined))?.isDirectory()) throw new Refusal(409, `"${name}" is a folder here: it is not replaced by a file.`);
191
+ ok();
190
192
  await rename(partial, join(folderPath, final));
191
193
  return { name: final, size, ...(taken && exists === 'replace' && final === name ? { replaced: true } : {}) };
192
194
  } catch (error) { await unlink(partial).catch(() => {}); throw error; }
@@ -402,7 +404,7 @@ export async function readText(root, relative) {
402
404
  not at that version any more (the agent wrote it meanwhile), nothing is
403
405
  written and the answer says so (409, kind "changed"); 'any' writes over
404
406
  it all the same. `copy`: written beside it under a free name instead. */
405
- export async function saveText(root, relative, request, { version, copy = false } = {}) {
407
+ export async function saveText(root, relative, request, { version, copy = false, ok = () => {} } = {}) {
406
408
  const parts = []; let size = 0;
407
409
  for await (const chunk of request) { size += chunk.length; if (size > EDIT_MAX) throw new Refusal(413, `A text edited here is ${EDIT_MAX / 1024 / 1024} MB at most.`); parts.push(chunk); }
408
410
  const bytes = Buffer.concat(parts);
@@ -423,6 +425,7 @@ export async function saveText(root, relative, request, { version, copy = false
423
425
  /* Looked at again, the moment before: a write of the agent in between is not lost silently. */
424
426
  if (!copy && version !== 'any') { const now = await lstat(at.path).catch(() => undefined); if (!now?.isFile() || versionOf(now) !== version) throw changed(); }
425
427
  if (copy && await lstat(target).then(() => true, () => false)) throw new Refusal(409, `"${name}" was just made by someone else: try again.`);
428
+ ok();
426
429
  await rename(partial, target);
427
430
  } catch (error) { await unlink(partial).catch(() => {}); throw error; }
428
431
  return { name, version: versionOf(await lstat(target)), size: bytes.length };
@@ -495,7 +498,7 @@ async function bridgeFiles(root) {
495
498
  }
496
499
 
497
500
  export const CHANGE_ROUTES = ['/files/thumb', '/files/text', '/files/save', '/files/make', '/files/rename', '/files/move', '/files/remove', '/files/taken'];
498
- export async function changeRoute(method, route, params, request, folder) {
501
+ export async function changeRoute(method, route, params, request, folder, ok = () => {}) {
499
502
  if (!CHANGE_ROUTES.includes(route)) return undefined;
500
503
  const p = params.get('p') ?? '';
501
504
  if (method === 'GET' && route === '/files/thumb') {
@@ -509,7 +512,7 @@ export async function changeRoute(method, route, params, request, folder) {
509
512
  const type = String(request.headers['content-type'] ?? '');
510
513
  if (route === '/files/save') {
511
514
  if (type !== 'application/octet-stream') return [400, { error: 'A text saved is sent as it is.' }];
512
- return [200, await saveText(folder('write'), p, request, { version: params.get('version') ?? '', copy: params.get('copy') === '1' })];
515
+ return [200, await saveText(folder('write'), p, request, { version: params.get('version') ?? '', copy: params.get('copy') === '1', ok })];
513
516
  }
514
517
  if (!type.startsWith('application/json')) return [400, { error: 'The request is not JSON.' }];
515
518
  const chunks = []; let size = 0;
package/server/grants.mjs CHANGED
@@ -67,7 +67,7 @@ import { Refusal } from './conversations.mjs';
67
67
  export const RIGHTS = Object.freeze({ conversation: 'rwxm', folder: 'rw', mailbox: 'r', git: 'rw', secret: 'x', server: 'rw', room: 'rwm', box: 'rw' });
68
68
  /* What each of the server's own assets takes: its state and its jobs are read, rooms are made. */
69
69
  const SERVER_RIGHTS = Object.freeze({ 'server:status': 'r', 'server:jobs': 'r', 'server:rooms': 'w', 'server:diagnostics': 'r' });
70
- const SUBJECT = /^(conversation:[a-z]([a-z0-9-]{0,30}[a-z0-9])?|(pairing|apikey):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
70
+ const SUBJECT = /^(conversation:[a-z]([a-z0-9-]{0,30}[a-z0-9])?|(pairing|apikey):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|person:[a-z0-9._+-]{1,64}@([a-z0-9-]{1,63}\.)+[a-z]{2,24})$/;
71
71
  const ASSET = /^(conversation|folder|mailbox|git):[a-z]([a-z0-9-]{0,30}[a-z0-9])?$|^secret:[A-Z][A-Z0-9_]{0,39}$|^server:(status|jobs|rooms|diagnostics)$|^(room|box):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
72
72
 
73
73
  export const typeOf = (asset) => String(asset).split(':')[0];
@@ -114,7 +114,9 @@ export class Grants {
114
114
  /* A secret is handed to a conversation, never to a device: a device
115
115
  would be a way to read it. */
116
116
  if (typeOf(asset) === 'secret' && !subject.startsWith('conversation:')) throw new Refusal(400, 'A secret is handed to a conversation, never shared with a device.');
117
- if (typeOf(asset) === 'conversation' && !subject.startsWith('pairing:') && !subject.startsWith('apikey:')) throw new Refusal(400, 'A conversation is shared with a device or an API key, not with another conversation.');
117
+ /* A MEMBER (person:, people.mjs, #419) is given conversations only, in this version: its chat, its terminal. */
118
+ if (subject.startsWith('person:') && typeOf(asset) !== 'conversation') throw new Refusal(400, 'A member is given conversations only.');
119
+ if (typeOf(asset) === 'conversation' && !subject.startsWith('pairing:') && !subject.startsWith('apikey:') && !subject.startsWith('person:')) throw new Refusal(400, 'A conversation is shared with a device or an API key, not with another conversation.');
118
120
  /* The state of the server is given to an API key only; an API key is given only that, and
119
121
  conversations one by one -- their chat, to read or to write in, never their terminal. */
120
122
  if (typeOf(asset) === 'server' && !subject.startsWith('apikey:')) throw new Refusal(400, 'The state of the server is given to an API key only.');
@@ -141,6 +143,8 @@ export class Grants {
141
143
  /* Who has something on one asset: [{ subject, rights }]. */
142
144
  on(asset) { return this.#store.all().filter((g) => g.asset === asset).map((g) => ({ subject: g.subject, rights: g.rights })); }
143
145
 
146
+ /* The subjects there are that start so ('person:'). */
147
+ subjects(prefix) { return [...new Set(this.#store.all().map((g) => g.subject).filter((s) => s.startsWith(prefix)))]; }
144
148
  forgetSubject(subject) { for (const g of this.#store.all()) if (g.subject === subject) this.#store.remove(g.name); }
145
149
  forgetAsset(asset) { for (const g of this.#store.all()) if (g.asset === asset) this.#store.remove(g.name); }
146
150
  }