@payez/next-mvp 4.0.47 → 4.0.49

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.
@@ -128,14 +128,16 @@ function createStatsHandler(config) {
128
128
  if (adminCheck.error)
129
129
  return adminCheck.error;
130
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)
131
+ // Fetch from 4 sources in parallel
132
+ const [usersResult, tierDistributionResult, sessionCount, auditResult] = await Promise.allSettled([
133
+ // 1. Users count via HMAC proxy (Vibe collection query)
134
134
  vibeServiceRequest('/v1/collections/vibe_app/tables/users/query', {
135
135
  method: 'POST',
136
136
  body: { page: 1, pageSize: 500, orderBy: 'created_at', orderDirection: 'desc' },
137
137
  }),
138
- // 2. Active sessions from Redis
138
+ // 2. Tier distribution from analytics endpoint (uses purchases table)
139
+ vibeServiceRequest('/v1/analytics/tier-distribution?includeTrend=false', { method: 'GET' }),
140
+ // 3. Active sessions from Redis
139
141
  (async () => {
140
142
  const redis = (0, redis_1.getRedis)();
141
143
  const sessionPrefix = getSessionPrefix();
@@ -148,12 +150,11 @@ function createStatsHandler(config) {
148
150
  } while (cursor !== '0');
149
151
  return sessionKeys.length;
150
152
  })(),
151
- // 3. Recent audit activity via HMAC proxy
153
+ // 4. Recent audit activity via HMAC proxy
152
154
  vibeServiceRequest('/v1/audit?pageSize=10&sortDir=desc', { method: 'GET' }),
153
155
  ]);
154
156
  // Parse users — deduplicate by user_id
155
157
  let totalUsers = 0;
156
- let tierBreakdown = {};
157
158
  if (usersResult.status === 'fulfilled' && usersResult.value.ok && usersResult.value.data) {
158
159
  const data = usersResult.value.data;
159
160
  const rawUsers = data.data || data.documents || data.users || [];
@@ -166,17 +167,26 @@ function createStatsHandler(config) {
166
167
  userMap.set(uid, u);
167
168
  }
168
169
  }
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;
170
+ totalUsers = userMap.size;
171
+ }
172
+ // Parse tier distribution from analytics endpoint (uses purchases table)
173
+ let tierBreakdown = {};
174
+ if (tierDistributionResult.status === 'fulfilled' && tierDistributionResult.value.ok && tierDistributionResult.value.data) {
175
+ const data = tierDistributionResult.value.data;
176
+ // Handle response shape: { distribution: [{ tierKey, userCount }, ...] }
177
+ const distribution = data.distribution || data.data || data.tiers || [];
178
+ if (Array.isArray(distribution)) {
179
+ for (const item of distribution) {
180
+ const tierKey = item.tierKey || item.tier || item.name || 'free';
181
+ const count = item.userCount || item.count || item.users || 0;
182
+ tierBreakdown[tierKey] = (tierBreakdown[tierKey] || 0) + count;
177
183
  }
178
184
  }
179
185
  }
186
+ // Fallback: if no tier data from analytics, show all as free
187
+ if (Object.keys(tierBreakdown).length === 0) {
188
+ tierBreakdown = { free: totalUsers };
189
+ }
180
190
  // Parse active sessions count
181
191
  let activeSessions = 0;
182
192
  if (sessionCount.status === 'fulfilled') {
@@ -5,6 +5,16 @@
5
5
  * getAuthInstance(); use getSession(req) for the request-scoped session.
6
6
  */
7
7
  import 'server-only';
8
+ import { type SessionData } from '../lib/session-store';
9
+ export type IdpTokenResult = {
10
+ success: true;
11
+ accessToken: string;
12
+ sessionData: SessionData;
13
+ } | {
14
+ success: false;
15
+ error: 'NO_SESSION' | 'NO_TOKEN';
16
+ terminal: true;
17
+ };
8
18
  /**
9
19
  * Get the initialized Better Auth instance (singleton).
10
20
  */
@@ -54,6 +64,20 @@ export declare function getAuthInstance(): Promise<import("better-auth/types").A
54
64
  * Returns the session object or null if not authenticated.
55
65
  */
56
66
  export declare function getSession(request?: Request): Promise<any>;
67
+ /**
68
+ * Get normalized session data for the current request.
69
+ *
70
+ * This prefers the app's Redis session because it carries the canonical
71
+ * IDP token, roles, and tenant-specific user identity used by app routes.
72
+ */
73
+ export declare function getSessionData(request?: Request): Promise<SessionData | null>;
74
+ /**
75
+ * Get the current request's IDP access token without triggering a refresh.
76
+ *
77
+ * Use this for routes that only need the currently-issued bearer token and
78
+ * should fail closed instead of performing token lifecycle work.
79
+ */
80
+ export declare function getIdpToken(request?: Request): Promise<IdpTokenResult>;
57
81
  /**
58
82
  * Get the current session, throwing if not authenticated.
59
83
  * Use in API handlers that require auth.
@@ -5,48 +5,67 @@
5
5
  * All server-side auth flows go through the Better Auth instance returned by
6
6
  * getAuthInstance(); use getSession(req) for the request-scoped session.
7
7
  */
8
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
- if (k2 === undefined) k2 = k;
10
- var desc = Object.getOwnPropertyDescriptor(m, k);
11
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
- desc = { enumerable: true, get: function() { return m[k]; } };
13
- }
14
- Object.defineProperty(o, k2, desc);
15
- }) : (function(o, m, k, k2) {
16
- if (k2 === undefined) k2 = k;
17
- o[k2] = m[k];
18
- }));
19
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
20
- Object.defineProperty(o, "default", { enumerable: true, value: v });
21
- }) : function(o, v) {
22
- o["default"] = v;
23
- });
24
- var __importStar = (this && this.__importStar) || (function () {
25
- var ownKeys = function(o) {
26
- ownKeys = Object.getOwnPropertyNames || function (o) {
27
- var ar = [];
28
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
- return ar;
30
- };
31
- return ownKeys(o);
32
- };
33
- return function (mod) {
34
- if (mod && mod.__esModule) return mod;
35
- var result = {};
36
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
- __setModuleDefault(result, mod);
38
- return result;
39
- };
40
- })();
41
8
  Object.defineProperty(exports, "__esModule", { value: true });
