@payez/next-mvp 3.9.1 → 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 (147) 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 -1020
  39. package/dist/client/fetch-with-auth.js +2 -2
  40. package/dist/components/SessionSync.js +121 -119
  41. package/dist/components/account/MobileNavDrawer.js +64 -64
  42. package/dist/components/account/UserAvatarMenu.js +91 -88
  43. package/dist/components/admin/VibeAdminLayout.js +71 -69
  44. package/dist/hooks/useAuth.js +9 -7
  45. package/dist/hooks/useAuthSettings.js +93 -93
  46. package/dist/hooks/useAvailableProviders.d.ts +43 -45
  47. package/dist/hooks/useAvailableProviders.js +112 -108
  48. package/dist/hooks/useSessionExpiration.d.ts +2 -3
  49. package/dist/hooks/useSessionExpiration.js +2 -2
  50. package/dist/hooks/useViabilitySession.js +3 -2
  51. package/dist/index.js +4 -6
  52. package/dist/lib/app-slug.d.ts +95 -95
  53. package/dist/lib/app-slug.js +172 -172
  54. package/dist/lib/standardized-client-api.js +10 -5
  55. package/dist/lib/startup-init.js +21 -25
  56. package/dist/lib/test-aware-get-token.js +86 -81
  57. package/dist/lib/token-lifecycle.d.ts +78 -52
  58. package/dist/lib/token-lifecycle.js +360 -398
  59. package/dist/pages/admin-login/page.js +73 -83
  60. package/dist/pages/client-admin/ClientSiteAdminPage.js +179 -177
  61. package/dist/pages/login/page.js +202 -211
  62. package/dist/pages/showcase/ShowcasePage.js +142 -140
  63. package/dist/pages/test-env/EmergencyLogoutPage.js +99 -98
  64. package/dist/pages/test-env/JwtInspectPage.js +116 -114
  65. package/dist/pages/test-env/RefreshTokenPage.js +4 -2
  66. package/dist/pages/test-env/TestEnvPage.js +51 -49
  67. package/dist/pages/verify-code/page.js +412 -408
  68. package/dist/routes/auth/logout.d.ts +31 -31
  69. package/dist/routes/auth/logout.js +98 -113
  70. package/dist/routes/auth/nextauth.d.ts +14 -11
  71. package/dist/routes/auth/nextauth.js +25 -57
  72. package/dist/routes/auth/session.js +157 -179
  73. package/dist/routes/auth/viability.js +190 -201
  74. package/dist/server/auth.d.ts +50 -0
  75. package/dist/server/auth.js +62 -0
  76. package/dist/stores/authStore.js +19 -23
  77. package/dist/utils/logout.js +5 -5
  78. package/package.json +1 -3
  79. package/src/api/auth-handler.ts +550 -549
  80. package/src/api-handlers/account/change-password.ts +5 -8
  81. package/src/api-handlers/admin/analytics.ts +4 -6
  82. package/src/api-handlers/admin/audit.ts +5 -7
  83. package/src/api-handlers/admin/index.ts +1 -2
  84. package/src/api-handlers/admin/redis-sessions.ts +6 -8
  85. package/src/api-handlers/admin/sessions.ts +5 -7
  86. package/src/api-handlers/admin/site-logs.ts +8 -10
  87. package/src/api-handlers/admin/stats.ts +4 -6
  88. package/src/api-handlers/admin/users.ts +5 -7
  89. package/src/api-handlers/admin/vibe-data.ts +10 -12
  90. package/src/api-handlers/auth/refresh.ts +5 -7
  91. package/src/api-handlers/auth/signout.ts +5 -6
  92. package/src/api-handlers/auth/status.ts +4 -7
  93. package/src/api-handlers/auth/update-session.ts +123 -125
  94. package/src/api-handlers/auth/verify-code.ts +9 -13
  95. package/src/api-handlers/session/viability.ts +10 -47
  96. package/src/api-handlers/test/force-expire.ts +4 -11
  97. package/src/auth/auth-decision.ts +1 -1
  98. package/src/auth/better-auth.ts +138 -141
  99. package/src/auth/route-config.ts +219 -219
  100. package/src/auth/utils/token-utils.ts +0 -1
  101. package/src/client/AuthContext.tsx +6 -2
  102. package/src/client/fetch-with-auth.ts +47 -47
  103. package/src/components/SessionSync.tsx +6 -5
  104. package/src/components/account/MobileNavDrawer.tsx +3 -3
  105. package/src/components/account/UserAvatarMenu.tsx +6 -3
  106. package/src/components/admin/VibeAdminLayout.tsx +4 -2
  107. package/src/config/logger.ts +1 -1
  108. package/src/hooks/useAuth.ts +117 -115
  109. package/src/hooks/useAuthSettings.ts +2 -2
  110. package/src/hooks/useAvailableProviders.ts +9 -5
  111. package/src/hooks/useSessionExpiration.ts +101 -102
  112. package/src/hooks/useViabilitySession.ts +336 -335
  113. package/src/index.ts +60 -63
  114. package/src/lib/api-handler.ts +0 -1
  115. package/src/lib/app-slug.ts +6 -6
  116. package/src/lib/standardized-client-api.ts +901 -895
  117. package/src/lib/startup-init.ts +243 -247
  118. package/src/lib/test-aware-get-token.ts +22 -12
  119. package/src/lib/token-lifecycle.ts +12 -53
  120. package/src/pages/admin-login/page.tsx +9 -17
  121. package/src/pages/client-admin/ClientSiteAdminPage.tsx +4 -2
  122. package/src/pages/login/page.tsx +21 -28
  123. package/src/pages/showcase/ShowcasePage.tsx +4 -2
  124. package/src/pages/test-env/EmergencyLogoutPage.tsx +7 -6
  125. package/src/pages/test-env/JwtInspectPage.tsx +5 -3
  126. package/src/pages/test-env/RefreshTokenPage.tsx +157 -155
  127. package/src/pages/test-env/TestEnvPage.tsx +4 -2
  128. package/src/pages/verify-code/page.tsx +10 -6
  129. package/src/routes/auth/logout.ts +7 -25
  130. package/src/routes/auth/nextauth.ts +45 -71
  131. package/src/routes/auth/session.ts +25 -50
  132. package/src/routes/auth/viability.ts +7 -19
  133. package/src/server/auth.ts +60 -0
  134. package/src/stores/authStore.ts +1899 -1904
  135. package/src/utils/logout.ts +30 -30
  136. package/src/auth/auth-options.ts +0 -237
  137. package/src/auth/callbacks/index.ts +0 -7
  138. package/src/auth/callbacks/jwt.ts +0 -382
  139. package/src/auth/callbacks/session.ts +0 -243
  140. package/src/auth/callbacks/signin.ts +0 -56
  141. package/src/auth/events/index.ts +0 -5
  142. package/src/auth/events/signout.ts +0 -33
  143. package/src/auth/providers/credentials.ts +0 -256
  144. package/src/auth/providers/index.ts +0 -6
  145. package/src/auth/providers/oauth.ts +0 -114
  146. package/src/lib/nextauth-secret.ts +0 -121
  147. package/src/types/next-auth.d.ts +0 -15
