Files
personal/components/dom/SliderCaptcha.tsx
T
virtheart bededec29c feat: 服务页双栏布局 + 滑块验证码 v2(图片化挑战/行为校验/限流/蜜罐)
服务页(/services):
- lg+ 双栏:左列服务菜单(NO.01-07,点击选中)、右列表单
  (sticky 跟随);移动端保持上下堆叠

滑块验证码 v2(防机械脚本):
- 答案坐标不再下发:缺口位置由服务端烘进 PNG(lib/captchaImage
  自绘点阵底图 + 拼块裁片,lib/pngEncoder 纯 TS PNG 编码器,
  node:zlib 零依赖),脚本必须做图像识别才能定位
- 行为轨迹校验:拖动采样提交服务端,样本数 ≥6、总时长 ≥1.2s、
  单调时间戳、峰值速度 > 平均×1.8(匀速直线 = 拒)、末点 ≈ 答案
- 位置容差 ±10px;失败 5 次作废;挑战 10 分钟过期
- IP 指纹(哈希)限流:challenge 15/10min、verify 30/10min、
  咨询提交 3/小时;蜜罐字段(website)命中静默丢弃

端到端:无轨迹/匀速直线/超短时长均拒;真人节奏通过;重放拦截;
蜜罐丢弃;第 14 次刷 challenge 起 429;SMTP 真发正常。
2026-09-02 19:12:54 +08:00

