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

View file

@ -0,0 +1,81 @@
import type Database from 'better-sqlite3';
export interface AuditEntryInput {
action: string;
actorIp: string;
sessionIdHash?: string | null;
target?: string | null;
status: 'ok' | 'denied' | 'error';
details?: Record<string, unknown> | string | null;
}
export interface AuditLogRecord {
id: number;
ts: number;
action: string;
actor_ip: string;
session_id_hash: string | null;
target: string | null;
status: string;
details: string | null;
}
export class AuditService {
private readonly insertStmt;
constructor(private readonly db: Database.Database) {
this.insertStmt = this.db.prepare(`
INSERT INTO audit_log (ts, action, actor_ip, session_id_hash, target, status, details)
VALUES (?, ?, ?, ?, ?, ?, ?)
`);
}
log(entry: AuditEntryInput): void {
const detailsText =
entry.details == null
? null
: typeof entry.details === 'string'
? entry.details
: JSON.stringify(entry.details);
this.insertStmt.run(
Date.now(),
entry.action,
entry.actorIp,
entry.sessionIdHash ?? null,
entry.target ?? null,
entry.status,
detailsText,
);
}
list(options: { limit?: number; offset?: number; action?: string } = {}): {
total: number;
items: AuditLogRecord[];
} {
const limit = Math.max(1, Math.min(200, options.limit ?? 50));
const offset = Math.max(0, options.offset ?? 0);
if (options.action) {
const countRow = this.db
.prepare('SELECT COUNT(*) AS cnt FROM audit_log WHERE action = ?')
.get(options.action) as { cnt: number };
const items = this.db
.prepare(
'SELECT id, ts, action, actor_ip, session_id_hash, target, status, details FROM audit_log WHERE action = ? ORDER BY ts DESC, id DESC LIMIT ? OFFSET ?',
)
.all(options.action, limit, offset) as AuditLogRecord[];
return { total: countRow.cnt, items };
}
const countRow = this.db
.prepare('SELECT COUNT(*) AS cnt FROM audit_log')
.get() as { cnt: number };
const items = this.db
.prepare(
'SELECT id, ts, action, actor_ip, session_id_hash, target, status, details FROM audit_log ORDER BY ts DESC, id DESC LIMIT ? OFFSET ?',
)
.all(limit, offset) as AuditLogRecord[];
return { total: countRow.cnt, items };
}
}

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,
},
};
}
}

View file

@ -0,0 +1,165 @@
import crypto from 'node:crypto';
import type { NextFunction, Request, Response } from 'express';
import {
SESSION_COOKIE_NAME,
sha256Hex,
type AuthService,
type AuthSession,
} from './auth.js';
declare global {
namespace Express {
interface Request {
authSession?: AuthSession;
clientIp?: string;
}
}
}
interface RateBucketState {
failures: number;
lockedUntil: number;
}
export class RateLimiter {
private readonly buckets = new Map<string, RateBucketState>();
check(scope: string, ip: string): { allowed: boolean; retryAfterSec: number } {
const key = `${scope}:${ip}`;
const state = this.buckets.get(key);
if (!state) return { allowed: true, retryAfterSec: 0 };
const now = Date.now();
if (state.lockedUntil > now) {
return {
allowed: false,
retryAfterSec: Math.max(1, Math.ceil((state.lockedUntil - now) / 1000)),
};
}
return { allowed: true, retryAfterSec: 0 };
}
recordFailure(scope: string, ip: string): number {
const key = `${scope}:${ip}`;
const prev = this.buckets.get(key) ?? { failures: 0, lockedUntil: 0 };
const failures = prev.failures + 1;
let lockedUntil = 0;
if (failures >= 5) {
const delayMs = Math.min(300_000, 2000 * 2 ** (failures - 5));
lockedUntil = Date.now() + delayMs;
}
this.buckets.set(key, { failures, lockedUntil });
return lockedUntil;
}
recordSuccess(scope: string, ip: string): void {
this.buckets.delete(`${scope}:${ip}`);
}
}
export function extractCookies(cookieHeader: string | undefined): Record<string, string> {
const result: Record<string, string> = {};
if (!cookieHeader) return result;
for (const part of cookieHeader.split(';')) {
const eq = part.indexOf('=');
if (eq <= 0) continue;
const key = part.slice(0, eq).trim();
const rawVal = part.slice(eq + 1).trim();
try {
result[key] = decodeURIComponent(rawVal);
} catch {
result[key] = rawVal;
}
}
return result;
}
export function resolveClientIp(req: Request, trustCloudflare: boolean): string {
if (trustCloudflare) {
const cf = req.headers['cf-connecting-ip'];
if (typeof cf === 'string' && cf.trim().length > 0) {
return cf.split(',')[0]!.trim();
}
}
return req.ip || req.socket.remoteAddress || 'unknown';
}
export function attachClientIp(trustCloudflare: boolean) {
return (req: Request, _res: Response, next: NextFunction): void => {
req.clientIp = resolveClientIp(req, trustCloudflare);
next();
};
}
export function requireAuth(authService: AuthService) {
return (req: Request, res: Response, next: NextFunction): void => {
const cookies = extractCookies(req.headers.cookie);
const token = cookies[SESSION_COOKIE_NAME];
const session = authService.getSessionByToken(token);
if (!session) {
res.status(401).json({ error: 'UNAUTHENTICATED' });
return;
}
req.authSession = session;
next();
};
}
export function requireCsrf(req: Request, res: Response, next: NextFunction): void {
if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') {
next();
return;
}
const session = req.authSession;
if (!session) {
res.status(401).json({ error: 'UNAUTHENTICATED' });
return;
}
const headerToken = req.headers['x-csrf-token'];
if (typeof headerToken !== 'string' || headerToken.length < 16) {
res.status(403).json({ error: 'CSRF_INVALID' });
return;
}
const providedHash = Buffer.from(sha256Hex(headerToken), 'hex');
const expectedHash = Buffer.from(session.csrfTokenHash, 'hex');
if (
providedHash.length !== expectedHash.length ||
!crypto.timingSafeEqual(providedHash, expectedHash)
) {
res.status(403).json({ error: 'CSRF_INVALID' });
return;
}
next();
}
export function enforceSafeMode(req: Request, res: Response, next: NextFunction): void {
if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') {
next();
return;
}
const clientSafeHeader = req.headers['x-gcoord-safe-mode'] === '1';
if (req.authSession?.safeMode || clientSafeHeader) {
res.status(423).json({
error: 'SAFE_MODE_ACTIVE',
message: 'Disable Safe / Read-Only Mode before performing mutating actions.',
});
return;
}
next();
}
export function requireStepUp(req: Request, res: Response, next: NextFunction): void {
const session = req.authSession;
if (!session) {
res.status(401).json({ error: 'UNAUTHENTICATED' });
return;
}
if (!session.elevatedUntil || session.elevatedUntil <= Date.now()) {
res.status(403).json({
error: 'STEP_UP_REQUIRED',
message: 'Fresh TOTP step-up verification is required for this sensitive operation.',
});
return;
}
next();
}

