Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : src/lib/auth/session.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website : https://www.orixlab.dev12 * Created : 2026-11-2113 * Last Modified : 2026-11-2114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { cookies } from "next/headers";44import { db, now } from "../database/db";45import { env } from "../env";46import { randomToken, safeEqual, sha256 } from "../security/crypto";47import { ApiError, assertSameOrigin, clientIp } from "../security/http";4849export const SESSION_COOKIE = "orix_admin";50export const SESSION_HOURS = 12;51export const IDLE_MINUTES = 60;5253export type AdminContext = { adminId: string; name: string; csrf: string; tokenHash: string; expiresAt: string };5455type Row = { token_hash: string; admin_id: string; csrf: string; expires_at: string; last_seen_at: string; name: string };5657/** Resolves a raw session token. Expired or idle sessions are deleted as they are met. */58export function adminFromToken(raw: string | undefined, at = Date.now()): AdminContext | null {59 if (!raw) return null;60 const h = sha256(raw);61 const r = db().prepare("SELECT s.*, a.name FROM sessions s JOIN admins a ON a.id = s.admin_id WHERE s.token_hash = ?").get(h) as Row | undefined;62 if (!r) return null;63 if (Date.parse(r.expires_at) <= at || at - Date.parse(r.last_seen_at) > IDLE_MINUTES * 60_000) {64 db().prepare("DELETE FROM sessions WHERE token_hash = ?").run(h);65 return null;66 }67 if (at - Date.parse(r.last_seen_at) > 60_000) db().prepare("UPDATE sessions SET last_seen_at = ? WHERE token_hash = ?").run(new Date(at).toISOString(), h);68 return { adminId: r.admin_id, name: r.name, csrf: r.csrf, tokenHash: h, expiresAt: r.expires_at };69}7071export function issueSession(adminId: string, meta: { ip?: string; ua?: string } = {}): { token: string; expires: Date } {72 const token = randomToken(32), expires = new Date(Date.now() + SESSION_HOURS * 3_600_000);73 db().prepare("INSERT INTO sessions (token_hash, admin_id, csrf, created_at, expires_at, last_seen_at, ip, ua) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")74 .run(sha256(token), adminId, randomToken(24), now(), expires.toISOString(), now(), meta.ip ?? null, (meta.ua ?? "").slice(0, 300));75 return { token, expires };76}7778/** A new session identifier is issued at every authentication; the previous one is revoked. */79export async function startSession(adminId: string, req: Request): Promise<void> {80 const jar = await cookies();81 const previous = jar.get(SESSION_COOKIE)?.value;82 if (previous) db().prepare("DELETE FROM sessions WHERE token_hash = ?").run(sha256(previous));83 const { token, expires } = issueSession(adminId, { ip: clientIp(req), ua: req.headers.get("user-agent") ?? "" });84 // Host-only, HttpOnly, SameSite=Strict: never sent on a cross-site request, never readable by scripts.85 jar.set(SESSION_COOKIE, token, { httpOnly: true, secure: env.secureCookies, sameSite: "strict", path: "/", expires });86}8788export async function endSession(): Promise<void> {89 const jar = await cookies();90 const raw = jar.get(SESSION_COOKIE)?.value;91 if (raw) db().prepare("DELETE FROM sessions WHERE token_hash = ?").run(sha256(raw));92 jar.set(SESSION_COOKIE, "", { httpOnly: true, secure: env.secureCookies, sameSite: "strict", path: "/", maxAge: 0 });93}9495export async function currentAdmin(): Promise<AdminContext | null> {96 return adminFromToken((await cookies()).get(SESSION_COOKIE)?.value);97}9899/**100 * Guard of the whole /api/admin surface: a live session, and for anything that changes state a same-origin101 * request carrying the session's CSRF token in a header.102 */103export async function requireAdmin(req: Request): Promise<AdminContext> {104 const admin = await currentAdmin();105 if (!admin) throw new ApiError(401, "unauthenticated", "Sign in required");106 if (req.method !== "GET" && req.method !== "HEAD") {107 assertSameOrigin(req);108 if (!safeEqual(req.headers.get("x-csrf-token") ?? "", admin.csrf)) throw new ApiError(403, "csrf", "Invalid CSRF token");109 }110 return admin;111}112