42
9
  exports.getAuthInstance = getAuthInstance;
43
10
  exports.getSession = getSession;
11
+ exports.getSessionData = getSessionData;
12
+ exports.getIdpToken = getIdpToken;
44
13
  exports.requireSession = requireSession;
45
14
  require("server-only");
46
15
  const better_auth_1 = require("../auth/better-auth");
47
16
  const idp_client_config_1 = require("../lib/idp-client-config");
17
+ const session_store_1 = require("../lib/session-store");
48
18
  let authInstance = null;
49
19
  let authInitPromise = null;
20
+ function buildSessionDataFromAuthSession(session) {
21
+ const user = session?.user;
22
+ if (!user?.id && !user?.email) {
23
+ return null;
24
+ }
25
+ const expiresAt = session?.session?.expiresAt
26
+ ? new Date(session.session.expiresAt).getTime()
27
+ : Date.now() + 24 * 60 * 60 * 1000;
28
+ return {
29
+ userId: user.userId || user.id || '',
30
+ email: user.email || '',
31
+ name: user.name || undefined,
32
+ roles: Array.isArray(user.roles) ? user.roles : [],
33
+ idpAccessToken: user.idpAccessToken,
34
+ idpRefreshToken: user.idpRefreshToken,
35
+ idpAccessTokenExpires: user.idpAccessTokenExpires || expiresAt,
36
+ mfaVerified: user.mfaVerified ?? user.twoFactorSessionVerified ?? false,
37
+ oauthProvider: user.oauthProvider,
38
+ idpClientId: user.idpClientId,
39
+ merchantId: user.merchantId,
40
+ };
41
+ }
42
+ function attachSessionData(session, sessionData, sessionToken) {
43
+ if (!sessionData) {
44
+ return session;
45
+ }
46
+ const enrichedSessionData = {
47
+ ...sessionData,
48
+ ...(sessionToken ? { sessionToken } : {}),
49
+ };
50
+ session.sessionData = enrichedSessionData;
51
+ if (session?.user) {
52
+ const user = session.user;
53
+ user.userId = enrichedSessionData.userId || user.userId;
54
+ user.email = enrichedSessionData.email || user.email;
55
+ user.name = enrichedSessionData.name || user.name;
56
+ user.roles = enrichedSessionData.roles || user.roles || [];
57
+ user.idpAccessToken = enrichedSessionData.idpAccessToken;
58
+ user.idpRefreshToken = enrichedSessionData.idpRefreshToken;
59
+ user.idpAccessTokenExpires = enrichedSessionData.idpAccessTokenExpires;
60
+ user.mfaVerified = enrichedSessionData.mfaVerified;
61
+ user.twoFactorSessionVerified =
62
+ enrichedSessionData.mfaVerified ?? user.twoFactorSessionVerified;
63
+ user.oauthProvider = enrichedSessionData.oauthProvider || user.oauthProvider;
64
+ user.idpClientId = enrichedSessionData.idpClientId || user.idpClientId;
65
+ user.merchantId = enrichedSessionData.merchantId || user.merchantId;
66
+ }
67
+ return session;
68
+ }
50
69
  /**
51
70
  * Get the initialized Better Auth instance (singleton).
52
71
  */
