mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-24 08:57:25 +00:00
feat: refactor authentication handling and migrate config to database
This commit is contained in:
+68
-18
@@ -6,7 +6,8 @@ import jwt from 'jsonwebtoken';
|
||||
import DockerController, { globalDockerNetwork } from './services/DockerController';
|
||||
import { FileSystemService } from './services/FileSystemService';
|
||||
import { ComposeService } from './services/ComposeService';
|
||||
import { ConfigService } from './services/ConfigService';
|
||||
import bcrypt from 'bcrypt';
|
||||
import crypto from 'crypto';
|
||||
// @ts-ignore - composerize lacks proper type definitions
|
||||
import composerize from 'composerize';
|
||||
import si from 'systeminformation';
|
||||
@@ -26,9 +27,6 @@ const execAsync = promisify(exec);
|
||||
const app = express();
|
||||
const PORT = 3000;
|
||||
|
||||
// ConfigService for persistent auth storage
|
||||
const configService = new ConfigService();
|
||||
|
||||
// FileSystemService for stack management
|
||||
const fileSystemService = new FileSystemService();
|
||||
|
||||
@@ -76,7 +74,9 @@ const authMiddleware = async (req: Request, res: Response, next: NextFunction):
|
||||
}
|
||||
|
||||
try {
|
||||
const jwtSecret = await configService.getJwtSecret();
|
||||
const settings = DatabaseService.getInstance().getGlobalSettings();
|
||||
const jwtSecret = settings.auth_jwt_secret;
|
||||
if (!jwtSecret) throw new Error('No JWT secret');
|
||||
const decoded = jwt.verify(token, jwtSecret) as { username: string };
|
||||
req.user = { username: decoded.username };
|
||||
next();
|
||||
@@ -91,7 +91,8 @@ const authMiddleware = async (req: Request, res: Response, next: NextFunction):
|
||||
// Check if setup is needed
|
||||
app.get('/api/auth/status', async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const needsSetup = await configService.needsSetup();
|
||||
const settings = DatabaseService.getInstance().getGlobalSettings();
|
||||
const needsSetup = !settings.auth_username || !settings.auth_password_hash || !settings.auth_jwt_secret;
|
||||
res.json({ needsSetup });
|
||||
} catch (error) {
|
||||
console.error('Error checking setup status:', error);
|
||||
@@ -102,8 +103,9 @@ app.get('/api/auth/status', async (req: Request, res: Response): Promise<void> =
|
||||
// Initial setup endpoint
|
||||
app.post('/api/auth/setup', async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
// Check if setup is still needed
|
||||
const needsSetup = await configService.needsSetup();
|
||||
const dbSvc = DatabaseService.getInstance();
|
||||
const settings = dbSvc.getGlobalSettings();
|
||||
const needsSetup = !settings.auth_username || !settings.auth_password_hash || !settings.auth_jwt_secret;
|
||||
if (!needsSetup) {
|
||||
res.status(400).json({ error: 'Setup has already been completed' });
|
||||
return;
|
||||
@@ -133,10 +135,13 @@ app.post('/api/auth/setup', async (req: Request, res: Response): Promise<void> =
|
||||
}
|
||||
|
||||
// Save credentials (this also generates the JWT secret)
|
||||
await configService.saveConfig(username, password);
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
const jwtSecret = crypto.randomBytes(64).toString('hex');
|
||||
dbSvc.updateGlobalSetting('auth_username', username);
|
||||
dbSvc.updateGlobalSetting('auth_password_hash', passwordHash);
|
||||
dbSvc.updateGlobalSetting('auth_jwt_secret', jwtSecret);
|
||||
|
||||
// Issue JWT and log user in
|
||||
const jwtSecret = await configService.getJwtSecret();
|
||||
const token = jwt.sign({ username }, jwtSecret, { expiresIn: '24h' });
|
||||
res.cookie(COOKIE_NAME, token, getCookieOptions(req));
|
||||
res.json({ success: true, message: 'Setup completed successfully' });
|
||||
@@ -156,14 +161,20 @@ app.post('/api/auth/login', async (req: Request, res: Response): Promise<void> =
|
||||
}
|
||||
|
||||
try {
|
||||
const isValid = await configService.validateCredentials(username, password);
|
||||
const settings = DatabaseService.getInstance().getGlobalSettings();
|
||||
const storedUsername = settings.auth_username;
|
||||
const storedHash = settings.auth_password_hash;
|
||||
|
||||
if (isValid) {
|
||||
const jwtSecret = await configService.getJwtSecret();
|
||||
const token = jwt.sign({ username }, jwtSecret, { expiresIn: '24h' });
|
||||
res.cookie(COOKIE_NAME, token, getCookieOptions(req));
|
||||
res.json({ success: true, message: 'Login successful' });
|
||||
return;
|
||||
if (storedUsername && storedHash && username === storedUsername) {
|
||||
const isValid = await bcrypt.compare(password, storedHash);
|
||||
if (isValid) {
|
||||
const jwtSecret = settings.auth_jwt_secret;
|
||||
if (!jwtSecret) throw new Error('JWT secret missing from DB');
|
||||
const token = jwt.sign({ username }, jwtSecret, { expiresIn: '24h' });
|
||||
res.cookie(COOKIE_NAME, token, getCookieOptions(req));
|
||||
res.json({ success: true, message: 'Login successful' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
res.status(401).json({ error: 'Invalid credentials' });
|
||||
@@ -173,6 +184,43 @@ app.post('/api/auth/login', async (req: Request, res: Response): Promise<void> =
|
||||
}
|
||||
});
|
||||
|
||||
// Update password endpoint
|
||||
app.put('/api/auth/password', authMiddleware, async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { oldPassword, newPassword } = req.body;
|
||||
if (!oldPassword || !newPassword) {
|
||||
res.status(400).json({ error: 'Old password and new password are required' });
|
||||
return;
|
||||
}
|
||||
if (newPassword.length < 6) {
|
||||
res.status(400).json({ error: 'New password must be at least 6 characters' });
|
||||
return;
|
||||
}
|
||||
|
||||
const dbSvc = DatabaseService.getInstance();
|
||||
const settings = dbSvc.getGlobalSettings();
|
||||
const storedHash = settings.auth_password_hash;
|
||||
|
||||
if (!storedHash) {
|
||||
res.status(400).json({ error: 'Auth not configured properly' });
|
||||
return;
|
||||
}
|
||||
|
||||
const isValid = await bcrypt.compare(oldPassword, storedHash);
|
||||
if (!isValid) {
|
||||
res.status(401).json({ error: 'Invalid old password' });
|
||||
return;
|
||||
}
|
||||
|
||||
const newHash = await bcrypt.hash(newPassword, 10);
|
||||
dbSvc.updateGlobalSetting('auth_password_hash', newHash);
|
||||
res.json({ success: true, message: 'Password updated successfully' });
|
||||
} catch (error) {
|
||||
console.error('Password update error:', error);
|
||||
res.status(500).json({ error: 'Failed to update password' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/auth/logout', (req: Request, res: Response): void => {
|
||||
res.clearCookie(COOKIE_NAME, {
|
||||
httpOnly: true,
|
||||
@@ -221,7 +269,9 @@ server.on('upgrade', async (req, socket, head) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const jwtSecret = await configService.getJwtSecret();
|
||||
const settings = DatabaseService.getInstance().getGlobalSettings();
|
||||
const jwtSecret = settings.auth_jwt_secret;
|
||||
if (!jwtSecret) throw new Error('No JWT secret');
|
||||
jwt.verify(token, jwtSecret);
|
||||
|
||||
// Check if this is a stack logs WebSocket request
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import bcrypt from 'bcrypt';
|
||||
import crypto from 'crypto';
|
||||
|
||||
interface AuthConfig {
|
||||
username: string;
|
||||
passwordHash: string;
|
||||
jwtSecret: string;
|
||||
}
|
||||
|
||||
export class ConfigService {
|
||||
private dataDir: string;
|
||||
private configPath: string;
|
||||
|
||||
constructor() {
|
||||
this.dataDir = process.env.DATA_DIR || '/app/data';
|
||||
this.configPath = path.join(this.dataDir, 'sencho.json');
|
||||
}
|
||||
|
||||
private async ensureDataDir(): Promise<void> {
|
||||
try {
|
||||
await fs.mkdir(this.dataDir, { recursive: true });
|
||||
} catch {
|
||||
// Directory already exists
|
||||
}
|
||||
}
|
||||
|
||||
async needsSetup(): Promise<boolean> {
|
||||
try {
|
||||
const config = await this.readConfig();
|
||||
return !config || !config.username || !config.passwordHash;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
async readConfig(): Promise<AuthConfig | null> {
|
||||
try {
|
||||
const data = await fs.readFile(this.configPath, 'utf-8');
|
||||
return JSON.parse(data);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async saveConfig(username: string, password: string): Promise<void> {
|
||||
await this.ensureDataDir();
|
||||
const saltRounds = 10;
|
||||
const passwordHash = await bcrypt.hash(password, saltRounds);
|
||||
const jwtSecret = crypto.randomBytes(64).toString('hex');
|
||||
const config: AuthConfig = { username, passwordHash, jwtSecret };
|
||||
await fs.writeFile(this.configPath, JSON.stringify(config, null, 2), 'utf-8');
|
||||
}
|
||||
|
||||
async validateCredentials(username: string, password: string): Promise<boolean> {
|
||||
const config = await this.readConfig();
|
||||
if (!config) return false;
|
||||
|
||||
if (username !== config.username) return false;
|
||||
|
||||
return await bcrypt.compare(password, config.passwordHash);
|
||||
}
|
||||
|
||||
async getJwtSecret(): Promise<string> {
|
||||
const config = await this.readConfig();
|
||||
if (!config || !config.jwtSecret) {
|
||||
throw new Error('JWT secret not found - setup may not be complete');
|
||||
}
|
||||
return config.jwtSecret;
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,7 @@ export class DatabaseService {
|
||||
// Default journal mode is safer for arbitrary Docker volume mounts than WAL
|
||||
|
||||
this.initSchema();
|
||||
this.migrateJsonConfig(dataDir);
|
||||
}
|
||||
|
||||
public static getInstance(): DatabaseService {
|
||||
@@ -106,6 +107,30 @@ export class DatabaseService {
|
||||
stmt.run('docker_janitor_gb', '5');
|
||||
}
|
||||
|
||||
private migrateJsonConfig(dataDir: string) {
|
||||
const configPath = path.join(dataDir, 'sencho.json');
|
||||
if (fs.existsSync(configPath)) {
|
||||
try {
|
||||
const data = fs.readFileSync(configPath, 'utf-8');
|
||||
const config = JSON.parse(data);
|
||||
|
||||
if (config.username && config.passwordHash && config.jwtSecret) {
|
||||
const stmt = this.db.prepare('INSERT OR IGNORE INTO global_settings (key, value) VALUES (?, ?)');
|
||||
stmt.run('auth_username', config.username);
|
||||
stmt.run('auth_password_hash', config.passwordHash);
|
||||
stmt.run('auth_jwt_secret', config.jwtSecret);
|
||||
|
||||
console.log('Successfully migrated sencho.json credentials to SQLite global_settings.');
|
||||
|
||||
// Delete the file after migrating
|
||||
fs.unlinkSync(configPath);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to migrate sencho.json:', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Agents ---
|
||||
|
||||
public getAgents(): Agent[] {
|
||||
|
||||
Reference in New Issue
Block a user