@payez/next-mvp 4.1.10 → 4.1.20

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 (181) hide show
  1. package/dist/api-handlers/account/profile.d.ts +38 -0
  2. package/dist/api-handlers/account/profile.js +73 -45
  3. package/dist/api-handlers/account/recovery/send-code.d.ts +33 -0
  4. package/dist/api-handlers/account/recovery/send-code.js +52 -18
  5. package/dist/api-handlers/account/recovery/verify-code.d.ts +33 -0
  6. package/dist/api-handlers/account/recovery/verify-code.js +52 -18
  7. package/dist/api-handlers/account/verify-email.js +15 -1
  8. package/dist/api-handlers/account/verify-sms.js +15 -1
  9. package/dist/api-handlers/auth/passkey-signin.d.ts +29 -0
  10. package/dist/api-handlers/auth/passkey-signin.js +97 -0
  11. package/dist/api-handlers/mfa/backup-code-verify.d.ts +73 -0
  12. package/dist/api-handlers/mfa/backup-code-verify.js +153 -0
  13. package/dist/api-handlers/mfa/backup-codes.d.ts +7 -0
  14. package/dist/api-handlers/mfa/backup-codes.js +40 -0
  15. package/dist/api-handlers/mfa/methods.d.ts +3 -0
  16. package/dist/api-handlers/mfa/methods.js +41 -0
  17. package/dist/api-handlers/mfa/totp-confirm.d.ts +8 -0
  18. package/dist/api-handlers/mfa/totp-confirm.js +41 -0
  19. package/dist/api-handlers/mfa/totp-enroll.d.ts +8 -0
  20. package/dist/api-handlers/mfa/totp-enroll.js +41 -0
  21. package/dist/api-handlers/mfa/totp-verify.d.ts +47 -0
  22. package/dist/api-handlers/mfa/totp-verify.js +134 -0
  23. package/dist/api-handlers/passkeys/list.d.ts +7 -0
  24. package/dist/api-handlers/passkeys/list.js +29 -0
  25. package/dist/api-handlers/passkeys/manage.d.ts +3 -0
  26. package/dist/api-handlers/passkeys/manage.js +54 -0
  27. package/dist/api-handlers/passkeys/register-options.d.ts +8 -0
  28. package/dist/api-handlers/passkeys/register-options.js +41 -0
  29. package/dist/api-handlers/passkeys/register-verify.d.ts +7 -0
  30. package/dist/api-handlers/passkeys/register-verify.js +40 -0
  31. package/dist/api-handlers/session/viability.js +19 -0
  32. package/dist/auth/better-auth.d.ts +68 -5
  33. package/dist/auth/better-auth.js +271 -45
  34. package/dist/auth/utils/idp-client.d.ts +13 -22
  35. package/dist/auth/utils/idp-client.js +12 -82
  36. package/dist/client/better-auth-client.d.ts +14 -2
  37. package/dist/lib/ensure-fresh-access-token.js +13 -2
  38. package/dist/lib/session-store.js +28 -21
  39. package/dist/lib/startup-init.js +19 -19
  40. package/dist/lib/token-lifecycle.d.ts +2 -0
  41. package/dist/lib/token-lifecycle.js +61 -7
  42. package/dist/models/SessionModel.d.ts +17 -0
  43. package/dist/pages/login/page.d.ts +10 -1
  44. package/dist/pages/login/page.js +69 -80
  45. package/dist/pages/verify-code/page.d.ts +10 -1
  46. package/dist/pages/verify-code/page.js +72 -4
  47. package/dist/routes/auth/passkey-signin.d.ts +13 -0
  48. package/dist/routes/auth/passkey-signin.js +18 -0
  49. package/dist/routes/auth/viability.d.ts +2 -0
  50. package/dist/routes/auth/viability.js +88 -0
  51. package/dist/routes/mfa/backup-code-verify.d.ts +1 -0
  52. package/dist/routes/mfa/backup-code-verify.js +5 -0
  53. package/dist/routes/mfa/backup-codes.d.ts +10 -0
  54. package/dist/routes/mfa/backup-codes.js +14 -0
  55. package/dist/routes/mfa/methods.d.ts +21 -0
  56. package/dist/routes/mfa/methods.js +10 -0
  57. package/dist/routes/mfa/totp-confirm.d.ts +10 -0
  58. package/dist/routes/mfa/totp-confirm.js +14 -0
  59. package/dist/routes/mfa/totp-enroll.d.ts +10 -0
  60. package/dist/routes/mfa/totp-enroll.js +14 -0
  61. package/dist/routes/mfa/totp-verify.d.ts +14 -0
  62. package/dist/routes/mfa/totp-verify.js +18 -0
  63. package/dist/routes/passkeys/list.d.ts +10 -0
  64. package/dist/routes/passkeys/list.js +14 -0
  65. package/dist/routes/passkeys/manage.d.ts +18 -0
  66. package/dist/routes/passkeys/manage.js +13 -0
  67. package/dist/routes/passkeys/register-options.d.ts +10 -0
  68. package/dist/routes/passkeys/register-options.js +14 -0
  69. package/dist/routes/passkeys/register-verify.d.ts +10 -0
  70. package/dist/routes/passkeys/register-verify.js +14 -0
  71. package/dist/server/auth.d.ts +2 -2
  72. package/dist/server/decode-session.js +37 -3
  73. package/package.json +958 -893
  74. package/scripts/check-internal-url-usage.sh +73 -73
  75. package/src/api/index.ts +17 -17
  76. package/src/api-handlers/account/masked-info.ts +45 -45
  77. package/src/api-handlers/account/profile.ts +99 -80
  78. package/src/api-handlers/account/recovery/initiate.ts +23 -23
  79. package/src/api-handlers/account/recovery/send-code.ts +73 -25
  80. package/src/api-handlers/account/recovery/verify-code.ts +73 -25
  81. package/src/api-handlers/account/reset-password.ts +23 -23
  82. package/src/api-handlers/account/send-code.ts +76 -76
  83. package/src/api-handlers/account/validate-password.ts +118 -118
  84. package/src/api-handlers/account/verify-email.ts +15 -1
  85. package/src/api-handlers/account/verify-sms.ts +15 -1
  86. package/src/api-handlers/admin/stats.ts +249 -249
  87. package/src/api-handlers/anon/preferences.ts +123 -123
  88. package/src/api-handlers/auth/jwks.ts +20 -20
  89. package/src/api-handlers/auth/login.ts +240 -240
  90. package/src/api-handlers/auth/passkey-signin.ts +98 -0
  91. package/src/api-handlers/auth/validate.ts +43 -43
  92. package/src/api-handlers/mfa/backup-code-verify.ts +175 -0
  93. package/src/api-handlers/mfa/backup-codes.ts +41 -0
  94. package/src/api-handlers/mfa/methods.ts +46 -0
  95. package/src/api-handlers/mfa/totp-confirm.ts +42 -0
  96. package/src/api-handlers/mfa/totp-enroll.ts +42 -0
  97. package/src/api-handlers/mfa/totp-verify.ts +156 -0
  98. package/src/api-handlers/passkeys/list.ts +31 -0
  99. package/src/api-handlers/passkeys/manage.ts +54 -0
  100. package/src/api-handlers/passkeys/register-options.ts +42 -0
  101. package/src/api-handlers/passkeys/register-verify.ts +41 -0
  102. package/src/api-handlers/session/viability.ts +161 -142
  103. package/src/auth/better-auth.ts +708 -455
  104. package/src/auth/unauthenticated-routes.ts +2 -2
  105. package/src/auth/utils/idp-client.ts +13 -95
  106. package/src/client/better-auth-client.ts +70 -70
  107. package/src/client/fetchWithSession.ts +21 -21
  108. package/src/client/index.ts +13 -13
  109. package/src/client/useAnonSession.ts +131 -131
  110. package/src/components/admin/VibeAdminContext.tsx +87 -87
  111. package/src/config/logging-config.ts +82 -82
  112. package/src/config/unauthenticated-routes.ts +19 -19
  113. package/src/edge/internal-api-url.ts +65 -65
  114. package/src/edge/middleware.ts +42 -42
  115. package/src/hooks/useProfile.ts +75 -75
  116. package/src/lib/anon-session.ts +213 -213
  117. package/src/lib/auth-secret.ts +137 -137
  118. package/src/lib/demo-mode.ts +17 -17
  119. package/src/lib/ensure-fresh-access-token.ts +13 -2
  120. package/src/lib/idp-client-config.ts +559 -559
  121. package/src/lib/idp-fetch.ts +126 -126
  122. package/src/lib/internal-api.ts +171 -171
  123. package/src/lib/jwt-decode-client.ts +45 -45
  124. package/src/lib/rate-limit-service.ts +9 -9
  125. package/src/lib/redis.ts +26 -26
  126. package/src/lib/refresh-token-validator.ts +64 -64
  127. package/src/lib/secret-validation.ts +8 -8
  128. package/src/lib/session-store.ts +702 -695
  129. package/src/lib/session.ts +34 -34
  130. package/src/lib/startup-init.ts +251 -251
  131. package/src/lib/token-expiry.ts +40 -40
  132. package/src/lib/token-lifecycle.ts +533 -470
  133. package/src/lib/types/api-responses.ts +336 -336
  134. package/src/middleware/auth-decision.ts +43 -43
  135. package/src/models/DecodedAccessToken.ts +16 -16
  136. package/src/models/SessionModel.ts +282 -264
  137. package/src/pages/admin-roles/index.ts +9 -9
  138. package/src/pages/login/page.tsx +123 -228
  139. package/src/pages/security/EnhancedSecurityPage.tsx +9 -9
  140. package/src/pages/verify-code/page.tsx +71 -5
  141. package/src/routes/account/index.ts +31 -31
  142. package/src/routes/account/masked-info.ts +36 -36
  143. package/src/routes/account/send-code.ts +39 -39
  144. package/src/routes/account/verify-email.ts +40 -40
  145. package/src/routes/account/verify-sms.ts +40 -40
  146. package/src/routes/auth/index.ts +22 -22
  147. package/src/routes/auth/passkey-signin.ts +13 -0
  148. package/src/routes/auth/refresh.ts +48 -48
  149. package/src/routes/auth/session.ts +166 -166
  150. package/src/routes/auth/viability.ts +89 -0
  151. package/src/routes/index.ts +17 -17
  152. package/src/routes/mfa/backup-code-verify.ts +1 -0
  153. package/src/routes/mfa/backup-codes.ts +10 -0
  154. package/src/routes/mfa/methods.ts +22 -0
  155. package/src/routes/mfa/totp-confirm.ts +10 -0
  156. package/src/routes/mfa/totp-enroll.ts +10 -0
  157. package/src/routes/mfa/totp-verify.ts +14 -0
  158. package/src/routes/passkeys/list.ts +10 -0
  159. package/src/routes/passkeys/manage.ts +23 -0
  160. package/src/routes/passkeys/register-options.ts +10 -0
  161. package/src/routes/passkeys/register-verify.ts +10 -0
  162. package/src/routes/session/index.ts +7 -7
  163. package/src/routes/session/refresh-viability.ts +17 -17
  164. package/src/server/auth.ts +373 -373
  165. package/src/server/decode-session.ts +235 -202
  166. package/src/services/signalrActivityService.ts +258 -258
  167. package/src/theme/ThemeProvider.tsx +39 -39
  168. package/src/theme/default.ts +33 -33
  169. package/src/theme/index.ts +31 -31
  170. package/src/theme/types.ts +69 -69
  171. package/src/theme/useTheme.ts +57 -57
  172. package/src/theme/utils.ts +40 -40
  173. package/src/types/api.ts +12 -12
  174. package/src/types/auth.d.ts +23 -23
  175. package/src/types/auth.ts +22 -22
  176. package/src/types/logging.ts +11 -11
  177. package/src/types/recovery.ts +54 -54
  178. package/src/utils/api.ts +353 -353
  179. package/src/utils/circuitBreaker.ts +40 -40
  180. package/src/utils/error-message.ts +108 -108
  181. package/src/utils/layout/reservedSpace.ts +124 -124
