clavarium 0.2.45-next.1 → 0.2.46-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.
@@ -724,8 +724,16 @@ AREA="$1"; VERB="$2"; shift 2
724
724
 
725
725
  case "$AREA $VERB" in
726
726
  "vm launch")
727
- [ $# -eq 2 ] || usage; vm_of "$1"; memory_ok "$2"
728
- run "$MULTIPASS" launch "$IMAGE" --name "$1" --memory "${2}M" --disk "$DISK" --cpus 1 --timeout "$LAUNCH_SECONDS" ;;
727
+ # <vm> <memory> [<disk-gigabytes> <cores>]: the size chosen at creation;
728
+ # without the last two, the defaults (DISK, one core).
729
+ [ $# -eq 2 ] || [ $# -eq 4 ] || usage; vm_of "$1"; memory_ok "$2"
730
+ disk="$DISK"; cores=1
731
+ if [ $# -eq 4 ]; then
732
+ [[ "$3" =~ ^[0-9]{1,4}$ ]] && [ "$3" -ge 5 ] && [ "$3" -le "$DISK_MAX_GB" ] || refuse "disk out of bounds: $3"
733
+ [[ "$4" =~ ^[0-9]{1,3}$ ]] && [ "$4" -ge 1 ] && [ "$4" -le "$(nproc)" ] || refuse "cores out of bounds: $4 (the host has $(nproc))"
734
+ disk="${3}G"; cores="$4"
735
+ fi
736
+ run "$MULTIPASS" launch "$IMAGE" --name "$1" --memory "${2}M" --disk "$disk" --cpus "$cores" --timeout "$LAUNCH_SECONDS" ;;
729
737
  "vm clone")
730
738
  # <shelf> <vm> <memory>: a conversation's machine, copied from the
731
739
  # ready-made one (which must be stopped: Multipass refuses otherwise).
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.45-next.1",
3
+ "version": "0.2.46-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.45-next.1",
9
+ "version": "0.2.46-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
- "clavarium-binder": "0.1.6-next.1",
14
+ "clavarium-binder": "0.1.8-next.1",
15
15
  "clavarium-docket": "0.1.1",
16
- "clavarium-parley": "0.17.4-next.1",
16
+ "clavarium-parley": "0.17.9-next.1",
17
17
  "mermaid": "11.17.2",
18
18
  "node-pty": "^1.1.0",
19
19
  "pdfjs-dist": "6.4.299",
@@ -688,9 +688,9 @@
688
688
  }
689
689
  },
690
690
  "node_modules/clavarium-binder": {
691
- "version": "0.1.6-next.1",
692
- "resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.6-next.1.tgz",
693
- "integrity": "sha512-urE1ZZCYq9svQmQR1ailNX6r5OeBcT0wNDea498PMDRbmcUCOciqoF/1C3IGLT7z133eb4dOUEhVcbRE42/h3A==",
691
+ "version": "0.1.8-next.1",
692
+ "resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.8-next.1.tgz",
693
+ "integrity": "sha512-0ZvTgn4z3IzLWjVyt5H82tnrE4g4Zdh0eb0kKrpVYjJ8vEfun6CmzHFclce9lb7vH+CC5ozKETuTAmSVYkk+lg==",
694
694
  "license": "MIT",
695
695
  "bin": {
696
696
  "binder": "bin/binder.mjs",
@@ -714,9 +714,9 @@
714
714
  }
715
715
  },
