ccdeck 3.45.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.
- package/README.md +79 -47
- package/bin/cli/startup.js +27 -3
- package/bin/deck.js +32 -1
- package/dist/web/assets/BrowserWatchModal-Bau0ttnH.js +1 -0
- package/dist/web/assets/IntegrationModal-8tTi25gA.js +6 -0
- package/dist/web/assets/RadioPanel-DbmJJPsz.js +1 -0
- package/dist/web/assets/TrafficRadar-CPjAXd5e.js +8 -0
- package/dist/web/assets/{UsageHistoryModal-DAhplVju.js → UsageHistoryModal-qfmvXdWJ.js} +1 -1
- package/dist/web/assets/app-BFFG6Wz8.js +321 -0
- package/dist/web/assets/app-DfcfHvcX.css +1 -0
- package/dist/web/assets/claude-settings-index-1Qg1AUda.js +1 -0
- package/dist/web/assets/{index-r8Ymr47Q.js → index-Ca87aJP9.js} +1 -1
- package/dist/web/index.html +3 -3
- package/package.json +1 -1
- package/release-notes.json +60 -0
- package/src/server/ccusage-install.mjs +58 -1
- package/src/server/ccusage-registry.mjs +289 -0
- package/src/server/ccusage-runner.mjs +9 -2
- package/src/server/claude-accounts.mjs +56 -19
- package/src/server/claude-login.mjs +129 -0
- package/src/server/claude-settings-catalog.d.mts +37 -0
- package/src/server/claude-settings-catalog.mjs +169 -0
- package/src/server/claude-settings-docs.mjs +109 -0
- package/src/server/claude-settings-index.json +251 -0
- package/src/server/claude-settings-routes.mjs +46 -0
- package/src/server/claude-settings.mjs +406 -0
- package/src/server/cli-arrival.mjs +64 -0
- package/src/server/cswap-admin.mjs +12 -3
- package/src/server/index.mjs +18 -2
- package/src/server/installer.mjs +24 -7
- package/src/server/integrations/proxy.mjs +11 -2
- package/src/server/integrations/routes.mjs +6 -4
- package/src/server/login-service.mjs +2 -2
- package/src/server/quota-close-watch.mjs +81 -0
- package/src/server/quota-closes.mjs +181 -0
- package/src/server/quota-history.mjs +8 -1
- package/src/server/quota-shape.mjs +12 -0
- package/src/server/quota.mjs +28 -1
- package/src/server/request-gates.mjs +3 -1
- package/src/server/skill-hook.mjs +28 -22
- package/src/server/system-metrics.mjs +4 -0
- package/src/server/tool-audit-operations.mjs +30 -10
- package/src/server/tool-audit-report.mjs +79 -7
- package/src/server/tool-audit-routes.mjs +5 -1
- package/src/server/tool-audit-skills.mjs +8 -3
- package/src/server/tool-audit.mjs +55 -5
- package/src/server/traffic-radar-capture.mjs +3 -3
- package/src/server/traffic-radar-config.mjs +43 -3
- package/src/server/traffic-radar-monitor.mjs +8 -5
- package/src/server/traffic-radar-permission.mjs +162 -0
- package/src/server/traffic-radar-platform.mjs +93 -20
- package/src/server/traffic-radar-routes.mjs +8 -18
- package/src/server/traffic-radar-service.mjs +81 -94
- package/src/server/traffic-radar.mjs +32 -9
- package/src/server/usage-routes.mjs +14 -2
- package/dist/web/assets/BrowserWatchModal-Cbzf3TWa.js +0 -1
- package/dist/web/assets/IntegrationModal-BnnBr0a3.js +0 -5
- package/dist/web/assets/RadioPanel-BIqrMLQN.js +0 -1
- package/dist/web/assets/TrafficRadar-D1gZCIwX.js +0 -8
- package/dist/web/assets/app-BW3NYUYB.js +0 -318
- package/dist/web/assets/app-C5RY_wZ4.css +0 -1
|
@@ -3,13 +3,19 @@ export async function buildToolAuditReport({ files, query, now, meta }, { create
|
|
|
3
3
|
const DAY = 86400000;
|
|
4
4
|
const finite = n => typeof n === 'number' && Number.isFinite(n);
|
|
5
5
|
const valid = r => /^[a-f0-9]{64}$/.test(r?.id ?? '') && ['claude', 'codex'].includes(r.provider)
|
|
6
|
-
&& ['start', 'end', 'skill'].includes(r.kind) && finite(r.t) && (r.at === null || finite(r.at))
|
|
6
|
+
&& ['start', 'end', 'skill', 'turn', 'turn-end'].includes(r.kind) && finite(r.t) && (r.at === null || finite(r.at))
|
|
7
7
|
&& ['hook', 'rollout'].includes(r.clock)
|
|
8
|
-
// A typed or detected skill is not a tool call; Skill activity reads it.
|
|
8
|
+
// A typed or detected skill is not a tool call; Skill activity reads it. Nor is a
|
|
9
|
+
// turn, which only bounds the calls made for one prompt.
|
|
9
10
|
&& (r.kind === 'skill' ? typeof r.skill === 'string'
|
|
10
|
-
: r.kind === '
|
|
11
|
+
: r.kind === 'turn' ? true
|
|
12
|
+
: r.kind === 'turn-end' ? typeof r.stop === 'string' && r.stop.length <= 40
|
|
13
|
+
: r.kind === 'end' ? typeof r.failed === 'boolean' && (r.ms === undefined || finite(r.ms) && r.ms >= 0) && (r.asked === undefined || typeof r.asked === 'boolean')
|
|
14
|
+
: typeof r.tool === 'string' && r.tool.length <= 100
|
|
11
15
|
&& Array.isArray(r.operations) && r.operations.length > 0 && r.operations.length <= 16
|
|
12
|
-
&& r.operations.every(s => typeof s === 'string' && s.length <= 150)
|
|
16
|
+
&& r.operations.every(s => typeof s === 'string' && s.length <= 150)
|
|
17
|
+
&& (r.lead === undefined || Array.isArray(r.lead) && r.lead.length > 0 && r.lead.every(s => r.operations.includes(s)))
|
|
18
|
+
&& (r.turn === undefined || /^[a-f0-9]{64}$/.test(r.turn)));
|
|
13
19
|
const percentile = (sorted, p) => sorted.length ? sorted[Math.max(0, Math.ceil(sorted.length * p) - 1)] : null;
|
|
14
20
|
const calls = new Map(); let corrupt = 0, duplicates = 0;
|
|
15
21
|
// Explicit failure rather than a convincing-looking partial report.
|
|
@@ -25,7 +31,8 @@ const percentile = (sorted, p) => sorted.length ? sorted[Math.max(0, Math.ceil(s
|
|
|
25
31
|
if (!valid(r)) { corrupt++; continue; }
|
|
26
32
|
let call = calls.get(r.id);
|
|
27
33
|
if (!call) { if (calls.size >= 500000) throw new Error('Tool history exceeds report capacity; choose shorter retention in Settings'); call = {}; calls.set(r.id, call); }
|
|
28
|
-
|
|
34
|
+
// A turn a Stop hook sent back to work ends at its last Stop.
|
|
35
|
+
if (call[r.kind]) { duplicates++; if (r.kind === 'turn-end' && finite(r.at) && !(r.at <= call[r.kind].at)) call[r.kind] = r; continue; }
|
|
29
36
|
call[r.kind] = r;
|
|
30
37
|
}
|
|
31
38
|
} finally { lines.close(); stream.destroy(); }
|
|
@@ -62,7 +69,7 @@ const percentile = (sorted, p) => sorted.length ? sorted[Math.max(0, Math.ceil(s
|
|
|
62
69
|
const providers = { claude: { calls: 0, measured: 0, failed: 0 }, codex: { calls: 0, measured: 0, failed: 0 } };
|
|
63
70
|
for (const [id, call] of calls) {
|
|
64
71
|
const start = call.start, end = call.end;
|
|
65
|
-
if (!start) { if (!call.skill) orphaned++; continue; }
|
|
72
|
+
if (!start) { if (!call.skill && !call.turn && !call['turn-end']) orphaned++; continue; }
|
|
66
73
|
if (start.t < since || start.t > until || query.provider !== 'all' && start.provider !== query.provider) continue;
|
|
67
74
|
total++; providers[start.provider].calls++;
|
|
68
75
|
observedSince = observedSince === null ? start.t : Math.min(observedSince, start.t);
|
|
@@ -89,6 +96,71 @@ const percentile = (sorted, p) => sorted.length ? sorted[Math.max(0, Math.ceil(s
|
|
|
89
96
|
capturedAt: start.t, durationMs: duration, state: !end ? 'unmatched' : end.failed ? 'failed' : 'success', clock: start.clock, shared });
|
|
90
97
|
}
|
|
91
98
|
}
|
|
99
|
+
// Where the turns' time went: Claude, this machine, or you. Wall-clock time, so the
|
|
100
|
+
// calls that ran together, a subagent's among them, count once; a turn's time is cut
|
|
101
|
+
// into the stretches between its calls' edges, and each stretch goes to one of three:
|
|
102
|
+
// this machine while any call runs or hooks start one, you while one waits for your
|
|
103
|
+
// approval or answer, and Claude while nothing does — the model, the network to it,
|
|
104
|
+
// and Claude Code itself. An Agent call only holds its subagent's calls, which count.
|
|
105
|
+
const holders = new Set(['Agent', 'Task']), questions = new Set(['AskUserQuestion', 'ExitPlanMode']);
|
|
106
|
+
const middle = list => list.length ? list.length % 2 ? list[Math.floor(list.length / 2)] : (list[list.length / 2 - 1] + list[list.length / 2]) / 2 : null;
|
|
107
|
+
let split = null;
|
|
108
|
+
if (query.provider !== 'codex') {
|
|
109
|
+
const byTurn = new Map();
|
|
110
|
+
for (const call of calls.values()) {
|
|
111
|
+
const s = call.start, e = call.end;
|
|
112
|
+
if (!s?.turn || !e || s.provider !== 'claude' || s.clock !== 'hook' || e.clock !== 'hook' || !finite(s.at) || !finite(e.at) || e.at < s.at || holders.has(s.tool)) continue;
|
|
113
|
+
if (!byTurn.has(s.turn)) byTurn.set(s.turn, []);
|
|
114
|
+
byTurn.get(s.turn).push(call);
|
|
115
|
+
}
|
|
116
|
+
const sum = { turns: 0, open: 0, totalMs: 0, claudeMs: 0, machineMs: 0, youMs: 0 }, machine = new Map(), you = new Map(), replies = [], stops = {};
|
|
117
|
+
const add = (map, operation, ms) => map.set(operation, (map.get(operation) ?? 0) + ms);
|
|
118
|
+
for (const [id, call] of calls) {
|
|
119
|
+
const begin = call.turn, end = call['turn-end'];
|
|
120
|
+
if (!begin || begin.t < since || begin.t > until) continue;
|
|
121
|
+
if (!end || !finite(begin.at) || !finite(end.at) || end.at <= begin.at || end.at - begin.at > DAY) { sum.open++; continue; }
|
|
122
|
+
const a = begin.at, b = end.at, spans = [];
|
|
123
|
+
sum.turns++; sum.totalMs += b - a;
|
|
124
|
+
if (end.stop !== 'done') stops[end.stop] = (stops[end.stop] ?? 0) + 1;
|
|
125
|
+
for (const { start: s, end: e } of byTurn.get(id) ?? []) {
|
|
126
|
+
// A command's time is its lead's: npm test's, not the tail reading its output.
|
|
127
|
+
const own = s.lead ?? s.operations;
|
|
128
|
+
if (questions.has(s.tool)) { spans.push([s.at, e.at, you, own]); continue; }
|
|
129
|
+
// Claude Code's own time for the call ends where the call does; what comes
|
|
130
|
+
// before it is the approval, when a prompt came up, or else the hooks.
|
|
131
|
+
const run = finite(e.ms) ? Math.min(e.ms, e.at - s.at) : e.at - s.at, from = e.at - run;
|
|
132
|
+
if (run > 0) spans.push([from, e.at, machine, own]);
|
|
133
|
+
if (from > s.at) spans.push(e.asked ? [s.at, from, you, own] : [s.at, from, machine, ['(starting tools)']]);
|
|
134
|
+
}
|
|
135
|
+
const edges = [];
|
|
136
|
+
for (const span of spans) { const x = Math.max(span[0], a), y = Math.min(span[1], b); if (y > x) edges.push([x, 1, span], [y, -1, span]); }
|
|
137
|
+
edges.sort((p, q) => p[0] - q[0] || p[1] - q[1]);
|
|
138
|
+
const live = new Set(); let at = a, reply = 0, replyFrom = a;
|
|
139
|
+
const spend = to => {
|
|
140
|
+
const ms = to - at; if (ms <= 0) return;
|
|
141
|
+
const running = [...live].filter(span => span[2] === machine), lane = running.length ? running : [...live];
|
|
142
|
+
if (!lane.length) { if (!reply) replyFrom = at; reply += ms; sum.claudeMs += ms; at = to; return; }
|
|
143
|
+
if (reply) { replies.push([replyFrom, reply]); reply = 0; }
|
|
144
|
+
if (running.length) sum.machineMs += ms; else sum.youMs += ms;
|
|
145
|
+
for (const span of lane) for (const operation of span[3]) add(span[2], operation, ms / lane.length / span[3].length);
|
|
146
|
+
at = to;
|
|
147
|
+
};
|
|
148
|
+
for (const [t, step, span] of edges) { spend(t); if (step > 0) live.add(span); else live.delete(span); }
|
|
149
|
+
spend(b);
|
|
150
|
+
if (reply) replies.push([replyFrom, reply]);
|
|
151
|
+
}
|
|
152
|
+
// Claude's replies by the reader's calendar day, so a slow afternoon shows as one.
|
|
153
|
+
const dayOf = new Intl.DateTimeFormat('en-CA', { timeZone: query.timeZone ?? 'UTC', year: 'numeric', month: '2-digit', day: '2-digit' });
|
|
154
|
+
const days = new Map();
|
|
155
|
+
for (let t = since; t <= until; t += DAY / 2) days.set(dayOf.format(new Date(t)), []);
|
|
156
|
+
days.set(dayOf.format(new Date(until)), days.get(dayOf.format(new Date(until))) ?? []);
|
|
157
|
+
for (const [t, ms] of replies) days.get(dayOf.format(new Date(t)))?.push(ms);
|
|
158
|
+
const lengths = replies.map(r => r[1]).sort((x, y) => x - y);
|
|
159
|
+
const top = (map, n) => [...map].map(([operation, ms]) => ({ operation, ms: Math.round(ms) })).sort((p, q) => q.ms - p.ms || p.operation.localeCompare(q.operation)).slice(0, n);
|
|
160
|
+
split = { ...sum, machine: top(machine, 40), you: top(you, 20), stops,
|
|
161
|
+
replies: { count: lengths.length, medianMs: middle(lengths), p90Ms: lengths.length >= 10 ? percentile(lengths, .9) : null, maxMs: lengths.at(-1) ?? null,
|
|
162
|
+
days: [...days].map(([date, list]) => { list.sort((x, y) => x - y); return { date, count: list.length, medianMs: middle(list) }; }) } };
|
|
163
|
+
}
|
|
92
164
|
const rows = [...groups.values()].map(g => {
|
|
93
165
|
const durations = g.durations.sort((a, b) => a - b);
|
|
94
166
|
const n = durations.length;
|
|
@@ -102,7 +174,7 @@ const percentile = (sorted, p) => sorted.length ? sorted[Math.max(0, Math.ceil(s
|
|
|
102
174
|
}).sort((a, b) => b.calls - a.calls || a.operation.localeCompare(b.operation));
|
|
103
175
|
return { ok: true, capturedAt: now, since, until, provider: query.provider, total, measured, failed, unmatched: pending,
|
|
104
176
|
corrupt, duplicates, orphaned, rows, totalMs, completed: total - pending, providers, observedSince, observedUntil,
|
|
105
|
-
retainedSince,
|
|
177
|
+
retainedSince, split,
|
|
106
178
|
details: query.operation ? { operation: query.operation, total: details.length,
|
|
107
179
|
...(query.history ? { capturedAt: now, measurements: rows.find(row => row.operation === query.operation) ?? null, history: { timeZone: query.timeZone ?? 'UTC', days: [...daily.values()].map(bucket => {
|
|
108
180
|
const sorted = bucket.durations.sort((a, b) => a - b), n = sorted.length;
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { toolAudit } from './tool-audit.mjs';
|
|
2
2
|
import { readBody, send } from './http-io.mjs';
|
|
3
|
+
import { skillHookState } from './installer.mjs';
|
|
4
|
+
import { deckProviders } from './deck-scope.mjs';
|
|
3
5
|
const calendarDate = value => /^\d{4}-\d{2}-\d{2}$/.test(value ?? '') && Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value;
|
|
4
6
|
export function auditQuery(params) {
|
|
5
7
|
const provider = params.get('provider') ?? 'all';
|
|
@@ -15,7 +17,7 @@ export function auditQuery(params) {
|
|
|
15
17
|
if (!['all', 'claude', 'codex'].includes(provider) || ![1, 7, 30, 60, 90].includes(days)
|
|
16
18
|
|| operation && operation.length > 150 || skill !== undefined && !/^[^\s<>]{1,150}$/.test(skill) || !!since !== !!until) return null;
|
|
17
19
|
if (since && (!calendarDate(since) || !calendarDate(until) || since > until || Date.parse(until) - Date.parse(since) >= 90 * 86400000)) return null;
|
|
18
|
-
return { provider, days, ...(view === 'skills' ? { view, skill } : { operation }), ...(history ? { history: true
|
|
20
|
+
return { provider, days, timeZone, ...(view === 'skills' ? { view, skill } : { operation }), ...(history ? { history: true } : {}), ...(since ? { since: Date.parse(since), until: Date.parse(until) + 86400000 - 1 } : {}) };
|
|
19
21
|
}
|
|
20
22
|
export async function handleToolAudit(req, res) {
|
|
21
23
|
const audit = toolAudit();
|
|
@@ -31,6 +33,8 @@ export async function handleToolAudit(req, res) {
|
|
|
31
33
|
try { report = await audit.report(query, controller.signal); }
|
|
32
34
|
catch (e) { if (controller.signal.aborted) return; throw e; }
|
|
33
35
|
finally { res.off('close', cancel); }
|
|
36
|
+
// The Skills tab says when the commands a person types cannot be counted.
|
|
37
|
+
if (report.ok && query.view === 'skills' && deckProviders().claude) report.typedCommands = await skillHookState();
|
|
34
38
|
return send(res, report.ok ? 200 : 409, report);
|
|
35
39
|
}
|
|
36
40
|
let body; try { body = JSON.parse(await readBody(req, res, 2048)); } catch { return send(res, 400, { ok: false, reason: 'bad_body' }); }
|
|
@@ -59,8 +59,13 @@ const named = r => text(r.skill, 150) && ['typed', 'agent', 'detected'].includes
|
|
|
59
59
|
const counted = picked.filter(use => !use.repeat).sort((a, b) => b.at - a.at);
|
|
60
60
|
const projects = new Map();
|
|
61
61
|
for (const use of counted) if (use.project) projects.set(use.project, (projects.get(use.project) ?? 0) + 1);
|
|
62
|
+
const ranked = [...projects].map(([name, uses]) => ({ name, uses })).sort((a, b) => b.uses - a.uses || a.name.localeCompare(b.name));
|
|
63
|
+
// What the five named projects leave out, so the list adds up to the uses: the
|
|
64
|
+
// rest of the projects, and uses with no project folder to name.
|
|
65
|
+
const rest = ranked.slice(5);
|
|
62
66
|
details = { name: query.skill, row: rows.find(row => row.name === query.skill) ?? null, total: counted.length,
|
|
63
|
-
projects:
|
|
67
|
+
projects: ranked.slice(0, 5), moreProjects: { projects: rest.length, uses: rest.reduce((sum, item) => sum + item.uses, 0) },
|
|
68
|
+
projectless: counted.filter(use => !use.project).length,
|
|
64
69
|
recent: counted.slice(0, 50).map(({ id, provider, at, origin, session, project, subagent, state }) => ({ id, provider, at, origin, session, project, subagent, state })) };
|
|
65
70
|
if (query.history) {
|
|
66
71
|
const format = new Intl.DateTimeFormat('en-CA', { timeZone: query.timeZone ?? 'UTC', year: 'numeric', month: '2-digit', day: '2-digit' });
|
|
@@ -71,9 +76,9 @@ const named = r => text(r.skill, 150) && ['typed', 'agent', 'detected'].includes
|
|
|
71
76
|
// Calendar labels advance independently of offsets: DST days may be 23 or 25 hours.
|
|
72
77
|
for (let date = first; date <= last; date += DAY) {
|
|
73
78
|
const key = new Date(date).toISOString().slice(0, 10);
|
|
74
|
-
days.set(key, { date: key, uses: 0, providers: { claude: 0, codex: 0 }, status: key < countedDay ? 'outside-history' : 'no-uses' });
|
|
79
|
+
days.set(key, { date: key, uses: 0, providers: { claude: 0, codex: 0 }, agent: 0, typed: 0, detected: 0, status: key < countedDay ? 'outside-history' : 'no-uses' });
|
|
75
80
|
}
|
|
76
|
-
for (const use of counted) { const day = days.get(dayKey(use.at)); if (day) { day.uses++; day.providers[use.provider]++; day.status = 'used'; } }
|
|
81
|
+
for (const use of counted) { const day = days.get(dayKey(use.at)); if (day) { day.uses++; day.providers[use.provider]++; day[use.origin]++; day.status = 'used'; } }
|
|
77
82
|
details.history = { timeZone: query.timeZone ?? 'UTC', days: [...days.values()] };
|
|
78
83
|
}
|
|
79
84
|
}
|
|
@@ -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}`)
|
|
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
|
-
|
|
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
|
|
171
|
-
// has;
|
|
172
|
-
//
|
|
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'),
|
|
@@ -58,7 +58,42 @@ export function radarVariables(settings, source) {
|
|
|
58
58
|
}));
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
-
|
|
61
|
+
export const LAUNCH_SOURCE = "Process launch environment";
|
|
62
|
+
|
|
63
|
+
/** Allowlisted telemetry variables from a NUL-separated /proc environ. Every
|
|
64
|
+
* other variable, credentials included, is dropped while parsing. */
|
|
65
|
+
export function environVariables(buffer) {
|
|
66
|
+
const env = {};
|
|
67
|
+
for (const entry of buffer.toString("utf8").split("\0")) {
|
|
68
|
+
const split = entry.indexOf("=");
|
|
69
|
+
const key = entry.slice(0, split);
|
|
70
|
+
if (split > 0 && RADAR_KEYS.includes(key)) env[key] = entry.slice(split + 1);
|
|
71
|
+
}
|
|
72
|
+
return radarVariables({ env }, LAUNCH_SOURCE);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** One row per variable and value across running Claude processes, so sessions
|
|
76
|
+
* launched alike read as one source; the lowest PID keeps rows for different
|
|
77
|
+
* values of a variable apart. Launch values are evidence, never switches. */
|
|
78
|
+
export function launchVariables(processes) {
|
|
79
|
+
const rows = new Map();
|
|
80
|
+
for (const { pid, variables } of [...processes].sort((a, b) => a.pid - b.pid)) {
|
|
81
|
+
for (const variable of variables) {
|
|
82
|
+
const id = JSON.stringify([variable.key, variable.value, variable.rawValue ?? null]);
|
|
83
|
+
const row = rows.get(id);
|
|
84
|
+
if (row) row.more++;
|
|
85
|
+
else rows.set(id, { variable, pid, more: 0 });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return [...rows.values()].map(({ variable, pid, more }) => ({
|
|
89
|
+
...variable, source: `${LAUNCH_SOURCE} · PID ${pid}${more ? ` and ${more} more` : ""}`, launch: true,
|
|
90
|
+
...(BOOLEAN_KEYS.includes(variable.key) ? { editable: false } : {}),
|
|
91
|
+
}));
|
|
92
|
+
}
|
|
93
|
+
|
|
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) {
|
|
62
97
|
const file = await open(path, "r");
|
|
63
98
|
try {
|
|
64
99
|
const stat = await file.stat();
|
|
@@ -70,11 +105,16 @@ async function readBoundedJson(path) {
|
|
|
70
105
|
} finally { await file.close(); }
|
|
71
106
|
}
|
|
72
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
|
+
|
|
73
114
|
export async function readRadarConfig({ home = homedir(), env = process.env, platform = process.platform, readJson = readBoundedJson } = {}) {
|
|
74
115
|
const pathJoin = platform === 'win32' ? win32.join : posix.join;
|
|
75
116
|
const dir = claudeConfigDir(env, home, platform);
|
|
76
|
-
const managed = platform
|
|
77
|
-
: platform === 'linux' ? '/etc/claude-code/managed-settings.json' : '/Library/Application Support/ClaudeCode/managed-settings.json';
|
|
117
|
+
const managed = managedSettingsPath(platform, env);
|
|
78
118
|
const files = [
|
|
79
119
|
["User settings", pathJoin(dir, "settings.json")],
|
|
80
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
|
-
|
|
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,
|
|
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 =
|
|
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 =
|
|
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
|
+
}
|