@lenne.tech/nest-server 12.6.13 → 12.6.14

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.
@@ -323,7 +323,7 @@ This pattern is currently applied to:
323
323
  | Response Model Interceptor | `security.responseModelInterceptor` | Boolean Shorthand | `true` (enabled), `debug: false` |
324
324
  | Translate Response Interceptor | `security.translateResponseInterceptor` | Boolean Shorthand | `true` (enabled) |
325
325
  | Mongoose CastError Filter | `security.mongooseCastErrorFilter` | Explicit Boolean — **safe default** | **`true` since 11.42.16.** `MongooseCastErrorFilter`, registered by `CoreModule` as `APP_FILTER` (so `main.ts` and `Test.createTestingModule()` setups need nothing). A malformed id reached Mongoose and its `CastError` — not an `HttpException` — escaped every `@Catch(HttpException)` filter, so `GET /users/<malformed-id>` and every other `:id` route answered **500**. The filter decides by WHERE the failing value came from: a route parameter or a top-level GraphQL argument → **404** `ErrorCode.RESOURCE_NOT_FOUND` (answered like an unknown id); the query string, an update or filter body, or a nested GraphQL input → **400** `ErrorCode.INVALID_FIELD_FORMAT [<path>]`; a value the request does not contain (a broken stored id, a server-computed value) → **stays a 500**, with Nest's own body and log line (context `ExceptionsHandler`), because that is a data or code defect monitoring must keep seeing — relabelling it as a client error is the mistake the refusal tests pin (mutations `cast-error-server-value-relabelled-*`). Only primitives and arrays of primitives (`$in`) are matched: an object cast as a whole yields no candidates, so its inner strings cannot match the body by coincidence. Never sends the Mongoose message (it names the model). REST bodies use the `HttpExceptionLogFilter` shape (`{ ...exception }`). A project's own catch-all filter via `app.useGlobalFilters()` is consulted first and wins. Covers casts Mongoose raises while running a QUERY or an UPDATE (`findById`, filters, `findByIdAndUpdate` — `CrudService.update()`). NOT covered, both stay a 500: a malformed id in a document being CREATED (`save()` / `create()` / `insertMany()` — `CrudService.create()`), which Mongoose reports as a `ValidationError` wrapping the CastError (validate in the input: `validator: () => [IsMongoId()]`); and a `BSONError` from `new Types.ObjectId(bad)`, which carries no value (check the id in the service, `CoreFileService.isMalformedFileId()`). `false` restores the 500. Implementation: `common/filters/mongoose-cast-error.filter.ts` |
326
- | 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), 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` |
326
+ | 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.6.14), every string or `Buffer` holding a PEM private key whatever its key is called (12.6.14 — 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` |
327
327
  | 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`) |
328
328
  | 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) |
329
329
  | 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 |
@@ -410,7 +410,7 @@ pnpm run check:mutations -- --id=<id> # one mutation
410
410
  pnpm run check:mutations -- --list # the registry, without running anything
411
411
  pnpm run check:mutations -- --allow-dirty # when the fix and its evidence share a working tree
412
412
  pnpm run check:mutations -- --jobs=4 # N mutations at a time (default: 2, or 4 on >=12 cores)
413
- pnpm run check:mutations -- --no-infra # only the 427 that need no MongoDB
413
+ pnpm run check:mutations -- --no-infra # only the 437 that need no MongoDB
414
414
  pnpm run check:mutations -- --since=<ref> # only mutations touching files changed since <ref>
415
415
  pnpm run check:mutations -- --shard=2/4 # this job's quarter of the selection (CI splits the full run)
416
416
  ```
@@ -430,7 +430,7 @@ when the registry, a vitest config or a setup file changed, since those can move
430
430
  commit, and in CI alongside the publish without blocking it. The price of caching is a cache that
431
431
  has to model each spec's full dependency closure correctly, and getting that wrong produces a stale
432
432
  PASS for a test that has since gone vacuous — exactly what the gate is there to prevent. Bad trade
433
- at 666 mutations.
433
+ at 676 mutations.
434
434
 
435
435
  **Decided 2026-10-03 (repo owner): keep the full run.** Measured at 128 mutations, the CI job for
436
436
  11.41.6 took **14 minutes**. The trigger to revisit is that wall time, not the mutation count —
@@ -503,7 +503,7 @@ exactly the environment where the answer matters.
503
503
 
504
504
  Worth knowing before optimising the wrong thing: the specs behind all 239 e2e mutations add up to
505
505
  **~40 seconds**. The step takes ~740s. The remaining ~700s is paying vitest's startup — process
506
- spawn, transform, module graph, mongod connect, DB create and drop — once per mutation, 666 times.
506
+ spawn, transform, module graph, mongod connect, DB create and drop — once per mutation, 676 times.
507
507
  That work is largely single-threaded I/O and barely scales with cores: the full registry measures
508
508
  **744s on a 12-core laptop and 777s on a 4-vCPU CI runner**.
509
509
 
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-11-15 (v12.6.13)
3
+ > Auto-generated from source code as of 2026-11-19 (v12.6.14)
4
4
  > File: `FRAMEWORK-API.md` — compact, machine-readable API surface for Claude Code
5
5
 
6
6
  ## CoreModule.forRoot()
@@ -10,6 +10,16 @@ function ignoreStream(stream) {
10
10
  stream.on('error', () => { });
11
11
  stream.resume();
12
12
  }