@@ -75,31 +94,66 @@ async function getSession(request) {
75
94
  const session = await auth.api.getSession({ headers: request.headers });
76
95
  if (!session?.session?.token || !session?.user)
77
96
  return session;
78
- // Enrich with IDP tokens from Redis (stored by post-login hook)
97
+ const sessionToken = session.session.token;
98
+ let sessionData = null;
99
+ // Prefer the app's normalized Redis session. Fall back to Better Auth's
100
+ // secondary storage record, then finally to whatever Better Auth already
101
+ // put on the request session object.
79
102
  try {
80
- const { getRedis } = await Promise.resolve().then(() => __importStar(require('../lib/redis')));
81
- const { getAppSlug } = await Promise.resolve().then(() => __importStar(require('../lib/app-slug')));
82
- const baKey = `ba:${getAppSlug()}:${session.session.token}`;
83
- const baRaw = await getRedis().get(baKey);
84
- if (baRaw) {
85
- const baData = JSON.parse(baRaw);
86
- if (baData.idpTokens) {
87
- const u = session.user;
88
- u.roles = baData.idpTokens.roles || [];
89
- u.userId = baData.idpTokens.userId;
90
- u.idpAccessToken = baData.idpTokens.idpAccessToken;
91
- u.idpRefreshToken = baData.idpTokens.idpRefreshToken;
92
- u.idpAccessTokenExpires = baData.idpTokens.idpAccessTokenExpires;
93
- }
103
+ sessionData = await (0, session_store_1.getSession)(sessionToken);
104
+ if (!sessionData) {
105
+ sessionData = await (0, session_store_1.getBetterAuthSession)(sessionToken);
94
106
  }
95
107
  }
96
108
  catch { /* Redis unavailable */ }
97
- return session;
109
+ if (!sessionData) {
110
+ sessionData = buildSessionDataFromAuthSession(session);
111
+ }
112
+ return attachSessionData(session, sessionData, sessionToken);
98
113
  }
99
114
  catch {
100
115
  return null;
101
116
  }
102
117
  }
