clavarium 0.2.45-beta.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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.45-beta.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-beta.1",
9
+ "version": "0.2.46-beta.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.45-beta.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.",
package/server/api.mjs CHANGED
@@ -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;
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.' });
@@ -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
+ }
package/server/signin.mjs CHANGED
@@ -23,6 +23,7 @@
23
23
  import { connect as tlsConnect } from 'node:tls';
24
24
  import { Refusal } from './conversations.mjs';
25
25
  import { Exchange, quoted, imapDate } from './imap.mjs';
26
+ import { refreshAccess, thunderbird, xoauth2 } from './oauth.mjs';
26
27
 
27
28
  export { quoted, imapDate };
28
29
 
@@ -111,15 +112,50 @@ export function readSettings(body) {
111
112
  return { host, port, user, password };
112
113
  }
113
114
 
115
+ /* The IMAP server for each OAuth provider: when a mailbox is connected by token,
116
+ the person never types a host -- it is the provider's own. */
117
+ export const PROVIDER_IMAP = {
118
+ google: { host: 'imap.gmail.com', port: 993 },
119
+ microsoft: { host: 'outlook.office365.com', port: 993 },
120
+ };
121
+
122
+ /* Settings for a token-connected mailbox, from the provider, the address and the
123
+ refresh token obtained at consent. The stored secret (`password` here) is that
124
+ refresh token; a fresh access token is spent from it at each read. */
125
+ export function oauthSettings({ provider, user, refresh }) {
126
+ const client = PROVIDER_IMAP[String(provider ?? '')];
127
+ if (!client) throw new Refusal(400, 'Choose Gmail or Microsoft.');
128
+ const address = String(user ?? '').trim();
129
+ if (address === '' || address.length > 200) throw new Refusal(400, 'The mailbox needs its email address.');
130
+ if (!refresh || String(refresh).length > 4096) throw new Refusal(400, 'The connection did not return a usable token.');
131
+ return { host: client.host, port: client.port, user: address, provider: String(provider), password: String(refresh) };
132
+ }
133
+
134
+ /* The IMAP auth step, shared by both readers: AUTHENTICATE XOAUTH2 with a fresh
135
+ access token when the mailbox is OAuth (its stored secret being the refresh
136
+ token), a plain LOGIN with the password otherwise. `fetch` is injectable. */
137
+ export async function imapAuthenticate(imap, settings, { fetch: fetchImpl = globalThis.fetch } = {}) {
138
+ if (!settings.provider) {
139
+ await imap.command(`LOGIN ${quoted(settings.user)} ${quoted(settings.password)}`, 'The mailbox refused the user or the password.');
140
+ return;
141
+ }
142
+ const { clientId, clientSecret } = thunderbird(settings.provider);
143
+ let accessToken;
144
+ try {
145
+ ({ accessToken } = await refreshAccess(settings.provider, { clientId, clientSecret, refreshToken: settings.password, fetch: fetchImpl }));
146
+ } catch { throw new Refusal(502, 'The mail account must be reconnected: its authorisation was refused.'); }
147
+ await imap.authenticateXoauth2(xoauth2(settings.user, accessToken), 'The mailbox refused the token: reconnect the account.');
148
+ }
149
+
114
150
  /* Recent sign-in messages of this mailbox, newest first. `connect` and `now`
115
151
  are injectable; a connection is always TLS, and never anything else. */
