@payez/next-mvp 3.1.0 → 3.1.1
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.
|
@@ -1,305 +1,305 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* JWT Callback
|
|
4
|
-
*
|
|
5
|
-
* Minimal token strategy - only store redisSessionId in JWT.
|
|
6
|
-
* All session data lives in Redis, not in the browser cookie.
|
|
7
|
-
*
|
|
8
|
-
* HANDLES:
|
|
9
|
-
* - Initial sign-in (credentials): Store redisSessionId from authorize()
|
|
10
|
-
* - Initial sign-in (OAuth): Register with IDP, create session, store redisSessionId
|
|
11
|
-
* - Subsequent requests: Validate session exists, return token
|
|
12
|
-
*
|
|
13
|
-
* @version 1.0.0
|
|
14
|
-
* @since auth-refactor-2026-01
|
|
15
|
-
*/
|
|
16
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.jwtCallback = jwtCallback;
|
|
18
|
-
const crypto_1 = require("crypto");
|
|
19
|
-
const session_store_1 = require("../../lib/session-store");
|
|
20
|
-
const idp_client_config_1 = require("../../lib/idp-client-config");
|
|
21
|
-
const idp_client_1 = require("../utils/idp-client");
|
|
22
|
-
const token_utils_1 = require("../utils/token-utils");
|
|
23
|
-
// NOTE: Using any for sessionData until Phase 3 normalizes types
|
|
24
|
-
// ============================================================================
|
|
25
|
-
// VIBE ROLE FETCHING
|
|
26
|
-
// ============================================================================
|
|
27
|
-
/**
|
|
28
|
-
* Generate HMAC signature for Vibe API request.
|
|
29
|
-
*/
|
|
30
|
-
function generateVibeSignature(endpoint, clientId, timestamp) {
|
|
31
|
-
const signingKey = process.env.VIBE_SIGNING_KEY;
|
|
32
|
-
if (!signingKey) {
|
|
33
|
-
return '';
|
|
34
|
-
}
|
|
35
|
-
const stringToSign = `${timestamp}|GET|${endpoint}|${clientId}`;
|
|
36
|
-
return (0, crypto_1.createHmac)('sha256', Buffer.from(signingKey, 'base64'))
|
|
37
|
-
.update(stringToSign)
|
|
38
|
-
.digest('base64');
|
|
39
|
-
}
|
|
40
|
-
/**
|
|
41
|
-
* Fetch user's roles from Vibe API.
|
|
42
|
-
* Returns empty array on failure (non-blocking).
|
|
43
|
-
* Uses HMAC signature for authentication when signing key is configured.
|
|
44
|
-
*/
|
|
45
|
-
async function fetchVibeRoles(userId, clientId) {
|
|
46
|
-
const vibeApiUrl = process.env.VIBE_API_URL;
|
|
47
|
-
if (!vibeApiUrl) {
|
|
48
|
-
return [];
|
|
49
|
-
}
|
|
50
|
-
const endpoint = `/api/v1/users/${userId}/roles`;
|
|
51
|
-
const timestamp = Math.floor(Date.now() / 1000);
|
|
52
|
-
const signature = generateVibeSignature(endpoint, clientId, timestamp);
|
|
53
|
-
// Build headers with optional signature
|
|
54
|
-
const headers = {
|
|
55
|
-
'Accept': 'application/json',
|
|
56
|
-
'X-Client-Id': clientId,
|
|
57
|
-
'X-Vibe-Client-Id': clientId,
|
|
58
|
-
};
|
|
59
|
-
if (signature) {
|
|
60
|
-
headers['X-Vibe-Timestamp'] = String(timestamp);
|
|
61
|
-
headers['X-Vibe-Signature'] = signature;
|
|
62
|
-
}
|
|
63
|
-
try {
|
|
64
|
-
const response = await fetch(`${vibeApiUrl}${endpoint}`, {
|
|
65
|
-
method: 'GET',
|
|
66
|
-
headers,
|
|
67
|
-
// 2 second timeout
|
|
68
|
-
signal: AbortSignal.timeout(2000),
|
|
69
|
-
});
|
|
70
|
-
if (!response.ok) {
|
|
71
|
-
console.warn('[JWT_CALLBACK] Failed to fetch Vibe roles:', response.status);
|
|
72
|
-
return [];
|
|
73
|
-
}
|
|
74
|
-
const data = await response.json();
|
|
75
|
-
const roles = data.roles?.map((r) => r.role_name || r) || [];
|
|
76
|
-
console.log('[JWT_CALLBACK] Fetched Vibe roles:', roles);
|
|
77
|
-
return roles;
|
|
78
|
-
}
|
|
79
|
-
catch (error) {
|
|
80
|
-
console.warn('[JWT_CALLBACK] Error fetching Vibe roles (continuing with IDP roles only):', error);
|
|
81
|
-
return [];
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
/**
|
|
85
|
-
* Merge IDP roles with Vibe roles, deduplicating.
|
|
86
|
-
*/
|
|
87
|
-
function mergeRoles(idpRoles, vibeRoles) {
|
|
88
|
-
return [...new Set([...idpRoles, ...vibeRoles])];
|
|
89
|
-
}
|
|
90
|
-
// ============================================================================
|
|
91
|
-
// JWT CALLBACK
|
|
92
|
-
// ============================================================================
|
|
93
|
-
/**
|
|
94
|
-
* JWT callback - builds the NextAuth JWT token.
|
|
95
|
-
*
|
|
96
|
-
* MINIMAL TOKEN STRATEGY:
|
|
97
|
-
* - Only store redisSessionId (key to Redis session)
|
|
98
|
-
* - All tokens and user data live in Redis
|
|
99
|
-
* - Browser cookie stays small and secure
|
|
100
|
-
*
|
|
101
|
-
* @param params - JWT callback parameters from NextAuth
|
|
102
|
-
* @returns JWT payload to store in browser cookie
|
|
103
|
-
*/
|
|
104
|
-
async function jwtCallback({ token, user, account, trigger, }) {
|
|
105
|
-
console.log('[JWT_CALLBACK] Called with:', {
|
|
106
|
-
trigger,
|
|
107
|
-
hasAccount: !!account,
|
|
108
|
-
provider: account?.provider,
|
|
109
|
-
hasUser: !!user,
|
|
110
|
-
userEmail: user?.email,
|
|
111
|
-
existingRedisSessionId: token?.redisSessionId ? 'yes' : 'no',
|
|
112
|
-
});
|
|
113
|
-
// -------------------------------------------------------------------------
|
|
114
|
-
// OAuth Sign-In: Register with IDP and create session
|
|
115
|
-
// -------------------------------------------------------------------------
|
|
116
|
-
if (account && account.provider !== 'credentials') {
|
|
117
|
-
console.log('[JWT_CALLBACK] Handling OAuth sign-in for provider:', account.provider);
|
|
118
|
-
return handleOAuthSignIn(token, user, account);
|
|
119
|
-
}
|
|
120
|
-
// -------------------------------------------------------------------------
|
|
121
|
-
// Credentials Sign-In: Session already created in authorize()
|
|
122
|
-
// -------------------------------------------------------------------------
|
|
123
|
-
if (user && user.redisSessionId) {
|
|
124
|
-
// Credentials authorize() returns redisSessionId
|
|
125
|
-
const redisSessionId = user.redisSessionId;
|
|
126
|
-
return {
|
|
127
|
-
...token,
|
|
128
|
-
redisSessionId,
|
|
129
|
-
sub: user.id || token.sub || 'unknown',
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
// -------------------------------------------------------------------------
|
|
133
|
-
// Subsequent Requests: Validate session exists
|
|
134
|
-
// -------------------------------------------------------------------------
|
|
135
|
-
const redisSessionId = user?.redisSessionId || token?.redisSessionId || token?.redisSessionId;
|
|
136
|
-
if (!redisSessionId) {
|
|
137
|
-
return { ...token, error: 'NoSession', sub: token.sub || 'unknown' };
|
|
138
|
-
}
|
|
139
|
-
// Validate session still exists in Redis
|
|
140
|
-
try {
|
|
141
|
-
const sessionData = await (0, session_store_1.getSession)(redisSessionId);
|
|
142
|
-
if (!sessionData) {
|
|
143
|
-
// Session expired or deleted
|
|
144
|
-
return { ...token, error: 'SessionNotFound', sub: token.sub || 'unknown' };
|
|
145
|
-
}
|
|
146
|
-
// Check if refresh token has expired (session should be terminated)
|
|
147
|
-
if (sessionData.idpRefreshTokenExpires && Date.now() >= sessionData.idpRefreshTokenExpires) {
|
|
148
|
-
return { ...token, error: 'RefreshTokenExpired', sub: token.sub || 'unknown' };
|
|
149
|
-
}
|
|
150
|
-
// Check if MFA has expired (requires step-up authentication)
|
|
151
|
-
if (sessionData.mfaExpiresAt && Date.now() > sessionData.mfaExpiresAt) {
|
|
152
|
-
return {
|
|
153
|
-
...token,
|
|
154
|
-
redisSessionId,
|
|
155
|
-
sub: sessionData.userId,
|
|
156
|
-
error: 'MfaExpired',
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
catch (error) {
|
|
161
|
-
console.error('[JWT_CALLBACK] Session validation error:', error);
|
|
162
|
-
return { ...token, error: 'SessionError', sub: token.sub || 'unknown' };
|
|
163
|
-
}
|
|
164
|
-
// Session is valid - return minimal token
|
|
165
|
-
return {
|
|
166
|
-
...token,
|
|
167
|
-
redisSessionId,
|
|
168
|
-
sub: token.sub || 'unknown',
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
// ============================================================================
|
|
172
|
-
// OAUTH SIGN-IN HANDLER
|
|
173
|
-
// ============================================================================
|
|
174
|
-
/**
|
|
175
|
-
* Handle OAuth sign-in by registering with IDP and creating session.
|
|
176
|
-
*/
|
|
177
|
-
async function handleOAuthSignIn(token, user, account) {
|
|
178
|
-
console.log('[JWT_CALLBACK] handleOAuthSignIn starting for:', {
|
|
179
|
-
provider: account.provider,
|
|
180
|
-
email: user?.email,
|
|
181
|
-
providerAccountId: account.providerAccountId,
|
|
182
|
-
});
|
|
183
|
-
try {
|
|
184
|
-
// Call IDP to register/authenticate OAuth user
|
|
185
|
-
const idpResult = await (0, idp_client_1.idpOAuthCallback)({
|
|
186
|
-
provider: account.provider,
|
|
187
|
-
providerAccountId: account.providerAccountId,
|
|
188
|
-
email: user?.email || '',
|
|
189
|
-
name: user?.name || '',
|
|
190
|
-
image: user?.image || '',
|
|
191
|
-
accessToken: account.access_token,
|
|
192
|
-
refreshToken: account.refresh_token,
|
|
193
|
-
expiresAt: account.expires_at,
|
|
194
|
-
});
|
|
195
|
-
// Build session data using normalized field names
|
|
196
|
-
let sessionData;
|
|
197
|
-
let mfaVerified = false;
|
|
198
|
-
if (idpResult.success && idpResult.data?.accessToken) {
|
|
199
|
-
// IDP integration succeeded - we have IDP tokens
|
|
200
|
-
const decoded = (0, token_utils_1.decodeIdpAccessToken)(idpResult.data.accessToken);
|
|
201
|
-
const amrClaims = decoded ? (0, token_utils_1.extractAmrFromToken)(decoded) : [];
|
|
202
|
-
const acrLevel = decoded?.acr || '1';
|
|
203
|
-
// Extract kid from JWT header (CRITICAL: different from client_id in payload)
|
|
204
|
-
const bearerKeyId = (0, token_utils_1.extractKidFromToken)(idpResult.data.accessToken);
|
|
205
|
-
if (bearerKeyId) {
|
|
206
|
-
console.log('[JWT_CALLBACK] Extracted bearerKeyId (kid) from JWT header:', bearerKeyId);
|
|
207
|
-
}
|
|
208
|
-
else {
|
|
209
|
-
console.warn('[JWT_CALLBACK] No kid found in JWT header');
|
|
210
|
-
}
|
|
211
|
-
// Check if MFA is required for this client
|
|
212
|
-
try {
|
|
213
|
-
const clientConfig = await (0, idp_client_config_1.getIDPClientConfig)();
|
|
214
|
-
const require2FA = clientConfig?.authSettings?.require2FA ?? true;
|
|
215
|
-
mfaVerified = !require2FA; // If MFA not required, mark as verified
|
|
216
|
-
}
|
|
217
|
-
catch {
|
|
218
|
-
// Default to requiring MFA if config unavailable
|
|
219
|
-
mfaVerified = false;
|
|
220
|
-
}
|
|
221
|
-
sessionData = {
|
|
222
|
-
userId: idpResult.data.user?.userId?.toString() || account.providerAccountId,
|
|
223
|
-
email: idpResult.data.user?.email || user?.email || '',
|
|
224
|
-
name: idpResult.data.user?.fullName || user?.name || '',
|
|
225
|
-
roles: idpResult.data.user?.roles || [],
|
|
226
|
-
// IDP tokens (normalized names)
|
|
227
|
-
idpAccessToken: idpResult.data.accessToken,
|
|
228
|
-
idpRefreshToken: idpResult.data.refreshToken,
|
|
229
|
-
idpAccessTokenExpires: decoded?.exp ? (0, token_utils_1.expClaimToMs)(decoded.exp) : Date.now() + 3600000,
|
|
230
|
-
decodedAccessToken: decoded || undefined,
|
|
231
|
-
// Bearer key ID from JWT header (NOT client_id from payload)
|
|
232
|
-
bearerKeyId,
|
|
233
|
-
// MFA state (normalized names)
|
|
234
|
-
mfaVerified,
|
|
235
|
-
authenticationMethods: amrClaims,
|
|
236
|
-
authenticationLevel: acrLevel,
|
|
237
|
-
// OAuth provider info (normalized names)
|
|
238
|
-
oauthProvider: account.provider,
|
|
239
|
-
oauthProviderToken: account.access_token,
|
|
240
|
-
oauthProviderRefreshToken: account.refresh_token,
|
|
241
|
-
// Multi-tenant info
|
|
242
|
-
idpClientId: decoded?.client_id,
|
|
243
|
-
merchantId: decoded?.merchant_id,
|
|
244
|
-
};
|
|
245
|
-
}
|
|
246
|
-
else {
|
|
247
|
-
// IDP integration failed - create OAuth-only session
|
|
248
|
-
// This allows OAuth login to work even if IDP is unavailable
|
|
249
|
-
mfaVerified = true; // OAuth IS multi-factor (Google/Microsoft handle MFA)
|
|
250
|
-
sessionData = {
|
|
251
|
-
userId: account.providerAccountId,
|
|
252
|
-
email: user?.email || '',
|
|
253
|
-
name: user?.name || '',
|
|
254
|
-
roles: [],
|
|
255
|
-
mfaVerified: true, // OAuth IS multi-factor
|
|
256
|
-
oauthProvider: account.provider,
|
|
257
|
-
oauthProviderToken: account.access_token,
|
|
258
|
-
oauthProviderRefreshToken: account.refresh_token,
|
|
259
|
-
idpAccessTokenExpires: account.expires_at
|
|
260
|
-
? account.expires_at * 1000
|
|
261
|
-
: Date.now() + 3600000,
|
|
262
|
-
};
|
|
263
|
-
}
|
|
264
|
-
// -------------------------------------------------------------------------
|
|
265
|
-
// ROLE MERGING: Fetch Vibe roles and merge with IDP roles
|
|
266
|
-
// -------------------------------------------------------------------------
|
|
267
|
-
const clientId = sessionData.idpClientId || process.env.IDP_CLIENT_ID || '';
|
|
268
|
-
if (clientId && sessionData.userId) {
|
|
269
|
-
const vibeRoles = await fetchVibeRoles(sessionData.userId, clientId);
|
|
270
|
-
// SECURITY: Filter out protected IDP-level role prefixes to prevent injection
|
|
271
|
-
const safeVibeRoles = vibeRoles.filter(r => !r.startsWith('payez_'));
|
|
272
|
-
const idpRoles = sessionData.roles || [];
|
|
273
|
-
sessionData.roles = mergeRoles(idpRoles, safeVibeRoles);
|
|
274
|
-
console.log('[JWT_CALLBACK] Merged roles:', {
|
|
275
|
-
idpRoles,
|
|
276
|
-
vibeRoles,
|
|
277
|
-
safeVibeRoles,
|
|
278
|
-
merged: sessionData.roles,
|
|
279
|
-
});
|
|
280
|
-
}
|
|
281
|
-
// Create Redis session
|
|
282
|
-
console.log('[JWT_CALLBACK] Creating Redis session for:', {
|
|
283
|
-
userId: sessionData.userId,
|
|
284
|
-
email: sessionData.email,
|
|
285
|
-
mfaVerified: sessionData.mfaVerified,
|
|
286
|
-
roles: sessionData.roles,
|
|
287
|
-
});
|
|
288
|
-
const redisSessionId = await (0, session_store_1.createSession)(sessionData);
|
|
289
|
-
console.log('[JWT_CALLBACK] Redis session created:', {
|
|
290
|
-
redisSessionId: redisSessionId ? redisSessionId.substring(0, 8) + '...' : 'NONE',
|
|
291
|
-
});
|
|
292
|
-
// Check if immediate MFA redirect is needed
|
|
293
|
-
const needsImmediateTwoFactor = !mfaVerified;
|
|
294
|
-
return {
|
|
295
|
-
...token,
|
|
296
|
-
redisSessionId,
|
|
297
|
-
sub: sessionData.userId,
|
|
298
|
-
requiresTwoFactorRedirect: needsImmediateTwoFactor,
|
|
299
|
-
};
|
|
300
|
-
}
|
|
301
|
-
catch (error) {
|
|
302
|
-
console.error('[JWT_CALLBACK] handleOAuthSignIn FAILED:', error);
|
|
303
|
-
return { ...token, error: 'OAuthSignInFailed', sub: token.sub || 'unknown' };
|
|
304
|
-
}
|
|
305
|
-
}
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* JWT Callback
|
|
4
|
+
*
|
|
5
|
+
* Minimal token strategy - only store redisSessionId in JWT.
|
|
6
|
+
* All session data lives in Redis, not in the browser cookie.
|
|
7
|
+
*
|
|
8
|
+
* HANDLES:
|
|
9
|
+
* - Initial sign-in (credentials): Store redisSessionId from authorize()
|
|
10
|
+
* - Initial sign-in (OAuth): Register with IDP, create session, store redisSessionId
|
|
11
|
+
* - Subsequent requests: Validate session exists, return token
|
|
12
|
+
*
|
|
13
|
+
* @version 1.0.0
|
|
14
|
+
* @since auth-refactor-2026-01
|
|
15
|
+
*/
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.jwtCallback = jwtCallback;
|
|
18
|
+
const crypto_1 = require("crypto");
|
|
19
|
+
const session_store_1 = require("../../lib/session-store");
|
|
20
|
+
const idp_client_config_1 = require("../../lib/idp-client-config");
|
|
21
|
+
const idp_client_1 = require("../utils/idp-client");
|
|
22
|
+
const token_utils_1 = require("../utils/token-utils");
|
|
23
|
+
// NOTE: Using any for sessionData until Phase 3 normalizes types
|
|
24
|
+
// ============================================================================
|
|
25
|
+
// VIBE ROLE FETCHING
|
|
26
|
+
// ============================================================================
|
|
27
|
+
/**
|
|
28
|
+
* Generate HMAC signature for Vibe API request.
|
|
29
|
+
*/
|
|
30
|
+
function generateVibeSignature(endpoint, clientId, timestamp) {
|
|
31
|
+
const signingKey = process.env.VIBE_SIGNING_KEY;
|
|
32
|
+
if (!signingKey) {
|
|
33
|
+
return '';
|
|
34
|
+
}
|
|
35
|
+
const stringToSign = `${timestamp}|GET|${endpoint}|${clientId}`;
|
|
36
|
+
return (0, crypto_1.createHmac)('sha256', Buffer.from(signingKey, 'base64'))
|
|
37
|
+
.update(stringToSign)
|
|
38
|
+
.digest('base64');
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Fetch user's roles from Vibe API.
|
|
42
|
+
* Returns empty array on failure (non-blocking).
|
|
43
|
+
* Uses HMAC signature for authentication when signing key is configured.
|
|
44
|
+
*/
|
|
45
|
+
async function fetchVibeRoles(userId, clientId) {
|
|
46
|
+
const vibeApiUrl = process.env.VIBE_API_URL;
|
|
47
|
+
if (!vibeApiUrl) {
|
|
48
|
+
return [];
|
|
49
|
+
}
|
|
50
|
+
const endpoint = `/api/v1/users/${userId}/roles`;
|
|
51
|
+
const timestamp = Math.floor(Date.now() / 1000);
|
|
52
|
+
const signature = generateVibeSignature(endpoint, clientId, timestamp);
|
|
53
|
+
// Build headers with optional signature
|
|
54
|
+
const headers = {
|
|
55
|
+
'Accept': 'application/json',
|
|
56
|
+
'X-Client-Id': clientId,
|
|
57
|
+
'X-Vibe-Client-Id': clientId,
|
|
58
|
+
};
|
|
59
|
+
if (signature) {
|
|
60
|
+
headers['X-Vibe-Timestamp'] = String(timestamp);
|
|
61
|
+
headers['X-Vibe-Signature'] = signature;
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
const response = await fetch(`${vibeApiUrl}${endpoint}`, {
|
|
65
|
+
method: 'GET',
|
|
66
|
+
headers,
|
|
67
|
+
// 2 second timeout
|
|
68
|
+
signal: AbortSignal.timeout(2000),
|
|
69
|
+
});
|
|
70
|
+
if (!response.ok) {
|
|
71
|
+
console.warn('[JWT_CALLBACK] Failed to fetch Vibe roles:', response.status);
|
|
72
|
+
return [];
|
|
73
|
+
}
|
|
74
|
+
const data = await response.json();
|
|
75
|
+
const roles = data.roles?.map((r) => r.role_name || r) || [];
|
|
76
|
+
console.log('[JWT_CALLBACK] Fetched Vibe roles:', roles);
|
|
77
|
+
return roles;
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
console.warn('[JWT_CALLBACK] Error fetching Vibe roles (continuing with IDP roles only):', error);
|
|
81
|
+
return [];
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Merge IDP roles with Vibe roles, deduplicating.
|
|
86
|
+
*/
|
|
87
|
+
function mergeRoles(idpRoles, vibeRoles) {
|
|
88
|
+
return [...new Set([...idpRoles, ...vibeRoles])];
|
|
89
|
+
}
|
|
90
|
+
// ============================================================================
|
|
91
|
+
// JWT CALLBACK
|
|
92
|
+
// ============================================================================
|
|
93
|
+
/**
|
|
94
|
+
* JWT callback - builds the NextAuth JWT token.
|
|
95
|
+
*
|
|
96
|
+
* MINIMAL TOKEN STRATEGY:
|
|
97
|
+
* - Only store redisSessionId (key to Redis session)
|
|
98
|
+
* - All tokens and user data live in Redis
|
|
99
|
+
* - Browser cookie stays small and secure
|
|
100
|
+
*
|
|
101
|
+
* @param params - JWT callback parameters from NextAuth
|
|
102
|
+
* @returns JWT payload to store in browser cookie
|
|
103
|
+
*/
|
|
104
|
+
async function jwtCallback({ token, user, account, trigger, }) {
|
|
105
|
+
console.log('[JWT_CALLBACK] Called with:', {
|
|
106
|
+
trigger,
|
|
107
|
+
hasAccount: !!account,
|
|
108
|
+
provider: account?.provider,
|
|
109
|
+
hasUser: !!user,
|
|
110
|
+
userEmail: user?.email,
|
|
111
|
+
existingRedisSessionId: token?.redisSessionId ? 'yes' : 'no',
|
|
112
|
+
});
|
|
113
|
+
// -------------------------------------------------------------------------
|
|
114
|
+
// OAuth Sign-In: Register with IDP and create session
|
|
115
|
+
// -------------------------------------------------------------------------
|
|
116
|
+
if (account && account.provider !== 'credentials') {
|
|
117
|
+
console.log('[JWT_CALLBACK] Handling OAuth sign-in for provider:', account.provider);
|
|
118
|
+
return handleOAuthSignIn(token, user, account);
|
|
119
|
+
}
|
|
120
|
+
// -------------------------------------------------------------------------
|
|
121
|
+
// Credentials Sign-In: Session already created in authorize()
|
|
122
|
+
// -------------------------------------------------------------------------
|
|
123
|
+
if (user && user.redisSessionId) {
|
|
124
|
+
// Credentials authorize() returns redisSessionId
|
|
125
|
+
const redisSessionId = user.redisSessionId;
|
|
126
|
+
return {
|
|
127
|
+
...token,
|
|
128
|
+
redisSessionId,
|
|
129
|
+
sub: user.id || token.sub || 'unknown',
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
// -------------------------------------------------------------------------
|
|
133
|
+
// Subsequent Requests: Validate session exists
|
|
134
|
+
// -------------------------------------------------------------------------
|
|
135
|
+
const redisSessionId = user?.redisSessionId || token?.redisSessionId || token?.redisSessionId;
|
|
136
|
+
if (!redisSessionId) {
|
|
137
|
+
return { ...token, error: 'NoSession', sub: token.sub || 'unknown' };
|
|
138
|
+
}
|
|
139
|
+
// Validate session still exists in Redis
|
|
140
|
+
try {
|
|
141
|
+
const sessionData = await (0, session_store_1.getSession)(redisSessionId);
|
|
142
|
+
if (!sessionData) {
|
|
143
|
+
// Session expired or deleted
|
|
144
|
+
return { ...token, error: 'SessionNotFound', sub: token.sub || 'unknown' };
|
|
145
|
+
}
|
|
146
|
+
// Check if refresh token has expired (session should be terminated)
|
|
147
|
+
if (sessionData.idpRefreshTokenExpires && Date.now() >= sessionData.idpRefreshTokenExpires) {
|
|
148
|
+
return { ...token, error: 'RefreshTokenExpired', sub: token.sub || 'unknown' };
|
|
149
|
+
}
|
|
150
|
+
// Check if MFA has expired (requires step-up authentication)
|
|
151
|
+
if (sessionData.mfaExpiresAt && Date.now() > sessionData.mfaExpiresAt) {
|
|
152
|
+
return {
|
|
153
|
+
...token,
|
|
154
|
+
redisSessionId,
|
|
155
|
+
sub: sessionData.userId,
|
|
156
|
+
error: 'MfaExpired',
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
console.error('[JWT_CALLBACK] Session validation error:', error);
|
|
162
|
+
return { ...token, error: 'SessionError', sub: token.sub || 'unknown' };
|
|
163
|
+
}
|
|
164
|
+
// Session is valid - return minimal token
|
|
165
|
+
return {
|
|
166
|
+
...token,
|
|
167
|
+
redisSessionId,
|
|
168
|
+
sub: token.sub || 'unknown',
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
// ============================================================================
|
|
172
|
+
// OAUTH SIGN-IN HANDLER
|
|
173
|
+
// ============================================================================
|
|
174
|
+
/**
|
|
175
|
+
* Handle OAuth sign-in by registering with IDP and creating session.
|
|
176
|
+
*/
|
|
177
|
+
async function handleOAuthSignIn(token, user, account) {
|
|
178
|
+
console.log('[JWT_CALLBACK] handleOAuthSignIn starting for:', {
|
|
179
|
+
provider: account.provider,
|
|
180
|
+
email: user?.email,
|
|
181
|
+
providerAccountId: account.providerAccountId,
|
|
182
|
+
});
|
|
183
|
+
try {
|
|
184
|
+
// Call IDP to register/authenticate OAuth user
|
|
185
|
+
const idpResult = await (0, idp_client_1.idpOAuthCallback)({
|
|
186
|
+
provider: account.provider,
|
|
187
|
+
providerAccountId: account.providerAccountId,
|
|
188
|
+
email: user?.email || '',
|
|
189
|
+
name: user?.name || '',
|
|
190
|
+
image: user?.image || '',
|
|
191
|
+
accessToken: account.access_token,
|
|
192
|
+
refreshToken: account.refresh_token,
|
|
193
|
+
expiresAt: account.expires_at,
|
|
194
|
+
});
|
|
195
|
+
// Build session data using normalized field names
|
|
196
|
+
let sessionData;
|
|
197
|
+
let mfaVerified = false;
|
|
198
|
+
if (idpResult.success && idpResult.data?.accessToken) {
|
|
199
|
+
// IDP integration succeeded - we have IDP tokens
|
|
200
|
+
const decoded = (0, token_utils_1.decodeIdpAccessToken)(idpResult.data.accessToken);
|
|
201
|
+
const amrClaims = decoded ? (0, token_utils_1.extractAmrFromToken)(decoded) : [];
|
|
202
|
+
const acrLevel = decoded?.acr || '1';
|
|
203
|
+
// Extract kid from JWT header (CRITICAL: different from client_id in payload)
|
|
204
|
+
const bearerKeyId = (0, token_utils_1.extractKidFromToken)(idpResult.data.accessToken);
|
|
205
|
+
if (bearerKeyId) {
|
|
206
|
+
console.log('[JWT_CALLBACK] Extracted bearerKeyId (kid) from JWT header:', bearerKeyId);
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
console.warn('[JWT_CALLBACK] No kid found in JWT header');
|
|
210
|
+
}
|
|
211
|
+
// Check if MFA is required for this client
|
|
212
|
+
try {
|
|
213
|
+
const clientConfig = await (0, idp_client_config_1.getIDPClientConfig)();
|
|
214
|
+
const require2FA = clientConfig?.authSettings?.require2FA ?? true;
|
|
215
|
+
mfaVerified = !require2FA; // If MFA not required, mark as verified
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
// Default to requiring MFA if config unavailable
|
|
219
|
+
mfaVerified = false;
|
|
220
|
+
}
|
|
221
|
+
sessionData = {
|
|
222
|
+
userId: idpResult.data.user?.userId?.toString() || account.providerAccountId,
|
|
223
|
+
email: idpResult.data.user?.email || user?.email || '',
|
|
224
|
+
name: idpResult.data.user?.fullName || user?.name || '',
|
|
225
|
+
roles: idpResult.data.user?.roles || [],
|
|
226
|
+
// IDP tokens (normalized names)
|
|
227
|
+
idpAccessToken: idpResult.data.accessToken,
|
|
228
|
+
idpRefreshToken: idpResult.data.refreshToken,
|
|
229
|
+
idpAccessTokenExpires: decoded?.exp ? (0, token_utils_1.expClaimToMs)(decoded.exp) : Date.now() + 3600000,
|
|
230
|
+
decodedAccessToken: decoded || undefined,
|
|
231
|
+
// Bearer key ID from JWT header (NOT client_id from payload)
|
|
232
|
+
bearerKeyId,
|
|
233
|
+
// MFA state (normalized names)
|
|
234
|
+
mfaVerified,
|
|
235
|
+
authenticationMethods: amrClaims,
|
|
236
|
+
authenticationLevel: acrLevel,
|
|
237
|
+
// OAuth provider info (normalized names)
|
|
238
|
+
oauthProvider: account.provider,
|
|
239
|
+
oauthProviderToken: account.access_token,
|
|
240
|
+
oauthProviderRefreshToken: account.refresh_token,
|
|
241
|
+
// Multi-tenant info
|
|
242
|
+
idpClientId: decoded?.client_id,
|
|
243
|
+
merchantId: decoded?.merchant_id,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
// IDP integration failed - create OAuth-only session
|
|
248
|
+
// This allows OAuth login to work even if IDP is unavailable
|
|
249
|
+
mfaVerified = true; // OAuth IS multi-factor (Google/Microsoft handle MFA)
|
|
250
|
+
sessionData = {
|
|
251
|
+
userId: account.providerAccountId,
|
|
252
|
+
email: user?.email || '',
|
|
253
|
+
name: user?.name || '',
|
|
254
|
+
roles: [],
|
|
255
|
+
mfaVerified: true, // OAuth IS multi-factor
|
|
256
|
+
oauthProvider: account.provider,
|
|
257
|
+
oauthProviderToken: account.access_token,
|
|
258
|
+
oauthProviderRefreshToken: account.refresh_token,
|
|
259
|
+
idpAccessTokenExpires: account.expires_at
|
|
260
|
+
? account.expires_at * 1000
|
|
261
|
+
: Date.now() + 3600000,
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
// -------------------------------------------------------------------------
|
|
265
|
+
// ROLE MERGING: Fetch Vibe roles and merge with IDP roles
|
|
266
|
+
// -------------------------------------------------------------------------
|
|
267
|
+
const clientId = sessionData.idpClientId || process.env.IDP_CLIENT_ID || '';
|
|
268
|
+
if (clientId && sessionData.userId) {
|
|
269
|
+
const vibeRoles = await fetchVibeRoles(sessionData.userId, clientId);
|
|
270
|
+
// SECURITY: Filter out protected IDP-level role prefixes to prevent injection
|
|
271
|
+
const safeVibeRoles = vibeRoles.filter(r => !r.startsWith('payez_'));
|
|
272
|
+
const idpRoles = sessionData.roles || [];
|
|
273
|
+
sessionData.roles = mergeRoles(idpRoles, safeVibeRoles);
|
|
274
|
+
console.log('[JWT_CALLBACK] Merged roles:', {
|
|
275
|
+
idpRoles,
|
|
276
|
+
vibeRoles,
|
|
277
|
+
safeVibeRoles,
|
|
278
|
+
merged: sessionData.roles,
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
// Create Redis session
|
|
282
|
+
console.log('[JWT_CALLBACK] Creating Redis session for:', {
|
|
283
|
+
userId: sessionData.userId,
|
|
284
|
+
email: sessionData.email,
|
|
285
|
+
mfaVerified: sessionData.mfaVerified,
|
|
286
|
+
roles: sessionData.roles,
|
|
287
|
+
});
|
|
288
|
+
const redisSessionId = await (0, session_store_1.createSession)(sessionData);
|
|
289
|
+
console.log('[JWT_CALLBACK] Redis session created:', {
|
|
290
|
+
redisSessionId: redisSessionId ? redisSessionId.substring(0, 8) + '...' : 'NONE',
|
|
291
|
+
});
|
|
292
|
+
// Check if immediate MFA redirect is needed
|
|
293
|
+
const needsImmediateTwoFactor = !mfaVerified;
|
|
294
|
+
return {
|
|
295
|
+
...token,
|
|
296
|
+
redisSessionId,
|
|
297
|
+
sub: sessionData.userId,
|
|
298
|
+
requiresTwoFactorRedirect: needsImmediateTwoFactor,
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
console.error('[JWT_CALLBACK] handleOAuthSignIn FAILED:', error);
|
|
303
|
+
return { ...token, error: 'OAuthSignInFailed', sub: token.sub || 'unknown' };
|
|
304
|
+
}
|
|
305
|
+
}
|
|
@@ -1,223 +1,223 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* Credentials Provider
|
|
4
|
-
*
|
|
5
|
-
* Handles email/password authentication via PayEz IDP.
|
|
6
|
-
* Creates Redis session and returns minimal user object to NextAuth.
|
|
7
|
-
*
|
|
8
|
-
* FLOW:
|
|
9
|
-
* 1. User submits email/password
|
|
10
|
-
* 2. We call IDP /api/ExternalAuth/login
|
|
11
|
-
* 3. IDP returns tokens if credentials valid
|
|
12
|
-
* 4. We create Redis session with tokens
|
|
13
|
-
* 5. Return user object with redisSessionId to NextAuth
|
|
14
|
-
*
|
|
15
|
-
* @version 1.0.0
|
|
16
|
-
* @since auth-refactor-2026-01
|
|
17
|
-
*/
|
|
18
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
19
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
20
|
-
};
|
|
21
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
-
exports.createCredentialsProvider = createCredentialsProvider;
|
|
23
|
-
const credentials_1 = __importDefault(require("next-auth/providers/credentials"));
|
|
24
|
-
const session_store_1 = require("../../lib/session-store");
|
|
25
|
-
const idp_client_1 = require("../utils/idp-client");
|
|
26
|
-
const token_utils_1 = require("../utils/token-utils");
|
|
27
|
-
const auth_types_1 = require("../types/auth-types");
|
|
28
|
-
// NOTE: Using any for sessionData until Phase 3 normalizes types
|
|
29
|
-
// ============================================================================
|
|
30
|
-
// CREDENTIALS PROVIDER
|
|
31
|
-
// ============================================================================
|
|
32
|
-
/**
|
|
33
|
-
* Create the CredentialsProvider for NextAuth.
|
|
34
|
-
*
|
|
35
|
-
* This provider handles email/password login. The authorize function
|
|
36
|
-
* is called when a user submits the login form.
|
|
37
|
-
*/
|
|
38
|
-
function createCredentialsProvider() {
|
|
39
|
-
return (0, credentials_1.default)({
|
|
40
|
-
id: 'credentials',
|
|
41
|
-
name: 'Credentials',
|
|
42
|
-
credentials: {
|
|
43
|
-
email: { label: 'Email', type: 'email' },
|
|
44
|
-
password: { label: 'Password', type: 'password' },
|
|
45
|
-
},
|
|
46
|
-
authorize: authorizeCredentials,
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Authorize user with email/password.
|
|
51
|
-
*
|
|
52
|
-
* This is the core authentication function. It:
|
|
53
|
-
* 1. Validates credentials with IDP
|
|
54
|
-
* 2. Decodes the returned tokens
|
|
55
|
-
* 3. Creates a Redis session
|
|
56
|
-
* 4. Returns user info for NextAuth JWT
|
|
57
|
-
*
|
|
58
|
-
* @param credentials - Email and password from login form
|
|
59
|
-
* @param req - The incoming request (for IP/UA forwarding)
|
|
60
|
-
* @returns User object for NextAuth, or null/throws on failure
|
|
61
|
-
*/
|
|
62
|
-
async function authorizeCredentials(credentials, req) {
|
|
63
|
-
// -------------------------------------------------------------------------
|
|
64
|
-
// Validate Input
|
|
65
|
-
// -------------------------------------------------------------------------
|
|
66
|
-
if (!credentials?.email || !credentials?.password) {
|
|
67
|
-
throw new Error('Email and password required');
|
|
68
|
-
}
|
|
69
|
-
const loginCredentials = {
|
|
70
|
-
email: credentials.email,
|
|
71
|
-
password: credentials.password,
|
|
72
|
-
};
|
|
73
|
-
// Extract client info for audit logging
|
|
74
|
-
const clientHeaders = extractClientHeaders(req);
|
|
75
|
-
// -------------------------------------------------------------------------
|
|
76
|
-
// Call IDP
|
|
77
|
-
// -------------------------------------------------------------------------
|
|
78
|
-
const loginResult = await (0, idp_client_1.idpLogin)(loginCredentials, clientHeaders);
|
|
79
|
-
if (!loginResult.success || !loginResult.result) {
|
|
80
|
-
// Build structured error for frontend
|
|
81
|
-
const errorResponse = buildAuthError(loginResult.error);
|
|
82
|
-
throw new Error(JSON.stringify(errorResponse));
|
|
83
|
-
}
|
|
84
|
-
const { access_token, refresh_token, user: idpUser } = loginResult.result;
|
|
85
|
-
// -------------------------------------------------------------------------
|
|
86
|
-
// Decode Token
|
|
87
|
-
// -------------------------------------------------------------------------
|
|
88
|
-
const decoded = (0, token_utils_1.decodeIdpAccessToken)(access_token);
|
|
89
|
-
if (!decoded) {
|
|
90
|
-
throw new Error('Failed to decode token');
|
|
91
|
-
}
|
|
92
|
-
// Extract kid from JWT header (CRITICAL: this is different from client_id in payload)
|
|
93
|
-
const bearerKeyId = (0, token_utils_1.extractKidFromToken)(access_token);
|
|
94
|
-
if (bearerKeyId) {
|
|
95
|
-
console.log('[CREDENTIALS] Extracted bearerKeyId (kid) from JWT header:', bearerKeyId);
|
|
96
|
-
}
|
|
97
|
-
else {
|
|
98
|
-
console.warn('[CREDENTIALS] No kid found in JWT header - token may be unsigned or malformed');
|
|
99
|
-
}
|
|
100
|
-
// Extract claims from token
|
|
101
|
-
const email = (0, token_utils_1.extractEmailFromToken)(decoded);
|
|
102
|
-
const roles = (0, token_utils_1.extractRolesFromToken)(decoded);
|
|
103
|
-
const amrClaims = (0, token_utils_1.extractAmrFromToken)(decoded);
|
|
104
|
-
const acrLevel = decoded.acr || '1';
|
|
105
|
-
const userId = decoded.sub;
|
|
106
|
-
// Check if 2FA is complete based on ACR level
|
|
107
|
-
// ACR=1: Provisional token (requires 2FA)
|
|
108
|
-
// ACR=2: Full authentication (2FA complete)
|
|
109
|
-
const mfaVerified = acrLevel === '2';
|
|
110
|
-
// Decode refresh token expiry if available
|
|
111
|
-
let refreshTokenExpires;
|
|
112
|
-
try {
|
|
113
|
-
const refreshDecoded = (0, token_utils_1.decodeIdpAccessToken)(refresh_token);
|
|
114
|
-
if (refreshDecoded?.exp) {
|
|
115
|
-
refreshTokenExpires = (0, token_utils_1.expClaimToMs)(refreshDecoded.exp);
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
catch {
|
|
119
|
-
// Ignore - will use default expiry
|
|
120
|
-
}
|
|
121
|
-
// -------------------------------------------------------------------------
|
|
122
|
-
// Create Redis Session
|
|
123
|
-
// -------------------------------------------------------------------------
|
|
124
|
-
// Using normalized field names (session-store handles backward compatibility)
|
|
125
|
-
const sessionData = {
|
|
126
|
-
userId,
|
|
127
|
-
email,
|
|
128
|
-
roles,
|
|
129
|
-
// IDP tokens (normalized names)
|
|
130
|
-
idpAccessToken: access_token,
|
|
131
|
-
idpRefreshToken: refresh_token,
|
|
132
|
-
idpAccessTokenExpires: (0, token_utils_1.expClaimToMs)(decoded.exp),
|
|
133
|
-
idpRefreshTokenExpires: refreshTokenExpires,
|
|
134
|
-
decodedAccessToken: decoded,
|
|
135
|
-
// Bearer key ID from JWT header (NOT client_id from payload)
|
|
136
|
-
bearerKeyId,
|
|
137
|
-
// MFA state (normalized names)
|
|
138
|
-
mfaVerified,
|
|
139
|
-
authenticationMethods: amrClaims,
|
|
140
|
-
authenticationLevel: acrLevel,
|
|
141
|
-
// MFA timing info from token
|
|
142
|
-
mfaCompletedAt: decoded.mfa_time ? (0, token_utils_1.expClaimToMs)(decoded.mfa_time) : undefined,
|
|
143
|
-
mfaExpiresAt: decoded.mfa_expires ? (0, token_utils_1.expClaimToMs)(decoded.mfa_expires) : undefined,
|
|
144
|
-
mfaValidityHours: decoded.mfa_validity_hours,
|
|
145
|
-
};
|
|
146
|
-
// Determine MFA method from IDP user info
|
|
147
|
-
let mfaMethod;
|
|
148
|
-
if (idpUser?.isEmailConfirmed) {
|
|
149
|
-
mfaMethod = 'email';
|
|
150
|
-
}
|
|
151
|
-
else if (idpUser?.isSmsConfirmed) {
|
|
152
|
-
mfaMethod = 'sms';
|
|
153
|
-
}
|
|
154
|
-
if (mfaMethod) {
|
|
155
|
-
sessionData.mfaMethod = mfaMethod;
|
|
156
|
-
}
|
|
157
|
-
// Create the Redis session
|
|
158
|
-
const redisSessionId = await (0, session_store_1.createSession)(sessionData);
|
|
159
|
-
// -------------------------------------------------------------------------
|
|
160
|
-
// Return User Object for NextAuth
|
|
161
|
-
// -------------------------------------------------------------------------
|
|
162
|
-
// NextAuth requires 'id' field - we use userId from IDP
|
|
163
|
-
// The redisSessionId is passed through to the JWT callback
|
|
164
|
-
return {
|
|
165
|
-
id: userId,
|
|
166
|
-
email,
|
|
167
|
-
roles,
|
|
168
|
-
redisSessionId: (0, auth_types_1.toRedisSessionId)(redisSessionId),
|
|
169
|
-
mfaRequired: !mfaVerified,
|
|
170
|
-
mfaMethod,
|
|
171
|
-
};
|
|
172
|
-
}
|
|
173
|
-
// ============================================================================
|
|
174
|
-
// HELPER FUNCTIONS
|
|
175
|
-
// ============================================================================
|
|
176
|
-
/**
|
|
177
|
-
* Extract client headers from request for audit logging.
|
|
178
|
-
*/
|
|
179
|
-
function extractClientHeaders(req) {
|
|
180
|
-
const headers = {};
|
|
181
|
-
// Extract client IP
|
|
182
|
-
const forwardedFor = req?.headers?.['x-forwarded-for'];
|
|
183
|
-
const realIp = req?.headers?.['x-real-ip'];
|
|
184
|
-
if (forwardedFor) {
|
|
185
|
-
const ip = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor.split(',')[0].trim();
|
|
186
|
-
headers.ip = ip;
|
|
187
|
-
}
|
|
188
|
-
else if (realIp) {
|
|
189
|
-
headers.ip = Array.isArray(realIp) ? realIp[0] : realIp;
|
|
190
|
-
}
|
|
191
|
-
// Extract User-Agent
|
|
192
|
-
const userAgent = req?.headers?.['user-agent'];
|
|
193
|
-
if (userAgent) {
|
|
194
|
-
headers.userAgent = Array.isArray(userAgent) ? userAgent[0] : userAgent;
|
|
195
|
-
}
|
|
196
|
-
return headers;
|
|
197
|
-
}
|
|
198
|
-
/**
|
|
199
|
-
* Build structured error response for frontend.
|
|
200
|
-
*
|
|
201
|
-
* The frontend expects a specific error structure to display
|
|
202
|
-
* appropriate messages and handle things like lockout.
|
|
203
|
-
*/
|
|
204
|
-
function buildAuthError(error) {
|
|
205
|
-
if (!error) {
|
|
206
|
-
return {
|
|
207
|
-
success: false,
|
|
208
|
-
error: {
|
|
209
|
-
code: 'AUTH_ERROR',
|
|
210
|
-
message: 'Authentication failed',
|
|
211
|
-
details: {},
|
|
212
|
-
},
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
return {
|
|
216
|
-
success: false,
|
|
217
|
-
error: {
|
|
218
|
-
code: error.code || 'AUTH_ERROR',
|
|
219
|
-
message: error.message || 'Authentication failed',
|
|
220
|
-
details: error.details || {},
|
|
221
|
-
},
|
|
222
|
-
};
|
|
223
|
-
}
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Credentials Provider
|
|
4
|
+
*
|
|
5
|
+
* Handles email/password authentication via PayEz IDP.
|
|
6
|
+
* Creates Redis session and returns minimal user object to NextAuth.
|
|
7
|
+
*
|
|
8
|
+
* FLOW:
|
|
9
|
+
* 1. User submits email/password
|
|
10
|
+
* 2. We call IDP /api/ExternalAuth/login
|
|
11
|
+
* 3. IDP returns tokens if credentials valid
|
|
12
|
+
* 4. We create Redis session with tokens
|
|
13
|
+
* 5. Return user object with redisSessionId to NextAuth
|
|
14
|
+
*
|
|
15
|
+
* @version 1.0.0
|
|
16
|
+
* @since auth-refactor-2026-01
|
|
17
|
+
*/
|
|
18
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
19
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
20
|
+
};
|
|
21
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
+
exports.createCredentialsProvider = createCredentialsProvider;
|
|
23
|
+
const credentials_1 = __importDefault(require("next-auth/providers/credentials"));
|
|
24
|
+
const session_store_1 = require("../../lib/session-store");
|
|
25
|
+
const idp_client_1 = require("../utils/idp-client");
|
|
26
|
+
const token_utils_1 = require("../utils/token-utils");
|
|
27
|
+
const auth_types_1 = require("../types/auth-types");
|
|
28
|
+
// NOTE: Using any for sessionData until Phase 3 normalizes types
|
|
29
|
+
// ============================================================================
|
|
30
|
+
// CREDENTIALS PROVIDER
|
|
31
|
+
// ============================================================================
|
|
32
|
+
/**
|
|
33
|
+
* Create the CredentialsProvider for NextAuth.
|
|
34
|
+
*
|
|
35
|
+
* This provider handles email/password login. The authorize function
|
|
36
|
+
* is called when a user submits the login form.
|
|
37
|
+
*/
|
|
38
|
+
function createCredentialsProvider() {
|
|
39
|
+
return (0, credentials_1.default)({
|
|
40
|
+
id: 'credentials',
|
|
41
|
+
name: 'Credentials',
|
|
42
|
+
credentials: {
|
|
43
|
+
email: { label: 'Email', type: 'email' },
|
|
44
|
+
password: { label: 'Password', type: 'password' },
|
|
45
|
+
},
|
|
46
|
+
authorize: authorizeCredentials,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Authorize user with email/password.
|
|
51
|
+
*
|
|
52
|
+
* This is the core authentication function. It:
|
|
53
|
+
* 1. Validates credentials with IDP
|
|
54
|
+
* 2. Decodes the returned tokens
|
|
55
|
+
* 3. Creates a Redis session
|
|
56
|
+
* 4. Returns user info for NextAuth JWT
|
|
57
|
+
*
|
|
58
|
+
* @param credentials - Email and password from login form
|
|
59
|
+
* @param req - The incoming request (for IP/UA forwarding)
|
|
60
|
+
* @returns User object for NextAuth, or null/throws on failure
|
|
61
|
+
*/
|
|
62
|
+
async function authorizeCredentials(credentials, req) {
|
|
63
|
+
// -------------------------------------------------------------------------
|
|
64
|
+
// Validate Input
|
|
65
|
+
// -------------------------------------------------------------------------
|
|
66
|
+
if (!credentials?.email || !credentials?.password) {
|
|
67
|
+
throw new Error('Email and password required');
|
|
68
|
+
}
|
|
69
|
+
const loginCredentials = {
|
|
70
|
+
email: credentials.email,
|
|
71
|
+
password: credentials.password,
|
|
72
|
+
};
|
|
73
|
+
// Extract client info for audit logging
|
|
74
|
+
const clientHeaders = extractClientHeaders(req);
|
|
75
|
+
// -------------------------------------------------------------------------
|
|
76
|
+
// Call IDP
|
|
77
|
+
// -------------------------------------------------------------------------
|
|
78
|
+
const loginResult = await (0, idp_client_1.idpLogin)(loginCredentials, clientHeaders);
|
|
79
|
+
if (!loginResult.success || !loginResult.result) {
|
|
80
|
+
// Build structured error for frontend
|
|
81
|
+
const errorResponse = buildAuthError(loginResult.error);
|
|
82
|
+
throw new Error(JSON.stringify(errorResponse));
|
|
83
|
+
}
|
|
84
|
+
const { access_token, refresh_token, user: idpUser } = loginResult.result;
|
|
85
|
+
// -------------------------------------------------------------------------
|
|
86
|
+
// Decode Token
|
|
87
|
+
// -------------------------------------------------------------------------
|
|
88
|
+
const decoded = (0, token_utils_1.decodeIdpAccessToken)(access_token);
|
|
89
|
+
if (!decoded) {
|
|
90
|
+
throw new Error('Failed to decode token');
|
|
91
|
+
}
|
|
92
|
+
// Extract kid from JWT header (CRITICAL: this is different from client_id in payload)
|
|
93
|
+
const bearerKeyId = (0, token_utils_1.extractKidFromToken)(access_token);
|
|
94
|
+
if (bearerKeyId) {
|
|
95
|
+
console.log('[CREDENTIALS] Extracted bearerKeyId (kid) from JWT header:', bearerKeyId);
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
console.warn('[CREDENTIALS] No kid found in JWT header - token may be unsigned or malformed');
|
|
99
|
+
}
|
|
100
|
+
// Extract claims from token
|
|
101
|
+
const email = (0, token_utils_1.extractEmailFromToken)(decoded);
|
|
102
|
+
const roles = (0, token_utils_1.extractRolesFromToken)(decoded);
|
|
103
|
+
const amrClaims = (0, token_utils_1.extractAmrFromToken)(decoded);
|
|
104
|
+
const acrLevel = decoded.acr || '1';
|
|
105
|
+
const userId = decoded.sub;
|
|
106
|
+
// Check if 2FA is complete based on ACR level
|
|
107
|
+
// ACR=1: Provisional token (requires 2FA)
|
|
108
|
+
// ACR=2: Full authentication (2FA complete)
|
|
109
|
+
const mfaVerified = acrLevel === '2';
|
|
110
|
+
// Decode refresh token expiry if available
|
|
111
|
+
let refreshTokenExpires;
|
|
112
|
+
try {
|
|
113
|
+
const refreshDecoded = (0, token_utils_1.decodeIdpAccessToken)(refresh_token);
|
|
114
|
+
if (refreshDecoded?.exp) {
|
|
115
|
+
refreshTokenExpires = (0, token_utils_1.expClaimToMs)(refreshDecoded.exp);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
// Ignore - will use default expiry
|
|
120
|
+
}
|
|
121
|
+
// -------------------------------------------------------------------------
|
|
122
|
+
// Create Redis Session
|
|
123
|
+
// -------------------------------------------------------------------------
|
|
124
|
+
// Using normalized field names (session-store handles backward compatibility)
|
|
125
|
+
const sessionData = {
|
|
126
|
+
userId,
|
|
127
|
+
email,
|
|
128
|
+
roles,
|
|
129
|
+
// IDP tokens (normalized names)
|
|
130
|
+
idpAccessToken: access_token,
|
|
131
|
+
idpRefreshToken: refresh_token,
|
|
132
|
+
idpAccessTokenExpires: (0, token_utils_1.expClaimToMs)(decoded.exp),
|
|
133
|
+
idpRefreshTokenExpires: refreshTokenExpires,
|
|
134
|
+
decodedAccessToken: decoded,
|
|
135
|
+
// Bearer key ID from JWT header (NOT client_id from payload)
|
|
136
|
+
bearerKeyId,
|
|
137
|
+
// MFA state (normalized names)
|
|
138
|
+
mfaVerified,
|
|
139
|
+
authenticationMethods: amrClaims,
|
|
140
|
+
authenticationLevel: acrLevel,
|
|
141
|
+
// MFA timing info from token
|
|
142
|
+
mfaCompletedAt: decoded.mfa_time ? (0, token_utils_1.expClaimToMs)(decoded.mfa_time) : undefined,
|
|
143
|
+
mfaExpiresAt: decoded.mfa_expires ? (0, token_utils_1.expClaimToMs)(decoded.mfa_expires) : undefined,
|
|
144
|
+
mfaValidityHours: decoded.mfa_validity_hours,
|
|
145
|
+
};
|
|
146
|
+
// Determine MFA method from IDP user info
|
|
147
|
+
let mfaMethod;
|
|
148
|
+
if (idpUser?.isEmailConfirmed) {
|
|
149
|
+
mfaMethod = 'email';
|
|
150
|
+
}
|
|
151
|
+
else if (idpUser?.isSmsConfirmed) {
|
|
152
|
+
mfaMethod = 'sms';
|
|
153
|
+
}
|
|
154
|
+
if (mfaMethod) {
|
|
155
|
+
sessionData.mfaMethod = mfaMethod;
|
|
156
|
+
}
|
|
157
|
+
// Create the Redis session
|
|
158
|
+
const redisSessionId = await (0, session_store_1.createSession)(sessionData);
|
|
159
|
+
// -------------------------------------------------------------------------
|
|
160
|
+
// Return User Object for NextAuth
|
|
161
|
+
// -------------------------------------------------------------------------
|
|
162
|
+
// NextAuth requires 'id' field - we use userId from IDP
|
|
163
|
+
// The redisSessionId is passed through to the JWT callback
|
|
164
|
+
return {
|
|
165
|
+
id: userId,
|
|
166
|
+
email,
|
|
167
|
+
roles,
|
|
168
|
+
redisSessionId: (0, auth_types_1.toRedisSessionId)(redisSessionId),
|
|
169
|
+
mfaRequired: !mfaVerified,
|
|
170
|
+
mfaMethod,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
// ============================================================================
|
|
174
|
+
// HELPER FUNCTIONS
|
|
175
|
+
// ============================================================================
|
|
176
|
+
/**
|
|
177
|
+
* Extract client headers from request for audit logging.
|
|
178
|
+
*/
|
|
179
|
+
function extractClientHeaders(req) {
|
|
180
|
+
const headers = {};
|
|
181
|
+
// Extract client IP
|
|
182
|
+
const forwardedFor = req?.headers?.['x-forwarded-for'];
|
|
183
|
+
const realIp = req?.headers?.['x-real-ip'];
|
|
184
|
+
if (forwardedFor) {
|
|
185
|
+
const ip = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor.split(',')[0].trim();
|
|
186
|
+
headers.ip = ip;
|
|
187
|
+
}
|
|
188
|
+
else if (realIp) {
|
|
189
|
+
headers.ip = Array.isArray(realIp) ? realIp[0] : realIp;
|
|
190
|
+
}
|
|
191
|
+
// Extract User-Agent
|
|
192
|
+
const userAgent = req?.headers?.['user-agent'];
|
|
193
|
+
if (userAgent) {
|
|
194
|
+
headers.userAgent = Array.isArray(userAgent) ? userAgent[0] : userAgent;
|
|
195
|
+
}
|
|
196
|
+
return headers;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Build structured error response for frontend.
|
|
200
|
+
*
|
|
201
|
+
* The frontend expects a specific error structure to display
|
|
202
|
+
* appropriate messages and handle things like lockout.
|
|
203
|
+
*/
|
|
204
|
+
function buildAuthError(error) {
|
|
205
|
+
if (!error) {
|
|
206
|
+
return {
|
|
207
|
+
success: false,
|
|
208
|
+
error: {
|
|
209
|
+
code: 'AUTH_ERROR',
|
|
210
|
+
message: 'Authentication failed',
|
|
211
|
+
details: {},
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
success: false,
|
|
217
|
+
error: {
|
|
218
|
+
code: error.code || 'AUTH_ERROR',
|
|
219
|
+
message: error.message || 'Authentication failed',
|
|
220
|
+
details: error.details || {},
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
}
|
|
@@ -120,7 +120,8 @@ async function getIDPClientConfig(forceRefresh = false) {
|
|
|
120
120
|
}
|
|
121
121
|
// Set IDENTITY_CLIENT_BASE_EXTERNAL_URL from cached config
|
|
122
122
|
// AUTH_TRUST_HOST=true tells NextAuth to derive OAuth callback URLs from headers.
|
|
123
|
-
if (
|
|
123
|
+
// Only set if not already defined (allows deployment override for beta/staging)
|
|
124
|
+
if (redisConfig.baseClientUrl && !process.env.IDENTITY_CLIENT_BASE_EXTERNAL_URL) {
|
|
124
125
|
process.env.IDENTITY_CLIENT_BASE_EXTERNAL_URL = redisConfig.baseClientUrl;
|
|
125
126
|
}
|
|
126
127
|
return redisConfig;
|
|
@@ -152,7 +153,8 @@ async function getIDPClientConfig(forceRefresh = false) {
|
|
|
152
153
|
}
|
|
153
154
|
// Set IDENTITY_CLIENT_BASE_EXTERNAL_URL from config
|
|
154
155
|
// AUTH_TRUST_HOST=true tells NextAuth to derive OAuth callback URLs from headers.
|
|
155
|
-
if (
|
|
156
|
+
// Only set if not already defined (allows deployment override for beta/staging)
|
|
157
|
+
if (config.baseClientUrl && !process.env.IDENTITY_CLIENT_BASE_EXTERNAL_URL) {
|
|
156
158
|
process.env.IDENTITY_CLIENT_BASE_EXTERNAL_URL = config.baseClientUrl;
|
|
157
159
|
console.log("[IDP_CONFIG] Set IDENTITY_CLIENT_BASE_EXTERNAL_URL:", config.baseClientUrl);
|
|
158
160
|
}
|
package/package.json
CHANGED
|
@@ -177,7 +177,8 @@ export async function getIDPClientConfig(forceRefresh: boolean = false): Promise
|
|
|
177
177
|
|
|
178
178
|
// Set IDENTITY_CLIENT_BASE_EXTERNAL_URL from cached config
|
|
179
179
|
// AUTH_TRUST_HOST=true tells NextAuth to derive OAuth callback URLs from headers.
|
|
180
|
-
if (
|
|
180
|
+
// Only set if not already defined (allows deployment override for beta/staging)
|
|
181
|
+
if (redisConfig.baseClientUrl && !process.env.IDENTITY_CLIENT_BASE_EXTERNAL_URL) {
|
|
181
182
|
process.env.IDENTITY_CLIENT_BASE_EXTERNAL_URL = redisConfig.baseClientUrl;
|
|
182
183
|
}
|
|
183
184
|
|
|
@@ -215,7 +216,8 @@ export async function getIDPClientConfig(forceRefresh: boolean = false): Promise
|
|
|
215
216
|
|
|
216
217
|
// Set IDENTITY_CLIENT_BASE_EXTERNAL_URL from config
|
|
217
218
|
// AUTH_TRUST_HOST=true tells NextAuth to derive OAuth callback URLs from headers.
|
|
218
|
-
if (
|
|
219
|
+
// Only set if not already defined (allows deployment override for beta/staging)
|
|
220
|
+
if (config.baseClientUrl && !process.env.IDENTITY_CLIENT_BASE_EXTERNAL_URL) {
|
|
219
221
|
process.env.IDENTITY_CLIENT_BASE_EXTERNAL_URL = config.baseClientUrl;
|
|
220
222
|
console.log("[IDP_CONFIG] Set IDENTITY_CLIENT_BASE_EXTERNAL_URL:", config.baseClientUrl);
|
|
221
223
|
}
|