@causyne/agent 1.20.120 → 1.20.122

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 (276) hide show
  1. package/README.md +3 -3
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +81 -26
  4. package/src/acp/agentCatalog.ts +73 -29
  5. package/src/acp/client.js +210 -53
  6. package/src/acp/client.ts +202 -52
  7. package/src/acp/peerProfiles.js +55 -22
  8. package/src/acp/peerProfiles.ts +51 -22
  9. package/src/acp/protocol.js +37 -8
  10. package/src/acp/protocol.ts +30 -8
  11. package/src/acp/server.js +123 -25
  12. package/src/acp/server.ts +124 -24
  13. package/src/agent/errorClassifier.js +117 -0
  14. package/src/agent/errorClassifier.ts +165 -0
  15. package/src/agent/promptIntent.js +200 -0
  16. package/src/agent/promptIntent.ts +203 -0
  17. package/src/agent/toolArgValidator.js +97 -0
  18. package/src/agent/toolArgValidator.ts +112 -0
  19. package/src/agentLoop.js +33 -344
  20. package/src/agentLoop.ts +51 -352
  21. package/src/approvalGrants.js +19 -7
  22. package/src/approvalGrants.ts +20 -7
  23. package/src/approvalPolicy.js +48 -15
  24. package/src/approvalPolicy.ts +46 -15
  25. package/src/autoUpdate.js +116 -10
  26. package/src/autoUpdate.ts +149 -10
  27. package/src/browser/causyneBrowser.js +3 -2
  28. package/src/browser/causyneBrowser.ts +3 -2
  29. package/src/browser/searchProviders.js +1 -1
  30. package/src/browser/searchProviders.ts +1 -1
  31. package/src/cliMode.js +16 -2
  32. package/src/commands.js +10 -9
  33. package/src/config.js +288 -272
  34. package/src/config.ts +342 -0
  35. package/src/configVault.js +271 -0
  36. package/src/configVault.ts +273 -0
  37. package/src/continuum/compactor.js +2 -1
  38. package/src/continuum/compactor.ts +2 -1
  39. package/src/continuum/sanitizer.js +10 -3
  40. package/src/continuum/sanitizer.ts +9 -3
  41. package/src/continuum/ui/continuumPickerView.js +3 -2
  42. package/src/continuum/ui/continuumPickerView.ts +3 -2
  43. package/src/core/contextCompactor.js +70 -11
  44. package/src/core/contextCompactor.ts +83 -11
  45. package/src/cortex/vectorDb.js +26 -15
  46. package/src/cortex/vectorDb.ts +26 -16
  47. package/src/creative/liveBridge.js +7 -5
  48. package/src/creative/liveBridge.ts +7 -5
  49. package/src/creative/studioScripts.js +16 -5
  50. package/src/creative/studioScripts.ts +14 -5
  51. package/src/decisionPolicy.js +16 -4
  52. package/src/decisionPolicy.ts +14 -4
  53. package/src/documentEngine/antiSlopAuditor.js +10 -5
  54. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  55. package/src/documentEngine/documentForge.js +47 -15
  56. package/src/documentEngine/documentForge.ts +43 -14
  57. package/src/dynamicCatalogue.js +42 -73
  58. package/src/dynamicCatalogue.ts +74 -60
  59. package/src/engines/design.js +2 -1
  60. package/src/engines/design.ts +2 -1
  61. package/src/engines/film.js +4 -4
  62. package/src/engines/film.ts +2 -2
  63. package/src/engines/light.js +2 -1
  64. package/src/engines/light.ts +2 -1
  65. package/src/engines/registry.js +1 -1
  66. package/src/engines/registry.ts +1 -1
  67. package/src/engines/reverseHarness.js +4 -3
  68. package/src/engines/reverseHarness.ts +4 -3
  69. package/src/entrypoint.js +77 -4
  70. package/src/headlessCli.js +305 -0
  71. package/src/headlessCli.ts +381 -0
  72. package/src/historyPruner.js +3 -2
  73. package/src/historyPruner.ts +3 -2
  74. package/src/hooks.js +3 -0
  75. package/src/hooks.ts +3 -0
  76. package/src/implementationPlan.js +21 -11
  77. package/src/implementationPlan.ts +21 -11
  78. package/src/infra/atomicWriter.js +4 -1
  79. package/src/infra/atomicWriter.ts +4 -1
  80. package/src/launchIntent.js +1 -1
  81. package/src/launchIntent.ts +1 -1
  82. package/src/mcp/mcpClient.js +38 -11
  83. package/src/mcp/mcpClient.ts +44 -11
  84. package/src/mcp/mcpRegistry.js +2 -5
  85. package/src/mcp/mcpRegistry.ts +2 -5
  86. package/src/mcp/mcpSecurity.js +189 -0
  87. package/src/mcp/mcpSecurity.ts +190 -0
  88. package/src/memory/scopedFacts.js +1 -1
  89. package/src/memory/scopedFacts.ts +1 -1
  90. package/src/memory/symbolFolder.js +1 -1
  91. package/src/memory/symbolFolder.ts +1 -1
  92. package/src/modelRouter.js +1 -1
  93. package/src/modelRouter.ts +1 -1
  94. package/src/observer/evidence.js +10 -4
  95. package/src/observer/evidence.ts +10 -4
  96. package/src/osKeychain.js +263 -0
  97. package/src/osKeychain.ts +287 -0
  98. package/src/perception.js +3 -2
  99. package/src/perception.ts +3 -2
  100. package/src/planCache.js +2 -2
  101. package/src/planCache.ts +2 -2
  102. package/src/pluginsFactory/pluginsFactory.js +19 -11
  103. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  104. package/src/promptMentions.js +2 -2
  105. package/src/promptMentions.ts +2 -2
  106. package/src/providers/acp.js +1 -1
  107. package/src/providers/acp.ts +1 -1
  108. package/src/providers/anthropic.js +328 -385
  109. package/src/providers/anthropic.ts +386 -0
  110. package/src/providers/antigravity.js +10 -4
  111. package/src/providers/antigravity.ts +10 -4
  112. package/src/providers/base.js +221 -319
  113. package/src/providers/base.ts +340 -0
  114. package/src/providers/byokHttp.js +397 -0
  115. package/src/providers/byokHttp.ts +497 -0
  116. package/src/providers/byokStream.js +748 -0
  117. package/src/providers/byokStream.ts +863 -0
  118. package/src/providers/dashscope-byok.js +98 -81
  119. package/src/providers/dashscope-byok.ts +114 -0
  120. package/src/providers/deepseek.js +74 -64
  121. package/src/providers/deepseek.ts +99 -0
  122. package/src/providers/factory.js +35 -28
  123. package/src/providers/factory.ts +40 -0
  124. package/src/providers/gemini.js +229 -253
  125. package/src/providers/gemini.ts +261 -0
  126. package/src/providers/loopGuard.js +9 -5
  127. package/src/providers/loopGuard.ts +10 -5
  128. package/src/providers/moonshot.js +71 -64
  129. package/src/providers/moonshot.ts +93 -0
  130. package/src/providers/muse.js +82 -152
  131. package/src/providers/muse.ts +122 -0
  132. package/src/providers/ollama.js +116 -93
  133. package/src/providers/ollama.ts +135 -0
  134. package/src/providers/openai-compatible.js +114 -65
  135. package/src/providers/openai-compatible.ts +139 -0
  136. package/src/providers/openai.js +22 -15
  137. package/src/providers/openai.ts +30 -0
  138. package/src/providers/openrouter.js +194 -98
  139. package/src/providers/openrouter.ts +202 -97
  140. package/src/providers/pi.js +6 -0
  141. package/src/providers/pi.ts +6 -0
  142. package/src/providers/qwen-byok.js +97 -71
  143. package/src/providers/qwen-byok.ts +113 -0
  144. package/src/providers/toolContracts.js +40 -14
  145. package/src/providers/toolContracts.ts +35 -14
  146. package/src/providers/wireNormalizer.js +78 -11
  147. package/src/providers/wireNormalizer.ts +68 -12
  148. package/src/providers/xai.js +74 -64
  149. package/src/providers/xai.ts +97 -0
  150. package/src/reliability/assetEvidence.js +4 -2
  151. package/src/reliability/assetEvidence.ts +4 -2
  152. package/src/sandbox.js +486 -530
  153. package/src/sandbox.ts +552 -0
  154. package/src/sandboxPolicy.js +1287 -0
  155. package/src/sandboxPolicy.ts +1381 -0
  156. package/src/sessionJournal.js +55 -3
  157. package/src/sessionJournal.ts +58 -3
  158. package/src/skills/skillResourceSafety.js +19 -8
  159. package/src/skills/skillResourceSafety.ts +16 -7
  160. package/src/skillsManager.js +3 -3
  161. package/src/skillsManager.ts +3 -3
  162. package/src/smartToolsUse.js +28 -4
  163. package/src/smartToolsUse.ts +29 -7
  164. package/src/stallGuard.js +45 -22
  165. package/src/stallGuard.ts +46 -22
  166. package/src/subagentJournal.js +6 -4
  167. package/src/subagentJournal.ts +6 -4
  168. package/src/textDiff.js +6 -1
  169. package/src/textDiff.ts +6 -1
  170. package/src/timeMachine.js +7 -1
  171. package/src/timeMachine.ts +7 -1
  172. package/src/tokenTracker.js +43 -28
  173. package/src/tokenTracker.ts +44 -30
  174. package/src/toolPacks.js +3 -1
  175. package/src/toolPacks.ts +3 -1
  176. package/src/tools/archive.js +245 -35
  177. package/src/tools/archive.ts +244 -35
  178. package/src/tools/computerUse.js +7 -3
  179. package/src/tools/computerUse.ts +7 -3
  180. package/src/tools/creativeApps.js +13 -8
  181. package/src/tools/creativeApps.ts +22 -9
  182. package/src/tools/deferredMcpSearch.js +26 -14
  183. package/src/tools/deferredMcpSearch.ts +26 -14
  184. package/src/tools/desktopOpen.js +69 -10
  185. package/src/tools/desktopOpen.ts +70 -11
  186. package/src/tools/documentForge.js +167 -82
  187. package/src/tools/documentForge.ts +169 -84
  188. package/src/tools/fsEdit.js +101 -30
  189. package/src/tools/fsEdit.ts +105 -32
  190. package/src/tools/fsFind.js +8 -5
  191. package/src/tools/fsFind.ts +7 -4
  192. package/src/tools/fsRead.js +119 -13
  193. package/src/tools/fsRead.ts +124 -13
  194. package/src/tools/fsWrite.js +17 -5
  195. package/src/tools/fsWrite.ts +17 -7
  196. package/src/tools/generateMediaViaApi.js +82 -19
  197. package/src/tools/generateMediaViaApi.ts +80 -19
  198. package/src/tools/memoryRecall.js +62 -11
  199. package/src/tools/memoryRecall.ts +70 -13
  200. package/src/tools/memoryWrite.js +27 -14
  201. package/src/tools/memoryWrite.ts +30 -14
  202. package/src/tools/multiEdit.js +100 -30
  203. package/src/tools/multiEdit.ts +104 -32
  204. package/src/tools/nativeEngine.js +33 -18
  205. package/src/tools/nativeEngine.ts +31 -18
  206. package/src/tools/openSourceToolProvisioner.js +49 -14
  207. package/src/tools/openSourceToolProvisioner.ts +54 -15
  208. package/src/tools/osSandbox.js +513 -0
  209. package/src/tools/osSandbox.ts +588 -0
  210. package/src/tools/payloadSanitizer.js +40 -8
  211. package/src/tools/payloadSanitizer.ts +39 -8
  212. package/src/tools/peerAgent.js +96 -34
  213. package/src/tools/peerAgent.ts +114 -37
  214. package/src/tools/persistentShell.js +8 -3
  215. package/src/tools/pluginsFactory.js +38 -6
  216. package/src/tools/pluginsFactory.ts +42 -6
  217. package/src/tools/readNativeSkill.js +10 -8
  218. package/src/tools/readNativeSkill.ts +10 -8
  219. package/src/tools/requestDecision.js +10 -3
  220. package/src/tools/requestDecision.ts +10 -3
  221. package/src/tools/resolveAutomator.js +91 -17
  222. package/src/tools/resolveAutomator.ts +102 -17
  223. package/src/tools/reverseEngineering.js +168 -41
  224. package/src/tools/reverseEngineering.ts +161 -41
  225. package/src/tools/subprocessEnv.js +197 -0
  226. package/src/tools/subprocessEnv.ts +212 -0
  227. package/src/tools/sysRun.js +108 -35
  228. package/src/tools/sysRun.ts +119 -31
  229. package/src/tools/toolDispatch.js +24 -1
  230. package/src/tools/toolDispatch.ts +21 -1
  231. package/src/tools/toolOutputStore.js +62 -23
  232. package/src/tools/toolOutputStore.ts +56 -23
  233. package/src/tools/toolScanner.js +13 -10
  234. package/src/tools/toolScanner.ts +13 -10
  235. package/src/tools/toolSelfRepair.js +94 -28
  236. package/src/tools/toolSelfRepair.ts +96 -28
  237. package/src/tools/uiForge.js +71 -6
  238. package/src/tools/uiForge.ts +74 -6
  239. package/src/tools/viewImage.js +62 -17
  240. package/src/tools/viewImage.ts +57 -12
  241. package/src/tools/visionInspector.js +15 -3
  242. package/src/tools/visionInspector.ts +15 -3
  243. package/src/tools/walkerSafety.js +2 -0
  244. package/src/tools/walkerSafety.ts +1 -0
  245. package/src/tools/webFetch.js +105 -10
  246. package/src/tools/webFetch.ts +105 -11
  247. package/src/tui/banner.js +3 -2
  248. package/src/tui/banner.ts +3 -2
  249. package/src/tui/consoleGuard.js +12 -4
  250. package/src/tui/consoleGuard.ts +9 -4
  251. package/src/tui/messageInteraction.js +2 -3
  252. package/src/tui/messageInteraction.ts +2 -3
  253. package/src/tui/modelPicker.js +1 -0
  254. package/src/tui/modelPicker.ts +1 -0
  255. package/src/tui/overlay.js +3 -1
  256. package/src/tui/overlay.ts +3 -1
  257. package/src/tui/sessionPicker.js +3 -2
  258. package/src/tui/sessionPicker.ts +3 -2
  259. package/src/tui/sessionPickerView.js +7 -1
  260. package/src/tui/sessionPickerView.ts +6 -1
  261. package/src/tui/toolOutputNormalizer.js +2 -3
  262. package/src/tui/toolOutputNormalizer.ts +4 -3
  263. package/src/tui/viewport.js +4 -4
  264. package/src/tui/viewport.ts +5 -5
  265. package/src/tui/workspaceIdentity.js +2 -1
  266. package/src/tui/workspaceIdentity.ts +2 -1
  267. package/src/uncertainty.js +8 -3
  268. package/src/uncertainty.ts +8 -3
  269. package/src/utils/paths.js +8 -5
  270. package/src/utils/paths.ts +9 -7
  271. package/src/vfeTracker.js +9 -3
  272. package/src/vfeTracker.ts +9 -3
  273. package/src/config.d.ts +0 -2
  274. package/src/providers/base.d.ts +0 -94
  275. package/src/providers/factory.d.ts +0 -1
  276. package/src/sandbox.d.ts +0 -1