318 lines
11 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
/**
* SliderCaptcha v2 — 图片化滑块验证(全屏居中弹层)。
*
* 与 v1 的区别:
* - 缺口位置由服务端烘进 PNG(bg 带缺口、piece 为裁片),JS 无答案,
* 脚本无法从响应反推位置。
* - 拖动过程按指针事件采样轨迹(时间 + 横坐标),verify 时提交服务端
* 做行为校验(时长 / 匀速直线 / 末点一致性),瞬间拖动直接拒绝。
* - verify 参数为 { challengeId, x, track };x 为 400 坐标系里的落点。
*/
import { useCallback, useEffect, useRef, useState } from "react";
const IMG_W = 400;
const PIECE_W = 48; // 与服务端 lib/captchaImage 的 PIECE_W 一致
type TrackSample = { t: number; x: number };
export default function SliderCaptcha({
open,
onClose,
onVerified,
}: {
open: boolean;
onClose: () => void;
onVerified: (submitToken: string) => void;
}) {
const [imgs, setImgs] = useState<{ bg: string; piece: string } | null>(null);
const [challengeId, setChallengeId] = useState<number | null>(null);
const [trackPx, setTrackPx] = useState(360);
const [dragX, setDragX] = useState(0);
const [status, setStatus] = useState<"idle" | "dragging" | "checking" | "error">(
"idle"
);
const [error, setError] = useState<string | null>(null);
const [shake, setShake] = useState(false);
const trackRef = useRef<HTMLDivElement | null>(null);
const trackPxRef = useRef(360);
// 轨迹采样:x 为「相对起点的位移(px)」,verify 前统一换算到 400 坐标系
const trackSamplesRef = useRef<TrackSample[]>([]);
const pointerRef = useRef<{ x: number; t: number } | null>(null);
const startXRef = useRef(0);
// 拉取新挑战(事件回调路径:允许同步重置状态)。
const newChallenge = useCallback(async () => {
setStatus("idle");
setError(null);
setDragX(0);
setImgs(null);
setChallengeId(null);
trackSamplesRef.current = [];
pointerRef.current = null;
try {
const res = await fetch("/api/captcha/new", { method: "POST" });
const data = (await res.json()) as {
challengeId?: number;
bg?: string;
piece?: string;
error?: string;
};
if (data.challengeId && data.bg && data.piece) {
setImgs({ bg: data.bg, piece: data.piece });
setChallengeId(data.challengeId);
} else {
setError(data.error ?? "验证码加载失败");
}
} catch {
setError("网络错误,请重试");
}
}, []);
// 打开弹层时拉取挑战 — 异步 IIFE,无同步 setState。
useEffect(() => {
if (!open) return;
let cancelled = false;
void (async () => {
try {
const res = await fetch("/api/captcha/new", { method: "POST" });
const data = (await res.json()) as {
challengeId?: number;
bg?: string;
piece?: string;
error?: string;
};
if (cancelled) return;
if (data.challengeId && data.bg && data.piece) {
setImgs({ bg: data.bg, piece: data.piece });
setChallengeId(data.challengeId);
} else {
setError(data.error ?? "验证码加载失败");
}
} catch {
if (!cancelled) setError("网络错误,请重试");
}
})();
return () => {
cancelled = true;
};
}, [open]);
// 轨道实际像素宽度(坐标换算基准)。初始测量走 ResizeObserver 的
// 异步首帧通知 + rAF,不在 effect 同步路径 setState。
useEffect(() => {
if (!open) return;
const el = trackRef.current;
if (!el) return;
const apply = (w: number) => {
const px = Math.round(w);
trackPxRef.current = px;
setTrackPx(px);
};
const ro = new ResizeObserver((entries) => {
apply(entries[0].contentRect.width);
});
ro.observe(el);
const raf = requestAnimationFrame(() => apply(el.clientWidth));
return () => {
ro.disconnect();
cancelAnimationFrame(raf);
};
}, [open, imgs]);
const scale = trackPx / IMG_W;
const pieceDisplayW = PIECE_W * scale;
const maxDrag = Math.max(0, trackPx - pieceDisplayW);
const verify = useCallback(
async (finalDragX: number) => {
if (challengeId === null) return;
setStatus("checking");
const scaleToImg = IMG_W / (trackPxRef.current || 1);
const track = trackSamplesRef.current.map((s) => ({
t: s.t,
x: Math.round(s.x * scaleToImg),
}));
const x = Math.round((finalDragX / (trackPxRef.current || 1)) * IMG_W);
try {
const res = await fetch("/api/captcha/verify", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ challengeId, x, track }),
});
const data = (await res.json()) as {
ok?: boolean;
submitToken?: string;
error?: string;
};
if (res.ok && data.submitToken) {
setStatus("idle");
onVerified(data.submitToken);
return;
}
setStatus("error");
setError(data.error ?? "验证失败,请重试");
setShake(true);
window.setTimeout(() => setShake(false), 400);
if (data.error?.includes("失效") || data.error?.includes("过期") || data.error?.includes("频繁")) {
void newChallenge();
} else {
setDragX(0);
trackSamplesRef.current = [];
pointerRef.current = null;
}
} catch {
setStatus("error");
setError("网络错误,请重试");
setDragX(0);
}
},
[challengeId, onVerified, newChallenge]
);
if (!open) return null;
const pieceX = Math.max(0, Math.min(maxDrag, dragX));
const onPointerDown = (e: React.PointerEvent) => {
if (status === "checking") return;
(e.target as HTMLElement).setPointerCapture?.(e.pointerId);
startXRef.current = e.clientX;
pointerRef.current = { x: e.clientX, t: performance.now() };
trackSamplesRef.current.push({ t: pointerRef.current.t, x: 0 });
setStatus("dragging");
};
const onPointerMove = (e: React.PointerEvent) => {
if (status !== "dragging") return;
const prev = pointerRef.current;
if (!prev) return;
const now = performance.now();
if (now - prev.t < 16) return; // ~60fps 采样
trackSamplesRef.current.push({ t: now, x: e.clientX - startXRef.current });
pointerRef.current = { x: e.clientX, t: now };
const next = dragX + (e.clientX - prev.x);
setDragX(Math.max(0, Math.min(maxDrag, next)));
};
const onPointerUp = () => {
if (status !== "dragging") return;
pointerRef.current = null;
void verify(pieceX);
};
return (
<div
className="inset-0 z-[80] fixed flex justify-center items-center bg-b1/85 p-4"
role="dialog"
aria-modal="true"
aria-label="滑块验证"
onClick={(e) => {
if (e.target === e.currentTarget) onClose();
}}
>
<div className="w-full max-w-sm border border-line bg-be p-5 select-none">
<div className="mb-4 flex items-center justify-between">
<span className="font-mono-2 text-xs uppercase tracking-widest text-l3">
安全验证
</span>
<button
type="button"
onClick={onClose}
aria-label="关闭验证"
className="cursor-pointer font-mono text-sm text-l3 hover:text-l1"
>
✕
</button>
</div>
{/* 拼图轨道(服务端渲染图:缺口位置在图里,不在 JS 里) */}
<div
ref={trackRef}
className="relative h-[140px] overflow-hidden border border-line bg-b1"
>
{imgs ? (
<>
{/* eslint-disable-next-line @next/next/no-img-element -- 动态验证码图 */}
<img
src={imgs.bg}
alt=""
draggable={false}
className="absolute inset-0 h-full w-full object-fill"
/>
{/* 拼块:globalPattern 在 answerX 的裁片,拖到缺口处图案连续 */}
<div
role="slider"
aria-label="拖动滑块,将拼块对齐缺口"
aria-valuenow={Math.round((pieceX / maxDrag) * 100) || 0}
aria-valuemin={0}
aria-valuemax={100}
tabIndex={0}
className={`absolute top-0 h-full cursor-grab active:cursor-grabbing touch-none ${
shake ? "animate-[vh-shake_0.35s_ease-in-out]" : ""
}`}
style={{
left: pieceX,
width: pieceDisplayW,
backgroundImage: `url(${imgs.piece})`,
backgroundSize: "100% 100%",
}}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
onKeyDown={(e) => {
if (status === "checking") return;
const step = e.key === "ArrowRight" ? 12 : e.key === "ArrowLeft" ? -12 : 0;
if (!step) return;
e.preventDefault();
const now = performance.now();
const lastX = trackSamplesRef.current.at(-1)?.x ?? 0;
trackSamplesRef.current.push({ t: now, x: lastX + step });
setDragX((d) => Math.max(0, Math.min(maxDrag, d + step)));
}}
onBlur={() => {
if (status === "dragging") {
setStatus("idle");
pointerRef.current = null;
}
}}
/>
</>
) : (
<div className="inset-0 absolute flex justify-center items-center font-mono-2 text-xs text-l3">
{error ? error : "加载中…"}
</div>
)}
</div>
{/* 进度条 */}
<div className="mt-3 h-1 w-full bg-line">
<div
className="h-full bg-(--selection-bg) transition-[width] duration-75"
style={{ width: `${maxDrag ? (pieceX / maxDrag) * 100 : 0}%` }}
/>
</div>
<div className="mt-3 flex items-center justify-between gap-3">
<p className="font-mono-2 text-xs text-l2">
{status === "checking"
? "校验中…"
: error && status === "error"
? error
: "拖动拼块,对齐缺口图案"}
</p>
<button
type="button"
onClick={() => void verify(pieceX)}
disabled={status === "checking" || !imgs}
className="shrink-0 cursor-pointer border border-line px-3 py-1.5 font-mono-2 text-xs text-l2 hover:border-l2 hover:text-l1 disabled:opacity-40"
>
验证
</button>
</div>
</div>
</div>
);
}