package/src/utils/api.ts CHANGED
@@ -1,353 +1,353 @@
1
- import { ENV_CONFIG, API_ENDPOINTS } from '../config/env';
2
- import { TwoFactorMethod } from '../types/security';
3
- import { standardizedApi, isApiSuccess, isApiError, extractApiData } from '../lib/standardized-client-api';
4
-
5
- export class ApiError extends Error {
6
- type: string;
7
- title: string;
8
- status: number;
9
- detail?: string;
10
- traceId?: string;
11
- errors?: Record<string, string[]>;
12
-
13
- constructor(message: string, details: any) {
14
- super(message);
15
- this.name = 'ApiError';
16
- this.type = details.type || 'UnknownError';
17
- this.title = details.title || message;
18
- this.status = details.status || 500;
19
- this.detail = details.detail;
20
- this.traceId = details.traceId;
21
- this.errors = details.errors;
22
- }
23
- }
24
-
25
- export interface ApiOptions {
26
- method?: string;
27
- body?: any;
28
- headers?: Record<string, string>;
29
- }
30
-
31
- export interface ApiResponse<T> {
32
- success: boolean;
33
- data?: T;
34
- error?: string;
35
- type?: string;
36
- title?: string;
37
- status?: number;
38
- errors?: Record<string, string[]>;
39
- traceId?: string;
40
- message?: string;
41
- }
42
-
43
- export async function apiFetch<T>(url: string, options: ApiOptions = {}): Promise<ApiResponse<T>> {
44
- const { method = 'GET', body, headers = {} } = options;
45
- let finalBody = body;
46
- const fetchOptions: RequestInit = {
47
- method,
48
- headers: {
49
- 'Content-Type': 'application/json',
50
- ...headers,
51
- },
52
- credentials: 'include',
53
- ...(finalBody ? { body: JSON.stringify(finalBody) } : {}),
54
- };
55
-
56
- let res = await fetch(url, fetchOptions);
57
- // If we get a 401, it may be a transient during server-side token refresh. Retry once after a short delay.
58
- if (res.status === 401) {
59
- await new Promise(resolve => setTimeout(resolve, 250));
60
- res = await fetch(url, fetchOptions);
61
- }
62
- const raw = await res.json().catch(() => ({}));
63
-
64
- if (!res.ok) {
65
- throw new ApiError((raw as any)?.message || 'API Error', raw);
66
- }
67
-
68
- // --- Universal normalization here ---
69
- let normalized: ApiResponse<T>;
70
- if (raw && typeof raw === 'object') {
71
- if ('data' in raw && typeof raw.data === 'object' && raw.data !== null) {
72
- // Already wrapped
73
- normalized = { ...raw };
74
- } else {
75
- // Not wrapped: move all fields except known meta to data
76
- const { success, error, errors, message, type, title, status, traceId, ...data } = raw;
77
- normalized = {
78
- success: typeof success === 'boolean' ? success : true,
79
- data: data as T,
80
- error,
81
- errors,
82
- message,
83
- type,
84
- title,
85
- status,
86
- traceId,
87
- };
88
- }
89
- } else {
90
- normalized = { success: true, data: raw as T };
91
- }
92
-
93
- return normalized;
94
- }
95
-
96
- // DELETED: apiFetchAuth - Use clientApi from @/lib/client-api instead for proper token refresh handling
97
-
98
- // Account API for masked info and 2FA
99
- export class AccountApi {
100
- /**
101
- * Get masked user info (email, phone, authenticator status)
102
- * User identification comes from JWT token in Authorization header, not from request body
103
- */
104
- async getMaskedInfo(accessToken?: string): Promise<{
105
- maskedEmail: string;
106
- maskedPhoneNumber: string;
107
- hasAuthenticator: boolean;
108
- method?: TwoFactorMethod;
109
- }> {
110
- // Require authentication for masked info retrieval; do not infer from session or token locally
111
- if (!accessToken) {
112
- throw new ApiError('Not authenticated', { status: 401, title: 'Unauthorized' });
113
- }
114
-
115
- // Authenticated request - proxy through Next API to IDP
116
- // Empty body: user info comes from JWT token
117
- const result = await standardizedApi.post<any>('/api/account/masked-info', {}, accessToken);
118
-
119
- console.log('[DEBUG] getMaskedInfo result:', {
120
- success: isApiSuccess(result),
121
- hasData: isApiSuccess(result) && !!result.data,
122
- rawData: isApiSuccess(result) ? result.data : null,
123
- dataFields: isApiSuccess(result) && result.data ? Object.keys(result.data) : []
124
- });
125
-
126
- console.log('[DEBUG] getMaskedInfo raw data structure:', JSON.stringify(isApiSuccess(result) ? result.data : result, null, 2));
127
-
128
- if (!isApiSuccess(result)) {
129
- const errorMessage = isApiError(result) ? result.message : 'Failed to get masked info';
130
- console.error('[DEBUG] getMaskedInfo failed:', result);
131
- throw new ApiError(errorMessage, result);
132
- }
133
- // Use only snake_case fields from backend response
134
- const d = result.data.data || result.data; // Access the nested data object
135
- const maskedInfoResult = {
136
- maskedEmail: d.masked_email ?? '',
137
- maskedPhoneNumber: d.masked_phone_number ?? '',
138
- hasAuthenticator: d.has_authenticator ?? false,
139
- method: d.method as TwoFactorMethod
140
- };
141
-
142
- console.log('[DEBUG] getMaskedInfo result:', maskedInfoResult);
143
- return maskedInfoResult;
144
- }
145
-
146
- async initiateRecovery(email: string) {
147
- const res = await fetch('/api/account/recovery/initiate', {
148
- method: 'POST',
149
- headers: { 'Content-Type': 'application/json' },
150
- body: JSON.stringify({ email }),
151
- });
152
- if (!res.ok) throw new Error('Failed to initiate recovery');
153
- return res.json();
154
- }
155
-
156
- async sendRecoveryCode(recoveryToken: string, method: 'email' | 'sms' | 'authenticator') {
157
- const res = await fetch('/api/account/recovery/send-code', {
158
- method: 'POST',
159
- headers: {
160
- 'Content-Type': 'application/json',
161
- 'Authorization': `Bearer ${recoveryToken}`
162
- },
163
- body: JSON.stringify({ method }),
164
- });
165
- if (!res.ok) throw new Error('Failed to send recovery code');
166
- return res.json();
167
- }
168
-
169
- async verifyRecoveryCode(recoveryToken: string, code: string, method: string) {
170
- const res = await fetch('/api/account/recovery/verify-code', {
171
- method: 'POST',
172
- headers: {
173
- 'Content-Type': 'application/json',
174
- 'Authorization': `Bearer ${recoveryToken}`
175
- },
176
- body: JSON.stringify({ code, method }),
177
- });
178
- if (!res.ok) {
179
- const e = await res.json().catch(() => null);
180
- throw new Error(e?.error?.message || 'Invalid verification code');
181
- }
182
- return res.json();
183
- }
184
-
185
- async resetPasswordWithToken(
186
- email: string,
187
- resetToken: string,
188
- newPassword: string,
189
- confirmPassword: string
190
- ) {
191
- const res = await fetch('/api/account/reset-password', {
192
- method: 'POST',
193
- headers: { 'Content-Type': 'application/json' },
194
- body: JSON.stringify({
195
- email,
196
- password_reset_token: resetToken,
197
- new_password: newPassword,
198
- confirm_password: confirmPassword,
199
- }),
200
- });
201
- if (!res.ok) throw new Error('Failed to reset password');
202
- return res.json();
203
- }
204
-
205
- async resetPassword(data: { email: string; token: string; password: string; password_confirmation: string }) {
206
- // Proxy to server API which in turn proxies to IDP
207
- const res = await fetch('/api/account/reset-password', {
208
- method: 'POST',
209
- headers: { 'Content-Type': 'application/json' },
210
- body: JSON.stringify({
211
- email: data.email,
212
- token: data.token,
213
- password: data.password,
214
- password_confirmation: data.password_confirmation
215
- })
216
- })
217
- const result = await res.json().catch(() => ({}))
218
- if (!res.ok || (result && result.success === false)) {
219
- const msg = result?.message || 'Failed to reset password'
220
- throw new ApiError(msg, result)
221
- }
222
- return result
223
- }
224
-
225
- // Onboarding flow methods
226
- async verifyWelcomeEmail(onboardToken: string, clientKey?: string): Promise<{
227
- maskedEmail: string;
228
- maskedPhoneNumber?: string;
229
- hasAuthenticator?: boolean;
230
- expiryMinutes: number;
231
- clientKey: string;
232
- }> {
233
- const qs = clientKey ? `?client_id=${encodeURIComponent(clientKey)}` : '';
234
- console.log('[accountApi.verifyWelcomeEmail] POST /api/onboarding/verify-welcome-email', { qs, onboardTokenLen: onboardToken?.length });
235
- const res = await fetch(`/api/onboarding/verify-welcome-email${qs}`, {
236
- method: 'POST',
237
- headers: { 'Content-Type': 'application/json' },
238
- body: JSON.stringify({ onboard_token: onboardToken })
239
- });
240
- const result = await res.json().catch(() => ({}));
241
- console.log('[accountApi.verifyWelcomeEmail] Response status:', res.status, 'body keys:', result && typeof result === 'object' ? Object.keys(result) : typeof result);
242
- if (!res.ok || (result && result.success === false)) {
243
- const msg = result?.message || 'Failed to verify welcome email';
244
- throw new ApiError(msg, result);
245
- }
246
- // Extract from nested data structure
247
- const data = result.data?.data || result.data || {} as any;
248
- const masked = data.masked_user_info || {};
249
- return {
250
- maskedEmail: masked.masked_email || '',
251
- maskedPhoneNumber: masked.masked_phone_number || '',
252
- hasAuthenticator: masked.has_authenticator ?? undefined,
253
- expiryMinutes: data.expiry_minutes || 10,
254
- clientKey: data.client_key || ''
255
- };
256
- }
257
-
258
- // Back-compat alias
259
- async sendOnboardingCode(onboardToken: string, clientKey?: string) {
260
- return this.verifyWelcomeEmail(onboardToken, clientKey);
261
- }
262
-
263
- async verifyOnboardingCode(onboardToken: string, code: string, clientKey?: string): Promise<{
264
- success: boolean;
265
- resetToken: string;
266
- email: string;
267
- clientKey: string;
268
- }> {
269
- const qs = clientKey ? `?clientId=${encodeURIComponent(clientKey)}` : '';
270
- const res = await fetch(`/api/onboarding/verify-code${qs}`, {
271
- method: 'POST',
272
- headers: { 'Content-Type': 'application/json' },
273
- body: JSON.stringify({
274
- onboard_token: onboardToken,
275
- code: code
276
- })
277
- });
278
- const result = await res.json().catch(() => ({}));
279
- if (!res.ok || (result && result.success === false)) {
280
- const msg = result?.message || 'Invalid verification code';
281
- throw new ApiError(msg, result);
282
- }
283
- // Extract from nested data structure
284
- const data = result.data?.data || result.data || {};
285
- return {
286
- success: data.success !== false,
287
- resetToken: data.reset_token || '',
288
- email: data.email || '',
289
- clientKey: data.client_key || ''
290
- };
291
- }
292
-
293
- async verifyOnboardingSmsCode(onboardToken: string, code: string, clientKey?: string): Promise<{
294
- success: boolean;
295
- resetToken: string;
296
- email: string;
297
- clientKey: string;
298
- }> {
299
- const qs = clientKey ? `?clientId=${encodeURIComponent(clientKey)}` : '';
300
- const res = await fetch(`/api/onboarding/verify-sms-code${qs}`, {
301
- method: 'POST',
302
- headers: { 'Content-Type': 'application/json' },
303
- body: JSON.stringify({
304
- onboard_token: onboardToken,
305
- code: code
306
- })
307
- });
308
- const result = await res.json().catch(() => ({}));
309
- if (!res.ok || (result && result.success === false)) {
310
- const msg = result?.message || 'Invalid verification code';
311
- throw new ApiError(msg, result);
312
- }
313
- // Extract from nested data structure
314
- const data = result.data?.data || result.data || {};
315
- return {
316
- success: data.success !== false,
317
- resetToken: data.reset_token || '',
318
- email: data.email || '',
319
- clientKey: data.client_key || ''
320
- };
321
- }
322
-
323
- async setOnboardingPassword(data: {
324
- onboardToken: string;
325
- email: string;
326
- resetToken: string;
327
- newPassword: string;
328
- }, clientKey?: string): Promise<{ success: boolean; message?: string }> {
329
- const qs = clientKey ? `?clientId=${encodeURIComponent(clientKey)}` : '';
330
- const res = await fetch(`/api/onboarding/set-password${qs}`, {
331
- method: 'POST',
332
- headers: { 'Content-Type': 'application/json' },
333
- body: JSON.stringify({
334
- onboard_token: data.onboardToken,
335
- email: data.email,
336
- reset_token: data.resetToken,
337
- new_password: data.newPassword
338
- })
339
- });
340
- const result = await res.json().catch(() => ({}));
341
- if (!res.ok || (result && result.success === false)) {
342
- const msg = result?.message || 'Failed to set password';
343
- throw new ApiError(msg, result);
344
- }
345
- return {
346
- success: result.success !== false,
347
- message: result.message || result.data?.message
348
- };
349
- }
350
- }
351
-
352
- export const accountApi = new AccountApi();
353
-
1
+ import { ENV_CONFIG, API_ENDPOINTS } from '../config/env';
2
+ import { TwoFactorMethod } from '../types/security';
3
+ import { standardizedApi, isApiSuccess, isApiError, extractApiData } from '../lib/standardized-client-api';
4
+
5
+ export class ApiError extends Error {
6
+ type: string;
7
+ title: string;
8
+ status: number;
9
+ detail?: string;
10
+ traceId?: string;
11
+ errors?: Record<string, string[]>;
12
+
13
+ constructor(message: string, details: any) {
14
+ super(message);
15
+ this.name = 'ApiError';
16
+ this.type = details.type || 'UnknownError';
17
+ this.title = details.title || message;
18
+ this.status = details.status || 500;
19
+ this.detail = details.detail;
20
+ this.traceId = details.traceId;
21
+ this.errors = details.errors;
22
+ }
23
+ }
24
+
25
+ export interface ApiOptions {
26
+ method?: string;
27
+ body?: any;
28
+ headers?: Record<string, string>;
29
+ }
30
+
31
+ export interface ApiResponse<T> {
32
+ success: boolean;
33
+ data?: T;
34
+ error?: string;
35
+ type?: string;
36
+ title?: string;
37
+ status?: number;
38
+ errors?: Record<string, string[]>;
39
+ traceId?: string;
40
+ message?: string;
41
+ }
42
+
43
+ export async function apiFetch<T>(url: string, options: ApiOptions = {}): Promise<ApiResponse<T>> {
44
+ const { method = 'GET', body, headers = {} } = options;
45
+ let finalBody = body;
46
+ const fetchOptions: RequestInit = {
47
+ method,
48
+ headers: {
49
+ 'Content-Type': 'application/json',
50
+ ...headers,
51
+ },
52
+ credentials: 'include',
53
+ ...(finalBody ? { body: JSON.stringify(finalBody) } : {}),
54
+ };
55
+
56
+ let res = await fetch(url, fetchOptions);
57
+ // If we get a 401, it may be a transient during server-side token refresh. Retry once after a short delay.
58
+ if (res.status === 401) {
59
+ await new Promise(resolve => setTimeout(resolve, 250));
60
+ res = await fetch(url, fetchOptions);
61
+ }
62
+ const raw = await res.json().catch(() => ({}));
63
+
64
+ if (!res.ok) {
65
+ throw new ApiError((raw as any)?.message || 'API Error', raw);
66
+ }
67
+
68
+ // --- Universal normalization here ---
69
+ let normalized: ApiResponse<T>;
70
+ if (raw && typeof raw === 'object') {
71
+ if ('data' in raw && typeof raw.data === 'object' && raw.data !== null) {
72
+ // Already wrapped
73
+ normalized = { ...raw };
74
+ } else {
75
+ // Not wrapped: move all fields except known meta to data
76
+ const { success, error, errors, message, type, title, status, traceId, ...data } = raw;
77
+ normalized = {
78
+ success: typeof success === 'boolean' ? success : true,
79
+ data: data as T,
80
+ error,
81
+ errors,
82
+ message,
83
+ type,
84
+ title,
85
+ status,
86
+ traceId,
87
+ };
88
+ }
89
+ } else {
90
+ normalized = { success: true, data: raw as T };
91
+ }
92
+
93
+ return normalized;
94
+ }
95
+
96
+ // DELETED: apiFetchAuth - Use clientApi from @/lib/client-api instead for proper token refresh handling
97
+
98
+ // Account API for masked info and 2FA
99
+ export class AccountApi {
100
+ /**
101
+ * Get masked user info (email, phone, authenticator status)
102
+ * User identification comes from JWT token in Authorization header, not from request body
103
+ */
104
+ async getMaskedInfo(accessToken?: string): Promise<{
105
+ maskedEmail: string;
106
+ maskedPhoneNumber: string;
107
+ hasAuthenticator: boolean;
108
+ method?: TwoFactorMethod;
109
+ }> {
110
+ // Require authentication for masked info retrieval; do not infer from session or token locally
111
+ if (!accessToken) {
112
+ throw new ApiError('Not authenticated', { status: 401, title: 'Unauthorized' });
113
+ }
114
+
115
+ // Authenticated request - proxy through Next API to IDP
116
+ // Empty body: user info comes from JWT token
117
+ const result = await standardizedApi.post<any>('/api/account/masked-info', {}, accessToken);
118
+
119
+ console.log('[DEBUG] getMaskedInfo result:', {
120
+ success: isApiSuccess(result),
121
+ hasData: isApiSuccess(result) && !!result.data,
122
+ rawData: isApiSuccess(result) ? result.data : null,
123
+ dataFields: isApiSuccess(result) && result.data ? Object.keys(result.data) : []
124
+ });
125
+
126
+ console.log('[DEBUG] getMaskedInfo raw data structure:', JSON.stringify(isApiSuccess(result) ? result.data : result, null, 2));
127
+
128
+ if (!isApiSuccess(result)) {
129
+ const errorMessage = isApiError(result) ? result.message : 'Failed to get masked info';
130
+ console.error('[DEBUG] getMaskedInfo failed:', result);
131
+ throw new ApiError(errorMessage, result);
132
+ }
133
+ // Use only snake_case fields from backend response
134
+ const d = result.data.data || result.data; // Access the nested data object
135
+ const maskedInfoResult = {
136
+ maskedEmail: d.masked_email ?? '',
137
+ maskedPhoneNumber: d.masked_phone_number ?? '',
138
+ hasAuthenticator: d.has_authenticator ?? false,
139
+ method: d.method as TwoFactorMethod
140
+ };
141
+
142
+ console.log('[DEBUG] getMaskedInfo result:', maskedInfoResult);
143
+ return maskedInfoResult;
144
+ }
145
+
146
+ async initiateRecovery(email: string) {
147
+ const res = await fetch('/api/account/recovery/initiate', {
148
+ method: 'POST',
149
+ headers: { 'Content-Type': 'application/json' },
150
+ body: JSON.stringify({ email }),
151
+ });
152
+ if (!res.ok) throw new Error('Failed to initiate recovery');
153
+ return res.json();
154
+ }
155
+
156
+ async sendRecoveryCode(recoveryToken: string, method: 'email' | 'sms' | 'authenticator') {
157
+ const res = await fetch('/api/account/recovery/send-code', {
158
+ method: 'POST',
159
+ headers: {
160
+ 'Content-Type': 'application/json',
161
+ 'Authorization': `Bearer ${recoveryToken}`
162
+ },
163
+ body: JSON.stringify({ method }),
164
+ });
165
+ if (!res.ok) throw new Error('Failed to send recovery code');
166
+ return res.json();
167
+ }
168
+
169
+ async verifyRecoveryCode(recoveryToken: string, code: string, method: string) {
170
+ const res = await fetch('/api/account/recovery/verify-code', {
171
+ method: 'POST',
172
+ headers: {
173
+ 'Content-Type': 'application/json',
174
+ 'Authorization': `Bearer ${recoveryToken}`
175
+ },
176
+ body: JSON.stringify({ code, method }),
177
+ });
178
+ if (!res.ok) {
179
+ const e = await res.json().catch(() => null);
180
+ throw new Error(e?.error?.message || 'Invalid verification code');
181
+ }
182
+ return res.json();
183
+ }
184
+
185
+ async resetPasswordWithToken(
186
+ email: string,
187
+ resetToken: string,
188
+ newPassword: string,
189
+ confirmPassword: string
190
+ ) {
191
+ const res = await fetch('/api/account/reset-password', {
192
+ method: 'POST',
193
+ headers: { 'Content-Type': 'application/json' },
194
+ body: JSON.stringify({
195
+ email,
196
+ password_reset_token: resetToken,
197
+ new_password: newPassword,
198
+ confirm_password: confirmPassword,
199
+ }),
200
+ });
201
+ if (!res.ok) throw new Error('Failed to reset password');
202
+ return res.json();
203
+ }
204
+
205
+ async resetPassword(data: { email: string; token: string; password: string; password_confirmation: string }) {
206
+ // Proxy to server API which in turn proxies to IDP
207
+ const res = await fetch('/api/account/reset-password', {
208
+ method: 'POST',
209
+ headers: { 'Content-Type': 'application/json' },
210
+ body: JSON.stringify({
211
+ email: data.email,
212
+ token: data.token,
213
+ password: data.password,
214
+ password_confirmation: data.password_confirmation
215
+ })
216
+ })
217
+ const result = await res.json().catch(() => ({}))
218
+ if (!res.ok || (result && result.success === false)) {
219
+ const msg = result?.message || 'Failed to reset password'
220
+ throw new ApiError(msg, result)
221
+ }
222
+ return result
223
+ }
224
+
225
+ // Onboarding flow methods
226
+ async verifyWelcomeEmail(onboardToken: string, clientKey?: string): Promise<{
227
+ maskedEmail: string;
228
+ maskedPhoneNumber?: string;
229
+ hasAuthenticator?: boolean;
230
+ expiryMinutes: number;
231
+ clientKey: string;
232
+ }> {
233
+ const qs = clientKey ? `?client_id=${encodeURIComponent(clientKey)}` : '';
234
+ console.log('[accountApi.verifyWelcomeEmail] POST /api/onboarding/verify-welcome-email', { qs, onboardTokenLen: onboardToken?.length });
235
+ const res = await fetch(`/api/onboarding/verify-welcome-email${qs}`, {
236
+ method: 'POST',
237
+ headers: { 'Content-Type': 'application/json' },
238
+ body: JSON.stringify({ onboard_token: onboardToken })
239
+ });
240
+ const result = await res.json().catch(() => ({}));
241
+ console.log('[accountApi.verifyWelcomeEmail] Response status:', res.status, 'body keys:', result && typeof result === 'object' ? Object.keys(result) : typeof result);
242
+ if (!res.ok || (result && result.success === false)) {
243
+ const msg = result?.message || 'Failed to verify welcome email';
244
+ throw new ApiError(msg, result);
245
+ }
246
+ // Extract from nested data structure
247
+ const data = result.data?.data || result.data || {} as any;
248
+ const masked = data.masked_user_info || {};
249
+ return {
250
+ maskedEmail: masked.masked_email || '',
251
+ maskedPhoneNumber: masked.masked_phone_number || '',
252
+ hasAuthenticator: masked.has_authenticator ?? undefined,
253
+ expiryMinutes: data.expiry_minutes || 10,
254
+ clientKey: data.client_key || ''
255
+ };
256
+ }
257
+
258
+ // Back-compat alias
259
+ async sendOnboardingCode(onboardToken: string, clientKey?: string) {
260
+ return this.verifyWelcomeEmail(onboardToken, clientKey);
261
+ }
262
+
263
+ async verifyOnboardingCode(onboardToken: string, code: string, clientKey?: string): Promise<{
264
+ success: boolean;
265
+ resetToken: string;
266
+ email: string;
267
+ clientKey: string;
268
+ }> {
269
+ const qs = clientKey ? `?clientId=${encodeURIComponent(clientKey)}` : '';
270
+ const res = await fetch(`/api/onboarding/verify-code${qs}`, {
271
+ method: 'POST',
272
+ headers: { 'Content-Type': 'application/json' },
273
+ body: JSON.stringify({
274
+ onboard_token: onboardToken,
275
+ code: code
276
+ })
277
+ });
278
+ const result = await res.json().catch(() => ({}));
279
+ if (!res.ok || (result && result.success === false)) {
280
+ const msg = result?.message || 'Invalid verification code';
281
+ throw new ApiError(msg, result);
282
+ }
283
+ // Extract from nested data structure
284
+ const data = result.data?.data || result.data || {};
285
+ return {
286
+ success: data.success !== false,
287
+ resetToken: data.reset_token || '',
288
+ email: data.email || '',
289
+ clientKey: data.client_key || ''
290
+ };
291
+ }
292
+
293
+ async verifyOnboardingSmsCode(onboardToken: string, code: string, clientKey?: string): Promise<{
294
+ success: boolean;
295
+ resetToken: string;
296
+ email: string;
297
+ clientKey: string;
298
+ }> {
299
+ const qs = clientKey ? `?clientId=${encodeURIComponent(clientKey)}` : '';
300
+ const res = await fetch(`/api/onboarding/verify-sms-code${qs}`, {
301
+ method: 'POST',
302
+ headers: { 'Content-Type': 'application/json' },
303
+ body: JSON.stringify({
304
+ onboard_token: onboardToken,
305
+ code: code
306
+ })
307
+ });
308
+ const result = await res.json().catch(() => ({}));
309
+ if (!res.ok || (result && result.success === false)) {
310
+ const msg = result?.message || 'Invalid verification code';
311
+ throw new ApiError(msg, result);
312
+ }
313
+ // Extract from nested data structure
314
+ const data = result.data?.data || result.data || {};
315
+ return {
316
+ success: data.success !== false,
317
+ resetToken: data.reset_token || '',
318
+ email: data.email || '',
319
+ clientKey: data.client_key || ''
320
+ };
321
+ }
322
+
323
+ async setOnboardingPassword(data: {
324
+ onboardToken: string;
325
+ email: string;
326
+ resetToken: string;
327
+ newPassword: string;
328
+ }, clientKey?: string): Promise<{ success: boolean; message?: string }> {
329
+ const qs = clientKey ? `?clientId=${encodeURIComponent(clientKey)}` : '';
330
+ const res = await fetch(`/api/onboarding/set-password${qs}`, {
331
+ method: 'POST',
332
+ headers: { 'Content-Type': 'application/json' },
333
+ body: JSON.stringify({
334
+ onboard_token: data.onboardToken,
335
+ email: data.email,
336
+ reset_token: data.resetToken,
337
+ new_password: data.newPassword
338
+ })
339
+ });
340
+ const result = await res.json().catch(() => ({}));
341
+ if (!res.ok || (result && result.success === false)) {
342
+ const msg = result?.message || 'Failed to set password';
343
+ throw new ApiError(msg, result);
344
+ }
345
+ return {
346
+ success: result.success !== false,
347
+ message: result.message || result.data?.message
348
+ };
349
+ }
350
+ }
351
+
352
+ export const accountApi = new AccountApi();
353
+