micro-models-agent 2.16.0 → 2.17.1
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.
- package/CHANGELOG.md +34 -0
- package/dist/assets/app.js +1 -314
- package/dist/assets/hljs.js +5 -1244
- package/dist/assets/index.html +11 -0
- package/dist/assets/js/api.js +1 -28
- package/dist/assets/js/core/menus.js +1 -0
- package/dist/assets/js/core/store/feed.js +1 -0
- package/dist/assets/js/core/store/index.js +1 -0
- package/dist/assets/js/core/store/session.js +1 -0
- package/dist/assets/js/core/store/settings.js +1 -0
- package/dist/assets/js/core/store/tabs.js +1 -0
- package/dist/assets/js/dialog.js +1 -105
- package/dist/assets/js/dom.js +1 -178
- package/dist/assets/js/feed/core.js +1 -0
- package/dist/assets/js/feed/history.js +1 -0
- package/dist/assets/js/feed/plan.js +1 -0
- package/dist/assets/js/feed/question.js +3 -0
- package/dist/assets/js/feed/sidebar.js +1 -0
- package/dist/assets/js/feed/stream.js +1 -0
- package/dist/assets/js/feed/turn.js +5 -0
- package/dist/assets/js/feed.js +1 -1211
- package/dist/assets/js/format.js +2 -122
- package/dist/assets/js/i18n.js +1 -46
- package/dist/assets/js/rail.js +1 -114
- package/dist/assets/js/session/cmdk.js +1 -0
- package/dist/assets/js/session/composer.js +1 -0
- package/dist/assets/js/session/sessions-menu.js +1 -0
- package/dist/assets/js/session/tabs.js +1 -0
- package/dist/assets/js/settings/controls.js +1 -0
- package/dist/assets/js/settings/editors.js +1 -0
- package/dist/assets/js/settings/form.js +1 -0
- package/dist/assets/js/settings/modal.js +1 -0
- package/dist/assets/js/settings/panels.js +1 -0
- package/dist/assets/js/settings/providers.js +1 -0
- package/dist/assets/js/settings/search.js +1 -0
- package/dist/assets/js/settings/subdialog.js +1 -0
- package/dist/assets/js/settings/write.js +1 -0
- package/dist/assets/js/settings.js +1 -1914
- package/dist/assets/js/sidebar/core.js +1 -0
- package/dist/assets/js/sidebar/lsp.js +2 -0
- package/dist/assets/js/sidebar/map.js +1 -0
- package/dist/assets/js/sidebar/state.js +1 -0
- package/dist/assets/js/sidebar/trace.js +5 -0
- package/dist/assets/js/sidebar.js +1 -705
- package/dist/assets/js/store.js +1 -82
- package/dist/assets/js/subdialog.js +1 -0
- package/dist/assets/md.js +1 -277
- package/dist/assets/setup.js +3 -816
- package/dist/assets/smd.js +29 -1665
- package/dist/assets/styles.css +1 -1592
- package/dist/certification/certifications.json +1 -494
- package/dist/i18n/en.json +1 -1851
- package/dist/i18n/ru.json +1 -1854
- package/dist/main.js +815 -55797
- package/dist/modules/browser/bridge-server.mjs +2 -252
- package/package.json +10 -5
- package/dist/assets/js/settings-controls.js +0 -452
- package/dist/assets/js/tabs.js +0 -867
- package/dist/cli/cache-line.js +0 -31
- package/dist/cli/command-suggest.js +0 -39
- package/dist/cli/commands.js +0 -781
- package/dist/cli/completer.js +0 -268
- package/dist/cli/index.js +0 -3
- package/dist/cli/json-payload.js +0 -32
- package/dist/cli/main.js +0 -346
- package/dist/cli/onboarding-commands.js +0 -126
- package/dist/cli/plugin-commands.js +0 -38
- package/dist/cli/relaunch.js +0 -40
- package/dist/cli/repl-commands-lsp.js +0 -75
- package/dist/cli/repl-commands-skills.js +0 -105
- package/dist/cli/repl-commands.js +0 -1218
- package/dist/cli/repl.js +0 -1238
- package/dist/cli/run-result.js +0 -38
- package/dist/cli/security-commands.js +0 -177
- package/dist/cli/setup-order.js +0 -6
- package/dist/cli/setup-prompt.js +0 -50
- package/dist/cli/setup.js +0 -161
- package/dist/cli/web-command.js +0 -98
- package/dist/config/budget.js +0 -48
- package/dist/config/config.js +0 -345
- package/dist/config/defaults.js +0 -197
- package/dist/config/domains.js +0 -135
- package/dist/config/env.js +0 -46
- package/dist/config/experts.js +0 -17
- package/dist/config/index.js +0 -5
- package/dist/config/paths.js +0 -56
- package/dist/config/redact.js +0 -44
- package/dist/config/registry-extra.js +0 -334
- package/dist/config/registry.js +0 -584
- package/dist/config/security.js +0 -212
- package/dist/config/timeouts.js +0 -74
- package/dist/config/types.js +0 -1
- package/dist/config/utils.js +0 -57
- package/dist/core/agent/artifact-progress.js +0 -59
- package/dist/core/agent/artifact-resolve.js +0 -79
- package/dist/core/agent/audit-gate.js +0 -53
- package/dist/core/agent/compaction.js +0 -89
- package/dist/core/agent/constants.js +0 -90
- package/dist/core/agent/context-log.js +0 -454
- package/dist/core/agent/context-renderer.js +0 -45
- package/dist/core/agent/critic-gate.js +0 -132
- package/dist/core/agent/hallucination-gate.js +0 -197
- package/dist/core/agent/loop-state.js +0 -68
- package/dist/core/agent/prefix-monitor.js +0 -101
- package/dist/core/agent/reasoning-resolver.js +0 -65
- package/dist/core/agent/token-tracker.js +0 -99
- package/dist/core/agent/tool-batch.js +0 -312
- package/dist/core/agent/tool-images.js +0 -18
- package/dist/core/agent/tool-output.js +0 -116
- package/dist/core/agent/tool-pairing.js +0 -60
- package/dist/core/agent-moe.js +0 -248
- package/dist/core/agent.js +0 -1299
- package/dist/core/bootstrap/agent-phase.js +0 -66
- package/dist/core/bootstrap/config-phase.js +0 -86
- package/dist/core/bootstrap/modules-phase.js +0 -269
- package/dist/core/bootstrap/provider-phase.js +0 -183
- package/dist/core/bootstrap/session-phase.js +0 -204
- package/dist/core/bootstrap/state.js +0 -94
- package/dist/core/bootstrap/workspace-phase.js +0 -115
- package/dist/core/bootstrap.js +0 -112
- package/dist/core/crash-handler.js +0 -62
- package/dist/core/environment.js +0 -224
- package/dist/core/host-plan.js +0 -43
- package/dist/core/host.js +0 -23
- package/dist/core/index.js +0 -3
- package/dist/core/prompt-builder.js +0 -95
- package/dist/core/prompt-overflow.js +0 -306
- package/dist/core/session-logger.js +0 -375
- package/dist/core/system-prompt.js +0 -117
- package/dist/core/types.js +0 -1
- package/dist/core/version.js +0 -28
- package/dist/core/web-host.js +0 -34
- package/dist/core/workspace.js +0 -80
- package/dist/i18n/index.js +0 -80
- package/dist/index.js +0 -30
- package/dist/llm/cache-usage.js +0 -76
- package/dist/llm/image-utils.js +0 -138
- package/dist/llm/index.js +0 -4
- package/dist/llm/llm-errors.js +0 -50
- package/dist/llm/model-loader.js +0 -86
- package/dist/llm/models-dev.js +0 -121
- package/dist/llm/openai-compat.js +0 -756
- package/dist/llm/orchestrator.js +0 -294
- package/dist/llm/provider-budget.js +0 -68
- package/dist/llm/provider-context.js +0 -233
- package/dist/llm/provider.js +0 -9
- package/dist/llm/response.js +0 -44
- package/dist/llm/stream-state.js +0 -26
- package/dist/llm/token-counter.js +0 -83
- package/dist/llm/types.js +0 -1
- package/dist/logger/app-logger.js +0 -212
- package/dist/logger/file-log.js +0 -160
- package/dist/logger/index.js +0 -2
- package/dist/migration/backup.js +0 -56
- package/dist/migration/detect.js +0 -61
- package/dist/migration/index.js +0 -3
- package/dist/modules/artifacts/store.js +0 -62
- package/dist/modules/browser/actions.js +0 -79
- package/dist/modules/browser/bridge-client.js +0 -203
- package/dist/modules/browser/bridge-path.js +0 -10
- package/dist/modules/browser/console-buffer.js +0 -37
- package/dist/modules/browser/cookie-store.js +0 -29
- package/dist/modules/browser/driver-types.js +0 -1
- package/dist/modules/browser/driver.js +0 -186
- package/dist/modules/browser/index.js +0 -9
- package/dist/modules/browser/module.js +0 -30
- package/dist/modules/browser/session.js +0 -322
- package/dist/modules/browser/snapshot.js +0 -154
- package/dist/modules/browser/types.js +0 -13
- package/dist/modules/certification/cli.js +0 -264
- package/dist/modules/certification/fact-checker.js +0 -90
- package/dist/modules/certification/loader.js +0 -127
- package/dist/modules/certification/manifest.js +0 -231
- package/dist/modules/certification/runner.js +0 -233
- package/dist/modules/certification/scenarios.js +0 -586
- package/dist/modules/certification/syntax-scenarios.js +0 -50
- package/dist/modules/certification/types.js +0 -1
- package/dist/modules/context/chunk-query.js +0 -122
- package/dist/modules/context/fact-extractor.js +0 -170
- package/dist/modules/context/history.js +0 -15
- package/dist/modules/context/index.js +0 -2
- package/dist/modules/context/manager.js +0 -482
- package/dist/modules/critic/client.js +0 -176
- package/dist/modules/critic/evidence.js +0 -81
- package/dist/modules/critic/provider.js +0 -45
- package/dist/modules/critic/tools.js +0 -78
- package/dist/modules/critic/types.js +0 -1
- package/dist/modules/execution/audit-runners.js +0 -206
- package/dist/modules/execution/auditor.js +0 -222
- package/dist/modules/execution/execution-plugin.js +0 -478
- package/dist/modules/execution/index.js +0 -8
- package/dist/modules/execution/input-from.js +0 -70
- package/dist/modules/execution/module.js +0 -891
- package/dist/modules/execution/moe-executor.js +0 -443
- package/dist/modules/execution/plan-actions.js +0 -642
- package/dist/modules/execution/plan-checks.js +0 -35
- package/dist/modules/execution/plan-coverage.js +0 -71
- package/dist/modules/execution/plan-persister.js +0 -46
- package/dist/modules/execution/plan-steps.js +0 -31
- package/dist/modules/execution/plan-store.js +0 -274
- package/dist/modules/execution/plan-tool.js +0 -249
- package/dist/modules/execution/plan-validator.js +0 -197
- package/dist/modules/execution/planner.js +0 -103
- package/dist/modules/execution/stuck-detector.js +0 -834
- package/dist/modules/execution/tracker.js +0 -92
- package/dist/modules/execution/transient-error.js +0 -30
- package/dist/modules/execution/types.js +0 -1
- package/dist/modules/execution/verifier.js +0 -343
- package/dist/modules/execution/windows-commands.js +0 -52
- package/dist/modules/hallucination/artifact-claim.js +0 -93
- package/dist/modules/hallucination/confidence.js +0 -81
- package/dist/modules/hallucination/consistency.js +0 -37
- package/dist/modules/hallucination/detector.js +0 -57
- package/dist/modules/hallucination/factual.js +0 -205
- package/dist/modules/hallucination/index.js +0 -6
- package/dist/modules/hallucination/js-identifiers.js +0 -261
- package/dist/modules/hallucination/llm-judge.js +0 -116
- package/dist/modules/hallucination/success-claim.js +0 -59
- package/dist/modules/index.js +0 -5
- package/dist/modules/indexer/cache.js +0 -88
- package/dist/modules/indexer/index.js +0 -4
- package/dist/modules/indexer/map-command.js +0 -33
- package/dist/modules/indexer/map-select.js +0 -87
- package/dist/modules/indexer/module.js +0 -293
- package/dist/modules/indexer/project-profile.js +0 -184
- package/dist/modules/indexer/symbols.js +0 -189
- package/dist/modules/indexer/walker.js +0 -285
- package/dist/modules/lsp/check-tool.js +0 -61
- package/dist/modules/lsp/client.js +0 -406
- package/dist/modules/lsp/command.js +0 -53
- package/dist/modules/lsp/config.js +0 -189
- package/dist/modules/lsp/index.js +0 -4
- package/dist/modules/lsp/module.js +0 -295
- package/dist/modules/lsp/probe.js +0 -86
- package/dist/modules/lsp/project-root.js +0 -69
- package/dist/modules/lsp/startup-check.js +0 -154
- package/dist/modules/lsp/types.js +0 -1
- package/dist/modules/mcp/client.js +0 -445
- package/dist/modules/mcp/index.js +0 -4
- package/dist/modules/mcp/module.js +0 -295
- package/dist/modules/mcp/registry.js +0 -20
- package/dist/modules/memory/index.js +0 -2
- package/dist/modules/memory/module.js +0 -101
- package/dist/modules/memory/search.js +0 -45
- package/dist/modules/memory/store.js +0 -107
- package/dist/modules/onboarding/init.js +0 -47
- package/dist/modules/onboarding/meet.js +0 -30
- package/dist/modules/onboarding/mode.js +0 -30
- package/dist/modules/onboarding/prompts.js +0 -43
- package/dist/modules/pipelines/engine.js +0 -70
- package/dist/modules/pipelines/index.js +0 -4
- package/dist/modules/pipelines/parser.js +0 -59
- package/dist/modules/pipelines/template.js +0 -18
- package/dist/modules/plugins/builtin/lint-on-write.js +0 -377
- package/dist/modules/plugins/builtin/notify.js +0 -11
- package/dist/modules/plugins/index.js +0 -2
- package/dist/modules/plugins/loader.js +0 -85
- package/dist/modules/plugins/manager.js +0 -244
- package/dist/modules/plugins/types.js +0 -1
- package/dist/modules/pricing/index.js +0 -70
- package/dist/modules/pricing/prices.js +0 -147
- package/dist/modules/processes/detect.js +0 -34
- package/dist/modules/processes/index.js +0 -4
- package/dist/modules/processes/kill-tree.js +0 -52
- package/dist/modules/processes/registry.js +0 -294
- package/dist/modules/processes/runner.js +0 -23
- package/dist/modules/providers/cache.js +0 -23
- package/dist/modules/providers/capabilities.js +0 -28
- package/dist/modules/providers/create.js +0 -21
- package/dist/modules/providers/factory.js +0 -28
- package/dist/modules/providers/fallback.js +0 -81
- package/dist/modules/providers/health.js +0 -47
- package/dist/modules/providers/index.js +0 -6
- package/dist/modules/providers/manager.js +0 -207
- package/dist/modules/providers/naming.js +0 -15
- package/dist/modules/providers/preflight.js +0 -71
- package/dist/modules/providers/presets.js +0 -232
- package/dist/modules/providers/registry.js +0 -27
- package/dist/modules/providers/types.js +0 -1
- package/dist/modules/reasoning/policy.js +0 -42
- package/dist/modules/reasoning/probe.js +0 -116
- package/dist/modules/registry.js +0 -48
- package/dist/modules/security/audit-log.js +0 -119
- package/dist/modules/security/audit-notifier.js +0 -267
- package/dist/modules/security/command-validator.js +0 -272
- package/dist/modules/security/content-scanner.js +0 -53
- package/dist/modules/security/data-sanitizer.js +0 -82
- package/dist/modules/security/encryption.js +0 -216
- package/dist/modules/security/index.js +0 -15
- package/dist/modules/security/network-validator.js +0 -236
- package/dist/modules/security/path-validator.js +0 -261
- package/dist/modules/security/protected-paths.js +0 -73
- package/dist/modules/security/rate-limiter.js +0 -98
- package/dist/modules/security/security-policies.js +0 -499
- package/dist/modules/security/session-encryption.js +0 -182
- package/dist/modules/security/session-isolation.js +0 -75
- package/dist/modules/session/auto-name.js +0 -63
- package/dist/modules/session/export.js +0 -98
- package/dist/modules/session/index.js +0 -4
- package/dist/modules/session/manager.js +0 -234
- package/dist/modules/session/module.js +0 -33
- package/dist/modules/session/store.js +0 -295
- package/dist/modules/session/types.js +0 -1
- package/dist/modules/setup/answers.js +0 -35
- package/dist/modules/setup/apply.js +0 -79
- package/dist/modules/setup/discovery.js +0 -72
- package/dist/modules/skills/index.js +0 -3
- package/dist/modules/skills/loader.js +0 -86
- package/dist/modules/skills/matcher.js +0 -27
- package/dist/modules/skills/module.js +0 -141
- package/dist/modules/types.js +0 -1
- package/dist/modules/updater/changelog-reader.js +0 -93
- package/dist/modules/updater/checker.js +0 -101
- package/dist/modules/updater/dev-detect.js +0 -18
- package/dist/modules/updater/index.js +0 -4
- package/dist/modules/updater/module.js +0 -129
- package/dist/modules/user-profile/compressor.js +0 -18
- package/dist/modules/user-profile/index.js +0 -2
- package/dist/modules/user-profile/profile.js +0 -77
- package/dist/modules/webui/answer-api.js +0 -29
- package/dist/modules/webui/assets.js +0 -50
- package/dist/modules/webui/body.js +0 -21
- package/dist/modules/webui/commands-settings.js +0 -209
- package/dist/modules/webui/commands-shared.js +0 -60
- package/dist/modules/webui/commands.js +0 -174
- package/dist/modules/webui/config-api.js +0 -134
- package/dist/modules/webui/file-api.js +0 -202
- package/dist/modules/webui/forward.js +0 -159
- package/dist/modules/webui/history-api.js +0 -112
- package/dist/modules/webui/host-state.js +0 -60
- package/dist/modules/webui/i18n-api.js +0 -9
- package/dist/modules/webui/limits.js +0 -6
- package/dist/modules/webui/log-forward.js +0 -20
- package/dist/modules/webui/memory-commands.js +0 -64
- package/dist/modules/webui/model-cache.js +0 -18
- package/dist/modules/webui/module.js +0 -148
- package/dist/modules/webui/persist.js +0 -24
- package/dist/modules/webui/prompt-io.js +0 -97
- package/dist/modules/webui/providers-api.js +0 -337
- package/dist/modules/webui/providers-view.js +0 -56
- package/dist/modules/webui/reasoning-view.js +0 -15
- package/dist/modules/webui/run-agent.js +0 -81
- package/dist/modules/webui/server.js +0 -284
- package/dist/modules/webui/sessions-api.js +0 -178
- package/dist/modules/webui/settings-api.js +0 -561
- package/dist/modules/webui/setup-api.js +0 -201
- package/dist/modules/webui/state.js +0 -74
- package/dist/modules/webui/util.js +0 -261
- package/dist/output/bus.js +0 -37
- package/dist/output/channel.js +0 -285
- package/dist/output/format.js +0 -15
- package/dist/output/index.js +0 -8
- package/dist/output/json-sink.js +0 -24
- package/dist/output/machine.js +0 -9
- package/dist/output/session-sink.js +0 -27
- package/dist/output/types.js +0 -1
- package/dist/tools/approve.js +0 -41
- package/dist/tools/attach-image.js +0 -102
- package/dist/tools/auto-fixer.js +0 -180
- package/dist/tools/auto-tags.js +0 -83
- package/dist/tools/bash.js +0 -649
- package/dist/tools/browser.js +0 -160
- package/dist/tools/chunk-query.js +0 -112
- package/dist/tools/create-dir.js +0 -60
- package/dist/tools/delete-file.js +0 -67
- package/dist/tools/download-file.js +0 -142
- package/dist/tools/edit-file.js +0 -136
- package/dist/tools/enable-tools.js +0 -59
- package/dist/tools/executor.js +0 -304
- package/dist/tools/file-info.js +0 -49
- package/dist/tools/filter-tools.js +0 -17
- package/dist/tools/glob-tool.js +0 -37
- package/dist/tools/grep-tool.js +0 -142
- package/dist/tools/hidden-tools-block.js +0 -37
- package/dist/tools/index.js +0 -88
- package/dist/tools/list-dir.js +0 -53
- package/dist/tools/load-skill.js +0 -51
- package/dist/tools/mcp-call.js +0 -80
- package/dist/tools/meet-done.js +0 -14
- package/dist/tools/move-file.js +0 -94
- package/dist/tools/path-utils.js +0 -108
- package/dist/tools/pipeline-run.js +0 -167
- package/dist/tools/preview.js +0 -2
- package/dist/tools/process-ids.js +0 -31
- package/dist/tools/process-kill.js +0 -33
- package/dist/tools/process-list.js +0 -38
- package/dist/tools/process-log.js +0 -49
- package/dist/tools/process-wait.js +0 -63
- package/dist/tools/prompt-io.js +0 -29
- package/dist/tools/question.js +0 -288
- package/dist/tools/read-file.js +0 -200
- package/dist/tools/recall.js +0 -124
- package/dist/tools/registry.js +0 -48
- package/dist/tools/remember.js +0 -72
- package/dist/tools/scope-check.js +0 -32
- package/dist/tools/scope-request.js +0 -96
- package/dist/tools/search-history.js +0 -88
- package/dist/tools/session-info.js +0 -46
- package/dist/tools/set-thinking.js +0 -75
- package/dist/tools/subagent.js +0 -257
- package/dist/tools/syntax-validator.js +0 -379
- package/dist/tools/types.js +0 -1
- package/dist/tools/user-input.js +0 -134
- package/dist/tools/web-browse.js +0 -93
- package/dist/tools/web-fetch.js +0 -108
- package/dist/tools/web-search.js +0 -107
- package/dist/tools/write-file.js +0 -128
- package/dist/ui/action-log.js +0 -13
- package/dist/ui/box.js +0 -78
- package/dist/ui/colors.js +0 -6
- package/dist/ui/diff.js +0 -189
- package/dist/ui/index.js +0 -7
- package/dist/ui/line-editor.js +0 -1083
- package/dist/ui/line-math.js +0 -98
- package/dist/ui/md-formatter.js +0 -322
- package/dist/ui/output.js +0 -19
- package/dist/ui/plan-view.js +0 -109
- package/dist/ui/renderer.js +0 -589
- package/dist/ui/spinner.js +0 -91
- package/dist/ui/table.js +0 -142
- package/dist/ui/theme.js +0 -143
- package/dist/utils/child-run.js +0 -20
- package/dist/utils/error.js +0 -4
- package/dist/utils/index.js +0 -6
- package/dist/utils/retry.js +0 -17
- package/dist/utils/sleep.js +0 -23
- 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";
|