feat(vault): keep established secrets active at runtime and require unlock only for modifications

This commit is contained in:
tyuXX 2026-11-26 22:25:55 +00:00
parent c5a5835ae6
commit 10a28bb316
14 changed files with 445 additions and 85 deletions

View file

@ -134,6 +134,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
bootstrapped, bootstrapped,
authenticated: false, authenticated: false,
vaultState: vaultService.state, vaultState: vaultService.state,
vaultRuntimeReady: vaultService.isRuntimeReady,
defaultMobileSafeMode: settings.defaultMobileSafeMode, defaultMobileSafeMode: settings.defaultMobileSafeMode,
theme: settings.theme, theme: settings.theme,
authRequirements, authRequirements,
@ -147,6 +148,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
safeMode: session.safeMode, safeMode: session.safeMode,
elevatedUntil: session.elevatedUntil, elevatedUntil: session.elevatedUntil,
vaultState: vaultService.state, vaultState: vaultService.state,
vaultRuntimeReady: vaultService.isRuntimeReady,
isPanicLocked: vaultService.isPanicLocked, isPanicLocked: vaultService.isPanicLocked,
defaultMobileSafeMode: settings.defaultMobileSafeMode, defaultMobileSafeMode: settings.defaultMobileSafeMode,
theme: settings.theme, theme: settings.theme,
@ -249,6 +251,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
safeMode: result.session.safeMode, safeMode: result.session.safeMode,
elevatedUntil: result.session.elevatedUntil, elevatedUntil: result.session.elevatedUntil,
vaultState: vaultService.state, vaultState: vaultService.state,
vaultRuntimeReady: vaultService.isRuntimeReady,
}); });
} catch (err) { } catch (err) {
rateLimiter.recordFailure('bootstrap', ip); rateLimiter.recordFailure('bootstrap', ip);
@ -332,6 +335,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
safeMode: result.session.safeMode, safeMode: result.session.safeMode,
elevatedUntil: result.session.elevatedUntil, elevatedUntil: result.session.elevatedUntil,
vaultState: vaultService.state, vaultState: vaultService.state,
vaultRuntimeReady: vaultService.isRuntimeReady,
}); });
}); });
@ -803,6 +807,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
safeMode: result.session.safeMode, safeMode: result.session.safeMode,
elevatedUntil: result.session.elevatedUntil, elevatedUntil: result.session.elevatedUntil,
vaultState: vaultService.state, vaultState: vaultService.state,
vaultRuntimeReady: vaultService.isRuntimeReady,
}); });
}); });

View file

