fix(comment): harden comment form with server honeypot, a11y labels, and reply layout
Some checks failed
CI / check (push) Failing after 5m20s
CI / build (push) Has been skipped

四项评论区输入框修复:

1. 蜜罐服务端二次校验
   - helpers.rs 新增 validate_comment_honeypot 校验器 + 单元测试
   - create_comment 加 honeypot 参数,在限流后做服务端校验
   - 即便机器人禁用 JS 绕过前端拦截,服务端仍返回 spam_detected 错误
   - 与 rate limit 共同构成纵深防御

2. label/input 关联 (可访问性)
   - 四个字段补 id + r#for 属性,用 id_suffix(顶层 root/回复用 parent_id)保证页面唯一
   - textarea 原本无 label,补上"内容 *"label

3. 提交按钮右对齐 + 宽度自适应
   - 新常量 COMMENT_SUBMIT_CLASS 去掉 w-full、px-4 改为 px-6
   - 外层包 flex justify-end,按钮跟随文字宽度
   - login/register 的全宽按钮保持不变(模态卡片场景)

4. 深层回复表单回到内容区左边缘
   - CommentForm 新增 parent_indent prop,回复时用负 margin 抵消父评论缩进
   - 避免 depth 越深表单被越挤越右

验证: cargo test (376 passed) / cargo clippy --all-targets (无警告) / dx check (无问题)
This commit is contained in:
xfy 2026-06-22 13:45:28 +08:00
parent 694e198331
commit 10ef52bede
5 changed files with 174 additions and 93 deletions

View File

