@payez/next-mvp 4.1.7 → 4.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/README.md +792 -792
  2. package/dist/auth/better-auth.js +15 -3
  3. package/dist/components/account/MobileNavDrawer.js +18 -18
  4. package/dist/components/account/UserAvatarMenu.js +1 -1
  5. package/dist/components/admin/AlertSettingsTab.js +40 -40
  6. package/dist/components/admin/LoggingSettingsTab.js +28 -28
  7. package/dist/pages/login/page.js +28 -28
  8. package/dist/pages/settings/EnhancedSettingsPage.js +17 -17
  9. package/package.json +1 -1
  10. package/scripts/dev-broker.ps1 +35 -35
  11. package/scripts/dev-local.ps1 +45 -45
  12. package/src/api/auth-handler.ts +548 -548
  13. package/src/api-handlers/account/change-password.ts +142 -142
  14. package/src/api-handlers/account/update-phone.ts +79 -79
  15. package/src/api-handlers/account/verify-email.ts +125 -125
  16. package/src/api-handlers/account/verify-sms.ts +125 -125
  17. package/src/api-handlers/admin/analytics.ts +443 -443
  18. package/src/api-handlers/admin/audit.ts +223 -223
  19. package/src/api-handlers/admin/index.ts +63 -63
  20. package/src/api-handlers/admin/redis-sessions.ts +251 -251
  21. package/src/api-handlers/admin/sessions.ts +318 -318
  22. package/src/api-handlers/admin/site-logs.ts +365 -365
  23. package/src/api-handlers/admin/users.ts +242 -242
  24. package/src/api-handlers/admin/vibe-data.ts +324 -324
  25. package/src/api-handlers/auth/refresh.ts +682 -682
  26. package/src/api-handlers/auth/signout.ts +199 -199
  27. package/src/api-handlers/auth/status.ts +20 -20
  28. package/src/api-handlers/auth/update-session.ts +110 -110
  29. package/src/api-handlers/auth/verify-code.ts +112 -112
  30. package/src/api-handlers/session/refresh-viability.ts +36 -36
  31. package/src/api-handlers/test/force-expire.ts +60 -60
  32. package/src/auth/auth-decision.ts +229 -229
  33. package/src/auth/better-auth.ts +15 -3
  34. package/src/auth/route-config.ts +219 -219
  35. package/src/auth/types/auth-types.ts +555 -555
  36. package/src/auth/types/index.ts +7 -7
  37. package/src/auth/utils/idp-client.ts +445 -445
  38. package/src/auth/utils/index.ts +6 -6
  39. package/src/auth/utils/token-utils.ts +243 -243
  40. package/src/client/AuthContext.tsx +143 -143
  41. package/src/client/fetch-with-auth.ts +47 -47
  42. package/src/components/SessionSync.tsx +138 -138
  43. package/src/components/SignalRHealthCheck.tsx +131 -131
  44. package/src/components/account/MobileNavDrawer.tsx +305 -305
  45. package/src/components/account/UserAvatarMenu.tsx +266 -266
  46. package/src/components/account/index.ts +13 -13
  47. package/src/components/admin/AlertSettingsTab.tsx +728 -728
  48. package/src/components/admin/AnalyticsTab.tsx +703 -703
  49. package/src/components/admin/DataBrowserTab.tsx +505 -505
  50. package/src/components/admin/LoggingSettingsTab.tsx +665 -665
  51. package/src/components/admin/SessionsTab.tsx +414 -414
  52. package/src/components/admin/StatsTab.tsx +379 -379
  53. package/src/components/admin/VibeAdminLayout.tsx +187 -187
  54. package/src/components/admin/index.ts +59 -59
  55. package/src/components/auth/FederatedAuthSection.tsx +95 -95
  56. package/src/components/auth/ModeAwareLoginPage.tsx +135 -135
  57. package/src/components/auth/ModeAwareSignupPage.tsx +267 -267
  58. package/src/components/auth/TraditionalAuthSection.tsx +99 -99
  59. package/src/components/recovery/CompleteStep.tsx +36 -36
  60. package/src/components/recovery/InitiateRecoveryStep.tsx +68 -68
  61. package/src/components/recovery/SelectMethodStep.tsx +73 -73
  62. package/src/components/recovery/SetPasswordStep.tsx +97 -97
  63. package/src/components/recovery/VerifyCodeStep.tsx +90 -90
  64. package/src/components/reserved/ReservedRecoveryWarning.tsx +160 -160
  65. package/src/components/reserved/ReservedStatusBox.tsx +118 -118
  66. package/src/components/ui/BetaBadge.tsx +58 -58
  67. package/src/components/ui/Footer.tsx +93 -93
  68. package/src/config/env.ts +57 -57
  69. package/src/config/logger.ts +62 -62
  70. package/src/config/vibe-log-transport.ts +264 -264
  71. package/src/hooks/useAuth.ts +117 -117
  72. package/src/hooks/useAuthSettings.ts +97 -97
  73. package/src/hooks/useAvailableProviders.ts +120 -120
  74. package/src/hooks/usePasswordValidation.ts +127 -127
  75. package/src/hooks/usePublicAuthSettings.ts +149 -149
  76. package/src/hooks/useSessionExpiration.ts +101 -101
  77. package/src/hooks/useViabilitySession.ts +336 -336
  78. package/src/index.ts +60 -60
  79. package/src/lib/api-handler.ts +643 -643
  80. package/src/lib/app-slug.ts +178 -178
  81. package/src/lib/geolocation.ts +265 -265
  82. package/src/lib/idp-fetch.ts +110 -110
  83. package/src/lib/jwt-decode.ts +82 -82
  84. package/src/lib/roles.ts +177 -177
  85. package/src/lib/site-logger.ts +245 -245
  86. package/src/lib/standardized-client-api.ts +901 -901
  87. package/src/lib/test-aware-get-token.ts +41 -41
  88. package/src/lib/user-agent-parser.ts +252 -252
  89. package/src/logging/api/admin-analytics.ts +51 -51
  90. package/src/logging/api/audit-log.ts +53 -53
  91. package/src/logging/components/AdminAnalyticsLayout.tsx +49 -49
  92. package/src/logging/components/AuditLogViewer.tsx +125 -125
  93. package/src/logging/components/ErrorMetricsCard.tsx +98 -98
  94. package/src/logging/components/HealthMetricsCard.tsx +70 -70
  95. package/src/logging/hooks/useAdminAnalytics.ts +22 -22
  96. package/src/logging/hooks/useAuditLog.ts +24 -24
  97. package/src/logging/hooks/useErrorMetrics.ts +40 -40
  98. package/src/logging/hooks/useHealthMetrics.ts +44 -44
  99. package/src/logging/index.ts +18 -18
  100. package/src/logging/types/analytics.ts +81 -81
  101. package/src/logging/types/audit.ts +31 -31
  102. package/src/logging/types/index.ts +3 -3
  103. package/src/middleware/create-middleware.ts +663 -663
  104. package/src/middleware/rbac-check.ts +279 -279
  105. package/src/middleware/twofa-presets.ts +224 -224
  106. package/src/pages/admin-login/page.tsx +221 -221
  107. package/src/pages/admin-page-permissions/PagePermissionsAdminPage.tsx +527 -527
  108. package/src/pages/admin-page-permissions/index.ts +7 -7
  109. package/src/pages/admin-roles/RolesAdminPage.tsx +533 -533
  110. package/src/pages/admin-roles/modals.tsx +469 -469
  111. package/src/pages/client-admin/ClientSiteAdminPage.tsx +382 -382
  112. package/src/pages/client-admin/index.ts +33 -33
  113. package/src/pages/coming-soon/page.tsx +83 -83
  114. package/src/pages/login/page.tsx +456 -456
  115. package/src/pages/profile/EnhancedProfilePage.tsx +485 -485
  116. package/src/pages/profile/index.ts +9 -9
  117. package/src/pages/profile/page.tsx +166 -166
  118. package/src/pages/recovery/page.tsx +234 -234
  119. package/src/pages/roles/MyRolesPage.tsx +211 -211
  120. package/src/pages/roles/components.tsx +294 -294
  121. package/src/pages/roles/index.ts +17 -17
  122. package/src/pages/security/EnhancedSecurityPage.tsx +565 -565
  123. package/src/pages/security/index.ts +9 -9
  124. package/src/pages/security/page.tsx +507 -507
  125. package/src/pages/settings/EnhancedSettingsPage.tsx +642 -642
  126. package/src/pages/settings/index.ts +9 -9
  127. package/src/pages/settings/page.tsx +47 -47
  128. package/src/pages/showcase/ShowcasePage.tsx +532 -532
  129. package/src/pages/showcase/index.ts +13 -13
  130. package/src/pages/test-env/EmergencyLogoutPage.tsx +180 -180
  131. package/src/pages/test-env/JwtInspectPage.tsx +456 -456
  132. package/src/pages/test-env/RefreshTokenPage.tsx +157 -157
  133. package/src/pages/test-env/TestEnvPage.tsx +118 -118
  134. package/src/pages/test-env/index.ts +25 -25
  135. package/src/pages/verify-code/page.tsx +652 -652
  136. package/src/routes/account/update-phone.ts +13 -13
  137. package/src/routes/auth/logout.ts +108 -108
  138. package/src/routes/auth/nextauth.ts +45 -45
  139. package/src/routes/auth/settings.ts +75 -75
  140. package/src/routes/auth/viability.ts +224 -224
  141. package/src/server/auth-guard.ts +170 -170
  142. package/src/server/slim-middleware.ts +117 -117
  143. package/src/server/with-auth.ts +93 -93
  144. package/src/stores/authStore.ts +1899 -1899
  145. package/src/templates/instrumentation.ts +41 -41
  146. package/src/utils/logout.ts +30 -30
  147. package/src/vibe/client.ts +590 -590
  148. package/src/vibe/enterprise-auth.ts +208 -208
  149. package/src/vibe/errors.ts +185 -185
  150. package/src/vibe/generic.ts +431 -431
  151. package/src/vibe/hooks/index.ts +367 -367
  152. package/src/vibe/index.ts +132 -132
  153. package/src/vibe/sessions.ts +551 -551
  154. package/src/vibe/types.ts +577 -577
