clavarium 0.2.527-next.1 → 0.2.529-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.
@@ -666,6 +666,15 @@ export class Updater {
666
666
  const live = busy.filter((c) => !stale.includes(c));
667
667
  return live.length ? `a machine is being built or restarted (${names(live)}): the update waits` : '';
668
668
  }
669
+ /* MEMBERS AND AN OLDER RELEASE (#419). A release from before accounts and rights takes every account for an
670
+ administrator: once accounts and rights were used here (people.json written, at the first member), going back to
671
+ one is refused, by hand and by the watchdog -- as for a release that cannot read the data. Undefined: allowed. */
672
+ #membersBlock(to) {
673
+ /* A release that reads the lists of today (0.2.526-next.1 wrote another form: refused too). */
674
+ try { if (readFileSync(join(to.app, 'server', 'people.mjs'), 'utf8').includes('export const PEOPLE_LISTS')) return undefined; } catch { /* none: from before accounts */ }
675
+ const file = join(this.#o.data, 'people.json');
676
+ return existsSync(file) || existsSync(`${file}.bak`) ? `${to.version} does not know these members: it would not read who is an administrator` : undefined;
677
+ }
669
678
  #dataFormat() { try { return JSON.parse(readFileSync(join(this.#o.data, 'data-format.json'), 'utf8')).format; } catch { return undefined; } }
670
679
 
671
680
  #lock() {
@@ -701,6 +710,9 @@ export class Updater {
701
710
  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) } : {}) });
702
711
  throw error;
703
712
  }
713
+ /* Members here, and a release that would not read them (a newer number cut without them, say): not installed. */
714
+ const blocked = this.#membersBlock(release);
715
+ 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); }
704
716
  const before = this.#dataFormat();
705
717
  let archive;
