@juspay/neurolink 9.31.1 → 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 (162) hide show
  1. package/CHANGELOG.md +12 -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/commands/proxy.js +4 -2
  49. package/dist/cli/factories/authCommandFactory.d.ts +23 -5
  50. package/dist/cli/factories/authCommandFactory.js +108 -5
  51. package/dist/cli/parser.js +1 -1
  52. package/dist/client/auth/AuthProviderFactory.js +111 -0
  53. package/dist/client/auth/AuthProviderRegistry.js +190 -0
  54. package/dist/client/auth/RequestContext.js +78 -0
  55. package/dist/client/auth/accountPool.js +178 -0
  56. package/dist/client/auth/authContext.js +314 -0
  57. package/dist/client/auth/errors.js +39 -0
  58. package/dist/client/auth/index.js +61 -0
  59. package/dist/client/auth/middleware/AuthMiddleware.js +519 -0
  60. package/dist/client/auth/middleware/rateLimitByUser.js +554 -0
  61. package/dist/client/auth/providers/BaseAuthProvider.js +723 -0
  62. package/dist/client/auth/providers/CognitoProvider.js +304 -0
  63. package/dist/client/auth/providers/KeycloakProvider.js +393 -0
  64. package/dist/client/auth/providers/auth0.js +274 -0
  65. package/dist/client/auth/providers/betterAuth.js +182 -0
  66. package/dist/client/auth/providers/clerk.js +317 -0
  67. package/dist/client/auth/providers/custom.js +112 -0
  68. package/dist/client/auth/providers/firebase.js +226 -0
  69. package/dist/client/auth/providers/jwt.js +212 -0
  70. package/dist/client/auth/providers/oauth2.js +303 -0
  71. package/dist/client/auth/providers/supabase.js +259 -0
  72. package/dist/client/auth/providers/workos.js +284 -0
  73. package/dist/client/auth/serverBridge.js +25 -0
  74. package/dist/client/auth/sessionManager.js +437 -0
  75. package/dist/client/core/infrastructure/baseRegistry.js +5 -1
  76. package/dist/client/index.js +25 -0
  77. package/dist/client/mcp/toolRegistry.js +11 -1
  78. package/dist/client/neurolink.js +218 -0
  79. package/dist/client/rag/ChunkerRegistry.js +2 -2
  80. package/dist/client/rag/metadata/MetadataExtractorRegistry.js +2 -2
  81. package/dist/client/rag/reranker/RerankerRegistry.js +2 -2
  82. package/dist/client/server/routes/agentRoutes.js +20 -2
  83. package/dist/client/types/authTypes.js +2 -1
  84. package/dist/core/infrastructure/baseRegistry.d.ts +3 -1
  85. package/dist/core/infrastructure/baseRegistry.js +5 -1
  86. package/dist/index.d.ts +1 -0
  87. package/dist/index.js +25 -0
  88. package/dist/lib/auth/AuthProviderFactory.d.ts +71 -0
  89. package/dist/lib/auth/AuthProviderFactory.js +112 -0
  90. package/dist/lib/auth/AuthProviderRegistry.d.ts +33 -0
  91. package/dist/lib/auth/AuthProviderRegistry.js +191 -0
  92. package/dist/lib/auth/RequestContext.d.ts +23 -0
  93. package/dist/lib/auth/RequestContext.js +79 -0
  94. package/dist/lib/auth/authContext.d.ts +198 -0
  95. package/dist/lib/auth/authContext.js +315 -0
  96. package/dist/lib/auth/errors.d.ts +63 -0
  97. package/dist/lib/auth/errors.js +40 -0
  98. package/dist/lib/auth/index.d.ts +20 -8
  99. package/dist/lib/auth/index.js +35 -7
  100. package/dist/lib/auth/middleware/AuthMiddleware.d.ts +181 -0
  101. package/dist/lib/auth/middleware/AuthMiddleware.js +520 -0
  102. package/dist/lib/auth/middleware/rateLimitByUser.d.ts +282 -0
  103. package/dist/lib/auth/middleware/rateLimitByUser.js +555 -0
  104. package/dist/lib/auth/providers/BaseAuthProvider.d.ts +259 -0
  105. package/dist/lib/auth/providers/BaseAuthProvider.js +724 -0
  106. package/dist/lib/auth/providers/CognitoProvider.d.ts +61 -0
  107. package/dist/lib/auth/providers/CognitoProvider.js +305 -0
  108. package/dist/lib/auth/providers/KeycloakProvider.d.ts +61 -0
  109. package/dist/lib/auth/providers/KeycloakProvider.js +394 -0
  110. package/dist/lib/auth/providers/auth0.d.ts +59 -0
  111. package/dist/lib/auth/providers/auth0.js +275 -0
  112. package/dist/lib/auth/providers/betterAuth.d.ts +51 -0
  113. package/dist/lib/auth/providers/betterAuth.js +183 -0
  114. package/dist/lib/auth/providers/clerk.d.ts +65 -0
  115. package/dist/lib/auth/providers/clerk.js +318 -0
  116. package/dist/lib/auth/providers/custom.d.ts +64 -0
  117. package/dist/lib/auth/providers/custom.js +113 -0
  118. package/dist/lib/auth/providers/firebase.d.ts +63 -0
  119. package/dist/lib/auth/providers/firebase.js +227 -0
  120. package/dist/lib/auth/providers/jwt.d.ts +68 -0
  121. package/dist/lib/auth/providers/jwt.js +213 -0
  122. package/dist/lib/auth/providers/oauth2.d.ts +73 -0
  123. package/dist/lib/auth/providers/oauth2.js +304 -0
  124. package/dist/lib/auth/providers/supabase.d.ts +63 -0
  125. package/dist/lib/auth/providers/supabase.js +260 -0
  126. package/dist/lib/auth/providers/workos.d.ts +61 -0
  127. package/dist/lib/auth/providers/workos.js +285 -0
  128. package/dist/lib/auth/serverBridge.d.ts +14 -0
  129. package/dist/lib/auth/serverBridge.js +26 -0
  130. package/dist/lib/auth/sessionManager.d.ts +142 -0
  131. package/dist/lib/auth/sessionManager.js +438 -0
  132. package/dist/lib/core/infrastructure/baseRegistry.d.ts +3 -1
  133. package/dist/lib/core/infrastructure/baseRegistry.js +5 -1
  134. package/dist/lib/index.d.ts +1 -0
  135. package/dist/lib/index.js +25 -0
  136. package/dist/lib/mcp/toolRegistry.js +11 -1
  137. package/dist/lib/neurolink.d.ts +42 -1
  138. package/dist/lib/neurolink.js +218 -0
  139. package/dist/lib/rag/ChunkerRegistry.js +2 -2
  140. package/dist/lib/rag/metadata/MetadataExtractorRegistry.js +2 -2
  141. package/dist/lib/rag/reranker/RerankerRegistry.js +2 -2
  142. package/dist/lib/server/routes/agentRoutes.js +20 -2
  143. package/dist/lib/types/authTypes.d.ts +937 -1
  144. package/dist/lib/types/authTypes.js +2 -1
  145. package/dist/lib/types/configTypes.d.ts +46 -0
  146. package/dist/lib/types/generateTypes.d.ts +6 -0
  147. package/dist/lib/types/index.d.ts +1 -0
  148. package/dist/lib/types/streamTypes.d.ts +6 -0
  149. package/dist/mcp/toolRegistry.js +11 -1
  150. package/dist/neurolink.d.ts +42 -1
  151. package/dist/neurolink.js +218 -0
  152. package/dist/rag/ChunkerRegistry.js +2 -2
  153. package/dist/rag/metadata/MetadataExtractorRegistry.js +2 -2
  154. package/dist/rag/reranker/RerankerRegistry.js +2 -2
  155. package/dist/server/routes/agentRoutes.js +20 -2
  156. package/dist/types/authTypes.d.ts +937 -1
  157. package/dist/types/authTypes.js +2 -1
  158. package/dist/types/configTypes.d.ts +46 -0
  159. package/dist/types/generateTypes.d.ts +6 -0
  160. package/dist/types/index.d.ts +1 -0
  161. package/dist/types/streamTypes.d.ts +6 -0
  162. package/package.json +2 -1
