@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.
- package/CHANGELOG.md +6 -0
- package/dist/auth/AuthProviderFactory.d.ts +71 -0
- package/dist/auth/AuthProviderFactory.js +111 -0
- package/dist/auth/AuthProviderRegistry.d.ts +33 -0
- package/dist/auth/AuthProviderRegistry.js +190 -0
- package/dist/auth/RequestContext.d.ts +23 -0
- package/dist/auth/RequestContext.js +78 -0
- package/dist/auth/authContext.d.ts +198 -0
- package/dist/auth/authContext.js +314 -0
- package/dist/auth/errors.d.ts +63 -0
- package/dist/auth/errors.js +39 -0
- package/dist/auth/index.d.ts +20 -8
- package/dist/auth/index.js +35 -7
- package/dist/auth/middleware/AuthMiddleware.d.ts +181 -0
- package/dist/auth/middleware/AuthMiddleware.js +519 -0
- package/dist/auth/middleware/rateLimitByUser.d.ts +282 -0
- package/dist/auth/middleware/rateLimitByUser.js +554 -0
- package/dist/auth/providers/BaseAuthProvider.d.ts +259 -0
- package/dist/auth/providers/BaseAuthProvider.js +723 -0
- package/dist/auth/providers/CognitoProvider.d.ts +61 -0
- package/dist/auth/providers/CognitoProvider.js +304 -0
- package/dist/auth/providers/KeycloakProvider.d.ts +61 -0
- package/dist/auth/providers/KeycloakProvider.js +393 -0
- package/dist/auth/providers/auth0.d.ts +59 -0
- package/dist/auth/providers/auth0.js +274 -0
- package/dist/auth/providers/betterAuth.d.ts +51 -0
- package/dist/auth/providers/betterAuth.js +182 -0
- package/dist/auth/providers/clerk.d.ts +65 -0
- package/dist/auth/providers/clerk.js +317 -0
- package/dist/auth/providers/custom.d.ts +64 -0
- package/dist/auth/providers/custom.js +112 -0
- package/dist/auth/providers/firebase.d.ts +63 -0
- package/dist/auth/providers/firebase.js +226 -0
- package/dist/auth/providers/jwt.d.ts +68 -0
- package/dist/auth/providers/jwt.js +212 -0
- package/dist/auth/providers/oauth2.d.ts +73 -0
- package/dist/auth/providers/oauth2.js +303 -0
- package/dist/auth/providers/supabase.d.ts +63 -0
- package/dist/auth/providers/supabase.js +259 -0
- package/dist/auth/providers/workos.d.ts +61 -0
- package/dist/auth/providers/workos.js +284 -0
- package/dist/auth/serverBridge.d.ts +14 -0
- package/dist/auth/serverBridge.js +25 -0
- package/dist/auth/sessionManager.d.ts +142 -0
- package/dist/auth/sessionManager.js +437 -0
- package/dist/cli/commands/authProviders.d.ts +43 -0
- package/dist/cli/commands/authProviders.js +399 -0
- package/dist/cli/factories/authCommandFactory.d.ts +23 -5
- package/dist/cli/factories/authCommandFactory.js +108 -5
- package/dist/cli/parser.js +1 -1
- package/dist/client/auth/AuthProviderFactory.js +111 -0
- package/dist/client/auth/AuthProviderRegistry.js +190 -0
- package/dist/client/auth/RequestContext.js +78 -0
- package/dist/client/auth/accountPool.js +178 -0
- package/dist/client/auth/authContext.js +314 -0
- package/dist/client/auth/errors.js +39 -0
- package/dist/client/auth/index.js +61 -0
- package/dist/client/auth/middleware/AuthMiddleware.js +519 -0
- package/dist/client/auth/middleware/rateLimitByUser.js +554 -0
- package/dist/client/auth/providers/BaseAuthProvider.js +723 -0
- package/dist/client/auth/providers/CognitoProvider.js +304 -0
- package/dist/client/auth/providers/KeycloakProvider.js +393 -0
- package/dist/client/auth/providers/auth0.js +274 -0
- package/dist/client/auth/providers/betterAuth.js +182 -0
- package/dist/client/auth/providers/clerk.js +317 -0
- package/dist/client/auth/providers/custom.js +112 -0
- package/dist/client/auth/providers/firebase.js +226 -0
- package/dist/client/auth/providers/jwt.js +212 -0
- package/dist/client/auth/providers/oauth2.js +303 -0
- package/dist/client/auth/providers/supabase.js +259 -0
- package/dist/client/auth/providers/workos.js +284 -0
- package/dist/client/auth/serverBridge.js +25 -0
- package/dist/client/auth/sessionManager.js +437 -0
- package/dist/client/core/infrastructure/baseRegistry.js +5 -1
- package/dist/client/index.js +25 -0
- package/dist/client/mcp/toolRegistry.js +11 -1
- package/dist/client/neurolink.js +218 -0
- package/dist/client/rag/ChunkerRegistry.js +2 -2
- package/dist/client/rag/metadata/MetadataExtractorRegistry.js +2 -2
- package/dist/client/rag/reranker/RerankerRegistry.js +2 -2
- package/dist/client/server/routes/agentRoutes.js +20 -2
- package/dist/client/types/authTypes.js +2 -1
- package/dist/core/infrastructure/baseRegistry.d.ts +3 -1
- package/dist/core/infrastructure/baseRegistry.js +5 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +25 -0
- package/dist/lib/auth/AuthProviderFactory.d.ts +71 -0
- package/dist/lib/auth/AuthProviderFactory.js +112 -0
- package/dist/lib/auth/AuthProviderRegistry.d.ts +33 -0
- package/dist/lib/auth/AuthProviderRegistry.js +191 -0
- package/dist/lib/auth/RequestContext.d.ts +23 -0
- package/dist/lib/auth/RequestContext.js +79 -0
- package/dist/lib/auth/authContext.d.ts +198 -0
- package/dist/lib/auth/authContext.js +315 -0
- package/dist/lib/auth/errors.d.ts +63 -0
- package/dist/lib/auth/errors.js +40 -0
- package/dist/lib/auth/index.d.ts +20 -8
- package/dist/lib/auth/index.js +35 -7
- package/dist/lib/auth/middleware/AuthMiddleware.d.ts +181 -0
- package/dist/lib/auth/middleware/AuthMiddleware.js +520 -0
- package/dist/lib/auth/middleware/rateLimitByUser.d.ts +282 -0
- package/dist/lib/auth/middleware/rateLimitByUser.js +555 -0
- package/dist/lib/auth/providers/BaseAuthProvider.d.ts +259 -0
- package/dist/lib/auth/providers/BaseAuthProvider.js +724 -0
- package/dist/lib/auth/providers/CognitoProvider.d.ts +61 -0
- package/dist/lib/auth/providers/CognitoProvider.js +305 -0
- package/dist/lib/auth/providers/KeycloakProvider.d.ts +61 -0
- package/dist/lib/auth/providers/KeycloakProvider.js +394 -0
- package/dist/lib/auth/providers/auth0.d.ts +59 -0
- package/dist/lib/auth/providers/auth0.js +275 -0
- package/dist/lib/auth/providers/betterAuth.d.ts +51 -0
- package/dist/lib/auth/providers/betterAuth.js +183 -0
- package/dist/lib/auth/providers/clerk.d.ts +65 -0
- package/dist/lib/auth/providers/clerk.js +318 -0
- package/dist/lib/auth/providers/custom.d.ts +64 -0
- package/dist/lib/auth/providers/custom.js +113 -0
- package/dist/lib/auth/providers/firebase.d.ts +63 -0
- package/dist/lib/auth/providers/firebase.js +227 -0
- package/dist/lib/auth/providers/jwt.d.ts +68 -0
- package/dist/lib/auth/providers/jwt.js +213 -0
- package/dist/lib/auth/providers/oauth2.d.ts +73 -0
- package/dist/lib/auth/providers/oauth2.js +304 -0
- package/dist/lib/auth/providers/supabase.d.ts +63 -0
- package/dist/lib/auth/providers/supabase.js +260 -0
- package/dist/lib/auth/providers/workos.d.ts +61 -0
- package/dist/lib/auth/providers/workos.js +285 -0
- package/dist/lib/auth/serverBridge.d.ts +14 -0
- package/dist/lib/auth/serverBridge.js +26 -0
- package/dist/lib/auth/sessionManager.d.ts +142 -0
- package/dist/lib/auth/sessionManager.js +438 -0
- package/dist/lib/core/infrastructure/baseRegistry.d.ts +3 -1
- package/dist/lib/core/infrastructure/baseRegistry.js +5 -1
- package/dist/lib/index.d.ts +1 -0
- package/dist/lib/index.js +25 -0
- package/dist/lib/mcp/toolRegistry.js +11 -1
- package/dist/lib/neurolink.d.ts +42 -1
- package/dist/lib/neurolink.js +218 -0
- package/dist/lib/rag/ChunkerRegistry.js +2 -2
- package/dist/lib/rag/metadata/MetadataExtractorRegistry.js +2 -2
- package/dist/lib/rag/reranker/RerankerRegistry.js +2 -2
- package/dist/lib/server/routes/agentRoutes.js +20 -2
- package/dist/lib/types/authTypes.d.ts +937 -1
- package/dist/lib/types/authTypes.js +2 -1
- package/dist/lib/types/configTypes.d.ts +46 -0
- package/dist/lib/types/generateTypes.d.ts +6 -0
- package/dist/lib/types/index.d.ts +1 -0
- package/dist/lib/types/streamTypes.d.ts +6 -0
- package/dist/mcp/toolRegistry.js +11 -1
- package/dist/neurolink.d.ts +42 -1
- package/dist/neurolink.js +218 -0
- package/dist/rag/ChunkerRegistry.js +2 -2
- package/dist/rag/metadata/MetadataExtractorRegistry.js +2 -2
- package/dist/rag/reranker/RerankerRegistry.js +2 -2
- package/dist/server/routes/agentRoutes.js +20 -2
- package/dist/types/authTypes.d.ts +937 -1
- package/dist/types/authTypes.js +2 -1
- package/dist/types/configTypes.d.ts +46 -0
- package/dist/types/generateTypes.d.ts +6 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/streamTypes.d.ts +6 -0
- package/package.json +2 -1
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CognitoProvider - AWS Cognito User Pools provider implementation
|
|
3
|
+
*
|
|
4
|
+
* Provides JWT validation, session management, and RBAC for AWS Cognito.
|
|
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
|
+
// COGNITO PROVIDER
|
|
13
|
+
// =============================================================================
|
|
14
|
+
/**
|
|
15
|
+
* CognitoProvider - AWS Cognito User Pools integration
|
|
16
|
+
*
|
|
17
|
+
* Features:
|
|
18
|
+
* - Cognito ID token and access token validation
|
|
19
|
+
* - JWKS-based signature verification
|
|
20
|
+
* - Cognito groups for roles
|
|
21
|
+
* - Custom attributes support
|
|
22
|
+
* - Session management
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```typescript
|
|
26
|
+
* const provider = new CognitoProvider({
|
|
27
|
+
* type: 'cognito',
|
|
28
|
+
* userPoolId: 'us-east-1_xxxxx',
|
|
29
|
+
* clientId: 'your-client-id',
|
|
30
|
+
* region: 'us-east-1',
|
|
31
|
+
* });
|
|
32
|
+
*
|
|
33
|
+
* const result = await provider.authenticateToken(idToken);
|
|
34
|
+
* if (result.valid) {
|
|
35
|
+
* console.log('User:', result.user);
|
|
36
|
+
* }
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
export class CognitoProvider extends BaseAuthProvider {
|
|
40
|
+
type = "cognito";
|
|
41
|
+
cognitoConfig;
|
|
42
|
+
jwksUri;
|
|
43
|
+
jwksCacheDuration;
|
|
44
|
+
expectedIssuer;
|
|
45
|
+
constructor(config) {
|
|
46
|
+
super(config);
|
|
47
|
+
if (config.type !== "cognito") {
|
|
48
|
+
throw AuthError.create("CONFIGURATION_ERROR", `Invalid provider type: ${config.type}. Expected: cognito`);
|
|
49
|
+
}
|
|
50
|
+
this.cognitoConfig = config;
|
|
51
|
+
if (!this.cognitoConfig.userPoolId) {
|
|
52
|
+
throw AuthError.create("CONFIGURATION_ERROR", "Cognito userPoolId is required");
|
|
53
|
+
}
|
|
54
|
+
if (!this.cognitoConfig.clientId) {
|
|
55
|
+
throw AuthError.create("CONFIGURATION_ERROR", "Cognito clientId is required");
|
|
56
|
+
}
|
|
57
|
+
if (!this.cognitoConfig.region) {
|
|
58
|
+
throw AuthError.create("CONFIGURATION_ERROR", "Cognito region is required");
|
|
59
|
+
}
|
|
60
|
+
// Set up JWKS URI and issuer
|
|
61
|
+
this.expectedIssuer = `https://cognito-idp.${this.cognitoConfig.region}.amazonaws.com/${this.cognitoConfig.userPoolId}`;
|
|
62
|
+
this.jwksUri = `${this.expectedIssuer}/.well-known/jwks.json`;
|
|
63
|
+
this.jwksCacheDuration =
|
|
64
|
+
config.tokenValidation?.jwksCacheDuration ?? 600000; // 10 minutes
|
|
65
|
+
logger.debug(`[CognitoProvider] Initialized for user pool: ${this.cognitoConfig.userPoolId}`);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Validate and authenticate a Cognito JWT token
|
|
69
|
+
*/
|
|
70
|
+
async authenticateToken(token) {
|
|
71
|
+
try {
|
|
72
|
+
// Parse token without verification first
|
|
73
|
+
const claims = this.parseJWT(token);
|
|
74
|
+
if (!claims) {
|
|
75
|
+
return {
|
|
76
|
+
valid: false,
|
|
77
|
+
error: "Failed to decode token",
|
|
78
|
+
errorCode: "AUTH-006",
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
// Validate issuer
|
|
82
|
+
if (claims.iss !== this.expectedIssuer) {
|
|
83
|
+
return {
|
|
84
|
+
valid: false,
|
|
85
|
+
error: `Invalid issuer: ${claims.iss}. Expected: ${this.expectedIssuer}`,
|
|
86
|
+
errorCode: "AUTH-001",
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
// Validate token_use (id or access)
|
|
90
|
+
const tokenUse = claims.token_use;
|
|
91
|
+
if (tokenUse !== "id" && tokenUse !== "access") {
|
|
92
|
+
return {
|
|
93
|
+
valid: false,
|
|
94
|
+
error: `Invalid token_use: ${tokenUse}. Expected: id or access`,
|
|
95
|
+
errorCode: "AUTH-001",
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
// Validate client_id for ID tokens, or client_id in aud for access tokens
|
|
99
|
+
if (tokenUse === "id") {
|
|
100
|
+
if (claims.aud !== this.cognitoConfig.clientId) {
|
|
101
|
+
return {
|
|
102
|
+
valid: false,
|
|
103
|
+
error: `Invalid audience: ${claims.aud}. Expected: ${this.cognitoConfig.clientId}`,
|
|
104
|
+
errorCode: "AUTH-001",
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
// Access tokens have client_id claim
|
|
110
|
+
if (claims.client_id !== this.cognitoConfig.clientId) {
|
|
111
|
+
return {
|
|
112
|
+
valid: false,
|
|
113
|
+
error: `Invalid client_id: ${claims.client_id}. Expected: ${this.cognitoConfig.clientId}`,
|
|
114
|
+
errorCode: "AUTH-001",
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
// Check expiration
|
|
119
|
+
const clockTolerance = this.config.tokenValidation?.clockTolerance ?? 30;
|
|
120
|
+
if (this.isTokenExpired(claims, clockTolerance)) {
|
|
121
|
+
return {
|
|
122
|
+
valid: false,
|
|
123
|
+
error: "Token has expired",
|
|
124
|
+
errorCode: "AUTH-002",
|
|
125
|
+
expiresAt: claims.exp ? new Date(claims.exp * 1000) : undefined,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
// Verify signature if enabled
|
|
129
|
+
if (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.extractCognitoUser(claims, tokenUse);
|
|
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(`[CognitoProvider] 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("[CognitoProvider] 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(`[CognitoProvider] 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(`[CognitoProvider] 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 Cognito-specific user data from claims
|
|
229
|
+
*/
|
|
230
|
+
extractCognitoUser(claims, tokenUse) {
|
|
231
|
+
// User ID (sub claim)
|
|
232
|
+
const userId = claims.sub ?? "";
|
|
233
|
+
// Email (from ID token or custom attributes)
|
|
234
|
+
const email = claims.email ?? claims["custom:email"];
|
|
235
|
+
// Name (various possible claims)
|
|
236
|
+
const name = claims.name ??
|
|
237
|
+
claims["cognito:username"] ??
|
|
238
|
+
claims.preferred_username;
|
|
239
|
+
// Picture (custom attribute)
|
|
240
|
+
const picture = claims.picture ?? claims["custom:picture"];
|
|
241
|
+
// Get roles from Cognito groups
|
|
242
|
+
let roles = [];
|
|
243
|
+
const cognitoGroups = claims["cognito:groups"];
|
|
244
|
+
if (cognitoGroups && Array.isArray(cognitoGroups)) {
|
|
245
|
+
roles = cognitoGroups;
|
|
246
|
+
}
|
|
247
|
+
// Apply default roles
|
|
248
|
+
if (roles.length === 0 && this.rbacConfig.defaultRoles) {
|
|
249
|
+
roles = this.rbacConfig.defaultRoles;
|
|
250
|
+
}
|
|
251
|
+
// Extract custom attributes as permissions if configured
|
|
252
|
+
const permissions = [];
|
|
253
|
+
if (this.cognitoConfig.customAttributes) {
|
|
254
|
+
for (const attr of this.cognitoConfig.customAttributes) {
|
|
255
|
+
const value = claims[`custom:${attr}`];
|
|
256
|
+
if (value) {
|
|
257
|
+
// If it looks like a comma-separated list, split it
|
|
258
|
+
if (value.includes(",")) {
|
|
259
|
+
permissions.push(...value.split(",").map((p) => p.trim()));
|
|
260
|
+
}
|
|
261
|
+
else {
|
|
262
|
+
permissions.push(value);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
// Build provider data, filtering out undefined values
|
|
268
|
+
const providerData = {
|
|
269
|
+
provider: "cognito",
|
|
270
|
+
};
|
|
271
|
+
if (claims["cognito:username"] !== undefined) {
|
|
272
|
+
providerData.username = claims["cognito:username"];
|
|
273
|
+
}
|
|
274
|
+
providerData.token_use = tokenUse;
|
|
275
|
+
if (claims.auth_time !== undefined) {
|
|
276
|
+
providerData.auth_time = claims.auth_time;
|
|
277
|
+
}
|
|
278
|
+
const clientId = claims.client_id ?? claims.aud;
|
|
279
|
+
if (clientId !== undefined) {
|
|
280
|
+
providerData.client_id = clientId;
|
|
281
|
+
}
|
|
282
|
+
if (cognitoGroups !== undefined) {
|
|
283
|
+
providerData.cognito_groups = cognitoGroups;
|
|
284
|
+
}
|
|
285
|
+
return {
|
|
286
|
+
id: userId,
|
|
287
|
+
email,
|
|
288
|
+
name,
|
|
289
|
+
picture,
|
|
290
|
+
roles,
|
|
291
|
+
permissions,
|
|
292
|
+
emailVerified: claims.email_verified,
|
|
293
|
+
providerData,
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Get user from Cognito
|
|
298
|
+
* Note: Requires AWS SDK for full implementation
|
|
299
|
+
*/
|
|
300
|
+
async getUser(_userId) {
|
|
301
|
+
logger.debug("[CognitoProvider] getUser() is not implemented. Requires AWS SDK (@aws-sdk/client-cognito-identity-provider).");
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
@@ -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
|
+
}
|