118
+ /**
119
+ * Get normalized session data for the current request.
120
+ *
121
+ * This prefers the app's Redis session because it carries the canonical
122
+ * IDP token, roles, and tenant-specific user identity used by app routes.
123
+ */
124
+ async function getSessionData(request) {
125
+ const session = await getSession(request);
126
+ const sessionData = session?.sessionData ||
127
+ buildSessionDataFromAuthSession(session);
128
+ if (!sessionData) {
129
+ return null;
130
+ }
131
+ const sessionToken = session?.session?.token;
132
+ return sessionToken
133
+ ? { ...sessionData, sessionToken }
134
+ : sessionData;
135
+ }
136
+ /**
137
+ * Get the current request's IDP access token without triggering a refresh.
138
+ *
139
+ * Use this for routes that only need the currently-issued bearer token and
140
+ * should fail closed instead of performing token lifecycle work.
141
+ */
142
+ async function getIdpToken(request) {
143
+ const sessionData = await getSessionData(request);
144
+ if (!sessionData) {
145
+ return { success: false, error: 'NO_SESSION', terminal: true };
146
+ }
147
+ const accessToken = sessionData.idpAccessToken || sessionData.accessToken;
148
+ if (!accessToken) {
149
+ return { success: false, error: 'NO_TOKEN', terminal: true };
150
+ }
151
+ return {
152
+ success: true,
153
+ accessToken,
154
+ sessionData,
155
+ };
156
+ }
103
157
  /**
104
158
  * Get the current session, throwing if not authenticated.
105
159
  * Use in API handlers that require auth.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payez/next-mvp",
3
- "version": "4.0.47",
3
+ "version": "4.0.49",
4
4
  "sideEffects": false,
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,238 +1,249 @@
1
- /**
2
- * Admin Stats API Handler
3
- *
4
- * Aggregates dashboard statistics from users, Redis sessions, and audit logs.
5
- * Uses service account HMAC auth for Vibe API requests.
6
- *
7
- * @version 1.0
8
- * @requires Admin role (vibe_app_admin or payez_admin)
9
- */
10
-
11
- import { NextRequest, NextResponse } from 'next/server';
12
- import { getSession } from '../../server/auth';
13
- import { getStartupIDPConfig } from '../../lib/startup-init';
14
- import { getRedis } from '../../lib/redis';
15
- import { ADMIN_ROLES } from '../../lib/roles';
16
-
17
- interface VibeRequestOptions {
18
- method: 'GET' | 'POST' | 'PUT' | 'DELETE';
19
- body?: unknown;
20
- }
21
-
22
- async function checkAdminRole(request: NextRequest): Promise<{ isAdmin: boolean; error?: NextResponse }> {
23
- const session = await getSession(request) as any;
24
-
25
- if (!session?.user) {
26
- return {
27
- isAdmin: false,
28
- error: NextResponse.json({ success: false, error: 'Please sign in' }, { status: 401 }),
29
- };
30
- }
31
-
32
- const userRoles = (session.user?.roles as string[]) || [];
33
- const hasAdminRole = ADMIN_ROLES.some(role => userRoles.includes(role));
34
-
35
- if (!hasAdminRole) {
36
- return {
37
- isAdmin: false,
38
- error: NextResponse.json({ success: false, error: 'Admin access required' }, { status: 403 }),
39
- };
40
- }
41
-
42
- return { isAdmin: true };
43
- }
44
-
45
- async function vibeServiceRequest<T = unknown>(
46
- endpoint: string,
47
- options: VibeRequestOptions
48
- ): Promise<{ ok: boolean; status: number; data: T | null; error?: string }> {
49
- const idpUrl = process.env.NEXT_PUBLIC_IDP_URL || process.env.IDP_URL;
50
- const clientId = process.env.VIBE_CLIENT_ID;
51
- const signingKey = process.env.VIBE_HMAC_KEY;
52
-
53
- if (!idpUrl || !clientId || !signingKey) {
54
- return { ok: false, status: 500, data: null, error: 'Vibe not configured' };
55
- }
56
-
57
- const timestamp = Math.floor(Date.now() / 1000);
58
- const stringToSign = `${timestamp}|${options.method}|${endpoint}`;
59
-
60
- const crypto = await import('crypto');
61
- const signature = crypto
62
- .createHmac('sha256', Buffer.from(signingKey, 'base64'))
63
- .update(stringToSign)
64
- .digest('base64');
65
-
66
- const proxyUrl = `${idpUrl}/api/vibe/proxy`;
67
-
68
- const idpConfig = getStartupIDPConfig();
69
- const idpClientId = idpConfig?.clientSlug || idpConfig?.clientId;
70
-
71
- try {
72
- const res = await fetch(proxyUrl, {
73
- method: 'POST',
74
- headers: {
75
- 'Content-Type': 'application/json',
76
- 'X-Vibe-Client-Id': clientId,
77
- 'X-Vibe-Timestamp': String(timestamp),
78
- 'X-Vibe-Signature': signature,
79
- ...(idpClientId && { 'X-Client-Id': idpClientId }),
80
- },
81
- body: JSON.stringify({
82
- endpoint,
83
- method: options.method,
84
- data: options.body ?? null,
85
- }),
86
- cache: 'no-store',
87
- });
88
-
89
- if (res.status === 204) return { ok: true, status: 204, data: null };
90
- if (!res.ok) {
91
- const errorText = await res.text();
92
- return { ok: false, status: res.status, data: null, error: errorText };
93
- }
94
-
95
- const body = await res.json();
96
- return { ok: true, status: res.status, data: body };
97
- } catch (error) {
98
- return { ok: false, status: 0, data: null, error: String(error) };
99
- }
100
- }
101
-
102
- export interface AdminStatsHandlerConfig {
103
- appSlug?: string;
104
- }
105
-
106
- /**
107
- * GET /api/admin/stats - Dashboard statistics
108
- * Aggregates users + tier breakdown, active Redis sessions, and recent audit activity.
109
- */
110
- export function createStatsHandler(config: AdminStatsHandlerConfig) {
111
- const getSessionPrefix = () => {
112
- const appSlug = config.appSlug || process.env.APP_SLUG || process.env.CLIENT_ID || 'app';
113
- return `${appSlug}:sess:`;
114
- };
115
-
116
- return {
117
- async GET(_request: NextRequest) {
118
- const adminCheck = await checkAdminRole(_request);
119
- if (adminCheck.error) return adminCheck.error;
120
-
121
- try {
122
- // Fetch from 3 sources in parallel
123
- const [usersResult, sessionCount, auditResult] = await Promise.allSettled([
124
- // 1. Users + tier breakdown via HMAC proxy (Vibe collection query)
125
- vibeServiceRequest<any>('/v1/collections/vibe_app/tables/users/query', {
126
- method: 'POST',
127
- body: { page: 1, pageSize: 500, orderBy: 'created_at', orderDirection: 'desc' },
128
- }),
129
-
130
- // 2. Active sessions from Redis
131
- (async () => {
132
- const redis = getRedis();
133
- const sessionPrefix = getSessionPrefix();
134
- const sessionKeys: string[] = [];
135
- let cursor = '0';
136
- do {
137
- const [newCursor, keys] = await redis.scan(cursor, 'MATCH', `${sessionPrefix}*`, 'COUNT', 100);
138
- cursor = newCursor;
139
- sessionKeys.push(...keys.filter((k: string) => !k.includes(':ver:')));
140
- } while (cursor !== '0');
141
- return sessionKeys.length;
142
- })(),
143
-
144
- // 3. Recent audit activity via HMAC proxy
145
- vibeServiceRequest<any>('/v1/audit?pageSize=10&sortDir=desc', { method: 'GET' }),
146
- ]);
147
-
148
- // Parse users deduplicate by user_id
149
- let totalUsers = 0;
150
- let tierBreakdown: Record<string, number> = {};
151
- if (usersResult.status === 'fulfilled' && usersResult.value.ok && usersResult.value.data) {
152
- const data = usersResult.value.data;
153
- const rawUsers = data.data || data.documents || data.users || [];
154
-
155
- // Deduplicate by user_id (keeps latest document_id)
156
- const userMap = new Map();
157
- for (const u of rawUsers) {
158
- const uid = u.user_id || u.id || u.document_id;
159
- const existing = userMap.get(uid);
160
- if (!existing || (u.document_id || '') > (existing.document_id || '')) {
161
- userMap.set(uid, u);
162
- }
163
- }
164
- const uniqueUsers = Array.from(userMap.values());
165
- totalUsers = uniqueUsers.length;
166
-
167
- // Build tier breakdown from deduplicated users (unless API provides one)
168
- tierBreakdown = data.tierBreakdown || data.tiers || {};
169
- if (Object.keys(tierBreakdown).length === 0) {
170
- for (const user of uniqueUsers) {
171
- const tier = user.tier || 'free';
172
- tierBreakdown[tier] = (tierBreakdown[tier] || 0) + 1;
173
- }
174
- }
175
- }
176
-
177
- // Parse active sessions count
178
- let activeSessions = 0;
179
- if (sessionCount.status === 'fulfilled') {
180
- activeSessions = sessionCount.value;
181
- }
182
-
183
- // Parse audit events for recent activity
184
- let recentActivity: any[] = [];
185
- if (auditResult.status === 'fulfilled' && auditResult.value.ok && auditResult.value.data) {
186
- const data = auditResult.value.data;
187
-
188
- // Handle multiple possible response shapes
189
- let events: any[] = [];
190
- if (Array.isArray(data)) {
191
- events = data;
192
- } else if (Array.isArray(data.data)) {
193
- events = data.data;
194
- } else if (Array.isArray(data.entries)) {
195
- events = data.entries;
196
- } else if (Array.isArray(data.items)) {
197
- events = data.items;
198
- } else if (Array.isArray(data.documents)) {
199
- events = data.documents;
200
- } else if (data.success && Array.isArray(data.results)) {
201
- events = data.results;
202
- }
203
-
204
- recentActivity = events.slice(0, 5).map((e: any) => ({
205
- id: e.audit_log_id || e.id || e.document_id,
206
- type: e.category || e.type || 'admin',
207
- action: e.action || e.event || e.message || 'Unknown action',
208
- actor: e.admin_email || e.actor || e.user || e.actor_email || 'System',
209
- target: e.target_type ? `${e.target_type}:${e.target_id}` : (e.target || e.target_user),
210
- details: e.description || e.details,
211
- timestamp: e.created_at || e.timestamp || e.date,
212
- success: e.is_success ?? e.success ?? true,
213
- }));
214
- }
215
-
216
- // Calculate tier percentages
217
- const tiers = Object.entries(tierBreakdown).map(([name, count]) => ({
218
- name,
219
- count: count as number,
220
- pct: totalUsers > 0 ? Math.round(((count as number) / totalUsers) * 100) : 0,
221
- }));
222
-
223
- return NextResponse.json({
224
- totalUsers,
225
- activeSessions,
226
- tiers,
227
- recentActivity,
228
- });
229
- } catch (error: any) {
230
- console.error('[admin/stats] Error:', error);
231
- return NextResponse.json(
232
- { error: error.message || 'Internal error' },
233
- { status: 500 }
234
- );
235
- }
236
- },
237
- };
238
- }
1
+ /**
2
+ * Admin Stats API Handler
3
+ *
4
+ * Aggregates dashboard statistics from users, Redis sessions, and audit logs.
5
+ * Uses service account HMAC auth for Vibe API requests.
6
+ *
7
+ * @version 1.0
8
+ * @requires Admin role (vibe_app_admin or payez_admin)
9
+ */
10
+
11
+ import { NextRequest, NextResponse } from 'next/server';
12
+ import { getSession } from '../../server/auth';
13
+ import { getStartupIDPConfig } from '../../lib/startup-init';
14
+ import { getRedis } from '../../lib/redis';
15
+ import { ADMIN_ROLES } from '../../lib/roles';
16
+
17
+ interface VibeRequestOptions {
18
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
19
+ body?: unknown;
20
+ }
21
+
22
+ async function checkAdminRole(request: NextRequest): Promise<{ isAdmin: boolean; error?: NextResponse }> {
23
+ const session = await getSession(request) as any;
24
+
25
+ if (!session?.user) {
26
+ return {
27
+ isAdmin: false,
28
+ error: NextResponse.json({ success: false, error: 'Please sign in' }, { status: 401 }),
29
+ };
30
+ }
31
+
32
+ const userRoles = (session.user?.roles as string[]) || [];
33
+ const hasAdminRole = ADMIN_ROLES.some(role => userRoles.includes(role));
34
+
35
+ if (!hasAdminRole) {
36
+ return {
37
+ isAdmin: false,
38
+ error: NextResponse.json({ success: false, error: 'Admin access required' }, { status: 403 }),
39
+ };
40
+ }
41
+
42
+ return { isAdmin: true };
43
+ }
44
+
45
+ async function vibeServiceRequest<T = unknown>(
46
+ endpoint: string,
47
+ options: VibeRequestOptions
48
+ ): Promise<{ ok: boolean; status: number; data: T | null; error?: string }> {
49
+ const idpUrl = process.env.NEXT_PUBLIC_IDP_URL || process.env.IDP_URL;
50
+ const clientId = process.env.VIBE_CLIENT_ID;
51
+ const signingKey = process.env.VIBE_HMAC_KEY;
52
+
53
+ if (!idpUrl || !clientId || !signingKey) {
54
+ return { ok: false, status: 500, data: null, error: 'Vibe not configured' };
55
+ }
56
+
57
+ const timestamp = Math.floor(Date.now() / 1000);
58
+ const stringToSign = `${timestamp}|${options.method}|${endpoint}`;
59
+
60
+ const crypto = await import('crypto');
61
+ const signature = crypto
62
+ .createHmac('sha256', Buffer.from(signingKey, 'base64'))
63
+ .update(stringToSign)
64
+ .digest('base64');
65
+
66
+ const proxyUrl = `${idpUrl}/api/vibe/proxy`;
67
+
68
+ const idpConfig = getStartupIDPConfig();
69
+ const idpClientId = idpConfig?.clientSlug || idpConfig?.clientId;
70
+
71
+ try {
72
+ const res = await fetch(proxyUrl, {
73
+ method: 'POST',
74
+ headers: {
75
+ 'Content-Type': 'application/json',
76
+ 'X-Vibe-Client-Id': clientId,
77
+ 'X-Vibe-Timestamp': String(timestamp),
78
+ 'X-Vibe-Signature': signature,
79
+ ...(idpClientId && { 'X-Client-Id': idpClientId }),
80
+ },
81
+ body: JSON.stringify({
82
+ endpoint,
83
+ method: options.method,
84
+ data: options.body ?? null,
85
+ }),
86
+ cache: 'no-store',
87
+ });
88
+
89
+ if (res.status === 204) return { ok: true, status: 204, data: null };
90
+ if (!res.ok) {
91
+ const errorText = await res.text();
92
+ return { ok: false, status: res.status, data: null, error: errorText };
93
+ }
94
+
95
+ const body = await res.json();
96
+ return { ok: true, status: res.status, data: body };
97
+ } catch (error) {
98
+ return { ok: false, status: 0, data: null, error: String(error) };
99
+ }
100
+ }
101
+
102
+ export interface AdminStatsHandlerConfig {
103
+ appSlug?: string;
104
+ }
105
+
106
+ /**
107
+ * GET /api/admin/stats - Dashboard statistics
108
+ * Aggregates users + tier breakdown, active Redis sessions, and recent audit activity.
109
+ */
110
+ export function createStatsHandler(config: AdminStatsHandlerConfig) {
111
+ const getSessionPrefix = () => {
112
+ const appSlug = config.appSlug || process.env.APP_SLUG || process.env.CLIENT_ID || 'app';
113
+ return `${appSlug}:sess:`;
114
+ };
115
+
116
+ return {
117
+ async GET(_request: NextRequest) {
118
+ const adminCheck = await checkAdminRole(_request);
119
+ if (adminCheck.error) return adminCheck.error;
120
+
121
+ try {
122
+ // Fetch from 4 sources in parallel
123
+ const [usersResult, tierDistributionResult, sessionCount, auditResult] = await Promise.allSettled([
124
+ // 1. Users count via HMAC proxy (Vibe collection query)
125
+ vibeServiceRequest<any>('/v1/collections/vibe_app/tables/users/query', {
126
+ method: 'POST',
127
+ body: { page: 1, pageSize: 500, orderBy: 'created_at', orderDirection: 'desc' },
128
+ }),
129
+
130
+ // 2. Tier distribution from analytics endpoint (uses purchases table)
131
+ vibeServiceRequest<any>('/v1/analytics/tier-distribution?includeTrend=false', { method: 'GET' }),
132
+
133
+ // 3. Active sessions from Redis
134
+ (async () => {
135
+ const redis = getRedis();
136
+ const sessionPrefix = getSessionPrefix();
137
+ const sessionKeys: string[] = [];
138
+ let cursor = '0';
139
+ do {
140
+ const [newCursor, keys] = await redis.scan(cursor, 'MATCH', `${sessionPrefix}*`, 'COUNT', 100);
141
+ cursor = newCursor;
142
+ sessionKeys.push(...keys.filter((k: string) => !k.includes(':ver:')));
143
+ } while (cursor !== '0');
144
+ return sessionKeys.length;
145
+ })(),
146
+
147
+ // 4. Recent audit activity via HMAC proxy
148
+ vibeServiceRequest<any>('/v1/audit?pageSize=10&sortDir=desc', { method: 'GET' }),
149
+ ]);
150
+
151
+ // Parse users deduplicate by user_id
152
+ let totalUsers = 0;
153
+ if (usersResult.status === 'fulfilled' && usersResult.value.ok && usersResult.value.data) {
154
+ const data = usersResult.value.data;
155
+ const rawUsers = data.data || data.documents || data.users || [];
156
+
157
+ // Deduplicate by user_id (keeps latest document_id)
158
+ const userMap = new Map();
159
+ for (const u of rawUsers) {
160
+ const uid = u.user_id || u.id || u.document_id;
161
+ const existing = userMap.get(uid);
162
+ if (!existing || (u.document_id || '') > (existing.document_id || '')) {
163
+ userMap.set(uid, u);
164
+ }
165
+ }
166
+ totalUsers = userMap.size;
167
+ }
168
+
169
+ // Parse tier distribution from analytics endpoint (uses purchases table)
170
+ let tierBreakdown: Record<string, number> = {};
171
+ if (tierDistributionResult.status === 'fulfilled' && tierDistributionResult.value.ok && tierDistributionResult.value.data) {
172
+ const data = tierDistributionResult.value.data;
173
+ // Handle response shape: { distribution: [{ tierKey, userCount }, ...] }
174
+ const distribution = data.distribution || data.data || data.tiers || [];
175
+ if (Array.isArray(distribution)) {
176
+ for (const item of distribution) {
177
+ const tierKey = item.tierKey || item.tier || item.name || 'free';
178
+ const count = item.userCount || item.count || item.users || 0;
179
+ tierBreakdown[tierKey] = (tierBreakdown[tierKey] || 0) + count;
180
+ }
181
+ }
182
+ }
183
+ // Fallback: if no tier data from analytics, show all as free
184
+ if (Object.keys(tierBreakdown).length === 0) {
185
+ tierBreakdown = { free: totalUsers };
186
+ }
187
+
188
+ // Parse active sessions count
189
+ let activeSessions = 0;
190
+ if (sessionCount.status === 'fulfilled') {
191
+ activeSessions = sessionCount.value;
192
+ }
193
+
194
+ // Parse audit events for recent activity
195
+ let recentActivity: any[] = [];
196
+ if (auditResult.status === 'fulfilled' && auditResult.value.ok && auditResult.value.data) {
197
+ const data = auditResult.value.data;
198
+
199
+ // Handle multiple possible response shapes
200
+ let events: any[] = [];
201
+ if (Array.isArray(data)) {
202
+ events = data;
203
+ } else if (Array.isArray(data.data)) {
204
+ events = data.data;
205
+ } else if (Array.isArray(data.entries)) {
206
+ events = data.entries;
207
+ } else if (Array.isArray(data.items)) {
208
+ events = data.items;
209
+ } else if (Array.isArray(data.documents)) {
210
+ events = data.documents;
211
+ } else if (data.success && Array.isArray(data.results)) {
212
+ events = data.results;
213
+ }
214
+
215
+ recentActivity = events.slice(0, 5).map((e: any) => ({
216
+ id: e.audit_log_id || e.id || e.document_id,
217
+ type: e.category || e.type || 'admin',
218
+ action: e.action || e.event || e.message || 'Unknown action',
219
+ actor: e.admin_email || e.actor || e.user || e.actor_email || 'System',
220
+ target: e.target_type ? `${e.target_type}:${e.target_id}` : (e.target || e.target_user),
221
+ details: e.description || e.details,
222
+ timestamp: e.created_at || e.timestamp || e.date,
223
+ success: e.is_success ?? e.success ?? true,
224
+ }));
225
+ }
226
+
227
+ // Calculate tier percentages
228
+ const tiers = Object.entries(tierBreakdown).map(([name, count]) => ({
229
+ name,
230
+ count: count as number,
231
+ pct: totalUsers > 0 ? Math.round(((count as number) / totalUsers) * 100) : 0,
232
+ }));
233
+
234
+ return NextResponse.json({
235
+ totalUsers,
236
+ activeSessions,
237
+ tiers,
238
+ recentActivity,
239
+ });
240
+ } catch (error: any) {
241
+ console.error('[admin/stats] Error:', error);
242
+ return NextResponse.json(
243
+ { error: error.message || 'Internal error' },
244
+ { status: 500 }
245
+ );
246
+ }
247
+ },
248
+ };
249
+ }
@@ -8,10 +8,76 @@
8
8
  import 'server-only';
