@warlock.js/core 5.19.1 → 5.21.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/CHANGELOG.md +1136 -1073
- package/esm/benchmark/benchmark.mjs +34 -25
- package/esm/benchmark/benchmark.mjs.map +1 -1
- package/esm/benchmark/profiler.d.mts.map +1 -1
- package/esm/benchmark/profiler.mjs +8 -3
- package/esm/benchmark/profiler.mjs.map +1 -1
- package/esm/bootstrap.d.mts.map +1 -1
- package/esm/bootstrap.mjs +3 -0
- package/esm/bootstrap.mjs.map +1 -1
- package/esm/cache/database-cache-driver.d.mts +2 -2
- package/esm/cache/database-cache-driver.d.mts.map +1 -1
- package/esm/cache/database-cache-driver.mjs +3 -2
- package/esm/cache/database-cache-driver.mjs.map +1 -1
- package/esm/cli/cli-commands.manager.mjs +16 -14
- package/esm/cli/cli-commands.manager.mjs.map +1 -1
- package/esm/cli/commands/add.command.mjs +1 -1
- package/esm/cli/commands/add.command.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/optional-peers.check.mjs +3 -2
- package/esm/cli/commands/doctor/checks/optional-peers.check.mjs.map +1 -1
- package/esm/cli/commands/generate/generate.command.mjs +20 -0
- package/esm/cli/commands/generate/generate.command.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/column-dsl-parser.mjs +4 -2
- package/esm/cli/commands/generate/generators/column-dsl-parser.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/controller.generator.mjs +1 -1
- package/esm/cli/commands/generate/generators/controller.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/migration.generator.mjs +22 -6
- package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/model.generator.mjs +22 -7
- package/esm/cli/commands/generate/generators/model.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/module.generator.mjs +8 -6
- package/esm/cli/commands/generate/generators/module.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/repository.generator.mjs +1 -1
- package/esm/cli/commands/generate/generators/repository.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/resource.generator.mjs +1 -1
- package/esm/cli/commands/generate/generators/resource.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/service.generator.mjs +1 -1
- package/esm/cli/commands/generate/generators/service.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/templates/stubs.mjs +7 -7
- package/esm/cli/commands/generate/templates/stubs.mjs.map +1 -1
- package/esm/cli/commands/generate/utils/writer.mjs +25 -1
- package/esm/cli/commands/generate/utils/writer.mjs.map +1 -1
- package/esm/cli/commands/routes/routes-command.action.mjs +5 -1
- package/esm/cli/commands/routes/routes-command.action.mjs.map +1 -1
- package/esm/cli/commands/routes/with-console-on-stderr.mjs +24 -0
- package/esm/cli/commands/routes/with-console-on-stderr.mjs.map +1 -0
- package/esm/cli/commands/routes.command.mjs +3 -4
- package/esm/cli/commands/routes.command.mjs.map +1 -1
- package/esm/cli/commands/start-production.command.mjs +5 -5
- package/esm/cli/commands/start-production.command.mjs.map +1 -1
- package/esm/cli/commands/storage-put.action.mjs +2 -1
- package/esm/cli/commands/storage-put.action.mjs.map +1 -1
- package/esm/cli/commands/update.command.mjs +1 -0
- package/esm/cli/commands/update.command.mjs.map +1 -1
- package/esm/cli/parse-cli-args.mjs +13 -1
- package/esm/cli/parse-cli-args.mjs.map +1 -1
- package/esm/commands/cli-command.d.mts.map +1 -1
- package/esm/commands/cli-command.mjs +4 -2
- package/esm/commands/cli-command.mjs.map +1 -1
- package/esm/commands/index.mjs +3 -0
- package/esm/config/config-key-from-path.mjs +20 -0
- package/esm/config/config-key-from-path.mjs.map +1 -0
- package/esm/config/config-loader.d.mts.map +1 -1
- package/esm/config/config-loader.mjs +2 -3
- package/esm/config/config-loader.mjs.map +1 -1
- package/esm/connectors/cache-connector.d.mts.map +1 -1
- package/esm/connectors/cache-connector.mjs +5 -0
- package/esm/connectors/cache-connector.mjs.map +1 -1
- package/esm/connectors/connectors-manager.d.mts +4 -0
- package/esm/connectors/connectors-manager.d.mts.map +1 -1
- package/esm/connectors/connectors-manager.mjs +30 -2
- package/esm/connectors/connectors-manager.mjs.map +1 -1
- package/esm/connectors/single-server-warnings.mjs +33 -0
- package/esm/connectors/single-server-warnings.mjs.map +1 -0
- package/esm/connectors/socket-connector.d.mts +29 -0
- package/esm/connectors/socket-connector.d.mts.map +1 -1
- package/esm/connectors/socket-connector.mjs +77 -9
- package/esm/connectors/socket-connector.mjs.map +1 -1
- package/esm/connectors/storage.connector.d.mts.map +1 -1
- package/esm/connectors/storage.connector.mjs +6 -0
- package/esm/connectors/storage.connector.mjs.map +1 -1
- package/esm/connectors/types.d.mts +4 -2
- package/esm/connectors/types.d.mts.map +1 -1
- package/esm/connectors/types.mjs.map +1 -1
- package/esm/database/models/database-log/database-log.d.mts +47 -24
- package/esm/database/models/database-log/database-log.d.mts.map +1 -1
- package/esm/database/models/database-log/database-log.mjs +36 -4
- package/esm/database/models/database-log/database-log.mjs.map +1 -1
- package/esm/database/seed-command-action.mjs +10 -2
- package/esm/database/seed-command-action.mjs.map +1 -1
- package/esm/dev-server/development-server.mjs +15 -4
- package/esm/dev-server/development-server.mjs.map +1 -1
- package/esm/dev-server/file-event-handler.mjs +26 -6
- package/esm/dev-server/file-event-handler.mjs.map +1 -1
- package/esm/dev-server/file-manager.d.mts.map +1 -1
- package/esm/dev-server/file-manager.mjs +2 -2
- package/esm/dev-server/file-manager.mjs.map +1 -1
- package/esm/dev-server/files-orchestrator.mjs +3 -1
- package/esm/dev-server/files-orchestrator.mjs.map +1 -1
- package/esm/dev-server/files-watcher.mjs +64 -5
- package/esm/dev-server/files-watcher.mjs.map +1 -1
- package/esm/dev-server/health-checker/files-healthcare.manager.mjs +31 -9
- package/esm/dev-server/health-checker/files-healthcare.manager.mjs.map +1 -1
- package/esm/dev-server/health-checker/workers/eslint-health.worker.mjs +11 -7
- package/esm/dev-server/health-checker/workers/eslint-health.worker.mjs.map +1 -1
- package/esm/dev-server/loader/load-hook.mjs +1 -1
- package/esm/dev-server/loader/register-loader.mjs +1 -1
- package/esm/dev-server/manifest-manager.d.mts.map +1 -1
- package/esm/dev-server/manifest-manager.mjs +12 -6
- package/esm/dev-server/manifest-manager.mjs.map +1 -1
- package/esm/dev-server/parse-imports.mjs +9 -0
- package/esm/dev-server/parse-imports.mjs.map +1 -1
- package/esm/dev-server/register-dev-shortcuts.mjs +2 -1
- package/esm/dev-server/register-dev-shortcuts.mjs.map +1 -1
- package/esm/dev-server/route-types-publisher.mjs +60 -0
- package/esm/dev-server/route-types-publisher.mjs.map +1 -0
- package/esm/dev-server/shortcuts.mjs +2 -2
- package/esm/dev-server/shortcuts.mjs.map +1 -1
- package/esm/dev-server/special-file-patterns.mjs +18 -0
- package/esm/dev-server/special-file-patterns.mjs.map +1 -0
- package/esm/dev-server/special-files-collector.d.mts.map +1 -1
- package/esm/dev-server/special-files-collector.mjs +2 -5
- package/esm/dev-server/special-files-collector.mjs.map +1 -1
- package/esm/dev-server/start-development-server.mjs +1 -2
- package/esm/dev-server/start-development-server.mjs.map +1 -1
- package/esm/dev-server/supervisor.mjs +23 -3
- package/esm/dev-server/supervisor.mjs.map +1 -1
- package/esm/dev-server/tsconfig-manager.mjs +22 -12
- package/esm/dev-server/tsconfig-manager.mjs.map +1 -1
- package/esm/dev-server/type-generator.mjs +10 -9
- package/esm/dev-server/type-generator.mjs.map +1 -1
- package/esm/encryption/encrypt.d.mts.map +1 -1
- package/esm/encryption/encrypt.mjs +16 -5
- package/esm/encryption/encrypt.mjs.map +1 -1
- package/esm/encryption/hash.d.mts.map +1 -1
- package/esm/encryption/hash.mjs +2 -0
- package/esm/encryption/hash.mjs.map +1 -1
- package/esm/encryption/password.d.mts.map +1 -1
- package/esm/encryption/password.mjs +3 -1
- package/esm/encryption/password.mjs.map +1 -1
- package/esm/generations/features/index.mjs +1 -1
- package/esm/generations/features/mysql.feature.mjs +9 -2
- package/esm/generations/features/mysql.feature.mjs.map +1 -1
- package/esm/generations/features/test.feature.mjs +2 -1
- package/esm/generations/features/test.feature.mjs.map +1 -1
- package/esm/generations/features/web.feature.mjs +4 -2
- package/esm/generations/features/web.feature.mjs.map +1 -1
- package/esm/http/build-rate-limit-options.d.mts +37 -0
- package/esm/http/build-rate-limit-options.d.mts.map +1 -0
- package/esm/http/build-rate-limit-options.mjs +37 -0
- package/esm/http/build-rate-limit-options.mjs.map +1 -0
- package/esm/http/csrf-origin-policy.d.mts.map +1 -1
- package/esm/http/csrf-origin-policy.mjs +5 -2
- package/esm/http/csrf-origin-policy.mjs.map +1 -1
- package/esm/http/flush-pending-cookies.mjs +52 -0
- package/esm/http/flush-pending-cookies.mjs.map +1 -0
- package/esm/http/middleware/cache-response-middleware.d.mts.map +1 -1
- package/esm/http/middleware/cache-response-middleware.mjs +4 -2
- package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
- package/esm/http/middleware/idempotency.middleware.d.mts +5 -0
- package/esm/http/middleware/idempotency.middleware.d.mts.map +1 -1
- package/esm/http/middleware/idempotency.middleware.mjs +35 -3
- package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
- package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
- package/esm/http/middleware/inject-request-context.mjs +14 -3
- package/esm/http/middleware/inject-request-context.mjs.map +1 -1
- package/esm/http/middleware/rate-limit.middleware.d.mts +4 -3
- package/esm/http/middleware/rate-limit.middleware.d.mts.map +1 -1
- package/esm/http/middleware/rate-limit.middleware.mjs +4 -3
- package/esm/http/middleware/rate-limit.middleware.mjs.map +1 -1
- package/esm/http/middleware/utils/cidr-match.d.mts +1 -1
- package/esm/http/middleware/utils/cidr-match.d.mts.map +1 -1
- package/esm/http/middleware/utils/cidr-match.mjs +11 -2
- package/esm/http/middleware/utils/cidr-match.mjs.map +1 -1
- package/esm/http/middleware/utils/idempotency-key.mjs +1 -1
- package/esm/http/middleware/utils/idempotency-key.mjs.map +1 -1
- package/esm/http/plugins.d.mts.map +1 -1
- package/esm/http/plugins.mjs +13 -5
- package/esm/http/plugins.mjs.map +1 -1
- package/esm/http/request.d.mts +12 -1
- package/esm/http/request.d.mts.map +1 -1
- package/esm/http/request.mjs +35 -7
- package/esm/http/request.mjs.map +1 -1
- package/esm/http/response.d.mts +16 -0
- package/esm/http/response.d.mts.map +1 -1
- package/esm/http/response.mjs +75 -37
- package/esm/http/response.mjs.map +1 -1
- package/esm/http/types.d.mts +26 -14
- package/esm/http/types.d.mts.map +1 -1
- package/esm/http/uploads/uploaded-file.controller.mjs +1 -1
- package/esm/http/uploads-config.mjs +2 -1
- package/esm/http/uploads-config.mjs.map +1 -1
- package/esm/http/uploads-types.d.mts +3 -3
- package/esm/image/image.d.mts +1 -1
- package/esm/image/image.d.mts.map +1 -1
- package/esm/image/image.mjs +25 -15
- package/esm/image/image.mjs.map +1 -1
- package/esm/index.d.mts +6 -4
- package/esm/index.mjs +7 -4
- package/esm/logger/logger.mjs +6 -1
- package/esm/logger/logger.mjs.map +1 -1
- package/esm/mail/config.d.mts.map +1 -1
- package/esm/mail/config.mjs +31 -21
- package/esm/mail/config.mjs.map +1 -1
- package/esm/mail/react-mail.mjs +6 -3
- package/esm/mail/react-mail.mjs.map +1 -1
- package/esm/mail/send-mail.d.mts.map +1 -1
- package/esm/mail/send-mail.mjs +40 -19
- package/esm/mail/send-mail.mjs.map +1 -1
- package/esm/production/assert-generated-imports.mjs +1 -0
- package/esm/production/assert-generated-imports.mjs.map +1 -1
- package/esm/production/build-contributions.mjs +3 -0
- package/esm/production/build-contributions.mjs.map +1 -1
- package/esm/production/esbuild-plugins.mjs +3 -2
- package/esm/production/esbuild-plugins.mjs.map +1 -1
- package/esm/production/production-builder.mjs +49 -37
- package/esm/production/production-builder.mjs.map +1 -1
- package/esm/production/production-supervisor.mjs +12 -5
- package/esm/production/production-supervisor.mjs.map +1 -1
- package/esm/production/route-registration-child.d.mts +1 -0
- package/esm/production/route-registration-child.mjs +65 -0
- package/esm/production/route-registration-child.mjs.map +1 -0
- package/esm/production/route-registration-snapshot.mjs +166 -0
- package/esm/production/route-registration-snapshot.mjs.map +1 -0
- package/esm/repositories/adapters/cascade/cascade-adapter.d.mts +3 -1
- package/esm/repositories/adapters/cascade/cascade-adapter.d.mts.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-adapter.mjs +22 -12
- package/esm/repositories/adapters/cascade/cascade-adapter.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts +3 -3
- package/esm/repositories/adapters/cascade/cascade-query-builder.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/filter-applicator.mjs +88 -61
- package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/index.d.mts +1 -1
- package/esm/repositories/adapters/cascade/index.mjs +1 -1
- package/esm/repositories/contracts/query-builder.contract.d.mts +3 -3
- package/esm/repositories/contracts/types.d.mts +5 -0
- package/esm/repositories/contracts/types.d.mts.map +1 -1
- package/esm/repositories/index.d.mts +1 -1
- package/esm/repositories/index.mjs +1 -1
- package/esm/repositories/repository.manager.d.mts +65 -3
- package/esm/repositories/repository.manager.d.mts.map +1 -1
- package/esm/repositories/repository.manager.mjs +146 -57
- package/esm/repositories/repository.manager.mjs.map +1 -1
- package/esm/resource/resource-field-builder.d.mts.map +1 -1
- package/esm/resource/resource-field-builder.mjs +1 -0
- package/esm/resource/resource-field-builder.mjs.map +1 -1
- package/esm/resource/resource.d.mts +10 -3
- package/esm/resource/resource.d.mts.map +1 -1
- package/esm/resource/resource.mjs +19 -5
- package/esm/resource/resource.mjs.map +1 -1
- package/esm/restful/restful.d.mts +12 -5
- package/esm/restful/restful.d.mts.map +1 -1
- package/esm/restful/restful.mjs +47 -16
- package/esm/restful/restful.mjs.map +1 -1
- package/esm/router/build-route-rate-limit.mjs +22 -0
- package/esm/router/build-route-rate-limit.mjs.map +1 -0
- package/esm/router/dev-dispatch.mjs +60 -0
- package/esm/router/dev-dispatch.mjs.map +1 -0
- package/esm/router/route-builder.mjs +4 -1
- package/esm/router/route-builder.mjs.map +1 -1
- package/esm/router/route-registry.d.mts.map +1 -1
- package/esm/router/route-registry.mjs +2 -2
- package/esm/router/route-registry.mjs.map +1 -1
- package/esm/router/router.d.mts +1 -1
- package/esm/router/router.d.mts.map +1 -1
- package/esm/router/router.mjs +57 -39
- package/esm/router/router.mjs.map +1 -1
- package/esm/socket/index.d.mts +1 -1
- package/esm/socket/types.d.mts +25 -3
- package/esm/socket/types.d.mts.map +1 -1
- package/esm/storage/drivers/cloud-driver.d.mts +26 -0
- package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
- package/esm/storage/drivers/cloud-driver.mjs +100 -16
- package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
- package/esm/storage/drivers/do-spaces-driver.d.mts +7 -0
- package/esm/storage/drivers/do-spaces-driver.d.mts.map +1 -1
- package/esm/storage/drivers/do-spaces-driver.mjs +9 -2
- package/esm/storage/drivers/do-spaces-driver.mjs.map +1 -1
- package/esm/storage/drivers/local-driver.d.mts +16 -5
- package/esm/storage/drivers/local-driver.d.mts.map +1 -1
- package/esm/storage/drivers/local-driver.mjs +71 -28
- package/esm/storage/drivers/local-driver.mjs.map +1 -1
- package/esm/storage/index.d.mts +3 -1
- package/esm/storage/index.mjs +4 -2
- package/esm/storage/scoped-storage.d.mts +27 -1
- package/esm/storage/scoped-storage.d.mts.map +1 -1
- package/esm/storage/scoped-storage.mjs +40 -8
- package/esm/storage/scoped-storage.mjs.map +1 -1
- package/esm/storage/storage.d.mts +11 -5
- package/esm/storage/storage.d.mts.map +1 -1
- package/esm/storage/storage.mjs +39 -16
- package/esm/storage/storage.mjs.map +1 -1
- package/esm/storage/types.d.mts +43 -4
- package/esm/storage/types.d.mts.map +1 -1
- package/esm/storage/utils/classify-ip-address.d.mts +13 -0
- package/esm/storage/utils/classify-ip-address.d.mts.map +1 -0
- package/esm/storage/utils/classify-ip-address.mjs +98 -0
- package/esm/storage/utils/classify-ip-address.mjs.map +1 -0
- package/esm/storage/utils/safe-fetch.d.mts +3 -12
- package/esm/storage/utils/safe-fetch.d.mts.map +1 -1
- package/esm/storage/utils/safe-fetch.mjs +3 -48
- package/esm/storage/utils/safe-fetch.mjs.map +1 -1
- package/esm/storage/utils/storage-capability-error.d.mts +25 -0
- package/esm/storage/utils/storage-capability-error.d.mts.map +1 -0
- package/esm/storage/utils/storage-capability-error.mjs +26 -0
- package/esm/storage/utils/storage-capability-error.mjs.map +1 -0
- package/esm/updater/update-warlock-packages.mjs +11 -1
- package/esm/updater/update-warlock-packages.mjs.map +1 -1
- package/esm/use-cases/use-case-broadcast.mjs +7 -1
- package/esm/use-cases/use-case-broadcast.mjs.map +1 -1
- package/esm/use-cases/use-cases-registry.mjs +21 -2
- package/esm/use-cases/use-cases-registry.mjs.map +1 -1
- package/esm/utils/database-log.mjs +0 -3
- package/esm/utils/database-log.mjs.map +1 -1
- package/esm/utils/queue.d.mts +6 -4
- package/esm/utils/queue.d.mts.map +1 -1
- package/esm/utils/queue.mjs +20 -9
- package/esm/utils/queue.mjs.map +1 -1
- package/esm/validation/database/exists-except-current-id.mjs +6 -2
- package/esm/validation/database/exists-except-current-id.mjs.map +1 -1
- package/esm/validation/database/unique-except-current-id.mjs +6 -2
- package/esm/validation/database/unique-except-current-id.mjs.map +1 -1
- package/esm/validation/init.mjs +6 -2
- package/esm/validation/init.mjs.map +1 -1
- package/esm/validation/validateAll.mjs +3 -2
- package/esm/validation/validateAll.mjs.map +1 -1
- package/esm/warlock-config/types.d.mts +14 -1
- package/esm/warlock-config/types.d.mts.map +1 -1
- package/esm/warlock-config/warlock-config.manager.d.mts.map +1 -1
- package/esm/warlock-config/warlock-config.manager.mjs +3 -1
- package/esm/warlock-config/warlock-config.manager.mjs.map +1 -1
- package/esm/warlock-config/warn-deprecated-config.mjs +25 -0
- package/esm/warlock-config/warn-deprecated-config.mjs.map +1 -0
- package/llms-full.txt +71 -42
- package/llms.txt +41 -41
- package/package.json +21 -15
- package/skills/add-connector/SKILL.md +5 -1
- package/skills/benchmark-code/SKILL.md +1 -1
- package/skills/build-restful/SKILL.md +1 -1
- package/skills/build-url/SKILL.md +1 -1
- package/skills/configure-app/SKILL.md +7 -1
- package/skills/create-controller/SKILL.md +1 -1
- package/skills/create-module/SKILL.md +1 -1
- package/skills/define-resource/SKILL.md +1 -1
- package/skills/encrypt-data/SKILL.md +1 -1
- package/skills/hash-password/SKILL.md +1 -1
- package/skills/health-checks/SKILL.md +1 -1
- package/skills/index.md +30 -0
- package/skills/lower-stage3-decorators/SKILL.md +1 -1
- package/skills/process-image/SKILL.md +1 -1
- package/skills/register-route/SKILL.md +1 -1
- package/skills/request-memo/SKILL.md +1 -1
- package/skills/request-tracing/SKILL.md +1 -1
- package/skills/resolve-path/SKILL.md +1 -1
- package/skills/retry-operation/SKILL.md +1 -1
- package/skills/run-app/SKILL.md +1 -1
- package/skills/send-mail/SKILL.md +1 -1
- package/skills/send-response/SKILL.md +1 -1
- package/skills/store-file/SKILL.md +11 -1
- package/skills/test-http/SKILL.md +1 -1
- package/skills/test-service/SKILL.md +1 -1
- package/skills/update-packages/SKILL.md +1 -1
- package/skills/upload-file/SKILL.md +1 -1
- package/skills/use-app-context/SKILL.md +1 -1
- package/skills/use-localization/SKILL.md +1 -1
- package/skills/use-middleware/SKILL.md +7 -2
- package/skills/use-model-transformers/SKILL.md +1 -1
- package/skills/use-repository/SKILL.md +1 -1
- package/skills/use-request-locals/SKILL.md +1 -1
- package/skills/validate-input/SKILL.md +1 -1
- package/skills/warlock-conventions/SKILL.md +1 -1
- package/skills/warlock-doctor/SKILL.md +1 -1
- package/skills/warlock-routes/SKILL.md +1 -1
- package/skills/wire-socket/SKILL.md +5 -1
- package/skills/write-cli-command/SKILL.md +1 -1
- package/skills/write-middleware/SKILL.md +1 -1
- package/skills/write-seeder/SKILL.md +1 -1
- package/skills/write-use-case/SKILL.md +1 -1
- package/esm/_virtual/_rolldown/runtime.mjs +0 -7
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
//#region ../core/src/http/build-rate-limit-options.ts
|
|
2
|
+
/**
|
|
3
|
+
* `@fastify/rate-limit` options that `http.rateLimit` passes straight through.
|
|
4
|
+
*/
|
|
5
|
+
const passthroughKeys = [
|
|
6
|
+
"redis",
|
|
7
|
+
"nameSpace",
|
|
8
|
+
"keyGenerator",
|
|
9
|
+
"skipOnError",
|
|
10
|
+
"allowList",
|
|
11
|
+
"continueExceeding",
|
|
12
|
+
"enableDraftSpec",
|
|
13
|
+
"global",
|
|
14
|
+
"hook",
|
|
15
|
+
"cache",
|
|
16
|
+
"errorResponseBuilder",
|
|
17
|
+
"addHeaders",
|
|
18
|
+
"addHeadersOnExceeding"
|
|
19
|
+
];
|
|
20
|
+
/**
|
|
21
|
+
* Build the `@fastify/rate-limit` plugin options from `http.rateLimit`.
|
|
22
|
+
* Returns `null` when the limiter is disabled.
|
|
23
|
+
*/
|
|
24
|
+
function buildRateLimitOptions(config) {
|
|
25
|
+
const source = config ?? {};
|
|
26
|
+
if (source.enabled === false) return null;
|
|
27
|
+
const options = {
|
|
28
|
+
max: source.max ?? 60,
|
|
29
|
+
timeWindow: source.timeWindow ?? source.duration ?? 60 * 1e3
|
|
30
|
+
};
|
|
31
|
+
for (const key of passthroughKeys) if (source[key] !== void 0) options[key] = source[key];
|
|
32
|
+
return options;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
//#endregion
|
|
36
|
+
export { buildRateLimitOptions };
|
|
37
|
+
//# sourceMappingURL=build-rate-limit-options.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"build-rate-limit-options.mjs","names":[],"sources":["../../../../../../../core/src/http/build-rate-limit-options.ts"],"sourcesContent":["import type { RateLimitPluginOptions } from \"@fastify/rate-limit\";\n\n/**\n * `@fastify/rate-limit` options that `http.rateLimit` passes straight through.\n */\nconst passthroughKeys = [\n \"redis\",\n \"nameSpace\",\n \"keyGenerator\",\n \"skipOnError\",\n \"allowList\",\n \"continueExceeding\",\n \"enableDraftSpec\",\n \"global\",\n \"hook\",\n \"cache\",\n \"errorResponseBuilder\",\n \"addHeaders\",\n \"addHeadersOnExceeding\",\n] as const;\n\n/**\n * Shape of the `http.rateLimit` config.\n */\nexport type HttpRateLimitConfig = Pick<RateLimitPluginOptions, (typeof passthroughKeys)[number]> & {\n /**\n * Set `false` to skip registering the global rate limiter.\n *\n * @default true\n */\n enabled?: boolean;\n /**\n * Max requests per time window.\n *\n * @default 60\n */\n max?: number;\n /**\n * Time window in milliseconds. Alias of `timeWindow`.\n *\n * @default 60 * 1000\n */\n duration?: number;\n /**\n * Time window; takes precedence over `duration` when both are set.\n */\n timeWindow?: RateLimitPluginOptions[\"timeWindow\"];\n};\n\n/**\n * Build the `@fastify/rate-limit` plugin options from `http.rateLimit`.\n * Returns `null` when the limiter is disabled.\n */\nexport function buildRateLimitOptions(\n config: HttpRateLimitConfig | undefined,\n): RateLimitPluginOptions | null {\n const source = config ?? {};\n\n if (source.enabled === false) {\n return null;\n }\n\n const options: Record<string, unknown> = {\n max: source.max ?? 60,\n timeWindow: source.timeWindow ?? source.duration ?? 60 * 1000,\n };\n\n for (const key of passthroughKeys) {\n if (source[key] !== undefined) {\n options[key] = source[key];\n }\n }\n\n return options as RateLimitPluginOptions;\n}\n"],"mappings":";;;;AAKA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAkCA,SAAgB,sBACd,QAC+B;CAC/B,MAAM,SAAS,UAAU,CAAC;CAE1B,IAAI,OAAO,YAAY,OACrB,OAAO;CAGT,MAAM,UAAmC;EACvC,KAAK,OAAO,OAAO;EACnB,YAAY,OAAO,cAAc,OAAO,YAAY,KAAK;CAC3D;CAEA,KAAK,MAAM,OAAO,iBAChB,IAAI,OAAO,SAAS,QAClB,QAAQ,OAAO,OAAO;CAI1B,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"csrf-origin-policy.d.mts","names":[],"sources":["../../../../../../../core/src/http/csrf-origin-policy.ts"],"mappings":";;;;KAyBY,qBAAA;AAAZ;AAAA,KAMY,iBAAA;EACN,OAAA;AAAA;EACA,OAAA;EAAgB,MAAA,EAAQ,qBAAqB;AAAA;;;;;;;;AAAA;AAgBnD;;;;AAA0C;
|
|
1
|
+
{"version":3,"file":"csrf-origin-policy.d.mts","names":[],"sources":["../../../../../../../core/src/http/csrf-origin-policy.ts"],"mappings":";;;;KAyBY,qBAAA;AAAZ;AAAA,KAMY,iBAAA;EACN,OAAA;AAAA;EACA,OAAA;EAAgB,MAAA,EAAQ,qBAAqB;AAAA;;;;;;;;AAAA;AAgBnD;;;;AAA0C;AAgB1C;iBAhBgB,SAAA,CAAU,OAAgB,EAAP,OAAO;;iBAgB1B,QAAA,CAAS,MAAc;AAAA;AAgBvC;;;;AAA8C;AAhBP,iBAgBvB,eAAA,CAAgB,MAAc;;iBAc9B,mBAAA,CAAoB,MAAA,UAAgB,OAAA,EAAS,OAAO;;;;;;AAAA;AAqBpE;;;;;iBAAgB,wBAAA,CAAyB,OAAA,EAAS,OAAA,GAAU,iBAAiB"}
|
|
@@ -37,8 +37,9 @@ import config from "@mongez/config";
|
|
|
37
37
|
* function does not need its own proxy-trust logic on top of that.
|
|
38
38
|
*/
|
|
39
39
|
function ownOrigin(request) {
|
|
40
|
+
const fastifyHost = request.baseRequest?.host;
|
|
40
41
|
const hostHeader = request.header("host");
|
|
41
|
-
const host = typeof hostHeader === "string" && hostHeader ? hostHeader : request.hostname;
|
|
42
|
+
const host = typeof fastifyHost === "string" && fastifyHost ? fastifyHost : typeof hostHeader === "string" && hostHeader ? hostHeader : request.hostname;
|
|
42
43
|
return `${request.protocol}://${host}`;
|
|
43
44
|
}
|
|
44
45
|
/** Extract `scheme://host` from a full URL (e.g. a `Referer` header value). */
|
|
@@ -68,7 +69,9 @@ function normalizeOrigin(origin) {
|
|
|
68
69
|
/** Same-origin, or an explicit entry in `auth.csrf.allowedOrigins` (default `[]`). */
|
|
69
70
|
function isAllowedCsrfOrigin(origin, request) {
|
|
70
71
|
if (normalizeOrigin(origin) === normalizeOrigin(ownOrigin(request))) return true;
|
|
71
|
-
|
|
72
|
+
const allowedOrigins = config.get("auth.csrf.allowedOrigins", []);
|
|
73
|
+
const normalized = normalizeOrigin(origin);
|
|
74
|
+
return allowedOrigins.some((allowed) => normalizeOrigin(allowed) === normalized);
|
|
72
75
|
}
|
|
73
76
|
/**
|
|
74
77
|
* The shared CSRF Origin/Referer verdict (lead decision, card 8a752ab2 §3.1):
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"csrf-origin-policy.mjs","names":[],"sources":["../../../../../../../core/src/http/csrf-origin-policy.ts"],"sourcesContent":["/**\n * The Origin/Referer same-origin (or `auth.csrf.allowedOrigins`) policy — the\n * one comparison every CSRF-Origin check in the framework must agree on.\n *\n * SECURITY, card 8a752ab2 (5.17). Extracted from\n * `@warlock.js/auth`'s `csrf-origin-check.ts` (the ONLY prior owner of this\n * logic) into `@warlock.js/core` so both call sites — the\n * `authMiddleware(\"cookie:*\")` check in `@warlock.js/auth` and the default\n * core HTTP-seam guard in `./csrf-default-guard.ts` — share ONE\n * implementation instead of drifting copies. `@warlock.js/core` cannot depend\n * on `@warlock.js/auth` (the dependency runs the other way), so the shared\n * logic had to move down into `core`, not up into a new shared package —\n * `auth`'s `csrf-origin-check.ts` now delegates to\n * {@link resolveCsrfOriginVerdict} instead of reimplementing it.\n *\n * Reads `auth.csrf.allowedOrigins` directly via `@mongez/config` (the exact\n * same config key `@warlock.js/auth`'s `authConfig.csrf.allowedOrigins()`\n * reads) rather than importing `@warlock.js/auth`, so an app's one\n * `auth.csrf.allowedOrigins` setting governs both checks without `core`\n * taking a hard dependency on `auth`.\n */\nimport config from \"@mongez/config\";\nimport type { Request } from \"./request\";\n\n/** Why {@link resolveCsrfOriginVerdict} refused a request. */\nexport type CsrfOriginCheckReason =\n | \"origin-mismatch\"\n | \"referer-mismatch\"\n | \"missing-origin-and-referer\";\n\n/** The verdict {@link resolveCsrfOriginVerdict} reaches for one request. */\nexport type CsrfOriginVerdict =\n | { allowed: true }\n | { allowed: false; reason: CsrfOriginCheckReason };\n\n/**\n * The request's own origin — what an `Origin`/`Referer` header must match.\n *\n * `request.hostname` (core's `Request`, backed by Fastify's `hostname`) never\n * carries a port. A browser's `Origin` header on a non-default port (e.g. any\n * `warlock dev` session) does, so the port must come from the raw `Host`\n * header instead — core exposes no getter for that, so it is read directly\n * here.\n *\n * Trust-proxy-aware for free: `request.protocol` is Fastify's own\n * `request.protocol`, which already honours `http.trustProxy`\n * (`X-Forwarded-Proto`) when the app has configured it (`server.ts`) — this\n * function does not need its own proxy-trust logic on top of that.\n */\nexport function ownOrigin(request: Request): string {\n const hostHeader = request.header(\"host\");\n const host
|
|
1
|
+
{"version":3,"file":"csrf-origin-policy.mjs","names":[],"sources":["../../../../../../../core/src/http/csrf-origin-policy.ts"],"sourcesContent":["/**\n * The Origin/Referer same-origin (or `auth.csrf.allowedOrigins`) policy — the\n * one comparison every CSRF-Origin check in the framework must agree on.\n *\n * SECURITY, card 8a752ab2 (5.17). Extracted from\n * `@warlock.js/auth`'s `csrf-origin-check.ts` (the ONLY prior owner of this\n * logic) into `@warlock.js/core` so both call sites — the\n * `authMiddleware(\"cookie:*\")` check in `@warlock.js/auth` and the default\n * core HTTP-seam guard in `./csrf-default-guard.ts` — share ONE\n * implementation instead of drifting copies. `@warlock.js/core` cannot depend\n * on `@warlock.js/auth` (the dependency runs the other way), so the shared\n * logic had to move down into `core`, not up into a new shared package —\n * `auth`'s `csrf-origin-check.ts` now delegates to\n * {@link resolveCsrfOriginVerdict} instead of reimplementing it.\n *\n * Reads `auth.csrf.allowedOrigins` directly via `@mongez/config` (the exact\n * same config key `@warlock.js/auth`'s `authConfig.csrf.allowedOrigins()`\n * reads) rather than importing `@warlock.js/auth`, so an app's one\n * `auth.csrf.allowedOrigins` setting governs both checks without `core`\n * taking a hard dependency on `auth`.\n */\nimport config from \"@mongez/config\";\nimport type { Request } from \"./request\";\n\n/** Why {@link resolveCsrfOriginVerdict} refused a request. */\nexport type CsrfOriginCheckReason =\n | \"origin-mismatch\"\n | \"referer-mismatch\"\n | \"missing-origin-and-referer\";\n\n/** The verdict {@link resolveCsrfOriginVerdict} reaches for one request. */\nexport type CsrfOriginVerdict =\n | { allowed: true }\n | { allowed: false; reason: CsrfOriginCheckReason };\n\n/**\n * The request's own origin — what an `Origin`/`Referer` header must match.\n *\n * `request.hostname` (core's `Request`, backed by Fastify's `hostname`) never\n * carries a port. A browser's `Origin` header on a non-default port (e.g. any\n * `warlock dev` session) does, so the port must come from the raw `Host`\n * header instead — core exposes no getter for that, so it is read directly\n * here.\n *\n * Trust-proxy-aware for free: `request.protocol` is Fastify's own\n * `request.protocol`, which already honours `http.trustProxy`\n * (`X-Forwarded-Proto`) when the app has configured it (`server.ts`) — this\n * function does not need its own proxy-trust logic on top of that.\n */\nexport function ownOrigin(request: Request): string {\n // Fastify's `host` keeps the port and honours `X-Forwarded-Host` under\n // `trustProxy`, so a proxy that rewrites `Host` does not break the match.\n const fastifyHost = request.baseRequest?.host;\n const hostHeader = request.header(\"host\");\n const host =\n typeof fastifyHost === \"string\" && fastifyHost\n ? fastifyHost\n : typeof hostHeader === \"string\" && hostHeader\n ? hostHeader\n : request.hostname;\n\n return `${request.protocol}://${host}`;\n}\n\n/** Extract `scheme://host` from a full URL (e.g. a `Referer` header value). */\nexport function originOf(rawUrl: string): string | undefined {\n try {\n const url = new URL(rawUrl);\n\n return `${url.protocol}//${url.host}`;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Normalize an origin string (`scheme://host[:port]`) so that a default port\n * (`:80` on `http:`, `:443` on `https:`) compares equal to the same origin\n * written without a port. Falls back to the raw value if it does not parse\n * as a URL (in which case it will simply fail the exact-match comparison).\n */\nexport function normalizeOrigin(origin: string): string {\n try {\n const url = new URL(origin);\n const isDefaultPort =\n (url.protocol === \"http:\" && (url.port === \"\" || url.port === \"80\")) ||\n (url.protocol === \"https:\" && (url.port === \"\" || url.port === \"443\"));\n\n return `${url.protocol}//${isDefaultPort ? url.hostname : url.host}`;\n } catch {\n return origin;\n }\n}\n\n/** Same-origin, or an explicit entry in `auth.csrf.allowedOrigins` (default `[]`). */\nexport function isAllowedCsrfOrigin(origin: string, request: Request): boolean {\n if (normalizeOrigin(origin) === normalizeOrigin(ownOrigin(request))) return true;\n\n const allowedOrigins: string[] = config.get(\"auth.csrf.allowedOrigins\", []);\n\n const normalized = normalizeOrigin(origin);\n\n return allowedOrigins.some(allowed => normalizeOrigin(allowed) === normalized);\n}\n\n/**\n * The shared CSRF Origin/Referer verdict (lead decision, card 8a752ab2 §3.1):\n * allowed when `Origin` — or, when `Origin` is absent, `Referer` — names the\n * request's own origin or an entry in `auth.csrf.allowedOrigins`. Refused\n * otherwise, including when BOTH headers are absent (fail closed).\n *\n * Callers decide WHETHER a request is in scope for this check at all (a\n * cookie-sourced credential / a non-locale cookie, an unsafe method, no route\n * exemption) — this function only answers the Origin/Referer question once a\n * caller has already decided the check applies.\n */\nexport function resolveCsrfOriginVerdict(request: Request): CsrfOriginVerdict {\n const origin = request.origin;\n\n if (origin) {\n return isAllowedCsrfOrigin(origin, request)\n ? { allowed: true }\n : { allowed: false, reason: \"origin-mismatch\" };\n }\n\n const referer = request.header(\"referer\");\n const refererOrigin = typeof referer === \"string\" ? originOf(referer) : undefined;\n\n if (refererOrigin) {\n return isAllowedCsrfOrigin(refererOrigin, request)\n ? { allowed: true }\n : { allowed: false, reason: \"referer-mismatch\" };\n }\n\n return { allowed: false, reason: \"missing-origin-and-referer\" };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,UAAU,SAA0B;CAGlD,MAAM,cAAc,QAAQ,aAAa;CACzC,MAAM,aAAa,QAAQ,OAAO,MAAM;CACxC,MAAM,OACJ,OAAO,gBAAgB,YAAY,cAC/B,cACA,OAAO,eAAe,YAAY,aAChC,aACA,QAAQ;CAEhB,OAAO,GAAG,QAAQ,SAAS,KAAK;AAClC;;AAGA,SAAgB,SAAS,QAAoC;CAC3D,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,MAAM;EAE1B,OAAO,GAAG,IAAI,SAAS,IAAI,IAAI;CACjC,QAAQ;EACN;CACF;AACF;;;;;;;AAQA,SAAgB,gBAAgB,QAAwB;CACtD,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,MAAM;EAC1B,MAAM,gBACH,IAAI,aAAa,YAAY,IAAI,SAAS,MAAM,IAAI,SAAS,SAC7D,IAAI,aAAa,aAAa,IAAI,SAAS,MAAM,IAAI,SAAS;EAEjE,OAAO,GAAG,IAAI,SAAS,IAAI,gBAAgB,IAAI,WAAW,IAAI;CAChE,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,SAAgB,oBAAoB,QAAgB,SAA2B;CAC7E,IAAI,gBAAgB,MAAM,MAAM,gBAAgB,UAAU,OAAO,CAAC,GAAG,OAAO;CAE5E,MAAM,iBAA2B,OAAO,IAAI,4BAA4B,CAAC,CAAC;CAE1E,MAAM,aAAa,gBAAgB,MAAM;CAEzC,OAAO,eAAe,MAAK,YAAW,gBAAgB,OAAO,MAAM,UAAU;AAC/E;;;;;;;;;;;;AAaA,SAAgB,yBAAyB,SAAqC;CAC5E,MAAM,SAAS,QAAQ;CAEvB,IAAI,QACF,OAAO,oBAAoB,QAAQ,OAAO,IACtC,EAAE,SAAS,KAAK,IAChB;EAAE,SAAS;EAAO,QAAQ;CAAkB;CAGlD,MAAM,UAAU,QAAQ,OAAO,SAAS;CACxC,MAAM,gBAAgB,OAAO,YAAY,WAAW,SAAS,OAAO,IAAI;CAExE,IAAI,eACF,OAAO,oBAAoB,eAAe,OAAO,IAC7C,EAAE,SAAS,KAAK,IAChB;EAAE,SAAS;EAAO,QAAQ;CAAmB;CAGnD,OAAO;EAAE,SAAS;EAAO,QAAQ;CAA6B;AAChE"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
//#region ../core/src/http/flush-pending-cookies.ts
|
|
5
|
+
/** The installed `@fastify/cookie` version, or undefined when it can't be resolved. */
|
|
6
|
+
function installedCookiePluginVersion() {
|
|
7
|
+
try {
|
|
8
|
+
const require = createRequire(path.join(process.cwd(), "noop.js"));
|
|
9
|
+
return require(require.resolve("@fastify/cookie/package.json")).version;
|
|
10
|
+
} catch {
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* `@fastify/cookie` only parks cookies set via `reply.setCookie()` in a map
|
|
16
|
+
* keyed by a private symbol; it serialises them in its own `onSend` hook.
|
|
17
|
+
* Raw-path writers (`raw.writeHead`) bypass `onSend`, so they must call this
|
|
18
|
+
* right before writing headers.
|
|
19
|
+
*
|
|
20
|
+
* Serialises the parked cookies, appends them to the `set-cookie` header
|
|
21
|
+
* (skipping any value already present) and clears the map so a later `onSend`
|
|
22
|
+
* cannot send them twice.
|
|
23
|
+
*
|
|
24
|
+
* Throws when the plugin is registered but its parked-cookie symbol cannot be
|
|
25
|
+
* found: silently doing nothing would drop every cookie on raw paths. Does
|
|
26
|
+
* nothing when the plugin is not registered.
|
|
27
|
+
*/
|
|
28
|
+
function flushPendingCookies(reply) {
|
|
29
|
+
const parkedSymbol = Object.getOwnPropertySymbols(reply).find((symbol) => symbol.description === "fastify.reply.setCookies");
|
|
30
|
+
if (!parkedSymbol) {
|
|
31
|
+
if (typeof reply.setCookie !== "function") return;
|
|
32
|
+
const version = installedCookiePluginVersion();
|
|
33
|
+
throw new Error(`@fastify/cookie's internal cookie storage changed: reply.setCookie exists but the "fastify.reply.setCookies" symbol was not found${version ? ` (installed @fastify/cookie@${version})` : ""}. Cookies set before a raw-path response would be lost; update flushPendingCookies for this version.`);
|
|
34
|
+
}
|
|
35
|
+
const parked = reply[parkedSymbol];
|
|
36
|
+
if (!parked || parked.size === 0) return;
|
|
37
|
+
const serializeCookie = reply.server.serializeCookie;
|
|
38
|
+
if (!serializeCookie) return;
|
|
39
|
+
const existing = reply.getHeader("set-cookie");
|
|
40
|
+
const cookies = existing === void 0 ? [] : Array.isArray(existing) ? [...existing] : [String(existing)];
|
|
41
|
+
for (const cookie of parked.values()) {
|
|
42
|
+
const serialized = serializeCookie(cookie.name, cookie.value, cookie.opts);
|
|
43
|
+
if (!cookies.includes(serialized)) cookies.push(serialized);
|
|
44
|
+
}
|
|
45
|
+
reply.removeHeader("set-cookie");
|
|
46
|
+
reply.header("set-cookie", cookies);
|
|
47
|
+
parked.clear();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
//#endregion
|
|
51
|
+
export { flushPendingCookies };
|
|
52
|
+
//# sourceMappingURL=flush-pending-cookies.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"flush-pending-cookies.mjs","names":[],"sources":["../../../../../../../core/src/http/flush-pending-cookies.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport type { FastifyReply } from \"fastify\";\n\ntype ParkedCookie = { name: string; value: string; opts?: Record<string, unknown> };\n\n/** The installed `@fastify/cookie` version, or undefined when it can't be resolved. */\nfunction installedCookiePluginVersion(): string | undefined {\n try {\n const require = createRequire(path.join(process.cwd(), \"noop.js\"));\n\n return (require(require.resolve(\"@fastify/cookie/package.json\")) as { version?: string })\n .version;\n } catch {\n return undefined;\n }\n}\n\n/**\n * `@fastify/cookie` only parks cookies set via `reply.setCookie()` in a map\n * keyed by a private symbol; it serialises them in its own `onSend` hook.\n * Raw-path writers (`raw.writeHead`) bypass `onSend`, so they must call this\n * right before writing headers.\n *\n * Serialises the parked cookies, appends them to the `set-cookie` header\n * (skipping any value already present) and clears the map so a later `onSend`\n * cannot send them twice.\n *\n * Throws when the plugin is registered but its parked-cookie symbol cannot be\n * found: silently doing nothing would drop every cookie on raw paths. Does\n * nothing when the plugin is not registered.\n */\nexport function flushPendingCookies(reply: FastifyReply): void {\n const parkedSymbol = Object.getOwnPropertySymbols(reply).find(\n symbol => symbol.description === \"fastify.reply.setCookies\",\n );\n\n if (!parkedSymbol) {\n if (typeof (reply as { setCookie?: unknown }).setCookie !== \"function\") return;\n\n const version = installedCookiePluginVersion();\n\n throw new Error(\n `@fastify/cookie's internal cookie storage changed: reply.setCookie exists but the \"fastify.reply.setCookies\" symbol was not found${\n version ? ` (installed @fastify/cookie@${version})` : \"\"\n }. Cookies set before a raw-path response would be lost; update flushPendingCookies for this version.`,\n );\n }\n\n const parked = (reply as unknown as Record<symbol, Map<string, ParkedCookie> | null>)[\n parkedSymbol\n ];\n\n if (!parked || parked.size === 0) return;\n\n const serializeCookie = (\n reply.server as unknown as {\n serializeCookie?: (name: string, value: string, opts?: unknown) => string;\n }\n ).serializeCookie;\n\n if (!serializeCookie) return;\n\n const existing = reply.getHeader(\"set-cookie\");\n const cookies: string[] =\n existing === undefined ? [] : Array.isArray(existing) ? [...existing] : [String(existing)];\n\n for (const cookie of parked.values()) {\n const serialized = serializeCookie(cookie.name, cookie.value, cookie.opts);\n\n if (!cookies.includes(serialized)) {\n cookies.push(serialized);\n }\n }\n\n reply.removeHeader(\"set-cookie\");\n reply.header(\"set-cookie\", cookies);\n parked.clear();\n}\n"],"mappings":";;;;;AAOA,SAAS,+BAAmD;CAC1D,IAAI;EACF,MAAM,UAAU,cAAc,KAAK,KAAK,QAAQ,IAAI,GAAG,SAAS,CAAC;EAEjE,OAAQ,QAAQ,QAAQ,QAAQ,8BAA8B,CAAC,CAAC,CAC7D;CACL,QAAQ;EACN;CACF;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,oBAAoB,OAA2B;CAC7D,MAAM,eAAe,OAAO,sBAAsB,KAAK,CAAC,CAAC,MACvD,WAAU,OAAO,gBAAgB,0BACnC;CAEA,IAAI,CAAC,cAAc;EACjB,IAAI,OAAQ,MAAkC,cAAc,YAAY;EAExE,MAAM,UAAU,6BAA6B;EAE7C,MAAM,IAAI,MACR,oIACE,UAAU,+BAA+B,QAAQ,KAAK,GACvD,qGACH;CACF;CAEA,MAAM,SAAU,MACd;CAGF,IAAI,CAAC,UAAU,OAAO,SAAS,GAAG;CAElC,MAAM,kBACJ,MAAM,OAGN;CAEF,IAAI,CAAC,iBAAiB;CAEtB,MAAM,WAAW,MAAM,UAAU,YAAY;CAC7C,MAAM,UACJ,aAAa,SAAY,CAAC,IAAI,MAAM,QAAQ,QAAQ,IAAI,CAAC,GAAG,QAAQ,IAAI,CAAC,OAAO,QAAQ,CAAC;CAE3F,KAAK,MAAM,UAAU,OAAO,OAAO,GAAG;EACpC,MAAM,aAAa,gBAAgB,OAAO,MAAM,OAAO,OAAO,OAAO,IAAI;EAEzE,IAAI,CAAC,QAAQ,SAAS,UAAU,GAC9B,QAAQ,KAAK,UAAU;CAE3B;CAEA,MAAM,aAAa,YAAY;CAC/B,MAAM,OAAO,cAAc,OAAO;CAClC,OAAO,MAAM;AACf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-response-middleware.d.mts","names":[],"sources":["../../../../../../../../core/src/http/middleware/cache-response-middleware.ts"],"mappings":";;;;KAsBY,sBAAA;;AAAZ;;EAIE,QAAA,aAAqB,OAAA,EAAS,OAAA,iBAAwB,OAAA,EAAS,OAAA,KAAY,OAAA;EAA7C;;;;;;EAO9B,UAAA;EAP8B;;;;;EAa9B,IAAA;EAAA;;;EAIA,GAAA;EAmB6B;;;AAAO;
|
|
1
|
+
{"version":3,"file":"cache-response-middleware.d.mts","names":[],"sources":["../../../../../../../../core/src/http/middleware/cache-response-middleware.ts"],"mappings":";;;;KAsBY,sBAAA;;AAAZ;;EAIE,QAAA,aAAqB,OAAA,EAAS,OAAA,iBAAwB,OAAA,EAAS,OAAA,KAAY,OAAA;EAA7C;;;;;;EAO9B,UAAA;EAP8B;;;;;EAa9B,IAAA;EAAA;;;EAIA,GAAA;EAmB6B;;;AAAO;AA+DtC;;EA3EE,MAAA;EA2EgG;;;;;AAAA;;;;;;EA/DhG,IAAA,gBAAoB,OAAA,EAAS,OAAA;AAAA;AAAA,iBA+Df,eAAA,CAAgB,oBAAA,EAAsB,sBAAA,YAAkC,UAAU"}
|
|
@@ -16,12 +16,14 @@ function resolveCacheTags(tags, request) {
|
|
|
16
16
|
}
|
|
17
17
|
async function parseCacheOptions(cacheOptions, request) {
|
|
18
18
|
if (typeof cacheOptions === "string") cacheOptions = { cacheKey: cacheOptions };
|
|
19
|
-
|
|
19
|
+
const resolvedCacheKey = typeof cacheOptions.cacheKey === "function" ? await cacheOptions.cacheKey(request) : cacheOptions.cacheKey;
|
|
20
20
|
const tags = resolveCacheTags(cacheOptions.tags, request);
|
|
21
21
|
const finalCacheOptions = {
|
|
22
22
|
...defaultCacheOptions,
|
|
23
23
|
...cacheOptions,
|
|
24
|
-
|
|
24
|
+
cacheKey: resolvedCacheKey,
|
|
25
|
+
tags: [...tags],
|
|
26
|
+
omit: cacheOptions.omit ? [...cacheOptions.omit] : void 0
|
|
25
27
|
};
|
|
26
28
|
if (finalCacheOptions.withLocale) {
|
|
27
29
|
const locale = request.getLocaleCode();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-response-middleware.mjs","names":[],"sources":["../../../../../../../../core/src/http/middleware/cache-response-middleware.ts"],"sourcesContent":["import { except } from \"@mongez/reinforcements\";\nimport { cache } from \"@warlock.js/cache\";\nimport { log } from \"@warlock.js/logger\";\nimport type { Middleware } from \"../../router/types\";\nimport type { Request } from \"./../request\";\nimport type { Response } from \"./../response\";\n\n/**\n * Shape persisted to the cache for a cached response. Stores the status and\n * content-type alongside the body so the HIT path can replay the response\n * faithfully via {@link Response.replay} instead of re-entering `send()`.\n */\ntype CachedResponsePayload = {\n status: number;\n data: unknown;\n contentType?: string;\n};\n\n// TODO: Add option to determine whether to cache the response or not\n// TODO: add option to determine what to be cached from the response\n// TODO: add cache middleware config options for example to set the default driver, ttl, etc\n\nexport type CacheMiddlewareOptions = {\n /**\n * Cache key\n */\n cacheKey: string | ((request: Request) => string) | ((request: Request) => Promise<string>);\n /**\n * If true, then the response will be cached based on the current locale code\n * This is useful when you have a multi-language website, and you want to cache the response based on the current locale\n *\n * @default true\n */\n withLocale?: boolean;\n /**\n * List of keys from the response object to omit from the cached response\n *\n * @default ['user']\n */\n omit?: string[];\n /**\n * Expires after number of seconds\n */\n ttl?: number;\n /**\n * Cache driver\n *\n * @see config/cache.ts: drivers object\n * @default cache manager\n */\n driver?: string;\n /**\n * Tags this cached response is stored under, mirroring `route.cache.tags`\n * on `@warlock.js/web`'s page cache (`PageCacheOptIn.tags`,\n * `web/src/routing/route-identity.ts`) so the two caches share one mental\n * model: `cache.tags([...]).invalidate()` from `@warlock.js/cache` evicts\n * a tagged API response the same way it evicts a tagged page. Either a\n * static list, or a function of the request — resolved once per request,\n * right before the response is stored.\n *\n * @default undefined (untagged — behaves exactly as before this option existed)\n */\n tags?: string[] | ((request: Request) => string[]);\n};\n\nconst defaultCacheOptions: Partial<CacheMiddlewareOptions> = {\n withLocale: true,\n};\n\ntype ParsedCacheOptions = Required<Omit<CacheMiddlewareOptions, \"tags\">> & {\n cacheKey: string;\n /** Resolved, concrete tag list — see {@link resolveCacheTags}. */\n tags: string[];\n};\n\n/**\n * Resolves `CacheMiddlewareOptions.tags` — a static list or a function of\n * the request — into a concrete list at store time. Mirrors\n * `resolveCacheTags` in `@warlock.js/web`'s `create-page-route-handler.ts`,\n * the equivalent seam for `route.cache.tags`.\n */\nfunction resolveCacheTags(tags: CacheMiddlewareOptions[\"tags\"], request: Request): string[] {\n if (tags === undefined) return [];\n\n return typeof tags === \"function\" ? tags(request) : tags;\n}\n\nasync function parseCacheOptions(cacheOptions: CacheMiddlewareOptions | string, request: Request) {\n if (typeof cacheOptions === \"string\") {\n cacheOptions = {\n cacheKey: cacheOptions,\n };\n }\n\n
|
|
1
|
+
{"version":3,"file":"cache-response-middleware.mjs","names":[],"sources":["../../../../../../../../core/src/http/middleware/cache-response-middleware.ts"],"sourcesContent":["import { except } from \"@mongez/reinforcements\";\nimport { cache } from \"@warlock.js/cache\";\nimport { log } from \"@warlock.js/logger\";\nimport type { Middleware } from \"../../router/types\";\nimport type { Request } from \"./../request\";\nimport type { Response } from \"./../response\";\n\n/**\n * Shape persisted to the cache for a cached response. Stores the status and\n * content-type alongside the body so the HIT path can replay the response\n * faithfully via {@link Response.replay} instead of re-entering `send()`.\n */\ntype CachedResponsePayload = {\n status: number;\n data: unknown;\n contentType?: string;\n};\n\n// TODO: Add option to determine whether to cache the response or not\n// TODO: add option to determine what to be cached from the response\n// TODO: add cache middleware config options for example to set the default driver, ttl, etc\n\nexport type CacheMiddlewareOptions = {\n /**\n * Cache key\n */\n cacheKey: string | ((request: Request) => string) | ((request: Request) => Promise<string>);\n /**\n * If true, then the response will be cached based on the current locale code\n * This is useful when you have a multi-language website, and you want to cache the response based on the current locale\n *\n * @default true\n */\n withLocale?: boolean;\n /**\n * List of keys from the response object to omit from the cached response\n *\n * @default ['user']\n */\n omit?: string[];\n /**\n * Expires after number of seconds\n */\n ttl?: number;\n /**\n * Cache driver\n *\n * @see config/cache.ts: drivers object\n * @default cache manager\n */\n driver?: string;\n /**\n * Tags this cached response is stored under, mirroring `route.cache.tags`\n * on `@warlock.js/web`'s page cache (`PageCacheOptIn.tags`,\n * `web/src/routing/route-identity.ts`) so the two caches share one mental\n * model: `cache.tags([...]).invalidate()` from `@warlock.js/cache` evicts\n * a tagged API response the same way it evicts a tagged page. Either a\n * static list, or a function of the request — resolved once per request,\n * right before the response is stored.\n *\n * @default undefined (untagged — behaves exactly as before this option existed)\n */\n tags?: string[] | ((request: Request) => string[]);\n};\n\nconst defaultCacheOptions: Partial<CacheMiddlewareOptions> = {\n withLocale: true,\n};\n\ntype ParsedCacheOptions = Required<Omit<CacheMiddlewareOptions, \"tags\">> & {\n cacheKey: string;\n /** Resolved, concrete tag list — see {@link resolveCacheTags}. */\n tags: string[];\n};\n\n/**\n * Resolves `CacheMiddlewareOptions.tags` — a static list or a function of\n * the request — into a concrete list at store time. Mirrors\n * `resolveCacheTags` in `@warlock.js/web`'s `create-page-route-handler.ts`,\n * the equivalent seam for `route.cache.tags`.\n */\nfunction resolveCacheTags(tags: CacheMiddlewareOptions[\"tags\"], request: Request): string[] {\n if (tags === undefined) return [];\n\n return typeof tags === \"function\" ? tags(request) : tags;\n}\n\nasync function parseCacheOptions(cacheOptions: CacheMiddlewareOptions | string, request: Request) {\n if (typeof cacheOptions === \"string\") {\n cacheOptions = {\n cacheKey: cacheOptions,\n };\n }\n\n // Everything below resolves into a fresh per-request object; the options\n // the factory closed over are shared across all requests and users, so they\n // must never be written to.\n const resolvedCacheKey =\n typeof cacheOptions.cacheKey === \"function\"\n ? await cacheOptions.cacheKey(request)\n : cacheOptions.cacheKey;\n\n const tags = resolveCacheTags(cacheOptions.tags, request);\n\n const finalCacheOptions = {\n ...defaultCacheOptions,\n ...cacheOptions,\n cacheKey: resolvedCacheKey,\n tags: [...tags],\n omit: cacheOptions.omit ? [...cacheOptions.omit] : undefined,\n } as unknown as ParsedCacheOptions;\n\n if (finalCacheOptions.withLocale) {\n const locale = request.getLocaleCode();\n\n finalCacheOptions.cacheKey = `${finalCacheOptions.cacheKey}:${locale}`;\n }\n\n if (!finalCacheOptions.omit) {\n finalCacheOptions.omit = [\"user\", \"settings\"];\n }\n\n return finalCacheOptions;\n}\n\nexport function cacheMiddleware(responseCacheOptions: CacheMiddlewareOptions | string): Middleware {\n // The `Middleware` return annotation is load-bearing: without it, tsc never\n // checks this factory's calling convention, which is how the positional v4\n // shape survived an earlier refactor unnoticed.\n return async function ({ request, response }) {\n const { ttl, omit, cacheKey, driver, tags } = await parseCacheOptions(\n responseCacheOptions,\n request,\n );\n const cacheDriver = driver ? await cache.use(driver) : cache;\n\n const content = (await cacheDriver.get(cacheKey)) as CachedResponsePayload | null;\n\n if (content) {\n // Replay through the standard pipeline (status + content-type preserved)\n // instead of `baseResponse.send()`, which would re-enter Response.send()\n // on an already-sent reply, trip the double-send guard, and drop the\n // status / content-type.\n return response.replay({\n status: content.status ?? 200,\n body: content.data,\n contentType: content.contentType,\n });\n }\n\n response.onSent((response: Response) => {\n if (!response.isOk || response.request.path !== request.path) {\n return;\n }\n\n const sentContentType = response.contentType;\n\n const content: CachedResponsePayload = {\n status: response.statusCode,\n data: except(response.parsedBody, omit),\n contentType: typeof sentContentType === \"string\" ? sentContentType : undefined,\n };\n\n // `set` is fire-and-forget inside `onSent`; without a `.catch` a rejected\n // write (e.g. Redis down) would surface as an unhandledRejection.\n //\n // Tagged and untagged writes go through separate calls rather than a\n // shared branch-free path so an untagged route's write stays byte\n // identical to what it was before `tags` existed.\n const write =\n tags.length > 0\n ? cacheDriver.tags(tags).set(cacheKey, content, ttl)\n : cacheDriver.set(cacheKey, content, ttl);\n\n write.catch((error: unknown) => {\n log.error(\"cache-middleware\", \"set\", error);\n });\n });\n };\n}\n"],"mappings":";;;;;AAiEA,MAAM,sBAAuD,EAC3D,YAAY,KACd;;;;;;;AAcA,SAAS,iBAAiB,MAAsC,SAA4B;CAC1F,IAAI,SAAS,QAAW,OAAO,CAAC;CAEhC,OAAO,OAAO,SAAS,aAAa,KAAK,OAAO,IAAI;AACtD;AAEA,eAAe,kBAAkB,cAA+C,SAAkB;CAChG,IAAI,OAAO,iBAAiB,UAC1B,eAAe,EACb,UAAU,aACZ;CAMF,MAAM,mBACJ,OAAO,aAAa,aAAa,aAC7B,MAAM,aAAa,SAAS,OAAO,IACnC,aAAa;CAEnB,MAAM,OAAO,iBAAiB,aAAa,MAAM,OAAO;CAExD,MAAM,oBAAoB;EACxB,GAAG;EACH,GAAG;EACH,UAAU;EACV,MAAM,CAAC,GAAG,IAAI;EACd,MAAM,aAAa,OAAO,CAAC,GAAG,aAAa,IAAI,IAAI;CACrD;CAEA,IAAI,kBAAkB,YAAY;EAChC,MAAM,SAAS,QAAQ,cAAc;EAErC,kBAAkB,WAAW,GAAG,kBAAkB,SAAS,GAAG;CAChE;CAEA,IAAI,CAAC,kBAAkB,MACrB,kBAAkB,OAAO,CAAC,QAAQ,UAAU;CAG9C,OAAO;AACT;AAEA,SAAgB,gBAAgB,sBAAmE;CAIjG,OAAO,eAAgB,EAAE,SAAS,YAAY;EAC5C,MAAM,EAAE,KAAK,MAAM,UAAU,QAAQ,SAAS,MAAM,kBAClD,sBACA,OACF;EACA,MAAM,cAAc,SAAS,MAAM,MAAM,IAAI,MAAM,IAAI;EAEvD,MAAM,UAAW,MAAM,YAAY,IAAI,QAAQ;EAE/C,IAAI,SAKF,OAAO,SAAS,OAAO;GACrB,QAAQ,QAAQ,UAAU;GAC1B,MAAM,QAAQ;GACd,aAAa,QAAQ;EACvB,CAAC;EAGH,SAAS,QAAQ,aAAuB;GACtC,IAAI,CAAC,SAAS,QAAQ,SAAS,QAAQ,SAAS,QAAQ,MACtD;GAGF,MAAM,kBAAkB,SAAS;GAEjC,MAAM,UAAiC;IACrC,QAAQ,SAAS;IACjB,MAAM,OAAO,SAAS,YAAY,IAAI;IACtC,aAAa,OAAO,oBAAoB,WAAW,kBAAkB;GACvE;GAaA,CAJE,KAAK,SAAS,IACV,YAAY,KAAK,IAAI,CAAC,CAAC,IAAI,UAAU,SAAS,GAAG,IACjD,YAAY,IAAI,UAAU,SAAS,GAAG,EAEvC,CAAC,OAAO,UAAmB;IAC9B,IAAI,MAAM,oBAAoB,OAAO,KAAK;GAC5C,CAAC;EACH,CAAC;CACH;AACF"}
|
|
@@ -8,6 +8,11 @@ type IdempotencyOptions = {
|
|
|
8
8
|
* Cache TTL in seconds. Falls back to `http.idempotency.ttl`, then `86400` (24h).
|
|
9
9
|
*/
|
|
10
10
|
ttl?: number;
|
|
11
|
+
/**
|
|
12
|
+
* TTL in seconds of the in-flight reservation held while the handler runs.
|
|
13
|
+
* Falls back to `http.idempotency.reservationTtl`, then `60`.
|
|
14
|
+
*/
|
|
15
|
+
reservationTtl?: number;
|
|
11
16
|
/**
|
|
12
17
|
* Header name carrying the client's key. Falls back to
|
|
13
18
|
* `http.idempotency.headerName`, then `"Idempotency-Key"`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"idempotency.middleware.d.mts","names":[],"sources":["../../../../../../../../core/src/http/middleware/idempotency.middleware.ts"],"mappings":";;;;;KAYY,kBAAA;EAAkB;;;EAI5B,GAAA;EAKA;;;;EAAA,UAAA;
|
|
1
|
+
{"version":3,"file":"idempotency.middleware.d.mts","names":[],"sources":["../../../../../../../../core/src/http/middleware/idempotency.middleware.ts"],"mappings":";;;;;KAYY,kBAAA;EAAkB;;;EAI5B,GAAA;EAKA;;;;EAAA,cAAA;EAgBM;AA+CR;;;EA1DE,UAAA;EA0D6C;;;;AAAoC;EApDjF,OAAA;;;;;EAKA,MAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+Cc,qBAAA,CAAsB,OAAA,GAAS,kBAAA,GAA0B,UAAU"}
|
|
@@ -47,6 +47,7 @@ function idempotencyMiddleware(options = {}) {
|
|
|
47
47
|
const headerName = options.headerName || config.get("http.idempotency.headerName", "Idempotency-Key");
|
|
48
48
|
const methods = options.methods || config.get("http.idempotency.methods", DEFAULT_METHODS);
|
|
49
49
|
const ttl = options.ttl || config.get("http.idempotency.ttl", 86400);
|
|
50
|
+
const reservationTtl = options.reservationTtl || config.get("http.idempotency.reservationTtl", 60);
|
|
50
51
|
const driverName = options.driver || config.get("http.idempotency.driver");
|
|
51
52
|
if (!methods.includes(request.method.toUpperCase())) return;
|
|
52
53
|
const idempotencyKey = request.header(headerName.toLowerCase());
|
|
@@ -58,8 +59,15 @@ function idempotencyMiddleware(options = {}) {
|
|
|
58
59
|
const cacheDriver = driverName ? await cache.use(driverName) : cache;
|
|
59
60
|
const cacheKey = buildIdempotencyCacheKey(request, idempotencyKey);
|
|
60
61
|
const bodyHash = hashBody(request.body);
|
|
61
|
-
const
|
|
62
|
-
|
|
62
|
+
const respondToExisting = (existing) => {
|
|
63
|
+
if (!existing || existing.state === "in-flight") {
|
|
64
|
+
response.header("Retry-After", "1");
|
|
65
|
+
return response.conflict({
|
|
66
|
+
error: "A request with this Idempotency-Key is already in progress",
|
|
67
|
+
errorCode: "EC100"
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
const cached = existing;
|
|
63
71
|
if (cached.bodyHash !== bodyHash) return response.unprocessableEntity({
|
|
64
72
|
error: t("http.idempotencyKeyConflict"),
|
|
65
73
|
errorCode: "EC100"
|
|
@@ -70,9 +78,33 @@ function idempotencyMiddleware(options = {}) {
|
|
|
70
78
|
body: cached.body,
|
|
71
79
|
contentType: cached.contentType
|
|
72
80
|
});
|
|
81
|
+
};
|
|
82
|
+
let existing = null;
|
|
83
|
+
try {
|
|
84
|
+
existing = await cacheDriver.get(cacheKey);
|
|
85
|
+
} catch (error) {
|
|
86
|
+
log.error("idempotency-middleware", "get", error);
|
|
87
|
+
}
|
|
88
|
+
if (existing) return respondToExisting(existing);
|
|
89
|
+
try {
|
|
90
|
+
const reservation = await cacheDriver.set(cacheKey, {
|
|
91
|
+
state: "in-flight",
|
|
92
|
+
startedAt: Date.now()
|
|
93
|
+
}, {
|
|
94
|
+
onConflict: "create",
|
|
95
|
+
ttl: reservationTtl
|
|
96
|
+
});
|
|
97
|
+
if (reservation && reservation.wasSet === false) return respondToExisting(reservation.existing);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
log.error("idempotency-middleware", "reserve", error);
|
|
73
100
|
}
|
|
74
101
|
response.onSent((sentResponse) => {
|
|
75
|
-
if (sentResponse.statusCode >= 500)
|
|
102
|
+
if (sentResponse.statusCode >= 500) {
|
|
103
|
+
Promise.resolve().then(() => cacheDriver.remove(cacheKey)).catch((error) => {
|
|
104
|
+
log.error("idempotency-middleware", "remove", error);
|
|
105
|
+
});
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
76
108
|
const sentContentType = sentResponse.contentType;
|
|
77
109
|
cacheDriver.set(cacheKey, {
|
|
78
110
|
status: sentResponse.statusCode,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"idempotency.middleware.mjs","names":[],"sources":["../../../../../../../../core/src/http/middleware/idempotency.middleware.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport { cache } from \"@warlock.js/cache\";\nimport { log } from \"@warlock.js/logger\";\nimport type { Middleware } from \"../../router\";\nimport { HttpErrorCodes } from \"../error-codes\";\nimport type { Response } from \"../response\";\nimport { t } from \"./inject-request-context\";\nimport { buildIdempotencyCacheKey, hashBody, isValidIdempotencyKey } from \"./utils/idempotency-key\";\n\n/**\n * Options for the idempotency middleware.\n */\nexport type IdempotencyOptions = {\n /**\n * Cache TTL in seconds. Falls back to `http.idempotency.ttl`, then `86400` (24h).\n */\n ttl?: number;\n /**\n * Header name carrying the client's key. Falls back to\n * `http.idempotency.headerName`, then `\"Idempotency-Key\"`.\n */\n headerName?: string;\n /**\n * HTTP methods eligible for idempotency. Falls back to\n * `http.idempotency.methods`, then `[\"POST\",\"PUT\",\"PATCH\",\"DELETE\"]`.\n * Safe methods (GET/HEAD) are skipped regardless.\n */\n methods?: string[];\n /**\n * Cache driver name. Falls back to `http.idempotency.driver`, then the\n * default driver of the cache manager.\n */\n driver?: string;\n};\n\ntype CachedResponse = {\n status: number;\n body: unknown;\n bodyHash: string;\n contentType?: string;\n};\n\nconst DEFAULT_METHODS = [\"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n\n/**\n * Dedupe non-idempotent writes by an `Idempotency-Key` header — same key,\n * same body, within TTL → cached replay; same key, different body → 422\n * `IdempotencyKeyConflict`.\n *\n * **Must run after `authMiddleware`** — the cache key is scoped per-user\n * (`idem:{userType}:{userId}:{key}`) so user A can't replay user B's key.\n * Anonymous requests fall back to IP scope.\n *\n * The replay sets `Idempotent-Replay: true` on the response for easy\n * client-side / observability detection.\n *\n * Eligible methods default to POST/PUT/PATCH/DELETE. GET/HEAD pass through\n * even with the header set (RFC: safe methods are already idempotent).\n *\n * @example\n * import { authMiddleware } from \"@warlock.js/auth\";\n * import { middleware } from \"@warlock.js/core\";\n *\n * router.post(\"/orders\", createOrderController, {\n * middleware: [authMiddleware(\"client\"), middleware.idempotency()],\n * });\n *\n * router.post(\"/ai/summarize\", summarizeController, {\n * middleware: [\n * authMiddleware(\"client\"),\n * middleware.idempotency({ ttl: 60 * 60 }), // 1h is enough for client retries\n * ],\n * });\n */\nexport function idempotencyMiddleware(options: IdempotencyOptions = {}): Middleware {\n return async ({ request, response }) => {\n const headerName =\n options.headerName || config.get(\"http.idempotency.headerName\", \"Idempotency-Key\");\n const methods = options.methods || config.get(\"http.idempotency.methods\", DEFAULT_METHODS);\n const ttl = options.ttl || config.get(\"http.idempotency.ttl\", 86400);\n const driverName = options.driver || config.get(\"http.idempotency.driver\");\n\n if (!methods.includes(request.method.toUpperCase())) return;\n\n const idempotencyKey = request.header(headerName.toLowerCase());\n\n if (!idempotencyKey) return;\n\n if (!isValidIdempotencyKey(idempotencyKey)) {\n return response.badRequest({\n error: t(\"http.idempotencyKeyInvalid\"),\n errorCode: HttpErrorCodes.IdempotencyKeyInvalid,\n });\n }\n\n const cacheDriver = driverName ? await cache.use(driverName) : cache;\n const cacheKey = buildIdempotencyCacheKey(request, idempotencyKey);\n const bodyHash = hashBody(request.body);\n\n const
|
|
1
|
+
{"version":3,"file":"idempotency.middleware.mjs","names":[],"sources":["../../../../../../../../core/src/http/middleware/idempotency.middleware.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport { cache } from \"@warlock.js/cache\";\nimport { log } from \"@warlock.js/logger\";\nimport type { Middleware } from \"../../router\";\nimport { HttpErrorCodes } from \"../error-codes\";\nimport type { Response } from \"../response\";\nimport { t } from \"./inject-request-context\";\nimport { buildIdempotencyCacheKey, hashBody, isValidIdempotencyKey } from \"./utils/idempotency-key\";\n\n/**\n * Options for the idempotency middleware.\n */\nexport type IdempotencyOptions = {\n /**\n * Cache TTL in seconds. Falls back to `http.idempotency.ttl`, then `86400` (24h).\n */\n ttl?: number;\n /**\n * TTL in seconds of the in-flight reservation held while the handler runs.\n * Falls back to `http.idempotency.reservationTtl`, then `60`.\n */\n reservationTtl?: number;\n /**\n * Header name carrying the client's key. Falls back to\n * `http.idempotency.headerName`, then `\"Idempotency-Key\"`.\n */\n headerName?: string;\n /**\n * HTTP methods eligible for idempotency. Falls back to\n * `http.idempotency.methods`, then `[\"POST\",\"PUT\",\"PATCH\",\"DELETE\"]`.\n * Safe methods (GET/HEAD) are skipped regardless.\n */\n methods?: string[];\n /**\n * Cache driver name. Falls back to `http.idempotency.driver`, then the\n * default driver of the cache manager.\n */\n driver?: string;\n};\n\ntype CachedResponse = {\n status: number;\n body: unknown;\n bodyHash: string;\n contentType?: string;\n};\n\ntype InFlightReservation = {\n state: \"in-flight\";\n startedAt: number;\n};\n\nconst DEFAULT_METHODS = [\"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n\n/**\n * Dedupe non-idempotent writes by an `Idempotency-Key` header — same key,\n * same body, within TTL → cached replay; same key, different body → 422\n * `IdempotencyKeyConflict`.\n *\n * **Must run after `authMiddleware`** — the cache key is scoped per-user\n * (`idem:{userType}:{userId}:{key}`) so user A can't replay user B's key.\n * Anonymous requests fall back to IP scope.\n *\n * The replay sets `Idempotent-Replay: true` on the response for easy\n * client-side / observability detection.\n *\n * Eligible methods default to POST/PUT/PATCH/DELETE. GET/HEAD pass through\n * even with the header set (RFC: safe methods are already idempotent).\n *\n * @example\n * import { authMiddleware } from \"@warlock.js/auth\";\n * import { middleware } from \"@warlock.js/core\";\n *\n * router.post(\"/orders\", createOrderController, {\n * middleware: [authMiddleware(\"client\"), middleware.idempotency()],\n * });\n *\n * router.post(\"/ai/summarize\", summarizeController, {\n * middleware: [\n * authMiddleware(\"client\"),\n * middleware.idempotency({ ttl: 60 * 60 }), // 1h is enough for client retries\n * ],\n * });\n */\nexport function idempotencyMiddleware(options: IdempotencyOptions = {}): Middleware {\n return async ({ request, response }) => {\n const headerName =\n options.headerName || config.get(\"http.idempotency.headerName\", \"Idempotency-Key\");\n const methods = options.methods || config.get(\"http.idempotency.methods\", DEFAULT_METHODS);\n const ttl = options.ttl || config.get(\"http.idempotency.ttl\", 86400);\n const reservationTtl =\n options.reservationTtl || config.get(\"http.idempotency.reservationTtl\", 60);\n const driverName = options.driver || config.get(\"http.idempotency.driver\");\n\n if (!methods.includes(request.method.toUpperCase())) return;\n\n const idempotencyKey = request.header(headerName.toLowerCase());\n\n if (!idempotencyKey) return;\n\n if (!isValidIdempotencyKey(idempotencyKey)) {\n return response.badRequest({\n error: t(\"http.idempotencyKeyInvalid\"),\n errorCode: HttpErrorCodes.IdempotencyKeyInvalid,\n });\n }\n\n const cacheDriver = driverName ? await cache.use(driverName) : cache;\n const cacheKey = buildIdempotencyCacheKey(request, idempotencyKey);\n const bodyHash = hashBody(request.body);\n\n const respondToExisting = (existing: CachedResponse | InFlightReservation | undefined | null) => {\n if (!existing || (existing as InFlightReservation).state === \"in-flight\") {\n response.header(\"Retry-After\", \"1\");\n\n return response.conflict({\n error: \"A request with this Idempotency-Key is already in progress\",\n errorCode: HttpErrorCodes.IdempotencyKeyConflict,\n });\n }\n\n const cached = existing as CachedResponse;\n\n if (cached.bodyHash !== bodyHash) {\n return response.unprocessableEntity({\n error: t(\"http.idempotencyKeyConflict\"),\n errorCode: HttpErrorCodes.IdempotencyKeyConflict,\n });\n }\n\n response.header(\"Idempotent-Replay\", \"true\");\n\n return response.replay({\n status: cached.status,\n body: cached.body,\n contentType: cached.contentType,\n });\n };\n\n // Fast path: a finished (or in-flight) request is already recorded.\n let existing: CachedResponse | InFlightReservation | null = null;\n\n try {\n existing = (await cacheDriver.get(cacheKey)) as CachedResponse | InFlightReservation | null;\n } catch (error) {\n // The cache is an optimisation of idempotency, not a gate on writes:\n // when it is down, fail open (the handler runs) and log it.\n log.error(\"idempotency-middleware\", \"get\", error);\n }\n\n if (existing) return respondToExisting(existing);\n\n // Reserve the key atomically before the handler runs, so concurrent\n // requests with the same key can't both execute it.\n try {\n const reservation = (await cacheDriver.set(\n cacheKey,\n { state: \"in-flight\", startedAt: Date.now() } satisfies InFlightReservation,\n { onConflict: \"create\", ttl: reservationTtl },\n )) as { wasSet?: boolean; existing?: CachedResponse | InFlightReservation } | undefined;\n\n if (reservation && reservation.wasSet === false) {\n return respondToExisting(reservation.existing);\n }\n } catch (error) {\n log.error(\"idempotency-middleware\", \"reserve\", error);\n }\n\n response.onSent((sentResponse: Response) => {\n // Don't cache server errors — clients should be able to retry past a 5xx.\n // 4xx are deterministic outcomes of the request, so caching is fine.\n // Free the reservation so a retry can run.\n if (sentResponse.statusCode >= 500) {\n // Wrapped so a synchronous throw is caught as well as a rejection.\n Promise.resolve()\n .then(() => cacheDriver.remove(cacheKey))\n .catch((error: unknown) => {\n log.error(\"idempotency-middleware\", \"remove\", error);\n });\n\n return;\n }\n\n const sentContentType = sentResponse.contentType;\n\n // `set` is fire-and-forget inside `onSent`; without a `.catch` a rejected\n // write (e.g. Redis down) would surface as an unhandledRejection.\n cacheDriver\n .set(\n cacheKey,\n {\n status: sentResponse.statusCode,\n body: sentResponse.parsedBody,\n bodyHash,\n contentType: typeof sentContentType === \"string\" ? sentContentType : undefined,\n },\n ttl,\n )\n .catch((error: unknown) => {\n log.error(\"idempotency-middleware\", \"set\", error);\n });\n });\n };\n}\n"],"mappings":";;;;;;;;AAoDA,MAAM,kBAAkB;CAAC;CAAQ;CAAO;CAAS;AAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCzD,SAAgB,sBAAsB,UAA8B,CAAC,GAAe;CAClF,OAAO,OAAO,EAAE,SAAS,eAAe;EACtC,MAAM,aACJ,QAAQ,cAAc,OAAO,IAAI,+BAA+B,iBAAiB;EACnF,MAAM,UAAU,QAAQ,WAAW,OAAO,IAAI,4BAA4B,eAAe;EACzF,MAAM,MAAM,QAAQ,OAAO,OAAO,IAAI,wBAAwB,KAAK;EACnE,MAAM,iBACJ,QAAQ,kBAAkB,OAAO,IAAI,mCAAmC,EAAE;EAC5E,MAAM,aAAa,QAAQ,UAAU,OAAO,IAAI,yBAAyB;EAEzE,IAAI,CAAC,QAAQ,SAAS,QAAQ,OAAO,YAAY,CAAC,GAAG;EAErD,MAAM,iBAAiB,QAAQ,OAAO,WAAW,YAAY,CAAC;EAE9D,IAAI,CAAC,gBAAgB;EAErB,IAAI,CAAC,sBAAsB,cAAc,GACvC,OAAO,SAAS,WAAW;GACzB,OAAO,EAAE,4BAA4B;GACrC;EACF,CAAC;EAGH,MAAM,cAAc,aAAa,MAAM,MAAM,IAAI,UAAU,IAAI;EAC/D,MAAM,WAAW,yBAAyB,SAAS,cAAc;EACjE,MAAM,WAAW,SAAS,QAAQ,IAAI;EAEtC,MAAM,qBAAqB,aAAsE;GAC/F,IAAI,CAAC,YAAa,SAAiC,UAAU,aAAa;IACxE,SAAS,OAAO,eAAe,GAAG;IAElC,OAAO,SAAS,SAAS;KACvB,OAAO;KACP;IACF,CAAC;GACH;GAEA,MAAM,SAAS;GAEf,IAAI,OAAO,aAAa,UACtB,OAAO,SAAS,oBAAoB;IAClC,OAAO,EAAE,6BAA6B;IACtC;GACF,CAAC;GAGH,SAAS,OAAO,qBAAqB,MAAM;GAE3C,OAAO,SAAS,OAAO;IACrB,QAAQ,OAAO;IACf,MAAM,OAAO;IACb,aAAa,OAAO;GACtB,CAAC;EACH;EAGA,IAAI,WAAwD;EAE5D,IAAI;GACF,WAAY,MAAM,YAAY,IAAI,QAAQ;EAC5C,SAAS,OAAO;GAGd,IAAI,MAAM,0BAA0B,OAAO,KAAK;EAClD;EAEA,IAAI,UAAU,OAAO,kBAAkB,QAAQ;EAI/C,IAAI;GACF,MAAM,cAAe,MAAM,YAAY,IACrC,UACA;IAAE,OAAO;IAAa,WAAW,KAAK,IAAI;GAAE,GAC5C;IAAE,YAAY;IAAU,KAAK;GAAe,CAC9C;GAEA,IAAI,eAAe,YAAY,WAAW,OACxC,OAAO,kBAAkB,YAAY,QAAQ;EAEjD,SAAS,OAAO;GACd,IAAI,MAAM,0BAA0B,WAAW,KAAK;EACtD;EAEA,SAAS,QAAQ,iBAA2B;GAI1C,IAAI,aAAa,cAAc,KAAK;IAElC,QAAQ,QAAQ,CAAC,CACd,WAAW,YAAY,OAAO,QAAQ,CAAC,CAAC,CACxC,OAAO,UAAmB;KACzB,IAAI,MAAM,0BAA0B,UAAU,KAAK;IACrD,CAAC;IAEH;GACF;GAEA,MAAM,kBAAkB,aAAa;GAIrC,YACG,IACC,UACA;IACE,QAAQ,aAAa;IACrB,MAAM,aAAa;IACnB;IACA,aAAa,OAAO,oBAAoB,WAAW,kBAAkB;GACvE,GACA,GACF,CAAC,CACA,OAAO,UAAmB;IACzB,IAAI,MAAM,0BAA0B,OAAO,KAAK;GAClD,CAAC;EACL,CAAC;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inject-request-context.d.mts","names":[],"sources":["../../../../../../../../core/src/http/middleware/inject-request-context.ts"],"mappings":";;;;;;;AA8CA;;;iBAAgB,kBAAA,CACd,OAAA,EAAS,OAAA,OACT,QAAA,EAAU,QAAA,GACT,OAAA,CAAQ,gBAAA;;;;
|
|
1
|
+
{"version":3,"file":"inject-request-context.d.mts","names":[],"sources":["../../../../../../../../core/src/http/middleware/inject-request-context.ts"],"mappings":";;;;;;;AA8CA;;;iBAAgB,kBAAA,CACd,OAAA,EAAS,OAAA,OACT,QAAA,EAAU,QAAA,GACT,OAAA,CAAQ,gBAAA;;;;iBA4JK,CAAA,CAAE,OAAA,UAAiB,YAAkB"}
|
|
@@ -70,24 +70,35 @@ function createRequestStore(request, response) {
|
|
|
70
70
|
return output;
|
|
71
71
|
} catch (error) {
|
|
72
72
|
request.log(error, "error");
|
|
73
|
-
return handleRequestError(error, response);
|
|
73
|
+
return handleRequestError(error, response, request);
|
|
74
74
|
}
|
|
75
75
|
});
|
|
76
76
|
}
|
|
77
77
|
/**
|
|
78
|
+
* Unconditional floor for an unhandled request error (canon 8d3c13a8): route it
|
|
79
|
+
* through the logger, and when no logger channel is configured (nothing would
|
|
80
|
+
* record it) fall back to `console.error` so the only copy is never lost.
|
|
81
|
+
* @internal
|
|
82
|
+
*/
|
|
83
|
+
function reportUnhandledRequestError(error, request) {
|
|
84
|
+
log.error("http", "unhandled-request-error", error, { requestId: request.id });
|
|
85
|
+
if (log.channels.length === 0) console.error(`[http] unhandled-request-error (requestId: ${request.id})`, error);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
78
88
|
* Handle request errors
|
|
79
89
|
* @internal
|
|
80
90
|
*/
|
|
81
|
-
function handleRequestError(error, response) {
|
|
91
|
+
function handleRequestError(error, response, request) {
|
|
82
92
|
response.header("Cache-Control", "private, no-store");
|
|
83
93
|
if (error instanceof HttpError) {
|
|
94
|
+
if (error.status >= 500) log.error("http", "request-error", error, { requestId: request.id });
|
|
84
95
|
const payload = { error: error.message };
|
|
85
96
|
if (error.payload) payload.payload = error.payload;
|
|
86
97
|
if (environment() === "development") payload.stack = error.stack;
|
|
87
98
|
return response.setStatusCode(error.status).send(payload);
|
|
88
99
|
}
|
|
89
100
|
if (error instanceof DatabaseWriterValidationError) return response.badRequest({ errors: error.errors });
|
|
90
|
-
|
|
101
|
+
reportUnhandledRequestError(error, request);
|
|
91
102
|
return response.serverError({ error: "Internal server error." });
|
|
92
103
|
}
|
|
93
104
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inject-request-context.mjs","names":["requestContextInstance"],"sources":["../../../../../../../../core/src/http/middleware/inject-request-context.ts"],"sourcesContent":["/**\n * Request Context Middleware\n *\n * Creates a unified context for each request using the ContextManager.\n * All framework contexts (request, storage, database) are available throughout the request lifecycle.\n */\nimport { trans } from \"@mongez/localization\";\nimport { type GenericObject } from \"@mongez/reinforcements\";\nimport { DatabaseWriterValidationError } from \"@warlock.js/cascade\";\nimport { contextManager } from \"@warlock.js/context\";\nimport { log } from \"@warlock.js/logger\";\nimport config from \"@mongez/config\";\nimport { environment } from \"../../utils\";\nimport { requestContext as requestContextInstance } from \"../context/request-context\";\nimport { applyCspHeader } from \"../csp\";\nimport { runDefaultCsrfGuard } from \"../csrf-default-guard\";\nimport { HttpError } from \"../errors\";\nimport { type Request } from \"../request\";\nimport { type Response } from \"../response\";\nimport { buildTracingContext, dispatchPhase, isTracingEnabled } from \"../tracing\";\nimport { type ReturnedResponse } from \"./../types\";\n\n// Contexts are now registered in core/context/init-contexts.ts via initializeContexts()\n\n/**\n * Echo `request.id` back as a response header so the FE / proxies / log\n * aggregators can correlate by the same value the server logs against.\n *\n * Reads the header name from `http.requestId.header` (default `X-Request-Id`).\n * Skip when `http.requestId.enabled` is explicitly false.\n */\nfunction stampRequestIdHeader(request: Request, response: Response) {\n const requestIdConfig = config.get(\"http.requestId\", {} as Record<string, any>);\n\n if (requestIdConfig.enabled === false) return;\n\n const headerName = requestIdConfig.header || \"X-Request-Id\";\n\n response.header(headerName, request.id);\n}\n\n/**\n * Create request store and execute middleware + handler\n *\n * Runs all registered contexts together using ContextManager.\n */\nexport function createRequestStore(\n request: Request<any>,\n response: Response,\n): Promise<ReturnedResponse> {\n stampRequestIdHeader(request, response);\n\n // Stamped this early — before any middleware or handler runs — so the\n // header carries the SAME nonce the web layer later reads off\n // `request.nonce` for its `<script>` tags: `request.nonce` caches on first\n // read, and this is deliberately the first read. A no-op when the app\n // hasn't opted into `http.csp` (see `csp.ts`).\n applyCspHeader(request, response);\n\n // Build all context stores using the immutable API\n // Each context defines its own store initialization via buildStore()\n const httpContextStore = contextManager.buildStores({ request, response });\n\n // Run all contexts together!\n return contextManager.runAll(httpContextStore, async () => {\n try {\n // Default CSRF-Origin guard (SECURITY, card 8a752ab2) — the earliest\n // seam common to every request, BEFORE the route's own middleware\n // (`request.runMiddleware()` below) and before any app handler, so it\n // applies even to a route that never attaches\n // `authMiddleware(\"cookie:*\")`. See `../csrf-default-guard.ts` for the\n // full scope rule and `{ csrf: false }` exemption.\n const csrfGuardResponse = await runDefaultCsrfGuard(request, response, t, (reason) => {\n log.error(\n \"http\",\n \"csrf-default-guard\",\n new Error(`Default CSRF Origin guard refused request: ${reason}`),\n );\n });\n\n if (csrfGuardResponse) {\n return csrfGuardResponse as ReturnedResponse;\n }\n\n // Run middleware chain\n const result = await request.runMiddleware();\n\n if (result) {\n return result as ReturnedResponse;\n }\n\n // Execute route handler\n request.trigger(\"executingAction\", request.route);\n\n const handler = request.getHandler();\n\n request.log(\"Executing Handler\", \"info\");\n\n const tracingEnabled = isTracingEnabled();\n const handlerStartedAt = tracingEnabled ? performance.now() : 0;\n\n const output = await handler({ request, response });\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(request), {\n name: \"handler\",\n durationMs: performance.now() - handlerStartedAt,\n });\n }\n\n request.log(\"Handler Executed Successfully\", \"success\");\n\n request.trigger(\"executedAction\", request.route);\n\n return output as ReturnedResponse;\n } catch (error) {\n request.log(error, \"error\");\n return handleRequestError(error, response);\n }\n });\n}\n\n/**\n * Handle request errors\n * @internal\n */\nfunction handleRequestError(error: unknown, response: Response): ReturnedResponse {\n // Availability floor, not a cache-policy nit: `handleRequestError` is the\n // single funnel every unhandled error in every Warlock app passes through\n // (`createRequestStore`'s catch above), and none of the branches below set\n // a `Cache-Control` header. Without this, an error response — a 500 as\n // much as a 401/403/404 carrying per-request/-user state — can be stored\n // by a shared cache or CDN and replayed to other requests/users long after\n // the condition that caused it is gone: a cached 500 becomes an outage\n // that outlives its cause; a cached 401/403 becomes a leak across users.\n // Set once, here, before any branch runs — not per branch — because the\n // branches below do not partition by status. `ResourceNotFoundError`,\n // `UnAuthorizedError`, `ForbiddenError`, `BadRequestError` and `ServerError`\n // all extend `HttpError`, so the `HttpError` branch answers for every one of\n // them, and a raw `HttpError` can carry any caller-chosen status, 4xx or 5xx.\n // Gating the floor on the eventual status would mean re-deriving that status\n // per branch — one rule meeting one form while others reach the same output.\n // Applying it once, unconditionally, is both simpler and safer.\n response.header(\"Cache-Control\", \"private, no-store\");\n\n if (error instanceof HttpError) {\n const payload: GenericObject = {\n error: error.message,\n };\n if (error.payload) {\n payload.payload = error.payload;\n }\n\n if (environment() === \"development\") {\n payload.stack = error.stack;\n }\n\n return response.setStatusCode(error.status).send(payload);\n }\n\n if (error instanceof DatabaseWriterValidationError) {\n return response.badRequest({\n errors: error.errors,\n });\n }\n\n // Last resort: the error matched none of the known shapes above, so the\n // client gets a deliberately opaque message. Without this line the error\n // itself is discarded here — no stack, no message, nothing in any log — and\n // an unrecognised failure becomes indistinguishable from a working server\n // returning 500. Never swallow the only copy of an error (`65e476ee`).\n console.error(\"[warlock] unhandled request error:\", error);\n\n return response.serverError({\n error: \"Internal server error.\",\n });\n}\n\n/**\n * Translate a keyword (uses request context for locale)\n */\nexport function t(keyword: string, placeholders?: any) {\n return (\n requestContextInstance.getRequest()?.trans(keyword, placeholders) ||\n trans(keyword, placeholders)\n );\n}\n\n// `fromRequest` was removed in v5. It cached computed values as dynamic\n// properties on the Request instance, which only compiled because of the\n// `[key: string]: any` index signature that v5 deletes (eed20184). Use\n// `requestMemo(key, fn)` from `../context/request-memo` instead — same\n// per-request lifetime, single-flight, and it never touches the Request object.\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAS,qBAAqB,SAAkB,UAAoB;CAClE,MAAM,kBAAkB,OAAO,IAAI,kBAAkB,CAAC,CAAwB;CAE9E,IAAI,gBAAgB,YAAY,OAAO;CAEvC,MAAM,aAAa,gBAAgB,UAAU;CAE7C,SAAS,OAAO,YAAY,QAAQ,EAAE;AACxC;;;;;;AAOA,SAAgB,mBACd,SACA,UAC2B;CAC3B,qBAAqB,SAAS,QAAQ;CAOtC,eAAe,SAAS,QAAQ;CAIhC,MAAM,mBAAmB,eAAe,YAAY;EAAE;EAAS;CAAS,CAAC;CAGzE,OAAO,eAAe,OAAO,kBAAkB,YAAY;EACzD,IAAI;GAOF,MAAM,oBAAoB,MAAM,oBAAoB,SAAS,UAAU,IAAI,WAAW;IACpF,IAAI,MACF,QACA,sCACA,IAAI,MAAM,8CAA8C,QAAQ,CAClE;GACF,CAAC;GAED,IAAI,mBACF,OAAO;GAIT,MAAM,SAAS,MAAM,QAAQ,cAAc;GAE3C,IAAI,QACF,OAAO;GAIT,QAAQ,QAAQ,mBAAmB,QAAQ,KAAK;GAEhD,MAAM,UAAU,QAAQ,WAAW;GAEnC,QAAQ,IAAI,qBAAqB,MAAM;GAEvC,MAAM,iBAAiB,iBAAiB;GACxC,MAAM,mBAAmB,iBAAiB,YAAY,IAAI,IAAI;GAE9D,MAAM,SAAS,MAAM,QAAQ;IAAE;IAAS;GAAS,CAAC;GAElD,IAAI,gBACF,cAAc,oBAAoB,OAAO,GAAG;IAC1C,MAAM;IACN,YAAY,YAAY,IAAI,IAAI;GAClC,CAAC;GAGH,QAAQ,IAAI,iCAAiC,SAAS;GAEtD,QAAQ,QAAQ,kBAAkB,QAAQ,KAAK;GAE/C,OAAO;EACT,SAAS,OAAO;GACd,QAAQ,IAAI,OAAO,OAAO;GAC1B,OAAO,mBAAmB,OAAO,QAAQ;EAC3C;CACF,CAAC;AACH;;;;;AAMA,SAAS,mBAAmB,OAAgB,UAAsC;CAiBhF,SAAS,OAAO,iBAAiB,mBAAmB;CAEpD,IAAI,iBAAiB,WAAW;EAC9B,MAAM,UAAyB,EAC7B,OAAO,MAAM,QACf;EACA,IAAI,MAAM,SACR,QAAQ,UAAU,MAAM;EAG1B,IAAI,YAAY,MAAM,eACpB,QAAQ,QAAQ,MAAM;EAGxB,OAAO,SAAS,cAAc,MAAM,MAAM,CAAC,CAAC,KAAK,OAAO;CAC1D;CAEA,IAAI,iBAAiB,+BACnB,OAAO,SAAS,WAAW,EACzB,QAAQ,MAAM,OAChB,CAAC;CAQH,QAAQ,MAAM,sCAAsC,KAAK;CAEzD,OAAO,SAAS,YAAY,EAC1B,OAAO,yBACT,CAAC;AACH;;;;AAKA,SAAgB,EAAE,SAAiB,cAAoB;CACrD,OACEA,eAAuB,WAAW,CAAC,EAAE,MAAM,SAAS,YAAY,KAChE,MAAM,SAAS,YAAY;AAE/B"}
|
|
1
|
+
{"version":3,"file":"inject-request-context.mjs","names":["requestContextInstance"],"sources":["../../../../../../../../core/src/http/middleware/inject-request-context.ts"],"sourcesContent":["/**\n * Request Context Middleware\n *\n * Creates a unified context for each request using the ContextManager.\n * All framework contexts (request, storage, database) are available throughout the request lifecycle.\n */\nimport { trans } from \"@mongez/localization\";\nimport { type GenericObject } from \"@mongez/reinforcements\";\nimport { DatabaseWriterValidationError } from \"@warlock.js/cascade\";\nimport { contextManager } from \"@warlock.js/context\";\nimport { log } from \"@warlock.js/logger\";\nimport config from \"@mongez/config\";\nimport { environment } from \"../../utils\";\nimport { requestContext as requestContextInstance } from \"../context/request-context\";\nimport { applyCspHeader } from \"../csp\";\nimport { runDefaultCsrfGuard } from \"../csrf-default-guard\";\nimport { HttpError } from \"../errors\";\nimport { type Request } from \"../request\";\nimport { type Response } from \"../response\";\nimport { buildTracingContext, dispatchPhase, isTracingEnabled } from \"../tracing\";\nimport { type ReturnedResponse } from \"./../types\";\n\n// Contexts are now registered in core/context/init-contexts.ts via initializeContexts()\n\n/**\n * Echo `request.id` back as a response header so the FE / proxies / log\n * aggregators can correlate by the same value the server logs against.\n *\n * Reads the header name from `http.requestId.header` (default `X-Request-Id`).\n * Skip when `http.requestId.enabled` is explicitly false.\n */\nfunction stampRequestIdHeader(request: Request, response: Response) {\n const requestIdConfig = config.get(\"http.requestId\", {} as Record<string, any>);\n\n if (requestIdConfig.enabled === false) return;\n\n const headerName = requestIdConfig.header || \"X-Request-Id\";\n\n response.header(headerName, request.id);\n}\n\n/**\n * Create request store and execute middleware + handler\n *\n * Runs all registered contexts together using ContextManager.\n */\nexport function createRequestStore(\n request: Request<any>,\n response: Response,\n): Promise<ReturnedResponse> {\n stampRequestIdHeader(request, response);\n\n // Stamped this early — before any middleware or handler runs — so the\n // header carries the SAME nonce the web layer later reads off\n // `request.nonce` for its `<script>` tags: `request.nonce` caches on first\n // read, and this is deliberately the first read. A no-op when the app\n // hasn't opted into `http.csp` (see `csp.ts`).\n applyCspHeader(request, response);\n\n // Build all context stores using the immutable API\n // Each context defines its own store initialization via buildStore()\n const httpContextStore = contextManager.buildStores({ request, response });\n\n // Run all contexts together!\n return contextManager.runAll(httpContextStore, async () => {\n try {\n // Default CSRF-Origin guard (SECURITY, card 8a752ab2) — the earliest\n // seam common to every request, BEFORE the route's own middleware\n // (`request.runMiddleware()` below) and before any app handler, so it\n // applies even to a route that never attaches\n // `authMiddleware(\"cookie:*\")`. See `../csrf-default-guard.ts` for the\n // full scope rule and `{ csrf: false }` exemption.\n const csrfGuardResponse = await runDefaultCsrfGuard(request, response, t, (reason) => {\n log.error(\n \"http\",\n \"csrf-default-guard\",\n new Error(`Default CSRF Origin guard refused request: ${reason}`),\n );\n });\n\n if (csrfGuardResponse) {\n return csrfGuardResponse as ReturnedResponse;\n }\n\n // Run middleware chain\n const result = await request.runMiddleware();\n\n if (result) {\n return result as ReturnedResponse;\n }\n\n // Execute route handler\n request.trigger(\"executingAction\", request.route);\n\n const handler = request.getHandler();\n\n request.log(\"Executing Handler\", \"info\");\n\n const tracingEnabled = isTracingEnabled();\n const handlerStartedAt = tracingEnabled ? performance.now() : 0;\n\n const output = await handler({ request, response });\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(request), {\n name: \"handler\",\n durationMs: performance.now() - handlerStartedAt,\n });\n }\n\n request.log(\"Handler Executed Successfully\", \"success\");\n\n request.trigger(\"executedAction\", request.route);\n\n return output as ReturnedResponse;\n } catch (error) {\n request.log(error, \"error\");\n return handleRequestError(error, response, request);\n }\n });\n}\n\n/**\n * Unconditional floor for an unhandled request error (canon 8d3c13a8): route it\n * through the logger, and when no logger channel is configured (nothing would\n * record it) fall back to `console.error` so the only copy is never lost.\n * @internal\n */\nfunction reportUnhandledRequestError(error: unknown, request: Request<any>) {\n log.error(\"http\", \"unhandled-request-error\", error, { requestId: request.id });\n\n if (log.channels.length === 0) {\n console.error(`[http] unhandled-request-error (requestId: ${request.id})`, error);\n }\n}\n\n/**\n * Handle request errors\n * @internal\n */\nfunction handleRequestError(\n error: unknown,\n response: Response,\n request: Request<any>,\n): ReturnedResponse {\n // Availability floor, not a cache-policy nit: `handleRequestError` is the\n // single funnel every unhandled error in every Warlock app passes through\n // (`createRequestStore`'s catch above), and none of the branches below set\n // a `Cache-Control` header. Without this, an error response — a 500 as\n // much as a 401/403/404 carrying per-request/-user state — can be stored\n // by a shared cache or CDN and replayed to other requests/users long after\n // the condition that caused it is gone: a cached 500 becomes an outage\n // that outlives its cause; a cached 401/403 becomes a leak across users.\n // Set once, here, before any branch runs — not per branch — because the\n // branches below do not partition by status. `ResourceNotFoundError`,\n // `UnAuthorizedError`, `ForbiddenError`, `BadRequestError` and `ServerError`\n // all extend `HttpError`, so the `HttpError` branch answers for every one of\n // them, and a raw `HttpError` can carry any caller-chosen status, 4xx or 5xx.\n // Gating the floor on the eventual status would mean re-deriving that status\n // per branch — one rule meeting one form while others reach the same output.\n // Applying it once, unconditionally, is both simpler and safer.\n response.header(\"Cache-Control\", \"private, no-store\");\n\n if (error instanceof HttpError) {\n // 5xx HttpErrors (e.g. `ServerError`) are server faults: send them to the\n // logger channels too, tagged with the request id.\n if (error.status >= 500) {\n log.error(\"http\", \"request-error\", error, { requestId: request.id });\n }\n\n const payload: GenericObject = {\n error: error.message,\n };\n if (error.payload) {\n payload.payload = error.payload;\n }\n\n if (environment() === \"development\") {\n payload.stack = error.stack;\n }\n\n return response.setStatusCode(error.status).send(payload);\n }\n\n if (error instanceof DatabaseWriterValidationError) {\n return response.badRequest({\n errors: error.errors,\n });\n }\n\n // Last resort: the error matched none of the known shapes above, so the\n // client gets a deliberately opaque message. Without this line the error\n // itself is discarded here — no stack, no message, nothing in any log — and\n // an unrecognised failure becomes indistinguishable from a working server\n // returning 500. Never swallow the only copy of an error (`65e476ee`).\n reportUnhandledRequestError(error, request);\n\n return response.serverError({\n error: \"Internal server error.\",\n });\n}\n\n/**\n * Translate a keyword (uses request context for locale)\n */\nexport function t(keyword: string, placeholders?: any) {\n return (\n requestContextInstance.getRequest()?.trans(keyword, placeholders) ||\n trans(keyword, placeholders)\n );\n}\n\n// `fromRequest` was removed in v5. It cached computed values as dynamic\n// properties on the Request instance, which only compiled because of the\n// `[key: string]: any` index signature that v5 deletes (eed20184). Use\n// `requestMemo(key, fn)` from `../context/request-memo` instead — same\n// per-request lifetime, single-flight, and it never touches the Request object.\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAS,qBAAqB,SAAkB,UAAoB;CAClE,MAAM,kBAAkB,OAAO,IAAI,kBAAkB,CAAC,CAAwB;CAE9E,IAAI,gBAAgB,YAAY,OAAO;CAEvC,MAAM,aAAa,gBAAgB,UAAU;CAE7C,SAAS,OAAO,YAAY,QAAQ,EAAE;AACxC;;;;;;AAOA,SAAgB,mBACd,SACA,UAC2B;CAC3B,qBAAqB,SAAS,QAAQ;CAOtC,eAAe,SAAS,QAAQ;CAIhC,MAAM,mBAAmB,eAAe,YAAY;EAAE;EAAS;CAAS,CAAC;CAGzE,OAAO,eAAe,OAAO,kBAAkB,YAAY;EACzD,IAAI;GAOF,MAAM,oBAAoB,MAAM,oBAAoB,SAAS,UAAU,IAAI,WAAW;IACpF,IAAI,MACF,QACA,sCACA,IAAI,MAAM,8CAA8C,QAAQ,CAClE;GACF,CAAC;GAED,IAAI,mBACF,OAAO;GAIT,MAAM,SAAS,MAAM,QAAQ,cAAc;GAE3C,IAAI,QACF,OAAO;GAIT,QAAQ,QAAQ,mBAAmB,QAAQ,KAAK;GAEhD,MAAM,UAAU,QAAQ,WAAW;GAEnC,QAAQ,IAAI,qBAAqB,MAAM;GAEvC,MAAM,iBAAiB,iBAAiB;GACxC,MAAM,mBAAmB,iBAAiB,YAAY,IAAI,IAAI;GAE9D,MAAM,SAAS,MAAM,QAAQ;IAAE;IAAS;GAAS,CAAC;GAElD,IAAI,gBACF,cAAc,oBAAoB,OAAO,GAAG;IAC1C,MAAM;IACN,YAAY,YAAY,IAAI,IAAI;GAClC,CAAC;GAGH,QAAQ,IAAI,iCAAiC,SAAS;GAEtD,QAAQ,QAAQ,kBAAkB,QAAQ,KAAK;GAE/C,OAAO;EACT,SAAS,OAAO;GACd,QAAQ,IAAI,OAAO,OAAO;GAC1B,OAAO,mBAAmB,OAAO,UAAU,OAAO;EACpD;CACF,CAAC;AACH;;;;;;;AAQA,SAAS,4BAA4B,OAAgB,SAAuB;CAC1E,IAAI,MAAM,QAAQ,2BAA2B,OAAO,EAAE,WAAW,QAAQ,GAAG,CAAC;CAE7E,IAAI,IAAI,SAAS,WAAW,GAC1B,QAAQ,MAAM,8CAA8C,QAAQ,GAAG,IAAI,KAAK;AAEpF;;;;;AAMA,SAAS,mBACP,OACA,UACA,SACkB;CAiBlB,SAAS,OAAO,iBAAiB,mBAAmB;CAEpD,IAAI,iBAAiB,WAAW;EAG9B,IAAI,MAAM,UAAU,KAClB,IAAI,MAAM,QAAQ,iBAAiB,OAAO,EAAE,WAAW,QAAQ,GAAG,CAAC;EAGrE,MAAM,UAAyB,EAC7B,OAAO,MAAM,QACf;EACA,IAAI,MAAM,SACR,QAAQ,UAAU,MAAM;EAG1B,IAAI,YAAY,MAAM,eACpB,QAAQ,QAAQ,MAAM;EAGxB,OAAO,SAAS,cAAc,MAAM,MAAM,CAAC,CAAC,KAAK,OAAO;CAC1D;CAEA,IAAI,iBAAiB,+BACnB,OAAO,SAAS,WAAW,EACzB,QAAQ,MAAM,OAChB,CAAC;CAQH,4BAA4B,OAAO,OAAO;CAE1C,OAAO,SAAS,YAAY,EAC1B,OAAO,yBACT,CAAC;AACH;;;;AAKA,SAAgB,EAAE,SAAiB,cAAoB;CACrD,OACEA,eAAuB,WAAW,CAAC,EAAE,MAAM,SAAS,YAAY,KAChE,MAAM,SAAS,YAAY;AAE/B"}
|
|
@@ -32,9 +32,10 @@ type RateLimitOptions = {
|
|
|
32
32
|
* 429. Use this for endpoints that need a tighter cap than the global default:
|
|
33
33
|
* login, OTP request, password reset, expensive search, AI completions.
|
|
34
34
|
*
|
|
35
|
-
* The counter lives in-process. With `N` replicas
|
|
36
|
-
* `N × max`.
|
|
37
|
-
*
|
|
35
|
+
* The counter of THIS middleware always lives in-process. With `N` replicas
|
|
36
|
+
* its effective cap is `N × max`. The global limit can be shared across
|
|
37
|
+
* replicas by setting `http.rateLimit.redis` (an ioredis instance); that
|
|
38
|
+
* does not affect this per-route middleware.
|
|
38
39
|
*
|
|
39
40
|
* Sets `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` on
|
|
40
41
|
* every response; adds `Retry-After` (seconds) on a 429.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rate-limit.middleware.d.mts","names":[],"sources":["../../../../../../../../core/src/http/middleware/rate-limit.middleware.ts"],"mappings":";;;;;;KAQY,gBAAA;EAAgB;;;EAI1B,GAAA;EAIA;;;EAAA,QAAA;EAYA;;AAAY;
|
|
1
|
+
{"version":3,"file":"rate-limit.middleware.d.mts","names":[],"sources":["../../../../../../../../core/src/http/middleware/rate-limit.middleware.ts"],"mappings":";;;;;;KAQY,gBAAA;EAAgB;;;EAI1B,GAAA;EAIA;;;EAAA,QAAA;EAYA;;AAAY;AA8Cd;;;;EAlDE,YAAA,IAAgB,OAAA,EAAS,OAAO;EAkDE;;;EA9ClC,YAAA;AAAA;;;;;;;;;;;;;;;;;;;;;iBA8Cc,mBAAA,CAAoB,OAAA,EAAS,gBAAA,GAAmB,UAAU"}
|
|
@@ -19,9 +19,10 @@ function pruneExpired(now) {
|
|
|
19
19
|
* 429. Use this for endpoints that need a tighter cap than the global default:
|
|
20
20
|
* login, OTP request, password reset, expensive search, AI completions.
|
|
21
21
|
*
|
|
22
|
-
* The counter lives in-process. With `N` replicas
|
|
23
|
-
* `N × max`.
|
|
24
|
-
*
|
|
22
|
+
* The counter of THIS middleware always lives in-process. With `N` replicas
|
|
23
|
+
* its effective cap is `N × max`. The global limit can be shared across
|
|
24
|
+
* replicas by setting `http.rateLimit.redis` (an ioredis instance); that
|
|
25
|
+
* does not affect this per-route middleware.
|
|
25
26
|
*
|
|
26
27
|
* Sets `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` on
|
|
27
28
|
* every response; adds `Retry-After` (seconds) on a 429.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rate-limit.middleware.mjs","names":[],"sources":["../../../../../../../../core/src/http/middleware/rate-limit.middleware.ts"],"sourcesContent":["import type { Middleware } from \"../../router\";\nimport { HttpErrorCodes } from \"../error-codes\";\nimport type { Request } from \"../request\";\nimport { t } from \"./inject-request-context\";\n\n/**\n * Options for the per-route rate limit middleware.\n */\nexport type RateLimitOptions = {\n /**\n * Max requests allowed within the time window.\n */\n max: number;\n /**\n * Time window in milliseconds.\n */\n duration: number;\n /**\n * Group key generator. Defaults to the client IP. Override to scope per-user,\n * per-organization, per-tenant, etc.\n *\n * @example\n * keyGenerator: (request) => request.locals.user?.id ?? request.ip,\n */\n keyGenerator?: (request: Request) => string;\n /**\n * Override the default error message.\n */\n errorMessage?: string;\n};\n\ntype Bucket = {\n count: number;\n resetAt: number;\n};\n\nconst buckets = new Map<string, Bucket>();\n\n/**\n * Sweep expired buckets so the Map doesn't grow unbounded with one-shot keys\n * (rare per-user keys, dynamic path parameters in `keyGenerator`, etc.).\n * Called opportunistically, at most once per minute, not on a timer — keeps\n * the module side-effect-free for testing.\n */\nlet lastPruneAt = 0;\n\nfunction pruneExpired(now: number) {\n for (const [key, bucket] of buckets) {\n if (bucket.resetAt <= now) {\n buckets.delete(key);\n }\n }\n}\n\n/**\n * Per-route / per-group rate limit. Layers on top of `@fastify/rate-limit`'s\n * global cap (configured via `http.rateLimit`) — both run, and either can\n * 429. Use this for endpoints that need a tighter cap than the global default:\n * login, OTP request, password reset, expensive search, AI completions.\n *\n * The counter lives in-process. With `N` replicas
|
|
1
|
+
{"version":3,"file":"rate-limit.middleware.mjs","names":[],"sources":["../../../../../../../../core/src/http/middleware/rate-limit.middleware.ts"],"sourcesContent":["import type { Middleware } from \"../../router\";\nimport { HttpErrorCodes } from \"../error-codes\";\nimport type { Request } from \"../request\";\nimport { t } from \"./inject-request-context\";\n\n/**\n * Options for the per-route rate limit middleware.\n */\nexport type RateLimitOptions = {\n /**\n * Max requests allowed within the time window.\n */\n max: number;\n /**\n * Time window in milliseconds.\n */\n duration: number;\n /**\n * Group key generator. Defaults to the client IP. Override to scope per-user,\n * per-organization, per-tenant, etc.\n *\n * @example\n * keyGenerator: (request) => request.locals.user?.id ?? request.ip,\n */\n keyGenerator?: (request: Request) => string;\n /**\n * Override the default error message.\n */\n errorMessage?: string;\n};\n\ntype Bucket = {\n count: number;\n resetAt: number;\n};\n\nconst buckets = new Map<string, Bucket>();\n\n/**\n * Sweep expired buckets so the Map doesn't grow unbounded with one-shot keys\n * (rare per-user keys, dynamic path parameters in `keyGenerator`, etc.).\n * Called opportunistically, at most once per minute, not on a timer — keeps\n * the module side-effect-free for testing.\n */\nlet lastPruneAt = 0;\n\nfunction pruneExpired(now: number) {\n for (const [key, bucket] of buckets) {\n if (bucket.resetAt <= now) {\n buckets.delete(key);\n }\n }\n}\n\n/**\n * Per-route / per-group rate limit. Layers on top of `@fastify/rate-limit`'s\n * global cap (configured via `http.rateLimit`) — both run, and either can\n * 429. Use this for endpoints that need a tighter cap than the global default:\n * login, OTP request, password reset, expensive search, AI completions.\n *\n * The counter of THIS middleware always lives in-process. With `N` replicas\n * its effective cap is `N × max`. The global limit can be shared across\n * replicas by setting `http.rateLimit.redis` (an ioredis instance); that\n * does not affect this per-route middleware.\n *\n * Sets `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` on\n * every response; adds `Retry-After` (seconds) on a 429.\n *\n * @example\n * import { middleware } from \"@warlock.js/core\";\n * router.post(\"/auth/login\", loginController, {\n * middleware: [middleware.rateLimit({ max: 5, duration: 60_000 })],\n * });\n */\nexport function rateLimitMiddleware(options: RateLimitOptions): Middleware {\n return ({ request, response }) => {\n const now = Date.now();\n\n if (now - lastPruneAt > 60_000) {\n pruneExpired(now);\n lastPruneAt = now;\n }\n\n const groupKey = options.keyGenerator?.(request) || request.detectIp() || \"unknown\";\n const cacheKey = `${request.route.path}:${groupKey}`;\n\n let bucket = buckets.get(cacheKey);\n\n if (!bucket || bucket.resetAt <= now) {\n bucket = { count: 0, resetAt: now + options.duration };\n buckets.set(cacheKey, bucket);\n }\n\n bucket.count++;\n\n const remaining = Math.max(0, options.max - bucket.count);\n const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000));\n\n response.header(\"X-RateLimit-Limit\", options.max);\n response.header(\"X-RateLimit-Remaining\", remaining);\n response.header(\"X-RateLimit-Reset\", Math.ceil(bucket.resetAt / 1000));\n\n if (bucket.count > options.max) {\n response.header(\"Retry-After\", retryAfter);\n\n return response.tooManyRequests({\n error: options.errorMessage || t(\"http.rateLimitExceeded\"),\n errorCode: HttpErrorCodes.RateLimitExceeded,\n });\n }\n };\n}\n"],"mappings":";;;;AAoCA,MAAM,0BAAU,IAAI,IAAoB;;;;;;;AAQxC,IAAI,cAAc;AAElB,SAAS,aAAa,KAAa;CACjC,KAAK,MAAM,CAAC,KAAK,WAAW,SAC1B,IAAI,OAAO,WAAW,KACpB,QAAQ,OAAO,GAAG;AAGxB;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,oBAAoB,SAAuC;CACzE,QAAQ,EAAE,SAAS,eAAe;EAChC,MAAM,MAAM,KAAK,IAAI;EAErB,IAAI,MAAM,cAAc,KAAQ;GAC9B,aAAa,GAAG;GAChB,cAAc;EAChB;EAEA,MAAM,WAAW,QAAQ,eAAe,OAAO,KAAK,QAAQ,SAAS,KAAK;EAC1E,MAAM,WAAW,GAAG,QAAQ,MAAM,KAAK,GAAG;EAE1C,IAAI,SAAS,QAAQ,IAAI,QAAQ;EAEjC,IAAI,CAAC,UAAU,OAAO,WAAW,KAAK;GACpC,SAAS;IAAE,OAAO;IAAG,SAAS,MAAM,QAAQ;GAAS;GACrD,QAAQ,IAAI,UAAU,MAAM;EAC9B;EAEA,OAAO;EAEP,MAAM,YAAY,KAAK,IAAI,GAAG,QAAQ,MAAM,OAAO,KAAK;EACxD,MAAM,aAAa,KAAK,IAAI,GAAG,KAAK,MAAM,OAAO,UAAU,OAAO,GAAI,CAAC;EAEvE,SAAS,OAAO,qBAAqB,QAAQ,GAAG;EAChD,SAAS,OAAO,yBAAyB,SAAS;EAClD,SAAS,OAAO,qBAAqB,KAAK,KAAK,OAAO,UAAU,GAAI,CAAC;EAErE,IAAI,OAAO,QAAQ,QAAQ,KAAK;GAC9B,SAAS,OAAO,eAAe,UAAU;GAEzC,OAAO,SAAS,gBAAgB;IAC9B,OAAO,QAAQ,gBAAgB,EAAE,wBAAwB;IACzD;GACF,CAAC;EACH;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cidr-match.d.mts","names":[],"sources":["../../../../../../../../../core/src/http/middleware/utils/cidr-match.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"cidr-match.d.mts","names":[],"sources":["../../../../../../../../../core/src/http/middleware/utils/cidr-match.ts"],"mappings":";iBA2CgB,SAAA,CAAU,KAAA,UAAe,UAAkB;AAA3D;;;;AAA2D;AAkD3D;AAlDA,iBAkDgB,QAAA,CAAS,EAAA,UAAY,QAAkB"}
|
|
@@ -22,8 +22,17 @@ function ipv4ToInt(ip) {
|
|
|
22
22
|
}
|
|
23
23
|
return result >>> 0;
|
|
24
24
|
}
|
|
25
|
-
|
|
26
|
-
|
|
25
|
+
const IPV4_MAPPED_PREFIX = /^::ffff:(?=\d+\.\d+\.\d+\.\d+$)/i;
|
|
26
|
+
/**
|
|
27
|
+
* Normalize IPv4-mapped IPv6 (`::ffff:1.2.3.4`) to plain IPv4.
|
|
28
|
+
*/
|
|
29
|
+
function normalizeIp(value) {
|
|
30
|
+
return value.replace(IPV4_MAPPED_PREFIX, "");
|
|
31
|
+
}
|
|
32
|
+
function ipMatches(rawIp, rawPattern) {
|
|
33
|
+
if (!rawIp || !rawPattern) return false;
|
|
34
|
+
const ip = normalizeIp(rawIp);
|
|
35
|
+
const pattern = normalizeIp(rawPattern);
|
|
27
36
|
if (pattern === ip) return true;
|
|
28
37
|
if (!pattern.includes("/")) return false;
|
|
29
38
|
const [base, bitsRaw] = pattern.split("/");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cidr-match.mjs","names":[],"sources":["../../../../../../../../../core/src/http/middleware/utils/cidr-match.ts"],"sourcesContent":["/**\n * Match an IPv4 address against an exact IP or a CIDR block.\n *\n * IPv6 patterns are matched as exact-string only — full IPv6 CIDR support is\n * out of scope; ACLs in production almost always use IPv4 ranges. Add IPv6 CIDR\n * later if a real use-case appears.\n *\n * @example\n * ipMatches(\"10.0.0.5\", \"10.0.0.0/8\"); // true\n * ipMatches(\"10.0.0.5\", \"10.0.0.5\"); // true\n * ipMatches(\"192.168.1.1\", \"10.0.0.0/8\"); // false\n */\nfunction ipv4ToInt(ip: string): number | null {\n const parts = ip.split(\".\");\n\n if (parts.length !== 4) {\n return null;\n }\n\n let result = 0;\n\n for (const part of parts) {\n const num = Number(part);\n\n if (!Number.isInteger(num) || num < 0 || num > 255) {\n return null;\n }\n\n result = (result << 8) + num;\n }\n\n return result >>> 0;\n}\n\nexport function ipMatches(
|
|
1
|
+
{"version":3,"file":"cidr-match.mjs","names":[],"sources":["../../../../../../../../../core/src/http/middleware/utils/cidr-match.ts"],"sourcesContent":["/**\n * Match an IPv4 address against an exact IP or a CIDR block.\n *\n * IPv6 patterns are matched as exact-string only — full IPv6 CIDR support is\n * out of scope; ACLs in production almost always use IPv4 ranges. Add IPv6 CIDR\n * later if a real use-case appears.\n *\n * @example\n * ipMatches(\"10.0.0.5\", \"10.0.0.0/8\"); // true\n * ipMatches(\"10.0.0.5\", \"10.0.0.5\"); // true\n * ipMatches(\"192.168.1.1\", \"10.0.0.0/8\"); // false\n */\nfunction ipv4ToInt(ip: string): number | null {\n const parts = ip.split(\".\");\n\n if (parts.length !== 4) {\n return null;\n }\n\n let result = 0;\n\n for (const part of parts) {\n const num = Number(part);\n\n if (!Number.isInteger(num) || num < 0 || num > 255) {\n return null;\n }\n\n result = (result << 8) + num;\n }\n\n return result >>> 0;\n}\n\nconst IPV4_MAPPED_PREFIX = /^::ffff:(?=\\d+\\.\\d+\\.\\d+\\.\\d+$)/i;\n\n/**\n * Normalize IPv4-mapped IPv6 (`::ffff:1.2.3.4`) to plain IPv4.\n */\nfunction normalizeIp(value: string): string {\n return value.replace(IPV4_MAPPED_PREFIX, \"\");\n}\n\nexport function ipMatches(rawIp: string, rawPattern: string): boolean {\n if (!rawIp || !rawPattern) {\n return false;\n }\n\n const ip = normalizeIp(rawIp);\n const pattern = normalizeIp(rawPattern);\n\n if (pattern === ip) {\n return true;\n }\n\n if (!pattern.includes(\"/\")) {\n return false;\n }\n\n const [base, bitsRaw] = pattern.split(\"/\");\n\n if (base === undefined || bitsRaw === undefined) {\n return false;\n }\n\n const bits = Number(bitsRaw);\n\n if (!Number.isInteger(bits) || bits < 0 || bits > 32) {\n return false;\n }\n\n const ipInt = ipv4ToInt(ip);\n const baseInt = ipv4ToInt(base);\n\n if (ipInt === null || baseInt === null) {\n return false;\n }\n\n if (bits === 0) {\n return true;\n }\n\n const mask = (~0 << (32 - bits)) >>> 0;\n\n return (ipInt & mask) === (baseInt & mask);\n}\n\n/**\n * Returns true if `ip` matches any pattern in the list.\n *\n * @example\n * anyMatch(\"10.0.0.5\", [\"192.168.0.0/16\", \"10.0.0.0/8\"]); // true\n */\nexport function anyMatch(ip: string, patterns: string[]): boolean {\n return patterns.some((pattern) => ipMatches(ip, pattern));\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAS,UAAU,IAA2B;CAC5C,MAAM,QAAQ,GAAG,MAAM,GAAG;CAE1B,IAAI,MAAM,WAAW,GACnB,OAAO;CAGT,IAAI,SAAS;CAEb,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,MAAM,OAAO,IAAI;EAEvB,IAAI,CAAC,OAAO,UAAU,GAAG,KAAK,MAAM,KAAK,MAAM,KAC7C,OAAO;EAGT,UAAU,UAAU,KAAK;CAC3B;CAEA,OAAO,WAAW;AACpB;AAEA,MAAM,qBAAqB;;;;AAK3B,SAAS,YAAY,OAAuB;CAC1C,OAAO,MAAM,QAAQ,oBAAoB,EAAE;AAC7C;AAEA,SAAgB,UAAU,OAAe,YAA6B;CACpE,IAAI,CAAC,SAAS,CAAC,YACb,OAAO;CAGT,MAAM,KAAK,YAAY,KAAK;CAC5B,MAAM,UAAU,YAAY,UAAU;CAEtC,IAAI,YAAY,IACd,OAAO;CAGT,IAAI,CAAC,QAAQ,SAAS,GAAG,GACvB,OAAO;CAGT,MAAM,CAAC,MAAM,WAAW,QAAQ,MAAM,GAAG;CAEzC,IAAI,SAAS,UAAa,YAAY,QACpC,OAAO;CAGT,MAAM,OAAO,OAAO,OAAO;CAE3B,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,IAChD,OAAO;CAGT,MAAM,QAAQ,UAAU,EAAE;CAC1B,MAAM,UAAU,UAAU,IAAI;CAE9B,IAAI,UAAU,QAAQ,YAAY,MAChC,OAAO;CAGT,IAAI,SAAS,GACX,OAAO;CAGT,MAAM,OAAQ,MAAO,KAAK,SAAW;CAErC,QAAQ,QAAQ,WAAW,UAAU;AACvC;;;;;;;AAQA,SAAgB,SAAS,IAAY,UAA6B;CAChE,OAAO,SAAS,MAAM,YAAY,UAAU,IAAI,OAAO,CAAC;AAC1D"}
|
|
@@ -61,7 +61,7 @@ function readUserId(user) {
|
|
|
61
61
|
function buildIdempotencyCacheKey(request, idempotencyKey) {
|
|
62
62
|
const userType = request.decodedAccessToken?.userType || "anonymous";
|
|
63
63
|
const locals = request.locals;
|
|
64
|
-
return `idem:${userType}:${readUserId(locals.user) || request.detectIp() || "unknown"}:${idempotencyKey}`;
|
|
64
|
+
return `idem:${userType}:${readUserId(locals.user) || request.detectIp() || "unknown"}:${(request.route?.method || request.method || "").toUpperCase()}:${request.route?.path || ""}:${idempotencyKey}`;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
67
|
//#endregion
|