@ -16,6 +16,7 @@ import {
requireCsrf, requireCsrf,
requireStepUp, requireStepUp,
} from '../../security/guards.js'; } from '../../security/guards.js';
import type { VaultService } from '../../security/vault.js';
import type { KeyManager } from '../../ssh/key-manager.js'; import type { KeyManager } from '../../ssh/key-manager.js';
import type { KnownHostsService } from '../../ssh/known-hosts.js'; import type { KnownHostsService } from '../../ssh/known-hosts.js';
import type { SSHPool } from '../../ssh/ssh-pool.js'; import type { SSHPool } from '../../ssh/ssh-pool.js';
@ -24,6 +25,7 @@ export interface ServersRouterDeps {
authService: AuthService; authService: AuthService;
configManager: ConfigManager; configManager: ConfigManager;
auditService: AuditService; auditService: AuditService;
vaultService?: VaultService;
knownHosts: KnownHostsService; knownHosts: KnownHostsService;
sshPool: SSHPool; sshPool: SSHPool;
keyManager: KeyManager; keyManager: KeyManager;
@ -41,6 +43,7 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
authService, authService,
configManager, configManager,
auditService, auditService,
vaultService,
knownHosts, knownHosts,
sshPool, sshPool,
keyManager, keyManager,
@ -98,6 +101,13 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
enforceSafeMode, enforceSafeMode,
stepUpGuard, stepUpGuard,
async (req, res) => { async (req, res) => {
if (vaultService && vaultService.state !== 'unlocked') {
res.status(423).json({
error: 'VAULT_LOCKED',
message: 'Vault is locked against modifications. Unlock the Vault before rotating SSH keys.',
});
return;
}
const parsed = z const parsed = z
.object({ .object({
serverIds: z.array(EntityIdSchema).optional(), serverIds: z.array(EntityIdSchema).optional(),

View file

@ -109,9 +109,19 @@ export function createVaultRouter(deps: VaultRouterDeps): {
}); });
}; };
const broadcastVaultState = () => {
wsHub.broadcastAll({
type: 'vault:state',
vaultState: vaultService.state,
vaultRuntimeReady: vaultService.isRuntimeReady,
isPanicLocked: vaultService.isPanicLocked,
});
};
vaultRouter.get('/status', requireAuth(authService), (_req, res) => { vaultRouter.get('/status', requireAuth(authService), (_req, res) => {
res.json({ res.json({
state: vaultService.state, state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady,
isPanicLocked: vaultService.isPanicLocked, isPanicLocked: vaultService.isPanicLocked,
}); });
}); });
@ -128,6 +138,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
notifyConfigReeval(); notifyConfigReeval();
onVaultUnlocked?.(); onVaultUnlocked?.();
onVaultChanged?.('vault-init'); onVaultChanged?.('vault-init');
broadcastVaultState();
auditService.log({ auditService.log({
action: 'vault.init', action: 'vault.init',
actorIp: ip, actorIp: ip,
@ -136,6 +147,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
}); });
res.status(201).json({ res.status(201).json({
state: vaultService.state, state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady,
generatedKeyHex: result.generatedKeyHex, generatedKeyHex: result.generatedKeyHex,
}); });
} catch (err) { } catch (err) {
@ -148,48 +160,102 @@ export function createVaultRouter(deps: VaultRouterDeps): {
vaultRouter.post('/unlock', requireAuth(authService), requireCsrf, (req, res) => { vaultRouter.post('/unlock', requireAuth(authService), requireCsrf, (req, res) => {
const ip = req.clientIp ?? 'unknown'; const ip = req.clientIp ?? 'unknown';
const rate = rateLimiter.check('vault-unlock', ip); const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {});
if (!rate.allowed) {
res.setHeader('Retry-After', String(rate.retryAfterSec));
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
return;
}
const parsed = z.object({ masterKey: z.string().min(1) }).safeParse(req.body);
if (!parsed.success) { if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return; return;
} }
try { const masterKeyInput = parsed.data.masterKey?.trim();
vaultService.unlock(parsed.data.masterKey); if (masterKeyInput && masterKeyInput.length > 0) {
rateLimiter.recordSuccess('vault-unlock', ip); const rate = rateLimiter.check('vault-unlock', ip);
notifyConfigReeval(); if (!rate.allowed) {
onVaultUnlocked?.(); res.setHeader('Retry-After', String(rate.retryAfterSec));
onVaultChanged?.(); res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
auditService.log({ return;
action: 'vault.unlock', }
actorIp: ip,
sessionIdHash: req.authSession!.idHash, try {
status: 'ok', vaultService.unlock(masterKeyInput);
}); rateLimiter.recordSuccess('vault-unlock', ip);
res.json({ notifyConfigReeval();
state: vaultService.state, onVaultUnlocked?.();
isPanicLocked: vaultService.isPanicLocked, onVaultChanged?.();
}); broadcastVaultState();
} catch (err) { auditService.log({
rateLimiter.recordFailure('vault-unlock', ip); action: 'vault.unlock',
auditService.log({ actorIp: ip,
action: 'vault.unlock', sessionIdHash: req.authSession!.idHash,
actorIp: ip, status: 'ok',
sessionIdHash: req.authSession!.idHash, });
status: 'denied', res.json({
}); state: vaultService.state,
res.status(403).json({ runtimeReady: vaultService.isRuntimeReady,
error: 'VAULT_UNLOCK_FAILED', isPanicLocked: vaultService.isPanicLocked,
message: err instanceof Error ? err.message : 'Invalid master key or corrupted vault', });
}); } catch (err) {
rateLimiter.recordFailure('vault-unlock', ip);
auditService.log({
action: 'vault.unlock',
actorIp: ip,
sessionIdHash: req.authSession!.idHash,
status: 'denied',
});
res.status(403).json({
error: 'VAULT_UNLOCK_FAILED',
message: err instanceof Error ? err.message : 'Invalid master key or corrupted vault',
});
}
return;
} }
if (!vaultService.isRuntimeReady || vaultService.isPanicLocked) {
res.status(423).json({
error: 'VAULT_MASTER_KEY_REQUIRED',
message: 'Enter your 32-byte Master Key to unseal the vault.',
});
return;
}
stepUpGuard(req, res, () => {
try {
vaultService.unlockForModifications();
broadcastVaultState();
auditService.log({
action: 'vault.unlock',
actorIp: ip,
sessionIdHash: req.authSession!.idHash,
status: 'ok',
details: { mode: 'session' },
});
res.json({
state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady,
isPanicLocked: vaultService.isPanicLocked,
});
} catch (err) {
res.status(423).json({
error: 'VAULT_MASTER_KEY_REQUIRED',
message: err instanceof Error ? err.message : 'Master key is required to unseal vault',
});
}
});
});
vaultRouter.post('/lock', requireAuth(authService), requireCsrf, (req, res) => {
vaultService.lockForModifications();
broadcastVaultState();
auditService.log({
action: 'vault.lock',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
status: 'ok',
});
res.json({
state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady,
isPanicLocked: vaultService.isPanicLocked,
});
}); });
// Panic Lock is ALWAYS reachable when authenticated + CSRF verified (even under Safe Mode!) // Panic Lock is ALWAYS reachable when authenticated + CSRF verified (even under Safe Mode!)
@ -211,12 +277,19 @@ export function createVaultRouter(deps: VaultRouterDeps): {
}); });
vaultRouter.get('/credentials', requireAuth(authService), (_req, res) => { vaultRouter.get('/credentials', requireAuth(authService), (_req, res) => {
if (vaultService.state !== 'unlocked') { if (!vaultService.isRuntimeReady) {
res.json({ state: vaultService.state, credentials: [] }); res.json({
state: vaultService.state,
runtimeReady: false,
isPanicLocked: vaultService.isPanicLocked,
credentials: [],
});
return; return;
} }
res.json({ res.json({
state: vaultService.state, state: vaultService.state,
runtimeReady: true,
isPanicLocked: vaultService.isPanicLocked,
credentials: vaultService.listMetadata(), credentials: vaultService.listMetadata(),
}); });
}); });

View file

