// xmail 服务入口:Express API + 前端静态文件托管
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import express from 'express';
import cookieParser from 'cookie-parser';
import bcrypt from 'bcryptjs';
import { PORT, DIST_DIR, DATA_DIR } from './config.js';
import { db } from './db.js';
import authRoutes from './routes/auth.js';
import accountRoutes from './routes/accounts.js';
import messageRoutes from './routes/messages.js';
import attachmentRoutes from './routes/attachments.js';
import draftRoutes from './routes/drafts.js';
import sendRoutes from './routes/send.js';
import settingsRoutes from './routes/settings.js';
import adminRoutes from './routes/admin.js';
import backupRoutes from './routes/backup.js';
import syncRoutes from './routes/sync.js';
import notificationRoutes from './routes/notifications.js';
import { startScheduler } from './scheduler.js';
const app = express();
app.set('trust proxy', 1);
app.disable('x-powered-by');
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('Referrer-Policy', 'same-origin');
next();
});
app.use(express.json({ limit: '32mb' }));
app.use(cookieParser());
app.get('/api/health', (req, res) => {
res.json({ ok: true, app: 'xmail', version: '1.0.0', time: Date.now() });
});
app.use('/api/auth', authRoutes);
app.use('/api/accounts', accountRoutes);
app.use('/api/messages', messageRoutes);
app.use('/api/attachments', attachmentRoutes);
app.use('/api/drafts', draftRoutes);
app.use('/api/send', sendRoutes);
app.use('/api/settings', settingsRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/backup', backupRoutes);
app.use('/api/sync', syncRoutes);
app.use('/api/notifications', notificationRoutes);
// 未匹配的 API 统一返回 JSON
app.use('/api', (req, res) => {
res.status(404).json({ error: '接口不存在' });
});
// 生产环境:托管前端构建产物,并支持前端路由回退
if (fs.existsSync(path.join(DIST_DIR, 'index.html'))) {
app.use(express.static(DIST_DIR, { index: false, maxAge: '7d' }));
app.get('*', (req, res) => {
res.setHeader('Cache-Control', 'no-cache');
res.sendFile(path.join(DIST_DIR, 'index.html'));
});
} else {
app.get('/', (req, res) => {
res.type('text/plain').send('xmail 后端已启动。开发模式下请访问 Vite 地址(默认 http://localhost:5173)。');
});
}
// 统一错误处理
app.use((err, req, res, next) => {
console.error('[xmail] 请求处理失败:', err);
if (err?.type === 'entity.too.large') {
return res.status(413).json({ error: '请求内容过大(附件总大小限制约 25MB)' });
}
if (res.headersSent) return next(err);
res.status(500).json({ error: '服务器内部错误' });
});
/**
* 首次启动时创建管理员账号。
* 密码来自 install.sh 传入的 ADMIN_PASSWORD;未提供时生成随机密码并打印到日志。
*/
function ensureAdmin() {
const count = db.prepare('SELECT COUNT(*) AS n FROM users').get().n;
if (count > 0) return;
const username = 'admin';
const envPassword = process.env.ADMIN_PASSWORD;
const password = envPassword && envPassword.length >= 6
? envPassword
: crypto.randomBytes(9).toString('base64url');
db.prepare(
'INSERT INTO users (username, password_hash, role, disabled, created_at) VALUES (?, ?, ?, 0, ?)'
).run(username, bcrypt.hashSync(password, 10), 'admin', Date.now());
if (envPassword && envPassword.length >= 6) {
console.log('[xmail] 已创建初始管理员账号 admin(密码来自 ADMIN_PASSWORD 环境变量)');
} else {
console.log('==================================================');
console.log('[xmail] 已创建初始管理员账号');
console.log(` 用户名: ${username}`);
console.log(` 密码: ${password}`);
console.log(' 请登录后立即在「账户」中修改密码');
console.log('==================================================');
}
}
ensureAdmin();
app.listen(PORT, '0.0.0.0', () => {
console.log(`[xmail] 服务已启动: http://0.0.0.0:${PORT}`);
console.log(`[xmail] 数据目录: ${DATA_DIR}`);
startScheduler();
});
process.on('unhandledRejection', (reason) => {
console.error('[xmail] 未处理的异步异常:', reason);
});