@payez/next-mvp 3.0.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
+ }