706
718
  try {
@@ -742,6 +754,7 @@ export class Updater {
742
754
  if (to.current) throw new Refused(`${id} is the release that runs`);
743
755
  const format = this.#dataFormat();
744
756
  if (format !== undefined && to.dataFormat < format) throw new Refused(`${to.version} cannot read the data of this version (format ${format}; it reads ${to.dataFormat})`);
757
+ const members = this.#membersBlock(to); if (members) throw new Refused(members);
745
758
  const why = await this.busy(); if (why) throw new Refused(why);
746
759
  const unlock = this.#lock();
747
760
  try {
@@ -870,7 +883,7 @@ export class Updater {
870
883
  const recent = failed && current && last && last.action === 'update' && last.result === 'done' && last.to === current.version && now - new Date(last.at) < WATCH_RECENT_MS;
871
884
  const previous = recent ? this.releases().find((r) => !r.current && r.version === last.from) : undefined;
872
885
  const format = this.#dataFormat();
873
- if (previous && (format === undefined || previous.dataFormat >= format)) {
886
+ if (previous && (format === undefined || previous.dataFormat >= format) && !this.#membersBlock(previous)) {
874
887
  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}`;
875
888
  this.#o.log(`watchdog: ${why}`);
876
889
  this.#step('update', current.version, 'Going back');
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.527-next.1",
3
+ "version": "0.2.529-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.527-next.1",
9
+ "version": "0.2.529-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.527-next.1",
3
+ "version": "0.2.529-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.",
@@ -22,7 +22,7 @@
22
22
  "README.md"
23
23
  ],
24
24
  "clavarium": {
25
- "dataFormat": 2
25
+ "dataFormat": 1
26
26
  },
27
27
  "scripts": {
28
28
  "start": "node server/main.mjs",
package/server/api.mjs CHANGED
@@ -592,6 +592,7 @@ export async function handleApi(request, response, conversations, headers, resou
592
592
  return send(403, { error: 'This request does not come from this site.' }), true;
593
593
  }
594
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.');
595
596
  /* A SIGN-IN CODE (#405): answered before anything below can see this body (the journal, say). */
596
597
  const codeOf = /^\/api\/conversations\/([^/]+)\/signin-code$/.exec(pathname);
597
598
  if (codeOf && conversations.signinHelp) return send(200, await conversations.signinHelp.enterCode(decodeURIComponent(codeOf[1]), body?.code)), true;
@@ -795,21 +796,31 @@ export async function handleApi(request, response, conversations, headers, resou
795
796
  if (pathname === '/api/operators' && team) {
796
797
  /* Its role said at once (#419): an account removed and added again does not come back as it was. */
797
798
  const role = body.role === 'member' ? 'member' : body.role === 'admin' ? 'admin' : (team.people?.defaultRole?.() ?? 'admin');
798
- team.people?.adding(String(body.email ?? '').trim().toLowerCase(), role);
799
- const made = await team.add(body.email);
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; }
800
807
  return send(201, { ...made, role: team.people?.roleOf(made.email) ?? 'admin' }), true;
801
808
  }
802
809
  /* An account made an administrator or a member (#419): never oneself, never the last administrator. */
803
810
  const roleOf = /^\/api\/operators\/([^/]{3,200})\/role$/.exec(pathname);
804
811
  if (roleOf && team?.people) {
805
- const email = decodeURIComponent(roleOf[1]).toLowerCase();
812
+ const email = decodeURIComponent(roleOf[1]).trim().toLowerCase();
806
813
  if (email === identity) throw new Refusal(409, 'You cannot change your own role: ask another administrator.');
807
- return send(200, { operators: team.people.setRole(email, String(body.role ?? '')) }), true;
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;
808
818
  }
809
819
  /* A conversation given to a member, or taken back: its chat (read or write) and/or its terminal (#419). */
810
820
  const giving = /^\/api\/operators\/([^/]{3,200})\/(give|take)$/.exec(pathname);
811
821
  if (giving && team?.people && team.grants) {
812
- const email = decodeURIComponent(giving[1]).toLowerCase();
822
+ const email = decodeURIComponent(giving[1]).trim().toLowerCase();
823
+ if (!team.list().some((o) => o.email === email)) throw new Refusal(404, 'No such account.');
813
824
  if (team.people.roleOf(email) !== 'member') throw new Refusal(409, 'Only a member is given conversations: an administrator has them all.');
814
825
  const name = String(body.conversation ?? '');
815
826
  if (!conversations.list().some((c) => c.name === name)) throw new Refusal(404, 'No such conversation.');
@@ -821,7 +832,7 @@ export async function handleApi(request, response, conversations, headers, resou
821
832
  }
822
833
  const op = /^\/api\/operators\/([^/]{3,200})\/(password|disable|enable|remove)$/.exec(pathname);
823
834
  if (op && team) {
824
- const email = decodeURIComponent(op[1]);
835
+ const email = decodeURIComponent(op[1]).trim().toLowerCase();
825
836
  /* Not oneself out: another operator does it, or nobody would see it was a mistake. */
826
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.');
827
838
  const done = op[2] === 'password' ? await team.password(email) : { operators: await team[op[2]](email) };
@@ -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);
@@ -22,10 +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
- /* 1 -> 2 (24-11, #419): nothing to change in the files. Its number is what matters: a release from before accounts
26
- and rights reads format 1 only, and would take every member for an administrator (it does not know people.json);
27
- the updater refuses to go back to it, by hand or by itself, and that release refuses to start on this data. */
28
- export const MIGRATIONS = { 1: () => {} };
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.) */
28
+ export const MIGRATIONS = {};
29
+ const SAME_AS_1 = 2;
29
30
 
30
31
  export function dataFormat(dataDir) {
31
32
  try { return JSON.parse(readFileSync(join(dataDir, FORMAT_FILE), 'utf8')).format; } catch { return undefined; }
@@ -39,6 +40,7 @@ export function migrateData(dataDir, { format = DATA_FORMAT, migrations = MIGRAT
39
40
  try { existing = readdirSync(dataDir).some((f) => f.endsWith('.json')); } catch { /* a new directory */ }
40
41
  found = existing ? 1 : format;
41
42
  }
43
+ if (found === SAME_AS_1 && format === 1) { write(dataDir, 1); found = 1; }
42
44
  if (!Number.isInteger(found) || found < 1) throw new Error(`${join(dataDir, FORMAT_FILE)} does not hold a format number`);
43
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.`);
44
46
  const ran = [];
package/server/door.mjs CHANGED
@@ -128,6 +128,10 @@ export async function handleDoor(request, response, { devices, conversations, re
128
128
  /* The parts of that conversation this pairing was given. */
129
129
  const rights = name === undefined ? '' : given_.rightsOn(pairing, name);
130
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.'); };
131
135
  const need = (ok, what) => { if (!ok) throw new Refusal(403, `This device was not given ${what} of this conversation.`); };
132
136
  /* Its chat alone: what is reached through the conversation is only what its chat holds. */
133
137
  const chatOnly = mine !== undefined && !part.terminal;
@@ -189,22 +193,38 @@ export async function handleDoor(request, response, { devices, conversations, re
189
193
  if (request.method === 'GET' && talking[1] === '/search') return send(200, talk.search(name, url.searchParams.get('q') ?? ''));
190
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. */
191
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.');
192
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)); }
193
199
  if (request.method === 'POST' && talking[1] === '/remind') return send(200, await talk.remind(name));
194
200
  if (request.method === 'POST' && talking[1] === '/file') {
195
201
  if (request.headers['content-type'] !== 'application/octet-stream') return send(400, { error: 'An attachment is a file.' });
196
- 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);
197
206
  }
198
- 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' }); /* A member's words (#419): said as theirs, so that the tool never takes them for its owner's. */
199
- const text = person && typeof body.text === 'string' && body.text.trim() ? `[${person.email}, a member] ${body.text}` : body.text;
200
- return send(201, await talk.say(name, 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 })); }
201
219
  }
202
220
  /* A sign-in code (#405): a device given its terminal could type it there; no other. Named twice, never guessed. */
203
221
  const codeFor = /^\/conversations\/([^/]+)\/signin-code$/.exec(route);
204
222
  if (request.method === 'POST' && codeFor && signinCode) {
205
223
  need(part.terminal, 'the terminal');
206
224
  if (decodeURIComponent(codeFor[1]) !== name) throw new Refusal(403, 'This device was not given the terminal of this conversation.');
207
- 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));
208
228
  }
