security: server-side CAPTCHA (HMAC-signed) + magic-byte upload sniff + pagination bounds

Port upstream ac4af62 + PR #14/#17:
- lib/captcha.js: HMAC(CAPTCHA_SECRET, id:answer) challenge; GET
  /api/captcha returns {id, text, sig}; register/createPost/createReply
  verify answer server-side (bad answer / forged sig rejected)
- Frontend (Modals/NewPost/ReplyList): fetch challenge from server,
  submit id+answer+sig; no more client-side answer check (was bypassable)
- Upload: sniff JPEG/PNG/GIF/WebP magic bytes (ignore client MIME), UUID
  filenames — blocks spoofed HTML-as-image (stored XSS)
- Posts pagination: limit cap 50, page cap (deep-pagination DoS)
- CAPTCHA_SECRET env (falls back to JWT_SECRET)
This commit is contained in:
lezi-fun committed 2026-08-11 20:25:16 +08:00
1 parent 2780dab8e2
commit 7188d07aea
12 files changed
+141 -51

No files matched your search

+6 -1
View File
@@ -1,15 +1,20 @@
// POST /api/auth/register
import bcrypt from 'bcryptjs';
import pool from '@/lib/db';
import { verifyCaptcha } from '@/lib/captcha';
export async function POST(req) {
const { email, password, username } = await req.json();
const { email, password, username, captcha_id, captcha_answer, captcha_sig } = await req.json();
if (!email || !password || !username) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
if (password.length < 6) {
return Response.json({ error: '密码至少6位' }, { status: 400 });
}
// 服务端验证码校验(ENABLE_CAPTCHA 关闭时跳过)
if (process.env.ENABLE_CAPTCHA !== 'false' && !verifyCaptcha(captcha_id, captcha_answer, captcha_sig)) {
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
}
try {
const countResult = await pool.query('SELECT COUNT(*) FROM users');
const isFirstUser = parseInt(countResult.rows[0].count) === 0;
+7
View File
@@ -0,0 +1,7 @@
// GET /api/captcha — 服务端验证码挑战(HMAC 签名答案,防前端绕过)
import { generateCaptchaChallenge } from '@/lib/captcha';
export async function GET() {
const ch = generateCaptchaChallenge();
return Response.json({ id: ch.id, text: ch.text, sig: ch.sig });
}
+6 -1
View File
@@ -2,6 +2,7 @@
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
import { jsonWithEtag } from '@/lib/http-cache';
import { verifyCaptcha } from '@/lib/captcha';
export async function GET(req, { params }) {
try {
@@ -24,10 +25,14 @@ export async function POST(req, { params }) {
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const { content } = await req.json();
const { content, captcha_id, captcha_answer, captcha_sig } = await req.json();
if (!content || content.trim().length === 0) {
return Response.json({ error: '请填写回复内容' }, { status: 400 });
}
// 服务端验证码校验(ENABLE_CAPTCHA 关闭时跳过)
if (process.env.ENABLE_CAPTCHA !== 'false' && !verifyCaptcha(captcha_id, captcha_answer, captcha_sig)) {
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
}
try {
const r = await pool.query(
`INSERT INTO replies (post_id, user_id, content)
+12 -4
View File
@@ -2,6 +2,7 @@
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
import { jsonWithEtag } from '@/lib/http-cache';
import { verifyCaptcha } from '@/lib/captcha';
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
export const dynamic = 'force-dynamic';
@@ -11,9 +12,12 @@ export async function GET(req) {
const url = new URL(req.url);
const sort = url.searchParams.get('sort') === 'hot' ? 'updated_at' : 'created_at';
const userId = url.searchParams.get('user_id');
const page = parseInt(url.searchParams.get('page')) || 1;
const limit = parseInt(url.searchParams.get('limit')) || 20;
const offset = (page - 1) * limit;
const page = Math.max(1, parseInt(url.searchParams.get('page')) || 1);
// 分页边界:limit 封顶 50,page 封顶 10000(防深分页 DoS)
const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit')) || 20));
const maxPage = Math.max(1, Math.ceil(200000 / limit));
const safePage = Math.min(page, maxPage);
const offset = (safePage - 1) * limit;
try {
const params = [];
@@ -54,10 +58,14 @@ export async function POST(req) {
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const { title, content, images } = await req.json();
const { title, content, images, captcha_id, captcha_answer, captcha_sig } = await req.json();
if (!content || content.trim().length === 0) {
return Response.json({ error: '请填写内容' }, { status: 400 });
}
// 服务端验证码校验(ENABLE_CAPTCHA 关闭时跳过)
if (process.env.ENABLE_CAPTCHA !== 'false' && !verifyCaptcha(captcha_id, captcha_answer, captcha_sig)) {
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
}
try {
const r = await pool.query(
`INSERT INTO posts (user_id, title, content, images)
+23 -7
View File
@@ -1,11 +1,26 @@
// POST /api/upload — 图片上传 (multipart/form-data)
// 安全:校验文件 magic bytes(不信任客户端 MIME/文件名),服务器生成 UUID 文件名
import path from 'path';
import { randomUUID } from 'crypto';
import { getUser } from '@/lib/auth';
import { saveObject } from '@/lib/storage';
const ALLOWED = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
const MAX_SIZE = 5 * 1024 * 1024;
// 从文件头字节嗅探真实图片类型(JPEG/PNG/GIF/WebP),拒绝伪造内容
function sniffImage(buf) {
if (buf.length < 12) return null;
// JPEG: FF D8 FF
if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return { ext: '.jpg', mime: 'image/jpeg' };
// PNG: 89 50 4E 47 0D 0A 1A 0A
if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 && buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) return { ext: '.png', mime: 'image/png' };
// GIF: "GIF8"
if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38) return { ext: '.gif', mime: 'image/gif' };
// WebP: "RIFF" .... "WEBP"
if (buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50) return { ext: '.webp', mime: 'image/webp' };
return null;
}
export const runtime = 'nodejs';
export async function POST(req) {
@@ -19,18 +34,19 @@ export async function POST(req) {
if (!file || typeof file === 'string') {
return Response.json({ error: '请选择图片' }, { status: 400 });
}
if (!ALLOWED.includes(file.type)) {
return Response.json({ error: '不支持的图片格式' }, { status: 400 });
}
if (file.size > MAX_SIZE) {
return Response.json({ error: '图片大小不能超过 5MB' }, { status: 400 });
}
try {
const ext = path.extname(file.name) || '.png';
const name = Date.now() + '-' + Math.round(Math.random() * 10000) + ext;
const buffer = Buffer.from(await file.arrayBuffer());
const { url } = await saveObject(name, buffer, file.type);
const sniff = sniffImage(buffer);
if (!sniff) {
return Response.json({ error: '不支持的图片格式' }, { status: 400 });
}
// 服务器生成 UUID 文件名 + 嗅探出的扩展名(不信任客户端文件名)
const name = randomUUID() + sniff.ext;
const { url } = await saveObject(name, buffer, sniff.mime);
return Response.json({ url });
} catch {
return Response.json({ error: '上传失败,请稍后重试' }, { status: 500 });
+2 -2
View File
@@ -400,8 +400,8 @@ export default function AppProvider({ children, cachedName = '' }) {
return result;
}, []);
const register = useCallback(async (email, password, username) => {
const result = await API.register(email, password, username);
const register = useCallback(async (email, password, username, captcha) => {
const result = await API.register(email, password, username, captcha);
const loginResult = await API.login(email, password);
if (loginResult.user) {
setCurrentUser(loginResult.user);
+1 -1
View File
@@ -38,7 +38,7 @@ export default function CaptchaImage({ captcha, onRefresh }) {
}
// 算式文字(每个字符轻微旋转/位移,增加识别难度)
const text = captcha.question.replace(' = ?', '');
const text = (captcha.text || captcha.question || '').replace(' = ?', '');
const chars = text.split('');
const fontSize = Math.floor(H * 0.52);
const step = W / (chars.length + 1);
+13 -8
View File
@@ -3,7 +3,7 @@
// 登录/注册/举报 模态框
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { API, generateCaptcha } from '@/lib/api';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import CaptchaImage from './CaptchaImage';
@@ -28,8 +28,11 @@ export default function Modals({ modal, onClose, reportPostId }) {
// 举报表单
const [reportReason, setReportReason] = useState('spam');
// 打开注册弹窗时从服务器获取验证码挑战(HMAC 签名)
useEffect(() => {
if (modal === 'register') setRegCaptcha(generateCaptcha());
if (modal === 'register') {
API.getCaptcha().then((c) => setRegCaptcha(c)).catch(() => {});
}
}, [modal]);
if (!modal) return null;
@@ -57,14 +60,13 @@ export default function Modals({ modal, onClose, reportPostId }) {
const handleRegister = async () => {
if (!regUsername.trim() || !regEmail.trim() || !regPassword) { toast('请填写完整信息', 'warning'); return; }
if (regPassword.length < 6) { toast('密码至少6位', 'warning'); return; }
if (!regCaptcha || parseInt(regCaptchaInput) !== regCaptcha.answer) {
toast('验证码错误,请重新计算', 'warning');
setRegCaptcha(generateCaptcha());
setRegCaptchaInput('');
if (!regCaptcha || !regCaptchaInput.trim()) {
toast('请填写验证码', 'warning');
return;
}
try {
await register(regEmail.trim(), regPassword, regUsername.trim());
// 答案由服务端 HMAC 校验,前端不对比答案
await register(regEmail.trim(), regPassword, regUsername.trim(), { id: regCaptcha.id, answer: regCaptchaInput.trim(), sig: regCaptcha.sig });
onClose();
setRegUsername('');
setRegEmail('');
@@ -74,6 +76,9 @@ export default function Modals({ modal, onClose, reportPostId }) {
refresh();
} catch (err) {
toast('注册失败:' + err.message, 'error');
// 失败后刷新验证码
API.getCaptcha().then((c) => setRegCaptcha(c)).catch(() => {});
setRegCaptchaInput('');
}
};
@@ -113,7 +118,7 @@ export default function Modals({ modal, onClose, reportPostId }) {
<input type="password" placeholder={t('auth.passwordHint')} value={regPassword} onChange={(e) => setRegPassword(e.target.value)} />
<div className="captcha-row" style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '12px 0' }}>
{regCaptcha ? (
<CaptchaImage captcha={regCaptcha} onRefresh={() => { setRegCaptcha(generateCaptcha()); setRegCaptchaInput(''); }} />
<CaptchaImage captcha={regCaptcha} onRefresh={() => { API.getCaptcha().then((c) => setRegCaptcha(c)).catch(() => {}); setRegCaptchaInput(''); }} />
) : (
<span style={{ color: 'var(--text-light)' }}>{t('newPost.captchaLoading')}</span>
)}
+6 -10
View File
@@ -3,7 +3,7 @@
// 发帖页
import { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { API, generateCaptcha, uploadImage } from '@/lib/api';
import { API, uploadImage } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { useToast } from './Toast';
@@ -21,7 +21,7 @@ export default function NewPost() {
const [captchaInput, setCaptchaInput] = useState('');
const [uploading, setUploading] = useState(false);
useEffect(() => { setCaptcha(generateCaptcha()); }, []);
useEffect(() => { API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {}); }, []);
const handleFiles = async (files) => {
setUploading(true);
@@ -67,14 +67,10 @@ export default function NewPost() {
return;
}
if (!content.trim()) { toast('请填写内容', 'error'); return; }
if (!captcha || parseInt(captchaInput) !== captcha.answer) {
toast('验证码错误,请重新计算', 'error');
setCaptcha(generateCaptcha());
setCaptchaInput('');
return;
}
if (!captcha || !captchaInput.trim()) { toast('请填写验证码', 'error'); return; }
try {
await API.createPost(title.trim() || '无标题', content.trim(), images);
// 答案由服务端 HMAC 校验
await API.createPost(title.trim() || '无标题', content.trim(), images, { id: captcha.id, answer: captchaInput.trim(), sig: captcha.sig });
API.logEvent('create_post').catch(() => {});
toast('发布成功', 'success');
navigate('feed');
@@ -133,7 +129,7 @@ export default function NewPost() {
/>
<div className="captcha-row" style={{ margin: '12px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
{captcha ? (
<CaptchaImage captcha={captcha} onRefresh={() => { setCaptcha(generateCaptcha()); setCaptchaInput(''); }} />
<CaptchaImage captcha={captcha} onRefresh={() => { API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {}); setCaptchaInput(''); }} />
) : (
<span style={{ color: 'var(--text-light)' }}>{t('newPost.captchaLoading')}</span>
)}
+9 -11
View File
@@ -2,7 +2,7 @@
// 回复列表 + 发表回复表单
import { useEffect, useState, useCallback } from 'react';
import { API, generateCaptcha } from '@/lib/api';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { renderMarkdown } from '@/lib/markdown';
@@ -30,27 +30,25 @@ export default function ReplyList({ postId, onRefresh }) {
}, [postId]);
useEffect(() => { load(); }, [load]);
useEffect(() => { setCaptcha(generateCaptcha()); }, [postId]);
useEffect(() => { API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {}); }, [postId]);
const handleSubmit = async () => {
if (!currentUser) { toast('请先登录', 'warning'); return; }
if (!content.trim()) { toast('请填写回复内容', 'warning'); return; }
if (!captcha || parseInt(captchaInput) !== captcha.answer) {
toast('验证码错误,请重新计算', 'warning');
setCaptcha(generateCaptcha());
setCaptchaInput('');
return;
}
if (!captcha || !captchaInput.trim()) { toast('请填写验证码', 'warning'); return; }
try {
await API.createReply(postId, content.trim());
// 答案由服务端 HMAC 校验
await API.createReply(postId, content.trim(), { id: captcha.id, answer: captchaInput.trim(), sig: captcha.sig });
API.logEvent('create_reply').catch(() => {});
setContent('');
setCaptchaInput('');
setCaptcha(generateCaptcha());
API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {});
load();
onRefresh();
} catch (err) {
toast('回复失败:' + err.message, 'error');
API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {});
setCaptchaInput('');
}
};
@@ -112,7 +110,7 @@ export default function ReplyList({ postId, onRefresh }) {
/>
<div className="captcha-row" style={{ margin: '10px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
{captcha ? (
<CaptchaImage captcha={captcha} onRefresh={() => { setCaptcha(generateCaptcha()); setCaptchaInput(''); }} />
<CaptchaImage captcha={captcha} onRefresh={() => { API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {}); setCaptchaInput(''); }} />
) : (
<span style={{ color: 'var(--text-light)' }}>验证码加载中...</span>
)}
+19 -6
View File
@@ -41,8 +41,15 @@ export const API = {
if (data.token) setToken(data.token);
return data;
},
register(email, password, username) {
return apiFetch('/auth/register', { method: 'POST', body: JSON.stringify({ email, password, username }) });
// 服务端验证码(HMAC 签名挑战)
getCaptcha() {
return apiFetch('/captcha');
},
register(email, password, username, captcha) {
return apiFetch('/auth/register', {
method: 'POST',
body: JSON.stringify({ email, password, username, captcha_id: captcha?.id, captcha_answer: captcha?.answer, captcha_sig: captcha?.sig }),
});
},
logout() { setToken(null); },
getMe() { return apiFetch('/auth/me'); },
@@ -54,8 +61,11 @@ export const API = {
return apiFetch(q);
},
getPost(postId) { return apiFetch('/posts/' + postId); },
createPost(title, content, images) {
return apiFetch('/posts', { method: 'POST', body: JSON.stringify({ title, content, images: images || [] }) });
createPost(title, content, images, captcha) {
return apiFetch('/posts', {
method: 'POST',
body: JSON.stringify({ title, content, images: images || [], captcha_id: captcha?.id, captcha_answer: captcha?.answer, captcha_sig: captcha?.sig }),
});
},
updatePost(postId, title, content, images) {
return apiFetch('/posts/' + postId, { method: 'PUT', body: JSON.stringify({ title, content, images }) });
@@ -67,8 +77,11 @@ export const API = {
// 回复
getReplies(postId) { return apiFetch('/posts/' + postId + '/replies'); },
createReply(postId, content) {
return apiFetch('/posts/' + postId + '/replies', { method: 'POST', body: JSON.stringify({ content }) });
createReply(postId, content, captcha) {
return apiFetch('/posts/' + postId + '/replies', {
method: 'POST',
body: JSON.stringify({ content, captcha_id: captcha?.id, captcha_answer: captcha?.answer, captcha_sig: captcha?.sig }),
});
},
deleteReply(replyId) { return apiFetch('/replies/' + replyId, { method: 'DELETE' }); },
+37
View File
@@ -0,0 +1,37 @@
// 服务端验证码:一次性算术挑战,答案签名用 HMAC(对齐上游 ac4af62)
// - GET /api/captcha 返回 { id, text, sig };sig = HMAC(secret, `${id}:${answer}`)
// - 前端提交 captcha_id + captcha_answer + sig
// - 服务端用提交的答案重算 HMAC 与 sig 比对(防绕过/重放,防前端读答案)
import crypto from 'crypto';
function secret() {
// CAPTCHA_SECRET 可单独配置;默认回退 JWT_SECRET
return process.env.CAPTCHA_SECRET || process.env.JWT_SECRET || 'forumlify';
}
// 生成挑战:返回 { id, text, answer, sig };sig 用于校验答案
export function generateCaptchaChallenge() {
const a = Math.floor(Math.random() * 10) + 1;
const b = Math.floor(Math.random() * 10) + 1;
const id = crypto.randomUUID();
const answer = a + b;
const sig = crypto
.createHmac('sha256', secret())
.update(`${id}:${answer}`)
.digest('hex');
return { id, text: `${a} + ${b} = ?`, answer, sig };
}
// 验证:提交的答案重算签名与 sig 比对(长度固定,timingSafeEqual 安全)
export function verifyCaptcha(id, answer, sig) {
if (!id || answer === undefined || answer === null || answer === '' || !sig) return false;
const n = typeof answer === 'number' ? answer : parseInt(answer, 10);
if (Number.isNaN(n)) return false;
const expected = crypto
.createHmac('sha256', secret())
.update(`${id}:${n}`)
.digest('hex');
const a = Buffer.from(expected, 'hex');
const b = Buffer.from(String(sig), 'hex');
return a.length === b.length && crypto.timingSafeEqual(a, b);
}