@payez/next-mvp 4.1.11 → 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 (178) 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 +256 -42
  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/session-store.js +28 -21
  38. package/dist/lib/startup-init.js +19 -19
  39. package/dist/lib/token-lifecycle.js +40 -4
  40. package/dist/models/SessionModel.d.ts +17 -0
  41. package/dist/pages/login/page.d.ts +10 -1
  42. package/dist/pages/login/page.js +69 -80
  43. package/dist/pages/verify-code/page.d.ts +10 -1
  44. package/dist/pages/verify-code/page.js +72 -4
  45. package/dist/routes/auth/passkey-signin.d.ts +13 -0
  46. package/dist/routes/auth/passkey-signin.js +18 -0
  47. package/dist/routes/auth/viability.d.ts +2 -0
  48. package/dist/routes/auth/viability.js +88 -0
  49. package/dist/routes/mfa/backup-code-verify.d.ts +1 -0
  50. package/dist/routes/mfa/backup-code-verify.js +5 -0
  51. package/dist/routes/mfa/backup-codes.d.ts +10 -0
  52. package/dist/routes/mfa/backup-codes.js +14 -0
  53. package/dist/routes/mfa/methods.d.ts +21 -0
  54. package/dist/routes/mfa/methods.js +10 -0
  55. package/dist/routes/mfa/totp-confirm.d.ts +10 -0
  56. package/dist/routes/mfa/totp-confirm.js +14 -0
  57. package/dist/routes/mfa/totp-enroll.d.ts +10 -0
  58. package/dist/routes/mfa/totp-enroll.js +14 -0
  59. package/dist/routes/mfa/totp-verify.d.ts +14 -0
  60. package/dist/routes/mfa/totp-verify.js +18 -0
  61. package/dist/routes/passkeys/list.d.ts +10 -0
  62. package/dist/routes/passkeys/list.js +14 -0
  63. package/dist/routes/passkeys/manage.d.ts +18 -0
  64. package/dist/routes/passkeys/manage.js +13 -0
  65. package/dist/routes/passkeys/register-options.d.ts +10 -0
  66. package/dist/routes/passkeys/register-options.js +14 -0
  67. package/dist/routes/passkeys/register-verify.d.ts +10 -0
  68. package/dist/routes/passkeys/register-verify.js +14 -0
  69. package/dist/server/auth.d.ts +2 -2
  70. package/dist/server/decode-session.js +37 -3
  71. package/package.json +958 -893
  72. package/scripts/check-internal-url-usage.sh +73 -73
  73. package/src/api/index.ts +17 -17
  74. package/src/api-handlers/account/masked-info.ts +45 -45
  75. package/src/api-handlers/account/profile.ts +99 -80
  76. package/src/api-handlers/account/recovery/initiate.ts +23 -23
  77. package/src/api-handlers/account/recovery/send-code.ts +73 -25
  78. package/src/api-handlers/account/recovery/verify-code.ts +73 -25
  79. package/src/api-handlers/account/reset-password.ts +23 -23
  80. package/src/api-handlers/account/send-code.ts +76 -76
  81. package/src/api-handlers/account/validate-password.ts +118 -118
  82. package/src/api-handlers/account/verify-email.ts +15 -1
  83. package/src/api-handlers/account/verify-sms.ts +15 -1
  84. package/src/api-handlers/admin/stats.ts +249 -249
  85. package/src/api-handlers/anon/preferences.ts +123 -123
  86. package/src/api-handlers/auth/jwks.ts +20 -20
  87. package/src/api-handlers/auth/login.ts +240 -240
  88. package/src/api-handlers/auth/passkey-signin.ts +98 -0
  89. package/src/api-handlers/auth/validate.ts +43 -43
  90. package/src/api-handlers/mfa/backup-code-verify.ts +175 -0
  91. package/src/api-handlers/mfa/backup-codes.ts +41 -0
  92. package/src/api-handlers/mfa/methods.ts +46 -0
  93. package/src/api-handlers/mfa/totp-confirm.ts +42 -0
  94. package/src/api-handlers/mfa/totp-enroll.ts +42 -0
  95. package/src/api-handlers/mfa/totp-verify.ts +156 -0
  96. package/src/api-handlers/passkeys/list.ts +31 -0
  97. package/src/api-handlers/passkeys/manage.ts +54 -0
  98. package/src/api-handlers/passkeys/register-options.ts +42 -0
  99. package/src/api-handlers/passkeys/register-verify.ts +41 -0
  100. package/src/api-handlers/session/viability.ts +161 -142
  101. package/src/auth/better-auth.ts +247 -6
  102. package/src/auth/unauthenticated-routes.ts +2 -2
  103. package/src/auth/utils/idp-client.ts +13 -95
  104. package/src/client/better-auth-client.ts +70 -70
  105. package/src/client/fetchWithSession.ts +21 -21
  106. package/src/client/index.ts +13 -13
  107. package/src/client/useAnonSession.ts +131 -131
  108. package/src/components/admin/VibeAdminContext.tsx +87 -87
  109. package/src/config/logging-config.ts +82 -82
  110. package/src/config/unauthenticated-routes.ts +19 -19
  111. package/src/edge/internal-api-url.ts +65 -65
  112. package/src/edge/middleware.ts +42 -42
  113. package/src/hooks/useProfile.ts +75 -75
  114. package/src/lib/anon-session.ts +213 -213
  115. package/src/lib/auth-secret.ts +137 -137
  116. package/src/lib/demo-mode.ts +17 -17
  117. package/src/lib/idp-client-config.ts +559 -559
  118. package/src/lib/idp-fetch.ts +126 -126
  119. package/src/lib/internal-api.ts +171 -171
  120. package/src/lib/jwt-decode-client.ts +45 -45
  121. package/src/lib/rate-limit-service.ts +9 -9
  122. package/src/lib/redis.ts +26 -26
  123. package/src/lib/refresh-token-validator.ts +64 -64
  124. package/src/lib/secret-validation.ts +8 -8
  125. package/src/lib/session-store.ts +702 -695
  126. package/src/lib/session.ts +34 -34
  127. package/src/lib/startup-init.ts +251 -251
  128. package/src/lib/token-expiry.ts +40 -40
  129. package/src/lib/token-lifecycle.ts +533 -497
  130. package/src/lib/types/api-responses.ts +336 -336
  131. package/src/middleware/auth-decision.ts +43 -43
  132. package/src/models/DecodedAccessToken.ts +16 -16
  133. package/src/models/SessionModel.ts +282 -264
  134. package/src/pages/admin-roles/index.ts +9 -9
  135. package/src/pages/login/page.tsx +123 -228
  136. package/src/pages/security/EnhancedSecurityPage.tsx +9 -9
  137. package/src/pages/verify-code/page.tsx +71 -5
  138. package/src/routes/account/index.ts +31 -31
  139. package/src/routes/account/masked-info.ts +36 -36
  140. package/src/routes/account/send-code.ts +39 -39
  141. package/src/routes/account/verify-email.ts +40 -40
  142. package/src/routes/account/verify-sms.ts +40 -40
  143. package/src/routes/auth/index.ts +22 -22
  144. package/src/routes/auth/passkey-signin.ts +13 -0
  145. package/src/routes/auth/refresh.ts +48 -48
  146. package/src/routes/auth/session.ts +166 -166
  147. package/src/routes/auth/viability.ts +89 -0
  148. package/src/routes/index.ts +17 -17
  149. package/src/routes/mfa/backup-code-verify.ts +1 -0
  150. package/src/routes/mfa/backup-codes.ts +10 -0
  151. package/src/routes/mfa/methods.ts +22 -0
  152. package/src/routes/mfa/totp-confirm.ts +10 -0
  153. package/src/routes/mfa/totp-enroll.ts +10 -0
  154. package/src/routes/mfa/totp-verify.ts +14 -0
  155. package/src/routes/passkeys/list.ts +10 -0
  156. package/src/routes/passkeys/manage.ts +23 -0
  157. package/src/routes/passkeys/register-options.ts +10 -0
  158. package/src/routes/passkeys/register-verify.ts +10 -0
  159. package/src/routes/session/index.ts +7 -7
  160. package/src/routes/session/refresh-viability.ts +17 -17
  161. package/src/server/auth.ts +373 -373
  162. package/src/server/decode-session.ts +235 -202
  163. package/src/services/signalrActivityService.ts +258 -258
  164. package/src/theme/ThemeProvider.tsx +39 -39
  165. package/src/theme/default.ts +33 -33
  166. package/src/theme/index.ts +31 -31
  167. package/src/theme/types.ts +69 -69
  168. package/src/theme/useTheme.ts +57 -57
  169. package/src/theme/utils.ts +40 -40
  170. package/src/types/api.ts +12 -12
  171. package/src/types/auth.d.ts +23 -23
  172. package/src/types/auth.ts +22 -22
  173. package/src/types/logging.ts +11 -11
  174. package/src/types/recovery.ts +54 -54
  175. package/src/utils/api.ts +353 -353
  176. package/src/utils/circuitBreaker.ts +40 -40
  177. package/src/utils/error-message.ts +108 -108
  178. package/src/utils/layout/reservedSpace.ts +124 -124
