@lenne.tech/nest-server 11.42.16 → 11.43.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 (55) hide show
  1. package/.claude/rules/better-auth.md +22 -0
  2. package/.claude/rules/configurable-features.md +3 -3
  3. package/.claude/rules/testing.md +4 -4
  4. package/FRAMEWORK-API.md +2 -2
  5. package/dist/core/common/interfaces/server-options.interface.d.ts +3 -0
  6. package/dist/core/modules/ai/core-ai-mcp-oauth.initializer.d.ts +19 -0
  7. package/dist/core/modules/ai/core-ai-mcp-oauth.initializer.js +145 -0
  8. package/dist/core/modules/ai/core-ai-mcp-oauth.initializer.js.map +1 -0
  9. package/dist/core/modules/ai/core-ai-mcp.controller.js +6 -5
  10. package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
  11. package/dist/core/modules/ai/core-ai.module.d.ts +2 -0
  12. package/dist/core/modules/ai/core-ai.module.js +6 -1
  13. package/dist/core/modules/ai/core-ai.module.js.map +1 -1
  14. package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.d.ts +33 -0
  15. package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.js +282 -0
  16. package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.js.map +1 -0
  17. package/dist/core/modules/ai/helpers/ai-mcp-oauth.helper.d.ts +15 -2
  18. package/dist/core/modules/ai/helpers/ai-mcp-oauth.helper.js +73 -19
  19. package/dist/core/modules/ai/helpers/ai-mcp-oauth.helper.js.map +1 -1
  20. package/dist/core/modules/ai/helpers/ai-mcp-oauth.registry.d.ts +5 -0
  21. package/dist/core/modules/ai/helpers/ai-mcp-oauth.registry.js.map +1 -1
  22. package/dist/core/modules/ai/index.d.ts +1 -0
  23. package/dist/core/modules/ai/index.js +1 -0
  24. package/dist/core/modules/ai/index.js.map +1 -1
  25. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +30 -2
  26. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +222 -15
  27. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
  28. package/dist/core/modules/better-auth/better-auth.config.d.ts +4 -0
  29. package/dist/core/modules/better-auth/better-auth.config.js +29 -2
  30. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  31. package/dist/core/modules/better-auth/core-better-auth.controller.d.ts +2 -0
  32. package/dist/core/modules/better-auth/core-better-auth.controller.js +36 -1
  33. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  34. package/dist/core/modules/better-auth/core-better-auth.service.js +9 -0
  35. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  36. package/dist/tsconfig.build.tsbuildinfo +1 -1
  37. package/docs/REQUEST-LIFECYCLE.md +1 -1
  38. package/migration-guides/11.42.x-to-11.43.x.md +195 -0
  39. package/migration-guides/11.43.0-to-11.43.1.md +73 -0
  40. package/package.json +4 -4
  41. package/src/core/common/helpers/swagger.helper.ts +4 -4
  42. package/src/core/common/interfaces/server-options.interface.ts +37 -9
  43. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +50 -24
  44. package/src/core/modules/ai/README.md +98 -13
  45. package/src/core/modules/ai/core-ai-mcp-oauth.initializer.ts +199 -0
  46. package/src/core/modules/ai/core-ai-mcp.controller.ts +13 -6
  47. package/src/core/modules/ai/core-ai.module.ts +14 -2
  48. package/src/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.ts +369 -0
  49. package/src/core/modules/ai/helpers/ai-mcp-oauth.helper.ts +149 -43
  50. package/src/core/modules/ai/helpers/ai-mcp-oauth.registry.ts +18 -5
  51. package/src/core/modules/ai/index.ts +1 -0
  52. package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +385 -28
  53. package/src/core/modules/better-auth/better-auth.config.ts +49 -5
  54. package/src/core/modules/better-auth/core-better-auth.controller.ts +75 -1
  55. package/src/core/modules/better-auth/core-better-auth.service.ts +21 -3
@@ -483,6 +483,27 @@ normalise them away; mutation `openapi-plugin-routable` drops `serverOnlyPlugin(
483
483
  red) and the "framework routes" cases in `tests/unit/swagger-helper.spec.ts`, which run against the
484
484
  REAL generator output rather than a fixture.
485
485
 
486
+ ## 10. Direct `api.*` calls must hand Better-Auth the request — or its CSRF protection does not run
487
+
488
+ `signInEmail` and `signUpEmail` carry Better-Auth's `formCsrfMiddleware`: it refuses a cross-site navigation
489
+ (`Sec-Fetch-Site: cross-site` + `Sec-Fetch-Mode: navigate`) and validates a present `Origin` / `Referer` against
490
+ `trustedOrigins`. It reads them from `ctx.request`. `CoreBetterAuthController` called both via `api.*({ body })` — no
491
+ request, so the check was skipped and a hostile page could sign a visitor in to the attacker's account (login CSRF,
492
+ fixed in 11.43.0; on the MCP consent page that turned into "approve a client for the attacker's account").
493
+
494
+ | Rule | Why |
495
+ |------|-----|
496
+ | Pass `request: this.csrfCheckedRequest(req, '<path>')` AND `asResponse: false` | with a request Better-Auth answers a `Response` by default; the controller reads the data |
497
+ | Forward `Origin`, `Referer`, `Sec-Fetch-*` only — never the cookie | a cookie alone makes Better-Auth demand an `Origin`, refusing non-browser clients with a cookie jar |
498
+ | Forward them only from a BROWSER request: one carrying `Origin`, `Referer` or `Sec-Fetch-Site` | Node's built-in `fetch` (undici) sends a lone `Sec-Fetch-Mode: cors` and no `Origin`; Better-Auth reads any fetch metadata without an origin as `MISSING_OR_NULL_ORIGIN`, so forwarding it unconditionally answered every server-side `fetch` sign-in with 403. A browser always sends `Origin` on a POST and `Sec-Fetch-Site` with its metadata, so nothing a hostile page can make it send escapes the check (mutations `iam-signin-csrf-nonbrowser-metadata-forwarded`, `iam-signin-csrf-site-not-a-browser-signal`) |
499
+ | Use `globalThis.Request`, not `Request` | the file imports Express's `Request` type; under Vitest (Vite SSR) the bare name resolves to that import, which is `undefined` at runtime — tsc happens to emit the global |
500
+ | Map `CROSS_SITE_NAVIGATION_LOGIN_BLOCKED` / `INVALID_ORIGIN` / `MISSING_OR_NULL_ORIGIN` to 403 (`rethrowCsrfRefusal`) | "invalid credentials" would send whoever debugs a missing `trustedOrigins` entry looking at the password |
501
+
502
+ **Tests:** Better-Auth skips its origin/CSRF checks under a test runner (`skipOriginCheck: isTest()`). A spec that pins
503
+ this protection must set `betterAuth.options.advanced.disableOriginCheck: false` — otherwise it is green with the check
504
+ removed. `tests/better-auth-signin-csrf.e2e-spec.ts` does; mutations `iam-signin-csrf-check-skipped` /
505
+ `iam-signup-csrf-check-skipped`.
506
+
486
507
  ## Summary
487
508
 
488
509
  | Principle | Requirement |
@@ -496,3 +517,4 @@ REAL generator output rather than a fixture.
496
517
  | Session cookie | Always the opaque session token — never the body JWT (§7) |
497
518
  | `account` reads / writes | Reads filter on `providerId` alone, never `issuer`. Writes set `issuer` only on better-auth 1.7.0–1.7.2, via the helper (§8) |
498
519
  | `openAPI()` plugin | Registered internally for `setupSwagger()`, kept off the router (`SERVER_ONLY`) unless the project registered it — never by a path check (§9) |
520
+ | Direct `api.*` calls | Hand Better-Auth the request (CSRF headers only) + `asResponse: false`, or its login-CSRF check is skipped (§10) |
@@ -343,8 +343,8 @@ This pattern is currently applied to:
343
343
  | 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 |
344
344
  | 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()` |
