-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhook.ts
More file actions
289 lines (250 loc) · 10.4 KB
/
hook.ts
File metadata and controls
289 lines (250 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#!/usr/bin/env bun
/**
* Commit Cursor Hook — beforeShellExecution
*
* Intercepts npm / pip / cargo / go install commands and scores
* each package against the Commit API (getcommit.dev).
*
* CRITICAL packages are blocked by default.
* HIGH packages trigger a warning (ask user).
*
* Usage: add to .cursor/hooks.json (see README.md)
*
* Environment variables:
* COMMIT_API_KEY — API key (free at getcommit.dev/get-started)
* COMMIT_HOOK_SEVERITY_BLOCK — severity to block: "CRITICAL" (default) or "HIGH"
*/
import { readFileSync } from "fs";
// ── Types ────────────────────────────────────────────────────────────────────
interface CursorHookInput {
command: string;
cwd?: string;
sandbox?: boolean;
conversation_id?: string;
generation_id?: string;
model?: string;
hook_event_name?: string;
cursor_version?: string;
workspace_roots?: string[];
user_email?: string | null;
transcript_path?: string | null;
}
interface HookDecision {
permission: "allow" | "deny" | "ask";
user_message?: string;
agent_message?: string;
}
interface PackageScore {
name: string;
ecosystem: string;
commitmentScore?: number;
maintainerCount?: number;
recentWeeklyDownloads?: number;
riskFlags?: string[];
error?: string;
}
// ── Config ───────────────────────────────────────────────────────────────────
const API_KEY = process.env.COMMIT_API_KEY ?? "";
const SEVERITY_BLOCK = (process.env.COMMIT_HOOK_SEVERITY_BLOCK ?? "CRITICAL").toUpperCase();
const API_BASE = "https://poc-backend.amdal-dev.workers.dev";
// In-memory session cache: "ecosystem:package" → PackageScore
const scoreCache = new Map<string, PackageScore>();
// ── Command Parsing ──────────────────────────────────────────────────────────
interface ParsedInstall {
ecosystem: "npm" | "pypi" | "cargo" | "go";
packages: string[];
}
/**
* Parse a shell command and extract package install targets.
* Returns null if not a known package install command.
*/
function parseInstallCommand(command: string): ParsedInstall | null {
const cmd = command.trim();
// npm / npx / pnpm / yarn
const npmMatch = cmd.match(
/^(?:npm\s+(?:i|install|add)|npx\s+\S+\s+|pnpm\s+(?:i|install|add)|yarn\s+add)\s+(.+)/
);
if (npmMatch) {
const args = parseArgs(npmMatch[1]);
const packages = args.filter(
(a) =>
!a.startsWith("-") &&
!a.startsWith("--") &&
a !== "install" &&
a !== "add"
);
if (packages.length > 0) return { ecosystem: "npm", packages };
}
// pip / pip3 / uv pip
const pipMatch = cmd.match(
/^(?:pip3?\s+install|uv\s+pip\s+install|python3?\s+-m\s+pip\s+install)\s+(.+)/
);
if (pipMatch) {
const args = parseArgs(pipMatch[1]);
const packages = args
.filter((a) => !a.startsWith("-"))
.map((a) => a.split("==")[0].split(">=")[0].split("<=")[0].trim())
.filter(Boolean);
if (packages.length > 0) return { ecosystem: "pypi", packages };
}
// cargo add / cargo install
const cargoMatch = cmd.match(/^cargo\s+(?:add|install)\s+(.+)/);
if (cargoMatch) {
const args = parseArgs(cargoMatch[1]);
const packages = args.filter((a) => !a.startsWith("-"));
if (packages.length > 0) return { ecosystem: "cargo", packages };
}
// go get / go install
const goMatch = cmd.match(/^go\s+(?:get|install)\s+(.+)/);
if (goMatch) {
const args = parseArgs(goMatch[1]);
const packages = args
.filter((a) => !a.startsWith("-"))
.map((a) => a.split("@")[0]) // strip @version
.filter(Boolean);
if (packages.length > 0) return { ecosystem: "go", packages };
}
return null;
}
/** Naive argument splitter — handles quoted strings. */
function parseArgs(str: string): string[] {
const args: string[] = [];
let current = "";
let inQuote: string | null = null;
for (const ch of str) {
if (inQuote) {
if (ch === inQuote) inQuote = null;
else current += ch;
} else if (ch === '"' || ch === "'") {
inQuote = ch;
} else if (ch === " " || ch === "\t") {
if (current) args.push(current);
current = "";
} else {
current += ch;
}
}
if (current) args.push(current);
return args;
}
// ── Scoring ──────────────────────────────────────────────────────────────────
async function scorePackages(
ecosystem: string,
packages: string[]
): Promise<PackageScore[]> {
const uncached = packages.filter(
(p) => !scoreCache.has(`${ecosystem}:${p}`)
);
if (uncached.length > 0) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
"Accept": "application/json",
};
if (API_KEY) headers["Authorization"] = `Bearer ${API_KEY}`;
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 4500); // stay <500ms total
const resp = await fetch(`${API_BASE}/api/audit`, {
method: "POST",
headers,
body: JSON.stringify({ packages: uncached, ecosystem }),
signal: controller.signal,
});
clearTimeout(timeout);
if (resp.ok || resp.status === 429) {
const data = await resp.json() as any;
// 200 → data.results; 429 with partial results → data.packages_already_scored
const results: any[] = data?.results ?? data?.packages_already_scored ?? [];
for (const r of results) {
const key = `${ecosystem}:${r.name}`;
// Audit results use `score`; score endpoint uses `commitmentScore`
scoreCache.set(key, {
name: r.name,
ecosystem,
commitmentScore: r.score ?? r.commitmentScore,
maintainerCount: r.maintainers ?? r.maintainerCount,
recentWeeklyDownloads: r.weeklyDownloads ?? r.recentWeeklyDownloads,
riskFlags: r.riskFlags ?? [],
});
}
}
} catch (_e) {
// network error / timeout — fail open
}
}
return packages.map((p) => {
const cached = scoreCache.get(`${ecosystem}:${p}`);
if (cached) return cached;
return { name: p, ecosystem, error: "not scored" };
});
}
// ── Risk classification ──────────────────────────────────────────────────────
function getRisk(score: PackageScore): "CRITICAL" | "HIGH" | "OK" | "UNKNOWN" {
if (score.error) return "UNKNOWN";
const flags = score.riskFlags ?? [];
if (flags.some((f) => f.startsWith("CRITICAL"))) return "CRITICAL";
if (flags.some((f) => f.startsWith("HIGH"))) return "HIGH";
return "OK";
}
// ── Decision ─────────────────────────────────────────────────────────────────
function formatScore(s: PackageScore): string {
const risk = getRisk(s);
const icon =
risk === "CRITICAL" ? "🔴" : risk === "HIGH" ? "🟡" : risk === "OK" ? "✅" : "⚪";
const score =
s.commitmentScore != null ? ` (score ${s.commitmentScore}/100)` : "";
const flags = s.riskFlags?.length
? ` — ${s.riskFlags.slice(0, 2).join(", ")}`
: "";
return ` ${icon} ${s.name}${score}${flags}`;
}
async function decide(input: CursorHookInput): Promise<HookDecision> {
const parsed = parseInstallCommand(input.command);
if (!parsed) return { permission: "allow" };
const scores = await scorePackages(parsed.ecosystem, parsed.packages);
const critical = scores.filter((s) => getRisk(s) === "CRITICAL");
const high = scores.filter((s) => getRisk(s) === "HIGH");
const ok = scores.filter((s) => getRisk(s) === "OK");
const shouldBlock =
(SEVERITY_BLOCK === "CRITICAL" && critical.length > 0) ||
(SEVERITY_BLOCK === "HIGH" && (critical.length > 0 || high.length > 0));
const scoreLines = scores.map(formatScore).join("\n");
const apiUrl = `https://getcommit.dev/audit?packages=${parsed.packages.join(",")}&ecosystem=${parsed.ecosystem}`;
if (shouldBlock) {
const blocked = SEVERITY_BLOCK === "HIGH" ? [...critical, ...high] : critical;
const names = blocked.map((s) => s.name).join(", ");
const user_message = `🔴 Commit blocked: ${names} ${blocked.length === 1 ? "is" : "are"} flagged CRITICAL by Commit supply chain scoring.\n\n${scoreLines}\n\n→ Review: ${apiUrl}`;
const agent_message = `Package install blocked by Commit hook. The following ${parsed.ecosystem} packages are flagged CRITICAL (single publisher, high download volume — the exact attack surface exploited by the axios and node-ipc supply chain attacks):\n\n${scoreLines}\n\nThe agent should use a safer alternative or get explicit user approval. Full report: ${apiUrl}`;
return { permission: "deny", user_message, agent_message };
}
if (high.length > 0 && SEVERITY_BLOCK !== "HIGH") {
const names = high.map((s) => s.name).join(", ");
const user_message = `🟡 Commit: ${names} scored HIGH risk.\n\n${scoreLines}\n\nProceed? → ${apiUrl}`;
const agent_message = `Package install flagged HIGH risk by Commit hook.\n\n${scoreLines}\n\nReport: ${apiUrl}`;
return { permission: "ask", user_message, agent_message };
}
// All OK — allow silently
return { permission: "allow" };
}
// ── Main ─────────────────────────────────────────────────────────────────────
async function main() {
let input: CursorHookInput;
try {
const raw = readFileSync("/dev/stdin", "utf-8");
input = JSON.parse(raw);
} catch {
// Can't parse stdin — fail open
process.stdout.write(JSON.stringify({ permission: "allow" }));
process.exit(0);
}
try {
const decision = await decide(input);
process.stdout.write(JSON.stringify(decision));
process.exit(0);
} catch {
// Unexpected error — fail open
process.stdout.write(JSON.stringify({ permission: "allow" }));
process.exit(0);
}
}
main();