@juspay/neurolink 9.31.2 → 9.32.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.
Files changed (161) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/auth/AuthProviderFactory.d.ts +71 -0
  3. package/dist/auth/AuthProviderFactory.js +111 -0
  4. package/dist/auth/AuthProviderRegistry.d.ts +33 -0
  5. package/dist/auth/AuthProviderRegistry.js +190 -0
  6. package/dist/auth/RequestContext.d.ts +23 -0
  7. package/dist/auth/RequestContext.js +78 -0
  8. package/dist/auth/authContext.d.ts +198 -0
  9. package/dist/auth/authContext.js +314 -0
  10. package/dist/auth/errors.d.ts +63 -0
  11. package/dist/auth/errors.js +39 -0
  12. package/dist/auth/index.d.ts +20 -8
  13. package/dist/auth/index.js +35 -7
  14. package/dist/auth/middleware/AuthMiddleware.d.ts +181 -0
  15. package/dist/auth/middleware/AuthMiddleware.js +519 -0
  16. package/dist/auth/middleware/rateLimitByUser.d.ts +282 -0
  17. package/dist/auth/middleware/rateLimitByUser.js +554 -0
  18. package/dist/auth/providers/BaseAuthProvider.d.ts +259 -0
  19. package/dist/auth/providers/BaseAuthProvider.js +723 -0
  20. package/dist/auth/providers/CognitoProvider.d.ts +61 -0
  21. package/dist/auth/providers/CognitoProvider.js +304 -0
  22. package/dist/auth/providers/KeycloakProvider.d.ts +61 -0
  23. package/dist/auth/providers/KeycloakProvider.js +393 -0
  24. package/dist/auth/providers/auth0.d.ts +59 -0
  25. package/dist/auth/providers/auth0.js +274 -0
  26. package/dist/auth/providers/betterAuth.d.ts +51 -0
  27. package/dist/auth/providers/betterAuth.js +182 -0
  28. package/dist/auth/providers/clerk.d.ts +65 -0
  29. package/dist/auth/providers/clerk.js +317 -0
  30. package/dist/auth/providers/custom.d.ts +64 -0
  31. package/dist/auth/providers/custom.js +112 -0
  32. package/dist/auth/providers/firebase.d.ts +63 -0
  33. package/dist/auth/providers/firebase.js +226 -0
  34. package/dist/auth/providers/jwt.d.ts +68 -0
  35. package/dist/auth/providers/jwt.js +212 -0
  36. package/dist/auth/providers/oauth2.d.ts +73 -0
  37. package/dist/auth/providers/oauth2.js +303 -0
  38. package/dist/auth/providers/supabase.d.ts +63 -0
  39. package/dist/auth/providers/supabase.js +259 -0
  40. package/dist/auth/providers/workos.d.ts +61 -0
  41. package/dist/auth/providers/workos.js +284 -0
  42. package/dist/auth/serverBridge.d.ts +14 -0
  43. package/dist/auth/serverBridge.js +25 -0
  44. package/dist/auth/sessionManager.d.ts +142 -0
  45. package/dist/auth/sessionManager.js +437 -0
  46. package/dist/cli/commands/authProviders.d.ts +43 -0
  47. package/dist/cli/commands/authProviders.js +399 -0
  48. package/dist/cli/factories/authCommandFactory.d.ts +23 -5
  49. package/dist/cli/factories/authCommandFactory.js +108 -5
  50. package/dist/cli/parser.js +1 -1
  51. package/dist/client/auth/AuthProviderFactory.js +111 -0
  52. package/dist/client/auth/AuthProviderRegistry.js +190 -0
  53. package/dist/client/auth/RequestContext.js +78 -0
  54. package/dist/client/auth/accountPool.js +178 -0
  55. package/dist/client/auth/authContext.js +314 -0
  56. package/dist/client/auth/errors.js +39 -0
  57. package/dist/client/auth/index.js +61 -0
  58. package/dist/client/auth/middleware/AuthMiddleware.js +519 -0
  59. package/dist/client/auth/middleware/rateLimitByUser.js +554 -0
  60. package/dist/client/auth/providers/BaseAuthProvider.js +723 -0
  61. package/dist/client/auth/providers/CognitoProvider.js +304 -0
  62. package/dist/client/auth/providers/KeycloakProvider.js +393 -0
  63. package/dist/client/auth/providers/auth0.js +274 -0
  64. package/dist/client/auth/providers/betterAuth.js +182 -0
  65. package/dist/client/auth/providers/clerk.js +317 -0
  66. package/dist/client/auth/providers/custom.js +112 -0
  67. package/dist/client/auth/providers/firebase.js +226 -0
  68. package/dist/client/auth/providers/jwt.js +212 -0
  69. package/dist/client/auth/providers/oauth2.js +303 -0
  70. package/dist/client/auth/providers/supabase.js +259 -0
  71. package/dist/client/auth/providers/workos.js +284 -0
  72. package/dist/client/auth/serverBridge.js +25 -0
  73. package/dist/client/auth/sessionManager.js +437 -0
  74. package/dist/client/core/infrastructure/baseRegistry.js +5 -1
  75. package/dist/client/index.js +25 -0
  76. package/dist/client/mcp/toolRegistry.js +11 -1
  77. package/dist/client/neurolink.js +218 -0
  78. package/dist/client/rag/ChunkerRegistry.js +2 -2
  79. package/dist/client/rag/metadata/MetadataExtractorRegistry.js +2 -2
  80. package/dist/client/rag/reranker/RerankerRegistry.js +2 -2
  81. package/dist/client/server/routes/agentRoutes.js +20 -2
  82. package/dist/client/types/authTypes.js +2 -1
  83. package/dist/core/infrastructure/baseRegistry.d.ts +3 -1
  84. package/dist/core/infrastructure/baseRegistry.js +5 -1
  85. package/dist/index.d.ts +1 -0
  86. package/dist/index.js +25 -0
  87. package/dist/lib/auth/AuthProviderFactory.d.ts +71 -0
  88. package/dist/lib/auth/AuthProviderFactory.js +112 -0
  89. package/dist/lib/auth/AuthProviderRegistry.d.ts +33 -0
  90. package/dist/lib/auth/AuthProviderRegistry.js +191 -0
  91. package/dist/lib/auth/RequestContext.d.ts +23 -0
  92. package/dist/lib/auth/RequestContext.js +79 -0
  93. package/dist/lib/auth/authContext.d.ts +198 -0
  94. package/dist/lib/auth/authContext.js +315 -0
  95. package/dist/lib/auth/errors.d.ts +63 -0
  96. package/dist/lib/auth/errors.js +40 -0
  97. package/dist/lib/auth/index.d.ts +20 -8
  98. package/dist/lib/auth/index.js +35 -7
  99. package/dist/lib/auth/middleware/AuthMiddleware.d.ts +181 -0
  100. package/dist/lib/auth/middleware/AuthMiddleware.js +520 -0
  101. package/dist/lib/auth/middleware/rateLimitByUser.d.ts +282 -0
  102. package/dist/lib/auth/middleware/rateLimitByUser.js +555 -0
  103. package/dist/lib/auth/providers/BaseAuthProvider.d.ts +259 -0
  104. package/dist/lib/auth/providers/BaseAuthProvider.js +724 -0
  105. package/dist/lib/auth/providers/CognitoProvider.d.ts +61 -0
  106. package/dist/lib/auth/providers/CognitoProvider.js +305 -0
  107. package/dist/lib/auth/providers/KeycloakProvider.d.ts +61 -0
  108. package/dist/lib/auth/providers/KeycloakProvider.js +394 -0
  109. package/dist/lib/auth/providers/auth0.d.ts +59 -0
  110. package/dist/lib/auth/providers/auth0.js +275 -0
  111. package/dist/lib/auth/providers/betterAuth.d.ts +51 -0
  112. package/dist/lib/auth/providers/betterAuth.js +183 -0
  113. package/dist/lib/auth/providers/clerk.d.ts +65 -0
  114. package/dist/lib/auth/providers/clerk.js +318 -0
  115. package/dist/lib/auth/providers/custom.d.ts +64 -0
  116. package/dist/lib/auth/providers/custom.js +113 -0
  117. package/dist/lib/auth/providers/firebase.d.ts +63 -0
  118. package/dist/lib/auth/providers/firebase.js +227 -0
  119. package/dist/lib/auth/providers/jwt.d.ts +68 -0
  120. package/dist/lib/auth/providers/jwt.js +213 -0
  121. package/dist/lib/auth/providers/oauth2.d.ts +73 -0
  122. package/dist/lib/auth/providers/oauth2.js +304 -0
  123. package/dist/lib/auth/providers/supabase.d.ts +63 -0
  124. package/dist/lib/auth/providers/supabase.js +260 -0
  125. package/dist/lib/auth/providers/workos.d.ts +61 -0
  126. package/dist/lib/auth/providers/workos.js +285 -0
  127. package/dist/lib/auth/serverBridge.d.ts +14 -0
  128. package/dist/lib/auth/serverBridge.js +26 -0
  129. package/dist/lib/auth/sessionManager.d.ts +142 -0
  130. package/dist/lib/auth/sessionManager.js +438 -0
  131. package/dist/lib/core/infrastructure/baseRegistry.d.ts +3 -1
  132. package/dist/lib/core/infrastructure/baseRegistry.js +5 -1
  133. package/dist/lib/index.d.ts +1 -0
  134. package/dist/lib/index.js +25 -0
  135. package/dist/lib/mcp/toolRegistry.js +11 -1
  136. package/dist/lib/neurolink.d.ts +42 -1
  137. package/dist/lib/neurolink.js +218 -0
  138. package/dist/lib/rag/ChunkerRegistry.js +2 -2
  139. package/dist/lib/rag/metadata/MetadataExtractorRegistry.js +2 -2
  140. package/dist/lib/rag/reranker/RerankerRegistry.js +2 -2
  141. package/dist/lib/server/routes/agentRoutes.js +20 -2
  142. package/dist/lib/types/authTypes.d.ts +937 -1
  143. package/dist/lib/types/authTypes.js +2 -1
  144. package/dist/lib/types/configTypes.d.ts +46 -0
  145. package/dist/lib/types/generateTypes.d.ts +6 -0
  146. package/dist/lib/types/index.d.ts +1 -0
  147. package/dist/lib/types/streamTypes.d.ts +6 -0
  148. package/dist/mcp/toolRegistry.js +11 -1
  149. package/dist/neurolink.d.ts +42 -1
  150. package/dist/neurolink.js +218 -0
  151. package/dist/rag/ChunkerRegistry.js +2 -2
  152. package/dist/rag/metadata/MetadataExtractorRegistry.js +2 -2
  153. package/dist/rag/reranker/RerankerRegistry.js +2 -2
  154. package/dist/server/routes/agentRoutes.js +20 -2
  155. package/dist/types/authTypes.d.ts +937 -1
  156. package/dist/types/authTypes.js +2 -1
  157. package/dist/types/configTypes.d.ts +46 -0
  158. package/dist/types/generateTypes.d.ts +6 -0
  159. package/dist/types/index.d.ts +1 -0
  160. package/dist/types/streamTypes.d.ts +6 -0
  161. package/package.json +2 -1