@@ -1,21 +1,20 @@
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
- import { NextRequest, NextResponse } from 'next/server';
11
- export interface AdminStatsHandlerConfig {
12
- getAuthOptions: () => Promise<any>;
13
- appSlug?: string;
14
- }
15
- /**
16
- * GET /api/admin/stats - Dashboard statistics
17
- * Aggregates users + tier breakdown, active Redis sessions, and recent audit activity.
18
- */
19
- export declare function createStatsHandler(config: AdminStatsHandlerConfig): {
20
- GET(_request: NextRequest): Promise<NextResponse<unknown>>;
21
- };
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
+ import { NextRequest, NextResponse } from 'next/server';
11
+ export interface AdminStatsHandlerConfig {
12
+ appSlug?: string;
13
+ }
14
+ /**
15
+ * GET /api/admin/stats - Dashboard statistics
16
+ * Aggregates users + tier breakdown, active Redis sessions, and recent audit activity.
17
+ */
18
+ export declare function createStatsHandler(config: AdminStatsHandlerConfig): {
19
+ GET(_request: NextRequest): Promise<NextResponse<unknown>>;
20
+ };
@@ -1,240 +1,239 @@
1
- "use strict";
2
- /**
3
- * Admin Stats API Handler
4
- *
5
- * Aggregates dashboard statistics from users, Redis sessions, and audit logs.
6
- * Uses service account HMAC auth for Vibe API requests.
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.createStatsHandler = createStatsHandler;
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 redis_1 = require("../../lib/redis");
50
- const roles_1 = require("../../lib/roles");
51
- async function checkAdminRole(getAuthOptions) {
52
- const authOptions = await getAuthOptions();
53
- const session = await (0, next_auth_1.getServerSession)(authOptions);
54
- if (!session?.user) {
55
- return {
56
- isAdmin: false,
57
- error: server_1.NextResponse.json({ success: false, error: 'Please sign in' }, { status: 401 }),
58
- };
59
- }
60
- const userRoles = session.user?.roles || [];
61
- const hasAdminRole = roles_1.ADMIN_ROLES.some(role => userRoles.includes(role));
62
- if (!hasAdminRole) {
63
- return {
64
- isAdmin: false,
65
- error: server_1.NextResponse.json({ success: false, error: 'Admin access required' }, { status: 403 }),
66
- };
67
- }
68
- return { isAdmin: true };
69
- }
70
- async function vibeServiceRequest(endpoint, options) {
71
- const idpUrl = process.env.NEXT_PUBLIC_IDP_URL || process.env.IDP_URL;
72
- const clientId = process.env.VIBE_CLIENT_ID;
73
- const signingKey = process.env.VIBE_HMAC_KEY;
74
- if (!idpUrl || !clientId || !signingKey) {
75
- return { ok: false, status: 500, data: null, error: 'Vibe not configured' };
76
- }
77
- const timestamp = Math.floor(Date.now() / 1000);
78
- const stringToSign = `${timestamp}|${options.method}|${endpoint}`;
79
- const crypto = await Promise.resolve().then(() => __importStar(require('crypto')));
80
- const signature = crypto
81
- .createHmac('sha256', Buffer.from(signingKey, 'base64'))
82
- .update(stringToSign)
83
- .digest('base64');
84
- const proxyUrl = `${idpUrl}/api/vibe/proxy`;
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
- /**
118
- * GET /api/admin/stats - Dashboard statistics
119
- * Aggregates users + tier breakdown, active Redis sessions, and recent audit activity.
120
- */
121
- function createStatsHandler(config) {
122
- const getSessionPrefix = () => {
123
- const appSlug = config.appSlug || process.env.APP_SLUG || process.env.CLIENT_ID || 'app';
124
- return `${appSlug}:sess:`;
125
- };
126
- return {
127
- async GET(_request) {
128
- const adminCheck = await checkAdminRole(config.getAuthOptions);
129
- if (adminCheck.error)
130
- return adminCheck.error;
131
- try {
132
- // Fetch from 3 sources in parallel
133
- const [usersResult, sessionCount, auditResult] = await Promise.allSettled([
134
- // 1. Users + tier breakdown via HMAC proxy (Vibe collection query)
135
- vibeServiceRequest('/v1/collections/vibe_app/tables/users/query', {
136
- method: 'POST',
137
- body: { page: 1, pageSize: 500, orderBy: 'created_at', orderDirection: 'desc' },
138
- }),
139
- // 2. Active sessions from Redis
140
- (async () => {
141
- const redis = (0, redis_1.getRedis)();
142
- const sessionPrefix = getSessionPrefix();
143
- const sessionKeys = [];
144
- let cursor = '0';
145
- do {
146
- const [newCursor, keys] = await redis.scan(cursor, 'MATCH', `${sessionPrefix}*`, 'COUNT', 100);
147
- cursor = newCursor;
148
- sessionKeys.push(...keys.filter((k) => !k.includes(':ver:')));
149
- } while (cursor !== '0');
150
- return sessionKeys.length;
151
- })(),
152
- // 3. Recent audit activity via HMAC proxy
153
- vibeServiceRequest('/v1/audit?pageSize=10&sortDir=desc', { method: 'GET' }),
154
- ]);
155
- // Parse users — deduplicate by user_id
156
- let totalUsers = 0;
157
- let tierBreakdown = {};
158
- if (usersResult.status === 'fulfilled' && usersResult.value.ok && usersResult.value.data) {
159
- const data = usersResult.value.data;
160
- const rawUsers = data.data || data.documents || data.users || [];
161
- // Deduplicate by user_id (keeps latest document_id)
162
- const userMap = new Map();
163
- for (const u of rawUsers) {
164
- const uid = u.user_id || u.id || u.document_id;
165
- const existing = userMap.get(uid);
166
- if (!existing || (u.document_id || '') > (existing.document_id || '')) {
167
- userMap.set(uid, u);
168
- }
169
- }
170
- const uniqueUsers = Array.from(userMap.values());
171
- totalUsers = uniqueUsers.length;
172
- // Build tier breakdown from deduplicated users (unless API provides one)
173
- tierBreakdown = data.tierBreakdown || data.tiers || {};
174
- if (Object.keys(tierBreakdown).length === 0) {
175
- for (const user of uniqueUsers) {
176
- const tier = user.tier || 'free';
177
- tierBreakdown[tier] = (tierBreakdown[tier] || 0) + 1;
178
- }
179
- }
180
- }
181
- // Parse active sessions count
182
- let activeSessions = 0;
183
- if (sessionCount.status === 'fulfilled') {
184
- activeSessions = sessionCount.value;
185
- }
186
- // Parse audit events for recent activity
187
- let recentActivity = [];
188
- if (auditResult.status === 'fulfilled' && auditResult.value.ok && auditResult.value.data) {
189
- const data = auditResult.value.data;
190
- // Handle multiple possible response shapes
191
- let events = [];
192
- if (Array.isArray(data)) {
193
- events = data;
194
- }
195
- else if (Array.isArray(data.data)) {
196
- events = data.data;
197
- }
198
- else if (Array.isArray(data.entries)) {
199
- events = data.entries;
200
- }
201
- else if (Array.isArray(data.items)) {
202
- events = data.items;
203
- }
204
- else if (Array.isArray(data.documents)) {
205
- events = data.documents;
206
- }
207
- else if (data.success && Array.isArray(data.results)) {
208
- events = data.results;
209
- }
210
- recentActivity = events.slice(0, 5).map((e) => ({
211
- id: e.audit_log_id || e.id || e.document_id,
212
- type: e.category || e.type || 'admin',
213
- action: e.action || e.event || e.message || 'Unknown action',
214
- actor: e.admin_email || e.actor || e.user || e.actor_email || 'System',
215
- target: e.target_type ? `${e.target_type}:${e.target_id}` : (e.target || e.target_user),
216
- details: e.description || e.details,
217
- timestamp: e.created_at || e.timestamp || e.date,
218
- success: e.is_success ?? e.success ?? true,
219
- }));
220
- }
221
- // Calculate tier percentages
222
- const tiers = Object.entries(tierBreakdown).map(([name, count]) => ({
223
- name,
224
- count: count,
225
- pct: totalUsers > 0 ? Math.round((count / totalUsers) * 100) : 0,
226
- }));
227
- return server_1.NextResponse.json({
228
- totalUsers,
229
- activeSessions,
230
- tiers,
231
- recentActivity,
232
- });
233
- }
234
- catch (error) {
235
- console.error('[admin/stats] Error:', error);
236
- return server_1.NextResponse.json({ error: error.message || 'Internal error' }, { status: 500 });
237
- }
238
- },
239
- };
240
- }
1
+ "use strict";
2
+ /**
3
+ * Admin Stats API Handler
4
+ *
5
+ * Aggregates dashboard statistics from users, Redis sessions, and audit logs.
6
+ * Uses service account HMAC auth for Vibe API requests.
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.createStatsHandler = createStatsHandler;
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 redis_1 = require("../../lib/redis");
50
+ const roles_1 = require("../../lib/roles");
51
+ async function checkAdminRole(request) {
52
+ const session = await (0, auth_1.getSession)(request);
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
+ 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
+ /**
117
+ * GET /api/admin/stats - Dashboard statistics
118
+ * Aggregates users + tier breakdown, active Redis sessions, and recent audit activity.
119
+ */
120
+ function createStatsHandler(config) {
121
+ const getSessionPrefix = () => {
122
+ const appSlug = config.appSlug || process.env.APP_SLUG || process.env.CLIENT_ID || 'app';
123
+ return `${appSlug}:sess:`;
124
+ };
125
+ return {
126
+ async GET(_request) {
127
+ const adminCheck = await checkAdminRole(_request);
128
+ if (adminCheck.error)
129
+ return adminCheck.error;
130
+ try {
131
+ // Fetch from 3 sources in parallel
132
+ const [usersResult, sessionCount, auditResult] = await Promise.allSettled([
133
+ // 1. Users + tier breakdown via HMAC proxy (Vibe collection query)
134
+ vibeServiceRequest('/v1/collections/vibe_app/tables/users/query', {
135
+ method: 'POST',
136
+ body: { page: 1, pageSize: 500, orderBy: 'created_at', orderDirection: 'desc' },
137
+ }),
138
+ // 2. Active sessions from Redis
139
+ (async () => {
140
+ const redis = (0, redis_1.getRedis)();
141
+ const sessionPrefix = getSessionPrefix();
142
+ const sessionKeys = [];
143
+ let cursor = '0';
144
+ do {
145
+ const [newCursor, keys] = await redis.scan(cursor, 'MATCH', `${sessionPrefix}*`, 'COUNT', 100);
146
+ cursor = newCursor;
147
+ sessionKeys.push(...keys.filter((k) => !k.includes(':ver:')));
148
+ } while (cursor !== '0');
149
+ return sessionKeys.length;
150
+ })(),
151
+ // 3. Recent audit activity via HMAC proxy
152
+ vibeServiceRequest('/v1/audit?pageSize=10&sortDir=desc', { method: 'GET' }),
153
+ ]);
154
+ // Parse users — deduplicate by user_id
155
+ let totalUsers = 0;
156
+ let tierBreakdown = {};
157
+ if (usersResult.status === 'fulfilled' && usersResult.value.ok && usersResult.value.data) {
158
+ const data = usersResult.value.data;
159
+ const rawUsers = data.data || data.documents || data.users || [];
160
+ // Deduplicate by user_id (keeps latest document_id)
161
+ const userMap = new Map();
162
+ for (const u of rawUsers) {
163
+ const uid = u.user_id || u.id || u.document_id;
164
+ const existing = userMap.get(uid);
165
+ if (!existing || (u.document_id || '') > (existing.document_id || '')) {
166
+ userMap.set(uid, u);
167
+ }
168
+ }
169
+ const uniqueUsers = Array.from(userMap.values());
170
+ totalUsers = uniqueUsers.length;
171
+ // Build tier breakdown from deduplicated users (unless API provides one)
172
+ tierBreakdown = data.tierBreakdown || data.tiers || {};
173
+ if (Object.keys(tierBreakdown).length === 0) {
174
+ for (const user of uniqueUsers) {
175
+ const tier = user.tier || 'free';
176
+ tierBreakdown[tier] = (tierBreakdown[tier] || 0) + 1;
177
+ }
178
+ }
179
+ }
180
+ // Parse active sessions count
181
+ let activeSessions = 0;
182
+ if (sessionCount.status === 'fulfilled') {
183
+ activeSessions = sessionCount.value;
184
+ }
185
+ // Parse audit events for recent activity
186
+ let recentActivity = [];
187
+ if (auditResult.status === 'fulfilled' && auditResult.value.ok && auditResult.value.data) {
188
+ const data = auditResult.value.data;
189
+ // Handle multiple possible response shapes
190
+ let events = [];
191
+ if (Array.isArray(data)) {
192
+ events = data;
193
+ }
194
+ else if (Array.isArray(data.data)) {
195
+ events = data.data;
196
+ }
197
+ else if (Array.isArray(data.entries)) {
198
+ events = data.entries;
199
+ }
200
+ else if (Array.isArray(data.items)) {
201
+ events = data.items;
202
+ }
203
+ else if (Array.isArray(data.documents)) {
204
+ events = data.documents;
205
+ }
206
+ else if (data.success && Array.isArray(data.results)) {
207
+ events = data.results;
208
+ }
209
+ recentActivity = events.slice(0, 5).map((e) => ({
210
+ id: e.audit_log_id || e.id || e.document_id,
211
+ type: e.category || e.type || 'admin',
212
+ action: e.action || e.event || e.message || 'Unknown action',
213
+ actor: e.admin_email || e.actor || e.user || e.actor_email || 'System',
214
+ target: e.target_type ? `${e.target_type}:${e.target_id}` : (e.target || e.target_user),
215
+ details: e.description || e.details,
216
+ timestamp: e.created_at || e.timestamp || e.date,
217
+ success: e.is_success ?? e.success ?? true,
218
+ }));
219
+ }
220
+ // Calculate tier percentages
221
+ const tiers = Object.entries(tierBreakdown).map(([name, count]) => ({
222
+ name,
223
+ count: count,
224
+ pct: totalUsers > 0 ? Math.round((count / totalUsers) * 100) : 0,
225
+ }));
226
+ return server_1.NextResponse.json({
227
+ totalUsers,
228
+ activeSessions,
229
+ tiers,
230
+ recentActivity,
231
+ });
232
+ }
233
+ catch (error) {
234
+ console.error('[admin/stats] Error:', error);
235
+ return server_1.NextResponse.json({ error: error.message || 'Internal error' }, { status: 500 });
236
+ }
237
+ },
238
+ };
239
+ }
@@ -1,20 +1,19 @@
1
- /**
2
- * Admin Users API Handler
3
- *
4
- * Provides admin-level access to users using service account credentials.
5
- *
6
- * @version 1.0
7
- * @requires Admin role (vibe_app_admin or payez_admin)
8
- */
9
- import { NextRequest, NextResponse } from 'next/server';
10
- export interface AdminUsersHandlerConfig {
11
- getAuthOptions: () => Promise<any>;
12
- }
13
- /**
14
- * GET /api/admin/users - List users
15
- * POST /api/admin/users - Stats, search, update tier
16
- */
17
- export declare function createUsersHandler(config: AdminUsersHandlerConfig): {
18
- GET(request: NextRequest): Promise<NextResponse<unknown>>;
19
- POST(request: NextRequest): Promise<NextResponse<unknown>>;
20
- };
1
+ /**
2
+ * Admin Users API Handler
3
+ *
4
+ * Provides admin-level access to users using service account credentials.
5
+ *
6
+ * @version 1.0
7
+ * @requires Admin role (vibe_app_admin or payez_admin)
8
+ */
9
+ import { NextRequest, NextResponse } from 'next/server';
10
+ export interface AdminUsersHandlerConfig {
11
+ }
12
+ /**
13
+ * GET /api/admin/users - List users
14
+ * POST /api/admin/users - Stats, search, update tier
15
+ */
16
+ export declare function createUsersHandler(config: AdminUsersHandlerConfig): {
17
+ GET(request: NextRequest): Promise<NextResponse<unknown>>;
18
+ POST(request: NextRequest): Promise<NextResponse<unknown>>;
19
+ };