clavarium 0.2.438-next.1 → 0.2.439-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.438-next.1",
3
+ "version": "0.2.439-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.438-next.1",
9
+ "version": "0.2.439-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.438-next.1",
3
+ "version": "0.2.439-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
package/server/api.mjs CHANGED
@@ -187,6 +187,7 @@ import { transcribe, AUDIO_MAX } from './voice.mjs';
187
187
  import { FILE_MAX } from './setup.mjs';
188
188
  import { demandeView } from './demandes.mjs';
189
189
  import { mcpAdd, mcpImport, mcpRefresh, mcpRights, mcpSeen, forgetKey } from './mcpx.mjs';
190
+ import { BACK_PATH, backPage } from './mcpoauth.mjs';
190
191
 
191
192
  const BODY_MAX = 16 * 1024;
192
193
  /* A setup file travels inside the JSON of a request: room for it, escaped. */
@@ -523,6 +524,15 @@ export async function handleApi(request, response, conversations, headers, resou
523
524
  if (paired && sharing) return send(200, sharing.devices.of(decodeURIComponent(paired[1]))), true;
524
525
  const sending = /^\/api\/conversations\/([^/]+)\/git\/([a-z0-9-]{1,32})\/auto$/.exec(pathname);
525
526
  if (sending && gitKeeper) return send(200, gitKeeper.auto(sending[2], decodeURIComponent(sending[1]))), true;
527
+ /* Back from signing in to an external MCP server (mcpoauth.mjs): the owner's browser, sent here by the
528
+ provider. A page, not JSON; its state is the proof it was started from this page. */
529
+ if (pathname === BACK_PATH && tethers?.oauth) {
530
+ let page;
531
+ try { const done = await tethers.oauth.finish({ tethers }, { code: query.get('code'), state: query.get('state'), error: query.get('error') }); page = backPage({ ok: true, title: done.title }); }
532
+ catch (error) { page = backPage({ ok: false, message: error instanceof Refusal ? error.message : 'The sign-in failed.' }); }
533
+ response.writeHead(200, { ...headers, 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' }).end(page);
534
+ return true;
535
+ }
526
536
  return send(404, { error: 'Not found.' }), true;
527
537
  }
528
538
  if (request.method !== 'POST') return send(405, { error: 'Method not allowed.' }), true;
@@ -676,6 +686,8 @@ export async function handleApi(request, response, conversations, headers, resou
676
686
  keeper runs as the owner (person), never as an agent. */
677
687
  /* External MCP servers (mcpx.mjs): added with their key (kept host-only in the vault, Tether given its name),
678
688
  imported from a pasted mcpServers block, listed again, a conversation's rights on their tools, new tools seen. */
689
+ /* Signing in to one with OAuth: the link the owner opens ({ url }), or { need: 'client' } for a client id to paste. */
690
+ if (pathname === '/api/tether/mcp-oauth' && tethers?.oauth) return send(200, await tethers.oauth.start({ tethers }, body ?? {}, sharing?.origin?.(request.headers) ?? `http://${request.headers.host}`)), true;
679
691
  const mcpOp = /^\/api\/tether\/mcp-(add|import|refresh|rights|seen)$/.exec(pathname);
680
692
  if (mcpOp && tethers) {
681
693
  const ctx = { tethers, secrets };
package/server/main.mjs CHANGED
@@ -73,6 +73,7 @@ import { Wifi } from './wifi.mjs';
73
73
  import { MeshCentral } from './meshcentral.mjs';
74
74
  import { Binders } from './binders.mjs';
75
75
  import { Tethers } from './tethers.mjs';
76
+ import { McpOAuth } from './mcpoauth.mjs';
76
77
  import { Browsers } from './browsers.mjs';
77
78
  import { Accounts } from './accounts.mjs';
78
79
  import { ServerLogs } from './serverlogs.mjs';
@@ -492,6 +493,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
492
493
  let tethers = null;
493
494
  const browsers = new Browsers({ dataDir, store: () => tethers?.store(), log: (line) => console.log(line) });
494
495
  tethers = new Tethers({ dataDir, resources: folders, conversations: () => all.list().map((c) => c.name), secrets, dockets, browsers, connectors: { voicebox: { run: (...a) => voiceboxConnector(boxes).run(...a) }, ...(tetherConnectors ?? {}) } });
496
+ /* External MCP servers signed in with OAuth: their tokens held here, refreshed here (mcpoauth.mjs). */
497
+ tethers.oauth = new McpOAuth({ secrets });
495
498
  const stopTethers = tethers.start();
496
499
  /* Connecting a mailbox, calendar or address book by token: the consent happens
497
500
  in the owner's browser, the refresh token is kept host-only (never in a
@@ -0,0 +1,250 @@
1
+ /* SIGNING IN TO AN EXTERNAL MCP SERVER WITH OAUTH (14-11). Some services offer no key, only a sign-in. This is
2
+ * the MCP authorization spec (2025-06-18) seen from the client: the server's 401 names its protected resource
3
+ * metadata (RFC 9728), that names its authorization server, whose metadata (RFC 8414) gives the endpoints; a
4
+ * client is registered by itself where the server offers it (RFC 7591), else the owner pastes a client id; then
5
+ * an authorization code with PKCE (S256), the `resource` said at each step (RFC 8707), and refresh tokens.
6
+ *
7
+ * WHO DOES WHAT. The owner allows it in their own browser, from a link the Access page opens; the provider
8
+ * sends the browser back to THIS server's own address (/api/tether/mcp-oauth/back, behind the same sign-in as
9
+ * the page), which trades the code. Nothing to paste.
10
+ *
11
+ * THE TOKENS STAY HERE, like a key: one host-only secret of the vault (secrets.mjs: never put in a machine,
12
+ * never listed on the page), named MCP_<ID>_TOK, holding the access token, the refresh token and what is needed
13
+ * to refresh. Tether is handed only that NAME; when its connector asks for it (tethers.mjs, reveal), access()
14
+ * answers a fresh access token, refreshed here first when it is near its end. No token is ever logged, said in
15
+ * an error or returned by a route.
16
+ *
17
+ * `fetch` is injected, so the tests run against a fake authorization server with no network. */
18
+ import { Refusal } from './conversations.mjs';
19
+ import { pkcePair, newState } from './oauth.mjs';
20
+ import { KEY_PREFIX, keyName, oauthName } from './mcpx.mjs';
21
+
22
+ export const TOKEN_SUFFIX = '_TOK';
23
+ export const BACK_PATH = '/api/tether/mcp-oauth/back';
24
+ const PROTOCOL = '2025-06-18';
25
+ const PENDING_MS = 10 * 60_000;
26
+ const PENDING_MAX = 20;
27
+ const FETCH_MS = 15_000;
28
+ /* Refreshed this long before its end: a call that starts now still has a valid token when it lands. */
29
+ const EARLY_MS = 60_000;
30
+ const KIND = 'mcp-oauth';
31
+
32
+ /* The vault's name for a server's tokens: as long as its key's name, so every server id fits. */
33
+ export const tokenName = oauthName;
34
+ export const isTokenName = (name) => typeof name === 'string' && name.startsWith(KEY_PREFIX) && name.endsWith(TOKEN_SUFFIX);
35
+
36
+ const oneLine = (x, n = 200) => String(x ?? '').replace(/[\r\n\0]/g, ' ').trim().slice(0, n);
37
+
38
+ /* https only, but plain http where the owner allowed it for that server (a local network), or on this machine. */
39
+ function safeUrl(raw, allowHttp) {
40
+ let u;
41
+ try { u = new URL(String(raw ?? '')); } catch { return null; }
42
+ if (u.username || u.password || u.hash) return null;
43
+ const local = u.hostname === '127.0.0.1' || u.hostname === 'localhost' || u.hostname === '[::1]';
44
+ if (u.protocol === 'https:' || (u.protocol === 'http:' && (allowHttp || local))) return u;
45
+ return null;
46
+ }
47
+
48
+ /* The resource a metadata names is this server: its origin, and its path or a parent of it. */
49
+ function sameResource(server, resource) {
50
+ let r;
51
+ try { r = new URL(String(resource)); } catch { return false; }
52
+ const path = r.pathname.replace(/\/+$/, '');
53
+ return r.origin === server.origin && (!path || server.pathname === path || server.pathname.startsWith(`${path}/`) || server.pathname === `${path}/`);
54
+ }
55
+
56
+ /* One field of a WWW-Authenticate: Bearer header, quoted or not. */
57
+ function authParam(header, key) {
58
+ const m = new RegExp(`(?:^|[\\s,])${key}\\s*=\\s*(?:"([^"]*)"|([^\\s,]+))`, 'i').exec(String(header ?? ''));
59
+ return m ? (m[1] ?? m[2]) : '';
60
+ }
61
+
62
+ /* The well-known addresses to try for a URL with a path (RFC 8414 / RFC 9728: inserted before the path). */
63
+ function wellKnown(base, suffix) {
64
+ const u = new URL(base);
65
+ const path = u.pathname.replace(/\/+$/, '');
66
+ return path ? [`${u.origin}/.well-known/${suffix}${path}`, `${u.origin}/.well-known/${suffix}`] : [`${u.origin}/.well-known/${suffix}`];
67
+ }
68
+
69
+ export class McpOAuth {
70
+ #secrets; #fetch; #now; #pending = new Map(); #refreshing = new Map();
71
+
72
+ constructor({ secrets, fetch = globalThis.fetch, now = () => Date.now() }) {
73
+ this.#secrets = secrets; this.#fetch = fetch; this.#now = now;
74
+ }
75
+
76
+ async #get(url, init = {}) {
77
+ const abort = new AbortController();
78
+ const timer = setTimeout(() => abort.abort(), FETCH_MS); timer.unref?.();
79
+ try { return await this.#fetch(url, { redirect: 'manual', ...init, signal: abort.signal }); }
80
+ finally { clearTimeout(timer); }
81
+ }
82
+ async #json(url, allowHttp) {
83
+ if (!safeUrl(url, allowHttp)) return null;
84
+ let res;
85
+ try { res = await this.#get(url, { headers: { accept: 'application/json', 'mcp-protocol-version': PROTOCOL } }); } catch { return null; }
86
+ if (!res.ok) return null;
87
+ try { const j = await res.json(); return j && typeof j === 'object' && !Array.isArray(j) ? j : null; } catch { return null; }
88
+ }
89
+
90
+ /* FROM THE SERVER'S ADDRESS TO ITS AUTHORIZATION SERVER: { resource, meta, scope }. */
91
+ async discover(serverUrl, { allowHttp = false } = {}) {
92
+ const server = safeUrl(serverUrl, allowHttp);
93
+ if (!server) throw new Refusal(400, 'The server\'s address must be https.');
94
+ /* Asked as a client would, without a token: an OAuth server answers 401 and says where its metadata is. */
95
+ let res;
96
+ try {
97
+ res = await this.#get(server.href, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'mcp-protocol-version': PROTOCOL },
98
+ body: JSON.stringify({ jsonrpc: '2.0', id: 'clv-oauth', method: 'initialize', params: { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: 'Clavarium', version: '1' } } }) });
99
+ } catch { throw new Refusal(502, 'The server could not be reached.'); }
100
+ try { await res.body?.cancel?.(); } catch { /* nothing to read */ }
101
+ if (res.ok) throw new Refusal(409, 'This server answers without signing in: no OAuth needed.');
102
+ const challenge = res.status === 401 ? String(res.headers.get('www-authenticate') ?? '') : '';
103
+ const scope = oneLine(authParam(challenge, 'scope'), 1000);
104
+ const named = authParam(challenge, 'resource_metadata');
105
+ const tries = [...(named ? [named] : []), ...wellKnown(server.href, 'oauth-protected-resource')];
106
+ let prm = null;
107
+ for (const at of tries) { prm = await this.#json(at, allowHttp); if (prm) break; }
108
+ /* The metadata must be about this server (RFC 9728 s.3.3): another resource's would send its token here. */
109
+ if (prm?.resource && !sameResource(server, prm.resource)) throw new Refusal(502, 'The server\'s metadata names another address: refused.');
110
+ /* An older server (MCP 2025-03-26) has no such metadata: its own origin is its authorization server. */
111
+ const issuer = Array.isArray(prm?.authorization_servers) && prm.authorization_servers.length ? String(prm.authorization_servers[0]) : server.origin;
112
+ if (!safeUrl(issuer, allowHttp)) throw new Refusal(502, 'The server\'s sign-in address is not https.');
113
+ let meta = null;
114
+ for (const at of [...wellKnown(issuer, 'oauth-authorization-server'), ...wellKnown(issuer, 'openid-configuration'), `${issuer.replace(/\/+$/, '')}/.well-known/openid-configuration`]) {
115
+ meta = await this.#json(at, allowHttp); if (meta) break;
116
+ }
117
+ if (!meta || !safeUrl(meta.authorization_endpoint, allowHttp) || !safeUrl(meta.token_endpoint, allowHttp)) throw new Refusal(502, 'This server does not say how to sign in (no OAuth metadata).');
118
+ if (Array.isArray(meta.code_challenge_methods_supported) && !meta.code_challenge_methods_supported.includes('S256')) throw new Refusal(502, 'This server does not offer PKCE (S256): refused.');
119
+ const resource = oneLine(prm?.resource || server.href, 1000);
120
+ return { resource, meta, scope: scope || (Array.isArray(prm?.scopes_supported) ? prm.scopes_supported.map(String).join(' ').slice(0, 1000) : '') };
121
+ }
122
+
123
+ /* A client registered by itself (RFC 7591), public (no secret) where the server allows it. */
124
+ async #register(meta, redirectUri, allowHttp) {
125
+ if (!safeUrl(meta.registration_endpoint, allowHttp)) return null;
126
+ let res;
127
+ try {
128
+ res = await this.#get(meta.registration_endpoint, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' },
129
+ body: JSON.stringify({ client_name: 'Clavarium', redirect_uris: [redirectUri], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none' }) });
130
+ } catch { throw new Refusal(502, 'The server\'s registration could not be reached.'); }
131
+ const j = await res.json().catch(() => null);
132
+ if (!res.ok || !j?.client_id) throw new Refusal(502, `The server refused to register this Clavarium (HTTP ${res.status}).`);
133
+ return { clientId: oneLine(j.client_id, 500), clientSecret: typeof j.client_secret === 'string' ? j.client_secret : '' };
134
+ }
135
+
136
+ /* START: { target, clientId?, clientSecret? } and this server's address -> { url } to open, or { need: 'client' }
137
+ when the server registers no client by itself (the page then asks for its id). */
138
+ async start({ tethers }, body = {}, origin = '') {
139
+ const t = tethers.store().target(String(body.target ?? ''));
140
+ if (!t || t.kind !== 'mcp') throw new Refusal(404, 'No such MCP server.');
141
+ const allowHttp = t.config?.allowHttp === true;
142
+ const back = safeUrl(`${String(origin).replace(/\/+$/, '')}${BACK_PATH}`, true);
143
+ if (!back) throw new Refusal(500, 'This server does not know its own address.');
144
+ const redirectUri = back.href;
145
+ const { resource, meta, scope } = await this.discover(t.config?.url, { allowHttp });
146
+ let client = null;
147
+ const given = oneLine(body.clientId, 500);
148
+ if (given) client = { clientId: given, clientSecret: typeof body.clientSecret === 'string' ? body.clientSecret.trim() : '' };
149
+ else client = await this.#register(meta, redirectUri, allowHttp);
150
+ if (!client) return { need: 'client' };
151
+ this.#sweep();
152
+ if (this.#pending.size >= PENDING_MAX) throw new Refusal(429, 'Too many sign-ins in progress; try again shortly.');
153
+ const state = newState();
154
+ const { verifier, challenge } = pkcePair();
155
+ const url = new URL(meta.authorization_endpoint);
156
+ const ask = { response_type: 'code', client_id: client.clientId, redirect_uri: redirectUri, state, code_challenge: challenge, code_challenge_method: 'S256', resource, ...(scope ? { scope } : {}) };
157
+ for (const [k, v] of Object.entries(ask)) url.searchParams.set(k, v);
158
+ const methods = Array.isArray(meta.token_endpoint_auth_methods_supported) ? meta.token_endpoint_auth_methods_supported : [];
159
+ const auth = !client.clientSecret ? 'none' : methods.includes('client_secret_post') || !methods.length ? 'post' : 'basic';
160
+ this.#pending.set(state, { target: t.id, title: t.title, url: t.config.url, allowHttp, redirectUri, verifier, resource, scope, token: meta.token_endpoint, ...client, auth, at: this.#now() });
161
+ return { url: url.href };
162
+ }
163
+
164
+ #sweep() { for (const [k, p] of this.#pending) if (this.#now() - p.at > PENDING_MS) this.#pending.delete(k); }
165
+
166
+ /* The token endpoint, by the client's way of proving itself. Never says back what it was sent or answered. */
167
+ async #token(rec, params, allowHttp) {
168
+ if (!safeUrl(rec.token, allowHttp)) throw new Refusal(502, 'The sign-in address is not https.');
169
+ const form = new URLSearchParams({ ...params, ...(rec.resource ? { resource: rec.resource } : {}) });
170
+ const headers = { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' };
171
+ if (rec.auth === 'basic') headers.authorization = `Basic ${Buffer.from(`${encodeURIComponent(rec.clientId)}:${encodeURIComponent(rec.clientSecret)}`).toString('base64')}`;
172
+ else { form.set('client_id', rec.clientId); if (rec.auth === 'post') form.set('client_secret', rec.clientSecret); }
173
+ let res;
174
+ try { res = await this.#get(rec.token, { method: 'POST', headers, body: form.toString() }); } catch { throw new Refusal(502, 'The sign-in server could not be reached.'); }
175
+ const j = await res.json().catch(() => null);
176
+ if (!res.ok || typeof j?.access_token !== 'string' || !j.access_token) {
177
+ const why = /^[a-z_]{1,40}$/.test(String(j?.error ?? '')) ? j.error : `HTTP ${res.status}`;
178
+ throw Object.assign(new Refusal(502, `The sign-in server refused (${why}).`), { grant: why === 'invalid_grant' });
179
+ }
180
+ if (/[\r\n]/.test(j.access_token)) throw new Refusal(502, 'The sign-in server answered a token that is not one line.');
181
+ const life = Number(j.expires_in);
182
+ return { access: j.access_token, refresh: typeof j.refresh_token === 'string' && j.refresh_token ? j.refresh_token : '', expiresAt: life > 0 ? this.#now() + life * 1000 : null };
183
+ }
184
+
185
+ #keep(name, rec) {
186
+ const { access, refresh, expiresAt, token, clientId, clientSecret, auth, resource, allowHttp } = rec;
187
+ this.#secrets.set({ name, value: JSON.stringify({ kind: KIND, access, refresh, expiresAt, token, clientId, clientSecret, auth, resource, allowHttp }), hostOnly: true });
188
+ }
189
+ #open(name) {
190
+ let raw;
191
+ try { raw = this.#secrets.reveal(name); } catch { return null; }
192
+ if (typeof raw !== 'string') return null;
193
+ try { const r = JSON.parse(raw); return r?.kind === KIND ? r : null; } catch { return null; }
194
+ }
195
+
196
+ /* BACK FROM THE PROVIDER (the owner's browser, /api/tether/mcp-oauth/back?code&state): trade the code, keep the
197
+ tokens host-only, and point the server's target at them. -> { target, title }. */
198
+ async finish({ tethers }, { code, state, error } = {}) {
199
+ this.#sweep();
200
+ const p = state ? this.#pending.get(String(state)) : null;
201
+ if (!p) throw new Refusal(400, 'This sign-in has expired or was already used; start it again.');
202
+ this.#pending.delete(String(state));
203
+ if (error) throw new Refusal(400, /^[a-z_]{1,40}$/.test(String(error)) ? `The sign-in was not allowed (${error}).` : 'The sign-in was not allowed.');
204
+ if (!code) throw new Refusal(400, 'The provider sent back no code.');
205
+ const got = await this.#token(p, { grant_type: 'authorization_code', code: String(code), redirect_uri: p.redirectUri, code_verifier: p.verifier }, p.allowHttp);
206
+ const name = tokenName(p.target);
207
+ this.#keep(name, { ...p, ...got });
208
+ const before = tethers.store().target(p.target);
209
+ /* Its key, if it had one kept here, is no longer used: it goes. The header for a key goes too (a token is Bearer). */
210
+ const r = await tethers.act('mcp-add', { id: p.target, name: before?.title ?? p.title, url: before?.config?.url ?? p.url, secret: name, ...(p.allowHttp ? { allowHttp: true } : {}) }, '');
211
+ if (!r.ok) throw new Refusal(400, 'Signed in, but the server could not be set again.');
212
+ if (before?.secrets?.token === keyName(p.target)) { try { this.#secrets.remove(keyName(p.target)); } catch { /* not there */ } }
213
+ return { target: p.target, title: before?.title ?? p.title };
214
+ }
215
+
216
+ /* THE CONNECTOR'S TOKEN (tethers.mjs, reveal): a fresh access token for a name of ours, refreshed first when near
217
+ its end; undefined for any other secret (revealed as it is). One refresh at a time per server. */
218
+ async access(name) {
219
+ if (!isTokenName(name)) return undefined;
220
+ const rec = this.#open(name);
221
+ if (!rec) return undefined;
222
+ if (!rec.expiresAt || rec.expiresAt - EARLY_MS > this.#now()) return rec.access;
223
+ if (!rec.refresh) throw new Error('signed out of this server: sign in again in Assets > Access');
224
+ let running = this.#refreshing.get(name);
225
+ if (!running) {
226
+ running = (async () => {
227
+ try {
228
+ const got = await this.#token(rec, { grant_type: 'refresh_token', refresh_token: rec.refresh }, rec.allowHttp);
229
+ /* A server that rotates refresh tokens sends a new one; one that does not keeps the old one valid. */
230
+ this.#keep(name, { ...rec, ...got, refresh: got.refresh || rec.refresh });
231
+ return got.access;
232
+ } catch (e) {
233
+ if (e?.grant) throw new Error('signed out of this server: sign in again in Assets > Access');
234
+ throw new Error(`could not refresh the sign-in: ${e?.message ?? 'failed'}`);
235
+ } finally { this.#refreshing.delete(name); }
236
+ })();
237
+ this.#refreshing.set(name, running);
238
+ }
239
+ return running;
240
+ }
241
+ }
242
+
243
+ /* The page the owner's browser lands on: said plainly, nothing to copy, no script. */
244
+ export function backPage({ ok, title = '', message = '' }) {
245
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
246
+ const said = ok ? `Signed in to ${esc(title)}. You can close this tab.` : esc(message || 'The sign-in failed.');
247
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Clavarium</title>`
248
+ + '<style>body{font:16px/1.5 system-ui,sans-serif;margin:0;padding:48px 16px;background:#fff;color:#222}@media (prefers-color-scheme: dark){body{background:#16181c;color:#eee}}main{max-width:32rem;margin:auto}</style>'
249
+ + `</head><body><main><p>${said}</p></main></body></html>`;
250
+ }
package/server/mcpx.mjs CHANGED
@@ -56,7 +56,8 @@ export async function mcpAdd({ tethers, secrets }, body = {}) {
56
56
  const had = known(secrets, ref);
57
57
  /* Its key, in the vault, host-only: Tether gets its name. None given: the one it had, or none. */
58
58
  let secret = '';
59
- if (key) { secrets.set({ name: ref, value: key, hostOnly: true }); secret = ref; }
59
+ /* A key given where it was signed in with OAuth: the key replaces the tokens, which go. */
60
+ if (key) { secrets.set({ name: ref, value: key, hostOnly: true }); secret = ref; if (before?.secrets?.token === oauthName(id)) { try { secrets.remove(oauthName(id)); } catch { /* not there */ } } }
60
61
  else if (before?.secrets?.token) secret = String(before.secrets.token);
61
62
  const r = await tethers.act('mcp-add', { id, name, url, ...(secret ? { secret } : {}), ...(body.header ? { header: String(body.header) } : {}), ...(body.allowHttp === true ? { allowHttp: true } : {}) }, '');
62
63
  if (!r.ok) {
@@ -146,9 +147,12 @@ export async function mcpSeen({ tethers }, body = {}) {
146
147
  return { seen: Array.isArray(r.data?.seen) ? r.data.seen : [] };
147
148
  }
148
149
 
149
- /* A server taken away: its key goes with it (only the one kept for it here). */
150
+ /* The vault's name for a server's OAuth tokens (mcpoauth.mjs): as long as its key's name. */
151
+ export const oauthName = (id) => `${keyName(id).slice(0, -KEY_SUFFIX.length)}_TOK`;
152
+
153
+ /* A server taken away: its key goes with it, or its OAuth tokens (only those kept for it here). */
150
154
  export function forgetKey(secrets, target) {
151
155
  const ref = target?.kind === 'mcp' ? String(target.secrets?.token ?? '') : '';
152
- if (!ref || ref !== keyName(target.id)) return;
156
+ if (!ref || (ref !== keyName(target.id) && ref !== oauthName(target.id))) return;
153
157
  try { secrets?.remove(ref); } catch { /* not there */ }
154
158
  }
@@ -176,6 +176,7 @@ export const SETTINGS_WORDS_FR = {
176
176
  'set-mcp-need': 'Collez le bloc, ou donnez nom et adresse.', 'set-mcp-tools': 'Outils', 'set-mcp-refresh': 'Actualiser', 'set-mcp-seen': 'Marquer comme vu',
177
177
  'set-mcp-none': 'Aucun outil listé pour l\'instant.', 'set-mcp-unreached': 'Injoignable : {why}', 'set-mcp-open': 'atteint l\'extérieur',
178
178
  'set-mcp-fresh': 'Nouveau : demandé jusqu\'à ce que vous l\'ayez vu',
179
+ 'set-mcp-oauth': 'Se connecter (OAuth)', 'set-mcp-client': 'Identifiant client', 'set-mcp-client-need': 'Collez son identifiant client.',
179
180
  'set-mcp-c-read': 'Lecture seule', 'set-mcp-c-write': 'Écrit', 'set-mcp-c-destructive': 'Supprime ou écrase',
180
181
  'set-mcp-custom': 'Droits personnalisés', 'set-mcp-yes': 'Oui', 'set-mcp-ask': 'Demander', 'set-mcp-no': 'Non',
181
182
  'set-rt-mcp-none': 'Coupé', 'set-rt-mcp-watch': 'Lit', 'set-rt-mcp-propose': 'Tout, approuvé', 'set-rt-mcp-free': 'Tout', 'set-rt-mcp-frame': 'Personnalisé',
@@ -113,6 +113,9 @@ export class Tethers {
113
113
  {kind, text, data}) } (dockets.mjs): what wakes an agent told of a notice. `make`: the keeper (tests). */
114
114
  /* `browsers`: the paired browsers (browsers.mjs), set by the constructor when it is given one; their connector is the keeper's `browser`. */
115
115
  browsers = null;
116
+ /* Set by the server (main.mjs): the OAuth sign-ins of external MCP servers (mcpoauth.mjs), whose tokens the
117
+ keeper reveals fresh. */
118
+ oauth = null;
116
119
  constructor({ dataDir, resources, conversations, secrets, connectors, browsers = null, dockets = null, now = () => Date.now(), make = keeper }) {
117
120
  if (browsers) { connectors = { ...(connectors ?? {}), browser: browsers.connector }; this.browsers = browsers; }
118
121
  this.#resources = resources; this.#conversations = conversations; this.#secrets = secrets; this.#dockets = dockets;
@@ -245,6 +248,9 @@ export class Tethers {
245
248
  /* A secret's value for a connector, by name, from this server's vault; never seen by the agent.
246
249
  An unknown or expired secret is a plain refusal the connector turns into "Refused". */
247
250
  async #reveal(name) {
251
+ /* An MCP server signed in with OAuth (mcpoauth.mjs): its current access token, refreshed here when due. */
252
+ const fresh = await this.oauth?.access?.(name);
253
+ if (fresh !== undefined) return fresh;
248
254
  const value = this.#secrets?.reveal?.(name);
249
255
  if (value === undefined || value === null) throw new Error(`no secret named "${name}" on this server`);
250
256
  return value;
package/web/app.js CHANGED
@@ -5566,6 +5566,23 @@
5566
5566
  catch (error) { sayAsErr(error); }
5567
5567
  await repaintAsset();
5568
5568
  });
5569
+ /* Signed in with OAuth where the service offers no key (mcpoauth.mjs): the consent in a new tab, back here by
5570
+ itself. A server that registers no client by itself asks for its client id once. */
5571
+ const oauth = el('button', '', uiSaid('set-mcp-oauth', 'Sign in with OAuth')); oauth.type = 'button'; oauth.dataset.act = 'mcp-oauth';
5572
+ const clientRow = el('div', 'set-row mcp-client'); clientRow.hidden = true;
5573
+ const clientId = el('input'); clientId.type = 'text'; clientId.autocomplete = 'off'; clientId.spellcheck = false;
5574
+ clientId.setAttribute('aria-label', uiSaid('set-mcp-client', 'Client id'));
5575
+ clientId.placeholder = uiSaid('set-mcp-client', 'Client id');
5576
+ clientRow.append(el('span', '', uiSaid('set-mcp-client-need', 'Paste its client id.')), clientId);
5577
+ oauth.addEventListener('click', async () => {
5578
+ oauth.disabled = true; $(asErrId()).hidden = true;
5579
+ try {
5580
+ const r = await post(`${API}/tether/mcp-oauth`, { target: t.id, ...(clientId.value.trim() ? { clientId: clientId.value.trim() } : {}) });
5581
+ if (r?.need === 'client') { clientRow.hidden = false; clientId.focus(); }
5582
+ else if (r?.url) window.open(r.url, '_blank', 'noopener');
5583
+ } catch (error) { sayAsErr(error); }
5584
+ oauth.disabled = false;
5585
+ });
5569
5586
  const fresh = tools.filter((x) => x.fresh === true);
5570
5587
  const seen = fresh.length ? el('button', '', uiSaid('set-mcp-seen', 'Mark as seen')) : null;
5571
5588
  if (seen) {
@@ -5590,7 +5607,8 @@
5590
5607
  const body = [];
5591
5608
  if (t.catalog?.error) body.push(el('p', 'error', uiSaid('set-mcp-unreached', 'Not reached: {why}', { why: t.catalog.error })));
5592
5609
  body.push(tools.length ? list : el('p', 'hint', uiSaid('set-mcp-none', 'No tools listed yet.')));
5593
- out.push({ title: uiSaid('set-mcp-tools', 'Tools'), extra: [seen, refresh], body, cls: 'as-mcp-tools' });
5610
+ body.push(clientRow);
5611
+ out.push({ title: uiSaid('set-mcp-tools', 'Tools'), extra: [seen, oauth, refresh], body, cls: 'as-mcp-tools' });
5594
5612
  /* Custom: each kind of tool Yes / Ask / No, for each conversation set to it. */
5595
5613
  const custom = Object.entries(t.grants ?? {}).filter(([id, g]) => id.startsWith('conversation:') && g?.level === 'frame');
5596
5614
  if (custom.length) {