feat(security): add strictness settings schema, multi-auth migration, and EmergencyRecoveryService
This commit is contained in:
parent
4ac7b5d1b4
commit
f3d05db412
5 changed files with 365 additions and 1 deletions
|
|
@ -2,8 +2,9 @@ import fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import Database from 'better-sqlite3';
|
import Database from 'better-sqlite3';
|
||||||
import { migration001Initial, type Migration } from './migrations/001_initial.js';
|
import { migration001Initial, type Migration } from './migrations/001_initial.js';
|
||||||
|
import { migration002MultiAuth } from './migrations/002_multi_auth.js';
|
||||||
|
|
||||||
const MIGRATIONS: Migration[] = [migration001Initial];
|
const MIGRATIONS: Migration[] = [migration001Initial, migration002MultiAuth];
|
||||||
|
|
||||||
export function openDatabase(dbPath: string): Database.Database {
|
export function openDatabase(dbPath: string): Database.Database {
|
||||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||||
|
|
|
||||||
65
src/server/db/migrations/002_multi_auth.ts
Normal file
65
src/server/db/migrations/002_multi_auth.ts
Normal file
|
|
@ -0,0 +1,65 @@
|
||||||
|
import type { Migration } from './001_initial.js';
|
||||||
|
|
||||||
|
interface LegacyAdminRow {
|
||||||
|
username: string;
|
||||||
|
password_hash: string;
|
||||||
|
totp_secret: string;
|
||||||
|
last_login_totp_step: number | null;
|
||||||
|
last_stepup_totp_step: number | null;
|
||||||
|
created_at: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const migration002MultiAuth: Migration = {
|
||||||
|
id: '002_multi_auth',
|
||||||
|
up(db) {
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS admin_passwords (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
label TEXT NOT NULL,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS admin_totps (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
label TEXT NOT NULL,
|
||||||
|
secret_base32 TEXT NOT NULL,
|
||||||
|
last_login_step INTEGER,
|
||||||
|
last_stepup_step INTEGER,
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
|
||||||
|
const legacy = db
|
||||||
|
.prepare('SELECT * FROM admin_users WHERE id = 1')
|
||||||
|
.get() as LegacyAdminRow | undefined;
|
||||||
|
|
||||||
|
if (legacy) {
|
||||||
|
const pwCount = (
|
||||||
|
db.prepare('SELECT COUNT(*) AS cnt FROM admin_passwords').get() as { cnt: number }
|
||||||
|
).cnt;
|
||||||
|
if (pwCount === 0) {
|
||||||
|
db.prepare(
|
||||||
|
'INSERT INTO admin_passwords (id, label, password_hash, created_at) VALUES (?, ?, ?, ?)',
|
||||||
|
).run('pw-primary', 'Primary Password', legacy.password_hash, legacy.created_at);
|
||||||
|
}
|
||||||
|
|
||||||
|
const totpCount = (
|
||||||
|
db.prepare('SELECT COUNT(*) AS cnt FROM admin_totps').get() as { cnt: number }
|
||||||
|
).cnt;
|
||||||
|
if (totpCount === 0) {
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||||
|
).run(
|
||||||
|
'totp-primary',
|
||||||
|
'Primary Authenticator',
|
||||||
|
legacy.totp_secret,
|
||||||
|
legacy.last_login_totp_step,
|
||||||
|
legacy.last_stepup_totp_step,
|
||||||
|
legacy.created_at,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
259
src/server/security/recovery-store.ts
Normal file
259
src/server/security/recovery-store.ts
Normal file
|
|
@ -0,0 +1,259 @@
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import type { VaultCredential } from '../../shared/schemas/vault.schema.js';
|
||||||
|
import type { VaultService } from './vault.js';
|
||||||
|
|
||||||
|
export interface SavedPasswordEntry {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
plaintextPassword?: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SavedTotpEntry {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
secretBase32: string;
|
||||||
|
otpauthUri: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EmergencySecretsBundle {
|
||||||
|
version: 1;
|
||||||
|
updatedAt: string;
|
||||||
|
note: string;
|
||||||
|
vaultMasterKeyHex: string | null;
|
||||||
|
admin: {
|
||||||
|
username: string | null;
|
||||||
|
passwords: SavedPasswordEntry[];
|
||||||
|
totps: SavedTotpEntry[];
|
||||||
|
recoveryCodes: string[];
|
||||||
|
};
|
||||||
|
vaultCredentials: Record<string, VaultCredential>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RecoveryBackupStatus {
|
||||||
|
enabled: boolean;
|
||||||
|
exists: boolean;
|
||||||
|
filePath: string;
|
||||||
|
updatedAt?: string;
|
||||||
|
snapshotCount: number;
|
||||||
|
hasMasterKey: boolean;
|
||||||
|
credentialCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SyncRecoveryOptions {
|
||||||
|
enabled: boolean;
|
||||||
|
vault: VaultService;
|
||||||
|
username?: string | null;
|
||||||
|
totps?: SavedTotpEntry[];
|
||||||
|
passwordMetaList?: Array<{ id: string; label: string; createdAt: number }>;
|
||||||
|
passwordPlaintextUpdate?: { id: string; label: string; password: string; createdAt?: number };
|
||||||
|
removedPasswordId?: string;
|
||||||
|
newRecoveryCodes?: string[];
|
||||||
|
snapshotReason?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_SNAPSHOTS = 10;
|
||||||
|
|
||||||
|
export class EmergencyRecoveryService {
|
||||||
|
private readonly recoveryDir: string;
|
||||||
|
private readonly snapshotsDir: string;
|
||||||
|
private readonly bundlePath: string;
|
||||||
|
|
||||||
|
constructor(dataDir: string) {
|
||||||
|
this.recoveryDir = path.join(path.resolve(dataDir), 'recovery');
|
||||||
|
this.snapshotsDir = path.join(this.recoveryDir, 'snapshots');
|
||||||
|
this.bundlePath = path.join(this.recoveryDir, 'emergency-secrets.json');
|
||||||
|
}
|
||||||
|
|
||||||
|
get filePath(): string {
|
||||||
|
return this.bundlePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
readBundle(): EmergencySecretsBundle | null {
|
||||||
|
if (!fs.existsSync(this.bundlePath)) return null;
|
||||||
|
try {
|
||||||
|
const raw = JSON.parse(fs.readFileSync(this.bundlePath, 'utf8'));
|
||||||
|
if (!raw || typeof raw !== 'object' || raw.version !== 1) return null;
|
||||||
|
return raw as EmergencySecretsBundle;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
readSavedMasterKeyHex(): string | undefined {
|
||||||
|
const bundle = this.readBundle();
|
||||||
|
const key = bundle?.vaultMasterKeyHex?.trim();
|
||||||
|
if (key && /^[0-9a-fA-F]{64}$/.test(key)) {
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
syncState(opts: SyncRecoveryOptions): EmergencySecretsBundle | null {
|
||||||
|
if (!opts.enabled) return null;
|
||||||
|
|
||||||
|
const existing = this.readBundle();
|
||||||
|
const nowIso = new Date().toISOString();
|
||||||
|
|
||||||
|
const masterKeyHex =
|
||||||
|
opts.vault.state === 'unlocked'
|
||||||
|
? opts.vault.exportMasterKeyHex()
|
||||||
|
: existing?.vaultMasterKeyHex ?? null;
|
||||||
|
|
||||||
|
const vaultCredentials =
|
||||||
|
opts.vault.state === 'unlocked'
|
||||||
|
? opts.vault.exportAllCredentials()
|
||||||
|
: existing?.vaultCredentials ?? {};
|
||||||
|
|
||||||
|
// Merge saved plaintext passwords safely across updates
|
||||||
|
const prevPwById = new Map<string, SavedPasswordEntry>();
|
||||||
|
for (const p of existing?.admin.passwords ?? []) {
|
||||||
|
prevPwById.set(p.id, p);
|
||||||
|
}
|
||||||
|
if (opts.removedPasswordId) {
|
||||||
|
prevPwById.delete(opts.removedPasswordId);
|
||||||
|
}
|
||||||
|
if (opts.passwordPlaintextUpdate) {
|
||||||
|
const u = opts.passwordPlaintextUpdate;
|
||||||
|
prevPwById.set(u.id, {
|
||||||
|
id: u.id,
|
||||||
|
label: u.label,
|
||||||
|
plaintextPassword: u.password,
|
||||||
|
createdAt: new Date(u.createdAt ?? Date.now()).toISOString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let finalPasswords: SavedPasswordEntry[];
|
||||||
|
if (opts.passwordMetaList) {
|
||||||
|
finalPasswords = opts.passwordMetaList.map((meta) => {
|
||||||
|
const prev = prevPwById.get(meta.id);
|
||||||
|
return {
|
||||||
|
id: meta.id,
|
||||||
|
label: meta.label,
|
||||||
|
plaintextPassword: prev?.plaintextPassword,
|
||||||
|
createdAt: new Date(meta.createdAt).toISOString(),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
finalPasswords = [...prevPwById.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
const bundle: EmergencySecretsBundle = {
|
||||||
|
version: 1,
|
||||||
|
updatedAt: nowIso,
|
||||||
|
note: 'Local emergency plaintext backup managed by GCoordinator. Keep this file private (chmod 0600).',
|
||||||
|
vaultMasterKeyHex: masterKeyHex,
|
||||||
|
admin: {
|
||||||
|
username: opts.username !== undefined ? opts.username : existing?.admin.username ?? null,
|
||||||
|
passwords: finalPasswords,
|
||||||
|
totps: opts.totps ?? existing?.admin.totps ?? [],
|
||||||
|
recoveryCodes: opts.newRecoveryCodes ?? existing?.admin.recoveryCodes ?? [],
|
||||||
|
},
|
||||||
|
vaultCredentials,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.ensureDirs();
|
||||||
|
const serialized = `${JSON.stringify(bundle, null, 2)}\n`;
|
||||||
|
this.writeAtomicSecure(this.bundlePath, serialized);
|
||||||
|
|
||||||
|
if (opts.snapshotReason) {
|
||||||
|
const safeReason = opts.snapshotReason.replace(/[^a-z0-9_-]/gi, '-');
|
||||||
|
const snapName = `emergency-secrets-${Date.now()}-${safeReason}.json`;
|
||||||
|
this.writeAtomicSecure(path.join(this.snapshotsDir, snapName), serialized);
|
||||||
|
this.pruneSnapshots();
|
||||||
|
}
|
||||||
|
|
||||||
|
return bundle;
|
||||||
|
}
|
||||||
|
|
||||||
|
getStatus(enabled: boolean): RecoveryBackupStatus {
|
||||||
|
const bundle = this.readBundle();
|
||||||
|
const snapFiles = fs.existsSync(this.snapshotsDir)
|
||||||
|
? fs.readdirSync(this.snapshotsDir).filter((f) => f.endsWith('.json'))
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return {
|
||||||
|
enabled,
|
||||||
|
exists: bundle !== null,
|
||||||
|
filePath: this.bundlePath,
|
||||||
|
updatedAt: bundle?.updatedAt,
|
||||||
|
snapshotCount: snapFiles.length,
|
||||||
|
hasMasterKey: Boolean(bundle?.vaultMasterKeyHex),
|
||||||
|
credentialCount: bundle ? Object.keys(bundle.vaultCredentials).length : 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
wipeAll(): void {
|
||||||
|
const shred = (filePath: string) => {
|
||||||
|
if (!fs.existsSync(filePath)) return;
|
||||||
|
try {
|
||||||
|
const stat = fs.statSync(filePath);
|
||||||
|
if (stat.isFile() && stat.size > 0) {
|
||||||
|
const fd = fs.openSync(filePath, 'r+');
|
||||||
|
try {
|
||||||
|
fs.writeSync(fd, Buffer.alloc(stat.size, 0), 0, stat.size, 0);
|
||||||
|
fs.fsyncSync(fd);
|
||||||
|
} finally {
|
||||||
|
fs.closeSync(fd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Best-effort overwrite before unlink
|
||||||
|
}
|
||||||
|
fs.unlinkSync(filePath);
|
||||||
|
};
|
||||||
|
|
||||||
|
shred(this.bundlePath);
|
||||||
|
if (fs.existsSync(this.snapshotsDir)) {
|
||||||
|
for (const f of fs.readdirSync(this.snapshotsDir)) {
|
||||||
|
shred(path.join(this.snapshotsDir, f));
|
||||||
|
}
|
||||||
|
fs.rmdirSync(this.snapshotsDir);
|
||||||
|
}
|
||||||
|
if (fs.existsSync(this.recoveryDir)) {
|
||||||
|
try {
|
||||||
|
fs.rmdirSync(this.recoveryDir);
|
||||||
|
} catch {
|
||||||
|
// Ignore if unexpected files remain
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensureDirs(): void {
|
||||||
|
fs.mkdirSync(this.recoveryDir, { recursive: true, mode: 0o700 });
|
||||||
|
fs.chmodSync(this.recoveryDir, 0o700);
|
||||||
|
fs.mkdirSync(this.snapshotsDir, { recursive: true, mode: 0o700 });
|
||||||
|
fs.chmodSync(this.snapshotsDir, 0o700);
|
||||||
|
}
|
||||||
|
|
||||||
|
private writeAtomicSecure(targetPath: string, content: string): void {
|
||||||
|
const tmpPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
|
||||||
|
const fd = fs.openSync(tmpPath, 'w', 0o600);
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(fd, content, 'utf8');
|
||||||
|
fs.fsyncSync(fd);
|
||||||
|
} finally {
|
||||||
|
fs.closeSync(fd);
|
||||||
|
}
|
||||||
|
fs.renameSync(tmpPath, targetPath);
|
||||||
|
fs.chmodSync(targetPath, 0o600);
|
||||||
|
}
|
||||||
|
|
||||||
|
private pruneSnapshots(): void {
|
||||||
|
if (!fs.existsSync(this.snapshotsDir)) return;
|
||||||
|
const files = fs
|
||||||
|
.readdirSync(this.snapshotsDir)
|
||||||
|
.filter((f) => f.endsWith('.json'))
|
||||||
|
.sort();
|
||||||
|
while (files.length > MAX_SNAPSHOTS) {
|
||||||
|
const oldest = files.shift()!;
|
||||||
|
try {
|
||||||
|
fs.unlinkSync(path.join(this.snapshotsDir, oldest));
|
||||||
|
} catch {
|
||||||
|
// Ignore cleanup failure
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -270,6 +270,19 @@ export class VaultService {
|
||||||
return cred ? structuredClone(cred) : undefined;
|
return cred ? structuredClone(cred) : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
exportMasterKeyHex(): string | null {
|
||||||
|
return this.masterKey ? this.masterKey.toString('hex') : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
exportAllCredentials(): Record<string, VaultCredential> {
|
||||||
|
this.assertUnlocked();
|
||||||
|
const out: Record<string, VaultCredential> = {};
|
||||||
|
for (const [id, cred] of this.credentials.entries()) {
|
||||||
|
out[id] = structuredClone(cred);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
upsertCredential(input: VaultCredentialInput): VaultCredentialMeta {
|
upsertCredential(input: VaultCredentialInput): VaultCredentialMeta {
|
||||||
this.assertUnlocked();
|
this.assertUnlocked();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,28 @@ export const ThemeIdSchema = z.enum([
|
||||||
'paper-light',
|
'paper-light',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
export const StepUpPolicySchema = z.enum([
|
||||||
|
'off',
|
||||||
|
'every-action',
|
||||||
|
'5m',
|
||||||
|
'1h',
|
||||||
|
'24h',
|
||||||
|
'session',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const StepUpMethodSchema = z.enum(['totp', 'password', 'both']);
|
||||||
|
|
||||||
|
export const SecuritySettingsSchema = z.object({
|
||||||
|
requireTotpOnLogin: z.boolean().default(true),
|
||||||
|
passwordMode: z.enum(['any', 'all']).default('any'),
|
||||||
|
totpMode: z.enum(['any', 'all']).default('any'),
|
||||||
|
stepUpPolicy: StepUpPolicySchema.default('1h'),
|
||||||
|
stepUpMethod: StepUpMethodSchema.default('totp'),
|
||||||
|
elevateOnLogin: z.boolean().default(true),
|
||||||
|
keepElevationOnSafeMode: z.boolean().default(true),
|
||||||
|
enableEmergencySecretsBackup: z.boolean().default(true),
|
||||||
|
});
|
||||||
|
|
||||||
export const SettingsSchema = z.object({
|
export const SettingsSchema = z.object({
|
||||||
version: z.literal(1).default(1),
|
version: z.literal(1).default(1),
|
||||||
theme: ThemeIdSchema.default('phosphor-green'),
|
theme: ThemeIdSchema.default('phosphor-green'),
|
||||||
|
|
@ -20,6 +42,7 @@ export const SettingsSchema = z.object({
|
||||||
ptyIdleTtlSec: z.number().int().min(60).max(604800).default(43200),
|
ptyIdleTtlSec: z.number().int().min(60).max(604800).default(43200),
|
||||||
sshKeepaliveMs: z.number().int().min(5000).max(120000).default(15000),
|
sshKeepaliveMs: z.number().int().min(5000).max(120000).default(15000),
|
||||||
sshReadyTimeoutMs: z.number().int().min(3000).max(120000).default(15000),
|
sshReadyTimeoutMs: z.number().int().min(3000).max(120000).default(15000),
|
||||||
|
security: SecuritySettingsSchema.default({}),
|
||||||
ai: z
|
ai: z
|
||||||
.object({
|
.object({
|
||||||
enabled: z.boolean().default(false),
|
enabled: z.boolean().default(false),
|
||||||
|
|
@ -37,4 +60,7 @@ export const SettingsSchema = z.object({
|
||||||
});
|
});
|
||||||
|
|
||||||
export type ThemeId = z.infer<typeof ThemeIdSchema>;
|
export type ThemeId = z.infer<typeof ThemeIdSchema>;
|
||||||
|
export type StepUpPolicy = z.infer<typeof StepUpPolicySchema>;
|
||||||
|
export type StepUpMethod = z.infer<typeof StepUpMethodSchema>;
|
||||||
|
export type SecuritySettings = z.infer<typeof SecuritySettingsSchema>;
|
||||||
export type SettingsConfig = z.infer<typeof SettingsSchema>;
|
export type SettingsConfig = z.infer<typeof SettingsSchema>;
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue