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/dist/store.js ADDED
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Per-tenant credential store backed by the OS keychain (via `@napi-rs/keyring`).
3
+ *
4
+ * Secrets — the Suppa access + refresh tokens — live in the operating system's
5
+ * keychain (Windows Credential Manager, macOS Keychain, Secret Service on Linux),
6
+ * never in plaintext on disk, never in a tool parameter, never in the model
7
+ * context. Each tenant gets one keychain entry keyed by its host.
8
+ *
9
+ * If the keychain backend is unavailable, reads degrade to "no stored
10
+ * credentials" (so the env-token path keeps working) and writes raise a clear
11
+ * error.
12
+ *
13
+ * Faithful 1:1 port of the Python `suppa_mcp/store.py`.
14
+ *
15
+ * PYTHON INTEROP: entries are stored under service name `"suppa-mcp"` as a JSON
16
+ * blob with snake_case keys (`access_token`, `refresh_token`, `access_exp`,
17
+ * `refresh_exp`). This matches the Python server's on-disk format exactly, so an
18
+ * entry written by either server loads in the other. The camelCase `Credentials`
19
+ * shape is a boundary-only convenience.
20
+ */
21
+ import { Entry } from "@napi-rs/keyring";
22
+ export const SERVICE = "suppa-mcp";
23
+ /**
24
+ * Return a keychain `Entry` for `host`, or `null` if the backend cannot load.
25
+ *
26
+ * Mirrors Python's `_keyring()`: any failure constructing the backend means
27
+ * "no store". On this platform `@napi-rs/keyring` is a native addon; a missing
28
+ * or incompatible binary throws at construction.
29
+ */
30
+ function entryFor(host) {
31
+ try {
32
+ return new Entry(SERVICE, host);
33
+ }
34
+ catch {
35
+ // Any construction/backend failure means "no store".
36
+ return null;
37
+ }
38
+ }
39
+ /** True iff the OS keychain backend can be loaded. */
40
+ export function available() {
41
+ // Probe with a throwaway account: constructing an Entry is what would fail
42
+ // if the native backend were missing.
43
+ return entryFor("__suppa_probe__") !== null;
44
+ }
45
+ /** Load credentials for `host`, or `null` if absent / unavailable / corrupt. */
46
+ export function load(host) {
47
+ const entry = entryFor(host);
48
+ if (entry === null) {
49
+ return null;
50
+ }
51
+ let raw;
52
+ try {
53
+ // getPassword returns null when absent on this version; guard against
54
+ // versions that instead throw by treating any error as "absent".
55
+ raw = entry.getPassword();
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ if (!raw) {
61
+ return null;
62
+ }
63
+ try {
64
+ const data = JSON.parse(raw);
65
+ // Keep only known keys, defaulting missing ones (tolerate a partial blob).
66
+ return {
67
+ accessToken: typeof data.access_token === "string" ? data.access_token : "",
68
+ refreshToken: typeof data.refresh_token === "string" ? data.refresh_token : "",
69
+ accessExp: typeof data.access_exp === "number" ? data.access_exp : 0,
70
+ refreshExp: typeof data.refresh_exp === "number" ? data.refresh_exp : 0,
71
+ };
72
+ }
73
+ catch {
74
+ // Corrupt entry: treat as absent.
75
+ return null;
76
+ }
77
+ }
78
+ /** Persist credentials for `host`. Throws if no keychain backend exists. */
79
+ export function save(host, creds) {
80
+ const entry = entryFor(host);
81
+ if (entry === null) {
82
+ throw new Error("No OS keychain backend available — cannot store Suppa credentials.");
83
+ }
84
+ const stored = {
85
+ access_token: creds.accessToken,
86
+ refresh_token: creds.refreshToken,
87
+ access_exp: creds.accessExp,
88
+ refresh_exp: creds.refreshExp,
89
+ };
90
+ entry.setPassword(JSON.stringify(stored));
91
+ }
92
+ /**
93
+ * Delete stored credentials for `host`. Returns `true` iff something was
94
+ * removed; `false` when absent or no backend. Errors are swallowed.
95
+ *
96
+ * Exported as `del` because `delete` is a reserved word.
97
+ */
98
+ export function del(host) {
99
+ const entry = entryFor(host);
100
+ if (entry === null) {
101
+ return false;
102
+ }
103
+ try {
104
+ let raw;
105
+ try {
106
+ raw = entry.getPassword();
107
+ }
108
+ catch {
109
+ return false;
110
+ }
111
+ if (raw === null) {
112
+ return false;
113
+ }
114
+ // deletePassword returns whether an entry was removed.
115
+ return entry.deletePassword();
116
+ }
117
+ catch {
118
+ return false;
119
+ }
120
+ }
@@ -0,0 +1,408 @@
1
+ /**
2
+ * Tenant context — resolves the base URL + auth token for each request.
3
+ *
4
+ * Layers:
5
+ * - `store` — secrets (tokens) in the OS keychain, per tenant.
6
+ * - `registry` — non-secret alias -> base_url map on disk.
7
+ * - this module — the *active* tenant for the session and the
8
+ * `current()` / `ensureValid()` / `getToken()` surface that
9
+ * `httpClient` calls. Every tool stays untouched as this evolves.
10
+ *
11
+ * A TenantContext's token is resolved lazily through a provider that prefers a
12
+ * stored access token (keychain) and falls back to the env token — so the
13
+ * default tenant keeps working with `SUPPA_API_KEY` while logged-in tenants use
14
+ * their keychain credentials. `ensureValid` refreshes expired access tokens
15
+ * transparently before each request.
16
+ *
17
+ * Faithful 1:1 port of the Python `suppa_mcp/tenants.py`.
18
+ *
19
+ * DEPENDENCY CYCLE: `ensureValid` / `reauth` / `probe` lazily import `auth` and
20
+ * `httpClient` INSIDE the functions (via dynamic `await import`) to avoid an
21
+ * import cycle, mirroring the Python `from suppa_mcp import auth` inside the
22
+ * function bodies.
23
+ */
24
+ import { config } from "./config.js";
25
+ import * as registry from "./registry.js";
26
+ import * as store from "./store.js";
27
+ import { jsonResponse } from "./utils.js";
28
+ /** Everything `httpClient` needs to talk to one Suppa tenant. */
29
+ export class TenantContext {
30
+ baseUrl;
31
+ host;
32
+ lang;
33
+ tz;
34
+ tokenProvider;
35
+ staticToken;
36
+ constructor(opts) {
37
+ this.baseUrl = opts.baseUrl;
38
+ this.host = opts.host;
39
+ this.lang = opts.lang ?? config.LANG;
40
+ this.tz = opts.tz ?? config.TZ;
41
+ this.tokenProvider = opts.tokenProvider ?? null;
42
+ this.staticToken = opts.staticToken ?? "";
43
+ }
44
+ getToken() {
45
+ if (this.tokenProvider !== null) {
46
+ return this.tokenProvider();
47
+ }
48
+ return this.staticToken;
49
+ }
50
+ }
51
+ // --------------------------------------------------------------------------
52
+ // Helpers
53
+ // --------------------------------------------------------------------------
54
+ /** `https://modern.suppa.me/` -> `modern.suppa.me`. */
55
+ export function hostOf(baseUrl) {
56
+ const afterScheme = baseUrl.includes("://")
57
+ ? baseUrl.slice(baseUrl.indexOf("://") + 3)
58
+ : baseUrl;
59
+ const noTrailingSlash = afterScheme.replace(/\/+$/, "");
60
+ const slash = noTrailingSlash.indexOf("/");
61
+ return slash === -1 ? noTrailingSlash : noTrailingSlash.slice(0, slash);
62
+ }
63
+ /** First DNS label as a friendly alias: `testing.modern.me` -> `testing`. */
64
+ export function aliasOf(host) {
65
+ const dot = host.indexOf(".");
66
+ return dot === -1 ? host : host.slice(0, dot);
67
+ }
68
+ function tokenProviderFor(host, envFallback = "") {
69
+ return function provider() {
70
+ const creds = store.load(host);
71
+ if (creds && creds.accessToken) {
72
+ return creds.accessToken;
73
+ }
74
+ return envFallback;
75
+ };
76
+ }
77
+ function contextFor(baseUrl, host, envFallback = "") {
78
+ return new TenantContext({
79
+ baseUrl,
80
+ host,
81
+ lang: config.LANG,
82
+ tz: config.TZ,
83
+ tokenProvider: tokenProviderFor(host, envFallback),
84
+ });
85
+ }
86
+ export function defaultHost() {
87
+ return hostOf(config.BASE_URL);
88
+ }
89
+ /** The env-configured tenant (backward compatible). */
90
+ function defaultContext() {
91
+ return contextFor(config.BASE_URL, defaultHost(), config.API_KEY);
92
+ }
93
+ /**
94
+ * If SUPPA_API_KEY and SUPPA_REFRESH_TOKEN are in .env, seed the keychain.
95
+ *
96
+ * This allows the session to stay alive indefinitely as long as auto-refresh
97
+ * happens before token expiry. Both tokens persist to .env after each refresh.
98
+ */
99
+ function bootstrapKeychainFromEnv() {
100
+ if (!(config.API_KEY && config.REFRESH_TOKEN)) {
101
+ return;
102
+ }
103
+ const host = defaultHost();
104
+ const existing = store.load(host);
105
+ if (existing && existing.accessToken) {
106
+ return; // Keychain already has credentials; don't overwrite
107
+ }
108
+ try {
109
+ const creds = {
110
+ accessToken: config.API_KEY,
111
+ refreshToken: config.REFRESH_TOKEN,
112
+ accessExp: 0,
113
+ refreshExp: 0,
114
+ };
115
+ store.save(host, creds);
116
+ }
117
+ catch {
118
+ // keychain unavailable; graceful degradation
119
+ }
120
+ }
121
+ bootstrapKeychainFromEnv();
122
+ // --------------------------------------------------------------------------
123
+ // Active tenant
124
+ // --------------------------------------------------------------------------
125
+ // Deliberately a plain module global. The active tenant is a process-wide
126
+ // session setting (one logical session per stdio process), so it persists
127
+ // across all tool invocations. Code needing a different tenant for one call
128
+ // passes an explicit ctx to makeRequest (see probe) so concurrent tool calls
129
+ // are safe.
130
+ let active = null;
131
+ /** Return the active tenant, falling back to the env-configured default. */
132
+ export function current() {
133
+ if (active === null) {
134
+ active = defaultContext();
135
+ }
136
+ return active;
137
+ }
138
+ export function setActive(ctx) {
139
+ active = ctx;
140
+ }
141
+ /** Build a context for `baseUrl`/`host` and make it the active tenant. */
142
+ export function activate(baseUrl, host) {
143
+ const envFallback = host === defaultHost() ? config.API_KEY : "";
144
+ const ctx = contextFor(baseUrl, host, envFallback);
145
+ setActive(ctx);
146
+ return ctx;
147
+ }
148
+ /**
149
+ * Refresh the tenant's access token if it is missing or near expiry.
150
+ *
151
+ * Delegates to the auth layer (lazily imported to avoid an import cycle).
152
+ * No-op for tenants with no stored session (e.g. the env-token default).
153
+ */
154
+ export async function ensureValid(ctx) {
155
+ const auth = await import("./auth.js");
156
+ auth.maybeRefresh(ctx);
157
+ }
158
+ /** Force a token refresh (used after a 401). Returns True on success. */
159
+ export async function reauth(ctx) {
160
+ const auth = await import("./auth.js");
161
+ return auth.forceRefresh(ctx);
162
+ }
163
+ // --------------------------------------------------------------------------
164
+ // Resolution + registration
165
+ // --------------------------------------------------------------------------
166
+ /**
167
+ * Resolve a user-supplied tenant name to `[baseUrl, host, alias]`.
168
+ *
169
+ * Accepts a known host, a known alias, the env default, or an explicit
170
+ * host/URL. Returns `null` if a bare unknown word can't be turned into a host.
171
+ */
172
+ export function resolve(name) {
173
+ name = (name || "").trim();
174
+ if (!name) {
175
+ return null;
176
+ }
177
+ const reg = registry.load(); // {host: {"alias", "base_url"}}
178
+ // Hosts and aliases are case-insensitive (DNS is), and users type "TESTING"
179
+ // or "Testing.Modern.Me". Match case-insensitively so we re-use the stored
180
+ // tenant instead of registering a mixed-case duplicate with no credentials.
181
+ const key = name.toLowerCase();
182
+ // Known host (exact, then case-insensitive).
183
+ if (name in reg) {
184
+ return [reg[name].base_url, name, reg[name].alias];
185
+ }
186
+ for (const [host, info] of Object.entries(reg)) {
187
+ if (host.toLowerCase() === key || String(info.alias).toLowerCase() === key) {
188
+ return [info.base_url, host, info.alias];
189
+ }
190
+ }
191
+ // The env default by host or its alias.
192
+ const dhost = defaultHost();
193
+ if (key === dhost.toLowerCase() || key === aliasOf(dhost).toLowerCase() || key === "default") {
194
+ return [config.BASE_URL, dhost, aliasOf(dhost)];
195
+ }
196
+ // Explicit URL or host (normalise the host to lower-case; leave URL paths be).
197
+ if (name.includes("://")) {
198
+ const sep = name.indexOf("://");
199
+ const scheme = name.slice(0, sep);
200
+ const rest = name.slice(sep + 3);
201
+ const slashIdx = rest.indexOf("/");
202
+ const hostpart = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
203
+ const path = slashIdx === -1 ? "" : rest.slice(slashIdx + 1);
204
+ // Lower-case the scheme+host (DNS is case-insensitive) so a mixed-case
205
+ // URL can't register a duplicate tenant with its own keychain entry;
206
+ // any path segment keeps its original case.
207
+ const host = hostpart.toLowerCase();
208
+ let baseUrl = `${scheme.toLowerCase()}://${host}` + (path ? `/${path}` : "");
209
+ baseUrl = baseUrl.replace(/\/+$/, "");
210
+ return [baseUrl, host, aliasOf(host)];
211
+ }
212
+ if (name.includes(".")) {
213
+ return [`https://${key}`, key, aliasOf(key)];
214
+ }
215
+ return null;
216
+ }
217
+ /** Add a tenant to the registry. Returns `[alias, host]`. */
218
+ export function register(baseUrl, host = "") {
219
+ host = host || hostOf(baseUrl);
220
+ const alias = aliasOf(host);
221
+ registry.add(host, alias, baseUrl);
222
+ return [alias, host];
223
+ }
224
+ /** Auth + expiry status for a host, for display in listTenants. */
225
+ export function sessionStatus(host) {
226
+ const creds = store.load(host);
227
+ if (creds && creds.accessToken) {
228
+ const exp = creds.refreshExp || 0.0;
229
+ return {
230
+ authenticated: true,
231
+ needs_login: Boolean(exp) && Date.now() / 1000 >= exp,
232
+ session_expires_at: exp || null,
233
+ };
234
+ }
235
+ if (host === defaultHost() && config.API_KEY) {
236
+ return { authenticated: true, needs_login: false, session_expires_at: null };
237
+ }
238
+ return { authenticated: false, needs_login: true, session_expires_at: null };
239
+ }
240
+ // --------------------------------------------------------------------------
241
+ // Tool-facing operations (return JSON strings)
242
+ // --------------------------------------------------------------------------
243
+ export function useTenant(name) {
244
+ const resolved = resolve(name);
245
+ if (resolved === null) {
246
+ const aliases = Object.values(registry.load()).map((info) => info.alias);
247
+ const known = aliases.length > 0 ? aliases : [aliasOf(defaultHost())];
248
+ return jsonResponse({
249
+ error: `Unknown tenant '${name}'. Pass a known alias, a host ` +
250
+ "(e.g. 'testing.modern.me'), or a full URL.",
251
+ known,
252
+ });
253
+ }
254
+ const [baseUrl, host, alias] = resolved;
255
+ // Persist non-default tenants so they show up next time.
256
+ if (host !== defaultHost()) {
257
+ registry.add(host, alias, baseUrl);
258
+ }
259
+ activate(baseUrl, host);
260
+ const status = sessionStatus(host);
261
+ return jsonResponse({
262
+ active: alias,
263
+ host,
264
+ base_url: baseUrl,
265
+ ...status,
266
+ hint: status.authenticated ? null : "Run suppa_login to authenticate this tenant.",
267
+ });
268
+ }
269
+ /**
270
+ * Every known tenant as `[alias, host, baseUrl, isDefault]` — env default
271
+ * first, then registered ones, de-duplicated by host.
272
+ */
273
+ export function allTenants() {
274
+ const dhost = defaultHost();
275
+ const out = [
276
+ [aliasOf(dhost), dhost, config.BASE_URL, true],
277
+ ];
278
+ const seen = new Set([dhost]);
279
+ for (const [host, info] of Object.entries(registry.load())) {
280
+ if (seen.has(host)) {
281
+ continue;
282
+ }
283
+ seen.add(host);
284
+ out.push([info.alias, host, info.base_url, false]);
285
+ }
286
+ return out;
287
+ }
288
+ export function listTenants() {
289
+ const activeHost = current().host;
290
+ const rows = allTenants().map(([alias, host, baseUrl, def]) => ({
291
+ alias,
292
+ host,
293
+ base_url: baseUrl,
294
+ active: host === activeHost,
295
+ default: def,
296
+ ...sessionStatus(host),
297
+ }));
298
+ return jsonResponse({ tenants: rows, keychain_available: store.available() });
299
+ }
300
+ export function logout(name = "") {
301
+ let host;
302
+ if (name) {
303
+ const resolved = resolve(name);
304
+ if (resolved === null) {
305
+ return jsonResponse({ error: `Unknown tenant '${name}'.` });
306
+ }
307
+ host = resolved[1];
308
+ }
309
+ else {
310
+ host = current().host;
311
+ }
312
+ const removed = store.del(host);
313
+ return jsonResponse({
314
+ host,
315
+ credentials_removed: removed,
316
+ note: removed ? "Keychain credentials cleared." : "No stored credentials to remove.",
317
+ });
318
+ }
319
+ // --------------------------------------------------------------------------
320
+ // Diagnostics — verify the whole multi-tenant setup in one shot
321
+ // --------------------------------------------------------------------------
322
+ /**
323
+ * Make a cheap authenticated call against one tenant; report ok/error.
324
+ *
325
+ * Passes an explicit per-tenant context to `makeRequest` instead of temporarily
326
+ * swapping the global active tenant. The normal auth/refresh path still runs —
327
+ * `makeRequest` calls `ensureValid` on the context it's given.
328
+ */
329
+ export async function probe(baseUrl, host) {
330
+ const httpClient = await import("./httpClient.js"); // lazy: avoids an import cycle
331
+ const envFallback = host === defaultHost() ? config.API_KEY : "";
332
+ const ctx = contextFor(baseUrl, host, envFallback);
333
+ try {
334
+ const res = await httpClient.makeRequest("GET", "/api/core/schema", undefined, { ctx });
335
+ return { ok: true, entities_visible: Array.isArray(res) ? res.length : null };
336
+ }
337
+ catch (ex) {
338
+ return { ok: false, error: String(ex instanceof Error ? ex.message : ex).slice(0, 300) };
339
+ }
340
+ }
341
+ /**
342
+ * Validate the multi-tenant configuration. Returns a JSON report.
343
+ *
344
+ * - environment: keychain backend, Google client, login port, registry.
345
+ * - per tenant: registration, stored credentials, expiry, and (deep=true) a
346
+ * live authenticated call that also exercises token refresh.
347
+ */
348
+ export async function diagnostics(deep = true) {
349
+ const registryPath = registry.path();
350
+ let registryExists = false;
351
+ try {
352
+ const { statSync } = await import("node:fs");
353
+ registryExists = statSync(registryPath).isFile();
354
+ }
355
+ catch {
356
+ registryExists = false;
357
+ }
358
+ const environment = {
359
+ keychain_available: store.available(),
360
+ google_client_id_set: Boolean(config.GOOGLE_CLIENT_ID),
361
+ login_origin: `http://localhost:${config.LOGIN_PORT}`,
362
+ login_origin_hint: "Add this to the Google OAuth client's Authorized JavaScript origins.",
363
+ registry_path: String(registryPath),
364
+ registry_exists: registryExists,
365
+ default_base_url: config.BASE_URL,
366
+ default_env_token: Boolean(config.API_KEY),
367
+ };
368
+ const tenantsReport = [];
369
+ for (const [alias, host, baseUrl, def] of allTenants()) {
370
+ const row = {
371
+ alias,
372
+ host,
373
+ base_url: baseUrl,
374
+ default: def,
375
+ ...sessionStatus(host),
376
+ };
377
+ if (deep) {
378
+ row.connectivity = await probe(baseUrl, host);
379
+ }
380
+ tenantsReport.push(row);
381
+ }
382
+ const warnings = [];
383
+ if (!environment.keychain_available) {
384
+ warnings.push("No OS keychain backend — install 'keyring' to store tokens (env token still works).");
385
+ }
386
+ for (const t of tenantsReport) {
387
+ if (t.needs_login) {
388
+ warnings.push(`${t.host}: not authenticated — run suppa_login.`);
389
+ }
390
+ else if (deep && !t.connectivity?.ok) {
391
+ const conn = t.connectivity ?? {};
392
+ warnings.push(`${t.host}: connectivity failed — ${(conn.error ?? "").slice(0, 120)}`);
393
+ }
394
+ }
395
+ let healthy = 0;
396
+ for (const t of tenantsReport) {
397
+ if (!t.needs_login && (!deep || t.connectivity?.ok)) {
398
+ healthy += 1;
399
+ }
400
+ }
401
+ return JSON.stringify({
402
+ status: warnings.length === 0 ? "ok" : "issues",
403
+ environment,
404
+ tenants: tenantsReport,
405
+ summary: { total: tenantsReport.length, healthy },
406
+ warnings,
407
+ }, null, 2);
408
+ }