clavarium 0.2.67-next.1 → 0.2.68-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.
package/deploy/install.sh CHANGED
@@ -605,7 +605,7 @@ $BIND
605
605
  @api path /api/* /c/api/*
606
606
  handle @api {
607
607
  header Content-Type "application/json; charset=utf-8"
608
- respond "{\"error\":\"Clavarium is being updated or restarted: it comes back by itself in a moment.\",\"down\":true}" 503
608
+ respond "{\"error\":\"Clavarium did not answer just now -- it may be busy or restarting. It comes back by itself; try again in a moment.\",\"down\":true}" 503
609
609
  }
610
610
  handle {
611
611
  root * /var/lib/clavarium/maintenance
@@ -140,7 +140,7 @@ export const MAINTENANCE_BLOCK = [
140
140
  '\t\t\t\t@api path /api/* /c/api/*',
141
141
  '\t\t\t\thandle @api {',
142
142
  '\t\t\t\t\theader Content-Type "application/json; charset=utf-8"',
143
- '\t\t\t\t\trespond "{\\"error\\":\\"Clavarium is being updated or restarted: it comes back by itself in a moment.\\",\\"down\\":true}" 503',
143
+ '\t\t\t\t\trespond "{\\"error\\":\\"Clavarium did not answer just now -- it may be busy or restarting. It comes back by itself; try again in a moment.\\",\\"down\\":true}" 503',
144
144
  '\t\t\t\t}',
145
145
  '\t\t\t\thandle {',
146
146
  `\t\t\t\t\troot * ${MAINTENANCE_DIR}`,
@@ -1,20 +1,20 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.67-next.1",
3
+ "version": "0.2.68-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.67-next.1",
9
+ "version": "0.2.68-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.8-next.1",
15
15
  "clavarium-docket": "0.1.1",
16
- "clavarium-parley": "0.17.9-next.1",
17
- "clavarium-tether": "0.1.0-next.10",
16
+ "clavarium-parley": "0.17.11-next.1",
17
+ "clavarium-tether": "0.1.0-next.20",
18
18
  "mermaid": "11.17.2",
19
19
  "node-pty": "^1.1.0",
20
20
  "pdfjs-dist": "6.4.299",
@@ -742,9 +742,9 @@
742
742
  }
743
743
  },
744
744
  "node_modules/clavarium-parley": {
745
- "version": "0.17.9-next.1",
746
- "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.9-next.1.tgz",
747
- "integrity": "sha512-pKwFQnq/6JO2nA37u9RNCO6ddgCUvpqmmmqRPQMa5GGT1nL0dFGDs1hY+Wed3TqKYRKxLmCgUWgts0aQBYihqw==",
745
+ "version": "0.17.11-next.1",
746
+ "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.11-next.1.tgz",
747
+ "integrity": "sha512-IHGgFbDzHjrNVRcSR/KudWPUfvKxCeu03bNXE8+84lLMGHL7LyaiIg+iuw/cXMq4etz5BVXddVA/DGDoTUFO3A==",
748
748
  "license": "MIT",
749
749
  "bin": {
750
750
  "parley": "bin/parley.mjs",
@@ -755,9 +755,9 @@
755
755
  }
756
756
  },
757
757
  "node_modules/clavarium-tether": {
758
- "version": "0.1.0-next.10",
759
- "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.10.tgz",
760
- "integrity": "sha512-MIuKFhnAZCBNCWYd5ZjlEZo66ZCt+uSfiq5vc6Au2Dwg126W6OIVZ8MdZLsiGCNiW6KstFeycN7nasfLqlxBRA==",
758
+ "version": "0.1.0-next.20",
759
+ "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.20.tgz",
760
+ "integrity": "sha512-XeUKJCQU95ScJwY76l6jNZsl8eQZFNMpuTLypW+oMhCtZvQXUTG2E8Zid3X6L1z3iFKCBfr1sJTX51B8TCaEjw==",
761
761
  "license": "MIT",
762
762
  "bin": {
763
763
  "tether": "bin/cli.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.67-next.1",
3
+ "version": "0.2.68-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.",
@@ -46,8 +46,8 @@
46
46
  "@xterm/xterm": "^6.0.0",
47
47
  "clavarium-binder": "0.1.8-next.1",
48
48
  "clavarium-docket": "0.1.1",
49
- "clavarium-parley": "0.17.9-next.1",
50
- "clavarium-tether": "0.1.0-next.10",
49
+ "clavarium-parley": "0.17.11-next.1",
50
+ "clavarium-tether": "0.1.0-next.20",
51
51
  "mermaid": "11.17.2",
52
52
  "node-pty": "^1.1.0",
53
53
  "pdfjs-dist": "6.4.299",
@@ -10,12 +10,11 @@
10
10
  * instead the keeper reveals it to the connector alone, host-side, and acts on
11
11
  * the agent's behalf within the level and rules the person set.
12
12
  *
13
- * ONE ACCOUNT, ONE TOKEN, SEVERAL TARGETS. A Google consent for mail+calendar+
14
- * contacts yields a single refresh token; this makes one host-only secret and a
15
- * Tether target per kind, each naming that secret. Microsoft's Thunderbird client
16
- * carries only the mail scope here, so a Microsoft consent makes the mail target
17
- * alone (calendar and files over Graph need a deployment's own OAuth app, added
18
- * later as config.clientId + an own client secret).
13
+ * ONE ACCOUNT, ONE TOKEN, SEVERAL TARGETS. A consent for mail+calendar+contacts
14
+ * yields a single refresh token; this makes one host-only secret and a Tether
15
+ * target per kind, each naming that secret. Both providers borrow Thunderbird's
16
+ * own open-source desktop client, verified for all three: Google over IMAP +
17
+ * CalDAV/CardDAV, Microsoft over Microsoft Graph (mail, calendar and contacts).
19
18
  *
20
19
  * A CREATED TARGET IS GIVEN TO NO ONE. The person grants it per conversation, at
21
20
  * its own level, from the page (Assets > Access) -- like git: one mailbox, many
@@ -23,14 +22,16 @@
23
22
  */
