feat(api): wire multi-factor endpoints, policy-aware step-up guard, and recovery backup auto-unlock
This commit is contained in:
parent
99ee259cec
commit
4915bce1e4
5 changed files with 463 additions and 63 deletions
|
|
@ -2,6 +2,7 @@ import fs from 'node:fs';
|
|||
import path from 'node:path';
|
||||
import readline from 'node:readline/promises';
|
||||
import { parseArgs } from 'node:util';
|
||||
import { EmergencyRecoveryService } from '../server/security/recovery-store.js';
|
||||
import { VaultService } from '../server/security/vault.js';
|
||||
|
||||
function printUsage(): void {
|
||||
|
|
@ -70,6 +71,11 @@ async function runRotateKey(args: string[]): Promise<number> {
|
|||
return 1;
|
||||
}
|
||||
|
||||
const recovery = new EmergencyRecoveryService(dataDir);
|
||||
if (recovery.readBundle() !== null) {
|
||||
recovery.syncState({ enabled: true, vault, snapshotReason: 'cli-rotate-key' });
|
||||
}
|
||||
|
||||
if (parsed.values['new-key-out']) {
|
||||
const outPath = path.resolve(parsed.values['new-key-out']);
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
|
|
|
|||
|
|
@ -4,12 +4,14 @@ import type { ConfigManager } from '../../config/config-manager.js';
|
|||
import type { AuditService } from '../../security/audit.js';
|
||||
import { SESSION_COOKIE_NAME, type AuthService } from '../../security/auth.js';
|
||||
import {
|
||||
createStepUpGuard,
|
||||
enforceSafeMode,
|
||||
extractCookies,
|
||||
requireAuth,
|
||||
requireCsrf,
|
||||
type RateLimiter,
|
||||
} from '../../security/guards.js';
|
||||
import type { EmergencyRecoveryService } from '../../security/recovery-store.js';
|
||||
import type { VaultService } from '../../security/vault.js';
|
||||
|
||||
export const CSRF_COOKIE_NAME = 'gcoord_csrf';
|
||||
|
|
@ -19,6 +21,7 @@ export interface AuthRouterDeps {
|
|||
vaultService: VaultService;
|
||||
configManager: ConfigManager;
|
||||
auditService: AuditService;
|
||||
recoveryStore: EmergencyRecoveryService;
|
||||
rateLimiter: RateLimiter;
|
||||
trustCloudflare: boolean;
|
||||
}
|
||||
|
|
@ -64,14 +67,27 @@ function clearAuthCookies(res: Response, req: Request, trustCloudflare: boolean)
|
|||
|
||||
export function createAuthRouter(deps: AuthRouterDeps): Router {
|
||||
const router = Router();
|
||||
const { authService, vaultService, configManager, auditService, rateLimiter, trustCloudflare } =
|
||||
deps;
|
||||
const {
|
||||
authService,
|
||||
vaultService,
|
||||
configManager,
|
||||
auditService,
|
||||
recoveryStore,
|
||||
rateLimiter,
|
||||
trustCloudflare,
|
||||
} = deps;
|
||||
|
||||
const stepUpGuard = createStepUpGuard(
|
||||
authService,
|
||||
() => configManager.getSettings().security.stepUpPolicy,
|
||||
);
|
||||
|
||||
router.get('/status', (req, res) => {
|
||||
const bootstrapped = authService.isBootstrapped();
|
||||
const cookies = extractCookies(req.headers.cookie);
|
||||
const session = authService.getSessionByToken(cookies[SESSION_COOKIE_NAME]);
|
||||
const settings = configManager.getSettings();
|
||||
const authRequirements = authService.getPublicAuthRequirements();
|
||||
|
||||
if (!session) {
|
||||
res.json({
|
||||
|
|
@ -80,6 +96,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
vaultState: vaultService.state,
|
||||
defaultMobileSafeMode: settings.defaultMobileSafeMode,
|
||||
theme: settings.theme,
|
||||
authRequirements,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
|
@ -93,6 +110,8 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
isPanicLocked: vaultService.isPanicLocked,
|
||||
defaultMobileSafeMode: settings.defaultMobileSafeMode,
|
||||
theme: settings.theme,
|
||||
security: settings.security,
|
||||
authRequirements,
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -128,6 +147,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
totpCode: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits'),
|
||||
secretBase32: z.string().optional(),
|
||||
initialSafeMode: z.boolean().optional(),
|
||||
securityPreset: z.enum(['relaxed', 'balanced', 'strict']).optional(),
|
||||
});
|
||||
const parsed = bodySchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
|
|
@ -137,6 +157,37 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
}
|
||||
|
||||
try {
|
||||
if (parsed.data.securityPreset) {
|
||||
const cur = configManager.getSettings();
|
||||
const presetSecurity =
|
||||
parsed.data.securityPreset === 'relaxed'
|
||||
? {
|
||||
...cur.security,
|
||||
requireTotpOnLogin: false,
|
||||
stepUpPolicy: 'off' as const,
|
||||
stepUpMethod: 'password' as const,
|
||||
elevateOnLogin: true,
|
||||
keepElevationOnSafeMode: true,
|
||||
}
|
||||
: parsed.data.securityPreset === 'strict'
|
||||
? {
|
||||
...cur.security,
|
||||
requireTotpOnLogin: true,
|
||||
stepUpPolicy: '5m' as const,
|
||||
stepUpMethod: 'totp' as const,
|
||||
elevateOnLogin: false,
|
||||
keepElevationOnSafeMode: false,
|
||||
}
|
||||
: cur.security;
|
||||
|
||||
configManager.saveConfigText(
|
||||
'settings.json',
|
||||
JSON.stringify({ ...cur, security: presetSecurity }, null, 2),
|
||||
'ui',
|
||||
`Bootstrap preset: ${parsed.data.securityPreset}`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await authService.completeBootstrap({
|
||||
...parsed.data,
|
||||
ip,
|
||||
|
|
@ -187,12 +238,19 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
return;
|
||||
}
|
||||
|
||||
const bodySchema = z.object({
|
||||
username: z.string().min(1).optional(),
|
||||
password: z.string().min(1),
|
||||
code: z.string().min(6).max(32),
|
||||
initialSafeMode: z.boolean().optional(),
|
||||
});
|
||||
const bodySchema = z
|
||||
.object({
|
||||
username: z.string().min(1).optional(),
|
||||
password: z.string().min(1).optional(),
|
||||
passwords: z.array(z.string().min(1)).optional(),
|
||||
code: z.string().max(32).optional(),
|
||||
codes: z.array(z.string().max(32)).optional(),
|
||||
initialSafeMode: z.boolean().optional(),
|
||||
})
|
||||
.refine(
|
||||
(b) => Boolean(b.password || (b.passwords && b.passwords.length > 0)),
|
||||
'Password is required',
|
||||
);
|
||||
const parsed = bodySchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
rateLimiter.recordFailure('login', ip);
|
||||
|
|
@ -276,55 +334,336 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
});
|
||||
});
|
||||
|
||||
router.post('/step-up', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('step-up', ip);
|
||||
if (!rate.allowed) {
|
||||
res.setHeader('Retry-After', String(rate.retryAfterSec));
|
||||
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
|
||||
return;
|
||||
}
|
||||
router.post(
|
||||
'/step-up',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('step-up', 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({ code: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits') })
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
const parsed = z
|
||||
.object({
|
||||
code: z.string().optional(),
|
||||
codes: z.array(z.string()).optional(),
|
||||
password: z.string().optional(),
|
||||
passwords: z.array(z.string()).optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const outcome = authService.stepUp(req.authSession!.idHash, parsed.data.code);
|
||||
if (!outcome.ok) {
|
||||
rateLimiter.recordFailure('step-up', ip);
|
||||
const outcome = await authService.stepUp(req.authSession!.idHash, parsed.data);
|
||||
if (!outcome.ok) {
|
||||
rateLimiter.recordFailure('step-up', ip);
|
||||
auditService.log({
|
||||
action: 'auth.step_up',
|
||||
actorIp: ip,
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'denied',
|
||||
details: { reason: outcome.reason },
|
||||
});
|
||||
res.status(outcome.reason === 'safe_mode_active' ? 423 : 403).json({
|
||||
error: 'STEP_UP_FAILED',
|
||||
reason: outcome.reason,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
rateLimiter.recordSuccess('step-up', ip);
|
||||
auditService.log({
|
||||
action: 'auth.step_up',
|
||||
actorIp: ip,
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'denied',
|
||||
details: { reason: outcome.reason },
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(outcome.reason === 'safe_mode_active' ? 423 : 403).json({
|
||||
error: 'STEP_UP_FAILED',
|
||||
reason: outcome.reason,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
rateLimiter.recordSuccess('step-up', ip);
|
||||
auditService.log({
|
||||
action: 'auth.step_up',
|
||||
actorIp: ip,
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ elevatedUntil: outcome.elevatedUntil });
|
||||
});
|
||||
res.json({ elevatedUntil: outcome.elevatedUntil });
|
||||
},
|
||||
);
|
||||
|
||||
router.post('/drop-elevation', requireAuth(authService), requireCsrf, (req, res) => {
|
||||
authService.dropElevation(req.authSession!.idHash);
|
||||
res.json({ elevatedUntil: null });
|
||||
});
|
||||
|
||||
// Multi-password / multi-TOTP & emergency backup routes
|
||||
router.get('/factors', requireAuth(authService), (_req, res) => {
|
||||
const settings = configManager.getSettings();
|
||||
res.json({
|
||||
...authService.listFactors(),
|
||||
security: settings.security,
|
||||
recoveryBackup: recoveryStore.getStatus(settings.security.enableEmergencySecretsBackup),
|
||||
});
|
||||
});
|
||||
|
||||
router.post(
|
||||
'/factors/passwords',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
label: z.string().min(1).max(64),
|
||||
password: z.string().min(8).max(256),
|
||||
})
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const added = await authService.addPassword(parsed.data.label, parsed.data.password);
|
||||
auditService.log({
|
||||
action: 'auth.password_add',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: added.id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(201).json({ password: added });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'PASSWORD_ADD_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to add password',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.delete(
|
||||
'/factors/passwords/:id',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
try {
|
||||
const removed = authService.removePassword(id);
|
||||
if (!removed) {
|
||||
res.status(404).json({ error: 'PASSWORD_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
auditService.log({
|
||||
action: 'auth.password_remove',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ deleted: true });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'PASSWORD_REMOVE_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to remove password',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/factors/totps/enroll',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const parsed = z.object({ label: z.string().min(1).max(64) }).safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
const data = await authService.beginTotpEnrollment(parsed.data.label);
|
||||
res.json(data);
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/factors/totps/confirm',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
enrollmentId: z.string().min(1),
|
||||
code: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits'),
|
||||
})
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const added = authService.confirmTotpEnrollment(
|
||||
parsed.data.enrollmentId,
|
||||
parsed.data.code,
|
||||
);
|
||||
auditService.log({
|
||||
action: 'auth.totp_add',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: added.id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(201).json({ totp: added });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'TOTP_CONFIRM_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to enroll TOTP',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.delete(
|
||||
'/factors/totps/:id',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
try {
|
||||
const removed = authService.removeTotp(id);
|
||||
if (!removed) {
|
||||
res.status(404).json({ error: 'TOTP_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
auditService.log({
|
||||
action: 'auth.totp_remove',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ deleted: true });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'TOTP_REMOVE_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to remove TOTP',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/factors/recovery-codes',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const recoveryCodes = authService.regenerateRecoveryCodes();
|
||||
auditService.log({
|
||||
action: 'auth.recovery_codes_regenerate',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ recoveryCodes });
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/recovery-backup/sync',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
(req, res) => {
|
||||
const settings = configManager.getSettings();
|
||||
if (!settings.security.enableEmergencySecretsBackup) {
|
||||
res.status(400).json({
|
||||
error: 'BACKUP_DISABLED',
|
||||
message: 'Enable emergency secrets backup in security settings first.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
authService.syncRecovery({ snapshotReason: 'manual-sync' });
|
||||
auditService.log({
|
||||
action: 'auth.recovery_backup_sync',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ recoveryBackup: recoveryStore.getStatus(true) });
|
||||
},
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/recovery-backup/export',
|
||||
requireAuth(authService),
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const settings = configManager.getSettings();
|
||||
if (settings.security.enableEmergencySecretsBackup) {
|
||||
authService.syncRecovery();
|
||||
}
|
||||
const bundle = recoveryStore.readBundle();
|
||||
if (!bundle) {
|
||||
res.status(404).json({ error: 'RECOVERY_BACKUP_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
auditService.log({
|
||||
action: 'auth.recovery_backup_export',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ bundle });
|
||||
},
|
||||
);
|
||||
|
||||
router.delete(
|
||||
'/recovery-backup',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
recoveryStore.wipeAll();
|
||||
if (req.query.disable === '1') {
|
||||
const cur = configManager.getSettings();
|
||||
configManager.saveConfigText(
|
||||
'settings.json',
|
||||
JSON.stringify(
|
||||
{
|
||||
...cur,
|
||||
security: { ...cur.security, enableEmergencySecretsBackup: false },
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
'ui',
|
||||
'Disabled local emergency secrets backup',
|
||||
);
|
||||
}
|
||||
auditService.log({
|
||||
action: 'auth.recovery_backup_wipe',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({
|
||||
wiped: true,
|
||||
recoveryBackup: recoveryStore.getStatus(
|
||||
configManager.getSettings().security.enableEmergencySecretsBackup,
|
||||
),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
router.get('/sessions', requireAuth(authService), (req, res) => {
|
||||
res.json({ sessions: authService.listSessions(req.authSession!.idHash) });
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { Router } from 'express';
|
||||
import { Router, type RequestHandler } from 'express';
|
||||
import { ZodError, z } from 'zod';
|
||||
import { EntityIdSchema } from '../../../shared/schemas/common.js';
|
||||
import { ServerConfigSchema } from '../../../shared/schemas/server.schema.js';
|
||||
|
|
@ -29,6 +29,8 @@ export interface ServersRouterDeps {
|
|||
keyManager: KeyManager;
|
||||
serverInspector: ServerInspector;
|
||||
monitoringService: MonitoringService;
|
||||
stepUpGuard?: RequestHandler;
|
||||
onKeysMutated?: (snapshotReason?: string) => void;
|
||||
}
|
||||
|
||||
const VALID_RANGES = new Set<MetricRange>(['1h', '6h', '24h', '7d', '30d']);
|
||||
|
|
@ -44,6 +46,8 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
keyManager,
|
||||
serverInspector,
|
||||
monitoringService,
|
||||
stepUpGuard = requireStepUp,
|
||||
onKeysMutated,
|
||||
} = deps;
|
||||
|
||||
router.get('/', requireAuth(authService), (_req, res) => {
|
||||
|
|
@ -68,7 +72,7 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
requireStepUp,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const hostPort = typeof req.query.hostPort === 'string' ? req.query.hostPort : '';
|
||||
if (!hostPort) {
|
||||
|
|
@ -92,7 +96,7 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
requireStepUp,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
|
|
@ -129,6 +133,7 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
sessionIdHash: req.authSession!.idHash,
|
||||
});
|
||||
monitoringService.syncServers();
|
||||
onKeysMutated?.('ssh-key-rotation');
|
||||
res.json({ results });
|
||||
},
|
||||
);
|
||||
|
|
@ -305,7 +310,7 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
requireStepUp,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const parsed = z.object({ fingerprint: z.string().min(1) }).safeParse(req.body);
|
||||
|
|
@ -417,7 +422,7 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
requireStepUp,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const parsed = z
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import crypto from 'node:crypto';
|
||||
import { Router } from 'express';
|
||||
import { Router, type RequestHandler } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { EntityIdSchema } from '../../../shared/schemas/common.js';
|
||||
import type { ConfigManager } from '../../config/config-manager.js';
|
||||
|
|
@ -27,7 +27,9 @@ export interface VaultRouterDeps {
|
|||
auditService: AuditService;
|
||||
rateLimiter: RateLimiter;
|
||||
wsHub: WsHub;
|
||||
stepUpGuard?: RequestHandler;
|
||||
onVaultUnlocked?: () => void;
|
||||
onVaultChanged?: (snapshotReason?: string) => void;
|
||||
}
|
||||
|
||||
interface PendingKeyRotation {
|
||||
|
|
@ -84,7 +86,9 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
auditService,
|
||||
rateLimiter,
|
||||
wsHub,
|
||||
stepUpGuard = requireStepUp,
|
||||
onVaultUnlocked,
|
||||
onVaultChanged,
|
||||
} = deps;
|
||||
const vaultRouter = Router();
|
||||
const panicLockHandler = Router();
|
||||
|
|
@ -123,6 +127,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
const result = vaultService.initializeNewVault(parsed.data.masterKey);
|
||||
notifyConfigReeval();
|
||||
onVaultUnlocked?.();
|
||||
onVaultChanged?.('vault-init');
|
||||
auditService.log({
|
||||
action: 'vault.init',
|
||||
actorIp: ip,
|
||||
|
|
@ -161,6 +166,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
rateLimiter.recordSuccess('vault-unlock', ip);
|
||||
notifyConfigReeval();
|
||||
onVaultUnlocked?.();
|
||||
onVaultChanged?.();
|
||||
auditService.log({
|
||||
action: 'vault.unlock',
|
||||
actorIp: ip,
|
||||
|
|
@ -218,7 +224,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
vaultRouter.get(
|
||||
'/credentials/:id/reveal',
|
||||
requireAuth(authService),
|
||||
requireStepUp,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
if (vaultService.state !== 'unlocked') {
|
||||
res.status(423).json({ error: 'VAULT_LOCKED' });
|
||||
|
|
@ -246,7 +252,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
requireStepUp,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
if (vaultService.state !== 'unlocked') {
|
||||
res.status(423).json({ error: 'VAULT_LOCKED' });
|
||||
|
|
@ -271,6 +277,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
}
|
||||
const meta = vaultService.upsertCredential(credInput);
|
||||
notifyConfigReeval();
|
||||
onVaultChanged?.();
|
||||
auditService.log({
|
||||
action: 'vault.upsert',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
|
|
@ -288,7 +295,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
requireStepUp,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
if (vaultService.state !== 'unlocked') {
|
||||
res.status(423).json({ error: 'VAULT_LOCKED' });
|
||||
|
|
@ -314,6 +321,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
}
|
||||
const meta = vaultService.upsertCredential(credInput);
|
||||
notifyConfigReeval();
|
||||
onVaultChanged?.();
|
||||
auditService.log({
|
||||
action: 'vault.upsert',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
|
|
@ -331,7 +339,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
requireStepUp,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
if (vaultService.state !== 'unlocked') {
|
||||
res.status(423).json({ error: 'VAULT_LOCKED' });
|
||||
|
|
@ -344,6 +352,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
return;
|
||||
}
|
||||
notifyConfigReeval();
|
||||
onVaultChanged?.('vault-delete');
|
||||
auditService.log({
|
||||
action: 'vault.delete',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
|
|
@ -360,7 +369,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
requireStepUp,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
if (vaultService.state !== 'unlocked') {
|
||||
res.status(423).json({ error: 'VAULT_LOCKED' });
|
||||
|
|
@ -380,6 +389,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
}
|
||||
const meta = vaultService.generateEd25519Credential(parsed.data);
|
||||
notifyConfigReeval();
|
||||
onVaultChanged?.();
|
||||
auditService.log({
|
||||
action: 'vault.generate_ed25519',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
|
|
@ -397,7 +407,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
requireStepUp,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
if (vaultService.state !== 'unlocked') {
|
||||
res.status(423).json({ error: 'VAULT_LOCKED' });
|
||||
|
|
@ -421,7 +431,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
requireStepUp,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
if (vaultService.state !== 'unlocked') {
|
||||
res.status(423).json({ error: 'VAULT_LOCKED' });
|
||||
|
|
@ -460,6 +470,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
const nextHex = pendingRotation.candidateKeyHex;
|
||||
pendingRotation = null;
|
||||
vaultService.rotateMasterKey(nextHex);
|
||||
onVaultChanged?.('master-key-rotation');
|
||||
auditService.log({
|
||||
action: 'vault.rotate_key',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
|
|
|
|||
|
|
@ -10,7 +10,12 @@ import { MonitoringService } from './monitoring/monitoring-service.js';
|
|||
import { ProbeRunner } from './monitoring/probes.js';
|
||||
import { AuditService } from './security/audit.js';
|
||||
import { AuthService } from './security/auth.js';
|
||||
import { RateLimiter, attachClientIp } from './security/guards.js';
|
||||
import {
|
||||
RateLimiter,
|
||||
attachClientIp,
|
||||
createStepUpGuard,
|
||||
} from './security/guards.js';
|
||||
import { EmergencyRecoveryService } from './security/recovery-store.js';
|
||||
import { VaultService } from './security/vault.js';
|
||||
import { KeyManager } from './ssh/key-manager.js';
|
||||
import { KnownHostsService } from './ssh/known-hosts.js';
|
||||
|
|
@ -41,6 +46,7 @@ export interface GCoordinatorInstance {
|
|||
authService: AuthService;
|
||||
configManager: ConfigManager;
|
||||
auditService: AuditService;
|
||||
recoveryStore: EmergencyRecoveryService;
|
||||
knownHosts: KnownHostsService;
|
||||
sshPool: SSHPool;
|
||||
keyManager: KeyManager;
|
||||
|
|
@ -65,16 +71,31 @@ export async function createGCoordinatorServer(
|
|||
const db = openDatabase(dbPath);
|
||||
const auditService = new AuditService(db);
|
||||
const vaultService = new VaultService(vaultPath);
|
||||
const authService = new AuthService(db);
|
||||
const recoveryStore = new EmergencyRecoveryService(dataDir);
|
||||
const rateLimiter = new RateLimiter();
|
||||
const configManager = new ConfigManager(configDir, db, vaultService);
|
||||
|
||||
vaultService.tryAutoUnlockFromEnvOrSecret({
|
||||
secretFilePath: options.secretFilePath,
|
||||
envKey: options.envMasterKey,
|
||||
await configManager.init({ watch: options.watchConfig ?? true });
|
||||
|
||||
const authService = new AuthService(db, {
|
||||
getSecuritySettings: () => configManager.getSettings().security,
|
||||
recoveryStore,
|
||||
vaultService,
|
||||
});
|
||||
|
||||
await configManager.init({ watch: options.watchConfig ?? true });
|
||||
const backupKey = configManager.getSettings().security.enableEmergencySecretsBackup
|
||||
? recoveryStore.readSavedMasterKeyHex()
|
||||
: undefined;
|
||||
const unlockResult = vaultService.tryAutoUnlockFromEnvOrSecret({
|
||||
secretFilePath: options.secretFilePath,
|
||||
envKey: options.envMasterKey || backupKey,
|
||||
});
|
||||
if (unlockResult.unlocked) {
|
||||
configManager.recomputeWarnings();
|
||||
if (authService.isBootstrapped()) {
|
||||
authService.syncRecovery();
|
||||
}
|
||||
}
|
||||
|
||||
const app = express();
|
||||
app.disable('x-powered-by');
|
||||
|
|
@ -156,10 +177,18 @@ export async function createGCoordinatorServer(
|
|||
if (event.entityType === 'server' && event.id) {
|
||||
sshPool.closeServer(event.id);
|
||||
}
|
||||
if (event.entityType === 'settings') {
|
||||
authService.syncRecovery();
|
||||
}
|
||||
monitoringService.syncServers();
|
||||
}
|
||||
});
|
||||
|
||||
const stepUpGuard = createStepUpGuard(
|
||||
authService,
|
||||
() => configManager.getSettings().security.stepUpPolicy,
|
||||
);
|
||||
|
||||
app.get('/api/healthz', (_req, res) => {
|
||||
res.json({ ok: true, vaultState: vaultService.state });
|
||||
});
|
||||
|
|
@ -171,6 +200,7 @@ export async function createGCoordinatorServer(
|
|||
vaultService,
|
||||
configManager,
|
||||
auditService,
|
||||
recoveryStore,
|
||||
rateLimiter,
|
||||
trustCloudflare,
|
||||
}),
|
||||
|
|
@ -183,9 +213,13 @@ export async function createGCoordinatorServer(
|
|||
auditService,
|
||||
rateLimiter,
|
||||
wsHub,
|
||||
stepUpGuard,
|
||||
onVaultUnlocked: () => {
|
||||
monitoringService.syncServers();
|
||||
},
|
||||
onVaultChanged: (snapshotReason) => {
|
||||
authService.syncRecovery({ snapshotReason });
|
||||
},
|
||||
});
|
||||
|
||||
app.use('/api/vault', vaultRouter);
|
||||
|
|
@ -201,6 +235,10 @@ export async function createGCoordinatorServer(
|
|||
keyManager,
|
||||
serverInspector,
|
||||
monitoringService,
|
||||
stepUpGuard,
|
||||
onKeysMutated: (snapshotReason) => {
|
||||
authService.syncRecovery({ snapshotReason });
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.use(
|
||||
|
|
@ -242,6 +280,7 @@ export async function createGCoordinatorServer(
|
|||
authService,
|
||||
configManager,
|
||||
auditService,
|
||||
recoveryStore,
|
||||
knownHosts,
|
||||
sshPool,
|
||||
keyManager,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue