feat(security): implement AES-256-GCM vault, Panic Lock, Argon2id+TOTP auth, guards, and rotate-key CLI

This commit is contained in:
tyuXX 2026-11-26 18:21:09 +00:00
parent 2c60483a90
commit 3b9e084916
5 changed files with 1249 additions and 0 deletions

475
src/server/security/auth.ts Normal file
View file

@ -0,0 +1,475 @@
import crypto from 'node:crypto';
import argon2 from 'argon2';
import type Database from 'better-sqlite3';
import * as OTPAuth from 'otpauth';
import QRCode from 'qrcode';
const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const STEP_UP_TTL_MS = 5 * 60 * 1000;
const BOOTSTRAP_TTL_MS = 15 * 60 * 1000;
const TOTP_PERIOD_SEC = 30;
export const SESSION_COOKIE_NAME = 'gcoord_sid';
export interface AuthSession {
idHash: string;
csrfTokenHash: string;
safeMode: boolean;
elevatedUntil: number | null;
ip: string;
userAgent: string;
createdAt: number;
lastSeenAt: number;
expiresAt: number;
}
export interface SessionSummary {
idPrefix: string;
ip: string;
userAgent: string;
safeMode: boolean;
elevatedUntil: number | null;
createdAt: number;
lastSeenAt: number;
expiresAt: number;
current: boolean;
}
interface AdminRow {
id: number;
username: string;
password_hash: string;
totp_secret: string;
last_login_totp_step: number | null;
last_stepup_totp_step: number | null;
}
interface SessionRow {
id_hash: string;
csrf_token_hash: string;
safe_mode: number;
elevated_until: number | null;
ip: string;
user_agent: string;
created_at: number;
last_seen_at: number;
expires_at: number;
}
export function sha256Hex(value: string): string {
return crypto.createHash('sha256').update(value, 'utf8').digest('hex');
}
function generateRecoveryCode(): string {
const bytes = crypto.randomBytes(10);
let out = '';
for (let i = 0; i < 10; i++) {
if (i === 5) out += '-';
out += RECOVERY_ALPHABET[bytes[i]! % RECOVERY_ALPHABET.length];
}
return out;
}
function normalizeRecoveryCode(input: string): string {
return input.trim().toUpperCase().replace(/[^A-Z0-9]/g, '');
}
function buildTotp(secretBase32: string, username: string): OTPAuth.TOTP {
return new OTPAuth.TOTP({
issuer: 'GCoordinator',
label: username,
algorithm: 'SHA1',
digits: 6,
period: TOTP_PERIOD_SEC,
secret: OTPAuth.Secret.fromBase32(secretBase32),
});
}
export class AuthService {
private pendingBootstrap: { secretBase32: string; createdAt: number } | null = null;
constructor(private readonly db: Database.Database) {}
isBootstrapped(): boolean {
const row = this.db.prepare('SELECT id FROM admin_users WHERE id = 1').get();
return Boolean(row);
}
async beginBootstrap(username = 'admin'): Promise<{
secretBase32: string;
otpauthUri: string;
qrSvg: string;
}> {
if (this.isBootstrapped()) {
throw new Error('Admin account is already configured');
}
if (
!this.pendingBootstrap ||
Date.now() - this.pendingBootstrap.createdAt > BOOTSTRAP_TTL_MS
) {
const secret = new OTPAuth.Secret({ size: 20 });
this.pendingBootstrap = {
secretBase32: secret.base32,
createdAt: Date.now(),
};
}
const totp = buildTotp(this.pendingBootstrap.secretBase32, username);
const otpauthUri = totp.toString();
const qrSvg = await QRCode.toString(otpauthUri, { type: 'svg', margin: 1 });
return {
secretBase32: this.pendingBootstrap.secretBase32,
otpauthUri,
qrSvg,
};
}
async completeBootstrap(params: {
username: string;
password: string;
totpCode: string;
secretBase32?: string;
ip: string;
userAgent: string;
initialSafeMode?: boolean;
}): Promise<{
sessionToken: string;
csrfToken: string;
session: AuthSession;
recoveryCodes: string[];
}> {
if (this.isBootstrapped()) {
throw new Error('Admin account is already configured');
}
const username = params.username.trim();
if (username.length < 2 || username.length > 64) {
throw new Error('Username must be 2–64 characters');
}
if (params.password.length < 10) {
throw new Error('Password must be at least 10 characters');
}
const secretBase32 = params.secretBase32 ?? this.pendingBootstrap?.secretBase32;
if (!secretBase32) {
throw new Error('Bootstrap enrollment session expired; reload setup');
}
const nowMs = Date.now();
const totp = buildTotp(secretBase32, username);
const delta = totp.validate({
token: params.totpCode.trim(),
window: 1,
timestamp: nowMs,
});
if (delta === null) {
throw new Error('Invalid TOTP verification code');
}
const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta;
const passwordHash = await argon2.hash(params.password, {
type: argon2.argon2id,
memoryCost: 65536,
timeCost: 3,
parallelism: 1,
});
const recoveryCodes: string[] = [];
for (let i = 0; i < 8; i++) {
recoveryCodes.push(generateRecoveryCode());
}
const tx = this.db.transaction(() => {
this.db
.prepare(
`INSERT INTO admin_users (id, username, password_hash, totp_secret, last_login_totp_step, last_stepup_totp_step, created_at, updated_at)
VALUES (1, ?, ?, ?, ?, NULL, ?, ?)`,
)
.run(username, passwordHash, secretBase32, matchedStep, nowMs, nowMs);
const insertRec = this.db.prepare(
'INSERT INTO recovery_codes (code_hash, used_at) VALUES (?, NULL)',
);
for (const code of recoveryCodes) {
insertRec.run(sha256Hex(normalizeRecoveryCode(code)));
}
});
tx();
this.pendingBootstrap = null;
const created = this.createSession(
params.ip,
params.userAgent,
Boolean(params.initialSafeMode),
);
return { ...created, recoveryCodes };
}
async login(params: {
username?: string;
password: string;
code: string;
ip: string;
userAgent: string;
initialSafeMode?: boolean;
}): Promise<{ sessionToken: string; csrfToken: string; session: AuthSession } | null> {
const admin = this.db
.prepare('SELECT * FROM admin_users WHERE id = 1')
.get() as AdminRow | undefined;
if (!admin) return null;
if (params.username && params.username.trim() !== admin.username) {
return null;
}
const passwordValid = await argon2.verify(admin.password_hash, params.password);
if (!passwordValid) return null;
const trimmedCode = params.code.trim();
const nowMs = Date.now();
if (/^\d{6}$/.test(trimmedCode)) {
const totp = buildTotp(admin.totp_secret, admin.username);
const delta = totp.validate({ token: trimmedCode, window: 1, timestamp: nowMs });
if (delta === null) return null;
const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta;
if (
admin.last_login_totp_step !== null &&
matchedStep <= admin.last_login_totp_step
) {
return null;
}
this.db
.prepare('UPDATE admin_users SET last_login_totp_step = ?, updated_at = ? WHERE id = 1')
.run(matchedStep, nowMs);
return this.createSession(
params.ip,
params.userAgent,
Boolean(params.initialSafeMode),
);
}
// Fallback: single-use recovery code
const normalized = normalizeRecoveryCode(trimmedCode);
if (normalized.length < 8) return null;
const codeHash = sha256Hex(normalized);
const updated = this.db
.prepare(
'UPDATE recovery_codes SET used_at = ? WHERE code_hash = ? AND used_at IS NULL',
)
.run(nowMs, codeHash);
if (updated.changes !== 1) return null;
return this.createSession(
params.ip,
params.userAgent,
Boolean(params.initialSafeMode),
);
}
getSessionByToken(sessionToken: string | undefined): AuthSession | null {
if (!sessionToken || sessionToken.length < 16) return null;
const idHash = sha256Hex(sessionToken);
const row = this.db
.prepare('SELECT * FROM sessions WHERE id_hash = ?')
.get(idHash) as SessionRow | undefined;
if (!row) return null;
const now = Date.now();
if (row.expires_at <= now) {
this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash);
return null;
}
if (now - row.last_seen_at > 60_000) {
this.db
.prepare('UPDATE sessions SET last_seen_at = ? WHERE id_hash = ?')
.run(now, idHash);
}
return {
idHash: row.id_hash,
csrfTokenHash: row.csrf_token_hash,
safeMode: row.safe_mode === 1,
elevatedUntil:
row.elevated_until && row.elevated_until > now ? row.elevated_until : null,
ip: row.ip,
userAgent: row.user_agent,
createdAt: row.created_at,
lastSeenAt: row.last_seen_at,
expiresAt: row.expires_at,
};
}
stepUp(idHash: string, totpCode: string): { ok: true; elevatedUntil: number } | { ok: false; reason: string } {
const admin = this.db
.prepare('SELECT * FROM admin_users WHERE id = 1')
.get() as AdminRow | undefined;
if (!admin) return { ok: false, reason: 'not_bootstrapped' };
const session = this.db
.prepare('SELECT safe_mode FROM sessions WHERE id_hash = ?')
.get(idHash) as { safe_mode: number } | undefined;
if (!session) return { ok: false, reason: 'invalid_session' };
if (session.safe_mode === 1) {
return { ok: false, reason: 'safe_mode_active' };
}
const trimmed = totpCode.trim();
if (!/^\d{6}$/.test(trimmed)) {
return { ok: false, reason: 'invalid_totp' };
}
const nowMs = Date.now();
const totp = buildTotp(admin.totp_secret, admin.username);
const delta = totp.validate({ token: trimmed, window: 1, timestamp: nowMs });
if (delta === null) {
return { ok: false, reason: 'invalid_totp' };
}
const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta;
if (
admin.last_stepup_totp_step !== null &&
matchedStep <= admin.last_stepup_totp_step
) {
return { ok: false, reason: 'totp_replayed' };
}
const elevatedUntil = nowMs + STEP_UP_TTL_MS;
const tx = this.db.transaction(() => {
this.db
.prepare('UPDATE admin_users SET last_stepup_totp_step = ?, updated_at = ? WHERE id = 1')
.run(matchedStep, nowMs);
this.db
.prepare('UPDATE sessions SET elevated_until = ? WHERE id_hash = ?')
.run(elevatedUntil, idHash);
});
tx();
return { ok: true, elevatedUntil };
}
dropElevation(idHash: string): void {
this.db
.prepare('UPDATE sessions SET elevated_until = NULL WHERE id_hash = ?')
.run(idHash);
}
setSafeMode(idHash: string, enabled: boolean): AuthSession | null {
if (enabled) {
this.db
.prepare('UPDATE sessions SET safe_mode = 1, elevated_until = NULL WHERE id_hash = ?')
.run(idHash);
} else {
this.db
.prepare('UPDATE sessions SET safe_mode = 0 WHERE id_hash = ?')
.run(idHash);
}
const row = this.db
.prepare('SELECT * FROM sessions WHERE id_hash = ?')
.get(idHash) as SessionRow | undefined;
if (!row) return null;
const now = Date.now();
return {
idHash: row.id_hash,
csrfTokenHash: row.csrf_token_hash,
safeMode: row.safe_mode === 1,
elevatedUntil:
row.elevated_until && row.elevated_until > now ? row.elevated_until : null,
ip: row.ip,
userAgent: row.user_agent,
createdAt: row.created_at,
lastSeenAt: row.last_seen_at,
expiresAt: row.expires_at,
};
}
listSessions(currentIdHash: string): SessionSummary[] {
const now = Date.now();
this.db.prepare('DELETE FROM sessions WHERE expires_at <= ?').run(now);
const rows = this.db
.prepare('SELECT * FROM sessions ORDER BY last_seen_at DESC')
.all() as SessionRow[];
return rows.map((row) => ({
idPrefix: row.id_hash.slice(0, 12),
ip: row.ip,
userAgent: row.user_agent,
safeMode: row.safe_mode === 1,
elevatedUntil:
row.elevated_until && row.elevated_until > now ? row.elevated_until : null,
createdAt: row.created_at,
lastSeenAt: row.last_seen_at,
expiresAt: row.expires_at,
current: row.id_hash === currentIdHash,
}));
}
revokeSessionByHash(idHash: string): void {
this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash);
}
revokeSessionByPrefix(prefix: string): number {
if (!/^[0-9a-f]{8,64}$/i.test(prefix)) return 0;
const result = this.db
.prepare('DELETE FROM sessions WHERE id_hash LIKE ?')
.run(`${prefix}%`);
return result.changes;
}
revokeAllSessions(exceptIdHash?: string): number {
if (exceptIdHash) {
return this.db
.prepare('DELETE FROM sessions WHERE id_hash != ?')
.run(exceptIdHash).changes;
}
return this.db.prepare('DELETE FROM sessions').run().changes;
}
private createSession(
ip: string,
userAgent: string,
safeMode: boolean,
): { sessionToken: string; csrfToken: string; session: AuthSession } {
const sessionToken = crypto.randomBytes(32).toString('base64url');
const csrfToken = crypto.randomBytes(32).toString('base64url');
const idHash = sha256Hex(sessionToken);
const csrfTokenHash = sha256Hex(csrfToken);
const now = Date.now();
const expiresAt = now + SESSION_TTL_MS;
this.db
.prepare(
`INSERT INTO sessions (id_hash, csrf_token_hash, safe_mode, elevated_until, ip, user_agent, created_at, last_seen_at, expires_at)
VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?)`,
)
.run(
idHash,
csrfTokenHash,
safeMode ? 1 : 0,
ip,
userAgent.slice(0, 256),
now,
now,
expiresAt,
);
return {
sessionToken,
csrfToken,
session: {
idHash,
csrfTokenHash,
safeMode,
elevatedUntil: null,
ip,
userAgent: userAgent.slice(0, 256),
createdAt: now,
lastSeenAt: now,
expiresAt,
},
};
}
}