13
+ function arrayGrowth(container, key) {
14
+ const index = Number.parseInt(key, 10);
15
+ if (index.toString() !== key || !Number.isInteger(index) || index < 0) {
16
+ return 0;
17
+ }
18
+ if (container === undefined) {
19
+ return index + 1;
20
+ }
21
+ return Array.isArray(container) ? Math.max(0, index + 1 - container.length) : 0;
22
+ }
13
23
  export function processGraphQlUploadRequest(request, response, { maxFieldSize = 1000000, maxFileSize = Infinity, maxFiles = Infinity } = {}) {
14
24
  return new Promise((resolve, reject) => {
15
25
  let released;
@@ -115,6 +125,13 @@ export function processGraphQlUploadRequest(request, response, { maxFieldSize =
115
125
  if (key === '__proto__') {
116
126
  throw new TypeError('Object path has a `__proto__` key.');
117
127
  }
128
+ const growth = arrayGrowth(pathValue, key);
129
+ if (growth > 0) {
130
+ mapKeyCount += growth;
131
+ if (mapKeyCount > GRAPHQL_UPLOAD_MAX_MAP_KEYS) {
132
+ throw new RangeError(`The map's arrays have more than ${GRAPHQL_UPLOAD_MAX_MAP_KEYS} elements.`);
133
+ }
134
+ }
118
135
  if (keyIndex < keys.length - 1) {
119
136
  pathValue = objectPath.get(pathValue, [key]);
120
137
  if (pathValue instanceof Upload) {
@@ -1 +1 @@
1
- {"version":3,"file":"graphql-upload.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/graphql-upload.helper.ts"],"names":[],"mappings":"AA2DA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,MAAM,MAAM,2BAA2B,CAAC;AAC/C,OAAO,WAAW,MAAM,aAAa,CAAC;AACtC,OAAO,UAAU,MAAM,aAAa,CAAC;AAMrC,MAAM,kCAAkC,GAAG,+DAA+D,CAAC;AAO3G,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC;AAW/C,MAAM,CAAC,MAAM,2BAA2B,GAAG,MAAM,CAAC;AAkClD,SAAS,YAAY,CAAC,MAAgB;IAEpC,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IAG7B,MAAM,CAAC,MAAM,EAAE,CAAC;AAClB,CAAC;AAaD,MAAM,UAAU,2BAA2B,CACzC,OAAwB,EACxB,QAAwB,EACxB,EAAE,YAAY,GAAG,OAAO,EAAE,WAAW,GAAG,QAAQ,EAAE,QAAQ,GAAG,QAAQ,KAAyC,EAAE;IAEhH,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,IAAI,QAAiB,CAAC;QACtB,IAAI,SAA8B,CAAC;QACnC,IAAI,UAAmC,CAAC;QACxC,IAAI,cAA6C,CAAC;QAClD,IAAI,GAAwB,CAAC;QAE7B,MAAM,MAAM,GAAG,MAAM,CAAC;YACpB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,eAAe,EAAE,MAAM;YACvB,MAAM,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C,CAAC;QACpB,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,EAAE;YAC1B,QAAQ,GAAG,IAAI,CAAC;YAEhB,IAAI,GAAG,EAAE,CAAC;gBACR,KAAK,MAAM,MAAM,IAAI,GAAG,CAAC,MAAM,EAAE,EAAE,CAAC;oBAClC,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;wBAEf,MAAM,CAAC,IAA4B,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC;oBAC3D,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,EAAE;YACzB,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC;gBAC3B,IAAI,CAAC,WAAW,CAAC,GAAG,EAAE,yDAAyD,CAAC,CAAC,CAAC;YACpF,CAAC;QACH,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -1,4 +1,5 @@
1
- const SECRET_KEY_PATTERN = /secret|passwd|password|passphrase|credential|api[-_]?key|access[-_]?key|private[-_]?key|encryption|token|\bpass\b|pass$|dsn|salt|key$|(^|[^a-z])key([^a-z]|$)/i;
1
+ const SECRET_KEY_PATTERN = /secret|passwd|password|passphrase|credential|api[-_]?key|access[-_]?key|private[-_]?key|encryption|token|\bpass\b|pass$|dsn|salt|key$|(^|[^a-z])key([^a-z]|$)|pfx|pkcs12/i;
2
+ const PRIVATE_KEY_PEM_PATTERN = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY[A-Z ]*-----/i;
2
3
  const URL_KEY_PATTERN = /(url|uri|endpoint|webhook)$/i;
3
4
  const URI_PARTS_PATTERN = /^([a-z][a-z0-9+.-]*:\/\/[^/?#]*)(.*)$/is;
4
5
  const URI_USERINFO_PATTERN = /^([a-z][a-z0-9+.-]*:\/\/).*@/is;
@@ -55,10 +56,14 @@ function redactValue(value, underSecretKey, extra, key) {
55
56
  if (typeof value !== 'string') {
56
57
  return value;
57
58
  }
59
+ if (PRIVATE_KEY_PEM_PATTERN.test(value)) {
60
+ return REDACTED_VALUE;
61
+ }
58
62
  return URL_KEY_PATTERN.test(key) ? redactUrl(value) : redactString(value);
59
63
  }
60
64
  if (value instanceof Date || Buffer.isBuffer(value)) {
61
- return underSecretKey ? REDACTED_VALUE : value;
65
+ const holdsPrivateKey = Buffer.isBuffer(value) && PRIVATE_KEY_PEM_PATTERN.test(value.toString('latin1'));
66
+ return underSecretKey || holdsPrivateKey ? REDACTED_VALUE : value;
62
67
  }
63
68
  if (Array.isArray(value)) {
64
69
  return value.map((item) => redactValue(item, underSecretKey, extra, key));
@@ -1 +1 @@
1
- {"version":3,"file":"redact-secrets.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/redact-secrets.helper.ts"],"names":[],"mappings":"AA8BA,MAAM,kBAAkB,GACtB,gKAAgK,CAAC;AAOnK,MAAM,eAAe,GAAG,8BAA8B,CAAC;AAGvD,MAAM,iBAAiB,GAAG,yCAAyC,CAAC;AAMpE,MAAM,oBAAoB,GAAG,gCAAgC,CAAC;AAc9D,MAAM,sBAAsB,GAAG,oEAAoE,CAAC;AAOpG,MAAM,uBAAuB,GAAG,+BAA+B,CAAC;AAGhE,MAAM,CAAC,MAAM,cAAc,GAAG,KAAK,CAAC;AAQpC,MAAM,CAAC,MAAM,uBAAuB,GAAsB;IACxD,UAAU;IACV,mBAAmB;IACnB,oBAAoB;IACpB,6BAA6B;IAC7B,eAAe;IACf,YAAY;IACZ,iBAAiB;CAClB,CAAC;AAgBF,MAAM,UAAU,aAAa,CAAI,KAAQ,EAAE,kBAAqC,EAAE;IAChF,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,GAA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C,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,EAAE,cAAc,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC;IAC5E,CAAC;IAED,MAAM,GAAG,GAA4B,EAAE,CAAC;IACxC,KAAK,MAAM,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAgC,CAAC,EAAE,CAAC;QAChF,GAAG,CAAC,QAAQ,CAAC,GAAG,WAAW,CAAC,IAAI,EAAE,cAAc,IAAI,WAAW,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;IACrG,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -9,9 +9,64 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  };
10
10
  import { Plugin } from '@nestjs/apollo';
11
11
  import { GraphQLSchemaHost } from '@nestjs/graphql';
12
- import { GraphQLError } from 'graphql';
13
- import { fieldExtensionsEstimator, getComplexity, simpleEstimator } from 'graphql-query-complexity';
12
+ import { getVariableValues, GraphQLError, Kind, TypeInfo, ValidationContext, visit, visitWithTypeInfo } from 'graphql';
13
+ import { createComplexityRule, fieldExtensionsEstimator, simpleEstimator } from 'graphql-query-complexity';
14
14
  import { ConfigService } from '../services/config.service.js';
15
+ const VARIABLE_COERCION_MAX_ERRORS = 1;
16
+ const COMPLEXITY_ANALYSIS_MAX_VARIABLE_WORK = 250_000;
17
+ function variableVisits(definitions) {
18
+ let visits = 0;
19
+ const pending = definitions.map((definition) => definition.selectionSet);
20
+ while (pending.length) {
21
+ const selectionSet = pending.pop();
22
+ for (const selection of selectionSet.selections) {
23
+ for (const directive of selection.directives ?? []) {
24
+ if (directive.name.value === 'include' || directive.name.value === 'skip') {
25
+ visits++;
26
+ }
27
+ }
28
+ if (selection.kind === Kind.FIELD) {
29
+ visits++;
30
+ }
31
+ if (selection.kind !== Kind.FRAGMENT_SPREAD && selection.selectionSet) {
32
+ pending.push(selection.selectionSet);
33
+ }
34
+ }
35
+ }
36
+ return visits;
37
+ }
38
+ function computeComplexity(schema, query, variables) {
39
+ const typeInfo = new TypeInfo(schema);
40
+ const context = new ValidationContext(schema, query, typeInfo, (error) => {
41
+ throw error;
42
+ });
43
+ const visitor = createComplexityRule({
44
+ estimators: [fieldExtensionsEstimator(), simpleEstimator({ defaultComplexity: 1 })],
45
+ maximumComplexity: Infinity,
46
+ variables,
47
+ })(context);
48
+ const evaluate = visitor.nodeComplexity.bind(visitor);
49
+ const fragments = new Map();
50
+ visitor.nodeComplexity = (node, typeDef, activeFragments) => {
51
+ if (node.kind !== Kind.FRAGMENT_DEFINITION) {
52
+ return evaluate(node, typeDef, activeFragments);
53
+ }
54
+ const known = fragments.get(node.name.value);
55
+ if (known) {
56
+ visitor.evaluatedNodes += known.nodes;
57
+ if (visitor.evaluatedNodes >= visitor.maxQueryNodes) {
58
+ throw new GraphQLError('Query exceeds the maximum allowed number of nodes.');
59
+ }
60
+ return known.complexity;
61
+ }
62
+ const before = visitor.evaluatedNodes;
63
+ const complexity = evaluate(node, typeDef, activeFragments);
64
+ fragments.set(node.name.value, { complexity, nodes: visitor.evaluatedNodes - before });
65
+ return complexity;
66
+ };
67
+ visit(query, visitWithTypeInfo(typeInfo, visitor));
68
+ return visitor.complexity;
69
+ }
15
70
  let ComplexityPlugin = class ComplexityPlugin {
16
71
  gqlSchemaHost;
17
72
  configService;
@@ -23,14 +78,23 @@ let ComplexityPlugin = class ComplexityPlugin {
23
78
  const maxComplexity = this.configService.getFastButReadOnly('graphQl.maxComplexity');
24
79
  const { schema } = this.gqlSchemaHost;
25
80
  return {
26
- async didResolveOperation({ document, request }) {
27
- const complexity = getComplexity({
28
- estimators: [fieldExtensionsEstimator(), simpleEstimator({ defaultComplexity: 1 })],
29
- operationName: request.operationName,
30
- query: document,
31
- schema,
32
- variables: request.variables,
81
+ async didResolveOperation({ document, operation, request }) {
82
+ if (!operation) {
83
+ return;
84
+ }
85
+ const { errors } = getVariableValues(schema, operation.variableDefinitions ?? [], request.variables ?? {}, {
86
+ maxErrors: VARIABLE_COERCION_MAX_ERRORS,
33
87
  });
88
+ if (errors?.length) {
89
+ return;
90
+ }
91
+ const fragments = document.definitions.filter((definition) => definition.kind === Kind.FRAGMENT_DEFINITION);
92
+ const variableCount = operation.variableDefinitions?.length ?? 0;
93
+ if (variableVisits([operation, ...fragments]) * variableCount > COMPLEXITY_ANALYSIS_MAX_VARIABLE_WORK) {
94
+ throw new GraphQLError('Query is too complex: too many fields for its number of variables');
95
+ }
96
+ const query = { definitions: [operation, ...fragments], kind: Kind.DOCUMENT };
97
+ const complexity = computeComplexity(schema, query, request.variables ?? {});
34
98
  if (maxComplexity !== undefined && complexity > maxComplexity) {
35
99
  throw new GraphQLError(`Query is too complex: ${complexity}. Maximum allowed complexity: ${maxComplexity}`);
36
100
  }
@@ -1 +1 @@
1
- {"version":3,"file":"complexity.plugin.js","sourceRoot":"","sources":["../../../../src/core/common/plugins/complexity.plugin.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEpD,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,wBAAwB,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAEpG,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAGvD,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IAEjB;IACA;IAFV,YACU,aAAgC,EAChC,aAA4B;QAD5B,kBAAa,GAAb,aAAa,CAAmB;QAChC,kBAAa,GAAb,aAAa,CAAe;IACnC,CAAC;IAEJ,KAAK,CAAC,eAAe;QACnB,MAAM,aAAa,GAAW,IAAI,CAAC,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,YAAY,CAAC,mEAAmE,CAAC,CAAC;gBAC9F,CAAC;gBAED,MAAM,KAAK,GAAiB,EAAE,WAAW,EAAE,CAAC,SAAS,EAAE,GAAG,SAAS,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC;gBAC5F,MAAM,UAAU,GAAG,iBAAiB,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,SAAS,IAAI,EAAE,CAAC,CAAC;gBAC7E,IAAI,aAAa,KAAK,SAAS,IAAI,UAAU,GAAG,aAAa,EAAE,CAAC;oBAC9D,MAAM,IAAI,YAAY,CAAC,yBAAyB,UAAU,iCAAiC,aAAa,EAAE,CAAC,CAAC;gBAC9G,CAAC;YACH,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAA;AAlDY,gBAAgB;IAD5B,MAAM,EAAE;qCAGkB,iBAAiB;QACjB,aAAa;GAH3B,gBAAgB,CAkD5B"}
@@ -215,9 +215,9 @@ JWT-based authentication for existing projects:
215
215
  | **Subscriptions** | WebSocket support via `graphql-ws` with auth. The `PUB_SUB` provider is built from a factory: `CoreRedisPubSub` when `redis` is configured (delivery is then cluster-wide), the in-memory `PubSub` otherwise (delivery only to clients connected to the publishing replica). **Constraint once Redis is in play: every published payload must be JSON-serializable** — it crosses the wire as JSON, so `Date`, class instances, `Map`/`Set` and `undefined` do not survive the round trip. An in-process `PubSub` never had this constraint, so a payload that worked on one replica can silently lose fields on a cluster. Publish plain objects and ISO strings |
216
216
  | **Subscription request context** | Since 11.35.0 `CoreModule` installs a context-aware `execute` / `subscribe` pair (inside `subscriptions`, where `ApolloDriver` forwards it) on all three GraphQL driver builders, so every WebSocket operation runs inside a `RequestContext`. Before that a WS operation had **none** — no Express middleware runs on an upgrade, and `CoreTenantGuard.getRequest()` finds no `req` on a subscription context — and `mongooseTenantPlugin` reads "no context" as "system operation, no filter", so a tenant-scoped read while delivering a subscription message returned EVERY tenant's rows. The tenant comes from the handshake's tenant header **validated against an active membership**, else from the subscriber's memberships; an unresolvable tenant leaves the safety net to refuse the read. The async iterator is wrapped too, not only the subscribe call: graphql-js runs `resolve` / `filter` / field resolvers inside its `next()`. See `.claude/rules/role-system.md` → "Tenant context on non-HTTP transports" |
217
217
  | **Subscription re-check** | Since 11.42.3 that context is not trusted for the life of the socket. Every connection a `CoreModule` `onConnect` accepts is registered (`registerWsConnection()`) and checked again — at once on an invalidation (tenant guard, role change, password reset, Better-Auth deleting the session), otherwise before the next operation or event once `graphQl.subscriptionRevalidationMs` (30 s) has passed. The check re-runs the handshake's authentication and the tenant resolution; a connection whose rights changed is closed with 4403 (retried by the graphql-ws client, which then reconnects with its current rights) and the event that triggered the check is dropped. Before, a removed membership, a deactivated tenant, a withdrawn role or a revoked session kept receiving events on an open socket until the client reconnected. See `.claude/rules/role-system.md` → "Open WebSockets" |
218
- | **Complexity Analysis** | Query cost calculation to prevent DoS attacks |
218
+ | **Complexity Analysis** | Query cost calculation to prevent DoS attacks. Since 12.6.14 `ComplexityPlugin` analyses only the operation Apollo resolved (none resolved: left to execution, which refuses it before coercing a variable), first checks whether its variables coerce (stopping at the first error) and leaves invalid ones to execution, which refuses them with graphql's cap (50), refuses an operation whose fields × declared variables exceed 250,000, computes graphql-query-complexity's number with each fragment evaluated once, and stops at its first error. Before, a document of many operations, a list of invalid items, a fragment spread thousands of times, tens of thousands of variables or thousands of failing arguments each blocked the event loop for seconds from one anonymous request |
219
219
  | **Enum Registration** | `registerEnum()` helper for GraphQL enum types |
220
- | **Upload Support** | `graphqlUploadExpress()` for multipart file uploads, with the framework's `processGraphQlUploadRequest` (graphql-upload's parser with the GHSA-5vm7-vc2x-p3w2 and GHSA-qwwm-252j-9whw fixes; `map` bounded to 64 keys per path and 10,000 entries and path keys together) |
220
+ | **Upload Support** | `graphqlUploadExpress()` for multipart file uploads, with the framework's `processGraphQlUploadRequest` (graphql-upload's parser with the GHSA-5vm7-vc2x-p3w2 and GHSA-qwwm-252j-9whw fixes; `map` bounded to 64 keys per path and 10,000 entries, path keys and array elements together) |
221
221
 
222
222
  ### Development & Operations
223
223
 
@@ -365,7 +365,7 @@ The following diagram shows the exact order of execution from HTTP request to re
365
365
  | 3. graphqlUploadExpress() [GraphQL only] |
366
366
  | - Handles multipart file uploads |
367
367
  | - processGraphQlUploadRequest: bad map path -> 400 |
368
- | - map: 64 keys/path, 10,000 entries + keys |
368
+ | - map: 64 keys/path, 10,000 units in total |
369
369
  +----------------------------+----------------------------+
370
370
  |
371
371
  +----------------------------v----------------------------+
@@ -752,13 +752,15 @@ the name of an already resolved upload is ignored (GHSA-qwwm-252j-9whw — befor
752
752
  that registers `graphqlUploadExpress()` itself passes `{ processRequest: processGraphQlUploadRequest }` too.
753
753
 
754
754
  It also bounds the `map`: at most `GRAPHQL_UPLOAD_MAX_PATH_KEYS` (64) keys per path, and at most
755
- `GRAPHQL_UPLOAD_MAX_MAP_KEYS` (10,000) entries and path keys together — each entry counts one, each key of its paths
756
- one more. A path over a bound is answered with 400 "Invalid object path", an entry over the map bound with 400
757
- "Invalid ‘map’ multipart field entry key …" before its upload is created. The parser places each upload with
758
- object-path's `set()`, which costs O(n²) for a path of n keys, and creates an upload per entry that it rejects with an
759
- error of its own when the file never arrives: before, one anonymous request with an 80 KB path exhausted a 1 GB heap
760
- and ended the process, 1 MB of paths just under a per-path bound blocked the event loop for up to 640 ms, and 1 MB of
761
- entries without a path for 410 ms with 230 MB. graphql-upload 18.0.2 has the same flaws.
755
+ `GRAPHQL_UPLOAD_MAX_MAP_KEYS` (10,000) units in the whole `map` — one per entry, one per path key and one per array
756
+ element a numeric path key creates, holes included. A path over a bound is answered with 400 "Invalid object path",
757
+ an entry over the map bound with 400 "Invalid ‘map’ multipart field entry key …" before its upload is created. The
758
+ parser places each upload with object-path's `set()`, which costs O(n²) for a path of n keys and reads a key like
759
+ `4294967294` as a number, setting that index of an array it creates; and it creates an upload per entry that it rejects
760
+ with an error of its own when the file never arrives. Before, one anonymous request with an 80 KB path exhausted a
761
+ 1 GB heap and ended the process, 1 MB of paths just under a per-path bound blocked the event loop for up to 640 ms,
762
+ 1 MB of entries without a path for 410 ms with 230 MB, and the 258-byte `variables.f.4294967294` handed GraphQL an
763
+ array of 2^32 − 1 elements whose coercion exhausted a 1 GB heap. graphql-upload 18.0.2 has the same flaws.
762
764
 
763
765
  > **NestJS docs:** [Middleware](https://docs.nestjs.com/middleware)
764
766
 
@@ -0,0 +1,143 @@
1
+ # Migration Guide: 12.6.13 → 12.6.14
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None |
8
+ | **New Features** | None |
9
+ | **Bugfixes** | None |
10
+ | **Security** | Unauthenticated denial of service, every one fixed in the framework — no action needed: a GraphQL multipart `map` path with a numeric key like `4294967294` (§1), and the GraphQL complexity check on invalid variables, documents of many operations, fragments spread thousands of times and tens of thousands of variables, a plain JSON POST included (§2). A PEM private key under a key such as `certificate` is masked in `GET /config`, the Hub config panel and the `ConfigService` debug output (§3) |
11
+ | **Migration Effort** | Package update |
12
+
13
+ ## Quick Migration
14
+
15
+ ```bash
16
+ pnpm add @lenne.tech/nest-server@12.6.14
17
+ pnpm run update # nest-server-starter based projects
18
+ pnpm run build
19
+ pnpm test
20
+ ```
21
+
22
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual. No new dependency.
23
+
24
+ ## 1. Security: numeric `map` keys count against the map bound
25
+
26
+ Since 12.6.13 `processGraphQlUploadRequest` refuses a GraphQL multipart `map` with more than
27
+ `GRAPHQL_UPLOAD_MAX_MAP_KEYS` (10,000) entries and path keys (see the 12.6.12 → 12.6.13 guide). That bound missed what
28
+ a path builds. object-path, which places each upload, reads a key like `4294967294` as a NUMBER and sets that index of
29
+ an array it creates. The 258-byte request `map={"1":["variables.f.4294967294"]}` counted 4 units and handed GraphQL an
30
+ array of 4,294,967,295 elements. GraphQL's list coercion walks every hole: `ComplexityPlugin` did, before any guard,
31
+ until the heap ran out. With a nullable list item (`[Upload]`) every hole is a valid `null`, so execution would walk
32
+ them too.
33
+
34
+ Since 12.6.14 every array element a numeric key creates counts one unit, holes included, and the path that goes over
35
+ the bound is refused with 400 "Invalid object path" before anything is set. `{"1":["variables.files.0"]}` counts 5,
36
+ or 4 when the operations already hold `files: [null]`; 10,000 units are at least 2,000 files at `variables.files.N`.
37
+
38
+ | Request | 12.6.13 | 12.6.14 |
39
+ |---|---|---|
40
+ | `{"1":["variables.f.4294967294"]}` (258 bytes), 1 GB heap | heap exhausted after 11 s, the process ends | 400, ~15 ms, +3 MB |
41
+
42
+ graphql-upload's own parser has the same flaw, 17.1.0 as well as 18.0.2. A project that registers
43
+ `graphqlUploadExpress()` itself with `processRequest: processGraphQlUploadRequest` (12.6.13 guide, §1) gets the fix
44
+ with the update.
45
+
46
+ ## 2. Security: the complexity check is bounded
47
+
48
+ `ComplexityPlugin` (registered by `CoreModule` whenever GraphQL is on) computes every operation's cost in Apollo's
49
+ `didResolveOperation`, after parsing and validation, before any guard. It called graphql-query-complexity's
50
+ `getComplexity()`, and these requests made that call itself the denial of service — each one anonymous, a plain JSON
51
+ POST to `/graphql` included:
52
+
53
+ - **Invalid variables.** `getComplexity()` coerces the variables with graphql's `getVariableValues()` without an error
54
+ cap, so a list of invalid items (`"variables":{"f":[0,0,…]}` for `$f: [Upload!]!`) created one `GraphQLError` per item.
55
+ - **Many operations, no `operationName`.** Apollo resolves no operation and still calls the hook. `getComplexity()`
56
+ then evaluated EVERY operation of the document and coerced the variables for each.
57
+ - **Fragment spreads.** graphql-query-complexity evaluates a fragment again at every spread, coercing its literal
58
+ arguments each time. Its node cap (10,000 visits) bounds the visits, not what one costs:
59
+ `{...F …×3300} fragment F on Query { findUsers(filter: { singleFilter: { …, value: [0,0,…] } }) { __typename } }`.
60
+ - **Many declared variables.** At every field it visits, the library walks every declared variable.
61
+ - **Many failing arguments.** The library catches the coercion error of every field's arguments and goes on, and every
62
+ error locates itself by scanning the query up to its field: `query($x: String = "a") { a: getUser(id: $x) { id } … }`
63
+ with `{"x": null}` is valid and fails at every field.
64
+
65
+ | Request | 12.6.13 | 12.6.14 |
66
+ |---|---|---|
67
+ | 100 KB of invalid list items | event loop blocked 1.9 s, +260 MB | ~7 ms, +1 MB |
68
+ | 1 MB of invalid list items | event loop blocked 26 s, +1.3 GB | ~14 ms, +13 MB |
69
+ | 860 operations sharing one 16,000-item variable (100 KB) | event loop blocked 5.9 s | < 1 ms, refused by execution |
70
+ | the same with 1,720 operations (200 KB multipart) | event loop blocked 25.5 s | < 1 ms, refused by execution |
71
+ | a 41,667-item literal in a fragment spread 3,300 times (100 KB) | event loop blocked 2.2 s | ~15 ms, "Query is too complex" |
72
+ | the same with a 490,000-item literal (990 KB multipart) | event loop blocked 22.5 s | ~100 ms, "Query is too complex" |
73
+ | 38,000 declared variables and 4,900 spreads (1.2 MB) | event loop blocked 17 s | ~100 ms, "Query is too complex" |
74
+ | 2,300 fields failing their argument, after 25,000 line breaks (98 KiB) | event loop blocked 1.4 s | ~6 ms, refused with the first error |
75
+ | 9,999 such fields after 395,000 line breaks (993 KiB multipart) | event loop blocked 86 s | ~16 ms, refused with the first error |
76
+
77
+ What is left for the large literal and the many variables is linear in the request: graphql's validation and
78
+ execution walk the same literal and the same variables once themselves.
79
+
80
+ The rows after the first two were measured on the development line, which has the same plugin and the same
81
+ graphql-query-complexity 2.0.0.
82
+
83
+ Since 12.6.14 the plugin:
84
+
85
+ 1. does nothing when Apollo resolved no operation — graphql's `execute()` then refuses the request ("Must provide
86
+ operation name…") before it coerces a single variable;
87
+ 2. coerces the resolved operation's variables, stopping at the first error, and skips the complexity check when they
88
+ do not coerce: `execute()` refuses such variables itself, with graphql's cap of 50, before any resolver runs, so
89
+ there is no operation whose cost could matter;
90
+ 3. refuses an operation whose fields (and `@skip` / `@include`) times declared variables exceed 250,000, with
91
+ `Query is too complex: too many fields for its number of variables` — measured at most about 23 ms of analysis.
92
+ With the default cost of 1 per field, a query `maxComplexity: 1000` accepts has at most 1,000 fields; with 30
93
+ variables that is at most 30,000;
94
+ 4. computes graphql-query-complexity's number with each fragment evaluated once and reused at every further spread.
95
+ The number is the one `getComplexity()` returns, and the 10,000-node cap still counts every spread. A field's
96
+ `complexity` extension that is a function runs once per fragment instead of once per spread, so it must depend only
97
+ on its arguments and `childComplexity`;
98
+ 5. stops the analysis at its first error and refuses the request with it — `getComplexity()` collected every error and
99
+ threw the last one.
100
+
101
+ For valid variables the result is what it was: `Query is too complex: …` above `graphQl.maxComplexity`, and
102
+ `Query exceeds the maximum allowed number of nodes.` above 10,000 nodes.
103
+
104
+ **What clients see:** a request with invalid variables gets execution's errors (up to 50 messages, then "Too many
105
+ errors processing variables, error limit reached. Execution aborted.") instead of the single coercion error the plugin
106
+ threw before. The status changes with it: HTTP 400 with the code `BAD_USER_INPUT` (Apollo 5 default
107
+ `status400ForVariableCoercionErrors`) instead of HTTP 500 with `INTERNAL_SERVER_ERROR`.
108
+
109
+ ## 3. Security: PEM private keys are masked by their value
110
+
111
+ `redactSecrets()` — behind `GET /config`, the Hub config panel and the `ConfigService` output with `warn: true` —
112
+ decided by the key name alone. A certificate login usually keeps certificate and private key in one PEM under a name
113
+ such as `certificate`, which no name rule may treat as secret, so the private key reached an administrator's response
114
+ and the debug output in clear text. Since 12.6.14 every string and `Buffer` that holds a PEM private key
115
+ (`-----BEGIN … PRIVATE KEY-----`, PGP's `PRIVATE KEY BLOCK` included) is masked as a whole, whatever its key is called.
116
+ A certificate without a key stays readable. Keys named `pfx` or `pkcs12` are masked too: a PKCS#12 container carries
117
+ no text marker.
118
+
119
+ No action needed. A project that worked around it with `security.secretFields: ['certificate']` can keep that entry.
120
+
121
+ ## Compatibility Notes
122
+
123
+ | Pattern | Status |
124
+ |---|---|
125
+ | Uploads through `CoreModule`'s `/graphql` registration | Protected with the update |
126
+ | `graphqlUploadExpress()` registered by the project with `processRequest: processGraphQlUploadRequest` | Protected with the update |
127
+ | A project's own Apollo plugin that calls `getComplexity()` with the request's variables | Same flaws as §2 — skip a request without a resolved operation, check the variables with `getVariableValues(…, { maxErrors: 50 })` first, and bound fragment spreads and variables, or rely on the framework's plugin |
128
+
129
+ ## Troubleshooting
130
+
131
+ | Symptom | Cause | Fix |
132
+ |---|---|---|
133
+ | An upload answers 400 `Invalid object path …` for a path with a large number in it | The index creates more array elements than the bound allows | Number the files from 0 (`variables.files.0`, `variables.files.1`) |
134
+ | A request with invalid variables answers with several variable errors instead of one | Execution reports them now (§2) | Fix the variables; the messages are graphql's own |
135
+ | A query answers `Query is too complex: too many fields for its number of variables` | Its fields × declared variables exceed 250,000 (§2) | Split the query, or pass related values as one input-object variable |
136
+
137
+ ## Module Documentation
138
+
139
+ - `docs/REQUEST-LIFECYCLE.md` — "3. graphqlUploadExpress", feature table "Complexity Analysis"
140
+ - `src/core/common/helpers/graphql-upload.helper.ts` — the parser and its bounds
141
+ - `src/core/common/plugins/complexity.plugin.ts` — the bounds and why they exist
142
+ - `src/core/common/helpers/redact-secrets.helper.ts` — the masker and its rules
143
+ - `migration-guides/12.6.12-to-12.6.13.md` — the 12.6.13 upload fixes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "12.6.13",
3
+ "version": "12.6.14",
4
4
  "type": "module",
5
5
  "description": "Server framework in TypeScript on top of NestJS: GraphQL and REST APIs on MongoDB, PostgreSQL, MySQL or MariaDB, with authentication, field-level permissions, multi-tenancy, offline sync and an AI assistant.",
6
6
  "keywords": [
@@ -19,16 +19,22 @@
19
19
  * when the response closed — temporary files and file descriptors leaked per request (with `maxFiles` > 1; the
20
20
  * default is unlimited).
21
21
  *
22
- * One addition of the framework's own, not in graphql-upload (18.0.2 has the same flaw): the `map` is bounded. A path
23
- * may have at most {@link GRAPHQL_UPLOAD_MAX_PATH_KEYS} keys, and the whole `map` at most
24
- * {@link GRAPHQL_UPLOAD_MAX_MAP_KEYS} entries and path keys together; over either bound the request is refused with
25
- * 400. object-path's `set()` recurses once per key and copies the remaining keys each time, so a path of n keys costs
26
- * O(n²) time and memory, all of it in one synchronous call: measured on Node 24, a single anonymous request with an
27
- * 80 KB path (40,000 keys) exhausted a 1 GB heap and ended the process; 16 KB (8,000 keys) took 300 MB and blocked the
28
- * event loop for half a second. Below the per-path bound, 1 MB of paths near it (the default `maxFieldSize`) still
29
- * blocked the event loop for 150 to 640 ms, and 1 MB of entries without any path (83,000 `Upload`s, each rejected with
30
- * an error of its own when its file never arrives) for 410 ms with 230 MB. With the map bound such requests are
31
- * refused within about 30 ms, most of it spent parsing the field's JSON.
22
+ * One addition of the framework's own, not in graphql-upload (18.0.2 has the same flaws): the `map` is bounded, and
23
+ * with it everything the parser builds from it. A path may have at most {@link GRAPHQL_UPLOAD_MAX_PATH_KEYS} keys. The
24
+ * whole `map` may name at most {@link GRAPHQL_UPLOAD_MAX_MAP_KEYS} units: one per entry, one per path key and one per
25
+ * array element a numeric path key creates, holes included. The entry or path that goes over a bound is refused with
26
+ * 400 before the parser builds anything for it. Measured on Node 24, one anonymous request each, before the bounds:
27
+ *
28
+ * - object-path's `set()` recurses once per key and copies the remaining keys each time, so a path of n keys costs
29
+ * O(n²): an 80 KB path (40,000 keys) exhausted a 1 GB heap and ended the process, 16 KB (8,000 keys) took 300 MB and
30
+ * blocked the event loop for half a second; 1 MB of paths under the per-path bound blocked it for up to 640 ms.
31
+ * - Every entry becomes an `Upload` that is rejected with an error of its own when its file never arrives: 1 MB of
32
+ * entries without a path (83,000) took 230 MB and blocked the event loop for 410 ms.
33
+ * - object-path reads a key like `4294967294` as a number and sets that index of an array it creates, so the 258-byte
34
+ * request `{"1":["variables.f.4294967294"]}` handed GraphQL an array of 4,294,967,295 elements. Coercing its holes in
35
+ * the complexity plugin exhausted a 1 GB heap within seconds.
36
+ *
37
+ * With the bounds such requests are refused within about 30 ms, most of it spent parsing the field's JSON.
32
38
  *
33
39
  * `CoreModule` passes this function to `graphqlUploadExpress({ processRequest })`. A project that registers
34
40
  * `graphqlUploadExpress()` itself must pass it too — graphql-upload's own default is the unpatched function.
@@ -77,13 +83,15 @@ const GRAPHQL_MULTIPART_REQUEST_SPEC_URL = 'https://github.com/jaydenseric/graph
77
83
  export const GRAPHQL_UPLOAD_MAX_PATH_KEYS = 64;
78
84
 
79
85
  /**
80
- * Most entries and path keys one `map` may name together: every entry counts one, every key of its paths one more, so
81
- * `{"1":["variables.file"]}` counts 3, and 2,000 files at `variables.input.files.N` count 10,000. An entry over it is
82
- * refused before its `Upload` exists, with 400 "Invalid ‘map’ multipart field entry key …"; a path over it with 400
83
- * "Invalid object path". It bounds the work of a `map` of many paths that each stay under
84
- * {@link GRAPHQL_UPLOAD_MAX_PATH_KEYS} (1 MB of them blocked the event loop for up to 640 ms) and of a `map` of many
85
- * entries, each of which becomes an `Upload` that the parser rejects with an error of its own when its file never
86
- * arrives (1 MB of entries without a path, 83,000 of them, took 230 MB and blocked the event loop for 410 ms).
86
+ * Most units one `map` may name: one per entry, one per key of its paths, and one per element a numeric path key adds
87
+ * to an array, holes included — object-path sets index i, so the array becomes i + 1 long.
88
+ * `{"1":["variables.files.0"]}` counts 5 when `variables.files` does not exist yet and 4 when the operations already
89
+ * hold the slot; 2,000 files at `variables.files.N` count at most 10,000. The entry that goes over it is refused before
90
+ * its `Upload` exists, with 400 "Invalid ‘map’ multipart field entry key …"; the path that goes over it with 400
91
+ * "Invalid object path". It bounds the work of many paths (1 MB of 64-key paths blocked the event loop for up to
92
+ * 640 ms), of many entries (83,000 path-less entries in 1 MB took 230 MB and 410 ms) and of sparse arrays
93
+ * (`variables.f.4294967294` became an array of 2^32 − 1 elements, and GraphQL's list coercion walked them until the
94
+ * heap ran out).
87
95
  */
88
96
  export const GRAPHQL_UPLOAD_MAX_MAP_KEYS = 10_000;
89
97
 
@@ -127,6 +135,25 @@ function ignoreStream(stream: Readable): void {
127
135
  stream.resume();
128
136
  }
129
137
 
138
+ /**
139
+ * How many elements setting `key` in `container` adds to an array, the way object-path's `set()` sees it. object-path
140
+ * reads a key that `parseInt()` turns back into the same string as a NUMBER, and creates an array — not an object —
141
+ * for a missing container whose key is a number. Setting index i makes an array of length n i + 1 long when i ≥ n,
142
+ * every element in between a hole, and GraphQL's list coercion walks each of them. 0 for an object container, a
143
+ * string key, or a number that is not a non-negative integer (`NaN`, `-1`: a property, not an element).
144
+ */
145
+ function arrayGrowth(container: unknown, key: string): number {
146
+ // object-path's getKey() calls parseInt() without a radix; for a key that round-trips the result is the same.
147
+ const index = Number.parseInt(key, 10);
148
+ if (index.toString() !== key || !Number.isInteger(index) || index < 0) {
149
+ return 0;
150
+ }
151
+ if (container === undefined) {
152
+ return index + 1;
153
+ }
154
+ return Array.isArray(container) ? Math.max(0, index + 1 - container.length) : 0;
155
+ }
156
+
130
157
  /**
131
158
  * Processes an incoming GraphQL multipart request
132
159
  * (https://github.com/jaydenseric/graphql-multipart-request-spec): parses the `operations` and `map` fields, places
@@ -328,6 +355,17 @@ export function processGraphQlUploadRequest(
328
355
  throw new TypeError('Object path has a `__proto__` key.');
329
356
  }
330
357
 
358
+ // `pathValue` is this key's container. A key object-path reads as a number extends an array — a new
359
+ // one when the container does not exist yet — up to that index: every element it adds counts against
360
+ // GRAPHQL_UPLOAD_MAX_MAP_KEYS, holes included (`variables.f.4294967294` adds 4,294,967,295).
361
+ const growth = arrayGrowth(pathValue, key);
362
+ if (growth > 0) {
363
+ mapKeyCount += growth;
364
+ if (mapKeyCount > GRAPHQL_UPLOAD_MAX_MAP_KEYS) {
365
+ throw new RangeError(`The map's arrays have more than ${GRAPHQL_UPLOAD_MAX_MAP_KEYS} elements.`);
366
+ }
367
+ }
368
+
331
369
  // Forbid setting an upload within an already set upload, but allow a total replacement. Resolved
332
370
  // with object-path's own `get`, so it sees what `set` will reach, inherited array elements included.
333
371
  if (keyIndex < keys.length - 1) {
@@ -29,7 +29,20 @@
29
29
  * and booleans below such a key stay visible.
30
30
  */
31
31
  const SECRET_KEY_PATTERN =
32
- /secret|passwd|password|passphrase|credential|api[-_]?key|access[-_]?key|private[-_]?key|encryption|token|\bpass\b|pass$|dsn|salt|key$|(^|[^a-z])key([^a-z]|$)/i;
32
+ /secret|passwd|password|passphrase|credential|api[-_]?key|access[-_]?key|private[-_]?key|encryption|token|\bpass\b|pass$|dsn|salt|key$|(^|[^a-z])key([^a-z]|$)|pfx|pkcs12/i;
33
+
34
+ /**
35
+ * Value-shape heuristic: a PEM block holding a private key — `-----BEGIN PRIVATE KEY-----` and its `RSA`, `EC`,
36
+ * `ENCRYPTED`, `OPENSSH` variants, and PGP's `-----BEGIN PGP PRIVATE KEY BLOCK-----`. Checked in every string and
37
+ * `Buffer`, whatever its key is called (12.6.14): a certificate login keeps certificate and key in ONE PEM, usually
38
+ * under a name such as `certificate` that no key heuristic may call secret — a certificate alone is public, and an
39
+ * operator needs to see which one is configured. Until 12.6.14 such a key reached `GET /config` and the `warn: true`
40
+ * debug output in clear text. The whole value is masked; the certificate beside the key goes with it.
41
+ *
42
+ * A PKCS#12 container carries no text marker, so it is caught by its NAME (`pfx`, `pkcs12` in
43
+ * {@link SECRET_KEY_PATTERN}).
44
+ */
45
+ const PRIVATE_KEY_PEM_PATTERN = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY[A-Z ]*-----/i;
33
46
 
34
47
  /**
35
48
  * Keys whose value is an address that can carry a secret in its PATH (a Slack or Teams webhook,
@@ -95,6 +108,7 @@ export const FRAMEWORK_SECRET_FIELDS: readonly string[] = [
95
108
  * keep flags such as `emailAndPassword.disableSignUp` readable.
96
109
  * - A string shaped like a connection URI has the password of its user info masked, and every secret-named query
97
110
  * parameter, whatever its key is called.
111
+ * - A string or `Buffer` holding a PEM private key is masked as a whole, whatever its key is called.
98
112
  * - `null` and `undefined` pass through; a `Date` or `Buffer` is kept as it is (masked under a secret key).
99
113
  *
100
114
  * @param value - the object or value to mask (never mutated)
@@ -154,13 +168,18 @@ function redactValue(value: unknown, underSecretKey: boolean, extra: Set<string>
154
168
  if (typeof value !== 'string') {
155
169
  return value;
156
170
  }
171
+ if (PRIVATE_KEY_PEM_PATTERN.test(value)) {
172
+ return REDACTED_VALUE;
173
+ }
157
174
  return URL_KEY_PATTERN.test(key) ? redactUrl(value) : redactString(value);
158
175
  }
159
176
 
160
177
  // Non-plain objects (Date, Buffer) are kept as they are — cloning would lose their type, and they carry no framework
161
- // secret — unless they sit below a secret key
178
+ // secret — unless they sit below a secret key or the Buffer holds a PEM private key (`readFileSync('key.pem')`
179
+ // without an encoding, which JSON would print byte by byte)
162
180
  if (value instanceof Date || Buffer.isBuffer(value)) {
163
- return underSecretKey ? REDACTED_VALUE : value;
181
+ const holdsPrivateKey = Buffer.isBuffer(value) && PRIVATE_KEY_PEM_PATTERN.test(value.toString('latin1'));
182
+ return underSecretKey || holdsPrivateKey ? REDACTED_VALUE : value;
164
183
  }
165
184
 
166
185
  if (Array.isArray(value)) {
@@ -1,11 +1,127 @@
1
1
  import { Plugin } from '@nestjs/apollo';
2
2
  import { GraphQLSchemaHost } from '@nestjs/graphql';
3
3
  import type { ApolloServerPlugin, BaseContext, GraphQLRequestListener } from '@apollo/server';
4
- import { GraphQLError } from 'graphql';
5
- import { fieldExtensionsEstimator, getComplexity, simpleEstimator } from 'graphql-query-complexity';
4
+ import { getVariableValues, GraphQLError, Kind, TypeInfo, ValidationContext, visit, visitWithTypeInfo } from 'graphql';
5
+ import type {
6
+ ASTVisitor,
7
+ DefinitionNode,
8
+ DocumentNode,
9
+ FragmentDefinitionNode,
10
+ GraphQLSchema,
11
+ OperationDefinitionNode,
12
+ SelectionSetNode,
13
+ } from 'graphql';
14
+ import { createComplexityRule, fieldExtensionsEstimator, simpleEstimator } from 'graphql-query-complexity';
6
15
 
7
16
  import { ConfigService } from '../services/config.service.js';
8
17
 
18
+ /**
19
+ * Most variable coercion errors the pre-check collects before it stops. It only needs to know WHETHER the variables
20
+ * coerce, and one error answers that. Every error graphql creates for a variable computes its line and column by
21
+ * scanning the query up to the variable's definition: with execution's cap of 50 the pre-check cost 550 ms for a
22
+ * 959 KiB multipart request whose definitions stood after 490,000 line breaks (12.6.14).
23
+ */
24
+ const VARIABLE_COERCION_MAX_ERRORS = 1;
25
+
26
+ /**
27
+ * Most visits × declared variables the complexity analysis may cost (12.6.14, SEC-4). graphql-query-complexity runs
28
+ * `Object.keys()` over the operation's variables at every field and every `@skip` / `@include` it visits — measured on
29
+ * Node 24 at 12–90 ns per variable and visit, so the limit is reached after at most about 23 ms. 38,000 declared
30
+ * variables and 4,900 visits blocked the event loop for 17 s before. With the default cost of 1 per field, a query
31
+ * `maxComplexity: 1000` accepts has at most 1,000 fields; with 30 variables that is at most 30,000.
32
+ */
33
+ const COMPLEXITY_ANALYSIS_MAX_VARIABLE_WORK = 250_000;
34
+
35
+ /** The visitor graphql-query-complexity builds (the class itself is not exported). */
36
+ type ComplexityVisitor = ReturnType<ReturnType<typeof createComplexityRule>>;
37
+
38
+ /** Fields and `@skip` / `@include` directives in the selection sets — each one a visit with the variables walked. */
39
+ function variableVisits(definitions: readonly (FragmentDefinitionNode | OperationDefinitionNode)[]): number {
40
+ let visits = 0;
41
+ const pending: SelectionSetNode[] = definitions.map((definition) => definition.selectionSet);
42
+ while (pending.length) {
43
+ const selectionSet = pending.pop()!;
44
+ for (const selection of selectionSet.selections) {
45
+ for (const directive of selection.directives ?? []) {
46
+ if (directive.name.value === 'include' || directive.name.value === 'skip') {
47
+ visits++;
48
+ }
49
+ }
50
+ if (selection.kind === Kind.FIELD) {
51
+ visits++;
52
+ }
53
+ if (selection.kind !== Kind.FRAGMENT_SPREAD && selection.selectionSet) {
54
+ pending.push(selection.selectionSet);
55
+ }
56
+ }
57
+ }
58
+ return visits;
59
+ }
60
+
61
+ /**
62
+ * The complexity graphql-query-complexity's `getComplexity()` computes, with each fragment evaluated once (12.6.14,
63
+ * SEC-4).
64
+ *
65
+ * The library evaluates a fragment again at EVERY spread, without caching, and at every visit coerces the field's
66
+ * literal arguments again. Its node cap (10,000 visits) bounds the visits, not their cost:
67
+ * `{...F ×3300} fragment F on Query { findUsers(filter: { … value: [0,0,…41,667 items] }) }` blocked the event loop
68
+ * for 2.2 s from a 100 KB JSON POST and for 22.5 s from a 990 KB multipart request — before any guard, with variables
69
+ * that coerce.
70
+ *
71
+ * A fragment's complexity depends on the fragment alone: its type is its type condition, and the variables and the
72
+ * estimators are the same for every spread. So the first spread evaluates it, every further spread reuses the result
73
+ * and adds the nodes the evaluation visited to the library's node count, so a query over 10,000 nodes is refused as
74
+ * before. The number this returns is the one `getComplexity()` returns; the work is that of the document, each
75
+ * fragment once. A field's `complexity` extension (read by `fieldExtensionsEstimator`) must therefore depend only on its
76
+ * arguments and `childComplexity` — as a function it runs once per fragment, not once per spread.
77
+ *
78
+ * The analysis stops at the first error it reports. The library catches the coercion error of every field's arguments
79
+ * and goes on, and `getComplexity()` throws the last one at the end — but every error with a node computes its line and
80
+ * column by scanning the query up to it. `query($x: String = "a") { a: getUser(id: $x) { id } b: … }` with
81
+ * `{"x": null}` is valid, passes the variable check and fails at every one of up to 9,999 fields: 1.4 s from a 98 KiB
82
+ * JSON POST, 86 s from a 993 KiB multipart request with the fields after 395,000 line breaks (12.6.14). The request is
83
+ * refused either way; now with the first error instead of the last.
84
+ *
85
+ * Built like `getComplexity()` (graphql-query-complexity 2.0.0, `QueryComplexity.js`), through the public
86
+ * `createComplexityRule()`; the cache wraps `nodeComplexity` of this one visitor, which the library calls through
87
+ * `this` for every fragment spread.
88
+ */
89
+ function computeComplexity(schema: GraphQLSchema, query: DocumentNode, variables: Record<string, unknown>): number {
90
+ const typeInfo = new TypeInfo(schema);
91
+ const context = new ValidationContext(schema, query, typeInfo, (error) => {
92
+ throw error;
93
+ });
94
+ const visitor: ComplexityVisitor = createComplexityRule({
95
+ estimators: [fieldExtensionsEstimator(), simpleEstimator({ defaultComplexity: 1 })],
96
+ // The maximum is checked by the plugin; the visitor only computes.
97
+ maximumComplexity: Infinity,
98
+ variables,
99
+ })(context);
100
+
101
+ const evaluate = visitor.nodeComplexity.bind(visitor);
102
+ const fragments = new Map<string, { complexity: number; nodes: number }>();
103
+ visitor.nodeComplexity = (node, typeDef, activeFragments) => {
104
+ if (node.kind !== Kind.FRAGMENT_DEFINITION) {
105
+ return evaluate(node, typeDef, activeFragments);
106
+ }
107
+ const known = fragments.get(node.name.value);
108
+ if (known) {
109
+ visitor.evaluatedNodes += known.nodes;
110
+ if (visitor.evaluatedNodes >= visitor.maxQueryNodes) {
111
+ throw new GraphQLError('Query exceeds the maximum allowed number of nodes.');
112
+ }
113
+ return known.complexity;
114
+ }
115
+ const before = visitor.evaluatedNodes;
116
+ const complexity = evaluate(node, typeDef, activeFragments);
117
+ fragments.set(node.name.value, { complexity, nodes: visitor.evaluatedNodes - before });
118
+ return complexity;
119
+ };
120
+
121
+ visit(query, visitWithTypeInfo(typeInfo, visitor as unknown as ASTVisitor));
122
+ return visitor.complexity;
123
+ }
124
+
9
125
  @Plugin()
10
126
  export class ComplexityPlugin implements ApolloServerPlugin {
11
127
  constructor(
@@ -18,14 +134,39 @@ export class ComplexityPlugin implements ApolloServerPlugin {
18
134
  const { schema } = this.gqlSchemaHost;
19
135
 
20
136
  return {
21
- async didResolveOperation({ document, request }) {
22
- const complexity = getComplexity({
23
- estimators: [fieldExtensionsEstimator(), simpleEstimator({ defaultComplexity: 1 })],
24
- operationName: request.operationName,
25
- query: document,
26
- schema,
27
- variables: request.variables,
137
+ async didResolveOperation({ document, operation, request }) {
138
+ // No operation resolved: several operations and no `operationName` naming one of them. Apollo still calls this
139
+ // hook, and graphql's `execute()` refuses the request afterwards, before it coerces a single variable.
140
+ // getComplexity() instead evaluated EVERY operation of such a document and coerced the variables for each
141
+ // (12.6.14, SEC-3): 860 operations sharing one 16,000-item variable blocked the event loop for 5.9 s from a
142
+ // 100 KB JSON POST, 1,720 operations for 25.5 s from 200 KB.
143
+ if (!operation) {
144
+ return;
145
+ }
146
+
147
+ // Invalid variables (12.6.14, SEC-2): getComplexity() coerces without an error cap, so a list of invalid items
148
+ // created one error per item — 1.5 s and 300 MB for 100 KB, 15 s and 2 GB for 1 MB. Execution refuses such
149
+ // variables itself, with graphql's cap of 50, before any resolver runs, so there is no complexity to compute.
150
+ const { errors } = getVariableValues(schema, operation.variableDefinitions ?? [], request.variables ?? {}, {
151
+ maxErrors: VARIABLE_COERCION_MAX_ERRORS,
28
152
  });
153
+ if (errors?.length) {
154
+ return;
155
+ }
156
+
157
+ // The resolved operation alone, with the fragments it may spread: the analysis evaluates exactly the operation
158
+ // execution runs, and coerces its variables once.
159
+ const fragments = document.definitions.filter(
160
+ (definition: DefinitionNode): definition is FragmentDefinitionNode =>
161
+ definition.kind === Kind.FRAGMENT_DEFINITION,
162
+ );
163
+ const variableCount = operation.variableDefinitions?.length ?? 0;
164
+ if (variableVisits([operation, ...fragments]) * variableCount > COMPLEXITY_ANALYSIS_MAX_VARIABLE_WORK) {
165
+ throw new GraphQLError('Query is too complex: too many fields for its number of variables');
166
+ }
167
+
168
+ const query: DocumentNode = { definitions: [operation, ...fragments], kind: Kind.DOCUMENT };
169
+ const complexity = computeComplexity(schema, query, request.variables ?? {});
29
170
  if (maxComplexity !== undefined && complexity > maxComplexity) {
30
171
  throw new GraphQLError(`Query is too complex: ${complexity}. Maximum allowed complexity: ${maxComplexity}`);
31
172
  }