clavarium 0.2.526-next.1 → 0.2.528-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.526-next.1",
3
+ "version": "0.2.528-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.526-next.1",
9
+ "version": "0.2.528-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.526-next.1",
3
+ "version": "0.2.528-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
@@ -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,27 @@ 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');
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
+ team.people?.adding(adding, role);
798
805
  const made = await team.add(body.email);
799
- team.people?.added(made.email, role);
800
806
  return send(201, { ...made, role: team.people?.roleOf(made.email) ?? 'admin' }), true;
801
807
  }
802
808
  /* An account made an administrator or a member (#419): never oneself, never the last administrator. */
803
809
  const roleOf = /^\/api\/operators\/([^/]{3,200})\/role$/.exec(pathname);
804
810
  if (roleOf && team?.people) {
805
- const email = decodeURIComponent(roleOf[1]).toLowerCase();
811
+ const email = decodeURIComponent(roleOf[1]).trim().toLowerCase();
806
812
  if (email === identity) throw new Refusal(409, 'You cannot change your own role: ask another administrator.');
807
813
  return send(200, { operators: team.people.setRole(email, String(body.role ?? '')) }), true;
808
814
  }
809
815
  /* A conversation given to a member, or taken back: its chat (read or write) and/or its terminal (#419). */
810
816
  const giving = /^\/api\/operators\/([^/]{3,200})\/(give|take)$/.exec(pathname);
811
817
  if (giving && team?.people && team.grants) {
812
- const email = decodeURIComponent(giving[1]).toLowerCase();
818
+ const email = decodeURIComponent(giving[1]).trim().toLowerCase();
819
+ if (!team.list().some((o) => o.email === email)) throw new Refusal(404, 'No such account.');
813
820
  if (team.people.roleOf(email) !== 'member') throw new Refusal(409, 'Only a member is given conversations: an administrator has them all.');
814
821
  const name = String(body.conversation ?? '');
815
822
  if (!conversations.list().some((c) => c.name === name)) throw new Refusal(404, 'No such conversation.');
@@ -821,7 +828,7 @@ export async function handleApi(request, response, conversations, headers, resou
821
828
  }
822
829
  const op = /^\/api\/operators\/([^/]{3,200})\/(password|disable|enable|remove)$/.exec(pathname);
823
830
  if (op && team) {
824
- const email = decodeURIComponent(op[1]);
831
+ const email = decodeURIComponent(op[1]).trim().toLowerCase();
825
832
  /* Not oneself out: another operator does it, or nobody would see it was a mistake. */
826
833
  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
834
  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);
package/server/bridge.mjs CHANGED
@@ -100,6 +100,8 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
100
100
  back used to end only at the next connection -- an open terminal went on (found 19-10). */
101
101
  const deviceSeats = new Map(); /* viewer -> () => still allowed */
102
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();
103
105
  const allowed = (viewer) => {
104
106
  if (revoked.has(viewer)) return false;
105
107
  const still = deviceSeats.get(viewer);
@@ -141,6 +143,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
141
143
  const resume = url.searchParams.get('resume') === '1';
142
144
  sockets.handleUpgrade(request, socket, head, (viewer) => {
143
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);
144
147
  seat(viewer, name, within(cols, COLS) ? cols : 80, within(rows, ROWS) ? rows : 24, resume);
145
148
  });
146
149
  });
@@ -197,7 +200,7 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
197
200
  }
198
201
  async function openNow(name, cols, rows, sink, say) {
199
202
  /* Who opens it, for What happened when it wakes a sleeper: a screen, or this server (warm). */
200
- 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;
201
204
  const terminal = await spawn(name, cols, rows, say, who);
202
205
  /* While it was being opened another one may have been: the newest wins. */
203
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
@@ -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,20 +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' }); 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 })); }
199
219
  }
200
220
  /* A sign-in code (#405): a device given its terminal could type it there; no other. Named twice, never guessed. */
201
221
  const codeFor = /^\/conversations\/([^/]+)\/signin-code$/.exec(route);
202
222
  if (request.method === 'POST' && codeFor && signinCode) {
203
223
  need(part.terminal, 'the terminal');
204
224
  if (decodeURIComponent(codeFor[1]) !== name) throw new Refusal(403, 'This device was not given the terminal of this conversation.');
205
- 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));
206
228
  }
207
229
  /* Its terminal does not come: only a device given it asks for it to be repaired. */
208
230
  if (request.method === 'POST' && route === '/terminal/repair') { need(part.terminal, 'the terminal'); return send(200, await repair(name)); }
