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

+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>
)}