@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.
- package/dist/api-handlers/account/change-password.js +110 -110
- package/dist/api-handlers/admin/analytics.d.ts +19 -19
- package/dist/api-handlers/admin/analytics.js +378 -378
- package/dist/api-handlers/admin/audit.d.ts +19 -19
- package/dist/api-handlers/admin/audit.js +213 -213
- package/dist/api-handlers/admin/index.d.ts +21 -21
- package/dist/api-handlers/admin/index.js +42 -42
- package/dist/api-handlers/admin/redis-sessions.d.ts +35 -35
- package/dist/api-handlers/admin/redis-sessions.js +203 -203
- package/dist/api-handlers/admin/sessions.d.ts +20 -20
- package/dist/api-handlers/admin/sessions.js +283 -283
- package/dist/api-handlers/admin/site-logs.d.ts +45 -45
- package/dist/api-handlers/admin/site-logs.js +317 -317
- package/dist/api-handlers/admin/stats.d.ts +20 -20
- package/dist/api-handlers/admin/stats.js +239 -239
- package/dist/api-handlers/admin/users.d.ts +19 -19
- package/dist/api-handlers/admin/users.js +221 -221
- package/dist/api-handlers/admin/vibe-data.d.ts +79 -79
- package/dist/api-handlers/admin/vibe-data.js +267 -267
- package/dist/api-handlers/auth/refresh.js +633 -633
- package/dist/api-handlers/auth/signout.js +186 -186
- package/dist/api-handlers/auth/verify-code.d.ts +43 -43
- package/dist/api-handlers/auth/verify-code.js +90 -90
- package/dist/api-handlers/session/viability.js +114 -114
- package/dist/api-handlers/test/force-expire.js +59 -59
- package/dist/auth/auth-decision.js +182 -182
- package/dist/auth/utils/token-utils.d.ts +83 -83
- package/dist/auth/utils/token-utils.js +218 -218
- package/dist/client/AuthContext.js +115 -115
- package/dist/client/better-auth-client.d.ts +1020 -1020
- package/dist/components/SessionSync.js +121 -121
- package/dist/components/account/MobileNavDrawer.js +64 -64
- package/dist/components/account/UserAvatarMenu.js +91 -91
- package/dist/components/admin/VibeAdminLayout.js +71 -71
- package/dist/hooks/useAuthSettings.js +93 -93
- package/dist/hooks/useAvailableProviders.d.ts +43 -43
- package/dist/hooks/useAvailableProviders.js +112 -112
- package/dist/lib/app-slug.d.ts +95 -95
- package/dist/lib/app-slug.js +172 -172
- package/dist/lib/test-aware-get-token.js +86 -86
- package/dist/lib/token-lifecycle.d.ts +78 -78
- package/dist/lib/token-lifecycle.js +360 -360
- package/dist/pages/admin-login/page.js +73 -73
- package/dist/pages/client-admin/ClientSiteAdminPage.js +179 -179
- package/dist/pages/login/page.js +202 -202
- package/dist/pages/showcase/ShowcasePage.js +142 -142
- package/dist/pages/test-env/EmergencyLogoutPage.js +99 -99
- package/dist/pages/test-env/JwtInspectPage.js +116 -116
- package/dist/pages/test-env/TestEnvPage.js +51 -51
- package/dist/pages/verify-code/page.js +412 -412
- package/dist/routes/auth/logout.d.ts +31 -31
- package/dist/routes/auth/logout.js +98 -98
- package/dist/routes/auth/session.js +157 -157
- package/dist/routes/auth/viability.js +190 -190
- package/package.json +6 -16
- package/dist/auth/auth-options.d.ts +0 -57
- package/dist/auth/auth-options.js +0 -213
- package/dist/auth/callbacks/index.d.ts +0 -6
- package/dist/auth/callbacks/index.js +0 -12
- package/dist/auth/callbacks/jwt.d.ts +0 -45
- package/dist/auth/callbacks/jwt.js +0 -305
- package/dist/auth/callbacks/session.d.ts +0 -60
- package/dist/auth/callbacks/session.js +0 -170
- package/dist/auth/callbacks/signin.d.ts +0 -23
- package/dist/auth/callbacks/signin.js +0 -44
- package/dist/auth/events/index.d.ts +0 -4
- package/dist/auth/events/index.js +0 -8
- package/dist/auth/events/signout.d.ts +0 -17
- package/dist/auth/events/signout.js +0 -32
- package/dist/auth/providers/credentials.d.ts +0 -32
- package/dist/auth/providers/credentials.js +0 -223
- package/dist/auth/providers/index.d.ts +0 -5
- package/dist/auth/providers/index.js +0 -21
- package/dist/auth/providers/oauth.d.ts +0 -26
- package/dist/auth/providers/oauth.js +0 -105
- package/dist/lib/nextauth-secret.d.ts +0 -10
- package/dist/lib/nextauth-secret.js +0 -100
- package/dist/pages/profile/profile-patch.d.ts +0 -1
- package/dist/pages/profile/profile-patch.js +0 -281
- package/dist/pages/security/security-patch.d.ts +0 -1
- package/dist/pages/security/security-patch.js +0 -302
|
@@ -1,283 +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 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
|
-
}
|
|
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
|
+
}
|
|
@@ -1,45 +1,45 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Admin Site Logs API Handlers
|
|
3
|
-
*
|
|
4
|
-
* Provides admin-level access to site activity logs.
|
|
5
|
-
* - GET /site-logs - Query logs from Vibe
|
|
6
|
-
* - POST /site-logs - Create test log entries via Redis queue
|
|
7
|
-
* - GET /site-logs/stats - Aggregated stats { total, unique_users, by_level, by_category }
|
|
8
|
-
* - POST /site-logs/drain - Manual drain trigger
|
|
9
|
-
* - GET /site-logs/queue - Redis queue status
|
|
10
|
-
*
|
|
11
|
-
* @version 1.0
|
|
12
|
-
* @requires Admin role (vibe_app_admin or payez_admin)
|
|
13
|
-
*/
|
|
14
|
-
import { NextRequest, NextResponse } from 'next/server';
|
|
15
|
-
export interface SiteLogsHandlerConfig {
|
|
16
|
-
vibeApiUrl?: string;
|
|
17
|
-
appSlug?: string;
|
|
18
|
-
vibeClientId?: string;
|
|
19
|
-
}
|
|
20
|
-
/**
|
|
21
|
-
* Create main site-logs handler (GET query, POST create test entries)
|
|
22
|
-
*/
|
|
23
|
-
export declare function createSiteLogsHandler(config: SiteLogsHandlerConfig): {
|
|
24
|
-
GET(request: NextRequest): Promise<NextResponse<any>>;
|
|
25
|
-
POST(request: NextRequest): Promise<NextResponse<unknown>>;
|
|
26
|
-
};
|
|
27
|
-
/**
|
|
28
|
-
* Create site-logs stats handler
|
|
29
|
-
* Returns: { total, unique_users, by_level, by_category }
|
|
30
|
-
*/
|
|
31
|
-
export declare function createSiteLogsStatsHandler(config: SiteLogsHandlerConfig): {
|
|
32
|
-
GET(request: NextRequest): Promise<NextResponse<any>>;
|
|
33
|
-
};
|
|
34
|
-
/**
|
|
35
|
-
* Create site-logs drain handler (manual trigger)
|
|
36
|
-
*/
|
|
37
|
-
export declare function createSiteLogsDrainHandler(config: SiteLogsHandlerConfig): {
|
|
38
|
-
POST(request: NextRequest): Promise<NextResponse<any>>;
|
|
39
|
-
};
|
|
40
|
-
/**
|
|
41
|
-
* Create site-logs queue status handler
|
|
42
|
-
*/
|
|
43
|
-
export declare function createSiteLogsQueueHandler(config: SiteLogsHandlerConfig): {
|
|
44
|
-
GET(request: NextRequest): Promise<NextResponse<unknown>>;
|
|
45
|
-
};
|
|
1
|
+
/**
|
|
2
|
+
* Admin Site Logs API Handlers
|
|
3
|
+
*
|
|
4
|
+
* Provides admin-level access to site activity logs.
|
|
5
|
+
* - GET /site-logs - Query logs from Vibe
|
|
6
|
+
* - POST /site-logs - Create test log entries via Redis queue
|
|
7
|
+
* - GET /site-logs/stats - Aggregated stats { total, unique_users, by_level, by_category }
|
|
8
|
+
* - POST /site-logs/drain - Manual drain trigger
|
|
9
|
+
* - GET /site-logs/queue - Redis queue status
|
|
10
|
+
*
|
|
11
|
+
* @version 1.0
|
|
12
|
+
* @requires Admin role (vibe_app_admin or payez_admin)
|
|
13
|
+
*/
|
|
14
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
15
|
+
export interface SiteLogsHandlerConfig {
|
|
16
|
+
vibeApiUrl?: string;
|
|
17
|
+
appSlug?: string;
|
|
18
|
+
vibeClientId?: string;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Create main site-logs handler (GET query, POST create test entries)
|
|
22
|
+
*/
|
|
23
|
+
export declare function createSiteLogsHandler(config: SiteLogsHandlerConfig): {
|
|
24
|
+
GET(request: NextRequest): Promise<NextResponse<any>>;
|
|
25
|
+
POST(request: NextRequest): Promise<NextResponse<unknown>>;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Create site-logs stats handler
|
|
29
|
+
* Returns: { total, unique_users, by_level, by_category }
|
|
30
|
+
*/
|
|
31
|
+
export declare function createSiteLogsStatsHandler(config: SiteLogsHandlerConfig): {
|
|
32
|
+
GET(request: NextRequest): Promise<NextResponse<any>>;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Create site-logs drain handler (manual trigger)
|
|
36
|
+
*/
|
|
37
|
+
export declare function createSiteLogsDrainHandler(config: SiteLogsHandlerConfig): {
|
|
38
|
+
POST(request: NextRequest): Promise<NextResponse<any>>;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Create site-logs queue status handler
|
|
42
|
+
*/
|
|
43
|
+
export declare function createSiteLogsQueueHandler(config: SiteLogsHandlerConfig): {
|
|
44
|
+
GET(request: NextRequest): Promise<NextResponse<unknown>>;
|
|
45
|
+
};
|