fullcourtdefense 2.0.0 → 2.2.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 (437) hide show
  1. package/README.md +233 -53
  2. package/dist/adapters.d.ts +11 -0
  3. package/dist/adapters.js +16 -0
  4. package/dist/anthropic.d.ts +32 -0
  5. package/dist/anthropic.js +67 -0
  6. package/dist/argsBounds.d.ts +38 -0
  7. package/dist/argsBounds.js +84 -0
  8. package/dist/autoInstrument.d.ts +24 -7
  9. package/dist/autoInstrument.js +148 -23
  10. package/dist/circuitBreaker.d.ts +17 -0
  11. package/dist/circuitBreaker.js +39 -0
  12. package/dist/cliMoved.d.ts +4 -0
  13. package/dist/cliMoved.js +20 -0
  14. package/dist/client.d.ts +185 -1
  15. package/dist/client.js +1094 -87
  16. package/dist/errors.d.ts +73 -0
  17. package/dist/errors.js +110 -0
  18. package/dist/failMode.d.ts +96 -0
  19. package/dist/failMode.js +180 -0
  20. package/dist/identity.d.ts +32 -0
  21. package/dist/identity.js +120 -0
  22. package/dist/index.d.ts +5 -2
  23. package/dist/index.js +9 -1
  24. package/dist/lambda.d.ts +101 -0
  25. package/dist/lambda.js +357 -0
  26. package/dist/localDecision.d.ts +100 -0
  27. package/dist/localDecision.js +246 -0
  28. package/dist/localGate.d.ts +44 -0
  29. package/dist/localGate.js +114 -0
  30. package/dist/localSafety.d.ts +48 -0
  31. package/dist/localSafety.js +220 -0
  32. package/dist/policy/acorn.js +6365 -0
  33. package/dist/policy/actionPolicyEngine.d.ts +427 -0
  34. package/dist/policy/actionPolicyEngine.js +6481 -0
  35. package/dist/policy/detectionData.d.ts +21 -0
  36. package/dist/policy/detectionData.js +71 -0
  37. package/dist/policy/detectorRuntime.d.ts +27 -0
  38. package/dist/policy/detectorRuntime.js +58 -0
  39. package/dist/policy/deterministicGuard.d.ts +406 -0
  40. package/dist/policy/deterministicGuard.js +6651 -0
  41. package/dist/protect.d.ts +48 -0
  42. package/dist/protect.js +223 -1
  43. package/dist/recordQueue.d.ts +53 -0
  44. package/dist/recordQueue.js +132 -0
  45. package/dist/recordSpool.d.ts +17 -0
  46. package/dist/recordSpool.js +137 -0
  47. package/dist/types.d.ts +167 -2
  48. package/lambda.js +6 -0
  49. package/package.json +31 -27
  50. package/dist/cli/actionPolicyEngine.d.ts +0 -146
  51. package/dist/cli/actionPolicyEngine.js +0 -754
  52. package/dist/cli/api.d.ts +0 -116
  53. package/dist/cli/api.js +0 -65
  54. package/dist/cli/appDetection.d.ts +0 -8
  55. package/dist/cli/appDetection.js +0 -107
  56. package/dist/cli/attack-corpus/context_escape/context-escape-newline.yaml +0 -23
  57. package/dist/cli/attack-corpus/context_escape/context-escape-unicode.yaml +0 -14
  58. package/dist/cli/attack-corpus/context_escape/delimiter-json.yaml +0 -14
  59. package/dist/cli/attack-corpus/context_escape/delimiter-markdown.yaml +0 -22
  60. package/dist/cli/attack-corpus/context_escape/delimiter-xml.yaml +0 -19
  61. package/dist/cli/attack-corpus/context_escape/html-injection.yaml +0 -14
  62. package/dist/cli/attack-corpus/context_escape/javascript-injection.yaml +0 -13
  63. package/dist/cli/attack-corpus/data_extraction/adv26-adversarial-function-hallucination.yaml +0 -20
  64. package/dist/cli/attack-corpus/data_extraction/adv26-cot-hijack-debug-trace.yaml +0 -20
  65. package/dist/cli/attack-corpus/data_extraction/adv26-cot-hijack-verification.yaml +0 -18
  66. package/dist/cli/attack-corpus/data_extraction/adv26-crossmodal-diff.yaml +0 -22
  67. package/dist/cli/attack-corpus/data_extraction/adv26-crossmodal-graphql.yaml +0 -34
  68. package/dist/cli/attack-corpus/data_extraction/adv26-crossmodal-regex.yaml +0 -19
  69. package/dist/cli/attack-corpus/data_extraction/adv26-crossmodal-sql-prose.yaml +0 -18
  70. package/dist/cli/attack-corpus/data_extraction/adv26-meta-confidence-calibration.yaml +0 -21
  71. package/dist/cli/attack-corpus/data_extraction/adv26-meta-instruction-count.yaml +0 -18
  72. package/dist/cli/attack-corpus/data_extraction/adv26-meta-output-format.yaml +0 -16
  73. package/dist/cli/attack-corpus/data_extraction/adv26-meta-summarize-yourself.yaml +0 -19
  74. package/dist/cli/attack-corpus/data_extraction/adv26-semantic-decomp-definition.yaml +0 -15
  75. package/dist/cli/attack-corpus/data_extraction/adv26-semantic-decomp-fill-blank.yaml +0 -19
  76. package/dist/cli/attack-corpus/data_extraction/adv26-semantic-decomp-negation.yaml +0 -14
  77. package/dist/cli/attack-corpus/data_extraction/cloud-provider-discovery.yaml +0 -11
  78. package/dist/cli/attack-corpus/data_extraction/config-file-request.yaml +0 -11
  79. package/dist/cli/attack-corpus/data_extraction/cve-2025-echoleak.yaml +0 -17
  80. package/dist/cli/attack-corpus/data_extraction/data-api-key.yaml +0 -11
  81. package/dist/cli/attack-corpus/data_extraction/data-architecture.yaml +0 -11
  82. package/dist/cli/attack-corpus/data_extraction/data-conversation-history.yaml +0 -10
  83. package/dist/cli/attack-corpus/data_extraction/data-credit-card.yaml +0 -15
  84. package/dist/cli/attack-corpus/data_extraction/data-customer-list.yaml +0 -11
  85. package/dist/cli/attack-corpus/data_extraction/data-database.yaml +0 -11
  86. package/dist/cli/attack-corpus/data_extraction/data-employees.yaml +0 -11
  87. package/dist/cli/attack-corpus/data_extraction/data-export.yaml +0 -11
  88. package/dist/cli/attack-corpus/data_extraction/data-inference-v1.yaml +0 -10
  89. package/dist/cli/attack-corpus/data_extraction/data-inference-v2.yaml +0 -10
  90. package/dist/cli/attack-corpus/data_extraction/data-logs.yaml +0 -10
  91. package/dist/cli/attack-corpus/data_extraction/data-model-info.yaml +0 -10
  92. package/dist/cli/attack-corpus/data_extraction/data-password.yaml +0 -11
  93. package/dist/cli/attack-corpus/data_extraction/data-ssn.yaml +0 -11
  94. package/dist/cli/attack-corpus/data_extraction/data-training.yaml +0 -10
  95. package/dist/cli/attack-corpus/data_extraction/dependency-enum.yaml +0 -11
  96. package/dist/cli/attack-corpus/data_extraction/dialogflow-fulfillment-leak.yaml +0 -11
  97. package/dist/cli/attack-corpus/data_extraction/dialogflow-intent-leak.yaml +0 -11
  98. package/dist/cli/attack-corpus/data_extraction/error-induced-leak.yaml +0 -17
  99. package/dist/cli/attack-corpus/data_extraction/error-message-leak.yaml +0 -12
  100. package/dist/cli/attack-corpus/data_extraction/infra-fingerprint.yaml +0 -16
  101. package/dist/cli/attack-corpus/data_extraction/make-scenario-leak.yaml +0 -11
  102. package/dist/cli/attack-corpus/data_extraction/n8n-execution-data.yaml +0 -11
  103. package/dist/cli/attack-corpus/data_extraction/n8n-node-enumeration.yaml +0 -11
  104. package/dist/cli/attack-corpus/data_extraction/n8n-workflow-disclosure.yaml +0 -15
  105. package/dist/cli/attack-corpus/data_extraction/prompt-extraction-v1.yaml +0 -10
  106. package/dist/cli/attack-corpus/data_extraction/prompt-extraction-v2.yaml +0 -11
  107. package/dist/cli/attack-corpus/data_extraction/prompt-extraction-v3.yaml +0 -10
  108. package/dist/cli/attack-corpus/data_extraction/prompt-leak-completion.yaml +0 -10
  109. package/dist/cli/attack-corpus/data_extraction/prompt-leak-indirect.yaml +0 -10
  110. package/dist/cli/attack-corpus/data_extraction/rasa-domain-leak.yaml +0 -11
  111. package/dist/cli/attack-corpus/data_extraction/system-prompt-section.yaml +0 -14
  112. package/dist/cli/attack-corpus/data_extraction/tech-architecture.yaml +0 -16
  113. package/dist/cli/attack-corpus/data_extraction/tool-api-key-exfil.yaml +0 -15
  114. package/dist/cli/attack-corpus/data_extraction/tool-email-exfil.yaml +0 -14
  115. package/dist/cli/attack-corpus/data_extraction/tool-env-extraction.yaml +0 -14
  116. package/dist/cli/attack-corpus/data_extraction/tool-file-read.yaml +0 -16
  117. package/dist/cli/attack-corpus/data_extraction/tool-nosql-injection.yaml +0 -11
  118. package/dist/cli/attack-corpus/data_extraction/tool-payment-manipulation.yaml +0 -11
  119. package/dist/cli/attack-corpus/data_extraction/tool-price-manipulation.yaml +0 -11
  120. package/dist/cli/attack-corpus/data_extraction/tool-session-hijack.yaml +0 -11
  121. package/dist/cli/attack-corpus/data_extraction/tool-sql-injection.yaml +0 -13
  122. package/dist/cli/attack-corpus/data_extraction/tool-webhook-hijack.yaml +0 -13
  123. package/dist/cli/attack-corpus/data_extraction/version-fingerprint.yaml +0 -16
  124. package/dist/cli/attack-corpus/data_extraction/webhook-secret-extraction.yaml +0 -11
  125. package/dist/cli/attack-corpus/data_extraction/webhook-url-enum.yaml +0 -11
  126. package/dist/cli/attack-corpus/data_extraction/workflow-instance-id.yaml +0 -11
  127. package/dist/cli/attack-corpus/data_extraction/workflow-state-leak.yaml +0 -16
  128. package/dist/cli/attack-corpus/data_extraction/zapier-zap-leak.yaml +0 -11
  129. package/dist/cli/attack-corpus/encoding_attack/adv26-adversarial-token-confusion.yaml +0 -13
  130. package/dist/cli/attack-corpus/encoding_attack/base64-decode-request.yaml +0 -14
  131. package/dist/cli/attack-corpus/encoding_attack/base64-injection-v1.yaml +0 -14
  132. package/dist/cli/attack-corpus/encoding_attack/flip-attack-v1.yaml +0 -14
  133. package/dist/cli/attack-corpus/encoding_attack/flip-attack-v2.yaml +0 -14
  134. package/dist/cli/attack-corpus/encoding_attack/token-smuggling.yaml +0 -10
  135. package/dist/cli/attack-corpus/encoding_attack/unicode-homoglyph.yaml +0 -15
  136. package/dist/cli/attack-corpus/encoding_attack/unicode-invisible.yaml +0 -15
  137. package/dist/cli/attack-corpus/encoding_attack/unicode-rtl.yaml +0 -11
  138. package/dist/cli/attack-corpus/encoding_bypass/adv26-compound-encoding-chain.yaml +0 -19
  139. package/dist/cli/attack-corpus/encoding_bypass/adv26-smuggle-acrostic.yaml +0 -26
  140. package/dist/cli/attack-corpus/encoding_bypass/adv26-smuggle-ascii-art.yaml +0 -25
  141. package/dist/cli/attack-corpus/encoding_bypass/adv26-smuggle-emoji-cipher.yaml +0 -22
  142. package/dist/cli/attack-corpus/encoding_bypass/adv26-smuggle-first-word.yaml +0 -15
  143. package/dist/cli/attack-corpus/encoding_bypass/adv26-smuggle-pig-latin.yaml +0 -15
  144. package/dist/cli/attack-corpus/encoding_bypass/encoding-base64-v1.yaml +0 -11
  145. package/dist/cli/attack-corpus/encoding_bypass/encoding-base64-v2.yaml +0 -15
  146. package/dist/cli/attack-corpus/encoding_bypass/encoding-hex-v1.yaml +0 -11
  147. package/dist/cli/attack-corpus/encoding_bypass/encoding-leetspeak-v1.yaml +0 -10
  148. package/dist/cli/attack-corpus/encoding_bypass/encoding-morse-v1.yaml +0 -11
  149. package/dist/cli/attack-corpus/encoding_bypass/encoding-reverse-v1.yaml +0 -11
  150. package/dist/cli/attack-corpus/encoding_bypass/encoding-rot13-v1.yaml +0 -11
  151. package/dist/cli/attack-corpus/encoding_bypass/unicode-tag-injection.yaml +0 -10
  152. package/dist/cli/attack-corpus/encoding_bypass/zero-width-injection.yaml +0 -10
  153. package/dist/cli/attack-corpus/exploitation/exploit-command-injection.yaml +0 -12
  154. package/dist/cli/attack-corpus/exploitation/exploit-path-traversal.yaml +0 -12
  155. package/dist/cli/attack-corpus/exploitation/exploit-sql-injection.yaml +0 -12
  156. package/dist/cli/attack-corpus/exploitation/exploit-sql-union.yaml +0 -12
  157. package/dist/cli/attack-corpus/exploitation/exploit-template-injection.yaml +0 -12
  158. package/dist/cli/attack-corpus/glitch_token/glitch-davidjl.yaml +0 -10
  159. package/dist/cli/attack-corpus/glitch_token/glitch-solidgoldmagikarp.yaml +0 -10
  160. package/dist/cli/attack-corpus/harmful_content/dna-deepfake-guidance.yaml +0 -14
  161. package/dist/cli/attack-corpus/harmful_content/dna-discrimination.yaml +0 -14
  162. package/dist/cli/attack-corpus/harmful_content/dna-information-hazard.yaml +0 -14
  163. package/dist/cli/attack-corpus/harmful_content/dna-malicious-use-phishing.yaml +0 -14
  164. package/dist/cli/attack-corpus/harmful_content/dna-malware-assistance.yaml +0 -16
  165. package/dist/cli/attack-corpus/harmful_content/dna-misinformation-health.yaml +0 -17
  166. package/dist/cli/attack-corpus/jailbreak/adv26-adversarial-few-shot-poison.yaml +0 -27
  167. package/dist/cli/attack-corpus/jailbreak/adv26-adversarial-prompt-refraction.yaml +0 -19
  168. package/dist/cli/attack-corpus/jailbreak/adv26-adversarial-response-prefill.yaml +0 -25
  169. package/dist/cli/attack-corpus/jailbreak/adv26-compound-authority-technical.yaml +0 -24
  170. package/dist/cli/attack-corpus/jailbreak/adv26-context-error-recovery.yaml +0 -19
  171. package/dist/cli/attack-corpus/jailbreak/adv26-context-token-budget.yaml +0 -19
  172. package/dist/cli/attack-corpus/jailbreak/adv26-cot-hijack-proof.yaml +0 -20
  173. package/dist/cli/attack-corpus/jailbreak/adv26-cot-hijack-reasoning.yaml +0 -19
  174. package/dist/cli/attack-corpus/jailbreak/adv26-meta-alignment-test.yaml +0 -22
  175. package/dist/cli/attack-corpus/jailbreak/adv26-persona-memory.yaml +0 -17
  176. package/dist/cli/attack-corpus/jailbreak/adv26-persona-mirror.yaml +0 -16
  177. package/dist/cli/attack-corpus/jailbreak/adv26-persona-split.yaml +0 -17
  178. package/dist/cli/attack-corpus/jailbreak/adv26-persona-timetravel.yaml +0 -15
  179. package/dist/cli/attack-corpus/jailbreak/dan-anti.yaml +0 -16
  180. package/dist/cli/attack-corpus/jailbreak/dan-dude.yaml +0 -16
  181. package/dist/cli/attack-corpus/jailbreak/dan-jailbreak-v1.yaml +0 -21
  182. package/dist/cli/attack-corpus/jailbreak/dan-jailbreak-v2.yaml +0 -19
  183. package/dist/cli/attack-corpus/jailbreak/dan-stan.yaml +0 -16
  184. package/dist/cli/attack-corpus/jailbreak/debug-mode-activation.yaml +0 -20
  185. package/dist/cli/attack-corpus/jailbreak/iris-self-jailbreak.yaml +0 -23
  186. package/dist/cli/attack-corpus/jailbreak/logic-trap-moral.yaml +0 -20
  187. package/dist/cli/attack-corpus/jailbreak/logic-trap-paradox.yaml +0 -17
  188. package/dist/cli/attack-corpus/jailbreak/policy-puppetry-json.yaml +0 -25
  189. package/dist/cli/attack-corpus/jailbreak/policy-puppetry-xml.yaml +0 -20
  190. package/dist/cli/attack-corpus/jailbreak/simulation-mode.yaml +0 -19
  191. package/dist/cli/attack-corpus/latent_injection/adv26-compound-trojan-doc.yaml +0 -26
  192. package/dist/cli/attack-corpus/latent_injection/latent-code-comment-injection.yaml +0 -18
  193. package/dist/cli/attack-corpus/latent_injection/latent-email-injection.yaml +0 -23
  194. package/dist/cli/attack-corpus/latent_injection/latent-report-injection.yaml +0 -21
  195. package/dist/cli/attack-corpus/latent_injection/latent-resume-injection.yaml +0 -23
  196. package/dist/cli/attack-corpus/latent_injection/latent-whois-snippet.yaml +0 -19
  197. package/dist/cli/attack-corpus/multi-turn/multiturn-context-confusion.yaml +0 -20
  198. package/dist/cli/attack-corpus/multi-turn/multiturn-emergency.yaml +0 -20
  199. package/dist/cli/attack-corpus/multi-turn/multiturn-employee-impersonation.yaml +0 -20
  200. package/dist/cli/attack-corpus/multi-turn/multiturn-example-injection.yaml +0 -20
  201. package/dist/cli/attack-corpus/multi-turn/multiturn-jailbreak-buildup.yaml +0 -20
  202. package/dist/cli/attack-corpus/multi-turn/multiturn-memory-manipulation.yaml +0 -20
  203. package/dist/cli/attack-corpus/multi-turn/multiturn-privilege-escalation.yaml +0 -23
  204. package/dist/cli/attack-corpus/multi-turn/multiturn-split-request.yaml +0 -20
  205. package/dist/cli/attack-corpus/multi-turn/multiturn-trust-building.yaml +0 -19
  206. package/dist/cli/attack-corpus/multilingual/multilingual-mixed.yaml +0 -10
  207. package/dist/cli/attack-corpus/multilingual/multilingual-spanish.yaml +0 -10
  208. package/dist/cli/attack-corpus/prompt_injection/adv26-context-fake-history.yaml +0 -16
  209. package/dist/cli/attack-corpus/prompt_injection/adv26-context-sandwich.yaml +0 -18
  210. package/dist/cli/attack-corpus/prompt_injection/adv26-context-system-message.yaml +0 -19
  211. package/dist/cli/attack-corpus/prompt_injection/adv26-crossmodal-yaml.yaml +0 -30
  212. package/dist/cli/attack-corpus/prompt_injection/adv26-semantic-decomp-stepwise.yaml +0 -16
  213. package/dist/cli/attack-corpus/prompt_injection/context-json-injection.yaml +0 -15
  214. package/dist/cli/attack-corpus/prompt_injection/context-markdown-injection.yaml +0 -26
  215. package/dist/cli/attack-corpus/prompt_injection/context-xml-injection.yaml +0 -19
  216. package/dist/cli/attack-corpus/prompt_injection/continuation-code.yaml +0 -16
  217. package/dist/cli/attack-corpus/prompt_injection/continuation-story.yaml +0 -10
  218. package/dist/cli/attack-corpus/prompt_injection/cve-2025-copilot.yaml +0 -17
  219. package/dist/cli/attack-corpus/prompt_injection/ignore-instructions-v1.yaml +0 -14
  220. package/dist/cli/attack-corpus/prompt_injection/ignore-instructions-v2.yaml +0 -16
  221. package/dist/cli/attack-corpus/prompt_injection/ignore-instructions-v3.yaml +0 -18
  222. package/dist/cli/attack-corpus/prompt_injection/indirect-file.yaml +0 -10
  223. package/dist/cli/attack-corpus/prompt_injection/indirect-url.yaml +0 -10
  224. package/dist/cli/attack-corpus/prompt_injection/instruction-hierarchy.yaml +0 -20
  225. package/dist/cli/attack-corpus/prompt_injection/multilang-chain.yaml +0 -16
  226. package/dist/cli/attack-corpus/prompt_injection/multilang-chinese.yaml +0 -10
  227. package/dist/cli/attack-corpus/prompt_injection/multilang-japanese.yaml +0 -11
  228. package/dist/cli/attack-corpus/prompt_injection/multilang-mixed.yaml +0 -10
  229. package/dist/cli/attack-corpus/prompt_injection/multilang-polish.yaml +0 -11
  230. package/dist/cli/attack-corpus/prompt_injection/multilang-spanish.yaml +0 -14
  231. package/dist/cli/attack-corpus/prompt_injection/nested-instruction.yaml +0 -22
  232. package/dist/cli/attack-corpus/prompt_injection/template-injection-v1.yaml +0 -14
  233. package/dist/cli/attack-corpus/prompt_injection/template-injection-v2.yaml +0 -10
  234. package/dist/cli/attack-corpus/prompt_injection/tool-file-write.yaml +0 -13
  235. package/dist/cli/attack-corpus/prompt_injection/tool-function-override.yaml +0 -13
  236. package/dist/cli/attack-corpus/prompt_injection/tool-log-injection.yaml +0 -13
  237. package/dist/cli/attack-corpus/prompt_injection/tool-orchestration-abuse.yaml +0 -14
  238. package/dist/cli/attack-corpus/prompt_injection/tool-session-fixation.yaml +0 -12
  239. package/dist/cli/attack-corpus/role_manipulation/role-reversal-v1.yaml +0 -20
  240. package/dist/cli/attack-corpus/role_manipulation/role-reversal-v2.yaml +0 -16
  241. package/dist/cli/attack-corpus/social_engineering/adv26-compound-compliance-trap.yaml +0 -23
  242. package/dist/cli/attack-corpus/social_engineering/adv26-compound-emotional-technical.yaml +0 -18
  243. package/dist/cli/attack-corpus/social_engineering/adv26-cot-hijack-socratic.yaml +0 -19
  244. package/dist/cli/attack-corpus/social_engineering/adv26-persona-dying.yaml +0 -15
  245. package/dist/cli/attack-corpus/social_engineering/adv26-reward-consensus.yaml +0 -17
  246. package/dist/cli/attack-corpus/social_engineering/adv26-reward-gradient.yaml +0 -21
  247. package/dist/cli/attack-corpus/social_engineering/adv26-reward-helpful-framing.yaml +0 -17
  248. package/dist/cli/attack-corpus/social_engineering/adv26-reward-praise-prime.yaml +0 -13
  249. package/dist/cli/attack-corpus/social_engineering/adv26-reward-punishment.yaml +0 -13
  250. package/dist/cli/attack-corpus/social_engineering/adv26-semantic-decomp-analogy.yaml +0 -16
  251. package/dist/cli/attack-corpus/social_engineering/emotional-authority.yaml +0 -14
  252. package/dist/cli/attack-corpus/social_engineering/emotional-urgency.yaml +0 -14
  253. package/dist/cli/attack-corpus/social_engineering/grandma-bedtime-v1.yaml +0 -21
  254. package/dist/cli/attack-corpus/social_engineering/grandma-bedtime-v2.yaml +0 -17
  255. package/dist/cli/attack-corpus/social_engineering/grandma-colorful-words.yaml +0 -14
  256. package/dist/cli/attack-corpus/social_engineering/hypothetical-fiction.yaml +0 -10
  257. package/dist/cli/attack-corpus/social_engineering/hypothetical-research.yaml +0 -10
  258. package/dist/cli/attack-corpus/social_engineering/hypothetical-training.yaml +0 -13
  259. package/dist/cli/attack-corpus/social_engineering/hypothetical-v1.yaml +0 -17
  260. package/dist/cli/attack-corpus/social_engineering/hypothetical-v2.yaml +0 -14
  261. package/dist/cli/attack-corpus/social_engineering/hypothetical-v3.yaml +0 -14
  262. package/dist/cli/attack-corpus/social_engineering/meta-explanation.yaml +0 -14
  263. package/dist/cli/attack-corpus/social_engineering/phrasing-comparative.yaml +0 -10
  264. package/dist/cli/attack-corpus/social_engineering/phrasing-educational.yaml +0 -14
  265. package/dist/cli/attack-corpus/social_engineering/phrasing-future-tense.yaml +0 -10
  266. package/dist/cli/attack-corpus/social_engineering/phrasing-past-tense.yaml +0 -10
  267. package/dist/cli/attack-corpus/social_engineering/phrasing-third-person.yaml +0 -10
  268. package/dist/cli/attack-corpus/social_engineering/privilege-escalation-v1.yaml +0 -14
  269. package/dist/cli/attack-corpus/social_engineering/privilege-escalation-v2.yaml +0 -14
  270. package/dist/cli/attack-corpus/social_engineering/recursive-explanation.yaml +0 -15
  271. package/dist/cli/attack-corpus/social_engineering/smuggle-academic-paper.yaml +0 -10
  272. package/dist/cli/attack-corpus/social_engineering/smuggle-function-masking.yaml +0 -19
  273. package/dist/cli/attack-corpus/social_engineering/smuggle-hypothetical-response.yaml +0 -10
  274. package/dist/cli/attack-corpus/social_engineering/smuggle-roleplay-interviewer.yaml +0 -12
  275. package/dist/cli/attack-corpus/social_engineering/smuggle-translation-mask.yaml +0 -12
  276. package/dist/cli/attack-corpus/social_engineering/tool-admin-impersonation.yaml +0 -16
  277. package/dist/cli/attack-corpus/social_engineering/tool-sudo-mode.yaml +0 -17
  278. package/dist/cli/attack-corpus/stress_test/context-window-overflow.yaml +0 -17
  279. package/dist/cli/attack-corpus/stress_test/extreme-payload-50k.yaml +0 -13
  280. package/dist/cli/attack-corpus/stress_test/large-payload-10k.yaml +0 -12
  281. package/dist/cli/attack-corpus/stress_test/large-payload-5k.yaml +0 -12
  282. package/dist/cli/attack-corpus/stress_test/long-prompt-exhaustion.yaml +0 -19
  283. package/dist/cli/attack-corpus/stress_test/stress-large-payload.yaml +0 -16
  284. package/dist/cli/attack-corpus/stress_test/stress-repetition.yaml +0 -14
  285. package/dist/cli/backupManifest.d.ts +0 -7
  286. package/dist/cli/backupManifest.js +0 -108
  287. package/dist/cli/commands/agentCi.d.ts +0 -15
  288. package/dist/cli/commands/agentCi.js +0 -418
  289. package/dist/cli/commands/approve.d.ts +0 -17
  290. package/dist/cli/commands/approve.js +0 -40
  291. package/dist/cli/commands/autoProtect.d.ts +0 -10
  292. package/dist/cli/commands/autoProtect.js +0 -154
  293. package/dist/cli/commands/ciProtect.d.ts +0 -44
  294. package/dist/cli/commands/ciProtect.js +0 -123
  295. package/dist/cli/commands/clipboardScan.d.ts +0 -2
  296. package/dist/cli/commands/clipboardScan.js +0 -51
  297. package/dist/cli/commands/cmdGuard.d.ts +0 -41
  298. package/dist/cli/commands/cmdGuard.js +0 -411
  299. package/dist/cli/commands/configure.d.ts +0 -10
  300. package/dist/cli/commands/configure.js +0 -131
  301. package/dist/cli/commands/credits.d.ts +0 -6
  302. package/dist/cli/commands/credits.js +0 -21
  303. package/dist/cli/commands/daemon.d.ts +0 -120
  304. package/dist/cli/commands/daemon.js +0 -2449
  305. package/dist/cli/commands/demoActions.d.ts +0 -117
  306. package/dist/cli/commands/demoActions.js +0 -450
  307. package/dist/cli/commands/desktopChatGuard.d.ts +0 -54
  308. package/dist/cli/commands/desktopChatGuard.js +0 -629
  309. package/dist/cli/commands/deterministicGuard.d.ts +0 -102
  310. package/dist/cli/commands/deterministicGuard.js +0 -1281
  311. package/dist/cli/commands/discover.d.ts +0 -92
  312. package/dist/cli/commands/discover.js +0 -1125
  313. package/dist/cli/commands/discoverAgentFiles.d.ts +0 -36
  314. package/dist/cli/commands/discoverAgentFiles.js +0 -345
  315. package/dist/cli/commands/discoverBlastRadius.d.ts +0 -36
  316. package/dist/cli/commands/discoverBlastRadius.js +0 -201
  317. package/dist/cli/commands/discoverPaths.d.ts +0 -83
  318. package/dist/cli/commands/discoverPaths.js +0 -537
  319. package/dist/cli/commands/discoverProxy.d.ts +0 -46
  320. package/dist/cli/commands/discoverProxy.js +0 -302
  321. package/dist/cli/commands/discoverSchedule.d.ts +0 -12
  322. package/dist/cli/commands/discoverSchedule.js +0 -209
  323. package/dist/cli/commands/discoverSecrets.d.ts +0 -41
  324. package/dist/cli/commands/discoverSecrets.js +0 -608
  325. package/dist/cli/commands/doctor.d.ts +0 -11
  326. package/dist/cli/commands/doctor.js +0 -297
  327. package/dist/cli/commands/ephemeralStack.d.ts +0 -82
  328. package/dist/cli/commands/ephemeralStack.js +0 -185
  329. package/dist/cli/commands/flushSpool.d.ts +0 -13
  330. package/dist/cli/commands/flushSpool.js +0 -28
  331. package/dist/cli/commands/hook.d.ts +0 -141
  332. package/dist/cli/commands/hook.js +0 -1679
  333. package/dist/cli/commands/init.d.ts +0 -1
  334. package/dist/cli/commands/init.js +0 -95
  335. package/dist/cli/commands/installAll.d.ts +0 -22
  336. package/dist/cli/commands/installAll.js +0 -186
  337. package/dist/cli/commands/installClaudeHook.d.ts +0 -39
  338. package/dist/cli/commands/installClaudeHook.js +0 -336
  339. package/dist/cli/commands/installCursorHook.d.ts +0 -33
  340. package/dist/cli/commands/installCursorHook.js +0 -380
  341. package/dist/cli/commands/knownMcpServers.d.ts +0 -8
  342. package/dist/cli/commands/knownMcpServers.js +0 -113
  343. package/dist/cli/commands/local-scan.d.ts +0 -44
  344. package/dist/cli/commands/local-scan.js +0 -3003
  345. package/dist/cli/commands/login.d.ts +0 -17
  346. package/dist/cli/commands/login.js +0 -75
  347. package/dist/cli/commands/mcpGateway.d.ts +0 -119
  348. package/dist/cli/commands/mcpGateway.js +0 -2987
  349. package/dist/cli/commands/onboard.d.ts +0 -41
  350. package/dist/cli/commands/onboard.js +0 -713
  351. package/dist/cli/commands/onboardingJournal.d.ts +0 -20
  352. package/dist/cli/commands/onboardingJournal.js +0 -104
  353. package/dist/cli/commands/posixShellGuard.d.ts +0 -26
  354. package/dist/cli/commands/posixShellGuard.js +0 -410
  355. package/dist/cli/commands/protectionRepair.d.ts +0 -14
  356. package/dist/cli/commands/protectionRepair.js +0 -24
  357. package/dist/cli/commands/restartNotice.d.ts +0 -2
  358. package/dist/cli/commands/restartNotice.js +0 -14
  359. package/dist/cli/commands/scan.d.ts +0 -48
  360. package/dist/cli/commands/scan.js +0 -134
  361. package/dist/cli/commands/shellGuard.d.ts +0 -96
  362. package/dist/cli/commands/shellGuard.js +0 -880
  363. package/dist/cli/commands/taintLedger.d.ts +0 -108
  364. package/dist/cli/commands/taintLedger.js +0 -587
  365. package/dist/cli/commands/uninstallAll.d.ts +0 -67
  366. package/dist/cli/commands/uninstallAll.js +0 -454
  367. package/dist/cli/commands/verifyRemoved.d.ts +0 -24
  368. package/dist/cli/commands/verifyRemoved.js +0 -294
  369. package/dist/cli/commands/watchdog.d.ts +0 -28
  370. package/dist/cli/commands/watchdog.js +0 -158
  371. package/dist/cli/commands/windowsAudit.d.ts +0 -92
  372. package/dist/cli/commands/windowsAudit.js +0 -479
  373. package/dist/cli/commands/workloadProtect.d.ts +0 -61
  374. package/dist/cli/commands/workloadProtect.js +0 -173
  375. package/dist/cli/config.d.ts +0 -130
  376. package/dist/cli/config.js +0 -583
  377. package/dist/cli/credentialStore.d.ts +0 -19
  378. package/dist/cli/credentialStore.js +0 -136
  379. package/dist/cli/daemonForensics.d.ts +0 -178
  380. package/dist/cli/daemonForensics.js +0 -318
  381. package/dist/cli/describeError.d.ts +0 -17
  382. package/dist/cli/describeError.js +0 -74
  383. package/dist/cli/devConfirm.d.ts +0 -78
  384. package/dist/cli/devConfirm.js +0 -241
  385. package/dist/cli/discoveryMarker.d.ts +0 -9
  386. package/dist/cli/discoveryMarker.js +0 -81
  387. package/dist/cli/distress.d.ts +0 -124
  388. package/dist/cli/distress.js +0 -245
  389. package/dist/cli/envDiagnostics.d.ts +0 -53
  390. package/dist/cli/envDiagnostics.js +0 -114
  391. package/dist/cli/honeypot.d.ts +0 -45
  392. package/dist/cli/honeypot.js +0 -190
  393. package/dist/cli/hookIo.d.ts +0 -43
  394. package/dist/cli/hookIo.js +0 -189
  395. package/dist/cli/hookSlim.d.ts +0 -32
  396. package/dist/cli/hookSlim.js +0 -142
  397. package/dist/cli/index.d.ts +0 -2
  398. package/dist/cli/index.js +0 -1141
  399. package/dist/cli/integrity.d.ts +0 -23
  400. package/dist/cli/integrity.js +0 -159
  401. package/dist/cli/localSafetySnapshot.d.ts +0 -49
  402. package/dist/cli/localSafetySnapshot.js +0 -254
  403. package/dist/cli/machineActionVerify.d.ts +0 -58
  404. package/dist/cli/machineActionVerify.js +0 -160
  405. package/dist/cli/machineIdentity.d.ts +0 -23
  406. package/dist/cli/machineIdentity.js +0 -235
  407. package/dist/cli/machineKeyFile.d.ts +0 -25
  408. package/dist/cli/machineKeyFile.js +0 -226
  409. package/dist/cli/notify.d.ts +0 -30
  410. package/dist/cli/notify.js +0 -139
  411. package/dist/cli/output.d.ts +0 -11
  412. package/dist/cli/output.js +0 -292
  413. package/dist/cli/perfSnapshot.d.ts +0 -113
  414. package/dist/cli/perfSnapshot.js +0 -274
  415. package/dist/cli/policyGateHealth.d.ts +0 -45
  416. package/dist/cli/policyGateHealth.js +0 -135
  417. package/dist/cli/pollLoop.d.ts +0 -78
  418. package/dist/cli/pollLoop.js +0 -160
  419. package/dist/cli/runtimeConfig.d.ts +0 -183
  420. package/dist/cli/runtimeConfig.js +0 -474
  421. package/dist/cli/securityAgents.d.ts +0 -26
  422. package/dist/cli/securityAgents.js +0 -65
  423. package/dist/cli/selfTest.d.ts +0 -48
  424. package/dist/cli/selfTest.js +0 -212
  425. package/dist/cli/selfUpdate.d.ts +0 -101
  426. package/dist/cli/selfUpdate.js +0 -515
  427. package/dist/cli/sessionLimits.d.ts +0 -76
  428. package/dist/cli/sessionLimits.js +0 -330
  429. package/dist/cli/telemetry.d.ts +0 -134
  430. package/dist/cli/telemetry.js +0 -433
  431. package/dist/cli/verdictIpc.d.ts +0 -30
  432. package/dist/cli/verdictIpc.js +0 -244
  433. package/dist/cli/verdictIpcClient.d.ts +0 -103
  434. package/dist/cli/verdictIpcClient.js +0 -251
  435. package/dist/cli/version.json +0 -3
  436. package/dist/cli/windowsTaskState.d.ts +0 -40
  437. package/dist/cli/windowsTaskState.js +0 -43