9
9
  import { createBetterAuthInstance } from '../auth/better-auth';
10
10
  import { getIDPClientConfig } from '../lib/idp-client-config';
11
+ import {
12
+ getSession as getRedisSession,
13
+ getBetterAuthSession as getBetterAuthRedisSession,
14
+ type SessionData,
15
+ } from '../lib/session-store';
11
16
 
12
17
  let authInstance: ReturnType<typeof createBetterAuthInstance> | null = null;
13
18
  let authInitPromise: Promise<ReturnType<typeof createBetterAuthInstance>> | null = null;
14
19
 
20
+ export type IdpTokenResult =
21
+ | { success: true; accessToken: string; sessionData: SessionData }
22
+ | { success: false; error: 'NO_SESSION' | 'NO_TOKEN'; terminal: true };
23
+
24
+ function buildSessionDataFromAuthSession(session: any): SessionData | null {
25
+ const user = session?.user;
26
+ if (!user?.id && !user?.email) {
27
+ return null;
28
+ }
29
+
30
+ const expiresAt = session?.session?.expiresAt
31
+ ? new Date(session.session.expiresAt).getTime()
32
+ : Date.now() + 24 * 60 * 60 * 1000;
33
+
34
+ return {
35
+ userId: user.userId || user.id || '',
36
+ email: user.email || '',
37
+ name: user.name || undefined,
38
+ roles: Array.isArray(user.roles) ? user.roles : [],
39
+ idpAccessToken: user.idpAccessToken,
40
+ idpRefreshToken: user.idpRefreshToken,
41
+ idpAccessTokenExpires: user.idpAccessTokenExpires || expiresAt,
42
+ mfaVerified: user.mfaVerified ?? user.twoFactorSessionVerified ?? false,
43
+ oauthProvider: user.oauthProvider,
44
+ idpClientId: user.idpClientId,
45
+ merchantId: user.merchantId,
46
+ };
47
+ }
48
+
49
+ function attachSessionData(session: any, sessionData: SessionData | null, sessionToken?: string) {
50
+ if (!sessionData) {
51
+ return session;
52
+ }
53
+
54
+ const enrichedSessionData = {
55
+ ...sessionData,
56
+ ...(sessionToken ? { sessionToken } : {}),
57
+ };
58
+
59
+ (session as any).sessionData = enrichedSessionData;
60
+
61
+ if (session?.user) {
62
+ const user = session.user as any;
63
+ user.userId = enrichedSessionData.userId || user.userId;
64
+ user.email = enrichedSessionData.email || user.email;
65
+ user.name = enrichedSessionData.name || user.name;
66
+ user.roles = enrichedSessionData.roles || user.roles || [];
67
+ user.idpAccessToken = enrichedSessionData.idpAccessToken;
68
+ user.idpRefreshToken = enrichedSessionData.idpRefreshToken;
69
+ user.idpAccessTokenExpires = enrichedSessionData.idpAccessTokenExpires;
70
+ user.mfaVerified = enrichedSessionData.mfaVerified;
71
+ user.twoFactorSessionVerified =
72
+ enrichedSessionData.mfaVerified ?? user.twoFactorSessionVerified;
73
+ user.oauthProvider = enrichedSessionData.oauthProvider || user.oauthProvider;
74
+ user.idpClientId = enrichedSessionData.idpClientId || user.idpClientId;
75
+ user.merchantId = enrichedSessionData.merchantId || user.merchantId;
76
+ }
77
+
78
+ return session;
79
+ }
80
+
15
81
  /**
16
82
  * Get the initialized Better Auth instance (singleton).
17
83
  */
