ccdeck 3.46.0 → 3.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +72 -43
  2. package/bin/cli/startup.js +23 -0
  3. package/bin/deck.js +32 -1
  4. package/dist/web/assets/BrowserWatchModal-Bau0ttnH.js +1 -0
  5. package/dist/web/assets/IntegrationModal-8tTi25gA.js +6 -0
  6. package/dist/web/assets/{RadioPanel-biw_BbZq.js → RadioPanel-DbmJJPsz.js} +1 -1
  7. package/dist/web/assets/TrafficRadar-CPjAXd5e.js +8 -0
  8. package/dist/web/assets/{UsageHistoryModal-Bd-JRAa4.js → UsageHistoryModal-qfmvXdWJ.js} +1 -1
  9. package/dist/web/assets/app-BFFG6Wz8.js +321 -0
  10. package/dist/web/assets/app-DfcfHvcX.css +1 -0
  11. package/dist/web/assets/claude-settings-index-1Qg1AUda.js +1 -0
  12. package/dist/web/assets/{index-DmENqVdt.js → index-Ca87aJP9.js} +1 -1
  13. package/dist/web/index.html +3 -3
  14. package/package.json +1 -1
  15. package/release-notes.json +30 -0
  16. package/src/server/ccusage-install.mjs +58 -1
  17. package/src/server/ccusage-registry.mjs +289 -0
  18. package/src/server/ccusage-runner.mjs +9 -2
  19. package/src/server/claude-accounts.mjs +21 -0
  20. package/src/server/claude-login.mjs +21 -3
  21. package/src/server/claude-settings-catalog.d.mts +37 -0
  22. package/src/server/claude-settings-catalog.mjs +169 -0
  23. package/src/server/claude-settings-docs.mjs +109 -0
  24. package/src/server/claude-settings-index.json +251 -0
  25. package/src/server/claude-settings-routes.mjs +46 -0
  26. package/src/server/claude-settings.mjs +406 -0
  27. package/src/server/cli-arrival.mjs +64 -0
  28. package/src/server/index.mjs +18 -2
  29. package/src/server/integrations/proxy.mjs +11 -2
  30. package/src/server/integrations/routes.mjs +6 -4
  31. package/src/server/quota-close-watch.mjs +81 -0
  32. package/src/server/quota-closes.mjs +181 -0
  33. package/src/server/quota-history.mjs +8 -1
  34. package/src/server/quota-shape.mjs +12 -0
  35. package/src/server/quota.mjs +28 -1
  36. package/src/server/request-gates.mjs +3 -1
  37. package/src/server/tool-audit-operations.mjs +30 -10
  38. package/src/server/tool-audit-report.mjs +79 -7
  39. package/src/server/tool-audit-routes.mjs +1 -1
  40. package/src/server/tool-audit-skills.mjs +8 -3
  41. package/src/server/tool-audit.mjs +55 -5
  42. package/src/server/traffic-radar-capture.mjs +3 -3
  43. package/src/server/traffic-radar-config.mjs +10 -3
  44. package/src/server/traffic-radar-monitor.mjs +8 -5
  45. package/src/server/traffic-radar-permission.mjs +162 -0
  46. package/src/server/traffic-radar-platform.mjs +9 -3
  47. package/src/server/traffic-radar-routes.mjs +8 -18
  48. package/src/server/traffic-radar-service.mjs +76 -92
  49. package/src/server/usage-routes.mjs +14 -2
  50. package/dist/web/assets/BrowserWatchModal-CoX9FIUE.js +0 -1
  51. package/dist/web/assets/IntegrationModal-B1ypkK-E.js +0 -5
  52. package/dist/web/assets/TrafficRadar-nhtFoYVv.js +0 -8
  53. package/dist/web/assets/app-BlRY6EME.css +0 -1
  54. package/dist/web/assets/app-DhGvSH7o.js +0 -319
@@ -8,6 +8,7 @@ import { writeFileAtomic } from './atomic-write.mjs';
8
8
  import { buildToolAuditReport } from './tool-audit-report.mjs';
9
9
  import { buildSkillReport } from './tool-audit-skills.mjs';
10
10
  import { auditOperations } from './tool-audit-operations.mjs';
11
+ import { stopError } from './stop-failure.mjs';
11
12
  const DAY = 86400000;
12
13
  const digest = text => createHash('sha256').update(text).digest('hex');
13
14
  const date = t => new Date(t).toISOString().slice(0, 10);