716
716
  "node_modules/clavarium-parley": {
717
- "version": "0.17.4-next.1",
718
- "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.4-next.1.tgz",
719
- "integrity": "sha512-/rQy9WLP9/XndInawH6mIhS9RivA1IQmMpB5IhYMUflnLSWBvP096Z0TF3xB3u2X1e8uni4tar5Tua5hq/wjWg==",
717
+ "version": "0.17.9-next.1",
718
+ "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.9-next.1.tgz",
719
+ "integrity": "sha512-pKwFQnq/6JO2nA37u9RNCO6ddgCUvpqmmmqRPQMa5GGT1nL0dFGDs1hY+Wed3TqKYRKxLmCgUWgts0aQBYihqw==",
720
720
  "license": "MIT",
721
721
  "bin": {
722
722
  "parley": "bin/parley.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.45-next.1",
3
+ "version": "0.2.46-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.",
@@ -44,9 +44,9 @@
44
44
  "dependencies": {
45
45
  "@xterm/addon-fit": "^0.11.0",
46
46
  "@xterm/xterm": "^6.0.0",
47
- "clavarium-binder": "0.1.6-next.1",
47
+ "clavarium-binder": "0.1.8-next.1",
48
48
  "clavarium-docket": "0.1.1",
49
- "clavarium-parley": "0.17.4-next.1",
49
+ "clavarium-parley": "0.17.9-next.1",
50
50
  "mermaid": "11.17.2",
51
51
  "node-pty": "^1.1.0",
52
52
  "pdfjs-dist": "6.4.299",
package/server/api.mjs CHANGED
@@ -235,7 +235,7 @@ export async function handleApi(request, response, conversations, headers, resou
235
235
  if (pathname === '/api/tools') return send(200, conversations.tools()), true;
236
236
  if (pathname === '/api/conversations') {
237
237
  const lists = binders?.given() ?? {};
238
- return send(200, conversations.list().map((c) => ({ ...c, lists: lists[c.name] ?? null, resources: resources?.of(c.name) ?? [], secrets: secrets?.of(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;
238
+ 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;
239
239
  }
240
240
  if (pathname === '/api/resources' && resources) return send(200, resources.list()), true;
241
241
  if (pathname === '/api/shortcuts' && shortcuts) return send(200, shortcuts.list()), true;
@@ -408,6 +408,8 @@ export async function handleApi(request, response, conversations, headers, resou
408
408
  return send(200, { ok: true }), true;
409
409
  }
410
410
  if (pathname === '/api/mailboxes' && mailboxes) { const made = await mailboxes.add(body); void setup?.assetAdded(made.name).catch(() => {}); return send(201, made), true; }
411
+ if (pathname === '/api/mailboxes/consent' && mailboxes) return send(200, mailboxes.consent(body)), true;
412
+ if (pathname === '/api/mailboxes/connect' && mailboxes) { const made = await mailboxes.connect(body); void setup?.assetAdded(made.name).catch(() => {}); return send(201, made), true; }
411
413
  const fetched = /^\/api\/mailboxes\/([a-z0-9-]{1,32})\/sync$/.exec(pathname);
412
414
  if (fetched && mailboxes) return send(200, await mailboxes.sync(fetched[1])), true;
413
415
  if (pathname === '/api/shortcuts' && shortcuts) return send(201, shortcuts.add(body)), true;
@@ -505,6 +507,14 @@ export async function handleApi(request, response, conversations, headers, resou
505
507
  retell(conversation);
506
508
  return send(200, { ok: true, secrets: secrets.of(conversation) }), true;
507
509
  }
510
+ /* Forget an ephemeral secret now (its stars in the chat have a button): gone from the vault and the machine. */
511
+ const forgetSecret = /^\/api\/conversations\/([^/]+)\/secrets\/([^/]+)\/forget$/.exec(pathname);
512
+ if (forgetSecret && secrets) {
513
+ const conversation = decodeURIComponent(forgetSecret[1]);
514
+ if (!conversations.list().some((c) => c.name === conversation)) throw new Refusal(404, 'No such conversation.');
515
+ await secrets.drop(conversation, decodeURIComponent(forgetSecret[2]));
516
+ return send(200, { ok: true }), true;
517
+ }
508
518
  const share = /^\/api\/conversations\/([^/]+)\/share$/.exec(pathname);
509
519
  if (share && sharing) {
510
520
  const conversation = decodeURIComponent(share[1]);
@@ -260,7 +260,7 @@ export class Conversations {
260
260
  return { name: id, title: title !== undefined && title !== id ? title : undefined };
261
261
  }
262
262
 
263
- create({ name: given, title: read, tool, memoryMb, workOnDisk, group }) {
263
+ create({ name: given, title: read, tool, memoryMb, cpus, diskGb, workOnDisk, group }) {
264
264
  const { name, title } = this.#naming({ name: given, title: read });
265
265
  if (group !== undefined) { const problem = groupProblem(group); if (problem) throw new Refusal(400, problem); }
266
266
  if (!isConversationName(name)) throw new Refusal(400, 'A name is 1 to 32 lower-case letters, digits or hyphens; it starts with a letter and does not end with a hyphen.');
@@ -270,9 +270,14 @@ export class Conversations {
270
270
  if (!Number.isInteger(memory) || memory < chosen.memoryMb || memory > 16384) {
271
271
  throw new Refusal(400, `This tool needs at least ${chosen.memoryMb} MB of memory.`);
272
272
  }
273
+ /* Cores and disk, chosen at creation like the memory; their defaults when not given. */
274
+ const cores = cpus ?? 1;
275
+ if (!Number.isInteger(cores) || cores < 1 || cores > availableParallelism()) throw new Refusal(400, `Cores are 1 to ${availableParallelism()} (what this server has).`);
276
+ const disk = diskGb ?? DISK_GB;
277
+ if (!Number.isInteger(disk) || disk < DISK_GB || disk > DISK_MAX_GB) throw new Refusal(400, `Disk is ${DISK_GB} to ${DISK_MAX_GB} GB.`);
273
278
  if (this.#store.get(name)) throw new Refusal(409, 'A conversation already has this name.');
274
279
  const now = new Date().toISOString();
275
- const conversation = { name, ...(title ? { title } : {}), ...(group ? { group } : {}), tool, memoryMb: memory, diskGb: DISK_GB, fixed: FIXES, work: workOnDisk === true ? 'disk' : 'kept', phase: 'building', step: 'Starting the machine', createdAt: now, buildingSince: now, progress: buildProgress(now) };
280
+ const conversation = { name, ...(title ? { title } : {}), ...(group ? { group } : {}), tool, memoryMb: memory, cpus: cores, diskGb: disk, fixed: FIXES, work: workOnDisk === true ? 'disk' : 'kept', phase: 'building', step: 'Starting the machine', createdAt: now, buildingSince: now, progress: buildProgress(now) };
276
281
  /* A new one comes first in its folder (or first of those in none). */
277
282
  const { order, groups } = this.#order();
278
283
  this.#store.put(conversation);
@@ -284,6 +289,11 @@ export class Conversations {
284
289
  /* `again`: a machine built anew for a conversation that had one. */
285
290
  async #build(name, tool, memoryMb, again = false) {
286
291
  const fail = (what, r) => { this.#store.patch(name, { phase: 'failed', step: undefined, progress: undefined, error: `${what}: ${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}` }); };
292
+ /* The size chosen at creation (stored by create, kept on a rebuild): launched with it, or, for a
293
+ copy of a ready-made machine, brought to it while the copy is still stopped. */
294
+ const made = this.#store.get(name);
295
+ const diskGb = made?.diskGb ?? DISK_GB; const cpus = made?.cpus ?? 1;
296
+ const custom = diskGb !== DISK_GB || cpus !== 1;
287
297
  /* A COPY OF THE READY-MADE MACHINE when there is one that holds this
288
298
  tool (see shelf.mjs): it only has to boot. Anything wrong with the
289
299
  copy -- an older VM manager without "clone", a copy that does not
@@ -293,13 +303,18 @@ export class Conversations {
293
303
  let readyMade = false;
294
304
  if (from) {
295
305
  const cloned = await this.#vms.clone(name, from, memoryMb);
306
+ if (cloned.code === 0 && custom) {
307
+ /* Still stopped, like the memory the clone set: its cores, and its disk grown to the chosen size. */
308
+ if (cpus !== 1) await this.#vms.setCpus(name, cpus).catch(() => {});
309
+ if (diskGb !== DISK_GB) await this.#vms.setDisk(name, diskGb).catch(() => {});
310
+ }
296
311
  const started = cloned.code === 0 ? await this.#vms.start(name) : cloned;
297
312
  readyMade = started.code === 0;
298
313
  if (!readyMade && await this.#vms.state(name, { fresh: true }) !== undefined) await this.#vms.remove(name);
299
314
  if (!this.#store.get(name)) return undefined; /* archived meanwhile */
300
315
  }
301
316
  if (!readyMade) {
302
- const launched = await this.#vms.launch(name, memoryMb);
317
+ const launched = await this.#vms.launch(name, memoryMb, custom ? diskGb : undefined, custom ? cpus : undefined);
303
318
  if (launched.code !== 0) return fail('The machine did not start', launched);
304
319
  }
305
320
  this.#store.patch(name, { step: 'Preparing the machine', readyMade: readyMade || undefined });
package/server/guide.mjs CHANGED
@@ -129,6 +129,8 @@ export function ownText({ name, tool, workKept, resources = [], chat, online, se
129
129
  if (chat) out.push('- When you work in batches: keep them in a binder of batches, shown beside the chat. None yet: make it once (binder new batches; MCP: new-list, template batches). Then one card each (binder add Batches "title"), kept up to date; start only those the person ticked.');
130
130
  out.push(online === false ? '- Internet: off.' : '- Internet: on.');
131
131
  if (secrets.length) out.push(`- Secrets given, by name only: ${list(secrets.map((s) => plain(s, 40)))}.`);
132
+ /* A secret pasted in the chat is lifted out (talk.mjs, secret-scan.mjs): the message shows a marker, the value waits in /run/secrets. */
133
+ if (chat) out.push('- A secret the person pastes in the chat is kept OUT of it: the message shows ⟨secret:NAME⟩ and the value waits at /run/secrets/NAME for a few minutes. Use it only from there, inside a command (clv-run, or $(cat /run/secrets/NAME)); never write its value back into the chat. It clears itself when its time runs out, or at once with `parley forget NAME` when you are done.');
132
134
  const own = lines.map((l) => plain(l)).filter(Boolean).slice(0, LINES_MAX);
133
135
  if (own.length) out.push('', '## From the owner', '', ...own.map((l) => `- ${l}`));
134
136
  out.push('');
package/server/imap.mjs CHANGED
@@ -72,4 +72,20 @@ export class Exchange {
72
72
  if (!new RegExp(`^${tag} OK`, 'i').test(lines.at(-1) ?? '')) throw new Refusal(502, failure);
73
73
  return lines;
74
74
  }
75
+ /* AUTHENTICATE XOAUTH2 with the base64 SASL response given inline (initial
76
+ response, which Gmail and Outlook accept). On success the server answers the
77
+ tag with OK. On failure it first sends a `+ <base64 error>` challenge and
78
+ waits for an empty line before the tagged NO, so we finish that exchange and
79
+ then surface the refusal, rather than hang. */
80
+ async authenticateXoauth2(initial, failure) {
81
+ const tag = `c${++this.#n}`;
82
+ this.#socket.write(`${tag} AUTHENTICATE XOAUTH2 ${initial}\r\n`);
83
+ let lines = await this.#until((l) => l.startsWith(`${tag} `) || l.startsWith('+ '));
84
+ if ((lines.at(-1) ?? '').startsWith('+ ')) {
85
+ this.#socket.write('\r\n');
86
+ lines = await this.#until((l) => l.startsWith(`${tag} `));
87
+ }
88
+ if (!new RegExp(`^${tag} OK`, 'i').test(lines.at(-1) ?? '')) throw new Refusal(502, failure);
89
+ return lines;
90
+ }
75
91
  }
@@ -21,8 +21,18 @@ import { connect as tlsConnect } from 'node:tls';
21
21
  import { mkdirSync, readdirSync, writeFileSync, renameSync, rmSync, existsSync } from 'node:fs';
22
22
  import { Refusal } from './conversations.mjs';
23
23
  import { Exchange, quoted } from './imap.mjs';
24
- import { readSettings, TIMEOUT_MS } from './signin.mjs';
24
+ import { readSettings, oauthSettings, imapAuthenticate, PROVIDER_IMAP, TIMEOUT_MS } from './signin.mjs';
25
25
  import { isConversationName } from './names.mjs';
26
+ import { consentUrl, exchangeCode, extractCode, thunderbird, scopeFor, pkcePair, newState } from './oauth.mjs';
27
+
28
+ /* The loopback address the provider sends the code back to. Nothing listens on it:
29
+ the person's browser lands there (a page that will not load), and they copy the
30
+ address -- which carries the code -- back into Clavarium. Desktop OAuth clients
31
+ (Thunderbird's) accept any 127.0.0.1 port, and the same address is used again to
32
+ trade the code, so it only has to be constant. */
33
+ const REDIRECT = 'http://127.0.0.1:47813/';
34
+ const PENDING_MS = 10 * 60_000;
35
+ const PENDING_MAX = 20;
26
36
 
27
37
  export const MESSAGES = 50;
28
38
  /* A message is kept up to this size; a longer one is cut (its text comes first). */
@@ -33,13 +43,13 @@ const SYNC_TIMEOUT_MS = TIMEOUT_MS * 6;
33
43
  /* ---------- reading ---------- */
34
44
 
35
45
  /* The most recent messages, oldest first: [{ uid, receivedAt, raw }]. */
36
- export async function recentMessages(settings, { connect = tlsConnect, ca, limit = MESSAGES } = {}) {
46
+ export async function recentMessages(settings, { connect = tlsConnect, ca, limit = MESSAGES, fetch: fetchImpl = globalThis.fetch } = {}) {
37
47
  const socket = connect({ host: settings.host, port: settings.port, servername: settings.host, ...(ca ? { ca } : {}) });
38
48
  const timer = setTimeout(() => socket.destroy(new Error('timeout')), SYNC_TIMEOUT_MS);
39
49
  try {
40
50
  const imap = new Exchange(socket, limit * (MESSAGE_BYTES + 4096) + 2_000_000);
41
51
  await imap.greeting();
42
- await imap.command(`LOGIN ${quoted(settings.user)} ${quoted(settings.password)}`, 'The mailbox refused the user or the password.');
52
+ await imapAuthenticate(imap, settings, { fetch: fetchImpl });
43
53
  await imap.command('EXAMINE INBOX', 'The inbox could not be opened.');
44
54
  const found = await imap.command('UID SEARCH ALL', 'The mailbox could not be searched.');
45
55
  const uids = (found.find((l) => /^\* SEARCH/i.test(l)) ?? '').split(' ').slice(2).map(Number).filter((n) => Number.isInteger(n) && n > 0).slice(-limit);
@@ -115,13 +125,13 @@ export function writeFolder(folder, user, messages) {
115
125
  /* ---------- the mailboxes kept ---------- */
116
126
 
117
127
  export class Mailboxes {
118
- #store; #vault; #resources; #reader; #busy = new Set();
128
+ #store; #vault; #resources; #reader; #fetch; #pending = new Map(); #busy = new Set();
119
129
 
120
- constructor({ store, vault, resources, reader = recentMessages }) { this.#store = store; this.#vault = vault; this.#resources = resources; this.#reader = reader; }
130
+ constructor({ store, vault, resources, reader = recentMessages, fetch = globalThis.fetch }) { this.#store = store; this.#vault = vault; this.#resources = resources; this.#reader = reader; this.#fetch = fetch; }
121
131
 
122
132
  /* What the page may know. Never the password. */
123
133
  list() {
124
- return this.#store.all().map((m) => ({ name: m.name, host: m.host, port: m.port ?? 993, user: m.user, messages: m.messages ?? 0, syncedAt: m.syncedAt ?? null, failure: m.failure ?? null }));
134
+ return this.#store.all().map((m) => ({ name: m.name, host: m.host, port: m.port ?? 993, user: m.user, provider: m.provider ?? null, messages: m.messages ?? 0, syncedAt: m.syncedAt ?? null, failure: m.failure ?? null }));
125
135
  }
126
136
 
127
137
  /* Adds a mailbox after proving it can be read, as a folder of that name. */
@@ -129,14 +139,53 @@ export class Mailboxes {
129
139
  const name = String(body?.name ?? '');
130
140
  if (!isConversationName(name)) throw new Refusal(400, 'A name is 1 to 32 lower-case letters, digits or hyphens; it starts with a letter and does not end with a hyphen.');
131
141
  if (this.#resources.list().some((r) => r.name === name)) throw new Refusal(409, 'A folder already has this name.');
132
- const settings = readSettings(body);
142
+ const settings = body?.provider ? oauthSettings(body) : readSettings(body);
133
143
  const messages = await this.#reader(settings);
134
144
  await this.#resources.create({ name, type: 'mailbox' });
135
- this.#store.put({ name, host: settings.host, port: settings.port, user: settings.user, sealed: this.#vault.seal(settings.password) });
145
+ this.#store.put({ name, host: settings.host, port: settings.port, user: settings.user, provider: settings.provider, sealed: this.#vault.seal(settings.password) });
136
146
  this.#write(name, settings.user, messages);
137
147
  return this.list().find((m) => m.name === name);
138
148
  }
139
149
 
150
+ /* Start connecting a mailbox by token: build the provider's consent page and
151
+ keep the state and PKCE verifier until the person pastes the address back. */
152
+ consent({ name, provider, user }) {
153
+ const nm = String(name ?? '');
154
+ if (!isConversationName(nm)) throw new Refusal(400, 'A name is 1 to 32 lower-case letters, digits or hyphens; it starts with a letter and does not end with a hyphen.');
155
+ if (this.#resources.list().some((r) => r.name === nm)) throw new Refusal(409, 'A folder already has this name.');
156
+ if (!PROVIDER_IMAP[String(provider ?? '')]) throw new Refusal(400, 'Choose Gmail or Microsoft.');
157
+ const address = String(user ?? '').trim();
158
+ if (address === '' || address.length > 200) throw new Refusal(400, 'The mailbox needs its email address.');
159
+ this.#sweepPending();
160
+ if (this.#pending.size >= PENDING_MAX) throw new Refusal(429, 'Too many connections in progress; try again shortly.');
161
+ const { clientId } = thunderbird(provider);
162
+ const state = newState();
163
+ const { verifier, challenge } = pkcePair();
164
+ const url = consentUrl(provider, { clientId, redirectUri: REDIRECT, scope: scopeFor(provider, ['mail']), state, codeChallenge: challenge, loginHint: address });
165
+ this.#pending.set(state, { name: nm, provider: String(provider), user: address, verifier, at: Date.now() });
166
+ return { url };
167
+ }
168
+
169
+ /* Finish it: from the pasted address, read the code, trade it for a refresh
170
+ token, and add the mailbox (which proves it can be read). */
171
+ async connect({ redirected }) {
172
+ this.#sweepPending();
173
+ let state;
174
+ try { state = new URL(String(redirected ?? '').trim()).searchParams.get('state'); } catch { throw new Refusal(400, 'Paste the whole address from the bar, after you allow.'); }
175
+ const p = state && this.#pending.get(state);
176
+ if (!p) throw new Refusal(400, 'This connection has expired or was already used; start it again.');
177
+ this.#pending.delete(state);
178
+ let code;
179
+ try { code = extractCode(redirected, { state }); } catch (e) { throw new Refusal(400, e.message); }
180
+ const { clientId, clientSecret } = thunderbird(p.provider);
181
+ let refreshToken;
182
+ try { ({ refreshToken } = await exchangeCode(p.provider, { clientId, clientSecret, redirectUri: REDIRECT, code, codeVerifier: p.verifier, fetch: this.#fetch })); }
183
+ catch (e) { throw new Refusal(502, `The connection could not be completed: ${e.message}`); }
184
+ return this.add({ name: p.name, provider: p.provider, user: p.user, refresh: refreshToken });
185
+ }
186
+
187
+ #sweepPending() { const now = Date.now(); for (const [k, v] of this.#pending) if (now - v.at > PENDING_MS) this.#pending.delete(k); }
188
+
140
189
  #write(name, user, messages) {
141
190
  writeFolder(this.#resources.folder(name), user, messages);
142
191
  this.#store.patch(name, { messages: messages.length, syncedAt: new Date().toISOString(), failure: undefined });
@@ -150,7 +199,7 @@ export class Mailboxes {
150
199
  if (this.#busy.has(name)) return this.list().find((x) => x.name === name);
151
200
  this.#busy.add(name);
152
201
  try {
153
- const messages = await this.#reader({ host: m.host, port: m.port, user: m.user, password: this.#vault.open(m.sealed) });
202
+ const messages = await this.#reader({ host: m.host, port: m.port, user: m.user, provider: m.provider, password: this.#vault.open(m.sealed) });
154
203
  this.#write(name, m.user, messages);
155
204
  } catch (error) {
156
205
  this.#store.patch(name, { failure: error instanceof Refusal ? error.message : 'The mailbox could not be read.' });
package/server/main.mjs CHANGED
@@ -35,6 +35,7 @@ import { Devices } from './devices.mjs';
35
35
  import { handleDoor, deviceTerminal } from './door.mjs';
36
36
  import { Vault } from './vault.mjs';
37
37
  import { Secrets, RUNNER } from './secrets.mjs';
38
+ import { scan, secretRef } from './secret-scan.mjs';
38
39
  import { Network } from './network.mjs';
39
40
  import { Answerer, answererConfig } from './answerer.mjs';
40
41
  import { Dockets } from './dockets.mjs';
@@ -420,6 +421,26 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
420
421
  what is already known of a machine used instead of asking (talk.mjs). */
421
422
  terminal: { open: (name) => bridge?.open(name) ?? false, type: (name, line, ms) => bridge?.type(name, line, ms) ?? false, droppedAt: (name) => bridge?.droppedAt(name) },
422
423
  health: { of: (name) => health?.of(name) ?? null },
424
+ /* A secret pasted in a message is lifted out before the message is kept:
425
+ it goes to the short-lived vault and the message keeps only a marker
426
+ the chat shows as stars; the value reaches the machine as
427
+ /run/secrets/<name>, and is swept after a few minutes. */
428
+ screen: async (conversation, text) => {
429
+ const hits = scan(text);
430
+ if (!hits.length) return text;
431
+ let out = ''; let last = 0; let any = false;
432
+ for (const h of hits) {
433
+ out += text.slice(last, h.start);
434
+ try { const { name, expiresAt } = secrets.stash(conversation, h.value); out += secretRef(name, Date.parse(expiresAt)); any = true; }
435
+ catch { out += text.slice(h.start, h.end); } /* cannot be stashed (too large): left as it is */
436
+ last = h.end;
437
+ }
438
+ out += text.slice(last);
439
+ if (any) { try { await secrets.deliver(conversation); } catch { /* machine not running: delivered at its next open */ } }
440
+ return out;
441
+ },
442
+ /* The agent asked to forget a short-lived secret (parley forget): drop it from the vault and machine. */
443
+ dropSecret: (conversation, name) => { void secrets.drop(conversation, name).catch(() => {}); },
423
444
  alert: (payload) => { void alerts.tell(payload); } });
424
445
  /* Its machine restarted or built again: said in its chat, and the tool told to read it again. */
425
446
  all.renewed = (name, text, running) => talk.renewed(name, text, running);
@@ -0,0 +1,224 @@
1
+ /* NOTE: the canonical home of this module is clavarium-tether (host/oauth.mjs). This
2
+ is a mirror kept in Clavarium for the mail feature, until the Tether integration is
3
+ in production here; then drop this copy and import it from clavarium-tether. Keep the
4
+ two in step. */
5
+
6
+ /* THE OAUTH SOCLE -- user-delegated access to Gmail and Microsoft (mail today,
7
+ * calendar and files next), so a mailbox is reached by a token and never a
8
+ * stored password. It is the shape Thunderbird uses: keep IMAP/SMTP, but
9
+ * AUTHENTICATE with a bearer token instead of LOGIN, and get that token from an
10
+ * OAuth consent the person gives in their own browser.
11
+ *
12
+ * THE RUSE, AND WHY A CLIENT ID SITS HERE. Google and Microsoft only let a
13
+ * *registered* application ask for consent. Registering one per installation is
14
+ * exactly what an open, self-hosted project cannot ask of everybody, so instead
15
+ * we present ourselves with Thunderbird's own built-in client -- the id (and, for
16
+ * Google, the secret) that ship, in the open, in Mozilla's source
17
+ * (comm-central mailnews/base/src/OAuth2Providers.sys.mjs). These are installed-
18
+ * app / public-client credentials: not a secret in the real sense (anyone who has
19
+ * Thunderbird has them), and that is why reusing them is sound. Mozilla's file
20
+ * says "don't copy these for your own application" -- we copy them *as*
21
+ * Thunderbird, deliberately, with the operator's decision, and the consent window
22
+ * tells the person plainly that this is what Clavarium does. A deployment that
23
+ * would rather register its own application sets its own clientId/secret and
24
+ * never touches the defaults below.
25
+ *
26
+ * NOTHING AUTOMATES THE LOGIN. The person signs in to Google/Microsoft in their
27
+ * own real browser, however they normally do (password, passkey, YubiKey, 2FA) --
28
+ * we never see or type a credential. All we ever handle is the authorization
29
+ * `code` the provider hands back to a loopback address, and the refresh token we
30
+ * trade it for. Capturing that code is the host's business (a pasted address, or
31
+ * the browser extension): this file is only the OAuth arithmetic, and takes an
32
+ * injected `fetch` so it runs under test with no network.
33
+ */
34
+ import { createHash, randomBytes } from 'node:crypto';
35
+
36
+ const b64url = (buf) => Buffer.from(buf).toString('base64url');
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). */
42
+ export const PROVIDERS = {
43
+ google: {
44
+ label: 'Google',
45
+ auth: 'https://accounts.google.com/o/oauth2/auth',
46
+ token: 'https://oauth2.googleapis.com/token',
47
+ pkce: true,
48
+ consentExtra: { access_type: 'offline', prompt: 'consent' },
49
+ offlineScope: null,
50
+ scopes: {
51
+ mail: 'https://mail.google.com/',
52
+ calendar: 'https://www.googleapis.com/auth/calendar',
53
+ contacts: 'https://www.googleapis.com/auth/carddav',
54
+ },
55
+ thunderbird: {
56
+ clientId: '406964657835-aq8lmia8j95dhl1a2bvharmfk3t1hgqj.apps.googleusercontent.com',
57
+ clientSecret: 'kSmqreRr0qwBWJgbf5Y-PjSU',
58
+ },
59
+ },
60
+ microsoft: {
61
+ label: 'Microsoft',
62
+ auth: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
63
+ token: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
64
+ pkce: true,
65
+ consentExtra: {},
66
+ 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. */
70
+ scopes: {
71
+ mail: 'https://outlook.office.com/IMAP.AccessAsUser.All',
72
+ smtp: 'https://outlook.office.com/SMTP.Send',
73
+ },
74
+ thunderbird: {
75
+ clientId: '9e5f94bc-e8a4-4e73-b8be-63364c29d753',
76
+ clientSecret: null,
77
+ },
78
+ },
79
+ };
80
+
81
+ export function provider(name) {
82
+ const p = PROVIDERS[name];
83
+ if (!p) throw new Error(`unknown oauth provider: ${name}`);
84
+ return p;
85
+ }
86
+
87
+ /* Thunderbird's built-in client for a provider -- the default when a deployment
88
+ has not set its own. Returned as a fresh object so a caller may override it. */
89
+ export function thunderbird(name) {
90
+ const { clientId, clientSecret } = provider(name).thunderbird;
91
+ return { clientId, clientSecret };
92
+ }
93
+
94
+ /* A PKCE pair: a random verifier kept by the host, and the S256 challenge put on
95
+ the consent URL. Both providers accept (Microsoft's public client needs) PKCE. */
96
+ export function pkcePair() {
97
+ const verifier = b64url(randomBytes(32));
98
+ const challenge = b64url(createHash('sha256').update(verifier).digest());
99
+ return { verifier, challenge, method: 'S256' };
100
+ }
101
+
102
+ /* An opaque value to tie a consent to the request that started it, so a stray or
103
+ forged redirect is refused (see extractCode). */
104
+ export function newState() { return b64url(randomBytes(16)); }
105
+
106
+ /* The scope string for the kinds wanted (default: mail), de-duplicated, with the
107
+ provider's offline scope appended when it has one. */
108
+ export function scopeFor(name, kinds = ['mail']) {
109
+ const p = provider(name);
110
+ const parts = [];
111
+ for (const k of kinds) {
112
+ const s = p.scopes[k];
113
+ if (!s) throw new Error(`${p.label} has no ${k} scope here`);
114
+ parts.push(...s.split(/\s+/).filter(Boolean));
115
+ }
116
+ if (p.offlineScope) parts.push(p.offlineScope);
117
+ return [...new Set(parts)].join(' ');
118
+ }
119
+
120
+ /* The URL the person's browser opens to sign in and allow. `redirectUri` is the
121
+ loopback the provider sends the code back to (http://127.0.0.1:PORT). */
122
+ export function consentUrl(name, { clientId, redirectUri, scope, state, codeChallenge, loginHint } = {}) {
123
+ const p = provider(name);
124
+ if (!clientId) throw new Error('consentUrl needs a clientId');
125
+ if (!redirectUri) throw new Error('consentUrl needs a redirectUri');
126
+ if (!scope) throw new Error('consentUrl needs a scope');
127
+ const q = new URLSearchParams({
128
+ client_id: clientId,
129
+ response_type: 'code',
130
+ redirect_uri: redirectUri,
131
+ scope,
132
+ ...(state ? { state } : {}),
133
+ ...p.consentExtra,
134
+ });
135
+ if (p.pkce) {
136
+ if (!codeChallenge) throw new Error(`${p.label} requires PKCE: pass codeChallenge`);
137
+ q.set('code_challenge', codeChallenge);
138
+ q.set('code_challenge_method', 'S256');
139
+ }
140
+ if (loginHint) q.set('login_hint', loginHint);
141
+ return `${p.auth}?${q.toString()}`;
142
+ }
143
+
144
+ /* Pull the authorization code out of the address the browser lands on after the
145
+ person allows -- the loopback URL they paste back, or that the extension reads.
146
+ Verifies the state when one is given, and turns an `error=...` redirect into a
147
+ plain message. */
148
+ export function extractCode(redirected, { state } = {}) {
149
+ let u;
150
+ try { u = new URL(String(redirected ?? '').trim()); } catch { throw new Error('that is not the address the provider sent back'); }
151
+ const q = u.searchParams;
152
+ const err = q.get('error');
153
+ if (err) throw new Error(`the provider refused: ${q.get('error_description') || err}`);
154
+ const code = q.get('code');
155
+ if (!code) throw new Error('that address carries no code -- paste the whole address from the bar after you allow');
156
+ const got = q.get('state');
157
+ if (state && got && got !== state) throw new Error('that address does not match this request (state mismatch)');
158
+ return code;
159
+ }
160
+
161
+ async function postToken(name, params, fetchImpl) {
162
+ const p = provider(name);
163
+ const body = new URLSearchParams(params);
164
+ let res;
165
+ try {
166
+ res = await fetchImpl(p.token, {
167
+ method: 'POST',
168
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
169
+ body: body.toString(),
170
+ });
171
+ } catch (e) { throw new Error(`cannot reach the ${p.label} token service: ${e?.message ?? e}`); }
172
+ const j = await res.json().catch(() => ({}));
173
+ if (!res.ok) throw new Error(`${p.label} token service refused (${res.status}): ${j.error_description || j.error || 'no detail'}`);
174
+ return j;
175
+ }
176
+
177
+ /* access_token + refresh_token + a wall-clock expiry (ms). */
178
+ function tokenShape(j) {
179
+ return {
180
+ accessToken: j.access_token,
181
+ refreshToken: j.refresh_token,
182
+ expiresAt: Date.now() + (Number(j.expires_in) || 3600) * 1000,
183
+ scope: j.scope,
184
+ };
185
+ }
186
+
187
+ /* Trade the authorization code for the first refresh token (consent, once per
188
+ mailbox). Google's installed-app client sends its secret and the PKCE verifier;
189
+ Microsoft's public client sends the verifier only. */
190
+ export async function exchangeCode(name, { clientId, clientSecret, redirectUri, code, codeVerifier, fetch: fetchImpl = globalThis.fetch } = {}) {
191
+ if (!clientId) throw new Error('exchangeCode needs a clientId');
192
+ if (!code) throw new Error('exchangeCode needs a code');
193
+ if (!redirectUri) throw new Error('exchangeCode needs the same redirectUri as the consent');
194
+ const params = { grant_type: 'authorization_code', code, redirect_uri: redirectUri, client_id: clientId };
195
+ if (clientSecret) params.client_secret = clientSecret;
196
+ if (codeVerifier) params.code_verifier = codeVerifier;
197
+ const t = tokenShape(await postToken(name, params, fetchImpl));
198
+ if (!t.accessToken) throw new Error(`${provider(name).label} gave no access token`);
199
+ if (!t.refreshToken) throw new Error(`${provider(name).label} gave no refresh token -- the consent must ask for offline access`);
200
+ return t;
201
+ }
202
+
203
+ /* Spend the refresh token for a fresh access token (every hour or so, at use).
204
+ The provider may or may not hand back a new refresh token; keep the old one if
205
+ it does not. */
206
+ export async function refreshAccess(name, { clientId, clientSecret, refreshToken, scope, fetch: fetchImpl = globalThis.fetch } = {}) {
207
+ if (!clientId) throw new Error('refreshAccess needs a clientId');
208
+ if (!refreshToken) throw new Error('refreshAccess needs a refreshToken');
209
+ const params = { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: clientId };
210
+ if (clientSecret) params.client_secret = clientSecret;
211
+ if (scope) params.scope = scope;
212
+ const t = tokenShape(await postToken(name, params, fetchImpl));
213
+ if (!t.accessToken) throw new Error(`${provider(name).label} gave no access token on refresh`);
214
+ if (!t.refreshToken) t.refreshToken = refreshToken;
215
+ return t;
216
+ }
217
+
218
+ /* The SASL XOAUTH2 initial response for an IMAP/SMTP AUTHENTICATE: the base64 of
219
+ `user=<mail>^Aauth=Bearer <token>^A^A`. The mail connector will use this in
220
+ place of LOGIN; kept here with the rest of the OAuth arithmetic. */
221
+ export function xoauth2(user, accessToken) {
222
+ if (!user || !accessToken) throw new Error('xoauth2 needs a user and an access token');
223
+ return Buffer.from(`user=${user}\x01auth=Bearer ${accessToken}\x01\x01`, 'utf8').toString('base64');
224
+ }