50 lines
1.6 KiB
TypeScript
50 lines
1.6 KiB
TypeScript
/**
|
|
* Active session management via refresh-token tracking.
|
|
*/
|
|
|
|
import * as refreshTokenRepository from '../repositories/refreshTokenRepository';
|
|
import * as settingsRepository from '../repositories/settingsRepository';
|
|
import { logSecurityEvent } from '../utils/securityAudit';
|
|
|
|
export type SessionContext = {
|
|
ipAddress?: string;
|
|
userAgent?: string;
|
|
};
|
|
|
|
/**
|
|
* Enforces max concurrent sessions by evicting oldest refresh tokens when over limit.
|
|
* Call after issuing a new refresh token on login or refresh.
|
|
*/
|
|
export async function enforceConcurrentSessionLimit(
|
|
userId: string,
|
|
ctx?: SessionContext
|
|
): Promise<{ evicted: number; atLimit: boolean }> {
|
|
const settings = await settingsRepository.getSettings();
|
|
const max = settings.max_concurrent_sessions;
|
|
if (max <= 0) return { evicted: 0, atLimit: false };
|
|
|
|
const active = await refreshTokenRepository.countActiveByUserId(userId);
|
|
const atLimit = active > max;
|
|
const excess = active - max;
|
|
if (excess <= 0) return { evicted: 0, atLimit };
|
|
|
|
const evicted = await refreshTokenRepository.deleteOldestSessions(userId, excess);
|
|
if (evicted > 0) {
|
|
logSecurityEvent('sessions_trimmed', {
|
|
userId,
|
|
ipAddress: ctx?.ipAddress ?? null,
|
|
userAgent: ctx?.userAgent ?? null,
|
|
metadata: { evicted, maxSessions: max, activeBefore: active },
|
|
});
|
|
}
|
|
if (atLimit) {
|
|
logSecurityEvent('concurrent_session_limit', {
|
|
userId,
|
|
ipAddress: ctx?.ipAddress ?? null,
|
|
userAgent: ctx?.userAgent ?? null,
|
|
metadata: { maxSessions: max, activeBefore: active, evicted },
|
|
});
|
|
}
|
|
return { evicted, atLimit };
|
|
}
|