"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(null); const [trackPx, setTrackPx] = useState(360); const [dragX, setDragX] = useState(0); const [status, setStatus] = useState<"idle" | "dragging" | "checking" | "error">( "idle" ); const [error, setError] = useState(null); const [shake, setShake] = useState(false); const trackRef = useRef(null); const trackPxRef = useRef(360); // 轨迹采样:x 为「相对起点的位移(px)」,verify 前统一换算到 400 坐标系 const trackSamplesRef = useRef([]); 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 (
{ if (e.target === e.currentTarget) onClose(); }} >
安全验证
{/* 拼图轨道(服务端渲染图:缺口位置在图里,不在 JS 里) */}
{imgs ? ( <> {/* eslint-disable-next-line @next/next/no-img-element -- 动态验证码图 */} {/* 拼块:globalPattern 在 answerX 的裁片,拖到缺口处图案连续 */}
{ 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; } }} /> ) : (
{error ? error : "加载中…"}
)}
{/* 进度条 */}

{status === "checking" ? "校验中…" : error && status === "error" ? error : "拖动拼块,对齐缺口图案"}

); }