@lenne.tech/nest-server 12.9.4 → 12.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/.claude/rules/configurable-features.md +5 -1
  2. package/.claude/rules/package-management.md +38 -12
  3. package/.claude/rules/role-system.md +12 -0
  4. package/.claude/rules/testing.md +4 -4
  5. package/CLAUDE.md +10 -1
  6. package/FRAMEWORK-API.md +2 -1
  7. package/dist/core/common/decorators/rest-user.decorator.js +4 -0
  8. package/dist/core/common/decorators/rest-user.decorator.js.map +1 -1
  9. package/dist/core/common/filters/http-exception-log.filter.js +3 -0
  10. package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
  11. package/dist/core/common/helpers/context.helper.js +9 -0
  12. package/dist/core/common/helpers/context.helper.js.map +1 -1
  13. package/dist/core/common/helpers/decorator.helper.js +4 -0
  14. package/dist/core/common/helpers/decorator.helper.js.map +1 -1
  15. package/dist/core/common/helpers/execution-context-request.helper.d.ts +14 -1
  16. package/dist/core/common/helpers/execution-context-request.helper.js +36 -0
  17. package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
  18. package/dist/core/common/helpers/graphql-upload.helper.d.ts +10 -0
  19. package/dist/core/common/helpers/graphql-upload.helper.js +237 -0
  20. package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
  21. package/dist/core/common/helpers/redact-secrets.helper.js +7 -2
  22. package/dist/core/common/helpers/redact-secrets.helper.js.map +1 -1
  23. package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
  24. package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
  25. package/dist/core/common/interfaces/server-options.interface.d.ts +11 -0
  26. package/dist/core/common/middleware/request-context.middleware.js +3 -0
  27. package/dist/core/common/middleware/request-context.middleware.js.map +1 -1
  28. package/dist/core/common/plugins/complexity.plugin.js +73 -9
  29. package/dist/core/common/plugins/complexity.plugin.js.map +1 -1
  30. package/dist/core/common/services/request-context.service.d.ts +2 -0
  31. package/dist/core/common/services/request-context.service.js +3 -0
  32. package/dist/core/common/services/request-context.service.js.map +1 -1
  33. package/dist/core/modules/ai/core-ai-mcp.controller.js +4 -2
  34. package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
  35. package/dist/core/modules/ai/core-ai.constants.d.ts +1 -0
  36. package/dist/core/modules/ai/core-ai.constants.js +1 -0
  37. package/dist/core/modules/ai/core-ai.constants.js.map +1 -1
  38. package/dist/core/modules/ai/core-ai.module.js +2 -0
  39. package/dist/core/modules/ai/core-ai.module.js.map +1 -1
  40. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.d.ts +8 -0
  41. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js +8 -0
  42. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js.map +1 -0
  43. package/dist/core/modules/ai/helpers/ai-verified-user.helper.d.ts +12 -0
  44. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js +23 -0
  45. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js.map +1 -0
  46. package/dist/core/modules/ai/index.d.ts +8 -0
  47. package/dist/core/modules/ai/index.js +8 -0
  48. package/dist/core/modules/ai/index.js.map +1 -1
  49. package/dist/core/modules/ai/interfaces/llm-provider.interface.d.ts +1 -0
  50. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js +2 -0
  51. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js.map +1 -1
  52. package/dist/core/modules/ai/providers/ai-egress.helper.d.ts +6 -0
  53. package/dist/core/modules/ai/providers/ai-egress.helper.js +58 -0
  54. package/dist/core/modules/ai/providers/ai-egress.helper.js.map +1 -0
  55. package/dist/core/modules/ai/providers/ai-sdk.packages.d.ts +16 -0
  56. package/dist/core/modules/ai/providers/ai-sdk.packages.js +99 -0
  57. package/dist/core/modules/ai/providers/ai-sdk.packages.js.map +1 -0
  58. package/dist/core/modules/ai/providers/ai-sdk.provider.d.ts +51 -0
  59. package/dist/core/modules/ai/providers/ai-sdk.provider.js +244 -0
  60. package/dist/core/modules/ai/providers/ai-sdk.provider.js.map +1 -0
  61. package/dist/core/modules/ai/providers/llm-provider.factory.d.ts +11 -1
  62. package/dist/core/modules/ai/providers/llm-provider.factory.js +44 -3
  63. package/dist/core/modules/ai/providers/llm-provider.factory.js.map +1 -1
  64. package/dist/core/modules/ai/providers/openai-compatible.provider.js +4 -21
  65. package/dist/core/modules/ai/providers/openai-compatible.provider.js.map +1 -1
  66. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.d.ts +34 -0
  67. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js +130 -0
  68. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js.map +1 -0
  69. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +28 -3
  70. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +141 -15
  71. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
  72. package/dist/core/modules/ai/services/core-ai-mcp.service.js +2 -1
  73. package/dist/core/modules/ai/services/core-ai-mcp.service.js.map +1 -1
  74. package/dist/core/modules/ai/services/core-ai.service.js +2 -7
  75. package/dist/core/modules/ai/services/core-ai.service.js.map +1 -1
  76. package/dist/core/modules/ai/tools/ai-tool-result.helper.d.ts +2 -0
  77. package/dist/core/modules/ai/tools/ai-tool-result.helper.js +117 -0
  78. package/dist/core/modules/ai/tools/ai-tool-result.helper.js.map +1 -0
  79. package/dist/core/modules/ai/tools/ai-tool-schema.helper.d.ts +36 -0
  80. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js +81 -0
  81. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js.map +1 -0
  82. package/dist/core/modules/ai/tools/ai-tool.registry.js +2 -1
  83. package/dist/core/modules/ai/tools/ai-tool.registry.js.map +1 -1
  84. package/dist/core/modules/auth/guards/auth.guard.js +10 -2
  85. package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
  86. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
  87. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
  88. package/dist/core/modules/auth/guards/roles.guard.js +11 -1
  89. package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
  90. package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
  91. package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
  92. package/dist/core/modules/better-auth/better-auth.config.js +78 -0
  93. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  94. package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
  95. package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
  96. package/dist/core.module.js +2 -1
  97. package/dist/core.module.js.map +1 -1
  98. package/dist/index.d.ts +1 -0
  99. package/dist/index.js +1 -0
  100. package/dist/index.js.map +1 -1
  101. package/dist/types/graphql-upload.d.ts +34 -2
  102. package/docs/REQUEST-LIFECYCLE.md +59 -10
  103. package/migration-guides/12.10.0-to-12.10.1.md +182 -0
  104. package/migration-guides/12.9.3-to-12.9.4.md +3 -1
  105. package/migration-guides/12.9.x-to-12.10.x.md +271 -0
  106. package/package.json +46 -21
  107. package/src/core/common/decorators/rest-user.decorator.ts +6 -0
  108. package/src/core/common/filters/http-exception-log.filter.ts +8 -0
  109. package/src/core/common/helpers/context.helper.ts +14 -0
  110. package/src/core/common/helpers/decorator.helper.ts +5 -0
  111. package/src/core/common/helpers/execution-context-request.helper.ts +97 -1
  112. package/src/core/common/helpers/graphql-upload.helper.ts +520 -0
  113. package/src/core/common/helpers/redact-secrets.helper.ts +22 -3
  114. package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
  115. package/src/core/common/interfaces/server-options.interface.ts +98 -0
  116. package/src/core/common/middleware/request-context.middleware.ts +3 -0
  117. package/src/core/common/plugins/complexity.plugin.ts +150 -9
  118. package/src/core/common/services/request-context.service.ts +11 -0
  119. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +16 -0
  120. package/src/core/modules/ai/README.md +101 -0
  121. package/src/core/modules/ai/core-ai-mcp.controller.ts +7 -2
  122. package/src/core/modules/ai/core-ai.constants.ts +4 -0
  123. package/src/core/modules/ai/core-ai.module.ts +3 -0
  124. package/src/core/modules/ai/decorators/ai-agent-function.decorator.ts +44 -0
  125. package/src/core/modules/ai/helpers/ai-verified-user.helper.ts +47 -0
  126. package/src/core/modules/ai/index.ts +8 -0
  127. package/src/core/modules/ai/interfaces/ai-tool.interface.ts +5 -1
  128. package/src/core/modules/ai/interfaces/llm-provider.interface.ts +6 -0
  129. package/src/core/modules/ai/models/core-ai-mcp-oauth.models.ts +4 -0
  130. package/src/core/modules/ai/providers/ai-egress.helper.ts +98 -0
  131. package/src/core/modules/ai/providers/ai-sdk.packages.ts +153 -0
  132. package/src/core/modules/ai/providers/ai-sdk.provider.ts +383 -0
  133. package/src/core/modules/ai/providers/llm-provider.factory.ts +93 -2
  134. package/src/core/modules/ai/providers/openai-compatible.provider.ts +5 -23
  135. package/src/core/modules/ai/services/core-ai-agent-function.bridge.ts +170 -0
  136. package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +240 -20
  137. package/src/core/modules/ai/services/core-ai-mcp.service.ts +3 -1
  138. package/src/core/modules/ai/services/core-ai.service.ts +5 -7
  139. package/src/core/modules/ai/tools/ai-tool-result.helper.ts +153 -0
  140. package/src/core/modules/ai/tools/ai-tool-schema.helper.ts +134 -0
  141. package/src/core/modules/ai/tools/ai-tool.registry.ts +6 -1
  142. package/src/core/modules/auth/guards/auth.guard.ts +19 -2
  143. package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
  144. package/src/core/modules/auth/guards/roles.guard.ts +23 -1
  145. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +11 -0
  146. package/src/core/modules/better-auth/README.md +204 -0
  147. package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
  148. package/src/core/modules/better-auth/better-auth.config.ts +138 -1
  149. package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
  150. package/src/core.module.ts +5 -1
  151. package/src/index.ts +1 -0
  152. package/src/types/graphql-upload.d.ts +34 -2
@@ -310,6 +310,8 @@ This pattern is currently applied to:
310
310
  | BetterAuth Passkey Plugin | `betterAuth.passkey` | Boolean Shorthand | `rpName: 'Nest Server'` |
311
311
  | BetterAuth Cross-Subdomain Cookies | `betterAuth.crossSubDomainCookies` | Boolean Shorthand | `domain: auto (appUrl → baseUrl without api. prefix)` |
