@lenne.tech/nest-server 12.9.4 → 12.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/rules/configurable-features.md +4 -0
- package/.claude/rules/package-management.md +29 -5
- package/.claude/rules/role-system.md +12 -0
- package/.claude/rules/testing.md +4 -4
- package/CLAUDE.md +10 -1
- package/FRAMEWORK-API.md +2 -1
- package/dist/core/common/decorators/rest-user.decorator.js +4 -0
- package/dist/core/common/decorators/rest-user.decorator.js.map +1 -1
- package/dist/core/common/filters/http-exception-log.filter.js +3 -0
- package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
- package/dist/core/common/helpers/context.helper.js +9 -0
- package/dist/core/common/helpers/context.helper.js.map +1 -1
- package/dist/core/common/helpers/decorator.helper.js +4 -0
- package/dist/core/common/helpers/decorator.helper.js.map +1 -1
- package/dist/core/common/helpers/execution-context-request.helper.d.ts +14 -1
- package/dist/core/common/helpers/execution-context-request.helper.js +36 -0
- package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
- package/dist/core/common/helpers/graphql-upload.helper.d.ts +8 -0
- package/dist/core/common/helpers/graphql-upload.helper.js +206 -0
- package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
- package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
- package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +11 -0
- package/dist/core/common/middleware/request-context.middleware.js +3 -0
- package/dist/core/common/middleware/request-context.middleware.js.map +1 -1
- package/dist/core/common/services/request-context.service.d.ts +2 -0
- package/dist/core/common/services/request-context.service.js +3 -0
- package/dist/core/common/services/request-context.service.js.map +1 -1
- package/dist/core/modules/ai/core-ai-mcp.controller.js +4 -2
- package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
- package/dist/core/modules/ai/core-ai.constants.d.ts +1 -0
- package/dist/core/modules/ai/core-ai.constants.js +1 -0
- package/dist/core/modules/ai/core-ai.constants.js.map +1 -1
- package/dist/core/modules/ai/core-ai.module.js +2 -0
- package/dist/core/modules/ai/core-ai.module.js.map +1 -1
- package/dist/core/modules/ai/decorators/ai-agent-function.decorator.d.ts +8 -0
- package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js +8 -0
- package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js.map +1 -0
- package/dist/core/modules/ai/helpers/ai-verified-user.helper.d.ts +12 -0
- package/dist/core/modules/ai/helpers/ai-verified-user.helper.js +23 -0
- package/dist/core/modules/ai/helpers/ai-verified-user.helper.js.map +1 -0
- package/dist/core/modules/ai/index.d.ts +8 -0
- package/dist/core/modules/ai/index.js +8 -0
- package/dist/core/modules/ai/index.js.map +1 -1
- package/dist/core/modules/ai/interfaces/llm-provider.interface.d.ts +1 -0
- package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js +2 -0
- package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js.map +1 -1
- package/dist/core/modules/ai/providers/ai-egress.helper.d.ts +6 -0
- package/dist/core/modules/ai/providers/ai-egress.helper.js +58 -0
- package/dist/core/modules/ai/providers/ai-egress.helper.js.map +1 -0
- package/dist/core/modules/ai/providers/ai-sdk.packages.d.ts +16 -0
- package/dist/core/modules/ai/providers/ai-sdk.packages.js +99 -0
- package/dist/core/modules/ai/providers/ai-sdk.packages.js.map +1 -0
- package/dist/core/modules/ai/providers/ai-sdk.provider.d.ts +51 -0
- package/dist/core/modules/ai/providers/ai-sdk.provider.js +244 -0
- package/dist/core/modules/ai/providers/ai-sdk.provider.js.map +1 -0
- package/dist/core/modules/ai/providers/llm-provider.factory.d.ts +11 -1
- package/dist/core/modules/ai/providers/llm-provider.factory.js +44 -3
- package/dist/core/modules/ai/providers/llm-provider.factory.js.map +1 -1
- package/dist/core/modules/ai/providers/openai-compatible.provider.js +4 -21
- package/dist/core/modules/ai/providers/openai-compatible.provider.js.map +1 -1
- package/dist/core/modules/ai/services/core-ai-agent-function.bridge.d.ts +34 -0
- package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js +130 -0
- package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js.map +1 -0
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +28 -3
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +141 -15
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
- package/dist/core/modules/ai/services/core-ai-mcp.service.js +2 -1
- package/dist/core/modules/ai/services/core-ai-mcp.service.js.map +1 -1
- package/dist/core/modules/ai/services/core-ai.service.js +2 -7
- package/dist/core/modules/ai/services/core-ai.service.js.map +1 -1
- package/dist/core/modules/ai/tools/ai-tool-result.helper.d.ts +2 -0
- package/dist/core/modules/ai/tools/ai-tool-result.helper.js +117 -0
- package/dist/core/modules/ai/tools/ai-tool-result.helper.js.map +1 -0
- package/dist/core/modules/ai/tools/ai-tool-schema.helper.d.ts +36 -0
- package/dist/core/modules/ai/tools/ai-tool-schema.helper.js +81 -0
- package/dist/core/modules/ai/tools/ai-tool-schema.helper.js.map +1 -0
- package/dist/core/modules/ai/tools/ai-tool.registry.js +2 -1
- package/dist/core/modules/ai/tools/ai-tool.registry.js.map +1 -1
- package/dist/core/modules/auth/guards/auth.guard.js +10 -2
- package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
- package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
- package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
- package/dist/core/modules/auth/guards/roles.guard.js +11 -1
- package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
- package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth.config.js +78 -0
- package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
- package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
- package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
- package/dist/core.module.js +2 -1
- package/dist/core.module.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/types/graphql-upload.d.ts +34 -2
- package/docs/REQUEST-LIFECYCLE.md +46 -9
- package/migration-guides/12.9.3-to-12.9.4.md +3 -1
- package/migration-guides/12.9.x-to-12.10.x.md +271 -0
- package/package.json +46 -21
- package/src/core/common/decorators/rest-user.decorator.ts +6 -0
- package/src/core/common/filters/http-exception-log.filter.ts +8 -0
- package/src/core/common/helpers/context.helper.ts +14 -0
- package/src/core/common/helpers/decorator.helper.ts +5 -0
- package/src/core/common/helpers/execution-context-request.helper.ts +97 -1
- package/src/core/common/helpers/graphql-upload.helper.ts +427 -0
- package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
- package/src/core/common/interfaces/server-options.interface.ts +98 -0
- package/src/core/common/middleware/request-context.middleware.ts +3 -0
- package/src/core/common/services/request-context.service.ts +11 -0
- package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +16 -0
- package/src/core/modules/ai/README.md +101 -0
- package/src/core/modules/ai/core-ai-mcp.controller.ts +7 -2
- package/src/core/modules/ai/core-ai.constants.ts +4 -0
- package/src/core/modules/ai/core-ai.module.ts +3 -0
- package/src/core/modules/ai/decorators/ai-agent-function.decorator.ts +44 -0
- package/src/core/modules/ai/helpers/ai-verified-user.helper.ts +47 -0
- package/src/core/modules/ai/index.ts +8 -0
- package/src/core/modules/ai/interfaces/ai-tool.interface.ts +5 -1
- package/src/core/modules/ai/interfaces/llm-provider.interface.ts +6 -0
- package/src/core/modules/ai/models/core-ai-mcp-oauth.models.ts +4 -0
- package/src/core/modules/ai/providers/ai-egress.helper.ts +98 -0
- package/src/core/modules/ai/providers/ai-sdk.packages.ts +153 -0
- package/src/core/modules/ai/providers/ai-sdk.provider.ts +383 -0
- package/src/core/modules/ai/providers/llm-provider.factory.ts +93 -2
- package/src/core/modules/ai/providers/openai-compatible.provider.ts +5 -23
- package/src/core/modules/ai/services/core-ai-agent-function.bridge.ts +170 -0
- package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +240 -20
- package/src/core/modules/ai/services/core-ai-mcp.service.ts +3 -1
- package/src/core/modules/ai/services/core-ai.service.ts +5 -7
- package/src/core/modules/ai/tools/ai-tool-result.helper.ts +153 -0
- package/src/core/modules/ai/tools/ai-tool-schema.helper.ts +134 -0
- package/src/core/modules/ai/tools/ai-tool.registry.ts +6 -1
- package/src/core/modules/auth/guards/auth.guard.ts +19 -2
- package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
- package/src/core/modules/auth/guards/roles.guard.ts +23 -1
- package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +11 -0
- package/src/core/modules/better-auth/README.md +204 -0
- package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
- package/src/core/modules/better-auth/better-auth.config.ts +138 -1
- package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
- package/src/core.module.ts +5 -1
- package/src/index.ts +1 -0
- package/src/types/graphql-upload.d.ts +34 -2
|
@@ -494,6 +494,7 @@ export default {
|
|
|
494
494
|
|
|
495
495
|
// Social Providers (enabled by default when credentials are configured)
|
|
496
496
|
// Set enabled: false to explicitly disable a provider
|
|
497
|
+
// Every other option reaches Better-Auth unchanged since 12.10.0 (see "Social providers" below)
|
|
497
498
|
socialProviders: {
|
|
498
499
|
google: {
|
|
499
500
|
clientId: 'your-google-client-id',
|
|
@@ -503,6 +504,11 @@ export default {
|
|
|
503
504
|
clientId: 'your-github-client-id',
|
|
504
505
|
clientSecret: 'your-github-client-secret',
|
|
505
506
|
},
|
|
507
|
+
microsoft: {
|
|
508
|
+
clientId: 'your-microsoft-client-id',
|
|
509
|
+
clientSecret: 'your-microsoft-client-secret',
|
|
510
|
+
tenantId: 'your-directory-tenant-id', // unset: `common`, every organization and personal accounts
|
|
511
|
+
},
|
|
506
512
|
},
|
|
507
513
|
|
|
508
514
|
// Trusted Origins for CORS
|
|
@@ -686,6 +692,127 @@ accounts whatever `disableSignUp` said.
|
|
|
686
692
|
|
|
687
693
|
**Default:** `false` (sign-up enabled) - fully backward compatible.
|
|
688
694
|
|
|
695
|
+
### Social providers
|
|
696
|
+
|
|
697
|
+
A provider is switched on by its `clientId` and `clientSecret`; `enabled: false` switches a configured one off.
|
|
698
|
+
**Since 12.10.0 every other option set on a provider reaches Better-Auth unchanged:** Microsoft's `tenantId`, Google's
|
|
699
|
+
`hd` and `accessType`, `scope` with `disableDefaultScope`, `prompt`, `mapProfileToUser` and the other options
|
|
700
|
+
[Better-Auth documents per provider](https://www.better-auth.com/docs/authentication/social-sign-in). Before 12.10.0
|
|
701
|
+
`buildSocialProviders()` handed Better-Auth `clientId`, `clientSecret` and `disableSignUp` only and dropped the rest
|
|
702
|
+
without a warning. `enabled` is the framework's own switch and is not handed on. `disableSignUp` follows
|
|
703
|
+
[Disable Sign-Up](#disable-sign-up) whatever else the provider sets.
|
|
704
|
+
|
|
705
|
+
`betterAuth.options.socialProviders` is not the place for provider options: it replaces the whole block, so the
|
|
706
|
+
provider disappears from `GET /iam/features` and `emailAndPassword.disableSignUp` no longer closes it.
|
|
707
|
+
|
|
708
|
+
#### Microsoft Entra ID: one organization, identity only
|
|
709
|
+
|
|
710
|
+
```typescript
|
|
711
|
+
betterAuth: {
|
|
712
|
+
socialProviders: {
|
|
713
|
+
microsoft: {
|
|
714
|
+
clientId: '<application (client) id>',
|
|
715
|
+
clientSecret: '<client secret>',
|
|
716
|
+
tenantId: '<directory (tenant) id>',
|
|
717
|
+
disableDefaultScope: true,
|
|
718
|
+
scope: ['openid', 'profile', 'email'],
|
|
719
|
+
disableProfilePhoto: true,
|
|
720
|
+
},
|
|
721
|
+
},
|
|
722
|
+
},
|
|
723
|
+
```
|
|
724
|
+
|
|
725
|
+
- `tenantId` names the organization whose accounts may sign in. **Without it Better-Auth uses `common`, which admits
|
|
726
|
+
accounts of every organization and personal Microsoft accounts.** Use the directory (tenant) id. A verified domain
|
|
727
|
+
works for the redirect flow, but sign-in with an `idToken` compares the token's issuer with
|
|
728
|
+
`https://login.microsoftonline.com/<tenantId>/v2.0`, and Microsoft writes the id there.
|
|
729
|
+
- `disableDefaultScope: true` with `scope: ['openid', 'profile', 'email']` asks for the sign-in and nothing else.
|
|
730
|
+
Better-Auth's default adds `User.Read` and `offline_access`, so each sign-in would store a Microsoft Graph access
|
|
731
|
+
token and a refresh token with the user's `account` record.
|
|
732
|
+
- `disableProfilePhoto: true` skips the Microsoft Graph request Better-Auth otherwise makes on every sign-in to fetch
|
|
733
|
+
the profile photo.
|
|
734
|
+
- The app registration needs `<baseUrl>/iam/callback/microsoft` as its redirect URI (`baseUrl` of the API, `/iam` the
|
|
735
|
+
default `basePath`).
|
|
736
|
+
|
|
737
|
+
To close e-mail sign-up and still let the organization's members create their account on the first Microsoft sign-in,
|
|
738
|
+
combine `emailAndPassword: { disableSignUp: true }` with `microsoft: { disableSignUp: false }`.
|
|
739
|
+
|
|
740
|
+
**Deployed stages** set the same options through `NSC__*` variables:
|
|
741
|
+
|
|
742
|
+
```bash
|
|
743
|
+
NSC__BETTER_AUTH__SOCIAL_PROVIDERS__MICROSOFT__CLIENT_ID=<application (client) id>
|
|
744
|
+
NSC__BETTER_AUTH__SOCIAL_PROVIDERS__MICROSOFT__CLIENT_SECRET=<client secret>
|
|
745
|
+
NSC__BETTER_AUTH__SOCIAL_PROVIDERS__MICROSOFT__TENANT_ID=<directory (tenant) id>
|
|
746
|
+
NSC__BETTER_AUTH__SOCIAL_PROVIDERS__MICROSOFT__DISABLE_DEFAULT_SCOPE=true
|
|
747
|
+
NSC__BETTER_AUTH__SOCIAL_PROVIDERS__MICROSOFT__SCOPE=openid,profile,email
|
|
748
|
+
NSC__BETTER_AUTH__SOCIAL_PROVIDERS__MICROSOFT__DISABLE_PROFILE_PHOTO=true
|
|
749
|
+
```
|
|
750
|
+
|
|
751
|
+
The `NSC__*` reader converts `true`, `false` and numbers and passes everything else on as a string, so `SCOPE` arrives
|
|
752
|
+
as a string. Since 12.10.0 a provider's `scope` string is split on commas and whitespace: `openid,profile,email` and
|
|
753
|
+
`openid profile email` ask for the same three scopes. `NSC__*` variables cannot write a list. Indexed names
|
|
754
|
+
(`…__SCOPE__0`, `…__SCOPE__1`) build an object with the keys `0`, `1`, … where `config.env.ts` holds no list, and an
|
|
755
|
+
empty `…__SCOPE=` becomes the number `0`. A `scope` that is neither a string nor a list is dropped with one error per
|
|
756
|
+
provider at boot, and the provider asks for its default scopes; with `disableDefaultScope: true` the request then
|
|
757
|
+
carries no scope, and the provider refuses it. Before, Better-Auth threw a `TypeError` on every `/iam/sign-in/social`
|
|
758
|
+
for such an object. `NEST_SERVER_CONFIG` (JSON) can carry a list.
|
|
759
|
+
|
|
760
|
+
**Provider claims** are mapped in `mapProfileToUser`. Better-Auth calls it with the claims of the ID token and merges
|
|
761
|
+
its return value over the `name`, `email`, `image` and `emailVerified` it read from them. That user is created on the
|
|
762
|
+
first sign-in; an existing user is updated only with `overrideUserInfoOnSignIn: true` on the provider. It is a
|
|
763
|
+
function, so it goes into `config.env.ts`; an `NSC__*` variable cannot carry it.
|
|
764
|
+
|
|
765
|
+
```typescript
|
|
766
|
+
import type { MicrosoftEntraIDProfile } from 'better-auth/social-providers';
|
|
767
|
+
|
|
768
|
+
microsoft: {
|
|
769
|
+
// ...
|
|
770
|
+
mapProfileToUser: (profile: MicrosoftEntraIDProfile) => ({ name: profile.name || profile.preferred_username }),
|
|
771
|
+
},
|
|
772
|
+
```
|
|
773
|
+
|
|
774
|
+
### Where a failed sign-in lands
|
|
775
|
+
|
|
776
|
+
When an OAuth sign-in fails, Better-Auth redirects the browser to an error URL with `?error=<code>` and, when the
|
|
777
|
+
provider sent one, `&error_description=…`. The flow's own `errorCallbackURL` (a field of `POST /iam/sign-in/social`)
|
|
778
|
+
travels inside the flow's state, which Better-Auth keeps for ten minutes. A user who needs longer on the provider's
|
|
779
|
+
sign-in page comes back with a state Better-Auth no longer has, and the `errorCallbackURL` is gone with it. Better-Auth
|
|
780
|
+
then uses its fallback, `onAPIError.errorURL`, and without one its own English "Error" page on the API host, which
|
|
781
|
+
offers no way back into the app.
|
|
782
|
+
|
|
783
|
+
**Since 12.10.0 the framework sets that fallback from `betterAuth.errorUrl`:**
|
|
784
|
+
|
|
785
|
+
| `betterAuth.errorUrl` | Where the browser lands |
|
|
786
|
+
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
787
|
+
| unset | `<appUrl>/auth/login?error=<code>`. The app URL resolves like the other derived links: explicit `appUrl`, the localhost default in `local` / `ci` / `e2e`, else derived from `baseUrl` unless `cors.deriveAppUrl: false`. No app URL: Better-Auth's own page |
|
|
788
|
+
| `'https://…'` | that URL |
|
|
789
|
+
| `'/sign-in'` | `<appUrl>/sign-in`; no app URL: Better-Auth's own page and a warning at boot |
|
|
790
|
+
| `false` | Better-Auth's own page, `<baseUrl>/iam/error`, as before 12.10.0 |
|
|
791
|
+
| anything else | refused with a warning at boot (another scheme, `//host`, the number `0` an empty `NSC__BETTER_AUTH__ERROR_URL=` becomes); Better-Auth's own page |
|
|
792
|
+
|
|
793
|
+
`betterAuth.options.onAPIError.errorURL` wins over all of these. Other keys of `options.onAPIError` (`onError`, `throw`,
|
|
794
|
+
`customizeDefaultErrorPage`) are merged with the derived URL instead of replacing it. With an error URL, Better-Auth's
|
|
795
|
+
page is no longer shown, so a project that customized it (`customizeDefaultErrorPage`) sets `betterAuth.errorUrl: false`
|
|
796
|
+
to keep it. A deployed stage sets the option with `NSC__BETTER_AUTH__ERROR_URL`.
|
|
797
|
+
|
|
798
|
+
Better-Auth 1.7.x reads `onAPIError.errorURL` in these places, so these redirects change:
|
|
799
|
+
|
|
800
|
+
- the OAuth callback `GET /iam/callback/:provider`, also for Generic OAuth providers, when its state is missing
|
|
801
|
+
(`state_not_found`), unreadable, expired or does not match (`state_mismatch`, `state_invalid`), or when the callback
|
|
802
|
+
request itself is malformed (`invalid_callback_request`);
|
|
803
|
+
- every later failure of a flow started without `errorCallbackURL`: the provider's refusal (`access_denied`,
|
|
804
|
+
`login_required`, `interaction_required`, …), `no_code`, a failed token exchange, `email_not_found`,
|
|
805
|
+
`signup_disabled`, a failed account link;
|
|
806
|
+
- `internal_server_error` when Better-Auth cannot create or link the user, also on sign-in with an `idToken`;
|
|
807
|
+
- `GET /iam/error` itself, which no longer renders its page and forwards `error` and `error_description` to the
|
|
808
|
+
error URL;
|
|
809
|
+
- the `oauthProxy()` plugin, if a project adds it.
|
|
810
|
+
|
|
811
|
+
A flow that sent its own `errorCallbackURL` and whose state Better-Auth can still read lands there, as before.
|
|
812
|
+
|
|
813
|
+
**A login page maps `error` to a text of its own and never renders `error_description`.** Anyone can link to
|
|
814
|
+
`<baseUrl>/iam/error?error=…&error_description=<any text>`, and Better-Auth forwards the description as given.
|
|
815
|
+
|
|
689
816
|
### Additional User Fields
|
|
690
817
|
|
|
691
818
|
Add custom fields to the Better-Auth user schema:
|
|
@@ -1274,6 +1401,63 @@ curl -X GET https://api.example.com/iam/token \
|
|
|
1274
1401
|
| `/iam/sign-in/social` | POST | Initiate social login |
|
|
1275
1402
|
| `/iam/callback/:provider` | GET | OAuth callback |
|
|
1276
1403
|
|
|
1404
|
+
`POST /iam/sign-in/social` is Better-Auth's own route. Besides `provider` it reads these fields:
|
|
1405
|
+
|
|
1406
|
+
| Field | Meaning |
|
|
1407
|
+
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1408
|
+
| `callbackURL` | Where the browser lands after a successful sign-in. Unset: the API's base URL |
|
|
1409
|
+
| `errorCallbackURL` | Where it lands when the provider or Better-Auth refuses, with `?error=<code>` and `&error_description=…` when the provider sent one. Unset: `betterAuth.errorUrl`, see [Where a failed sign-in lands](#where-a-failed-sign-in-lands) |
|
|
1410
|
+
| `loginHint` | Sent as `login_hint`: the account the provider should offer |
|
|
1411
|
+
| `additionalParams` | Further query parameters (strings) for the provider's authorization URL. A `prompt` here replaces the provider's `prompt` for this request. The parameters Better-Auth sets itself (`state`, `client_id`, `redirect_uri`, `response_type`, `code_challenge`, `code_challenge_method`, `nonce`, `scope`) are refused |
|
|
1412
|
+
| `disableRedirect` | `true` answers `{ url, redirect: false }` without a `Location` header |
|
|
1413
|
+
| `idToken` | Sign-in without a redirect, see below |
|
|
1414
|
+
|
|
1415
|
+
Better-Auth checks `callbackURL` and `errorCallbackURL` against the trusted origins and answers `403` for any other.
|
|
1416
|
+
It accepts a relative path as well, but the browser follows it from the callback, which runs on the API host. A
|
|
1417
|
+
frontend on a host of its own therefore sends absolute URLs of its own origin. Send the request from the browser with
|
|
1418
|
+
credentials: Better-Auth sets a signed `<cookiePrefix>.state` cookie for five minutes, and the callback refuses a
|
|
1419
|
+
browser without it (`error=state_mismatch`).
|
|
1420
|
+
|
|
1421
|
+
#### Silent sign-in with fallback
|
|
1422
|
+
|
|
1423
|
+
A page can try to sign the user in without showing anything and fall back to the interactive sign-in when that fails.
|
|
1424
|
+
The recipe uses Better-Auth's own fields only:
|
|
1425
|
+
|
|
1426
|
+
```typescript
|
|
1427
|
+
async function signInWithMicrosoft(silent: boolean): Promise<void> {
|
|
1428
|
+
const response = await fetch(`${apiUrl}/iam/sign-in/social`, {
|
|
1429
|
+
body: JSON.stringify({
|
|
1430
|
+
...(silent ? { additionalParams: { prompt: 'none' } } : {}),
|
|
1431
|
+
callbackURL: `${appUrl}/`,
|
|
1432
|
+
disableRedirect: true,
|
|
1433
|
+
errorCallbackURL: `${appUrl}/auth/login${silent ? '?silent=1' : ''}`,
|
|
1434
|
+
provider: 'microsoft',
|
|
1435
|
+
}),
|
|
1436
|
+
credentials: 'include',
|
|
1437
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1438
|
+
method: 'POST',
|
|
1439
|
+
});
|
|
1440
|
+
window.location.assign((await response.json()).url);
|
|
1441
|
+
}
|
|
1442
|
+
```
|
|
1443
|
+
|
|
1444
|
+
1. The page calls `signInWithMicrosoft(true)`. With `prompt=none` Microsoft shows nothing: either the browser comes
|
|
1445
|
+
back through the callback, signed in, at `callbackURL`, or Microsoft answers `login_required` or
|
|
1446
|
+
`interaction_required`, and the callback sends the browser to `errorCallbackURL` with that code in `error`.
|
|
1447
|
+
2. The login page sees `silent=1` and one of those two codes and calls `signInWithMicrosoft(false)`, optionally with a
|
|
1448
|
+
`loginHint`. Codes from Better-Auth itself, such as `signup_disabled`, are refusals an interactive sign-in does not
|
|
1449
|
+
change.
|
|
1450
|
+
|
|
1451
|
+
With Better-Auth's client the same fields go into `authClient.signIn.social({ … })`.
|
|
1452
|
+
|
|
1453
|
+
#### Sign-in with an ID token
|
|
1454
|
+
|
|
1455
|
+
A client that already holds a Microsoft ID token, such as a native app using MSAL, sends
|
|
1456
|
+
`{ provider: 'microsoft', idToken: { token } }` and gets the session in the answer, without a redirect. Better-Auth
|
|
1457
|
+
checks the signature against Microsoft's keys, the audience against `clientId` and the issuer against the configured
|
|
1458
|
+
tenant (`https://login.microsoftonline.com/<tenantId>/v2.0`), so with `tenantId` set to the directory id a token of
|
|
1459
|
+
another organization is refused.
|
|
1460
|
+
|
|
1277
1461
|
### Two-Factor Authentication Endpoints (Native Better Auth)
|
|
1278
1462
|
|
|
1279
1463
|
These endpoints are handled by Better Auth's native `twoFactor` plugin:
|
|
@@ -2211,6 +2395,26 @@ See **[ARCHITECTURE.md](./ARCHITECTURE.md)** for detailed documentation on why c
|
|
|
2211
2395
|
- Verify `clientId` and `clientSecret` are correct
|
|
2212
2396
|
- Check that redirect URLs are configured in provider settings
|
|
2213
2397
|
- Ensure `trustedOrigins` includes your application URL
|
|
2398
|
+
- **Provider options have no effect (before 12.10.0).** Up to 12.9.4 a provider received `clientId`, `clientSecret`
|
|
2399
|
+
and `disableSignUp` only. `tenantId`, `scope`, `disableDefaultScope`, `prompt` and every other option were dropped,
|
|
2400
|
+
so a Microsoft sign-in ran against `common` with Better-Auth's default scope. Update to 12.10.0 or later. To see what
|
|
2401
|
+
the provider receives, read the authorization URL:
|
|
2402
|
+
`POST /iam/sign-in/social` with `{ "provider": "microsoft", "disableRedirect": true }` answers it in `url`, with the
|
|
2403
|
+
tenant in the path and the scopes in `scope`.
|
|
2404
|
+
- **The authorization URL asks for single letters** (`scope=o p e n i d …`): `scope` reached Better-Auth as a string,
|
|
2405
|
+
which it spreads into one scope per character. Since 12.10.0 `socialProviders.<name>.scope` accepts a comma- or
|
|
2406
|
+
space-separated string, which is what an `NSC__…__SCOPE` variable delivers. `betterAuth.options.socialProviders`
|
|
2407
|
+
goes to Better-Auth unchanged and needs a list.
|
|
2408
|
+
- **The log says `socialProviders.<name>.scope is neither a string nor a list`**: indexed variables
|
|
2409
|
+
(`NSC__…__SCOPE__0`) build an object, an empty `NSC__…__SCOPE=` the number `0`. The value is ignored and the
|
|
2410
|
+
provider asks for its default scopes, or, with `disableDefaultScope: true`, for none, which the provider refuses.
|
|
2411
|
+
Before 12.10.0 an object made every `/iam/sign-in/social` fail with a `TypeError`. Write one comma-separated
|
|
2412
|
+
`NSC__…__SCOPE` instead.
|
|
2413
|
+
- **A failed sign-in shows an English "Error" page on the API host**: the OAuth flow failed (state expired after ten
|
|
2414
|
+
minutes on the provider's page, provider refused) and no error URL applied. Since 12.10.0 the browser lands on
|
|
2415
|
+
`<appUrl>/auth/login?error=<code>` instead; if it still lands on the API, no app URL resolves (set `appUrl`, or
|
|
2416
|
+
`baseUrl` without `cors.deriveAppUrl: false`) or `betterAuth.errorUrl` is `false` or was refused (see the boot log).
|
|
2417
|
+
See [Where a failed sign-in lands](#where-a-failed-sign-in-lands).
|
|
2214
2418
|
|
|
2215
2419
|
### 2FA/Passkey not working
|
|
2216
2420
|
|
|
@@ -8,7 +8,11 @@ import {
|
|
|
8
8
|
} from '@nestjs/common';
|
|
9
9
|
import { GqlExecutionContext } from '@nestjs/graphql';
|
|
10
10
|
|
|
11
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
agentCallOf,
|
|
13
|
+
isAgentCallContext,
|
|
14
|
+
resolveGuardRequest,
|
|
15
|
+
} from '../../common/helpers/execution-context-request.helper.js';
|
|
12
16
|
|
|
13
17
|
import { RoleEnum } from '../../common/enums/role.enum.js';
|
|
14
18
|
import { ApiTokenKind } from '../api-token/core-api-token.constants.js';
|
|
@@ -103,6 +107,20 @@ export class BetterAuthRolesGuard implements CanActivate {
|
|
|
103
107
|
// that does not declare @ApiTokenScopes(), public ones included. A tenant token is fully decided
|
|
104
108
|
// there; a user token continues through the ordinary checks as its user (see core-api-token.helpers).
|
|
105
109
|
const request = this.getRequest(context);
|
|
110
|
+
|
|
111
|
+
// An agent function / MCP tool call without a request (`@nestjs/ai`'s `caller: { user }`, a durable run, MCP over
|
|
112
|
+
// stdio) is ANONYMOUS: nothing authenticated `caller.user`, and the call's arguments are the model's. Open only
|
|
113
|
+
// where the route is public. Kept in sync with RolesGuard (nestjs-ai plan §1).
|
|
114
|
+
if (isAgentCallContext(context) && !request) {
|
|
115
|
+
// The method's own roles win over the class's, as CoreTenantGuard decides system roles: a class-level
|
|
116
|
+
// S_EVERYONE does not open a method that asks for S_USER. Kept in sync with RolesGuard.
|
|
117
|
+
const effective = handlerRoles?.some((value) => !!value) ? handlerRoles : roles;
|
|
118
|
+
if (!effective || !effective.some((value) => !!value) || effective.includes(RoleEnum.S_EVERYONE)) {
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
|
|
122
|
+
}
|
|
123
|
+
|
|
106
124
|
const apiTokenKind = enforceApiTokenRoute({
|
|
107
125
|
controllerClass: context.getClass(),
|
|
108
126
|
handler: context.getHandler(),
|
|
@@ -205,6 +223,16 @@ export class BetterAuthRolesGuard implements CanActivate {
|
|
|
205
223
|
* Get target ID from context for S_SELF checks
|
|
206
224
|
*/
|
|
207
225
|
private getTargetId(context: ExecutionContext): null | string {
|
|
226
|
+
// An agent function / MCP call: its arguments are the target, as a resolver's args are on GraphQL. Never the HTTP
|
|
227
|
+
// fallback below, which would read the same arguments as if they were a request with `params`.
|
|
228
|
+
if (isAgentCallContext(context)) {
|
|
229
|
+
if (!agentCallOf(context)) {
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
const input = context.getArgByIndex(0);
|
|
233
|
+
return typeof input?.id === 'string' ? input.id : null;
|
|
234
|
+
}
|
|
235
|
+
|
|
208
236
|
// Try GraphQL args
|
|
209
237
|
try {
|
|
210
238
|
const gqlContext = GqlExecutionContext.create(context);
|
|
@@ -439,9 +439,11 @@ interface PasskeyNormalizationResult {
|
|
|
439
439
|
}
|
|
440
440
|
|
|
441
441
|
/**
|
|
442
|
-
* Social provider configuration for better-auth
|
|
442
|
+
* Social provider configuration for better-auth: the three values the framework decides, plus every option the project
|
|
443
|
+
* set on the provider (`tenantId`, `scope`, `prompt`, …), which Better-Auth reads itself.
|
|
443
444
|
*/
|
|
444
445
|
interface SocialProviderConfig {
|
|
446
|
+
[option: string]: unknown;
|
|
445
447
|
clientId: string;
|
|
446
448
|
clientSecret: string;
|
|
447
449
|
disableSignUp: boolean;
|
|
@@ -579,6 +581,7 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
|
|
|
579
581
|
mcpOAuthIssuerOrigin(ConfigService.configFastButReadOnly),
|
|
580
582
|
);
|
|
581
583
|
const additionalFields = buildUserFields(config);
|
|
584
|
+
const errorUrl = resolveErrorUrl(config.errorUrl, resolvedUrls.appUrl);
|
|
582
585
|
|
|
583
586
|
// Resolve cross-subdomain cookies (Boolean Shorthand)
|
|
584
587
|
const crossSubDomain = resolveCrossSubDomainCookies(config, resolvedUrls);
|
|
@@ -728,6 +731,9 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
|
|
|
728
731
|
},
|
|
729
732
|
}),
|
|
730
733
|
},
|
|
734
|
+
// Where a failed OAuth flow without an error URL of its own lands (`resolveErrorUrl()`); a project's own
|
|
735
|
+
// `options.onAPIError` is merged over it (see below).
|
|
736
|
+
...(errorUrl && { onAPIError: { errorURL: errorUrl } }),
|
|
731
737
|
plugins,
|
|
732
738
|
secret: validation.resolvedSecret || config.secret,
|
|
733
739
|
socialProviders,
|
|
@@ -810,6 +816,17 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
|
|
|
810
816
|
finalConfig.logger = { ...(betterAuthConfig.logger as object), ...(restOptions.logger as object) };
|
|
811
817
|
}
|
|
812
818
|
|
|
819
|
+
// `onAPIError` is merged, not replaced: a project that sets it for another reason (`onError`, `throw`,
|
|
820
|
+
// `customizeDefaultErrorPage`) keeps the derived `errorURL`, and only an `errorURL` it actually set wins.
|
|
821
|
+
if (restOptions.onAPIError && typeof restOptions.onAPIError === 'object') {
|
|
822
|
+
const projectOnApiError = restOptions.onAPIError as Record<string, unknown>;
|
|
823
|
+
finalConfig.onAPIError = {
|
|
824
|
+
...(betterAuthConfig.onAPIError as Record<string, unknown> | undefined),
|
|
825
|
+
...projectOnApiError,
|
|
826
|
+
errorURL: projectOnApiError.errorURL ?? errorUrl,
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
|
|
813
830
|
// `emailAndPassword` needs a DEEP merge, and this one is load-bearing.
|
|
814
831
|
// The block above carries `password: { hash: nativeScryptHash, verify:
|
|
815
832
|
// nativeScryptVerify }` — the hashing every stored credential was created
|
|
@@ -1175,6 +1192,17 @@ function serverOnlyPlugin<T extends BetterAuthPlugin>(plugin: T): T {
|
|
|
1175
1192
|
* callback and in `/sign-in/social` with an `idToken`), so each provider receives it explicitly. A boolean
|
|
1176
1193
|
* `disableSignUp` on the provider is the deliberate exception for that provider; any other value follows the global
|
|
1177
1194
|
* flag, so a string arriving through `NEST_SERVER_CONFIG` cannot open a closed registration.
|
|
1195
|
+
*
|
|
1196
|
+
* Every other option the project set on a provider reaches Better-Auth unchanged (12.10.0): Microsoft's `tenantId`,
|
|
1197
|
+
* `scope` with `disableDefaultScope`, `prompt`, `mapProfileToUser` and so on. Before, they were dropped, so a Microsoft
|
|
1198
|
+
* sign-in ran against `common` with the default scope whatever the project configured. `enabled` is the framework's
|
|
1199
|
+
* own switch and stays here. The three values below are written AFTER the project's options on purpose: spread last,
|
|
1200
|
+
* the project's raw `disableSignUp` would replace the decision made above.
|
|
1201
|
+
*
|
|
1202
|
+
* `scope` given as a string becomes a list (`splitScopeList()`), because that is how an `NSC__*` variable delivers it.
|
|
1203
|
+
* A `scope` that is neither a string nor a list (the object indexed `NSC__…__SCOPE__0` variables build, the `0` an
|
|
1204
|
+
* empty `NSC__…__SCOPE=` becomes) is dropped with one error per provider: Better-Auth spreads `scope` into its list, so
|
|
1205
|
+
* an object made every `/sign-in/social` throw a `TypeError`. The provider then asks for its default scopes.
|
|
1178
1206
|
*/
|
|
1179
1207
|
function buildSocialProviders(config: IBetterAuth): Record<string, SocialProviderConfig> {
|
|
1180
1208
|
const socialProvidersConfig: Record<string, SocialProviderConfig> = {};
|
|
@@ -1186,7 +1214,22 @@ function buildSocialProviders(config: IBetterAuth): Record<string, SocialProvide
|
|
|
1186
1214
|
if (config.socialProviders) {
|
|
1187
1215
|
for (const [name, provider] of Object.entries(config.socialProviders)) {
|
|
1188
1216
|
if (provider?.clientId && provider?.clientSecret && provider?.enabled !== false) {
|
|
1217
|
+
const providerOptions: Record<string, unknown> = { ...provider };
|
|
1218
|
+
delete providerOptions.enabled;
|
|
1219
|
+
if (typeof providerOptions.scope === 'string') {
|
|
1220
|
+
providerOptions.scope = splitScopeList(providerOptions.scope);
|
|
1221
|
+
} else if (
|
|
1222
|
+
providerOptions.scope !== undefined &&
|
|
1223
|
+
providerOptions.scope !== null &&
|
|
1224
|
+
!Array.isArray(providerOptions.scope)
|
|
1225
|
+
) {
|
|
1226
|
+
logger.error(
|
|
1227
|
+
malformedScopeMessage(name, providerOptions.scope, providerOptions.disableDefaultScope === true),
|
|
1228
|
+
);
|
|
1229
|
+
delete providerOptions.scope;
|
|
1230
|
+
}
|
|
1189
1231
|
socialProvidersConfig[name] = {
|
|
1232
|
+
...providerOptions,
|
|
1190
1233
|
clientId: provider.clientId,
|
|
1191
1234
|
clientSecret: provider.clientSecret,
|
|
1192
1235
|
disableSignUp: typeof provider.disableSignUp === 'boolean' ? provider.disableSignUp : signUpClosed,
|
|
@@ -1198,6 +1241,43 @@ function buildSocialProviders(config: IBetterAuth): Record<string, SocialProvide
|
|
|
1198
1241
|
return socialProvidersConfig;
|
|
1199
1242
|
}
|
|
1200
1243
|
|
|
1244
|
+
/**
|
|
1245
|
+
* Splits a provider's `scope` string on commas and whitespace into the list Better-Auth expects, dropping empty
|
|
1246
|
+
* entries: `'openid profile email'` and `'openid,profile,email'` both become `['openid', 'profile', 'email']`.
|
|
1247
|
+
*
|
|
1248
|
+
* `NSC__BETTER_AUTH__SOCIAL_PROVIDERS__<PROVIDER>__SCOPE` reaches the configuration as a string, since the `NSC__*`
|
|
1249
|
+
* reader converts only `true`, `false` and numbers. Better-Auth spreads `scope` into its list
|
|
1250
|
+
* (`scopes.push(...options.scope)`), so a string handed on unchanged became one scope per character.
|
|
1251
|
+
*/
|
|
1252
|
+
function splitScopeList(scope: string): string[] {
|
|
1253
|
+
return scope.split(/[\s,]+/).filter((entry) => entry.length > 0);
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
/**
|
|
1257
|
+
* The error for a provider `scope` that is neither a string nor a list: which provider, what arrived, the two forms
|
|
1258
|
+
* that work, and, with `disableDefaultScope`, that the authorization request then carries no scope at all.
|
|
1259
|
+
*/
|
|
1260
|
+
function malformedScopeMessage(provider: string, scope: unknown, defaultScopeDisabled: boolean): string {
|
|
1261
|
+
let shown: string;
|
|
1262
|
+
try {
|
|
1263
|
+
shown = JSON.stringify(scope) ?? String(scope);
|
|
1264
|
+
} catch {
|
|
1265
|
+
shown = String(scope);
|
|
1266
|
+
}
|
|
1267
|
+
if (shown.length > 200) {
|
|
1268
|
+
shown = `${shown.slice(0, 200)}…`;
|
|
1269
|
+
}
|
|
1270
|
+
const variable = `NSC__BETTER_AUTH__SOCIAL_PROVIDERS__${provider.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase()}__SCOPE`;
|
|
1271
|
+
return (
|
|
1272
|
+
`betterAuth.socialProviders.${provider}.scope is neither a string nor a list (received ${typeof scope} ${shown}) ` +
|
|
1273
|
+
'and is ignored. Write it as a list in config.env.ts or NEST_SERVER_CONFIG, or as a comma- or space-separated ' +
|
|
1274
|
+
`string (${variable}=openid,profile,email); indexed ${variable}__0 variables build an object, not a list. ` +
|
|
1275
|
+
(defaultScopeDisabled
|
|
1276
|
+
? 'With disableDefaultScope: true the authorization request now carries no scope, and the provider will refuse it.'
|
|
1277
|
+
: 'The provider asks for its default scopes until then.')
|
|
1278
|
+
);
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1201
1281
|
/**
|
|
1202
1282
|
* Builds the trusted origins array for CORS configuration.
|
|
1203
1283
|
*
|
|
@@ -1889,6 +1969,63 @@ function deriveCookieDomainFromUrls(appUrl?: string, baseUrl?: string): string |
|
|
|
1889
1969
|
return undefined;
|
|
1890
1970
|
}
|
|
1891
1971
|
|
|
1972
|
+
/** The app page a failed OAuth flow lands on when `betterAuth.errorUrl` is unset; the starter's login page */
|
|
1973
|
+
const DEFAULT_ERROR_PATH = '/auth/login';
|
|
1974
|
+
|
|
1975
|
+
/**
|
|
1976
|
+
* Better-Auth's `onAPIError.errorURL`: where a failed OAuth flow lands when no error URL of the flow's own applies
|
|
1977
|
+
* (12.10.0). Its readers in better-auth 1.7.x: the OAuth callback (a callback without a readable state, and every
|
|
1978
|
+
* later failure of a flow started without `errorCallbackURL`, through `parseState()`), the `internal_server_error`
|
|
1979
|
+
* redirects of `handleOAuthUserInfo()`, the `GET /error` page (which forwards there) and the `oauthProxy()` plugin.
|
|
1980
|
+
* Unset, all of them send the browser to Better-Auth's own HTML page on the API host, which offers no way back into
|
|
1981
|
+
* the app.
|
|
1982
|
+
*
|
|
1983
|
+
* Unset → `<appUrl>/auth/login`; an absolute `http(s)` URL as it is; a path with one leading `/` against the app URL;
|
|
1984
|
+
* `false` → Better-Auth's page. Anything else, and a path without an app URL, keeps Better-Auth's page with a warning:
|
|
1985
|
+
* a misconfiguration must neither stop the boot nor send the browser somewhere nobody chose. A protocol-relative
|
|
1986
|
+
* `//host` (and `/\host`, which browsers read the same way) is refused for that reason; Better-Auth's own
|
|
1987
|
+
* `appendQueryParams()` would throw on it as well.
|
|
1988
|
+
*
|
|
1989
|
+
* @param value - `betterAuth.errorUrl` as configured
|
|
1990
|
+
* @param appUrl - the app URL, resolved like the other derived links (`resolveServerUrls()`)
|
|
1991
|
+
* @returns the URL to hand Better-Auth, or `undefined` for Better-Auth's own page
|
|
1992
|
+
*/
|
|
1993
|
+
function resolveErrorUrl(value: unknown, appUrl: string | undefined): string | undefined {
|
|
1994
|
+
const againstApp = (appPath: string) => `${appUrl!.replace(/\/$/, '')}${appPath}`;
|
|
1995
|
+
if (value === false) {
|
|
1996
|
+
return undefined;
|
|
1997
|
+
}
|
|
1998
|
+
if (value === undefined || value === null) {
|
|
1999
|
+
return appUrl ? againstApp(DEFAULT_ERROR_PATH) : undefined;
|
|
2000
|
+
}
|
|
2001
|
+
const refuse = (reason: string): undefined => {
|
|
2002
|
+
logger.warn(`betterAuth.errorUrl ${reason}; failed sign-ins land on Better-Auth's own error page on the API host.`);
|
|
2003
|
+
return undefined;
|
|
2004
|
+
};
|
|
2005
|
+
if (typeof value !== 'string') {
|
|
2006
|
+
return refuse(
|
|
2007
|
+
`must be an absolute http(s) URL, a path starting with "/" or false (received ${typeof value} ${String(value)})`,
|
|
2008
|
+
);
|
|
2009
|
+
}
|
|
2010
|
+
const trimmed = value.trim();
|
|
2011
|
+
if (/^https?:\/\//i.test(trimmed)) {
|
|
2012
|
+
try {
|
|
2013
|
+
if (new URL(trimmed).hostname) {
|
|
2014
|
+
return trimmed;
|
|
2015
|
+
}
|
|
2016
|
+
} catch {
|
|
2017
|
+
// refused below
|
|
2018
|
+
}
|
|
2019
|
+
return refuse(`"${trimmed}" is not a valid URL`);
|
|
2020
|
+
}
|
|
2021
|
+
if (/^\/(?![/\\])/.test(trimmed)) {
|
|
2022
|
+
return appUrl
|
|
2023
|
+
? againstApp(trimmed)
|
|
2024
|
+
: refuse(`"${trimmed}" is a path, but no app URL resolves to put it on (set appUrl or baseUrl)`);
|
|
2025
|
+
}
|
|
2026
|
+
return refuse(`"${trimmed}" must be an absolute http(s) URL, a path starting with "/" or false`);
|
|
2027
|
+
}
|
|
2028
|
+
|
|
1892
2029
|
function resolveUrls(options: CreateBetterAuthOptions): ResolvedUrls {
|
|
1893
2030
|
const { config, serverAppUrl, serverBaseUrl, serverCorsConfig, serverEnv } = options;
|
|
1894
2031
|
const warnings: string[] = [];
|
|
@@ -17,7 +17,7 @@ import { firstValueFrom, isObservable } from 'rxjs';
|
|
|
17
17
|
|
|
18
18
|
import { RoleEnum } from '../../common/enums/role.enum.js';
|
|
19
19
|
import { ROLE_GUARD } from '../auth/guards/role-guard.token.js';
|
|
20
|
-
import { resolveGuardRequest } from '../../common/helpers/execution-context-request.helper.js';
|
|
20
|
+
import { isAgentCallContext, resolveGuardRequest } from '../../common/helpers/execution-context-request.helper.js';
|
|
21
21
|
import {
|
|
22
22
|
revalidateAllWsConnections,
|
|
23
23
|
revalidateWsConnectionsForTenant,
|
|
@@ -431,6 +431,18 @@ export class CoreTenantGuard implements CanActivate, OnApplicationBootstrap, OnM
|
|
|
431
431
|
|
|
432
432
|
const request = this.getRequest(context);
|
|
433
433
|
if (!request) {
|
|
434
|
+
// An agent function / MCP call without a request is anonymous (nestjs-ai plan §1). "No request" is never
|
|
435
|
+
// permission there: only a public method runs, every other one is refused like an unauthenticated request.
|
|
436
|
+
if (isAgentCallContext(context)) {
|
|
437
|
+
const rolesMetadata = this.reflector.getAll<string[][]>('roles', [context.getHandler(), context.getClass()]);
|
|
438
|
+
const roles = mergeRolesMetadata(rolesMetadata);
|
|
439
|
+
// The method's own roles win over the class's (as `systemCheckRoles` below): a class-level S_EVERYONE does
|
|
440
|
+
// not open a method that asks for S_USER or a tenant role
|
|
441
|
+
const effective = rolesMetadata?.[0]?.some((role) => !!role) ? rolesMetadata[0] : roles;
|
|
442
|
+
if (effective?.some((role) => !!role) && !effective.includes(RoleEnum.S_EVERYONE)) {
|
|
443
|
+
throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
434
446
|
return true;
|
|
435
447
|
}
|
|
436
448
|
|
package/src/core.module.ts
CHANGED
|
@@ -15,6 +15,7 @@ import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs';
|
|
|
15
15
|
|
|
16
16
|
import { MongooseCastErrorFilter } from './core/common/filters/mongoose-cast-error.filter.js';
|
|
17
17
|
import { merge } from './core/common/helpers/config.helper.js';
|
|
18
|
+
import { processGraphQlUploadRequest } from './core/common/helpers/graphql-upload.helper.js';
|
|
18
19
|
import { refuseWsHandshake, registerWsConnection } from './core/common/helpers/graphql-ws-connection.helper.js';
|
|
19
20
|
import {
|
|
20
21
|
buildRequestContextAwareExecute,
|
|
@@ -127,7 +128,10 @@ export class CoreModule implements NestModule {
|
|
|
127
128
|
// config read here and the values there.
|
|
128
129
|
consumer.apply(SecurityHeadersMiddleware).forRoutes('*');
|
|
129
130
|
if (CoreModule.graphQlEnabled) {
|
|
130
|
-
|
|
131
|
+
// The framework's processRequest, never graphql-upload's default: the default (graphql-upload < 18.0.2) lets
|
|
132
|
+
// one anonymous multipart request crash the process (GHSA-5vm7-vc2x-p3w2) and leaks temporary files on
|
|
133
|
+
// duplicate file fields (GHSA-qwwm-252j-9whw). This middleware runs before any authentication.
|
|
134
|
+
consumer.apply(graphqlUploadExpress({ processRequest: processGraphQlUploadRequest })).forRoutes('graphql');
|
|
131
135
|
}
|
|
132
136
|
}
|
|
133
137
|
|
package/src/index.ts
CHANGED
|
@@ -44,6 +44,7 @@ export * from './core/common/helpers/execution-context-request.helper.js';
|
|
|
44
44
|
export * from './core/common/helpers/file.helper.js';
|
|
45
45
|
export * from './core/common/helpers/filter.helper.js';
|
|
46
46
|
export * from './core/common/helpers/graphql.helper.js';
|
|
47
|
+
export * from './core/common/helpers/graphql-upload.helper.js';
|
|
47
48
|
export * from './core/common/helpers/graphql-ws-connection.helper.js';
|
|
48
49
|
export * from './core/common/helpers/graphql-ws-context.helper.js';
|
|
49
50
|
export * from './core/common/helpers/idle-stream.helper.js';
|
|
@@ -4,21 +4,53 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Since graphql-upload 16 the package is ESM: its `exports` map lists only the `.mjs` deep paths, each
|
|
6
6
|
* with a default export, and it ships no declaration files (its types are JSDoc inside the `.mjs`
|
|
7
|
-
* sources, which TypeScript does not read from `node_modules`).
|
|
7
|
+
* sources, which TypeScript does not read from `node_modules`). The names below are the ones the
|
|
8
8
|
* framework imports.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
declare module 'graphql-upload/graphqlUploadExpress.mjs' {
|
|
12
12
|
import { RequestHandler } from 'express';
|
|
13
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
13
14
|
|
|
14
|
-
interface
|
|
15
|
+
interface GraphQLUploadProcessRequestOptions {
|
|
16
|
+
maxFieldSize?: number;
|
|
15
17
|
maxFiles?: number;
|
|
16
18
|
maxFileSize?: number;
|
|
17
19
|
}
|
|
18
20
|
|
|
21
|
+
interface GraphQLUploadOptions extends GraphQLUploadProcessRequestOptions {
|
|
22
|
+
/**
|
|
23
|
+
* The function that parses the multipart request. graphql-upload's default is its own `processRequest`, which is
|
|
24
|
+
* vulnerable to GHSA-5vm7-vc2x-p3w2 and GHSA-qwwm-252j-9whw below 18.0.2 — pass the framework's
|
|
25
|
+
* `processGraphQlUploadRequest`.
|
|
26
|
+
*/
|
|
27
|
+
processRequest?: (
|
|
28
|
+
request: IncomingMessage,
|
|
29
|
+
response: ServerResponse,
|
|
30
|
+
options?: GraphQLUploadProcessRequestOptions,
|
|
31
|
+
) => Promise<unknown>;
|
|
32
|
+
}
|
|
33
|
+
|
|
19
34
|
export default function graphqlUploadExpress(options?: GraphQLUploadOptions): RequestHandler;
|
|
20
35
|
}
|
|
21
36
|
|
|
37
|
+
declare module 'graphql-upload/Upload.mjs' {
|
|
38
|
+
/**
|
|
39
|
+
* A file expected in a GraphQL multipart request, placed in the operations wherever the `map` names it. The
|
|
40
|
+
* `GraphQLUpload` scalar accepts a value only if it is `instanceof` this class, of the same graphql-upload copy.
|
|
41
|
+
*/
|
|
42
|
+
export default class Upload {
|
|
43
|
+
/** The file's details once it streamed in (set by `resolve`). */
|
|
44
|
+
file?: unknown;
|
|
45
|
+
/** Resolves with the file's details; the scalar hands it to the resolver. */
|
|
46
|
+
promise: Promise<unknown>;
|
|
47
|
+
/** Rejects the upload (missing file, aborted request). */
|
|
48
|
+
reject: (error: Error) => void;
|
|
49
|
+
/** Resolves the upload with the file's details. */
|
|
50
|
+
resolve: (file: unknown) => void;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
22
54
|
declare module 'graphql-upload/GraphQLUpload.mjs' {
|
|
23
55
|
import { GraphQLScalarType } from 'graphql';
|
|
24
56
|
|