Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Chat SPBoucher AI8 * File : src/lib/auth/session.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/chat-spboucher-ai11 * Project Website : https://chat.spboucher.ai12 * Created : 2026-11-1713 * Last Modified : 2026-11-1714 *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: contact@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 { createHash, randomBytes } from "node:crypto";44import { sql } from "../db";45import { authConfig } from "./config";46import { deviceLabel } from "./device";4748/**49 * Server-side sessions. The cookie carries a random 256-bit token; the database stores only its SHA-256, so a database50 * leak does not yield usable cookies. Every session can be revoked on its own, or all at once.51 * No `next/headers` here: this module is also used by src/proxy.ts and by the CLI.52 */53export interface SessionRow {54 id: string; public_id: string; created_at: Date; expires_at: Date; absolute_expires_at: Date | null; last_seen: Date; auth_at: Date | null;55 user_agent: string | null; ip: string | null; label: string | null; credential_id: string | null; revoked_at: Date | null;56}5758const hashToken = (t: string) => createHash("sha256").update(t).digest("hex");59const newToken = () => randomBytes(32).toString("base64url");60const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/;6162export async function createSession(o: { credentialId: string | null; userAgent?: string | null; ip?: string | null }): Promise<{ token: string; session: SessionRow }> {63 const token = newToken();64 const rows = await sql<SessionRow[]>`INSERT INTO sessions (id, public_id, expires_at, absolute_expires_at, auth_at, user_agent, ip, label, credential_id)65 VALUES (${hashToken(token)}, ${"ses_" + randomBytes(9).toString("hex")}, now() + make_interval(days => ${authConfig.idleDays}), now() + make_interval(days => ${authConfig.absoluteDays}), now(),66 ${o.userAgent?.slice(0, 300) ?? null}, ${o.ip ?? null}, ${deviceLabel(o.userAgent)}, ${o.credentialId}) RETURNING *`;67 return { token, session: rows[0] };68}6970/** Valid session for this cookie value, or null. Slides the idle expiry (at most one write every 5 minutes). */71export async function readSession(token: string | undefined | null): Promise<SessionRow | null> {72 if (!token || !TOKEN_RE.test(token)) return null;73 const rows = await sql<SessionRow[]>`SELECT * FROM sessions WHERE id = ${hashToken(token)} AND revoked_at IS NULL AND expires_at > now() AND (absolute_expires_at IS NULL OR absolute_expires_at > now())`;74 const s = rows[0]; if (!s) return null;75 if (Date.now() - s.last_seen.getTime() > 5 * 60_000)76 void sql`UPDATE sessions SET last_seen = now(), expires_at = LEAST(now() + make_interval(days => ${authConfig.idleDays}), COALESCE(absolute_expires_at, 'infinity')) WHERE id = ${s.id}`.catch(() => {});77 return s;78}7980/** New token for the same session (after a passkey verification): the previous cookie value stops working at once. */81export async function rotateSession(token: string, o: { credentialId?: string | null } = {}): Promise<{ token: string; session: SessionRow } | null> {82 if (!TOKEN_RE.test(token)) return null;83 const next = newToken();84 const rows = await sql<SessionRow[]>`UPDATE sessions SET id = ${hashToken(next)}, rotated_at = now(), auth_at = now(), last_seen = now(), credential_id = COALESCE(${o.credentialId ?? null}, credential_id)85 WHERE id = ${hashToken(token)} AND revoked_at IS NULL AND expires_at > now() RETURNING *`;86 return rows[0] ? { token: next, session: rows[0] } : null;87}8889export async function revokeSessionByToken(token: string | undefined | null, reason = "lock"): Promise<SessionRow | null> {90 if (!token || !TOKEN_RE.test(token)) return null;91 const r = await sql<SessionRow[]>`UPDATE sessions SET revoked_at = now(), revoked_reason = ${reason} WHERE id = ${hashToken(token)} AND revoked_at IS NULL RETURNING *`;92 return r[0] ?? null;93}94export async function revokeSessionByPublicId(publicId: string, reason = "revoked"): Promise<boolean> {95 const r = await sql`UPDATE sessions SET revoked_at = now(), revoked_reason = ${reason} WHERE public_id = ${publicId} AND revoked_at IS NULL RETURNING public_id`;96 return r.length > 0;97}98/** Global revocation. `exceptId` (token hash) keeps the calling device signed in. Returns the number of sessions closed. */99export async function revokeAllSessions(o: { exceptId?: string | null; reason?: string; credentialId?: string } = {}): Promise<number> {100 const r = await sql`UPDATE sessions SET revoked_at = now(), revoked_reason = ${o.reason ?? "revoke-all"}101 WHERE revoked_at IS NULL AND (${o.exceptId ?? null}::text IS NULL OR id <> ${o.exceptId ?? null}) AND (${o.credentialId ?? null}::text IS NULL OR credential_id = ${o.credentialId ?? null}) RETURNING id`;102 return r.length;103}104105export async function listSessions(): Promise<SessionRow[]> {106 return sql<SessionRow[]>`SELECT * FROM sessions WHERE revoked_at IS NULL AND expires_at > now() AND (absolute_expires_at IS NULL OR absolute_expires_at > now()) ORDER BY last_seen DESC LIMIT 100`;107}108109export const recentlyAuthenticated = (s: SessionRow) => !!s.auth_at && Date.now() - s.auth_at.getTime() < authConfig.recentAuthSec * 1000;110111export function sessionCookieOptions() {112 return { httpOnly: true as const, secure: authConfig.secure, sameSite: "lax" as const, path: "/", maxAge: authConfig.idleDays * 86_400 };113}114