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

View file

@ -16,6 +16,7 @@ import {
requireCsrf,
requireStepUp,
} from '../../security/guards.js';
import type { VaultService } from '../../security/vault.js';
import type { KeyManager } from '../../ssh/key-manager.js';
import type { KnownHostsService } from '../../ssh/known-hosts.js';
import type { SSHPool } from '../../ssh/ssh-pool.js';
@ -24,6 +25,7 @@ export interface ServersRouterDeps {
authService: AuthService;
configManager: ConfigManager;
auditService: AuditService;
vaultService?: VaultService;
knownHosts: KnownHostsService;
sshPool: SSHPool;
keyManager: KeyManager;
@ -41,6 +43,7 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
authService,
configManager,
auditService,
vaultService,
knownHosts,
sshPool,
keyManager,
@ -98,6 +101,13 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
enforceSafeMode,
stepUpGuard,
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
.object({
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) => {
res.json({
state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady,
isPanicLocked: vaultService.isPanicLocked,
});
});
@ -128,6 +138,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
notifyConfigReeval();
onVaultUnlocked?.();
onVaultChanged?.('vault-init');
broadcastVaultState();
auditService.log({
action: 'vault.init',
actorIp: ip,
@ -136,6 +147,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
});
res.status(201).json({
state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady,
generatedKeyHex: result.generatedKeyHex,
});
} catch (err) {
@ -148,48 +160,102 @@ export function createVaultRouter(deps: VaultRouterDeps): {
vaultRouter.post('/unlock', requireAuth(authService), requireCsrf, (req, res) => {
const ip = req.clientIp ?? 'unknown';
const rate = rateLimiter.check('vault-unlock', ip);
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);
const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {});
if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
try {
vaultService.unlock(parsed.data.masterKey);
rateLimiter.recordSuccess('vault-unlock', ip);
notifyConfigReeval();
onVaultUnlocked?.();
onVaultChanged?.();
auditService.log({
action: 'vault.unlock',
actorIp: ip,
sessionIdHash: req.authSession!.idHash,
status: 'ok',
});
res.json({
state: vaultService.state,
isPanicLocked: vaultService.isPanicLocked,
});
} 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',
});
const masterKeyInput = parsed.data.masterKey?.trim();
if (masterKeyInput && masterKeyInput.length > 0) {
const rate = rateLimiter.check('vault-unlock', ip);
if (!rate.allowed) {
res.setHeader('Retry-After', String(rate.retryAfterSec));
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
return;
}
try {
vaultService.unlock(masterKeyInput);
rateLimiter.recordSuccess('vault-unlock', ip);
notifyConfigReeval();
onVaultUnlocked?.();
onVaultChanged?.();
broadcastVaultState();
auditService.log({
action: 'vault.unlock',
actorIp: ip,
sessionIdHash: req.authSession!.idHash,
status: 'ok',
});
res.json({
state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady,
isPanicLocked: vaultService.isPanicLocked,
});
} 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!)
@ -211,12 +277,19 @@ export function createVaultRouter(deps: VaultRouterDeps): {
});
vaultRouter.get('/credentials', requireAuth(authService), (_req, res) => {
if (vaultService.state !== 'unlocked') {
res.json({ state: vaultService.state, credentials: [] });
if (!vaultService.isRuntimeReady) {
res.json({
state: vaultService.state,
runtimeReady: false,
isPanicLocked: vaultService.isPanicLocked,
credentials: [],
});
return;
}
res.json({
state: vaultService.state,
runtimeReady: true,
isPanicLocked: vaultService.isPanicLocked,
credentials: vaultService.listMetadata(),
});
});

View file

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

View file

@ -82,7 +82,9 @@ export async function createGCoordinatorServer(
const db = openDatabase(dbPath);
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 rateLimiter = new RateLimiter();
const configManager = new ConfigManager(configDir, db, vaultService);
@ -98,11 +100,13 @@ export async function createGCoordinatorServer(
const backupKey = configManager.getSettings().security.enableEmergencySecretsBackup
? recoveryStore.readSavedMasterKeyHex()
: undefined;
const unlockResult = vaultService.tryAutoUnlockFromEnvOrSecret({
const runtimeInit = vaultService.initRuntime({
secretFilePath: options.secretFilePath,
envKey: options.envMasterKey || backupKey,
envKey: options.envMasterKey,
backupKey,
autoCreateIfMissing: true,
});
if (unlockResult.unlocked) {
if (runtimeInit.runtimeReady) {
configManager.recomputeWarnings();
if (authService.isBootstrapped()) {
authService.syncRecovery();
@ -177,6 +181,8 @@ export async function createGCoordinatorServer(
for (const frame of customSystemsEngine.getStreamReplayFrames(jobId)) {
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) => {
res.json({ ok: true, vaultState: vaultService.state });
res.json({
ok: true,
vaultState: vaultService.state,
vaultRuntimeReady: vaultService.isRuntimeReady,
});
});
app.use(
@ -338,6 +348,7 @@ export async function createGCoordinatorServer(
authService,
configManager,
auditService,
vaultService,
knownHosts,
sshPool,
keyManager,

View file

@ -193,7 +193,7 @@ export class ConfigManager {
for (const server of this.servers.values()) {
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)) {
next.push({
filePath: relPath,
@ -297,7 +297,7 @@ export class ConfigManager {
// 3. Alerts cross-references
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) {
if (!this.vault.hasCredential(ch.secretRef)) {
next.push({

View file

@ -36,6 +36,7 @@ export interface MonitoringTickEvent {
interface ServerTimers {
metricTimer: NodeJS.Timeout | null;
warmupTimer: NodeJS.Timeout | null;
probeTimers: Map<string, NodeJS.Timeout>;
pollingMetrics: boolean;
}
@ -68,6 +69,7 @@ export class MonitoringService {
start(): void {
this.stopped = false;
this.hydrateLatestFromDb();
this.syncServers();
if (!this.maintenanceTimer) {
this.runMaintenance();
@ -81,6 +83,7 @@ export class MonitoringService {
stopAll(): void {
for (const timers of this.serverTimers.values()) {
if (timers.metricTimer) clearInterval(timers.metricTimer);
if (timers.warmupTimer) clearTimeout(timers.warmupTimer);
for (const pt of timers.probeTimers.values()) clearInterval(pt);
}
this.serverTimers.clear();
@ -100,7 +103,7 @@ export class MonitoringService {
this.stopAll();
this.sshPool.syncWithConfig();
if (this.vaultService.state !== 'unlocked') {
if (!this.vaultService.isRuntimeReady) {
return;
}
@ -117,7 +120,7 @@ export class MonitoringService {
async pollServerNow(serverId: string): Promise<MonitoringTickEvent | null> {
const server = this.configManager.getServer(serverId);
if (!server || !server.enabled || this.vaultService.state !== 'unlocked') {
if (!server || !server.enabled || !this.vaultService.isRuntimeReady) {
return null;
}
return this.executeMetricPoll(server);
@ -266,13 +269,30 @@ export class MonitoringService {
private scheduleServer(server: ServerConfig): void {
const timers: ServerTimers = {
metricTimer: null,
warmupTimer: null,
probeTimers: new Map(),
pollingMetrics: false,
};
this.serverTimers.set(server.id, timers);
// 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(() => {
void this.executeMetricPoll(server);
@ -293,7 +313,7 @@ export class MonitoringService {
private async executeMetricPoll(
server: ServerConfig,
): 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);
if (timerState?.pollingMetrics) return null;
@ -362,7 +382,7 @@ export class MonitoringService {
}
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);
if (!probe || !probe.enabled) return;
@ -392,6 +412,73 @@ export class MonitoringService {
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(
serverId: string,
sample: MetricSample,

View file

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

View file

@ -101,13 +101,24 @@ export type VaultCredentialInput = DistributiveOmit<
updatedAt?: string;
};
export interface VaultServiceOptions {
keyFilePath?: string;
}
export class VaultService {
private masterKey: Buffer | null = null;
private credentials = new Map<string, VaultCredential>();
private writeUnlocked = false;
private autoInitializedEmpty = false;
private wasPanicLocked = false;
private readonly keyFilePath: string | null;
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());
}
@ -130,8 +141,12 @@ export class VaultService {
return this.vaultFilePath;
}
get isRuntimeReady(): boolean {
return this.masterKey !== null;
}
get state(): VaultState {
if (this.masterKey !== null) return 'unlocked';
if (this.masterKey !== null && this.writeUnlocked) return 'unlocked';
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: {
secretFilePath?: string;
envKey?: string;
@ -182,7 +286,9 @@ export class VaultService {
}
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');
}
@ -195,7 +301,10 @@ export class VaultService {
this.zeroizeMasterKey();
this.masterKey = keyBuf;
this.credentials.clear();
this.writeUnlocked = true;
this.autoInitializedEmpty = false;
this.setPanicLockMarker(false);
this.persistKeyFileIfConfigured(keyBuf);
return masterKeyInput ? {} : { generatedKeyHex: keyBuf.toString('hex') };
}
@ -214,16 +323,32 @@ export class VaultService {
this.zeroizeMasterKey();
this.masterKey = keyBuf;
this.credentials = new Map(Object.entries(payload.credentials));
this.writeUnlocked = true;
this.autoInitializedEmpty = false;
this.setPanicLockMarker(false);
this.persistKeyFileIfConfigured(keyBuf);
} catch (err) {
keyBuf.fill(0);
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 {
this.zeroizeMasterKey();
this.credentials.clear();
this.writeUnlocked = false;
this.autoInitializedEmpty = false;
this.setPanicLockMarker(true);
for (const listener of this.panicListeners) {
@ -236,7 +361,7 @@ export class VaultService {
}
rotateMasterKey(newMasterKeyInput?: string): { generatedKeyHex?: string } {
this.assertUnlocked();
this.assertWriteUnlocked();
const nextKey = newMasterKeyInput
? parseMasterKey(newMasterKeyInput)
: generateMasterKeyBuffer();
@ -250,6 +375,8 @@ export class VaultService {
this.writeVerifiedVaultAtomic(payload, nextKey);
this.zeroizeMasterKey();
this.masterKey = nextKey;
this.writeUnlocked = true;
this.persistKeyFileIfConfigured(nextKey);
return newMasterKeyInput ? {} : { generatedKeyHex: nextKey.toString('hex') };
} catch (err) {
nextKey.fill(0);
@ -258,7 +385,7 @@ export class VaultService {
}
listMetadata(): VaultCredentialMeta[] {
this.assertUnlocked();
this.assertRuntimeReady();
return [...this.credentials.values()].map((cred) => {
const meta: VaultCredentialMeta = {
id: cred.id,
@ -281,8 +408,14 @@ export class VaultService {
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 {
this.assertUnlocked();
this.assertWriteUnlocked();
const cred = this.credentials.get(id);
return cred ? structuredClone(cred) : undefined;
}
@ -292,7 +425,7 @@ export class VaultService {
}
exportAllCredentials(): Record<string, VaultCredential> {
this.assertUnlocked();
this.assertRuntimeReady();
const out: Record<string, VaultCredential> = {};
for (const [id, cred] of this.credentials.entries()) {
out[id] = structuredClone(cred);
@ -301,7 +434,8 @@ export class VaultService {
}
upsertCredential(input: VaultCredentialInput): VaultCredentialMeta {
this.assertUnlocked();
this.assertWriteUnlocked();
this.autoInitializedEmpty = false;
const now = new Date().toISOString();
const existing = this.credentials.get(input.id);
const candidate = VaultCredentialSchema.parse({
@ -325,7 +459,7 @@ export class VaultService {
}
deleteCredential(id: string): boolean {
this.assertUnlocked();
this.assertWriteUnlocked();
if (!this.credentials.has(id)) return false;
const nextMap = new Map(this.credentials);
@ -346,7 +480,8 @@ export class VaultService {
comment?: string;
passphrase?: string;
}): VaultCredentialMeta {
this.assertUnlocked();
this.assertWriteUnlocked();
this.autoInitializedEmpty = false;
const keyPair = options.passphrase
? ssh2.utils.generateKeyPairSync('ed25519', {
@ -373,12 +508,37 @@ export class VaultService {
});
}
private assertUnlocked(): void {
private assertRuntimeReady(): void {
if (this.masterKey === null) {
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 {
if (this.masterKey !== null) {
this.masterKey.fill(0);

View file

@ -161,8 +161,9 @@ export class KeyManager {
);
}
const vaultCreds =
this.vaultService.state === 'unlocked' ? this.vaultService.listMetadata() : [];
const vaultCreds = this.vaultService.isRuntimeReady
? this.vaultService.listMetadata()
: [];
const entries = parseAuthorizedKeys(res.stdout, vaultCreds, server.credentialId);
return { raw: res.stdout, entries };
}
@ -172,7 +173,7 @@ export class KeyManager {
credentialId: string,
actor = { ip: 'hub', sessionIdHash: null as string | null },
): 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) {
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}"`);
}
const activeCred = this.vaultService.getSecret(server.credentialId);
const activeCred = this.vaultService.getRuntimeSecret(server.credentialId);
const activeFp =
activeCred?.type === 'ssh-key'
? activeCred.fingerprint ??

View file

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

View file

@ -99,7 +99,7 @@ export class TunnelManager {
}
async syncAutoStart(): Promise<void> {
if (this.vaultService.state !== 'unlocked') return;
if (!this.vaultService.isRuntimeReady) return;
for (const server of this.configManager.listServers()) {
if (!server.enabled) continue;
for (const tunnel of server.tunnels) {
@ -121,7 +121,7 @@ export class TunnelManager {
if (!tunnel) {
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');
}

View file

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

View file

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