-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfailproofai-pack.mjs
More file actions
1999 lines (1991 loc) · 71.2 KB
/
Copy pathfailproofai-pack.mjs
File metadata and controls
1999 lines (1991 loc) · 71.2 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// policy-pack/.entry.generated.ts
import { customPolicies } from "failproofai";
// src/hooks/builtin-policies.ts
import { resolve as resolve2, join as join2 } from "node:path";
import { statSync as statSync2 } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { execSync, execFileSync } from "node:child_process";
import { homedir as homedir2 } from "node:os";
// src/hooks/policy-catalog.ts
var POLICY_CATALOG = [
{
name: "sanitize-jwt",
description: "Stop Claude from reading JWTs in tool responses",
displayTitle: "Redacted JWT tokens from tool output",
impact: "Stops the agent from echoing auth tokens it saw in command output.",
match: { events: ["PostToolUse"] },
defaultEnabled: true,
category: "Sanitize"
},
{
name: "sanitize-api-keys",
description: "Stop Claude from reading API keys (OpenAI, Anthropic, GitHub, AWS, Stripe, Google) in tool responses",
displayTitle: "Redacted API keys from tool output",
impact: "Catches OpenAI / Anthropic / GitHub / AWS / Stripe / Google keys before the model sees them.",
match: { events: ["PostToolUse"] },
defaultEnabled: true,
category: "Sanitize",
params: {
additionalPatterns: {
type: "pattern[]",
description: "Additional API key patterns to scrub, each with { regex, label }",
default: []
}
}
},
{
name: "sanitize-connection-strings",
description: "Stop Claude from reading database connection strings with embedded credentials in tool responses",
displayTitle: "Redacted database connection strings from tool output",
impact: "Strips embedded DB credentials before they reach the model context.",
match: { events: ["PostToolUse"] },
defaultEnabled: true,
category: "Sanitize"
},
{
name: "sanitize-private-key-content",
description: "Stop Claude from reading PEM private key content in tool responses",
displayTitle: "Redacted PEM private keys from tool output",
impact: "Prevents private key bodies from being echoed into chat context.",
match: { events: ["PostToolUse"] },
defaultEnabled: true,
category: "Sanitize"
},
{
name: "sanitize-bearer-tokens",
displayTitle: "Redacted bearer tokens from tool output",
impact: "Strips Authorization: Bearer values before they hit the model.",
description: "Stop Claude from reading Authorization Bearer tokens in tool responses",
match: { events: ["PostToolUse"] },
defaultEnabled: true,
category: "Sanitize"
},
{
name: "protect-env-vars",
displayTitle: "Tried to dump environment variables to chat",
impact: "Env vars often contain secrets; blocking `env` / `printenv` keeps them out of the model context.",
description: "Prevent commands that read environment variables",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: true,
category: "Environment"
},
{
name: "block-env-files",
displayTitle: "Tried to read or write a .env file",
impact: "`.env` files routinely contain API keys and DB credentials.",
description: "Block reading/writing .env files",
match: { events: ["PreToolUse"] },
defaultEnabled: true,
category: "Environment"
},
{
name: "block-read-outside-cwd",
displayTitle: "Tried to read files outside your project directory",
impact: "Stops the agent from peeking at neighboring repos or your home directory.",
description: "Block file reads outside the session working directory",
match: { events: ["PreToolUse"], toolNames: ["Read", "Glob", "Grep", "Bash"] },
defaultEnabled: false,
category: "Environment",
params: {
allowPaths: {
type: "string[]",
description: "Absolute paths outside cwd that are allowed to be read",
default: []
}
}
},
{
name: "block-sudo",
displayTitle: "Tried to run a command with sudo",
impact: "Sudo gives the agent root — blocked unless explicitly allow-listed.",
description: "Block sudo commands",
match: { events: ["PreToolUse", "PermissionRequest"], toolNames: ["Bash"] },
defaultEnabled: true,
category: "Dangerous Commands",
params: {
allowPatterns: {
type: "string[]",
description: "Sudo command patterns to allow, matched token-by-token (e.g. 'sudo systemctl status')",
default: []
}
}
},
{
name: "block-curl-pipe-sh",
displayTitle: "Tried to pipe a downloaded script straight to a shell",
impact: "`curl ... | sh` runs unverified remote code on your machine.",
description: "Block piping downloads to shell",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: true,
category: "Dangerous Commands"
},
{
name: "block-rm-rf",
displayTitle: "Tried to recursively delete a system path",
impact: "Catches catastrophic `rm -rf /` and Windows equivalents.",
description: "Prevent catastrophic deletions",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Dangerous Commands",
params: {
allowPaths: {
type: "string[]",
description: "Paths that are allowed to be recursively deleted",
default: []
}
}
},
{
name: "block-failproofai-commands",
displayTitle: "Tried to disable, pause or modify failproofai itself",
impact: "An agent that can pause or remove enforcement can switch off every other policy.",
description: "Block failproofai CLI commands, self-pause and uninstallation",
match: { events: ["PreToolUse", "PermissionRequest"], toolNames: ["Bash"] },
defaultEnabled: true,
alwaysOn: true,
category: "Dangerous Commands"
},
{
name: "block-kubectl",
displayTitle: "Tried to run a Kubernetes command",
impact: "kubectl can change live cluster state — gated unless allow-listed.",
description: "Block kubectl commands (Kubernetes cluster mutations)",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Infra Commands",
params: {
allowPatterns: {
type: "string[]",
description: "kubectl command patterns to allow, matched token-by-token (e.g. 'kubectl get *', 'kubectl describe *')",
default: []
}
}
},
{
name: "block-terraform",
displayTitle: "Tried to run a Terraform/OpenTofu command",
impact: "Terraform mutates real infrastructure — gated unless allow-listed.",
description: "Block terraform and tofu (OpenTofu) commands",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Infra Commands",
params: {
allowPatterns: {
type: "string[]",
description: "terraform/tofu command patterns to allow (e.g. 'terraform plan', 'terraform validate')",
default: []
}
}
},
{
name: "block-aws-cli",
displayTitle: "Tried to run an AWS CLI command",
impact: "AWS CLI can spend money or break prod — gated.",
description: "Block aws CLI commands",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Infra Commands",
params: {
allowPatterns: {
type: "string[]",
description: "aws CLI command patterns to allow (e.g. 'aws s3 ls *', 'aws sts get-caller-identity')",
default: []
}
}
},
{
name: "block-gcloud",
displayTitle: "Tried to run a Google Cloud command",
impact: "gcloud can spend money or break prod — gated.",
description: "Block gcloud (Google Cloud) CLI commands",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Infra Commands",
params: {
allowPatterns: {
type: "string[]",
description: "gcloud command patterns to allow (e.g. 'gcloud auth list', 'gcloud config list')",
default: []
}
}
},
{
name: "block-az-cli",
displayTitle: "Tried to run an Azure CLI command",
impact: "az can spend money or break prod — gated.",
description: "Block az (Azure) CLI commands",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Infra Commands",
params: {
allowPatterns: {
type: "string[]",
description: "az CLI command patterns to allow (e.g. 'az account show', 'az group list')",
default: []
}
}
},
{
name: "block-helm",
displayTitle: "Tried to run a Helm command",
impact: "Helm releases mutate cluster state — gated.",
description: "Block helm commands",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Infra Commands",
params: {
allowPatterns: {
type: "string[]",
description: "helm command patterns to allow (e.g. 'helm list', 'helm status *')",
default: []
}
}
},
{
name: "block-gh-pipeline",
displayTitle: "Tried to run a privileged GitHub CLI pipeline command",
impact: "Catches `gh workflow run`, `gh pr merge`, `gh secret set`, etc.",
description: "Block gh CLI pipeline-trigger subcommands (workflow run, run rerun/cancel, pr merge, release create/delete, cache delete, secret set/delete)",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Infra Commands",
params: {
allowPatterns: {
type: "string[]",
description: "gh pipeline command patterns to allow (e.g. specific scripted invocations); read-only gh subcommands like 'gh pr view' and 'gh run list' are not matched by this policy",
default: []
}
}
},
{
name: "block-secrets-write",
displayTitle: "Tried to write a secret-key file",
impact: "Stops the agent from creating `.pem`, `id_rsa`, `credentials.json`, etc.",
description: "Block writing secret key files",
match: { events: ["PreToolUse"], toolNames: ["Write"] },
defaultEnabled: false,
category: "Dangerous Commands",
params: {
additionalPatterns: {
type: "string[]",
description: "Additional filename patterns (substrings) to block",
default: []
}
}
},
{
name: "block-push-master",
displayTitle: "Tried to push directly to main/master",
impact: "Direct pushes to a protected branch bypass review.",
description: "Block pushing to main/master",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: true,
category: "Git",
params: {
protectedBranches: {
type: "string[]",
description: "Branch names to protect from direct pushes",
default: ["main", "master"]
}
}
},
{
name: "block-force-push",
displayTitle: "Tried to force-push",
impact: "Force-pushes rewrite history and can clobber teammates' work.",
description: "Prevent force-pushing to any branch",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Git"
},
{
name: "block-work-on-main",
displayTitle: "Tried to commit or merge on main/master",
impact: "Work should land via PR — direct commits skip review.",
description: "Block git commits and merges on main/master branch",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Git",
params: {
protectedBranches: {
type: "string[]",
description: "Branch names where commits/merges are blocked",
default: ["main", "master"]
}
}
},
{
name: "warn-git-amend",
displayTitle: "Used git commit --amend",
impact: "Amending after a push rewrites history that others may have pulled.",
description: "Warns before amending git commits, which rewrites history",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Git"
},
{
name: "warn-git-stash-drop",
displayTitle: "Tried to drop or clear git stash",
impact: "Stash deletions are permanent and silent.",
description: "Warns before permanently deleting stashed changes",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Git"
},
{
name: "warn-all-files-staged",
displayTitle: "Staged all files with git add -A / .",
impact: "Wide stages routinely catch generated files or secrets you didn't intend to commit.",
description: "Warns before staging all working tree files with git add -A / . / --all",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Git"
},
{
name: "warn-destructive-sql",
displayTitle: "Ran destructive SQL (DROP / TRUNCATE / DELETE without WHERE)",
impact: "Easy way to wipe a table by accident.",
description: "Warn before executing destructive SQL (DROP/TRUNCATE/DELETE without WHERE) via database clients",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Database"
},
{
name: "warn-schema-alteration",
displayTitle: "Altered a database schema column",
impact: "ALTER TABLE operations can lock tables and break readers.",
description: "Warns before SQL schema changes (ALTER TABLE with column or rename operations)",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Database"
},
{
name: "warn-package-publish",
displayTitle: "Tried to publish a package",
impact: "Publishes are irreversible — `npm publish` / `cargo publish` shouldn't happen without intent.",
description: "Warn before publishing packages to public registries (npm, PyPI, crates.io, RubyGems, etc.)",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Packages & System"
},
{
name: "warn-global-package-install",
displayTitle: "Installed a package globally",
impact: "`npm i -g`, `cargo install`, `pip --user` pollute your machine outside the project.",
description: "Warns before installing packages globally (npm -g, cargo install, etc.)",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Packages & System"
},
{
name: "prefer-package-manager",
displayTitle: "Used a non-preferred package manager",
impact: "Mixing package managers creates lockfile churn for your team.",
description: "Blocks non-preferred package managers and tells Claude to use an allowed one (e.g., uv instead of pip)",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Packages & System",
params: {
allowed: {
type: "string[]",
description: "Allowed package manager names (e.g. ['uv', 'bun']). Any detected manager not in this list is blocked.",
default: []
},
blocked: {
type: "string[]",
description: "Additional manager names to block beyond the built-in list (e.g. ['pdm', 'pipx']).",
default: []
}
}
},
{
name: "warn-large-file-write",
displayTitle: "Wrote a file larger than the configured threshold",
impact: "Catches accidentally large file writes (logs, binaries, model dumps).",
description: "Warn before writing files larger than 1MB (configurable via thresholdKb param)",
match: { events: ["PreToolUse"], toolNames: ["Write"] },
defaultEnabled: false,
category: "Packages & System",
params: {
thresholdKb: {
type: "number",
description: "File size threshold in KB above which a warning is issued",
default: 1024
}
}
},
{
name: "warn-background-process",
displayTitle: "Started a long-lived background process",
impact: "Catches `nohup` / `&` / `screen` / `tmux` / `disown` patterns that the agent often forgets to clean up.",
description: "Warns before starting detached or background processes",
match: { events: ["PreToolUse"], toolNames: ["Bash"] },
defaultEnabled: false,
category: "Packages & System"
},
{
name: "warn-repeated-tool-calls",
displayTitle: "Called the same tool 3+ times with identical arguments",
impact: "Usually a sign of a stuck loop burning tokens.",
description: "Warn when the same tool is called 3+ times with identical parameters",
match: { events: ["PreToolUse"] },
defaultEnabled: false,
category: "AI Behavior"
},
{
name: "require-commit-before-stop",
displayTitle: "Stopped with uncommitted changes",
impact: "Work not in a commit is invisible to teammates and easy to lose.",
description: "Require all changes to be committed before Claude stops",
match: { events: ["Stop"] },
defaultEnabled: false,
category: "Workflow"
},
{
name: "require-push-before-stop",
displayTitle: "Stopped with unpushed commits",
impact: "Local-only commits won't trigger CI or be reviewable.",
description: "Require all commits to be pushed to remote before Claude stops",
match: { events: ["Stop"] },
defaultEnabled: false,
category: "Workflow",
params: {
remote: {
type: "string",
description: "Remote name to push to (default: origin)",
default: "origin"
},
baseBranch: {
type: "string",
description: "Base branch to compare against (default: main)",
default: "main"
}
}
},
{
name: "require-pr-before-stop",
displayTitle: "Stopped without a PR for the branch",
impact: "Branches without PRs don't get reviewed.",
description: "Require a pull request to exist for the current branch before Claude stops",
match: { events: ["Stop"] },
defaultEnabled: false,
category: "Workflow",
params: {
baseBranch: {
type: "string",
description: "Base branch to compare against (default: main)",
default: "main"
}
}
},
{
name: "require-no-conflicts-before-stop",
displayTitle: "Stopped with a branch that conflicts with main",
impact: "Conflicting branches can't merge — surface them early.",
description: "Require the current branch to merge cleanly with the base branch before Claude stops",
match: { events: ["Stop"] },
defaultEnabled: false,
category: "Workflow",
params: {
baseBranch: {
type: "string",
description: "Base branch to check for conflicts against (default: main)",
default: "main"
}
}
},
{
name: "require-ci-green-before-stop",
displayTitle: "Stopped with failing CI",
impact: "Failing CI blocks deploy.",
description: "Require CI checks to pass on the current HEAD commit before Claude stops (ignores stale runs on prior commits)",
match: { events: ["Stop"] },
defaultEnabled: false,
category: "Workflow"
}
];
// src/hooks/policy-helpers.ts
function allow(reason) {
return reason ? { decision: "allow", reason } : { decision: "allow" };
}
function deny(reason) {
return { decision: "deny", reason };
}
function instruct(reason) {
return { decision: "instruct", reason };
}
// src/hooks/hook-logger.ts
import {
appendFileSync,
renameSync,
mkdirSync,
existsSync,
statSync
} from "node:fs";
import { join } from "node:path";
// src/hooks/fp-home.ts
import { homedir } from "node:os";
import { resolve } from "node:path";
function failproofaiHome(home) {
if (home)
return resolve(home, ".failproofai");
return process.env.FAILPROOFAI_HOME || resolve(homedir(), ".failproofai");
}
var at = (...parts) => resolve(failproofaiHome(), ...parts);
var atHome = (home, ...parts) => home ? resolve(failproofaiHome(home), ...parts) : at(...parts);
var logsDir = (home) => atHome(home, "logs");
// src/hooks/hook-logger.ts
var LEVEL_ORDER = { info: 0, warn: 1, error: 2 };
var MAX_FILE_SIZE = 512 * 1024;
var LOG_FILENAME = "hooks.log";
var DEFAULT_LOG_DIR = logsDir();
var resolved = false;
var currentLevel = "warn";
var fileLoggingEnabled = false;
var logDir = DEFAULT_LOG_DIR;
function ensureResolved() {
if (resolved)
return;
resolved = true;
const rawLevel = (process.env.FAILPROOFAI_LOG_LEVEL ?? "").toLowerCase();
if (rawLevel === "info" || rawLevel === "warn" || rawLevel === "error") {
currentLevel = rawLevel;
}
const rawFile = (process.env.FAILPROOFAI_HOOK_LOG_FILE ?? "").trim();
if (rawFile) {
fileLoggingEnabled = true;
if (rawFile !== "1" && rawFile !== "true") {
logDir = rawFile;
}
}
}
function shouldEmit(level) {
ensureResolved();
return LEVEL_ORDER[level] >= LEVEL_ORDER[currentLevel];
}
function emitStderr(label, msg) {
process.stderr.write(`[failproofai:hook] ${label} ${msg}
`);
}
function ensureLogDir() {
if (!existsSync(logDir)) {
mkdirSync(logDir, { recursive: true });
}
}
function rotateIfNeeded(filePath) {
try {
const stats = statSync(filePath);
if (stats.size >= MAX_FILE_SIZE) {
const archiveName = `hooks-${Date.now()}.log`;
renameSync(filePath, join(logDir, archiveName));
}
} catch {}
}
function appendToFile(label, msg) {
if (!fileLoggingEnabled)
return;
try {
ensureLogDir();
const filePath = join(logDir, LOG_FILENAME);
rotateIfNeeded(filePath);
const timestamp = new Date().toISOString();
const line = `[${timestamp}] ${label} ${msg}
`;
appendFileSync(filePath, line, "utf-8");
} catch {}
}
function hookLogWarn(msg) {
if (!shouldEmit("warn"))
return;
emitStderr("WARN", msg);
appendToFile("WARN", msg);
}
// src/hooks/builtin-policies.ts
function isAgentInternalPath(resolved2) {
const normResolved = resolved2.replaceAll("\\", "/");
for (const dir of [".claude", ".codex", ".copilot", ".cursor", ".opencode", ".pi", ".gemini"]) {
const root = join2(homedir2(), dir).replaceAll("\\", "/");
if (normResolved === root || normResolved.startsWith(root + "/"))
return true;
}
for (const sub of [join2(".config", "opencode"), join2(".local", "share", "opencode")]) {
const root = join2(homedir2(), sub).replaceAll("\\", "/");
if (normResolved === root || normResolved.startsWith(root + "/"))
return true;
}
return false;
}
function isAgentSettingsFile(resolved2) {
if (/[\\/]\.claude[\\/]settings(?:\.[^/\\]+)?\.json$/.test(resolved2))
return true;
if (/[\\/]\.codex[\\/]hooks\.json$/.test(resolved2))
return true;
if (/[\\/]\.copilot[\\/]hooks[\\/][^/\\]+\.json$/.test(resolved2))
return true;
if (/[\\/]\.github[\\/]hooks[\\/][^/\\]+\.json$/.test(resolved2))
return true;
if (/[\\/]\.cursor[\\/]hooks\.json$/.test(resolved2))
return true;
if (/[\\/]\.opencode[\\/]opencode\.jsonc?$/.test(resolved2))
return true;
if (/[\\/]\.opencode[\\/]plugins[\\/][^/\\]+\.(?:mjs|js|ts)$/.test(resolved2))
return true;
if (/[\\/]\.config[\\/]opencode[\\/]opencode\.jsonc?$/.test(resolved2))
return true;
if (/[\\/]\.config[\\/]opencode[\\/]config\.json$/.test(resolved2))
return true;
if (/[\\/]\.config[\\/]opencode[\\/]plugins[\\/][^/\\]+\.(?:mjs|js|ts)$/.test(resolved2))
return true;
if (/[\\/]\.pi[\\/](?:agent[\\/])?settings\.json$/.test(resolved2))
return true;
if (/[\\/]\.pi[\\/](?:agent[\\/])?extensions[\\/]/.test(resolved2))
return true;
if (/[\\/]\.gemini[\\/]settings\.json$/.test(resolved2))
return true;
if (/[\\/]\.gemini[\\/]config[\\/]hooks\.json$/.test(resolved2))
return true;
return false;
}
var isClaudeInternalPath = isAgentInternalPath;
var isClaudeSettingsFile = isAgentSettingsFile;
function getCommand(ctx) {
return ctx.toolInput?.command ?? "";
}
function getFilePath(ctx) {
return ctx.toolInput?.file_path ?? "";
}
function parseArgvTokens(cmd) {
return cmd.trim().split(/\s+/).map((t) => t.replace(/^['"]|['"]$/g, ""));
}
var SHELL_OPERATORS = new Set(["&&", "||", "|", ";"]);
var SHELL_METACHAR_RE = /[;&<>`$()\\]/;
var JWT_RE = /eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/;
var API_KEY_PATTERNS = [
[/sk-ant-[A-Za-z0-9\-_]{20,}/, "Anthropic API key"],
[/sk-proj-[A-Za-z0-9\-_]{20,}/, "OpenAI project API key"],
[/sk-[A-Za-z0-9]{20,}/, "OpenAI API key"],
[/ghp_[A-Za-z0-9]{36}/, "GitHub personal access token"],
[/github_pat_[A-Za-z0-9_]{82}/, "GitHub fine-grained token"],
[/AKIA[A-Z0-9]{16}/, "AWS access key ID"],
[/sk_live_[A-Za-z0-9]{24,}/, "Stripe live secret key"],
[/sk_test_[A-Za-z0-9]{24,}/, "Stripe test secret key"],
[/AIza[0-9A-Za-z\-_]{35}/, "Google API key"]
];
var CONNECTION_STRING_RE = /(?:postgresql|postgres|mysql|mongodb(?:\+srv)?|redis|amqps?|smtps?):\/\/[^@\s]+@/;
var PRIVATE_KEY_RE = /-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/;
var BEARER_TOKEN_RE = /Authorization:\s*Bearer\s+[A-Za-z0-9\-._~+/]{20,}/i;
var SECRET_PATTERNS = [
[PRIVATE_KEY_RE, "private key"],
[JWT_RE, "JWT"],
[BEARER_TOKEN_RE, "bearer token"],
[CONNECTION_STRING_RE, "database credentials"],
...API_KEY_PATTERNS
];
var SQL_TOOL_RE = /\b(?:psql|mysql|sqlite3|pgcli|clickhouse-client)\b/;
var DESTRUCTIVE_SQL_RE = /\b(?:DROP\s+(?:TABLE|DATABASE|SCHEMA)|TRUNCATE\b)/i;
var DELETE_NO_WHERE_RE = /\bDELETE\s+FROM\b/i;
var SQL_WHERE_RE = /\bWHERE\b/i;
var SCHEMA_ALTER_RE = /\bALTER\s+TABLE\b[\s\S]*\b(?:DROP\s+COLUMN|ADD\s+COLUMN|RENAME\s+(?:COLUMN|TO)|MODIFY\s+COLUMN)\b/i;
var PUBLISH_CMD_RE = /(?:npm\s+publish|bun\s+publish|pnpm\s+publish|yarn\s+npm\s+publish|twine\s+upload|poetry\s+publish|cargo\s+publish|gem\s+push)\b/;
var ENV_PRINTENV_RE = /(?:^|\s|;|&&|\|\|)(?:env|printenv)(?:\s|$|;|&&|\|)/;
var ECHO_ENV_RE = /echo\s+.*\$\{?[A-Za-z_]/;
var EXPORT_RE = /(?:^|\s|;|&&|\|\|)export\s+\w+/;
var PS_ENV_VAR_RE = /\$env:[A-Za-z_]/i;
var PS_CHILDITEM_ENV_RE = /(?:Get-ChildItem|dir|gci|ls)\s+Env:/i;
var DOTNET_GETENV_RE = /\[Environment\]::GetEnvironment/i;
var CMD_ECHO_ENV_RE = /echo\s+%[A-Za-z_]/i;
var ENV_FILE_PATH_RE = /(?:^|[\\/])\.env(?:\.|$)/;
var ENV_CMD_RE = /\.env(?:\b|\s|$|\.)/;
var PS_ELEVATION_RE = /Start-Process\s+.*-Verb\s+RunAs/i;
var RUNAS_RE = /(?:^|;|&&|\|\|)\s*runas\s/i;
var CURL_PIPE_SH_RE = /(?:curl|wget)\s.*\|\s*(?:sh|bash|zsh|dash|ksh|csh|tcsh|fish|ash)\b/;
var SEGMENT_SEPARATORS = /[;&|\n\r(){}`]+/;
var COMMAND_PREFIX_TOKENS = new Set([
"npx",
"bunx",
"pnpx",
"npm",
"pnpm",
"yarn",
"dlx",
"exec",
"run",
"node",
"bun",
"deno",
"env",
"command",
"builtin",
"nohup",
"setsid",
"time",
"timeout",
"nice",
"stdbuf",
"xargs",
"sudo",
"doas",
"sh",
"bash",
"zsh",
"dash",
"ksh",
"fish",
"ash"
]);
var SELF_BINARY_TOKEN_RE = /(?:^|\/)failproofai[^/]*$/;
var CONFIG_SUBCOMMAND_RE = /^(?:config|configure|setup)$/;
var PAUSE_FLAG_RE = /^--pause(?:=|$)/;
var ENV_ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/;
var RUNNER_OPERAND_RE = /^\d+[a-z]*$/i;
function classifySelfInvocation(command) {
let found = null;
for (const segment of command.split(SEGMENT_SEPARATORS)) {
const tokens = segment.split(/\s+/).filter(Boolean);
let i = 0;
while (i < tokens.length) {
const token = tokens[i];
const isSkippable = ENV_ASSIGNMENT_RE.test(token) || token.startsWith("-") || token.startsWith(">") || token.startsWith("<") || RUNNER_OPERAND_RE.test(token) || COMMAND_PREFIX_TOKENS.has(token.slice(token.lastIndexOf("/") + 1));
if (!isSkippable)
break;
i++;
}
if (i >= tokens.length)
continue;
if (!SELF_BINARY_TOKEN_RE.test(tokens[i]))
continue;
const args = tokens.slice(i + 1);
const configAt = args.findIndex((a) => CONFIG_SUBCOMMAND_RE.test(a));
if (configAt !== -1 && args.slice(configAt + 1).some((a) => PAUSE_FLAG_RE.test(a))) {
return "pause";
}
found = "cli";
}
return found;
}
function decodeAnsiC(body) {
return body.replace(/\\(x[0-9A-Fa-f]{1,2}|u[0-9A-Fa-f]{1,4}|U[0-9A-Fa-f]{1,8}|[0-7]{1,3}|.)/g, (_, seq) => {
try {
if (seq[0] === "x")
return String.fromCharCode(parseInt(seq.slice(1), 16));
if (seq[0] === "u" || seq[0] === "U")
return String.fromCodePoint(parseInt(seq.slice(1), 16));
if (/^[0-7]+$/.test(seq))
return String.fromCharCode(parseInt(seq, 8));
} catch {
return seq;
}
const named = {
a: "\x07",
b: "\b",
e: "\x1B",
f: "\f",
n: `
`,
r: "\r",
t: "\t",
v: "\v",
"\\": "\\",
"'": "'",
'"': '"',
"?": "?"
};
return named[seq] ?? seq;
});
}
function stripShellQuoting(command) {
const joined = command.replace(/\\\r?\n/g, "");
const ansiDecoded = joined.replace(/\$'((?:[^'\\]|\\.)*)'/g, (_, body) => decodeAnsiC(body));
return ansiDecoded.replace(/\\(.)/g, "$1").replace(/['"]/g, "");
}
var PS_WEB_PIPE_RE = /(?:Invoke-WebRequest|iwr|Invoke-RestMethod|irm)\s+.*\|\s*(?:Invoke-Expression|iex)/i;
var SHORT_FLAG_BUNDLE_RE = /^-[a-zA-Z]*f[a-zA-Z]*$/;
var SAFE_FORCE_PREFIXES = ["--force-with-lease", "--force-if-includes"];
var SECRET_FILE_RE = /\.(?:pem|key)$/;
var SECRET_FILE_ID_RSA_RE = /id_rsa/;
var SECRET_FILE_CREDENTIALS_RE = /credentials/;
var GIT_COMMIT_MERGE_RE = /git\s+(commit|merge|rebase|cherry-pick)\b/;
var FAILPROOFAI_UNINSTALL_RE = /(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/;
var GIT_AMEND_RE = /\bgit\s+commit\b.*--amend\b/;
var GIT_STASH_DROP_RE = /\bgit\s+stash\s+(?:drop|clear)\b/;
var GIT_ADD_ALL_RE = /\bgit\s+add\s+(?:-A\b|--all\b|\.(?:\s|$|;|&&|\|\|))/;
var NPM_GLOBAL_RE = /\bnpm\s+(?:install|i)\b(?=.*(?:\s-g\b|--global\b))/;
var YARN_GLOBAL_RE = /\byarn\s+global\s+add\b/;
var PNPM_GLOBAL_RE = /\bpnpm\s+(?:add|install|i)\b(?=.*(?:\s-g\b|--global\b))/;
var BUN_GLOBAL_RE = /\bbun\s+(?:install|add)\b(?=.*(?:\s-g\b|--global\b))/;
var CARGO_INSTALL_RE = /\bcargo\s+install\b/;
var PIP_SYSTEM_RE = /\bpip(?:3)?\s+install\b(?=.*(?:--user\b|--break-system-packages\b))/;
var PKG_MANAGER_DETECTORS = {
pip: [/\bpip\b/, /\bpip3\b/, /\bpython3?\s+-m\s+pip\b/],
npm: [/\bnpm\b/, /\bnpx\b/],
yarn: [/\byarn\b/],
pnpm: [/\bpnpm\b/, /\bpnpx\b/],
bun: [/\bbun\b/, /\bbunx\b/],
uv: [/\buv\b/],
poetry: [/\bpoetry\b/],
pipenv: [/\bpipenv\b/],
conda: [/\bconda\b/],
cargo: [/\bcargo\b/]
};
var NOHUP_RE = /\bnohup\s+\S/;
var SCREEN_DETACH_RE = /\bscreen\s+-[A-Za-z]*d[A-Za-z]*\b/;
var TMUX_DETACH_RE = /\btmux\s+(?:new-session|new)\b[^|&;]*-d\b/;
var DISOWN_RE = /\bdisown\b/;
var BACKGROUND_AMPERSAND_RE = /(?<![&|])\s?&\s*(?:$|#|;)/;
var KUBECTL_RE = /(?:^|[;\n]|&&|\|\|?|&)\s*kubectl(?:\s|$)/;
var TERRAFORM_RE = /(?:^|[;\n]|&&|\|\|?|&)\s*(?:terraform|tofu)(?:\s|$)/;
var AWS_CLI_RE = /(?:^|[;\n]|&&|\|\|?|&)\s*aws(?:\s|$)/;
var GCLOUD_RE = /(?:^|[;\n]|&&|\|\|?|&)\s*gcloud(?:\s|$)/;
var AZ_CLI_RE = /(?:^|[;\n]|&&|\|\|?|&)\s*az(?:\s|$)/;
var HELM_RE = /(?:^|[;\n]|&&|\|\|?|&)\s*helm(?:\s|$)/;
var GH_PIPELINE_RE = /(?:^|[;\n]|&&|\|\|?|&)\s*gh\s+(?:workflow\s+(?:run|enable|disable)|run\s+(?:rerun|cancel)|pr\s+merge|release\s+(?:create|delete)|cache\s+delete|secret\s+(?:set|delete))\b/;
var gitBranchCache = new Map;
var GIT_BRANCH_CACHE_MAX_ENTRIES = 500;
function statGitHeadMtimeMs(cwd) {
try {
return statSync2(join2(cwd, ".git", "HEAD")).mtimeMs;
} catch {
return null;
}
}
function getCurrentBranch(cwd) {
try {
const headMtimeMs = statGitHeadMtimeMs(cwd);
const cached = gitBranchCache.get(cwd);
if (cached && headMtimeMs !== null && cached.headMtimeMs === headMtimeMs) {
return cached.branch || null;
}
const branch = execSync("git rev-parse --abbrev-ref HEAD", {
cwd,
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
timeout: 3000
}).trim();
if (headMtimeMs !== null) {
if (gitBranchCache.size >= GIT_BRANCH_CACHE_MAX_ENTRIES)
gitBranchCache.clear();
gitBranchCache.set(cwd, { branch, headMtimeMs });
}
return branch || null;
} catch {
return null;
}
}
function getHeadSha(cwd) {
try {
const sha = execSync("git rev-parse HEAD", {
cwd,
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
timeout: 3000
}).trim();
return sha || null;
} catch {
return null;
}
}
function getThirdPartyCheckRuns(cwd, sha) {
try {
const json = execFileSync("gh", [
"api",
`repos/{owner}/{repo}/commits/${sha}/check-runs`,
"--jq",
'.check_runs | map(select(.app.slug != "github-actions")) | map({name: .name, status: .status, conclusion: (.conclusion // "")})'
], {
cwd,
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
timeout: 15000
}).trim();
if (!json || json === "[]")
return [];
return JSON.parse(json);
} catch {
return [];
}
}
function getCommitStatuses(cwd, sha) {
try {
const json = execFileSync("gh", [
"api",
`repos/{owner}/{repo}/commits/${sha}/statuses`,
"--jq",
"map({name: .context, state: .state}) | unique_by(.name)"
], {
cwd,
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
timeout: 15000
}).trim();
if (!json || json === "[]")
return [];
const statuses = JSON.parse(json);
return statuses.map((s) => ({
name: s.name,
status: s.state === "pending" ? "in_progress" : "completed",
conclusion: s.state === "pending" ? "" : s.state === "success" ? "success" : "failure"
}));
} catch {
return [];
}
}
function matchesAllowedPattern(cmd, pattern) {
const cmdTokens = parseArgvTokens(cmd);
const patTokens = parseArgvTokens(pattern);
if (cmdTokens.length < patTokens.length)
return false;
if (cmdTokens.some((tok) => SHELL_OPERATORS.has(tok)))
return false;
if (cmdTokens.some((tok) => SHELL_METACHAR_RE.test(tok)))
return false;
return patTokens.every((tok, i) => tok === "*" || tok === cmdTokens[i]);
}
function sanitizeJwt(ctx) {
const output = JSON.stringify(ctx.payload);
if (JWT_RE.test(output)) {
return {
decision: "deny",
reason: "JWT token detected in tool output",
message: "[REDACTED: JWT token removed by failproofai]"
};
}
return allow();
}
function sanitizeApiKeys(ctx) {
const output = JSON.stringify(ctx.payload);
for (const [pattern, label] of API_KEY_PATTERNS) {
if (pattern.test(output)) {
return {
decision: "deny",
reason: `${label} detected in tool output`,
message: `[REDACTED: ${label} removed by failproofai]`
};
}
}
const additional = ctx.params?.additionalPatterns ?? [];
for (const { regex, label } of additional) {
try {
if (new RegExp(regex).test(output)) {
return {
decision: "deny",
reason: `${label} detected in tool output`,
message: `[REDACTED: ${label} removed by failproofai]`
};
}
} catch {
hookLogWarn(`additionalPatterns: invalid regex "${regex}", skipping`);
}
}
return allow();
}
function sanitizeConnectionStrings(ctx) {
const output = JSON.stringify(ctx.payload);
if (CONNECTION_STRING_RE.test(output)) {
return {
decision: "deny",
reason: "Database connection string with credentials detected in tool output",
message: "[REDACTED: connection string removed by failproofai]"
};
}
return allow();
}
function sanitizePrivateKeyContent(ctx) {
const output = JSON.stringify(ctx.payload);