209
229
  /* Its terminal does not come: only a device given it asks for it to be repaired. */
210
230
  if (request.method === 'POST' && route === '/terminal/repair') { need(part.terminal, 'the terminal'); return send(200, await repair(name)); }
@@ -248,13 +268,13 @@ export async function handleDoor(request, response, { devices, conversations, re
248
268
  if (request.method === 'POST' && route === '/files/import') {
249
269
  if (request.headers['content-type'] !== 'application/octet-stream') return send(400, { error: 'An import is a file.' });
250
270
  return send(201, await importFile(attached('write'), url.searchParams.get('p') ?? '', url.searchParams.get('name') ?? '', request,
251
- { 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 }));
252
272
  }
253
273
  /* Thumbnails, editing, making, renaming, moving, removing: as listing
254
274
  and importing are. A device given the chat alone has none of them
255
275
  (`attached` refuses all but opening a file of the chat). */
256
276
  /* A thumbnail is the file read, as opening it is: a device given the chat alone sees the pictures of its chat. */
257
- 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);
258
278
  if (answer?.picture) {
259
279
  response.writeHead(200, { ...headers, ...IMAGE_HEADERS, 'content-type': answer.picture.type, 'content-length': answer.picture.bytes.length });
260
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
@@ -75,7 +75,6 @@ export const nameOf = (asset) => String(asset).slice(String(asset).indexOf(':')
75
75
  export const conversationSubject = (name) => `conversation:${name}`;
76
76
  export const pairingSubject = (id) => `pairing:${id}`;
77
77
  export const apiKeySubject = (id) => `apikey:${id}`;
78
- export const personSubject = (email) => `person:${String(email).toLowerCase()}`;
79
78
 
80
79
  /* The rights asked for, in the one order they are written, or a refusal:
81
80
  only letters this type of asset takes, at least one, none twice. */
@@ -144,6 +143,8 @@ export class Grants {
144
143
  /* Who has something on one asset: [{ subject, rights }]. */
145
144
  on(asset) { return this.#store.all().filter((g) => g.asset === asset).map((g) => ({ subject: g.subject, rights: g.rights })); }
146
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)))]; }
147
148
  forgetSubject(subject) { for (const g of this.#store.all()) if (g.subject === subject) this.#store.remove(g.name); }
148
149
  forgetAsset(asset) { for (const g of this.#store.all()) if (g.asset === asset) this.#store.remove(g.name); }
149
150
  }
package/server/main.mjs CHANGED
@@ -274,12 +274,14 @@ function serve(port, conversations, resources, { gate = () => 'local', memberGat
274
274
  }
275
275
  /* Before anything else, static files included: see gate.mjs. */
276
276
  const who = gate(request.headers);
277
+ /* Looked at again once a body is read: one made a member or disabled meanwhile does nothing more (audit 8). */
278
+ request.stillAllowed = () => gate(request.headers) !== undefined;
277
279
  if (who === undefined) {
278
280
  /* A MEMBER (people.mjs, #419): its own door, and nothing else of this server -- not a page, not an API,
279
281
  not a file. A page it held from before (an administrator then) is told, and goes to its own. */
280
282
  const member = memberGate(request.headers);
281
283
  if (member !== undefined && door && personOf) {
282
- if (await handleDoor(request, response, { ...door, person: personOf(member) })) return;
284
+ if (await handleDoor(request, response, { ...door, person: { ...personOf(member), still: () => memberGate(request.headers) === member } })) return;
283
285
  if (pathname === '/m/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
284
286
  if (pathname === '/m/' && (request.method === 'GET' || request.method === 'HEAD')) { response.writeHead(200, { ...HEADERS, 'content-type': 'text/html; charset=utf-8' }).end(memberPage()); return; }
285
287
  const file = MEMBER_FILES[pathname];
@@ -353,9 +355,18 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
353
355
  /* WHO IS WHAT (people.mjs, #419): the gate of everything there was admits ADMINISTRATORS only -- pages, API,
354
356
  terminals, the SSH console, all of it -- so a member is refused there by default; members come in through
355
357
  their own door alone (/m/, memberGate). With no member, everybody who may sign in passes, as before. */
356
- const people = team ? new People({ path: `${dataDir}/people.json`, install: operators, accounts: () => team.list(), tell: (title, body) => { try { void alerts?.tell?.({ title, body, url: '/?open=settings&at=operators' })?.catch?.(() => {}); } catch { /* said in the log */ } console.error(`people: ${title}: ${body}`); } }) : null;
358
+ const people = team ? new People({ path: `${dataDir}/people.json`, install: operators, accounts: () => team.list(), leaving: () => team.leaving, tell: (title, body) => { try { void alerts?.tell?.({ title, body, url: '/?open=settings&at=operators' })?.catch?.(() => {}); } catch { /* said in the log */ } console.error(`people: ${title}: ${body}`); } }) : null;
357
359
  team?.useLastAdmin((email) => people.roleOf(email) === 'admin' && people.isLastAdmin(email));
358
- if (team) { team.people = people; team.onChanged = () => people.changed(); }
360
+ /* The list changed outside the page too: an account gone takes its role and what it was given with it (audit 6). */
361
+ if (team) {
362
+ team.people = people;
363
+ team.onChanged = () => {
364
+ people.prune();
365
+ const here = new Set(team.list().map((o) => o.email));
366
+ if (here.size && team.grants) for (const s of team.grants.subjects('person:')) if (!here.has(s.slice('person:'.length))) team.grants.forgetSubject(s);
367
+ people.changed();
368
+ };
369
+ }
359
370
  const gate = makeGate(team ? () => team.allowed().filter((e) => people.roleOf(e) === 'admin') : []);
360
371
  const memberGate = team ? makeGate(() => team.allowed().filter((e) => people.roleOf(e) === 'member')) : () => undefined;
361
372
  const originOk = makeOriginCheck(publicOrigin);
@@ -1041,7 +1052,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
1041
1052
  boxes.attach(server, WebSocketServer);
1042
1053
  browsers.attach(server, WebSocketServer); server.on('close', () => browsers.shutdown());
1043
1054
  /* A machine's shared SSH console, live in its asset panel (sshconsole.mjs): the same checks as the terminal. */
1044
- attachConsole(server, { tethers, gate, originOk });
1055
+ const consoles = attachConsole(server, { tethers, gate, originOk });
1045
1056
  /* The wake word's weekly threshold tuning (Sunday from 03:00, each box's own time): looked at every 10 minutes. */
1046
1057
  const wakeWeekly = setInterval(() => { try { boxes.wakeWeekly(); } catch (error) { console.error(`wake tuning: ${error.message}`); } }, 10 * 60_000); wakeWeekly.unref?.(); server.on('close', () => clearInterval(wakeWeekly));
1047
1058
  /* A collect session's clock: the stations asked, its end, the speaker told to stop (boxcollect.mjs). */
@@ -1076,7 +1087,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
1076
1087
  memberName: (headers, wanted) => { const m = memberGate(headers); if (m === undefined || !personOf) return undefined; const p = personOf(m); return p.conversationOf(wanted) === wanted && p.rightsOn(p.key, wanted).includes('x') ? wanted : undefined; },
1077
1088
  });
1078
1089
  /* A role or a person's right changed: the terminals it held and lost go at once (#419). */
1079
- people?.useChanged?.(() => bridge.recheck());
1090
+ people?.useChanged?.(() => { bridge.recheck(); consoles?.recheck?.(); });
1080
1091
  all.drop = (name) => bridge.drop(name);
1081
1092
  /* What a device was given changes: a terminal it holds and lost goes at once. */
1082
1093
  devices.changed = () => bridge.recheck();
@@ -78,9 +78,25 @@ export class Operators {
78
78
  #lastAdmin = () => false;
79
79
  useLastAdmin(fn) { this.#lastAdmin = fn; }
80
80
  #keep(email) { if (this.#lastAdmin(email)) throw new Refusal(409, 'The last administrator cannot be disabled or removed.'); }
81
- async disable(email) { this.#keep(this.#email(email)); await this.#do(['operator', 'disable', this.#email(email)]); this.#unlock(this.#email(email)); return this.list(); }
81
+ /* Disabled or removed now: not counted as an administrator from the check on, so that two of them taking each
82
+ other out at once cannot leave none (audit 6, 24-11). One at a time, too. */
83
+ leaving = new Set();
84
+ #turn = Promise.resolve();
85
+ #leave(email, verb) {
86
+ const e = this.#email(email);
87
+ const go = async () => {
88
+ this.#keep(e);
89
+ this.leaving.add(e);
90
+ try { await this.#do(['operator', verb, e]); } finally { this.leaving.delete(e); }
91
+ this.#unlock(e);
92
+ return this.list();
93
+ };
94
+ const p = this.#turn.then(go, go); this.#turn = p.catch(() => {});
95
+ return p;
96
+ }
97
+ async disable(email) { return this.#leave(email, 'disable'); }
82
98
  async enable(email) { await this.#do(['operator', 'enable', this.#email(email)]); this.#unlock(this.#email(email)); return this.list(); }
83
- async remove(email) { this.#keep(this.#email(email)); await this.#do(['operator', 'remove', this.#email(email)]); this.#unlock(this.#email(email)); return this.list(); }
99
+ async remove(email) { return this.#leave(email, 'remove'); }
84
100
  #unlock(email) { const locks = { ...(this.#store.get('locks') ?? {}) }; delete locks[email]; this.#store.put({ name: 'locks', ...locks }); }
85
101
 
86
102
  /* At each turn: too many failed sign-ins lock an address for a while; a lock that is over is lifted. */
package/server/people.mjs CHANGED
@@ -18,19 +18,23 @@
18
18
  * server was installed with (`install`, its --operators) are the administrators and every other one a member --
19
19
  * never everybody locked out, never a member made an administrator. It is said, loudly.
20
20
  */
21
- import { readFileSync, writeFileSync, renameSync, existsSync, copyFileSync, mkdirSync } from 'node:fs';
21
+ import { readFileSync, writeFileSync, renameSync, existsSync, copyFileSync, mkdirSync, rmSync } from 'node:fs';
22
22
  import { dirname } from 'node:path';
23
23
  import { Refusal } from './conversations.mjs';
24
24
 
25
25
  export const ROLES = Object.freeze(['admin', 'member']);
26
+ /* What deploy/updater.mjs looks for in a release before going back to it: it reads these lists (#419). */
27
+ export const PEOPLE_LISTS = 1;
26
28
  const low = (e) => String(e ?? '').trim().toLowerCase();
27
29
 
28
30
  export class People {
29
31
  #path; #lists = null; #damaged = false; #accounts; #tell; #install; #changed = () => {};
30
32
  /* `accounts()`: every account there is, enabled or not ([{ email, enabled }], operators.mjs).
31
33
  `install`: the accounts the server was started with (--operators), the administrators of last resort. */
32
- constructor({ path, accounts = () => [], tell = () => {}, install = [] }) {
33
- this.#path = path; this.#accounts = accounts; this.#tell = tell; this.#install = install.map(low);
34
+ #leaving;
35
+ /* `leaving()`: the accounts being disabled or removed right now (operators.mjs), already not counted. */
36
+ constructor({ path, accounts = () => [], tell = () => {}, install = [], leaving = () => [] }) {
37
+ this.#path = path; this.#accounts = accounts; this.#tell = tell; this.#install = install.map(low); this.#leaving = leaving;
34
38
  mkdirSync(dirname(path), { recursive: true });
35
39
  this.#load();
36
40
  }
@@ -60,20 +64,17 @@ export class People {
60
64
  }
61
65
 
62
66
  #all() { return (this.#accounts() ?? []).map((a) => ({ email: low(a.email), enabled: a.enabled !== false })); }
63
- /* Whether there are members at all (a file written). */
64
- hasMembers() { return this.#lists !== null && this.#lists.members.length > 0; }
65
67
 
66
68
  /* 'admin' or 'member'. */
67
69
  roleOf(email) {
68
70
  const e = low(email);
69
71
  if (this.#all().length <= 1) return 'admin';
70
- if (this.#damaged && this.#lists === null) return this.#install.includes(e) ? 'admin' : 'member';
72
+ if (this.#damaged) return this.#install.includes(e) ? 'admin' : 'member';
71
73
  if (this.#lists === null) return 'admin';
72
74
  return this.#lists.admins.includes(e) && !this.#lists.members.includes(e) ? 'admin' : 'member';
73
75
  }
74
- damaged() { return this.#damaged; }
75
76
  /* The enabled administrators. */
76
- admins() { return this.#all().filter((a) => a.enabled && this.roleOf(a.email) === 'admin').map((a) => a.email); }
77
+ admins() { const out = new Set([...this.#leaving()].map(low)); return this.#all().filter((a) => a.enabled && !out.has(a.email) && this.roleOf(a.email) === 'admin').map((a) => a.email); }
77
78
  /* Whether taking `email` out of the administrators (made a member, disabled, removed, locked out) leaves none. */
78
79
  isLastAdmin(email) {
79
80
  const e = low(email);
@@ -102,11 +103,18 @@ export class People {
102
103
  }
103
104
  /* An account ABOUT TO BE added, its role said first: never an administrator for a moment by mistake, and an
104
105
  account removed then added again does not come back as it was. */
106
+ /* Returns what puts it back as it was, when the account could not be added after all (audit 13): no file left
107
+ where there was none -- an owner without members keeps everything as before. */
105
108
  adding(email, role) {
106
109
  const e = low(email);
107
- if (!ROLES.includes(role) || this.#damaged) return;
108
- if (this.#lists === null && role === 'admin') return;
110
+ if (!ROLES.includes(role) || this.#damaged) return () => {};
111
+ if (this.#lists === null && role === 'admin') return () => {};
112
+ const before = this.#lists === null ? null : { admins: [...this.#lists.admins], members: [...this.#lists.members] };
109
113
  this.#seed(); this.#put(e, role); this.#save();
114
+ return () => {
115
+ if (before === null) { this.#lists = null; rmSync(this.#path, { force: true }); rmSync(`${this.#path}.bak`, { force: true }); return; }
116
+ this.#lists = before; this.#save();
117
+ };
110
118
  }
111
119
  /* An account removed: its role forgotten with it. */
112
120
  removed(email) {
@@ -116,6 +124,17 @@ export class People {
116
124
  this.#lists.members = this.#lists.members.filter((x) => x !== e);
117
125
  this.#save();
118
126
  }
127
+ /* Accounts gone outside the page (the host program): their roles forgotten. Returns the addresses forgotten. */
128
+ prune() {
129
+ if (this.#lists === null || this.#damaged) return [];
130
+ const here = new Set(this.#all().map((a) => a.email));
131
+ if (here.size === 0) return [];
132
+ const gone = [...this.#lists.admins, ...this.#lists.members].filter((e) => !here.has(e));
133
+ if (!gone.length) return [];
134
+ this.#lists.admins = this.#lists.admins.filter((e) => here.has(e)); this.#lists.members = this.#lists.members.filter((e) => here.has(e));
135
+ this.#save();
136
+ return gone;
137
+ }
119
138
  /* The role a new account gets when none is said: a member (24-11, its owner's choice); an administrator is ticked. */
120
139
  defaultRole() { return 'member'; }
121
140
  list() { return this.#all().map((a) => ({ ...a, role: this.roleOf(a.email) })); }
@@ -41,6 +41,8 @@ const machineOf = (tethers, id) => {
41
41
  };
42
42
 
43
43
  export function attachConsole(server, { tethers, gate = () => 'local', originOk }) {
44
+ /* Each open console and whether it may stay: looked at again when a role changes (#419), not only every 30 s. */
45
+ const open = new Map();
44
46
  const sockets = new WebSocketServer({ noServer: true, maxPayload: KEYS_MAX });
45
47
  server.on('upgrade', (request, socket, head) => {
46
48
  const url = new URL(request.url ?? '/', 'http://local');
@@ -51,7 +53,9 @@ export function attachConsole(server, { tethers, gate = () => 'local', originOk
51
53
  sockets.handleUpgrade(request, socket, head, (ws) => {
52
54
  /* Still an administrator (#419): made a member, disabled, removed -- the console ends at once. */
53
55
  const still = () => gate(request.headers) !== undefined;
54
- const watch = setInterval(() => { if (!still()) { try { ws.close(4403, 'not allowed any more'); } catch { /* gone */ } } }, 30_000); watch.unref?.();
56
+ const look = () => { if (!still()) { try { ws.close(4403, 'not allowed any more'); } catch { /* gone */ } } };
57
+ const watch = setInterval(look, 30_000); watch.unref?.();
58
+ open.set(ws, look); ws.on('close', () => open.delete(ws));
55
59
  ws.on('close', () => clearInterval(watch));
56
60
  ws.on('message', () => { if (!still()) { try { ws.close(4403, 'not allowed any more'); } catch { /* gone */ } } });
57
61
  void seat(ws, target, whoOf(request.headers), { cols, rows }, still);
@@ -90,6 +94,8 @@ export function attachConsole(server, { tethers, gate = () => 'local', originOk
90
94
  else if (m?.type === 'interrupt') handle.interrupt();
91
95
  });
92
96
  }
97
+ /* `recheck`: each open console looked at now (a role changed, #419). */
98
+ sockets.recheck = () => { for (const look of [...open.values()]) look(); };
93
99
  return sockets;
94
100
  }
95
101