View file

@ -0,0 +1,418 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { z } from 'zod';
import {
VaultCredentialSchema,
VaultPayloadSchema,
type VaultCredential,
type VaultCredentialMeta,
type VaultPayload,
} from '../../shared/schemas/vault.schema.js';
import type { VaultState } from '../../shared/ws-protocol.js';
const VaultEnvelopeSchema = z.object({
version: z.literal(1),
alg: z.literal('aes-256-gcm'),
iv: z.string().min(1),
tag: z.string().min(1),
ciphertext: z.string().min(1),
updatedAt: z.string(),
});
type VaultEnvelope = z.infer<typeof VaultEnvelopeSchema>;
export function parseMasterKey(raw: string): Buffer {
const trimmed = raw.trim();
if (/^[0-9a-fA-F]{64}$/.test(trimmed)) {
return Buffer.from(trimmed, 'hex');
}
if (/^[A-Za-z0-9+/=]{43,44}$/.test(trimmed)) {
const buf = Buffer.from(trimmed, 'base64');
if (buf.length === 32) return buf;
}
throw new Error('Master key must be a 32-byte key encoded as 64 hex chars or base64');
}
export function generateMasterKeyBuffer(): Buffer {
return crypto.randomBytes(32);
}
function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const plaintext = Buffer.from(JSON.stringify(payload), 'utf8');
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
const tag = cipher.getAuthTag();
plaintext.fill(0);
return {
version: 1,
alg: 'aes-256-gcm',
iv: iv.toString('base64'),
tag: tag.toString('base64'),
ciphertext: ciphertext.toString('base64'),
updatedAt: new Date().toISOString(),
};
}
function decryptEnvelope(envelope: VaultEnvelope, key: Buffer): VaultPayload {
const iv = Buffer.from(envelope.iv, 'base64');
const tag = Buffer.from(envelope.tag, 'base64');
const ciphertext = Buffer.from(envelope.ciphertext, 'base64');
if (iv.length !== 12 || tag.length !== 16) {
throw new Error('Invalid AES-256-GCM envelope parameters');
}
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
try {
const parsed = JSON.parse(plaintext.toString('utf8'));
return VaultPayloadSchema.parse(parsed);
} finally {
plaintext.fill(0);
}
}
function buildSshEd25519PublicAndFingerprint(spkiDer: Buffer, comment?: string): {
publicKey: string;
fingerprint: string;
} {
// Ed25519 SPKI DER is 44 bytes: 12-byte ASN.1 header + 32-byte raw public key
if (spkiDer.length !== 44) {
throw new Error(`Unexpected Ed25519 SPKI DER length: ${spkiDer.length}`);
}
const rawPub = spkiDer.subarray(12);
const algBuf = Buffer.from('ssh-ed25519', 'ascii');
const wire = Buffer.allocUnsafe(4 + algBuf.length + 4 + rawPub.length);
wire.writeUInt32BE(algBuf.length, 0);
algBuf.copy(wire, 4);
wire.writeUInt32BE(rawPub.length, 4 + algBuf.length);
rawPub.copy(wire, 8 + algBuf.length);
const publicB64 = wire.toString('base64');
const fingerprintHash = crypto
.createHash('sha256')
.update(wire)
.digest('base64')
.replace(/=+$/, '');
const publicKey = comment ? `ssh-ed25519 ${publicB64} ${comment}` : `ssh-ed25519 ${publicB64}`;
return {
publicKey,
fingerprint: `SHA256:${fingerprintHash}`,
};
}
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
export type VaultCredentialInput = DistributiveOmit<
VaultCredential,
'createdAt' | 'updatedAt'
> & {
createdAt?: string;
updatedAt?: string;
};
export class VaultService {
private masterKey: Buffer | null = null;
private credentials = new Map<string, VaultCredential>();
private wasPanicLocked = false;
private readonly panicListeners = new Set<() => void>();
constructor(private readonly vaultFilePath: string) {}
get filePath(): string {
return this.vaultFilePath;
}
get state(): VaultState {
if (this.masterKey !== null) return 'unlocked';
return fs.existsSync(this.vaultFilePath) ? 'locked' : 'uninitialized';
}
get isPanicLocked(): boolean {
return this.wasPanicLocked;
}
onPanicLock(listener: () => void): () => void {
this.panicListeners.add(listener);
return () => {
this.panicListeners.delete(listener);
};
}
tryAutoUnlockFromEnvOrSecret(options: {
secretFilePath?: string;
envKey?: string;
}): { unlocked: boolean; initialized?: boolean; reason?: string } {
// Security invariant: never silently re-read disk secrets after Emergency Panic Lock
if (this.wasPanicLocked) {
return { unlocked: false, reason: 'panic_locked' };
}
let rawKey: string | undefined;
if (options.secretFilePath && fs.existsSync(options.secretFilePath)) {
rawKey = fs.readFileSync(options.secretFilePath, 'utf8').trim();
} else if (options.envKey && options.envKey.trim().length > 0) {
rawKey = options.envKey.trim();
}
if (!rawKey) {
return { unlocked: false, reason: 'no_key' };
}
try {
if (!fs.existsSync(this.vaultFilePath)) {
this.initializeNewVault(rawKey);
return { unlocked: true, initialized: true };
}
this.unlock(rawKey);
return { unlocked: true };
} catch (err) {
return {
unlocked: false,
reason: err instanceof Error ? err.message : 'decrypt_failed',
};
}
}
initializeNewVault(masterKeyInput?: string): { generatedKeyHex?: string } {
if (fs.existsSync(this.vaultFilePath)) {
throw new Error('Vault file already exists; unlock it instead of initializing');
}
const keyBuf = masterKeyInput
? parseMasterKey(masterKeyInput)
: generateMasterKeyBuffer();
const emptyPayload: VaultPayload = { version: 1, credentials: {} };
this.writeVerifiedVaultAtomic(emptyPayload, keyBuf);
this.zeroizeMasterKey();
this.masterKey = keyBuf;
this.credentials.clear();
this.wasPanicLocked = false;
return masterKeyInput ? {} : { generatedKeyHex: keyBuf.toString('hex') };
}
unlock(masterKeyInput: string): void {
if (!fs.existsSync(this.vaultFilePath)) {
throw new Error('Vault is not initialized yet');
}
const keyBuf = parseMasterKey(masterKeyInput);
try {
const rawText = fs.readFileSync(this.vaultFilePath, 'utf8');
const envelope = VaultEnvelopeSchema.parse(JSON.parse(rawText));
const payload = decryptEnvelope(envelope, keyBuf);
this.zeroizeMasterKey();
this.masterKey = keyBuf;
this.credentials = new Map(Object.entries(payload.credentials));
this.wasPanicLocked = false;
} catch (err) {
keyBuf.fill(0);
throw err;
}
}
panicLock(): void {
this.zeroizeMasterKey();
this.credentials.clear();
this.wasPanicLocked = true;
for (const listener of this.panicListeners) {
try {
listener();
} catch {
// Panic lock cleanup must continue across all listeners
}
}
}
rotateMasterKey(newMasterKeyInput?: string): { generatedKeyHex?: string } {
this.assertUnlocked();
const nextKey = newMasterKeyInput
? parseMasterKey(newMasterKeyInput)
: generateMasterKeyBuffer();
const payload: VaultPayload = {
version: 1,
credentials: Object.fromEntries(this.credentials.entries()),
};
try {
this.writeVerifiedVaultAtomic(payload, nextKey);
this.zeroizeMasterKey();
this.masterKey = nextKey;
return newMasterKeyInput ? {} : { generatedKeyHex: nextKey.toString('hex') };
} catch (err) {
nextKey.fill(0);
throw err;
}
}
listMetadata(): VaultCredentialMeta[] {
this.assertUnlocked();
return [...this.credentials.values()].map((cred) => {
const meta: VaultCredentialMeta = {
id: cred.id,
name: cred.name,
type: cred.type,
createdAt: cred.createdAt,
updatedAt: cred.updatedAt,
};
if (cred.type === 'ssh-key') {
meta.fingerprint = cred.fingerprint;
meta.publicKey = cred.publicKey;
meta.hasPassphrase = Boolean(cred.passphrase);
}
return meta;
});
}
hasCredential(id: string): boolean {
if (this.masterKey === null) return false;
return this.credentials.has(id);
}
getSecret(id: string): VaultCredential | undefined {
this.assertUnlocked();
const cred = this.credentials.get(id);
return cred ? structuredClone(cred) : undefined;
}
upsertCredential(input: VaultCredentialInput): VaultCredentialMeta {
this.assertUnlocked();
const now = new Date().toISOString();
const existing = this.credentials.get(input.id);
const candidate = VaultCredentialSchema.parse({
...input,
createdAt: existing?.createdAt ?? input.createdAt ?? now,
updatedAt: now,
});
const nextMap = new Map(this.credentials);
nextMap.set(candidate.id, candidate);
const payload: VaultPayload = {
version: 1,
credentials: Object.fromEntries(nextMap.entries()),
};
this.writeVerifiedVaultAtomic(payload, this.masterKey!);
this.credentials = nextMap;
const meta = this.listMetadata().find((m) => m.id === candidate.id)!;
return meta;
}
deleteCredential(id: string): boolean {
this.assertUnlocked();
if (!this.credentials.has(id)) return false;
const nextMap = new Map(this.credentials);
nextMap.delete(id);
const payload: VaultPayload = {
version: 1,
credentials: Object.fromEntries(nextMap.entries()),
};
this.writeVerifiedVaultAtomic(payload, this.masterKey!);
this.credentials = nextMap;
return true;
}
generateEd25519Credential(options: {
id: string;
name: string;
comment?: string;
passphrase?: string;
}): VaultCredentialMeta {
this.assertUnlocked();
const privateKeyEncoding = options.passphrase
? ({
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: options.passphrase,
} as const)
: ({
type: 'pkcs8',
format: 'pem',
} as const);
const { publicKey: spkiDer, privateKey: privatePem } = crypto.generateKeyPairSync(
'ed25519',
{
publicKeyEncoding: { type: 'spki', format: 'der' },
privateKeyEncoding,
},
);
const { publicKey, fingerprint } = buildSshEd25519PublicAndFingerprint(
spkiDer,
options.comment ?? options.id,
);
return this.upsertCredential({
id: options.id,
name: options.name,
type: 'ssh-key',
privateKey: privatePem,
publicKey,
passphrase: options.passphrase || undefined,
fingerprint,
});
}
private assertUnlocked(): void {
if (this.masterKey === null) {
throw new Error('Vault is locked');
}
}
private zeroizeMasterKey(): void {
if (this.masterKey !== null) {
this.masterKey.fill(0);
this.masterKey = null;
}
}
private writeVerifiedVaultAtomic(payload: VaultPayload, key: Buffer): void {
const dir = path.dirname(this.vaultFilePath);
fs.mkdirSync(dir, { recursive: true });
const envelope = encryptPayload(payload, key);
const serialized = JSON.stringify(envelope, null, 2);
const tmpPath = `${this.vaultFilePath}.tmp.${process.pid}.${Date.now()}`;
const fd = fs.openSync(tmpPath, 'w', 0o600);
try {
fs.writeFileSync(fd, serialized, 'utf8');
fs.fsyncSync(fd);
} finally {
fs.closeSync(fd);
}
// Verify round-trip read + GCM tag before replacing live vault.enc
try {
const readBack = VaultEnvelopeSchema.parse(
JSON.parse(fs.readFileSync(tmpPath, 'utf8')),
);
decryptEnvelope(readBack, key);
fs.renameSync(tmpPath, this.vaultFilePath);
fs.chmodSync(this.vaultFilePath, 0o600);
} catch (err) {
try {
fs.unlinkSync(tmpPath);
} catch {
// Ignore cleanup errors
}
throw err;
}
}
}