@@ -1,249 +1,249 @@
1
- /**
2
- * Admin Stats API Handler
3
- *
4
- * Aggregates dashboard statistics from users, Redis sessions, and audit logs.
5
- * Uses service account HMAC auth for Vibe API requests.
6
- *
7
- * @version 1.0
8
- * @requires Admin role (vibe_app_admin or payez_admin)
9
- */
10
-
11
- import { NextRequest, NextResponse } from 'next/server';
12
- import { getSession } from '../../server/auth';
13
- import { getStartupIDPConfig } from '../../lib/startup-init';
14
- import { getRedis } from '../../lib/redis';
15
- import { ADMIN_ROLES } from '../../lib/roles';
16
-
17
- interface VibeRequestOptions {
18
- method: 'GET' | 'POST' | 'PUT' | 'DELETE';
19
- body?: unknown;
20
- }
21
-
22
- async function checkAdminRole(request: NextRequest): Promise<{ isAdmin: boolean; error?: NextResponse }> {
23
- const session = await getSession(request) as any;
24
-
25
- if (!session?.user) {
26
- return {
27
- isAdmin: false,
28
- error: NextResponse.json({ success: false, error: 'Please sign in' }, { status: 401 }),
29
- };
30
- }
31
-
32
- const userRoles = (session.user?.roles as string[]) || [];
33
- const hasAdminRole = ADMIN_ROLES.some(role => userRoles.includes(role));
34
-
35
- if (!hasAdminRole) {
36
- return {
37
- isAdmin: false,
38
- error: NextResponse.json({ success: false, error: 'Admin access required' }, { status: 403 }),
39
- };
40
- }
41
-
42
- return { isAdmin: true };
43
- }
44
-
45
- async function vibeServiceRequest<T = unknown>(
46
- endpoint: string,
47
- options: VibeRequestOptions
48
- ): Promise<{ ok: boolean; status: number; data: T | null; error?: string }> {
49
- const idpUrl = process.env.NEXT_PUBLIC_IDP_URL || process.env.IDP_URL;
50
- const clientId = process.env.VIBE_CLIENT_ID;
51
- const signingKey = process.env.VIBE_HMAC_KEY;
52
-
53
- if (!idpUrl || !clientId || !signingKey) {
54
- return { ok: false, status: 500, data: null, error: 'Vibe not configured' };
55
- }
56
-
57
- const timestamp = Math.floor(Date.now() / 1000);
58
- const stringToSign = `${timestamp}|${options.method}|${endpoint}`;
59
-
60
- const crypto = await import('crypto');
61
- const signature = crypto
62
- .createHmac('sha256', Buffer.from(signingKey, 'base64'))
63
- .update(stringToSign)
64
- .digest('base64');
65
-
66
- const proxyUrl = `${idpUrl}/api/vibe/proxy`;
67
-
68
- const idpConfig = getStartupIDPConfig();
69
- const idpClientId = idpConfig?.clientSlug || idpConfig?.clientId;
70
-
71
- try {
72
- const res = await fetch(proxyUrl, {
73
- method: 'POST',
74
- headers: {
75
- 'Content-Type': 'application/json',
76
- 'X-Vibe-Client-Id': clientId,
77
- 'X-Vibe-Timestamp': String(timestamp),
78
- 'X-Vibe-Signature': signature,
79
- ...(idpClientId && { 'X-Client-Id': idpClientId }),
80
- },
81
- body: JSON.stringify({
82
- endpoint,
83
- method: options.method,
84
- data: options.body ?? null,
85
- }),
86
- cache: 'no-store',
87
- });
88
-
89
- if (res.status === 204) return { ok: true, status: 204, data: null };
90
- if (!res.ok) {
91
- const errorText = await res.text();
92
- return { ok: false, status: res.status, data: null, error: errorText };
93
- }
94
-
95
- const body = await res.json();
96
- return { ok: true, status: res.status, data: body };
97
- } catch (error) {
98
- return { ok: false, status: 0, data: null, error: String(error) };
99
- }
100
- }
101
-
102
- export interface AdminStatsHandlerConfig {
103
- appSlug?: string;
104
- }
105
-
106
- /**
107
- * GET /api/admin/stats - Dashboard statistics
108
- * Aggregates users + tier breakdown, active Redis sessions, and recent audit activity.
109
- */
110
- export function createStatsHandler(config: AdminStatsHandlerConfig) {
111
- const getSessionPrefix = () => {
112
- const appSlug = config.appSlug || process.env.APP_SLUG || process.env.CLIENT_ID || 'app';
113
- return `${appSlug}:sess:`;
114
- };
115
-
116
- return {
117
- async GET(_request: NextRequest) {
118
- const adminCheck = await checkAdminRole(_request);
119
- if (adminCheck.error) return adminCheck.error;
120
-
121
- try {
122
- // Fetch from 4 sources in parallel
123
- const [usersResult, tierDistributionResult, sessionCount, auditResult] = await Promise.allSettled([
124
- // 1. Users count via HMAC proxy (Vibe collection query)
125
- vibeServiceRequest<any>('/v1/collections/vibe_app/tables/users/query', {
126
- method: 'POST',
127
- body: { page: 1, pageSize: 500, orderBy: 'created_at', orderDirection: 'desc' },
128
- }),
129
-
130
- // 2. Tier distribution from analytics endpoint (uses purchases table)
131
- vibeServiceRequest<any>('/v1/analytics/tier-distribution?includeTrend=false', { method: 'GET' }),
132
-
133
- // 3. Active sessions from Redis
134
- (async () => {
135
- const redis = getRedis();
136
- const sessionPrefix = getSessionPrefix();
137
- const sessionKeys: string[] = [];
138
- let cursor = '0';
139
- do {
140
- const [newCursor, keys] = await redis.scan(cursor, 'MATCH', `${sessionPrefix}*`, 'COUNT', 100);
141
- cursor = newCursor;
142
- sessionKeys.push(...keys.filter((k: string) => !k.includes(':ver:')));
143
- } while (cursor !== '0');
144
- return sessionKeys.length;
145
- })(),
146
-
147
- // 4. Recent audit activity via HMAC proxy
148
- vibeServiceRequest<any>('/v1/audit?pageSize=10&sortDir=desc', { method: 'GET' }),
149
- ]);
150
-
151
- // Parse users — deduplicate by user_id
152
- let totalUsers = 0;
153
- if (usersResult.status === 'fulfilled' && usersResult.value.ok && usersResult.value.data) {
154
- const data = usersResult.value.data;
155
- const rawUsers = data.data || data.documents || data.users || [];
156
-
157
- // Deduplicate by user_id (keeps latest document_id)
158
- const userMap = new Map();
159
- for (const u of rawUsers) {
160
- const uid = u.user_id || u.id || u.document_id;
161
- const existing = userMap.get(uid);
162
- if (!existing || (u.document_id || '') > (existing.document_id || '')) {
163
- userMap.set(uid, u);
164
- }
165
- }
166
- totalUsers = userMap.size;
167
- }
168
-
169
- // Parse tier distribution from analytics endpoint (uses purchases table)
170
- let tierBreakdown: Record<string, number> = {};
171
- if (tierDistributionResult.status === 'fulfilled' && tierDistributionResult.value.ok && tierDistributionResult.value.data) {
172
- const data = tierDistributionResult.value.data;
173
- // Handle response shape: { distribution: [{ tierKey, userCount }, ...] }
174
- const distribution = data.distribution || data.data || data.tiers || [];
175
- if (Array.isArray(distribution)) {
176
- for (const item of distribution) {
177
- const tierKey = item.tierKey || item.tier || item.name || 'free';
178
- const count = item.userCount || item.count || item.users || 0;
179
- tierBreakdown[tierKey] = (tierBreakdown[tierKey] || 0) + count;
180
- }
181
- }
182
- }
183
- // Fallback: if no tier data from analytics, show all as free
184
- if (Object.keys(tierBreakdown).length === 0) {
185
- tierBreakdown = { free: totalUsers };
186
- }
187
-
188
- // Parse active sessions count
189
- let activeSessions = 0;
190
- if (sessionCount.status === 'fulfilled') {
191
- activeSessions = sessionCount.value;
192
- }
193
-
194
- // Parse audit events for recent activity
195
- let recentActivity: any[] = [];
196
- if (auditResult.status === 'fulfilled' && auditResult.value.ok && auditResult.value.data) {
197
- const data = auditResult.value.data;
198
-
199
- // Handle multiple possible response shapes
200
- let events: any[] = [];
201
- if (Array.isArray(data)) {
202
- events = data;
203
- } else if (Array.isArray(data.data)) {
204
- events = data.data;
205
- } else if (Array.isArray(data.entries)) {
206
- events = data.entries;
207
- } else if (Array.isArray(data.items)) {
208
- events = data.items;
209
- } else if (Array.isArray(data.documents)) {
210
- events = data.documents;
211
- } else if (data.success && Array.isArray(data.results)) {
212
- events = data.results;
213
- }
214
-
215
- recentActivity = events.slice(0, 5).map((e: any) => ({
216
- id: e.audit_log_id || e.id || e.document_id,
217
- type: e.category || e.type || 'admin',
218
- action: e.action || e.event || e.message || 'Unknown action',
219
- actor: e.admin_email || e.actor || e.user || e.actor_email || 'System',
220
- target: e.target_type ? `${e.target_type}:${e.target_id}` : (e.target || e.target_user),
221
- details: e.description || e.details,
222
- timestamp: e.created_at || e.timestamp || e.date,
223
- success: e.is_success ?? e.success ?? true,
224
- }));
225
- }
226
-
227
- // Calculate tier percentages
228
- const tiers = Object.entries(tierBreakdown).map(([name, count]) => ({
229
- name,
230
- count: count as number,
231
- pct: totalUsers > 0 ? Math.round(((count as number) / totalUsers) * 100) : 0,
232
- }));
233
-
234
- return NextResponse.json({
235
- totalUsers,
236
- activeSessions,
237
- tiers,
238
- recentActivity,
239
- });
240
- } catch (error: any) {
241
- console.error('[admin/stats] Error:', error);
242
- return NextResponse.json(
243
- { error: error.message || 'Internal error' },
244
- { status: 500 }
245
- );
246
- }
247
- },
248
- };
249
- }
1
+ /**
2
+ * Admin Stats API Handler
3
+ *
4
+ * Aggregates dashboard statistics from users, Redis sessions, and audit logs.
5
+ * Uses service account HMAC auth for Vibe API requests.
6
+ *
7
+ * @version 1.0
8
+ * @requires Admin role (vibe_app_admin or payez_admin)
9
+ */
10
+
11
+ import { NextRequest, NextResponse } from 'next/server';
12
+ import { getSession } from '../../server/auth';
13
+ import { getStartupIDPConfig } from '../../lib/startup-init';
14
+ import { getRedis } from '../../lib/redis';
15
+ import { ADMIN_ROLES } from '../../lib/roles';
16
+
17
+ interface VibeRequestOptions {
18
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
19
+ body?: unknown;
20
+ }
21
+
22
+ async function checkAdminRole(request: NextRequest): Promise<{ isAdmin: boolean; error?: NextResponse }> {
23
+ const session = await getSession(request) as any;
24
+
25
+ if (!session?.user) {
26
+ return {
27
+ isAdmin: false,
28
+ error: NextResponse.json({ success: false, error: 'Please sign in' }, { status: 401 }),
29
+ };
30
+ }
31
+
32
+ const userRoles = (session.user?.roles as string[]) || [];
33
+ const hasAdminRole = ADMIN_ROLES.some(role => userRoles.includes(role));
34
+
35
+ if (!hasAdminRole) {
36
+ return {
37
+ isAdmin: false,
38
+ error: NextResponse.json({ success: false, error: 'Admin access required' }, { status: 403 }),
39
+ };
40
+ }
41
+
42
+ return { isAdmin: true };
43
+ }
44
+
45
+ async function vibeServiceRequest<T = unknown>(
46
+ endpoint: string,
47
+ options: VibeRequestOptions
48
+ ): Promise<{ ok: boolean; status: number; data: T | null; error?: string }> {
49
+ const idpUrl = process.env.NEXT_PUBLIC_IDP_URL || process.env.IDP_URL;
50
+ const clientId = process.env.VIBE_CLIENT_ID;
51
+ const signingKey = process.env.VIBE_HMAC_KEY;
52
+
53
+ if (!idpUrl || !clientId || !signingKey) {
54
+ return { ok: false, status: 500, data: null, error: 'Vibe not configured' };
55
+ }
56
+
57
+ const timestamp = Math.floor(Date.now() / 1000);
58
+ const stringToSign = `${timestamp}|${options.method}|${endpoint}`;
59
+
60
+ const crypto = await import('crypto');
61
+ const signature = crypto
62
+ .createHmac('sha256', Buffer.from(signingKey, 'base64'))
63
+ .update(stringToSign)
64
+ .digest('base64');
65
+
66
+ const proxyUrl = `${idpUrl}/api/vibe/proxy`;
67
+
68
+ const idpConfig = getStartupIDPConfig();
69
+ const idpClientId = idpConfig?.clientSlug || idpConfig?.clientId;
70
+
71
+ try {
72
+ const res = await fetch(proxyUrl, {
73
+ method: 'POST',
74
+ headers: {
75
+ 'Content-Type': 'application/json',
76
+ 'X-Vibe-Client-Id': clientId,
77
+ 'X-Vibe-Timestamp': String(timestamp),
78
+ 'X-Vibe-Signature': signature,
79
+ ...(idpClientId && { 'X-Client-Id': idpClientId }),
80
+ },
81
+ body: JSON.stringify({
82
+ endpoint,
83
+ method: options.method,
84
+ data: options.body ?? null,
85
+ }),
86
+ cache: 'no-store',
87
+ });
88
+
89
+ if (res.status === 204) return { ok: true, status: 204, data: null };
90
+ if (!res.ok) {
91
+ const errorText = await res.text();
92
+ return { ok: false, status: res.status, data: null, error: errorText };
93
+ }
94
+
95
+ const body = await res.json();
96
+ return { ok: true, status: res.status, data: body };
97
+ } catch (error) {
98
+ return { ok: false, status: 0, data: null, error: String(error) };
99
+ }
100
+ }
101
+
102
+ export interface AdminStatsHandlerConfig {
103
+ appSlug?: string;
104
+ }
105
+
106
+ /**
107
+ * GET /api/admin/stats - Dashboard statistics
108
+ * Aggregates users + tier breakdown, active Redis sessions, and recent audit activity.
109
+ */
110
+ export function createStatsHandler(config: AdminStatsHandlerConfig) {
111
+ const getSessionPrefix = () => {
112
+ const appSlug = config.appSlug || process.env.APP_SLUG || process.env.CLIENT_ID || 'app';
113
+ return `${appSlug}:sess:`;
114
+ };
115
+
116
+ return {
117
+ async GET(_request: NextRequest) {
118
+ const adminCheck = await checkAdminRole(_request);
119
+ if (adminCheck.error) return adminCheck.error;
120
+
121
+ try {
122
+ // Fetch from 4 sources in parallel
123
+ const [usersResult, tierDistributionResult, sessionCount, auditResult] = await Promise.allSettled([
124
+ // 1. Users count via HMAC proxy (Vibe collection query)
125
+ vibeServiceRequest<any>('/v1/collections/vibe_app/tables/users/query', {
126
+ method: 'POST',
127
+ body: { page: 1, pageSize: 500, orderBy: 'created_at', orderDirection: 'desc' },
128
+ }),
129
+
130
+ // 2. Tier distribution from analytics endpoint (uses purchases table)
131
+ vibeServiceRequest<any>('/v1/analytics/tier-distribution?includeTrend=false', { method: 'GET' }),
132
+
133
+ // 3. Active sessions from Redis
134
+ (async () => {
135
+ const redis = getRedis();
136
+ const sessionPrefix = getSessionPrefix();
137
+ const sessionKeys: string[] = [];
138
+ let cursor = '0';
139
+ do {
140
+ const [newCursor, keys] = await redis.scan(cursor, 'MATCH', `${sessionPrefix}*`, 'COUNT', 100);
141
+ cursor = newCursor;
142
+ sessionKeys.push(...keys.filter((k: string) => !k.includes(':ver:')));
143
+ } while (cursor !== '0');
144
+ return sessionKeys.length;
145
+ })(),
146
+
147
+ // 4. Recent audit activity via HMAC proxy
148
+ vibeServiceRequest<any>('/v1/audit?pageSize=10&sortDir=desc', { method: 'GET' }),
149
+ ]);
150
+
151
+ // Parse users — deduplicate by user_id
152
+ let totalUsers = 0;
153
+ if (usersResult.status === 'fulfilled' && usersResult.value.ok && usersResult.value.data) {
154
+ const data = usersResult.value.data;
155
+ const rawUsers = data.data || data.documents || data.users || [];
156
+
157
+ // Deduplicate by user_id (keeps latest document_id)
158
+ const userMap = new Map();
159
+ for (const u of rawUsers) {
160
+ const uid = u.user_id || u.id || u.document_id;
161
+ const existing = userMap.get(uid);
162
+ if (!existing || (u.document_id || '') > (existing.document_id || '')) {
163
+ userMap.set(uid, u);
164
+ }
165
+ }
166
+ totalUsers = userMap.size;
167
+ }
168
+
169
+ // Parse tier distribution from analytics endpoint (uses purchases table)
170
+ let tierBreakdown: Record<string, number> = {};
171
+ if (tierDistributionResult.status === 'fulfilled' && tierDistributionResult.value.ok && tierDistributionResult.value.data) {
172
+ const data = tierDistributionResult.value.data;
173
+ // Handle response shape: { distribution: [{ tierKey, userCount }, ...] }
174
+ const distribution = data.distribution || data.data || data.tiers || [];
175
+ if (Array.isArray(distribution)) {
176
+ for (const item of distribution) {
177
+ const tierKey = item.tierKey || item.tier || item.name || 'free';
178
+ const count = item.userCount || item.count || item.users || 0;
179
+ tierBreakdown[tierKey] = (tierBreakdown[tierKey] || 0) + count;
180
+ }
181
+ }
182
+ }
183
+ // Fallback: if no tier data from analytics, show all as free
184
+ if (Object.keys(tierBreakdown).length === 0) {
185
+ tierBreakdown = { free: totalUsers };
186
+ }
187
+
188
+ // Parse active sessions count
189
+ let activeSessions = 0;
190
+ if (sessionCount.status === 'fulfilled') {
191
+ activeSessions = sessionCount.value;
192
+ }
193
+
194
+ // Parse audit events for recent activity
195
+ let recentActivity: any[] = [];
196
+ if (auditResult.status === 'fulfilled' && auditResult.value.ok && auditResult.value.data) {
197
+ const data = auditResult.value.data;
198
+
199
+ // Handle multiple possible response shapes
200
+ let events: any[] = [];
201
+ if (Array.isArray(data)) {
202
+ events = data;
203
+ } else if (Array.isArray(data.data)) {
204
+ events = data.data;
205
+ } else if (Array.isArray(data.entries)) {
206
+ events = data.entries;
207
+ } else if (Array.isArray(data.items)) {
208
+ events = data.items;
209
+ } else if (Array.isArray(data.documents)) {
210
+ events = data.documents;
211
+ } else if (data.success && Array.isArray(data.results)) {
212
+ events = data.results;
213
+ }
214
+
215
+ recentActivity = events.slice(0, 5).map((e: any) => ({
216
+ id: e.audit_log_id || e.id || e.document_id,
217
+ type: e.category || e.type || 'admin',
218
+ action: e.action || e.event || e.message || 'Unknown action',
219
+ actor: e.admin_email || e.actor || e.user || e.actor_email || 'System',
220
+ target: e.target_type ? `${e.target_type}:${e.target_id}` : (e.target || e.target_user),
221
+ details: e.description || e.details,
222
+ timestamp: e.created_at || e.timestamp || e.date,
223
+ success: e.is_success ?? e.success ?? true,
224
+ }));
225
+ }
226
+
227
+ // Calculate tier percentages
228
+ const tiers = Object.entries(tierBreakdown).map(([name, count]) => ({
229
+ name,
230
+ count: count as number,
231
+ pct: totalUsers > 0 ? Math.round(((count as number) / totalUsers) * 100) : 0,
232
+ }));
233
+
234
+ return NextResponse.json({
235
+ totalUsers,
236
+ activeSessions,
237
+ tiers,
238
+ recentActivity,
239
+ });
240
+ } catch (error: any) {
241
+ console.error('[admin/stats] Error:', error);
242
+ return NextResponse.json(
243
+ { error: error.message || 'Internal error' },
244
+ { status: 500 }
245
+ );
246
+ }
247
+ },
248
+ };
249
+ }