116
- export async function recentSignIns(settings, rules, { connect = tlsConnect, now = new Date(), ca } = {}) {
152
+ export async function recentSignIns(settings, rules, { connect = tlsConnect, now = new Date(), ca, fetch: fetchImpl = globalThis.fetch } = {}) {
117
153
  const socket = connect({ host: settings.host, port: settings.port, servername: settings.host, ...(ca ? { ca } : {}) });
118
154
  const timer = setTimeout(() => socket.destroy(new Error('timeout')), TIMEOUT_MS);
119
155
  try {
120
156
  const imap = new Exchange(socket, BYTES_MAX);
121
157
  await imap.greeting();
122
- await imap.command(`LOGIN ${quoted(settings.user)} ${quoted(settings.password)}`, 'The mailbox refused the user or the password.');
158
+ await imapAuthenticate(imap, settings, { fetch: fetchImpl });
123
159
  await imap.command('EXAMINE INBOX', 'The inbox could not be opened.');
124
160
  const since = new Date(now.getTime() - 24 * 3_600_000);
125
161
  const found = await imap.command(`UID SEARCH SINCE ${imapDate(since)}`, 'The mailbox could not be searched.');
package/web/app.js CHANGED
@@ -5861,6 +5861,7 @@
5861
5861
 
5862
5862
  $('mailbox-new').addEventListener('submit', async (event) => {
5863
5863
  event.preventDefault();
5864
+ if ($('mailbox-new').dataset.provider !== 'imap') return;
5864
5865
  $('mailbox-error').hidden = true;
5865
5866
  const button = $('mailbox-new').querySelector('button[type=submit]');
5866
5867
  button.disabled = true; button.textContent = 'Reading the mailbox...';
@@ -5871,6 +5872,49 @@
5871
5872
  button.disabled = false; button.textContent = 'Add';
5872
5873
  await paintAssets();
5873
5874
  });
5875
+ /* Gmail / Microsoft / IMAP, in the New-mailbox form. For a provider, the person
5876
+ signs in in their own browser (as Thunderbird) and pastes the address back;
5877
+ Clavarium trades it for a token and never sees a password. */
5878
+ const MAILBOX_PROVIDER = { google: 'Google', microsoft: 'Microsoft' };
5879
+ const setMailboxProvider = (provider) => {
5880
+ const form = $('mailbox-new');
5881
+ form.dataset.provider = provider;
5882
+ for (const b of $('mailbox-provider').querySelectorAll('button')) b.setAttribute('aria-pressed', String(b.dataset.provider === provider));
5883
+ const oauth = provider !== 'imap';
5884
+ form.querySelector('.mailbox-imap').hidden = oauth;
5885
+ form.querySelector('.mailbox-oauth').hidden = !oauth;
5886
+ $('mailbox-paste').hidden = true;
5887
+ $('mailbox-error').hidden = true;
5888
+ if (oauth) {
5889
+ const who = MAILBOX_PROVIDER[provider];
5890
+ $('mailbox-notice').textContent = `Clavarium signs in as Thunderbird — that is what ${who} will see. You sign in in your own browser; Clavarium never sees your password.`;
5891
+ $('mailbox-open').textContent = `Open the ${who} sign-in page`;
5892
+ $('mailbox-email').placeholder = provider === 'google' ? 'your Gmail address' : 'your Microsoft address';
5893
+ }
5894
+ };
5895
+ for (const b of $('mailbox-provider').querySelectorAll('button')) b.addEventListener('click', () => setMailboxProvider(b.dataset.provider));
5896
+ $('mailbox-open').addEventListener('click', async () => {
5897
+ $('mailbox-error').hidden = true;
5898
+ const btn = $('mailbox-open'); btn.disabled = true;
5899
+ try {
5900
+ const { url } = await post(`${API}/mailboxes/consent`, { name: $('mailbox-name').value.trim(), provider: $('mailbox-new').dataset.provider, user: $('mailbox-email').value.trim() });
5901
+ window.open(url, '_blank', 'noopener');
5902
+ $('mailbox-paste').hidden = false;
5903
+ $('mailbox-code').focus();
5904
+ } catch (error) { $('mailbox-error').textContent = error.message; $('mailbox-error').hidden = false; }
5905
+ btn.disabled = false;
5906
+ });
5907
+ $('mailbox-connect').addEventListener('click', async () => {
5908
+ $('mailbox-error').hidden = true;
5909
+ const btn = $('mailbox-connect'); const was = btn.textContent; btn.disabled = true; btn.textContent = 'Connecting...';
5910
+ try {
5911
+ await post(`${API}/mailboxes/connect`, { redirected: $('mailbox-code').value.trim() });
5912
+ assetOpen = `mailbox:${$('mailbox-name').value.trim()}`; assetsAdding = '';
5913
+ $('mailbox-new').reset(); setMailboxProvider('imap');
5914
+ } catch (error) { $('mailbox-error').textContent = error.message; $('mailbox-error').hidden = false; }
5915
+ btn.disabled = false; btn.textContent = was;
5916
+ await paintAssets();
5917
+ });
5874
5918
  $('list-new').addEventListener('submit', async (event) => {
5875
5919
  event.preventDefault();
5876
5920
  $('assets-error').hidden = true;
package/web/index.html CHANGED
@@ -516,16 +516,33 @@
516
516
  </div>
517
517
  <div id="mailbox-box" class="as-form" data-kind="mailbox"><h3>New mailbox</h3>
518
518
  <div class="hint">Recent messages as files, read only. <details class="more"><summary>Before attaching it</summary><span>Kept up to date in a folder a conversation can read and never write. The mailbox itself is never changed. Mail is written by strangers: attach it only where the tool may read what anyone can send you.</span></details></div>
519
- <form id="mailbox-new" autocomplete="off">
519
+ <form id="mailbox-new" autocomplete="off" data-provider="imap">
520
520
  <label for="mailbox-name">Folder name</label>
521
521
  <input id="mailbox-name" maxlength="32" pattern="[a-z]([a-z0-9-]{0,30}[a-z0-9])?" placeholder="inbox" spellcheck="false" autocapitalize="off" required>
522
- <label for="mailbox-host">Mail server (IMAP, TLS)</label>
523
- <div class="row"><input id="mailbox-host" placeholder="imap.example.com" spellcheck="false" autocapitalize="off" required><input id="mailbox-port" inputmode="numeric" placeholder="993" aria-label="Port" size="5"></div>
524
- <label for="mailbox-user">User</label>
525
- <input id="mailbox-user" spellcheck="false" autocapitalize="off" autocomplete="off" required>
526
- <label for="mailbox-password">Password</label>
527
- <div class="row"><input id="mailbox-password" type="password" autocomplete="new-password" required>
528
- <button type="submit" class="primary">Add</button></div>
522
+ <div id="mailbox-provider" class="choices" role="group" aria-label="Kind of mailbox">
523
+ <button type="button" data-provider="google">Gmail</button>
524
+ <button type="button" data-provider="microsoft">Microsoft</button>
525
+ <button type="button" data-provider="imap" aria-pressed="true">IMAP</button>
526
+ </div>
527
+ <div class="mailbox-imap">
528
+ <label for="mailbox-host">Mail server (IMAP, TLS)</label>
529
+ <div class="row"><input id="mailbox-host" placeholder="imap.example.com" spellcheck="false" autocapitalize="off"><input id="mailbox-port" inputmode="numeric" placeholder="993" aria-label="Port" size="5"></div>
530
+ <label for="mailbox-user">User</label>
531
+ <input id="mailbox-user" spellcheck="false" autocapitalize="off" autocomplete="off">
532
+ <label for="mailbox-password">Password</label>
533
+ <div class="row"><input id="mailbox-password" type="password" autocomplete="new-password">
534
+ <button type="submit" class="primary">Add</button></div>
535
+ </div>
536
+ <div class="mailbox-oauth" hidden>
537
+ <label for="mailbox-email">Email address</label>
538
+ <input id="mailbox-email" type="email" spellcheck="false" autocapitalize="off" autocomplete="off" placeholder="your email address">
539
+ <p class="hint" id="mailbox-notice"></p>
540
+ <div class="row"><button type="button" id="mailbox-open" class="primary">Open the sign-in page</button></div>
541
+ <div id="mailbox-paste" hidden>
542
+ <label for="mailbox-code">After you allow, the page will not load — copy its full address and paste it here</label>
543
+ <div class="row"><input id="mailbox-code" spellcheck="false" autocapitalize="off" placeholder="http://127.0.0.1..."><button type="button" id="mailbox-connect" class="primary">Connect</button></div>
544
+ </div>
545
+ </div>
529
546
  <p id="mailbox-error" class="error" role="alert" hidden></p>
530
547
  </form>
531
548
  </div>
package/web/style.css CHANGED
@@ -222,6 +222,12 @@ footer button.careful { border-style: dashed; color: var(--ink2); }
222
222
  .auto-send label:not(.check) { display: flex; flex-direction: column; gap: 4px; }
223
223
  #mailbox-new input, #git-new input { min-width: 0; min-height: 40px; font: .875rem var(--sans); color: var(--ink); background: var(--bg); border: 1px solid var(--line); border-radius: 7px; padding: 7px 9px; }
224
224
  #mailbox-new .row input, #git-new .row input { flex: 1; }
225
+ #mailbox-provider { margin: 10px 0; }
226
+ #mailbox-provider button[aria-pressed="true"] { border-color: var(--brass); color: var(--brass-ink); background: rgba(210, 169, 78, .16); }
227
+ /* The provider sections stack their fields like the form itself (a flex column);
228
+ :not([hidden]) keeps the hidden attribute winning when a section is off. */
229
+ .mailbox-imap:not([hidden]), .mailbox-oauth:not([hidden]), #mailbox-paste:not([hidden]) { display: flex; flex-direction: column; gap: 6px; }
230
+ #mailbox-new #mailbox-notice { margin: 8px 0; }
225
231
  #mailbox-new #mailbox-port { flex: 0 0 90px; }
226
232
  #mailbox-new label, #git-new label { font-size: .8125rem; color: var(--muted, inherit); margin-top: 4px; }
227
233