mayura 0.1.0-dev.0 → 1.0.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +152 -35
- package/docs/README.md +82 -0
- package/docs/ai-agents.md +73 -0
- package/docs/cli/dev.md +111 -0
- package/docs/cli/init.md +192 -0
- package/docs/cli/operations.md +235 -0
- package/docs/cli/overview.md +129 -0
- package/docs/cli/run.md +182 -0
- package/docs/concepts/agent.md +197 -0
- package/docs/concepts/costs-and-budgets.md +177 -0
- package/docs/concepts/outcomes.md +154 -0
- package/docs/concepts/permissions.md +155 -0
- package/docs/concepts/runtime.md +172 -0
- package/docs/concepts/tools.md +202 -0
- package/docs/concepts/workflows.md +134 -0
- package/docs/guides/approvals-and-human-input.md +278 -0
- package/docs/guides/artifacts.md +123 -0
- package/docs/guides/child-agents.md +158 -0
- package/docs/guides/code-mode.md +233 -0
- package/docs/guides/deployment.md +644 -0
- package/docs/guides/durable-workflows.md +463 -0
- package/docs/guides/guardrails.md +205 -0
- package/docs/guides/helpers.md +176 -0
- package/docs/guides/lifecycle-hooks.md +187 -0
- package/docs/guides/mcp.md +123 -0
- package/docs/guides/memory-and-context.md +293 -0
- package/docs/guides/model-providers.md +371 -0
- package/docs/guides/model-routing.md +138 -0
- package/docs/guides/observability.md +238 -0
- package/docs/guides/operator-console.md +140 -0
- package/docs/guides/react.md +276 -0
- package/docs/guides/sagas-and-loops.md +212 -0
- package/docs/guides/server-and-client.md +559 -0
- package/docs/guides/skills.md +152 -0
- package/docs/guides/storage.md +251 -0
- package/docs/guides/streaming.md +146 -0
- package/docs/guides/terminal.md +166 -0
- package/docs/guides/testing.md +220 -0
- package/docs/guides/vision.md +155 -0
- package/docs/guides/webhooks.md +172 -0
- package/docs/guides/workflow-composition.md +141 -0
- package/docs/guides/workflow-operations.md +269 -0
- package/docs/installation.md +90 -0
- package/docs/introduction.md +74 -0
- package/docs/project/credits.md +78 -0
- package/docs/project/security.md +178 -0
- package/docs/project/support.md +91 -0
- package/docs/project/versioning.md +122 -0
- package/docs/quickstart.md +190 -0
- package/docs/reference/entry-points.md +146 -0
- package/lib/adapter-code-docker/dist/index.d.ts +8 -1
- package/lib/adapter-code-docker/dist/index.d.ts.map +1 -1
- package/lib/adapter-code-docker/dist/index.js +64 -67
- package/lib/adapter-code-docker/dist/index.js.map +1 -1
- package/lib/adapter-code-docker/dist/options.d.ts +15 -0
- package/lib/adapter-code-docker/dist/options.d.ts.map +1 -0
- package/lib/adapter-code-docker/dist/options.js +56 -0
- package/lib/adapter-code-docker/dist/options.js.map +1 -0
- package/lib/adapter-code-docker/image/Dockerfile +4 -2
- package/lib/adapter-code-docker/package.json +1 -1
- package/lib/adapter-code-docker/src/index.ts +63 -65
- package/lib/adapter-code-docker/src/options.ts +51 -0
- package/lib/adapter-code-quickjs/dist/index.d.ts +16 -4
- package/lib/adapter-code-quickjs/dist/index.d.ts.map +1 -1
- package/lib/adapter-code-quickjs/dist/index.js +94 -50
- package/lib/adapter-code-quickjs/dist/index.js.map +1 -1
- package/lib/adapter-code-quickjs/dist/worker-command.d.ts +27 -0
- package/lib/adapter-code-quickjs/dist/worker-command.d.ts.map +1 -0
- package/lib/adapter-code-quickjs/dist/worker-command.js +66 -0
- package/lib/adapter-code-quickjs/dist/worker-command.js.map +1 -0
- package/lib/adapter-code-quickjs/dist/worker.js +421 -104
- package/lib/adapter-code-quickjs/dist/worker.js.map +1 -1
- package/lib/adapter-code-quickjs/package.json +1 -1
- package/lib/adapter-code-quickjs/src/index.ts +88 -44
- package/lib/adapter-code-quickjs/src/worker-command.ts +68 -0
- package/lib/adapter-code-quickjs/src/worker.ts +315 -89
- package/lib/adapter-mcp/package.json +1 -1
- package/lib/artifacts/dist/contracts.d.ts +6 -2
- package/lib/artifacts/dist/contracts.d.ts.map +1 -1
- package/lib/artifacts/dist/contracts.js.map +1 -1
- package/lib/artifacts/dist/index.d.ts +1 -0
- package/lib/artifacts/dist/index.d.ts.map +1 -1
- package/lib/artifacts/dist/index.js +1 -0
- package/lib/artifacts/dist/index.js.map +1 -1
- package/lib/artifacts/dist/local-store.d.ts.map +1 -1
- package/lib/artifacts/dist/local-store.js +4 -7
- package/lib/artifacts/dist/local-store.js.map +1 -1
- package/lib/artifacts/dist/media.d.ts +11 -0
- package/lib/artifacts/dist/media.d.ts.map +1 -0
- package/lib/artifacts/dist/media.js +18 -0
- package/lib/artifacts/dist/media.js.map +1 -0
- package/lib/artifacts/package.json +1 -1
- package/lib/artifacts/src/contracts.ts +6 -2
- package/lib/artifacts/src/index.ts +1 -0
- package/lib/artifacts/src/local-store.ts +5 -7
- package/lib/artifacts/src/media.ts +20 -0
- package/lib/cli/dist/agent-guide.d.ts +10 -0
- package/lib/cli/dist/agent-guide.d.ts.map +1 -0
- package/lib/cli/dist/agent-guide.js +48 -0
- package/lib/cli/dist/agent-guide.js.map +1 -0
- package/lib/cli/dist/application.d.ts +24 -0
- package/lib/cli/dist/application.d.ts.map +1 -1
- package/lib/cli/dist/application.js +21 -0
- package/lib/cli/dist/application.js.map +1 -1
- package/lib/cli/dist/bin.js +26 -6
- package/lib/cli/dist/bin.js.map +1 -1
- package/lib/cli/dist/dev.d.ts.map +1 -1
- package/lib/cli/dist/dev.js +7 -1
- package/lib/cli/dist/dev.js.map +1 -1
- package/lib/cli/dist/index.d.ts +3 -3
- package/lib/cli/dist/index.d.ts.map +1 -1
- package/lib/cli/dist/index.js +19 -9
- package/lib/cli/dist/index.js.map +1 -1
- package/lib/cli/dist/interactive.d.ts.map +1 -1
- package/lib/cli/dist/interactive.js +52 -11
- package/lib/cli/dist/interactive.js.map +1 -1
- package/lib/cli/dist/operations.d.ts +25 -2
- package/lib/cli/dist/operations.d.ts.map +1 -1
- package/lib/cli/dist/operations.js +125 -12
- package/lib/cli/dist/operations.js.map +1 -1
- package/lib/cli/dist/output.d.ts.map +1 -1
- package/lib/cli/dist/output.js +3 -0
- package/lib/cli/dist/output.js.map +1 -1
- package/lib/cli/dist/providers.d.ts +34 -4
- package/lib/cli/dist/providers.d.ts.map +1 -1
- package/lib/cli/dist/providers.js +26 -5
- package/lib/cli/dist/providers.js.map +1 -1
- package/lib/cli/package.json +1 -1
- package/lib/cli/src/agent-guide.ts +47 -0
- package/lib/cli/src/application.ts +24 -0
- package/lib/cli/src/bin.ts +22 -5
- package/lib/cli/src/dev.ts +5 -1
- package/lib/cli/src/index.ts +18 -10
- package/lib/cli/src/interactive.ts +44 -12
- package/lib/cli/src/operations.ts +82 -12
- package/lib/cli/src/output.ts +3 -0
- package/lib/cli/src/providers.ts +45 -10
- package/lib/cli/starters/approval-workflow/dot-env.example +11 -0
- package/lib/cli/starters/approval-workflow/package.json +1 -2
- package/lib/cli/starters/approval-workflow/src/config.ts +25 -7
- package/lib/cli/starters/approval-workflow/src/intake.ts +1 -2
- package/lib/cli/starters/approval-workflow/src/model.ts +11 -4
- package/lib/cli/starters/approval-workflow/src/workflow.ts +1 -2
- package/lib/cli/starters/cli-agent/README.md +121 -0
- package/lib/cli/starters/cli-agent/dot-env.example +37 -0
- package/lib/cli/starters/cli-agent/dot-github/workflows/ci.yml +13 -0
- package/lib/cli/starters/cli-agent/dot-gitignore +10 -0
- package/lib/cli/starters/cli-agent/mayura.project.json +15 -0
- package/lib/cli/starters/cli-agent/package.json +28 -0
- package/lib/cli/starters/cli-agent/skills/release-notes/SKILL.md +18 -0
- package/lib/cli/starters/cli-agent/skills/release-notes/references/example.md +12 -0
- package/lib/cli/starters/cli-agent/src/assistant.ts +124 -0
- package/lib/cli/starters/cli-agent/src/cli.ts +72 -0
- package/lib/cli/starters/cli-agent/src/config.ts +117 -0
- package/lib/cli/starters/cli-agent/src/model.ts +34 -0
- package/lib/cli/starters/cli-agent/src/workspace.ts +170 -0
- package/lib/cli/starters/cli-agent/test/assistant.test.ts +205 -0
- package/lib/cli/starters/cli-agent/tsconfig.json +20 -0
- package/lib/cli/starters/event-automation/README.md +4 -3
- package/lib/cli/starters/event-automation/dot-env.example +11 -0
- package/lib/cli/starters/event-automation/package.json +1 -2
- package/lib/cli/starters/event-automation/src/config.ts +25 -7
- package/lib/cli/starters/event-automation/src/ingress.ts +3 -5
- package/lib/cli/starters/event-automation/src/model.ts +11 -4
- package/lib/cli/starters/event-automation/src/send-sample.ts +1 -1
- package/lib/cli/starters/event-automation/src/tracker/main.ts +1 -1
- package/lib/cli/starters/event-automation/src/tracker/mcp-server.ts +1 -1
- package/lib/cli/starters/event-automation/src/tracker/tickets.ts +1 -1
- package/lib/cli/starters/event-automation/src/tracker-tools.ts +1 -1
- package/lib/cli/starters/event-automation/src/triage.ts +15 -22
- package/lib/cli/starters/event-automation/src/workflows.ts +1 -1
- package/lib/cli/starters/event-automation/test/automation.test.ts +3 -3
- package/lib/cli/starters/research-team/README.md +2 -2
- package/lib/cli/starters/research-team/dot-env.example +11 -0
- package/lib/cli/starters/research-team/package.json +1 -2
- package/lib/cli/starters/research-team/src/config.ts +25 -7
- package/lib/cli/starters/research-team/src/desk.ts +1 -2
- package/lib/cli/starters/research-team/src/library/index.ts +1 -2
- package/lib/cli/starters/research-team/src/model.ts +11 -4
- package/lib/cli/starters/research-team/src/services.ts +1 -1
- package/lib/cli/starters/research-team/src/team.ts +1 -2
- package/lib/cli/starters/research-team/src/workflow.ts +45 -59
- package/lib/cli/starters/support-agent/dot-env.example +11 -0
- package/lib/cli/starters/support-agent/package.json +1 -2
- package/lib/cli/starters/support-agent/src/assistant.ts +5 -5
- package/lib/cli/starters/support-agent/src/config.ts +25 -7
- package/lib/cli/starters/support-agent/src/guardrails.ts +3 -1
- package/lib/cli/starters/support-agent/src/model.ts +11 -4
- package/lib/cli/starters/support-agent/src/returns.ts +1 -2
- package/lib/cli/starters/support-agent/test/support.test.ts +25 -1
- package/lib/cli/templates/basic-agent.ts +1 -2
- package/lib/cli/templates/capability-policy.ts +1 -2
- package/lib/cli/templates/code-mode-workflow.ts +1 -1
- package/lib/cli/templates/durable-approval.ts +1 -1
- package/lib/cli/templates/parallel-research.ts +1 -2
- package/lib/cli/templates/typed-tool-runner.ts +1 -2
- package/lib/client/dist/forms.d.ts.map +1 -1
- package/lib/client/dist/forms.js +3 -4
- package/lib/client/dist/forms.js.map +1 -1
- package/lib/client/dist/headless.d.ts +3 -1
- package/lib/client/dist/headless.d.ts.map +1 -1
- package/lib/client/dist/headless.js +10 -6
- package/lib/client/dist/headless.js.map +1 -1
- package/lib/client/dist/index.d.ts +95 -6
- package/lib/client/dist/index.d.ts.map +1 -1
- package/lib/client/dist/index.js +397 -124
- package/lib/client/dist/index.js.map +1 -1
- package/lib/client/dist/workflows.d.ts +1 -1
- package/lib/client/dist/workflows.d.ts.map +1 -1
- package/lib/client/dist/workflows.js +7 -6
- package/lib/client/dist/workflows.js.map +1 -1
- package/lib/client/package.json +1 -1
- package/lib/client/src/forms.ts +3 -4
- package/lib/client/src/headless.ts +13 -7
- package/lib/client/src/index.ts +344 -74
- package/lib/client/src/workflows.ts +8 -7
- package/lib/client-react/package.json +1 -1
- package/lib/code-mode/dist/index.d.ts +32 -1
- package/lib/code-mode/dist/index.d.ts.map +1 -1
- package/lib/code-mode/dist/index.js +289 -221
- package/lib/code-mode/dist/index.js.map +1 -1
- package/lib/code-mode/package.json +1 -1
- package/lib/code-mode/src/index.ts +288 -184
- package/lib/code-mode-workflows/package.json +1 -1
- package/lib/context/package.json +1 -1
- package/lib/core/dist/budget.d.ts.map +1 -1
- package/lib/core/dist/budget.js +17 -2
- package/lib/core/dist/budget.js.map +1 -1
- package/lib/core/dist/contracts.d.ts +57 -0
- package/lib/core/dist/contracts.d.ts.map +1 -1
- package/lib/core/dist/contracts.js +36 -0
- package/lib/core/dist/contracts.js.map +1 -1
- package/lib/core/dist/destination.d.ts +12 -0
- package/lib/core/dist/destination.d.ts.map +1 -0
- package/lib/core/dist/destination.js +37 -0
- package/lib/core/dist/destination.js.map +1 -0
- package/lib/core/dist/event-stream.d.ts +1 -1
- package/lib/core/dist/event-stream.d.ts.map +1 -1
- package/lib/core/dist/event-stream.js +7 -0
- package/lib/core/dist/event-stream.js.map +1 -1
- package/lib/core/dist/host.d.ts +3 -0
- package/lib/core/dist/host.d.ts.map +1 -1
- package/lib/core/dist/host.js +3 -0
- package/lib/core/dist/host.js.map +1 -1
- package/lib/core/dist/index.d.ts +2 -0
- package/lib/core/dist/index.d.ts.map +1 -1
- package/lib/core/dist/index.js +2 -0
- package/lib/core/dist/index.js.map +1 -1
- package/lib/core/dist/media.d.ts +98 -0
- package/lib/core/dist/media.d.ts.map +1 -0
- package/lib/core/dist/media.js +227 -0
- package/lib/core/dist/media.js.map +1 -0
- package/lib/core/dist/model-schema.d.ts +37 -0
- package/lib/core/dist/model-schema.d.ts.map +1 -0
- package/lib/core/dist/model-schema.js +154 -0
- package/lib/core/dist/model-schema.js.map +1 -0
- package/lib/core/package.json +1 -1
- package/lib/core/src/budget.ts +17 -2
- package/lib/core/src/contracts.ts +71 -3
- package/lib/core/src/destination.ts +33 -0
- package/lib/core/src/event-stream.ts +5 -1
- package/lib/core/src/host.ts +3 -0
- package/lib/core/src/index.ts +2 -0
- package/lib/core/src/media.ts +228 -0
- package/lib/core/src/model-schema.ts +129 -0
- package/lib/exporter-otlp/dist/otlp-http-json.js +1 -1
- package/lib/exporter-otlp/dist/otlp-http-json.js.map +1 -1
- package/lib/exporter-otlp/dist/signals.js +2 -2
- package/lib/exporter-otlp/dist/signals.js.map +1 -1
- package/lib/exporter-otlp/package.json +1 -1
- package/lib/exporter-otlp/src/otlp-http-json.ts +1 -1
- package/lib/exporter-otlp/src/signals.ts +2 -2
- package/lib/guardrails/package.json +1 -1
- package/lib/helpers/package.json +1 -1
- package/lib/memory/dist/index.js +1 -1
- package/lib/memory/dist/index.js.map +1 -1
- package/lib/memory/dist/native.d.ts.map +1 -1
- package/lib/memory/dist/native.js +4 -3
- package/lib/memory/dist/native.js.map +1 -1
- package/lib/memory/package.json +1 -1
- package/lib/memory/src/index.ts +1 -1
- package/lib/memory/src/native.ts +4 -3
- package/lib/memory-remote/package.json +1 -1
- package/lib/observability/package.json +1 -1
- package/lib/provider-anthropic/dist/index.d.ts +36 -3
- package/lib/provider-anthropic/dist/index.d.ts.map +1 -1
- package/lib/provider-anthropic/dist/index.js +128 -78
- package/lib/provider-anthropic/dist/index.js.map +1 -1
- package/lib/provider-anthropic/package.json +1 -1
- package/lib/provider-anthropic/src/index.ts +152 -76
- package/lib/provider-openai/dist/index.d.ts +71 -4
- package/lib/provider-openai/dist/index.d.ts.map +1 -1
- package/lib/provider-openai/dist/index.js +259 -96
- package/lib/provider-openai/dist/index.js.map +1 -1
- package/lib/provider-openai/package.json +1 -1
- package/lib/provider-openai/src/index.ts +282 -84
- package/lib/runtime/dist/agent.d.ts +18 -1
- package/lib/runtime/dist/agent.d.ts.map +1 -1
- package/lib/runtime/dist/agent.js +59 -3
- package/lib/runtime/dist/agent.js.map +1 -1
- package/lib/runtime/dist/composition.d.ts.map +1 -1
- package/lib/runtime/dist/composition.js +2 -1
- package/lib/runtime/dist/composition.js.map +1 -1
- package/lib/runtime/dist/hooks.d.ts +15 -3
- package/lib/runtime/dist/hooks.d.ts.map +1 -1
- package/lib/runtime/dist/hooks.js.map +1 -1
- package/lib/runtime/dist/index.d.ts +1 -1
- package/lib/runtime/dist/index.d.ts.map +1 -1
- package/lib/runtime/dist/index.js.map +1 -1
- package/lib/runtime/dist/response.d.ts +7 -1
- package/lib/runtime/dist/response.d.ts.map +1 -1
- package/lib/runtime/dist/response.js +23 -2
- package/lib/runtime/dist/response.js.map +1 -1
- package/lib/runtime/dist/router.d.ts +10 -3
- package/lib/runtime/dist/router.d.ts.map +1 -1
- package/lib/runtime/dist/router.js +45 -8
- package/lib/runtime/dist/router.js.map +1 -1
- package/lib/runtime/dist/runtime.d.ts +9 -1
- package/lib/runtime/dist/runtime.d.ts.map +1 -1
- package/lib/runtime/dist/runtime.js +50 -22
- package/lib/runtime/dist/runtime.js.map +1 -1
- package/lib/runtime/package.json +1 -1
- package/lib/runtime/src/agent.ts +69 -3
- package/lib/runtime/src/composition.ts +2 -1
- package/lib/runtime/src/hooks.ts +10 -4
- package/lib/runtime/src/index.ts +1 -1
- package/lib/runtime/src/response.ts +20 -2
- package/lib/runtime/src/router.ts +43 -10
- package/lib/runtime/src/runtime.ts +58 -27
- package/lib/sdk/dist/index.d.ts +9 -1
- package/lib/sdk/dist/index.d.ts.map +1 -1
- package/lib/sdk/dist/index.js +9 -1
- package/lib/sdk/dist/index.js.map +1 -1
- package/lib/sdk/package.json +1 -1
- package/lib/sdk/src/index.ts +9 -1
- package/lib/server/dist/index.d.ts +201 -3
- package/lib/server/dist/index.d.ts.map +1 -1
- package/lib/server/dist/index.js +701 -149
- package/lib/server/dist/index.js.map +1 -1
- package/lib/server/dist/inspector-bundle.d.ts +1 -1
- package/lib/server/dist/inspector-bundle.d.ts.map +1 -1
- package/lib/server/dist/inspector-bundle.js +4 -4
- package/lib/server/dist/inspector-bundle.js.map +1 -1
- package/lib/server/package.json +1 -1
- package/lib/server/src/index.ts +611 -135
- package/lib/server/src/inspector-bundle.ts +4 -4
- package/lib/server-node/dist/hardening.d.ts +1 -1
- package/lib/server-node/dist/hardening.d.ts.map +1 -1
- package/lib/server-node/dist/hardening.js +4 -2
- package/lib/server-node/dist/hardening.js.map +1 -1
- package/lib/server-node/dist/index.d.ts +2 -1
- package/lib/server-node/dist/index.d.ts.map +1 -1
- package/lib/server-node/dist/index.js.map +1 -1
- package/lib/server-node/dist/probe.js +2 -2
- package/lib/server-node/dist/probe.js.map +1 -1
- package/lib/server-node/dist/production.d.ts +8 -1
- package/lib/server-node/dist/production.d.ts.map +1 -1
- package/lib/server-node/dist/production.js +15 -2
- package/lib/server-node/dist/production.js.map +1 -1
- package/lib/server-node/package.json +1 -1
- package/lib/server-node/src/hardening.ts +5 -3
- package/lib/server-node/src/index.ts +2 -1
- package/lib/server-node/src/probe.ts +2 -2
- package/lib/server-node/src/production.ts +23 -3
- package/lib/skills/dist/index.d.ts +81 -0
- package/lib/skills/dist/index.d.ts.map +1 -0
- package/lib/skills/dist/index.js +311 -0
- package/lib/skills/dist/index.js.map +1 -0
- package/lib/skills/package.json +5 -0
- package/lib/skills/src/index.ts +260 -0
- package/lib/storage/dist/index.d.ts +1 -1
- package/lib/storage/dist/index.d.ts.map +1 -1
- package/lib/storage/dist/index.js.map +1 -1
- package/lib/storage/package.json +1 -1
- package/lib/storage/src/index.ts +1 -1
- package/lib/storage-contracts/dist/contracts.d.ts +12 -5
- package/lib/storage-contracts/dist/contracts.d.ts.map +1 -1
- package/lib/storage-contracts/dist/contracts.js +24 -6
- package/lib/storage-contracts/dist/contracts.js.map +1 -1
- package/lib/storage-contracts/dist/index.d.ts +2 -0
- package/lib/storage-contracts/dist/index.d.ts.map +1 -1
- package/lib/storage-contracts/dist/index.js +2 -0
- package/lib/storage-contracts/dist/index.js.map +1 -1
- package/lib/storage-contracts/dist/memory-contracts.js +1 -1
- package/lib/storage-contracts/dist/memory-contracts.js.map +1 -1
- package/lib/storage-contracts/dist/run-records.d.ts +100 -0
- package/lib/storage-contracts/dist/run-records.d.ts.map +1 -0
- package/lib/storage-contracts/dist/run-records.js +464 -0
- package/lib/storage-contracts/dist/run-records.js.map +1 -0
- package/lib/storage-contracts/dist/schema-digest.d.ts +17 -0
- package/lib/storage-contracts/dist/schema-digest.d.ts.map +1 -0
- package/lib/storage-contracts/dist/schema-digest.js +94 -0
- package/lib/storage-contracts/dist/schema-digest.js.map +1 -0
- package/lib/storage-contracts/dist/submission-journal.js +1 -1
- package/lib/storage-contracts/dist/submission-journal.js.map +1 -1
- package/lib/storage-contracts/dist/workflow-format5.d.ts +30 -2
- package/lib/storage-contracts/dist/workflow-format5.d.ts.map +1 -1
- package/lib/storage-contracts/dist/workflow-format5.js +57 -5
- package/lib/storage-contracts/dist/workflow-format5.js.map +1 -1
- package/lib/storage-contracts/package.json +1 -1
- package/lib/storage-contracts/src/contracts.ts +29 -5
- package/lib/storage-contracts/src/index.ts +2 -0
- package/lib/storage-contracts/src/memory-contracts.ts +1 -1
- package/lib/storage-contracts/src/run-records.ts +365 -0
- package/lib/storage-contracts/src/schema-digest.ts +71 -0
- package/lib/storage-contracts/src/submission-journal.ts +1 -1
- package/lib/storage-contracts/src/workflow-format5.ts +70 -6
- package/lib/storage-postgres/dist/index.d.ts +1 -1
- package/lib/storage-postgres/dist/index.d.ts.map +1 -1
- package/lib/storage-postgres/dist/index.js.map +1 -1
- package/lib/storage-postgres/dist/postgres.d.ts +15 -0
- package/lib/storage-postgres/dist/postgres.d.ts.map +1 -1
- package/lib/storage-postgres/dist/postgres.js +18 -7
- package/lib/storage-postgres/dist/postgres.js.map +1 -1
- package/lib/storage-postgres/package.json +1 -1
- package/lib/storage-postgres/src/index.ts +1 -1
- package/lib/storage-postgres/src/postgres.ts +34 -8
- package/lib/storage-sql/dist/aggregate-session.js +1 -1
- package/lib/storage-sql/dist/aggregate-session.js.map +1 -1
- package/lib/storage-sql/dist/scheduled-database.js +1 -1
- package/lib/storage-sql/dist/scheduled-database.js.map +1 -1
- package/lib/storage-sql/dist/workflow-tree-validation.js +1 -1
- package/lib/storage-sql/dist/workflow-tree-validation.js.map +1 -1
- package/lib/storage-sql/package.json +1 -1
- package/lib/storage-sql/src/aggregate-session.ts +1 -1
- package/lib/storage-sql/src/scheduled-database.ts +1 -1
- package/lib/storage-sql/src/workflow-tree-validation.ts +1 -1
- package/lib/storage-sqlite/dist/sqlite-database.js +4 -4
- package/lib/storage-sqlite/dist/sqlite-database.js.map +1 -1
- package/lib/storage-sqlite/dist/sqlite-worker.js +2 -2
- package/lib/storage-sqlite/dist/sqlite-worker.js.map +1 -1
- package/lib/storage-sqlite/dist/sqlite.js +1 -1
- package/lib/storage-sqlite/dist/sqlite.js.map +1 -1
- package/lib/storage-sqlite/package.json +1 -1
- package/lib/storage-sqlite/src/sqlite-database.ts +4 -4
- package/lib/storage-sqlite/src/sqlite-worker.ts +2 -2
- package/lib/storage-sqlite/src/sqlite.ts +1 -1
- package/lib/terminal/dist/index.d.ts +92 -0
- package/lib/terminal/dist/index.d.ts.map +1 -0
- package/lib/terminal/dist/index.js +397 -0
- package/lib/terminal/dist/index.js.map +1 -0
- package/lib/terminal/package.json +5 -0
- package/lib/terminal/src/index.ts +273 -0
- package/lib/testing/dist/index.d.ts +44 -1
- package/lib/testing/dist/index.d.ts.map +1 -1
- package/lib/testing/dist/index.js +63 -10
- package/lib/testing/dist/index.js.map +1 -1
- package/lib/testing/package.json +1 -1
- package/lib/testing/src/index.ts +83 -10
- package/lib/tools/dist/index.d.ts +32 -4
- package/lib/tools/dist/index.d.ts.map +1 -1
- package/lib/tools/dist/index.js +64 -11
- package/lib/tools/dist/index.js.map +1 -1
- package/lib/tools/package.json +1 -1
- package/lib/tools/src/index.ts +74 -13
- package/lib/workflows/dist/abandoned.d.ts +15 -0
- package/lib/workflows/dist/abandoned.d.ts.map +1 -0
- package/lib/workflows/dist/abandoned.js +33 -0
- package/lib/workflows/dist/abandoned.js.map +1 -0
- package/lib/workflows/dist/agent-step.d.ts +83 -0
- package/lib/workflows/dist/agent-step.d.ts.map +1 -0
- package/lib/workflows/dist/agent-step.js +161 -0
- package/lib/workflows/dist/agent-step.js.map +1 -0
- package/lib/workflows/dist/children-runtime.js +8 -8
- package/lib/workflows/dist/children-runtime.js.map +1 -1
- package/lib/workflows/dist/composite-fleet.js +2 -2
- package/lib/workflows/dist/composite-fleet.js.map +1 -1
- package/lib/workflows/dist/composite-host.d.ts.map +1 -1
- package/lib/workflows/dist/composite-host.js +26 -2
- package/lib/workflows/dist/composite-host.js.map +1 -1
- package/lib/workflows/dist/hook-relay.js +2 -2
- package/lib/workflows/dist/hook-relay.js.map +1 -1
- package/lib/workflows/dist/index.d.ts +1 -1
- package/lib/workflows/dist/index.d.ts.map +1 -1
- package/lib/workflows/dist/index.js.map +1 -1
- package/lib/workflows/dist/leadership.js +3 -3
- package/lib/workflows/dist/leadership.js.map +1 -1
- package/lib/workflows/dist/lifecycle-definition.d.ts +26 -4
- package/lib/workflows/dist/lifecycle-definition.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-definition.js +31 -6
- package/lib/workflows/dist/lifecycle-definition.js.map +1 -1
- package/lib/workflows/dist/lifecycle-fleet.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-fleet.js +9 -11
- package/lib/workflows/dist/lifecycle-fleet.js.map +1 -1
- package/lib/workflows/dist/lifecycle-host.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-host.js +26 -2
- package/lib/workflows/dist/lifecycle-host.js.map +1 -1
- package/lib/workflows/dist/lifecycle-human-transport.d.ts +22 -2
- package/lib/workflows/dist/lifecycle-human-transport.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-human-transport.js +115 -33
- package/lib/workflows/dist/lifecycle-human-transport.js.map +1 -1
- package/lib/workflows/dist/lifecycle-runtime.d.ts +62 -1
- package/lib/workflows/dist/lifecycle-runtime.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-runtime.js +268 -64
- package/lib/workflows/dist/lifecycle-runtime.js.map +1 -1
- package/lib/workflows/dist/lifecycle.d.ts +6 -4
- package/lib/workflows/dist/lifecycle.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle.js +2 -0
- package/lib/workflows/dist/lifecycle.js.map +1 -1
- package/lib/workflows/dist/loop-runtime.d.ts.map +1 -1
- package/lib/workflows/dist/loop-runtime.js +38 -26
- package/lib/workflows/dist/loop-runtime.js.map +1 -1
- package/lib/workflows/dist/migration.d.ts +1 -1
- package/lib/workflows/dist/migration.d.ts.map +1 -1
- package/lib/workflows/dist/migration.js +3 -3
- package/lib/workflows/dist/migration.js.map +1 -1
- package/lib/workflows/dist/operator-transports.d.ts +24 -2
- package/lib/workflows/dist/operator-transports.d.ts.map +1 -1
- package/lib/workflows/dist/operator-transports.js +49 -3
- package/lib/workflows/dist/operator-transports.js.map +1 -1
- package/lib/workflows/dist/runtime.d.ts.map +1 -1
- package/lib/workflows/dist/runtime.js +34 -22
- package/lib/workflows/dist/runtime.js.map +1 -1
- package/lib/workflows/dist/saga-runtime.d.ts.map +1 -1
- package/lib/workflows/dist/saga-runtime.js +44 -30
- package/lib/workflows/dist/saga-runtime.js.map +1 -1
- package/lib/workflows/dist/scheduled-helpers.d.ts.map +1 -1
- package/lib/workflows/dist/scheduled-helpers.js +3 -3
- package/lib/workflows/dist/scheduled-helpers.js.map +1 -1
- package/lib/workflows/dist/storage-failure.d.ts +16 -0
- package/lib/workflows/dist/storage-failure.d.ts.map +1 -0
- package/lib/workflows/dist/storage-failure.js +38 -0
- package/lib/workflows/dist/storage-failure.js.map +1 -0
- package/lib/workflows/dist/sweep-position.d.ts +22 -0
- package/lib/workflows/dist/sweep-position.d.ts.map +1 -0
- package/lib/workflows/dist/sweep-position.js +45 -0
- package/lib/workflows/dist/sweep-position.js.map +1 -0
- package/lib/workflows/dist/traces.js +2 -2
- package/lib/workflows/dist/traces.js.map +1 -1
- package/lib/workflows/dist/worker.d.ts +31 -0
- package/lib/workflows/dist/worker.d.ts.map +1 -1
- package/lib/workflows/dist/worker.js +94 -0
- package/lib/workflows/dist/worker.js.map +1 -1
- package/lib/workflows/package.json +1 -1
- package/lib/workflows/src/abandoned.ts +32 -0
- package/lib/workflows/src/agent-step.ts +199 -0
- package/lib/workflows/src/children-runtime.ts +8 -8
- package/lib/workflows/src/composite-fleet.ts +2 -2
- package/lib/workflows/src/composite-host.ts +21 -3
- package/lib/workflows/src/hook-relay.ts +2 -2
- package/lib/workflows/src/index.ts +2 -1
- package/lib/workflows/src/leadership.ts +3 -3
- package/lib/workflows/src/lifecycle-definition.ts +50 -9
- package/lib/workflows/src/lifecycle-fleet.ts +7 -8
- package/lib/workflows/src/lifecycle-host.ts +21 -5
- package/lib/workflows/src/lifecycle-human-transport.ts +110 -26
- package/lib/workflows/src/lifecycle-runtime.ts +270 -60
- package/lib/workflows/src/lifecycle.ts +7 -0
- package/lib/workflows/src/loop-runtime.ts +34 -25
- package/lib/workflows/src/migration.ts +2 -2
- package/lib/workflows/src/operator-transports.ts +48 -4
- package/lib/workflows/src/runtime.ts +28 -22
- package/lib/workflows/src/saga-runtime.ts +38 -28
- package/lib/workflows/src/scheduled-helpers.ts +3 -3
- package/lib/workflows/src/storage-failure.ts +37 -0
- package/lib/workflows/src/sweep-position.ts +52 -0
- package/lib/workflows/src/traces.ts +2 -2
- package/lib/workflows/src/worker.ts +79 -1
- package/lib/workstream/dist/humans.d.ts +7 -3
- package/lib/workstream/dist/humans.d.ts.map +1 -1
- package/lib/workstream/dist/humans.js +13 -2
- package/lib/workstream/dist/humans.js.map +1 -1
- package/lib/workstream/dist/index.js +2 -2
- package/lib/workstream/dist/index.js.map +1 -1
- package/lib/workstream/dist/timers.js +2 -2
- package/lib/workstream/dist/timers.js.map +1 -1
- package/lib/workstream/dist/webhooks.d.ts +6 -2
- package/lib/workstream/dist/webhooks.d.ts.map +1 -1
- package/lib/workstream/dist/webhooks.js +17 -7
- package/lib/workstream/dist/webhooks.js.map +1 -1
- package/lib/workstream/package.json +1 -1
- package/lib/workstream/src/humans.ts +15 -5
- package/lib/workstream/src/index.ts +2 -2
- package/lib/workstream/src/timers.ts +2 -2
- package/lib/workstream/src/webhooks.ts +21 -8
- package/llms-full.txt +9766 -0
- package/llms.txt +92 -0
- package/package.json +18 -6
|
@@ -3,7 +3,7 @@ import type { Socket } from 'node:net';
|
|
|
3
3
|
import type { AgentServerOptions } from '../../server/dist/index.js';
|
|
4
4
|
export declare const unavailable: () => Response;
|
|
5
5
|
/** Snapshot and freeze every trusted option before a socket opens; no mutable caller reference is retained. */
|
|
6
|
-
export declare function snapshotSettings(options: Omit<AgentServerOptions, 'publicOrigin'>): Omit<AgentServerOptions, 'publicOrigin'>;
|
|
6
|
+
export declare function snapshotSettings(options: Omit<AgentServerOptions, 'publicOrigin' | 'mounted'>): Omit<AgentServerOptions, 'publicOrigin' | 'mounted'>;
|
|
7
7
|
/** Apply the shared socket, header and timeout bounds and track sockets for a bounded shutdown. */
|
|
8
8
|
export declare function hardenServer(server: Server, maxConnections: number): Set<Socket>;
|
|
9
9
|
export declare const serverTimeouts: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hardening.d.ts","sourceRoot":"","sources":["../src/hardening.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEzD,eAAO,MAAM,WAAW,QAAO,
|
|
1
|
+
{"version":3,"file":"hardening.d.ts","sourceRoot":"","sources":["../src/hardening.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEzD,eAAO,MAAM,WAAW,QAAO,QAG7B,CAAC;AAEH,+GAA+G;AAC/G,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,IAAI,CAAC,kBAAkB,EAAE,cAAc,GAAG,SAAS,CAAC,GAAG,IAAI,CAAC,kBAAkB,EAAE,cAAc,GAAG,SAAS,CAAC,CAuBpJ;AAED,mGAAmG;AACnG,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAgBhF;AAED,eAAO,MAAM,cAAc;aAAK,aAAa,EAAE,KAAM;aAAE,cAAc,EAAE,IAAK;aAAE,cAAc,EAAE,KAAM;aAClG,gBAAgB,EAAE,IAAK;aAAE,2BAA2B,EAAE,IAAK;CAAW,CAAC;AAEzE,wBAAgB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAMrG;AAED,mGAAmG;AACnG,wBAAgB,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAchJ"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
export const unavailable = () => new Response(
|
|
2
|
-
|
|
1
|
+
export const unavailable = () => new Response(JSON.stringify({ error: { code: 'HOST_UNAVAILABLE', retryAfterMs: 1_000,
|
|
2
|
+
message: 'The server is starting, stopping or could not handle the request. Retry shortly, against another replica if possible.' } }), {
|
|
3
|
+
status: 503, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Retry-After': '1' },
|
|
3
4
|
});
|
|
4
5
|
/** Snapshot and freeze every trusted option before a socket opens; no mutable caller reference is retained. */
|
|
5
6
|
export function snapshotSettings(options) {
|
|
@@ -21,6 +22,7 @@ export function snapshotSettings(options) {
|
|
|
21
22
|
...(options.workflowFleet === undefined ? {} : { workflowFleet: options.workflowFleet }),
|
|
22
23
|
...(options.workflowMigrations === undefined ? {} : { workflowMigrations: options.workflowMigrations }),
|
|
23
24
|
...(options.submissionJournal === undefined ? {} : { submissionJournal: options.submissionJournal }),
|
|
25
|
+
...(options.runRecords === undefined ? {} : { runRecords: options.runRecords }),
|
|
24
26
|
...(options.allowedOrigins === undefined ? {} : { allowedOrigins: Object.freeze([...options.allowedOrigins]) }),
|
|
25
27
|
...(options.limits === undefined ? {} : { limits: Object.freeze({ ...options.limits }) }),
|
|
26
28
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hardening.js","sourceRoot":"","sources":["../src/hardening.ts"],"names":[],"mappings":"AAIA,MAAM,CAAC,MAAM,WAAW,GAAG,GAAa,EAAE,CAAC,IAAI,QAAQ,CAAC,uCAAuC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AE,GAAG,EAAE;YAChG,YAAY,CAAC,KAAK,CAAC,CAAC;YAAC,KAAK,MAAM,MAAM,IAAI,OAAO;gBAAE,MAAM,CAAC,OAAO,EAAE,CAAC;YACpE,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;QAC7B,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { Server } from 'node:http';\nimport type { Socket } from 'node:net';\nimport type { AgentServerOptions } from '@mayura/server';\n\nexport const unavailable = (): Response => new Response('{\"error\":{\"code\":\"HOST_UNAVAILABLE\"}}', {\n status: 503, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },\n});\n\n/** Snapshot and freeze every trusted option before a socket opens; no mutable caller reference is retained. */\nexport function snapshotSettings(options: Omit<AgentServerOptions, 'publicOrigin'>): Omit<AgentServerOptions, 'publicOrigin'> {\n return {\n agents: Object.freeze(options.agents.map(config => Object.freeze({ agent: config.agent,\n permissions: Object.freeze({ allow: Object.freeze([...config.permissions.allow]) }),\n ...(config.limits === undefined ? {} : { limits: Object.freeze({ ...config.limits }) }),\n }))), authenticate: options.authenticate,\n ...(options.publicLiveness === undefined ? {} : { publicLiveness: options.publicLiveness }),\n ...(options.inspector === undefined ? {} : { inspector: options.inspector }),\n ...(options.healthChecks === undefined ? {} : { healthChecks: Object.freeze(options.healthChecks.map(check => Object.freeze({ id: check.id, check: check.check }))) }),\n ...(options.humanRequests === undefined ? {} : { humanRequests: options.humanRequests }),\n ...(options.workflowViews === undefined ? {} : { workflowViews: options.workflowViews }),\n ...(options.workflowIndex === undefined ? {} : { workflowIndex: options.workflowIndex }),\n ...(options.workflowControls === undefined ? {} : { workflowControls: options.workflowControls }),\n ...(options.workflowSignals === undefined ? {} : { workflowSignals: options.workflowSignals }),\n ...(options.workflowResumes === undefined ? {} : { workflowResumes: options.workflowResumes }),\n ...(options.workflowPauses === undefined ? {} : { workflowPauses: options.workflowPauses }),\n ...(options.workflowFleet === undefined ? {} : { workflowFleet: options.workflowFleet }),\n ...(options.workflowMigrations === undefined ? {} : { workflowMigrations: options.workflowMigrations }),\n ...(options.submissionJournal === undefined ? {} : { submissionJournal: options.submissionJournal }),\n ...(options.allowedOrigins === undefined ? {} : { allowedOrigins: Object.freeze([...options.allowedOrigins]) }),\n ...(options.limits === undefined ? {} : { limits: Object.freeze({ ...options.limits }) }),\n };\n}\n\n/** Apply the shared socket, header and timeout bounds and track sockets for a bounded shutdown. */\nexport function hardenServer(server: Server, maxConnections: number): Set<Socket> {\n server.maxConnections = maxConnections;\n const sockets = new Set<Socket>();\n // TLS servers report the encrypted socket through 'secureConnection'; plain servers through 'connection'.\n const track = (socket: Socket): void => { sockets.add(socket); socket.once('close', () => { sockets.delete(socket); }); };\n server.on('connection', track); server.on('secureConnection', track);\n server.maxRequestsPerSocket = 100;\n server.setTimeout(35_000, socket => socket.destroy());\n server.on('upgrade', (_request, socket) => { socket.end('HTTP/1.1 426 Upgrade Required\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n'); });\n server.on('connect', (_request, socket) => { socket.destroy(); });\n server.on('clientError', (error, socket) => {\n const status = (error as NodeJS.ErrnoException).code === 'HPE_HEADER_OVERFLOW' ? '431 Request Header Fields Too Large' : '400 Bad Request';\n if (socket.writable) socket.end(`HTTP/1.1 ${status}\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n`);\n else socket.destroy();\n });\n return sockets;\n}\n\nexport const serverTimeouts = { maxHeaderSize: 16_384, headersTimeout: 5_000, requestTimeout: 15_000,\n keepAliveTimeout: 5_000, connectionsCheckingInterval: 1_000 } as const;\n\nexport function listen(server: Server, port: number, hostname: string, failure: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const failed = (): void => { server.removeListener('listening', ready); reject(new Error(failure)); };\n const ready = (): void => { server.removeListener('error', failed); resolve(); };\n server.once('error', failed); server.once('listening', ready); server.listen(port, hostname);\n });\n}\n\n/** Stop accepting, then close the protocol; the grace timer bounds stale and half-open sockets. */\nexport function shutdown(server: Server, sockets: Set<Socket>, grace: number, closeProtocol: () => Promise<void>, failure: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n server.closeAllConnections();\n // Node excludes upgraded sockets from closeAllConnections, including rejected half-open peers.\n for (const socket of sockets) socket.destroy();\n }, grace);\n const stopped = new Promise<void>(done => { server.close(() => done()); });\n server.closeIdleConnections();\n void Promise.all([stopped, closeProtocol()]).then(() => { clearTimeout(timer); resolve(); }, () => {\n clearTimeout(timer); for (const socket of sockets) socket.destroy();\n reject(new Error(failure));\n });\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"hardening.js","sourceRoot":"","sources":["../src/hardening.ts"],"names":[],"mappings":"AAIA,MAAM,CAAC,MAAM,WAAW,GAAG,GAAa,EAAE,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,kBAAkB,EAAE,YAAY,EAAE,KAAK;QAC7H,OAAO,EAAE,uHAAuH,EAAE,EAAE,CAAC,EAAE;IACvI,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE,eAAe,EAAE,UAAU,EAAE,wBAAwB,EAAE,SAAS,EAAE,aAAa,EAAE,GAAG,EAAE;CACnJ,CAAC,CAAC;AAEH,+GAA+G;AAC/G,MAAM,UAAU,gBAAgB,CAAC,OAA6D;IAC5F,OAAO;QACL,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK;YACpF,WAAW,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,MAAM,CAAC,WAAW,CAAC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AAC,CAAC;QAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IAC/F,CAAC,CAAC,CAAC;AACL,CAAC;AAED,mGAAmG;AACnG,MAAM,UAAU,QAAQ,CAAC,MAAc,EAAE,OAAoB,EAAE,KAAa,EAAE,aAAkC,EAAE,OAAe;IAC/H,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QAC3C,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;YAC5B,MAAM,CAAC,mBAAmB,EAAE,CAAC;YAC7B,+FAA+F;YAC/F,KAAK,MAAM,MAAM,IAAI,OAAO;gBAAE,MAAM,CAAC,OAAO,EAAE,CAAC;QACjD,CAAC,EAAE,KAAK,CAAC,CAAC;QACV,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,IAAI,CAAC,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3E,MAAM,CAAC,oBAAoB,EAAE,CAAC;QAC9B,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE;YAChG,YAAY,CAAC,KAAK,CAAC,CAAC;YAAC,KAAK,MAAM,MAAM,IAAI,OAAO;gBAAE,MAAM,CAAC,OAAO,EAAE,CAAC;YACpE,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;QAC7B,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { Server } from 'node:http';\nimport type { Socket } from 'node:net';\nimport type { AgentServerOptions } from '@mayura/server';\n\nexport const unavailable = (): Response => new Response(JSON.stringify({ error: { code: 'HOST_UNAVAILABLE', retryAfterMs: 1_000,\n message: 'The server is starting, stopping or could not handle the request. Retry shortly, against another replica if possible.' } }), {\n status: 503, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Retry-After': '1' },\n});\n\n/** Snapshot and freeze every trusted option before a socket opens; no mutable caller reference is retained. */\nexport function snapshotSettings(options: Omit<AgentServerOptions, 'publicOrigin' | 'mounted'>): Omit<AgentServerOptions, 'publicOrigin' | 'mounted'> {\n return {\n agents: Object.freeze(options.agents.map(config => Object.freeze({ agent: config.agent,\n permissions: Object.freeze({ allow: Object.freeze([...config.permissions.allow]) }),\n ...(config.limits === undefined ? {} : { limits: Object.freeze({ ...config.limits }) }),\n }))), authenticate: options.authenticate,\n ...(options.publicLiveness === undefined ? {} : { publicLiveness: options.publicLiveness }),\n ...(options.inspector === undefined ? {} : { inspector: options.inspector }),\n ...(options.healthChecks === undefined ? {} : { healthChecks: Object.freeze(options.healthChecks.map(check => Object.freeze({ id: check.id, check: check.check }))) }),\n ...(options.humanRequests === undefined ? {} : { humanRequests: options.humanRequests }),\n ...(options.workflowViews === undefined ? {} : { workflowViews: options.workflowViews }),\n ...(options.workflowIndex === undefined ? {} : { workflowIndex: options.workflowIndex }),\n ...(options.workflowControls === undefined ? {} : { workflowControls: options.workflowControls }),\n ...(options.workflowSignals === undefined ? {} : { workflowSignals: options.workflowSignals }),\n ...(options.workflowResumes === undefined ? {} : { workflowResumes: options.workflowResumes }),\n ...(options.workflowPauses === undefined ? {} : { workflowPauses: options.workflowPauses }),\n ...(options.workflowFleet === undefined ? {} : { workflowFleet: options.workflowFleet }),\n ...(options.workflowMigrations === undefined ? {} : { workflowMigrations: options.workflowMigrations }),\n ...(options.submissionJournal === undefined ? {} : { submissionJournal: options.submissionJournal }),\n ...(options.runRecords === undefined ? {} : { runRecords: options.runRecords }),\n ...(options.allowedOrigins === undefined ? {} : { allowedOrigins: Object.freeze([...options.allowedOrigins]) }),\n ...(options.limits === undefined ? {} : { limits: Object.freeze({ ...options.limits }) }),\n };\n}\n\n/** Apply the shared socket, header and timeout bounds and track sockets for a bounded shutdown. */\nexport function hardenServer(server: Server, maxConnections: number): Set<Socket> {\n server.maxConnections = maxConnections;\n const sockets = new Set<Socket>();\n // TLS servers report the encrypted socket through 'secureConnection'; plain servers through 'connection'.\n const track = (socket: Socket): void => { sockets.add(socket); socket.once('close', () => { sockets.delete(socket); }); };\n server.on('connection', track); server.on('secureConnection', track);\n server.maxRequestsPerSocket = 100;\n server.setTimeout(35_000, socket => socket.destroy());\n server.on('upgrade', (_request, socket) => { socket.end('HTTP/1.1 426 Upgrade Required\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n'); });\n server.on('connect', (_request, socket) => { socket.destroy(); });\n server.on('clientError', (error, socket) => {\n const status = (error as NodeJS.ErrnoException).code === 'HPE_HEADER_OVERFLOW' ? '431 Request Header Fields Too Large' : '400 Bad Request';\n if (socket.writable) socket.end(`HTTP/1.1 ${status}\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n`);\n else socket.destroy();\n });\n return sockets;\n}\n\nexport const serverTimeouts = { maxHeaderSize: 16_384, headersTimeout: 5_000, requestTimeout: 15_000,\n keepAliveTimeout: 5_000, connectionsCheckingInterval: 1_000 } as const;\n\nexport function listen(server: Server, port: number, hostname: string, failure: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const failed = (): void => { server.removeListener('listening', ready); reject(new Error(failure)); };\n const ready = (): void => { server.removeListener('error', failed); resolve(); };\n server.once('error', failed); server.once('listening', ready); server.listen(port, hostname);\n });\n}\n\n/** Stop accepting, then close the protocol; the grace timer bounds stale and half-open sockets. */\nexport function shutdown(server: Server, sockets: Set<Socket>, grace: number, closeProtocol: () => Promise<void>, failure: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n server.closeAllConnections();\n // Node excludes upgraded sockets from closeAllConnections, including rejected half-open peers.\n for (const socket of sockets) socket.destroy();\n }, grace);\n const stopped = new Promise<void>(done => { server.close(() => done()); });\n server.closeIdleConnections();\n void Promise.all([stopped, closeProtocol()]).then(() => { clearTimeout(timer); resolve(); }, () => {\n clearTimeout(timer); for (const socket of sockets) socket.destroy();\n reject(new Error(failure));\n });\n });\n}\n"]}
|
|
@@ -3,7 +3,8 @@ export { listenProductionServer, type ProductionAgentServer, type ProductionServ
|
|
|
3
3
|
/** The identity an application's `authenticate` callback returns, re-exported so hosts need not import @mayura/server. */
|
|
4
4
|
export type { ServerIdentity } from '../../server/dist/index.js';
|
|
5
5
|
export { listenProbe, type ProbeServer, type ProbeServerOptions } from './probe.js';
|
|
6
|
-
|
|
6
|
+
/** The host builds each request's URL from its own origin, so `mounted` does not apply. */
|
|
7
|
+
export interface LocalServerOptions extends Omit<AgentServerOptions, 'publicOrigin' | 'mounted'> {
|
|
7
8
|
readonly hostname?: '127.0.0.1' | '::1';
|
|
8
9
|
readonly port?: number;
|
|
9
10
|
readonly shutdownGraceMs?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAuC,KAAK,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAG9F,OAAO,EAAE,sBAAsB,EAAE,KAAK,qBAAqB,EAAE,KAAK,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AACnH,0HAA0H;AAC1H,YAAY,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,KAAK,WAAW,EAAE,KAAK,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAEpF,MAAM,WAAW,kBAAmB,SAAQ,IAAI,CAAC,kBAAkB,EAAE,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAuC,KAAK,kBAAkB,EAAE,MAAM,gB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iB,CAAC,EAAE,GAAG,QAAQ,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC,CAAC;QACpE,IAAI,cAAyC,CAAC;QAC9C,MAAM,KAAK,GAAG,GAAkB,EAAE;YAChC,IAAI,cAAc;gBAAE,OAAO,cAAc,CAAC;YAC1C,OAAO,GAAG,IAAI,CAAC;YACf,cAAc,GAAG,QAAQ,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,QAAS,CAAC,KAAK,EAAE,EAAE,sDAAsD,CAAC,CAAC;YACnI,OAAO,cAAc,CAAC;QACxB,CAAC,CAAC;QACF,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,KAAK,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAC5D,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;IAC1C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,GAAG,IAAI,CAAC;QAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QAAC,MAAM,CAAC,mBAAmB,EAAE,CAAC;QAAC,MAAM,QAAQ,EAAE,KAAK,EAAE,CAAC;QACtF,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;IAC7D,CAAC;AACH,CAAC","sourcesContent":["import { createServer } from 'node:http';\nimport { getRequestListener } from '@hono/node-server';\nimport { Hono } from 'hono';\nimport { createAgentServer, type AgentServer, type AgentServerOptions } from '@mayura/server';\nimport { hardenServer, listen, serverTimeouts, shutdown, snapshotSettings, unavailable } from './hardening.js';\n\nexport { listenProductionServer, type ProductionAgentServer, type ProductionServerOptions } from './production.js';\n/** The identity an application's `authenticate` callback returns, re-exported so hosts need not import @mayura/server. */\nexport type { ServerIdentity } from '@mayura/server';\nexport { listenProbe, type ProbeServer, type ProbeServerOptions } from './probe.js';\n\n/** The host builds each request's URL from its own origin, so `mounted` does not apply. */\nexport interface LocalServerOptions extends Omit<AgentServerOptions, 'publicOrigin' | 'mounted'> {\n readonly hostname?: '127.0.0.1' | '::1';\n readonly port?: number;\n readonly shutdownGraceMs?: number;\n}\nexport interface LocalAgentServer {\n readonly origin: string;\n /** Stop listeners and request cancellation, retaining truthful unknown-effect semantics. */\n close(): Promise<void>;\n}\n\n/** Explicit local host. Never binds a wildcard/public interface or changes global Web API objects. */\nexport async function listenAgentServer(options: LocalServerOptions): Promise<LocalAgentServer> {\n const hostname = options.hostname ?? '127.0.0.1'; const port = options.port ?? 0; const grace = options.shutdownGraceMs ?? 5_000;\n if (!['127.0.0.1', '::1'].includes(hostname) || !Number.isInteger(port) || port < 0 || port > 65535\n || !Number.isSafeInteger(grace) || grace < 1 || grace > 30_000) throw new Error('Invalid bounded loopback server configuration.');\n const settings = snapshotSettings(options);\n const validation = createAgentServer({ ...settings, publicOrigin: 'http://127.0.0.1' });\n await validation.close();\n let protocol: AgentServer | undefined;\n let closing = false;\n const app = new Hono();\n app.onError(() => unavailable());\n app.all('*', context => closing || !protocol ? unavailable() : protocol.fetch(context.req.raw));\n const listener = getRequestListener(app.fetch, { overrideGlobalObjects: false, autoCleanupIncoming: true, errorHandler: () => unavailable() });\n const server = createServer(serverTimeouts, listener);\n const sockets = hardenServer(server, 128);\n try {\n await listen(server, port, hostname, 'The local server could not bind its configured loopback address.');\n const address = server.address();\n if (!address || typeof address === 'string') throw new Error('The local server did not establish a network address.');\n const origin = `http://${hostname === '::1' ? '[::1]' : hostname}:${address.port}`;\n protocol = createAgentServer({ ...settings, publicOrigin: origin });\n let closingPromise: Promise<void> | undefined;\n const close = (): Promise<void> => {\n if (closingPromise) return closingPromise;\n closing = true;\n closingPromise = shutdown(server, sockets, grace, () => protocol!.close(), 'The local server could not confirm runtime shutdown.');\n return closingPromise;\n };\n server.on('error', () => { void close().catch(() => {}); });\n return Object.freeze({ origin, close });\n } catch {\n closing = true; server.close(); server.closeAllConnections(); await protocol?.close();\n throw new Error('The local agent server could not start.');\n }\n}\n"]}
|
|
@@ -18,7 +18,7 @@ export async function listenProbe(options) {
|
|
|
18
18
|
return false;
|
|
19
19
|
} };
|
|
20
20
|
if (request.method !== 'GET')
|
|
21
|
-
reply(response, 405, '{"error":{"code":"METHOD_NOT_ALLOWED"}}');
|
|
21
|
+
reply(response, 405, '{"error":{"code":"METHOD_NOT_ALLOWED","message":"Probes answer GET only."}}');
|
|
22
22
|
else if (path === '/livez')
|
|
23
23
|
reply(response, check(options.isLive) ? 200 : 503, check(options.isLive) ? '{"status":"ok"}' : '{"status":"stopping"}');
|
|
24
24
|
else if (path === '/readyz') {
|
|
@@ -26,7 +26,7 @@ export async function listenProbe(options) {
|
|
|
26
26
|
reply(response, ready ? 200 : 503, ready ? '{"status":"ready"}' : '{"status":"unavailable"}');
|
|
27
27
|
}
|
|
28
28
|
else
|
|
29
|
-
reply(response, 404, '{"error":{"code":"
|
|
29
|
+
reply(response, 404, '{"error":{"code":"ROUTE_NOT_FOUND","message":"This probe server answers only GET /livez and GET /readyz."}}');
|
|
30
30
|
});
|
|
31
31
|
server.maxConnections = 64;
|
|
32
32
|
await new Promise((resolve, reject) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"probe.js","sourceRoot":"","sources":["../src/probe.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAuB,MAAM,WAAW,CAAC;AAU9D,+GAA+G;AAC/G,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,OAA2B;IAC3D,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,4BAA4B,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC;WAC1I,OAAO,CAAC,IAAI,GAAG,CAAC,IAAI,OAAO,CAAC,IAAI,GAAG,MAAM,IAAI,OAAO,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,IAAI,EAAE,OAAO,CAAC,IAAI;QACvC,KAAK,EAAE,GAAG,EAAE,CAAC,IAAI,OAAO,CAAO,OAAO,CAAC,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,mBAAmB,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;AACnH,CAAC","sourcesContent":["import { createServer, type ServerResponse } from 'node:http';\n\nexport interface ProbeServerOptions {\n readonly hostname: string;\n readonly port: number;\n readonly isLive: () => boolean;\n readonly isReady: () => boolean;\n}\nexport interface ProbeServer { readonly port: number; close(): Promise<void> }\n\n/** Content-free `/livez` and `/readyz` for processes without an HTTP surface of their own, such as workers. */\nexport async function listenProbe(options: ProbeServerOptions): Promise<ProbeServer> {\n if (!options || typeof options.hostname !== 'string' || !/^[A-Za-z0-9.:[\\]-]{1,255}$/.test(options.hostname) || !Number.isInteger(options.port)\n || options.port < 0 || options.port > 65_535 || typeof options.isLive !== 'function' || typeof options.isReady !== 'function') {\n throw new Error('Invalid probe server configuration.');\n }\n const reply = (response: ServerResponse, status: number, body: string): void => {\n response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' }); response.end(body);\n };\n const server = createServer({ headersTimeout: 5_000, requestTimeout: 5_000 }, (request, response) => {\n const path = (request.url ?? '').split('?')[0];\n const check = (probe: () => boolean): boolean => { try { return probe() === true; } catch { return false; } };\n if (request.method !== 'GET') reply(response, 405, '{\"error\":{\"code\":\"METHOD_NOT_ALLOWED\",\"message\":\"Probes answer GET only.\"}}');\n else if (path === '/livez') reply(response, check(options.isLive) ? 200 : 503, check(options.isLive) ? '{\"status\":\"ok\"}' : '{\"status\":\"stopping\"}');\n else if (path === '/readyz') { const ready = check(options.isReady); reply(response, ready ? 200 : 503, ready ? '{\"status\":\"ready\"}' : '{\"status\":\"unavailable\"}'); }\n else reply(response, 404, '{\"error\":{\"code\":\"ROUTE_NOT_FOUND\",\"message\":\"This probe server answers only GET /livez and GET /readyz.\"}}');\n });\n server.maxConnections = 64;\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject); server.listen(options.port, options.hostname, () => { server.removeListener('error', reject); resolve(); });\n });\n const address = server.address();\n if (!address || typeof address === 'string') { server.close(); throw new Error('The probe server did not bind.'); }\n return Object.freeze({ port: address.port,\n close: () => new Promise<void>(resolve => { server.close(() => resolve()); server.closeAllConnections(); }) });\n}\n"]}
|
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
import { type AgentServerOptions } from '../../server/dist/index.js';
|
|
2
|
-
|
|
2
|
+
/** The host rebuilds each request's URL from `publicOrigin` itself, so `mounted` does not apply. */
|
|
3
|
+
export interface ProductionServerOptions extends Omit<AgentServerOptions, 'publicOrigin' | 'mounted'> {
|
|
3
4
|
/** The canonical external origin clients use. Must be HTTPS; requests for any other host are refused. */
|
|
4
5
|
readonly publicOrigin: string;
|
|
6
|
+
/**
|
|
7
|
+
* IP addresses of reverse proxies that rewrite the `Host` header. A request whose socket peer is one of them is
|
|
8
|
+
* accepted when its `X-Forwarded-Host` (the last value, the one that proxy set) names the public host. Every other
|
|
9
|
+
* request must carry the public host in `Host`. Either way the destination is `publicOrigin`: no header changes it.
|
|
10
|
+
*/
|
|
11
|
+
readonly trustedProxies?: readonly string[];
|
|
5
12
|
/** Explicit bind address, for example `0.0.0.0`, `::` or one interface. There is no default. */
|
|
6
13
|
readonly hostname: string;
|
|
7
14
|
readonly port: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"production.d.ts","sourceRoot":"","sources":["../src/production.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"production.d.ts","sourceRoot":"","sources":["../src/production.ts"],"names":[],"mappings":"AAKA,OAAO,EAAuC,KAAK,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAG9F,oGAAoG;AACpG,MAAM,WAAW,uBAAwB,SAAQ,IAAI,CA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import { createServer as createHttpsServer } from 'node:https';
|
|
3
4
|
import { getRequestListener } from '@hono/node-server';
|
|
4
5
|
import { Hono } from 'hono';
|
|
@@ -7,6 +8,9 @@ import { hardenServer, listen, serverTimeouts, shutdown, snapshotSettings, unava
|
|
|
7
8
|
const json = (status, body) => new Response(body, {
|
|
8
9
|
status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },
|
|
9
10
|
});
|
|
11
|
+
const misdirected = JSON.stringify({ error: { code: 'MISDIRECTED_REQUEST', message: 'This server answers only for its public origin. Send the public host in the Host header; behind a proxy that rewrites Host, list the proxy in trustedProxies and have it set X-Forwarded-Host.' } });
|
|
12
|
+
/** IPv4 peers can appear as IPv4-mapped IPv6 addresses; compare them in one form. */
|
|
13
|
+
const peerAddress = (value) => value.toLowerCase().replace(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/, '$1');
|
|
10
14
|
const bytes = (value) => (typeof value === 'string' && value.length > 0) || (value instanceof Uint8Array && value.byteLength > 0);
|
|
11
15
|
const material = (value) => typeof value === 'string' ? value
|
|
12
16
|
: Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
@@ -38,6 +42,12 @@ export async function listenProductionServer(options) {
|
|
|
38
42
|
throw new Error('Production servers require in-process TLS material or an explicit TLS-terminating proxy.');
|
|
39
43
|
if (options.readiness !== undefined && typeof options.readiness !== 'function')
|
|
40
44
|
throw new Error('Readiness must be a function.');
|
|
45
|
+
const trustedProxies = (() => {
|
|
46
|
+
const supplied = options.trustedProxies ?? [];
|
|
47
|
+
if (!Array.isArray(supplied) || supplied.length > 64 || supplied.some(address => typeof address !== 'string' || isIP(address) === 0))
|
|
48
|
+
throw new Error('Trusted proxies must be at most 64 exact IP addresses.');
|
|
49
|
+
return new Set(supplied.map(peerAddress));
|
|
50
|
+
})();
|
|
41
51
|
const settings = snapshotSettings(options);
|
|
42
52
|
const readiness = options.readiness;
|
|
43
53
|
// Validate the complete protocol configuration before opening a socket.
|
|
@@ -81,8 +91,11 @@ export async function listenProductionServer(options) {
|
|
|
81
91
|
if (closing || !protocol)
|
|
82
92
|
return unavailable();
|
|
83
93
|
const raw = context.req.raw;
|
|
84
|
-
|
|
85
|
-
|
|
94
|
+
// A trusted proxy may carry the public host in X-Forwarded-Host after rewriting Host; it only decides acceptance.
|
|
95
|
+
const peer = peerAddress(context.env?.incoming?.socket.remoteAddress ?? '');
|
|
96
|
+
const forwarded = trustedProxies.has(peer) ? raw.headers.get('x-forwarded-host')?.split(',').at(-1)?.trim().toLowerCase() : undefined;
|
|
97
|
+
if ((forwarded ?? (raw.headers.get('host') ?? '').toLowerCase()) !== expectedHost)
|
|
98
|
+
return secure(json(421, misdirected));
|
|
86
99
|
// Rebuild the canonical public URL; the listener's own scheme and address are never trusted as the destination.
|
|
87
100
|
const incoming = new URL(raw.url);
|
|
88
101
|
const canonical = new URL(`${incoming.pathname}${incoming.search}`, publicOrigin.origin);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"production.js","sourceRoot":"","sources":["../src/production.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,IAAI,gBAAgB,EAAe,MAAM,WAAW,CAAC;AAC1E,OAAO,EAAE,YAAY,IAAI,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAA6C,MAAM,gBAAgB,CAAC;AAC9F,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,cAAc,EAAE,QAAQ,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AA0B/G,MAAM,IAAI,GAAG,CAAC,MAAc,EAAE,IAAY,EAAY,EAAE,CAAC,IAAI,QAAQ,CAAC,IAAI,EAAE;IAC1E,MAAM,EAAE,OAAO,EAAE,EAAE,cAAc,EAAE,k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AAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAC5D,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,YAAY,EAAE,YAAY,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;IACnI,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,GAAG,IAAI,CAAC;QAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QAAC,MAAM,CAAC,mBAAmB,EAAE,CAAC;QAAC,MAAM,QAAQ,EAAE,KAAK,EAAE,CAAC;QACtF,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import { createServer as createHttpServer, type Server } from 'node:http';\nimport { createServer as createHttpsServer } from 'node:https';\nimport { getRequestListener } from '@hono/node-server';\nimport { Hono } from 'hono';\nimport { createAgentServer, type AgentServer, type AgentServerOptions } from '@mayura/server';\nimport { hardenServer, listen, serverTimeouts, shutdown, snapshotSettings, unavailable } from './hardening.js';\n\nexport interface ProductionServerOptions extends Omit<AgentServerOptions, 'publicOrigin'> {\n /** The canonical external origin clients use. Must be HTTPS; requests for any other host are refused. */\n readonly publicOrigin: string;\n /** Explicit bind address, for example `0.0.0.0`, `::` or one interface. There is no default. */\n readonly hostname: string;\n readonly port: number;\n /** Terminate TLS in-process, or declare that a trusted proxy terminates TLS in front of this listener. */\n readonly tls: { readonly key: string | Uint8Array; readonly cert: string | Uint8Array } | { readonly terminatedBy: 'proxy' };\n /** Application readiness for `/readyz`, for example storage reachability. Bounded to 2 s; failures report not ready. */\n readonly readiness?: (signal: AbortSignal) => Promise<boolean>;\n readonly shutdownGraceMs?: number;\n readonly maxConnections?: number;\n readonly hstsMaxAgeSeconds?: number;\n}\nexport interface ProductionAgentServer {\n readonly publicOrigin: string;\n /** The bound port, useful when `port` is 0. */\n readonly port: number;\n /** False before startup completes and from the moment shutdown begins, so load balancers stop routing first. */\n isAccepting(): boolean;\n /** Stop accepting, fail readiness, drain in-flight requests within the grace period, then close runs and streams. */\n close(): Promise<void>;\n}\n\nconst json = (status: number, body: string): Response => new Response(body, {\n status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },\n});\nconst bytes = (value: unknown): boolean => (typeof value === 'string' && value.length > 0) || (value instanceof Uint8Array && value.byteLength > 0);\n\nconst material = (value: unknown): string | Buffer => typeof value === 'string' ? value\n : Buffer.from((value as Uint8Array).buffer, (value as Uint8Array).byteOffset, (value as Uint8Array).byteLength);\n\n/** Explicit production host: public binding, HTTPS-only origin, unauthenticated content-free probes and bounded shutdown. */\nexport async function listenProductionServer(options: ProductionServerOptions): Promise<ProductionAgentServer> {\n let publicOrigin: URL;\n try { publicOrigin = new URL(options.publicOrigin); } catch { throw new Error('Production servers require an exact HTTPS public origin.'); }\n if (publicOrigin.protocol !== 'https:' || publicOrigin.username || publicOrigin.password || publicOrigin.pathname !== '/'\n || publicOrigin.search || publicOrigin.hash || publicOrigin.origin !== options.publicOrigin.replace(/\\/$/, '')) {\n throw new Error('Production servers require an exact HTTPS public origin.');\n }\n const { hostname, port } = options; const grace = options.shutdownGraceMs ?? 30_000;\n const maxConnections = options.maxConnections ?? 1_024; const hsts = options.hstsMaxAgeSeconds ?? 31_536_000;\n if (typeof hostname !== 'string' || !/^[A-Za-z0-9.:[\\]-]{1,255}$/.test(hostname) || !Number.isInteger(port) || port < 0 || port > 65_535\n || !Number.isSafeInteger(grace) || grace < 1 || grace > 120_000 || !Number.isSafeInteger(maxConnections) || maxConnections < 1 || maxConnections > 65_536\n || !Number.isSafeInteger(hsts) || hsts < 0 || hsts > 63_072_000) throw new Error('Invalid bounded production server configuration.');\n const tls = options.tls as Record<string, unknown> | undefined;\n const proxied = tls?.['terminatedBy'] === 'proxy' && Object.keys(tls).length === 1;\n const inProcess = !!tls && Object.keys(tls).length === 2 && bytes(tls['key']) && bytes(tls['cert']);\n if (!proxied && !inProcess) throw new Error('Production servers require in-process TLS material or an explicit TLS-terminating proxy.');\n if (options.readiness !== undefined && typeof options.readiness !== 'function') throw new Error('Readiness must be a function.');\n const settings = snapshotSettings(options); const readiness = options.readiness;\n // Validate the complete protocol configuration before opening a socket.\n await createAgentServer({ ...settings, publicOrigin: publicOrigin.origin }).close();\n\n let protocol: AgentServer | undefined; let accepting = false; let closing = false;\n const expectedHost = publicOrigin.host.toLowerCase();\n const secure = (response: Response): Response => {\n if (hsts === 0) return response;\n const headers = new Headers(response.headers); headers.set('Strict-Transport-Security', `max-age=${hsts}`);\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers });\n };\n const app = new Hono();\n app.onError(() => unavailable());\n // Probes precede the host check: orchestrators address pods directly, not through the public name.\n app.get('/livez', () => closing ? json(503, '{\"status\":\"stopping\"}') : json(200, '{\"status\":\"ok\"}'));\n app.get('/readyz', async () => {\n if (!accepting || closing) return json(503, '{\"status\":\"unavailable\"}');\n if (!readiness) return json(200, '{\"status\":\"ready\"}');\n const controller = new AbortController(); let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const ready = await Promise.race([Promise.resolve().then(() => readiness(controller.signal)),\n new Promise<false>(resolve => { timer = setTimeout(() => { controller.abort(); resolve(false); }, 2_000); })]);\n return ready === true && accepting && !closing ? json(200, '{\"status\":\"ready\"}') : json(503, '{\"status\":\"unavailable\"}');\n } catch { return json(503, '{\"status\":\"unavailable\"}'); } finally { if (timer) clearTimeout(timer); }\n });\n app.all('*', async context => {\n if (closing || !protocol) return unavailable();\n const raw = context.req.raw;\n if ((raw.headers.get('host') ?? '').toLowerCase() !== expectedHost) return secure(json(421, '{\"error\":{\"code\":\"MISDIRECTED_REQUEST\"}}'));\n // Rebuild the canonical public URL; the listener's own scheme and address are never trusted as the destination.\n const incoming = new URL(raw.url); const canonical = new URL(`${incoming.pathname}${incoming.search}`, publicOrigin.origin);\n const body = raw.method === 'GET' || raw.method === 'HEAD' ? null : raw.body;\n const request = new Request(canonical, { method: raw.method, headers: raw.headers, body, signal: raw.signal, ...(body ? { duplex: 'half' } : {}) } as RequestInit);\n return secure(await protocol.fetch(request));\n });\n const listener = getRequestListener(app.fetch, { overrideGlobalObjects: false, autoCleanupIncoming: true, errorHandler: () => unavailable() });\n const server = (inProcess\n ? createHttpsServer({ ...serverTimeouts, key: material(tls!['key']), cert: material(tls!['cert']), minVersion: 'TLSv1.2' }, listener)\n : createHttpServer(serverTimeouts, listener)) as unknown as Server;\n const sockets = hardenServer(server, maxConnections);\n try {\n await listen(server, port, hostname, 'The production server could not bind its configured address.');\n const address = server.address();\n if (!address || typeof address === 'string') throw new Error('The production server did not establish a network address.');\n protocol = createAgentServer({ ...settings, publicOrigin: publicOrigin.origin }); accepting = true;\n let closingPromise: Promise<void> | undefined;\n const close = (): Promise<void> => {\n if (closingPromise) return closingPromise;\n accepting = false; closing = true;\n closingPromise = shutdown(server, sockets, grace, () => protocol!.close(), 'The production server could not confirm runtime shutdown.');\n return closingPromise;\n };\n server.on('error', () => { void close().catch(() => {}); });\n return Object.freeze({ publicOrigin: publicOrigin.origin, port: address.port, isAccepting: () => accepting && !closing, close });\n } catch {\n closing = true; server.close(); server.closeAllConnections(); await protocol?.close();\n throw new Error('The production agent server could not start.');\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"production.js","sourceRoot":"","sources":["../src/production.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,IAAI,gBAAgB,EAAqC,MAAM,WAAW,CAAC;AAChG,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,YAAY,IAAI,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAA6C,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,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,QAAS,CAAC,KAAK,EAAE,EAAE,2DAA2D,CAAC,CAAC;YACxI,OAAO,cAAc,CAAC;QACxB,CAAC,CAAC;QACF,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,KAAK,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAC5D,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,YAAY,EAAE,YAAY,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;IACnI,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,GAAG,IAAI,CAAC;QAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QAAC,MAAM,CAAC,mBAAmB,EAAE,CAAC;QAAC,MAAM,QAAQ,EAAE,KAAK,EAAE,CAAC;QACtF,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import { createServer as createHttpServer, type IncomingMessage, type Server } from 'node:http';\nimport { isIP } from 'node:net';\nimport { createServer as createHttpsServer } from 'node:https';\nimport { getRequestListener } from '@hono/node-server';\nimport { Hono } from 'hono';\nimport { createAgentServer, type AgentServer, type AgentServerOptions } from '@mayura/server';\nimport { hardenServer, listen, serverTimeouts, shutdown, snapshotSettings, unavailable } from './hardening.js';\n\n/** The host rebuilds each request's URL from `publicOrigin` itself, so `mounted` does not apply. */\nexport interface ProductionServerOptions extends Omit<AgentServerOptions, 'publicOrigin' | 'mounted'> {\n /** The canonical external origin clients use. Must be HTTPS; requests for any other host are refused. */\n readonly publicOrigin: string;\n /**\n * IP addresses of reverse proxies that rewrite the `Host` header. A request whose socket peer is one of them is\n * accepted when its `X-Forwarded-Host` (the last value, the one that proxy set) names the public host. Every other\n * request must carry the public host in `Host`. Either way the destination is `publicOrigin`: no header changes it.\n */\n readonly trustedProxies?: readonly string[];\n /** Explicit bind address, for example `0.0.0.0`, `::` or one interface. There is no default. */\n readonly hostname: string;\n readonly port: number;\n /** Terminate TLS in-process, or declare that a trusted proxy terminates TLS in front of this listener. */\n readonly tls: { readonly key: string | Uint8Array; readonly cert: string | Uint8Array } | { readonly terminatedBy: 'proxy' };\n /** Application readiness for `/readyz`, for example storage reachability. Bounded to 2 s; failures report not ready. */\n readonly readiness?: (signal: AbortSignal) => Promise<boolean>;\n readonly shutdownGraceMs?: number;\n readonly maxConnections?: number;\n readonly hstsMaxAgeSeconds?: number;\n}\nexport interface ProductionAgentServer {\n readonly publicOrigin: string;\n /** The bound port, useful when `port` is 0. */\n readonly port: number;\n /** False before startup completes and from the moment shutdown begins, so load balancers stop routing first. */\n isAccepting(): boolean;\n /** Stop accepting, fail readiness, drain in-flight requests within the grace period, then close runs and streams. */\n close(): Promise<void>;\n}\n\nconst json = (status: number, body: string): Response => new Response(body, {\n status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },\n});\nconst misdirected = JSON.stringify({ error: { code: 'MISDIRECTED_REQUEST', message: 'This server answers only for its public origin. Send the public host in the Host header; behind a proxy that rewrites Host, list the proxy in trustedProxies and have it set X-Forwarded-Host.' } });\n/** IPv4 peers can appear as IPv4-mapped IPv6 addresses; compare them in one form. */\nconst peerAddress = (value: string): string => value.toLowerCase().replace(/^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/, '$1');\nconst bytes = (value: unknown): boolean => (typeof value === 'string' && value.length > 0) || (value instanceof Uint8Array && value.byteLength > 0);\n\nconst material = (value: unknown): string | Buffer => typeof value === 'string' ? value\n : Buffer.from((value as Uint8Array).buffer, (value as Uint8Array).byteOffset, (value as Uint8Array).byteLength);\n\n/** Explicit production host: public binding, HTTPS-only origin, unauthenticated content-free probes and bounded shutdown. */\nexport async function listenProductionServer(options: ProductionServerOptions): Promise<ProductionAgentServer> {\n let publicOrigin: URL;\n try { publicOrigin = new URL(options.publicOrigin); } catch { throw new Error('Production servers require an exact HTTPS public origin.'); }\n if (publicOrigin.protocol !== 'https:' || publicOrigin.username || publicOrigin.password || publicOrigin.pathname !== '/'\n || publicOrigin.search || publicOrigin.hash || publicOrigin.origin !== options.publicOrigin.replace(/\\/$/, '')) {\n throw new Error('Production servers require an exact HTTPS public origin.');\n }\n const { hostname, port } = options; const grace = options.shutdownGraceMs ?? 30_000;\n const maxConnections = options.maxConnections ?? 1_024; const hsts = options.hstsMaxAgeSeconds ?? 31_536_000;\n if (typeof hostname !== 'string' || !/^[A-Za-z0-9.:[\\]-]{1,255}$/.test(hostname) || !Number.isInteger(port) || port < 0 || port > 65_535\n || !Number.isSafeInteger(grace) || grace < 1 || grace > 120_000 || !Number.isSafeInteger(maxConnections) || maxConnections < 1 || maxConnections > 65_536\n || !Number.isSafeInteger(hsts) || hsts < 0 || hsts > 63_072_000) throw new Error('Invalid bounded production server configuration.');\n const tls = options.tls as Record<string, unknown> | undefined;\n const proxied = tls?.['terminatedBy'] === 'proxy' && Object.keys(tls).length === 1;\n const inProcess = !!tls && Object.keys(tls).length === 2 && bytes(tls['key']) && bytes(tls['cert']);\n if (!proxied && !inProcess) throw new Error('Production servers require in-process TLS material or an explicit TLS-terminating proxy.');\n if (options.readiness !== undefined && typeof options.readiness !== 'function') throw new Error('Readiness must be a function.');\n const trustedProxies = (() => {\n const supplied = options.trustedProxies ?? [];\n if (!Array.isArray(supplied) || supplied.length > 64 || supplied.some(address => typeof address !== 'string' || isIP(address) === 0))\n throw new Error('Trusted proxies must be at most 64 exact IP addresses.');\n return new Set(supplied.map(peerAddress));\n })();\n const settings = snapshotSettings(options); const readiness = options.readiness;\n // Validate the complete protocol configuration before opening a socket.\n await createAgentServer({ ...settings, publicOrigin: publicOrigin.origin }).close();\n\n let protocol: AgentServer | undefined; let accepting = false; let closing = false;\n const expectedHost = publicOrigin.host.toLowerCase();\n const secure = (response: Response): Response => {\n if (hsts === 0) return response;\n const headers = new Headers(response.headers); headers.set('Strict-Transport-Security', `max-age=${hsts}`);\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers });\n };\n const app = new Hono();\n app.onError(() => unavailable());\n // Probes precede the host check: orchestrators address pods directly, not through the public name.\n app.get('/livez', () => closing ? json(503, '{\"status\":\"stopping\"}') : json(200, '{\"status\":\"ok\"}'));\n app.get('/readyz', async () => {\n if (!accepting || closing) return json(503, '{\"status\":\"unavailable\"}');\n if (!readiness) return json(200, '{\"status\":\"ready\"}');\n const controller = new AbortController(); let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const ready = await Promise.race([Promise.resolve().then(() => readiness(controller.signal)),\n new Promise<false>(resolve => { timer = setTimeout(() => { controller.abort(); resolve(false); }, 2_000); })]);\n return ready === true && accepting && !closing ? json(200, '{\"status\":\"ready\"}') : json(503, '{\"status\":\"unavailable\"}');\n } catch { return json(503, '{\"status\":\"unavailable\"}'); } finally { if (timer) clearTimeout(timer); }\n });\n app.all('*', async context => {\n if (closing || !protocol) return unavailable();\n const raw = context.req.raw;\n // A trusted proxy may carry the public host in X-Forwarded-Host after rewriting Host; it only decides acceptance.\n const peer = peerAddress((context.env as { incoming?: IncomingMessage } | undefined)?.incoming?.socket.remoteAddress ?? '');\n const forwarded = trustedProxies.has(peer) ? raw.headers.get('x-forwarded-host')?.split(',').at(-1)?.trim().toLowerCase() : undefined;\n if ((forwarded ?? (raw.headers.get('host') ?? '').toLowerCase()) !== expectedHost) return secure(json(421, misdirected));\n // Rebuild the canonical public URL; the listener's own scheme and address are never trusted as the destination.\n const incoming = new URL(raw.url); const canonical = new URL(`${incoming.pathname}${incoming.search}`, publicOrigin.origin);\n const body = raw.method === 'GET' || raw.method === 'HEAD' ? null : raw.body;\n const request = new Request(canonical, { method: raw.method, headers: raw.headers, body, signal: raw.signal, ...(body ? { duplex: 'half' } : {}) } as RequestInit);\n return secure(await protocol.fetch(request));\n });\n const listener = getRequestListener(app.fetch, { overrideGlobalObjects: false, autoCleanupIncoming: true, errorHandler: () => unavailable() });\n const server = (inProcess\n ? createHttpsServer({ ...serverTimeouts, key: material(tls!['key']), cert: material(tls!['cert']), minVersion: 'TLSv1.2' }, listener)\n : createHttpServer(serverTimeouts, listener)) as unknown as Server;\n const sockets = hardenServer(server, maxConnections);\n try {\n await listen(server, port, hostname, 'The production server could not bind its configured address.');\n const address = server.address();\n if (!address || typeof address === 'string') throw new Error('The production server did not establish a network address.');\n protocol = createAgentServer({ ...settings, publicOrigin: publicOrigin.origin }); accepting = true;\n let closingPromise: Promise<void> | undefined;\n const close = (): Promise<void> => {\n if (closingPromise) return closingPromise;\n accepting = false; closing = true;\n closingPromise = shutdown(server, sockets, grace, () => protocol!.close(), 'The production server could not confirm runtime shutdown.');\n return closingPromise;\n };\n server.on('error', () => { void close().catch(() => {}); });\n return Object.freeze({ publicOrigin: publicOrigin.origin, port: address.port, isAccepting: () => accepting && !closing, close });\n } catch {\n closing = true; server.close(); server.closeAllConnections(); await protocol?.close();\n throw new Error('The production agent server could not start.');\n }\n}\n"]}
|
|
@@ -2,12 +2,13 @@ import type { Server } from 'node:http';
|
|
|
2
2
|
import type { Socket } from 'node:net';
|
|
3
3
|
import type { AgentServerOptions } from '@mayura/server';
|
|
4
4
|
|
|
5
|
-
export const unavailable = (): Response => new Response(
|
|
6
|
-
|
|
5
|
+
export const unavailable = (): Response => new Response(JSON.stringify({ error: { code: 'HOST_UNAVAILABLE', retryAfterMs: 1_000,
|
|
6
|
+
message: 'The server is starting, stopping or could not handle the request. Retry shortly, against another replica if possible.' } }), {
|
|
7
|
+
status: 503, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Retry-After': '1' },
|
|
7
8
|
});
|
|
8
9
|
|
|
9
10
|
/** Snapshot and freeze every trusted option before a socket opens; no mutable caller reference is retained. */
|
|
10
|
-
export function snapshotSettings(options: Omit<AgentServerOptions, 'publicOrigin'>): Omit<AgentServerOptions, 'publicOrigin'> {
|
|
11
|
+
export function snapshotSettings(options: Omit<AgentServerOptions, 'publicOrigin' | 'mounted'>): Omit<AgentServerOptions, 'publicOrigin' | 'mounted'> {
|
|
11
12
|
return {
|
|
12
13
|
agents: Object.freeze(options.agents.map(config => Object.freeze({ agent: config.agent,
|
|
13
14
|
permissions: Object.freeze({ allow: Object.freeze([...config.permissions.allow]) }),
|
|
@@ -26,6 +27,7 @@ export function snapshotSettings(options: Omit<AgentServerOptions, 'publicOrigin
|
|
|
26
27
|
...(options.workflowFleet === undefined ? {} : { workflowFleet: options.workflowFleet }),
|
|
27
28
|
...(options.workflowMigrations === undefined ? {} : { workflowMigrations: options.workflowMigrations }),
|
|
28
29
|
...(options.submissionJournal === undefined ? {} : { submissionJournal: options.submissionJournal }),
|
|
30
|
+
...(options.runRecords === undefined ? {} : { runRecords: options.runRecords }),
|
|
29
31
|
...(options.allowedOrigins === undefined ? {} : { allowedOrigins: Object.freeze([...options.allowedOrigins]) }),
|
|
30
32
|
...(options.limits === undefined ? {} : { limits: Object.freeze({ ...options.limits }) }),
|
|
31
33
|
};
|
|
@@ -9,7 +9,8 @@ export { listenProductionServer, type ProductionAgentServer, type ProductionServ
|
|
|
9
9
|
export type { ServerIdentity } from '@mayura/server';
|
|
10
10
|
export { listenProbe, type ProbeServer, type ProbeServerOptions } from './probe.js';
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
/** The host builds each request's URL from its own origin, so `mounted` does not apply. */
|
|
13
|
+
export interface LocalServerOptions extends Omit<AgentServerOptions, 'publicOrigin' | 'mounted'> {
|
|
13
14
|
readonly hostname?: '127.0.0.1' | '::1';
|
|
14
15
|
readonly port?: number;
|
|
15
16
|
readonly shutdownGraceMs?: number;
|
|
@@ -20,10 +20,10 @@ export async function listenProbe(options: ProbeServerOptions): Promise<ProbeSer
|
|
|
20
20
|
const server = createServer({ headersTimeout: 5_000, requestTimeout: 5_000 }, (request, response) => {
|
|
21
21
|
const path = (request.url ?? '').split('?')[0];
|
|
22
22
|
const check = (probe: () => boolean): boolean => { try { return probe() === true; } catch { return false; } };
|
|
23
|
-
if (request.method !== 'GET') reply(response, 405, '{"error":{"code":"METHOD_NOT_ALLOWED"}}');
|
|
23
|
+
if (request.method !== 'GET') reply(response, 405, '{"error":{"code":"METHOD_NOT_ALLOWED","message":"Probes answer GET only."}}');
|
|
24
24
|
else if (path === '/livez') reply(response, check(options.isLive) ? 200 : 503, check(options.isLive) ? '{"status":"ok"}' : '{"status":"stopping"}');
|
|
25
25
|
else if (path === '/readyz') { const ready = check(options.isReady); reply(response, ready ? 200 : 503, ready ? '{"status":"ready"}' : '{"status":"unavailable"}'); }
|
|
26
|
-
else reply(response, 404, '{"error":{"code":"
|
|
26
|
+
else reply(response, 404, '{"error":{"code":"ROUTE_NOT_FOUND","message":"This probe server answers only GET /livez and GET /readyz."}}');
|
|
27
27
|
});
|
|
28
28
|
server.maxConnections = 64;
|
|
29
29
|
await new Promise<void>((resolve, reject) => {
|
|
@@ -1,13 +1,21 @@
|
|
|
1
|
-
import { createServer as createHttpServer, type Server } from 'node:http';
|
|
1
|
+
import { createServer as createHttpServer, type IncomingMessage, type Server } from 'node:http';
|
|
2
|
+
import { isIP } from 'node:net';
|
|
2
3
|
import { createServer as createHttpsServer } from 'node:https';
|
|
3
4
|
import { getRequestListener } from '@hono/node-server';
|
|
4
5
|
import { Hono } from 'hono';
|
|
5
6
|
import { createAgentServer, type AgentServer, type AgentServerOptions } from '@mayura/server';
|
|
6
7
|
import { hardenServer, listen, serverTimeouts, shutdown, snapshotSettings, unavailable } from './hardening.js';
|
|
7
8
|
|
|
8
|
-
|
|
9
|
+
/** The host rebuilds each request's URL from `publicOrigin` itself, so `mounted` does not apply. */
|
|
10
|
+
export interface ProductionServerOptions extends Omit<AgentServerOptions, 'publicOrigin' | 'mounted'> {
|
|
9
11
|
/** The canonical external origin clients use. Must be HTTPS; requests for any other host are refused. */
|
|
10
12
|
readonly publicOrigin: string;
|
|
13
|
+
/**
|
|
14
|
+
* IP addresses of reverse proxies that rewrite the `Host` header. A request whose socket peer is one of them is
|
|
15
|
+
* accepted when its `X-Forwarded-Host` (the last value, the one that proxy set) names the public host. Every other
|
|
16
|
+
* request must carry the public host in `Host`. Either way the destination is `publicOrigin`: no header changes it.
|
|
17
|
+
*/
|
|
18
|
+
readonly trustedProxies?: readonly string[];
|
|
11
19
|
/** Explicit bind address, for example `0.0.0.0`, `::` or one interface. There is no default. */
|
|
12
20
|
readonly hostname: string;
|
|
13
21
|
readonly port: number;
|
|
@@ -32,6 +40,9 @@ export interface ProductionAgentServer {
|
|
|
32
40
|
const json = (status: number, body: string): Response => new Response(body, {
|
|
33
41
|
status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },
|
|
34
42
|
});
|
|
43
|
+
const misdirected = JSON.stringify({ error: { code: 'MISDIRECTED_REQUEST', message: 'This server answers only for its public origin. Send the public host in the Host header; behind a proxy that rewrites Host, list the proxy in trustedProxies and have it set X-Forwarded-Host.' } });
|
|
44
|
+
/** IPv4 peers can appear as IPv4-mapped IPv6 addresses; compare them in one form. */
|
|
45
|
+
const peerAddress = (value: string): string => value.toLowerCase().replace(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/, '$1');
|
|
35
46
|
const bytes = (value: unknown): boolean => (typeof value === 'string' && value.length > 0) || (value instanceof Uint8Array && value.byteLength > 0);
|
|
36
47
|
|
|
37
48
|
const material = (value: unknown): string | Buffer => typeof value === 'string' ? value
|
|
@@ -55,6 +66,12 @@ export async function listenProductionServer(options: ProductionServerOptions):
|
|
|
55
66
|
const inProcess = !!tls && Object.keys(tls).length === 2 && bytes(tls['key']) && bytes(tls['cert']);
|
|
56
67
|
if (!proxied && !inProcess) throw new Error('Production servers require in-process TLS material or an explicit TLS-terminating proxy.');
|
|
57
68
|
if (options.readiness !== undefined && typeof options.readiness !== 'function') throw new Error('Readiness must be a function.');
|
|
69
|
+
const trustedProxies = (() => {
|
|
70
|
+
const supplied = options.trustedProxies ?? [];
|
|
71
|
+
if (!Array.isArray(supplied) || supplied.length > 64 || supplied.some(address => typeof address !== 'string' || isIP(address) === 0))
|
|
72
|
+
throw new Error('Trusted proxies must be at most 64 exact IP addresses.');
|
|
73
|
+
return new Set(supplied.map(peerAddress));
|
|
74
|
+
})();
|
|
58
75
|
const settings = snapshotSettings(options); const readiness = options.readiness;
|
|
59
76
|
// Validate the complete protocol configuration before opening a socket.
|
|
60
77
|
await createAgentServer({ ...settings, publicOrigin: publicOrigin.origin }).close();
|
|
@@ -83,7 +100,10 @@ export async function listenProductionServer(options: ProductionServerOptions):
|
|
|
83
100
|
app.all('*', async context => {
|
|
84
101
|
if (closing || !protocol) return unavailable();
|
|
85
102
|
const raw = context.req.raw;
|
|
86
|
-
|
|
103
|
+
// A trusted proxy may carry the public host in X-Forwarded-Host after rewriting Host; it only decides acceptance.
|
|
104
|
+
const peer = peerAddress((context.env as { incoming?: IncomingMessage } | undefined)?.incoming?.socket.remoteAddress ?? '');
|
|
105
|
+
const forwarded = trustedProxies.has(peer) ? raw.headers.get('x-forwarded-host')?.split(',').at(-1)?.trim().toLowerCase() : undefined;
|
|
106
|
+
if ((forwarded ?? (raw.headers.get('host') ?? '').toLowerCase()) !== expectedHost) return secure(json(421, misdirected));
|
|
87
107
|
// Rebuild the canonical public URL; the listener's own scheme and address are never trusted as the destination.
|
|
88
108
|
const incoming = new URL(raw.url); const canonical = new URL(`${incoming.pathname}${incoming.search}`, publicOrigin.origin);
|
|
89
109
|
const body = raw.method === 'GET' || raw.method === 'HEAD' ? null : raw.body;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { type AnyTool } from '../../tools/dist/index.js';
|
|
2
|
+
/** A file a skill bundles besides SKILL.md, by path relative to the skill folder (`references/api.md`). */
|
|
3
|
+
export interface SkillFile {
|
|
4
|
+
readonly path: string;
|
|
5
|
+
readonly bytes: number;
|
|
6
|
+
readonly text: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface Skill {
|
|
9
|
+
readonly name: string;
|
|
10
|
+
readonly description: string;
|
|
11
|
+
/** The Markdown after the front matter: what the agent reads when it loads the skill. */
|
|
12
|
+
readonly instructions: string;
|
|
13
|
+
readonly files: readonly SkillFile[];
|
|
14
|
+
readonly license?: string;
|
|
15
|
+
/** Tools the skill expects (informational: it grants nothing). */
|
|
16
|
+
readonly allowedTools: readonly string[];
|
|
17
|
+
readonly metadata: Readonly<Record<string, string>>;
|
|
18
|
+
/** SHA-256 over the skill's front matter, instructions and every file. */
|
|
19
|
+
readonly digest: string;
|
|
20
|
+
}
|
|
21
|
+
export interface SkillSet {
|
|
22
|
+
readonly skills: readonly Skill[];
|
|
23
|
+
/** SHA-256 over every skill's digest; also the version of the skill tools, so durable runs pin what they read. */
|
|
24
|
+
readonly digest: string;
|
|
25
|
+
get(name: string): Skill | undefined;
|
|
26
|
+
/** A skill file's text. Binary files are listed but not readable. */
|
|
27
|
+
readFile(name: string, path: string): string;
|
|
28
|
+
/** The block to add to an agent's instructions: how to use skills, and each skill's name and description. */
|
|
29
|
+
catalog(): string;
|
|
30
|
+
/** `skills.load` and `skills.read`: read-only tools with no effects. */
|
|
31
|
+
readonly tools: readonly AnyTool[];
|
|
32
|
+
/** What a runtime must allow for the tools: `tool:skills.load`, `tool:skills.read` and `skills:read`. */
|
|
33
|
+
readonly permissions: readonly string[];
|
|
34
|
+
}
|
|
35
|
+
export interface SkillLimits {
|
|
36
|
+
/** Skills in one set (default 64). */
|
|
37
|
+
readonly maxSkills?: number;
|
|
38
|
+
/** Files in one skill besides SKILL.md (default 128). */
|
|
39
|
+
readonly maxFilesPerSkill?: number;
|
|
40
|
+
/** Bytes in one file, SKILL.md included (default 256 KiB). */
|
|
41
|
+
readonly maxFileBytes?: number;
|
|
42
|
+
/** Bytes across all skills (default 16 MiB). */
|
|
43
|
+
readonly maxTotalBytes?: number;
|
|
44
|
+
/** Bytes of the catalog added to the agent's instructions (default 16 KiB). */
|
|
45
|
+
readonly maxCatalogBytes?: number;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The front matter of SKILL.md: a small, strict YAML subset (`key: value`, quoted values, `>`/`|` block scalars, a
|
|
49
|
+
* `metadata` map and an `allowed-tools` list). Unknown keys are ignored.
|
|
50
|
+
*/
|
|
51
|
+
export declare function parseSkillFile(text: string, label?: string): {
|
|
52
|
+
readonly fields: Record<string, unknown>;
|
|
53
|
+
readonly body: string;
|
|
54
|
+
};
|
|
55
|
+
/** Define a skill in code: the same shape a SKILL.md folder has. `files` maps relative paths to their text. */
|
|
56
|
+
export declare function defineSkill(options: {
|
|
57
|
+
readonly name: string;
|
|
58
|
+
readonly description: string;
|
|
59
|
+
readonly instructions: string;
|
|
60
|
+
readonly files?: Readonly<Record<string, string>>;
|
|
61
|
+
readonly license?: string;
|
|
62
|
+
readonly allowedTools?: readonly string[];
|
|
63
|
+
readonly metadata?: Readonly<Record<string, string>>;
|
|
64
|
+
}): Skill;
|
|
65
|
+
/**
|
|
66
|
+
* Load skills from folders. Each source is either one skill folder (it has a SKILL.md) or a folder of skill folders.
|
|
67
|
+
* Everything is read once, within bounds, so later reads cannot change what the digest names. Symbolic links, hidden
|
|
68
|
+
* entries and node_modules are refused or skipped; a skill's name must match its folder's.
|
|
69
|
+
*/
|
|
70
|
+
export declare function loadSkills(sources: string | readonly string[], options?: SkillLimits): Promise<SkillSet>;
|
|
71
|
+
/** A skill set from skills loaded or defined elsewhere. Names must be unique. */
|
|
72
|
+
export declare function createSkillSet(skills: readonly Skill[], options?: SkillLimits): SkillSet;
|
|
73
|
+
/**
|
|
74
|
+
* Give an agent a skill set: its catalog appended to the instructions and its two tools added. Grant
|
|
75
|
+
* `skills.permissions` in the runtime too.
|
|
76
|
+
*/
|
|
77
|
+
export declare function withSkills<T extends {
|
|
78
|
+
readonly instructions: string;
|
|
79
|
+
readonly tools: readonly An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