SHA256
@@ -0,0 +1,50 @@
|
||||
import crypto from 'node:crypto';
|
||||
import { getConfig } from './config.js';
|
||||
|
||||
const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
||||
|
||||
interface Session {
|
||||
username: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
const sessions = new Map<string, Session>();
|
||||
|
||||
function verifyPassword(password: string, stored: string): boolean {
|
||||
if (stored.startsWith('scrypt$')) {
|
||||
const [, salt, hash] = stored.split('$');
|
||||
const derived = crypto.scryptSync(password, salt, 64).toString('hex');
|
||||
return derived === hash;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function login(username: string, password: string): string | null {
|
||||
const config = getConfig();
|
||||
const stored = config.users?.[username];
|
||||
if (!stored || !verifyPassword(password, stored)) return null;
|
||||
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
sessions.set(token, { username, expiresAt: Date.now() + SESSION_TTL_MS });
|
||||
return token;
|
||||
}
|
||||
|
||||
export function validateSession(token: string): string | null {
|
||||
const session = sessions.get(token);
|
||||
if (!session) return null;
|
||||
if (Date.now() > session.expiresAt) {
|
||||
sessions.delete(token);
|
||||
return null;
|
||||
}
|
||||
return session.username;
|
||||
}
|
||||
|
||||
export function logout(token: string): void {
|
||||
sessions.delete(token);
|
||||
}
|
||||
|
||||
export function generatePasswordHash(password: string): string {
|
||||
const salt = crypto.randomBytes(16).toString('hex');
|
||||
const hash = crypto.scryptSync(password, salt, 64).toString('hex');
|
||||
return `scrypt$${salt}$${hash}`;
|
||||
}
|
||||
Reference in New Issue
Block a user