@@ -1,1281 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.stripInertDataSegments = stripInertDataSegments;
37
- exports.scanDeterministicToolCall = scanDeterministicToolCall;
38
- exports.scanDeterministicTextResponse = scanDeterministicTextResponse;
39
- exports.scanDeterministicPrompt = scanDeterministicPrompt;
40
- exports.resolveDeterministicOutcome = resolveDeterministicOutcome;
41
- exports.resolveDeterministicTextResponse = resolveDeterministicTextResponse;
42
- const fs = __importStar(require("fs"));
43
- const os = __importStar(require("os"));
44
- const path = __importStar(require("path"));
45
- const SECRET_PATTERNS = [
46
- { itemId: 'private_key_material', label: 'private key material', re: /-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----/i },
47
- { itemId: 'aws_access_key', label: 'AWS access key', re: /\bAKIA[0-9A-Z]{16}\b/ },
48
- { itemId: 'github_token', label: 'GitHub token', re: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{20,}\b/ },
49
- { itemId: 'github_token', label: 'GitHub fine-grained token', re: /\bgithub_pat_[A-Za-z0-9_]{20,}\b/ },
50
- { itemId: 'anthropic_key', label: 'Anthropic API key', re: /\bsk-ant-[A-Za-z0-9_-]{20,}\b/ },
51
- { itemId: 'openai_key', label: 'OpenAI project key', re: /\bsk-proj-[A-Za-z0-9_-]{20,}\b/ },
52
- { itemId: 'openai_key', label: 'OpenAI API key', re: /\bsk-[A-Za-z0-9_-]{32,}\b/ },
53
- { itemId: 'slack_token', label: 'Slack token', re: /\bxox[baprs]-[A-Za-z0-9-]{20,}\b/ },
54
- { itemId: 'stripe_live_key', label: 'Stripe live key', re: /\b[rs]k_live_[0-9a-zA-Z]{24,}\b/ },
55
- { itemId: 'google_api_key', label: 'Google API key', re: /\bAIza[0-9A-Za-z_-]{35}\b/ },
56
- { itemId: 'huggingface_token_secret', label: 'HuggingFace token', re: /\bhf_[A-Za-z0-9]{30,}\b/ },
57
- { itemId: 'database_url_password', label: 'database URL with password', re: /\b(?:postgres(?:ql)?|mongodb(?:\+srv)?|mysql):\/\/[^/\s'":]+:[^@\s'"]+@/i },
58
- ];
59
- // Contextual secret detection: bare high-entropy strings (hex app secrets,
60
- // random tokens) have no recognizable prefix, so SECRET_PATTERNS misses them.
61
- // When one sits next to a credential keyword ("secret", "password", "api key"
62
- // ...), treat it as secret material. Keyword proximity keeps git SHAs, UUIDs
63
- // in URLs, and hashes in ordinary output from false-positiving.
64
- // English terms use \b word boundaries (so "tokenizer" does not match "token").
65
- // Deliberately canonical words only — no typo/shorthand variants (pswd, scrt,
66
- // ...). A deterministic guard must stay predictable; typo evasion is handled
67
- // by the cloud tier (meta-safety specialist is typo-augmented).
68
- const CONTEXT_SECRET_KEYWORD_EN = /\b(?:secret|password|passwd|pwd|credential|passphrase|api[ _-]?key|apikey|access[ _-]?key|private[ _-]?key|client[ _-]?secret|app[ _-]?secret|signing[ _-]?key|auth[ _-]?token|bearer|token)\b/i;
69
- // Language-agnostic pack: password/secret/key words across common languages.
70
- // No \b — JS word boundaries break on diacritics and non-Latin scripts. Broad
71
- // everyday words ("clave", "chiave", "ключ") are safe to include because a
72
- // keyword NEVER blocks alone: a high-entropy credential-looking token must
73
- // also sit within the context window.
74
- const CONTEXT_SECRET_KEYWORD_MULTI = new RegExp([
75
- // Romance: Romanian (first customer — parola/parolă, cheie/cheia/cheile,
76
- // credențial; "secret"/"token" are identical to English and covered there),
77
- // Spanish, French, Italian, Portuguese
78
- 'parol', 'chei', 'credenția', 'credentia', 'contraseñ', 'clave', 'mot de passe', 'clé', 'jeton', 'chiave', 'segret', 'senha', 'chave', 'segredo',
79
- // Germanic: German, Dutch, Swedish, Norwegian, Danish
80
- 'passwort', 'kennwort', 'schlüssel', 'geheim', 'wachtwoord', 'sleutel', 'lösenord', 'løsenord', 'passord', 'adgangskode', 'nøkkel', 'hemlig',
81
- // Slavic (Latin + Cyrillic): Polish, Czech, Russian, Ukrainian, Bulgarian, Serbian
82
- 'hasło', 'haslo', 'klucz', 'sekret', 'heslo', 'klíč', 'geslo', 'пароль', 'парол', 'ключ', 'секрет', 'токен',
83
- // Turkish, Hungarian, Finnish, Greek
84
- 'şifre', 'sifre', 'anahtar', 'gizli', 'jelszó', 'jelszo', 'kulcs', 'titok', 'salasana', 'avain', 'salainen', 'κωδικ', 'μυστικ', 'κλειδ',
85
- // Hebrew, Arabic, Persian
86
- 'סיסמה', 'סיסמא', 'מפתח', 'סוד', 'كلمة المرور', 'كلمة السر', 'مفتاح', 'رمز سري', 'رمز', 'گذرواژه', 'رمز عبور',
87
- // Indic: Hindi, Bengali, Tamil
88
- 'पासवर्ड', 'कुंजी', 'गुप्त', 'পাসওয়ার্ড', 'கடவுச்சொல்',
89
- // CJK: Chinese (simplified + traditional), Japanese, Korean
90
- '密码', '密碼', '密钥', '密鑰', '口令', '令牌', '秘钥', 'パスワード', 'トークン', '秘密鍵', '비밀번호', '암호', '토큰', '비밀 키',
91
- // Vietnamese, Indonesian/Malay, Thai
92
- 'mật khẩu', 'bí mật', 'kata sandi', 'kata laluan', 'rahasia', 'rahsia', 'kunci', 'รหัสผ่าน', 'กุญแจ', 'ความลับ',
93
- ].join('|'), 'iu');
94
- function hasSecretKeyword(text) {
95
- return CONTEXT_SECRET_KEYWORD_EN.test(text) || CONTEXT_SECRET_KEYWORD_MULTI.test(text);
96
- }
97
- const CONTEXT_WINDOW_CHARS = 120;
98
- function shannonEntropy(value) {
99
- const counts = new Map();
100
- for (const ch of value)
101
- counts.set(ch, (counts.get(ch) || 0) + 1);
102
- let entropy = 0;
103
- for (const count of counts.values()) {
104
- const p = count / value.length;
105
- entropy -= p * Math.log2(p);
106
- }
107
- return entropy;
108
- }
109
- function isHighEntropyToken(token) {
110
- // Pure hex (app secrets, HMAC keys): hex charset caps entropy at 4 bits and
111
- // excludes most English letters, so a modest bar is already selective.
112
- if (/^[A-Fa-f0-9]+$/.test(token)) {
113
- return token.length >= 24 && shannonEntropy(token) >= 3.0;
114
- }
115
- // Mixed charset: the 3.8-bit bar keeps camelCase identifiers and English-y
116
- // names out (they sit ~3.0-3.6) while random tokens land at ~4.1+.
117
- if (token.length >= 20 && /\d/.test(token) && /[A-Za-z]/.test(token) && shannonEntropy(token) >= 3.8)
118
- return true;
119
- // KEY=value style: evaluate the assigned value on its own.
120
- const assigned = token.includes('=') ? token.split('=').pop() : undefined;
121
- if (assigned && assigned !== token && assigned.length >= 20)
122
- return isHighEntropyToken(assigned);
123
- return false;
124
- }
125
- function maskSecretValue(value) {
126
- return value.length <= 10 ? '***' : `${value.slice(0, 6)}…${value.slice(-4)} (${value.length} chars)`;
127
- }
128
- function findContextualSecret(text) {
129
- if (!hasSecretKeyword(text))
130
- return undefined;
131
- for (const match of text.matchAll(/[A-Za-z0-9_\-+/=]{20,}/g)) {
132
- const token = match[0];
133
- const index = match.index ?? 0;
134
- // Skip tokens inside URLs / file paths — path segments and query params
135
- // routinely look random but are not pasteable credentials.
136
- const before = text.slice(Math.max(0, index - 2), index);
137
- if (/[/\\.]/.test(before))
138
- continue;
139
- const windowText = text.slice(Math.max(0, index - CONTEXT_WINDOW_CHARS), Math.min(text.length, index + token.length + CONTEXT_WINDOW_CHARS));
140
- if (!hasSecretKeyword(windowText.replace(token, '')))
141
- continue;
142
- if (!isHighEntropyToken(token))
143
- continue;
144
- return { itemId: 'contextual_secret', label: 'credential-like string near a secret keyword', value: maskSecretValue(token) };
145
- }
146
- return undefined;
147
- }
148
- /** toolArgs like { password: "<random>" } — the keyword lives in the key, not the value. */
149
- function contextualSecretFromKeyPath(keyPath, value) {
150
- const lastKey = keyPath.split('.').pop() || '';
151
- if (!hasSecretKeyword(lastKey.replace(/[_-]/g, ' ')))
152
- return undefined;
153
- const trimmed = value.trim();
154
- if (!/^[A-Za-z0-9_\-+/=]+$/.test(trimmed) || !isHighEntropyToken(trimmed))
155
- return undefined;
156
- return { itemId: 'contextual_secret', label: `credential-like value in "${lastKey}"`, value: maskSecretValue(trimmed) };
157
- }
158
- const METADATA_ENDPOINTS = [
159
- { itemId: 'aws_gcp_metadata_ip', value: '169.254.169.254', label: 'cloud metadata endpoint' },
160
- { itemId: 'gcp_metadata_host', value: 'metadata.google.internal', label: 'GCP metadata endpoint' },
161
- { itemId: 'azure_metadata_host', value: 'metadata.azure.com', label: 'Azure metadata endpoint' },
162
- { itemId: 'alibaba_metadata_ip', value: '100.100.100.200', label: 'Alibaba cloud metadata endpoint' },
163
- ];
164
- const OUTBOUND_TOOL_HINT = /(?:http|fetch|request|curl|wget|webhook|upload|send|email|mail|slack|discord|teams|post|put|publish|notify)/i;
165
- const COMMAND_TOOL_HINT = /(?:shell|bash|command|cmd|powershell|terminal|exec|subprocess|run|script)/i;
166
- const SQL_TOOL_HINT = /(?:sql|query|database|postgres|mysql|sqlite|snowflake|bigquery|db)/i;
167
- const COMMAND_KEYS = new Set([
168
- 'command',
169
- 'cmd',
170
- 'script',
171
- 'shell',
172
- 'bash',
173
- 'powershell',
174
- 'args.command',
175
- 'toolArgs.command',
176
- ]);
177
- const SQL_KEYS = new Set([
178
- 'query',
179
- 'sql',
180
- 'statement',
181
- 'migration',
182
- 'args.query',
183
- 'args.sql',
184
- 'toolArgs.query',
185
- 'toolArgs.sql',
186
- ]);
187
- const DEFAULT_DISABLED_BUILT_INS = new Set([
188
- 'git_clean_force',
189
- 'generic_kubectl_delete',
190
- 'truncate_table',
191
- // Entropy-based contextual secret detection false-positives on ordinary
192
- // hashes/tokens near credential wording (e.g. source files opened in an
193
- // IDE). Off by default — orgs opt in via the Local Safety console toggle,
194
- // which the runtime snapshot then applies on every machine.
195
- 'contextual_secret',
196
- // Cloud token printers / secret fetchers used constantly by LEGITIMATE
197
- // deploy tooling and dev loops. Off by default; orgs with stricter posture
198
- // opt in via the console. (The rarely-legitimate forms — gh auth token,
199
- // git credential fill, keychain dumps — are ON by default.)
200
- 'gcloud_access_token_cmd',
201
- 'gcloud_secret_access_cmd',
202
- 'az_access_token_cmd',
203
- 'aws_secret_fetch_cmd',
204
- 'vault_read_cmd',
205
- ]);
206
- function evidence(value) {
207
- const compact = value.replace(/\s+/g, ' ').trim();
208
- return compact.length > 180 ? `${compact.slice(0, 180)}...` : compact;
209
- }
210
- function decodeLoosely(value) {
211
- let out = value;
212
- for (let i = 0; i < 2; i++) {
213
- try {
214
- const decoded = decodeURIComponent(out);
215
- if (decoded === out)
216
- break;
217
- out = decoded;
218
- }
219
- catch {
220
- break;
221
- }
222
- }
223
- return out;
224
- }
225
- function normalizeForPath(value) {
226
- return decodeLoosely(value)
227
- .replace(/\\/g, '/')
228
- .replace(/\/+/g, '/')
229
- .toLowerCase();
230
- }
231
- function normalizeForCommand(value) {
232
- return decodeLoosely(value).replace(/\s+/g, ' ').trim();
233
- }
234
- /** Strip shell quoting/escaping that carries no semantic weight but defeats a
235
- * naive substring/regex scan: de"l" /s /q, "C:\", 'rm' -rf /, i`e`x. Only used
236
- * to build alternate COMMAND-matching variants — never for secret/path rules,
237
- * where quotes can be meaningful. */
238
- function stripShellQuoting(text) {
239
- return text.replace(/["'`]/g, '').replace(/\s+/g, ' ').trim();
240
- }
241
- /** Drop Windows executable suffixes so `gh.exe`, `del.exe`, `powershell.exe`,
242
- * `foo.cmd` match the same rules as their bare command word. Scoped to real
243
- * script-host extensions so it cannot maul URLs/filenames (`evil.com` is left
244
- * intact). */
245
- function stripExeSuffix(text) {
246
- return text.replace(/\.(?:exe|cmd|bat|ps1)\b/gi, '');
247
- }
248
- /** cmd.exe treats `^` as an escape for the NEXT character, so `r^m -rf /` runs
249
- * `rm -rf /` and `powershe^ll` runs powershell. `^^` is a literal caret —
250
- * protect it before stripping so we don't delete both. Variant-only transform. */
251
- function stripCmdCarets(text) {
252
- return text.replace(/\^\^/g, '\u0000').replace(/\^/g, '').replace(/\u0000/g, '^');
253
- }
254
- /** POSIX shell token evasions (PayloadsAllTheThings "Filter Bypasses"):
255
- * - `${IFS}` / `$IFS` / `${IFS%??}` whitespace substitution: `rm${IFS}-rf${IFS}/`
256
- * - brace expansion word-splitting: `{rm,-rf,/}` -> `rm -rf /`
257
- * - backslash escaping of ordinary chars: `r\m -rf /` -> `rm -rf /`
258
- * Variant-only (raw is always kept), so a benign command whose de-obfuscated
259
- * form is harmless simply yields a non-matching extra surface. */
260
- function deobfuscateShellTokens(text) {
261
- let out = text.replace(/\$\{IFS[^}]*\}/g, ' ').replace(/\$IFS\b/g, ' ');
262
- for (let i = 0; i < 3 && /\{[^{}]*,[^{}]*\}/.test(out); i++) {
263
- out = out.replace(/\{([^{}]*,[^{}]*)\}/g, (_m, body) => body.split(',').join(' '));
264
- }
265
- out = out.replace(/\\(?=[A-Za-z0-9])/g, '');
266
- return out.replace(/\s+/g, ' ').trim();
267
- }
268
- /** bash/zsh ANSI-C quoting: `$'\x72\x6d'` IS `rm`. Decode `\xHH`, `\uHHHH`,
269
- * octal, and single-char escapes, splicing plain text back into the command. */
270
- function decodeAnsiCQuoting(text) {
271
- return text.replace(/\$'((?:[^'\\]|\\.)*)'/g, (_m, body) => body.replace(/\\(x[0-9a-fA-F]{1,2}|u[0-9a-fA-F]{1,4}|[0-7]{1,3}|.)/g, (_e, esc) => {
272
- if (esc[0] === 'x' || esc[0] === 'u')
273
- return String.fromCharCode(parseInt(esc.slice(1), 16));
274
- if (/^[0-7]/.test(esc))
275
- return String.fromCharCode(parseInt(esc, 8));
276
- const map = { n: '\n', t: '\t', r: '\r', a: '\x07', b: '\b', f: '\f', v: '\v', e: '\x1b', '\\': '\\', "'": "'" };
277
- return map[esc] ?? esc;
278
- }));
279
- }
280
- /** Decode a base64 blob to printable text, UTF-16LE (PowerShell) then UTF-8.
281
- * Returns nothing for binary garbage so we never feed noise into the rules. */
282
- function decodeBase64Blob(b64) {
283
- const out = [];
284
- for (const enc of ['utf16le', 'utf8']) {
285
- try {
286
- const decoded = Buffer.from(b64, 'base64').toString(enc);
287
- if (decoded && /[\x20-\x7e]/.test(decoded) && !/\u0000/.test(decoded))
288
- out.push(decoded);
289
- }
290
- catch { /* not valid base64 for this encoding */ }
291
- }
292
- return out;
293
- }
294
- /** Extract hidden script payloads from one command string: PowerShell
295
- * `-EncodedCommand <b64>`, `FromBase64String('<b64>')` cradles, and
296
- * `echo <b64> | base64 -d | sh` pipelines. Short flags `-e`/`-ec`/`-en` are
297
- * ambiguous (`docker run -e`, `node -e`) — only decoded in a real PowerShell
298
- * context; `-enc` and longer are accepted anywhere. */
299
- function decodeEncodedPayloads(text) {
300
- const out = [];
301
- const push = (b64) => { for (const d of decodeBase64Blob(b64))
302
- if (out.length < 8)
303
- out.push(d); };
304
- const hasPwsh = /\b(?:powershell|pwsh)\b/i.test(text);
305
- const psEnc = /-(e(?:c|n(?:c(?:o(?:d(?:e(?:d(?:c(?:o(?:m(?:m(?:a(?:n(?:d)?)?)?)?)?)?)?)?)?)?)?)?)?)\s+([A-Za-z0-9+/=]{16,})/gi;
306
- let match;
307
- while ((match = psEnc.exec(text)) && out.length < 8) {
308
- if (match[1].toLowerCase().length < 3 && !hasPwsh)
309
- continue;
310
- push(match[2]);
311
- }
312
- const fromB64 = /frombase64string\(\s*["']([A-Za-z0-9+/=]{16,})["']/gi;
313
- while ((match = fromB64.exec(text)) && out.length < 8)
314
- push(match[1]);
315
- if (/\bbase64\s+(?:-d|-D|--decode)\b/.test(text) || /\bopenssl\s+(?:enc\s+.*-d|base64\s+-d)/.test(text)) {
316
- // Decoder present => intentional payload; >=8 covers short commands like
317
- // `rm -rf /` (12 b64 chars) that the speculative >=16 floor missed.
318
- const loose = /(?:^|["'\s|;&=])([A-Za-z0-9+/]{8,}={0,2})(?=["'\s|;&]|$)/g;
319
- while ((match = loose.exec(text)) && out.length < 8)
320
- push(match[1]);
321
- }
322
- return out;
323
- }
324
- /**
325
- * Obfuscation-resistant command expansion. A single-string regex scan is blind
326
- * to the standard evasions attackers (and prompt-injected agents) use: base64
327
- * `-EncodedCommand` / `FromBase64String` / `base64 -d` payloads (nested up to
328
- * two levels), wrapper quoting (`de"l"`, `'rm' -rf`), cmd caret escapes
329
- * (`r^m`), bash ANSI-C quoting (`$'\x72\x6d'`), POSIX token evasions
330
- * (`${IFS}`, `{rm,-rf,/}`, `r\m`), and executable-suffix aliasing (`gh.exe`).
331
- * Wrapper commands (wsl, docker exec, bash -c, ssh) need no special handling —
332
- * the inner command survives as a substring of the dequoted variant.
333
- *
334
- * Bounded by design (decode depth 2, capped variant count, length guard).
335
- * Known static limits (documented, covered by taint/approval layers instead):
336
- * runtime-only values such as `%VAR%` / `$VAR` concatenation, `${PATH:0:1}`
337
- * substrings, and `eval` of computed strings cannot be resolved statically.
338
- */
339
- function commandVariants(value) {
340
- const variants = new Set();
341
- const add = (s) => { if (s && s.length <= 8000 && variants.size < 48)
342
- variants.add(s); };
343
- const addSurfaces = (seed) => {
344
- const s = normalizeForCommand(seed);
345
- add(s);
346
- const dequoted = stripShellQuoting(s);
347
- add(dequoted);
348
- add(stripExeSuffix(s));
349
- add(stripExeSuffix(dequoted));
350
- const deob = deobfuscateShellTokens(s);
351
- if (deob !== s) {
352
- add(deob);
353
- add(stripShellQuoting(deob));
354
- }
355
- // ANSI-C decode MUST run before token de-obfuscation: the backslash-strip in
356
- // deobfuscateShellTokens would otherwise eat the `\xHH` escapes.
357
- add(normalizeForCommand(stripExeSuffix(stripShellQuoting(deobfuscateShellTokens(stripCmdCarets(decodeAnsiCQuoting(s)))))));
358
- };
359
- const base = normalizeForCommand(value);
360
- addSurfaces(base);
361
- // Nested encodes: decode payloads of the base, then decode payloads of what
362
- // came out (powershell -enc wrapping another -enc / FromBase64String).
363
- let frontier = [base];
364
- for (let depth = 0; depth < 2 && frontier.length > 0 && variants.size < 48; depth++) {
365
- const next = [];
366
- for (const source of frontier) {
367
- for (const decoded of decodeEncodedPayloads(source)) {
368
- addSurfaces(decoded);
369
- next.push(normalizeForCommand(decoded));
370
- }
371
- }
372
- frontier = next;
373
- }
374
- return Array.from(variants);
375
- }
376
- /** Run a command matcher across every de-obfuscated variant, returning the
377
- * first hit. Callers keep passing the RAW value — variant expansion is the
378
- * single seam every command rule shares, so a new evasion is defeated in one
379
- * place instead of per-rule. */
380
- function matchCommand(value, test) {
381
- for (const variant of commandVariants(value)) {
382
- const hit = test(variant, variant.toLowerCase());
383
- if (hit)
384
- return hit;
385
- }
386
- return undefined;
387
- }
388
- function collectStrings(value, keyPath = 'args', out = [], depth = 0) {
389
- if (depth > 6 || value === null || value === undefined)
390
- return out;
391
- if (typeof value === 'string') {
392
- out.push({ keyPath, value });
393
- return out;
394
- }
395
- if (typeof value === 'number' || typeof value === 'boolean') {
396
- out.push({ keyPath, value: String(value) });
397
- return out;
398
- }
399
- if (Array.isArray(value)) {
400
- value.slice(0, 50).forEach((item, index) => collectStrings(item, `${keyPath}.${index}`, out, depth + 1));
401
- return out;
402
- }
403
- if (typeof value === 'object') {
404
- for (const [key, nested] of Object.entries(value).slice(0, 100)) {
405
- collectStrings(nested, `${keyPath}.${key}`, out, depth + 1);
406
- }
407
- }
408
- return out;
409
- }
410
- function disabled(options) {
411
- return new Set(options?.disabledBuiltInItemIds || Array.from(DEFAULT_DISABLED_BUILT_INS));
412
- }
413
- function isEnabled(itemId, options) {
414
- return !disabled(options).has(itemId);
415
- }
416
- /**
417
- * Items that WARN by default (catalog-level default action). Applies only when
418
- * the snapshot carries no explicit action for the item — an org override to
419
- * 'block' ships explicitly in the snapshot and wins. Keeps offline machines
420
- * and stale snapshots on the warn-first rollout instead of hard-blocking.
421
- */
422
- const DEFAULT_WARN_BUILT_INS = new Set(['env_workspace']);
423
- function actionFor(itemId, options) {
424
- const action = options?.itemActions?.[itemId];
425
- if (action === 'warn' || action === 'mask' || action === 'block')
426
- return action;
427
- // No snapshot resolved at all: never hard-block on the catalog default —
428
- // an unarmed / offline machine mirrors the server's warn-first gate rather
429
- // than over-blocking (the class of failure Romania hit). A present snapshot
430
- // keeps the strict "absent item = block" contract below.
431
- if (options?.snapshotPresent === false)
432
- return 'warn';
433
- return DEFAULT_WARN_BUILT_INS.has(itemId) ? 'warn' : 'block';
434
- }
435
- function builtIn(itemId, categoryId, category, ruleId, reason, findingEvidence, explanation, options) {
436
- if (!isEnabled(itemId, options))
437
- return undefined;
438
- return {
439
- blocked: true,
440
- ruleId,
441
- category,
442
- categoryId,
443
- itemId,
444
- source: 'builtin',
445
- reason,
446
- evidence: evidence(findingEvidence),
447
- explanation,
448
- policyHash: options?.policyHash,
449
- action: actionFor(itemId, options),
450
- };
451
- }
452
- /**
453
- * Honeypot decoy touch — the highest-precision signal the guard has. The decoy
454
- * paths are machine-local absolute paths planted by the daemon; matching is on
455
- * the normalized absolute path or its home-anchored `~/relative` form, so a
456
- * repo file that merely shares a basename (e.g. a project-local `.env.bak`)
457
- * never matches. Fires regardless of tool context: no legitimate workflow
458
- * references these files at all.
459
- */
460
- function honeypotTouch(value, options) {
461
- // Honeypot is a catalog item (id 'honeypot_decoy_access') so admins can see it
462
- // in the console and, if they must, turn it off — nothing enforces invisibly.
463
- // It is zero-FP by design (daemon-planted decoy paths only), so it defaults ON
464
- // and disabling is discouraged, but the toggle is honored like any other rule.
465
- if (!isEnabled('honeypot_decoy_access', options))
466
- return undefined;
467
- const paths = options?.honeypotPaths;
468
- if (!paths || paths.length === 0)
469
- return undefined;
470
- const text = normalizeForPath(value);
471
- const home = normalizeForPath(os.homedir());
472
- for (const decoyPath of paths) {
473
- const decoy = normalizeForPath(decoyPath);
474
- if (!decoy)
475
- continue;
476
- const candidates = [decoy];
477
- if (home && decoy.startsWith(home + '/'))
478
- candidates.push('~' + decoy.slice(home.length));
479
- if (candidates.some(candidate => text.includes(candidate))) {
480
- return {
481
- blocked: true,
482
- ruleId: 'local-honeypot',
483
- category: 'honeypot',
484
- categoryId: 'honeypot',
485
- itemId: 'honeypot_decoy_access',
486
- source: 'builtin',
487
- reason: 'Blocked access to a decoy credential file (honeypot). No legitimate tool uses this file — this indicates credential-hunting behavior.',
488
- evidence: evidence(value),
489
- policyHash: options?.policyHash,
490
- action: actionFor('honeypot_decoy_access', options),
491
- };
492
- }
493
- }
494
- return undefined;
495
- }
496
- function customBlock(value, options) {
497
- const lower = value.toLowerCase();
498
- for (const block of options?.customBlocks || []) {
499
- const pattern = block.pattern.trim();
500
- if (!pattern || !lower.includes(pattern.toLowerCase()))
501
- continue;
502
- return {
503
- blocked: true,
504
- ruleId: 'local-custom-block',
505
- category: 'destructive_command',
506
- categoryId: block.categoryId || 'custom',
507
- itemId: block.id,
508
- source: 'custom',
509
- reason: block.explanation || `Blocked custom local safety pattern: ${pattern}.`,
510
- evidence: evidence(value),
511
- explanation: block.explanation,
512
- policyHash: options?.policyHash,
513
- action: block.action === 'warn' || block.action === 'mask' ? block.action : 'block',
514
- };
515
- }
516
- return undefined;
517
- }
518
- function findSecret(value) {
519
- for (const pattern of SECRET_PATTERNS) {
520
- const match = value.match(pattern.re);
521
- if (match?.[0])
522
- return { itemId: pattern.itemId, label: pattern.label, value: match[0] };
523
- }
524
- return undefined;
525
- }
526
- function containsMetadataEndpoint(value) {
527
- const normalized = decodeLoosely(value).toLowerCase();
528
- return METADATA_ENDPOINTS.find(endpoint => normalized.includes(endpoint.value));
529
- }
530
- function containsSensitiveCredentialPath(value) {
531
- const text = normalizeForPath(value);
532
- const traversal = /(?:^|\/)\.\.(?:\/|$)/.test(text) || /%2e/i.test(value);
533
- const checks = [
534
- { itemId: 'ssh_private_key', label: 'SSH private key', re: /(?:^|\/)\.ssh\/id_(?:rsa|ed25519|ecdsa|dsa)(?:$|[/?#\s'"])/ },
535
- { itemId: 'ssh_config', label: 'SSH config', re: /(?:^|\/)\.ssh\/config(?:$|[/?#\s'"])/ },
536
- { itemId: 'aws_credentials', label: 'AWS credentials', re: /(?:^|\/)\.aws\/(?:credentials|config)(?:$|[/?#\s'"])/ },
537
- { itemId: 'kube_config', label: 'Kubernetes config', re: /(?:^|\/)\.kube\/config(?:$|[/?#\s'"])/ },
538
- { itemId: 'docker_auth', label: 'Docker auth config', re: /(?:^|\/)\.docker\/config\.json(?:$|[/?#\s'"])/ },
539
- // GitHub CLI stores its OAuth token in hosts.yml — ~/.config/gh/ on Unix,
540
- // AppData/Roaming/GitHub CLI/ on Windows (normalized+lowercased upstream).
541
- { itemId: 'github_cli_token', label: 'GitHub CLI token', re: /(?:^|\/)(?:gh|github cli)\/hosts\.yml(?:$|[/?#\s'"])/ },
542
- { itemId: 'git_credentials', label: 'Git plaintext credentials', re: /(?:^|\/)\.git-credentials(?:$|[/?#\s'"])/ },
543
- { itemId: 'gcloud_credentials', label: 'gcloud credential store', re: /(?:^|\/)gcloud\/(?:credentials\.db|access_tokens\.db|legacy_credentials)(?:$|[/?#\s'"])/ },
544
- { itemId: 'azure_tokens', label: 'Azure token cache', re: /(?:^|\/)\.azure\/(?:msal_token_cache|accesstokens\.json)/ },
545
- { itemId: 'gnupg_private_keys', label: 'GnuPG private keys', re: /(?:^|\/)\.gnupg\/(?:private-keys-v1\.d|secring\.gpg)(?:$|[/?#\s'"])/ },
546
- { itemId: 'pgpass', label: 'PostgreSQL password file', re: /(?:^|\/)(?:\.pgpass|pgpass\.conf)(?:$|[/?#\s'"])/ },
547
- { itemId: 'mysql_cnf', label: 'MySQL credentials file', re: /(?:^|\/)\.my\.cnf(?:$|[/?#\s'"])/ },
548
- { itemId: 'terraform_credentials', label: 'Terraform credentials', re: /credentials\.tfrc\.json(?:$|[/?#\s'"])/ },
549
- { itemId: 'huggingface_token', label: 'Hugging Face token', re: /(?:^|\/)\.?huggingface\/token(?:$|[/?#\s'"])/ },
550
- { itemId: 'cargo_credentials', label: 'Cargo registry credentials', re: /(?:^|\/)\.cargo\/credentials(?:\.toml)?(?:$|[/?#\s'"])/ },
551
- { itemId: 'gem_credentials', label: 'RubyGems credentials', re: /(?:^|\/)\.gem\/credentials(?:$|[/?#\s'"])/ },
552
- { itemId: 'composer_auth', label: 'Composer auth tokens', re: /(?:^|\/)\.composer\/auth\.json(?:$|[/?#\s'"])/ },
553
- { itemId: 'npmrc', label: 'npm credentials', re: /(?:^|\/)\.npmrc(?:$|[/?#\s'"])/ },
554
- { itemId: 'pypirc', label: 'PyPI credentials', re: /(?:^|\/)\.pypirc(?:$|[/?#\s'"])/ },
555
- { itemId: 'netrc', label: 'netrc credentials', re: /(?:^|\/)\.netrc(?:$|[/?#\s'"])/ },
556
- { itemId: 'gcp_adc', label: 'GCP ADC credentials', re: /application_default_credentials\.json(?:$|[/?#\s'"])/ },
557
- { itemId: 'linux_shadow', label: 'Linux shadow file', re: /(?:^|\/)etc\/(?:shadow|sudoers)(?:$|[/?#\s'"])/ },
558
- { itemId: 'powershell_history', label: 'PowerShell history', re: /powershell\/psreadline\/consolehost_history\.txt(?:$|[/?#\s'"])/ },
559
- // Anchored to real browser-profile paths (Chromium: "User Data/<profile>/Network/Cookies",
560
- // "<profile>/Login Data"; Firefox: key4.db / logins.json / cookies.sqlite). Bare English
561
- // words like "cookies" in prose, code, or a "/cookies" web route must NOT match — the
562
- // unanchored version over-blocked ordinary web-dev work.
563
- { itemId: 'browser_credentials', label: 'browser credential store', re: /(?:^|\/)(?:(?:default|profile [0-9]+|network)\/cookies|login data|cookies\.sqlite|key4\.db|logins\.json)(?:$|[/?#\s'"])/ },
564
- ];
565
- for (const check of checks) {
566
- if (check.re.test(text))
567
- return { itemId: check.itemId, label: check.label };
568
- }
569
- if (/(?:^|\/)\.env(?:\.[a-z0-9_-]+)?(?:$|[/?#\s'"])/.test(text)) {
570
- // Traversal to a .env outside the workspace stays a hard block
571
- // (env_traversal); a plain workspace .env is a separate warn-by-default
572
- // item (env_workspace) — agents legitimately read it during development,
573
- // but the fleet should still see every touch.
574
- return traversal
575
- ? { itemId: 'env_traversal', label: 'environment file via path traversal' }
576
- : { itemId: 'env_workspace', label: 'workspace environment file' };
577
- }
578
- return undefined;
579
- }
580
- /**
581
- * Commands that PRINT stored credentials to stdout — the file-path rules are
582
- * useless against them because the secret never comes from a watched file
583
- * ("gh auth token" emits the same token that lives in hosts.yml). Obvious,
584
- * rarely-legitimate-for-agents forms are on by default; cloud token printers
585
- * that legitimate deploy tooling uses constantly are strict (off by default).
586
- */
587
- function credentialCommandReason(value) {
588
- return matchCommand(value, (_text, lower) => {
589
- if (/\bgh\s+auth\s+token\b/.test(lower) || (/\bgh\s+auth\s+status\b/.test(lower) && /(?:--show-token|\s-t\b)/.test(lower))) {
590
- return { itemId: 'gh_auth_token_cmd', reason: 'GitHub CLI token print (gh auth token)' };
591
- }
592
- if (/\bgit\s+credential(?:-manager|-store|-cache)?\s+(?:fill|get)\b/.test(lower)) {
593
- return { itemId: 'git_credential_fill', reason: 'git credential helper dump' };
594
- }
595
- if (/\bsecurity\s+(?:find-generic-password|find-internet-password)\b[^\n;|&]*\s-w\b/.test(lower) || /\bsecurity\s+dump-keychain\b/.test(lower)) {
596
- return { itemId: 'macos_keychain_dump', reason: 'macOS keychain password dump' };
597
- }
598
- if (/\bkubectl\s+config\s+view\b[^\n;|&]*--raw\b/.test(lower)) {
599
- return { itemId: 'kubectl_config_raw', reason: 'raw kubeconfig dump (kubectl config view --raw)' };
600
- }
601
- if (/\baws\s+configure\s+export-credentials\b/.test(lower) || /\baws\s+configure\s+get\b[^\n;|&]*secret/.test(lower)) {
602
- return { itemId: 'aws_export_credentials', reason: 'AWS secret access key export' };
603
- }
604
- if (/\bgcloud\s+auth\b[^\n;|&]*\bprint-access-token\b/.test(lower)) {
605
- return { itemId: 'gcloud_access_token_cmd', reason: 'gcloud access-token print' };
606
- }
607
- if (/\bgcloud\s+secrets\s+versions\s+access\b/.test(lower)) {
608
- return { itemId: 'gcloud_secret_access_cmd', reason: 'GCP Secret Manager read' };
609
- }
610
- if (/\baz\s+account\s+get-access-token\b/.test(lower)) {
611
- return { itemId: 'az_access_token_cmd', reason: 'Azure access-token print' };
612
- }
613
- if (/\baws\s+secretsmanager\s+get-secret-value\b/.test(lower) || /\baws\s+ssm\s+get-parameter\b[^\n;|&]*--with-decryption\b/.test(lower)) {
614
- return { itemId: 'aws_secret_fetch_cmd', reason: 'AWS secret fetch' };
615
- }
616
- if (/\bvault\s+(?:kv\s+get|read)\b/.test(lower)) {
617
- return { itemId: 'vault_read_cmd', reason: 'Vault secret read' };
618
- }
619
- return undefined;
620
- });
621
- }
622
- // Container-scoped execution context immediately before an `rm` hit: a
623
- // docker/podman/nerdctl/kubectl exec|run (incl. `compose exec/run`) earlier in
624
- // the SAME statement (no ; & | between). Inside that context a bare `rm -rf *`
625
- // wipes the CONTAINER's workdir — routine build/image cleanup on a
626
- // docker-heavy fleet — not the developer's machine, so it must never warn or
627
- // stall. Root targets (`/`, `/*`) stay blocked even inside containers (the
628
- // Patria case: an agent nuking a running container's filesystem).
629
- const CONTAINER_EXEC_BEFORE = /\b(?:docker|podman|nerdctl|kubectl)(?:\.exe)?\s+(?:compose\s+)?(?:exec|run)\b[^;&|]*$/i;
630
- function destructiveCommandReason(value) {
631
- return matchCommand(value, (text, lower) => {
632
- // Flag cluster is order-independent (`-rf`, `-fr`, `-rfv`). Terminators
633
- // include `)` so command substitution — `$(rm -rf /)` runs BEFORE the
634
- // outer command — is caught too. Path-aware: only the root `/`, the root
635
- // wildcard `/*`, and a bare `*` are treated as destructive — scoped paths
636
- // (`/tmp/...`, `/var/cache/...`, `./build`) are everyday cleanup.
637
- if (/\b(?:sudo\s+)?rm\s+-(?=[a-z]*r)(?=[a-z]*f)[a-z]+\s+["']?\/\*?["']?(?:\s|$|[;&|)])/.test(lower))
638
- return { itemId: 'rm_rf_root', reason: 'recursive force delete of filesystem root' };
639
- // Bare `*` deletes the current directory tree — destructive on the HOST,
640
- // but inside a container exec/run it is the container workdir (cleanup).
641
- const bareStar = /\b(?:sudo\s+)?rm\s+-(?=[a-z]*r)(?=[a-z]*f)[a-z]+\s+\*(?:\s|$|[;&|)])/.exec(lower);
642
- if (bareStar && !CONTAINER_EXEC_BEFORE.test(lower.slice(0, bareStar.index)))
643
- return { itemId: 'rm_rf_root', reason: 'recursive force delete of filesystem root' };
644
- // Windows recursive quiet drive delete via del/erase/rd/rmdir. Flag order
645
- // is independent (`/s /q` and `/q /s` both wipe), and the dequoted variant
646
- // handles `"C:\"`. rd/rmdir are the same wipe under a different verb — the
647
- // old rule only knew del/erase in a fixed flag order.
648
- if (/\b(?:del|erase|rd|rmdir)\b(?=[^\n;|&]*\s\/[a-z]*s\b)(?=[^\n;|&]*\s\/[a-z]*q\b)[^\n;|&]*\s[a-z]:(?:\\|"|\s|$)/i.test(text)) {
649
- return { itemId: 'windows_drive_delete', reason: 'recursive Windows drive delete' };
650
- }
651
- // Drive-ROOT Remove-Item only: the bare drive (C:\) must be an argument of
652
- // the SAME Remove-Item command (no ;|& between them). The previous loose
653
- // drive-letter match flagged ANY text containing Remove-Item -Recurse
654
- // -Force plus an unrelated "x: " pattern — e.g. our own installer's
655
- // legitimate cleanup script, blocking a customer's git command that merely
656
- // referenced it.
657
- if (lower.includes('remove-item') && lower.includes('-recurse') && lower.includes('-force')
658
- && /remove-item\b[^;|&]{0,80}?["']?\b[a-z]:[\\/]?["']?(?=\s|$|[;&|])/i.test(text)) {
659
- return { itemId: 'windows_drive_delete', reason: 'recursive Windows drive delete' };
660
- }
661
- if (/: *\(\) *\{ *: *\| *: *& *\} *; *:/.test(text))
662
- return { itemId: 'fork_bomb', reason: 'fork bomb' };
663
- if (/\bmkfs(?:\.[a-z0-9]+)?\s+\/dev\//i.test(text))
664
- return { itemId: 'mkfs_device', reason: 'filesystem format command' };
665
- if (/\bdd\b(?=.*\bof=\/dev\/(?:sd|xvd|hd|nvme|disk))/i.test(text))
666
- return { itemId: 'dd_disk_overwrite', reason: 'raw disk overwrite command' };
667
- if (/\bchmod\s+-r\s+777\s+\/(?:\s|$)/i.test(text))
668
- return { itemId: 'chmod_root_777', reason: 'recursive permission change on root' };
669
- if (/\bgit\s+(?:reset\s+--hard|clean\s+-f(?:d|x|dx)?\b)/i.test(text))
670
- return { itemId: 'git_clean_force', reason: 'destructive git clean/reset' };
671
- return undefined;
672
- });
673
- }
674
- function reverseShellReason(value) {
675
- return matchCommand(value, (text) => {
676
- if (/\bbash\s+-i\b.*\/dev\/tcp\//i.test(text))
677
- return { itemId: 'bash_dev_tcp', reason: 'bash reverse shell' };
678
- if (/\b(?:nc|ncat|netcat)\b.*\s-e\s+(?:\/bin\/)?(?:sh|bash)\b/i.test(text))
679
- return { itemId: 'netcat_exec', reason: 'netcat reverse shell' };
680
- if (/\bsocat\b.*\bexec:(?:\/bin\/)?(?:sh|bash)\b/i.test(text))
681
- return { itemId: 'socat_exec', reason: 'socat reverse shell' };
682
- if (/\b(?:curl|wget)\b[^|;&]{0,300}\|\s*(?:sudo\s+)?(?:sh|bash)\b/i.test(text))
683
- return { itemId: 'curl_pipe_shell', reason: 'remote script piped to shell' };
684
- // PowerShell download-and-execute cradle: Invoke-Expression / iex fed by a
685
- // downloader (iwr/irm/Invoke-WebRequest/Invoke-RestMethod/DownloadString/
686
- // DownloadFile/Net.WebClient/Start-BitsTransfer, or a bare `... | iex`).
687
- // This is the Windows equivalent of `curl … | sh`, so it rides the same
688
- // catalog toggle (curl_pipe_shell).
689
- if (/\b(?:iex|invoke-expression)\b/i.test(text)
690
- && /\b(?:iwr|irm|invoke-webrequest|invoke-restmethod|curl|wget|downloadstring|downloadfile|net\.webclient|start-bitstransfer)\b/i.test(text)) {
691
- return { itemId: 'curl_pipe_shell', reason: 'remote script downloaded and executed (PowerShell cradle)' };
692
- }
693
- if (/\|\s*(?:iex|invoke-expression)\b/i.test(text)) {
694
- return { itemId: 'curl_pipe_shell', reason: 'remote script piped to shell (PowerShell iex)' };
695
- }
696
- if (/\bpython(?:3)?\s+-c\b(?=.*socket)(?=.*subprocess)/i.test(text))
697
- return { itemId: 'python_socket_subprocess', reason: 'python reverse shell' };
698
- return undefined;
699
- });
700
- }
701
- function destructiveSqlReason(value) {
702
- return matchCommand(value, (text) => {
703
- if (/\bdrop\s+database\b/i.test(text))
704
- return { itemId: 'drop_database', reason: 'DROP DATABASE' };
705
- if (/\bdrop\s+schema\b/i.test(text))
706
- return { itemId: 'drop_schema', reason: 'DROP SCHEMA' };
707
- if (/\btruncate\s+table\b/i.test(text))
708
- return { itemId: 'truncate_table', reason: 'TRUNCATE TABLE' };
709
- return undefined;
710
- });
711
- }
712
- function infraDestroyReason(value) {
713
- return matchCommand(value, (text) => {
714
- if (/\bterraform\s+destroy\b(?=.*-{1,2}auto-approve)/i.test(text))
715
- return { itemId: 'terraform_destroy_auto', reason: 'terraform destroy with auto-approve' };
716
- if (/\bpulumi\s+destroy\b(?=.*(?:--yes|-y))/i.test(text))
717
- return { itemId: 'pulumi_destroy_yes', reason: 'pulumi destroy with auto-approve' };
718
- // Specific kubectl deletes first (default-on), then the broad catch-all
719
- // (generic_kubectl_delete, default-OFF). The generic rule now matches any
720
- // `kubectl delete` as its catalog description advertises — previously it
721
- // only fired on clusterrole|secret, silently under-delivering the toggle.
722
- if (/\bkubectl\s+delete\s+namespace\b/i.test(text))
723
- return { itemId: 'kubectl_delete_namespace', reason: 'destructive kubectl namespace delete' };
724
- if (/\bkubectl\s+delete\s+all\b(?=.*--all)/i.test(text))
725
- return { itemId: 'kubectl_delete_all_all', reason: 'broad kubectl delete all' };
726
- if (/\bkubectl\s+delete\b/i.test(text))
727
- return { itemId: 'generic_kubectl_delete', reason: 'destructive kubectl delete' };
728
- if (/\bgcloud\s+projects\s+delete\b/i.test(text))
729
- return { itemId: 'gcloud_project_delete', reason: 'GCP project deletion' };
730
- if (/\bgcloud\s+sql\s+instances\s+delete\b/i.test(text))
731
- return { itemId: 'gcloud_sql_delete', reason: 'GCP SQL instance deletion' };
732
- if (/\baws\s+s3\s+rm\s+s3:\/\/\S+\s+--recursive\b/i.test(text))
733
- return { itemId: 'aws_s3_recursive_rm', reason: 'recursive S3 deletion' };
734
- if (/\baws\s+cloudformation\s+delete-stack\b/i.test(text))
735
- return { itemId: 'aws_cloudformation_delete_stack', reason: 'CloudFormation stack deletion' };
736
- if (/\baws\s+iam\s+attach-user-policy\b(?=.*AdministratorAccess)/i.test(text))
737
- return { itemId: 'aws_iam_admin_policy', reason: 'IAM administrator privilege grant' };
738
- if (/\baws\s+iam\s+create-access-key\b/i.test(text))
739
- return { itemId: 'aws_iam_access_key', reason: 'IAM access key creation' };
740
- if (/\baz\s+group\s+delete\b(?=.*(?:--yes|-y))/i.test(text))
741
- return { itemId: 'az_group_delete_yes', reason: 'Azure resource group deletion' };
742
- return undefined;
743
- });
744
- }
745
- /**
746
- * Local file editors (Write / StrReplace / edit_file / EditNotebook / apply_patch ...)
747
- * write to DISK — that is not egress. Their contents/new_string arguments legitimately
748
- * carry secret-shaped fixtures (test suites, docs, security tooling source), and the
749
- * `content(s)` key name otherwise matches the outbound-payload heuristic, which blocked
750
- * editing our own guard test files. Real exfiltration is still caught at the actual
751
- * egress point (outbound/HTTP tools, shell commands), where secret rules apply unchanged.
752
- */
753
- function isLocalFileEditor(toolName, candidates) {
754
- if (!/(?:write|edit|replace|patch|notebook|create)/i.test(toolName))
755
- return false;
756
- return candidates.some(candidate => {
757
- const lastKey = (candidate.keyPath.split('.').pop() || '').toLowerCase();
758
- return ['path', 'file', 'filename', 'file_path', 'filepath', 'target_file', 'target_notebook'].includes(lastKey);
759
- });
760
- }
761
- function isOutboundContext(toolName, candidates) {
762
- if (OUTBOUND_TOOL_HINT.test(toolName))
763
- return true;
764
- if (isLocalFileEditor(toolName, candidates))
765
- return false;
766
- return candidates.some(candidate => /(?:url|uri|webhook|endpoint|recipient|channel|email|to|body|payload|message|content)/i.test(candidate.keyPath));
767
- }
768
- function isCommandContext(toolName, candidate) {
769
- const lastKey = candidate.keyPath.split('.').pop() || '';
770
- return COMMAND_TOOL_HINT.test(toolName) || COMMAND_KEYS.has(lastKey) || COMMAND_KEYS.has(candidate.keyPath);
771
- }
772
- function isSqlContext(toolName, candidate) {
773
- const lastKey = candidate.keyPath.split('.').pop() || '';
774
- return SQL_TOOL_HINT.test(toolName) || SQL_KEYS.has(lastKey) || SQL_KEYS.has(candidate.keyPath);
775
- }
776
- /**
777
- * Metadata SSRF only matters where the string can actually BECOME a request: a shell
778
- * command, an outbound/HTTP tool, or a URL-typed argument. Source code or file contents
779
- * that merely MENTION the endpoint (e.g. editing a file that implements an SSRF guard)
780
- * must not block — the unconditional match over-blocked ordinary development work.
781
- */
782
- function isMetadataRequestContext(toolName, candidate) {
783
- if (isCommandContext(toolName, candidate))
784
- return true;
785
- if (OUTBOUND_TOOL_HINT.test(toolName))
786
- return true;
787
- const lastKey = candidate.keyPath.split('.').pop() || '';
788
- return /(?:url|uri|endpoint|host|address|webhook)/i.test(lastKey);
789
- }
790
- /**
791
- * Sensitive credential PATHS only matter where the string is used AS a path (a file access,
792
- * a path-typed argument) or inside a command. File CONTENTS being written/edited routinely
793
- * mention such paths legitimately (security tooling source, tests, docs) and must not block.
794
- */
795
- function isSensitivePathContext(toolName, candidate) {
796
- if (isCommandContext(toolName, candidate))
797
- return true;
798
- if (/(?:read|open|cat|copy|download|upload|access|stat|list|glob|search|find|grep)/i.test(toolName))
799
- return true;
800
- const lastKey = candidate.keyPath.split('.').pop() || '';
801
- return /(?:path|file|filename|dir|directory|target|source|src|dest|location|glob|pattern|uri|url)/i.test(lastKey);
802
- }
803
- // ---- execution view: message/document DATA inside a command is inert ---------
804
- // Industry-standard model (Sigma / EDR command-line parsing): detection matches
805
- // what EXECUTES — the command word and its argv — never free text riding inside
806
- // a data argument. Quoted spans containing whitespace are prose (commit
807
- // messages, issue/PR bodies, file contents via Set-Content/-Value, docs) and
808
- // are inert BY DEFAULT; code positions are the enumerated exception. This
809
- // inverts the old text-sink flag allowlist (-m/--body/-Value…), which lost
810
- // every time a new data flag appeared — code sinks are a small stable set,
811
- // data flags are infinite.
812
- //
813
- // Safety invariants (false-negative guards):
814
- // 1. NOTHING is stripped when the text can feed an interpreter (| sh, iex,
815
- // eval, xargs, base64 -d, -EncodedCommand, FromBase64String) or invoke an
816
- // interpreter code flag (bash -c, python -c) or a remote/nested executor
817
- // (ssh, wsl, chroot, docker|kubectl|podman exec/run). A whole-line bailout
818
- // is always FN-safe and also defeats quote-splitting obfuscation
819
- // (`wsl -e bash -c ""r""m"…`) that per-span reasoning cannot survive.
820
- // 2. A double-quoted span containing $( … ) or real backtick command
821
- // substitution is kept — substitution executes BEFORE the outer command.
822
- // A single-char backtick pair (`n, `t) is a PowerShell ESCAPE, not code.
823
- // 3. Single-token quoted spans (rm -rf "/") are argv, not prose — kept.
824
- // 4. Quoted spans in a CODE POSITION (interpreter -c/-Command/-e flags, or a
825
- // remote executor earlier in the same statement) are kept.
826
- // 5. Secret-literal rules and honeypot/custom rules never use this view —
827
- // a token pasted into a commit message still leaks.
828
- const DATA_TO_INTERPRETER = /\b(?:iex|invoke-expression|invoke-command)\b|\beval\b|\bxargs\b|\bbase64\b[^\n]*(?:-d\b|--decode\b)|frombase64string|-encodedcommand\b|\s-enc\s|\|\s*&?\s*(?:sh|bash|zsh|dash|ksh|csh|pwsh|powershell(?:\.exe)?|cmd(?:\.exe)?|node|python[0-9.]*|perl|ruby)\b|\b(?:sh|bash|zsh|dash|ksh|csh|pwsh|powershell(?:\.exe)?|cmd(?:\.exe)?|node|python[0-9.]*|perl|ruby)\s+(?:-c|\/c|-e|-command|-scriptblock)\b|\b(?:ssh|wsl(?:\.exe)?|chroot)\b|\b(?:docker|kubectl|podman|nerdctl)(?:\.exe)?\s+(?:exec|run)\b/i;
829
- // $( … ) always executes; backtick pairs only with ≥2 chars of content
830
- // (PowerShell escapes like `n / `t are single-char and inert).
831
- const INTERPOLATES = /\$\(|`[^`]{2,}`/;
832
- const INERT_DATA = ' fcd_inert_data ';
833
- // Code position immediately before a quoted span: interpreter code flags or a
834
- // remote/nested executor earlier in the same statement (no ; & | between).
835
- const CODE_CONTEXT_BEFORE = /(?:(?:^|[;&|(]|\s)(?:-c|\/c|-e|-command|-scriptblock|-filter)[= ]\s*|(?:^|[;&|(]\s*)(?:\S*[\\/])?(?:sudo\s+|doas\s+)?(?:ssh|wsl(?:\.exe)?|chroot|su|screen|tmux)(?:\s[^;&|"']*)?\s|(?:\S*[\\/])?(?:docker|kubectl|podman|nerdctl)(?:\.exe)?\s+(?:exec|run)\b[^;&|"']*\s)$/i;
836
- function stripInertDataSegments(text) {
837
- if (DATA_TO_INTERPRETER.test(text))
838
- return text;
839
- let out = text;
840
- // PowerShell here-strings: @'…'@ is fully literal; @"…"@ interpolates $( ).
841
- out = out.replace(/@'[\s\S]*?'@/g, INERT_DATA);
842
- out = out.replace(/@"[\s\S]*?"@/g, m => (m.includes('$(') ? m : INERT_DATA));
843
- // POSIX heredocs: quoted delimiter (<<'EOF') is literal; unquoted interpolates.
844
- out = out.replace(/<<-?\s*'(\w+)'[\s\S]*?(?:\n\1\b|$)/g, INERT_DATA);
845
- out = out.replace(/<<-?\s*"?(\w+)"?[\s\S]*?(?:\n\1\b|$)/g, m => (INTERPOLATES.test(m) ? m : INERT_DATA));
846
- // Generic quoted-span pass: whitespace inside quotes ⇒ free text ⇒ inert,
847
- // unless the span sits in a code position (invariants 2–4 above).
848
- const src = out;
849
- out = src.replace(/"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'/g, (whole, dq, sq, offset) => {
850
- const body = dq !== undefined ? dq : (sq || '');
851
- if (!/\s/.test(body))
852
- return whole; // single token: argv, not prose
853
- const before = src.slice(Math.max(0, offset - 80), offset);
854
- if (CODE_CONTEXT_BEFORE.test(before))
855
- return whole; // code position: executes
856
- if (dq !== undefined && INTERPOLATES.test(body))
857
- return whole; // $( )/`cmd` executes first
858
- return INERT_DATA;
859
- });
860
- return out;
861
- }
862
- function scanTextValue(toolName, rawValue, options) {
863
- // Honeypot decoys and org custom patterns scan the RAW value: a decoy path
864
- // even inside message data is exfiltration staging, and custom rules define
865
- // their own scope.
866
- const honeypot = honeypotTouch(rawValue, options);
867
- if (honeypot)
868
- return honeypot;
869
- const custom = customBlock(rawValue, options);
870
- if (custom)
871
- return custom;
872
- // Every rule below asks "can this text ACT?" — so it sees the execution
873
- // view: quoted message/document data (commit -m, issue --body, here-strings,
874
- // heredocs) is inert unless it can flow into an interpreter (see
875
- // stripInertDataSegments invariants). This is the generic FP guard for
876
- // "wrote ABOUT a dangerous command" vs "ran one".
877
- const value = stripInertDataSegments(rawValue);
878
- // NOTE: a disabled item must FALL THROUGH to the later rules, not end the
879
- // scan — otherwise turning off (or gating) a path rule would mask a real
880
- // reverse shell / destructive command in the same value.
881
- const sensitivePath = containsSensitiveCredentialPath(value);
882
- if (sensitivePath) {
883
- const finding = builtIn(sensitivePath.itemId, 'sensitive_files', 'sensitive_file', 'local-sensitive-credential-path', `Blocked local agent access to ${sensitivePath.label}.`, value, sensitivePath.label, options);
884
- if (finding)
885
- return finding;
886
- }
887
- const metadata = containsMetadataEndpoint(value);
888
- if (metadata) {
889
- const finding = builtIn(metadata.itemId, 'metadata_ssrf', 'metadata_ssrf', 'local-cloud-metadata-ssrf', `Blocked request to ${metadata.label}.`, value, metadata.value, options);
890
- if (finding)
891
- return finding;
892
- }
893
- const reverseShell = reverseShellReason(value);
894
- if (reverseShell) {
895
- return builtIn(reverseShell.itemId, 'reverse_shells', 'reverse_shell', 'local-reverse-shell', `Blocked ${reverseShell.reason}.`, value, reverseShell.reason, options);
896
- }
897
- const credentialCmd = credentialCommandReason(value);
898
- if (credentialCmd) {
899
- const finding = builtIn(credentialCmd.itemId, 'credential_commands', 'credential_command', 'local-credential-command', `Blocked credential-revealing command: ${credentialCmd.reason}.`, value, credentialCmd.reason, options);
900
- if (finding)
901
- return finding;
902
- }
903
- const destructive = destructiveCommandReason(value);
904
- if (destructive) {
905
- return builtIn(destructive.itemId, 'destructive_filesystem', 'destructive_command', 'local-destructive-command', `Blocked ${destructive.reason}.`, value, destructive.reason, options);
906
- }
907
- const infraDestroy = infraDestroyReason(value);
908
- if (infraDestroy) {
909
- return builtIn(infraDestroy.itemId, 'infra_destroy', 'infra_destroy', 'local-infra-destroy', `Blocked ${infraDestroy.reason}.`, value, infraDestroy.reason, options);
910
- }
911
- const destructiveSql = destructiveSqlReason(value);
912
- if (destructiveSql) {
913
- return builtIn(destructiveSql.itemId, 'destructive_sql', 'destructive_sql', 'local-destructive-sql', `Blocked destructive SQL command: ${destructiveSql.reason}.`, value, destructiveSql.reason, options);
914
- }
915
- return undefined;
916
- }
917
- /**
918
- * A string can only DO something in an actionable context: a shell command, an outbound
919
- * request, or a path/target argument. File CONTENTS being written or edited are inert —
920
- * mentioning a blocked path/endpoint/pattern in source code, tests, or docs is normal
921
- * development work and must never block (see isMetadataRequestContext / isSensitivePathContext).
922
- */
923
- function isActionableContext(toolName, candidate) {
924
- return isCommandContext(toolName, candidate)
925
- || isSensitivePathContext(toolName, candidate)
926
- || OUTBOUND_TOOL_HINT.test(toolName);
927
- }
928
- function scanDeterministicToolCall(toolName, toolArgs, options) {
929
- const candidates = collectStrings(toolArgs);
930
- const outbound = isOutboundContext(toolName, candidates);
931
- for (const candidate of candidates) {
932
- // Custom rules ("block AI agents from touching this path/pattern") follow the same
933
- // context principle as built-ins: enforce on access/execution/egress, not on editing
934
- // file contents that merely mention the pattern.
935
- if (!isActionableContext(toolName, candidate))
936
- continue;
937
- const custom = customBlock(candidate.value, options);
938
- if (custom)
939
- return custom;
940
- }
941
- for (const candidate of candidates) {
942
- const finding = scanTextValue(toolName, candidate.value, options);
943
- if (!finding)
944
- continue;
945
- // Context gates: a pattern is only dangerous where it can act — a command, a request
946
- // target, or a path being accessed. A bare mention inside file contents / source code
947
- // being written (e.g. editing security tooling or its tests) must not block.
948
- if (finding.category === 'metadata_ssrf' && !isMetadataRequestContext(toolName, candidate))
949
- continue;
950
- if (finding.category === 'sensitive_file' && !isSensitivePathContext(toolName, candidate))
951
- continue;
952
- // Honeypot decoy paths block in ANY context where the string can act —
953
- // path access, command execution, or outbound egress (a decoy path inside
954
- // a request body is exfiltration staging). Inert file-content mentions
955
- // still pass, consistent with the other path rules.
956
- if (finding.category === 'honeypot' && !(isActionableContext(toolName, candidate) || outbound))
957
- continue;
958
- if (isCommandContext(toolName, candidate) || finding.category === 'sensitive_file' || finding.category === 'metadata_ssrf' || finding.category === 'honeypot')
959
- return finding;
960
- }
961
- for (const candidate of candidates) {
962
- if (!isSqlContext(toolName, candidate))
963
- continue;
964
- const destructiveSql = destructiveSqlReason(candidate.value);
965
- if (destructiveSql) {
966
- return builtIn(destructiveSql.itemId, 'destructive_sql', 'destructive_sql', 'local-destructive-sql', `Blocked destructive SQL command: ${destructiveSql.reason}.`, candidate.value, destructiveSql.reason, options);
967
- }
968
- }
969
- if (outbound) {
970
- for (const candidate of candidates) {
971
- const secret = findSecret(candidate.value)
972
- || contextualSecretFromKeyPath(candidate.keyPath, candidate.value)
973
- || findContextualSecret(candidate.value);
974
- if (secret) {
975
- const finding = builtIn(secret.itemId, 'secret_exfiltration', 'secret_exfiltration', 'local-secret-exfiltration', `Blocked outbound data containing ${secret.label}.`, secret.value, secret.label, options);
976
- return finding ? { ...finding, matchedSecret: secret.value } : undefined;
977
- }
978
- }
979
- }
980
- if (options?.inspectScripts && toolArgs.command && typeof toolArgs.command === 'string') {
981
- const scriptFinding = scanReferencedScript(toolArgs.command, typeof toolArgs.cwd === 'string' ? toolArgs.cwd : options.cwd, options);
982
- if (scriptFinding)
983
- return scriptFinding;
984
- }
985
- return undefined;
986
- }
987
- function scanDeterministicTextResponse(text, options) {
988
- const secret = findSecret(text) || findContextualSecret(text);
989
- if (!secret)
990
- return undefined;
991
- const finding = builtIn(secret.itemId, 'secret_exfiltration', 'secret_exfiltration', 'local-secret-in-tool-response', `Blocked tool response containing ${secret.label}.`, secret.value, secret.label, options);
992
- return finding ? { ...finding, matchedSecret: secret.value } : undefined;
993
- }
994
- function looksLikeQuestion(value) {
995
- return /^(?:what|why|how|explain|describe|is|are|can you explain)\b/i.test(value.trim());
996
- }
997
- function bareOrActionIntent(value, action) {
998
- const trimmed = value.trim();
999
- if (looksLikeQuestion(trimmed))
1000
- return false;
1001
- return action.test(trimmed) || /^[^\n]{1,240}$/.test(trimmed);
1002
- }
1003
- function scanDeterministicPrompt(text, options) {
1004
- const trimmed = text.trim();
1005
- if (!trimmed)
1006
- return undefined;
1007
- const custom = customBlock(trimmed, options);
1008
- if (custom)
1009
- return custom;
1010
- const secret = findSecret(trimmed);
1011
- if (secret && OUTBOUND_TOOL_HINT.test(trimmed)) {
1012
- return builtIn(secret.itemId, 'secret_exfiltration', 'secret_exfiltration', 'local-prompt-secret-exfiltration', `Blocked prompt asking to send ${secret.label}.`, secret.value, secret.label, options);
1013
- }
1014
- // Pasting a credential next to "secret"/"password"/"api key" wording blocks
1015
- // even without send intent — once it is in the agent context it can leak
1016
- // through any later tool call. Known-prefix secrets without such wording
1017
- // keep the outbound-intent requirement above (devs paste keys to debug).
1018
- const contextualSecret = findContextualSecret(trimmed);
1019
- if (contextualSecret) {
1020
- return builtIn(contextualSecret.itemId, 'secret_exfiltration', 'secret_exfiltration', 'local-prompt-contextual-secret', `Blocked prompt containing ${contextualSecret.label}.`, contextualSecret.value, contextualSecret.label, options);
1021
- }
1022
- // Questions are benign for action-oriented rules below, but this check must
1023
- // happen AFTER secret detection: "is this my API secret: <value>?" still
1024
- // leaks a credential into agent context.
1025
- if (looksLikeQuestion(trimmed))
1026
- return undefined;
1027
- const sensitivePath = containsSensitiveCredentialPath(trimmed);
1028
- if (sensitivePath && bareOrActionIntent(trimmed, /\b(?:read|open|cat|show|print|copy|upload|send|exfiltrate)\b/i)) {
1029
- return builtIn(sensitivePath.itemId, 'sensitive_files', 'sensitive_file', 'local-prompt-sensitive-credential-path', `Blocked prompt targeting ${sensitivePath.label}.`, trimmed, sensitivePath.label, options);
1030
- }
1031
- if (bareOrActionIntent(trimmed, /\b(?:run|execute|launch|start)\b/i)) {
1032
- const reverseShell = reverseShellReason(trimmed);
1033
- if (reverseShell) {
1034
- return builtIn(reverseShell.itemId, 'reverse_shells', 'reverse_shell', 'local-prompt-reverse-shell', `Blocked prompt containing ${reverseShell.reason}.`, trimmed, reverseShell.reason, options);
1035
- }
1036
- const credentialCmd = credentialCommandReason(trimmed);
1037
- if (credentialCmd) {
1038
- const finding = builtIn(credentialCmd.itemId, 'credential_commands', 'credential_command', 'local-prompt-credential-command', `Blocked prompt containing ${credentialCmd.reason}.`, trimmed, credentialCmd.reason, options);
1039
- if (finding)
1040
- return finding;
1041
- }
1042
- const destructive = destructiveCommandReason(trimmed);
1043
- if (destructive) {
1044
- return builtIn(destructive.itemId, 'destructive_filesystem', 'destructive_command', 'local-prompt-destructive-command', `Blocked prompt containing ${destructive.reason}.`, trimmed, destructive.reason, options);
1045
- }
1046
- const infraDestroy = infraDestroyReason(trimmed);
1047
- if (infraDestroy) {
1048
- return builtIn(infraDestroy.itemId, 'infra_destroy', 'infra_destroy', 'local-prompt-infra-destroy', `Blocked prompt containing ${infraDestroy.reason}.`, trimmed, infraDestroy.reason, options);
1049
- }
1050
- }
1051
- const destructiveSql = destructiveSqlReason(trimmed);
1052
- if (destructiveSql && bareOrActionIntent(trimmed, /\b(?:run|execute|query|apply)\b/i)) {
1053
- return builtIn(destructiveSql.itemId, 'destructive_sql', 'destructive_sql', 'local-prompt-destructive-sql', `Blocked prompt containing destructive SQL command: ${destructiveSql.reason}.`, trimmed, destructiveSql.reason, options);
1054
- }
1055
- const metadata = containsMetadataEndpoint(trimmed);
1056
- if (metadata && /\b(?:fetch|request|curl|open|connect|call)\b/i.test(trimmed)) {
1057
- return builtIn(metadata.itemId, 'metadata_ssrf', 'metadata_ssrf', 'local-prompt-cloud-metadata-ssrf', `Blocked prompt targeting ${metadata.label}.`, trimmed, metadata.value, options);
1058
- }
1059
- return undefined;
1060
- }
1061
- function splitCommand(command) {
1062
- return command.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g)?.map(part => part.replace(/^["']|["']$/g, '')) || [];
1063
- }
1064
- function safeResolveScriptPath(candidate, cwd) {
1065
- if (!candidate || /^https?:\/\//i.test(candidate))
1066
- return undefined;
1067
- const base = cwd || process.cwd();
1068
- const resolved = path.resolve(base, candidate);
1069
- const root = path.resolve(base);
1070
- if (!resolved.toLowerCase().startsWith(root.toLowerCase()))
1071
- return undefined;
1072
- const ext = path.extname(resolved).toLowerCase();
1073
- if (!['.sh', '.bash', '.zsh', '.ps1', '.bat', '.cmd', '.py', '.js', '.mjs', '.cjs'].includes(ext))
1074
- return undefined;
1075
- return resolved;
1076
- }
1077
- function referencedScripts(command, cwd) {
1078
- const tokens = splitCommand(command);
1079
- const scripts = [];
1080
- const runners = new Set(['bash', 'sh', 'zsh', 'python', 'python3', 'node', 'pwsh']);
1081
- // Wrappers that still EXECUTE the script that follows them ("sudo ./x.sh").
1082
- const execPrefixes = new Set(['sudo', 'time', 'nohup', 'exec', 'call', 'source', '.']);
1083
- const startsNewCommand = (prev) => prev === undefined || /[;&|]$/.test(prev) || execPrefixes.has(path.basename(prev).toLowerCase());
1084
- for (let i = 0; i < tokens.length; i++) {
1085
- const token = path.basename(tokens[i]).toLowerCase();
1086
- if (runners.has(token)) {
1087
- const next = tokens.slice(i + 1).find(part => part && !part.startsWith('-'));
1088
- const resolved = next ? safeResolveScriptPath(next, cwd) : undefined;
1089
- if (resolved)
1090
- scripts.push(resolved);
1091
- }
1092
- if ((token === 'powershell' || token === 'powershell.exe') && tokens[i + 1]?.toLowerCase() === '-file') {
1093
- const resolved = safeResolveScriptPath(tokens[i + 2], cwd);
1094
- if (resolved)
1095
- scripts.push(resolved);
1096
- }
1097
- // A bare script path only EXECUTES when it is the command word itself
1098
- // ("./deploy.sh --prod", "sudo ./x.sh", "a.sh && b.sh"). A script path that
1099
- // is an ARGUMENT of another command ("git add guard.test.js",
1100
- // "code scripts/x.py") is inert — content-scanning those blocked ordinary
1101
- // version-control and editor commands on our own test fixtures.
1102
- if (startsNewCommand(tokens[i - 1])) {
1103
- const direct = safeResolveScriptPath(tokens[i], cwd);
1104
- if (direct)
1105
- scripts.push(direct);
1106
- }
1107
- }
1108
- if (tokens[0]?.toLowerCase() === 'npm' && tokens[1]?.toLowerCase() === 'run' && tokens[2]) {
1109
- const pkg = path.resolve(cwd || process.cwd(), 'package.json');
1110
- try {
1111
- const stat = fs.statSync(pkg);
1112
- if (stat.size <= 200_000) {
1113
- const parsed = JSON.parse(fs.readFileSync(pkg, 'utf8'));
1114
- const script = parsed?.scripts?.[tokens[2]];
1115
- if (typeof script === 'string')
1116
- scripts.push(`npm:${tokens[2]}:${script}`);
1117
- }
1118
- }
1119
- catch { /* ignore */ }
1120
- }
1121
- return Array.from(new Set(scripts));
1122
- }
1123
- /**
1124
- * Verbs that make a sensitive path / metadata endpoint on a script line ACTIONABLE:
1125
- * reading, copying, uploading, or requesting it. A mere string mention (test fixture,
1126
- * detector regex, doc comment) has none of these on the same line.
1127
- */
1128
- // Collision-hardened forms: `ssh` must be a command start (NOT the `.ssh` of the
1129
- // flagged path itself), `type` the cmd.exe read form (`type file`, not `type:` in
1130
- // JSON/TS fixtures), `open` a call (`open(`), `requests.*` a python HTTP call.
1131
- const SCRIPT_ACCESS_VERB = /\b(?:cat|gc|get-content|get-item|copy(?:-item)?|cp|xcopy|robocopy|move(?:-item)?|mv|scp|sftp|rsync|curl|wget|invoke-webrequest|invoke-restmethod|iwr|irm|openssl|tar|zip|7z|certutil|base64|readfile(?:sync)?|createreadstream|read_text|read_bytes|fopen|urlopen|fetch|upload|download)\b|\btype\s+\S|(?:^|[^.\w])ssh(?:-add|-keygen|\.exe)?\s|\bopen\s*\(|\brequests\.\w+\s*\(/i;
1132
- /**
1133
- * A path/metadata finding inside a referenced script only counts when some LINE both
1134
- * contains the flagged pattern AND acts on it. Scripts (and their tests, and security
1135
- * tooling) routinely mention credential paths as inert strings — "found inside
1136
- * referenced script" used to block running our own guard test suite over fixtures.
1137
- */
1138
- function scriptActsOnFinding(content, category) {
1139
- const matcher = category === 'sensitive_file'
1140
- ? (line) => Boolean(containsSensitiveCredentialPath(line))
1141
- : (line) => Boolean(containsMetadataEndpoint(line));
1142
- for (const rawLine of content.split(/\r?\n/)) {
1143
- if (!rawLine || rawLine.length > 4000)
1144
- continue;
1145
- if (matcher(rawLine) && SCRIPT_ACCESS_VERB.test(rawLine))
1146
- return true;
1147
- }
1148
- return false;
1149
- }
1150
- /** Org-trusted script paths (from the Local Safety snapshot): skip content scanning. */
1151
- function isTrustedScriptPath(script, options) {
1152
- const trusted = options?.trustedScriptPaths;
1153
- if (!trusted || trusted.length === 0)
1154
- return false;
1155
- const normalized = normalizeForPath(script);
1156
- return trusted.some(entry => {
1157
- const pattern = normalizeForPath(String(entry || '')).replace(/\/+$/, '');
1158
- return pattern.length >= 3 && normalized.includes(pattern);
1159
- });
1160
- }
1161
- function scanReferencedScript(command, cwd, options) {
1162
- for (const script of referencedScripts(command, cwd)) {
1163
- if (isTrustedScriptPath(script, options))
1164
- continue;
1165
- let content = '';
1166
- if (script.startsWith('npm:')) {
1167
- content = script;
1168
- }
1169
- else {
1170
- try {
1171
- const stat = fs.statSync(script);
1172
- if (!stat.isFile() || stat.size > 250_000)
1173
- continue;
1174
- content = fs.readFileSync(script, 'utf8');
1175
- }
1176
- catch {
1177
- continue;
1178
- }
1179
- }
1180
- // Path/metadata findings must be ACTIONABLE inside the script; suppress inert
1181
- // string mentions and rescan so command-shaped rules (reverse shell, destructive
1182
- // delete...) in the SAME file still surface.
1183
- let scanOptions = options;
1184
- let finding = scanTextValue('script_file', content, scanOptions);
1185
- while (finding
1186
- && (finding.category === 'sensitive_file' || finding.category === 'metadata_ssrf')
1187
- && !scriptActsOnFinding(content, finding.category)) {
1188
- const baseDisabled = scanOptions?.disabledBuiltInItemIds || Array.from(DEFAULT_DISABLED_BUILT_INS);
1189
- scanOptions = { ...(scanOptions || {}), disabledBuiltInItemIds: [...baseDisabled, finding.itemId] };
1190
- finding = scanTextValue('script_file', content, scanOptions);
1191
- }
1192
- if (!finding)
1193
- continue;
1194
- return {
1195
- ...finding,
1196
- evidence: evidence(`${script}: ${finding.evidence}`),
1197
- reason: `${finding.reason} Found inside referenced script ${script.startsWith('npm:') ? script.split(':').slice(0, 2).join(':') : path.basename(script)}.`,
1198
- };
1199
- }
1200
- return undefined;
1201
- }
1202
- const MAX_ACTION_PASSES = 10;
1203
- function withRuleSuppressed(options, finding) {
1204
- if (finding.source === 'custom') {
1205
- return {
1206
- ...(options || {}),
1207
- customBlocks: (options?.customBlocks || []).filter(block => block.id !== finding.itemId),
1208
- };
1209
- }
1210
- const baseDisabled = options?.disabledBuiltInItemIds || Array.from(DEFAULT_DISABLED_BUILT_INS);
1211
- return { ...(options || {}), disabledBuiltInItemIds: [...baseDisabled, finding.itemId] };
1212
- }
1213
- function findingAction(finding) {
1214
- return finding.action === 'warn' || finding.action === 'mask' ? finding.action : 'block';
1215
- }
1216
- /**
1217
- * Resolve a scan under per-rule actions WITHOUT letting a warn rule shadow a
1218
- * block rule. Scans return the FIRST match, so a single pass would let one
1219
- * warn-mode rule hide a second, block-mode rule matching the same value. This
1220
- * re-scans with each warn rule suppressed until a blocking finding surfaces or
1221
- * nothing matches. Default (no itemActions configured) is a single pass
1222
- * returning today's behavior exactly.
1223
- *
1224
- * 'mask' degrades to block here: these surfaces (tool calls, prompts, shell
1225
- * commands) cannot rewrite content, so mask can only fail strict.
1226
- */
1227
- function resolveDeterministicOutcome(scan, options) {
1228
- const warnings = [];
1229
- let current = options;
1230
- for (let pass = 0; pass < MAX_ACTION_PASSES; pass++) {
1231
- const finding = scan(current);
1232
- if (!finding)
1233
- return { warnings };
1234
- if (findingAction(finding) !== 'warn')
1235
- return { blockingFinding: finding, warnings };
1236
- warnings.push(finding);
1237
- current = withRuleSuppressed(current, finding);
1238
- }
1239
- // Pass budget exhausted with matches still appearing — fail strict.
1240
- const last = scan(current);
1241
- return last ? { blockingFinding: last, warnings } : { warnings };
1242
- }
1243
- /**
1244
- * Resolve a TOOL RESPONSE under per-rule actions. The response is the one
1245
- * surface that can be rewritten, so 'mask' redacts here: each masked secret is
1246
- * replaced in the text and the REDACTED text is rescanned — a second secret of
1247
- * the same type is still found (rule suppression would hide it). Warn rules
1248
- * are suppressed as in resolveDeterministicOutcome. Any 'block' rule match
1249
- * blocks regardless of what was masked before it.
1250
- */
1251
- function resolveDeterministicTextResponse(text, options) {
1252
- const warnings = [];
1253
- const maskFindings = [];
1254
- let currentOptions = options;
1255
- let currentText = text;
1256
- for (let pass = 0; pass < MAX_ACTION_PASSES; pass++) {
1257
- const finding = scanDeterministicTextResponse(currentText, currentOptions);
1258
- if (!finding)
1259
- return { warnings, maskFindings, maskedText: currentText };
1260
- const action = findingAction(finding);
1261
- if (action === 'block')
1262
- return { blockingFinding: finding, warnings, maskFindings, maskedText: currentText };
1263
- if (action === 'mask') {
1264
- if (!finding.matchedSecret || !currentText.includes(finding.matchedSecret)) {
1265
- // Nothing concrete to redact — mask degrades to block, never to allow.
1266
- return { blockingFinding: finding, warnings, maskFindings, maskedText: currentText };
1267
- }
1268
- maskFindings.push(finding);
1269
- currentText = currentText.split(finding.matchedSecret).join(`[REDACTED:${finding.itemId}]`);
1270
- }
1271
- else {
1272
- warnings.push(finding);
1273
- currentOptions = withRuleSuppressed(currentOptions, finding);
1274
- }
1275
- }
1276
- // Pass budget exhausted with matches still appearing — fail strict.
1277
- const last = scanDeterministicTextResponse(currentText, currentOptions);
1278
- return last
1279
- ? { blockingFinding: last, warnings, maskFindings, maskedText: currentText }
1280
- : { warnings, maskFindings, maskedText: currentText };
1281
- }