@@ -0,0 +1,1381 @@
1
+ /**
2
+ * Causyne Agent — Sandbox Workspace, Credential & Shell Command Policy
3
+ *
4
+ * Linear-time (O(n), zero ReDoS) security helpers supporting `src/sandbox.js`:
5
+ * 1. Canonical blocked-workspace-root checks (POSIX + Windows + symlink resolution)
6
+ * enforced uniformly by both `updateWorkspacePaths()` and `addWorkspacePath()`.
7
+ * 2. Expanded credential-path recognition (`.env*` excluding example/sample/template
8
+ * files, `.envrc`, `.git-credentials`, `.pypirc`, `.pgpass`, `.my.cnf`, private
9
+ * SSH key filenames, and cloud service-account credential JSONs).
10
+ * 3. Quote-aware shell parser that extracts nested command substitutions
11
+ * (`$(...)` and backticks, including inside double quotes), strips leading env
12
+ * assignments and wrapper commands (`env`, `command`, `nohup`, `nice`, `time`,
13
+ * `timeout`, `exec`, `stdbuf`, `builtin`, `caffeinate`), resolves absolute
14
+ * executable basenames (`/bin/rm` -> `rm`), and extracts redirection + `tee`
15
+ * write targets even when quoted or prefixed with `$HOME`.
16
+ */
17
+
18
+ import os from 'node:os';
19
+ import path from 'node:path';
20
+ import { isWithinPhysicalPath, physicalPath } from './agent/workspaceBoundary.js';
21
+
22
+ const MAX_SUBSTITUTION_DEPTH = 16;
23
+ const MAX_SUBSTITUTIONS = 64;
24
+
25
+ const SAFE_ENV_TEMPLATE_EXACT = new Set([
26
+ '.env.example',
27
+ '.env.sample',
28
+ '.env.template',
29
+ '.env.dist',
30
+ '.env.defaults',
31
+ '.env.schema'
32
+ ]);
33
+
34
+ const SAFE_ENV_TEMPLATE_SUFFIXES = [
35
+ '.example',
36
+ '.sample',
37
+ '.template',
38
+ '.dist'
39
+ ];
40
+
41
+ const CREDENTIAL_DIR_SEGMENTS = new Set([
42
+ '.ssh',
43
+ '.aws',
44
+ '.gnupg',
45
+ '.kube',
46
+ '.causyne'
47
+ ]);
48
+
49
+ const CREDENTIAL_EXACT_BASENAMES = new Set([
50
+ '.netrc',
51
+ '.npmrc',
52
+ '.envrc',
53
+ '.git-credentials',
54
+ '.pypirc',
55
+ '.pgpass',
56
+ '.my.cnf',
57
+ 'id_rsa',
58
+ 'id_ed25519',
59
+ 'id_ecdsa',
60
+ 'id_dsa',
61
+ 'credentials.json',
62
+ 'application_default_credentials.json',
63
+ '.htpasswd',
64
+ 'kubeconfig',
65
+ 'terraform.tfvars',
66
+ 'terraform.tfvars.json',
67
+ '.terraformrc'
68
+ ]);
69
+
70
+ const SENSITIVE_WRITE_EXACT_BASENAMES = new Set([
71
+ '.bashrc',
72
+ '.bash_profile',
73
+ '.bash_login',
74
+ '.profile',
75
+ '.zshrc',
76
+ '.zprofile',
77
+ '.zshenv',
78
+ '.zlogin',
79
+ '.npmrc',
80
+ '.netrc',
81
+ '.git-credentials',
82
+ '.pypirc',
83
+ '.envrc'
84
+ ]);
85
+
86
+ const SHELL_INTERPRETERS = new Set([
87
+ 'sh',
88
+ 'bash',
89
+ 'zsh',
90
+ 'dash',
91
+ 'ksh',
92
+ 'fish',
93
+ 'ash',
94
+ 'pwsh',
95
+ 'powershell'
96
+ ]);
97
+
98
+ const LEADING_SHELL_KEYWORDS = new Set([
99
+ '!',
100
+ '(',
101
+ '{',
102
+ 'if',
103
+ 'then',
104
+ 'else',
105
+ 'elif',
106
+ 'do',
107
+ 'while',
108
+ 'until',
109
+ 'case'
110
+ ]);
111
+
112
+ const POSIX_TEMP_ALLOWLIST = [
113
+ '/tmp',
114
+ '/private/tmp',
115
+ '/private/var/tmp',
116
+ '/private/var/folders',
117
+ '/var/tmp',
118
+ '/var/folders'
119
+ ];
120
+
121
+ const POSIX_BLOCKED_WORKSPACE_ROOTS = [
122
+ '/etc',
123
+ '/private/etc',
124
+ '/usr',
125
+ '/bin',
126
+ '/sbin',
127
+ '/System',
128
+ '/var',
129
+ '/private',
130
+ '/Library',
131
+ '/dev',
132
+ '/proc',
133
+ '/sys',
134
+ '/boot',
135
+ '/root'
136
+ ];
137
+
138
+ function expandLeadingTilde(targetPath: string): string {
139
+ if (targetPath === '~') return os.homedir();
140
+ if (targetPath.startsWith('~/') || targetPath.startsWith('~\\')) {
141
+ return path.join(os.homedir(), targetPath.slice(2));
142
+ }
143
+ return targetPath;
144
+ }
145
+
146
+ function isWithinForPlatform(child: string, parent: string, platform: NodeJS.Platform): boolean {
147
+ if (platform === 'win32') {
148
+ const rel = path.win32.relative(parent.toLowerCase(), child.toLowerCase());
149
+ return rel === '' || (rel !== '..' && !rel.startsWith('..\\') && !path.win32.isAbsolute(rel));
150
+ }
151
+ return isWithinPhysicalPath(child, parent);
152
+ }
153
+
154
+ function stripWindowsDevicePrefix(candidate: string): string {
155
+ if (candidate.startsWith('\\\\?\\') || candidate.startsWith('\\\\.\\')) {
156
+ return candidate.slice(4);
157
+ }
158
+ if (candidate.startsWith('//?/') || candidate.startsWith('//./')) {
159
+ return candidate.slice(4);
160
+ }
161
+ return candidate;
162
+ }
163
+
164
+ function isBlockedResolvedRoot(rawCandidate: string, platform: NodeJS.Platform): boolean {
165
+ const candidate = platform === 'win32' ? stripWindowsDevicePrefix(rawCandidate) : rawCandidate;
166
+ const pathApi = platform === 'win32' ? path.win32 : path.posix;
167
+ const parsedRoot = pathApi.parse(candidate).root;
168
+ if (parsedRoot && candidate.toLowerCase() === parsedRoot.toLowerCase()) {
169
+ return true;
170
+ }
171
+
172
+ if (platform === 'win32') {
173
+ const sysRoot = process.env.SystemRoot || process.env.SYSTEMROOT || 'C:\\Windows';
174
+ const winBlocked = [
175
+ sysRoot,
176
+ 'C:\\Windows',
177
+ 'C:\\Program Files',
178
+ 'C:\\Program Files (x86)',
179
+ 'C:\\ProgramData',
180
+ 'C:\\System Volume Information'
181
+ ];
182
+ return winBlocked.some(root => isWithinForPlatform(candidate, root, 'win32'));
183
+ }
184
+
185
+ if (POSIX_TEMP_ALLOWLIST.some(allowed => isWithinForPlatform(candidate, allowed, platform))) {
186
+ return false;
187
+ }
188
+
189
+ return POSIX_BLOCKED_WORKSPACE_ROOTS.some(root => isWithinForPlatform(candidate, root, platform));
190
+ }
191
+
192
+ /**
193
+ * Returns true if `targetPath` is a system-critical root, filesystem root,
194
+ * invalid/dangling symlink, or resolves via symlinks into a blocked system root.
195
+ * Used uniformly by `updateWorkspacePaths()` and `addWorkspacePath()`.
196
+ */
197
+ export function isBlockedWorkspaceRoot(
198
+ targetPath: string,
199
+ options?: { platform?: NodeJS.Platform | undefined }
200
+ ): boolean {
201
+ if (typeof targetPath !== 'string' || targetPath.trim().length === 0 || targetPath.includes('\0')) return true;
202
+ const platform = options?.platform ?? process.platform;
203
+ const expanded = expandLeadingTilde(targetPath.trim());
204
+ const resolved = platform === 'win32' ? path.win32.resolve(expanded) : path.resolve(expanded);
205
+
206
+ if (isBlockedResolvedRoot(resolved, platform)) return true;
207
+
208
+ if (platform === process.platform) {
209
+ const realTarget = physicalPath(resolved);
210
+ if (!realTarget) return true;
211
+ if (isBlockedResolvedRoot(realTarget, platform)) return true;
212
+ }
213
+
214
+ return false;
215
+ }
216
+
217
+ /**
218
+ * Recognizes credential stores, private key files, and secret env files
219
+ * without backtracking regexes. Explicitly excludes `.env.example`, `.env.sample`,
220
+ * `.env.template`, and `.env.dist` templates to prevent developer false positives.
221
+ */
222
+ export function isExtendedCredentialPath(targetPath: string): boolean {
223
+ if (typeof targetPath !== 'string' || targetPath.length === 0 || targetPath.includes('\0')) return false;
224
+ const normalized = targetPath.replace(/\\/g, '/').trim();
225
+ if (!normalized) return false;
226
+
227
+ const trimmed = normalized.endsWith('/') && normalized.length > 1
228
+ ? normalized.slice(0, -1)
229
+ : normalized;
230
+ const parts = trimmed.split('/').filter(Boolean);
231
+ if (parts.length === 0) return false;
232
+
233
+ const lowerParts = parts.map(p => p.toLowerCase());
234
+
235
+ for (const part of lowerParts) {
236
+ if (CREDENTIAL_DIR_SEGMENTS.has(part)) return true;
237
+ }
238
+
239
+ for (let i = 0; i < lowerParts.length - 1; i++) {
240
+ if (lowerParts[i] === 'library' && lowerParts[i + 1] === 'keychains') return true;
241
+ if (lowerParts[i] === '.docker' && lowerParts[i + 1] === 'config.json') return true;
242
+ if (lowerParts[i] === 'gh' && lowerParts[i + 1] === 'hosts.yml') return true;
243
+ if (lowerParts[i] === 'gcloud' && (lowerParts[i + 1] === 'credentials.db' || lowerParts[i + 1] === 'access_tokens.db')) return true;
244
+ }
245
+
246
+ const baseLower = lowerParts[lowerParts.length - 1] ?? '';
247
+ if (CREDENTIAL_EXACT_BASENAMES.has(baseLower)) return true;
248
+
249
+ if (baseLower === '.env') return true;
250
+ if (baseLower.startsWith('.env.')) {
251
+ if (SAFE_ENV_TEMPLATE_EXACT.has(baseLower)) return false;
252
+ for (const suffix of SAFE_ENV_TEMPLATE_SUFFIXES) {
253
+ if (baseLower.endsWith(suffix)) return false;
254
+ }
255
+ return true;
256
+ }
257
+
258
+ if (
259
+ (baseLower.startsWith('service-account') || baseLower.startsWith('service_account')) &&
260
+ baseLower.endsWith('.json')
261
+ ) {
262
+ return true;
263
+ }
264
+
265
+ const isSafeTemplate = SAFE_ENV_TEMPLATE_SUFFIXES.some(suffix => baseLower.endsWith(suffix));
266
+ if (
267
+ !isSafeTemplate &&
268
+ !baseLower.endsWith('.pub') &&
269
+ (baseLower.endsWith('.pem') || baseLower.endsWith('.key') || baseLower.endsWith('.p12') || baseLower.endsWith('.pfx'))
270
+ ) {
271
+ return true;
272
+ }
273
+
274
+ return false;
275
+ }
276
+
277
+ /**
278
+ * Returns true if a file target is a high-risk persistence or credential target
279
+ * for shell redirection (`>`, `>>`) or `tee`.
280
+ */
281
+ export function isSensitiveWriteTarget(rawTarget: string): boolean {
282
+ if (typeof rawTarget !== 'string' || rawTarget.length === 0 || rawTarget.includes('\0')) return false;
283
+
284
+ let target = rawTarget.trim();
285
+ if (
286
+ (target.startsWith('"') && target.endsWith('"') && target.length >= 2) ||
287
+ (target.startsWith("'") && target.endsWith("'") && target.length >= 2)
288
+ ) {
289
+ target = target.slice(1, -1);
290
+ }
291
+ target = target.replace(/\\/g, '/');
292
+
293
+ // Normalize common home-directory expansions for matching
294
+ if (target === '~' || target.startsWith('~/')) {
295
+ target = `/home/user${target.slice(1)}`;
296
+ } else if (target.startsWith('$home/') || target.startsWith('${home}/')) {
297
+ const slash = target.indexOf('/');
298
+ target = `/home/user${target.slice(slash)}`;
299
+ } else if (target.startsWith('$HOME/') || target.startsWith('${HOME}/')) {
300
+ const slash = target.indexOf('/');
301
+ target = `/home/user${target.slice(slash)}`;
302
+ } else if (
303
+ target.startsWith('$ZDOTDIR/') ||
304
+ target.startsWith('${ZDOTDIR}/') ||
305
+ /^%(?:userprofile|home|appdata)%\//i.test(target)
306
+ ) {
307
+ const slash = target.indexOf('/');
308
+ target = `/home/user${target.slice(slash)}`;
309
+ }
310
+
311
+ const lower = target.toLowerCase();
312
+ const parts = lower.split('/').filter(Boolean);
313
+ if (parts.length === 0) return false;
314
+
315
+ const base = parts[parts.length - 1] ?? '';
316
+ if (SENSITIVE_WRITE_EXACT_BASENAMES.has(base)) return true;
317
+
318
+ // Protected system / persistence directories
319
+ if (lower.startsWith('/etc/') || lower === '/etc' || lower.includes('/etc/')) return true;
320
+
321
+ for (let i = 0; i < parts.length; i++) {
322
+ const seg = parts[i];
323
+ if (seg === '.ssh' || seg === '.causyne' || seg === '.aws' || seg === '.kube' || seg === '.gnupg') {
324
+ return true;
325
+ }
326
+ if (seg === 'crontab' || seg === 'cron.d') return true;
327
+ if (seg === '.git' && (parts[i + 1] === 'hooks' || parts[i + 1] === 'config')) return true;
328
+ if (seg === '.docker' && parts[i + 1] === 'config.json') return true;
329
+ if (seg === '.config' && parts[i + 1] === 'fish' && parts[i + 2] === 'config.fish') return true;
330
+ }
331
+
332
+ return false;
333
+ }
334
+
335
+ interface ParsedMaskResult {
336
+ masked: string;
337
+ substitutions: string[];
338
+ }
339
+
340
+ /**
341
+ * Single-pass quote-aware scanner that masks literal single/double-quoted text
342
+ * while extracting executable command substitutions (`$(...)` and backticks)
343
+ * both outside quotes and inside double quotes (single quotes stay literal).
344
+ */
345
+ export function parseMaskAndExtractSubstitutions(
346
+ input: string,
347
+ depth = 0
348
+ ): ParsedMaskResult {
349
+ let masked = '';
350
+ const substitutions: string[] = [];
351
+ const len = input.length;
352
+ let i = 0;
353
+
354
+ while (i < len) {
355
+ const ch = input[i];
356
+
357
+ // Backslash escape outside quotes
358
+ if (ch === '\\' && i + 1 < len) {
359
+ masked += ch + input[i + 1];
360
+ i += 2;
361
+ continue;
362
+ }
363
+
364
+ // Single-quoted literal span (no variable or command substitution in POSIX)
365
+ if (ch === "'") {
366
+ i++;
367
+ while (i < len && input[i] !== "'") {
368
+ i++;
369
+ }
370
+ if (i < len) i++; // consume closing quote
371
+ masked += "''";
372
+ continue;
373
+ }
374
+
375
+ // Double-quoted span: literal text is masked, but `$(...)` and `` `...` `` EXECUTE!
376
+ if (ch === '"') {
377
+ i++;
378
+ while (i < len && input[i] !== '"') {
379
+ const inner = input[i];
380
+ if (inner === '\\' && i + 1 < len) {
381
+ i += 2;
382
+ continue;
383
+ }
384
+ if (inner === '$' && input[i + 1] === '(') {
385
+ const captured = readDollarSubshell(input, i + 2);
386
+ if (captured.content.trim().length > 0) {
387
+ substitutions.push(captured.content);
388
+ }
389
+ i = captured.nextIndex;
390
+ continue;
391
+ }
392
+ if (inner === '`') {
393
+ const captured = readBacktickSubshell(input, i + 1);
394
+ if (captured.content.trim().length > 0) {
395
+ substitutions.push(captured.content);
396
+ }
397
+ i = captured.nextIndex;
398
+ continue;
399
+ }
400
+ i++;
401
+ }
402
+ if (i < len) i++; // consume closing quote
403
+ masked += '""';
404
+ continue;
405
+ }
406
+
407
+ // Unquoted `$(...)` command substitution
408
+ if (ch === '$' && input[i + 1] === '(') {
409
+ const captured = readDollarSubshell(input, i + 2);
410
+ if (captured.content.trim().length > 0) {
411
+ substitutions.push(captured.content);
412
+ }
413
+ masked += ' ';
414
+ i = captured.nextIndex;
415
+ continue;
416
+ }
417
+
418
+ // Unquoted backtick command substitution
419
+ if (ch === '`') {
420
+ const captured = readBacktickSubshell(input, i + 1);
421
+ if (captured.content.trim().length > 0) {
422
+ substitutions.push(captured.content);
423
+ }
424
+ masked += ' ';
425
+ i = captured.nextIndex;
426
+ continue;
427
+ }
428
+
429
+ masked += ch;
430
+ i++;
431
+ }
432
+
433
+ if (substitutions.length > MAX_SUBSTITUTIONS) {
434
+ substitutions.length = MAX_SUBSTITUTIONS;
435
+ }
436
+ if (depth < MAX_SUBSTITUTION_DEPTH && substitutions.length > 0 && substitutions.length < MAX_SUBSTITUTIONS) {
437
+ const nested: string[] = [];
438
+ for (const sub of substitutions) {
439
+ if (substitutions.length + nested.length >= MAX_SUBSTITUTIONS) break;
440
+ const parsed = parseMaskAndExtractSubstitutions(sub, depth + 1);
441
+ for (const deeper of parsed.substitutions) {
442
+ if (substitutions.length + nested.length >= MAX_SUBSTITUTIONS) break;
443
+ nested.push(deeper);
444
+ }
445
+ }
446
+ for (const deeper of nested) {
447
+ substitutions.push(deeper);
448
+ }
449
+ }
450
+
451
+ return { masked, substitutions };
452
+ }
453
+
454
+ function readDollarSubshell(input: string, startIndex: number): { content: string; nextIndex: number } {
455
+ const len = input.length;
456
+ let i = startIndex;
457
+ let parenDepth = 1;
458
+ let inSingle = false;
459
+ let inDouble = false;
460
+
461
+ while (i < len && parenDepth > 0) {
462
+ const ch = input[i];
463
+ if (inSingle) {
464
+ if (ch === "'") inSingle = false;
465
+ i++;
466
+ continue;
467
+ }
468
+ if (inDouble) {
469
+ if (ch === '\\' && i + 1 < len) {
470
+ i += 2;
471
+ continue;
472
+ }
473
+ if (ch === '"') inDouble = false;
474
+ i++;
475
+ continue;
476
+ }
477
+ if (ch === '\\' && i + 1 < len) {
478
+ i += 2;
479
+ continue;
480
+ }
481
+ if (ch === "'") {
482
+ inSingle = true;
483
+ i++;
484
+ continue;
485
+ }
486
+ if (ch === '"') {
487
+ inDouble = true;
488
+ i++;
489
+ continue;
490
+ }
491
+ if (ch === '(') {
492
+ parenDepth++;
493
+ i++;
494
+ continue;
495
+ }
496
+ if (ch === ')') {
497
+ parenDepth--;
498
+ if (parenDepth === 0) {
499
+ return { content: input.slice(startIndex, i), nextIndex: i + 1 };
500
+ }
501
+ i++;
502
+ continue;
503
+ }
504
+ i++;
505
+ }
506
+ return { content: input.slice(startIndex, i), nextIndex: i };
507
+ }
508
+
509
+ function readBacktickSubshell(input: string, startIndex: number): { content: string; nextIndex: number } {
510
+ const len = input.length;
511
+ let i = startIndex;
512
+ while (i < len) {
513
+ const ch = input[i];
514
+ if (ch === '\\' && i + 1 < len) {
515
+ i += 2;
516
+ continue;
517
+ }
518
+ if (ch === '`') {
519
+ return { content: input.slice(startIndex, i), nextIndex: i + 1 };
520
+ }
521
+ i++;
522
+ }
523
+ return { content: input.slice(startIndex, i), nextIndex: i };
524
+ }
525
+
526
+ /**
527
+ * Splits a masked shell command string into sequential command lists and
528
+ * pipe-connected pipeline groups while keeping `2>&1` / `>&2` descriptor
529
+ * duplications intact.
530
+ */
531
+ export function splitIntoPipelinesAndSegments(maskedText: string): {
532
+ segments: string[];
533
+ pipelines: string[][];
534
+ } {
535
+ const listGroups: string[] = [];
536
+ let current = '';
537
+ const len = maskedText.length;
538
+ let i = 0;
539
+
540
+ const pushGroup = (): void => {
541
+ const trimmed = current.trim();
542
+ if (trimmed.length > 0) listGroups.push(trimmed);
543
+ current = '';
544
+ };
545
+
546
+ while (i < len) {
547
+ const ch = maskedText[i]!;
548
+ const next = maskedText[i + 1];
549
+
550
+ if (ch === ';' || ch === '\n') {
551
+ pushGroup();
552
+ i++;
553
+ continue;
554
+ }
555
+ if (ch === '&' && next === '&') {
556
+ pushGroup();
557
+ i += 2;
558
+ continue;
559
+ }
560
+ if (ch === '|' && next === '|') {
561
+ pushGroup();
562
+ i += 2;
563
+ continue;
564
+ }
565
+ if (ch === '&') {
566
+ const prev = i > 0 ? maskedText[i - 1] : '';
567
+ // Keep `>&1`, `2>&1`, `<&0`, `&>` redirections intact
568
+ if (prev === '>' || prev === '<' || next === '>') {
569
+ current += ch;
570
+ i++;
571
+ continue;
572
+ }
573
+ pushGroup();
574
+ i++;
575
+ continue;
576
+ }
577
+
578
+ current += ch;
579
+ i++;
580
+ }
581
+ pushGroup();
582
+
583
+ const segments: string[] = [];
584
+ const pipelines: string[][] = [];
585
+
586
+ for (const group of listGroups) {
587
+ const stages: string[] = [];
588
+ let stage = '';
589
+ for (let j = 0; j < group.length; j++) {
590
+ const ch = group[j]!;
591
+ if (ch === '|') {
592
+ const trimmed = stage.trim();
593
+ if (trimmed.length > 0) {
594
+ stages.push(trimmed);
595
+ segments.push(trimmed);
596
+ }
597
+ stage = '';
598
+ continue;
599
+ }
600
+ stage += ch;
601
+ }
602
+ const trimmed = stage.trim();
603
+ if (trimmed.length > 0) {
604
+ stages.push(trimmed);
605
+ segments.push(trimmed);
606
+ }
607
+ if (stages.length > 0) {
608
+ pipelines.push(stages);
609
+ }
610
+ }
611
+
612
+ return { segments, pipelines };
613
+ }
614
+
615
+ function isEnvAssignmentToken(token: string): boolean {
616
+ const eq = token.indexOf('=');
617
+ if (eq <= 0) return false;
618
+ const name = token.slice(0, eq);
619
+ const first = name.charCodeAt(0);
620
+ const isFirstValid =
621
+ (first >= 97 && first <= 122) || // a-z
622
+ (first >= 65 && first <= 90) || // A-Z
623
+ first === 95; // _
624
+ if (!isFirstValid) return false;
625
+ for (let i = 1; i < name.length; i++) {
626
+ const code = name.charCodeAt(i);
627
+ const valid =
628
+ (code >= 97 && code <= 122) ||
629
+ (code >= 65 && code <= 90) ||
630
+ (code >= 48 && code <= 57) ||
631
+ code === 95;
632
+ if (!valid) return false;
633
+ }
634
+ return true;
635
+ }
636
+
637
+ function isStandaloneRedirectOperator(token: string): boolean {
638
+ return (
639
+ token === '>' ||
640
+ token === '>>' ||
641
+ token === '<' ||
642
+ token === '1>' ||
643
+ token === '1>>' ||
644
+ token === '2>' ||
645
+ token === '2>>' ||
646
+ token === '&>' ||
647
+ token === '&>>'
648
+ );
649
+ }
650
+
651
+ function isAttachedRedirectToken(token: string): boolean {
652
+ return (
653
+ token.startsWith('>') ||
654
+ token.startsWith('<') ||
655
+ token.startsWith('1>') ||
656
+ token.startsWith('2>') ||
657
+ token.startsWith('&>')
658
+ );
659
+ }
660
+
661
+ function resolveExecutableBasename(token: string): string {
662
+ const normalized = token.replace(/\\/g, '/');
663
+ const slash = normalized.lastIndexOf('/');
664
+ let base = slash !== -1 ? normalized.slice(slash + 1) : normalized;
665
+ if (base.endsWith('.exe') && base.length > 4) {
666
+ base = base.slice(0, -4);
667
+ }
668
+ return base;
669
+ }
670
+
671
+ export interface NormalizedSegment {
672
+ normalized: string;
673
+ executable: string;
674
+ args: string[];
675
+ isReadOnlyLookup: boolean;
676
+ }
677
+
678
+ /**
679
+ * Normalizes one already-lowercased, quote-masked shell segment by stripping
680
+ * leading env assignments (`FOO=1`), redirections, control keywords, and
681
+ * benign command wrappers (`env`, `command`, `nohup`, `nice`, `time`, `timeout`,
682
+ * `exec`, `stdbuf`, `builtin`, `caffeinate`), then resolving the executable
683
+ * basename (`/bin/rm` -> `rm`).
684
+ *
685
+ * Preserves read-only lookup semantics for `command -v` / `command -V` so
686
+ * existence probes do not trigger false alarms.
687
+ */
688
+ export function normalizeExecutableSegment(segment: string): NormalizedSegment {
689
+ const tokens = segment.trim().split(/\s+/).filter(Boolean);
690
+ let idx = 0;
691
+
692
+ // Bounded normalization loop
693
+ for (let guard = 0; guard < 32 && idx < tokens.length; guard++) {
694
+ const tok = tokens[idx]!;
695
+
696
+ // Strip leading parentheses attached to a token, e.g. `(rm`
697
+ if (tok.startsWith('(') && tok.length > 1) {
698
+ tokens[idx] = tok.slice(1);
699
+ continue;
700
+ }
701
+
702
+ if (LEADING_SHELL_KEYWORDS.has(tok)) {
703
+ idx++;
704
+ continue;
705
+ }
706
+
707
+ if (isStandaloneRedirectOperator(tok)) {
708
+ idx += 2; // operator + filename
709
+ continue;
710
+ }
711
+ if (isAttachedRedirectToken(tok)) {
712
+ idx++;
713
+ continue;
714
+ }
715
+
716
+ if (isEnvAssignmentToken(tok)) {
717
+ idx++;
718
+ continue;
719
+ }
720
+
721
+ const base = resolveExecutableBasename(tok);
722
+
723
+ if (base === 'env') {
724
+ idx++;
725
+ while (idx < tokens.length) {
726
+ const next = tokens[idx]!;
727
+ if (next === '--') {
728
+ idx++;
729
+ break;
730
+ }
731
+ if (next === '-u' || next === '-c' || next === '-s' || next === '--unset' || next === '--chdir') {
732
+ idx += 2;
733
+ continue;
734
+ }
735
+ if (next.startsWith('-')) {
736
+ idx++;
737
+ continue;
738
+ }
739
+ if (isEnvAssignmentToken(next)) {
740
+ idx++;
741
+ continue;
742
+ }
743
+ break;
744
+ }
745
+ continue;
746
+ }
747
+
748
+ if (base === 'command') {
749
+ let scan = idx + 1;
750
+ let isQueryOnly = false;
751
+ while (scan < tokens.length) {
752
+ const next = tokens[scan]!;
753
+ if (next === '--') {
754
+ scan++;
755
+ break;
756
+ }
757
+ if (next.startsWith('-') && next.length > 1) {
758
+ // POSIX `command -v` and `command -V` only look up the path; never execute
759
+ if (next.includes('v')) {
760
+ isQueryOnly = true;
761
+ }
762
+ scan++;
763
+ continue;
764
+ }
765
+ break;
766
+ }
767
+ if (isQueryOnly) {
768
+ const rest = tokens.slice(idx);
769
+ return {
770
+ normalized: rest.join(' '),
771
+ executable: 'command',
772
+ args: rest.slice(1),
773
+ isReadOnlyLookup: true
774
+ };
775
+ }
776
+ idx = scan;
777
+ continue;
778
+ }
779
+
780
+ if (base === 'nohup' || base === 'builtin' || base === 'setsid') {
781
+ idx++;
782
+ if (tokens[idx] === '--') idx++;
783
+ continue;
784
+ }
785
+
786
+ if (base === 'time') {
787
+ idx++;
788
+ while (idx < tokens.length && tokens[idx]!.startsWith('-')) {
789
+ if (tokens[idx] === '--') {
790
+ idx++;
791
+ break;
792
+ }
793
+ idx++;
794
+ }
795
+ continue;
796
+ }
797
+
798
+ if (base === 'nice') {
799
+ idx++;
800
+ while (idx < tokens.length && tokens[idx]!.startsWith('-')) {
801
+ const flag = tokens[idx]!;
802
+ if (flag === '--') {
803
+ idx++;
804
+ break;
805
+ }
806
+ if (flag === '-n' || flag === '--adjustment') {
807
+ idx += 2;
808
+ continue;
809
+ }
810
+ idx++;
811
+ }
812
+ continue;
813
+ }
814
+
815
+ if (base === 'exec') {
816
+ idx++;
817
+ while (idx < tokens.length && tokens[idx]!.startsWith('-')) {
818
+ const flag = tokens[idx]!;
819
+ if (flag === '--') {
820
+ idx++;
821
+ break;
822
+ }
823
+ if (flag === '-a') {
824
+ idx += 2;
825
+ continue;
826
+ }
827
+ idx++;
828
+ }
829
+ continue;
830
+ }
831
+
832
+ if (base === 'stdbuf' || base === 'ionice' || base === 'taskset') {
833
+ idx++;
834
+ while (idx < tokens.length && tokens[idx]!.startsWith('-')) {
835
+ const flag = tokens[idx]!;
836
+ if (flag === '--') {
837
+ idx++;
838
+ break;
839
+ }
840
+ if (flag === '-i' || flag === '-o' || flag === '-e' || flag === '-c' || flag === '-n' || flag === '-p') {
841
+ idx += 2;
842
+ continue;
843
+ }
844
+ idx++;
845
+ }
846
+ continue;
847
+ }
848
+
849
+ if (base === 'caffeinate') {
850
+ idx++;
851
+ while (idx < tokens.length && tokens[idx]!.startsWith('-')) {
852
+ const flag = tokens[idx]!;
853
+ if (flag === '--') {
854
+ idx++;
855
+ break;
856
+ }
857
+ if (flag === '-t' || flag === '-w') {
858
+ idx += 2;
859
+ continue;
860
+ }
861
+ idx++;
862
+ }
863
+ continue;
864
+ }
865
+
866
+ if (base === 'timeout') {
867
+ idx++;
868
+ while (idx < tokens.length && tokens[idx]!.startsWith('-')) {
869
+ const flag = tokens[idx]!;
870
+ if (flag === '--') {
871
+ idx++;
872
+ break;
873
+ }
874
+ if (flag === '-k' || flag === '-s' || flag === '--signal' || flag === '--kill-after') {
875
+ idx += 2;
876
+ continue;
877
+ }
878
+ idx++;
879
+ }
880
+ // Consume duration operand (e.g. `10`, `30s`, `2m`)
881
+ if (idx < tokens.length && /^\d+(?:\.\d+)?[smhd]?$/.test(tokens[idx]!)) {
882
+ idx++;
883
+ }
884
+ continue;
885
+ }
886
+
887
+ break;
888
+ }
889
+
890
+ if (idx >= tokens.length) {
891
+ return { normalized: '', executable: '', args: [], isReadOnlyLookup: false };
892
+ }
893
+
894
+ const executable = resolveExecutableBasename(tokens[idx]!);
895
+ const args = tokens.slice(idx + 1);
896
+ const normalized = args.length > 0 ? `${executable} ${args.join(' ')}` : executable;
897
+
898
+ return {
899
+ normalized,
900
+ executable,
901
+ args,
902
+ isReadOnlyLookup: false
903
+ };
904
+ }
905
+
906
+ /**
907
+ * Splits a raw command string into sequential/piped stages while ignoring
908
+ * separators (`;`, `&&`, `||`, `|`, `&`, `\n`) inside single or double quotes.
909
+ */
910
+ function splitRawIntoStages(rawCommand: string): string[] {
911
+ const stages: string[] = [];
912
+ let current = '';
913
+ const len = rawCommand.length;
914
+ let i = 0;
915
+ let inSingle = false;
916
+ let inDouble = false;
917
+
918
+ const pushStage = (): void => {
919
+ const trimmed = current.trim();
920
+ if (trimmed.length > 0) stages.push(trimmed);
921
+ current = '';
922
+ };
923
+
924
+ while (i < len) {
925
+ const ch = rawCommand[i]!;
926
+ const next = rawCommand[i + 1];
927
+
928
+ if (inSingle) {
929
+ current += ch;
930
+ if (ch === "'") inSingle = false;
931
+ i++;
932
+ continue;
933
+ }
934
+ if (inDouble) {
935
+ if (ch === '\\' && i + 1 < len) {
936
+ current += ch + next;
937
+ i += 2;
938
+ continue;
939
+ }
940
+ current += ch;
941
+ if (ch === '"') inDouble = false;
942
+ i++;
943
+ continue;
944
+ }
945
+ if (ch === '\\' && i + 1 < len) {
946
+ current += ch + next;
947
+ i += 2;
948
+ continue;
949
+ }
950
+ if (ch === "'") {
951
+ inSingle = true;
952
+ current += ch;
953
+ i++;
954
+ continue;
955
+ }
956
+ if (ch === '"') {
957
+ inDouble = true;
958
+ current += ch;
959
+ i++;
960
+ continue;
961
+ }
962
+
963
+ if (ch === ';' || ch === '\n') {
964
+ pushStage();
965
+ i++;
966
+ continue;
967
+ }
968
+ if (ch === '|' && next === '|') {
969
+ pushStage();
970
+ i += 2;
971
+ continue;
972
+ }
973
+ if (ch === '&' && next === '&') {
974
+ pushStage();
975
+ i += 2;
976
+ continue;
977
+ }
978
+ if (ch === '|') {
979
+ pushStage();
980
+ i++;
981
+ continue;
982
+ }
983
+ if (ch === '&') {
984
+ const prev = i > 0 ? rawCommand[i - 1] : '';
985
+ if (prev === '>' || prev === '<' || next === '>') {
986
+ current += ch;
987
+ i++;
988
+ continue;
989
+ }
990
+ pushStage();
991
+ i++;
992
+ continue;
993
+ }
994
+
995
+ current += ch;
996
+ i++;
997
+ }
998
+ pushStage();
999
+ return stages;
1000
+ }
1001
+
1002
+ /**
1003
+ * Extracts unquoted and quoted file targets written via redirection (`>`, `>>`)
1004
+ * or `tee` across a raw command string without matching operators inside quotes.
1005
+ */
1006
+ export function extractWriteTargetsFromRaw(rawCommand: string): string[] {
1007
+ const targets: string[] = [];
1008
+ const len = rawCommand.length;
1009
+ let i = 0;
1010
+ let inSingle = false;
1011
+ let inDouble = false;
1012
+
1013
+ const readShellWord = (start: number): { word: string; nextIndex: number } => {
1014
+ let j = start;
1015
+ while (j < len && (rawCommand[j] === ' ' || rawCommand[j] === '\t')) j++;
1016
+ let word = '';
1017
+ while (j < len) {
1018
+ const c = rawCommand[j]!;
1019
+ if (c === ' ' || c === '\t' || c === '\n' || c === ';' || c === '|' || c === '&' || c === '<' || c === '>') {
1020
+ break;
1021
+ }
1022
+ if (c === "'") {
1023
+ j++;
1024
+ while (j < len && rawCommand[j] !== "'") {
1025
+ word += rawCommand[j];
1026
+ j++;
1027
+ }
1028
+ if (j < len) j++;
1029
+ continue;
1030
+ }
1031
+ if (c === '"') {
1032
+ j++;
1033
+ while (j < len && rawCommand[j] !== '"') {
1034
+ if (rawCommand[j] === '\\' && j + 1 < len) {
1035
+ word += rawCommand[j + 1];
1036
+ j += 2;
1037
+ continue;
1038
+ }
1039
+ word += rawCommand[j];
1040
+ j++;
1041
+ }
1042
+ if (j < len) j++;
1043
+ continue;
1044
+ }
1045
+ if (c === '\\' && j + 1 < len) {
1046
+ word += rawCommand[j + 1];
1047
+ j += 2;
1048
+ continue;
1049
+ }
1050
+ word += c;
1051
+ j++;
1052
+ }
1053
+ return { word, nextIndex: j };
1054
+ };
1055
+
1056
+ while (i < len) {
1057
+ const ch = rawCommand[i]!;
1058
+ if (inSingle) {
1059
+ if (ch === "'") inSingle = false;
1060
+ i++;
1061
+ continue;
1062
+ }
1063
+ if (inDouble) {
1064
+ if (ch === '\\' && i + 1 < len) {
1065
+ i += 2;
1066
+ continue;
1067
+ }
1068
+ if (ch === '"') inDouble = false;
1069
+ i++;
1070
+ continue;
1071
+ }
1072
+ if (ch === '\\' && i + 1 < len) {
1073
+ i += 2;
1074
+ continue;
1075
+ }
1076
+ if (ch === "'") {
1077
+ inSingle = true;
1078
+ i++;
1079
+ continue;
1080
+ }
1081
+ if (ch === '"') {
1082
+ inDouble = true;
1083
+ i++;
1084
+ continue;
1085
+ }
1086
+
1087
+ if (ch === '>') {
1088
+ // Handle `>>`, `>|`, and `>&`: FD duplications (`2>&1`, `>&2`, `>&-`) are not files,
1089
+ // whereas `>& file` in Bash/Zsh redirects stdout+stderr to `file`.
1090
+ let next = i + 1;
1091
+ if (rawCommand[next] === '&') {
1092
+ const { word, nextIndex } = readShellWord(next + 1);
1093
+ if (word && !/^(?:\d+-?|-)$/.test(word)) {
1094
+ targets.push(word);
1095
+ }
1096
+ i = nextIndex;
1097
+ continue;
1098
+ }
1099
+ if (rawCommand[next] === '>' || rawCommand[next] === '|') {
1100
+ next++;
1101
+ }
1102
+ const { word, nextIndex } = readShellWord(next);
1103
+ if (word && !word.startsWith('&')) {
1104
+ targets.push(word);
1105
+ }
1106
+ i = nextIndex;
1107
+ continue;
1108
+ }
1109
+
1110
+ i++;
1111
+ }
1112
+
1113
+ // Also capture `tee [-a|-i] <target...>` destinations on unquoted pipe/command stages
1114
+ const stages = splitRawIntoStages(rawCommand);
1115
+ for (const seg of stages) {
1116
+ const words = tokenizeRawShellWords(seg);
1117
+ if (words.length < 2) continue;
1118
+ const norm = normalizeExecutableSegment(words.map(w => w.toLowerCase()).join(' '));
1119
+ if (norm.executable === 'tee') {
1120
+ // Re-scan original-case words after the `tee` token
1121
+ const teeIndex = words.findIndex(w => resolveExecutableBasename(w.toLowerCase()) === 'tee');
1122
+ if (teeIndex !== -1) {
1123
+ for (let k = teeIndex + 1; k < words.length; k++) {
1124
+ const arg = words[k]!;
1125
+ if (arg === '--') continue;
1126
+ if (arg.startsWith('-')) continue;
1127
+ targets.push(arg);
1128
+ }
1129
+ }
1130
+ }
1131
+ }
1132
+
1133
+ return targets;
1134
+ }
1135
+
1136
+ function tokenizeRawShellWords(segment: string): string[] {
1137
+ const words: string[] = [];
1138
+ const len = segment.length;
1139
+ let i = 0;
1140
+
1141
+ while (i < len) {
1142
+ while (i < len && (segment[i] === ' ' || segment[i] === '\t' || segment[i] === '\n')) i++;
1143
+ if (i >= len) break;
1144
+
1145
+ let word = '';
1146
+ while (i < len) {
1147
+ const ch = segment[i]!;
1148
+ if (ch === ' ' || ch === '\t' || ch === '\n') break;
1149
+ if (ch === "'") {
1150
+ i++;
1151
+ while (i < len && segment[i] !== "'") {
1152
+ word += segment[i];
1153
+ i++;
1154
+ }
1155
+ if (i < len) i++;
1156
+ continue;
1157
+ }
1158
+ if (ch === '"') {
1159
+ i++;
1160
+ while (i < len && segment[i] !== '"') {
1161
+ if (segment[i] === '\\' && i + 1 < len) {
1162
+ word += segment[i + 1];
1163
+ i += 2;
1164
+ continue;
1165
+ }
1166
+ word += segment[i];
1167
+ i++;
1168
+ }
1169
+ if (i < len) i++;
1170
+ continue;
1171
+ }
1172
+ if (ch === '\\' && i + 1 < len) {
1173
+ word += segment[i + 1];
1174
+ i += 2;
1175
+ continue;
1176
+ }
1177
+ word += ch;
1178
+ i++;
1179
+ }
1180
+ if (word.length > 0) words.push(word);
1181
+ }
1182
+ return words;
1183
+ }
1184
+
1185
+ /**
1186
+ * Detects destructive recursive-force removals regardless of flag order or
1187
+ * flag bundling (e.g. `rm -r -f /`, `rm -f -r ~`, `rm -rfv /`, `rm --recursive --force *`).
1188
+ */
1189
+ export function isExtremeRemovalSegment(seg: NormalizedSegment): boolean {
1190
+ if (seg.executable !== 'rm') return false;
1191
+
1192
+ let hasRecursive = false;
1193
+ let hasForce = false;
1194
+ const targets: string[] = [];
1195
+ let endOfFlags = false;
1196
+
1197
+ for (const arg of seg.args) {
1198
+ if (!endOfFlags && arg === '--') {
1199
+ endOfFlags = true;
1200
+ continue;
1201
+ }
1202
+ if (!endOfFlags && arg.startsWith('--')) {
1203
+ if (arg === '--recursive') hasRecursive = true;
1204
+ if (arg === '--force') hasForce = true;
1205
+ continue;
1206
+ }
1207
+ if (!endOfFlags && arg.startsWith('-') && arg.length > 1) {
1208
+ const flags = arg.slice(1);
1209
+ if (flags.includes('r')) hasRecursive = true;
1210
+ if (flags.includes('f')) hasForce = true;
1211
+ continue;
1212
+ }
1213
+ targets.push(arg);
1214
+ }
1215
+
1216
+ if (!hasRecursive || !hasForce) return false;
1217
+
1218
+ for (const target of targets) {
1219
+ if (
1220
+ target === '/' ||
1221
+ target.startsWith('/') ||
1222
+ target === '~' ||
1223
+ target.startsWith('~/') ||
1224
+ target.startsWith('~') ||
1225
+ target.startsWith('*') ||
1226
+ target === '.' ||
1227
+ target === './' ||
1228
+ target.startsWith('./*') ||
1229
+ target === '..' ||
1230
+ target === '../' ||
1231
+ target.startsWith('../*') ||
1232
+ /^[a-z]:[\\/]?$/.test(target) ||
1233
+ target === '$home' ||
1234
+ target.startsWith('$home/') ||
1235
+ target === '${home}' ||
1236
+ target.startsWith('${home}/')
1237
+ ) {
1238
+ // Allow `/tmp/...`? Wait — `rm -rf /tmp/foo` is dangerous, not necessarily root wipe,
1239
+ // EXCEPT existing classifier explicitly treated `/rm\s+(-rf|-fr)\s+[\/~]/` as extreme!
1240
+ // Preserve exact strictness: any leading `/` or `~` or `*` with recursive+force is extreme.
1241
+ return true;
1242
+ }
1243
+ }
1244
+ return false;
1245
+ }
1246
+
1247
+ /**
1248
+ * Detects fetch-and-execute pipelines (`curl ... | bash`, `wget ... | /bin/zsh`,
1249
+ * `curl ... | sudo sh`, `curl ... | env bash`) in linear time.
1250
+ */
1251
+ export function isFetchAndExecPipeline(pipelines: readonly (readonly NormalizedSegment[])[]): boolean {
1252
+ for (const pipeline of pipelines) {
1253
+ if (pipeline.length < 2) continue;
1254
+ let sawFetcher = false;
1255
+ for (const stage of pipeline) {
1256
+ if (stage.executable === 'curl' || stage.executable === 'wget') {
1257
+ sawFetcher = true;
1258
+ continue;
1259
+ }
1260
+ if (!sawFetcher) continue;
1261
+ if (SHELL_INTERPRETERS.has(stage.executable)) return true;
1262
+ // Handle `curl ... | sudo|su|doas|pkexec|xargs bash`
1263
+ if (
1264
+ stage.executable === 'sudo' ||
1265
+ stage.executable === 'su' ||
1266
+ stage.executable === 'doas' ||
1267
+ stage.executable === 'pkexec' ||
1268
+ stage.executable === 'xargs'
1269
+ ) {
1270
+ const valueFlags = new Set([
1271
+ '-u', '-g', '-c', '-d', '-h', '-p', '-r', '-t', '-a', '-s',
1272
+ '--user', '--group', '--prompt', '--chdir', '--shell'
1273
+ ]);
1274
+ for (let i = 0; i < stage.args.length; i++) {
1275
+ const arg = stage.args[i]!;
1276
+ if (arg === '--') {
1277
+ const next = stage.args[i + 1];
1278
+ if (next && SHELL_INTERPRETERS.has(resolveExecutableBasename(next))) return true;
1279
+ break;
1280
+ }
1281
+ if (arg.startsWith('-')) {
1282
+ if (valueFlags.has(arg)) i++;
1283
+ continue;
1284
+ }
1285
+ if (SHELL_INTERPRETERS.has(resolveExecutableBasename(arg))) return true;
1286
+ break;
1287
+ }
1288
+ }
1289
+ }
1290
+ }
1291
+ return false;
1292
+ }
1293
+
1294
+ export interface AnalyzedShellCommand {
1295
+ maskedTopLevel: string;
1296
+ allRawUnits: string[];
1297
+ allMaskedUnits: string[];
1298
+ normalizedSegments: NormalizedSegment[];
1299
+ unwrappedRawSegments: NormalizedSegment[];
1300
+ normalizedPipelines: NormalizedSegment[][];
1301
+ writeTargets: string[];
1302
+ }
1303
+
1304
+ /**
1305
+ * Parses a shell command string (including nested `$(...)` and backtick
1306
+ * substitutions) into normalized executable segments, pipelines, and write targets.
1307
+ */
1308
+ export function analyzeShellCommand(rawCommand: string): AnalyzedShellCommand {
1309
+ if (typeof rawCommand !== 'string') {
1310
+ return {
1311
+ maskedTopLevel: '',
1312
+ allRawUnits: [],
1313
+ allMaskedUnits: [],
1314
+ normalizedSegments: [],
1315
+ unwrappedRawSegments: [],
1316
+ normalizedPipelines: [],
1317
+ writeTargets: []
1318
+ };
1319
+ }
1320
+ const lower = rawCommand.trim().toLowerCase();
1321
+ const topParsed = parseMaskAndExtractSubstitutions(lower, 0);
1322
+
1323
+ const allRawUnits: string[] = [rawCommand.trim()];
1324
+ const allMaskedUnits: string[] = [topParsed.masked];
1325
+
1326
+ // Also keep original-case substitutions for accurate path-target extraction
1327
+ const rawCaseParsed = parseMaskAndExtractSubstitutions(rawCommand.trim(), 0);
1328
+ for (const sub of rawCaseParsed.substitutions) {
1329
+ allRawUnits.push(sub);
1330
+ }
1331
+ for (const sub of topParsed.substitutions) {
1332
+ const subParsed = parseMaskAndExtractSubstitutions(sub, MAX_SUBSTITUTION_DEPTH);
1333
+ allMaskedUnits.push(subParsed.masked);
1334
+ }
1335
+
1336
+ const normalizedSegments: NormalizedSegment[] = [];
1337
+ const normalizedPipelines: NormalizedSegment[][] = [];
1338
+
1339
+ for (const unit of allMaskedUnits) {
1340
+ const { pipelines } = splitIntoPipelinesAndSegments(unit);
1341
+ for (const pipeline of pipelines) {
1342
+ const normPipeline: NormalizedSegment[] = [];
1343
+ for (const stage of pipeline) {
1344
+ const norm = normalizeExecutableSegment(stage);
1345
+ if (norm.normalized.length > 0) {
1346
+ normalizedSegments.push(norm);
1347
+ normPipeline.push(norm);
1348
+ }
1349
+ }
1350
+ if (normPipeline.length > 0) {
1351
+ normalizedPipelines.push(normPipeline);
1352
+ }
1353
+ }
1354
+ }
1355
+
1356
+ const unwrappedRawSegments: NormalizedSegment[] = [];
1357
+ const writeTargets: string[] = [];
1358
+ for (const rawUnit of allRawUnits) {
1359
+ for (const target of extractWriteTargetsFromRaw(rawUnit)) {
1360
+ writeTargets.push(target);
1361
+ }
1362
+ for (const stage of splitRawIntoStages(rawUnit)) {
1363
+ const words = tokenizeRawShellWords(stage);
1364
+ if (words.length === 0) continue;
1365
+ const norm = normalizeExecutableSegment(words.map(w => w.toLowerCase()).join(' '));
1366
+ if (norm.normalized.length > 0) {
1367
+ unwrappedRawSegments.push(norm);
1368
+ }
1369
+ }
1370
+ }
1371
+
1372
+ return {
1373
+ maskedTopLevel: topParsed.masked,
1374
+ allRawUnits,
1375
+ allMaskedUnits,
1376
+ normalizedSegments,
1377
+ unwrappedRawSegments,
1378
+ normalizedPipelines,
1379
+ writeTargets
1380
+ };
1381
+ }