@ -21,12 +21,13 @@ pub async fn create_comment(
author_email: String,
author_url: Option<String>,
content_md: String,
honeypot: String,
) -> Result<CommentResponse, ServerFnError> {
#[cfg(feature = "server")]
{
use crate::api::comments::helpers::{
compute_content_hash, validate_comment_content, validate_comment_email,
validate_comment_name, validate_comment_url,
validate_comment_honeypot, validate_comment_name, validate_comment_url,
};
use crate::api::error::AppError;
use crate::cache;
@ -48,6 +49,18 @@ pub async fn create_comment(
}
}
// 蜜罐字段二次校验:禁用 JS 的机器人可能绕过前端拦截,这里作为服务端防线。
if let Err(e) = validate_comment_honeypot(&honeypot) {
return Ok(CommentResponse {
success: false,
message: e,
error_code: Some("spam_detected".into()),
comment_id: None,
avatar_url: None,
depth: None,
});
}
// 依次校验昵称、邮箱、网址与评论内容。
if let Err(e) = validate_comment_name(&author_name) {
return Ok(CommentResponse {

View File

@ -158,6 +158,19 @@ pub fn validate_comment_content(content: &str) -> Result<(), String> {
Ok(())
}
/// 校验蜜罐字段:正常用户蜜罐为空,机器人可能填入任意内容。
///
/// 为空视为通过;一旦被填入内容即判定为机器人提交并拒绝。
/// 这是禁用 JS / 无视前端校验的机器人也能在服务端被拦下的防线。
#[cfg(feature = "server")]
pub fn validate_comment_honeypot(value: &str) -> Result<(), String> {
if value.is_empty() {
Ok(())
} else {
Err("评论提交异常".to_string())
}
}
/// 计算评论内容哈希,用于检测短时间内的重复提交。
#[cfg(feature = "server")]
pub fn compute_content_hash(
@ -400,4 +413,15 @@ mod tests {
assert_eq!(h.len(), 64);
assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
}
#[test]
fn validate_comment_honeypot_empty_is_ok() {
assert!(validate_comment_honeypot("").is_ok());
}
#[test]
fn validate_comment_honeypot_filled_is_err() {
assert!(validate_comment_honeypot("anything").is_err());
assert!(validate_comment_honeypot(" ").is_err());
}
}

View File

@ -6,21 +6,32 @@ use dioxus::prelude::*;
use crate::api::comments::create_comment;
use crate::components::comments::section::CommentContext;
use crate::components::forms::{AlertBox, BUTTON_PRIMARY_CLASS, INPUT_CLASS};
use crate::components::forms::{AlertBox, INPUT_CLASS};
use crate::hooks::comment_storage::{self, PendingComment};
/// 评论提交按钮样式:去掉全宽,改为内联宽度并右对齐。
///
/// 与 `BUTTON_PRIMARY_CLASS` 视觉一致,但不含 `w-full`,并把 `px-4` 加宽为 `px-6`
/// 使按钮宽度跟随文字、更适合文章页内联场景。
const COMMENT_SUBMIT_CLASS: &str = "py-2.5 px-6 bg-paper-accent text-white font-medium rounded-full hover:brightness-110 active:scale-[0.98] transition-all duration-200 cursor-pointer";
/// 评论表单组件,用于顶层评论或回复评论。
///
/// Props
/// - `post_id`:所属文章 ID
/// - `parent_id`:回复目标评论 ID`None` 表示顶层评论
/// - `parent_indent`:回复时父评论的缩进像素值,用于用负 margin 把表单拉回内容区左边缘
///
/// 关键事件:
/// - 挂载时从本地存储恢复上次填写的作者信息
/// - 提交时校验必填项与蜜罐字段
/// - 提交成功后清空内容、保存作者信息、添加待审核评论并触发列表刷新
#[component]
pub fn CommentForm(post_id: i32, parent_id: Option<i64>) -> Element {
pub fn CommentForm(
post_id: i32,
parent_id: Option<i64>,
parent_indent: Option<i32>,
) -> Element {
let ctx: CommentContext = use_context();
let mut active_reply = ctx.active_reply;
let mut refresh_trigger = ctx.refresh_trigger;
@ -57,9 +68,22 @@ pub fn CommentForm(post_id: i32, parent_id: Option<i64>) -> Element {
let is_reply = parent_id.is_some();
// 用于区分顶层表单与多个回复表单的 id 后缀,保证页面内 label/for 关联唯一。
let id_suffix = match parent_id {
Some(pid) => pid.to_string(),
None => "root".to_string(),
};
// 回复表单抵消父评论缩进,让表单回到内容区左边缘,避免深层回复时被越挤越右。
let negative_margin = match (is_reply, parent_indent) {
(true, Some(px)) if px > 0 => format!("margin-left: -{px}px;"),
_ => String::new(),
};
rsx! {
div {
class: if is_reply { "mt-3 pt-3 border-t border-gray-100 dark:border-[#333]" } else { "" },
style: "{negative_margin}",
role: "form",
aria_label: if is_reply { "回复评论" } else { "发表评论" },
@ -72,10 +96,13 @@ pub fn CommentForm(post_id: i32, parent_id: Option<i64>) -> Element {
div { class: "space-y-3",
div { class: "grid grid-cols-1 sm:grid-cols-2 gap-3",
div {
label { class: "block text-sm font-medium text-paper-secondary mb-1",
label {
r#for: "comment-name-{id_suffix}",
class: "block text-sm font-medium text-paper-secondary mb-1",
"昵称 *"
}
input {
id: "comment-name-{id_suffix}",
class: INPUT_CLASS,
r#type: "text",
placeholder: "你的昵称",
@ -85,10 +112,13 @@ pub fn CommentForm(post_id: i32, parent_id: Option<i64>) -> Element {
}
}
div {
label { class: "block text-sm font-medium text-paper-secondary mb-1",
label {
r#for: "comment-email-{id_suffix}",
class: "block text-sm font-medium text-paper-secondary mb-1",
"邮箱 *"
}
input {
id: "comment-email-{id_suffix}",
class: INPUT_CLASS,
r#type: "email",
placeholder: "your@email.com",
@ -99,10 +129,13 @@ pub fn CommentForm(post_id: i32, parent_id: Option<i64>) -> Element {
}
}
div {
label { class: "block text-sm font-medium text-paper-secondary mb-1",
label {
r#for: "comment-url-{id_suffix}",
class: "block text-sm font-medium text-paper-secondary mb-1",
"网站"
}
input {
id: "comment-url-{id_suffix}",
class: INPUT_CLASS,
r#type: "url",
placeholder: "https://example.com可选",
@ -112,12 +145,20 @@ pub fn CommentForm(post_id: i32, parent_id: Option<i64>) -> Element {
}
}
div {
label {
r#for: "comment-content-{id_suffix}",
class: "block text-sm font-medium text-paper-secondary mb-1",
"内容 *"
}
textarea {
id: "comment-content-{id_suffix}",
class: "{INPUT_CLASS} min-h-[100px] resize-y",
value: "{content_md}",
disabled: submitting(),
oninput: move |e| content_md.set(e.value()),
}
}
p { class: "text-xs text-paper-tertiary",
"支持 Markdown 语法"
@ -132,8 +173,9 @@ pub fn CommentForm(post_id: i32, parent_id: Option<i64>) -> Element {
oninput: move |e| honeypot.set(e.value()),
}
div { class: "flex justify-end",
button {
class: BUTTON_PRIMARY_CLASS,
class: COMMENT_SUBMIT_CLASS,
disabled: submitting(),
onclick: move |_| {
if submitting() {
@ -169,6 +211,7 @@ pub fn CommentForm(post_id: i32, parent_id: Option<i64>) -> Element {
email.clone(),
if url_val.trim().is_empty() { None } else { Some(url_val.clone()) },
content.clone(),
hp.clone(),
).await;
submitting.set(false);
@ -231,4 +274,5 @@ pub fn CommentForm(post_id: i32, parent_id: Option<i64>) -> Element {
}
}
}
}
}

View File

@ -104,7 +104,7 @@ pub fn CommentItem(comment: PublicComment, post_id: i32) -> Element {
}
if is_replying {
CommentForm { post_id, parent_id: Some(comment.id) }
CommentForm { post_id, parent_id: Some(comment.id), parent_indent: Some(indent) }
}
}
}

View File

@ -98,7 +98,7 @@ pub fn CommentSection(post_id: i32) -> Element {
"评论区 ({total_count})"
}
CommentForm { post_id, parent_id: None }
CommentForm { post_id, parent_id: None, parent_indent: None }
if !has_any {
p { class: "text-paper-tertiary text-center py-8",