@lenne.tech/nest-server 12.13.0 → 12.14.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/.claude/rules/configurable-features.md +1 -1
- package/.claude/rules/package-management.md +1 -1
- package/.claude/rules/testing.md +3 -3
- package/FRAMEWORK-API.md +1 -1
- package/dist/core/common/helpers/meta.helper.d.ts +5 -0
- package/dist/core/common/helpers/meta.helper.js +16 -1
- package/dist/core/common/helpers/meta.helper.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-jwt-rejection.helper.d.ts +21 -0
- package/dist/core/modules/better-auth/core-better-auth-jwt-rejection.helper.js +106 -0
- package/dist/core/modules/better-auth/core-better-auth-jwt-rejection.helper.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth.service.d.ts +4 -1
- package/dist/core/modules/better-auth/core-better-auth.service.js +25 -7
- package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
- package/dist/core/modules/better-auth/index.d.ts +1 -0
- package/dist/core/modules/better-auth/index.js +1 -0
- package/dist/core/modules/better-auth/index.js.map +1 -1
- package/dist/core/modules/health-check/core-health-check.service.d.ts +8 -0
- package/dist/core/modules/health-check/core-health-check.service.js +28 -4
- package/dist/core/modules/health-check/core-health-check.service.js.map +1 -1
- package/migration-guides/12.13.x-to-12.14.x.md +132 -0
- package/migration-guides/12.14.0-to-12.14.1.md +63 -0
- package/package.json +7 -7
- package/src/core/common/helpers/meta.helper.ts +62 -3
- package/src/core/common/interfaces/server-options.interface.ts +6 -1
- package/src/core/modules/better-auth/README.md +4 -1
- package/src/core/modules/better-auth/core-better-auth-jwt-rejection.helper.ts +164 -0
- package/src/core/modules/better-auth/core-better-auth.service.ts +50 -6
- package/src/core/modules/better-auth/index.ts +1 -0
- package/src/core/modules/health-check/core-health-check.service.ts +69 -12
|
@@ -351,7 +351,7 @@ This pattern is currently applied to:
|
|
|
351
351
|
| S3 Connection Pool & Download Guard | `s3.maxSockets`, `s3.connectionTimeoutMs`, `s3.socketTimeoutMs`, `s3.downloadIdleTimeoutMs`; `file.downloadIdleTimeoutMs`, `file.downloadCaching` | Numeric — invalid → default, never off (Family C without opt-out) + Explicit Enum | **12.8.9, after a production outage**: S3 downloads delivered with a bare `stream.pipe(res)` kept their sockets when clients aborted; after 50 the SDK's pool was full, every S3 request waited forever (health check green), heap OOM hours later. Since then: `CoreS3Service` builds its client with OWN agents (`maxSockets` **200**, keep-alive), `connectionTimeout` **15 000** per attempt (the SDK starts it when the request is CREATED, so it also bounds the wait for a free socket — a short value fails healthy downloads under load; the SDK retries a timed-out attempt, 3 attempts in all, so a download that gets no socket answers **503** + `Retry-After: 5` after about 46 s — keep 3 × the value below the reverse proxy's read timeout, commonly 60 s), `socketTimeout` **120 000** (inactivity backstop for every request, uploads and copies included). The SDK's `requestTimeout` stops at the headers and its socket timeout destroys the body WITH an error (a process crash without a listener), so the real guard is `guardIdleStream()` (`common/helpers/idle-stream.helper.ts`): every stream from `getObject()` (`s3.downloadIdleTimeoutMs`, 30 000) and from `CoreFileService.getFileStream()` / `getFileStreamByName()` (`file.downloadIdleTimeoutMs`, 30 000 — GridFS cursors, file handles) is destroyed after that long WITHOUT READ PROGRESS, measured on the consumer side (`_read`) and at the source; a slow reader that keeps reading is never cut off; code that opens a stream and reads it LATE (an archive appending every file first) breaks — per call `downloadIdleTimeoutMs: false` (`FileServiceOptions`) / `getObject(key, { idleTimeoutMs: false })` opts out. `pipeFileToResponse()` destroys the source when the client goes — the response's `close`, the request's `close` (before its end and while the response is unfinished — Node closes a request whose body was read to the end by itself, a POST export stays deliverable) or the socket's `end`/`close`: measured under a k6 abort storm, about one in six aborted downloads never got a `close` on the response and reported it only through the request or the socket — and at once when it had ALREADY gone (`isResponseGone()`: response destroyed/closed OR request destroyed before its end OR socket destroyed; a client that gave up while waiting for a socket — the avalanche path); the routes pass an `abortSignal` (`downloadAbortSignal()`, exported: the same client-gone signals) down to `GetObjectCommand` and open the stream through `openDownloadStream()` (exported since 12.9.2 for a project's own routes): no store request for a gone client, `RESPONSE_GONE` instead of an ERROR when the store request failed because the client left (an aborted S3 request rejects with `AbortError`), a late stream destroyed, `TimeoutError` → 503 + `Retry-After`. An exhausted pool is logged as an ERROR once per minute with numbers (`getSocketPoolStats()` exposes them); deliberately NOT a health-check failure. `file.downloadCaching`: `'none'` (default, `private, no-store`) or `'revalidate'` (`private, no-cache` — the browser revalidates every use, `304` after the rights check without a store read); both send a WEAK `ETag` `W/"<id>"` (bytes under an id never change, but a `compression` middleware sends a gzip and an identity representation of the same file — RFC 9110 §8.8.3 forbids one strong validator for both; `If-None-Match` compares weakly) and `Content-Length`. The reference `src/main.ts` uses `compression.filter` (no gzip for JPEG/PNG/PDF/ZIP). Pinned by `tests/unit/idle-stream.spec.ts`, `tests/unit/core-file.controller.spec.ts`, `tests/unit/download-idle-opt-out.spec.ts` and `tests/s3-download-resilience.e2e-spec.ts` (real RustFS: dropped streams, abort storm with bare `pipe()`, clients giving up while waiting, 500 parallel downloads with `maxSockets: 4`, slow reader; mutations `idle-guard-*`, `s3-get-object-*`, `pipe-file-to-response-*`, `download-route-keeps-late-stream`, `file-stream-drops-idle-opt-out`). Implementation: `core-s3.service.ts`, `core-file.controller.ts`, `core-file.service.ts` |
|
|
352
352
|
| TUS S3 Staging | `tus.s3Staging` | Explicit Boolean (default ON when S3 configured) | `true` when `s3` is configured, otherwise inert. Stages in-progress uploads in `s3.stagingBucket` via `@tus/s3-store` instead of `tus.uploadDir` on local disk, so resumable uploads survive replica restarts and need no sticky sessions. Set `false` to force local disk. Missing OPTIONAL peer `@tus/s3-store` → warning + fall back to local disk (NOT a boot failure). **Give the staging bucket a lifecycle rule expiring incomplete multipart uploads** — the framework's own expiration cleanup is skipped in S3 mode (S3 is the right place for that policy), so aborted uploads otherwise accumulate parts nothing removes |
|
|
353
353
|
| TUS Configuration Source, Path & Extensions | `tus` (server config) / `TusModule.forRoot({ config })` | Enabled by Default + explicit-config-wins | **Since 11.42.9 `TusModule.forRoot()` without `config` reads the server config's `tus` key** (`ConfigService.get('tus')`, the zero-config rule `CoreBetterAuthModule.forRoot()` follows); an explicit `config` wins. Before, the key was never read: `tus: false`, `allowedTypes`, `maxSize`, `roles` in `config.env.ts` did nothing — real projects had upload restrictions they believed were enforced. **`path`** has three readings (`applyPath()`): unset → follows the controller's route; a new route (`/uploads`) → mounts the registered controller there (writes `PATH_METADATA`, config wins like the roles; the declared route is remembered per class and restored by a later `forRoot()` without `path`); a path ENDING with the controller's route (`/api/tus`, `/files/tus`) → the PUBLIC URL: the controller stays and upload URLs use it. The third reading is load-bearing: it was the only working setting under a global prefix or a prefix-stripping proxy before 11.42.9, and treating it as a route doubled the prefix (`/api/api/tus`, 404 on every upload — caught in the second pre-release review). The upload URL (`Location`) is built from the path the creation request arrived at (`uploadCollectionPath(req)`), or from `path` when that is longer and ends with it (proxy strip); `@tus/server` built it from `path` alone, which broke every resume below a global prefix, a URI version or a project route. **`relativeLocation`** (new): the framework owns `generateUrl`, which takes precedence over `@tus/server`'s option of that name, so it is honoured from `tus.relativeLocation` AND from the tus server's own options (a vendored core may pass it there). **Extensions**: `@tus/server` consults no flag, so `creation`, `creationWithUpload` and `termination` are enforced by `CoreTusService` — the store's advertised `extensions` are narrowed, and `assertExtensionEnabled()` answers 501 inside the server's `onIncomingRequest` / `onUploadCreate` options (not in the overridable hook, so an override without `super` cannot reopen it). `checksum` / `concatenation` have no effect: neither built-in store supports them. `configure(false)` now yields a DISABLED config (before it kept the defaults and started a tus server behind a module with no endpoint). Implementation: `tus.module.ts`, `core-tus.service.ts` |
|
|
354
|
-
| Health Check | `healthCheck` | Presence Implies Enabled | Absent → no endpoints. Any object registers `GET /health-check` + the `healthCheck` query; **`enabled: false` leaves them out (honoured since 11.42.9 — before, it was declared and ignored)**. Individual checks under `configs.*` each have their own `enabled`. **Readiness (12.11.0): `healthCheck.readiness`, Boolean Shorthand + Presence Implies Enabled — absent = no readiness route, the health check exactly as before.** `true` / `{}` registers `GET /health-check/ready` (public, REST only, its own controller `CoreHealthCheckReadinessController`, so without it the route does not exist: 404) with the default checks `['database', 'build']`; `readiness.checks` lists the checks of `configs` it runs (`database` — MongoDB ping and every SQL source —, `memoryHeap`, `memoryRss`, `storage`, `build`; a comma-separated string as `NSC__HEALTH_CHECK__READINESS__CHECKS` gives it; unknown names ignored with one warning; not a list or string → the defaults; `[]` → only project indicators), with key, thresholds and options from `configs.<check>` and whatever `configs.<check>.enabled` says (that flag decides for liveness). `false` / `{ enabled: false }` registers nothing. 200 while every check is up, 503 when one is down, and `shutting_down` from the first shutdown signal on when `installGracefulShutdown()` handles it (it marks the shutdown before its `shutdownDelayMs` wait — `shutdown-state.helper.ts`, mutations `readiness-ignores-shutdown`, `graceful-shutdown-skips-drain-mark`); Terminus' own state alone comes only inside `app.close()`. **Project checks**: extend `CoreHealthCheckService`, override the protected `additionalHealthIndicators(kind: 'liveness' \| 'readiness')` (default `[]`, may be async) and return Terminus indicators; register the subclass with `CoreModule.forRoot(env, { healthCheck: { service } })` (`readinessController` replaces the readiness controller). `CoreHealthCheckModule` imported as it is stays the pre-12.11.0 module; `CoreHealthCheckModule.forRoot()` adds the readiness controller and the service override (a dynamic module extends the static metadata, so the liveness controller is never registered twice). Pinned by `tests/unit/health-check-readiness.spec.ts`, `tests/unit/core-module-signatures.spec.ts`. Implementation: `core.module.ts`, `modules/health-check/` (`resolveHealthCheckReadiness()` in `core-health-check.helpers.ts`) |
|
|
354
|
+
| Health Check | `healthCheck` | Presence Implies Enabled | Absent → no endpoints. Any object registers `GET /health-check` + the `healthCheck` query; **`enabled: false` leaves them out (honoured since 11.42.9 — before, it was declared and ignored)**. Individual checks under `configs.*` each have their own `enabled`. **Database ping (12.14.0):** `configs.database.options.timeout` (ms) bounds the MongoDB ping and every SQL source; default 2000 (`DEFAULT_DATABASE_PING_TIMEOUT_MS`; before: 300 ms for MongoDB without options, otherwise 1000 ms, SQL 1000 ms). The MongoDB ping is the core's own (`CoreHealthCheckService.pingMongoDb()`): a real `ping` that waits for the driver's server selection, WITHOUT Terminus' `readyState` gate, which reported a reachable replica set as down whenever the driver briefly saw no primary (Mongoose sets `disconnected` then) — more than 95 % of all "database down" alarms on a cluster with managed replica sets. Connection: `options.connection`, else the injected `@InjectConnection()` (property, so subclasses keep it). Pinned by `tests/unit/health-check-mongo-ping.spec.ts` (mutations `health-check-mongo-ping-*`). **Readiness (12.11.0): `healthCheck.readiness`, Boolean Shorthand + Presence Implies Enabled — absent = no readiness route, the health check exactly as before.** `true` / `{}` registers `GET /health-check/ready` (public, REST only, its own controller `CoreHealthCheckReadinessController`, so without it the route does not exist: 404) with the default checks `['database', 'build']`; `readiness.checks` lists the checks of `configs` it runs (`database` — MongoDB ping and every SQL source —, `memoryHeap`, `memoryRss`, `storage`, `build`; a comma-separated string as `NSC__HEALTH_CHECK__READINESS__CHECKS` gives it; unknown names ignored with one warning; not a list or string → the defaults; `[]` → only project indicators), with key, thresholds and options from `configs.<check>` and whatever `configs.<check>.enabled` says (that flag decides for liveness). `false` / `{ enabled: false }` registers nothing. 200 while every check is up, 503 when one is down, and `shutting_down` from the first shutdown signal on when `installGracefulShutdown()` handles it (it marks the shutdown before its `shutdownDelayMs` wait — `shutdown-state.helper.ts`, mutations `readiness-ignores-shutdown`, `graceful-shutdown-skips-drain-mark`); Terminus' own state alone comes only inside `app.close()`. **Project checks**: extend `CoreHealthCheckService`, override the protected `additionalHealthIndicators(kind: 'liveness' \| 'readiness')` (default `[]`, may be async) and return Terminus indicators; register the subclass with `CoreModule.forRoot(env, { healthCheck: { service } })` (`readinessController` replaces the readiness controller). `CoreHealthCheckModule` imported as it is stays the pre-12.11.0 module; `CoreHealthCheckModule.forRoot()` adds the readiness controller and the service override (a dynamic module extends the static metadata, so the liveness controller is never registered twice). Pinned by `tests/unit/health-check-readiness.spec.ts`, `tests/unit/core-module-signatures.spec.ts`. Implementation: `core.module.ts`, `modules/health-check/` (`resolveHealthCheckReadiness()` in `core-health-check.helpers.ts`) |
|
|
355
355
|
| Cron Job Deduplication | per job: `distributed` in `CronJobConfig` | Explicit Boolean | **`true` when `redis` is configured, otherwise `false`** — a single-replica project that upgrades must not silently gain a `cron-locks` collection, a lease write per tick, and a new way for a tick to be skipped. A Redis-less multi-replica fleet opts in per job with `distributed: true` (lease in the SQL lease table of the default source, else in MongoDB). Mechanism: BullMQ job scheduler when Redis + the OPTIONAL peer `bullmq` are present AND `cronTime` is a string without `utcOffset`; otherwise local timer + lease (Redis `SET NX`, else the SQL lease table of the default source (`lt_locks`), else a TTL-indexed `cron-locks` document). Tick lease TTL 3600 s. **Leases fail open** — an unreachable lease store runs the tick everywhere rather than stopping all scheduled work fleet-wide. **`runOnInit` (default `true`) deduplicates over a FIXED per-job key with a 300 s TTL**, because replicas do not share a boot instant: replicas booting within 5 min run the startup tick once between them, and a replica restarting inside that window SKIPS its startup tick — set `distributed: false` on jobs whose `runOnInit` work is per-process (warming a process-local cache). No constructor change needed: `CoreModule` fills `core-cron-jobs.registry.ts` via `CoreCronJobsInitializer` and `CoreCronJobs` reads it lazily; explicit `{ connection, redisService }` in `CoreCronJobsOptions` wins. With neither source it warns once and every replica runs every tick. **A BullMQ schedule lost in Redis comes back (12.1.1+)**: `upsertJobScheduler` writes it once at bootstrap, and a Redis restart without persistence, a FLUSHDB or an eviction removed it with nothing re-registering it, so no replica ran the job until the next deploy. `restoreBullSchedulers()` now runs after every `ready` of the queue connection and every `bullSchedulerCheckIntervalMs` (protected, 60000; `0` switches only the timer off) and registers the schedules the queue's listing (`getJobSchedulers()`) no longer contains, with a warning — the listing, because `getJobScheduler()` does not exist before bullmq 5.23 and answers a deleted scheduler with an object up to 5.40.2, both inside the peer range. Only MISSING ones: an upsert of an existing scheduler removes its last planned job even when it is due and waits for a free worker, so a blind periodic upsert would drop that tick. A scheduler `removeStaleBullSchedulers()` removed on purpose carries a `cron-scheduler-removed:<job>` key, so a replica of the previous version still running in a rolling deploy does not bring it back (a job moved to a local timer would otherwise run twice per tick); the next BullMQ registration of that job deletes the key, and a real data loss takes it along. Only the schedule comes back (no second `runOnInit`, no second registry entry); a tick that fell due while it was missing is not run. **Changing a schedule at runtime (12.11.0): `rescheduleCronJob(name, schedule)`**, public — a cron expression or date (time zone / UTC offset kept) or `{ cronTime, timeZone }` / `{ cronTime, utcOffset }`; validated first (an invalid expression, an unknown zone or a past date rejects, the job stays as it was); calls run one after the other; rejects for a job that is not registered (unknown, disabled, before bootstrap, after shutdown). Only the schedule changes: `distributed`, `runParallel`, `throwException`, the leases and `bullJobOptions` stay. Local timer: the timer is replaced, a distributed tick leases on the NEW schedule's instant, a recurring job the Hub stopped stays stopped, `runOnInit` is not repeated. BullMQ: the scheduler is upserted with the new pattern and `bullJobOptions` — skipped when Redis already holds exactly that pattern and time zone, so N replicas calling it plan no tick twice —, the Hub's registry entry is replaced, and `restoreBullSchedulers()` restores the NEW schedule; Redis refusing the upsert rejects and keeps the old schedule. A schedule BullMQ cannot express (a date, a UTC offset) moves the job to a local timer with lease and removes its scheduler WITH the `cron-scheduler-removed:<job>` marker (marker first), so replicas still scheduling it through BullMQ do not restore it; a cron expression moves it back and deletes the marker. A BullMQ schedule changes fleet-wide, a local timer per process — call it on every replica; it is not stored, the next bootstrap schedules from the configuration (re-apply after `super.onApplicationBootstrap()`). Pinned by `tests/unit/core-cron-jobs-reschedule.spec.ts`. **Since 12.1.1 (DEV-3896)**: (1) a timer job's tick lease is keyed on the tick's SCHEDULED instant, captured from `nextDate()` when the job is armed and after each scheduled fire, and moved forward through the schedule to the last instant at or before the fire when the job did not fire for a while (stopped and started in the Hub; not for a `utcOffset` job) — cron 4 sets `lastDate()` to the moment its timer fired, so two replicas firing on either side of a second boundary computed different keys and both ran the tick. A fire that does not advance `lastDate()` is a manual run (the Hub's "Run now") with a key of its own, also on a job stopped in the Hub. (2) `runParallel: false` (or `1`) holds across replicas for a distributed job, in timer and BullMQ mode: the run holds a `<job>:running` lease (60 s, renewed every 20 s, released in `finally`; Redis — owner-checked renew and release —, else the SQL lease table, else `cron-locks`), and a replica that finds it held skips its tick; fail-open like the tick lease. A run that never ends therefore holds the job on EVERY replica while its process lives, not only on its own. A larger `runParallel` stays per process. (3) A failed TTL index on `cron-locks` is tried again on the next tick instead of being cached as done. (4) Without `redis`, startup logs ONE info line naming the jobs that run on every replica because they did not set `distributed` (silent with `log: false`, and for jobs that set `distributed: false`). (5) BullMQ scheduler jobs carry `bullJobOptions` (protected): `attempts: 1` — a failed tick is not repeated, as with the local timer —, `removeOnComplete: { count: 100 }`, `removeOnFail: { count: 500 }`; before, every completed and failed tick stayed in Redis for good. Existing schedulers get them at the next bootstrap, which upserts every scheduler — after `trimBullJobBacklog()` has removed the backlog an earlier version kept, oldest first, 1000 jobs per `clean()` call: BullMQ trims by `count` in one Lua call without a limit, and the first tick under the new options would otherwise delete the whole backlog at once (measured 2 s for 300k jobs, 4.4 s for 700k, with Redis answering nobody) |
|
|
356
356
|
| Shutdown Delay | `shutdownDelayMs` | Numeric Sentinel — Family B (`0` = off) | `0` (default, no delay, no log). Waits N ms **in the SIGTERM/SIGINT handler, before `close()` is entered**, so a load balancer can finish deregistering while the instance still serves; from the signal on `GET /health-check/ready` answers 503 `shutting_down` (12.11.0, `markShutdownDraining()`), so a load balancer polling readiness starts deregistering at once. NOT a lifecycle hook: `close()` runs `onModuleDestroy` → `beforeApplicationShutdown` → dispose → `onApplicationShutdown`, so a delay in `beforeApplicationShutdown` would wait with every module already torn down while the socket still accepts — worse than no delay. **Requires `installGracefulShutdown(app)` in main.ts, which REPLACES `server.enableShutdownHooks()`** — keeping both makes Nest close the app in parallel with the wait, so the delay silently never happens. At delay `0` the helper IS `enableShutdownHooks()`. **Keep the value well below the orchestrator grace period AND leave room for the drain that follows**: Compose `stop_grace_period` 10s, Kubernetes `terminationGracePeriodSeconds` 30s, and `installProcessDiagnostics()` force-exits after 30s — exceed any and the process is SIGKILLed mid-wait with no hook running. Warns above `10000`, capped at `60000`. Non-numeric / negative values behave like `0` |
|
|
357
357
|
| Body Parser Limits | `bodyParser.json.limit`, `bodyParser.urlencoded.limit` | Explicit Value (Express/body-parser default) — invalid → default, never unbounded | **Unset = 100 kB each, exactly as NestJS registers the parsers** (body-parser's own default — a limit nobody chose, and before 11.42.4 the only one in force: over it a request got a bare `request entity too large`, before auth and routing, GraphQL included). A number is bytes, a string a 1024-based size (`'500kb'`, `'2mb'`, units `b`/`kb`/`mb`/`gb`). The two limits are separate on purpose — raising JSON must not raise form posts. **Not raised by default because the parser runs before authentication** and `JSON.parse` blocks the event loop for the whole body: ~0.5 ms for 100 kB, ~16 ms for 1 MB, ~55 ms for 2 MB per request on a realistic document shape. Applied by `CoreBodyParserInitializer` (CoreModule provider) in `onModuleInit` by **swapping the handle of the global `jsonParser`/`urlencodedParser` layers NestJS registered, in place** — NestJS registers them inside `app.init()` before any init hook, and a parser appended later would sit behind the routes. Same position, `extended: true` for URL-encoded, `req.rawBody` kept when the app came from `NestFactory.create(…, { rawBody: true })` (read from the container's context options; under `Test.createTestingModule()` those options never reach the container, so a test app with `rawBody: true` gets no `req.rawBody` from a CONFIGURED parser). Because it runs during module init it **holds under `Test.createTestingModule()`**, which never runs `main.ts` — the reason a `useBodyParser()` in `main.ts` was not enough. A configured value also replaces a global parser registered in `main.ts`; a **path-scoped** one (`server.use('/upload', json({ limit }))`) is left alone and stays the way to give one path its own limit (the parser runs before routing; GraphQL shares one path). **Keep `server.useBodyParser('json')` in `main.ts` next to a path-scoped parser**: NestJS registers its global parser only when no layer with the same FUNCTION NAME exists (`isMiddlewareApplied()`), so a path-scoped `json()` registered before `app.init()` suppresses it and every other path gets an empty body (a sign-in fails with a validation error). Since 11.42.6 the initializer warns at boot about exactly that (`warnMissingGlobalParser()`). It deliberately does not re-insert the parser: NestJS would have placed it after everything `main.ts` registered, a position no longer knowable during module init, and a raw-body webhook or proxy registered after the path-scoped parser must keep seeing the unread stream. An invalid value (`0`, negative, `NaN`, a word) is refused with an error log and the parser keeps its limit. **Independent of configuration**, every 413 from a global parser is answered as `PayloadTooLargeException` with `#LTNS_0304: Request body too large [<n> bytes, limit <m> bytes]` (size only when a `Content-Length` was sent) and logged as a WARN naming method, path without query string, and the config key — no boot warning, because the framework cannot know which routes expect large bodies; the first oversized request is the earliest point anything can be said. Other parser errors pass through unchanged. Pinned by `tests/unit/body-parser.spec.ts` and `tests/body-parser.e2e-spec.ts` (mutations `body-parser-*`). Implementation: `common/services/core-body-parser.initializer.ts` |
|
|
@@ -181,7 +181,7 @@ by the ws maintainers on 2026-11-12 and was not yet in GitHub's global database
|
|
|
181
181
|
`pnpm audit` did not report it — read the advisories of a package's own repository when a release announces a
|
|
182
182
|
security fix. It left in 12.12.0, once `@nestjs/graphql` 14.2.2 pinned ws 8.23.0 itself (two fresh resolves with and
|
|
183
183
|
without the entry: identical package set, one `ws@8.23.0`). `check:overrides` could not report it as UNUSED: every
|
|
184
|
-
edge resolved to the override's target either way, so only the with/without resolve shows such an entry is inert. From 12.10.0 to 12.10.1 a second entry, `minimatch` 11 -> 11.0.9: `@nestjs/cli` 12.0.13 exact-pins 11.0.5, covered by three moderate advisories (dev tooling only; the target is the newest 11.x, because an older one held every other `^11` consumer back). It left in 12.11.0, once `@nestjs/cli` 12.0.15 pinned 11.0.9 itself. Since 12.10.0 the set holds `i18next` 26 -> 26.4.4 (its only entry since 12.12.0): `@compodoc/compodoc` 2.0.0 exact-pins 26.3.3, covered by two advisories (dev tooling only); GHSA-6jcc is in GitHub's global database since 2026-11-23, GHSA-5jr9 was still repository-only at 12.12.0. Since 12.12.2 the target is 26.7.2, the newest 26.x, as in nest-server-starter: the oldest-that-clears target held a generated project that hoists the starter's file and asks `^26` three minors back. An override is only necessary if removing it lets the package resolve
|
|
184
|
+
edge resolved to the override's target either way, so only the with/without resolve shows such an entry is inert. From 12.10.0 to 12.10.1 a second entry, `minimatch` 11 -> 11.0.9: `@nestjs/cli` 12.0.13 exact-pins 11.0.5, covered by three moderate advisories (dev tooling only; the target is the newest 11.x, because an older one held every other `^11` consumer back). It left in 12.11.0, once `@nestjs/cli` 12.0.15 pinned 11.0.9 itself. Since 12.10.0 the set holds `i18next` 26 -> 26.4.4 (its only entry since 12.12.0): `@compodoc/compodoc` 2.0.0 exact-pins 26.3.3, covered by two advisories (dev tooling only); GHSA-6jcc is in GitHub's global database since 2026-11-23, GHSA-5jr9 was still repository-only at 12.12.0. Since 12.12.2 the target is 26.7.2, the newest 26.x, as in nest-server-starter: the oldest-that-clears target held a generated project that hoists the starter's file and asks `^26` three minors back. Since 12.14.0 a second entry, `minimatch` 11 -> 11.0.10: GHSA-3924-r96c-gp9w (low, 11.0.6 to 11.0.9) reached GitHub's global database on 2026-12-04, and `@nestjs/cli` 12.0.15 as well as `@ts-morph/common` (production path via ts-morph) resolve 11.0.9; target 11.0.10, the newest 11.0.x, as in nest-server-starter. An override is only necessary if removing it lets the package resolve
|
|
185
185
|
back INTO its vulnerable range (verify with a with/without lockfile diff; `pnpm audit` is the arbiter).
|
|
186
186
|
"Cheap insurance against a parent re-pinning downwards" is not a reason to keep one: `pnpm audit` and
|
|
187
187
|
`check:overrides` run on every `check` and report such a regression the day it happens. Each surviving entry carries its CVE rationale as a comment. Remove an entry once its parent dependency ships a fixed version.
|
package/.claude/rules/testing.md
CHANGED
|
@@ -418,7 +418,7 @@ pnpm run check:mutations -- --id=<id> # one mutation
|
|
|
418
418
|
pnpm run check:mutations -- --list # the registry, without running anything
|
|
419
419
|
pnpm run check:mutations -- --allow-dirty # when the fix and its evidence share a working tree
|
|
420
420
|
pnpm run check:mutations -- --jobs=4 # N mutations at a time (default: 2, or 4 on >=12 cores)
|
|
421
|
-
pnpm run check:mutations -- --no-infra # only the
|
|
421
|
+
pnpm run check:mutations -- --no-infra # only the 554 that need no MongoDB
|
|
422
422
|
pnpm run check:mutations -- --since=<ref> # only mutations touching files changed since <ref>
|
|
423
423
|
pnpm run check:mutations -- --shard=2/4 # this job's quarter of the selection (CI splits the full run)
|
|
424
424
|
```
|
|
@@ -438,7 +438,7 @@ when the registry, a vitest config or a setup file changed, since those can move
|
|
|
438
438
|
commit, and in CI alongside the publish without blocking it. The price of caching is a cache that
|
|
439
439
|
has to model each spec's full dependency closure correctly, and getting that wrong produces a stale
|
|
440
440
|
PASS for a test that has since gone vacuous — exactly what the gate is there to prevent. Bad trade
|
|
441
|
-
at
|
|
441
|
+
at 813 mutations.
|
|
442
442
|
|
|
443
443
|
**Decided 2026-10-03 (repo owner): keep the full run.** Measured at 128 mutations, the CI job for
|
|
444
444
|
11.41.6 took **14 minutes**. The trigger to revisit is that wall time, not the mutation count —
|
|
@@ -511,7 +511,7 @@ exactly the environment where the answer matters.
|
|
|
511
511
|
|
|
512
512
|
Worth knowing before optimising the wrong thing: the specs behind all 259 e2e mutations add up to
|
|
513
513
|
**~40 seconds**. The step takes ~740s. The remaining ~700s is paying vitest's startup — process
|
|
514
|
-
spawn, transform, module graph, mongod connect, DB create and drop — once per mutation,
|
|
514
|
+
spawn, transform, module graph, mongod connect, DB create and drop — once per mutation, 813 times.
|
|
515
515
|
That work is largely single-threaded I/O and barely scales with cores: the full registry measures
|
|
516
516
|
**744s on a 12-core laptop and 777s on a 4-vCPU CI runner**.
|
|
517
517
|
|
package/FRAMEWORK-API.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @lenne.tech/nest-server — Framework API Reference
|
|
2
2
|
|
|
3
|
-
> Auto-generated from source code as of 2026-12-
|
|
3
|
+
> Auto-generated from source code as of 2026-12-05 (v12.14.1)
|
|
4
4
|
> File: `FRAMEWORK-API.md` — compact, machine-readable API surface for Claude Code
|
|
5
5
|
|
|
6
6
|
## CoreModule.forRoot()
|
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
export declare const DEFAULT_COMMIT_ENV = "APP_VERSION_COMMIT";
|
|
2
|
+
export declare const DEFAULT_BUILD_ENV = "APP_VERSION_BUILD";
|
|
2
3
|
export declare const UNKNOWN_COMMIT = "unknown";
|
|
3
4
|
export interface BuildInfo {
|
|
5
|
+
build?: string;
|
|
4
6
|
commit: string;
|
|
5
7
|
env?: string;
|
|
6
8
|
version?: string;
|
|
7
9
|
}
|
|
8
10
|
export declare function getCommit(envName?: string): string;
|
|
11
|
+
export declare function getBuild(envName?: string): string | undefined;
|
|
12
|
+
export declare function composeVersion(version: string, build?: null | string): string;
|
|
9
13
|
export declare function getBuildInfo(options?: {
|
|
14
|
+
buildEnvName?: string;
|
|
10
15
|
commitEnvName?: string;
|
|
11
16
|
env?: string;
|
|
12
17
|
version?: string;
|
|
@@ -1,16 +1,31 @@
|
|
|
1
1
|
import { existsSync, readFileSync } from 'fs';
|
|
2
2
|
import { join } from 'path';
|
|
3
3
|
export const DEFAULT_COMMIT_ENV = 'APP_VERSION_COMMIT';
|
|
4
|
+
export const DEFAULT_BUILD_ENV = 'APP_VERSION_BUILD';
|
|
4
5
|
export const UNKNOWN_COMMIT = 'unknown';
|
|
5
6
|
let cachedVersion;
|
|
6
7
|
export function getCommit(envName = DEFAULT_COMMIT_ENV) {
|
|
7
8
|
return process.env[envName] || UNKNOWN_COMMIT;
|
|
8
9
|
}
|
|
10
|
+
export function getBuild(envName = DEFAULT_BUILD_ENV) {
|
|
11
|
+
const build = (process.env[envName] || '').trim();
|
|
12
|
+
return /^\d+$/.test(build) ? build : undefined;
|
|
13
|
+
}
|
|
14
|
+
export function composeVersion(version, build) {
|
|
15
|
+
const buildNumber = (build ?? '').trim();
|
|
16
|
+
const match = /^(\d+)\.(\d+)/.exec(version);
|
|
17
|
+
if (!match || !/^\d+$/.test(buildNumber)) {
|
|
18
|
+
return version;
|
|
19
|
+
}
|
|
20
|
+
return `${match[1]}.${match[2]}.${buildNumber}`;
|
|
21
|
+
}
|
|
9
22
|
export function getBuildInfo(options = {}) {
|
|
23
|
+
const build = getBuild(options.buildEnvName);
|
|
10
24
|
return {
|
|
25
|
+
...(build ? { build } : {}),
|
|
11
26
|
commit: getCommit(options.commitEnvName),
|
|
12
27
|
env: options.env,
|
|
13
|
-
version: options.version || getVersion(),
|
|
28
|
+
version: composeVersion(options.version || getVersion(), build),
|
|
14
29
|
};
|
|
15
30
|
}
|
|
16
31
|
export function getVersion() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"meta.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/meta.helper.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"meta.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/meta.helper.ts"],"names":[],"mappings":"AA2BA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAG5B,MAAM,CAAC,MAAM,kBAAkB,GAAG,oBAAoB,CAAC;AAGvD,MAAM,CAAC,MAAM,iBAAiB,GAAG,mBAAmB,CAAC;AAGrD,MAAM,CAAC,MAAM,cAAc,GAAG,SAAS,CAAC;AAGxC,IAAI,aAAwC,CAAC;AAgC7C,MAAM,UAAU,SAAS,CAAC,UAAkB,kBAAkB;IAC5D,OAAO,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,cAAc,CAAC;AAChD,CAAC;AAWD,MAAM,UAAU,QAAQ,CAAC,UAAkB,iBAAiB;IAC1D,MAAM,KAAK,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IAClD,OAAO,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACjD,CAAC;AAYD,MAAM,UAAU,cAAc,CAAC,OAAe,EAAE,KAAqB;IACnE,MAAM,WAAW,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACzC,MAAM,KAAK,GAAG,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC5C,IAAI,CAAC,KAAK,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC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,MAAM;gBACR,CAAC;YACH,CAAC;YACD,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;YAC/B,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;gBACnB,MAAM;YACR,CAAC;YACD,GAAG,GAAG,MAAM,CAAC;QACf,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;IAET,CAAC;IACD,OAAO,aAAa,IAAI,cAAc,CAAC;AACzC,CAAC"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Request } from 'express';
|
|
2
|
+
export interface JwtVerificationContext {
|
|
3
|
+
method?: string;
|
|
4
|
+
origin?: string;
|
|
5
|
+
path?: string;
|
|
6
|
+
userAgent?: string;
|
|
7
|
+
}
|
|
8
|
+
export type JwtRejectionKind = 'invalid signature' | 'issuer or audience mismatch' | 'unknown signing key';
|
|
9
|
+
export declare function jwtVerificationContextFromRequest(req: Request | undefined): JwtVerificationContext | undefined;
|
|
10
|
+
export declare function describeRejectedJwt(kind: JwtRejectionKind, token: string, expected: string, context?: JwtVerificationContext, kid?: string): {
|
|
11
|
+
key: string;
|
|
12
|
+
message: string;
|
|
13
|
+
};
|
|
14
|
+
export declare class JwtRejectionThrottle {
|
|
15
|
+
private readonly windowMs;
|
|
16
|
+
private readonly maxKeys;
|
|
17
|
+
private static readonly OVERFLOW_KEY;
|
|
18
|
+
private readonly seen;
|
|
19
|
+
constructor(windowMs?: number, maxKeys?: number);
|
|
20
|
+
take(key: string): null | number;
|
|
21
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { decodeJwt } from 'jose';
|
|
2
|
+
const USER_AGENT_MAX_LENGTH = 120;
|
|
3
|
+
const CLAIM_MAX_LENGTH = 200;
|
|
4
|
+
const KID_MAX_LENGTH = 40;
|
|
5
|
+
function isUnsafeLogCharacter(code) {
|
|
6
|
+
return (code < 0x20 ||
|
|
7
|
+
(code >= 0x7f && code <= 0x9f) ||
|
|
8
|
+
code === 0x2028 ||
|
|
9
|
+
code === 0x2029 ||
|
|
10
|
+
(code >= 0x202a && code <= 0x202e) ||
|
|
11
|
+
(code >= 0x2066 && code <= 0x2069));
|
|
12
|
+
}
|
|
13
|
+
function clean(value, maxLength) {
|
|
14
|
+
let result = '';
|
|
15
|
+
for (const char of String(value)) {
|
|
16
|
+
if (result.length >= maxLength) {
|
|
17
|
+
break;
|
|
18
|
+
}
|
|
19
|
+
const code = char.codePointAt(0) ?? 0;
|
|
20
|
+
result += isUnsafeLogCharacter(code) ? '?' : char;
|
|
21
|
+
}
|
|
22
|
+
return result.slice(0, maxLength);
|
|
23
|
+
}
|
|
24
|
+
function header(req, name) {
|
|
25
|
+
const value = req.headers?.[name];
|
|
26
|
+
return Array.isArray(value) ? value[0] : value;
|
|
27
|
+
}
|
|
28
|
+
export function jwtVerificationContextFromRequest(req) {
|
|
29
|
+
if (!req) {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
const url = req.originalUrl || req.url || '';
|
|
33
|
+
return {
|
|
34
|
+
method: req.method,
|
|
35
|
+
origin: header(req, 'origin'),
|
|
36
|
+
path: url.split('?')[0] || undefined,
|
|
37
|
+
userAgent: header(req, 'user-agent')?.slice(0, USER_AGENT_MAX_LENGTH),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function isoFromEpoch(seconds) {
|
|
41
|
+
return typeof seconds === 'number' ? new Date(seconds * 1000).toISOString() : '-';
|
|
42
|
+
}
|
|
43
|
+
export function describeRejectedJwt(kind, token, expected, context, kid) {
|
|
44
|
+
const parts = [`JWT rejected (${kind})`];
|
|
45
|
+
let key;
|
|
46
|
+
if (kind === 'issuer or audience mismatch') {
|
|
47
|
+
let claims = {};
|
|
48
|
+
try {
|
|
49
|
+
claims = decodeJwt(token);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
}
|
|
53
|
+
const iss = claims.iss === undefined ? '-' : clean(claims.iss, CLAIM_MAX_LENGTH);
|
|
54
|
+
const aud = Array.isArray(claims.aud) ? claims.aud.join(',') : (claims.aud ?? '-');
|
|
55
|
+
const expired = typeof claims.exp === 'number' && claims.exp * 1000 < Date.now();
|
|
56
|
+
parts.push(`expected "${expected}", got iss "${iss}", aud "${clean(aud, CLAIM_MAX_LENGTH)}"`);
|
|
57
|
+
parts.push(`issued ${isoFromEpoch(claims.iat)}, expires ${isoFromEpoch(claims.exp)}${expired ? ' (expired)' : ''}`);
|
|
58
|
+
key = `${kind}|${iss}`;
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
const safeKid = kid === undefined ? '-' : clean(kid, KID_MAX_LENGTH);
|
|
62
|
+
parts.push(`kid "${safeKid}"`);
|
|
63
|
+
key = kind === 'unknown signing key' ? kind : `${kind}|${safeKid}`;
|
|
64
|
+
}
|
|
65
|
+
if (context?.method || context?.path) {
|
|
66
|
+
parts.push(`${clean(context.method ?? '?', 10)} ${clean(context.path ?? '?', CLAIM_MAX_LENGTH)}`);
|
|
67
|
+
}
|
|
68
|
+
if (context?.origin) {
|
|
69
|
+
parts.push(`origin ${clean(context.origin, CLAIM_MAX_LENGTH)}`);
|
|
70
|
+
}
|
|
71
|
+
if (context?.userAgent) {
|
|
72
|
+
parts.push(`ua "${clean(context.userAgent, USER_AGENT_MAX_LENGTH)}"`);
|
|
73
|
+
}
|
|
74
|
+
return { key, message: parts.join('; ') };
|
|
75
|
+
}
|
|
76
|
+
export class JwtRejectionThrottle {
|
|
77
|
+
windowMs;
|
|
78
|
+
maxKeys;
|
|
79
|
+
static OVERFLOW_KEY = '*';
|
|
80
|
+
seen = new Map();
|
|
81
|
+
constructor(windowMs = 60 * 60 * 1000, maxKeys = 500) {
|
|
82
|
+
this.windowMs = windowMs;
|
|
83
|
+
this.maxKeys = maxKeys;
|
|
84
|
+
}
|
|
85
|
+
take(key) {
|
|
86
|
+
const now = Date.now();
|
|
87
|
+
if (!this.seen.has(key) && this.seen.size >= this.maxKeys) {
|
|
88
|
+
for (const [seenKey, seenEntry] of this.seen) {
|
|
89
|
+
if (now - seenEntry.lastAt >= this.windowMs) {
|
|
90
|
+
this.seen.delete(seenKey);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (this.seen.size >= this.maxKeys) {
|
|
94
|
+
key = JwtRejectionThrottle.OVERFLOW_KEY;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const entry = this.seen.get(key);
|
|
98
|
+
if (entry && now - entry.lastAt < this.windowMs) {
|
|
99
|
+
entry.suppressed += 1;
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
this.seen.set(key, { lastAt: now, suppressed: 0 });
|
|
103
|
+
return entry?.suppressed ?? 0;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
//# sourceMappingURL=core-better-auth-jwt-rejection.helper.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core-better-auth-jwt-rejection.helper.js","sourceRoot":"","sources":["../../../../src/core/modules/better-auth/core-better-auth-jwt-rejection.helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAgBjC,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAClC,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAC7B,MAAM,cAAc,GAAG,EAAE,CAAC;AAQ1B,SAAS,oBAAoB,CAAC,IAAY;IACxC,OAAO,CACL,IAAI,GAAG,IAAI;QACX,CAAC,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,CAAC;QAC9B,IAAI,KAAK,MAAM;QACf,IAAI,KAAK,MAAM;QACf,CAAC,IAAI,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,CAAC;QAClC,CAAC,IAAI,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,CAAC,CACnC,CAAC;AACJ,CAAC;AAGD,SAAS,KAAK,CAAC,KAAc,EAAE,SAAiB;IAC9C,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,MAAM,IA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/server-options.interfa
|
|
|
7
7
|
import { ConfigService } from '../../common/services/config.service.js';
|
|
8
8
|
import type { BetterAuthInstance } from './better-auth.config.js';
|
|
9
9
|
import type { IBetterAuthOpenApiDocument } from './core-better-auth-openapi.helper.js';
|
|
10
|
+
import { type JwtRejectionKind, JwtRejectionThrottle, type JwtVerificationContext } from './core-better-auth-jwt-rejection.helper.js';
|
|
10
11
|
import { BetterAuthSessionUser } from './core-better-auth-user.mapper.js';
|
|
11
12
|
export interface SessionResult {
|
|
12
13
|
session: null | {
|
|
@@ -30,6 +31,7 @@ export declare class CoreBetterAuthService implements OnApplicationBootstrap, On
|
|
|
30
31
|
private openApiSchema;
|
|
31
32
|
private unavailableOperations;
|
|
32
33
|
private cachedCookiePrefix;
|
|
34
|
+
protected readonly jwtRejectionThrottle: JwtRejectionThrottle;
|
|
33
35
|
constructor(authInstance: BetterAuthInstance | null, connection?: Connection, resolvedConfig?: IBetterAuth | null, configService?: ConfigService, cookieDomain?: string | null);
|
|
34
36
|
onModuleInit(): Promise<void>;
|
|
35
37
|
onApplicationBootstrap(): Promise<void>;
|
|
@@ -82,7 +84,7 @@ export declare class CoreBetterAuthService implements OnApplicationBootstrap, On
|
|
|
82
84
|
getActiveSessionForUser(userId: string): Promise<SessionResult>;
|
|
83
85
|
protected liveSession(lookup: () => Promise<null | SessionResult>, caller: string): Promise<SessionResult>;
|
|
84
86
|
isUserEmailVerified(email: string): Promise<boolean | null>;
|
|
85
|
-
verifyJwtToken(token: string): Promise<null | {
|
|
87
|
+
verifyJwtToken(token: string, context?: JwtVerificationContext): Promise<null | {
|
|
86
88
|
[key: string]: any;
|
|
87
89
|
email?: string;
|
|
88
90
|
sub: string;
|
|
@@ -98,6 +100,7 @@ export declare class CoreBetterAuthService implements OnApplicationBootstrap, On
|
|
|
98
100
|
}): Promise<boolean>;
|
|
99
101
|
private verifyHs256Token;
|
|
100
102
|
private verifyJwksToken;
|
|
103
|
+
protected reportRejectedJwt(kind: JwtRejectionKind, token: string, context?: JwtVerificationContext, kid?: string): void;
|
|
101
104
|
verifyJwtFromRequest(req: Request, token?: string): Promise<null | {
|
|
102
105
|
[key: string]: any;
|
|
103
106
|
email?: string;
|
|
@@ -14,7 +14,7 @@ var CoreBetterAuthService_1;
|
|
|
14
14
|
import { BadRequestException, Inject, Injectable, Logger, Optional, } from '@nestjs/common';
|
|
15
15
|
import { InjectConnection } from '../../common/persistence/mongo/mongoose-compat.js';
|
|
16
16
|
import { freshSessionMiddleware, requestOnlySessionMiddleware, sensitiveSessionMiddleware, sessionMiddleware, } from 'better-auth/api';
|
|
17
|
-
import { importJWK, jwtVerify } from 'jose';
|
|
17
|
+
import { errors as joseErrors, importJWK, jwtVerify } from 'jose';
|
|
18
18
|
import { isCookiesEnabled, isExposeTokenInBodyEnabled, shouldConvertSessionTokenToJwt, } from '../../common/helpers/cookies.helper.js';
|
|
19
19
|
import { scheduleExpirySweep } from '../../common/persistence/expiry-sweep.js';
|
|
20
20
|
import { isQueryableString } from '../../common/helpers/input.helper.js';
|
|
@@ -26,6 +26,7 @@ import { legacyCredentialAccountIssuer, usesLegacyAccountIssuer } from './core-b
|
|
|
26
26
|
import { BUILT_IN_BETTER_AUTH_PLUGIN_IDS, HANDLER_SESSION_PATHS, isUnavailableOperation, toOpenApiPath, unavailableBetterAuthOperations, } from './core-better-auth-openapi.helper.js';
|
|
27
27
|
import { cachedJwtSession, cachedJwtSessionRecord, rememberJwtSession } from './core-better-auth-jwt-session.cache.js';
|
|
28
28
|
import { isEmailAndPasswordSignInEnabled, isPasskeyConfigured, isTwoFactorConfigured, } from './core-better-auth-sign-in-factors.helper.js';
|
|
29
|
+
import { describeRejectedJwt, JwtRejectionThrottle, jwtVerificationContextFromRequest, } from './core-better-auth-jwt-rejection.helper.js';
|
|
29
30
|
import { isJwtShaped } from './core-better-auth-token.helper.js';
|
|
30
31
|
import { presentSessionTokens } from './core-better-auth-session-token.helper.js';
|
|
31
32
|
import { convertExpressHeaders, parseCookieHeader, sendWebResponse, signCookieValueIfNeeded, } from './core-better-auth-web.helper.js';
|
|
@@ -44,6 +45,7 @@ let CoreBetterAuthService = CoreBetterAuthService_1 = class CoreBetterAuthServic
|
|
|
44
45
|
openApiSchema;
|
|
45
46
|
unavailableOperations;
|
|
46
47
|
cachedCookiePrefix = null;
|
|
48
|
+
jwtRejectionThrottle = new JwtRejectionThrottle();
|
|
47
49
|
constructor(authInstance, connection, resolvedConfig, configService, cookieDomain) {
|
|
48
50
|
this.authInstance = authInstance;
|
|
49
51
|
this.connection = connection;
|
|
@@ -740,7 +742,7 @@ let CoreBetterAuthService = CoreBetterAuthService_1 = class CoreBetterAuthServic
|
|
|
740
742
|
return null;
|
|
741
743
|
}
|
|
742
744
|
}
|
|
743
|
-
async verifyJwtToken(token) {
|
|
745
|
+
async verifyJwtToken(token, context) {
|
|
744
746
|
if (!this.isEnabled() || !this.isJwtEnabled()) {
|
|
745
747
|
return null;
|
|
746
748
|
}
|
|
@@ -759,7 +761,7 @@ let CoreBetterAuthService = CoreBetterAuthService_1 = class CoreBetterAuthServic
|
|
|
759
761
|
payload = await this.verifyHs256Token(token);
|
|
760
762
|
}
|
|
761
763
|
else if (kid) {
|
|
762
|
-
payload = await this.verifyJwksToken(token, kid, alg);
|
|
764
|
+
payload = await this.verifyJwksToken(token, kid, alg, context);
|
|
763
765
|
}
|
|
764
766
|
else {
|
|
765
767
|
this.logger.debug(`JWT verification: unsupported algorithm=${alg} or missing kid`);
|
|
@@ -881,7 +883,7 @@ let CoreBetterAuthService = CoreBetterAuthService_1 = class CoreBetterAuthServic
|
|
|
881
883
|
return null;
|
|
882
884
|
}
|
|
883
885
|
}
|
|
884
|
-
async verifyJwksToken(token, kid, alg) {
|
|
886
|
+
async verifyJwksToken(token, kid, alg, context) {
|
|
885
887
|
const sql = getBetterAuthSqlStore();
|
|
886
888
|
if (!this.connection && !sql) {
|
|
887
889
|
this.logger.debug('JWKS verification failed: no database connection');
|
|
@@ -891,14 +893,14 @@ let CoreBetterAuthService = CoreBetterAuthService_1 = class CoreBetterAuthServic
|
|
|
891
893
|
const jwksCollection = this.connection?.collection('jwks');
|
|
892
894
|
let keyRecord = sql ? await sql.findJwk(kid) : await jwksCollection?.findOne({ id: kid });
|
|
893
895
|
if (!keyRecord && sql) {
|
|
894
|
-
this.
|
|
896
|
+
this.reportRejectedJwt('unknown signing key', token, context, kid);
|
|
895
897
|
return null;
|
|
896
898
|
}
|
|
897
899
|
if (!keyRecord && jwksCollection) {
|
|
898
900
|
const allKeys = await jwksCollection.find({}).toArray();
|
|
899
901
|
const matchingKey = allKeys.find((k) => k.id === kid || k._id?.toString() === kid);
|
|
900
902
|
if (!matchingKey) {
|
|
901
|
-
this.
|
|
903
|
+
this.reportRejectedJwt('unknown signing key', token, context, kid);
|
|
902
904
|
return null;
|
|
903
905
|
}
|
|
904
906
|
keyRecord = matchingKey;
|
|
@@ -922,10 +924,26 @@ let CoreBetterAuthService = CoreBetterAuthService_1 = class CoreBetterAuthServic
|
|
|
922
924
|
return payload;
|
|
923
925
|
}
|
|
924
926
|
catch (error) {
|
|
927
|
+
if (error instanceof joseErrors.JWTClaimValidationFailed && (error.claim === 'iss' || error.claim === 'aud')) {
|
|
928
|
+
this.reportRejectedJwt('issuer or audience mismatch', token, context);
|
|
929
|
+
return null;
|
|
930
|
+
}
|
|
931
|
+
if (error instanceof joseErrors.JWSSignatureVerificationFailed) {
|
|
932
|
+
this.reportRejectedJwt('invalid signature', token, context, kid);
|
|
933
|
+
return null;
|
|
934
|
+
}
|
|
925
935
|
this.logger.debug(`JWKS verification error: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
926
936
|
return null;
|
|
927
937
|
}
|
|
928
938
|
}
|
|
939
|
+
reportRejectedJwt(kind, token, context, kid) {
|
|
940
|
+
const { key, message } = describeRejectedJwt(kind, token, this.getBaseUrl(), context, kid);
|
|
941
|
+
const suppressed = this.jwtRejectionThrottle.take(key);
|
|
942
|
+
if (suppressed === null) {
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
this.logger.warn(suppressed > 0 ? `${message} (${suppressed} more since the last warning)` : message);
|
|
946
|
+
}
|
|
929
947
|
async verifyJwtFromRequest(req, token) {
|
|
930
948
|
if (!token) {
|
|
931
949
|
const authHeader = req.headers.authorization;
|
|
@@ -934,7 +952,7 @@ let CoreBetterAuthService = CoreBetterAuthService_1 = class CoreBetterAuthServic
|
|
|
934
952
|
}
|
|
935
953
|
token = authHeader.substring(7);
|
|
936
954
|
}
|
|
937
|
-
return this.verifyJwtToken(token);
|
|
955
|
+
return this.verifyJwtToken(token, jwtVerificationContextFromRequest(req));
|
|
938
956
|
}
|
|
939
957
|
};
|
|
940
958
|
CoreBetterAuthService = CoreBetterAuthService_1 = __decorate([
|