@mcpjam/inspector 3.13.0 → 3.14.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.
Files changed (46) hide show
  1. package/bin/runtime-profile.mjs +774 -0
  2. package/bin/start.js +117 -24
  3. package/dist/client/assets/{OAuthDesktopReturnNotice-D5tJNqny.js → OAuthDesktopReturnNotice-D7d-faB1.js} +2 -2
  4. package/dist/client/assets/{app-bootstrap-baadQQNk.js → app-bootstrap-BtDjj9nz.js} +350 -350
  5. package/dist/client/assets/{button-DHPqnOj6.js → button-B99pZFz_.js} +2 -2
  6. package/dist/client/assets/{chunk-D32TOXHM-BPB6AqSK.js → chunk-D32TOXHM-Bcyg0ZVj.js} +5 -5
  7. package/dist/client/assets/{dead-clicks-autocapture-Cbczl2El.js → dead-clicks-autocapture-CnUHv5CB.js} +2 -2
  8. package/dist/client/assets/{error-reporting-CORfsjyM.js → error-reporting-BohBwcQQ.js} +4 -4
  9. package/dist/client/assets/{error-reporting-B4hGM_ob.js → error-reporting-p6G1ojum.js} +1 -1
  10. package/dist/client/assets/{exception-autocapture-CMOUrnel.js → exception-autocapture-Q-isBTHp.js} +2 -2
  11. package/dist/client/assets/{failed-request-tracker-DoQRXuIy.js → failed-request-tracker-BBJW8izb.js} +2 -2
  12. package/dist/client/assets/{highlighted-body-KQOG7T2V-_ljE4u1k.js → highlighted-body-KQOG7T2V-zsXWRnSM.js} +2 -2
  13. package/dist/client/assets/{index-BBr8TZVx.js → index-C9oFRqoK.js} +3 -3
  14. package/dist/client/assets/{jszip.min-C-vIQbxH.js → jszip.min-C86zG41a.js} +2 -2
  15. package/dist/client/assets/{mermaid-MCJ5UELQ-DTJaEEBm.js → mermaid-MCJ5UELQ-DAW4LYwz.js} +1 -1
  16. package/dist/client/assets/{posthog-recorder-Dby9Z8HR.js → posthog-recorder-trUd0BXy.js} +2 -2
  17. package/dist/client/assets/{preload-helper-Dvt1a6xa.js → preload-helper-Buauuydw.js} +2 -2
  18. package/dist/client/assets/{react-CD7Pk4KS.js → react-CZb-kDOs.js} +2 -2
  19. package/dist/client/assets/{rolldown-runtime-mzU9SaVm.js → rolldown-runtime-Bkua2_Tb.js} +1 -1
  20. package/dist/client/assets/{surveys-DYqpu8xl.js → surveys-BISK_WOT.js} +2 -2
  21. package/dist/client/assets/{trace-timeline-PnE1ouRj.js → trace-timeline-CRewsP1E.js} +2 -2
  22. package/dist/client/assets/{trace-timeline-WXINST5z.js → trace-timeline-D-DWE-sO.js} +1 -1
  23. package/dist/client/assets/{web-vitals-BLq6M5vx.js → web-vitals-DqmZ9w02.js} +2 -2
  24. package/dist/client/index.html +7 -7
  25. package/dist/server/authorization-MA42CNYT.js +22 -0
  26. package/dist/server/chunk-7M3XVZCQ.js +381 -0
  27. package/dist/server/{chunk-MBS3EZ3U.js → chunk-7ZIR7SX7.js} +5 -44
  28. package/dist/server/chunk-C47PTIDS.js +487 -0
  29. package/dist/server/chunk-DHRTCKJA.js +3979 -0
  30. package/dist/server/chunk-HJTKF2X6.js +45 -0
  31. package/dist/server/{chunk-2FVSBJQF.js → chunk-KNO4KZJF.js} +224 -758
  32. package/dist/server/{chunk-QHYREDE3.js → chunk-RWFTW2EW.js} +7 -5
  33. package/dist/server/chunk-SDWJSPSI.js +252 -0
  34. package/dist/server/chunk-VFRLMHOC.js +33 -0
  35. package/dist/server/chunk-XSQ2GC45.js +438 -0
  36. package/dist/server/chunk-YQ2BTE46.js +88 -0
  37. package/dist/server/{consent-lifetime-TYLDY64H.js → consent-lifetime-OXQM37RV.js} +4 -3
  38. package/dist/server/grants-UVE62NGN.js +37 -0
  39. package/dist/server/harness-install-cli.js +239 -4
  40. package/dist/server/index.js +9044 -9216
  41. package/dist/server/local-turn-XSUGEKTL.js +19 -0
  42. package/dist/server/runtime-health-TCF3ZEKS.js +28 -0
  43. package/dist/server/runtime-lifecycle-YQ3KWDLJ.js +53 -0
  44. package/package.json +26 -23
  45. package/dist/server/chunk-I7ZVTBZP.js +0 -3100
  46. package/dist/server/local-turn-VQDSTY6T.js +0 -12
