@payez/next-mvp 4.1.11 → 4.1.13

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 (92) hide show
  1. package/dist/api-handlers/auth/refresh.js +15 -38
  2. package/dist/auth/better-auth.d.ts +0 -3
  3. package/dist/auth/better-auth.js +164 -69
  4. package/dist/client/better-auth-client.d.ts +14 -2
  5. package/dist/lib/ensure-fresh-access-token.js +8 -42
  6. package/dist/lib/session-store.d.ts +0 -1
  7. package/dist/lib/session-store.js +29 -33
  8. package/dist/lib/startup-init.js +19 -19
  9. package/dist/lib/token-lifecycle.d.ts +0 -2
  10. package/dist/lib/token-lifecycle.js +3 -21
  11. package/package.json +5 -4
  12. package/scripts/check-internal-url-usage.sh +73 -73
  13. package/src/api/index.ts +17 -17
  14. package/src/api-handlers/account/masked-info.ts +45 -45
  15. package/src/api-handlers/account/profile.ts +80 -80
  16. package/src/api-handlers/account/recovery/initiate.ts +23 -23
  17. package/src/api-handlers/account/recovery/send-code.ts +25 -25
  18. package/src/api-handlers/account/recovery/verify-code.ts +25 -25
  19. package/src/api-handlers/account/reset-password.ts +23 -23
  20. package/src/api-handlers/account/send-code.ts +76 -76
  21. package/src/api-handlers/account/validate-password.ts +118 -118
  22. package/src/api-handlers/admin/stats.ts +249 -249
  23. package/src/api-handlers/anon/preferences.ts +123 -123
  24. package/src/api-handlers/auth/jwks.ts +20 -20
  25. package/src/api-handlers/auth/login.ts +240 -240
  26. package/src/api-handlers/auth/refresh.ts +15 -38
  27. package/src/api-handlers/auth/validate.ts +43 -43
  28. package/src/api-handlers/session/viability.ts +142 -142
  29. package/src/auth/better-auth.ts +130 -29
  30. package/src/auth/unauthenticated-routes.ts +2 -2
  31. package/src/client/better-auth-client.ts +70 -70
  32. package/src/client/fetchWithSession.ts +21 -21
  33. package/src/client/index.ts +13 -13
  34. package/src/client/useAnonSession.ts +131 -131
  35. package/src/components/admin/VibeAdminContext.tsx +87 -87
  36. package/src/config/logging-config.ts +82 -82
  37. package/src/config/unauthenticated-routes.ts +19 -19
  38. package/src/edge/internal-api-url.ts +65 -65
  39. package/src/edge/middleware.ts +42 -42
  40. package/src/hooks/useProfile.ts +75 -75
  41. package/src/lib/anon-session.ts +213 -213
  42. package/src/lib/auth-secret.ts +137 -137
  43. package/src/lib/demo-mode.ts +17 -17
  44. package/src/lib/ensure-fresh-access-token.ts +8 -42
  45. package/src/lib/idp-client-config.ts +559 -559
  46. package/src/lib/idp-fetch.ts +126 -126
  47. package/src/lib/internal-api.ts +171 -171
  48. package/src/lib/jwt-decode-client.ts +45 -45
  49. package/src/lib/rate-limit-service.ts +9 -9
  50. package/src/lib/redis.ts +26 -26
  51. package/src/lib/refresh-token-validator.ts +64 -64
  52. package/src/lib/secret-validation.ts +8 -8
  53. package/src/lib/session-store.ts +692 -695
  54. package/src/lib/session.ts +34 -34
  55. package/src/lib/startup-init.ts +251 -251
  56. package/src/lib/token-expiry.ts +40 -40
  57. package/src/lib/token-lifecycle.ts +470 -497
  58. package/src/lib/types/api-responses.ts +336 -336
  59. package/src/middleware/auth-decision.ts +43 -43
  60. package/src/models/DecodedAccessToken.ts +16 -16
  61. package/src/models/SessionModel.ts +264 -264
  62. package/src/pages/admin-roles/index.ts +9 -9
  63. package/src/pages/security/EnhancedSecurityPage.tsx +9 -9
  64. package/src/routes/account/index.ts +31 -31
  65. package/src/routes/account/masked-info.ts +36 -36
  66. package/src/routes/account/send-code.ts +39 -39
  67. package/src/routes/account/verify-email.ts +40 -40
  68. package/src/routes/account/verify-sms.ts +40 -40
  69. package/src/routes/auth/index.ts +22 -22
  70. package/src/routes/auth/refresh.ts +48 -48
  71. package/src/routes/auth/session.ts +166 -166
  72. package/src/routes/index.ts +17 -17
  73. package/src/routes/session/index.ts +7 -7
  74. package/src/routes/session/refresh-viability.ts +17 -17
  75. package/src/server/auth.ts +373 -373
  76. package/src/server/decode-session.ts +202 -202
  77. package/src/services/signalrActivityService.ts +258 -258
  78. package/src/theme/ThemeProvider.tsx +39 -39
  79. package/src/theme/default.ts +33 -33
  80. package/src/theme/index.ts +31 -31
  81. package/src/theme/types.ts +69 -69
  82. package/src/theme/useTheme.ts +57 -57
  83. package/src/theme/utils.ts +40 -40
  84. package/src/types/api.ts +12 -12
  85. package/src/types/auth.d.ts +23 -23
  86. package/src/types/auth.ts +22 -22
  87. package/src/types/logging.ts +11 -11
  88. package/src/types/recovery.ts +54 -54
  89. package/src/utils/api.ts +353 -353
  90. package/src/utils/circuitBreaker.ts +40 -40
  91. package/src/utils/error-message.ts +108 -108
  92. 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
+