narcx 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,2644 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { spawn as spawn2, execFileSync as execFileSync2 } from "child_process";
5
+ import * as fs5 from "fs";
6
+ import * as os3 from "os";
7
+ import * as path7 from "path";
8
+ import { fileURLToPath as fileURLToPath2 } from "url";
9
+ import pc3 from "picocolors";
10
+
11
+ // package.json
12
+ var package_default = {
13
+ name: "narcx",
14
+ version: "0.2.0",
15
+ description: "Catch any CLI tool, AI coding harness, or MCP server red-handed when it phones home or reads your dotfiles.",
16
+ license: "MIT",
17
+ author: "arrrshia",
18
+ repository: {
19
+ type: "git",
20
+ url: "git+https://github.com/arrrshia/narcx.git"
21
+ },
22
+ homepage: "https://github.com/arrrshia/narcx#readme",
23
+ bugs: {
24
+ url: "https://github.com/arrrshia/narcx/issues"
25
+ },
26
+ type: "module",
27
+ bin: {
28
+ narc: "dist/cli.js"
29
+ },
30
+ files: [
31
+ "dist",
32
+ "assets/fonts",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ engines: {
37
+ node: ">=18"
38
+ },
39
+ scripts: {
40
+ build: "rm -rf dist && tsup",
41
+ dev: "tsup --watch",
42
+ typecheck: "tsc --noEmit",
43
+ test: "vitest run",
44
+ demo: "node dist/cli.js --demo --card ./demo-report.png",
45
+ prepublishOnly: "npm run typecheck && npm run build && npm test"
46
+ },
47
+ keywords: [
48
+ "privacy",
49
+ "telemetry",
50
+ "audit",
51
+ "cli",
52
+ "mcp",
53
+ "ai",
54
+ "security",
55
+ "proxy"
56
+ ],
57
+ dependencies: {
58
+ "@resvg/resvg-js": "^2.6.2",
59
+ picocolors: "^1.1.1"
60
+ },
61
+ devDependencies: {
62
+ "@types/node": "^20.17.0",
63
+ tsup: "^8.3.5",
64
+ typescript: "^5.7.2",
65
+ vitest: "^2.1.8"
66
+ }
67
+ };
68
+
69
+ // src/core/collector.ts
70
+ import { EventEmitter } from "events";
71
+
72
+ // src/core/classify.ts
73
+ var LLM_API_HOSTS = [
74
+ "api.anthropic.com",
75
+ "mcp-proxy.anthropic.com",
76
+ "api.openai.com",
77
+ "chatgpt.com",
78
+ "generativelanguage.googleapis.com",
79
+ "cloudcode-pa.googleapis.com",
80
+ "openrouter.ai",
81
+ "api.githubcopilot.com",
82
+ "copilot-proxy.githubusercontent.com",
83
+ "api.x.ai",
84
+ "api.mistral.ai",
85
+ "api.deepseek.com",
86
+ "api.groq.com",
87
+ "api.cohere.com",
88
+ "api.together.xyz",
89
+ "api.fireworks.ai"
90
+ ];
91
+ var AUTH_HOSTS = [
92
+ "oauth2.googleapis.com",
93
+ "accounts.google.com",
94
+ "auth.openai.com",
95
+ "auth0.openai.com",
96
+ "console.anthropic.com",
97
+ "login.microsoftonline.com",
98
+ "github.com/login"
99
+ ];
100
+ var TELEMETRY_DOMAINS = [
101
+ "posthog.com",
102
+ "sentry.io",
103
+ "segment.io",
104
+ "segment.com",
105
+ "mixpanel.com",
106
+ "amplitude.com",
107
+ "datadoghq.com",
108
+ // vendor-specific metrics / experiment endpoints
109
+ "ab.chatgpt.com",
110
+ "play.googleapis.com",
111
+ "statsigapi.net",
112
+ "featuregates.org",
113
+ "firebaselogging-pa.googleapis.com",
114
+ // observability / error-reporting / product-analytics vendors
115
+ "grafana.net",
116
+ "honeycomb.io",
117
+ "newrelic.com",
118
+ "nr-data.net",
119
+ "bugsnag.com",
120
+ "rollbar.com",
121
+ "logrocket.com",
122
+ "fullstory.com",
123
+ "hotjar.com",
124
+ "crashlytics.com",
125
+ "raygun.io",
126
+ "loggly.com",
127
+ "sumologic.com",
128
+ "axiom.co",
129
+ "google-analytics.com",
130
+ "googletagmanager.com",
131
+ "app-measurement.com"
132
+ ];
133
+ var TELEMETRY_ENDPOINTS = [
134
+ { host: "www.googleapis.com", pathPrefix: "/log", note: "Google Clearcut logging" },
135
+ { host: "clients4.google.com", pathPrefix: "/log", note: "Google Clearcut logging" }
136
+ ];
137
+ var TELEMETRY_LABELS = [
138
+ "telemetry",
139
+ "ingest",
140
+ "analytics",
141
+ "metrics",
142
+ "statsig",
143
+ "launchdarkly",
144
+ "otlp",
145
+ "otel"
146
+ ];
147
+ var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "0.0.0.0", "::", "[::1]"]);
148
+ function normalizeHost(host) {
149
+ let h = host.trim().toLowerCase();
150
+ if (h.startsWith("[") && h.endsWith("]")) h = h.slice(1, -1);
151
+ if (h.endsWith(".")) h = h.slice(0, -1);
152
+ return h;
153
+ }
154
+ function isLoopback(host) {
155
+ const h = normalizeHost(host);
156
+ if (LOOPBACK.has(h)) return true;
157
+ if (h.startsWith("127.")) return true;
158
+ if (h.endsWith(".localhost")) return true;
159
+ return false;
160
+ }
161
+ function isIpAddress(host) {
162
+ const h = normalizeHost(host);
163
+ if (/^\d{1,3}(\.\d{1,3}){3}$/.test(h)) return true;
164
+ if (h.includes(":") && /^[0-9a-f:.]+$/i.test(h)) return true;
165
+ return false;
166
+ }
167
+ var matchesDomain = (h, list) => list.some((d) => h === d || h.endsWith("." + d));
168
+ function classifyHost(host) {
169
+ const h = normalizeHost(host);
170
+ if (!h) return "UNKNOWN";
171
+ if (isLoopback(h)) return "LLM_API";
172
+ if (matchesDomain(h, TELEMETRY_DOMAINS)) return "TELEMETRY";
173
+ if (h.split(".").some((l) => TELEMETRY_LABELS.includes(l))) return "TELEMETRY";
174
+ if (matchesDomain(h, AUTH_HOSTS)) return "AUTH";
175
+ if (matchesDomain(h, LLM_API_HOSTS)) return "LLM_API";
176
+ return "UNKNOWN";
177
+ }
178
+ function classifyRequest(host, path8) {
179
+ const base = classifyHost(host);
180
+ if (base === "TELEMETRY" || !path8) return base;
181
+ const h = normalizeHost(host);
182
+ for (const e of TELEMETRY_ENDPOINTS) {
183
+ if (h === e.host && path8.startsWith(e.pathPrefix)) return "TELEMETRY";
184
+ }
185
+ return base;
186
+ }
187
+
188
+ // src/core/grade.ts
189
+ var PENALTY = {
190
+ TELEMETRY_HOST: 25,
191
+ SENSITIVE_FILE: 30,
192
+ UNKNOWN_HOST: 10
193
+ };
194
+ function gradeFromScore(score) {
195
+ if (score >= 100) return "A+";
196
+ if (score >= 90) return "A";
197
+ if (score >= 80) return "B";
198
+ if (score >= 65) return "C";
199
+ if (score >= 50) return "D";
200
+ return "F";
201
+ }
202
+ function computeScore(input) {
203
+ const deductions = [];
204
+ for (const f of input.sensitiveFiles) {
205
+ deductions.push({
206
+ reason: "sensitive-file",
207
+ points: -PENALTY.SENSITIVE_FILE,
208
+ detail: f
209
+ });
210
+ }
211
+ for (const h of input.telemetryHosts) {
212
+ deductions.push({ reason: "telemetry-host", points: -PENALTY.TELEMETRY_HOST, detail: h });
213
+ }
214
+ for (const h of input.unknownHosts) {
215
+ deductions.push({ reason: "unknown-host", points: -PENALTY.UNKNOWN_HOST, detail: h });
216
+ }
217
+ const total = deductions.reduce((acc, d) => acc + d.points, 0);
218
+ const score = Math.max(0, Math.min(100, 100 + total));
219
+ return { score, grade: gradeFromScore(score), deductions };
220
+ }
221
+
222
+ // src/core/watchlist.ts
223
+ import * as fs from "fs";
224
+ import * as os from "os";
225
+ import * as path from "path";
226
+ var WATCHLIST = [
227
+ { id: "claude", label: "Claude Code config", patterns: ["~/.claude.json", "~/.claude/**"] },
228
+ { id: "codex", label: "Codex config", patterns: ["~/.codex/**"] },
229
+ { id: "cursor", label: "Cursor config", patterns: ["~/.cursor/**"] },
230
+ { id: "gemini", label: "Gemini CLI auth", patterns: ["~/.gemini/**"] },
231
+ { id: "opencode", label: "OpenCode config", patterns: ["~/.config/opencode/**", "~/.local/share/opencode/**"] },
232
+ { id: "gh", label: "GitHub CLI auth", patterns: ["~/.config/gh/**"] },
233
+ { id: "ssh", label: "SSH keys", patterns: ["~/.ssh/**"] },
234
+ { id: "aws", label: "AWS credentials", patterns: ["~/.aws/**"] },
235
+ { id: "gitconfig", label: "Git config", patterns: ["~/.gitconfig", "~/.config/git/credentials"] },
236
+ { id: "npmrc", label: "npm auth", patterns: ["~/.npmrc", ".npmrc"] },
237
+ { id: "netrc", label: "netrc credentials", patterns: ["~/.netrc", "~/_netrc"] },
238
+ { id: "pypirc", label: "PyPI credentials", patterns: ["~/.pypirc"] },
239
+ { id: "env", label: "dotenv secrets", patterns: [".env", ".env.*"] },
240
+ { id: "gnupg", label: "GPG keyring", patterns: ["~/.gnupg/**"] },
241
+ { id: "docker", label: "Docker auth", patterns: ["~/.docker/config.json"] },
242
+ { id: "kube", label: "Kubernetes config", patterns: ["~/.kube/**"] },
243
+ { id: "gcloud", label: "gcloud credentials", patterns: ["~/.config/gcloud/**"] },
244
+ {
245
+ id: "keychain",
246
+ label: "macOS keychain (TLS trust store)",
247
+ patterns: ["~/Library/Keychains/**", "/Library/Keychains/**"],
248
+ // Every process that evaluates a TLS certificate chain through Security.framework opens
249
+ // these files; secrets inside are only reachable through securityd. Reported, not graded.
250
+ graded: false
251
+ },
252
+ {
253
+ id: "browser",
254
+ label: "Browser cookies/logins",
255
+ patterns: [
256
+ // macOS
257
+ "~/Library/Cookies/**",
258
+ "~/Library/Application Support/Google/Chrome/**/Cookies",
259
+ "~/Library/Application Support/Google/Chrome/**/Login Data",
260
+ "~/Library/Application Support/Chromium/**/Cookies",
261
+ "~/Library/Application Support/BraveSoftware/**/Cookies",
262
+ "~/Library/Application Support/Microsoft Edge/**/Cookies",
263
+ "~/Library/Application Support/Arc/**/Cookies",
264
+ "~/Library/Application Support/Firefox/Profiles/**/cookies.sqlite",
265
+ "~/Library/Application Support/Firefox/Profiles/**/logins.json",
266
+ "~/Library/Safari/Cookies.binarycookies",
267
+ // Linux
268
+ "~/.config/google-chrome/**/Cookies",
269
+ "~/.config/chromium/**/Cookies",
270
+ "~/.config/BraveSoftware/**/Cookies",
271
+ "~/.mozilla/firefox/**/cookies.sqlite",
272
+ "~/.mozilla/firefox/**/logins.json",
273
+ // Windows-ish paths seen through WSL/Git Bash
274
+ "~/AppData/Local/Google/Chrome/User Data/**/Cookies"
275
+ ]
276
+ }
277
+ ];
278
+ function escapeRe(s) {
279
+ return s.replace(/[.+^${}()|[\]\\]/g, "\\$&");
280
+ }
281
+ function globToRegExp(glob) {
282
+ let re = "";
283
+ for (let i = 0; i < glob.length; i++) {
284
+ const c = glob[i];
285
+ if (c === "/" && glob[i + 1] === "*" && glob[i + 2] === "*" && i + 3 === glob.length) {
286
+ re += "(?:/.*)?";
287
+ i += 2;
288
+ } else if (c === "*") {
289
+ if (glob[i + 1] === "*") {
290
+ const next = glob[i + 2];
291
+ if (next === "/") {
292
+ re += "(?:.*/)?";
293
+ i += 2;
294
+ } else {
295
+ re += ".*";
296
+ i += 1;
297
+ }
298
+ } else {
299
+ re += "[^/]*";
300
+ }
301
+ } else if (c === "?") {
302
+ re += "[^/]";
303
+ } else {
304
+ re += escapeRe(c);
305
+ }
306
+ }
307
+ return new RegExp("^" + re + "$");
308
+ }
309
+ var SensitiveMatcher = class {
310
+ home;
311
+ /** All spellings of the home dir (e.g. macOS `/var/...` vs `/private/var/...`). */
312
+ homes;
313
+ compiled;
314
+ constructor(home = os.homedir()) {
315
+ this.home = path.resolve(home);
316
+ const variants = /* @__PURE__ */ new Set([this.home]);
317
+ try {
318
+ variants.add(fs.realpathSync.native(this.home));
319
+ } catch {
320
+ }
321
+ this.homes = [...variants];
322
+ this.compiled = WATCHLIST.map((entry) => {
323
+ const anchored = [];
324
+ const basename4 = [];
325
+ for (const p of entry.patterns) {
326
+ if (p.startsWith("~/")) {
327
+ for (const h of this.homes) anchored.push(globToRegExp(path.join(h, p.slice(2))));
328
+ } else if (p.includes("/")) {
329
+ anchored.push(globToRegExp(p));
330
+ } else {
331
+ basename4.push(globToRegExp(p));
332
+ }
333
+ }
334
+ return { entry, anchored, basename: basename4 };
335
+ });
336
+ }
337
+ /** Normalize a path for matching: absolute, no trailing slash, expand ~. */
338
+ normalize(p) {
339
+ let s = p;
340
+ if (s.startsWith("~/")) s = path.join(this.home, s.slice(2));
341
+ s = path.resolve(s);
342
+ if (s.length > 1 && s.endsWith("/")) s = s.slice(0, -1);
343
+ return s;
344
+ }
345
+ match(filePath) {
346
+ const p = this.normalize(filePath);
347
+ const base = path.basename(p);
348
+ for (const c of this.compiled) {
349
+ for (const re of c.anchored) if (re.test(p)) return c.entry;
350
+ for (const re of c.basename) if (re.test(base)) return c.entry;
351
+ }
352
+ return null;
353
+ }
354
+ isSensitive(filePath) {
355
+ return this.match(filePath) !== null;
356
+ }
357
+ /** True if the path lives under the home dir and has a dot-segment (a dotfile/dotdir). */
358
+ /** The home-dir spelling this path lives under, or null. */
359
+ homeOf(p) {
360
+ for (const h of this.homes) if (p === h || p.startsWith(h + path.sep)) return h;
361
+ return null;
362
+ }
363
+ isDotfileUnderHome(filePath) {
364
+ const p = this.normalize(filePath);
365
+ const h = this.homeOf(p);
366
+ if (!h || p === h) return false;
367
+ if (p.includes("/node_modules/")) return false;
368
+ const rel = p.slice(h.length + 1);
369
+ return rel.split("/").some((seg) => seg.startsWith(".") && seg.length > 1);
370
+ }
371
+ /** Pretty-print with ~ for home. */
372
+ display(filePath) {
373
+ const p = this.normalize(filePath);
374
+ const h = this.homeOf(p);
375
+ if (!h) return p;
376
+ return p === h ? "~" : "~" + p.slice(h.length);
377
+ }
378
+ };
379
+ function ownNamespaces(command) {
380
+ const own = /* @__PURE__ */ new Set();
381
+ const tokens = [];
382
+ for (const c of command) {
383
+ const t = c.toLowerCase();
384
+ if (t.startsWith("-")) continue;
385
+ if (t.startsWith("@") || !t.includes("/")) tokens.push(t.replace(/@[^/]*$/, ""));
386
+ else tokens.push(path.basename(t).replace(/\.(c|m)?js$/, ""));
387
+ }
388
+ const bases = tokens;
389
+ const has = (re) => bases.some((b) => re.test(b));
390
+ if (has(/^(@anthropic-ai\/)?claude(-code)?$/)) own.add("claude");
391
+ if (has(/^(@openai\/)?codex$/)) own.add("codex");
392
+ if (has(/^cursor(-agent)?$/)) own.add("cursor");
393
+ if (has(/^(@google\/)?gemini(-cli)?$/)) own.add("gemini");
394
+ if (has(/^opencode(-ai)?$/)) own.add("opencode");
395
+ if (has(/^gh$/)) own.add("gh");
396
+ if (has(/^(npm|npx|pnpm|pnpx|yarn|bun|bunx|corepack)$/)) own.add("npmrc");
397
+ if (bases.includes("aws") || has(/^aws-/)) own.add("aws");
398
+ if (has(/^git(-[a-z0-9-]+)?$/)) {
399
+ own.add("gitconfig");
400
+ own.add("ssh");
401
+ own.add("netrc");
402
+ }
403
+ if (has(/^(curl|wget)$/)) own.add("netrc");
404
+ if (has(/^(ssh|scp|sftp|ssh-add|ssh-agent|rsync|mosh)$/)) own.add("ssh");
405
+ if (has(/^(pip|pip3|twine|poetry|uv|pipx|hatch|flit)$/)) own.add("pypirc");
406
+ if (bases.includes("docker") || bases.includes("docker-compose")) own.add("docker");
407
+ if (has(/^(kubectl|helm|k9s|kustomize|minikube|kind)$/)) own.add("kube");
408
+ if (bases.includes("gcloud") || bases.includes("gsutil")) own.add("gcloud");
409
+ if (has(/^(gpg|gpg2|gpg-agent)$/)) own.add("gnupg");
410
+ if (has(CODING_AGENT)) own.add("gitconfig");
411
+ return own;
412
+ }
413
+ var CODING_AGENT = /^((@anthropic-ai\/)?claude(-code)?|(@openai\/)?codex|cursor(-agent)?|(@google\/)?gemini(-cli)?|opencode(-ai)?|t3(code)?|aider|(@github\/)?copilot(-cli)?|amp|goose|cline|droid|jules)$/;
414
+
415
+ // src/core/collector.ts
416
+ var SOURCE_RANK = {
417
+ preload: 5,
418
+ proxy: 4,
419
+ strace: 3,
420
+ fs_usage: 3,
421
+ lsof: 1,
422
+ narc: 0
423
+ };
424
+ var Collector = class extends EventEmitter {
425
+ matcher;
426
+ ownNamespaces;
427
+ events = [];
428
+ files = /* @__PURE__ */ new Map();
429
+ hosts = /* @__PURE__ */ new Map();
430
+ netById = /* @__PURE__ */ new Map();
431
+ ipToHost = /* @__PURE__ */ new Map();
432
+ ignoreLocalPorts;
433
+ launcher = null;
434
+ resolveProc = null;
435
+ ownCache = /* @__PURE__ */ new Map();
436
+ seq = 0;
437
+ constructor(opts) {
438
+ super();
439
+ this.matcher = opts.matcher;
440
+ this.ownNamespaces = opts.ownNamespaces;
441
+ this.ignoreLocalPorts = new Set(opts.ignoreLocalPorts ?? []);
442
+ }
443
+ ignorePort(port) {
444
+ this.ignoreLocalPorts.add(port);
445
+ }
446
+ /**
447
+ * Mark the direct child as a package runner (npx, pnpm dlx, bunx, …). Its own
448
+ * reads and requests (registry lookups, ~/.npmrc, ~/.gitconfig) are reported
449
+ * but excluded from the grade so the tool is judged on its own behaviour.
450
+ */
451
+ setLauncher(pid, name) {
452
+ this.launcher = { pid, name };
453
+ }
454
+ getLauncher() {
455
+ return this.launcher;
456
+ }
457
+ /** Lets the collector turn pids from the hook into process names at summary time. */
458
+ setProcessResolver(fn) {
459
+ this.resolveProc = fn;
460
+ }
461
+ ownOf(proc) {
462
+ let v = this.ownCache.get(proc);
463
+ if (!v) {
464
+ v = ownNamespaces([proc]);
465
+ this.ownCache.set(proc, v);
466
+ }
467
+ return v;
468
+ }
469
+ isLauncherPid(pid) {
470
+ return this.launcher !== null && pid !== void 0 && pid === this.launcher.pid;
471
+ }
472
+ launcherOnly(pids) {
473
+ if (!this.launcher || pids.size === 0) return false;
474
+ for (const p of pids) if (p !== this.launcher.pid) return false;
475
+ return true;
476
+ }
477
+ nextId(prefix) {
478
+ return `${prefix}-${++this.seq}`;
479
+ }
480
+ // ---- files ---------------------------------------------------------------
481
+ addFile(input) {
482
+ const norm = this.matcher.normalize(input.path);
483
+ const watch = this.matcher.match(norm);
484
+ const dot = watch ? true : this.matcher.isDotfileUnderHome(norm);
485
+ if (!watch && !dot) return null;
486
+ const ev = {
487
+ kind: "file",
488
+ id: input.id ?? this.nextId("f"),
489
+ ts: input.ts ?? Date.now(),
490
+ source: input.source,
491
+ pid: input.pid,
492
+ path: norm,
493
+ op: input.op,
494
+ sensitive: watch ? watch.id : null,
495
+ exists: input.exists,
496
+ proc: Array.isArray(input.proc) ? input.proc[0] : input.proc
497
+ };
498
+ this.events.push(ev);
499
+ let rec = this.files.get(norm);
500
+ const first = !rec;
501
+ if (!rec) {
502
+ rec = { path: norm, ops: /* @__PURE__ */ new Map(), sources: /* @__PURE__ */ new Set(), pids: /* @__PURE__ */ new Set(), watch, exists: false, procs: /* @__PURE__ */ new Set() };
503
+ this.files.set(norm, rec);
504
+ }
505
+ rec.ops.set(ev.op, (rec.ops.get(ev.op) ?? 0) + 1);
506
+ rec.sources.add(ev.source);
507
+ if (ev.pid !== void 0) rec.pids.add(ev.pid);
508
+ for (const pr of Array.isArray(input.proc) ? input.proc : input.proc ? [input.proc] : []) rec.procs.add(pr);
509
+ if (input.exists !== false) rec.exists = true;
510
+ if (first && input.exists === false) return ev;
511
+ if (first) {
512
+ const display = this.matcher.display(norm);
513
+ const launcher = this.isLauncherPid(ev.pid);
514
+ if (watch) {
515
+ const alert = { level: "high", kind: "file", event: ev, watch, display, launcher };
516
+ this.emit("alert", alert);
517
+ } else {
518
+ const alert = { level: "info", kind: "file", event: ev, display, launcher };
519
+ this.emit("alert", alert);
520
+ }
521
+ }
522
+ return ev;
523
+ }
524
+ // ---- dns -----------------------------------------------------------------
525
+ addDns(input) {
526
+ const host = normalizeHost(input.host);
527
+ if (!host) return;
528
+ for (const a of input.addresses) {
529
+ if (a && !this.ipToHost.has(a)) this.ipToHost.set(a, host);
530
+ }
531
+ const ev = {
532
+ kind: "dns",
533
+ id: input.id ?? this.nextId("d"),
534
+ ts: Date.now(),
535
+ source: input.source,
536
+ pid: input.pid,
537
+ host,
538
+ addresses: input.addresses
539
+ };
540
+ this.events.push(ev);
541
+ }
542
+ resolveIp(ip) {
543
+ return this.ipToHost.get(ip);
544
+ }
545
+ // ---- net -----------------------------------------------------------------
546
+ addNet(input) {
547
+ let host = normalizeHost(input.host);
548
+ if (!host) return null;
549
+ if (isLoopback(host)) return null;
550
+ if (isIpAddress(host)) {
551
+ const mapped = this.ipToHost.get(host);
552
+ if (mapped) host = mapped;
553
+ }
554
+ const category = classifyRequest(host, input.path);
555
+ const ev = {
556
+ kind: "net",
557
+ id: input.id ?? this.nextId("n"),
558
+ ts: input.ts ?? Date.now(),
559
+ source: input.source,
560
+ pid: input.pid,
561
+ host,
562
+ port: input.port,
563
+ protocol: input.protocol,
564
+ method: input.method,
565
+ path: input.path,
566
+ url: input.url,
567
+ bytesOut: input.bytesOut ?? 0,
568
+ bytesIn: input.bytesIn ?? 0,
569
+ category
570
+ };
571
+ this.events.push(ev);
572
+ this.netById.set(ev.id, ev);
573
+ let rec = this.hosts.get(host);
574
+ const first = !rec;
575
+ let upgraded = false;
576
+ if (!rec) {
577
+ rec = { host, category, firstSeen: ev.ts, perSource: /* @__PURE__ */ new Map(), pids: /* @__PURE__ */ new Set() };
578
+ this.hosts.set(host, rec);
579
+ } else if (rec.category !== "TELEMETRY" && category === "TELEMETRY") {
580
+ rec.category = "TELEMETRY";
581
+ upgraded = true;
582
+ }
583
+ let stats = rec.perSource.get(ev.source);
584
+ if (!stats) {
585
+ stats = {
586
+ requests: 0,
587
+ bytesOut: 0,
588
+ bytesIn: 0,
589
+ ports: /* @__PURE__ */ new Set(),
590
+ protocols: /* @__PURE__ */ new Set(),
591
+ methods: /* @__PURE__ */ new Set(),
592
+ paths: /* @__PURE__ */ new Set()
593
+ };
594
+ rec.perSource.set(ev.source, stats);
595
+ }
596
+ if (ev.pid !== void 0) rec.pids.add(ev.pid);
597
+ stats.requests += 1;
598
+ stats.bytesOut += ev.bytesOut;
599
+ stats.bytesIn += ev.bytesIn;
600
+ stats.ports.add(ev.port);
601
+ stats.protocols.add(ev.protocol);
602
+ if (ev.method) stats.methods.add(ev.method);
603
+ if (ev.path) stats.paths.add(ev.path);
604
+ if (first || upgraded) {
605
+ const level = category === "TELEMETRY" ? "high" : category === "UNKNOWN" ? "warn" : "info";
606
+ const alert = { level, kind: "net", event: ev, launcher: this.isLauncherPid(ev.pid) };
607
+ this.emit("alert", alert);
608
+ } else if (ev.source === "preload" || ev.source === "proxy") {
609
+ this.emit("request", ev);
610
+ }
611
+ return ev;
612
+ }
613
+ updateNet(id, bytesOut, bytesIn) {
614
+ const ev = this.netById.get(id);
615
+ if (!ev) return;
616
+ const rec = this.hosts.get(ev.host);
617
+ const stats = rec?.perSource.get(ev.source);
618
+ if (bytesOut !== void 0) {
619
+ const delta = bytesOut - ev.bytesOut;
620
+ ev.bytesOut = bytesOut;
621
+ if (stats) stats.bytesOut += delta;
622
+ }
623
+ if (bytesIn !== void 0) {
624
+ const delta = bytesIn - ev.bytesIn;
625
+ ev.bytesIn = bytesIn;
626
+ if (stats) stats.bytesIn += delta;
627
+ }
628
+ }
629
+ // ---- summary -------------------------------------------------------------
630
+ fileSummary(rec) {
631
+ const ops = {};
632
+ for (const [k, v] of rec.ops) ops[k] = v;
633
+ const procs = new Set(rec.procs);
634
+ if (this.resolveProc) {
635
+ for (const pid of rec.pids) {
636
+ const n = this.resolveProc(pid);
637
+ if (n) procs.add(n);
638
+ }
639
+ }
640
+ let own = rec.watch ? this.ownNamespaces.has(rec.watch.id) : false;
641
+ if (!own && rec.watch && procs.size) {
642
+ const id = rec.watch.id;
643
+ own = [...procs].every((p) => this.ownOf(p).has(id));
644
+ }
645
+ return {
646
+ path: rec.path,
647
+ ops,
648
+ sources: [...rec.sources],
649
+ pids: [...rec.pids],
650
+ watch: rec.watch,
651
+ ownNamespace: own,
652
+ launcher: this.launcherOnly(rec.pids),
653
+ exists: rec.exists,
654
+ procs: [...procs],
655
+ graded: rec.watch ? rec.watch.graded !== false : false
656
+ };
657
+ }
658
+ sensitiveFiles() {
659
+ return [...this.files.values()].filter((r) => r.watch && r.exists).map((r) => this.fileSummary(r)).sort((a, b) => a.path.localeCompare(b.path));
660
+ }
661
+ /** Watchlist paths the tool tried to open that do not exist here. Reported, never graded. */
662
+ probedFiles() {
663
+ return [...this.files.values()].filter((r) => r.watch && !r.exists).map((r) => this.fileSummary(r)).sort((a, b) => a.path.localeCompare(b.path));
664
+ }
665
+ otherDotfiles() {
666
+ return [...this.files.values()].filter((r) => !r.watch && r.exists).map((r) => this.fileSummary(r)).sort((a, b) => a.path.localeCompare(b.path));
667
+ }
668
+ /**
669
+ * Raw IP records that only socket-level layers saw while a hostname-level
670
+ * layer (proxy / hook) was also reporting named hosts in this run. They are
671
+ * almost always the same connections seen twice, so they are reported
672
+ * separately and not graded.
673
+ */
674
+ isSuppressedIp(rec, hasNamedHosts) {
675
+ if (!hasNamedHosts || !isIpAddress(rec.host)) return false;
676
+ for (const src of rec.perSource.keys()) if (src === "proxy" || src === "preload") return false;
677
+ return true;
678
+ }
679
+ hasNamedHosts() {
680
+ for (const rec of this.hosts.values()) {
681
+ if (isIpAddress(rec.host)) continue;
682
+ for (const src of rec.perSource.keys()) if (src === "proxy" || src === "preload") return true;
683
+ }
684
+ return false;
685
+ }
686
+ suppressedHosts() {
687
+ return this.allHostSummaries().filter((h) => h.suppressed);
688
+ }
689
+ hostSummaries() {
690
+ return this.allHostSummaries().filter((h) => !h.suppressed);
691
+ }
692
+ allHostSummaries() {
693
+ const named = this.hasNamedHosts();
694
+ const out = [];
695
+ for (const rec of this.hosts.values()) {
696
+ let best = null;
697
+ for (const s of rec.perSource.keys()) {
698
+ if (!best || SOURCE_RANK[s] > SOURCE_RANK[best]) best = s;
699
+ }
700
+ if (!best) continue;
701
+ const primary = rec.perSource.get(best);
702
+ const ports = /* @__PURE__ */ new Set();
703
+ const protocols = /* @__PURE__ */ new Set();
704
+ const methods = /* @__PURE__ */ new Set();
705
+ const paths = /* @__PURE__ */ new Set();
706
+ let bytesOut = primary.bytesOut;
707
+ let bytesIn = primary.bytesIn;
708
+ for (const [src, st] of rec.perSource) {
709
+ for (const p of st.ports) ports.add(p);
710
+ for (const p of st.protocols) protocols.add(p);
711
+ for (const m of st.methods) methods.add(m);
712
+ for (const p of st.paths) paths.add(p);
713
+ if (src !== best && bytesOut === 0 && bytesIn === 0) {
714
+ bytesOut = st.bytesOut;
715
+ bytesIn = st.bytesIn;
716
+ }
717
+ }
718
+ out.push({
719
+ host: rec.host,
720
+ category: rec.category,
721
+ requests: primary.requests,
722
+ bytesOut,
723
+ bytesIn,
724
+ ports: [...ports].sort((a, b) => a - b),
725
+ protocols: [...protocols],
726
+ methods: [...methods],
727
+ paths: [...paths].slice(0, 50),
728
+ sources: [...rec.perSource.keys()],
729
+ primarySource: best,
730
+ firstSeen: rec.firstSeen,
731
+ launcher: this.launcherOnly(rec.pids),
732
+ suppressed: this.isSuppressedIp(rec, named)
733
+ });
734
+ }
735
+ const order = { TELEMETRY: 0, UNKNOWN: 1, LLM_API: 2, AUTH: 3 };
736
+ return out.sort(
737
+ (a, b) => order[a.category] - order[b.category] || b.requests - a.requests || a.host.localeCompare(b.host)
738
+ );
739
+ }
740
+ score() {
741
+ const hosts = this.hostSummaries();
742
+ return computeScore({
743
+ telemetryHosts: hosts.filter((h) => h.category === "TELEMETRY" && !h.launcher).map((h) => h.host),
744
+ unknownHosts: hosts.filter((h) => h.category === "UNKNOWN" && !h.launcher).map((h) => h.host),
745
+ sensitiveFiles: this.sensitiveFiles().filter((f) => !f.ownNamespace && !f.launcher && f.graded).map((f) => this.matcher.display(f.path))
746
+ });
747
+ }
748
+ };
749
+
750
+ // src/demo.ts
751
+ import * as fs2 from "fs";
752
+ import * as http from "http";
753
+ import * as https from "https";
754
+ import * as path2 from "path";
755
+
756
+ // src/fixtures/demo-cert.ts
757
+ var DEMO_KEY = `
758
+ -----BEGIN PRIVATE KEY-----
759
+ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJMbKximDMnqBq
760
+ sVMZ2TTpDVjFY9wo0eE1+KM5hj5V149rYMzeucBsGgFutP7Qot0Hfo1ASlYHDVFw
761
+ rzm2UyMHxXfhcX9g0e7H2NlU96GPT0BlDy4UYq3NyYrsckBig75zkH+SuxK64SzA
762
+ jJvgwojQw4p1MQOKvGF65UBRZ3flSqWq8H/AXJ+RJLkeuCOBOZiiksRJVAi7nRgK
763
+ BYQ+3Yr2elZRnpokFE5zT1fkDVGQOxg3Tn7or/nTkTaVVRLSqQq1e1Jpy7HIuV8D
764
+ SOHF3Y8qXPQ3CBcunykzaugcX5N3+9VCY7E/wAwWamjb42PhF8UZHtQdkCNSd22V
765
+ qWrTb3xZAgMBAAECggEAJ3X97GCNt9Rs9kAtYmZ9wDAD90MszTzNBT7tFL1FwKR0
766
+ 1sS3qf+YxBsdqM8LI3SuEWg64B80XFG6ZXWYxi/sMPwEFU2jhCPox326srWXFHqg
767
+ 0LF3gjwQhso+2z1Vb30Tf6sZunfCprC/jEyHzj+Zggi4QWAJp85m+Cm6wbyfgXMX
768
+ jScbC5qwBkP+RC9TKNLvnr0vf3y2frO9ZaWyaxyG6Z4b/D0xN809FlT3D0Jpw08x
769
+ UfuBKlyY5I5Lhunya5rXEhWqRVKYzdCH6oquFyblR3KN6AE9hs4i1+PEw2PSh4H2
770
+ 1MInohxzQzNpyW/vBUTJ+ciUYsHFuFecWkEc+GQF+QKBgQDshvUdbaB1W84nCiRZ
771
+ 6meL2hpKfHblNh4An4bzFPWsNcEUdfd//hgsJ0i1SfDQLRqb0zSGFdS64R1i1v5c
772
+ vj1MUIIm+ZGXZEkzS9NY0Y6w/Yz7WyTSYcVzIRdKHwVVeyYk7V/ZnfCcH9XI5ioh
773
+ 6IWOu4VvDg3GMEBv6VgQSRPNJwKBgQDZwg/aj81/ycqhX09otwC5YaX1i3Seu74u
774
+ 7daiWuFWU1Mi0m2Yeb4O3hazFoRd5wgEPAOaduOgHTVUQdWhDrMmI2Uv1w5JETPe
775
+ 3ANS/EE8nBswDg2elJ1LCufb01ujSyyinZG3SIFhErA/oRYYzPV9GIT/V80UPSeP
776
+ 5h/l17tafwKBgQDlk3y4yp5TKv+m3u43pBBLKzAXmkVg5y0p162JpY9rTmWRMYtA
777
+ XWYi/SJSbGlj9lN8afzyJKBtn3EBbcJITJJ8zyv1HonVEw8FzhReglBotEGx+157
778
+ IVEgFT9gv0lTFgwJDanaNLXFJBVCQT0l2mZACv1RtKdj9ZOlzCyg6f1hQwKBgGP4
779
+ Ip0dXaNn+Z2iCuuw8CUrPix/DFf/Ku2ShPHeNQsTj9wxrNzOL0HWFae8E6KkeNqw
780
+ zpqwMAoGvr/ixXd+LyK4JzESUt2ahyyt5tzHMA/qPtUN7pS594hHBnC2FKDf1ysE
781
+ mawCHlt5X+6mPmW+WolGo3AyV9UNykbWyBgVtU5zAoGBALMMvpNfae/6qDCLdOZk
782
+ 01mUKAOFC4dxk65p9jHaerxNBkJfZ8LA9AnJFLFg+ZQZ91Hzk7A2hIHwqO/Sxn7R
783
+ V/vSt9B0EXd9+nbDMdzrKOKJdP8bryKz7TAVn7Muostwi3dpx68YiLd12yOYkKAD
784
+ Pcp0u93DTehzqhuJPnXGd0Oe
785
+ -----END PRIVATE KEY-----
786
+ `;
787
+ var DEMO_CERT = `
788
+ -----BEGIN CERTIFICATE-----
789
+ MIIDLzCCAhegAwIBAgIUW+wHzVI1jrFqQcLre+FiLgz/1aowDQYJKoZIhvcNAQEL
790
+ BQAwGTEXMBUGA1UEAwwObmFyYy1kZW1vLXNpbmswHhcNMjYxMTI1MDU1NzM3WhcN
791
+ MzYxMTIyMDU1NzM3WjAZMRcwFQYDVQQDDA5uYXJjLWRlbW8tc2luazCCASIwDQYJ
792
+ KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMkxsrGKYMyeoGqxUxnZNOkNWMVj3CjR
793
+ 4TX4ozmGPlXXj2tgzN65wGwaAW60/tCi3Qd+jUBKVgcNUXCvObZTIwfFd+Fxf2DR
794
+ 7sfY2VT3oY9PQGUPLhRirc3JiuxyQGKDvnOQf5K7ErrhLMCMm+DCiNDDinUxA4q8
795
+ YXrlQFFnd+VKparwf8Bcn5EkuR64I4E5mKKSxElUCLudGAoFhD7divZ6VlGemiQU
796
+ TnNPV+QNUZA7GDdOfuiv+dORNpVVEtKpCrV7UmnLsci5XwNI4cXdjypc9DcIFy6f
797
+ KTNq6Bxfk3f71UJjsT/ADBZqaNvjY+EXxRke1B2QI1J3bZWpatNvfFkCAwEAAaNv
798
+ MG0wHQYDVR0OBBYEFBFtImtXzzhdbRmlp+13kD9cdhJhMB8GA1UdIwQYMBaAFBFt
799
+ ImtXzzhdbRmlp+13kD9cdhJhMA8GA1UdEwEB/wQFMAMBAf8wGgYDVR0RBBMwEYIJ
800
+ bG9jYWxob3N0hwR/AAABMA0GCSqGSIb3DQEBCwUAA4IBAQAk0Dy2VeufiVefTWoB
801
+ ipvKp5jeS+Y5zm52F2eWUArTBZICTJOVWsc+RKGPKnBTN5zWuCVYlOp83fgNqAXX
802
+ Z2R75T+onouZ9HB3FGHkjVep/cD6yfG78rf5XPnrUj9A5W4NheORT7/k/eSvK112
803
+ AXeOF5EKv93s932EiQaAhyqhSDyG3nMLSn6E3nqIHup4OETiBepcJIlV7jf5aY1F
804
+ cpUP+0xVZ/RVNCPO/zZNl985aa896FsDt2s/FjnoCSCNPLX8Y0d4Y0GeBUL4J6oQ
805
+ 7n6ptYkXCYs5Zm/ZLUH+ObMh5OXMEDZIng9t4AVMlMfu/rTfUqahkASekV7lg41H
806
+ DN0u
807
+ -----END CERTIFICATE-----
808
+ `;
809
+
810
+ // src/demo.ts
811
+ var FAKE_FILES = {
812
+ ".claude.json": JSON.stringify({ oauthAccount: { emailAddress: "fake@example.invalid" }, primaryApiKey: "sk-ant-FAKE-FAKE-FAKE" }, null, 2),
813
+ ".ssh/id_rsa": "-----BEGIN OPENSSH PRIVATE KEY-----\nTHIS-IS-A-FAKE-KEY-FOR-THE-NARC-DEMO\n-----END OPENSSH PRIVATE KEY-----\n",
814
+ ".ssh/config": "Host *\n IdentityFile ~/.ssh/id_rsa\n",
815
+ ".aws/credentials": "[default]\naws_access_key_id = AKIAFAKEFAKEFAKEFAKE\naws_secret_access_key = FAKE/FAKE/FAKE\n",
816
+ ".config/gh/hosts.yml": "github.com:\n oauth_token: gho_FAKEFAKEFAKE\n user: demo\n",
817
+ ".npmrc": "//registry.npmjs.org/:_authToken=npm_FAKEFAKEFAKE\n",
818
+ ".gitconfig": "[user]\n name = Demo\n email = demo@example.invalid\n",
819
+ "project/.env": "OPENAI_API_KEY=sk-FAKE\nDATABASE_URL=postgres://fake\n",
820
+ "project/README.md": "# demo project\n",
821
+ ".config/shady-ai/settings.json": JSON.stringify({ theme: "dark", telemetry: true })
822
+ };
823
+ async function setupDemo(tmpDir, distDir) {
824
+ const home = path2.join(tmpDir, "home");
825
+ for (const [rel, content] of Object.entries(FAKE_FILES)) {
826
+ const abs = path2.join(home, rel);
827
+ fs2.mkdirSync(path2.dirname(abs), { recursive: true });
828
+ fs2.writeFileSync(abs, content, { mode: 384 });
829
+ }
830
+ const handler = (req, res) => {
831
+ req.on("data", () => void 0);
832
+ req.on("end", () => {
833
+ res.writeHead(200, { "content-type": "application/json", "content-length": "11" });
834
+ res.end('{"ok":true}');
835
+ });
836
+ };
837
+ const httpSink = http.createServer(handler);
838
+ const httpsSink = https.createServer({ key: DEMO_KEY, cert: DEMO_CERT }, handler);
839
+ const sockets = /* @__PURE__ */ new Set();
840
+ for (const s of [httpSink, httpsSink]) {
841
+ s.on("connection", (sock) => {
842
+ sockets.add(sock);
843
+ sock.once("close", () => sockets.delete(sock));
844
+ });
845
+ s.on("clientError", (_e, sock) => sock.destroy());
846
+ }
847
+ await Promise.all([listen(httpSink), listen(httpsSink)]);
848
+ const httpPort = portOf(httpSink);
849
+ const httpsPort = portOf(httpsSink);
850
+ return {
851
+ home,
852
+ cwd: path2.join(home, "project"),
853
+ command: [process.execPath, path2.join(distDir, "shady-ai-tool.cjs")],
854
+ env: {
855
+ HOME: home,
856
+ NARC_HOME: home,
857
+ NARC_DEMO_HTTP_SINK: String(httpPort),
858
+ NARC_DEMO_HTTPS_SINK: String(httpsPort)
859
+ },
860
+ resolveUpstream: (_host, port) => ({ host: "127.0.0.1", port: port === 443 ? httpsPort : httpPort }),
861
+ sinkPorts: [httpPort, httpsPort],
862
+ close: async () => {
863
+ for (const s of sockets) s.destroy();
864
+ await Promise.all([closeServer(httpSink), closeServer(httpsSink)]);
865
+ }
866
+ };
867
+ }
868
+ function listen(s) {
869
+ return new Promise((resolve4, reject) => {
870
+ s.once("error", reject);
871
+ s.listen(0, "127.0.0.1", () => resolve4());
872
+ });
873
+ }
874
+ function portOf(s) {
875
+ const a = s.address();
876
+ return typeof a === "object" && a ? a.port : 0;
877
+ }
878
+ function closeServer(s) {
879
+ return new Promise((resolve4) => {
880
+ s.close(() => resolve4());
881
+ setTimeout(resolve4, 300).unref();
882
+ });
883
+ }
884
+
885
+ // src/layers/fsusage.ts
886
+ import { spawn, spawnSync } from "child_process";
887
+ import * as path3 from "path";
888
+ function parseFsUsageLine(line) {
889
+ const m = /^\d{2}:\d{2}:\d{2}(?:\.\d+)?\s+(\S+)\s+(.*?)\s+(\d+\.\d+)\s+(?:W\s+)?(\S+?)(?:\.(\d+))?\s*$/.exec(line);
890
+ if (!m) return null;
891
+ const call = m[1] ?? "";
892
+ let middle = (m[2] ?? "").trim();
893
+ middle = middle.replace(/^F=-?\d+\s*/, "").replace(/^B=0x[0-9a-fA-F]+\s*/, "").replace(/^\[\s*\d+\]\s*/, "").replace(/^\([^)]*\)\s*/, "").trim();
894
+ const pathTail = middle.length ? middle : null;
895
+ return { call, pathTail, procName: m[4] ?? "", tid: m[5] ? Number(m[5]) : null };
896
+ }
897
+ var OPEN_CALLS = /* @__PURE__ */ new Set([
898
+ "open",
899
+ "openat",
900
+ "open_nocancel",
901
+ "openat_nocancel",
902
+ "open_extended",
903
+ "guarded_open_np",
904
+ "open_dprotected_np"
905
+ ]);
906
+ var ROOTS = /\/(Users|home|private|tmp|var|etc|Library|opt|usr|System|Applications|dev|nix|Volumes)\//;
907
+ function reconstructPath(tail, home) {
908
+ const t = tail.trim();
909
+ if (t.startsWith("/")) return t;
910
+ if (!t.includes("/")) return null;
911
+ const h = t.indexOf(home + "/");
912
+ if (h >= 0) return t.slice(h);
913
+ const lastSpace = t.lastIndexOf(" ");
914
+ if (lastSpace >= 0 && t[lastSpace + 1] === "/") return t.slice(lastSpace + 1);
915
+ const withSlash = "/" + t;
916
+ if (withSlash === home || withSlash.startsWith(home + "/")) return withSlash;
917
+ const m = ROOTS.exec(t);
918
+ if (m && m.index > 0 && !home.endsWith(t.slice(0, m.index))) return t.slice(m.index);
919
+ return path3.join(home, t.slice(t.indexOf("/") + 1));
920
+ }
921
+ function sudoCached() {
922
+ const r = spawnSync("sudo", ["-n", "true"], { stdio: "ignore", timeout: 3e3 });
923
+ return r.status === 0;
924
+ }
925
+ function sudoValidate(prompt) {
926
+ const r = spawnSync("sudo", ["-p", prompt, "-v"], { stdio: "inherit" });
927
+ return r.status === 0;
928
+ }
929
+ function startFsUsage(opts) {
930
+ const { collector, tree, home } = opts;
931
+ const args = ["-w", "-f", "filesys"];
932
+ let child;
933
+ if (opts.asRoot) {
934
+ child = spawn("fs_usage", args, { stdio: ["ignore", "pipe", "ignore"] });
935
+ } else {
936
+ child = spawn("sudo", ["-n", "fs_usage", ...args], { stdio: ["ignore", "pipe", "ignore"] });
937
+ }
938
+ const handle = { active: true, stop: () => void 0 };
939
+ child.on("error", () => handle.active = false);
940
+ child.on("exit", () => handle.active = false);
941
+ let buf = "";
942
+ child.stdout?.setEncoding("utf8");
943
+ child.stdout?.on("data", (chunk) => {
944
+ buf += chunk;
945
+ let nl;
946
+ while ((nl = buf.indexOf("\n")) >= 0) {
947
+ const line = buf.slice(0, nl);
948
+ buf = buf.slice(nl + 1);
949
+ const parsed = parseFsUsageLine(line);
950
+ if (!parsed || !parsed.pathTail || !OPEN_CALLS.has(parsed.call)) continue;
951
+ if (!nameInTree(parsed.procName, tree)) continue;
952
+ const full = reconstructPath(parsed.pathTail, home);
953
+ if (!full) continue;
954
+ collector.addFile({ source: "fs_usage", path: full, op: parsed.call, proc: tree.displayNameFor(parsed.procName) });
955
+ }
956
+ });
957
+ handle.stop = () => {
958
+ handle.active = false;
959
+ try {
960
+ child.stdout?.destroy();
961
+ } catch {
962
+ }
963
+ if (child.pid) {
964
+ if (opts.asRoot) {
965
+ try {
966
+ process.kill(child.pid, "SIGTERM");
967
+ } catch {
968
+ }
969
+ } else {
970
+ spawnSync("sudo", ["-n", "kill", "-TERM", String(child.pid)], { stdio: "ignore", timeout: 2e3 });
971
+ }
972
+ }
973
+ };
974
+ return handle;
975
+ }
976
+ function nameInTree(procName, tree) {
977
+ if (!procName) return false;
978
+ for (const n of tree.names()) {
979
+ if (n === procName) return true;
980
+ if (procName.length >= 15 && n.startsWith(procName)) return true;
981
+ }
982
+ return false;
983
+ }
984
+
985
+ // src/layers/ipc.ts
986
+ import * as fs3 from "fs";
987
+ import * as net from "net";
988
+ import * as os2 from "os";
989
+ import * as path4 from "path";
990
+ async function startIpc(collector, tmpDir) {
991
+ const hookedPids = /* @__PURE__ */ new Set();
992
+ const sockets = /* @__PURE__ */ new Set();
993
+ const server = net.createServer((sock) => {
994
+ sockets.add(sock);
995
+ sock.once("close", () => sockets.delete(sock));
996
+ sock.on("error", () => sock.destroy());
997
+ let buf = "";
998
+ sock.setEncoding("utf8");
999
+ sock.on("data", (chunk) => {
1000
+ buf += chunk;
1001
+ let nl;
1002
+ while ((nl = buf.indexOf("\n")) >= 0) {
1003
+ const line = buf.slice(0, nl);
1004
+ buf = buf.slice(nl + 1);
1005
+ if (!line) continue;
1006
+ let msg;
1007
+ try {
1008
+ msg = JSON.parse(line);
1009
+ } catch {
1010
+ continue;
1011
+ }
1012
+ dispatch(collector, hookedPids, msg);
1013
+ }
1014
+ });
1015
+ });
1016
+ let address;
1017
+ const unixPath = path4.join(tmpDir, "ipc.sock");
1018
+ const canUnix = os2.platform() !== "win32" && Buffer.byteLength(unixPath) < 100;
1019
+ await new Promise((resolve4, reject) => {
1020
+ server.once("error", reject);
1021
+ if (canUnix) {
1022
+ try {
1023
+ fs3.rmSync(unixPath, { force: true });
1024
+ } catch {
1025
+ }
1026
+ server.listen(unixPath, () => resolve4());
1027
+ } else {
1028
+ server.listen(0, "127.0.0.1", () => resolve4());
1029
+ }
1030
+ });
1031
+ if (canUnix) {
1032
+ address = unixPath;
1033
+ } else {
1034
+ const a = server.address();
1035
+ const port = typeof a === "object" && a ? a.port : 0;
1036
+ collector.ignorePort(port);
1037
+ address = `tcp://127.0.0.1:${port}`;
1038
+ }
1039
+ return {
1040
+ address,
1041
+ hookedPids,
1042
+ close: () => new Promise((resolve4) => {
1043
+ for (const s of sockets) s.destroy();
1044
+ server.close(() => {
1045
+ if (canUnix) {
1046
+ try {
1047
+ fs3.rmSync(unixPath, { force: true });
1048
+ } catch {
1049
+ }
1050
+ }
1051
+ resolve4();
1052
+ });
1053
+ setTimeout(resolve4, 300).unref();
1054
+ })
1055
+ };
1056
+ }
1057
+ function dispatch(collector, hookedPids, msg) {
1058
+ switch (msg.t) {
1059
+ case "hello":
1060
+ hookedPids.add(msg.pid);
1061
+ break;
1062
+ case "file":
1063
+ hookedPids.add(msg.pid);
1064
+ collector.addFile({ source: "preload", pid: msg.pid, path: msg.path, op: msg.op, id: "p" + msg.id, exists: msg.exists });
1065
+ break;
1066
+ case "net":
1067
+ hookedPids.add(msg.pid);
1068
+ collector.addNet({
1069
+ source: "preload",
1070
+ pid: msg.pid,
1071
+ host: msg.host,
1072
+ port: msg.port,
1073
+ protocol: msg.protocol,
1074
+ method: msg.method,
1075
+ path: msg.path,
1076
+ url: msg.url,
1077
+ bytesOut: msg.bytesOut,
1078
+ id: "p" + msg.id
1079
+ });
1080
+ break;
1081
+ case "net-update":
1082
+ collector.updateNet("p" + msg.id, msg.bytesOut, msg.bytesIn);
1083
+ break;
1084
+ case "dns":
1085
+ collector.addDns({ source: "preload", pid: msg.pid, host: msg.host, addresses: msg.addresses, id: "p" + msg.id });
1086
+ break;
1087
+ }
1088
+ }
1089
+
1090
+ // src/layers/lsof.ts
1091
+ import { execFile } from "child_process";
1092
+ function parseLsof(output) {
1093
+ const out = [];
1094
+ let pid = 0;
1095
+ let command = "";
1096
+ let proto = null;
1097
+ for (const line of output.split("\n")) {
1098
+ if (!line) continue;
1099
+ const tag = line[0];
1100
+ const val = line.slice(1);
1101
+ switch (tag) {
1102
+ case "p":
1103
+ pid = Number(val);
1104
+ break;
1105
+ case "c":
1106
+ command = val;
1107
+ break;
1108
+ case "P":
1109
+ proto = val.toUpperCase() === "UDP" ? "udp" : val.toUpperCase() === "TCP" ? "tcp" : null;
1110
+ break;
1111
+ case "n": {
1112
+ if (!proto) break;
1113
+ const arrow = val.indexOf("->");
1114
+ if (arrow < 0) break;
1115
+ const local = splitAddr(val.slice(0, arrow));
1116
+ const remoteRaw = val.slice(arrow + 2).replace(/\s*\(.*\)$/, "");
1117
+ const remote = splitAddr(remoteRaw);
1118
+ if (!remote) break;
1119
+ out.push({
1120
+ pid,
1121
+ command,
1122
+ protocol: proto,
1123
+ localHost: local?.host ?? "",
1124
+ localPort: local?.port ?? 0,
1125
+ remoteHost: remote.host,
1126
+ remotePort: remote.port
1127
+ });
1128
+ break;
1129
+ }
1130
+ default:
1131
+ break;
1132
+ }
1133
+ }
1134
+ return out;
1135
+ }
1136
+ function splitAddr(s) {
1137
+ const t = s.trim();
1138
+ if (!t) return null;
1139
+ const m = /^(?:\[([^\]]+)\]|([^:]+)):(\d+|\*)$/.exec(t);
1140
+ if (!m) return null;
1141
+ const host = m[1] ?? m[2] ?? "";
1142
+ const port = m[3] === "*" ? 0 : Number(m[3]);
1143
+ return { host, port };
1144
+ }
1145
+ function startLsofPoller(opts) {
1146
+ const { collector, tree } = opts;
1147
+ const seen = /* @__PURE__ */ new Set();
1148
+ let busy = false;
1149
+ let stopped = false;
1150
+ const handle = { polls: 0, stop: () => void 0 };
1151
+ const tick = () => {
1152
+ if (busy || stopped) return;
1153
+ const pids = tree.pids();
1154
+ if (!pids.length) return;
1155
+ busy = true;
1156
+ execFile(
1157
+ "lsof",
1158
+ ["-n", "-P", "-i", "-a", "-p", pids.join(","), "-F", "pcPn"],
1159
+ { maxBuffer: 8 * 1024 * 1024, timeout: 3e3 },
1160
+ (_err, stdout) => {
1161
+ busy = false;
1162
+ if (!stdout) return;
1163
+ handle.polls++;
1164
+ for (const c of parseLsof(stdout)) {
1165
+ const key = `${c.pid}|${c.protocol}|${c.localPort}|${c.remoteHost}|${c.remotePort}`;
1166
+ if (seen.has(key)) continue;
1167
+ seen.add(key);
1168
+ collector.addNet({
1169
+ source: "lsof",
1170
+ pid: c.pid,
1171
+ host: c.remoteHost,
1172
+ port: c.remotePort,
1173
+ protocol: c.protocol
1174
+ });
1175
+ }
1176
+ if (seen.size > 2e4) seen.clear();
1177
+ }
1178
+ );
1179
+ };
1180
+ const timer = setInterval(tick, opts.intervalMs ?? 150);
1181
+ timer.unref();
1182
+ tick();
1183
+ handle.stop = () => {
1184
+ stopped = true;
1185
+ clearInterval(timer);
1186
+ };
1187
+ return handle;
1188
+ }
1189
+
1190
+ // src/layers/pidtree.ts
1191
+ import { execFile as execFile2 } from "child_process";
1192
+ import * as path5 from "path";
1193
+ var PidTree = class _PidTree {
1194
+ constructor(rootPid, intervalMs = 150) {
1195
+ this.intervalMs = intervalMs;
1196
+ this.rootPid = rootPid;
1197
+ if (rootPid > 0) this.descendants.add(rootPid);
1198
+ }
1199
+ intervalMs;
1200
+ rootPid;
1201
+ procs = /* @__PURE__ */ new Map();
1202
+ descendants = /* @__PURE__ */ new Set();
1203
+ everSeen = /* @__PURE__ */ new Map();
1204
+ timer = null;
1205
+ running = false;
1206
+ /** Set (or change) the root after construction, e.g. once the child has spawned. */
1207
+ setRoot(pid) {
1208
+ this.rootPid = pid;
1209
+ this.descendants = /* @__PURE__ */ new Set([pid]);
1210
+ void this.refresh();
1211
+ }
1212
+ start() {
1213
+ if (this.timer) return;
1214
+ void this.refresh();
1215
+ this.timer = setInterval(() => void this.refresh(), this.intervalMs);
1216
+ this.timer.unref();
1217
+ }
1218
+ stop() {
1219
+ if (this.timer) clearInterval(this.timer);
1220
+ this.timer = null;
1221
+ }
1222
+ /** Current pid set: root + all live descendants. */
1223
+ pids() {
1224
+ return this.rootPid > 0 ? [...this.descendants] : [];
1225
+ }
1226
+ has(pid) {
1227
+ return this.descendants.has(pid);
1228
+ }
1229
+ /** Accounting names (and executable basenames) for every live pid in the tree. */
1230
+ names() {
1231
+ const out = /* @__PURE__ */ new Set();
1232
+ for (const pid of this.descendants) {
1233
+ const p = this.procs.get(pid);
1234
+ if (!p) continue;
1235
+ if (p.ucomm) out.add(p.ucomm);
1236
+ out.add(path5.basename(p.comm.split(" ")[0] ?? p.comm));
1237
+ }
1238
+ return out;
1239
+ }
1240
+ info(pid) {
1241
+ return this.procs.get(pid) ?? this.everSeen.get(pid);
1242
+ }
1243
+ /** Human name for a process: the accounting name unless it is just a version string (`2.1.323`). */
1244
+ static displayName(p) {
1245
+ const exe = path5.basename(p.comm.split(" ")[0] ?? p.comm);
1246
+ if (!p.ucomm || /^[\d.]+$/.test(p.ucomm)) return exe;
1247
+ return p.ucomm;
1248
+ }
1249
+ /** Short display name for a pid seen at any point during the run. */
1250
+ nameOf(pid) {
1251
+ const p = this.everSeen.get(pid) ?? this.procs.get(pid);
1252
+ return p ? _PidTree.displayName(p) : void 0;
1253
+ }
1254
+ /** Map an accounting name fs_usage printed back to a display name of a process in the tree. */
1255
+ displayNameFor(ucomm) {
1256
+ for (const p of [...this.procs.values(), ...this.everSeen.values()]) {
1257
+ if (p.ucomm === ucomm || ucomm.length >= 15 && p.ucomm.startsWith(ucomm)) return _PidTree.displayName(p);
1258
+ }
1259
+ return ucomm;
1260
+ }
1261
+ /** Every process observed in the tree during the run, including ones that have exited. */
1262
+ seenProcesses() {
1263
+ return [...this.everSeen.values()];
1264
+ }
1265
+ /**
1266
+ * Processes observed in the tree that are still alive after the root exited
1267
+ * (daemonised servers, detached helpers). The accounting name must still
1268
+ * match so a reused pid is never mistaken for one of ours.
1269
+ */
1270
+ leftovers() {
1271
+ const out = [];
1272
+ for (const seen of this.everSeen.values()) {
1273
+ if (seen.pid === this.rootPid) continue;
1274
+ const now = this.procs.get(seen.pid);
1275
+ if (now && now.ucomm === seen.ucomm && now.comm === seen.comm) out.push(now);
1276
+ }
1277
+ return out;
1278
+ }
1279
+ refresh() {
1280
+ if (this.running) return Promise.resolve();
1281
+ this.running = true;
1282
+ return new Promise((resolve4) => {
1283
+ execFile2("ps", ["-axo", "pid=,ppid=,comm="], { maxBuffer: 16 * 1024 * 1024, timeout: 2e3 }, (err, stdout) => {
1284
+ if (err || !stdout) {
1285
+ this.running = false;
1286
+ return resolve4();
1287
+ }
1288
+ execFile2("ps", ["-axo", "pid=,ucomm="], { maxBuffer: 16 * 1024 * 1024, timeout: 2e3 }, (err2, names) => {
1289
+ this.running = false;
1290
+ this.ingest(stdout, err2 ? "" : names);
1291
+ resolve4();
1292
+ });
1293
+ });
1294
+ });
1295
+ }
1296
+ /** Parse `ps -axo pid=,ppid=,comm=` (+ optional `ps -axo pid=,ucomm=`) output and recompute the tree. */
1297
+ ingest(psOutput, ucommOutput = "") {
1298
+ const ucomms = /* @__PURE__ */ new Map();
1299
+ for (const raw of ucommOutput.split("\n")) {
1300
+ const m = /^\s*(\d+)\s+(.*)$/.exec(raw);
1301
+ if (m) ucomms.set(Number(m[1]), (m[2] ?? "").trim());
1302
+ }
1303
+ const procs = /* @__PURE__ */ new Map();
1304
+ for (const raw of psOutput.split("\n")) {
1305
+ const m = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(raw);
1306
+ if (!m) continue;
1307
+ const pid = Number(m[1]);
1308
+ const comm = (m[3] ?? "").trim();
1309
+ procs.set(pid, { pid, ppid: Number(m[2]), comm, ucomm: ucomms.get(pid) ?? "" });
1310
+ }
1311
+ const children = /* @__PURE__ */ new Map();
1312
+ for (const p of procs.values()) {
1313
+ const arr = children.get(p.ppid);
1314
+ if (arr) arr.push(p.pid);
1315
+ else children.set(p.ppid, [p.pid]);
1316
+ }
1317
+ const seen = /* @__PURE__ */ new Set([this.rootPid]);
1318
+ const stack = [this.rootPid];
1319
+ while (stack.length) {
1320
+ const cur = stack.pop();
1321
+ for (const c of children.get(cur) ?? []) {
1322
+ if (!seen.has(c)) {
1323
+ seen.add(c);
1324
+ stack.push(c);
1325
+ }
1326
+ }
1327
+ }
1328
+ this.procs = procs;
1329
+ this.descendants = seen;
1330
+ for (const pid of seen) {
1331
+ const p = procs.get(pid);
1332
+ if (!p) continue;
1333
+ const prev = this.everSeen.get(pid);
1334
+ if (!prev || prev.comm !== p.comm || !prev.ucomm && p.ucomm) this.everSeen.set(pid, p);
1335
+ }
1336
+ }
1337
+ };
1338
+
1339
+ // src/layers/proxy.ts
1340
+ import * as http2 from "http";
1341
+ import * as net2 from "net";
1342
+ var HOP_BY_HOP = /* @__PURE__ */ new Set([
1343
+ "proxy-connection",
1344
+ "proxy-authorization",
1345
+ "connection",
1346
+ "keep-alive",
1347
+ "transfer-encoding",
1348
+ "te",
1349
+ "trailer",
1350
+ "upgrade"
1351
+ ]);
1352
+ function headerBytes(method, url, raw) {
1353
+ let n = method.length + 1 + url.length + 11;
1354
+ for (let i = 0; i < raw.length; i += 2) n += (raw[i]?.length ?? 0) + 2 + (raw[i + 1]?.length ?? 0) + 2;
1355
+ return n + 2;
1356
+ }
1357
+ async function startProxy(opts) {
1358
+ const { collector } = opts;
1359
+ const sockets = /* @__PURE__ */ new Set();
1360
+ const track = (s) => {
1361
+ sockets.add(s);
1362
+ s.once("close", () => sockets.delete(s));
1363
+ };
1364
+ const server = http2.createServer((req, res) => {
1365
+ let target;
1366
+ try {
1367
+ target = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
1368
+ } catch {
1369
+ res.writeHead(400).end("narc: bad request");
1370
+ return;
1371
+ }
1372
+ const host = target.hostname;
1373
+ const port2 = Number(target.port) || (target.protocol === "https:" ? 443 : 80);
1374
+ const method = req.method ?? "GET";
1375
+ const pathq = target.pathname + target.search;
1376
+ let bytesOut = headerBytes(method, req.url ?? "/", req.rawHeaders);
1377
+ let bytesIn = 0;
1378
+ const ev = collector.addNet({
1379
+ source: "proxy",
1380
+ host,
1381
+ port: port2,
1382
+ protocol: "http",
1383
+ method,
1384
+ path: pathq,
1385
+ url: target.toString(),
1386
+ bytesOut
1387
+ });
1388
+ const tick = () => ev && collector.updateNet(ev.id, bytesOut, bytesIn);
1389
+ const up = opts.resolveUpstream?.(host, port2) ?? { host, port: port2 };
1390
+ const headers = {};
1391
+ for (const [k, v] of Object.entries(req.headers)) {
1392
+ if (v === void 0 || HOP_BY_HOP.has(k)) continue;
1393
+ headers[k] = v;
1394
+ }
1395
+ headers["connection"] = "close";
1396
+ const upstream = http2.request(
1397
+ { host: up.host, port: up.port, method, path: pathq, headers, setHost: false },
1398
+ (upRes) => {
1399
+ bytesIn += 12 + JSON.stringify(upRes.rawHeaders).length;
1400
+ res.writeHead(upRes.statusCode ?? 502, upRes.headers);
1401
+ upRes.on("data", (c) => {
1402
+ bytesIn += c.length;
1403
+ tick();
1404
+ });
1405
+ upRes.pipe(res);
1406
+ }
1407
+ );
1408
+ upstream.on("error", () => {
1409
+ if (!res.headersSent) res.writeHead(502, { "content-type": "text/plain" });
1410
+ res.end("narc: upstream connection failed");
1411
+ tick();
1412
+ });
1413
+ req.on("data", (c) => {
1414
+ bytesOut += c.length;
1415
+ tick();
1416
+ });
1417
+ req.on("error", () => upstream.destroy());
1418
+ res.on("close", tick);
1419
+ req.pipe(upstream);
1420
+ });
1421
+ server.on("connect", (req, clientSocket, head) => {
1422
+ track(clientSocket);
1423
+ const [rawHost, rawPort] = splitHostPort(req.url ?? "");
1424
+ const host = rawHost;
1425
+ const port2 = rawPort || 443;
1426
+ let bytesOut = head.length;
1427
+ let bytesIn = 0;
1428
+ const ev = collector.addNet({
1429
+ source: "proxy",
1430
+ host,
1431
+ port: port2,
1432
+ protocol: port2 === 443 ? "https" : "tcp",
1433
+ method: "CONNECT",
1434
+ bytesOut
1435
+ });
1436
+ const tick = () => ev && collector.updateNet(ev.id, bytesOut, bytesIn);
1437
+ const up = opts.resolveUpstream?.(host, port2) ?? { host, port: port2 };
1438
+ const upstream = net2.connect(up.port, up.host);
1439
+ track(upstream);
1440
+ upstream.setNoDelay(true);
1441
+ clientSocket.setNoDelay(true);
1442
+ upstream.once("connect", () => {
1443
+ clientSocket.write("HTTP/1.1 200 Connection Established\r\nProxy-Agent: narc\r\n\r\n");
1444
+ if (head.length) upstream.write(head);
1445
+ clientSocket.on("data", (c) => {
1446
+ bytesOut += c.length;
1447
+ tick();
1448
+ });
1449
+ upstream.on("data", (c) => {
1450
+ bytesIn += c.length;
1451
+ tick();
1452
+ });
1453
+ clientSocket.pipe(upstream);
1454
+ upstream.pipe(clientSocket);
1455
+ });
1456
+ const teardown = () => {
1457
+ tick();
1458
+ clientSocket.destroy();
1459
+ upstream.destroy();
1460
+ };
1461
+ upstream.on("error", () => {
1462
+ if (clientSocket.writable && !clientSocket.destroyed) {
1463
+ clientSocket.write("HTTP/1.1 502 Bad Gateway\r\n\r\n");
1464
+ }
1465
+ teardown();
1466
+ });
1467
+ clientSocket.on("error", teardown);
1468
+ clientSocket.on("close", teardown);
1469
+ upstream.on("close", teardown);
1470
+ });
1471
+ server.on("connection", track);
1472
+ server.on("clientError", (_err, socket) => {
1473
+ try {
1474
+ socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
1475
+ } catch {
1476
+ }
1477
+ });
1478
+ await new Promise((resolve4, reject) => {
1479
+ server.once("error", reject);
1480
+ server.listen(0, "127.0.0.1", () => resolve4());
1481
+ });
1482
+ const addr = server.address();
1483
+ const port = typeof addr === "object" && addr ? addr.port : 0;
1484
+ collector.ignorePort(port);
1485
+ return {
1486
+ port,
1487
+ close: () => new Promise((resolve4) => {
1488
+ for (const s of sockets) s.destroy();
1489
+ server.close(() => resolve4());
1490
+ setTimeout(resolve4, 500).unref();
1491
+ })
1492
+ };
1493
+ }
1494
+ function splitHostPort(s) {
1495
+ const m = /^\[?([^\]]+?)\]?(?::(\d+))?$/.exec(s.trim());
1496
+ if (!m) return [s, 0];
1497
+ return [m[1] ?? s, m[2] ? Number(m[2]) : 0];
1498
+ }
1499
+ function proxyEnv(port) {
1500
+ const url = `http://127.0.0.1:${port}`;
1501
+ return {
1502
+ HTTP_PROXY: url,
1503
+ HTTPS_PROXY: url,
1504
+ ALL_PROXY: url,
1505
+ http_proxy: url,
1506
+ https_proxy: url,
1507
+ all_proxy: url,
1508
+ // Make sure nothing is excluded from the proxy. narc's own ports are
1509
+ // filtered on the collector side, so looping back is harmless.
1510
+ NO_PROXY: "",
1511
+ no_proxy: "",
1512
+ // Node >= 24 honours proxy env vars for fetch/http when this is set.
1513
+ NODE_USE_ENV_PROXY: "1",
1514
+ // global-agent users
1515
+ GLOBAL_AGENT_HTTP_PROXY: url,
1516
+ GLOBAL_AGENT_HTTPS_PROXY: url
1517
+ };
1518
+ }
1519
+
1520
+ // src/layers/strace.ts
1521
+ import { execFileSync } from "child_process";
1522
+ function straceAvailable() {
1523
+ if (process.platform !== "linux") return false;
1524
+ try {
1525
+ execFileSync("strace", ["-qq", "-e", "trace=none", "-o", "/dev/null", "--", "/bin/true"], {
1526
+ stdio: "ignore",
1527
+ timeout: 3e3
1528
+ });
1529
+ return true;
1530
+ } catch {
1531
+ return false;
1532
+ }
1533
+ }
1534
+ function straceWrap(command) {
1535
+ return [
1536
+ "strace",
1537
+ "-f",
1538
+ "-qq",
1539
+ "-s",
1540
+ "512",
1541
+ "-e",
1542
+ "trace=open,openat,openat2,connect",
1543
+ "-e",
1544
+ "signal=none",
1545
+ "-o",
1546
+ "/dev/fd/3",
1547
+ "--",
1548
+ ...command
1549
+ ];
1550
+ }
1551
+ var LINE_RE = /^(?:\[pid\s+)?(\d+)\]?\s+(?:<\.\.\.\s+(\w+)\s+resumed>|(\w+)\()(.*?)(?:\)\s*=\s*(.+))?$/;
1552
+ function parseStraceLine(line) {
1553
+ const m = LINE_RE.exec(line.trim());
1554
+ if (!m) return null;
1555
+ const syscall = m[2] ?? m[3];
1556
+ if (!syscall) return null;
1557
+ return { pid: Number(m[1]), syscall, args: m[4] ?? "", result: m[5] ?? null };
1558
+ }
1559
+ function straceEvent(line) {
1560
+ const p = parseStraceLine(line);
1561
+ if (!p) return null;
1562
+ if (p.result && /^-1\s/.test(p.result)) return null;
1563
+ if (p.syscall === "open" || p.syscall === "openat" || p.syscall === "openat2") {
1564
+ const m = /"((?:[^"\\]|\\.)*)"/.exec(p.args);
1565
+ if (!m) return null;
1566
+ return { pid: p.pid, kind: "file", path: unescapeC(m[1] ?? "") };
1567
+ }
1568
+ if (p.syscall === "connect") {
1569
+ if (/AF_UNIX/.test(p.args)) return null;
1570
+ const port = /sin6?_port=htons\((\d+)\)/.exec(p.args);
1571
+ const v4 = /inet_addr\("([^"]+)"\)/.exec(p.args);
1572
+ const v6 = /inet_pton\(AF_INET6,\s*"([^"]+)"/.exec(p.args);
1573
+ const host = v4?.[1] ?? v6?.[1];
1574
+ if (!host || !port) return null;
1575
+ const portNum = Number(port[1]);
1576
+ return { pid: p.pid, kind: "net", host, port: portNum, protocol: portNum === 53 ? "udp" : "tcp" };
1577
+ }
1578
+ return null;
1579
+ }
1580
+ function unescapeC(s) {
1581
+ return s.replace(/\\(x[0-9a-fA-F]{2}|[0-7]{1,3}|.)/g, (_, e) => {
1582
+ if (e.startsWith("x")) return String.fromCharCode(parseInt(e.slice(1), 16));
1583
+ if (/^[0-7]+$/.test(e)) return String.fromCharCode(parseInt(e, 8));
1584
+ const map = { n: "\n", t: " ", r: "\r", '"': '"', "\\": "\\" };
1585
+ return map[e] ?? e;
1586
+ });
1587
+ }
1588
+ function attachStrace(stream, collector) {
1589
+ let buf = "";
1590
+ stream.setEncoding("utf8");
1591
+ stream.on("data", (chunk) => {
1592
+ buf += chunk;
1593
+ let nl;
1594
+ while ((nl = buf.indexOf("\n")) >= 0) {
1595
+ const line = buf.slice(0, nl);
1596
+ buf = buf.slice(nl + 1);
1597
+ const ev = straceEvent(line);
1598
+ if (!ev) continue;
1599
+ if (ev.kind === "file" && ev.path) {
1600
+ collector.addFile({ source: "strace", pid: ev.pid, path: ev.path, op: "openat" });
1601
+ } else if (ev.kind === "net" && ev.host) {
1602
+ collector.addNet({
1603
+ source: "strace",
1604
+ pid: ev.pid,
1605
+ host: ev.host,
1606
+ port: ev.port ?? 0,
1607
+ protocol: ev.protocol ?? "tcp"
1608
+ });
1609
+ }
1610
+ }
1611
+ });
1612
+ }
1613
+
1614
+ // src/ui/card.ts
1615
+ import * as fs4 from "fs";
1616
+ import * as path6 from "path";
1617
+ import { fileURLToPath } from "url";
1618
+
1619
+ // src/ui/format.ts
1620
+ function fmtBytes(n) {
1621
+ if (!Number.isFinite(n) || n <= 0) return "0 B";
1622
+ if (n < 1024) return `${n} B`;
1623
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
1624
+ if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`;
1625
+ return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GB`;
1626
+ }
1627
+ function fmtDuration(ms) {
1628
+ if (ms < 1e3) return `${Math.round(ms)}ms`;
1629
+ if (ms < 6e4) return `${(ms / 1e3).toFixed(1)}s`;
1630
+ const m = Math.floor(ms / 6e4);
1631
+ const s = Math.round(ms % 6e4 / 1e3);
1632
+ return `${m}m${s.toString().padStart(2, "0")}s`;
1633
+ }
1634
+ function fit(s, max) {
1635
+ if (max <= 0) return "";
1636
+ if (s.length <= max) return s;
1637
+ if (max <= 1) return "\u2026";
1638
+ return s.slice(0, max - 1) + "\u2026";
1639
+ }
1640
+ function fitLeft(s, max) {
1641
+ if (max <= 0) return "";
1642
+ if (s.length <= max) return s;
1643
+ if (max <= 1) return "\u2026";
1644
+ return "\u2026" + s.slice(s.length - (max - 1));
1645
+ }
1646
+ var ANSI_RE = /\u001b\[[0-9;]*m/g;
1647
+ function stripAnsi(s) {
1648
+ return s.replace(ANSI_RE, "");
1649
+ }
1650
+ function visibleWidth(s) {
1651
+ let w = 0;
1652
+ for (const ch of stripAnsi(s)) {
1653
+ const cp = ch.codePointAt(0) ?? 0;
1654
+ if (cp >= 127744 && cp <= 129791 || cp >= 9728 && cp <= 10175 && cp !== 8226 && cp !== 9679 && cp !== 9650 || cp >= 4352 && cp <= 4447 || cp >= 11904 && cp <= 42191 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65072 && cp <= 65103 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510) {
1655
+ w += 2;
1656
+ } else if (cp === 65039 || cp === 8205) {
1657
+ } else {
1658
+ w += 1;
1659
+ }
1660
+ }
1661
+ return w;
1662
+ }
1663
+ function padEndAnsi(s, width) {
1664
+ const w = visibleWidth(s);
1665
+ return w >= width ? s : s + " ".repeat(width - w);
1666
+ }
1667
+ function escapeXml(s) {
1668
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1669
+ }
1670
+ function shellJoin(cmd) {
1671
+ return cmd.map((a) => /^[A-Za-z0-9_@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`).join(" ");
1672
+ }
1673
+
1674
+ // src/ui/scorecard.ts
1675
+ import pc from "picocolors";
1676
+ function gradeBadge(grade) {
1677
+ const label = ` ${grade.padEnd(2, " ")} `;
1678
+ const paint = (s) => {
1679
+ switch (grade) {
1680
+ case "A+":
1681
+ case "A":
1682
+ return pc.bold(pc.bgGreen(pc.black(s)));
1683
+ case "B":
1684
+ return pc.bold(pc.bgCyan(pc.black(s)));
1685
+ case "C":
1686
+ return pc.bold(pc.bgYellow(pc.black(s)));
1687
+ case "D":
1688
+ return pc.bold(pc.bgMagenta(pc.white(s)));
1689
+ default:
1690
+ return pc.bold(pc.bgRed(pc.white(s)));
1691
+ }
1692
+ };
1693
+ return [paint(" "), paint(label.padStart(5, " ").padEnd(6, " ")), paint(" ")];
1694
+ }
1695
+ var CAT_PAINT = {
1696
+ TELEMETRY: pc.red,
1697
+ UNKNOWN: pc.yellow,
1698
+ LLM_API: pc.green,
1699
+ AUTH: pc.cyan
1700
+ };
1701
+ var CAT_DOT = { TELEMETRY: "\u25CF", UNKNOWN: "\u25B2", LLM_API: "\u2713", AUTH: "\u2713" };
1702
+ var CAT_TITLE = { TELEMETRY: "TELEMETRY", UNKNOWN: "OTHER", LLM_API: "LLM API", AUTH: "AUTH" };
1703
+ function renderScorecard(report, opts) {
1704
+ const cols = opts.width ?? Math.min(Math.max(process.stderr.columns || 80, 64), 110);
1705
+ const W = cols - 2;
1706
+ const inner = W - 2;
1707
+ const lines = [];
1708
+ const bar = (n) => "\u2500".repeat(Math.max(0, n));
1709
+ const row = (content) => lines.push(pc.dim("\u2502") + " " + padEndAnsi(content, inner) + " " + pc.dim("\u2502"));
1710
+ const blank = () => row("");
1711
+ const section = (title2) => {
1712
+ const t = ` ${title2} `;
1713
+ lines.push(pc.dim("\u251C\u2500") + pc.bold(t) + pc.dim(bar(W - 2 - visibleWidth(t)) + "\u2524"));
1714
+ };
1715
+ const score = report.score;
1716
+ const g = score.grade;
1717
+ const gradeColor2 = g === "A+" || g === "A" ? pc.green : g === "B" ? pc.cyan : g === "C" || g === "D" ? pc.yellow : pc.red;
1718
+ const title = " NARC \xB7 PRIVACY SCORECARD ";
1719
+ lines.push(pc.dim("\u250C\u2500") + pc.bold(pc.white(title)) + pc.dim(bar(W - 2 - title.length) + "\u2510"));
1720
+ blank();
1721
+ const badge = gradeBadge(g);
1722
+ const leftW = inner - 8;
1723
+ const layersOn = Object.entries(report.layers).filter(([, v]) => v).map(([k]) => k);
1724
+ const status = report.signal ? `killed by ${report.signal}` : `exit ${report.exitCode ?? "?"}`;
1725
+ const left = [
1726
+ pc.bold(pc.white("$ ")) + pc.white(fit(report.commandLabel, leftW - 2)),
1727
+ pc.dim(`${status} \xB7 ${fmtDuration(report.durationMs)} \xB7 layers: ${layersOn.join(", ") || "none"}`),
1728
+ gradeColor2(pc.bold(`score ${score.score}/100`)) + pc.dim(` (${score.deductions.length} deduction${score.deductions.length === 1 ? "" : "s"})`)
1729
+ ];
1730
+ for (let i = 0; i < 3; i++) row(padEndAnsi(left[i] ?? "", leftW) + " " + badge[i]);
1731
+ blank();
1732
+ const sens = report.sensitiveFiles;
1733
+ const tracing = report.fileTracing;
1734
+ section(`SENSITIVE FILES TOUCHED (${sens.length})`);
1735
+ if (tracing.coverage === "none") {
1736
+ row(pc.yellow(`\u26A0 file reads not traced (native binary${tracing.untraced.length ? ": " + describeUntraced(tracing.untraced) : ""} \u2014 run with --deep)`));
1737
+ } else if (!sens.length) {
1738
+ row(pc.green("\u2713 none"));
1739
+ } else {
1740
+ const pathW = Math.min(Math.max(...sens.map((f) => opts.matcher.display(f.path).length)), Math.floor(inner * 0.55));
1741
+ const launcherName = report.launcher?.name ?? "launcher";
1742
+ for (const f of sens) {
1743
+ const ops = Object.entries(f.ops).map(([k, v]) => `${k}\xD7${v}`).join(" ");
1744
+ const disp = fitLeft(opts.matcher.display(f.path), pathW);
1745
+ const quiet = f.ownNamespace || f.launcher || !f.graded;
1746
+ const who = f.procs.length ? ` \xB7 ${f.procs.slice(0, 3).join(", ")}` : "";
1747
+ const tag = f.launcher ? pc.dim(`via ${launcherName} \xB7 not graded`) : !f.graded ? pc.dim(`${f.watch?.label ?? "system"} \xB7 not graded${who}`) : f.ownNamespace ? pc.cyan("OWN CONFIG") + pc.dim(` \xB7 not penalised${who}`) : pc.dim((f.watch?.label ?? "") + who);
1748
+ const mark = f.launcher || !f.graded ? pc.dim("\u25CB") : f.ownNamespace ? pc.cyan("\u25CB") : pc.red("\u25CF");
1749
+ row(`${mark} ${quiet ? pc.dim(disp) : pc.bold(pc.red(disp))}${" ".repeat(Math.max(1, pathW - disp.length + 2))}${tag} ${pc.dim(ops)}`);
1750
+ }
1751
+ }
1752
+ const dots = report.otherDotfiles.length;
1753
+ if (dots) row(pc.dim(` + ${dots} other dotfile${dots === 1 ? "" : "s"} under ~ (see --json)`));
1754
+ if (tracing.coverage === "partial") {
1755
+ row(pc.yellow(`\u26A0 not hooked: ${describeUntraced(tracing.untraced)} \u2014 reads inside those binaries are invisible (run with --deep)`));
1756
+ }
1757
+ const probed = report.probedFiles ?? [];
1758
+ if (probed.length) row(pc.dim(` probed but absent (not graded): ${probed.map((f) => opts.matcher.display(f.path)).join(", ")}`));
1759
+ if (report.leftoverProcesses?.length) row(pc.yellow(`\u26A0 left running after exit, stopped by narc: ${report.leftoverProcesses.join(", ")}`));
1760
+ blank();
1761
+ const hosts = report.hosts;
1762
+ section(`OUTBOUND (${hosts.length} host${hosts.length === 1 ? "" : "s"})`);
1763
+ if (!hosts.length) {
1764
+ row(pc.green("\u2713 no network activity observed"));
1765
+ } else {
1766
+ for (const cat of ["TELEMETRY", "UNKNOWN", "LLM_API", "AUTH"]) {
1767
+ const group = hosts.filter((h) => h.category === cat);
1768
+ if (!group.length) continue;
1769
+ row(CAT_PAINT[cat](pc.bold(CAT_TITLE[cat])) + pc.dim(` (${group.length})`));
1770
+ const hostW = Math.min(Math.max(...group.map((h) => h.host.length)), Math.floor(inner * 0.45));
1771
+ for (const h of group) row(" " + hostRow(h, hostW, inner - 2, report.launcher?.name));
1772
+ }
1773
+ }
1774
+ if (report.suppressedHosts.length) {
1775
+ row(pc.dim(` raw IPs seen only by lsof, likely the hosts above (not graded): ${report.suppressedHosts.map((h) => h.host).join(", ")}`));
1776
+ }
1777
+ blank();
1778
+ if (score.deductions.length) {
1779
+ section("DEDUCTIONS");
1780
+ for (const d of score.deductions) {
1781
+ const label = d.reason === "telemetry-host" ? "telemetry host" : d.reason === "sensitive-file" ? "sensitive file" : "unknown host";
1782
+ row(`${pc.red(pc.bold(String(d.points).padStart(4)))} ${pc.dim(label.padEnd(15))} ${fit(d.detail, inner - 23)}`);
1783
+ }
1784
+ blank();
1785
+ }
1786
+ if (opts.cardPath || opts.jsonPath) {
1787
+ lines.push(pc.dim("\u251C" + bar(W) + "\u2524"));
1788
+ if (opts.cardPath) row(`${pc.dim("PNG ")} ${pc.cyan(opts.cardPath)}`);
1789
+ if (opts.jsonPath) row(`${pc.dim("JSON")} ${pc.cyan(opts.jsonPath)}`);
1790
+ }
1791
+ lines.push(pc.dim("\u2514" + bar(W) + "\u2518"));
1792
+ return lines.join("\n");
1793
+ }
1794
+ function describeUntraced(list) {
1795
+ if (!list.length) return "";
1796
+ return list.length === 1 ? list[0] : `${list[0]} +${list.length - 1} more`;
1797
+ }
1798
+ function hostRow(h, hostW, maxW, launcherName) {
1799
+ const paint = h.launcher ? pc.dim : CAT_PAINT[h.category];
1800
+ const dot = paint(CAT_DOT[h.category]);
1801
+ const host = fit(h.host, hostW).padEnd(hostW);
1802
+ const req = `${h.requests} req`.padStart(8);
1803
+ const bytes = `${fmtBytes(h.bytesOut)} \u2191 ${fmtBytes(h.bytesIn)} \u2193`.padStart(20);
1804
+ const via = h.sources.map((s) => s === "preload" ? "hook" : s).join("+");
1805
+ let extra = "";
1806
+ if (h.paths.length) {
1807
+ const p = h.paths[0];
1808
+ extra = ` ${h.methods[0] ?? ""} ${p}${h.paths.length > 1 ? ` (+${h.paths.length - 1})` : ""}`;
1809
+ }
1810
+ const launcherTag = h.launcher ? pc.dim(` (${launcherName ?? "launcher"} itself, not graded)`) : "";
1811
+ const base = `${dot} ${paint(host)} ${pc.dim(req)} ${pc.dim(bytes)} ${pc.dim(`via ${via}`)}${launcherTag}`;
1812
+ const room = maxW - visibleWidth(base);
1813
+ return base + (room > 8 && extra ? pc.dim(fit(extra, room)) : "");
1814
+ }
1815
+
1816
+ // src/ui/card.ts
1817
+ var CARD_W = 1200;
1818
+ var CARD_H = 675;
1819
+ var M = 56;
1820
+ var PAPER = "#F4F1EA";
1821
+ var INK = "#111111";
1822
+ var MUTED = "#66625B";
1823
+ var RULE = "#D6D1C7";
1824
+ var ROW = "#E6E2D8";
1825
+ var RED = "#D92D20";
1826
+ var GREEN = "#1B6B3A";
1827
+ var SANS = "IBM Plex Sans";
1828
+ var MONO = "IBM Plex Mono";
1829
+ var CH = 0.6;
1830
+ function fontDir() {
1831
+ const here = path6.dirname(fileURLToPath(import.meta.url));
1832
+ for (const cand of [path6.join(here, "..", "assets", "fonts"), path6.join(here, "..", "..", "assets", "fonts")]) {
1833
+ if (fs4.existsSync(cand)) return cand;
1834
+ }
1835
+ return null;
1836
+ }
1837
+ function fontFiles() {
1838
+ const dir = fontDir();
1839
+ if (!dir) return [];
1840
+ return fs4.readdirSync(dir).filter((f) => /\.(ttf|otf)$/i.test(f)).map((f) => path6.join(dir, f)).sort();
1841
+ }
1842
+ function resvgFontOptions() {
1843
+ return {
1844
+ fontFiles: fontFiles(),
1845
+ loadSystemFonts: true,
1846
+ defaultFontFamily: SANS,
1847
+ sansSerifFamily: SANS,
1848
+ monospaceFamily: MONO,
1849
+ serifFamily: SANS
1850
+ };
1851
+ }
1852
+ function text(x, y, s, o) {
1853
+ const attrs = [
1854
+ `x="${x}"`,
1855
+ `y="${y}"`,
1856
+ `font-family="${o.family ?? SANS}"`,
1857
+ `font-size="${o.size}"`,
1858
+ `fill="${o.fill ?? INK}"`
1859
+ ];
1860
+ if (o.weight && o.weight !== 400) attrs.push(`font-weight="${o.weight}"`);
1861
+ if (o.anchor && o.anchor !== "start") attrs.push(`text-anchor="${o.anchor}"`);
1862
+ if (o.italic) attrs.push(`font-style="italic"`);
1863
+ if (o.spacing) attrs.push(`letter-spacing="${o.spacing}"`);
1864
+ return `<text ${attrs.join(" ")}>${escapeXml(o.upper ? s.toUpperCase() : s)}</text>`;
1865
+ }
1866
+ var hr = (x1, x2, y, color = RULE, h = 1) => `<rect x="${x1}" y="${y}" width="${x2 - x1}" height="${h}" fill="${color}"/>`;
1867
+ var vr = (x, y1, y2, color = RULE) => `<rect x="${x}" y="${y1}" width="1" height="${y2 - y1}" fill="${color}"/>`;
1868
+ var monoW = (chars, size) => chars * size * CH;
1869
+ var TAG = { TELEMETRY: "TELEMETRY", UNKNOWN: "OTHER", LLM_API: "LLM", AUTH: "AUTH" };
1870
+ function gradeColor(grade) {
1871
+ if (grade === "A+" || grade === "A" || grade === "B") return GREEN;
1872
+ if (grade === "D" || grade === "F") return RED;
1873
+ return INK;
1874
+ }
1875
+ function commandLine(report) {
1876
+ return "$ " + report.commandLabel;
1877
+ }
1878
+ function renderCardSvg(report, matcher) {
1879
+ const p = [];
1880
+ const R = CARD_W - M;
1881
+ const grade = report.score.grade;
1882
+ const gcol = gradeColor(grade);
1883
+ const tracing = report.fileTracing ?? { mode: "none", coverage: "none", untraced: [] };
1884
+ const launcher = report.launcher?.name ?? "launcher";
1885
+ const date = (report.endedAt || (/* @__PURE__ */ new Date()).toISOString()).slice(0, 10);
1886
+ p.push(`<svg xmlns="http://www.w3.org/2000/svg" width="${CARD_W}" height="${CARD_H}" viewBox="0 0 ${CARD_W} ${CARD_H}">`);
1887
+ p.push(`<rect width="${CARD_W}" height="${CARD_H}" fill="${PAPER}"/>`);
1888
+ const stampW = 120;
1889
+ const stampX = R - stampW;
1890
+ const stampY = M;
1891
+ p.push(text(M, M + 13, `NARCX PRIVACY AUDIT / ${date}`, { size: 13, family: MONO, fill: MUTED, spacing: 1.5, upper: true }));
1892
+ const titleMax = Math.floor((stampX - 24 - M) / (36 * 0.56));
1893
+ p.push(text(M, M + 62, fit(report.title, titleMax), { size: 36, weight: 700 }));
1894
+ const cmdMax = Math.floor((stampX - 24 - M) / (15 * CH));
1895
+ p.push(text(M, M + 92, fit(commandLine(report), cmdMax), { size: 15, family: MONO }));
1896
+ p.push(`<rect x="${stampX + 1}" y="${stampY + 1}" width="${stampW - 2}" height="${stampW - 2}" fill="none" stroke="${gcol}" stroke-width="2"/>`);
1897
+ p.push(text(stampX + stampW / 2, stampY + 88, grade, { size: 76, weight: 700, fill: gcol, anchor: "middle" }));
1898
+ p.push(text(R, stampY + stampW + 22, `${report.score.score} / 100`, { size: 13, family: MONO, fill: MUTED, anchor: "end", spacing: 1 }));
1899
+ const topRuleY = 212;
1900
+ p.push(hr(M, R, topRuleY, INK, 2));
1901
+ const hosts = report.hosts.filter((h) => !h.launcher);
1902
+ const telemetry = hosts.filter((h) => h.category === "TELEMETRY");
1903
+ const other = hosts.filter((h) => h.category === "UNKNOWN");
1904
+ const thirdParty = report.sensitiveFiles.filter((f) => !f.ownNamespace && !f.launcher && f.graded !== false);
1905
+ const untracedFiles = tracing.coverage === "none";
1906
+ const metrics = [
1907
+ { label: "Telemetry hosts", value: String(telemetry.length), hot: telemetry.length > 0 },
1908
+ {
1909
+ label: "3rd-party secrets",
1910
+ value: untracedFiles ? "\u2014" : String(thirdParty.length),
1911
+ hot: !untracedFiles && thirdParty.length > 0,
1912
+ note: untracedFiles ? "not traced" : tracing.coverage === "partial" ? "partial trace" : void 0
1913
+ },
1914
+ { label: "Other outbound", value: String(other.length), hot: false },
1915
+ { label: "Audit mode", value: tracing.mode === "deep" ? "--deep" : "standard", hot: false }
1916
+ ];
1917
+ const stripTop = topRuleY + 14;
1918
+ const stripBottom = 322;
1919
+ const colW = (R - M) / 4;
1920
+ metrics.forEach((m, i) => {
1921
+ const x = M + colW * i + (i === 0 ? 0 : 20);
1922
+ p.push(text(x, stripTop + 16, m.label, { size: 11, family: MONO, fill: MUTED, spacing: 1.5, upper: true }));
1923
+ const isDash = m.value === "\u2014";
1924
+ const isWord = !isDash && Number.isNaN(Number(m.value));
1925
+ const size = isDash ? 40 : isWord ? 30 : 40;
1926
+ p.push(text(x, stripTop + 66, m.value, { size, weight: 700, fill: isDash ? MUTED : m.hot ? RED : INK, family: isWord ? MONO : SANS }));
1927
+ if (m.note) {
1928
+ const valueW = isDash ? 40 : isWord ? monoW(m.value.length, 30) : m.value.length * 40 * 0.58;
1929
+ p.push(text(x + valueW + 14, stripTop + 66, m.note, { size: 12, family: MONO, fill: MUTED, italic: true }));
1930
+ }
1931
+ if (i > 0) p.push(vr(M + colW * i, stripTop, stripBottom));
1932
+ });
1933
+ p.push(hr(M, R, stripBottom + 10));
1934
+ const colTop = 362;
1935
+ const gap = 48;
1936
+ const cw = (R - M - gap) / 2;
1937
+ const lx = M;
1938
+ const rx = M + cw + gap;
1939
+ const rowH = 36;
1940
+ const maxRows = 6;
1941
+ const firstBaseline = colTop + 34;
1942
+ const header = (x, label, right) => {
1943
+ p.push(text(x, colTop, label, { size: 11, family: MONO, fill: MUTED, spacing: 1.5, upper: true }));
1944
+ if (right) p.push(text(x + cw, colTop, right, { size: 11, family: MONO, fill: MUTED, spacing: 1.5, upper: true, anchor: "end" }));
1945
+ p.push(hr(x, x + cw, colTop + 10));
1946
+ };
1947
+ const visibleCount = (n, reserved) => {
1948
+ const slots = maxRows - reserved;
1949
+ return n <= slots ? n : slots - 1;
1950
+ };
1951
+ header(lx, "Outbound hosts", "bytes sent");
1952
+ const orderedHosts = [...hosts, ...report.hosts.filter((h) => h.launcher)];
1953
+ if (!orderedHosts.length) {
1954
+ p.push(text(lx, firstBaseline, "No network activity observed", { size: 15, family: MONO, fill: MUTED, italic: true }));
1955
+ } else {
1956
+ const shownHosts = visibleCount(orderedHosts.length, 0);
1957
+ orderedHosts.slice(0, shownHosts).forEach((h, i) => {
1958
+ const y = firstBaseline + rowH * i;
1959
+ const bytes = fmtBytes(h.bytesOut);
1960
+ const tag = h.launcher ? launcher.toUpperCase() : TAG[h.category];
1961
+ const hot = !h.launcher && h.category === "TELEMETRY";
1962
+ const bytesW = monoW(bytes.length, 13);
1963
+ const tagW = monoW(tag.length, 12) + (hot ? 1 : 0) * tag.length;
1964
+ const tagX = lx + cw - bytesW - 18;
1965
+ const hostMax = Math.floor((tagX - tagW - 16 - lx) / (15 * CH));
1966
+ p.push(text(lx, y, fit(h.host, hostMax), { size: 15, family: MONO, fill: h.launcher ? MUTED : INK }));
1967
+ p.push(text(tagX, y, tag, { size: 12, family: MONO, fill: hot ? RED : MUTED, weight: hot ? 700 : 400, anchor: "end", spacing: 1 }));
1968
+ p.push(text(lx + cw, y, bytes, { size: 13, family: MONO, fill: MUTED, anchor: "end" }));
1969
+ p.push(hr(lx, lx + cw, y + 12, ROW));
1970
+ });
1971
+ if (orderedHosts.length > shownHosts) {
1972
+ p.push(text(lx, firstBaseline + rowH * shownHosts, `+ ${orderedHosts.length - shownHosts} more in the JSON report`, { size: 12, family: MONO, fill: MUTED, italic: true }));
1973
+ }
1974
+ }
1975
+ header(rx, "Files accessed");
1976
+ if (untracedFiles) {
1977
+ const who = tracing.untraced.length ? `: ${describeUntraced(tracing.untraced)}` : "";
1978
+ p.push(text(rx, firstBaseline, fit(`File reads not traced (native binary${who} \u2014 run with --deep)`, Math.floor(cw / (15 * CH))), { size: 15, family: MONO, fill: MUTED, italic: true }));
1979
+ } else {
1980
+ const graded = (f) => f.graded !== false;
1981
+ const files = [
1982
+ ...report.sensitiveFiles.filter((f) => !f.ownNamespace && !f.launcher && graded(f)),
1983
+ ...report.sensitiveFiles.filter((f) => f.ownNamespace && !f.launcher && graded(f)),
1984
+ ...report.sensitiveFiles.filter((f) => f.launcher && graded(f)),
1985
+ ...report.sensitiveFiles.filter((f) => !graded(f))
1986
+ ];
1987
+ const partial = tracing.coverage === "partial";
1988
+ const rowsAvail = visibleCount(files.length, partial ? 1 : 0);
1989
+ if (!files.length) {
1990
+ p.push(text(rx, firstBaseline, "No watchlist files read", { size: 15, family: MONO, fill: MUTED, italic: true }));
1991
+ } else {
1992
+ files.slice(0, rowsAvail).forEach((f, i) => {
1993
+ const y = firstBaseline + rowH * i;
1994
+ const tag = f.graded === false ? "TRUST STORE" : f.launcher ? launcher.toUpperCase() : f.ownNamespace ? "OWN" : "3RD-PARTY";
1995
+ const hot = !f.launcher && !f.ownNamespace && f.graded !== false;
1996
+ const tagW = monoW(tag.length, 12);
1997
+ const pathMax = Math.floor((cw - tagW - 24) / (15 * CH));
1998
+ p.push(text(rx, y, fitLeft(matcher.display(f.path), pathMax), { size: 15, family: MONO, fill: hot ? INK : MUTED }));
1999
+ p.push(text(rx + cw, y, tag, { size: 12, family: MONO, fill: hot ? RED : MUTED, weight: hot ? 700 : 400, anchor: "end", spacing: 1 }));
2000
+ p.push(hr(rx, rx + cw, y + 12, ROW));
2001
+ });
2002
+ if (files.length > rowsAvail) {
2003
+ p.push(text(rx, firstBaseline + rowH * rowsAvail, `+ ${files.length - rowsAvail} more in the JSON report`, { size: 12, family: MONO, fill: MUTED, italic: true }));
2004
+ }
2005
+ }
2006
+ if (partial) {
2007
+ const y = firstBaseline + rowH * (maxRows - 1);
2008
+ const msg = `Not hooked: ${describeUntraced(tracing.untraced)} \xB7 needs --deep`;
2009
+ p.push(text(rx, y, fit(msg, Math.floor(cw / (13 * CH))), { size: 13, family: MONO, fill: MUTED, italic: true }));
2010
+ }
2011
+ }
2012
+ const footRule = 595;
2013
+ p.push(hr(M, R, footRule));
2014
+ p.push(text(M, footRule + 24, "out-of-the-box defaults \xB7 no TLS interception \xB7 zero auditor network calls", { size: 12, family: MONO, fill: MUTED }));
2015
+ p.push(text(R, footRule + 24, "npx narcx", { size: 15, family: MONO, weight: 700, anchor: "end" }));
2016
+ p.push("</svg>");
2017
+ return p.join("\n");
2018
+ }
2019
+ async function writeCardPng(report, matcher, outPath) {
2020
+ const svg = renderCardSvg(report, matcher);
2021
+ const { Resvg } = await import("@resvg/resvg-js");
2022
+ const resvg = new Resvg(svg, {
2023
+ fitTo: { mode: "width", value: CARD_W },
2024
+ background: PAPER,
2025
+ font: resvgFontOptions()
2026
+ });
2027
+ const png = resvg.render().asPng();
2028
+ const abs = path6.resolve(outPath);
2029
+ fs4.mkdirSync(path6.dirname(abs), { recursive: true });
2030
+ fs4.writeFileSync(abs, png);
2031
+ return abs;
2032
+ }
2033
+
2034
+ // src/ui/live.ts
2035
+ import pc2 from "picocolors";
2036
+ var TAG_HIGH = pc2.bold(pc2.red("[NARC \u{1F6A8}]"));
2037
+ var TAG_WARN = pc2.bold(pc2.yellow("[NARC \u26A0\uFE0F ]"));
2038
+ var TAG_INFO = pc2.dim("[NARC \xB7\xB7]");
2039
+ function netLine(ev) {
2040
+ const target = ev.url ?? `${ev.host}:${ev.port}`;
2041
+ const method = ev.method ? ev.method + " " : "";
2042
+ const via = ev.source === "preload" ? "hook" : ev.source;
2043
+ const pid = ev.pid ? ` pid ${ev.pid}` : "";
2044
+ const bytes = ev.bytesOut ? ` ${fmtBytes(ev.bytesOut)}\u2191` : "";
2045
+ return `${method}${target}${bytes} ${pc2.dim(`(${ev.protocol} \xB7 via ${via}${pid})`)}`;
2046
+ }
2047
+ function attachLiveFeed(collector, opts) {
2048
+ if (opts.quiet) return;
2049
+ const out = opts.out ?? process.stderr;
2050
+ const write = (s) => out.write(s + "\n");
2051
+ collector.on("alert", (a) => {
2052
+ if (a.launcher) {
2053
+ if (opts.verbose) {
2054
+ const what = a.kind === "file" ? a.display : netLine(a.event);
2055
+ write(`${TAG_INFO} ${pc2.dim("launcher")} ${what} ${pc2.dim("(not graded)")}`);
2056
+ }
2057
+ return;
2058
+ }
2059
+ if (a.kind === "file") {
2060
+ if (a.level === "high") {
2061
+ const pid = a.event.pid ? ` \xB7 pid ${a.event.pid}` : "";
2062
+ write(
2063
+ `${TAG_HIGH} ${pc2.red(pc2.bold("READ"))} ${pc2.bold(a.display)} ${pc2.dim(
2064
+ `(${a.watch.label} \xB7 ${a.event.op}${pid})`
2065
+ )}`
2066
+ );
2067
+ } else if (opts.verbose) {
2068
+ write(`${TAG_INFO} ${pc2.dim("dotfile")} ${a.display} ${pc2.dim(`(${a.event.op})`)}`);
2069
+ }
2070
+ return;
2071
+ }
2072
+ const ev = a.event;
2073
+ if (a.level === "high") {
2074
+ write(`${TAG_HIGH} ${pc2.red(pc2.bold("TELEMETRY"))} ${netLine(ev)}`);
2075
+ } else if (a.level === "warn") {
2076
+ write(`${TAG_WARN} ${pc2.yellow(pc2.bold("UNKNOWN HOST"))} ${netLine(ev)}`);
2077
+ } else if (opts.verbose) {
2078
+ write(`${TAG_INFO} ${pc2.green("llm api")} ${netLine(ev)}`);
2079
+ }
2080
+ });
2081
+ if (opts.verbose) {
2082
+ collector.on("request", (ev) => {
2083
+ if (ev.category === "LLM_API") return;
2084
+ const color = ev.category === "TELEMETRY" ? pc2.red : pc2.yellow;
2085
+ write(`${TAG_INFO} ${color("\u21B3")} ${netLine(ev)}`);
2086
+ });
2087
+ }
2088
+ }
2089
+
2090
+ // src/cli.ts
2091
+ var VERSION = package_default.version;
2092
+ var DIST_DIR = path7.dirname(fileURLToPath2(import.meta.url));
2093
+ var HELP = `
2094
+ ${pc3.bold("narc")} ${pc3.dim("v" + VERSION)} \u2014 catch any CLI, AI harness or MCP server phoning home or reading your dotfiles.
2095
+
2096
+ ${pc3.bold("USAGE")}
2097
+ narc [options] -- <command> [args...]
2098
+ narc --demo [--card ./report.png]
2099
+ ${pc3.dim("(npm package: narcx \u2014 run without installing via")} npx narcx -- <command>${pc3.dim(")")}
2100
+
2101
+ ${pc3.bold("OPTIONS")}
2102
+ --card [path] Save a 1200x675 Privacy Scorecard PNG (editorial audit sheet) (default ./narc-report.png)
2103
+ --json [path] Export the raw audit log as JSON (default ./narc-report.json)
2104
+ --deep Kernel-level tracing: fs_usage on macOS (asks for sudo), strace -f on Linux
2105
+ --demo Run the built-in mock "shady-ai-tool" to see every layer fire
2106
+ --render <json> Re-render the scorecard (terminal + --card PNG) from a saved --json report
2107
+ --regrade <json> Rebuild a saved report's summaries and grade from its events under the current rules (writes it back)
2108
+ --title <text> Display name for the scorecard, e.g. "Claude Code 2.1.323" (default: command basename)
2109
+ -v, --verbose Also show LLM API traffic, dotfile reads and repeat requests live
2110
+ -q, --quiet No live alerts, only the exit scorecard
2111
+ --no-lsof Disable the lsof socket poller
2112
+ --interval <ms> lsof poll interval (default 150)
2113
+ -h, --help Show this help
2114
+ -V, --version Print version
2115
+
2116
+ ${pc3.bold("LAYERS")} ${pc3.dim("(all work without sudo)")}
2117
+ 1. HTTP/HTTPS CONNECT proxy on 127.0.0.1, injected via HTTP(S)_PROXY / ALL_PROXY \u2014 logs host, method, path, bytes. TLS is never broken.
2118
+ 2. NODE_OPTIONS preload hook \u2014 patches fs.*, http(s).request and fetch inside Node children for exact URLs and file paths.
2119
+ 3. lsof -i poller on the child's process tree \u2014 catches Go/Rust/Python binaries that ignore proxy env vars.
2120
+
2121
+ ${pc3.bold("GRADING")}
2122
+ 100 points, then: \u221225 per telemetry host, \u221230 per sensitive file read outside the tool's own namespace, \u221210 per unknown host.
2123
+ A+ 100 \xB7 A 90+ \xB7 B 80+ \xB7 C 65+ \xB7 D 50+ \xB7 F below 50
2124
+
2125
+ ${pc3.bold("EXAMPLES")}
2126
+ narc -- npx some-ai-cli --help
2127
+ narc --card --json -- claude -p "hello"
2128
+ narc --deep -- ./my-go-binary serve
2129
+ `;
2130
+ function parseArgs(argv) {
2131
+ const o = {
2132
+ card: null,
2133
+ json: null,
2134
+ deep: false,
2135
+ demo: false,
2136
+ render: null,
2137
+ regrade: null,
2138
+ title: null,
2139
+ quiet: false,
2140
+ verbose: false,
2141
+ lsof: true,
2142
+ interval: 150,
2143
+ command: []
2144
+ };
2145
+ let i = 0;
2146
+ const optionalPath = (def) => {
2147
+ const next = argv[i + 1];
2148
+ if (next !== void 0 && next !== "--" && !next.startsWith("-")) {
2149
+ i++;
2150
+ return next;
2151
+ }
2152
+ return def;
2153
+ };
2154
+ for (; i < argv.length; i++) {
2155
+ const a = argv[i];
2156
+ if (a === "--") {
2157
+ o.command = argv.slice(i + 1);
2158
+ break;
2159
+ }
2160
+ if (a === "--card") o.card = optionalPath("./narc-report.png");
2161
+ else if (a.startsWith("--card=")) o.card = a.slice(7);
2162
+ else if (a === "--json") o.json = optionalPath("./narc-report.json");
2163
+ else if (a.startsWith("--json=")) o.json = a.slice(7);
2164
+ else if (a === "--deep") o.deep = true;
2165
+ else if (a === "--demo") o.demo = true;
2166
+ else if (a === "--render") o.render = argv[++i] ?? fail("--render needs a path to a narc JSON report");
2167
+ else if (a.startsWith("--render=")) o.render = a.slice(9);
2168
+ else if (a === "--regrade") o.regrade = argv[++i] ?? fail("--regrade needs a path to a narc JSON report");
2169
+ else if (a.startsWith("--regrade=")) o.regrade = a.slice(10);
2170
+ else if (a === "--title") o.title = argv[++i] ?? fail("--title needs a value");
2171
+ else if (a.startsWith("--title=")) o.title = a.slice(8);
2172
+ else if (a === "-q" || a === "--quiet") o.quiet = true;
2173
+ else if (a === "-v" || a === "--verbose") o.verbose = true;
2174
+ else if (a === "--no-lsof") o.lsof = false;
2175
+ else if (a === "--interval") o.interval = Math.max(50, Number(argv[++i]) || 150);
2176
+ else if (a.startsWith("--interval=")) o.interval = Math.max(50, Number(a.slice(11)) || 150);
2177
+ else if (a === "-h" || a === "--help") {
2178
+ process.stdout.write(HELP + "\n");
2179
+ process.exit(0);
2180
+ } else if (a === "-V" || a === "--version") {
2181
+ process.stdout.write(VERSION + "\n");
2182
+ process.exit(0);
2183
+ } else if (a.startsWith("-")) {
2184
+ fail(`unknown option ${a}`);
2185
+ } else {
2186
+ o.command = argv.slice(i);
2187
+ break;
2188
+ }
2189
+ }
2190
+ return o;
2191
+ }
2192
+ function fail(msg, code = 2) {
2193
+ process.stderr.write(`${pc3.red(pc3.bold("narc:"))} ${msg}
2194
+ `);
2195
+ process.exit(code);
2196
+ }
2197
+ var log = (s) => process.stderr.write(`${pc3.dim("[narc]")} ${s}
2198
+ `);
2199
+ function sudoDrop() {
2200
+ if (typeof process.getuid !== "function" || process.getuid() !== 0) return null;
2201
+ const user = process.env.SUDO_USER;
2202
+ if (!user || user === "root") return null;
2203
+ try {
2204
+ const uid = Number(execFileSync2("id", ["-u", user], { encoding: "utf8" }).trim());
2205
+ const gid = Number(execFileSync2("id", ["-g", user], { encoding: "utf8" }).trim());
2206
+ let home = "";
2207
+ if (process.platform === "darwin") {
2208
+ const out = execFileSync2("dscl", [".", "-read", `/Users/${user}`, "NFSHomeDirectory"], { encoding: "utf8" });
2209
+ home = out.replace("NFSHomeDirectory:", "").trim();
2210
+ } else {
2211
+ const out = execFileSync2("getent", ["passwd", user], { encoding: "utf8" });
2212
+ home = out.split(":")[5] ?? "";
2213
+ }
2214
+ if (!home) home = path7.join(process.platform === "darwin" ? "/Users" : "/home", user);
2215
+ return { uid, gid, home, user };
2216
+ } catch {
2217
+ return null;
2218
+ }
2219
+ }
2220
+ function loadReport(file, opts) {
2221
+ const src = path7.resolve(file);
2222
+ let report;
2223
+ try {
2224
+ report = JSON.parse(fs5.readFileSync(src, "utf8"));
2225
+ } catch (e) {
2226
+ fail(`cannot read report ${src}: ${e.message}`);
2227
+ }
2228
+ if (!report.score || !Array.isArray(report.hosts)) fail(`${src} is not a narc JSON report`);
2229
+ report.title = opts.title ?? report.title ?? path7.basename(report.command[0] ?? "narc");
2230
+ report.suppressedHosts ??= [];
2231
+ report.probedFiles ??= [];
2232
+ report.leftoverProcesses ??= [];
2233
+ report.fileTracing ??= {
2234
+ mode: report.layers.fs_usage || report.layers.strace ? "deep" : report.layers.preload ? "hook" : "none",
2235
+ coverage: report.layers.fs_usage || report.layers.strace ? "full" : report.layers.preload ? "partial" : "none",
2236
+ untraced: []
2237
+ };
2238
+ for (const f of [...report.sensitiveFiles, ...report.otherDotfiles, ...report.probedFiles]) {
2239
+ f.procs ??= [];
2240
+ f.graded ??= true;
2241
+ }
2242
+ return { src, report };
2243
+ }
2244
+ async function regradeFromJson(opts) {
2245
+ const { src, report } = loadReport(opts.regrade, opts);
2246
+ const matcher = new SensitiveMatcher(process.env.NARC_HOME || os3.homedir());
2247
+ const collector = new Collector({ matcher, ownNamespaces: ownNamespaces(report.command) });
2248
+ if (report.launcher) collector.setLauncher(report.launcher.pid, report.launcher.name);
2249
+ const procsByPath = /* @__PURE__ */ new Map();
2250
+ for (const f of [...report.sensitiveFiles, ...report.otherDotfiles, ...report.probedFiles]) {
2251
+ if (f.procs?.length) procsByPath.set(matcher.normalize(f.path), f.procs);
2252
+ }
2253
+ const before = report.score;
2254
+ for (const e of report.events) {
2255
+ if (e.kind === "file") {
2256
+ const procs = e.proc ? [e.proc] : procsByPath.get(matcher.normalize(e.path)) ?? [];
2257
+ collector.addFile({ source: e.source, pid: e.pid, path: e.path, op: e.op, exists: e.exists, proc: procs, id: e.id, ts: e.ts });
2258
+ } else if (e.kind === "net") {
2259
+ collector.addNet({ ...e, id: e.id, ts: e.ts });
2260
+ } else if (e.kind === "dns") {
2261
+ collector.addDns({ source: e.source, pid: e.pid, host: e.host, addresses: e.addresses, id: e.id });
2262
+ }
2263
+ }
2264
+ report.sensitiveFiles = collector.sensitiveFiles();
2265
+ report.otherDotfiles = collector.otherDotfiles();
2266
+ report.probedFiles = collector.probedFiles();
2267
+ report.hosts = collector.hostSummaries();
2268
+ report.suppressedHosts = collector.suppressedHosts();
2269
+ report.score = collector.score();
2270
+ report.regradedAt = (/* @__PURE__ */ new Date()).toISOString();
2271
+ report.regradedWith = VERSION;
2272
+ fs5.writeFileSync(src, JSON.stringify(report, null, 2));
2273
+ log(`regraded ${relative2(src)}: ${before.grade} (${before.score}) \u2192 ${report.score.grade} (${report.score.score})`);
2274
+ let cardPath = null;
2275
+ if (opts.card) cardPath = await writeCardPng(report, matcher, opts.card);
2276
+ if (!opts.quiet) {
2277
+ process.stderr.write("\n" + renderScorecard(report, { matcher, cardPath: cardPath && relative2(cardPath), jsonPath: relative2(src) }) + "\n");
2278
+ }
2279
+ process.exit(0);
2280
+ }
2281
+ async function renderFromJson(opts) {
2282
+ const { src, report } = loadReport(opts.render, opts);
2283
+ const matcher = new SensitiveMatcher(process.env.NARC_HOME || os3.homedir());
2284
+ let cardPath = null;
2285
+ if (opts.card) cardPath = await writeCardPng(report, matcher, opts.card);
2286
+ if (!opts.quiet) {
2287
+ process.stderr.write("\n" + renderScorecard(report, { matcher, cardPath: cardPath && relative2(cardPath), jsonPath: relative2(src) }) + "\n");
2288
+ }
2289
+ process.exit(0);
2290
+ }
2291
+ async function main() {
2292
+ const opts = parseArgs(process.argv.slice(2));
2293
+ if (opts.render) return renderFromJson(opts);
2294
+ if (opts.regrade) return regradeFromJson(opts);
2295
+ if (!opts.demo && !opts.command.length) {
2296
+ process.stdout.write(HELP + "\n");
2297
+ process.exit(2);
2298
+ }
2299
+ const tmpDir = fs5.mkdtempSync(path7.join(os3.tmpdir(), "narc-"));
2300
+ const cleanups = [];
2301
+ const cleanupSync = () => {
2302
+ try {
2303
+ fs5.rmSync(tmpDir, { recursive: true, force: true });
2304
+ } catch {
2305
+ }
2306
+ };
2307
+ process.on("exit", cleanupSync);
2308
+ const drop = sudoDrop();
2309
+ let demo = null;
2310
+ let home = drop?.home ?? os3.homedir();
2311
+ let command = opts.command;
2312
+ let cwd = process.cwd();
2313
+ const childEnv = { ...process.env };
2314
+ if (opts.demo) {
2315
+ demo = await setupDemo(tmpDir, DIST_DIR);
2316
+ cleanups.push(() => demo.close());
2317
+ home = demo.home;
2318
+ command = demo.command;
2319
+ cwd = demo.cwd;
2320
+ Object.assign(childEnv, demo.env);
2321
+ log(`${pc3.bold("demo mode")} \u2014 decoy HOME at ${pc3.cyan(home)}, every "vendor" is a loopback sink. Nothing leaves this machine.`);
2322
+ }
2323
+ const matcher = new SensitiveMatcher(home);
2324
+ const collector = new Collector({ matcher, ownNamespaces: ownNamespaces(command) });
2325
+ attachLiveFeed(collector, { quiet: opts.quiet, verbose: opts.verbose });
2326
+ const [ipc, proxy] = await Promise.all([startIpc(collector, tmpDir), startProxy({ collector, resolveUpstream: demo?.resolveUpstream })]);
2327
+ cleanups.push(() => ipc.close(), () => proxy.close());
2328
+ const preloadSrc = path7.join(DIST_DIR, "preload.cjs");
2329
+ const preloadPath = path7.join(tmpDir, "narc-preload.cjs");
2330
+ fs5.copyFileSync(preloadSrc, preloadPath);
2331
+ if (drop) fs5.chmodSync(preloadPath, 420);
2332
+ Object.assign(childEnv, proxyEnv(proxy.port));
2333
+ const existingNodeOpts = process.env.NODE_OPTIONS ? process.env.NODE_OPTIONS + " " : "";
2334
+ childEnv.NODE_OPTIONS = `${existingNodeOpts}--require "${preloadPath}"`;
2335
+ childEnv.NARC_SOCK = ipc.address;
2336
+ childEnv.NARC_PROXY_PORT = String(proxy.port);
2337
+ if (!childEnv.NARC_HOME) childEnv.NARC_HOME = home;
2338
+ if (drop) {
2339
+ childEnv.HOME = drop.home;
2340
+ childEnv.USER = drop.user;
2341
+ childEnv.LOGNAME = drop.user;
2342
+ delete childEnv.SUDO_USER;
2343
+ delete childEnv.SUDO_UID;
2344
+ delete childEnv.SUDO_GID;
2345
+ delete childEnv.SUDO_COMMAND;
2346
+ }
2347
+ const tree = new PidTree(0, opts.interval);
2348
+ let spawnCommand = command;
2349
+ let useStrace = false;
2350
+ let fsUsage = null;
2351
+ const layers = { proxy: true, preload: false, lsof: false };
2352
+ if (opts.deep) {
2353
+ if (process.platform === "linux") {
2354
+ if (straceAvailable()) {
2355
+ useStrace = true;
2356
+ spawnCommand = straceWrap(command);
2357
+ log(`deep mode: tracing openat/connect with ${pc3.bold("strace -f")}`);
2358
+ } else {
2359
+ log(pc3.yellow("deep mode requested but strace is unavailable (not installed or ptrace blocked); continuing without it"));
2360
+ }
2361
+ } else if (process.platform === "darwin") {
2362
+ const asRoot = typeof process.getuid === "function" && process.getuid() === 0;
2363
+ let ok = asRoot || sudoCached();
2364
+ if (!ok && process.stdin.isTTY) {
2365
+ log(`deep mode: ${pc3.bold("fs_usage")} needs root for kernel tracing. Asking sudo once; the traced command itself runs as you.`);
2366
+ ok = sudoValidate("[narc] sudo password for fs_usage: ");
2367
+ } else if (!ok) {
2368
+ log(pc3.yellow("deep mode: sudo needs a password but there is no terminal to ask on (sudo tickets are per-tty); continuing without fs_usage"));
2369
+ }
2370
+ if (ok) {
2371
+ fsUsage = startFsUsage({ collector, tree, home, asRoot });
2372
+ cleanups.unshift(() => fsUsage?.stop());
2373
+ await new Promise((r) => setTimeout(r, 400));
2374
+ layers.fs_usage = true;
2375
+ } else {
2376
+ log(pc3.yellow("sudo not granted; continuing without fs_usage"));
2377
+ }
2378
+ } else {
2379
+ log(pc3.yellow(`deep mode is not available on ${process.platform}`));
2380
+ }
2381
+ }
2382
+ const startedAt = Date.now();
2383
+ let child;
2384
+ try {
2385
+ child = spawn2(spawnCommand[0], spawnCommand.slice(1), {
2386
+ stdio: useStrace ? ["inherit", "inherit", "inherit", "pipe"] : "inherit",
2387
+ env: childEnv,
2388
+ cwd,
2389
+ uid: drop?.uid,
2390
+ gid: drop?.gid
2391
+ });
2392
+ } catch (e) {
2393
+ fail(`failed to start ${command[0]}: ${e.message}`, 127);
2394
+ }
2395
+ if (useStrace && child.stdio[3]) attachStrace(child.stdio[3], collector);
2396
+ const spawnError = new Promise((resolve4) => {
2397
+ child.once("error", (e) => resolve4(e));
2398
+ child.once("spawn", () => resolve4(null));
2399
+ });
2400
+ const err = await spawnError;
2401
+ if (err) {
2402
+ const code2 = err.code;
2403
+ await runCleanups(cleanups);
2404
+ fail(code2 === "ENOENT" ? `command not found: ${command[0]}` : `failed to start ${command[0]}: ${err.message}`, 127);
2405
+ }
2406
+ const launcherName = launcherOf(command);
2407
+ if (launcherName) collector.setLauncher(child.pid, launcherName);
2408
+ const rootName = path7.basename(command[0] ?? "");
2409
+ collector.setProcessResolver((pid) => pid === child.pid ? rootName : tree.nameOf(pid));
2410
+ tree.setRoot(child.pid);
2411
+ tree.start();
2412
+ cleanups.unshift(() => tree.stop());
2413
+ let lsof = null;
2414
+ if (opts.lsof && (process.platform === "darwin" || process.platform === "linux")) {
2415
+ lsof = startLsofPoller({ collector, tree, intervalMs: opts.interval });
2416
+ cleanups.unshift(() => lsof?.stop());
2417
+ }
2418
+ let interrupts = 0;
2419
+ const forward = (sig) => {
2420
+ if (child.exitCode !== null || child.signalCode !== null) return;
2421
+ interrupts++;
2422
+ try {
2423
+ child.kill(interrupts >= 2 ? "SIGKILL" : sig);
2424
+ } catch {
2425
+ }
2426
+ };
2427
+ process.on("SIGINT", () => forward("SIGINT"));
2428
+ process.on("SIGTERM", () => forward("SIGTERM"));
2429
+ process.on("SIGHUP", () => forward("SIGHUP"));
2430
+ const { code, signal } = await new Promise((resolve4) => {
2431
+ child.once("close", (c, s) => resolve4({ code: c, signal: s }));
2432
+ });
2433
+ const endedAt = Date.now();
2434
+ await new Promise((r) => setTimeout(r, Math.min(300, opts.interval + 100)));
2435
+ await tree.refresh();
2436
+ const leftovers = tree.leftovers();
2437
+ const leftoverProcesses = leftovers.map((p) => PidTree.displayName(p));
2438
+ if (leftovers.length) {
2439
+ for (const p of leftovers) {
2440
+ try {
2441
+ process.kill(p.pid, "SIGTERM");
2442
+ } catch {
2443
+ }
2444
+ }
2445
+ await new Promise((r) => setTimeout(r, 600));
2446
+ await tree.refresh();
2447
+ for (const p of tree.leftovers()) {
2448
+ try {
2449
+ process.kill(p.pid, "SIGKILL");
2450
+ } catch {
2451
+ }
2452
+ }
2453
+ log(pc3.yellow(`stopped ${leftovers.length} process${leftovers.length === 1 ? "" : "es"} the tool left running: ${[...new Set(leftoverProcesses)].join(", ")}`));
2454
+ }
2455
+ await runCleanups(cleanups);
2456
+ layers.preload = ipc.hookedPids.size > 0;
2457
+ layers.lsof = Boolean(lsof && lsof.polls > 0);
2458
+ if (useStrace) layers.strace = true;
2459
+ const fileTracing = computeFileTracing({
2460
+ deep: Boolean(layers.fs_usage || layers.strace),
2461
+ hooked: ipc.hookedPids,
2462
+ seen: tree.seenProcesses(),
2463
+ childPid: child.pid,
2464
+ command
2465
+ });
2466
+ for (const e of collector.events) {
2467
+ if (e.kind === "file" && !e.proc && e.pid !== void 0) e.proc = e.pid === child.pid ? rootName : tree.nameOf(e.pid);
2468
+ }
2469
+ const report = {
2470
+ narcVersion: VERSION,
2471
+ title: opts.title ?? (demo ? "shady-ai-tool" : path7.basename(command[0] ?? "narc")),
2472
+ platform: `${process.platform}-${process.arch}`,
2473
+ command,
2474
+ commandLabel: demo ? "shady-ai-tool (narc --demo fixture)" : shellJoin(displayCommand(command, matcher.homes)),
2475
+ startedAt: new Date(startedAt).toISOString(),
2476
+ endedAt: new Date(endedAt).toISOString(),
2477
+ durationMs: endedAt - startedAt,
2478
+ exitCode: code,
2479
+ signal,
2480
+ layers,
2481
+ launcher: launcherName ? { pid: child.pid, name: launcherName } : null,
2482
+ fileTracing,
2483
+ score: collector.score(),
2484
+ sensitiveFiles: collector.sensitiveFiles(),
2485
+ otherDotfiles: collector.otherDotfiles(),
2486
+ probedFiles: collector.probedFiles(),
2487
+ hosts: collector.hostSummaries(),
2488
+ suppressedHosts: collector.suppressedHosts(),
2489
+ leftoverProcesses: [...new Set(leftoverProcesses)],
2490
+ events: collector.events
2491
+ };
2492
+ let cardPath = null;
2493
+ let jsonPath = null;
2494
+ if (opts.json) {
2495
+ jsonPath = path7.resolve(opts.json);
2496
+ fs5.mkdirSync(path7.dirname(jsonPath), { recursive: true });
2497
+ fs5.writeFileSync(jsonPath, JSON.stringify(report, null, 2));
2498
+ }
2499
+ if (opts.card) {
2500
+ try {
2501
+ cardPath = await writeCardPng(report, matcher, opts.card);
2502
+ } catch (e) {
2503
+ log(pc3.yellow(`could not render PNG scorecard: ${e.message}`));
2504
+ }
2505
+ }
2506
+ process.stderr.write("\n" + renderScorecard(report, { matcher, cardPath: cardPath && relative2(cardPath), jsonPath: jsonPath && relative2(jsonPath) }) + "\n");
2507
+ if (signal) {
2508
+ const n = os3.constants.signals[signal] ?? 1;
2509
+ process.exit(128 + n);
2510
+ }
2511
+ process.exit(code ?? 1);
2512
+ }
2513
+ var UTILITIES = /* @__PURE__ */ new Set([
2514
+ "sh",
2515
+ "bash",
2516
+ "zsh",
2517
+ "fish",
2518
+ "dash",
2519
+ "env",
2520
+ "git",
2521
+ "ps",
2522
+ "lsof",
2523
+ "uname",
2524
+ "sw_vers",
2525
+ "which",
2526
+ "whoami",
2527
+ "id",
2528
+ "cat",
2529
+ "ls",
2530
+ "sed",
2531
+ "awk",
2532
+ "grep",
2533
+ "tr",
2534
+ "head",
2535
+ "tail",
2536
+ "mkdir",
2537
+ "rm",
2538
+ "cp",
2539
+ "mv",
2540
+ "ln",
2541
+ "chmod",
2542
+ "touch",
2543
+ "sleep",
2544
+ "tee",
2545
+ "cut",
2546
+ "sort",
2547
+ "uniq",
2548
+ "wc",
2549
+ "date",
2550
+ "hostname",
2551
+ "xcrun",
2552
+ "xcode-select",
2553
+ "security",
2554
+ "osascript",
2555
+ "defaults",
2556
+ "launchctl",
2557
+ "sysctl",
2558
+ "ioreg",
2559
+ "system_profiler",
2560
+ "pbcopy",
2561
+ "pbpaste",
2562
+ "script",
2563
+ "stty",
2564
+ "tput",
2565
+ "open",
2566
+ "xdg-open",
2567
+ "python3",
2568
+ "python",
2569
+ "perl",
2570
+ "ruby",
2571
+ "curl",
2572
+ "wget"
2573
+ ]);
2574
+ var MAGIC = /* @__PURE__ */ new Set([4277009102, 4277009103, 3472551422, 3489328638, 3405691582, 3199925962, 2135247942]);
2575
+ function isNativeExecutable(exe) {
2576
+ if (!path7.isAbsolute(exe)) return false;
2577
+ try {
2578
+ const fd = fs5.openSync(exe, "r");
2579
+ const b = Buffer.alloc(4);
2580
+ const n = fs5.readSync(fd, b, 0, 4, 0);
2581
+ fs5.closeSync(fd);
2582
+ return n === 4 && MAGIC.has(b.readUInt32BE(0));
2583
+ } catch {
2584
+ return false;
2585
+ }
2586
+ }
2587
+ function computeFileTracing(input) {
2588
+ if (input.deep) return { mode: "deep", coverage: "full", untraced: [] };
2589
+ const untraced = /* @__PURE__ */ new Set();
2590
+ for (const p of input.seen) {
2591
+ if (input.hooked.has(p.pid)) continue;
2592
+ const exe = p.comm.split(" ")[0] ?? "";
2593
+ const base = PidTree.displayName(p);
2594
+ if (UTILITIES.has(base) || UTILITIES.has(path7.basename(exe))) continue;
2595
+ if (!isNativeExecutable(exe)) continue;
2596
+ untraced.add(p.pid === input.childPid ? path7.basename(input.command[0] ?? base) : base);
2597
+ }
2598
+ const mode = input.hooked.size > 0 ? "hook" : "none";
2599
+ const coverage = mode === "none" ? "none" : untraced.size ? "partial" : "full";
2600
+ return { mode, coverage, untraced: [...untraced] };
2601
+ }
2602
+ var RUNNERS = /* @__PURE__ */ new Set(["npx", "pnpx", "bunx", "uvx", "pipx"]);
2603
+ function launcherOf(cmd) {
2604
+ const base = path7.basename(cmd[0] ?? "").toLowerCase();
2605
+ const sub = (cmd[1] ?? "").toLowerCase();
2606
+ if (RUNNERS.has(base)) return base;
2607
+ if (base === "npm" && (sub === "exec" || sub === "x")) return `npm ${sub}`;
2608
+ if (base === "pnpm" && sub === "dlx") return "pnpm dlx";
2609
+ if (base === "yarn" && sub === "dlx") return "yarn dlx";
2610
+ if (base === "bun" && sub === "x") return "bun x";
2611
+ return null;
2612
+ }
2613
+ var INTERPRETERS = /* @__PURE__ */ new Set(["node", "nodejs", "python", "python3", "ruby", "deno", "bun", "perl", "php", "sh", "bash", "zsh"]);
2614
+ function displayCommand(cmd, homes) {
2615
+ const out = cmd.map((tok) => {
2616
+ for (const h of homes) {
2617
+ if (tok === h) return "~";
2618
+ if (tok.startsWith(h + path7.sep)) return "~" + tok.slice(h.length);
2619
+ }
2620
+ return tok;
2621
+ });
2622
+ const first = cmd[0];
2623
+ if (first && path7.isAbsolute(first) && INTERPRETERS.has(path7.basename(first))) out[0] = path7.basename(first);
2624
+ return out;
2625
+ }
2626
+ function relative2(p) {
2627
+ const r = path7.relative(process.cwd(), p);
2628
+ return r.startsWith("..") ? p : "./" + r;
2629
+ }
2630
+ async function runCleanups(cleanups) {
2631
+ const list = cleanups.splice(0, cleanups.length);
2632
+ for (const fn of list) {
2633
+ try {
2634
+ await fn();
2635
+ } catch {
2636
+ }
2637
+ }
2638
+ }
2639
+ main().catch((e) => {
2640
+ fail(e.stack ?? String(e), 1);
2641
+ });
2642
+ export {
2643
+ launcherOf
2644
+ };