@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,284 +1,283 @@
1
- "use strict";
2
- /**
3
- * Admin Sessions API Handler
4
- *
5
- * Provides admin-level access to login sessions using service account credentials.
6
- * Used by SessionsTab component.
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.createSessionsHandler = createSessionsHandler;
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
- /**
51
- * Check if the current user has admin role
52
- */
53
- async function checkAdminRole(getAuthOptions) {
54
- const authOptions = await getAuthOptions();
55
- const session = await (0, next_auth_1.getServerSession)(authOptions);
56
- if (!session?.user) {
57
- return {
58
- isAdmin: false,
59
- error: server_1.NextResponse.json({ success: false, error: 'Please sign in' }, { status: 401 }),
60
- };
61
- }
62
- const userRoles = session.user?.roles || [];
63
- const hasAdminRole = roles_1.ADMIN_ROLES.some(role => userRoles.includes(role));
64
- if (!hasAdminRole) {
65
- return {
66
- isAdmin: false,
67
- error: server_1.NextResponse.json({ success: false, error: 'Admin access required' }, { status: 403 }),
68
- };
69
- }
70
- return { isAdmin: true, userId: session.user?.id };
71
- }
72
- /**
73
- * Make a service account request to Vibe (admin mode)
74
- */
75
- async function vibeServiceRequest(endpoint, options) {
76
- const idpUrl = process.env.NEXT_PUBLIC_IDP_URL || process.env.IDP_URL;
77
- const clientId = process.env.VIBE_CLIENT_ID;
78
- const signingKey = process.env.VIBE_HMAC_KEY;
79
- if (!idpUrl || !clientId || !signingKey) {
80
- return { ok: false, status: 500, data: null, error: 'Vibe not configured' };
81
- }
82
- const timestamp = Math.floor(Date.now() / 1000);
83
- const stringToSign = `${timestamp}|${options.method}|${endpoint}`;
84
- const crypto = await Promise.resolve().then(() => __importStar(require('crypto')));
85
- const signature = crypto
86
- .createHmac('sha256', Buffer.from(signingKey, 'base64'))
87
- .update(stringToSign)
88
- .digest('base64');
89
- const proxyUrl = `${idpUrl}/api/vibe/proxy`;
90
- // Get the client slug from startup config for multi-client admin support
91
- const idpConfig = (0, startup_init_1.getStartupIDPConfig)();
92
- const idpClientId = idpConfig?.clientSlug || idpConfig?.clientId;
93
- try {
94
- const res = await fetch(proxyUrl, {
95
- method: 'POST',
96
- headers: {
97
- 'Content-Type': 'application/json',
98
- 'X-Vibe-Client-Id': clientId,
99
- 'X-Vibe-Timestamp': String(timestamp),
100
- 'X-Vibe-Signature': signature,
101
- ...(idpClientId && { 'X-Client-Id': idpClientId }),
102
- },
103
- body: JSON.stringify({
104
- endpoint,
105
- method: options.method,
106
- data: options.body ?? null,
107
- }),
108
- cache: 'no-store',
109
- });
110
- if (res.status === 204) {
111
- return { ok: true, status: 204, data: null };
112
- }
113
- if (!res.ok) {
114
- const errorText = await res.text();
115
- return { ok: false, status: res.status, data: null, error: errorText };
116
- }
117
- const body = await res.json();
118
- return { ok: true, status: res.status, data: body };
119
- }
120
- catch (error) {
121
- return { ok: false, status: 0, data: null, error: String(error) };
122
- }
123
- }
124
- // Country code to flag emoji mapping
125
- function getCountryFlag(countryCode) {
126
- if (!countryCode || countryCode.length !== 2)
127
- return '';
128
- const codePoints = countryCode
129
- .toUpperCase()
130
- .split('')
131
- .map(char => 127397 + char.charCodeAt(0));
132
- return String.fromCodePoint(...codePoints);
133
- }
134
- /**
135
- * GET /api/admin/sessions - List sessions
136
- * POST /api/admin/sessions - Stats, revoke actions
137
- */
138
- function createSessionsHandler(config) {
139
- return {
140
- async GET(request) {
141
- const adminCheck = await checkAdminRole(config.getAuthOptions);
142
- if (adminCheck.error)
143
- return adminCheck.error;
144
- const { searchParams } = new URL(request.url);
145
- const status = searchParams.get('status');
146
- const email = searchParams.get('email');
147
- // Build query for login_sessions table
148
- const queryBody = {
149
- page: 1,
150
- pageSize: 100,
151
- orderBy: 'created_at',
152
- orderDirection: 'desc',
153
- };
154
- // Build filter conditions
155
- const conditions = [];
156
- if (status && status !== 'all') {
157
- conditions.push({ field: 'status', operator: 'eq', value: status });
158
- }
159
- if (email) {
160
- conditions.push({ field: 'email', operator: 'like', value: `%${email}%` });
161
- }
162
- if (conditions.length === 1) {
163
- queryBody.filter = conditions[0];
164
- }
165
- else if (conditions.length > 1) {
166
- queryBody.filter = { operator: 'and', conditions };
167
- }
168
- const result = await vibeServiceRequest('/v1/collections/vibe_app/tables/login_sessions/query', { method: 'POST', body: queryBody });
169
- if (!result.ok) {
170
- return server_1.NextResponse.json({ error: result.error }, { status: result.status || 500 });
171
- }
172
- // Extract sessions from response
173
- const rawSessions = result.data?.data || result.data?.documents || [];
174
- const sessions = rawSessions.map((s) => ({
175
- id: s.id || s.document_id,
176
- idp_user_id: s.idp_user_id || s.user_id,
177
- email: s.email || '',
178
- name: s.name || s.display_name || '',
179
- status: s.status || 'active',
180
- ip_address: s.ip_address || s.ip,
181
- city: s.city,
182
- region: s.region,
183
- country_code: s.country_code || s.country,
184
- device_type: s.device_type || s.device,
185
- browser: s.browser,
186
- os: s.os,
187
- created_at: s.created_at,
188
- last_activity: s.last_activity || s.updated_at,
189
- revoked_at: s.revoked_at,
190
- revoked_by: s.revoked_by,
191
- country_flag: getCountryFlag(s.country_code || s.country || ''),
192
- }));
193
- return server_1.NextResponse.json({ sessions });
194
- },
195
- async POST(request) {
196
- const adminCheck = await checkAdminRole(config.getAuthOptions);
197
- if (adminCheck.error)
198
- return adminCheck.error;
199
- const body = await request.json();
200
- const { action, sessionId, userId } = body;
201
- if (action === 'stats') {
202
- // Get all sessions for stats calculation
203
- const result = await vibeServiceRequest('/v1/collections/vibe_app/tables/login_sessions/query', { method: 'POST', body: { page: 1, pageSize: 1000 } });
204
- if (!result.ok) {
205
- return server_1.NextResponse.json({ error: result.error }, { status: result.status || 500 });
206
- }
207
- const sessions = result.data?.data || result.data?.documents || [];
208
- // Calculate stats
209
- const now = new Date();
210
- const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
211
- const stats = {
212
- totalActive: sessions.filter((s) => s.status === 'active').length,
213
- totalRevoked: sessions.filter((s) => s.status === 'revoked').length,
214
- uniqueUsers: new Set(sessions.map((s) => s.idp_user_id || s.user_id)).size,
215
- recentLogins: sessions.filter((s) => new Date(s.created_at) > oneDayAgo).length,
216
- byCountryWithFlags: {},
217
- byDevice: {},
218
- };
219
- // Count by country
220
- sessions.forEach((s) => {
221
- const country = s.country_code || s.country || 'Unknown';
222
- if (!stats.byCountryWithFlags[country]) {
223
- stats.byCountryWithFlags[country] = { count: 0, flag: getCountryFlag(country) };
224
- }
225
- stats.byCountryWithFlags[country].count++;
226
- const device = s.device_type || s.device || 'Unknown';
227
- stats.byDevice[device] = (stats.byDevice[device] || 0) + 1;
228
- });
229
- return server_1.NextResponse.json({ stats });
230
- }
231
- if (action === 'revoke' && sessionId) {
232
- // Revoke single session
233
- const result = await vibeServiceRequest(`/v1/collections/vibe_app/tables/login_sessions/${sessionId}`, {
234
- method: 'PUT',
235
- body: {
236
- status: 'revoked',
237
- revoked_at: new Date().toISOString(),
238
- revoked_by: `admin:${adminCheck.userId}`,
239
- },
240
- });
241
- if (!result.ok) {
242
- return server_1.NextResponse.json({ error: result.error }, { status: result.status || 500 });
243
- }
244
- return server_1.NextResponse.json({ success: true });
245
- }
246
- if (action === 'revoke_all' && userId) {
247
- // Get all active sessions for user
248
- const queryResult = await vibeServiceRequest('/v1/collections/vibe_app/tables/login_sessions/query', {
249
- method: 'POST',
250
- body: {
251
- filter: {
252
- operator: 'and',
253
- conditions: [
254
- { field: 'idp_user_id', operator: 'eq', value: userId },
255
- { field: 'status', operator: 'eq', value: 'active' },
256
- ],
257
- },
258
- },
259
- });
260
- if (!queryResult.ok) {
261
- return server_1.NextResponse.json({ error: queryResult.error }, { status: queryResult.status || 500 });
262
- }
263
- const sessions = queryResult.data?.data || queryResult.data?.documents || [];
264
- let revokedCount = 0;
265
- // Revoke each session
266
- for (const session of sessions) {
267
- const id = session.id || session.document_id;
268
- const result = await vibeServiceRequest(`/v1/collections/vibe_app/tables/login_sessions/${id}`, {
269
- method: 'PUT',
270
- body: {
271
- status: 'revoked',
272
- revoked_at: new Date().toISOString(),
273
- revoked_by: `admin:${adminCheck.userId}`,
274
- },
275
- });
276
- if (result.ok)
277
- revokedCount++;
278
- }
279
- return server_1.NextResponse.json({ success: true, revokedCount });
280
- }
281
- return server_1.NextResponse.json({ error: 'Invalid action' }, { status: 400 });
282
- },
283
- };
284
- }
1
+ "use strict";
2
+ /**
3
+ * Admin Sessions API Handler
4
+ *
5
+ * Provides admin-level access to login sessions using service account credentials.
6
+ * Used by SessionsTab component.
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.createSessionsHandler = createSessionsHandler;
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
+ /**
51
+ * Check if the current user has admin role
52
+ */
53
+ async function checkAdminRole(request) {
54
+ const session = await (0, auth_1.getSession)(request);
55
+ if (!session?.user) {
56
+ return {
57
+ isAdmin: false,
58
+ error: server_1.NextResponse.json({ success: false, error: 'Please sign in' }, { status: 401 }),
59
+ };
60
+ }
61
+ const userRoles = session.user?.roles || [];
62
+ const hasAdminRole = roles_1.ADMIN_ROLES.some(role => userRoles.includes(role));
63
+ if (!hasAdminRole) {
64
+ return {
65
+ isAdmin: false,
66
+ error: server_1.NextResponse.json({ success: false, error: 'Admin access required' }, { status: 403 }),
67
+ };
68
+ }
69
+ return { isAdmin: true, userId: session.user?.id };
70
+ }
71
+ /**
72
+ * Make a service account request to Vibe (admin mode)
73
+ */
74
+ async function vibeServiceRequest(endpoint, options) {
75
+ const idpUrl = process.env.NEXT_PUBLIC_IDP_URL || process.env.IDP_URL;
76
+ const clientId = process.env.VIBE_CLIENT_ID;
77
+ const signingKey = process.env.VIBE_HMAC_KEY;
78
+ if (!idpUrl || !clientId || !signingKey) {
79
+ return { ok: false, status: 500, data: null, error: 'Vibe not configured' };
80
+ }
81
+ const timestamp = Math.floor(Date.now() / 1000);
82
+ const stringToSign = `${timestamp}|${options.method}|${endpoint}`;
83
+ const crypto = await Promise.resolve().then(() => __importStar(require('crypto')));
84
+ const signature = crypto
85
+ .createHmac('sha256', Buffer.from(signingKey, 'base64'))
86
+ .update(stringToSign)
87
+ .digest('base64');
88
+ const proxyUrl = `${idpUrl}/api/vibe/proxy`;
89
+ // Get the client slug from startup config for multi-client admin support
90
+ const idpConfig = (0, startup_init_1.getStartupIDPConfig)();
91
+ const idpClientId = idpConfig?.clientSlug || idpConfig?.clientId;
92
+ try {
93
+ const res = await fetch(proxyUrl, {
94
+ method: 'POST',
95
+ headers: {
96
+ 'Content-Type': 'application/json',
97
+ 'X-Vibe-Client-Id': clientId,
98
+ 'X-Vibe-Timestamp': String(timestamp),
99
+ 'X-Vibe-Signature': signature,
100
+ ...(idpClientId && { 'X-Client-Id': idpClientId }),
101
+ },
102
+ body: JSON.stringify({
103
+ endpoint,
104
+ method: options.method,
105
+ data: options.body ?? null,
106
+ }),
107
+ cache: 'no-store',
108
+ });
109
+ if (res.status === 204) {
110
+ return { ok: true, status: 204, data: null };
111
+ }
112
+ if (!res.ok) {
113
+ const errorText = await res.text();
114
+ return { ok: false, status: res.status, data: null, error: errorText };
115
+ }
116
+ const body = await res.json();
117
+ return { ok: true, status: res.status, data: body };
118
+ }
119
+ catch (error) {
120
+ return { ok: false, status: 0, data: null, error: String(error) };
121
+ }
122
+ }
123
+ // Country code to flag emoji mapping
124
+ function getCountryFlag(countryCode) {
125
+ if (!countryCode || countryCode.length !== 2)
126
+ return '';
127
+ const codePoints = countryCode
128
+ .toUpperCase()
129
+ .split('')
130
+ .map(char => 127397 + char.charCodeAt(0));
131
+ return String.fromCodePoint(...codePoints);
132
+ }
133
+ /**
134
+ * GET /api/admin/sessions - List sessions
135
+ * POST /api/admin/sessions - Stats, revoke actions
136
+ */
137
+ function createSessionsHandler(config) {
138
+ return {
139
+ async GET(request) {
140
+ const adminCheck = await checkAdminRole(request);
141
+ if (adminCheck.error)
142
+ return adminCheck.error;
143
+ const { searchParams } = new URL(request.url);
144
+ const status = searchParams.get('status');
145
+ const email = searchParams.get('email');
146
+ // Build query for login_sessions table
147
+ const queryBody = {
148
+ page: 1,
149
+ pageSize: 100,
150
+ orderBy: 'created_at',
151
+ orderDirection: 'desc',
152
+ };
153
+ // Build filter conditions
154
+ const conditions = [];
155
+ if (status && status !== 'all') {
156
+ conditions.push({ field: 'status', operator: 'eq', value: status });
157
+ }
158
+ if (email) {
159
+ conditions.push({ field: 'email', operator: 'like', value: `%${email}%` });
160
+ }
161
+ if (conditions.length === 1) {
162
+ queryBody.filter = conditions[0];
163
+ }
164
+ else if (conditions.length > 1) {
165
+ queryBody.filter = { operator: 'and', conditions };
166
+ }
167
+ const result = await vibeServiceRequest('/v1/collections/vibe_app/tables/login_sessions/query', { method: 'POST', body: queryBody });
168
+ if (!result.ok) {
169
+ return server_1.NextResponse.json({ error: result.error }, { status: result.status || 500 });
170
+ }
171
+ // Extract sessions from response
172
+ const rawSessions = result.data?.data || result.data?.documents || [];
173
+ const sessions = rawSessions.map((s) => ({
174
+ id: s.id || s.document_id,
175
+ idp_user_id: s.idp_user_id || s.user_id,
176
+ email: s.email || '',
177
+ name: s.name || s.display_name || '',
178
+ status: s.status || 'active',
179
+ ip_address: s.ip_address || s.ip,
180
+ city: s.city,
181
+ region: s.region,
182
+ country_code: s.country_code || s.country,
183
+ device_type: s.device_type || s.device,
184
+ browser: s.browser,
185
+ os: s.os,
186
+ created_at: s.created_at,
187
+ last_activity: s.last_activity || s.updated_at,
188
+ revoked_at: s.revoked_at,
189
+ revoked_by: s.revoked_by,
190
+ country_flag: getCountryFlag(s.country_code || s.country || ''),
191
+ }));
192
+ return server_1.NextResponse.json({ sessions });
193
+ },
194
+ async POST(request) {
195
+ const adminCheck = await checkAdminRole(request);
196
+ if (adminCheck.error)
197
+ return adminCheck.error;
198
+ const body = await request.json();
199
+ const { action, sessionId, userId } = body;
200
+ if (action === 'stats') {
201
+ // Get all sessions for stats calculation
202
+ const result = await vibeServiceRequest('/v1/collections/vibe_app/tables/login_sessions/query', { method: 'POST', body: { page: 1, pageSize: 1000 } });
203
+ if (!result.ok) {
204
+ return server_1.NextResponse.json({ error: result.error }, { status: result.status || 500 });
205
+ }
206
+ const sessions = result.data?.data || result.data?.documents || [];
207
+ // Calculate stats
208
+ const now = new Date();
209
+ const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
210
+ const stats = {
211
+ totalActive: sessions.filter((s) => s.status === 'active').length,
212
+ totalRevoked: sessions.filter((s) => s.status === 'revoked').length,
213
+ uniqueUsers: new Set(sessions.map((s) => s.idp_user_id || s.user_id)).size,
214
+ recentLogins: sessions.filter((s) => new Date(s.created_at) > oneDayAgo).length,
215
+ byCountryWithFlags: {},
216
+ byDevice: {},
217
+ };
218
+ // Count by country
219
+ sessions.forEach((s) => {
220
+ const country = s.country_code || s.country || 'Unknown';
221
+ if (!stats.byCountryWithFlags[country]) {
222
+ stats.byCountryWithFlags[country] = { count: 0, flag: getCountryFlag(country) };
223
+ }
224
+ stats.byCountryWithFlags[country].count++;
225
+ const device = s.device_type || s.device || 'Unknown';
226
+ stats.byDevice[device] = (stats.byDevice[device] || 0) + 1;
227
+ });
228
+ return server_1.NextResponse.json({ stats });
229
+ }
230
+ if (action === 'revoke' && sessionId) {
231
+ // Revoke single session
232
+ const result = await vibeServiceRequest(`/v1/collections/vibe_app/tables/login_sessions/${sessionId}`, {
233
+ method: 'PUT',
234
+ body: {
235
+ status: 'revoked',
236
+ revoked_at: new Date().toISOString(),
237
+ revoked_by: `admin:${adminCheck.userId}`,
238
+ },
239
+ });
240
+ if (!result.ok) {
241
+ return server_1.NextResponse.json({ error: result.error }, { status: result.status || 500 });
242
+ }
243
+ return server_1.NextResponse.json({ success: true });
244
+ }
245
+ if (action === 'revoke_all' && userId) {
246
+ // Get all active sessions for user
247
+ const queryResult = await vibeServiceRequest('/v1/collections/vibe_app/tables/login_sessions/query', {
248
+ method: 'POST',
249
+ body: {
250
+ filter: {
251
+ operator: 'and',
252
+ conditions: [
253
+ { field: 'idp_user_id', operator: 'eq', value: userId },
254
+ { field: 'status', operator: 'eq', value: 'active' },
255
+ ],
256
+ },
257
+ },
258
+ });
259
+ if (!queryResult.ok) {
260
+ return server_1.NextResponse.json({ error: queryResult.error }, { status: queryResult.status || 500 });
261
+ }
262
+ const sessions = queryResult.data?.data || queryResult.data?.documents || [];
263
+ let revokedCount = 0;
264
+ // Revoke each session
265
+ for (const session of sessions) {
266
+ const id = session.id || session.document_id;
267
+ const result = await vibeServiceRequest(`/v1/collections/vibe_app/tables/login_sessions/${id}`, {
268
+ method: 'PUT',
269
+ body: {
270
+ status: 'revoked',
271
+ revoked_at: new Date().toISOString(),
272
+ revoked_by: `admin:${adminCheck.userId}`,
273
+ },
274
+ });
275
+ if (result.ok)
276
+ revokedCount++;
277
+ }
278
+ return server_1.NextResponse.json({ success: true, revokedCount });
279
+ }
280
+ return server_1.NextResponse.json({ error: 'Invalid action' }, { status: 400 });
281
+ },
282
+ };
283
+ }