345
345
  | 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()` |
346
- | 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; 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. 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 in PLAN MODE only; in auto mode and over MCP, data-level checks must live inside `execute()`.) **MCP server** (`mcp: false` → `/ai/mcp` Streamable HTTP, Bearer auth, lazy `@modelcontextprotocol/sdk`; `mcp: { oauth: true, oauthSecret }` adds OAuth 2.1 — HMAC tokens + PKCE S256 + dynamic registration via `mountAiMcpOAuth(app)` in main.ts). Overrides via `CoreModule.forRoot(env, { ai: { budgetService, connectionResolver, connectionService, controller, conversationService, interactionService, mcpClientService, modeService, placeholderRegistry, preferenceService, promptBuilder, promptHintService, promptService, resolver, service, slotService, toolGrantService, toolPolicyService } })` |
347
- | Swagger API-Token View | `setupSwagger(app, { apiTokenView })` (helper option, not server config) | Boolean Shorthand / Presence Implies Enabled | **Off without the option** (11.42.7+). `true` / `{}` serves a second document with only the routes that release a scope via `@ApiTokenScopes()`: UI at `swagger-api-tokens`, JSON at `/api-docs-api-tokens-json`, title `<title> — API tokens`, bearer as the only scheme, unused schemas pruned; the tenant header stays while `apiTokens.userTokens` is on (a personal token chooses the company like a session) and is dropped with company tokens only. Keep its path OUTSIDE the full UI's path: Swagger UI serves its assets below its own path. The full document's enrichment (global bearer + session-cookie requirement, `security: []` on public routes, `x-api-token-scopes` + description line, `TenantHeader` parameter) is not optional — it is what `setupSwagger()` is for, and it reads the same metadata as the guards. Implementation: `common/helpers/swagger.helper.ts` **Better-Auth routes (11.42.9):** the full document also lists every route Better-Auth serves itself under the base path — whatever the configured plugins add — from Better-Auth's own generator, under the project's Better-Auth controller (its tags and `operationTags`, ids `<Controller>_betterAuth_<id>`, schemas prefixed `BetterAuth`, OpenAPI 3.1 constructs converted to 3.0). Their security is what Better-Auth enforces, not the generator's blanket bearer-only: a route behind one of Better-Auth's session middlewares (or one of the three social-account routes in `HANDLER_SESSION_PATHS`, which check in the handler) gets the global requirement, every other route `security: []` — except routes of plugins nest-server does not register itself (`BUILT_IN_BETTER_AUTH_PLUGIN_IDS`), which always keep the global requirement — and if the instance's middlewares cannot be identified (two copies of better-auth), all of them keep the global requirement rather than risk documenting a session route as public. They carry the "not allowed" API-token line, and never reach the API-token view. The `openAPI()` plugin this needs is registered internally; its routes answer 404 (see `.claude/rules/better-auth.md` §9). **Only usable operations (11.42.9):** an operation that answers an error to every caller under the running configuration is left out — `@ApiMethods()` on `@All()` handlers (TUS), legacy `/auth/*` while `auth.legacyEndpoints` keeps REST closed, Better-Auth routes refused by the configuration or the live instance, Hub endpoints of switched-off panels. `/ai/mcp` and the MCP OAuth endpoints `mountAiMcpOAuth()` mounted are documented. An explicit `@ApiBearerAuth()` keeps a guard-public route from being documented as public. Rules: `isSwitchedOffOperation()` in `swagger.helper.ts` |
346
+ | 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; 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. 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 in PLAN MODE only; in auto mode and over MCP, data-level checks must live inside `execute()`.) **MCP server** (`mcp: false` → `/ai/mcp` Streamable HTTP, Bearer auth, lazy `@modelcontextprotocol/sdk`; `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. 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 } })` |
347
+ | Swagger API-Token View | `setupSwagger(app, { apiTokenView })` (helper option, not server config) | Boolean Shorthand / Presence Implies Enabled | **Off without the option** (11.42.7+). `true` / `{}` serves a second document with only the routes that release a scope via `@ApiTokenScopes()`: UI at `swagger-api-tokens`, JSON at `/api-docs-api-tokens-json`, title `<title> — API tokens`, bearer as the only scheme, unused schemas pruned; the tenant header stays while `apiTokens.userTokens` is on (a personal token chooses the company like a session) and is dropped with company tokens only. Keep its path OUTSIDE the full UI's path: Swagger UI serves its assets below its own path. The full document's enrichment (global bearer + session-cookie requirement, `security: []` on public routes, `x-api-token-scopes` + description line, `TenantHeader` parameter) is not optional — it is what `setupSwagger()` is for, and it reads the same metadata as the guards. Implementation: `common/helpers/swagger.helper.ts` **Better-Auth routes (11.42.9):** the full document also lists every route Better-Auth serves itself under the base path — whatever the configured plugins add — from Better-Auth's own generator, under the project's Better-Auth controller (its tags and `operationTags`, ids `<Controller>_betterAuth_<id>`, schemas prefixed `BetterAuth`, OpenAPI 3.1 constructs converted to 3.0). Their security is what Better-Auth enforces, not the generator's blanket bearer-only: a route behind one of Better-Auth's session middlewares (or one of the three social-account routes in `HANDLER_SESSION_PATHS`, which check in the handler) gets the global requirement, every other route `security: []` — except routes of plugins nest-server does not register itself (`BUILT_IN_BETTER_AUTH_PLUGIN_IDS`), which always keep the global requirement — and if the instance's middlewares cannot be identified (two copies of better-auth), all of them keep the global requirement rather than risk documenting a session route as public. They carry the "not allowed" API-token line, and never reach the API-token view. The `openAPI()` plugin this needs is registered internally; its routes answer 404 (see `.claude/rules/better-auth.md` §9). **Only usable operations (11.42.9):** an operation that answers an error to every caller under the running configuration is left out — `@ApiMethods()` on `@All()` handlers (TUS), legacy `/auth/*` while `auth.legacyEndpoints` keeps REST closed, Better-Auth routes refused by the configuration or the live instance, Hub endpoints of switched-off panels. `/ai/mcp` and the MCP OAuth endpoints that are actually mounted are documented. An explicit `@ApiBearerAuth()` keeps a guard-public route from being documented as public. Rules: `isSwitchedOffOperation()` in `swagger.helper.ts` |
348
348
 
349
349
  ## Module Override Pattern (via `ICoreModuleOverrides`)
350
350
 
@@ -376,7 +376,7 @@ CoreModule.forRoot(CoreAuthService, AuthModule.forRoot(envConfig.jwt), envConfig
376
376
 
377
377
  | Module | Fields | Description |
378
378
  |--------|--------|-------------|
379
- | `ai` | `budgetService`, `connectionResolver`, `connectionService`, `controller`, `conversationService`, `interactionService`, `mcpClientService`, `modeService`, `placeholderRegistry`, `preferenceService`, `promptBuilder`, `promptHintService`, `promptService`, `resolver`, `service`, `slotService`, `toolGrantService`, `toolPolicyService` | Custom AI orchestrator, connection-resolution chain, connection/preference/budget/conversation/interaction/MCP-client services, slot + user-prompt + learning-hint stores, mode service, placeholder registry, tool-grant + tool-policy services, endpoints |
379
+ | `ai` | `budgetService`, `connectionResolver`, `connectionService`, `controller`, `conversationService`, `interactionService`, `mcpClientService`, `mcpOAuthService`, `modeService`, `placeholderRegistry`, `preferenceService`, `promptBuilder`, `promptHintService`, `promptService`, `resolver`, `service`, `slotService`, `toolGrantService`, `toolPolicyService` | Custom AI orchestrator, connection-resolution chain, connection/preference/budget/conversation/interaction/MCP-client services, MCP OAuth service (the consent step), slot + user-prompt + learning-hint stores, mode service, placeholder registry, tool-grant + tool-policy services, endpoints |
380
380
  | `errorCode` | `controller`, `service` | Custom error code endpoint and/or service |
381
381
  | `betterAuth` | `controller`, `resolver` | Custom IAM REST controller and/or GraphQL resolver |
382
382
  | `hub` | `controller`, `actionsController`, `service`, `htmlService`, `actionsService` | Custom Hub page/actions controllers and aggregator/HTML/actions services (each must extend its `Core*` base) |
@@ -268,7 +268,7 @@ pnpm run check:mutations -- --id=<id> # one mutation
268
268
  pnpm run check:mutations -- --list # the registry, without running anything
269
269
  pnpm run check:mutations -- --allow-dirty # when the fix and its evidence share a working tree
270
270
  pnpm run check:mutations -- --jobs=4 # N mutations at a time (default: 2, or 4 on >=12 cores)
271
- pnpm run check:mutations -- --no-infra # only the 137 that need no MongoDB
271
+ pnpm run check:mutations -- --no-infra # only the 165 that need no MongoDB
272
272
  pnpm run check:mutations -- --since=<ref> # only mutations touching files changed since <ref>
273
273
  ```
274
274
 
@@ -287,7 +287,7 @@ when the registry, a vitest config or a setup file changed, since those can move
287
287
  commit, and in CI alongside the publish without blocking it. The price of caching is a cache that
288
288
  has to model each spec's full dependency closure correctly, and getting that wrong produces a stale
289
289
  PASS for a test that has since gone vacuous — exactly what the gate is there to prevent. Bad trade
290
- at 212 mutations.
290
+ at 246 mutations.
291
291
 
292
292
  **Decided 2026-10-03 (repo owner): keep the full run.** Measured at 128 mutations, the CI job for
293
293
  11.41.6 took **14 minutes**. The trigger to revisit is that wall time, not the mutation count —
@@ -332,9 +332,9 @@ exactly the environment where the answer matters.
332
332
 
333
333
  ### The cost is vitest's cold start, not the tests
334
334
 
335
- Worth knowing before optimising the wrong thing: the specs behind all 75 e2e mutations add up to
335
+ Worth knowing before optimising the wrong thing: the specs behind all 81 e2e mutations add up to
336
336
  **~40 seconds**. The step takes ~740s. The remaining ~700s is paying vitest's startup — process
337
- spawn, transform, module graph, mongod connect, DB create and drop — once per mutation, 212 times.
337
+ spawn, transform, module graph, mongod connect, DB create and drop — once per mutation, 246 times.
338
338
  That work is largely single-threaded I/O and barely scales with cores: the full registry measures
339
339
  **744s on a 12-core laptop and 777s on a 4-vCPU CI runner**.
340
340
 
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-10-17 (v11.42.16)
3
+ > Auto-generated from source code as of 2026-10-20 (v11.43.1)
4
4
  > File: `FRAMEWORK-API.md` — compact, machine-readable API surface for Claude Code
5
5
 
6
6
  ## CoreModule.forRoot()
@@ -131,7 +131,7 @@ When `passkey` is enabled, `trustedOrigins` is required (compile-time enforcemen
131
131
  - `maxRunMs?`: `number | undefined` (default: `0`) — Wall-clock ceiling for ONE prompt run, in milliseconds. Checked before each
132
132
  - `maxToolResultChars?`: `number | undefined` (default: `12000`) — Maximum characters of a tool-results payload fed back to the model.
133
133
  - `promptLearning?`: `{ autoApply?: boolean; enabled?: boolean; minOccurrences?: number; } | undefined` — Governed self-improvement loop for the system prompt. The orchestrator records
134
- - `mcp?`: `boolean | { enabled?: boolean; oauth?: boolean; oauthSecret?: string; } | und...` (default: `false`) — Expose the tool registry as an MCP server at `/ai/mcp` (Streamable HTTP) for
134
+ - `mcp?`: `boolean | { enabled?: boolean; oauth?: boolean; oauthBaseUrl?: string; oauthL...` (default: `false`) — Expose the tool registry as an MCP server at `/ai/mcp` (Streamable HTTP) for
135
135
  - `rateLimit?`: `IAiRateLimit | undefined` — Rate limiting for prompts.
136
136
  - `systemPrompt?`: `string | undefined` — Base system prompt prepended to every conversation.
137
137
 
@@ -260,6 +260,8 @@ export interface IAi {
260
260
  mcp?: boolean | {
261
261
  enabled?: boolean;
262
262
  oauth?: boolean;
263
+ oauthBaseUrl?: string;
264
+ oauthLoginUrl?: string;
263
265
  oauthSecret?: string;
264
266
  };
265
267
  rateLimit?: IAiRateLimit;
@@ -532,6 +534,7 @@ export interface ICoreModuleOverrides {
532
534
  conversationService?: Type<any>;
533
535
  interactionService?: Type<any>;
534
536
  mcpClientService?: Type<any>;
537
+ mcpOAuthService?: Type<any>;
535
538
  modeService?: Type<any>;
536
539
  placeholderRegistry?: Type<any>;
537
540
  preferenceService?: Type<any>;
@@ -0,0 +1,19 @@
1
+ import { Logger, OnApplicationBootstrap, OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
2
+ import { HttpAdapterHost, ModuleRef, ModulesContainer } from '@nestjs/core';
3
+ import { CoreAiMcpOAuthService } from './services/core-ai-mcp-oauth.service';
4
+ export declare class CoreAiMcpOAuthInitializer implements OnApplicationBootstrap, OnApplicationShutdown, OnModuleInit {
5
+ protected readonly oauthService: CoreAiMcpOAuthService;
6
+ protected readonly httpAdapterHost?: HttpAdapterHost;
7
+ protected readonly moduleRef?: ModuleRef;
8
+ protected readonly modulesContainer?: ModulesContainer;
9
+ protected readonly logger: Logger;
10
+ private mounted?;
11
+ constructor(oauthService: CoreAiMcpOAuthService, httpAdapterHost?: HttpAdapterHost, moduleRef?: ModuleRef, modulesContainer?: ModulesContainer);
12
+ onModuleInit(): Promise<void>;
13
+ onApplicationBootstrap(): void;
14
+ onApplicationShutdown(): void;
15
+ protected resolveMcpPath(): string;
16
+ protected resolveAuthBasePath(): string;
17
+ private controllerPath;
18
+ private modulePath;
19
+ }
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var CoreAiMcpOAuthInitializer_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.CoreAiMcpOAuthInitializer = void 0;
17
+ const common_1 = require("@nestjs/common");
18
+ const constants_1 = require("@nestjs/common/constants");
19
+ const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
20
+ const core_1 = require("@nestjs/core");
21
+ const route_path_factory_1 = require("@nestjs/core/router/route-path-factory");
22
+ const config_service_1 = require("../../common/services/config.service");
23
+ const core_better_auth_registry_1 = require("../better-auth/core-better-auth.registry");
24
+ const core_ai_mcp_controller_1 = require("./core-ai-mcp.controller");
25
+ const ai_mcp_oauth_helper_1 = require("./helpers/ai-mcp-oauth.helper");
26
+ const ai_mcp_oauth_registry_1 = require("./helpers/ai-mcp-oauth.registry");
27
+ const core_ai_mcp_oauth_service_1 = require("./services/core-ai-mcp-oauth.service");
28
+ let CoreAiMcpOAuthInitializer = CoreAiMcpOAuthInitializer_1 = class CoreAiMcpOAuthInitializer {
29
+ oauthService;
30
+ httpAdapterHost;
31
+ moduleRef;
32
+ modulesContainer;
33
+ logger = new common_1.Logger(CoreAiMcpOAuthInitializer_1.name);
34
+ mounted;
35
+ constructor(oauthService, httpAdapterHost, moduleRef, modulesContainer) {
36
+ this.oauthService = oauthService;
37
+ this.httpAdapterHost = httpAdapterHost;
38
+ this.moduleRef = moduleRef;
39
+ this.modulesContainer = modulesContainer;
40
+ }
41
+ async onModuleInit() {
42
+ if (!this.oauthService.isOAuthEnabled()) {
43
+ return;
44
+ }
45
+ const adapter = this.httpAdapterHost?.httpAdapter;
46
+ if (!adapter) {
47
+ return;
48
+ }
49
+ this.oauthService.assertProductionSafe();
50
+ if (adapter.getType() !== 'express') {
51
+ throw new Error(`ai.mcp.oauth requires the Express adapter, but the application runs on "${adapter.getType()}": ` +
52
+ 'the MCP OAuth endpoints are an Express router.');
53
+ }
54
+ this.mounted = await (0, ai_mcp_oauth_helper_1.mountAiMcpOAuthRouter)(adapter.getInstance(), (router) => adapter.use(router), this.oauthService, {
55
+ baseUrl: config_service_1.ConfigService.get('ai.mcp.oauthBaseUrl'),
56
+ authBasePath: this.resolveAuthBasePath(),
57
+ baseUrlSource: 'ai.mcp.oauthBaseUrl',
58
+ mcpPath: this.resolveMcpPath(),
59
+ });
60
+ }
61
+ onApplicationBootstrap() {
62
+ if (!this.mounted || !this.oauthService.usesBuiltInConsent() || (0, core_better_auth_registry_1.getBetterAuthTokenService)()) {
63
+ return;
64
+ }
65
+ this.logger.warn('ai.mcp.oauth is enabled, but Better-Auth is not active: the built-in consent page has no way to sign a user ' +
66
+ 'in, so no MCP client can be authorized. Enable betterAuth, or register a CoreAiMcpOAuthService subclass ' +
67
+ 'with an authorizeConsent() of your own via CoreModule.forRoot(env, { ai: { mcpOAuthService } }).');
68
+ }
69
+ onApplicationShutdown() {
70
+ if (this.mounted && (0, ai_mcp_oauth_registry_1.getMountedMcpOAuth)() === this.mounted) {
71
+ (0, ai_mcp_oauth_registry_1.setMountedMcpOAuth)(undefined);
72
+ }
73
+ }
74
+ resolveMcpPath() {
75
+ const container = this.moduleRef
76
+ ?.container;
77
+ const applicationConfig = container?.applicationConfig;
78
+ const ctrlPath = this.controllerPath();
79
+ if (!applicationConfig) {
80
+ return ctrlPath;
81
+ }
82
+ const versioningOptions = applicationConfig.getVersioning();
83
+ const controllerVersion = versioningOptions
84
+ ? (Reflect.getMetadata(constants_1.VERSION_METADATA, core_ai_mcp_controller_1.CoreAiMcpController) ?? versioningOptions.defaultVersion)
85
+ : undefined;
86
+ const paths = new route_path_factory_1.RoutePathFactory(applicationConfig).create({
87
+ controllerVersion,
88
+ ctrlPath,
89
+ globalPrefix: (0, shared_utils_1.addLeadingSlash)(applicationConfig.getGlobalPrefix()),
90
+ methodPath: '/',
91
+ modulePath: this.modulePath(),
92
+ versioningOptions,
93
+ }, common_1.RequestMethod.POST);
94
+ if (paths.length > 1) {
95
+ this.logger.warn(`The MCP endpoint is registered at ${paths.join(', ')}; the OAuth metadata describes the first one only.`);
96
+ }
97
+ return paths[0];
98
+ }
99
+ resolveAuthBasePath() {
100
+ const basePath = `/${String(config_service_1.ConfigService.get('betterAuth.basePath') || 'iam').replace(/^\//, '')}`;
101
+ const applicationConfig = this.moduleRef
102
+ ?.container?.applicationConfig;
103
+ if (!applicationConfig) {
104
+ return basePath;
105
+ }
106
+ const versioningOptions = applicationConfig.getVersioning();
107
+ const [signIn] = new route_path_factory_1.RoutePathFactory(applicationConfig).create({
108
+ controllerVersion: versioningOptions?.defaultVersion,
109
+ ctrlPath: basePath,
110
+ globalPrefix: (0, shared_utils_1.addLeadingSlash)(applicationConfig.getGlobalPrefix()),
111
+ methodPath: '/sign-in/email',
112
+ versioningOptions,
113
+ }, common_1.RequestMethod.POST);
114
+ return signIn.replace(/\/sign-in\/email$/, '');
115
+ }
116
+ controllerPath() {
117
+ const declared = Reflect.getMetadata(constants_1.PATH_METADATA, core_ai_mcp_controller_1.CoreAiMcpController);
118
+ const path = Array.isArray(declared) ? declared[0] : declared;
119
+ return `/${String(path ?? 'ai/mcp').replace(/^\//, '')}`;
120
+ }
121
+ modulePath() {
122
+ if (!this.modulesContainer) {
123
+ return undefined;
124
+ }
125
+ for (const module of this.modulesContainer.values()) {
126
+ if (module.controllers.has(core_ai_mcp_controller_1.CoreAiMcpController)) {
127
+ return (Reflect.getMetadata(constants_1.MODULE_PATH + this.modulesContainer.applicationId, module.metatype) ??
128
+ Reflect.getMetadata(constants_1.MODULE_PATH, module.metatype));
129
+ }
130
+ }
131
+ return undefined;
132
+ }
133
+ };
134
+ exports.CoreAiMcpOAuthInitializer = CoreAiMcpOAuthInitializer;
135
+ exports.CoreAiMcpOAuthInitializer = CoreAiMcpOAuthInitializer = CoreAiMcpOAuthInitializer_1 = __decorate([
136
+ (0, common_1.Injectable)(),
137
+ __param(1, (0, common_1.Optional)()),
138
+ __param(2, (0, common_1.Optional)()),
139
+ __param(3, (0, common_1.Optional)()),
140
+ __metadata("design:paramtypes", [core_ai_mcp_oauth_service_1.CoreAiMcpOAuthService,
141
+ core_1.HttpAdapterHost,
142
+ core_1.ModuleRef,
143
+ core_1.ModulesContainer])
144
+ ], CoreAiMcpOAuthInitializer);
145
+ //# sourceMappingURL=core-ai-mcp-oauth.initializer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core-ai-mcp-oauth.initializer.js","sourceRoot":"","sources":["../../../../src/core/modules/ai/core-ai-mcp-oauth.initializer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAQwB;AACxB,w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AAK,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;QAC9D,OAAO,IAAI,MAAM,CAAC,IAAI,IAAI,QAAQ,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,CAAC;IAC3D,CAAC;IAOO,UAAU;QAChB,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC;YAC3B,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC,gBAAgB,CAAC,MAAM,EAAE,EAAE,CAAC;YACpD,IAAI,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,4CAAmB,CAAC,EAAE,CAAC;gBAChD,OAAO,CACL,OAAO,CAAC,WAAW,CAAC,uBAAW,GAAG,IAAI,CAAC,gBAAgB,CAAC,aAAa,EAAE,MAAM,CAAC,QAAQ,CAAC;oBACvF,OAAO,CAAC,WAAW,CAAC,uBAAW,EAAE,MAAM,CAAC,QAAQ,CAAC,CAClD,CAAC;YACJ,CAAC;QACH,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF,CAAA;AA7JY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,mBAAU,GAAE;IASR,WAAA,IAAA,iBAAQ,GAAE,CAAA;IACV,WAAA,IAAA,iBAAQ,GAAE,CAAA;IACV,WAAA,IAAA,iBAAQ,GAAE,CAAA;qCAHsB,iDAAqB;QACL,sBAAe;QACrB,gBAAS;QACF,uBAAgB;GAVzD,yBAAyB,CA6JrC"}
@@ -23,6 +23,7 @@ const config_service_1 = require("../../common/services/config.service");
23
23
  const core_redis_service_1 = require("../../common/services/core-redis.service");
24
24
  const core_better_auth_module_1 = require("../better-auth/core-better-auth.module");
25
25
  const error_codes_1 = require("../error-code/error-codes");
26
+ const ai_mcp_oauth_registry_1 = require("./helpers/ai-mcp-oauth.registry");
26
27
  const core_ai_mcp_oauth_service_1 = require("./services/core-ai-mcp-oauth.service");
27
28
  const core_ai_mcp_service_1 = require("./services/core-ai-mcp.service");
28
29
  let CoreAiMcpController = CoreAiMcpController_1 = class CoreAiMcpController {
@@ -43,7 +44,7 @@ let CoreAiMcpController = CoreAiMcpController_1 = class CoreAiMcpController {
43
44
  async handlePost(req, res) {
44
45
  const user = await this.resolveUser(req);
45
46
  if (!user?.id) {
46
- this.unauthorized(req, res);
47
+ this.unauthorized(res);
47
48
  return;
48
49
  }
49
50
  const sessionId = req.headers['mcp-session-id'];
@@ -141,7 +142,7 @@ let CoreAiMcpController = CoreAiMcpController_1 = class CoreAiMcpController {
141
142
  async handleSessionRequest(req, res) {
142
143
  const user = await this.resolveUser(req);
143
144
  if (!user?.id) {
144
- this.unauthorized(req, res);
145
+ this.unauthorized(res);
145
146
  return;
146
147
  }
147
148
  const sessionId = req.headers['mcp-session-id'];
@@ -243,11 +244,11 @@ let CoreAiMcpController = CoreAiMcpController_1 = class CoreAiMcpController {
243
244
  statusCode: 503,
244
245
  });
245
246
  }
246
- unauthorized(req, res) {
247
- const baseUrl = `${req.protocol}://${req.get('host')}`;
247
+ unauthorized(res) {
248
+ const oauth = (0, ai_mcp_oauth_registry_1.getMountedMcpOAuth)();
248
249
  res
249
250
  .status(401)
250
- .set({ 'WWW-Authenticate': `Bearer resource_metadata="${baseUrl}/ai/mcp"` })
251
+ .set({ 'WWW-Authenticate': oauth ? `Bearer resource_metadata="${oauth.resourceMetadataUrl}"` : 'Bearer' })
251
252
  .json({ error: 'Unauthorized: a valid Bearer token is required' });
252
253
  }
253
254
  evictIfNeeded(ownerId) {
@@ -1 +1 @@
1
- {"version":3,"file":"core-ai-mcp.controller.js","sourceRoot":"","sources":["../../../../src/core/modules/ai/core-ai-mcp.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAA4G;AAC5G,6CAAuE;AAEvE,qCAAmC;AAEnC,6EAAgE;AAChE,4DAAwD;AACxD,yEAA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K;IALL,IAAA,sBAAY,EAAC;QACZ,WAAW,EAAE,yEAAyE;QACtF,OAAO,EAAE,iBAAiB;KAC3B,CAAC;IACD,IAAA,eAAM,GAAE;IACW,WAAA,IAAA,YAAG,GAAE,CAAA;IAAgB,WAAA,IAAA,YAAG,GAAE,CAAA;;;;uDAE7C;8BAnKU,mBAAmB;IAJ/B,IAAA,uBAAa,EAAC,QAAQ,CAAC;IACvB,IAAA,iBAAO,EAAC,QAAQ,CAAC;IACjB,IAAA,mBAAU,EAAC,QAAQ,CAAC;IACpB,IAAA,uBAAK,EAAC,oBAAQ,CAAC,UAAU,CAAC;IAyCtB,WAAA,IAAA,iBAAQ,GAAE,CAAA;qCAFkB,sCAAgB;QACd,iDAAqB;QACN,qCAAgB;GAxCrD,mBAAmB,CA+d/B"}
@@ -1,6 +1,7 @@
1
1
  import { DynamicModule, Type } from '@nestjs/common';
2
2
  import { CoreAiController } from './core-ai.controller';
3
3
  import { CoreAiResolver } from './core-ai.resolver';
4
+ import { CoreAiMcpOAuthService } from './services/core-ai-mcp-oauth.service';
4
5
  import { CoreAiBudgetService } from './services/core-ai-budget.service';
5
6
  import { CoreAiConnectionPreferenceService } from './services/core-ai-connection-preference.service';
6
7
  import { CoreAiConnectionResolverService } from './services/core-ai-connection-resolver.service';
@@ -25,6 +26,7 @@ export interface CoreAiModuleOptions {
25
26
  conversationService?: Type<CoreAiConversationService>;
26
27
  interactionService?: Type<CoreAiInteractionService>;
27
28
  mcpEnabled?: boolean;
29
+ mcpOAuthService?: Type<CoreAiMcpOAuthService>;
28
30
  preferenceService?: Type<CoreAiConnectionPreferenceService>;
29
31
  placeholderRegistry?: Type<CoreAiPlaceholderRegistry>;
30
32
  promptBuilder?: Type<CoreAiPromptBuilderService>;
@@ -10,6 +10,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
10
10
  exports.CoreAiModule = void 0;
11
11
  const common_1 = require("@nestjs/common");
12
12
  const mongoose_1 = require("@nestjs/mongoose");
13
+ const core_ai_mcp_oauth_initializer_1 = require("./core-ai-mcp-oauth.initializer");
13
14
  const core_ai_mcp_controller_1 = require("./core-ai-mcp.controller");
14
15
  const core_ai_controller_1 = require("./core-ai.controller");
15
16
  const core_ai_resolver_1 = require("./core-ai.resolver");
@@ -68,9 +69,12 @@ let CoreAiModule = CoreAiModule_1 = class CoreAiModule {
68
69
  const ToolPolicyServiceClass = options.toolPolicyService || core_ai_tool_policy_service_1.CoreAiToolPolicyService;
69
70
  const ModeServiceClass = options.modeService || core_ai_mode_service_1.CoreAiModeService;
70
71
  const McpClientServiceClass = options.mcpClientService || core_ai_mcp_client_service_1.CoreAiMcpClientService;
72
+ const McpOAuthServiceClass = options.mcpOAuthService || core_ai_mcp_oauth_service_1.CoreAiMcpOAuthService;
71
73
  const controllers = [ControllerClass];
74
+ const mcpProviders = [];
72
75
  if (options.mcpEnabled) {
73
76
  controllers.push(core_ai_mcp_controller_1.CoreAiMcpController);
77
+ mcpProviders.push(core_ai_mcp_oauth_initializer_1.CoreAiMcpOAuthInitializer);
74
78
  }
75
79
  return {
76
80
  controllers,
@@ -137,7 +141,7 @@ let CoreAiModule = CoreAiModule_1 = class CoreAiModule {
137
141
  { provide: core_ai_conversation_service_1.CoreAiConversationService, useClass: ConversationServiceClass },
138
142
  { provide: core_ai_interaction_service_1.CoreAiInteractionService, useClass: InteractionServiceClass },
139
143
  core_ai_mcp_service_1.CoreAiMcpService,
140
- core_ai_mcp_oauth_service_1.CoreAiMcpOAuthService,
144
+ ...mcpProviders,
141
145
  { provide: core_ai_connection_preference_service_1.CoreAiConnectionPreferenceService, useClass: PreferenceServiceClass },
142
146
  { provide: core_ai_connection_resolver_service_1.CoreAiConnectionResolverService, useClass: ConnectionResolverClass },
143
147
  { provide: core_ai_connection_service_1.CoreAiConnectionService, useClass: ConnectionServiceClass },
@@ -151,6 +155,7 @@ let CoreAiModule = CoreAiModule_1 = class CoreAiModule {
151
155
  { provide: core_ai_tool_policy_service_1.CoreAiToolPolicyService, useClass: ToolPolicyServiceClass },
152
156
  { provide: core_ai_mode_service_1.CoreAiModeService, useClass: ModeServiceClass },
153
157
  { provide: core_ai_mcp_client_service_1.CoreAiMcpClientService, useClass: McpClientServiceClass },
158
+ { provide: core_ai_mcp_oauth_service_1.CoreAiMcpOAuthService, useClass: McpOAuthServiceClass },
154
159
  ResolverClass,
155
160
  ],
156
161
  };
@@ -1 +1 @@
1
- {"version":3,"file":"core-ai.module.js","sourceRoot":"","sources":["../../../../src/core/modules/ai/core-ai.module.ts"],"names":[],"mappings":";;;;;;;;;;AAAA,2CAAqE;AACrE,+CAAkD;AAElD,qEAA+D;AAC/D,6DAAwD;AACxD,yDAAoD;AACpD,oFAA6E;AAC7E,wEAAkE;AAClE,oFAA6F;AAC7F,sGAAwH;AACxH,gFAAyF;AACzF,oFAA+F;AAC/F,kFAA4F;AAC5F,kFAA0F;AAC1F,wEAA6E;AAC7E,oEAAuE;AACvE,oEAAuE;AACvE,gFAAuF;AACvF,kFAA0F;AAC1F,2EAAsE;AACtE,oEAA+D;AAC/D,8EAAsH;AACtH,4GAI0D;AAC1D,wGAAiG;AACjG,sFAI+C;AAC/C,0FAIiD;AACjD,wFAIgD;AAChD,0FAAoF;AACpF,8FAAuF;AACvF,wFAIgD;AAChD,8EAA0G;AAC1G,0EAAkG;AAClG,sFAI+C;AAC/C,wFAIgD;AAChD,0EAAkG;AAClG,sFAA+E;AAC/E,gEAA2D;AAC3D,+DAA0D;AAC1D,2EAAuE;AACvE,iEAA8D;AAC9D,+DAA0D;AAwFnD,IAAM,YAAY,oBAAlB,MAAM,YAAY;IACvB,MAAM,CAAC,OAAO,CAAC,UAA+B,EAAE;QAC9C,MAAM,kBAAkB,GAAG,OAAO,CAAC,aAAa,IAAI,4CAAmB,CAAC;QACxE,MAAM,uBAAuB,GAAG,OAAO,CAAC,kBAAkB,IAAI,qEAA+B,CAAC;QAC9F,MAAM,sBAAsB,GAAG,OAAO,CAAC,iBAAiB,IAAI,oDAAuB,CAAC;QACpF,M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EAAE,gBAAgB,EAAE;gBAC1D,EAAE,OAAO,EAAE,mDAAsB,EAAE,QAAQ,EAAE,qBAAqB,EAAE;gBACpE,EAAE,OAAO,EAAE,iDAAqB,EAAE,QAAQ,EAAE,oBAAoB,EAAE;gBAClE,aAAa;aACd;SACF,CAAC;IACJ,CAAC;CACF,CAAA;AArHY,oCAAY;uBAAZ,YAAY;IAFxB,IAAA,eAAM,GAAE;IACR,IAAA,eAAM,EAAC,EAAE,CAAC;GACE,YAAY,CAqHxB"}
@@ -0,0 +1,33 @@
1
+ export interface IMcpOAuthConsentView {
2
+ appHost: string;
3
+ authBasePath?: string;
4
+ client: {
5
+ id: string;
6
+ name?: string;
7
+ };
8
+ csrfToken?: string;
9
+ notice?: 'expired';
10
+ locale: McpOAuthConsentLocale;
11
+ loginUrl?: {
12
+ href: string;
13
+ returnsHere: boolean;
14
+ };
15
+ nonce: string;
16
+ oauthParams: Record<string, string>;
17
+ redirect: {
18
+ host: string;
19
+ loopback: boolean;
20
+ };
21
+ user?: {
22
+ email?: string;
23
+ name?: string;
24
+ };
25
+ }
26
+ export type McpOAuthConsentLocale = 'de' | 'en';
27
+ export declare const MCP_OAUTH_CONSENT_DECISION_FIELD = "lt_mcp_consent";
28
+ export declare const MCP_OAUTH_CONSENT_TOKEN_FIELD = "lt_mcp_csrf";
29
+ export declare function mcpOAuthConsentLocale(acceptLanguage: unknown): McpOAuthConsentLocale;
30
+ export declare function mcpOAuthConsentHeaders(nonce: string): Record<string, string>;
31
+ export declare function renderMcpOAuthConsentPage(view: IMcpOAuthConsentView): string;
32
+ export declare const MCP_OAUTH_CONSENT_GUARD_SCRIPT = "(function () {\n var allow = document.getElementById('lt-mcp-allow');\n if (allow) {\n var since = 0;\n var armed = false;\n var reset = function () { since = 0; armed = false; };\n var watch = function () {\n if (document.visibilityState === 'visible' && document.hasFocus()) { if (!since) { since = Date.now(); } } else { reset(); }\n };\n var intent = function (event) {\n watch();\n var stationaryClick = event.type === 'pointerdown' && event.pointerType === 'mouse';\n if (since && !stationaryClick && Date.now() - since >= 600) { armed = true; }\n };\n window.addEventListener('blur', reset);\n window.addEventListener('focus', watch);\n document.addEventListener('visibilitychange', function () { if (document.visibilityState === 'visible') { watch(); } else { reset(); } });\n document.addEventListener('pointermove', intent);\n document.addEventListener('pointerdown', intent);\n document.addEventListener('keydown', intent);\n allow.addEventListener('click', function (event) { if (!armed) { event.preventDefault(); } });\n allow.disabled = false;\n watch();\n }\n var other = document.getElementById('lt-mcp-switch');\n if (other) {\n other.addEventListener('click', function (event) {\n event.preventDefault();\n var done = function () { location.reload(); };\n fetch(other.getAttribute('data-sign-out'), { body: '{}', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, method: 'POST' }).then(done, done);\n });\n }\n})();";
33
+ export declare const MCP_OAUTH_CONSENT_SCRIPT = "(function () {\n var root = document.getElementById('lt-mcp-signin');\n if (!root) { return; }\n var base = root.getAttribute('data-auth-base');\n var passwordForm = document.getElementById('lt-mcp-password');\n var factorForm = document.getElementById('lt-mcp-second-factor');\n var error = document.getElementById('lt-mcp-error');\n // Both forms are rendered hidden and with method=\"post\": without this script nothing can be\n // submitted, and nothing would ever put the password into a URL.\n passwordForm.hidden = false;\n function fail(message) { error.textContent = message; error.hidden = false; }\n function post(path, body) {\n return fetch(base + path, {\n body: JSON.stringify(body),\n credentials: 'same-origin',\n headers: { 'content-type': 'application/json' },\n method: 'POST'\n }).then(function (response) {\n return response.json().then(function (json) { return json; }, function () { return {}; }).then(function (json) {\n return { body: json || {}, ok: response.ok };\n });\n });\n }\n passwordForm.addEventListener('submit', function (event) {\n event.preventDefault();\n error.hidden = true;\n post('/sign-in/email', { email: passwordForm.elements.email.value, password: passwordForm.elements.password.value })\n .then(function (result) {\n if (result.body.requiresTwoFactor || result.body.twoFactorRedirect) {\n passwordForm.hidden = true;\n factorForm.hidden = false;\n return;\n }\n if (!result.ok) { fail(root.getAttribute('data-sign-in-failed')); return; }\n location.reload();\n }, function () { fail(root.getAttribute('data-sign-in-failed')); });\n });\n factorForm.addEventListener('submit', function (event) {\n event.preventDefault();\n error.hidden = true;\n var path = factorForm.elements.backup.checked ? '/two-factor/verify-backup-code' : '/two-factor/verify-totp';\n post(path, { code: factorForm.elements.code.value })\n .then(function (result) {\n if (!result.ok) { fail(root.getAttribute('data-code-failed')); return; }\n location.reload();\n }, function () { fail(root.getAttribute('data-code-failed')); });\n });\n})();";