312
312
  | BetterAuth Disable Sign-Up | `betterAuth.emailAndPassword.disableSignUp` | Explicit Boolean | `false` (sign-up enabled). `true` also removes `POST /iam/sign-up/email` from the document `setupSwagger()` builds — the route answers `SIGNUP_DISABLED` to every caller then, so documenting it only misleads. The rule is `CoreBetterAuthService.isSignUpEnabled()`'s (`=== true`); a project controller extending `CoreBetterAuthController` that overrides `signUp` is covered, and so is the route Better-Auth generates for it. **Since 12.3.0 it closes social sign-up too:** Better-Auth reads the flag for `/sign-up/email` only and decides a social sign-up per provider, so `buildSocialProviders()` hands every provider it as `disableSignUp` — a first social sign-in of an unknown user is refused (`error=signup_disabled` on the callback, 401 on `/sign-in/social` with an `idToken`), existing users keep signing in. `socialProviders.<name>.disableSignUp` is the deliberate exception per provider (`false` opens, `true` closes only that one); only a boolean counts there, any other value follows the global flag, so a string from `NEST_SERVER_CONFIG` cannot open a closed registration. Plugins a project adds through `betterAuth.plugins` are not covered (they need their own sign-up option, `magicLink({ disableSignUp: true })`); `betterAuth.options.plugins` would replace the framework's own plugins and is not the place for them. Pinned by `tests/unit/better-auth-social-sign-up.spec.ts` against the REAL `createBetterAuthInstance()`, including Better-Auth's own `/sign-in/social` handler (mutations `iam-social-sign-up-ignores-disable-sign-up`, `iam-social-sign-up-string-opens`). Implementation: `switchedOffBetterAuthPaths()` in `core-better-auth-openapi.helper.ts`, applied by `swagger.helper.ts`; `buildSocialProviders()` in `better-auth.config.ts` |
