feat: web setup wizard + admin config/state dir split (#226)

This commit is contained in:
Linus Rath
2026-05-09 17:37:41 +02:00
parent c44a9ce6e0
commit 51745ea03d
36 changed files with 2612 additions and 164 deletions
+7 -14
View File
@@ -1,28 +1,23 @@
import { appendFile, stat, rename, mkdir } from 'node:fs/promises';
import { appendFile, stat, rename, readFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { logger } from '@/lib/logger';
import { ensureStateDir, getStatePath } from './paths';
import type { AuditEntry } from './types';
const MAX_LOG_SIZE = 10 * 1024 * 1024; // 10 MB
const MAX_ROTATIONS = 3;
function getAdminDir(): string {
return process.env.ADMIN_DATA_DIR || path.join(process.cwd(), 'data', 'admin');
}
const AUDIT_LOG_FILE = 'audit.log';
function getAuditLogPath(): string {
return path.join(getAdminDir(), 'audit.log');
return getStatePath(AUDIT_LOG_FILE);
}
/**
* Append an audit entry to the admin audit log.
* Append an audit entry to the admin audit log. Stored under the state dir
* so it remains writable when the config dir is mounted read-only.
*/
export async function auditLog(action: string, detail: Record<string, unknown>, ip: string): Promise<void> {
const dir = getAdminDir();
if (!existsSync(dir)) {
await mkdir(dir, { recursive: true });
}
await ensureStateDir();
const entry: AuditEntry = {
ts: new Date().toISOString(),
@@ -64,7 +59,6 @@ async function rotateIfNeeded(logPath: string): Promise<void> {
export async function readAuditLog(page: number = 1, limit: number = 50, actionFilter?: string): Promise<{ entries: AuditEntry[]; total: number }> {
const logPath = getAuditLogPath();
try {
const { readFile } = await import('node:fs/promises');
const content = await readFile(logPath, 'utf-8');
const lines = content.trim().split('\n').filter(Boolean);
@@ -77,7 +71,6 @@ export async function readAuditLog(page: number = 1, limit: number = 50, actionF
}
const total = entries.length;
// Return newest first
entries.reverse();
const start = (page - 1) * limit;
return { entries: entries.slice(start, start + limit), total };
+36 -14
View File
@@ -1,13 +1,8 @@
import { readFile, writeFile, mkdir, rename } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { readFile, writeFile, rename } from 'node:fs/promises';
import { logger } from '@/lib/logger';
import { readFileEnv } from '@/lib/read-file-env';
import { CONFIG_ENV_MAP, DEFAULT_FEATURE_GATES, DEFAULT_POLICY, DEFAULT_THEME_POLICY, type SettingsPolicy } from './types';
function getAdminDir(): string {
return process.env.ADMIN_DATA_DIR || path.join(process.cwd(), 'data', 'admin');
}
import { ensureConfigDir, getConfigPath, assertWritable } from './paths';
function parseEnvValue(value: string, type: string): unknown {
switch (type) {
@@ -127,6 +122,7 @@ class ConfigManager {
* Update admin config overrides. Writes to disk.
*/
async setAdminConfig(updates: Record<string, unknown>): Promise<void> {
assertWritable('update admin config');
Object.assign(this.adminConfig, updates);
await this.writeJsonFile('config.json', this.adminConfig);
}
@@ -135,10 +131,29 @@ class ConfigManager {
* Remove an admin override, reverting to env/default.
*/
async removeAdminOverride(key: string): Promise<void> {
assertWritable('remove admin override');
delete this.adminConfig[key];
await this.writeJsonFile('config.json', this.adminConfig);
}
/**
* Whether the setup wizard has completed. Used by middleware to gate the
* /setup routes and the rest of the app.
*/
isSetupComplete(): boolean {
return this.adminConfig.setupComplete === true;
}
/**
* Mark setup wizard as complete. Called by the wizard's finish endpoint
* after all other config has been written. Refuses in read-only mode.
*/
async markSetupComplete(): Promise<void> {
assertWritable('mark setup complete');
this.adminConfig.setupComplete = true;
await this.writeJsonFile('config.json', this.adminConfig);
}
/**
* Get the current settings policy.
*/
@@ -150,6 +165,7 @@ class ConfigManager {
* Update the settings policy. Writes to disk.
*/
async setPolicy(policy: SettingsPolicy): Promise<void> {
assertWritable('update settings policy');
this.policyCache = {
...DEFAULT_POLICY,
...policy,
@@ -167,7 +183,7 @@ class ConfigManager {
}
private async readJsonFile(filename: string): Promise<Record<string, unknown> | null> {
const filePath = path.join(getAdminDir(), filename);
const filePath = getConfigPath(filename);
try {
const raw = await readFile(filePath, 'utf-8');
return JSON.parse(raw);
@@ -179,15 +195,21 @@ class ConfigManager {
}
private async writeJsonFile(filename: string, data: Record<string, unknown>): Promise<void> {
const dir = getAdminDir();
if (!existsSync(dir)) {
await mkdir(dir, { recursive: true });
}
const targetPath = path.join(dir, filename);
await ensureConfigDir();
const targetPath = getConfigPath(filename);
const tmpPath = targetPath + '.tmp';
await writeFile(tmpPath, JSON.stringify(data, null, 2), 'utf-8');
await rename(tmpPath, targetPath);
}
}
export const configManager = new ConfigManager();
// Stash the singleton on globalThis so HMR / multiple module-evaluation
// boundaries (middleware vs route handlers in dev with turbopack) all share
// the same in-memory state. Without this, marking setupComplete=true in a
// route handler is invisible to the next middleware run, and the wizard
// redirect after finish never fires.
const SINGLETON_KEY = Symbol.for('bulwark.admin.configManager');
type GlobalWithConfig = typeof globalThis & { [SINGLETON_KEY]?: ConfigManager };
const g = globalThis as GlobalWithConfig;
export const configManager: ConfigManager =
g[SINGLETON_KEY] ?? (g[SINGLETON_KEY] = new ConfigManager());
+196
View File
@@ -0,0 +1,196 @@
import { readFile, writeFile, rename, stat, unlink } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { logger } from '@/lib/logger';
import {
ensureConfigDir,
ensureStateDir,
getConfigPath,
getStatePath,
isConfigReadOnly,
} from './paths';
import type { AdminConfigData, AdminStateData } from './types';
const MIGRATION_MARKER = '.migrated-v2';
interface LegacyAdminData {
passwordHash: string;
createdAt?: string;
lastLogin?: string | null;
passwordChangedAt?: string;
}
/**
* One-shot migration from the v1 layout (everything mixed in `data/admin/`)
* to the v2 layout (config + state split, see lib/admin/paths.ts).
*
* Idempotent: writes a `.migrated-v2` marker into the config dir on success.
*
* Migrations performed:
* 1. admin.json with timestamps → admin.json (passwordHash only) +
* admin-state.json (createdAt, lastLogin, passwordChangedAt)
* 2. audit.log moved from config dir to state dir (by rename if same FS,
* else copy + delete).
*
* Skipped silently when the config dir is read-only - operators who already
* locked their config volume must do the migration manually before mounting
* :ro.
*/
export async function migrateLegacyAdminLayout(): Promise<void> {
if (isConfigReadOnly()) return;
const markerPath = getConfigPath(MIGRATION_MARKER);
if (existsSync(markerPath)) return;
let didWork = false;
try {
didWork = (await migrateAdminJson()) || didWork;
didWork = (await migrateAuditLog()) || didWork;
await ensureConfigDir();
await writeFile(markerPath, new Date().toISOString(), 'utf-8');
if (didWork) {
logger.info('Admin layout migrated to v2 (config/state split)');
}
} catch (error) {
logger.warn('Admin layout migration failed; will retry on next boot', {
error: error instanceof Error ? error.message : 'Unknown error',
});
}
}
/**
* If the existing admin.json carries timestamp fields (legacy mixed layout),
* split them into admin-state.json and rewrite admin.json without them.
* Returns true if a migration was performed.
*/
async function migrateAdminJson(): Promise<boolean> {
const adminJsonPath = getConfigPath('admin.json');
if (!existsSync(adminJsonPath)) return false;
let raw: string;
try {
raw = await readFile(adminJsonPath, 'utf-8');
} catch {
return false;
}
let data: LegacyAdminData;
try {
data = JSON.parse(raw) as LegacyAdminData;
} catch {
logger.warn('admin.json is not valid JSON; skipping migration');
return false;
}
const hasLegacyFields =
'createdAt' in data || 'lastLogin' in data || 'passwordChangedAt' in data;
if (!hasLegacyFields) return false; // already in v2 shape
if (!data.passwordHash || typeof data.passwordHash !== 'string') {
logger.warn('admin.json missing passwordHash; skipping migration');
return false;
}
const now = new Date().toISOString();
const stateData: AdminStateData = {
createdAt: data.createdAt ?? now,
lastLogin: data.lastLogin ?? null,
passwordChangedAt: data.passwordChangedAt ?? now,
};
const configData: AdminConfigData = { passwordHash: data.passwordHash };
await ensureStateDir();
const statePath = getStatePath('admin-state.json');
// If admin-state.json already exists, prefer its values: a previous
// migration may have succeeded and recorded fresh login timestamps that
// we'd otherwise stomp. The legacy admin.json data is older by definition.
if (!existsSync(statePath)) {
const stateTmp = statePath + '.tmp';
await writeFile(stateTmp, JSON.stringify(stateData, null, 2), 'utf-8');
await rename(stateTmp, statePath);
}
const configTmp = adminJsonPath + '.tmp';
await writeFile(configTmp, JSON.stringify(configData, null, 2), 'utf-8');
await rename(configTmp, adminJsonPath);
logger.info('Migrated admin.json: split timestamps into admin-state.json');
return true;
}
/**
* Move audit.log from the config dir to the state dir if present. Returns
* true if a migration was performed. Also moves rotated copies (audit.log.1
* through .3).
*/
async function migrateAuditLog(): Promise<boolean> {
const sources = [
'audit.log',
'audit.log.1',
'audit.log.2',
'audit.log.3',
];
let moved = false;
for (const name of sources) {
const src = getConfigPath(name);
if (!existsSync(src)) continue;
await ensureStateDir();
const dst = getStatePath(name);
try {
// Same-FS rename is atomic. Falls through to copy if cross-device.
await rename(src, dst);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === 'EXDEV') {
// Cross-device: copy bytes, then delete source.
const data = await readFile(src);
await writeFile(dst, data);
await unlink(src);
} else {
throw error;
}
}
moved = true;
}
if (moved) {
logger.info('Migrated audit.log to state dir');
}
return moved;
}
/**
* Returns approximate size of legacy data still mixed in the config dir
* (for diagnostics / admin UI). Always returns 0 once migration has run.
*/
export async function getLegacyDataInfo(): Promise<{ adminJsonHasTimestamps: boolean; auditLogInConfigDir: boolean }> {
let adminJsonHasTimestamps = false;
const adminJsonPath = getConfigPath('admin.json');
if (existsSync(adminJsonPath)) {
try {
const raw = await readFile(adminJsonPath, 'utf-8');
const parsed = JSON.parse(raw);
adminJsonHasTimestamps =
'createdAt' in parsed ||
'lastLogin' in parsed ||
'passwordChangedAt' in parsed;
} catch {
/* ignore */
}
}
let auditLogInConfigDir = false;
try {
await stat(getConfigPath('audit.log'));
auditLogInConfigDir = true;
} catch {
/* not present - good */
}
return { adminJsonHasTimestamps, auditLogInConfigDir };
}
+115 -84
View File
@@ -1,9 +1,14 @@
import { scrypt, randomBytes, timingSafeEqual } from 'node:crypto';
import { readFile, writeFile, mkdir, rename } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { readFile, writeFile, rename } from 'node:fs/promises';
import { logger } from '@/lib/logger';
import type { AdminData } from './types';
import {
ensureConfigDir,
ensureStateDir,
getConfigPath,
getStatePath,
assertWritable,
} from './paths';
import type { AdminConfigData, AdminStateData } from './types';
const SCRYPT_KEYLEN = 64;
const SCRYPT_COST = 16384; // 2^14
@@ -11,13 +16,8 @@ const SCRYPT_BLOCK_SIZE = 8;
const SCRYPT_PARALLELIZATION = 1;
const SALT_LENGTH = 32;
function getAdminDir(): string {
return process.env.ADMIN_DATA_DIR || path.join(process.cwd(), 'data', 'admin');
}
function getAdminJsonPath(): string {
return path.join(getAdminDir(), 'admin.json');
}
const ADMIN_CONFIG_FILE = 'admin.json';
const ADMIN_STATE_FILE = 'admin-state.json';
function hashPassword(password: string): Promise<string> {
return new Promise((resolve, reject) => {
@@ -33,10 +33,8 @@ function hashPassword(password: string): Promise<string> {
function verifyPassword(password: string, stored: string): Promise<boolean> {
return new Promise((resolve, reject) => {
// Support both scrypt format and bcrypt-prefixed values
if (stored.startsWith('$scrypt$')) {
const parts = stored.split('$');
// $scrypt$N=...,r=...,p=...$salt$hash
if (parts.length !== 5) return resolve(false);
const paramStr = parts[2];
const salt = Buffer.from(parts[3], 'base64');
@@ -53,7 +51,6 @@ function verifyPassword(password: string, stored: string): Promise<boolean> {
resolve(timingSafeEqual(derivedKey, storedHash));
});
} else {
// Unknown format
resolve(false);
}
});
@@ -63,50 +60,84 @@ function isHashed(value: string): boolean {
return value.startsWith('$scrypt$') || value.startsWith('$2a$') || value.startsWith('$2b$');
}
async function readAdminData(): Promise<AdminData | null> {
const filePath = getAdminJsonPath();
// ─── Disk I/O ───────────────────────────────────────────────────────────────
async function readJson<T>(filePath: string): Promise<T | null> {
try {
const raw = await readFile(filePath, 'utf-8');
return JSON.parse(raw) as AdminData;
return JSON.parse(raw) as T;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
logger.warn('Failed to read admin.json', { error: error instanceof Error ? error.message : 'Unknown error' });
logger.warn('Failed to read admin file', {
filePath,
error: error instanceof Error ? error.message : 'Unknown error',
});
return null;
}
}
async function writeAdminData(data: AdminData): Promise<void> {
const dir = getAdminDir();
if (!existsSync(dir)) {
await mkdir(dir, { recursive: true });
}
const targetPath = getAdminJsonPath();
const tmpPath = targetPath + '.tmp';
await writeFile(tmpPath, JSON.stringify(data, null, 2), 'utf-8');
await rename(tmpPath, targetPath);
async function readConfigData(): Promise<AdminConfigData | null> {
return readJson<AdminConfigData>(getConfigPath(ADMIN_CONFIG_FILE));
}
let cachedAdminData: AdminData | null = null;
async function readStateData(): Promise<AdminStateData | null> {
return readJson<AdminStateData>(getStatePath(ADMIN_STATE_FILE));
}
async function writeConfigData(data: AdminConfigData): Promise<void> {
assertWritable('save admin password');
await ensureConfigDir();
const target = getConfigPath(ADMIN_CONFIG_FILE);
const tmp = target + '.tmp';
await writeFile(tmp, JSON.stringify(data, null, 2), 'utf-8');
await rename(tmp, target);
}
async function writeStateData(data: AdminStateData): Promise<void> {
await ensureStateDir();
const target = getStatePath(ADMIN_STATE_FILE);
const tmp = target + '.tmp';
await writeFile(tmp, JSON.stringify(data, null, 2), 'utf-8');
await rename(tmp, target);
}
// ─── Cache & init ───────────────────────────────────────────────────────────
let cachedConfig: AdminConfigData | null = null;
let cachedState: AdminStateData | null = null;
let initialized = false;
function freshState(): AdminStateData {
const now = new Date().toISOString();
return { createdAt: now, lastLogin: null, passwordChangedAt: now };
}
/**
* Initialize admin password on startup.
* If ADMIN_PASSWORD is cleartext, hash it and write to admin.json.
* Returns true if admin is enabled.
* - If admin.json exists, use it (state file may or may not exist; created on first need).
* - Otherwise, if ADMIN_PASSWORD env var is set, hash and persist it.
* - Otherwise, admin dashboard stays disabled.
*/
export async function initAdminPassword(): Promise<boolean> {
if (initialized) return cachedAdminData !== null;
if (initialized) return cachedConfig !== null;
// Check persistent file first
const existing = await readAdminData();
if (existing) {
cachedAdminData = existing;
const existingConfig = await readConfigData();
if (existingConfig) {
cachedConfig = existingConfig;
cachedState = (await readStateData()) ?? freshState();
if (!(await readStateData())) {
// No state file yet (fresh install or migration); create it.
try {
await writeStateData(cachedState);
} catch {
/* state dir may not be writable yet during early boot probes */
}
}
initialized = true;
logger.info('Admin dashboard enabled (password loaded from admin.json)');
return true;
}
// Check env var
const envPassword = process.env.ADMIN_PASSWORD;
if (!envPassword) {
initialized = true;
@@ -114,33 +145,17 @@ export async function initAdminPassword(): Promise<boolean> {
return false;
}
if (isHashed(envPassword)) {
// Already hashed in env - save to file
const data: AdminData = {
passwordHash: envPassword,
createdAt: new Date().toISOString(),
lastLogin: null,
passwordChangedAt: new Date().toISOString(),
};
await writeAdminData(data);
cachedAdminData = data;
initialized = true;
logger.info('Admin password hash saved to admin.json from environment variable');
return true;
}
// Cleartext - hash it
const hash = await hashPassword(envPassword);
const data: AdminData = {
passwordHash: hash,
createdAt: new Date().toISOString(),
lastLogin: null,
passwordChangedAt: new Date().toISOString(),
};
await writeAdminData(data);
cachedAdminData = data;
const hash = isHashed(envPassword) ? envPassword : await hashPassword(envPassword);
cachedConfig = { passwordHash: hash };
cachedState = freshState();
await writeConfigData(cachedConfig);
await writeStateData(cachedState);
initialized = true;
logger.warn('Admin password hashed and saved to admin.json. You may now remove ADMIN_PASSWORD from .env');
if (isHashed(envPassword)) {
logger.info('Admin password hash saved to admin.json from environment variable');
} else {
logger.warn('Admin password hashed and saved to admin.json. You may now remove ADMIN_PASSWORD from .env');
}
return true;
}
@@ -148,11 +163,9 @@ export async function initAdminPassword(): Promise<boolean> {
* Verify a password against the stored admin hash.
*/
export async function verifyAdminPassword(password: string): Promise<boolean> {
if (!cachedAdminData) {
cachedAdminData = await readAdminData();
}
if (!cachedAdminData) return false;
return verifyPassword(password, cachedAdminData.passwordHash);
if (!cachedConfig) cachedConfig = await readConfigData();
if (!cachedConfig) return false;
return verifyPassword(password, cachedConfig.passwordHash);
}
/**
@@ -163,14 +176,30 @@ export async function changeAdminPassword(currentPassword: string, newPassword:
if (!valid) return false;
const hash = await hashPassword(newPassword);
if (!cachedAdminData) return false;
cachedConfig = { passwordHash: hash };
await writeConfigData(cachedConfig);
cachedAdminData = {
...cachedAdminData,
passwordHash: hash,
cachedState = {
...(cachedState ?? freshState()),
passwordChangedAt: new Date().toISOString(),
};
await writeAdminData(cachedAdminData);
await writeStateData(cachedState);
return true;
}
/**
* Set the admin password without verifying a current one. Used by the setup
* wizard during initial bootstrap. Refuses to overwrite an existing password.
*/
export async function setInitialAdminPassword(newPassword: string): Promise<boolean> {
const existing = await readConfigData();
if (existing) return false;
const hash = await hashPassword(newPassword);
cachedConfig = { passwordHash: hash };
cachedState = freshState();
await writeConfigData(cachedConfig);
await writeStateData(cachedState);
initialized = true;
return true;
}
@@ -178,29 +207,31 @@ export async function changeAdminPassword(currentPassword: string, newPassword:
* Update the last login timestamp.
*/
export async function updateLastLogin(): Promise<void> {
if (!cachedAdminData) return;
cachedAdminData = {
...cachedAdminData,
if (!cachedConfig) return;
cachedState = {
...(cachedState ?? freshState()),
lastLogin: new Date().toISOString(),
};
await writeAdminData(cachedAdminData);
try {
await writeStateData(cachedState);
} catch (error) {
logger.warn('Failed to update admin last-login state', {
error: error instanceof Error ? error.message : 'Unknown error',
});
}
}
/**
* Check if admin dashboard is enabled (has a password configured).
*/
export function isAdminEnabled(): boolean {
return cachedAdminData !== null;
return cachedConfig !== null;
}
/**
* Get admin metadata (without the hash).
*/
export function getAdminMeta(): { createdAt: string; lastLogin: string | null; passwordChangedAt: string } | null {
if (!cachedAdminData) return null;
return {
createdAt: cachedAdminData.createdAt,
lastLogin: cachedAdminData.lastLogin,
passwordChangedAt: cachedAdminData.passwordChangedAt,
};
export function getAdminMeta(): AdminStateData | null {
if (!cachedConfig) return null;
return cachedState ?? freshState();
}
+126
View File
@@ -0,0 +1,126 @@
import { existsSync } from 'node:fs';
import { mkdir, writeFile, unlink } from 'node:fs/promises';
import path from 'node:path';
import { logger } from '@/lib/logger';
/**
* Admin data directories.
*
* Two dirs intentionally split (issue #226):
* - CONFIG: holds operator-authored state (config.json, policy.json,
* admin.json passwordHash, plugins, themes, branding uploads). Can be
* mounted read-only after initial setup.
* - STATE: holds runtime mutations (admin-state.json with login timestamps,
* audit.log, .setup-token). Always read-write.
*
* Resolution order:
* getConfigDir()
* 1. ADMIN_CONFIG_DIR
* 2. ADMIN_DATA_DIR (legacy)
* 3. <cwd>/data/admin
*
* getStateDir()
* 1. ADMIN_STATE_DIR
* 2. <ADMIN_CONFIG_DIR>/state - if config dir was set explicitly
* 3. <ADMIN_DATA_DIR>/state - back-compat: stays on the legacy volume
* 4. <cwd>/data/admin-state - fresh-install default; matches the
* sibling mount in docker-compose.yml
*
* The legacy ADMIN_DATA_DIR keeps existing single-volume mounts working
* unchanged: everything ends up under it, with state in a `state/` subdir.
* Fresh installs and the docker-compose default keep state in a separate
* sibling dir so the config dir can be mounted :ro after setup.
*/
export function getConfigDir(): string {
return (
process.env.ADMIN_CONFIG_DIR ||
process.env.ADMIN_DATA_DIR ||
path.join(process.cwd(), 'data', 'admin')
);
}
export function getStateDir(): string {
if (process.env.ADMIN_STATE_DIR) return process.env.ADMIN_STATE_DIR;
if (process.env.ADMIN_CONFIG_DIR) {
return path.join(process.env.ADMIN_CONFIG_DIR, 'state');
}
if (process.env.ADMIN_DATA_DIR) {
return path.join(process.env.ADMIN_DATA_DIR, 'state');
}
return path.join(process.cwd(), 'data', 'admin-state');
}
export function getConfigPath(filename: string): string {
return path.join(getConfigDir(), filename);
}
export function getStatePath(filename: string): string {
return path.join(getStateDir(), filename);
}
export async function ensureConfigDir(): Promise<void> {
const dir = getConfigDir();
if (!existsSync(dir)) {
await mkdir(dir, { recursive: true });
}
}
export async function ensureStateDir(): Promise<void> {
const dir = getStateDir();
if (!existsSync(dir)) {
await mkdir(dir, { recursive: true });
}
}
// ─── Read-only mode ─────────────────────────────────────────────────────────
let cachedReadOnly: boolean | null = null;
/**
* Whether the config dir is locked. Operators set ADMIN_CONFIG_READONLY=true
* after running the setup wizard and remounting the volume :ro.
*
* When true, all writes to the config dir are refused at the application
* layer (cleaner error than a mid-request EROFS).
*/
export function isConfigReadOnly(): boolean {
if (cachedReadOnly !== null) return cachedReadOnly;
const v = (process.env.ADMIN_CONFIG_READONLY || '').toLowerCase();
cachedReadOnly = v === 'true' || v === '1' || v === 'yes';
return cachedReadOnly;
}
/**
* Probe the config dir by writing a temp file. Used to auto-detect RO mounts
* when ADMIN_CONFIG_READONLY is not set explicitly. Run once at startup;
* cheap on local FS, can be slow on networked FS, hence opt-in.
*/
export async function probeConfigReadOnly(): Promise<boolean> {
if (process.env.ADMIN_CONFIG_READONLY) return isConfigReadOnly();
try {
const probe = path.join(getConfigDir(), '.rw-probe');
await writeFile(probe, '');
await unlink(probe);
cachedReadOnly = false;
return false;
} catch {
cachedReadOnly = true;
logger.info('Config dir is read-only (auto-detected)');
return true;
}
}
export class ConfigReadOnlyError extends Error {
constructor(operation: string) {
super(
`Cannot ${operation}: configuration is read-only. ` +
`Remount the config volume read-write or unset ADMIN_CONFIG_READONLY.`
);
this.name = 'ConfigReadOnlyError';
}
}
export function assertWritable(operation: string): void {
if (isConfigReadOnly()) throw new ConfigReadOnlyError(operation);
}
+5 -5
View File
@@ -2,13 +2,10 @@ import { readFile, writeFile, mkdir, rename, unlink } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { logger } from '@/lib/logger';
function getAdminDir(): string {
return process.env.ADMIN_DATA_DIR || path.join(process.cwd(), 'data', 'admin');
}
import { getConfigDir, assertWritable } from './paths';
function getPluginConfigDir(): string {
return path.join(getAdminDir(), 'plugin-config');
return path.join(getConfigDir(), 'plugin-config');
}
function configPath(pluginId: string): string {
@@ -41,6 +38,7 @@ export async function getPluginConfig(pluginId: string): Promise<Record<string,
* Set a single config key for a plugin.
*/
export async function setPluginConfig(pluginId: string, key: string, value: unknown): Promise<void> {
assertWritable('update plugin config');
const dir = getPluginConfigDir();
await ensureDir(dir);
@@ -57,6 +55,7 @@ export async function setPluginConfig(pluginId: string, key: string, value: unkn
* Delete a single config key for a plugin.
*/
export async function deletePluginConfigKey(pluginId: string, key: string): Promise<void> {
assertWritable('delete plugin config key');
const config = await getPluginConfig(pluginId);
delete config[key];
@@ -77,5 +76,6 @@ export async function deletePluginConfigKey(pluginId: string, key: string): Prom
* Delete all config for a plugin (used when uninstalling).
*/
export async function deleteAllPluginConfig(pluginId: string): Promise<void> {
assertWritable('delete plugin config');
try { await unlink(configPath(pluginId)); } catch { /* ok if missing */ }
}
+9 -6
View File
@@ -3,17 +3,14 @@ import { existsSync } from 'node:fs';
import { createHash } from 'node:crypto';
import path from 'node:path';
import { logger } from '@/lib/logger';
function getAdminDir(): string {
return process.env.ADMIN_DATA_DIR || path.join(process.cwd(), 'data', 'admin');
}
import { getConfigDir, assertWritable } from './paths';
function getPluginsDir(): string {
return path.join(getAdminDir(), 'plugins');
return path.join(getConfigDir(), 'plugins');
}
function getThemesDir(): string {
return path.join(getAdminDir(), 'themes');
return path.join(getConfigDir(), 'themes');
}
// ─── Types ───────────────────────────────────────────────────
@@ -141,6 +138,7 @@ export async function savePlugin(
plugin: ServerPlugin,
code: string,
): Promise<void> {
assertWritable('install plugin');
const dir = getPluginsDir();
await ensureDir(dir);
@@ -171,6 +169,7 @@ export async function savePlugin(
}
export async function updatePluginMeta(id: string, updates: Partial<Pick<ServerPlugin, 'enabled' | 'forceEnabled'>>): Promise<ServerPlugin | null> {
assertWritable('update plugin metadata');
const registry = await getPluginRegistry();
const idx = registry.plugins.findIndex(p => p.id === id);
if (idx < 0) return null;
@@ -181,6 +180,7 @@ export async function updatePluginMeta(id: string, updates: Partial<Pick<ServerP
}
export async function deletePlugin(id: string): Promise<boolean> {
assertWritable('delete plugin');
const registry = await getPluginRegistry();
const idx = registry.plugins.findIndex(p => p.id === id);
if (idx < 0) return false;
@@ -221,6 +221,7 @@ export async function saveTheme(
theme: ServerTheme,
css: string,
): Promise<void> {
assertWritable('install theme');
const dir = getThemesDir();
await ensureDir(dir);
@@ -240,6 +241,7 @@ export async function saveTheme(
}
export async function updateThemeMeta(id: string, updates: Partial<Pick<ServerTheme, 'enabled' | 'forceEnabled'>>): Promise<ServerTheme | null> {
assertWritable('update theme metadata');
const registry = await getThemeRegistry();
const idx = registry.themes.findIndex(t => t.id === id);
if (idx < 0) return null;
@@ -250,6 +252,7 @@ export async function updateThemeMeta(id: string, updates: Partial<Pick<ServerTh
}
export async function deleteTheme(id: string): Promise<boolean> {
assertWritable('delete theme');
const registry = await getThemeRegistry();
const idx = registry.themes.findIndex(t => t.id === id);
if (idx < 0) return false;
+2 -2
View File
@@ -1,7 +1,7 @@
import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';
import { createCipheriv, createDecipheriv, randomBytes, createHash } from 'node:crypto';
import { readFileEnv } from '@/lib/read-file-env';
import { getSessionSecret } from '@/lib/auth/session-secret';
import { ADMIN_SESSION_COOKIE, DEFAULT_ADMIN_SESSION_TTL } from './types';
import type { AdminSessionPayload } from './types';
@@ -12,7 +12,7 @@ const TAG_LENGTH = 16;
const MIN_SECRET_LENGTH = 32;
function getKey(): Buffer {
const secret = process.env.SESSION_SECRET || readFileEnv(process.env.SESSION_SECRET_FILE);
const secret = getSessionSecret();
if (!secret) throw new Error('SESSION_SECRET not configured');
if (secret.length < MIN_SECRET_LENGTH) {
throw new Error(
+19 -1
View File
@@ -1,12 +1,30 @@
// Admin dashboard types
export interface AdminData {
/**
* Operator-authored admin record. Lives in admin.json under the config dir
* and can be mounted read-only after setup. Only the password hash itself
* is config; mutable timestamps live in AdminStateData.
*/
export interface AdminConfigData {
passwordHash: string;
}
/**
* Runtime-mutable admin record. Lives in admin-state.json under the state
* dir. Updated on every login and password change, so it must stay writable.
*/
export interface AdminStateData {
createdAt: string;
lastLogin: string | null;
passwordChangedAt: string;
}
/**
* Combined view used by getAdminMeta() and tests. Constructed by merging
* admin.json + admin-state.json at read time.
*/
export interface AdminData extends AdminConfigData, AdminStateData {}
export interface AdminSessionPayload {
role: 'admin';
iat: number;