feat(backup,cli): add AES-256-GCM .gcoord.enc backup, verify, restore CLI and API
This commit is contained in:
parent
413053182b
commit
fbc1eb94e0
7 changed files with 1155 additions and 19 deletions
216
src/server/api/routes/backup.routes.ts
Normal file
216
src/server/api/routes/backup.routes.ts
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
import type Database from 'better-sqlite3';
|
||||
import { Router, type RequestHandler } from 'express';
|
||||
import { z } from 'zod';
|
||||
import type { ConfigManager } from '../../config/config-manager.js';
|
||||
import type { AuditService } from '../../security/audit.js';
|
||||
import type { AuthService } from '../../security/auth.js';
|
||||
import {
|
||||
createBackupBundle,
|
||||
restoreBackupBundle,
|
||||
verifyBackupSummaryOnly,
|
||||
type BackupInnerPayload,
|
||||
type BackupVerificationSummary,
|
||||
} from '../../security/backup.js';
|
||||
import {
|
||||
enforceSafeMode,
|
||||
requireAuth,
|
||||
requireCsrf,
|
||||
} from '../../security/guards.js';
|
||||
import type { VaultService } from '../../security/vault.js';
|
||||
|
||||
export interface BackupRouterDeps {
|
||||
dataDir: string;
|
||||
db: Database.Database;
|
||||
authService: AuthService;
|
||||
vaultService: VaultService;
|
||||
configManager: ConfigManager;
|
||||
auditService: AuditService;
|
||||
stepUpGuard: RequestHandler;
|
||||
onRestored: (info: {
|
||||
summary: BackupVerificationSummary;
|
||||
inner: BackupInnerPayload;
|
||||
vaultKeyCandidate?: string;
|
||||
}) => void | Promise<void>;
|
||||
}
|
||||
|
||||
const ExportBackupBodySchema = z.object({
|
||||
passphrase: z.string().max(256).optional(),
|
||||
});
|
||||
|
||||
const VerifyBackupBodySchema = z.object({
|
||||
bundleBase64: z.string().min(1),
|
||||
passphrase: z.string().max(256).optional(),
|
||||
masterKey: z.string().max(256).optional(),
|
||||
vaultMasterKey: z.string().max(256).optional(),
|
||||
});
|
||||
|
||||
export function createBackupRouter(deps: BackupRouterDeps): Router {
|
||||
const router = Router();
|
||||
const {
|
||||
dataDir,
|
||||
db,
|
||||
authService,
|
||||
vaultService,
|
||||
configManager,
|
||||
auditService,
|
||||
stepUpGuard,
|
||||
onRestored,
|
||||
} = deps;
|
||||
|
||||
router.post(
|
||||
'/export',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const parsed = ExportBackupBodySchema.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const passphrase = parsed.data.passphrase?.trim() || undefined;
|
||||
const masterKey = vaultService.exportMasterKeyHex() ?? undefined;
|
||||
if (!passphrase && !masterKey) {
|
||||
res.status(423).json({
|
||||
error: 'VAULT_LOCKED',
|
||||
message: 'Vault is sealed; unlock Vault or provide a backup passphrase.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = createBackupBundle({
|
||||
dataDir,
|
||||
db,
|
||||
masterKey,
|
||||
passphrase,
|
||||
});
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
|
||||
const filename = `gcoordinator-backup-${stamp}.gcoord.enc`;
|
||||
|
||||
auditService.log({
|
||||
action: 'backup.export',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: filename,
|
||||
status: 'ok',
|
||||
details: {
|
||||
kdf: result.summary.kdf,
|
||||
configFileCount: result.summary.configFileCount,
|
||||
knownHostsCount: result.summary.knownHostsCount,
|
||||
},
|
||||
});
|
||||
|
||||
res.json({
|
||||
filename,
|
||||
bundleBase64: Buffer.from(result.serialized, 'utf8').toString('base64'),
|
||||
summary: result.summary,
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'BACKUP_EXPORT_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to create backup bundle',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Read-only verification: exempt from enforceSafeMode
|
||||
router.post('/verify', requireAuth(authService), requireCsrf, (req, res) => {
|
||||
const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64');
|
||||
const summary = verifyBackupSummaryOnly(rawBuf, {
|
||||
masterKey:
|
||||
parsed.data.masterKey?.trim() || vaultService.exportMasterKeyHex() || undefined,
|
||||
passphrase: parsed.data.passphrase?.trim() || undefined,
|
||||
vaultMasterKey: parsed.data.vaultMasterKey?.trim() || undefined,
|
||||
});
|
||||
res.json({ summary });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'BACKUP_INVALID',
|
||||
message: err instanceof Error ? err.message : 'Backup verification failed',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post(
|
||||
'/restore',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64');
|
||||
const passphrase = parsed.data.passphrase?.trim() || undefined;
|
||||
const runtimeKey = vaultService.exportMasterKeyHex() ?? undefined;
|
||||
const masterKey = parsed.data.masterKey?.trim() || runtimeKey;
|
||||
const vaultMasterKey = parsed.data.vaultMasterKey?.trim() || undefined;
|
||||
|
||||
const wasWatching = await configManager.pauseWatcher();
|
||||
try {
|
||||
const restored = restoreBackupBundle(rawBuf, {
|
||||
dataDir,
|
||||
db,
|
||||
masterKey,
|
||||
passphrase,
|
||||
vaultMasterKey,
|
||||
});
|
||||
|
||||
await onRestored({
|
||||
summary: restored.summary,
|
||||
inner: restored.inner,
|
||||
vaultKeyCandidate: vaultMasterKey || masterKey,
|
||||
});
|
||||
|
||||
auditService.log({
|
||||
action: 'backup.restore',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: 'data',
|
||||
status: 'ok',
|
||||
details: {
|
||||
configFileCount: restored.summary.configFileCount,
|
||||
knownHostsCount: restored.summary.knownHostsCount,
|
||||
vaultVerified: restored.summary.vaultVerified,
|
||||
},
|
||||
});
|
||||
|
||||
res.json({ restored: true, summary: restored.summary });
|
||||
} catch (err) {
|
||||
auditService.log({
|
||||
action: 'backup.restore',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: 'data',
|
||||
status: 'error',
|
||||
details: { message: err instanceof Error ? err.message : String(err) },
|
||||
});
|
||||
res.status(400).json({
|
||||
error: 'BACKUP_RESTORE_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Backup restore failed',
|
||||
});
|
||||
} finally {
|
||||
if (wasWatching) {
|
||||
await configManager.resumeWatcher();
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue