@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
@@ -0,0 +1,318 @@
1
+ // src/lib/auth/providers/clerk.ts
2
+ import { BaseAuthProvider } from "./BaseAuthProvider.js";
3
+ import { AuthError } from "../errors.js";
4
+ import { logger } from "../../utils/logger.js";
5
+ import { createProxyFetch } from "../../proxy/proxyFetch.js";
6
+ import * as jose from "jose";
7
+ /**
8
+ * Clerk Authentication Provider
9
+ *
10
+ * Supports Clerk's session-based and JWT authentication.
11
+ * Can validate both JWT tokens and session tokens via Clerk API.
12
+ *
13
+ * Features:
14
+ * - JWT validation using Clerk's JWKS
15
+ * - Session token validation via Clerk API
16
+ * - User profile fetching
17
+ * - Organization support for multi-tenant apps
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * const clerk = new ClerkProvider({
22
+ * type: "clerk",
23
+ * publishableKey: "pk_test_...",
24
+ * secretKey: "sk_test_..."
25
+ * });
26
+ *
27
+ * const result = await clerk.authenticateToken(sessionToken);
28
+ * if (result.valid) {
29
+ * console.log("Authenticated user:", result.user);
30
+ * }
31
+ * ```
32
+ */
33
+ export class ClerkProvider extends BaseAuthProvider {
34
+ type = "clerk";
35
+ secretKey;
36
+ jwtKey;
37
+ publishableKey;
38
+ jwks = null;
39
+ localKey = null;
40
+ constructor(config) {
41
+ super(config);
42
+ if (!config.secretKey) {
43
+ throw AuthError.create("CONFIGURATION_ERROR", "Clerk secretKey is required", { details: { missingFields: ["secretKey"] } });
44
+ }
45
+ this.secretKey = config.secretKey;
46
+ this.jwtKey = config.jwtKey;
47
+ this.publishableKey = config.publishableKey;
48
+ }
49
+ /**
50
+ * Initialize Clerk JWKS
51
+ */
52
+ async initialize() {
53
+ // Clerk JWKS endpoint (v1 API)
54
+ const jwksUrl = new URL("https://api.clerk.com/v1/jwks");
55
+ this.jwks = jose.createRemoteJWKSet(jwksUrl);
56
+ logger.debug("Clerk provider initialized");
57
+ }
58
+ /**
59
+ * Validate Clerk session token or JWT
60
+ */
61
+ async authenticateToken(token, _context) {
62
+ // First try JWT validation (tokens with dots)
63
+ if (token.includes(".") && token.split(".").length === 3) {
64
+ return this.validateJWT(token);
65
+ }
66
+ // Otherwise treat as session token
67
+ return this.validateSessionToken(token);
68
+ }
69
+ /**
70
+ * Validate JWT using local jwtKey (if configured) or JWKS
71
+ */
72
+ async validateJWT(token) {
73
+ try {
74
+ let payload;
75
+ if (this.jwtKey) {
76
+ // Use locally provided JWT key for verification
77
+ if (!this.localKey) {
78
+ this.localKey = new TextEncoder().encode(this.jwtKey);
79
+ }
80
+ ({ payload } = await jose.jwtVerify(token, this.localKey));
81
+ }
82
+ else {
83
+ // Fall back to Clerk JWKS endpoint
84
+ if (!this.jwks) {
85
+ await this.initialize();
86
+ }
87
+ if (!this.jwks) {
88
+ return {
89
+ valid: false,
90
+ error: "Clerk JWKS not initialized",
91
+ };
92
+ }
93
+ ({ payload } = await jose.jwtVerify(token, this.jwks));
94
+ }
95
+ // Validate azp (authorized party) claim if publishableKey is configured
96
+ if (this.publishableKey && payload.azp) {
97
+ if (payload.azp !== this.publishableKey) {
98
+ return {
99
+ valid: false,
100
+ error: `Invalid authorized party: ${payload.azp}. Expected: ${this.publishableKey}`,
101
+ };
102
+ }
103
+ }
104
+ const user = {
105
+ id: payload.sub,
106
+ email: payload.email,
107
+ name: payload.name,
108
+ picture: payload.picture,
109
+ emailVerified: payload.email_verified,
110
+ roles: payload["https://clerk.dev/roles"] || [],
111
+ permissions: payload["https://clerk.dev/permissions"] || [],
112
+ organizationId: payload.org_id,
113
+ metadata: {
114
+ azp: payload.azp,
115
+ sid: payload.sid,
116
+ },
117
+ };
118
+ return {
119
+ valid: true,
120
+ payload: payload,
121
+ user,
122
+ expiresAt: payload.exp ? new Date(payload.exp * 1000) : undefined,
123
+ tokenType: "jwt",
124
+ };
125
+ }
126
+ catch (error) {
127
+ return {
128
+ valid: false,
129
+ error: error instanceof Error ? error.message : String(error),
130
+ };
131
+ }
132
+ }
133
+ /**
134
+ * Validate session token via Clerk API
135
+ */
136
+ async validateSessionToken(token) {
137
+ try {
138
+ const proxyFetch = createProxyFetch();
139
+ const response = await proxyFetch("https://api.clerk.com/v1/sessions/verify", {
140
+ method: "POST",
141
+ headers: {
142
+ Authorization: `Bearer ${this.secretKey}`,
143
+ "Content-Type": "application/json",
144
+ },
145
+ body: JSON.stringify({ token }),
146
+ });
147
+ if (!response.ok) {
148
+ const error = (await response.json());
149
+ return {
150
+ valid: false,
151
+ error: error.errors?.[0]?.message || "Session validation failed",
152
+ };
153
+ }
154
+ const session = (await response.json());
155
+ const userData = session.user;
156
+ const emailAddresses = userData?.email_addresses;
157
+ const user = {
158
+ id: session.user_id,
159
+ email: emailAddresses?.[0]?.email_address,
160
+ name: userData?.first_name
161
+ ? `${userData.first_name} ${userData.last_name || ""}`.trim()
162
+ : undefined,
163
+ picture: userData?.image_url,
164
+ roles: userData?.public_metadata
165
+ ?.roles || [],
166
+ permissions: userData?.public_metadata
167
+ ?.permissions || [],
168
+ organizationId: session.active_organization_id,
169
+ };
170
+ return {
171
+ valid: true,
172
+ payload: session,
173
+ user,
174
+ expiresAt: session.expire_at
175
+ ? new Date(session.expire_at)
176
+ : undefined,
177
+ tokenType: "session",
178
+ };
179
+ }
180
+ catch (error) {
181
+ return {
182
+ valid: false,
183
+ error: error instanceof Error ? error.message : String(error),
184
+ };
185
+ }
186
+ }
187
+ /**
188
+ * Get user by ID from Clerk API
189
+ */
190
+ async getUser(userId) {
191
+ try {
192
+ const proxyFetch = createProxyFetch();
193
+ const response = await proxyFetch(`https://api.clerk.com/v1/users/${userId}`, {
194
+ headers: {
195
+ Authorization: `Bearer ${this.secretKey}`,
196
+ },
197
+ });
198
+ if (!response.ok) {
199
+ if (response.status === 404) {
200
+ return null;
201
+ }
202
+ throw AuthError.create("PROVIDER_ERROR", `Clerk API returned ${response.status}`, { details: { statusCode: response.status } });
203
+ }
204
+ const data = (await response.json());
205
+ const emailAddresses = data.email_addresses;
206
+ return {
207
+ id: data.id,
208
+ email: emailAddresses?.[0]?.email_address,
209
+ name: data.first_name
210
+ ? `${data.first_name} ${data.last_name || ""}`.trim()
211
+ : undefined,
212
+ picture: data.image_url,
213
+ emailVerified: emailAddresses?.[0]?.verification?.status === "verified",
214
+ roles: data.public_metadata
215
+ ?.roles || [],
216
+ permissions: data.public_metadata
217
+ ?.permissions || [],
218
+ createdAt: data.created_at
219
+ ? new Date(data.created_at)
220
+ : undefined,
221
+ lastLoginAt: data.last_sign_in_at
222
+ ? new Date(data.last_sign_in_at)
223
+ : undefined,
224
+ metadata: data.private_metadata,
225
+ };
226
+ }
227
+ catch (error) {
228
+ logger.error("Failed to fetch Clerk user:", error);
229
+ if (error &&
230
+ typeof error === "object" &&
231
+ "code" in error &&
232
+ typeof error.code === "string") {
233
+ throw error;
234
+ }
235
+ return null;
236
+ }
237
+ }
238
+ /**
239
+ * Get user by email from Clerk API
240
+ */
241
+ async getUserByEmail(email) {
242
+ try {
243
+ const proxyFetch = createProxyFetch();
244
+ const response = await proxyFetch(`https://api.clerk.com/v1/users?email_address=${encodeURIComponent(email)}`, {
245
+ headers: {
246
+ Authorization: `Bearer ${this.secretKey}`,
247
+ },
248
+ });
249
+ if (!response.ok) {
250
+ throw AuthError.create("PROVIDER_ERROR", `Clerk API returned ${response.status}`, { details: { statusCode: response.status } });
251
+ }
252
+ const users = (await response.json());
253
+ if (users.length === 0) {
254
+ return null;
255
+ }
256
+ const data = users[0];
257
+ const emailAddresses = data.email_addresses;
258
+ return {
259
+ id: data.id,
260
+ email: emailAddresses?.[0]?.email_address,
261
+ name: data.first_name
262
+ ? `${data.first_name} ${data.last_name || ""}`.trim()
263
+ : undefined,
264
+ picture: data.image_url,
265
+ emailVerified: emailAddresses?.[0]?.verification?.status === "verified",
266
+ roles: data.public_metadata
267
+ ?.roles || [],
268
+ permissions: data.public_metadata
269
+ ?.permissions || [],
270
+ createdAt: data.created_at
271
+ ? new Date(data.created_at)
272
+ : undefined,
273
+ lastLoginAt: data.last_sign_in_at
274
+ ? new Date(data.last_sign_in_at)
275
+ : undefined,
276
+ metadata: data.private_metadata,
277
+ };
278
+ }
279
+ catch (error) {
280
+ logger.error("Failed to fetch Clerk user by email:", error);
281
+ if (error &&
282
+ typeof error === "object" &&
283
+ "code" in error &&
284
+ typeof error.code === "string") {
285
+ throw error;
286
+ }
287
+ return null;
288
+ }
289
+ }
290
+ /**
291
+ * Health check
292
+ */
293
+ async healthCheck() {
294
+ try {
295
+ const proxyFetch = createProxyFetch();
296
+ // Use a lightweight endpoint to check connectivity
297
+ const response = await proxyFetch("https://api.clerk.com/v1/organizations?limit=1", {
298
+ headers: {
299
+ Authorization: `Bearer ${this.secretKey}`,
300
+ },
301
+ });
302
+ return {
303
+ healthy: response.ok,
304
+ providerConnected: response.ok,
305
+ sessionStorageHealthy: true,
306
+ };
307
+ }
308
+ catch (error) {
309
+ return {
310
+ healthy: false,
311
+ providerConnected: false,
312
+ sessionStorageHealthy: true,
313
+ error: error instanceof Error ? error.message : String(error),
314
+ };
315
+ }
316
+ }
317
+ }
318
+ //# sourceMappingURL=clerk.js.map
@@ -0,0 +1,64 @@
1
+ import type { AuthProviderConfig, CustomAuthConfig, AuthUser, AuthSession, TokenValidationResult, AuthRequestContext, AuthHealthCheck } from "../../types/authTypes.js";
2
+ import { BaseAuthProvider } from "./BaseAuthProvider.js";
3
+ /**
4
+ * Custom Authentication Provider
5
+ *
6
+ * Allows users to provide their own authentication logic through callback functions.
7
+ * Useful for integrating with custom auth systems or implementing unique auth flows.
8
+ *
9
+ * Features:
10
+ * - Custom token validation via callback
11
+ * - Custom user fetching (optional)
12
+ * - Custom session creation (optional, delegates to base when not provided)
13
+ * - Session management (inherited from BaseAuthProvider)
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const custom = new CustomAuthProvider({
18
+ * type: "custom",
19
+ * validateToken: async (token, context) => {
20
+ * // Your custom token validation logic
21
+ * const decoded = await myAuthService.verify(token);
22
+ * return {
23
+ * valid: !!decoded,
24
+ * user: decoded ? {
25
+ * id: decoded.sub,
26
+ * email: decoded.email,
27
+ * roles: decoded.roles || [],
28
+ * permissions: decoded.permissions || [],
29
+ * } : undefined,
30
+ * };
31
+ * },
32
+ * getUser: async (userId) => {
33
+ * // Your custom user fetching logic
34
+ * return myUserService.getById(userId);
35
+ * },
36
+ * });
37
+ *
38
+ * const result = await custom.authenticateToken(token);
39
+ * ```
40
+ */
41
+ export declare class CustomAuthProvider extends BaseAuthProvider {
42
+ readonly type: "custom";
43
+ private validateTokenFn;
44
+ private getUserFn?;
45
+ private createSessionFn?;
46
+ constructor(config: AuthProviderConfig & CustomAuthConfig);
47
+ /**
48
+ * Validate token using custom function
49
+ */
50
+ authenticateToken(token: string, context?: AuthRequestContext): Promise<TokenValidationResult>;
51
+ /**
52
+ * Create a new session.
53
+ * Uses custom function if provided, otherwise delegates to BaseAuthProvider.
54
+ */
55
+ createSession(user: AuthUser, context?: AuthRequestContext): Promise<AuthSession>;
56
+ /**
57
+ * Get user by ID using custom function
58
+ */
59
+ getUser(userId: string): Promise<AuthUser | null>;
60
+ /**
61
+ * Health check - always healthy for custom provider
62
+ */
63
+ healthCheck(): Promise<AuthHealthCheck>;
64
+ }
@@ -0,0 +1,113 @@
1
+ // src/lib/auth/providers/custom.ts
2
+ import { logger } from "../../utils/logger.js";
3
+ import { AuthError } from "../errors.js";
4
+ import { BaseAuthProvider } from "./BaseAuthProvider.js";
5
+ /**
6
+ * Custom Authentication Provider
7
+ *
8
+ * Allows users to provide their own authentication logic through callback functions.
9
+ * Useful for integrating with custom auth systems or implementing unique auth flows.
10
+ *
11
+ * Features:
12
+ * - Custom token validation via callback
13
+ * - Custom user fetching (optional)
14
+ * - Custom session creation (optional, delegates to base when not provided)
15
+ * - Session management (inherited from BaseAuthProvider)
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * const custom = new CustomAuthProvider({
20
+ * type: "custom",
21
+ * validateToken: async (token, context) => {
22
+ * // Your custom token validation logic
23
+ * const decoded = await myAuthService.verify(token);
24
+ * return {
25
+ * valid: !!decoded,
26
+ * user: decoded ? {
27
+ * id: decoded.sub,
28
+ * email: decoded.email,
29
+ * roles: decoded.roles || [],
30
+ * permissions: decoded.permissions || [],
31
+ * } : undefined,
32
+ * };
33
+ * },
34
+ * getUser: async (userId) => {
35
+ * // Your custom user fetching logic
36
+ * return myUserService.getById(userId);
37
+ * },
38
+ * });
39
+ *
40
+ * const result = await custom.authenticateToken(token);
41
+ * ```
42
+ */
43
+ export class CustomAuthProvider extends BaseAuthProvider {
44
+ type = "custom";
45
+ validateTokenFn;
46
+ getUserFn;
47
+ createSessionFn;
48
+ constructor(config) {
49
+ super(config);
50
+ if (!config.validateToken) {
51
+ throw AuthError.create("CONFIGURATION_ERROR", "Custom validateToken function is required", { details: { provider: "custom", missingFields: ["validateToken"] } });
52
+ }
53
+ this.validateTokenFn = config.validateToken;
54
+ this.getUserFn = config.getUser;
55
+ this.createSessionFn = config.createSession;
56
+ }
57
+ /**
58
+ * Validate token using custom function
59
+ */
60
+ async authenticateToken(token, context) {
61
+ try {
62
+ return await this.validateTokenFn(token, context);
63
+ }
64
+ catch (error) {
65
+ return {
66
+ valid: false,
67
+ error: error instanceof Error ? error.message : String(error),
68
+ };
69
+ }
70
+ }
71
+ /**
72
+ * Create a new session.
73
+ * Uses custom function if provided, otherwise delegates to BaseAuthProvider.
74
+ */
75
+ async createSession(user, context) {
76
+ if (this.createSessionFn) {
77
+ const session = await this.createSessionFn(user, context);
78
+ await this.sessionStorage.save(session);
79
+ this.emit("auth:login", session.user);
80
+ return session;
81
+ }
82
+ // Delegate to base class session creation
83
+ return super.createSession(user, context);
84
+ }
85
+ /**
86
+ * Get user by ID using custom function
87
+ */
88
+ async getUser(userId) {
89
+ if (this.getUserFn) {
90
+ try {
91
+ return await this.getUserFn(userId);
92
+ }
93
+ catch (error) {
94
+ logger.error("Custom getUser failed:", error);
95
+ return null;
96
+ }
97
+ }
98
+ // No custom user fetching, return null
99
+ logger.warn("Custom getUser function not provided");
100
+ return null;
101
+ }
102
+ /**
103
+ * Health check - always healthy for custom provider
104
+ */
105
+ async healthCheck() {
106
+ return {
107
+ healthy: true,
108
+ providerConnected: true,
109
+ sessionStorageHealthy: true,
110
+ };
111
+ }
112
+ }
113
+ //# sourceMappingURL=custom.js.map
@@ -0,0 +1,63 @@
1
+ import { BaseAuthProvider } from "./BaseAuthProvider.js";
2
+ import type { AuthProviderConfig, FirebaseConfig, AuthUser, TokenValidationResult, AuthRequestContext, AuthHealthCheck, AuthProviderType } from "../../types/authTypes.js";
3
+ /**
4
+ * Firebase Authentication Provider
5
+ *
6
+ * Supports Firebase ID token validation using Google's public keys.
7
+ * Can validate tokens locally or via Firebase REST API.
8
+ *
9
+ * Features:
10
+ * - JWT validation using Google's public keys
11
+ * - Token verification via Firebase REST API
12
+ * - Custom claims extraction for roles/permissions
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * const firebase = new FirebaseAuthProvider({
17
+ * type: "firebase",
18
+ * projectId: "your-project-id"
19
+ * });
20
+ *
21
+ * const result = await firebase.authenticateToken(idToken);
22
+ * if (result.valid) {
23
+ * console.log("Authenticated user:", result.user);
24
+ * }
25
+ * ```
26
+ */
27
+ export declare class FirebaseAuthProvider extends BaseAuthProvider {
28
+ readonly type: AuthProviderType;
29
+ private projectId;
30
+ private apiKey?;
31
+ private serviceAccount?;
32
+ private jwks;
33
+ constructor(config: AuthProviderConfig & FirebaseConfig);
34
+ /**
35
+ * Initialize JWKS for Firebase token verification
36
+ */
37
+ initialize(): Promise<void>;
38
+ /**
39
+ * Validate Firebase ID token
40
+ */
41
+ authenticateToken(token: string, _context?: AuthRequestContext): Promise<TokenValidationResult>;
42
+ /**
43
+ * Validate token via Firebase REST API
44
+ */
45
+ private validateViaApi;
46
+ /**
47
+ * Convert JWT payload to AuthUser
48
+ */
49
+ private payloadToUser;
50
+ /**
51
+ * Convert Firebase user data to AuthUser
52
+ */
53
+ private firebaseUserToAuthUser;
54
+ /**
55
+ * Get user by ID via Firebase REST API
56
+ * Requires API key
57
+ */
58
+ getUser(_userId: string): Promise<AuthUser | null>;
59
+ /**
60
+ * Health check
61
+ */
62
+ healthCheck(): Promise<AuthHealthCheck>;
63
+ }