feat: add plugin/theme harness and admin dashboard
Plugin & Theme System: - Add plugin type definitions, permissions (30+), and validation constants - Add IndexedDB storage layer for plugin code, theme CSS, and previews - Add theme CSS sanitization, injection, and safety validation - Add HookBus event system with 130+ hooks across 20 domains - Add plugin ZIP extraction and manifest validation with JS security checks - Add sandboxed PluginAPI factory with scoped storage, logging, and permission gating - Add plugin loader with blob URL dynamic import and auto-disable circuit breaker - Add 3 built-in themes (Nord, Catppuccin, Solarized) - Add Zustand plugin store with install/uninstall/enable/disable lifecycle - Add PluginSlot, PluginSlotRenderer, and PluginErrorBoundary components - Add plugins and themes settings UI panels - Integrate plugin slots into email viewer, composer, navigation rail, sidebar, and context menu - Extend theme store with custom theme installation and activation Admin Dashboard: - Add admin authentication with scrypt password hashing and AES-256-GCM sessions - Add rate-limited login (5 attempts/15min per IP) - Add config manager with admin override > env var > default priority - Add settings policy system with feature gates and per-setting restrictions - Add audit logging with rotation - Add admin API routes (login, logout, config, policy, audit, password change) - Add admin UI pages (login, dashboard, config, policy, audit) - Add policy store for client-side feature gate enforcement - Wire admin password initialization into server instrumentation Tests: - Add 139 tests across 10 test files covering all plugin/theme modules
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
import { appendFile, stat, rename, mkdir } from 'node:fs/promises';
|
||||
import { existsSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { logger } from '@/lib/logger';
|
||||
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');
|
||||
}
|
||||
|
||||
function getAuditLogPath(): string {
|
||||
return path.join(getAdminDir(), 'audit.log');
|
||||
}
|
||||
|
||||
/**
|
||||
* Append an audit entry to the admin audit log.
|
||||
*/
|
||||
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 });
|
||||
}
|
||||
|
||||
const entry: AuditEntry = {
|
||||
ts: new Date().toISOString(),
|
||||
action,
|
||||
detail,
|
||||
ip,
|
||||
};
|
||||
|
||||
const logPath = getAuditLogPath();
|
||||
try {
|
||||
await appendFile(logPath, JSON.stringify(entry) + '\n', 'utf-8');
|
||||
await rotateIfNeeded(logPath);
|
||||
} catch (error) {
|
||||
logger.error('Failed to write audit log', { error: error instanceof Error ? error.message : 'Unknown error' });
|
||||
}
|
||||
}
|
||||
|
||||
async function rotateIfNeeded(logPath: string): Promise<void> {
|
||||
try {
|
||||
const stats = await stat(logPath);
|
||||
if (stats.size < MAX_LOG_SIZE) return;
|
||||
|
||||
// Rotate: audit.log.3 → deleted, audit.log.2 → .3, audit.log.1 → .2, audit.log → .1
|
||||
for (let i = MAX_ROTATIONS; i >= 1; i--) {
|
||||
const from = i === 1 ? logPath : `${logPath}.${i - 1}`;
|
||||
const to = `${logPath}.${i}`;
|
||||
if (existsSync(from)) {
|
||||
try { await rename(from, to); } catch { /* target may exist on overwrite */ }
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// stat failed, probably file doesn't exist yet
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read audit log entries, newest first. Supports pagination.
|
||||
*/
|
||||
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);
|
||||
|
||||
let entries: AuditEntry[] = lines.map(line => {
|
||||
try { return JSON.parse(line); } catch { return null; }
|
||||
}).filter((e): e is AuditEntry => e !== null);
|
||||
|
||||
if (actionFilter) {
|
||||
entries = entries.filter(e => e.action === actionFilter);
|
||||
}
|
||||
|
||||
const total = entries.length;
|
||||
// Return newest first
|
||||
entries.reverse();
|
||||
const start = (page - 1) * limit;
|
||||
return { entries: entries.slice(start, start + limit), total };
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return { entries: [], total: 0 };
|
||||
}
|
||||
logger.warn('Failed to read audit log', { error: error instanceof Error ? error.message : 'Unknown error' });
|
||||
return { entries: [], total: 0 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { readFile, writeFile, mkdir, rename } from 'node:fs/promises';
|
||||
import { existsSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { logger } from '@/lib/logger';
|
||||
import { CONFIG_ENV_MAP, DEFAULT_POLICY, type SettingsPolicy } from './types';
|
||||
|
||||
function getAdminDir(): string {
|
||||
return process.env.ADMIN_DATA_DIR || path.join(process.cwd(), 'data', 'admin');
|
||||
}
|
||||
|
||||
function parseEnvValue(value: string, type: string): unknown {
|
||||
switch (type) {
|
||||
case 'boolean':
|
||||
return value === 'true';
|
||||
case 'string':
|
||||
case 'url':
|
||||
case 'enum':
|
||||
return value;
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
class ConfigManager {
|
||||
private adminConfig: Record<string, unknown> = {};
|
||||
private policyCache: SettingsPolicy = { ...DEFAULT_POLICY };
|
||||
private loaded = false;
|
||||
|
||||
/** Load admin config and policy from disk. Called once at startup and on reload. */
|
||||
async load(): Promise<void> {
|
||||
this.adminConfig = await this.readJsonFile('config.json') || {};
|
||||
const policy = await this.readJsonFile('policy.json');
|
||||
this.policyCache = policy ? { ...DEFAULT_POLICY, ...policy } : { ...DEFAULT_POLICY };
|
||||
this.loaded = true;
|
||||
logger.debug('ConfigManager loaded', { configKeys: Object.keys(this.adminConfig).length });
|
||||
}
|
||||
|
||||
/** Ensure config is loaded (no-op if already loaded). */
|
||||
async ensureLoaded(): Promise<void> {
|
||||
if (!this.loaded) await this.load();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a config value. Priority: admin override > env var > default.
|
||||
*/
|
||||
get<T>(key: string, defaultValue?: T): T {
|
||||
// Admin override (highest priority)
|
||||
if (key in this.adminConfig) {
|
||||
return this.adminConfig[key] as T;
|
||||
}
|
||||
|
||||
// Environment variable
|
||||
const mapping = CONFIG_ENV_MAP[key];
|
||||
if (mapping) {
|
||||
const envVal = process.env[mapping.envVar];
|
||||
if (envVal !== undefined) {
|
||||
return parseEnvValue(envVal, mapping.type) as T;
|
||||
}
|
||||
if (defaultValue !== undefined) return defaultValue;
|
||||
return mapping.defaultValue as T;
|
||||
}
|
||||
|
||||
return defaultValue as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all config values as a flat object (merged from all layers).
|
||||
*/
|
||||
getAll(): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const [key, mapping] of Object.entries(CONFIG_ENV_MAP)) {
|
||||
result[key] = this.get(key, mapping.defaultValue);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all config values with source information (for admin UI).
|
||||
*/
|
||||
getAllWithSources(): Record<string, { value: unknown; source: 'admin' | 'env' | 'default' }> {
|
||||
const result: Record<string, { value: unknown; source: 'admin' | 'env' | 'default' }> = {};
|
||||
for (const [key, mapping] of Object.entries(CONFIG_ENV_MAP)) {
|
||||
if (key in this.adminConfig) {
|
||||
result[key] = { value: this.adminConfig[key], source: 'admin' };
|
||||
} else {
|
||||
const envVal = process.env[mapping.envVar];
|
||||
if (envVal !== undefined) {
|
||||
result[key] = { value: parseEnvValue(envVal, mapping.type), source: 'env' };
|
||||
} else {
|
||||
result[key] = { value: mapping.defaultValue, source: 'default' };
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update admin config overrides. Writes to disk.
|
||||
*/
|
||||
async setAdminConfig(updates: Record<string, unknown>): Promise<void> {
|
||||
Object.assign(this.adminConfig, updates);
|
||||
await this.writeJsonFile('config.json', this.adminConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an admin override, reverting to env/default.
|
||||
*/
|
||||
async removeAdminOverride(key: string): Promise<void> {
|
||||
delete this.adminConfig[key];
|
||||
await this.writeJsonFile('config.json', this.adminConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current settings policy.
|
||||
*/
|
||||
getPolicy(): SettingsPolicy {
|
||||
return this.policyCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the settings policy. Writes to disk.
|
||||
*/
|
||||
async setPolicy(policy: SettingsPolicy): Promise<void> {
|
||||
this.policyCache = { ...DEFAULT_POLICY, ...policy };
|
||||
await this.writeJsonFile('policy.json', this.policyCache as unknown as Record<string, unknown>);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reload config from disk (for manual file edits or multi-instance).
|
||||
*/
|
||||
async reload(): Promise<void> {
|
||||
await this.load();
|
||||
}
|
||||
|
||||
private async readJsonFile(filename: string): Promise<Record<string, unknown> | null> {
|
||||
const filePath = path.join(getAdminDir(), filename);
|
||||
try {
|
||||
const raw = await readFile(filePath, 'utf-8');
|
||||
return JSON.parse(raw);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
|
||||
logger.warn(`Failed to read ${filename}`, { error: error instanceof Error ? error.message : 'Unknown error' });
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
const tmpPath = targetPath + '.tmp';
|
||||
await writeFile(tmpPath, JSON.stringify(data, null, 2), 'utf-8');
|
||||
await rename(tmpPath, targetPath);
|
||||
}
|
||||
}
|
||||
|
||||
export const configManager = new ConfigManager();
|
||||
@@ -0,0 +1,206 @@
|
||||
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 { logger } from '@/lib/logger';
|
||||
import type { AdminData } from './types';
|
||||
|
||||
const SCRYPT_KEYLEN = 64;
|
||||
const SCRYPT_COST = 16384; // 2^14
|
||||
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');
|
||||
}
|
||||
|
||||
function hashPassword(password: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const salt = randomBytes(SALT_LENGTH);
|
||||
scrypt(password, salt, SCRYPT_KEYLEN, { N: SCRYPT_COST, r: SCRYPT_BLOCK_SIZE, p: SCRYPT_PARALLELIZATION }, (err, derivedKey) => {
|
||||
if (err) return reject(err);
|
||||
// Format: $scrypt$N=16384,r=8,p=1$<salt_base64>$<hash_base64>
|
||||
const params = `N=${SCRYPT_COST},r=${SCRYPT_BLOCK_SIZE},p=${SCRYPT_PARALLELIZATION}`;
|
||||
resolve(`$scrypt$${params}$${salt.toString('base64')}$${derivedKey.toString('base64')}`);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
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');
|
||||
const storedHash = Buffer.from(parts[4], 'base64');
|
||||
|
||||
const params: Record<string, number> = {};
|
||||
for (const p of paramStr.split(',')) {
|
||||
const [k, v] = p.split('=');
|
||||
params[k] = parseInt(v, 10);
|
||||
}
|
||||
|
||||
scrypt(password, salt, storedHash.length, { N: params.N, r: params.r, p: params.p }, (err, derivedKey) => {
|
||||
if (err) return reject(err);
|
||||
resolve(timingSafeEqual(derivedKey, storedHash));
|
||||
});
|
||||
} else {
|
||||
// Unknown format
|
||||
resolve(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function isHashed(value: string): boolean {
|
||||
return value.startsWith('$scrypt$') || value.startsWith('$2a$') || value.startsWith('$2b$');
|
||||
}
|
||||
|
||||
async function readAdminData(): Promise<AdminData | null> {
|
||||
const filePath = getAdminJsonPath();
|
||||
try {
|
||||
const raw = await readFile(filePath, 'utf-8');
|
||||
return JSON.parse(raw) as AdminData;
|
||||
} 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' });
|
||||
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);
|
||||
}
|
||||
|
||||
let cachedAdminData: AdminData | null = null;
|
||||
let initialized = false;
|
||||
|
||||
/**
|
||||
* Initialize admin password on startup.
|
||||
* If ADMIN_PASSWORD is cleartext, hash it and write to admin.json.
|
||||
* Returns true if admin is enabled.
|
||||
*/
|
||||
export async function initAdminPassword(): Promise<boolean> {
|
||||
if (initialized) return cachedAdminData !== null;
|
||||
|
||||
// Check persistent file first
|
||||
const existing = await readAdminData();
|
||||
if (existing) {
|
||||
cachedAdminData = existing;
|
||||
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;
|
||||
logger.info('Admin dashboard disabled (no ADMIN_PASSWORD set)');
|
||||
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;
|
||||
initialized = true;
|
||||
logger.warn('Admin password hashed and saved to admin.json. You may now remove ADMIN_PASSWORD from .env');
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the admin password. Returns true on success.
|
||||
*/
|
||||
export async function changeAdminPassword(currentPassword: string, newPassword: string): Promise<boolean> {
|
||||
const valid = await verifyAdminPassword(currentPassword);
|
||||
if (!valid) return false;
|
||||
|
||||
const hash = await hashPassword(newPassword);
|
||||
if (!cachedAdminData) return false;
|
||||
|
||||
cachedAdminData = {
|
||||
...cachedAdminData,
|
||||
passwordHash: hash,
|
||||
passwordChangedAt: new Date().toISOString(),
|
||||
};
|
||||
await writeAdminData(cachedAdminData);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the last login timestamp.
|
||||
*/
|
||||
export async function updateLastLogin(): Promise<void> {
|
||||
if (!cachedAdminData) return;
|
||||
cachedAdminData = {
|
||||
...cachedAdminData,
|
||||
lastLogin: new Date().toISOString(),
|
||||
};
|
||||
await writeAdminData(cachedAdminData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if admin dashboard is enabled (has a password configured).
|
||||
*/
|
||||
export function isAdminEnabled(): boolean {
|
||||
return cachedAdminData !== 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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* In-memory rate limiter for admin login.
|
||||
* Max 5 attempts per IP per 15 minutes.
|
||||
*/
|
||||
|
||||
const MAX_ATTEMPTS = 5;
|
||||
const WINDOW_MS = 15 * 60 * 1000; // 15 minutes
|
||||
|
||||
interface RateLimitEntry {
|
||||
count: number;
|
||||
resetAt: number;
|
||||
}
|
||||
|
||||
const attempts = new Map<string, RateLimitEntry>();
|
||||
|
||||
// Clean up expired entries periodically
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [key, entry] of attempts) {
|
||||
if (entry.resetAt <= now) {
|
||||
attempts.delete(key);
|
||||
}
|
||||
}
|
||||
}, 60_000).unref();
|
||||
|
||||
/**
|
||||
* Check if the IP is rate limited. Returns remaining attempts, or 0 if blocked.
|
||||
*/
|
||||
export function checkRateLimit(ip: string): { allowed: boolean; remaining: number; retryAfterMs: number } {
|
||||
const now = Date.now();
|
||||
const entry = attempts.get(ip);
|
||||
|
||||
if (!entry || entry.resetAt <= now) {
|
||||
// New window
|
||||
attempts.set(ip, { count: 1, resetAt: now + WINDOW_MS });
|
||||
return { allowed: true, remaining: MAX_ATTEMPTS - 1, retryAfterMs: 0 };
|
||||
}
|
||||
|
||||
if (entry.count >= MAX_ATTEMPTS) {
|
||||
return { allowed: false, remaining: 0, retryAfterMs: entry.resetAt - now };
|
||||
}
|
||||
|
||||
entry.count++;
|
||||
return { allowed: true, remaining: MAX_ATTEMPTS - entry.count, retryAfterMs: 0 };
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { cookies } from 'next/headers';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { createCipheriv, createDecipheriv, randomBytes, createHash } from 'node:crypto';
|
||||
import { ADMIN_SESSION_COOKIE, DEFAULT_ADMIN_SESSION_TTL } from './types';
|
||||
import type { AdminSessionPayload } from './types';
|
||||
|
||||
const ALGORITHM = 'aes-256-gcm';
|
||||
const IV_LENGTH = 12;
|
||||
const TAG_LENGTH = 16;
|
||||
|
||||
function getKey(): Buffer {
|
||||
const secret = process.env.SESSION_SECRET;
|
||||
if (!secret) throw new Error('SESSION_SECRET not configured');
|
||||
return createHash('sha256').update(secret).digest();
|
||||
}
|
||||
|
||||
function getSessionTTL(): number {
|
||||
const ttl = parseInt(process.env.ADMIN_SESSION_TTL || '', 10);
|
||||
return isNaN(ttl) || ttl <= 0 ? DEFAULT_ADMIN_SESSION_TTL : ttl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an encrypted admin session token.
|
||||
*/
|
||||
export function createAdminSession(): string {
|
||||
const key = getKey();
|
||||
const iv = randomBytes(IV_LENGTH);
|
||||
const cipher = createCipheriv(ALGORITHM, key, iv);
|
||||
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const payload: AdminSessionPayload = {
|
||||
role: 'admin',
|
||||
iat: now,
|
||||
exp: now + getSessionTTL(),
|
||||
};
|
||||
|
||||
const json = JSON.stringify(payload);
|
||||
const encrypted = Buffer.concat([cipher.update(json, 'utf8'), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
|
||||
return Buffer.concat([iv, tag, encrypted]).toString('base64');
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify and decode an admin session token. Returns null if invalid or expired.
|
||||
*/
|
||||
export function verifyAdminSession(token: string): AdminSessionPayload | null {
|
||||
try {
|
||||
const key = getKey();
|
||||
const data = Buffer.from(token, 'base64');
|
||||
if (data.length < IV_LENGTH + TAG_LENGTH) return null;
|
||||
|
||||
const iv = data.subarray(0, IV_LENGTH);
|
||||
const tag = data.subarray(IV_LENGTH, IV_LENGTH + TAG_LENGTH);
|
||||
const encrypted = data.subarray(IV_LENGTH + TAG_LENGTH);
|
||||
|
||||
const decipher = createDecipheriv(ALGORITHM, key, iv);
|
||||
decipher.setAuthTag(tag);
|
||||
|
||||
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
|
||||
const payload = JSON.parse(decrypted.toString('utf8')) as AdminSessionPayload;
|
||||
|
||||
if (payload.role !== 'admin') return null;
|
||||
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
if (payload.exp < now) return null;
|
||||
|
||||
return payload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the admin session from cookies. Returns the payload or a 401 response.
|
||||
*/
|
||||
export async function requireAdminAuth(): Promise<{ payload: AdminSessionPayload } | { error: NextResponse }> {
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get(ADMIN_SESSION_COOKIE)?.value;
|
||||
|
||||
if (!token) {
|
||||
return { error: NextResponse.json({ error: 'Not authenticated' }, { status: 401 }) };
|
||||
}
|
||||
|
||||
const payload = verifyAdminSession(token);
|
||||
if (!payload) {
|
||||
cookieStore.delete(ADMIN_SESSION_COOKIE);
|
||||
return { error: NextResponse.json({ error: 'Session expired' }, { status: 401 }) };
|
||||
}
|
||||
|
||||
return { payload };
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the admin session cookie.
|
||||
*/
|
||||
export async function setAdminSessionCookie(): Promise<void> {
|
||||
const token = createAdminSession();
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.set(ADMIN_SESSION_COOKIE, token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
maxAge: getSessionTTL(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the admin session cookie.
|
||||
*/
|
||||
export async function clearAdminSessionCookie(): Promise<void> {
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.delete(ADMIN_SESSION_COOKIE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the client IP from the request headers.
|
||||
*/
|
||||
export function getClientIP(request: Request): string {
|
||||
const forwarded = request.headers.get('x-forwarded-for');
|
||||
if (forwarded) {
|
||||
return forwarded.split(',')[0].trim();
|
||||
}
|
||||
return request.headers.get('x-real-ip') || '0.0.0.0';
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// Admin dashboard types
|
||||
|
||||
export interface AdminData {
|
||||
passwordHash: string;
|
||||
createdAt: string;
|
||||
lastLogin: string | null;
|
||||
passwordChangedAt: string;
|
||||
}
|
||||
|
||||
export interface AdminSessionPayload {
|
||||
role: 'admin';
|
||||
iat: number;
|
||||
exp: number;
|
||||
}
|
||||
|
||||
export interface SettingRestriction {
|
||||
locked?: boolean;
|
||||
value?: unknown;
|
||||
hidden?: boolean;
|
||||
allowedValues?: unknown[];
|
||||
min?: number;
|
||||
max?: number;
|
||||
}
|
||||
|
||||
export interface FeatureGates {
|
||||
sidebarAppsEnabled: boolean;
|
||||
userThemesEnabled: boolean;
|
||||
settingsExportEnabled: boolean;
|
||||
customKeywordsEnabled: boolean;
|
||||
templatesEnabled: boolean;
|
||||
calendarTasksEnabled: boolean;
|
||||
smimeEnabled: boolean;
|
||||
externalContentEnabled: boolean;
|
||||
debugModeEnabled: boolean;
|
||||
folderIconsEnabled: boolean;
|
||||
hoverActionsConfigEnabled: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_FEATURE_GATES: FeatureGates = {
|
||||
sidebarAppsEnabled: true,
|
||||
userThemesEnabled: true,
|
||||
settingsExportEnabled: true,
|
||||
customKeywordsEnabled: true,
|
||||
templatesEnabled: true,
|
||||
calendarTasksEnabled: true,
|
||||
smimeEnabled: true,
|
||||
externalContentEnabled: true,
|
||||
debugModeEnabled: true,
|
||||
folderIconsEnabled: true,
|
||||
hoverActionsConfigEnabled: true,
|
||||
};
|
||||
|
||||
export interface SettingsPolicy {
|
||||
restrictions: Record<string, SettingRestriction>;
|
||||
features: FeatureGates;
|
||||
defaults: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export const DEFAULT_POLICY: SettingsPolicy = {
|
||||
restrictions: {},
|
||||
features: { ...DEFAULT_FEATURE_GATES },
|
||||
defaults: {},
|
||||
};
|
||||
|
||||
export interface AuditEntry {
|
||||
ts: string;
|
||||
action: string;
|
||||
detail: Record<string, unknown>;
|
||||
ip: string;
|
||||
}
|
||||
|
||||
/** Config keys that map to environment variables */
|
||||
export const CONFIG_ENV_MAP: Record<string, { envVar: string; type: 'string' | 'boolean' | 'url' | 'enum'; defaultValue: unknown; enumValues?: string[] }> = {
|
||||
appName: { envVar: 'APP_NAME', type: 'string', defaultValue: 'Webmail' },
|
||||
jmapServerUrl: { envVar: 'JMAP_SERVER_URL', type: 'url', defaultValue: '' },
|
||||
stalwartFeaturesEnabled: { envVar: 'STALWART_FEATURES', type: 'boolean', defaultValue: true },
|
||||
stalwartApiUrl: { envVar: 'STALWART_API_URL', type: 'url', defaultValue: '' },
|
||||
demoMode: { envVar: 'DEMO_MODE', type: 'boolean', defaultValue: false },
|
||||
devMode: { envVar: 'DEV_MOCK_JMAP', type: 'boolean', defaultValue: false },
|
||||
faviconUrl: { envVar: 'FAVICON_URL', type: 'url', defaultValue: '/branding/Bulwark_Favicon.svg' },
|
||||
appLogoLightUrl: { envVar: 'APP_LOGO_LIGHT_URL', type: 'url', defaultValue: '' },
|
||||
appLogoDarkUrl: { envVar: 'APP_LOGO_DARK_URL', type: 'url', defaultValue: '' },
|
||||
loginLogoLightUrl: { envVar: 'LOGIN_LOGO_LIGHT_URL', type: 'url', defaultValue: '/branding/Bulwark_Logo_Color.svg' },
|
||||
loginLogoDarkUrl: { envVar: 'LOGIN_LOGO_DARK_URL', type: 'url', defaultValue: '/branding/Bulwark_Logo_White.svg' },
|
||||
loginCompanyName: { envVar: 'LOGIN_COMPANY_NAME', type: 'string', defaultValue: '' },
|
||||
loginImprintUrl: { envVar: 'LOGIN_IMPRINT_URL', type: 'url', defaultValue: '' },
|
||||
loginPrivacyPolicyUrl: { envVar: 'LOGIN_PRIVACY_POLICY_URL', type: 'url', defaultValue: '' },
|
||||
loginWebsiteUrl: { envVar: 'LOGIN_WEBSITE_URL', type: 'url', defaultValue: '' },
|
||||
oauthEnabled: { envVar: 'OAUTH_ENABLED', type: 'boolean', defaultValue: false },
|
||||
oauthOnly: { envVar: 'OAUTH_ONLY', type: 'boolean', defaultValue: false },
|
||||
oauthClientId: { envVar: 'OAUTH_CLIENT_ID', type: 'string', defaultValue: '' },
|
||||
oauthClientSecret: { envVar: 'OAUTH_CLIENT_SECRET', type: 'string', defaultValue: '' },
|
||||
oauthIssuerUrl: { envVar: 'OAUTH_ISSUER_URL', type: 'url', defaultValue: '' },
|
||||
autoSsoEnabled: { envVar: 'AUTO_SSO_ENABLED', type: 'boolean', defaultValue: false },
|
||||
cookieSameSite: { envVar: 'COOKIE_SAME_SITE', type: 'enum', defaultValue: 'lax', enumValues: ['lax', 'strict', 'none'] },
|
||||
allowedFrameAncestors: { envVar: 'ALLOWED_FRAME_ANCESTORS', type: 'string', defaultValue: '' },
|
||||
parentOrigin: { envVar: 'NEXT_PUBLIC_PARENT_ORIGIN', type: 'string', defaultValue: '' },
|
||||
settingsSyncEnabled: { envVar: 'SETTINGS_SYNC_ENABLED', type: 'boolean', defaultValue: false },
|
||||
logFormat: { envVar: 'LOG_FORMAT', type: 'enum', defaultValue: 'text', enumValues: ['text', 'json'] },
|
||||
logLevel: { envVar: 'LOG_LEVEL', type: 'enum', defaultValue: 'info', enumValues: ['error', 'warn', 'info', 'debug'] },
|
||||
sessionSecret: { envVar: 'SESSION_SECRET', type: 'string', defaultValue: '' },
|
||||
};
|
||||
|
||||
/** Keys that should never be exposed to the client config endpoint */
|
||||
export const SENSITIVE_CONFIG_KEYS = new Set(['oauthClientSecret', 'sessionSecret']);
|
||||
|
||||
/** Admin session cookie name */
|
||||
export const ADMIN_SESSION_COOKIE = 'admin_session';
|
||||
|
||||
/** Default admin session TTL in seconds */
|
||||
export const DEFAULT_ADMIN_SESSION_TTL = 3600;
|
||||
Reference in New Issue
Block a user