@payez/next-mvp 4.0.0 → 4.0.2

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 (81) hide show
  1. package/dist/api-handlers/account/change-password.js +110 -110
  2. package/dist/api-handlers/admin/analytics.d.ts +19 -19
  3. package/dist/api-handlers/admin/analytics.js +378 -378
  4. package/dist/api-handlers/admin/audit.d.ts +19 -19
  5. package/dist/api-handlers/admin/audit.js +213 -213
  6. package/dist/api-handlers/admin/index.d.ts +21 -21
  7. package/dist/api-handlers/admin/index.js +42 -42
  8. package/dist/api-handlers/admin/redis-sessions.d.ts +35 -35
  9. package/dist/api-handlers/admin/redis-sessions.js +203 -203
  10. package/dist/api-handlers/admin/sessions.d.ts +20 -20
  11. package/dist/api-handlers/admin/sessions.js +283 -283
  12. package/dist/api-handlers/admin/site-logs.d.ts +45 -45
  13. package/dist/api-handlers/admin/site-logs.js +317 -317
  14. package/dist/api-handlers/admin/stats.d.ts +20 -20
  15. package/dist/api-handlers/admin/stats.js +239 -239
  16. package/dist/api-handlers/admin/users.d.ts +19 -19
  17. package/dist/api-handlers/admin/users.js +221 -221
  18. package/dist/api-handlers/admin/vibe-data.d.ts +79 -79
  19. package/dist/api-handlers/admin/vibe-data.js +267 -267
  20. package/dist/api-handlers/auth/refresh.js +633 -633
  21. package/dist/api-handlers/auth/signout.js +186 -186
  22. package/dist/api-handlers/auth/verify-code.d.ts +43 -43
  23. package/dist/api-handlers/auth/verify-code.js +90 -90
  24. package/dist/api-handlers/session/viability.js +114 -114
  25. package/dist/api-handlers/test/force-expire.js +59 -59
  26. package/dist/auth/auth-decision.js +182 -182
  27. package/dist/auth/utils/token-utils.d.ts +83 -83
  28. package/dist/auth/utils/token-utils.js +218 -218
  29. package/dist/client/AuthContext.js +115 -115
  30. package/dist/client/better-auth-client.d.ts +1020 -1020
  31. package/dist/components/SessionSync.js +121 -121
  32. package/dist/components/account/MobileNavDrawer.js +64 -64
  33. package/dist/components/account/UserAvatarMenu.js +91 -91
  34. package/dist/components/admin/VibeAdminLayout.js +71 -71
  35. package/dist/hooks/useAuthSettings.js +93 -93
  36. package/dist/hooks/useAvailableProviders.d.ts +43 -43
  37. package/dist/hooks/useAvailableProviders.js +112 -112
  38. package/dist/lib/app-slug.d.ts +95 -95
  39. package/dist/lib/app-slug.js +172 -172
  40. package/dist/lib/test-aware-get-token.js +86 -86
  41. package/dist/lib/token-lifecycle.d.ts +78 -78
  42. package/dist/lib/token-lifecycle.js +360 -360
  43. package/dist/pages/admin-login/page.js +73 -73
  44. package/dist/pages/client-admin/ClientSiteAdminPage.js +179 -179
  45. package/dist/pages/login/page.js +202 -202
  46. package/dist/pages/showcase/ShowcasePage.js +142 -142
  47. package/dist/pages/test-env/EmergencyLogoutPage.js +99 -99
  48. package/dist/pages/test-env/JwtInspectPage.js +116 -116
  49. package/dist/pages/test-env/TestEnvPage.js +51 -51
  50. package/dist/pages/verify-code/page.js +412 -412
  51. package/dist/routes/auth/logout.d.ts +31 -31
  52. package/dist/routes/auth/logout.js +98 -98
  53. package/dist/routes/auth/session.js +157 -157
  54. package/dist/routes/auth/viability.js +190 -190
  55. package/package.json +6 -16
  56. package/dist/auth/auth-options.d.ts +0 -57
  57. package/dist/auth/auth-options.js +0 -213
  58. package/dist/auth/callbacks/index.d.ts +0 -6
  59. package/dist/auth/callbacks/index.js +0 -12
  60. package/dist/auth/callbacks/jwt.d.ts +0 -45
  61. package/dist/auth/callbacks/jwt.js +0 -305
  62. package/dist/auth/callbacks/session.d.ts +0 -60
  63. package/dist/auth/callbacks/session.js +0 -170
  64. package/dist/auth/callbacks/signin.d.ts +0 -23
  65. package/dist/auth/callbacks/signin.js +0 -44
  66. package/dist/auth/events/index.d.ts +0 -4
  67. package/dist/auth/events/index.js +0 -8
  68. package/dist/auth/events/signout.d.ts +0 -17
  69. package/dist/auth/events/signout.js +0 -32
  70. package/dist/auth/providers/credentials.d.ts +0 -32
  71. package/dist/auth/providers/credentials.js +0 -223
  72. package/dist/auth/providers/index.d.ts +0 -5
  73. package/dist/auth/providers/index.js +0 -21
  74. package/dist/auth/providers/oauth.d.ts +0 -26
  75. package/dist/auth/providers/oauth.js +0 -105
  76. package/dist/lib/nextauth-secret.d.ts +0 -10
  77. package/dist/lib/nextauth-secret.js +0 -100
  78. package/dist/pages/profile/profile-patch.d.ts +0 -1
  79. package/dist/pages/profile/profile-patch.js +0 -281
  80. package/dist/pages/security/security-patch.d.ts +0 -1
  81. package/dist/pages/security/security-patch.js +0 -302
@@ -1,378 +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 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
- }
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
+ }