@@ -40,31 +106,75 @@ export async function getSession(request?: Request): Promise<any> {
40
106
  const session = await auth.api.getSession({ headers: request.headers });
41
107
  if (!session?.session?.token || !session?.user) return session;
42
108
 
43
- // Enrich with IDP tokens from Redis (stored by post-login hook)
109
+ const sessionToken = session.session.token as string;
110
+ let sessionData: SessionData | null = null;
111
+
112
+ // Prefer the app's normalized Redis session. Fall back to Better Auth's
113
+ // secondary storage record, then finally to whatever Better Auth already
114
+ // put on the request session object.
44
115
  try {
45
- const { getRedis } = await import('../lib/redis');
46
- const { getAppSlug } = await import('../lib/app-slug');
47
- const baKey = `ba:${getAppSlug()}:${session.session.token}`;
48
- const baRaw = await getRedis().get(baKey);
49
- if (baRaw) {
50
- const baData = JSON.parse(baRaw);
51
- if (baData.idpTokens) {
52
- const u = session.user as any;
53
- u.roles = baData.idpTokens.roles || [];
54
- u.userId = baData.idpTokens.userId;
55
- u.idpAccessToken = baData.idpTokens.idpAccessToken;
56
- u.idpRefreshToken = baData.idpTokens.idpRefreshToken;
57
- u.idpAccessTokenExpires = baData.idpTokens.idpAccessTokenExpires;
58
- }
116
+ sessionData = await getRedisSession(sessionToken);
117
+ if (!sessionData) {
118
+ sessionData = await getBetterAuthRedisSession(sessionToken);
59
119
  }
60
120
  } catch { /* Redis unavailable */ }
61
121
 
62
- return session;
122
+ if (!sessionData) {
123
+ sessionData = buildSessionDataFromAuthSession(session);
124
+ }
125
+
126
+ return attachSessionData(session, sessionData, sessionToken);
63
127
  } catch {
64
128
  return null;
65
129
  }
66
130
  }
