@pedr0ni/nestjs-better-auth 1.0.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.
@@ -0,0 +1,232 @@
1
+ import * as _nestjs_common from '@nestjs/common';
2
+ import { CustomDecorator, createParamDecorator, NestModule, OnModuleInit, MiddlewareConsumer, DynamicModule, CanActivate, ExecutionContext } from '@nestjs/common';
3
+ import { createAuthMiddleware, getSession } from 'better-auth/api';
4
+ import { Auth as Auth$1 } from 'better-auth';
5
+ import { ApplicationConfig, DiscoveryService, MetadataScanner, HttpAdapterHost, Reflector } from '@nestjs/core';
6
+ import { Request, Response, NextFunction } from 'express';
7
+
8
+ /**
9
+ * Allows unauthenticated (anonymous) access to a route or controller.
10
+ * When applied, the AuthGuard will not perform authentication checks.
11
+ */
12
+ declare const AllowAnonymous: () => CustomDecorator<string>;
13
+ /**
14
+ * Marks a route or controller as having optional authentication.
15
+ * When applied, the AuthGuard allows the request to proceed
16
+ * even if no session is present.
17
+ */
18
+ declare const OptionalAuth: () => CustomDecorator<string>;
19
+ /**
20
+ * Specifies the user-level roles required to access a route or controller.
21
+ * Checks ONLY the `user.role` field (from Better Auth's admin plugin).
22
+ * Does NOT check organization member roles.
23
+ *
24
+ * Use this for system-wide admin protection (e.g., superadmin routes).
25
+ *
26
+ * @param roles - The roles required for access
27
+ * @example
28
+ * ```ts
29
+ * @Roles(['admin']) // Only users with user.role = 'admin' can access
30
+ * ```
31
+ */
32
+ declare const Roles: (roles: string[]) => CustomDecorator;
33
+ /**
34
+ * Specifies the organization-level roles required to access a route or controller.
35
+ * Checks ONLY the organization member role (from Better Auth's organization plugin).
36
+ * Requires an active organization (`activeOrganizationId` in session).
37
+ *
38
+ * Use this for organization-scoped protection (e.g., org admin routes).
39
+ *
40
+ * @param roles - The organization roles required for access
41
+ * @example
42
+ * ```ts
43
+ * @OrgRoles(['owner', 'admin']) // Only org owners/admins can access
44
+ * ```
45
+ */
46
+ declare const OrgRoles: (roles: string[]) => CustomDecorator;
47
+ /**
48
+ * @deprecated Use AllowAnonymous() instead.
49
+ */
50
+ declare const Public: () => CustomDecorator<string>;
51
+ /**
52
+ * @deprecated Use OptionalAuth() instead.
53
+ */
54
+ declare const Optional: () => CustomDecorator<string>;
55
+ /**
56
+ * Parameter decorator that extracts the user session from the request.
57
+ * Provides easy access to the authenticated user's session data in controller methods.
58
+ * Works with both HTTP and GraphQL execution contexts.
59
+ */
60
+ declare const Session: ReturnType<typeof createParamDecorator>;
61
+ /**
62
+ * Represents the context object passed to hooks.
63
+ * This type is derived from the parameters of the createAuthMiddleware function.
64
+ */
65
+ type AuthHookContext = Parameters<Parameters<typeof createAuthMiddleware>[0]>[0];
66
+ /**
67
+ * Registers a method to be executed before a specific auth route is processed.
68
+ * @param path - The auth route path that triggers this hook (must start with '/')
69
+ */
70
+ declare const BeforeHook: (path?: `/${string}`) => CustomDecorator<symbol>;
71
+ /**
72
+ * Registers a method to be executed after a specific auth route is processed.
73
+ * @param path - The auth route path that triggers this hook (must start with '/')
74
+ */
75
+ declare const AfterHook: (path?: `/${string}`) => CustomDecorator<symbol>;
76
+ /**
77
+ * Class decorator that marks a provider as containing hook methods.
78
+ * Must be applied to classes that use BeforeHook or AfterHook decorators.
79
+ */
80
+ declare const Hook: () => ClassDecorator;
81
+
82
+ type Auth = any;
83
+ /**
84
+ * NestJS module that integrates the Auth library with NestJS applications.
85
+ * Provides authentication middleware, hooks, and exception handling.
86
+ */
87
+ declare class AuthModule extends ConfigurableModuleClass implements NestModule, OnModuleInit {
88
+ private readonly applicationConfig;
89
+ private readonly discoveryService;
90
+ private readonly metadataScanner;
91
+ private readonly adapter;
92
+ private readonly options;
93
+ private readonly logger;
94
+ private readonly basePath;
95
+ constructor(applicationConfig: ApplicationConfig, discoveryService: DiscoveryService, metadataScanner: MetadataScanner, adapter: HttpAdapterHost, options: AuthModuleOptions);
96
+ onModuleInit(): void;
97
+ configure(consumer: MiddlewareConsumer): void;
98
+ private setupHooks;
99
+ static forRootAsync(options: typeof ASYNC_OPTIONS_TYPE): DynamicModule;
100
+ static forRoot(options: typeof OPTIONS_TYPE): DynamicModule;
101
+ /**
102
+ * @deprecated Use the object-based signature: AuthModule.forRoot({ auth, ...options })
103
+ */
104
+ static forRoot(auth: Auth, options?: Omit<typeof OPTIONS_TYPE, "auth">): DynamicModule;
105
+ }
106
+
107
+ type AuthModuleOptions<A = Auth> = {
108
+ auth: A;
109
+ disableTrustedOriginsCors?: boolean;
110
+ disableBodyParser?: boolean;
111
+ /**
112
+ * When set to `true`, enables raw body parsing and attaches it to `req.rawBody`.
113
+ *
114
+ * This is useful for webhook signature verification that requires the raw,
115
+ * unparsed request body.
116
+ *
117
+ * **Important:** Since this library disables NestJS's built-in body parser,
118
+ * NestJS's `rawBody: true` option in `NestFactory.create()` has no effect.
119
+ * Use this option instead.
120
+ *
121
+ * @default false
122
+ */
123
+ enableRawBodyParser?: boolean;
124
+ middleware?: (req: Request, res: Response, next: NextFunction) => void;
125
+ };
126
+ declare const ConfigurableModuleClass: _nestjs_common.ConfigurableModuleCls<AuthModuleOptions<any>, "forRoot", "create", {
127
+ isGlobal: boolean;
128
+ disableGlobalAuthGuard: boolean;
129
+ disableControllers: boolean;
130
+ }>;
131
+ declare const OPTIONS_TYPE: AuthModuleOptions<any> & Partial<{
132
+ isGlobal: boolean;
133
+ disableGlobalAuthGuard: boolean;
134
+ disableControllers: boolean;
135
+ }>;
136
+ declare const ASYNC_OPTIONS_TYPE: _nestjs_common.ConfigurableModuleAsyncOptions<AuthModuleOptions<any>, "create"> & Partial<{
137
+ isGlobal: boolean;
138
+ disableGlobalAuthGuard: boolean;
139
+ disableControllers: boolean;
140
+ }>;
141
+
142
+ /**
143
+ * NestJS service that provides access to the Better Auth instance
144
+ * Use generics to support auth instances extended by plugins
145
+ */
146
+ declare class AuthService<T extends {
147
+ api: T["api"];
148
+ } = Auth$1> {
149
+ private readonly options;
150
+ constructor(options: AuthModuleOptions<T>);
151
+ /**
152
+ * Returns the API endpoints provided by the auth instance
153
+ */
154
+ get api(): T["api"];
155
+ /**
156
+ * Returns the complete auth instance
157
+ * Access this for plugin-specific functionality
158
+ */
159
+ get instance(): T;
160
+ }
161
+
162
+ /**
163
+ * Type representing a valid user session after authentication
164
+ * Excludes null and undefined values from the session return type
165
+ */
166
+ type BaseUserSession = NonNullable<Awaited<ReturnType<ReturnType<typeof getSession>>>>;
167
+ type UserSession = BaseUserSession & {
168
+ user: BaseUserSession["user"] & {
169
+ role?: string | string[];
170
+ };
171
+ session: BaseUserSession["session"] & {
172
+ activeOrganizationId?: string;
173
+ };
174
+ };
175
+ /**
176
+ * NestJS guard that handles authentication for protected routes
177
+ * Can be configured with @AllowAnonymous() or @OptionalAuth() decorators to modify authentication behavior
178
+ */
179
+ declare class AuthGuard implements CanActivate {
180
+ private readonly reflector;
181
+ private readonly options;
182
+ constructor(reflector: Reflector, options: AuthModuleOptions);
183
+ /**
184
+ * Validates if the current request is authenticated
185
+ * Attaches session and user information to the request object
186
+ * Supports HTTP, GraphQL and WebSocket execution contexts
187
+ * @param context - The execution context of the current request
188
+ * @returns True if the request is authorized to proceed, throws an error otherwise
189
+ */
190
+ canActivate(context: ExecutionContext): Promise<boolean>;
191
+ /**
192
+ * Checks if a role value matches any of the required roles
193
+ * Handles both array and comma-separated string role formats
194
+ * @param role - The role value to check (string, array, or undefined)
195
+ * @param requiredRoles - Array of roles that grant access
196
+ * @returns True if the role matches any required role
197
+ */
198
+ private matchesRequiredRole;
199
+ /**
200
+ * Fetches the user's role within an organization from the member table
201
+ * Uses Better Auth's organization plugin API if available
202
+ * @param headers - The request headers containing session cookies
203
+ * @returns The member's role in the organization, or undefined if not found
204
+ */
205
+ private getMemberRoleInOrganization;
206
+ /**
207
+ * Checks if the user has any of the required roles in user.role only.
208
+ * Used by @Roles() decorator for system-level role checks (admin plugin).
209
+ * @param session - The user's session
210
+ * @param requiredRoles - Array of roles that grant access
211
+ * @returns True if user.role matches any required role
212
+ */
213
+ private checkUserRole;
214
+ /**
215
+ * Checks if the user has any of the required roles in their organization.
216
+ * Used by @OrgRoles() decorator for organization-level role checks.
217
+ * Requires an active organization in the session.
218
+ * @param session - The user's session
219
+ * @param headers - The request headers for API calls
220
+ * @param requiredRoles - Array of roles that grant access
221
+ * @returns True if org member role matches any required role
222
+ */
223
+ private checkOrgRole;
224
+ }
225
+
226
+ declare const BEFORE_HOOK_KEY: symbol;
227
+ declare const AFTER_HOOK_KEY: symbol;
228
+ declare const HOOK_KEY: symbol;
229
+ declare const AUTH_MODULE_OPTIONS_KEY: symbol;
230
+
231
+ export { AFTER_HOOK_KEY, AUTH_MODULE_OPTIONS_KEY, AfterHook, AllowAnonymous, AuthGuard, AuthModule, AuthService, BEFORE_HOOK_KEY, BeforeHook, HOOK_KEY, Hook, Optional, OptionalAuth, OrgRoles, Public, Roles, Session };
232
+ export type { Auth, AuthHookContext, BaseUserSession, UserSession };
@@ -0,0 +1,232 @@
1
+ import * as _nestjs_common from '@nestjs/common';
2
+ import { CustomDecorator, createParamDecorator, NestModule, OnModuleInit, MiddlewareConsumer, DynamicModule, CanActivate, ExecutionContext } from '@nestjs/common';
3
+ import { createAuthMiddleware, getSession } from 'better-auth/api';
4
+ import { Auth as Auth$1 } from 'better-auth';
5
+ import { ApplicationConfig, DiscoveryService, MetadataScanner, HttpAdapterHost, Reflector } from '@nestjs/core';
6
+ import { Request, Response, NextFunction } from 'express';
7
+
8
+ /**
9
+ * Allows unauthenticated (anonymous) access to a route or controller.
10
+ * When applied, the AuthGuard will not perform authentication checks.
11
+ */
12
+ declare const AllowAnonymous: () => CustomDecorator<string>;
13
+ /**
14
+ * Marks a route or controller as having optional authentication.
15
+ * When applied, the AuthGuard allows the request to proceed
16
+ * even if no session is present.
17
+ */
18
+ declare const OptionalAuth: () => CustomDecorator<string>;
19
+ /**
20
+ * Specifies the user-level roles required to access a route or controller.
21
+ * Checks ONLY the `user.role` field (from Better Auth's admin plugin).
22
+ * Does NOT check organization member roles.
23
+ *
24
+ * Use this for system-wide admin protection (e.g., superadmin routes).
25
+ *
26
+ * @param roles - The roles required for access
27
+ * @example
28
+ * ```ts
29
+ * @Roles(['admin']) // Only users with user.role = 'admin' can access
30
+ * ```
31
+ */
32
+ declare const Roles: (roles: string[]) => CustomDecorator;
33
+ /**
34
+ * Specifies the organization-level roles required to access a route or controller.
35
+ * Checks ONLY the organization member role (from Better Auth's organization plugin).
36
+ * Requires an active organization (`activeOrganizationId` in session).
37
+ *
38
+ * Use this for organization-scoped protection (e.g., org admin routes).
39
+ *
40
+ * @param roles - The organization roles required for access
41
+ * @example
42
+ * ```ts
43
+ * @OrgRoles(['owner', 'admin']) // Only org owners/admins can access
44
+ * ```
45
+ */
46
+ declare const OrgRoles: (roles: string[]) => CustomDecorator;
47
+ /**
48
+ * @deprecated Use AllowAnonymous() instead.
49
+ */
50
+ declare const Public: () => CustomDecorator<string>;
51
+ /**
52
+ * @deprecated Use OptionalAuth() instead.
53
+ */
54
+ declare const Optional: () => CustomDecorator<string>;
55
+ /**
56
+ * Parameter decorator that extracts the user session from the request.
57
+ * Provides easy access to the authenticated user's session data in controller methods.
58
+ * Works with both HTTP and GraphQL execution contexts.
59
+ */
60
+ declare const Session: ReturnType<typeof createParamDecorator>;
61
+ /**
62
+ * Represents the context object passed to hooks.
63
+ * This type is derived from the parameters of the createAuthMiddleware function.
64
+ */
65
+ type AuthHookContext = Parameters<Parameters<typeof createAuthMiddleware>[0]>[0];
66
+ /**
67
+ * Registers a method to be executed before a specific auth route is processed.
68
+ * @param path - The auth route path that triggers this hook (must start with '/')
69
+ */
70
+ declare const BeforeHook: (path?: `/${string}`) => CustomDecorator<symbol>;
71
+ /**
72
+ * Registers a method to be executed after a specific auth route is processed.
73
+ * @param path - The auth route path that triggers this hook (must start with '/')
74
+ */
75
+ declare const AfterHook: (path?: `/${string}`) => CustomDecorator<symbol>;
76
+ /**
77
+ * Class decorator that marks a provider as containing hook methods.
78
+ * Must be applied to classes that use BeforeHook or AfterHook decorators.
79
+ */
80
+ declare const Hook: () => ClassDecorator;
81
+
82
+ type Auth = any;
83
+ /**
84
+ * NestJS module that integrates the Auth library with NestJS applications.
85
+ * Provides authentication middleware, hooks, and exception handling.
86
+ */
87
+ declare class AuthModule extends ConfigurableModuleClass implements NestModule, OnModuleInit {
88
+ private readonly applicationConfig;
89
+ private readonly discoveryService;
90
+ private readonly metadataScanner;
91
+ private readonly adapter;
92
+ private readonly options;
93
+ private readonly logger;
94
+ private readonly basePath;
95
+ constructor(applicationConfig: ApplicationConfig, discoveryService: DiscoveryService, metadataScanner: MetadataScanner, adapter: HttpAdapterHost, options: AuthModuleOptions);
96
+ onModuleInit(): void;
97
+ configure(consumer: MiddlewareConsumer): void;
98
+ private setupHooks;
99
+ static forRootAsync(options: typeof ASYNC_OPTIONS_TYPE): DynamicModule;
100
+ static forRoot(options: typeof OPTIONS_TYPE): DynamicModule;
101
+ /**
102
+ * @deprecated Use the object-based signature: AuthModule.forRoot({ auth, ...options })
103
+ */
104
+ static forRoot(auth: Auth, options?: Omit<typeof OPTIONS_TYPE, "auth">): DynamicModule;
105
+ }
106
+
107
+ type AuthModuleOptions<A = Auth> = {
108
+ auth: A;
109
+ disableTrustedOriginsCors?: boolean;
110
+ disableBodyParser?: boolean;
111
+ /**
112
+ * When set to `true`, enables raw body parsing and attaches it to `req.rawBody`.
113
+ *
114
+ * This is useful for webhook signature verification that requires the raw,
115
+ * unparsed request body.
116
+ *
117
+ * **Important:** Since this library disables NestJS's built-in body parser,
118
+ * NestJS's `rawBody: true` option in `NestFactory.create()` has no effect.
119
+ * Use this option instead.
120
+ *
121
+ * @default false
122
+ */
123
+ enableRawBodyParser?: boolean;
124
+ middleware?: (req: Request, res: Response, next: NextFunction) => void;
125
+ };
126
+ declare const ConfigurableModuleClass: _nestjs_common.ConfigurableModuleCls<AuthModuleOptions<any>, "forRoot", "create", {
127
+ isGlobal: boolean;
128
+ disableGlobalAuthGuard: boolean;
129
+ disableControllers: boolean;
130
+ }>;
131
+ declare const OPTIONS_TYPE: AuthModuleOptions<any> & Partial<{
132
+ isGlobal: boolean;
133
+ disableGlobalAuthGuard: boolean;
134
+ disableControllers: boolean;
135
+ }>;
136
+ declare const ASYNC_OPTIONS_TYPE: _nestjs_common.ConfigurableModuleAsyncOptions<AuthModuleOptions<any>, "create"> & Partial<{
137
+ isGlobal: boolean;
138
+ disableGlobalAuthGuard: boolean;
139
+ disableControllers: boolean;
140
+ }>;
141
+
142
+ /**
143
+ * NestJS service that provides access to the Better Auth instance
144
+ * Use generics to support auth instances extended by plugins
145
+ */
146
+ declare class AuthService<T extends {
147
+ api: T["api"];
148
+ } = Auth$1> {
149
+ private readonly options;
150
+ constructor(options: AuthModuleOptions<T>);
151
+ /**
152
+ * Returns the API endpoints provided by the auth instance
153
+ */
154
+ get api(): T["api"];
155
+ /**
156
+ * Returns the complete auth instance
157
+ * Access this for plugin-specific functionality
158
+ */
159
+ get instance(): T;
160
+ }
161
+
162
+ /**
163
+ * Type representing a valid user session after authentication
164
+ * Excludes null and undefined values from the session return type
165
+ */
166
+ type BaseUserSession = NonNullable<Awaited<ReturnType<ReturnType<typeof getSession>>>>;
167
+ type UserSession = BaseUserSession & {
168
+ user: BaseUserSession["user"] & {
169
+ role?: string | string[];
170
+ };
171
+ session: BaseUserSession["session"] & {
172
+ activeOrganizationId?: string;
173
+ };
174
+ };
175
+ /**
176
+ * NestJS guard that handles authentication for protected routes
177
+ * Can be configured with @AllowAnonymous() or @OptionalAuth() decorators to modify authentication behavior
178
+ */
179
+ declare class AuthGuard implements CanActivate {
180
+ private readonly reflector;
181
+ private readonly options;
182
+ constructor(reflector: Reflector, options: AuthModuleOptions);
183
+ /**
184
+ * Validates if the current request is authenticated
185
+ * Attaches session and user information to the request object
186
+ * Supports HTTP, GraphQL and WebSocket execution contexts
187
+ * @param context - The execution context of the current request
188
+ * @returns True if the request is authorized to proceed, throws an error otherwise
189
+ */
190
+ canActivate(context: ExecutionContext): Promise<boolean>;
191
+ /**
192
+ * Checks if a role value matches any of the required roles
193
+ * Handles both array and comma-separated string role formats
194
+ * @param role - The role value to check (string, array, or undefined)
195
+ * @param requiredRoles - Array of roles that grant access
196
+ * @returns True if the role matches any required role
197
+ */
198
+ private matchesRequiredRole;
199
+ /**
200
+ * Fetches the user's role within an organization from the member table
201
+ * Uses Better Auth's organization plugin API if available
202
+ * @param headers - The request headers containing session cookies
203
+ * @returns The member's role in the organization, or undefined if not found
204
+ */
205
+ private getMemberRoleInOrganization;
206
+ /**
207
+ * Checks if the user has any of the required roles in user.role only.
208
+ * Used by @Roles() decorator for system-level role checks (admin plugin).
209
+ * @param session - The user's session
210
+ * @param requiredRoles - Array of roles that grant access
211
+ * @returns True if user.role matches any required role
212
+ */
213
+ private checkUserRole;
214
+ /**
215
+ * Checks if the user has any of the required roles in their organization.
216
+ * Used by @OrgRoles() decorator for organization-level role checks.
217
+ * Requires an active organization in the session.
218
+ * @param session - The user's session
219
+ * @param headers - The request headers for API calls
220
+ * @param requiredRoles - Array of roles that grant access
221
+ * @returns True if org member role matches any required role
222
+ */
223
+ private checkOrgRole;
224
+ }
225
+
226
+ declare const BEFORE_HOOK_KEY: symbol;
227
+ declare const AFTER_HOOK_KEY: symbol;
228
+ declare const HOOK_KEY: symbol;
229
+ declare const AUTH_MODULE_OPTIONS_KEY: symbol;
230
+
231
+ export { AFTER_HOOK_KEY, AUTH_MODULE_OPTIONS_KEY, AfterHook, AllowAnonymous, AuthGuard, AuthModule, AuthService, BEFORE_HOOK_KEY, BeforeHook, HOOK_KEY, Hook, Optional, OptionalAuth, OrgRoles, Public, Roles, Session };
232
+ export type { Auth, AuthHookContext, BaseUserSession, UserSession };
@@ -0,0 +1,232 @@
1
+ import * as _nestjs_common from '@nestjs/common';
2
+ import { CustomDecorator, createParamDecorator, NestModule, OnModuleInit, MiddlewareConsumer, DynamicModule, CanActivate, ExecutionContext } from '@nestjs/common';
3
+ import { createAuthMiddleware, getSession } from 'better-auth/api';
4
+ import { Auth as Auth$1 } from 'better-auth';
5
+ import { ApplicationConfig, DiscoveryService, MetadataScanner, HttpAdapterHost, Reflector } from '@nestjs/core';
6
+ import { Request, Response, NextFunction } from 'express';
7
+
8
+ /**
9
+ * Allows unauthenticated (anonymous) access to a route or controller.
10
+ * When applied, the AuthGuard will not perform authentication checks.
11
+ */
12
+ declare const AllowAnonymous: () => CustomDecorator<string>;
13
+ /**
14
+ * Marks a route or controller as having optional authentication.
15
+ * When applied, the AuthGuard allows the request to proceed
16
+ * even if no session is present.
17
+ */
18
+ declare const OptionalAuth: () => CustomDecorator<string>;
19
+ /**
20
+ * Specifies the user-level roles required to access a route or controller.
21
+ * Checks ONLY the `user.role` field (from Better Auth's admin plugin).
22
+ * Does NOT check organization member roles.
23
+ *
24
+ * Use this for system-wide admin protection (e.g., superadmin routes).
25
+ *
26
+ * @param roles - The roles required for access
27
+ * @example
28
+ * ```ts
29
+ * @Roles(['admin']) // Only users with user.role = 'admin' can access
30
+ * ```
31
+ */
32
+ declare const Roles: (roles: string[]) => CustomDecorator;
33
+ /**
34
+ * Specifies the organization-level roles required to access a route or controller.
35
+ * Checks ONLY the organization member role (from Better Auth's organization plugin).
36
+ * Requires an active organization (`activeOrganizationId` in session).
37
+ *
38
+ * Use this for organization-scoped protection (e.g., org admin routes).
39
+ *
40
+ * @param roles - The organization roles required for access
41
+ * @example
42
+ * ```ts
43
+ * @OrgRoles(['owner', 'admin']) // Only org owners/admins can access
44
+ * ```
45
+ */
46
+ declare const OrgRoles: (roles: string[]) => CustomDecorator;
47
+ /**
48
+ * @deprecated Use AllowAnonymous() instead.
49
+ */
50
+ declare const Public: () => CustomDecorator<string>;
51
+ /**
52
+ * @deprecated Use OptionalAuth() instead.
53
+ */
54
+ declare const Optional: () => CustomDecorator<string>;
55
+ /**
56
+ * Parameter decorator that extracts the user session from the request.
57
+ * Provides easy access to the authenticated user's session data in controller methods.
58
+ * Works with both HTTP and GraphQL execution contexts.
59
+ */
60
+ declare const Session: ReturnType<typeof createParamDecorator>;
61
+ /**
62
+ * Represents the context object passed to hooks.
63
+ * This type is derived from the parameters of the createAuthMiddleware function.
64
+ */
65
+ type AuthHookContext = Parameters<Parameters<typeof createAuthMiddleware>[0]>[0];
66
+ /**
67
+ * Registers a method to be executed before a specific auth route is processed.
68
+ * @param path - The auth route path that triggers this hook (must start with '/')
69
+ */
70
+ declare const BeforeHook: (path?: `/${string}`) => CustomDecorator<symbol>;
71
+ /**
72
+ * Registers a method to be executed after a specific auth route is processed.
73
+ * @param path - The auth route path that triggers this hook (must start with '/')
74
+ */
75
+ declare const AfterHook: (path?: `/${string}`) => CustomDecorator<symbol>;
76
+ /**
77
+ * Class decorator that marks a provider as containing hook methods.
78
+ * Must be applied to classes that use BeforeHook or AfterHook decorators.
79
+ */
80
+ declare const Hook: () => ClassDecorator;
81
+
82
+ type Auth = any;
83
+ /**
84
+ * NestJS module that integrates the Auth library with NestJS applications.
85
+ * Provides authentication middleware, hooks, and exception handling.
86
+ */
87
+ declare class AuthModule extends ConfigurableModuleClass implements NestModule, OnModuleInit {
88
+ private readonly applicationConfig;
89
+ private readonly discoveryService;
90
+ private readonly metadataScanner;
91
+ private readonly adapter;
92
+ private readonly options;
93
+ private readonly logger;
94
+ private readonly basePath;
95
+ constructor(applicationConfig: ApplicationConfig, discoveryService: DiscoveryService, metadataScanner: MetadataScanner, adapter: HttpAdapterHost, options: AuthModuleOptions);
96
+ onModuleInit(): void;
97
+ configure(consumer: MiddlewareConsumer): void;
98
+ private setupHooks;
99
+ static forRootAsync(options: typeof ASYNC_OPTIONS_TYPE): DynamicModule;
100
+ static forRoot(options: typeof OPTIONS_TYPE): DynamicModule;
101
+ /**
102
+ * @deprecated Use the object-based signature: AuthModule.forRoot({ auth, ...options })
103
+ */
104
+ static forRoot(auth: Auth, options?: Omit<typeof OPTIONS_TYPE, "auth">): DynamicModule;
105
+ }
106
+
107
+ type AuthModuleOptions<A = Auth> = {
108
+ auth: A;
109
+ disableTrustedOriginsCors?: boolean;
110
+ disableBodyParser?: boolean;
111
+ /**
112
+ * When set to `true`, enables raw body parsing and attaches it to `req.rawBody`.
113
+ *
114
+ * This is useful for webhook signature verification that requires the raw,
115
+ * unparsed request body.
116
+ *
117
+ * **Important:** Since this library disables NestJS's built-in body parser,
118
+ * NestJS's `rawBody: true` option in `NestFactory.create()` has no effect.
119
+ * Use this option instead.
120
+ *
121
+ * @default false
122
+ */
123
+ enableRawBodyParser?: boolean;
124
+ middleware?: (req: Request, res: Response, next: NextFunction) => void;
125
+ };
126
+ declare const ConfigurableModuleClass: _nestjs_common.ConfigurableModuleCls<AuthModuleOptions<any>, "forRoot", "create", {
127
+ isGlobal: boolean;
128
+ disableGlobalAuthGuard: boolean;
129
+ disableControllers: boolean;
130
+ }>;
131
+ declare const OPTIONS_TYPE: AuthModuleOptions<any> & Partial<{
132
+ isGlobal: boolean;
133
+ disableGlobalAuthGuard: boolean;
134
+ disableControllers: boolean;
135
+ }>;
136
+ declare const ASYNC_OPTIONS_TYPE: _nestjs_common.ConfigurableModuleAsyncOptions<AuthModuleOptions<any>, "create"> & Partial<{
137
+ isGlobal: boolean;
138
+ disableGlobalAuthGuard: boolean;
139
+ disableControllers: boolean;
140
+ }>;
141
+
142
+ /**
143
+ * NestJS service that provides access to the Better Auth instance
144
+ * Use generics to support auth instances extended by plugins
145
+ */
146
+ declare class AuthService<T extends {
147
+ api: T["api"];
148
+ } = Auth$1> {
149
+ private readonly options;
150
+ constructor(options: AuthModuleOptions<T>);
151
+ /**
152
+ * Returns the API endpoints provided by the auth instance
153
+ */
154
+ get api(): T["api"];
155
+ /**
156
+ * Returns the complete auth instance
157
+ * Access this for plugin-specific functionality
158
+ */
159
+ get instance(): T;
160
+ }
161
+
162
+ /**
163
+ * Type representing a valid user session after authentication
164
+ * Excludes null and undefined values from the session return type
165
+ */
166
+ type BaseUserSession = NonNullable<Awaited<ReturnType<ReturnType<typeof getSession>>>>;
167
+ type UserSession = BaseUserSession & {
168
+ user: BaseUserSession["user"] & {
169
+ role?: string | string[];
170
+ };
171
+ session: BaseUserSession["session"] & {
172
+ activeOrganizationId?: string;
173
+ };
174
+ };
175
+ /**
176
+ * NestJS guard that handles authentication for protected routes
177
+ * Can be configured with @AllowAnonymous() or @OptionalAuth() decorators to modify authentication behavior
178
+ */
179
+ declare class AuthGuard implements CanActivate {
180
+ private readonly reflector;
181
+ private readonly options;
182
+ constructor(reflector: Reflector, options: AuthModuleOptions);
183
+ /**
184
+ * Validates if the current request is authenticated
185
+ * Attaches session and user information to the request object
186
+ * Supports HTTP, GraphQL and WebSocket execution contexts
187
+ * @param context - The execution context of the current request
188
+ * @returns True if the request is authorized to proceed, throws an error otherwise
189
+ */
190
+ canActivate(context: ExecutionContext): Promise<boolean>;
191
+ /**
192
+ * Checks if a role value matches any of the required roles
193
+ * Handles both array and comma-separated string role formats
194
+ * @param role - The role value to check (string, array, or undefined)
195
+ * @param requiredRoles - Array of roles that grant access
196
+ * @returns True if the role matches any required role
197
+ */
198
+ private matchesRequiredRole;
199
+ /**
200
+ * Fetches the user's role within an organization from the member table
201
+ * Uses Better Auth's organization plugin API if available
202
+ * @param headers - The request headers containing session cookies
203
+ * @returns The member's role in the organization, or undefined if not found
204
+ */
205
+ private getMemberRoleInOrganization;
206
+ /**
207
+ * Checks if the user has any of the required roles in user.role only.
208
+ * Used by @Roles() decorator for system-level role checks (admin plugin).
209
+ * @param session - The user's session
210
+ * @param requiredRoles - Array of roles that grant access
211
+ * @returns True if user.role matches any required role
212
+ */
213
+ private checkUserRole;
214
+ /**
215
+ * Checks if the user has any of the required roles in their organization.
216
+ * Used by @OrgRoles() decorator for organization-level role checks.
217
+ * Requires an active organization in the session.
218
+ * @param session - The user's session
219
+ * @param headers - The request headers for API calls
220
+ * @param requiredRoles - Array of roles that grant access
221
+ * @returns True if org member role matches any required role
222
+ */
223
+ private checkOrgRole;
224
+ }
225
+
226
+ declare const BEFORE_HOOK_KEY: symbol;
227
+ declare const AFTER_HOOK_KEY: symbol;
228
+ declare const HOOK_KEY: symbol;
229
+ declare const AUTH_MODULE_OPTIONS_KEY: symbol;
230
+
231
+ export { AFTER_HOOK_KEY, AUTH_MODULE_OPTIONS_KEY, AfterHook, AllowAnonymous, AuthGuard, AuthModule, AuthService, BEFORE_HOOK_KEY, BeforeHook, HOOK_KEY, Hook, Optional, OptionalAuth, OrgRoles, Public, Roles, Session };
232
+ export type { Auth, AuthHookContext, BaseUserSession, UserSession };