24
23
  import { Refusal } from './conversations.mjs';
25
24
  import { createHash } from 'node:crypto';
26
- import { consentUrl, exchangeCode, extractCode, thunderbird, scopeFor, pkcePair, newState, PROVIDERS } from './oauth.mjs';
25
+ import { consentUrl, exchangeCode, extractCode, thunderbird, scopeFor, kindsGranted, refreshAccess, pkcePair, newState, PROVIDERS } from './oauth.mjs';
27
26
 
28
27
  /* The loopback the provider sends the code back to; nothing listens there. The
29
28
  person's browser lands on a page that will not load, and they copy the whole
30
- address -- which carries the code -- back into Clavarium. Desktop OAuth clients
31
- accept any 127.0.0.1 port, and the same address trades the code, so it only has
32
- to stay constant. (Shared, on purpose, with the older file-copy mailbox.) */
29
+ address -- which carries the code -- back into Clavarium. The same address
30
+ trades the code, so it must match what the borrowed client registered. Both
31
+ borrowed Thunderbird clients (one for Google, one for Microsoft) registered the
32
+ loopback on any 127.0.0.1 port, so one address serves both. */
33
33
  const REDIRECT = 'http://127.0.0.1:47813/';
34
+ const redirectFor = () => REDIRECT;
34
35
  const PENDING_MS = 10 * 60_000;
35
36
  const PENDING_MAX = 20;
36
37
 
@@ -38,11 +39,11 @@ const PENDING_MAX = 20;
38
39
  Tether kind each becomes, and whether the target needs the email address. */
39
40
  const KIND = {
40
41
  mail: { connector: 'mail', kind: 'mail', title: 'Mail', needsUser: true },
41
- calendar: { connector: 'calendar', kind: 'calendar', title: 'Agenda', needsUser: false },
42
+ calendar: { connector: 'calendar', kind: 'calendar', title: 'Agenda', needsUser: true },
42
43
  contacts: { connector: 'contacts', kind: 'contacts', title: 'Contacts', needsUser: true },
43
44
  };
44
45
  /* What each provider's built-in (Thunderbird) client grants a refresh token for. */
45
- const SUPPORTED = { google: ['mail', 'calendar', 'contacts'], microsoft: ['mail'] };
46
+ const SUPPORTED = { google: ['mail', 'calendar', 'contacts'], microsoft: ['mail', 'calendar', 'contacts'] };
46
47
 
47
48
  const emailOk = (s) => /^[^\s@]{1,64}@[^\s@]{1,190}\.[^\s@]{2,}$/.test(s);
48
49
  /* A deterministic, valid secret name for an account's token: a short slug of the
@@ -85,7 +86,7 @@ export class Accounts {
85
86
  const { clientId } = thunderbird(prov);
86
87
  const state = newState();
87
88
  const { verifier, challenge } = pkcePair();
88
- const url = consentUrl(prov, { clientId, redirectUri: REDIRECT, scope: scopeFor(prov, chosen), state, codeChallenge: challenge, loginHint: address });
89
+ const url = consentUrl(prov, { clientId, redirectUri: redirectFor(prov), scope: scopeFor(prov, chosen), state, codeChallenge: challenge, loginHint: address });
89
90
  this.#pending.set(state, { provider: prov, user: address, kinds: chosen, verifier, at: Date.now() });
90
91
  return { url };
91
92
  }
@@ -102,19 +103,32 @@ export class Accounts {
102
103
  let code;
103
104
  try { code = extractCode(redirected, { state }); } catch (e) { throw new Refusal(400, e.message); }
104
105
  const { clientId, clientSecret } = thunderbird(p.provider);
105
- let refreshToken;
106
- try { ({ refreshToken } = await exchangeCode(p.provider, { clientId, clientSecret, redirectUri: REDIRECT, code, codeVerifier: p.verifier, fetch: this.#fetch })); }
106
+ let refreshToken, grantedScope;
107
+ try { ({ refreshToken, scope: grantedScope } = await exchangeCode(p.provider, { clientId, clientSecret, redirectUri: redirectFor(p.provider), code, codeVerifier: p.verifier, fetch: this.#fetch })); }
107
108
  catch (e) { throw new Refusal(502, `The connection could not be completed: ${e.message}`); }
108
109
  if (!refreshToken) throw new Refusal(502, 'The account returned no lasting token; allow offline access and try again.');
110
+ /* What was actually allowed. A provider may grant fewer kinds than asked
111
+ (the person unticks one); the token's scope says so, so we make a target
112
+ only for a kind that was really granted, and tell the caller which were
113
+ denied -- no guessing. If the scope is unreadable (matched nothing) we
114
+ trust what was asked, as before. */
115
+ const matched = kindsGranted(p.provider, grantedScope);
116
+ const useScope = matched.length > 0;
117
+ const authorized = useScope ? p.kinds.filter((k) => matched.includes(k)) : p.kinds;
118
+ const denied = useScope ? p.kinds.filter((k) => !matched.includes(k)) : [];
109
119
  /* The token is kept host-only: it can never be attached to a conversation,
110
120
  so it is never delivered to a machine -- the keeper reveals it by name. */