@@ -1,10 +1,13 @@
1
1
  /**
2
2
  * Auth-related type definitions for NeuroLink
3
3
  *
4
- * Canonical location for OAuth token storage types and token refresher contracts.
4
+ * Canonical location for OAuth token storage types, token refresher contracts,
5
+ * and multi-provider authentication types.
5
6
  * All auth type imports should reference this module (or the barrel re-export
6
7
  * via src/lib/types/index.ts).
7
8
  */
9
+ import type { JsonValue } from "./common.js";
10
+ import type { UnknownRecord } from "./common.js";
8
11
  /**
9
12
  * OAuth tokens structure for storage.
10
13
  * Stricter version of OAuthTokens with required fields for persistent storage.
@@ -54,3 +57,936 @@ export type StoredProviderTokens = {
54
57
  /** Reason the tokens were disabled (e.g., "refresh_failed") */
55
58
  disabledReason?: string;
56
59
  };
60
+ /**
61
+ * Supported authentication provider types
62
+ */
63
+ export type AuthProviderType = "auth0" | "clerk" | "firebase" | "supabase" | "cognito" | "keycloak" | "workos" | "better-auth" | "oauth2" | "jwt" | "custom";
64
+ /**
65
+ * Authentication token types
66
+ */
67
+ export type TokenType = "jwt" | "session" | "api-key" | "oauth";
68
+ /**
69
+ * User information from authentication
70
+ */
71
+ export type AuthUser = {
72
+ /** Unique user identifier */
73
+ id: string;
74
+ /** User's email address */
75
+ email?: string;
76
+ /** User's display name */
77
+ name?: string;
78
+ /** Profile picture URL */
79
+ picture?: string;
80
+ /** User's roles */
81
+ roles: string[];
82
+ /** User's permissions */
83
+ permissions: string[];
84
+ /** Provider-specific user data */
85
+ providerData?: Record<string, JsonValue>;
86
+ /** Provider-specific metadata */
87
+ metadata?: UnknownRecord;
88
+ /** Organization/tenant ID for multi-tenant apps */
89
+ organizationId?: string;
90
+ /** Email verification status */
91
+ emailVerified?: boolean;
92
+ /** Account creation timestamp */
93
+ createdAt?: Date;
94
+ /** Last update timestamp */
95
+ updatedAt?: Date;
96
+ /** Last login timestamp */
97
+ lastLoginAt?: Date;
98
+ };
99
+ /**
100
+ * Session information
101
+ */
102
+ export type AuthSession = {
103
+ /** Session identifier */
104
+ id: string;
105
+ /** Associated user */
106
+ user: AuthUser;
107
+ /** Session access token */
108
+ accessToken?: string;
109
+ /** Session refresh token */
110
+ refreshToken?: string;
111
+ /** Session creation time */
112
+ createdAt: Date;
113
+ /** Session expiration time */
114
+ expiresAt: Date;
115
+ /** Whether session is still valid */
116
+ isValid: boolean;
117
+ /** Last activity timestamp */
118
+ lastActivityAt?: Date;
119
+ /** IP address of session origin */
120
+ ipAddress?: string;
121
+ /** User agent string */
122
+ userAgent?: string;
123
+ /** Device fingerprint */
124
+ deviceId?: string;
125
+ /** Session metadata */
126
+ metadata?: UnknownRecord;
127
+ };
128
+ /**
129
+ * Token validation result
130
+ */
131
+ export type TokenValidationResult = {
132
+ /** Whether the token is valid */
133
+ valid: boolean;
134
+ /** Decoded token payload */
135
+ payload?: UnknownRecord;
136
+ /** Associated user if token is valid */
137
+ user?: AuthUser;
138
+ /** Decoded token claims */
139
+ claims?: Record<string, JsonValue>;
140
+ /** Error message if invalid */
141
+ error?: string;
142
+ /** Error code for programmatic handling */
143
+ errorCode?: AuthErrorCode;
144
+ /** Token expiration time */
145
+ expiresAt?: Date;
146
+ /** Token type */
147
+ tokenType?: TokenType;
148
+ /** Token issuer */
149
+ issuer?: string;
150
+ /** Token audience */
151
+ audience?: string | string[];
152
+ };
153
+ /**
154
+ * Token claims extracted from JWT
155
+ */
156
+ export type TokenClaims = {
157
+ /** Subject (user ID) */
158
+ sub?: string;
159
+ /** Issuer */
160
+ iss?: string;
161
+ /** Audience */
162
+ aud?: string | string[];
163
+ /** Expiration time */
164
+ exp?: number;
165
+ /** Issued at */
166
+ iat?: number;
167
+ /** Not before */
168
+ nbf?: number;
169
+ /** JWT ID */
170
+ jti?: string;
171
+ /** Email */
172
+ email?: string;
173
+ /** Email verified */
174
+ email_verified?: boolean;
175
+ /** Name */
176
+ name?: string;
177
+ /** Picture */
178
+ picture?: string;
179
+ /** Custom claims */
180
+ [key: string]: JsonValue | undefined;
181
+ };
182
+ /**
183
+ * JWKS (JSON Web Key Set) types
184
+ */
185
+ export type JWK = {
186
+ kty: string;
187
+ kid?: string;
188
+ use?: string;
189
+ alg?: string;
190
+ n?: string;
191
+ e?: string;
192
+ x?: string;
193
+ y?: string;
194
+ crv?: string;
195
+ };
196
+ export type JWKS = {
197
+ keys: JWK[];
198
+ };
199
+ /**
200
+ * Token refresh result
201
+ */
202
+ export type TokenRefreshResult = {
203
+ /** New access token */
204
+ accessToken: string;
205
+ /** New refresh token (if rotated) */
206
+ refreshToken?: string;
207
+ /** Token expiration in seconds */
208
+ expiresIn: number;
209
+ };
210
+ /**
211
+ * Session validation result
212
+ */
213
+ export type SessionValidationResult = {
214
+ /** Whether the session is valid */
215
+ valid: boolean;
216
+ /** Validated session if valid */
217
+ session?: AuthSession;
218
+ /** Error message if validation failed */
219
+ error?: string;
220
+ /** Error code for programmatic handling */
221
+ errorCode?: AuthErrorCode;
222
+ /** Whether session was refreshed */
223
+ refreshed?: boolean;
224
+ };
225
+ /**
226
+ * Session storage interface
227
+ */
228
+ export type SessionStorage = {
229
+ /** Get a session by ID */
230
+ get(sessionId: string): Promise<AuthSession | null>;
231
+ /** Save a session */
232
+ save(session: AuthSession): Promise<void>;
233
+ /** Delete a session */
234
+ delete(sessionId: string): Promise<void>;
235
+ /** Delete all sessions for a user */
236
+ deleteAllForUser(userId: string): Promise<void>;
237
+ /** Get all sessions for a user */
238
+ getForUser(userId: string): Promise<AuthSession[]>;
239
+ /** Check if a session exists */
240
+ exists(sessionId: string): Promise<boolean>;
241
+ /** Update session last activity */
242
+ touch(sessionId: string): Promise<void>;
243
+ /** Clear all sessions */
244
+ clear(): Promise<void>;
245
+ };
246
+ /**
247
+ * Authorization check result
248
+ */
249
+ export type AuthorizationResult = {
250
+ /** Whether the user is authorized */
251
+ authorized: boolean;
252
+ /** User being authorized */
253
+ user?: AuthUser;
254
+ /** Required roles that were checked */
255
+ requiredRoles?: string[];
256
+ /** Required permissions that were checked */
257
+ requiredPermissions?: string[];
258
+ /** Reason for denial if not authorized */
259
+ reason?: string;
260
+ /** Missing permissions if denied */
261
+ missingPermissions?: string[];
262
+ /** Missing roles if denied */
263
+ missingRoles?: string[];
264
+ };
265
+ /**
266
+ * Authentication request context
267
+ */
268
+ export type AuthRequestContext = {
269
+ /** HTTP method */
270
+ method?: string;
271
+ /** Request URL/path */
272
+ path?: string;
273
+ /** HTTP request headers */
274
+ headers: Record<string, string | string[] | undefined>;
275
+ /** Request cookies */
276
+ cookies?: Record<string, string>;
277
+ /** Query parameters */
278
+ query?: Record<string, string | string[] | undefined>;
279
+ /** Request body (if available) */
280
+ body?: unknown;
281
+ /** IP address */
282
+ ip?: string;
283
+ /** IP address (alias for session builders that expect this field) */
284
+ ipAddress?: string;
285
+ /** Request user agent */
286
+ userAgent?: string;
287
+ /** Request ID for tracing */
288
+ requestId?: string;
289
+ };
290
+ /**
291
+ * Enhanced request context with authenticated user.
292
+ *
293
+ * Extends AuthRequestContext so it can be passed wherever a plain
294
+ * request context is expected (e.g. RBAC middleware callbacks).
295
+ */
296
+ export type AuthenticatedContext = AuthRequestContext & {
297
+ /** Authenticated user */
298
+ user: AuthUser;
299
+ /** Current session */
300
+ session?: AuthSession;
301
+ /** Original request context (for callers that embed it explicitly) */
302
+ request?: AuthRequestContext;
303
+ /** Authentication timestamp */
304
+ authenticatedAt?: Date;
305
+ /** Provider that performed authentication */
306
+ provider?: AuthProviderType;
307
+ /** Token used for authentication */
308
+ token?: string;
309
+ /** Token claims */
310
+ claims?: Record<string, JsonValue>;
311
+ };
312
+ /**
313
+ * Base authentication provider configuration.
314
+ *
315
+ * Contains the common fields shared by every provider-specific config variant.
316
+ * Provider-specific fields are added via intersection in {@link AuthProviderConfig}.
317
+ */
318
+ export type BaseAuthProviderConfig = {
319
+ /** Provider type */
320
+ type: AuthProviderType;
321
+ /** Whether authentication is required */
322
+ required?: boolean;
323
+ /** Enable debug logging */
324
+ debug?: boolean;
325
+ /** Custom token validation options */
326
+ tokenValidation?: TokenValidationConfig;
327
+ /** Token extraction strategy */
328
+ tokenExtraction?: TokenExtractionStrategy;
329
+ /** Session configuration */
330
+ session?: SessionConfig;
331
+ /** RBAC configuration */
332
+ rbac?: RBACConfig;
333
+ /** Cache configuration */
334
+ cache?: AuthCacheConfig;
335
+ /** Provider-specific options (generic extensibility point) */
336
+ options?: UnknownRecord;
337
+ };
338
+ /**
339
+ * Token validation configuration
340
+ */
341
+ export type TokenValidationConfig = {
342
+ /** Token issuer to validate against */
343
+ issuer?: string;
344
+ /** Token audience to validate against */
345
+ audience?: string | string[];
346
+ /** Clock tolerance in seconds for expiration checks */
347
+ clockTolerance?: number;
348
+ /** Custom claims to extract */
349
+ extractClaims?: string[];
350
+ /** Whether to validate token signature */
351
+ validateSignature?: boolean;
352
+ /** JWKS endpoint for signature verification */
353
+ jwksUri?: string;
354
+ /** Cache JWKS for this duration (ms) */
355
+ jwksCacheDuration?: number;
356
+ };
357
+ /**
358
+ * Auth cache configuration
359
+ */
360
+ export type AuthCacheConfig = {
361
+ /** Enable caching */
362
+ enabled?: boolean;
363
+ /** Cache TTL in seconds */
364
+ ttl?: number;
365
+ /** Maximum cache entries */
366
+ maxEntries?: number;
367
+ /** Cache key prefix */
368
+ prefix?: string;
369
+ };
370
+ /**
371
+ * Token extraction configuration (detailed, used by middleware)
372
+ */
373
+ export type TokenExtractionConfig = {
374
+ /** Extract from Authorization header (Bearer token) */
375
+ fromHeader?: {
376
+ name?: string;
377
+ prefix?: string;
378
+ };
379
+ /** Extract from cookie */
380
+ fromCookie?: {
381
+ name: string;
382
+ };
383
+ /** Extract from query parameter */
384
+ fromQuery?: {
385
+ name: string;
386
+ };
387
+ /** Custom extraction function */
388
+ custom?: (context: AuthRequestContext) => string | null | Promise<string | null>;
389
+ };
390
+ /**
391
+ * Token extraction configuration (simple strategy)
392
+ */
393
+ export type TokenExtractionStrategy = {
394
+ /** Extract from Authorization header */
395
+ fromHeader?: {
396
+ name: string;
397
+ scheme?: string;
398
+ };
399
+ /** Extract from cookie */
400
+ fromCookie?: {
401
+ name: string;
402
+ };
403
+ /** Extract from query parameter */
404
+ fromQuery?: {
405
+ name: string;
406
+ };
407
+ /** Custom extraction function (may be sync or async) */
408
+ custom?: (context: AuthRequestContext) => string | null | Promise<string | null>;
409
+ };
410
+ /**
411
+ * Session configuration
412
+ */
413
+ export type SessionConfig = {
414
+ /** Session storage type */
415
+ storage?: SessionStorageType;
416
+ /** Session duration in seconds */
417
+ duration?: number;
418
+ /** Auto-refresh sessions before expiration */
419
+ autoRefresh?: boolean;
420
+ /** Refresh threshold in seconds (refresh when this much time remains) */
421
+ refreshThreshold?: number;
422
+ /** Allow multiple sessions per user */
423
+ allowMultipleSessions?: boolean;
424
+ /** Maximum sessions per user */
425
+ maxSessionsPerUser?: number;
426
+ /** Session identifier prefix */
427
+ prefix?: string;
428
+ /** Custom session storage implementation */
429
+ customStorage?: SessionStorage;
430
+ /** Redis configuration for distributed sessions */
431
+ redis?: {
432
+ url: string;
433
+ prefix?: string;
434
+ ttl?: number;
435
+ };
436
+ };
437
+ /**
438
+ * Session storage types
439
+ */
440
+ export type SessionStorageType = "memory" | "redis" | "custom";
441
+ /**
442
+ * Role-Based Access Control configuration
443
+ */
444
+ export type RBACConfig = {
445
+ /** Enable RBAC */
446
+ enabled?: boolean;
447
+ /** Default roles for new users */
448
+ defaultRoles?: string[];
449
+ /** Role hierarchy (higher roles inherit lower role permissions) */
450
+ roleHierarchy?: Record<string, string[]>;
451
+ /** Permission definitions per role */
452
+ rolePermissions?: Record<string, string[]>;
453
+ /** Permission definitions */
454
+ permissions?: PermissionDefinition[];
455
+ /** Default permissions for authenticated users */
456
+ defaultPermissions?: string[];
457
+ /** Super admin roles (bypass all checks) */
458
+ superAdminRoles?: string[];
459
+ };
460
+ /**
461
+ * Permission definition
462
+ */
463
+ export type PermissionDefinition = {
464
+ /** Permission identifier */
465
+ id: string;
466
+ /** Human-readable name */
467
+ name: string;
468
+ /** Description */
469
+ description?: string;
470
+ /** Required roles for this permission */
471
+ requiredRoles?: string[];
472
+ };
473
+ /**
474
+ * Auth middleware options
475
+ */
476
+ export type AuthMiddlewareOptions = {
477
+ /** Auth provider instance */
478
+ provider: MastraAuthProvider;
479
+ /** Routes to exclude from authentication */
480
+ excludePaths?: string[];
481
+ /** Whether auth is optional (continue if no token) */
482
+ optional?: boolean;
483
+ /** Custom unauthorized handler */
484
+ onUnauthorized?: (context: AuthRequestContext) => Response | Promise<Response>;
485
+ /** Custom error handler */
486
+ onError?: (error: Error, context: AuthRequestContext) => Response | Promise<Response>;
487
+ };
488
+ /**
489
+ * Auth middleware configuration
490
+ */
491
+ export type AuthMiddlewareConfig = {
492
+ /** Auth provider to use */
493
+ provider: AuthProviderType;
494
+ /** Provider configuration */
495
+ providerConfig: AuthProviderConfig;
496
+ /** Token extraction configuration */
497
+ tokenExtraction?: TokenExtractionConfig;
498
+ /** Routes that don't require authentication */
499
+ publicRoutes?: string[];
500
+ /** Whether authentication is optional (request proceeds with or without auth) */
501
+ optional?: boolean;
502
+ /** Custom error handler */
503
+ onError?: (error: AuthErrorInfo, context: AuthRequestContext) => void | Promise<void>;
504
+ /** Hook called after successful authentication */
505
+ onAuthenticated?: (context: AuthenticatedContext) => void | Promise<void>;
506
+ };
507
+ /**
508
+ * RBAC middleware configuration
509
+ */
510
+ export type RBACMiddlewareConfig = {
511
+ /** Required roles (user must have at least one) */
512
+ roles?: string[];
513
+ /** Required permissions (user must have all) */
514
+ permissions?: string[];
515
+ /** Whether all roles are required (default: false, any role matches) */
516
+ requireAllRoles?: boolean;
517
+ /** Super admin roles that bypass all role/permission checks */
518
+ superAdminRoles?: string[];
519
+ /** Mapping from role name to granted permissions */
520
+ rolePermissions?: Record<string, string[]>;
521
+ /** Role hierarchy: a role inherits permissions from its children */
522
+ roleHierarchy?: Record<string, string[]>;
523
+ /** Custom authorization function */
524
+ custom?: (user: AuthUser, context: AuthRequestContext) => boolean | Promise<boolean>;
525
+ /** Custom error handler */
526
+ onDenied?: (result: AuthorizationResult, context: AuthRequestContext) => void | Promise<void>;
527
+ };
528
+ /**
529
+ * Auth0 provider configuration
530
+ */
531
+ export type Auth0Config = {
532
+ /** Auth0 domain (e.g., 'your-tenant.auth0.com') */
533
+ domain: string;
534
+ /** Auth0 client ID */
535
+ clientId: string;
536
+ /** Auth0 client secret (for backend operations) */
537
+ clientSecret?: string;
538
+ /** Auth0 audience (API identifier) */
539
+ audience?: string;
540
+ /** Auth0 scope */
541
+ scope?: string;
542
+ /** Custom namespace for claims */
543
+ claimsNamespace?: string;
544
+ /** Management API configuration */
545
+ managementApi?: {
546
+ clientId: string;
547
+ clientSecret: string;
548
+ };
549
+ };
550
+ /**
551
+ * Clerk provider configuration
552
+ */
553
+ export type ClerkConfig = {
554
+ /** Clerk publishable key */
555
+ publishableKey?: string;
556
+ /** Clerk secret key */
557
+ secretKey: string;
558
+ /** Clerk JWT key (for local validation) */
559
+ jwtKey?: string;
560
+ /** Clerk API version */
561
+ apiVersion?: string;
562
+ /** JWKS endpoint override */
563
+ jwksUrl?: string;
564
+ /** Allowed origins */
565
+ allowedOrigins?: string[];
566
+ };
567
+ /**
568
+ * Firebase provider configuration
569
+ */
570
+ export type FirebaseConfig = {
571
+ /** Firebase project ID */
572
+ projectId: string;
573
+ /** Firebase API key */
574
+ apiKey?: string;
575
+ /** Service account credentials */
576
+ serviceAccount?: {
577
+ clientEmail: string;
578
+ privateKey: string;
579
+ };
580
+ /** Firebase database URL */
581
+ databaseURL?: string;
582
+ /** Custom claims key for roles */
583
+ rolesClaimKey?: string;
584
+ /** Custom claims key for permissions */
585
+ permissionsClaimKey?: string;
586
+ };
587
+ /**
588
+ * Supabase provider configuration
589
+ */
590
+ export type SupabaseConfig = {
591
+ /** Supabase project URL */
592
+ url: string;
593
+ /** Supabase anon key */
594
+ anonKey: string;
595
+ /** Supabase service role key (for backend operations) */
596
+ serviceRoleKey?: string;
597
+ /** JWT secret for custom token verification */
598
+ jwtSecret?: string;
599
+ };
600
+ /**
601
+ * AWS Cognito provider configuration
602
+ */
603
+ export type CognitoConfig = {
604
+ /** Cognito user pool ID */
605
+ userPoolId: string;
606
+ /** Cognito client ID */
607
+ clientId: string;
608
+ /** Cognito client secret */
609
+ clientSecret?: string;
610
+ /** AWS region */
611
+ region: string;
612
+ /** Custom attributes to extract as claims */
613
+ customAttributes?: string[];
614
+ };
615
+ /**
616
+ * Keycloak provider configuration
617
+ */
618
+ export type KeycloakConfig = {
619
+ /** Keycloak server URL */
620
+ serverUrl: string;
621
+ /** Keycloak realm */
622
+ realm: string;
623
+ /** Client ID */
624
+ clientId: string;
625
+ /** Client secret */
626
+ clientSecret?: string;
627
+ /** Verify token signature */
628
+ verifyToken?: boolean;
629
+ };
630
+ /**
631
+ * Generic OAuth2 provider configuration
632
+ */
633
+ export type OAuth2Config = {
634
+ /** Authorization endpoint URL */
635
+ authorizationUrl: string;
636
+ /** Token endpoint URL */
637
+ tokenUrl: string;
638
+ /** User info endpoint URL */
639
+ userInfoUrl?: string;
640
+ /** JWKS endpoint URL */
641
+ jwksUrl?: string;
642
+ /** Client ID */
643
+ clientId: string;
644
+ /** Client secret */
645
+ clientSecret?: string;
646
+ /** OAuth scopes */
647
+ scopes?: string[];
648
+ /** Redirect URL */
649
+ redirectUrl?: string;
650
+ /** Enable PKCE */
651
+ usePKCE?: boolean;
652
+ };
653
+ /**
654
+ * JWT provider configuration
655
+ */
656
+ export type JWTConfig = {
657
+ /** JWT secret for HMAC algorithms */
658
+ secret?: string;
659
+ /** Public key for RSA/EC algorithms */
660
+ publicKey?: string;
661
+ /** Supported algorithms */
662
+ algorithms?: string[];
663
+ /** Token issuer */
664
+ issuer?: string;
665
+ /** Token audience */
666
+ audience?: string | string[];
667
+ };
668
+ /**
669
+ * Better Auth provider configuration
670
+ */
671
+ export type BetterAuthConfig = {
672
+ /** Better Auth secret */
673
+ secret: string;
674
+ /** Better Auth base URL */
675
+ baseUrl: string;
676
+ /** Database connection string */
677
+ databaseUrl?: string;
678
+ /** Social providers configuration */
679
+ socialProviders?: {
680
+ github?: {
681
+ clientId: string;
682
+ clientSecret: string;
683
+ };
684
+ google?: {
685
+ clientId: string;
686
+ clientSecret: string;
687
+ };
688
+ discord?: {
689
+ clientId: string;
690
+ clientSecret: string;
691
+ };
692
+ };
693
+ };
694
+ /**
695
+ * WorkOS provider configuration
696
+ */
697
+ export type WorkOSConfig = {
698
+ /** WorkOS API key */
699
+ apiKey: string;
700
+ /** WorkOS client ID */
701
+ clientId: string;
702
+ /** Organization ID (optional for multi-tenant) */
703
+ organizationId?: string;
704
+ };
705
+ /**
706
+ * Custom auth provider configuration
707
+ */
708
+ export type CustomAuthConfig = {
709
+ /** Custom token validation function */
710
+ validateToken: (token: string, context?: AuthRequestContext) => Promise<TokenValidationResult>;
711
+ /** Custom user fetching function */
712
+ getUser?: (userId: string) => Promise<AuthUser | null>;
713
+ /** Custom session creation function */
714
+ createSession?: (user: AuthUser, context?: AuthRequestContext) => Promise<AuthSession>;
715
+ };
716
+ /**
717
+ * Configuration for MastraAuthProvider.
718
+ *
719
+ * Discriminated union of base + each provider-specific config so that
720
+ * provider factories receive the properly typed config without requiring
721
+ * `as any` casts or an open index signature.
722
+ *
723
+ * The `type` discriminant narrows to the correct provider-specific fields.
724
+ * The final `BaseAuthProviderConfig` branch serves as a generic fallback
725
+ * for code that only needs the common fields.
726
+ */
727
+ export type AuthProviderConfig = (BaseAuthProviderConfig & Auth0Config & {
728
+ type: "auth0";
729
+ }) | (BaseAuthProviderConfig & ClerkConfig & {
730
+ type: "clerk";
731
+ }) | (BaseAuthProviderConfig & FirebaseConfig & {
732
+ type: "firebase";
733
+ }) | (BaseAuthProviderConfig & SupabaseConfig & {
734
+ type: "supabase";
735
+ }) | (BaseAuthProviderConfig & CognitoConfig & {
736
+ type: "cognito";
737
+ }) | (BaseAuthProviderConfig & KeycloakConfig & {
738
+ type: "keycloak";
739
+ }) | (BaseAuthProviderConfig & OAuth2Config & {
740
+ type: "oauth2";
741
+ }) | (BaseAuthProviderConfig & JWTConfig & {
742
+ type: "jwt";
743
+ }) | (BaseAuthProviderConfig & BetterAuthConfig & {
744
+ type: "better-auth";
745
+ }) | (BaseAuthProviderConfig & WorkOSConfig & {
746
+ type: "workos";
747
+ }) | (BaseAuthProviderConfig & CustomAuthConfig & {
748
+ type: "custom";
749
+ }) | BaseAuthProviderConfig;
750
+ /**
751
+ * Auth error codes
752
+ */
753
+ export type AuthErrorCode = "AUTH-001" | "AUTH-002" | "AUTH-003" | "AUTH-004" | "AUTH-005" | "AUTH-006" | "AUTH-007" | "AUTH-008" | "AUTH-009" | "AUTH-010" | "AUTH-011" | "AUTH-012" | "AUTH-013" | "AUTH-014" | "AUTH-015" | "AUTH-016" | "AUTH-017" | "AUTH-018" | "AUTH-019" | "AUTH-020";
754
+ /**
755
+ * Auth error information with additional context.
756
+ *
757
+ * Renamed from `AuthError` to `AuthErrorInfo` to avoid collision with the
758
+ * `createErrorFactory` result that is named `AuthError` in errors.ts.
759
+ */
760
+ export type AuthErrorInfo = Error & {
761
+ /** Error code */
762
+ code: AuthErrorCode;
763
+ /** Provider that threw the error */
764
+ provider?: AuthProviderType;
765
+ /** HTTP status code */
766
+ statusCode?: number;
767
+ /** Whether the error is retryable */
768
+ retryable?: boolean;
769
+ /** Additional error context */
770
+ context?: Record<string, JsonValue>;
771
+ /** Original error if wrapped */
772
+ cause?: Error;
773
+ };
774
+ /**
775
+ * Auth events for EventEmitter
776
+ */
777
+ export type AuthEvents = {
778
+ "auth:login": (user: AuthUser) => void;
779
+ "auth:logout": (userId: string) => void;
780
+ "auth:tokenRefresh": (session: AuthSession) => void;
781
+ "auth:unauthorized": (context: AuthRequestContext, reason: string) => void;
782
+ "auth:error": (error: Error, context?: AuthRequestContext) => void;
783
+ };
784
+ /**
785
+ * Auth event types for hooks
786
+ */
787
+ export type AuthEventType = "token:validated" | "token:expired" | "token:invalid" | "session:created" | "session:refreshed" | "session:expired" | "session:revoked" | "auth:success" | "auth:failed" | "rbac:allowed" | "rbac:denied";
788
+ /**
789
+ * Auth event data
790
+ */
791
+ export type AuthEventData = {
792
+ type: AuthEventType;
793
+ timestamp: Date;
794
+ provider?: AuthProviderType;
795
+ user?: AuthUser;
796
+ session?: AuthSession;
797
+ error?: AuthErrorInfo;
798
+ context?: Record<string, JsonValue>;
799
+ };
800
+ /**
801
+ * Auth event handler
802
+ */
803
+ export type AuthEventHandler = (event: AuthEventData) => void | Promise<void>;
804
+ /**
805
+ * Auth provider factory function type
806
+ */
807
+ export type AuthProviderFactoryFn = (config: AuthProviderConfig) => Promise<MastraAuthProvider>;
808
+ /**
809
+ * Auth provider registration entry
810
+ */
811
+ export type AuthProviderRegistration = {
812
+ /** Provider type */
813
+ type: AuthProviderType;
814
+ /** Factory function */
815
+ factory: AuthProviderFactoryFn;
816
+ /** Provider aliases */
817
+ aliases: string[];
818
+ /** Provider metadata */
819
+ metadata?: {
820
+ name: string;
821
+ description: string;
822
+ version?: string;
823
+ documentation?: string;
824
+ };
825
+ };
826
+ /**
827
+ * Auth health check result
828
+ */
829
+ export type AuthHealthCheck = {
830
+ /** Overall health status */
831
+ healthy: boolean;
832
+ /** Provider connection status */
833
+ providerConnected: boolean;
834
+ /** Session storage status */
835
+ sessionStorageHealthy: boolean;
836
+ /** Last successful authentication */
837
+ lastSuccessfulAuth?: Date;
838
+ /** Error details if unhealthy */
839
+ error?: string;
840
+ };
841
+ /**
842
+ * Health check result for auth providers (detailed)
843
+ */
844
+ export type AuthProviderHealthCheck = {
845
+ /** Provider is healthy */
846
+ healthy: boolean;
847
+ /** Provider type */
848
+ provider: AuthProviderType;
849
+ /** Response time in ms */
850
+ latency?: number;
851
+ /** Last successful check */
852
+ lastCheck?: Date;
853
+ /** Error message if unhealthy */
854
+ error?: string;
855
+ /** Additional details */
856
+ details?: Record<string, JsonValue>;
857
+ };
858
+ /**
859
+ * Provider registration metadata used by AuthProviderRegistry.
860
+ *
861
+ * Previously defined in `AuthProviderRegistry.ts`; centralised here so all
862
+ * auth-domain types live in a single canonical file.
863
+ */
864
+ export type AuthProviderMetadata = {
865
+ /** Provider type */
866
+ type: AuthProviderType;
867
+ /** Human-readable name */
868
+ name: string;
869
+ /** Description */
870
+ description: string;
871
+ /** Version */
872
+ version?: string;
873
+ /** Documentation URL */
874
+ documentation?: string;
875
+ /** Provider aliases */
876
+ aliases: string[];
877
+ /** Features supported by the provider */
878
+ features?: string[];
879
+ /** Whether provider requires external dependencies */
880
+ requiresExternalDependencies?: boolean;
881
+ /** Whether the provider ships built-in (no extra install) */
882
+ builtIn?: boolean;
883
+ };
884
+ /**
885
+ * Auth-domain provider health status returned by AuthProviderRegistry.
886
+ *
887
+ * Not to be confused with the AI-provider `ProviderHealthStatus` union in
888
+ * `providers.ts`; this type tracks auth-provider connectivity.
889
+ */
890
+ export type AuthProviderHealthStatus = {
891
+ type: AuthProviderType;
892
+ healthy: boolean;
893
+ lastCheck: Date;
894
+ latency?: number;
895
+ error?: string;
896
+ };
897
+ /**
898
+ * Token operations: validate, extract, refresh, revoke.
899
+ */
900
+ export type AuthTokenValidator = {
901
+ /** Validate and decode an authentication token */
902
+ authenticateToken(token: string, context?: AuthRequestContext): Promise<TokenValidationResult>;
903
+ /** Extract token from request context */
904
+ extractToken(context: AuthRequestContext): string | null | Promise<string | null>;
905
+ /** Refresh an authentication token (optional) */
906
+ refreshToken?(refreshToken: string): Promise<TokenRefreshResult>;
907
+ /** Revoke a token / logout (optional) */
908
+ revokeToken?(token: string): Promise<void>;
909
+ };
910
+ /**
911
+ * Authorization: check roles and permissions.
912
+ */
913
+ export type AuthUserAuthorizer = {
914
+ /** Check if a user is authorized to perform an action */
915
+ authorizeUser(user: AuthUser, permission: string): Promise<AuthorizationResult>;
916
+ /** Check if user has specific roles */
917
+ authorizeRoles(user: AuthUser, roles: string[]): Promise<AuthorizationResult>;
918
+ /** Check if user has all specified permissions */
919
+ authorizePermissions(user: AuthUser, permissions: string[]): Promise<AuthorizationResult>;
920
+ };
921
+ /**
922
+ * Session management: create, read, refresh, destroy.
923
+ */
924
+ export type AuthSessionManager = {
925
+ /** Create a new session for a user */
926
+ createSession(user: AuthUser, context?: AuthRequestContext): Promise<AuthSession>;
927
+ /** Get an existing session by ID */
928
+ getSession(sessionId: string): Promise<AuthSession | null>;
929
+ /** Refresh/extend a session */
930
+ refreshSession(sessionId: string): Promise<AuthSession | null>;
931
+ /** Invalidate/destroy a session */
932
+ destroySession(sessionId: string): Promise<void>;
933
+ /** Get all active sessions for a user */
934
+ getUserSessions(userId: string): Promise<AuthSession[]>;
935
+ /** Invalidate all sessions for a user (global logout) */
936
+ destroyAllUserSessions(userId: string): Promise<void>;
937
+ };
938
+ /**
939
+ * Request-level authentication.
940
+ */
941
+ export type AuthRequestHandler = {
942
+ /** Authenticate a request and return full context */
943
+ authenticateRequest(context: AuthRequestContext): Promise<AuthenticatedContext | null>;
944
+ };
945
+ /**
946
+ * Optional user management operations.
947
+ */
948
+ export type AuthUserManager = {
949
+ /** Get user by ID */
950
+ getUser?(userId: string): Promise<AuthUser | null>;
951
+ /** Get user by email */
952
+ getUserByEmail?(email: string): Promise<AuthUser | null>;
953
+ /** Update user metadata */
954
+ updateUserMetadata?(userId: string, metadata: Record<string, unknown>): Promise<AuthUser>;
955
+ /** Update user roles */
956
+ updateUserRoles?(userId: string, roles: string[]): Promise<AuthUser>;
957
+ /** Update user permissions */
958
+ updateUserPermissions?(userId: string, permissions: string[]): Promise<AuthUser>;
959
+ };
960
+ /**
961
+ * Provider lifecycle hooks.
962
+ */
963
+ export type AuthLifecycle = {
964
+ /** Check provider health */
965
+ healthCheck?(): Promise<AuthHealthCheck>;
966
+ /** Initialize the provider */
967
+ initialize?(): Promise<void>;
968
+ /** Cleanup provider resources */
969
+ cleanup?(): Promise<void>;
970
+ /** Clean up resources (alias for cleanup) */
971
+ dispose?(): Promise<void>;
972
+ };
973
+ /**
974
+ * Base interface for all authentication providers.
975
+ *
976
+ * Composed from focused sub-types so consumers can depend on only the
977
+ * slice they need (e.g. `AuthTokenValidator` for token-only middleware).
978
+ *
979
+ * Implements Mastra-style auth provider pattern with unified methods for:
980
+ * - Token validation (AuthTokenValidator)
981
+ * - User authorization (AuthUserAuthorizer)
982
+ * - Session management (AuthSessionManager)
983
+ * - Request context (AuthRequestHandler)
984
+ * - User management (AuthUserManager)
985
+ * - Lifecycle (AuthLifecycle)
986
+ */
987
+ export type MastraAuthProvider = AuthTokenValidator & AuthUserAuthorizer & AuthSessionManager & AuthRequestHandler & AuthUserManager & AuthLifecycle & {
988
+ /** Provider type identifier */
989
+ readonly type: AuthProviderType;
990
+ /** Provider configuration */
991
+ readonly config: AuthProviderConfig;
992
+ };