@payez/next-mvp 3.9.0 → 4.0.0

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 (149) hide show
  1. package/dist/api/auth-handler.d.ts +1 -2
  2. package/dist/api/auth-handler.js +9 -9
  3. package/dist/api-handlers/account/change-password.js +110 -112
  4. package/dist/api-handlers/admin/analytics.d.ts +19 -20
  5. package/dist/api-handlers/admin/analytics.js +378 -379
  6. package/dist/api-handlers/admin/audit.d.ts +19 -20
  7. package/dist/api-handlers/admin/audit.js +213 -214
  8. package/dist/api-handlers/admin/index.d.ts +21 -22
  9. package/dist/api-handlers/admin/index.js +42 -43
  10. package/dist/api-handlers/admin/redis-sessions.d.ts +35 -36
  11. package/dist/api-handlers/admin/redis-sessions.js +203 -204
  12. package/dist/api-handlers/admin/sessions.d.ts +20 -21
  13. package/dist/api-handlers/admin/sessions.js +283 -284
  14. package/dist/api-handlers/admin/site-logs.d.ts +45 -46
  15. package/dist/api-handlers/admin/site-logs.js +317 -318
  16. package/dist/api-handlers/admin/stats.d.ts +20 -21
  17. package/dist/api-handlers/admin/stats.js +239 -240
  18. package/dist/api-handlers/admin/users.d.ts +19 -20
  19. package/dist/api-handlers/admin/users.js +221 -222
  20. package/dist/api-handlers/admin/vibe-data.d.ts +79 -80
  21. package/dist/api-handlers/admin/vibe-data.js +267 -268
  22. package/dist/api-handlers/auth/refresh.js +633 -635
  23. package/dist/api-handlers/auth/signout.js +186 -187
  24. package/dist/api-handlers/auth/status.js +4 -7
  25. package/dist/api-handlers/auth/update-session.d.ts +1 -1
  26. package/dist/api-handlers/auth/update-session.js +12 -14
  27. package/dist/api-handlers/auth/verify-code.d.ts +43 -43
  28. package/dist/api-handlers/auth/verify-code.js +90 -94
  29. package/dist/api-handlers/session/viability.js +114 -146
  30. package/dist/api-handlers/test/force-expire.js +59 -65
  31. package/dist/auth/auth-decision.js +182 -182
  32. package/dist/auth/better-auth.d.ts +3 -6
  33. package/dist/auth/better-auth.js +3 -6
  34. package/dist/auth/route-config.js +2 -2
  35. package/dist/auth/utils/token-utils.d.ts +83 -84
  36. package/dist/auth/utils/token-utils.js +218 -219
  37. package/dist/client/AuthContext.js +115 -112
  38. package/dist/client/better-auth-client.d.ts +1020 -961
  39. package/dist/client/better-auth-client.js +54 -7
  40. package/dist/client/fetch-with-auth.js +2 -2
  41. package/dist/components/SessionSync.js +121 -119
  42. package/dist/components/account/MobileNavDrawer.js +64 -64
  43. package/dist/components/account/UserAvatarMenu.js +91 -88
  44. package/dist/components/admin/VibeAdminLayout.js +71 -69
  45. package/dist/hooks/useAuth.js +9 -7
  46. package/dist/hooks/useAuthSettings.js +93 -93
  47. package/dist/hooks/useAvailableProviders.d.ts +43 -45
  48. package/dist/hooks/useAvailableProviders.js +112 -108
  49. package/dist/hooks/useSessionExpiration.d.ts +2 -3
  50. package/dist/hooks/useSessionExpiration.js +2 -2
  51. package/dist/hooks/useViabilitySession.js +3 -2
  52. package/dist/index.js +4 -6
  53. package/dist/lib/app-slug.d.ts +95 -95
  54. package/dist/lib/app-slug.js +172 -172
  55. package/dist/lib/standardized-client-api.js +10 -5
  56. package/dist/lib/startup-init.js +21 -25
  57. package/dist/lib/test-aware-get-token.js +86 -81
  58. package/dist/lib/token-lifecycle.d.ts +78 -52
  59. package/dist/lib/token-lifecycle.js +360 -398
  60. package/dist/pages/admin-login/page.js +73 -83
  61. package/dist/pages/client-admin/ClientSiteAdminPage.js +179 -177
  62. package/dist/pages/login/page.js +202 -211
  63. package/dist/pages/showcase/ShowcasePage.js +142 -140
  64. package/dist/pages/test-env/EmergencyLogoutPage.js +99 -98
  65. package/dist/pages/test-env/JwtInspectPage.js +116 -114
  66. package/dist/pages/test-env/RefreshTokenPage.js +4 -2
  67. package/dist/pages/test-env/TestEnvPage.js +51 -49
  68. package/dist/pages/verify-code/page.js +412 -408
  69. package/dist/routes/auth/logout.d.ts +31 -31
  70. package/dist/routes/auth/logout.js +98 -113
  71. package/dist/routes/auth/nextauth.d.ts +14 -11
  72. package/dist/routes/auth/nextauth.js +25 -57
  73. package/dist/routes/auth/session.js +157 -179
  74. package/dist/routes/auth/viability.js +190 -201
  75. package/dist/server/auth.d.ts +50 -0
  76. package/dist/server/auth.js +62 -0
  77. package/dist/stores/authStore.js +19 -23
  78. package/dist/utils/logout.js +5 -5
  79. package/package.json +1 -3
  80. package/src/api/auth-handler.ts +550 -549
  81. package/src/api-handlers/account/change-password.ts +5 -8
  82. package/src/api-handlers/admin/analytics.ts +4 -6
  83. package/src/api-handlers/admin/audit.ts +5 -7
  84. package/src/api-handlers/admin/index.ts +1 -2
  85. package/src/api-handlers/admin/redis-sessions.ts +6 -8
  86. package/src/api-handlers/admin/sessions.ts +5 -7
  87. package/src/api-handlers/admin/site-logs.ts +8 -10
  88. package/src/api-handlers/admin/stats.ts +4 -6
  89. package/src/api-handlers/admin/users.ts +5 -7
  90. package/src/api-handlers/admin/vibe-data.ts +10 -12
  91. package/src/api-handlers/auth/refresh.ts +5 -7
  92. package/src/api-handlers/auth/signout.ts +5 -6
  93. package/src/api-handlers/auth/status.ts +4 -7
  94. package/src/api-handlers/auth/update-session.ts +123 -125
  95. package/src/api-handlers/auth/verify-code.ts +9 -13
  96. package/src/api-handlers/session/viability.ts +10 -47
  97. package/src/api-handlers/test/force-expire.ts +4 -11
  98. package/src/auth/auth-decision.ts +1 -1
  99. package/src/auth/better-auth.ts +138 -141
  100. package/src/auth/route-config.ts +219 -219
  101. package/src/auth/utils/token-utils.ts +0 -1
  102. package/src/client/AuthContext.tsx +6 -2
  103. package/src/client/better-auth-client.ts +54 -7
  104. package/src/client/fetch-with-auth.ts +47 -47
  105. package/src/components/SessionSync.tsx +6 -5
  106. package/src/components/account/MobileNavDrawer.tsx +3 -3
  107. package/src/components/account/UserAvatarMenu.tsx +6 -3
  108. package/src/components/admin/VibeAdminLayout.tsx +4 -2
  109. package/src/config/logger.ts +1 -1
  110. package/src/hooks/useAuth.ts +117 -115
  111. package/src/hooks/useAuthSettings.ts +2 -2
  112. package/src/hooks/useAvailableProviders.ts +9 -5
  113. package/src/hooks/useSessionExpiration.ts +101 -102
  114. package/src/hooks/useViabilitySession.ts +336 -335
  115. package/src/index.ts +60 -63
  116. package/src/lib/api-handler.ts +0 -1
  117. package/src/lib/app-slug.ts +6 -6
  118. package/src/lib/standardized-client-api.ts +901 -895
  119. package/src/lib/startup-init.ts +243 -247
  120. package/src/lib/test-aware-get-token.ts +22 -12
  121. package/src/lib/token-lifecycle.ts +12 -53
  122. package/src/pages/admin-login/page.tsx +9 -17
  123. package/src/pages/client-admin/ClientSiteAdminPage.tsx +4 -2
  124. package/src/pages/login/page.tsx +21 -28
  125. package/src/pages/showcase/ShowcasePage.tsx +4 -2
  126. package/src/pages/test-env/EmergencyLogoutPage.tsx +7 -6
  127. package/src/pages/test-env/JwtInspectPage.tsx +5 -3
  128. package/src/pages/test-env/RefreshTokenPage.tsx +157 -155
  129. package/src/pages/test-env/TestEnvPage.tsx +4 -2
  130. package/src/pages/verify-code/page.tsx +10 -6
  131. package/src/routes/auth/logout.ts +7 -25
  132. package/src/routes/auth/nextauth.ts +45 -71
  133. package/src/routes/auth/session.ts +25 -50
  134. package/src/routes/auth/viability.ts +7 -19
  135. package/src/server/auth.ts +60 -0
  136. package/src/stores/authStore.ts +1899 -1904
  137. package/src/utils/logout.ts +30 -30
  138. package/src/auth/auth-options.ts +0 -237
  139. package/src/auth/callbacks/index.ts +0 -7
  140. package/src/auth/callbacks/jwt.ts +0 -382
  141. package/src/auth/callbacks/session.ts +0 -243
  142. package/src/auth/callbacks/signin.ts +0 -56
  143. package/src/auth/events/index.ts +0 -5
  144. package/src/auth/events/signout.ts +0 -33
  145. package/src/auth/providers/credentials.ts +0 -256
  146. package/src/auth/providers/index.ts +0 -6
  147. package/src/auth/providers/oauth.ts +0 -114
  148. package/src/lib/nextauth-secret.ts +0 -121
  149. package/src/types/next-auth.d.ts +0 -15