313
+ | BetterAuth Social Provider Options | `betterAuth.socialProviders.<name>.*` | Pass-through — the provider is on with `clientId` + `clientSecret`, `enabled: false` switches it off | **Since 12.10.0 every option a project sets on a provider reaches Better-Auth's provider unchanged**: `tenantId`, `scope`, `disableDefaultScope`, `prompt`, `disableProfilePhoto`, `mapProfileToUser`, `overrideUserInfoOnSignIn`, Google's `hd` / `accessType`, and so on. Up to 12.9.4 `buildSocialProviders()` handed each provider `clientId`, `clientSecret` and `disableSignUp` only and dropped the rest without a warning, so a Microsoft sign-in ran against `common` (accounts of every organization and personal Microsoft accounts) with Better-Auth's default scope (`User.Read`, `offline_access`: a Graph access and refresh token in `account`). The only way round, `betterAuth.options.socialProviders`, replaced the whole block: the provider left `GET /iam/features` and `emailAndPassword.disableSignUp` no longer closed it. `enabled` is the framework's own switch and is not handed on. `clientId`, `clientSecret` and the computed `disableSignUp` are written AFTER the project's options, so a raw `disableSignUp` (a string from `NEST_SERVER_CONFIG`) cannot replace the sign-up decision of the Disable Sign-Up row. `scope` given as a string is split on commas and whitespace (`splitScopeList()`), because `NSC__…__SCOPE` arrives as one: the `NSC__*` reader converts only `true`, `false` and numbers, and Better-Auth spreads `scope` into its list, one scope per character for a string. A `scope` that is neither a string nor a list (the object indexed `…__SCOPE__0` variables build, the `0` an empty `…__SCOPE=` becomes) is dropped with ONE error per provider at boot, never converted: Better-Auth spread an object into a `TypeError` on every `/sign-in/social`; without it the provider asks for its default scopes, and with `disableDefaultScope: true` for none, which the error says the provider will refuse. A list comes from `config.env.ts` or `NEST_SERVER_CONFIG`. Unset `tenantId` → `common`. Functions (`mapProfileToUser`) only from `config.env.ts`. Pinned by `tests/unit/better-auth-social-provider-options.spec.ts` against the REAL `createBetterAuthInstance()`, including the authorization URL from Better-Auth's own `/sign-in/social` handler and a configuration built by `getEnvironmentObject()` from `NSC__*` variables alone (mutations `iam-social-provider-options-dropped`, `iam-social-provider-options-override-sign-up`). Implementation: `buildSocialProviders()`, `splitScopeList()` and `malformedScopeMessage()` in `better-auth.config.ts`; documented in `src/core/modules/better-auth/README.md` → "Social providers" |
314
+ | BetterAuth OAuth Error URL | `betterAuth.errorUrl` | Explicit Value with derived default | **`<appUrl>/auth/login` since 12.10.0**, handed to Better-Auth as `onAPIError.errorURL`. Before, nest-server set none, so an OAuth flow that failed without an error URL of its own landed on Better-Auth's built-in English "Error" page on the API host (HTTP 200, no way back into the app). Measured against Microsoft Entra ID: a user who took more than ten minutes on the provider's sign-in page came back with an expired state, and the request's `errorCallbackURL` travels inside that state. Readers in better-auth 1.7.x: the OAuth callback (missing, unreadable, expired or mismatched state; a malformed callback request; through `parseState()` every later failure of a flow started without `errorCallbackURL`), `handleOAuthUserInfo()`'s `internal_server_error` (also on `idToken` sign-in), `GET <basePath>/error` (forwards `error` and the raw `error_description` instead of rendering), and the `oauthProxy()` plugin. None appends a path; Better-Auth only adds query parameters (`appendQueryParams()`). The app URL comes from `resolveServerUrls()` like `trustedOrigins` (explicit `appUrl` → localhost default in `local` / `ci` / `e2e` → derived from `baseUrl` unless `cors.deriveAppUrl: false`); none resolves → Better-Auth's page, never a guessed host. An absolute `http(s)` URL is used as it is, a path with one leading `/` against the app URL (no app URL → warning, Better-Auth's page), `false` keeps Better-Auth's page; anything else (another scheme, `//host`, `/\host`, a non-string such as the `0` an empty `NSC__BETTER_AUTH__ERROR_URL=` becomes) is refused with ONE warning and Better-Auth's page: a misconfiguration neither stops the boot nor redirects anywhere nobody chose. `betterAuth.options.onAPIError` is MERGED, not replaced (like `logger` and `emailAndPassword`): its `errorURL` wins when set, its other keys (`onError`, `throw`, `customizeDefaultErrorPage`) keep the derived URL; with an error URL Better-Auth's page is never shown, so a project that customized it sets `errorUrl: false`. A login page maps the `error` code to its own text and never renders `error_description`, which anyone can set through a link to `<basePath>/error`. Pinned by `tests/unit/better-auth-error-url.spec.ts` against the REAL `createBetterAuthInstance()`, including Better-Auth's own handler for `GET <basePath>/callback/microsoft` without state and `GET <basePath>/error` (mutations `iam-oauth-error-url-not-derived`, `iam-oauth-error-url-options-replace`). Implementation: `resolveErrorUrl()` in `better-auth.config.ts`; documented in `src/core/modules/better-auth/README.md` → "Where a failed sign-in lands" |
313
315
  | BetterAuth Auto Sign-In After Verification | `betterAuth.emailVerification.autoSignInAfterVerification` | Explicit Boolean — **safe default** | **`false` since 12.3.0** (was `true`, against Better-Auth's own default). With it on, `GET /iam/verify-email` creates a session for the account the link belongs to in WHATEVER browser opens it. The link is a bearer credential that travels by mail: someone who signs up with their own address and forwards the unopened link has the recipient's browser signed in to their account, and what the recipient enters there (payment data, documents, messages) lands with them — login CSRF, the same class §10 of `.claude/rules/better-auth.md` closes for sign-in. Off, the user verifies and then signs in once. Matched with `=== true` in BOTH places that read it — `better-auth.config.ts` (what Better-Auth receives) and `CoreBetterAuthEmailVerificationService.shouldAutoSignIn()` (what a project asks) — so a truthy non-boolean (the string `"true"` in `NEST_SERVER_CONFIG`; `NSC__*` already coerces `true`) cannot switch it on, and the two cannot disagree. Pinned by `tests/unit/better-auth-auto-sign-in.spec.ts` against the REAL `createBetterAuthInstance()` (mutations `iam-auto-sign-in-after-verification-default-on`, `iam-auto-sign-in-service-default-on`) |
314
316
  | BetterAuth Native Password Reset | `betterAuth.emailAndPassword.passwordReset` | Explicit Boolean | **`true` — ON by default, and there is no other off switch.** Better-Auth treats the PRESENCE of an `emailAndPassword.sendResetPassword` hook as the enable flag, and `CoreBetterAuthModule` always injects one (delegating to `CoreBetterAuthEmailVerificationService.sendPasswordResetEmail()`). So `POST /iam/request-password-reset` is a live, **unauthenticated**, token-minting, mail-sending endpoint on every deployment — before 11.36.1 it answered `RESET_PASSWORD_DISABLED` because no hook was wired. Set `false` to withhold the hook and restore that refusal, for deployments whose reset policy is support-mediated or SSO-primary. **Two things bound the abuse and both need checking:** a per-ADDRESS cooldown in the mailer (reuses `emailVerification.resendCooldownSeconds`, own namespace so a pending verification mail cannot block a reset), and the IP-axis `betterAuth.rateLimit` in front of the route — which is OFF unless configured. `/request-password-reset` is in `strictEndpoints`, so it gets the halved limit. Implementation: `better-auth.config.ts` (graft), `core-better-auth-email-verification.service.ts` (delivery) **Swagger (11.42.9):** `false` also removes `/request-password-reset`, `/reset-password` and `/reset-password/{token}` from the document `setupSwagger()` builds — without the hook no token can be minted, so none of them can succeed |
315
317
  | BetterAuth Password-Reset Brevo Template | `betterAuth.emailVerification.passwordResetBrevoTemplateId` | Presence Implies Enabled | `undefined` → SMTP/EJS path. When set, the reset mail goes out through the Brevo transactional API with that template id. **Deliberately does NOT fall back to `brevoTemplateId`**: that one is the VERIFICATION mail, and reusing it would tell somebody who asked to reset their password to confirm their address instead. A Brevo send that resolves to `null` (its way of reporting failure unless `brevo.throwOnError` is set) falls THROUGH to SMTP rather than returning, so an outage does not leave a locked-out user with no mail at all. Template variables: `name`, `link`, `appName` |
@@ -326,7 +328,7 @@ This pattern is currently applied to:
326
328
  | 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` |
327
329
  | Primitive Parameter Types | `security.mapAndValidatePipe.rejectObjectsForPrimitiveTypes` | Explicit Boolean — **safe default** | **`true` since 12.8.0 (DEV-4144).** `MapAndValidatePipe` answers 400 `#LTNS_0306 [<parameter>]` when a request value is a PLAIN OBJECT where the route declares `string`, `number` or `boolean` (`@Body('token') token: string`, `@Query(…)`, `@Param(…)`; metatype `String` / `Number` / `Boolean`). Before, the pipe returned basic-type values unchecked — the declared type is erased at runtime — so `{ "token": { "$ne": null } }` reached the service as a MongoDB operator (DEV-4143: a reset token that set somebody else's password). `null` and arrays pass on purpose (clearing an optional field; a repeated query key). NOT covered, guard at the query with `isQueryableString()`: a class-typed parameter whose DTO field has no type validator (`isAny`, a custom `validator` that does not check the type), `any`, a UNION the compiler emits as `Object` (`tsc` with `strictNullChecks` does so for `string | undefined`; SWC and `tsc` without it emit `String`, then it is covered), a NUMBER at a `string` parameter (passes on purpose; MySQL / MariaDB compare it numerically), a value a project reads from `req.body` / `req.query` itself, and a value that reaches an aggregation pipeline. Only an explicit `false` switches it off; with `security.mapAndValidatePipe: false` the whole pipe — this check included — is off. Pinned by `tests/unit/primitive-param-objects.spec.ts` (mutation `primitive-param-object-accepted`) and `tests/primitive-param-objects.e2e-spec.ts` (mutation `primitive-param-object-reaches-route`). Implementation: `common/pipes/map-and-validate.pipe.ts` → `receivesObjectForPrimitive()` |
328
330
  | String Cookies Only | `security.stringCookiesOnly` | Explicit Boolean — **safe default** | **`true` since 12.8.0 (DEV-4144).** `StringCookiesMiddleware` (registered by `CoreModule` for all routes, right after the request context) removes every non-string value from `req.cookies`, and from `req.signedCookies` everything but strings and `false` (cookie-parser's invalid-signature marker). cookie-parser turns a cookie value starting with `j:` into the parsed JSON, so `iam.session_token=j:{"$ne":null}` arrived as an object (DEV-4138); on MySQL / MariaDB a number (`j:7`) is compared numerically. The framework writes only string cookies. Only an explicit `false` switches it off — for a project that writes `res.cookie(name, object)` and reads the object back. Pinned by `tests/unit/primitive-param-objects.spec.ts` (mutation `object-cookie-kept`) and `tests/primitive-param-objects.e2e-spec.ts` (mutation `string-cookies-middleware-not-registered`). Implementation: `common/middlewares/string-cookies.middleware.ts` |
329
- | 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` |
331
+ | 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` |
330
332
  | 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`) |
331
333
  | 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) |
332
334
  | 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 |
@@ -352,6 +354,8 @@ This pattern is currently applied to:
352
354
  | Trust Proxy | `trustProxy` | Explicit Value (pass-through, Express default) | `false` (Express's own default — the forwarded chain is not trusted). Passed verbatim to `app.set('trust proxy', …)` by `CoreTrustProxyInitializer`, a `CoreModule` provider, so a consumer inherits it by upgrading and needs no `main.ts` edit. Accepts `false` / a hop count (`1`, `2`) / `'loopback'` / a subnet list — **not** Express's predicate function: the value must survive `NEST_SERVER_CONFIG` / `NSC__*` (JSON) and the ConfigService deep clone. **This is what makes `request.ip` correct, and every IP-keyed rate limit depends on it**: unset behind Caddy/nginx/an ingress, `req.ip` is the PROXY address for every request, so all clients share ONE bucket and `auth.rateLimit.max` throttles everybody at once — exactly fleet-wide once `redis` is configured. Trusting MORE hops than exist is the opposite failure: a client prepends its own header entry and picks a fresh bucket per request. Applied at module init (inside `app.init()`/`listen()`, i.e. AFTER `main.ts`), so a configured value wins over a hand-written `app.set()`; an UNSET value is never applied, which keeps `app.set('trust proxy', fn)` in `main.ts` available as the escape hatch for the predicate form. **Unset + an IP-keyed limiter enabled (`auth.rateLimit` / `betterAuth.rateLimit`) logs a boot warning naming the shared-bucket consequence**; `trustProxy: false` is the explicit "nothing proxies me" answer that silences it. The AI limiter keys on the user id and is unaffected |
353
355
  | Outbound URL Guard (SSRF) | `security.allowPrivateOutboundTargets` | Explicit Boolean with DERIVED default | **Opt-in helper for URLs a USER entered** (webhooks, export targets, ERP addresses) — `outboundFetch()`, `assertOutboundUrlAllowed()`, `createOutboundDispatcher()` in `common/helpers/outbound-url.helper.ts` (11.42.0). Nothing is applied globally: configured targets (AI providers, SMTP, S3, Redis, Brevo) never go through it. Refuses loopback, RFC 1918, link-local incl. `169.254.169.254`, CGNAT, `0/8`, benchmarking, multicast/reserved, IPv6 unspecified/loopback/IPv4-compatible (`::/96`), NAT64, ULA, link-local and multicast, and IPv4-mapped IPv6 in every notation (canonicalised through the URL parser). Checked TWICE: on the URL before sending (readable `OutboundUrlBlockedError`) and on every connection through an undici `Agent` with a guarded connector — the only place that sees a redirect's next hop and a DNS answer at connect time (rebinding). **Unset → derived from the environment**: allowed in `local`, `e2e`, `ci`, refused everywhere else — deliberately including `test`, a DEPLOYED stage in starter-based projects; `true`/`false` (also the strings, from `NSC__SECURITY__ALLOW_PRIVATE_OUTBOUND_TARGETS`) decide explicitly. Per call, `allowedHosts` frees single internal hosts (`'erp.local:8443'` = that port, `'erp.local'` = any port) without opening the rest — re-checked per connection, so a redirect does not inherit it. `outboundFetch()` uses undici's OWN `fetch` (runtime dependency `undici` since 11.42.0), because Node 22's built-in fetch bundles a different undici major than the agent |
354
356
  | AI Egress Allowlist (SSRF) | `ai.allowedBaseUrlHosts` | Explicit Value — **unset = permissive**, malformed = INTERPRETED or reported, never silently off | `undefined` → no restriction, so a local provider (Ollama on `localhost:11434`) works out of the box. Set → only those hosts are reachable, matched against `URL.host` (incl. port) and `URL.hostname`. **Accepts an array OR a comma-separated string, and the string form is not a convenience** — it is what the framework's own env mapping produces: `NSC__AI__ALLOWED_BASE_URL_HOSTS` becomes `{ ai: { allowedBaseUrlHosts: '<string>' } }` and lodash `merge` assigns that scalar straight over a configured array. Until 11.39.x a bare `!Array.isArray(...) -> return` read that as "not configured" and skipped the check entirely, so the canonical `NSC__` spelling silently disabled SSRF egress control with no log line at all. Entries are trimmed, lowercased and stripped of a fully-qualifying trailing dot, and the SAME normalisation is applied to the URL, so neither side wins by spelling one DNS name differently; a bare hostname entry matches any port, and an entry naming the scheme's default port (`example.com:443` on https) also matches the portless URL. A value that is neither array nor string carries no hostnames — the allowlist is then inactive and that is LOGGED as an error, because from the outside it looks exactly like "correctly unset". Enforced on **all three** outbound paths (`chat()`, the capability `probe()`, and `probeContextWindow()` — the last was unguarded before 11.39.x and is reachable from an ordinary user prompt via `detectAndPersistCapabilities()`, before the rate limit). Implementation: `openai-compatible.provider.ts` → `assertBaseUrlAllowed()` / `resolveAllowedBaseUrlHosts()` |
357
+ | AI Agent Functions | `ai.agentFunctions` | Boolean Shorthand + Presence Implies Enabled — absent = off | **Absent → nothing loaded (12.10.0)**: `@nestjs/ai` is not imported. `true` / `{}` offers every `@AgentFunction()` method of the application (`@nestjs/ai`'s `AiTools`) as a tool of the assistant and of `/ai/mcp`; `include` / `exclude` name agent functions; `false` / `{ enabled: false }` off. Every gate of the AI module runs first (registry role filter, tool policies and grants, `authorize()`, confirmation, plan mode, budgets), then `CoreAiAgentFunctionBridge` hands the call to `AiTools.call()` with the run's HTTP request (`RequestContext.getRequest()`) as the caller, so `@nestjs/ai`'s validation and the application's guards (context `'ai'`) run on top. Roles / `mutating` / `destructive` / `authorize` from `@AiAgentFunction()`; roles default to the method's `@Roles()`, else `S_USER` — never open. An agent function with `scopes` is not offered (the assistant has no scopes); one named like a registered tool stops the boot; `@nestjs/ai` missing, outside `>=0.0.2 <0.0.3`, or no `AiModule.forRoot()` imported → boot error naming the tested range (`AiSdkPackageError`). Pinned by `tests/unit/ai-agent-function-bridge.spec.ts` (mutations `ai-agent-function-default-roles-open`, `ai-tool-standard-schema-unvalidated`, `ai-tool-result-secrets-kept`). Implementation: `services/core-ai-agent-function.bridge.ts` |
358
+ | AI SDK Transport | `providerType: 'nestjs-ai'` (connection) / `LlmProviderFactory.registerAiSdkModel()` (code) | Explicit Value — inert until a connection names it | **Nothing loaded until a connection uses it (12.10.0).** A connection of `providerType: 'nestjs-ai'` calls the model its `model` names in `AiModule.forRoot({ models })` (`AiModels.get()`), wrapped in `@nestjs/resilience` (3 attempts on what the provider marks retryable, then a timeout of the connection's `timeoutMs`); `baseUrl` is informative there. `registerAiSdkModel(providerType, (connection, { fetch }) => LanguageModel)` runs database-managed connections (encrypted key, per tenant) on an AI SDK model the project builds — the `fetch` refuses hosts outside `ai.allowedBaseUrlHosts` (`createAiEgressFetch()`), the AI SDK retries twice. Native tools are sent WITHOUT `execute` (the SDK returns the calls; mutation `ai-sdk-tools-carry-execute`); an attachment URL the model cannot read is downloaded through `outboundFetch()` (mutations `ai-sdk-attachment-download-unguarded`, `ai-sdk-download-hook-unwired`), streamed and capped — 20 MB each, 50 MB and 10 downloads per call, never trusting `Content-Length` (mutation `ai-sdk-attachment-read-unbounded`); the builder's `fetch` is pinned by `ai-sdk-builder-fetch-unguarded`. `ai` (`>=7.0.0 <8`), `@nestjs/ai` (`>=0.0.2 <0.0.3`), `@nestjs/resilience` (`>=0.0.3 <0.0.4`) are optional peers, checked by version AND by the members called (`AI_SDK_TESTED_RANGES`, mutation `ai-sdk-version-gate-open`). Implementation: `providers/ai-sdk.provider.ts`, `ai-sdk.packages.ts`, `ai-egress.helper.ts` |
355
359
  | AI Run Time Limit | `ai.maxRunMs` | **Numeric Sentinel — Family A** (`0` = no limit) | `0` (omitted = unbounded, the previous behaviour). Wall-clock ceiling for ONE prompt run, checked before each agent-loop iteration; once exceeded the run stops and answers with whatever it has. **Without it a run's only bound is `maxIterations` MULTIPLIED BY the connection's per-call timeout** — 8 iterations at the 120s default is a request that can legitimately hold a socket, its message buffer and a request context for 16 minutes, and compaction can add a call per iteration on top. Guarded as `maxRunMs > 0`, never `<= 0`: a value arriving as a non-numeric string through `NSC__AI__MAX_RUN_MS` (the reader coerces only `'true'`, `'false'` and numbers) yields `NaN`, and `NaN > 0` is `false`, so a misconfiguration degrades to "no limit" rather than to an instantly-expired deadline that would break every prompt. Set it to something a client would actually wait for. Implementation: `core-ai.service.ts` -> `runDeadlineExceeded()` |
356
360
  | AI Assistant | `ai` | Presence Implies Enabled | Core: `maxIterations: 5`, `defaultMode: 'auto'` (or `'plan'`), `rateLimit` (presence implies enabled: `max: 20`, `windowSeconds: 60`), `systemPrompt`, `documentation` (injected into the system prompt), `encryptionSecret`. **DB-backed LLM connections** (`aiConnections`, admin CRUD) with AES-256-GCM-encrypted API keys (`AiCryptoService`, secret from `ai.encryptionSecret` / `NSC__AI__ENCRYPTION_SECRET` / `SECRETS_ENCRYPTION_KEY`; `apiKeyEncrypted` is a global `secretFields` entry, never returned — only `hasApiKey`); optional `defaultConnection` one-time seed. **Provider abstraction** (`ILlmProvider`, default `OpenAiCompatibleProvider` for any OpenAI-compatible endpoint via `fetch`; per-connection `supportsNativeTools`/`supportsJsonResponse` capabilities, emulated tool calling when native tools are unavailable). **Tool registry** (`AiToolRegistry`, tools self-register, role-filtered — under multi-tenancy (11.42.0+) a tool's roles resolve like `@Roles()` in `CoreTenantGuard`: global roles against `user.roles`, tenant roles against the request's membership role, ADMIN bypass only where `adminBypass` grants it, so chat and MCP never exceed the user's own rights; an MCP session reads the user per request, so a revoked role stops working without a reconnect; tools may be `mutating`/`destructive` and define `authorize()` for pre-flight data-level checks). **Plan mode** (`input.mode: 'plan'`): full plan → pre-flight authorize ALL steps → all-or-nothing execution with a translated (de/en) error when any step is not permitted. **Confirmation policy**: `confirmation.mutating: { default, enforced }` + client `input.requireConfirmation` (ignored when enforced); `destructive` always confirms. **Client metadata** (`input.metadata`: URL/nav/console logs, untrusted+capped). **Multi-turn conversations** (`aiConversations`, owner-scoped). **SSE streaming** (`POST /ai/stream`). **Audit** (`audit: false` → persist to `aiInteractions`, admin-readable). **Token budgets** (`budget: { period: 'day'|'month'|'none', user: { maxTokens?, maxPrompts? }, tenant: { maxTokens?, maxPrompts? } }`, requires audit): per-user AND per-tenant limits with config defaults; admins override per user/tenant at runtime (`aiBudgetLimits`, `CoreAiBudgetService`). Resolution: override → default → unlimited (missing/0 = unlimited). Enforced before the run (HTTP 429 + translated). Each response carries a compact `budget` summary (promptTokens, usedTokens, remainingTokens, resetAt); full breakdown via `aiUsage` query / `GET /ai/usage`. **Self-optimizing prompts**: the system prompt is assembled from keyed fragments (`CoreAiPromptBuilderService` ships built-in defaults; works with zero rows). Admin-editable overrides per slot (`aiSlots`, admin CRUD, `/ai/slots`) scoped by `key`/`locale`/`capability`/`tenantId`, with tenant override/reset semantics and placeholder tokens resolved at run time via the placeholder registry. **Governed learning loop** (`promptLearning: { enabled: true, autoApply: false }`): tool errors record `suggested` hints (`aiPromptHints`, admin CRUD, `/ai/prompt-hints`) that only reach the prompt once admin-approved (or auto-approved when `autoApply`); hints only ADD guidance, never relax permissions. **Context window** (`contextWindow`, default 8192 — the fallback for connections without a window of their own; native tool definitions count against the input budget and a system prompt plus tools above half of it is warned about once per connection since 12.3.0; auto-detected per connection via `ILlmProvider.detectContextWindow()` — Ollama `/api/show` probe / known-model table / Claude alias — and persisted): per-user/session history is trimmed (oldest non-system turns dropped, last truncated) and tool-results capped to `maxToolResultChars` (default 12000) so a session never overflows the model. A connection's window can be seeded via `ai.defaultConnection.contextWindow` (validated: a non-positive/non-integer value is dropped with a warning). **Capability drift check** (`capabilityDriftCheck`, default `false`): opt-in boot self-check that probes each enabled connection with an EXPLICIT `supportsNativeTools`/`supportsJsonResponse` (built with those flags cleared so the endpoint is actually re-probed) and logs a warning on mismatch — the stored value is never changed. OFF by default because it makes outbound calls to the LLM endpoints on every boot; also skipped in the ci/e2e runners. **Deferred tool schemas** (`deferToolSchemas`, default `false`): the system-prompt tool catalog then lists only tool NAMES + descriptions instead of full JSON schemas, and the model fetches a schema on demand via the built-in `search_tools` meta-tool — with a large registry the schemas alone can dominate a small context window. `deferToolSummaryChars` (default `0` = untruncated) additionally caps each description in that DEFERRED catalog: whole sentences up to the cap (always at least the first), word-boundary cut when the first sentence already exceeds it, and a `…` marker appended ON TOP of the cap. The default of `0` keeps the saving opt-in, so enabling `deferToolSchemas` alone never changes what a description says; set roughly 200–400 alongside it to actually reclaim the context. Both apply to EMULATED providers only — a connection with `supportsNativeTools: true` receives every full description + schema via `buildToolSchemas()` regardless, so truncation and the banner are skipped there rather than asserting a cut the tool payload contradicts. **Native catalog** (`nativeToolCatalog`, 12.3.0+): such a connection's prompt catalog lists names only (`'names'`, default) instead of repeating what the payload carries; `'full'` restores it. Emulated connections and plan mode keep the full catalog. The omitted tail is where preconditions and role restrictions usually live — the catalog banner tells the model to fetch the full text via `search_tools` first, but this is model GUIDANCE only: authorization is enforced server-side by the registry's role filter (`forUser()`), the execution-time re-check, and the `mutating`/`destructive` flags read by the confirmation gate — never by what the catalog shows. (`AiTool.authorize()` runs before EVERY execution since 12.3.0 — auto mode, plan mode, MCP — on the arguments after the PreToolUse hooks, fail-closed; a refusal is `TOOL_NOT_AVAILABLE` with its reason and no learning signal, and `data` reaches `execute()` as `context.authorization.data`. Data access in `execute()` still goes through `CrudService` with `context.serviceOptions`.) **MCP server** (`mcp: false` → `/ai/mcp` Streamable HTTP, Bearer auth, lazy `@modelcontextprotocol/sdk`; since 12.3.0 `tools/call` applies the admin's tool policies (`deny` refuses, `ask` asks), `authorize()` and the confirmation of `destructive` tools (and `mutating` ones under `ai.confirmation.mutating`) through MCP elicitation — only an explicit yes runs the tool, a client without elicitation gets a refusal; `mcp.confirmation` (`true` default, `false`, `{ default, enforced }`, only `false` / `enforced: true` count) is the default each user may switch for themselves like a "bypass permissions" mode via `GET/PUT /ai/settings` / `aiSettings` / `updateAiSettings` (stored in `aiUserSettings`, 403 `#LTNS_0609` while enforced); `tools/list` annotates `destructive` / `mutating` tools (`destructiveHint`, `readOnlyHint: false`), an unflagged tool gets none — never advertised as read-only; `mcp.stateless: true` (12.3.0+, default `false`) serves `/ai/mcp` without sessions — a server and transport per POST, no `mcp-session-id`, a sent one ignored, GET / DELETE 405 with `Allow: POST`, auth and tenant per request — so any replica answers and no sticky sessions are needed; no server-initiated messages or requests there, so no elicitation: a tool that needs confirmation is refused unless the user or `mcp.confirmation` switched the question off; the consent page's wording and CSS change through `renderMcpOAuthConsentPage(view, { texts, styles })` from an overridden `renderConsentPage()` (code/config only; a `<` in styles is neutralized, CSP blocks external loads); who may use MCP at all is `ai.mcp.roles` (12.8.6+; see the MCP Access row) or an overridden `mayUseMcp()`, and a project's own notice on the consent route goes through `sendConsentNotice(res, { title, message })` — the framework applies the page's security headers, which stay unexported; `mcp: { oauth: true, oauthSecret }` adds OAuth 2.1 — HMAC tokens + PKCE S256 + dynamic registration. **Since 11.43.0 `CoreAiMcpOAuthInitializer` mounts the endpoints during `app.init()` (`onModuleInit`)** — behind the Nest middleware and routes, ahead of Nest's not-found handler; `mountAiMcpOAuth(app)` after `app.init()`, the documented way before, sat behind that handler and answered 404 everywhere, and is a no-op now. The protected resource is described at the path Nest registered `/ai/mcp` at (global prefix + exclusions, URI versioning, `RouterModule`, via Nest's own `RoutePathFactory`), and the MCP 401 names that metadata URL — plain `Bearer` without OAuth. Issuer: `mcp.oauthBaseUrl` (its origin is added to Better-Auth's `trustedOrigins`, explicit list included, via `withMcpOAuthIssuerOrigin()`), else `baseUrl`; a deployed environment with neither fails the boot. Signing secret required everywhere except `local` / `ci` / `e2e` (`allowsDevelopmentSecret()` → `isLocalEnv`), deployed `develop` / `test` stages included. Under a global prefix the consent page resolves the session itself (the Better-Auth middleware runs below the prefix only) and signs in at the prefixed IAM path. Express only (boot error otherwise); an application context without HTTP server mounts nothing. Consent: a built-in page (`authorizeConsent()` default) — sign-in through Better-Auth on the API origin (password + TOTP/backup code; passkey/social via `mcp.oauthLoginUrl`, default `<appUrl>/auth/login`), then Allow/Deny as a form POST with a CSRF token signed and bound to user, client, redirect URI and PKCE challenge (10 min); Allow is `disabled` until a nonce'd guard arms it and counts a click only after intent (visible + focused + pointer move / key / touch ≥ 600 ms later — against double-clickjacking); the account is shown first with "use another account"; own CSP with nonces + `frame-ancestors 'none'`, everything escaped; boot warning without Better-Auth; restyle via `renderConsentPage()`, replace via the `mcpOAuthService` override. A code saved while answering a GET to `/authorize` is refused for every consent implementation. Since 12.3.0 an error the SDK finds before the provider's `authorize` runs (a malformed request) is answered with 400 instead of a 302 to the client's self-registered redirect URI — that was an open redirect on the API domain (RFC 9700 §4.11.2); registration stays open (no redirect-URI allowlist, claude.ai / ChatGPT / Cursor / Claude Code register their own), and the built-in Deny needs the consent token like Allow (`mountAiMcpOAuthRouter()` wraps the SDK router, `authorizeConsent()`). Refusals are SDK `OAuthError` classes (`invalid_grant` etc.), never a plain `Error`, which the SDK answers as 500). Overrides via `CoreModule.forRoot(env, { ai: { budgetService, connectionResolver, connectionService, controller, conversationService, interactionService, mcpClientService, mcpOAuthService, modeService, placeholderRegistry, preferenceService, promptBuilder, promptHintService, promptService, resolver, service, slotService, toolGrantService, toolPolicyService, userSettingService } })` |
357
361
  | MCP Access | `ai.mcp.roles` | Explicit Value — **unset = everyone**, invalid = BOOT ERROR (never "everyone") | **Unset → every signed-in user may use MCP, as before 12.8.6.** An array of role names or a comma-separated string (`NSC__AI__MCP__ROLES=admin,support`) limits MCP to users whose own (global) `roles` hold one of them — never a tenant membership role; list `admin` too if administrators should. Checked by `CoreAiMcpOAuthService.checkMcpAccess()` → `mayUseMcp(user, req)` on EVERY request to `/ai/mcp` (POST, GET, DELETE; the user's session token or JWT as bearer and MCP OAuth access tokens alike → 403, so an open session ends with its next request), on the consent route (the refusal notice of `consentRefusal()`, 403, instead of the form) and on `/token` (authorization code and refresh token → `invalid_grant`, the rotated refresh token is revoked; the user's roles come from `loadUser()`, a user it cannot load counts as holding none). Exists because until 12.8.5 there was no account-level rule: a refusal a project built into `authorizeConsent()` was bypassed with the user's own session or JWT as bearer, which never passes `/authorize`, and earlier grants kept refreshing. A value that names no role (`[]`, `''`, an empty entry, a non-string) or a system role fails the boot in `onModuleInit()` and refuses at runtime for a subclass that skips it. Any other rule: override `mayUseMcp()` in the `mcpOAuthService` subclass — only an explicit `true` admits, a throw refuses and is logged. Pinned by `tests/unit/ai-mcp-access.spec.ts` (mutations `mcp-route-skips-access-check`, `mcp-consent-ignores-access`, `mcp-refresh-ignores-access`). Implementation: `core-ai-mcp-oauth.service.ts`, `core-ai-mcp.controller.ts` |
@@ -179,7 +179,7 @@ entry, `ws`: GHSA-37g9-w4hg-h9qr (high, pre-auth memory-exhaustion DoS, patched
179
179
  `@nestjs/graphql` 14.2.1 exact-pins, and the GraphQL WebSocket server runs on that copy. The advisory was published
180
180
  by the ws maintainers on 2026-11-12 and was not yet in GitHub's global database when the entry was added, so
181
181
  `pnpm audit` did not report it — read the advisories of a package's own repository when a release announces a
182
- security fix. Its target moves in lockstep with the declared `ws` dependency (`docs/security-overrides.md`). An override is only necessary if removing it lets the package resolve
182
+ security fix. Its target moves in lockstep with the declared `ws` dependency (`docs/security-overrides.md`). Since 12.10.0 a second entry, `minimatch` 11 -> 11.0.9: `@nestjs/cli` 12.0.13 exact-pins 11.0.5, covered by three moderate advisories (dev tooling only; the target is the newest 11.x, because an older one held every other `^11` consumer back). And a third, `i18next` 26 -> 26.4.4: `@compodoc/compodoc` 2.0.0 exact-pins 26.3.3, covered by two repository advisories that were not yet in GitHub's global database (dev tooling only). An override is only necessary if removing it lets the package resolve
183
183
  back INTO its vulnerable range (verify with a with/without lockfile diff; `pnpm audit` is the arbiter).
184
184
  "Cheap insurance against a parent re-pinning downwards" is not a reason to keep one: `pnpm audit` and
185
185
  `check:overrides` run on every `check` and report such a regression the day it happens. Each surviving entry carries its CVE rationale as a comment. Remove an entry once its parent dependency ships a fixed version.
@@ -344,9 +344,9 @@ nothing in the repo could have said so.
344
344
  anywhere. A drifted override is at least still visible.
345
345
 
346
346
  `pnpm run check:overrides` re-checks every listed GHSA against the GitHub Advisory API and **fails**
347
- on `FIX AVAILABLE` (a `first_patched_version` now exists) or on a withdrawn advisory. An unreachable
348
- API is reported as `UNVERIFIED` and tolerated locally — but **fails under `CI`**, because a skip
349
- nobody reads is indistinguishable from a check that ran.
347
+ on `FIX AVAILABLE` (a `first_patched_version` now exists) or on a withdrawn advisory that npm's audit
348
+ no longer lists (below). An unreachable API is reported as `UNVERIFIED` and tolerated locally — but
349
+ **fails under `CI`**, because a skip nobody reads is indistinguishable from a check that ran.
350
350
 
351
351
  **A fix nobody named is still a fix.** GitHub leaves `first_patched_version` null on some advisories
352
352
  after a release outside the vulnerable range shipped: GHSA-86w9-cpqp-85rv (node-forge) read
@@ -364,9 +364,33 @@ counts only when every such release is deprecated, because some packages depreca
364
364
  | some copy has none | passes — the suppression is still justified |
365
365
  | no version the lockfile resolves is in the range any more | `NOT IN TREE` — the entry hides nothing |
366
366
  | registry or lockfile unreadable | `UNVERIFIED`, with the reason (fails under `CI`) |
367
+ | withdrawn advisory, npm's audit still lists it | passes, printed as `withdrawn … npm still lists it` — remove the entry once `pnpm audit` is clean without it |
368
+ | withdrawn advisory, npm's audit no longer lists it (or the lockfile resolves none of its packages) | `FIX AVAILABLE` (the advisory was WITHDRAWN) — remove the entry |
369
+ | withdrawn advisory, npm's audit endpoint unreachable | `UNVERIFIED`, with the reason (fails under `CI`) |
370
+
371
+ **A withdrawal reaches npm late (the last three rows).** GitHub withdrew GHSA-fc5q-39xc-vjpf
372
+ (picomatch `<= 4.0.7`) at 15:38:56 UTC on 2026-11-18, and npm's audit feed listed it until about
373
+ 17:15 UTC. The guard failed a withdrawn advisory on sight, so for those 1.5 hours no pipeline could be
374
+ green: with the entry `check:overrides` failed, without it `pnpm audit` did. A withdrawn advisory now
375
+ counts as obsolete only once npm's audit no longer lists it for the versions the lockfile resolves.
376
+ The audit report cannot answer that, because a suppressed advisory is removed from it, so the guard
377
+ asks pnpm's own source: npm's bulk advisory endpoint on the registry pnpm installs from. Verified
378
+ 2026-11-19:
379
+
380
+ ```
381
+ POST <registry>/-/npm/v1/security/advisories/bulk
382
+ { "picomatch": ["2.3.1", "4.0.7"] }
383
+ → { "picomatch": [{ "id": 1115549, "url": "https://github.com/advisories/GHSA-3v7f-55p6-f55p", "vulnerable_versions": "<2.3.2", … }] }
384
+ ```
385
+
386
+ npm filters by version itself and leaves out a package with no advisory. The guard matches the answer
387
+ by GHSA id (the `url` ends in it), never by package: in the example npm lists two OTHER picomatch
388
+ advisories, and "picomatch is listed" would keep a withdrawn one alive for good (mutation
389
+ `withdrawn-npm-listing-matches-package`; the other direction is `withdrawn-suppression-ignores-npm-listing`).
367
390
 
368
391
  `--advisory-file` runs stay offline: they take packuments from `--packument-file` and never ask the
369
- registry.
392
+ registry or npm's audit endpoint. A withdrawn entry there states the listing with `npmListed: true` /
393
+ `false`; an entry without it (or with a non-boolean) fails as obsolete, as before.
370
394
 
371
395
  One consequence worth knowing before you reach for this mechanism: the guard fires when the advisory
372
396
  has a patched version for **any** affected range. For most findings that is the honest outcome — a
@@ -460,13 +484,15 @@ which is how the hole this feature closes came about in the first place.
460
484
 
461
485
  **Current entry (since 2026-10-31, owner decision, DEV-3899).** `GHSA-g3hv-75wg-m249` (minimatch
462
486
  `< 11.0.1`, moderate), fixed only in a new major released 2026-10-27 that its remaining consumers cannot
463
- take yet — `@swc/cli` 0.8.2, `@ts-morph/common` 0.29.0 and nodemon 3.1.14, each on its newest release
464
- (re-verified 2026-11-09; `@nestjs/cli` 12.0.12 and glob 14 moved to minimatch 11). The justification is in
465
- the comment above `ignoreGhsas`, the declaration in `unusableFixConsumers`.
466
- `tests/unit/audit-suppression-scope.spec.ts` allows minimatch in the production tree only under
467
- `@ts-morph/common` (ts-morph, the Permissions module's scanner, matching globs the developer writes) — its
468
- `prodVia` form. `GHSA-3g3m-2fjr-6pw4` (glob `<= 14.0.1`) was a second entry until 2026-11-09 (nest-server
469
- 12.8.4), when rimraf 6.1.4 moved to glob 14.0.4 and no affected glob remained.
487
+ take yet — `@swc/cli` 0.8.2 and nodemon 3.1.14, both dev tooling, each on its newest release
488
+ (re-verified 2026-11-19; `@nestjs/cli` 12.0.12 and glob 14 moved to minimatch 11, and `@ts-morph/common`
489
+ 0.29.1 on 2026-11-16). The justification is in the comment above `ignoreGhsas`, the declaration in
490
+ `unusableFixConsumers`. `tests/unit/audit-suppression-scope.spec.ts` keeps every vulnerable minimatch (< 11)
491
+ out of the production tree. Until nest-server 12.10.1 it allowed one production path, `@ts-morph/common`
492
+ 0.29.0 (the Permissions module's scanner), in its `prodVia` form; a fresh resolve then picked 0.29.1 and
493
+ `check:overrides` reported the stale declaration as RE-TEST. `GHSA-3g3m-2fjr-6pw4` (glob `<= 14.0.1`) was a
494
+ second entry until 2026-11-09 (nest-server 12.8.4), when rimraf 6.1.4 moved to glob 14.0.4 and no affected
495
+ glob remained.
470
496
 
471
497
  **Before that, no entry from 2026-10-24.** `GHSA-vfj7-8cjw-p6xm` (braces, via nodemon / npm-watch) was
472
498
  listed from 2026-10-11 to 2026-10-24: a dev-tooling-only path of an advisory with no patched release
@@ -502,6 +502,18 @@ reserved for a socket whose rights changed while it was open (above). Pinned by
502
502
  `tests/subscription-session-iam.e2e-spec.ts` / `tests/subscription-session-legacy.e2e-spec.ts` (mutations
503
503
  `iam-ws-handshake-refusal-throws`, `legacy-ws-handshake-refusal-throws`).
504
504
 
505
+ ## Agent function and MCP calls (12.10.0)
506
+
507
+ `@nestjs/ai` (`@AgentFunction()`) and `@nestjs/mcp` (`@Tool()` …) run every global guard around their methods with the
508
+ context types `'ai'` / `'mcp'` and the arguments `[input, call]`. Index 0 is what the model or the MCP client wrote.
509
+ `resolveGuardRequest()` answers `call.request` there — never index 0, which the HTTP fallback returned before (tool
510
+ arguments `{ "user": { "roles": ["admin"] } }` were the caller). A REQUEST-LESS caller (`caller: { user }`, a durable
511
+ run, stdio) is anonymous: public methods run, everything else is 401 in every guard, `CoreTenantGuard` included. The user
512
+ of an MCP OAuth access token reaches a `@nestjs/mcp` tool only through `createMcpTokenVerifier()`
513
+ (`MCP_VERIFIED_USER`). Pinned by `tests/unit/agent-call-context.spec.ts` (mutations `agent-call-guard-reads-arguments`,
514
+ `agent-call-context-data-reads-arguments`, `tenant-guard-requestless-agent-grants`, `mcp-verified-user-string-key`).
515
+ **When you add a guard, resolve the request through `resolveGuardRequest()`; never `switchToHttp()` on its own.**
516
+
505
517
  ## Role Check Implementation
506
518
 
507
519
  The role system is evaluated in:
@@ -412,7 +412,7 @@ pnpm run check:mutations -- --id=<id> # one mutation
412
412
  pnpm run check:mutations -- --list # the registry, without running anything
413
413
  pnpm run check:mutations -- --allow-dirty # when the fix and its evidence share a working tree
414
414
  pnpm run check:mutations -- --jobs=4 # N mutations at a time (default: 2, or 4 on >=12 cores)
415
- pnpm run check:mutations -- --no-infra # only the 445 that need no MongoDB
415
+ pnpm run check:mutations -- --no-infra # only the 501 that need no MongoDB
416
416
  pnpm run check:mutations -- --since=<ref> # only mutations touching files changed since <ref>
417
417
  pnpm run check:mutations -- --shard=2/4 # this job's quarter of the selection (CI splits the full run)
418
418
  ```
@@ -432,7 +432,7 @@ when the registry, a vitest config or a setup file changed, since those can move
432
432
  commit, and in CI alongside the publish without blocking it. The price of caching is a cache that
433
433
  has to model each spec's full dependency closure correctly, and getting that wrong produces a stale
434
434
  PASS for a test that has since gone vacuous — exactly what the gate is there to prevent. Bad trade
435
- at 688 mutations.
435
+ at 745 mutations.
436
436
 
437
437
  **Decided 2026-10-03 (repo owner): keep the full run.** Measured at 128 mutations, the CI job for
438
438
  11.41.6 took **14 minutes**. The trigger to revisit is that wall time, not the mutation count —
@@ -503,9 +503,9 @@ exactly the environment where the answer matters.
503
503
 
504
504
  ### The cost is vitest's cold start, not the tests
505
505
 
506
- Worth knowing before optimising the wrong thing: the specs behind all 243 e2e mutations add up to
506
+ Worth knowing before optimising the wrong thing: the specs behind all 244 e2e mutations add up to
507
507
  **~40 seconds**. The step takes ~740s. The remaining ~700s is paying vitest's startup — process
508
- spawn, transform, module graph, mongod connect, DB create and drop — once per mutation, 688 times.
508
+ spawn, transform, module graph, mongod connect, DB create and drop — once per mutation, 745 times.
509
509
  That work is largely single-threaded I/O and barely scales with cores: the full registry measures
510
510
  **744s on a 12-core laptop and 777s on a 4-vCPU CI runner**.
511
511
 
package/CLAUDE.md CHANGED
@@ -103,7 +103,8 @@ compatible with either downstream layout:
103
103
  The vendoring step copies `dependencies` only — it never reads
104
104
  `peerDependencies` — so a package in either of the other two sections is
105
105
  invisible to it. The live case today is `better-auth` / `@better-auth/passkey` /
106
- `@better-auth/core` (required peers since 11.37.0). `find-file-up`, the
106
+ `@better-auth/core` (required peers since 11.37.0), and since 12.10.0 the OPTIONAL peers `ai` / `@nestjs/ai` /
107
+ `@nestjs/resilience` (AI SDK transport, agent-function bridge). `find-file-up`, the
107
108
  other entry on that list, was never imported by framework code — only by the
108
109
  pre-commit hook's `extras/sync-version.ts` — and left together with `husky`
109
110
  in 11.41.8; its list entry is now inert.
@@ -251,6 +252,14 @@ The pattern: extend `AiTool`, route through a `CrudService` with
251
252
  `securityCheck`), mark mutating tools `mutating: true` and destructive ones
252
253
  `destructive: true`. Group in an `AiToolsModule` and add it to `ServerModule.imports`.
253
254
 
255
+ **NestJS AI interop (12.10.0, opt-in):** `ai`, `@nestjs/ai`, `@nestjs/resilience` are OPTIONAL peers, loaded lazily
256
+ and refused outside their tested range (`AI_SDK_TESTED_RANGES`). `providerType: 'nestjs-ai'` connections use a model of
257
+ `AiModule.forRoot({ models })`; `LlmProviderFactory.registerAiSdkModel()` plugs an AI SDK provider into DB-managed
258
+ connections (pass the guarded `fetch`); `ai.agentFunctions` offers `@AgentFunction()` methods as tools — the module's
259
+ gates first, then `@nestjs/ai`'s pipeline. Native tools never carry `execute`. In ANY project with `@nestjs/ai` /
260
+ `@nestjs/mcp` installed, our global guards run on `'ai'` / `'mcp'` contexts: resolve the request through
261
+ `resolveGuardRequest()` (never `switchToHttp()` — that is the MODEL's arguments there), a request-less caller is anonymous.
262
+
254
263
  Reference tools live at `src/server/modules/ai/tools/` (find-users, get-user,
255
264
  delete-user, update-user-job-title) — these are framework test fixtures, NOT
256
265
  auto-registered in consumer projects. See `src/core/modules/ai/INTEGRATION-CHECKLIST.md`
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-13 (v12.9.4)
3
+ > Auto-generated from source code as of 2026-11-19 (v12.10.1)
4
4
  > File: `FRAMEWORK-API.md` — compact, machine-readable API surface for Claude Code
5
5
 
6
6
  ## CoreModule.forRoot()
@@ -116,6 +116,7 @@ When `passkey` is enabled, `trustedOrigins` is required (compile-time enforcemen
116
116
 
117
117
  ### IAi
118
118
 
119
+ - `agentFunctions?`: `boolean | { enabled?: boolean; exclude?: string[]; include?: string[]; }` (default: `undefined (off)`) — Offer the application's `@nestjs/ai` agent functions (`@AgentFunction()` methods) as tools of the AI assistant and
119
120
  - `allowedBaseUrlHosts?`: `string | string[]` — Optional SSRF allowlist for connection base URLs. When set (non-empty), the
120
121
  - `audit?`: `boolean` (default: `false`) — Persist an audit record (`aiInteractions`) for every prompt run (admin-readable).
121
122
  - `budget?`: `{ period?: "day" | "month" | "none"; tenant?: { maxPrompts?: number; maxToken...` — Token/prompt budgets for AI prompts, enforced before a run (HTTP 429 + translated
@@ -1,5 +1,9 @@
1
1
  import { createParamDecorator } from '@nestjs/common';
2
+ import { isAgentCallContext, resolveAgentCallRequest } from '../helpers/execution-context-request.helper.js';
2
3
  export const RESTUser = createParamDecorator((data, ctx) => {
4
+ if (isAgentCallContext(ctx)) {
5
+ return resolveAgentCallRequest(ctx)?.user;
6
+ }
3
7
  const request = ctx.switchToHttp().getRequest();
4
8
  return request.user;
5
9
  });
@@ -1 +1 @@
1
- {"version":3,"file":"rest-user.decorator.js","sourceRoot":"","sources":["../../../../src/core/common/decorators/rest-user.decorator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAoB,MAAM,gBAAgB,CAAC;AAKxE,MAAM,CAAC,MAAM,QAAQ,GAAG,oBAAoB,CAAC,CAAC,IAAa,EAAE,GAAqB,EAAE,EAAE;IACpF,MAAM,OAAO,GAAG,GAAG,CAAC,YAAY,EAAE,CAAC,UAAU,EAAE,CAAC;IAChD,OAAO,OAAO,CAAC,IAAI,CAAC;AACtB,CAAC,CAAC,CAAC"}
1
+ {"version":3,"file":"rest-user.decorator.js","sourceRoot":"","sources":["../../../../src/core/common/decorators/rest-user.decorator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAoB,MAAM,gBAAgB,CAAC;AAExE,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,gDAAgD,CAAC;AAK7G,MAAM,CAAC,MAAM,QAAQ,GAAG,oBAAoB,CAAC,CAAC,IAAa,EAAE,GAAqB,EAAE,EAAE;IAEpF,IAAI,kBAAkB,CAAC,GAAG,CAAC,EAAE,CAAC;QAC5B,OAAO,uBAAuB,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC;IAC5C,CAAC;IACD,MAAM,OAAO,GAAG,GAAG,CAAC,YAAY,EAAE,CAAC,UAAU,EAAE,CAAC;IAChD,OAAO,OAAO,CAAC,IAAI,CAAC;AACtB,CAAC,CAAC,CAAC"}
@@ -18,6 +18,9 @@ let HttpExceptionLogFilter = class HttpExceptionLogFilter {
18
18
  if (type === 'graphql') {
19
19
  return exception;
20
20
  }
21
+ if (type !== 'http') {
22
+ return undefined;
23
+ }
21
24
  const ctx = host.switchToHttp();
22
25
  const res = ctx.getResponse();
23
26
  const status = exception.getStatus();
@@ -1 +1 @@
1
- {"version":3,"file":"http-exception-log.filter.js","sourceRoot":"","sources":["../../../../src/core/common/filters/http-exception-log.filter.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAEL,KAAK,EAEL,aAAa,EACb,UAAU,EACV,MAAM,EACN,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AASxB,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,wBAAwB,CAAC,CAAC;AAGtD,IAAM,sBAAsB,GAA5B,MAAM,sBAAsB;IAIjC,KAAK,CAAC,SAAwB,EAAE,IAAmB;QAGjD,IAAI,SAAS,CAAC,SAAS,EAAE,KAAK,UAAU,CAAC,SAAS,EAAE,CAAC;YACnD,eAAe,CAAC,KAAK,CAAC,OAAO,SAAS,CAAC,OAAO,EAAE,CAAC,CAAC;QACpD,CAAC;aAAM,CAAC;YACN,eAAe,CAAC,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACzC,CAAC;QAGD,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAkB,CAAC;QAC5C,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,OAAO,SAAS,CAAC;QACnB,CAAC;QAGD,MAAM,GAAG,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QAChC,MAAM,GAAG,GAAG,GAAG,CAAC,WAAW,EAAY,CAAC;QACxC,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,EAAE,CAAC;QAIrC,MAAM,IAAI,GAA4B,EAAE,GAAG,SAAS,EAAE,CAAC;QACvD,OAAO,IAAI,CAAC,OAAO,CAAC;QACpB,OAAO,IAAI,CAAC,KAAK,CAAC;QAClB,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,SAAS,YAAY,2BAA2B,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IACnG,CAAC;CACF,CAAA;AA/BY,sBAAsB;IADlC,KAAK,CAAC,aAAa,CAAC;GACR,sBAAsB,CA+BlC"}
1
+ {"version":3,"file":"http-exception-log.filter.js","sourceRoot":"","sources":["../../../../src/core/common/filters/http-exception-log.filter.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAEL,KAAK,EAEL,aAAa,EACb,UAAU,EACV,MAAM,EACN,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AASxB,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,wBAAwB,CAAC,CAAC;AAGtD,IAAM,sBAAsB,GAA5B,MAAM,sBAAsB;IAIjC,KAAK,CAAC,SAAwB,EAAE,IAAmB;QAGjD,IAAI,SAAS,CAAC,SAAS,EAAE,KAAK,UAAU,CAAC,SAAS,EAAE,CAAC;YACnD,eAAe,CAAC,KAAK,CAAC,OAAO,SAAS,CAAC,OAAO,EAAE,CAAC,CAAC;QACpD,CAAC;aAAM,CAAC;YACN,eAAe,CAAC,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACzC,CAAC;QAGD,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAkB,CAAC;QAC5C,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,OAAO,SAAS,CAAC;QACnB,CAAC;QAMD,IAAI,IAAI,KAAK,MAAM,EAAE,CAAC;YACpB,OAAO,SAAS,CAAC;QACnB,CAAC;QAGD,MAAM,GAAG,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QAChC,MAAM,GAAG,GAAG,GAAG,CAAC,WAAW,EAAY,CAAC;QACxC,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,EAAE,CAAC;QAIrC,MAAM,IAAI,GAA4B,EAAE,GAAG,SAAS,EAAE,CAAC;QACvD,OAAO,IAAI,CAAC,OAAO,CAAC;QACpB,OAAO,IAAI,CAAC,KAAK,CAAC;QAClB,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,SAAS,YAAY,2BAA2B,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IACnG,CAAC;CACF,CAAA;AAvCY,sBAAsB;IADlC,KAAK,CAAC,aAAa,CAAC;GACR,sBAAsB,CAuClC"}
@@ -1,4 +1,5 @@
1
1
  import { GqlExecutionContext } from '@nestjs/graphql';
2
+ import { isAgentCallContext, resolveAgentCallRequest } from './execution-context-request.helper.js';
2
3
  export default class Context {
3
4
  static getData(context) {
4
5
  return getContextData(context);
@@ -8,6 +9,14 @@ export function getContextData(context) {
8
9
  if (!context) {
9
10
  return { args: null, currentUser: null, request: null };
10
11
  }
12
+ if (isAgentCallContext(context)) {
13
+ const agentRequest = resolveAgentCallRequest(context);
14
+ return {
15
+ args: context.getArgByIndex(0),
16
+ currentUser: agentRequest?.user,
17
+ request: (agentRequest ?? null),
18
+ };
19
+ }
11
20
  let user;
12
21
  let rawContext = null;
13
22
  let ctx = null;
@@ -1 +1 @@
1
- {"version":3,"file":"context.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/context.helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAOtD,MAAM,CAAC,OAAO,OAAO,OAAO;IAKnB,MAAM,CAAC,OAAO,CAAC,OAAyB;QAK7C,OAAO,cAAc,CAAC,OAAO,CAAC,CAAC;IACjC,CAAC;CACF;AAKD,MAAM,UAAU,cAAc,CAAC,OAAyB;IAMtD,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC1D,CAAC;IAGD,IAAI,IAA4B,CAAC;IACjC,IAAI,UAAU,GAAQ,IAAI,CAAC;IAC3B,IAAI,GAAG,GAAQ,IAAI,CAAC;IACpB,IAAI,OAAY,CAAC;IACjB,IAAI,CAAC;QACH,UAAU,GAAG,mBAAmB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACjD,GAAG,GAAG,UAAU,EAAE,UAAU,EAAE,CAAC;QAC/B,OAAO,GAAG,GAAG,CAAC,GAAG,CAAC;IACpB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;IAEb,CAAC;IAED,IAAI,IAAS,CAAC;IACd,IAAI,UAAU,EAAE,CAAC;QACf,IAAI,CAAC;YACH,IAAI,GAAG,UAAU,CAAC,OAAO,EAAE,CAAC;QAC9B,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;QAEb,CAAC;IACH,CAAC;IAGD,IAAI,GAAG,EAAE,CAAC;QAER,IAAI,GAAG,GAAG,EAAE,IAAI,IAAI,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC;IACrC,CAAC;SAAM,CAAC;QACN,OAAO,GAAG,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;QAC9E,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;YAGpB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACtB,CAAC;IACH,CAAC;IAGD,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;AAC9C,CAAC"}
1
+ {"version":3,"file":"context.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/context.helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAGtD,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAMpG,MAAM,CAAC,OAAO,OAAO,OAAO;IAKnB,MAAM,CAAC,OAAO,CAAC,OAAyB;QAK7C,OAAO,cAAc,CAAC,OAAO,CAAC,CAAC;IACjC,CAAC;CACF;AAKD,MAAM,UAAU,cAAc,CAAC,OAAyB;IAMtD,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC1D,CAAC;IAKD,IAAI,kBAAkB,CAAC,OAAO,CAAC,EAAE,CAAC;QAChC,MAAM,YAAY,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC;QACtD,OAAO;YACL,IAAI,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC;YAC9B,WAAW,EAAE,YAAY,EAAE,IAAI;YAC/B,OAAO,EAAE,CAAC,YAAY,IAAI,IAAI,CAAgB;SAC/C,CAAC;IACJ,CAAC;IAGD,IAAI,IAA4B,CAAC;IACjC,IAAI,UAAU,GAAQ,IAAI,CAAC;IAC3B,IAAI,GAAG,GAAQ,IAAI,CAAC;IACpB,IAAI,OAAY,CAAC;IACjB,IAAI,CAAC;QACH,UAAU,GAAG,mBAAmB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACjD,GAAG,GAAG,UAAU,EAAE,UAAU,EAAE,CAAC;QAC/B,OAAO,GAAG,GAAG,CAAC,GAAG,CAAC;IACpB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;IAEb,CAAC;IAED,IAAI,IAAS,CAAC;IACd,IAAI,UAAU,EAAE,CAAC;QACf,IAAI,CAAC;YACH,IAAI,GAAG,UAAU,CAAC,OAAO,EAAE,CAAC;QAC9B,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;QAEb,CAAC;IACH,CAAC;IAGD,IAAI,GAAG,EAAE,CAAC;QAER,IAAI,GAAG,GAAG,EAAE,IAAI,IAAI,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC;IACrC,CAAC;SAAM,CAAC;QACN,OAAO,GAAG,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;QAC9E,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;YAGpB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACtB,CAAC;IACH,CAAC;IAGD,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;AAC9C,CAAC"}
@@ -1,7 +1,11 @@
1
1
  import { GqlExecutionContext } from '@nestjs/graphql';
2
2
  import { getPopulateOptions } from './db.helper.js';
3
+ import { isAgentCallContext, resolveAgentCallRequest } from './execution-context-request.helper.js';
3
4
  import { removePropertiesDeep } from './input.helper.js';
4
5
  export function currentUserDec(data, ctx) {
6
+ if (isAgentCallContext(ctx)) {
7
+ return resolveAgentCallRequest(ctx)?.user;
8
+ }
5
9
  if (ctx.getType() === 'graphql') {
6
10
  const gqlContext = GqlExecutionContext.create(ctx);
7
11
  return gqlContext.getContext().req.user;
@@ -1 +1 @@
1
- {"version":3,"file":"decorator.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/decorator.helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAkB,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAGtE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAKzD,MAAM,UAAU,cAAc,CAAC,IAAI,EAAE,GAAqB;IACxD,IAAI,GAAG,CAAC,OAAO,EAAkB,KAAK,SAAS,EAAE,CAAC;QAChD,MAAM,UAAU,GAAG,mBAAmB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACnD,OAAO,UAAU,CAAC,UAAU,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC;IAC1C,CAAC;IACD,OAAO,GAAG,CAAC,YAAY,EAAE,CAAC,UAAU,EAAE,CAAC,IAAI,CAAC;AAC9C,CAAC;AAaD,MAAM,UAAU,kBAAkB,CAChC,IAAsD,EACtD,GAAqB;IAGrB,IAAI,GAAG,CAAC,OAAO,EAAkB,KAAK,SAAS,EAAE,CAAC;QAChD,OAAO,SAAS,CAAC;IACnB,CAAC;IAGD,MAAM,UAAU,GAAG,mBAAmB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACnD,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,GAAG;QACpC,OAAO,EAAE,UAAU,CAAC,UAAU,EAAE,CAAC,IAAI;QACrC,gBAAgB,EAAE,IAAI;QACtB,GAAG,IAAI;KACR,CAAC;IAGF,MAAM,eAAe,GAAG,kBAAkB,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,OAAO,CAAC,CAAC;IAC1E,IAAI,gBAAgB,EAAE,CAAC;QACrB,oBAAoB,CAAC,eAAe,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;IACpD,CAAC;IAGD,OAAO,eAAe,CAAC;AACzB,CAAC"}
1
+ {"version":3,"file":"decorator.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/decorator.helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAkB,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAGtE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AACpG,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAKzD,MAAM,UAAU,cAAc,CAAC,IAAI,EAAE,GAAqB;IAExD,IAAI,kBAAkB,CAAC,GAAG,CAAC,EAAE,CAAC;QAC5B,OAAO,uBAAuB,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC;IAC5C,CAAC;IACD,IAAI,GAAG,CAAC,OAAO,EAAkB,KAAK,SAAS,EAAE,CAAC;QAChD,MAAM,UAAU,GAAG,mBAAmB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACnD,OAAO,UAAU,CAAC,UAAU,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC;IAC1C,CAAC;IACD,OAAO,GAAG,CAAC,YAAY,EAAE,CAAC,UAAU,EAAE,CAAC,IAAI,CAAC;AAC9C,CAAC;AAaD,MAAM,UAAU,kBAAkB,CAChC,IAAsD,EACtD,GAAqB;IAGrB,IAAI,GAAG,CAAC,OAAO,EAAkB,KAAK,SAAS,EAAE,CAAC;QAChD,OAAO,SAAS,CAAC;IACnB,CAAC;IAGD,MAAM,UAAU,GAAG,mBAAmB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACnD,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,GAAG;QACpC,OAAO,EAAE,UAAU,CAAC,UAAU,EAAE,CAAC,IAAI;QACrC,gBAAgB,EAAE,IAAI;QACtB,GAAG,IAAI;KACR,CAAC;IAGF,MAAM,eAAe,GAAG,kBAAkB,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,OAAO,CAAC,CAAC;IAC1E,IAAI,gBAAgB,EAAE,CAAC;QACrB,oBAAoB,CAAC,eAAe,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;IACpD,CAAC;IAGD,OAAO,eAAe,CAAC;AACzB,CAAC"}
@@ -1,4 +1,17 @@
1
- import type { ExecutionContext } from '@nestjs/common';
1
+ import type { ArgumentsHost, ExecutionContext } from '@nestjs/common';
2
+ export declare const AGENT_CALL_CONTEXT_TYPES: ReadonlySet<string>;
3
+ export interface AgentCallLike {
4
+ authInfo?: {
5
+ [key: string]: unknown;
6
+ extra?: Record<PropertyKey, unknown>;
7
+ };
8
+ name?: string;
9
+ request?: GuardRequestLike;
10
+ }
11
+ export declare const MCP_VERIFIED_USER: unique symbol;
12
+ export declare function isAgentCallContext(context: ArgumentsHost | undefined): boolean;
13
+ export declare function agentCallOf(context: ArgumentsHost | undefined): AgentCallLike | undefined;
14
+ export declare function resolveAgentCallRequest(context: ArgumentsHost | undefined): GuardRequestLike | undefined;
2
15
  export interface GuardRequestLike {
3
16
  [key: string]: any;
4
17
  headers?: Record<string, any>;
@@ -1,7 +1,43 @@
1
+ export const AGENT_CALL_CONTEXT_TYPES = new Set(['ai', 'mcp']);
2
+ export const MCP_VERIFIED_USER = Symbol.for('lt.nest-server.mcp-verified-user');
3
+ export function isAgentCallContext(context) {
4
+ let type;
5
+ try {
6
+ type = context?.getType?.();
7
+ }
8
+ catch {
9
+ return false;
10
+ }
11
+ return typeof type === 'string' && AGENT_CALL_CONTEXT_TYPES.has(type);
12
+ }
13
+ export function agentCallOf(context) {
14
+ if (!isAgentCallContext(context)) {
15
+ return undefined;
16
+ }
17
+ const call = context.getArgByIndex(1);
18
+ return call && typeof call === 'object' ? call : undefined;
19
+ }
20
+ export function resolveAgentCallRequest(context) {
21
+ const call = agentCallOf(context);
22
+ const request = call?.request;
23
+ if (!request || typeof request !== 'object') {
24
+ return undefined;
25
+ }
26
+ if (!request.user) {
27
+ const verified = call.authInfo?.extra?.[MCP_VERIFIED_USER];
28
+ if (verified && typeof verified === 'object') {
29
+ request.user = verified;
30
+ }
31
+ }
32
+ return request;
33
+ }
1
34
  function isSubscriptionContext(value) {
2
35
  return (!!value && typeof value === 'object' && ('socket' in value || 'connectionParams' in value || 'request' in value));
3
36
  }
4
37
  export function resolveGuardRequest(context, gqlContextOf) {
38
+ if (isAgentCallContext(context)) {
39
+ return resolveAgentCallRequest(context);
40
+ }
5
41
  let gqlContext;
6
42
  try {
7
43
  gqlContext = gqlContextOf(context);
@@ -1 +1 @@
1
- {"version":3,"file":"execution-context-request.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/execution-context-request.helper.ts"],"names":[],"mappings":"AAqDA,SAAS,qBAAqB,CAAC,KAAU;IACvC,OAAO,CACL,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,QAAQ,IAAI,KAAK,IAAI,kBAAkB,IAAI,KAAK,IAAI,SAAS,IAAI,KAAK,CAAC,CACjH,CAAC;AACJ,CAAC;AAcD,MAAM,UAAU,mBAAmB,CACjC,OAAyB,EACzB,YAAgD;IAEhD,IAAI,UAAe,CAAC;IACpB,IAAI,CAAC;QACH,UAAU,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;IAAC,MAAM,CAAC;QACP,UAAU,GAAG,SAAS,CAAC;IACzB,CAAC;IAED,IAAI,UAAU,EAAE,GAAG,EAAE,CAAC;QACpB,OAAO,UAAU,CAAC,GAAG,CAAC;IACxB,CAAC;IAED,IAAI,qBAAqB,CAAC,UAAU,CAAC,EAAE,CAAC;QAItC,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC;YACxB,UAAU,CAAC,OAAO,GAAG,UAAU,CAAC,gBAAgB,IAAI,UAAU,CAAC,OAAO,EAAE,OAAO,IAAI,EAAE,CAAC;QACxF,CAAC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,IAAI,CAAC;QACH,OAAO,OAAO,CAAC,YAAY,EAAE,CAAC,UAAU,EAAE,CAAC;IAC7C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"execution-context-request.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/execution-context-request.helper.ts"],"names":[],"mappings":"AAkDA,MAAM,CAAC,MAAM,wBAAwB,GAAwB,IAAI,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;AAqBpF,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;AAGhF,MAAM,UAAU,kBAAkB,CAAC,OAAkC;IACnE,IAAI,IAAa,CAAC;IAClB,IAAI,CAAC;QACH,IAAI,GAAG,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC;IAC9B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,OAAO,IAAI,KAAK,QAAQ,IAAI,wBAAwB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AACxE,CAAC;AAGD,MAAM,UAAU,WAAW,CAAC,OAAkC;IAC5D,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,EAAE,CAAC;QACjC,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,IAAI,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;IACtC,OAAO,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAE,IAAsB,CAAC,CAAC,CAAC,SAAS,CAAC;AAChF,CAAC;AAgBD,MAAM,UAAU,uBAAuB,CAAC,OAAkC;IACxE,MAAM,IAAI,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC;IAClC,MAAM,OAAO,GAAG,IAAI,EAAE,OAAO,CAAC;IAC9B,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAC5C,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;QAClB,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC,iBAAiB,CAAC,CAAC;QAC3D,IAAI,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE,CAAC;YAC7C,OAAO,CAAC,IAAI,GAAG,QAAQ,CAAC;QAC1B,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAuBD,SAAS,qBAAqB,CAAC,KAAU;IACvC,OAAO,CACL,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,QAAQ,IAAI,KAAK,IAAI,kBAAkB,IAAI,KAAK,IAAI,SAAS,IAAI,KAAK,CAAC,CACjH,CAAC;AACJ,CAAC;AAgBD,MAAM,UAAU,mBAAmB,CACjC,OAAyB,EACzB,YAAgD;IAEhD,IAAI,kBAAkB,CAAC,OAAO,CAAC,EAAE,CAAC;QAChC,OAAO,uBAAuB,CAAC,OAAO,CAAC,CAAC;IAC1C,CAAC;IAED,IAAI,UAAe,CAAC;IACpB,IAAI,CAAC;QACH,UAAU,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;IAAC,MAAM,CAAC;QACP,UAAU,GAAG,SAAS,CAAC;IACzB,CAAC;IAED,IAAI,UAAU,EAAE,GAAG,EAAE,CAAC;QACpB,OAAO,UAAU,CAAC,GAAG,CAAC;IACxB,CAAC;IAED,IAAI,qBAAqB,CAAC,UAAU,CAAC,EAAE,CAAC;QAItC,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC;YACxB,UAAU,CAAC,OAAO,GAAG,UAAU,CAAC,gBAAgB,IAAI,UAAU,CAAC,OAAO,EAAE,OAAO,IAAI,EAAE,CAAC;QACxF,CAAC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,IAAI,CAAC;QACH,OAAO,OAAO,CAAC,YAAY,EAAE,CAAC,UAAU,EAAE,CAAC;IAC7C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC"}
@@ -0,0 +1,10 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ export declare const GRAPHQL_UPLOAD_MAX_PATH_KEYS = 64;
3
+ export declare const GRAPHQL_UPLOAD_MAX_MAP_KEYS = 10000;
4
+ export interface GraphQlUploadProcessRequestOptions {
5
+ maxFieldSize?: number;
6
+ maxFileSize?: number;
7
+ maxFiles?: number;
8
+ }
9
+ export type GraphQlUploadOperations = Array<Record<string, unknown>> | Record<string, unknown>;
10
+ export declare function processGraphQlUploadRequest(request: IncomingMessage, response: ServerResponse, { maxFieldSize, maxFileSize, maxFiles }?: GraphQlUploadProcessRequestOptions): Promise<GraphQlUploadOperations>;