fix: deploy crash + multiple bug fixes + cleanup
- server.js: fix getSiteName() returning string when not installed causing 'getSiteName(...).then is not a function' crash on homepage (deploy blocker) - server.js: auto-load business routes after install completes (no restart needed), HTML cache keyed by api_key - install: validate db name/email/password, trigger route loading after complete - app.js: fix forgot/reset/verify pages rendering HomePage (missing page mapping) - verify.js: support URL token auto-verification for external registration links - auth: new email_code template for 6-digit code, reset_password template (forgot-password was using verify_email template) - upload.js: fix MP4 magic-bytes check using undefined buf variable - tickets.js: status enum validation, anonymous submission rate limit - security.js: XSS whitelist preserves email template HTML, strips scripts, blocks javascript:/data: hrefs; CORS reject returns 403 - bans.js: allow clearing reason/duration, status enum validation - users.js: fix req.user.role ReferenceError in create user modal - home.js: tracking results now have detail view button - .gitignore: ignore data/ (db credentials), logs, session files, temp scripts
This commit is contained in:
17
.gitignore
vendored
17
.gitignore
vendored
@@ -1,11 +1,10 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
data/config.json
|
# 本地运行配置与上传文件(含数据库密码,严禁入库)
|
||||||
data/uploads/*
|
data/
|
||||||
data/*.db
|
# 日志与临时文件
|
||||||
data/*.db-*
|
|
||||||
*.log
|
*.log
|
||||||
*.log
|
*.tmp.js
|
||||||
o.log
|
*.tmp.sh
|
||||||
e.log
|
*.bak
|
||||||
err.log
|
# 会话记录
|
||||||
out.log
|
session-*.md
|
||||||
|
|||||||
@@ -307,6 +307,9 @@ async function seedTemplates(db) {
|
|||||||
['verify_email', '邮箱验证', '【{{site_name}}】请验证您的邮箱',
|
['verify_email', '邮箱验证', '【{{site_name}}】请验证您的邮箱',
|
||||||
'<p>您好 <strong>{{username}}</strong>(游戏名: {{game_name}},UID: {{game_uid}}),</p><p>感谢注册!请点击以下链接验证邮箱:</p><p><a href="{{verify_link}}">{{verify_link}}</a></p><p>链接有效期24小时。</p><p>— {{site_name}}</p>',
|
'<p>您好 <strong>{{username}}</strong>(游戏名: {{game_name}},UID: {{game_uid}}),</p><p>感谢注册!请点击以下链接验证邮箱:</p><p><a href="{{verify_link}}">{{verify_link}}</a></p><p>链接有效期24小时。</p><p>— {{site_name}}</p>',
|
||||||
'变量: {{site_name}}, {{username}}, {{game_name}}, {{game_uid}}, {{verify_link}}'],
|
'变量: {{site_name}}, {{username}}, {{game_name}}, {{game_uid}}, {{verify_link}}'],
|
||||||
|
['email_code', '邮箱验证码', '【{{site_name}}】您的邮箱验证码',
|
||||||
|
'<p>您好,</p><p>您的邮箱验证码为:</p><p style="font-size:24px;font-weight:bold;letter-spacing:4px">{{code}}</p><p>验证码10分钟内有效。如非本人操作,请忽略此邮件。</p><p>— {{site_name}}</p>',
|
||||||
|
'变量: {{site_name}}, {{code}}'],
|
||||||
['ticket_created', '工单创建通知', '【{{site_name}}】{{ticket_type}}已提交 #{{ticket_id}}',
|
['ticket_created', '工单创建通知', '【{{site_name}}】{{ticket_type}}已提交 #{{ticket_id}}',
|
||||||
'<p><strong>{{reporter_game_name}}</strong>(UID: {{reporter_game_uid}}),您的{{ticket_type}}已提交。</p><p>工单编号: <strong>#{{ticket_id}}</strong></p><p>标题: {{ticket_title}}</p><p><a href="{{tracking_link}}">查看工单</a></p><p>— {{site_name}}</p>',
|
'<p><strong>{{reporter_game_name}}</strong>(UID: {{reporter_game_uid}}),您的{{ticket_type}}已提交。</p><p>工单编号: <strong>#{{ticket_id}}</strong></p><p>标题: {{ticket_title}}</p><p><a href="{{tracking_link}}">查看工单</a></p><p>— {{site_name}}</p>',
|
||||||
'变量: {{site_name}}, {{reporter_game_name}}, {{ticket_type}}, {{ticket_id}}, {{ticket_title}}, {{tracking_link}}'],
|
'变量: {{site_name}}, {{reporter_game_name}}, {{ticket_type}}, {{ticket_id}}, {{ticket_title}}, {{tracking_link}}'],
|
||||||
@@ -319,6 +322,9 @@ async function seedTemplates(db) {
|
|||||||
['ticket_transferred', '工单已转交', '【{{site_name}}】工单 #{{ticket_id}} 已转交',
|
['ticket_transferred', '工单已转交', '【{{site_name}}】工单 #{{ticket_id}} 已转交',
|
||||||
'<p>工单 <strong>#{{ticket_id}}</strong>({{ticket_title}})已由 {{from_user}} 转交给 {{to_user}}。</p><p>— {{site_name}}</p>',
|
'<p>工单 <strong>#{{ticket_id}}</strong>({{ticket_title}})已由 {{from_user}} 转交给 {{to_user}}。</p><p>— {{site_name}}</p>',
|
||||||
'变量: {{site_name}}, {{ticket_id}}, {{ticket_title}}, {{from_user}}, {{to_user}}'],
|
'变量: {{site_name}}, {{ticket_id}}, {{ticket_title}}, {{from_user}}, {{to_user}}'],
|
||||||
|
['reset_password', '密码重置', '【{{site_name}}】密码重置请求',
|
||||||
|
'<p>您好 <strong>{{username}}</strong>,</p><p>我们收到了您的密码重置请求。请点击以下链接设置新密码:</p><p><a href="{{reset_link}}">{{reset_link}}</a></p><p>链接1小时内有效。如非本人操作,请忽略此邮件。</p><p>— {{site_name}}</p>',
|
||||||
|
'变量: {{site_name}}, {{username}}, {{reset_link}}'],
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const t of temps) {
|
for (const t of temps) {
|
||||||
|
|||||||
@@ -22,9 +22,20 @@ function getApiKey() {
|
|||||||
function clearApiKeyCache() { cachedApiKey = null; }
|
function clearApiKeyCache() { cachedApiKey = null; }
|
||||||
|
|
||||||
const xssOptions = {
|
const xssOptions = {
|
||||||
whiteList: {},
|
whiteList: {
|
||||||
|
p: [], br: [], strong: [], b: [], em: [], i: [], u: [], s: [], strike: [],
|
||||||
|
a: ['href', 'title', 'target', 'rel'], span: [], div: [],
|
||||||
|
ul: [], ol: [], li: [], h1: [], h2: [], h3: [], h4: [], h5: [], h6: [],
|
||||||
|
table: [], thead: [], tbody: [], tfoot: [], tr: [], th: [], td: [], caption: [],
|
||||||
|
code: [], pre: [], blockquote: [], hr: [], img: ['src', 'alt', 'title', 'width', 'height'],
|
||||||
|
font: ['color', 'size', 'face'], small: [], sub: [], sup: [],
|
||||||
|
},
|
||||||
stripIgnoreTag: true,
|
stripIgnoreTag: true,
|
||||||
stripIgnoreTagBody: ['script', 'style', 'xml', 'iframe', 'object', 'embed'],
|
stripIgnoreTagBody: ['script', 'style', 'xml', 'iframe', 'object', 'embed'],
|
||||||
|
onTagAttr: (tag, name, value) => {
|
||||||
|
if ((name === 'href' || name === 'src') && /^\s*(javascript|data):/i.test(value)) return '';
|
||||||
|
return;
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
function sanitize(value) {
|
function sanitize(value) {
|
||||||
@@ -85,6 +96,7 @@ const ticketLimiter = rateLimit({
|
|||||||
const ticketAnonLimiter = rateLimit({
|
const ticketAnonLimiter = rateLimit({
|
||||||
windowMs: 60 * 1000,
|
windowMs: 60 * 1000,
|
||||||
max: 5,
|
max: 5,
|
||||||
|
skip: (req) => !!(req.headers.authorization),
|
||||||
message: { error: '匿名提交过于频繁,请登录后再试或稍后重试' },
|
message: { error: '匿名提交过于频繁,请登录后再试或稍后重试' },
|
||||||
standardHeaders: true,
|
standardHeaders: true,
|
||||||
legacyHeaders: false,
|
legacyHeaders: false,
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ function validateMagicBytes(buffer, mime) {
|
|||||||
'image/png': () => head[0] === 0x89 && head[1] === 0x50 && head[2] === 0x4E && head[3] === 0x47,
|
'image/png': () => head[0] === 0x89 && head[1] === 0x50 && head[2] === 0x4E && head[3] === 0x47,
|
||||||
'image/gif': () => head.toString('ascii', 0, 6) === 'GIF89a' || head.toString('ascii', 0, 6) === 'GIF87a',
|
'image/gif': () => head.toString('ascii', 0, 6) === 'GIF89a' || head.toString('ascii', 0, 6) === 'GIF87a',
|
||||||
'image/webp': () => head.toString('ascii', 0, 4) === 'RIFF' && head.toString('ascii', 8, 12) === 'WEBP',
|
'image/webp': () => head.toString('ascii', 0, 4) === 'RIFF' && head.toString('ascii', 8, 12) === 'WEBP',
|
||||||
'video/mp4': () => buf[4] === 0x66 && buf[5] === 0x74 && buf[6] === 0x79 && buf[7] === 0x70,
|
'video/mp4': () => head[4] === 0x66 && head[5] === 0x74 && head[6] === 0x79 && head[7] === 0x70,
|
||||||
'video/webm': () => head[0] === 0x1A && head[1] === 0x45 && head[2] === 0xDF && head[3] === 0xA3,
|
'video/webm': () => head[0] === 0x1A && head[1] === 0x45 && head[2] === 0xDF && head[3] === 0xA3,
|
||||||
};
|
};
|
||||||
if (!sigs[mime]) return false;
|
if (!sigs[mime]) return false;
|
||||||
|
|||||||
@@ -24,9 +24,9 @@ router.post('/send-verify-code', async (req, res) => {
|
|||||||
await query("DELETE FROM captchas WHERE created_at < NOW() - INTERVAL 5 MINUTE");
|
await query("DELETE FROM captchas WHERE created_at < NOW() - INTERVAL 5 MINUTE");
|
||||||
await query('INSERT INTO captchas(id, question, answer) VALUES (?,?,?)', [codeId, email, code]);
|
await query('INSERT INTO captchas(id, question, answer) VALUES (?,?,?)', [codeId, email, code]);
|
||||||
|
|
||||||
const sent = await sendEmail(email, 'verify_email', {
|
const sent = await sendEmail(email, 'email_code', {
|
||||||
username: email.split('@')[0], game_name: '', game_uid: '',
|
username: email.split('@')[0], game_name: '', game_uid: '',
|
||||||
verify_link: code,
|
code,
|
||||||
});
|
});
|
||||||
if (!sent) {
|
if (!sent) {
|
||||||
await query('DELETE FROM captchas WHERE id = ?', [codeId]);
|
await query('DELETE FROM captchas WHERE id = ?', [codeId]);
|
||||||
@@ -229,9 +229,9 @@ router.post('/forgot-password', async (req, res) => {
|
|||||||
const resetToken = uuid();
|
const resetToken = uuid();
|
||||||
await query("UPDATE users SET reset_token = ?, reset_expires = DATE_ADD(NOW(), INTERVAL 1 HOUR) WHERE id = ?", [resetToken, user.id]);
|
await query("UPDATE users SET reset_token = ?, reset_expires = DATE_ADD(NOW(), INTERVAL 1 HOUR) WHERE id = ?", [resetToken, user.id]);
|
||||||
const site = await getRow("SELECT v FROM settings WHERE k='site_url'");
|
const site = await getRow("SELECT v FROM settings WHERE k='site_url'");
|
||||||
await sendEmail(email, 'verify_email', {
|
await sendEmail(email, 'reset_password', {
|
||||||
username: user.username, game_name: user.game_name, game_uid: user.game_uid,
|
username: user.username, game_name: user.game_name, game_uid: user.game_uid,
|
||||||
verify_link: `${site?.v||'http://localhost:3100'}#/reset?token=${resetToken}`,
|
reset_link: `${site?.v||'http://localhost:3100'}#/reset?token=${resetToken}`,
|
||||||
});
|
});
|
||||||
res.json({ message: '如果邮箱已注册,重置链接已发送' });
|
res.json({ message: '如果邮箱已注册,重置链接已发送' });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -53,9 +53,12 @@ router.post('/', authenticate, requireRole('owner'), async (req, res) => {
|
|||||||
|
|
||||||
router.put('/:id', authenticate, requireRole('owner'), async (req, res) => {
|
router.put('/:id', authenticate, requireRole('owner'), async (req, res) => {
|
||||||
const fields = {};
|
const fields = {};
|
||||||
if (req.body.status) fields.status = req.body.status;
|
if (req.body.status) {
|
||||||
if (req.body.reason) fields.reason = req.body.reason;
|
if (!['active','expired','appealed','lifted'].includes(req.body.status)) return res.status(400).json({ error: '无效的状态值' });
|
||||||
if (req.body.duration) fields.duration = req.body.duration;
|
fields.status = req.body.status;
|
||||||
|
}
|
||||||
|
if (req.body.reason !== undefined) fields.reason = req.body.reason;
|
||||||
|
if (req.body.duration !== undefined) fields.duration = req.body.duration;
|
||||||
if (!Object.keys(fields).length) return res.status(400).json({ error: '无更新内容' });
|
if (!Object.keys(fields).length) return res.status(400).json({ error: '无更新内容' });
|
||||||
const sets = Object.keys(fields).map(k => `${k} = ?`).join(', ');
|
const sets = Object.keys(fields).map(k => `${k} = ?`).join(', ');
|
||||||
await query(`UPDATE bans SET ${sets} WHERE id = ?`, [...Object.values(fields), req.params.id]);
|
await query(`UPDATE bans SET ${sets} WHERE id = ?`, [...Object.values(fields), req.params.id]);
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ router.get('/status', (req, res) => {
|
|||||||
|
|
||||||
router.post('/check-db', async (req, res) => {
|
router.post('/check-db', async (req, res) => {
|
||||||
const { host, port, user, password, database } = req.body;
|
const { host, port, user, password, database } = req.body;
|
||||||
|
if (!/^[A-Za-z0-9_]+$/.test(database || '')) return res.status(400).json({ error: '数据库名仅允许字母、数字、下划线' });
|
||||||
try {
|
try {
|
||||||
const conn = await mysql.createConnection({
|
const conn = await mysql.createConnection({
|
||||||
host: host || 'localhost',
|
host: host || 'localhost',
|
||||||
@@ -42,6 +43,9 @@ router.post('/complete', async (req, res) => {
|
|||||||
if (!db_host || !db_user || !db_name || !admin_username || !admin_password || !admin_email) {
|
if (!db_host || !db_user || !db_name || !admin_username || !admin_password || !admin_email) {
|
||||||
return res.status(400).json({ error: '必填字段不完整' });
|
return res.status(400).json({ error: '必填字段不完整' });
|
||||||
}
|
}
|
||||||
|
if (!/^[A-Za-z0-9_]+$/.test(db_name || '')) return res.status(400).json({ error: '数据库名仅允许字母、数字、下划线' });
|
||||||
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(admin_email)) return res.status(400).json({ error: '邮箱格式不正确' });
|
||||||
|
if (admin_password.length < 6) return res.status(400).json({ error: '密码至少6位' });
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const conn = await mysql.createConnection({
|
const conn = await mysql.createConnection({
|
||||||
@@ -90,7 +94,9 @@ router.post('/complete', async (req, res) => {
|
|||||||
external_api_key: externalKey,
|
external_api_key: externalKey,
|
||||||
});
|
});
|
||||||
|
|
||||||
res.json({ ok: true, message: '安装完成,请重新启动服务器' });
|
try { if (typeof global.__loadBusinessRoutes === 'function') global.__loadBusinessRoutes(); } catch {}
|
||||||
|
|
||||||
|
res.json({ ok: true, message: '安装完成,无需重启,系统已就绪' });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
res.status(500).json({ error: '安装失败: ' + e.message });
|
res.status(500).json({ error: '安装失败: ' + e.message });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ const { authenticate, requireRole, optionalAuth } = require('../middleware/auth'
|
|||||||
const { upload, finalizeUpload } = require('../middleware/upload');
|
const { upload, finalizeUpload } = require('../middleware/upload');
|
||||||
const { sendEmail } = require('../mailer');
|
const { sendEmail } = require('../mailer');
|
||||||
const { sendWebhook } = require('../webhook');
|
const { sendWebhook } = require('../webhook');
|
||||||
const { validateLengths } = require('../middleware/security');
|
const { validateLengths, ticketAnonLimiter } = require('../middleware/security');
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
@@ -101,7 +101,7 @@ router.get('/:id', authenticate, async (req, res) => {
|
|||||||
res.json(t);
|
res.json(t);
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/', optionalAuth, upload.array('files', 5), finalizeUpload, validateLengths({
|
router.post('/', ticketAnonLimiter, optionalAuth, upload.array('files', 5), finalizeUpload, validateLengths({
|
||||||
title:100, reporter_game_name:50, reporter_game_uid:50, target_game_name:50, target_game_uid:50, reason:300, description:5000,
|
title:100, reporter_game_name:50, reporter_game_uid:50, target_game_name:50, target_game_uid:50, reason:300, description:5000,
|
||||||
}), async (req, res) => {
|
}), async (req, res) => {
|
||||||
const { type, title, reporter_game_name, reporter_game_uid, target_game_name, target_game_uid, reason, description, is_admin_complaint, parent_ticket_id } = req.body;
|
const { type, title, reporter_game_name, reporter_game_uid, target_game_name, target_game_uid, reason, description, is_admin_complaint, parent_ticket_id } = req.body;
|
||||||
@@ -185,7 +185,10 @@ router.put('/:id', authenticate, requireRole('owner','admin'), async (req, res)
|
|||||||
if (req.user.role === 'admin' && t.assigned_to && t.assigned_to !== req.user.id) return res.status(403).json({ error: '只能修改自己负责的工单' });
|
if (req.user.role === 'admin' && t.assigned_to && t.assigned_to !== req.user.id) return res.status(403).json({ error: '只能修改自己负责的工单' });
|
||||||
if (t.status === 'closed' && req.user.role !== 'owner') return res.status(400).json({ error: '已关闭的工单仅服主可操作' });
|
if (t.status === 'closed' && req.user.role !== 'owner') return res.status(400).json({ error: '已关闭的工单仅服主可操作' });
|
||||||
const fields = {};
|
const fields = {};
|
||||||
if (req.body.status) fields.status = req.body.status;
|
if (req.body.status) {
|
||||||
|
if (!['pending','processing','awaiting_info','appealing','resolved','rejected','closed'].includes(req.body.status)) return res.status(400).json({ error: '无效的状态值' });
|
||||||
|
fields.status = req.body.status;
|
||||||
|
}
|
||||||
if (req.body.priority) fields.priority = req.body.priority;
|
if (req.body.priority) fields.priority = req.body.priority;
|
||||||
if (req.body.priority && !['low','medium','high','urgent'].includes(req.body.priority)) return res.status(400).json({ error: '无效的优先级' });
|
if (req.body.priority && !['low','medium','high','urgent'].includes(req.body.priority)) return res.status(400).json({ error: '无效的优先级' });
|
||||||
if (req.body.claim_note !== undefined) fields.claim_note = req.body.claim_note;
|
if (req.body.claim_note !== undefined) fields.claim_note = req.body.claim_note;
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ const HTML_PATH = path.join(PUBLIC_DIR, 'index.html');
|
|||||||
|
|
||||||
let cachedHtml = null;
|
let cachedHtml = null;
|
||||||
let htmlTimestamp = 0;
|
let htmlTimestamp = 0;
|
||||||
|
let htmlKey = null;
|
||||||
|
|
||||||
function getSiteName() {
|
function getSiteName() {
|
||||||
if (!isInstalled()) return 'MC举报系统';
|
if (!isInstalled()) return 'MC举报系统';
|
||||||
@@ -27,17 +28,18 @@ function getSiteName() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function getHtmlWithKey() {
|
function getHtmlWithKey() {
|
||||||
return getSiteName().then(siteName => {
|
return Promise.resolve(getSiteName()).then(siteName => {
|
||||||
const stat = fs.statSync(HTML_PATH);
|
const stat = fs.statSync(HTML_PATH);
|
||||||
const mtime = stat.mtimeMs;
|
const mtime = stat.mtimeMs;
|
||||||
if (!cachedHtml || htmlTimestamp < mtime || cachedHtml.indexOf(siteName) === -1) {
|
|
||||||
let html = fs.readFileSync(HTML_PATH, 'utf-8');
|
|
||||||
const cfg = getConfig();
|
const cfg = getConfig();
|
||||||
const key = cfg?.api_key || '';
|
const key = cfg?.api_key || '';
|
||||||
|
if (!cachedHtml || htmlTimestamp < mtime || htmlKey !== key || cachedHtml.indexOf(siteName) === -1) {
|
||||||
|
let html = fs.readFileSync(HTML_PATH, 'utf-8');
|
||||||
const redirect = isInstalled() ? '' : '<script>location.hash="#/install"</script>';
|
const redirect = isInstalled() ? '' : '<script>location.hash="#/install"</script>';
|
||||||
html = html.replace('</head>', `<script>window.__API_KEY__=${JSON.stringify(key)};window.__SITE_NAME__=${JSON.stringify(siteName)}</script>${redirect}</head>`);
|
html = html.replace('</head>', `<script>window.__API_KEY__=${JSON.stringify(key)};window.__SITE_NAME__=${JSON.stringify(siteName)}</script>${redirect}</head>`);
|
||||||
cachedHtml = html;
|
cachedHtml = html;
|
||||||
htmlTimestamp = mtime;
|
htmlTimestamp = mtime;
|
||||||
|
htmlKey = key;
|
||||||
}
|
}
|
||||||
return cachedHtml;
|
return cachedHtml;
|
||||||
});
|
});
|
||||||
@@ -65,11 +67,9 @@ app.use(cors({
|
|||||||
const allowed = process.env.CORS_ORIGIN;
|
const allowed = process.env.CORS_ORIGIN;
|
||||||
if (!allowed || allowed === '*') return cb(null, true);
|
if (!allowed || allowed === '*') return cb(null, true);
|
||||||
if (allowed === origin) return cb(null, true);
|
if (allowed === origin) return cb(null, true);
|
||||||
if (!allowed) {
|
|
||||||
const host = origin || '';
|
const host = origin || '';
|
||||||
if (host.startsWith('http://localhost:') || host.startsWith('https://localhost:')) return cb(null, true);
|
if (host.startsWith('http://localhost:') || host.startsWith('https://localhost:')) return cb(null, true);
|
||||||
}
|
cb(null, false);
|
||||||
cb(new Error('Not allowed by CORS'));
|
|
||||||
},
|
},
|
||||||
credentials: true,
|
credentials: true,
|
||||||
methods: ['GET','POST','PUT','DELETE'],
|
methods: ['GET','POST','PUT','DELETE'],
|
||||||
@@ -100,7 +100,11 @@ app.use('/js', express.static(path.join(PUBLIC_DIR, 'js'), staticOpts));
|
|||||||
const installRoutes = require('./routes/install');
|
const installRoutes = require('./routes/install');
|
||||||
app.use('/api/install', installRoutes);
|
app.use('/api/install', installRoutes);
|
||||||
|
|
||||||
if (isInstalled()) {
|
let businessLoaded = false;
|
||||||
|
function loadBusinessRoutes() {
|
||||||
|
if (businessLoaded) return;
|
||||||
|
businessLoaded = true;
|
||||||
|
|
||||||
const authRoutes = require('./routes/auth');
|
const authRoutes = require('./routes/auth');
|
||||||
app.use('/api/auth/login', methodGuard(['POST']), loginLimiter);
|
app.use('/api/auth/login', methodGuard(['POST']), loginLimiter);
|
||||||
app.use('/api/auth/register', methodGuard(['POST']), registerLimiter);
|
app.use('/api/auth/register', methodGuard(['POST']), registerLimiter);
|
||||||
@@ -124,6 +128,9 @@ if (isInstalled()) {
|
|||||||
app.get('/api/verify', (req, res) => res.redirect(`/#/verify?token=${req.query.token}`));
|
app.get('/api/verify', (req, res) => res.redirect(`/#/verify?token=${req.query.token}`));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isInstalled()) loadBusinessRoutes();
|
||||||
|
global.__loadBusinessRoutes = loadBusinessRoutes;
|
||||||
|
|
||||||
app.get('/api/health', (req, res) => res.json({ status: 'ok', installed: isInstalled() }));
|
app.get('/api/health', (req, res) => res.json({ status: 'ok', installed: isInstalled() }));
|
||||||
|
|
||||||
app.get('/', async (req, res) => {
|
app.get('/', async (req, res) => {
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
{
|
|
||||||
"$schema": "https://opencode.ai/config.json",
|
|
||||||
"instructions": ["AGENTS.md"]
|
|
||||||
}
|
|
||||||
@@ -109,7 +109,7 @@ const App = {
|
|||||||
pub.classList.remove('hidden');
|
pub.classList.remove('hidden');
|
||||||
document.getElementById('top-bar').classList.remove('hidden');
|
document.getElementById('top-bar').classList.remove('hidden');
|
||||||
this.updateTopAuth();
|
this.updateTopAuth();
|
||||||
const comp = page === 'login' ? LoginPage : page === 'register' ? RegisterPage : page === 'install' ? InstallPage : HomePage;
|
const comp = page === 'login' ? LoginPage : page === 'register' ? RegisterPage : page === 'install' ? InstallPage : page === 'forgot' ? ForgotPage : page === 'reset' ? ResetPage : page === 'verify' ? VerifyPage : HomePage;
|
||||||
comp.render(param).then(html => { pub.innerHTML = html; if (comp.mount) comp.mount(param); }).catch(() => {
|
comp.render(param).then(html => { pub.innerHTML = html; if (comp.mount) comp.mount(param); }).catch(() => {
|
||||||
pub.innerHTML = '<div class="pub-card"><div class="logo"><i class="fas fa-exclamation-triangle" style="color:var(--d)"></i><h2>加载失败</h2><p>请刷新页面重试</p></div></div>';
|
pub.innerHTML = '<div class="pub-card"><div class="logo"><i class="fas fa-exclamation-triangle" style="color:var(--d)"></i><h2>加载失败</h2><p>请刷新页面重试</p></div></div>';
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ const HomePage = {
|
|||||||
r.innerHTML = '<div class="loading"><i class="fas fa-spinner"></i></div>';
|
r.innerHTML = '<div class="loading"><i class="fas fa-spinner"></i></div>';
|
||||||
try {
|
try {
|
||||||
const tickets = await API.get(`/tickets/tracking?token=${token}`);
|
const tickets = await API.get(`/tickets/tracking?token=${token}`);
|
||||||
r.innerHTML = tickets.length ? `<div class="table-wrap"><table><thead><tr><th>#</th><th>类型</th><th>标题</th><th>状态</th><th>时间</th></tr></thead><tbody>${tickets.map(tk=>`<tr><td>${tk.id}</td><td>${U.badge(tk.type,'type')}</td><td>${U.esc(tk.title)}</td><td>${U.badge(tk.status,'status')}</td><td>${U.date(tk.created_at)}</td></tr>`).join('')}</tbody></table></div>` : '<div class="empty"><i class="fas fa-inbox"></i><p>未找到工单</p></div>';
|
r.innerHTML = tickets.length ? `<div class="table-wrap"><table><thead><tr><th>#</th><th>类型</th><th>标题</th><th>状态</th><th>时间</th><th>操作</th></tr></thead><tbody>${tickets.map(tk=>`<tr><td>${tk.id}</td><td>${U.badge(tk.type,'type')}</td><td>${U.esc(tk.title)}</td><td>${U.badge(tk.status,'status')}</td><td>${U.date(tk.created_at)}</td><td><button class="btn btn-o btn-sm" onclick="HomePage.showTrackDetail(${tk.id},'${U.escJs(token)}')"><i class="fas fa-eye"></i></button></td></tr>`).join('')}</tbody></table></div>` : '<div class="empty"><i class="fas fa-inbox"></i><p>未找到工单</p></div>';
|
||||||
} catch (e) { r.innerHTML = `<div class="alert alert-e">${e.message}</div>`; }
|
} catch (e) { r.innerHTML = `<div class="alert alert-e">${e.message}</div>`; }
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -97,7 +97,8 @@ const InstallPage = {
|
|||||||
admin_game_name: document.getElementById('ia-game').value,
|
admin_game_name: document.getElementById('ia-game').value,
|
||||||
admin_game_uid: document.getElementById('ia-uid').value,
|
admin_game_uid: document.getElementById('ia-uid').value,
|
||||||
});
|
});
|
||||||
document.getElementById('install-admin').innerHTML = '<div class="alert alert-s"><h3><i class="fas fa-check-circle"></i> 安装成功!</h3><p>配置已保存。请重启服务器后刷新页面。</p></div>';
|
document.getElementById('install-admin').innerHTML = '<div class="alert alert-s"><h3><i class="fas fa-check-circle"></i> 安装成功!</h3><p>系统已就绪,正在跳转登录...</p></div>';
|
||||||
|
setTimeout(() => location.hash = '#/login', 1500);
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
document.getElementById('ia-err').textContent = ex.message;
|
document.getElementById('ia-err').textContent = ex.message;
|
||||||
document.getElementById('ia-err').classList.remove('hidden');
|
document.getElementById('ia-err').classList.remove('hidden');
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ const UsersPage = {
|
|||||||
<form id="cu-form">
|
<form id="cu-form">
|
||||||
<div class="grid-2"><div class="form-group"><label>用户名 *</label><input id="cu-u" required></div><div class="form-group"><label>密码 *</label><input type="password" id="cu-p" required minlength="6"></div></div>
|
<div class="grid-2"><div class="form-group"><label>用户名 *</label><input id="cu-u" required></div><div class="form-group"><label>密码 *</label><input type="password" id="cu-p" required minlength="6"></div></div>
|
||||||
<div class="grid-2"><div class="form-group"><label>邮箱 *</label><input type="email" id="cu-e" required></div><div class="form-group"><label>来源</label><select id="cu-s"><option value="netease">网易端</option><option value="skin">皮肤站</option></select></div></div>
|
<div class="grid-2"><div class="form-group"><label>邮箱 *</label><input type="email" id="cu-e" required></div><div class="form-group"><label>来源</label><select id="cu-s"><option value="netease">网易端</option><option value="skin">皮肤站</option></select></div></div>
|
||||||
<div class="grid-2"><div class="form-group"><label>角色 *</label><select id="cu-r" onchange="UsersPage.toggleCreateServers()">${req.user.role==='owner'?'<option value="owner">服主</option>':''}<option value="admin">管理员</option><option value="player">玩家</option></select></div></div>
|
<div class="grid-2"><div class="form-group"><label>角色 *</label><select id="cu-r" onchange="UsersPage.toggleCreateServers()">${Auth.isOwner()?'<option value="owner">服主</option>':''}<option value="admin">管理员</option><option value="player">玩家</option></select></div></div>
|
||||||
<div class="grid-2"><div class="form-group"><label>游戏名 *</label><input id="cu-gn" required></div><div class="form-group"><label>游戏UID *</label><input id="cu-gu" required></div></div>
|
<div class="grid-2"><div class="form-group"><label>游戏名 *</label><input id="cu-gn" required></div><div class="form-group"><label>游戏UID *</label><input id="cu-gu" required></div></div>
|
||||||
<div class="form-group hidden" id="cu-servers"><label>管辖子服务器</label><div style="max-height:120px;overflow-y:auto;border:1px solid var(--g200);border-radius:var(--r);padding:8px">${checks||'<span class="tm">暂无可选服务器</span>'}</div></div>
|
<div class="form-group hidden" id="cu-servers"><label>管辖子服务器</label><div style="max-height:120px;overflow-y:auto;border:1px solid var(--g200);border-radius:var(--r);padding:8px">${checks||'<span class="tm">暂无可选服务器</span>'}</div></div>
|
||||||
<div class="modal-f"><button type="button" class="btn btn-o" data-action="App:closeModal">取消</button><button type="submit" class="btn btn-p">创建</button></div>
|
<div class="modal-f"><button type="button" class="btn btn-o" data-action="App:closeModal">取消</button><button type="submit" class="btn btn-p">创建</button></div>
|
||||||
|
|||||||
@@ -1,5 +1,13 @@
|
|||||||
const VerifyPage = {
|
const VerifyPage = {
|
||||||
async render() {
|
async render() {
|
||||||
|
const params = new URLSearchParams((location.hash.split('?')[1] || ''));
|
||||||
|
const token = params.get('token');
|
||||||
|
if (token) {
|
||||||
|
return `<div class="pub-card"><div class="logo"><i class="fas fa-envelope"></i><h2>邮箱验证</h2><p>正在验证您的邮箱...</p></div>
|
||||||
|
<div id="vf-msg" class="alert alert-i">验证中,请稍候...</div>
|
||||||
|
<div style="margin-top:14px;text-align:center;font-size:13px"><a href="#/login" style="color:var(--p);text-decoration:none">返回登录</a></div>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
return `<div class="pub-card"><div class="logo"><i class="fas fa-envelope"></i><h2>邮箱验证</h2><p>请输入邮件中的6位验证码</p></div>
|
return `<div class="pub-card"><div class="logo"><i class="fas fa-envelope"></i><h2>邮箱验证</h2><p>请输入邮件中的6位验证码</p></div>
|
||||||
<form id="verify-form"><div class="form-group"><input id="vf-code" placeholder="6位验证码" required maxlength="6" minlength="6" pattern="[0-9]{6}" autofocus></div>
|
<form id="verify-form"><div class="form-group"><input id="vf-code" placeholder="6位验证码" required maxlength="6" minlength="6" pattern="[0-9]{6}" autofocus></div>
|
||||||
<div id="vf-msg" class="hidden"></div>
|
<div id="vf-msg" class="hidden"></div>
|
||||||
@@ -8,6 +16,12 @@ const VerifyPage = {
|
|||||||
</div>`;
|
</div>`;
|
||||||
},
|
},
|
||||||
mount() {
|
mount() {
|
||||||
|
const params = new URLSearchParams((location.hash.split('?')[1] || ''));
|
||||||
|
const token = params.get('token');
|
||||||
|
if (token) {
|
||||||
|
this.verifyToken(token);
|
||||||
|
return;
|
||||||
|
}
|
||||||
document.getElementById('verify-form').addEventListener('submit', async e => {
|
document.getElementById('verify-form').addEventListener('submit', async e => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const code = document.getElementById('vf-code').value.trim();
|
const code = document.getElementById('vf-code').value.trim();
|
||||||
@@ -22,5 +36,15 @@ const VerifyPage = {
|
|||||||
msg.classList.remove('hidden');
|
msg.classList.remove('hidden');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
},
|
||||||
|
async verifyToken(token) {
|
||||||
|
const msg = document.getElementById('vf-msg');
|
||||||
|
try {
|
||||||
|
const r = await API.post('/auth/verify-email', { code: token });
|
||||||
|
msg.className = 'alert alert-s'; msg.textContent = r.message || '验证成功';
|
||||||
|
setTimeout(() => location.hash = '#/login', 2000);
|
||||||
|
} catch (ex) {
|
||||||
|
msg.className = 'alert alert-e'; msg.textContent = ex.message;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user