@@ -1,379 +1,378 @@
1
- "use strict";
2
- /**
3
- * Admin Analytics API Handler
4
- *
5
- * Provides admin-level analytics data using service account credentials.
6
- * Supports: geo stats, login stats, revenue stats, feature usage.
7
- *
8
- * @version 1.0
9
- * @requires Admin role (vibe_app_admin or payez_admin)
10
- */
11
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
- if (k2 === undefined) k2 = k;
13
- var desc = Object.getOwnPropertyDescriptor(m, k);
14
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
- desc = { enumerable: true, get: function() { return m[k]; } };
16
- }
17
- Object.defineProperty(o, k2, desc);
18
- }) : (function(o, m, k, k2) {
19
- if (k2 === undefined) k2 = k;
20
- o[k2] = m[k];
21
- }));
22
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
- Object.defineProperty(o, "default", { enumerable: true, value: v });
24
- }) : function(o, v) {
25
- o["default"] = v;
26
- });
27
- var __importStar = (this && this.__importStar) || (function () {
28
- var ownKeys = function(o) {
29
- ownKeys = Object.getOwnPropertyNames || function (o) {
30
- var ar = [];
31
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
- return ar;
33
- };
34
- return ownKeys(o);
35
- };
36
- return function (mod) {
37
- if (mod && mod.__esModule) return mod;
38
- var result = {};
39
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
- __setModuleDefault(result, mod);
41
- return result;
42
- };
43
- })();
44
- Object.defineProperty(exports, "__esModule", { value: true });
45
- exports.createAnalyticsHandler = createAnalyticsHandler;
46
- const server_1 = require("next/server");
47
- const next_auth_1 = require("next-auth");
48
- const startup_init_1 = require("../../lib/startup-init");
49
- const roles_1 = require("../../lib/roles");
50
- async function checkAdminRole(getAuthOptions) {
51
- const authOptions = await getAuthOptions();
52
- const session = await (0, next_auth_1.getServerSession)(authOptions);
53
- if (!session?.user) {
54
- return {
55
- isAdmin: false,
56
- error: server_1.NextResponse.json({ success: false, error: 'Please sign in' }, { status: 401 }),
57
- };
58
- }
59
- const userRoles = session.user?.roles || [];
60
- const hasAdminRole = roles_1.ADMIN_ROLES.some(role => userRoles.includes(role));
61
- if (!hasAdminRole) {
62
- return {
63
- isAdmin: false,
64
- error: server_1.NextResponse.json({ success: false, error: 'Admin access required' }, { status: 403 }),
65
- };
66
- }
67
- return { isAdmin: true };
68
- }
69
- async function vibeServiceRequest(endpoint, options) {
70
- const idpUrl = process.env.NEXT_PUBLIC_IDP_URL || process.env.IDP_URL;
71
- const clientId = process.env.VIBE_CLIENT_ID;
72
- const signingKey = process.env.VIBE_HMAC_KEY;
73
- if (!idpUrl || !clientId || !signingKey) {
74
- return { ok: false, status: 500, data: null, error: 'Vibe not configured' };
75
- }
76
- const timestamp = Math.floor(Date.now() / 1000);
77
- const stringToSign = `${timestamp}|${options.method}|${endpoint}`;
78
- const crypto = await Promise.resolve().then(() => __importStar(require('crypto')));
79
- const signature = crypto
80
- .createHmac('sha256', Buffer.from(signingKey, 'base64'))
81
- .update(stringToSign)
82
- .digest('base64');
83
- const proxyUrl = `${idpUrl}/api/vibe/proxy`;
84
- // Get the client slug from startup config for multi-client admin support
85
- const idpConfig = (0, startup_init_1.getStartupIDPConfig)();
86
- const idpClientId = idpConfig?.clientSlug || idpConfig?.clientId;
87
- try {
88
- const res = await fetch(proxyUrl, {
89
- method: 'POST',
90
- headers: {
91
- 'Content-Type': 'application/json',
92
- 'X-Vibe-Client-Id': clientId,
93
- 'X-Vibe-Timestamp': String(timestamp),
94
- 'X-Vibe-Signature': signature,
95
- ...(idpClientId && { 'X-Client-Id': idpClientId }),
96
- },
97
- body: JSON.stringify({
98
- endpoint,
99
- method: options.method,
100
- data: options.body ?? null,
101
- }),
102
- cache: 'no-store',
103
- });
104
- if (res.status === 204)
105
- return { ok: true, status: 204, data: null };
106
- if (!res.ok) {
107
- const errorText = await res.text();
108
- return { ok: false, status: res.status, data: null, error: errorText };
109
- }
110
- const body = await res.json();
111
- return { ok: true, status: res.status, data: body };
112
- }
113
- catch (error) {
114
- return { ok: false, status: 0, data: null, error: String(error) };
115
- }
116
- }
117
- function getCountryFlag(countryCode) {
118
- if (!countryCode || countryCode.length !== 2)
119
- return '';
120
- const codePoints = countryCode
121
- .toUpperCase()
122
- .split('')
123
- .map(char => 127397 + char.charCodeAt(0));
124
- return String.fromCodePoint(...codePoints);
125
- }
126
- /**
127
- * POST /api/admin/analytics
128
- * Body: { type: 'geo' | 'logins' | 'revenue' | 'features', period?: string }
129
- */
130
- function createAnalyticsHandler(config) {
131
- return {
132
- async POST(request) {
133
- const adminCheck = await checkAdminRole(config.getAuthOptions);
134
- if (adminCheck.error)
135
- return adminCheck.error;
136
- const body = await request.json();
137
- const { type, period = '7d' } = body;
138
- const now = new Date();
139
- let startDate;
140
- switch (period) {
141
- case '24h':
142
- startDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);
143
- break;
144
- case '7d':
145
- startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
146
- break;
147
- case '30d':
148
- startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
149
- break;
150
- case '90d':
151
- startDate = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
152
- break;
153
- default:
154
- startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
155
- }
156
- if (type === 'geo') {
157
- return await getGeoAnalytics(startDate);
158
- }
159
- if (type === 'logins') {
160
- return await getLoginAnalytics(startDate);
161
- }
162
- if (type === 'revenue') {
163
- return await getRevenueAnalytics(startDate);
164
- }
165
- if (type === 'features') {
166
- return await getFeatureUsageAnalytics(startDate);
167
- }
168
- if (type === 'summary') {
169
- return await getSummaryAnalytics(startDate);
170
- }
171
- return server_1.NextResponse.json({ error: 'Invalid analytics type' }, { status: 400 });
172
- },
173
- };
174
- }
175
- async function getGeoAnalytics(startDate) {
176
- const result = await vibeServiceRequest('/v1/collections/vibe_app/tables/login_sessions/query', { method: 'POST', body: { page: 1, pageSize: 5000 } });
177
- if (!result.ok) {
178
- return server_1.NextResponse.json({ error: result.error }, { status: result.status || 500 });
179
- }
180
- const sessions = result.data?.data || result.data?.documents || [];
181
- const recentSessions = sessions.filter((s) => new Date(s.created_at) >= startDate);
182
- const byCountry = {};
183
- const byCity = {};
184
- recentSessions.forEach((s) => {
185
- const country = s.country_code || s.country || 'Unknown';
186
- const city = s.city || 'Unknown';
187
- if (!byCountry[country]) {
188
- byCountry[country] = { count: 0, flag: getCountryFlag(country), cities: new Set() };
189
- }
190
- byCountry[country].count++;
191
- byCountry[country].cities.add(city);
192
- const cityKey = `${city}, ${country}`;
193
- byCity[cityKey] = (byCity[cityKey] || 0) + 1;
194
- });
195
- const countries = Object.entries(byCountry)
196
- .map(([code, data]) => ({
197
- code,
198
- flag: data.flag,
199
- count: data.count,
200
- cities: data.cities.size,
201
- }))
202
- .sort((a, b) => b.count - a.count);
203
- const cities = Object.entries(byCity)
204
- .map(([name, count]) => ({ name, count }))
205
- .sort((a, b) => b.count - a.count)
206
- .slice(0, 20);
207
- return server_1.NextResponse.json({
208
- geo: {
209
- totalSessions: recentSessions.length,
210
- uniqueCountries: countries.length,
211
- countries,
212
- topCities: cities,
213
- },
214
- });
215
- }
216
- async function getLoginAnalytics(startDate) {
217
- const result = await vibeServiceRequest('/v1/collections/vibe_app/tables/login_sessions/query', { method: 'POST', body: { page: 1, pageSize: 5000 } });
218
- if (!result.ok) {
219
- return server_1.NextResponse.json({ error: result.error }, { status: result.status || 500 });
220
- }
221
- const sessions = result.data?.data || result.data?.documents || [];
222
- const recentSessions = sessions.filter((s) => new Date(s.created_at) >= startDate);
223
- // Group by day
224
- const byDay = {};
225
- const byHour = {};
226
- const byDevice = {};
227
- const byBrowser = {};
228
- recentSessions.forEach((s) => {
229
- const date = new Date(s.created_at);
230
- const dayKey = date.toISOString().split('T')[0];
231
- byDay[dayKey] = (byDay[dayKey] || 0) + 1;
232
- const hour = date.getHours();
233
- byHour[hour] = (byHour[hour] || 0) + 1;
234
- const device = s.device_type || s.device || 'Unknown';
235
- byDevice[device] = (byDevice[device] || 0) + 1;
236
- const browser = s.browser || 'Unknown';
237
- byBrowser[browser] = (byBrowser[browser] || 0) + 1;
238
- });
239
- const dailyLogins = Object.entries(byDay)
240
- .map(([date, count]) => ({ date, count }))
241
- .sort((a, b) => a.date.localeCompare(b.date));
242
- const hourlyDistribution = Object.entries(byHour)
243
- .map(([hour, count]) => ({ hour: parseInt(hour), count }))
244
- .sort((a, b) => a.hour - b.hour);
245
- return server_1.NextResponse.json({
246
- logins: {
247
- total: recentSessions.length,
248
- uniqueUsers: new Set(recentSessions.map((s) => s.idp_user_id || s.user_id)).size,
249
- dailyLogins,
250
- hourlyDistribution,
251
- byDevice: Object.entries(byDevice).map(([device, count]) => ({ device, count })),
252
- byBrowser: Object.entries(byBrowser).map(([browser, count]) => ({ browser, count })),
253
- },
254
- });
255
- }
256
- async function getRevenueAnalytics(startDate) {
257
- // Try to get transactions table
258
- const result = await vibeServiceRequest('/v1/collections/vibe_app/tables/transactions/query', { method: 'POST', body: { page: 1, pageSize: 5000 } });
259
- if (!result.ok) {
260
- // Table might not exist, return empty stats
261
- return server_1.NextResponse.json({
262
- revenue: {
263
- total: 0,
264
- count: 0,
265
- byDay: [],
266
- byTier: {},
267
- message: 'No transactions table or data available',
268
- },
269
- });
270
- }
271
- const transactions = result.data?.data || result.data?.documents || [];
272
- const recentTxns = transactions.filter((t) => new Date(t.created_at) >= startDate);
273
- const byDay = {};
274
- const byTier = {};
275
- let totalAmount = 0;
276
- recentTxns.forEach((t) => {
277
- const date = new Date(t.created_at).toISOString().split('T')[0];
278
- const amount = parseFloat(t.amount) || 0;
279
- const tier = t.tier || t.product || 'unknown';
280
- if (!byDay[date])
281
- byDay[date] = { count: 0, amount: 0 };
282
- byDay[date].count++;
283
- byDay[date].amount += amount;
284
- if (!byTier[tier])
285
- byTier[tier] = { count: 0, amount: 0 };
286
- byTier[tier].count++;
287
- byTier[tier].amount += amount;
288
- totalAmount += amount;
289
- });
290
- const dailyRevenue = Object.entries(byDay)
291
- .map(([date, data]) => ({ date, ...data }))
292
- .sort((a, b) => a.date.localeCompare(b.date));
293
- return server_1.NextResponse.json({
294
- revenue: {
295
- total: totalAmount,
296
- count: recentTxns.length,
297
- byDay: dailyRevenue,
298
- byTier,
299
- },
300
- });
301
- }
302
- async function getFeatureUsageAnalytics(startDate) {
303
- // Try to get feature_usage or analytics table
304
- const result = await vibeServiceRequest('/v1/collections/vibe_app/tables/feature_usage/query', { method: 'POST', body: { page: 1, pageSize: 5000 } });
305
- if (!result.ok) {
306
- // Try analytics table as fallback
307
- const analyticsResult = await vibeServiceRequest('/v1/collections/vibe_app/tables/analytics/query', { method: 'POST', body: { page: 1, pageSize: 5000 } });
308
- if (!analyticsResult.ok) {
309
- return server_1.NextResponse.json({
310
- features: {
311
- total: 0,
312
- byFeature: {},
313
- message: 'No feature usage data available',
314
- },
315
- });
316
- }
317
- const events = analyticsResult.data?.data || analyticsResult.data?.documents || [];
318
- return processFeatureUsage(events, startDate);
319
- }
320
- const events = result.data?.data || result.data?.documents || [];
321
- return processFeatureUsage(events, startDate);
322
- }
323
- function processFeatureUsage(events, startDate) {
324
- const recentEvents = events.filter((e) => new Date(e.created_at) >= startDate);
325
- const byFeature = {};
326
- const byDay = {};
327
- recentEvents.forEach((e) => {
328
- const feature = e.feature || e.action || e.event_type || 'unknown';
329
- const userId = e.user_id || e.idp_user_id || 'anonymous';
330
- const date = new Date(e.created_at).toISOString().split('T')[0];
331
- if (!byFeature[feature]) {
332
- byFeature[feature] = { count: 0, uniqueUsers: new Set() };
333
- }
334
- byFeature[feature].count++;
335
- byFeature[feature].uniqueUsers.add(userId);
336
- byDay[date] = (byDay[date] || 0) + 1;
337
- });
338
- const features = Object.entries(byFeature)
339
- .map(([name, data]) => ({
340
- name,
341
- count: data.count,
342
- uniqueUsers: data.uniqueUsers.size,
343
- }))
344
- .sort((a, b) => b.count - a.count);
345
- const dailyUsage = Object.entries(byDay)
346
- .map(([date, count]) => ({ date, count }))
347
- .sort((a, b) => a.date.localeCompare(b.date));
348
- return server_1.NextResponse.json({
349
- features: {
350
- total: recentEvents.length,
351
- byFeature: features,
352
- dailyUsage,
353
- },
354
- });
355
- }
356
- async function getSummaryAnalytics(startDate) {
357
- // Get users
358
- const usersResult = await vibeServiceRequest('/v1/collections/vibe_app/tables/users/query', { method: 'POST', body: { page: 1, pageSize: 10000 } });
359
- // Get sessions
360
- const sessionsResult = await vibeServiceRequest('/v1/collections/vibe_app/tables/login_sessions/query', { method: 'POST', body: { page: 1, pageSize: 5000 } });
361
- const users = usersResult.ok ? (usersResult.data?.data || usersResult.data?.documents || []) : [];
362
- const sessions = sessionsResult.ok ? (sessionsResult.data?.data || sessionsResult.data?.documents || []) : [];
363
- const recentUsers = users.filter((u) => new Date(u.created_at) >= startDate);
364
- const recentSessions = sessions.filter((s) => new Date(s.created_at) >= startDate);
365
- const tierCounts = {};
366
- users.forEach((u) => {
367
- const tier = u.tier || 'free';
368
- tierCounts[tier] = (tierCounts[tier] || 0) + 1;
369
- });
370
- return server_1.NextResponse.json({
371
- summary: {
372
- totalUsers: users.length,
373
- newUsers: recentUsers.length,
374
- activeSessions: sessions.filter((s) => s.status === 'active').length,
375
- recentLogins: recentSessions.length,
376
- usersByTier: tierCounts,
377
- },
378
- });
379
- }
1
+ "use strict";
2
+ /**
3
+ * Admin Analytics API Handler
4
+ *
5
+ * Provides admin-level analytics data using service account credentials.
6
+ * Supports: geo stats, login stats, revenue stats, feature usage.
7
+ *
8
+ * @version 1.0
9
+ * @requires Admin role (vibe_app_admin or payez_admin)
10
+ */
11
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ var desc = Object.getOwnPropertyDescriptor(m, k);
14
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
+ desc = { enumerable: true, get: function() { return m[k]; } };
16
+ }
17
+ Object.defineProperty(o, k2, desc);
18
+ }) : (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ }));
22
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
24
+ }) : function(o, v) {
25
+ o["default"] = v;
26
+ });
27
+ var __importStar = (this && this.__importStar) || (function () {
28
+ var ownKeys = function(o) {
29
+ ownKeys = Object.getOwnPropertyNames || function (o) {
30
+ var ar = [];
31
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
+ return ar;
33
+ };
34
+ return ownKeys(o);
35
+ };
36
+ return function (mod) {
37
+ if (mod && mod.__esModule) return mod;
38
+ var result = {};
39
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
+ __setModuleDefault(result, mod);
41
+ return result;
42
+ };
43
+ })();
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.createAnalyticsHandler = createAnalyticsHandler;
46
+ const server_1 = require("next/server");
47
+ const auth_1 = require("../../server/auth");
48
+ const startup_init_1 = require("../../lib/startup-init");
49
+ const roles_1 = require("../../lib/roles");
50
+ async function checkAdminRole(request) {
51
+ const session = await (0, auth_1.getSession)(request);
52
+ if (!session?.user) {
53
+ return {
54
+ isAdmin: false,
55
+ error: server_1.NextResponse.json({ success: false, error: 'Please sign in' }, { status: 401 }),
56
+ };
57
+ }
58
+ const userRoles = session.user?.roles || [];
59
+ const hasAdminRole = roles_1.ADMIN_ROLES.some(role => userRoles.includes(role));
60
+ if (!hasAdminRole) {
61
+ return {
62
+ isAdmin: false,
63
+ error: server_1.NextResponse.json({ success: false, error: 'Admin access required' }, { status: 403 }),
64
+ };
65
+ }
66
+ return { isAdmin: true };
67
+ }
68
+ async function vibeServiceRequest(endpoint, options) {
69
+ const idpUrl = process.env.NEXT_PUBLIC_IDP_URL || process.env.IDP_URL;
70
+ const clientId = process.env.VIBE_CLIENT_ID;
71
+ const signingKey = process.env.VIBE_HMAC_KEY;
72
+ if (!idpUrl || !clientId || !signingKey) {
73
+ return { ok: false, status: 500, data: null, error: 'Vibe not configured' };
74
+ }
75
+ const timestamp = Math.floor(Date.now() / 1000);
76
+ const stringToSign = `${timestamp}|${options.method}|${endpoint}`;
77
+ const crypto = await Promise.resolve().then(() => __importStar(require('crypto')));
78
+ const signature = crypto
79
+ .createHmac('sha256', Buffer.from(signingKey, 'base64'))
80
+ .update(stringToSign)
81
+ .digest('base64');
82
+ const proxyUrl = `${idpUrl}/api/vibe/proxy`;
83
+ // Get the client slug from startup config for multi-client admin support
84
+ const idpConfig = (0, startup_init_1.getStartupIDPConfig)();
85
+ const idpClientId = idpConfig?.clientSlug || idpConfig?.clientId;
86
+ try {
87
+ const res = await fetch(proxyUrl, {
88
+ method: 'POST',
89
+ headers: {
90
+ 'Content-Type': 'application/json',
91
+ 'X-Vibe-Client-Id': clientId,
92
+ 'X-Vibe-Timestamp': String(timestamp),
93
+ 'X-Vibe-Signature': signature,
94
+ ...(idpClientId && { 'X-Client-Id': idpClientId }),
95
+ },
96
+ body: JSON.stringify({
97
+ endpoint,
98
+ method: options.method,
99
+ data: options.body ?? null,
100
+ }),
101
+ cache: 'no-store',
102
+ });
103
+ if (res.status === 204)
104
+ return { ok: true, status: 204, data: null };
105
+ if (!res.ok) {
106
+ const errorText = await res.text();
107
+ return { ok: false, status: res.status, data: null, error: errorText };
108
+ }
109
+ const body = await res.json();
110
+ return { ok: true, status: res.status, data: body };
111
+ }
112
+ catch (error) {
113
+ return { ok: false, status: 0, data: null, error: String(error) };
114
+ }
115
+ }
116
+ function getCountryFlag(countryCode) {
117
+ if (!countryCode || countryCode.length !== 2)
118
+ return '';
119
+ const codePoints = countryCode
120
+ .toUpperCase()
121
+ .split('')
122
+ .map(char => 127397 + char.charCodeAt(0));
123
+ return String.fromCodePoint(...codePoints);
124
+ }
125
+ /**
126
+ * POST /api/admin/analytics
127
+ * Body: { type: 'geo' | 'logins' | 'revenue' | 'features', period?: string }
128
+ */
129
+ function createAnalyticsHandler(config) {
130
+ return {
131
+ async POST(request) {
132
+ const adminCheck = await checkAdminRole(request);
133
+ if (adminCheck.error)
134
+ return adminCheck.error;
135
+ const body = await request.json();
136
+ const { type, period = '7d' } = body;
137
+ const now = new Date();
138
+ let startDate;
139
+ switch (period) {
140
+ case '24h':
141
+ startDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);
142
+ break;
143
+ case '7d':
144
+ startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
145
+ break;
146
+ case '30d':
147
+ startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
148
+ break;
149
+ case '90d':
150
+ startDate = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
151
+ break;
152
+ default:
153
+ startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
154
+ }
155
+ if (type === 'geo') {
156
+ return await getGeoAnalytics(startDate);
157
+ }
158
+ if (type === 'logins') {
159
+ return await getLoginAnalytics(startDate);
160
+ }
161
+ if (type === 'revenue') {
162
+ return await getRevenueAnalytics(startDate);
163
+ }
164
+ if (type === 'features') {
165
+ return await getFeatureUsageAnalytics(startDate);
166
+ }
167
+ if (type === 'summary') {
168
+ return await getSummaryAnalytics(startDate);
169
+ }
170
+ return server_1.NextResponse.json({ error: 'Invalid analytics type' }, { status: 400 });
171
+ },
172
+ };
173
+ }
174
+ async function getGeoAnalytics(startDate) {
175
+ const result = await vibeServiceRequest('/v1/collections/vibe_app/tables/login_sessions/query', { method: 'POST', body: { page: 1, pageSize: 5000 } });
176
+ if (!result.ok) {
177
+ return server_1.NextResponse.json({ error: result.error }, { status: result.status || 500 });
178
+ }
179
+ const sessions = result.data?.data || result.data?.documents || [];
180
+ const recentSessions = sessions.filter((s) => new Date(s.created_at) >= startDate);
181
+ const byCountry = {};
182
+ const byCity = {};
183
+ recentSessions.forEach((s) => {
184
+ const country = s.country_code || s.country || 'Unknown';
185
+ const city = s.city || 'Unknown';
186
+ if (!byCountry[country]) {
187
+ byCountry[country] = { count: 0, flag: getCountryFlag(country), cities: new Set() };
188
+ }
189
+ byCountry[country].count++;
190
+ byCountry[country].cities.add(city);
191
+ const cityKey = `${city}, ${country}`;
192
+ byCity[cityKey] = (byCity[cityKey] || 0) + 1;
193
+ });
194
+ const countries = Object.entries(byCountry)
195
+ .map(([code, data]) => ({
196
+ code,
197
+ flag: data.flag,
198
+ count: data.count,
199
+ cities: data.cities.size,
200
+ }))
201
+ .sort((a, b) => b.count - a.count);
202
+ const cities = Object.entries(byCity)
203
+ .map(([name, count]) => ({ name, count }))
204
+ .sort((a, b) => b.count - a.count)
205
+ .slice(0, 20);
206
+ return server_1.NextResponse.json({
207
+ geo: {
208
+ totalSessions: recentSessions.length,
209
+ uniqueCountries: countries.length,
210
+ countries,
211
+ topCities: cities,
212
+ },
213
+ });
214
+ }
215
+ async function getLoginAnalytics(startDate) {
216
+ const result = await vibeServiceRequest('/v1/collections/vibe_app/tables/login_sessions/query', { method: 'POST', body: { page: 1, pageSize: 5000 } });
217
+ if (!result.ok) {
218
+ return server_1.NextResponse.json({ error: result.error }, { status: result.status || 500 });
219
+ }
220
+ const sessions = result.data?.data || result.data?.documents || [];
221
+ const recentSessions = sessions.filter((s) => new Date(s.created_at) >= startDate);
222
+ // Group by day
223
+ const byDay = {};
224
+ const byHour = {};
225
+ const byDevice = {};
226
+ const byBrowser = {};
227
+ recentSessions.forEach((s) => {
228
+ const date = new Date(s.created_at);
229
+ const dayKey = date.toISOString().split('T')[0];
230
+ byDay[dayKey] = (byDay[dayKey] || 0) + 1;
231
+ const hour = date.getHours();
232
+ byHour[hour] = (byHour[hour] || 0) + 1;
233
+ const device = s.device_type || s.device || 'Unknown';
234
+ byDevice[device] = (byDevice[device] || 0) + 1;
235
+ const browser = s.browser || 'Unknown';
236
+ byBrowser[browser] = (byBrowser[browser] || 0) + 1;
237
+ });
238
+ const dailyLogins = Object.entries(byDay)
239
+ .map(([date, count]) => ({ date, count }))
240
+ .sort((a, b) => a.date.localeCompare(b.date));
241
+ const hourlyDistribution = Object.entries(byHour)
242
+ .map(([hour, count]) => ({ hour: parseInt(hour), count }))
243
+ .sort((a, b) => a.hour - b.hour);
244
+ return server_1.NextResponse.json({
245
+ logins: {
246
+ total: recentSessions.length,
247
+ uniqueUsers: new Set(recentSessions.map((s) => s.idp_user_id || s.user_id)).size,
248
+ dailyLogins,
249
+ hourlyDistribution,
250
+ byDevice: Object.entries(byDevice).map(([device, count]) => ({ device, count })),
251
+ byBrowser: Object.entries(byBrowser).map(([browser, count]) => ({ browser, count })),
252
+ },
253
+ });
254
+ }
255
+ async function getRevenueAnalytics(startDate) {
256
+ // Try to get transactions table
257
+ const result = await vibeServiceRequest('/v1/collections/vibe_app/tables/transactions/query', { method: 'POST', body: { page: 1, pageSize: 5000 } });
258
+ if (!result.ok) {
259
+ // Table might not exist, return empty stats
260
+ return server_1.NextResponse.json({
261
+ revenue: {
262
+ total: 0,
263
+ count: 0,
264
+ byDay: [],
265
+ byTier: {},
266
+ message: 'No transactions table or data available',
267
+ },
268
+ });
269
+ }
270
+ const transactions = result.data?.data || result.data?.documents || [];
271
+ const recentTxns = transactions.filter((t) => new Date(t.created_at) >= startDate);
272
+ const byDay = {};
273
+ const byTier = {};
274
+ let totalAmount = 0;
275
+ recentTxns.forEach((t) => {
276
+ const date = new Date(t.created_at).toISOString().split('T')[0];
277
+ const amount = parseFloat(t.amount) || 0;
278
+ const tier = t.tier || t.product || 'unknown';
279
+ if (!byDay[date])
280
+ byDay[date] = { count: 0, amount: 0 };
281
+ byDay[date].count++;
282
+ byDay[date].amount += amount;
283
+ if (!byTier[tier])
284
+ byTier[tier] = { count: 0, amount: 0 };
285
+ byTier[tier].count++;
286
+ byTier[tier].amount += amount;
287
+ totalAmount += amount;
288
+ });
289
+ const dailyRevenue = Object.entries(byDay)
290
+ .map(([date, data]) => ({ date, ...data }))
291
+ .sort((a, b) => a.date.localeCompare(b.date));
292
+ return server_1.NextResponse.json({
293
+ revenue: {
294
+ total: totalAmount,
295
+ count: recentTxns.length,
296
+ byDay: dailyRevenue,
297
+ byTier,
298
+ },
299
+ });
300
+ }
301
+ async function getFeatureUsageAnalytics(startDate) {
302
+ // Try to get feature_usage or analytics table
303
+ const result = await vibeServiceRequest('/v1/collections/vibe_app/tables/feature_usage/query', { method: 'POST', body: { page: 1, pageSize: 5000 } });
304
+ if (!result.ok) {
305
+ // Try analytics table as fallback
306
+ const analyticsResult = await vibeServiceRequest('/v1/collections/vibe_app/tables/analytics/query', { method: 'POST', body: { page: 1, pageSize: 5000 } });
307
+ if (!analyticsResult.ok) {
308
+ return server_1.NextResponse.json({
309
+ features: {
310
+ total: 0,
311
+ byFeature: {},
312
+ message: 'No feature usage data available',
313
+ },
314
+ });
315
+ }
316
+ const events = analyticsResult.data?.data || analyticsResult.data?.documents || [];
317
+ return processFeatureUsage(events, startDate);
318
+ }
319
+ const events = result.data?.data || result.data?.documents || [];
320
+ return processFeatureUsage(events, startDate);
321
+ }
322
+ function processFeatureUsage(events, startDate) {
323
+ const recentEvents = events.filter((e) => new Date(e.created_at) >= startDate);
324
+ const byFeature = {};
325
+ const byDay = {};
326
+ recentEvents.forEach((e) => {
327
+ const feature = e.feature || e.action || e.event_type || 'unknown';
328
+ const userId = e.user_id || e.idp_user_id || 'anonymous';
329
+ const date = new Date(e.created_at).toISOString().split('T')[0];
330
+ if (!byFeature[feature]) {
331
+ byFeature[feature] = { count: 0, uniqueUsers: new Set() };
332
+ }
333
+ byFeature[feature].count++;
334
+ byFeature[feature].uniqueUsers.add(userId);
335
+ byDay[date] = (byDay[date] || 0) + 1;
336
+ });
337
+ const features = Object.entries(byFeature)
338
+ .map(([name, data]) => ({
339
+ name,
340
+ count: data.count,
341
+ uniqueUsers: data.uniqueUsers.size,
342
+ }))
343
+ .sort((a, b) => b.count - a.count);
344
+ const dailyUsage = Object.entries(byDay)
345
+ .map(([date, count]) => ({ date, count }))
346
+ .sort((a, b) => a.date.localeCompare(b.date));
347
+ return server_1.NextResponse.json({
348
+ features: {
349
+ total: recentEvents.length,
350
+ byFeature: features,
351
+ dailyUsage,
352
+ },
353
+ });
354
+ }
355
+ async function getSummaryAnalytics(startDate) {
356
+ // Get users
357
+ const usersResult = await vibeServiceRequest('/v1/collections/vibe_app/tables/users/query', { method: 'POST', body: { page: 1, pageSize: 10000 } });
358
+ // Get sessions
359
+ const sessionsResult = await vibeServiceRequest('/v1/collections/vibe_app/tables/login_sessions/query', { method: 'POST', body: { page: 1, pageSize: 5000 } });
360
+ const users = usersResult.ok ? (usersResult.data?.data || usersResult.data?.documents || []) : [];
361
+ const sessions = sessionsResult.ok ? (sessionsResult.data?.data || sessionsResult.data?.documents || []) : [];
362
+ const recentUsers = users.filter((u) => new Date(u.created_at) >= startDate);
363
+ const recentSessions = sessions.filter((s) => new Date(s.created_at) >= startDate);
364
+ const tierCounts = {};
365
+ users.forEach((u) => {
366
+ const tier = u.tier || 'free';
367
+ tierCounts[tier] = (tierCounts[tier] || 0) + 1;
368
+ });
369
+ return server_1.NextResponse.json({
370
+ summary: {
371
+ totalUsers: users.length,
372
+ newUsers: recentUsers.length,
373
+ activeSessions: sessions.filter((s) => s.status === 'active').length,
374
+ recentLogins: recentSessions.length,
375
+ usersByTier: tierCounts,
376
+ },
377
+ });
378
+ }