@articul8/bivia-mcp 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/oauth.js ADDED
@@ -0,0 +1,910 @@
1
+ // @articul8/bivia-mcp — OAuth 2.1 + PKCE + Dynamic Client Registration &
2
+ // local credential store (~/.bivia/credentials.json).
3
+ //
4
+ // Zero runtime dependencies (Node 18+ built-ins only).
5
+ // Shares ~/.bivia/credentials.json with @articul8/bivia-cli and the Go `bivia` CLI.
6
+
7
+ import crypto from "node:crypto";
8
+ import fs from "node:fs";
9
+ import http from "node:http";
10
+ import os from "node:os";
11
+ import path from "node:path";
12
+ import { spawn } from "node:child_process";
13
+
14
+ export const DEFAULT_BASE = "https://api.articul8.ai/bivia";
15
+
16
+ export class OAuthError extends Error {
17
+ constructor(message, code) {
18
+ super(message);
19
+ this.name = "OAuthError";
20
+ this.code = code || "oauth_error";
21
+ }
22
+ }
23
+
24
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
25
+
26
+ export function biviaConfigDir() {
27
+ if (process.env.BIVIA_CONFIG_DIR) return process.env.BIVIA_CONFIG_DIR;
28
+ return path.join(os.homedir(), ".bivia");
29
+ }
30
+
31
+ export function credentialsPath() {
32
+ return path.join(biviaConfigDir(), "credentials.json");
33
+ }
34
+
35
+ export function credentialsLockPath() {
36
+ return path.join(biviaConfigDir(), "credentials.lock");
37
+ }
38
+
39
+ export function oauthClientsPath() {
40
+ return path.join(biviaConfigDir(), "oauth_clients.json");
41
+ }
42
+
43
+ export function configFilePath() {
44
+ return path.join(biviaConfigDir(), "config");
45
+ }
46
+
47
+ export function normalizeExpiresAt(val) {
48
+ const n = Number(val) || 0;
49
+ return n > 1e12 ? Math.floor(n / 1000) : Math.floor(n);
50
+ }
51
+
52
+ async function acquireCredentialsLock() {
53
+ const lockPath = credentialsLockPath();
54
+ const dir = biviaConfigDir();
55
+ try {
56
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
57
+ } catch {
58
+ /* ignore */
59
+ }
60
+ const deadline = Date.now() + 5000;
61
+ while (true) {
62
+ try {
63
+ const fd = fs.openSync(lockPath, "wx", 0o600);
64
+ try {
65
+ fs.writeFileSync(fd, `${process.pid}\n`);
66
+ } finally {
67
+ fs.closeSync(fd);
68
+ }
69
+ return () => {
70
+ try {
71
+ fs.unlinkSync(lockPath);
72
+ } catch {
73
+ /* ignore */
74
+ }
75
+ };
76
+ } catch {
77
+ try {
78
+ const st = fs.statSync(lockPath);
79
+ if (Date.now() - st.mtimeMs > 30_000) {
80
+ fs.unlinkSync(lockPath);
81
+ continue;
82
+ }
83
+ } catch {
84
+ /* ignore */
85
+ }
86
+ if (Date.now() >= deadline) {
87
+ return () => {};
88
+ }
89
+ await sleep(50);
90
+ }
91
+ }
92
+ }
93
+
94
+ export function loadCachedClientId(platformUrl, redirectUri) {
95
+ const plat = String(platformUrl || "").trim().replace(/\/+$/, "");
96
+ const redir = String(redirectUri || "").trim();
97
+ if (!plat) return "";
98
+ try {
99
+ const raw = fs.readFileSync(oauthClientsPath(), "utf8");
100
+ const map = JSON.parse(raw);
101
+ if (map && typeof map === "object") {
102
+ if (redir && map[`${plat}|${redir}`]) return String(map[`${plat}|${redir}`]).trim();
103
+ if (map[plat]) return String(map[plat]).trim();
104
+ }
105
+ } catch {
106
+ /* ignore */
107
+ }
108
+ const creds = loadCredentials();
109
+ if (
110
+ creds &&
111
+ creds.client_id &&
112
+ String(creds.platform_url || "").trim().replace(/\/+$/, "") === plat
113
+ ) {
114
+ return String(creds.client_id).trim();
115
+ }
116
+ return "";
117
+ }
118
+
119
+ export function saveCachedClientId(platformUrl, redirectUri, clientId) {
120
+ const plat = String(platformUrl || "").trim().replace(/\/+$/, "");
121
+ const redir = String(redirectUri || "").trim();
122
+ const cid = String(clientId || "").trim();
123
+ if (!plat || !cid) return;
124
+ try {
125
+ const dir = biviaConfigDir();
126
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
127
+ let map = {};
128
+ try {
129
+ map = JSON.parse(fs.readFileSync(oauthClientsPath(), "utf8")) || {};
130
+ } catch {
131
+ map = {};
132
+ }
133
+ if (redir) map[`${plat}|${redir}`] = cid;
134
+ map[plat] = cid;
135
+ fs.writeFileSync(oauthClientsPath(), JSON.stringify(map, null, 2) + "\n", {
136
+ mode: 0o600,
137
+ });
138
+ } catch {
139
+ /* ignore */
140
+ }
141
+ }
142
+
143
+ export function clearCachedClientId(platformUrl, redirectUri) {
144
+ const plat = String(platformUrl || "").trim().replace(/\/+$/, "");
145
+ const redir = String(redirectUri || "").trim();
146
+ if (!plat) return;
147
+ try {
148
+ const map = JSON.parse(fs.readFileSync(oauthClientsPath(), "utf8")) || {};
149
+ delete map[`${plat}|${redir}`];
150
+ delete map[plat];
151
+ fs.writeFileSync(oauthClientsPath(), JSON.stringify(map, null, 2) + "\n", {
152
+ mode: 0o600,
153
+ });
154
+ } catch {
155
+ /* ignore */
156
+ }
157
+ }
158
+
159
+ export function parseScopeMetadata(scopeStr) {
160
+ const scopes = String(scopeStr || "").trim().split(/\s+/).filter(Boolean);
161
+ let tenantId = null;
162
+ const groupIds = [];
163
+ let permission = null;
164
+ for (const s of scopes) {
165
+ const parts = s.split(":");
166
+ if (parts.length === 3 && ["read", "write", "admin"].includes(parts[2])) {
167
+ if (!tenantId) tenantId = parts[0];
168
+ if (!groupIds.includes(parts[1])) groupIds.push(parts[1]);
169
+ if (
170
+ !permission ||
171
+ parts[2] === "admin" ||
172
+ (parts[2] === "write" && permission === "read")
173
+ ) {
174
+ permission = parts[2];
175
+ }
176
+ }
177
+ }
178
+ return {
179
+ tenantId,
180
+ groupId: groupIds[0] || null,
181
+ groupIds,
182
+ permission,
183
+ scopes,
184
+ };
185
+ }
186
+
187
+ export function platformOrigin(apiBase) {
188
+ if (process.env.BIVIA_PLATFORM_URL) {
189
+ return process.env.BIVIA_PLATFORM_URL.replace(/\/+$/, "");
190
+ }
191
+ const b = String(apiBase || process.env.BIVIA_API_BASE || DEFAULT_BASE)
192
+ .trim()
193
+ .replace(/\/+$/, "");
194
+ try {
195
+ const u = new URL(b);
196
+ if (u.hostname === "api.articul8.ai") return "https://app.articul8.ai";
197
+ if (u.hostname.startsWith("api.")) {
198
+ return `${u.protocol}//app.${u.hostname.slice(4)}`;
199
+ }
200
+ if (u.hostname === "localhost" || u.hostname === "127.0.0.1") {
201
+ if (u.port === "8888" || u.port === "8902") {
202
+ return `${u.protocol}//${u.hostname}:3000`;
203
+ }
204
+ }
205
+ return u.origin;
206
+ } catch {
207
+ return "https://app.articul8.ai";
208
+ }
209
+ }
210
+
211
+ export function loadCredentials() {
212
+ try {
213
+ const raw = fs.readFileSync(credentialsPath(), "utf8");
214
+ const creds = JSON.parse(raw);
215
+ if (!creds || typeof creds !== "object") return null;
216
+ if (creds.expires_at) {
217
+ creds.expires_at = normalizeExpiresAt(creds.expires_at);
218
+ }
219
+ return creds;
220
+ } catch {
221
+ return null;
222
+ }
223
+ }
224
+
225
+ export function loadLegacyConfigKey() {
226
+ try {
227
+ const raw = fs.readFileSync(configFilePath(), "utf8");
228
+ for (const line of raw.split(/\r?\n/)) {
229
+ const trimmed = line.trim();
230
+ if (!trimmed || trimmed.startsWith("#")) continue;
231
+ const eq = trimmed.indexOf("=");
232
+ if (eq < 0) continue;
233
+ const k = trimmed.slice(0, eq).trim();
234
+ const v = trimmed
235
+ .slice(eq + 1)
236
+ .trim()
237
+ .replace(/^["']|["']$/g, "");
238
+ if ((k === "A8_API_KEY" || k === "BIVIA_API_KEY") && v) return v;
239
+ }
240
+ } catch {
241
+ /* ignore */
242
+ }
243
+ return "";
244
+ }
245
+
246
+ export function saveCredentials(creds) {
247
+ if (creds && creds.expires_at) {
248
+ creds.expires_at = normalizeExpiresAt(creds.expires_at);
249
+ }
250
+ const dir = biviaConfigDir();
251
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
252
+ fs.writeFileSync(credentialsPath(), JSON.stringify(creds, null, 2) + "\n", {
253
+ mode: 0o600,
254
+ });
255
+ // ~/.bivia/config belongs to the `bivia` CLI (its long-lived BIVIA_API_KEY / BIVIA_API_BASE, read by the
256
+ // background Turbo proxy and the guardian). OAuth tokens live only in credentials.json — never write config.
257
+ }
258
+
259
+ // A sign-in: credentials.json holds a token from an OAuth login (it carries a refresh token or a client).
260
+ // A key saved with `login --key` (method "api_key", or a bare token from older versions) is not one.
261
+ export function hasOAuthSession(creds = loadCredentials()) {
262
+ return Boolean(
263
+ creds &&
264
+ creds.access_token &&
265
+ creds.method !== "api_key" &&
266
+ (creds.refresh_token || creds.client_id)
267
+ );
268
+ }
269
+
270
+ // An API key replaces any sign-in: credentials.json then holds only the key.
271
+ export function saveApiKey(key) {
272
+ const k = cleanToken(key);
273
+ if (!k) throw new OAuthError("The API key is empty", "empty_api_key");
274
+ saveCredentials({
275
+ method: "api_key",
276
+ access_token: k,
277
+ api_base: process.env.BIVIA_API_BASE || undefined,
278
+ });
279
+ }
280
+
281
+ export function clearCredentials() {
282
+ try {
283
+ fs.unlinkSync(credentialsPath());
284
+ } catch {
285
+ /* ignore */
286
+ }
287
+ // leave ~/.bivia/config alone: it is the `bivia` CLI's saved API key, not this sign-in
288
+ }
289
+
290
+ let _mcpRefreshing = null;
291
+
292
+ export async function refreshCredentialsIfNeeded(opts = {}) {
293
+ const initial = loadCredentials();
294
+ if (!initial || !initial.refresh_token || !initial.client_id) {
295
+ return initial;
296
+ }
297
+ const nowSec = Math.floor(Date.now() / 1000);
298
+ const expSec = normalizeExpiresAt(initial.expires_at);
299
+ const expiresSoon = expSec > 0 ? nowSec + 60 >= expSec : false;
300
+ if (!opts.force && !expiresSoon) {
301
+ return initial;
302
+ }
303
+
304
+ if (_mcpRefreshing) return _mcpRefreshing;
305
+
306
+ _mcpRefreshing = (async () => {
307
+ const unlock = await acquireCredentialsLock();
308
+ try {
309
+ let creds = loadCredentials() || initial;
310
+ const diskExp = normalizeExpiresAt(creds.expires_at);
311
+ if (
312
+ (initial.access_token &&
313
+ creds.access_token &&
314
+ creds.access_token !== initial.access_token) ||
315
+ (!opts.force && diskExp > 0 && Math.floor(Date.now() / 1000) + 60 < diskExp)
316
+ ) {
317
+ return creds;
318
+ }
319
+
320
+ const plat =
321
+ creds.platform_url || platformOrigin(opts.base || creds.api_base);
322
+ const tokenEndpoint =
323
+ creds.token_endpoint || `${plat.replace(/\/+$/, "")}/api/oauth/token`;
324
+
325
+ const form = new URLSearchParams({
326
+ grant_type: "refresh_token",
327
+ refresh_token: creds.refresh_token,
328
+ client_id: creds.client_id,
329
+ });
330
+
331
+ const fetchImpl = opts.fetch || fetch;
332
+ const res = await fetchImpl(tokenEndpoint, {
333
+ method: "POST",
334
+ headers: {
335
+ "content-type": "application/x-www-form-urlencoded",
336
+ accept: "application/json",
337
+ },
338
+ body: form.toString(),
339
+ });
340
+ if (!res.ok) {
341
+ throw new OAuthError(
342
+ `OAuth token refresh failed (HTTP ${res.status})`,
343
+ "oauth_refresh_failed"
344
+ );
345
+ }
346
+ const tok = await res.json();
347
+ if (!tok || !tok.access_token) {
348
+ throw new OAuthError(
349
+ "OAuth token refresh returned no access_token",
350
+ "oauth_refresh_failed"
351
+ );
352
+ }
353
+
354
+ const updated = {
355
+ ...creds,
356
+ access_token: tok.access_token,
357
+ refresh_token: tok.refresh_token || creds.refresh_token,
358
+ token_type: tok.token_type || creds.token_type || "bearer",
359
+ scope: tok.scope || creds.scope || "",
360
+ expires_at:
361
+ Math.floor(Date.now() / 1000) + (Number(tok.expires_in) || 3600),
362
+ };
363
+ const meta = parseScopeMetadata(updated.scope);
364
+ if (meta.tenantId) updated.tenant_id = meta.tenantId;
365
+ if (meta.groupId) updated.group_id = meta.groupId;
366
+ if (meta.groupIds.length) updated.group_ids = meta.groupIds;
367
+ if (meta.permission) updated.permission = meta.permission;
368
+
369
+ saveCredentials(updated);
370
+ return updated;
371
+ } finally {
372
+ unlock();
373
+ }
374
+ })().finally(() => {
375
+ _mcpRefreshing = null;
376
+ });
377
+
378
+ return _mcpRefreshing;
379
+ }
380
+
381
+ // The key or token as sent: no "Bearer " prefix, no whitespace.
382
+ export function cleanToken(raw) {
383
+ return String(raw || "")
384
+ .trim()
385
+ .replace(/^bearer(\s+|$)/i, "")
386
+ .replace(/\s+/g, "");
387
+ }
388
+
389
+ // Only the last 4 characters of a key are ever shown, as in the browser extension.
390
+ export function maskKey(key) {
391
+ const k = cleanToken(key);
392
+ return k ? `••••${k.slice(-4)}` : "";
393
+ }
394
+
395
+ export async function resolveAuthConfig(opts = {}) {
396
+ const envKey = cleanToken(
397
+ (opts && opts.apiKey) ||
398
+ process.env.A8_API_KEY ||
399
+ process.env.BIVIA_API_KEY ||
400
+ ""
401
+ );
402
+ if (envKey) {
403
+ return {
404
+ apiKey: envKey,
405
+ baseURL: opts.base || process.env.BIVIA_API_BASE || undefined,
406
+ source: "env",
407
+ };
408
+ }
409
+
410
+ try {
411
+ await refreshCredentialsIfNeeded(opts);
412
+ } catch {
413
+ /* proceed with existing token if refresh fails */
414
+ }
415
+
416
+ const creds = loadCredentials();
417
+ if (creds && creds.access_token) {
418
+ return {
419
+ apiKey: cleanToken(creds.access_token),
420
+ baseURL:
421
+ opts.base ||
422
+ process.env.BIVIA_API_BASE ||
423
+ creds.api_base ||
424
+ undefined,
425
+ source: hasOAuthSession(creds) ? "oauth" : "api_key",
426
+ };
427
+ }
428
+
429
+ const legacy = cleanToken(loadLegacyConfigKey());
430
+ if (legacy) {
431
+ return {
432
+ apiKey: legacy,
433
+ baseURL: opts.base || process.env.BIVIA_API_BASE || undefined,
434
+ source: "config",
435
+ };
436
+ }
437
+
438
+ return {
439
+ apiKey: "",
440
+ baseURL: opts.base || process.env.BIVIA_API_BASE || undefined,
441
+ source: null,
442
+ };
443
+ }
444
+
445
+ function escapeHtml(s) {
446
+ return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
447
+ }
448
+
449
+ function base64Url(buf) {
450
+ return Buffer.from(buf)
451
+ .toString("base64")
452
+ .replace(/\+/g, "-")
453
+ .replace(/\//g, "_")
454
+ .replace(/=+$/g, "");
455
+ }
456
+
457
+ // The platform's sign-up page with the Bivia code and source, as in the browser extension. Sign-up
458
+ // happens in the browser; the OAuth login runs afterwards, with the new account.
459
+ export function signupUrl(platformUrl) {
460
+ let u;
461
+ try {
462
+ u = new URL("/registration", platformUrl || platformOrigin());
463
+ } catch {
464
+ u = null;
465
+ }
466
+ if (!u || !isWebUrl(u)) {
467
+ throw new OAuthError("The platform URL must be an http(s) URL", "invalid_platform_url");
468
+ }
469
+ u.searchParams.set("code", "bivia");
470
+ u.searchParams.set("source", "bivia");
471
+ return u.toString();
472
+ }
473
+
474
+ // A platform URL a tool call may pass (it comes from the model): an Articul8 https host, or the platform the
475
+ // user set in BIVIA_PLATFORM_URL. Any other platform is set by the user (env or the CLI's --platform).
476
+ export function isAllowedPlatformUrl(raw) {
477
+ let u;
478
+ try {
479
+ u = new URL(raw);
480
+ } catch {
481
+ return false;
482
+ }
483
+ if (u.protocol === "https:" && (u.hostname === "articul8.ai" || u.hostname.endsWith(".articul8.ai"))) {
484
+ return true;
485
+ }
486
+ try {
487
+ return Boolean(process.env.BIVIA_PLATFORM_URL) && new URL(process.env.BIVIA_PLATFORM_URL).origin === u.origin;
488
+ } catch {
489
+ return false;
490
+ }
491
+ }
492
+
493
+ function isWebUrl(u) {
494
+ return u.protocol === "https:" || u.protocol === "http:";
495
+ }
496
+
497
+ export function openBrowserUrl(url) {
498
+ // Only web pages: a URL built from tool input (platform_url) or from discovery must never reach the OS
499
+ // opener with another scheme (file:, an app's custom scheme, …).
500
+ let parsed;
501
+ try {
502
+ parsed = new URL(url);
503
+ } catch {
504
+ return false;
505
+ }
506
+ if (!isWebUrl(parsed)) return false;
507
+ try {
508
+ const plat = process.platform;
509
+ const cmd =
510
+ plat === "darwin" ? "open" : plat === "win32" ? "rundll32" : "xdg-open";
511
+ const args =
512
+ plat === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
513
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
514
+ // no opener on this machine (e.g. a server without xdg-open): ignore — the link is printed for the user.
515
+ // Without a listener, the spawn error would crash the whole process.
516
+ child.on("error", () => {});
517
+ child.unref();
518
+ return true;
519
+ } catch {
520
+ return false;
521
+ }
522
+ }
523
+
524
+ export async function discoverOAuth(platformUrl, fetchImpl = fetch) {
525
+ const plat = String(platformUrl || "").replace(/\/+$/, "");
526
+ for (const pathSuffix of [
527
+ "/.well-known/oauth-authorization-server",
528
+ "/api/oauth/config",
529
+ ]) {
530
+ try {
531
+ const res = await fetchImpl(`${plat}${pathSuffix}`, {
532
+ headers: { accept: "application/json" },
533
+ });
534
+ if (res.ok) {
535
+ const j = await res.json();
536
+ return {
537
+ issuer: j.issuer || j.hydraBrowserUrl || plat,
538
+ authorization_endpoint:
539
+ j.authorization_endpoint ||
540
+ `${(j.hydraBrowserUrl || plat).replace(/\/+$/, "")}/oauth2/auth`,
541
+ token_endpoint:
542
+ j.token_proxy_endpoint ||
543
+ j.token_endpoint ||
544
+ `${plat}/api/oauth/token`,
545
+ registration_endpoint:
546
+ j.registration_endpoint || `${plat}/api/oauth/register`,
547
+ };
548
+ }
549
+ } catch {
550
+ /* try next */
551
+ }
552
+ }
553
+ return {
554
+ issuer: plat,
555
+ authorization_endpoint: `${plat}/oauth2/auth`,
556
+ token_endpoint: `${plat}/api/oauth/token`,
557
+ registration_endpoint: `${plat}/api/oauth/register`,
558
+ };
559
+ }
560
+
561
+ const DEFAULT_LOOPBACK_PORTS = [19284, 19285, 19286, 0];
562
+
563
+ async function listenLoopback(srv, explicitPort) {
564
+ const candidates =
565
+ explicitPort != null ? [explicitPort] : DEFAULT_LOOPBACK_PORTS;
566
+ let lastErr;
567
+ for (const p of candidates) {
568
+ try {
569
+ await new Promise((res, rej) => {
570
+ const onErr = (err) => {
571
+ srv.removeListener("listening", onListen);
572
+ rej(err);
573
+ };
574
+ const onListen = () => {
575
+ srv.removeListener("error", onErr);
576
+ res();
577
+ };
578
+ srv.once("error", onErr);
579
+ srv.once("listening", onListen);
580
+ srv.listen(p, "127.0.0.1");
581
+ });
582
+ return;
583
+ } catch (e) {
584
+ lastErr = e;
585
+ }
586
+ }
587
+ throw lastErr || new OAuthError("Failed to bind loopback port", "oauth_port_failed");
588
+ }
589
+
590
+ export async function oauthLogin(opts = {}) {
591
+ const fetchImpl = opts.fetch || fetch;
592
+ const apiBase =
593
+ opts.base || process.env.BIVIA_API_BASE || DEFAULT_BASE;
594
+ const plat = (opts.platformUrl || platformOrigin(apiBase)).replace(/\/+$/, "");
595
+ const meta = await discoverOAuth(plat, fetchImpl);
596
+
597
+ const verifier = base64Url(crypto.randomBytes(32));
598
+ const challenge = base64Url(
599
+ crypto.createHash("sha256").update(verifier).digest()
600
+ );
601
+ const state = base64Url(crypto.randomBytes(16));
602
+
603
+ let resolveCallback;
604
+ let rejectCallback;
605
+ const callbackPromise = new Promise((res, rej) => {
606
+ resolveCallback = res;
607
+ rejectCallback = rej;
608
+ });
609
+
610
+ let redirectUri = "";
611
+ const srv = http.createServer((req, res) => {
612
+ try {
613
+ const reqUrl = new URL(req.url || "/", "http://127.0.0.1");
614
+ if (reqUrl.pathname !== "/callback") {
615
+ res.writeHead(404);
616
+ res.end("Not found");
617
+ return;
618
+ }
619
+ // Anything can request this local address while we wait (a web page via <img>), so only a callback
620
+ // carrying OUR state may end the login; others get a page and are otherwise ignored.
621
+ const gotState = reqUrl.searchParams.get("state");
622
+ if (gotState !== state) {
623
+ res.writeHead(400, { "content-type": "text/html; charset=utf-8" });
624
+ res.end(
625
+ `<html><body style="font-family:system-ui;background:#09090b;color:#f4f4f5;padding:40px;text-align:center"><h2>Invalid OAuth Callback</h2><p>This link doesn't belong to the sign-in in progress.</p></body></html>`
626
+ );
627
+ return;
628
+ }
629
+ const errParam = reqUrl.searchParams.get("error");
630
+ if (errParam) {
631
+ if (/invalid_client|unauthorized_client/i.test(errParam)) {
632
+ clearCachedClientId(plat, redirectUri);
633
+ }
634
+ const desc = escapeHtml(reqUrl.searchParams.get("error_description") || errParam);
635
+ res.writeHead(400, { "content-type": "text/html; charset=utf-8" });
636
+ res.end(
637
+ `<html><body style="font-family:system-ui;background:#09090b;color:#f4f4f5;padding:40px;text-align:center"><h2>Authentication Failed</h2><p>${desc}</p></body></html>`
638
+ );
639
+ rejectCallback(new OAuthError(`OAuth error: ${desc}`, "oauth_denied"));
640
+ return;
641
+ }
642
+ const code = reqUrl.searchParams.get("code");
643
+ if (!code) {
644
+ res.writeHead(400, { "content-type": "text/html; charset=utf-8" });
645
+ res.end(
646
+ `<html><body style="font-family:system-ui;background:#09090b;color:#f4f4f5;padding:40px;text-align:center"><h2>Invalid OAuth Callback</h2><p>State mismatch or missing code.</p></body></html>`
647
+ );
648
+ rejectCallback(
649
+ new OAuthError(
650
+ "OAuth callback is missing the authorization code",
651
+ "oauth_invalid_callback"
652
+ )
653
+ );
654
+ return;
655
+ }
656
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
657
+ res.end(
658
+ `<html><body style="font-family:system-ui;background:#09090b;color:#34d399;padding:40px;text-align:center"><h2>✓ Signed in to Articul8 Bivia</h2><p style="color:#a1a1aa">You can close this tab and return to your terminal or editor.</p></body></html>`
659
+ );
660
+ resolveCallback(code);
661
+ } catch (e) {
662
+ rejectCallback(e);
663
+ }
664
+ });
665
+
666
+ await listenLoopback(srv, opts.port);
667
+
668
+ const addr = srv.address();
669
+ const port = typeof addr === "object" && addr ? addr.port : 0;
670
+ redirectUri = `http://127.0.0.1:${port}/callback`;
671
+
672
+ // 5 minutes, like the Go bivia CLI: a first sign-in or a switch can stop on the consent page for a while
673
+ const timeoutMs = opts.timeoutMs || 300_000;
674
+ const timer = setTimeout(() => {
675
+ rejectCallback(
676
+ new OAuthError("Timed out waiting for browser OAuth login", "oauth_timeout")
677
+ );
678
+ }, timeoutMs);
679
+
680
+ try {
681
+ // The platform binds a client to the account that first consents to it, so the cached client is reused
682
+ // only while signed in; after a sign-out, or to switch account, the next login may be a different account.
683
+ let clientId = opts.forceRegister || opts.switchAccount
684
+ ? ""
685
+ : opts.clientId || (hasOAuthSession() ? loadCachedClientId(plat, redirectUri) : "");
686
+ if (!clientId) {
687
+ const redirectUris = Array.from(
688
+ new Set([
689
+ redirectUri,
690
+ "http://127.0.0.1:19284/callback",
691
+ "http://127.0.0.1:19285/callback",
692
+ "http://127.0.0.1:19286/callback",
693
+ ])
694
+ );
695
+ const dcrRes = await fetchImpl(meta.registration_endpoint, {
696
+ method: "POST",
697
+ headers: {
698
+ "content-type": "application/json",
699
+ accept: "application/json",
700
+ },
701
+ body: JSON.stringify({
702
+ client_name: opts.clientName || "Bivia MCP Server",
703
+ redirect_uris: redirectUris,
704
+ grant_types: ["authorization_code", "refresh_token"],
705
+ response_types: ["code"],
706
+ token_endpoint_auth_method: "none",
707
+ }),
708
+ });
709
+ if (!dcrRes.ok) {
710
+ const txt = await dcrRes.text().catch(() => "");
711
+ throw new OAuthError(
712
+ `Dynamic client registration failed (HTTP ${dcrRes.status}): ${txt}`,
713
+ "oauth_dcr_failed"
714
+ );
715
+ }
716
+ const clientInfo = await dcrRes.json();
717
+ clientId = clientInfo.client_id;
718
+ if (!clientId) {
719
+ throw new OAuthError(
720
+ "Dynamic client registration did not return client_id",
721
+ "oauth_dcr_failed"
722
+ );
723
+ }
724
+ saveCachedClientId(plat, redirectUri, clientId);
725
+ }
726
+
727
+ const authUrl = new URL(meta.authorization_endpoint);
728
+ authUrl.searchParams.set("response_type", "code");
729
+ authUrl.searchParams.set("client_id", clientId);
730
+ authUrl.searchParams.set("redirect_uri", redirectUri);
731
+ authUrl.searchParams.set(
732
+ "scope",
733
+ opts.scope || "openid offline_access"
734
+ );
735
+ authUrl.searchParams.set("state", state);
736
+ authUrl.searchParams.set("code_challenge", challenge);
737
+ authUrl.searchParams.set("code_challenge_method", "S256");
738
+ // Standard OIDC hint. The platform ignores it today and reuses the browser's Articul8 session, so a switch
739
+ // changes organization and group only (see SWITCH_ACCOUNT_NOTE).
740
+ if (opts.switchAccount) authUrl.searchParams.set("prompt", "login");
741
+
742
+ const authorizeUrlStr = authUrl.toString();
743
+ if (typeof opts.onAuthUrl === "function") {
744
+ opts.onAuthUrl(authorizeUrlStr);
745
+ }
746
+ if (opts.openBrowser !== false) {
747
+ openBrowserUrl(authorizeUrlStr);
748
+ }
749
+
750
+ const code = await callbackPromise;
751
+
752
+ const tokenForm = new URLSearchParams({
753
+ grant_type: "authorization_code",
754
+ code,
755
+ redirect_uri: redirectUri,
756
+ client_id: clientId,
757
+ code_verifier: verifier,
758
+ });
759
+ const tokRes = await fetchImpl(meta.token_endpoint, {
760
+ method: "POST",
761
+ headers: {
762
+ "content-type": "application/x-www-form-urlencoded",
763
+ accept: "application/json",
764
+ },
765
+ body: tokenForm.toString(),
766
+ });
767
+ if (!tokRes.ok) {
768
+ const txt = await tokRes.text().catch(() => "");
769
+ if (/invalid_client/i.test(txt)) {
770
+ clearCachedClientId(plat, redirectUri);
771
+ }
772
+ throw new OAuthError(
773
+ `OAuth token exchange failed (HTTP ${tokRes.status}): ${txt}`,
774
+ "oauth_token_failed"
775
+ );
776
+ }
777
+ const tok = await tokRes.json();
778
+ if (!tok || !tok.access_token) {
779
+ throw new OAuthError(
780
+ "OAuth token exchange returned no access_token",
781
+ "oauth_token_failed"
782
+ );
783
+ }
784
+
785
+ saveCachedClientId(plat, redirectUri, clientId);
786
+ const scopeMeta = parseScopeMetadata(tok.scope || "");
787
+ const creds = {
788
+ access_token: tok.access_token,
789
+ refresh_token: tok.refresh_token || "",
790
+ token_type: tok.token_type || "bearer",
791
+ expires_at:
792
+ Math.floor(Date.now() / 1000) + (Number(tok.expires_in) || 3600),
793
+ scope: tok.scope || "",
794
+ client_id: clientId,
795
+ redirect_uri: redirectUri,
796
+ tenant_id: scopeMeta.tenantId || "",
797
+ group_id: scopeMeta.groupId || "",
798
+ group_ids: scopeMeta.groupIds || [],
799
+ permission: scopeMeta.permission || "",
800
+ platform_url: plat,
801
+ token_endpoint: meta.token_endpoint,
802
+ api_base: process.env.BIVIA_API_BASE || undefined,
803
+ };
804
+ saveCredentials(creds);
805
+ return creds;
806
+ } finally {
807
+ clearTimeout(timer);
808
+ try {
809
+ srv.close();
810
+ } catch {
811
+ /* ignore */
812
+ }
813
+ }
814
+ }
815
+
816
+ // The platform signs in whichever account the browser already has a session for, even with prompt=login.
817
+ export const SWITCH_ACCOUNT_NOTE =
818
+ "To use a different account, sign out of Articul8 in your browser first, then switch again.";
819
+
820
+ // As the browser extension shows them: ids over 16 characters become "first8…last5".
821
+ export function shortId(id) {
822
+ const s = String(id || "");
823
+ return s.length > 16 ? s.slice(0, 8) + "…" + s.slice(-5) : s;
824
+ }
825
+
826
+ // The host the Bivia calls go to (the same base resolveAuthConfig picks).
827
+ function endpointHost(base) {
828
+ const b = process.env.BIVIA_API_BASE || base || DEFAULT_BASE;
829
+ try {
830
+ return new URL(b).host;
831
+ } catch {
832
+ return b;
833
+ }
834
+ }
835
+
836
+ export function getAuthStatus() {
837
+ const envKey = cleanToken(
838
+ process.env.A8_API_KEY || process.env.BIVIA_API_KEY || ""
839
+ );
840
+ const creds = loadCredentials();
841
+ const legacyKey = cleanToken(loadLegacyConfigKey());
842
+ if (envKey) {
843
+ // resolveAuthConfig uses an env key before any sign-in, so say so
844
+ return {
845
+ authenticated: true,
846
+ method: "env_api_key",
847
+ token_type: /^ory_at_/.test(envKey) ? "ory_access_token" : "api_key",
848
+ key_hint: maskKey(envKey),
849
+ endpoint: endpointHost(),
850
+ oauth_signed_in_but_unused: hasOAuthSession(creds),
851
+ };
852
+ }
853
+ if (creds && creds.access_token && !hasOAuthSession(creds)) {
854
+ return {
855
+ authenticated: true,
856
+ method: "api_key",
857
+ token_type: /^ory_at_/.test(creds.access_token) ? "ory_access_token" : "api_key",
858
+ key_hint: maskKey(creds.access_token),
859
+ endpoint: endpointHost(creds.api_base),
860
+ };
861
+ }
862
+ if (creds && creds.access_token) {
863
+ const scopeMeta = parseScopeMetadata(creds.scope || "");
864
+ const groupId = creds.group_id || scopeMeta.groupId || null;
865
+ return {
866
+ authenticated: true,
867
+ method: "oauth",
868
+ tenant_id: creds.tenant_id || scopeMeta.tenantId || null,
869
+ group_id: groupId,
870
+ group_short: groupId ? shortId(groupId) : null,
871
+ group_ids:
872
+ creds.group_ids && creds.group_ids.length
873
+ ? creds.group_ids
874
+ : scopeMeta.groupIds,
875
+ permission: creds.permission || scopeMeta.permission || null,
876
+ scope: creds.scope || "",
877
+ expires_at: creds.expires_at || null,
878
+ platform_url: creds.platform_url || null,
879
+ endpoint: endpointHost(creds.api_base),
880
+ has_refresh_token: Boolean(creds.refresh_token),
881
+ };
882
+ }
883
+ if (legacyKey) {
884
+ return {
885
+ authenticated: true,
886
+ method: "config_api_key",
887
+ token_type: /^ory_at_/.test(legacyKey) ? "ory_access_token" : "api_key",
888
+ key_hint: maskKey(legacyKey),
889
+ endpoint: endpointHost(),
890
+ };
891
+ }
892
+ return { authenticated: false, method: null };
893
+ }
894
+
895
+ // One readable line per state, like the extension popup's connected card.
896
+ export function describeAuthStatus(st) {
897
+ const at = st.endpoint ? `. Endpoint: ${st.endpoint}` : "";
898
+ switch (st.method) {
899
+ case "oauth":
900
+ return `Signed in with Articul8 — tenant ${st.tenant_id || "unknown"}, group ${st.group_short || "unknown"}, permission ${st.permission || "unknown"}${at}`;
901
+ case "api_key":
902
+ return `Connected with API key ${st.key_hint} (saved with login --key)${at}`;
903
+ case "env_api_key":
904
+ return `Connected with API key ${st.key_hint} from the environment${at}${st.oauth_signed_in_but_unused ? ". An Articul8 sign-in is saved but unused while the environment key is set" : ""}`;
905
+ case "config_api_key":
906
+ return `Connected with the bivia CLI's API key ${st.key_hint} (~/.bivia/config)${at}`;
907
+ default:
908
+ return "Not authenticated — call bivia_login (or bivia_signup to create a free account), run `npx @articul8/bivia-mcp login`, or set A8_API_KEY";
909
+ }
910
+ }