nulladrift 0.6.0 → 0.6.2

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/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/index.ts
4
4
  import { parseArgs } from "util";
5
- import { resolve as resolve4 } from "path";
5
+ import { resolve as resolve5 } from "path";
6
6
 
7
7
  // ../core/src/changes.ts
8
8
  var CHANGE_KINDS = [
@@ -139,7 +139,7 @@ function toJson(value, depth = 0) {
139
139
  if (value === null) return null;
140
140
  if (Array.isArray(value)) return value.map((member) => toJson(member, depth + 1));
141
141
  if (typeof value === "object") {
142
- const out = {};
142
+ const out = /* @__PURE__ */ Object.create(null);
143
143
  for (const [key, member] of Object.entries(value)) {
144
144
  if (member === void 0) continue;
145
145
  out[key] = toJson(member, depth + 1);
@@ -190,6 +190,262 @@ function resealMcpServer(entry) {
190
190
  };
191
191
  }
192
192
 
193
+ // ../core/src/lock/credentials.ts
194
+ var REDACTED = "REDACTED";
195
+ var CREDENTIAL_WORDS = /* @__PURE__ */ new Set([
196
+ "key",
197
+ "apikey",
198
+ "token",
199
+ "secret",
200
+ "password",
201
+ "passwd",
202
+ "pwd",
203
+ "pass",
204
+ "pat",
205
+ "auth",
206
+ "bearer",
207
+ "credential",
208
+ "credentials",
209
+ "privatekey",
210
+ "accesskey",
211
+ "clientsecret",
212
+ "sig",
213
+ "signature",
214
+ "jwt",
215
+ "cookie"
216
+ ]);
217
+ var DESCRIBES_IT = /* @__PURE__ */ new Set([
218
+ "file",
219
+ "path",
220
+ "dir",
221
+ "directory",
222
+ "url",
223
+ "uri",
224
+ "endpoint",
225
+ "host",
226
+ "type",
227
+ "mode",
228
+ "method",
229
+ "header",
230
+ "name",
231
+ "id",
232
+ "env",
233
+ "var",
234
+ "length",
235
+ "limit",
236
+ "count",
237
+ "max",
238
+ "min",
239
+ "size",
240
+ "timeout",
241
+ "ttl",
242
+ "format",
243
+ "prefix",
244
+ "location",
245
+ "store",
246
+ "provider",
247
+ "region",
248
+ "scope",
249
+ "scopes",
250
+ "version",
251
+ "algorithm",
252
+ "kind",
253
+ "expiry"
254
+ ]);
255
+ function nameWords(name) {
256
+ return name.replace(/^-+/, "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
257
+ }
258
+ function isCredentialName(name) {
259
+ const words = nameWords(name);
260
+ const last = words[words.length - 1];
261
+ if (last === void 0 || DESCRIBES_IT.has(last) || words[0] === "no") return false;
262
+ return words.some((word) => CREDENTIAL_WORDS.has(word));
263
+ }
264
+ var CREDENTIAL_HEADERS = /* @__PURE__ */ new Set(["authorization", "proxy-authorization", "cookie", "set-cookie"]);
265
+ var ISSUER_FORMATS = [
266
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
267
+ // AWS access key id
268
+ /\bgh[pousr]_[A-Za-z0-9]{36,}\b/g,
269
+ // GitHub
270
+ /\bgithub_pat_[A-Za-z0-9_]{40,}\b/g,
271
+ /\bglpat-[A-Za-z0-9_-]{20,}/g,
272
+ // GitLab
273
+ /\bxox[abprs]-[A-Za-z0-9-]{10,}/g,
274
+ // Slack
275
+ /\b[rs]k_(?:live|test)_[A-Za-z0-9]{16,}\b/g,
276
+ // Stripe
277
+ /\bsk-ant-[A-Za-z0-9_-]{20,}/g,
278
+ // Anthropic
279
+ /\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{32,}/g,
280
+ // OpenAI
281
+ /\bAIza[0-9A-Za-z_-]{35}\b/g,
282
+ // Google API key
283
+ /\bnpm_[A-Za-z0-9]{36}\b/g,
284
+ /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g
285
+ // JWT
286
+ ];
287
+ var PLACEHOLDER = /\$\{|^\$[A-Za-z_]/;
288
+ function looksRandom(value) {
289
+ if (value.length < 32 || !/^[A-Za-z0-9_-]+$/.test(value)) return false;
290
+ if (!/[a-z]/.test(value) || !/[A-Z]/.test(value) || !/[0-9]/.test(value)) return false;
291
+ const kind = (character) => /[a-z]/.test(character) ? 0 : /[A-Z]/.test(character) ? 1 : /[0-9]/.test(character) ? 2 : 3;
292
+ let switches = 0;
293
+ for (let index = 1; index < value.length; index += 1) {
294
+ if (kind(value[index] ?? "") !== kind(value[index - 1] ?? "")) switches += 1;
295
+ }
296
+ return switches >= value.length / 3;
297
+ }
298
+ function decoded(value) {
299
+ try {
300
+ return decodeURIComponent(value);
301
+ } catch {
302
+ return value;
303
+ }
304
+ }
305
+ function isSecretValue(value) {
306
+ if (value === "" || value === REDACTED || PLACEHOLDER.test(value)) return false;
307
+ if (/^(?:[./~]|[A-Za-z]:\\|[a-z][a-z0-9+.-]*:\/\/)/i.test(value)) return false;
308
+ return true;
309
+ }
310
+ function redactFormats(value) {
311
+ let out = value;
312
+ for (const format of ISSUER_FORMATS) out = out.replace(format, REDACTED);
313
+ return out;
314
+ }
315
+ function redactUrl(value) {
316
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) return value;
317
+ let url;
318
+ try {
319
+ url = new URL(value);
320
+ } catch {
321
+ return redactPairs(value);
322
+ }
323
+ let changed = false;
324
+ if (url.password && !PLACEHOLDER.test(decoded(url.password))) {
325
+ url.password = REDACTED;
326
+ changed = true;
327
+ }
328
+ for (const [key, parameter] of [...url.searchParams]) {
329
+ if (isCredentialName(key) && isSecretValue(parameter)) {
330
+ url.searchParams.set(key, REDACTED);
331
+ changed = true;
332
+ }
333
+ }
334
+ const path = redactPath(url.pathname);
335
+ if (path !== url.pathname) {
336
+ url.pathname = path;
337
+ changed = true;
338
+ }
339
+ const hash = url.hash ? redactPairs(url.hash) : url.hash;
340
+ if (hash !== url.hash) {
341
+ url.hash = hash;
342
+ changed = true;
343
+ }
344
+ return changed ? url.toString() : value;
345
+ }
346
+ function redactPairs(text) {
347
+ return text.replace(
348
+ /(^|[?&;#\s,])([A-Za-z_][A-Za-z0-9_.-]*)=([^&;#\s,]*)/g,
349
+ (whole, lead, name, value) => isCredentialName(name) && isSecretValue(value) ? `${lead}${name}=${REDACTED}` : whole
350
+ );
351
+ }
352
+ function redactHeader(text) {
353
+ const header = /^([A-Za-z][A-Za-z0-9-]*)\s*:\s*(\S.*)$/s.exec(text);
354
+ if (!header) return void 0;
355
+ const [, name = "", value = ""] = header;
356
+ if (!(CREDENTIAL_HEADERS.has(name.toLowerCase()) || isCredentialName(name)) || PLACEHOLDER.test(value)) return void 0;
357
+ return `${name}: ${REDACTED}`;
358
+ }
359
+ function redactJson(text) {
360
+ if (!/^\s*[[{]/.test(text)) return void 0;
361
+ let parsed;
362
+ try {
363
+ parsed = JSON.parse(text);
364
+ } catch {
365
+ return void 0;
366
+ }
367
+ let changed = false;
368
+ const walk = (node) => {
369
+ if (Array.isArray(node)) return node.map(walk);
370
+ if (node !== null && typeof node === "object") {
371
+ const out = /* @__PURE__ */ Object.create(null);
372
+ for (const [key, child] of Object.entries(node)) {
373
+ if (typeof child === "string" && isCredentialName(key) && isSecretValue(child)) {
374
+ out[key] = REDACTED;
375
+ changed = true;
376
+ } else if (typeof child === "string") {
377
+ const next = redactText(child);
378
+ if (next !== child) changed = true;
379
+ out[key] = next;
380
+ } else {
381
+ out[key] = walk(child);
382
+ }
383
+ }
384
+ return out;
385
+ }
386
+ return node;
387
+ };
388
+ const result = walk(parsed);
389
+ return changed ? JSON.stringify(result) : void 0;
390
+ }
391
+ function redactText(text) {
392
+ if (PLACEHOLDER.test(text) && !/[?&;#]/.test(text)) return text;
393
+ if (looksRandom(text)) return REDACTED;
394
+ const json = redactJson(text);
395
+ if (json !== void 0) return json;
396
+ const header = redactHeader(text);
397
+ if (header !== void 0) return header;
398
+ return redactFormats(redactPairs(redactUrl(text)));
399
+ }
400
+ function redactArgs(args) {
401
+ const out = [...args];
402
+ for (let index = 0; index < out.length; index += 1) {
403
+ const argument = out[index] ?? "";
404
+ const assignment = /^(-{0,2}[A-Za-z][A-Za-z0-9_.-]*)=(.*)$/s.exec(argument);
405
+ if (assignment) {
406
+ const [, name = "", value = ""] = assignment;
407
+ if (isCredentialName(name) && isSecretValue(value)) {
408
+ out[index] = `${name}=${REDACTED}`;
409
+ continue;
410
+ }
411
+ if (!PLACEHOLDER.test(value) || /[?&;#]/.test(value)) out[index] = `${name}=${redactText(value)}`;
412
+ continue;
413
+ }
414
+ const flag = /^-{1,2}([A-Za-z][A-Za-z0-9_.-]*)$/.exec(argument);
415
+ const next = out[index + 1];
416
+ if (flag && next !== void 0 && !next.startsWith("-")) {
417
+ const name = flag[1] ?? "";
418
+ if (isCredentialName(name) && isSecretValue(next) && !looksLikeAnOperand(next)) {
419
+ out[index + 1] = REDACTED;
420
+ index += 1;
421
+ continue;
422
+ }
423
+ if (["u", "user", "basic-auth"].includes(name.toLowerCase()) && /^[^:\s]+:[^\s]+$/.test(next) && !PLACEHOLDER.test(next)) {
424
+ out[index + 1] = `${next.slice(0, next.indexOf(":"))}:${REDACTED}`;
425
+ index += 1;
426
+ continue;
427
+ }
428
+ }
429
+ out[index] = redactText(argument);
430
+ }
431
+ return out;
432
+ }
433
+ function looksLikeAnOperand(value) {
434
+ return value.startsWith("@") || value.includes("/") || /\.(m?[jt]s|cjs|py|json|ya?ml|toml|sh|exe)$/i.test(value);
435
+ }
436
+ function redactPath(pathname) {
437
+ return pathname.split("/").map((segment) => {
438
+ if (segment === "" || PLACEHOLDER.test(decoded(segment))) return segment;
439
+ if (looksRandom(segment)) return REDACTED;
440
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment) || /^[0-9a-f]{32,}$/i.test(segment)) return REDACTED;
441
+ return redactFormats(segment);
442
+ }).join("/");
443
+ }
444
+ function countRedacted(transport2) {
445
+ const occurrences = (text) => text.split(REDACTED).length - 1;
446
+ return (transport2.args ?? []).reduce((total, argument) => total + occurrences(argument), 0) + occurrences(transport2.url ?? "");
447
+ }
448
+
193
449
  // ../core/src/lock/jsonschema.ts
194
450
  var MAX_REF_DEPTH = 32;
195
451
  var MAX_VISIT_DEPTH = 12;
@@ -198,12 +454,12 @@ function asObject(value) {
198
454
  return value !== null && value !== void 0 && typeof value === "object" && !Array.isArray(value) ? value : void 0;
199
455
  }
200
456
  function decodeToken(token) {
201
- let decoded = token;
457
+ let decoded2 = token;
202
458
  try {
203
- decoded = decodeURIComponent(token);
459
+ decoded2 = decodeURIComponent(token);
204
460
  } catch {
205
461
  }
206
- return decoded.replace(/~1/g, "/").replace(/~0/g, "~");
462
+ return decoded2.replace(/~1/g, "/").replace(/~0/g, "~");
207
463
  }
208
464
  function resolvePointer(root, ref) {
209
465
  if (!ref.startsWith("#")) return void 0;
@@ -221,20 +477,20 @@ function effectiveSchema(node, root, seenRefs = /* @__PURE__ */ new Set(), depth
221
477
  const object = asObject(node);
222
478
  if (object === void 0) return void 0;
223
479
  if (depth > MAX_REF_DEPTH) return object;
224
- const out = {};
480
+ const out = /* @__PURE__ */ Object.create(null);
225
481
  const merge = (source) => {
226
482
  for (const [key, value] of Object.entries(source)) {
227
483
  if (key === "$ref" || key === "allOf") continue;
228
484
  if (key === "properties") {
229
- const merged = { ...asObject(out["properties"]) ?? {} };
485
+ const merged = Object.assign(/* @__PURE__ */ Object.create(null), asObject(out["properties"]) ?? {});
230
486
  for (const [name, schema] of Object.entries(asObject(value) ?? {})) {
231
- if (!(name in merged)) merged[name] = schema;
487
+ if (!Object.hasOwn(merged, name)) Object.defineProperty(merged, name, { value: schema, enumerable: true, writable: true, configurable: true });
232
488
  }
233
489
  out["properties"] = merged;
234
490
  } else if (key === "required" && Array.isArray(value)) {
235
491
  const already = Array.isArray(out["required"]) ? out["required"] : [];
236
492
  out["required"] = [...new Set([...already, ...value].filter((entry) => typeof entry === "string"))];
237
- } else if (!(key in out)) {
493
+ } else if (!Object.hasOwn(out, key)) {
238
494
  out[key] = value;
239
495
  }
240
496
  }
@@ -283,7 +539,7 @@ function isEscalation(previous, next) {
283
539
  function normalizeSchema(value) {
284
540
  if (Array.isArray(value)) return value.map(normalizeSchema);
285
541
  if (value === null || typeof value !== "object") return value;
286
- const out = {};
542
+ const out = /* @__PURE__ */ Object.create(null);
287
543
  for (const [key, member] of Object.entries(value)) {
288
544
  if (key === "required" && Array.isArray(member) && member.every((entry) => typeof entry === "string")) {
289
545
  out[key] = [...member].sort();
@@ -295,8 +551,11 @@ function normalizeSchema(value) {
295
551
  }
296
552
  function extractHeaderParams(schema) {
297
553
  const found = [];
298
- const walk = (node, path, depth) => {
554
+ let budget = MAX_HEADER_VISITS;
555
+ const walk = (node, path, depth, refsOnPath) => {
299
556
  if (depth > MAX_VISIT_DEPTH) return;
557
+ if (budget <= 0) return;
558
+ budget -= 1;
300
559
  const object = effectiveSchema(node, schema);
301
560
  if (!object) return;
302
561
  const properties = asObject(object["properties"]);
@@ -306,17 +565,26 @@ function extractHeaderParams(schema) {
306
565
  if (!resolved) continue;
307
566
  const header = resolved["x-mcp-header"];
308
567
  if (typeof header === "string" && header.length > 0) found.push(`${[...path, name].join(".")} -> ${header}`);
309
- walk(child, [...path, name], depth + 1);
568
+ const ref = asObject(child)?.["$ref"];
569
+ if (typeof ref === "string" && refsOnPath.has(ref)) continue;
570
+ walk(child, [...path, name], depth + 1, typeof ref === "string" ? /* @__PURE__ */ new Set([...refsOnPath, ref]) : refsOnPath);
310
571
  }
311
572
  }
312
- for (const branch of alternatives(object)) walk(branch.schema, path, depth + 1);
573
+ for (const branch of alternatives(object)) {
574
+ const ref = asObject(branch.schema)?.["$ref"];
575
+ if (typeof ref === "string" && refsOnPath.has(ref)) continue;
576
+ walk(branch.schema, path, depth + 1, typeof ref === "string" ? /* @__PURE__ */ new Set([...refsOnPath, ref]) : refsOnPath);
577
+ }
313
578
  };
314
- walk(schema, [], 0);
579
+ const rootRef = asObject(schema)?.["$ref"];
580
+ walk(schema, [], 0, new Set(typeof rootRef === "string" ? [rootRef] : []));
581
+ if (budget <= 0) found.push(`(schema too large to scan for headers past ${MAX_HEADER_VISITS} nodes)`);
315
582
  return [...new Set(found)].sort();
316
583
  }
584
+ var MAX_HEADER_VISITS = 2e4;
317
585
  function stripIgnoredMeta(meta, ignoredPrefixes) {
318
586
  if (meta === null || meta === void 0 || typeof meta !== "object" || Array.isArray(meta)) return void 0;
319
- const out = {};
587
+ const out = /* @__PURE__ */ Object.create(null);
320
588
  for (const [key, value] of Object.entries(meta)) {
321
589
  if (ignoredPrefixes.some((prefix) => key.startsWith(prefix))) continue;
322
590
  out[key] = value;
@@ -324,17 +592,25 @@ function stripIgnoredMeta(meta, ignoredPrefixes) {
324
592
  return Object.keys(out).length > 0 ? out : void 0;
325
593
  }
326
594
  function sanitizeUrl(raw) {
595
+ if (raw.includes("${")) return sanitizeText(raw);
327
596
  try {
328
597
  const url = new URL(raw);
329
598
  url.search = "";
330
599
  url.hash = "";
331
600
  url.username = "";
332
601
  url.password = "";
602
+ url.pathname = redactPath(url.pathname);
333
603
  return url.toString();
334
604
  } catch {
335
- return raw;
605
+ return sanitizeText(raw);
336
606
  }
337
607
  }
608
+ function sanitizeText(raw) {
609
+ const withoutUser = raw.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@]*@/i, "$1");
610
+ const base = withoutUser.split(/[?#]/)[0] ?? withoutUser;
611
+ const parts = /^([a-z][a-z0-9+.-]*:\/\/[^/]*)(\/.*)?$/i.exec(base);
612
+ return parts ? `${parts[1]}${parts[2] ? redactPath(parts[2]) : ""}` : base;
613
+ }
338
614
 
339
615
  // ../core/src/risk/untrusted.ts
340
616
  function objectsIn(value) {
@@ -1027,7 +1303,7 @@ function newSteering(committed, observed) {
1027
1303
 
1028
1304
  // src/lib/ui.ts
1029
1305
  var enabled = process.stdout.isTTY === true && process.env["NO_COLOR"] === void 0 && process.env["TERM"] !== "dumb";
1030
- var wrap = (code) => (text) => enabled ? `\x1B[${code}m${text}\x1B[0m` : text;
1306
+ var wrap = (code2) => (text) => enabled ? `\x1B[${code2}m${text}\x1B[0m` : text;
1031
1307
  var bold = wrap(1);
1032
1308
  var dim = wrap(2);
1033
1309
  var red = wrap(31);
@@ -1047,7 +1323,8 @@ function truncate(text, limit = 160) {
1047
1323
  const collapsed = visibleControls(text).replace(/\s+/g, " ").trim();
1048
1324
  return collapsed.length <= limit ? collapsed : `${collapsed.slice(0, limit - 1)}\u2026`;
1049
1325
  }
1050
- function elideMiddle(path, limit) {
1326
+ function elideMiddle(raw, limit) {
1327
+ const path = visibleControls(raw);
1051
1328
  if (path.length <= limit) return path;
1052
1329
  const keep = Math.floor((limit - 1) / 2);
1053
1330
  return `${path.slice(0, keep)}\u2026${path.slice(-keep)}`;
@@ -1065,10 +1342,30 @@ import { z } from "zod";
1065
1342
 
1066
1343
  // src/config/expand.ts
1067
1344
  import { homedir } from "os";
1068
- var PLACEHOLDER = /\$\{([^}]+)\}/g;
1345
+ var PLACEHOLDER2 = /\$\{([^}]+)\}/g;
1346
+ var RUN_CREDENTIALS = /* @__PURE__ */ new Set([
1347
+ "CI_JOB_TOKEN",
1348
+ "CI_REGISTRY_PASSWORD",
1349
+ "CI_DEPLOY_PASSWORD",
1350
+ "CI_DEPENDENCY_PROXY_PASSWORD",
1351
+ "CI_REPOSITORY_URL",
1352
+ "BUILDKITE_AGENT_ACCESS_TOKEN",
1353
+ "BITBUCKET_STEP_OIDC_TOKEN",
1354
+ "SYSTEM_ACCESSTOKEN"
1355
+ ]);
1356
+ function isRunCredential(name) {
1357
+ const upper = name.toUpperCase();
1358
+ return RUN_CREDENTIALS.has(upper) || upper.startsWith("NULLADRIFT_") || upper.startsWith("ACTIONS_") || upper.startsWith("CI_JOB_JWT") || upper.startsWith("CIRCLE_OIDC_TOKEN");
1359
+ }
1069
1360
  function expand(input, context) {
1070
1361
  const unresolved = [];
1071
- const value = input.replace(PLACEHOLDER, (match, body) => {
1362
+ const refused = [];
1363
+ const value = input.replace(PLACEHOLDER2, (match, body) => {
1364
+ const named = body.startsWith("env:") ? body.slice(4) : body.includes(":-") ? body.slice(0, body.indexOf(":-")) : body;
1365
+ if (isRunCredential(named)) {
1366
+ refused.push(match);
1367
+ return match;
1368
+ }
1072
1369
  if (body === "workspaceFolder") return context.workspaceFolder;
1073
1370
  if (body === "userHome") return homedir();
1074
1371
  if (body === "pathSeparator" || body === "/") return "/";
@@ -1093,7 +1390,7 @@ function expand(input, context) {
1093
1390
  unresolved.push(match);
1094
1391
  return match;
1095
1392
  });
1096
- return { value, unresolved };
1393
+ return { value, unresolved, refused };
1097
1394
  }
1098
1395
 
1099
1396
  // src/config/parsers.ts
@@ -1110,6 +1407,7 @@ var serverEntrySchema = z.looseObject({
1110
1407
  oauth: z.looseObject({
1111
1408
  clientId: z.string().optional(),
1112
1409
  clientSecret: z.string().optional(),
1410
+ issuer: z.string().optional(),
1113
1411
  scope: z.string().optional(),
1114
1412
  scopes: z.array(z.string()).optional()
1115
1413
  }).optional()
@@ -1130,11 +1428,20 @@ function scalarsToStrings(record) {
1130
1428
  }
1131
1429
  return out;
1132
1430
  }
1431
+ function refusedCredentials(name, refused) {
1432
+ const names = [...new Set(refused)];
1433
+ return new UnsupportedServerError(
1434
+ name,
1435
+ `configuration uses ${names.join(", ")}, which ${names.length === 1 ? "holds" : "hold"} this run's own credentials (the CI job's token or identity, or Nulladrift's). They are never given to a server under audit. Give the server a credential of its own.`
1436
+ );
1437
+ }
1133
1438
  function resolveTransport(name, entry, context) {
1134
1439
  const unresolved = [];
1440
+ const refused = [];
1135
1441
  const take = (input) => {
1136
1442
  const result = expand(input, context);
1137
1443
  unresolved.push(...result.unresolved);
1444
+ refused.push(...result.refused);
1138
1445
  return result.value;
1139
1446
  };
1140
1447
  const declared = entry.type === "streamable-http" ? "http" : entry.type;
@@ -1155,6 +1462,7 @@ function resolveTransport(name, entry, context) {
1155
1462
  // Expanded here so a secret can live in the environment rather than the config file.
1156
1463
  clientId: oauth.clientId === void 0 ? void 0 : take(oauth.clientId),
1157
1464
  clientSecret: oauth.clientSecret === void 0 ? void 0 : take(oauth.clientSecret),
1465
+ issuer: oauth.issuer === void 0 ? void 0 : take(oauth.issuer),
1158
1466
  scope: oauth.scope ?? oauth.scopes?.join(" ")
1159
1467
  }
1160
1468
  }
@@ -1165,11 +1473,22 @@ function resolveTransport(name, entry, context) {
1165
1473
  type: "stdio",
1166
1474
  command: take(entry.command),
1167
1475
  args: (entry.args ?? []).map((argument) => take(String(argument))),
1168
- asWritten: { command: String(entry.command), args: (entry.args ?? []).map((argument) => String(argument)) },
1476
+ asWritten: {
1477
+ command: String(entry.command),
1478
+ args: (entry.args ?? []).map((argument) => String(argument)),
1479
+ ...entry.cwd ? { cwd: String(entry.cwd) } : {}
1480
+ },
1169
1481
  env: Object.fromEntries(Object.entries(scalarsToStrings(entry.env)).map(([key, value]) => [key, take(value)])),
1170
1482
  cwd: entry.cwd ? take(entry.cwd) : void 0
1171
1483
  };
1172
1484
  }
1485
+ if (transport2.type !== "stdio" && transport2.oauth?.clientSecret !== void 0 && !transport2.oauth.issuer) {
1486
+ throw new UnsupportedServerError(
1487
+ name,
1488
+ "oauth.clientSecret is set without oauth.issuer. Set oauth.issuer to the authorization server's issuer URL, so the secret can only be sent there and not to an authorization server the MCP server chooses."
1489
+ );
1490
+ }
1491
+ if (refused.length > 0) throw refusedCredentials(name, refused);
1173
1492
  if (unresolved.length > 0) {
1174
1493
  const names = [...new Set(unresolved)].join(", ");
1175
1494
  throw new UnsupportedServerError(
@@ -1189,17 +1508,27 @@ function detectMapKey(raw) {
1189
1508
  }
1190
1509
  async function readEnvFile(path) {
1191
1510
  const out = {};
1192
- const text = await readFile(path, "utf8");
1193
- for (const line of text.split(/\r?\n/)) {
1194
- const trimmed = line.trim();
1511
+ const lines = (await readFile(path, "utf8")).split(/\r?\n/);
1512
+ for (let index = 0; index < lines.length; index += 1) {
1513
+ const trimmed = (lines[index] ?? "").trim();
1195
1514
  if (trimmed === "" || trimmed.startsWith("#")) continue;
1196
- const at = trimmed.indexOf("=");
1515
+ const body = trimmed.replace(/^export\s+/, "");
1516
+ const at = body.indexOf("=");
1197
1517
  if (at <= 0) continue;
1198
- const key = trimmed.slice(0, at).trim().replace(/^export\s+/, "");
1199
- let value = trimmed.slice(at + 1).trim();
1200
- if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
1201
- value = value.slice(1, -1);
1518
+ const key = body.slice(0, at).trim();
1519
+ let value = body.slice(at + 1).trim();
1520
+ const quote = value[0];
1521
+ if (quote === '"' || quote === "'") {
1522
+ let rest = value.slice(1);
1523
+ const closed = (text) => text.endsWith(quote) && !text.endsWith(`\\${quote}`);
1524
+ while (!closed(rest) && index + 1 < lines.length) {
1525
+ index += 1;
1526
+ rest += `
1527
+ ${lines[index] ?? ""}`;
1528
+ }
1529
+ value = closed(rest) ? rest.slice(0, -1) : rest;
1202
1530
  }
1531
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue;
1203
1532
  out[key] = value;
1204
1533
  }
1205
1534
  return out;
@@ -1211,6 +1540,10 @@ async function parseServerMap(raw, mapKey, source, context) {
1211
1540
  const map = raw[mapKey];
1212
1541
  if (typeof map !== "object" || map === null) return { servers, skipped };
1213
1542
  for (const [name, value] of Object.entries(map)) {
1543
+ if (name === "__proto__") {
1544
+ skipped.push(new UnsupportedServerError(name, "a server cannot be named __proto__; rename it"));
1545
+ continue;
1546
+ }
1214
1547
  const entry = serverEntrySchema.safeParse(value);
1215
1548
  if (!entry.success) {
1216
1549
  skipped.push(new UnsupportedServerError(name, `entry is not a server definition: ${entry.error.issues[0]?.message ?? "unknown"}`));
@@ -1223,6 +1556,7 @@ async function parseServerMap(raw, mapKey, source, context) {
1223
1556
  const transport2 = resolveTransport(name, entry.data, context);
1224
1557
  if (transport2.type === "stdio" && entry.data.envFile !== void 0) {
1225
1558
  const expanded = expand(entry.data.envFile, context);
1559
+ if (expanded.refused.length > 0) throw refusedCredentials(name, expanded.refused);
1226
1560
  if (expanded.unresolved.length > 0) {
1227
1561
  throw new UnsupportedServerError(name, `envFile path contains unresolved placeholders: ${expanded.unresolved.join(", ")}`);
1228
1562
  }
@@ -1296,9 +1630,9 @@ async function readJsonIfPresent(path) {
1296
1630
  try {
1297
1631
  text = await readFile2(path, "utf8");
1298
1632
  } catch (error) {
1299
- const code = error.code;
1300
- if (code === "ENOENT" || code === "ENOTDIR") return { present: false };
1301
- if (code === "EACCES") return { present: true, ok: false, reason: "permission denied" };
1633
+ const code2 = error.code;
1634
+ if (code2 === "ENOENT" || code2 === "ENOTDIR") return { present: false };
1635
+ if (code2 === "EACCES") return { present: true, ok: false, reason: "permission denied" };
1302
1636
  throw error;
1303
1637
  }
1304
1638
  try {
@@ -1309,7 +1643,9 @@ async function readJsonIfPresent(path) {
1309
1643
  }
1310
1644
  function anchorCwd(server2, projectRoot) {
1311
1645
  const { transport: transport2 } = server2;
1312
- if (transport2.type !== "stdio" || transport2.cwd === void 0 || isAbsolute(transport2.cwd)) return server2;
1646
+ if (transport2.type !== "stdio") return server2;
1647
+ if (transport2.cwd === void 0) return { ...server2, transport: { ...transport2, cwd: projectRoot } };
1648
+ if (isAbsolute(transport2.cwd)) return server2;
1313
1649
  return { ...server2, transport: { ...transport2, cwd: resolve2(projectRoot, transport2.cwd) } };
1314
1650
  }
1315
1651
  function describeSearch(searched, filesRead) {
@@ -1317,11 +1653,13 @@ function describeSearch(searched, filesRead) {
1317
1653
  const lines = searched.map((path) => ` ${(read.has(path) ? "read" : "absent").padEnd(6)} ${path}`);
1318
1654
  return lines.join("\n");
1319
1655
  }
1320
- async function discoverServers(projectRoot, extraFiles = []) {
1656
+ async function discoverServers(projectRoot, extraFiles = [], options = {}) {
1321
1657
  const context = { workspaceFolder: projectRoot, env: process.env };
1658
+ const candidates = candidateConfigFiles(projectRoot);
1659
+ const userFiles = candidates.filter((file) => file.scope === "user");
1322
1660
  const files = [
1323
1661
  ...extraFiles.map((path) => ({ client: "generic", path: resolve2(projectRoot, path) })),
1324
- ...candidateConfigFiles(projectRoot)
1662
+ ...candidates.filter((file) => options.userConfigs === true || file.scope !== "user")
1325
1663
  ];
1326
1664
  const byName2 = /* @__PURE__ */ new Map();
1327
1665
  const skipped = [];
@@ -1368,6 +1706,9 @@ async function discoverServers(projectRoot, extraFiles = []) {
1368
1706
  skipped,
1369
1707
  filesRead,
1370
1708
  searched: files.map((file) => file.path),
1709
+ userConfigsSkipped: options.userConfigs === true ? [] : (await Promise.all(userFiles.map(async (file) => (await readJsonIfPresent(file.path)).present ? portablePath(file.path, projectRoot) : void 0))).filter(
1710
+ (path) => path !== void 0
1711
+ ),
1371
1712
  shadowed,
1372
1713
  problems
1373
1714
  };
@@ -1393,13 +1734,13 @@ function lockTransport(server2) {
1393
1734
  const { transport: transport2 } = server2;
1394
1735
  if (transport2.type === "stdio") {
1395
1736
  const command = transport2.asWritten?.command ?? transport2.command;
1396
- const args = transport2.asWritten?.args ?? transport2.args;
1737
+ const args = redactArgs(transport2.asWritten?.args ?? transport2.args);
1397
1738
  return {
1398
1739
  type: "stdio",
1399
1740
  command,
1400
1741
  args: args.length > 0 ? args : void 0,
1401
1742
  envKeys: Object.keys(transport2.env).length > 0 ? Object.keys(transport2.env).sort() : void 0,
1402
- cwd: transport2.cwd
1743
+ cwd: transport2.asWritten ? transport2.asWritten.cwd : transport2.cwd
1403
1744
  };
1404
1745
  }
1405
1746
  const headerKeys = Object.keys(transport2.headers);
@@ -1505,7 +1846,7 @@ import { readFile as readFile3 } from "fs/promises";
1505
1846
  import { isAbsolute as isAbsolute2, resolve as resolve3 } from "path";
1506
1847
 
1507
1848
  // src/lib/version.ts
1508
- var VERSION = "0.6.0";
1849
+ var VERSION = "0.6.2";
1509
1850
  var USER_AGENT = `nulladrift/${VERSION} (+https://github.com/Nulladrift/nulladrift)`;
1510
1851
 
1511
1852
  // src/lock/provenance.ts
@@ -1565,6 +1906,7 @@ var UV_VALUE_FLAGS = /* @__PURE__ */ new Set([
1565
1906
  "-p",
1566
1907
  "--index",
1567
1908
  "--index-url",
1909
+ "-i",
1568
1910
  "--extra-index-url",
1569
1911
  "--default-index",
1570
1912
  "--find-links",
@@ -1785,6 +2127,15 @@ function isExact(reference) {
1785
2127
  return false;
1786
2128
  }
1787
2129
  }
2130
+ var NPM_PUBLIC = "https://registry.npmjs.org";
2131
+ function npmEnv(env, name) {
2132
+ const wanted = name.toLowerCase();
2133
+ for (const [key, value] of Object.entries(env)) if (key.toLowerCase() === wanted && value) return value;
2134
+ return void 0;
2135
+ }
2136
+ function resolverNpmRegistry(env = process.env) {
2137
+ return (npmEnv(env, "npm_config_registry") ?? NPM_PUBLIC).replace(/\/+$/, "");
2138
+ }
1788
2139
  var DEFAULT_TIMEOUT_MS = 1e4;
1789
2140
  async function getJson(url, options) {
1790
2141
  const response = await (options.fetch ?? fetch)(url, {
@@ -1798,7 +2149,7 @@ async function getJson(url, options) {
1798
2149
  async function resolveNpm(reference, options) {
1799
2150
  const asked = reference.requested ?? "latest";
1800
2151
  if (!NPM_EXACT.test(asked) && !NPM_TAG.test(asked)) return void 0;
1801
- const registry = (process.env["npm_config_registry"] ?? "https://registry.npmjs.org").replace(/\/+$/, "");
2152
+ const registry = resolverNpmRegistry();
1802
2153
  const body = await getJson(`${registry}/${reference.name.replace("/", "%2F")}/${encodeURIComponent(asked)}`, options);
1803
2154
  if (typeof body?.version !== "string") return void 0;
1804
2155
  const integrity = typeof body.dist?.integrity === "string" ? body.dist.integrity : typeof body.dist?.shasum === "string" ? `sha1:${body.dist.shasum}` : void 0;
@@ -1902,6 +2253,191 @@ function carriedForward(previous, reference) {
1902
2253
  return previous;
1903
2254
  }
1904
2255
 
2256
+ // src/lock/source.ts
2257
+ import { existsSync, readFileSync, statSync } from "fs";
2258
+ import { homedir as homedir3 } from "os";
2259
+ import { dirname, join as join2, resolve as resolve4 } from "path";
2260
+ var PYPI_PUBLIC = "https://pypi.org/simple";
2261
+ function canonicalRegistry(url) {
2262
+ const trimmed = url.trim().replace(/\/+$/, "");
2263
+ try {
2264
+ const parsed = new URL(trimmed);
2265
+ const host = parsed.host.toLowerCase() === "registry.yarnpkg.com" ? "registry.npmjs.org" : parsed.host.toLowerCase();
2266
+ return `${parsed.protocol}//${host}${parsed.pathname.replace(/\/+$/, "")}`;
2267
+ } catch {
2268
+ return trimmed;
2269
+ }
2270
+ }
2271
+ function readSmall(path) {
2272
+ try {
2273
+ const stat = statSync(path);
2274
+ if (!stat.isFile() || stat.size > 1e6) return void 0;
2275
+ return readFileSync(path, "utf8");
2276
+ } catch {
2277
+ return void 0;
2278
+ }
2279
+ }
2280
+ function readIni(path, env) {
2281
+ const out = /* @__PURE__ */ new Map();
2282
+ for (const line of (readSmall(path) ?? "").split(/\r?\n/)) {
2283
+ const match = /^\s*([^;#=\s][^=]*?)\s*=\s*(.*?)\s*$/.exec(line);
2284
+ if (!match) continue;
2285
+ const value = match[2].replace(/^(["'])(.*)\1$/, "$2").replace(/\$\{([^}]+)\}/g, (_, name) => env[name] ?? "");
2286
+ out.set(match[1].toLowerCase(), value);
2287
+ }
2288
+ return out;
2289
+ }
2290
+ function launcherOptions(args, valueFlags, explicitFlags) {
2291
+ const out = [];
2292
+ for (let index = 0; index < args.length; index += 1) {
2293
+ const arg = args[index];
2294
+ if (arg === "--" || !arg.startsWith("-") || arg.length === 1) break;
2295
+ const equals = arg.indexOf("=");
2296
+ if (arg.startsWith("--") && equals > 0) {
2297
+ out.push([arg.slice(0, equals).toLowerCase(), arg.slice(equals + 1)]);
2298
+ continue;
2299
+ }
2300
+ if (valueFlags.has(arg) || explicitFlags.includes(arg)) {
2301
+ out.push([arg.toLowerCase(), args[index + 1]]);
2302
+ index += 1;
2303
+ continue;
2304
+ }
2305
+ out.push([arg.toLowerCase(), void 0]);
2306
+ }
2307
+ return out;
2308
+ }
2309
+ function afterSubcommand(name, args) {
2310
+ if ((name === "pnpm" || name === "yarn") && args[0] === "dlx") return args.slice(1);
2311
+ if (name === "npm" && (args[0] === "exec" || args[0] === "x")) return args.slice(1);
2312
+ if (name === "uv" && args[0] === "tool" && args[1] === "run") return args.slice(2);
2313
+ if (name === "pipx" && args[0] === "run") return args.slice(1);
2314
+ return args;
2315
+ }
2316
+ function ancestors(start) {
2317
+ const out = [];
2318
+ for (let dir = resolve4(start); ; dir = dirname(dir)) {
2319
+ out.push(dir);
2320
+ if (dirname(dir) === dir) return out;
2321
+ }
2322
+ }
2323
+ function npmPrefix(start) {
2324
+ return ancestors(start).find((dir) => existsSync(join2(dir, "package.json")) || existsSync(join2(dir, "node_modules"))) ?? resolve4(start);
2325
+ }
2326
+ function npmElsewhere(transport2, reference, context) {
2327
+ const env = context.env ?? process.env;
2328
+ const name = commandName(transport2.command);
2329
+ const base = transport2.cwd ?? context.projectRoot;
2330
+ const launcherEnv = { ...env, ...transport2.env };
2331
+ const options = launcherOptions(afterSubcommand(name, transport2.args), NPM_VALUE_FLAGS, ["-p", "--package"]);
2332
+ const prefix = npmPrefix(base);
2333
+ if (name !== "pnpm" && name !== "yarn" && name !== "pnpx") {
2334
+ const bin = reference.name.split("/").pop();
2335
+ for (const dir of ancestors(base)) {
2336
+ if (existsSync(join2(dir, "node_modules", ...reference.name.split("/"), "package.json")) || existsSync(join2(dir, "node_modules", ".bin", bin))) {
2337
+ return "a copy installed in node_modules runs instead of the registry's";
2338
+ }
2339
+ }
2340
+ }
2341
+ const cli = new Map(options.filter(([flag]) => flag.startsWith("--")).map(([flag, value]) => [flag.slice(2), value ?? ""]));
2342
+ const userconfig = cli.get("userconfig") ?? npmEnv(launcherEnv, "npm_config_userconfig");
2343
+ const levels = [
2344
+ (key) => cli.get(key),
2345
+ (key) => npmEnv(launcherEnv, `npm_config_${key}`),
2346
+ /* @__PURE__ */ ((rc) => (key) => rc.get(key))(readIni(join2(prefix, ".npmrc"), launcherEnv)),
2347
+ /* @__PURE__ */ ((rc) => (key) => rc.get(key))(readIni(userconfig ? resolve4(base, userconfig) : join2(context.home ?? homedir3(), ".npmrc"), launcherEnv))
2348
+ ];
2349
+ const setting = (key) => {
2350
+ for (const level of levels) {
2351
+ const value = level(key);
2352
+ if (value !== void 0) return value;
2353
+ }
2354
+ return void 0;
2355
+ };
2356
+ const scope = reference.name.startsWith("@") ? reference.name.slice(0, reference.name.indexOf("/")).toLowerCase() : void 0;
2357
+ const registry = (scope ? setting(`${scope}:registry`) : void 0) ?? setting("registry") ?? NPM_PUBLIC;
2358
+ if (canonicalRegistry(registry) !== canonicalRegistry(resolverNpmRegistry(env))) return "the launcher is pointed at a different npm registry";
2359
+ if (name === "yarn") {
2360
+ for (const dir of [prefix, context.home ?? homedir3()]) {
2361
+ const text = readSmall(join2(dir, ".yarnrc.yml")) ?? "";
2362
+ const server2 = /^\s*npmRegistryServer:\s*["']?([^"'\s#]+)/m.exec(text)?.[1];
2363
+ if (server2 && canonicalRegistry(server2) !== canonicalRegistry(resolverNpmRegistry(env)) || /^\s*npmScopes:/m.test(text)) {
2364
+ return "the launcher is pointed at a different npm registry";
2365
+ }
2366
+ }
2367
+ }
2368
+ if (name === "bunx" || name === "bun") {
2369
+ for (const dir of [prefix, context.home ?? homedir3()]) {
2370
+ if (/^\s*(?:registry\s*=|\[install\.scopes\])/m.test(readSmall(join2(dir, "bunfig.toml")) ?? "")) {
2371
+ return "the launcher is pointed at a different npm registry";
2372
+ }
2373
+ }
2374
+ }
2375
+ return void 0;
2376
+ }
2377
+ var PYPI_SOURCE_FLAGS = /* @__PURE__ */ new Set([
2378
+ "--index",
2379
+ "--index-url",
2380
+ "-i",
2381
+ "--extra-index-url",
2382
+ "--default-index",
2383
+ "--find-links",
2384
+ "-f",
2385
+ "--no-index",
2386
+ "--pip-args",
2387
+ "--config-file"
2388
+ ]);
2389
+ var PYPI_SOURCE_ENV = [
2390
+ "UV_INDEX",
2391
+ "UV_INDEX_URL",
2392
+ "UV_DEFAULT_INDEX",
2393
+ "UV_EXTRA_INDEX_URL",
2394
+ "UV_FIND_LINKS",
2395
+ "UV_NO_INDEX",
2396
+ "UV_CONFIG_FILE",
2397
+ "PIP_INDEX_URL",
2398
+ "PIP_EXTRA_INDEX_URL",
2399
+ "PIP_FIND_LINKS",
2400
+ "PIP_NO_INDEX",
2401
+ "PIP_CONFIG_FILE"
2402
+ ];
2403
+ var PYPI_INDEX_KEY = /^\s*(?:index-url|extra-index-url|default-index|find-links|no-index|\[\[(?:tool\.uv\.)?index\]\])/m;
2404
+ function pypiElsewhere(transport2, context) {
2405
+ const env = context.env ?? process.env;
2406
+ const name = commandName(transport2.command);
2407
+ const base = transport2.cwd ?? context.projectRoot;
2408
+ const home = context.home ?? homedir3();
2409
+ const launcherEnv = { ...env, ...transport2.env };
2410
+ if (launcherOptions(afterSubcommand(name, transport2.args), UV_VALUE_FLAGS, ["--from", "--spec"]).some(([flag]) => PYPI_SOURCE_FLAGS.has(flag))) {
2411
+ return "the launcher is given another package index";
2412
+ }
2413
+ for (const variable of PYPI_SOURCE_ENV) {
2414
+ const value = launcherEnv[variable];
2415
+ if (value && canonicalRegistry(value) !== PYPI_PUBLIC) return "the launcher is given another package index";
2416
+ }
2417
+ const files = [
2418
+ ...ancestors(base).flatMap((dir) => [join2(dir, "uv.toml"), join2(dir, "pyproject.toml")]),
2419
+ join2(launcherEnv["XDG_CONFIG_HOME"] ?? join2(home, ".config"), "uv", "uv.toml"),
2420
+ "/etc/uv/uv.toml",
2421
+ ...name === "pipx" ? [join2(home, ".config", "pip", "pip.conf"), join2(home, ".pip", "pip.conf"), join2(home, "Library", "Application Support", "pip", "pip.conf"), "/etc/pip.conf"] : []
2422
+ ];
2423
+ for (const file of files) {
2424
+ const text = readSmall(file);
2425
+ if (text === void 0) continue;
2426
+ if (file.endsWith("pyproject.toml") && !/\[\[?tool\.uv/.test(text)) continue;
2427
+ if (PYPI_INDEX_KEY.test(text) && !indexIsPublic(text)) return "a config file gives the launcher another package index";
2428
+ }
2429
+ return void 0;
2430
+ }
2431
+ function indexIsPublic(text) {
2432
+ const urls = [...text.matchAll(/^\s*(?:index-url|extra-index-url|default-index|url)\s*=\s*["']?([^"'\s#]+)/gm)].map((match) => match[1]);
2433
+ return urls.length > 0 && urls.every((url) => canonicalRegistry(url) === PYPI_PUBLIC) && !/^\s*(?:find-links|no-index)/m.test(text);
2434
+ }
2435
+ function fetchedElsewhere(transport2, reference, context) {
2436
+ if (reference.ecosystem === "npm") return npmElsewhere(transport2, reference, context);
2437
+ if (reference.ecosystem === "pypi") return pypiElsewhere(transport2, context);
2438
+ return void 0;
2439
+ }
2440
+
1905
2441
  // src/mcp/connect.ts
1906
2442
  import { Client, SSEClientTransport, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
1907
2443
  import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotocol/client/stdio";
@@ -1909,18 +2445,18 @@ import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotoc
1909
2445
  // src/mcp/oauth.ts
1910
2446
  import { spawn } from "child_process";
1911
2447
  import { createHash as createHash3, randomUUID } from "crypto";
1912
- import { readFileSync } from "fs";
2448
+ import { readFileSync as readFileSync2 } from "fs";
1913
2449
  import { mkdir, readFile as readFile4, rm, writeFile } from "fs/promises";
1914
- import { homedir as homedir3, platform as platform2 } from "os";
1915
- import { dirname, join as join2 } from "path";
2450
+ import { homedir as homedir4, platform as platform2 } from "os";
2451
+ import { dirname as dirname2, join as join3 } from "path";
1916
2452
  import { ClientCredentialsProvider, UnauthorizedError } from "@modelcontextprotocol/client";
1917
2453
  var DEFAULT_CALLBACK_PATH = "/callback";
1918
2454
  function authDir() {
1919
- const base = process.env["XDG_CONFIG_HOME"] ?? join2(homedir3(), ".config");
1920
- return join2(base, "nulladrift", "auth");
2455
+ const base = process.env["XDG_CONFIG_HOME"] ?? join3(homedir4(), ".config");
2456
+ return join3(base, "nulladrift", "auth");
1921
2457
  }
1922
2458
  function credentialPath(url) {
1923
- return join2(authDir(), `${createHash3("sha256").update(url).digest("hex").slice(0, 16)}.json`);
2459
+ return join3(authDir(), `${createHash3("sha256").update(url).digest("hex").slice(0, 16)}.json`);
1924
2460
  }
1925
2461
  var InteractiveAuthRequiredError = class extends Error {
1926
2462
  constructor(serverName) {
@@ -1973,7 +2509,7 @@ var FileTokenProvider = class {
1973
2509
  const next = { ...await this.read(), ...patch, serverUrl: this.serverUrl };
1974
2510
  this.cache = next;
1975
2511
  const path = credentialPath(this.serverUrl);
1976
- await mkdir(dirname(path), { recursive: true, mode: 448 });
2512
+ await mkdir(dirname2(path), { recursive: true, mode: 448 });
1977
2513
  await writeFile(path, `${JSON.stringify(next, null, 2)}
1978
2514
  `, { encoding: "utf8", mode: 384 });
1979
2515
  }
@@ -2026,25 +2562,35 @@ var FileTokenProvider = class {
2026
2562
  }
2027
2563
  async redirectToAuthorization(authorizationUrl) {
2028
2564
  if (!this.options.interactive) throw new InteractiveAuthRequiredError(this.serverName);
2029
- openInBrowser(authorizationUrl);
2030
- process.stderr.write(`
2565
+ if (openInBrowser(authorizationUrl)) {
2566
+ process.stderr.write(`
2031
2567
  If a browser did not open, visit:
2032
2568
  ${authorizationUrl.toString()}
2033
2569
 
2034
2570
  `);
2571
+ } else {
2572
+ process.stderr.write(`
2573
+ Not opening ${authorizationUrl.protocol} address the server named; an authorization page has to be https. Address:
2574
+ ${authorizationUrl.toString()}
2575
+
2576
+ `);
2577
+ }
2035
2578
  }
2036
2579
  };
2037
2580
  function openInBrowser(url) {
2038
- const command = platform2() === "darwin" ? "open" : platform2() === "win32" ? "cmd" : "xdg-open";
2039
- const args = platform2() === "win32" ? ["/c", "start", "", url.toString()] : [url.toString()];
2581
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
2582
+ if (!(url.protocol === "https:" || url.protocol === "http:" && loopback)) return false;
2583
+ const target = url.toString();
2584
+ const [command, args] = platform2() === "darwin" ? ["open", [target]] : platform2() === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", target]] : ["xdg-open", [target]];
2040
2585
  try {
2041
- spawn(command, args, { detached: true, stdio: "ignore" }).unref();
2586
+ spawn(command, args, { detached: true, stdio: "ignore", windowsHide: true }).unref();
2042
2587
  } catch {
2043
2588
  }
2589
+ return true;
2044
2590
  }
2045
2591
  function hasStoredCredentials(url) {
2046
2592
  try {
2047
- const stored = JSON.parse(readFileSync(credentialPath(url), "utf8"));
2593
+ const stored = JSON.parse(readFileSync2(credentialPath(url), "utf8"));
2048
2594
  return typeof stored.tokens?.access_token === "string" && stored.tokens.access_token.length > 0;
2049
2595
  } catch {
2050
2596
  return false;
@@ -2057,6 +2603,8 @@ function createAuthProvider(server2, options = {}) {
2057
2603
  return new ClientCredentialsProvider({
2058
2604
  clientId: oauth.clientId,
2059
2605
  clientSecret: oauth.clientSecret,
2606
+ // The SDK then refuses to send the secret to any other authorization server (SEP-2352).
2607
+ ...oauth.issuer === void 0 ? {} : { expectedIssuer: oauth.issuer },
2060
2608
  clientName: `nulladrift ${VERSION}`,
2061
2609
  ...oauth.scope === void 0 ? {} : { scope: oauth.scope }
2062
2610
  });
@@ -2221,6 +2769,21 @@ function describeListFailure(error) {
2221
2769
  }
2222
2770
  return message;
2223
2771
  }
2772
+ var MAX_LIST_PAGES = 64;
2773
+ async function listAllTools(client, timeoutMs) {
2774
+ const tools = [];
2775
+ const cursors = /* @__PURE__ */ new Set();
2776
+ let cursor;
2777
+ for (let page = 0; page < MAX_LIST_PAGES; page += 1) {
2778
+ const result = await client.request({ method: "tools/list", params: cursor === void 0 ? {} : { cursor } }, { timeout: timeoutMs });
2779
+ tools.push(...result.tools);
2780
+ cursor = result.nextCursor;
2781
+ if (cursor === void 0) return tools;
2782
+ if (cursors.has(cursor)) throw new Error("tools/list: the server repeated a page cursor, so the listing would never end");
2783
+ cursors.add(cursor);
2784
+ }
2785
+ throw new Error(`tools/list: more than ${MAX_LIST_PAGES} pages; the server's pagination did not end`);
2786
+ }
2224
2787
  async function listOrEmpty(label, serverName, fetchList) {
2225
2788
  try {
2226
2789
  return await fetchList();
@@ -2250,30 +2813,59 @@ function readServerInfo(client) {
2250
2813
  };
2251
2814
  }
2252
2815
  async function captureSurface(server2, timeoutMs = DEFAULT_TIMEOUT_MS2) {
2253
- const connection = await connect(server2, timeoutMs);
2254
- const { client } = connection;
2816
+ let connection;
2817
+ let expired = false;
2818
+ let timer;
2819
+ const late = () => new UnreachableServerError(server2.name, `did not finish within ${timeoutMs}ms`);
2820
+ const deadline = new Promise((_resolve, reject) => {
2821
+ timer = setTimeout(() => {
2822
+ expired = true;
2823
+ void connection?.close();
2824
+ reject(late());
2825
+ }, timeoutMs);
2826
+ timer.unref?.();
2827
+ });
2828
+ const work = (async () => {
2829
+ const opened = await connect(server2, timeoutMs);
2830
+ if (expired) {
2831
+ await opened.close();
2832
+ throw late();
2833
+ }
2834
+ connection = opened;
2835
+ try {
2836
+ return await readSurface(opened.client, server2, timeoutMs);
2837
+ } finally {
2838
+ await opened.close();
2839
+ }
2840
+ })();
2841
+ work.catch(() => void 0);
2255
2842
  try {
2256
- const capabilities = client.getServerCapabilities();
2257
- const [tools, resources, resourceTemplates, prompts] = await Promise.all([
2258
- capabilities?.tools ? listOrEmpty("tools/list", server2.name, async () => (await client.listTools(void 0, FRESH)).tools) : [],
2259
- capabilities?.resources ? listOrEmpty("resources/list", server2.name, async () => (await client.listResources(void 0, FRESH)).resources) : [],
2260
- capabilities?.resources ? listOrEmpty("resources/templates/list", server2.name, async () => (await client.listResourceTemplates(void 0, FRESH)).resourceTemplates) : [],
2261
- capabilities?.prompts ? listOrEmpty("prompts/list", server2.name, async () => (await client.listPrompts(void 0, FRESH)).prompts) : []
2262
- ]);
2263
- return {
2264
- protocol: readProtocol(client),
2265
- serverInfo: readServerInfo(client),
2266
- capabilities: capabilities ? toJson(capabilities) : void 0,
2267
- // Clients place this in the model's system prompt, so it is part of the capability surface.
2268
- instructions: client.getInstructions(),
2269
- tools,
2270
- resources,
2271
- resourceTemplates,
2272
- prompts
2273
- };
2843
+ return await Promise.race([work, deadline]);
2274
2844
  } finally {
2275
- await connection.close();
2276
- }
2845
+ clearTimeout(timer);
2846
+ }
2847
+ }
2848
+ async function readSurface(client, server2, timeoutMs) {
2849
+ const capabilities = client.getServerCapabilities();
2850
+ const [tools, resources, resourceTemplates, prompts] = await Promise.all([
2851
+ capabilities?.tools ? listOrEmpty("tools/list", server2.name, async () => listAllTools(client, timeoutMs)) : [],
2852
+ // Each list call is bounded by the server's timeout too. With none, the SDK's default
2853
+ // applied per page (60s, up to 64 pages), so one slow server could hold a run for an hour.
2854
+ capabilities?.resources ? listOrEmpty("resources/list", server2.name, async () => (await client.listResources(void 0, { ...FRESH, timeout: timeoutMs })).resources) : [],
2855
+ capabilities?.resources ? listOrEmpty("resources/templates/list", server2.name, async () => (await client.listResourceTemplates(void 0, { ...FRESH, timeout: timeoutMs })).resourceTemplates) : [],
2856
+ capabilities?.prompts ? listOrEmpty("prompts/list", server2.name, async () => (await client.listPrompts(void 0, { ...FRESH, timeout: timeoutMs })).prompts) : []
2857
+ ]);
2858
+ return {
2859
+ protocol: readProtocol(client),
2860
+ serverInfo: readServerInfo(client),
2861
+ capabilities: capabilities ? toJson(capabilities) : void 0,
2862
+ // Clients place this in the model's system prompt, so it is part of the capability surface.
2863
+ instructions: client.getInstructions(),
2864
+ tools,
2865
+ resources,
2866
+ resourceTemplates,
2867
+ prompts
2868
+ };
2277
2869
  }
2278
2870
 
2279
2871
  // src/audit.ts
@@ -2281,6 +2873,7 @@ async function provenanceOf(server2, options) {
2281
2873
  if (server2.transport.type !== "stdio") return { unverified: false };
2282
2874
  const reference = referenceOf(server2.transport, options.projectRoot);
2283
2875
  if (!reference) return { unverified: false };
2876
+ if (fetchedElsewhere(server2.transport, reference, { projectRoot: options.projectRoot })) return { unverified: true };
2284
2877
  const previous = options.previous?.subjects[server2.name]?.provenance;
2285
2878
  if (options.provenance === false) {
2286
2879
  const kept2 = carriedForward(previous, reference);
@@ -2305,31 +2898,13 @@ async function mapWithLimit(items, limit, worker) {
2305
2898
  await Promise.all(runners);
2306
2899
  return results;
2307
2900
  }
2308
- async function withDeadline(ms, name, run) {
2309
- let timer;
2310
- try {
2311
- return await Promise.race([
2312
- run(),
2313
- new Promise((_resolve, reject) => {
2314
- timer = setTimeout(() => reject(new UnreachableServerError(name, `did not finish within ${ms}ms`)), ms);
2315
- timer.unref?.();
2316
- })
2317
- ]);
2318
- } finally {
2319
- if (timer) clearTimeout(timer);
2320
- }
2321
- }
2322
2901
  async function captureAll(options) {
2323
- const discovery = await discoverServers(options.projectRoot, options.configFiles);
2902
+ const discovery = await discoverServers(options.projectRoot, options.configFiles, { userConfigs: options.userConfigs === true });
2324
2903
  const captured = await mapWithLimit(discovery.servers, options.concurrency ?? 4, async (server2) => {
2325
2904
  try {
2326
- const surface = await withDeadline(
2327
- options.timeoutMs ?? DEFAULT_TIMEOUT_MS2,
2328
- server2.name,
2329
- () => captureSurface(server2, options.timeoutMs ?? DEFAULT_TIMEOUT_MS2)
2330
- );
2331
- const entry = buildLockedServer(server2, surface, options.policy);
2332
2905
  const { provenance: provenance2, unverified: unverified2 } = await provenanceOf(server2, options);
2906
+ const surface = await captureSurface(server2, options.timeoutMs ?? DEFAULT_TIMEOUT_MS2);
2907
+ const entry = buildLockedServer(server2, surface, options.policy);
2333
2908
  options.onServerDone?.(server2.name, "captured");
2334
2909
  return { name: server2.name, entry: provenance2 ? { ...entry, provenance: provenance2 } : entry, unverified: unverified2 };
2335
2910
  } catch (error) {
@@ -2368,14 +2943,25 @@ async function captureAll(options) {
2368
2943
  }
2369
2944
 
2370
2945
  // src/lock/io.ts
2946
+ import { randomUUID as randomUUID2 } from "crypto";
2371
2947
  import { lstat, readFile as readFile5, rename, rm as rm2, writeFile as writeFile2 } from "fs/promises";
2372
2948
 
2373
2949
  // src/lock/schema.ts
2374
2950
  import { z as z2 } from "zod";
2375
- var jsonValue = z2.lazy(
2376
- () => z2.union([z2.string(), z2.number(), z2.boolean(), z2.null(), z2.array(jsonValue), z2.record(z2.string(), jsonValue)])
2951
+ function isJsonValue(value, depth = 0) {
2952
+ if (depth > 256) return false;
2953
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
2954
+ if (typeof value === "number") return Number.isFinite(value);
2955
+ if (Array.isArray(value)) return value.every((member) => isJsonValue(member, depth + 1));
2956
+ if (typeof value !== "object") return false;
2957
+ const prototype = Object.getPrototypeOf(value);
2958
+ if (prototype !== Object.prototype && prototype !== null) return false;
2959
+ return Object.values(value).every((member) => isJsonValue(member, depth + 1));
2960
+ }
2961
+ var jsonObject = z2.custom(
2962
+ (value) => value !== null && typeof value === "object" && !Array.isArray(value) && isJsonValue(value),
2963
+ "expected a JSON object"
2377
2964
  );
2378
- var jsonObject = z2.record(z2.string(), jsonValue);
2379
2965
  var digestString = z2.string().regex(/^sha256:[0-9a-f]{64}$/, "expected a sha256 digest");
2380
2966
  var icon = z2.object({
2381
2967
  src: z2.string(),
@@ -2549,13 +3135,14 @@ function isPlainObject(value) {
2549
3135
  function printScalar(value) {
2550
3136
  return JSON.stringify(value);
2551
3137
  }
3138
+ var childKind = (key) => Object.hasOwn(CHILD_KIND, key) ? CHILD_KIND[key] : void 0;
2552
3139
  function printObject(value, kind, depth) {
2553
- const declared = kind ? KEY_ORDER[kind] : [];
3140
+ const declared = kind && Object.hasOwn(KEY_ORDER, kind) ? KEY_ORDER[kind] : [];
2554
3141
  const present = Object.keys(value).filter((key) => value[key] !== void 0);
2555
3142
  const ordered = kind ? [...declared.filter((key) => present.includes(key)), ...present.filter((key) => !declared.includes(key)).sort()] : present.sort();
2556
3143
  if (ordered.length === 0) return "{}";
2557
3144
  const pad = INDENT.repeat(depth + 1);
2558
- const body = ordered.map((key) => `${pad}${JSON.stringify(key)}: ${printNode(value[key], CHILD_KIND[key], depth + 1)}`).join(",\n");
3145
+ const body = ordered.map((key) => `${pad}${JSON.stringify(key)}: ${printNode(value[key], childKind(key), depth + 1)}`).join(",\n");
2559
3146
  return `{
2560
3147
  ${body}
2561
3148
  ${INDENT.repeat(depth)}}`;
@@ -2599,7 +3186,7 @@ ${pad}}`;
2599
3186
  parts.push(`${pad}${JSON.stringify(key)}: ${body}`);
2600
3187
  continue;
2601
3188
  }
2602
- parts.push(`${pad}${JSON.stringify(key)}: ${printNode(value, CHILD_KIND[key], 1)}`);
3189
+ parts.push(`${pad}${JSON.stringify(key)}: ${printNode(value, childKind(key), 1)}`);
2603
3190
  }
2604
3191
  return `{
2605
3192
  ${parts.join(",\n")}
@@ -2643,8 +3230,8 @@ async function readLockfile(path) {
2643
3230
  try {
2644
3231
  text = await readFile5(path, "utf8");
2645
3232
  } catch (error) {
2646
- const code = error.code;
2647
- if (code === "ENOENT") throw new LockfileError(`no lockfile at ${path}. Run \`nulladrift init\` first.`);
3233
+ const code2 = error.code;
3234
+ if (code2 === "ENOENT") throw new LockfileError(`no lockfile at ${path}. Run \`nulladrift init\` first.`);
2648
3235
  throw new LockfileError(`could not read ${path}: ${error.message}`);
2649
3236
  }
2650
3237
  const lock = parseLockfile(text, path);
@@ -2663,8 +3250,8 @@ async function writeLockfile(path, lock) {
2663
3250
  if (error instanceof LockfileError) throw error;
2664
3251
  }
2665
3252
  try {
2666
- const temporary = `${path}.${process.pid}.tmp`;
2667
- await writeFile2(temporary, serializeLockfile(lock), "utf8");
3253
+ const temporary = `${path}.${randomUUID2()}.tmp`;
3254
+ await writeFile2(temporary, serializeLockfile(lock), { encoding: "utf8", flag: "wx" });
2668
3255
  try {
2669
3256
  await rename(temporary, path);
2670
3257
  } catch (error) {
@@ -2673,9 +3260,9 @@ async function writeLockfile(path, lock) {
2673
3260
  throw error;
2674
3261
  }
2675
3262
  } catch (error) {
2676
- const code = error.code;
2677
- if (code === "ENOENT") throw new LockfileError(`cannot write ${path}: the directory does not exist. Note that --lock is resolved against --cwd.`);
2678
- if (code === "EACCES" || code === "EPERM") throw new LockfileError(`cannot write ${path}: permission denied.`);
3263
+ const code2 = error.code;
3264
+ if (code2 === "ENOENT") throw new LockfileError(`cannot write ${path}: the directory does not exist. Note that --lock is resolved against --cwd.`);
3265
+ if (code2 === "EACCES" || code2 === "EPERM") throw new LockfileError(`cannot write ${path}: permission denied.`);
2679
3266
  throw new LockfileError(`cannot write ${path}: ${error.message}`);
2680
3267
  }
2681
3268
  }
@@ -2703,8 +3290,8 @@ function renderTextChange(before, after) {
2703
3290
  return lines;
2704
3291
  }
2705
3292
  function renderChange(change2) {
2706
- const where = change2.member ? `${change2.server} \u203A ${change2.member}` : change2.server;
2707
- const lines = [` ${MARK[change2.severity](change2.severity.padEnd(6))} ${bold(where)} ${dim(change2.kind)}`, ` ${change2.summary}`];
3293
+ const where = visibleControls(change2.member ? `${change2.server} \u203A ${change2.member}` : change2.server);
3294
+ const lines = [` ${MARK[change2.severity](change2.severity.padEnd(6))} ${bold(where)} ${dim(change2.kind)}`, ` ${visibleControls(change2.summary)}`];
2708
3295
  if (change2.kind === "tool.description.changed" || change2.kind === "server.instructions.changed") {
2709
3296
  lines.push(...renderTextChange(change2.before, change2.after));
2710
3297
  }
@@ -2719,7 +3306,7 @@ function renderSteering(report) {
2719
3306
  ""
2720
3307
  ];
2721
3308
  for (const { server: server2, signals } of found) {
2722
- lines.push(` ${bold(server2)}`);
3309
+ lines.push(` ${bold(visibleControls(server2))}`);
2723
3310
  const byField = /* @__PURE__ */ new Map();
2724
3311
  for (const signal of signals) byField.set(signal.field, [...byField.get(signal.field) ?? [], signal.quote]);
2725
3312
  const fields = [...byField];
@@ -2738,7 +3325,7 @@ function renderViolations(report) {
2738
3325
  const lines = ["", bold(red(`${found.length} capability(ies) this project does not permit:`)), ""];
2739
3326
  for (const violation of found) {
2740
3327
  lines.push(
2741
- ` ${red("denied")} ${bold(`${violation.server} \u203A ${violation.tool}`)} ${dim(violation.kind)}`,
3328
+ ` ${red("denied")} ${bold(visibleControls(`${violation.server} \u203A ${violation.tool}`))} ${dim(violation.kind)}`,
2742
3329
  ` ${violation.severity} \xB7 ${violation.evidence}`
2743
3330
  );
2744
3331
  }
@@ -2762,7 +3349,7 @@ function renderHumanReport(report) {
2762
3349
  if (quiet.length > 0) {
2763
3350
  lines.push(
2764
3351
  yellow(`${quiet.length === 1 ? "This server" : "These servers"} changed without shipping a new version:`),
2765
- ...quiet.map((server2) => ` ${bold(server2)}`),
3352
+ ...quiet.map((server2) => ` ${bold(visibleControls(server2))}`),
2766
3353
  ""
2767
3354
  );
2768
3355
  }
@@ -2771,14 +3358,14 @@ function renderHumanReport(report) {
2771
3358
  lines.push(bold(`Could not audit ${report.unreachable.length} server(s):`), "");
2772
3359
  for (const failure of report.unreachable) {
2773
3360
  const label = failure.kind === "auth" ? yellow("needs creds") : failure.kind === "forbidden" ? yellow("not permitted") : red("unreachable");
2774
- lines.push(` ${label} ${bold(failure.server)}`, ` ${failure.reason}`, "");
3361
+ lines.push(` ${label} ${bold(visibleControls(failure.server))}`, ` ${visibleControls(failure.reason)}`, "");
2775
3362
  }
2776
3363
  }
2777
3364
  const unverified = report.unverified ?? [];
2778
3365
  if (unverified.length > 0) {
2779
3366
  lines.push(
2780
3367
  yellow(`Could not establish what ${unverified.length} server(s) run:`),
2781
- ...unverified.map((server2) => ` ${bold(server2)}`),
3368
+ ...unverified.map((server2) => ` ${bold(visibleControls(server2))}`),
2782
3369
  dim(" Their surfaces were checked; the package or file behind them was not. A pin the config names exactly is kept."),
2783
3370
  ""
2784
3371
  );
@@ -2817,6 +3404,18 @@ function renderHumanReport(report) {
2817
3404
  `;
2818
3405
  }
2819
3406
 
3407
+ // src/report/redacted.ts
3408
+ function redactedLine(count) {
3409
+ const values = count === 1 ? "1 value that looks like a credential is" : `${count} values that look like credentials are`;
3410
+ return `${values} left out of the lock. Write each as \${VAR} instead, and rotate any an earlier mcp.lock committed.`;
3411
+ }
3412
+ function redactedNotes(lock) {
3413
+ return Object.entries(lock.subjects).flatMap(([name, entry]) => {
3414
+ const count = countRedacted(entry.transport);
3415
+ return count > 0 ? [`${name}: ${redactedLine(count)}`] : [];
3416
+ });
3417
+ }
3418
+
2820
3419
  // src/report/json.ts
2821
3420
  function renderJsonReport(report, exitCode) {
2822
3421
  return `${JSON.stringify(
@@ -2995,12 +3594,19 @@ var AUDIT_FAILURE_LABEL = {
2995
3594
  unreachable: "unreachable"
2996
3595
  };
2997
3596
  var MARK2 = { high: "\u{1F534}", medium: "\u{1F7E0}", low: "\u26AA" };
2998
- function cell(text) {
2999
- return visibleControls(text).replace(/\|/g, "\\|").replace(/`/g, "\\`").replace(/\r?\n/g, " ").trim();
3597
+ function plain(text) {
3598
+ return visibleControls(text).replace(/\r?\n/g, " ").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/([\\`*_{}[\]()#+!|~])/g, "\\$1").replace(/@/g, "&#64;").replace(/:\/\//g, "&#58;//").trim();
3599
+ }
3600
+ function code(text) {
3601
+ const body = visibleControls(text).replace(/\r?\n/g, " ").replace(/\|/g, "\\|").trim();
3602
+ const longest = Math.max(0, ...(body.match(/`+/g) ?? []).map((run) => run.length));
3603
+ const fence = "`".repeat(longest + 1);
3604
+ const pad = body.startsWith("`") || body.endsWith("`") ? " " : "";
3605
+ return `${fence}${pad}${body}${pad}${fence}`;
3000
3606
  }
3001
3607
  function row(change2) {
3002
3608
  const where = change2.member ? `${change2.server}/${change2.member}` : change2.server;
3003
- return `| ${MARK2[change2.severity]} ${change2.severity} | \`${cell(where)}\` | ${cell(change2.kind)} | ${cell(change2.summary)} |`;
3609
+ return `| ${MARK2[change2.severity]} ${change2.severity} | ${code(where)} | ${plain(change2.kind)} | ${plain(change2.summary)} |`;
3004
3610
  }
3005
3611
  function renderMarkdownReport(report, options = {}) {
3006
3612
  if (report.changes.length === 0 && report.unreachable.length === 0) return null;
@@ -3018,7 +3624,7 @@ function renderMarkdownReport(report, options = {}) {
3018
3624
  const quiet = serversThatShippedNothing(report.changes);
3019
3625
  if (quiet.length > 0) {
3020
3626
  lines.push(
3021
- `> **${quiet.length === 1 ? "This server" : "These servers"} changed without shipping a new version:** ${quiet.map((server2) => `\`${cell(server2)}\``).join(", ")}`,
3627
+ `> **${quiet.length === 1 ? "This server" : "These servers"} changed without shipping a new version:** ${quiet.map((server2) => code(server2)).join(", ")}`,
3022
3628
  ">",
3023
3629
  "> Same package, same version, a different declaration. Nothing was published.",
3024
3630
  ""
@@ -3038,7 +3644,7 @@ function renderMarkdownReport(report, options = {}) {
3038
3644
  "| Server | Field | Passage |",
3039
3645
  "| --- | --- | --- |",
3040
3646
  ...steering.flatMap(
3041
- ({ server: server2, signals }) => signals.slice(0, 10).map((signal) => `| \`${cell(server2)}\` | \`${cell(signal.field)}\` | ${cell(signal.quote)} |`)
3647
+ ({ server: server2, signals }) => signals.slice(0, 10).map((signal) => `| ${code(server2)} | ${code(signal.field)} | ${plain(signal.quote)} |`)
3042
3648
  ),
3043
3649
  "",
3044
3650
  "</details>",
@@ -3050,7 +3656,7 @@ function renderMarkdownReport(report, options = {}) {
3050
3656
  `<details><summary>${report.unreachable.length} server${report.unreachable.length === 1 ? "" : "s"} could not be read</summary>`,
3051
3657
  "",
3052
3658
  ...report.unreachable.map(
3053
- (failure) => `- \`${cell(failure.server)}\` \xB7 ${AUDIT_FAILURE_LABEL[failure.kind]}: ${cell(failure.reason)}`
3659
+ (failure) => `- ${code(failure.server)} \xB7 ${AUDIT_FAILURE_LABEL[failure.kind]}: ${plain(failure.reason)}`
3054
3660
  ),
3055
3661
  "",
3056
3662
  "</details>",
@@ -3107,16 +3713,16 @@ ${body}`;
3107
3713
  }
3108
3714
 
3109
3715
  // src/telemetry/index.ts
3110
- import { createHash as createHash5, randomUUID as randomUUID2 } from "crypto";
3716
+ import { createHash as createHash5, randomUUID as randomUUID3 } from "crypto";
3111
3717
  import { mkdir as mkdir2, readFile as readFile6, rm as rm3, writeFile as writeFile3 } from "fs/promises";
3112
- import { homedir as homedir4 } from "os";
3113
- import { dirname as dirname2, join as join3 } from "path";
3718
+ import { homedir as homedir5 } from "os";
3719
+ import { dirname as dirname3, join as join4 } from "path";
3114
3720
  var PAYLOAD_SCHEMA = 2;
3115
3721
  var SEND_TIMEOUT_MS = 2e3;
3116
3722
  var ID_ROTATION_MS = 30 * 24 * 60 * 60 * 1e3;
3117
3723
  function configPath() {
3118
- const base = process.env["XDG_CONFIG_HOME"] ?? join3(homedir4(), ".config");
3119
- return join3(base, "nulladrift", "config.json");
3724
+ const base = process.env["XDG_CONFIG_HOME"] ?? join4(homedir5(), ".config");
3725
+ return join4(base, "nulladrift", "config.json");
3120
3726
  }
3121
3727
  function isCi() {
3122
3728
  return process.env["CI"] !== void 0 && process.env["CI"] !== "false";
@@ -3131,7 +3737,7 @@ async function readConfig() {
3131
3737
  }
3132
3738
  async function writeConfig(patch) {
3133
3739
  const path = configPath();
3134
- await mkdir2(dirname2(path), { recursive: true });
3740
+ await mkdir2(dirname3(path), { recursive: true });
3135
3741
  await writeFile3(path, `${JSON.stringify({ ...await readConfig(), ...patch }, null, 2)}
3136
3742
  `, "utf8");
3137
3743
  }
@@ -3150,7 +3756,7 @@ async function resolveInstallId(now = Date.now()) {
3150
3756
  const issuedAt = config.installIdIssuedAt ? Date.parse(config.installIdIssuedAt) : Number.NaN;
3151
3757
  const fresh = config.installId !== void 0 && Number.isFinite(issuedAt) && now - issuedAt < ID_ROTATION_MS;
3152
3758
  if (fresh && config.installId !== void 0) return config.installId;
3153
- const installId = randomUUID2();
3759
+ const installId = randomUUID3();
3154
3760
  await writeConfig({ installId, installIdIssuedAt: new Date(now).toISOString(), lastReportHash: void 0 });
3155
3761
  return installId;
3156
3762
  }
@@ -3161,7 +3767,7 @@ function buildPayload(report, changes, installId) {
3161
3767
  schema: PAYLOAD_SCHEMA,
3162
3768
  installId,
3163
3769
  // Distinguishes two runs from the same installation; not stored, and not an identifier.
3164
- runId: randomUUID2(),
3770
+ runId: randomUUID3(),
3165
3771
  auditVersion: VERSION,
3166
3772
  context: isCi() ? "ci" : "local",
3167
3773
  serverCount: report.serversChecked,
@@ -3212,8 +3818,11 @@ async function buildReport(options) {
3212
3818
  // The committed policy governs the check, so every consumer of the repo audits identically.
3213
3819
  policy: committed.policy,
3214
3820
  previous: committed,
3215
- provenance: options.provenance
3821
+ provenance: options.provenance,
3822
+ userConfigs: options.userConfigs
3216
3823
  });
3824
+ for (const note of redactedNotes(result.lock)) process.stderr.write(`${yellow("note:")} ${note}
3825
+ `);
3217
3826
  const changes = diffLockfiles(committed, result.lock);
3218
3827
  const allowUnreachable = options.allowUnreachable || committed.policy?.allowUnreachable === true;
3219
3828
  const report = {
@@ -3405,7 +4014,8 @@ async function runInit(options) {
3405
4014
  projectRoot: options.projectRoot,
3406
4015
  configFiles: options.configFiles,
3407
4016
  timeoutMs: options.timeoutMs,
3408
- provenance: options.provenance
4017
+ provenance: options.provenance,
4018
+ userConfigs: options.userConfigs
3409
4019
  });
3410
4020
  const names = Object.keys(result.lock.subjects);
3411
4021
  if (names.length === 0 && result.unreachable.length === 0) {
@@ -3432,9 +4042,11 @@ async function runInit(options) {
3432
4042
  `${entry?.resourceTemplates?.length ?? 0} templates`,
3433
4043
  `${entry?.prompts?.length ?? 0} prompts`
3434
4044
  ].join(", ");
3435
- lines.push(` ${green("\u2713")} ${bold(name)} ${dim(counts)}`);
4045
+ lines.push(` ${green("\u2713")} ${bold(visibleControls(name))} ${dim(counts)}`);
3436
4046
  const deprecated = entry?.transport.type === "sse" ? " \xB7 HTTP+SSE transport is deprecated in the spec" : "";
3437
- lines.push(` ${dim(`${entry?.protocol.era}/${entry?.protocol.version} \xB7 from ${entry?.source.file}${deprecated}`)}`);
4047
+ lines.push(` ${dim(visibleControls(`${entry?.protocol.era}/${entry?.protocol.version} \xB7 from ${entry?.source.file}${deprecated}`))}`);
4048
+ const redacted = entry ? countRedacted(entry.transport) : 0;
4049
+ if (redacted > 0) lines.push(` ${yellow(redactedLine(redacted))}`);
3438
4050
  const tools = entry?.tools ?? [];
3439
4051
  const capabilities = surfaceCapabilities(tools);
3440
4052
  if (capabilities.length > 0) {
@@ -3442,7 +4054,7 @@ async function runInit(options) {
3442
4054
  const paint = worst.length > 0 ? yellow : dim;
3443
4055
  lines.push(` ${paint(`can: ${capabilities.map((capability) => capability.kind).join(", ")}`)}`);
3444
4056
  for (const capability of worst) {
3445
- lines.push(` ${dim(`${capability.kind} \xB7 ${capability.tools.slice(0, 3).join(", ")}${capability.tools.length > 3 ? ` +${capability.tools.length - 3}` : ""}`)}`);
4057
+ lines.push(` ${dim(visibleControls(`${capability.kind} \xB7 ${capability.tools.slice(0, 3).join(", ")}${capability.tools.length > 3 ? ` +${capability.tools.length - 3}` : ""}`))}`);
3446
4058
  }
3447
4059
  }
3448
4060
  const steering = (entry ? surfaceText(entry) : []).flatMap(
@@ -3466,6 +4078,12 @@ async function runInit(options) {
3466
4078
  for (const failure of result.unreachable) {
3467
4079
  lines.push(` ${red("\u2717")} ${bold(failure.server)} ${dim("not pinned")}`, ` ${failure.reason}`);
3468
4080
  }
4081
+ if (result.discovery.userConfigsSkipped.length > 0) {
4082
+ lines.push(
4083
+ dim(` note: your own configs were not pinned (${result.discovery.userConfigsSkipped.join(", ")}). mcp.lock is the project's and is committed;`),
4084
+ dim(" pass --user-configs to include their servers anyway.")
4085
+ );
4086
+ }
3469
4087
  for (const shadow of result.discovery.shadowed) {
3470
4088
  lines.push(dim(` note: "${shadow.name}" is defined in both ${shadow.keptFrom} and ${shadow.alsoIn}; kept the first.`));
3471
4089
  }
@@ -3495,14 +4113,14 @@ async function awaitCallback(expectedState) {
3495
4113
  return;
3496
4114
  }
3497
4115
  const error = url.searchParams.get("error");
3498
- const code = url.searchParams.get("code");
4116
+ const code2 = url.searchParams.get("code");
3499
4117
  const state = url.searchParams.get("state");
3500
4118
  if (error !== null) {
3501
4119
  response.writeHead(400, { "content-type": "text/plain" }).end(`authorization failed: ${error}`);
3502
4120
  fail?.(new Error(`${error}${url.searchParams.get("error_description") ? `: ${url.searchParams.get("error_description")}` : ""}`));
3503
4121
  return;
3504
4122
  }
3505
- if (code === null) {
4123
+ if (code2 === null) {
3506
4124
  response.writeHead(400, { "content-type": "text/plain" }).end("no authorization code in the callback");
3507
4125
  fail?.(new Error("callback carried no authorization code"));
3508
4126
  return;
@@ -3513,15 +4131,15 @@ async function awaitCallback(expectedState) {
3513
4131
  return;
3514
4132
  }
3515
4133
  response.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end("<!doctype html><title>nulladrift</title><p>Authorized. You can close this tab.");
3516
- settle?.({ code, state, iss: url.searchParams.get("iss") ?? void 0 });
4134
+ settle?.({ code: code2, state, iss: url.searchParams.get("iss") ?? void 0 });
3517
4135
  });
3518
4136
  await new Promise((ready, broke) => {
3519
4137
  server2.once("error", broke);
3520
4138
  server2.listen(0, "127.0.0.1", ready);
3521
4139
  });
3522
4140
  const { port } = server2.address();
3523
- const received = new Promise((resolve5, reject) => {
3524
- settle = resolve5;
4141
+ const received = new Promise((resolve6, reject) => {
4142
+ settle = resolve6;
3525
4143
  fail = reject;
3526
4144
  setTimeout(() => reject(new Error(`no callback within ${CALLBACK_TIMEOUT_MS / 1e3}s`)), CALLBACK_TIMEOUT_MS).unref();
3527
4145
  });
@@ -3532,7 +4150,7 @@ async function awaitCallback(expectedState) {
3532
4150
  };
3533
4151
  }
3534
4152
  async function findServer(projectRoot, configFiles, name) {
3535
- const discovery = await discoverServers(projectRoot, configFiles);
4153
+ const discovery = await discoverServers(projectRoot, configFiles, { userConfigs: true });
3536
4154
  const server2 = discovery.servers.find((candidate) => candidate.name === name);
3537
4155
  if (!server2) {
3538
4156
  const known = discovery.servers.map((candidate) => candidate.name);
@@ -3560,7 +4178,7 @@ async function runLogin(options) {
3560
4178
  Object.assign(authenticating, { stateValue: provider.stateValue });
3561
4179
  try {
3562
4180
  process.stdout.write(`${bold(`Authorizing ${found.name}`)}
3563
- ${dim(serverUrl)}
4181
+ ${dim(sanitizeUrl(serverUrl))}
3564
4182
  `);
3565
4183
  const started = await auth(authenticating, { serverUrl });
3566
4184
  if (started === "AUTHORIZED") {
@@ -3568,8 +4186,8 @@ ${dim(serverUrl)}
3568
4186
  `);
3569
4187
  return EXIT_CLEAN;
3570
4188
  }
3571
- const { code, iss } = await callback.wait();
3572
- const finished = await auth(authenticating, { serverUrl, authorizationCode: code, ...iss === void 0 ? {} : { iss } });
4189
+ const { code: code2, iss } = await callback.wait();
4190
+ const finished = await auth(authenticating, { serverUrl, authorizationCode: code2, ...iss === void 0 ? {} : { iss } });
3573
4191
  if (finished !== "AUTHORIZED") {
3574
4192
  process.stderr.write(`${red("authorization did not complete")}
3575
4193
  `);
@@ -3610,10 +4228,10 @@ async function runLogout(options) {
3610
4228
  function envelope(body) {
3611
4229
  try {
3612
4230
  const parsed = JSON.parse(body);
3613
- const code = parsed.error?.code;
4231
+ const code2 = parsed.error?.code;
3614
4232
  const message = parsed.error?.message;
3615
- if (typeof code !== "string" || typeof message !== "string") return null;
3616
- return { code, message };
4233
+ if (typeof code2 !== "string" || typeof message !== "string") return null;
4234
+ return { code: code2, message };
3617
4235
  } catch {
3618
4236
  return null;
3619
4237
  }
@@ -3696,6 +4314,18 @@ function inferRef() {
3696
4314
  function inferCommit() {
3697
4315
  return process.env["GITHUB_SHA"] ?? process.env["CI_COMMIT_SHA"] ?? void 0;
3698
4316
  }
4317
+ function refuseApiUrl(apiUrl) {
4318
+ let url;
4319
+ try {
4320
+ url = new URL(apiUrl);
4321
+ } catch {
4322
+ return "the control plane's address is not a URL.";
4323
+ }
4324
+ if (url.username || url.password) return "the control plane's address carries credentials. Pass the token with --token or NULLADRIFT_TOKEN instead.";
4325
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
4326
+ if (url.protocol === "https:" || url.protocol === "http:" && loopback) return void 0;
4327
+ return `the control plane has to be reached over https (http only on this machine), not ${url.protocol}`;
4328
+ }
3699
4329
  async function runPush(options) {
3700
4330
  const apiUrl = (options.apiUrl ?? process.env["NULLADRIFT_API_URL"] ?? "").replace(/\/+$/, "");
3701
4331
  const token = options.token ?? process.env["NULLADRIFT_TOKEN"] ?? "";
@@ -3711,12 +4341,21 @@ async function runPush(options) {
3711
4341
  );
3712
4342
  return EXIT_INCOMPLETE;
3713
4343
  }
4344
+ const refusal = refuseApiUrl(apiUrl);
4345
+ if (refusal) {
4346
+ process.stderr.write(`${red("push refused:")} ${refusal}
4347
+ `);
4348
+ return EXIT_INCOMPLETE;
4349
+ }
3714
4350
  const result = await captureAll({
3715
4351
  projectRoot: options.projectRoot,
3716
4352
  configFiles: options.configFiles,
3717
4353
  timeoutMs: options.timeoutMs,
3718
- provenance: options.provenance
4354
+ provenance: options.provenance,
4355
+ userConfigs: options.userConfigs
3719
4356
  });
4357
+ for (const note of redactedNotes(result.lock)) process.stderr.write(`${yellow("note:")} ${note}
4358
+ `);
3720
4359
  if (Object.keys(result.lock.subjects).length === 0 && result.unreachable.length === 0) {
3721
4360
  const looked = result.discovery.filesRead.length > 0 ? result.discovery.filesRead.join(", ") : "no client config files exist for this project";
3722
4361
  process.stderr.write(`No MCP servers found, so there is nothing to push.
@@ -3745,7 +4384,9 @@ ${dim(`Looked in: ${looked}`)}
3745
4384
  context: options.watch ? "watch" : process.env["CI"] !== void 0 && process.env["CI"] !== "false" ? "ci" : "local",
3746
4385
  collectorVersion: VERSION,
3747
4386
  servers,
3748
- unreachable: result.unreachable.map((failure) => ({ server: failure.server, reason: failure.reason }))
4387
+ // The error, not the server's stderr: stderr is where a server prints its tokens and paths, and
4388
+ // this leaves the machine. The full reason is still printed locally.
4389
+ unreachable: result.unreachable.map((failure) => ({ server: failure.server, reason: failure.reason.split("\n server stderr:")[0] ?? failure.reason }))
3749
4390
  };
3750
4391
  const build = await acquireBuildToken();
3751
4392
  const buildToken = build && "token" in build ? build.token : void 0;
@@ -3759,6 +4400,8 @@ ${dim(`Looked in: ${looked}`)}
3759
4400
  ...buildToken ? { [BUILD_TOKEN_HEADER]: buildToken } : {}
3760
4401
  },
3761
4402
  body: JSON.stringify(body),
4403
+ // A redirect would carry the reading and the identity token to wherever it points.
4404
+ redirect: "error",
3762
4405
  signal: AbortSignal.timeout(options.timeoutMs)
3763
4406
  });
3764
4407
  } catch (error) {
@@ -3767,8 +4410,8 @@ ${dim(`Looked in: ${looked}`)}
3767
4410
  return EXIT_INCOMPLETE;
3768
4411
  }
3769
4412
  if (!response.ok) {
3770
- const refusal = describeRefusal(response.status, await response.text());
3771
- process.stderr.write(`${refusal.planLimit ? yellow("plan limit:") : red("push failed:")} ${refusal.text}
4413
+ const refusal2 = describeRefusal(response.status, await response.text());
4414
+ process.stderr.write(`${refusal2.planLimit ? yellow("plan limit:") : red("push failed:")} ${refusal2.text}
3772
4415
  `);
3773
4416
  return EXIT_INCOMPLETE;
3774
4417
  }
@@ -3817,7 +4460,7 @@ function describeSurface(subject, previous) {
3817
4460
  return lines;
3818
4461
  }
3819
4462
  function describe(change2) {
3820
- const head = ` ${change2.severity === "high" ? red("\u25CF") : change2.severity === "medium" ? yellow("\u25CF") : dim("\u25CF")} ${change2.member ? `${bold(change2.member)}: ` : ""}${change2.summary} ${dim(change2.kind)}`;
4463
+ const head = ` ${change2.severity === "high" ? red("\u25CF") : change2.severity === "medium" ? yellow("\u25CF") : dim("\u25CF")} ${change2.member ? `${bold(visibleControls(change2.member))}: ` : ""}${visibleControls(change2.summary)} ${dim(change2.kind)}`;
3821
4464
  if (change2.kind !== "tool.description.changed" && change2.kind !== "server.instructions.changed") return head;
3822
4465
  const before = typeof change2.before === "string" ? `
3823
4466
  ${red(`- ${truncate(change2.before, 220)}`)}` : "";
@@ -3838,7 +4481,8 @@ async function runReview(options) {
3838
4481
  * run would re-pin whatever had been published since, with nothing to compare it against.
3839
4482
  */
3840
4483
  previous: committed,
3841
- provenance: options.provenance
4484
+ provenance: options.provenance,
4485
+ userConfigs: options.userConfigs
3842
4486
  });
3843
4487
  const changes = diffLockfiles(committed, result.lock);
3844
4488
  if (changes.length === 0) {
@@ -3869,7 +4513,7 @@ async function runReview(options) {
3869
4513
  const context = describeSurface(result.lock.subjects[serverName], committed.subjects[serverName]);
3870
4514
  process.stdout.write(
3871
4515
  `
3872
- ${bold(serverName)}
4516
+ ${bold(visibleControls(serverName))}
3873
4517
  ${serverChanges.map(describe).join("\n")}
3874
4518
  ${context.length > 0 ? `${context.join("\n")}
3875
4519
  ` : ""}`
@@ -3926,6 +4570,7 @@ ${bold("Options")}
3926
4570
  --timeout <ms> per-server timeout (default: ${DEFAULT_TIMEOUT_MS2})
3927
4571
  --allow-unreachable a server that cannot be reached warns instead of failing
3928
4572
  --no-provenance do not look up what each stdio server runs (air-gapped runs)
4573
+ --user-configs also pin servers from your own configs (~/.claude.json, Claude Desktop, ...)
3929
4574
  --json machine-readable output (check)
3930
4575
  --sarif SARIF 2.1.0 output (check)
3931
4576
  --sarif-steering also emit steering passages as SARIF notes (off: an alert is a gate)
@@ -3956,6 +4601,7 @@ async function main() {
3956
4601
  timeout: { type: "string" },
3957
4602
  "allow-unreachable": { type: "boolean", default: false },
3958
4603
  "no-provenance": { type: "boolean", default: false },
4604
+ "user-configs": { type: "boolean", default: false },
3959
4605
  json: { type: "boolean", default: false },
3960
4606
  sarif: { type: "boolean", default: false },
3961
4607
  "sarif-steering": { type: "boolean", default: false },
@@ -3992,17 +4638,18 @@ async function main() {
3992
4638
  `);
3993
4639
  return EXIT_INCOMPLETE;
3994
4640
  }
3995
- const projectRoot = resolve4(values.cwd ?? process.cwd());
4641
+ const projectRoot = resolve5(values.cwd ?? process.cwd());
3996
4642
  const options = {
3997
4643
  projectRoot,
3998
- lockPath: resolve4(projectRoot, values.lock ?? DEFAULT_LOCK_FILENAME),
4644
+ lockPath: resolve5(projectRoot, values.lock ?? DEFAULT_LOCK_FILENAME),
3999
4645
  configFiles: values.config ?? [],
4000
4646
  timeoutMs,
4001
4647
  allowUnreachable: values["allow-unreachable"],
4002
4648
  format: values.sarif ? "sarif" : values.json ? "json" : "human",
4003
4649
  sarifSteering: values["sarif-steering"] === true,
4004
4650
  comment: values.comment,
4005
- provenance: values["no-provenance"] !== true
4651
+ provenance: values["no-provenance"] !== true,
4652
+ userConfigs: values["user-configs"] === true
4006
4653
  };
4007
4654
  switch (command) {
4008
4655
  case "init":
@@ -4026,9 +4673,9 @@ ${dim("Run `nulladrift --help`.")}
4026
4673
  return EXIT_INCOMPLETE;
4027
4674
  }
4028
4675
  }
4029
- main().then((code) => {
4030
- process.exitCode = code;
4031
- setTimeout(() => process.exit(code), 2e3).unref();
4676
+ main().then((code2) => {
4677
+ process.exitCode = code2;
4678
+ setTimeout(() => process.exit(code2), 2e3).unref();
4032
4679
  }).catch((error) => {
4033
4680
  const message = error instanceof LockfileError ? error.message : error.stack ?? String(error);
4034
4681
  process.stderr.write(`${red("nulladrift failed:")} ${message}