coldpin 0.0.0-stage → 1.5.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 (102) hide show
  1. package/ACCESSIBILITY.md +17 -0
  2. package/CHANGELOG.md +89 -0
  3. package/CONTRIBUTING.md +36 -0
  4. package/LICENSE +98 -0
  5. package/MAINTENANCE.md +33 -0
  6. package/README.md +142 -2
  7. package/SECURITY.md +34 -0
  8. package/TESTING.md +26 -0
  9. package/agents/coldpin-auditor.md +47 -0
  10. package/agents/coldpin-compliance.md +38 -0
  11. package/agents/coldpin-confusion-auditor.md +38 -0
  12. package/agents/coldpin-discoverer.md +37 -0
  13. package/agents/coldpin-forensics.md +38 -0
  14. package/agents/coldpin-inspector.md +37 -0
  15. package/agents/coldpin-manifest-auditor.md +38 -0
  16. package/assets/icon.svg +7 -0
  17. package/catalog/mcp-schema-pin.json +14 -0
  18. package/catalog/plugin.oms.sig +19 -0
  19. package/catalog/sigma/npx-suspicious-child-process-linux.yml +54 -0
  20. package/catalog/sigma/npx-suspicious-child-process.yml +49 -0
  21. package/catalog/triage-rules.json +104 -0
  22. package/docs/assets/readme-header.svg +21 -0
  23. package/docs/designs/SITEMAP.md +14 -0
  24. package/docs/designs/coldpin.md +68 -0
  25. package/docs/fact-ledger.md +35 -0
  26. package/docs/faq.md +31 -0
  27. package/docs/getting_started.md +62 -0
  28. package/docs/harnesses.md +45 -0
  29. package/docs/privacy.md +27 -0
  30. package/docs/verification/skill-inspector-self-audit.md +33 -0
  31. package/examples/.coldpin.policy.example.json +27 -0
  32. package/examples/.npmrc.example +8 -0
  33. package/examples/mcp_config.private-registry.example.json +42 -0
  34. package/hooks.json +47 -0
  35. package/lib/analysis/parity-and-bisect.mjs +1371 -0
  36. package/lib/analysis/static-triage.mjs +4572 -0
  37. package/lib/cache/sqlite-store.mjs +251 -0
  38. package/lib/cli.mjs +427 -0
  39. package/lib/compliance/audit-log.mjs +357 -0
  40. package/lib/config/policy.mjs +780 -0
  41. package/lib/core/path-confinement.mjs +289 -0
  42. package/lib/core/workflows.mjs +1205 -0
  43. package/lib/discovery/slopsquat-guard.mjs +289 -0
  44. package/lib/hook.mjs +1038 -0
  45. package/lib/intel/registry-osv.mjs +1681 -0
  46. package/lib/mcp/report-store.mjs +175 -0
  47. package/lib/mcp/server.mjs +1387 -0
  48. package/lib/mcp/stdio-transport.mjs +289 -0
  49. package/lib/mcp/tool-catalog.mjs +273 -0
  50. package/lib/mcp/types.mjs +95 -0
  51. package/lib/mcp.mjs +19 -0
  52. package/lib/quarantine/safe-unpack.mjs +568 -0
  53. package/lib/types.mjs +383 -0
  54. package/lib/verdict/engine-and-formatters.mjs +895 -0
  55. package/mcp_config.json +21 -0
  56. package/package.json +71 -3
  57. package/plugin.json +54 -0
  58. package/rules/AGENTS.md +18 -0
  59. package/rules/coldpin-incident-checklist.md +18 -0
  60. package/rules/coldpin-manifest-guard.md +14 -0
  61. package/server.json +38 -0
  62. package/skills/coldpin/BENCHMARK.md +166 -0
  63. package/skills/coldpin/SKILL.md +110 -0
  64. package/skills/coldpin/TEST.md +13 -0
  65. package/skills/coldpin/agents/openai.yaml +6 -0
  66. package/skills/coldpin/assets/icon.svg +7 -0
  67. package/skills/coldpin/assets/runtime-contract.yaml +105 -0
  68. package/skills/coldpin/evals/evals.json +60 -0
  69. package/skills/coldpin/references/aspect-compliance-audit.md +27 -0
  70. package/skills/coldpin/references/aspect-discovery.md +26 -0
  71. package/skills/coldpin/references/aspect-forensics-rea.md +26 -0
  72. package/skills/coldpin/references/aspect-inspection.md +26 -0
  73. package/skills/coldpin/references/aspect-manifest-confusion.md +26 -0
  74. package/skills/coldpin/references/enterprise-policy-schema.md +65 -0
  75. package/skills/coldpin/references/evidence-card-spec.md +27 -0
  76. package/skills/coldpin/references/rea-integration-playbook.md +34 -0
  77. package/skills/coldpin/references/threat-taxonomy.md +35 -0
  78. package/skills/coldpin/skill-card.md +62 -0
  79. package/skills/coldpin/skill.oms.sig +19 -0
  80. package/skills/coldpin/test_scenarios.yaml +61 -0
  81. package/skills/coldpin-audit/SKILL.md +39 -0
  82. package/skills/coldpin-incident/SKILL.md +37 -0
  83. package/src/analysis/parity-and-bisect.ts +1368 -0
  84. package/src/analysis/static-triage.ts +4569 -0
  85. package/src/cache/sqlite-store.ts +248 -0
  86. package/src/cli.ts +424 -0
  87. package/src/compliance/audit-log.ts +354 -0
  88. package/src/config/policy.ts +777 -0
  89. package/src/core/path-confinement.ts +286 -0
  90. package/src/core/workflows.ts +1202 -0
  91. package/src/discovery/slopsquat-guard.ts +286 -0
  92. package/src/hook.ts +1035 -0
  93. package/src/intel/registry-osv.ts +1678 -0
  94. package/src/mcp/report-store.ts +172 -0
  95. package/src/mcp/server.ts +1384 -0
  96. package/src/mcp/stdio-transport.ts +286 -0
  97. package/src/mcp/tool-catalog.ts +270 -0
  98. package/src/mcp/types.ts +92 -0
  99. package/src/mcp.ts +16 -0
  100. package/src/quarantine/safe-unpack.ts +565 -0
  101. package/src/types.ts +380 -0
  102. package/src/verdict/engine-and-formatters.ts +892 -0