@@ -246,13 +268,13 @@ export async function handleDoor(request, response, { devices, conversations, re
246
268
  if (request.method === 'POST' && route === '/files/import') {
247
269
  if (request.headers['content-type'] !== 'application/octet-stream') return send(400, { error: 'An import is a file.' });
248
270
  return send(201, await importFile(attached('write'), url.searchParams.get('p') ?? '', url.searchParams.get('name') ?? '', request,
249
- { 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 }));
250
272
  }
251
273
  /* Thumbnails, editing, making, renaming, moving, removing: as listing
252
274
  and importing are. A device given the chat alone has none of them
253
275
  (`attached` refuses all but opening a file of the chat). */
254
276
  /* A thumbnail is the file read, as opening it is: a device given the chat alone sees the pictures of its chat. */
255
- 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);
256
278
  if (answer?.picture) {
257
279
  response.writeHead(200, { ...headers, ...IMAGE_HEADERS, 'content-type': answer.picture.type, 'content-length': answer.picture.bytes.length });
258
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`, 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;
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);
@@ -380,7 +391,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
380
391
  const grants = new Grants(new Store(`${dataDir}/grants.json`));
381
392
  if (team) team.grants = grants;
382
393
  /* A MEMBER, as the door sees it (door.mjs, #419): what the table gives `person:<email>`, conversations only. */
383
- const personOf = team ? (email) => {
394
+ const personOf = team ? (given) => {
395
+ const email = String(given).trim().toLowerCase();
384
396
  const subject = `person:${email}`;
385
397
  const mine = () => grants.of(subject, 'conversation').map((g) => g.name).filter((n) => all.list().some((c) => c.name === n));
386
398
  return {
@@ -1040,7 +1052,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
1040
1052
  boxes.attach(server, WebSocketServer);
1041
1053
  browsers.attach(server, WebSocketServer); server.on('close', () => browsers.shutdown());
1042
1054
  /* A machine's shared SSH console, live in its asset panel (sshconsole.mjs): the same checks as the terminal. */
1043
- attachConsole(server, { tethers, gate, originOk });
1055
+ const consoles = attachConsole(server, { tethers, gate, originOk });
1044
1056
  /* The wake word's weekly threshold tuning (Sunday from 03:00, each box's own time): looked at every 10 minutes. */
1045
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));
1046
1058
  /* A collect session's clock: the stations asked, its end, the speaker told to stop (boxcollect.mjs). */
@@ -1075,7 +1087,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
1075
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; },
1076
1088
  });
1077
1089
  /* A role or a person's right changed: the terminals it held and lost go at once (#419). */
1078
- people?.useChanged?.(() => bridge.recheck());
1090
+ people?.useChanged?.(() => { bridge.recheck(); consoles?.recheck?.(); });
1079
1091
  all.drop = (name) => bridge.drop(name);
1080
1092
  /* What a device was given changes: a terminal it holds and lost goes at once. */
1081
1093
  devices.changed = () => bridge.recheck();
@@ -46,7 +46,10 @@ export class Operators {
46
46
  const r = await this.#host(['operator', 'list']);
47
47
  if (r.code !== 0) throw new Refusal(502, `Who may sign in could not be read: ${firstLine(r.stderr) || `exit ${r.code}`}`);
48
48
  const read = String(r.stdout).split('\n').map((l) => l.split('\t')).filter(([e, s]) => EMAIL.test(e ?? '') && ['enabled', 'disabled'].includes(s));
49
+ const before = JSON.stringify(this.#list);
49
50
  if (read.length) this.#list = read.map(([email, state]) => ({ email, enabled: state === 'enabled' }));
51
+ /* Changed outside the page (the host program): whoever lost their place loses their terminals at once (#419). */
52
+ if (JSON.stringify(this.#list) !== before) { try { this.onChanged?.(); } catch { /* the minute's recheck sees it */ } }
50
53
  return this.list();
51
54
  }
52
55
  async #do(argv, input) {
@@ -75,9 +78,25 @@ export class Operators {
75
78
  #lastAdmin = () => false;
76
79
  useLastAdmin(fn) { this.#lastAdmin = fn; }
77
80
  #keep(email) { if (this.#lastAdmin(email)) throw new Refusal(409, 'The last administrator cannot be disabled or removed.'); }
78
- 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'); }
79
98
  async enable(email) { await this.#do(['operator', 'enable', this.#email(email)]); this.#unlock(this.#email(email)); return this.list(); }
80
- 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'); }
81
100
  #unlock(email) { const locks = { ...(this.#store.get('locks') ?? {}) }; delete locks[email]; this.#store.put({ name: 'locks', ...locks }); }
82
101
 
83
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
@@ -1,104 +1,133 @@
1
1
  /* WHO IS AN ADMINISTRATOR, WHO A MEMBER (24-11, #419).
2
2
  *
3
- * Every account that may sign in (operators.mjs) is, by default, an ADMINISTRATOR: it may do everything, as
4
- * every account did before this file existed -- an update changes nothing for the accounts already there. An
5
- * administrator makes another account a MEMBER, who sees only the conversations given to it (grants.mjs,
6
- * `person:<email>`), through its own door (/m/, door.mjs), and nothing else: the gate of everything else
7
- * (gate.mjs, main.mjs) admits administrators only.
3
+ * BEFORE ANY MEMBER (no file): every account that may sign in (operators.mjs) is an ADMINISTRATOR, as every account
4
+ * was before this file existed -- an update changes nothing for the accounts already there.
5
+ *
6
+ * THE FIRST MEMBER writes the file, and from then on BOTH lists are written out: the administrators by name (every
7
+ * account there was then, but the new member) and the members. An account in neither -- added outside the page,
8
+ * or between two steps -- is a MEMBER: nothing is ever given by default (audit 24-11).
8
9
  *
9
10
  * Two rules on top, never broken:
10
- * - ONE ACCOUNT, AN ADMINISTRATOR: when only one account exists (enabled or not: a member must never become
11
- * the only one by having the others locked out), it is an administrator, whatever was written;
11
+ * - ONE ACCOUNT, AN ADMINISTRATOR: when only one account exists (enabled or not: a member must never become the
12
+ * only one by having the others locked out), it is an administrator, whatever was written;
12
13
  * - THE LAST ADMINISTRATOR stays one: it cannot be made a member (nor, in operators.mjs, disabled, removed or
13
14
  * locked out after failed sign-ins).
14
15
  *
15
- * KEPT where nothing half-written is ever read: written to a new file renamed over the old one, the good one
16
- * before it kept as `.bak`. Unreadable both: nobody is taken for an administrator but the one account alone,
17
- * and it is said -- a damaged file never hands a member everything.
16
+ * KEPT where nothing half-written is ever read: written to a new file renamed over the old one, the good one before
17
+ * it kept as `.bak`. Both unreadable: the lists last read stay in use; at a start with none, the accounts the
18
+ * server was installed with (`install`, its --operators) are the administrators and every other one a member --
19
+ * never everybody locked out, never a member made an administrator. It is said, loudly.
18
20
  */
19
21
  import { readFileSync, writeFileSync, renameSync, existsSync, copyFileSync, mkdirSync } from 'node:fs';
20
22
  import { dirname } from 'node:path';
21
23
  import { Refusal } from './conversations.mjs';
22
24
 
23
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;
28
+ const low = (e) => String(e ?? '').trim().toLowerCase();
24
29
 
25
30
  export class People {
26
- #path; #roles = {}; #damaged = false; #accounts; #tell; #changed = () => {};
27
- /* Told when a role changes: the terminals of whoever lost something end at once (bridge.recheck). */
28
- useChanged(fn) { this.#changed = fn; }
29
- /* `accounts()`: every account there is, enabled or not ([{ email, enabled }], operators.mjs). */
30
- constructor({ path, accounts = () => [], tell = () => {} }) {
31
- this.#path = path; this.#accounts = accounts; this.#tell = tell;
31
+ #path; #lists = null; #damaged = false; #accounts; #tell; #install; #changed = () => {};
32
+ /* `accounts()`: every account there is, enabled or not ([{ email, enabled }], operators.mjs).
33
+ `install`: the accounts the server was started with (--operators), the administrators of last resort. */
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;
32
38
  mkdirSync(dirname(path), { recursive: true });
33
39
  this.#load();
34
40
  }
41
+ /* Told when a role changes: the terminals of whoever lost something end at once (bridge.recheck). */
42
+ useChanged(fn) { this.#changed = fn; }
43
+ changed() { try { this.#changed(); } catch { /* the minute's recheck sees it */ } }
35
44
 
36
45
  #read(file) {
37
46
  const data = JSON.parse(readFileSync(file, 'utf8'));
38
- if (!data || typeof data !== 'object' || !data.roles || typeof data.roles !== 'object') throw new Error('not a roles file');
39
- return Object.fromEntries(Object.entries(data.roles).filter(([e, r]) => typeof e === 'string' && ROLES.includes(r)));
47
+ if (!data || !Array.isArray(data.admins) || !Array.isArray(data.members)) throw new Error('not a roles file');
48
+ return { admins: [...new Set(data.admins.map(low))], members: [...new Set(data.members.map(low))] };
40
49
  }
41
50
  #load() {
42
- if (!existsSync(this.#path) && !existsSync(`${this.#path}.bak`)) { this.#roles = {}; return; }
51
+ if (!existsSync(this.#path) && !existsSync(`${this.#path}.bak`)) { this.#lists = null; return; }
43
52
  for (const file of [this.#path, `${this.#path}.bak`]) {
44
- try { this.#roles = this.#read(file); this.#damaged = false; return; } catch { /* the next one */ }
53
+ try { this.#lists = this.#read(file); this.#damaged = false; return; } catch { /* the next one */ }
45
54
  }
46
- this.#damaged = true; this.#roles = {};
47
- this.#tell('The file of who is an administrator cannot be read', `${this.#path}: until it is repaired, only an account alone is an administrator.`);
55
+ this.#damaged = true;
56
+ this.#tell('The file of who is an administrator cannot be read', `${this.#path}: until it is repaired, the accounts this server was installed with are its administrators, every other one a member.`);
48
57
  }
49
58
  #save() {
50
59
  const tmp = `${this.#path}.new`;
51
- writeFileSync(tmp, `${JSON.stringify({ roles: this.#roles }, null, 1)}\n`, { mode: 0o600 });
60
+ writeFileSync(tmp, `${JSON.stringify(this.#lists, null, 1)}\n`, { mode: 0o600 });
52
61
  if (existsSync(this.#path)) { try { this.#read(this.#path); copyFileSync(this.#path, `${this.#path}.bak`); } catch { /* the old one was bad: no copy of it */ } }
53
62
  renameSync(tmp, this.#path);
63
+ this.#damaged = false;
54
64
  }
55
65
 
56
- #all() { return (this.#accounts() ?? []).map((a) => ({ email: String(a.email).toLowerCase(), enabled: a.enabled !== false })); }
66
+ #all() { return (this.#accounts() ?? []).map((a) => ({ email: low(a.email), enabled: a.enabled !== false })); }
57
67
 
58
68
  /* 'admin' or 'member'. */
59
69
  roleOf(email) {
60
- const e = String(email ?? '').toLowerCase();
61
- const all = this.#all();
62
- if (all.length <= 1) return 'admin';
63
- if (this.#damaged) return 'member';
64
- return this.#roles[e] === 'member' ? 'member' : 'admin';
70
+ const e = low(email);
71
+ if (this.#all().length <= 1) return 'admin';
72
+ if (this.#damaged) return this.#install.includes(e) ? 'admin' : 'member';
73
+ if (this.#lists === null) return 'admin';
74
+ return this.#lists.admins.includes(e) && !this.#lists.members.includes(e) ? 'admin' : 'member';
65
75
  }
66
- damaged() { return this.#damaged; }
67
76
  /* The enabled administrators. */
68
- 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); }
69
78
  /* Whether taking `email` out of the administrators (made a member, disabled, removed, locked out) leaves none. */
70
79
  isLastAdmin(email) {
71
- const e = String(email ?? '').toLowerCase();
80
+ const e = low(email);
72
81
  const admins = this.admins();
73
82
  return admins.length <= 1 && (admins.length === 0 || admins[0] === e);
74
83
  }
75
84
 
85
+ /* The lists written out at the first member: every account there is now an administrator, as it was. */
86
+ #seed() { if (this.#lists === null) this.#lists = { admins: this.#all().map((a) => a.email), members: [] }; }
87
+ #put(e, role) {
88
+ this.#lists.admins = this.#lists.admins.filter((x) => x !== e);
89
+ this.#lists.members = this.#lists.members.filter((x) => x !== e);
90
+ (role === 'admin' ? this.#lists.admins : this.#lists.members).push(e);
91
+ }
92
+
76
93
  setRole(email, role) {
77
- const e = String(email ?? '').toLowerCase();
94
+ const e = low(email);
78
95
  if (!ROLES.includes(role)) throw new Refusal(400, 'A role is admin or member.');
79
96
  if (!this.#all().some((a) => a.email === e)) throw new Refusal(404, 'No such account.');
80
97
  if (this.#damaged) throw new Refusal(503, 'The file of who is an administrator cannot be read: repair it first.');
81
- if (role === 'member' && this.roleOf(e) === 'admin' && this.isLastAdmin(e)) throw new Refusal(409, 'The last administrator cannot be made a member.');
82
- if (role === 'admin') delete this.#roles[e]; else this.#roles[e] = 'member';
83
- this.#save();
84
- try { this.#changed(); } catch { /* the minute's recheck sees it */ }
98
+ if (role === this.roleOf(e)) return this.list();
99
+ if (role === 'member' && this.isLastAdmin(e)) throw new Refusal(409, 'The last administrator cannot be made a member.');
100
+ this.#seed(); this.#put(e, role); this.#save();
101
+ this.changed();
85
102
  return this.list();
86
103
  }
87
- /* An account added: its role, said at once (a removed account added again does not come back as it was). */
88
- added(email, role) {
89
- const e = String(email ?? '').toLowerCase();
90
- if (!ROLES.includes(role)) return;
91
- if (role === 'admin') delete this.#roles[e]; else this.#roles[e] = 'member';
92
- if (!this.#damaged) this.#save();
104
+ /* An account ABOUT TO BE added, its role said first: never an administrator for a moment by mistake, and an
105
+ account removed then added again does not come back as it was. */
106
+ adding(email, role) {
107
+ const e = low(email);
108
+ if (!ROLES.includes(role) || this.#damaged) return;
109
+ if (this.#lists === null && role === 'admin') return;
110
+ this.#seed(); this.#put(e, role); this.#save();
93
111
  }
94
112
  /* An account removed: its role forgotten with it. */
95
113
  removed(email) {
96
- const e = String(email ?? '').toLowerCase();
97
- if (!(e in this.#roles) || this.#damaged) return;
98
- delete this.#roles[e]; this.#save();
114
+ const e = low(email);
115
+ if (this.#lists === null || this.#damaged) return;
116
+ this.#lists.admins = this.#lists.admins.filter((x) => x !== e);
117
+ this.#lists.members = this.#lists.members.filter((x) => x !== e);
118
+ this.#save();
119
+ }
120
+ /* Accounts gone outside the page (the host program): their roles forgotten. Returns the addresses forgotten. */
121
+ prune() {
122
+ if (this.#lists === null || this.#damaged) return [];
123
+ const here = new Set(this.#all().map((a) => a.email));
124
+ if (here.size === 0) return [];
125
+ const gone = [...this.#lists.admins, ...this.#lists.members].filter((e) => !here.has(e));
126
+ if (!gone.length) return [];
127
+ this.#lists.admins = this.#lists.admins.filter((e) => here.has(e)); this.#lists.members = this.#lists.members.filter((e) => here.has(e));
128
+ this.#save();
129
+ return gone;
99
130
  }
100
- /* Said to whoever waits on a change (a right taken: its terminal ends). */
101
- changed() { try { this.#changed(); } catch { /* the minute's recheck sees it */ } }
102
131
  /* The role a new account gets when none is said: a member (24-11, its owner's choice); an administrator is ticked. */
103
132
  defaultRole() { return 'member'; }
104
133
  list() { return this.#all().map((a) => ({ ...a, role: this.roleOf(a.email) })); }
@@ -59,7 +59,7 @@ export const SETTINGS_WORDS_FR = {
59
59
  'set-lang-device': 'La langue de chaque appareil', 'set-res-now': 'Mémoire {m} % · disque {d} %',
60
60
  'set-share-memory': 'Mémoire par machine', 'set-share-disk': 'Disque par machine', 'set-share-others': 'Autres',
61
61
  'set-share-rest': 'Système et autres', 'set-share-else': 'Tout le reste', 'set-share-free': 'Libre', 'set-share-used': 'Utilisé', 'set-share-of': 'sur {total}',
62
- 'set-binders-max': 'Les agents en font {n} au plus', 'set-admin-1': '1 administrateur', 'set-admins': '{n} administrateurs', 'set-member-1': '1 membre', 'set-members': '{n} membres',
62
+ 'set-binders-max': 'Les agents en font {n} au plus', 'set-admin-1': '1 administrateur', 'set-admins': '{n} administrateurs', 'set-member-1': '1 membre', 'set-members': '{n} membres', 'set-member-gone': 'Plus rien n\'est partagé avec vous.', 'set-give-read': 'Lecture seule', 'set-give-chat': 'Chat', 'set-give-both': 'Chat + terminal', 'set-give-terminal': 'Terminal', 'set-give-none': 'Retirer l\'accès', 'set-given-none': 'Rien de partagé pour l\'instant.', 'set-given-ai': 'Chat et terminal : tout ce que son IA atteint.', 'set-give-add': 'Partager une conversation…', 'set-role-admin': 'Administrateur', 'set-role-member': 'Membre', 'set-add-account': 'Ajouter un compte', 'set-ch-s-operators-about': 'Qui se connecte, et ce qu\'il voit.',
63
63
  'set-backup-now': 'Exporter · importer', 'set-git-key': '1 clé git', 'set-git-keys': '{n} clés git', 'set-restart': 'redémarrer',
64
64
  'set-logs-now': 'Clavarium, machines, système',
65
65
  /* Diagnostics › Charge (vm.mjs HostTally): les commandes à l'hôte, par fenêtre de 5 minutes. */
@@ -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');
@@ -48,10 +50,19 @@ export function attachConsole(server, { tethers, gate = () => 'local', originOk
48
50
  const target = machineOf(tethers, url.searchParams.get('target'));
49
51
  if (!originOk(request.headers) || gate(request.headers) === undefined || !target) { socket.destroy(); return; }
50
52
  const cols = Number(url.searchParams.get('cols')); const rows = Number(url.searchParams.get('rows'));
51
- sockets.handleUpgrade(request, socket, head, (ws) => { void seat(ws, target, whoOf(request.headers), { cols, rows }); });
53
+ sockets.handleUpgrade(request, socket, head, (ws) => {
54
+ /* Still an administrator (#419): made a member, disabled, removed -- the console ends at once. */
55
+ const still = () => gate(request.headers) !== undefined;
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));
59
+ ws.on('close', () => clearInterval(watch));
60
+ ws.on('message', () => { if (!still()) { try { ws.close(4403, 'not allowed any more'); } catch { /* gone */ } } });
61
+ void seat(ws, target, whoOf(request.headers), { cols, rows }, still);
62
+ });
52
63
  });
53
64
 
54
- async function seat(ws, target, who, { cols, rows }) {
65
+ async function seat(ws, target, who, { cols, rows }, still = () => true) {
55
66
  const send = (data, binary = false) => { if (ws.readyState === 1) ws.send(data, { binary }); };
56
67
  let handle = null; let gone = false; const early = [];
57
68
  const onEvent = (e) => {
@@ -73,6 +84,7 @@ export function attachConsole(server, { tethers, gate = () => 'local', originOk
73
84
  /* What came meanwhile is in the replay already: only the latest state is said again. */
74
85
  if (early.some((e) => e.type === 'closed')) { try { ws.close(CLOSE_ENDED, 'ended'); } catch { /* gone */ } return; }
75
86
  ws.on('message', (data, binary) => {
87
+ if (!still()) return;
76
88
  if (binary) { handle.write(Buffer.from(data).toString('utf8')); return; }
77
89
  let m; try { m = JSON.parse(String(data)); } catch { return; }
78
90
  if (m?.type === 'resize') handle.resize(Number(m.cols), Number(m.rows));
@@ -82,6 +94,8 @@ export function attachConsole(server, { tethers, gate = () => 'local', originOk
82
94
  else if (m?.type === 'interrupt') handle.interrupt();
83
95
  });
84
96
  }
97
+ /* `recheck`: each open console looked at now (a role changed, #419). */
98
+ sockets.recheck = () => { for (const look of [...open.values()]) look(); };
85
99
  return sockets;
86
100
  }
87
101
 
package/web/app.js CHANGED
@@ -1353,7 +1353,7 @@
1353
1353
  return j;
1354
1354
  };
1355
1355
  /* The name a person reads; a conversation made before free names is read by its identifier. */
1356
- const shownName = (c) => (c && typeof c.title === 'string' && c.title ? c.title : c?.name ?? '');
1356
+ const shownName = (c) => (c && typeof c.title === 'string' && c.title ? c.title : DEVICE && c && typeof c.chatName === 'string' && c.chatName ? c.chatName : c?.name ?? '');
1357
1357
  /* It needs its owner: it asks or waits, its answerer asks, it failed, its machine is unwell. Said even when it is hidden. */
1358
1358
  /* Its tool asks or waits for its owner, and the owner has not written since (talk.mjs, brief). */
1359
1359
  const talkNeeds = (c) => Boolean(c.talk && (c.talk.needs ?? (c.talk.waiting > 0 || c.talk.state === 'waiting')));
@@ -1996,6 +1996,8 @@
1996
1996
  const mePath = () => `${API}/me?c=${encodeURIComponent(current)}`;
1997
1997
  let r = await fetch(mePath());
1998
1998
  if (leaving(r)) return;
1999
+ /* A member whose account was changed or removed (#419): said plainly, nothing more tried. */
2000
+ if (MEMBER && r.status === 403) { shut(uiSaid('set-member-gone', 'Nothing is shared with you now.')); return; }
1999
2001
  if (r.status === 401) {
2000
2002
  /* The session ended: the device signs again, quietly. */
2001
2003
  const door = await window.clavariumDoor();
@@ -8331,7 +8333,7 @@
8331
8333
 
8332
8334
  /* ---------- Settings: this device, and the platform ---------- */
8333
8335
  /* What a member may use, conversation by conversation (#419): Chat to read, Chat, Chat and terminal, Terminal. */
8334
- const GIVE_LEVELS = [['', 'Nothing'], ['r', 'Read the chat'], ['rw', 'Chat'], ['rwx', 'Chat and terminal'], ['x', 'Terminal']];
8336
+ const GIVE_LEVELS = () => [['r', uiSaid('set-give-read', 'Read only')], ['rw', uiSaid('set-give-chat', 'Chat')], ['rwx', uiSaid('set-give-both', 'Chat + terminal')], ['x', uiSaid('set-give-terminal', 'Terminal')], ['', uiSaid('set-give-none', 'Remove access')]];
8335
8337
  function memberGiven(o) {
8336
8338
  const box = el('div', 'op-given');
8337
8339
  const given = new Map((o.given ?? []).map((g) => [g.name, g.rights]));
@@ -8345,17 +8347,19 @@
8345
8347
  };
8346
8348
  const level = (name, rights) => {
8347
8349
  const sel = el('select'); sel.setAttribute('aria-label', `What ${o.email} may use in ${label(name)}`);
8348
- for (const [v, l] of GIVE_LEVELS) { const opt = el('option', '', l); opt.value = v; sel.append(opt); }
8349
- sel.value = GIVE_LEVELS.some(([v]) => v === rights) ? rights : 'rw';
8350
+ for (const [v, l] of GIVE_LEVELS()) { const opt = el('option', '', l); opt.value = v; sel.append(opt); }
8351
+ sel.value = GIVE_LEVELS().some(([v]) => v === rights) ? rights : 'rw';
8350
8352
  sel.addEventListener('change', () => void set(name, sel.value));
8351
8353
  return sel;
8352
8354
  };
8353
- if (given.size === 0) box.append(el('small', '', 'Given nothing yet.'));
8355
+ if (given.size === 0) box.append(el('small', '', uiSaid('set-given-none', 'Nothing shared yet.')));
8356
+ /* What a chat or a terminal really gives (audit 24-11): what its AI can reach -- its folders, mail, keys. */
8357
+ else box.append(el('small', 'hint', uiSaid('set-given-ai', 'Chat and terminal: all its AI can reach.')));
8354
8358
  for (const [name, rights] of given) { const line = el('div', 'op-given-line'); line.append(el('span', '', label(name)), level(name, rights)); box.append(line); }
8355
8359
  const rest = conversations.filter((c) => !given.has(c.name));
8356
8360
  if (rest.length) {
8357
8361
  const add = el('select', 'op-give-add'); add.setAttribute('aria-label', `Give ${o.email} a conversation`);
8358
- const first = el('option', '', 'Give a conversation...'); first.value = ''; add.append(first);
8362
+ const first = el('option', '', uiSaid('set-give-add', 'Share a conversation…')); first.value = ''; add.append(first);
8359
8363
  for (const c of rest) { const opt = el('option', '', label(c.name)); opt.value = c.name; add.append(opt); }
8360
8364
  add.addEventListener('change', () => { if (add.value) void set(add.value, 'rw'); });
8361
8365
  box.append(add);
@@ -8368,6 +8372,7 @@
8368
8372
  $('settings-ch-operators').hidden = !got || got.local === true;
8369
8373
  if (!got || got.local) return;
8370
8374
  if (got.defaultRole && !$('operators-role').dataset.touched) $('operators-role').value = got.defaultRole;
8375
+ $('operators-role').onchange = () => { $('operators-role').dataset.touched = '1'; };
8371
8376
  const rows = $('operators-rows'); rows.replaceChildren();
8372
8377
  const act = async (path) => {
8373
8378
  $('operators-error').hidden = true;
@@ -8386,7 +8391,7 @@
8386
8391
  /* ITS ROLE (#419): an administrator does everything; a member sees only what it is given. Never one's own. */
8387
8392
  if (o.email !== got.me) {
8388
8393
  const role = el('select', 'op-role'); role.setAttribute('aria-label', `Role of ${o.email}`);
8389
- for (const [v, l] of [['admin', 'Administrator'], ['member', 'Member']]) { const opt = el('option', '', l); opt.value = v; role.append(opt); }
8394
+ for (const [v, l] of [['admin', uiSaid('set-role-admin', 'Administrator')], ['member', uiSaid('set-role-member', 'Member')]]) { const opt = el('option', '', l); opt.value = v; role.append(opt); }
8390
8395
  role.value = o.role ?? 'admin';
8391
8396
  role.addEventListener('change', async () => {
8392
8397
  $('operators-error').hidden = true;
@@ -8395,13 +8400,15 @@
8395
8400
  await paintOperators();
8396
8401
  });
8397
8402
  acts.append(role);
8398
- } else name.append(el('small', '', o.role === 'member' ? 'Member' : 'Administrator'));
8403
+ } else name.append(el('small', '', o.role === 'member' ? uiSaid('set-role-member', 'Member') : uiSaid('set-role-admin', 'Administrator')));
8399
8404
  acts.append(...buttons.map(([verb, label]) => { const b = el('button', verb === 'remove' ? 'danger' : '', label); b.type = 'button'; b.dataset.act = verb; b.addEventListener('click', () => void act([o.email, verb])); return b; }));
8400
8405
  row.append(name, acts);
8401
8406
  rows.append(row);
8402
8407
  /* WHAT A MEMBER WAS GIVEN (#419): each conversation, its chat and/or its terminal; one more added from a list. */
8403
8408
  if (o.role === 'member') rows.append(memberGiven(o));
8404
8409
  }
8410
+ /* Its line in the chapter's head: counted once the rows are there (#419). */
8411
+ void paintSettingsStates().catch(() => {});
8405
8412
  }
8406
8413
  /* API KEYS (server/apikeys.mjs): what a program or an AI elsewhere may read with a key. Made with no
8407
8414
  scope until one is ticked; its secret shown this once, then never; revoked at once, confirmed in place.
@@ -13875,7 +13882,7 @@
13875
13882
  /* A device may have been given several conversations, each by a code of
13876
13883
  its own. One is shown at a time; the others are a tap away. */
13877
13884
  function offerOthers(others) {
13878
- $('others').hidden = false;
13885
+ $('others').hidden = MEMBER && others.length === 0;
13879
13886
  $('others').textContent = others.length > 0 ? `Conversations (${others.length + 1})` : MEMBER ? 'Conversations' : 'This device';
13880
13887
  $('others').onclick = () => {
13881
13888
  const rows = $('others-rows');
package/web/index.html CHANGED
@@ -1163,10 +1163,10 @@
1163
1163
  <section class="settings-group" id="settings-group-access" data-group="access" role="tabpanel" aria-label="Access">
1164
1164
  <!-- WHO MAY SIGN IN (server/operators.mjs): hidden on this machine alone. -->
1165
1165
  <details class="chapter" id="settings-ch-operators" data-chapter="s-operators" hidden>
1166
- <summary><span class="chapter-title" data-said="set-ch-s-operators">Accounts</span><span class="chapter-about">Who may sign in, and what each sees.</span></summary>
1166
+ <summary><span class="chapter-title" data-said="set-ch-s-operators">Accounts</span><span class="chapter-about" data-said="set-ch-s-operators-about">Who signs in, and what they see.</span></summary>
1167
1167
  <div class="chapter-body">
1168
1168
  <div id="operators-rows"></div>
1169
- <form id="operators-new" class="set-row" autocomplete="off"><div class="set-what"><label for="operators-email">Add an account</label><small>Email address</small><small class="tip" hidden>Locked 15 min after 5 failures. The last administrator is never locked or removed.</small></div><div class="set-control"><input id="operators-email" type="email" placeholder="someone@example.com" spellcheck="false" autocapitalize="off" required><select id="operators-role" aria-label="Role of the new account"><option value="member">Member</option><option value="admin">Administrator</option></select><button type="submit">Add</button></div></form>
1169
+ <form id="operators-new" class="set-row" autocomplete="off"><div class="set-what"><label for="operators-email" data-said="set-add-account">Add an account</label><small>Email address</small><small class="tip" hidden>Locked 15 min after 5 failures. The last administrator is never locked or removed.</small></div><div class="set-control"><input id="operators-email" type="email" placeholder="someone@example.com" spellcheck="false" autocapitalize="off" required><select id="operators-role" aria-label="Role of the new account"><option value="member" data-said="set-role-member">Member</option><option value="admin" data-said="set-role-admin">Administrator</option></select><button type="submit">Add</button></div></form>
1170
1170
  <div id="operators-password" class="as-form" hidden><p><b id="operators-password-for"></b>: its password, shown <b>this once</b>. Give it to them yourself.</p><div class="row"><input id="operators-password-value" readonly spellcheck="false"><button type="button" id="operators-password-copy">Copy</button><button type="button" id="operators-password-done">Done</button></div></div>
1171
1171
  <p class="error" id="operators-error" role="alert" hidden></p>
1172
1172
  </div>
package/web/style.css CHANGED
@@ -195,8 +195,8 @@ footer#keys { border-top: 0; }
195
195
  .device { display: flex; align-items: center; gap: 10px; padding: 8px 0; border-top: 1px solid var(--line); flex-wrap: wrap; }
196
196
  .device b { flex: 1; min-width: 120px; } .device small { color: var(--ink2); }
197
197
  button.danger { border-color: var(--danger); color: var(--danger); }
198
- html[data-door="device"] #app { display: block; }
199
- html[data-door="device"] #room { height: 100%; }
198
+ html:is([data-door="device"],[data-door="member"]) #app { display: block; }
199
+ html:is([data-door="device"],[data-door="member"]) #room { height: 100%; }
200
200
  #secret-rows { display: flex; flex-direction: column; }
201
201
  #secret-new { display: flex; flex-direction: column; gap: 6px; max-width: 560px; }
202
202
  #secret-new label { font-size: .75rem; color: var(--ink2); }
@@ -1148,9 +1148,9 @@ button.inline:hover { color: var(--brass-ink); }
1148
1148
  .item[data-hidden="true"] { opacity: .7; }
1149
1149
 
1150
1150
  /* ---------- THE BAR (G): « · state dot + name · [Chat | Terminal | Assets N] · settings ---------- */
1151
- html:not([data-door="device"]) #room > header { flex-wrap: nowrap; }
1152
- html:not([data-door="device"]) #room > header #state { flex: 0 0 auto; width: 10px; height: 10px; overflow: hidden; font-size: 0; color: transparent; }
1153
- html:not([data-door="device"]) #room > header #state::before { width: 10px; height: 10px; margin: 0; vertical-align: top; }
1151
+ html:not([data-door="device"]):not([data-door="member"]) #room > header { flex-wrap: nowrap; }
1152
+ html:not([data-door="device"]):not([data-door="member"]) #room > header #state { flex: 0 0 auto; width: 10px; height: 10px; overflow: hidden; font-size: 0; color: transparent; }
1153
+ html:not([data-door="device"]):not([data-door="member"]) #room > header #state::before { width: 10px; height: 10px; margin: 0; vertical-align: top; }
1154
1154
  .views { display: inline-flex; flex: 0 0 auto; gap: 2px; padding: 3px; border: 1px solid var(--line); border-radius: 10px; background: var(--bg); }
1155
1155
  .views button { display: inline-flex; align-items: center; gap: 6px; border: 0; background: transparent; color: var(--ink2); border-radius: 7px; padding: 5px 11px; }
1156
1156
  .views button[aria-pressed="true"] { background: var(--panel); color: var(--ink); box-shadow: 0 0 0 1px var(--line); }
@@ -1159,7 +1159,7 @@ html:not([data-door="device"]) #room > header #state::before { width: 10px; heig
1159
1159
  header .ic, #folders .ic { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; flex: 0 0 auto; }
1160
1160
  #folders { display: inline-flex; align-items: center; gap: 6px; flex: 0 0 auto; }
1161
1161
  @media (max-width: 900px) { .views button span, #folders span { display: none; } .views button { padding: 6px 10px; } }
1162
- @media (max-width: 700px) { html:not([data-door="device"]) #room > header #menu { display: none; } }
1162
+ @media (max-width: 700px) { html:not([data-door="device"]):not([data-door="member"]) #room > header #menu { display: none; } }
1163
1163
 
1164
1164
  /* The chat's display settings: an eye, not sliders (Parley draws its own sign; it is masked here). */
1165
1165
  #simple-thread .parley-prefs-open svg, #salon-thread .parley-prefs-open svg { display: none; }
@@ -1490,7 +1490,7 @@ select.pill { appearance: auto; }
1490
1490
  .rv-tree { position: static; max-height: none; }
1491
1491
  }
1492
1492
  @media (max-width: 700px) {
1493
- html:not([data-door="device"]) #room > header .views button, html:not([data-door="device"]) #room > header #folders, html:not([data-door="device"]) #room > header .topbar-lead-back { min-height: 36px; height: 36px; }
1493
+ html:not([data-door="device"]):not([data-door="member"]) #room > header .views button, html:not([data-door="device"]):not([data-door="member"]) #room > header #folders, html:not([data-door="device"]):not([data-door="member"]) #room > header .topbar-lead-back { min-height: 36px; height: 36px; }
1494
1494
  .views { padding: 2px; }
1495
1495
  }
1496
1496
  #copy-close, #files-close, #preview-close { font-size: 1.375rem; line-height: 1; min-width: 40px; padding: 4px 10px; }
@@ -2583,7 +2583,7 @@ header.topbar > :is(.topbar-fold, .topbar-lead-back):hover { color: var(--ink);
2583
2583
  header.topbar > .topbar-lead-back[hidden] { display: none; }
2584
2584
  @media (max-width: 700px) { header.topbar > .topbar-fold { display: none; } }
2585
2585
  @media (min-width: 701px) { header.topbar > .topbar-lead-back { display: none; } }
2586
- header.topbar .bar-state, html:not([data-door="device"]) header.topbar #state { width: 10px; height: 10px; border-radius: 50%; flex: none; }
2586
+ header.topbar .bar-state, html:not([data-door="device"]):not([data-door="member"]) header.topbar #state { width: 10px; height: 10px; border-radius: 50%; flex: none; }
2587
2587
  header.topbar .bar-state { background: var(--ok); }
2588
2588
  header.topbar .bar-state[hidden] { display: none; }
2589
2589
  /* A room one of whose AIs speaks now: its dot as a conversation's at work, the words under its name. */
@@ -2600,7 +2600,7 @@ header.topbar .views .icon-btn { width: auto; height: auto; }
2600
2600
  header.topbar .views button { height: 32px; min-height: 32px; padding-block: 0; }
2601
2601
  @media (max-width: 700px) { header.topbar { height: 48px; min-height: 48px; padding: 0 8px; gap: 6px; } }
2602
2602
  /* A device's page (/c/): the same bar, its own controls may take a second line on a narrow screen (its menu "..."). */
2603
- html[data-door="device"] header.topbar { height: auto; }
2603
+ html:is([data-door="device"],[data-door="member"]) header.topbar { height: auto; }
2604
2604
  /* A place's top bar stays at the top while its page scrolls (05-11), edge to edge over the page's own margins.
2605
2605
  (A page with a bar starts at its bar: no margin above it, so it sticks where it rests.) */
2606
2606
  :is(.sheet, #newconv, #salon-new):has(> header.topbar) { padding-top: 0; }
@@ -3179,11 +3179,11 @@ button.kit-switch[aria-checked="true"]::after { left: 18px; background: var(--ok
3179
3179
  #machines-confirm { margin: 8px 16px; }
3180
3180
  /* A phone (13-11): the bar's five buttons tighter, so that all stay on the screen -- its name gives way, never the bar. */
3181
3181
  @media (max-width: 480px) {
3182
- html:not([data-door="device"]) #room > header #name { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
3183
- html:not([data-door="device"]) #room > header :is(.bar-right, .views) { flex: none; }
3184
- html:not([data-door="device"]) #room > header .views { gap: 0; padding: 2px; }
3185
- html:not([data-door="device"]) #room > header .views button { gap: 4px; padding-inline: 7px; }
3186
- html:not([data-door="device"]) #room > header .views .count { min-width: 1.2em; padding: 1px 4px; }
3182
+ html:not([data-door="device"]):not([data-door="member"]) #room > header #name { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
3183
+ html:not([data-door="device"]):not([data-door="member"]) #room > header :is(.bar-right, .views) { flex: none; }
3184
+ html:not([data-door="device"]):not([data-door="member"]) #room > header .views { gap: 0; padding: 2px; }
3185
+ html:not([data-door="device"]):not([data-door="member"]) #room > header .views button { gap: 4px; padding-inline: 7px; }
3186
+ html:not([data-door="device"]):not([data-door="member"]) #room > header .views .count { min-width: 1.2em; padding: 1px 4px; }
3187
3187
  }
3188
3188
  /* At hand (13-11): a switch's name never under its buttons -- the name keeps its width, the buttons wrap. */
3189
3189
  .hand-switches .set-row > .set-what { flex: none; }