suppa-mcp-2 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrii Herasymchuk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # suppa-mcp-2
2
+
3
+ MCP (Model Context Protocol) server for the [Suppa platform](https://modern.suppa.me) — gives
4
+ AI agents tools to manage Tasks, Docs/Pages, Entities & Schema, Forms, Automations, and file
5
+ attachments, with multi-tenant Google authentication.
6
+
7
+ This is the Node.js/TypeScript port of the Python [`suppa-mcp`](https://pypi.org/project/suppa-mcp/)
8
+ package, published to npm as **`suppa-mcp-2`**.
9
+
10
+ ## Install
11
+
12
+ Zero-install via `npx` — your MCP client fetches and runs the latest release on demand:
13
+
14
+ ```bash
15
+ npx suppa-mcp-2
16
+ ```
17
+
18
+ ## Connect to your AI agent
19
+
20
+ Point any MCP client at `npx`:
21
+
22
+ ```json
23
+ {
24
+ "mcpServers": {
25
+ "suppa-2.0": {
26
+ "command": "npx",
27
+ "args": ["-y", "suppa-mcp-2"]
28
+ }
29
+ }
30
+ }
31
+ ```
32
+
33
+ ## Authentication
34
+
35
+ No API key to paste. Run the **`suppa_login`** tool from your MCP client — it opens a browser
36
+ for Google sign-in, then stores the resulting credentials locally (in the OS keychain). The
37
+ server is multi-tenant, so you can log in to more than one Suppa tenant and switch between them.
38
+
39
+ Credentials stay on your machine and are sent only in the `Authorization` header to your
40
+ configured `SUPPA_BASE_URL`; they are **never** exposed to the AI agent.
41
+
42
+ ## Environment Variables
43
+
44
+ All are optional — the server works out of the box and authenticates via `suppa_login`.
45
+
46
+ | Variable | Default | Description |
47
+ |----------|---------|-------------|
48
+ | `SUPPA_BASE_URL` | `https://modern.suppa.me` | Platform URL |
49
+ | `SUPPA_API_KEY` | (none) | JWT token or API key; skips interactive login when set |
50
+ | `SUPPA_LANG` | `en` | Language (`en` / `uk`) |
51
+ | `SUPPA_TZ` | `Europe/Kyiv` | Timezone |
52
+ | `SUPPA_MCP_LOGIN_PORT` | (auto) | Local port for the browser login callback |
53
+ | `SUPPA_MCP_HOME` | OS config dir | Directory for stored credentials / tenant state |
54
+ | `SUPPA_HTTP_TIMEOUT` | `60` | Per-request timeout, seconds |
55
+ | `SUPPA_MCP_DEBUG` | (off) | `1` logs each request line to stderr |
56
+
57
+ ## License
58
+
59
+ MIT — see [LICENSE](LICENSE).
package/dist/auth.js ADDED
@@ -0,0 +1,612 @@
1
+ /**
2
+ * Authentication for Suppa tenants: Google browser login + automatic refresh.
3
+ *
4
+ * Two responsibilities, both transparent to tools:
5
+ *
6
+ * 1. `maybeRefresh` — called from `tenants.ensureValid` before every request.
7
+ * If the stored access token is near expiry it POSTs the refresh endpoint
8
+ * (under a per-tenant single-flight guard), persists the *rotated* access
9
+ * *and* refresh tokens, and lets the request proceed. If the refresh token
10
+ * itself is gone/expired it throws {@link ReloginRequired}.
11
+ *
12
+ * 2. `login` — opens a local page in the browser that runs Google Identity
13
+ * Services, captures the Google ID token, exchanges it at the tenant's
14
+ * `/api/auth/accounts/oauth2` endpoint, and stores the resulting Suppa
15
+ * tokens in the keychain. After this, (1) keeps the session alive for as
16
+ * long as the refresh token's rolling window allows.
17
+ *
18
+ * This module talks to the network directly (raw `fetch`, not via
19
+ * `httpClient`) so refresh never recurses through `ensureValid` and never
20
+ * carries a stale access token.
21
+ *
22
+ * Faithful 1:1 port of the Python `suppa_mcp/auth.py`.
23
+ */
24
+ import { randomBytes } from "node:crypto";
25
+ import { spawn } from "node:child_process";
26
+ import { createServer } from "node:http";
27
+ import { readFileSync, statSync, writeFileSync } from "node:fs";
28
+ import { config } from "./config.js";
29
+ import * as store from "./store.js";
30
+ import * as tenants from "./tenants.js";
31
+ export const REFRESH_PATH = "/api/auth/accounts/refresh-token";
32
+ export const OAUTH2_PATH = "/api/auth/accounts/oauth2";
33
+ export const EXPIRY_SKEW = 30.0; // seconds — refresh this long before the token actually expires
34
+ export class ReloginRequired extends Error {
35
+ host;
36
+ constructor(host) {
37
+ super(`Suppa session expired for '${host}'. Run suppa_login to re-authenticate.`);
38
+ this.name = "ReloginRequired";
39
+ this.host = host;
40
+ }
41
+ }
42
+ // ---------------------------------------------------------------------------
43
+ // Token helpers
44
+ // ---------------------------------------------------------------------------
45
+ function b64urlJson(segment) {
46
+ const buf = Buffer.from(segment, "base64url");
47
+ return JSON.parse(buf.toString("utf-8"));
48
+ }
49
+ /** Return a JWT's `exp` (epoch seconds), or 0 if it can't be read. */
50
+ export function jwtExp(token) {
51
+ try {
52
+ const payload = b64urlJson(token.split(".")[1]);
53
+ return Number(payload.exp) || 0;
54
+ }
55
+ catch {
56
+ return 0;
57
+ }
58
+ }
59
+ /**
60
+ * Parse an ISO timestamp to epoch SECONDS (float). An offset-less timestamp is
61
+ * treated as UTC (not host-local), so token expiries don't skew by the
62
+ * machine's timezone. Any failure -> 0.
63
+ */
64
+ function isoToEpoch(value) {
65
+ try {
66
+ if (!value) {
67
+ return 0;
68
+ }
69
+ // Determine whether the string carries a timezone (Z or ±HH:MM after the
70
+ // time portion). If not, treat it as UTC by appending "Z".
71
+ const hasTz = /[zZ]$/.test(value) || /[+-]\d{2}:?\d{2}$/.test(value);
72
+ const normalized = hasTz ? value : `${value}Z`;
73
+ const ms = Date.parse(normalized);
74
+ if (Number.isNaN(ms)) {
75
+ return 0;
76
+ }
77
+ return ms / 1000;
78
+ }
79
+ catch {
80
+ return 0;
81
+ }
82
+ }
83
+ /**
84
+ * Build Credentials from a login/refresh response body and/or Set-Cookie.
85
+ *
86
+ * Handles the observed shape `{access:{token,expiredAt}, refresh:{...}}` as
87
+ * well as flat fields and httpOnly cookies, so the same parser serves both the
88
+ * oauth2 and refresh-token endpoints.
89
+ */
90
+ export function extractCredentials(body, setCookies) {
91
+ let access = "";
92
+ let refresh = "";
93
+ let aExp = 0;
94
+ let rExp = 0;
95
+ if (body && typeof body === "object") {
96
+ const b = body;
97
+ const acc = b.access;
98
+ const ref = b.refresh;
99
+ if (acc && typeof acc === "object") {
100
+ const a = acc;
101
+ access = (typeof a.token === "string" ? a.token : "") || "";
102
+ aExp = isoToEpoch((typeof a.expiredAt === "string" ? a.expiredAt : "") || "");
103
+ }
104
+ if (ref && typeof ref === "object") {
105
+ const r = ref;
106
+ refresh = (typeof r.token === "string" ? r.token : "") || "";
107
+ rExp = isoToEpoch((typeof r.expiredAt === "string" ? r.expiredAt : "") || "");
108
+ }
109
+ access =
110
+ access ||
111
+ (typeof b.accessToken === "string" ? b.accessToken : "") ||
112
+ (typeof b.access_token === "string" ? b.access_token : "") ||
113
+ "";
114
+ refresh =
115
+ refresh ||
116
+ (typeof b.refreshToken === "string" ? b.refreshToken : "") ||
117
+ (typeof b.refresh_token === "string" ? b.refresh_token : "") ||
118
+ "";
119
+ }
120
+ for (const cookie of setCookies) {
121
+ const eq = cookie.indexOf("=");
122
+ const name = (eq === -1 ? cookie : cookie.slice(0, eq)).trim();
123
+ const rest = eq === -1 ? "" : cookie.slice(eq + 1);
124
+ const val = rest.split(";", 1)[0].trim();
125
+ if (name === "accessToken" && !access) {
126
+ access = val;
127
+ }
128
+ else if (name === "refreshToken" && !refresh) {
129
+ refresh = val;
130
+ }
131
+ }
132
+ if (access && !aExp) {
133
+ aExp = jwtExp(access);
134
+ }
135
+ if (refresh && !rExp) {
136
+ rExp = jwtExp(refresh);
137
+ }
138
+ return {
139
+ accessToken: access,
140
+ refreshToken: refresh,
141
+ accessExp: aExp,
142
+ refreshExp: rExp,
143
+ };
144
+ }
145
+ // ---------------------------------------------------------------------------
146
+ // Low-level network (auth endpoints only — no tenant auth headers)
147
+ // ---------------------------------------------------------------------------
148
+ /** Pull Set-Cookie header values off a fetch Response, tolerating a mock. */
149
+ function readSetCookies(headers) {
150
+ if (!headers || typeof headers !== "object") {
151
+ return [];
152
+ }
153
+ const h = headers;
154
+ try {
155
+ if (typeof h.getSetCookie === "function") {
156
+ const cookies = h.getSetCookie();
157
+ if (Array.isArray(cookies)) {
158
+ return cookies;
159
+ }
160
+ }
161
+ }
162
+ catch {
163
+ /* fall through */
164
+ }
165
+ try {
166
+ if (typeof h.get === "function") {
167
+ const single = h.get("set-cookie");
168
+ if (single) {
169
+ return [single];
170
+ }
171
+ }
172
+ }
173
+ catch {
174
+ /* fall through */
175
+ }
176
+ return [];
177
+ }
178
+ const rawPost = async (url, opts) => {
179
+ const { cookie = "", body = null, timeout = 60 } = opts;
180
+ const headers = {
181
+ Accept: "application/json, text/plain, */*",
182
+ };
183
+ if (cookie) {
184
+ headers.Cookie = cookie;
185
+ }
186
+ let data;
187
+ if (body !== null && body !== undefined) {
188
+ data = JSON.stringify(body);
189
+ headers["Content-Type"] = "application/json; charset=UTF-8";
190
+ }
191
+ const controller = new AbortController();
192
+ const timer = setTimeout(() => controller.abort(), timeout * 1000);
193
+ let resp;
194
+ try {
195
+ resp = await fetch(url, {
196
+ method: "POST",
197
+ headers,
198
+ body: data,
199
+ signal: controller.signal,
200
+ });
201
+ }
202
+ catch (e) {
203
+ clearTimeout(timer);
204
+ if (e instanceof Error && e.name === "AbortError") {
205
+ throw new Error(`Auth request to ${url} timed out after ${timeout}s.`);
206
+ }
207
+ const reason = e instanceof Error ? e.message : String(e);
208
+ throw new Error(`Connection error: ${reason}`);
209
+ }
210
+ clearTimeout(timer);
211
+ const raw = await resp.text();
212
+ if (!resp.ok) {
213
+ throw new Error(`HTTP ${resp.status} ${resp.statusText}: ${raw}`);
214
+ }
215
+ const cookies = readSetCookies(resp.headers);
216
+ const parsed = raw.trim() ? JSON.parse(raw) : {};
217
+ return { body: parsed, cookies };
218
+ };
219
+ let authPost = rawPost;
220
+ /** Test-only seam: override the auth-endpoint POST implementation. */
221
+ export function __setAuthPost(fn) {
222
+ authPost = fn ?? rawPost;
223
+ }
224
+ // ---------------------------------------------------------------------------
225
+ // Persist tokens to .env
226
+ // ---------------------------------------------------------------------------
227
+ function findEnvFile() {
228
+ for (const candidate of config.candidateEnvFiles()) {
229
+ try {
230
+ if (statSync(candidate).isFile()) {
231
+ return candidate;
232
+ }
233
+ }
234
+ catch {
235
+ /* not a file / unreadable — skip */
236
+ }
237
+ }
238
+ return null;
239
+ }
240
+ /** Write both access and refresh tokens to .env, preserving other content. */
241
+ function writeTokensToEnv(accessToken, refreshToken) {
242
+ const envPath = findEnvFile();
243
+ if (!envPath) {
244
+ return; // No .env file found; skip silently
245
+ }
246
+ let content;
247
+ try {
248
+ content = readFileSync(envPath, { encoding: "utf-8" });
249
+ }
250
+ catch {
251
+ return; // Can't read file; skip silently
252
+ }
253
+ // Preserve line endings (splitlines(keepends=True) equivalent).
254
+ const lines = content.match(/[^\n]*\n|[^\n]+$/g) ?? [];
255
+ let foundAccess = false;
256
+ let foundRefresh = false;
257
+ const result = [];
258
+ for (const line of lines) {
259
+ const stripped = line.split("=", 1)[0].trim();
260
+ if (stripped === "SUPPA_API_KEY") {
261
+ result.push(`SUPPA_API_KEY=${accessToken}\n`);
262
+ foundAccess = true;
263
+ }
264
+ else if (stripped === "SUPPA_REFRESH_TOKEN") {
265
+ result.push(`SUPPA_REFRESH_TOKEN=${refreshToken}\n`);
266
+ foundRefresh = true;
267
+ }
268
+ else {
269
+ result.push(line);
270
+ }
271
+ }
272
+ if (!foundAccess) {
273
+ result.push(`SUPPA_API_KEY=${accessToken}\n`);
274
+ }
275
+ if (!foundRefresh) {
276
+ result.push(`SUPPA_REFRESH_TOKEN=${refreshToken}\n`);
277
+ }
278
+ try {
279
+ writeFileSync(envPath, result.join(""), { encoding: "utf-8" });
280
+ }
281
+ catch {
282
+ /* Can't write; silently skip (keychain save already worked) */
283
+ }
284
+ }
285
+ // ---------------------------------------------------------------------------
286
+ // Refresh (single-flight per tenant)
287
+ // ---------------------------------------------------------------------------
288
+ // A per-host in-flight promise. Concurrent callers for the same host share the
289
+ // SAME refresh (exactly one network call); the entry is cleared in a finally.
290
+ const inflight = new Map();
291
+ function accessExpiring(creds) {
292
+ const exp = creds.accessExp || jwtExp(creds.accessToken);
293
+ if (!exp) {
294
+ return true; // unknown expiry -> refresh to be safe
295
+ }
296
+ return Date.now() / 1000 >= exp - EXPIRY_SKEW;
297
+ }
298
+ function refreshDead(creds) {
299
+ const exp = creds.refreshExp || jwtExp(creds.refreshToken);
300
+ return !creds.refreshToken || (Boolean(exp) && Date.now() / 1000 >= exp);
301
+ }
302
+ /** Refresh `ctx`'s access token if needed. No-op when there's no session. */
303
+ export async function maybeRefresh(ctx) {
304
+ let creds = store.load(ctx.host);
305
+ if (!creds || !creds.accessToken) {
306
+ return; // env-token tenant or not logged in — nothing to refresh
307
+ }
308
+ if (!accessExpiring(creds)) {
309
+ return;
310
+ }
311
+ let promise = inflight.get(ctx.host);
312
+ if (!promise) {
313
+ promise = (async () => {
314
+ // re-read under the "lock" (another caller may have refreshed)
315
+ const fresh = store.load(ctx.host);
316
+ if (!fresh || !fresh.accessToken || !accessExpiring(fresh)) {
317
+ return;
318
+ }
319
+ if (refreshDead(fresh)) {
320
+ throw new ReloginRequired(ctx.host);
321
+ }
322
+ await doRefresh(ctx.baseUrl, ctx.host, fresh);
323
+ })();
324
+ // Ensure the map entry is cleared once this refresh settles.
325
+ promise = promise.finally(() => {
326
+ inflight.delete(ctx.host);
327
+ });
328
+ inflight.set(ctx.host, promise);
329
+ }
330
+ await promise;
331
+ }
332
+ /**
333
+ * Refresh now regardless of local expiry (called after a 401). Returns success.
334
+ *
335
+ * Robust to clock skew and server-side early invalidation: even if our local
336
+ * clock thinks the access token is valid, a 401 means it isn't — so we refresh
337
+ * unconditionally (single-flight) and let the caller retry.
338
+ */
339
+ export async function forceRefresh(ctx) {
340
+ const creds = store.load(ctx.host);
341
+ if (!creds || refreshDead(creds)) {
342
+ return false;
343
+ }
344
+ let promise = inflight.get(ctx.host);
345
+ if (!promise) {
346
+ promise = (async () => {
347
+ const fresh = store.load(ctx.host);
348
+ if (!fresh || refreshDead(fresh)) {
349
+ throw new ReloginRequired(ctx.host);
350
+ }
351
+ await doRefresh(ctx.baseUrl, ctx.host, fresh);
352
+ })();
353
+ promise = promise.finally(() => {
354
+ inflight.delete(ctx.host);
355
+ });
356
+ inflight.set(ctx.host, promise);
357
+ }
358
+ try {
359
+ await promise;
360
+ return true;
361
+ }
362
+ catch {
363
+ // caller surfaces the original 401 if this fails
364
+ return false;
365
+ }
366
+ }
367
+ export async function doRefresh(baseUrl, host, creds) {
368
+ const { body, cookies } = await authPost(baseUrl + REFRESH_PATH, {
369
+ cookie: `refreshToken=${creds.refreshToken}`,
370
+ });
371
+ const fresh = extractCredentials(body, cookies);
372
+ if (!fresh.accessToken) {
373
+ throw new ReloginRequired(host);
374
+ }
375
+ if (!fresh.refreshToken) {
376
+ // server didn't rotate — keep the existing one
377
+ fresh.refreshToken = creds.refreshToken;
378
+ fresh.refreshExp = creds.refreshExp;
379
+ }
380
+ store.save(host, fresh);
381
+ writeTokensToEnv(fresh.accessToken, fresh.refreshToken); // Persist both tokens to .env
382
+ return fresh;
383
+ }
384
+ // ---------------------------------------------------------------------------
385
+ // Google login (browser loopback + GIS)
386
+ // ---------------------------------------------------------------------------
387
+ const LOGIN_HTML = `<!doctype html>
388
+ <html><head><meta charset="utf-8"><title>Suppa login</title>
389
+ <script src="https://accounts.google.com/gsi/client" async></script>
390
+ <style>body{font-family:system-ui,sans-serif;display:flex;flex-direction:column;
391
+ align-items:center;justify-content:center;height:100vh;margin:0;gap:1.5rem}
392
+ #msg{color:#444}</style></head>
393
+ <body>
394
+ <h2>Sign in to Suppa &mdash; __HOST__</h2>
395
+ <div id="g_id_onload" data-client_id="__CLIENT_ID__" data-callback="onCred"
396
+ data-auto_select="false" data-ux_mode="popup"></div>
397
+ <div class="g_id_signin" data-type="standard" data-size="large"
398
+ data-text="signin_with" data-shape="rectangular"></div>
399
+ <div id="msg"></div>
400
+ <script>
401
+ function onCred(resp){
402
+ document.getElementById('msg').textContent='Signing in…';
403
+ fetch('/callback',{method:'POST',headers:{'Content-Type':'application/json'},
404
+ body:JSON.stringify({credential:resp.credential,state:"__STATE__"})})
405
+ .then(r=>r.text()).then(t=>{document.body.innerHTML=
406
+ '<h2>'+t+'</h2><p>You can close this tab and return to your agent.</p>';});
407
+ }
408
+ </script>
409
+ </body></html>`;
410
+ /** HTML-escape text. Mirrors Python's html.escape (quote=True by default here). */
411
+ function htmlEscape(text, quote = true) {
412
+ let out = text
413
+ .replace(/&/g, "&amp;")
414
+ .replace(/</g, "&lt;")
415
+ .replace(/>/g, "&gt;");
416
+ if (quote) {
417
+ out = out.replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
418
+ }
419
+ return out;
420
+ }
421
+ /** Open a URL in the platform browser; swallow any spawn failure. */
422
+ function openBrowser(url) {
423
+ try {
424
+ if (process.platform === "win32") {
425
+ spawn("cmd", ["/c", "start", "", url], { detached: true, stdio: "ignore" }).unref();
426
+ }
427
+ else if (process.platform === "darwin") {
428
+ spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
429
+ }
430
+ else {
431
+ spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
432
+ }
433
+ return true;
434
+ }
435
+ catch {
436
+ return false;
437
+ }
438
+ }
439
+ /** Run the Google sign-in page locally and return the Google ID token. */
440
+ export function browserGoogleLogin(host, timeout = 180) {
441
+ const state = randomBytes(24).toString("base64url"); // CSRF guard
442
+ // The host comes from user input (suppa_login tenant arg) — escape it so a
443
+ // crafted "tenant" can't inject markup into the local login page.
444
+ const page = LOGIN_HTML.replace("__CLIENT_ID__", htmlEscape(config.GOOGLE_CLIENT_ID, true))
445
+ .replace("__HOST__", htmlEscape(host))
446
+ .replace("__STATE__", state);
447
+ const port = config.LOGIN_PORT;
448
+ return new Promise((resolve, reject) => {
449
+ let settled = false;
450
+ let timer;
451
+ const server = createServer((req, res) => {
452
+ const method = req.method ?? "GET";
453
+ const url = req.url ?? "/";
454
+ if (method === "GET") {
455
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
456
+ res.end(page);
457
+ return;
458
+ }
459
+ if (method === "POST" && url === "/callback") {
460
+ const chunks = [];
461
+ req.on("data", (c) => chunks.push(c));
462
+ req.on("end", () => {
463
+ let data = {};
464
+ try {
465
+ const raw = Buffer.concat(chunks).toString("utf-8") || "{}";
466
+ data = JSON.parse(raw);
467
+ }
468
+ catch {
469
+ data = {};
470
+ }
471
+ const cred = typeof data.credential === "string" ? data.credential : "";
472
+ let msg;
473
+ let error = null;
474
+ let idToken = null;
475
+ if (data.state !== state) {
476
+ error = "state mismatch (possible CSRF) — login rejected";
477
+ msg = "Login rejected.";
478
+ }
479
+ else if (cred) {
480
+ idToken = cred;
481
+ msg = "Signed in successfully.";
482
+ }
483
+ else {
484
+ error = "no credential returned by Google";
485
+ msg = "Login failed.";
486
+ }
487
+ res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
488
+ res.end(msg);
489
+ finish(error, idToken);
490
+ });
491
+ return;
492
+ }
493
+ // Any other request: just serve the page.
494
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
495
+ res.end(page);
496
+ });
497
+ const finish = (error, idToken) => {
498
+ if (settled) {
499
+ return;
500
+ }
501
+ settled = true;
502
+ if (timer) {
503
+ clearTimeout(timer);
504
+ }
505
+ server.close();
506
+ if (error) {
507
+ reject(new Error(`Google sign-in failed: ${error}`));
508
+ }
509
+ else if (idToken) {
510
+ resolve(idToken);
511
+ }
512
+ else {
513
+ reject(new Error("Google sign-in failed: no credential returned by Google"));
514
+ }
515
+ };
516
+ server.on("error", (e) => {
517
+ if (settled) {
518
+ return;
519
+ }
520
+ settled = true;
521
+ if (timer) {
522
+ clearTimeout(timer);
523
+ }
524
+ reject(new Error(`Could not start the login server on port ${port} (${e.message}). ` +
525
+ "Close whatever is using it or set SUPPA_MCP_LOGIN_PORT."));
526
+ });
527
+ server.listen(port, "127.0.0.1", () => {
528
+ const url = `http://localhost:${port}/`;
529
+ const opened = openBrowser(url);
530
+ timer = setTimeout(() => {
531
+ if (settled) {
532
+ return;
533
+ }
534
+ settled = true;
535
+ server.close();
536
+ reject(new Error(`Login timed out after ${timeout}s. ` +
537
+ (opened ? "" : `Open ${url} manually and sign in.`)));
538
+ }, timeout * 1000);
539
+ });
540
+ });
541
+ }
542
+ /** Authenticate to a tenant via Google and store the tokens. Returns JSON status. */
543
+ export async function login(tenant = "") {
544
+ let baseUrl;
545
+ let host;
546
+ let alias;
547
+ if (tenant) {
548
+ const resolved = tenants.resolve(tenant);
549
+ if (resolved === null) {
550
+ return JSON.stringify({
551
+ error: `Unknown tenant '${tenant}'. Pass an alias, host, or URL.`,
552
+ });
553
+ }
554
+ [baseUrl, host, alias] = resolved;
555
+ }
556
+ else {
557
+ const ctx = tenants.current();
558
+ baseUrl = ctx.baseUrl;
559
+ host = ctx.host;
560
+ alias = hostAlias(ctx.host);
561
+ }
562
+ let idToken;
563
+ try {
564
+ idToken = await browserGoogleLogin(host);
565
+ }
566
+ catch (ex) {
567
+ return JSON.stringify({
568
+ error: ex instanceof Error ? ex.message : String(ex),
569
+ host,
570
+ });
571
+ }
572
+ let result;
573
+ try {
574
+ result = await authPost(baseUrl + OAUTH2_PATH, {
575
+ body: {
576
+ token: idToken,
577
+ clientId: config.GOOGLE_CLIENT_ID,
578
+ clientUrl: host,
579
+ },
580
+ });
581
+ }
582
+ catch (ex) {
583
+ return JSON.stringify({
584
+ error: `Token exchange failed: ${ex instanceof Error ? ex.message : String(ex)}`,
585
+ host,
586
+ });
587
+ }
588
+ const creds = extractCredentials(result.body, result.cookies);
589
+ if (!creds.accessToken) {
590
+ return JSON.stringify({
591
+ error: "Login exchange returned no access token.",
592
+ host,
593
+ });
594
+ }
595
+ store.save(host, creds);
596
+ writeTokensToEnv(creds.accessToken, creds.refreshToken); // Persist both tokens to .env after login
597
+ tenants.register(baseUrl, host);
598
+ tenants.activate(baseUrl, host);
599
+ return JSON.stringify({
600
+ status: "ok",
601
+ tenant: alias,
602
+ host,
603
+ base_url: baseUrl,
604
+ authenticated: true,
605
+ access_expires_at: creds.accessExp,
606
+ refresh_expires_at: creds.refreshExp,
607
+ });
608
+ }
609
+ export function hostAlias(host) {
610
+ const dot = host.indexOf(".");
611
+ return dot === -1 ? host : host.slice(0, dot);
612
+ }