suppa-mcp-2 1.21.2 → 1.22.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
@@ -237,8 +237,22 @@ function findEnvFile() {
237
237
  }
238
238
  return null;
239
239
  }
240
- /** Write both access and refresh tokens to .env, preserving other content. */
241
- function writeTokensToEnv(accessToken, refreshToken) {
240
+ /**
241
+ * Write both tokens back to the .env they came from — and ONLY there.
242
+ *
243
+ * Two rules, both learned from what the old version did. The file is found by
244
+ * walking UP from the current directory, so it lands on whatever project the
245
+ * user happens to be in: it must therefore already carry SUPPA_API_KEY or
246
+ * SUPPA_REFRESH_TOKEN before anything is written, or Suppa tokens end up in an
247
+ * unrelated repository's .env in plaintext. And the tokens belong to ONE
248
+ * tenant, while SUPPA_API_KEY names the env-configured default: writing tenant
249
+ * B's tokens there made the default tenant send B's credentials on the next
250
+ * start, and seeded B's pair into A's keychain entry.
251
+ */
252
+ function writeTokensToEnv(host, accessToken, refreshToken) {
253
+ if (host !== tenants.defaultHost()) {
254
+ return; // these tokens are not the env-configured tenant's
255
+ }
242
256
  const envPath = findEnvFile();
243
257
  if (!envPath) {
244
258
  return; // No .env file found; skip silently
@@ -250,6 +264,9 @@ function writeTokensToEnv(accessToken, refreshToken) {
250
264
  catch {
251
265
  return; // Can't read file; skip silently
252
266
  }
267
+ if (!/^\s*SUPPA_(API_KEY|REFRESH_TOKEN)\s*=/m.test(content)) {
268
+ return; // not a Suppa .env — never introduce secrets into someone else's file
269
+ }
253
270
  // Preserve line endings (splitlines(keepends=True) equivalent).
254
271
  const lines = content.match(/[^\n]*\n|[^\n]+$/g) ?? [];
255
272
  let foundAccess = false;
@@ -269,11 +286,10 @@ function writeTokensToEnv(accessToken, refreshToken) {
269
286
  result.push(line);
270
287
  }
271
288
  }
272
- if (!foundAccess) {
273
- result.push(`SUPPA_API_KEY=${accessToken}\n`);
274
- }
275
- if (!foundRefresh) {
276
- result.push(`SUPPA_REFRESH_TOKEN=${refreshToken}\n`);
289
+ // Only keys the file already declares are refreshed; a file that carries one
290
+ // of the two does not silently gain the other.
291
+ if (!foundAccess && !foundRefresh) {
292
+ return;
277
293
  }
278
294
  try {
279
295
  writeFileSync(envPath, result.join(""), { encoding: "utf-8" });
@@ -382,34 +398,34 @@ export async function doRefresh(baseUrl, host, creds) {
382
398
  fresh.refreshExp = creds.refreshExp;
383
399
  }
384
400
  store.save(host, fresh);
385
- writeTokensToEnv(fresh.accessToken, fresh.refreshToken); // Persist both tokens to .env
401
+ writeTokensToEnv(host, fresh.accessToken, fresh.refreshToken); // Persist both tokens to .env
386
402
  return fresh;
387
403
  }
388
404
  // ---------------------------------------------------------------------------
389
405
  // Google login (browser loopback + GIS)
390
406
  // ---------------------------------------------------------------------------
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>
407
+ const LOGIN_HTML = `<!doctype html>
408
+ <html><head><meta charset="utf-8"><title>Suppa login</title>
409
+ <script src="https://accounts.google.com/gsi/client" async></script>
410
+ <style>body{font-family:system-ui,sans-serif;display:flex;flex-direction:column;
411
+ align-items:center;justify-content:center;height:100vh;margin:0;gap:1.5rem}
412
+ #msg{color:#444}</style></head>
413
+ <body>
414
+ <h2>Sign in to Suppa &mdash; __HOST__</h2>
415
+ <div id="g_id_onload" data-client_id="__CLIENT_ID__" data-callback="onCred"
416
+ data-auto_select="false" data-ux_mode="popup"></div>
417
+ <div class="g_id_signin" data-type="standard" data-size="large"
418
+ data-text="signin_with" data-shape="rectangular"></div>
419
+ <div id="msg"></div>
420
+ <script>
421
+ function onCred(resp){
422
+ document.getElementById('msg').textContent='Signing in…';
423
+ fetch('/callback',{method:'POST',headers:{'Content-Type':'application/json'},
424
+ body:JSON.stringify({credential:resp.credential,state:"__STATE__"})})
425
+ .then(r=>r.text()).then(t=>{document.body.innerHTML=
426
+ '<h2>'+t+'</h2><p>You can close this tab and return to your agent.</p>';});
427
+ }
428
+ </script>
413
429
  </body></html>`;
414
430
  /** HTML-escape text. Mirrors Python's html.escape (quote=True by default here). */
415
431
  function htmlEscape(text, quote = true) {
@@ -624,7 +640,7 @@ export async function login(tenant = "") {
624
640
  });
625
641
  }
626
642
  store.save(host, creds);
627
- writeTokensToEnv(creds.accessToken, creds.refreshToken); // Persist both tokens to .env after login
643
+ writeTokensToEnv(host, creds.accessToken, creds.refreshToken); // Persist both tokens to .env after login
628
644
  tenants.register(baseUrl, host);
629
645
  tenants.activate(baseUrl, host);
630
646
  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;
@@ -22,7 +22,15 @@ function debug(msg) {
22
22
  * removes must NOT be retried blindly — a retry could double-apply them.
23
23
  */
24
24
  function isSafeRequest(method, url) {
25
- return method === "GET" || url.includes("/search") || url.includes("/select");
25
+ if (method === "GET") {
26
+ return true;
27
+ }
28
+ // Decided on the ACTION segment, never by substring: `url.includes("/search")`
29
+ // made every write to an entity named `searchLogs` or `selections` retryable,
30
+ // and a retry after a gateway 504 that the backend had already committed is a
31
+ // duplicate row reported as one clean success.
32
+ const path = parsedPath(url) ?? rawPath(url);
33
+ return /\/core\/data\/[^/]+\/(?:search|select|select\/validate)$/.test(path);
26
34
  }
27
35
  function headers(ctx, token, extra) {
28
36
  const h = {
@@ -63,7 +71,12 @@ function headers(ctx, token, extra) {
63
71
  * of scheme+host, query string and fragment, had its dot segments resolved, and
64
72
  * been collapsed, trimmed and lowercased.
65
73
  */
66
- const PERMANENT_DELETE_ROUTE = /^(?:api\/)?core\/data\/[^/]+\/delete$/;
74
+ // Anchored on the TAIL, not the head. A tenant reached through a reverse proxy
75
+ // under a path prefix (tenants.resolve deliberately preserves a base-URL path,
76
+ // e.g. https://proxy.example/suppa) put `suppa/api/core/data/X/delete` on the
77
+ // wire, and a head-anchored `^(?:api/)?core/...` let it through. Over-matching
78
+ // is the safe direction: no legitimate route ends in core/data/<x>/delete.
79
+ const PERMANENT_DELETE_ROUTE = /(?:^|\/)core\/data\/[^/]+\/delete$/;
67
80
  // The segments the WHATWG URL parser (the one inside fetch) removes or walks up
68
81
  // on. It matches them ASCII case-insensitively AND through their %2e escapes —
69
82
  // "a single-dot path segment must be '.' or '%2e'; a double-dot path segment
@@ -278,94 +291,231 @@ async function sendWithReauth(ctx, buildHeaders, method, url, data, timeout, opt
278
291
  throw noTokenError(ctx);
279
292
  }
280
293
  const controller = new AbortController();
294
+ // The timer is NOT cleared when headers arrive. It covers the body too:
295
+ // a proxy or platform that sends `200` and then stalls used to hang the
296
+ // tool call forever, because the abort was disarmed the moment fetch()
297
+ // resolved. Every path out of this iteration clears it in `finally`.
281
298
  const timer = setTimeout(() => controller.abort(), timeout * 1000);
282
299
  const started = Date.now();
283
- let res;
300
+ const timedOut = () => new Error(`Request to ${ctx.host} timed out after ${timeout}s. ` +
301
+ "The platform may be slow — retry, or narrow the request (smaller limit/fields).");
284
302
  try {
285
- res = await fetch(url, {
303
+ let res;
304
+ try {
305
+ res = await fetch(url, {
306
+ method,
307
+ headers: buildHeaders(token),
308
+ body: data,
309
+ signal: controller.signal,
310
+ });
311
+ }
312
+ catch (e) {
313
+ const err = e;
314
+ if (err && err.name === "AbortError") {
315
+ debug(`${method} ${url} -> timeout after ${timeout}s`);
316
+ throw timedOut();
317
+ }
318
+ const reason = e instanceof Error ? e.message : String(e);
319
+ debug(`${method} ${url} -> URLError ${reason}`);
320
+ if (retriable && !transientRetried) {
321
+ transientRetried = true;
322
+ await sleep(500);
323
+ continue;
324
+ }
325
+ throw new Error(`Connection error: ${reason}`);
326
+ }
327
+ const outcome = await readResponse(res, {
286
328
  method,
287
- headers: buildHeaders(token),
288
- body: data,
289
- signal: controller.signal,
329
+ url,
330
+ ctx,
331
+ refreshed,
332
+ transientRetried,
333
+ retriable,
334
+ opts,
335
+ started,
336
+ timedOut,
290
337
  });
291
- }
292
- catch (e) {
293
- clearTimeout(timer);
294
- const err = e;
295
- if (err && err.name === "AbortError") {
296
- // Timeout while connecting or reading the response body.
297
- debug(`${method} ${url} -> timeout after ${timeout}s`);
298
- throw new Error(`Request to ${ctx.host} timed out after ${timeout}s. ` +
299
- "The platform may be slow — retry, or narrow the request (smaller limit/fields).");
300
- }
301
- const reason = e instanceof Error ? e.message : String(e);
302
- debug(`${method} ${url} -> URLError ${reason}`);
303
- if (retriable && !transientRetried) {
304
- transientRetried = true;
305
- await sleep(500);
338
+ if (outcome.kind === "retry") {
339
+ if (outcome.refreshed)
340
+ refreshed = true;
341
+ if (outcome.transient)
342
+ transientRetried = true;
306
343
  continue;
307
344
  }
308
- throw new Error(`Connection error: ${reason}`);
345
+ return outcome.value;
309
346
  }
310
347
  finally {
311
348
  clearTimeout(timer);
312
349
  }
313
- const code = res.status;
314
- if (code >= 400) {
315
- debug(`${method} ${url} -> HTTP ${code} (${((Date.now() - started) / 1000).toFixed(2)}s)`);
316
- if (code === 401 && !refreshed && (await tenants.reauth(ctx))) {
317
- refreshed = true;
318
- continue; // token refreshed — retry once
319
- }
320
- if (TRANSIENT_CODES.has(code) && retriable && !transientRetried) {
321
- transientRetried = true;
322
- await sleep(500);
323
- continue;
324
- }
325
- let errorBody = "";
326
- try {
327
- errorBody = await res.text();
328
- }
329
- catch {
330
- // ignore
331
- }
332
- if (code === 401) {
333
- throw new Error(`HTTP 401 for tenant '${ctx.host}': session could not be refreshed. ` +
334
- `Run suppa_login. ${errorBody}`);
335
- }
336
- throw new Error(`HTTP ${code} ${safeStatusText(res)}: ${errorBody}`);
350
+ }
351
+ }
352
+ /**
353
+ * Everything that happens after fetch() resolves, kept inside the timer's
354
+ * scope by the caller. Returns the value to hand back, or an instruction to go
355
+ * round the loop again.
356
+ */
357
+ async function readResponse(res, rc) {
358
+ const { method, url, ctx, opts, started, timedOut } = rc;
359
+ const code = res.status;
360
+ const isAbort = (e) => e?.name === "AbortError";
361
+ /** Read the body as text; an abort during the read IS the timeout. */
362
+ const bodyText = async () => {
363
+ try {
364
+ return await res.text();
337
365
  }
338
- // A download returns bytes, not JSON — reading it as text would corrupt
339
- // anything that is not UTF-8 (every PDF, image and zip). Content-Type comes
340
- // back with it so the caller can name the file sensibly.
341
- if (opts.binary) {
342
- const buf = Buffer.from(await res.arrayBuffer());
343
- if (config.DEBUG) {
344
- debug(`${method} ${url} -> ${code} ${buf.length}B (${((Date.now() - started) / 1000).toFixed(2)}s)`);
345
- }
346
- return {
347
- bytes: buf,
348
- contentType: res.headers.get("content-type") ?? "",
349
- contentDisposition: res.headers.get("content-disposition") ?? "",
350
- };
366
+ catch (e) {
367
+ if (isAbort(e))
368
+ throw timedOut();
369
+ throw e;
351
370
  }
352
- const raw = await res.text();
353
- if (config.DEBUG) {
354
- debug(`${method} ${url} -> ${code} (${((Date.now() - started) / 1000).toFixed(2)}s)`);
371
+ };
372
+ if (code >= 400) {
373
+ debug(`${method} ${url} -> HTTP ${code} (${((Date.now() - started) / 1000).toFixed(2)}s)`);
374
+ if (code === 401 && !rc.refreshed && (await tenants.reauth(ctx))) {
375
+ return { kind: "retry", refreshed: true }; // token refreshed — retry once
355
376
  }
356
- if (!raw || !raw.trim()) {
357
- return null;
377
+ if (TRANSIENT_CODES.has(code) && rc.retriable && !rc.transientRetried) {
378
+ await sleep(500);
379
+ return { kind: "retry", transient: true };
358
380
  }
359
- // Every JSON response this server ever sees passes through here, which is
360
- // the only place a backstop can cover the endpoints whose access flag is
361
- // undocumented as well as the ones where it is set. See stripAccessMetadata.
362
- const result = stripAccessMetadata(JSON.parse(raw));
363
- return opts.unwrap ? unwrapEnvelope(result) : result;
381
+ let errorBody = "";
382
+ try {
383
+ errorBody = await bodyText();
384
+ }
385
+ catch {
386
+ // ignore — the status code is the message
387
+ }
388
+ if (code === 401) {
389
+ throw new Error(`HTTP 401 for tenant '${ctx.host}': the session could not be refreshed ` +
390
+ "(no stored session to refresh, or the platform rejected the refresh). " +
391
+ "Run suppa_login — or, if this tenant is configured through SUPPA_API_KEY, " +
392
+ `set a valid key. ${errorBody}`);
393
+ }
394
+ throw new Error(`HTTP ${code} ${safeStatusText(res)}: ${errorBody}`);
364
395
  }
396
+ // A download returns bytes, not JSON — reading it as text would corrupt
397
+ // anything that is not UTF-8 (every PDF, image and zip). Content-Type comes
398
+ // back with it so the caller can name the file sensibly.
399
+ if (opts.binary) {
400
+ let buf;
401
+ try {
402
+ buf = Buffer.from(await res.arrayBuffer());
403
+ }
404
+ catch (e) {
405
+ if (isAbort(e))
406
+ throw timedOut();
407
+ throw e;
408
+ }
409
+ if (config.DEBUG) {
410
+ debug(`${method} ${url} -> ${code} ${buf.length}B (${((Date.now() - started) / 1000).toFixed(2)}s)`);
411
+ }
412
+ return {
413
+ kind: "value",
414
+ value: {
415
+ bytes: buf,
416
+ contentType: res.headers.get("content-type") ?? "",
417
+ contentDisposition: res.headers.get("content-disposition") ?? "",
418
+ },
419
+ };
420
+ }
421
+ const raw = await bodyText();
422
+ if (config.DEBUG) {
423
+ debug(`${method} ${url} -> ${code} (${((Date.now() - started) / 1000).toFixed(2)}s)`);
424
+ }
425
+ if (!raw || !raw.trim()) {
426
+ return { kind: "value", value: null };
427
+ }
428
+ let parsed;
429
+ try {
430
+ parsed = JSON.parse(raw);
431
+ }
432
+ catch {
433
+ // A bare SyntaxError names neither the request nor the cause. The usual
434
+ // cause is a proxy or login page answering 200 with HTML.
435
+ const preview = raw.slice(0, 160).replace(/\s+/g, " ");
436
+ throw new Error(`${method} ${url} answered ${code} with a body that is not JSON: ${preview}` +
437
+ (raw.length > 160 ? "…" : ""));
438
+ }
439
+ // Unwrap FIRST, then strip. The strip is record-level by design (it never
440
+ // descends into a value), so stripping the {data:[...]} envelope object did
441
+ // nothing and every row inside kept its access arrays. See stripAccessMetadata.
442
+ const result = opts.unwrap ? unwrapEnvelope(parsed) : parsed;
443
+ return { kind: "value", value: stripAccessMetadata(result) };
365
444
  }
366
445
  function sleep(ms) {
367
446
  return new Promise((resolve) => setTimeout(resolve, ms));
368
447
  }
448
+ /**
449
+ * The only characters a path segment may contain on the way to a tenant.
450
+ *
451
+ * Every route this server calls is built from fixed literals, entity and field
452
+ * names (builder.txt:38/:103 — "letters, numbers, underscores", 1–50 chars) and
453
+ * numeric ids. Nothing legitimate needs a dot, a percent sign, a slash inside a
454
+ * segment, a `?` or a `#`. So those are refused — not encoded, REFUSED — at the
455
+ * funnel every request passes through.
456
+ *
457
+ * This is the fix for a real bypass: `suppa_search_records` with
458
+ * entity_name "Tasks/remove?" built `/api/core/data/Tasks/remove?/search`, which
459
+ * the platform routed as POST /core/data/Tasks/remove with the search body's
460
+ * conditions — a mass soft-delete issued by a tool annotated read-only, with no
461
+ * confirmation, reported back as an empty search. Twenty-odd call sites
462
+ * interpolate a caller-supplied name into a path; validating each one is how
463
+ * one gets missed. The funnel cannot be missed.
464
+ */
465
+ const PATH_SEGMENT = /^[A-Za-z0-9_-]+$/;
466
+ export class UnsafePathError extends Error {
467
+ constructor(path, why) {
468
+ super(`REFUSED: '${path}' is not a valid API path — ${why}. ` +
469
+ "Entity and field names may contain only letters, digits and underscores; " +
470
+ "this request was not sent.");
471
+ this.name = "UnsafePathError";
472
+ }
473
+ }
474
+ /**
475
+ * Refuse any path that could be routed as something other than what its
476
+ * literal segments say. Returns the path unchanged when it is acceptable.
477
+ */
478
+ export function assertSafePath(path) {
479
+ if (typeof path !== "string" || !path.startsWith("/")) {
480
+ throw new UnsafePathError(String(path), "it must start with '/'");
481
+ }
482
+ if (/[?#%\\]/.test(path)) {
483
+ throw new UnsafePathError(path, "a path may not contain '?', '#', '%' or a backslash (pass query parameters via opts.query)");
484
+ }
485
+ const segments = path.slice(1).split("/");
486
+ for (const segment of segments) {
487
+ if (segment === "") {
488
+ throw new UnsafePathError(path, "it contains an empty segment ('//' or a trailing '/')");
489
+ }
490
+ if (!PATH_SEGMENT.test(segment)) {
491
+ throw new UnsafePathError(path, `the segment '${segment}' contains characters outside [A-Za-z0-9_-]`);
492
+ }
493
+ }
494
+ return path;
495
+ }
496
+ /**
497
+ * Build the absolute URL for a tenant request: validated path plus an
498
+ * explicitly encoded query string. The one place a path becomes a URL.
499
+ */
500
+ function tenantUrl(ctx, path, query) {
501
+ // Policy before syntax. A hard-delete attempt is refused with the message
502
+ // that names the reversible pair, whatever else is wrong with its path; the
503
+ // generic allowlist is the second layer, for everything else.
504
+ const naive = path.startsWith("/") ? `${ctx.baseUrl}${path}` : path;
505
+ if (isPermanentDeletePath(naive)) {
506
+ throw permanentDeleteRefusal(naive);
507
+ }
508
+ assertSafePath(path);
509
+ let url = `${ctx.baseUrl}${path}`;
510
+ if (query && Object.keys(query).length > 0) {
511
+ const qs = new URLSearchParams();
512
+ for (const [k, v] of Object.entries(query)) {
513
+ qs.set(k, String(v));
514
+ }
515
+ url += `?${qs.toString()}`;
516
+ }
517
+ return url;
518
+ }
369
519
  /**
370
520
  * Make an HTTP request to a Suppa tenant. Returns parsed JSON or null.
371
521
  *
@@ -375,7 +525,7 @@ export async function makeRequest(method, path, body = null, opts = {}) {
375
525
  const ctx = opts.ctx ?? tenants.current();
376
526
  await tenants.ensureValid(ctx);
377
527
  const timeout = opts.timeout ?? config.HTTP_TIMEOUT;
378
- const url = path.startsWith("/") ? `${ctx.baseUrl}${path}` : path;
528
+ const url = tenantUrl(ctx, path, opts.query);
379
529
  let data = null;
380
530
  const extra = { ...(opts.extraHeaders ?? {}) };
381
531
  if (body !== null && body !== undefined) {
@@ -389,7 +539,7 @@ export async function makeRequestRawBytes(method, path, data, contentType, opts
389
539
  const ctx = tenants.current();
390
540
  await tenants.ensureValid(ctx);
391
541
  const timeout = opts.timeout ?? Math.max(120, config.HTTP_TIMEOUT); // uploads need headroom
392
- const url = path.startsWith("/") ? `${ctx.baseUrl}${path}` : path;
542
+ const url = tenantUrl(ctx, path);
393
543
  return sendWithReauth(ctx, (t) => headers(ctx, t, { "Content-Type": contentType }), method, url, data, timeout, { unwrap: false });
394
544
  }
395
545
  /**
@@ -403,7 +553,7 @@ export async function makeRequestBinary(method, path, body = null, opts = {}) {
403
553
  const ctx = tenants.current();
404
554
  await tenants.ensureValid(ctx);
405
555
  const timeout = opts.timeout ?? Math.max(120, config.HTTP_TIMEOUT); // downloads need headroom
406
- const url = path.startsWith("/") ? `${ctx.baseUrl}${path}` : path;
556
+ const url = tenantUrl(ctx, path, opts.query);
407
557
  const payload = body === null || body === undefined ? null : JSON.stringify(body);
408
558
  return (await sendWithReauth(ctx, (t) => headers(ctx, t, payload === null ? null : { "Content-Type": "application/json" }), method, url, payload, timeout, { unwrap: false, binary: true }));
409
559
  }
@@ -463,7 +613,9 @@ export async function selectEntity(entity, filters, fields = null, deletedScope
463
613
  includeDeletedRelations, // data.txt:75 (platform default true; was hard-coded false)
464
614
  deletedScope, // data.txt:76
465
615
  };
466
- const result = await makeRequest("POST", dataUrl(entity, "select") + "?markAsView=false", body);
616
+ const result = await makeRequest("POST", dataUrl(entity, "select"), body, {
617
+ query: { markAsView: false },
618
+ });
467
619
  // The select endpoint returns a list of matching rows; return the first.
468
620
  if (Array.isArray(result)) {
469
621
  return (result.length ? result[0] : null);
package/dist/registry.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  /**
2
3
  * Non-secret registry of known tenants, keyed by host.
3
4
  *
@@ -89,9 +90,24 @@ export function load() {
89
90
  export function save(reg) {
90
91
  const p = path();
91
92
  mkdirSync(homeDir(), { recursive: true });
92
- const tmp = join(homeDir(), "tenants.json.tmp");
93
+ // A UNIQUE temp name per writer. Two MCP clients logging in at once shared
94
+ // one "tenants.json.tmp" and threw EPERM/ENOENT out of rename — after login
95
+ // had already stored the tokens, so it reported failure having succeeded.
96
+ const tmp = join(homeDir(), `tenants.json.${process.pid}.${randomUUID()}.tmp`);
93
97
  writeFileSync(tmp, JSON.stringify(reg, null, 2), "utf-8");
94
- renameSync(tmp, p);
98
+ try {
99
+ renameSync(tmp, p);
100
+ }
101
+ catch (e) {
102
+ // Windows: an antivirus or indexer can hold the target for a moment.
103
+ if (e?.code !== "EPERM")
104
+ throw e;
105
+ const until = Date.now() + 200;
106
+ while (Date.now() < until) {
107
+ /* brief spin — rename is synchronous and this path is rare */
108
+ }
109
+ renameSync(tmp, p);
110
+ }
95
111
  }
96
112
  /** Register (or overwrite) a tenant. */
97
113
  export function add(host, alias, baseUrl) {