67
131
 
132
+ /**
133
+ * Get normalized session data for the current request.
134
+ *
135
+ * This prefers the app's Redis session because it carries the canonical
136
+ * IDP token, roles, and tenant-specific user identity used by app routes.
137
+ */
138
+ export async function getSessionData(request?: Request): Promise<SessionData | null> {
139
+ const session = await getSession(request);
140
+ const sessionData =
141
+ ((session as any)?.sessionData as SessionData | undefined) ||
142
+ buildSessionDataFromAuthSession(session);
143
+
144
+ if (!sessionData) {
145
+ return null;
146
+ }
147
+
148
+ const sessionToken = session?.session?.token as string | undefined;
149
+ return sessionToken
150
+ ? { ...sessionData, sessionToken }
151
+ : sessionData;
152
+ }
153
+
154
+ /**
155
+ * Get the current request's IDP access token without triggering a refresh.
156
+ *
157
+ * Use this for routes that only need the currently-issued bearer token and
158
+ * should fail closed instead of performing token lifecycle work.
159
+ */
160
+ export async function getIdpToken(request?: Request): Promise<IdpTokenResult> {
161
+ const sessionData = await getSessionData(request);
162
+ if (!sessionData) {
163
+ return { success: false, error: 'NO_SESSION', terminal: true };
164
+ }
165
+
166
+ const accessToken = sessionData.idpAccessToken || (sessionData as any).accessToken;
167
+ if (!accessToken) {
168
+ return { success: false, error: 'NO_TOKEN', terminal: true };
169
+ }
170
+
171
+ return {
172
+ success: true,
173
+ accessToken,
174
+ sessionData,
175
+ };
176
+ }
177
+
68
178
  /**
69
179
  * Get the current session, throwing if not authenticated.
70
180
  * Use in API handlers that require auth.