clavarium 0.2.253-beta.1 → 0.2.254-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.253-beta.1",
3
+ "version": "0.2.254-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.253-beta.1",
9
+ "version": "0.2.254-beta.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
13
13
  "@xterm/xterm": "^6.0.0",
14
14
  "clavarium-binder": "0.1.66-next.1",
15
15
  "clavarium-docket": "0.1.2-next.3",
16
- "clavarium-parley": "0.17.102-next.1",
16
+ "clavarium-parley": "0.17.103-next.1",
17
17
  "clavarium-tether": "0.1.0-next.79",
18
18
  "mammoth": "1.13.0",
19
19
  "mermaid": "11.17.2",
@@ -787,9 +787,9 @@
787
787
  }
788
788
  },
789
789
  "node_modules/clavarium-parley": {
790
- "version": "0.17.102-next.1",
791
- "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.102-next.1.tgz",
792
- "integrity": "sha512-RUGpMBGs1ibNjVZnz0ghMP9YJPRlIYQtqlaI94WP354gzcwoUiQ/0G/m8HiWNxXGLVvcWU0hy7pM+3lFvvvosw==",
790
+ "version": "0.17.103-next.1",
791
+ "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.103-next.1.tgz",
792
+ "integrity": "sha512-3gb9swir4OJefi2daaija5RA1GObk+XVwK4iu+Bp6vokei5JiByQk45FoFMZtZYYv+hGo5WpOIHpmuoxK/FXtg==",
793
793
  "license": "MIT",
794
794
  "bin": {
795
795
  "parley": "bin/parley.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.253-beta.1",
3
+ "version": "0.2.254-beta.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.",
@@ -47,7 +47,7 @@
47
47
  "@xterm/xterm": "^6.0.0",
48
48
  "clavarium-binder": "0.1.66-next.1",
49
49
  "clavarium-docket": "0.1.2-next.3",
50
- "clavarium-parley": "0.17.102-next.1",
50
+ "clavarium-parley": "0.17.103-next.1",
51
51
  "clavarium-tether": "0.1.0-next.79",
52
52
  "mammoth": "1.13.0",
53
53
  "mermaid": "11.17.2",
@@ -0,0 +1,84 @@
1
+ /* WHAT A MEMBER MAY CALL (#431, 29-11): the same routes as an administrator, filtered by the server -- never a
2
+ * second API to keep in step. One table, here, says which routes a member reaches at all; every other one is
3
+ * refused, so a route added one day stays closed to members until it is put here on purpose.
4
+ *
5
+ * Each line: a method, the route, and what it needs:
6
+ * 'any' -- nothing of anyone's: the same answer for every account (the tools that can be chosen);
7
+ * 'list' -- answered with what this member may see only (the handler filters, by `request.member`);
8
+ * 'create' -- a conversation of its own, under the room an administrator gave it;
9
+ * 'own' -- what is kept per person (its desk), read and written under its own name only;
10
+ * 'owner' -- a route of one conversation it owns (it made it, or it was made its own);
11
+ * 'asset-owner' -- a route of one asset it owns (its own folder);
12
+ * 'key-owner' -- a route of one key it owns;
13
+ * 'files' -- the files of a folder: which folder it may reach is decided where it is chosen (api.mjs, attached);
14
+ * 'r' / 'w' / 'x' -- a route of one conversation (its name is the route's first part): that right on it,
15
+ * read from the one table of who may do what (grants.mjs), at each request.
16
+ * Administrators are not looked at here: they reach everything, as before. */
17
+
18
+ const NAME = '([a-z][a-z0-9-]{0,31})';
19
+ export const MEMBER_ROUTES = Object.freeze([
20
+ ['GET', /^\/api\/conversations$/, 'list'],
21
+ ['POST', /^\/api\/conversations$/, 'create'],
22
+ ['GET', /^\/api\/tools$/, 'any'],
23
+ /* Its own desk, the home page (desktop.mjs keeps one per person, by the name the sign-in gives). */
24
+ ['GET', /^\/api\/desktop$/, 'own'],
25
+ ['PUT', /^\/api\/desktop$/, 'own'],
26
+ /* The chat's words in the reader's language: the same for everybody. */
27
+ ['GET', /^\/api\/talk\/words$/, 'any'],
28
+ ['GET', new RegExp(`^/api/conversations/${NAME}/talk$`), 'r'],
29
+ ['GET', new RegExp(`^/api/conversations/${NAME}/talk/search$`), 'r'],
30
+ ['POST', new RegExp(`^/api/conversations/${NAME}/talk$`), 'w'],
31
+ ['POST', new RegExp(`^/api/conversations/${NAME}/talk/remind$`), 'w'],
32
+ ['POST', new RegExp(`^/api/conversations/${NAME}/talk/file$`), 'w'],
33
+ ['GET', new RegExp(`^/api/conversations/${NAME}/health$`), 'r'],
34
+ /* Its OWN conversations (it is their owner): their settings and their machine's life -- a name, sleep,
35
+ wake, restart, delete. Not those it was only given. */
36
+ ['POST', new RegExp(`^/api/conversations/${NAME}/title$`), 'owner'],
37
+ ['POST', new RegExp(`^/api/conversations/${NAME}/chat-name$`), 'owner'],
38
+ ['POST', new RegExp(`^/api/conversations/${NAME}/sleep$`), 'owner'],
39
+ ['POST', new RegExp(`^/api/conversations/${NAME}/resume$`), 'owner'],
40
+ ['POST', new RegExp(`^/api/conversations/${NAME}/restart$`), 'owner'],
41
+ ['POST', new RegExp(`^/api/conversations/${NAME}/erase$`), 'owner'],
42
+ ['POST', new RegExp(`^/api/conversations/${NAME}/machine$`), 'owner'],
43
+ /* ITS OWN ASSETS (#431 step 2): its folders -- listed, made, removed, given to its own conversations. */
44
+ ['GET', /^\/api\/resources$/, 'list'],
45
+ ['POST', /^\/api\/resources$/, 'create'],
46
+ ['POST', new RegExp(`^/api/resources/${NAME}/remove$`), 'asset-owner'],
47
+ ['POST', new RegExp(`^/api/conversations/${NAME}/resources$`), 'owner'],
48
+ /* Its own keys: listed (names only), made under a new name, replaced, removed, given to its own conversations. */
49
+ ['GET', /^\/api\/secrets$/, 'list'],
50
+ ['POST', /^\/api\/secrets$/, 'create'],
51
+ ['POST', /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/(replace|remove)$/, 'key-owner'],
52
+ ['POST', new RegExp(`^/api/conversations/${NAME}/secrets$`), 'owner'],
53
+ /* The files of its own folders and of its conversations' work (checked where the folder is chosen: api.mjs). */
54
+ ['GET', /^\/api\/files$/, 'files'],
55
+ ['GET', /^\/api\/files\/(download|page|thumb|text)$/, 'files'],
56
+ ['POST', /^\/api\/files\/(import|make|move|remove|rename|save|taken)$/, 'files'],
57
+ ]);
58
+
59
+ /* { ok: false } or { ok: true, need, conversation? }. `rightsOn(name)`: the member's rights on that conversation. */
60
+ export function memberMay(method, pathname, rightsOn, owns = () => false, ownsAsset = () => false, ownsKey = () => false) {
61
+ for (const [m, route, need] of MEMBER_ROUTES) {
62
+ if (m !== method) continue;
63
+ const hit = route.exec(pathname);
64
+ if (!hit) continue;
65
+ if (need === 'any' || need === 'list' || need === 'create' || need === 'own' || need === 'files') return { ok: true, need };
66
+ const conversation = hit[1];
67
+ if (need === 'key-owner') return ownsKey(hit[1]) ? { ok: true, need, key: hit[1] } : { ok: false, why: 'Only its owner does that.' };
68
+ if (need === 'asset-owner') return ownsAsset(conversation) ? { ok: true, need, asset: conversation } : { ok: false, why: 'Only its owner does that.' };
69
+ if (need === 'owner') return owns(conversation) ? { ok: true, need, conversation } : { ok: false, why: 'Only its owner does that.' };
70
+ return String(rightsOn(conversation) ?? '').includes(need) ? { ok: true, need, conversation } : { ok: false, why: 'This conversation is not shared with you for that.' };
71
+ }
72
+ return { ok: false, why: 'This is for administrators.' };
73
+ }
74
+
75
+ /* What of a conversation a member's list shows: what the list draws, never what is the server's (its keys, its
76
+ folders, its machine's user, its wake-ups, its answerer). */
77
+ export const MEMBER_FIELDS = Object.freeze(['name', 'title', 'chatName', 'group', 'tool', 'toolLabel', 'phase', 'step', 'progress', 'error', 'asleep', 'stopped', 'owner', 'memoryMb', 'cpus', 'diskGb', 'voiceMark', 'hidden']);
78
+ export function memberView(c, rights, email) {
79
+ return {
80
+ ...Object.fromEntries(MEMBER_FIELDS.filter((k) => c[k] !== undefined).map((k) => [k, c[k]])),
81
+ mine: c.owner === email,
82
+ parts: { terminal: rights.includes('x'), chat: rights.includes('r') ? (rights.includes('w') ? 'write' : 'read') : null },
83
+ };
84
+ }
package/server/api.mjs CHANGED
@@ -189,6 +189,8 @@
189
189
  * A request that changes something must come from this site's own pages: the
190
190
  * Origin header is compared, and the body must be JSON, which a form on
191
191
  * another site cannot send. */
192
+ import { memberView } from './access.mjs';
193
+ import { memberCreate } from './door.mjs';
192
194
  import { addMachine } from './sshmachine.mjs';
193
195
  import { openCodeConfig } from './catalog.mjs';
194
196
  import { writeFileSync } from 'node:fs';
@@ -246,6 +248,16 @@ export async function handleApi(request, response, conversations, headers, resou
246
248
  /* A sign-in, said once in a while for the same person (events.mjs). */
247
249
  events?.seen(identity);
248
250
  const attached = (need) => {
251
+ /* A MEMBER (#431 step 2): its own folders; the work folder of a conversation it owns or was given the terminal
252
+ of (its files are the terminal's anyway); nothing else, whatever the address says. */
253
+ if (request.member) {
254
+ const m = request.member;
255
+ if (query.get('r') === WORK_TAB) {
256
+ const c = conversations.list().find((x) => x.name === query.get('c'));
257
+ if (!c || !(c.owner === m.email || m.rightsOn(m.key, c.name).includes('x'))) throw new Refusal(403, 'This conversation\'s files are not yours.');
258
+ } else if (!m.ownsAsset(query.get('r') ?? '')) throw new Refusal(403, 'This folder is not yours.');
259
+ if (!m.still()) throw new Refusal(403, 'This account may not use this page now.');
260
+ }
249
261
  /* The conversation's own work folder, when the server keeps it. */
250
262
  if (query.get('r') === WORK_TAB && resources) {
251
263
  const c = conversations.list().find((x) => x.name === query.get('c'));
@@ -351,12 +363,32 @@ export async function handleApi(request, response, conversations, headers, resou
351
363
  }
352
364
  if (request.method === 'GET') {
353
365
  if (pathname === '/api/tools') return send(200, conversations.tools()), true;
366
+ if (pathname === '/api/conversations' && request.member) {
367
+ /* A member (#431): those it was given and those it made, as the list draws them, nothing of the server's. */
368
+ const m = request.member;
369
+ const names = new Set(m.grantsOf().map((g) => g.name));
370
+ return send(200, conversations.list().filter((c) => names.has(c.name)).map((c) => {
371
+ const rights = m.rightsOn(m.key, c.name);
372
+ return { ...memberView(c, rights, m.email), talk: rights.includes('r') ? (talk?.brief(c.name) ?? null) : null };
373
+ })), true;
374
+ }
354
375
  if (pathname === '/api/conversations') {
355
376
  const lists = binders?.given() ?? {};
356
377
  return send(200, conversations.list().map((c) => ({ ...c, lists: lists[c.name] ?? null, resources: resources?.of(c.name) ?? [], secrets: secrets?.of(c.name) ?? [], ephemeralSecrets: secrets?.liveFor(c.name) ?? [], answerer: answerer?.of(c.name) ?? null, wakeups: wakeups?.of(c.name) ?? null, health: health?.of(c.name) ?? null, talk: talk?.brief(c.name) ?? null }))), true;
357
378
  }
379
+ /* A member's (#431 step 2): its own folders, and to which of ITS conversations each is given -- never
380
+ the administrators' conversations' names. */
381
+ if (pathname === '/api/resources' && resources && request.member) {
382
+ const mine = new Set(request.member.grantsOf().map((g) => g.name));
383
+ return send(200, resources.list().filter((r) => r.owner === request.member.email).map((r) => ({ ...r, attachments: Object.fromEntries(Object.entries(r.attachments ?? {}).filter(([c]) => mine.has(c))) }))), true;
384
+ }
358
385
  if (pathname === '/api/resources' && resources) return send(200, resources.list()), true;
359
386
  if (pathname === '/api/shortcuts' && shortcuts) return send(200, shortcuts.list()), true;
387
+ /* A member's (#431 step 2): its own keys' names, and which of ITS conversations has each. */
388
+ if (pathname === '/api/secrets' && secrets && request.member) {
389
+ const mine = new Set(request.member.grantsOf().map((g) => g.name));
390
+ return send(200, secrets.list().filter((x) => x.owner === request.member.email).map((x) => ({ ...x, conversations: (x.conversations ?? []).filter((c) => mine.has(typeof c === 'string' ? c : c?.name)) }))), true;
391
+ }
360
392
  if (pathname === '/api/secrets' && secrets) return send(200, secrets.list()), true;
361
393
  /* The providers and models OpenCode knows (models.dev), for a conversation made with it (03-11). */
362
394
  if (pathname === '/api/catalog/models' && catalogue) return send(200, { providers: await catalogue.providers() }), true;
@@ -574,7 +606,10 @@ export async function handleApi(request, response, conversations, headers, resou
574
606
  const attaching = /^\/api\/conversations\/([^/]+)\/talk\/file$/.exec(pathname);
575
607
  if (attaching && talk) {
576
608
  if (!originOk(request.headers) || request.headers['content-type'] !== 'application/octet-stream') return send(403, { error: 'This request does not come from this site.' }), true;
577
- return send(201, await talk.attach(decodeURIComponent(attaching[1]), query.get('name') ?? '', request)), true;
609
+ const attached = await talk.attach(decodeURIComponent(attaching[1]), query.get('name') ?? '', request);
610
+ /* A member whose right went while its file came: not given back to it (#431, audit 10 of the door). */
611
+ if (request.member && !request.member.still()) return send(403, { error: 'This conversation is not shared with you any more.' }), true;
612
+ return send(201, attached), true;
578
613
  }
579
614
  /* A file the person attaches in a room (06-11): the same as in a chat, kept in the room. */
580
615
  const roomAttaching = /^\/api\/rooms\/([0-9a-f-]{36})\/talk\/file$/.exec(pathname);
@@ -605,6 +640,7 @@ export async function handleApi(request, response, conversations, headers, resou
605
640
  if (r && r[2] === '/remove') { rooms.remove(r[1]); return send(200, { removed: r[1] }), true; }
606
641
  if (r && r[2] === '/talk') return send(201, await rooms.say(r[1], body?.text, { to: body?.to, files: body?.files })), true;
607
642
  }
643
+ if (pathname === '/api/conversations' && request.member) return send(201, await memberCreate({ conversations, talk, person: request.member, body: body ?? {}, kept: (id) => Boolean(tethers?.grantsOf?.(id)?.length || binders?.grantsOf?.(id)?.length || team?.grants?.on?.(`conversation:${id}`)?.length) })), true;
608
644
  if (pathname === '/api/conversations') {
609
645
  await conversations.admit?.(body);
610
646
  const made = conversations.create(body);
@@ -665,6 +701,8 @@ export async function handleApi(request, response, conversations, headers, resou
665
701
  return send(404, { error: 'Not found.' }), true;
666
702
  }
667
703
  /* A folder, or a git repository (empty, or cloned from `from`). A mailbox has its own way in. */
704
+ /* A member's own folder (#431 step 2): a folder only, its own -- no repository, nothing cloned. */
705
+ if (pathname === '/api/resources' && resources && request.member) return send(201, await resources.create({ name: body.name, type: 'folder', owner: request.member.email })), true;
668
706
  if (pathname === '/api/resources' && resources) {
669
707
  const made = await resources.create({ name: body.name, type: body.type === 'git' ? 'git' : 'folder', from: body.from, via: body.via });
670
708
  /* One an import was waiting for: attached where the file said. */
@@ -768,6 +806,7 @@ export async function handleApi(request, response, conversations, headers, resou
768
806
  return send(200, { ok: true, signature }), true;
769
807
  }
770
808
  if (pathname === '/api/shortcuts' && shortcuts) return send(201, shortcuts.add(body)), true;
809
+ if (pathname === '/api/secrets' && secrets && request.member) return send(201, secrets.set({ name: body.name, value: body.value, expires: body.expires, owner: request.member.email })), true;
771
810
  if (pathname === '/api/secrets' && secrets) { const made = secrets.set(body); setup?.secretAdded(made.name); return send(201, made), true; }
772
811
  /* Asset groups (groups.mjs): a folder-style tidy-up, not a right. */
773
812
  if (pathname === '/api/asset-groups' && groups) return send(201, groups.create(body.label)), true;
@@ -934,6 +973,23 @@ export async function handleApi(request, response, conversations, headers, resou
934
973
  const talking = /^\/api\/conversations\/([^/]+)\/talk(\/invite|\/remind|\/react|\/pin|\/split)?$/.exec(pathname);
935
974
  if (talking && talk) {
936
975
  const conversation = decodeURIComponent(talking[1]);
976
+ /* A member (#431): it writes, as a member, and reminds -- nothing else (turning the chat on or off,
977
+ reacting or answering for the owner, pins); its right looked at again once the body is read
978
+ (audits 6, 8, 10 of the member's door). */
979
+ if (request.member) {
980
+ if (!request.member.still()) return send(403, { error: 'This conversation is not shared with you any more.' }), true;
981
+ if (talking[2] === '/remind') return send(200, await talk.remind(conversation)), true;
982
+ /* Its own conversation's chat, on or off (#431); not one it was only given. */
983
+ if (talking[2] === undefined && typeof body.on === 'boolean' && conversations.list().some((c) => c.name === conversation && c.owner === request.member.email)) { const now = await talk.set(conversation, body.on); retell(conversation); return send(200, now), true; }
984
+ if (talking[2] !== undefined || typeof body.on === 'boolean') return send(403, { error: 'This is for administrators.' }), true;
985
+ /* A sign-in code pasted while its sign-in waits: typed into its tool, never in the thread (#405) -- by a
986
+ member given its terminal only, as on its door (audit 29-11). */
987
+ if (request.member.rightsOn(request.member.key, conversation).includes('x') && conversations.signinHelp?.codeInChat(conversation, body.text, body.files)) return send(201, { ...(await conversations.signinHelp.enterCode(conversation, body.text)), told: 'signin' }), true;
988
+ const mark = `[${request.member.email}, a member]`;
989
+ const clean = (t) => String(t ?? '').replace(/[\u200B-\u200F\u2060\uFEFF]/g, '').replace(/[[\uFF3B]/g, '(');
990
+ const files = Array.isArray(body.files) ? body.files.map((f) => (f && typeof f === 'object' ? { ...f, note: `${mark} ${clean(f.note)}`.trim() } : f)) : body.files;
991
+ return send(201, await talk.say(conversation, `${mark} ${clean(body.text)}`.trim(), undefined, files, undefined, { quick: false })), true;
992
+ }
937
993
  if (talking[2] === '/invite') return send(200, await talk.invite(conversation, typeof body.lang === 'string' ? body.lang : 'en')), true;
938
994
  if (talking[2] === '/remind') return send(200, await talk.remind(conversation, { urgent: body?.urgent === true })), true;
939
995
  if (talking[2] === '/react') return send(200, await talk.react(conversation, body.to, body.reaction ?? null)), true;
@@ -980,6 +1036,8 @@ export async function handleApi(request, response, conversations, headers, resou
980
1036
  const handed = /^\/api\/conversations\/([^/]+)\/secrets$/.exec(pathname);
981
1037
  if (handed && secrets) {
982
1038
  const conversation = decodeURIComponent(handed[1]);
1039
+ /* A member: its own key to its own conversation (the table checked the conversation). */
1040
+ if (request.member && !request.member.ownsKey(String(body.secret ?? ''))) return send(403, { error: 'Only your own keys, to your own conversations.' }), true;
983
1041
  await handSecret(conversation, String(body.secret ?? ''), body.attached === true);
984
1042
  return send(200, { ok: true, secrets: secrets.of(conversation) }), true;
985
1043
  }
@@ -1043,6 +1101,9 @@ export async function handleApi(request, response, conversations, headers, resou
1043
1101
  const attach = /^\/api\/conversations\/([^/]+)\/resources$/.exec(pathname);
1044
1102
  if (attach && resources) {
1045
1103
  const conversation = decodeURIComponent(attach[1]);
1104
+ /* A member (#431 step 2): its own folder to its own conversation (the table checked the conversation), read
1105
+ or write, or taken back; never another's folder. */
1106
+ if (request.member && (!request.member.ownsAsset(String(body.resource ?? '')) || !['read', 'write', 'none', ''].includes(String(body.access ?? '')) || body.shared === true)) return send(403, { error: 'Only your own folders, to your own conversations.' }), true;
1046
1107
  await attachResource(conversation, String(body.resource ?? ''), String(body.access ?? ''), body.shared === true);
1047
1108
  return send(200, { ok: true, resources: resources.of(conversation) }), true;
1048
1109
  }
@@ -1079,6 +1140,21 @@ export async function handleApi(request, response, conversations, headers, resou
1079
1140
  await health.check(conversation, { asked: true }); return send(200, health.of(conversation)), true;
1080
1141
  }
1081
1142
  if (machine[2] === 'restart') return send(202, await conversations.restart(conversation)), true;
1143
+ /* A member, its own conversation (#431): start, stop or cut off (force) its machine -- not its size (that is counted
1144
+ against its room: later), its watchdog nor its way down. */
1145
+ /* Its size (#431): memory, disk, cores, within the room an administrator gave it for all its own together. */
1146
+ if (request.member && typeof body?.action !== 'string') {
1147
+ const m = request.member; const c = conversations.list().find((x) => x.name === conversation);
1148
+ if (!c || body?.machineMb !== undefined || body?.machineDiskGb !== undefined || body?.machineCpus !== undefined || body?.watchdog !== undefined || body?.escalate !== undefined) return send(403, { error: 'This is for administrators.' }), true;
1149
+ const quota = m.quota(); const used = m.used();
1150
+ const want = { mb: body.memoryMb ?? c.memoryMb ?? 0, diskGb: body.diskGb ?? c.diskGb ?? 0, cpus: body.cpus ?? c.cpus ?? 1 };
1151
+ const was = { mb: c.memoryMb ?? 0, diskGb: c.diskGb ?? 0, cpus: c.cpus ?? 1 };
1152
+ for (const [k, what, unit] of [['mb', 'memory', ' MB'], ['diskGb', 'disk', ' GB'], ['cpus', 'cores', '']]) {
1153
+ if (!Number.isFinite(Number(want[k]))) return send(400, { error: `Its ${what} is a number.` }), true;
1154
+ if (quota[k] > 0 && used[k] - was[k] + Number(want[k]) > quota[k]) return send(409, { error: `Not enough ${what} left: ${quota[k] - used[k] + was[k]}${unit} for this conversation, of your ${quota[k]}${unit}.` }), true;
1155
+ }
1156
+ }
1157
+ if (request.member && typeof body?.action === 'string' && !['start', 'stop', 'force'].includes(body.action)) return send(403, { error: 'This is for administrators.' }), true;
1082
1158
  /* One action on its machine, or the owner's choice for its way down (conversations.mjs, machineAction). */
1083
1159
  if (typeof body?.action === 'string') return send(202, await conversations.machineAction(conversation, body.action)), true;
1084
1160
  if (typeof body?.escalate === 'boolean') return send(200, conversations.setStopEscalate(conversation, body.escalate)), true;
@@ -1152,18 +1228,29 @@ export async function handleApi(request, response, conversations, headers, resou
1152
1228
  const action = /^\/api\/conversations\/([^/]+)\/(sleep|archive|erase)$/.exec(pathname);
1153
1229
  if (action?.[2] === 'erase' && String(body?.confirm ?? '') !== decodeURIComponent(action[1])) throw new Refusal(400, 'Type the name of the conversation to delete it for good.');
1154
1230
  if (!action) return send(404, { error: 'Not found.' }), true;
1155
- await conversations[action[2]](decodeURIComponent(action[1]));
1156
- if (action[2] === 'erase') action[2] = 'archive'; /* what it leaves behind is forgotten as for an archive */
1157
- if (action[2] === 'archive') resources?.forget(decodeURIComponent(action[1]));
1158
- if (action[2] === 'archive') gitKeeper?.forgetConversation(decodeURIComponent(action[1]));
1159
- if (action[2] === 'archive') sharing?.devices.forget(decodeURIComponent(action[1]));
1160
- if (action[2] === 'archive') secrets?.forget(decodeURIComponent(action[1]));
1161
- if (action[2] === 'archive') signin?.forget(decodeURIComponent(action[1]));
1162
- if (action[2] === 'archive') answerer?.forget(decodeURIComponent(action[1]));
1163
- if (action[2] === 'archive') wakeups?.forget(decodeURIComponent(action[1]));
1164
- if (action[2] === 'archive') talk?.forget(decodeURIComponent(action[1]));
1165
- if (action[2] === 'archive') guide?.forget(decodeURIComponent(action[1]));
1166
- if (action[2] === 'archive') health?.forget(decodeURIComponent(action[1]));
1231
+ /* The cleaning once its record is gone, even when the deleting failed half-way (audit 29-11): what it was
1232
+ given never waits for a new conversation of the same name. */
1233
+ const forget = () => {
1234
+ if (conversations.list().some((c) => c.name === decodeURIComponent(action[1]))) return;
1235
+ if (action[2] === 'erase') action[2] = 'archive'; /* what it leaves behind is forgotten as for an archive */
1236
+ if (action[2] === 'archive') resources?.forget(decodeURIComponent(action[1]));
1237
+ if (action[2] === 'archive') gitKeeper?.forgetConversation(decodeURIComponent(action[1]));
1238
+ if (action[2] === 'archive') sharing?.devices.forget(decodeURIComponent(action[1]));
1239
+ if (action[2] === 'archive') secrets?.forget(decodeURIComponent(action[1]));
1240
+ if (action[2] === 'archive') signin?.forget(decodeURIComponent(action[1]));
1241
+ if (action[2] === 'archive') answerer?.forget(decodeURIComponent(action[1]));
1242
+ /* What a member was given of it goes with it: a new conversation of that name is nobody's but its maker's (29-11). */
1243
+ if (action[2] === 'archive') team?.grants?.forgetAsset(`conversation:${decodeURIComponent(action[1])}`);
1244
+ if (action[2] === 'archive') wakeups?.forget(decodeURIComponent(action[1]));
1245
+ if (action[2] === 'archive') talk?.forget(decodeURIComponent(action[1]));
1246
+ if (action[2] === 'archive') guide?.forget(decodeURIComponent(action[1]));
1247
+ if (action[2] === 'archive') health?.forget(decodeURIComponent(action[1]));
1248
+ /* Its accesses to accounts and its lists: kept by an archive (it may come back), gone with a delete (its
1249
+ owner's choice, 29-11). A member's new conversation never takes a name that still has some (door.mjs). */
1250
+ if (erased) { tethers?.forgetConversation?.(decodeURIComponent(action[1])); binders?.forgetConversation?.(decodeURIComponent(action[1])); }
1251
+ };
1252
+ const erased = action[2] === 'erase';
1253
+ try { await conversations[action[2]](decodeURIComponent(action[1])); } finally { if (action[2] !== 'sleep') { action[2] = 'archive'; forget(); } }
1167
1254
  return send(200, { ok: true }), true;
1168
1255
  } catch (error) {
1169
1256
  /* A git failure also says which (`kind`), and an fsck id the owner may waive (`offer`). */
@@ -139,6 +139,11 @@ export class Binders {
139
139
  if (level === 'read' || level === 'write') this.#keeper.store.grant(l.id, `${AGENT}${to}`, level, keeper);
140
140
  }
141
141
  }
142
+ /* A conversation archived or deleted (audit 29-11): its lists are no longer given to its name. */
143
+ forgetConversation(name) {
144
+ const keeper = { id: 'person:keeper', kind: 'person', name: 'keeper' };
145
+ for (const l of this.#keeper.store.lists(keeper)) if (l.grants?.[`${AGENT}${name}`] !== undefined) { try { this.#keeper.store.grant(l.id, `${AGENT}${name}`, null, keeper); } catch { /* gone meanwhile */ } }
146
+ }
142
147
  /* WHAT IT WAS GIVEN, for a whole export (carry.mjs): each list by its id, with its access; and the same given
143
148
  again, on an import, where the list exists here -> the ids not found. */
144
149
  grantsOf(name) {
package/server/bridge.mjs CHANGED
@@ -133,9 +133,17 @@ export function attachBridge(server, { spawn, onLeft = () => {}, onEnded = () =>
133
133
  still = () => ask() === name;
134
134
  } else if (url.pathname === PATH) {
135
135
  name = url.searchParams.get('c') ?? '';
136
- if (!isConversationName(name) || !originOk(request.headers) || gate(request.headers) === undefined) { socket.destroy(); return; }
137
- /* An administrator made a member, or an account disabled: its open terminals end too (#419). */
138
- still = () => gate(request.headers) !== undefined;
136
+ if (!isConversationName(name) || !originOk(request.headers)) { socket.destroy(); return; }
137
+ if (gate(request.headers) !== undefined) {
138
+ /* An administrator made a member, or an account disabled: its open terminals end too (#419). */
139
+ still = () => gate(request.headers) !== undefined;
140
+ } else {
141
+ /* A member on the common route (#431): the terminal of a conversation it was given it, only; ends when
142
+ that right goes. Its own door's path stays for its older page. */
143
+ const ask = () => memberName(request.headers, name) ?? '';
144
+ if (ask() !== name) { socket.destroy(); return; }
145
+ still = () => ask() === name;
146
+ }
139
147
  } else return;
140
148
  const cols = Number(url.searchParams.get('cols'));
141
149
  const rows = Number(url.searchParams.get('rows'));
@@ -143,9 +143,10 @@ export class Dockets {
143
143
  #heard(name, e) {
144
144
  if (e.type === 'acked') { try { void Promise.resolve(this.#acked(name, { event: e.event, ack: e.ack })).catch(() => {}); } catch { /* a hook that fails stops nothing */ } }
145
145
  if (e.type === 'acked' && e.ack.kind === 'done' && hidden(e.event)) { this.#line(name, { kind: 'docket-done', text: 'Handled: a sign-in for another conversation.', topic: 'Handled', brief: 'Sign-in' }); return; }
146
- if (e.type === 'acked' && e.ack.kind === 'done') this.#line(name, { kind: 'docket-done', text: `Handled: ${cut(e.event.text, 80)}${e.ack.note ? ` -- ${cut(e.ack.note, 120)}` : ''}`, topic: 'Handled', brief: e.event.text.slice(0, 60) });
146
+ /* In the reader's words (Parley's { k, v, t }, 29-11): its English `t` where a page has no such word. */
147
+ if (e.type === 'acked' && e.ack.kind === 'done') this.#line(name, { kind: 'docket-done', text: e.ack.note ? { k: 'line-docket-done-said', v: { text: cut(e.event.text, 80), said: cut(e.ack.note, 120) }, t: `Handled: ${cut(e.event.text, 80)} -- ${cut(e.ack.note, 120)}` } : { k: 'line-docket-done', v: { text: cut(e.event.text, 80) }, t: `Handled: ${cut(e.event.text, 80)}` }, topic: { k: 'line-topic-docket-done', t: 'Handled' }, brief: e.event.text.slice(0, 60) });
147
148
  if (e.type === 'acked' && e.ack.kind === 'failed') {
148
- this.#line(name, { kind: 'docket-failed', text: `Could not be handled: ${e.event.text} -- ${e.ack.note}`, tone: 'warn', topic: 'Not handled' });
149
+ this.#line(name, { kind: 'docket-failed', text: { k: 'line-docket-failed', v: { text: e.event.text, said: e.ack.note }, t: `Could not be handled: ${e.event.text} -- ${e.ack.note}` }, tone: 'warn', topic: { k: 'line-topic-docket-failed', t: 'Not handled' } });
149
150
  try { this.#alert({ title: `${name}: could not be handled`, body: `${e.event.text}: ${e.ack.note}`, url: `/?c=${name}` }); } catch { /* as said */ }
150
151
  }
151
152
  if (e.type === 'planned') this.#line(name, { kind: 'docket-reminder', text: `Reminder set by ${this.#setBy.has(e.plan.id) ? `API key "${this.#setBy.get(e.plan.id)}"` : 'the tool'}: ${e.plan.text} (${e.plan.cron ? `"${e.plan.cron}", next ` : ''}${new Date(e.plan.next ?? e.plan.due).toISOString().slice(0, 16).replace('T', ' ')} UTC)`, topic: 'Reminder' });
@@ -182,7 +183,7 @@ export class Dockets {
182
183
  const t = told[e.id];
183
184
  if (t && t.count >= TOLD_MAX && !t.said && now - t.at >= AGAIN_MS) {
184
185
  if (waiting.some((o) => told[o.id]?.said === true)) { t.said = 'grouped'; grouped += 1; continue; }
185
- this.#line(name, { kind: 'docket-unhandled', text: `Not handled, told ${t.count} times: ${e.text}`, tone: 'warn', topic: 'Not handled' });
186
+ this.#line(name, { kind: 'docket-unhandled', text: { k: 'line-docket-unhandled', v: { count: t.count, text: e.text }, t: `Not handled, told ${t.count} times: ${e.text}` }, tone: 'warn', topic: { k: 'line-topic-docket-unhandled', t: 'Not handled' } });
186
187
  t.said = true;
187
188
  }
188
189
  }
package/server/door.mjs CHANGED
@@ -48,6 +48,7 @@
48
48
  * conversation.)
49
49
  */
50
50
  import { Refusal, DISK_GB } from './conversations.mjs';
51
+ import { identifierFrom } from './names.mjs';
51
52
  import { readCookie, sessionCookie, cookieNameOf, isPairingId } from './devices.mjs';
52
53
  import { WORK_TAB } from './resources.mjs';
53
54
  import { list, download, importFile, page, PAGE_HEADERS, changeRoute, CHANGE_ROUTES, IMAGE_HEADERS, mailFile, mailPage } from './files.mjs';
@@ -168,32 +169,7 @@ export async function handleDoor(request, response, { devices, conversations, re
168
169
  return send(200, { quota: person.quota(), used: person.used(), diskMinGb: DISK_GB, tools: conversations.tools().map((t) => ({ id: t.id, label: t.label, memoryMb: t.memoryMb })) });
169
170
  }
170
171
  if (person && request.method === 'POST' && route === '/conversations') {
171
- const body = await readJson(request);
172
- if (!person.still()) throw new Refusal(403, 'This account may not use this page now.');
173
- const quota = person.quota();
174
- if (!(quota.mb > 0)) throw new Refusal(403, 'An administrator has not let you make conversations.');
175
- const tool = conversations.tools().find((t) => t.id === body.tool);
176
- if (!tool) throw new Refusal(400, 'Choose an AI.');
177
- const want = { mb: body.memoryMb === undefined ? tool.memoryMb : Number(body.memoryMb), diskGb: body.diskGb === undefined ? DISK_GB : Number(body.diskGb), cpus: body.cpus === undefined ? 1 : Number(body.cpus) };
178
- await conversations.admit?.({ title: body.title, tool: tool.id, memoryMb: want.mb });
179
- /* Counted after the wait, just before it is made: two at once never go past it together. */
180
- const used = person.used();
181
- const over = [['mb', 'memory', 'MB'], ['diskGb', 'disk', 'GB'], ['cpus', 'cores', '']].find(([k]) => quota[k] > 0 && used[k] + want[k] > quota[k]);
182
- if (over) { const [k, what, unit] = over; throw new Refusal(409, `Not enough ${what} left: ${quota[k] - used[k]}${unit ? ` ${unit}` : ''} of your ${quota[k]}${unit ? ` ${unit}` : ''}, this one needs ${want[k]}${unit ? ` ${unit}` : ''}.`); }
183
- const made = conversations.create({ title: String(body.title ?? '').trim() || undefined, tool: tool.id, memoryMb: want.mb, diskGb: want.diskGb, cpus: want.cpus, owner: person.email });
184
- person.own(made.name);
185
- /* Its chat on once it is built, as for one an administrator makes. */
186
- if (talk) {
187
- const until = Date.now() + 30 * 60_000;
188
- const on = async () => {
189
- const c = conversations.list().find((x) => x.name === made.name);
190
- if (!c || Date.now() > until) return;
191
- if (c.phase === 'ready') { try { await talk.set(made.name, true); } catch { /* turned on from its settings */ } return; }
192
- setTimeout(() => { void on(); }, 2000).unref?.();
193
- };
194
- void on();
195
- }
196
- return send(201, { name: made.name, title: made.title, tool: made.tool, memoryMb: made.memoryMb });
172
+ return send(201, await memberCreate({ conversations, talk, person, body: await readJson(request) }));
197
173
  }
198
174
  if (request.method === 'GET' && route === '/me') {
199
175
  /* `conversations`: all this pairing may use. `shared`: what it was given for itself. */
@@ -321,3 +297,43 @@ export async function handleDoor(request, response, { devices, conversations, re
321
297
  return send(500, { error: 'Something failed on the server.' });
322
298
  }
323
299
  }
300
+
301
+ /* A MEMBER MAKES A CONVERSATION OF ITS OWN (29-11), through its door or the application's route (#431): a
302
+ name and a tool, under the memory, disk and cores an administrator gave it for all of them together. It signs
303
+ in to its own AI account there; nothing else is set here (no folder, no key, no shared machine). */
304
+ export async function memberCreate({ conversations, talk, person, body, kept = () => false }) {
305
+ if (!person.still()) throw new Refusal(403, 'This account may not use this page now.');
306
+ const quota = person.quota();
307
+ if (!(quota.mb > 0)) throw new Refusal(403, 'An administrator has not let you make conversations.');
308
+ const tool = conversations.tools().find((t) => t.id === body.tool);
309
+ if (!tool) throw new Refusal(400, 'Choose an AI.');
310
+ const want = { mb: body.memoryMb === undefined ? tool.memoryMb : Number(body.memoryMb), diskGb: body.diskGb === undefined ? DISK_GB : Number(body.diskGb), cpus: body.cpus === undefined ? 1 : Number(body.cpus) };
311
+ /* Its own room said first (the server's memory after): what the member can act on. Counted again after
312
+ the wait, just before it is made: two at once never go past it together. */
313
+ const room = () => {
314
+ const used = person.used();
315
+ const over = [['mb', 'memory', 'MB'], ['diskGb', 'disk', 'GB'], ['cpus', 'cores', '']].find(([k]) => quota[k] > 0 && used[k] + want[k] > quota[k]);
316
+ if (over) { const [k, what, unit] = over; throw new Refusal(409, `Not enough ${what} left: ${quota[k] - used[k]}${unit ? ` ${unit}` : ''} of your ${quota[k]}${unit ? ` ${unit}` : ''}, this one needs ${want[k]}${unit ? ` ${unit}` : ''}.`); }
317
+ };
318
+ room();
319
+ await conversations.admit?.({ title: body.title, tool: tool.id, memoryMb: want.mb });
320
+ room();
321
+ /* Its name: never one that an archived conversation's accesses, lists or shares are still kept under -- it would
322
+ inherit them (audit 29-11): the next free one instead ("homework-2"). */
323
+ const title = String(body.title ?? '').trim() || undefined;
324
+ const name = identifierFrom(title ?? tool.label, (id) => conversations.list().some((c) => c.name === id) || kept(id));
325
+ const made = conversations.create({ name, title, tool: tool.id, memoryMb: want.mb, diskGb: want.diskGb, cpus: want.cpus, owner: person.email });
326
+ person.own(made.name);
327
+ /* Its chat on once it is built, as for one an administrator makes. */
328
+ if (talk) {
329
+ const until = Date.now() + 30 * 60_000;
330
+ const on = async () => {
331
+ const c = conversations.list().find((x) => x.name === made.name);
332
+ if (!c || Date.now() > until) return;
333
+ if (c.phase === 'ready') { try { await talk.set(made.name, true); } catch { /* turned on from its settings */ } return; }
334
+ setTimeout(() => { void on(); }, 2000).unref?.();
335
+ };
336
+ void on();
337
+ }
338
+ return { name: made.name, title: made.title, tool: made.tool, memoryMb: made.memoryMb };
339
+ }
package/server/files.mjs CHANGED
@@ -31,7 +31,8 @@ export function isFileName(name) {
31
31
 
32
32
  /* The real path of `relative` under `root`, or a refusal. */
33
33
  export async function inside(root, relative) {
34
- const base = await realpath(root);
34
+ /* A folder not made yet (a work folder before its first start): said as missing, not a failure (audit 29-11). */
35
+ const base = await realpath(root).catch(() => { throw new Refusal(404, 'No such file or folder.'); });
35
36
  let real;
36
37
  try { real = await realpath(join(base, String(relative ?? ''))); }
37
38
  catch { throw new Refusal(404, 'No such file or folder.'); }
package/server/main.mjs CHANGED
@@ -33,6 +33,7 @@ import { Resources, WORK_TAB } from './resources.mjs';
33
33
  import { download } from './files.mjs';
34
34
  import { makeGate, makeOriginCheck, readOperators } from './gate.mjs';
35
35
  import { People } from './people.mjs';
36
+ import { memberMay } from './access.mjs';
36
37
  import { Shortcuts } from './shortcuts.mjs';
37
38
  import { hearBox, Dictation } from './voice.mjs';
38
39
  import QRCode from 'qrcode';
@@ -280,13 +281,39 @@ function serve(port, conversations, resources, { gate = () => 'local', memberGat
280
281
  /* A MEMBER (people.mjs, #419): its own door, and nothing else of this server -- not a page, not an API,
281
282
  not a file. A page it held from before (an administrator then) is told, and goes to its own. */
282
283
  const member = memberGate(request.headers);
284
+ /* THE SAME ROUTES AS AN ADMINISTRATOR, FILTERED (#431, 29-11): a member reaches /api only through the one
285
+ table of access.mjs -- every other route refused -- and the handler is told who it is
286
+ (`request.member`) to answer with what it may see. */
287
+ if (member !== undefined && personOf && pathname.startsWith('/api/') && conversations) {
288
+ const person = personOf(member);
289
+ const owns = (name) => conversations.list().some((c) => c.name === name && c.owner === person.email);
290
+ const ownsAsset = (name) => resources?.get(name)?.owner === person.email;
291
+ const ownsKey = (name) => secrets?.ownerOf?.(name) === person.email;
292
+ const may = memberMay(request.method, pathname, (name) => person.rightsOn(person.key, name), owns, ownsAsset, ownsKey);
293
+ if (!may.ok) { response.writeHead(403, { ...HEADERS, 'x-clavarium-role': 'member', 'content-type': 'application/json; charset=utf-8' }).end(JSON.stringify({ error: may.why })); return; }
294
+ /* Every answer marked as a member's (audit 29-11): an administrators' page made stale by a change of role sees it. */
295
+ response.setHeader('x-clavarium-role', 'member');
296
+ request.member = { ...person, need: may.need, conversation: may.conversation, asset: may.asset, ownsAsset, ownsKey, still: () => memberGate(request.headers) === member && ((may.conversation === undefined && may.asset === undefined && may.key === undefined) || (may.need === 'key-owner' ? ownsKey(may.key) : false) || (may.need === 'owner' ? owns(may.conversation) : may.need === 'asset-owner' ? ownsAsset(may.asset) : person.rightsOn(person.key, may.conversation).includes(may.need))) };
297
+ request.stillAllowed = request.member.still;
298
+ /* Its desk: under its own name, as an administrator's is under theirs. */
299
+ if (pathname === '/api/desktop' && desks) { await handleDesktop(request, response, desks, member, originOk, HEADERS); return; }
300
+ if (await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, catalogue, rooms, machineList)) return;
301
+ response.writeHead(404, { ...HEADERS, 'content-type': 'application/json; charset=utf-8' }).end(JSON.stringify({ error: 'Not found.' }));
302
+ return;
303
+ }
283
304
  if (member !== undefined && door && personOf) {
284
305
  if (await handleDoor(request, response, { ...door, person: { ...personOf(member), still: () => memberGate(request.headers) === member } })) return;
285
306
  if (pathname === '/m/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
286
307
  if (pathname === '/m/' && (request.method === 'GET' || request.method === 'HEAD')) { response.writeHead(200, { ...HEADERS, 'content-type': 'text/html; charset=utf-8' }).end(memberPage()); return; }
287
308
  const file = MEMBER_FILES[pathname];
288
309
  if (file && (request.method === 'GET' || request.method === 'HEAD')) { await sendFile(response, file); return; }
289
- if (pathname === '/' && request.method === 'GET') { response.writeHead(302, { ...HEADERS, location: '/m/' }).end(); return; }
310
+ /* THE ADMINISTRATORS' PAGE, FOR A MEMBER (#431 step 1): the same page and files, told it is a member's;
311
+ its API filtered by the server (access.mjs). Its older page stays at /m/ for a while. */
312
+ if (pathname === '/' && (request.method === 'GET' || request.method === 'HEAD')) {
313
+ response.writeHead(200, { ...HEADERS, 'content-type': 'text/html; charset=utf-8' }).end(readFileSync(`${ROOT}web/index.html`, 'utf8').replace('<html lang="en">', '<html lang="en" data-role="member">'));
314
+ return;
315
+ }
316
+ if (FILES[pathname] && pathname !== '/' && (request.method === 'GET' || request.method === 'HEAD')) { await sendFile(response, FILES[pathname]); return; }
290
317
  response.writeHead(403, { ...HEADERS, 'x-clavarium-role': 'member', 'content-type': 'text/plain; charset=utf-8' }).end(REFUSED);
291
318
  return;
292
319
  }
@@ -167,7 +167,7 @@ export class Resources {
167
167
  setup.mjs): done in the same fresh folder, right after the clone, with
168
168
  hooks off. Not found there, the clone stays at the newest commit, and
169
169
  says so (`pinned: false`). */
170
- async create({ name, type = 'folder', from, via, pin }) {
170
+ async create({ name, type = 'folder', from, via, pin, owner }) {
171
171
  if (pin !== undefined && (typeof pin !== 'string' || !/^[0-9a-f]{7,40}$/.test(pin))) throw new Refusal(400, 'A pinned commit is written in hexadecimal, 7 to 40 characters.');
172
172
  if (!TYPES.includes(type)) throw new Refusal(400, 'A resource is a folder, a mailbox or a git repository.');
173
173
  const address = type === 'git' ? readAddress(from) : undefined;
@@ -202,7 +202,8 @@ export class Resources {
202
202
  pinned = r.code === 0;
203
203
  }
204
204
  if (credential) this.#access.remember(name, credential);
205
- const resource = { name, type, ...(origin ? { from: origin } : {}), createdAt: new Date().toISOString() };
205
+ /* `owner` (#431): a member's own folder -- only it (and the administrators) see and give it. */
206
+ const resource = { name, type, ...(origin ? { from: origin } : {}), ...(typeof owner === 'string' && owner ? { owner } : {}), createdAt: new Date().toISOString() };
206
207
  this.#store.put(resource);
207
208
  /* firstSeen: the host keys recorded by this very clone, to be shown once. */
208
209
  return { ...resource, attachments: {}, ...(type === 'git' && this.#access ? { via: this.#access.describe(name, origin) } : {}), ...(firstSeen.length ? { firstSeen } : {}), ...(pinned === undefined ? {} : { pinned }) };
@@ -102,18 +102,19 @@ export class Secrets {
102
102
  #expired(s) { return s.expiresAt ? Date.parse(s.expiresAt) <= this.#now().getTime() : (Boolean(s.expires) && daysTo(s.expires, this.#now()) <= 0); }
103
103
  #users(name) { return this.#grants.on(`secret:${name}`).map((g) => g.subject.slice('conversation:'.length)); }
104
104
  /* What is delivered to this conversation: handed, and not expired. */
105
- #given(conversation) { return this.#store.all().filter((s) => this.#handed(conversation, s.name) && !this.#expired(s)); }
105
+ #given(conversation) { return this.#store.all().filter((s) => !s.hostOnly && this.#handed(conversation, s.name) && !this.#expired(s)); }
106
106
 
107
107
  /* Names, where they are attached, the expiry. Never a value. `days`: whole
108
108
  days left (null without an expiry); `expired`: no longer delivered. A
109
109
  host-only secret (an account token the server holds) is left out -- it is
110
110
  never given to a machine, so the page never lists it; `held` includes it. */
111
111
  list({ held = false } = {}) {
112
- return this.#store.all().filter((s) => held || !s.hostOnly).map((s) => ({ name: s.name, conversations: this.#users(s.name), createdAt: s.createdAt,
112
+ return this.#store.all().filter((s) => held || !s.hostOnly).map((s) => ({ name: s.name, ...(s.owner ? { owner: s.owner } : {}), conversations: this.#users(s.name), createdAt: s.createdAt,
113
113
  expires: s.expires ?? null, days: s.expires ? daysTo(s.expires, this.#now()) : null, expired: this.#expired(s), ...(s.hostOnly ? { hostOnly: true } : {}),
114
114
  ...(s.ephemeral ? { ephemeral: true, expiresAt: s.expiresAt, expiresInMs: Math.max(0, Date.parse(s.expiresAt) - this.#now().getTime()) } : {}) }));
115
115
  }
116
116
  /* Past its expiry day: kept, not used (nor by dictation, voice.mjs). */
117
+ ownerOf(name) { return this.#store.get(name)?.owner; }
117
118
  isExpired(name) { const s = this.#store.get(name); return Boolean(s) && this.#expired(s); }
118
119
  /* Handed to it, expired or not (its Assets show both). */
119
120
  of(conversation) { return this.#store.all().filter((s) => this.#handed(conversation, s.name)).map((s) => s.name); }
@@ -129,15 +130,22 @@ export class Secrets {
129
130
 
130
131
  /* Creates, or replaces the value of, a secret. `expires`: a day, '' for
131
132
  none, left out to keep the one it had. */
132
- set({ name, value, expires, hostOnly }) {
133
+ set({ name, value, expires, hostOnly, owner }) {
133
134
  if (!isSecretName(name)) throw new Refusal(400, 'A secret is named like a variable: capitals, digits and underscores, starting with a letter.');
135
+ /* A member's own key (#431 step 2): a new name only -- never one that exists, whoever's it is (set would replace it). */
136
+ if (owner !== undefined && this.#store.get(name)) throw new Refusal(409, 'This name is taken: choose another one.');
137
+ /* Names the server writes by itself (account tokens, tools' keys) are never a member's (audit 29-11). */
138
+ if (owner !== undefined && /^(OAUTH_|MCP_|SECRET_|CLAVARIUM_)/.test(name)) throw new Refusal(409, 'This name is kept for the server: choose another one.');
134
139
  const sealed = this.#seal(value);
135
140
  const day = expires === undefined ? undefined : expiryOf(expires);
136
- const before = this.#store.get(name);
141
+ let before = this.#store.get(name);
142
+ /* A member's key written by an administrator or the server (audit 29-11): no longer the member's, and handed
143
+ to none of its conversations any more -- a value it did not set never reaches its machines. */
144
+ if (before?.owner && before.owner !== owner) { for (const g of this.#grants.on(`secret:${name}`)) this.#grants.take(g.subject, `secret:${name}`); const { owner: _gone, ...rest } = before; before = rest; }
137
145
  /* hostOnly: a secret the server uses on the agent's behalf (an account token the
138
146
  keeper reveals by name). It is never attached to a conversation, so never
139
147
  delivered to a machine; attach() refuses it, so this cannot be undone by hand. */
140
- this.#write({ ...before, name, sealed, createdAt: before?.createdAt ?? new Date().toISOString(), ...(hostOnly ? { hostOnly: true } : {}) }, day);
148
+ this.#write({ ...before, name, sealed, createdAt: before?.createdAt ?? new Date().toISOString(), ...(hostOnly ? { hostOnly: true } : {}), ...(typeof owner === 'string' && owner ? { owner } : {}) }, day);
141
149
  return { name };
142
150
  }
143
151
 
@@ -344,6 +344,13 @@ export class Tethers {
344
344
  }
345
345
  }
346
346
 
347
+ /* A conversation archived or deleted (audit 29-11): what it was given goes with it -- a new conversation of that
348
+ name (a member's own, say) never inherits its mail, calendar or other accesses. */
349
+ forgetConversation(name) {
350
+ const store = this.#keeper.store;
351
+ for (const t of store.targets()) if (t.grants?.[`${AGENT}${name}`]) { try { store.grant(t.id, `${AGENT}${name}`, null); } catch { /* gone meanwhile */ } }
352
+ }
353
+
347
354
  /* WHAT IT WAS GIVEN, for a whole export (carry.mjs): each target by its id, with its level and its allow rules;
348
355
  and the same given again, on an import, to those that exist here -> the ids not found. */
349
356
  grantsOf(name) {
package/web/app.js CHANGED
@@ -21,6 +21,9 @@
21
21
  /* A MEMBER (#419) has the page of a device: the same screens, what it was given only, at /m/ (member.js). */
22
22
  const MEMBER = document.documentElement.dataset.door === 'member';
23
23
  const DEVICE = document.documentElement.dataset.door === 'device' || MEMBER;
24
+ /* A MEMBER ON THE ADMINISTRATORS' PAGE (#431): the same page; the server filters what it answers
25
+ (access.mjs) and the administrators' parts are hidden, never a second set of screens. */
26
+ const MEMBER_PAGE = document.documentElement.dataset.role === 'member';
24
27
  /* THE KIT (kit.js): the pieces every screen shares -- the state's point, the conversation's card... */
25
28
  const KIT = window.clavariumKit;
26
29
  /* On a paired device, every request names the pairing it speaks for:
@@ -36,7 +39,7 @@
36
39
  /* What Parley mounted for the chat screen, and for which conversation. */
37
40
  let thread = null;
38
41
  let threadOf = '';
39
- const noTerminal = () => DEVICE && !deviceParts.terminal;
42
+ const noTerminal = () => (DEVICE || MEMBER_PAGE) && !deviceParts.terminal;
40
43
  /* A phone: what needs a wide screen (the Machine chapter's sizes) is not offered there. */
41
44
  const narrow = () => matchMedia('(max-width: 700px)').matches;
42
45
  /* THE LIST'S WIDTH, on this device: between LIST_MIN and LIST_MAX (never more than half the window). */
@@ -92,7 +95,9 @@
92
95
  let serverVersion = '';
93
96
  const leaving = (r) => {
94
97
  /* Made a member while this administrators' page was open (#419): its own page, at once. */
95
- if (!DEVICE && r.status === 403 && r.headers.get('x-clavarium-role') === 'member') { location.replace('/m/'); return true; }
98
+ /* Since #431 a member's answers on the common routes are marked too, refused or not: an administrators'
99
+ page that gets one goes to the member's page at once (audit 29-11). */
100
+ if (!DEVICE && !MEMBER_PAGE && r.headers.get('x-clavarium-role') === 'member') { location.replace('/'); return true; }
96
101
  const update = r.headers.get('x-clavarium-update') ?? '';
97
102
  if (update || r.headers.get('x-clavarium-down')) {
98
103
  const [kind, to] = update ? update.split(' ') : ['', ''];
@@ -600,6 +605,8 @@
600
605
  keeps it open (a person who wants it open sets it once). Open only when that choice was remembered. */
601
606
  let listFolded = true;
602
607
  try { listFolded = localStorage.getItem('clavarium-list') !== 'open'; } catch { /* a private window */ }
608
+ /* A member (#431): no desk to arrive on; its list is its home, open until it folds it. */
609
+ try { if (MEMBER_PAGE && localStorage.getItem('clavarium-list') === null) listFolded = false; } catch { if (MEMBER_PAGE) listFolded = false; }
603
610
  /* PINNED OPEN (the pin at the top of the list): it stays open, even when a conversation is opened.
604
611
  Folding it by hand takes the pin out. Kept on this device. */
605
612
  let listPinned = false;
@@ -2021,6 +2028,10 @@
2021
2028
  if (leaving(r)) return;
2022
2029
  if (!r.ok) throw new Error('no api');
2023
2030
  conversations = await r.json();
2031
+ /* A member (#431): the parts it was given of the one shown, as a device's (its chat, its terminal). */
2032
+ if (MEMBER_PAGE) deviceParts = conversations.find((x) => x.name === current)?.parts ?? { terminal: false, chat: null };
2033
+ /* Its own conversation: its settings shown (its name, its machine, its health), not one only given. */
2034
+ if (MEMBER_PAGE) document.documentElement.toggleAttribute('data-mine', conversations.find((x) => x.name === current)?.mine === true);
2024
2035
  /* The rooms, for the list (their rows, Recent). */
2025
2036
  try { await loadRooms(); } catch { /* not set up yet */ }
2026
2037
  await readDevices();
@@ -2362,7 +2373,7 @@
2362
2373
  const asReplies = (all) => (Array.isArray(all) ? all : []).filter((x) => x.starter !== true).map((x) => ({ label: x.label, text: x.text, send: x.enter === true }));
2363
2374
  /* A device has them when it may type into its terminal, or write in its chat. */
2364
2375
  async function loadReplies() {
2365
- if (DEVICE && !deviceParts.terminal && deviceParts.chat !== 'write') return [];
2376
+ if ((DEVICE || MEMBER_PAGE) && !deviceParts.terminal && deviceParts.chat !== 'write') return [];
2366
2377
  try { const r = await fetch(`${API}/shortcuts`); return r.ok ? asReplies(await r.json()) : []; } catch { return []; }
2367
2378
  }
2368
2379
  $('shortcut-cancel').addEventListener('click', () => { $('shortcut-new').hidden = true; });
@@ -3743,7 +3754,7 @@
3743
3754
  const windowFor = (choice) => { const [kind, n] = choice.split(':'); return kind === 'days' ? { days: Number(n) } : { messages: Number(n) }; };
3744
3755
  async function readTalk() {
3745
3756
  /* A device not given the chat does not ask for it: the server would refuse. */
3746
- if (!current || (DEVICE && deviceParts.chat === null)) { talk = { on: false, messages: [] }; talkOf = current; return talk; }
3757
+ if (!current || ((DEVICE || MEMBER_PAGE) && deviceParts.chat === null)) { talk = { on: false, messages: [] }; talkOf = current; return talk; }
3747
3758
  /* Whether it is on, nothing of the thread: asked every few seconds. */
3748
3759
  /* No answer (the network cut for a moment, the server restarting): what was known is kept. Taken
3749
3760
  for "off", the chat would be taken down and drawn again -- its box with it, and a tablet's keyboard. */
@@ -3851,9 +3862,9 @@
3851
3862
  a chip that opens the mail viewer, read when tapped, by whoever may read that mailbox (else the viewer says so). */
3852
3863
  schemes: { mail: { icon: 'mail', open: (ref, label) => { void openMailRef(ref, { label, of: name }); } } },
3853
3864
  /* A reaction to one of its messages: wherever the chat may be written in. */
3854
- ...(!DEVICE || deviceParts.chat === 'write' ? { react: (to, reaction) => post(talkPath(name, '/react'), { to, reaction }) } : {}),
3865
+ ...(!MEMBER_PAGE && (!DEVICE || deviceParts.chat === 'write') ? { react: (to, reaction) => post(talkPath(name, '/react'), { to, reaction }) } : {}),
3855
3866
  /* A message pinned at the top of the chat (5 at most, either side): wherever the chat may be written in. */
3856
- ...(!DEVICE || deviceParts.chat === 'write' ? { pin: (to, on) => post(talkPath(name, '/pin'), { to, on }) } : {}),
3867
+ ...(!MEMBER_PAGE && (!DEVICE || deviceParts.chat === 'write') ? { pin: (to, on) => post(talkPath(name, '/pin'), { to, on }) } : {}),
3857
3868
  /* A message attached to a card (#180), from its menu: its id, as the card opens it again. */
3858
3869
  ...(!DEVICE ? { card: (m) => attachToCard({ kind: 'message', ref: m.id, title: String(m.short || m.text || '').replace(/\s+/g, ' ').trim().slice(0, 80) }) } : {}),
3859
3870
  /* The buttons of a line of the machine: what this screen may do. */
@@ -3861,7 +3872,7 @@
3861
3872
  /* What it opens over the thread (a picture, its media, a search...) is a step of this page's: one Back closes it. */
3862
3873
  back: { open: (name, close) => nav.over(`chat-${name}`, () => close(), { stack: true }), closed: (step) => { if (step) nav.drop(step); } },
3863
3874
  /* Files attached to a message: wherever the chat may be written in. */
3864
- ...(!DEVICE || deviceParts.chat === 'write' ? { attach: { upload: (file) => attachToChat(name, file) } } : {}),
3875
+ ...((!DEVICE && !MEMBER_PAGE) || deviceParts.chat === 'write' ? { attach: { upload: (file) => attachToChat(name, file) } } : {}),
3865
3876
  /* Its terminal, when this device was given it. */
3866
3877
  /* A file the tool showed opens in the window when it is in its work folder or an attached folder ("work:report.html"). */
3867
3878
  open: (file) => { if (!file.open) return; const at = file.open.indexOf(':'); const tab = file.open.slice(0, at); const inner = file.open.slice(at + 1); void openFromChat(tab, inner); },
@@ -6264,7 +6275,8 @@
6264
6275
  const model = own ? null : KIT.accessModel({ key: KIT.rightsKey(chosen), holders: accessHolders(chosen), from: from ? `conversation:${from}` : '' });
6265
6276
  if (model) {
6266
6277
  /* Given to a device: from here too (the map shows who has it). */
6267
- const share = !t && ['folder', 'git', 'mailbox'].includes(chosen.kind) ? el('button', 'as-link', uiSaid('set-acc-share', 'Share with a device...')) : null;
6278
+ /* Sharing with a paired device is the administrators' (the older way, #431): not offered to a member. */
6279
+ const share = !t && !MEMBER_PAGE && ['folder', 'git', 'mailbox'].includes(chosen.kind) ? el('button', 'as-link', uiSaid('set-acc-share', 'Share with a device...')) : null;
6268
6280
  if (share) { share.type = 'button'; share.addEventListener('click', () => { void openCompose([[chosen.key, 'r']]); }); }
6269
6281
  parts.push(KIT.AccessList(model, { key: KIT.rightsKey(chosen), kind: chosen.kind, name: chosen.name, onChange: (row, level, stored) => setAccess(chosen, row, level, stored), actions: [share] }));
6270
6282
  }
@@ -8679,6 +8691,13 @@
8679
8691
  Chat & voice, Automatic, Diagnostics, Advanced: the same names in the same order on every settings page -- one
8680
8692
  shown at a time. The one last shown is kept on this device. A tab whose group has nothing to show is hidden,
8681
8693
  the order of the others unchanged. While a search is typed, every group is searched and shown (CSS). */
8694
+ /* A MEMBER'S SETTINGS (#431): only what concerns it -- this screen of its own (theme, text, sounds); the
8695
+ server's chapters are the administrators' (and refused to it by the server anyway). */
8696
+ const MEMBER_CHAPTERS = new Set(['settings-ch-screen']);
8697
+ if (MEMBER_PAGE) for (const d of document.querySelectorAll('#settings details.chapter')) if (!MEMBER_CHAPTERS.has(d.id)) d.hidden = true;
8698
+ /* Of its own conversation's settings: its name and tool, its machine, its health. */
8699
+ const MEMBER_PANEL = new Set(['chapter-general', 'chapter-machine', 'chapter-health']);
8700
+ if (MEMBER_PAGE) for (const d of document.querySelectorAll('#panel details.chapter')) if (!MEMBER_PANEL.has(d.id)) d.hidden = true;
8682
8701
  function settingsTabs(sheet) {
8683
8702
  const nav = sheet?.querySelector('.settings-tabs'); if (!nav) return;
8684
8703
  const buttons = [...nav.querySelectorAll('button[data-group]')];
@@ -8695,7 +8714,9 @@
8695
8714
  /* Hidden: a tab whose chapters are all hidden (Usage, Administrators on this machine alone...). */
8696
8715
  const refresh = () => {
8697
8716
  if (sheet.dataset.searching === 'on') return;
8698
- for (const b of buttons) { const g = groupOf(b.dataset.group); b.hidden = !g || ![...g.querySelectorAll('details.chapter')].some((d) => !d.hidden); }
8717
+ /* Written only when it changes: setting `hidden` again to the same value is a mutation too, and this runs
8718
+ from the observer below -- a loop that froze a member's page (29-11). */
8719
+ for (const b of buttons) { const g = groupOf(b.dataset.group); const h = !g || ![...g.querySelectorAll('details.chapter')].some((d) => !d.hidden); if (b.hidden !== h) b.hidden = h; }
8699
8720
  if (buttons.find((b) => b.dataset.group === sheet.dataset.tab)?.hidden) show(buttons.find((b) => !b.hidden)?.dataset.group ?? buttons[0].dataset.group, { keep: false });
8700
8721
  };
8701
8722
  for (const b of buttons) b.addEventListener('click', () => { show(b.dataset.group); b.focus(); });
@@ -8907,7 +8928,7 @@
8907
8928
  void paintChatWindow().catch(() => {});
8908
8929
  const [platform, saved] = await Promise.all([fetch(`${API}/platform`).then((r) => r.json()).catch(() => ({})), fetch(`${API}/shortcuts`).then((r) => r.json()).catch(() => [])]);
8909
8930
  const list = $('settings-shortcuts'); list.replaceChildren();
8910
- for (const shortcut of saved) {
8931
+ for (const shortcut of Array.isArray(saved) ? saved : []) {
8911
8932
  const row = document.createElement('div'); row.className = 'list-item';
8912
8933
  const label = document.createElement('div'); label.className = 'set-what';
8913
8934
  const name = document.createElement('b'); name.textContent = shortcut.label;
@@ -12625,7 +12646,7 @@
12625
12646
  head.append(details, all);
12626
12647
  view.append(head);
12627
12648
  /* Reply: never sent from here -- the AI is asked in the chat, and its answer comes back as a request to approve. */
12628
- if (ref && (ref.of || DEVICE) && (!DEVICE || deviceParts.chat === 'write')) {
12649
+ if (ref && (ref.of || DEVICE) && ((!DEVICE && !MEMBER_PAGE) || deviceParts.chat === 'write')) {
12629
12650
  const acts = el('div', 'mail-acts');
12630
12651
  const reply = el('button', 'mail-reply', uiSaid('set-mail-reply', 'Reply…')); reply.type = 'button';
12631
12652
  reply.addEventListener('click', () => { void replyToMail({ ref: ref.got?.ref || ref.ref, of: ref.of }); });
@@ -13049,7 +13070,7 @@
13049
13070
  let basket = new Map(); /* asset -> rights */
13050
13071
  let shareTarget = ''; /* '' : a new device; otherwise the device being changed */
13051
13072
  let shareKind = ''; let catalog = []; let codeTimers = [];
13052
- const readDevices = async () => { sharedDevices = DEVICE ? [] : await (await fetch(`${API}/devices`)).json().catch(() => []); return sharedDevices; };
13073
+ const readDevices = async () => { sharedDevices = DEVICE || MEMBER_PAGE ? [] : await (await fetch(`${API}/devices`)).json().catch(() => []); if (!Array.isArray(sharedDevices)) sharedDevices = []; return sharedDevices; };
13053
13074
  const devicesWith = (asset) => sharedDevices.filter((d) => d.grants.some((g) => g.asset === asset));
13054
13075
  const face = (which) => {
13055
13076
  for (const id of ['share-compose', 'share-code', 'share-manage']) $(id).hidden = id !== `share-${which}`;
@@ -14063,7 +14084,7 @@
14063
14084
  if (home && new URLSearchParams(location.search).has('open')) await followAddress();
14064
14085
  /* THE FIRST START (Features, features.js): nothing made yet, the welcome not passed -- the home
14065
14086
  page opens on it, once; passed ("Skip", or a conversation made), it never comes back by itself. */
14066
- else if (home && !DEVICE && !current && conversations.length === 0) {
14087
+ else if (home && !DEVICE && !MEMBER_PAGE && !current && conversations.length === 0) {
14067
14088
  const d = await features?.refresh().catch(() => null);
14068
14089
  if (d?.welcome && place === 'conversations' && !conversations.length) openDeck(false);
14069
14090
  }
package/web/style.css CHANGED
@@ -3469,3 +3469,15 @@ span.tile-spark { display: block; height: 22px; }
3469
3469
  .op-room>span{flex:1 1 100%;font-size:.9em;color:var(--ink2)}
3470
3470
  .op-room select{flex:0 1 auto;min-width:0}
3471
3471
  .op-role{margin-right:6px}
3472
+ /* A MEMBER ON THE ADMINISTRATORS' PAGE (#431 step 1): the places that are the administrators' are not shown;
3473
+ the server refuses them anyway (access.mjs). Its conversations, their chat and terminal are its page. */
3474
+ html[data-role="member"] #nav-access, html[data-role="member"] #view-assets, html[data-role="member"] #view-lists { display: none !important; }
3475
+ /* Its own conversation (#431): a name, a tool, a size within its room -- no folder of the administrators', no
3476
+ shared machine (the server sets neither for a member). */
3477
+ html[data-role="member"] .set-row:has(#newconv-group), html[data-role="member"] #newconv-where-card { display: none !important; }
3478
+ html[data-role="member"] #settings details.chapter:not(#settings-ch-screen) { display: none !important; }
3479
+ html[data-role="member"] #settings-hand { display: none !important; }
3480
+ html[data-role="member"]:not([data-mine]) #folders { display: none !important; }
3481
+ html[data-role="member"] #panel details.chapter:not(#chapter-general):not(#chapter-machine):not(#chapter-health) { display: none !important; }
3482
+ html[data-role="member"] #assets-view { display: none !important; }
3483
+ html[data-role="member"] #assets .as-group-add, html[data-role="member"] #assets-detail .kit-groupchip { display: none !important; }