@lenne.tech/nest-server 12.14.0 → 12.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/rules/better-auth.md +6 -3
- package/.claude/rules/configurable-features.md +1 -0
- package/.claude/rules/persistence.md +23 -0
- package/.claude/rules/testing.md +4 -4
- package/FRAMEWORK-API.md +1 -1
- package/dist/core/common/persistence/sql/mysql/mysql-executor.js +6 -1
- package/dist/core/common/persistence/sql/mysql/mysql-executor.js.map +1 -1
- package/dist/core/common/persistence/sql/mysql/mysql-transport.d.ts +9 -0
- package/dist/core/common/persistence/sql/mysql/mysql-transport.js +42 -0
- package/dist/core/common/persistence/sql/mysql/mysql-transport.js.map +1 -0
- 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/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/docs/choosing-a-database.md +8 -0
- package/migration-guides/12.13.x-to-12.14.x.md +3 -3
- package/migration-guides/12.14.0-to-12.14.1.md +63 -0
- package/migration-guides/12.14.x-to-12.15.x.md +102 -0
- package/package.json +9 -9
- package/src/core/common/helpers/meta.helper.ts +2 -2
- package/src/core/common/persistence/sql/mysql/mysql-executor.ts +8 -1
- package/src/core/common/persistence/sql/mysql/mysql-transport.ts +91 -0
- 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/index.ts +1 -0
|
@@ -644,9 +644,12 @@ statements run in the session the framework set up (strict mode, UTC). On MongoD
|
|
|
644
644
|
`sql-escaper` 1.5.1 on, an object turns into `key = value` pairs only after a bare `SET ?`, which Kysely never writes
|
|
645
645
|
(it writes `col = ?`); before that, `{"name": {"roles": "[\"admin\"]"}}` assigned `roles` — a signed-in user making
|
|
646
646
|
themselves an administrator. The peer range (`>= 3.24.6`; `>= 3.25.0` since 12.13.0, for GHSA-f763-mv98-7rv9)
|
|
647
|
-
guarantees the fixed escaper; never lower it.
|
|
648
|
-
|
|
649
|
-
(
|
|
647
|
+
guarantees the fixed escaper; never lower it. Since 12.15.0 the floor is `>= 3.26.0`: 3.25 and older carry
|
|
648
|
+
GHSA-jxvc-9hcf-fw42 (critical: SQL injection through `query()` on non-UTF-8 connection charsets — Kysely's path),
|
|
649
|
+
GHSA-mxg9-wm8p-75g7 (high: forged packets before the TLS handshake ends) and GHSA-cc6q-ch5m-cffx (the server's RSA key
|
|
650
|
+
fetched from whoever answers). 3.26 fetches that key over a connection without TLS only when allowed, which
|
|
651
|
+
`mysqlKeyRetrievalOption()` decides for every pool the framework opens — Better-Auth's included
|
|
652
|
+
(`.claude/rules/persistence.md` → "Connections to MySQL without TLS").
|
|
650
653
|
|
|
651
654
|
**Sign-up holds a pool connection while it hashes (accepted).** Better-Auth runs its Kysely adapter with transactions
|
|
652
655
|
on a `pg` pool, and `/sign-up/email` hashes the password inside its transaction — on the framework's application pool
|
|
@@ -335,6 +335,7 @@ This pattern is currently applied to:
|
|
|
335
335
|
| Config Endpoint | `configEndpoint` | Explicit Boolean with DERIVED default | **Unset → a project's `GET /config` answers only in `local` / `ci` / `e2e` (`isLocalEnv()`), 404 everywhere else (12.5.0+)**; `true` answers everywhere, `false` nowhere; a non-boolean value counts as not set (`NSC__CONFIG_ENDPOINT=true`). The route lives in project code (the starter's `ServerController`) and returns `configEndpointResponse()`, which throws `NotFoundException` when closed (404, as if the route did not exist; the route's `@Roles(ADMIN)` still answers 401 first) and otherwise the REDACTED configuration (`ConfigService.getRedactedConfig()`). Before 12.5.0 the starter's endpoint returned the database URI, auth secrets and mail password to every administrator, and projects created before the starter redacted kept doing so. Redaction is the one framework masker `redactSecrets()` (`common/helpers/redact-secrets.helper.ts`, moved from the Hub where it remains as `maskConfigDeep`): key patterns (`secret`/`password`/`token`/`credential` anywhere in the name, names ending in `pass` or `key`, `encryption`, `dsn`, `salt`, … — a superset of the pattern the starter used before; `pfx` / `pkcs12` since 12.10.1), every string or `Buffer` holding a PEM private key whatever its key is called (12.10.1 — a certificate login keeps certificate and key in one PEM under `certificate`, which reached `GET /config` in clear text before; a certificate alone stays readable), the password of a connection URI and secret-named URI query parameters, scheme + host + port only for an address under a key ending in `url`/`uri`/`endpoint`/`webhook` (a webhook carries its secret in the path), nested values; below a secret-named key EVERYTHING is masked except booleans; plus `FRAMEWORK_SECRET_FIELDS` and `security.secretFields`. The Hub config panel and the `ConfigService` `warn: true` debug output use the same view. Implementation: `common/helpers/config-endpoint.helper.ts` |
|
|
336
336
|
| Secret Fields Removal | `security.secretFields` | Array | `['password', 'verificationToken', ...]`. A project list is a UNION with the defaults (it can add, never remove). `CheckSecurityInterceptor` strips each field under its SQL column name too since 12.3.1 (`passwordResetToken` and `password_reset_token`): a row read through `store.native()` / `store.raw()` carries snake_case columns, and a route returning it unchanged used to hand every secret but `password` to the client. Pinned by `tests/unit/check-security-secret-columns.spec.ts` (mutation `secret-columns-not-stripped`) |
|
|
337
337
|
| Data Sources | `database` | Explicit Value — absent = today's `mongoose` config | **Absent → the `mongoose` configuration is the only data source, exactly as before; nothing SQL is loaded or installed.** A URL string (`'postgres://…'`) sets the default source (driver from the scheme, `sqlEngine` defaults to `typeorm`; `kysely` and `drizzle` are the alternatives — optional peers, each with `pg`); an object adds `ownerUrl` (default source), `sources` (name → URL or `{ url, ownerUrl, sqlEngine }`) and per-model exceptions (`models`); `false` means no database. Precedence for a model: `database.models` > the `dataSource` of a `CorePersistenceModule.forFeature()` definition > `@PersistedModel({ dataSource })` (read from the definition's `model:` class, otherwise from the decorated class named like the model; two such classes naming different sources refuse to guess) > default. When `database` sets a default and the project ALSO configures `mongoose` explicitly, that MongoDB becomes the source `mongoose` — only the project's own `mongoose` counts, because `CoreModule.forRoot()` always merges a fallback URI. **Since phase 1 (DEV-3829) PostgreSQL sources are wired**: only models registered with `CorePersistenceModule.forFeature()` are routed — **since phase 2 (DEV-3830) that includes the core's own models**: the user model (the reference `UserModule`), tenant memberships and API tokens, whose services switch to the routed store (a service that only received `@InjectModel()` follows its model's store; the Mongoose model of a model routed to SQL refuses every data access with a named error, so a direct `mainDbModel` call cannot split a model's data). **Since phase 3 (DEV-3831) Better-Auth follows the user model**: with the user model (table `users`) on a SQL source, Better-Auth runs its built-in Kysely adapter on that source's application pool — ONE `users` row per user shared with the user model (Better-Auth's own columns `name`, `email_verified`, `image` beside the framework's; its required ones are added nullable, so a row the user model writes alone stays valid), snake_case tables (`session`, `account`, `verification`, `jwks`, `two_factor`, `passkey`), ObjectId-hex ids. Its schema is applied as the OWNER at boot, under the same schema lock and grants as the framework's tables; without `ownerUrl` the application role only verifies and the boot stops while Better-Auth's migrations are pending. The framework's own reads and writes of Better-Auth's data follow it (session lookup by token, token service, JWKS, passkey challenge mappings — as Better-Auth verification values —, the e-mail-verified hook, user mapper, system setup, migration status — counted in SQL —, the MCP OAuth subject's roles); the MongoDB boot steps (indices, account-issuer backfill) are skipped there. Nothing is copied from MongoDB: a project that moves its users brings them over itself. **Since phase 4 (DEV-3832) the remaining core persistence follows too**: the AI module's eleven models and the three MCP OAuth stores (clients, codes, refresh tokens) are registered through `CorePersistenceModule.forFeature()` and run on their routed store (one code path; an upsert is update-then-insert with a retry on a duplicate, `sum()` replaces the budget aggregation, `find(…, { exclude })` the `-field` projection); the S3 and filesystem file metadata are two framework models (`CoreS3File`, `CoreFilesystemFile`, tables `s3_files` / `filesystem_files`) read and written through `fileMetadataCollection()` by the file service, the TUS hand-off and the Hub — GridFS stays MongoDB-only. A collection name with a hyphen becomes a table with an underscore. A TTL (`expires`, `index: { expireAfterSeconds }`) is a plain index on SQL; an **expiry sweep** (`scheduleExpirySweep()`, every 15 min, one replica per interval through a lease in the default SQL source's `lt_locks`, fail-open) deletes the expired rows of every routed TTL model, and — with Better-Auth on SQL — expired sessions and verification values. Nothing relies on it for correctness: every reader checks the expiry (an MCP authorization code older than ten minutes is refused on read on both databases). MongoDB keeps its TTL indexes and gets no sweep. The framework's leases (system-setup claim, cron, migrations) live in the default source: on MongoDB in the 12.0.0 documents (a rolling deploy with older replicas shares them), on SQL in `lt_locks`, namespaced, swept an hour after expiry. With `healthCheck.configs.database` every SQL source answers as `<key>:<source>`; `createMigrationStore(<owner URL>)` keeps the migration state in `lt_migrations` with an advisory run lock, on the first SQL engine installed (the CLI cannot read `database.sqlEngine`), and the Hub refuses to run migrations while that table is empty and the MongoDB collection is not (a `migrate.js` still writing MongoDB); the Hub's Persistence panel shows the routing. a SQL model's table is migrated as the OWNER (`ownerUrl`) when its store is created — without `ownerUrl` the application role only verifies and the boot stops while changes are pending; ONE owner connection per source, released once the application is bootstrapped — and the boot refuses an application role that is superuser, has `BYPASSRLS`, owns (or inherits the owner of) a framework table or may `TRUNCATE` it. Two roles in every environment (plan §3.9). Changes the framework never applies on its own (type change, new unique index, rename collision) stop the boot with the suggested statements; `migrate create <name> --sql` + `runSqlMigration()` apply them after review. **Since phase 5 (DEV-3833, 12.1.0) MongoDB is optional**: `mongoose`, `@nestjs/mongoose` and `mongodb` are optional peers, loaded through `common/persistence/mongo/mongo-packages.ts`; `CoreModule` connects MongoDB only when a source uses it (`usesMongoDb()` — `mongoose` configured explicitly, `database` naming MongoDB, or `database` absent), otherwise `@InjectConnection()` receives `null` and a model token without a connection is a stand-in that refuses data access. A configured MongoDB feature without the packages fails the boot with `MongoPackagesMissingError`. `database: false` runs a service without any database: a registered model's store refuses with the reason, Better-Auth is refused at boot. Proven by `pnpm run check:without-mongodb` (dist, packages hidden) and `check:without-mongodb:package` (the tarball installed without them, publish path). **Since phase 6 (DEV-3848) MySQL 8.4 and MariaDB 11.8 sources are wired** (`mysql://`, `mariadb://` — the scheme must name the server the URL reaches): `mysql2` is an optional peer beside the engine, all three engines run on one pool the framework creates (strict session with backslash escapes, UTC), `MysqlDataStore` writes the statements, the owner grants the application account `SELECT, INSERT, UPDATE, DELETE` on the database once and the boot refuses an application account that may alter, drop, index, trigger or grant; leases, migration state (`createMigrationStore()` / `runSqlMigration()` under `GET_LOCK`), the expiry sweep, health check and Hub work there. **Neither database has row-level security**: tenant isolation is the store's, the boot warns once per source, and native / raw access on a tenant table must filter by tenant itself. **Since 12.1.1 (DEV-3904) Better-Auth runs there too**: its Kysely adapter on the source's `mysql2` pool (the promise wrapper — Better-Auth builds `MysqlDialect` from it), its migrations as the owner under `GET_LOCK`, with the database's default collation switched to `utf8mb4_bin` while it creates a table and restored (`withFrameworkDefaultCollation()`; only on such a run and with a 5 s lock wait, because `ALTER DATABASE` locks every table) — Better-Auth names no collation, and MariaDB refuses a foreign key to `users.id` across collations; the database-level grant covers its tables. 12.1.0 refused it at boot. An indexed text field is `varchar(255)` (longer: 400); a DDL run is not transactional. Still refused with a named `DataSourceConfigError`: a second MongoDB source, and an `ownerUrl` without `url` — what `NSC__DATABASE__OWNER_URL` leaves of a `database` given as a URL string, because the environment merge replaces the string with an object (write `database: { url }`, or set `NSC__DATABASE__URL` too). An update path the model does not declare is dropped on SQL as by MongoDB's strict mode (`CrudService.update()` adds `updatedBy` to every update with a current user). URLs appear in errors and logs as scheme + host only. Implementation: `common/persistence/data-source.config.ts`, `data-source.runtime.ts`, `sql/` (db-agnostic plan §3.9) |
|
|
338
|
+
| MySQL Password Transport | the query string of a `mysql://` `database` URL (`ssl`, `socketPath`, `serverPublicKey`, `allowPublicKeyRetrieval`) | Explicit Value with DERIVED default | **12.15.0.** mysql2 3.26+ fetches the server's RSA key over a connection without TLS only when allowed (GHSA-cc6q-ch5m-cffx); `caching_sha2_password` (MySQL 8.4's default) needs it for the first login after a MySQL restart, so an undecided connection fails with `PUBLIC_KEY_RETRIEVAL_NOT_ALLOWED` after the next restart while every test passes (the server cache is warm). **URL carries one of the four parameters** → it decides, in every environment, and the framework adds nothing (mysql2 keeps an option set in the object over the URL's value, so adding one would turn a project's `false` into `true`). **URL carries none, `local` / `ci` / `e2e`** (`isLocalEnv()`; the configured `env`, else `NODE_ENV`, unset = `local`) → `allowPublicKeyRetrieval: true`. **None, any other environment, `mysql://`** → `MysqlTransportUndecidedError` before anything connects, naming the ways out: `?ssl={"rejectUnauthorized":true,"verifyIdentity":true}` (TLS, recommended; without `verifyIdentity` mysql2 accepts any certificate a trusted CA issued for any domain, and for an IP host it never checks the name), `?serverPublicKey=<PEM>`, `?allowPublicKeyRetrieval=true` (accepts that a host in the network path can read the password), `?allowPublicKeyRetrieval=false` (an account without `caching_sha2_password`). **`mariadb://`** → left alone (`mysql_native_password` by default, measured on 11.8). Applies to every pool `createMysqlExecutor()` opens: application and owner URL, Better-Auth's Kysely adapter, migration state, the migrate CLI. Pinned by `tests/unit/mysql-transport.spec.ts` and `tests/persistence-mysql-executor.e2e-spec.ts` (flushes privileges before each login; mutations `mysql-transport-undecided-deployed-accepted`, `mysql-transport-url-overridden`, `mysql-pool-key-retrieval-dropped`). Implementation: `common/persistence/sql/mysql/mysql-transport.ts` |
|
|
338
339
|
| Multi-Tenancy | `multiTenancy` | Presence Implies Enabled | **`excludeSchemas` is an OFF SWITCH for isolation, per model** — a listed schema gets no tenant filter at all; since 11.35.0 the plugin WARNS once per model when the excluded schema declares `tenantId` (i.e. was built for isolation). The framework's own docs recommended `['User', 'Session']` until then; that is withdrawn — it is only right for the global-user model. Since 11.35.0 GraphQL operations over the WEBSOCKET also run inside a `RequestContext` (`CoreModule` installs a context-aware `execute`/`subscribe` pair inside `subscriptions`, where `ApolloDriver` forwards it): the tenant comes from the handshake header validated against an active membership, else from the subscriber's memberships, and an unresolvable tenant leaves the safety net to refuse the read rather than returning everything. `headerName: 'x-tenant-id'`, `membershipModel: 'TenantMember'`, `adminBypass: true`, `excludeSchemas: []`, `roleHierarchy: { member: 1, manager: 2, owner: 3 }`, `cacheTtlMs: 30000` (0 disables, process-local). System roles (`S_EVERYONE`, `S_USER`, `S_VERIFIED`) are checked as OR alternatives before real roles; method-level system roles take precedence; membership validated for context when system role grants access + header present. Hierarchy roles use level comparison, normal roles use exact match. Use `DefaultHR` or `createHierarchyRoles()` for type-safe role constants. Bypass: `RequestContext.runWithBypassTenantGuard()`. Cache invalidation: `invalidateUser(userId)` / `invalidateAll()` are **instance** methods on the singleton `CoreTenantGuard` — inject it and call `this.tenantGuard?.invalidateUser(userId)`, never `CoreTenantGuard.invalidateUser(...)` (there is no static). With `redis` configured, both additionally BROADCAST the invalidation to every replica (`<keyPrefix>:tenant-cache:invalidate` pub/sub); without Redis they clear the local process only, so other replicas stay stale until `cacheTtlMs`. A received broadcast clears locally without re-publishing. **`isTenantActive` (11.42.0)**: optional hook `(tenantId, { connection, store }) => boolean \| Promise<boolean>`, absent = every tenant active (no change). `store(modelName)` (12.x, db-agnostic) is the data store of a model registered with `CorePersistenceModule.forFeature()`, wherever `database` routes it, and THROWS for any other model — an `undefined` would read as "active" in a hook written with `?.` and open every deactivated tenant. Asked AFTER the membership check on every path that establishes a tenant: 403 on header paths and for tenant API tokens, no enrichment on `S_EVERYONE`, dropped from the header-less tenant list, no tenant for a NEW WebSocket subscription, and since 11.42.3 an OPEN one is closed with 4403 on `invalidateTenant()` (or at its next event once `graphQl.subscriptionRevalidationMs` has passed — see the GraphQL Subscription Re-check row); an admin under `adminBypass` is exempt (someone must be able to switch it back on). Only `false` deactivates. Cached for `cacheTtlMs`; `invalidateTenant(tenantId)` clears and broadcasts (`{ scope: 'tenant' }`) — since 12.3.0 together with the tenant's cached memberships and every cached tenant list holding it, so memberships removed without `invalidateUser()` (a deleted tenant) stop counting at once rather than after `cacheTtlMs` (a tenant switched off through `isTenantActive` was already refused at once, its answer being cleared). **Removing a tenant (12.3.0)**: `CoreTenantService.purgeTenantData(tenantId, { dryRun?, exclude? })` first ends every way in — the memberships (`deleteAllMembers()`) and the tenant's API tokens, which need no member — then deletes, in batches of 1000 ids, every registered model with a `tenantId` path (MongoDB and SQL), the core references without one (the AI settings with `scope: 'tenant'`) and the AI connections — one only this tenant could use is deleted, from a shared one the tenant is removed (an empty `tenantIds` means every tenant). `excludeSchemas` and `exclude` are left out, so are users and files; the protected `purgeTenantRecords()` is where a project adds its own references. A function, so `config.env.ts` only — not reachable through `NSC__*`. **`adminBypass: false` (11.42.0)** additionally withholds two things that went around it: `CoreUserService.update()` refuses changing another account's e-mail or password (`assertCredentialChangeAllowed()`, administrator targets included — promote-then-change — system work without a current user exempt), and the AI tool registry grants no ADMIN bypass, and (12.13.0) the `file.access: 'tenant'` preset reads a tenant's files for an administrator only through an active membership. **`selectionCookie` (12.13.0)**: Boolean Shorthand, absent = off. `true` / `{}` / `{ name }`: the tenant guard writes `lt-tenant-id` (`__Host-` prefixed where cookies are `Secure`, the auth-cookie rule; HttpOnly, SameSite=Lax, Path=/, no Domain, session cookie) whenever a request's tenant header passed its check, never for API tokens. Read only on routes with `@ResolveTenantSelection()` (the file controller and resolver), after access was granted and when no tenant was set: header (foreign → 403, on a public route no tenant) → cookie (no active membership → ignored and cleared) → the only active membership; several and no selection → no tenant. Not `lt-tenant` (nuxt-extensions' app cookie, one host behind `apiProxy`). Implementation: `core-tenant-selection.helper.ts`, `CoreTenantGuard.completeTenantSelection()` |
|
|
339
340
|
| GraphQL Subscription Re-check | `graphQl.subscriptionRevalidationMs` | Numeric — `0` = STRICTEST, `false` = off, invalid → default (a fifth shape: Family C's "invalid never means unbounded", but `0` asks for MORE checking, not less) | **30000 since 11.42.3.** Before, a WebSocket was authorized once, at the handshake, and every event and operation on it ran on that snapshot until the client reconnected. Every connection a `CoreModule` `onConnect` accepts is now registered (`registerWsConnection()`) and re-checked — at once when an invalidation names it (`CoreTenantGuard.invalidateUser()` / `invalidateTenant()` / `invalidateAll()`, `CoreUserService.setRoles()` and role/verification `update()`s, the legacy password reset, and Better-Auth deleting a session through `wsSessionRevocationPlugin()`), and otherwise before the next event or operation once the last check is older than this value. The check re-runs the handshake's own authentication (session store, Better-Auth JWT signature/expiry, or for legacy tokens `CoreAuthService.verifyJwt()` — signature/expiry, verified on the WebSocket since 11.42.3 — plus the device binding) and the tenant resolution; any difference in user id, roles, verification state or tenant scope closes the socket with **4403**, which the graphql-ws client retries — the user continues with current rights or is refused at the handshake. `0` re-checks on every event and operation (one session lookup each); `false` switches only the TIME-based check off, invalidations still apply. Process-local registry: an invalidation reaches other replicas only where a Redis broadcast carries it — the tenant guard's (memberships, tenants) and, since 12.1.1, the Better-Auth user mapper's (`invalidateUserCache()`: roles and verification of IAM users); everything else is bounded by the interval. A project that replaces `onConnect` through `graphQl.driver.subscriptions` must call `registerWsConnection()` itself to keep this. An HTTP stream (SSE) of a project's own registers with `registerHttpStream()` (12.11.0): re-checked in place like a WebSocket when its Better-Auth credential can be run again, ended on every re-check otherwise. Implementation: `common/helpers/graphql-ws-connection.helper.ts` |
|
|
340
341
|
| API Tokens | `apiTokens` | Boolean Shorthand + Presence Implies Enabled — absent = off | `prefix: 'ltt'`, `scopes: []` (vocabulary; empty = no token creatable, boot warning), `manageRole`: highest hierarchy role, `maxAssertionLifetimeSeconds: 900` (invalid → default, never unbounded — Family C), `rateLimit: { max: 600, windowSeconds: 60 }` per token (**on by default**, `false` disables; Redis-shared when configured), `userTokens: true`, `tenantTokens: true` (effective only with `multiTenancy`), `encryptionKey` → `SECRETS_ENCRYPTION_KEY` → dev default (boot FAILS in production/staging). Top-level, NOT under `multiTenancy`: user tokens must work without it. **Deny by default**: every guard refuses a token on a route without `@ApiTokenScopes()`, public routes included, via ONE shared function (`enforceApiTokenRoute`) called BEFORE each guard's public-route shortcut. USER tokens act as their user with global roles REMOVED (no admin bypass); TENANT tokens act with the lowest hierarchy role in their own tenant, and a route guarded ONLY by `S_SELF` / `S_CREATOR` refuses them (a tenant token is nobody's self — skipping those roles would grant for any target). A tenant token depends on no member, so it outlives an off-boarded or deleted tenant until the project calls `deleteAllForTenant()` or `CoreTenantService.purgeTenantData()`. The boot refuses a hierarchy in which that lowest role reaches `manageRole`. A prefixed credential that fails answers 401 on every route (not anonymous); `CoreBetterAuthMiddleware` skips prefixed credentials entirely, cookie fallback included. A password reset that ends the user's sessions ends their USER tokens too (legacy reset always; IAM reset while `betterAuth.emailAndPassword.revokeSessionsOnPasswordReset` is on), wired through `core-api-token.registry.ts` so neither reset path imports the optional module. Implementation: `src/core/modules/api-token/` |
|
|
@@ -82,6 +82,29 @@ On MySQL / MariaDB a text field that is part of an index is `varchar(255)` (a lo
|
|
|
82
82
|
prefix when it is a lookup index and is refused when unique. DDL commits on its own there: a run is serialized by
|
|
83
83
|
`GET_LOCK`, not a transaction, and a failed change leaves the statements before it applied.
|
|
84
84
|
|
|
85
|
+
## Connections to MySQL without TLS (12.15.0)
|
|
86
|
+
|
|
87
|
+
MySQL 8.4 signs accounts in with `caching_sha2_password`. While the server caches the account a scrambled proof
|
|
88
|
+
suffices; the first login after a restart (or `FLUSH PRIVILEGES`, a password change) needs the password, which a client
|
|
89
|
+
without TLS encrypts with the server's RSA key. mysql2 3.26+ fetches that key only when allowed
|
|
90
|
+
(GHSA-cc6q-ch5m-cffx) and otherwise fails with `PUBLIC_KEY_RETRIEVAL_NOT_ALLOWED` — after the next MySQL restart, not
|
|
91
|
+
when it is tested. Every pool the framework opens goes through `createMysqlExecutor()`, which asks
|
|
92
|
+
`mysqlKeyRetrievalOption()` (`sql/mysql/mysql-transport.ts`):
|
|
93
|
+
|
|
94
|
+
| The URL carries … | Result |
|
|
95
|
+
|---|---|
|
|
96
|
+
| `ssl`, `socketPath`, `serverPublicKey` or `allowPublicKeyRetrieval` | the URL decides, in every environment |
|
|
97
|
+
| nothing, `local` / `ci` / `e2e` | the framework adds `allowPublicKeyRetrieval: true` (nobody sits in that network path) |
|
|
98
|
+
| nothing, any other environment, `mysql://` | boot refused with `MysqlTransportUndecidedError` naming the ways out |
|
|
99
|
+
| nothing, any other environment, `mariadb://` | left alone (`mysql_native_password` by default, no RSA key) |
|
|
100
|
+
|
|
101
|
+
| Do | Never |
|
|
102
|
+
|---|---|
|
|
103
|
+
| Open MySQL connections through `createSqlExecutor()` / the data store | A pool of your own without the same decision — it boots and fails after the next MySQL restart |
|
|
104
|
+
| Let the URL decide (`?ssl={"rejectUnauthorized":true,"verifyIdentity":true}`, `?allowPublicKeyRetrieval=false` for an account without RSA) | Set `allowPublicKeyRetrieval` in the options object next to a URL: mysql2 keeps the object's value over the URL's, so the project's `false` would turn into `true` |
|
|
105
|
+
| Recommend TLS with `verifyIdentity` | `{"rejectUnauthorized":true}` alone: mysql2 checks the host name only with `verifyIdentity`, so any certificate a trusted CA issued for any domain passes, and the password goes to whoever presents one. For an IP host it skips the name check altogether: only a private `ca` protects that connection |
|
|
106
|
+
| Open direct test connections to MySQL with `allowPublicKeyRetrieval: true` (`tests/helpers/mysql-test-db.ts`) | Rely on a warm server cache in a test — the e2e case flushes privileges first (mutation `mysql-pool-key-retrieval-dropped`) |
|
|
107
|
+
|
|
85
108
|
## Updates on MySQL / MariaDB
|
|
86
109
|
|
|
87
110
|
Two operators on one path, or on a path and a path inside it, are refused (`Updating the path … would create a
|
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 556 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 816 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 —
|
|
@@ -509,9 +509,9 @@ exactly the environment where the answer matters.
|
|
|
509
509
|
|
|
510
510
|
### The cost is vitest's cold start, not the tests
|
|
511
511
|
|
|
512
|
-
Worth knowing before optimising the wrong thing: the specs behind all
|
|
512
|
+
Worth knowing before optimising the wrong thing: the specs behind all 260 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, 816 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-06 (v12.15.0)
|
|
4
4
|
> File: `FRAMEWORK-API.md` — compact, machine-readable API surface for Claude Code
|
|
5
5
|
|
|
6
6
|
## CoreModule.forRoot()
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { Logger } from '@nestjs/common';
|
|
2
2
|
import { MYSQL_SESSION_SQL, mysqlConnectionOptions, mysqlResult, mysqlStatementParts, toMysqlStatement, } from './mysql-session.js';
|
|
3
|
+
import { mysqlKeyRetrievalOption } from './mysql-transport.js';
|
|
3
4
|
const logger = new Logger('SqlPool');
|
|
4
5
|
export async function createMysqlExecutor(options) {
|
|
6
|
+
mysqlKeyRetrievalOption(options.url, options.variant);
|
|
5
7
|
switch (options.engine) {
|
|
6
8
|
case 'drizzle':
|
|
7
9
|
return createDrizzleExecutor(options);
|
|
@@ -27,7 +29,10 @@ async function loadMysql2() {
|
|
|
27
29
|
}
|
|
28
30
|
function createPool(mysql2, options) {
|
|
29
31
|
const url = options.url.replace(/^mariadb:/i, 'mysql:');
|
|
30
|
-
const pool = mysql2.createPool(
|
|
32
|
+
const pool = mysql2.createPool({
|
|
33
|
+
...mysqlConnectionOptions(url, options.maxConnections ?? 10),
|
|
34
|
+
...mysqlKeyRetrievalOption(options.url, options.variant),
|
|
35
|
+
});
|
|
31
36
|
pool.on('connection', (connection) => {
|
|
32
37
|
connection.query(MYSQL_SESSION_SQL, (error) => {
|
|
33
38
|
if (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mysql-executor.js","sourceRoot":"","sources":["../../../../../../src/core/common/persistence/sql/mysql/mysql-executor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAIxC,OAAO,EACL,iBAAiB,EACjB,sBAAsB,EACtB,WAAW,EACX,mBAAmB,EAEnB,gBAAgB,GACjB,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"mysql-executor.js","sourceRoot":"","sources":["../../../../../../src/core/common/persistence/sql/mysql/mysql-executor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAIxC,OAAO,EACL,iBAAi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AAE;YACxB,MAAM,aAAa,CAAC,KAAK,CAAC,CAAC;QAC7B,CAAC,CAAC;QACN,OAAO,EAAE,OAAO,CAAC,OAAO;KACzB,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { MysqlVariant } from './mysql-session.js';
|
|
2
|
+
export declare const MYSQL_TRANSPORT_PARAMETERS: readonly ["allowPublicKeyRetrieval", "serverPublicKey", "socketPath", "ssl"];
|
|
3
|
+
export declare class MysqlTransportUndecidedError extends Error {
|
|
4
|
+
readonly name = "MysqlTransportUndecidedError";
|
|
5
|
+
}
|
|
6
|
+
export declare function currentMysqlEnvironment(): string;
|
|
7
|
+
export declare function mysqlKeyRetrievalOption(url: string, variant: MysqlVariant, env?: string | undefined): {
|
|
8
|
+
allowPublicKeyRetrieval?: true;
|
|
9
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { isLocalEnv } from '../../../helpers/cookies.helper.js';
|
|
2
|
+
import { ConfigService } from '../../../services/config.service.js';
|
|
3
|
+
import { redactUrl } from '../../data-source.config.js';
|
|
4
|
+
export const MYSQL_TRANSPORT_PARAMETERS = ['allowPublicKeyRetrieval', 'serverPublicKey', 'socketPath', 'ssl'];
|
|
5
|
+
export class MysqlTransportUndecidedError extends Error {
|
|
6
|
+
name = 'MysqlTransportUndecidedError';
|
|
7
|
+
}
|
|
8
|
+
export function currentMysqlEnvironment() {
|
|
9
|
+
return ConfigService.configFastButReadOnly?.env || process.env.NODE_ENV || 'local';
|
|
10
|
+
}
|
|
11
|
+
export function mysqlKeyRetrievalOption(url, variant, env = currentMysqlEnvironment()) {
|
|
12
|
+
const stated = statedTransportParameters(url);
|
|
13
|
+
if (stated === null || stated.length > 0) {
|
|
14
|
+
return {};
|
|
15
|
+
}
|
|
16
|
+
if (isLocalEnv(env)) {
|
|
17
|
+
return { allowPublicKeyRetrieval: true };
|
|
18
|
+
}
|
|
19
|
+
if (variant === 'mysql') {
|
|
20
|
+
throw new MysqlTransportUndecidedError(`The MySQL source ${redactUrl(url)} does not say how the password travels, and the environment ` +
|
|
21
|
+
`"${env ?? ''}" is not local. mysql2 fetches the server's RSA key over a connection without TLS only when ` +
|
|
22
|
+
'allowed, so the first login after the next MySQL restart would fail with PUBLIC_KEY_RETRIEVAL_NOT_ALLOWED. ' +
|
|
23
|
+
'Add one parameter to the URL: ?ssl={"rejectUnauthorized":true,"verifyIdentity":true} (TLS, recommended: verifyIdentity makes mysql2 ' +
|
|
24
|
+
'check that the certificate names the URL host, which must be a DNS name; with your CA add "ca":"<PEM>"), ' +
|
|
25
|
+
"?serverPublicKey=<PEM of the server's RSA public key>, " +
|
|
26
|
+
'?allowPublicKeyRetrieval=true (accepts that a host in the network path can read the password), or ' +
|
|
27
|
+
'?allowPublicKeyRetrieval=false when the account does not use caching_sha2_password. ' +
|
|
28
|
+
'See migration-guides/12.14.x-to-12.15.x.md.');
|
|
29
|
+
}
|
|
30
|
+
return {};
|
|
31
|
+
}
|
|
32
|
+
function statedTransportParameters(url) {
|
|
33
|
+
let parameters;
|
|
34
|
+
try {
|
|
35
|
+
parameters = new URL(url).searchParams;
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
return MYSQL_TRANSPORT_PARAMETERS.filter((name) => parameters.has(name));
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=mysql-transport.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mysql-transport.js","sourceRoot":"","sources":["../../../../../../src/core/common/persistence/sql/mysql/mysql-transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AACpE,OAAO,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AA0BxD,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,yBAAyB,EAAE,iBAAiB,EA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AI,CAAC,CAAC,CAAC;AAC3E,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,IAAI,IAAI,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QACjC,IAAI,MAAM,CAAC,MAAM,IAAI,SAAS,EAAE,CAAC;YAC/B,MAAM;QACR,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QACtC,MAAM,IAAI,oBAAoB,CAAC,IAAI,CAAC,CAAC,CA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AC,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YAC1D,KAAK,MAAM,CAAC,OAAO,EAAE,SAAS,CAAC,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;gBAC7C,IAAI,GAAG,GAAG,SAAS,CAAC,MAAM,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;oBAC5C,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;gBAC5B,CAAC;YACH,CAAC;YACD,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;gBACnC,GAAG,GAAG,oBAAoB,CAAC,YAAY,CAAC;YAC1C,CAAC;QACH,CAAC;QACD,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACjC,IAAI,KAAK,IAAI,GAAG,GAAG,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;YAChD,KAAK,CAAC,UAAU,IAAI,CAAC,CAAC;YACtB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,EAAE,CAAC,EAAE,CAAC,CAAC;QACnD,OAAO,KAAK,EAAE,UAAU,IAAI,CAAC,CAAC;IAChC,CAAC"}
|
|
@@ -7,6 +7,7 @@ import { type IBetterAuth } from '../../common/interfaces/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([
|