@@ -17,21 +18,33 @@ const validMeta = m => m?.v === 1 && /^[a-f0-9-]{36}$/.test(m.deviceId ?? '') &&
17
18
  const skillName = value => { const name = typeof value === 'string' ? value.trim().replace(/^\//, '') : ''; return /^[^\s<>]{1,150}$/.test(name) ? name : null; };
18
19
  const folder = cwd => typeof cwd === 'string' ? cwd.replace(/^file:\/\//, '').split(/[\\/]/).filter(Boolean).at(-1)?.slice(0, 150) ?? null : null;
19
20
  const skillUse = (name, origin, session, cwd, subagent) => ({ skill: name, origin, session, project: folder(cwd), subagent: !!subagent });
21
+ // Where a turn's time went: a Claude Code turn runs from UserPromptSubmit to its Stop
22
+ // or StopFailure, and every hook names the prompt it serves, a subagent's included, so
23
+ // each tool call is filed under its turn. Codex rollouts name no prompt and stay out.
24
+ const promptKey = raw => typeof raw.prompt_id === 'string' && raw.prompt_id && raw.prompt_id.length <= 256 ? `claude|${raw.session_id}|${raw.prompt_id}` : null;
25
+ // Claude Code's own time for a call, which leaves out the approval prompt and the
26
+ // PreToolUse hooks; the rest of the call's span is one or the other.
27
+ const runMs = ms => typeof ms === 'number' && Number.isFinite(ms) && ms >= 0 && ms <= 7 * DAY ? Math.round(ms) : null;
20
28
 
21
29
  export function createToolAudit({ dir, now = Date.now, runReport = workerReport } = {}) {
22
30
  let meta, readyPromise, serial = Promise.resolve(), pending = [], timer, storageOk = true, dropped = 0, reportFlight = null, prunedDay = null;
23
31
  // The last arguments each session typed a command with, as a digest held in memory:
24
32
  // the same command again with the same arguments is a repeat, such as a /loop tick.
25
33
  const lastArgs = new Map();
34
+ // Each session's calls still running, and whether a permission prompt came up while
35
+ // they did: that is what tells a wait for approval from hooks starting the tool.
36
+ const running = new Map();
26
37
  const enqueue = fn => { const task = serial.then(fn); serial = task.catch(() => {}); return task; };
27
38
  const ready = () => readyPromise ??= (async () => {
28
39
  await mkdir(dir, { recursive: true });
29
40
  try { meta = JSON.parse(await readFile(join(dir, 'settings.json'), 'utf8')); }
30
41
  catch (e) { if (e.code !== 'ENOENT') throw e; }
31
42
  if (meta && !validMeta(meta)) throw new Error('Unreadable tool history settings');
32
- if (!meta) { meta = { v: 1, deviceId: randomUUID(), epoch: randomUUID(), retentionDays: 90, startedAt: now(), skillsSince: now() }; await saveMeta(); }
43
+ if (!meta) { meta = { v: 1, deviceId: randomUUID(), epoch: randomUUID(), retentionDays: 90, startedAt: now(), skillsSince: now(), turnsSince: now() }; await saveMeta(); }
33
44
  // A journal from before skills were counted: its Skill calls never named the skill.
34
45
  if (!Number.isFinite(meta.skillsSince)) { meta.skillsSince = now(); await saveMeta(); }
46
+ // Nor did it hold turns, so the split of the time starts here.
47
+ if (!Number.isFinite(meta.turnsSince)) { meta.turnsSince = now(); await saveMeta(); }
35
48
  await prune();
36
49
  })();
37
50
  const saveMeta = () => writeFileAtomic(join(dir, 'settings.json'), JSON.stringify(meta));
@@ -50,7 +63,8 @@ export function createToolAudit({ dir, now = Date.now, runReport = workerReport
50
63
  for (const row of batch) { const d = date(row.t); if (!days.has(d)) days.set(d, []); days.get(d).push(row); }
51
64
  for (const [d, rows] of days) {
52
65
  try {
53
- await appendFile(join(dir, `${d}.jsonl`), rows.map(row => JSON.stringify({ ...row, id: digest(`${meta.deviceId}|${meta.epoch}|${row.id}`) })).join('\n') + '\n', { mode: 0o600 });
66
+ await appendFile(join(dir, `${d}.jsonl`), rows.map(row => JSON.stringify({ ...row, id: digest(`${meta.deviceId}|${meta.epoch}|${row.id}`),
67
+ ...(row.turn ? { turn: digest(`${meta.deviceId}|${meta.epoch}|${row.turn}`) } : {}) })).join('\n') + '\n', { mode: 0o600 });
54
68
  storageOk = true;
55
69
  } catch { storageOk = false; dropped += rows.length; }
56
70
  }
@@ -80,11 +94,32 @@ export function createToolAudit({ dir, now = Date.now, runReport = workerReport
80
94
  queue({ id: `claude|${raw.session_id}|${prompt}|${name}`, provider: 'claude', kind: 'skill', t, at: measured(at, t), clock: 'hook',
81
95
  ...skillUse(name, 'typed', raw.session_id, raw.cwd, typeof raw.agent_id === 'string' && raw.agent_id), repeat });
82
96
  };
97
+ // A turn's two ends. A second Stop for one prompt (a Stop hook sent Claude back to
98
+ // work) is a later end of the same turn, and the report keeps the latest.
99
+ const turn = (raw, opts) => {
100
+ const key = promptKey(raw);
101
+ if (!key) return;
102
+ const t = now(), at = opts.receivedAt ?? t, start = raw.hook_event_name === 'UserPromptSubmit';
103
+ queue({ id: key, provider: 'claude', kind: start ? 'turn' : 'turn-end', t, at: measured(at, t), clock: 'hook',
104
+ ...(start ? {} : { stop: raw.hook_event_name === 'Stop' ? 'done' : stopError(raw) }) });
105
+ };
106
+ const calls = session => {
107
+ let held = running.get(session);
108
+ if (!held) { running.set(session, held = new Map()); if (running.size > 500) running.delete(running.keys().next().value); }
109
+ return held;
110
+ };
83
111
  return {
84
112
  async start() { await ready(); },
85
113
  observe(raw, source, opts = {}) {
86
114
  if (opts.replay || !['hook', 'codex'].includes(source)) return;
87
115
  if (raw?.hook_event_name === 'UserPromptExpansion' && source === 'hook') return typed(raw, opts);
116
+ const claudeHook = source === 'hook' && raw?.provider !== 'codex' && typeof raw?.session_id === 'string' && raw.session_id.length <= 256;
117
+ if (claudeHook && ['UserPromptSubmit', 'Stop', 'StopFailure'].includes(raw.hook_event_name)) return turn(raw, opts);
118
+ if (claudeHook && raw.hook_event_name === 'Notification' && raw.notification_type === 'permission_prompt') {
119
+ const held = running.get(raw.session_id);
120
+ for (const id of held?.keys() ?? []) held.set(id, true);
121
+ return;
122
+ }
88
123
  const kind = raw?.hook_event_name === 'PreToolUse' ? 'start' : ['PostToolUse', 'PostToolUseFailure'].includes(raw?.hook_event_name) ? 'end' : null;
89
124
  if (!kind || typeof raw.session_id !== 'string' || typeof raw.tool_use_id !== 'string' || raw.session_id.length > 256 || raw.tool_use_id.length > 256) return;
90
125
  const provider = raw.provider === 'codex' || source === 'codex' ? 'codex' : 'claude';
@@ -96,7 +131,22 @@ export function createToolAudit({ dir, now = Date.now, runReport = workerReport
96
131
  Object.assign(row, auditOperations(raw.tool_name, raw.tool_input));
97
132
  const name = provider === 'claude' && raw.tool_name === 'Skill' ? skillName(raw.tool_input?.skill) : null;
98
133
  if (name) Object.assign(row, skillUse(name, 'agent', raw.session_id, raw.cwd, typeof raw.agent_id === 'string' && raw.agent_id));
99
- } else row.failed = kind === 'end' && raw.hook_event_name === 'PostToolUseFailure';
134
+ if (claudeHook) {
135
+ const key = promptKey(raw);
136
+ if (key) row.turn = key;
137
+ const held = calls(raw.session_id);
138
+ held.set(raw.tool_use_id, false);
139
+ if (held.size > 200) held.delete(held.keys().next().value);
140
+ }
141
+ } else {
142
+ row.failed = kind === 'end' && raw.hook_event_name === 'PostToolUseFailure';
143
+ if (claudeHook) {
144
+ const ms = runMs(raw.duration_ms), held = running.get(raw.session_id);
145
+ if (ms !== null) row.ms = ms;
146
+ if (held?.get(raw.tool_use_id)) row.asked = true;
147
+ held?.delete(raw.tool_use_id);
148
+ }
149
+ }
100
150
  queue(row);
101
151
  },
102
152
  /** A Codex skill read off a rollout: `key` names the turn and skill, so a
@@ -117,7 +167,7 @@ export function createToolAudit({ dir, now = Date.now, runReport = workerReport
117
167
  async clear() { return enqueue(async () => {
118
168
  await flush();
119
169
  for (const name of await files()) await unlink(join(dir, name));
120
- meta = { ...meta, epoch: randomUUID(), startedAt: now(), skillsSince: now() }; await saveMeta(); dropped = 0; storageOk = true; lastArgs.clear();
170
+ meta = { ...meta, epoch: randomUUID(), startedAt: now(), skillsSince: now(), turnsSince: now() }; await saveMeta(); dropped = 0; storageOk = true; lastArgs.clear(); running.clear();
121
171
  return { ok: true };
122
172
  }); },
123
173
  async report(query, signal) {
@@ -126,7 +176,7 @@ export function createToolAudit({ dir, now = Date.now, runReport = workerReport
126
176
  const snapshot = await enqueue(async () => { await flush(); const inv = await inventory(); return { ...inv, meta: { ...meta }, storageOk, dropped }; });
127
177
  const result = await runReport({ files: snapshot.journal, query, now: now(), meta: snapshot.meta }, signal);
128
178
  if (meta.epoch !== snapshot.meta.epoch) return { ok: false, reason: 'history_cleared' };
129
- return { ...result, bytes: snapshot.bytes, storageOk: snapshot.storageOk, dropped: snapshot.dropped, deviceId: snapshot.meta.deviceId, startedAt: snapshot.meta.startedAt, skillsSince: snapshot.meta.skillsSince, retentionDays: snapshot.meta.retentionDays };
179
+ return { ...result, bytes: snapshot.bytes, storageOk: snapshot.storageOk, dropped: snapshot.dropped, deviceId: snapshot.meta.deviceId, startedAt: snapshot.meta.startedAt, skillsSince: snapshot.meta.skillsSince, turnsSince: snapshot.meta.turnsSince, retentionDays: snapshot.meta.retentionDays };
130
180
  })();
131
181
  try { return await reportFlight; } finally { reportFlight = null; }
132
182
  },
@@ -167,9 +167,9 @@ export function createTrafficCapture({ now = Date.now, platform = process.platfo
167
167
  };
168
168
  return api;
169
169
  }
170
- // The monitor keeps its own opt-in (radar-monitor-<port>.json), as it always
171
- // has; Settings › Radar's automatic monitoring, off unless switched on, keeps
172
- // its own beside it (traffic-radar-service.mjs).
170
+ // The monitor keeps its own record (radar-monitor-<port>.json), as it always
171
+ // has; the service that keeps it on Claude's collector, always on, keeps the
172
+ // collectors it found beside it (traffic-radar-service.mjs).
173
173
  export const trafficCapture = createRadarService({
174
174
  capture: createTrafficCapture({ managed: true, preferences: capturePreferences() }),
175
175
  preferences: capturePreferences(undefined, 'radar-settings'),
@@ -91,7 +91,9 @@ export function launchVariables(processes) {
91
91
  }));
92
92
  }
93
93
 
94
- async function readBoundedJson(path) {
94
+ /** A settings file as JSON, refused past 256 KB or when it is not a file.
95
+ * Settings › Claude Code reads the same three files (claude-settings.mjs). */
96
+ export async function readBoundedJson(path) {
95
97
  const file = await open(path, "r");
96
98
  try {
97
99
  const stat = await file.stat();
@@ -103,11 +105,16 @@ async function readBoundedJson(path) {
103
105
  } finally { await file.close(); }
104
106
  }
105
107
 
108
+ /** Where an administrator's managed-settings.json lives on each platform. */
109
+ export function managedSettingsPath(platform = process.platform, env = process.env) {
110
+ return platform === 'win32' ? win32.join(env.ProgramFiles || 'C:\\Program Files', 'ClaudeCode', 'managed-settings.json')
111
+ : platform === 'linux' ? '/etc/claude-code/managed-settings.json' : '/Library/Application Support/ClaudeCode/managed-settings.json';
112
+ }
113
+
106
114
  export async function readRadarConfig({ home = homedir(), env = process.env, platform = process.platform, readJson = readBoundedJson } = {}) {
107
115
  const pathJoin = platform === 'win32' ? win32.join : posix.join;
108
116
  const dir = claudeConfigDir(env, home, platform);
109
- const managed = platform === 'win32' ? pathJoin(env.ProgramFiles || 'C:\\Program Files', 'ClaudeCode', 'managed-settings.json')
110
- : platform === 'linux' ? '/etc/claude-code/managed-settings.json' : '/Library/Application Support/ClaudeCode/managed-settings.json';
117
+ const managed = managedSettingsPath(platform, env);
111
118
  const files = [
112
119
  ["User settings", pathJoin(dir, "settings.json")],
113
120
  ["Cached organization settings", pathJoin(dir, "remote-settings.json")],
@@ -29,10 +29,13 @@ const stopAtExit = () => { for (const stop of activeMonitors) stop(); };
29
29
 
30
30
  // A child per destination keeps pcap headers and TCP decoders independent.
31
31
  // Retry after a crash or adapter change; an explicit stop cancels every retry.
32
- export function monitorDestination({ platform, tool, host, port, resolveInterface, reset, ingest, status, launch = spawn, retryMs = 3000 }) {
32
+ // A refused permission is retried less often: monitoring is always on, and
33
+ // granting it restarts capture at once (traffic-radar-permission.mjs).
34
+ const PERMISSION = 'Packet capture permission is required.';
35
+ export function monitorDestination({ platform, tool, host, port, resolveInterface, reset, ingest, status, launch = spawn, retryMs = 3000, permissionRetryMs = 30_000 }) {
33
36
  let stopped = false, child = null, retry = null, heartbeat = null, ready = false;
34
37
  const stopHeartbeat = () => { clearInterval(heartbeat); heartbeat = null; };
35
- const retryLater = () => { if (!stopped) { retry = setTimeout(start, retryMs); retry.unref?.(); } };
38
+ const retryLater = (ms = retryMs) => { if (!stopped) { retry = setTimeout(start, ms); retry.unref?.(); } };
36
39
  async function start() {
37
40
  if (stopped) return;
38
41
  try {
@@ -53,11 +56,11 @@ export function monitorDestination({ platform, tool, host, port, resolveInterfac
53
56
  };
54
57
  const end = () => {
55
58
  if (ended) return; ended = true; stopHeartbeat(); capturing.stdout.destroy(); capturing.kill();
56
- if (!stopped) { status(error || 'Capture disconnected. Retrying automatically.'); retryLater(); }
59
+ if (!stopped) { status(error || 'Capture disconnected. Retrying automatically.'); retryLater(error === PERMISSION ? permissionRetryMs : retryMs); }
57
60
  };
58
61
  child.stderr.on('data', bytes => {
59
62
  stderr = (stderr + bytes.toString()).slice(-4096);
60
- if (/permission|access.*denied|not permitted|administrator/i.test(stderr)) error = 'Packet capture permission is required.';
63
+ if (/permission|access.*denied|not permitted|administrator/i.test(stderr)) error = PERMISSION;
61
64
  if (/listening on|Capturing on/i.test(stderr)) listening();
62
65
  });
63
66
  child.stdout.on('data', bytes => {
@@ -66,7 +69,7 @@ export function monitorDestination({ platform, tool, host, port, resolveInterfac
66
69
  for (let i = 0; i < bytes.length; i += 65536) ingest(bytes.subarray(i, i + 65536));
67
70
  });
68
71
  child.stdout.on('error', end);
69
- child.once('error', reason => { if (['EACCES', 'EPERM'].includes(reason.code)) error = 'Packet capture permission is required.'; end(); }); child.once('exit', end);
72
+ child.once('error', reason => { if (['EACCES', 'EPERM'].includes(reason.code)) error = PERMISSION; end(); }); child.once('exit', end);
70
73
  } catch { if (!stopped) { status('Capture interface unavailable. Retrying automatically.'); retryLater(); } }
71
74
  }
72
75
  const stop = () => {
@@ -0,0 +1,162 @@
1
+ // Packet capture is the one thing Telemetry Radar needs that a person cannot
2
+ // grant from inside ccdeck: macOS and Linux keep it for administrators. Allow
3
+ // capture asks for the password once, through the system's own prompt, and
4
+ // sets capture up for good, so monitoring, which is always on, starts by
5
+ // itself afterwards:
6
+ //
7
+ // - macOS: a LaunchDaemon of ccdeck's own does at every startup what
8
+ // Wireshark's ChmodBPF does: it makes the BPF devices and lets the
9
+ // access_bpf group read and write them, and the person joins that group.
10
+ // A new group reaches a person's processes only after they log in again, so
11
+ // this boot's devices are also handed to them directly and capture starts now.
12
+ // - Linux: tcpdump, installed by the system's package manager when missing,
13
+ // may capture (cap_net_raw, cap_net_admin) and may be run by the person's
14
+ // own group only: a group they already have, so it applies now. A tcpdump
15
+ // update replaces the file and drops this; Radar then asks again.
16
+ //
17
+ // Windows has no such step: Npcap's free edition may not be installed by
18
+ // another program, so the person installs Wireshark with Npcap themselves.
19
+ //
20
+ // Where no prompt can open (a deck reached over SSH, a Linux desktop with no
21
+ // polkit agent) the same script is written to the deck's folder and the answer
22
+ // names the one command that runs it.
23
+ import { mkdir, writeFile } from 'node:fs/promises';
24
+ import { homedir, userInfo } from 'node:os';
25
+ import { join } from 'node:path';
26
+ import { run } from './exec.mjs';
27
+
28
+ export const OSASCRIPT = '/usr/bin/osascript';
29
+ export const PKEXEC = 'pkexec';
30
+ export const LAUNCH_LABEL = 'dev.ccdeck.chmodbpf';
31
+ const HELPER = '/Library/Application Support/ccdeck/ccdeck-chmodbpf';
32
+ const PLIST = `/Library/LaunchDaemons/${LAUNCH_LABEL}.plist`;
33
+ /** Long enough for a person to find and type their password. */
34
+ const PROMPT_TIMEOUT_MS = 5 * 60_000;
35
+ const PROMPT = 'ccdeck needs your password once so Telemetry Radar can read the telemetry Claude Code sends to its collector.';
36
+ /** osascript's "User canceled.", and its "No user interaction allowed." where no one is logged in to answer. */
37
+ const CANCELLED = /\(-128\)/;
38
+ const NO_SESSION = /\(-1713\)|no user interaction/i;
39
+
40
+ /** A login name safe to write into a root script inside single quotes. */
41
+ export const validUser = name => typeof name === 'string' && /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/.test(name);
42
+
43
+ /** Run as root on macOS. Every value in it is a constant but `user`, checked by validUser. */
44
+ export function macosScript(user) {
45
+ if (!validUser(user)) throw new Error('Unexpected user name.');
46
+ return `set -e
47
+ user='${user}'
48
+ mkdir -p '/Library/Application Support/ccdeck'
49
+ cat > '${HELPER}' <<'CCDECK_HELPER'
50
+ #!/bin/sh
51
+ # ccdeck: lets the access_bpf group capture packets for Telemetry Radar, as
52
+ # Wireshark's ChmodBPF does. macOS makes BPF devices on demand, owned by root,
53
+ # and opening the last one makes the next, so all exist before their group is set.
54
+ max=$(sysctl -n debug.bpf_maxdevices 2>/dev/null || echo 256)
55
+ [ "$max" -le 256 ] 2>/dev/null || max=256
56
+ i=0
57
+ while [ "$i" -lt "$max" ]; do true 2>/dev/null < "/dev/bpf$i"; i=$((i + 1)); done
58
+ chgrp access_bpf /dev/bpf*
59
+ chmod g+rw /dev/bpf*
60
+ CCDECK_HELPER
61
+ cat > '${PLIST}' <<'CCDECK_PLIST'
62
+ <?xml version="1.0" encoding="UTF-8"?>
63
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
64
+ <plist version="1.0">
65
+ <dict>
66
+ <key>Label</key><string>${LAUNCH_LABEL}</string>
67
+ <key>Program</key><string>${HELPER}</string>
68
+ <key>RunAtLoad</key><true/>
69
+ </dict>
70
+ </plist>
71
+ CCDECK_PLIST
72
+ chown root:wheel '${HELPER}' '${PLIST}'
73
+ chmod 755 '${HELPER}'
74
+ chmod 644 '${PLIST}'
75
+ dseditgroup -q -o read access_bpf >/dev/null 2>&1 || dseditgroup -q -o create access_bpf
76
+ dseditgroup -q -o edit -a "$user" -t user access_bpf
77
+ launchctl bootout system/${LAUNCH_LABEL} >/dev/null 2>&1 || true
78
+ launchctl bootstrap system '${PLIST}'
79
+ '${HELPER}'
80
+ chown "$user" /dev/bpf*
81
+ `;
82
+ }
83
+
84
+ /** Run as root on Linux, by pkexec, whose PATH has the sbin folders. `gid` is the person's own group. */
85
+ export function linuxScript(gid) {
86
+ if (!Number.isInteger(gid) || gid <= 0) throw new Error('Unexpected group.');
87
+ return `set -e
88
+ found() { for t in "$(command -v tcpdump 2>/dev/null)" /usr/sbin/tcpdump /usr/bin/tcpdump /sbin/tcpdump; do if [ -n "$t" ] && [ -x "$t" ]; then echo "$t"; return 0; fi; done; return 1; }
89
+ install() {
90
+ if command -v apt-get >/dev/null 2>&1; then
91
+ DEBIAN_FRONTEND=noninteractive apt-get install -y "$1" || { apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y "$1"; }
92
+ elif command -v dnf >/dev/null 2>&1; then dnf install -y "$2"
93
+ elif command -v zypper >/dev/null 2>&1; then zypper --non-interactive install "$3"
94
+ elif command -v pacman >/dev/null 2>&1; then pacman -S --noconfirm --needed "$4"
95
+ else echo "ccdeck: no supported package manager. Install $1, then allow capture again." >&2; exit 4
96
+ fi
97
+ }
98
+ found >/dev/null || install tcpdump tcpdump tcpdump tcpdump
99
+ command -v setcap >/dev/null 2>&1 || install libcap2-bin libcap libcap-progs libcap
100
+ tool=$(readlink -f "$(found)")
101
+ chgrp ${gid} "$tool"
102
+ chmod 0750 "$tool"
103
+ setcap cap_net_raw,cap_net_admin=eip "$tool"
104
+ `;
105
+ }
106
+
107
+ /** The script, written where its owner can read it, and the command that runs it. */
108
+ async function handOver(script, directory) {
109
+ const file = join(directory, 'radar-capture-setup.sh');
110
+ await mkdir(directory, { recursive: true });
111
+ await writeFile(file, script, { mode: 0o600 });
112
+ return `sudo sh '${file.replaceAll("'", "'\\''")}'`;
113
+ }
114
+
115
+ /** The last line a failed script said, for the person: a package manager's own words. */
116
+ const lastLine = text => String(text ?? '').trim().split('\n').filter(Boolean).pop()?.slice(0, 300) ?? '';
117
+
118
+ let inFlight = null;
119
+
120
+ /**
121
+ * Ask the system for capture permission, once. Answers one of:
122
+ * granted the script ran as root; capture can start now
123
+ * cancelled the person closed the password prompt; nothing changed
124
+ * unavailable no prompt can open here; `command` runs the same script
125
+ * failed the script ran and stopped; `message` says why, `command` retries it
126
+ * Windows, and anything else, answer unavailable with no command.
127
+ */
128
+ export function askCapturePermission(deps = {}) {
129
+ if (!inFlight) inFlight = ask(deps).finally(() => { inFlight = null; });
130
+ return inFlight;
131
+ }
132
+
133
+ async function ask({ platform = process.platform, env = process.env, user = userInfo(), exec = run, directory = join(homedir(), '.agents-deck') } = {}) {
134
+ if (platform === 'darwin') {
135
+ if (!validUser(user.username) || user.uid === 0) return { outcome: 'unavailable', message: 'Capture permission is set up for a signed-in user.' };
136
+ const script = macosScript(user.username);
137
+ const r = await exec(OSASCRIPT, ['-e', 'on run argv\ndo shell script (item 1 of argv) with prompt (item 2 of argv) with administrator privileges\nend run', '--', script, PROMPT], { timeout: PROMPT_TIMEOUT_MS });
138
+ if (r.ok) return { outcome: 'granted' };
139
+ if (CANCELLED.test(r.stderr ?? '')) return { outcome: 'cancelled' };
140
+ const command = await handOver(script, directory);
141
+ if (r.timedOut) return { outcome: 'failed', message: 'Nobody answered the password prompt.', command };
142
+ if (NO_SESSION.test(r.stderr ?? '')) return { outcome: 'unavailable', message: 'No password prompt can open in this session.', command };
143
+ return { outcome: 'failed', message: `macOS refused: ${lastLine(r.stderr) || 'the setup did not finish'}.`, command };
144
+ }
145
+ if (platform === 'linux') {
146
+ if (!Number.isInteger(user.gid) || user.gid <= 0 || user.uid === 0) return { outcome: 'unavailable', message: 'Capture permission is set up for a signed-in user.' };
147
+ const script = linuxScript(user.gid);
148
+ // A desktop session is where pkexec's agent draws its prompt; over SSH,
149
+ // pkexec would fall back to asking on a terminal nobody is looking at.
150
+ if (!env.DISPLAY && !env.WAYLAND_DISPLAY) return { outcome: 'unavailable', message: 'No password prompt can open in this session.', command: await handOver(script, directory) };
151
+ const r = await exec(PKEXEC, ['/bin/sh', '-c', script], { timeout: PROMPT_TIMEOUT_MS });
152
+ if (r.ok) return { outcome: 'granted' };
153
+ // pkexec: 126 is a dismissed prompt, 127 one that could not be shown or was refused.
154
+ if (r.code === 126) return { outcome: 'cancelled' };
155
+ const command = await handOver(script, directory);
156
+ if (r.code === 'ENOENT' || /authentication agent/i.test(r.stderr ?? '')) return { outcome: 'unavailable', message: 'No password prompt can open in this session.', command };
157
+ if (r.timedOut) return { outcome: 'failed', message: 'Nobody answered the password prompt.', command };
158
+ if (r.code === 127) return { outcome: 'failed', message: 'The password was not accepted.', command };
159
+ return { outcome: 'failed', message: `The setup stopped: ${lastLine(r.stderr) || `exit ${r.code}`}.`, command };
160
+ }
161
+ return { outcome: 'unavailable', message: 'Install Wireshark with Npcap to allow packet capture.' };
162
+ }
@@ -137,10 +137,16 @@ export function dumpcapPath(env = process.env, exists = existsSync) {
137
137
  return 'dumpcap.exe'; // Custom installs may expose it on PATH.
138
138
  }
139
139
  export class CaptureSetupError extends Error {}
140
+ // Linux keeps tcpdump in /usr/sbin on some distributions (openSUSE, Fedora
141
+ // before 42), which a user's PATH, or a desktop app's, may leave out.
142
+ const LINUX_TCPDUMP = ['tcpdump', '/usr/sbin/tcpdump', '/usr/bin/tcpdump', '/sbin/tcpdump'];
140
143
  export async function captureTool(platform, run = systemCommand) {
141
- const file = platform === 'win32' ? dumpcapPath() : platform === 'darwin' ? '/usr/sbin/tcpdump' : 'tcpdump';
142
- if (await run(file, [platform === 'win32' ? '-v' : '--version']) === null)
143
- throw new CaptureSetupError(platform === 'win32' ? 'Install Wireshark with Npcap to capture traffic, then retry. Configuration and file inspection work without it.' : 'Install tcpdump to capture traffic, then retry. Configuration and file inspection work without it.');
144
+ const version = platform === 'win32' ? '-v' : '--version';
145
+ const tried = platform === 'win32' ? [dumpcapPath()] : platform === 'darwin' ? ['/usr/sbin/tcpdump'] : LINUX_TCPDUMP;
146
+ let file = null;
147
+ for (const candidate of tried) if (await run(candidate, [version]) !== null) { file = candidate; break; }
148
+ if (file === null)
149
+ throw new CaptureSetupError(platform === 'win32' ? 'Install Wireshark with Npcap to capture traffic. Configuration and file inspection work without it.' : 'Install tcpdump to capture traffic. Configuration and file inspection work without it.');
144
150
  if (platform === 'win32' && await run(file, ['-D']) === null)
145
151
  throw new CaptureSetupError('Npcap interfaces are unavailable. Check that Npcap is installed and its capture permissions allow this user.');
146
152
  return file;
@@ -1,5 +1,6 @@
1
1
  import { trafficCapture } from "./traffic-radar-capture.mjs";
2
2
  import { CaptureSetupError } from './traffic-radar-platform.mjs';
3
+ import { askCapturePermission } from './traffic-radar-permission.mjs';
3
4
  import { updateRadarFlag } from './traffic-radar-config.mjs';
4
5
  import { trafficRadar } from './traffic-radar.mjs';
5
6
  const BASE = '/api/system/traffic-radar';
@@ -17,7 +18,7 @@ async function body(req, max) {
17
18
  for await (const chunk of req) { size += chunk.length; if (size > max) throw new Error('Request too large.'); chunks.push(chunk); }
18
19
  return Buffer.concat(chunks);
19
20
  }
20
- export async function handleTrafficCapture(req, res, url, capture = trafficCapture) {
21
+ export async function handleTrafficCapture(req, res, url, capture = trafficCapture, permission = askCapturePermission) {
21
22
  if (!loopback(req)) return reply(res, 403, { error: 'Telemetry contents are available on this machine only.' });
22
23
  const action = url.pathname.slice(BASE.length);
23
24
  try {
@@ -32,19 +33,6 @@ export async function handleTrafficCapture(req, res, url, capture = trafficCaptu
32
33
  }
33
34
  catch (error) { return reply(res, 400, { error: error.message }); }
34
35
  }
35
- // Settings › Radar: `enabled` is automatic monitoring, off unless switched on.
36
- if (req.method === 'GET' && action === '/settings') return reply(res, 200, await capture.settings());
37
- if (req.method === 'POST' && action === '/settings') {
38
- let data;
39
- try { data = JSON.parse((await body(req, 4096)).toString()); } catch { return reply(res, 400, { error: 'Invalid Radar settings.' }); }
40
- // One field, a boolean, and nothing else: a body that names anything more
41
- // is not this switch's and is refused whole, not half-applied.
42
- if (!data || typeof data !== 'object' || Array.isArray(data) || Object.keys(data).join() !== 'enabled')
43
- return reply(res, 400, { error: 'Invalid Radar settings.' });
44
- if (typeof data.enabled !== 'boolean') return reply(res, 400, { error: 'Radar enabled must be a boolean.' });
45
- try { return reply(res, 200, await capture.setEnabled(data.enabled)); }
46
- catch { return reply(res, 500, { error: 'Could not save Radar settings. Try again.' }); }
47
- }
48
36
  if (req.method === 'GET' && action === '/capture') return reply(res, 200, capture.read());
49
37
  if (req.method === 'GET' && action === '/capture/event') {
50
38
  const detail = capture.detail(Number(url.searchParams.get('id')));
@@ -56,11 +44,13 @@ export async function handleTrafficCapture(req, res, url, capture = trafficCaptu
56
44
  const data = await body(req, 262_144);
57
45
  return reply(res, capture.ingest(token, data, Number(req.headers['x-radar-source'] ?? 0)) ? 200 : 409, { ok: capture.read().state === 'capturing' });
58
46
  }
59
- if (req.method === 'POST' && action === '/capture/prepare') {
60
- const data = JSON.parse((await body(req, 4096)).toString());
61
- return reply(res, 200, await capture.prepare(data.destination, req.socket.localPort));
47
+ // Allow capture: the system's own password prompt, once. Granted, capture
48
+ // starts again now rather than at its next retry.
49
+ if (req.method === 'POST' && action === '/capture/permission') {
50
+ const result = await permission();
51
+ if (result.outcome === 'granted') await capture.retry?.();
52
+ return reply(res, 200, { ok: true, ...result });
62
53
  }
63
- if (req.method === 'POST' && action === '/capture/stop') { await capture.stop(); return reply(res, 200, { ok: true }); }
64
54
  if (req.method === 'POST' && action === '/capture/clear') { capture.clear(); return reply(res, 200, { ok: true }); }
65
55
  return reply(res, 404, { error: 'Unknown capture action.' });
66
56
  } catch (error) { return reply(res, 400, { error: error instanceof CaptureSetupError ? error.message : 'Could not complete capture setup. Use a valid IPv4 destination and check its network route.' }); }