111
121
  const name = secretName(p.provider, p.user);
112
122
  this.#secrets.set({ name, value: refreshToken, hostOnly: true });
113
123
  const label = PROVIDERS[p.provider].label;
114
124
  const made = [];
115
- for (const k of p.kinds) {
125
+ for (const k of authorized) {
116
126
  const spec = KIND[k];
117
- const config = { provider: p.provider };
127
+ /* Pin the client that minted the token onto the target, so the keeper
128
+ refreshes with the same one -- a refresh token is bound to its client,
129
+ and this keeps a target working even if the built-in default later
130
+ moves (the connector prefers config.clientId over its own default). */
131
+ const config = { provider: p.provider, clientId, authorizedKinds: authorized };
118
132
  if (spec.needsUser) config.user = p.user;
119
133
  const target = this.#targets.put({
120
134
  id: targetId(k, p.provider, p.user),
@@ -123,7 +137,33 @@ export class Accounts {
123
137
  });
124
138
  made.push({ id: target?.id ?? targetId(k, p.provider, p.user), title: target?.title, kind: spec.kind });
125
139
  }
126
- return { provider: p.provider, user: p.user, targets: made };
140
+ return { provider: p.provider, user: p.user, targets: made, authorized, denied };
141
+ }
142
+
143
+ /* Check, live, what a connected account is really authorized for right now --
144
+ not only at connection. A refresh host-side (the token never leaves the
145
+ server) reads the token's current scopes, so the page can say "mail yes,
146
+ calendar no" at any time and reflect a permission removed since. Records the
147
+ result on every target of the account, so it shows without another check. */
148
+ async verify({ id } = {}) {
149
+ const all = this.#targets.all?.() ?? [];
150
+ const target = all.find((t) => t.id === id);
151
+ if (!target) throw new Refusal(404, 'No such connexion.');
152
+ const provider = target.config?.provider;
153
+ if (!PROVIDERS[provider]) throw new Refusal(400, 'This connexion is not an account.');
154
+ const secretRef = target.secrets?.refresh;
155
+ const refreshToken = secretRef && this.#secrets.reveal(secretRef);
156
+ if (!refreshToken) throw new Refusal(404, 'The account token is gone; connect it again.');
157
+ const def = thunderbird(provider);
158
+ const clientId = target.config?.clientId || def.clientId;
159
+ let scope, fresh;
160
+ try { ({ scope, refreshToken: fresh } = await refreshAccess(provider, { clientId, clientSecret: def.clientSecret, refreshToken, fetch: this.#fetch })); }
161
+ catch (e) { throw new Refusal(502, `The account could not be checked: ${e.message}`); }
162
+ /* Keep the token current if the provider rotated it on the refresh. */
163
+ if (fresh && fresh !== refreshToken) this.#secrets.set({ name: secretRef, value: fresh, hostOnly: true });
164
+ const authorized = kindsGranted(provider, scope);
165
+ for (const t of all.filter((x) => x.secrets?.refresh === secretRef)) this.#targets.put({ ...t, config: { ...t.config, authorizedKinds: authorized } });
166
+ return { id, provider, all: SUPPORTED[provider], authorized };
127
167
  }
128
168
 
129
169
  #sweep() { const now = Date.now(); for (const [k, v] of this.#pending) if (now - v.at > PENDING_MS) this.#pending.delete(k); }
package/server/api.mjs CHANGED
@@ -78,6 +78,11 @@
78
78
  * POST /api/secrets/<NAME>/replace {value?, expires?}: in place, its name and grants kept; '' removes the expiry
79
79
  * POST /api/secrets/<NAME>/remove
80
80
  * POST /api/secrets/<NAME>/rename {name}: its value and where it is handed go with it
81
+ * GET /api/asset-groups the owner's asset groups: [{id, label, members}]
82
+ * POST /api/asset-groups {label}: a new, empty group
83
+ * POST /api/asset-groups/place {asset, group}: put an asset in a group (group null to take it out)
84
+ * POST /api/asset-groups/<id>/rename {label}
85
+ * POST /api/asset-groups/<id>/remove
81
86
  * GET /api/conversations/<name>/health-react POST the same {on?, message?, command?}: what it does when its machine is short
82
87
  * GET /api/machines/places GET /api/machines/moving POST /api/machines/move {to}: all the machines to another disk
83
88
  * POST /api/machines/forget-old: the copy a move left behind, removed
@@ -146,7 +151,7 @@ function readBody(request, max = BODY_MAX) {
146
151
  }
147
152
 
148
153
  /* Returns true when the request was an API request (answered here). */
149
- export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, 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) {
154
+ export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, 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) {
150
155
  const { pathname } = new URL(request.url ?? '/', 'http://local');
151
156
  if (!pathname.startsWith('/api/')) return false;
152
157
  let send = (status, body) => {
@@ -240,6 +245,10 @@ export async function handleApi(request, response, conversations, headers, resou
240
245
  if (pathname === '/api/resources' && resources) return send(200, resources.list()), true;
241
246
  if (pathname === '/api/shortcuts' && shortcuts) return send(200, shortcuts.list()), true;
242
247
  if (pathname === '/api/secrets' && secrets) return send(200, secrets.list()), true;
248
+ /* The owner's asset groups (groups.mjs): a label and the asset ids each
249
+ holds. Distinct from /api/groups/* above, which are the conversation
250
+ list's folders. */
251
+ if (pathname === '/api/asset-groups' && groups) return send(200, groups.list()), true;
243
252
  if (pathname === '/api/mailboxes' && mailboxes) return send(200, mailboxes.list()), true;
244
253
  /* Which providers and kinds an account can be connected for here. */
245
254
  if (pathname === '/api/accounts' && accounts) return send(200, { supported: accounts.supported() }), true;
@@ -421,6 +430,7 @@ export async function handleApi(request, response, conversations, headers, resou
421
430
  kept host-only, a Tether target made): see accounts.mjs. */
422
431
  if (pathname === '/api/accounts/consent' && accounts) return send(200, accounts.consent(body)), true;
423
432
  if (pathname === '/api/accounts/connect' && accounts) { const made = await accounts.connect(body); return send(201, made), true; }
433
+ if (pathname === '/api/accounts/verify' && accounts) { const r = await accounts.verify(body); return send(200, r), true; }
424
434
  /* Assets > Access: the owner sets a conversation's level and rules on a
425
435
  target, decides a call that waited, or removes a target. Each is an op the
426
436
  keeper runs as the owner (person), never as an agent. */
@@ -428,6 +438,14 @@ export async function handleApi(request, response, conversations, headers, resou
428
438
  if (tetherOp && tethers) { const r = await tethers.act(tetherOp[1], body, ''); if (!r.ok) throw new Refusal(400, r.text); return send(200, r.data ?? { ok: true }), true; }
429
439
  if (pathname === '/api/shortcuts' && shortcuts) return send(201, shortcuts.add(body)), true;
430
440
  if (pathname === '/api/secrets' && secrets) { const made = secrets.set(body); setup?.secretAdded(made.name); return send(201, made), true; }
441
+ /* Asset groups (groups.mjs): a folder-style tidy-up, not a right. */
442
+ if (pathname === '/api/asset-groups' && groups) return send(201, groups.create(body.label)), true;
443
+ if (pathname === '/api/asset-groups/place' && groups) return send(200, groups.place(body.asset, body.group ?? null)), true;
444
+ const groupOp = /^\/api\/asset-groups\/([0-9a-f]{12})\/(rename|remove)$/.exec(pathname);
445
+ if (groupOp && groups) {
446
+ if (groupOp[2] === 'rename') return send(200, groups.rename(groupOp[1], body.label)), true;
447
+ return groups.remove(groupOp[1]), send(200, { ok: true }), true;
448
+ }
431
449
  const reactSet = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
432
450
  if (reactSet && reacting) { const n = decodeURIComponent(reactSet[1]); if (!conversations.list().some((c) => c.name === n)) throw new Refusal(404, 'No such conversation.'); return send(200, reacting.set(n, body)), true; }
433
451
  if (pathname === '/api/machines/move' && machinesMove) return send(202, await machinesMove.move(String(body.to ?? ''))), true;
@@ -211,9 +211,15 @@ const seeCommits = (name, head, base, n) => (short(head) && short(base) && Numbe
211
211
  long a finished run is kept for the request that asks again just after. */
212
212
  export const CHECK_WAIT_MS = 20_000;
213
213
  export const CHECK_KEEP_MS = 60_000;
214
+ /* A send (the push to the remote) runs in the background, like a check: one
215
+ request waits at most this long, then hears { status: 'sending' } and asks
216
+ again (join), so a long push never outruns the proxy. The push itself is
217
+ already bounded (PUSH_MS); a finished send is kept this long for the asking. */
218
+ export const SENDING_WAIT_MS = 20_000;
219
+ export const SENDING_KEEP_MS = 60_000;
214
220
 
215
221
  export class GitKeeper {
216
- #store; #review; #resources; #checks; #alerts; #now; #tellAgent; #thread; #last; #held = new Map(); #results = new Map(); #running = new Set(); #telling = new Map(); #inFlight = new Map();
222
+ #store; #review; #resources; #checks; #alerts; #now; #tellAgent; #thread; #last; #held = new Map(); #results = new Map(); #running = new Set(); #telling = new Map(); #inFlight = new Map(); #sending = new Map();
217
223
 
218
224
  /* `review`: GitReview (reads, the reference, Send). `checks`: GitChecks.
219
225
  `alerts`: what tells the owner's phone. `tellAgent(repository, line,
@@ -556,7 +562,30 @@ export class GitKeeper {
556
562
 
557
563
  /* Send, from the page: as GitReview.push, and refused when the owner
558
564
  requires passing checks and none passed for this commit and branch. */
565
+ /* The push runs in the background; the request waits at most SENDING_WAIT_MS,
566
+ then returns { status: 'sending' } and the page asks again with `join: true`
567
+ until it ends -- so a slow push never blocks the request past the proxy's
568
+ patience. The push itself is still bounded (PUSH_MS), so it cannot run on
569
+ for hours. A send already going is joined; one just ended is re-run only
570
+ on a fresh click (no `join`), and re-sending the same commit is a no-op. */
559
571
  async send(name, body) {
572
+ const r = this.#repository(name);
573
+ const key = `${r.name}\n${body?.head ?? ''}\n${body?.target ?? ''}`;
574
+ let entry = this.#sending.get(key);
575
+ if (!entry || (entry.done && body?.join !== true)) {
576
+ const made = { done: false, result: undefined, error: undefined };
577
+ made.run = this.#doSend(r.name, body)
578
+ .then((result) => { made.result = result; }, (error) => { made.error = error; })
579
+ .finally(() => { made.done = true; setTimeout(() => { if (this.#sending.get(key) === made) this.#sending.delete(key); }, SENDING_KEEP_MS).unref?.(); });
580
+ entry = made; this.#sending.set(key, made);
581
+ }
582
+ const ms = Number.isFinite(body?.wait) ? Math.max(0, Math.min(body.wait, SENDING_WAIT_MS)) : SENDING_WAIT_MS;
583
+ await Promise.race([entry.run, new Promise((res) => { setTimeout(res, ms).unref?.(); })]);
584
+ if (!entry.done) return { status: 'sending' };
585
+ if (entry.error) throw entry.error;
586
+ return entry.result;
587
+ }
588
+ async #doSend(name, body) {
560
589
  const r = this.#repository(name);
561
590
  if (this.settings(r.name).requireForSend) {
562
591
  const target = body?.target || undefined;
@@ -0,0 +1,120 @@
1
+ /* GROUPS OF ASSETS: a folder-style tidy-up, for the owner's convenience.
2
+ *
3
+ * The owner may have many assets -- folders, git repositories, mailboxes,
4
+ * secrets, connexions. A GROUP is a named box they drop some of them into,
5
+ * to calm the three places assets are shown (the Assets list, a
6
+ * conversation's panel, the access map) and to hand a whole box to a
7
+ * conversation at once.
8
+ *
9
+ * WHAT A GROUP IS NOT: a right. The table of rights (grants.mjs, and the
10
+ * Tether levels) stays the ONE truth of who may do what. A group is only a
11
+ * label an asset carries. "Give the group" is a shortcut that gives each of
12
+ * its assets, one by one, each at a sensible default for its own type -- it
13
+ * is never a line of its own in the rights table, and there is no
14
+ * inheritance. So a group may hold assets of mixed types, and taking a right
15
+ * back is still done on the one asset.
16
+ *
17
+ * THE MODEL IS A FOLDER: an asset sits in AT MOST ONE group; placing it in a
18
+ * group takes it out of any other. Assets with no group ("loose") and
19
+ * grouped assets live side by side. A group emptied of its assets is still a
20
+ * group until it is removed.
21
+ *
22
+ * A MEMBER is an asset id, the same string the rest of the server uses:
23
+ * "folder:reports", "git:site", "mailbox:news", "secret:MODEL_KEY",
24
+ * "connexion:<id>". This store does not police what an id points at (assets
25
+ * come and go, and a Tether connexion is not in grants.mjs), so it keeps ids
26
+ * as given; a view resolves them against the assets that exist and ignores
27
+ * the rest. `forget(asset)` drops a member whose asset is gone.
28
+ */
29
+ import { randomBytes } from 'node:crypto';
30
+ import { Refusal } from './conversations.mjs';
31
+ import { titleProblem } from './names.mjs';
32
+
33
+ export const LABEL_MAX = 40;
34
+ /* An id a browser cannot forge into something else: short, random, lower. */
35
+ const ID = /^[0-9a-f]{12}$/;
36
+ /* A member is "<type>:<name>" -- a type of a few lower letters, then a name
37
+ with no space or control character. Kept loose on purpose (see above). */
38
+ const MEMBER = /^[a-z]{2,16}:[^\s\u0000-\u001f]{1,64}$/;
39
+
40
+ export function labelProblem(value) {
41
+ const problem = titleProblem(value);
42
+ if (problem) return problem.replace('A name', 'A group name').replace('Give a name.', 'Give the group a name.');
43
+ if ([...value].length > LABEL_MAX) return `A group name is ${LABEL_MAX} characters at most.`;
44
+ return '';
45
+ }
46
+
47
+ export const isMember = (asset) => typeof asset === 'string' && MEMBER.test(asset);
48
+
49
+ export class Groups {
50
+ #store;
51
+
52
+ constructor({ store }) { this.#store = store; }
53
+
54
+ /* [{ id, label, members: [asset...] }], in the order they were made. */
55
+ list() {
56
+ return this.#store.all().map((g) => ({ id: g.name, label: g.label, members: [...(g.members ?? [])] }));
57
+ }
58
+
59
+ /* The group an asset is in, or null. */
60
+ groupOf(asset) {
61
+ const g = this.#store.all().find((x) => (x.members ?? []).includes(asset));
62
+ return g ? g.name : null;
63
+ }
64
+
65
+ /* A new, empty group. */
66
+ create(label) {
67
+ const problem = labelProblem(label);
68
+ if (problem) throw new Refusal(400, problem);
69
+ let id; do { id = randomBytes(6).toString('hex'); } while (this.#store.get(id));
70
+ this.#store.put({ name: id, label, members: [] });
71
+ return { id, label, members: [] };
72
+ }
73
+
74
+ rename(id, label) {
75
+ const group = this.#require(id);
76
+ const problem = labelProblem(label);
77
+ if (problem) throw new Refusal(400, problem);
78
+ this.#store.put({ ...group, label });
79
+ return { id, label, members: [...(group.members ?? [])] };
80
+ }
81
+
82
+ remove(id) {
83
+ this.#require(id);
84
+ this.#store.remove(id);
85
+ }
86
+
87
+ /* Put an asset in a group, or take it out (group null). A folder move:
88
+ the asset leaves whatever other group it was in. */
89
+ place(asset, group) {
90
+ if (!isMember(asset)) throw new Refusal(400, 'Not an asset: a type and a name, such as "folder:reports".');
91
+ if (group !== null && group !== undefined) this.#require(group);
92
+ for (const g of this.#store.all()) {
93
+ const has = (g.members ?? []).includes(asset);
94
+ if (g.name === group) { if (!has) this.#store.put({ ...g, members: [...(g.members ?? []), asset] }); }
95
+ else if (has) this.#store.put({ ...g, members: (g.members ?? []).filter((a) => a !== asset) });
96
+ }
97
+ return { asset, group: group ?? null };
98
+ }
99
+
100
+ /* Drop a member everywhere its asset appears (the asset was removed). */
101
+ forget(asset) {
102
+ for (const g of this.#store.all()) {
103
+ if ((g.members ?? []).includes(asset)) this.#store.put({ ...g, members: (g.members ?? []).filter((a) => a !== asset) });
104
+ }
105
+ }
106
+
107
+ /* An asset renamed keeps its place under its new id. */
108
+ renamed(from, to) {
109
+ for (const g of this.#store.all()) {
110
+ if ((g.members ?? []).includes(from)) this.#store.put({ ...g, members: (g.members ?? []).map((a) => (a === from ? to : a)).filter((a, i, all) => all.indexOf(a) === i) });
111
+ }
112
+ }
113
+
114
+ #require(id) {
115
+ if (typeof id !== 'string' || !ID.test(id)) throw new Refusal(400, 'Not a group.');
116
+ const group = this.#store.get(id);
117
+ if (!group) throw new Refusal(404, 'No such group.');
118
+ return group;
119
+ }
120
+ }
package/server/main.mjs CHANGED
@@ -48,6 +48,7 @@ import { Guide, commonText } from './guide.mjs';
48
48
  import { SignInMailboxes } from './signin.mjs';
49
49
  import { Mailboxes, recentMessages } from './mailbox.mjs';
50
50
  import { Grants } from './grants.mjs';
51
+ import { Groups } from './groups.mjs';
51
52
  import { GitReview } from './gitpush.mjs';
52
53
  import { GitAccess } from './gitaccess.mjs';
53
54
  import { GitChecks } from './gitchecks.mjs';
@@ -157,7 +158,7 @@ const withoutTmux = (env) => Object.fromEntries(Object.entries(env).filter(([key
157
158
 
158
159
  const REFUSED = 'This Clavarium belongs to someone else: your account is not one of its operators.\n';
159
160
 
160
- function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts } = {}) {
161
+ function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups } = {}) {
161
162
  /* Its manifest carries the name of this Clavarium, or the one a device chose (instance.mjs). */
162
163
  const sendManifest = (response, url) => response.writeHead(200, { ...HEADERS, 'content-type': 'application/manifest+json' }).end(instance.manifest(new URL(url ?? '/', 'http://local').searchParams.get('name') ?? undefined));
163
164
  const sendFile = async (response, file) => {
@@ -200,7 +201,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
200
201
  response.writeHead(403, { ...HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end(REFUSED);
201
202
  return;
202
203
  }
203
- if (conversations && 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)) return;
204
+ if (conversations && 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)) return;
204
205
  if (pathname === '/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
205
206
  const file = FILES[pathname];
206
207
  if (!file || (request.method !== 'GET' && request.method !== 'HEAD')) {
@@ -251,6 +252,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
251
252
  const all = conversations ?? new Conversations({ store: new Store(`${dataDir}/conversations.json`), layout: new JsonFile(`${dataDir}/layout.json`, {}), vms, tools, ...(stopDelayMs === undefined ? {} : { stopDelayMs }) });
252
253
  /* Who may do what with what: ONE table, shared by everything below. */
253
254
  const grants = new Grants(new Store(`${dataDir}/grants.json`));
255
+ /* Folder-style boxes the owner drops assets into, to tidy the views and hand a whole box at once (groups.mjs). */
256
+ const groups = new Groups({ store: new Store(`${dataDir}/groups.json`) });
254
257
  /* What happened, in one dated list (events.mjs): the owner's actions, and what the server did by itself. */
255
258
  const events = new Events({ file: `${dataDir}/events.log` });
256
259
  const vault = new Vault(vaultKey ?? `${dataDir}/vault.key`);
@@ -408,7 +411,19 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
408
411
  /* Connecting a mailbox, calendar or address book by token: the consent happens
409
412
  in the owner's browser, the refresh token is kept host-only (never in a
410
413
  machine) and a Tether target is made for it: see accounts.mjs. */
411
- const accounts = new Accounts({ secrets, targets: { put: (spec) => tethers.store().putTarget(spec) } });
414
+ const accounts = new Accounts({ secrets, targets: { put: (spec) => tethers.store().putTarget(spec), all: () => tethers.store().targets() } });
415
+ /* A calendar target made before it needed the account address (Google CalDAV
416
+ puts it in the URL) carries none. The same account's mailbox or address book
417
+ has it -- they share the one refresh token -- so fill it in from a sibling,
418
+ once, with no reconnection asked of anyone. */
419
+ (() => {
420
+ const store = tethers.store();
421
+ for (const t of store.targets()) {
422
+ if (t.kind !== 'calendar' || t.config?.user || !t.secrets?.refresh) continue;
423
+ const sib = store.targets().find((o) => o.secrets?.refresh === t.secrets.refresh && o.config?.user);
424
+ if (sib) store.putTarget({ ...t, config: { ...t.config, user: sib.config.user } });
425
+ }
426
+ })();
412
427
  /* A repository's origin kept up to date, checks run in the machine, and
413
428
  automatic sending to the branches the owner listed: see gitkeeper.mjs. */
414
429
  /* What could not be read is told to the agents that write in the repository, where they can act. */
@@ -504,7 +519,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
504
519
  /* Settings, Updates: what the updater (deploy/updater.mjs, as root) wrote, and how to ask it. */
505
520
  const updates = new Updates({ host: asHost, version: platform.version, store: new Store(`${dataDir}/updates.json`), alerts, ...(updateState ? { stateFile: updateState } : {}), ...(updateConf ? { confFile: updateConf } : {}) });
506
521
  const stopUpdates = updates.watch();
507
- const setup = new Setup({ store: new Store(`${dataDir}/flows.json`), version: platform.version, conversations: all, resources: folders, secrets, devices, shortcuts, wakeups, answerer, talk, gitKeeper, gitAccess, mailboxes, signin, network, guide, ...(setupPollMs ? { pollMs: setupPollMs } : {}) });
522
+ const setup = new Setup({ store: new Store(`${dataDir}/flows.json`), version: platform.version, conversations: all, resources: folders, secrets, devices, shortcuts, wakeups, answerer, talk, gitKeeper, gitAccess, mailboxes, signin, network, guide, tethers, groups, ...(setupPollMs ? { pollMs: setupPollMs } : {}) });
508
523
  /* This server's disk and memory, and the reserve no machine may eat into: see capacity.mjs. */
509
524
  const capacity = new Capacity({ run: asHost, store: new Store(`${dataDir}/server.json`), conversations: all, shelf, ...(serverRoomMs === undefined ? {} : { roomMs: serverRoomMs }),
510
525
  /* Under the reserve: the machine that takes the most put to sleep, the owner told, and its chat. */
@@ -531,7 +546,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
531
546
  void team.refresh().catch((error) => console.error(`operators: ${error.message}`));
532
547
  const watching = setInterval(() => { void team.watch().catch(() => {}); }, 60_000); watching.unref?.();
533
548
  }
534
- const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
549
+ const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, groups, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
535
550
  server.on('close', () => { closing = true; stopBinders(); stopTethers(); clearInterval(historyTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
536
551
  let closing = false;
537
552
  bridge = attachBridge(server, {
package/server/oauth.mjs CHANGED
@@ -35,10 +35,16 @@ import { createHash, randomBytes } from 'node:crypto';
35
35
 
36
36
  const b64url = (buf) => Buffer.from(buf).toString('base64url');
37
37
 
38
- /* Per-provider endpoints, the scopes we may ask for by kind, and Thunderbird's
39
- built-in client as the default. `consentExtra` is what a provider needs on the
40
- consent URL to return a refresh token; `offlineScope` is the same thing when it
41
- is a scope rather than a parameter (Microsoft). */
38
+ /* Per-provider endpoints, the scopes we may ask for by kind, and a built-in,
39
+ already-verified open-source desktop client as the default (the `thunderbird`
40
+ field). We borrow THUNDERBIRD's own client for BOTH providers: each registered
41
+ the loopback 127.0.0.1 redirect on any port, so the person always lands on the
42
+ same copy-pastable http://127.0.0.1 address, and each is cleared for the three
43
+ kinds -- Google's client carries the mail + CalDAV + CardDAV scopes; Microsoft's
44
+ takes mail, calendar and contacts over Graph (a multitenant public client, by
45
+ dynamic consent). `consentExtra` is what a provider needs on the consent URL to
46
+ return a refresh token; `offlineScope` is the same thing when it is a scope
47
+ rather than a parameter (Microsoft). */
42
48
  export const PROVIDERS = {
43
49
  google: {
44
50
  label: 'Google',
@@ -52,6 +58,13 @@ export const PROVIDERS = {
52
58
  calendar: 'https://www.googleapis.com/auth/calendar',
53
59
  contacts: 'https://www.googleapis.com/auth/carddav',
54
60
  },
61
+ /* Thunderbird's own built-in Google client (open source, embedded secret
62
+ sanctioned by Google for an installed app; comm-central
63
+ OAuth2Providers.sys.mjs). Its GOOGLE_SCOPES carry mail AND CalDAV AND
64
+ CardDAV, so one consent gives all three -- the same loopback 127.0.0.1
65
+ redirect as before. Using Thunderbird for Google too means one borrowed
66
+ identity for both providers. (GNOME Online Accounts' client
67
+ 44438659992-... worked as well; we unified on Thunderbird.) */
55
68
  thunderbird: {
56
69
  clientId: '406964657835-aq8lmia8j95dhl1a2bvharmfk3t1hgqj.apps.googleusercontent.com',
57
70
  clientSecret: 'kSmqreRr0qwBWJgbf5Y-PjSU',
@@ -64,13 +77,21 @@ export const PROVIDERS = {
64
77
  pkce: true,
65
78
  consentExtra: {},
66
79
  offlineScope: 'offline_access',
67
- /* Mail (and SMTP) are outlook.office.com resources; calendar/files over
68
- Graph are a different resource and a separate token -- added when those
69
- connectors arrive, not mixed into one mail request. */
80
+ /* Microsoft over Graph: mail, calendar and contacts all go through
81
+ graph.microsoft.com (the mail connector uses its Graph path for
82
+ Microsoft). mail.send is needed to send. Thunderbird's public client
83
+ takes these delegated scopes by dynamic consent. */
70
84
  scopes: {
71
- mail: 'https://outlook.office.com/IMAP.AccessAsUser.All',
72
- smtp: 'https://outlook.office.com/SMTP.Send',
85
+ mail: 'mail.readwrite mail.send',
86
+ calendar: 'calendars.readwrite',
87
+ contacts: 'contacts.readwrite',
73
88
  },
89
+ /* Thunderbird's built-in Microsoft client (open source, public, no secret;
90
+ comm-central OAuth2Providers.sys.mjs). It registered the loopback
91
+ 127.0.0.1 redirect on ANY port, so we reuse the same http://127.0.0.1
92
+ address as Google -- the person copies it from the bar. (GNOME Online
93
+ Accounts' Graph client, b155a604-..., registered only a custom-scheme
94
+ goa-oauth2:// redirect a browser cannot surface, so we left it.) */
74
95
  thunderbird: {
75
96
  clientId: '9e5f94bc-e8a4-4e73-b8be-63364c29d753',
76
97
  clientSecret: null,
@@ -117,6 +138,22 @@ export function scopeFor(name, kinds = ['mail']) {
117
138
  return [...new Set(parts)].join(' ');
118
139
  }
119
140
 
141
+ /* Which kinds a granted scope string actually covers. A provider may grant fewer
142
+ scopes than asked (the person unticks one on the consent screen); the token's
143
+ `scope` field says what was allowed, so we never have to guess. A kind counts as
144
+ granted when the first (primary) scope token of its request appears in the
145
+ granted string, matched case-insensitively -- providers echo scopes back in
146
+ their own casing and URL form (Microsoft returns
147
+ `https://graph.microsoft.com/Calendars.ReadWrite` for a requested
148
+ `calendars.readwrite`). Returns [] when the scope is unknown, so a caller can
149
+ fall back to trusting what it asked for. */
150
+ export function kindsGranted(name, granted = '') {
151
+ const p = provider(name);
152
+ const g = String(granted).toLowerCase();
153
+ if (!g) return [];
154
+ return Object.keys(p.scopes).filter((k) => g.includes(p.scopes[k].split(/\s+/)[0].toLowerCase()));
155
+ }
156
+
120
157
  /* The URL the person's browser opens to sign in and allow. `redirectUri` is the
121
158
  loopback the provider sends the code back to (http://127.0.0.1:PORT). */
122
159
  export function consentUrl(name, { clientId, redirectUri, scope, state, codeChallenge, loginHint } = {}) {