@warlock.js/core 5.16.0 → 5.17.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/esm/cli/commands/migrate.command.mjs +5 -1
- package/esm/cli/commands/migrate.command.mjs.map +1 -1
- package/esm/cli/commands/seed.command.mjs +2 -1
- package/esm/cli/commands/seed.command.mjs.map +1 -1
- package/esm/cli/commands/typings-generator.command.mjs +16 -23
- package/esm/cli/commands/typings-generator.command.mjs.map +1 -1
- package/esm/config/locale-configuration.mjs +7 -1
- package/esm/config/locale-configuration.mjs.map +1 -1
- package/esm/connectors/http-connector.d.mts.map +1 -1
- package/esm/connectors/http-connector.mjs +1 -18
- package/esm/connectors/http-connector.mjs.map +1 -1
- package/esm/connectors/read-bound-port.mjs +32 -0
- package/esm/connectors/read-bound-port.mjs.map +1 -0
- package/esm/dev-server/development-server.mjs +6 -2
- package/esm/dev-server/development-server.mjs.map +1 -1
- package/esm/dev-server/extract-translation-keys.mjs +68 -0
- package/esm/dev-server/extract-translation-keys.mjs.map +1 -0
- package/esm/dev-server/health-checker/checkers/typescript-health-checker.mjs +5 -1
- package/esm/dev-server/health-checker/checkers/typescript-health-checker.mjs.map +1 -1
- package/esm/dev-server/health-checker/workers/ts-health.worker.mjs +37 -8
- package/esm/dev-server/health-checker/workers/ts-health.worker.mjs.map +1 -1
- package/esm/dev-server/translation-keys-sources.mjs +19 -0
- package/esm/dev-server/translation-keys-sources.mjs.map +1 -0
- package/esm/dev-server/type-generator.mjs +64 -11
- package/esm/dev-server/type-generator.mjs.map +1 -1
- package/esm/generations/stubs.mjs +7 -6
- package/esm/generations/stubs.mjs.map +1 -1
- package/esm/http/csrf-default-guard.d.mts +32 -0
- package/esm/http/csrf-default-guard.d.mts.map +1 -0
- package/esm/http/csrf-default-guard.mjs +156 -0
- package/esm/http/csrf-default-guard.mjs.map +1 -0
- package/esm/http/csrf-origin-policy.d.mts +53 -0
- package/esm/http/csrf-origin-policy.d.mts.map +1 -0
- package/esm/http/csrf-origin-policy.mjs +104 -0
- package/esm/http/csrf-origin-policy.mjs.map +1 -0
- package/esm/http/error-codes.d.mts +14 -1
- package/esm/http/error-codes.d.mts.map +1 -1
- package/esm/http/error-codes.mjs +13 -0
- package/esm/http/error-codes.mjs.map +1 -1
- package/esm/http/index.d.mts +7 -1
- package/esm/http/index.mjs +7 -1
- package/esm/http/middleware/concurrency-limit.middleware.mjs +1 -1
- package/esm/http/middleware/idempotency.middleware.mjs +1 -1
- package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
- package/esm/http/middleware/inject-request-context.mjs +6 -0
- package/esm/http/middleware/inject-request-context.mjs.map +1 -1
- package/esm/http/middleware/ip-filter.middleware.mjs +1 -1
- package/esm/http/middleware/maintenance.middleware.mjs +1 -1
- package/esm/http/middleware/max-body-size.middleware.mjs +1 -1
- package/esm/http/middleware/rate-limit.middleware.mjs +1 -1
- package/esm/http/request.d.mts +2 -2
- package/esm/http/request.d.mts.map +1 -1
- package/esm/http/request.mjs +7 -3
- package/esm/http/request.mjs.map +1 -1
- package/esm/http/response.d.mts +3 -3
- package/esm/http/response.d.mts.map +1 -1
- package/esm/http/response.mjs +7 -1
- package/esm/http/response.mjs.map +1 -1
- package/esm/http/uploads/detect-image-format.mjs +59 -0
- package/esm/http/uploads/detect-image-format.mjs.map +1 -0
- package/esm/http/uploads/generate-image-variant.mjs +46 -0
- package/esm/http/uploads/generate-image-variant.mjs.map +1 -0
- package/esm/http/uploads/generate-image-variants.d.mts +49 -0
- package/esm/http/uploads/generate-image-variants.d.mts.map +1 -0
- package/esm/http/uploads/generate-image-variants.mjs +141 -0
- package/esm/http/uploads/generate-image-variants.mjs.map +1 -0
- package/esm/http/uploads/image-variant-types.d.mts +93 -0
- package/esm/http/uploads/image-variant-types.d.mts.map +1 -0
- package/esm/http/uploads/image-variants-config-error.d.mts +13 -0
- package/esm/http/uploads/image-variants-config-error.d.mts.map +1 -0
- package/esm/http/uploads/image-variants-config-error.mjs +17 -0
- package/esm/http/uploads/image-variants-config-error.mjs.map +1 -0
- package/esm/http/uploads/index.d.mts +4 -0
- package/esm/http/uploads/index.mjs +5 -0
- package/esm/http/uploads/is-path-inside.mjs +26 -0
- package/esm/http/uploads/is-path-inside.mjs.map +1 -0
- package/esm/http/uploads/load-variant-source.mjs +42 -0
- package/esm/http/uploads/load-variant-source.mjs.map +1 -0
- package/esm/http/uploads/matches-if-none-match.mjs +13 -0
- package/esm/http/uploads/matches-if-none-match.mjs.map +1 -0
- package/esm/http/uploads/parse-uploaded-file-query.mjs +51 -0
- package/esm/http/uploads/parse-uploaded-file-query.mjs.map +1 -0
- package/esm/http/uploads/read-file-head.mjs +20 -0
- package/esm/http/uploads/read-file-head.mjs.map +1 -0
- package/esm/http/uploads/resolve-image-variants-config.mjs +91 -0
- package/esm/http/uploads/resolve-image-variants-config.mjs.map +1 -0
- package/esm/http/uploads/resolve-inline-image-content-type.mjs +53 -0
- package/esm/http/uploads/resolve-inline-image-content-type.mjs.map +1 -0
- package/esm/http/uploads/resolve-original-content-type.mjs +31 -0
- package/esm/http/uploads/resolve-original-content-type.mjs.map +1 -0
- package/esm/http/uploads/resolve-upload-path.mjs +56 -0
- package/esm/http/uploads/resolve-upload-path.mjs.map +1 -0
- package/esm/http/uploads/resolve-variant-candidate.mjs +39 -0
- package/esm/http/uploads/resolve-variant-candidate.mjs.map +1 -0
- package/esm/http/uploads/single-flight.mjs +40 -0
- package/esm/http/uploads/single-flight.mjs.map +1 -0
- package/esm/http/uploads/uploaded-file.controller.d.mts +24 -0
- package/esm/http/uploads/uploaded-file.controller.d.mts.map +1 -0
- package/esm/http/uploads/uploaded-file.controller.mjs +174 -0
- package/esm/http/uploads/uploaded-file.controller.mjs.map +1 -0
- package/esm/http/uploads/variant-cache-key.mjs +45 -0
- package/esm/http/uploads/variant-cache-key.mjs.map +1 -0
- package/esm/http/uploads/variant-generations.mjs +16 -0
- package/esm/http/uploads/variant-generations.mjs.map +1 -0
- package/esm/http/uploads-types.d.mts +102 -1
- package/esm/http/uploads-types.d.mts.map +1 -1
- package/esm/index.d.mts +9 -2
- package/esm/index.mjs +8 -2
- package/esm/router/types.d.mts +23 -0
- package/esm/router/types.d.mts.map +1 -1
- package/esm/storage/index.d.mts +1 -0
- package/esm/storage/index.mjs +1 -0
- package/esm/storage/scoped-storage.d.mts +1 -0
- package/esm/storage/scoped-storage.d.mts.map +1 -1
- package/esm/storage/scoped-storage.mjs +3 -0
- package/esm/storage/scoped-storage.mjs.map +1 -1
- package/esm/storage/storage.d.mts +2 -0
- package/esm/storage/storage.d.mts.map +1 -1
- package/esm/storage/storage.mjs +4 -0
- package/esm/storage/storage.mjs.map +1 -1
- package/esm/storage/utils/storage-not-initialized-error.d.mts +22 -0
- package/esm/storage/utils/storage-not-initialized-error.d.mts.map +1 -0
- package/esm/storage/utils/storage-not-initialized-error.mjs +24 -0
- package/esm/storage/utils/storage-not-initialized-error.mjs.map +1 -0
- package/llms-full.txt +17 -1
- package/package.json +22 -21
- package/skills/use-localization/SKILL.md +16 -0
- package/skills/use-middleware/SKILL.md +1 -1
- package/esm/dev-server/translation-type-generator.mjs +0 -28
- package/esm/dev-server/translation-type-generator.mjs.map +0 -1
|
@@ -37,7 +37,20 @@ declare enum HttpErrorCodes {
|
|
|
37
37
|
/**
|
|
38
38
|
* Application is in maintenance mode and the request did not match the allowlist.
|
|
39
39
|
*/
|
|
40
|
-
Maintenance = "EC106"
|
|
40
|
+
Maintenance = "EC106",
|
|
41
|
+
/**
|
|
42
|
+
* Default core CSRF-Origin guard (SECURITY, card 8a752ab2, `./csrf-default-guard.ts`)
|
|
43
|
+
* refused an unsafe-method, cookie-carrying request whose `Origin`/`Referer`
|
|
44
|
+
* did not name the request's own origin or an entry in
|
|
45
|
+
* `auth.csrf.allowedOrigins`.
|
|
46
|
+
*
|
|
47
|
+
* Deliberately reuses `@warlock.js/auth`'s `AuthErrorCodes.CsrfOriginMismatch`
|
|
48
|
+
* value (`EC006`), NOT a fresh `EC1xx` core code: this is the exact same
|
|
49
|
+
* failure class `authMiddleware("cookie:*")`'s own CSRF-Origin check
|
|
50
|
+
* reports — one client-visible identifier for "CSRF Origin check failed",
|
|
51
|
+
* regardless of which seam caught it.
|
|
52
|
+
*/
|
|
53
|
+
CsrfOriginMismatch = "EC006"
|
|
41
54
|
}
|
|
42
55
|
//#endregion
|
|
43
56
|
export { HttpErrorCodes };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-codes.d.mts","names":[],"sources":["../../../../../../../core/src/http/error-codes.ts"],"mappings":";;AASA;;;;;;;;aAAY,cAAA;EA8BV
|
|
1
|
+
{"version":3,"file":"error-codes.d.mts","names":[],"sources":["../../../../../../../core/src/http/error-codes.ts"],"mappings":";;AASA;;;;;;;;aAAY,cAAA;EA8BV;;;;EAzBA,sBAAA;;;;EAKA,qBAAA;;;;EAKA,iBAAA;;;;EAKA,uBAAA;;;;EAKA,YAAA;;;;EAKA,WAAA;;;;EAKA,WAAA;;;;;;;;;;;;;EAcA,kBAAA;AAAA"}
|
package/esm/http/error-codes.mjs
CHANGED
|
@@ -38,6 +38,19 @@ let HttpErrorCodes = /* @__PURE__ */ function(HttpErrorCodes) {
|
|
|
38
38
|
* Application is in maintenance mode and the request did not match the allowlist.
|
|
39
39
|
*/
|
|
40
40
|
HttpErrorCodes["Maintenance"] = "EC106";
|
|
41
|
+
/**
|
|
42
|
+
* Default core CSRF-Origin guard (SECURITY, card 8a752ab2, `./csrf-default-guard.ts`)
|
|
43
|
+
* refused an unsafe-method, cookie-carrying request whose `Origin`/`Referer`
|
|
44
|
+
* did not name the request's own origin or an entry in
|
|
45
|
+
* `auth.csrf.allowedOrigins`.
|
|
46
|
+
*
|
|
47
|
+
* Deliberately reuses `@warlock.js/auth`'s `AuthErrorCodes.CsrfOriginMismatch`
|
|
48
|
+
* value (`EC006`), NOT a fresh `EC1xx` core code: this is the exact same
|
|
49
|
+
* failure class `authMiddleware("cookie:*")`'s own CSRF-Origin check
|
|
50
|
+
* reports — one client-visible identifier for "CSRF Origin check failed",
|
|
51
|
+
* regardless of which seam caught it.
|
|
52
|
+
*/
|
|
53
|
+
HttpErrorCodes["CsrfOriginMismatch"] = "EC006";
|
|
41
54
|
return HttpErrorCodes;
|
|
42
55
|
}({});
|
|
43
56
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-codes.mjs","names":[],"sources":["../../../../../../../core/src/http/error-codes.ts"],"sourcesContent":["/**\n * HTTP middleware error codes.\n *\n * Mirrors the convention used by `@warlock.js/auth`'s `AuthErrorCodes` —\n * stable string identifiers clients can branch on without parsing message text.\n *\n * Range `EC100..EC199` is reserved for `@warlock.js/core` HTTP middleware.\n * `EC001..EC099` belongs to `@warlock.js/auth`.\n */\nexport enum HttpErrorCodes {\n /**\n * Same idempotency key reused with a different request body.\n * Client likely has a bug — same intent must reuse the same body.\n */\n IdempotencyKeyConflict = \"EC100\",\n\n /**\n * Idempotency key header is malformed (wrong length / non-printable chars).\n */\n IdempotencyKeyInvalid = \"EC101\",\n\n /**\n * Per-route rate limit exceeded. Different from the global `@fastify/rate-limit` 429.\n */\n RateLimitExceeded = \"EC102\",\n\n /**\n * Per-route concurrency cap reached — too many in-flight requests against this endpoint.\n */\n ConcurrencyLimitReached = \"EC103\",\n\n /**\n * Request `Content-Length` exceeds the per-route body cap.\n */\n BodyTooLarge = \"EC104\",\n\n /**\n * Client IP failed the `ipFilter()` allow/deny check.\n */\n IpForbidden = \"EC105\",\n\n /**\n * Application is in maintenance mode and the request did not match the allowlist.\n */\n Maintenance = \"EC106\",\n}\n"],"mappings":";;;;;;;;;;AASA,IAAY,iBAAL;;;;;CAKL;;;;CAKA;;;;CAKA;;;;CAKA;;;;CAKA;;;;CAKA;;;;CAKA;;AACF"}
|
|
1
|
+
{"version":3,"file":"error-codes.mjs","names":[],"sources":["../../../../../../../core/src/http/error-codes.ts"],"sourcesContent":["/**\n * HTTP middleware error codes.\n *\n * Mirrors the convention used by `@warlock.js/auth`'s `AuthErrorCodes` —\n * stable string identifiers clients can branch on without parsing message text.\n *\n * Range `EC100..EC199` is reserved for `@warlock.js/core` HTTP middleware.\n * `EC001..EC099` belongs to `@warlock.js/auth`.\n */\nexport enum HttpErrorCodes {\n /**\n * Same idempotency key reused with a different request body.\n * Client likely has a bug — same intent must reuse the same body.\n */\n IdempotencyKeyConflict = \"EC100\",\n\n /**\n * Idempotency key header is malformed (wrong length / non-printable chars).\n */\n IdempotencyKeyInvalid = \"EC101\",\n\n /**\n * Per-route rate limit exceeded. Different from the global `@fastify/rate-limit` 429.\n */\n RateLimitExceeded = \"EC102\",\n\n /**\n * Per-route concurrency cap reached — too many in-flight requests against this endpoint.\n */\n ConcurrencyLimitReached = \"EC103\",\n\n /**\n * Request `Content-Length` exceeds the per-route body cap.\n */\n BodyTooLarge = \"EC104\",\n\n /**\n * Client IP failed the `ipFilter()` allow/deny check.\n */\n IpForbidden = \"EC105\",\n\n /**\n * Application is in maintenance mode and the request did not match the allowlist.\n */\n Maintenance = \"EC106\",\n\n /**\n * Default core CSRF-Origin guard (SECURITY, card 8a752ab2, `./csrf-default-guard.ts`)\n * refused an unsafe-method, cookie-carrying request whose `Origin`/`Referer`\n * did not name the request's own origin or an entry in\n * `auth.csrf.allowedOrigins`.\n *\n * Deliberately reuses `@warlock.js/auth`'s `AuthErrorCodes.CsrfOriginMismatch`\n * value (`EC006`), NOT a fresh `EC1xx` core code: this is the exact same\n * failure class `authMiddleware(\"cookie:*\")`'s own CSRF-Origin check\n * reports — one client-visible identifier for \"CSRF Origin check failed\",\n * regardless of which seam caught it.\n */\n CsrfOriginMismatch = \"EC006\",\n}\n"],"mappings":";;;;;;;;;;AASA,IAAY,iBAAL;;;;;CAKL;;;;CAKA;;;;CAKA;;;;CAKA;;;;CAKA;;;;CAKA;;;;CAKA;;;;;;;;;;;;;CAcA;;AACF"}
|
package/esm/http/index.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { PipeableReactStream, StreamReactResponseOptions, streamReactResponse } from "./stream-react-response.mjs";
|
|
2
2
|
import { XMLable } from "./xmlable.mjs";
|
|
3
3
|
import { CookieOptions, Response, ResponseStatus, SendBufferOptions, SendFileOptions } from "./response.mjs";
|
|
4
|
-
import { FileNamingStrategy, ImageTransformCallback, ImageTransformConfig, PrefixConfig, PrefixOptions, SaveAsOptions, SaveOptions, UploadedFileImageOptions, UploadsConfigurations } from "./uploads-types.mjs";
|
|
4
|
+
import { FileNamingStrategy, ImageTransformCallback, ImageTransformConfig, ImageVariantDefinition, ImageVariantFit, ImageVariantOutputFormat, PrefixConfig, PrefixOptions, SaveAsOptions, SaveOptions, UploadedFileImageOptions, UploadsConfigurations, UploadsImagesConfigurations } from "./uploads-types.mjs";
|
|
5
5
|
import { FileValidationOptions, UploadedFile, UploadedFileJson } from "./uploaded-file.mjs";
|
|
6
6
|
import { Request } from "./request.mjs";
|
|
7
7
|
import { CspConfig, DEFAULT_CSP_DIRECTIVES, InvalidCspDirectiveError, applyCspHeader, buildCspHeaderValue, mergeCspDirectives, resolveCspConfig, serializeCspDirectives, validateCspConfigAtBoot, validateCspDirectives } from "./csp.mjs";
|
|
@@ -9,12 +9,18 @@ import { HttpTracingConfig, TracingContext, TracingHooks, TracingPhaseInfo, Trac
|
|
|
9
9
|
import { DecodedAccessToken, HttpConfigurations, PartialMiddleware, RequestEvent, RequestLocals, ResponseEvent, ResponseSSEController, ResponseStreamController, ReturnedResponse } from "./types.mjs";
|
|
10
10
|
import { defaultHttpConfigurations, httpConfig } from "./config.mjs";
|
|
11
11
|
import { createHttpApplication, stopHttpApplication } from "./createHttpApplication.mjs";
|
|
12
|
+
import { requiresDefaultCsrfGuard, runDefaultCsrfGuard } from "./csrf-default-guard.mjs";
|
|
13
|
+
import { CsrfOriginCheckReason, CsrfOriginVerdict, isAllowedCsrfOrigin, normalizeOrigin, originOf, ownOrigin, resolveCsrfOriginVerdict } from "./csrf-origin-policy.mjs";
|
|
12
14
|
import { RequestLog } from "./database/RequestLog.mjs";
|
|
13
15
|
import { HttpErrorCodes } from "./error-codes.mjs";
|
|
14
16
|
import { logResponse, wrapResponseInDataKey } from "./events.mjs";
|
|
15
17
|
import { HealthCheck, HealthStatus, health } from "./health.mjs";
|
|
16
18
|
import { RequestController } from "./request-controller.mjs";
|
|
17
19
|
import { UPLOADS_DEFAULTS, uploadsConfig } from "./uploads-config.mjs";
|
|
20
|
+
import { DetectedImageFormat, GeneratedImageDescriptor, GeneratedImageVariant, ResolvedImageVariantsConfig, UploadedFileQuery, VariantOutputFormat, VariantSourceFormat } from "./uploads/image-variant-types.mjs";
|
|
21
|
+
import { GenerateImageVariantsOptions, generateImageVariants } from "./uploads/generate-image-variants.mjs";
|
|
22
|
+
import { ImageVariantsConfigError } from "./uploads/image-variants-config-error.mjs";
|
|
23
|
+
import { uploadedFileController } from "./uploads/uploaded-file.controller.mjs";
|
|
18
24
|
import { BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, RequestUserMovedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./errors/errors.mjs";
|
|
19
25
|
import { CacheMiddlewareOptions } from "./middleware/cache-response-middleware.mjs";
|
|
20
26
|
import { ConcurrencyLimitOptions } from "./middleware/concurrency-limit.middleware.mjs";
|
package/esm/http/index.mjs
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { requestContext, useCurrentUser, useRequest, useRequestStore } from "./context/request-context.mjs";
|
|
2
2
|
import { DEFAULT_CSP_DIRECTIVES, InvalidCspDirectiveError, applyCspHeader, buildCspHeaderValue, mergeCspDirectives, resolveCspConfig, serializeCspDirectives, validateCspConfigAtBoot, validateCspDirectives } from "./csp.mjs";
|
|
3
|
+
import { HttpErrorCodes } from "./error-codes.mjs";
|
|
4
|
+
import { isAllowedCsrfOrigin, normalizeOrigin, originOf, ownOrigin, resolveCsrfOriginVerdict } from "./csrf-origin-policy.mjs";
|
|
5
|
+
import { requiresDefaultCsrfGuard, runDefaultCsrfGuard } from "./csrf-default-guard.mjs";
|
|
3
6
|
import { BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, RequestUserMovedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./errors/errors.mjs";
|
|
4
7
|
import { deriveTraceId, parseTraceparentTraceId } from "./tracing/trace-id.mjs";
|
|
5
8
|
import { buildTracingContext, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled, resetTracingConfigForTests, resolveTracingConfig } from "./tracing/tracing-dispatcher.mjs";
|
|
@@ -15,10 +18,13 @@ import { registerHttpPlugins } from "./plugins.mjs";
|
|
|
15
18
|
import { closeServerWithTimeout, getHttpServer, startHttpServer } from "./server.mjs";
|
|
16
19
|
import { createHttpApplication, stopHttpApplication } from "./createHttpApplication.mjs";
|
|
17
20
|
import { RequestLog } from "./database/RequestLog.mjs";
|
|
18
|
-
import { HttpErrorCodes } from "./error-codes.mjs";
|
|
19
21
|
import { logResponse, wrapResponseInDataKey } from "./events.mjs";
|
|
20
22
|
import { health } from "./health.mjs";
|
|
21
23
|
import { RequestController } from "./request-controller.mjs";
|
|
24
|
+
import { ImageVariantsConfigError } from "./uploads/image-variants-config-error.mjs";
|
|
25
|
+
import { generateImageVariants } from "./uploads/generate-image-variants.mjs";
|
|
26
|
+
import { uploadedFileController } from "./uploads/uploaded-file.controller.mjs";
|
|
27
|
+
import "./uploads/index.mjs";
|
|
22
28
|
import { buildIdempotencyCacheKey, hashBody, isValidIdempotencyKey } from "./middleware/utils/idempotency-key.mjs";
|
|
23
29
|
import { anyMatch, ipMatches } from "./middleware/utils/cidr-match.mjs";
|
|
24
30
|
import { parseSize } from "./middleware/utils/parse-size.mjs";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t } from "./inject-request-context.mjs";
|
|
2
1
|
import { HttpErrorCodes } from "../error-codes.mjs";
|
|
2
|
+
import { t } from "./inject-request-context.mjs";
|
|
3
3
|
|
|
4
4
|
//#region ../core/src/http/middleware/concurrency-limit.middleware.ts
|
|
5
5
|
const counters = /* @__PURE__ */ new Map();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t } from "./inject-request-context.mjs";
|
|
2
1
|
import { HttpErrorCodes } from "../error-codes.mjs";
|
|
2
|
+
import { t } from "./inject-request-context.mjs";
|
|
3
3
|
import { buildIdempotencyCacheKey, hashBody, isValidIdempotencyKey } from "./utils/idempotency-key.mjs";
|
|
4
4
|
import config from "@mongez/config";
|
|
5
5
|
import { log } from "@warlock.js/logger";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inject-request-context.d.mts","names":[],"sources":["../../../../../../../../core/src/http/middleware/inject-request-context.ts"],"mappings":";;;;;;;
|
|
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;;;;iBAoIK,CAAA,CAAE,OAAA,UAAiB,YAAkB"}
|
|
@@ -2,6 +2,7 @@ import { environment } from "../../utils/environment.mjs";
|
|
|
2
2
|
import { requestContext } from "../context/request-context.mjs";
|
|
3
3
|
import "../../utils/index.mjs";
|
|
4
4
|
import { applyCspHeader } from "../csp.mjs";
|
|
5
|
+
import { runDefaultCsrfGuard } from "../csrf-default-guard.mjs";
|
|
5
6
|
import { HttpError } from "../errors/errors.mjs";
|
|
6
7
|
import { buildTracingContext, dispatchPhase, isTracingEnabled } from "../tracing/tracing-dispatcher.mjs";
|
|
7
8
|
import "../tracing/index.mjs";
|
|
@@ -9,6 +10,7 @@ import config from "@mongez/config";
|
|
|
9
10
|
import { trans } from "@mongez/localization";
|
|
10
11
|
import { DatabaseWriterValidationError } from "@warlock.js/cascade";
|
|
11
12
|
import { contextManager } from "@warlock.js/context";
|
|
13
|
+
import { log } from "@warlock.js/logger";
|
|
12
14
|
|
|
13
15
|
//#region ../core/src/http/middleware/inject-request-context.ts
|
|
14
16
|
/**
|
|
@@ -44,6 +46,10 @@ function createRequestStore(request, response) {
|
|
|
44
46
|
});
|
|
45
47
|
return contextManager.runAll(httpContextStore, async () => {
|
|
46
48
|
try {
|
|
49
|
+
const csrfGuardResponse = await runDefaultCsrfGuard(request, response, t, (reason) => {
|
|
50
|
+
log.error("http", "csrf-default-guard", /* @__PURE__ */ new Error(`Default CSRF Origin guard refused request: ${reason}`));
|
|
51
|
+
});
|
|
52
|
+
if (csrfGuardResponse) return csrfGuardResponse;
|
|
47
53
|
const result = await request.runMiddleware();
|
|
48
54
|
if (result) return result;
|
|
49
55
|
request.trigger("executingAction", request.route);
|
|
@@ -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 config from \"@mongez/config\";\nimport { environment } from \"../../utils\";\nimport { requestContext as requestContextInstance } from \"../context/request-context\";\nimport { applyCspHeader } from \"../csp\";\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 // 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":"
|
|
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,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S,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,5 +1,5 @@
|
|
|
1
|
-
import { t } from "./inject-request-context.mjs";
|
|
2
1
|
import { HttpErrorCodes } from "../error-codes.mjs";
|
|
2
|
+
import { t } from "./inject-request-context.mjs";
|
|
3
3
|
import { anyMatch } from "./utils/cidr-match.mjs";
|
|
4
4
|
|
|
5
5
|
//#region ../core/src/http/middleware/ip-filter.middleware.ts
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t } from "./inject-request-context.mjs";
|
|
2
1
|
import { HttpErrorCodes } from "../error-codes.mjs";
|
|
2
|
+
import { t } from "./inject-request-context.mjs";
|
|
3
3
|
import { parseSize } from "./utils/parse-size.mjs";
|
|
4
4
|
|
|
5
5
|
//#region ../core/src/http/middleware/max-body-size.middleware.ts
|
package/esm/http/request.d.mts
CHANGED
|
@@ -210,8 +210,8 @@ declare class Request<RequestValidation = any> {
|
|
|
210
210
|
*/
|
|
211
211
|
protected cacheLocale(candidate: unknown): string;
|
|
212
212
|
/**
|
|
213
|
-
* Resolve the first present Mode B source
|
|
214
|
-
*
|
|
213
|
+
* Resolve the first present Mode B source, skipping unsupported browser
|
|
214
|
+
* preferences. Other unsupported values resolve to the configured default.
|
|
215
215
|
*/
|
|
216
216
|
protected resolveLocale(): string;
|
|
217
217
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.d.mts","names":[],"sources":["../../../../../../../core/src/http/request.ts"],"mappings":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L,KAAA,CAAM,IAAA;;;;EAWN,MAAA,CAAO,IAAA;;;;EAOP,IAAA,CAAK,GAAA,UAAa,YAAA;;;;EAqBlB,GAAA,CAAI,GAAA,UAAa,YAAA;;;;MAWb,OAAA;;;;EAOJ,MAAA,CAAO,GAAA,UAAa,YAAA;;;;EASpB,KAAA,CAAM,GAAA,UAAa,YAAA;;;;EASnB,MAAA,CAAO,GAAA,UAAa,YAAA;;;;;;;;;;MAehB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAqCJ,QAAA;;;;MAoCI,MAAA;;;;MAOA,GAAA;;;;MAOA,OAAA;;;;MAOA,SAAA;;;;MAOA,OAAA,gBAAuB,WAAA,CAAY,OAAA;;;;EAOvC,SAAA,CAAU,GAAA,EAAK,UAAA,EAAY,KAAA;AAAA"}
|
package/esm/http/request.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { config } from "../config/config-getter.mjs";
|
|
2
|
-
import { LOCALE_COOKIE_NAME, resolveLocaleConfiguration } from "../config/locale-configuration.mjs";
|
|
2
|
+
import { LOCALE_COOKIE_NAME, LOCALE_PREFERENCE_COOKIE_NAME, resolveLocaleConfiguration } from "../config/locale-configuration.mjs";
|
|
3
3
|
import { CookieJarUnavailableError, RequestUserMovedError } from "./errors/errors.mjs";
|
|
4
4
|
import { deriveTraceId } from "./tracing/trace-id.mjs";
|
|
5
5
|
import { buildTracingContext, dispatchPhase, isTracingEnabled } from "./tracing/tracing-dispatcher.mjs";
|
|
@@ -162,12 +162,16 @@ var Request = class Request {
|
|
|
162
162
|
return this._locale;
|
|
163
163
|
}
|
|
164
164
|
/**
|
|
165
|
-
* Resolve the first present Mode B source
|
|
166
|
-
*
|
|
165
|
+
* Resolve the first present Mode B source, skipping unsupported browser
|
|
166
|
+
* preferences. Other unsupported values resolve to the configured default.
|
|
167
167
|
*/
|
|
168
168
|
resolveLocale() {
|
|
169
|
+
const { localeCodes } = resolveLocaleConfiguration(config.key("app.localeCode"), config.key("app.localeCodes"));
|
|
170
|
+
const preference = this.cookies[LOCALE_PREFERENCE_COOKIE_NAME];
|
|
171
|
+
const supportedPreference = typeof preference === "string" && (localeCodes === void 0 || localeCodes.includes(preference)) ? preference : void 0;
|
|
169
172
|
const candidate = [
|
|
170
173
|
this.query["locale"],
|
|
174
|
+
supportedPreference,
|
|
171
175
|
this.cookies[LOCALE_COOKIE_NAME],
|
|
172
176
|
this.header("locale")
|
|
173
177
|
].find((value) => typeof value === "string" && value.length > 0);
|
package/esm/http/request.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.mjs","names":[],"sources":["../../../../../../../core/src/http/request.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport events from \"@mongez/events\";\nimport { trans, transFrom } from \"@mongez/localization\";\nimport { Random, except, get, only, rtrim, set, unset } from \"@mongez/reinforcements\";\nimport { isEmpty } from \"@mongez/supportive-is\";\nimport type { LogLevel } from \"@warlock.js/logger\";\nimport { log } from \"@warlock.js/logger\";\nimport { BaseValidator, v } from \"@warlock.js/seal\";\nimport type { FastifyRequest } from \"fastify\";\nimport { randomBytes } from \"node:crypto\";\nimport { type IncomingHttpHeaders } from \"node:http2\";\nimport { Application } from \"../application/application\";\nimport { config } from \"../config/config-getter\";\nimport { LOCALE_COOKIE_NAME, resolveLocaleConfiguration } from \"../config/locale-configuration\";\nimport type { Middleware, Route } from \"../router\";\nimport { validateAll } from \"../validation/validateAll\";\nimport { CookieJarUnavailableError, RequestUserMovedError } from \"./errors\";\nimport { createRequestStore } from \"./middleware/inject-request-context\";\nimport { Response } from \"./response\";\nimport { buildTracingContext, deriveTraceId, dispatchPhase, isTracingEnabled } from \"./tracing\";\nimport type { DecodedAccessToken, RequestEvent, RequestLocals } from \"./types\";\nimport { UploadedFile } from \"./uploaded-file\";\n\ntype StandardHeaders = {\n // copy every declared property from http.IncomingHttpHeaders\n // but remove index signatures\n [\n K in keyof IncomingHttpHeaders as string extends K ? never : number extends K ? never : K\n ]: IncomingHttpHeaders[K];\n};\n\ntype HeaderKeys = keyof StandardHeaders;\n\nexport class Request<RequestValidation = any> {\n /**\n * Underlying Fastify request — a public escape hatch to capabilities the\n * framework's high-level helpers don't yet cover.\n *\n * **Prefer framework methods first**: `request.input()`, `request.header()`,\n * `request.body`, `request.query`, `request.params`, `request.file()`,\n * `request.locals.user` (set by `@warlock.js/auth`), `request.detectIp()`,\n * etc. They handle locale, parsing,\n * trust-proxy, and validation pipeline integration correctly.\n *\n * **Reach for `baseRequest` only** when the framework genuinely lacks a\n * helper for what you need — and when you do, file an issue so we can add\n * it. The escape hatch is the release valve that lets consumers move\n * faster than the framework, but every long-term reach here is a missing\n * helper waiting to be added.\n */\n public baseRequest!: FastifyRequest;\n\n /**\n * Response Object\n */\n public response!: Response;\n\n /**\n * Route Object\n */\n public route!: Route;\n\n /**\n * Parsed Request Payload\n */\n protected payload: any = {};\n\n /**\n * Backing field for `decodedAccessToken` — see the accessor below.\n */\n private _decodedAccessToken?: DecodedAccessToken;\n\n /**\n * Decoded access token payload (set by auth middleware).\n *\n * A prototype accessor, not a plain field, so assignment can mark the\n * request `authDerived` (see the setter below and `RequestLocals` in\n * `types.ts`) without every call site remembering to do so itself.\n */\n public get decodedAccessToken(): DecodedAccessToken | undefined {\n return this._decodedAccessToken;\n }\n\n public set decodedAccessToken(value: DecodedAccessToken | undefined) {\n this._decodedAccessToken = value;\n this.locals.authDerived = true;\n }\n\n /**\n * REMOVED in 5.12.0 — the authenticated user now lives at\n * `request.locals.user`, a key `@warlock.js/auth` declares via module\n * augmentation on `RequestLocals` and writes from its middleware after a\n * successful token resolution. `RequestUser` moved out of core to\n * `@warlock.js/auth` alongside it.\n *\n * This getter is a development-time diagnostic only, kept for one release\n * so a call site that still reads `request.user` fails loudly at runtime\n * instead of silently reading `undefined`. It is typed `never` so it\n * cannot reintroduce an auth-shaped type into core, and it throws\n * unconditionally outside production so the failure is impossible to miss\n * in local dev — see `RequestUserMovedError`.\n *\n * There is no setter: nothing in core or downstream packages should ever\n * assign to `request.user` again.\n */\n public get user(): never {\n if (Application.isDevelopment) {\n throw new RequestUserMovedError();\n }\n\n return undefined as never;\n }\n\n /**\n * Private, server-only, per-request data bag.\n *\n * Distinct from the input payload (`body` / `query` / `params` / `all()`):\n * a write here never surfaces in `request.all()`, `request.validated()`, or\n * `request.input()`. That is the trap `request.set()` sets for private data\n * — it writes into the payload `all` bag, so anything stored there leaks\n * into every input accessor and, from there, into the client-facing\n * payload. `locals` is the correct home for private per-request app data\n * (a resolved session, a fetched-once model) that must never be mistaken\n * for client input.\n *\n * Augmentable via module augmentation, in the module that OWNS the key:\n *\n * ```typescript\n * declare module \"@warlock.js/core\" {\n * interface RequestLocals {\n * session?: { token: string };\n * }\n * }\n * ```\n *\n * A plain class-field initializer is sufficient for \"fresh per request\":\n * `router.ts:925` constructs `new Request()` for every incoming request —\n * `Request` instances are not pooled or reused across requests — so this\n * initializer runs exactly once per request and no value can leak in from\n * a prior one.\n */\n public locals: RequestLocals = {};\n\n /**\n * Backing field for the lazily-generated CSP nonce. Left `undefined` until\n * the first `request.nonce` read; see the `nonce` getter below.\n */\n protected _nonce?: string;\n\n /**\n * Per-request Content-Security-Policy nonce — a fresh, unguessable value\n * the web layer hands to `<Scripts nonce={...} />` (the inline payload\n * script) and to the `Content-Security-Policy` header, so a strict\n * `script-src 'nonce-...'` allows only the script this request actually\n * rendered.\n *\n * Generated LAZILY on first access, not eagerly in `setRequest()`: most\n * requests (API routes, anything that isn't rendering HTML) never read it,\n * and spending a `randomBytes` call on every single request for a value\n * most of them discard is wasted entropy draw + CPU. Once generated it is\n * cached in `_nonce`, so every subsequent read within the SAME request\n * returns the identical value — required, since the header and the inline\n * `<script>` tag must agree on one nonce. `_nonce` is a plain field on a\n * per-request `Request` instance (see `locals` above — `router.ts:925`,\n * no pooling), so the cache can never leak into the next request; a fresh\n * `Request` means a fresh, unset `_nonce`.\n *\n * 16 random bytes, base64-encoded — the size the CSP Level 3 spec's own\n * examples use, and far more entropy than an attacker could feasibly guess\n * to defeat the policy.\n */\n public get nonce(): string {\n if (!this._nonce) {\n this._nonce = randomBytes(16).toString(\"base64\");\n }\n\n return this._nonce;\n }\n\n /**\n * Current request instance\n */\n public static current: Request;\n\n /**\n * Translation method\n * Type of it is the same as the type of trans function\n */\n public trans: ReturnType<typeof trans> = trans;\n\n /**\n * Alias to trans method\n */\n public t: ReturnType<typeof trans> = trans;\n\n /*\n * v5 removed the `[key: string]: any` index signature (eed20184). Attaching\n * arbitrary properties compiled silently and hid real bugs behind `any`.\n * The sanctioned extension paths are:\n * - `request.locals` (augment `RequestLocals` via module augmentation) for\n * per-request attached data, e.g. models fetched in validation middleware.\n * - `requestMemo(key, fn)` for per-request memoized computation.\n * - Module augmentation of the `Request` class itself for new typed members.\n */\n\n /**\n * Locale code\n */\n protected _locale = \"\";\n\n /**\n * Validated data\n */\n protected validatedData?: RequestValidation;\n\n /**\n * Request id\n */\n public id = Random.string(32);\n\n /**\n * Trace id. The inbound `traceparent` header's trace id\n * when valid, otherwise `id`. Resolved once in `setRequest`, alongside\n * `id` itself — see `resolveTraceId`.\n */\n public traceId = \"\";\n\n /**\n * Start Time\n */\n public startTime = Date.now();\n\n /**\n * End Time\n */\n public endTime?: undefined | number;\n\n /**\n * Set request handler\n */\n public setRequest(request: FastifyRequest) {\n this.baseRequest = request;\n\n this.resolveRequestId();\n\n this.resolveTraceId();\n\n this.parsePayload();\n\n // Resolve the locale at CALL time, never at bind time. `setRequest` runs\n // before routing, so a locale set later (path locale, `setLocaleCode`, the\n // web layer's C3 derivation) must steer translations too — the old\n // `transFrom.bind(null, localeCode)` snapshot made `request.locale` and\n // `request.trans()` silently disagree for the rest of the request.\n this.trans = this.t = (keyword: string, placeholders?: any) =>\n transFrom(this.getLocaleCode(), keyword, placeholders);\n\n return this;\n }\n\n /**\n * Inherit `X-Request-Id` from the incoming request, fall back to a custom\n * generator, then to the field-init default (`Random.string(32)`).\n *\n * Inherited values are validated (length cap + printable-ASCII) to prevent\n * log-injection from a malicious client. Disable the whole behavior by\n * setting `http.requestId.enabled = false` — in which case the field-init\n * default is used regardless of any incoming header.\n */\n protected resolveRequestId() {\n const requestIdConfig = config.key(\"http.requestId\") || {};\n\n if (requestIdConfig.enabled === false) return;\n\n const headerName = (requestIdConfig.header || \"x-request-id\").toLowerCase();\n const incoming = this.baseRequest.headers[headerName];\n\n if (Request.isValidRequestId(incoming)) {\n this.id = incoming;\n\n return;\n }\n\n if (typeof requestIdConfig.generator === \"function\") {\n this.id = requestIdConfig.generator();\n }\n }\n\n /**\n * Derive `traceId`: the inbound\n * `traceparent` header's trace id when it is a valid W3C traceparent,\n * otherwise `id`. Always runs — unlike request-id inheritance this has no\n * `enabled: false` escape hatch, since `traceId` is only ever read when\n * tracing hooks are enabled (see `./tracing`).\n */\n protected resolveTraceId() {\n const header = this.baseRequest.headers.traceparent;\n const traceparent = Array.isArray(header) ? header[0] : header;\n\n this.traceId = deriveTraceId(traceparent, this.id);\n }\n\n /**\n * Validate a candidate request-id value. Accepts non-empty printable ASCII\n * up to 128 characters — tight enough to reject newline / control-character\n * log-injection, loose enough to accept UUIDs, ULIDs, snowflakes, etc.\n */\n protected static isValidRequestId(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= 128 &&\n /^[\\x21-\\x7e]+$/.test(value)\n );\n }\n\n /**\n * Translate from the given locale code\n */\n public transFrom(localeCode: string, keyword: string, placeholders?: any) {\n return transFrom(localeCode, keyword, placeholders);\n }\n\n /**\n * Cache one supported locale without coercing request-controlled input.\n *\n * The default is the answer for a client that asked for NOTHING. A client\n * that did ask is only overridden when its value fails a declared\n * `app.localeCodes` allow-list; with no list declared there is nothing to\n * fail, so the requested locale passes through unchanged.\n */\n protected cacheLocale(candidate: unknown): string {\n const { defaultLocaleCode, localeCodes } = resolveLocaleConfiguration(\n config.key(\"app.localeCode\"),\n config.key(\"app.localeCodes\"),\n );\n\n const requested = typeof candidate === \"string\" && candidate.length > 0 ? candidate : undefined;\n\n this._locale =\n requested !== undefined && (localeCodes === undefined || localeCodes.includes(requested))\n ? requested\n : defaultLocaleCode;\n\n return this._locale;\n }\n\n /**\n * Resolve the first present Mode B source. Unsupported values fail closed to\n * the configured default instead of widening the application's locale set.\n */\n protected resolveLocale(): string {\n const candidate = [\n this.query[\"locale\"],\n this.cookies[LOCALE_COOKIE_NAME],\n this.header(\"locale\"),\n ].find((value) => typeof value === \"string\" && value.length > 0);\n\n return this.cacheLocale(candidate);\n }\n\n /**\n * Get current locale code\n */\n public get locale(): string {\n if (this._locale) return this._locale;\n\n return this.resolveLocale();\n }\n\n /**\n * Set locale code\n */\n public set locale(localeCode: string) {\n this.cacheLocale(localeCode);\n }\n\n /**\n * Set locale code\n */\n public setLocaleCode(localeCode: string) {\n this.locale = localeCode;\n\n return this;\n }\n\n /**\n * @deprecated Use `request.locale`. This alias is removed after one version.\n * The legacy default argument is accepted for source compatibility but the\n * resolved default is owned exclusively by app configuration.\n */\n public getLocaleCode(_legacyDefaultLocaleCode?: string): string {\n return this.locale;\n }\n\n /**\n * Get http protocol\n */\n public get protocol() {\n return this.baseRequest.protocol;\n }\n\n /**\n * Validate the given validation schema\n */\n public async validate(validation: BaseValidator, selectedInputs?: string[]) {\n return await v.validate(validation, selectedInputs ? this.only(selectedInputs) : this.all());\n }\n\n /**\n * Get value of the given header\n */\n public header<TCustomHeader extends string = HeaderKeys>(\n name: TCustomHeader | HeaderKeys,\n defaultValue: any = null,\n ) {\n return this.baseRequest.headers[name.toLocaleLowerCase()] ?? defaultValue;\n }\n\n /**\n * Get all cookies from the current request\n */\n public get cookies(): Record<string, string | undefined> {\n return this.baseRequest.cookies || {};\n }\n\n /**\n * Assert the cookie jar exists before a by-name read. `get cookies()` stays\n * lenient (returns `{}`) for the framework's own opportunistic reads, but a\n * deliberate by-name read from application code must fail loudly when\n * `@fastify/cookie` was never registered, rather than being indistinguishable\n * from \"the caller sent no such cookie\".\n */\n private assertCookieJarAvailable(name: string): void {\n if (this.baseRequest.cookies === undefined) {\n throw new CookieJarUnavailableError(name);\n }\n }\n\n /**\n * Get a particular cookie value or fallback to default\n */\n public cookie(name: string, defaultValue?: any): string | any {\n this.assertCookieJarAvailable(name);\n\n const value = this.cookies[name] ?? defaultValue;\n\n try {\n return JSON.parse(value);\n } catch (error) {\n return value;\n }\n }\n\n /**\n * Determine if the request has the specified cookie\n */\n public hasCookie(name: string): boolean {\n this.assertCookieJarAvailable(name);\n\n return this.cookies[name] !== undefined;\n }\n\n /**\n * Get the current request domain\n */\n public get domain() {\n return this.baseRequest.hostname.replace(/^www\\./, \"\");\n }\n\n /**\n * Get hostname\n */\n public get hostname() {\n return this.domain;\n }\n\n /**\n * Get request origin\n */\n public get origin() {\n return this.baseRequest.headers.origin as string;\n }\n\n /**\n * Get the domain of the origin\n */\n public get originDomain() {\n const domain = this.origin ? new URL(this.origin).hostname : null;\n\n if (domain?.startsWith(\"www.\")) {\n return domain.replace(/^www\\./, \"\");\n }\n\n return domain;\n }\n\n /**\n * Get authorization header value\n */\n public get authorizationValue(): string {\n const authorization = this.header(\"authorization\");\n\n if (!authorization) return \"\";\n\n const [type, value] = authorization.split(\" \");\n\n if (![\"bearer\", \"key\"].includes(type.toLowerCase())) return \"\";\n\n return value || \"\";\n }\n\n /**\n * Get access token from Authorization header\n *\n * If the Authorization header does not start with `Bearer` value then return null\n */\n public get accessToken(): string | undefined {\n const authorization = this.header(\"authorization\");\n\n if (!authorization) return;\n\n const [type, value] = authorization.split(\" \");\n\n if (type.toLowerCase() !== \"bearer\") return;\n\n return value;\n }\n\n /**\n * Get the authorization header\n */\n public get authorization() {\n return this.header(\"authorization\");\n }\n\n /**\n * Get current request method\n */\n public get method(): string {\n return this.baseRequest.method;\n }\n\n /**\n * Parse the payload and merge it from the request body, params and query string\n */\n /**\n * Turn a bracket-notation key into the dotted path `set()` expects.\n *\n * `a[b][c]` -> `a.b.c`. Used only for NON-numeric nesting; numeric indices\n * keep the array-of-objects path in {@link parseBody}, which builds real\n * arrays rather than objects with numeric keys.\n */\n protected bracketKeyToPath(key: string): string {\n return key.replace(/\\]\\[/g, \".\").replace(/\\[/g, \".\").replace(/\\]/g, \"\");\n }\n\n /**\n * Apply the `key[]` array marker to a parsed value.\n *\n * The subtlety this exists to remove: a key declared `[]` should ALWAYS be an\n * array, but the underlying query/body parser only hands us one when the\n * caller sent the key more than once. Deciding the TYPE from the number of\n * occurrences means one selected filter is a string and two are an array —\n * a shape that changes under the user's hands.\n */\n protected arrayValueFor(value: any, isArrayKey: boolean, parse: (value: any) => any) {\n if (Array.isArray(value)) return value.map(parse);\n\n return isArrayKey ? [parse(value)] : parse(value);\n }\n\n protected parsePayload() {\n this.payload.body = this.parseBody(this.baseRequest.body);\n\n this.payload.query = this.parseBody(this.baseRequest.query);\n this.payload.params = { ...(this.baseRequest.params || {}) };\n this.payload.all = {\n ...this.payload.body,\n ...this.payload.query,\n ...this.payload.params,\n };\n }\n\n /**\n * Parse body payload\n */\n protected parseBody(data: any) {\n try {\n if (!data) return {};\n\n const body: any = {};\n\n const arrayOfObjectValues: any = {};\n\n for (let key in data) {\n const value = data[key];\n\n let isArrayKey = false;\n\n if (key.endsWith(\"[]\")) {\n isArrayKey = true;\n }\n\n key = rtrim(key, \"[]\");\n\n // check if the key is has a square brackets, then convert it into object\n // i.e user[email] => user: {email: \"value\"}\n // also check if its an array of objects\n\n if (key.includes(\"[\")) {\n // check if its an array of objects\n if (key.includes(\"][\")) {\n const keyParts = key.split(\"[\");\n\n const keyName = keyParts[0];\n const firstBracket = keyParts[1];\n const secondBracket = keyParts[2];\n\n /*\n `key.includes(\"][\")` guarantees all three segments — but that is a\n property of the string test above, not of these reads, so each is\n `string | undefined`.\n\n When the shape is not what this branch assumes, fall through to\n the generic bracket path rather than skipping the key. That is the\n same choice the NaN branch below makes, and for the same reason\n spelled out there: the failure this code has already been bitten\n by is answering with a shape the caller did not send. Dropping the\n pair silently would be that bug again, in a new place.\n */\n if (\n keyName === undefined ||\n firstBracket === undefined ||\n secondBracket === undefined\n ) {\n set(\n body,\n this.bracketKeyToPath(key),\n this.arrayValueFor(value, isArrayKey, this.parseValue.bind(this)),\n );\n\n continue;\n }\n\n const keyNameParts = firstBracket.split(\"]\");\n\n const index = Number(keyNameParts[0]);\n\n /*\n A NON-NUMERIC first segment is not an array index — it is a deeper\n nested object. `a[b][c]=x` reaches this branch because it contains\n \"][\", but `Number(\"b\")` is NaN, and the code below used to write to\n `[NaN]`: that sets a \"NaN\" PROPERTY on an array whose length stays\n 0, so the request arrived as `{a: []}` and the value was gone. No\n error, no warning — the caller simply never got `x`.\n\n Deciding between refusing (4xx) and interpreting: a doubly-nested\n key is unambiguous and is exactly what every bracket-notation\n parser means by it, so we interpret. Refusing would reject a URL\n shape that is standard elsewhere and that we ourselves already\n honour one level shallower, five lines below. What was definitely\n wrong was answering with a shape the caller did not send.\n\n Numeric indices keep the array-of-objects path below unchanged —\n `items[0][name]` is still an array.\n */\n if (Number.isNaN(index)) {\n set(\n body,\n this.bracketKeyToPath(key),\n this.arrayValueFor(value, isArrayKey, this.parseValue.bind(this)),\n );\n\n continue;\n }\n\n const bucket = (arrayOfObjectValues[keyName] ??= []);\n\n const entry = (bucket[index] ??= {});\n\n // now get the key after the index\n const keyNameParts2 = secondBracket.split(\"]\");\n const keyName2 = keyNameParts2[0];\n\n // `split` always yields a first element, so this holds — but an\n // undefined key here would write a property literally named\n // \"undefined\" onto the entry, which is the same silent-wrong-shape\n // outcome the comment above describes.\n if (keyName2 === undefined) continue;\n\n entry[keyName2] = this.parseValue(value);\n\n continue;\n }\n\n const keyParts = key.split(\"[\");\n const keyName = keyParts[0];\n // `key.includes(\"[\")` puts at least two segments here. Falling back\n // to the whole key rather than asserting keeps the parse total: an\n // undefined segment would make `keyNameParts[0]` undefined too, and\n // this branch writes that straight into the body shape.\n const keyNameParts = (keyParts[1] ?? key).split(\"]\");\n\n /*\n `isArrayKey` is honoured HERE, and used not to be. `filter[tags][]=a`\n sets the flag at the top of the loop, but this branch only wrapped\n when the underlying value was ALREADY an array — which it is for two\n or more occurrences and is not for one. So `filter[tags][]=a` arrived\n as `{filter:{tags:\"a\"}}` while `…=a&…=b` arrived as `{tags:[\"a\",\"b\"]}`:\n the same declared shape, two different types, decided by how many\n times the caller happened to send it.\n\n That single-element case is the one a UI hits first — one filter\n chip selected — and `@warlock.js/web`'s decoder reads it as an array,\n so the page and the server disagreed about the same URL.\n */\n set(\n body,\n keyName + \".\" + keyNameParts[0],\n this.arrayValueFor(value, isArrayKey, this.parseValue.bind(this)),\n );\n\n continue;\n }\n\n if (Array.isArray(value)) {\n set(body, key, value.map(this.parseValue.bind(this)));\n } else if (isArrayKey) {\n if (body[key]) {\n body[key].push(this.parseValue(value));\n } else {\n body[key] = [this.parseValue(value)];\n\n continue;\n }\n } else {\n set(body, key, this.parseValue(value));\n }\n }\n\n // now merge the array of objects into the body\n for (const key in arrayOfObjectValues) {\n body[key] = arrayOfObjectValues[key];\n }\n\n return body;\n } catch (error) {\n console.log(error);\n this.log(error, \"error\");\n }\n }\n\n /**\n * Parse the given data\n */\n protected parseValue(data: any) {\n // data.value appears only in the multipart form data\n // if it json, then just return the data\n if (data?.file) return new UploadedFile(data);\n if (data?.value !== undefined && data?.fields && data?.type) {\n data = data.value;\n }\n\n if (data === \"false\") return false;\n\n if (data === \"true\") return true;\n\n if (data === \"null\") return null;\n\n if (typeof data === \"string\") return data.trim();\n\n return data;\n }\n\n /**\n * Set route handler\n */\n public setRoute(route: Route) {\n this.route = route;\n\n // pass the route to the response object\n this.response.setRoute(route);\n\n return this;\n }\n\n /**\n * Trigger an http event\n */\n public trigger(eventName: RequestEvent, ...args: any[]) {\n return events.trigger(`request.${eventName}`, ...args, this);\n }\n\n /**\n * Listen to the given event\n */\n public on(eventName: RequestEvent, callback: any) {\n return events.subscribe(`request.${eventName}`, callback);\n }\n\n /**\n * Make a log message\n */\n public log(message: any, level: LogLevel = \"info\") {\n if (!config.key(\"http.log\")) return;\n\n log.log({\n module: \"request\",\n action: this.route.method + \" \" + this.route.path.replace(\"/*\", \"\") + `:${this.id}`,\n message,\n type: level,\n context: {\n request: this,\n },\n });\n }\n\n /**\n * Get current request path\n */\n public get path() {\n return this.baseRequest.url;\n }\n\n /**\n * {@alias}\n */\n public get url() {\n return this.baseRequest.url;\n }\n\n /**\n * Get full url\n */\n public get fullUrl() {\n return this.protocol + \"://\" + this.hostname + this.path;\n }\n\n /**\n * Drive the middleware chain for the current route, then defer to the\n * controller. Returns the first response value any middleware short-circuits\n * with, or `undefined` to continue into validation + handler.\n *\n * @internal Framework orchestration — do not call from app code. Will move\n * to a dedicated controller dispatcher in a future refactor.\n */\n public async runMiddleware() {\n // measure request time\n // check for middleware first\n const middlewareOutput = await this.executeMiddleware();\n\n if (middlewareOutput !== undefined) {\n // 👇🏻 make sure first its not a response instance\n if (middlewareOutput instanceof Response) return middlewareOutput;\n // 👇🏻 send the response\n return this.response.send(middlewareOutput);\n }\n\n const handler = this.route.handler;\n\n if (!handler.validation) return;\n\n // 👇🏻 check for validation using validateAll helper function — timed as\n // the \"validation\" tracing phase when tracing is\n // enabled; a single boolean check and zero allocation otherwise.\n const tracingEnabled = isTracingEnabled();\n const validationStartedAt = tracingEnabled ? performance.now() : 0;\n\n const validationOutput = await validateAll(handler.validation, this, this.response);\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(this), {\n name: \"validation\",\n durationMs: performance.now() - validationStartedAt,\n });\n }\n\n return validationOutput;\n }\n\n /**\n * Return the request handler attached to the current route.\n *\n * @internal Framework orchestration — do not call from app code.\n */\n public getHandler() {\n return this.route.handler;\n }\n\n /**\n * Get inputs that has been validated only\n * You can also pass an array of inputs to get only the validated inputs\n */\n public validated<Output = RequestValidation>(inputs?: (keyof Output | (string & {}))[]): Output {\n if (this.validatedData) {\n return inputs\n ? only(this.validatedData as Output, inputs as string[])\n : (this.validatedData as Output);\n }\n\n return {} as Output;\n }\n\n /**\n * Get inputs that has been validated except the given inputs\n */\n public validatedExcept(...inputs: string[]): RequestValidation {\n return except(this.validated(), inputs);\n }\n\n /**\n * Set validated data\n */\n public setValidatedData(data: RequestValidation) {\n this.validatedData = data;\n }\n\n /**\n * Top-level entry into the request lifecycle — opens the context store,\n * runs middleware, drives the handler, handles errors.\n *\n * @internal Framework orchestration — do not call from app code. Wired\n * from the Fastify route handler in `router.scan()`.\n */\n public async execute() {\n try {\n // call executingAction event\n\n this.log(\"Executing the request\");\n\n return await createRequestStore(this, this.response);\n } catch (error) {\n this.log(error, \"error\");\n\n throw error;\n }\n }\n\n /**\n * Iterate the collected middlewares in order; return the first short-circuit\n * value or `undefined` when every middleware passes through.\n *\n * @internal Framework orchestration — do not call from app code.\n */\n protected async executeMiddleware() {\n // collect all middlewares for current route\n const middlewares = this.collectMiddlewares();\n\n // check if there are no middlewares, then return\n if (middlewares.length === 0) return;\n\n this.log(\"About to execute request middlewares\");\n\n // trigger the executingMiddleware event\n this.trigger(\"executingMiddleware\", middlewares, this.route);\n\n const tracingEnabled = isTracingEnabled();\n\n for (const [index, middleware] of middlewares.entries()) {\n this.log(\"Executing middleware \" + colors.yellowBright(middleware.name));\n\n const middlewareStartedAt = tracingEnabled ? performance.now() : 0;\n\n const output = await middleware({\n request: this,\n response: this.response,\n });\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(this), {\n name: \"middleware\",\n durationMs: performance.now() - middlewareStartedAt,\n attrs: { name: middleware.name, index },\n });\n }\n\n this.log(\"Executed middleware \" + colors.yellowBright(middleware.name), \"success\");\n\n if (output !== undefined) {\n this.log(\n colors.yellow(\"request intercepted by middleware \") + colors.cyanBright(middleware.name),\n \"warn\",\n );\n\n this.trigger(\"executedMiddleware\");\n\n this.log(\"Request middlewares executed\", \"success\");\n\n return output;\n }\n }\n\n this.log(\"Request middlewares executed\", \"success\");\n\n // trigger the executedMiddleware event\n this.trigger(\"executedMiddleware\", middlewares, this.route);\n }\n\n /**\n * Gather the middleware list for the current route — today just the\n * route-level array; future extraction may merge group + app-wide layers.\n *\n * @internal Framework orchestration — do not call from app code.\n */\n protected collectMiddlewares(): Middleware[] {\n const middlewaresList: Middleware[] = [];\n\n // collect route middlewares\n if (this.route.middleware) {\n middlewaresList.push(...this.route.middleware);\n }\n\n return middlewaresList;\n }\n\n /**\n * Get request input value from query string, params or body\n */\n public input(key: string, defaultValue?: any) {\n return get(this.payload.all, key, defaultValue);\n }\n\n /**\n * Get email input value, this will lowercase the value\n */\n public email(key: string = \"email\", defaultValue: string = \"\"): string {\n return this.input(key, defaultValue)?.toLowerCase() || defaultValue;\n }\n\n /**\n * @alias input\n */\n public get(key: string, defaultValue?: any) {\n return this.input(key, defaultValue);\n }\n\n /**\n * Determine if request has input value\n */\n public has(key: string) {\n return get(this.payload.all, key, undefined) !== undefined;\n }\n\n /**\n * Set request input value\n */\n public set(key: string, value: any) {\n set(this.payload.all, key, value);\n\n return this;\n }\n\n /**\n * Set the given value if the request does not have the input\n */\n public setDefault(key: string, value: any) {\n if (this.has(key)) return this;\n\n set(this.payload.all, key, value);\n\n return this;\n }\n\n /**\n * Unset request payload keys\n */\n public unset(...keys: string[]) {\n this.payload.all = unset(this.payload.all, keys);\n\n return this;\n }\n\n /**\n * Get request body\n */\n public get body() {\n return this.payload.body;\n }\n\n /**\n * Set request body value\n */\n public setBody(key: string, value: any) {\n set(this.payload.body, key, value);\n\n return this;\n }\n\n /**\n * Get body inputs except files\n */\n public get bodyInputs() {\n const inputs = this.payload.body;\n\n const bodyInputs: any = {};\n\n for (const key in inputs) {\n const value = inputs[key];\n\n if (value.file && value.fieldname) continue;\n\n bodyInputs[key] = value;\n }\n\n return bodyInputs;\n }\n\n /**\n * Get request file in UploadedFile instance\n */\n public file(key: string): UploadedFile | undefined {\n const file = this.input(key);\n\n return file;\n }\n\n /**\n * Get uploaded files from the request for the given name\n * If the given name is not present in the request, return an empty array\n */\n public files(name: string): UploadedFile[] {\n return this.input(name) || [];\n }\n\n /**\n * Get request params\n */\n public get params() {\n return this.payload.params;\n }\n\n /**\n * Set request params value\n */\n public setParam(key: string, value: any) {\n set(this.payload.params, key, value);\n\n return this;\n }\n\n /**\n * Get request query\n */\n public get query() {\n return this.payload.query;\n }\n\n /**\n * Set request query value\n */\n public setQuery(key: string, value: any) {\n set(this.payload.query, key, value);\n\n return this;\n }\n\n /**\n * Get all inputs\n */\n public all() {\n return this.payload.all;\n }\n\n /**\n * Get all inputs except params\n */\n public allExceptParams() {\n return {\n ...this.payload.query,\n ...this.payload.body,\n };\n }\n\n /**\n * Get all heavy inputs except params\n */\n public heavyExceptParams() {\n const inputs = this.allExceptParams();\n\n const heavyInputs: any = {};\n\n for (const key in inputs) {\n const value = inputs[key];\n\n if (isEmpty(value) && value !== null) continue;\n\n heavyInputs[key] = value;\n }\n\n return heavyInputs;\n }\n\n /**\n * Get only heavy inputs, the input with a value\n */\n public heavy() {\n const inputs = this.all();\n\n const heavyInputs: any = {};\n\n for (const key in inputs) {\n const value = inputs[key];\n\n if (isEmpty(value) && value !== null) continue;\n\n heavyInputs[key] = value;\n }\n\n return heavyInputs;\n }\n\n /**\n * Get only the given keys from the request data\n */\n public only(keys: string[]) {\n return only(this.all(), keys);\n }\n\n /**\n * Pluck the given keys from the request data\n */\n public pluck(keys: string[]) {\n const data = this.only(keys);\n\n this.unset(...keys);\n\n return data;\n }\n\n /**\n * Get all request inputs except the given keys\n */\n public except(keys: string[]) {\n return except(this.all(), keys);\n }\n\n /**\n * Get boolean input value\n */\n public bool(key: string, defaultValue = false) {\n const value = this.input(key, defaultValue);\n\n if (value === \"true\") {\n return true;\n }\n\n if (value === \"false\") {\n return false;\n }\n\n if (value === 0) {\n return false;\n }\n\n return Boolean(value);\n }\n\n /**\n * Get integer input value\n */\n public int(key: string, defaultValue: number = 0): number | undefined {\n const value = this.input(key, defaultValue);\n\n if (!value && value !== 0) return undefined;\n\n return parseInt(value);\n }\n\n /**\n * Shorthand getter to get id param\n */\n public get idParam() {\n return this.int(\"id\");\n }\n\n /**\n * Get string input value\n */\n public string(key: string, defaultValue: string = \"\"): string {\n const value = this.input(key, defaultValue);\n\n return String(value);\n }\n\n /**\n * Get float input value\n */\n public float(key: string, defaultValue: number = 0): number {\n const value = this.input(key, defaultValue);\n\n return parseFloat(value) || 0;\n }\n\n /**\n * Get number input value\n */\n public number(key: string, defaultValue: number = 0): number {\n const value = Number(this.input(key, defaultValue));\n\n return isNaN(value) ? defaultValue : value;\n }\n\n /**\n * Immediate-peer IP as Fastify reports it — the address that connected to\n * the server socket, with `trustProxy` resolution applied. Use this when\n * you specifically need the peer address (rate-limit-by-direct-connection,\n * health-check origin verification).\n *\n * **For most use cases prefer `request.detectIp()`** — behind any proxy\n * (load balancer, CDN, sidecar) `ip` reports the proxy, not the real client.\n */\n public get ip() {\n return this.baseRequest.ip;\n }\n\n /**\n * Best-effort real client IP — the value everything IP-scoped keys on\n * (ip-filter allowlists, rate-limit buckets, idempotency scoping).\n *\n * `X-Forwarded-For` resolution is **delegated to Fastify**: `baseRequest.ip`\n * is already the client address Fastify's `trustProxy` machinery picked out\n * of the chain, so every shape `http.trustProxy` accepts is honoured here\n * with exactly the semantics Fastify documents:\n *\n * - `false` (default) — no header is trusted; the socket peer address wins.\n * Both forwarding headers are client-settable, so without a trusted edge\n * that rewrites them any client could otherwise forge its own IP.\n * - `true` — the whole chain is trusted; the leftmost hop (original client)\n * wins.\n * - `number` — that many rightmost hops are trusted, so an edge that\n * APPENDS to `X-Forwarded-For` yields the real client rather than whatever\n * the client prepended.\n * - CIDR / IP list (string, comma-separated string, or array) or a custom\n * predicate — the chain is walked right-to-left and stops at the first hop\n * that isn't a trusted proxy.\n *\n * `X-Real-IP` is NOT part of that resolution — Fastify never looks at it,\n * and unlike `X-Forwarded-For` it carries no chain, so there is nothing to\n * validate a proxy allowlist against. It is therefore honoured\n * only under `trustProxy: true` (\"everything upstream is mine\"), where it is\n * no weaker than the trust already granted. Under a bounded `trustProxy`\n * (CIDR / IP list) it is ignored: a trusted-but-passthrough edge that\n * forwards the client's own `X-Real-IP` verbatim would otherwise hand any\n * client a way around the bound.\n *\n * **Prefer this over `request.ip` for any caller behind a proxy** (load\n * balancer, CDN, reverse proxy, k8s ingress).\n */\n public detectIp() {\n // Trusting `X-Real-IP` is only sound when the config trusts the entire\n // upstream chain; bounded shapes get chain-aware resolution instead.\n // Typed as `unknown`: config.get(key, fallback) infers the FALLBACK's type, so\n // the literal `false` narrowed this to `false` and TypeScript called the\n // comparison unreachable. The stored value is genuinely unconstrained at compile\n // time - trustProxy accepts a boolean, a CIDR list or a predicate - so `unknown`\n // is what it actually is, and the === true check is the narrowing.\n const trustProxy: unknown = config.get(\"http.trustProxy\", false);\n\n if (trustProxy === true) {\n const realIp = this.header(\"x-real-ip\");\n\n if (realIp) {\n // `split` always yields a first element, so `?? \"\"` changes nothing —\n // and an empty address is already falsy, so it falls through to the\n // next source exactly as a blank header does. This is the CLIENT IP\n // used for rate limiting and logging; it must never become the string\n // \"undefined\".\n const address = (String(realIp).split(\",\")[0] ?? \"\").trim();\n\n if (address) return address;\n }\n }\n\n // Fastify resolved this against the configured `trustProxy` already:\n // socket peer when trust is off, the correct hop of `X-Forwarded-For`\n // when it is on. Re-parsing the header here would mean a second, weaker\n // trust model that could disagree with `request.ip` and with the plugins\n // (rate limit, proxy) that key on it.\n return this.baseRequest.ip;\n }\n\n /**\n * An alias to detectIp\n */\n public get realIp() {\n return this.detectIp();\n }\n\n /**\n * Get request ips\n */\n public get ips() {\n return this.baseRequest.ips;\n }\n\n /**\n * Get request referer\n */\n public get referer() {\n return this.baseRequest.headers.referer;\n }\n\n /**\n * Get user agent\n */\n public get userAgent() {\n return this.baseRequest.headers[\"user-agent\"];\n }\n\n /**\n * Get request headers\n */\n public get headers(): typeof this.baseRequest.headers {\n return this.baseRequest.headers;\n }\n\n /**\n * Set the given header\n */\n public setHeader(key: HeaderKeys, value: string) {\n this.baseRequest.headers[key.toLowerCase()] = value;\n\n return this;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;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AC1D,MAAM,QAAQ,KAAK,MAAM,KAAK,YAAY;EAE1C,OAAO,WAAW,KAAK,KAAK;CAC9B;;;;CAKA,AAAO,OAAO,KAAa,eAAuB,GAAW;EAC3D,MAAM,QAAQ,OAAO,KAAK,MAAM,KAAK,YAAY,CAAC;EAElD,OAAO,MAAM,KAAK,IAAI,eAAe;CACvC;;;;;;;;;;CAWA,IAAW,KAAK;EACd,OAAO,KAAK,YAAY;CAC1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCA,AAAO,WAAW;EAUhB,IAF4B,OAAO,IAAI,mBAAmB,KAE7C,MAAM,MAAM;GACvB,MAAM,SAAS,KAAK,OAAO,WAAW;GAEtC,IAAI,QAAQ;IAMV,MAAM,WAAW,OAAO,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,GAAE,CAAE,KAAK;IAE1D,IAAI,SAAS,OAAO;GACtB;EACF;EAOA,OAAO,KAAK,YAAY;CAC1B;;;;CAKA,IAAW,SAAS;EAClB,OAAO,KAAK,SAAS;CACvB;;;;CAKA,IAAW,MAAM;EACf,OAAO,KAAK,YAAY;CAC1B;;;;CAKA,IAAW,UAAU;EACnB,OAAO,KAAK,YAAY,QAAQ;CAClC;;;;CAKA,IAAW,YAAY;EACrB,OAAO,KAAK,YAAY,QAAQ;CAClC;;;;CAKA,IAAW,UAA2C;EACpD,OAAO,KAAK,YAAY;CAC1B;;;;CAKA,AAAO,UAAU,KAAiB,OAAe;EAC/C,KAAK,YAAY,QAAQ,IAAI,YAAY,KAAK;EAE9C,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"request.mjs","names":[],"sources":["../../../../../../../core/src/http/request.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport events from \"@mongez/events\";\nimport { trans, transFrom } from \"@mongez/localization\";\nimport { Random, except, get, only, rtrim, set, unset } from \"@mongez/reinforcements\";\nimport { isEmpty } from \"@mongez/supportive-is\";\nimport type { LogLevel } from \"@warlock.js/logger\";\nimport { log } from \"@warlock.js/logger\";\nimport { BaseValidator, v } from \"@warlock.js/seal\";\nimport type { FastifyRequest } from \"fastify\";\nimport { randomBytes } from \"node:crypto\";\nimport { type IncomingHttpHeaders } from \"node:http2\";\nimport { Application } from \"../application/application\";\nimport { config } from \"../config/config-getter\";\nimport {\n LOCALE_COOKIE_NAME,\n LOCALE_PREFERENCE_COOKIE_NAME,\n resolveLocaleConfiguration,\n} from \"../config/locale-configuration\";\nimport type { Middleware, Route } from \"../router\";\nimport { validateAll } from \"../validation/validateAll\";\nimport { CookieJarUnavailableError, RequestUserMovedError } from \"./errors\";\nimport { createRequestStore } from \"./middleware/inject-request-context\";\nimport { Response } from \"./response\";\nimport { buildTracingContext, deriveTraceId, dispatchPhase, isTracingEnabled } from \"./tracing\";\nimport type { DecodedAccessToken, RequestEvent, RequestLocals } from \"./types\";\nimport { UploadedFile } from \"./uploaded-file\";\n\ntype StandardHeaders = {\n // copy every declared property from http.IncomingHttpHeaders\n // but remove index signatures\n [\n K in keyof IncomingHttpHeaders as string extends K ? never : number extends K ? never : K\n ]: IncomingHttpHeaders[K];\n};\n\ntype HeaderKeys = keyof StandardHeaders;\n\nexport class Request<RequestValidation = any> {\n /**\n * Underlying Fastify request — a public escape hatch to capabilities the\n * framework's high-level helpers don't yet cover.\n *\n * **Prefer framework methods first**: `request.input()`, `request.header()`,\n * `request.body`, `request.query`, `request.params`, `request.file()`,\n * `request.locals.user` (set by `@warlock.js/auth`), `request.detectIp()`,\n * etc. They handle locale, parsing,\n * trust-proxy, and validation pipeline integration correctly.\n *\n * **Reach for `baseRequest` only** when the framework genuinely lacks a\n * helper for what you need — and when you do, file an issue so we can add\n * it. The escape hatch is the release valve that lets consumers move\n * faster than the framework, but every long-term reach here is a missing\n * helper waiting to be added.\n */\n public baseRequest!: FastifyRequest;\n\n /**\n * Response Object\n */\n public response!: Response;\n\n /**\n * Route Object\n */\n public route!: Route;\n\n /**\n * Parsed Request Payload\n */\n protected payload: any = {};\n\n /**\n * Backing field for `decodedAccessToken` — see the accessor below.\n */\n private _decodedAccessToken?: DecodedAccessToken;\n\n /**\n * Decoded access token payload (set by auth middleware).\n *\n * A prototype accessor, not a plain field, so assignment can mark the\n * request `authDerived` (see the setter below and `RequestLocals` in\n * `types.ts`) without every call site remembering to do so itself.\n */\n public get decodedAccessToken(): DecodedAccessToken | undefined {\n return this._decodedAccessToken;\n }\n\n public set decodedAccessToken(value: DecodedAccessToken | undefined) {\n this._decodedAccessToken = value;\n this.locals.authDerived = true;\n }\n\n /**\n * REMOVED in 5.12.0 — the authenticated user now lives at\n * `request.locals.user`, a key `@warlock.js/auth` declares via module\n * augmentation on `RequestLocals` and writes from its middleware after a\n * successful token resolution. `RequestUser` moved out of core to\n * `@warlock.js/auth` alongside it.\n *\n * This getter is a development-time diagnostic only, kept for one release\n * so a call site that still reads `request.user` fails loudly at runtime\n * instead of silently reading `undefined`. It is typed `never` so it\n * cannot reintroduce an auth-shaped type into core, and it throws\n * unconditionally outside production so the failure is impossible to miss\n * in local dev — see `RequestUserMovedError`.\n *\n * There is no setter: nothing in core or downstream packages should ever\n * assign to `request.user` again.\n */\n public get user(): never {\n if (Application.isDevelopment) {\n throw new RequestUserMovedError();\n }\n\n return undefined as never;\n }\n\n /**\n * Private, server-only, per-request data bag.\n *\n * Distinct from the input payload (`body` / `query` / `params` / `all()`):\n * a write here never surfaces in `request.all()`, `request.validated()`, or\n * `request.input()`. That is the trap `request.set()` sets for private data\n * — it writes into the payload `all` bag, so anything stored there leaks\n * into every input accessor and, from there, into the client-facing\n * payload. `locals` is the correct home for private per-request app data\n * (a resolved session, a fetched-once model) that must never be mistaken\n * for client input.\n *\n * Augmentable via module augmentation, in the module that OWNS the key:\n *\n * ```typescript\n * declare module \"@warlock.js/core\" {\n * interface RequestLocals {\n * session?: { token: string };\n * }\n * }\n * ```\n *\n * A plain class-field initializer is sufficient for \"fresh per request\":\n * `router.ts:925` constructs `new Request()` for every incoming request —\n * `Request` instances are not pooled or reused across requests — so this\n * initializer runs exactly once per request and no value can leak in from\n * a prior one.\n */\n public locals: RequestLocals = {};\n\n /**\n * Backing field for the lazily-generated CSP nonce. Left `undefined` until\n * the first `request.nonce` read; see the `nonce` getter below.\n */\n protected _nonce?: string;\n\n /**\n * Per-request Content-Security-Policy nonce — a fresh, unguessable value\n * the web layer hands to `<Scripts nonce={...} />` (the inline payload\n * script) and to the `Content-Security-Policy` header, so a strict\n * `script-src 'nonce-...'` allows only the script this request actually\n * rendered.\n *\n * Generated LAZILY on first access, not eagerly in `setRequest()`: most\n * requests (API routes, anything that isn't rendering HTML) never read it,\n * and spending a `randomBytes` call on every single request for a value\n * most of them discard is wasted entropy draw + CPU. Once generated it is\n * cached in `_nonce`, so every subsequent read within the SAME request\n * returns the identical value — required, since the header and the inline\n * `<script>` tag must agree on one nonce. `_nonce` is a plain field on a\n * per-request `Request` instance (see `locals` above — `router.ts:925`,\n * no pooling), so the cache can never leak into the next request; a fresh\n * `Request` means a fresh, unset `_nonce`.\n *\n * 16 random bytes, base64-encoded — the size the CSP Level 3 spec's own\n * examples use, and far more entropy than an attacker could feasibly guess\n * to defeat the policy.\n */\n public get nonce(): string {\n if (!this._nonce) {\n this._nonce = randomBytes(16).toString(\"base64\");\n }\n\n return this._nonce;\n }\n\n /**\n * Current request instance\n */\n public static current: Request;\n\n /**\n * Translation method\n * Type of it is the same as the type of trans function\n */\n public trans: ReturnType<typeof trans> = trans;\n\n /**\n * Alias to trans method\n */\n public t: ReturnType<typeof trans> = trans;\n\n /*\n * v5 removed the `[key: string]: any` index signature (eed20184). Attaching\n * arbitrary properties compiled silently and hid real bugs behind `any`.\n * The sanctioned extension paths are:\n * - `request.locals` (augment `RequestLocals` via module augmentation) for\n * per-request attached data, e.g. models fetched in validation middleware.\n * - `requestMemo(key, fn)` for per-request memoized computation.\n * - Module augmentation of the `Request` class itself for new typed members.\n */\n\n /**\n * Locale code\n */\n protected _locale = \"\";\n\n /**\n * Validated data\n */\n protected validatedData?: RequestValidation;\n\n /**\n * Request id\n */\n public id = Random.string(32);\n\n /**\n * Trace id. The inbound `traceparent` header's trace id\n * when valid, otherwise `id`. Resolved once in `setRequest`, alongside\n * `id` itself — see `resolveTraceId`.\n */\n public traceId = \"\";\n\n /**\n * Start Time\n */\n public startTime = Date.now();\n\n /**\n * End Time\n */\n public endTime?: undefined | number;\n\n /**\n * Set request handler\n */\n public setRequest(request: FastifyRequest) {\n this.baseRequest = request;\n\n this.resolveRequestId();\n\n this.resolveTraceId();\n\n this.parsePayload();\n\n // Resolve the locale at CALL time, never at bind time. `setRequest` runs\n // before routing, so a locale set later (path locale, `setLocaleCode`, the\n // web layer's C3 derivation) must steer translations too — the old\n // `transFrom.bind(null, localeCode)` snapshot made `request.locale` and\n // `request.trans()` silently disagree for the rest of the request.\n this.trans = this.t = (keyword: string, placeholders?: any) =>\n transFrom(this.getLocaleCode(), keyword, placeholders);\n\n return this;\n }\n\n /**\n * Inherit `X-Request-Id` from the incoming request, fall back to a custom\n * generator, then to the field-init default (`Random.string(32)`).\n *\n * Inherited values are validated (length cap + printable-ASCII) to prevent\n * log-injection from a malicious client. Disable the whole behavior by\n * setting `http.requestId.enabled = false` — in which case the field-init\n * default is used regardless of any incoming header.\n */\n protected resolveRequestId() {\n const requestIdConfig = config.key(\"http.requestId\") || {};\n\n if (requestIdConfig.enabled === false) return;\n\n const headerName = (requestIdConfig.header || \"x-request-id\").toLowerCase();\n const incoming = this.baseRequest.headers[headerName];\n\n if (Request.isValidRequestId(incoming)) {\n this.id = incoming;\n\n return;\n }\n\n if (typeof requestIdConfig.generator === \"function\") {\n this.id = requestIdConfig.generator();\n }\n }\n\n /**\n * Derive `traceId`: the inbound\n * `traceparent` header's trace id when it is a valid W3C traceparent,\n * otherwise `id`. Always runs — unlike request-id inheritance this has no\n * `enabled: false` escape hatch, since `traceId` is only ever read when\n * tracing hooks are enabled (see `./tracing`).\n */\n protected resolveTraceId() {\n const header = this.baseRequest.headers.traceparent;\n const traceparent = Array.isArray(header) ? header[0] : header;\n\n this.traceId = deriveTraceId(traceparent, this.id);\n }\n\n /**\n * Validate a candidate request-id value. Accepts non-empty printable ASCII\n * up to 128 characters — tight enough to reject newline / control-character\n * log-injection, loose enough to accept UUIDs, ULIDs, snowflakes, etc.\n */\n protected static isValidRequestId(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= 128 &&\n /^[\\x21-\\x7e]+$/.test(value)\n );\n }\n\n /**\n * Translate from the given locale code\n */\n public transFrom(localeCode: string, keyword: string, placeholders?: any) {\n return transFrom(localeCode, keyword, placeholders);\n }\n\n /**\n * Cache one supported locale without coercing request-controlled input.\n *\n * The default is the answer for a client that asked for NOTHING. A client\n * that did ask is only overridden when its value fails a declared\n * `app.localeCodes` allow-list; with no list declared there is nothing to\n * fail, so the requested locale passes through unchanged.\n */\n protected cacheLocale(candidate: unknown): string {\n const { defaultLocaleCode, localeCodes } = resolveLocaleConfiguration(\n config.key(\"app.localeCode\"),\n config.key(\"app.localeCodes\"),\n );\n\n const requested = typeof candidate === \"string\" && candidate.length > 0 ? candidate : undefined;\n\n this._locale =\n requested !== undefined && (localeCodes === undefined || localeCodes.includes(requested))\n ? requested\n : defaultLocaleCode;\n\n return this._locale;\n }\n\n /**\n * Resolve the first present Mode B source, skipping unsupported browser\n * preferences. Other unsupported values resolve to the configured default.\n */\n protected resolveLocale(): string {\n const { localeCodes } = resolveLocaleConfiguration(\n config.key(\"app.localeCode\"),\n config.key(\"app.localeCodes\"),\n );\n const preference = this.cookies[LOCALE_PREFERENCE_COOKIE_NAME];\n // A stale browser preference must not hide the server's legacy cookie or\n // header after an application removes a supported locale.\n const supportedPreference =\n typeof preference === \"string\" &&\n (localeCodes === undefined || localeCodes.includes(preference))\n ? preference\n : undefined;\n const candidate = [\n this.query[\"locale\"],\n supportedPreference,\n this.cookies[LOCALE_COOKIE_NAME],\n this.header(\"locale\"),\n ].find((value) => typeof value === \"string\" && value.length > 0);\n\n return this.cacheLocale(candidate);\n }\n\n /**\n * Get current locale code\n */\n public get locale(): string {\n if (this._locale) return this._locale;\n\n return this.resolveLocale();\n }\n\n /**\n * Set locale code\n */\n public set locale(localeCode: string) {\n this.cacheLocale(localeCode);\n }\n\n /**\n * Set locale code\n */\n public setLocaleCode(localeCode: string) {\n this.locale = localeCode;\n\n return this;\n }\n\n /**\n * @deprecated Use `request.locale`. This alias is removed after one version.\n * The legacy default argument is accepted for source compatibility but the\n * resolved default is owned exclusively by app configuration.\n */\n public getLocaleCode(_legacyDefaultLocaleCode?: string): string {\n return this.locale;\n }\n\n /**\n * Get http protocol\n */\n public get protocol() {\n return this.baseRequest.protocol;\n }\n\n /**\n * Validate the given validation schema\n */\n public async validate(validation: BaseValidator, selectedInputs?: string[]) {\n return await v.validate(validation, selectedInputs ? this.only(selectedInputs) : this.all());\n }\n\n /**\n * Get value of the given header\n */\n public header<TCustomHeader extends string = HeaderKeys>(\n name: TCustomHeader | HeaderKeys,\n defaultValue: any = null,\n ) {\n return this.baseRequest.headers[name.toLocaleLowerCase()] ?? defaultValue;\n }\n\n /**\n * Get all cookies from the current request\n */\n public get cookies(): Record<string, string | undefined> {\n return this.baseRequest.cookies || {};\n }\n\n /**\n * Assert the cookie jar exists before a by-name read. `get cookies()` stays\n * lenient (returns `{}`) for the framework's own opportunistic reads, but a\n * deliberate by-name read from application code must fail loudly when\n * `@fastify/cookie` was never registered, rather than being indistinguishable\n * from \"the caller sent no such cookie\".\n */\n private assertCookieJarAvailable(name: string): void {\n if (this.baseRequest.cookies === undefined) {\n throw new CookieJarUnavailableError(name);\n }\n }\n\n /**\n * Get a particular cookie value or fallback to default\n */\n public cookie(name: string, defaultValue?: any): string | any {\n this.assertCookieJarAvailable(name);\n\n const value = this.cookies[name] ?? defaultValue;\n\n try {\n return JSON.parse(value);\n } catch (error) {\n return value;\n }\n }\n\n /**\n * Determine if the request has the specified cookie\n */\n public hasCookie(name: string): boolean {\n this.assertCookieJarAvailable(name);\n\n return this.cookies[name] !== undefined;\n }\n\n /**\n * Get the current request domain\n */\n public get domain() {\n return this.baseRequest.hostname.replace(/^www\\./, \"\");\n }\n\n /**\n * Get hostname\n */\n public get hostname() {\n return this.domain;\n }\n\n /**\n * Get request origin\n */\n public get origin() {\n return this.baseRequest.headers.origin as string;\n }\n\n /**\n * Get the domain of the origin\n */\n public get originDomain() {\n const domain = this.origin ? new URL(this.origin).hostname : null;\n\n if (domain?.startsWith(\"www.\")) {\n return domain.replace(/^www\\./, \"\");\n }\n\n return domain;\n }\n\n /**\n * Get authorization header value\n */\n public get authorizationValue(): string {\n const authorization = this.header(\"authorization\");\n\n if (!authorization) return \"\";\n\n const [type, value] = authorization.split(\" \");\n\n if (![\"bearer\", \"key\"].includes(type.toLowerCase())) return \"\";\n\n return value || \"\";\n }\n\n /**\n * Get access token from Authorization header\n *\n * If the Authorization header does not start with `Bearer` value then return null\n */\n public get accessToken(): string | undefined {\n const authorization = this.header(\"authorization\");\n\n if (!authorization) return;\n\n const [type, value] = authorization.split(\" \");\n\n if (type.toLowerCase() !== \"bearer\") return;\n\n return value;\n }\n\n /**\n * Get the authorization header\n */\n public get authorization() {\n return this.header(\"authorization\");\n }\n\n /**\n * Get current request method\n */\n public get method(): string {\n return this.baseRequest.method;\n }\n\n /**\n * Parse the payload and merge it from the request body, params and query string\n */\n /**\n * Turn a bracket-notation key into the dotted path `set()` expects.\n *\n * `a[b][c]` -> `a.b.c`. Used only for NON-numeric nesting; numeric indices\n * keep the array-of-objects path in {@link parseBody}, which builds real\n * arrays rather than objects with numeric keys.\n */\n protected bracketKeyToPath(key: string): string {\n return key.replace(/\\]\\[/g, \".\").replace(/\\[/g, \".\").replace(/\\]/g, \"\");\n }\n\n /**\n * Apply the `key[]` array marker to a parsed value.\n *\n * The subtlety this exists to remove: a key declared `[]` should ALWAYS be an\n * array, but the underlying query/body parser only hands us one when the\n * caller sent the key more than once. Deciding the TYPE from the number of\n * occurrences means one selected filter is a string and two are an array —\n * a shape that changes under the user's hands.\n */\n protected arrayValueFor(value: any, isArrayKey: boolean, parse: (value: any) => any) {\n if (Array.isArray(value)) return value.map(parse);\n\n return isArrayKey ? [parse(value)] : parse(value);\n }\n\n protected parsePayload() {\n this.payload.body = this.parseBody(this.baseRequest.body);\n\n this.payload.query = this.parseBody(this.baseRequest.query);\n this.payload.params = { ...(this.baseRequest.params || {}) };\n this.payload.all = {\n ...this.payload.body,\n ...this.payload.query,\n ...this.payload.params,\n };\n }\n\n /**\n * Parse body payload\n */\n protected parseBody(data: any) {\n try {\n if (!data) return {};\n\n const body: any = {};\n\n const arrayOfObjectValues: any = {};\n\n for (let key in data) {\n const value = data[key];\n\n let isArrayKey = false;\n\n if (key.endsWith(\"[]\")) {\n isArrayKey = true;\n }\n\n key = rtrim(key, \"[]\");\n\n // check if the key is has a square brackets, then convert it into object\n // i.e user[email] => user: {email: \"value\"}\n // also check if its an array of objects\n\n if (key.includes(\"[\")) {\n // check if its an array of objects\n if (key.includes(\"][\")) {\n const keyParts = key.split(\"[\");\n\n const keyName = keyParts[0];\n const firstBracket = keyParts[1];\n const secondBracket = keyParts[2];\n\n /*\n `key.includes(\"][\")` guarantees all three segments — but that is a\n property of the string test above, not of these reads, so each is\n `string | undefined`.\n\n When the shape is not what this branch assumes, fall through to\n the generic bracket path rather than skipping the key. That is the\n same choice the NaN branch below makes, and for the same reason\n spelled out there: the failure this code has already been bitten\n by is answering with a shape the caller did not send. Dropping the\n pair silently would be that bug again, in a new place.\n */\n if (\n keyName === undefined ||\n firstBracket === undefined ||\n secondBracket === undefined\n ) {\n set(\n body,\n this.bracketKeyToPath(key),\n this.arrayValueFor(value, isArrayKey, this.parseValue.bind(this)),\n );\n\n continue;\n }\n\n const keyNameParts = firstBracket.split(\"]\");\n\n const index = Number(keyNameParts[0]);\n\n /*\n A NON-NUMERIC first segment is not an array index — it is a deeper\n nested object. `a[b][c]=x` reaches this branch because it contains\n \"][\", but `Number(\"b\")` is NaN, and the code below used to write to\n `[NaN]`: that sets a \"NaN\" PROPERTY on an array whose length stays\n 0, so the request arrived as `{a: []}` and the value was gone. No\n error, no warning — the caller simply never got `x`.\n\n Deciding between refusing (4xx) and interpreting: a doubly-nested\n key is unambiguous and is exactly what every bracket-notation\n parser means by it, so we interpret. Refusing would reject a URL\n shape that is standard elsewhere and that we ourselves already\n honour one level shallower, five lines below. What was definitely\n wrong was answering with a shape the caller did not send.\n\n Numeric indices keep the array-of-objects path below unchanged —\n `items[0][name]` is still an array.\n */\n if (Number.isNaN(index)) {\n set(\n body,\n this.bracketKeyToPath(key),\n this.arrayValueFor(value, isArrayKey, this.parseValue.bind(this)),\n );\n\n continue;\n }\n\n const bucket = (arrayOfObjectValues[keyName] ??= []);\n\n const entry = (bucket[index] ??= {});\n\n // now get the key after the index\n const keyNameParts2 = secondBracket.split(\"]\");\n const keyName2 = keyNameParts2[0];\n\n // `split` always yields a first element, so this holds — but an\n // undefined key here would write a property literally named\n // \"undefined\" onto the entry, which is the same silent-wrong-shape\n // outcome the comment above describes.\n if (keyName2 === undefined) continue;\n\n entry[keyName2] = this.parseValue(value);\n\n continue;\n }\n\n const keyParts = key.split(\"[\");\n const keyName = keyParts[0];\n // `key.includes(\"[\")` puts at least two segments here. Falling back\n // to the whole key rather than asserting keeps the parse total: an\n // undefined segment would make `keyNameParts[0]` undefined too, and\n // this branch writes that straight into the body shape.\n const keyNameParts = (keyParts[1] ?? key).split(\"]\");\n\n /*\n `isArrayKey` is honoured HERE, and used not to be. `filter[tags][]=a`\n sets the flag at the top of the loop, but this branch only wrapped\n when the underlying value was ALREADY an array — which it is for two\n or more occurrences and is not for one. So `filter[tags][]=a` arrived\n as `{filter:{tags:\"a\"}}` while `…=a&…=b` arrived as `{tags:[\"a\",\"b\"]}`:\n the same declared shape, two different types, decided by how many\n times the caller happened to send it.\n\n That single-element case is the one a UI hits first — one filter\n chip selected — and `@warlock.js/web`'s decoder reads it as an array,\n so the page and the server disagreed about the same URL.\n */\n set(\n body,\n keyName + \".\" + keyNameParts[0],\n this.arrayValueFor(value, isArrayKey, this.parseValue.bind(this)),\n );\n\n continue;\n }\n\n if (Array.isArray(value)) {\n set(body, key, value.map(this.parseValue.bind(this)));\n } else if (isArrayKey) {\n if (body[key]) {\n body[key].push(this.parseValue(value));\n } else {\n body[key] = [this.parseValue(value)];\n\n continue;\n }\n } else {\n set(body, key, this.parseValue(value));\n }\n }\n\n // now merge the array of objects into the body\n for (const key in arrayOfObjectValues) {\n body[key] = arrayOfObjectValues[key];\n }\n\n return body;\n } catch (error) {\n console.log(error);\n this.log(error, \"error\");\n }\n }\n\n /**\n * Parse the given data\n */\n protected parseValue(data: any) {\n // data.value appears only in the multipart form data\n // if it json, then just return the data\n if (data?.file) return new UploadedFile(data);\n if (data?.value !== undefined && data?.fields && data?.type) {\n data = data.value;\n }\n\n if (data === \"false\") return false;\n\n if (data === \"true\") return true;\n\n if (data === \"null\") return null;\n\n if (typeof data === \"string\") return data.trim();\n\n return data;\n }\n\n /**\n * Set route handler\n */\n public setRoute(route: Route) {\n this.route = route;\n\n // pass the route to the response object\n this.response.setRoute(route);\n\n return this;\n }\n\n /**\n * Trigger an http event\n */\n public trigger(eventName: RequestEvent, ...args: any[]) {\n return events.trigger(`request.${eventName}`, ...args, this);\n }\n\n /**\n * Listen to the given event\n */\n public on(eventName: RequestEvent, callback: any) {\n return events.subscribe(`request.${eventName}`, callback);\n }\n\n /**\n * Make a log message\n */\n public log(message: any, level: LogLevel = \"info\") {\n if (!config.key(\"http.log\")) return;\n\n log.log({\n module: \"request\",\n action: this.route.method + \" \" + this.route.path.replace(\"/*\", \"\") + `:${this.id}`,\n message,\n type: level,\n context: {\n request: this,\n },\n });\n }\n\n /**\n * Get current request path\n */\n public get path() {\n return this.baseRequest.url;\n }\n\n /**\n * {@alias}\n */\n public get url() {\n return this.baseRequest.url;\n }\n\n /**\n * Get full url\n */\n public get fullUrl() {\n return this.protocol + \"://\" + this.hostname + this.path;\n }\n\n /**\n * Drive the middleware chain for the current route, then defer to the\n * controller. Returns the first response value any middleware short-circuits\n * with, or `undefined` to continue into validation + handler.\n *\n * @internal Framework orchestration — do not call from app code. Will move\n * to a dedicated controller dispatcher in a future refactor.\n */\n public async runMiddleware() {\n // measure request time\n // check for middleware first\n const middlewareOutput = await this.executeMiddleware();\n\n if (middlewareOutput !== undefined) {\n // 👇🏻 make sure first its not a response instance\n if (middlewareOutput instanceof Response) return middlewareOutput;\n // 👇🏻 send the response\n return this.response.send(middlewareOutput);\n }\n\n const handler = this.route.handler;\n\n if (!handler.validation) return;\n\n // 👇🏻 check for validation using validateAll helper function — timed as\n // the \"validation\" tracing phase when tracing is\n // enabled; a single boolean check and zero allocation otherwise.\n const tracingEnabled = isTracingEnabled();\n const validationStartedAt = tracingEnabled ? performance.now() : 0;\n\n const validationOutput = await validateAll(handler.validation, this, this.response);\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(this), {\n name: \"validation\",\n durationMs: performance.now() - validationStartedAt,\n });\n }\n\n return validationOutput;\n }\n\n /**\n * Return the request handler attached to the current route.\n *\n * @internal Framework orchestration — do not call from app code.\n */\n public getHandler() {\n return this.route.handler;\n }\n\n /**\n * Get inputs that has been validated only\n * You can also pass an array of inputs to get only the validated inputs\n */\n public validated<Output = RequestValidation>(inputs?: (keyof Output | (string & {}))[]): Output {\n if (this.validatedData) {\n return inputs\n ? only(this.validatedData as Output, inputs as string[])\n : (this.validatedData as Output);\n }\n\n return {} as Output;\n }\n\n /**\n * Get inputs that has been validated except the given inputs\n */\n public validatedExcept(...inputs: string[]): RequestValidation {\n return except(this.validated(), inputs);\n }\n\n /**\n * Set validated data\n */\n public setValidatedData(data: RequestValidation) {\n this.validatedData = data;\n }\n\n /**\n * Top-level entry into the request lifecycle — opens the context store,\n * runs middleware, drives the handler, handles errors.\n *\n * @internal Framework orchestration — do not call from app code. Wired\n * from the Fastify route handler in `router.scan()`.\n */\n public async execute() {\n try {\n // call executingAction event\n\n this.log(\"Executing the request\");\n\n return await createRequestStore(this, this.response);\n } catch (error) {\n this.log(error, \"error\");\n\n throw error;\n }\n }\n\n /**\n * Iterate the collected middlewares in order; return the first short-circuit\n * value or `undefined` when every middleware passes through.\n *\n * @internal Framework orchestration — do not call from app code.\n */\n protected async executeMiddleware() {\n // collect all middlewares for current route\n const middlewares = this.collectMiddlewares();\n\n // check if there are no middlewares, then return\n if (middlewares.length === 0) return;\n\n this.log(\"About to execute request middlewares\");\n\n // trigger the executingMiddleware event\n this.trigger(\"executingMiddleware\", middlewares, this.route);\n\n const tracingEnabled = isTracingEnabled();\n\n for (const [index, middleware] of middlewares.entries()) {\n this.log(\"Executing middleware \" + colors.yellowBright(middleware.name));\n\n const middlewareStartedAt = tracingEnabled ? performance.now() : 0;\n\n const output = await middleware({\n request: this,\n response: this.response,\n });\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(this), {\n name: \"middleware\",\n durationMs: performance.now() - middlewareStartedAt,\n attrs: { name: middleware.name, index },\n });\n }\n\n this.log(\"Executed middleware \" + colors.yellowBright(middleware.name), \"success\");\n\n if (output !== undefined) {\n this.log(\n colors.yellow(\"request intercepted by middleware \") + colors.cyanBright(middleware.name),\n \"warn\",\n );\n\n this.trigger(\"executedMiddleware\");\n\n this.log(\"Request middlewares executed\", \"success\");\n\n return output;\n }\n }\n\n this.log(\"Request middlewares executed\", \"success\");\n\n // trigger the executedMiddleware event\n this.trigger(\"executedMiddleware\", middlewares, this.route);\n }\n\n /**\n * Gather the middleware list for the current route — today just the\n * route-level array; future extraction may merge group + app-wide layers.\n *\n * @internal Framework orchestration — do not call from app code.\n */\n protected collectMiddlewares(): Middleware[] {\n const middlewaresList: Middleware[] = [];\n\n // collect route middlewares\n if (this.route.middleware) {\n middlewaresList.push(...this.route.middleware);\n }\n\n return middlewaresList;\n }\n\n /**\n * Get request input value from query string, params or body\n */\n public input(key: string, defaultValue?: any) {\n return get(this.payload.all, key, defaultValue);\n }\n\n /**\n * Get email input value, this will lowercase the value\n */\n public email(key: string = \"email\", defaultValue: string = \"\"): string {\n return this.input(key, defaultValue)?.toLowerCase() || defaultValue;\n }\n\n /**\n * @alias input\n */\n public get(key: string, defaultValue?: any) {\n return this.input(key, defaultValue);\n }\n\n /**\n * Determine if request has input value\n */\n public has(key: string) {\n return get(this.payload.all, key, undefined) !== undefined;\n }\n\n /**\n * Set request input value\n */\n public set(key: string, value: any) {\n set(this.payload.all, key, value);\n\n return this;\n }\n\n /**\n * Set the given value if the request does not have the input\n */\n public setDefault(key: string, value: any) {\n if (this.has(key)) return this;\n\n set(this.payload.all, key, value);\n\n return this;\n }\n\n /**\n * Unset request payload keys\n */\n public unset(...keys: string[]) {\n this.payload.all = unset(this.payload.all, keys);\n\n return this;\n }\n\n /**\n * Get request body\n */\n public get body() {\n return this.payload.body;\n }\n\n /**\n * Set request body value\n */\n public setBody(key: string, value: any) {\n set(this.payload.body, key, value);\n\n return this;\n }\n\n /**\n * Get body inputs except files\n */\n public get bodyInputs() {\n const inputs = this.payload.body;\n\n const bodyInputs: any = {};\n\n for (const key in inputs) {\n const value = inputs[key];\n\n if (value.file && value.fieldname) continue;\n\n bodyInputs[key] = value;\n }\n\n return bodyInputs;\n }\n\n /**\n * Get request file in UploadedFile instance\n */\n public file(key: string): UploadedFile | undefined {\n const file = this.input(key);\n\n return file;\n }\n\n /**\n * Get uploaded files from the request for the given name\n * If the given name is not present in the request, return an empty array\n */\n public files(name: string): UploadedFile[] {\n return this.input(name) || [];\n }\n\n /**\n * Get request params\n */\n public get params() {\n return this.payload.params;\n }\n\n /**\n * Set request params value\n */\n public setParam(key: string, value: any) {\n set(this.payload.params, key, value);\n\n return this;\n }\n\n /**\n * Get request query\n */\n public get query() {\n return this.payload.query;\n }\n\n /**\n * Set request query value\n */\n public setQuery(key: string, value: any) {\n set(this.payload.query, key, value);\n\n return this;\n }\n\n /**\n * Get all inputs\n */\n public all() {\n return this.payload.all;\n }\n\n /**\n * Get all inputs except params\n */\n public allExceptParams() {\n return {\n ...this.payload.query,\n ...this.payload.body,\n };\n }\n\n /**\n * Get all heavy inputs except params\n */\n public heavyExceptParams() {\n const inputs = this.allExceptParams();\n\n const heavyInputs: any = {};\n\n for (const key in inputs) {\n const value = inputs[key];\n\n if (isEmpty(value) && value !== null) continue;\n\n heavyInputs[key] = value;\n }\n\n return heavyInputs;\n }\n\n /**\n * Get only heavy inputs, the input with a value\n */\n public heavy() {\n const inputs = this.all();\n\n const heavyInputs: any = {};\n\n for (const key in inputs) {\n const value = inputs[key];\n\n if (isEmpty(value) && value !== null) continue;\n\n heavyInputs[key] = value;\n }\n\n return heavyInputs;\n }\n\n /**\n * Get only the given keys from the request data\n */\n public only(keys: string[]) {\n return only(this.all(), keys);\n }\n\n /**\n * Pluck the given keys from the request data\n */\n public pluck(keys: string[]) {\n const data = this.only(keys);\n\n this.unset(...keys);\n\n return data;\n }\n\n /**\n * Get all request inputs except the given keys\n */\n public except(keys: string[]) {\n return except(this.all(), keys);\n }\n\n /**\n * Get boolean input value\n */\n public bool(key: string, defaultValue = false) {\n const value = this.input(key, defaultValue);\n\n if (value === \"true\") {\n return true;\n }\n\n if (value === \"false\") {\n return false;\n }\n\n if (value === 0) {\n return false;\n }\n\n return Boolean(value);\n }\n\n /**\n * Get integer input value\n */\n public int(key: string, defaultValue: number = 0): number | undefined {\n const value = this.input(key, defaultValue);\n\n if (!value && value !== 0) return undefined;\n\n return parseInt(value);\n }\n\n /**\n * Shorthand getter to get id param\n */\n public get idParam() {\n return this.int(\"id\");\n }\n\n /**\n * Get string input value\n */\n public string(key: string, defaultValue: string = \"\"): string {\n const value = this.input(key, defaultValue);\n\n return String(value);\n }\n\n /**\n * Get float input value\n */\n public float(key: string, defaultValue: number = 0): number {\n const value = this.input(key, defaultValue);\n\n return parseFloat(value) || 0;\n }\n\n /**\n * Get number input value\n */\n public number(key: string, defaultValue: number = 0): number {\n const value = Number(this.input(key, defaultValue));\n\n return isNaN(value) ? defaultValue : value;\n }\n\n /**\n * Immediate-peer IP as Fastify reports it — the address that connected to\n * the server socket, with `trustProxy` resolution applied. Use this when\n * you specifically need the peer address (rate-limit-by-direct-connection,\n * health-check origin verification).\n *\n * **For most use cases prefer `request.detectIp()`** — behind any proxy\n * (load balancer, CDN, sidecar) `ip` reports the proxy, not the real client.\n */\n public get ip() {\n return this.baseRequest.ip;\n }\n\n /**\n * Best-effort real client IP — the value everything IP-scoped keys on\n * (ip-filter allowlists, rate-limit buckets, idempotency scoping).\n *\n * `X-Forwarded-For` resolution is **delegated to Fastify**: `baseRequest.ip`\n * is already the client address Fastify's `trustProxy` machinery picked out\n * of the chain, so every shape `http.trustProxy` accepts is honoured here\n * with exactly the semantics Fastify documents:\n *\n * - `false` (default) — no header is trusted; the socket peer address wins.\n * Both forwarding headers are client-settable, so without a trusted edge\n * that rewrites them any client could otherwise forge its own IP.\n * - `true` — the whole chain is trusted; the leftmost hop (original client)\n * wins.\n * - `number` — that many rightmost hops are trusted, so an edge that\n * APPENDS to `X-Forwarded-For` yields the real client rather than whatever\n * the client prepended.\n * - CIDR / IP list (string, comma-separated string, or array) or a custom\n * predicate — the chain is walked right-to-left and stops at the first hop\n * that isn't a trusted proxy.\n *\n * `X-Real-IP` is NOT part of that resolution — Fastify never looks at it,\n * and unlike `X-Forwarded-For` it carries no chain, so there is nothing to\n * validate a proxy allowlist against. It is therefore honoured\n * only under `trustProxy: true` (\"everything upstream is mine\"), where it is\n * no weaker than the trust already granted. Under a bounded `trustProxy`\n * (CIDR / IP list) it is ignored: a trusted-but-passthrough edge that\n * forwards the client's own `X-Real-IP` verbatim would otherwise hand any\n * client a way around the bound.\n *\n * **Prefer this over `request.ip` for any caller behind a proxy** (load\n * balancer, CDN, reverse proxy, k8s ingress).\n */\n public detectIp() {\n // Trusting `X-Real-IP` is only sound when the config trusts the entire\n // upstream chain; bounded shapes get chain-aware resolution instead.\n // Typed as `unknown`: config.get(key, fallback) infers the FALLBACK's type, so\n // the literal `false` narrowed this to `false` and TypeScript called the\n // comparison unreachable. The stored value is genuinely unconstrained at compile\n // time - trustProxy accepts a boolean, a CIDR list or a predicate - so `unknown`\n // is what it actually is, and the === true check is the narrowing.\n const trustProxy: unknown = config.get(\"http.trustProxy\", false);\n\n if (trustProxy === true) {\n const realIp = this.header(\"x-real-ip\");\n\n if (realIp) {\n // `split` always yields a first element, so `?? \"\"` changes nothing —\n // and an empty address is already falsy, so it falls through to the\n // next source exactly as a blank header does. This is the CLIENT IP\n // used for rate limiting and logging; it must never become the string\n // \"undefined\".\n const address = (String(realIp).split(\",\")[0] ?? \"\").trim();\n\n if (address) return address;\n }\n }\n\n // Fastify resolved this against the configured `trustProxy` already:\n // socket peer when trust is off, the correct hop of `X-Forwarded-For`\n // when it is on. Re-parsing the header here would mean a second, weaker\n // trust model that could disagree with `request.ip` and with the plugins\n // (rate limit, proxy) that key on it.\n return this.baseRequest.ip;\n }\n\n /**\n * An alias to detectIp\n */\n public get realIp() {\n return this.detectIp();\n }\n\n /**\n * Get request ips\n */\n public get ips() {\n return this.baseRequest.ips;\n }\n\n /**\n * Get request referer\n */\n public get referer() {\n return this.baseRequest.headers.referer;\n }\n\n /**\n * Get user agent\n */\n public get userAgent() {\n return this.baseRequest.headers[\"user-agent\"];\n }\n\n /**\n * Get request headers\n */\n public get headers(): typeof this.baseRequest.headers {\n return this.baseRequest.headers;\n }\n\n /**\n * Set the given header\n */\n public setHeader(key: HeaderKeys, value: string) {\n this.baseRequest.headers[key.toLowerCase()] = value;\n\n return this;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,UAAb,MAAa,QAAiC;;iBAgCnB,CAAC;gBA4EK,CAAC;eA+CS;WAKJ;iBAejB;YAUR,OAAO,OAAO,EAAE;iBAOX;mBAKE,KAAK,IAAI;;;;;;;;;CAvJ5B,IAAW,qBAAqD;EAC9D,OAAO,KAAK;CACd;CAEA,IAAW,mBAAmB,OAAuC;EACnE,KAAK,sBAAsB;EAC3B,KAAK,OAAO,cAAc;CAC5B;;;;;;;;;;;;;;;;;;CAmBA,IAAW,OAAc;EAC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