@@ -0,0 +1,774 @@
1
+ /**
2
+ * ONE resolved runtime configuration per Inspector instance.
3
+ *
4
+ * The launcher resolves it once — which backend, which WorkOS client, which
5
+ * guest authority, which ports and origins — and hands the result to the
6
+ * server, Vite and the platform MCP worker explicitly. None of them then reads
7
+ * configuration files of its own (`MCPJAM_RESOLVED_RUNTIME=1`), so no child can
8
+ * quietly fill a value the selected profile left out from some other file.
9
+ *
10
+ * Plain ESM with no dependencies: it runs under a bare Node before anything is
11
+ * built (`bin/start.js`, `scripts/*.mjs`, the Vite config).
12
+ *
13
+ * PROFILES. A target is resolved from layers, lowest priority first:
14
+ *
15
+ * local (default) the committed standard OSS profile (`.env.local`), then a
16
+ * developer overlay: this worktree's `.env.development.local`,
17
+ * or — only because no target was selected — the main
18
+ * worktree's, read in place and never copied.
19
+ * --env-file F F alone. Explicit selection wins over everything.
20
+ * staging public staging defaults, the MCPJAM_STAGING_* URLs, then
21
+ * this worktree's `.env.staging.local`.
22
+ * preview A B public staging defaults (WorkOS client, hosted guest
23
+ * authority), then `--env-file` if given, then the two URLs.
24
+ *
25
+ * Settings that belong together are resolved as a GROUP: the backend group
26
+ * (Convex addresses, guest authority, every backend-bound credential) and the
27
+ * auth group (WorkOS ids/credentials, CLI/Slack/Discord auth) each come
28
+ * entirely from the highest layer that sets any of their keys. A developer
29
+ * overlay that points at another deployment therefore cannot inherit the
30
+ * standard profile's credentials, and an explicit target never inherits the
31
+ * standard profile at all.
32
+ */
33
+ import { existsSync, readFileSync } from "node:fs";
34
+ import { dirname, join, resolve } from "node:path";
35
+
36
+ export const RESOLVED_RUNTIME_MARKER = "MCPJAM_RESOLVED_RUNTIME";
37
+
38
+ /** Public, non-secret identifiers. Client ids are not credentials. */
39
+ export const STAGING_WORKOS_CLIENT_ID = "client_01K4C1TVA6CMQ3G32F1P301A9G";
40
+ export const STAGING_HOSTED_ORIGIN = "https://staging.mcpjam.com";
41
+ const KNOWN_AUTHKIT_DOMAINS = {
42
+ client_01K4C1TVPBE7JTBFQJF9SDW9P9: "login.mcpjam.com",
43
+ client_01K4C1TVA6CMQ3G32F1P301A9G: "dynamic-echo-14-staging.authkit.app",
44
+ client_01KTN2EWHHJCKRB8RSR307X4SG: "deep-vanilla-68-test.authkit.app",
45
+ };
46
+
47
+ const BACKEND_KEYS = new Set([
48
+ "CONVEX_URL",
49
+ "VITE_CONVEX_URL",
50
+ "CONVEX_HTTP_URL",
51
+ "VITE_CONVEX_SITE_URL",
52
+ "CONVEX_DEPLOYMENT",
53
+ "MCPJAM_GUEST_AUTHORITY",
54
+ "MCPJAM_GUEST_AUTHORITY_ORIGIN",
55
+ "MCPJAM_GUEST_SESSION_URL",
56
+ "MCPJAM_GUEST_SESSION_REVOKE_URL",
57
+ "MCPJAM_GUEST_PROMOTION_PROOF_URL",
58
+ "MCPJAM_GUEST_JWKS_URL",
59
+ "MCPJAM_GUEST_SESSION_SHARED_SECRET",
60
+ "GUEST_SESSION_HASH_PEPPER",
61
+ "INSPECTOR_SERVICE_TOKEN",
62
+ ]);
63
+ const BACKEND_PREFIXES = ["DEPLOYMENT_SESSION_JWT_", "COMPUTERS_"];
64
+
65
+ const AUTH_KEYS = new Set([
66
+ "WORKOS_CLIENT_ID",
67
+ "VITE_WORKOS_CLIENT_ID",
68
+ "WORKOS_API_KEY",
69
+ "WORKOS_API_HOSTNAME",
70
+ "VITE_WORKOS_API_HOSTNAME",
71
+ "WORKOS_ISSUER",
72
+ "AUTHKIT_DOMAIN",
73
+ "VITE_WORKOS_REDIRECT_URI",
74
+ ]);
75
+ const AUTH_PREFIXES = ["CLI_AUTH_", "SLACK_", "DISCORD_"];
76
+
77
+ /**
78
+ * Per-instance addresses. Always computed from this instance's ports (or kept
79
+ * only when they deliberately name a non-loopback public origin) — a value
80
+ * inherited from the main instance must never survive a port change.
81
+ */
82
+ export const INSTANCE_KEYS = [
83
+ "MCPJAM_BROWSER_PORT",
84
+ "CLIENT_PORT",
85
+ "SERVER_PORT",
86
+ "PORT",
87
+ "VITE_API_BASE_URL",
88
+ "BASE_URL",
89
+ "WEB_ALLOWED_ORIGINS",
90
+ "CLI_AUTH_PUBLIC_ORIGIN",
91
+ "SLACK_LINK_PUBLIC_ORIGIN",
92
+ "DISCORD_LINK_PUBLIC_ORIGIN",
93
+ "MCPJAM_PLATFORM_MCP_URL",
94
+ "MCPJAM_INSPECTOR_FRONTEND_URL",
95
+ ];
96
+
97
+ /** Names that may carry a secret; their values never appear in output. */
98
+ const SECRET_NAME = /(SECRET|TOKEN|KEY|PEPPER|PASSWORD|PRIVATE)/i;
99
+
100
+ export function profileGroupOf(name) {
101
+ if (
102
+ BACKEND_KEYS.has(name) ||
103
+ BACKEND_PREFIXES.some((p) => name.startsWith(p))
104
+ ) {
105
+ return "backend";
106
+ }
107
+ if (
108
+ AUTH_KEYS.has(name) ||
109
+ (AUTH_PREFIXES.some((p) => name.startsWith(p)) &&
110
+ !INSTANCE_KEYS.includes(name))
111
+ ) {
112
+ return "auth";
113
+ }
114
+ return null;
115
+ }
116
+
117
+ /** Every key a profile owns: grouped settings plus per-instance addresses. */
118
+ export function isProfileOwnedKey(name) {
119
+ return profileGroupOf(name) !== null || INSTANCE_KEYS.includes(name);
120
+ }
121
+
122
+ export class RuntimeConfigError extends Error {
123
+ constructor(message) {
124
+ super(message);
125
+ this.name = "RuntimeConfigError";
126
+ }
127
+ }
128
+
129
+ // ── .env files ──────────────────────────────────────────────────────────────
130
+
131
+ /** Index of the first closing `quote` in `text`; `\` escapes in `"` only. */
132
+ function closingQuoteIndex(text, quote) {
133
+ for (let j = 0; j < text.length; j += 1) {
134
+ if (quote === '"' && text[j] === "\\") {
135
+ j += 1;
136
+ continue;
137
+ }
138
+ if (text[j] === quote) return j;
139
+ }
140
+ return -1;
141
+ }
142
+
143
+ /** Reverse `formatEnvAssignment`: `\n`, `\r`, `\"`, `\\`; others stay as-is. */
144
+ function decodeDoubleQuoted(text) {
145
+ return text.replace(/\\([nr"\\])/g, (_, c) =>
146
+ c === "n" ? "\n" : c === "r" ? "\r" : c,
147
+ );
148
+ }
149
+
150
+ /**
151
+ * Parse a dotenv file: `KEY=value`, `export KEY=value`, `#` comments, single /
152
+ * double quotes, and double-quoted `\n` / `\"` / `\\` escapes (multi-line PEMs).
153
+ */
154
+ export function parseEnvText(text) {
155
+ const out = {};
156
+ const lines = String(text).split(/\r?\n/);
157
+ for (let i = 0; i < lines.length; i += 1) {
158
+ const line = lines[i].trim();
159
+ if (!line || line.startsWith("#")) continue;
160
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(
161
+ line,
162
+ );
163
+ if (!match) continue;
164
+ const [, key, rawValue] = match;
165
+ let value = rawValue;
166
+ const quote = value[0];
167
+ if (quote === '"' || quote === "'") {
168
+ // A quoted value may span lines until its first unescaped closing
169
+ // quote; anything after it (e.g. `# comment`) is ignored.
170
+ let body = value.slice(1);
171
+ let end = closingQuoteIndex(body, quote);
172
+ while (end === -1 && i + 1 < lines.length) {
173
+ i += 1;
174
+ body += `\n${lines[i]}`;
175
+ end = closingQuoteIndex(body, quote);
176
+ }
177
+ if (end === -1) {
178
+ throw new RuntimeConfigError(
179
+ `The value of ${key} opens a ${quote} quote that is never closed.`,
180
+ );
181
+ }
182
+ value = body.slice(0, end);
183
+ if (quote === '"') value = decodeDoubleQuoted(value);
184
+ } else {
185
+ value = value.replace(/\s+#.*$/, "").trim();
186
+ }
187
+ out[key] = value;
188
+ }
189
+ return out;
190
+ }
191
+
192
+ /** Serialize one assignment, quoting whenever the value needs it. */
193
+ export function formatEnvAssignment(name, value) {
194
+ const needsQuotes = /[\s#"'\\]/.test(value);
195
+ if (!needsQuotes) return `${name}=${value}`;
196
+ const escaped = value
197
+ .replace(/\\/g, "\\\\")
198
+ .replace(/\n/g, "\\n")
199
+ .replace(/\r/g, "\\r")
200
+ .replace(/"/g, '\\"');
201
+ return `${name}="${escaped}"`;
202
+ }
203
+
204
+ /**
205
+ * A path the user typed, resolved against the directory they ran npm from:
206
+ * `npm run -w <workspace>` runs the script from the workspace directory.
207
+ */
208
+ export function resolveInvocationPath(path, env = process.env) {
209
+ return resolve(env.INIT_CWD ?? process.cwd(), path);
210
+ }
211
+
212
+ export function readEnvFile(path, fs = { existsSync, readFileSync }) {
213
+ if (!fs.existsSync(path)) return null;
214
+ return parseEnvText(fs.readFileSync(path, "utf8"));
215
+ }
216
+
217
+ // ── profiles ────────────────────────────────────────────────────────────────
218
+
219
+ function nonEmpty(value) {
220
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
221
+ }
222
+
223
+ function originOrSelf(url) {
224
+ try {
225
+ return new URL(url).origin;
226
+ } catch {
227
+ return url;
228
+ }
229
+ }
230
+
231
+ function convexSlug(url) {
232
+ try {
233
+ const host = new URL(url).hostname;
234
+ if (!host.endsWith(".convex.cloud") && !host.endsWith(".convex.site")) {
235
+ return null;
236
+ }
237
+ return host.split(".")[0] || null;
238
+ } catch {
239
+ return null;
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Merge layers (lowest priority first). Grouped keys come, per group, from the
245
+ * highest layer that sets ANY key of the group; ungrouped keys merge per key.
246
+ */
247
+ export function mergeProfileLayers(layers) {
248
+ const values = {};
249
+ const sources = {};
250
+ const groupSource = {};
251
+ for (const group of ["backend", "auth"]) {
252
+ for (let i = layers.length - 1; i >= 0; i -= 1) {
253
+ const layer = layers[i];
254
+ if (Object.keys(layer.values).some((k) => profileGroupOf(k) === group)) {
255
+ groupSource[group] = layer.name;
256
+ for (const [key, value] of Object.entries(layer.values)) {
257
+ if (profileGroupOf(key) === group) {
258
+ values[key] = value;
259
+ sources[key] = layer.name;
260
+ }
261
+ }
262
+ break;
263
+ }
264
+ }
265
+ }
266
+ // Per-instance addresses are never taken as values (they are computed from
267
+ // ports); a profile's setting is kept only as a hint for a deliberate
268
+ // non-loopback public origin.
269
+ const instanceHints = {};
270
+ for (const layer of layers) {
271
+ for (const [key, value] of Object.entries(layer.values)) {
272
+ if (INSTANCE_KEYS.includes(key)) {
273
+ instanceHints[key] = value;
274
+ continue;
275
+ }
276
+ if (profileGroupOf(key) !== null) continue;
277
+ values[key] = value;
278
+ sources[key] = layer.name;
279
+ }
280
+ }
281
+ return { values, sources, groupSource, instanceHints };
282
+ }
283
+
284
+ /**
285
+ * The profile layers for a target. Pure apart from reading the named files
286
+ * through `fs`.
287
+ *
288
+ * @param {object} args
289
+ * @param {"local"|"staging"|"preview"} [args.target]
290
+ * @param {string} [args.envFile] explicit profile file
291
+ * @param {string[]} [args.previewUrls] [viteConvexUrl, convexHttpUrl]
292
+ * @param {string} args.inspectorDir this worktree's mcpjam-inspector dir
293
+ * @param {string|null} [args.mainInspectorDir] the main worktree's, if different
294
+ * @param {Record<string,string|undefined>} [args.env] launcher environment
295
+ */
296
+ export function resolveProfileLayers(args) {
297
+ const fs = args.fs ?? { existsSync, readFileSync };
298
+ const env = args.env ?? {};
299
+ const target = args.target ?? "local";
300
+ const layers = [];
301
+ const read = (name, path) => {
302
+ const values = readEnvFile(path, fs);
303
+ if (values) layers.push({ name, path, values });
304
+ return values;
305
+ };
306
+
307
+ if (target === "preview") {
308
+ const [viteConvexUrl, convexHttpUrl] = (args.previewUrls ?? []).map(
309
+ nonEmpty,
310
+ );
311
+ if (!viteConvexUrl || !convexHttpUrl) {
312
+ throw new RuntimeConfigError(
313
+ "The preview target needs explicit VITE_CONVEX_URL and CONVEX_HTTP_URL arguments.",
314
+ );
315
+ }
316
+ layers.push({
317
+ name: "preview defaults",
318
+ values: {
319
+ WORKOS_CLIENT_ID: STAGING_WORKOS_CLIENT_ID,
320
+ VITE_WORKOS_CLIENT_ID: STAGING_WORKOS_CLIENT_ID,
321
+ },
322
+ });
323
+ const path = args.envFile ? resolve(args.envFile) : undefined;
324
+ const fileValues = path ? readEnvFile(path, fs) : null;
325
+ if (path && !fileValues) {
326
+ throw new RuntimeConfigError(
327
+ `--env-file ${args.envFile} does not exist.`,
328
+ );
329
+ }
330
+ const urls = {
331
+ VITE_CONVEX_URL: viteConvexUrl,
332
+ CONVEX_URL: viteConvexUrl,
333
+ CONVEX_HTTP_URL: convexHttpUrl,
334
+ };
335
+ for (const [key, value] of Object.entries(urls)) {
336
+ const fromFile = nonEmpty(fileValues?.[key]);
337
+ if (fromFile && fromFile !== value) {
338
+ throw new RuntimeConfigError(
339
+ `--env-file ${args.envFile} sets ${key} to a different backend than the preview arguments.`,
340
+ );
341
+ }
342
+ }
343
+ // Like staging: the URLs, the hosted guest authority and the file are ONE
344
+ // layer, so the file can supply the preview backend's credentials without
345
+ // replacing the backend the arguments name.
346
+ layers.push({
347
+ name: path ? `preview with --env-file ${args.envFile}` : "preview",
348
+ path,
349
+ values: {
350
+ MCPJAM_GUEST_AUTHORITY: "hosted",
351
+ MCPJAM_GUEST_AUTHORITY_ORIGIN: STAGING_HOSTED_ORIGIN,
352
+ ...(fileValues ?? {}),
353
+ ...urls,
354
+ },
355
+ });
356
+ return { target, explicit: true, layers };
357
+ }
358
+
359
+ if (args.envFile) {
360
+ const path = resolve(args.envFile);
361
+ if (!read(`--env-file ${args.envFile}`, path)) {
362
+ throw new RuntimeConfigError(
363
+ `--env-file ${args.envFile} does not exist.`,
364
+ );
365
+ }
366
+ return { target, explicit: true, layers };
367
+ }
368
+
369
+ if (target === "staging") {
370
+ layers.push({
371
+ name: "staging defaults",
372
+ values: {
373
+ WORKOS_CLIENT_ID: STAGING_WORKOS_CLIENT_ID,
374
+ VITE_WORKOS_CLIENT_ID: STAGING_WORKOS_CLIENT_ID,
375
+ },
376
+ });
377
+ const viteConvexUrl = nonEmpty(env.MCPJAM_STAGING_VITE_CONVEX_URL);
378
+ const convexHttpUrl = nonEmpty(env.MCPJAM_STAGING_CONVEX_HTTP_URL);
379
+ const stagingFile = join(args.inspectorDir, ".env.staging.local");
380
+ const fileValues = readEnvFile(stagingFile, fs);
381
+ if (!fileValues && (!viteConvexUrl || !convexHttpUrl)) {
382
+ throw new RuntimeConfigError(
383
+ "The staging target needs MCPJAM_STAGING_VITE_CONVEX_URL and " +
384
+ "MCPJAM_STAGING_CONVEX_HTTP_URL, or a .env.staging.local profile in this worktree.",
385
+ );
386
+ }
387
+ // The staging layer is ONE layer (URLs + its file), so the backend group
388
+ // is resolved from it as a whole.
389
+ const values = {
390
+ MCPJAM_GUEST_AUTHORITY: "hosted",
391
+ MCPJAM_GUEST_AUTHORITY_ORIGIN: STAGING_HOSTED_ORIGIN,
392
+ ...(viteConvexUrl
393
+ ? { VITE_CONVEX_URL: viteConvexUrl, CONVEX_URL: viteConvexUrl }
394
+ : {}),
395
+ ...(convexHttpUrl ? { CONVEX_HTTP_URL: convexHttpUrl } : {}),
396
+ ...(fileValues ?? {}),
397
+ };
398
+ layers.push({
399
+ name: "staging",
400
+ path: fileValues ? stagingFile : undefined,
401
+ values,
402
+ });
403
+ return { target, explicit: true, layers };
404
+ }
405
+
406
+ // local: the standard OSS profile, then a developer overlay.
407
+ read("standard profile (.env.local)", join(args.inspectorDir, ".env.local"));
408
+ const own = join(args.inspectorDir, ".env.development.local");
409
+ if (
410
+ !read("worktree profile (.env.development.local)", own) &&
411
+ args.mainInspectorDir
412
+ ) {
413
+ const main = join(args.mainInspectorDir, ".env.development.local");
414
+ read("main worktree profile (read in place)", main);
415
+ }
416
+ return { target, explicit: false, layers };
417
+ }
418
+
419
+ /**
420
+ * Validate and normalize a merged profile into the settings the children get.
421
+ * Throws `RuntimeConfigError` with an actionable message; never echoes a
422
+ * secret value.
423
+ */
424
+ export function finalizeProfile(
425
+ merged,
426
+ { explicit, standardLayerName, standardBackends },
427
+ ) {
428
+ const values = { ...merged.values };
429
+ const errors = [];
430
+
431
+ const backendFrom = merged.groupSource.backend
432
+ ? ` (backend settings come from the ${merged.groupSource.backend}, which must name its backend as a whole)`
433
+ : "";
434
+ const httpUrl = nonEmpty(values.CONVEX_HTTP_URL);
435
+ const viteUrl =
436
+ nonEmpty(values.VITE_CONVEX_URL) ?? nonEmpty(values.CONVEX_URL);
437
+ if (!httpUrl)
438
+ errors.push(
439
+ `CONVEX_HTTP_URL is not set by the selected profile${backendFrom}.`,
440
+ );
441
+ if (!viteUrl)
442
+ errors.push(
443
+ `VITE_CONVEX_URL is not set by the selected profile${backendFrom}.`,
444
+ );
445
+ // The browser (VITE_CONVEX_URL) and the server's Convex clients (CONVEX_URL)
446
+ // must reach the same deployment: one is filled from the other only when it
447
+ // is unset, never kept when it disagrees.
448
+ const browserCloud = nonEmpty(values.VITE_CONVEX_URL);
449
+ const serverCloud = nonEmpty(values.CONVEX_URL);
450
+ if (
451
+ browserCloud &&
452
+ serverCloud &&
453
+ originOrSelf(browserCloud) !== originOrSelf(serverCloud)
454
+ ) {
455
+ errors.push(
456
+ `VITE_CONVEX_URL (${convexSlug(browserCloud) ?? originOrSelf(browserCloud)}) and ` +
457
+ `CONVEX_URL (${convexSlug(serverCloud) ?? originOrSelf(serverCloud)}) name different deployments.`,
458
+ );
459
+ }
460
+ if (viteUrl && !nonEmpty(values.VITE_CONVEX_URL))
461
+ values.VITE_CONVEX_URL = viteUrl;
462
+ if (viteUrl && !nonEmpty(values.CONVEX_URL)) values.CONVEX_URL = viteUrl;
463
+ const httpSlug = httpUrl ? convexSlug(httpUrl) : null;
464
+ const viteSlug = viteUrl ? convexSlug(viteUrl) : null;
465
+ if (httpSlug && viteSlug && httpSlug !== viteSlug) {
466
+ errors.push(
467
+ `VITE_CONVEX_URL (${viteSlug}) and CONVEX_HTTP_URL (${httpSlug}) name different deployments.`,
468
+ );
469
+ }
470
+
471
+ const workosA = nonEmpty(values.WORKOS_CLIENT_ID);
472
+ const workosB = nonEmpty(values.VITE_WORKOS_CLIENT_ID);
473
+ if (workosA && workosB && workosA !== workosB) {
474
+ errors.push("WORKOS_CLIENT_ID and VITE_WORKOS_CLIENT_ID disagree.");
475
+ }
476
+ const workosClientId = workosA ?? workosB;
477
+ if (!workosClientId && merged.groupSource.auth) {
478
+ errors.push(
479
+ `The ${merged.groupSource.auth} sets sign-in settings but no WORKOS_CLIENT_ID; ` +
480
+ "a profile that sets any sign-in setting must name its WorkOS client.",
481
+ );
482
+ }
483
+ if (workosClientId) {
484
+ values.WORKOS_CLIENT_ID = workosClientId;
485
+ values.VITE_WORKOS_CLIENT_ID = workosClientId;
486
+ }
487
+
488
+ // The standard OSS profile needs no developer secrets: its guest authority
489
+ // is the hosted Inspector, through a pairing operators manage. That is a
490
+ // property of the BACKEND — one of the committed standard profiles' — not of
491
+ // how it was selected, so `--env-file .env.local` is standard too. Any other
492
+ // backend must say which authority it uses and carry its credentials.
493
+ let httpOrigin = null;
494
+ try {
495
+ httpOrigin = httpUrl ? new URL(httpUrl).origin : null;
496
+ } catch {
497
+ httpOrigin = null;
498
+ }
499
+ const standard =
500
+ (!explicit && merged.groupSource.backend === standardLayerName) ||
501
+ (httpOrigin !== null && (standardBackends ?? []).includes(httpOrigin));
502
+ const authority = nonEmpty(values.MCPJAM_GUEST_AUTHORITY);
503
+ const secret = nonEmpty(values.MCPJAM_GUEST_SESSION_SHARED_SECRET);
504
+ if (authority && authority !== "backend" && authority !== "hosted") {
505
+ errors.push(`MCPJAM_GUEST_AUTHORITY must be "backend" or "hosted".`);
506
+ } else if (authority === "backend" && !secret) {
507
+ errors.push(
508
+ "The selected profile uses its backend as the guest authority but has no " +
509
+ "MCPJAM_GUEST_SESSION_SHARED_SECRET. Run `npm run dev:setup-guest-auth -- " +
510
+ "--deployment dev:<name> --env-file <profile>` for your own development " +
511
+ "deployment, or set MCPJAM_GUEST_AUTHORITY=hosted with MCPJAM_GUEST_AUTHORITY_ORIGIN.",
512
+ );
513
+ } else if (!standard && !authority && !secret) {
514
+ errors.push(
515
+ "The selected profile points at a private backend but names no guest " +
516
+ "authority. Add MCPJAM_GUEST_SESSION_SHARED_SECRET (see " +
517
+ "`npm run dev:setup-guest-auth`) or MCPJAM_GUEST_AUTHORITY=hosted with " +
518
+ "MCPJAM_GUEST_AUTHORITY_ORIGIN to the profile.",
519
+ );
520
+ }
521
+ if (!authority) {
522
+ values.MCPJAM_GUEST_AUTHORITY = secret ? "backend" : "hosted";
523
+ }
524
+
525
+ if (errors.length > 0) {
526
+ throw new RuntimeConfigError(
527
+ `Configuration for this instance is incomplete:\n - ${errors.join("\n - ")}`,
528
+ );
529
+ }
530
+ return { values, standard, workosClientId };
531
+ }
532
+
533
+ // ── ports and origins ───────────────────────────────────────────────────────
534
+
535
+ export const DEFAULT_PORT_BASES = Object.freeze({
536
+ client: 5173,
537
+ server: 6274,
538
+ worker: 8787,
539
+ debugger: 9229,
540
+ });
541
+
542
+ function parsePortValue(name, raw) {
543
+ if (raw === undefined || raw === null || raw === "") return undefined;
544
+ const text = String(raw);
545
+ const port = Number(text);
546
+ if (
547
+ !/^\d+$/.test(text) ||
548
+ !Number.isInteger(port) ||
549
+ port < 1 ||
550
+ port > 65535
551
+ ) {
552
+ throw new RuntimeConfigError(
553
+ `${name} must be a port number between 1 and 65535 (got "${text}").`,
554
+ );
555
+ }
556
+ return port;
557
+ }
558
+
559
+ /** Ports for instance N, with explicit overrides; all distinct. */
560
+ export function computeInstancePorts(instance, overrides = {}) {
561
+ if (!Number.isInteger(instance) || instance < 0) {
562
+ throw new RuntimeConfigError(
563
+ "The instance must be a non-negative integer.",
564
+ );
565
+ }
566
+ const ports = {
567
+ client:
568
+ parsePortValue("--client-port", overrides.client) ??
569
+ DEFAULT_PORT_BASES.client + instance,
570
+ server:
571
+ parsePortValue("--server-port", overrides.server) ??
572
+ DEFAULT_PORT_BASES.server + instance,
573
+ worker:
574
+ parsePortValue("--worker-port", overrides.worker) ??
575
+ DEFAULT_PORT_BASES.worker + instance,
576
+ debugger:
577
+ parsePortValue("--debugger-port", overrides.debugger) ??
578
+ DEFAULT_PORT_BASES.debugger + instance,
579
+ };
580
+ const seen = new Map();
581
+ for (const [role, port] of Object.entries(ports)) {
582
+ if (port > 65535) {
583
+ throw new RuntimeConfigError(
584
+ `The ${role} port for instance ${instance} would be ${port}.`,
585
+ );
586
+ }
587
+ if (seen.has(port)) {
588
+ throw new RuntimeConfigError(
589
+ `The ${seen.get(port)} and ${role} ports are both ${port}; give each its own port.`,
590
+ );
591
+ }
592
+ seen.set(port, role);
593
+ }
594
+ return ports;
595
+ }
596
+
597
+ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
598
+
599
+ export function isLoopbackOrigin(value) {
600
+ try {
601
+ const url = new URL(value);
602
+ return (
603
+ (url.protocol === "http:" || url.protocol === "https:") &&
604
+ LOOPBACK_HOSTS.has(url.hostname)
605
+ );
606
+ } catch {
607
+ return false;
608
+ }
609
+ }
610
+
611
+ /**
612
+ * The per-instance addresses.
613
+ *
614
+ * `browserPort` is where the browser loads the app (the Vite client in
615
+ * development, the server itself when packaged). Public callback origins for
616
+ * CLI login and Slack/Discord linking follow it; a profile value that names a
617
+ * NON-loopback origin is a deliberate public deployment and is kept.
618
+ */
619
+ export function computeInstanceEnv({
620
+ ports,
621
+ browserPort,
622
+ host = "localhost",
623
+ profile = {},
624
+ withWorker = false,
625
+ }) {
626
+ const browserOrigin = `http://${host}:${browserPort}`;
627
+ const serverOrigin = `http://${host}:${ports.server}`;
628
+ const keepPublic = (name) => {
629
+ const value = nonEmpty(profile[name]);
630
+ if (!value || isLoopbackOrigin(value)) return undefined;
631
+ try {
632
+ return new URL(value).origin;
633
+ } catch {
634
+ return undefined;
635
+ }
636
+ };
637
+ const cliOrigin = keepPublic("CLI_AUTH_PUBLIC_ORIGIN") ?? browserOrigin;
638
+ const extraOrigins = (profile.WEB_ALLOWED_ORIGINS ?? "")
639
+ .split(",")
640
+ .map((origin) => origin.trim())
641
+ .filter((origin) => origin && !isLoopbackOrigin(origin));
642
+ const env = {
643
+ MCPJAM_BROWSER_PORT: String(browserPort),
644
+ SERVER_PORT: String(ports.server),
645
+ PORT: String(ports.server),
646
+ BASE_URL: serverOrigin,
647
+ // Every loopback spelling the browser can show for this instance; the
648
+ // scoped session cookies and the backend's CORS accept `[::1]` as well.
649
+ WEB_ALLOWED_ORIGINS: [
650
+ `http://localhost:${browserPort}`,
651
+ `http://127.0.0.1:${browserPort}`,
652
+ `http://[::1]:${browserPort}`,
653
+ ...extraOrigins,
654
+ ].join(","),
655
+ CLI_AUTH_PUBLIC_ORIGIN: cliOrigin,
656
+ SLACK_LINK_PUBLIC_ORIGIN:
657
+ keepPublic("SLACK_LINK_PUBLIC_ORIGIN") ?? cliOrigin,
658
+ DISCORD_LINK_PUBLIC_ORIGIN:
659
+ keepPublic("DISCORD_LINK_PUBLIC_ORIGIN") ?? cliOrigin,
660
+ MCPJAM_INSPECTOR_FRONTEND_URL: browserOrigin,
661
+ };
662
+ if (ports.client !== undefined) {
663
+ env.CLIENT_PORT = String(ports.client);
664
+ env.VITE_API_BASE_URL = serverOrigin;
665
+ }
666
+ if (withWorker) {
667
+ env.MCPJAM_PLATFORM_MCP_URL = `http://localhost:${ports.worker}/mcp`;
668
+ }
669
+ return env;
670
+ }
671
+
672
+ /**
673
+ * Variables the platform MCP worker gets for this instance, written to the
674
+ * env file `wrangler dev` reads INSTEAD of `.dev.vars`/`.env`.
675
+ */
676
+ export function computeWorkerVars({ ports, profile }) {
677
+ const serverOrigin = `http://localhost:${ports.server}`;
678
+ const clientId =
679
+ nonEmpty(profile.WORKOS_CLIENT_ID) ??
680
+ nonEmpty(profile.VITE_WORKOS_CLIENT_ID);
681
+ const authkitDomain =
682
+ nonEmpty(profile.AUTHKIT_DOMAIN) ??
683
+ (clientId ? KNOWN_AUTHKIT_DOMAINS[clientId] : undefined);
684
+ return {
685
+ PLATFORM_API_URL: `${serverOrigin}/api/v1`,
686
+ MCPJAM_APP_ORIGIN: serverOrigin,
687
+ MCPJAM_GUEST_JWKS_URL: `${serverOrigin}/api/web/guest-jwks`,
688
+ MCPJAM_GUEST_MINT_URL: `${serverOrigin}/api/web/guest-token`,
689
+ ...(clientId ? { WORKOS_CLIENT_ID: clientId } : {}),
690
+ ...(authkitDomain ? { AUTHKIT_DOMAIN: authkitDomain } : {}),
691
+ };
692
+ }
693
+
694
+ /**
695
+ * The environment a child process starts with: the launcher's own
696
+ * environment MINUS every profile-owned key (so nothing inherited from the
697
+ * shell or another target survives), plus the resolved profile, plus this
698
+ * instance's addresses, plus the marker that tells the child not to load
699
+ * configuration files of its own.
700
+ */
701
+ export function buildChildEnv({ baseEnv, profileValues, instanceEnv }) {
702
+ const env = {};
703
+ const dropped = [];
704
+ for (const [key, value] of Object.entries(baseEnv)) {
705
+ if (value === undefined) continue;
706
+ if (isProfileOwnedKey(key)) {
707
+ if (!(key in profileValues) && !(key in instanceEnv) && value !== "")
708
+ dropped.push(key);
709
+ continue;
710
+ }
711
+ env[key] = value;
712
+ }
713
+ Object.assign(env, profileValues, instanceEnv, {
714
+ [RESOLVED_RUNTIME_MARKER]: "1",
715
+ });
716
+ return { env, droppedInheritedKeys: dropped.sort() };
717
+ }
718
+
719
+ /** A printable, secret-free description of a resolved profile. */
720
+ export function describeProfile({ values, sources }) {
721
+ const lines = [];
722
+ for (const key of Object.keys(values).sort()) {
723
+ if (!isProfileOwnedKey(key)) continue;
724
+ const shown = SECRET_NAME.test(key) ? "<set>" : values[key];
725
+ lines.push(`${key}=${shown}${sources?.[key] ? ` (${sources[key]})` : ""}`);
726
+ }
727
+ return lines;
728
+ }
729
+
730
+ /** The main worktree's mcpjam-inspector dir, or null when this IS the main worktree. */
731
+ export function findMainInspectorDir(inspectorDir, gitCommonDir) {
732
+ if (!gitCommonDir) return null;
733
+ const mainRoot = dirname(resolve(gitCommonDir));
734
+ const main = join(mainRoot, "mcpjam-inspector");
735
+ return resolve(main) === resolve(inspectorDir) ? null : main;
736
+ }
737
+
738
+ /**
739
+ * The backends of the committed standard OSS profiles (`.env.local` for
740
+ * source checkouts, `.env.production` for packaged releases).
741
+ */
742
+ export function standardBackendOrigins(inspectorDir, fs) {
743
+ const origins = [];
744
+ for (const name of [".env.local", ".env.production"]) {
745
+ const values = readEnvFile(join(inspectorDir, name), fs);
746
+ try {
747
+ if (values?.CONVEX_HTTP_URL)
748
+ origins.push(new URL(values.CONVEX_HTTP_URL).origin);
749
+ } catch {
750
+ // not a URL; not a standard backend
751
+ }
752
+ }
753
+ return origins;
754
+ }
755
+
756
+ /** End-to-end resolution for a launcher. */
757
+ export function resolveRuntimeProfile(args) {
758
+ const layerSet = resolveProfileLayers(args);
759
+ const merged = mergeProfileLayers(layerSet.layers);
760
+ const finalized = finalizeProfile(merged, {
761
+ explicit: layerSet.explicit,
762
+ standardLayerName: "standard profile (.env.local)",
763
+ standardBackends: standardBackendOrigins(args.inspectorDir, args.fs),
764
+ });
765
+ return {
766
+ target: layerSet.target,
767
+ explicit: layerSet.explicit,
768
+ layers: layerSet.layers.map(({ name, path }) => ({ name, path })),
769
+ values: finalized.values,
770
+ sources: merged.sources,
771
+ instanceHints: merged.instanceHints,
772
+ standard: finalized.standard,
773
+ };
774
+ }