@@ -1,445 +1,445 @@
1
- /**
2
- * IDP Client Utilities
3
- *
4
- * Functions for calling PayEz IDP API endpoints.
5
- * Handles login, OAuth callback, token refresh, and 2FA verification.
6
- *
7
- * URL USAGE:
8
- * - IDP_URL: Used for all calls to the PayEz Identity Provider
9
- * - INTERNAL_API_URL: NOT used here - that's for calling THIS app's own endpoints
10
- *
11
- * @version 1.0.0
12
- * @since auth-refactor-2026-01
13
- */
14
-
15
- import type {
16
- IdpLoginResponse,
17
- IdpOAuthCallbackResponse,
18
- IdpRefreshResponse,
19
- LoginCredentials,
20
- } from '../types/auth-types';
21
-
22
- // ============================================================================
23
- // CONFIGURATION
24
- // ============================================================================
25
-
26
- /**
27
- * Get IDP base URL. Throws if not configured.
28
- */
29
- export function getIdpUrl(): string {
30
- const url = process.env.IDP_URL;
31
- if (!url) {
32
- throw new Error('[IDP_CLIENT] FATAL: IDP_URL environment variable is REQUIRED');
33
- }
34
- return url.replace(/\/$/, ''); // Remove trailing slash
35
- }
36
-
37
- /**
38
- * Get client ID for this application.
39
- */
40
- export function getClientId(): string {
41
- const clientId = process.env.CLIENT_ID || process.env.NEXT_PUBLIC_CLIENT_ID;
42
- if (!clientId) {
43
- throw new Error('[IDP_CLIENT] FATAL: CLIENT_ID environment variable is REQUIRED');
44
- }
45
- return clientId;
46
- }
47
-
48
- // ============================================================================
49
- // LOGIN
50
- // ============================================================================
51
-
52
- /**
53
- * Authenticate user with email/password via IDP.
54
- *
55
- * @param credentials - User's email and password
56
- * @param clientHeaders - Headers to forward (IP, User-Agent for audit)
57
- * @returns IDP login response with tokens or error
58
- */
59
- export async function idpLogin(
60
- credentials: LoginCredentials,
61
- clientHeaders?: { ip?: string; userAgent?: string }
62
- ): Promise<IdpLoginResponse> {
63
- const idpUrl = getIdpUrl();
64
- const clientId = getClientId();
65
-
66
- const headers: Record<string, string> = {
67
- 'Content-Type': 'application/json',
68
- 'X-Client-Id': clientId,
69
- };
70
-
71
- // Forward client IP for audit logging
72
- if (clientHeaders?.ip) {
73
- headers['X-Forwarded-For'] = clientHeaders.ip;
74
- }
75
-
76
- // Forward User-Agent for audit logging
77
- if (clientHeaders?.userAgent) {
78
- headers['User-Agent'] = clientHeaders.userAgent;
79
- }
80
-
81
- try {
82
- const response = await fetch(`${idpUrl}/api/ExternalAuth/login`, {
83
- method: 'POST',
84
- headers,
85
- body: JSON.stringify({
86
- username_or_email: credentials.email,
87
- password: credentials.password,
88
- client_id: clientId,
89
- }),
90
- });
91
-
92
- const data = await response.json();
93
-
94
- // Unwrap PayEz response envelope if present
95
- const responseData = data.data || data;
96
-
97
- if (!response.ok || !responseData.result || !responseData.success) {
98
- return {
99
- success: false,
100
- error: responseData.error || {
101
- code: `HTTP_${response.status}`,
102
- message: getLoginErrorMessage(response.status, responseData),
103
- },
104
- };
105
- }
106
-
107
- return {
108
- success: true,
109
- result: responseData.result,
110
- };
111
- } catch (error) {
112
- console.error('[IDP_CLIENT] Login request failed:', error);
113
- return {
114
- success: false,
115
- error: {
116
- code: 'NETWORK_ERROR',
117
- message: 'Failed to connect to authentication service',
118
- },
119
- };
120
- }
121
- }
122
-
123
- /**
124
- * Get user-friendly error message for login failures.
125
- */
126
- function getLoginErrorMessage(status: number, responseData: any): string {
127
- // Check for structured error from IDP
128
- if (responseData?.error?.message) {
129
- return responseData.error.message;
130
- }
131
-
132
- // Fallback to HTTP status-based messages
133
- switch (status) {
134
- case 401:
135
- return 'Invalid email or password. Please try again.';
136
- case 403:
137
- return 'Account access denied. Please contact support.';
138
- case 429:
139
- return 'Too many login attempts. Please try again later.';
140
- default:
141
- if (status >= 500) {
142
- return 'Authentication service is temporarily unavailable.';
143
- }
144
- return 'Authentication failed. Please try again.';
145
- }
146
- }
147
-
148
- // ============================================================================
149
- // OAUTH CALLBACK
150
- // ============================================================================
151
-
152
- /**
153
- * Register/authenticate OAuth user with IDP.
154
- *
155
- * Called after OAuth provider (Google, etc.) redirects back.
156
- * Creates or retrieves IDP user and returns IDP tokens.
157
- *
158
- * @param oauthData - Data from OAuth provider
159
- * @returns IDP response with tokens and user info
160
- */
161
- export async function idpOAuthCallback(oauthData: {
162
- provider: string;
163
- providerAccountId: string;
164
- email: string;
165
- name?: string;
166
- image?: string;
167
- accessToken?: string;
168
- refreshToken?: string;
169
- expiresAt?: number;
170
- }): Promise<IdpOAuthCallbackResponse> {
171
- const idpUrl = getIdpUrl();
172
- const clientId = getClientId();
173
-
174
- try {
175
- const response = await fetch(`${idpUrl}/api/ExternalAuth/oauth-callback`, {
176
- method: 'POST',
177
- headers: {
178
- 'Content-Type': 'application/json',
179
- 'X-Client-Id': clientId,
180
- },
181
- body: JSON.stringify({
182
- provider: oauthData.provider,
183
- provider_account_id: oauthData.providerAccountId,
184
- email: oauthData.email,
185
- name: oauthData.name || '',
186
- image: oauthData.image || '',
187
- access_token: oauthData.accessToken || '',
188
- refresh_token: oauthData.refreshToken || '',
189
- expires_at: oauthData.expiresAt || 0,
190
- client_id: clientId,
191
- }),
192
- });
193
-
194
- if (!response.ok) {
195
- const errorText = await response.text().catch(() => 'Unknown error');
196
- console.error('[IDP_CLIENT] OAuth callback failed:', response.status, errorText);
197
- return {
198
- success: false,
199
- error: {
200
- code: `HTTP_${response.status}`,
201
- message: 'OAuth registration failed',
202
- },
203
- };
204
- }
205
-
206
- const data = await response.json();
207
- const responseData = data.data || data;
208
-
209
- // Normalize snake_case to camelCase
210
- return {
211
- success: responseData.success !== false,
212
- data: responseData.success !== false
213
- ? {
214
- accessToken: responseData.accessToken || responseData.access_token,
215
- refreshToken: responseData.refreshToken || responseData.refresh_token,
216
- isNewUser: responseData.isNewUser ?? responseData.is_new_user ?? false,
217
- user: responseData.user
218
- ? {
219
- userId: responseData.user.userId || responseData.user.user_id,
220
- email: responseData.user.email || responseData.user.Email,
221
- fullName: responseData.user.fullName || responseData.user.full_name || responseData.user.name,
222
- roles: responseData.user.roles || [],
223
- }
224
- : undefined,
225
- }
226
- : undefined,
227
- error: responseData.error,
228
- };
229
- } catch (error) {
230
- console.error('[IDP_CLIENT] OAuth callback request failed:', error);
231
- return {
232
- success: false,
233
- error: {
234
- code: 'NETWORK_ERROR',
235
- message: 'Failed to connect to authentication service',
236
- },
237
- };
238
- }
239
- }
240
-
241
- // ============================================================================
242
- // TOKEN REFRESH
243
- // ============================================================================
244
-
245
- /**
246
- * Refresh an expired access token using the refresh token.
247
- *
248
- * @param refreshToken - The refresh token from previous login
249
- * @param mfaContext - MFA context to preserve across refresh
250
- * @returns New tokens or error
251
- */
252
- export async function idpRefreshToken(
253
- refreshToken: string,
254
- mfaContext?: {
255
- amr?: string[];
256
- acr?: string;
257
- twoFactorVerified?: boolean;
258
- twoFactorMethod?: string;
259
- twoFactorCompletedAt?: number;
260
- }
261
- ): Promise<IdpRefreshResponse> {
262
- const idpUrl = getIdpUrl();
263
- const clientId = getClientId();
264
-
265
- const requestBody: Record<string, any> = {
266
- refresh_token: refreshToken,
267
- };
268
-
269
- // Include MFA context so new token preserves authentication level
270
- if (mfaContext) {
271
- if (mfaContext.amr) {
272
- requestBody.amr = mfaContext.amr;
273
- }
274
- if (mfaContext.acr) {
275
- requestBody.acr = mfaContext.acr;
276
- }
277
- if (mfaContext.twoFactorVerified) {
278
- requestBody.two_factor_verified = true;
279
- }
280
- if (mfaContext.twoFactorMethod) {
281
- requestBody.two_factor_method = mfaContext.twoFactorMethod;
282
- }
283
- if (mfaContext.twoFactorCompletedAt) {
284
- requestBody.two_factor_completed_at = new Date(mfaContext.twoFactorCompletedAt).toISOString();
285
- }
286
- }
287
-
288
- try {
289
- const response = await fetch(`${idpUrl}/api/ExternalAuth/refresh`, {
290
- method: 'POST',
291
- headers: {
292
- 'Content-Type': 'application/json',
293
- 'X-Client-Id': clientId,
294
- },
295
- body: JSON.stringify(requestBody),
296
- });
297
-
298
- if (!response.ok) {
299
- const errorText = await response.text().catch(() => 'Unknown error');
300
- console.error('[IDP_CLIENT] Token refresh failed:', response.status, errorText);
301
- return {
302
- success: false,
303
- error: {
304
- code: `HTTP_${response.status}`,
305
- message: response.status === 401 ? 'Refresh token expired' : 'Token refresh failed',
306
- },
307
- };
308
- }
309
-
310
- const data = await response.json();
311
-
312
- if (data.success === false) {
313
- return {
314
- success: false,
315
- error: data.error || { code: 'REFRESH_FAILED', message: 'Token refresh failed' },
316
- };
317
- }
318
-
319
- const tokenData = data.data || data;
320
-
321
- return {
322
- success: true,
323
- data: {
324
- access_token: tokenData.access_token,
325
- refresh_token: tokenData.refresh_token,
326
- expires_in: tokenData.expires_in || 3600,
327
- },
328
- };
329
- } catch (error) {
330
- console.error('[IDP_CLIENT] Token refresh request failed:', error);
331
- return {
332
- success: false,
333
- error: {
334
- code: 'NETWORK_ERROR',
335
- message: 'Failed to connect to authentication service',
336
- },
337
- };
338
- }
339
- }
340
-
341
- // ============================================================================
342
- // 2FA VERIFICATION
343
- // ============================================================================
344
-
345
- /**
346
- * Verify 2FA code with IDP.
347
- *
348
- * @param sessionToken - Redis session ID
349
- * @param code - The 2FA code entered by user
350
- * @param method - The 2FA method ('email' | 'sms' | 'totp')
351
- * @returns Success status and updated tokens
352
- */
353
- export async function idpVerify2FA(
354
- accessToken: string,
355
- code: string,
356
- method: 'email' | 'sms' | 'totp'
357
- ): Promise<{ success: boolean; error?: { code: string; message: string } }> {
358
- const idpUrl = getIdpUrl();
359
- const clientId = getClientId();
360
-
361
- try {
362
- const response = await fetch(`${idpUrl}/api/ExternalAuth/verify-2fa`, {
363
- method: 'POST',
364
- headers: {
365
- 'Content-Type': 'application/json',
366
- 'X-Client-Id': clientId,
367
- Authorization: `Bearer ${accessToken}`,
368
- },
369
- body: JSON.stringify({
370
- code,
371
- method,
372
- }),
373
- });
374
-
375
- if (!response.ok) {
376
- const data = await response.json().catch(() => ({}));
377
- return {
378
- success: false,
379
- error: data.error || {
380
- code: `HTTP_${response.status}`,
381
- message: response.status === 401 ? 'Invalid code' : '2FA verification failed',
382
- },
383
- };
384
- }
385
-
386
- return { success: true };
387
- } catch (error) {
388
- console.error('[IDP_CLIENT] 2FA verification failed:', error);
389
- return {
390
- success: false,
391
- error: {
392
- code: 'NETWORK_ERROR',
393
- message: 'Failed to connect to authentication service',
394
- },
395
- };
396
- }
397
- }
398
-
399
- /**
400
- * Request a new 2FA code to be sent.
401
- *
402
- * @param accessToken - User's access token
403
- * @param method - How to send the code ('email' | 'sms')
404
- */
405
- export async function idpSend2FACode(
406
- accessToken: string,
407
- method: 'email' | 'sms'
408
- ): Promise<{ success: boolean; error?: { code: string; message: string } }> {
409
- const idpUrl = getIdpUrl();
410
- const clientId = getClientId();
411
-
412
- try {
413
- const response = await fetch(`${idpUrl}/api/ExternalAuth/send-2fa-code`, {
414
- method: 'POST',
415
- headers: {
416
- 'Content-Type': 'application/json',
417
- 'X-Client-Id': clientId,
418
- Authorization: `Bearer ${accessToken}`,
419
- },
420
- body: JSON.stringify({ method }),
421
- });
422
-
423
- if (!response.ok) {
424
- const data = await response.json().catch(() => ({}));
425
- return {
426
- success: false,
427
- error: data.error || {
428
- code: `HTTP_${response.status}`,
429
- message: 'Failed to send 2FA code',
430
- },
431
- };
432
- }
433
-
434
- return { success: true };
435
- } catch (error) {
436
- console.error('[IDP_CLIENT] Send 2FA code failed:', error);
437
- return {
438
- success: false,
439
- error: {
440
- code: 'NETWORK_ERROR',
441
- message: 'Failed to connect to authentication service',
442
- },
443
- };
444
- }
445
- }
1
+ /**
2
+ * IDP Client Utilities
3
+ *
4
+ * Functions for calling PayEz IDP API endpoints.
5
+ * Handles login, OAuth callback, token refresh, and 2FA verification.
6
+ *
7
+ * URL USAGE:
8
+ * - IDP_URL: Used for all calls to the PayEz Identity Provider
9
+ * - INTERNAL_API_URL: NOT used here - that's for calling THIS app's own endpoints
10
+ *
11
+ * @version 1.0.0
12
+ * @since auth-refactor-2026-01
13
+ */
14
+
15
+ import type {
16
+ IdpLoginResponse,
17
+ IdpOAuthCallbackResponse,
18
+ IdpRefreshResponse,
19
+ LoginCredentials,
20
+ } from '../types/auth-types';
21
+
22
+ // ============================================================================
23
+ // CONFIGURATION
24
+ // ============================================================================
25
+
26
+ /**
27
+ * Get IDP base URL. Throws if not configured.
28
+ */
29
+ export function getIdpUrl(): string {
30
+ const url = process.env.IDP_URL;
31
+ if (!url) {
32
+ throw new Error('[IDP_CLIENT] FATAL: IDP_URL environment variable is REQUIRED');
33
+ }
34
+ return url.replace(/\/$/, ''); // Remove trailing slash
35
+ }
36
+
37
+ /**
38
+ * Get client ID for this application.
39
+ */
40
+ export function getClientId(): string {
41
+ const clientId = process.env.CLIENT_ID || process.env.NEXT_PUBLIC_CLIENT_ID;
42
+ if (!clientId) {
43
+ throw new Error('[IDP_CLIENT] FATAL: CLIENT_ID environment variable is REQUIRED');
44
+ }
45
+ return clientId;
46
+ }
47
+
48
+ // ============================================================================
49
+ // LOGIN
50
+ // ============================================================================
51
+
52
+ /**
53
+ * Authenticate user with email/password via IDP.
54
+ *
55
+ * @param credentials - User's email and password
56
+ * @param clientHeaders - Headers to forward (IP, User-Agent for audit)
57
+ * @returns IDP login response with tokens or error
58
+ */
59
+ export async function idpLogin(
60
+ credentials: LoginCredentials,
61
+ clientHeaders?: { ip?: string; userAgent?: string }
62
+ ): Promise<IdpLoginResponse> {
63
+ const idpUrl = getIdpUrl();
64
+ const clientId = getClientId();
65
+
66
+ const headers: Record<string, string> = {
67
+ 'Content-Type': 'application/json',
68
+ 'X-Client-Id': clientId,
69
+ };
70
+
71
+ // Forward client IP for audit logging
72
+ if (clientHeaders?.ip) {
73
+ headers['X-Forwarded-For'] = clientHeaders.ip;
74
+ }
75
+
76
+ // Forward User-Agent for audit logging
77
+ if (clientHeaders?.userAgent) {
78
+ headers['User-Agent'] = clientHeaders.userAgent;
79
+ }
80
+
81
+ try {
82
+ const response = await fetch(`${idpUrl}/api/ExternalAuth/login`, {
83
+ method: 'POST',
84
+ headers,
85
+ body: JSON.stringify({
86
+ username_or_email: credentials.email,
87
+ password: credentials.password,
88
+ client_id: clientId,
89
+ }),
90
+ });
91
+
92
+ const data = await response.json();
93
+
94
+ // Unwrap PayEz response envelope if present
95
+ const responseData = data.data || data;
96
+
97
+ if (!response.ok || !responseData.result || !responseData.success) {
98
+ return {
99
+ success: false,
100
+ error: responseData.error || {
101
+ code: `HTTP_${response.status}`,
102
+ message: getLoginErrorMessage(response.status, responseData),
103
+ },
104
+ };
105
+ }
106
+
107
+ return {
108
+ success: true,
109
+ result: responseData.result,
110
+ };
111
+ } catch (error) {
112
+ console.error('[IDP_CLIENT] Login request failed:', error);
113
+ return {
114
+ success: false,
115
+ error: {
116
+ code: 'NETWORK_ERROR',
117
+ message: 'Failed to connect to authentication service',
118
+ },
119
+ };
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Get user-friendly error message for login failures.
125
+ */
126
+ function getLoginErrorMessage(status: number, responseData: any): string {
127
+ // Check for structured error from IDP
128
+ if (responseData?.error?.message) {
129
+ return responseData.error.message;
130
+ }
131
+
132
+ // Fallback to HTTP status-based messages
133
+ switch (status) {
134
+ case 401:
135
+ return 'Invalid email or password. Please try again.';
136
+ case 403:
137
+ return 'Account access denied. Please contact support.';
138
+ case 429:
139
+ return 'Too many login attempts. Please try again later.';
140
+ default:
141
+ if (status >= 500) {
142
+ return 'Authentication service is temporarily unavailable.';
143
+ }
144
+ return 'Authentication failed. Please try again.';
145
+ }
146
+ }
147
+
148
+ // ============================================================================
149
+ // OAUTH CALLBACK
150
+ // ============================================================================
151
+
152
+ /**
153
+ * Register/authenticate OAuth user with IDP.
154
+ *
155
+ * Called after OAuth provider (Google, etc.) redirects back.
156
+ * Creates or retrieves IDP user and returns IDP tokens.
157
+ *
158
+ * @param oauthData - Data from OAuth provider
159
+ * @returns IDP response with tokens and user info
160
+ */
161
+ export async function idpOAuthCallback(oauthData: {
162
+ provider: string;
163
+ providerAccountId: string;
164
+ email: string;
165
+ name?: string;
166
+ image?: string;
167
+ accessToken?: string;
168
+ refreshToken?: string;
169
+ expiresAt?: number;
170
+ }): Promise<IdpOAuthCallbackResponse> {
171
+ const idpUrl = getIdpUrl();
172
+ const clientId = getClientId();
173
+
174
+ try {
175
+ const response = await fetch(`${idpUrl}/api/ExternalAuth/oauth-callback`, {
176
+ method: 'POST',
177
+ headers: {
178
+ 'Content-Type': 'application/json',
179
+ 'X-Client-Id': clientId,
180
+ },
181
+ body: JSON.stringify({
182
+ provider: oauthData.provider,
183
+ provider_account_id: oauthData.providerAccountId,
184
+ email: oauthData.email,
185
+ name: oauthData.name || '',
186
+ image: oauthData.image || '',
187
+ access_token: oauthData.accessToken || '',
188
+ refresh_token: oauthData.refreshToken || '',
189
+ expires_at: oauthData.expiresAt || 0,
190
+ client_id: clientId,
191
+ }),
192
+ });
193
+
194
+ if (!response.ok) {
195
+ const errorText = await response.text().catch(() => 'Unknown error');
196
+ console.error('[IDP_CLIENT] OAuth callback failed:', response.status, errorText);
197
+ return {
198
+ success: false,
199
+ error: {
200
+ code: `HTTP_${response.status}`,
201
+ message: 'OAuth registration failed',
202
+ },
203
+ };
204
+ }
205
+
206
+ const data = await response.json();
207
+ const responseData = data.data || data;
208
+
209
+ // Normalize snake_case to camelCase
210
+ return {
211
+ success: responseData.success !== false,
212
+ data: responseData.success !== false
213
+ ? {
214
+ accessToken: responseData.accessToken || responseData.access_token,
215
+ refreshToken: responseData.refreshToken || responseData.refresh_token,
216
+ isNewUser: responseData.isNewUser ?? responseData.is_new_user ?? false,
217
+ user: responseData.user
218
+ ? {
219
+ userId: responseData.user.userId || responseData.user.user_id,
220
+ email: responseData.user.email || responseData.user.Email,
221
+ fullName: responseData.user.fullName || responseData.user.full_name || responseData.user.name,
222
+ roles: responseData.user.roles || [],
223
+ }
224
+ : undefined,
225
+ }
226
+ : undefined,
227
+ error: responseData.error,
228
+ };
229
+ } catch (error) {
230
+ console.error('[IDP_CLIENT] OAuth callback request failed:', error);
231
+ return {
232
+ success: false,
233
+ error: {
234
+ code: 'NETWORK_ERROR',
235
+ message: 'Failed to connect to authentication service',
236
+ },
237
+ };
238
+ }
239
+ }
240
+
241
+ // ============================================================================
242
+ // TOKEN REFRESH
243
+ // ============================================================================
244
+
245
+ /**
246
+ * Refresh an expired access token using the refresh token.
247
+ *
248
+ * @param refreshToken - The refresh token from previous login
249
+ * @param mfaContext - MFA context to preserve across refresh
250
+ * @returns New tokens or error
251
+ */
252
+ export async function idpRefreshToken(
253
+ refreshToken: string,
254
+ mfaContext?: {
255
+ amr?: string[];
256
+ acr?: string;
257
+ twoFactorVerified?: boolean;
258
+ twoFactorMethod?: string;
259
+ twoFactorCompletedAt?: number;
260
+ }
261
+ ): Promise<IdpRefreshResponse> {
262
+ const idpUrl = getIdpUrl();
263
+ const clientId = getClientId();
264
+
265
+ const requestBody: Record<string, any> = {
266
+ refresh_token: refreshToken,
267
+ };
268
+
269
+ // Include MFA context so new token preserves authentication level
270
+ if (mfaContext) {
271
+ if (mfaContext.amr) {
272
+ requestBody.amr = mfaContext.amr;
273
+ }
274
+ if (mfaContext.acr) {
275
+ requestBody.acr = mfaContext.acr;
276
+ }
277
+ if (mfaContext.twoFactorVerified) {
278
+ requestBody.two_factor_verified = true;
279
+ }
280
+ if (mfaContext.twoFactorMethod) {
281
+ requestBody.two_factor_method = mfaContext.twoFactorMethod;
282
+ }
283
+ if (mfaContext.twoFactorCompletedAt) {
284
+ requestBody.two_factor_completed_at = new Date(mfaContext.twoFactorCompletedAt).toISOString();
285
+ }
286
+ }
287
+
288
+ try {
289
+ const response = await fetch(`${idpUrl}/api/ExternalAuth/refresh`, {
290
+ method: 'POST',
291
+ headers: {
292
+ 'Content-Type': 'application/json',
293
+ 'X-Client-Id': clientId,
294
+ },
295
+ body: JSON.stringify(requestBody),
296
+ });
297
+
298
+ if (!response.ok) {
299
+ const errorText = await response.text().catch(() => 'Unknown error');
300
+ console.error('[IDP_CLIENT] Token refresh failed:', response.status, errorText);
301
+ return {
302
+ success: false,
303
+ error: {
304
+ code: `HTTP_${response.status}`,
305
+ message: response.status === 401 ? 'Refresh token expired' : 'Token refresh failed',
306
+ },
307
+ };
308
+ }
309
+
310
+ const data = await response.json();
311
+
312
+ if (data.success === false) {
313
+ return {
314
+ success: false,
315
+ error: data.error || { code: 'REFRESH_FAILED', message: 'Token refresh failed' },
316
+ };
317
+ }
318
+
319
+ const tokenData = data.data || data;
320
+
321
+ return {
322
+ success: true,
323
+ data: {
324
+ access_token: tokenData.access_token,
325
+ refresh_token: tokenData.refresh_token,
326
+ expires_in: tokenData.expires_in || 3600,
327
+ },
328
+ };
329
+ } catch (error) {
330
+ console.error('[IDP_CLIENT] Token refresh request failed:', error);
331
+ return {
332
+ success: false,
333
+ error: {
334
+ code: 'NETWORK_ERROR',
335
+ message: 'Failed to connect to authentication service',
336
+ },
337
+ };
338
+ }
339
+ }
340
+
341
+ // ============================================================================
342
+ // 2FA VERIFICATION
343
+ // ============================================================================
344
+
345
+ /**
346
+ * Verify 2FA code with IDP.
347
+ *
348
+ * @param sessionToken - Redis session ID
349
+ * @param code - The 2FA code entered by user
350
+ * @param method - The 2FA method ('email' | 'sms' | 'totp')
351
+ * @returns Success status and updated tokens
352
+ */
353
+ export async function idpVerify2FA(
354
+ accessToken: string,
355
+ code: string,
356
+ method: 'email' | 'sms' | 'totp'
357
+ ): Promise<{ success: boolean; error?: { code: string; message: string } }> {
358
+ const idpUrl = getIdpUrl();
359
+ const clientId = getClientId();
360
+
361
+ try {
362
+ const response = await fetch(`${idpUrl}/api/ExternalAuth/verify-2fa`, {
363
+ method: 'POST',
364
+ headers: {
365
+ 'Content-Type': 'application/json',
366
+ 'X-Client-Id': clientId,
367
+ Authorization: `Bearer ${accessToken}`,
368
+ },
369
+ body: JSON.stringify({
370
+ code,
371
+ method,
372
+ }),
373
+ });
374
+
375
+ if (!response.ok) {
376
+ const data = await response.json().catch(() => ({}));
377
+ return {
378
+ success: false,
379
+ error: data.error || {
380
+ code: `HTTP_${response.status}`,
381
+ message: response.status === 401 ? 'Invalid code' : '2FA verification failed',
382
+ },
383
+ };
384
+ }
385
+
386
+ return { success: true };
387
+ } catch (error) {
388
+ console.error('[IDP_CLIENT] 2FA verification failed:', error);
389
+ return {
390
+ success: false,
391
+ error: {
392
+ code: 'NETWORK_ERROR',
393
+ message: 'Failed to connect to authentication service',
394
+ },
395
+ };
396
+ }
397
+ }
398
+
399
+ /**
400
+ * Request a new 2FA code to be sent.
401
+ *
402
+ * @param accessToken - User's access token
403
+ * @param method - How to send the code ('email' | 'sms')
404
+ */
405
+ export async function idpSend2FACode(
406
+ accessToken: string,
407
+ method: 'email' | 'sms'
408
+ ): Promise<{ success: boolean; error?: { code: string; message: string } }> {
409
+ const idpUrl = getIdpUrl();
410
+ const clientId = getClientId();
411
+
412
+ try {
413
+ const response = await fetch(`${idpUrl}/api/ExternalAuth/send-2fa-code`, {
414
+ method: 'POST',
415
+ headers: {
416
+ 'Content-Type': 'application/json',
417
+ 'X-Client-Id': clientId,
418
+ Authorization: `Bearer ${accessToken}`,
419
+ },
420
+ body: JSON.stringify({ method }),
421
+ });
422
+
423
+ if (!response.ok) {
424
+ const data = await response.json().catch(() => ({}));
425
+ return {
426
+ success: false,
427
+ error: data.error || {
428
+ code: `HTTP_${response.status}`,
429
+ message: 'Failed to send 2FA code',
430
+ },
431
+ };
432
+ }
433
+
434
+ return { success: true };
435
+ } catch (error) {
436
+ console.error('[IDP_CLIENT] Send 2FA code failed:', error);
437
+ return {
438
+ success: false,
439
+ error: {
440
+ code: 'NETWORK_ERROR',
441
+ message: 'Failed to connect to authentication service',
442
+ },
443
+ };
444
+ }
445
+ }