micro-models-agent 2.16.1 → 2.17.2

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 (428) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +8 -3
  3. package/dist/assets/app.js +1 -314
  4. package/dist/assets/hljs.js +5 -1244
  5. package/dist/assets/index.html +11 -0
  6. package/dist/assets/js/api.js +1 -28
  7. package/dist/assets/js/core/menus.js +1 -0
  8. package/dist/assets/js/core/store/feed.js +1 -0
  9. package/dist/assets/js/core/store/index.js +1 -0
  10. package/dist/assets/js/core/store/session.js +1 -0
  11. package/dist/assets/js/core/store/settings.js +1 -0
  12. package/dist/assets/js/core/store/tabs.js +1 -0
  13. package/dist/assets/js/dialog.js +1 -105
  14. package/dist/assets/js/dom.js +1 -178
  15. package/dist/assets/js/feed/core.js +1 -0
  16. package/dist/assets/js/feed/history.js +1 -0
  17. package/dist/assets/js/feed/plan.js +1 -0
  18. package/dist/assets/js/feed/question.js +3 -0
  19. package/dist/assets/js/feed/sidebar.js +1 -0
  20. package/dist/assets/js/feed/stream.js +1 -0
  21. package/dist/assets/js/feed/turn.js +5 -0
  22. package/dist/assets/js/feed.js +1 -1250
  23. package/dist/assets/js/format.js +2 -122
  24. package/dist/assets/js/i18n.js +1 -46
  25. package/dist/assets/js/rail.js +1 -114
  26. package/dist/assets/js/session/cmdk.js +1 -0
  27. package/dist/assets/js/session/composer.js +1 -0
  28. package/dist/assets/js/session/sessions-menu.js +1 -0
  29. package/dist/assets/js/session/tabs.js +1 -0
  30. package/dist/assets/js/settings/controls.js +1 -0
  31. package/dist/assets/js/settings/editors.js +1 -0
  32. package/dist/assets/js/settings/form.js +1 -0
  33. package/dist/assets/js/settings/modal.js +1 -0
  34. package/dist/assets/js/settings/panels.js +1 -0
  35. package/dist/assets/js/settings/providers.js +1 -0
  36. package/dist/assets/js/settings/search.js +1 -0
  37. package/dist/assets/js/settings/subdialog.js +1 -0
  38. package/dist/assets/js/settings/write.js +1 -0
  39. package/dist/assets/js/settings.js +1 -1914
  40. package/dist/assets/js/sidebar/core.js +1 -0
  41. package/dist/assets/js/sidebar/lsp.js +2 -0
  42. package/dist/assets/js/sidebar/map.js +1 -0
  43. package/dist/assets/js/sidebar/state.js +1 -0
  44. package/dist/assets/js/sidebar/trace.js +5 -0
  45. package/dist/assets/js/sidebar.js +1 -705
  46. package/dist/assets/js/store.js +1 -82
  47. package/dist/assets/js/subdialog.js +1 -0
  48. package/dist/assets/md.js +1 -291
  49. package/dist/assets/setup.js +3 -816
  50. package/dist/assets/smd.js +29 -1665
  51. package/dist/assets/styles.css +1 -1598
  52. package/dist/certification/certifications.json +1 -494
  53. package/dist/i18n/en.json +1 -1851
  54. package/dist/i18n/ru.json +1 -1854
  55. package/dist/main.js +815 -55797
  56. package/dist/modules/browser/bridge-server.mjs +2 -252
  57. package/package.json +10 -5
  58. package/dist/assets/js/settings-controls.js +0 -452
  59. package/dist/assets/js/tabs.js +0 -867
  60. package/dist/cli/cache-line.js +0 -31
  61. package/dist/cli/command-suggest.js +0 -39
  62. package/dist/cli/commands.js +0 -781
  63. package/dist/cli/completer.js +0 -268
  64. package/dist/cli/index.js +0 -3
  65. package/dist/cli/json-payload.js +0 -32
  66. package/dist/cli/main.js +0 -346
  67. package/dist/cli/onboarding-commands.js +0 -126
  68. package/dist/cli/plugin-commands.js +0 -38
  69. package/dist/cli/relaunch.js +0 -40
  70. package/dist/cli/repl-commands-lsp.js +0 -75
  71. package/dist/cli/repl-commands-skills.js +0 -105
  72. package/dist/cli/repl-commands.js +0 -1218
  73. package/dist/cli/repl.js +0 -1238
  74. package/dist/cli/run-result.js +0 -38
  75. package/dist/cli/security-commands.js +0 -177
  76. package/dist/cli/setup-order.js +0 -6
  77. package/dist/cli/setup-prompt.js +0 -50
  78. package/dist/cli/setup.js +0 -161
  79. package/dist/cli/web-command.js +0 -98
  80. package/dist/config/budget.js +0 -48
  81. package/dist/config/config.js +0 -345
  82. package/dist/config/defaults.js +0 -197
  83. package/dist/config/domains.js +0 -135
  84. package/dist/config/env.js +0 -46
  85. package/dist/config/experts.js +0 -17
  86. package/dist/config/index.js +0 -5
  87. package/dist/config/paths.js +0 -56
  88. package/dist/config/redact.js +0 -44
  89. package/dist/config/registry-extra.js +0 -334
  90. package/dist/config/registry.js +0 -584
  91. package/dist/config/security.js +0 -212
  92. package/dist/config/timeouts.js +0 -74
  93. package/dist/config/types.js +0 -1
  94. package/dist/config/utils.js +0 -57
  95. package/dist/core/agent/artifact-progress.js +0 -59
  96. package/dist/core/agent/artifact-resolve.js +0 -79
  97. package/dist/core/agent/audit-gate.js +0 -53
  98. package/dist/core/agent/compaction.js +0 -89
  99. package/dist/core/agent/constants.js +0 -90
  100. package/dist/core/agent/context-log.js +0 -454
  101. package/dist/core/agent/context-renderer.js +0 -45
  102. package/dist/core/agent/critic-gate.js +0 -132
  103. package/dist/core/agent/hallucination-gate.js +0 -197
  104. package/dist/core/agent/loop-state.js +0 -68
  105. package/dist/core/agent/prefix-monitor.js +0 -101
  106. package/dist/core/agent/reasoning-resolver.js +0 -65
  107. package/dist/core/agent/token-tracker.js +0 -99
  108. package/dist/core/agent/tool-batch.js +0 -312
  109. package/dist/core/agent/tool-images.js +0 -18
  110. package/dist/core/agent/tool-output.js +0 -116
  111. package/dist/core/agent/tool-pairing.js +0 -60
  112. package/dist/core/agent-moe.js +0 -248
  113. package/dist/core/agent.js +0 -1299
  114. package/dist/core/bootstrap/agent-phase.js +0 -66
  115. package/dist/core/bootstrap/config-phase.js +0 -86
  116. package/dist/core/bootstrap/modules-phase.js +0 -269
  117. package/dist/core/bootstrap/provider-phase.js +0 -183
  118. package/dist/core/bootstrap/session-phase.js +0 -204
  119. package/dist/core/bootstrap/state.js +0 -94
  120. package/dist/core/bootstrap/workspace-phase.js +0 -115
  121. package/dist/core/bootstrap.js +0 -112
  122. package/dist/core/crash-handler.js +0 -62
  123. package/dist/core/environment.js +0 -224
  124. package/dist/core/host-plan.js +0 -43
  125. package/dist/core/host.js +0 -23
  126. package/dist/core/index.js +0 -3
  127. package/dist/core/prompt-builder.js +0 -95
  128. package/dist/core/prompt-overflow.js +0 -306
  129. package/dist/core/session-logger.js +0 -375
  130. package/dist/core/system-prompt.js +0 -117
  131. package/dist/core/types.js +0 -1
  132. package/dist/core/version.js +0 -28
  133. package/dist/core/web-host.js +0 -34
  134. package/dist/core/workspace.js +0 -80
  135. package/dist/i18n/index.js +0 -80
  136. package/dist/index.js +0 -30
  137. package/dist/llm/cache-usage.js +0 -76
  138. package/dist/llm/image-utils.js +0 -138
  139. package/dist/llm/index.js +0 -4
  140. package/dist/llm/llm-errors.js +0 -50
  141. package/dist/llm/model-loader.js +0 -86
  142. package/dist/llm/models-dev.js +0 -121
  143. package/dist/llm/openai-compat.js +0 -756
  144. package/dist/llm/orchestrator.js +0 -294
  145. package/dist/llm/provider-budget.js +0 -68
  146. package/dist/llm/provider-context.js +0 -233
  147. package/dist/llm/provider.js +0 -9
  148. package/dist/llm/response.js +0 -44
  149. package/dist/llm/stream-state.js +0 -26
  150. package/dist/llm/token-counter.js +0 -83
  151. package/dist/llm/types.js +0 -1
  152. package/dist/logger/app-logger.js +0 -212
  153. package/dist/logger/file-log.js +0 -160
  154. package/dist/logger/index.js +0 -2
  155. package/dist/migration/backup.js +0 -56
  156. package/dist/migration/detect.js +0 -61
  157. package/dist/migration/index.js +0 -3
  158. package/dist/modules/artifacts/store.js +0 -62
  159. package/dist/modules/browser/actions.js +0 -79
  160. package/dist/modules/browser/bridge-client.js +0 -203
  161. package/dist/modules/browser/bridge-path.js +0 -10
  162. package/dist/modules/browser/console-buffer.js +0 -37
  163. package/dist/modules/browser/cookie-store.js +0 -29
  164. package/dist/modules/browser/driver-types.js +0 -1
  165. package/dist/modules/browser/driver.js +0 -186
  166. package/dist/modules/browser/index.js +0 -9
  167. package/dist/modules/browser/module.js +0 -30
  168. package/dist/modules/browser/session.js +0 -322
  169. package/dist/modules/browser/snapshot.js +0 -154
  170. package/dist/modules/browser/types.js +0 -13
  171. package/dist/modules/certification/cli.js +0 -264
  172. package/dist/modules/certification/fact-checker.js +0 -90
  173. package/dist/modules/certification/loader.js +0 -127
  174. package/dist/modules/certification/manifest.js +0 -231
  175. package/dist/modules/certification/runner.js +0 -233
  176. package/dist/modules/certification/scenarios.js +0 -586
  177. package/dist/modules/certification/syntax-scenarios.js +0 -50
  178. package/dist/modules/certification/types.js +0 -1
  179. package/dist/modules/context/chunk-query.js +0 -122
  180. package/dist/modules/context/fact-extractor.js +0 -170
  181. package/dist/modules/context/history.js +0 -15
  182. package/dist/modules/context/index.js +0 -2
  183. package/dist/modules/context/manager.js +0 -482
  184. package/dist/modules/critic/client.js +0 -176
  185. package/dist/modules/critic/evidence.js +0 -81
  186. package/dist/modules/critic/provider.js +0 -45
  187. package/dist/modules/critic/tools.js +0 -78
  188. package/dist/modules/critic/types.js +0 -1
  189. package/dist/modules/execution/audit-runners.js +0 -206
  190. package/dist/modules/execution/auditor.js +0 -222
  191. package/dist/modules/execution/execution-plugin.js +0 -478
  192. package/dist/modules/execution/index.js +0 -8
  193. package/dist/modules/execution/input-from.js +0 -70
  194. package/dist/modules/execution/module.js +0 -891
  195. package/dist/modules/execution/moe-executor.js +0 -443
  196. package/dist/modules/execution/plan-actions.js +0 -642
  197. package/dist/modules/execution/plan-checks.js +0 -35
  198. package/dist/modules/execution/plan-coverage.js +0 -71
  199. package/dist/modules/execution/plan-persister.js +0 -46
  200. package/dist/modules/execution/plan-steps.js +0 -31
  201. package/dist/modules/execution/plan-store.js +0 -274
  202. package/dist/modules/execution/plan-tool.js +0 -249
  203. package/dist/modules/execution/plan-validator.js +0 -197
  204. package/dist/modules/execution/planner.js +0 -103
  205. package/dist/modules/execution/stuck-detector.js +0 -834
  206. package/dist/modules/execution/tracker.js +0 -92
  207. package/dist/modules/execution/transient-error.js +0 -30
  208. package/dist/modules/execution/types.js +0 -1
  209. package/dist/modules/execution/verifier.js +0 -343
  210. package/dist/modules/execution/windows-commands.js +0 -52
  211. package/dist/modules/hallucination/artifact-claim.js +0 -93
  212. package/dist/modules/hallucination/confidence.js +0 -81
  213. package/dist/modules/hallucination/consistency.js +0 -37
  214. package/dist/modules/hallucination/detector.js +0 -57
  215. package/dist/modules/hallucination/factual.js +0 -205
  216. package/dist/modules/hallucination/index.js +0 -6
  217. package/dist/modules/hallucination/js-identifiers.js +0 -261
  218. package/dist/modules/hallucination/llm-judge.js +0 -116
  219. package/dist/modules/hallucination/success-claim.js +0 -59
  220. package/dist/modules/index.js +0 -5
  221. package/dist/modules/indexer/cache.js +0 -88
  222. package/dist/modules/indexer/index.js +0 -4
  223. package/dist/modules/indexer/map-command.js +0 -33
  224. package/dist/modules/indexer/map-select.js +0 -87
  225. package/dist/modules/indexer/module.js +0 -293
  226. package/dist/modules/indexer/project-profile.js +0 -184
  227. package/dist/modules/indexer/symbols.js +0 -189
  228. package/dist/modules/indexer/walker.js +0 -285
  229. package/dist/modules/lsp/check-tool.js +0 -61
  230. package/dist/modules/lsp/client.js +0 -406
  231. package/dist/modules/lsp/command.js +0 -53
  232. package/dist/modules/lsp/config.js +0 -189
  233. package/dist/modules/lsp/index.js +0 -4
  234. package/dist/modules/lsp/module.js +0 -295
  235. package/dist/modules/lsp/probe.js +0 -86
  236. package/dist/modules/lsp/project-root.js +0 -69
  237. package/dist/modules/lsp/startup-check.js +0 -154
  238. package/dist/modules/lsp/types.js +0 -1
  239. package/dist/modules/mcp/client.js +0 -445
  240. package/dist/modules/mcp/index.js +0 -4
  241. package/dist/modules/mcp/module.js +0 -295
  242. package/dist/modules/mcp/registry.js +0 -20
  243. package/dist/modules/memory/index.js +0 -2
  244. package/dist/modules/memory/module.js +0 -101
  245. package/dist/modules/memory/search.js +0 -45
  246. package/dist/modules/memory/store.js +0 -107
  247. package/dist/modules/onboarding/init.js +0 -47
  248. package/dist/modules/onboarding/meet.js +0 -30
  249. package/dist/modules/onboarding/mode.js +0 -30
  250. package/dist/modules/onboarding/prompts.js +0 -43
  251. package/dist/modules/pipelines/engine.js +0 -70
  252. package/dist/modules/pipelines/index.js +0 -4
  253. package/dist/modules/pipelines/parser.js +0 -59
  254. package/dist/modules/pipelines/template.js +0 -18
  255. package/dist/modules/plugins/builtin/lint-on-write.js +0 -377
  256. package/dist/modules/plugins/builtin/notify.js +0 -11
  257. package/dist/modules/plugins/index.js +0 -2
  258. package/dist/modules/plugins/loader.js +0 -85
  259. package/dist/modules/plugins/manager.js +0 -244
  260. package/dist/modules/plugins/types.js +0 -1
  261. package/dist/modules/pricing/index.js +0 -70
  262. package/dist/modules/pricing/prices.js +0 -147
  263. package/dist/modules/processes/detect.js +0 -34
  264. package/dist/modules/processes/index.js +0 -4
  265. package/dist/modules/processes/kill-tree.js +0 -52
  266. package/dist/modules/processes/registry.js +0 -294
  267. package/dist/modules/processes/runner.js +0 -23
  268. package/dist/modules/providers/cache.js +0 -23
  269. package/dist/modules/providers/capabilities.js +0 -28
  270. package/dist/modules/providers/create.js +0 -21
  271. package/dist/modules/providers/factory.js +0 -28
  272. package/dist/modules/providers/fallback.js +0 -81
  273. package/dist/modules/providers/health.js +0 -47
  274. package/dist/modules/providers/index.js +0 -6
  275. package/dist/modules/providers/manager.js +0 -207
  276. package/dist/modules/providers/naming.js +0 -15
  277. package/dist/modules/providers/preflight.js +0 -71
  278. package/dist/modules/providers/presets.js +0 -232
  279. package/dist/modules/providers/registry.js +0 -27
  280. package/dist/modules/providers/types.js +0 -1
  281. package/dist/modules/reasoning/policy.js +0 -42
  282. package/dist/modules/reasoning/probe.js +0 -116
  283. package/dist/modules/registry.js +0 -48
  284. package/dist/modules/security/audit-log.js +0 -119
  285. package/dist/modules/security/audit-notifier.js +0 -267
  286. package/dist/modules/security/command-validator.js +0 -272
  287. package/dist/modules/security/content-scanner.js +0 -53
  288. package/dist/modules/security/data-sanitizer.js +0 -82
  289. package/dist/modules/security/encryption.js +0 -216
  290. package/dist/modules/security/index.js +0 -15
  291. package/dist/modules/security/network-validator.js +0 -236
  292. package/dist/modules/security/path-validator.js +0 -261
  293. package/dist/modules/security/protected-paths.js +0 -73
  294. package/dist/modules/security/rate-limiter.js +0 -98
  295. package/dist/modules/security/security-policies.js +0 -499
  296. package/dist/modules/security/session-encryption.js +0 -182
  297. package/dist/modules/security/session-isolation.js +0 -75
  298. package/dist/modules/session/auto-name.js +0 -63
  299. package/dist/modules/session/export.js +0 -98
  300. package/dist/modules/session/index.js +0 -4
  301. package/dist/modules/session/manager.js +0 -234
  302. package/dist/modules/session/module.js +0 -33
  303. package/dist/modules/session/store.js +0 -295
  304. package/dist/modules/session/types.js +0 -1
  305. package/dist/modules/setup/answers.js +0 -35
  306. package/dist/modules/setup/apply.js +0 -79
  307. package/dist/modules/setup/discovery.js +0 -72
  308. package/dist/modules/skills/index.js +0 -3
  309. package/dist/modules/skills/loader.js +0 -86
  310. package/dist/modules/skills/matcher.js +0 -27
  311. package/dist/modules/skills/module.js +0 -141
  312. package/dist/modules/types.js +0 -1
  313. package/dist/modules/updater/changelog-reader.js +0 -93
  314. package/dist/modules/updater/checker.js +0 -101
  315. package/dist/modules/updater/dev-detect.js +0 -18
  316. package/dist/modules/updater/index.js +0 -4
  317. package/dist/modules/updater/module.js +0 -129
  318. package/dist/modules/user-profile/compressor.js +0 -18
  319. package/dist/modules/user-profile/index.js +0 -2
  320. package/dist/modules/user-profile/profile.js +0 -77
  321. package/dist/modules/webui/answer-api.js +0 -29
  322. package/dist/modules/webui/assets.js +0 -50
  323. package/dist/modules/webui/body.js +0 -21
  324. package/dist/modules/webui/commands-settings.js +0 -209
  325. package/dist/modules/webui/commands-shared.js +0 -60
  326. package/dist/modules/webui/commands.js +0 -174
  327. package/dist/modules/webui/config-api.js +0 -134
  328. package/dist/modules/webui/file-api.js +0 -202
  329. package/dist/modules/webui/forward.js +0 -159
  330. package/dist/modules/webui/history-api.js +0 -112
  331. package/dist/modules/webui/host-state.js +0 -60
  332. package/dist/modules/webui/i18n-api.js +0 -9
  333. package/dist/modules/webui/limits.js +0 -6
  334. package/dist/modules/webui/log-forward.js +0 -20
  335. package/dist/modules/webui/memory-commands.js +0 -64
  336. package/dist/modules/webui/model-cache.js +0 -18
  337. package/dist/modules/webui/module.js +0 -148
  338. package/dist/modules/webui/persist.js +0 -24
  339. package/dist/modules/webui/prompt-io.js +0 -97
  340. package/dist/modules/webui/providers-api.js +0 -337
  341. package/dist/modules/webui/providers-view.js +0 -56
  342. package/dist/modules/webui/reasoning-view.js +0 -15
  343. package/dist/modules/webui/run-agent.js +0 -81
  344. package/dist/modules/webui/server.js +0 -284
  345. package/dist/modules/webui/sessions-api.js +0 -178
  346. package/dist/modules/webui/settings-api.js +0 -561
  347. package/dist/modules/webui/setup-api.js +0 -201
  348. package/dist/modules/webui/state.js +0 -74
  349. package/dist/modules/webui/util.js +0 -261
  350. package/dist/output/bus.js +0 -37
  351. package/dist/output/channel.js +0 -285
  352. package/dist/output/format.js +0 -15
  353. package/dist/output/index.js +0 -8
  354. package/dist/output/json-sink.js +0 -24
  355. package/dist/output/machine.js +0 -9
  356. package/dist/output/session-sink.js +0 -27
  357. package/dist/output/types.js +0 -1
  358. package/dist/tools/approve.js +0 -41
  359. package/dist/tools/attach-image.js +0 -102
  360. package/dist/tools/auto-fixer.js +0 -180
  361. package/dist/tools/auto-tags.js +0 -83
  362. package/dist/tools/bash.js +0 -649
  363. package/dist/tools/browser.js +0 -160
  364. package/dist/tools/chunk-query.js +0 -112
  365. package/dist/tools/create-dir.js +0 -60
  366. package/dist/tools/delete-file.js +0 -67
  367. package/dist/tools/download-file.js +0 -142
  368. package/dist/tools/edit-file.js +0 -136
  369. package/dist/tools/enable-tools.js +0 -59
  370. package/dist/tools/executor.js +0 -304
  371. package/dist/tools/file-info.js +0 -49
  372. package/dist/tools/filter-tools.js +0 -17
  373. package/dist/tools/glob-tool.js +0 -37
  374. package/dist/tools/grep-tool.js +0 -142
  375. package/dist/tools/hidden-tools-block.js +0 -37
  376. package/dist/tools/index.js +0 -88
  377. package/dist/tools/list-dir.js +0 -53
  378. package/dist/tools/load-skill.js +0 -51
  379. package/dist/tools/mcp-call.js +0 -80
  380. package/dist/tools/meet-done.js +0 -14
  381. package/dist/tools/move-file.js +0 -94
  382. package/dist/tools/path-utils.js +0 -108
  383. package/dist/tools/pipeline-run.js +0 -167
  384. package/dist/tools/preview.js +0 -2
  385. package/dist/tools/process-ids.js +0 -31
  386. package/dist/tools/process-kill.js +0 -33
  387. package/dist/tools/process-list.js +0 -38
  388. package/dist/tools/process-log.js +0 -49
  389. package/dist/tools/process-wait.js +0 -63
  390. package/dist/tools/prompt-io.js +0 -29
  391. package/dist/tools/question.js +0 -288
  392. package/dist/tools/read-file.js +0 -200
  393. package/dist/tools/recall.js +0 -124
  394. package/dist/tools/registry.js +0 -48
  395. package/dist/tools/remember.js +0 -72
  396. package/dist/tools/scope-check.js +0 -32
  397. package/dist/tools/scope-request.js +0 -96
  398. package/dist/tools/search-history.js +0 -88
  399. package/dist/tools/session-info.js +0 -46
  400. package/dist/tools/set-thinking.js +0 -75
  401. package/dist/tools/subagent.js +0 -257
  402. package/dist/tools/syntax-validator.js +0 -379
  403. package/dist/tools/types.js +0 -1
  404. package/dist/tools/user-input.js +0 -134
  405. package/dist/tools/web-browse.js +0 -93
  406. package/dist/tools/web-fetch.js +0 -108
  407. package/dist/tools/web-search.js +0 -107
  408. package/dist/tools/write-file.js +0 -128
  409. package/dist/ui/action-log.js +0 -13
  410. package/dist/ui/box.js +0 -78
  411. package/dist/ui/colors.js +0 -6
  412. package/dist/ui/diff.js +0 -189
  413. package/dist/ui/index.js +0 -7
  414. package/dist/ui/line-editor.js +0 -1083
  415. package/dist/ui/line-math.js +0 -98
  416. package/dist/ui/md-formatter.js +0 -322
  417. package/dist/ui/output.js +0 -19
  418. package/dist/ui/plan-view.js +0 -109
  419. package/dist/ui/renderer.js +0 -589
  420. package/dist/ui/spinner.js +0 -91
  421. package/dist/ui/table.js +0 -142
  422. package/dist/ui/theme.js +0 -143
  423. package/dist/utils/child-run.js +0 -20
  424. package/dist/utils/error.js +0 -4
  425. package/dist/utils/index.js +0 -6
  426. package/dist/utils/retry.js +0 -17
  427. package/dist/utils/sleep.js +0 -23
  428. package/dist/utils/truncate.js +0 -9
