@payez/next-mvp 4.0.47 → 4.1.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.
@@ -1,238 +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 3 sources in parallel
123
- const [usersResult, sessionCount, auditResult] = await Promise.allSettled([
124
- // 1. Users + tier breakdown 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. Active sessions from Redis
131
- (async () => {
132
- const redis = getRedis();
133
- const sessionPrefix = getSessionPrefix();
134
- const sessionKeys: string[] = [];
135
- let cursor = '0';
136
- do {
137
- const [newCursor, keys] = await redis.scan(cursor, 'MATCH', `${sessionPrefix}*`, 'COUNT', 100);
138
- cursor = newCursor;
139
- sessionKeys.push(...keys.filter((k: string) => !k.includes(':ver:')));
140
- } while (cursor !== '0');
141
- return sessionKeys.length;
142
- })(),
143
-
144
- // 3. Recent audit activity via HMAC proxy
145
- vibeServiceRequest<any>('/v1/audit?pageSize=10&sortDir=desc', { method: 'GET' }),
146
- ]);
147
-
148
- // Parse users deduplicate by user_id
149
- let totalUsers = 0;
150
- let tierBreakdown: Record<string, number> = {};
151
- if (usersResult.status === 'fulfilled' && usersResult.value.ok && usersResult.value.data) {
152
- const data = usersResult.value.data;
153
- const rawUsers = data.data || data.documents || data.users || [];
154
-
155
- // Deduplicate by user_id (keeps latest document_id)
156
- const userMap = new Map();
157
- for (const u of rawUsers) {
158
- const uid = u.user_id || u.id || u.document_id;
159
- const existing = userMap.get(uid);
160
- if (!existing || (u.document_id || '') > (existing.document_id || '')) {
161
- userMap.set(uid, u);
162
- }
163
- }
164
- const uniqueUsers = Array.from(userMap.values());
165
- totalUsers = uniqueUsers.length;
166
-
167
- // Build tier breakdown from deduplicated users (unless API provides one)
168
- tierBreakdown = data.tierBreakdown || data.tiers || {};
169
- if (Object.keys(tierBreakdown).length === 0) {
170
- for (const user of uniqueUsers) {
171
- const tier = user.tier || 'free';
172
- tierBreakdown[tier] = (tierBreakdown[tier] || 0) + 1;
173
- }
174
- }
175
- }
176
-
177
- // Parse active sessions count
178
- let activeSessions = 0;
179
- if (sessionCount.status === 'fulfilled') {
180
- activeSessions = sessionCount.value;
181
- }
182
-
183
- // Parse audit events for recent activity
184
- let recentActivity: any[] = [];
185
- if (auditResult.status === 'fulfilled' && auditResult.value.ok && auditResult.value.data) {
186
- const data = auditResult.value.data;
187
-
188
- // Handle multiple possible response shapes
189
- let events: any[] = [];
190
- if (Array.isArray(data)) {
191
- events = data;
192
- } else if (Array.isArray(data.data)) {
193
- events = data.data;
194
- } else if (Array.isArray(data.entries)) {
195
- events = data.entries;
196
- } else if (Array.isArray(data.items)) {
197
- events = data.items;
198
- } else if (Array.isArray(data.documents)) {
199
- events = data.documents;
200
- } else if (data.success && Array.isArray(data.results)) {
201
- events = data.results;
202
- }
203
-
204
- recentActivity = events.slice(0, 5).map((e: any) => ({
205
- id: e.audit_log_id || e.id || e.document_id,
206
- type: e.category || e.type || 'admin',
207
- action: e.action || e.event || e.message || 'Unknown action',
208
- actor: e.admin_email || e.actor || e.user || e.actor_email || 'System',
209
- target: e.target_type ? `${e.target_type}:${e.target_id}` : (e.target || e.target_user),
210
- details: e.description || e.details,
211
- timestamp: e.created_at || e.timestamp || e.date,
212
- success: e.is_success ?? e.success ?? true,
213
- }));
214
- }
215
-
216
- // Calculate tier percentages
217
- const tiers = Object.entries(tierBreakdown).map(([name, count]) => ({
218
- name,
219
- count: count as number,
220
- pct: totalUsers > 0 ? Math.round(((count as number) / totalUsers) * 100) : 0,
221
- }));
222
-
223
- return NextResponse.json({
224
- totalUsers,
225
- activeSessions,
226
- tiers,
227
- recentActivity,
228
- });
229
- } catch (error: any) {
230
- console.error('[admin/stats] Error:', error);
231
- return NextResponse.json(
232
- { error: error.message || 'Internal error' },
233
- { status: 500 }
234
- );
235
- }
236
- },
237
- };
238
- }
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
+ }