suppa-mcp-2 1.21.2 → 1.23.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/dist/auth.js CHANGED
@@ -28,6 +28,7 @@ import { readFileSync, statSync, writeFileSync } from "node:fs";
28
28
  import { config } from "./config.js";
29
29
  import * as store from "./store.js";
30
30
  import * as tenants from "./tenants.js";
31
+ import { recordRefreshFailure, clearRefreshFailure } from "./sessionDiag.js";
31
32
  export const REFRESH_PATH = "/api/auth/accounts/refresh-token";
32
33
  export const OAUTH2_PATH = "/api/auth/accounts/oauth2";
33
34
  export const EXPIRY_SKEW = 30.0; // seconds — refresh this long before the token actually expires
@@ -175,6 +176,28 @@ function readSetCookies(headers) {
175
176
  }
176
177
  return [];
177
178
  }
179
+ /**
180
+ * A non-2xx answer from an auth endpoint, carrying enough to diagnose it.
181
+ *
182
+ * The message is unchanged from the plain Error this replaces; the fields are
183
+ * what lets the refresh layer tell "this route does not exist" (404/405 — the
184
+ * platform moved it) apart from "this token is no good" (401/403 — the session
185
+ * aged out). Those two need opposite actions from the user.
186
+ */
187
+ export class AuthHttpError extends Error {
188
+ status;
189
+ method;
190
+ url;
191
+ body;
192
+ constructor(status, statusText, method, url, body) {
193
+ super(`HTTP ${status} ${statusText}: ${body}`);
194
+ this.name = "AuthHttpError";
195
+ this.status = status;
196
+ this.method = method;
197
+ this.url = url;
198
+ this.body = body;
199
+ }
200
+ }
178
201
  const rawPost = async (url, opts) => {
179
202
  const { cookie = "", body = null, timeout = 60, method = "POST" } = opts;
180
203
  const headers = {
@@ -210,7 +233,7 @@ const rawPost = async (url, opts) => {
210
233
  clearTimeout(timer);
211
234
  const raw = await resp.text();
212
235
  if (!resp.ok) {
213
- throw new Error(`HTTP ${resp.status} ${resp.statusText}: ${raw}`);
236
+ throw new AuthHttpError(resp.status, resp.statusText, method, url, raw);
214
237
  }
215
238
  const cookies = readSetCookies(resp.headers);
216
239
  const parsed = raw.trim() ? JSON.parse(raw) : {};
@@ -237,8 +260,22 @@ function findEnvFile() {
237
260
  }
238
261
  return null;
239
262
  }
240
- /** Write both access and refresh tokens to .env, preserving other content. */
241
- function writeTokensToEnv(accessToken, refreshToken) {
263
+ /**
264
+ * Write both tokens back to the .env they came from — and ONLY there.
265
+ *
266
+ * Two rules, both learned from what the old version did. The file is found by
267
+ * walking UP from the current directory, so it lands on whatever project the
268
+ * user happens to be in: it must therefore already carry SUPPA_API_KEY or
269
+ * SUPPA_REFRESH_TOKEN before anything is written, or Suppa tokens end up in an
270
+ * unrelated repository's .env in plaintext. And the tokens belong to ONE
271
+ * tenant, while SUPPA_API_KEY names the env-configured default: writing tenant
272
+ * B's tokens there made the default tenant send B's credentials on the next
273
+ * start, and seeded B's pair into A's keychain entry.
274
+ */
275
+ function writeTokensToEnv(host, accessToken, refreshToken) {
276
+ if (host !== tenants.defaultHost()) {
277
+ return; // these tokens are not the env-configured tenant's
278
+ }
242
279
  const envPath = findEnvFile();
243
280
  if (!envPath) {
244
281
  return; // No .env file found; skip silently
@@ -250,6 +287,9 @@ function writeTokensToEnv(accessToken, refreshToken) {
250
287
  catch {
251
288
  return; // Can't read file; skip silently
252
289
  }
290
+ if (!/^\s*SUPPA_(API_KEY|REFRESH_TOKEN)\s*=/m.test(content)) {
291
+ return; // not a Suppa .env — never introduce secrets into someone else's file
292
+ }
253
293
  // Preserve line endings (splitlines(keepends=True) equivalent).
254
294
  const lines = content.match(/[^\n]*\n|[^\n]+$/g) ?? [];
255
295
  let foundAccess = false;
@@ -269,11 +309,10 @@ function writeTokensToEnv(accessToken, refreshToken) {
269
309
  result.push(line);
270
310
  }
271
311
  }
272
- if (!foundAccess) {
273
- result.push(`SUPPA_API_KEY=${accessToken}\n`);
274
- }
275
- if (!foundRefresh) {
276
- result.push(`SUPPA_REFRESH_TOKEN=${refreshToken}\n`);
312
+ // Only keys the file already declares are refreshed; a file that carries one
313
+ // of the two does not silently gain the other.
314
+ if (!foundAccess && !foundRefresh) {
315
+ return;
277
316
  }
278
317
  try {
279
318
  writeFileSync(envPath, result.join(""), { encoding: "utf-8" });
@@ -299,6 +338,23 @@ function refreshDead(creds) {
299
338
  const exp = creds.refreshExp || jwtExp(creds.refreshToken);
300
339
  return !creds.refreshToken || (Boolean(exp) && Date.now() / 1000 >= exp);
301
340
  }
341
+ /**
342
+ * Record the one refresh failure that never reaches the network: the stored
343
+ * refresh token is already past its expiry. This IS the case where signing in
344
+ * again is the right answer, and saying the date makes that obvious instead of
345
+ * leaving "session expired" to compete with every other cause.
346
+ */
347
+ function noteExpiredRefresh(host, creds) {
348
+ const exp = creds.refreshExp || jwtExp(creds.refreshToken);
349
+ if (!creds.refreshToken) {
350
+ recordRefreshFailure(host, "no refresh token is stored for this tenant, so the session could not be extended");
351
+ return;
352
+ }
353
+ recordRefreshFailure(host, exp
354
+ ? `the stored refresh token expired on ${readableDate(exp)} — a Suppa session lasts ` +
355
+ "about ten days, so this one simply aged out and suppa_login starts a new one"
356
+ : "the stored refresh token is no longer valid; suppa_login starts a new session");
357
+ }
302
358
  /** Refresh `ctx`'s access token if needed. No-op when there's no session. */
303
359
  export async function maybeRefresh(ctx) {
304
360
  let creds = store.load(ctx.host);
@@ -317,6 +373,7 @@ export async function maybeRefresh(ctx) {
317
373
  return;
318
374
  }
319
375
  if (refreshDead(fresh)) {
376
+ noteExpiredRefresh(ctx.host, fresh);
320
377
  throw new ReloginRequired(ctx.host);
321
378
  }
322
379
  await doRefresh(ctx.baseUrl, ctx.host, fresh);
@@ -339,6 +396,9 @@ export async function maybeRefresh(ctx) {
339
396
  export async function forceRefresh(ctx) {
340
397
  const creds = store.load(ctx.host);
341
398
  if (!creds || refreshDead(creds)) {
399
+ if (creds) {
400
+ noteExpiredRefresh(ctx.host, creds);
401
+ }
342
402
  return false;
343
403
  }
344
404
  let promise = inflight.get(ctx.host);
@@ -346,6 +406,9 @@ export async function forceRefresh(ctx) {
346
406
  promise = (async () => {
347
407
  const fresh = store.load(ctx.host);
348
408
  if (!fresh || refreshDead(fresh)) {
409
+ if (fresh) {
410
+ noteExpiredRefresh(ctx.host, fresh);
411
+ }
349
412
  throw new ReloginRequired(ctx.host);
350
413
  }
351
414
  await doRefresh(ctx.baseUrl, ctx.host, fresh);
@@ -364,16 +427,76 @@ export async function forceRefresh(ctx) {
364
427
  return false;
365
428
  }
366
429
  }
430
+ /** Statuses that mean "this route does not answer that verb" — not "no". */
431
+ const VERB_MISMATCH = new Set([404, 405]);
432
+ /** The verb that last worked for a host's refresh route. */
433
+ const refreshVerb = new Map();
434
+ /** A date a person can read, from epoch seconds. */
435
+ function readableDate(epochSeconds) {
436
+ return new Date(epochSeconds * 1000).toISOString().replace("T", " ").slice(0, 16) + " UTC";
437
+ }
438
+ /**
439
+ * Call the refresh route, surviving a change of verb.
440
+ *
441
+ * The platform has moved this route once already — it used to accept POST and
442
+ * now accepts only GET — and the whole session dies the moment the server
443
+ * guesses wrong. A 404/405 means nothing happened, so trying the other verb
444
+ * once costs one wasted request and saves the session; the verb that works is
445
+ * then remembered per host, so the mistake is paid once, not on every refresh.
446
+ */
447
+ async function callRefresh(baseUrl, host, creds) {
448
+ const url = baseUrl + REFRESH_PATH;
449
+ const cookie = `refreshToken=${creds.refreshToken}`;
450
+ const first = refreshVerb.get(host) ?? "GET";
451
+ const second = first === "GET" ? "POST" : "GET";
452
+ try {
453
+ const result = await authPost(url, { cookie, method: first });
454
+ refreshVerb.set(host, first);
455
+ return result;
456
+ }
457
+ catch (e) {
458
+ if (!(e instanceof AuthHttpError) || !VERB_MISMATCH.has(e.status)) {
459
+ throw e; // the route answered on the merits — asking again as a verb it
460
+ // does accept would just be a second failed auth attempt
461
+ }
462
+ const result = await authPost(url, { cookie, method: second });
463
+ refreshVerb.set(host, second);
464
+ return result;
465
+ }
466
+ }
467
+ /** Turn a refresh failure into a sentence that names the actual problem. */
468
+ function refreshFailureReason(e) {
469
+ if (e instanceof AuthHttpError) {
470
+ if (VERB_MISMATCH.has(e.status)) {
471
+ return (`the tenant answered HTTP ${e.status} for both GET and POST ${REFRESH_PATH} — ` +
472
+ "the platform's auth API has moved, so signing in again will only buy one more " +
473
+ "access-token lifetime. Install a newer suppa-mcp-2 (npm i -g suppa-mcp-2@latest) " +
474
+ "or report this if none exists yet");
475
+ }
476
+ if (e.status === 401 || e.status === 403) {
477
+ return (`the platform rejected the stored refresh token (HTTP ${e.status}) — the refresh ` +
478
+ "window has run out or the session was revoked; suppa_login starts a new one");
479
+ }
480
+ return `the refresh endpoint answered HTTP ${e.status}: ${e.body.slice(0, 200)}`;
481
+ }
482
+ if (e instanceof ReloginRequired) {
483
+ return e.message;
484
+ }
485
+ return `the refresh request failed: ${e instanceof Error ? e.message : String(e)}`;
486
+ }
367
487
  export async function doRefresh(baseUrl, host, creds) {
368
- // The platform exposes refresh as GET only (the web client does
369
- // `axios.get('/auth/accounts/refresh-token', { withCredentials })`);
370
- // a POST 404s on production backends.
371
- const { body, cookies } = await authPost(baseUrl + REFRESH_PATH, {
372
- cookie: `refreshToken=${creds.refreshToken}`,
373
- method: "GET",
374
- });
488
+ let body;
489
+ let cookies;
490
+ try {
491
+ ({ body, cookies } = await callRefresh(baseUrl, host, creds));
492
+ }
493
+ catch (e) {
494
+ recordRefreshFailure(host, refreshFailureReason(e));
495
+ throw e;
496
+ }
375
497
  const fresh = extractCredentials(body, cookies);
376
498
  if (!fresh.accessToken) {
499
+ recordRefreshFailure(host, `the refresh endpoint returned HTTP 200 with no access token in it (${REFRESH_PATH})`);
377
500
  throw new ReloginRequired(host);
378
501
  }
379
502
  if (!fresh.refreshToken) {
@@ -382,34 +505,35 @@ export async function doRefresh(baseUrl, host, creds) {
382
505
  fresh.refreshExp = creds.refreshExp;
383
506
  }
384
507
  store.save(host, fresh);
385
- writeTokensToEnv(fresh.accessToken, fresh.refreshToken); // Persist both tokens to .env
508
+ clearRefreshFailure(host);
509
+ writeTokensToEnv(host, fresh.accessToken, fresh.refreshToken); // Persist both tokens to .env
386
510
  return fresh;
387
511
  }
388
512
  // ---------------------------------------------------------------------------
389
513
  // Google login (browser loopback + GIS)
390
514
  // ---------------------------------------------------------------------------
391
- const LOGIN_HTML = `<!doctype html>
392
- <html><head><meta charset="utf-8"><title>Suppa login</title>
393
- <script src="https://accounts.google.com/gsi/client" async></script>
394
- <style>body{font-family:system-ui,sans-serif;display:flex;flex-direction:column;
395
- align-items:center;justify-content:center;height:100vh;margin:0;gap:1.5rem}
396
- #msg{color:#444}</style></head>
397
- <body>
398
- <h2>Sign in to Suppa &mdash; __HOST__</h2>
399
- <div id="g_id_onload" data-client_id="__CLIENT_ID__" data-callback="onCred"
400
- data-auto_select="false" data-ux_mode="popup"></div>
401
- <div class="g_id_signin" data-type="standard" data-size="large"
402
- data-text="signin_with" data-shape="rectangular"></div>
403
- <div id="msg"></div>
404
- <script>
405
- function onCred(resp){
406
- document.getElementById('msg').textContent='Signing in…';
407
- fetch('/callback',{method:'POST',headers:{'Content-Type':'application/json'},
408
- body:JSON.stringify({credential:resp.credential,state:"__STATE__"})})
409
- .then(r=>r.text()).then(t=>{document.body.innerHTML=
410
- '<h2>'+t+'</h2><p>You can close this tab and return to your agent.</p>';});
411
- }
412
- </script>
515
+ const LOGIN_HTML = `<!doctype html>
516
+ <html><head><meta charset="utf-8"><title>Suppa login</title>
517
+ <script src="https://accounts.google.com/gsi/client" async></script>
518
+ <style>body{font-family:system-ui,sans-serif;display:flex;flex-direction:column;
519
+ align-items:center;justify-content:center;height:100vh;margin:0;gap:1.5rem}
520
+ #msg{color:#444}</style></head>
521
+ <body>
522
+ <h2>Sign in to Suppa &mdash; __HOST__</h2>
523
+ <div id="g_id_onload" data-client_id="__CLIENT_ID__" data-callback="onCred"
524
+ data-auto_select="false" data-ux_mode="popup"></div>
525
+ <div class="g_id_signin" data-type="standard" data-size="large"
526
+ data-text="signin_with" data-shape="rectangular"></div>
527
+ <div id="msg"></div>
528
+ <script>
529
+ function onCred(resp){
530
+ document.getElementById('msg').textContent='Signing in…';
531
+ fetch('/callback',{method:'POST',headers:{'Content-Type':'application/json'},
532
+ body:JSON.stringify({credential:resp.credential,state:"__STATE__"})})
533
+ .then(r=>r.text()).then(t=>{document.body.innerHTML=
534
+ '<h2>'+t+'</h2><p>You can close this tab and return to your agent.</p>';});
535
+ }
536
+ </script>
413
537
  </body></html>`;
414
538
  /** HTML-escape text. Mirrors Python's html.escape (quote=True by default here). */
415
539
  function htmlEscape(text, quote = true) {
@@ -624,7 +748,7 @@ export async function login(tenant = "") {
624
748
  });
625
749
  }
626
750
  store.save(host, creds);
627
- writeTokensToEnv(creds.accessToken, creds.refreshToken); // Persist both tokens to .env after login
751
+ writeTokensToEnv(host, creds.accessToken, creds.refreshToken); // Persist both tokens to .env after login
628
752
  tenants.register(baseUrl, host);
629
753
  tenants.activate(baseUrl, host);
630
754
  return JSON.stringify({
package/dist/config.js CHANGED
@@ -118,9 +118,31 @@ const API_KEY = process.env.SUPPA_API_KEY || process.env.SUPPA_TOKEN || "";
118
118
  const REFRESH_TOKEN = process.env.SUPPA_REFRESH_TOKEN || "";
119
119
  const LANG = process.env.SUPPA_LANG || "en";
120
120
  const TZ = process.env.SUPPA_TZ || "Europe/Kyiv";
121
- const TASKS_ENTITY_ID = parseInt(process.env.SUPPA_TASKS_ENTITY_ID || "37", 10);
121
+ /**
122
+ * A positive integer from the environment, or the fallback.
123
+ *
124
+ * `parseInt("abc")` is NaN and `parseInt("0")` is 0; both used to flow straight
125
+ * into setTimeout and the login server, so a typo in SUPPA_HTTP_TIMEOUT made
126
+ * every request fail after a millisecond with "timed out after NaNs — the
127
+ * platform may be slow". A configuration mistake must not be reported as a
128
+ * platform problem: fall back, and say so once on stderr.
129
+ */
130
+ function positiveIntEnv(name, fallback, max = Number.MAX_SAFE_INTEGER) {
131
+ const raw = process.env[name];
132
+ if (raw === undefined || raw.trim() === "") {
133
+ return fallback;
134
+ }
135
+ const n = Number.parseInt(raw, 10);
136
+ if (!Number.isFinite(n) || n <= 0 || n > max) {
137
+ process.stderr.write(`suppa-mcp: ${name}=${JSON.stringify(raw)} is not a positive integer` +
138
+ `${max !== Number.MAX_SAFE_INTEGER ? ` up to ${max}` : ""}; using ${fallback}.\n`);
139
+ return fallback;
140
+ }
141
+ return n;
142
+ }
143
+ const TASKS_ENTITY_ID = positiveIntEnv("SUPPA_TASKS_ENTITY_ID", 37);
122
144
  // Default per-request timeout (seconds); uploads use at least 120s.
123
- const HTTP_TIMEOUT = parseInt(process.env.SUPPA_HTTP_TIMEOUT || "60", 10);
145
+ const HTTP_TIMEOUT = positiveIntEnv("SUPPA_HTTP_TIMEOUT", 60);
124
146
  // When truthy, log each request line (method, URL, status, duration) to stderr.
125
147
  const DEBUG = ["1", "true", "yes"].includes((process.env.SUPPA_MCP_DEBUG || "").toLowerCase());
126
148
  // ---------------------------------------------------------------------------
@@ -137,7 +159,7 @@ const V1_ACCESS_TOKEN = process.env.SUPPA_V1_ACCESS_TOKEN || "";
137
159
  // "Authorized JavaScript origins" in Google Cloud for the in-browser flow.
138
160
  const GOOGLE_CLIENT_ID = process.env.SUPPA_GOOGLE_CLIENT_ID ||
139
161
  "294101885657-gl7ee19of4e2h5g8fj99q21ct74l0etg.apps.googleusercontent.com";
140
- const LOGIN_PORT = parseInt(process.env.SUPPA_MCP_LOGIN_PORT || "8080", 10);
162
+ const LOGIN_PORT = positiveIntEnv("SUPPA_MCP_LOGIN_PORT", 8080, 65535);
141
163
  /** Return a masked preview of a secret for safe logging. */
142
164
  export function maskedKey(value = "") {
143
165
  const secret = value || API_KEY;