@@ -1,272 +0,0 @@
1
- import { DEFAULT_SECURITY_CONFIG } from "../../config/security";
2
- // Резерв, если DEFAULT_SECURITY_CONFIG недоступен
3
- const FALLBACK_BASH_CONFIG = {
4
- enabled: false,
5
- blacklist: [
6
- "rm",
7
- "dd",
8
- "chmod",
9
- "wget",
10
- "curl",
11
- "scp",
12
- "ssh",
13
- "nc",
14
- "netcat",
15
- "powershell",
16
- "pwsh",
17
- "cmd",
18
- ],
19
- whitelist: [],
20
- blockDangerousFlags: false,
21
- dangerousFlags: ["--force", "-rf", "--no-preserve-root"],
22
- dangerousOperators: [">", ">>", "2>", "2>>", "|", "&&", "||", ";", "`", "$("],
23
- logCommands: true,
24
- };
25
- export const DEFAULT_BASH_CONFIG = DEFAULT_SECURITY_CONFIG?.bash || FALLBACK_BASH_CONFIG;
26
- /**
27
- * Выделить базовую команду из shell-строки.
28
- * Учитывает пути, env-присваивания и sudo.
29
- *
30
- * Примеры:
31
- * "/usr/bin/rm -rf /" → "rm"
32
- * "sudo /usr/bin/rm file" → "rm"
33
- * "NODE_ENV=prod node app.js" → "node"
34
- * "env PATH=/x rm -rf /" → "rm"
35
- * "cmd=rm; $cmd -rf /" → "cmd" (переменная не раскрывается)
36
- * "powershell Remove-Item x" → "Remove-Item"
37
- * "cmd /c del /s /q" → "del"
38
- */
39
- /** Обёртки, запускающие другую команду; их опции пропускаются. */
40
- const WRAPPERS = new Set([
41
- "sudo",
42
- "doas",
43
- "env",
44
- "command",
45
- "exec",
46
- "nohup",
47
- "nice",
48
- "timeout",
49
- "stdbuf",
50
- "ionice",
51
- "setsid",
52
- "time",
53
- ]);
54
- /** Флаги обёрток, съедающие следующий токен как значение. */
55
- const WRAPPER_VALUE_FLAGS = {
56
- sudo: new Set(["-u", "-g", "-p", "-C", "-U", "-h", "-r", "-t", "-c"]),
57
- doas: new Set(["-u"]),
58
- nice: new Set(["-n", "--adjustment"]),
59
- timeout: new Set(["-k", "-s", "--signal", "--kill-after"]),
60
- stdbuf: new Set(["-i", "-o", "-e"]),
61
- ionice: new Set(["-c", "-n"]),
62
- };
63
- /** Пропустить собственные опции/значения обёртки; вернуть следующий индекс. */
64
- function skipWrapperArgs(tokens, i, wrapper) {
65
- const valueFlags = WRAPPER_VALUE_FLAGS[wrapper] ?? new Set();
66
- while (i < tokens.length) {
67
- const t = tokens[i];
68
- if (t.startsWith("-")) {
69
- i++;
70
- if (t.includes("="))
71
- continue; // --flag=value самодостаточен
72
- if (valueFlags.has(t))
73
- i++; // съесть значение флага
74
- continue;
75
- }
76
- // Голое число (timeout 5, nice 10) — никогда не команда.
77
- if (/^\d+(?:\.\d+)?[smhd]?$/.test(t)) {
78
- i++;
79
- continue;
80
- }
81
- break;
82
- }
83
- return i;
84
- }
85
- function extractBaseCommand(trimmed) {
86
- const tokens = trimmed.split(/\s+/);
87
- let i = 0;
88
- // Пропуск env-присваиваний (KEY=val, KEY="val" и т.п.) и обёрток
89
- // (sudo/nice/timeout/stdbuf/…) ВМЕСТЕ с их опциями — иначе
90
- // `nice rm file` извлёк бы "nice", и blacklist не увидел бы `rm`.
91
- while (i < tokens.length) {
92
- const tok = tokens[i];
93
- if (/^[a-zA-Z_][a-zA-Z0-9_]*=/.test(tok)) {
94
- i++;
95
- continue;
96
- }
97
- if (WRAPPERS.has(tok)) {
98
- i = skipWrapperArgs(tokens, i + 1, tok);
99
- continue;
100
- }
101
- break;
102
- }
103
- if (i >= tokens.length)
104
- return tokens[0] ?? "";
105
- // basename из пути (/usr/bin/rm → rm). Сначала снять кавычки —
106
- // иначе `'rm'` / `"rm"` полностью обойдут blacklist.
107
- const raw = tokens[i].replace(/^["']+|["']+$/g, "");
108
- const parts = raw.split(/[\\/]/);
109
- const basename = parts[parts.length - 1] || raw;
110
- // Срезать .exe/.cmd/.bat для сверки (powershell.exe → powershell)
111
- return basename.replace(/\.(exe|cmd|bat)$/i, "") || basename;
112
- }
113
- /**
114
- * Есть ли shell-оператор отдельным токеном в команде.
115
- * Regex с lookbehind/lookahead, чтобы:
116
- * "&" НЕ матчил "&&" (AND)
117
- * "|" НЕ матчил "||" (OR)
118
- * ">" НЕ матчил ">>" (append)
119
- * "2>" НЕ матчил "2>>" (append stderr)
120
- */
121
- function containsOperator(command, op) {
122
- const escaped = op.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
123
- // Односимвольные операторы — префиксы многосимвольных:
124
- // не матчить внутри длинной цепочки.
125
- // "&" уже не в dangerousOperators (&& легитимен),
126
- // спецкейс оставлен на случай ручного добавления.
127
- if (op === "&")
128
- return /(?<!&)&(?!&)/.test(command);
129
- if (op === "|")
130
- return /(?<!\|)\|(?!\|)/.test(command);
131
- if (op === ">")
132
- return /(?<!>)>(?!>)/.test(command);
133
- // Остальное (">>", "2>", "2>>", ";", "`") — буквальное совпадение.
134
- return new RegExp(escaped).test(command);
135
- }
136
- /**
137
- * Разрешена ли команда по конфигу безопасности.
138
- * Выключенная защита разрешает всё; пустая команда запрещена.
139
- */
140
- export function isCommandAllowed(command, securityConfig) {
141
- // Выключенная защита разрешает всё
142
- if (!securityConfig?.enabled) {
143
- return { allowed: true, sanitizedCommand: command };
144
- }
145
- // Конфиг должен иметь все поля
146
- let config = securityConfig;
147
- if (!config.blacklist || !Array.isArray(config.blacklist)) {
148
- config = {
149
- ...FALLBACK_BASH_CONFIG,
150
- enabled: config.enabled ?? FALLBACK_BASH_CONFIG.enabled,
151
- };
152
- }
153
- const trimmedCommand = command.trim();
154
- if (!trimmedCommand) {
155
- return { allowed: false, reason: "Empty command" };
156
- }
157
- // Shell-обёртки запрещены всегда — они обходят всю валидацию.
158
- // Агент использует тул bash напрямую, а не интерпретаторы.
159
- const ALWAYS_BLOCKED = ["powershell", "pwsh", "cmd"];
160
- const baseForShellCheck = extractBaseCommand(trimmedCommand);
161
- if (ALWAYS_BLOCKED.includes(baseForShellCheck)) {
162
- return {
163
- allowed: false,
164
- reason: `Shell wrapper "${baseForShellCheck}" is blocked — use the bash tool directly`,
165
- };
166
- }
167
- // Интерпретаторы с -c/-e исполняют произвольный код в обход blacklist.
168
- // Кавычки снимаются заранее (`'bash' -c`), имя может идти после пути
169
- // (`/bin/bash -c`) — матчить и их.
170
- const unquotedCommand = trimmedCommand.replace(/["']/g, "");
171
- const INTERPRETER_FLAGS = /(?:^|[\\/\s])(?:bash|sh|zsh|dash|python[0-9.]*|pypy[0-9.]*|node(?:js)?|bun|deno|perl|ruby|php|lua)\s+(?:-c|-e|--command|--eval)\b/;
172
- if (INTERPRETER_FLAGS.test(unquotedCommand)) {
173
- return { allowed: false, reason: "Interpreter -c/-e invocation is blocked" };
174
- }
175
- // Многострочники прячут запрещённые команды после перевода строки.
176
- if (/\r?\n/.test(trimmedCommand)) {
177
- return { allowed: false, reason: "Multi-line commands are blocked" };
178
- }
179
- // Цепочки обходят проверку базовой команды ("echo hi; rm -rf /").
180
- if (/[;&|]/.test(trimmedCommand) &&
181
- /(^|[;&|\s])(rm|del|rd|dd|chmod|chown|wget|curl|nc|netcat|shutdown|reboot|mkfs|fdisk)\b/.test(trimmedCommand)) {
182
- return { allowed: false, reason: "Command chaining to a dangerous command is blocked" };
183
- }
184
- // Опасные операторы — ПЕРЕД разбором базовой команды:
185
- // "curl http://x | bash" ловится, даже если curl не в blacklist.
186
- if (config.blockDangerousFlags) {
187
- for (const op of config.dangerousOperators || []) {
188
- if (containsOperator(trimmedCommand, op)) {
189
- return {
190
- allowed: false,
191
- reason: `Operator "${op}" is not allowed`,
192
- };
193
- }
194
- }
195
- }
196
- // Базовая команда (пути, env, sudo уже учтены)
197
- const baseCommand = extractBaseCommand(trimmedCommand);
198
- // Сравнение регистронезависимо: exec на win32/macOS нечувствителен к регистру,
199
- // `RM -rf x` обязан попасть в blacklist как `rm`.
200
- const blacklistLower = new Set((config.blacklist || []).map((c) => c.toLowerCase()));
201
- const whitelistLower = (config.whitelist || []).map((c) => c.toLowerCase());
202
- // Whitelist сначала (непустой — разрешены только перечисленные)
203
- if (whitelistLower.length > 0) {
204
- if (!whitelistLower.includes(baseCommand.toLowerCase())) {
205
- return {
206
- allowed: false,
207
- reason: `Command "${baseCommand}" is not in the whitelist`,
208
- };
209
- }
210
- }
211
- // Blacklist — по извлечённому basename, не по сырому токену
212
- if (blacklistLower.has(baseCommand.toLowerCase())) {
213
- return {
214
- allowed: false,
215
- reason: `Command "${baseCommand}" is blacklisted`,
216
- };
217
- }
218
- // И сырой первый токен — вдруг это простое имя
219
- const rawFirst = trimmedCommand
220
- .split(/\s+/)[0]
221
- .replace(/^["']+|["']+$/g, "")
222
- .replace(/\.(exe|cmd|bat)$/i, "");
223
- if (rawFirst !== baseCommand && blacklistLower.has(rawFirst.toLowerCase())) {
224
- return {
225
- allowed: false,
226
- reason: `Command "${rawFirst}" is blacklisted`,
227
- };
228
- }
229
- // Опасные флаги
230
- if (config.blockDangerousFlags) {
231
- for (const flag of config.dangerousFlags || []) {
232
- // Флаг целым словом или с equals
233
- const flagPattern = new RegExp(`(?:^|\\s)${flag}(?:\\s|$|=)`);
234
- if (flagPattern.test(trimmedCommand)) {
235
- return {
236
- allowed: false,
237
- reason: `Dangerous flag "${flag}" is not allowed`,
238
- };
239
- }
240
- }
241
- }
242
- // Команда разрешена
243
- return { allowed: true, sanitizedCommand: command };
244
- }
245
- /**
246
- * Санитизация команды для логов (вырезание секретов).
247
- * Те же паттерны, что в sanitizeLogMessage, — для консистентности.
248
- */
249
- export function sanitizeCommandForLog(command) {
250
- // Паттерны из data-sanitizer — для консистентности
251
- const patterns = [
252
- /(api[_-]?key|apikey|api_key)\s*[=:\s]\s*["']?([a-zA-Z0-9_-]{10,})["']?/gi,
253
- /(token|access[_-]?token|auth[_-]?token)\s*[=:\s]\s*["']?([a-zA-Z0-9_-]{10,})["']?/gi,
254
- /(password|passwd|pwd|pass)\s*[=:\s]\s*["']?([^\s"'&]+)["']?/gi,
255
- /(secret|private[_-]?key|secret[_-]?key)\s*[=:\s]\s*["']?([^\s"'&]+)["']?/gi,
256
- /\bsk-[a-zA-Z0-9_-]{20,}\b/gi,
257
- /\bctx7sk-[a-zA-Z0-9_-]{10,}\b/gi,
258
- /\bghp_[a-zA-Z0-9]{30,}\b/gi,
259
- /\bgithub_pat_[a-zA-Z0-9]{20,}\b/gi,
260
- /\bAKIA[0-9A-Z]{15,}\b/gi,
261
- /Bearer\s+[a-zA-Z0-9_-]{20,}/gi,
262
- /\b([a-zA-Z0-9_-]{30,})\b/g,
263
- ];
264
- let sanitized = command;
265
- for (const pattern of patterns) {
266
- // Замена целиком по каждому паттерну: замена с учётом групп
267
- // переизлучила бы сам секрет для паттернов, где группа И ЕСТЬ значение
268
- // (например, "Bearer <token>", sk-...).
269
- sanitized = sanitized.replace(pattern, "[REDACTED]");
270
- }
271
- return sanitized;
272
- }
@@ -1,53 +0,0 @@
1
- /**
2
- * Дефолтные опасные паттерны.
3
- * В списке только реально опасные конструкции. Легитимные рантайм-API
4
- * (process.exit, setTimeout/setInterval, шаблонные литералы `${}`, бэктики)
5
- * НЕ сканируются — это валидный JS/TS, их блок ломает обычный CLI-код.
6
- */
7
- const DEFAULT_DANGEROUS_PATTERNS = [
8
- /eval\(/gi,
9
- /new Function\(/gi,
10
- /child_process\.exec\(/gi,
11
- /child_process\.spawn\(/gi,
12
- /require\('child_process'\)/gi,
13
- /require\('http'\).createServer/gi,
14
- /require\('net'\).createServer/gi,
15
- /require\('fs'\).writeFileSync/gi,
16
- /require\('fs'\).unlinkSync/gi,
17
- /while\(true\)/gi,
18
- /for\(;;\)/gi,
19
- /rm -rf/gi,
20
- /dd if=/gi,
21
- /chmod 777/gi,
22
- /wget.*\|.*sh/gi,
23
- /curl.*\|.*sh/gi,
24
- ];
25
- /**
26
- * Проверить содержимое файла на опасные паттерны.
27
- * Выключенный скан и пустой список паттернов разрешают всё.
28
- */
29
- export function scanContent(content, filePath, config) {
30
- // Выключенный скан разрешает всё
31
- if (!config?.enabled) {
32
- return { allowed: true };
33
- }
34
- // Без своих паттернов — дефолтные
35
- const patterns = config.dangerousPatterns?.length
36
- ? config.dangerousPatterns
37
- : DEFAULT_DANGEROUS_PATTERNS;
38
- const matches = [];
39
- for (const pattern of patterns) {
40
- const match = content.match(pattern);
41
- if (match) {
42
- matches.push(...match);
43
- }
44
- }
45
- if (matches.length > 0) {
46
- return {
47
- allowed: false,
48
- reason: `Content contains dangerous patterns in ${filePath}: ${matches.slice(0, 3).join(", ")}`,
49
- matches,
50
- };
51
- }
52
- return { allowed: true };
53
- }
@@ -1,82 +0,0 @@
1
- // Вырезание секретов (ключи, токены, пароли) из логов, команд и URL.
2
- /** Паттерны чувствительных данных для редактуры в логах. */
3
- const SENSITIVE_PATTERNS = [
4
- // Ключи и токены в формате key=value
5
- {
6
- pattern: /(api[_-]?key|apikey|api_key)\s*[=:\s]\s*["']?([a-zA-Z0-9_-]{10,})["']?/gi,
7
- replacement: "$1=[REDACTED]",
8
- },
9
- {
10
- pattern: /(token|access[_-]?token|auth[_-]?token)\s*[=:\s]\s*["']?([a-zA-Z0-9_-]{10,})["']?/gi,
11
- replacement: "$1=[REDACTED]",
12
- },
13
- {
14
- pattern: /(password|passwd|pwd|pass)\s*[=:\s]\s*["']?([^\s"'&]+)["']?/gi,
15
- replacement: "$1=[REDACTED]",
16
- },
17
- {
18
- pattern: /(secret|private[_-]?key|secret[_-]?key)\s*[=:\s]\s*["']?([^\s"'&]+)["']?/gi,
19
- replacement: "$1=[REDACTED]",
20
- },
21
- // Отдельные ключи (не key=value)
22
- {
23
- pattern: /\bsk-[a-zA-Z0-9_-]{20,}\b/gi,
24
- replacement: "sk-[REDACTED]",
25
- },
26
- {
27
- pattern: /\bctx7sk-[a-zA-Z0-9_-]{10,}\b/gi,
28
- replacement: "ctx7sk-[REDACTED]",
29
- },
30
- {
31
- pattern: /\bghp_[a-zA-Z0-9]{30,}\b/gi,
32
- replacement: "ghp_[REDACTED]",
33
- },
34
- {
35
- pattern: /\bgithub_pat_[a-zA-Z0-9]{20,}\b/gi,
36
- replacement: "github_pat_[REDACTED]",
37
- },
38
- {
39
- pattern: /\bAKIA[0-9A-Z]{15,}\b/gi,
40
- replacement: "AKIA[REDACTED]",
41
- },
42
- // Bearer-токены в заголовках
43
- {
44
- pattern: /Bearer\s+[a-zA-Z0-9_-]{20,}/gi,
45
- replacement: "Bearer [REDACTED]",
46
- },
47
- // Прочие высокоэнтропийные строки, похожие на секреты (30+ символов)
48
- {
49
- pattern: /\b([a-zA-Z0-9_-]{30,})\b/g,
50
- replacement: "[REDACTED]",
51
- },
52
- ];
53
- /** Вычистить секреты из лог-сообщения. */
54
- export function sanitizeLogMessage(message) {
55
- let sanitized = message;
56
- for (const { pattern, replacement } of SENSITIVE_PATTERNS) {
57
- sanitized = sanitized.replace(pattern, replacement);
58
- }
59
- return sanitized;
60
- }
61
- /** Вычистить секреты из командной строки. */
62
- export function sanitizeCommand(command) {
63
- return sanitizeLogMessage(command);
64
- }
65
- /** Вычистить секретные query-параметры из URL; не-URL — как лог-сообщение. */
66
- export function sanitizeUrl(url) {
67
- try {
68
- const urlObj = new URL(url);
69
- const sensitiveKeys = ["api_key", "token", "password", "secret", "access_token", "auth", "key"];
70
- const sanitizedParams = new URLSearchParams(urlObj.search);
71
- for (const key of sensitiveKeys) {
72
- if (sanitizedParams.has(key)) {
73
- sanitizedParams.set(key, "[REDACTED]");
74
- }
75
- }
76
- urlObj.search = sanitizedParams.toString();
77
- return urlObj.toString();
78
- }
79
- catch {
80
- return sanitizeLogMessage(url);
81
- }
82
- }
@@ -1,216 +0,0 @@
1
- // Шифрование секретов конфига: AES-256-CBC + HMAC, ключ в ~/.mma/.encryption-key.
2
- import { createCipheriv, createDecipheriv, randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
3
- import { join } from "path";
4
- import { readFileSync, writeFileSync, existsSync, copyFileSync } from "fs";
5
- import { globalMmaDir } from "../../config/paths";
6
- const DEFAULT_CONFIG = {
7
- keyPath: join(globalMmaDir(), ".encryption-key"),
8
- algorithm: "aes-256-gcm",
9
- };
10
- const IV_LENGTH = 16;
11
- const SALT_LENGTH = 16;
12
- const KEY_LENGTH = 32;
13
- /** Сгенерировать новый ключ шифрования. */
14
- export function generateEncryptionKey() {
15
- return randomBytes(KEY_LENGTH);
16
- }
17
- /** Взять ключ из файла или создать новый. */
18
- export function getOrCreateEncryptionKey(config) {
19
- const { keyPath } = { ...DEFAULT_CONFIG, ...config };
20
- // Каталог обязан существовать
21
- const dir = join(keyPath, "..");
22
- if (!existsSync(dir)) {
23
- // mkdirSync тут нельзя — чистая функция, создаёт вызывающий
24
- }
25
- if (!existsSync(keyPath)) {
26
- const key = generateEncryptionKey();
27
- try {
28
- writeFileSync(keyPath, key.toString("base64"), { mode: 0o600 });
29
- return key;
30
- }
31
- catch (e) {
32
- // Без персиста ключа зашифрованное станет невосстановимым при
33
- // следующем запуске — падаем громко, а не деградируем молча.
34
- throw new Error(`Cannot write encryption key to ${keyPath}: ${errMsg(e)}`);
35
- }
36
- }
37
- try {
38
- const keyBase64 = readFileSync(keyPath, "utf8");
39
- return Buffer.from(keyBase64, "base64");
40
- }
41
- catch {
42
- // Битый ключ бэкапим перед выбросом
43
- try {
44
- const backupPath = `${keyPath}.corrupted.${Date.now()}`;
45
- copyFileSync(keyPath, backupPath);
46
- }
47
- catch {
48
- /* бэкап не удался, идём дальше */
49
- }
50
- throw new Error(`Encryption key file is corrupted or unreadable: ${keyPath}. ` +
51
- `All previously encrypted data will be unrecoverable. ` +
52
- `Delete the key file to generate a new one.`);
53
- }
54
- }
55
- /**
56
- * Зашифровать строку (AES-256-GCM).
57
- * В crypto Bun нет getAuthTag/setAuthTag напрямую, поэтому проще:
58
- * AES-256-CBC + HMAC для аутентификации.
59
- */
60
- export function encryptString(plaintext, key) {
61
- const iv = randomBytes(IV_LENGTH);
62
- const salt = randomBytes(SALT_LENGTH);
63
- // Ключ шифрования и HMAC-ключ выводятся из главного ключа
64
- const encKey = scryptSync(key, salt, KEY_LENGTH);
65
- const hmacSalt = Buffer.concat([salt, Buffer.from([1, 2, 3, 4])]);
66
- const hmacKey = scryptSync(key, hmacSalt, KEY_LENGTH);
67
- // Шифрование AES-256-CBC
68
- const cipher = createCipheriv("aes-256-cbc", encKey, iv);
69
- let encrypted = cipher.update(plaintext, "utf8", "base64");
70
- encrypted += cipher.final("base64");
71
- // HMAC для аутентификации
72
- const hmac = createHmac("sha256", hmacKey);
73
- hmac.update(iv);
74
- hmac.update(Buffer.from(encrypted, "base64"));
75
- const authTag = hmac.digest();
76
- // Формат: salt:iv:authTag:encrypted
77
- return `${salt.toString("base64")}:${iv.toString("base64")}:${authTag.toString("base64")}:${encrypted}`;
78
- }
79
- /** Расшифровать строку (AES-256-CBC + HMAC). */
80
- export function decryptString(encryptedText, key) {
81
- const parts = encryptedText.split(":");
82
- if (parts.length !== 4) {
83
- throw new Error("Invalid encrypted format");
84
- }
85
- const salt = Buffer.from(parts[0], "base64");
86
- const iv = Buffer.from(parts[1], "base64");
87
- const authTag = Buffer.from(parts[2], "base64");
88
- const encrypted = parts[3];
89
- // Ключ шифрования и HMAC-ключ выводятся из главного ключа
90
- const encKey = scryptSync(key, salt, KEY_LENGTH);
91
- const hmacSalt = Buffer.concat([salt, Buffer.from([1, 2, 3, 4])]);
92
- const hmacKey = scryptSync(key, hmacSalt, KEY_LENGTH);
93
- // Проверка HMAC
94
- const hmac = createHmac("sha256", hmacKey);
95
- hmac.update(iv);
96
- hmac.update(Buffer.from(encrypted, "base64"));
97
- const computedTag = hmac.digest();
98
- if (computedTag.length !== authTag.length || !timingSafeEqual(computedTag, authTag)) {
99
- throw new Error("Authentication failed: invalid tag");
100
- }
101
- // Расшифровка AES-256-CBC
102
- const decipher = createDecipheriv("aes-256-cbc", encKey, iv);
103
- let decrypted = decipher.update(encrypted, "base64", "utf8");
104
- decrypted += decipher.final("utf8");
105
- return decrypted;
106
- }
107
- import { createHmac } from "node:crypto";
108
- import { errMsg } from "../../utils";
109
- /** Похоже ли значение на зашифрованное (формат salt:iv:authTag:encrypted). */
110
- export function isEncryptedString(value) {
111
- // Формат: salt:iv:authTag:encrypted, каждая часть — base64 через двоеточие
112
- const parts = value.split(":");
113
- if (parts.length !== 4)
114
- return false;
115
- // Строгая проверка формы base64: Buffer.from(value, "base64") НИКОГДА не бросает
116
- // (ленивое декодирование), так что plaintext от base64 он не отличит.
117
- const isB64 = (s) => s.length > 0 && s.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(s);
118
- return parts.every(isB64);
119
- }
120
- /** Имена чувствительных полей для шифрования. */
121
- export const SENSITIVE_FIELD_NAMES = [
122
- "api_key",
123
- "apikey",
124
- "apiKey",
125
- "token",
126
- "access_token",
127
- "accessToken",
128
- "password",
129
- "passwd",
130
- "pwd",
131
- "secret",
132
- "private_key",
133
- "privateKey",
134
- "auth",
135
- "authorization",
136
- "key",
137
- ];
138
- /** Имя поля указывает на чувствительные данные или нет. */
139
- export function isSensitiveFieldName(fieldName) {
140
- const lowerFieldName = fieldName.toLowerCase();
141
- return SENSITIVE_FIELD_NAMES.some((name) => lowerFieldName.includes(name));
142
- }
143
- /** Зашифровать чувствительные поля объекта (рекурсивно, RegExp не трогает). */
144
- export function encryptSensitiveFields(obj, key) {
145
- const result = {};
146
- for (const [fieldName, value] of Object.entries(obj)) {
147
- if (isSensitiveFieldName(fieldName) && typeof value === "string" && !isEncryptedString(value)) {
148
- result[fieldName] = encryptString(value, key);
149
- }
150
- else if (typeof value === "object" && value !== null) {
151
- if (Array.isArray(value)) {
152
- result[fieldName] = value.map((item) => typeof item === "object" && item !== null && !(item instanceof RegExp)
153
- ? encryptSensitiveFields(item, key)
154
- : item);
155
- }
156
- else if (value instanceof RegExp) {
157
- result[fieldName] = value;
158
- }
159
- else {
160
- result[fieldName] = encryptSensitiveFields(value, key);
161
- }
162
- }
163
- else {
164
- result[fieldName] = value;
165
- }
166
- }
167
- return result;
168
- }
169
- /** Расшифровать чувствительные поля объекта; неудача — оставить как есть. */
170
- export function decryptSensitiveFields(obj, key) {
171
- const result = {};
172
- for (const [fieldName, value] of Object.entries(obj)) {
173
- if (isSensitiveFieldName(fieldName) && typeof value === "string" && isEncryptedString(value)) {
174
- try {
175
- result[fieldName] = decryptString(value, key);
176
- }
177
- catch {
178
- // Расшифровка не удалась — оставить зашифрованное значение
179
- result[fieldName] = value;
180
- }
181
- }
182
- else if (typeof value === "object" && value !== null) {
183
- if (Array.isArray(value)) {
184
- result[fieldName] = value.map((item) => typeof item === "object" && item !== null && !(item instanceof RegExp)
185
- ? decryptSensitiveFields(item, key)
186
- : item);
187
- }
188
- else if (value instanceof RegExp) {
189
- result[fieldName] = value;
190
- }
191
- else {
192
- result[fieldName] = decryptSensitiveFields(value, key);
193
- }
194
- }
195
- else {
196
- result[fieldName] = value;
197
- }
198
- }
199
- return result;
200
- }
201
- /** Обёртка шифрования/расшифровки значений конфига. */
202
- export class ConfigEncryptor {
203
- key;
204
- constructor(config) {
205
- this.key = getOrCreateEncryptionKey(config);
206
- }
207
- encrypt(config) {
208
- return encryptSensitiveFields(config, this.key);
209
- }
210
- decrypt(config) {
211
- return decryptSensitiveFields(config, this.key);
212
- }
213
- getKey() {
214
- return this.key;
215
- }
216
- }
@@ -1,15 +0,0 @@
1
- // Публичный фасад модуля безопасности: валидаторы, аудит, шифрование, политики.
2
- export * from "./command-validator";
3
- export * from "./path-validator";
4
- export * from "./network-validator";
5
- export * from "./content-scanner";
6
- export * from "./data-sanitizer";
7
- export * from "./audit-log";
8
- export * from "./rate-limiter";
9
- export * from "./encryption";
10
- export * from "./session-isolation";
11
- export * from "./session-encryption";
12
- export * from "./audit-notifier";
13
- export * from "./security-policies";
14
- // Реэкспорт sanitizeUrl из network-validator — единый источник (без конфликтов)
15
- export { sanitizeUrl } from "./network-validator";