@payez/next-mvp 4.1.9 → 4.1.11

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 (164) hide show
  1. package/README.md +792 -792
  2. package/dist/api-handlers/auth/refresh.js +38 -15
  3. package/dist/auth/better-auth.js +4 -3
  4. package/dist/components/account/MobileNavDrawer.js +18 -18
  5. package/dist/components/account/UserAvatarMenu.js +1 -1
  6. package/dist/components/admin/AlertSettingsTab.js +40 -40
  7. package/dist/components/admin/LoggingSettingsTab.js +28 -28
  8. package/dist/lib/ensure-fresh-access-token.js +42 -8
  9. package/dist/lib/idp-fetch.js +25 -9
  10. package/dist/lib/session-store.d.ts +1 -0
  11. package/dist/lib/session-store.js +12 -8
  12. package/dist/lib/token-lifecycle.d.ts +2 -0
  13. package/dist/lib/token-lifecycle.js +21 -3
  14. package/dist/pages/login/page.js +28 -28
  15. package/dist/pages/settings/EnhancedSettingsPage.js +17 -17
  16. package/package.json +893 -893
  17. package/scripts/dev-broker.ps1 +35 -35
  18. package/scripts/dev-local.ps1 +45 -45
  19. package/src/api/auth-handler.ts +548 -548
  20. package/src/api-handlers/account/change-password.ts +142 -142
  21. package/src/api-handlers/account/update-phone.ts +79 -79
  22. package/src/api-handlers/account/verify-email.ts +125 -125
  23. package/src/api-handlers/account/verify-sms.ts +125 -125
  24. package/src/api-handlers/admin/analytics.ts +443 -443
  25. package/src/api-handlers/admin/audit.ts +223 -223
  26. package/src/api-handlers/admin/index.ts +63 -63
  27. package/src/api-handlers/admin/redis-sessions.ts +251 -251
  28. package/src/api-handlers/admin/sessions.ts +318 -318
  29. package/src/api-handlers/admin/site-logs.ts +365 -365
  30. package/src/api-handlers/admin/users.ts +242 -242
  31. package/src/api-handlers/admin/vibe-data.ts +324 -324
  32. package/src/api-handlers/auth/refresh.ts +705 -682
  33. package/src/api-handlers/auth/signout.ts +199 -199
  34. package/src/api-handlers/auth/status.ts +20 -20
  35. package/src/api-handlers/auth/update-session.ts +110 -110
  36. package/src/api-handlers/auth/verify-code.ts +112 -112
  37. package/src/api-handlers/session/refresh-viability.ts +36 -36
  38. package/src/api-handlers/test/force-expire.ts +60 -60
  39. package/src/auth/auth-decision.ts +229 -229
  40. package/src/auth/better-auth.ts +467 -466
  41. package/src/auth/route-config.ts +219 -219
  42. package/src/auth/types/auth-types.ts +555 -555
  43. package/src/auth/types/index.ts +7 -7
  44. package/src/auth/utils/idp-client.ts +445 -445
  45. package/src/auth/utils/index.ts +6 -6
  46. package/src/auth/utils/token-utils.ts +243 -243
  47. package/src/client/AuthContext.tsx +143 -143
  48. package/src/client/fetch-with-auth.ts +47 -47
  49. package/src/components/SessionSync.tsx +138 -138
  50. package/src/components/SignalRHealthCheck.tsx +131 -131
  51. package/src/components/account/MobileNavDrawer.tsx +305 -305
  52. package/src/components/account/UserAvatarMenu.tsx +266 -266
  53. package/src/components/account/index.ts +13 -13
  54. package/src/components/admin/AlertSettingsTab.tsx +728 -728
  55. package/src/components/admin/AnalyticsTab.tsx +703 -703
  56. package/src/components/admin/DataBrowserTab.tsx +505 -505
  57. package/src/components/admin/LoggingSettingsTab.tsx +665 -665
  58. package/src/components/admin/SessionsTab.tsx +414 -414
  59. package/src/components/admin/StatsTab.tsx +379 -379
  60. package/src/components/admin/VibeAdminLayout.tsx +187 -187
  61. package/src/components/admin/index.ts +59 -59
  62. package/src/components/auth/FederatedAuthSection.tsx +95 -95
  63. package/src/components/auth/ModeAwareLoginPage.tsx +135 -135
  64. package/src/components/auth/ModeAwareSignupPage.tsx +267 -267
  65. package/src/components/auth/TraditionalAuthSection.tsx +99 -99
  66. package/src/components/recovery/CompleteStep.tsx +36 -36
  67. package/src/components/recovery/InitiateRecoveryStep.tsx +68 -68
  68. package/src/components/recovery/SelectMethodStep.tsx +73 -73
  69. package/src/components/recovery/SetPasswordStep.tsx +97 -97
  70. package/src/components/recovery/VerifyCodeStep.tsx +90 -90
  71. package/src/components/reserved/ReservedRecoveryWarning.tsx +160 -160
  72. package/src/components/reserved/ReservedStatusBox.tsx +118 -118
  73. package/src/components/ui/BetaBadge.tsx +58 -58
  74. package/src/components/ui/Footer.tsx +93 -93
  75. package/src/config/env.ts +57 -57
  76. package/src/config/logger.ts +62 -62
  77. package/src/config/vibe-log-transport.ts +264 -264
  78. package/src/hooks/useAuth.ts +117 -117
  79. package/src/hooks/useAuthSettings.ts +97 -97
  80. package/src/hooks/useAvailableProviders.ts +120 -120
  81. package/src/hooks/usePasswordValidation.ts +127 -127
  82. package/src/hooks/usePublicAuthSettings.ts +149 -149
  83. package/src/hooks/useSessionExpiration.ts +101 -101
  84. package/src/hooks/useViabilitySession.ts +336 -336
  85. package/src/index.ts +60 -60
  86. package/src/lib/api-handler.ts +643 -643
  87. package/src/lib/app-slug.ts +178 -178
  88. package/src/lib/ensure-fresh-access-token.ts +369 -335
  89. package/src/lib/geolocation.ts +265 -265
  90. package/src/lib/idp-fetch.ts +26 -10
  91. package/src/lib/jwt-decode.ts +82 -82
  92. package/src/lib/roles.ts +177 -177
  93. package/src/lib/session-store.ts +4 -1
  94. package/src/lib/site-logger.ts +245 -245
  95. package/src/lib/standardized-client-api.ts +901 -901
  96. package/src/lib/test-aware-get-token.ts +41 -41
  97. package/src/lib/token-lifecycle.ts +30 -3
  98. package/src/lib/user-agent-parser.ts +252 -252
  99. package/src/logging/api/admin-analytics.ts +51 -51
  100. package/src/logging/api/audit-log.ts +53 -53
  101. package/src/logging/components/AdminAnalyticsLayout.tsx +49 -49
  102. package/src/logging/components/AuditLogViewer.tsx +125 -125
  103. package/src/logging/components/ErrorMetricsCard.tsx +98 -98
  104. package/src/logging/components/HealthMetricsCard.tsx +70 -70
  105. package/src/logging/hooks/useAdminAnalytics.ts +22 -22
  106. package/src/logging/hooks/useAuditLog.ts +24 -24
  107. package/src/logging/hooks/useErrorMetrics.ts +40 -40
  108. package/src/logging/hooks/useHealthMetrics.ts +44 -44
  109. package/src/logging/index.ts +18 -18
  110. package/src/logging/types/analytics.ts +81 -81
  111. package/src/logging/types/audit.ts +31 -31
  112. package/src/logging/types/index.ts +3 -3
  113. package/src/middleware/create-middleware.ts +663 -663
  114. package/src/middleware/rbac-check.ts +279 -279
  115. package/src/middleware/twofa-presets.ts +224 -224
  116. package/src/pages/admin-login/page.tsx +221 -221
  117. package/src/pages/admin-page-permissions/PagePermissionsAdminPage.tsx +527 -527
  118. package/src/pages/admin-page-permissions/index.ts +7 -7
  119. package/src/pages/admin-roles/RolesAdminPage.tsx +533 -533
  120. package/src/pages/admin-roles/modals.tsx +469 -469
  121. package/src/pages/client-admin/ClientSiteAdminPage.tsx +382 -382
  122. package/src/pages/client-admin/index.ts +33 -33
  123. package/src/pages/coming-soon/page.tsx +83 -83
  124. package/src/pages/login/page.tsx +456 -456
  125. package/src/pages/profile/EnhancedProfilePage.tsx +485 -485
  126. package/src/pages/profile/index.ts +9 -9
  127. package/src/pages/profile/page.tsx +166 -166
  128. package/src/pages/recovery/page.tsx +234 -234
  129. package/src/pages/roles/MyRolesPage.tsx +211 -211
  130. package/src/pages/roles/components.tsx +294 -294
  131. package/src/pages/roles/index.ts +17 -17
  132. package/src/pages/security/EnhancedSecurityPage.tsx +565 -565
  133. package/src/pages/security/index.ts +9 -9
  134. package/src/pages/security/page.tsx +507 -507
  135. package/src/pages/settings/EnhancedSettingsPage.tsx +642 -642
  136. package/src/pages/settings/index.ts +9 -9
  137. package/src/pages/settings/page.tsx +47 -47
  138. package/src/pages/showcase/ShowcasePage.tsx +532 -532
  139. package/src/pages/showcase/index.ts +13 -13
  140. package/src/pages/test-env/EmergencyLogoutPage.tsx +180 -180
  141. package/src/pages/test-env/JwtInspectPage.tsx +456 -456
  142. package/src/pages/test-env/RefreshTokenPage.tsx +157 -157
  143. package/src/pages/test-env/TestEnvPage.tsx +118 -118
  144. package/src/pages/test-env/index.ts +25 -25
  145. package/src/pages/verify-code/page.tsx +652 -652
  146. package/src/routes/account/update-phone.ts +13 -13
  147. package/src/routes/auth/logout.ts +108 -108
  148. package/src/routes/auth/nextauth.ts +45 -45
  149. package/src/routes/auth/settings.ts +75 -75
  150. package/src/routes/auth/viability.ts +224 -224
  151. package/src/server/auth-guard.ts +170 -170
  152. package/src/server/slim-middleware.ts +117 -117
  153. package/src/server/with-auth.ts +93 -93
  154. package/src/stores/authStore.ts +1899 -1899
  155. package/src/templates/instrumentation.ts +41 -41
  156. package/src/utils/logout.ts +30 -30
  157. package/src/vibe/client.ts +590 -590
  158. package/src/vibe/enterprise-auth.ts +208 -208
  159. package/src/vibe/errors.ts +185 -185
  160. package/src/vibe/generic.ts +431 -431
  161. package/src/vibe/hooks/index.ts +367 -367
  162. package/src/vibe/index.ts +132 -132
  163. package/src/vibe/sessions.ts +551 -551
  164. 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
+ }