@ -187,6 +187,7 @@ export class WsHub {
this.sendFrame(ws, { this.sendFrame(ws, {
type: 'hello', type: 'hello',
vaultState: this.vaultService.state, vaultState: this.vaultService.state,
vaultRuntimeReady: this.vaultService.isRuntimeReady,
safeMode: session.safeMode, safeMode: session.safeMode,
elevatedUntil: session.elevatedUntil, elevatedUntil: session.elevatedUntil,
}); });

View file

@ -82,7 +82,9 @@ export async function createGCoordinatorServer(
const db = openDatabase(dbPath); const db = openDatabase(dbPath);
const auditService = new AuditService(db); const auditService = new AuditService(db);
const vaultService = new VaultService(vaultPath); const vaultService = new VaultService(vaultPath, {
keyFilePath: path.join(dataDir, 'vault.key'),
});
const recoveryStore = new EmergencyRecoveryService(dataDir); const recoveryStore = new EmergencyRecoveryService(dataDir);
const rateLimiter = new RateLimiter(); const rateLimiter = new RateLimiter();
const configManager = new ConfigManager(configDir, db, vaultService); const configManager = new ConfigManager(configDir, db, vaultService);
@ -98,11 +100,13 @@ export async function createGCoordinatorServer(
const backupKey = configManager.getSettings().security.enableEmergencySecretsBackup const backupKey = configManager.getSettings().security.enableEmergencySecretsBackup
? recoveryStore.readSavedMasterKeyHex() ? recoveryStore.readSavedMasterKeyHex()
: undefined; : undefined;
const unlockResult = vaultService.tryAutoUnlockFromEnvOrSecret({ const runtimeInit = vaultService.initRuntime({
secretFilePath: options.secretFilePath, secretFilePath: options.secretFilePath,
envKey: options.envMasterKey || backupKey, envKey: options.envMasterKey,
backupKey,
autoCreateIfMissing: true,
}); });
if (unlockResult.unlocked) { if (runtimeInit.runtimeReady) {
configManager.recomputeWarnings(); configManager.recomputeWarnings();
if (authService.isBootstrapped()) { if (authService.isBootstrapped()) {
authService.syncRecovery(); authService.syncRecovery();
@ -177,6 +181,8 @@ export async function createGCoordinatorServer(
for (const frame of customSystemsEngine.getStreamReplayFrames(jobId)) { for (const frame of customSystemsEngine.getStreamReplayFrames(jobId)) {
ctx.send(frame); ctx.send(frame);
} }
} else if (channel === 'metrics') {
ctx.send({ type: 'servers:state', states: sshPool.getStates() });
} }
}); });
@ -283,7 +289,11 @@ export async function createGCoordinatorServer(
); );
app.get('/api/healthz', (_req, res) => { app.get('/api/healthz', (_req, res) => {
res.json({ ok: true, vaultState: vaultService.state }); res.json({
ok: true,
vaultState: vaultService.state,
vaultRuntimeReady: vaultService.isRuntimeReady,
});
}); });
app.use( app.use(
@ -338,6 +348,7 @@ export async function createGCoordinatorServer(
authService, authService,
configManager, configManager,
auditService, auditService,
vaultService,
knownHosts, knownHosts,
sshPool, sshPool,
keyManager, keyManager,

View file

@ -193,7 +193,7 @@ export class ConfigManager {
for (const server of this.servers.values()) { for (const server of this.servers.values()) {
const relPath = `servers/${server.id}.json`; const relPath = `servers/${server.id}.json`;
if (this.vault && this.vault.state === 'unlocked') { if (this.vault && this.vault.isRuntimeReady) {
if (!this.vault.hasCredential(server.credentialId)) { if (!this.vault.hasCredential(server.credentialId)) {
next.push({ next.push({
filePath: relPath, filePath: relPath,
@ -297,7 +297,7 @@ export class ConfigManager {
// 3. Alerts cross-references // 3. Alerts cross-references
const channelIds = new Set(this.alerts.channels.map((c) => c.id)); const channelIds = new Set(this.alerts.channels.map((c) => c.id));
if (this.vault && this.vault.state === 'unlocked') { if (this.vault && this.vault.isRuntimeReady) {
for (const ch of this.alerts.channels) { for (const ch of this.alerts.channels) {
if (!this.vault.hasCredential(ch.secretRef)) { if (!this.vault.hasCredential(ch.secretRef)) {
next.push({ next.push({

View file

@ -36,6 +36,7 @@ export interface MonitoringTickEvent {
interface ServerTimers { interface ServerTimers {
metricTimer: NodeJS.Timeout | null; metricTimer: NodeJS.Timeout | null;
warmupTimer: NodeJS.Timeout | null;
probeTimers: Map<string, NodeJS.Timeout>; probeTimers: Map<string, NodeJS.Timeout>;
pollingMetrics: boolean; pollingMetrics: boolean;
} }
@ -68,6 +69,7 @@ export class MonitoringService {
start(): void { start(): void {
this.stopped = false; this.stopped = false;
this.hydrateLatestFromDb();
this.syncServers(); this.syncServers();
if (!this.maintenanceTimer) { if (!this.maintenanceTimer) {
this.runMaintenance(); this.runMaintenance();
@ -81,6 +83,7 @@ export class MonitoringService {
stopAll(): void { stopAll(): void {
for (const timers of this.serverTimers.values()) { for (const timers of this.serverTimers.values()) {
if (timers.metricTimer) clearInterval(timers.metricTimer); if (timers.metricTimer) clearInterval(timers.metricTimer);
if (timers.warmupTimer) clearTimeout(timers.warmupTimer);
for (const pt of timers.probeTimers.values()) clearInterval(pt); for (const pt of timers.probeTimers.values()) clearInterval(pt);
} }
this.serverTimers.clear(); this.serverTimers.clear();
@ -100,7 +103,7 @@ export class MonitoringService {
this.stopAll(); this.stopAll();
this.sshPool.syncWithConfig(); this.sshPool.syncWithConfig();
if (this.vaultService.state !== 'unlocked') { if (!this.vaultService.isRuntimeReady) {
return; return;
} }
@ -117,7 +120,7 @@ export class MonitoringService {
async pollServerNow(serverId: string): Promise<MonitoringTickEvent | null> { async pollServerNow(serverId: string): Promise<MonitoringTickEvent | null> {
const server = this.configManager.getServer(serverId); const server = this.configManager.getServer(serverId);
if (!server || !server.enabled || this.vaultService.state !== 'unlocked') { if (!server || !server.enabled || !this.vaultService.isRuntimeReady) {
return null; return null;
} }
return this.executeMetricPoll(server); return this.executeMetricPoll(server);
@ -266,13 +269,30 @@ export class MonitoringService {
private scheduleServer(server: ServerConfig): void { private scheduleServer(server: ServerConfig): void {
const timers: ServerTimers = { const timers: ServerTimers = {
metricTimer: null, metricTimer: null,
warmupTimer: null,
probeTimers: new Map(), probeTimers: new Map(),
pollingMetrics: false, pollingMetrics: false,
}; };
this.serverTimers.set(server.id, timers); this.serverTimers.set(server.id, timers);
// Kick initial poll asynchronously without delaying syncServers() // Kick initial poll asynchronously without delaying syncServers()
void this.executeMetricPoll(server); const hadDelta = this.deltaStates.has(server.id);
void this.executeMetricPoll(server).then((ev) => {
if (
ev &&
!hadDelta &&
!this.stopped &&
this.serverTimers.get(server.id) === timers &&
server.pollIntervalSec >= 3
) {
const wt = setTimeout(() => {
timers.warmupTimer = null;
void this.executeMetricPoll(server);
}, 1000);
wt.unref();
timers.warmupTimer = wt;
}
});
timers.metricTimer = setInterval(() => { timers.metricTimer = setInterval(() => {
void this.executeMetricPoll(server); void this.executeMetricPoll(server);
@ -293,7 +313,7 @@ export class MonitoringService {
private async executeMetricPoll( private async executeMetricPoll(
server: ServerConfig, server: ServerConfig,
): Promise<MonitoringTickEvent | null> { ): Promise<MonitoringTickEvent | null> {
if (this.stopped || this.vaultService.state !== 'unlocked') return null; if (this.stopped || !this.vaultService.isRuntimeReady) return null;
const timerState = this.serverTimers.get(server.id); const timerState = this.serverTimers.get(server.id);
if (timerState?.pollingMetrics) return null; if (timerState?.pollingMetrics) return null;
@ -362,7 +382,7 @@ export class MonitoringService {
} }
private async executeProbe(server: ServerConfig, probeId: string): Promise<void> { private async executeProbe(server: ServerConfig, probeId: string): Promise<void> {
if (this.stopped || this.vaultService.state !== 'unlocked') return; if (this.stopped || !this.vaultService.isRuntimeReady) return;
const probe = server.probes.find((p) => p.id === probeId); const probe = server.probes.find((p) => p.id === probeId);
if (!probe || !probe.enabled) return; if (!probe || !probe.enabled) return;
@ -392,6 +412,73 @@ export class MonitoringService {
this.latest.set(server.id, prevLatest); this.latest.set(server.id, prevLatest);
} }
private hydrateLatestFromDb(): void {
for (const server of this.configManager.listServers()) {
if (this.latest.has(server.id)) continue;
const row = this.db
.prepare(
`SELECT ts, cpu_pct AS cpuPct, mem_used_mb AS memUsedMb, mem_total_mb AS memTotalMb,
net_rx_bps AS netRxBps, net_tx_bps AS netTxBps, load_1m AS load1m, uptime_sec AS uptimeSec
FROM metrics_raw
WHERE server_id = ?
ORDER BY ts DESC
LIMIT 1`,
)
.get(server.id) as MetricSample | undefined;
const disks = this.db
.prepare(
`SELECT mount_point AS mountPoint, fs_type AS fsType, used_mb AS usedMb, total_mb AS totalMb, used_pct AS usedPct
FROM metrics_disks
WHERE server_id = ? AND ts = (SELECT MAX(ts) FROM metrics_disks WHERE server_id = ?)
ORDER BY mount_point ASC`,
)
.all(server.id, server.id) as DiskSample[];
const probeRows = this.db
.prepare(
`SELECT p.probe_id AS probeId, p.ok AS okInt, p.status_code AS statusCode,
p.latency_ms AS latencyMs, p.error AS error
FROM probe_results p
INNER JOIN (
SELECT probe_id, MAX(ts) AS max_ts
FROM probe_results
WHERE server_id = ?
GROUP BY probe_id
) latest ON latest.probe_id = p.probe_id AND latest.max_ts = p.ts
WHERE p.server_id = ?`,
)
.all(server.id, server.id) as Array<{
probeId: string;
okInt: number;
statusCode: number | null;
latencyMs: number;
error: string | null;
}>;
if (!row && disks.length === 0 && probeRows.length === 0) continue;
const probes: Record<string, ProbeSample> = {};
for (const p of probeRows) {
probes[p.probeId] = {
probeId: p.probeId,
ok: p.okInt === 1,
statusCode: p.statusCode ?? undefined,
latencyMs: p.latencyMs,
error: p.error ?? undefined,
};
}
this.latest.set(server.id, {
serverId: server.id,
sample: row,
disks,
probes,
});
}
}
private persistMetricSample( private persistMetricSample(
serverId: string, serverId: string,
sample: MetricSample, sample: MetricSample,

View file

@ -97,15 +97,13 @@ export class EmergencyRecoveryService {
const existing = this.readBundle(); const existing = this.readBundle();
const nowIso = new Date().toISOString(); const nowIso = new Date().toISOString();
const masterKeyHex = const masterKeyHex = opts.vault.isRuntimeReady
opts.vault.state === 'unlocked' ? opts.vault.exportMasterKeyHex()
? opts.vault.exportMasterKeyHex() : existing?.vaultMasterKeyHex ?? null;
: existing?.vaultMasterKeyHex ?? null;
const vaultCredentials = const vaultCredentials = opts.vault.isRuntimeReady
opts.vault.state === 'unlocked' ? opts.vault.exportAllCredentials()
? opts.vault.exportAllCredentials() : existing?.vaultCredentials ?? {};
: existing?.vaultCredentials ?? {};
// Merge saved plaintext passwords safely across updates // Merge saved plaintext passwords safely across updates
const prevPwById = new Map<string, SavedPasswordEntry>(); const prevPwById = new Map<string, SavedPasswordEntry>();

View file

@ -101,13 +101,24 @@ export type VaultCredentialInput = DistributiveOmit<
updatedAt?: string; updatedAt?: string;
}; };
export interface VaultServiceOptions {
keyFilePath?: string;
}
export class VaultService { export class VaultService {
private masterKey: Buffer | null = null; private masterKey: Buffer | null = null;
private credentials = new Map<string, VaultCredential>(); private credentials = new Map<string, VaultCredential>();
private writeUnlocked = false;
private autoInitializedEmpty = false;
private wasPanicLocked = false; private wasPanicLocked = false;
private readonly keyFilePath: string | null;
private readonly panicListeners = new Set<() => void>(); private readonly panicListeners = new Set<() => void>();
constructor(private readonly vaultFilePath: string) { constructor(
private readonly vaultFilePath: string,
options: VaultServiceOptions = {},
) {
this.keyFilePath = options.keyFilePath ? path.resolve(options.keyFilePath) : null;
this.wasPanicLocked = fs.existsSync(this.panicLockMarkerPath()); this.wasPanicLocked = fs.existsSync(this.panicLockMarkerPath());
} }
@ -130,8 +141,12 @@ export class VaultService {
return this.vaultFilePath; return this.vaultFilePath;
} }
get isRuntimeReady(): boolean {
return this.masterKey !== null;
}
get state(): VaultState { get state(): VaultState {
if (this.masterKey !== null) return 'unlocked'; if (this.masterKey !== null && this.writeUnlocked) return 'unlocked';
return fs.existsSync(this.vaultFilePath) ? 'locked' : 'uninitialized'; return fs.existsSync(this.vaultFilePath) ? 'locked' : 'uninitialized';
} }
@ -146,6 +161,95 @@ export class VaultService {
}; };
} }
initRuntime(options: {
secretFilePath?: string;
envKey?: string;
backupKey?: string;
autoCreateIfMissing?: boolean;
}): { runtimeReady: boolean; initialized?: boolean; reason?: string } {
// Security invariant: never silently re-read disk secrets after Emergency Panic Lock
if (this.isPanicLocked) {
return { runtimeReady: false, reason: 'panic_locked' };
}
const candidates: string[] = [];
if (options.secretFilePath && fs.existsSync(options.secretFilePath)) {
const val = fs.readFileSync(options.secretFilePath, 'utf8').trim();
if (val) candidates.push(val);
}
if (options.envKey && options.envKey.trim().length > 0) {
candidates.push(options.envKey.trim());
}
if (this.keyFilePath && fs.existsSync(this.keyFilePath)) {
const val = fs.readFileSync(this.keyFilePath, 'utf8').trim();
if (val) candidates.push(val);
}
if (options.backupKey && options.backupKey.trim().length > 0) {
candidates.push(options.backupKey.trim());
}
if (fs.existsSync(this.vaultFilePath)) {
if (candidates.length === 0) {
return { runtimeReady: false, reason: 'no_key' };
}
let envelope: VaultEnvelope;
try {
const rawText = fs.readFileSync(this.vaultFilePath, 'utf8');
envelope = VaultEnvelopeSchema.parse(JSON.parse(rawText));
} catch (err) {
return {
runtimeReady: false,
reason: err instanceof Error ? err.message : 'decrypt_failed',
};
}
for (const candidate of candidates) {
let keyBuf: Buffer | null = null;
try {
keyBuf = parseMasterKey(candidate);
const payload = decryptEnvelope(envelope, keyBuf);
this.zeroizeMasterKey();
this.masterKey = keyBuf;
this.credentials = new Map(Object.entries(payload.credentials));
this.writeUnlocked = false;
this.autoInitializedEmpty = false;
this.setPanicLockMarker(false);
this.persistKeyFileIfConfigured(keyBuf);
return { runtimeReady: true };
} catch {
keyBuf?.fill(0);
}
}
return { runtimeReady: false, reason: 'decrypt_failed' };
}
if (!options.autoCreateIfMissing && candidates.length === 0) {
return { runtimeReady: false, reason: 'no_key' };
}
let keyBuf: Buffer | null = null;
try {
keyBuf = candidates[0] ? parseMasterKey(candidates[0]) : generateMasterKeyBuffer();
const emptyPayload: VaultPayload = { version: 1, credentials: {} };
this.writeVerifiedVaultAtomic(emptyPayload, keyBuf);
this.zeroizeMasterKey();
this.masterKey = keyBuf;
this.credentials.clear();
this.writeUnlocked = false;
this.autoInitializedEmpty = true;
this.setPanicLockMarker(false);
this.persistKeyFileIfConfigured(keyBuf);
return { runtimeReady: true, initialized: true };
} catch (err) {
keyBuf?.fill(0);
return {
runtimeReady: false,
reason: err instanceof Error ? err.message : 'init_failed',
};
}
}
tryAutoUnlockFromEnvOrSecret(options: { tryAutoUnlockFromEnvOrSecret(options: {
secretFilePath?: string; secretFilePath?: string;
envKey?: string; envKey?: string;
@ -182,7 +286,9 @@ export class VaultService {
} }
initializeNewVault(masterKeyInput?: string): { generatedKeyHex?: string } { initializeNewVault(masterKeyInput?: string): { generatedKeyHex?: string } {
if (fs.existsSync(this.vaultFilePath)) { const allowOverwriteAutoEmpty =
this.autoInitializedEmpty && this.credentials.size === 0;
if (fs.existsSync(this.vaultFilePath) && !allowOverwriteAutoEmpty) {
throw new Error('Vault file already exists; unlock it instead of initializing'); throw new Error('Vault file already exists; unlock it instead of initializing');
} }
@ -195,7 +301,10 @@ export class VaultService {
this.zeroizeMasterKey(); this.zeroizeMasterKey();
this.masterKey = keyBuf; this.masterKey = keyBuf;
this.credentials.clear(); this.credentials.clear();
this.writeUnlocked = true;
this.autoInitializedEmpty = false;
this.setPanicLockMarker(false); this.setPanicLockMarker(false);
this.persistKeyFileIfConfigured(keyBuf);
return masterKeyInput ? {} : { generatedKeyHex: keyBuf.toString('hex') }; return masterKeyInput ? {} : { generatedKeyHex: keyBuf.toString('hex') };
} }
@ -214,16 +323,32 @@ export class VaultService {
this.zeroizeMasterKey(); this.zeroizeMasterKey();
this.masterKey = keyBuf; this.masterKey = keyBuf;
this.credentials = new Map(Object.entries(payload.credentials)); this.credentials = new Map(Object.entries(payload.credentials));
this.writeUnlocked = true;
this.autoInitializedEmpty = false;
this.setPanicLockMarker(false); this.setPanicLockMarker(false);
this.persistKeyFileIfConfigured(keyBuf);
} catch (err) { } catch (err) {
keyBuf.fill(0); keyBuf.fill(0);
throw err; throw err;
} }
} }
unlockForModifications(): void {
if (this.masterKey === null || this.isPanicLocked) {
throw new Error('Master key is required to unseal vault');
}
this.writeUnlocked = true;
}
lockForModifications(): void {
this.writeUnlocked = false;
}
panicLock(): void { panicLock(): void {
this.zeroizeMasterKey(); this.zeroizeMasterKey();
this.credentials.clear(); this.credentials.clear();
this.writeUnlocked = false;
this.autoInitializedEmpty = false;
this.setPanicLockMarker(true); this.setPanicLockMarker(true);
for (const listener of this.panicListeners) { for (const listener of this.panicListeners) {
@ -236,7 +361,7 @@ export class VaultService {
} }
rotateMasterKey(newMasterKeyInput?: string): { generatedKeyHex?: string } { rotateMasterKey(newMasterKeyInput?: string): { generatedKeyHex?: string } {
this.assertUnlocked(); this.assertWriteUnlocked();
const nextKey = newMasterKeyInput const nextKey = newMasterKeyInput
? parseMasterKey(newMasterKeyInput) ? parseMasterKey(newMasterKeyInput)
: generateMasterKeyBuffer(); : generateMasterKeyBuffer();
@ -250,6 +375,8 @@ export class VaultService {
this.writeVerifiedVaultAtomic(payload, nextKey); this.writeVerifiedVaultAtomic(payload, nextKey);
this.zeroizeMasterKey(); this.zeroizeMasterKey();
this.masterKey = nextKey; this.masterKey = nextKey;
this.writeUnlocked = true;
this.persistKeyFileIfConfigured(nextKey);
return newMasterKeyInput ? {} : { generatedKeyHex: nextKey.toString('hex') }; return newMasterKeyInput ? {} : { generatedKeyHex: nextKey.toString('hex') };
} catch (err) { } catch (err) {
nextKey.fill(0); nextKey.fill(0);
@ -258,7 +385,7 @@ export class VaultService {
} }
listMetadata(): VaultCredentialMeta[] { listMetadata(): VaultCredentialMeta[] {
this.assertUnlocked(); this.assertRuntimeReady();
return [...this.credentials.values()].map((cred) => { return [...this.credentials.values()].map((cred) => {
const meta: VaultCredentialMeta = { const meta: VaultCredentialMeta = {
id: cred.id, id: cred.id,
@ -281,8 +408,14 @@ export class VaultService {
return this.credentials.has(id); return this.credentials.has(id);
} }
getRuntimeSecret(id: string): VaultCredential | undefined {
this.assertRuntimeReady();
const cred = this.credentials.get(id);
return cred ? structuredClone(cred) : undefined;
}
getSecret(id: string): VaultCredential | undefined { getSecret(id: string): VaultCredential | undefined {
this.assertUnlocked(); this.assertWriteUnlocked();
const cred = this.credentials.get(id); const cred = this.credentials.get(id);
return cred ? structuredClone(cred) : undefined; return cred ? structuredClone(cred) : undefined;
} }
@ -292,7 +425,7 @@ export class VaultService {
} }
exportAllCredentials(): Record<string, VaultCredential> { exportAllCredentials(): Record<string, VaultCredential> {
this.assertUnlocked(); this.assertRuntimeReady();
const out: Record<string, VaultCredential> = {}; const out: Record<string, VaultCredential> = {};
for (const [id, cred] of this.credentials.entries()) { for (const [id, cred] of this.credentials.entries()) {
out[id] = structuredClone(cred); out[id] = structuredClone(cred);
@ -301,7 +434,8 @@ export class VaultService {
} }
upsertCredential(input: VaultCredentialInput): VaultCredentialMeta { upsertCredential(input: VaultCredentialInput): VaultCredentialMeta {
this.assertUnlocked(); this.assertWriteUnlocked();
this.autoInitializedEmpty = false;
const now = new Date().toISOString(); const now = new Date().toISOString();
const existing = this.credentials.get(input.id); const existing = this.credentials.get(input.id);
const candidate = VaultCredentialSchema.parse({ const candidate = VaultCredentialSchema.parse({
@ -325,7 +459,7 @@ export class VaultService {
} }
deleteCredential(id: string): boolean { deleteCredential(id: string): boolean {
this.assertUnlocked(); this.assertWriteUnlocked();
if (!this.credentials.has(id)) return false; if (!this.credentials.has(id)) return false;
const nextMap = new Map(this.credentials); const nextMap = new Map(this.credentials);
@ -346,7 +480,8 @@ export class VaultService {
comment?: string; comment?: string;
passphrase?: string; passphrase?: string;
}): VaultCredentialMeta { }): VaultCredentialMeta {
this.assertUnlocked(); this.assertWriteUnlocked();
this.autoInitializedEmpty = false;
const keyPair = options.passphrase const keyPair = options.passphrase
? ssh2.utils.generateKeyPairSync('ed25519', { ? ssh2.utils.generateKeyPairSync('ed25519', {
@ -373,12 +508,37 @@ export class VaultService {
}); });
} }
private assertUnlocked(): void { private assertRuntimeReady(): void {
if (this.masterKey === null) { if (this.masterKey === null) {
throw new Error('Vault is locked'); throw new Error('Vault is locked');
} }
} }
private assertWriteUnlocked(): void {
if (this.masterKey === null || !this.writeUnlocked) {
throw new Error('Vault is locked');
}
}
private persistKeyFileIfConfigured(key: Buffer): void {
const siblingKeyFile = path.join(path.dirname(this.vaultFilePath), 'vault.key');
const targetPath =
this.keyFilePath ?? (fs.existsSync(siblingKeyFile) ? siblingKeyFile : null);
if (!targetPath) return;
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
const tmpPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
const fd = fs.openSync(tmpPath, 'w', 0o600);
try {
fs.writeFileSync(fd, `${key.toString('hex')}\n`, 'utf8');
fs.fsyncSync(fd);
} finally {
fs.closeSync(fd);
}
fs.renameSync(tmpPath, targetPath);
fs.chmodSync(targetPath, 0o600);
}
private zeroizeMasterKey(): void { private zeroizeMasterKey(): void {
if (this.masterKey !== null) { if (this.masterKey !== null) {
this.masterKey.fill(0); this.masterKey.fill(0);

View file

@ -161,8 +161,9 @@ export class KeyManager {
); );
} }
const vaultCreds = const vaultCreds = this.vaultService.isRuntimeReady
this.vaultService.state === 'unlocked' ? this.vaultService.listMetadata() : []; ? this.vaultService.listMetadata()
: [];
const entries = parseAuthorizedKeys(res.stdout, vaultCreds, server.credentialId); const entries = parseAuthorizedKeys(res.stdout, vaultCreds, server.credentialId);
return { raw: res.stdout, entries }; return { raw: res.stdout, entries };
} }
@ -172,7 +173,7 @@ export class KeyManager {
credentialId: string, credentialId: string,
actor = { ip: 'hub', sessionIdHash: null as string | null }, actor = { ip: 'hub', sessionIdHash: null as string | null },
): Promise<{ deployed: boolean; alreadyPresent: boolean; fingerprint: string }> { ): Promise<{ deployed: boolean; alreadyPresent: boolean; fingerprint: string }> {
const cred = this.vaultService.getSecret(credentialId); const cred = this.vaultService.getRuntimeSecret(credentialId);
if (!cred || cred.type !== 'ssh-key' || !cred.publicKey) { if (!cred || cred.type !== 'ssh-key' || !cred.publicKey) {
throw new Error(`Vault credential "${credentialId}" is not an SSH key with a publicKey`); throw new Error(`Vault credential "${credentialId}" is not an SSH key with a publicKey`);
} }
@ -210,7 +211,7 @@ export class KeyManager {
throw new Error(`Unknown server "${serverId}"`); throw new Error(`Unknown server "${serverId}"`);
} }
const activeCred = this.vaultService.getSecret(server.credentialId); const activeCred = this.vaultService.getRuntimeSecret(server.credentialId);
const activeFp = const activeFp =
activeCred?.type === 'ssh-key' activeCred?.type === 'ssh-key'
? activeCred.fingerprint ?? ? activeCred.fingerprint ??

View file

@ -121,7 +121,7 @@ export class SSHPool {
this.updateState(serverId, { status: 'disabled' }); this.updateState(serverId, { status: 'disabled' });
throw new Error(`Server "${serverId}" is disabled`); throw new Error(`Server "${serverId}" is disabled`);
} }
if (this.vaultService.state !== 'unlocked') { if (!this.vaultService.isRuntimeReady) {
this.updateState(serverId, { this.updateState(serverId, {
status: 'vault_locked', status: 'vault_locked',
lastError: 'Vault is locked', lastError: 'Vault is locked',
@ -170,7 +170,7 @@ export class SSHPool {
if (opts.sudo) { if (opts.sudo) {
let sudoPassword: string | undefined; let sudoPassword: string | undefined;
if (server.sudoCredentialId) { if (server.sudoCredentialId) {
const sudoCred = this.vaultService.getSecret(server.sudoCredentialId); const sudoCred = this.vaultService.getRuntimeSecret(server.sudoCredentialId);
if (sudoCred && (sudoCred.type === 'sudo-password' || sudoCred.type === 'ssh-password')) { if (sudoCred && (sudoCred.type === 'sudo-password' || sudoCred.type === 'ssh-password')) {
sudoPassword = sudoCred.password; sudoPassword = sudoCred.password;
} }
@ -404,7 +404,7 @@ export class SSHPool {
privateKey: string, privateKey: string,
passphrase?: string, passphrase?: string,
): Promise<void> { ): Promise<void> {
if (this.vaultService.state !== 'unlocked') { if (!this.vaultService.isRuntimeReady) {
throw new Error('Vault is locked'); throw new Error('Vault is locked');
} }
@ -509,14 +509,21 @@ export class SSHPool {
syncWithConfig(): void { syncWithConfig(): void {
const activeIds = new Set<string>(); const activeIds = new Set<string>();
const runtimeReady = this.vaultService.isRuntimeReady;
for (const server of this.configManager.listServers()) { for (const server of this.configManager.listServers()) {
activeIds.add(server.id); activeIds.add(server.id);
const prev = this.states.get(server.id);
if (!server.enabled) { if (!server.enabled) {
this.closeServer(server.id); this.closeServer(server.id);
this.updateState(server.id, { status: 'disabled' }); this.updateState(server.id, { status: 'disabled' });
} else if (!this.states.has(server.id)) { } else if (
!prev ||
(runtimeReady && prev.status === 'vault_locked') ||
(!runtimeReady && prev.status !== 'vault_locked')
) {
this.updateState(server.id, { this.updateState(server.id, {
status: this.vaultService.state === 'unlocked' ? 'disconnected' : 'vault_locked', status: runtimeReady ? 'disconnected' : 'vault_locked',
lastError: runtimeReady ? undefined : prev?.lastError,
}); });
} }
} }
@ -597,7 +604,7 @@ export class SSHPool {
server: ServerConfig, server: ServerConfig,
visited: Set<string>, visited: Set<string>,
): Promise<Client> { ): Promise<Client> {
const cred = this.vaultService.getSecret(server.credentialId); const cred = this.vaultService.getRuntimeSecret(server.credentialId);
if (!cred || (cred.type !== 'ssh-key' && cred.type !== 'ssh-password')) { if (!cred || (cred.type !== 'ssh-key' && cred.type !== 'ssh-password')) {
const msg = `Missing or incompatible SSH credential "${server.credentialId}" in Vault`; const msg = `Missing or incompatible SSH credential "${server.credentialId}" in Vault`;
this.updateState(server.id, { status: 'auth_error', lastError: msg }); this.updateState(server.id, { status: 'auth_error', lastError: msg });
@ -747,7 +754,7 @@ export class SSHPool {
? 'host_key_mismatch' ? 'host_key_mismatch'
: tofu : tofu
? 'tofu_pending' ? 'tofu_pending'
: this.vaultService.state !== 'unlocked' : !this.vaultService.isRuntimeReady
? 'vault_locked' ? 'vault_locked'
: 'disconnected'; : 'disconnected';
@ -833,7 +840,7 @@ export class SSHPool {
tofuPending: tofu, tofuPending: tofu,
}; };
} }
if (this.vaultService.state !== 'unlocked') { if (!this.vaultService.isRuntimeReady) {
return { return {
...(existing ?? { serverId: server.id }), ...(existing ?? { serverId: server.id }),
status: 'vault_locked', status: 'vault_locked',

View file

@ -99,7 +99,7 @@ export class TunnelManager {
} }
async syncAutoStart(): Promise<void> { async syncAutoStart(): Promise<void> {
if (this.vaultService.state !== 'unlocked') return; if (!this.vaultService.isRuntimeReady) return;
for (const server of this.configManager.listServers()) { for (const server of this.configManager.listServers()) {
if (!server.enabled) continue; if (!server.enabled) continue;
for (const tunnel of server.tunnels) { for (const tunnel of server.tunnels) {
@ -121,7 +121,7 @@ export class TunnelManager {
if (!tunnel) { if (!tunnel) {
throw new Error(`Tunnel "${tunnelId}" not found on server "${serverId}"`); throw new Error(`Tunnel "${tunnelId}" not found on server "${serverId}"`);
} }
if (this.vaultService.state !== 'unlocked') { if (!this.vaultService.isRuntimeReady) {
throw new Error('Vault must be unlocked before starting SSH tunnels'); throw new Error('Vault must be unlocked before starting SSH tunnels');
} }

View file

@ -525,7 +525,7 @@ export class CustomSystemsEngine {
syncBackgroundChecks(): void { syncBackgroundChecks(): void {
this.stopBackgroundChecks(); this.stopBackgroundChecks();
if (this.vaultService.state !== 'unlocked') return; if (!this.vaultService.isRuntimeReady) return;
for (const server of this.configManager.listServers()) { for (const server of this.configManager.listServers()) {
if (!server.enabled) continue; if (!server.enabled) continue;
@ -534,7 +534,7 @@ export class CustomSystemsEngine {
if (!sys?.backgroundCheckSec) continue; if (!sys?.backgroundCheckSec) continue;
const key = `${server.id}:${sys.id}`; const key = `${server.id}:${sys.id}`;
const timer = setInterval(() => { const timer = setInterval(() => {
if (this.vaultService.state !== 'unlocked') return; if (!this.vaultService.isRuntimeReady) return;
void this.getServerSystem(server.id, sys.id, { forceRefresh: true }).catch( void this.getServerSystem(server.id, sys.id, { forceRefresh: true }).catch(
() => undefined, () => undefined,
); );

View file

@ -132,9 +132,16 @@ export type ServerWsFrame =
| { | {
type: 'hello'; type: 'hello';
vaultState: VaultState; vaultState: VaultState;
vaultRuntimeReady?: boolean;
safeMode: boolean; safeMode: boolean;
elevatedUntil: number | null; elevatedUntil: number | null;
} }
| {
type: 'vault:state';
vaultState: VaultState;
vaultRuntimeReady: boolean;
isPanicLocked: boolean;
}
| { | {
type: 'config:updated'; type: 'config:updated';
entityType: 'server' | 'system' | 'workflow' | 'snippets' | 'alerts' | 'settings' | 'all'; entityType: 'server' | 'system' | 'workflow' | 'snippets' | 'alerts' | 'settings' | 'all';