airlock-bot 0.3.1 → 0.4.0
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 +46 -33
- package/airlock.service +1 -0
- package/dist/airlock/context.d.ts.map +1 -1
- package/dist/airlock/context.js +5 -3
- package/dist/airlock/context.js.map +1 -1
- package/dist/airlock/tools.d.ts +15 -3
- package/dist/airlock/tools.d.ts.map +1 -1
- package/dist/airlock/tools.js +29 -1
- package/dist/airlock/tools.js.map +1 -1
- package/dist/allowlist/engine.d.ts +3 -0
- package/dist/allowlist/engine.d.ts.map +1 -1
- package/dist/allowlist/engine.js +46 -2
- package/dist/allowlist/engine.js.map +1 -1
- package/dist/audit/db.d.ts +22 -1
- package/dist/audit/db.d.ts.map +1 -1
- package/dist/audit/db.js +77 -10
- package/dist/audit/db.js.map +1 -1
- package/dist/audit/logger.d.ts +7 -2
- package/dist/audit/logger.d.ts.map +1 -1
- package/dist/audit/logger.js +18 -3
- package/dist/audit/logger.js.map +1 -1
- package/dist/audit/redactor.d.ts.map +1 -1
- package/dist/audit/redactor.js +6 -6
- package/dist/audit/redactor.js.map +1 -1
- package/dist/backend/airlock-adapter.d.ts +20 -2
- package/dist/backend/airlock-adapter.d.ts.map +1 -1
- package/dist/backend/airlock-adapter.js +443 -10
- package/dist/backend/airlock-adapter.js.map +1 -1
- package/dist/backend/cli/adapter.d.ts +4 -2
- package/dist/backend/cli/adapter.d.ts.map +1 -1
- package/dist/backend/cli/adapter.js +36 -11
- package/dist/backend/cli/adapter.js.map +1 -1
- package/dist/backend/cli/builder.d.ts +1 -1
- package/dist/backend/cli/builder.d.ts.map +1 -1
- package/dist/backend/cli/builder.js +28 -12
- package/dist/backend/cli/builder.js.map +1 -1
- package/dist/backend/exec-adapter.d.ts +1 -1
- package/dist/backend/exec-adapter.d.ts.map +1 -1
- package/dist/backend/exec-adapter.js +1 -5
- package/dist/backend/exec-adapter.js.map +1 -1
- package/dist/backend/factory.d.ts +2 -0
- package/dist/backend/factory.d.ts.map +1 -1
- package/dist/backend/factory.js +19 -5
- package/dist/backend/factory.js.map +1 -1
- package/dist/backend/http-adapter.d.ts +6 -3
- package/dist/backend/http-adapter.d.ts.map +1 -1
- package/dist/backend/http-adapter.js +24 -10
- package/dist/backend/http-adapter.js.map +1 -1
- package/dist/backend/mcp-adapter.d.ts +7 -2
- package/dist/backend/mcp-adapter.d.ts.map +1 -1
- package/dist/backend/mcp-adapter.js +74 -16
- package/dist/backend/mcp-adapter.js.map +1 -1
- package/dist/backend/openapi/adapter.d.ts +8 -2
- package/dist/backend/openapi/adapter.d.ts.map +1 -1
- package/dist/backend/openapi/adapter.js +196 -17
- package/dist/backend/openapi/adapter.js.map +1 -1
- package/dist/backend/openapi/parser.d.ts +15 -1
- package/dist/backend/openapi/parser.d.ts.map +1 -1
- package/dist/backend/openapi/parser.js +153 -11
- package/dist/backend/openapi/parser.js.map +1 -1
- package/dist/backend/types.d.ts +12 -1
- package/dist/backend/types.d.ts.map +1 -1
- package/dist/config/loader.d.ts.map +1 -1
- package/dist/config/loader.js +334 -50
- package/dist/config/loader.js.map +1 -1
- package/dist/config/mutator.d.ts.map +1 -1
- package/dist/config/mutator.js +13 -3
- package/dist/config/mutator.js.map +1 -1
- package/dist/config/profiles.d.ts +2 -1
- package/dist/config/profiles.d.ts.map +1 -1
- package/dist/config/profiles.js +50 -2
- package/dist/config/profiles.js.map +1 -1
- package/dist/config/provider-credentials.d.ts +4 -0
- package/dist/config/provider-credentials.d.ts.map +1 -0
- package/dist/config/provider-credentials.js +48 -0
- package/dist/config/provider-credentials.js.map +1 -0
- package/dist/config/schema.d.ts +2829 -8642
- package/dist/config/schema.d.ts.map +1 -1
- package/dist/config/schema.js +337 -122
- package/dist/config/schema.js.map +1 -1
- package/dist/config/watcher.d.ts.map +1 -1
- package/dist/config/watcher.js +3 -0
- package/dist/config/watcher.js.map +1 -1
- package/dist/config/yaml-merge.d.ts +9 -0
- package/dist/config/yaml-merge.d.ts.map +1 -0
- package/dist/config/yaml-merge.js +54 -0
- package/dist/config/yaml-merge.js.map +1 -0
- package/dist/configure-agent/cli.d.ts +26 -0
- package/dist/configure-agent/cli.d.ts.map +1 -1
- package/dist/configure-agent/cli.js +70 -35
- package/dist/configure-agent/cli.js.map +1 -1
- package/dist/configure-cli/cli.d.ts +6 -0
- package/dist/configure-cli/cli.d.ts.map +1 -1
- package/dist/configure-cli/cli.js +45 -14
- package/dist/configure-cli/cli.js.map +1 -1
- package/dist/configure-web/assistant.d.ts +49 -0
- package/dist/configure-web/assistant.d.ts.map +1 -0
- package/dist/configure-web/assistant.js +312 -0
- package/dist/configure-web/assistant.js.map +1 -0
- package/dist/configure-web/changes.d.ts +214 -0
- package/dist/configure-web/changes.d.ts.map +1 -0
- package/dist/configure-web/changes.js +317 -0
- package/dist/configure-web/changes.js.map +1 -0
- package/dist/configure-web/cli.d.ts +33 -11
- package/dist/configure-web/cli.d.ts.map +1 -1
- package/dist/configure-web/cli.js +704 -151
- package/dist/configure-web/cli.js.map +1 -1
- package/dist/discover/cli.js +2 -2
- package/dist/discover/cli.js.map +1 -1
- package/dist/discover/index.d.ts.map +1 -1
- package/dist/discover/index.js +16 -22
- package/dist/discover/index.js.map +1 -1
- package/dist/discover/openapi.d.ts.map +1 -1
- package/dist/discover/openapi.js +2 -0
- package/dist/discover/openapi.js.map +1 -1
- package/dist/discover/strategies/completion.d.ts.map +1 -1
- package/dist/discover/strategies/completion.js +19 -2
- package/dist/discover/strategies/completion.js.map +1 -1
- package/dist/discover/strategies/fig.d.ts +10 -1
- package/dist/discover/strategies/fig.d.ts.map +1 -1
- package/dist/discover/strategies/fig.js +24 -10
- package/dist/discover/strategies/fig.js.map +1 -1
- package/dist/discover/strategies/help-parser.d.ts.map +1 -1
- package/dist/discover/strategies/help-parser.js +9 -6
- package/dist/discover/strategies/help-parser.js.map +1 -1
- package/dist/events/payload-inspector.d.ts +25 -0
- package/dist/events/payload-inspector.d.ts.map +1 -0
- package/dist/events/payload-inspector.js +210 -0
- package/dist/events/payload-inspector.js.map +1 -0
- package/dist/events/protocol.d.ts +227 -0
- package/dist/events/protocol.d.ts.map +1 -0
- package/dist/events/protocol.js +422 -0
- package/dist/events/protocol.js.map +1 -0
- package/dist/events/registry.d.ts +57 -0
- package/dist/events/registry.d.ts.map +1 -0
- package/dist/events/registry.js +179 -0
- package/dist/events/registry.js.map +1 -0
- package/dist/events/schema-validator.d.ts +13 -0
- package/dist/events/schema-validator.d.ts.map +1 -0
- package/dist/events/schema-validator.js +54 -0
- package/dist/events/schema-validator.js.map +1 -0
- package/dist/events/service.d.ts +97 -0
- package/dist/events/service.d.ts.map +1 -0
- package/dist/events/service.js +918 -0
- package/dist/events/service.js.map +1 -0
- package/dist/events/stream-manager.d.ts +58 -0
- package/dist/events/stream-manager.d.ts.map +1 -0
- package/dist/events/stream-manager.js +94 -0
- package/dist/events/stream-manager.js.map +1 -0
- package/dist/events/upstream-client.d.ts +88 -0
- package/dist/events/upstream-client.d.ts.map +1 -0
- package/dist/events/upstream-client.js +437 -0
- package/dist/events/upstream-client.js.map +1 -0
- package/dist/gateway.d.ts +14 -0
- package/dist/gateway.d.ts.map +1 -1
- package/dist/gateway.js +208 -33
- package/dist/gateway.js.map +1 -1
- package/dist/hitl/api.d.ts.map +1 -1
- package/dist/hitl/api.js +9 -2
- package/dist/hitl/api.js.map +1 -1
- package/dist/hitl/approval-dashboard.d.ts +5 -0
- package/dist/hitl/approval-dashboard.d.ts.map +1 -1
- package/dist/hitl/approval-dashboard.js +107 -20
- package/dist/hitl/approval-dashboard.js.map +1 -1
- package/dist/hitl/approval-stream.d.ts +2 -0
- package/dist/hitl/approval-stream.d.ts.map +1 -1
- package/dist/hitl/approval-stream.js +11 -0
- package/dist/hitl/approval-stream.js.map +1 -1
- package/dist/hitl/engine.d.ts +154 -4
- package/dist/hitl/engine.d.ts.map +1 -1
- package/dist/hitl/engine.js +616 -102
- package/dist/hitl/engine.js.map +1 -1
- package/dist/hitl/formatter.d.ts.map +1 -1
- package/dist/hitl/formatter.js +60 -10
- package/dist/hitl/formatter.js.map +1 -1
- package/dist/hitl/grant-api.d.ts +32 -0
- package/dist/hitl/grant-api.d.ts.map +1 -0
- package/dist/hitl/grant-api.js +249 -0
- package/dist/hitl/grant-api.js.map +1 -0
- package/dist/hitl/grants.d.ts +153 -0
- package/dist/hitl/grants.d.ts.map +1 -0
- package/dist/hitl/grants.js +273 -0
- package/dist/hitl/grants.js.map +1 -0
- package/dist/hitl/parser.d.ts +9 -0
- package/dist/hitl/parser.d.ts.map +1 -1
- package/dist/hitl/parser.js +60 -4
- package/dist/hitl/parser.js.map +1 -1
- package/dist/hitl/provider-factory.js +6 -1
- package/dist/hitl/provider-factory.js.map +1 -1
- package/dist/hitl/providers/composite.d.ts +0 -1
- package/dist/hitl/providers/composite.d.ts.map +1 -1
- package/dist/hitl/providers/composite.js +0 -3
- package/dist/hitl/providers/composite.js.map +1 -1
- package/dist/hitl/providers/dashboard.d.ts +1 -0
- package/dist/hitl/providers/dashboard.d.ts.map +1 -1
- package/dist/hitl/providers/dashboard.js +9 -2
- package/dist/hitl/providers/dashboard.js.map +1 -1
- package/dist/hitl/providers/ios.d.ts +0 -1
- package/dist/hitl/providers/ios.d.ts.map +1 -1
- package/dist/hitl/providers/ios.js +94 -39
- package/dist/hitl/providers/ios.js.map +1 -1
- package/dist/hitl/providers/macos.d.ts +2 -0
- package/dist/hitl/providers/macos.d.ts.map +1 -1
- package/dist/hitl/providers/macos.js +90 -3
- package/dist/hitl/providers/macos.js.map +1 -1
- package/dist/hitl/providers/openclaw.js +3 -9
- package/dist/hitl/providers/openclaw.js.map +1 -1
- package/dist/hitl/providers/stdio.js +3 -9
- package/dist/hitl/providers/stdio.js.map +1 -1
- package/dist/hitl/providers/telegram.d.ts.map +1 -1
- package/dist/hitl/providers/telegram.js +6 -10
- package/dist/hitl/providers/telegram.js.map +1 -1
- package/dist/hitl/providers/tui.d.ts +1 -1
- package/dist/hitl/providers/tui.d.ts.map +1 -1
- package/dist/hitl/providers/tui.js +91 -31
- package/dist/hitl/providers/tui.js.map +1 -1
- package/dist/hitl/providers/types.d.ts +38 -3
- package/dist/hitl/providers/types.d.ts.map +1 -1
- package/dist/hitl/runtime.d.ts +18 -0
- package/dist/hitl/runtime.d.ts.map +1 -0
- package/dist/hitl/runtime.js +60 -0
- package/dist/hitl/runtime.js.map +1 -0
- package/dist/hook/api.d.ts +6 -1
- package/dist/hook/api.d.ts.map +1 -1
- package/dist/hook/api.js +51 -12
- package/dist/hook/api.js.map +1 -1
- package/dist/index.js +15 -3
- package/dist/index.js.map +1 -1
- package/dist/introspect/cli.d.ts.map +1 -1
- package/dist/introspect/cli.js +5 -2
- package/dist/introspect/cli.js.map +1 -1
- package/dist/mcp-apps/ui.d.ts +69 -0
- package/dist/mcp-apps/ui.d.ts.map +1 -0
- package/dist/mcp-apps/ui.js +143 -0
- package/dist/mcp-apps/ui.js.map +1 -0
- package/dist/middleware/audit-args.d.ts +7 -0
- package/dist/middleware/audit-args.d.ts.map +1 -0
- package/dist/middleware/audit-args.js +23 -0
- package/dist/middleware/audit-args.js.map +1 -0
- package/dist/middleware/chain-builder.d.ts +2 -2
- package/dist/middleware/chain-builder.d.ts.map +1 -1
- package/dist/middleware/chain-builder.js +7 -3
- package/dist/middleware/chain-builder.js.map +1 -1
- package/dist/middleware/core/allowlist.d.ts.map +1 -1
- package/dist/middleware/core/allowlist.js +8 -5
- package/dist/middleware/core/allowlist.js.map +1 -1
- package/dist/middleware/core/arg-policy.d.ts +1 -0
- package/dist/middleware/core/arg-policy.d.ts.map +1 -1
- package/dist/middleware/core/arg-policy.js +34 -37
- package/dist/middleware/core/arg-policy.js.map +1 -1
- package/dist/middleware/core/command-policy.d.ts +4 -1
- package/dist/middleware/core/command-policy.d.ts.map +1 -1
- package/dist/middleware/core/command-policy.js +50 -4
- package/dist/middleware/core/command-policy.js.map +1 -1
- package/dist/middleware/core/exec-policy.d.ts.map +1 -1
- package/dist/middleware/core/exec-policy.js +5 -5
- package/dist/middleware/core/exec-policy.js.map +1 -1
- package/dist/middleware/core/execute.d.ts +5 -1
- package/dist/middleware/core/execute.d.ts.map +1 -1
- package/dist/middleware/core/execute.js +18 -15
- package/dist/middleware/core/execute.js.map +1 -1
- package/dist/middleware/core/hitl-gate.d.ts +4 -1
- package/dist/middleware/core/hitl-gate.d.ts.map +1 -1
- package/dist/middleware/core/hitl-gate.js +153 -45
- package/dist/middleware/core/hitl-gate.js.map +1 -1
- package/dist/middleware/core/rate-limiter.d.ts.map +1 -1
- package/dist/middleware/core/rate-limiter.js +23 -7
- package/dist/middleware/core/rate-limiter.js.map +1 -1
- package/dist/middleware/core/schema-validator.d.ts +3 -0
- package/dist/middleware/core/schema-validator.d.ts.map +1 -1
- package/dist/middleware/core/schema-validator.js +31 -12
- package/dist/middleware/core/schema-validator.js.map +1 -1
- package/dist/middleware/core/upload-policy.d.ts +18 -0
- package/dist/middleware/core/upload-policy.d.ts.map +1 -0
- package/dist/middleware/core/upload-policy.js +98 -0
- package/dist/middleware/core/upload-policy.js.map +1 -0
- package/dist/middleware/detectors/injection-detector.d.ts.map +1 -1
- package/dist/middleware/detectors/injection-detector.js +8 -6
- package/dist/middleware/detectors/injection-detector.js.map +1 -1
- package/dist/middleware/detectors/sensitivity-classifier.d.ts.map +1 -1
- package/dist/middleware/detectors/sensitivity-classifier.js +19 -5
- package/dist/middleware/detectors/sensitivity-classifier.js.map +1 -1
- package/dist/middleware/post/untrusted-envelope.d.ts.map +1 -1
- package/dist/middleware/post/untrusted-envelope.js +4 -1
- package/dist/middleware/post/untrusted-envelope.js.map +1 -1
- package/dist/middleware/response.d.ts +33 -0
- package/dist/middleware/response.d.ts.map +1 -0
- package/dist/middleware/response.js +110 -0
- package/dist/middleware/response.js.map +1 -0
- package/dist/middleware/types.d.ts +13 -0
- package/dist/middleware/types.d.ts.map +1 -1
- package/dist/mobile/api.d.ts.map +1 -1
- package/dist/mobile/api.js +57 -34
- package/dist/mobile/api.js.map +1 -1
- package/dist/mobile/apns.d.ts +39 -2
- package/dist/mobile/apns.d.ts.map +1 -1
- package/dist/mobile/apns.js +84 -83
- package/dist/mobile/apns.js.map +1 -1
- package/dist/pool/client-credentials.d.ts +2 -0
- package/dist/pool/client-credentials.d.ts.map +1 -1
- package/dist/pool/client-credentials.js +18 -3
- package/dist/pool/client-credentials.js.map +1 -1
- package/dist/pool/credential-health.d.ts +2 -2
- package/dist/pool/credential-health.d.ts.map +1 -1
- package/dist/pool/credential-health.js +7 -2
- package/dist/pool/credential-health.js.map +1 -1
- package/dist/pool/http-client.d.ts +105 -16
- package/dist/pool/http-client.d.ts.map +1 -1
- package/dist/pool/http-client.js +712 -116
- package/dist/pool/http-client.js.map +1 -1
- package/dist/pool/oauth-callback-router.d.ts +35 -0
- package/dist/pool/oauth-callback-router.d.ts.map +1 -0
- package/dist/pool/oauth-callback-router.js +84 -0
- package/dist/pool/oauth-callback-router.js.map +1 -0
- package/dist/pool/oauth-cli.d.ts +10 -0
- package/dist/pool/oauth-cli.d.ts.map +1 -0
- package/dist/pool/oauth-cli.js +318 -0
- package/dist/pool/oauth-cli.js.map +1 -0
- package/dist/pool/oauth-lock.d.ts +149 -0
- package/dist/pool/oauth-lock.d.ts.map +1 -0
- package/dist/pool/oauth-lock.js +575 -0
- package/dist/pool/oauth-lock.js.map +1 -0
- package/dist/pool/oauth-provider.d.ts +231 -27
- package/dist/pool/oauth-provider.d.ts.map +1 -1
- package/dist/pool/oauth-provider.js +802 -142
- package/dist/pool/oauth-provider.js.map +1 -1
- package/dist/pool/oauth-refresh.d.ts +94 -0
- package/dist/pool/oauth-refresh.d.ts.map +1 -0
- package/dist/pool/oauth-refresh.js +477 -0
- package/dist/pool/oauth-refresh.js.map +1 -0
- package/dist/pool/oauth-store.d.ts +304 -0
- package/dist/pool/oauth-store.d.ts.map +1 -0
- package/dist/pool/oauth-store.js +684 -0
- package/dist/pool/oauth-store.js.map +1 -0
- package/dist/pool/pool.d.ts +37 -4
- package/dist/pool/pool.d.ts.map +1 -1
- package/dist/pool/pool.js +170 -8
- package/dist/pool/pool.js.map +1 -1
- package/dist/pool/required-mcps.d.ts +7 -0
- package/dist/pool/required-mcps.d.ts.map +1 -1
- package/dist/pool/required-mcps.js +40 -2
- package/dist/pool/required-mcps.js.map +1 -1
- package/dist/pool/sse-client.d.ts +17 -3
- package/dist/pool/sse-client.d.ts.map +1 -1
- package/dist/pool/sse-client.js +59 -6
- package/dist/pool/sse-client.js.map +1 -1
- package/dist/pool/status.d.ts +53 -0
- package/dist/pool/status.d.ts.map +1 -1
- package/dist/pool/stdio-client.d.ts +23 -3
- package/dist/pool/stdio-client.d.ts.map +1 -1
- package/dist/pool/stdio-client.js +84 -6
- package/dist/pool/stdio-client.js.map +1 -1
- package/dist/registry/airlock-policy.d.ts +1 -1
- package/dist/registry/airlock-policy.d.ts.map +1 -1
- package/dist/registry/airlock-policy.js +1 -1
- package/dist/registry/airlock-policy.js.map +1 -1
- package/dist/registry/registry.d.ts +22 -2
- package/dist/registry/registry.d.ts.map +1 -1
- package/dist/registry/registry.js +176 -22
- package/dist/registry/registry.js.map +1 -1
- package/dist/registry/sanitizer.d.ts +5 -0
- package/dist/registry/sanitizer.d.ts.map +1 -1
- package/dist/registry/sanitizer.js +17 -13
- package/dist/registry/sanitizer.js.map +1 -1
- package/dist/security/request.d.ts +19 -0
- package/dist/security/request.d.ts.map +1 -1
- package/dist/security/request.js +35 -1
- package/dist/security/request.js.map +1 -1
- package/dist/stdio-mode.d.ts.map +1 -1
- package/dist/stdio-mode.js +237 -50
- package/dist/stdio-mode.js.map +1 -1
- package/dist/tools/api.d.ts.map +1 -1
- package/dist/tools/api.js +49 -15
- package/dist/tools/api.js.map +1 -1
- package/dist/tools/exec.d.ts +1 -1
- package/dist/tools/exec.d.ts.map +1 -1
- package/dist/tools/http.d.ts +7 -3
- package/dist/tools/http.d.ts.map +1 -1
- package/dist/tools/http.js +179 -25
- package/dist/tools/http.js.map +1 -1
- package/dist/transport/agent-server.d.ts +29 -2
- package/dist/transport/agent-server.d.ts.map +1 -1
- package/dist/transport/agent-server.js +190 -32
- package/dist/transport/agent-server.js.map +1 -1
- package/dist/transport/http-server.d.ts +17 -2
- package/dist/transport/http-server.d.ts.map +1 -1
- package/dist/transport/http-server.js +109 -96
- package/dist/transport/http-server.js.map +1 -1
- package/dist/transport/keepalive.d.ts +11 -13
- package/dist/transport/keepalive.d.ts.map +1 -1
- package/dist/transport/keepalive.js +11 -13
- package/dist/transport/keepalive.js.map +1 -1
- package/dist/transport/oauth-callback.d.ts +19 -0
- package/dist/transport/oauth-callback.d.ts.map +1 -0
- package/dist/transport/oauth-callback.js +30 -0
- package/dist/transport/oauth-callback.js.map +1 -0
- package/dist/transport/session-limiter.d.ts +10 -3
- package/dist/transport/session-limiter.d.ts.map +1 -1
- package/dist/transport/session-limiter.js +13 -3
- package/dist/transport/session-limiter.js.map +1 -1
- package/dist/transport/sse-server.d.ts.map +1 -1
- package/dist/transport/sse-server.js +54 -24
- package/dist/transport/sse-server.js.map +1 -1
- package/dist/transport/stdio-server.d.ts +6 -0
- package/dist/transport/stdio-server.d.ts.map +1 -1
- package/dist/transport/stdio-server.js +19 -7
- package/dist/transport/stdio-server.js.map +1 -1
- package/dist/types.d.ts +0 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/uploads/api.d.ts +20 -0
- package/dist/uploads/api.d.ts.map +1 -0
- package/dist/uploads/api.js +280 -0
- package/dist/uploads/api.js.map +1 -0
- package/dist/uploads/refs.d.ts +48 -0
- package/dist/uploads/refs.d.ts.map +1 -0
- package/dist/uploads/refs.js +273 -0
- package/dist/uploads/refs.js.map +1 -0
- package/dist/uploads/resolve.d.ts +117 -0
- package/dist/uploads/resolve.d.ts.map +1 -0
- package/dist/uploads/resolve.js +581 -0
- package/dist/uploads/resolve.js.map +1 -0
- package/dist/uploads/store.d.ts +224 -0
- package/dist/uploads/store.d.ts.map +1 -0
- package/dist/uploads/store.js +1908 -0
- package/dist/uploads/store.js.map +1 -0
- package/dist/util/atomic-file.d.ts +6 -0
- package/dist/util/atomic-file.d.ts.map +1 -1
- package/dist/util/atomic-file.js +42 -2
- package/dist/util/atomic-file.js.map +1 -1
- package/dist/util/is-record.d.ts +3 -0
- package/dist/util/is-record.d.ts.map +1 -0
- package/dist/util/is-record.js +5 -0
- package/dist/util/is-record.js.map +1 -0
- package/dist/util/stable-json.d.ts +3 -0
- package/dist/util/stable-json.d.ts.map +1 -0
- package/dist/util/stable-json.js +10 -0
- package/dist/util/stable-json.js.map +1 -0
- package/dist/util/tool-name.d.ts +9 -0
- package/dist/util/tool-name.d.ts.map +1 -0
- package/dist/util/tool-name.js +14 -0
- package/dist/util/tool-name.js.map +1 -0
- package/dist/web/assets/airlock-shield-fPu067nB.png +0 -0
- package/dist/web/assets/favicon-DL7sWXGq.png +0 -0
- package/dist/web/assets/index-B_qY7DgQ.js +225 -0
- package/dist/web/assets/index-Bc_jHlFK.css +1 -0
- package/dist/web/assets/inter-cyrillic-ext-opsz-normal-CfYZpDVp.woff2 +0 -0
- package/dist/web/assets/inter-cyrillic-opsz-normal-BFQXbQ-f.woff2 +0 -0
- package/dist/web/assets/inter-greek-ext-opsz-normal-BmPQvyvo.woff2 +0 -0
- package/dist/web/assets/inter-greek-opsz-normal-BM0NlUE_.woff2 +0 -0
- package/dist/web/assets/inter-latin-ext-opsz-normal-DpK-iCPk.woff2 +0 -0
- package/dist/web/assets/inter-latin-opsz-normal-BwkfbSeq.woff2 +0 -0
- package/dist/web/assets/inter-vietnamese-opsz-normal-Ci9T9ieq.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
- package/dist/web/index.html +17 -0
- package/examples/airlock.yaml +3 -1
- package/examples/claude-code-setup.md +1 -1
- package/examples/docker-compose.yaml +3 -1
- package/examples/docker-gateway.yaml +2 -1
- package/examples/gateway.yaml +1 -1
- package/examples/profiles.yaml +5 -2
- package/examples/sandbox-presets.yaml +4 -1
- package/extensions/openclaw/index.ts +3 -3
- package/extensions/openclaw/openclaw.plugin.json +4 -4
- package/package.json +25 -10
- package/schema.json +2819 -2029
- package/dist/transport/mcp-normalizer.d.ts +0 -9
- package/dist/transport/mcp-normalizer.d.ts.map +0 -1
- package/dist/transport/mcp-normalizer.js +0 -12
- package/dist/transport/mcp-normalizer.js.map +0 -1
- package/extensions/openclaw/package-lock.json +0 -8548
|
@@ -0,0 +1,1908 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'crypto';
|
|
2
|
+
import { constants as fsConstants, createWriteStream, lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmdirSync, rmSync, unlinkSync, } from 'fs';
|
|
3
|
+
import { lstat, mkdir, open, realpath, rename, rm, stat } from 'fs/promises';
|
|
4
|
+
import { tmpdir } from 'os';
|
|
5
|
+
import { dirname, join, resolve, sep } from 'path';
|
|
6
|
+
import { Readable, Transform } from 'stream';
|
|
7
|
+
import Database from 'better-sqlite3';
|
|
8
|
+
import { UploadsConfig } from '../config/schema.js';
|
|
9
|
+
import { sha256Hex } from '../security/request.js';
|
|
10
|
+
import { childLogger } from '../util/logger.js';
|
|
11
|
+
import { UPLOAD_ID_PATTERN, formatUploadRef, inferMimeType, matchesMimeAllowlist, normalizeMimeType, sanitizeFilename, toWellFormedUnicode, } from './refs.js';
|
|
12
|
+
const log = childLogger('uploads');
|
|
13
|
+
const MULTIPART_OVERHEAD_BYTES = 64 * 1024;
|
|
14
|
+
const SWEEP_INTERVAL_MS = 60_000;
|
|
15
|
+
const OWNER_LOCK_FILENAME = '.airlock-owner.lock';
|
|
16
|
+
const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 60_000;
|
|
17
|
+
const SESSION_AGENT_RECORD_MULTIPLIER = 4;
|
|
18
|
+
const MIN_GLOBAL_RECORD_CAP = 2000;
|
|
19
|
+
/** Block size for staging-time per-chunk SHA-256 authentication on streamed delivery (256 KiB). */
|
|
20
|
+
const STREAM_VERIFY_BLOCK_BYTES = 256 * 1024;
|
|
21
|
+
/** Canonical staging directories currently owned by live UploadStore instances in this process. */
|
|
22
|
+
const ACTIVE_OWNED_DIRS = new Set();
|
|
23
|
+
export class UploadHttpError extends Error {
|
|
24
|
+
statusCode;
|
|
25
|
+
constructor(statusCode, message, options) {
|
|
26
|
+
super(message, options);
|
|
27
|
+
this.statusCode = statusCode;
|
|
28
|
+
this.name = 'UploadHttpError';
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export function effectiveMaxFileBytes(globalConfig, agentConfig) {
|
|
32
|
+
// Per-agent max_file_bytes overrides the default (letting e.g. a video or 3D-print agent accept
|
|
33
|
+
// larger files without widening every other agent), still bounded by global max_total_bytes.
|
|
34
|
+
const desired = agentConfig?.max_file_bytes ?? globalConfig.max_file_bytes;
|
|
35
|
+
return Math.min(desired, globalConfig.max_total_bytes);
|
|
36
|
+
}
|
|
37
|
+
export function effectiveMaxFiles(globalConfig, agentConfig) {
|
|
38
|
+
if (agentConfig?.max_files === undefined)
|
|
39
|
+
return globalConfig.max_files_per_agent;
|
|
40
|
+
return Math.min(globalConfig.max_files_per_agent, agentConfig.max_files);
|
|
41
|
+
}
|
|
42
|
+
function isMimeAllowed(mimeType, globalConfig, agentConfig) {
|
|
43
|
+
if (!matchesMimeAllowlist(mimeType, globalConfig.allowed_mime_types))
|
|
44
|
+
return false;
|
|
45
|
+
if (agentConfig?.allowed_mime_types &&
|
|
46
|
+
agentConfig.allowed_mime_types.length > 0 &&
|
|
47
|
+
!matchesMimeAllowlist(mimeType, agentConfig.allowed_mime_types)) {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
function stripTrailingSlash(url) {
|
|
53
|
+
return url.replace(/\/+$/, '');
|
|
54
|
+
}
|
|
55
|
+
function normalizeRequestHost(raw) {
|
|
56
|
+
if (!raw)
|
|
57
|
+
return undefined;
|
|
58
|
+
const first = raw.split(',')[0]?.trim().toLowerCase();
|
|
59
|
+
return first || undefined;
|
|
60
|
+
}
|
|
61
|
+
function hostMatchesPublicUrl(candidateUrl, requestHost) {
|
|
62
|
+
try {
|
|
63
|
+
const parsed = new URL(candidateUrl);
|
|
64
|
+
if (parsed.host.toLowerCase() === requestHost)
|
|
65
|
+
return true;
|
|
66
|
+
const defaultPort = parsed.protocol === 'https:' ? '443' : parsed.protocol === 'http:' ? '80' : '';
|
|
67
|
+
if (defaultPort && `${parsed.hostname.toLowerCase()}:${defaultPort}` === requestHost) {
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
return !parsed.port && parsed.hostname.toLowerCase() === requestHost;
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function escapeMultipartParam(value) {
|
|
77
|
+
return toWellFormedUnicode(value)
|
|
78
|
+
.replace(/[\r\n]/g, '_')
|
|
79
|
+
.replace(/["\\]/g, '_');
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Incremental whole-file + fixed-block SHA-256 builder used during upload staging so streaming
|
|
83
|
+
* delivery can authenticate every block against staging-time digests BEFORE emitting a single
|
|
84
|
+
* unverified byte downstream.
|
|
85
|
+
*/
|
|
86
|
+
class ChunkedDigestBuilder {
|
|
87
|
+
blockSize;
|
|
88
|
+
wholeHash = createHash('sha256');
|
|
89
|
+
blockHash = createHash('sha256');
|
|
90
|
+
blockBytes = 0;
|
|
91
|
+
digests = [];
|
|
92
|
+
constructor(blockSize = STREAM_VERIFY_BLOCK_BYTES) {
|
|
93
|
+
this.blockSize = blockSize;
|
|
94
|
+
}
|
|
95
|
+
update(buf) {
|
|
96
|
+
if (buf.byteLength === 0)
|
|
97
|
+
return;
|
|
98
|
+
this.wholeHash.update(buf);
|
|
99
|
+
let offset = 0;
|
|
100
|
+
while (offset < buf.byteLength) {
|
|
101
|
+
const take = Math.min(this.blockSize - this.blockBytes, buf.byteLength - offset);
|
|
102
|
+
this.blockHash.update(buf.subarray(offset, offset + take));
|
|
103
|
+
this.blockBytes += take;
|
|
104
|
+
offset += take;
|
|
105
|
+
if (this.blockBytes === this.blockSize) {
|
|
106
|
+
this.digests.push(this.blockHash.digest());
|
|
107
|
+
this.blockHash = createHash('sha256');
|
|
108
|
+
this.blockBytes = 0;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
finish() {
|
|
113
|
+
if (this.blockBytes > 0) {
|
|
114
|
+
this.digests.push(this.blockHash.digest());
|
|
115
|
+
this.blockBytes = 0;
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
sha256: this.wholeHash.digest('hex'),
|
|
119
|
+
blockSize: this.blockSize,
|
|
120
|
+
blockDigests: Buffer.concat(this.digests),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Wrap a verified `FileHandle` in a streaming readable that authenticates each fixed-size block
|
|
126
|
+
* against its staging-time SHA-256 digest BEFORE emitting any bytes of that block downstream, and
|
|
127
|
+
* verifies the exact byte count and whole-file SHA-256 before completing.
|
|
128
|
+
*/
|
|
129
|
+
function createDigestVerifyingStream(fh, record, onDone, onFdClosed) {
|
|
130
|
+
const wholeHash = createHash('sha256');
|
|
131
|
+
const blockSize = record.blockSize > 0 ? record.blockSize : STREAM_VERIFY_BLOCK_BYTES;
|
|
132
|
+
const expectedBlockCount = Math.floor(record.blockDigests.byteLength / 32);
|
|
133
|
+
let blockIndex = 0;
|
|
134
|
+
let bytesRead = 0;
|
|
135
|
+
let pending = [];
|
|
136
|
+
let pendingBytes = 0;
|
|
137
|
+
let released = false;
|
|
138
|
+
let fdClosed = false;
|
|
139
|
+
const release = () => {
|
|
140
|
+
if (released)
|
|
141
|
+
return;
|
|
142
|
+
released = true;
|
|
143
|
+
onDone?.();
|
|
144
|
+
};
|
|
145
|
+
const markFdClosed = () => {
|
|
146
|
+
if (fdClosed)
|
|
147
|
+
return;
|
|
148
|
+
fdClosed = true;
|
|
149
|
+
onFdClosed?.();
|
|
150
|
+
};
|
|
151
|
+
const verifyBlock = (block) => {
|
|
152
|
+
if (blockIndex >= expectedBlockCount) {
|
|
153
|
+
return new Error(`Staged upload "${record.id}" exceeded expected authenticated block count.`);
|
|
154
|
+
}
|
|
155
|
+
const actualDigest = createHash('sha256').update(block).digest();
|
|
156
|
+
const expectedDigest = record.blockDigests.subarray(blockIndex * 32, (blockIndex + 1) * 32);
|
|
157
|
+
if (Buffer.compare(actualDigest, expectedDigest) !== 0) {
|
|
158
|
+
return new Error(`Staged upload "${record.id}" failed block SHA-256 integrity verification before emission.`);
|
|
159
|
+
}
|
|
160
|
+
blockIndex += 1;
|
|
161
|
+
wholeHash.update(block);
|
|
162
|
+
return undefined;
|
|
163
|
+
};
|
|
164
|
+
const takePendingBlock = (size) => {
|
|
165
|
+
const only = pending[0];
|
|
166
|
+
if (pending.length === 1 && only && only.byteLength === size) {
|
|
167
|
+
pending = [];
|
|
168
|
+
pendingBytes = 0;
|
|
169
|
+
return only;
|
|
170
|
+
}
|
|
171
|
+
const combined = Buffer.concat(pending, pendingBytes);
|
|
172
|
+
const block = combined.subarray(0, size);
|
|
173
|
+
const rest = combined.subarray(size);
|
|
174
|
+
pending = rest.byteLength > 0 ? [rest] : [];
|
|
175
|
+
pendingBytes = rest.byteLength;
|
|
176
|
+
return block;
|
|
177
|
+
};
|
|
178
|
+
const source = fh.createReadStream({ autoClose: true, highWaterMark: blockSize });
|
|
179
|
+
source.once('close', markFdClosed);
|
|
180
|
+
const verifier = new Transform({
|
|
181
|
+
transform(chunk, _encoding, callback) {
|
|
182
|
+
bytesRead += chunk.byteLength;
|
|
183
|
+
if (bytesRead > record.sizeBytes) {
|
|
184
|
+
callback(new Error(`Staged upload "${record.id}" exceeded verified byte length.`));
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (chunk.byteLength > 0) {
|
|
188
|
+
pending.push(chunk);
|
|
189
|
+
pendingBytes += chunk.byteLength;
|
|
190
|
+
}
|
|
191
|
+
while (pendingBytes >= blockSize) {
|
|
192
|
+
const block = takePendingBlock(blockSize);
|
|
193
|
+
const err = verifyBlock(block);
|
|
194
|
+
if (err) {
|
|
195
|
+
callback(err);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
this.push(block);
|
|
199
|
+
}
|
|
200
|
+
callback();
|
|
201
|
+
},
|
|
202
|
+
flush(callback) {
|
|
203
|
+
let finalBlock;
|
|
204
|
+
if (pendingBytes > 0) {
|
|
205
|
+
finalBlock = takePendingBlock(pendingBytes);
|
|
206
|
+
const err = verifyBlock(finalBlock);
|
|
207
|
+
if (err) {
|
|
208
|
+
callback(err);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
const actualHash = wholeHash.digest('hex');
|
|
213
|
+
if (bytesRead !== record.sizeBytes ||
|
|
214
|
+
blockIndex !== expectedBlockCount ||
|
|
215
|
+
actualHash !== record.sha256) {
|
|
216
|
+
callback(new Error(`Staged upload "${record.id}" failed SHA-256 integrity verification.`));
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (finalBlock && finalBlock.byteLength > 0) {
|
|
220
|
+
this.push(finalBlock);
|
|
221
|
+
}
|
|
222
|
+
callback();
|
|
223
|
+
},
|
|
224
|
+
destroy(err, callback) {
|
|
225
|
+
pending = [];
|
|
226
|
+
pendingBytes = 0;
|
|
227
|
+
if (!source.destroyed)
|
|
228
|
+
source.destroy();
|
|
229
|
+
if (source.closed)
|
|
230
|
+
markFdClosed();
|
|
231
|
+
release();
|
|
232
|
+
callback(err);
|
|
233
|
+
},
|
|
234
|
+
});
|
|
235
|
+
source.on('error', (err) => {
|
|
236
|
+
verifier.destroy(err);
|
|
237
|
+
});
|
|
238
|
+
verifier.once('close', () => {
|
|
239
|
+
if (!source.destroyed)
|
|
240
|
+
source.destroy();
|
|
241
|
+
if (source.closed)
|
|
242
|
+
markFdClosed();
|
|
243
|
+
release();
|
|
244
|
+
});
|
|
245
|
+
source.pipe(verifier);
|
|
246
|
+
return verifier;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Build a streaming `multipart/form-data` body from text-only parts (used when an OpenAPI
|
|
250
|
+
* multipart endpoint is called without any staged upload fields and no `UploadStore` is active).
|
|
251
|
+
*/
|
|
252
|
+
export function buildStreamingMultipartFromParts(parts) {
|
|
253
|
+
const boundary = `----AirlockBoundary${randomBytes(16).toString('hex')}`;
|
|
254
|
+
const chunks = [];
|
|
255
|
+
for (const part of parts) {
|
|
256
|
+
if (part.kind !== 'text') {
|
|
257
|
+
throw new Error('Cannot stream upload part without an active UploadStore.');
|
|
258
|
+
}
|
|
259
|
+
const header = `--${boundary}\r\n` +
|
|
260
|
+
`Content-Disposition: form-data; name="${escapeMultipartParam(part.name)}"\r\n\r\n`;
|
|
261
|
+
chunks.push(Buffer.from(header, 'utf8'), Buffer.from(part.value, 'utf8'), Buffer.from('\r\n'));
|
|
262
|
+
}
|
|
263
|
+
chunks.push(Buffer.from(`--${boundary}--\r\n`, 'utf8'));
|
|
264
|
+
const totalBytes = chunks.reduce((sum, b) => sum + b.byteLength, 0);
|
|
265
|
+
const nodeStream = Readable.from(chunks);
|
|
266
|
+
return {
|
|
267
|
+
stream: Readable.toWeb(nodeStream),
|
|
268
|
+
contentType: `multipart/form-data; boundary=${boundary}`,
|
|
269
|
+
contentLength: totalBytes,
|
|
270
|
+
close: () => {
|
|
271
|
+
if (!nodeStream.destroyed)
|
|
272
|
+
nodeStream.destroy();
|
|
273
|
+
},
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
export class UploadStore {
|
|
277
|
+
config;
|
|
278
|
+
resolvedDir;
|
|
279
|
+
canonicalDir = '';
|
|
280
|
+
/** True when this store created its own unique temp dir (no explicit `uploads.dir` configured). */
|
|
281
|
+
ownedTempDir;
|
|
282
|
+
/** Kernel-held SQLite EXCLUSIVE lock handle for an explicitly configured `uploads.dir`. */
|
|
283
|
+
ownerLockDb;
|
|
284
|
+
runtimeBaseUrl;
|
|
285
|
+
streamIdleTimeoutMs;
|
|
286
|
+
uploads = new Map();
|
|
287
|
+
/** sha256(rawUploadToken) -> uploadId */
|
|
288
|
+
uploadTokens = new Map();
|
|
289
|
+
/** sha256(rawDownloadToken) -> DownloadTicket */
|
|
290
|
+
downloadTokens = new Map();
|
|
291
|
+
/** Live bytes reserved by concurrent in-flight upload streams against `max_total_bytes`. */
|
|
292
|
+
inFlightReservedBytes = 0;
|
|
293
|
+
/** Active download / binary / multipart streams so disable/stop can abort them and keep accounting accurate until their fds close. */
|
|
294
|
+
activeTransfers = new Set();
|
|
295
|
+
/** Bytes held by aborted/unlinked transfers whose OS file descriptors have not finished closing yet. */
|
|
296
|
+
drainingTransferBytes = 0;
|
|
297
|
+
sweepTimer;
|
|
298
|
+
dirReady = false;
|
|
299
|
+
constructor(config, runtimeBaseUrl = 'http://127.0.0.1:4111', options = {}) {
|
|
300
|
+
this.config = config ?? UploadsConfig.parse({});
|
|
301
|
+
this.ownedTempDir = !this.config.dir;
|
|
302
|
+
this.resolvedDir = this.config.dir ? resolve(this.config.dir) : '';
|
|
303
|
+
this.runtimeBaseUrl = stripTrailingSlash(runtimeBaseUrl);
|
|
304
|
+
this.streamIdleTimeoutMs = options.streamIdleTimeoutMs ?? DEFAULT_STREAM_IDLE_TIMEOUT_MS;
|
|
305
|
+
if (this.config.enabled) {
|
|
306
|
+
this.ensureDir();
|
|
307
|
+
this.startSweeper();
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
isEnabled() {
|
|
311
|
+
return this.config.enabled;
|
|
312
|
+
}
|
|
313
|
+
getConfig() {
|
|
314
|
+
return this.config;
|
|
315
|
+
}
|
|
316
|
+
getStagingDir() {
|
|
317
|
+
if (this.config.enabled && !this.dirReady) {
|
|
318
|
+
this.ensureDir();
|
|
319
|
+
}
|
|
320
|
+
return this.resolvedDir;
|
|
321
|
+
}
|
|
322
|
+
setRuntimeBaseUrl(url) {
|
|
323
|
+
this.runtimeBaseUrl = stripTrailingSlash(url);
|
|
324
|
+
}
|
|
325
|
+
getPublicBaseUrl(opts = {}) {
|
|
326
|
+
if (opts.agentPublicUrl) {
|
|
327
|
+
return stripTrailingSlash(opts.agentPublicUrl);
|
|
328
|
+
}
|
|
329
|
+
const allowed = [];
|
|
330
|
+
if (this.config.public_url)
|
|
331
|
+
allowed.push(stripTrailingSlash(this.config.public_url));
|
|
332
|
+
for (const url of this.config.public_urls) {
|
|
333
|
+
const normalized = stripTrailingSlash(url);
|
|
334
|
+
if (!allowed.includes(normalized))
|
|
335
|
+
allowed.push(normalized);
|
|
336
|
+
}
|
|
337
|
+
const requestHost = normalizeRequestHost(opts.requestHost);
|
|
338
|
+
if (requestHost && allowed.length > 0) {
|
|
339
|
+
const matched = allowed.find((candidate) => hostMatchesPublicUrl(candidate, requestHost));
|
|
340
|
+
if (matched)
|
|
341
|
+
return matched;
|
|
342
|
+
}
|
|
343
|
+
return allowed[0] ?? this.runtimeBaseUrl;
|
|
344
|
+
}
|
|
345
|
+
getInternalBaseUrl() {
|
|
346
|
+
return stripTrailingSlash(this.config.internal_url ??
|
|
347
|
+
this.config.public_url ??
|
|
348
|
+
this.config.public_urls[0] ??
|
|
349
|
+
this.runtimeBaseUrl);
|
|
350
|
+
}
|
|
351
|
+
updateConfig(nextConfig) {
|
|
352
|
+
const next = nextConfig ?? UploadsConfig.parse({});
|
|
353
|
+
const wasEnabled = this.config.enabled;
|
|
354
|
+
if (!wasEnabled && next.enabled) {
|
|
355
|
+
const prevOwned = this.ownedTempDir;
|
|
356
|
+
const prevResolved = this.resolvedDir;
|
|
357
|
+
const prevCanonical = this.canonicalDir;
|
|
358
|
+
const prevDirReady = this.dirReady;
|
|
359
|
+
this.ownedTempDir = !next.dir;
|
|
360
|
+
this.resolvedDir = next.dir ? resolve(next.dir) : '';
|
|
361
|
+
this.canonicalDir = '';
|
|
362
|
+
this.dirReady = false;
|
|
363
|
+
try {
|
|
364
|
+
this.ensureDir();
|
|
365
|
+
}
|
|
366
|
+
catch (err) {
|
|
367
|
+
this.ownedTempDir = prevOwned;
|
|
368
|
+
this.resolvedDir = prevResolved;
|
|
369
|
+
this.canonicalDir = prevCanonical;
|
|
370
|
+
this.dirReady = prevDirReady;
|
|
371
|
+
throw err;
|
|
372
|
+
}
|
|
373
|
+
this.config = next;
|
|
374
|
+
this.startSweeper();
|
|
375
|
+
}
|
|
376
|
+
else if (wasEnabled && !next.enabled) {
|
|
377
|
+
this.config = next;
|
|
378
|
+
this.stopSweeper();
|
|
379
|
+
this.clearAllSync();
|
|
380
|
+
}
|
|
381
|
+
else {
|
|
382
|
+
this.config = next;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Immediately revoke all staged uploads, upload/download tickets, and active transfers for any
|
|
387
|
+
* agent that was removed from config or had `uploads.enabled: false` set while global uploads
|
|
388
|
+
* remain enabled.
|
|
389
|
+
*/
|
|
390
|
+
reconcileAgents(agents) {
|
|
391
|
+
const revokedAgents = new Set();
|
|
392
|
+
const isRevoked = (agentId) => {
|
|
393
|
+
if (!Object.prototype.hasOwnProperty.call(agents, agentId))
|
|
394
|
+
return true;
|
|
395
|
+
const cfg = agents[agentId];
|
|
396
|
+
return !cfg || cfg.uploads?.enabled === false;
|
|
397
|
+
};
|
|
398
|
+
for (const rec of this.uploads.values()) {
|
|
399
|
+
if (isRevoked(rec.agentId))
|
|
400
|
+
revokedAgents.add(rec.agentId);
|
|
401
|
+
}
|
|
402
|
+
for (const ticket of this.downloadTokens.values()) {
|
|
403
|
+
if (isRevoked(ticket.agentId))
|
|
404
|
+
revokedAgents.add(ticket.agentId);
|
|
405
|
+
}
|
|
406
|
+
for (const transfer of this.activeTransfers) {
|
|
407
|
+
if (isRevoked(transfer.agentId))
|
|
408
|
+
revokedAgents.add(transfer.agentId);
|
|
409
|
+
}
|
|
410
|
+
for (const agentId of revokedAgents) {
|
|
411
|
+
this.revokeAgentSync(agentId);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
revokeAgentSync(agentId) {
|
|
415
|
+
for (const transfer of Array.from(this.activeTransfers)) {
|
|
416
|
+
if (transfer.agentId !== agentId)
|
|
417
|
+
continue;
|
|
418
|
+
if (!transfer.draining) {
|
|
419
|
+
transfer.draining = true;
|
|
420
|
+
this.drainingTransferBytes += transfer.bytes;
|
|
421
|
+
}
|
|
422
|
+
transfer.abort();
|
|
423
|
+
}
|
|
424
|
+
for (const [id, rec] of Array.from(this.uploads.entries())) {
|
|
425
|
+
if (rec.agentId === agentId) {
|
|
426
|
+
this.deleteRecordSync(id);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
for (const [tokenHash, ticket] of Array.from(this.downloadTokens.entries())) {
|
|
430
|
+
if (ticket.agentId === agentId) {
|
|
431
|
+
this.downloadTokens.delete(tokenHash);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
prepareUpload(agentId, opts) {
|
|
436
|
+
this.assertEnabled(opts.agentLimits);
|
|
437
|
+
this.sweepExpired();
|
|
438
|
+
const maxBytes = effectiveMaxFileBytes(this.config, opts.agentLimits);
|
|
439
|
+
const maxFiles = effectiveMaxFiles(this.config, opts.agentLimits);
|
|
440
|
+
if (opts.sizeBytes !== undefined) {
|
|
441
|
+
if (!Number.isFinite(opts.sizeBytes) || opts.sizeBytes < 0) {
|
|
442
|
+
throw new Error('size_bytes must be a non-negative number.');
|
|
443
|
+
}
|
|
444
|
+
if (opts.sizeBytes > maxBytes) {
|
|
445
|
+
throw new Error(`Declared file size (${opts.sizeBytes} bytes) exceeds limit of ${maxBytes} bytes.`);
|
|
446
|
+
}
|
|
447
|
+
if (this.totalStoredBytes() + this.inFlightReservedBytes + opts.sizeBytes >
|
|
448
|
+
this.config.max_total_bytes) {
|
|
449
|
+
throw new Error(`Upload would exceed gateway staged upload storage quota (${this.config.max_total_bytes} bytes).`);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
this.assertRecordQuota(agentId, maxFiles, opts.sessionId, false);
|
|
453
|
+
const filename = sanitizeFilename(opts.filename);
|
|
454
|
+
const normalizedProvided = normalizeMimeType(opts.contentType);
|
|
455
|
+
if (opts.contentType && !normalizedProvided) {
|
|
456
|
+
throw new Error(`Invalid content_type: "${opts.contentType}".`);
|
|
457
|
+
}
|
|
458
|
+
const contentType = inferMimeType(filename, normalizedProvided);
|
|
459
|
+
if (!isMimeAllowed(contentType, this.config, opts.agentLimits)) {
|
|
460
|
+
throw new Error(`MIME type "${contentType}" is not allowed for uploads.`);
|
|
461
|
+
}
|
|
462
|
+
// 128-bit capability ID: short (22 base64url chars) yet unguessable across concurrent sessionless threads.
|
|
463
|
+
const id = `upl_${randomBytes(16).toString('base64url')}`;
|
|
464
|
+
const uploadToken = `up_${randomBytes(32).toString('base64url')}`;
|
|
465
|
+
const now = Date.now();
|
|
466
|
+
const expiresAt = now + this.config.ticket_ttl_ms;
|
|
467
|
+
this.ensureDir();
|
|
468
|
+
const diskPath = this.safeDiskPath(id, filename);
|
|
469
|
+
const record = {
|
|
470
|
+
id,
|
|
471
|
+
agentId,
|
|
472
|
+
...(opts.sessionId ? { sessionId: opts.sessionId } : {}),
|
|
473
|
+
status: 'pending',
|
|
474
|
+
filename,
|
|
475
|
+
contentType,
|
|
476
|
+
sizeBytes: 0,
|
|
477
|
+
sha256: '',
|
|
478
|
+
blockSize: STREAM_VERIFY_BLOCK_BYTES,
|
|
479
|
+
blockDigests: Buffer.alloc(0),
|
|
480
|
+
diskPath,
|
|
481
|
+
createdAt: now,
|
|
482
|
+
expiresAt,
|
|
483
|
+
maxBytes,
|
|
484
|
+
allowedMimeTypes: opts.agentLimits?.allowed_mime_types && opts.agentLimits.allowed_mime_types.length > 0
|
|
485
|
+
? opts.agentLimits.allowed_mime_types
|
|
486
|
+
: this.config.allowed_mime_types,
|
|
487
|
+
explicitFilename: Boolean(opts.filename?.trim()),
|
|
488
|
+
explicitContentType: Boolean(normalizedProvided && normalizedProvided !== 'application/octet-stream'),
|
|
489
|
+
inFlightRefs: 0,
|
|
490
|
+
};
|
|
491
|
+
this.uploads.set(id, record);
|
|
492
|
+
this.uploadTokens.set(sha256Hex(uploadToken), id);
|
|
493
|
+
const uploadPath = `/uploads/${uploadToken}`;
|
|
494
|
+
const uploadUrl = `${this.getPublicBaseUrl({
|
|
495
|
+
agentPublicUrl: opts.agentLimits?.public_url,
|
|
496
|
+
requestHost: opts.requestHost,
|
|
497
|
+
})}${uploadPath}`;
|
|
498
|
+
return {
|
|
499
|
+
uploadId: id,
|
|
500
|
+
ref: formatUploadRef(id),
|
|
501
|
+
uploadToken,
|
|
502
|
+
uploadPath,
|
|
503
|
+
uploadUrl,
|
|
504
|
+
method: 'PUT',
|
|
505
|
+
filename,
|
|
506
|
+
contentType,
|
|
507
|
+
expiresAt: new Date(expiresAt).toISOString(),
|
|
508
|
+
maxBytes,
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
async completePresignedUpload(rawToken, input) {
|
|
512
|
+
if (!this.config.enabled) {
|
|
513
|
+
throw new UploadHttpError(404, 'File uploads are disabled.');
|
|
514
|
+
}
|
|
515
|
+
this.sweepExpired();
|
|
516
|
+
const tokenHash = sha256Hex(rawToken);
|
|
517
|
+
const uploadId = this.uploadTokens.get(tokenHash);
|
|
518
|
+
if (!uploadId) {
|
|
519
|
+
throw new UploadHttpError(404, 'Upload URL is invalid, expired, or already used.');
|
|
520
|
+
}
|
|
521
|
+
const record = this.uploads.get(uploadId);
|
|
522
|
+
if (!record) {
|
|
523
|
+
this.uploadTokens.delete(tokenHash);
|
|
524
|
+
throw new UploadHttpError(404, 'Upload URL is invalid, expired, or already used.');
|
|
525
|
+
}
|
|
526
|
+
if (record.expiresAt <= Date.now()) {
|
|
527
|
+
this.uploadTokens.delete(tokenHash);
|
|
528
|
+
this.uploads.delete(uploadId);
|
|
529
|
+
throw new UploadHttpError(410, 'Upload URL has expired.');
|
|
530
|
+
}
|
|
531
|
+
if (record.status !== 'pending') {
|
|
532
|
+
throw new UploadHttpError(409, 'Upload has already been used.');
|
|
533
|
+
}
|
|
534
|
+
// Consume the one-time token atomically before any await so concurrent PUTs cannot race.
|
|
535
|
+
this.uploadTokens.delete(tokenHash);
|
|
536
|
+
record.status = 'uploading';
|
|
537
|
+
try {
|
|
538
|
+
return await this.receiveUploadStream(record, input);
|
|
539
|
+
}
|
|
540
|
+
catch (err) {
|
|
541
|
+
if (this.uploads.get(record.id) === record) {
|
|
542
|
+
this.uploads.delete(record.id);
|
|
543
|
+
}
|
|
544
|
+
await this.removeUploadDir(record.id);
|
|
545
|
+
throw err;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
async createDirectUpload(agentId, input) {
|
|
549
|
+
if (!this.config.enabled || input.agentLimits?.enabled === false) {
|
|
550
|
+
throw new UploadHttpError(404, 'File uploads are disabled.');
|
|
551
|
+
}
|
|
552
|
+
this.sweepExpired();
|
|
553
|
+
const maxBytes = effectiveMaxFileBytes(this.config, input.agentLimits);
|
|
554
|
+
const maxFiles = effectiveMaxFiles(this.config, input.agentLimits);
|
|
555
|
+
this.assertRecordQuota(agentId, maxFiles, input.sessionId, true);
|
|
556
|
+
const id = `upl_${randomBytes(16).toString('base64url')}`;
|
|
557
|
+
const filename = sanitizeFilename(input.filename);
|
|
558
|
+
const isMultipart = isMultipartHeader(input.contentTypeHeader);
|
|
559
|
+
const headerMime = isMultipart ? undefined : normalizeMimeType(input.contentTypeHeader);
|
|
560
|
+
const contentType = inferMimeType(filename, headerMime);
|
|
561
|
+
this.ensureDir();
|
|
562
|
+
const record = {
|
|
563
|
+
id,
|
|
564
|
+
agentId,
|
|
565
|
+
...(input.sessionId ? { sessionId: input.sessionId } : {}),
|
|
566
|
+
status: 'uploading',
|
|
567
|
+
filename,
|
|
568
|
+
contentType,
|
|
569
|
+
sizeBytes: 0,
|
|
570
|
+
sha256: '',
|
|
571
|
+
blockSize: STREAM_VERIFY_BLOCK_BYTES,
|
|
572
|
+
blockDigests: Buffer.alloc(0),
|
|
573
|
+
diskPath: this.safeDiskPath(id, filename),
|
|
574
|
+
createdAt: Date.now(),
|
|
575
|
+
expiresAt: Date.now() + this.config.ttl_ms,
|
|
576
|
+
maxBytes,
|
|
577
|
+
allowedMimeTypes: input.agentLimits?.allowed_mime_types && input.agentLimits.allowed_mime_types.length > 0
|
|
578
|
+
? input.agentLimits.allowed_mime_types
|
|
579
|
+
: this.config.allowed_mime_types,
|
|
580
|
+
explicitFilename: Boolean(input.filename?.trim()),
|
|
581
|
+
explicitContentType: Boolean(headerMime && headerMime !== 'application/octet-stream'),
|
|
582
|
+
inFlightRefs: 0,
|
|
583
|
+
};
|
|
584
|
+
this.uploads.set(id, record);
|
|
585
|
+
try {
|
|
586
|
+
return await this.receiveUploadStream(record, {
|
|
587
|
+
stream: input.stream,
|
|
588
|
+
contentTypeHeader: input.contentTypeHeader,
|
|
589
|
+
contentLength: input.contentLength,
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
catch (err) {
|
|
593
|
+
if (this.uploads.get(record.id) === record) {
|
|
594
|
+
this.uploads.delete(record.id);
|
|
595
|
+
}
|
|
596
|
+
await this.removeUploadDir(record.id);
|
|
597
|
+
throw err;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
getReadyUpload(agentId, uploadId, sessionId) {
|
|
601
|
+
const record = this.uploads.get(uploadId);
|
|
602
|
+
if (!record || !this.ownsUpload(record, agentId, sessionId) || record.status !== 'ready') {
|
|
603
|
+
return undefined;
|
|
604
|
+
}
|
|
605
|
+
if (record.inFlightRefs === 0 && record.expiresAt <= Date.now()) {
|
|
606
|
+
this.deleteRecordSync(record.id);
|
|
607
|
+
return undefined;
|
|
608
|
+
}
|
|
609
|
+
return record;
|
|
610
|
+
}
|
|
611
|
+
getUploadAnyStatus(agentId, uploadId, sessionId) {
|
|
612
|
+
const record = this.uploads.get(uploadId);
|
|
613
|
+
if (!record || !this.ownsUpload(record, agentId, sessionId))
|
|
614
|
+
return undefined;
|
|
615
|
+
// Never evict an actively streaming or pinned record mid-flight.
|
|
616
|
+
if (record.status !== 'uploading' &&
|
|
617
|
+
record.inFlightRefs === 0 &&
|
|
618
|
+
record.expiresAt <= Date.now()) {
|
|
619
|
+
this.deleteRecordSync(record.id);
|
|
620
|
+
return undefined;
|
|
621
|
+
}
|
|
622
|
+
return record;
|
|
623
|
+
}
|
|
624
|
+
deleteUpload(agentId, uploadId, sessionId) {
|
|
625
|
+
const record = this.uploads.get(uploadId);
|
|
626
|
+
if (!record || !this.ownsUpload(record, agentId, sessionId))
|
|
627
|
+
return false;
|
|
628
|
+
if (record.status === 'uploading') {
|
|
629
|
+
throw new Error(`Upload "${uploadId}" is currently uploading and cannot be deleted yet.`);
|
|
630
|
+
}
|
|
631
|
+
if (record.inFlightRefs > 0) {
|
|
632
|
+
throw new Error(`Upload "${uploadId}" is currently in use by an active tool call or download.`);
|
|
633
|
+
}
|
|
634
|
+
this.deleteRecordSync(uploadId);
|
|
635
|
+
return true;
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Pin one or more ready uploads for the duration of a tool call (including any HITL approval
|
|
639
|
+
* wait) so TTL cleanup never evicts a file before execution completes.
|
|
640
|
+
*/
|
|
641
|
+
pin(agentId, uploadIds, sessionId) {
|
|
642
|
+
const uniqueIds = Array.from(new Set(uploadIds));
|
|
643
|
+
const pinned = [];
|
|
644
|
+
for (const id of uniqueIds) {
|
|
645
|
+
const rec = this.getReadyUpload(agentId, id, sessionId);
|
|
646
|
+
if (rec) {
|
|
647
|
+
rec.inFlightRefs += 1;
|
|
648
|
+
pinned.push(rec);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
let released = false;
|
|
652
|
+
return () => {
|
|
653
|
+
if (released)
|
|
654
|
+
return;
|
|
655
|
+
released = true;
|
|
656
|
+
for (const rec of pinned) {
|
|
657
|
+
rec.inFlightRefs = Math.max(0, rec.inFlightRefs - 1);
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* Read staged bytes from a verified non-symlink regular file descriptor and confirm the SHA-256
|
|
663
|
+
* digest matches the staged record, tracking the pending read against concurrent revocation.
|
|
664
|
+
*/
|
|
665
|
+
async readBytes(agentId, uploadId, sessionId) {
|
|
666
|
+
if (!this.config.enabled) {
|
|
667
|
+
throw new Error('File uploads are disabled.');
|
|
668
|
+
}
|
|
669
|
+
const record = this.getReadyUpload(agentId, uploadId, sessionId);
|
|
670
|
+
if (!record) {
|
|
671
|
+
throw new Error(`Upload "${uploadId}" not found, not yet uploaded, or expired.`);
|
|
672
|
+
}
|
|
673
|
+
let aborted = false;
|
|
674
|
+
const { finish: finishFd } = this.registerActiveTransfer(agentId, record.sizeBytes, () => {
|
|
675
|
+
aborted = true;
|
|
676
|
+
});
|
|
677
|
+
record.inFlightRefs += 1;
|
|
678
|
+
let fh;
|
|
679
|
+
try {
|
|
680
|
+
fh = await this.openVerifiedFile(record);
|
|
681
|
+
if (aborted || !this.config.enabled || this.uploads.get(record.id) !== record) {
|
|
682
|
+
throw new Error(`Upload "${uploadId}" is no longer available.`);
|
|
683
|
+
}
|
|
684
|
+
const bytes = await fh.readFile();
|
|
685
|
+
await fh.close().catch(() => { });
|
|
686
|
+
fh = undefined;
|
|
687
|
+
if (aborted || !this.config.enabled || this.uploads.get(record.id) !== record) {
|
|
688
|
+
throw new Error(`Upload "${uploadId}" is no longer available.`);
|
|
689
|
+
}
|
|
690
|
+
const actualHash = createHash('sha256').update(bytes).digest('hex');
|
|
691
|
+
if (actualHash !== record.sha256) {
|
|
692
|
+
throw new Error(`Staged upload "${uploadId}" failed SHA-256 integrity verification.`);
|
|
693
|
+
}
|
|
694
|
+
return { record, bytes };
|
|
695
|
+
}
|
|
696
|
+
finally {
|
|
697
|
+
if (fh)
|
|
698
|
+
await fh.close().catch(() => { });
|
|
699
|
+
record.inFlightRefs = Math.max(0, record.inFlightRefs - 1);
|
|
700
|
+
finishFd();
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Open a verified non-symlink file descriptor as a digest-verifying Web ReadableStream for
|
|
705
|
+
* zero-buffer raw binary HTTP/OpenAPI delivery. Tracks the transfer across the async open and
|
|
706
|
+
* pins the record until the descriptor closes.
|
|
707
|
+
*/
|
|
708
|
+
async openVerifiedStream(agentId, uploadId, sessionId) {
|
|
709
|
+
if (!this.config.enabled) {
|
|
710
|
+
throw new Error('File uploads are disabled.');
|
|
711
|
+
}
|
|
712
|
+
const record = this.getReadyUpload(agentId, uploadId, sessionId);
|
|
713
|
+
if (!record) {
|
|
714
|
+
throw new Error(`Upload "${uploadId}" not found, not yet uploaded, or expired.`);
|
|
715
|
+
}
|
|
716
|
+
let aborted = false;
|
|
717
|
+
const streamRef = {};
|
|
718
|
+
const { finish: finishFd } = this.registerActiveTransfer(agentId, record.sizeBytes, () => {
|
|
719
|
+
aborted = true;
|
|
720
|
+
if (streamRef.current && !streamRef.current.destroyed) {
|
|
721
|
+
streamRef.current.destroy(new Error('Staged file uploads were disabled.'));
|
|
722
|
+
}
|
|
723
|
+
});
|
|
724
|
+
record.inFlightRefs += 1;
|
|
725
|
+
let fh;
|
|
726
|
+
try {
|
|
727
|
+
fh = await this.openVerifiedFile(record);
|
|
728
|
+
}
|
|
729
|
+
catch (err) {
|
|
730
|
+
record.inFlightRefs = Math.max(0, record.inFlightRefs - 1);
|
|
731
|
+
finishFd();
|
|
732
|
+
throw err;
|
|
733
|
+
}
|
|
734
|
+
if (aborted || !this.config.enabled || this.uploads.get(record.id) !== record) {
|
|
735
|
+
record.inFlightRefs = Math.max(0, record.inFlightRefs - 1);
|
|
736
|
+
await fh.close().catch(() => { });
|
|
737
|
+
finishFd();
|
|
738
|
+
throw new Error(`Upload "${uploadId}" is no longer available.`);
|
|
739
|
+
}
|
|
740
|
+
const nodeStream = createDigestVerifyingStream(fh, record, () => {
|
|
741
|
+
record.inFlightRefs = Math.max(0, record.inFlightRefs - 1);
|
|
742
|
+
}, finishFd);
|
|
743
|
+
streamRef.current = nodeStream;
|
|
744
|
+
return {
|
|
745
|
+
record,
|
|
746
|
+
stream: Readable.toWeb(nodeStream),
|
|
747
|
+
close: () => {
|
|
748
|
+
if (!nodeStream.destroyed && !nodeStream.readableEnded)
|
|
749
|
+
nodeStream.destroy();
|
|
750
|
+
},
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* Stream a `multipart/form-data` request directly from verified, already-open `O_NOFOLLOW` file
|
|
755
|
+
* descriptors without path reopens or RAM buffering, verifying each file's exact size and
|
|
756
|
+
* SHA-256 digest during transmission and tracking pending opens/transfers until every descriptor
|
|
757
|
+
* closes.
|
|
758
|
+
*/
|
|
759
|
+
async openStreamingMultipart(agentId, parts, sessionId) {
|
|
760
|
+
if (!this.config.enabled) {
|
|
761
|
+
throw new Error('File uploads are disabled.');
|
|
762
|
+
}
|
|
763
|
+
const boundary = `----AirlockBoundary${randomBytes(16).toString('hex')}`;
|
|
764
|
+
const prepared = [];
|
|
765
|
+
const openedHandles = [];
|
|
766
|
+
const pinnedRecords = [];
|
|
767
|
+
let aborted = false;
|
|
768
|
+
let activePartStream;
|
|
769
|
+
const nodeStreamRef = {};
|
|
770
|
+
let cleaned = false;
|
|
771
|
+
const { entry: transferEntry, finish: finishFd } = this.registerActiveTransfer(agentId, 0, () => {
|
|
772
|
+
aborted = true;
|
|
773
|
+
if (activePartStream && !activePartStream.destroyed) {
|
|
774
|
+
activePartStream.destroy(new Error('Staged file uploads were disabled.'));
|
|
775
|
+
}
|
|
776
|
+
if (nodeStreamRef.current && !nodeStreamRef.current.destroyed) {
|
|
777
|
+
nodeStreamRef.current.destroy(new Error('Staged file uploads were disabled.'));
|
|
778
|
+
}
|
|
779
|
+
});
|
|
780
|
+
const releaseAll = async () => {
|
|
781
|
+
if (cleaned)
|
|
782
|
+
return;
|
|
783
|
+
cleaned = true;
|
|
784
|
+
for (const rec of pinnedRecords) {
|
|
785
|
+
rec.inFlightRefs = Math.max(0, rec.inFlightRefs - 1);
|
|
786
|
+
}
|
|
787
|
+
await Promise.allSettled(openedHandles.map((fh) => fh.close()));
|
|
788
|
+
finishFd();
|
|
789
|
+
};
|
|
790
|
+
try {
|
|
791
|
+
for (const part of parts) {
|
|
792
|
+
if (aborted || !this.config.enabled) {
|
|
793
|
+
throw new Error('File uploads were disabled before transfer started.');
|
|
794
|
+
}
|
|
795
|
+
if (part.kind === 'text') {
|
|
796
|
+
const header = Buffer.from(`--${boundary}\r\n` +
|
|
797
|
+
`Content-Disposition: form-data; name="${escapeMultipartParam(part.name)}"\r\n\r\n`, 'utf8');
|
|
798
|
+
const body = Buffer.from(part.value, 'utf8');
|
|
799
|
+
prepared.push({ kind: 'text', header, body });
|
|
800
|
+
}
|
|
801
|
+
else {
|
|
802
|
+
const record = this.getReadyUpload(agentId, part.uploadId, sessionId);
|
|
803
|
+
if (!record) {
|
|
804
|
+
throw new Error(`Upload "${part.uploadId}" not found, not yet uploaded, or expired.`);
|
|
805
|
+
}
|
|
806
|
+
// Account and pin BEFORE awaiting open so concurrent disable/revoke tracks this handle.
|
|
807
|
+
transferEntry.bytes += record.sizeBytes;
|
|
808
|
+
record.inFlightRefs += 1;
|
|
809
|
+
pinnedRecords.push(record);
|
|
810
|
+
const fh = await this.openVerifiedFile(record);
|
|
811
|
+
openedHandles.push(fh);
|
|
812
|
+
if (aborted || !this.config.enabled || this.uploads.get(record.id) !== record) {
|
|
813
|
+
throw new Error(`Upload "${part.uploadId}" is no longer available.`);
|
|
814
|
+
}
|
|
815
|
+
const header = Buffer.from(`--${boundary}\r\n` +
|
|
816
|
+
`Content-Disposition: form-data; name="${escapeMultipartParam(part.name)}"; filename="${escapeMultipartParam(record.filename)}"\r\n` +
|
|
817
|
+
`Content-Type: ${record.contentType}\r\n\r\n`, 'utf8');
|
|
818
|
+
prepared.push({ kind: 'upload', header, record, fh });
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
if (aborted || !this.config.enabled) {
|
|
822
|
+
throw new Error('File uploads were disabled before transfer started.');
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
catch (err) {
|
|
826
|
+
await releaseAll();
|
|
827
|
+
throw err;
|
|
828
|
+
}
|
|
829
|
+
const crlf = Buffer.from('\r\n');
|
|
830
|
+
const closing = Buffer.from(`--${boundary}--\r\n`, 'utf8');
|
|
831
|
+
let contentLength = closing.byteLength;
|
|
832
|
+
for (const part of prepared) {
|
|
833
|
+
contentLength +=
|
|
834
|
+
part.header.byteLength +
|
|
835
|
+
(part.kind === 'text' ? part.body.byteLength : part.record.sizeBytes) +
|
|
836
|
+
crlf.byteLength;
|
|
837
|
+
}
|
|
838
|
+
const cleanup = () => {
|
|
839
|
+
void releaseAll();
|
|
840
|
+
};
|
|
841
|
+
async function* generate() {
|
|
842
|
+
try {
|
|
843
|
+
for (const part of prepared) {
|
|
844
|
+
yield part.header;
|
|
845
|
+
if (part.kind === 'text') {
|
|
846
|
+
if (part.body.byteLength > 0)
|
|
847
|
+
yield part.body;
|
|
848
|
+
}
|
|
849
|
+
else {
|
|
850
|
+
const verifiedStream = createDigestVerifyingStream(part.fh, part.record);
|
|
851
|
+
activePartStream = verifiedStream;
|
|
852
|
+
try {
|
|
853
|
+
for await (const chunk of verifiedStream) {
|
|
854
|
+
yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
finally {
|
|
858
|
+
activePartStream = undefined;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
yield crlf;
|
|
862
|
+
}
|
|
863
|
+
yield closing;
|
|
864
|
+
}
|
|
865
|
+
finally {
|
|
866
|
+
cleanup();
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
const nodeStream = Readable.from(generate());
|
|
870
|
+
nodeStreamRef.current = nodeStream;
|
|
871
|
+
nodeStream.once('close', cleanup);
|
|
872
|
+
nodeStream.once('error', cleanup);
|
|
873
|
+
return {
|
|
874
|
+
stream: Readable.toWeb(nodeStream),
|
|
875
|
+
contentType: `multipart/form-data; boundary=${boundary}`,
|
|
876
|
+
contentLength,
|
|
877
|
+
close: () => {
|
|
878
|
+
if (!nodeStream.destroyed && !nodeStream.readableEnded)
|
|
879
|
+
nodeStream.destroy();
|
|
880
|
+
cleanup();
|
|
881
|
+
},
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
resolveDiskPath(agentId, uploadId, pathPrefix, sessionId) {
|
|
885
|
+
const record = this.getReadyUpload(agentId, uploadId, sessionId);
|
|
886
|
+
if (!record) {
|
|
887
|
+
throw new Error(`Upload "${uploadId}" not found, not yet uploaded, or expired.`);
|
|
888
|
+
}
|
|
889
|
+
this.assertContainedPath(record.diskPath);
|
|
890
|
+
if (pathPrefix) {
|
|
891
|
+
const trimmed = pathPrefix.replace(/\/+$/, '');
|
|
892
|
+
return { record, diskPath: `${trimmed}/${record.id}/${record.filename}` };
|
|
893
|
+
}
|
|
894
|
+
return { record, diskPath: record.diskPath };
|
|
895
|
+
}
|
|
896
|
+
mintDownloadUrl(agentId, uploadId, sessionId) {
|
|
897
|
+
const record = this.getReadyUpload(agentId, uploadId, sessionId);
|
|
898
|
+
if (!record) {
|
|
899
|
+
throw new Error(`Upload "${uploadId}" not found, not yet uploaded, or expired.`);
|
|
900
|
+
}
|
|
901
|
+
const token = `dl_${randomBytes(32).toString('base64url')}`;
|
|
902
|
+
const expiresAt = Date.now() + this.config.download_ttl_ms;
|
|
903
|
+
const MAX_DOWNLOAD_TOKENS = 10_000;
|
|
904
|
+
if (this.downloadTokens.size >= MAX_DOWNLOAD_TOKENS) {
|
|
905
|
+
const now = Date.now();
|
|
906
|
+
for (const [k, ticket] of this.downloadTokens) {
|
|
907
|
+
if (ticket.expiresAt <= now)
|
|
908
|
+
this.downloadTokens.delete(k);
|
|
909
|
+
}
|
|
910
|
+
if (this.downloadTokens.size >= MAX_DOWNLOAD_TOKENS) {
|
|
911
|
+
const oldest = this.downloadTokens.keys().next().value;
|
|
912
|
+
if (oldest !== undefined)
|
|
913
|
+
this.downloadTokens.delete(oldest);
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
this.downloadTokens.set(sha256Hex(token), {
|
|
917
|
+
uploadId: record.id,
|
|
918
|
+
agentId,
|
|
919
|
+
...(sessionId ? { sessionId } : {}),
|
|
920
|
+
expiresAt,
|
|
921
|
+
});
|
|
922
|
+
const downloadPath = `/uploads/dl/${token}`;
|
|
923
|
+
const downloadUrl = `${this.getInternalBaseUrl()}${downloadPath}`;
|
|
924
|
+
return {
|
|
925
|
+
record,
|
|
926
|
+
downloadToken: token,
|
|
927
|
+
downloadUrl,
|
|
928
|
+
downloadPath,
|
|
929
|
+
expiresAt: new Date(expiresAt).toISOString(),
|
|
930
|
+
};
|
|
931
|
+
}
|
|
932
|
+
revokeDownloadToken(rawToken) {
|
|
933
|
+
this.downloadTokens.delete(sha256Hex(rawToken));
|
|
934
|
+
}
|
|
935
|
+
async openDownload(rawToken, consume) {
|
|
936
|
+
if (!this.config.enabled)
|
|
937
|
+
return undefined;
|
|
938
|
+
const tokenHash = sha256Hex(rawToken);
|
|
939
|
+
const ticket = this.downloadTokens.get(tokenHash);
|
|
940
|
+
if (!ticket)
|
|
941
|
+
return undefined;
|
|
942
|
+
if (ticket.expiresAt <= Date.now()) {
|
|
943
|
+
this.downloadTokens.delete(tokenHash);
|
|
944
|
+
return undefined;
|
|
945
|
+
}
|
|
946
|
+
const record = this.getReadyUpload(ticket.agentId, ticket.uploadId, ticket.sessionId);
|
|
947
|
+
if (!record) {
|
|
948
|
+
this.downloadTokens.delete(tokenHash);
|
|
949
|
+
return undefined;
|
|
950
|
+
}
|
|
951
|
+
let aborted = false;
|
|
952
|
+
const streamRef = {};
|
|
953
|
+
const { finish: finishFd } = this.registerActiveTransfer(ticket.agentId, record.sizeBytes, () => {
|
|
954
|
+
aborted = true;
|
|
955
|
+
if (streamRef.current && !streamRef.current.destroyed) {
|
|
956
|
+
streamRef.current.destroy(new Error('Staged file uploads were disabled.'));
|
|
957
|
+
}
|
|
958
|
+
});
|
|
959
|
+
record.inFlightRefs += 1;
|
|
960
|
+
let fh;
|
|
961
|
+
try {
|
|
962
|
+
fh = await this.openVerifiedFile(record);
|
|
963
|
+
}
|
|
964
|
+
catch {
|
|
965
|
+
record.inFlightRefs = Math.max(0, record.inFlightRefs - 1);
|
|
966
|
+
finishFd();
|
|
967
|
+
this.downloadTokens.delete(tokenHash);
|
|
968
|
+
return undefined;
|
|
969
|
+
}
|
|
970
|
+
// Re-check store state, record ownership, and ticket atomically after async open so concurrent
|
|
971
|
+
// disable/revocation or a racing GET can never stream an invalid or unlinked descriptor.
|
|
972
|
+
if (aborted ||
|
|
973
|
+
!this.config.enabled ||
|
|
974
|
+
this.uploads.get(record.id) !== record ||
|
|
975
|
+
!this.downloadTokens.has(tokenHash)) {
|
|
976
|
+
record.inFlightRefs = Math.max(0, record.inFlightRefs - 1);
|
|
977
|
+
await fh.close().catch(() => { });
|
|
978
|
+
finishFd();
|
|
979
|
+
return undefined;
|
|
980
|
+
}
|
|
981
|
+
if (!consume) {
|
|
982
|
+
record.inFlightRefs = Math.max(0, record.inFlightRefs - 1);
|
|
983
|
+
await fh.close().catch(() => { });
|
|
984
|
+
finishFd();
|
|
985
|
+
return { record };
|
|
986
|
+
}
|
|
987
|
+
this.downloadTokens.delete(tokenHash);
|
|
988
|
+
const stream = createDigestVerifyingStream(fh, record, () => {
|
|
989
|
+
record.inFlightRefs = Math.max(0, record.inFlightRefs - 1);
|
|
990
|
+
}, finishFd);
|
|
991
|
+
streamRef.current = stream;
|
|
992
|
+
return { record, stream };
|
|
993
|
+
}
|
|
994
|
+
sweepExpired() {
|
|
995
|
+
const now = Date.now();
|
|
996
|
+
for (const [tokenHash, uploadId] of this.uploadTokens.entries()) {
|
|
997
|
+
const rec = this.uploads.get(uploadId);
|
|
998
|
+
if (!rec || rec.status !== 'pending' || rec.expiresAt <= now) {
|
|
999
|
+
this.uploadTokens.delete(tokenHash);
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
for (const [tokenHash, ticket] of this.downloadTokens.entries()) {
|
|
1003
|
+
if (ticket.expiresAt <= now || !this.uploads.has(ticket.uploadId)) {
|
|
1004
|
+
this.downloadTokens.delete(tokenHash);
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
for (const [id, rec] of this.uploads.entries()) {
|
|
1008
|
+
if (rec.status === 'uploading' || rec.inFlightRefs > 0)
|
|
1009
|
+
continue;
|
|
1010
|
+
if (rec.expiresAt <= now) {
|
|
1011
|
+
this.deleteRecordSync(id);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
async stop() {
|
|
1016
|
+
this.stopSweeper();
|
|
1017
|
+
this.clearAllSync();
|
|
1018
|
+
await Promise.resolve();
|
|
1019
|
+
}
|
|
1020
|
+
assertEnabled(agentLimits) {
|
|
1021
|
+
if (!this.config.enabled || agentLimits?.enabled === false) {
|
|
1022
|
+
throw new Error('File uploads are disabled.');
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
ownsUpload(record, agentId, sessionId) {
|
|
1026
|
+
return record.agentId === agentId && record.sessionId === sessionId;
|
|
1027
|
+
}
|
|
1028
|
+
countAgentUploads(agentId, sessionId) {
|
|
1029
|
+
let count = 0;
|
|
1030
|
+
for (const rec of this.uploads.values()) {
|
|
1031
|
+
if (this.ownsUpload(rec, agentId, sessionId))
|
|
1032
|
+
count += 1;
|
|
1033
|
+
}
|
|
1034
|
+
return count;
|
|
1035
|
+
}
|
|
1036
|
+
countAllAgentUploads(agentId) {
|
|
1037
|
+
let count = 0;
|
|
1038
|
+
for (const rec of this.uploads.values()) {
|
|
1039
|
+
if (rec.agentId === agentId)
|
|
1040
|
+
count += 1;
|
|
1041
|
+
}
|
|
1042
|
+
return count;
|
|
1043
|
+
}
|
|
1044
|
+
assertRecordQuota(agentId, maxFiles, sessionId, httpError) {
|
|
1045
|
+
const fail = (message) => {
|
|
1046
|
+
if (httpError)
|
|
1047
|
+
throw new UploadHttpError(429, message);
|
|
1048
|
+
throw new Error(message);
|
|
1049
|
+
};
|
|
1050
|
+
const globalCap = Math.max(MIN_GLOBAL_RECORD_CAP, this.config.max_files_per_agent * 20);
|
|
1051
|
+
if (this.uploads.size >= globalCap) {
|
|
1052
|
+
fail(`Gateway active staged upload record cap reached (${globalCap}). Delete unused uploads or wait for expiry.`);
|
|
1053
|
+
}
|
|
1054
|
+
const activeInScope = this.countAgentUploads(agentId, sessionId);
|
|
1055
|
+
if (activeInScope >= maxFiles) {
|
|
1056
|
+
fail(`Agent "${agentId}" already has ${activeInScope} active staged upload(s) (limit: ${maxFiles}). Delete an unused upload or wait for expiry.`);
|
|
1057
|
+
}
|
|
1058
|
+
// Always bound total active records per agent across both sessioned and sessionless callers.
|
|
1059
|
+
const aggregateCap = maxFiles * SESSION_AGENT_RECORD_MULTIPLIER;
|
|
1060
|
+
const totalForAgent = this.countAllAgentUploads(agentId);
|
|
1061
|
+
if (totalForAgent >= aggregateCap) {
|
|
1062
|
+
fail(`Agent "${agentId}" already has ${totalForAgent} active staged upload(s) across all sessions (limit: ${aggregateCap}). Delete unused uploads or wait for expiry.`);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
totalStoredBytes() {
|
|
1066
|
+
let total = this.drainingTransferBytes;
|
|
1067
|
+
for (const rec of this.uploads.values()) {
|
|
1068
|
+
if (rec.status === 'ready')
|
|
1069
|
+
total += rec.sizeBytes;
|
|
1070
|
+
}
|
|
1071
|
+
return total;
|
|
1072
|
+
}
|
|
1073
|
+
registerActiveTransfer(agentId, bytes, abort) {
|
|
1074
|
+
const entry = { agentId, bytes, draining: false, abort };
|
|
1075
|
+
this.activeTransfers.add(entry);
|
|
1076
|
+
let finished = false;
|
|
1077
|
+
return {
|
|
1078
|
+
entry,
|
|
1079
|
+
finish: () => {
|
|
1080
|
+
if (finished)
|
|
1081
|
+
return;
|
|
1082
|
+
finished = true;
|
|
1083
|
+
this.activeTransfers.delete(entry);
|
|
1084
|
+
if (entry.draining) {
|
|
1085
|
+
entry.draining = false;
|
|
1086
|
+
this.drainingTransferBytes = Math.max(0, this.drainingTransferBytes - entry.bytes);
|
|
1087
|
+
}
|
|
1088
|
+
},
|
|
1089
|
+
};
|
|
1090
|
+
}
|
|
1091
|
+
tryReserveBytes(delta) {
|
|
1092
|
+
if (delta <= 0)
|
|
1093
|
+
return true;
|
|
1094
|
+
if (this.totalStoredBytes() + this.inFlightReservedBytes + delta >
|
|
1095
|
+
this.config.max_total_bytes) {
|
|
1096
|
+
return false;
|
|
1097
|
+
}
|
|
1098
|
+
this.inFlightReservedBytes += delta;
|
|
1099
|
+
return true;
|
|
1100
|
+
}
|
|
1101
|
+
releaseReservedBytes(delta) {
|
|
1102
|
+
if (delta <= 0)
|
|
1103
|
+
return;
|
|
1104
|
+
this.inFlightReservedBytes = Math.max(0, this.inFlightReservedBytes - delta);
|
|
1105
|
+
}
|
|
1106
|
+
ownerLeasePath() {
|
|
1107
|
+
return join(this.resolvedDir, OWNER_LOCK_FILENAME);
|
|
1108
|
+
}
|
|
1109
|
+
acquireOwnerLockOrThrow() {
|
|
1110
|
+
if (ACTIVE_OWNED_DIRS.has(this.canonicalDir)) {
|
|
1111
|
+
throw new Error(`Upload staging directory "${this.resolvedDir}" is already owned by another active Airlock instance in this process. Configure a separate uploads.dir or omit uploads.dir for an isolated temporary directory.`);
|
|
1112
|
+
}
|
|
1113
|
+
// Acquire an OS-kernel-enforced exclusive lock for the entire ownership lifetime via SQLite's
|
|
1114
|
+
// EXCLUSIVE locking mode (POSIX fcntl F_WRLCK / Windows LockFileEx). The kernel guarantees at
|
|
1115
|
+
// most one process/container owns the staging directory concurrently and releases the lock
|
|
1116
|
+
// automatically on process exit or crash (SIGKILL/OOM).
|
|
1117
|
+
const lockPath = this.ownerLeasePath();
|
|
1118
|
+
let db;
|
|
1119
|
+
try {
|
|
1120
|
+
// Short busy timeout (50ms) resolves transient simultaneous-startup SHARED-lock collisions
|
|
1121
|
+
// deterministically (exactly one starter wins), while still failing promptly against any
|
|
1122
|
+
// live owner holding the permanent EXCLUSIVE lock.
|
|
1123
|
+
db = new Database(lockPath, { timeout: 50 });
|
|
1124
|
+
db.pragma('locking_mode = EXCLUSIVE');
|
|
1125
|
+
// Acquire the permanent EXCLUSIVE lock and check whether a shutting-down temp-dir owner
|
|
1126
|
+
// already retired this lock inode before unlinking it. Checking on the same SQLite handle
|
|
1127
|
+
// avoids opening/closing a second descriptor (which would drop POSIX fcntl locks).
|
|
1128
|
+
db.exec('BEGIN EXCLUSIVE; CREATE TABLE IF NOT EXISTS owner_lock_v2 (id INTEGER PRIMARY KEY, pid INTEGER, retired INTEGER NOT NULL DEFAULT 0);');
|
|
1129
|
+
const existing = db.prepare('SELECT retired FROM owner_lock_v2 WHERE id = 1').get();
|
|
1130
|
+
if (existing?.retired === 1) {
|
|
1131
|
+
db.exec('ROLLBACK;');
|
|
1132
|
+
const staleErr = new Error('Ownership lock file was retired during directory teardown.');
|
|
1133
|
+
staleErr.code = 'SQLITE_BUSY';
|
|
1134
|
+
throw staleErr;
|
|
1135
|
+
}
|
|
1136
|
+
db.prepare('INSERT OR REPLACE INTO owner_lock_v2 (id, pid, retired) VALUES (1, ?, 0)').run(process.pid);
|
|
1137
|
+
db.exec('COMMIT;');
|
|
1138
|
+
}
|
|
1139
|
+
catch (err) {
|
|
1140
|
+
try {
|
|
1141
|
+
db?.close();
|
|
1142
|
+
}
|
|
1143
|
+
catch {
|
|
1144
|
+
// Ignore close error on failed lock
|
|
1145
|
+
}
|
|
1146
|
+
const code = err.code ?? '';
|
|
1147
|
+
if (code === 'SQLITE_BUSY' || code === 'SQLITE_LOCKED') {
|
|
1148
|
+
throw new Error(`Upload staging directory "${this.resolvedDir}" is already owned by another active Airlock instance. Configure a separate uploads.dir or omit uploads.dir for an isolated temporary directory.`, { cause: err });
|
|
1149
|
+
}
|
|
1150
|
+
throw new Error(`Failed to acquire exclusive ownership lock on upload staging directory "${this.resolvedDir}": ${err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
1151
|
+
}
|
|
1152
|
+
this.ownerLockDb = db;
|
|
1153
|
+
ACTIVE_OWNED_DIRS.add(this.canonicalDir);
|
|
1154
|
+
}
|
|
1155
|
+
releaseOwnerLease() {
|
|
1156
|
+
if (this.canonicalDir) {
|
|
1157
|
+
ACTIVE_OWNED_DIRS.delete(this.canonicalDir);
|
|
1158
|
+
}
|
|
1159
|
+
if (!this.ownerLockDb)
|
|
1160
|
+
return;
|
|
1161
|
+
const db = this.ownerLockDb;
|
|
1162
|
+
this.ownerLockDb = undefined;
|
|
1163
|
+
try {
|
|
1164
|
+
db.close();
|
|
1165
|
+
}
|
|
1166
|
+
catch {
|
|
1167
|
+
// Best-effort release
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
ensureDir() {
|
|
1171
|
+
if (this.dirReady)
|
|
1172
|
+
return;
|
|
1173
|
+
if (this.ownedTempDir) {
|
|
1174
|
+
// Every store without an explicit uploads.dir gets its own unique temp directory AND acquires
|
|
1175
|
+
// the same OS-enforced exclusive lock so another process explicitly targeting this path
|
|
1176
|
+
// cannot claim ownership or sweep live files.
|
|
1177
|
+
this.resolvedDir = resolve(mkdtempSync(join(tmpdir(), 'airlock-uploads-')));
|
|
1178
|
+
this.canonicalDir = realpathSync(this.resolvedDir);
|
|
1179
|
+
this.acquireOwnerLockOrThrow();
|
|
1180
|
+
}
|
|
1181
|
+
else {
|
|
1182
|
+
mkdirSync(this.resolvedDir, { recursive: true, mode: 0o700 });
|
|
1183
|
+
this.canonicalDir = realpathSync(this.resolvedDir);
|
|
1184
|
+
// Require OS-enforced exclusive directory ownership before accepting uploads or reaping orphans.
|
|
1185
|
+
this.acquireOwnerLockOrThrow();
|
|
1186
|
+
this.cleanupOrphanedEntriesFromDeadOwner();
|
|
1187
|
+
}
|
|
1188
|
+
this.dirReady = true;
|
|
1189
|
+
}
|
|
1190
|
+
cleanupOrphanedEntriesFromDeadOwner() {
|
|
1191
|
+
try {
|
|
1192
|
+
const entries = readdirSync(this.resolvedDir);
|
|
1193
|
+
for (const name of entries) {
|
|
1194
|
+
const isManaged = (UPLOAD_ID_PATTERN.test(name) && !this.uploads.has(name)) || name.startsWith('.tmp-');
|
|
1195
|
+
if (!isManaged)
|
|
1196
|
+
continue;
|
|
1197
|
+
const fullPath = join(this.resolvedDir, name);
|
|
1198
|
+
try {
|
|
1199
|
+
lstatSync(fullPath);
|
|
1200
|
+
rmSync(fullPath, { recursive: true, force: true });
|
|
1201
|
+
}
|
|
1202
|
+
catch {
|
|
1203
|
+
// Entry disappeared concurrently
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
catch (err) {
|
|
1208
|
+
log.warn({ err, dir: this.resolvedDir }, 'Failed to sweep orphaned upload staging entries');
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
startSweeper() {
|
|
1212
|
+
if (this.sweepTimer)
|
|
1213
|
+
return;
|
|
1214
|
+
this.sweepTimer = setInterval(() => this.sweepExpired(), SWEEP_INTERVAL_MS);
|
|
1215
|
+
this.sweepTimer.unref();
|
|
1216
|
+
}
|
|
1217
|
+
stopSweeper() {
|
|
1218
|
+
if (!this.sweepTimer)
|
|
1219
|
+
return;
|
|
1220
|
+
clearInterval(this.sweepTimer);
|
|
1221
|
+
this.sweepTimer = undefined;
|
|
1222
|
+
}
|
|
1223
|
+
safeDiskPath(uploadId, filename) {
|
|
1224
|
+
const expectedDir = resolve(this.resolvedDir, uploadId);
|
|
1225
|
+
const filePath = resolve(expectedDir, filename);
|
|
1226
|
+
this.assertContainedPath(filePath);
|
|
1227
|
+
if (dirname(filePath) !== expectedDir) {
|
|
1228
|
+
throw new UploadHttpError(400, 'Invalid upload filename.');
|
|
1229
|
+
}
|
|
1230
|
+
return filePath;
|
|
1231
|
+
}
|
|
1232
|
+
assertContainedPath(filePath) {
|
|
1233
|
+
const resolved = resolve(filePath);
|
|
1234
|
+
if (!this.resolvedDir || !resolved.startsWith(this.resolvedDir + sep)) {
|
|
1235
|
+
throw new Error('Resolved upload path escaped staging directory.');
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
async openVerifiedFile(record) {
|
|
1239
|
+
this.assertContainedPath(record.diskPath);
|
|
1240
|
+
const parentDir = resolve(this.resolvedDir, record.id);
|
|
1241
|
+
const parentStat = await lstat(parentDir);
|
|
1242
|
+
if (!parentStat.isDirectory() || parentStat.isSymbolicLink()) {
|
|
1243
|
+
throw new Error(`Staged upload "${record.id}" directory failed integrity verification.`);
|
|
1244
|
+
}
|
|
1245
|
+
// Verify canonical parent path sits directly under canonical staging root (blocks ancestor symlinks).
|
|
1246
|
+
const canonicalParent = await realpath(dirname(record.diskPath));
|
|
1247
|
+
const expectedParent = join(this.canonicalDir || realpathSync(this.resolvedDir), record.id);
|
|
1248
|
+
if (canonicalParent !== expectedParent) {
|
|
1249
|
+
throw new Error(`Staged upload "${record.id}" parent path escaped staging root.`);
|
|
1250
|
+
}
|
|
1251
|
+
const flags = fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0);
|
|
1252
|
+
const fh = await open(record.diskPath, flags);
|
|
1253
|
+
try {
|
|
1254
|
+
const st = await fh.stat();
|
|
1255
|
+
if (!st.isFile() || st.size !== record.sizeBytes) {
|
|
1256
|
+
throw new Error(`Staged upload "${record.id}" failed size or file-type verification.`);
|
|
1257
|
+
}
|
|
1258
|
+
if (record.fileIdentity &&
|
|
1259
|
+
(st.dev !== record.fileIdentity.dev ||
|
|
1260
|
+
st.ino !== record.fileIdentity.ino ||
|
|
1261
|
+
st.mtimeMs !== record.fileIdentity.mtimeMs ||
|
|
1262
|
+
st.ctimeMs !== record.fileIdentity.ctimeMs)) {
|
|
1263
|
+
throw new Error(`Staged upload "${record.id}" file metadata changed after staging.`);
|
|
1264
|
+
}
|
|
1265
|
+
return fh;
|
|
1266
|
+
}
|
|
1267
|
+
catch (err) {
|
|
1268
|
+
await fh.close().catch(() => { });
|
|
1269
|
+
throw err;
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
deleteRecordSync(uploadId) {
|
|
1273
|
+
this.uploads.delete(uploadId);
|
|
1274
|
+
for (const [tokenHash, id] of this.uploadTokens.entries()) {
|
|
1275
|
+
if (id === uploadId)
|
|
1276
|
+
this.uploadTokens.delete(tokenHash);
|
|
1277
|
+
}
|
|
1278
|
+
for (const [tokenHash, ticket] of this.downloadTokens.entries()) {
|
|
1279
|
+
if (ticket.uploadId === uploadId)
|
|
1280
|
+
this.downloadTokens.delete(tokenHash);
|
|
1281
|
+
}
|
|
1282
|
+
if (!this.resolvedDir)
|
|
1283
|
+
return;
|
|
1284
|
+
try {
|
|
1285
|
+
const dir = resolve(this.resolvedDir, uploadId);
|
|
1286
|
+
if (dir.startsWith(this.resolvedDir + sep)) {
|
|
1287
|
+
rmSync(dir, { recursive: true, force: true });
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
catch (err) {
|
|
1291
|
+
log.warn({ err, uploadId }, 'Failed to remove staged upload directory');
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
async removeUploadDir(uploadId) {
|
|
1295
|
+
if (!this.resolvedDir)
|
|
1296
|
+
return;
|
|
1297
|
+
try {
|
|
1298
|
+
const dir = resolve(this.resolvedDir, uploadId);
|
|
1299
|
+
if (dir.startsWith(this.resolvedDir + sep)) {
|
|
1300
|
+
await rm(dir, { recursive: true, force: true });
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
catch (err) {
|
|
1304
|
+
log.warn({ err, uploadId }, 'Failed to clean up failed upload directory');
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
clearAllSync() {
|
|
1308
|
+
// Transfer any active download/delivery streams into draining byte accounting BEFORE deleting
|
|
1309
|
+
// records, and immediately abort them so open descriptors cannot outlive quota accounting.
|
|
1310
|
+
for (const transfer of Array.from(this.activeTransfers)) {
|
|
1311
|
+
if (!transfer.draining) {
|
|
1312
|
+
transfer.draining = true;
|
|
1313
|
+
this.drainingTransferBytes += transfer.bytes;
|
|
1314
|
+
}
|
|
1315
|
+
transfer.abort();
|
|
1316
|
+
}
|
|
1317
|
+
for (const id of Array.from(this.uploads.keys())) {
|
|
1318
|
+
this.deleteRecordSync(id);
|
|
1319
|
+
}
|
|
1320
|
+
this.uploadTokens.clear();
|
|
1321
|
+
this.downloadTokens.clear();
|
|
1322
|
+
if (this.ownedTempDir && this.dirReady && this.resolvedDir) {
|
|
1323
|
+
const dirToRemove = this.resolvedDir;
|
|
1324
|
+
const lockPath = this.ownerLeasePath();
|
|
1325
|
+
try {
|
|
1326
|
+
// Remove all staged child entries WHILE `.airlock-owner.lock` stays intact at its stable
|
|
1327
|
+
// pathname and exclusively locked by the OS kernel, so no second process can acquire
|
|
1328
|
+
// ownership or stage files while recursive child removal is running.
|
|
1329
|
+
for (const name of readdirSync(dirToRemove)) {
|
|
1330
|
+
if (name === OWNER_LOCK_FILENAME || name.startsWith(`${OWNER_LOCK_FILENAME}-`)) {
|
|
1331
|
+
continue;
|
|
1332
|
+
}
|
|
1333
|
+
rmSync(join(dirToRemove, name), { recursive: true, force: true });
|
|
1334
|
+
}
|
|
1335
|
+
// Mark this lock inode retired while still holding the EXCLUSIVE lock so any concurrent
|
|
1336
|
+
// process already waiting on this inode rejects acquisition after we release the handle.
|
|
1337
|
+
// Require confirmation: if the tombstone fails, abort teardown without unlinking.
|
|
1338
|
+
if (!this.ownerLockDb) {
|
|
1339
|
+
throw new Error('Cannot tear down temporary upload directory without an active ownership lock.');
|
|
1340
|
+
}
|
|
1341
|
+
this.ownerLockDb
|
|
1342
|
+
.prepare('INSERT OR REPLACE INTO owner_lock_v2 (id, pid, retired) VALUES (1, ?, 1)')
|
|
1343
|
+
.run(process.pid);
|
|
1344
|
+
// Switch journaling to MEMORY BEFORE unlinking `.airlock-owner.lock` so SQLite closes and
|
|
1345
|
+
// deletes its on-disk `-journal` sidecar while our lock still occupies its pathname, and
|
|
1346
|
+
// `db.close()` will never unlink a successor's journal file afterwards.
|
|
1347
|
+
this.ownerLockDb.pragma('journal_mode = MEMORY');
|
|
1348
|
+
for (const sidecar of [`${lockPath}-journal`, `${lockPath}-wal`, `${lockPath}-shm`]) {
|
|
1349
|
+
try {
|
|
1350
|
+
unlinkSync(sidecar);
|
|
1351
|
+
}
|
|
1352
|
+
catch (err) {
|
|
1353
|
+
if (err.code !== 'ENOENT') {
|
|
1354
|
+
throw err;
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
if (process.platform === 'win32') {
|
|
1359
|
+
// On Windows, locked files cannot be unlinked while open; release first, then remove
|
|
1360
|
+
// only the lock file and attempt a non-recursive rmdir (which leaves any reclaimed dir intact).
|
|
1361
|
+
this.releaseOwnerLease();
|
|
1362
|
+
try {
|
|
1363
|
+
unlinkSync(lockPath);
|
|
1364
|
+
}
|
|
1365
|
+
catch {
|
|
1366
|
+
// Reclaimed or already gone
|
|
1367
|
+
}
|
|
1368
|
+
try {
|
|
1369
|
+
rmdirSync(dirToRemove);
|
|
1370
|
+
}
|
|
1371
|
+
catch {
|
|
1372
|
+
// Non-empty or already gone; never recursively wipe after releasing the lock
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
else {
|
|
1376
|
+
// On POSIX, unlink ONLY `.airlock-owner.lock` LAST (after all children and sidecars are
|
|
1377
|
+
// gone), then attempt a non-recursive rmdir (fails harmlessly with ENOTEMPTY if another
|
|
1378
|
+
// process created anything), and finally close the SQLite handle.
|
|
1379
|
+
try {
|
|
1380
|
+
unlinkSync(lockPath);
|
|
1381
|
+
}
|
|
1382
|
+
catch (err) {
|
|
1383
|
+
if (err.code !== 'ENOENT') {
|
|
1384
|
+
throw err;
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
try {
|
|
1388
|
+
rmdirSync(dirToRemove);
|
|
1389
|
+
}
|
|
1390
|
+
catch {
|
|
1391
|
+
// Non-empty or already gone; never recursively remove after unlinking the lock
|
|
1392
|
+
}
|
|
1393
|
+
this.releaseOwnerLease();
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
catch (err) {
|
|
1397
|
+
log.warn({ err, dir: dirToRemove }, 'Failed to remove temporary upload directory');
|
|
1398
|
+
this.releaseOwnerLease();
|
|
1399
|
+
}
|
|
1400
|
+
this.resolvedDir = '';
|
|
1401
|
+
this.canonicalDir = '';
|
|
1402
|
+
this.dirReady = false;
|
|
1403
|
+
}
|
|
1404
|
+
else {
|
|
1405
|
+
this.releaseOwnerLease();
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
async receiveUploadStream(record, input) {
|
|
1409
|
+
const isMultipart = isMultipartHeader(input.contentTypeHeader);
|
|
1410
|
+
const streamLimit = isMultipart ? record.maxBytes + MULTIPART_OVERHEAD_BYTES : record.maxBytes;
|
|
1411
|
+
if (input.contentLength !== undefined &&
|
|
1412
|
+
Number.isFinite(input.contentLength) &&
|
|
1413
|
+
input.contentLength > streamLimit) {
|
|
1414
|
+
throw new UploadHttpError(413, `Upload exceeds maximum file size of ${record.maxBytes} bytes.`);
|
|
1415
|
+
}
|
|
1416
|
+
if (!isMultipart &&
|
|
1417
|
+
input.contentLength !== undefined &&
|
|
1418
|
+
Number.isFinite(input.contentLength) &&
|
|
1419
|
+
this.totalStoredBytes() + this.inFlightReservedBytes + input.contentLength >
|
|
1420
|
+
this.config.max_total_bytes) {
|
|
1421
|
+
throw new UploadHttpError(507, `Upload exceeds gateway staged upload storage quota (${this.config.max_total_bytes} bytes).`);
|
|
1422
|
+
}
|
|
1423
|
+
let filename = record.filename;
|
|
1424
|
+
let contentType;
|
|
1425
|
+
let sizeBytes;
|
|
1426
|
+
let sha256;
|
|
1427
|
+
let blockSize;
|
|
1428
|
+
let blockDigests;
|
|
1429
|
+
let reservedBytes = 0;
|
|
1430
|
+
const reserveChunk = (delta) => {
|
|
1431
|
+
if (!this.tryReserveBytes(delta))
|
|
1432
|
+
return false;
|
|
1433
|
+
reservedBytes += delta;
|
|
1434
|
+
return true;
|
|
1435
|
+
};
|
|
1436
|
+
// Register incoming PUT/POST stream so disabling uploads or revoking this agent immediately
|
|
1437
|
+
// cancels the transfer, deletes its temp file, and frees shared quota.
|
|
1438
|
+
const { finish: finishIngress } = this.registerActiveTransfer(record.agentId, 0, () => {
|
|
1439
|
+
if (!input.stream.destroyed) {
|
|
1440
|
+
input.stream.destroy(new UploadHttpError(409, 'Upload was cancelled before completion.'));
|
|
1441
|
+
}
|
|
1442
|
+
});
|
|
1443
|
+
const tmpPath = resolve(this.resolvedDir, `.tmp-${record.id}-${randomBytes(6).toString('hex')}`);
|
|
1444
|
+
try {
|
|
1445
|
+
if (isMultipart) {
|
|
1446
|
+
const result = await streamMultipartFileToDisk(input.stream, input.contentTypeHeader, tmpPath, record.maxBytes, this.config.max_total_bytes, this.streamIdleTimeoutMs, reserveChunk);
|
|
1447
|
+
sizeBytes = result.sizeBytes;
|
|
1448
|
+
sha256 = result.sha256;
|
|
1449
|
+
blockSize = result.blockSize;
|
|
1450
|
+
blockDigests = result.blockDigests;
|
|
1451
|
+
if (!record.explicitFilename && result.filename) {
|
|
1452
|
+
filename = sanitizeFilename(result.filename);
|
|
1453
|
+
}
|
|
1454
|
+
const extractedMime = normalizeMimeType(result.contentType);
|
|
1455
|
+
if (!record.explicitContentType &&
|
|
1456
|
+
extractedMime &&
|
|
1457
|
+
extractedMime !== 'application/octet-stream') {
|
|
1458
|
+
contentType = extractedMime;
|
|
1459
|
+
}
|
|
1460
|
+
else {
|
|
1461
|
+
contentType = inferMimeType(filename, record.explicitContentType ? record.contentType : extractedMime);
|
|
1462
|
+
}
|
|
1463
|
+
if (!matchesMimeAllowlist(contentType, this.config.allowed_mime_types) ||
|
|
1464
|
+
!matchesMimeAllowlist(contentType, record.allowedMimeTypes)) {
|
|
1465
|
+
throw new UploadHttpError(415, `MIME type "${contentType}" is not allowed for uploads.`);
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
else {
|
|
1469
|
+
const headerMime = normalizeMimeType(input.contentTypeHeader);
|
|
1470
|
+
if (!record.explicitContentType &&
|
|
1471
|
+
headerMime &&
|
|
1472
|
+
headerMime !== 'application/octet-stream') {
|
|
1473
|
+
contentType = headerMime;
|
|
1474
|
+
}
|
|
1475
|
+
else {
|
|
1476
|
+
contentType = inferMimeType(filename, record.explicitContentType ? record.contentType : headerMime);
|
|
1477
|
+
}
|
|
1478
|
+
if (!matchesMimeAllowlist(contentType, this.config.allowed_mime_types) ||
|
|
1479
|
+
!matchesMimeAllowlist(contentType, record.allowedMimeTypes)) {
|
|
1480
|
+
throw new UploadHttpError(415, `MIME type "${contentType}" is not allowed for uploads.`);
|
|
1481
|
+
}
|
|
1482
|
+
const result = await streamToFileWithHash(input.stream, tmpPath, record.maxBytes, this.config.max_total_bytes, this.streamIdleTimeoutMs, reserveChunk);
|
|
1483
|
+
sizeBytes = result.sizeBytes;
|
|
1484
|
+
sha256 = result.sha256;
|
|
1485
|
+
blockSize = result.blockSize;
|
|
1486
|
+
blockDigests = result.blockDigests;
|
|
1487
|
+
}
|
|
1488
|
+
// Confirm this upload still belongs to the live store before publishing on disk.
|
|
1489
|
+
if (!this.config.enabled || this.uploads.get(record.id) !== record) {
|
|
1490
|
+
throw new UploadHttpError(409, 'Upload was cancelled before completion.');
|
|
1491
|
+
}
|
|
1492
|
+
const finalPath = this.safeDiskPath(record.id, filename);
|
|
1493
|
+
await mkdir(dirname(finalPath), { recursive: true, mode: 0o755 });
|
|
1494
|
+
if (!this.config.enabled || this.uploads.get(record.id) !== record) {
|
|
1495
|
+
await this.removeUploadDir(record.id);
|
|
1496
|
+
throw new UploadHttpError(409, 'Upload was cancelled before completion.');
|
|
1497
|
+
}
|
|
1498
|
+
await rename(tmpPath, finalPath);
|
|
1499
|
+
const committedStat = await stat(finalPath);
|
|
1500
|
+
// Re-verify store state and record ownership AFTER rename/stat and before publishing ready so
|
|
1501
|
+
// revocation during commit never returns success for a detached record or leaves an orphan.
|
|
1502
|
+
if (!this.config.enabled || this.uploads.get(record.id) !== record) {
|
|
1503
|
+
await this.removeUploadDir(record.id);
|
|
1504
|
+
throw new UploadHttpError(409, 'Upload was cancelled before completion.');
|
|
1505
|
+
}
|
|
1506
|
+
// Transfer reserved bytes atomically to the ready record (no await between these lines).
|
|
1507
|
+
record.filename = filename;
|
|
1508
|
+
record.contentType = contentType;
|
|
1509
|
+
record.sizeBytes = sizeBytes;
|
|
1510
|
+
record.sha256 = sha256;
|
|
1511
|
+
record.blockSize = blockSize;
|
|
1512
|
+
record.blockDigests = blockDigests;
|
|
1513
|
+
record.diskPath = finalPath;
|
|
1514
|
+
record.fileIdentity = {
|
|
1515
|
+
dev: committedStat.dev,
|
|
1516
|
+
ino: committedStat.ino,
|
|
1517
|
+
mtimeMs: committedStat.mtimeMs,
|
|
1518
|
+
ctimeMs: committedStat.ctimeMs,
|
|
1519
|
+
};
|
|
1520
|
+
record.expiresAt = Date.now() + this.config.ttl_ms;
|
|
1521
|
+
record.status = 'ready';
|
|
1522
|
+
this.releaseReservedBytes(reservedBytes);
|
|
1523
|
+
reservedBytes = 0;
|
|
1524
|
+
return {
|
|
1525
|
+
upload_id: record.id,
|
|
1526
|
+
ref: formatUploadRef(record.id),
|
|
1527
|
+
filename: record.filename,
|
|
1528
|
+
content_type: record.contentType,
|
|
1529
|
+
size_bytes: record.sizeBytes,
|
|
1530
|
+
sha256: record.sha256,
|
|
1531
|
+
expires_at: new Date(record.expiresAt).toISOString(),
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
catch (err) {
|
|
1535
|
+
await rm(tmpPath, { force: true }).catch(() => { });
|
|
1536
|
+
if (!this.config.enabled || this.uploads.get(record.id) !== record) {
|
|
1537
|
+
await this.removeUploadDir(record.id);
|
|
1538
|
+
if (err instanceof UploadHttpError)
|
|
1539
|
+
throw err;
|
|
1540
|
+
throw new UploadHttpError(409, 'Upload was cancelled before completion.', { cause: err });
|
|
1541
|
+
}
|
|
1542
|
+
throw err;
|
|
1543
|
+
}
|
|
1544
|
+
finally {
|
|
1545
|
+
finishIngress();
|
|
1546
|
+
if (reservedBytes > 0) {
|
|
1547
|
+
this.releaseReservedBytes(reservedBytes);
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
function isMultipartHeader(header) {
|
|
1553
|
+
return typeof header === 'string' && header.toLowerCase().startsWith('multipart/form-data');
|
|
1554
|
+
}
|
|
1555
|
+
function parseMultipartBoundary(header) {
|
|
1556
|
+
if (!header)
|
|
1557
|
+
return undefined;
|
|
1558
|
+
const match = /;\s*boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(header);
|
|
1559
|
+
const boundary = match?.[1] ?? match?.[2];
|
|
1560
|
+
return boundary && boundary.length > 0 && boundary.length <= 200 ? boundary : undefined;
|
|
1561
|
+
}
|
|
1562
|
+
function parsePartHeaders(headerBlock) {
|
|
1563
|
+
let name;
|
|
1564
|
+
let filename;
|
|
1565
|
+
let contentType;
|
|
1566
|
+
for (const line of headerBlock.split('\r\n')) {
|
|
1567
|
+
const colon = line.indexOf(':');
|
|
1568
|
+
if (colon <= 0)
|
|
1569
|
+
continue;
|
|
1570
|
+
const key = line.slice(0, colon).trim().toLowerCase();
|
|
1571
|
+
const val = line.slice(colon + 1).trim();
|
|
1572
|
+
if (key === 'content-disposition') {
|
|
1573
|
+
const nameMatch = /;\s*name="([^"]*)"/i.exec(val) ?? /;\s*name=([^;\s]+)/i.exec(val);
|
|
1574
|
+
if (nameMatch)
|
|
1575
|
+
name = nameMatch[1];
|
|
1576
|
+
const extFilenameMatch = /;\s*filename\*=(?:utf-8''|UTF-8'')([^;\s]+)/i.exec(val);
|
|
1577
|
+
if (extFilenameMatch) {
|
|
1578
|
+
try {
|
|
1579
|
+
filename = decodeURIComponent(extFilenameMatch[1]);
|
|
1580
|
+
}
|
|
1581
|
+
catch {
|
|
1582
|
+
filename = extFilenameMatch[1];
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
else {
|
|
1586
|
+
const filenameMatch = /;\s*filename="([^"]*)"/i.exec(val) ?? /;\s*filename=([^;\s]+)/i.exec(val);
|
|
1587
|
+
if (filenameMatch)
|
|
1588
|
+
filename = filenameMatch[1];
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
else if (key === 'content-type') {
|
|
1592
|
+
contentType = val;
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
return { name, filename, contentType };
|
|
1596
|
+
}
|
|
1597
|
+
function attachIdleTimeout(stream, timeoutMs) {
|
|
1598
|
+
if (!timeoutMs || timeoutMs <= 0) {
|
|
1599
|
+
return { touch: () => { }, clear: () => { } };
|
|
1600
|
+
}
|
|
1601
|
+
let timer;
|
|
1602
|
+
const reset = () => {
|
|
1603
|
+
if (timer)
|
|
1604
|
+
clearTimeout(timer);
|
|
1605
|
+
timer = setTimeout(() => {
|
|
1606
|
+
stream.destroy(new UploadHttpError(408, `Upload stalled with no data received for ${timeoutMs}ms.`));
|
|
1607
|
+
}, timeoutMs);
|
|
1608
|
+
timer.unref?.();
|
|
1609
|
+
};
|
|
1610
|
+
reset();
|
|
1611
|
+
return {
|
|
1612
|
+
touch: reset,
|
|
1613
|
+
clear: () => {
|
|
1614
|
+
if (timer)
|
|
1615
|
+
clearTimeout(timer);
|
|
1616
|
+
timer = undefined;
|
|
1617
|
+
},
|
|
1618
|
+
};
|
|
1619
|
+
}
|
|
1620
|
+
async function writeStreamChunk(ws, buf) {
|
|
1621
|
+
if (buf.byteLength === 0)
|
|
1622
|
+
return;
|
|
1623
|
+
if (!ws.write(buf)) {
|
|
1624
|
+
await new Promise((resolveDrain, rejectDrain) => {
|
|
1625
|
+
const onDrain = () => {
|
|
1626
|
+
ws.off('error', onError);
|
|
1627
|
+
resolveDrain();
|
|
1628
|
+
};
|
|
1629
|
+
const onError = (err) => {
|
|
1630
|
+
ws.off('drain', onDrain);
|
|
1631
|
+
rejectDrain(err);
|
|
1632
|
+
};
|
|
1633
|
+
ws.once('drain', onDrain);
|
|
1634
|
+
ws.once('error', onError);
|
|
1635
|
+
});
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
async function finishWriteStream(ws, existingError) {
|
|
1639
|
+
await new Promise((resolveEnd, rejectEnd) => {
|
|
1640
|
+
if (existingError) {
|
|
1641
|
+
rejectEnd(existingError);
|
|
1642
|
+
return;
|
|
1643
|
+
}
|
|
1644
|
+
const onFinish = () => {
|
|
1645
|
+
ws.off('error', onError);
|
|
1646
|
+
resolveEnd();
|
|
1647
|
+
};
|
|
1648
|
+
const onError = (err) => {
|
|
1649
|
+
ws.off('finish', onFinish);
|
|
1650
|
+
rejectEnd(err);
|
|
1651
|
+
};
|
|
1652
|
+
ws.once('finish', onFinish);
|
|
1653
|
+
ws.once('error', onError);
|
|
1654
|
+
ws.end();
|
|
1655
|
+
});
|
|
1656
|
+
}
|
|
1657
|
+
async function streamToFileWithHash(stream, destPath, maxFileBytes, maxTotalBytes, idleTimeoutMs, reserveChunk) {
|
|
1658
|
+
const digest = new ChunkedDigestBuilder();
|
|
1659
|
+
const ws = createWriteStream(destPath, { mode: 0o644 });
|
|
1660
|
+
let sizeBytes = 0;
|
|
1661
|
+
let wsError;
|
|
1662
|
+
ws.once('error', (err) => {
|
|
1663
|
+
wsError = err;
|
|
1664
|
+
});
|
|
1665
|
+
const idle = attachIdleTimeout(stream, idleTimeoutMs);
|
|
1666
|
+
try {
|
|
1667
|
+
for await (const chunk of stream) {
|
|
1668
|
+
idle.touch();
|
|
1669
|
+
if (wsError)
|
|
1670
|
+
throw wsError;
|
|
1671
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
1672
|
+
sizeBytes += buf.byteLength;
|
|
1673
|
+
if (sizeBytes > maxFileBytes) {
|
|
1674
|
+
stream.destroy();
|
|
1675
|
+
throw new UploadHttpError(413, `Upload exceeds maximum file size of ${maxFileBytes} bytes.`);
|
|
1676
|
+
}
|
|
1677
|
+
if (!reserveChunk(buf.byteLength)) {
|
|
1678
|
+
stream.destroy();
|
|
1679
|
+
throw new UploadHttpError(507, `Upload exceeds gateway staged upload storage quota (${maxTotalBytes} bytes).`);
|
|
1680
|
+
}
|
|
1681
|
+
digest.update(buf);
|
|
1682
|
+
await writeStreamChunk(ws, buf);
|
|
1683
|
+
}
|
|
1684
|
+
await finishWriteStream(ws, wsError);
|
|
1685
|
+
return { sizeBytes, ...digest.finish() };
|
|
1686
|
+
}
|
|
1687
|
+
catch (err) {
|
|
1688
|
+
ws.destroy();
|
|
1689
|
+
throw err;
|
|
1690
|
+
}
|
|
1691
|
+
finally {
|
|
1692
|
+
idle.clear();
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
/**
|
|
1696
|
+
* Stream the first file part of a `multipart/form-data` request directly to disk while hashing and
|
|
1697
|
+
* enforcing both per-file and live gateway storage budgets without buffering the file in memory.
|
|
1698
|
+
*/
|
|
1699
|
+
async function streamMultipartFileToDisk(stream, contentTypeHeader, destPath, maxFileBytes, maxTotalBytes, idleTimeoutMs, reserveChunk) {
|
|
1700
|
+
const boundary = parseMultipartBoundary(contentTypeHeader);
|
|
1701
|
+
if (!boundary) {
|
|
1702
|
+
throw new UploadHttpError(400, 'Malformed multipart/form-data upload body (missing boundary).');
|
|
1703
|
+
}
|
|
1704
|
+
const firstBoundary = Buffer.from(`--${boundary}`);
|
|
1705
|
+
const closingMarker = Buffer.from(`\r\n--${boundary}`);
|
|
1706
|
+
const headerTerminator = Buffer.from('\r\n\r\n');
|
|
1707
|
+
let state = 'preamble';
|
|
1708
|
+
let carry = Buffer.alloc(0);
|
|
1709
|
+
let overheadBytes = 0;
|
|
1710
|
+
let fileCaptured = false;
|
|
1711
|
+
let capturedFilename;
|
|
1712
|
+
let capturedContentType;
|
|
1713
|
+
let sizeBytes = 0;
|
|
1714
|
+
const digest = new ChunkedDigestBuilder();
|
|
1715
|
+
let ws;
|
|
1716
|
+
let wsError;
|
|
1717
|
+
const accountOverhead = (bytes) => {
|
|
1718
|
+
overheadBytes += bytes;
|
|
1719
|
+
if (overheadBytes > MULTIPART_OVERHEAD_BYTES) {
|
|
1720
|
+
stream.destroy();
|
|
1721
|
+
throw new UploadHttpError(413, `Multipart non-file form overhead exceeded ${MULTIPART_OVERHEAD_BYTES} bytes.`);
|
|
1722
|
+
}
|
|
1723
|
+
};
|
|
1724
|
+
const writeFileBytes = async (slice) => {
|
|
1725
|
+
if (slice.byteLength === 0)
|
|
1726
|
+
return;
|
|
1727
|
+
if (wsError)
|
|
1728
|
+
throw wsError;
|
|
1729
|
+
sizeBytes += slice.byteLength;
|
|
1730
|
+
if (sizeBytes > maxFileBytes) {
|
|
1731
|
+
stream.destroy();
|
|
1732
|
+
throw new UploadHttpError(413, `Upload exceeds maximum file size of ${maxFileBytes} bytes.`);
|
|
1733
|
+
}
|
|
1734
|
+
if (!reserveChunk(slice.byteLength)) {
|
|
1735
|
+
stream.destroy();
|
|
1736
|
+
throw new UploadHttpError(507, `Upload exceeds gateway staged upload storage quota (${maxTotalBytes} bytes).`);
|
|
1737
|
+
}
|
|
1738
|
+
digest.update(slice);
|
|
1739
|
+
await writeStreamChunk(ws, slice);
|
|
1740
|
+
};
|
|
1741
|
+
const idle = attachIdleTimeout(stream, idleTimeoutMs);
|
|
1742
|
+
try {
|
|
1743
|
+
for await (const rawChunk of stream) {
|
|
1744
|
+
idle.touch();
|
|
1745
|
+
const chunk = Buffer.isBuffer(rawChunk) ? rawChunk : Buffer.from(rawChunk);
|
|
1746
|
+
carry = carry.byteLength > 0 ? Buffer.concat([carry, chunk]) : chunk;
|
|
1747
|
+
let progress = true;
|
|
1748
|
+
while (progress) {
|
|
1749
|
+
progress = false;
|
|
1750
|
+
if (state === 'preamble') {
|
|
1751
|
+
const idx = carry.indexOf(firstBoundary);
|
|
1752
|
+
if (idx === -1) {
|
|
1753
|
+
const keep = firstBoundary.byteLength - 1;
|
|
1754
|
+
if (carry.byteLength > keep) {
|
|
1755
|
+
accountOverhead(carry.byteLength - keep);
|
|
1756
|
+
carry = carry.subarray(carry.byteLength - keep);
|
|
1757
|
+
}
|
|
1758
|
+
break;
|
|
1759
|
+
}
|
|
1760
|
+
if (carry.byteLength < idx + firstBoundary.byteLength + 2) {
|
|
1761
|
+
break;
|
|
1762
|
+
}
|
|
1763
|
+
accountOverhead(idx + firstBoundary.byteLength + 2);
|
|
1764
|
+
const after = idx + firstBoundary.byteLength;
|
|
1765
|
+
const b0 = carry[after];
|
|
1766
|
+
const b1 = carry[after + 1];
|
|
1767
|
+
if (b0 === 0x2d && b1 === 0x2d) {
|
|
1768
|
+
state = 'done';
|
|
1769
|
+
carry = carry.subarray(after + 2);
|
|
1770
|
+
break;
|
|
1771
|
+
}
|
|
1772
|
+
if (b0 === 0x0d && b1 === 0x0a) {
|
|
1773
|
+
carry = carry.subarray(after + 2);
|
|
1774
|
+
state = 'headers';
|
|
1775
|
+
progress = true;
|
|
1776
|
+
continue;
|
|
1777
|
+
}
|
|
1778
|
+
throw new UploadHttpError(400, 'Malformed multipart/form-data boundary.');
|
|
1779
|
+
}
|
|
1780
|
+
if (state === 'headers') {
|
|
1781
|
+
const idx = carry.indexOf(headerTerminator);
|
|
1782
|
+
if (idx === -1) {
|
|
1783
|
+
if (carry.byteLength > MULTIPART_OVERHEAD_BYTES) {
|
|
1784
|
+
accountOverhead(carry.byteLength);
|
|
1785
|
+
}
|
|
1786
|
+
break;
|
|
1787
|
+
}
|
|
1788
|
+
const headerText = carry.subarray(0, idx).toString('utf8');
|
|
1789
|
+
accountOverhead(idx + headerTerminator.byteLength);
|
|
1790
|
+
carry = carry.subarray(idx + headerTerminator.byteLength);
|
|
1791
|
+
const parsed = parsePartHeaders(headerText);
|
|
1792
|
+
if (!fileCaptured && parsed.filename !== undefined) {
|
|
1793
|
+
capturedFilename = parsed.filename || undefined;
|
|
1794
|
+
capturedContentType = parsed.contentType || undefined;
|
|
1795
|
+
ws = createWriteStream(destPath, { mode: 0o644 });
|
|
1796
|
+
ws.once('error', (err) => {
|
|
1797
|
+
wsError = err;
|
|
1798
|
+
});
|
|
1799
|
+
state = 'file-body';
|
|
1800
|
+
}
|
|
1801
|
+
else {
|
|
1802
|
+
state = 'skip-body';
|
|
1803
|
+
}
|
|
1804
|
+
progress = true;
|
|
1805
|
+
continue;
|
|
1806
|
+
}
|
|
1807
|
+
if (state === 'file-body') {
|
|
1808
|
+
const idx = carry.indexOf(closingMarker);
|
|
1809
|
+
if (idx !== -1) {
|
|
1810
|
+
const after = idx + closingMarker.byteLength;
|
|
1811
|
+
if (carry.byteLength < after + 2) {
|
|
1812
|
+
break;
|
|
1813
|
+
}
|
|
1814
|
+
const b0 = carry[after];
|
|
1815
|
+
const b1 = carry[after + 1];
|
|
1816
|
+
const isClosing = b0 === 0x2d && b1 === 0x2d;
|
|
1817
|
+
const isNextPart = b0 === 0x0d && b1 === 0x0a;
|
|
1818
|
+
if (isClosing || isNextPart) {
|
|
1819
|
+
await writeFileBytes(carry.subarray(0, idx));
|
|
1820
|
+
await finishWriteStream(ws, wsError);
|
|
1821
|
+
ws = undefined;
|
|
1822
|
+
fileCaptured = true;
|
|
1823
|
+
carry = carry.subarray(after + 2);
|
|
1824
|
+
state = isClosing ? 'done' : 'headers';
|
|
1825
|
+
progress = true;
|
|
1826
|
+
continue;
|
|
1827
|
+
}
|
|
1828
|
+
// Marker text occurred inside file payload without valid boundary trailer.
|
|
1829
|
+
await writeFileBytes(carry.subarray(0, idx + 2));
|
|
1830
|
+
carry = carry.subarray(idx + 2);
|
|
1831
|
+
progress = true;
|
|
1832
|
+
continue;
|
|
1833
|
+
}
|
|
1834
|
+
const keep = closingMarker.byteLength + 1;
|
|
1835
|
+
if (carry.byteLength > keep) {
|
|
1836
|
+
await writeFileBytes(carry.subarray(0, carry.byteLength - keep));
|
|
1837
|
+
carry = carry.subarray(carry.byteLength - keep);
|
|
1838
|
+
}
|
|
1839
|
+
break;
|
|
1840
|
+
}
|
|
1841
|
+
if (state === 'skip-body') {
|
|
1842
|
+
const idx = carry.indexOf(closingMarker);
|
|
1843
|
+
if (idx !== -1) {
|
|
1844
|
+
const after = idx + closingMarker.byteLength;
|
|
1845
|
+
if (carry.byteLength < after + 2) {
|
|
1846
|
+
break;
|
|
1847
|
+
}
|
|
1848
|
+
const b0 = carry[after];
|
|
1849
|
+
const b1 = carry[after + 1];
|
|
1850
|
+
const isClosing = b0 === 0x2d && b1 === 0x2d;
|
|
1851
|
+
const isNextPart = b0 === 0x0d && b1 === 0x0a;
|
|
1852
|
+
if (isClosing || isNextPart) {
|
|
1853
|
+
accountOverhead(idx + closingMarker.byteLength + 2);
|
|
1854
|
+
carry = carry.subarray(after + 2);
|
|
1855
|
+
state = isClosing ? 'done' : 'headers';
|
|
1856
|
+
progress = true;
|
|
1857
|
+
continue;
|
|
1858
|
+
}
|
|
1859
|
+
accountOverhead(idx + 2);
|
|
1860
|
+
carry = carry.subarray(idx + 2);
|
|
1861
|
+
progress = true;
|
|
1862
|
+
continue;
|
|
1863
|
+
}
|
|
1864
|
+
const keep = closingMarker.byteLength + 1;
|
|
1865
|
+
if (carry.byteLength > keep) {
|
|
1866
|
+
accountOverhead(carry.byteLength - keep);
|
|
1867
|
+
carry = carry.subarray(carry.byteLength - keep);
|
|
1868
|
+
}
|
|
1869
|
+
break;
|
|
1870
|
+
}
|
|
1871
|
+
if (state === 'done') {
|
|
1872
|
+
if (carry.byteLength > 0) {
|
|
1873
|
+
accountOverhead(carry.byteLength);
|
|
1874
|
+
carry = Buffer.alloc(0);
|
|
1875
|
+
}
|
|
1876
|
+
break;
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
if (ws) {
|
|
1881
|
+
ws.destroy();
|
|
1882
|
+
ws = undefined;
|
|
1883
|
+
}
|
|
1884
|
+
if (state !== 'done') {
|
|
1885
|
+
if (state === 'preamble') {
|
|
1886
|
+
throw new UploadHttpError(400, 'Malformed multipart/form-data upload body.');
|
|
1887
|
+
}
|
|
1888
|
+
throw new UploadHttpError(400, 'Truncated multipart/form-data upload body (missing closing boundary).');
|
|
1889
|
+
}
|
|
1890
|
+
if (!fileCaptured) {
|
|
1891
|
+
throw new UploadHttpError(400, 'Multipart upload contained no file part. Send a file field (e.g. -F "file=@path") or raw binary body (--data-binary @path).');
|
|
1892
|
+
}
|
|
1893
|
+
return {
|
|
1894
|
+
sizeBytes,
|
|
1895
|
+
...digest.finish(),
|
|
1896
|
+
filename: capturedFilename,
|
|
1897
|
+
contentType: capturedContentType,
|
|
1898
|
+
};
|
|
1899
|
+
}
|
|
1900
|
+
catch (err) {
|
|
1901
|
+
ws?.destroy();
|
|
1902
|
+
throw err;
|
|
1903
|
+
}
|
|
1904
|
+
finally {
|
|
1905
|
+
idle.clear();
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
//# sourceMappingURL=store.js.map
|