package/lib/hook.mjs ADDED
@@ -0,0 +1,1038 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Coldpin Fail-Safe PreToolUse Lifecycle Hook (Pure ES2020, Zero External Dependencies).
4
+ *
5
+ * Binary-verified contract for Antigravity >= v1.5.13:
6
+ * - Benign pass-through MUST emit `{"decision":"allow"}` (exit 0) — emitting `{}` is rewritten to
7
+ * `"deny"` by `applyPreToolHooks`, whereas `"allow"` delegates cleanly to default policy without
8
+ * auto-approval (`EnsurePermissions.func1`).
9
+ * - Provably unsafe/evasive/oversized commands emit `{"decision":"deny","reason":"..."}` (exit 0).
10
+ * - Exact-pinned `--ignore-scripts` single-segment `npx`, sensitive config edits, `define_subagent`
11
+ * requests with write tools, and fail-closed parse/runtime errors emit
12
+ * `{"decision":"force_ask","reason":"..."}` (exit 0).
13
+ * - Exits 0 in 100% of code paths to neutralize host fail-open on non-zero exit.
14
+ * - Pure ES2020 only (compatible with Node 18/20/22/24/26; zero network or subprocess APIs).
15
+ */
16
+
17
+ import { resolve } from "node:path";
18
+ import { pathToFileURL } from "node:url";
19
+
20
+
21
+
22
+
23
+
24
+
25
+ const MAX_COMMAND_STDIN_BYTES = 256 * 1024;
26
+ const MAX_EDIT_HEADER_SCAN_BYTES = 16 * 1024;
27
+ const MAX_EDIT_FALLBACK_BYTES = 8 * 1024 * 1024;
28
+ const MAX_COMMAND_CHARS = 65536;
29
+ const MAX_WRAPPER_DEPTH = 4;
30
+
31
+ const FILE_EDIT_TOOLS = new Set([
32
+ "write_to_file",
33
+ "replace_file_content",
34
+ "multi_replace_file_content",
35
+ "write_file",
36
+ "edit_file",
37
+ "sed_file",
38
+ ]);
39
+
40
+ const SENSITIVE_BASENAMES = new Set([
41
+ ".npmrc",
42
+ ".coldpin.policy.json",
43
+ ".npx-guard.policy.json",
44
+ "hooks.json",
45
+ "mcp_config.json",
46
+ ]);
47
+
48
+ const SENSITIVE_SUFFIXES = [
49
+ "/.agents/plugins.json",
50
+ "/.agents/rules.json",
51
+ "/lib/hook.mjs",
52
+ "/catalog/triage-rules.json",
53
+ "/.gemini/config/config.json",
54
+ ];
55
+
56
+ const POST_DASH_BLOCKED_INTERPRETERS = new Set([
57
+ "sh",
58
+ "bash",
59
+ "zsh",
60
+ "dash",
61
+ "ash",
62
+ "ksh",
63
+ "csh",
64
+ "tcsh",
65
+ "fish",
66
+ "cmd",
67
+ "pwsh",
68
+ "powershell",
69
+ "node",
70
+ "nodejs",
71
+ "deno",
72
+ "bun",
73
+ "python",
74
+ "python3",
75
+ "py",
76
+ "perl",
77
+ "ruby",
78
+ "php",
79
+ "awk",
80
+ "gawk",
81
+ "env",
82
+ "eval",
83
+ "exec",
84
+ "xargs",
85
+ "find",
86
+ "wsl",
87
+ ]);
88
+
89
+ const DOWNLOAD_CMDS = new Set([
90
+ "curl",
91
+ "wget",
92
+ "iwr",
93
+ "irm",
94
+ "invoke-webrequest",
95
+ "invoke-restmethod",
96
+ ]);
97
+
98
+ const PIPE_EXEC_SINKS = new Set([
99
+ "sh",
100
+ "bash",
101
+ "zsh",
102
+ "dash",
103
+ "ash",
104
+ "ksh",
105
+ "iex",
106
+ "invoke-expression",
107
+ "pwsh",
108
+ "powershell",
109
+ "cmd",
110
+ "node",
111
+ "python",
112
+ "python3",
113
+ "perl",
114
+ "ruby",
115
+ ]);
116
+
117
+ const EXACT_PINNED_SPEC_RE =
118
+ /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*@\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
119
+ const SAFE_BIN_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
120
+ const ENV_ASSIGN_RE = /^[A-Za-z_][A-Za-z0-9_]*=(.*)$/;
121
+ const WIN_DRIVE_PATH_RE = /^[A-Za-z]:\\/;
122
+
123
+ function normalizeToken(raw ) {
124
+ let s = raw.trim();
125
+ if (!s) return "";
126
+
127
+ // Strip quote pairs and shell escapes linearly in a single O(n) pass
128
+ let unquoted = "";
129
+ let inSingle = false;
130
+ let inDouble = false;
131
+ const looksLikePath =
132
+ s.startsWith("/") ||
133
+ s.startsWith("./") ||
134
+ s.startsWith("../") ||
135
+ s.startsWith(".\\") ||
136
+ s.startsWith("..\\") ||
137
+ WIN_DRIVE_PATH_RE.test(s) ||
138
+ s.includes("/");
139
+
140
+ for (let i = 0; i < s.length; i++) {
141
+ const ch = s[i] ;
142
+ if (ch === "'" && !inDouble) {
143
+ inSingle = !inSingle;
144
+ continue;
145
+ }
146
+ if (ch === '"' && !inSingle) {
147
+ inDouble = !inDouble;
148
+ continue;
149
+ }
150
+ if (ch === "\\" && !inSingle && !looksLikePath) {
151
+ if (i + 1 < s.length) {
152
+ unquoted += s[i + 1] ;
153
+ i++;
154
+ }
155
+ continue;
156
+ }
157
+ if (ch === "`" && !inSingle) {
158
+ // PowerShell backtick escape (e.g., n`px)
159
+ continue;
160
+ }
161
+ unquoted += ch;
162
+ }
163
+
164
+ return unquoted;
165
+ }
166
+
167
+ function normalizeExecutableName(raw ) {
168
+ const cleaned = normalizeToken(raw);
169
+ if (!cleaned) return "";
170
+ const slashIdx = Math.max(cleaned.lastIndexOf("/"), cleaned.lastIndexOf("\\"));
171
+ const base = slashIdx >= 0 ? cleaned.slice(slashIdx + 1) : cleaned;
172
+ const lower = base.toLowerCase();
173
+ if (lower.endsWith(".cmd")) return lower.slice(0, -4);
174
+ if (lower.endsWith(".exe")) return lower.slice(0, -4);
175
+ if (lower.endsWith(".ps1")) return lower.slice(0, -4);
176
+ if (lower.endsWith(".bat")) return lower.slice(0, -4);
177
+ return lower;
178
+ }
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+ function splitShellCommand(cmd ) {
187
+ const segments = [];
188
+ const subshells = [];
189
+ let curTokens = [];
190
+ let curTok = "";
191
+ let inSingle = false;
192
+ let inDouble = false;
193
+ let hasCompound = false;
194
+
195
+ const pushTok = () => {
196
+ if (curTok.length > 0) {
197
+ curTokens.push(curTok);
198
+ curTok = "";
199
+ }
200
+ };
201
+ const pushSeg = (piped ) => {
202
+ pushTok();
203
+ if (curTokens.length > 0) {
204
+ segments.push({ tokens: curTokens, pipedIntoNext: piped });
205
+ curTokens = [];
206
+ }
207
+ };
208
+
209
+ for (let i = 0; i < cmd.length; i++) {
210
+ const ch = cmd[i] ;
211
+ const next = i + 1 < cmd.length ? cmd[i + 1] : "";
212
+
213
+ if (inSingle) {
214
+ curTok += ch;
215
+ if (ch === "'") inSingle = false;
216
+ continue;
217
+ }
218
+
219
+ if (ch === "\\" && !inDouble) {
220
+ curTok += ch;
221
+ if (i + 1 < cmd.length) {
222
+ curTok += cmd[i + 1] ;
223
+ i++;
224
+ }
225
+ continue;
226
+ }
227
+
228
+ // Extract $(...) subshell payloads even inside double quotes
229
+ if (ch === "$" && next === "(") {
230
+ hasCompound = true;
231
+ let depth = 1;
232
+ let j = i + 2;
233
+ let inner = "";
234
+ let sQ = false;
235
+ let dQ = false;
236
+ while (j < cmd.length && depth > 0) {
237
+ const c = cmd[j] ;
238
+ if (c === "'" && !dQ) sQ = !sQ;
239
+ else if (c === '"' && !sQ) dQ = !dQ;
240
+ else if (!sQ && !dQ) {
241
+ if (c === "(") depth++;
242
+ else if (c === ")") depth--;
243
+ }
244
+ if (depth > 0) inner += c;
245
+ j++;
246
+ }
247
+ if (inner.trim()) subshells.push(inner.trim());
248
+ curTok += "$(SUB)";
249
+ i = j - 1;
250
+ continue;
251
+ }
252
+
253
+ // Distinguish POSIX paired backticks (`cmd arg`) from PowerShell escape (n`px)
254
+ if (ch === "`") {
255
+ const closeIdx = cmd.indexOf("`", i + 1);
256
+ if (closeIdx > i + 1) {
257
+ const inner = cmd.slice(i + 1, closeIdx);
258
+ // If interior has whitespace or slash/semicolon/pipe, treat as POSIX subshell; otherwise PS escape
259
+ if (/[\s;|&]/.test(inner)) {
260
+ hasCompound = true;
261
+ subshells.push(inner.trim());
262
+ curTok += "`SUB`";
263
+ i = closeIdx;
264
+ continue;
265
+ }
266
+ }
267
+ curTok += ch;
268
+ continue;
269
+ }
270
+
271
+ if (inDouble) {
272
+ curTok += ch;
273
+ if (ch === "\\" && i + 1 < cmd.length) {
274
+ curTok += cmd[i + 1] ;
275
+ i++;
276
+ } else if (ch === '"') {
277
+ inDouble = false;
278
+ }
279
+ continue;
280
+ }
281
+
282
+ if (ch === "'") {
283
+ inSingle = true;
284
+ curTok += ch;
285
+ continue;
286
+ }
287
+ if (ch === '"') {
288
+ inDouble = true;
289
+ curTok += ch;
290
+ continue;
291
+ }
292
+
293
+ if (ch === "\n" || ch === "\r" || ch === ";") {
294
+ hasCompound = true;
295
+ pushSeg(false);
296
+ continue;
297
+ }
298
+ if (ch === "&" && next === "&") {
299
+ hasCompound = true;
300
+ pushSeg(false);
301
+ i++;
302
+ continue;
303
+ }
304
+ if (ch === "|" && next === "|") {
305
+ hasCompound = true;
306
+ pushSeg(false);
307
+ i++;
308
+ continue;
309
+ }
310
+ if (ch === "|") {
311
+ hasCompound = true;
312
+ pushSeg(true);
313
+ continue;
314
+ }
315
+ if (ch === "&") {
316
+ hasCompound = true;
317
+ pushSeg(false);
318
+ continue;
319
+ }
320
+ if (ch === " " || ch === "\t") {
321
+ pushTok();
322
+ continue;
323
+ }
324
+ curTok += ch;
325
+ }
326
+
327
+ pushSeg(false);
328
+ if (segments.length > 1) hasCompound = true;
329
+ return { segments, subshells, hasCompound };
330
+ }
331
+
332
+ function isSensitiveConfigCommand(tokens , rawCmd ) {
333
+ const lowerRaw = rawCmd.toLowerCase();
334
+ if (/\bagy(?:\.exe)?\s+plugin\s+(?:disable|uninstall|remove)\b/.test(lowerRaw)) {
335
+ return true;
336
+ }
337
+ const normalizedJoined = tokens.map((t) => normalizeToken(t).toLowerCase()).join(" ");
338
+ const writeHints = [">", "tee", "sed", "rm", "del", "mv", "move", "cp", "copy", "set-content", "out-file", "add-content"];
339
+ const hasWriteHint = writeHints.some((w) => normalizedJoined.includes(w));
340
+ if (!hasWriteHint) return false;
341
+ for (const name of SENSITIVE_BASENAMES) {
342
+ if (normalizedJoined.includes(name)) return true;
343
+ }
344
+ for (const suf of SENSITIVE_SUFFIXES) {
345
+ if (normalizedJoined.includes(suf.slice(1))) return true;
346
+ }
347
+ return false;
348
+ }
349
+
350
+ function evaluateNpxInvocation(
351
+ args ,
352
+ envFlags ,
353
+ hasCompound ,
354
+ ) {
355
+ if (envFlags.disableIgnoreScripts) {
356
+ return {
357
+ decision: "deny",
358
+ reason: "Blocked npx invocation with npm_config_ignore_scripts disabled; vet with Coldpin first.",
359
+ };
360
+ }
361
+ if (envFlags.registryOverride) {
362
+ return {
363
+ decision: "deny",
364
+ reason: "Blocked npx invocation with registry/config environment override.",
365
+ };
366
+ }
367
+
368
+ let hasIgnoreScripts = false;
369
+ let sawDoubleDash = false;
370
+ const packageSpecs = [];
371
+ let postDashCmd = null;
372
+
373
+ for (let i = 0; i < args.length; i++) {
374
+ const raw = args[i] ;
375
+ const tok = normalizeToken(raw);
376
+ const lower = tok.toLowerCase();
377
+
378
+ if (sawDoubleDash) {
379
+ if (postDashCmd === null) postDashCmd = tok;
380
+ if (lower.includes("rea-agents")) {
381
+ return {
382
+ decision: "deny",
383
+ reason: "Blocked self-bootstrap of rea-agents via npx; use pre-installed REA only.",
384
+ };
385
+ }
386
+ continue;
387
+ }
388
+
389
+ if (tok === "--") {
390
+ sawDoubleDash = true;
391
+ continue;
392
+ }
393
+
394
+ if (lower.includes("rea-agents")) {
395
+ return {
396
+ decision: "deny",
397
+ reason: "Blocked self-bootstrap of rea-agents via npx; use pre-installed REA only.",
398
+ };
399
+ }
400
+
401
+ if (lower === "--ignore-scripts" || lower === "--ignore-scripts=true") {
402
+ hasIgnoreScripts = true;
403
+ continue;
404
+ }
405
+ if (lower === "--ignore-scripts=false" || lower === "--no-ignore-scripts") {
406
+ return {
407
+ decision: "deny",
408
+ reason: "Blocked npx invocation disabling --ignore-scripts.",
409
+ };
410
+ }
411
+ if (
412
+ lower === "-c" ||
413
+ lower === "--call" ||
414
+ lower.startsWith("--call=") ||
415
+ lower === "--shell" ||
416
+ lower.startsWith("--shell=") ||
417
+ lower === "--registry" ||
418
+ lower.startsWith("--registry=") ||
419
+ lower === "--userconfig" ||
420
+ lower.startsWith("--userconfig=") ||
421
+ lower === "--globalconfig" ||
422
+ lower.startsWith("--globalconfig=")
423
+ ) {
424
+ return {
425
+ decision: "deny",
426
+ reason: `Blocked unsafe npx flag '${tok}' (shell/registry/config override).`,
427
+ };
428
+ }
429
+ if (lower === "-y" || lower === "--yes" || lower === "-q" || lower === "--quiet" || lower === "--no" || lower === "--no-install") {
430
+ continue;
431
+ }
432
+ if (lower === "-p" || lower === "--package") {
433
+ const nextVal = i + 1 < args.length ? normalizeToken(args[i + 1] ) : "";
434
+ if (!nextVal) {
435
+ return { decision: "deny", reason: "Blocked npx invocation with missing --package specifier." };
436
+ }
437
+ packageSpecs.push(nextVal);
438
+ i++;
439
+ continue;
440
+ }
441
+ if (lower.startsWith("--package=")) {
442
+ packageSpecs.push(tok.slice("--package=".length));
443
+ continue;
444
+ }
445
+ if (lower.startsWith("-p=")) {
446
+ packageSpecs.push(tok.slice("-p=".length));
447
+ continue;
448
+ }
449
+ if (tok.startsWith("-")) {
450
+ // Unknown flags on npx cannot bypass verification
451
+ return {
452
+ decision: "deny",
453
+ reason: `Blocked npx invocation with unvetted flag '${tok}'; use Coldpin's exact pinned command.`,
454
+ };
455
+ }
456
+
457
+ // Positional package/command token before `--`: only the first positional is the package spec
458
+ if (packageSpecs.length === 0) {
459
+ packageSpecs.push(tok);
460
+ // Remaining positional args after direct package spec belong to the invoked binary
461
+ break;
462
+ }
463
+ }
464
+
465
+ if (!hasIgnoreScripts) {
466
+ return {
467
+ decision: "deny",
468
+ reason: "Blocked npx without --ignore-scripts; inspect with Coldpin (inspect_package_artifact) first.",
469
+ };
470
+ }
471
+ if (packageSpecs.length === 0) {
472
+ return {
473
+ decision: "deny",
474
+ reason: "Blocked npx invocation with no pinned package specifier.",
475
+ };
476
+ }
477
+ for (const spec of packageSpecs) {
478
+ const specLower = spec.toLowerCase();
479
+ if (specLower.includes("rea-agents")) {
480
+ return {
481
+ decision: "deny",
482
+ reason: "Blocked self-bootstrap of rea-agents via npx; use pre-installed REA only.",
483
+ };
484
+ }
485
+ if (!EXACT_PINNED_SPEC_RE.test(spec)) {
486
+ return {
487
+ decision: "deny",
488
+ reason: `Blocked unpinned or remote npx package '${spec}'; pin exact X.Y.Z after Coldpin inspection.`,
489
+ };
490
+ }
491
+ }
492
+ if (postDashCmd !== null) {
493
+ const binNorm = normalizeExecutableName(postDashCmd);
494
+ if (!SAFE_BIN_RE.test(postDashCmd) || POST_DASH_BLOCKED_INTERPRETERS.has(binNorm)) {
495
+ return {
496
+ decision: "deny",
497
+ reason: `Blocked shell or interpreter '${postDashCmd}' after npx '--' separator.`,
498
+ };
499
+ }
500
+ }
501
+ if (hasCompound) {
502
+ return {
503
+ decision: "deny",
504
+ reason: "Blocked compound/chained shell command containing npx; run Coldpin's pinned command standalone.",
505
+ };
506
+ }
507
+
508
+ return {
509
+ decision: "force_ask",
510
+ reason: "Coldpin exact-pinned npx command with --ignore-scripts; explicit human confirmation required before execution.",
511
+ };
512
+ }
513
+
514
+ function evaluatePackageManagerInstall(
515
+ mgr ,
516
+ subcmd ,
517
+ args ,
518
+ envFlags ,
519
+ ) {
520
+ if (envFlags.disableIgnoreScripts || envFlags.registryOverride) {
521
+ return {
522
+ decision: "deny",
523
+ reason: `Blocked ${mgr} ${subcmd} with unsafe npm_config environment override.`,
524
+ };
525
+ }
526
+ let hasIgnoreScripts = false;
527
+ for (const raw of args) {
528
+ const lower = normalizeToken(raw).toLowerCase();
529
+ if (lower === "--ignore-scripts" || lower === "--ignore-scripts=true") {
530
+ hasIgnoreScripts = true;
531
+ } else if (
532
+ lower === "--ignore-scripts=false" ||
533
+ lower === "--no-ignore-scripts" ||
534
+ lower === "--registry" ||
535
+ lower.startsWith("--registry=") ||
536
+ lower === "--userconfig" ||
537
+ lower.startsWith("--userconfig=")
538
+ ) {
539
+ return {
540
+ decision: "deny",
541
+ reason: `Blocked ${mgr} ${subcmd} with unsafe flag '${lower}'.`,
542
+ };
543
+ }
544
+ }
545
+ if (!hasIgnoreScripts) {
546
+ return {
547
+ decision: "deny",
548
+ reason: `Blocked ${mgr} ${subcmd} without --ignore-scripts; untrusted lifecycle scripts may execute. Audit with Coldpin first.`,
549
+ };
550
+ }
551
+ return {
552
+ decision: "force_ask",
553
+ reason: `${mgr} ${subcmd} with --ignore-scripts requires explicit human confirmation.`,
554
+ };
555
+ }
556
+
557
+ function extractShellWrapperPayload(exe , args ) {
558
+ if (exe === "sh" || exe === "bash" || exe === "zsh" || exe === "dash" || exe === "ash" || exe === "ksh") {
559
+ for (let i = 0; i < args.length; i++) {
560
+ const t = normalizeToken(args[i] );
561
+ if (t === "-c" || t === "-lc" || t === "-ic" || t === "-ec") {
562
+ return i + 1 < args.length ? normalizeToken(args[i + 1] ) : null;
563
+ }
564
+ }
565
+ }
566
+ if (exe === "cmd") {
567
+ for (let i = 0; i < args.length; i++) {
568
+ const l = normalizeToken(args[i] ).toLowerCase();
569
+ if (l === "/c" || l === "/k") {
570
+ return args.slice(i + 1).map(normalizeToken).join(" ").trim() || null;
571
+ }
572
+ }
573
+ }
574
+ if (exe === "pwsh" || exe === "powershell") {
575
+ for (let i = 0; i < args.length; i++) {
576
+ const l = normalizeToken(args[i] ).toLowerCase();
577
+ if (l === "-c" || l === "-command" || l === "-cmd") {
578
+ return args.slice(i + 1).map(normalizeToken).join(" ").trim() || null;
579
+ }
580
+ }
581
+ }
582
+ if (exe === "wsl") {
583
+ for (let i = 0; i < args.length; i++) {
584
+ const l = normalizeToken(args[i] ).toLowerCase();
585
+ if (l === "--" || l === "-e" || l === "--exec") {
586
+ return args.slice(i + 1).map(normalizeToken).join(" ").trim() || null;
587
+ }
588
+ }
589
+ }
590
+ return null;
591
+ }
592
+
593
+ function mergeDecision(current , next ) {
594
+ if (current.decision === "deny") return current;
595
+ if (next.decision === "deny") return next;
596
+ if (current.decision === "force_ask") return current;
597
+ if (next.decision === "force_ask") return next;
598
+ return { decision: "allow" };
599
+ }
600
+
601
+ export function evaluateCommandText(commandText , depth = 0) {
602
+ if (!commandText || !commandText.trim()) return { decision: "allow" };
603
+ if (commandText.length > MAX_COMMAND_CHARS) {
604
+ return {
605
+ decision: "deny",
606
+ reason: "Oversized command line (>64 KiB) blocked by Coldpin fail-closed hook policy.",
607
+ };
608
+ }
609
+ if (depth > MAX_WRAPPER_DEPTH) {
610
+ return {
611
+ decision: "deny",
612
+ reason: "Excessively nested shell wrapper depth blocked by Coldpin hook policy.",
613
+ };
614
+ }
615
+
616
+ const parsed = splitShellCommand(commandText);
617
+ let verdict = { decision: "allow" };
618
+
619
+ // Inspect extracted subshells ($(...) and `...`) recursively
620
+ for (const sub of parsed.subshells) {
621
+ const subDecision = evaluateCommandText(sub, depth + 1);
622
+ if (subDecision.decision === "deny") return subDecision;
623
+ // Any npx inside a subshell must be denied (cannot run standalone pinned command inside subshell)
624
+ if (subDecision.decision === "force_ask" && /\bnpx\b/i.test(sub)) {
625
+ return {
626
+ decision: "deny",
627
+ reason: "Blocked npx invocation inside shell subshell.",
628
+ };
629
+ }
630
+ verdict = mergeDecision(verdict, subDecision);
631
+ }
632
+
633
+ // Inspect pipe chains (download | shell) and each segment
634
+ for (let sIdx = 0; sIdx < parsed.segments.length; sIdx++) {
635
+ const seg = parsed.segments[sIdx] ;
636
+ const tokens = seg.tokens;
637
+ if (tokens.length === 0) continue;
638
+
639
+ // Strip leading env / command / sudo / VAR=val assignments
640
+ let idx = 0;
641
+ const envFlags = { disableIgnoreScripts: false, registryOverride: false };
642
+ while (idx < tokens.length) {
643
+ const rawTok = tokens[idx] ;
644
+ const normTok = normalizeToken(rawTok);
645
+ const envMatch = ENV_ASSIGN_RE.exec(normTok);
646
+ if (envMatch) {
647
+ const keyLower = normTok.slice(0, normTok.indexOf("=")).toLowerCase();
648
+ const valLower = (envMatch[1] ?? "").trim().toLowerCase();
649
+ if (keyLower === "npm_config_ignore_scripts" && (valLower === "false" || valLower === "0" || valLower === "no")) {
650
+ envFlags.disableIgnoreScripts = true;
651
+ }
652
+ if (keyLower === "npm_config_registry" || keyLower === "npm_config_userconfig" || keyLower === "npm_config_globalconfig") {
653
+ envFlags.registryOverride = true;
654
+ }
655
+ idx++;
656
+ continue;
657
+ }
658
+ const exeCandidate = normalizeExecutableName(rawTok);
659
+ if (exeCandidate === "env" || exeCandidate === "command" || exeCandidate === "sudo" || exeCandidate === "nohup" || exeCandidate === "time") {
660
+ idx++;
661
+ // Skip short flags on env/sudo (e.g., env -i, sudo -E)
662
+ while (idx < tokens.length && normalizeToken(tokens[idx] ).startsWith("-")) {
663
+ idx++;
664
+ }
665
+ continue;
666
+ }
667
+ break;
668
+ }
669
+
670
+ if (idx >= tokens.length) continue;
671
+ const exe = normalizeExecutableName(tokens[idx] );
672
+ const rest = tokens.slice(idx + 1);
673
+
674
+ // Download-and-execute pipe check (curl/wget/iwr/irm | sh/bash/iex/pwsh)
675
+ if (DOWNLOAD_CMDS.has(exe) && seg.pipedIntoNext && sIdx + 1 < parsed.segments.length) {
676
+ const nextSeg = parsed.segments[sIdx + 1] ;
677
+ const nextExe = nextSeg.tokens[0] ? normalizeExecutableName(nextSeg.tokens[0]) : "";
678
+ if (PIPE_EXEC_SINKS.has(nextExe)) {
679
+ return {
680
+ decision: "deny",
681
+ reason: `Blocked download-and-execute pipe (${exe} | ${nextExe}) under Coldpin supply-chain policy.`,
682
+ };
683
+ }
684
+ }
685
+
686
+ // Shell wrapper recursion (sh -c, bash -c, cmd /c, pwsh -c, wsl --)
687
+ const wrapped = extractShellWrapperPayload(exe, rest);
688
+ if (wrapped !== null) {
689
+ const innerDecision = evaluateCommandText(wrapped, depth + 1);
690
+ if (innerDecision.decision === "deny") return innerDecision;
691
+ if (innerDecision.decision === "force_ask" && parsed.hasCompound) {
692
+ return {
693
+ decision: "deny",
694
+ reason: "Blocked wrapped compound package-runner invocation.",
695
+ };
696
+ }
697
+ verdict = mergeDecision(verdict, innerDecision);
698
+ continue;
699
+ }
700
+
701
+ // Direct npx
702
+ if (exe === "npx") {
703
+ const d = evaluateNpxInvocation(rest, envFlags, parsed.hasCompound || depth > 0);
704
+ if (d.decision === "deny") return d;
705
+ verdict = mergeDecision(verdict, d);
706
+ continue;
707
+ }
708
+
709
+ // Alternative package runners: pnpx, bunx, corepack
710
+ if (exe === "pnpx" || exe === "bunx" || exe === "corepack") {
711
+ return {
712
+ decision: "deny",
713
+ reason: `Blocked unvetted package runner '${exe}'; inspect with Coldpin and use Coldpin's exact pinned command.`,
714
+ };
715
+ }
716
+
717
+ // npm / pnpm / yarn / bun subcommands
718
+ if (exe === "npm" || exe === "pnpm" || exe === "yarn" || exe === "bun") {
719
+ const subIdx = rest.findIndex((t) => !normalizeToken(t).startsWith("-"));
720
+ const sub = subIdx >= 0 ? normalizeToken(rest[subIdx] ).toLowerCase() : "";
721
+ const subArgs = subIdx >= 0 ? [...rest.slice(0, subIdx), ...rest.slice(subIdx + 1)] : rest;
722
+
723
+ if (
724
+ (exe === "npm" && (sub === "exec" || sub === "x" || sub === "create")) ||
725
+ (exe === "pnpm" && (sub === "dlx" || sub === "exec" || sub === "create")) ||
726
+ (exe === "yarn" && (sub === "dlx" || sub === "create")) ||
727
+ (exe === "bun" && (sub === "x" || sub === "create"))
728
+ ) {
729
+ return {
730
+ decision: "deny",
731
+ reason: `Blocked unvetted package runner '${exe} ${sub}'; inspect with Coldpin first.`,
732
+ };
733
+ }
734
+
735
+ if (exe === "npm" && sub === "init") {
736
+ // `npm init <pkg>` invokes create-<pkg> from npm registry! Allow only bare `npm init -y`
737
+ const hasInitializer = subArgs.some((a) => !normalizeToken(a).startsWith("-"));
738
+ if (hasInitializer) {
739
+ return {
740
+ decision: "deny",
741
+ reason: "Blocked 'npm init <initializer>' remote package execution; inspect with Coldpin first.",
742
+ };
743
+ }
744
+ }
745
+
746
+ if (sub === "install" || sub === "i" || sub === "ci" || sub === "add") {
747
+ const d = evaluatePackageManagerInstall(exe, sub, subArgs, envFlags);
748
+ if (d.decision === "deny") return d;
749
+ verdict = mergeDecision(verdict, d);
750
+ continue;
751
+ }
752
+ }
753
+
754
+ // Security control tampering via shell
755
+ if (isSensitiveConfigCommand(tokens, commandText)) {
756
+ verdict = mergeDecision(verdict, {
757
+ decision: "force_ask",
758
+ reason: "Command modifies Coldpin or npm security configuration; explicit human confirmation required.",
759
+ });
760
+ }
761
+ }
762
+
763
+ return verdict;
764
+ }
765
+
766
+ export function evaluateFileEditPath(rawPath ) {
767
+ if (!rawPath || typeof rawPath !== "string") return { decision: "allow" };
768
+ const norm = rawPath.replace(/\\/g, "/").trim().toLowerCase();
769
+ if (!norm) return { decision: "allow" };
770
+ const slashIdx = norm.lastIndexOf("/");
771
+ const base = slashIdx >= 0 ? norm.slice(slashIdx + 1) : norm;
772
+
773
+ if (SENSITIVE_BASENAMES.has(base)) {
774
+ return {
775
+ decision: "force_ask",
776
+ reason: `Editing security-sensitive file '${base}' requires explicit human confirmation.`,
777
+ };
778
+ }
779
+ for (const suffix of SENSITIVE_SUFFIXES) {
780
+ if (norm.endsWith(suffix) || norm === suffix.slice(1)) {
781
+ return {
782
+ decision: "force_ask",
783
+ reason: `Editing security-sensitive path '${suffix.slice(1)}' requires explicit human confirmation.`,
784
+ };
785
+ }
786
+ }
787
+ return { decision: "allow" };
788
+ }
789
+
790
+ function getStringProp(obj , keys ) {
791
+ for (const k of keys) {
792
+ const v = obj[k];
793
+ if (typeof v === "string") return v;
794
+ }
795
+ return undefined;
796
+ }
797
+
798
+ function isTrueFlag(val ) {
799
+ if (val === true) return true;
800
+ if (typeof val === "string") return val.trim().toLowerCase() === "true";
801
+ return false;
802
+ }
803
+
804
+ export function evaluatePreToolUsePayload(payload ) {
805
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
806
+ return {
807
+ decision: "force_ask",
808
+ reason: "Malformed hook payload; requiring explicit human confirmation (fail-closed).",
809
+ };
810
+ }
811
+
812
+ const root = payload ;
813
+ const toolCallObj =
814
+ root["toolCall"] && typeof root["toolCall"] === "object" && !Array.isArray(root["toolCall"])
815
+ ? (root["toolCall"] )
816
+ : root;
817
+
818
+ const toolName = getStringProp(toolCallObj, ["name", "tool_name", "toolName"]) ?? "";
819
+ const rawArgs =
820
+ toolCallObj["args"] ?? toolCallObj["arguments"] ?? toolCallObj["tool_input"] ?? toolCallObj["input"] ?? {};
821
+ const args =
822
+ rawArgs && typeof rawArgs === "object" && !Array.isArray(rawArgs) ? (rawArgs ) : {};
823
+
824
+ if (toolName === "run_command") {
825
+ const cmd = getStringProp(args, ["CommandLine", "command", "cmd"]);
826
+ if (!cmd) return { decision: "allow" };
827
+ return evaluateCommandText(cmd);
828
+ }
829
+
830
+ if (toolName === "manage_task") {
831
+ const action = (getStringProp(args, ["Action", "action"]) ?? "").toLowerCase();
832
+ if (action === "send_input") {
833
+ const input = getStringProp(args, ["Input", "input"]);
834
+ if (!input) return { decision: "allow" };
835
+ return evaluateCommandText(input);
836
+ }
837
+ return { decision: "allow" };
838
+ }
839
+
840
+ if (FILE_EDIT_TOOLS.has(toolName)) {
841
+ const targetPath = getStringProp(args, ["TargetFile", "Path", "path", "file_path", "AbsolutePath", "FilePath"]);
842
+ return evaluateFileEditPath(targetPath);
843
+ }
844
+
845
+ if (toolName === "define_subagent") {
846
+ if (isTrueFlag(args["EnableWriteTools"]) || isTrueFlag(args["enable_write_tools"])) {
847
+ return {
848
+ decision: "force_ask",
849
+ reason: "Dynamic subagent requests write/shell tools (EnableWriteTools=true); explicit human confirmation required.",
850
+ };
851
+ }
852
+ return { decision: "allow" };
853
+ }
854
+
855
+ return { decision: "allow" };
856
+ }
857
+
858
+ /**
859
+ * Linear prefix JSON string extractor for oversized file-edit payloads (`>256 KiB` `CodeContent`).
860
+ * Extracts a JSON string value for a given property key without parsing megabytes of source code.
861
+ */
862
+ function extractJsonStringFieldFromPrefix(prefix , keys ) {
863
+ for (const key of keys) {
864
+ const needle = `"${key}"`;
865
+ let pos = 0;
866
+ while (pos < prefix.length) {
867
+ const idx = prefix.indexOf(needle, pos);
868
+ if (idx < 0) break;
869
+ let j = idx + needle.length;
870
+ while (j < prefix.length && (prefix[j] === " " || prefix[j] === "\t" || prefix[j] === "\r" || prefix[j] === "\n")) j++;
871
+ if (prefix[j] !== ":") {
872
+ pos = idx + needle.length;
873
+ continue;
874
+ }
875
+ j++;
876
+ while (j < prefix.length && (prefix[j] === " " || prefix[j] === "\t" || prefix[j] === "\r" || prefix[j] === "\n")) j++;
877
+ if (prefix[j] !== '"') {
878
+ pos = j;
879
+ continue;
880
+ }
881
+ j++;
882
+ let rawStr = '"';
883
+ let closed = false;
884
+ while (j < prefix.length) {
885
+ const ch = prefix[j] ;
886
+ rawStr += ch;
887
+ if (ch === "\\" && j + 1 < prefix.length) {
888
+ rawStr += prefix[j + 1] ;
889
+ j += 2;
890
+ continue;
891
+ }
892
+ if (ch === '"') {
893
+ closed = true;
894
+ break;
895
+ }
896
+ j++;
897
+ }
898
+ if (closed) {
899
+ try {
900
+ const parsed = JSON.parse(rawStr);
901
+ if (typeof parsed === "string") return parsed;
902
+ } catch {
903
+ return undefined;
904
+ }
905
+ }
906
+ pos = j;
907
+ }
908
+ }
909
+ return undefined;
910
+ }
911
+
912
+ function runCliHook() {
913
+ let emitted = false;
914
+ const verbose = process.env["COLDPIN_HOOK_VERBOSE"] === "1";
915
+
916
+ const emitAndExit = (result , diag ) => {
917
+ if (emitted) return;
918
+ emitted = true;
919
+ if (verbose && diag) {
920
+ try {
921
+ process.stderr.write(`[coldpin-hook] ${diag}\n`);
922
+ } catch {
923
+ // Ignore stderr errors
924
+ }
925
+ }
926
+ try {
927
+ process.stdout.write(`${JSON.stringify(result)}\n`);
928
+ } catch {
929
+ // Best-effort stdout write
930
+ }
931
+ process.exit(0);
932
+ };
933
+
934
+ process.on("uncaughtException", (err) => {
935
+ emitAndExit(
936
+ { decision: "force_ask", reason: "Coldpin hook encountered an internal error; explicit human confirmation required." },
937
+ `uncaughtException: ${err instanceof Error ? err.message : String(err)}`,
938
+ );
939
+ });
940
+ process.on("unhandledRejection", (reason) => {
941
+ emitAndExit(
942
+ { decision: "force_ask", reason: "Coldpin hook encountered an async error; explicit human confirmation required." },
943
+ `unhandledRejection: ${String(reason)}`,
944
+ );
945
+ });
946
+
947
+ const chunks = [];
948
+ let totalBytes = 0;
949
+ let detectedToolName ;
950
+
951
+ process.stdin.on("data", (chunk ) => {
952
+ if (emitted) return;
953
+ const buf = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
954
+ totalBytes += buf.length;
955
+ chunks.push(buf);
956
+
957
+ if (detectedToolName === undefined && totalBytes >= 64) {
958
+ const prefix = Buffer.concat(chunks).subarray(0, MAX_EDIT_HEADER_SCAN_BYTES).toString("utf8");
959
+ detectedToolName = extractJsonStringFieldFromPrefix(prefix, ["name", "tool_name", "toolName"]);
960
+ }
961
+
962
+ if (totalBytes > MAX_COMMAND_STDIN_BYTES) {
963
+ if (detectedToolName && FILE_EDIT_TOOLS.has(detectedToolName)) {
964
+ const prefix = Buffer.concat(chunks).subarray(0, MAX_EDIT_HEADER_SCAN_BYTES).toString("utf8");
965
+ const fastPath = extractJsonStringFieldFromPrefix(prefix, [
966
+ "TargetFile",
967
+ "Path",
968
+ "path",
969
+ "file_path",
970
+ "AbsolutePath",
971
+ "FilePath",
972
+ ]);
973
+ if (fastPath !== undefined) {
974
+ emitAndExit(evaluateFileEditPath(fastPath), `fast-path edit decision for ${detectedToolName}`);
975
+ return;
976
+ }
977
+ if (totalBytes > MAX_EDIT_FALLBACK_BYTES) {
978
+ emitAndExit(
979
+ {
980
+ decision: "force_ask",
981
+ reason: "Oversized file-edit payload (>8 MiB) without resolvable target path; confirmation required.",
982
+ },
983
+ `oversized edit payload (${totalBytes} bytes)`,
984
+ );
985
+ return;
986
+ }
987
+ } else {
988
+ emitAndExit(
989
+ {
990
+ decision: "deny",
991
+ reason: "Oversized command payload (>256 KiB) blocked by Coldpin fail-closed hook policy.",
992
+ },
993
+ `oversized non-edit payload (${totalBytes} bytes)`,
994
+ );
995
+ return;
996
+ }
997
+ }
998
+ });
999
+
1000
+ process.stdin.on("end", () => {
1001
+ if (emitted) return;
1002
+ try {
1003
+ const raw = Buffer.concat(chunks).toString("utf8").trim();
1004
+ if (!raw) {
1005
+ emitAndExit(
1006
+ { decision: "force_ask", reason: "Empty hook stdin payload; explicit human confirmation required." },
1007
+ "empty stdin",
1008
+ );
1009
+ return;
1010
+ }
1011
+ const parsed = JSON.parse(raw);
1012
+ emitAndExit(evaluatePreToolUsePayload(parsed), "evaluated payload");
1013
+ } catch (err) {
1014
+ emitAndExit(
1015
+ { decision: "force_ask", reason: "Malformed JSON on hook stdin; explicit human confirmation required." },
1016
+ `parse error: ${err instanceof Error ? err.message : String(err)}`,
1017
+ );
1018
+ }
1019
+ });
1020
+
1021
+ process.stdin.on("error", (err) => {
1022
+ emitAndExit(
1023
+ { decision: "force_ask", reason: "Hook stdin read error; explicit human confirmation required." },
1024
+ `stdin error: ${err instanceof Error ? err.message : String(err)}`,
1025
+ );
1026
+ });
1027
+ }
1028
+
1029
+ const isEntrypoint =
1030
+ typeof process.argv[1] === "string" &&
1031
+ import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
1032
+
1033
+ if (isEntrypoint) {
1034
+ runCliHook();
1035
+ }
1036
+
1037
+
1038
+ //# sourceURL=hook.ts