Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 3x 3x 5x 5x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 3x 4x 1x 1x 2x 2x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /**
* Session Security Module
*
* Provides session security features including:
* - Session rotation on privilege changes
* - Session metadata tracking (IP, user agent)
* - Session anomaly detection
*/
import { prisma } from '@/lib/prisma';
import { logger } from '@/lib/logging';
import { randomBytes } from "crypto";
/**
* Session metadata interface
*/
export interface SessionMetadata {
ipAddress: string | null;
userAgent: string | null;
createdAt: Date;
lastActivityAt: Date;
loginMethod: "credentials" | "oauth";
}
/**
* Extract request metadata for session tracking
*/
export function extractRequestMetadata(request?: Request): {
ipAddress: string | null;
userAgent: string | null;
} {
if (!request) {
return { ipAddress: null, userAgent: null };
}
const ipAddress =
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
request.headers.get("x-real-ip") ||
null;
const userAgent = request.headers.get("user-agent") || null;
return { ipAddress, userAgent };
}
/**
* Generate a new session token for rotation
*/
export function generateSessionToken(): string {
return randomBytes(32).toString("hex");
}
/**
* Rotate user session (invalidate old, create new)
*
* Should be called on:
* - Password change
* - Role/permission change
* - Explicit session rotation request
*
* @param userId - User ID to rotate session for
* @param request - Optional request for metadata
* @returns New session token or null if error
*/
export async function rotateUserSession(
userId: number,
request?: Request
): Promise<string | null> {
try {
const { ipAddress, userAgent } = extractRequestMetadata(request);
const newToken = generateSessionToken();
const now = new Date();
// Transaction: delete old sessions and create new one
await prisma.$transaction([
// Delete all existing sessions for user
prisma.session.deleteMany({
where: { userId }}),
// Create new session
prisma.session.create({
data: {
id: randomBytes(16).toString("hex"),
sessionToken: newToken,
userId,
expires: new Date(now.getTime() + 24 * 60 * 60 * 1000), // 24 hours
}}),
]);
logger.info(`Session rotated for user ${userId}`, {
category: "SESSION",
ipAddress,
userAgent: userAgent?.substring(0, 50)});
return newToken;
} catch (error) {
logger.error(
"Failed to rotate session",
error instanceof Error ? error : new Error(String(error)),
{ category: "SESSION" }
);
return null;
}
}
/**
* Invalidate all sessions for a user
*
* Should be called on:
* - Account lockout
* - Password reset (via forgot password)
* - Security breach detection
* - User logout from all devices
*
* @param userId - User ID to invalidate sessions for
*/
export async function invalidateAllUserSessions(userId: number): Promise<void> {
try {
const deleted = await prisma.session.deleteMany({
where: { userId }});
logger.info(`Invalidated ${deleted.count} sessions for user ${userId}`, {
category: "SESSION"
});
} catch (error) {
logger.error(
"Failed to invalidate sessions",
error instanceof Error ? error : new Error(String(error)),
{ category: "SESSION" }
);
throw error;
}
}
/**
* Check if session is valid and not expired
*
* @param sessionToken - Session token to validate
* @returns Session data if valid, null otherwise
*/
export async function validateSession(
sessionToken: string
): Promise<{ userId: number; expires: Date } | null> {
try {
const session = await prisma.session.findUnique({
where: { sessionToken },
select: {
userId: true,
expires: true}});
if (!session) {
return null;
}
// Check if expired
if (session.expires < new Date()) {
// Clean up expired session
await prisma.session.delete({
where: { sessionToken }});
return null;
}
return session;
} catch (error) {
logger.error(
"Failed to validate session",
error instanceof Error ? error : new Error(String(error)),
{ category: "SESSION" }
);
return null;
}
}
/**
* Update session last activity timestamp
*
* @param sessionToken - Session token to update
*/
export async function updateSessionActivity(sessionToken: string): Promise<void> {
try {
await prisma.session.update({
where: { sessionToken },
data: {
expires: new Date(Date.now() + 24 * 60 * 60 * 1000), // Extend by 24 hours
}});
} catch (error) {
// Session might not exist, log but don't throw
logger.warn("Failed to update session activity", {
category: "SESSION",
error: error instanceof Error ? error.message : String(error)
});
}
}
/**
* Detect session anomalies
*
* Checks for suspicious session activity like:
* - IP address changes
* - User agent changes
* - Unusual request patterns
*
* @param userId - User ID to check
* @param currentIp - Current request IP
* @param currentUserAgent - Current request user agent
* @returns boolean indicating if anomaly detected
*/
export async function detectSessionAnomaly(
userId: number,
currentIp: string | null,
currentUserAgent: string | null
): Promise<{
isAnomaly: boolean;
reason?: string;
}> {
try {
// Get recent audit logs for this user
const recentLogs = await prisma.auditLog.findMany({
where: {
userId,
action: "LOGIN_SUCCESS",
createdAt: {
gte: new Date(Date.now() - 24 * 60 * 60 * 1000), // Last 24 hours
}},
orderBy: { createdAt: "desc" },
take: 5,
select: {
ipAddress: true,
userAgent: true}});
if (recentLogs.length === 0) {
return { isAnomaly: false };
}
// Check for IP address change
const knownIps = new Set(recentLogs.map((log) => log.ipAddress).filter(Boolean));
if (currentIp && knownIps.size > 0 && !knownIps.has(currentIp)) {
// New IP detected - could be legitimate (mobile, VPN) or suspicious
logger.warn(`New IP detected for user ${userId}`, {
category: "SESSION",
currentIp,
knownIps: Array.from(knownIps)});
// Don't flag as anomaly immediately, but log for monitoring
// A more sophisticated system would use geolocation, risk scoring, etc.
}
// Check for user agent change (major browser/OS change)
const knownAgents = new Set(recentLogs.map((log) => log.userAgent).filter(Boolean));
if (
currentUserAgent &&
knownAgents.size > 0 &&
!Array.from(knownAgents).some(
(agent) =>
agent &&
extractBrowserFamily(agent) === extractBrowserFamily(currentUserAgent)
)
) {
logger.warn(`New browser detected for user ${userId}`, {
category: "SESSION",
currentUserAgent: currentUserAgent?.substring(0, 100)});
}
return { isAnomaly: false };
} catch (error) {
logger.error(
"Failed to detect session anomaly",
error instanceof Error ? error : new Error(String(error)),
{ category: "SESSION" }
);
return { isAnomaly: false };
}
}
/**
* Extract browser family from user agent (simplified)
*/
function extractBrowserFamily(userAgent: string): string {
const ua = userAgent.toLowerCase();
if (ua.includes("firefox")) return "firefox";
if (ua.includes("chrome") && !ua.includes("edge")) return "chrome";
if (ua.includes("safari") && !ua.includes("chrome")) return "safari";
if (ua.includes("edge")) return "edge";
if (ua.includes("opera")) return "opera";
return "other";
}
/**
* Clean up expired sessions
*
* Should be called periodically (e.g., via cron job)
*/
export async function cleanupExpiredSessions(): Promise<number> {
try {
const result = await prisma.session.deleteMany({
where: {
expires: { lt: new Date() }}});
if (result.count > 0) {
logger.info(`Cleaned up ${result.count} expired sessions`, {
category: "SESSION"
});
}
return result.count;
} catch (error) {
logger.error(
"Failed to cleanup sessions",
error instanceof Error ? error : new Error(String(error)),
{ category: "SESSION" }
);
return 0;
}
}
/**
* Get active session count for a user
*/
export async function getActiveSessionCount(userId: number): Promise<number> {
return prisma.session.count({
where: {
userId,
expires: { gt: new Date() }}});
}
/**
* Get all active sessions for a user
*/
export async function getUserSessions(
userId: number,
currentSessionToken?: string
): Promise<Array<{
id: string;
sessionToken: string;
expires: Date;
userAgent: string | null;
ipAddress: string | null;
lastActive: Date | null;
isCurrent: boolean;
}>> {
const sessions = await prisma.session.findMany({
where: {
userId,
expires: { gt: new Date() },
},
select: {
id: true,
sessionToken: true,
expires: true,
userAgent: true,
ipAddress: true,
lastActive: true,
},
orderBy: { lastActive: 'desc' },
});
return sessions.map((s) => ({
...s,
isCurrent: s.sessionToken === currentSessionToken,
}));
}
/**
* Parse user agent to get device info
*/
export function parseDeviceInfo(userAgent: string | null): {
browser: string;
os: string;
device: string;
} {
if (!userAgent) {
return { browser: 'Unknown', os: 'Unknown', device: 'Unknown' };
}
const ua = userAgent.toLowerCase();
// Browser
let browser = 'Unknown';
if (ua.includes('firefox')) browser = 'Firefox';
else if (ua.includes('edg')) browser = 'Edge';
else if (ua.includes('chrome')) browser = 'Chrome';
else if (ua.includes('safari')) browser = 'Safari';
else if (ua.includes('opera') || ua.includes('opr')) browser = 'Opera';
// OS
let os = 'Unknown';
if (ua.includes('windows')) os = 'Windows';
else if (ua.includes('mac os') || ua.includes('macos')) os = 'macOS';
else if (ua.includes('linux') && !ua.includes('android')) os = 'Linux';
else if (ua.includes('android')) os = 'Android';
else if (ua.includes('ios') || ua.includes('iphone') || ua.includes('ipad')) os = 'iOS';
// Device
let device = 'Desktop';
if (ua.includes('mobile') || ua.includes('android') || ua.includes('iphone')) device = 'Mobile';
else if (ua.includes('tablet') || ua.includes('ipad')) device = 'Tablet';
return { browser, os, device };
}
/**
* Revoke a specific session by token
*/
export async function revokeSession(sessionToken: string): Promise<boolean> {
try {
await prisma.session.delete({
where: { sessionToken },
});
return true;
} catch {
return false;
}
}
/**
* Check if session limit exceeded and clean up if needed
*/
export async function enforceSessionLimit(
userId: number,
maxSessions: number = 10
): Promise<void> {
const count = await getActiveSessionCount(userId);
if (count > maxSessions) {
// Get oldest sessions to delete
const oldestSessions = await prisma.session.findMany({
where: {
userId,
expires: { gt: new Date() },
},
orderBy: { lastActive: 'asc' },
take: count - maxSessions,
select: { sessionToken: true },
});
// Delete oldest sessions
for (const session of oldestSessions) {
await revokeSession(session.sessionToken);
}
logger.info(`Enforced session limit for user ${userId}, removed ${oldestSessions.length} sessions`, {
category: 'SESSION'
});
}
}
|