@@ -0,0 +1,393 @@
1
+ /**
2
+ * KeycloakProvider - Keycloak OpenID Connect provider implementation
3
+ *
4
+ * Provides JWT validation, session management, and RBAC for Keycloak.
5
+ */
6
+ import { importJWK, jwtVerify } from "jose";
7
+ import { logger } from "../../utils/logger.js";
8
+ import { AuthError } from "../errors.js";
9
+ import { BaseAuthProvider } from "./BaseAuthProvider.js";
10
+ const jwksCache = new Map();
11
+ // =============================================================================
12
+ // KEYCLOAK PROVIDER
13
+ // =============================================================================
14
+ /**
15
+ * KeycloakProvider - Keycloak OpenID Connect integration
16
+ *
17
+ * Features:
18
+ * - Keycloak JWT token validation
19
+ * - JWKS-based signature verification
20
+ * - Realm roles and client roles support
21
+ * - Resource access for fine-grained permissions
22
+ * - Session management
23
+ *
24
+ * @example
25
+ * ```typescript
26
+ * const provider = new KeycloakProvider({
27
+ * type: 'keycloak',
28
+ * serverUrl: 'https://keycloak.example.com',
29
+ * realm: 'your-realm',
30
+ * clientId: 'your-client-id',
31
+ * });
32
+ *
33
+ * const result = await provider.authenticateToken(accessToken);
34
+ * if (result.valid) {
35
+ * console.log('User:', result.user);
36
+ * }
37
+ * ```
38
+ */
39
+ export class KeycloakProvider extends BaseAuthProvider {
40
+ type = "keycloak";
41
+ keycloakConfig;
42
+ jwksUri;
43
+ jwksCacheDuration;
44
+ expectedIssuer;
45
+ constructor(config) {
46
+ super(config);
47
+ if (config.type !== "keycloak") {
48
+ throw AuthError.create("CONFIGURATION_ERROR", `Invalid provider type: ${config.type}. Expected: keycloak`);
49
+ }
50
+ this.keycloakConfig = config;
51
+ if (!this.keycloakConfig.serverUrl) {
52
+ throw AuthError.create("CONFIGURATION_ERROR", "Keycloak serverUrl is required");
53
+ }
54
+ if (!this.keycloakConfig.realm) {
55
+ throw AuthError.create("CONFIGURATION_ERROR", "Keycloak realm is required");
56
+ }
57
+ if (!this.keycloakConfig.clientId) {
58
+ throw AuthError.create("CONFIGURATION_ERROR", "Keycloak clientId is required");
59
+ }
60
+ // Normalize server URL
61
+ const serverUrl = this.keycloakConfig.serverUrl.replace(/\/$/, "");
62
+ // Set up issuer and JWKS URI
63
+ this.expectedIssuer = `${serverUrl}/realms/${this.keycloakConfig.realm}`;
64
+ this.jwksUri = `${this.expectedIssuer}/protocol/openid-connect/certs`;
65
+ this.jwksCacheDuration =
66
+ config.tokenValidation?.jwksCacheDuration ?? 600000; // 10 minutes
67
+ logger.debug(`[KeycloakProvider] Initialized for realm: ${this.keycloakConfig.realm}`);
68
+ }
69
+ /**
70
+ * Validate and authenticate a Keycloak JWT token
71
+ */
72
+ async authenticateToken(token) {
73
+ try {
74
+ // Parse token without verification first
75
+ const claims = this.parseJWT(token);
76
+ if (!claims) {
77
+ return {
78
+ valid: false,
79
+ error: "Failed to decode token",
80
+ errorCode: "AUTH-006",
81
+ };
82
+ }
83
+ // Validate issuer
84
+ if (claims.iss !== this.expectedIssuer) {
85
+ return {
86
+ valid: false,
87
+ error: `Invalid issuer: ${claims.iss}. Expected: ${this.expectedIssuer}`,
88
+ errorCode: "AUTH-001",
89
+ };
90
+ }
91
+ // Validate audience — always check aud contains clientId
92
+ const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
93
+ if (!audiences.includes(this.keycloakConfig.clientId)) {
94
+ return {
95
+ valid: false,
96
+ error: `Invalid audience: token aud does not contain clientId "${this.keycloakConfig.clientId}"`,
97
+ errorCode: "AUTH-001",
98
+ };
99
+ }
100
+ // Additionally validate azp if present
101
+ const azp = claims.azp;
102
+ if (azp && azp !== this.keycloakConfig.clientId) {
103
+ return {
104
+ valid: false,
105
+ error: `Invalid authorized party: ${azp}. Expected: ${this.keycloakConfig.clientId}`,
106
+ errorCode: "AUTH-001",
107
+ };
108
+ }
109
+ // Check expiration
110
+ const clockTolerance = this.config.tokenValidation?.clockTolerance ?? 0;
111
+ if (this.isTokenExpired(claims, clockTolerance)) {
112
+ return {
113
+ valid: false,
114
+ error: "Token has expired",
115
+ errorCode: "AUTH-002",
116
+ expiresAt: claims.exp ? new Date(claims.exp * 1000) : undefined,
117
+ };
118
+ }
119
+ // Check nbf (not before)
120
+ if (this.isTokenNotYetValid(claims, clockTolerance)) {
121
+ return {
122
+ valid: false,
123
+ error: "Token is not yet valid",
124
+ errorCode: "AUTH-001",
125
+ };
126
+ }
127
+ // Verify signature if enabled
128
+ if (this.keycloakConfig.verifyToken !== false &&
129
+ this.config.tokenValidation?.validateSignature !== false) {
130
+ const signatureValid = await this.verifySignature(token);
131
+ if (!signatureValid) {
132
+ return {
133
+ valid: false,
134
+ error: "Invalid token signature",
135
+ errorCode: "AUTH-004",
136
+ };
137
+ }
138
+ }
139
+ // Extract user from claims
140
+ const user = this.extractKeycloakUser(claims);
141
+ // Convert claims to Record<string, JsonValue> by filtering out undefined
142
+ const validClaims = {};
143
+ for (const [key, value] of Object.entries(claims)) {
144
+ if (value !== undefined) {
145
+ validClaims[key] = value;
146
+ }
147
+ }
148
+ return {
149
+ valid: true,
150
+ user,
151
+ claims: validClaims,
152
+ expiresAt: claims.exp ? new Date(claims.exp * 1000) : undefined,
153
+ issuer: claims.iss,
154
+ audience: claims.aud,
155
+ };
156
+ }
157
+ catch (error) {
158
+ logger.error(`[KeycloakProvider] Token validation error:`, error);
159
+ return {
160
+ valid: false,
161
+ error: error instanceof Error ? error.message : "Token validation failed",
162
+ errorCode: "AUTH-014",
163
+ };
164
+ }
165
+ }
166
+ /**
167
+ * Verify token signature using JWKS
168
+ */
169
+ async verifySignature(token) {
170
+ try {
171
+ const parts = token.split(".");
172
+ if (parts.length !== 3) {
173
+ return false;
174
+ }
175
+ // Decode header to get kid
176
+ const header = JSON.parse(Buffer.from(parts[0], "base64url").toString("utf-8"));
177
+ const kid = header.kid;
178
+ if (!kid) {
179
+ logger.warn("[KeycloakProvider] Token missing kid in header");
180
+ return false;
181
+ }
182
+ // Get JWKS
183
+ const jwks = await this.getJWKS();
184
+ const key = jwks.keys.find((k) => k.kid === kid);
185
+ if (!key) {
186
+ logger.warn(`[KeycloakProvider] Key not found for kid: ${kid}`);
187
+ return false;
188
+ }
189
+ // Verify the JWT signature against the public key
190
+ const publicKey = await importJWK(key, header.alg);
191
+ const clockTolerance = this.config.tokenValidation?.clockTolerance ?? 30;
192
+ await jwtVerify(token, publicKey, { clockTolerance });
193
+ return true;
194
+ }
195
+ catch (error) {
196
+ logger.error(`[KeycloakProvider] Signature verification error:`, error);
197
+ return false;
198
+ }
199
+ }
200
+ /**
201
+ * Fetch JWKS with caching
202
+ */
203
+ async getJWKS() {
204
+ const cached = jwksCache.get(this.jwksUri);
205
+ if (cached && cached.expiresAt > Date.now()) {
206
+ return cached.jwks;
207
+ }
208
+ try {
209
+ const response = await fetch(this.jwksUri, {
210
+ signal: AbortSignal.timeout(5000),
211
+ });
212
+ if (!response.ok) {
213
+ throw new Error(`JWKS fetch failed: ${response.status}`);
214
+ }
215
+ const jwks = (await response.json());
216
+ // Cache the JWKS
217
+ jwksCache.set(this.jwksUri, {
218
+ jwks,
219
+ expiresAt: Date.now() + this.jwksCacheDuration,
220
+ });
221
+ return jwks;
222
+ }
223
+ catch (error) {
224
+ throw AuthError.create("JWKS_FETCH_FAILED", `Failed to fetch JWKS from ${this.jwksUri}: ${error instanceof Error ? error.message : String(error)}`, { cause: error instanceof Error ? error : undefined });
225
+ }
226
+ }
227
+ /**
228
+ * Extract Keycloak-specific user data from claims
229
+ */
230
+ extractKeycloakUser(claims) {
231
+ const userId = claims.sub ?? "";
232
+ const email = claims.email;
233
+ const name = claims.name ?? claims.preferred_username;
234
+ const picture = claims.picture;
235
+ // Get realm roles
236
+ let roles = [];
237
+ const realmAccess = claims.realm_access;
238
+ if (realmAccess?.roles) {
239
+ roles = [...realmAccess.roles];
240
+ }
241
+ // Get client roles
242
+ const resourceAccess = claims.resource_access;
243
+ if (resourceAccess) {
244
+ // Add roles from the specific client
245
+ const clientRoles = resourceAccess[this.keycloakConfig.clientId]?.roles;
246
+ if (clientRoles) {
247
+ roles = [
248
+ ...roles,
249
+ ...clientRoles.map((r) => `${this.keycloakConfig.clientId}:${r}`),
250
+ ];
251
+ }
252
+ // Optionally add roles from all clients (prefixed)
253
+ for (const [client, access] of Object.entries(resourceAccess)) {
254
+ if (client !== this.keycloakConfig.clientId && access.roles) {
255
+ roles = [...roles, ...access.roles.map((r) => `${client}:${r}`)];
256
+ }
257
+ }
258
+ }
259
+ // Apply default roles
260
+ if (roles.length === 0 && this.rbacConfig.defaultRoles) {
261
+ roles = this.rbacConfig.defaultRoles;
262
+ }
263
+ // Get scope as permissions
264
+ let permissions = [];
265
+ const scope = claims.scope;
266
+ if (scope) {
267
+ permissions = scope.split(" ").filter((s) => s.length > 0);
268
+ }
269
+ // Build provider data, filtering out undefined values
270
+ const providerData = {
271
+ provider: "keycloak",
272
+ };
273
+ if (claims.preferred_username !== undefined) {
274
+ providerData.preferred_username = claims.preferred_username;
275
+ }
276
+ if (claims.given_name !== undefined) {
277
+ providerData.given_name = claims.given_name;
278
+ }
279
+ if (claims.family_name !== undefined) {
280
+ providerData.family_name = claims.family_name;
281
+ }
282
+ if (realmAccess !== undefined) {
283
+ providerData.realm_access =
284
+ realmAccess;
285
+ }
286
+ if (resourceAccess !== undefined) {
287
+ providerData.resource_access =
288
+ resourceAccess;
289
+ }
290
+ if (claims.azp !== undefined) {
291
+ providerData.azp = claims.azp;
292
+ }
293
+ if (claims.session_state !== undefined) {
294
+ providerData.session_state = claims.session_state;
295
+ }
296
+ if (claims.acr !== undefined) {
297
+ providerData.acr = claims.acr;
298
+ }
299
+ if (claims.typ !== undefined) {
300
+ providerData.typ = claims.typ;
301
+ }
302
+ return {
303
+ id: userId,
304
+ email,
305
+ name,
306
+ picture,
307
+ roles,
308
+ permissions,
309
+ emailVerified: claims.email_verified,
310
+ providerData,
311
+ };
312
+ }
313
+ /**
314
+ * Get user from Keycloak Admin API
315
+ * Note: Requires client credentials with admin access
316
+ */
317
+ async getUser(userId) {
318
+ if (!this.keycloakConfig.clientSecret) {
319
+ logger.debug("[KeycloakProvider] clientSecret required for admin API");
320
+ return null;
321
+ }
322
+ try {
323
+ // Get admin token
324
+ const tokenResponse = await fetch(`${this.expectedIssuer}/protocol/openid-connect/token`, {
325
+ method: "POST",
326
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
327
+ body: new URLSearchParams({
328
+ grant_type: "client_credentials",
329
+ client_id: this.keycloakConfig.clientId,
330
+ client_secret: this.keycloakConfig.clientSecret,
331
+ }),
332
+ signal: AbortSignal.timeout(5000),
333
+ });
334
+ if (!tokenResponse.ok) {
335
+ throw new Error(`Failed to get admin token: ${tokenResponse.status}`);
336
+ }
337
+ const tokenData = (await tokenResponse.json());
338
+ // Get user from admin API
339
+ const serverUrl = this.keycloakConfig.serverUrl.replace(/\/$/, "");
340
+ const userResponse = await fetch(`${serverUrl}/admin/realms/${this.keycloakConfig.realm}/users/${encodeURIComponent(userId)}`, {
341
+ headers: {
342
+ Authorization: `Bearer ${tokenData.access_token}`,
343
+ },
344
+ signal: AbortSignal.timeout(5000),
345
+ });
346
+ if (!userResponse.ok) {
347
+ if (userResponse.status === 404) {
348
+ return null;
349
+ }
350
+ throw new Error(`Failed to get user: ${userResponse.status}`);
351
+ }
352
+ const userData = (await userResponse.json());
353
+ // Get user's realm roles
354
+ const rolesResponse = await fetch(`${serverUrl}/admin/realms/${this.keycloakConfig.realm}/users/${encodeURIComponent(userId)}/role-mappings/realm`, {
355
+ headers: {
356
+ Authorization: `Bearer ${tokenData.access_token}`,
357
+ },
358
+ signal: AbortSignal.timeout(5000),
359
+ });
360
+ let roles = this.rbacConfig.defaultRoles ?? [];
361
+ if (rolesResponse.ok) {
362
+ const rolesData = (await rolesResponse.json());
363
+ roles = rolesData.map((r) => r.name);
364
+ }
365
+ // Convert userData to Record<string, JsonValue> by filtering out undefined
366
+ const providerData = {};
367
+ for (const [key, value] of Object.entries(userData)) {
368
+ if (value !== undefined) {
369
+ providerData[key] =
370
+ value;
371
+ }
372
+ }
373
+ return {
374
+ id: userData.id,
375
+ email: userData.email,
376
+ name: `${userData.firstName ?? ""} ${userData.lastName ?? ""}`.trim() ||
377
+ userData.username,
378
+ picture: undefined, // Keycloak doesn't store picture by default
379
+ roles,
380
+ permissions: [],
381
+ emailVerified: userData.emailVerified,
382
+ providerData,
383
+ createdAt: userData.createdTimestamp
384
+ ? new Date(userData.createdTimestamp)
385
+ : undefined,
386
+ };
387
+ }
388
+ catch (error) {
389
+ logger.error(`[KeycloakProvider] Failed to get user ${userId}:`, error);
390
+ return null;
391
+ }
392
+ }
393
+ }
@@ -0,0 +1,59 @@
1
+ import { BaseAuthProvider } from "./BaseAuthProvider.js";
2
+ import type { AuthProviderConfig, Auth0Config, AuthUser, TokenValidationResult, AuthRequestContext, AuthHealthCheck, AuthProviderType } from "../../types/authTypes.js";
3
+ /**
4
+ * Auth0 Authentication Provider
5
+ *
6
+ * Supports JWT validation with JWKS for Auth0-issued tokens.
7
+ * Uses jose library for JWT verification against Auth0's JWKS endpoint.
8
+ *
9
+ * Features:
10
+ * - JWT validation with JWKS
11
+ * - User profile fetching (requires Management API token)
12
+ * - Role and permission extraction from token claims
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * const auth0 = new Auth0Provider({
17
+ * type: "auth0",
18
+ * domain: "your-tenant.auth0.com",
19
+ * clientId: "your-client-id",
20
+ * audience: "https://your-api.example.com"
21
+ * });
22
+ *
23
+ * const result = await auth0.authenticateToken(bearerToken);
24
+ * if (result.valid) {
25
+ * console.log("Authenticated user:", result.user);
26
+ * }
27
+ * ```
28
+ */
29
+ export declare class Auth0Provider extends BaseAuthProvider {
30
+ readonly type: AuthProviderType;
31
+ private domain;
32
+ private clientId;
33
+ private audience?;
34
+ private rolesNamespace?;
35
+ private permissionsNamespace?;
36
+ private jwks;
37
+ constructor(config: AuthProviderConfig & Auth0Config);
38
+ /**
39
+ * Initialize JWKS for JWT verification
40
+ */
41
+ initialize(): Promise<void>;
42
+ /**
43
+ * Validate Auth0 JWT token
44
+ */
45
+ authenticateToken(token: string, _context?: AuthRequestContext): Promise<TokenValidationResult>;
46
+ /**
47
+ * Fetch user profile from Auth0 Management API
48
+ * Note: Requires AUTH0_MANAGEMENT_TOKEN environment variable
49
+ */
50
+ getUser(userId: string): Promise<AuthUser | null>;
51
+ /**
52
+ * Get user by email from Auth0 Management API
53
+ */
54
+ getUserByEmail(email: string): Promise<AuthUser | null>;
55
+ /**
56
+ * Health check
57
+ */
58
+ healthCheck(): Promise<AuthHealthCheck>;
59
+ }