@sayknow-cli/coding-agent 0.7.11 → 0.7.13
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 +16 -0
- package/dist/types/async/result-formatting.d.ts +2 -0
- package/dist/types/capability/fs.d.ts +22 -3
- package/dist/types/capability/mcp.d.ts +2 -0
- package/dist/types/cli/append-system-prompt.d.ts +6 -0
- package/dist/types/cli/update-cli.d.ts +3 -0
- package/dist/types/commands/contribution-prep.d.ts +0 -3
- package/dist/types/commands/migrate.d.ts +1 -1
- package/dist/types/commands/sdk.d.ts +9 -0
- package/dist/types/commit/changelog/index.d.ts +1 -0
- package/dist/types/config/settings-schema.d.ts +14 -0
- package/dist/types/config/settings.d.ts +7 -1
- package/dist/types/coordinator-mcp/session-reaper.d.ts +5 -0
- package/dist/types/cursor-delete-path.d.ts +1 -0
- package/dist/types/cursor-mcp-name.d.ts +8 -0
- package/dist/types/dap/config.d.ts +8 -4
- package/dist/types/dap/session.d.ts +11 -2
- package/dist/types/debug/report-bundle-parent.d.ts +2 -0
- package/dist/types/debug/system-info.d.ts +6 -1
- package/dist/types/discovery/helpers.d.ts +11 -3
- package/dist/types/discovery/mcp-json.d.ts +1 -0
- package/dist/types/edit/file-read-cache.d.ts +4 -0
- package/dist/types/edit/modes/patch.d.ts +14 -0
- package/dist/types/edit/modes/replace.d.ts +8 -0
- package/dist/types/eval/py/runtime.d.ts +9 -0
- package/dist/types/exa/mcp-client.d.ts +11 -6
- package/dist/types/exec/bash-executor.d.ts +18 -1
- package/dist/types/export/html/css-color.d.ts +2 -0
- package/dist/types/export/html/html-export-destination.d.ts +2 -0
- package/dist/types/export/html/template.generated.d.ts +1 -1
- package/dist/types/extensibility/custom-tools/loader.d.ts +3 -2
- package/dist/types/extensibility/custom-tools/types.d.ts +3 -1
- package/dist/types/extensibility/plugins/marketplace/cache.d.ts +2 -0
- package/dist/types/extensibility/plugins/plugin-link-path.d.ts +2 -0
- package/dist/types/goals/runtime.d.ts +6 -0
- package/dist/types/harness-control-plane/receipt-spool.d.ts +4 -0
- package/dist/types/hindsight/content.d.ts +5 -6
- package/dist/types/internal-urls/skill-path.d.ts +1 -0
- package/dist/types/internal-urls/types.d.ts +2 -0
- package/dist/types/lsp/clients/swiftlint-client.d.ts +0 -4
- package/dist/types/lsp/config.d.ts +8 -5
- package/dist/types/lsp/workspace-path.d.ts +1 -0
- package/dist/types/migrate/adapters/codex.d.ts +2 -1
- package/dist/types/migrate/adapters/index.d.ts +10 -1
- package/dist/types/migrate/executor.d.ts +3 -1
- package/dist/types/migrate/types.d.ts +15 -3
- package/dist/types/modes/components/custom-editor.d.ts +6 -0
- package/dist/types/modes/components/extensions/state-manager.d.ts +4 -3
- package/dist/types/modes/components/model-selector.d.ts +46 -0
- package/dist/types/modes/controllers/input-controller.d.ts +9 -0
- package/dist/types/modes/interactive-mode.d.ts +1 -0
- package/dist/types/modes/utils/macos-option-forwarding.d.ts +17 -0
- package/dist/types/runtime-mcp/content-limits.d.ts +4 -0
- package/dist/types/runtime-mcp/manager.d.ts +9 -1
- package/dist/types/runtime-mcp/mcp-redirect.d.ts +9 -0
- package/dist/types/runtime-mcp/oauth-public-url.d.ts +1 -0
- package/dist/types/runtime-mcp/plugin-mcp-name-filter.d.ts +22 -0
- package/dist/types/runtime-mcp/plugin-network-boundary.d.ts +1 -0
- package/dist/types/runtime-mcp/project-host-values.d.ts +33 -0
- package/dist/types/runtime-mcp/smithery-registry.d.ts +24 -0
- package/dist/types/runtime-mcp/tool-bridge.d.ts +4 -0
- package/dist/types/runtime-mcp/types.d.ts +6 -0
- package/dist/types/sdk/broker/ensure.d.ts +2 -0
- package/dist/types/sdk/broker/lifecycle-ledger.d.ts +5 -1
- package/dist/types/sdk/broker/runtime.d.ts +1 -1
- package/dist/types/sdk/bus/chat-daemon-control.d.ts +3 -1
- package/dist/types/sdk/bus/telegram-daemon-contract.d.ts +3 -1
- package/dist/types/sdk/bus/telegram-daemon.d.ts +1 -0
- package/dist/types/sdk/host/events.d.ts +4 -0
- package/dist/types/session/agent-session.d.ts +22 -2
- package/dist/types/session/auto-resume.d.ts +5 -0
- package/dist/types/session/messages.d.ts +5 -1
- package/dist/types/session/session-manager.d.ts +13 -0
- package/dist/types/session/session-storage.d.ts +8 -0
- package/dist/types/session/streaming-output.d.ts +11 -0
- package/dist/types/session-import/redact.d.ts +1 -1
- package/dist/types/skc-runtime/managed-owner-admission.d.ts +3 -0
- package/dist/types/skc-runtime/psmux-detect.d.ts +5 -4
- package/dist/types/skc-runtime/ralplan-runtime.d.ts +5 -0
- package/dist/types/skc-runtime/sidecar-bootstrap-env.d.ts +6 -0
- package/dist/types/skc-runtime/state-writer.d.ts +4 -1
- package/dist/types/skc-runtime/tmux-sessions.d.ts +24 -0
- package/dist/types/skc-runtime/ultragoal-runtime.d.ts +4 -0
- package/dist/types/skill-state/workflow-mutation-guard.d.ts +20 -1
- package/dist/types/slash-commands/helpers/mcp.d.ts +5 -0
- package/dist/types/ssh/ssh-executor.d.ts +3 -1
- package/dist/types/system-prompt.d.ts +5 -2
- package/dist/types/task/executor.d.ts +17 -3
- package/dist/types/task/isolation-dir.d.ts +26 -0
- package/dist/types/task/role-body.d.ts +11 -0
- package/dist/types/task/token-log-mode.test.d.ts +1 -0
- package/dist/types/tools/ask.d.ts +77 -254
- package/dist/types/tools/ast-edit-write-path.d.ts +23 -0
- package/dist/types/tools/atomic-file-write.d.ts +74 -0
- package/dist/types/tools/auto-generated-guard.d.ts +5 -2
- package/dist/types/tools/bash-allowed-prefixes.d.ts +16 -0
- package/dist/types/tools/bash-interactive.d.ts +2 -0
- package/dist/types/tools/bash-skill-urls.d.ts +5 -1
- package/dist/types/tools/bash.d.ts +1 -0
- package/dist/types/tools/browser/cdp-url.d.ts +2 -0
- package/dist/types/tools/browser/tab-worker.d.ts +2 -0
- package/dist/types/tools/debug.d.ts +2 -2
- package/dist/types/tools/explicit-artifact.d.ts +8 -0
- package/dist/types/tools/fetch.d.ts +7 -4
- package/dist/types/tools/github-side-effect.d.ts +22 -0
- package/dist/types/tools/index.d.ts +3 -0
- package/dist/types/tools/monitor-mutation.d.ts +9 -0
- package/dist/types/tools/recipe/index.d.ts +2 -0
- package/dist/types/tools/recipe/recipe-guard.d.ts +7 -0
- package/dist/types/tools/restricted-cwd.d.ts +1 -0
- package/dist/types/tools/reverse-engineer.d.ts +81 -0
- package/dist/types/tools/search-tool-bm25.d.ts +2 -0
- package/dist/types/tools/tmux-self-injection-guard.d.ts +17 -0
- package/dist/types/tools/untrusted-content.d.ts +12 -0
- package/dist/types/utils/file-mentions.d.ts +5 -0
- package/dist/types/utils/open.d.ts +0 -1
- package/dist/types/utils/shell-snapshot.d.ts +2 -0
- package/dist/types/utils/title-generator.d.ts +12 -2
- package/dist/types/utils/tools-checksum.d.ts +7 -0
- package/dist/types/utils/xml-escape.d.ts +2 -0
- package/dist/types/web/scrapers/types.d.ts +8 -1
- package/dist/types/web/search/providers/codex.d.ts +6 -7
- package/dist/types/web/search/providers/insane.d.ts +7 -1
- package/dist/types/web/search/providers/kimi.d.ts +2 -0
- package/dist/types/web/search/providers/searxng.d.ts +7 -0
- package/dist/types/web/search/providers/xai.d.ts +2 -0
- package/package.json +7 -7
- package/scripts/generate-sdk-operation-inventory.ts +4 -0
- package/src/async/job-manager.ts +23 -9
- package/src/async/result-formatting.ts +40 -0
- package/src/capability/fs.ts +78 -11
- package/src/capability/mcp.ts +2 -0
- package/src/cli/append-system-prompt.ts +12 -0
- package/src/cli/auth-broker-cli.ts +22 -12
- package/src/cli/config-cli.ts +8 -18
- package/src/cli/migrate-cli.ts +7 -5
- package/src/cli/ssh-cli.ts +6 -3
- package/src/cli/stats-cli.ts +9 -4
- package/src/cli/update-cli.ts +42 -0
- package/src/cli/web-search-cli.ts +9 -3
- package/src/cli.ts +5 -9
- package/src/commands/commit.ts +2 -2
- package/src/commands/contribution-prep.ts +1 -3
- package/src/commands/harness.ts +25 -15
- package/src/commands/launch.ts +1 -1
- package/src/commands/migrate.ts +3 -3
- package/src/commands/sdk.ts +115 -14
- package/src/commands/ultragoal.ts +14 -8
- package/src/commit/agentic/agent.ts +6 -6
- package/src/commit/analysis/conventional.ts +14 -5
- package/src/commit/changelog/index.ts +39 -1
- package/src/commit/message.ts +10 -3
- package/src/config/config-file.ts +106 -3
- package/src/config/keybindings.ts +154 -7
- package/src/config/mcp-schema.json +4 -0
- package/src/config/model-registry.ts +10 -2
- package/src/config/settings-schema.ts +18 -0
- package/src/config/settings.ts +32 -4
- package/src/coordinator-mcp/policy.ts +14 -4
- package/src/coordinator-mcp/server.ts +44 -4
- package/src/coordinator-mcp/session-reaper.ts +9 -1
- package/src/cursor-delete-path.ts +10 -0
- package/src/cursor-mcp-name.ts +15 -0
- package/src/cursor.ts +13 -2
- package/src/dap/client.ts +9 -2
- package/src/dap/config.ts +33 -13
- package/src/dap/defaults.json +1 -1
- package/src/dap/session.ts +161 -36
- package/src/debug/crash-diagnostics.ts +89 -6
- package/src/debug/report-bundle-parent.ts +22 -0
- package/src/debug/report-bundle.ts +100 -3
- package/src/debug/system-info.ts +21 -4
- package/src/defaults/skc/extensions/grok-cli-vendor/src/shared/base-url.ts +21 -7
- package/src/defaults/skc/skills/deep-interview/SKILL.md +1 -1
- package/src/discovery/agents-md.ts +3 -2
- package/src/discovery/agents.ts +3 -2
- package/src/discovery/builtin.ts +21 -11
- package/src/discovery/claude.ts +5 -4
- package/src/discovery/cline.ts +2 -2
- package/src/discovery/codex.ts +6 -5
- package/src/discovery/cursor.ts +11 -2
- package/src/discovery/gemini.ts +4 -3
- package/src/discovery/github.ts +2 -2
- package/src/discovery/helpers.ts +51 -11
- package/src/discovery/mcp-json.ts +28 -12
- package/src/discovery/opencode.ts +2 -1
- package/src/discovery/ssh.ts +11 -6
- package/src/discovery/substitute-plugin-root.ts +3 -1
- package/src/discovery/vscode.ts +3 -3
- package/src/edit/apply-patch/index.ts +12 -1
- package/src/edit/file-read-cache.ts +24 -6
- package/src/edit/index.ts +90 -20
- package/src/edit/modes/patch.ts +215 -9
- package/src/edit/modes/replace.ts +141 -0
- package/src/eval/js/context-manager.ts +29 -3
- package/src/eval/js/worker-entry.ts +51 -18
- package/src/eval/py/runner.py +144 -5
- package/src/eval/py/runtime.ts +44 -4
- package/src/eval/py/tool-bridge.ts +4 -0
- package/src/exa/mcp-client.ts +53 -11
- package/src/exec/bash-executor.ts +87 -4
- package/src/exec/non-interactive-env.ts +0 -1
- package/src/export/html/css-color.ts +9 -0
- package/src/export/html/html-export-destination.ts +16 -0
- package/src/export/html/index.ts +102 -8
- package/src/export/html/template.generated.ts +1 -1
- package/src/extensibility/custom-tools/loader.ts +13 -3
- package/src/extensibility/custom-tools/types.ts +3 -1
- package/src/extensibility/custom-tools/wrapper.ts +3 -1
- package/src/extensibility/plugins/manager.ts +3 -2
- package/src/extensibility/plugins/marketplace/cache.ts +15 -0
- package/src/extensibility/plugins/marketplace/fetcher.ts +2 -2
- package/src/extensibility/plugins/marketplace/manager.ts +5 -3
- package/src/extensibility/plugins/plugin-link-path.ts +12 -0
- package/src/extensibility/skc-plugins/mcp-policy.ts +2 -1
- package/src/goals/runtime.ts +30 -8
- package/src/harness-control-plane/finalize.ts +10 -0
- package/src/harness-control-plane/operate.ts +12 -4
- package/src/harness-control-plane/owner.ts +8 -1
- package/src/harness-control-plane/receipt-spool.ts +105 -28
- package/src/harness-control-plane/storage.ts +124 -6
- package/src/hashline/execute.ts +3 -3
- package/src/hashline/recovery.ts +85 -2
- package/src/hindsight/config.ts +9 -3
- package/src/hindsight/content.ts +116 -16
- package/src/hindsight/mental-models.ts +22 -10
- package/src/hindsight/state.ts +7 -4
- package/src/hooks/native-skill-hook.ts +17 -12
- package/src/i18n/messages/de.settings.ts +3 -0
- package/src/i18n/messages/es.settings.ts +3 -0
- package/src/i18n/messages/fr.settings.ts +3 -0
- package/src/i18n/messages/ja.settings.ts +3 -0
- package/src/i18n/messages/ko.settings.ts +3 -0
- package/src/i18n/messages/zh.settings.ts +3 -0
- package/src/internal-urls/artifact-protocol.ts +3 -1
- package/src/internal-urls/docs-index.generated.ts +10 -10
- package/src/internal-urls/local-protocol.ts +167 -8
- package/src/internal-urls/skill-path.ts +18 -0
- package/src/internal-urls/skill-protocol.ts +2 -0
- package/src/internal-urls/types.ts +2 -0
- package/src/lsp/client.ts +2 -1
- package/src/lsp/clients/biome-client.ts +2 -0
- package/src/lsp/clients/swiftlint-client.ts +2 -0
- package/src/lsp/config.ts +18 -62
- package/src/lsp/edits.ts +6 -0
- package/src/lsp/index.ts +29 -0
- package/src/lsp/workspace-path.ts +75 -0
- package/src/main.ts +33 -11
- package/src/memories/index.ts +141 -9
- package/src/migrate/action-planner.ts +57 -0
- package/src/migrate/adapters/claude-code.ts +23 -4
- package/src/migrate/adapters/codex.ts +22 -4
- package/src/migrate/adapters/index.ts +22 -4
- package/src/migrate/adapters/opencode.ts +6 -1
- package/src/migrate/executor.ts +84 -7
- package/src/migrate/report.ts +19 -2
- package/src/migrate/types.ts +14 -4
- package/src/modes/DESIGN.md +5 -0
- package/src/modes/acp/acp-agent.ts +35 -2
- package/src/modes/acp/permission-mode.ts +18 -1
- package/src/modes/components/custom-editor.ts +14 -0
- package/src/modes/components/extensions/extension-dashboard.ts +2 -2
- package/src/modes/components/extensions/inspector-panel.ts +9 -5
- package/src/modes/components/extensions/state-manager.ts +15 -5
- package/src/modes/components/model-selector.ts +144 -94
- package/src/modes/components/welcome.ts +3 -2
- package/src/modes/controllers/command-controller.ts +300 -9
- package/src/modes/controllers/event-controller.ts +1 -1
- package/src/modes/controllers/extension-ui-controller.ts +32 -19
- package/src/modes/controllers/input-controller.ts +62 -26
- package/src/modes/controllers/plan-mode-controller.ts +17 -7
- package/src/modes/controllers/runtime-mcp-command-controller.ts +25 -20
- package/src/modes/controllers/ssh-command-controller.ts +3 -1
- package/src/modes/interactive-mode.ts +10 -0
- package/src/modes/utils/macos-option-forwarding.ts +80 -0
- package/src/prompts/system/irc-incoming.md +3 -1
- package/src/prompts/system/project-prompt.md +19 -0
- package/src/prompts/system/system-prompt.md +3 -0
- package/src/prompts/tools/ask.md +2 -0
- package/src/prompts/tools/debug.md +1 -1
- package/src/prompts/tools/monitor.md +7 -5
- package/src/prompts/tools/reverse-engineer.md +29 -0
- package/src/runtime-credential-selector.ts +2 -2
- package/src/runtime-mcp/config-writer.ts +10 -6
- package/src/runtime-mcp/config.ts +1 -0
- package/src/runtime-mcp/content-limits.ts +7 -0
- package/src/runtime-mcp/json-rpc.ts +2 -1
- package/src/runtime-mcp/manager.ts +57 -9
- package/src/runtime-mcp/mcp-redirect.ts +73 -0
- package/src/runtime-mcp/oauth-flow.ts +43 -5
- package/src/runtime-mcp/oauth-public-url.ts +8 -0
- package/src/runtime-mcp/plugin-mcp-name-filter.ts +62 -0
- package/src/runtime-mcp/plugin-network-boundary.ts +4 -0
- package/src/runtime-mcp/project-host-values.ts +50 -0
- package/src/runtime-mcp/render.ts +16 -1
- package/src/runtime-mcp/smithery-registry.ts +22 -3
- package/src/runtime-mcp/tool-bridge.ts +194 -21
- package/src/runtime-mcp/transports/http.ts +4 -3
- package/src/runtime-mcp/transports/stdio.ts +2 -1
- package/src/runtime-mcp/types.ts +6 -0
- package/src/sdk/broker/broker.ts +11 -2
- package/src/sdk/broker/ensure.ts +131 -10
- package/src/sdk/broker/lifecycle-ledger.ts +18 -3
- package/src/sdk/broker/lifecycle.ts +21 -19
- package/src/sdk/broker/runtime.ts +1 -1
- package/src/sdk/bus/chat-daemon-cli.ts +38 -1
- package/src/sdk/bus/chat-daemon-control.ts +5 -3
- package/src/sdk/bus/index.ts +5 -3
- package/src/sdk/bus/lifecycle-control-runtime.ts +9 -2
- package/src/sdk/bus/session-control.ts +2 -0
- package/src/sdk/bus/slack-daemon.ts +8 -1
- package/src/sdk/bus/slack-live-provider.ts +3 -1
- package/src/sdk/bus/telegram-daemon-contract.ts +3 -1
- package/src/sdk/bus/telegram-daemon-control.ts +17 -12
- package/src/sdk/bus/telegram-daemon.ts +41 -1
- package/src/sdk/host/events.ts +67 -4
- package/src/sdk/mcp/server.ts +16 -3
- package/src/sdk/protocol/operation-inventory.generated.json +22 -0
- package/src/sdk/session.ts +18 -25
- package/src/secrets/obfuscator.ts +92 -12
- package/src/session/agent-session.ts +466 -100
- package/src/session/artifacts.ts +3 -1
- package/src/session/auto-resume.ts +45 -8
- package/src/session/history-storage.ts +172 -8
- package/src/session/internal/managed-session-scope.ts +130 -52
- package/src/session/messages.ts +47 -6
- package/src/session/session-manager.ts +116 -8
- package/src/session/session-storage.ts +31 -1
- package/src/session/streaming-output.ts +263 -4
- package/src/session-import/redact.ts +76 -3
- package/src/setup/hermes-setup.ts +4 -1
- package/src/skc-runtime/gc-runtime.ts +26 -4
- package/src/skc-runtime/launch-tmux.ts +21 -11
- package/src/skc-runtime/launch-worktree.ts +42 -3
- package/src/skc-runtime/managed-owner-admission.ts +46 -2
- package/src/skc-runtime/psmux-detect.ts +29 -5
- package/src/skc-runtime/ralplan-runtime.ts +14 -1
- package/src/skc-runtime/session-resolution.ts +38 -6
- package/src/skc-runtime/sidecar-bootstrap-env.ts +19 -0
- package/src/skc-runtime/state-writer.ts +134 -16
- package/src/skc-runtime/tmux-sessions.ts +85 -4
- package/src/skc-runtime/ultragoal-change-set.ts +18 -2
- package/src/skc-runtime/ultragoal-guard.ts +9 -1
- package/src/skc-runtime/ultragoal-runtime.ts +26 -9
- package/src/skill-state/active-state.ts +13 -0
- package/src/skill-state/workflow-mutation-guard.ts +3297 -180
- package/src/slash-commands/builtin-registry.ts +14 -8
- package/src/slash-commands/helpers/mcp.ts +20 -7
- package/src/ssh/ssh-executor.ts +3 -1
- package/src/stt/recorder.ts +26 -9
- package/src/system-prompt.ts +65 -16
- package/src/task/commands.ts +3 -1
- package/src/task/executor.ts +52 -7
- package/src/task/index.ts +28 -0
- package/src/task/isolation-dir.ts +143 -0
- package/src/task/role-body.ts +84 -0
- package/src/task/token-log-mode.test.ts +162 -0
- package/src/task/token-log.ts +91 -2
- package/src/task/worktree.ts +16 -7
- package/src/tools/archive-reader.ts +653 -31
- package/src/tools/ask.ts +86 -14
- package/src/tools/ast-edit-write-path.ts +133 -0
- package/src/tools/ast-edit.ts +27 -1
- package/src/tools/ast-grep.ts +7 -2
- package/src/tools/atomic-file-write.ts +625 -0
- package/src/tools/auto-generated-guard.ts +28 -8
- package/src/tools/bash-allowed-prefixes.ts +225 -6
- package/src/tools/bash-interactive.ts +12 -0
- package/src/tools/bash-skill-urls.ts +113 -7
- package/src/tools/bash.ts +152 -20
- package/src/tools/browser/cdp-url.ts +18 -0
- package/src/tools/browser/tab-worker.ts +49 -14
- package/src/tools/browser.ts +25 -8
- package/src/tools/cron.ts +10 -1
- package/src/tools/debug.ts +16 -8
- package/src/tools/eval.ts +71 -34
- package/src/tools/explicit-artifact.ts +89 -0
- package/src/tools/fetch.ts +26 -17
- package/src/tools/gh.ts +40 -12
- package/src/tools/github-side-effect.ts +112 -0
- package/src/tools/image-gen.ts +24 -10
- package/src/tools/index.ts +6 -0
- package/src/tools/monitor-mutation.ts +27 -0
- package/src/tools/monitor.ts +28 -1
- package/src/tools/output-meta.ts +74 -5
- package/src/tools/read.ts +24 -36
- package/src/tools/recipe/index.ts +12 -0
- package/src/tools/recipe/recipe-guard.ts +19 -0
- package/src/tools/recipe/runner.ts +23 -12
- package/src/tools/render-utils.ts +2 -2
- package/src/tools/restricted-cwd.ts +10 -0
- package/src/tools/reverse-engineer.ts +497 -0
- package/src/tools/search-tool-bm25.ts +14 -3
- package/src/tools/search.ts +3 -2
- package/src/tools/ssh.ts +235 -8
- package/src/tools/subagent-render.ts +43 -7
- package/src/tools/subagent.ts +7 -3
- package/src/tools/tmux-self-injection-guard.ts +3538 -0
- package/src/tools/todo-write.ts +41 -3
- package/src/tools/untrusted-content.ts +23 -0
- package/src/tools/vim.ts +2 -2
- package/src/tools/write.ts +37 -4
- package/src/tui/tree-list.ts +15 -1
- package/src/utils/commit-message-generator.ts +9 -2
- package/src/utils/external-editor.ts +21 -7
- package/src/utils/file-mentions.ts +75 -7
- package/src/utils/git.ts +38 -7
- package/src/utils/open.ts +73 -4
- package/src/utils/shell-snapshot.ts +9 -1
- package/src/utils/title-generator.ts +61 -16
- package/src/utils/tools-checksum.ts +34 -0
- package/src/utils/tools-manager.ts +24 -6
- package/src/utils/xml-escape.ts +14 -0
- package/src/web/insane/url-guard.ts +2 -1
- package/src/web/scrapers/types.ts +8 -0
- package/src/web/scrapers/youtube.ts +3 -2
- package/src/web/search/index.ts +4 -3
- package/src/web/search/providers/anthropic.ts +4 -4
- package/src/web/search/providers/codex.ts +31 -34
- package/src/web/search/providers/insane.ts +145 -28
- package/src/web/search/providers/kimi.ts +15 -5
- package/src/web/search/providers/searxng.ts +47 -4
- package/src/web/search/providers/xai.ts +7 -2
- package/dist/types/cli/shell-cli.d.ts +0 -8
- package/dist/types/commands/shell.d.ts +0 -21
- package/src/cli/shell-cli.ts +0 -176
- package/src/commands/shell.ts +0 -29
|
@@ -3,12 +3,19 @@ import * as os from "node:os";
|
|
|
3
3
|
import * as path from "node:path";
|
|
4
4
|
import type { AgentTool } from "@sayknow-cli/agent-core";
|
|
5
5
|
import { logger } from "@sayknow-cli/utils";
|
|
6
|
+
import { canonicalEnvKey, type ProjectEnvSnapshot, projectEnvSnapshot } from "@sayknow-cli/utils/env-file";
|
|
6
7
|
import { expandApplyPatchToEntries } from "../edit/modes/apply-patch";
|
|
7
8
|
import { LocalProtocolHandler, resolveLocalUrlToPath } from "../internal-urls/local-protocol";
|
|
8
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
SKC_SESSION_PREFIX,
|
|
11
|
+
sessionDirName,
|
|
12
|
+
modeStatePath as sessionModeStatePath,
|
|
13
|
+
} from "../skc-runtime/session-layout";
|
|
9
14
|
import { resolveSkcSessionForRead } from "../skc-runtime/session-resolution";
|
|
10
15
|
import { ModeStateSchema } from "../skc-runtime/state-schema";
|
|
16
|
+
import { workflowEnvelopeChecksumStatus } from "../skc-runtime/state-writer";
|
|
11
17
|
import { getSkillManifest } from "../skc-runtime/workflow-manifest";
|
|
18
|
+
import { isGithubReadOnlyArgs } from "../tools/github-side-effect";
|
|
12
19
|
import { resolveToCwd } from "../tools/path-utils";
|
|
13
20
|
import { ToolError } from "../tools/tool-errors";
|
|
14
21
|
import { listActiveSkills, readVisibleSkillActiveState, type SkillActiveEntry } from "./active-state";
|
|
@@ -34,7 +41,18 @@ function planningPhaseBlockMessage(skill: CanonicalSkcWorkflowSkill): string {
|
|
|
34
41
|
return DEEP_INTERVIEW_MUTATION_BLOCK_MESSAGE;
|
|
35
42
|
}
|
|
36
43
|
|
|
37
|
-
|
|
44
|
+
/**
|
|
45
|
+
* Tools whose execute path can mutate product state. `github` is included so
|
|
46
|
+
* side-effect ops share this guard. `eval` and `python` run code that can write
|
|
47
|
+
* files without going through edit, write, or bash.
|
|
48
|
+
*/
|
|
49
|
+
export const WORKFLOW_MUTATION_TOOL_NAMES = ["edit", "write", "ast_edit", "bash", "github", "eval", "python"] as const;
|
|
50
|
+
|
|
51
|
+
const BLOCKED_TOOL_NAMES = new Set<string>(WORKFLOW_MUTATION_TOOL_NAMES);
|
|
52
|
+
|
|
53
|
+
export function isWorkflowMutationTool(name: string): boolean {
|
|
54
|
+
return BLOCKED_TOOL_NAMES.has(name);
|
|
55
|
+
}
|
|
38
56
|
/**
|
|
39
57
|
* Only `/dev/null` is exempt. `/dev/stdout`, `/dev/stderr`, and `/dev/fd/<n>` are descriptor
|
|
40
58
|
* aliases: `exec 1<>src/product.ts; printf x >/dev/stdout` reaches a real repository file
|
|
@@ -49,17 +67,134 @@ const BASH_EXEC_REDIRECT_RE = /(?:^|[;&|\n])\s*(?:sudo\s+)?exec\b[^;&|\n]*[<>]/i
|
|
|
49
67
|
const ARCHIVE_OR_SQLITE_BASE_RE = /^(.+?\.(?:tar\.gz|sqlite3|sqlite|db3|zip|tgz|tar|db))(?:$|:)/i;
|
|
50
68
|
const INTERNAL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
51
69
|
const VIM_FILE_SWITCH_RE = /^\s*:(?:e|e!|edit|edit!)(?:\s+([^<\r\n]+))?(?:<CR>|\r|\n|$)/i;
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const
|
|
70
|
+
/**
|
|
71
|
+
* Executable wrappers that run their operand as a command (`command rm x`,
|
|
72
|
+
* `env rm x`, `exec rm x`). Bash resolves through them, so the mutator that
|
|
73
|
+
* follows is a real write. Left unmodeled they produced no target and no
|
|
74
|
+
* unknown flag, letting a mutation cross the planning boundary. `env` may
|
|
75
|
+
* carry `NAME=value` assignments before the wrapped command.
|
|
76
|
+
*/
|
|
77
|
+
const BASH_COMMAND_WRAPPER_SOURCE =
|
|
78
|
+
"(?:(?:command|builtin|exec|nohup|nice|ionice|stdbuf|setsid|time|env)\\s+(?:-[^\\s]+\\s+(?:\\d+\\s+)?|\\w+=[^\\s]*\\s+)*)*";
|
|
79
|
+
/**
|
|
80
|
+
* Shell keywords that open a NEW command position without a `;`/`|`/`&`
|
|
81
|
+
* separator in front of the command word (`then rm x`, `do rm x`, `else rm x`).
|
|
82
|
+
* Normalizing them to separators lets the existing mutation regexes see the
|
|
83
|
+
* command position instead of treating `then rm` as one opaque word.
|
|
84
|
+
*/
|
|
85
|
+
const BASH_COMMAND_POSITION_KEYWORD_RE = /(?:^|[;&|(\n{}])\s*(?:then|else|elif|do|in|\{|!)(?=\s)/gi;
|
|
86
|
+
const BASH_MUTATION_COMMAND_RE = new RegExp(
|
|
87
|
+
`(?:^|[;&|(\\n])\\s*(?:\\w+=[^\\s]+\\s+)*(?:sudo\\s+)?${BASH_COMMAND_WRAPPER_SOURCE}(?:[^\\s;&|()]*\\/)?(?:tee|touch|rm|mkdir|cp|mv|install|truncate|chmod|ln)\\b([^;&|()\\n]*)|(?:^|[^<>])(?:>>?|\\d>>?)\\s*([^\\s;&|]+)`,
|
|
88
|
+
"gi",
|
|
89
|
+
);
|
|
90
|
+
/** Command-word extractor; must accept the same prefixes as `BASH_MUTATION_COMMAND_RE`. */
|
|
91
|
+
const BASH_MUTATION_COMMAND_NAME_RE = new RegExp(
|
|
92
|
+
`(?:^|[;&|(\\n])\\s*(?:\\w+=[^\\s]+\\s+)*(?:sudo\\s+)?${BASH_COMMAND_WRAPPER_SOURCE}(?:[^\\s;&|()]*\\/)?(tee|touch|rm|mkdir|cp|mv|install|truncate|chmod|ln)\\b`,
|
|
93
|
+
"i",
|
|
94
|
+
);
|
|
95
|
+
const BASH_CHMOD_MODE_RE = /^(?:[0-7]{1,4}|(?:[ugoa]*[+=-][rwxXstugo]*)(?:,[ugoa]*[+=-][rwxXstugo]*)*)$/;
|
|
96
|
+
const BASH_IN_PLACE_MUTATION_COMMAND_RE = new RegExp(
|
|
97
|
+
`(?:^|[;&|(\\n])\\s*(?:\\w+=[^\\s]+\\s+)*(?:sudo\\s+)?${BASH_COMMAND_WRAPPER_SOURCE}(?:[^\\s;&|()]*\\/)?(?:sed|perl)\\b([^;&|()\\n]*)`,
|
|
98
|
+
"gi",
|
|
99
|
+
);
|
|
100
|
+
/**
|
|
101
|
+
* Write APIs a planning one-liner cannot be allowed to call. The destination is
|
|
102
|
+
* not a static path the temp allowlist can trust, so a match fails closed the
|
|
103
|
+
* same way `open(` / `writeFile(` / `.write(` already do. `perl` is included
|
|
104
|
+
* because `perl -e 'open(...)'` is that same call.
|
|
105
|
+
*/
|
|
106
|
+
const BASH_INTERPRETER_WRITE_API_PATTERNS = [
|
|
107
|
+
"open\\s*\\(",
|
|
108
|
+
"writeFile(?:Sync)?\\s*\\(",
|
|
109
|
+
"appendFile(?:Sync)?\\s*\\(",
|
|
110
|
+
"file_put_contents\\s*\\(",
|
|
111
|
+
"fwrite\\s*\\(",
|
|
112
|
+
"fputs\\s*\\(",
|
|
113
|
+
"unlink\\s*\\(",
|
|
114
|
+
"rename\\s*\\(",
|
|
115
|
+
"mkdir\\s*\\(",
|
|
116
|
+
"rmdir\\s*\\(",
|
|
117
|
+
"copy\\s*\\(",
|
|
118
|
+
"symlink\\s*\\(",
|
|
119
|
+
"link\\s*\\(",
|
|
120
|
+
"move_uploaded_file\\s*\\(",
|
|
121
|
+
"truncate\\s*\\(",
|
|
122
|
+
"touch\\s*\\(",
|
|
123
|
+
"\\.write\\s*\\(",
|
|
124
|
+
"shutil\\s*\\.\\s*(?:copy2?|copyfileobj|copyfile)\\s*\\(",
|
|
125
|
+
"os\\s*\\.\\s*symlink\\s*\\(",
|
|
126
|
+
] as const;
|
|
127
|
+
const BASH_INTERPRETER_WRITE_API = `(?:${BASH_INTERPRETER_WRITE_API_PATTERNS.join("|")})`;
|
|
128
|
+
const BASH_INTERPRETER_WRITE_API_EXCLUDING_OPEN = `(?:${BASH_INTERPRETER_WRITE_API_PATTERNS.slice(1).join("|")})`;
|
|
129
|
+
const INTERPRETER_OUTPUT_METHOD_ASSIGNMENT_RE =
|
|
130
|
+
/^\b(?:(?:process|Bun|Deno|sys)(?:\s*\.\s*(?:stdout|stderr)|\s*\[\s*["'`](?:stdout|stderr)["'`]\s*\])|(?:process|Bun|Deno|sys)\s*\[\s*[^\]]+\s*\]\s*(?:\.\s*write|\[\s*["'`]write["'`]\s*\])|(?:(?:globalThis|global)\s*\.\s*)?console)(?:\s*(?:\.\s*[\w$]+|\[\s*[^\]]+\s*\]))?\s*(?:\|\|=|&&=|\?\?=|[+\-*/%&|^]?=(?!=|>))/;
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* A stream object can also be mutated reflectively, so an exempted
|
|
134
|
+
* `process.stdout.write(...)` is only trustworthy when nothing in the source can
|
|
135
|
+
* have replaced that method (`Object.assign(process.stdout, {write: ...})`).
|
|
136
|
+
*/
|
|
137
|
+
const INTERPRETER_OUTPUT_STREAM_MUTATION_RE =
|
|
138
|
+
/\b(?:Object\s*\.\s*(?:assign|definePropert(?:y|ies))|Reflect\s*\.\s*(?:set|defineProperty))\s*\(\s*(?:process|Bun|Deno|sys)\s*(?:\.\s*(?:stdout|stderr)|\[\s*["'`](?:stdout|stderr)["'`]\s*\])/;
|
|
139
|
+
/**
|
|
140
|
+
* Inline interpreter source is opaque whenever it exposes code evaluation or
|
|
141
|
+
* reflective loading. This deliberately scans the complete source spelling,
|
|
142
|
+
* including quoted spans, because another language may evaluate those spans.
|
|
143
|
+
*/
|
|
144
|
+
const INTERPRETER_DYNAMIC_EXECUTION_RE =
|
|
145
|
+
/\b(?:eval|exec|execfile|Function|instance_eval|instance_exec|class_eval|class_exec|module_eval|module_exec|send|public_send|__send__|method_missing|__import__|exec_module|import_module|run_path|run_module|loadstring|dofile|loadfile|load|source|include|include_once|require_once|create_function|call_user_func(?:_array)?|setTimeout|setInterval|runInThisContext|runInNewContext|runInContext|getattr|setattr|__getattr__|__getattribute__|ReflectionClass|ReflectionFunction|ReflectionMethod|invokeMethod|invokeArgs)\b/;
|
|
146
|
+
const INTERPRETER_FILESYSTEM_REQUIRE_RE =
|
|
147
|
+
/\b(?:require|import|from)\s*(?:\(\s*)?(['"\x60])(?:node:)?(?:fs(?:\/promises)?|fs-extra|graceful-fs|child_process|fileutils|io|lfs)\1(?:\s*\))?/i;
|
|
148
|
+
const INTERPRETER_NONLITERAL_REQUIRE_RE = /\brequire\s*(?:\(\s*(?!['"\x60])|\s+(?!['"\x60]))/i;
|
|
149
|
+
const SHELL_DOT_SOURCE_RE = /(?:^|[;&|\n])\s*(?:(?:if|then|do)\s+)?\.\s+(?:["'$`]|[A-Za-z0-9_./~])/;
|
|
150
|
+
/** Executable Python source evaluation and dynamic imports make payloads opaque; compile() alone is inert. */
|
|
151
|
+
const PYTHON_DYNAMIC_EXECUTION_IDENTIFIER_RE =
|
|
152
|
+
/^(?:exec|eval|execfile|__import__|exec_module|import_module|run_path|run_module|getattr|setattr|__getattr__|__getattribute__)\b/;
|
|
153
|
+
const PYTHON_DYNAMIC_EXECUTION_TOKEN_RE =
|
|
154
|
+
/\b(?:exec|eval|execfile|__import__|exec_module|import_module|run_path|run_module|getattr|setattr|__getattr__|__getattribute__)\b/;
|
|
155
|
+
/** JavaScript eval and Function construct executable code from runtime strings. */
|
|
156
|
+
const JAVASCRIPT_DYNAMIC_EXECUTION_IDENTIFIER_RE = /^(?:eval|Function)\b/;
|
|
157
|
+
const JAVASCRIPT_DYNAMIC_EXECUTION_TOKEN_RE = /\b(?:eval|Function)\b/;
|
|
158
|
+
const BASH_HEREDOC_OPAQUE_INTERPRETER_WRITE_RE = new RegExp(
|
|
159
|
+
`(?:^|[;&|\\n])\\s*(?:\\w+=[^\\s]+\\s+)*(?:sudo\\s+)?(?:python3?|node|ruby|perl)\\b[^;&|\\n]*(?:<<[-]?\\s*['"]?\\w+['"]?)[\\s\\S]*${BASH_INTERPRETER_WRITE_API}`,
|
|
160
|
+
"i",
|
|
161
|
+
);
|
|
162
|
+
const BASH_DD_OUTPUT_RE = new RegExp(
|
|
163
|
+
`(?:^|[;&|\\n])\\s*(?:\\w+=[^\\s]+\\s+)*(?:sudo\\s+)?${BASH_COMMAND_WRAPPER_SOURCE}(?:[^\\s;&|]*\\/)?dd\\b([^;&|\\n]*)`,
|
|
164
|
+
"gi",
|
|
165
|
+
);
|
|
60
166
|
/** Literal `sh|bash|zsh -c '<script>'` payloads whose nested script must also be scanned. */
|
|
61
167
|
const BASH_NESTED_SHELL_RE =
|
|
62
168
|
/(?:^|[;&|\n])\s*(?:\w+=[^\s]+\s+)*(?:sudo\s+)?(?:[^\s;&|]*\/)?(?:ba|z|da)?sh\s+(?:-[A-Za-z]+\s+)*-[A-Za-z]*c\s+(?:(')([^']*)'|(")([^"]*)")/g;
|
|
169
|
+
/** Heredoc opener (`<<`/`<<-` plus an optionally quoted delimiter); `<<<` here-strings excluded. */
|
|
170
|
+
const BASH_HEREDOC_OPEN_RE = /(?<!<)<<(?!<)(-?)\s*(?:'([^'\s]+)'|"([^"\s]+)"|(\\)?([A-Za-z_][\w.-]*))/g;
|
|
171
|
+
/** Consumers whose stdin is inert data: their heredoc bodies are safe to mask. Anything else stays live. */
|
|
172
|
+
const HEREDOC_DATA_CONSUMERS = new Set([
|
|
173
|
+
"cat",
|
|
174
|
+
"tee",
|
|
175
|
+
"head",
|
|
176
|
+
"tail",
|
|
177
|
+
"wc",
|
|
178
|
+
"sort",
|
|
179
|
+
"uniq",
|
|
180
|
+
"tr",
|
|
181
|
+
"cut",
|
|
182
|
+
"grep",
|
|
183
|
+
"column",
|
|
184
|
+
"nl",
|
|
185
|
+
"fold",
|
|
186
|
+
"fmt",
|
|
187
|
+
"base64",
|
|
188
|
+
"md5sum",
|
|
189
|
+
"sha1sum",
|
|
190
|
+
"sha256sum",
|
|
191
|
+
"sha512sum",
|
|
192
|
+
"shasum",
|
|
193
|
+
"jq",
|
|
194
|
+
"yq",
|
|
195
|
+
]);
|
|
196
|
+
/** Stdin appliers whose heredoc body mutates files in ways no body scan can model. */
|
|
197
|
+
const HEREDOC_MUTATING_CONSUMERS = new Set(["patch", "ed", "ex", "sqlite3"]);
|
|
63
198
|
|
|
64
199
|
type ToolWithEditMode = AgentTool & {
|
|
65
200
|
mode?: unknown;
|
|
@@ -191,8 +326,11 @@ function modeStateMatchesContext(state: ModeState, sessionId?: string, threadId?
|
|
|
191
326
|
return true;
|
|
192
327
|
}
|
|
193
328
|
|
|
194
|
-
/**
|
|
195
|
-
|
|
329
|
+
/** Canonical workflow skills whose active posture gates product-code mutation. */
|
|
330
|
+
type MutationGatedSkill = "deep-interview" | "ralplan" | "ultragoal";
|
|
331
|
+
|
|
332
|
+
/** Workflow skills whose active posture this guard enforces against product-code mutation. */
|
|
333
|
+
function isPlanningSkill(skill: string): skill is MutationGatedSkill {
|
|
196
334
|
return skill === "deep-interview" || skill === "ralplan" || skill === "ultragoal";
|
|
197
335
|
}
|
|
198
336
|
|
|
@@ -204,14 +342,14 @@ function isPlanningSkill(skill: string): skill is "deep-interview" | "ralplan" |
|
|
|
204
342
|
* `ultragoal` only blocks during `goal-planning`; once goals are created it is an
|
|
205
343
|
* executor and mutates freely.
|
|
206
344
|
*/
|
|
207
|
-
function isBlockingPlanningPhase(skill:
|
|
345
|
+
function isBlockingPlanningPhase(skill: MutationGatedSkill, phase: string): boolean {
|
|
208
346
|
const normalized = phase.trim().toLowerCase();
|
|
209
347
|
if (skill === "ultragoal") return normalized === "goal-planning";
|
|
210
348
|
return !getSkillManifest(skill).stopReleasingPhases.includes(normalized);
|
|
211
349
|
}
|
|
212
350
|
|
|
213
351
|
interface ActivePlanningSkill {
|
|
214
|
-
skill:
|
|
352
|
+
skill: MutationGatedSkill;
|
|
215
353
|
phase: string;
|
|
216
354
|
}
|
|
217
355
|
|
|
@@ -222,11 +360,11 @@ interface ActivePlanningSkill {
|
|
|
222
360
|
* to `active:false`, which `listActiveSkills` already filters out). If several
|
|
223
361
|
* are momentarily active, prefer the most-recently-updated entry so a stale
|
|
224
362
|
* planning row (e.g. a still-active ralplan `final`) can never be selected over a
|
|
225
|
-
* newer executor (ultragoal
|
|
363
|
+
* newer executor (ultragoal), and a planning *return* (newer `updated_at`)
|
|
226
364
|
* reliably wins. Ties fall back to the resolved top-level `skill`, then to the
|
|
227
365
|
* first entry, matching how the HUD/chain guard pick `activeSkills[0]`.
|
|
228
366
|
*/
|
|
229
|
-
function resolveCurrentWorkflowEntry(entries: SkillActiveEntry[], topLevelSkill: string): SkillActiveEntry {
|
|
367
|
+
export function resolveCurrentWorkflowEntry(entries: SkillActiveEntry[], topLevelSkill: string): SkillActiveEntry {
|
|
230
368
|
const ts = (entry: SkillActiveEntry): number => {
|
|
231
369
|
const value = Date.parse(safeString(entry.updated_at) || safeString(entry.activated_at));
|
|
232
370
|
return Number.isNaN(value) ? -1 : value;
|
|
@@ -252,10 +390,20 @@ function resolveCurrentWorkflowEntry(entries: SkillActiveEntry[], topLevelSkill:
|
|
|
252
390
|
* governs, so a stale planning entry can never block while an executor runs and
|
|
253
391
|
* a resumed planning phase reliably re-blocks.
|
|
254
392
|
*
|
|
255
|
-
* Fail-open contract: a missing or invalid durable mode-state releases
|
|
256
|
-
* (a corrupt state file must not lock all mutation), matching the
|
|
257
|
-
* historical behavior — this is intentionally looser than the Stop
|
|
258
|
-
* fails closed for handoff-required skills.
|
|
393
|
+
* Fail-open contract: a missing or schema-invalid durable mode-state releases
|
|
394
|
+
* the block (a corrupt state file must not lock all mutation), matching the
|
|
395
|
+
* guard's historical behavior — this is intentionally looser than the Stop
|
|
396
|
+
* hook, which fails closed for handoff-required skills. A checksum mismatch is
|
|
397
|
+
* not that case: the file is still schema-valid, and the CLI already refuses
|
|
398
|
+
* it as an out-of-band edit. The guard keeps the active entry's phase instead
|
|
399
|
+
* of letting the forged `current_phase` or `active: false` release the block.
|
|
400
|
+
* An unsigned envelope may restate that entry, but it may not release a block
|
|
401
|
+
* the entry still holds. It may still name a stricter blocking phase: the
|
|
402
|
+
* pre-fix guard honored that phase, and dropping it would allow an edit the
|
|
403
|
+
* base rejected. A `session_id` or `thread_id` that does not match this
|
|
404
|
+
* session is the same kind of claim: it does not make the file someone else's,
|
|
405
|
+
* and it does not open the block. A matching `content_sha256` whose context
|
|
406
|
+
* also matches is the existing writer stamp and is trusted.
|
|
259
407
|
*/
|
|
260
408
|
async function getActivePlanningSkill(
|
|
261
409
|
cwd: string,
|
|
@@ -278,11 +426,73 @@ async function getActivePlanningSkill(
|
|
|
278
426
|
const modeState = guardContext.modeStates.get(current.skill) ?? null;
|
|
279
427
|
|
|
280
428
|
if (!modeState) return null;
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
429
|
+
const activePhase = String(current.phase ?? "").trim();
|
|
430
|
+
const posture = planningPostureFromModeState(current.skill, activePhase, modeState, resolvedSessionId, threadId);
|
|
431
|
+
if (posture.tampered) {
|
|
432
|
+
warnInvalidModeState(
|
|
433
|
+
modeStatePath(cwd, current.skill, resolvedSessionId),
|
|
434
|
+
"out-of-band edit detected (content_sha256 mismatch)",
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
if (!posture.blocking) return null;
|
|
438
|
+
return { skill: current.skill, phase: posture.phase };
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Decide whether `modeState` may release the planning block.
|
|
443
|
+
*
|
|
444
|
+
* The active entry is the seal. A mode-state file releases that seal only when
|
|
445
|
+
* its writer-stamped `content_sha256` matches and its session context matches,
|
|
446
|
+
* or when an unsigned file in the same context does not claim a looser posture
|
|
447
|
+
* than the entry. An unsigned file may still impose a stricter blocking phase.
|
|
448
|
+
* Checksum mismatch ignores the file. A context mismatch does not release the
|
|
449
|
+
* entry's block: the file was read from this session's path.
|
|
450
|
+
*/
|
|
451
|
+
function planningPostureFromModeState(
|
|
452
|
+
skill: MutationGatedSkill,
|
|
453
|
+
activePhase: string,
|
|
454
|
+
modeState: ModeState,
|
|
455
|
+
sessionId?: string,
|
|
456
|
+
threadId?: string,
|
|
457
|
+
): { blocking: boolean; phase: string; tampered: boolean } {
|
|
458
|
+
const status = workflowEnvelopeChecksumStatus(modeState);
|
|
459
|
+
if (status === "mismatch") {
|
|
460
|
+
return {
|
|
461
|
+
blocking: isBlockingPlanningPhase(skill, activePhase),
|
|
462
|
+
phase: activePhase,
|
|
463
|
+
tampered: true,
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
if (!modeStateMatchesContext(modeState, sessionId, threadId)) {
|
|
467
|
+
return {
|
|
468
|
+
blocking: isBlockingPlanningPhase(skill, activePhase),
|
|
469
|
+
phase: activePhase,
|
|
470
|
+
tampered: false,
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
if (status === "match") {
|
|
474
|
+
if (modeState.active !== true) return { blocking: false, phase: activePhase, tampered: false };
|
|
475
|
+
const phase = String(modeState.current_phase ?? activePhase).trim();
|
|
476
|
+
return { blocking: isBlockingPlanningPhase(skill, phase), phase, tampered: false };
|
|
477
|
+
}
|
|
478
|
+
if (!isBlockingPlanningPhase(skill, activePhase)) {
|
|
479
|
+
const stricterPhase = String(modeState.current_phase ?? "").trim();
|
|
480
|
+
if (modeState.active === true && stricterPhase && isBlockingPlanningPhase(skill, stricterPhase)) {
|
|
481
|
+
return { blocking: true, phase: stricterPhase, tampered: false };
|
|
482
|
+
}
|
|
483
|
+
return { blocking: false, phase: activePhase, tampered: false };
|
|
484
|
+
}
|
|
485
|
+
if (modeState.active !== true) return { blocking: true, phase: activePhase, tampered: false };
|
|
486
|
+
const modePhase = String(modeState.current_phase ?? "").trim();
|
|
487
|
+
if (
|
|
488
|
+
modePhase &&
|
|
489
|
+
!isBlockingPlanningPhase(skill, modePhase) &&
|
|
490
|
+
modePhase.trim().toLowerCase() !== activePhase.trim().toLowerCase()
|
|
491
|
+
) {
|
|
492
|
+
return { blocking: true, phase: activePhase, tampered: false };
|
|
493
|
+
}
|
|
494
|
+
const phase = modePhase || activePhase;
|
|
495
|
+
return { blocking: isBlockingPlanningPhase(skill, phase), phase, tampered: false };
|
|
286
496
|
}
|
|
287
497
|
|
|
288
498
|
function normalizePosix(value: string): string {
|
|
@@ -392,174 +602,2937 @@ function cleanShellWord(value: string): string {
|
|
|
392
602
|
}
|
|
393
603
|
|
|
394
604
|
/**
|
|
395
|
-
* Blank out
|
|
396
|
-
*
|
|
397
|
-
* redirections or separators.
|
|
398
|
-
*
|
|
399
|
-
*
|
|
605
|
+
* Blank out quoted spans so shell metacharacters inside a literal argument
|
|
606
|
+
* value (e.g. `--evidence "p99 500ms -> 120ms"`) are not misread as
|
|
607
|
+
* redirections or separators.
|
|
608
|
+
*
|
|
609
|
+
* Both quote styles are masked because in POSIX shells neither one can contain
|
|
610
|
+
* a redirection or a command separator: `>`, `|`, `;`, and `&` are always
|
|
611
|
+
* literal data inside quotes. Masking only single quotes made every `>` in
|
|
612
|
+
* double-quoted PROSE look like a real redirect, so ordinary evidence text
|
|
613
|
+
* (`"throughput > baseline"`, `"500ms -> 120ms"`) was scanned as a file write
|
|
614
|
+
* and blocked.
|
|
615
|
+
*
|
|
616
|
+
* Double quotes differ from single quotes in one way that matters here: they
|
|
617
|
+
* still expand `$(...)` and backticks, and that substitution IS live code. So
|
|
618
|
+
* the literal text of a double-quoted span is masked while any substitution
|
|
619
|
+
* inside it is preserved verbatim for the scanners that follow.
|
|
620
|
+
*
|
|
621
|
+
* One span is never prose: a quoted word that is the OPERAND of a redirection
|
|
622
|
+
* or of `of=` (`> "/dev/null"`, `>" src.ts"`, `of=" /dev/null"`) names a file.
|
|
623
|
+
* Masking it would erase the very path the sink and bypass checks must read, so
|
|
624
|
+
* operand spans are preserved verbatim. The returned dequoted view performs
|
|
625
|
+
* shell quote removal for executable-word/argument extraction while replacing
|
|
626
|
+
* quoted separators with inert placeholders.
|
|
627
|
+
*/
|
|
628
|
+
/**
|
|
629
|
+
* Does the double quote at `quoteIndex` open a redirection / `of=` operand
|
|
630
|
+
* rather than a prose argument? Only whitespace may sit between the operator
|
|
631
|
+
* and the quote, so `> "x"`, `>"x"`, `2>>"x"`, `>|"x"`, and `of="x"` all
|
|
632
|
+
* qualify, while `--evidence "a > b"` does not.
|
|
400
633
|
*/
|
|
401
|
-
function
|
|
634
|
+
function opensRedirectionOperand(command: string, quoteIndex: number): boolean {
|
|
635
|
+
let cursor = quoteIndex - 1;
|
|
636
|
+
while (cursor >= 0 && (command[cursor] === " " || command[cursor] === "\t")) cursor -= 1;
|
|
637
|
+
if (cursor < 0) return false;
|
|
638
|
+
const previous = command[cursor];
|
|
639
|
+
if (previous === ">" || previous === "<" || previous === "|" || previous === "&") {
|
|
640
|
+
// `|`/`&` qualify only as part of a redirection operator (`>|`, `>&`).
|
|
641
|
+
if (previous === "|" || previous === "&") {
|
|
642
|
+
const before = command[cursor - 1];
|
|
643
|
+
return before === ">" || before === "<";
|
|
644
|
+
}
|
|
645
|
+
return true;
|
|
646
|
+
}
|
|
647
|
+
// `of="..."` (dd) names an output file the same way a redirection does.
|
|
648
|
+
return previous === "=" && /(?:^|[\s;&|])of=$/i.test(command.slice(0, cursor + 1));
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
interface MaskedQuotedSpans {
|
|
652
|
+
masked: string;
|
|
653
|
+
/**
|
|
654
|
+
* Quote removal preserves executable word characters while neutralizing
|
|
655
|
+
* quoted separators/metacharacters. This lets mutation extraction recognize
|
|
656
|
+
* `r"m"` and `rm "src/product.ts"` without re-exposing prose as syntax.
|
|
657
|
+
*/
|
|
658
|
+
dequoted: string;
|
|
659
|
+
/** True when live syntax cannot be balanced by this lightweight parser. */
|
|
660
|
+
unmodeled: boolean;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
type QuotedSpanFrame = {
|
|
664
|
+
kind: "root" | "paren" | "backtick";
|
|
665
|
+
quote: "none" | "single" | "double";
|
|
666
|
+
parenDepth: number;
|
|
667
|
+
quotedOperand: boolean;
|
|
668
|
+
/** An unquoted `#` comment consumes the rest of this live frame line. */
|
|
669
|
+
comment: boolean;
|
|
670
|
+
/** Last live byte in this frame, used for comment-boundary recognition. */
|
|
671
|
+
previous: string;
|
|
672
|
+
/** True while the frame is at a command-list boundary before its first word. */
|
|
673
|
+
expectCommand: boolean;
|
|
674
|
+
};
|
|
675
|
+
|
|
676
|
+
function maskQuotedSpans(command: string): MaskedQuotedSpans {
|
|
402
677
|
let masked = "";
|
|
403
|
-
let
|
|
404
|
-
|
|
678
|
+
let dequoted = "";
|
|
679
|
+
let unmodeledSyntax = false;
|
|
680
|
+
const frames: QuotedSpanFrame[] = [
|
|
681
|
+
{
|
|
682
|
+
kind: "root",
|
|
683
|
+
quote: "none",
|
|
684
|
+
parenDepth: 0,
|
|
685
|
+
quotedOperand: false,
|
|
686
|
+
comment: false,
|
|
687
|
+
previous: "",
|
|
688
|
+
expectCommand: true,
|
|
689
|
+
},
|
|
690
|
+
];
|
|
691
|
+
const dequoteData = (character: string): string => (/[\w./-]/.test(character) ? character : "_");
|
|
692
|
+
const appendLive = (frame: QuotedSpanFrame, character: string): void => {
|
|
693
|
+
masked += character;
|
|
694
|
+
dequoted += character;
|
|
695
|
+
frame.previous = character;
|
|
696
|
+
if (character === "\n" || ";|&".includes(character)) frame.expectCommand = true;
|
|
697
|
+
else if (character === "(" && frame.kind === "paren") frame.expectCommand = true;
|
|
698
|
+
else if (!/\s/.test(character)) frame.expectCommand = false;
|
|
699
|
+
};
|
|
700
|
+
const appendQuoted = (character: string, operand: boolean): void => {
|
|
701
|
+
if (operand) masked += character;
|
|
702
|
+
else masked += character === "\n" ? "\n" : " ";
|
|
703
|
+
dequoted += dequoteData(character);
|
|
704
|
+
};
|
|
705
|
+
|
|
706
|
+
for (let index = 0; index < command.length; index += 1) {
|
|
707
|
+
const frame = frames.at(-1) as QuotedSpanFrame;
|
|
708
|
+
const character = command[index] as string;
|
|
709
|
+
const next = command[index + 1];
|
|
710
|
+
|
|
711
|
+
// A comment inside a live substitution must not let a literal `)` close
|
|
712
|
+
// that substitution. Preserve the newline as syntax, but mask all bytes
|
|
713
|
+
// before it as inert comment data.
|
|
714
|
+
if (frame.comment) {
|
|
715
|
+
if (character === "\n") {
|
|
716
|
+
frame.comment = false;
|
|
717
|
+
appendLive(frame, character);
|
|
718
|
+
} else {
|
|
719
|
+
appendQuoted(character, false);
|
|
720
|
+
}
|
|
721
|
+
continue;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
// Backslash escapes are quote syntax, not command boundaries. In the
|
|
725
|
+
// dequoted view the escaped byte survives only as data; in the masked
|
|
726
|
+
// view preserve the historical bytes so redirection extraction remains
|
|
727
|
+
// conservative.
|
|
728
|
+
if (character === "\\" && frame.quote !== "single") {
|
|
729
|
+
if (next === undefined) {
|
|
730
|
+
appendQuoted(character, frame.quote !== "none" && frame.quotedOperand);
|
|
731
|
+
continue;
|
|
732
|
+
}
|
|
733
|
+
if (next === "\n") {
|
|
734
|
+
index += 1;
|
|
735
|
+
continue;
|
|
736
|
+
}
|
|
737
|
+
if (frame.quote === "none" || frame.quotedOperand) masked += character + next;
|
|
738
|
+
else masked += " ";
|
|
739
|
+
dequoted += dequoteData(next);
|
|
740
|
+
frame.previous = "_";
|
|
741
|
+
if (frame.quote === "none") frame.expectCommand = false;
|
|
742
|
+
index += 1;
|
|
743
|
+
continue;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
if (frame.quote === "single") {
|
|
747
|
+
if (character === "'") {
|
|
748
|
+
masked += character;
|
|
749
|
+
frame.quote = "none";
|
|
750
|
+
frame.quotedOperand = false;
|
|
751
|
+
frame.previous = character;
|
|
752
|
+
} else {
|
|
753
|
+
appendQuoted(character, frame.quotedOperand);
|
|
754
|
+
}
|
|
755
|
+
continue;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
if (frame.quote === "double") {
|
|
759
|
+
if (character === '"') {
|
|
760
|
+
masked += character;
|
|
761
|
+
frame.quote = "none";
|
|
762
|
+
frame.quotedOperand = false;
|
|
763
|
+
frame.previous = character;
|
|
764
|
+
continue;
|
|
765
|
+
}
|
|
766
|
+
// A substitution is live even when it appears inside a double-quoted
|
|
767
|
+
// argument. Push a separate parser frame so quotes/parentheses inside
|
|
768
|
+
// the substitution cannot close the surrounding `"` prematurely.
|
|
769
|
+
if (character === "$" && next === "(") {
|
|
770
|
+
masked += "$(";
|
|
771
|
+
dequoted += "$(";
|
|
772
|
+
frame.previous = "(";
|
|
773
|
+
frame.expectCommand = false;
|
|
774
|
+
frames.push({
|
|
775
|
+
kind: "paren",
|
|
776
|
+
quote: "none",
|
|
777
|
+
parenDepth: 0,
|
|
778
|
+
quotedOperand: false,
|
|
779
|
+
comment: false,
|
|
780
|
+
previous: "",
|
|
781
|
+
expectCommand: true,
|
|
782
|
+
});
|
|
783
|
+
index += 1;
|
|
784
|
+
continue;
|
|
785
|
+
}
|
|
786
|
+
if (character === "`") {
|
|
787
|
+
masked += character;
|
|
788
|
+
dequoted += character;
|
|
789
|
+
frame.previous = character;
|
|
790
|
+
frame.expectCommand = false;
|
|
791
|
+
frames.push({
|
|
792
|
+
kind: "backtick",
|
|
793
|
+
quote: "none",
|
|
794
|
+
parenDepth: 0,
|
|
795
|
+
quotedOperand: false,
|
|
796
|
+
comment: false,
|
|
797
|
+
previous: "",
|
|
798
|
+
expectCommand: true,
|
|
799
|
+
});
|
|
800
|
+
continue;
|
|
801
|
+
}
|
|
802
|
+
appendQuoted(character, frame.quotedOperand);
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
// A command-substitution frame closes only at its own unquoted `)`.
|
|
807
|
+
// Parentheses nested inside `$((…))`/`$( (… ) …)` are tracked separately.
|
|
808
|
+
if (frame.kind === "paren" && character === ")") {
|
|
809
|
+
if (frame.parenDepth > 0) {
|
|
810
|
+
frame.parenDepth -= 1;
|
|
811
|
+
appendLive(frame, character);
|
|
812
|
+
} else {
|
|
813
|
+
appendLive(frame, character);
|
|
814
|
+
frames.pop();
|
|
815
|
+
const parent = frames.at(-1);
|
|
816
|
+
if (parent) {
|
|
817
|
+
// A substitution close belongs to the current shell word.
|
|
818
|
+
parent.previous = "_";
|
|
819
|
+
parent.expectCommand = false;
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
if (frame.kind === "backtick" && character === "`") {
|
|
825
|
+
appendLive(frame, character);
|
|
826
|
+
frames.pop();
|
|
827
|
+
const parent = frames.at(-1);
|
|
828
|
+
if (parent) {
|
|
829
|
+
parent.previous = character;
|
|
830
|
+
parent.expectCommand = false;
|
|
831
|
+
}
|
|
832
|
+
continue;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
if (frame.quote === "none" && character === "#" && (frame.previous === "" || /[\s;|&()]/.test(frame.previous))) {
|
|
836
|
+
frame.comment = true;
|
|
837
|
+
appendQuoted(character, false);
|
|
838
|
+
continue;
|
|
839
|
+
}
|
|
840
|
+
if (frame.quote === "none" && frame.expectCommand) {
|
|
841
|
+
const ahead = command.slice(index, index + 9);
|
|
842
|
+
if (
|
|
843
|
+
frame.kind !== "root" &&
|
|
844
|
+
/^(?:case|if|for|while|until|select|function|time|!|\{)(?:[\s;|&()]|$)/.test(ahead)
|
|
845
|
+
) {
|
|
846
|
+
// Compound commands have command positions the mutation regexes do
|
|
847
|
+
// not model; `case` also uses `)` as a pattern terminator. Balanced
|
|
848
|
+
// parentheses alone cannot authorize these live substitution bodies.
|
|
849
|
+
unmodeledSyntax = true;
|
|
850
|
+
} else if (frame.kind === "root" && /^(?:case|select|function)(?:[\s;|&()]|$)/.test(ahead)) {
|
|
851
|
+
// At the root the other compounds are recovered by command-position
|
|
852
|
+
// keyword normalization below, but `case` overloads `)` as a pattern
|
|
853
|
+
// terminator and `select`/`function` introduce command positions the
|
|
854
|
+
// regexes cannot attribute. Fail closed instead of scanning blind.
|
|
855
|
+
unmodeledSyntax = true;
|
|
856
|
+
}
|
|
857
|
+
}
|
|
405
858
|
if (character === "'") {
|
|
406
|
-
inSingle = !inSingle;
|
|
407
859
|
masked += character;
|
|
860
|
+
frame.quote = "single";
|
|
861
|
+
// A single-quoted redirection/`of=` operand names a file exactly like a
|
|
862
|
+
// double-quoted one (`> '/dev/null'`, `of='/dev/null'`). Masking it would
|
|
863
|
+
// erase the path the sink and bypass checks must read.
|
|
864
|
+
frame.quotedOperand = opensRedirectionOperand(command, index);
|
|
865
|
+
frame.previous = character;
|
|
866
|
+
frame.expectCommand = false;
|
|
867
|
+
continue;
|
|
868
|
+
}
|
|
869
|
+
if (character === '"') {
|
|
870
|
+
masked += character;
|
|
871
|
+
frame.quote = "double";
|
|
872
|
+
frame.quotedOperand = opensRedirectionOperand(command, index);
|
|
873
|
+
frame.previous = character;
|
|
874
|
+
frame.expectCommand = false;
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
877
|
+
if (character === "$" && next === "(") {
|
|
878
|
+
masked += "$(";
|
|
879
|
+
dequoted += "$(";
|
|
880
|
+
frame.previous = "(";
|
|
881
|
+
frame.expectCommand = false;
|
|
882
|
+
frames.push({
|
|
883
|
+
kind: "paren",
|
|
884
|
+
quote: "none",
|
|
885
|
+
parenDepth: 0,
|
|
886
|
+
quotedOperand: false,
|
|
887
|
+
comment: false,
|
|
888
|
+
previous: "",
|
|
889
|
+
expectCommand: true,
|
|
890
|
+
});
|
|
891
|
+
index += 1;
|
|
892
|
+
continue;
|
|
893
|
+
}
|
|
894
|
+
// ANSI-C (`$'…'`) and locale-translated (`$"…"`) quoting: bash strips the
|
|
895
|
+
// `$` during quote removal, so `$'rm' src/product.ts` really executes `rm`.
|
|
896
|
+
// The dequoted view must drop the `$` too, otherwise the executable word
|
|
897
|
+
// keeps a leading `$` and misses the mutation regexes entirely. The masked
|
|
898
|
+
// (syntax) view keeps the byte so redirection offsets stay conservative.
|
|
899
|
+
if (character === "$" && (next === "'" || next === '"')) {
|
|
900
|
+
masked += character;
|
|
901
|
+
frame.quote = next === "'" ? "single" : "double";
|
|
902
|
+
masked += next;
|
|
903
|
+
frame.quotedOperand = opensRedirectionOperand(command, index);
|
|
904
|
+
frame.previous = next;
|
|
905
|
+
frame.expectCommand = false;
|
|
906
|
+
index += 1;
|
|
408
907
|
continue;
|
|
409
908
|
}
|
|
410
|
-
|
|
909
|
+
if (character === "`") {
|
|
910
|
+
appendLive(frame, character);
|
|
911
|
+
frames.push({
|
|
912
|
+
kind: "backtick",
|
|
913
|
+
quote: "none",
|
|
914
|
+
parenDepth: 0,
|
|
915
|
+
quotedOperand: false,
|
|
916
|
+
comment: false,
|
|
917
|
+
previous: "",
|
|
918
|
+
expectCommand: true,
|
|
919
|
+
});
|
|
920
|
+
continue;
|
|
921
|
+
}
|
|
922
|
+
if (frame.kind === "paren" && character === "(") frame.parenDepth += 1;
|
|
923
|
+
appendLive(frame, character);
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
// An unbalanced quote/substitution means the parse is unreliable; keep the
|
|
927
|
+
// original text so both passes remain fail-closed rather than going blind.
|
|
928
|
+
const root = frames[0];
|
|
929
|
+
const unbalanced = frames.length !== 1 || root?.quote !== "none";
|
|
930
|
+
if (unbalanced || unmodeledSyntax) {
|
|
931
|
+
return { masked: command, dequoted: command, unmodeled: true };
|
|
411
932
|
}
|
|
412
|
-
//
|
|
413
|
-
//
|
|
414
|
-
|
|
933
|
+
// `then rm x` / `do rm x` / `{ rm x` put a mutator in a command position that
|
|
934
|
+
// is not preceded by a `;`/`|`/`&` separator, so the mutation regexes would
|
|
935
|
+
// read `then rm` as a single opaque word. Replacing the keyword with a `;`
|
|
936
|
+
// keeps byte length (match offsets stay aligned) while exposing the position.
|
|
937
|
+
const exposeCommandPositions = (value: string): string =>
|
|
938
|
+
value.replace(BASH_COMMAND_POSITION_KEYWORD_RE, segment => {
|
|
939
|
+
const keyword = segment.trimEnd();
|
|
940
|
+
return `${keyword.slice(0, keyword.length - 1)};`.padEnd(segment.length, " ");
|
|
941
|
+
});
|
|
942
|
+
return { masked: exposeCommandPositions(masked), dequoted: exposeCommandPositions(dequoted), unmodeled: false };
|
|
415
943
|
}
|
|
416
944
|
|
|
417
945
|
function isDeviceSinkPath(value: string): boolean {
|
|
418
946
|
return DEVICE_SINK_PATHS.has(cleanShellWord(value));
|
|
419
947
|
}
|
|
420
948
|
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
949
|
+
interface HeredocMaskResult {
|
|
950
|
+
masked: string;
|
|
951
|
+
/** An unquoted-delimiter heredoc body carried `$(…)`/backtick expansion — live code the scanner cannot model. */
|
|
952
|
+
opaqueExpansion: boolean;
|
|
953
|
+
/** The heredoc feeds a stdin applier (patch/ed/ex/sqlite3) whose body mutates files no scan can attribute. */
|
|
954
|
+
mutatingConsumer: boolean;
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/** Quote/substitution state carried ACROSS physical lines so multiline constructs cannot fake heredoc openers. */
|
|
958
|
+
interface ShellQuoteState {
|
|
959
|
+
inSingle: boolean;
|
|
960
|
+
inDouble: boolean;
|
|
961
|
+
/** The open single quote is ANSI-C (`$'…'`): backslash escapes inside it decode at runtime. */
|
|
962
|
+
inAnsiC: boolean;
|
|
963
|
+
/**
|
|
964
|
+
* Paren stack inside substitutions: `true` for a `$(`/`<(`/`>(` opener
|
|
965
|
+
* (its `)` is a word character), `false` for a plain nested paren (its `)`
|
|
966
|
+
* is an operator, so a following `#` starts a comment).
|
|
967
|
+
*/
|
|
968
|
+
parenStack: boolean[];
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
/**
|
|
972
|
+
* Mask one physical line for syntax analysis, carrying `state` across lines:
|
|
973
|
+
* quoted spans and backslash-escaped characters become spaces (they are data,
|
|
974
|
+
* never syntax), so a `<<` inside `"…"`/`'…'` — even when the quote opened on a
|
|
975
|
+
* PREVIOUS line — or an escaped separator like `\|` is never misread. An
|
|
976
|
+
* unquoted `#` at a word boundary starts a comment: the rest of the line is
|
|
977
|
+
* blanked without touching quote state, so a stray quote inside a comment
|
|
978
|
+
* cannot poison later lines. A `)` closing a `$(`/`<(`/`>(` substitution is
|
|
979
|
+
* part of the current word (`x=$(true)#literal`), not a comment boundary.
|
|
980
|
+
* `masked` is the same length as the input so match offsets stay aligned.
|
|
981
|
+
* `dequoted` applies bash-like QUOTE REMOVAL instead — quote/backslash marks
|
|
982
|
+
* drop, quoted word characters stay, quoted metacharacters neutralize to `_` —
|
|
983
|
+
* so obfuscated spellings (`e\val`, `'ev'al`) reassemble into their real
|
|
984
|
+
* command word without quoted data ever forming fake command boundaries. A
|
|
985
|
+
* leading `$` immediately before `'…'` (ANSI-C) or `"…"` (locale-translated)
|
|
986
|
+
* is stripped during quote removal too, so `$'eval'`/`$"eval"` dequote to
|
|
987
|
+
* plain `eval`, matching real bash quote-removal semantics for both forms.
|
|
988
|
+
* `continued` reports an unescaped trailing backslash outside quotes (logical
|
|
989
|
+
* line continuation).
|
|
990
|
+
*/
|
|
991
|
+
function maskLineForSyntax(
|
|
992
|
+
line: string,
|
|
993
|
+
state: ShellQuoteState,
|
|
994
|
+
): { masked: string; dequoted: string; continued: boolean; ansiCEscape: boolean } {
|
|
995
|
+
let masked = "";
|
|
996
|
+
let dequoted = "";
|
|
997
|
+
let escaped = false;
|
|
998
|
+
let previous = "";
|
|
999
|
+
let ansiCEscape = false;
|
|
1000
|
+
// Quoted data keeps word characters (so `'ev'al` reassembles to `eval`) but
|
|
1001
|
+
// neutralizes everything else to `_` so it can never form a command boundary.
|
|
1002
|
+
const dequoteData = (character: string): string => (/[\w./-]/.test(character) ? character : "_");
|
|
1003
|
+
for (const character of line) {
|
|
1004
|
+
if (state.inSingle) {
|
|
1005
|
+
if (character === "'") {
|
|
1006
|
+
state.inSingle = false;
|
|
1007
|
+
state.inAnsiC = false;
|
|
1008
|
+
} else {
|
|
1009
|
+
// ANSI-C escapes (`$'\145val'`) decode at runtime into characters the
|
|
1010
|
+
// dequoted view cannot reproduce — flag them so the caller fails closed.
|
|
1011
|
+
if (state.inAnsiC && character === "\\") ansiCEscape = true;
|
|
1012
|
+
masked += " ";
|
|
1013
|
+
dequoted += dequoteData(character);
|
|
1014
|
+
previous = character;
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
masked += "'";
|
|
1018
|
+
previous = character;
|
|
1019
|
+
continue;
|
|
437
1020
|
}
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
// on the masked view so quoted argument data cannot look like a redirection.
|
|
445
|
-
const scanned = maskSingleQuotedSpans(command);
|
|
446
|
-
if (BASH_OPAQUE_INTERPRETER_WRITE_RE.test(command) || BASH_HEREDOC_OPAQUE_INTERPRETER_WRITE_RE.test(command)) {
|
|
447
|
-
targets.explicitMutation = true;
|
|
448
|
-
targets.unknown = true;
|
|
449
|
-
}
|
|
450
|
-
// `exec 1<>file` rebinds a descriptor, so a later `>/dev/null` may not reach the device at all.
|
|
451
|
-
if (BASH_EXEC_REDIRECT_RE.test(scanned)) {
|
|
452
|
-
targets.explicitMutation = true;
|
|
453
|
-
targets.unknown = true;
|
|
454
|
-
}
|
|
455
|
-
for (const match of scanned.matchAll(BASH_EXTENDED_WRITE_RE)) {
|
|
456
|
-
targets.explicitMutation = true;
|
|
457
|
-
const cleaned = cleanShellWord(match[1] ?? "");
|
|
458
|
-
if (!cleaned) targets.unknown = true;
|
|
459
|
-
else if (!isDeviceSinkPath(cleaned)) addPath(targets, cleaned);
|
|
460
|
-
}
|
|
461
|
-
for (const match of scanned.matchAll(BASH_DD_OUTPUT_RE)) {
|
|
462
|
-
targets.explicitMutation = true;
|
|
463
|
-
const parts = shellWords(match[1] ?? "").map(cleanShellWord);
|
|
464
|
-
// Every `of=` counts: GNU dd honors the last one, so `of=/dev/null of=real.ts` writes real.ts.
|
|
465
|
-
const outputs = parts.filter(part => part.startsWith("of="));
|
|
466
|
-
if (outputs.length === 0) targets.unknown = true;
|
|
467
|
-
for (const output of outputs) {
|
|
468
|
-
const outputPath = cleanShellWord(output.slice(3));
|
|
469
|
-
if (!outputPath) targets.unknown = true;
|
|
470
|
-
else if (!isDeviceSinkPath(outputPath)) addPath(targets, outputPath);
|
|
1021
|
+
if (escaped) {
|
|
1022
|
+
escaped = false;
|
|
1023
|
+
masked += " ";
|
|
1024
|
+
dequoted += dequoteData(character);
|
|
1025
|
+
previous = character;
|
|
1026
|
+
continue;
|
|
471
1027
|
}
|
|
1028
|
+
if (character === "\\") {
|
|
1029
|
+
escaped = true;
|
|
1030
|
+
masked += " ";
|
|
1031
|
+
previous = character;
|
|
1032
|
+
continue;
|
|
1033
|
+
}
|
|
1034
|
+
if (state.inDouble) {
|
|
1035
|
+
if (character === '"') state.inDouble = false;
|
|
1036
|
+
else {
|
|
1037
|
+
masked += " ";
|
|
1038
|
+
dequoted += dequoteData(character);
|
|
1039
|
+
previous = character;
|
|
1040
|
+
continue;
|
|
1041
|
+
}
|
|
1042
|
+
masked += '"';
|
|
1043
|
+
previous = character;
|
|
1044
|
+
continue;
|
|
1045
|
+
}
|
|
1046
|
+
if (
|
|
1047
|
+
character === "(" &&
|
|
1048
|
+
(previous === "$" || previous === "<" || previous === ">" || state.parenStack.length > 0)
|
|
1049
|
+
) {
|
|
1050
|
+
// Substitution opener, or any paren nested INSIDE one (e.g. `$((1))`,
|
|
1051
|
+
// `$(f (x))`): both must be balanced before the substitution closes.
|
|
1052
|
+
state.parenStack.push(previous === "$" || previous === "<" || previous === ">");
|
|
1053
|
+
masked += character;
|
|
1054
|
+
dequoted += character;
|
|
1055
|
+
previous = character;
|
|
1056
|
+
continue;
|
|
1057
|
+
}
|
|
1058
|
+
if (character === ")" && state.parenStack.length > 0) {
|
|
1059
|
+
const wasSubstitutionOpener = state.parenStack.pop() === true;
|
|
1060
|
+
masked += character;
|
|
1061
|
+
dequoted += character;
|
|
1062
|
+
// A substitution close binds to the surrounding word (`x=$(true)#lit`);
|
|
1063
|
+
// a nested subshell close is an operator, so `#` after it comments.
|
|
1064
|
+
previous = wasSubstitutionOpener ? "x" : ")";
|
|
1065
|
+
continue;
|
|
1066
|
+
}
|
|
1067
|
+
if (
|
|
1068
|
+
character === "#" &&
|
|
1069
|
+
(previous === "" || previous === " " || previous === "\t" || ";|&()".includes(previous))
|
|
1070
|
+
) {
|
|
1071
|
+
// Comment: blank the remainder without evaluating quotes inside it.
|
|
1072
|
+
masked += " ".repeat(line.length - masked.length);
|
|
1073
|
+
return { masked, dequoted, continued: false, ansiCEscape };
|
|
1074
|
+
}
|
|
1075
|
+
if (character === "'") {
|
|
1076
|
+
state.inSingle = true;
|
|
1077
|
+
masked += "'";
|
|
1078
|
+
// ANSI-C quoting `$'…'`: bash strips the `$` during quote removal, and
|
|
1079
|
+
// escapes inside decode at runtime.
|
|
1080
|
+
if (dequoted.endsWith("$")) {
|
|
1081
|
+
dequoted = dequoted.slice(0, -1);
|
|
1082
|
+
state.inAnsiC = true;
|
|
1083
|
+
}
|
|
1084
|
+
previous = character;
|
|
1085
|
+
continue;
|
|
1086
|
+
}
|
|
1087
|
+
if (character === '"') {
|
|
1088
|
+
state.inDouble = true;
|
|
1089
|
+
masked += '"';
|
|
1090
|
+
// `$"…"` locale-translated strings undergo the same quote removal as
|
|
1091
|
+
// ANSI-C `$'…'`: bash drops the `$`, so `$"eval"` dequotes to `eval`.
|
|
1092
|
+
if (dequoted.endsWith("$")) dequoted = dequoted.slice(0, -1);
|
|
1093
|
+
previous = character;
|
|
1094
|
+
continue;
|
|
1095
|
+
}
|
|
1096
|
+
masked += character;
|
|
1097
|
+
dequoted += character;
|
|
1098
|
+
previous = character;
|
|
472
1099
|
}
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
1100
|
+
return { masked, dequoted, continued: escaped, ansiCEscape };
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
const DATA_CONSUMER_NAMES = new Set(HEREDOC_DATA_CONSUMERS);
|
|
1104
|
+
/**
|
|
1105
|
+
* Command-position words that force the fail-closed pass. `eval`/`source`/`.`
|
|
1106
|
+
* can install a shadow from data the syntax view has blanked (quoted strings,
|
|
1107
|
+
* /dev/stdin). `case` introduces pattern `)` terminators that desync the
|
|
1108
|
+
* substitution-depth scanner (`$(case x in x) …;; esac)`), making comment
|
|
1109
|
+
* detection unreliable — masking is disabled rather than guessing.
|
|
1110
|
+
*/
|
|
1111
|
+
const SHELL_EVALUATED_COMMANDS = new Set(["eval", "source", ".", "case"]);
|
|
1112
|
+
|
|
1113
|
+
/** Wrappers whose next word is still the effective command (`builtin eval …`, `command cat …`). */
|
|
1114
|
+
const SHELL_COMMAND_WRAPPER_WORDS = new Set(["sudo", "builtin", "command", "exec", "nohup", "nice"]);
|
|
1115
|
+
|
|
1116
|
+
/** Reserved words that introduce a nested command position (`if eval …`, `while eval …`). */
|
|
1117
|
+
const SHELL_RESERVED_PREFIX_WORDS = new Set([
|
|
1118
|
+
"if",
|
|
1119
|
+
"then",
|
|
1120
|
+
"else",
|
|
1121
|
+
"elif",
|
|
1122
|
+
"while",
|
|
1123
|
+
"until",
|
|
1124
|
+
"do",
|
|
1125
|
+
"time",
|
|
1126
|
+
"coproc",
|
|
1127
|
+
"{",
|
|
1128
|
+
"!",
|
|
1129
|
+
]);
|
|
1130
|
+
|
|
1131
|
+
/** A redirection token (`</dev/null`, `2>err`, `>out`) — not a command word. */
|
|
1132
|
+
const SHELL_REDIRECTION_TOKEN_RE = /^\d*[<>]/;
|
|
1133
|
+
|
|
1134
|
+
/** Command-position words of one command-list segment: the first real word plus words after reserved prefixes. */
|
|
1135
|
+
function commandPositionWords(segment: string): string[] {
|
|
1136
|
+
const words: string[] = [];
|
|
1137
|
+
let expectCommand = true;
|
|
1138
|
+
let afterWrapper = false;
|
|
1139
|
+
let afterBareRedirection = false;
|
|
1140
|
+
for (const word of segment.trim().split(/\s+/)) {
|
|
1141
|
+
if (!word) continue;
|
|
1142
|
+
// A bare redirection operator (`<`, `2>`) consumes the NEXT word as its target.
|
|
1143
|
+
if (afterBareRedirection) {
|
|
1144
|
+
afterBareRedirection = false;
|
|
490
1145
|
continue;
|
|
491
1146
|
}
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
)
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
1147
|
+
if (expectCommand) {
|
|
1148
|
+
if (/^\w+=/.test(word)) continue;
|
|
1149
|
+
// Leading redirections precede the command word (`</dev/null eval …`).
|
|
1150
|
+
// A bare operator (`<`, `2>`) additionally consumes its separated target.
|
|
1151
|
+
if (SHELL_REDIRECTION_TOKEN_RE.test(word)) {
|
|
1152
|
+
if (/^\d*[<>]+$/.test(word)) afterBareRedirection = true;
|
|
1153
|
+
continue;
|
|
1154
|
+
}
|
|
1155
|
+
if (SHELL_COMMAND_WRAPPER_WORDS.has(word.toLowerCase())) {
|
|
1156
|
+
// The wrapper's effective command follows, possibly after options/`--`.
|
|
1157
|
+
afterWrapper = true;
|
|
1158
|
+
continue;
|
|
1159
|
+
}
|
|
1160
|
+
if (afterWrapper && (word === "--" || word.startsWith("-"))) {
|
|
1161
|
+
// `command -v`/`-V` only DESCRIBES its operand — the rest is data.
|
|
1162
|
+
if (/^-[a-zA-Z]*[vV]/.test(word)) return words;
|
|
1163
|
+
// Other wrapper options (`command -p`, `builtin --`) precede the real command.
|
|
1164
|
+
continue;
|
|
1165
|
+
}
|
|
1166
|
+
afterWrapper = false;
|
|
1167
|
+
if (SHELL_RESERVED_PREFIX_WORDS.has(word.toLowerCase())) {
|
|
1168
|
+
// Reserved word keeps the NEXT word in command position.
|
|
1169
|
+
continue;
|
|
1170
|
+
}
|
|
1171
|
+
words.push(word.split("/").pop()?.toLowerCase() ?? "");
|
|
1172
|
+
expectCommand = false;
|
|
506
1173
|
}
|
|
1174
|
+
// Argument position: only real list operators (handled by the segment
|
|
1175
|
+
// split) restore command position — reserved-word TEXT here is data.
|
|
507
1176
|
}
|
|
508
|
-
return
|
|
1177
|
+
return words;
|
|
509
1178
|
}
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
if (tool.name === "bash") return extractBashTargets(args);
|
|
515
|
-
return { paths: [], unknown: true };
|
|
1179
|
+
|
|
1180
|
+
/** Command-list segments of a dequoted view (split at `;`, `|`, `&`, `(`, backtick, newline). */
|
|
1181
|
+
function commandListSegments(dequotedView: string): string[] {
|
|
1182
|
+
return dequotedView.split(/[;|&(`\n]/);
|
|
516
1183
|
}
|
|
517
1184
|
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
1185
|
+
/**
|
|
1186
|
+
* True when any command-position word of the dequoted syntax view is
|
|
1187
|
+
* eval/source/`.` — including nested positions after reserved words
|
|
1188
|
+
* (`if eval …`). `echo eval` and `find .` never match because their
|
|
1189
|
+
* tokens sit in argument position.
|
|
1190
|
+
*/
|
|
1191
|
+
function hasShellEvaluatedCommand(dequotedView: string): boolean {
|
|
1192
|
+
return commandListSegments(dequotedView).some(segment =>
|
|
1193
|
+
commandPositionWords(segment).some(word => SHELL_EVALUATED_COMMANDS.has(word)),
|
|
1194
|
+
);
|
|
522
1195
|
}
|
|
523
1196
|
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
1197
|
+
/**
|
|
1198
|
+
* True when live syntax actually DECLARES a shadow of an allowlisted
|
|
1199
|
+
* data-consumer name: `name()` at a command-list start, `function name`,
|
|
1200
|
+
* or `alias name=…` — each in command position, so `echo function cat`
|
|
1201
|
+
* (argument position) never matches.
|
|
1202
|
+
*/
|
|
1203
|
+
function hasDataConsumerShadow(dequotedView: string): boolean {
|
|
1204
|
+
for (const segment of commandListSegments(dequotedView)) {
|
|
1205
|
+
const words = commandPositionWords(segment);
|
|
1206
|
+
for (let index = 0; index < words.length; index++) {
|
|
1207
|
+
const word = words[index] ?? "";
|
|
1208
|
+
if (word === "function") {
|
|
1209
|
+
// commandPositionWords stops after the first non-reserved word, so
|
|
1210
|
+
// re-inspect the raw segment for the name following `function`.
|
|
1211
|
+
const rawWords = segment.trim().split(/\s+/).filter(Boolean);
|
|
1212
|
+
const at = rawWords.findIndex(raw => raw.toLowerCase() === "function");
|
|
1213
|
+
const name = rawWords[at + 1]?.split("/").pop()?.toLowerCase() ?? "";
|
|
1214
|
+
if (DATA_CONSUMER_NAMES.has(name)) return true;
|
|
1215
|
+
}
|
|
1216
|
+
if (word === "alias") {
|
|
1217
|
+
const rawWords = segment.trim().split(/\s+/).filter(Boolean);
|
|
1218
|
+
if (rawWords.some(raw => DATA_CONSUMER_NAMES.has(raw.split("=")[0]?.toLowerCase() ?? ""))) return true;
|
|
1219
|
+
}
|
|
535
1220
|
}
|
|
536
1221
|
}
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
const
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
1222
|
+
// `name()` / `name ()` in command position — allow reserved-word prefixes
|
|
1223
|
+
// (`then cat() { … }`) before the name (POSIX function definition).
|
|
1224
|
+
const nameGroup = [...DATA_CONSUMER_NAMES].join("|");
|
|
1225
|
+
const reservedGroup = [...SHELL_RESERVED_PREFIX_WORDS].filter(word => /^\w+$/.test(word)).join("|");
|
|
1226
|
+
return new RegExp(
|
|
1227
|
+
`(?:^|[;|&{(\`\\n])\\s*(?:(?:${reservedGroup}|\\{|!)\\s+)*(?:${nameGroup})\\s*\\(\\s*\\)`,
|
|
1228
|
+
"i",
|
|
1229
|
+
).test(dequotedView);
|
|
545
1230
|
}
|
|
546
1231
|
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
const relative = path.relative(path.resolve(cwd), path.resolve(absolutePath));
|
|
551
|
-
if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
|
|
552
|
-
return normalizePosix(relative).split("/").filter(Boolean);
|
|
1232
|
+
/** First command word of a pipeline-segment slice of a quote-masked opener line. */
|
|
1233
|
+
function firstCommandWord(segment: string): string {
|
|
1234
|
+
return commandPositionWords(segment)[0] ?? "";
|
|
553
1235
|
}
|
|
554
1236
|
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
1237
|
+
/**
|
|
1238
|
+
* Classify the command consuming the heredoc at offset `at` of the comment-cut,
|
|
1239
|
+
* quote-masked opener line — including every DOWNSTREAM pipe stage, because
|
|
1240
|
+
* `cat <<'EOF' | bash` hands the body to the interpreter even though `cat` is
|
|
1241
|
+
* inert. Only a pipeline whose every stage is an explicitly inert data consumer
|
|
1242
|
+
* qualifies for body masking; any stdin applier stage fails closed; anything
|
|
1243
|
+
* else (interpreters, awk, unknown binaries) keeps the body live.
|
|
1244
|
+
*/
|
|
1245
|
+
function heredocConsumerKind(syntaxLine: string, at: number): "data" | "mutating" | "other" {
|
|
1246
|
+
let start = 0;
|
|
1247
|
+
for (let index = at - 1; index >= 0; index--) {
|
|
1248
|
+
const character = syntaxLine[index] ?? "";
|
|
1249
|
+
if (";|&(`".includes(character) || character === "\n") {
|
|
1250
|
+
start = index + 1;
|
|
1251
|
+
break;
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
// The heredoc's own simple command plus every downstream `|` stage until the
|
|
1255
|
+
// command list ends (`;`, `&&`, `||`, `&`, backtick, or subshell close).
|
|
1256
|
+
const segments: string[] = [syntaxLine.slice(start, at)];
|
|
1257
|
+
let cursor = at;
|
|
1258
|
+
while (cursor < syntaxLine.length) {
|
|
1259
|
+
const character = syntaxLine[cursor] ?? "";
|
|
1260
|
+
if (character === ";" || character === "&" || character === "`" || character === ")") break;
|
|
1261
|
+
if (character === "|") {
|
|
1262
|
+
if (syntaxLine[cursor + 1] === "|") break;
|
|
1263
|
+
let stageEnd = cursor + 1;
|
|
1264
|
+
while (stageEnd < syntaxLine.length && !";|&`)".includes(syntaxLine[stageEnd] ?? "")) stageEnd++;
|
|
1265
|
+
segments.push(syntaxLine.slice(cursor + 1, stageEnd));
|
|
1266
|
+
cursor = stageEnd;
|
|
1267
|
+
continue;
|
|
1268
|
+
}
|
|
1269
|
+
cursor++;
|
|
1270
|
+
}
|
|
1271
|
+
let kind: "data" | "mutating" | "other" = "data";
|
|
1272
|
+
for (const segment of segments) {
|
|
1273
|
+
const base = firstCommandWord(segment);
|
|
1274
|
+
if (HEREDOC_MUTATING_CONSUMERS.has(base)) return "mutating";
|
|
1275
|
+
if (!HEREDOC_DATA_CONSUMERS.has(base)) kind = "other";
|
|
1276
|
+
}
|
|
1277
|
+
return kind;
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
/**
|
|
1281
|
+
* Blank out heredoc BODY lines so document payloads (markdown specs, plans,
|
|
1282
|
+
* fixtures) piped to an explicitly inert data consumer (`cat <<'EOF' >
|
|
1283
|
+
* /tmp/spec.md`) are not misread as shell commands: body text like `a > b` or
|
|
1284
|
+
* stray apostrophes must not register redirection targets or unbalance the
|
|
1285
|
+
* quote masker. Bodies stay UNMASKED (scanned as today) for every other
|
|
1286
|
+
* consumer — interpreters, awk, unknown binaries — because there the body may
|
|
1287
|
+
* be live code. Stdin appliers (patch/ed/ex/sqlite3) flag `mutatingConsumer`
|
|
1288
|
+
* and the caller fails closed. Unquoted-delimiter bodies still expand
|
|
1289
|
+
* `$(…)`/backticks in real shells, so masked ones flag `opaqueExpansion`. A
|
|
1290
|
+
* `<<` inside a comment or a quoted span (including a quote opened on a
|
|
1291
|
+
* previous line) is not an opener; a line-continued opener, a shadowed
|
|
1292
|
+
* data-consumer name (`cat() { … }`), and an unterminated heredoc all keep
|
|
1293
|
+
* their bodies live so the scanner stays fail-closed rather than blind.
|
|
1294
|
+
*/
|
|
1295
|
+
function maskHeredocBodies(command: string): HeredocMaskResult {
|
|
1296
|
+
if (!command.includes("<<")) return { masked: command, opaqueExpansion: false, mutatingConsumer: false };
|
|
1297
|
+
const first = maskHeredocBodiesPass(command, false);
|
|
1298
|
+
// Fail closed on live-syntax constructs that can install a shadow the syntax
|
|
1299
|
+
// view cannot see: a function/alias definition of an allowlisted consumer
|
|
1300
|
+
// name, or a command-position eval/source/`.` whose argument is blanked
|
|
1301
|
+
// quoted data. Both run against the DEQUOTED view so quoting tricks
|
|
1302
|
+
// (`e\val`, `'ev'al`) cannot hide the word, while heredoc bodies and
|
|
1303
|
+
// comments stay excluded — a spec that merely DOCUMENTS `cat() { … }` or
|
|
1304
|
+
// mentions "eval" in prose stays inert.
|
|
1305
|
+
if (first.ansiCEscape || hasDataConsumerShadow(first.dequotedView) || hasShellEvaluatedCommand(first.dequotedView)) {
|
|
1306
|
+
return maskHeredocBodiesPass(command, true).result;
|
|
1307
|
+
}
|
|
1308
|
+
return first.result;
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
function maskHeredocBodiesPass(
|
|
1312
|
+
command: string,
|
|
1313
|
+
shadowed: boolean,
|
|
1314
|
+
): { result: HeredocMaskResult; dequotedView: string; ansiCEscape: boolean } {
|
|
1315
|
+
const lines = command.split("\n");
|
|
1316
|
+
const out: string[] = [];
|
|
1317
|
+
const dequotedLines: string[] = [];
|
|
1318
|
+
const state: ShellQuoteState = { inSingle: false, inDouble: false, inAnsiC: false, parenStack: [] };
|
|
1319
|
+
let previousContinued = false;
|
|
1320
|
+
let opaqueExpansion = false;
|
|
1321
|
+
let mutatingConsumer = false;
|
|
1322
|
+
let sawAnsiCEscape = false;
|
|
1323
|
+
for (let index = 0; index < lines.length; index++) {
|
|
1324
|
+
const line = lines[index] ?? "";
|
|
1325
|
+
out.push(line);
|
|
1326
|
+
// Cross-line quote masking decides whether a `<<` is real syntax or inert
|
|
1327
|
+
// data — even when the enclosing quote opened on a previous line.
|
|
1328
|
+
const { masked, dequoted, continued, ansiCEscape } = maskLineForSyntax(line, state);
|
|
1329
|
+
if (ansiCEscape) sawAnsiCEscape = true;
|
|
1330
|
+
const syntax = masked;
|
|
1331
|
+
const isContinuationLine = previousContinued;
|
|
1332
|
+
// Bash removes a backslash-newline pair entirely: fold a continuation into
|
|
1333
|
+
// the previous dequoted line so split command words (`e\` + `val`)
|
|
1334
|
+
// reassemble for command/shadow detection.
|
|
1335
|
+
if (isContinuationLine && dequotedLines.length > 0) {
|
|
1336
|
+
let previousDequoted = dequotedLines[dequotedLines.length - 1] ?? "";
|
|
1337
|
+
// A continuation can also split ANSI-C/locale quoting (`$\` + `'eval'` or
|
|
1338
|
+
// `$\` + `"eval"`): the rejoined `$'`/`$"` still drops its `$` during
|
|
1339
|
+
// quote removal.
|
|
1340
|
+
if (previousDequoted.endsWith("$") && (line.startsWith("'") || line.startsWith('"'))) {
|
|
1341
|
+
previousDequoted = previousDequoted.slice(0, -1);
|
|
1342
|
+
// The masker already opened this quote as ordinary (it ran before the
|
|
1343
|
+
// fold), so re-check the rejoined ANSI-C span for runtime-decoding
|
|
1344
|
+
// escapes (`$\` + `'\145val'`) it could not have flagged.
|
|
1345
|
+
if (line.startsWith("'") && /^'[^']*\\/.test(line)) sawAnsiCEscape = true;
|
|
1346
|
+
}
|
|
1347
|
+
dequotedLines[dequotedLines.length - 1] = previousDequoted + dequoted;
|
|
1348
|
+
} else {
|
|
1349
|
+
dequotedLines.push(dequoted);
|
|
1350
|
+
}
|
|
1351
|
+
previousContinued = continued;
|
|
1352
|
+
for (const match of line.matchAll(BASH_HEREDOC_OPEN_RE)) {
|
|
1353
|
+
const at = match.index ?? 0;
|
|
1354
|
+
if (syntax.slice(at, at + 2) !== "<<") continue;
|
|
1355
|
+
const delimiter = match[2] ?? match[3] ?? match[5] ?? "";
|
|
1356
|
+
if (!delimiter) continue;
|
|
1357
|
+
let kind = heredocConsumerKind(syntax, at);
|
|
1358
|
+
// A continued/continuation opener line hides part of the pipeline
|
|
1359
|
+
// (`cat <<'EOF' \` / `| bash`); a shadowed consumer name is untrustworthy.
|
|
1360
|
+
// Both downgrade masking eligibility, never block eligibility.
|
|
1361
|
+
if (kind === "data" && (shadowed || continued || isContinuationLine)) kind = "other";
|
|
1362
|
+
if (kind === "mutating") mutatingConsumer = true;
|
|
1363
|
+
const quoted = match[2] !== undefined || match[3] !== undefined || match[4] !== undefined;
|
|
1364
|
+
const stripTabs = match[1] === "-";
|
|
1365
|
+
let end = -1;
|
|
1366
|
+
for (let scan = index + 1; scan < lines.length; scan++) {
|
|
1367
|
+
const candidate = stripTabs ? (lines[scan] ?? "").replace(/^\t+/, "") : (lines[scan] ?? "");
|
|
1368
|
+
if (candidate === delimiter) {
|
|
1369
|
+
end = scan;
|
|
1370
|
+
break;
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
if (end === -1) {
|
|
1374
|
+
return {
|
|
1375
|
+
result: { masked: command, opaqueExpansion, mutatingConsumer },
|
|
1376
|
+
dequotedView: dequotedLines.join("\n"),
|
|
1377
|
+
ansiCEscape: sawAnsiCEscape,
|
|
1378
|
+
};
|
|
1379
|
+
}
|
|
1380
|
+
const maskBody = kind === "data" || kind === "mutating";
|
|
1381
|
+
for (let body = index + 1; body < end; body++) {
|
|
1382
|
+
const bodyLine = lines[body] ?? "";
|
|
1383
|
+
if (maskBody && !quoted && /\$\(|`/.test(bodyLine)) opaqueExpansion = true;
|
|
1384
|
+
out.push(maskBody ? "" : bodyLine);
|
|
1385
|
+
}
|
|
1386
|
+
out.push(lines[end] ?? "");
|
|
1387
|
+
index = end;
|
|
1388
|
+
// Heredoc bodies are data: they never affect the shell quote state or
|
|
1389
|
+
// the syntax view used for shadow detection.
|
|
1390
|
+
previousContinued = false;
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
return {
|
|
1394
|
+
result: { masked: out.join("\n"), opaqueExpansion, mutatingConsumer },
|
|
1395
|
+
dequotedView: dequotedLines.join("\n"),
|
|
1396
|
+
ansiCEscape: sawAnsiCEscape,
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
/**
|
|
1401
|
+
* A command-substitution body and whether its delimiters were balanced. An
|
|
1402
|
+
* unbalanced body is an unreliable parse and the caller fails closed on it.
|
|
1403
|
+
*/
|
|
1404
|
+
interface SubstitutionBody {
|
|
1405
|
+
body: string;
|
|
1406
|
+
balanced: boolean;
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
/** Keep parser-frame recursion bounded before extractBashTargets' semantic depth guard. */
|
|
1410
|
+
const SUBSTITUTION_PARSER_MAX_DEPTH = 64;
|
|
1411
|
+
|
|
1412
|
+
/**
|
|
1413
|
+
* Scan a `$(` body starting just after the opening paren. Quotes inside the
|
|
1414
|
+
* body are honoured: a `)` inside `'...'` or `"..."` is data, not the closer.
|
|
1415
|
+
* Nested substitutions are scanned with their own quote/comment frame, so a
|
|
1416
|
+
* `#` or quote inside `$(...)` nested in a double-quoted outer substitution
|
|
1417
|
+
* cannot desynchronise this frame. Returns the body and the index just past
|
|
1418
|
+
* its closing paren, or `end === command.length` with `balanced: false`.
|
|
1419
|
+
*/
|
|
1420
|
+
function scanDollarParenBody(command: string, start: number, parserDepth = 0): SubstitutionBody & { end: number } {
|
|
1421
|
+
let depth = 1;
|
|
1422
|
+
let inSingle = false;
|
|
1423
|
+
let inDouble = false;
|
|
1424
|
+
let inComment = false;
|
|
1425
|
+
let previous = "";
|
|
1426
|
+
for (let cursor = start; cursor < command.length; cursor += 1) {
|
|
1427
|
+
const character = command[cursor];
|
|
1428
|
+
if (inComment) {
|
|
1429
|
+
if (character === "\n") {
|
|
1430
|
+
inComment = false;
|
|
1431
|
+
previous = character;
|
|
1432
|
+
}
|
|
1433
|
+
continue;
|
|
1434
|
+
}
|
|
1435
|
+
if (character === "\\" && !inSingle) {
|
|
1436
|
+
cursor += 1;
|
|
1437
|
+
previous = "x";
|
|
1438
|
+
continue;
|
|
1439
|
+
}
|
|
1440
|
+
if (character === "'" && !inDouble) {
|
|
1441
|
+
inSingle = !inSingle;
|
|
1442
|
+
previous = character;
|
|
1443
|
+
continue;
|
|
1444
|
+
}
|
|
1445
|
+
if (character === '"' && !inSingle) {
|
|
1446
|
+
inDouble = !inDouble;
|
|
1447
|
+
previous = character;
|
|
1448
|
+
continue;
|
|
1449
|
+
}
|
|
1450
|
+
if (inSingle) continue;
|
|
1451
|
+
if (character === "$" && command[cursor + 1] === "(") {
|
|
1452
|
+
if (parserDepth >= SUBSTITUTION_PARSER_MAX_DEPTH) {
|
|
1453
|
+
return { body: command.slice(start), balanced: false, end: command.length };
|
|
1454
|
+
}
|
|
1455
|
+
const nested = scanDollarParenBody(command, cursor + 2, parserDepth + 1);
|
|
1456
|
+
if (!nested.balanced) {
|
|
1457
|
+
return { body: command.slice(start), balanced: false, end: command.length };
|
|
1458
|
+
}
|
|
1459
|
+
cursor = nested.end - 1;
|
|
1460
|
+
previous = "x";
|
|
1461
|
+
continue;
|
|
1462
|
+
}
|
|
1463
|
+
if (character === "`") {
|
|
1464
|
+
if (parserDepth >= SUBSTITUTION_PARSER_MAX_DEPTH) {
|
|
1465
|
+
return { body: command.slice(start), balanced: false, end: command.length };
|
|
1466
|
+
}
|
|
1467
|
+
const nested = scanBacktickBody(command, cursor + 1, parserDepth + 1);
|
|
1468
|
+
if (!nested.balanced) {
|
|
1469
|
+
return { body: command.slice(start), balanced: false, end: command.length };
|
|
1470
|
+
}
|
|
1471
|
+
cursor = nested.end - 1;
|
|
1472
|
+
previous = "x";
|
|
1473
|
+
continue;
|
|
1474
|
+
}
|
|
1475
|
+
if (!inDouble && character === "#" && (previous === "" || /\s/.test(previous) || ";|&()".includes(previous))) {
|
|
1476
|
+
inComment = true;
|
|
1477
|
+
continue;
|
|
1478
|
+
}
|
|
1479
|
+
if (!inDouble && character === "(") depth += 1;
|
|
1480
|
+
else if (!inDouble && character === ")") {
|
|
1481
|
+
depth -= 1;
|
|
1482
|
+
if (depth === 0) {
|
|
1483
|
+
return { body: command.slice(start, cursor), balanced: true, end: cursor + 1 };
|
|
1484
|
+
}
|
|
1485
|
+
previous = ")";
|
|
1486
|
+
continue;
|
|
1487
|
+
}
|
|
1488
|
+
previous = character;
|
|
1489
|
+
}
|
|
1490
|
+
return { body: command.slice(start), balanced: false, end: command.length };
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
/**
|
|
1494
|
+
* Scan a backtick command substitution with the same quote/comment rules as
|
|
1495
|
+
* `scanDollarParenBody`. Nested `$()` frames are skipped with their own
|
|
1496
|
+
* parser so backticks in those frames cannot close this one.
|
|
1497
|
+
*/
|
|
1498
|
+
function scanBacktickBody(command: string, start: number, parserDepth = 0): SubstitutionBody & { end: number } {
|
|
1499
|
+
let inSingle = false;
|
|
1500
|
+
let inDouble = false;
|
|
1501
|
+
let inComment = false;
|
|
1502
|
+
let previous = "";
|
|
1503
|
+
for (let cursor = start; cursor < command.length; cursor += 1) {
|
|
1504
|
+
const character = command[cursor];
|
|
1505
|
+
if (inComment) {
|
|
1506
|
+
if (character === "\n") {
|
|
1507
|
+
inComment = false;
|
|
1508
|
+
previous = character;
|
|
1509
|
+
}
|
|
1510
|
+
continue;
|
|
1511
|
+
}
|
|
1512
|
+
if (character === "\\" && !inSingle) {
|
|
1513
|
+
cursor += 1;
|
|
1514
|
+
previous = "x";
|
|
1515
|
+
continue;
|
|
1516
|
+
}
|
|
1517
|
+
if (character === "'" && !inDouble) {
|
|
1518
|
+
inSingle = !inSingle;
|
|
1519
|
+
previous = character;
|
|
1520
|
+
continue;
|
|
1521
|
+
}
|
|
1522
|
+
if (character === '"' && !inSingle) {
|
|
1523
|
+
inDouble = !inDouble;
|
|
1524
|
+
previous = character;
|
|
1525
|
+
continue;
|
|
1526
|
+
}
|
|
1527
|
+
if (inSingle) continue;
|
|
1528
|
+
if (character === "$" && command[cursor + 1] === "(") {
|
|
1529
|
+
if (parserDepth >= SUBSTITUTION_PARSER_MAX_DEPTH) {
|
|
1530
|
+
return { body: command.slice(start), balanced: false, end: command.length };
|
|
1531
|
+
}
|
|
1532
|
+
const nested = scanDollarParenBody(command, cursor + 2, parserDepth + 1);
|
|
1533
|
+
if (!nested.balanced) {
|
|
1534
|
+
return { body: command.slice(start), balanced: false, end: command.length };
|
|
1535
|
+
}
|
|
1536
|
+
cursor = nested.end - 1;
|
|
1537
|
+
previous = "x";
|
|
1538
|
+
continue;
|
|
1539
|
+
}
|
|
1540
|
+
if (character === "`") {
|
|
1541
|
+
return { body: command.slice(start, cursor), balanced: true, end: cursor + 1 };
|
|
1542
|
+
}
|
|
1543
|
+
if (!inDouble && character === "#" && (previous === "" || /\s/.test(previous) || ";|&()".includes(previous))) {
|
|
1544
|
+
inComment = true;
|
|
1545
|
+
continue;
|
|
1546
|
+
}
|
|
1547
|
+
previous = character;
|
|
1548
|
+
}
|
|
1549
|
+
return { body: command.slice(start), balanced: false, end: command.length };
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
/**
|
|
1553
|
+
* Collect the bodies of `$(...)` and backtick command substitutions. Their
|
|
1554
|
+
* contents are a live command list wherever they appear -- including inside a
|
|
1555
|
+
* double-quoted span -- so the caller rescans each one as its own script.
|
|
1556
|
+
*
|
|
1557
|
+
* Quote state is tracked the way the shell does it: an apostrophe inside a
|
|
1558
|
+
* double-quoted word is data, not a single-quote opener, so `"it's $(rm x)"`
|
|
1559
|
+
* still yields the substitution; a `)` inside a quoted argument does not close
|
|
1560
|
+
* the body, so `$(printf ')'; rm x)` yields the whole body. Single-quoted spans
|
|
1561
|
+
* are skipped because they suppress substitution entirely. Shell comments are
|
|
1562
|
+
* skipped only at word boundaries, and their quote-like text cannot poison the
|
|
1563
|
+
* surrounding frame. A body whose delimiters never balance is reported as such
|
|
1564
|
+
* so the caller fails closed.
|
|
1565
|
+
*/
|
|
1566
|
+
function extractSubstitutionBodies(command: string): SubstitutionBody[] {
|
|
1567
|
+
const bodies: SubstitutionBody[] = [];
|
|
1568
|
+
let inSingle = false;
|
|
1569
|
+
let inDouble = false;
|
|
1570
|
+
let inComment = false;
|
|
1571
|
+
let previous = "";
|
|
1572
|
+
for (let index = 0; index < command.length; index += 1) {
|
|
1573
|
+
const character = command[index];
|
|
1574
|
+
if (inComment) {
|
|
1575
|
+
if (character === "\n") {
|
|
1576
|
+
inComment = false;
|
|
1577
|
+
previous = character;
|
|
1578
|
+
}
|
|
1579
|
+
continue;
|
|
1580
|
+
}
|
|
1581
|
+
if (character === "\\" && !inSingle) {
|
|
1582
|
+
index += 1;
|
|
1583
|
+
previous = "x";
|
|
1584
|
+
continue;
|
|
1585
|
+
}
|
|
1586
|
+
if (character === "'" && !inDouble) {
|
|
1587
|
+
inSingle = !inSingle;
|
|
1588
|
+
previous = character;
|
|
1589
|
+
continue;
|
|
1590
|
+
}
|
|
1591
|
+
if (character === '"' && !inSingle) {
|
|
1592
|
+
inDouble = !inDouble;
|
|
1593
|
+
previous = character;
|
|
1594
|
+
continue;
|
|
1595
|
+
}
|
|
1596
|
+
if (inSingle) continue;
|
|
1597
|
+
if (character === "$" && command[index + 1] === "(") {
|
|
1598
|
+
const scanned = scanDollarParenBody(command, index + 2);
|
|
1599
|
+
bodies.push({ body: scanned.body, balanced: scanned.balanced });
|
|
1600
|
+
index = scanned.end - 1;
|
|
1601
|
+
previous = "x";
|
|
1602
|
+
continue;
|
|
1603
|
+
}
|
|
1604
|
+
if (character === "`") {
|
|
1605
|
+
const scanned = scanBacktickBody(command, index + 1);
|
|
1606
|
+
bodies.push({ body: scanned.body, balanced: scanned.balanced });
|
|
1607
|
+
index = scanned.end - 1;
|
|
1608
|
+
previous = "x";
|
|
1609
|
+
continue;
|
|
1610
|
+
}
|
|
1611
|
+
if (!inDouble && character === "#" && (previous === "" || /\s/.test(previous) || ";|&()".includes(previous))) {
|
|
1612
|
+
inComment = true;
|
|
1613
|
+
continue;
|
|
1614
|
+
}
|
|
1615
|
+
previous = character;
|
|
1616
|
+
}
|
|
1617
|
+
return bodies;
|
|
1618
|
+
}
|
|
1619
|
+
|
|
1620
|
+
const BASH_SED_COMMAND_RE = new RegExp(
|
|
1621
|
+
`(?:^|[;&|(\\n])\\s*(?:(?:if|then|else|elif|do|in|while|until)\\s+)*(?:!\\s+)?(?:\\w+=[^\\s]+\\s+)*(?:sudo\\s+)?${BASH_COMMAND_WRAPPER_SOURCE}(?:[^\\s;&|()]*\\/)?sed\\b((?:'[^']*'|"(?:\\\\.|[^"\\\\])*"|\\\\.|[^'";&|()\\n\\\\])*)`,
|
|
1622
|
+
"gi",
|
|
1623
|
+
);
|
|
1624
|
+
const BASH_AWK_COMMAND_RE = new RegExp(
|
|
1625
|
+
`(?:^|[;&|(\\n])\\s*(?:(?:if|then|else|elif|do|in)\\s+)*(?:!\\s+)?(?:\\w+=[^\\s]+\\s+)*(?:sudo\\s+)?${BASH_COMMAND_WRAPPER_SOURCE}(?:[^\\s;&|()]*\\/)?(?:awk|gawk|mawk|nawk|busybox\\s+awk)\\b((?:'[^']*'|"(?:\\\\.|[^"\\\\])*"|\\\\.|[^'";&|()\\n\\\\])*)`,
|
|
1626
|
+
"gi",
|
|
1627
|
+
);
|
|
1628
|
+
|
|
1629
|
+
/** `true` when index sits at a sed command letter, not inside a pattern. */
|
|
1630
|
+
function sedCommandPosition(script: string, index: number): boolean {
|
|
1631
|
+
if (index === 0) return true;
|
|
1632
|
+
return /[\s;{}\n\d$,]/.test(script[index - 1] ?? "");
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
function sedWriteName(script: string, index: number): { path: string | null; next: number } {
|
|
1636
|
+
let cursor = index;
|
|
1637
|
+
while (cursor < script.length && (script[cursor] === " " || script[cursor] === "\t")) cursor++;
|
|
1638
|
+
const start = cursor;
|
|
1639
|
+
while (cursor < script.length && script[cursor] !== ";" && script[cursor] !== "\n" && script[cursor] !== "}") {
|
|
1640
|
+
cursor++;
|
|
1641
|
+
}
|
|
1642
|
+
return { path: cursor > start ? script.slice(start, cursor) : null, next: cursor };
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
function sedAddressEnd(script: string, start: number): number | undefined {
|
|
1646
|
+
if (script[start] === "/") {
|
|
1647
|
+
let cursor = start + 1;
|
|
1648
|
+
while (cursor < script.length) {
|
|
1649
|
+
if (script[cursor] === "\\") {
|
|
1650
|
+
cursor += 2;
|
|
1651
|
+
continue;
|
|
1652
|
+
}
|
|
1653
|
+
if (script[cursor] === "/") return cursor + 1;
|
|
1654
|
+
cursor++;
|
|
1655
|
+
}
|
|
1656
|
+
return undefined;
|
|
1657
|
+
}
|
|
1658
|
+
if (script[start] === "$") return start + 1;
|
|
1659
|
+
if (!/\d/.test(script[start] ?? "")) return undefined;
|
|
1660
|
+
let cursor = start + 1;
|
|
1661
|
+
while (/\d/.test(script[cursor] ?? "")) cursor++;
|
|
1662
|
+
if (script[cursor] === "~") {
|
|
1663
|
+
cursor++;
|
|
1664
|
+
while (/\d/.test(script[cursor] ?? "")) cursor++;
|
|
1665
|
+
}
|
|
1666
|
+
return cursor;
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1669
|
+
function sedAddressWithModifiersEnd(script: string, start: number): number | undefined {
|
|
1670
|
+
let cursor = sedAddressEnd(script, start);
|
|
1671
|
+
if (cursor === undefined) return undefined;
|
|
1672
|
+
if (script[start] === "/") {
|
|
1673
|
+
while (script[cursor] === "I" || script[cursor] === "M") cursor++;
|
|
1674
|
+
}
|
|
1675
|
+
return cursor;
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
function sedRegexAddressWritePath(script: string, start: number): { path: string | null; next: number } | undefined {
|
|
1679
|
+
let cursor = sedAddressWithModifiersEnd(script, start);
|
|
1680
|
+
if (cursor === undefined) return undefined;
|
|
1681
|
+
while (script[cursor] === " " || script[cursor] === "\t") cursor++;
|
|
1682
|
+
if (script[cursor] === ",") {
|
|
1683
|
+
cursor++;
|
|
1684
|
+
while (script[cursor] === " " || script[cursor] === "\t") cursor++;
|
|
1685
|
+
const rangeEnd = sedAddressWithModifiersEnd(script, cursor);
|
|
1686
|
+
if (rangeEnd === undefined) return undefined;
|
|
1687
|
+
cursor = rangeEnd;
|
|
1688
|
+
while (script[cursor] === " " || script[cursor] === "\t") cursor++;
|
|
1689
|
+
}
|
|
1690
|
+
if (script[cursor] === "!") cursor++;
|
|
1691
|
+
while (script[cursor] === " " || script[cursor] === "\t") cursor++;
|
|
1692
|
+
if ((script[cursor] !== "w" && script[cursor] !== "W") || !" \t;\n}".includes(script[cursor + 1] ?? "\n")) {
|
|
1693
|
+
return undefined;
|
|
1694
|
+
}
|
|
1695
|
+
return sedWriteName(script, cursor + 1);
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
/**
|
|
1699
|
+
* Filename a sed script writes with the `w`/`W` command or an `s///w file` flag.
|
|
1700
|
+
* `undefined` means this text does not write. `null` means it writes without a
|
|
1701
|
+
* literal filename.
|
|
1702
|
+
*/
|
|
1703
|
+
/**
|
|
1704
|
+
* GNU sed can execute shell commands: the `e` command replaces the pattern
|
|
1705
|
+
* space with a shell command's output and `s///e` runs the result. Neither form
|
|
1706
|
+
* names a file, so their write targets cannot be derived and the whole program
|
|
1707
|
+
* must be treated as an unclassified mutation.
|
|
1708
|
+
*/
|
|
1709
|
+
function sedScriptRunsShellCommand(script: string): boolean {
|
|
1710
|
+
// GNU sed accepts a numeric, `$`, or regular-expression address (`/re/e cmd`).
|
|
1711
|
+
if (/(?:^|[;{}\n])\s*(?:(?:[0-9$]+(?:,[0-9$]+)?|\/(?:\\[\s\S]|[^\\/\n])*\/)\s*!?\s*)?e(?=[\s;}\n]|$)/.test(script))
|
|
1712
|
+
return true;
|
|
1713
|
+
return /\bs(\W)(?:\\.|(?!\1)[^\n])*?\1(?:\\.|(?!\1)[^\n])*?\1[gpiImM0-9]*e(?![A-Za-z])/.test(script);
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
function sedScriptWritePath(script: string): string | null | undefined {
|
|
1717
|
+
if (sedScriptRunsShellCommand(script)) return null;
|
|
1718
|
+
let index = 0;
|
|
1719
|
+
let foundWrite = false;
|
|
1720
|
+
let foundPath: string | null | undefined;
|
|
1721
|
+
while (index < script.length) {
|
|
1722
|
+
const character = script[index] ?? "";
|
|
1723
|
+
if (" \t\n;{}".includes(character)) {
|
|
1724
|
+
index++;
|
|
1725
|
+
continue;
|
|
1726
|
+
}
|
|
1727
|
+
if (character === "/" && sedCommandPosition(script, index)) {
|
|
1728
|
+
const written = sedRegexAddressWritePath(script, index);
|
|
1729
|
+
if (written) {
|
|
1730
|
+
if (foundWrite) return null;
|
|
1731
|
+
foundWrite = true;
|
|
1732
|
+
foundPath = written.path;
|
|
1733
|
+
index = Math.max(written.next, index + 1);
|
|
1734
|
+
continue;
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1737
|
+
if ((character === "w" || character === "W") && sedCommandPosition(script, index)) {
|
|
1738
|
+
const next = script[index + 1];
|
|
1739
|
+
if (next === undefined || " \t;\n}".includes(next)) {
|
|
1740
|
+
const taken = sedWriteName(script, index + 1);
|
|
1741
|
+
if (foundWrite) return null;
|
|
1742
|
+
foundWrite = true;
|
|
1743
|
+
foundPath = taken.path;
|
|
1744
|
+
index = Math.max(taken.next, index + 1);
|
|
1745
|
+
continue;
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
if (character === "s" && index + 1 < script.length) {
|
|
1749
|
+
const delimiter = script[index + 1] ?? "";
|
|
1750
|
+
if (delimiter && !/[\s\\]/.test(delimiter)) {
|
|
1751
|
+
index += 2;
|
|
1752
|
+
let fields = 1;
|
|
1753
|
+
while (index < script.length && fields < 3) {
|
|
1754
|
+
if (script[index] === "\\") {
|
|
1755
|
+
index += 2;
|
|
1756
|
+
continue;
|
|
1757
|
+
}
|
|
1758
|
+
if (script[index] === delimiter) fields++;
|
|
1759
|
+
index++;
|
|
1760
|
+
}
|
|
1761
|
+
while (index < script.length && script[index] !== ";" && script[index] !== "\n" && script[index] !== "}") {
|
|
1762
|
+
if (
|
|
1763
|
+
(script[index] === "w" || script[index] === "W") &&
|
|
1764
|
+
(script[index + 1] === " " || script[index + 1] === "\t")
|
|
1765
|
+
) {
|
|
1766
|
+
const taken = sedWriteName(script, index + 1);
|
|
1767
|
+
if (foundWrite) return null;
|
|
1768
|
+
foundWrite = true;
|
|
1769
|
+
foundPath = taken.path;
|
|
1770
|
+
index = Math.max(taken.next, index + 1);
|
|
1771
|
+
break;
|
|
1772
|
+
}
|
|
1773
|
+
index++;
|
|
1774
|
+
}
|
|
1775
|
+
continue;
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
index++;
|
|
1779
|
+
}
|
|
1780
|
+
return foundWrite ? foundPath : undefined;
|
|
1781
|
+
}
|
|
1782
|
+
|
|
1783
|
+
/**
|
|
1784
|
+
* `-c`/`-e` bodies are one shell word, so a `;` inside the quotes is not a
|
|
1785
|
+
* statement break. The line-oriented interpreter regex stops at that `;` and
|
|
1786
|
+
* misses `import shutil; shutil.copy(...)`.
|
|
1787
|
+
*/
|
|
1788
|
+
function interpreterStatementEnd(command: string, start: number): number {
|
|
1789
|
+
let index = start;
|
|
1790
|
+
let inSingle = false;
|
|
1791
|
+
let inDouble = false;
|
|
1792
|
+
while (index < command.length) {
|
|
1793
|
+
const character = command[index] ?? "";
|
|
1794
|
+
if (inSingle) {
|
|
1795
|
+
if (character === "'") inSingle = false;
|
|
1796
|
+
index++;
|
|
1797
|
+
continue;
|
|
1798
|
+
}
|
|
1799
|
+
if (inDouble) {
|
|
1800
|
+
if (character === "\\") {
|
|
1801
|
+
index += 2;
|
|
1802
|
+
continue;
|
|
1803
|
+
}
|
|
1804
|
+
if (character === '"') inDouble = false;
|
|
1805
|
+
index++;
|
|
1806
|
+
continue;
|
|
1807
|
+
}
|
|
1808
|
+
if (character === "'") {
|
|
1809
|
+
inSingle = true;
|
|
1810
|
+
index++;
|
|
1811
|
+
continue;
|
|
1812
|
+
}
|
|
1813
|
+
if (character === '"') {
|
|
1814
|
+
inDouble = true;
|
|
1815
|
+
index++;
|
|
1816
|
+
continue;
|
|
1817
|
+
}
|
|
1818
|
+
if (character === "\\") {
|
|
1819
|
+
index += 2;
|
|
1820
|
+
continue;
|
|
1821
|
+
}
|
|
1822
|
+
if (character === ";" || character === "&" || character === "|" || character === "\n") break;
|
|
1823
|
+
index++;
|
|
1824
|
+
}
|
|
1825
|
+
return index;
|
|
1826
|
+
}
|
|
1827
|
+
|
|
1828
|
+
function pythonSystemCallArguments(script: string): { starts: number[]; unclassifiable: boolean } {
|
|
1829
|
+
const starts: number[] = [];
|
|
1830
|
+
let quote: "'" | '"' | null = null;
|
|
1831
|
+
let tripleQuote = false;
|
|
1832
|
+
let inComment = false;
|
|
1833
|
+
let unclassifiable = false;
|
|
1834
|
+
for (let index = 0; index < script.length; index++) {
|
|
1835
|
+
const character = script[index] ?? "";
|
|
1836
|
+
if (inComment) {
|
|
1837
|
+
if (character === "\n") inComment = false;
|
|
1838
|
+
continue;
|
|
1839
|
+
}
|
|
1840
|
+
if (quote) {
|
|
1841
|
+
if (character === "\\") {
|
|
1842
|
+
index++;
|
|
1843
|
+
continue;
|
|
1844
|
+
}
|
|
1845
|
+
if (tripleQuote && script.startsWith(quote.repeat(3), index)) {
|
|
1846
|
+
quote = null;
|
|
1847
|
+
tripleQuote = false;
|
|
1848
|
+
index += 2;
|
|
1849
|
+
continue;
|
|
1850
|
+
}
|
|
1851
|
+
if (!tripleQuote && character === quote) quote = null;
|
|
1852
|
+
continue;
|
|
1853
|
+
}
|
|
1854
|
+
if (character === "#") {
|
|
1855
|
+
inComment = true;
|
|
1856
|
+
continue;
|
|
1857
|
+
}
|
|
1858
|
+
if (character === "'" || character === '"') {
|
|
1859
|
+
const isFString = /(?:^|[^\w])(?:[rR]?[fF]|[fF][rR])$/.test(script.slice(0, index));
|
|
1860
|
+
tripleQuote = script.startsWith(character.repeat(3), index);
|
|
1861
|
+
quote = character;
|
|
1862
|
+
if (tripleQuote) {
|
|
1863
|
+
const close = script.indexOf(character.repeat(3), index + 3);
|
|
1864
|
+
const body = close < 0 ? script.slice(index + 3) : script.slice(index + 3, close);
|
|
1865
|
+
if (isFString && /\bos\s*\.\s*system\s*\(/.test(body)) unclassifiable = true;
|
|
1866
|
+
index += 2;
|
|
1867
|
+
} else if (isFString) {
|
|
1868
|
+
let close = index + 1;
|
|
1869
|
+
while (close < script.length) {
|
|
1870
|
+
if (script[close] === "\\") {
|
|
1871
|
+
close += 2;
|
|
1872
|
+
continue;
|
|
1873
|
+
}
|
|
1874
|
+
if (script[close] === character) break;
|
|
1875
|
+
close++;
|
|
1876
|
+
}
|
|
1877
|
+
if (/\bos\s*\.\s*system\s*\(/.test(script.slice(index + 1, close))) unclassifiable = true;
|
|
1878
|
+
}
|
|
1879
|
+
continue;
|
|
1880
|
+
}
|
|
1881
|
+
const call = script.slice(index).match(/^\bos\s*\.\s*system\s*\(/);
|
|
1882
|
+
if (call) {
|
|
1883
|
+
starts.push(index + call[0].length);
|
|
1884
|
+
index += call[0].length - 1;
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
// `os.system` can reach the shell under another name: a captured callable
|
|
1888
|
+
// (`run = os.system`), a module alias (`import os as o`), a direct import alias
|
|
1889
|
+
// (`from os import system as run`), or any other `<obj>.system(...)`. Neither form
|
|
1890
|
+
// names its command here, so the shell payload is unclassifiable rather than invisible.
|
|
1891
|
+
const systemCalls = (script.match(/\.\s*system\s*\(/g) ?? []).length;
|
|
1892
|
+
const osSystemCalls = (script.match(/\bos\s*\.\s*system\s*\(/g) ?? []).length;
|
|
1893
|
+
if (systemCalls > osSystemCalls) unclassifiable = true;
|
|
1894
|
+
if (/\b[A-Za-z_]\w*\s*=\s*(?:os\s*\.\s*(?:system|popen)|subprocess\s*\.\s*\w+)\b/.test(script))
|
|
1895
|
+
unclassifiable = true;
|
|
1896
|
+
// Detect `from os import system as <name>` and then calls to `<name>(...)`
|
|
1897
|
+
const fromOsImport = /\bfrom\s+os\s+import\s+system\s+as\s+([A-Za-z_]\w*)\b/.exec(script);
|
|
1898
|
+
if (fromOsImport) {
|
|
1899
|
+
const importedName = fromOsImport[1];
|
|
1900
|
+
const importedCalls = new RegExp(`\\b${importedName}\\s*\\(`, "g");
|
|
1901
|
+
if (importedCalls.test(script)) {
|
|
1902
|
+
unclassifiable = true;
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
return { starts, unclassifiable };
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
function pythonSystemCommand(script: string, start: number): string | undefined {
|
|
1909
|
+
let index = start;
|
|
1910
|
+
while (/\s/.test(script[index] ?? "")) index++;
|
|
1911
|
+
const quote = script[index];
|
|
1912
|
+
if (quote !== "'" && quote !== '"') return undefined;
|
|
1913
|
+
const tripleQuote = script.startsWith(quote.repeat(3), index);
|
|
1914
|
+
index += tripleQuote ? 3 : 1;
|
|
1915
|
+
let value = "";
|
|
1916
|
+
let hasEscape = false;
|
|
1917
|
+
while (index < script.length) {
|
|
1918
|
+
if (script[index] === "\\") {
|
|
1919
|
+
hasEscape = true;
|
|
1920
|
+
index += 2;
|
|
1921
|
+
continue;
|
|
1922
|
+
}
|
|
1923
|
+
if (tripleQuote && script.startsWith(quote.repeat(3), index)) {
|
|
1924
|
+
index += 3;
|
|
1925
|
+
while (/\s/.test(script[index] ?? "")) index++;
|
|
1926
|
+
return !hasEscape && script[index] === ")" ? value : undefined;
|
|
1927
|
+
}
|
|
1928
|
+
if (!tripleQuote && script[index] === quote) {
|
|
1929
|
+
index++;
|
|
1930
|
+
while (/\s/.test(script[index] ?? "")) index++;
|
|
1931
|
+
return !hasEscape && script[index] === ")" ? value : undefined;
|
|
1932
|
+
}
|
|
1933
|
+
value += script[index];
|
|
1934
|
+
index++;
|
|
1935
|
+
}
|
|
1936
|
+
return undefined;
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
function collectPythonSystemWrites(script: string, targets: ExtractedTargets, depth: number): void {
|
|
1940
|
+
const calls = pythonSystemCallArguments(script);
|
|
1941
|
+
if (calls.unclassifiable) {
|
|
1942
|
+
targets.explicitMutation = true;
|
|
1943
|
+
targets.unknown = true;
|
|
1944
|
+
}
|
|
1945
|
+
for (const start of calls.starts) {
|
|
1946
|
+
const payload = pythonSystemCommand(script, start);
|
|
1947
|
+
if (payload === undefined || depth >= 2) {
|
|
1948
|
+
targets.explicitMutation = true;
|
|
1949
|
+
targets.unknown = true;
|
|
1950
|
+
continue;
|
|
1951
|
+
}
|
|
1952
|
+
const nested = extractBashTargets({ command: payload }, depth + 1);
|
|
1953
|
+
for (const nestedPath of nested.paths) addPath(targets, nestedPath);
|
|
1954
|
+
if (nested.unknown) {
|
|
1955
|
+
targets.explicitMutation = true;
|
|
1956
|
+
targets.unknown = true;
|
|
1957
|
+
}
|
|
1958
|
+
if (nested.explicitMutation) targets.explicitMutation = true;
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
|
|
1962
|
+
function cleanInterpreterCodeWord(word: string): string | undefined {
|
|
1963
|
+
if (!word.startsWith("$'")) {
|
|
1964
|
+
const fullyQuoted = (/^'[^']*'$/.test(word) || /^"(?:\\.|[^"\\])*"$/.test(word)) && word.length >= 2;
|
|
1965
|
+
if (word.includes("$'") && !fullyQuoted) return undefined;
|
|
1966
|
+
return cleanShellWord(word);
|
|
1967
|
+
}
|
|
1968
|
+
if (word.length < 3 || !word.endsWith("'")) return undefined;
|
|
1969
|
+
|
|
1970
|
+
let decoded = "";
|
|
1971
|
+
for (let index = 2; index < word.length - 1; index++) {
|
|
1972
|
+
const character = word[index] ?? "";
|
|
1973
|
+
if (character !== "\\") {
|
|
1974
|
+
if (character === "'") return undefined;
|
|
1975
|
+
decoded += character;
|
|
1976
|
+
continue;
|
|
1977
|
+
}
|
|
1978
|
+
const escapeCode = word[++index];
|
|
1979
|
+
if (escapeCode === undefined) return undefined;
|
|
1980
|
+
switch (escapeCode) {
|
|
1981
|
+
case "a":
|
|
1982
|
+
decoded += "\x07";
|
|
1983
|
+
break;
|
|
1984
|
+
case "b":
|
|
1985
|
+
decoded += "\b";
|
|
1986
|
+
break;
|
|
1987
|
+
case "e":
|
|
1988
|
+
case "E":
|
|
1989
|
+
decoded += "\x1b";
|
|
1990
|
+
break;
|
|
1991
|
+
case "f":
|
|
1992
|
+
decoded += "\f";
|
|
1993
|
+
break;
|
|
1994
|
+
case "n":
|
|
1995
|
+
decoded += "\n";
|
|
1996
|
+
break;
|
|
1997
|
+
case "r":
|
|
1998
|
+
decoded += "\r";
|
|
1999
|
+
break;
|
|
2000
|
+
case "t":
|
|
2001
|
+
decoded += "\t";
|
|
2002
|
+
break;
|
|
2003
|
+
case "v":
|
|
2004
|
+
decoded += "\v";
|
|
2005
|
+
break;
|
|
2006
|
+
case "\\":
|
|
2007
|
+
case "'":
|
|
2008
|
+
case '"':
|
|
2009
|
+
case "?":
|
|
2010
|
+
decoded += escapeCode;
|
|
2011
|
+
break;
|
|
2012
|
+
case "c": {
|
|
2013
|
+
const control = word[++index];
|
|
2014
|
+
if (control === undefined || control.charCodeAt(0) > 0x7f) return undefined;
|
|
2015
|
+
const code = control === "?" ? 0x7f : control.toUpperCase().charCodeAt(0) & 0x1f;
|
|
2016
|
+
if (code === 0) return undefined;
|
|
2017
|
+
decoded += String.fromCharCode(code);
|
|
2018
|
+
break;
|
|
2019
|
+
}
|
|
2020
|
+
case "x": {
|
|
2021
|
+
let digits = "";
|
|
2022
|
+
while (digits.length < 2 && /[\da-f]/i.test(word[index + 1] ?? "")) {
|
|
2023
|
+
digits += word[++index];
|
|
2024
|
+
}
|
|
2025
|
+
if (!digits) return undefined;
|
|
2026
|
+
const code = Number.parseInt(digits, 16);
|
|
2027
|
+
if (code === 0) return undefined;
|
|
2028
|
+
decoded += String.fromCharCode(code);
|
|
2029
|
+
break;
|
|
2030
|
+
}
|
|
2031
|
+
case "u":
|
|
2032
|
+
case "U": {
|
|
2033
|
+
const width = escapeCode === "u" ? 4 : 8;
|
|
2034
|
+
const digits = word.slice(index + 1, index + 1 + width);
|
|
2035
|
+
if (digits.length !== width || !new RegExp(`^[\\da-f]{${width}}$`, "i").test(digits)) return undefined;
|
|
2036
|
+
const code = Number.parseInt(digits, 16);
|
|
2037
|
+
if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return undefined;
|
|
2038
|
+
decoded += String.fromCodePoint(code);
|
|
2039
|
+
index += width;
|
|
2040
|
+
break;
|
|
2041
|
+
}
|
|
2042
|
+
default: {
|
|
2043
|
+
if (!/[0-7]/.test(escapeCode)) return undefined;
|
|
2044
|
+
let digits = escapeCode;
|
|
2045
|
+
while (digits.length < 3 && /[0-7]/.test(word[index + 1] ?? "")) {
|
|
2046
|
+
digits += word[++index];
|
|
2047
|
+
}
|
|
2048
|
+
const code = Number.parseInt(digits, 8);
|
|
2049
|
+
if (code === 0 || code > 0xff) return undefined;
|
|
2050
|
+
decoded += String.fromCharCode(code);
|
|
2051
|
+
break;
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
return decoded;
|
|
2056
|
+
}
|
|
2057
|
+
|
|
2058
|
+
function collectInterpreterOneLinerWrites(command: string, targets: ExtractedTargets, depth: number): void {
|
|
2059
|
+
const api = new RegExp(BASH_INTERPRETER_WRITE_API, "i");
|
|
2060
|
+
const names = new RegExp(
|
|
2061
|
+
`(?:^|[;&|\\n])\\s*(?:(?:if|then|else|elif|do|in|while|until)\\s+)*(?:!\\s+)?(?:\\w+=[^\\s]+\\s+)*(?:sudo\\s+)?${BASH_COMMAND_WRAPPER_SOURCE}(?:[^\\s;&|()]*\\/)?(?:busybox\\s+)?(python(?:\\d+(?:\\.\\d+)*)?|pypy(?:\\d+(?:\\.\\d+)*)?|node(?:js)?|bun|deno|ruby|jruby|perl|php(?:\\d+(?:\\.\\d+)*)?|lua(?:\\d+(?:\\.\\d+)*)?|bash|ash|sh|zsh|dash|ksh|fish)\\b`,
|
|
2062
|
+
"gi",
|
|
2063
|
+
);
|
|
2064
|
+
for (const match of command.matchAll(names)) {
|
|
2065
|
+
const start = (match.index ?? 0) + match[0].length;
|
|
2066
|
+
const tail = command.slice(start, interpreterStatementEnd(command, start));
|
|
2067
|
+
const words = shellWords(tail);
|
|
2068
|
+
const parts = words.map(cleanShellWord);
|
|
2069
|
+
const binary = (match[1] ?? "").toLowerCase();
|
|
2070
|
+
const options = interpreterCodeOptions(binary);
|
|
2071
|
+
for (let index = 0; index < parts.length; index++) {
|
|
2072
|
+
const part = parts[index] ?? "";
|
|
2073
|
+
let rawScript: string | undefined;
|
|
2074
|
+
const option = options.find(
|
|
2075
|
+
candidate =>
|
|
2076
|
+
part === candidate || (candidate.length === 2 && part.startsWith(candidate) && part.length > 2),
|
|
2077
|
+
);
|
|
2078
|
+
if (option && part === option) {
|
|
2079
|
+
rawScript = words[++index];
|
|
2080
|
+
} else if (option) {
|
|
2081
|
+
const rawWord = words[index] ?? "";
|
|
2082
|
+
rawScript = rawWord.startsWith("-") ? rawWord.slice(option.length) : part.slice(option.length);
|
|
2083
|
+
} else {
|
|
2084
|
+
const longOption = options.find(
|
|
2085
|
+
candidate => candidate.startsWith("--") && part.startsWith(`${candidate}=`),
|
|
2086
|
+
);
|
|
2087
|
+
if (!longOption) continue;
|
|
2088
|
+
rawScript = words[index]?.slice(longOption.length + 1);
|
|
2089
|
+
}
|
|
2090
|
+
if (rawScript === undefined) continue;
|
|
2091
|
+
// Node preload options (-r/--require) load external files that cannot be scanned,
|
|
2092
|
+
// so fail closed when encountered.
|
|
2093
|
+
if ((option === "-r" || option === "--require") && /^(?:node|bun)$/.test(binary)) {
|
|
2094
|
+
targets.explicitMutation = true;
|
|
2095
|
+
targets.unknown = true;
|
|
2096
|
+
return;
|
|
2097
|
+
}
|
|
2098
|
+
const script = cleanInterpreterCodeWord(rawScript);
|
|
2099
|
+
if (
|
|
2100
|
+
script === undefined ||
|
|
2101
|
+
(!rawScript.startsWith("$'") && shellWordHasExpansion(rawScript)) ||
|
|
2102
|
+
containsOpaqueInterpreterSource(script, binary)
|
|
2103
|
+
) {
|
|
2104
|
+
targets.explicitMutation = true;
|
|
2105
|
+
targets.unknown = true;
|
|
2106
|
+
return;
|
|
2107
|
+
}
|
|
2108
|
+
if (/^(?:bash|ash|sh|zsh|dash|ksh|fish)$/.test(binary)) {
|
|
2109
|
+
if (depth >= 2) {
|
|
2110
|
+
targets.explicitMutation = true;
|
|
2111
|
+
targets.unknown = true;
|
|
2112
|
+
return;
|
|
2113
|
+
}
|
|
2114
|
+
const nested = extractBashTargets({ command: script }, depth + 1);
|
|
2115
|
+
for (const nestedPath of nested.paths) addPath(targets, nestedPath);
|
|
2116
|
+
if (nested.unknown) targets.unknown = true;
|
|
2117
|
+
if (nested.explicitMutation) targets.explicitMutation = true;
|
|
2118
|
+
continue;
|
|
2119
|
+
}
|
|
2120
|
+
const language = /^(?:python|pypy)/.test(binary)
|
|
2121
|
+
? "py"
|
|
2122
|
+
: /^(?:node|bun|deno)$/.test(binary)
|
|
2123
|
+
? "js"
|
|
2124
|
+
: /^(?:ruby|jruby)$/.test(binary)
|
|
2125
|
+
? "ruby"
|
|
2126
|
+
: "perl";
|
|
2127
|
+
if (/^(?:python|pypy)/.test(binary)) {
|
|
2128
|
+
scanInterpreterWrites(script, "py", targets);
|
|
2129
|
+
if (
|
|
2130
|
+
interpreterCodeContainsWriteApi(script, "py", new RegExp(BASH_INTERPRETER_WRITE_API_EXCLUDING_OPEN, "i"))
|
|
2131
|
+
) {
|
|
2132
|
+
targets.explicitMutation = true;
|
|
2133
|
+
targets.unknown = true;
|
|
2134
|
+
}
|
|
2135
|
+
collectPythonSystemWrites(script, targets, depth);
|
|
2136
|
+
continue;
|
|
2137
|
+
}
|
|
2138
|
+
if (interpreterCodeContainsWriteApi(script, language, api)) {
|
|
2139
|
+
targets.explicitMutation = true;
|
|
2140
|
+
targets.unknown = true;
|
|
2141
|
+
return;
|
|
2142
|
+
}
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
|
|
2147
|
+
function interpreterCodeOptions(binary: string): string[] {
|
|
2148
|
+
if (/^(?:python|pypy)/.test(binary)) return ["-c"];
|
|
2149
|
+
if (/^(?:node|bun)$/.test(binary)) return ["-r", "--require", "-e", "--eval", "-p", "--print"];
|
|
2150
|
+
if (binary === "deno") return ["eval", "-e", "--eval"];
|
|
2151
|
+
if (/^(?:ruby|jruby|perl|lua)/.test(binary)) return ["-e"];
|
|
2152
|
+
if (/^php/.test(binary)) return ["-r"];
|
|
2153
|
+
if (/^(?:bash|ash|sh|zsh|dash|ksh|fish)$/.test(binary)) return ["-c"];
|
|
2154
|
+
return [];
|
|
2155
|
+
}
|
|
2156
|
+
|
|
2157
|
+
function containsOpaqueInterpreterSource(source: string, binary: string): boolean {
|
|
2158
|
+
return (
|
|
2159
|
+
(!/^(?:python|pypy)/.test(binary) && INTERPRETER_DYNAMIC_EXECUTION_RE.test(source)) ||
|
|
2160
|
+
INTERPRETER_FILESYSTEM_REQUIRE_RE.test(source) ||
|
|
2161
|
+
INTERPRETER_NONLITERAL_REQUIRE_RE.test(source) ||
|
|
2162
|
+
(/^php/.test(binary) && /\bassert\b/i.test(source)) ||
|
|
2163
|
+
(/^(?:bash|ash|sh|zsh|dash|ksh|fish)$/.test(binary) && SHELL_DOT_SOURCE_RE.test(source))
|
|
2164
|
+
);
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
function interpreterCodeContainsWriteApi(
|
|
2168
|
+
script: string,
|
|
2169
|
+
language: "py" | "js" | "ruby" | "perl",
|
|
2170
|
+
api: RegExp,
|
|
2171
|
+
): boolean {
|
|
2172
|
+
const apiAtStart = new RegExp(`^(?:${api.source})`, "i");
|
|
2173
|
+
// Reflective mutation of a stream object defeats the stdout/stderr write
|
|
2174
|
+
// exemption: the method that runs may write to a file. Fail closed instead.
|
|
2175
|
+
const streamMutated =
|
|
2176
|
+
INTERPRETER_OUTPUT_METHOD_ASSIGNMENT_RE.test(script) || INTERPRETER_OUTPUT_STREAM_MUTATION_RE.test(script);
|
|
2177
|
+
let index = 0;
|
|
2178
|
+
while (index < script.length) {
|
|
2179
|
+
if (language === "py" || language === "js") {
|
|
2180
|
+
const next =
|
|
2181
|
+
language === "js" && script[index] === "`"
|
|
2182
|
+
? skipJavaScriptTemplate(script, index)
|
|
2183
|
+
: skipNoise(script, index, language);
|
|
2184
|
+
if (next !== index) {
|
|
2185
|
+
const skipped = script.slice(index, next);
|
|
2186
|
+
const isInterpolated =
|
|
2187
|
+
(language === "js" && script[index] === "`" && skipped.includes("${")) ||
|
|
2188
|
+
(language === "py" &&
|
|
2189
|
+
/(?:^|[^\w])(?:[rR]?[fF]|[fF][rR])$/.test(script.slice(Math.max(0, index - 3), index)) &&
|
|
2190
|
+
skipped.includes("{"));
|
|
2191
|
+
if (
|
|
2192
|
+
isInterpolated &&
|
|
2193
|
+
(api.test(skipped) ||
|
|
2194
|
+
(language === "py" && PYTHON_DYNAMIC_EXECUTION_TOKEN_RE.test(skipped)) ||
|
|
2195
|
+
(language === "js" && JAVASCRIPT_DYNAMIC_EXECUTION_TOKEN_RE.test(skipped)))
|
|
2196
|
+
)
|
|
2197
|
+
return true;
|
|
2198
|
+
index = next;
|
|
2199
|
+
continue;
|
|
2200
|
+
}
|
|
2201
|
+
} else {
|
|
2202
|
+
const next = skipOtherInterpreterNoise(script, index);
|
|
2203
|
+
if (next !== index) {
|
|
2204
|
+
const skipped = script.slice(index, next);
|
|
2205
|
+
if (language === "ruby" && script[index] !== "'" && skipped.includes("#{") && api.test(skipped))
|
|
2206
|
+
return true;
|
|
2207
|
+
index = next;
|
|
2208
|
+
continue;
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
if (INTERPRETER_OUTPUT_METHOD_ASSIGNMENT_RE.test(script.slice(index))) return true;
|
|
2212
|
+
if (language === "py" && PYTHON_DYNAMIC_EXECUTION_IDENTIFIER_RE.test(script.slice(index))) return true;
|
|
2213
|
+
if (language === "js" && JAVASCRIPT_DYNAMIC_EXECUTION_IDENTIFIER_RE.test(script.slice(index))) return true;
|
|
2214
|
+
if (language === "perl" && /^open\b/.test(script.slice(index))) {
|
|
2215
|
+
// Both `open(...)` and the list form `open H, MODE, EXPR` matter; only an
|
|
2216
|
+
// explicit read mode is safe, and an unparsed open fails closed.
|
|
2217
|
+
if (!isReadOnlyPerlOpen(script, index)) return true;
|
|
2218
|
+
index += "open".length;
|
|
2219
|
+
continue;
|
|
2220
|
+
}
|
|
2221
|
+
if (apiAtStart.test(script.slice(index))) {
|
|
2222
|
+
const outputWrite =
|
|
2223
|
+
!streamMutated &&
|
|
2224
|
+
/^\.\s*write\s*\(/.test(script.slice(index)) &&
|
|
2225
|
+
/\b(?:process|Bun)\s*\.\s*(?:stdout|stderr)\s*$/.test(script.slice(0, index));
|
|
2226
|
+
// Aliased mutation: if process.stdout is passed through a function or parameter,
|
|
2227
|
+
// it may be rebound. Fail closed when there are function definitions or calls
|
|
2228
|
+
// that could capture and mutate the stream object.
|
|
2229
|
+
const hasAliasVectors =
|
|
2230
|
+
outputWrite &&
|
|
2231
|
+
/[([]\s*[A-Za-z_]\w*\s*=>|\([^)]*(?:process|Bun)\s*\.\s*(?:stdout|stderr)[^)]*\)/.test(script);
|
|
2232
|
+
if (!outputWrite || hasAliasVectors) return true;
|
|
2233
|
+
}
|
|
2234
|
+
index += 1;
|
|
2235
|
+
}
|
|
2236
|
+
return false;
|
|
2237
|
+
}
|
|
2238
|
+
|
|
2239
|
+
/**
|
|
2240
|
+
* Perl `open` accepts two spellings — `open(H, MODE, EXPR)` and the list form
|
|
2241
|
+
* `open H, MODE, EXPR` — and only an explicit read mode is safe. Any other shape
|
|
2242
|
+
* (write/pipe modes, a variable mode, or an unparsed statement) fails closed.
|
|
2243
|
+
*/
|
|
2244
|
+
function isReadOnlyPerlOpen(script: string, index: number): boolean {
|
|
2245
|
+
const rest = script.slice(index);
|
|
2246
|
+
if (!/^open\b/.test(rest)) return false;
|
|
2247
|
+
const parenthesized = /^open\s*\(/.exec(rest);
|
|
2248
|
+
const body = parenthesized ? rest.slice(parenthesized[0].length) : rest.slice("open".length);
|
|
2249
|
+
const statementEnd = body.search(/[;\n}]/);
|
|
2250
|
+
const statement = statementEnd < 0 ? body : body.slice(0, statementEnd);
|
|
2251
|
+
|
|
2252
|
+
// Parse arguments properly: count commas to find the MODE position (second argument)
|
|
2253
|
+
// and extract only that argument.
|
|
2254
|
+
let depth = 0;
|
|
2255
|
+
let inString = false;
|
|
2256
|
+
let stringChar = "";
|
|
2257
|
+
let commaCount = 0;
|
|
2258
|
+
let modeStart = -1;
|
|
2259
|
+
let modeEnd = -1;
|
|
2260
|
+
|
|
2261
|
+
for (let i = 0; i < statement.length; i++) {
|
|
2262
|
+
const ch = statement[i];
|
|
2263
|
+
|
|
2264
|
+
if (inString) {
|
|
2265
|
+
if (ch === "\\" && i + 1 < statement.length) {
|
|
2266
|
+
i++; // skip escape sequence
|
|
2267
|
+
continue;
|
|
2268
|
+
}
|
|
2269
|
+
if (ch === stringChar) {
|
|
2270
|
+
inString = false;
|
|
2271
|
+
}
|
|
2272
|
+
continue;
|
|
2273
|
+
}
|
|
2274
|
+
|
|
2275
|
+
if (ch === "'" || ch === '"') {
|
|
2276
|
+
inString = true;
|
|
2277
|
+
stringChar = ch;
|
|
2278
|
+
continue;
|
|
2279
|
+
}
|
|
2280
|
+
|
|
2281
|
+
if (ch === "(") depth++;
|
|
2282
|
+
else if (ch === ")") depth--;
|
|
2283
|
+
else if (ch === "," && depth === 0) {
|
|
2284
|
+
commaCount++;
|
|
2285
|
+
if (commaCount === 1) {
|
|
2286
|
+
// This comma separates first and second arguments
|
|
2287
|
+
modeStart = i + 1;
|
|
2288
|
+
}
|
|
2289
|
+
if (commaCount === 2) {
|
|
2290
|
+
// This comma ends the mode argument
|
|
2291
|
+
modeEnd = i;
|
|
2292
|
+
break;
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
}
|
|
2296
|
+
|
|
2297
|
+
if (modeStart === -1) return false; // Can't find MODE argument
|
|
2298
|
+
if (modeEnd === -1) modeEnd = statement.length;
|
|
2299
|
+
|
|
2300
|
+
const modeArg = statement.slice(modeStart, modeEnd).trim();
|
|
2301
|
+
|
|
2302
|
+
// Extract the mode value if it's a quoted string; if it's a variable, fail closed
|
|
2303
|
+
const quotedMode = /^(['"])(.*?)\1$/.exec(modeArg);
|
|
2304
|
+
if (!quotedMode) return false; // Variable mode, fail closed
|
|
2305
|
+
|
|
2306
|
+
const mode = quotedMode[2].trim();
|
|
2307
|
+
return mode.startsWith("<") && !mode.startsWith("<+");
|
|
2308
|
+
}
|
|
2309
|
+
|
|
2310
|
+
function skipJavaScriptTemplate(script: string, index: number): number {
|
|
2311
|
+
let cursor = index + 1;
|
|
2312
|
+
while (cursor < script.length) {
|
|
2313
|
+
if (script[cursor] === "\\") {
|
|
2314
|
+
cursor += 2;
|
|
2315
|
+
continue;
|
|
2316
|
+
}
|
|
2317
|
+
if (script[cursor] === "`") return cursor + 1;
|
|
2318
|
+
cursor += 1;
|
|
2319
|
+
}
|
|
2320
|
+
return script.length;
|
|
2321
|
+
}
|
|
2322
|
+
|
|
2323
|
+
function skipOtherInterpreterNoise(script: string, index: number): number {
|
|
2324
|
+
const character = script[index] ?? "";
|
|
2325
|
+
if (character === "#") {
|
|
2326
|
+
const end = script.indexOf("\n", index);
|
|
2327
|
+
return end < 0 ? script.length : end;
|
|
2328
|
+
}
|
|
2329
|
+
if (character !== "'" && character !== '"' && character !== "`") return index;
|
|
2330
|
+
let cursor = index + 1;
|
|
2331
|
+
while (cursor < script.length) {
|
|
2332
|
+
if (script[cursor] === "\\") {
|
|
2333
|
+
cursor += 2;
|
|
2334
|
+
continue;
|
|
2335
|
+
}
|
|
2336
|
+
if (script[cursor] === character) return cursor + 1;
|
|
2337
|
+
cursor += 1;
|
|
2338
|
+
}
|
|
2339
|
+
return script.length;
|
|
2340
|
+
}
|
|
2341
|
+
|
|
2342
|
+
function collectSedScriptWrites(command: string, targets: ExtractedTargets): void {
|
|
2343
|
+
for (const match of command.matchAll(BASH_SED_COMMAND_RE)) {
|
|
2344
|
+
const matchIndex = match.index ?? 0;
|
|
2345
|
+
if (!shellSyntaxPosition(command, matchIndex)) continue;
|
|
2346
|
+
const words = shellWords(match[1] ?? "").map(cleanShellWord);
|
|
2347
|
+
const parsed = sedScriptOperands(words);
|
|
2348
|
+
if (parsed.unknown) {
|
|
2349
|
+
targets.explicitMutation = true;
|
|
2350
|
+
targets.unknown = true;
|
|
2351
|
+
}
|
|
2352
|
+
for (const script of parsed.scripts) {
|
|
2353
|
+
const writePath = sedScriptWritePath(script);
|
|
2354
|
+
if (writePath === undefined) continue;
|
|
2355
|
+
targets.explicitMutation = true;
|
|
2356
|
+
if (writePath && !isDeviceSinkPath(writePath)) addPath(targets, writePath);
|
|
2357
|
+
else if (!writePath) targets.unknown = true;
|
|
2358
|
+
}
|
|
2359
|
+
}
|
|
2360
|
+
}
|
|
2361
|
+
|
|
2362
|
+
function sedScriptOperands(words: string[]): { scripts: string[]; unknown: boolean } {
|
|
2363
|
+
const scripts: string[] = [];
|
|
2364
|
+
let hasBareScript = false;
|
|
2365
|
+
let unknown = false;
|
|
2366
|
+
for (let index = 0; index < words.length; index++) {
|
|
2367
|
+
const word = words[index] ?? "";
|
|
2368
|
+
if (!word) continue;
|
|
2369
|
+
if (word === "--") {
|
|
2370
|
+
if (!hasBareScript && scripts.length === 0 && words[index + 1]) scripts.push(words[index + 1] ?? "");
|
|
2371
|
+
break;
|
|
2372
|
+
}
|
|
2373
|
+
if (word === "-e" || word === "--expression") {
|
|
2374
|
+
const script = words[index + 1];
|
|
2375
|
+
if (script) scripts.push(script);
|
|
2376
|
+
index += 1;
|
|
2377
|
+
continue;
|
|
2378
|
+
}
|
|
2379
|
+
if (word.startsWith("--expression=")) {
|
|
2380
|
+
scripts.push(word.slice("--expression=".length));
|
|
2381
|
+
continue;
|
|
2382
|
+
}
|
|
2383
|
+
if (word.startsWith("-e") && word.length > 2) {
|
|
2384
|
+
scripts.push(word.slice(2));
|
|
2385
|
+
continue;
|
|
2386
|
+
}
|
|
2387
|
+
if (word === "-f" || word === "--file") {
|
|
2388
|
+
// The script contents are not present in the command, so their write behavior is opaque.
|
|
2389
|
+
unknown = true;
|
|
2390
|
+
index += 1;
|
|
2391
|
+
continue;
|
|
2392
|
+
}
|
|
2393
|
+
if (word.startsWith("--file=") || (word.startsWith("-f") && word.length > 2)) {
|
|
2394
|
+
unknown = true;
|
|
2395
|
+
continue;
|
|
2396
|
+
}
|
|
2397
|
+
if (word === "-l" || word === "--line-length") {
|
|
2398
|
+
index += 1;
|
|
2399
|
+
continue;
|
|
2400
|
+
}
|
|
2401
|
+
if (word.startsWith("-")) continue;
|
|
2402
|
+
if (!hasBareScript && scripts.length === 0) {
|
|
2403
|
+
scripts.push(word);
|
|
2404
|
+
hasBareScript = true;
|
|
2405
|
+
}
|
|
2406
|
+
}
|
|
2407
|
+
return { scripts, unknown };
|
|
2408
|
+
}
|
|
2409
|
+
|
|
2410
|
+
function shellSyntaxPosition(command: string, targetIndex: number, allowComment = false): boolean {
|
|
2411
|
+
let quote: "'" | '"' | null = null;
|
|
2412
|
+
let inComment = false;
|
|
2413
|
+
let previous = "";
|
|
2414
|
+
for (let index = 0; index < targetIndex; index++) {
|
|
2415
|
+
const character = command[index] ?? "";
|
|
2416
|
+
if (inComment) {
|
|
2417
|
+
if (character === "\n") {
|
|
2418
|
+
inComment = false;
|
|
2419
|
+
previous = character;
|
|
2420
|
+
}
|
|
2421
|
+
continue;
|
|
2422
|
+
}
|
|
2423
|
+
if (quote === "'") {
|
|
2424
|
+
if (character === "'") quote = null;
|
|
2425
|
+
continue;
|
|
2426
|
+
}
|
|
2427
|
+
if (quote === '"') {
|
|
2428
|
+
if (character === "\\") {
|
|
2429
|
+
index++;
|
|
2430
|
+
continue;
|
|
2431
|
+
}
|
|
2432
|
+
if (character === '"') quote = null;
|
|
2433
|
+
continue;
|
|
2434
|
+
}
|
|
2435
|
+
if (character === "\\") {
|
|
2436
|
+
index++;
|
|
2437
|
+
continue;
|
|
2438
|
+
}
|
|
2439
|
+
if (character === "'" || character === '"') {
|
|
2440
|
+
quote = character;
|
|
2441
|
+
continue;
|
|
2442
|
+
}
|
|
2443
|
+
if (character === "#" && (previous === "" || /\s/.test(previous) || ";|&()".includes(previous))) {
|
|
2444
|
+
inComment = true;
|
|
2445
|
+
continue;
|
|
2446
|
+
}
|
|
2447
|
+
previous = character;
|
|
2448
|
+
}
|
|
2449
|
+
if (command[targetIndex] === "\n" && inComment) return quote === null;
|
|
2450
|
+
return quote === null && (allowComment || !inComment);
|
|
2451
|
+
}
|
|
2452
|
+
|
|
2453
|
+
function awkRegexCanStart(tokens: AwkToken[]): boolean {
|
|
2454
|
+
const previous = tokens.at(-1);
|
|
2455
|
+
if (!previous) return true;
|
|
2456
|
+
if (previous.kind === "separator") return true;
|
|
2457
|
+
return (
|
|
2458
|
+
(previous.kind === "symbol" &&
|
|
2459
|
+
["{", "(", "[", ",", "?", ":", "=", "==", "!=", "!", "&&", "||", "~", "!~"].includes(previous.value)) ||
|
|
2460
|
+
(previous.kind === "word" && ["print", "printf", "return"].includes(previous.value))
|
|
2461
|
+
);
|
|
2462
|
+
}
|
|
2463
|
+
|
|
2464
|
+
function awkRegexEnd(program: string, start: number): number | undefined {
|
|
2465
|
+
let inCharacterClass = false;
|
|
2466
|
+
for (let index = start + 1; index < program.length; index++) {
|
|
2467
|
+
const character = program[index] ?? "";
|
|
2468
|
+
if (character === "\\") {
|
|
2469
|
+
index++;
|
|
2470
|
+
continue;
|
|
2471
|
+
}
|
|
2472
|
+
if (character === "[" && !inCharacterClass) inCharacterClass = true;
|
|
2473
|
+
else if (character === "]" && inCharacterClass) inCharacterClass = false;
|
|
2474
|
+
else if (character === "/" && !inCharacterClass) return index + 1;
|
|
2475
|
+
else if (character === "\n") return undefined;
|
|
2476
|
+
}
|
|
2477
|
+
return undefined;
|
|
2478
|
+
}
|
|
2479
|
+
|
|
2480
|
+
interface AwkToken {
|
|
2481
|
+
kind: "word" | "string" | "symbol" | "separator";
|
|
2482
|
+
value: string;
|
|
2483
|
+
unsafeEscapes?: boolean;
|
|
2484
|
+
}
|
|
2485
|
+
|
|
2486
|
+
function tokenizeAwkProgram(program: string): { tokens: AwkToken[]; balanced: boolean } {
|
|
2487
|
+
const tokens: AwkToken[] = [];
|
|
2488
|
+
let balanced = true;
|
|
2489
|
+
for (let index = 0; index < program.length; ) {
|
|
2490
|
+
const character = program[index] ?? "";
|
|
2491
|
+
if (character === "\n") {
|
|
2492
|
+
tokens.push({ kind: "separator", value: character });
|
|
2493
|
+
index++;
|
|
2494
|
+
continue;
|
|
2495
|
+
}
|
|
2496
|
+
if (/\s/.test(character)) {
|
|
2497
|
+
index++;
|
|
2498
|
+
continue;
|
|
2499
|
+
}
|
|
2500
|
+
if (character === "#") {
|
|
2501
|
+
while (index < program.length && program[index] !== "\n") index++;
|
|
2502
|
+
continue;
|
|
2503
|
+
}
|
|
2504
|
+
if (character === '"') {
|
|
2505
|
+
let value = "";
|
|
2506
|
+
let unsafeEscapes = false;
|
|
2507
|
+
let closed = false;
|
|
2508
|
+
index++;
|
|
2509
|
+
while (index < program.length) {
|
|
2510
|
+
const next = program[index] ?? "";
|
|
2511
|
+
if (next === "\\") {
|
|
2512
|
+
const escapedChar = program[index + 1] ?? "";
|
|
2513
|
+
if (escapedChar === "\\" || escapedChar === '"') {
|
|
2514
|
+
value += escapedChar;
|
|
2515
|
+
index += 2;
|
|
2516
|
+
continue;
|
|
2517
|
+
}
|
|
2518
|
+
switch (escapedChar) {
|
|
2519
|
+
case "a":
|
|
2520
|
+
value += "\u0007";
|
|
2521
|
+
index += 2;
|
|
2522
|
+
continue;
|
|
2523
|
+
case "b":
|
|
2524
|
+
value += "\b";
|
|
2525
|
+
index += 2;
|
|
2526
|
+
continue;
|
|
2527
|
+
case "f":
|
|
2528
|
+
value += "\f";
|
|
2529
|
+
index += 2;
|
|
2530
|
+
continue;
|
|
2531
|
+
case "n":
|
|
2532
|
+
value += "\n";
|
|
2533
|
+
index += 2;
|
|
2534
|
+
continue;
|
|
2535
|
+
case "r":
|
|
2536
|
+
value += "\r";
|
|
2537
|
+
index += 2;
|
|
2538
|
+
continue;
|
|
2539
|
+
case "t":
|
|
2540
|
+
value += "\t";
|
|
2541
|
+
index += 2;
|
|
2542
|
+
continue;
|
|
2543
|
+
case "v":
|
|
2544
|
+
value += "\u000b";
|
|
2545
|
+
index += 2;
|
|
2546
|
+
continue;
|
|
2547
|
+
}
|
|
2548
|
+
if (/[0-7]/.test(escapedChar)) {
|
|
2549
|
+
let end = index + 1;
|
|
2550
|
+
while (end < program.length && end < index + 4 && /[0-7]/.test(program[end] ?? "")) end++;
|
|
2551
|
+
value += String.fromCharCode(Number.parseInt(program.slice(index + 1, end), 8));
|
|
2552
|
+
index = end;
|
|
2553
|
+
continue;
|
|
2554
|
+
}
|
|
2555
|
+
if (escapedChar === "x") {
|
|
2556
|
+
let end = index + 2;
|
|
2557
|
+
while (end < program.length && /[\da-f]/i.test(program[end] ?? "")) end++;
|
|
2558
|
+
const hex = program.slice(index + 2, end);
|
|
2559
|
+
const codePoint = hex ? Number.parseInt(hex, 16) : Number.NaN;
|
|
2560
|
+
if (hex && codePoint <= 0xffff) value += String.fromCharCode(codePoint);
|
|
2561
|
+
else unsafeEscapes = true;
|
|
2562
|
+
index = end;
|
|
2563
|
+
continue;
|
|
2564
|
+
}
|
|
2565
|
+
unsafeEscapes = true;
|
|
2566
|
+
if (escapedChar) value += escapedChar;
|
|
2567
|
+
index += escapedChar ? 2 : 1;
|
|
2568
|
+
continue;
|
|
2569
|
+
}
|
|
2570
|
+
if (next === '"') {
|
|
2571
|
+
closed = true;
|
|
2572
|
+
index++;
|
|
2573
|
+
break;
|
|
2574
|
+
}
|
|
2575
|
+
value += next;
|
|
2576
|
+
index++;
|
|
2577
|
+
}
|
|
2578
|
+
if (!closed) balanced = false;
|
|
2579
|
+
tokens.push({ kind: "string", value, unsafeEscapes });
|
|
2580
|
+
continue;
|
|
2581
|
+
}
|
|
2582
|
+
if (character === "/" && awkRegexCanStart(tokens)) {
|
|
2583
|
+
const end = awkRegexEnd(program, index);
|
|
2584
|
+
if (end === undefined) balanced = false;
|
|
2585
|
+
else {
|
|
2586
|
+
tokens.push({ kind: "symbol", value: "regex" });
|
|
2587
|
+
index = end;
|
|
2588
|
+
continue;
|
|
2589
|
+
}
|
|
2590
|
+
}
|
|
2591
|
+
if (/[A-Za-z_]/.test(character)) {
|
|
2592
|
+
const start = index++;
|
|
2593
|
+
while (/[A-Za-z0-9_]/.test(program[index] ?? "")) index++;
|
|
2594
|
+
tokens.push({ kind: "word", value: program.slice(start, index) });
|
|
2595
|
+
continue;
|
|
2596
|
+
}
|
|
2597
|
+
if (character === ";") {
|
|
2598
|
+
tokens.push({ kind: "separator", value: character });
|
|
2599
|
+
index++;
|
|
2600
|
+
continue;
|
|
2601
|
+
}
|
|
2602
|
+
const pair = program.slice(index, index + 2);
|
|
2603
|
+
const operator = [">>", ">=", "==", "!=", "<=", "&&", "||", "!~", "++", "--"].includes(pair) ? pair : character;
|
|
2604
|
+
tokens.push({ kind: "symbol", value: operator });
|
|
2605
|
+
index += operator.length;
|
|
2606
|
+
}
|
|
2607
|
+
return { tokens, balanced };
|
|
2608
|
+
}
|
|
2609
|
+
|
|
2610
|
+
interface AwkProgramSource {
|
|
2611
|
+
source: string;
|
|
2612
|
+
expanded: boolean;
|
|
2613
|
+
}
|
|
2614
|
+
|
|
2615
|
+
function shellWordHasExpansion(word: string): boolean {
|
|
2616
|
+
let quote: "'" | '"' | null = null;
|
|
2617
|
+
for (let index = 0; index < word.length; index++) {
|
|
2618
|
+
const character = word[index] ?? "";
|
|
2619
|
+
if (quote === "'") {
|
|
2620
|
+
if (character === "'") quote = null;
|
|
2621
|
+
continue;
|
|
2622
|
+
}
|
|
2623
|
+
if (quote === '"') {
|
|
2624
|
+
if (character === "\\") {
|
|
2625
|
+
index++;
|
|
2626
|
+
continue;
|
|
2627
|
+
}
|
|
2628
|
+
if (character === '"') quote = null;
|
|
2629
|
+
else if (character === "$" || character === "`") return true;
|
|
2630
|
+
continue;
|
|
2631
|
+
}
|
|
2632
|
+
if (character === "\\") {
|
|
2633
|
+
index++;
|
|
2634
|
+
continue;
|
|
2635
|
+
}
|
|
2636
|
+
if (character === "'" || character === '"') quote = character;
|
|
2637
|
+
else if (character === "$" || character === "`") return true;
|
|
2638
|
+
}
|
|
2639
|
+
return quote !== null;
|
|
2640
|
+
}
|
|
2641
|
+
|
|
2642
|
+
function awkPrograms(words: string[]): { programs: AwkProgramSource[]; unknown: boolean } {
|
|
2643
|
+
const programs: AwkProgramSource[] = [];
|
|
2644
|
+
const noOperandOptions = new Set([
|
|
2645
|
+
"-b",
|
|
2646
|
+
"-c",
|
|
2647
|
+
"-C",
|
|
2648
|
+
"-g",
|
|
2649
|
+
"-h",
|
|
2650
|
+
"-M",
|
|
2651
|
+
"-n",
|
|
2652
|
+
"-N",
|
|
2653
|
+
"-O",
|
|
2654
|
+
"-P",
|
|
2655
|
+
"-r",
|
|
2656
|
+
"-s",
|
|
2657
|
+
"-S",
|
|
2658
|
+
"-t",
|
|
2659
|
+
"-V",
|
|
2660
|
+
"--characters-as-bytes",
|
|
2661
|
+
"--csv",
|
|
2662
|
+
"--help",
|
|
2663
|
+
"--lint",
|
|
2664
|
+
"--lint-no-ext",
|
|
2665
|
+
"--lint-old",
|
|
2666
|
+
"--posix",
|
|
2667
|
+
"--sandbox",
|
|
2668
|
+
"--traditional",
|
|
2669
|
+
"--version",
|
|
2670
|
+
]);
|
|
2671
|
+
let unknown = false;
|
|
2672
|
+
let hasFileProgram = false;
|
|
2673
|
+
let hasSourceOption = false;
|
|
2674
|
+
const programSource = (raw: string): AwkProgramSource => ({
|
|
2675
|
+
source: cleanShellWord(raw),
|
|
2676
|
+
expanded: shellWordHasExpansion(raw),
|
|
2677
|
+
});
|
|
2678
|
+
const operand = (index: number): string | undefined => {
|
|
2679
|
+
const next = words[index + 1];
|
|
2680
|
+
if (!next) {
|
|
2681
|
+
unknown = true;
|
|
2682
|
+
return undefined;
|
|
2683
|
+
}
|
|
2684
|
+
return next;
|
|
2685
|
+
};
|
|
2686
|
+
for (let index = 0; index < words.length; index++) {
|
|
2687
|
+
const word = words[index];
|
|
2688
|
+
if (!word) continue;
|
|
2689
|
+
if (/^(?:\d+)?(?:>>?|<<<?|&>)/.test(word)) {
|
|
2690
|
+
if (/^(?:\d+)?(?:>>?|<<<?)$/.test(word)) index++;
|
|
2691
|
+
continue;
|
|
2692
|
+
}
|
|
2693
|
+
const part = cleanShellWord(word);
|
|
2694
|
+
if (part === "--") {
|
|
2695
|
+
if (hasFileProgram || hasSourceOption) break;
|
|
2696
|
+
const program = words[index + 1];
|
|
2697
|
+
if (!program) unknown = true;
|
|
2698
|
+
else programs.push(programSource(program));
|
|
2699
|
+
break;
|
|
2700
|
+
}
|
|
2701
|
+
if (part === "-e" || part === "--source") {
|
|
2702
|
+
const program = operand(index);
|
|
2703
|
+
if (program) programs.push(programSource(program));
|
|
2704
|
+
hasSourceOption = true;
|
|
2705
|
+
index++;
|
|
2706
|
+
continue;
|
|
2707
|
+
}
|
|
2708
|
+
if (part.startsWith("--source=")) {
|
|
2709
|
+
programs.push(programSource(part.slice("--source=".length)));
|
|
2710
|
+
hasSourceOption = true;
|
|
2711
|
+
continue;
|
|
2712
|
+
}
|
|
2713
|
+
if (part === "-v" || part === "--assign" || part === "-F" || part === "--field-separator") {
|
|
2714
|
+
if (!operand(index)) continue;
|
|
2715
|
+
index++;
|
|
2716
|
+
continue;
|
|
2717
|
+
}
|
|
2718
|
+
if (part === "-W") {
|
|
2719
|
+
const extension = operand(index);
|
|
2720
|
+
if (extension !== "version" && extension !== "lint" && extension !== "posix") {
|
|
2721
|
+
unknown = true;
|
|
2722
|
+
break;
|
|
2723
|
+
}
|
|
2724
|
+
index++;
|
|
2725
|
+
continue;
|
|
2726
|
+
}
|
|
2727
|
+
if (part.startsWith("-W")) {
|
|
2728
|
+
const extension = part.slice(2);
|
|
2729
|
+
if (extension !== "version" && extension !== "lint" && extension !== "posix") {
|
|
2730
|
+
unknown = true;
|
|
2731
|
+
break;
|
|
2732
|
+
}
|
|
2733
|
+
continue;
|
|
2734
|
+
}
|
|
2735
|
+
if (part.startsWith("--assign=") || part.startsWith("--field-separator=")) continue;
|
|
2736
|
+
if (part === "-f" || part === "--file" || part === "-E") {
|
|
2737
|
+
if (!operand(index)) continue;
|
|
2738
|
+
hasFileProgram = true;
|
|
2739
|
+
index++;
|
|
2740
|
+
continue;
|
|
2741
|
+
}
|
|
2742
|
+
if (part.startsWith("--file=") || (part.startsWith("-f") && part.length > 2)) {
|
|
2743
|
+
hasFileProgram = true;
|
|
2744
|
+
continue;
|
|
2745
|
+
}
|
|
2746
|
+
if (part.startsWith("-e") && part.length > 2) {
|
|
2747
|
+
programs.push(programSource(part.slice(2)));
|
|
2748
|
+
hasSourceOption = true;
|
|
2749
|
+
continue;
|
|
2750
|
+
}
|
|
2751
|
+
if (part.startsWith("-v") && part.length > 2) continue;
|
|
2752
|
+
if (part.startsWith("-F") && part.length > 2) continue;
|
|
2753
|
+
if (part.startsWith("-") && noOperandOptions.has(part)) continue;
|
|
2754
|
+
if (part.startsWith("-") && /^-[bcCghMnNPrStV]+$/.test(part)) continue;
|
|
2755
|
+
if (part.startsWith("-")) {
|
|
2756
|
+
unknown = true;
|
|
2757
|
+
break;
|
|
2758
|
+
}
|
|
2759
|
+
if (hasFileProgram || hasSourceOption) break;
|
|
2760
|
+
programs.push(programSource(word));
|
|
2761
|
+
break;
|
|
2762
|
+
}
|
|
2763
|
+
if (hasFileProgram) unknown = true;
|
|
2764
|
+
return { programs, unknown };
|
|
2765
|
+
}
|
|
2766
|
+
|
|
2767
|
+
function analyzeAwkProgram(program: string): { paths: string[]; unknown: boolean } {
|
|
2768
|
+
const { tokens, balanced } = tokenizeAwkProgram(program);
|
|
2769
|
+
const paths: string[] = [];
|
|
2770
|
+
let unknown =
|
|
2771
|
+
!balanced ||
|
|
2772
|
+
tokens.some(
|
|
2773
|
+
(token, index) => token.kind === "word" && token.value === "system" && tokens[index + 1]?.value === "(",
|
|
2774
|
+
);
|
|
2775
|
+
let braceDepth = 0;
|
|
2776
|
+
let parenDepth = 0;
|
|
2777
|
+
let bracketDepth = 0;
|
|
2778
|
+
let statementStart = true;
|
|
2779
|
+
let pendingControlParen = false;
|
|
2780
|
+
const controlParens: boolean[] = [];
|
|
2781
|
+
let printStatement: { braceDepth: number; parenDepth: number; bracketDepth: number } | undefined;
|
|
2782
|
+
for (let index = 0; index < tokens.length; index++) {
|
|
2783
|
+
const token = tokens[index];
|
|
2784
|
+
if (!token) continue;
|
|
2785
|
+
if (token.kind === "separator") {
|
|
2786
|
+
if (parenDepth === 0 && bracketDepth === 0) {
|
|
2787
|
+
printStatement = undefined;
|
|
2788
|
+
statementStart = true;
|
|
2789
|
+
pendingControlParen = false;
|
|
2790
|
+
}
|
|
2791
|
+
continue;
|
|
2792
|
+
}
|
|
2793
|
+
if (token.kind === "string" || token.kind === "word") {
|
|
2794
|
+
if (token.kind === "word" && statementStart && (token.value === "print" || token.value === "printf")) {
|
|
2795
|
+
printStatement = { braceDepth, parenDepth, bracketDepth };
|
|
2796
|
+
statementStart = false;
|
|
2797
|
+
pendingControlParen = false;
|
|
2798
|
+
continue;
|
|
2799
|
+
}
|
|
2800
|
+
if (token.kind === "word" && statementStart && ["for", "if", "while"].includes(token.value)) {
|
|
2801
|
+
pendingControlParen = true;
|
|
2802
|
+
statementStart = false;
|
|
2803
|
+
continue;
|
|
2804
|
+
}
|
|
2805
|
+
if (token.kind === "word" && statementStart && ["do", "else"].includes(token.value)) {
|
|
2806
|
+
statementStart = true;
|
|
2807
|
+
pendingControlParen = false;
|
|
2808
|
+
continue;
|
|
2809
|
+
}
|
|
2810
|
+
statementStart = false;
|
|
2811
|
+
pendingControlParen = false;
|
|
2812
|
+
continue;
|
|
2813
|
+
}
|
|
2814
|
+
if (token.value === "{") {
|
|
2815
|
+
braceDepth++;
|
|
2816
|
+
printStatement = undefined;
|
|
2817
|
+
statementStart = true;
|
|
2818
|
+
pendingControlParen = false;
|
|
2819
|
+
continue;
|
|
2820
|
+
}
|
|
2821
|
+
if (token.value === "}") {
|
|
2822
|
+
braceDepth--;
|
|
2823
|
+
if (braceDepth < 0) unknown = true;
|
|
2824
|
+
printStatement = undefined;
|
|
2825
|
+
statementStart = true;
|
|
2826
|
+
pendingControlParen = false;
|
|
2827
|
+
continue;
|
|
2828
|
+
}
|
|
2829
|
+
if (token.value === "(") {
|
|
2830
|
+
controlParens.push(pendingControlParen);
|
|
2831
|
+
pendingControlParen = false;
|
|
2832
|
+
parenDepth++;
|
|
2833
|
+
statementStart = false;
|
|
2834
|
+
continue;
|
|
2835
|
+
}
|
|
2836
|
+
if (token.value === ")") {
|
|
2837
|
+
parenDepth--;
|
|
2838
|
+
if (parenDepth < 0) unknown = true;
|
|
2839
|
+
statementStart = controlParens.pop() ?? false;
|
|
2840
|
+
continue;
|
|
2841
|
+
}
|
|
2842
|
+
if (token.value === "[") {
|
|
2843
|
+
bracketDepth++;
|
|
2844
|
+
statementStart = false;
|
|
2845
|
+
continue;
|
|
2846
|
+
}
|
|
2847
|
+
if (token.value === "]") {
|
|
2848
|
+
bracketDepth--;
|
|
2849
|
+
if (bracketDepth < 0) unknown = true;
|
|
2850
|
+
statementStart = false;
|
|
2851
|
+
continue;
|
|
2852
|
+
}
|
|
2853
|
+
if (token.value === ">" || token.value === ">>") {
|
|
2854
|
+
if (
|
|
2855
|
+
printStatement &&
|
|
2856
|
+
braceDepth === printStatement.braceDepth &&
|
|
2857
|
+
parenDepth === printStatement.parenDepth &&
|
|
2858
|
+
bracketDepth === printStatement.bracketDepth
|
|
2859
|
+
) {
|
|
2860
|
+
const destination = tokens[index + 1];
|
|
2861
|
+
const trailing = tokens[index + 2];
|
|
2862
|
+
if (
|
|
2863
|
+
destination?.kind !== "string" ||
|
|
2864
|
+
destination.unsafeEscapes ||
|
|
2865
|
+
(destination.value !== "" && trailing && trailing.kind !== "separator" && trailing.value !== "}")
|
|
2866
|
+
) {
|
|
2867
|
+
unknown = true;
|
|
2868
|
+
} else if (destination.value) {
|
|
2869
|
+
paths.push(destination.value);
|
|
2870
|
+
} else {
|
|
2871
|
+
unknown = true;
|
|
2872
|
+
}
|
|
2873
|
+
}
|
|
2874
|
+
statementStart = false;
|
|
2875
|
+
continue;
|
|
2876
|
+
}
|
|
2877
|
+
if (token.value === "|") {
|
|
2878
|
+
// AWK pipe I/O executes a command; print, printf, and getline effects are opaque.
|
|
2879
|
+
unknown = true;
|
|
2880
|
+
statementStart = false;
|
|
2881
|
+
continue;
|
|
2882
|
+
}
|
|
2883
|
+
if (token.value === ";" && parenDepth === 0 && bracketDepth === 0) {
|
|
2884
|
+
printStatement = undefined;
|
|
2885
|
+
statementStart = true;
|
|
2886
|
+
pendingControlParen = false;
|
|
2887
|
+
continue;
|
|
2888
|
+
}
|
|
2889
|
+
statementStart = false;
|
|
2890
|
+
pendingControlParen = false;
|
|
2891
|
+
}
|
|
2892
|
+
if (braceDepth !== 0 || parenDepth !== 0 || bracketDepth !== 0 || controlParens.length > 0) unknown = true;
|
|
2893
|
+
return { paths, unknown };
|
|
2894
|
+
}
|
|
2895
|
+
|
|
2896
|
+
function collectAwkProgramWrites(command: string, targets: ExtractedTargets): void {
|
|
2897
|
+
for (const match of command.matchAll(BASH_AWK_COMMAND_RE)) {
|
|
2898
|
+
const matchIndex = match.index ?? 0;
|
|
2899
|
+
if (!shellSyntaxPosition(command, matchIndex)) continue;
|
|
2900
|
+
const matchEnd = matchIndex + match[0].length;
|
|
2901
|
+
const { programs, unknown } = awkPrograms(shellWords(match[1] ?? ""));
|
|
2902
|
+
if (!shellSyntaxPosition(command, matchEnd, true) || unknown) {
|
|
2903
|
+
targets.explicitMutation = true;
|
|
2904
|
+
targets.unknown = true;
|
|
2905
|
+
}
|
|
2906
|
+
for (const program of programs) {
|
|
2907
|
+
if (program.expanded) {
|
|
2908
|
+
targets.explicitMutation = true;
|
|
2909
|
+
targets.unknown = true;
|
|
2910
|
+
}
|
|
2911
|
+
const analyzed = analyzeAwkProgram(program.source);
|
|
2912
|
+
if (analyzed.unknown) {
|
|
2913
|
+
targets.explicitMutation = true;
|
|
2914
|
+
targets.unknown = true;
|
|
2915
|
+
}
|
|
2916
|
+
for (const destination of analyzed.paths) {
|
|
2917
|
+
targets.explicitMutation = true;
|
|
2918
|
+
if (!isDeviceSinkPath(destination)) addPath(targets, destination);
|
|
2919
|
+
}
|
|
2920
|
+
}
|
|
2921
|
+
}
|
|
2922
|
+
}
|
|
2923
|
+
|
|
2924
|
+
function extractBashTargets(args: unknown, depth = 0): ExtractedTargets {
|
|
2925
|
+
const record = getRecord(args);
|
|
2926
|
+
const command = safeString(record?.command);
|
|
2927
|
+
const targets: ExtractedTargets = { paths: [], unknown: false };
|
|
2928
|
+
if (!command.trim()) {
|
|
2929
|
+
targets.unknown = true;
|
|
2930
|
+
return targets;
|
|
2931
|
+
}
|
|
2932
|
+
// A literal `sh|bash|zsh -c '<script>'` payload is a real command list. Its
|
|
2933
|
+
// mutations never match the top-level patterns, so recurse into it; anything
|
|
2934
|
+
// deeper than a bounded depth is not statically analyzable and fails closed.
|
|
2935
|
+
for (const match of command.matchAll(BASH_NESTED_SHELL_RE)) {
|
|
2936
|
+
if (depth >= 2) {
|
|
2937
|
+
targets.explicitMutation = true;
|
|
2938
|
+
targets.unknown = true;
|
|
2939
|
+
break;
|
|
2940
|
+
}
|
|
2941
|
+
const nested = extractBashTargets({ command: match[2] ?? match[4] ?? "" }, depth + 1);
|
|
2942
|
+
for (const nestedPath of nested.paths) addPath(targets, nestedPath);
|
|
2943
|
+
if (nested.unknown) targets.unknown = true;
|
|
2944
|
+
if (nested.explicitMutation) targets.explicitMutation = true;
|
|
2945
|
+
}
|
|
2946
|
+
// `$(...)` / backticks are a nested command list, exactly like `sh -c`: the
|
|
2947
|
+
// statement anchors below (`^`, `;`, `&`, `|`, newline) never see inside one,
|
|
2948
|
+
// so `echo "$(rm -rf src/x.ts)"` would otherwise scan clean. Heredoc masking
|
|
2949
|
+
// removes literal data-consumer bodies first; the extractor then ignores
|
|
2950
|
+
// inert `#` tails without touching quote/escape bytes needed by extraction.
|
|
2951
|
+
const heredoc = maskHeredocBodies(command);
|
|
2952
|
+
for (const substitution of extractSubstitutionBodies(heredoc.masked)) {
|
|
2953
|
+
if (depth >= 2 || !substitution.balanced) {
|
|
2954
|
+
targets.explicitMutation = true;
|
|
2955
|
+
targets.unknown = true;
|
|
2956
|
+
break;
|
|
2957
|
+
}
|
|
2958
|
+
const nested = extractBashTargets({ command: substitution.body }, depth + 1);
|
|
2959
|
+
for (const nestedPath of nested.paths) addPath(targets, nestedPath);
|
|
2960
|
+
if (nested.unknown) targets.unknown = true;
|
|
2961
|
+
if (nested.explicitMutation) targets.explicitMutation = true;
|
|
2962
|
+
}
|
|
2963
|
+
// Heredoc bodies fed to data consumers are inert document payloads; mask them
|
|
2964
|
+
// so spec/plan text cannot fake redirections. Script-consumer bodies survive
|
|
2965
|
+
// the mask and are still scanned as live code below.
|
|
2966
|
+
if (heredoc.opaqueExpansion || heredoc.mutatingConsumer) {
|
|
2967
|
+
targets.explicitMutation = true;
|
|
2968
|
+
targets.unknown = true;
|
|
2969
|
+
}
|
|
2970
|
+
// Nested scripts were read from the raw text above. Redirection extraction
|
|
2971
|
+
// uses the quote-preserving syntax view; command extraction uses its
|
|
2972
|
+
// dequoted executable-word view so quoted operands and split command words
|
|
2973
|
+
// remain visible without turning prose into syntax.
|
|
2974
|
+
const scanned = maskQuotedSpans(heredoc.masked);
|
|
2975
|
+
if (scanned.unmodeled) {
|
|
2976
|
+
// A live substitution construct we cannot balance (for example a
|
|
2977
|
+
// `case` pattern whose `)` is not the substitution close) must never
|
|
2978
|
+
// silently hide a mutation from the scanner.
|
|
2979
|
+
targets.explicitMutation = true;
|
|
2980
|
+
targets.unknown = true;
|
|
2981
|
+
}
|
|
2982
|
+
if (BASH_HEREDOC_OPAQUE_INTERPRETER_WRITE_RE.test(heredoc.masked)) {
|
|
2983
|
+
targets.explicitMutation = true;
|
|
2984
|
+
targets.unknown = true;
|
|
2985
|
+
}
|
|
2986
|
+
// `exec 1<>file` rebinds a descriptor, so a later `>/dev/null` may not reach the device at all.
|
|
2987
|
+
if (BASH_EXEC_REDIRECT_RE.test(scanned.masked)) {
|
|
2988
|
+
targets.explicitMutation = true;
|
|
2989
|
+
targets.unknown = true;
|
|
2990
|
+
}
|
|
2991
|
+
for (const match of scanned.masked.matchAll(BASH_EXTENDED_WRITE_RE)) {
|
|
2992
|
+
targets.explicitMutation = true;
|
|
2993
|
+
const cleaned = cleanShellWord(match[1] ?? "");
|
|
2994
|
+
if (!cleaned) targets.unknown = true;
|
|
2995
|
+
else if (!isDeviceSinkPath(cleaned)) addPath(targets, cleaned);
|
|
2996
|
+
}
|
|
2997
|
+
for (const match of scanned.masked.matchAll(BASH_DD_OUTPUT_RE)) {
|
|
2998
|
+
targets.explicitMutation = true;
|
|
2999
|
+
const parts = shellWords(match[1] ?? "").map(cleanShellWord);
|
|
3000
|
+
// Every `of=` counts: GNU dd honors the last one, so `of=/dev/null of=real.ts` writes real.ts.
|
|
3001
|
+
const outputs = parts.filter(part => part.startsWith("of="));
|
|
3002
|
+
if (outputs.length === 0) targets.unknown = true;
|
|
3003
|
+
for (const output of outputs) {
|
|
3004
|
+
const outputPath = cleanShellWord(output.slice(3));
|
|
3005
|
+
if (!outputPath) targets.unknown = true;
|
|
3006
|
+
else if (!isDeviceSinkPath(outputPath)) addPath(targets, outputPath);
|
|
3007
|
+
}
|
|
3008
|
+
}
|
|
3009
|
+
for (const match of scanned.dequoted.matchAll(BASH_IN_PLACE_MUTATION_COMMAND_RE)) {
|
|
3010
|
+
const parts = shellWords(match[1] ?? "").map(cleanShellWord);
|
|
3011
|
+
const hasInPlaceFlag = parts.some(part => /^-.*i/.test(part));
|
|
3012
|
+
if (!hasInPlaceFlag) continue;
|
|
3013
|
+
targets.explicitMutation = true;
|
|
3014
|
+
const target = [...parts].reverse().find(part => part && !part.startsWith("-"));
|
|
3015
|
+
if (target) addPath(targets, target);
|
|
3016
|
+
else targets.unknown = true;
|
|
3017
|
+
}
|
|
3018
|
+
for (const match of scanned.masked.matchAll(BASH_MUTATION_COMMAND_RE)) {
|
|
3019
|
+
const redirected = match[2]?.trim();
|
|
3020
|
+
if (!redirected) continue;
|
|
3021
|
+
targets.explicitMutation = true;
|
|
3022
|
+
const cleaned = cleanShellWord(redirected);
|
|
3023
|
+
// A capture that dequotes to nothing (e.g. `>" src.ts"`) is a truncated parse, not a safe no-op.
|
|
3024
|
+
if (!cleaned) targets.unknown = true;
|
|
3025
|
+
else if (!isDeviceSinkPath(cleaned)) addPath(targets, cleaned);
|
|
3026
|
+
}
|
|
3027
|
+
for (const match of scanned.dequoted.matchAll(BASH_MUTATION_COMMAND_RE)) {
|
|
3028
|
+
// Redirections are extracted from the quote-preserving syntax view above.
|
|
3029
|
+
// The dequoted view exists so quote-split command words (`r"m"`) and
|
|
3030
|
+
// quoted operands (`rm "src/product.ts"`) still reach this command branch.
|
|
3031
|
+
if (match[2]) continue;
|
|
3032
|
+
targets.explicitMutation = true;
|
|
3033
|
+
const parts = shellWords(match[1] ?? "");
|
|
3034
|
+
const commandName = match[0]?.match(BASH_MUTATION_COMMAND_NAME_RE)?.[1]?.toLowerCase();
|
|
3035
|
+
const chmodModeIndex =
|
|
3036
|
+
commandName === "chmod" ? parts.findIndex(part => BASH_CHMOD_MODE_RE.test(cleanShellWord(part))) : -1;
|
|
3037
|
+
let targetParts = parts;
|
|
3038
|
+
if (
|
|
3039
|
+
commandName === "cp" ||
|
|
3040
|
+
commandName === "mv" ||
|
|
3041
|
+
commandName === "install" ||
|
|
3042
|
+
commandName === "truncate" ||
|
|
3043
|
+
commandName === "ln"
|
|
3044
|
+
) {
|
|
3045
|
+
targetParts = parts.slice(-1);
|
|
3046
|
+
} else if (commandName === "chmod" && chmodModeIndex >= 0) {
|
|
3047
|
+
targetParts = parts.filter((_part, index) => index !== chmodModeIndex);
|
|
3048
|
+
}
|
|
3049
|
+
let extractedTarget = false;
|
|
3050
|
+
for (const part of targetParts) {
|
|
3051
|
+
const cleaned = cleanShellWord(part);
|
|
3052
|
+
if (!cleaned || cleaned.startsWith("-")) continue;
|
|
3053
|
+
// Redirection/heredoc operator words (`>/dev/null`, `<<'DOC'`, `2>&1`) are
|
|
3054
|
+
// not argument paths; their targets are captured by the redirect scanners.
|
|
3055
|
+
if (/^\d*[<>]/.test(cleaned)) continue;
|
|
3056
|
+
addPath(targets, cleaned);
|
|
3057
|
+
extractedTarget = true;
|
|
3058
|
+
}
|
|
3059
|
+
// A recognized mutator with no attributable operand is not a safe no-op:
|
|
3060
|
+
// quote masking, unsupported expansions, and option-only invocations all
|
|
3061
|
+
// fail closed rather than allowing a targetless mutation through planning.
|
|
3062
|
+
if (!extractedTarget) targets.unknown = true;
|
|
3063
|
+
}
|
|
3064
|
+
// `sed w file` and `s///w file` write without `-i`. `awk 'print > "file"'`
|
|
3065
|
+
// writes inside the program, which is not a shell redirection.
|
|
3066
|
+
collectInterpreterOneLinerWrites(heredoc.masked, targets, depth);
|
|
3067
|
+
collectSedScriptWrites(heredoc.masked, targets);
|
|
3068
|
+
collectAwkProgramWrites(heredoc.masked, targets);
|
|
3069
|
+
return targets;
|
|
3070
|
+
}
|
|
3071
|
+
/**
|
|
3072
|
+
* Read-only github ops extract no mutation. Every other op fails closed during
|
|
3073
|
+
* planning: remote push, PR creation, and worktree/config writes are not a
|
|
3074
|
+
* filesystem path the planning allowlist can clear.
|
|
3075
|
+
*/
|
|
3076
|
+
function extractGithubTargets(args: unknown): ExtractedTargets {
|
|
3077
|
+
if (isGithubReadOnlyArgs(args)) return { paths: [], unknown: false };
|
|
3078
|
+
return { paths: [], unknown: true, explicitMutation: true };
|
|
3079
|
+
}
|
|
3080
|
+
|
|
3081
|
+
function simpleLiteral(raw: string): string | null {
|
|
3082
|
+
const trimmed = raw.trim();
|
|
3083
|
+
const quote = trimmed[0];
|
|
3084
|
+
if ((quote !== "'" && quote !== '"') || trimmed.length < 2 || trimmed[trimmed.length - 1] !== quote) return null;
|
|
3085
|
+
const body = trimmed.slice(1, -1);
|
|
3086
|
+
return /[\\\n${]/.test(body) || body.includes(quote) ? null : body;
|
|
3087
|
+
}
|
|
3088
|
+
|
|
3089
|
+
function pythonFStringContainsDynamicExecution(code: string, start: number, end: number): boolean {
|
|
3090
|
+
const source = code.slice(start, end);
|
|
3091
|
+
const isFString = /(?:^|[^\w])(?:[rR]?[fF]|[fF][rR])$/.test(code.slice(Math.max(0, start - 3), start));
|
|
3092
|
+
return isFString && source.includes("{") && PYTHON_DYNAMIC_EXECUTION_TOKEN_RE.test(source);
|
|
3093
|
+
}
|
|
3094
|
+
|
|
3095
|
+
function skipNoise(code: string, index: number, language: "py" | "js"): number {
|
|
3096
|
+
if (language === "py" && (code.startsWith('"""', index) || code.startsWith("'''", index))) {
|
|
3097
|
+
const quote = code.slice(index, index + 3);
|
|
3098
|
+
const end = code.indexOf(quote, index + 3);
|
|
3099
|
+
return end < 0 ? code.length : end + 3;
|
|
3100
|
+
}
|
|
3101
|
+
const character = code[index] ?? "";
|
|
3102
|
+
if (character === "'" || character === '"') {
|
|
3103
|
+
let cursor = index + 1;
|
|
3104
|
+
while (cursor < code.length && code[cursor] !== character) cursor += code[cursor] === "\\" ? 2 : 1;
|
|
3105
|
+
return Math.min(code.length, cursor + 1);
|
|
3106
|
+
}
|
|
3107
|
+
if (
|
|
3108
|
+
(language === "py" && character === "#") ||
|
|
3109
|
+
(language === "js" && character === "/" && code[index + 1] === "/")
|
|
3110
|
+
) {
|
|
3111
|
+
const end = code.indexOf("\n", index);
|
|
3112
|
+
return end < 0 ? code.length : end;
|
|
3113
|
+
}
|
|
3114
|
+
if (language === "js" && character === "/" && code[index + 1] === "*") {
|
|
3115
|
+
const end = code.indexOf("*/", index + 2);
|
|
3116
|
+
return end < 0 ? code.length : end + 2;
|
|
3117
|
+
}
|
|
3118
|
+
return index;
|
|
3119
|
+
}
|
|
3120
|
+
|
|
3121
|
+
function readArg(code: string, index: number): { raw: string; end: number } | null {
|
|
3122
|
+
let cursor = index;
|
|
3123
|
+
while (/\s/.test(code[cursor] ?? "")) cursor += 1;
|
|
3124
|
+
if (cursor >= code.length || code[cursor] === ")") return null;
|
|
3125
|
+
const start = cursor;
|
|
3126
|
+
let depth = 0;
|
|
3127
|
+
while (cursor < code.length) {
|
|
3128
|
+
const character = code[cursor];
|
|
3129
|
+
if (character === "(") depth += 1;
|
|
3130
|
+
else if ((character === "," || character === ")") && depth === 0) break;
|
|
3131
|
+
else if (character === ")") depth -= 1;
|
|
3132
|
+
else if (character === "'" || character === '"') {
|
|
3133
|
+
const quote = character;
|
|
3134
|
+
cursor += 1;
|
|
3135
|
+
while (cursor < code.length && code[cursor] !== quote) cursor += code[cursor] === "\\" ? 2 : 1;
|
|
3136
|
+
}
|
|
3137
|
+
cursor += 1;
|
|
3138
|
+
}
|
|
3139
|
+
const raw = code.slice(start, cursor).trim();
|
|
3140
|
+
return raw.length > 0 ? { raw, end: cursor } : null;
|
|
3141
|
+
}
|
|
3142
|
+
|
|
3143
|
+
/** Omitted mode is Python's default `"r"`. A non-literal mode cannot be proved read-only. */
|
|
3144
|
+
function modeWrites(raw: string | undefined): boolean | null {
|
|
3145
|
+
if (raw === undefined) return false;
|
|
3146
|
+
const literal = simpleLiteral(raw);
|
|
3147
|
+
return literal === null ? null : /[wax+]/.test(literal);
|
|
3148
|
+
}
|
|
3149
|
+
|
|
3150
|
+
const PY_OS_MUTATORS = new Set(
|
|
3151
|
+
"remove unlink rename replace rmtree move copy copy2 copyfile symlink link mkdir makedirs rmdir truncate open".split(
|
|
3152
|
+
" ",
|
|
3153
|
+
),
|
|
3154
|
+
);
|
|
3155
|
+
/** Copy and rename write the destination, not only the source. */
|
|
3156
|
+
const TWO_ARG_MUTATORS = new Set(
|
|
3157
|
+
"rename replace move copy copy2 copyfile symlink link renameSync copyFileSync".split(" "),
|
|
3158
|
+
);
|
|
3159
|
+
const JS_FS_MUTATORS = new Set(
|
|
3160
|
+
"writeFileSync writeFile appendFileSync appendFile rmSync unlinkSync renameSync copyFileSync mkdirSync openSync".split(
|
|
3161
|
+
" ",
|
|
3162
|
+
),
|
|
3163
|
+
);
|
|
3164
|
+
|
|
3165
|
+
function nextCallArg(code: string, end: number): { raw: string; end: number } | null {
|
|
3166
|
+
let cursor = end;
|
|
3167
|
+
while (/\s/.test(code[cursor] ?? "")) cursor += 1;
|
|
3168
|
+
if (code[cursor] !== ",") return null;
|
|
3169
|
+
return readArg(code, cursor + 1);
|
|
3170
|
+
}
|
|
3171
|
+
|
|
3172
|
+
function openModeWrites(code: string, first: { raw: string; end: number }): boolean | null {
|
|
3173
|
+
let cursor = first.end;
|
|
3174
|
+
let positionalIndex = 1;
|
|
3175
|
+
let mode: string | undefined;
|
|
3176
|
+
let unknownMode = false;
|
|
3177
|
+
while (cursor < code.length) {
|
|
3178
|
+
while (/\s/.test(code[cursor] ?? "")) cursor += 1;
|
|
3179
|
+
if (code[cursor] !== ",") break;
|
|
3180
|
+
const argument = readArg(code, cursor + 1);
|
|
3181
|
+
if (!argument) break;
|
|
3182
|
+
const raw = argument.raw.trim();
|
|
3183
|
+
if (raw.startsWith("*") || raw.startsWith("**")) {
|
|
3184
|
+
unknownMode = true;
|
|
3185
|
+
} else {
|
|
3186
|
+
const keyword = /^([A-Za-z_]\w*)\s*=\s*([\s\S]*)$/.exec(raw);
|
|
3187
|
+
if (keyword?.[1] === "mode") {
|
|
3188
|
+
if (mode !== undefined) unknownMode = true;
|
|
3189
|
+
else mode = keyword[2];
|
|
3190
|
+
} else if (!keyword && positionalIndex === 1) {
|
|
3191
|
+
if (mode !== undefined) unknownMode = true;
|
|
3192
|
+
else mode = raw;
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
positionalIndex += 1;
|
|
3196
|
+
cursor = argument.end;
|
|
3197
|
+
}
|
|
3198
|
+
if (unknownMode) return null;
|
|
3199
|
+
return modeWrites(mode);
|
|
3200
|
+
}
|
|
3201
|
+
|
|
3202
|
+
/** Whitespace or a backslash-newline may sit before an attribute (`shutil .copy`). */
|
|
3203
|
+
function skipCallGap(code: string, index: number): number {
|
|
3204
|
+
let cursor = index;
|
|
3205
|
+
while (cursor < code.length) {
|
|
3206
|
+
const character = code[cursor] ?? "";
|
|
3207
|
+
if (/\s/.test(character)) {
|
|
3208
|
+
cursor += 1;
|
|
3209
|
+
continue;
|
|
3210
|
+
}
|
|
3211
|
+
if (character === "\\" && code[cursor + 1] === "\n") {
|
|
3212
|
+
cursor += 2;
|
|
3213
|
+
continue;
|
|
3214
|
+
}
|
|
3215
|
+
if (character === "\\" && code[cursor + 1] === "\r" && code[cursor + 2] === "\n") {
|
|
3216
|
+
cursor += 3;
|
|
3217
|
+
continue;
|
|
3218
|
+
}
|
|
3219
|
+
break;
|
|
3220
|
+
}
|
|
3221
|
+
return cursor;
|
|
3222
|
+
}
|
|
3223
|
+
|
|
3224
|
+
function literalWrite(targets: ExtractedTargets, raw: string | undefined, write: boolean | null): void {
|
|
3225
|
+
if (write === false) return;
|
|
3226
|
+
targets.explicitMutation = true;
|
|
3227
|
+
const literal = raw === undefined ? null : simpleLiteral(raw);
|
|
3228
|
+
if (write === null || literal === null || literal.length === 0) {
|
|
3229
|
+
targets.unknown = true;
|
|
3230
|
+
return;
|
|
3231
|
+
}
|
|
3232
|
+
addPath(targets, literal);
|
|
3233
|
+
}
|
|
3234
|
+
|
|
3235
|
+
/** Arguments of one Path() call, through its own closing parenthesis. */
|
|
3236
|
+
function readPathConstructor(code: string, argAt: number): { parts: string[]; after: number } | null {
|
|
3237
|
+
let cursor = argAt;
|
|
3238
|
+
const parts: string[] = [];
|
|
3239
|
+
while (cursor < code.length) {
|
|
3240
|
+
while (/\s/.test(code[cursor] ?? "")) cursor += 1;
|
|
3241
|
+
if (code[cursor] === ")") return { parts, after: cursor + 1 };
|
|
3242
|
+
const argument = readArg(code, cursor);
|
|
3243
|
+
if (!argument) return null;
|
|
3244
|
+
parts.push(argument.raw);
|
|
3245
|
+
cursor = argument.end;
|
|
3246
|
+
while (/\s/.test(code[cursor] ?? "")) cursor += 1;
|
|
3247
|
+
if (code[cursor] === ",") {
|
|
3248
|
+
cursor += 1;
|
|
3249
|
+
continue;
|
|
3250
|
+
}
|
|
3251
|
+
if (code[cursor] === ")") return { parts, after: cursor + 1 };
|
|
3252
|
+
return null;
|
|
3253
|
+
}
|
|
3254
|
+
return null;
|
|
3255
|
+
}
|
|
3256
|
+
|
|
3257
|
+
/** pathlib keeps the last absolute segment. A non-literal segment is an unresolved receiver. */
|
|
3258
|
+
function literalPathReceiver(parts: string[]): string | null {
|
|
3259
|
+
if (parts.length === 0) return ".";
|
|
3260
|
+
let joined = "";
|
|
3261
|
+
for (const part of parts) {
|
|
3262
|
+
const literal = simpleLiteral(part);
|
|
3263
|
+
if (literal === null) return null;
|
|
3264
|
+
if (path.isAbsolute(literal)) joined = literal;
|
|
3265
|
+
else joined = joined ? path.join(joined, literal) : literal;
|
|
3266
|
+
}
|
|
3267
|
+
return joined.length === 0 ? "." : joined;
|
|
3268
|
+
}
|
|
3269
|
+
|
|
3270
|
+
/** `Path.open()` defaults to read mode; a dynamic mode cannot be proven read-only. */
|
|
3271
|
+
function pathlibOpenModeWrites(code: string, methodAt: number): boolean | null {
|
|
3272
|
+
const call = /^\s*\.\s*open\s*\(/.exec(code.slice(methodAt));
|
|
3273
|
+
if (!call) return false;
|
|
3274
|
+
let cursor = methodAt + call[0].length;
|
|
3275
|
+
let mode: string | undefined;
|
|
3276
|
+
let modeSeen = false;
|
|
3277
|
+
let unknownMode = false;
|
|
3278
|
+
let positionalIndex = 0;
|
|
3279
|
+
while (cursor < code.length) {
|
|
3280
|
+
while (/\s/.test(code[cursor] ?? "")) cursor += 1;
|
|
3281
|
+
if (code[cursor] === ")") break;
|
|
3282
|
+
const argument = readArg(code, cursor);
|
|
3283
|
+
if (!argument) return null;
|
|
3284
|
+
const raw = argument.raw.trim();
|
|
3285
|
+
if (raw.startsWith("*") || raw.startsWith("**")) {
|
|
3286
|
+
unknownMode = true;
|
|
3287
|
+
} else {
|
|
3288
|
+
const keyword = /^([A-Za-z_]\w*)\s*=\s*([\s\S]*)$/.exec(raw);
|
|
3289
|
+
if (keyword?.[1] === "mode") {
|
|
3290
|
+
if (modeSeen) unknownMode = true;
|
|
3291
|
+
else {
|
|
3292
|
+
mode = keyword[2];
|
|
3293
|
+
modeSeen = true;
|
|
3294
|
+
}
|
|
3295
|
+
} else if (!keyword && positionalIndex === 0) {
|
|
3296
|
+
if (modeSeen) unknownMode = true;
|
|
3297
|
+
else {
|
|
3298
|
+
mode = raw;
|
|
3299
|
+
modeSeen = true;
|
|
3300
|
+
}
|
|
3301
|
+
}
|
|
3302
|
+
}
|
|
3303
|
+
positionalIndex += 1;
|
|
3304
|
+
cursor = argument.end;
|
|
3305
|
+
while (/\s/.test(code[cursor] ?? "")) cursor += 1;
|
|
3306
|
+
if (code[cursor] === ",") cursor += 1;
|
|
3307
|
+
else if (code[cursor] !== ")") return null;
|
|
3308
|
+
}
|
|
3309
|
+
return unknownMode ? null : modeWrites(mode);
|
|
3310
|
+
}
|
|
3311
|
+
|
|
3312
|
+
/** Calls inside strings or comments are skipped. A non-literal write path fails closed. */
|
|
3313
|
+
function scanInterpreterWrites(code: string, language: "py" | "js", targets: ExtractedTargets): void {
|
|
3314
|
+
let index = 0;
|
|
3315
|
+
const recognizedPathMethodIndexes = new Set<number>();
|
|
3316
|
+
while (index < code.length) {
|
|
3317
|
+
const trivia = skipNoise(code, index, language);
|
|
3318
|
+
if (trivia !== index) {
|
|
3319
|
+
if (language === "py" && pythonFStringContainsDynamicExecution(code, index, trivia)) {
|
|
3320
|
+
targets.explicitMutation = true;
|
|
3321
|
+
targets.unknown = true;
|
|
3322
|
+
return;
|
|
3323
|
+
}
|
|
3324
|
+
index = trivia;
|
|
3325
|
+
continue;
|
|
3326
|
+
}
|
|
3327
|
+
if (
|
|
3328
|
+
INTERPRETER_OUTPUT_METHOD_ASSIGNMENT_RE.test(code.slice(index)) ||
|
|
3329
|
+
INTERPRETER_OUTPUT_STREAM_MUTATION_RE.test(code.slice(index))
|
|
3330
|
+
) {
|
|
3331
|
+
targets.explicitMutation = true;
|
|
3332
|
+
targets.unknown = true;
|
|
3333
|
+
return;
|
|
3334
|
+
}
|
|
3335
|
+
const previous = index === 0 ? "" : (code[index - 1] ?? "");
|
|
3336
|
+
if ((index > 0 && /[\w]/.test(previous)) || !/[A-Za-z_]/.test(code[index] ?? "")) {
|
|
3337
|
+
index += 1;
|
|
3338
|
+
continue;
|
|
3339
|
+
}
|
|
3340
|
+
const ident = /^[A-Za-z_]\w*/.exec(code.slice(index));
|
|
3341
|
+
if (!ident) {
|
|
3342
|
+
index += 1;
|
|
3343
|
+
continue;
|
|
3344
|
+
}
|
|
3345
|
+
const name = ident[0];
|
|
3346
|
+
if (language === "py" && PYTHON_DYNAMIC_EXECUTION_IDENTIFIER_RE.test(name)) {
|
|
3347
|
+
targets.explicitMutation = true;
|
|
3348
|
+
targets.unknown = true;
|
|
3349
|
+
return;
|
|
3350
|
+
}
|
|
3351
|
+
let receiverDot = index - 1;
|
|
3352
|
+
while (receiverDot >= 0 && /\s/.test(code[receiverDot] ?? "")) receiverDot -= 1;
|
|
3353
|
+
const unresolvedPathMethod =
|
|
3354
|
+
language === "py" &&
|
|
3355
|
+
code[receiverDot] === "." &&
|
|
3356
|
+
(/^write_\w+$/.test(name) || name === "touch" || name === "open");
|
|
3357
|
+
if (unresolvedPathMethod && !recognizedPathMethodIndexes.has(index)) {
|
|
3358
|
+
const callAt = skipCallGap(code, index + name.length);
|
|
3359
|
+
if (code[callAt] === "(") {
|
|
3360
|
+
const writes = name === "open" ? pathlibOpenModeWrites(code, receiverDot) : true;
|
|
3361
|
+
if (writes !== false) {
|
|
3362
|
+
targets.explicitMutation = true;
|
|
3363
|
+
targets.unknown = true;
|
|
3364
|
+
}
|
|
3365
|
+
index = Math.max(callAt + 1, index + name.length);
|
|
3366
|
+
continue;
|
|
3367
|
+
}
|
|
3368
|
+
}
|
|
3369
|
+
if ((name === "write" || name === "append") && previous === ".") {
|
|
3370
|
+
index += name.length;
|
|
3371
|
+
continue;
|
|
3372
|
+
}
|
|
3373
|
+
let cursor = skipCallGap(code, index + name.length);
|
|
3374
|
+
let dotted = "";
|
|
3375
|
+
if (code[cursor] === ".") {
|
|
3376
|
+
const methodAt = skipCallGap(code, cursor + 1);
|
|
3377
|
+
const dot = /^\w+/.exec(code.slice(methodAt));
|
|
3378
|
+
dotted = dot?.[0] ?? "";
|
|
3379
|
+
cursor = methodAt + dotted.length;
|
|
3380
|
+
}
|
|
3381
|
+
const paren = /^\s*\(/.exec(code.slice(cursor));
|
|
3382
|
+
const helper = (name === "write" || name === "append") && dotted === "";
|
|
3383
|
+
const open = (name === "open" && language === "py") || (name === "openSync" && language === "js");
|
|
3384
|
+
const pathCtor =
|
|
3385
|
+
(name === "Path" && dotted === "") || (language === "py" && name === "pathlib" && dotted === "Path");
|
|
3386
|
+
const osCall =
|
|
3387
|
+
language === "py" &&
|
|
3388
|
+
((name === "os" && PY_OS_MUTATORS.has(dotted)) || (name === "shutil" && PY_OS_MUTATORS.has(dotted)));
|
|
3389
|
+
const jsCall =
|
|
3390
|
+
language === "js" && ((JS_FS_MUTATORS.has(name) && dotted === "") || (name === "Bun" && dotted === "write"));
|
|
3391
|
+
if (!paren || (!helper && !(open && dotted === "") && !pathCtor && !osCall && !jsCall)) {
|
|
3392
|
+
index += name.length;
|
|
3393
|
+
continue;
|
|
3394
|
+
}
|
|
3395
|
+
const argAt = cursor + paren[0].length;
|
|
3396
|
+
const first = readArg(code, argAt);
|
|
3397
|
+
if (pathCtor) {
|
|
3398
|
+
const ctor = readPathConstructor(code, argAt);
|
|
3399
|
+
if (!ctor) {
|
|
3400
|
+
index += 1;
|
|
3401
|
+
continue;
|
|
3402
|
+
}
|
|
3403
|
+
const method = /^\s*\.\s*(write_\w+|open|touch)\s*\(/.exec(code.slice(ctor.after));
|
|
3404
|
+
if (method) {
|
|
3405
|
+
if (ctor.parts.length > 1) {
|
|
3406
|
+
recognizedPathMethodIndexes.add(ctor.after + method[0].indexOf(method[1]));
|
|
3407
|
+
}
|
|
3408
|
+
const writes = method[1] === "open" ? pathlibOpenModeWrites(code, ctor.after) : true;
|
|
3409
|
+
if (writes !== false) {
|
|
3410
|
+
targets.explicitMutation = true;
|
|
3411
|
+
const receiver = literalPathReceiver(ctor.parts);
|
|
3412
|
+
if (writes === null || receiver === null || receiver.length === 0) targets.unknown = true;
|
|
3413
|
+
else addPath(targets, receiver);
|
|
3414
|
+
}
|
|
3415
|
+
}
|
|
3416
|
+
// Extra segments stay in the argument walk so a nested mutator is still recorded.
|
|
3417
|
+
index =
|
|
3418
|
+
ctor.parts.length > 1 ? index + name.length : Math.max(ctor.after + (method?.[0].length ?? 0), index + 1);
|
|
3419
|
+
continue;
|
|
3420
|
+
}
|
|
3421
|
+
if (!first) {
|
|
3422
|
+
literalWrite(targets, undefined, null);
|
|
3423
|
+
index = Math.max(argAt, index + 1);
|
|
3424
|
+
continue;
|
|
3425
|
+
}
|
|
3426
|
+
if (open && dotted === "") {
|
|
3427
|
+
literalWrite(targets, first.raw, openModeWrites(code, first));
|
|
3428
|
+
index = Math.max(first.end, index + 1);
|
|
3429
|
+
continue;
|
|
3430
|
+
}
|
|
3431
|
+
literalWrite(targets, first.raw, true);
|
|
3432
|
+
let end = first.end;
|
|
3433
|
+
if (TWO_ARG_MUTATORS.has(dotted || name)) {
|
|
3434
|
+
const second = nextCallArg(code, first.end);
|
|
3435
|
+
if (!second) literalWrite(targets, undefined, null);
|
|
3436
|
+
else {
|
|
3437
|
+
literalWrite(targets, second.raw, true);
|
|
3438
|
+
end = second.end;
|
|
3439
|
+
}
|
|
3440
|
+
}
|
|
3441
|
+
index = Math.max(end, index + 1);
|
|
3442
|
+
}
|
|
3443
|
+
}
|
|
3444
|
+
|
|
3445
|
+
function extractCodeToolTargets(toolName: string, args: unknown): ExtractedTargets {
|
|
3446
|
+
const targets: ExtractedTargets = { paths: [], unknown: false };
|
|
3447
|
+
const record = getRecord(args);
|
|
3448
|
+
if (!record) {
|
|
3449
|
+
targets.unknown = true;
|
|
3450
|
+
targets.explicitMutation = true;
|
|
3451
|
+
return targets;
|
|
3452
|
+
}
|
|
3453
|
+
if (toolName === "python") {
|
|
3454
|
+
if ((safeString(record.action) || "execute") === "clear") return targets;
|
|
3455
|
+
if (typeof record.code !== "string" || record.code.trim() === "") return targets;
|
|
3456
|
+
scanInterpreterWrites(record.code, "py", targets);
|
|
3457
|
+
return targets;
|
|
3458
|
+
}
|
|
3459
|
+
if (!Array.isArray(record.cells)) {
|
|
3460
|
+
targets.unknown = true;
|
|
3461
|
+
targets.explicitMutation = true;
|
|
3462
|
+
return targets;
|
|
3463
|
+
}
|
|
3464
|
+
for (const cell of record.cells) {
|
|
3465
|
+
const cellRecord = getRecord(cell);
|
|
3466
|
+
if (typeof cellRecord?.code !== "string") {
|
|
3467
|
+
targets.unknown = true;
|
|
3468
|
+
targets.explicitMutation = true;
|
|
3469
|
+
continue;
|
|
3470
|
+
}
|
|
3471
|
+
if (cellRecord.language === "py") scanInterpreterWrites(cellRecord.code, "py", targets);
|
|
3472
|
+
else if (cellRecord.language === "js") scanInterpreterWrites(cellRecord.code, "js", targets);
|
|
3473
|
+
else {
|
|
3474
|
+
targets.unknown = true;
|
|
3475
|
+
targets.explicitMutation = true;
|
|
3476
|
+
}
|
|
3477
|
+
}
|
|
3478
|
+
return targets;
|
|
3479
|
+
}
|
|
3480
|
+
|
|
3481
|
+
function extractTargets(tool: ToolWithEditMode, args: unknown): ExtractedTargets {
|
|
3482
|
+
if (tool.name === "write") return extractWriteTargets(args);
|
|
3483
|
+
if (tool.name === "ast_edit") return extractAstEditTargets(args);
|
|
3484
|
+
if (tool.name === "edit") return extractEditTargets(args, tool);
|
|
3485
|
+
if (tool.name === "bash") return extractBashTargets(args);
|
|
3486
|
+
if (tool.name === "github") return extractGithubTargets(args);
|
|
3487
|
+
if (tool.name === "python" || tool.name === "eval") return extractCodeToolTargets(tool.name, args);
|
|
3488
|
+
return { paths: [], unknown: true };
|
|
3489
|
+
}
|
|
3490
|
+
|
|
3491
|
+
function stripSelectorBase(rawPath: string): string {
|
|
3492
|
+
const archiveOrSqlite = rawPath.match(ARCHIVE_OR_SQLITE_BASE_RE);
|
|
3493
|
+
if (archiveOrSqlite?.[1]) return archiveOrSqlite[1];
|
|
3494
|
+
return rawPath;
|
|
3495
|
+
}
|
|
3496
|
+
|
|
3497
|
+
function resolveRawPath(cwd: string, rawPath: string): { absolutePath?: string; unknown: boolean } {
|
|
3498
|
+
const normalized = rawPath.trim();
|
|
3499
|
+
if (!normalized) return { unknown: true };
|
|
3500
|
+
if (normalized === ".") return { absolutePath: path.resolve(cwd), unknown: false };
|
|
3501
|
+
if (normalized.startsWith("local://") || normalized.startsWith("local:/")) {
|
|
3502
|
+
const options = LocalProtocolHandler.resolveOptions();
|
|
3503
|
+
if (!options) return { unknown: true };
|
|
3504
|
+
try {
|
|
3505
|
+
return { absolutePath: resolveLocalUrlToPath(normalized, options), unknown: false };
|
|
3506
|
+
} catch {
|
|
3507
|
+
return { unknown: true };
|
|
3508
|
+
}
|
|
3509
|
+
}
|
|
3510
|
+
if (INTERNAL_SCHEME_RE.test(normalized)) return { unknown: true };
|
|
3511
|
+
|
|
3512
|
+
const basePath = stripSelectorBase(normalized);
|
|
3513
|
+
try {
|
|
3514
|
+
return { absolutePath: resolveToCwd(basePath, cwd), unknown: false };
|
|
3515
|
+
} catch {
|
|
3516
|
+
return { unknown: true };
|
|
3517
|
+
}
|
|
3518
|
+
}
|
|
3519
|
+
|
|
3520
|
+
function relativeSkcSegments(cwd: string, rawPath: string): string[] | null {
|
|
3521
|
+
const { absolutePath, unknown } = resolveRawPath(cwd, rawPath);
|
|
3522
|
+
if (unknown || !absolutePath) return null;
|
|
3523
|
+
const relative = path.relative(path.resolve(cwd), path.resolve(absolutePath));
|
|
3524
|
+
if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
|
|
3525
|
+
return normalizePosix(relative).split("/").filter(Boolean);
|
|
3526
|
+
}
|
|
3527
|
+
|
|
3528
|
+
function blockedWorkflowStateSkill(cwd: string, rawPath: string): CanonicalSkcWorkflowSkill | null {
|
|
3529
|
+
const segments = relativeSkcSegments(cwd, rawPath);
|
|
3530
|
+
if (segments?.[0] !== ".skc") return null;
|
|
558
3531
|
const generatedRoot = segments[1]?.startsWith(SKC_SESSION_PREFIX) ? segments[2] : segments[1];
|
|
559
3532
|
if (generatedRoot === "specs" || generatedRoot === "plans") return null;
|
|
560
3533
|
if (generatedRoot !== "state") return null;
|
|
561
3534
|
const fileName = segments.at(-1) ?? "";
|
|
562
|
-
for (const skillName of ["deep-interview", "ralplan", "ultragoal"
|
|
3535
|
+
for (const skillName of ["deep-interview", "ralplan", "ultragoal"] as const) {
|
|
563
3536
|
if (fileName === workflowModeStateFileName(skillName)) return skillName;
|
|
564
3537
|
}
|
|
565
3538
|
if (fileName === "skill-active-state.json") return "deep-interview";
|
|
@@ -574,11 +3547,23 @@ function firstBlockedWorkflowStateSkill(cwd: string, targets: ExtractedTargets):
|
|
|
574
3547
|
return null;
|
|
575
3548
|
}
|
|
576
3549
|
|
|
577
|
-
function
|
|
3550
|
+
function planningSessionDirName(sessionId: string | null | undefined): string | undefined {
|
|
3551
|
+
const trimmed = sessionId?.trim();
|
|
3552
|
+
if (!trimmed) return undefined;
|
|
3553
|
+
return sessionDirName(trimmed);
|
|
3554
|
+
}
|
|
3555
|
+
|
|
3556
|
+
/** Specs and plans are planning-writable. A `_session-` directory must be this session's encoded name. */
|
|
3557
|
+
function isAllowlistedPath(cwd: string, rawPath: string, sessionId?: string | null): boolean {
|
|
578
3558
|
const segments = relativeSkcSegments(cwd, rawPath);
|
|
579
3559
|
if (segments?.[0] !== ".skc") return false;
|
|
580
|
-
const
|
|
581
|
-
|
|
3560
|
+
const head = segments[1];
|
|
3561
|
+
if (head?.startsWith(SKC_SESSION_PREFIX)) {
|
|
3562
|
+
const bound = planningSessionDirName(sessionId);
|
|
3563
|
+
if (!bound || head !== bound) return false;
|
|
3564
|
+
return segments[2] === "specs" || segments[2] === "plans";
|
|
3565
|
+
}
|
|
3566
|
+
return head === "specs" || head === "plans";
|
|
582
3567
|
}
|
|
583
3568
|
function isBlockedSkcPath(cwd: string, rawPath: string): boolean {
|
|
584
3569
|
const segments = relativeSkcSegments(cwd, rawPath);
|
|
@@ -589,21 +3574,119 @@ function hasBlockedSkcTarget(cwd: string, targets: ExtractedTargets): boolean {
|
|
|
589
3574
|
return targets.paths.some(rawPath => isBlockedSkcPath(cwd, rawPath));
|
|
590
3575
|
}
|
|
591
3576
|
|
|
592
|
-
function allTargetsAllowlisted(cwd: string, targets: ExtractedTargets): boolean {
|
|
3577
|
+
function allTargetsAllowlisted(cwd: string, targets: ExtractedTargets, sessionId?: string | null): boolean {
|
|
593
3578
|
return (
|
|
594
|
-
!targets.unknown &&
|
|
3579
|
+
!targets.unknown &&
|
|
3580
|
+
targets.paths.length > 0 &&
|
|
3581
|
+
targets.paths.every(rawPath => isAllowlistedPath(cwd, rawPath, sessionId))
|
|
595
3582
|
);
|
|
596
3583
|
}
|
|
597
3584
|
|
|
598
|
-
|
|
3585
|
+
/** POSIX directories that are temp roots even when `TMPDIR` is unset or poisoned. */
|
|
3586
|
+
const POSIX_SYSTEM_TEMP_ROOTS = ["/tmp", "/var/tmp", "/private/tmp", "/private/var/tmp"];
|
|
3587
|
+
|
|
3588
|
+
/**
|
|
3589
|
+
* `os.tmpdir()` follows `TMPDIR`, and Bun copies `cwd/.env` into the environment
|
|
3590
|
+
* when that variable was unset. A repository can therefore name an arbitrary
|
|
3591
|
+
* directory. Declarations below are not neutral scratch roots.
|
|
3592
|
+
*/
|
|
3593
|
+
function tempEnvNames(): readonly string[] {
|
|
3594
|
+
return process.platform === "win32" ? ["TEMP", "TMP", "TMPDIR"] : ["TMPDIR"];
|
|
3595
|
+
}
|
|
3596
|
+
|
|
3597
|
+
const PROJECT_TEMP_DOTENV_MAX_FILE_BYTES = 64 * 1024;
|
|
3598
|
+
|
|
3599
|
+
// The snapshot is the cwd at module import, not a directory created later or a chdir before this module is imported.
|
|
3600
|
+
const startupTempSnapshot = projectEnvSnapshot(process.cwd(), {
|
|
3601
|
+
maxFileBytes: PROJECT_TEMP_DOTENV_MAX_FILE_BYTES,
|
|
3602
|
+
});
|
|
3603
|
+
|
|
3604
|
+
function projectTempSnapshots(cwd: string): ProjectEnvSnapshot[] {
|
|
3605
|
+
// Check both the cwd's .env and the startup snapshot (for module-import-time cwd).
|
|
3606
|
+
// The cwd's .env catches project-declared TMPDIR in the current working directory.
|
|
3607
|
+
// The startup snapshot is a fallback for when the cwd's .env is deleted or inaccessible
|
|
3608
|
+
// (e.g., after unlink or chdir), and also handles the case where cwd differs from the
|
|
3609
|
+
// module-import-time cwd. These workspace-controlled files are read as bounded regular files.
|
|
3610
|
+
const snapshots: ProjectEnvSnapshot[] = [
|
|
3611
|
+
projectEnvSnapshot(cwd, { maxFileBytes: PROJECT_TEMP_DOTENV_MAX_FILE_BYTES }),
|
|
3612
|
+
startupTempSnapshot,
|
|
3613
|
+
];
|
|
3614
|
+
return snapshots;
|
|
3615
|
+
}
|
|
3616
|
+
|
|
3617
|
+
/** macOS account temp directory. `getconf` does not read `TMPDIR`. */
|
|
3618
|
+
let darwinUserTempDirCache: string | undefined | null = null;
|
|
3619
|
+
function darwinUserTempDir(): string | undefined {
|
|
3620
|
+
if (process.platform !== "darwin") return undefined;
|
|
3621
|
+
if (darwinUserTempDirCache !== null) return darwinUserTempDirCache;
|
|
3622
|
+
darwinUserTempDirCache = undefined;
|
|
3623
|
+
try {
|
|
3624
|
+
const result = Bun.spawnSync({
|
|
3625
|
+
cmd: ["/usr/bin/getconf", "DARWIN_USER_TEMP_DIR"],
|
|
3626
|
+
env: { PATH: "/usr/bin:/bin:/usr/sbin:/sbin", LC_ALL: "C" },
|
|
3627
|
+
stdout: "pipe",
|
|
3628
|
+
stderr: "ignore",
|
|
3629
|
+
});
|
|
3630
|
+
if (result.exitCode !== 0) return undefined;
|
|
3631
|
+
const value = new TextDecoder().decode(result.stdout).trim();
|
|
3632
|
+
if (value) darwinUserTempDirCache = value;
|
|
3633
|
+
} catch {
|
|
3634
|
+
// Fixed `/tmp` roots still cover the POSIX default.
|
|
3635
|
+
}
|
|
3636
|
+
return darwinUserTempDirCache ?? undefined;
|
|
3637
|
+
}
|
|
3638
|
+
|
|
3639
|
+
function addResolvedTempRoot(roots: Set<string>, value: string | undefined): void {
|
|
3640
|
+
const trimmed = value?.trim();
|
|
3641
|
+
if (trimmed) roots.add(path.resolve(trimmed));
|
|
3642
|
+
}
|
|
3643
|
+
|
|
3644
|
+
function isPlatformTempPath(resolved: string): boolean {
|
|
3645
|
+
for (const root of POSIX_SYSTEM_TEMP_ROOTS) {
|
|
3646
|
+
const resolvedRoot = path.resolve(root);
|
|
3647
|
+
if (resolved === resolvedRoot || isPathWithin(resolvedRoot, resolved)) return true;
|
|
3648
|
+
}
|
|
3649
|
+
const darwin = darwinUserTempDir();
|
|
3650
|
+
if (!darwin) return false;
|
|
3651
|
+
const resolvedDarwin = path.resolve(darwin);
|
|
3652
|
+
return resolved === resolvedDarwin || isPathWithin(resolvedDarwin, resolved);
|
|
3653
|
+
}
|
|
3654
|
+
|
|
3655
|
+
/** True when `live` is declared, or cannot be trusted because a dotenv layer was unsafe to read. */
|
|
3656
|
+
function projectDeclaresTempPath(snapshots: readonly ProjectEnvSnapshot[], live: string): boolean {
|
|
3657
|
+
const trimmedLive = live.trim();
|
|
3658
|
+
if (!trimmedLive) return false;
|
|
3659
|
+
const resolvedLive = path.resolve(trimmedLive);
|
|
3660
|
+
for (const snapshot of snapshots) {
|
|
3661
|
+
if (snapshot.incomplete && !isPlatformTempPath(resolvedLive)) return true;
|
|
3662
|
+
for (const name of tempEnvNames()) {
|
|
3663
|
+
const key = canonicalEnvKey(name);
|
|
3664
|
+
const declared = snapshot.values[key];
|
|
3665
|
+
if (declared === undefined) continue;
|
|
3666
|
+
if (snapshot.dynamic.has(key)) {
|
|
3667
|
+
// Expansion is not comparable. A dynamic value that landed on a
|
|
3668
|
+
// real system temp dir is already allowed through those roots.
|
|
3669
|
+
if (!isPlatformTempPath(resolvedLive)) return true;
|
|
3670
|
+
continue;
|
|
3671
|
+
}
|
|
3672
|
+
const trimmedDeclared = declared.trim();
|
|
3673
|
+
if (trimmedDeclared && path.resolve(trimmedDeclared) === resolvedLive) return true;
|
|
3674
|
+
}
|
|
3675
|
+
}
|
|
3676
|
+
return false;
|
|
3677
|
+
}
|
|
3678
|
+
|
|
3679
|
+
function neutralTempRoots(cwd: string): string[] {
|
|
599
3680
|
const roots = new Set<string>();
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
3681
|
+
for (const fixed of POSIX_SYSTEM_TEMP_ROOTS) addResolvedTempRoot(roots, fixed);
|
|
3682
|
+
addResolvedTempRoot(roots, darwinUserTempDir());
|
|
3683
|
+
const candidates = [os.tmpdir(), process.env.TMPDIR];
|
|
3684
|
+
if (process.platform === "win32") candidates.push(process.env.TEMP, process.env.TMP);
|
|
3685
|
+
const snapshots = projectTempSnapshots(cwd);
|
|
3686
|
+
for (const candidate of candidates) {
|
|
3687
|
+
if (!candidate || projectDeclaresTempPath(snapshots, candidate)) continue;
|
|
3688
|
+
addResolvedTempRoot(roots, candidate);
|
|
3689
|
+
}
|
|
607
3690
|
return [...roots];
|
|
608
3691
|
}
|
|
609
3692
|
|
|
@@ -657,18 +3740,44 @@ async function isNeutralTempPath(cwd: string, rawPath: string): Promise<boolean>
|
|
|
657
3740
|
if (unknown || !absolutePath) return false;
|
|
658
3741
|
const resolvedCwd = path.resolve(cwd);
|
|
659
3742
|
if (isPathWithin(resolvedCwd, absolutePath)) return false;
|
|
660
|
-
|
|
3743
|
+
const roots = neutralTempRoots(cwd);
|
|
3744
|
+
const realRoots = await Promise.all(roots.map(realpathOrSelf));
|
|
3745
|
+
// Accept both spellings (`/var/folders` and `/private/var/folders`) before the
|
|
3746
|
+
// canonical re-check. The re-check still rejects a temp path whose real
|
|
3747
|
+
// target is inside the project.
|
|
3748
|
+
const lexicalRoots = new Set([...roots, ...realRoots]);
|
|
3749
|
+
if (![...lexicalRoots].some(root => isPathWithin(root, absolutePath))) return false;
|
|
661
3750
|
const realTarget = await canonicalizeForContainment(absolutePath);
|
|
662
3751
|
if (isPathWithin(await realpathOrSelf(resolvedCwd), realTarget)) return false;
|
|
663
|
-
const realRoots = await Promise.all(neutralTempRoots().map(realpathOrSelf));
|
|
664
3752
|
return realRoots.some(root => isPathWithin(root, realTarget));
|
|
665
3753
|
}
|
|
666
3754
|
|
|
3755
|
+
/** realpath cannot expose another name for the same inode outside a writable root. */
|
|
3756
|
+
async function hasUnsharedFileTarget(cwd: string, rawPath: string): Promise<boolean> {
|
|
3757
|
+
const { absolutePath, unknown } = resolveRawPath(cwd, rawPath);
|
|
3758
|
+
if (unknown || !absolutePath) return false;
|
|
3759
|
+
try {
|
|
3760
|
+
const target = await fs.stat(absolutePath);
|
|
3761
|
+
return !target.isFile() || target.nlink === 1;
|
|
3762
|
+
} catch (error) {
|
|
3763
|
+
// New scratch files remain writable; inaccessible or unresolvable targets fail closed.
|
|
3764
|
+
return (error as NodeJS.ErrnoException).code === "ENOENT";
|
|
3765
|
+
}
|
|
3766
|
+
}
|
|
3767
|
+
|
|
667
3768
|
/** Targets that remain disallowed during a planning phase (excludes neutral temp scratch). */
|
|
668
|
-
async function planningBlockedTargets(
|
|
3769
|
+
async function planningBlockedTargets(
|
|
3770
|
+
cwd: string,
|
|
3771
|
+
targets: ExtractedTargets,
|
|
3772
|
+
sessionId?: string | null,
|
|
3773
|
+
): Promise<string[]> {
|
|
669
3774
|
const blocked: string[] = [];
|
|
670
3775
|
for (const rawPath of targets.paths) {
|
|
671
|
-
if (
|
|
3776
|
+
if (!(await hasUnsharedFileTarget(cwd, rawPath))) {
|
|
3777
|
+
blocked.push(rawPath);
|
|
3778
|
+
continue;
|
|
3779
|
+
}
|
|
3780
|
+
if (isAllowlistedPath(cwd, rawPath, sessionId)) continue;
|
|
672
3781
|
if (!(await isNeutralTempPath(cwd, rawPath))) blocked.push(rawPath);
|
|
673
3782
|
}
|
|
674
3783
|
return blocked;
|
|
@@ -690,12 +3799,15 @@ export async function assertWorkflowMutationRawPathsAllowed(input: {
|
|
|
690
3799
|
throw new ToolError(`${WORKFLOW_STATE_MUTATION_BLOCK_MESSAGE}\nUse: ${command}`);
|
|
691
3800
|
}
|
|
692
3801
|
if (input.forceOverride) return;
|
|
693
|
-
const
|
|
3802
|
+
const guardContext =
|
|
3803
|
+
input.guardContext ??
|
|
3804
|
+
(await readWorkflowGuardContext(input.cwd, { sessionId: input.sessionId, threadId: input.threadId }));
|
|
3805
|
+
const planning = await getActivePlanningSkill(input.cwd, input.sessionId, input.threadId, guardContext);
|
|
694
3806
|
|
|
695
3807
|
if (!planning) return;
|
|
696
3808
|
const message = planningPhaseBlockMessage(planning.skill);
|
|
697
3809
|
if (input.rawPaths.length === 0) throw new ToolError(message);
|
|
698
|
-
const blocked = await planningBlockedTargets(input.cwd, targets);
|
|
3810
|
+
const blocked = await planningBlockedTargets(input.cwd, targets, guardContext.sessionId);
|
|
699
3811
|
if (blocked.length > 0) throw new ToolError(message);
|
|
700
3812
|
}
|
|
701
3813
|
|
|
@@ -715,7 +3827,10 @@ export async function getWorkflowMutationDecision(
|
|
|
715
3827
|
command,
|
|
716
3828
|
};
|
|
717
3829
|
}
|
|
718
|
-
const
|
|
3830
|
+
const guardContext =
|
|
3831
|
+
input.guardContext ??
|
|
3832
|
+
(await readWorkflowGuardContext(input.cwd, { sessionId: input.sessionId, threadId: input.threadId }));
|
|
3833
|
+
const planning = await getActivePlanningSkill(input.cwd, input.sessionId, input.threadId, guardContext);
|
|
719
3834
|
if (!planning) {
|
|
720
3835
|
return { blocked: false, targets: [] };
|
|
721
3836
|
}
|
|
@@ -735,7 +3850,7 @@ export async function getWorkflowMutationDecision(
|
|
|
735
3850
|
// Neutral temp scratch (outside the project tree) stays writable so agents can
|
|
736
3851
|
// stage artifacts and feed their path to the sanctioned `skc ... --write` CLIs.
|
|
737
3852
|
// Read-only / `skc` bash extract no targets and fall through to allowed here.
|
|
738
|
-
const blockedTargets = await planningBlockedTargets(input.cwd, targets);
|
|
3853
|
+
const blockedTargets = await planningBlockedTargets(input.cwd, targets, guardContext.sessionId);
|
|
739
3854
|
if (blockedTargets.length === 0) {
|
|
740
3855
|
return { blocked: false, targets: targets.paths };
|
|
741
3856
|
}
|
|
@@ -743,7 +3858,9 @@ export async function getWorkflowMutationDecision(
|
|
|
743
3858
|
blocked: true,
|
|
744
3859
|
message,
|
|
745
3860
|
targets: targets.paths,
|
|
746
|
-
reason: allTargetsAllowlisted(input.cwd, targets)
|
|
3861
|
+
reason: allTargetsAllowlisted(input.cwd, targets, guardContext.sessionId)
|
|
3862
|
+
? "handoff-artifact-tool-target"
|
|
3863
|
+
: "phase-boundary",
|
|
747
3864
|
};
|
|
748
3865
|
}
|
|
749
3866
|
|