nulladrift 0.1.0 → 0.1.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
@@ -270,6 +270,16 @@ async function readJsonIfPresent(path) {
270
270
  return { present: true, ok: false, reason: `not valid JSON: ${error.message}` };
271
271
  }
272
272
  }
273
+ function anchorCwd(server2, projectRoot) {
274
+ const { transport: transport2 } = server2;
275
+ if (transport2.type !== "stdio" || transport2.cwd === void 0 || isAbsolute(transport2.cwd)) return server2;
276
+ return { ...server2, transport: { ...transport2, cwd: resolve2(projectRoot, transport2.cwd) } };
277
+ }
278
+ function describeSearch(searched, filesRead) {
279
+ const read = new Set(filesRead);
280
+ const lines = searched.map((path) => ` ${(read.has(path) ? "read" : "absent").padEnd(6)} ${path}`);
281
+ return lines.join("\n");
282
+ }
273
283
  async function discoverServers(projectRoot, extraFiles = []) {
274
284
  const context = { workspaceFolder: projectRoot, env: process.env };
275
285
  const files = [
@@ -301,7 +311,7 @@ async function discoverServers(projectRoot, extraFiles = []) {
301
311
  }
302
312
  const parsed = file.client === "claude-code" && file.scope === "user" ? await parseClaudeJson(raw, projectRoot, source, context) : await parseServerMap(raw, mapKey, { ...source, scope: file.scope }, context);
303
313
  skipped.push(...parsed.skipped);
304
- for (const server2 of parsed.servers) {
314
+ for (const server2 of parsed.servers.map((entry) => anchorCwd(entry, projectRoot))) {
305
315
  const existing = byName2.get(server2.name);
306
316
  if (existing) {
307
317
  shadowed.push({ name: server2.name, keptFrom: existing.from, alsoIn: source.file });
@@ -314,6 +324,7 @@ async function discoverServers(projectRoot, extraFiles = []) {
314
324
  servers: [...byName2.values()].map((entry) => entry.server).sort((a, b) => a.name.localeCompare(b.name)),
315
325
  skipped,
316
326
  filesRead,
327
+ searched: files.map((file) => file.path),
317
328
  shadowed,
318
329
  problems
319
330
  };
@@ -649,7 +660,7 @@ import { dirname, join as join2 } from "path";
649
660
  import { ClientCredentialsProvider, UnauthorizedError } from "@modelcontextprotocol/client";
650
661
 
651
662
  // src/lib/version.ts
652
- var VERSION = "0.1.0";
663
+ var VERSION = "0.1.2";
653
664
  var USER_AGENT = `nulladrift/${VERSION}`;
654
665
 
655
666
  // src/mcp/oauth.ts
@@ -820,6 +831,17 @@ var UnreachableServerError = class extends Error {
820
831
  serverName;
821
832
  cause;
822
833
  };
834
+ function authFailureKind(error) {
835
+ if (!isAuthFailure(error)) return void 0;
836
+ const text = `${error instanceof Error ? error.message : String(error)}`.toLowerCase();
837
+ const cause = error instanceof UnreachableServerError && error.cause instanceof Error ? error.cause.message.toLowerCase() : "";
838
+ const both = `${text} ${cause}`;
839
+ const scoped = [error, error instanceof UnreachableServerError ? error.cause : void 0].some(
840
+ (candidate) => candidate instanceof Error && candidate.name === "InsufficientScopeError"
841
+ );
842
+ if (scoped || /\b403\b|forbidden|insufficient[_ ]scope/.test(both)) return "forbidden";
843
+ return "auth";
844
+ }
823
845
  function isAuthFailure(error) {
824
846
  if (error instanceof UnauthorizedError2) return true;
825
847
  if (error instanceof Error && error.name === "InteractiveAuthRequiredError") return true;
@@ -830,7 +852,9 @@ function isAuthFailure(error) {
830
852
  const name = candidate instanceof Error ? candidate.name : "";
831
853
  if (name === "RegistrationRejectedError" || name === "InsufficientScopeError" || name === "OAuthClientFlowError") return true;
832
854
  }
833
- const text = `${error instanceof Error ? error.message : String(error)}`.toLowerCase();
855
+ const outer = `${error instanceof Error ? error.message : String(error)}`;
856
+ const inner = error instanceof UnreachableServerError && error.cause instanceof Error ? error.cause.message : "";
857
+ const text = `${outer} ${inner}`.toLowerCase();
834
858
  return /\b(401|403)\b|unauthorized|forbidden|invalid or missing.*token|authentication required|invalid_client|dynamic client registration/.test(text);
835
859
  }
836
860
 
@@ -860,6 +884,12 @@ function buildTransport(server2, captureStderr = () => {
860
884
  if (transport2.type === "sse") return new SSEClientTransport(url, { requestInit: { headers }, authProvider });
861
885
  return new StreamableHTTPClientTransport(url, { requestInit: { headers }, authProvider });
862
886
  }
887
+ function diagnosticLines(stderr, limit = 3) {
888
+ const lines = stderr.split("\n").map((line) => line.trimEnd()).filter((line) => line.trim().length > 0).filter((line) => !/^\s*(at\s|\^+$|[}\])]+$|Node\.js v[\d.]+$)/.test(line));
889
+ const named = lines.filter((line) => /\b(error|exception|cannot|failed|refused|denied|not found|enoent|eacces)\b/i.test(line));
890
+ const chosen = named.length > 0 ? named : lines;
891
+ return chosen.slice(0, limit).map((line) => line.trim());
892
+ }
863
893
  async function connect(server2, timeoutMs = DEFAULT_TIMEOUT_MS, options = {}) {
864
894
  let stderrBuffer = "";
865
895
  const captureStderr = (chunk) => {
@@ -891,7 +921,7 @@ async function connect(server2, timeoutMs = DEFAULT_TIMEOUT_MS, options = {}) {
891
921
  throw new UnreachableServerError(
892
922
  server2.name,
893
923
  `${error.message}${detail ? `
894
- server stderr: ${detail.split("\n").slice(-3).join("\n ")}` : ""}`,
924
+ server stderr: ${diagnosticLines(detail).join("\n ")}` : ""}`,
895
925
  error
896
926
  );
897
927
  }
@@ -987,7 +1017,7 @@ async function captureAll(options) {
987
1017
  } catch (error) {
988
1018
  options.onServerDone?.(server2.name, "failed");
989
1019
  const reason = error instanceof UnreachableServerError ? error.message : error.message;
990
- const kind = isAuthFailure(error) ? "auth" : "unreachable";
1020
+ const kind = authFailureKind(error) ?? "unreachable";
991
1021
  return { name: server2.name, failure: { server: server2.name, reason, kind } };
992
1022
  }
993
1023
  });
@@ -1424,6 +1454,43 @@ function diffLockfiles(before, after) {
1424
1454
  return sortChanges(changes);
1425
1455
  }
1426
1456
 
1457
+ // ../core/src/lock/reseal.ts
1458
+ function sealMember(member) {
1459
+ const { digest: _discarded, ...body } = member;
1460
+ return { ...body, digest: digest(toJson(body)) };
1461
+ }
1462
+ function reseal(entry) {
1463
+ switch (entry.kind) {
1464
+ case "mcp-server":
1465
+ return resealMcpServer(entry);
1466
+ }
1467
+ }
1468
+ function resealMcpServer(entry) {
1469
+ const tools = (entry.tools ?? []).map((tool2) => sealMember(tool2));
1470
+ const resources = (entry.resources ?? []).map((resource2) => sealMember(resource2));
1471
+ const resourceTemplates = (entry.resourceTemplates ?? []).map((template) => sealMember(template));
1472
+ const prompts = (entry.prompts ?? []).map((prompt2) => sealMember(prompt2));
1473
+ const covered = {
1474
+ transport: entry.transport,
1475
+ protocol: entry.protocol,
1476
+ serverInfo: entry.serverInfo,
1477
+ capabilities: entry.capabilities,
1478
+ instructions: entry.instructions,
1479
+ tools: tools.map((tool2) => tool2.digest),
1480
+ resources: resources.map((resource2) => resource2.digest),
1481
+ resourceTemplates: resourceTemplates.map((template) => template.digest),
1482
+ prompts: prompts.map((prompt2) => prompt2.digest)
1483
+ };
1484
+ return {
1485
+ ...entry,
1486
+ tools: tools.length > 0 ? tools : void 0,
1487
+ resources: resources.length > 0 ? resources : void 0,
1488
+ resourceTemplates: resourceTemplates.length > 0 ? resourceTemplates : void 0,
1489
+ prompts: prompts.length > 0 ? prompts : void 0,
1490
+ digest: digest(toJson(covered))
1491
+ };
1492
+ }
1493
+
1427
1494
  // src/lock/io.ts
1428
1495
  import { readFile as readFile4, writeFile as writeFile2 } from "fs/promises";
1429
1496
 
@@ -1690,10 +1757,21 @@ async function readLockfile(path) {
1690
1757
  if (code === "ENOENT") throw new LockfileError(`no lockfile at ${path}. Run \`nulladrift init\` first.`);
1691
1758
  throw new LockfileError(`could not read ${path}: ${error.message}`);
1692
1759
  }
1693
- return parseLockfile(text, path);
1760
+ const lock = parseLockfile(text, path);
1761
+ return {
1762
+ ...lock,
1763
+ subjects: Object.fromEntries(Object.entries(lock.subjects).map(([name, subject]) => [name, reseal(subject)]))
1764
+ };
1694
1765
  }
1695
1766
  async function writeLockfile(path, lock) {
1696
- await writeFile2(path, serializeLockfile(lock), "utf8");
1767
+ try {
1768
+ await writeFile2(path, serializeLockfile(lock), "utf8");
1769
+ } catch (error) {
1770
+ const code = error.code;
1771
+ if (code === "ENOENT") throw new LockfileError(`cannot write ${path}: the directory does not exist. Note that --lock is resolved against --cwd.`);
1772
+ if (code === "EACCES" || code === "EPERM") throw new LockfileError(`cannot write ${path}: permission denied.`);
1773
+ throw new LockfileError(`cannot write ${path}: ${error.message}`);
1774
+ }
1697
1775
  }
1698
1776
 
1699
1777
  // src/lib/exit.ts
@@ -1729,7 +1807,9 @@ function renderChange(change2) {
1729
1807
  function renderHumanReport(report) {
1730
1808
  const lines = [];
1731
1809
  if (report.changes.length > 0) {
1732
- lines.push("", bold(`Drift in ${new Set(report.changes.map((change2) => change2.server)).size} of ${report.serversChecked} server(s):`), "");
1810
+ const drifted = new Set(report.changes.map((change2) => change2.server)).size;
1811
+ const heading = report.serversChecked === 0 ? `Drift in ${drifted} server(s), none of which is still configured:` : `Drift in ${drifted} of ${report.serversChecked} server(s):`;
1812
+ lines.push("", bold(heading), "");
1733
1813
  for (const change2 of report.changes) lines.push(...renderChange(change2), "");
1734
1814
  const quiet = serversThatShippedNothing(report.changes);
1735
1815
  if (quiet.length > 0) {
@@ -1743,7 +1823,7 @@ function renderHumanReport(report) {
1743
1823
  if (report.unreachable.length > 0) {
1744
1824
  lines.push(bold(`Could not audit ${report.unreachable.length} server(s):`), "");
1745
1825
  for (const failure of report.unreachable) {
1746
- const label = failure.kind === "auth" ? yellow("needs creds") : red("unreachable");
1826
+ const label = failure.kind === "auth" ? yellow("needs creds") : failure.kind === "forbidden" ? yellow("not permitted") : red("unreachable");
1747
1827
  lines.push(` ${label} ${bold(failure.server)}`, ` ${failure.reason}`, "");
1748
1828
  }
1749
1829
  }
@@ -1762,9 +1842,17 @@ function renderHumanReport(report) {
1762
1842
  lines.push(dim("A server that cannot be checked fails the audit. Use --allow-unreachable to downgrade that to a warning."));
1763
1843
  if (report.unreachable.some((failure) => failure.kind === "auth")) {
1764
1844
  lines.push(
1765
- dim("`needs creds` means the server refused this client, not that it is down. The tool list a"),
1766
- dim("server shows may depend on who is asking, so auditing without them would pin the wrong"),
1767
- dim("surface. Run `nulladrift login <server>` once, or set oauth.clientId/clientSecret for CI.")
1845
+ dim("`needs creds` means the server would not accept this client, not that it is down. The tool"),
1846
+ dim("list a server shows may depend on who is asking, so auditing without credentials would pin"),
1847
+ dim("the wrong surface. Run `nulladrift login <server>` once, or set oauth.clientId/clientSecret"),
1848
+ dim("for CI.")
1849
+ );
1850
+ }
1851
+ if (report.unreachable.some((failure) => failure.kind === "forbidden")) {
1852
+ lines.push(
1853
+ dim("`not permitted` means your credentials were accepted and refused. Running `nulladrift login`"),
1854
+ dim("again will not change that. Check the server URL for an organization or project you do not"),
1855
+ dim("belong to, and whether the grant covers that resource.")
1768
1856
  );
1769
1857
  }
1770
1858
  }
@@ -1882,6 +1970,11 @@ function renderSarifReport(report) {
1882
1970
  }
1883
1971
 
1884
1972
  // src/report/markdown.ts
1973
+ var AUDIT_FAILURE_LABEL = {
1974
+ auth: "refused the audit",
1975
+ forbidden: "accepted the credentials and refused",
1976
+ unreachable: "unreachable"
1977
+ };
1885
1978
  var MARK2 = { high: "\u{1F534}", medium: "\u{1F7E0}", low: "\u26AA" };
1886
1979
  function cell(text) {
1887
1980
  return text.replace(/\|/g, "\\|").replace(/`/g, "\\`").replace(/\r?\n/g, " ").trim();
@@ -1918,7 +2011,7 @@ function renderMarkdownReport(report, options = {}) {
1918
2011
  `<details><summary>${report.unreachable.length} server${report.unreachable.length === 1 ? "" : "s"} could not be read</summary>`,
1919
2012
  "",
1920
2013
  ...report.unreachable.map(
1921
- (failure) => `- \`${cell(failure.server)}\` \xB7 ${failure.kind === "auth" ? "refused the audit" : "unreachable"}: ${cell(failure.reason)}`
2014
+ (failure) => `- \`${cell(failure.server)}\` \xB7 ${AUDIT_FAILURE_LABEL[failure.kind]}: ${cell(failure.reason)}`
1922
2015
  ),
1923
2016
  "",
1924
2017
  "</details>",
@@ -2256,14 +2349,20 @@ async function runInit(options) {
2256
2349
  const names = Object.keys(result.lock.subjects);
2257
2350
  if (names.length === 0 && result.unreachable.length === 0) {
2258
2351
  process.stderr.write(
2259
- `No MCP servers found.
2260
- ${dim(`Looked in: ${result.discovery.filesRead.length > 0 ? result.discovery.filesRead.join(", ") : "no client config files exist for this project"}`)}
2261
- `
2352
+ [
2353
+ "No MCP servers found.",
2354
+ dim("Looked in:"),
2355
+ dim(describeSearch(result.discovery.searched, result.discovery.filesRead)),
2356
+ dim("Nothing was written. `nulladrift check` needs a lockfile, so it will fail until a"),
2357
+ dim("config declaring at least one server exists."),
2358
+ ""
2359
+ ].join("\n")
2262
2360
  );
2263
2361
  return EXIT_CLEAN;
2264
2362
  }
2265
- await writeLockfile(options.lockPath, result.lock);
2266
- const lines = ["", bold(`Pinned ${names.length} server(s) to ${options.lockPath}:`), ""];
2363
+ const pinnedSomething = names.length > 0;
2364
+ if (pinnedSomething) await writeLockfile(options.lockPath, result.lock);
2365
+ const lines = pinnedSomething ? ["", bold(`Pinned ${names.length} server(s) to ${options.lockPath}:`), ""] : ["", bold("Pinned nothing: no server answered."), ""];
2267
2366
  for (const name of names) {
2268
2367
  const entry = result.lock.subjects[name];
2269
2368
  const counts = [
@@ -2282,7 +2381,11 @@ ${dim(`Looked in: ${result.discovery.filesRead.length > 0 ? result.discovery.fil
2282
2381
  for (const shadow of result.discovery.shadowed) {
2283
2382
  lines.push(dim(` note: "${shadow.name}" is defined in both ${shadow.keptFrom} and ${shadow.alsoIn}; kept the first.`));
2284
2383
  }
2285
- lines.push("", dim("Commit mcp.lock. `nulladrift check` in CI will fail if any of this changes."), "");
2384
+ lines.push(
2385
+ "",
2386
+ pinnedSomething ? dim("Commit mcp.lock. `nulladrift check` in CI will fail if any of this changes.") : dim("No lockfile was written. Fix the server(s) above and run `nulladrift init` again."),
2387
+ ""
2388
+ );
2286
2389
  process.stdout.write(lines.join("\n"));
2287
2390
  await maybeOfferTelemetry();
2288
2391
  if (result.unreachable.length > 0 && !options.allowUnreachable) return EXIT_INCOMPLETE;
@@ -2472,11 +2575,12 @@ async function runPush(options) {
2472
2575
  const apiUrl = (options.apiUrl ?? process.env["NULLADRIFT_API_URL"] ?? "").replace(/\/+$/, "");
2473
2576
  const token = options.token ?? process.env["NULLADRIFT_TOKEN"] ?? "";
2474
2577
  if (!apiUrl || !token) {
2578
+ const missing = !apiUrl && !token ? "a control plane to push to, and a token" : !apiUrl ? "a control plane to push to" : "a collector token";
2475
2579
  process.stderr.write(
2476
2580
  [
2477
- red("push needs a control plane to push to."),
2478
- dim(" --api <url> or NULLADRIFT_API_URL"),
2479
- dim(" --token <token> or NULLADRIFT_TOKEN"),
2581
+ red(`push needs ${missing}.`),
2582
+ ...!apiUrl ? [dim(" --api <url> or NULLADRIFT_API_URL")] : [],
2583
+ ...!token ? [dim(" --token <token> or NULLADRIFT_TOKEN")] : [],
2480
2584
  ""
2481
2585
  ].join("\n")
2482
2586
  );
@@ -2487,6 +2591,13 @@ async function runPush(options) {
2487
2591
  configFiles: options.configFiles,
2488
2592
  timeoutMs: options.timeoutMs
2489
2593
  });
2594
+ if (Object.keys(result.lock.subjects).length === 0 && result.unreachable.length === 0) {
2595
+ const looked = result.discovery.filesRead.length > 0 ? result.discovery.filesRead.join(", ") : "no client config files exist for this project";
2596
+ process.stderr.write(`No MCP servers found, so there is nothing to push.
2597
+ ${dim(`Looked in: ${looked}`)}
2598
+ `);
2599
+ return EXIT_INCOMPLETE;
2600
+ }
2490
2601
  const servers = Object.entries(result.lock.subjects).map(([name, entry]) => ({
2491
2602
  name,
2492
2603
  transport: entry.transport.type,