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 真发正常。
This commit is contained in:
2026-09-02 19:12:54 +08:00
parent 7744a6b420
commit bededec29c
12 changed files with 867 additions and 390 deletions
+32 -24
View File
@@ -416,31 +416,39 @@ export function LoadingCurtain({
onComplete?: (open: boolean) => void;
}) {
const materialRef = useRef<any>(null);
// R3F's Canvas container carries inline `position: relative; width/height:
// 100%` which OVERRIDES any Tailwind `fixed inset-0` on the Canvas itself —
// the curtain then renders as an in-flow ~150px strip (invisible during
// transitions and, worse, pointer-events:auto so it eats card clicks). A
// dedicated fullscreen fixed wrapper gives the container a real viewport
// box; pointer-events:none inherits to the whole subtree.
return (
<Canvas
dpr={[1, 2]}
frameloop="demand"
gl={{
alpha: true,
antialias: false,
premultipliedAlpha: true,
depth: false,
stencil: false,
powerPreference: "high-performance",
preserveDrawingBuffer: false,
}}
className="fixed inset-0 z-[60] pointer-events-none"
>
<RadialHoleMask
open={open}
duration={duration}
initialProgress={initialProgress}
resetKey={resetKey}
onComplete={onComplete}
materialRef={materialRef}
/>
<DotsPost materialRef={materialRef} />
</Canvas>
<div className="fixed inset-0 z-[60] pointer-events-none">
<Canvas
dpr={[1, 2]}
frameloop="demand"
style={{ pointerEvents: "none" }}
gl={{
alpha: true,
antialias: false,
premultipliedAlpha: true,
depth: false,
stencil: false,
powerPreference: "high-performance",
preserveDrawingBuffer: false,
}}
>
<RadialHoleMask
open={open}
duration={duration}
initialProgress={initialProgress}
resetKey={resetKey}
onComplete={onComplete}
materialRef={materialRef}
/>
<DotsPost materialRef={materialRef} />
</Canvas>
</div>
);
}
+13 -115
View File
@@ -1,42 +1,28 @@
"use client";
import { useEffect, useState, useSyncExternalStore } from "react";
import { usePathname } from "next/navigation";
import { useEffect, useSyncExternalStore } from "react";
import { loadingBus } from "@/lib/loadingBus";
import LoadingCurtain from "@/components/canvas/LoadingCurtain";
/**
* Heavy-load hooks (formerly the entry LoadingOverlay). The entry/route
* curtain orchestration now lives in RouteTransitionOverlay (the original
* module 34841 drives BOTH flows from one pinhole curtain); this file keeps
* only the readiness plumbing other components consume.
*/
/** Stable server snapshot (must be cached — a fresh object would loop). */
const SERVER_SNAPSHOT = { progress: 0, ready: false };
function useHeavyLoad() {
export function useHeavyLoad() {
return useSyncExternalStore(
loadingBus.subscribe,
loadingBus.getSnapshot,
loadingBusSubscribe,
loadingBusGetSnapshot,
() => SERVER_SNAPSHOT
);
}
function useFontsReady() {
const [fontsReady, setFontsReady] = useState(false);
useEffect(() => {
let cancelled = false;
const fonts = (document as any).fonts;
if (!fonts) {
setFontsReady(true);
return;
}
fonts.ready.then(() => {
if (!cancelled) setFontsReady(true);
});
return () => {
cancelled = true;
};
}, []);
return fontsReady;
}
const clamp = (v: number, min: number, max: number) =>
Math.min(max, Math.max(min, v));
const loadingBusSubscribe = loadingBus.subscribe;
const loadingBusGetSnapshot = loadingBus.getSnapshot;
/**
* Heavy-asset readiness for the camera intro dolly (original cV's `p`:
@@ -53,91 +39,3 @@ export function useAppReady(): boolean {
return heavy.ready;
}
/**
* Entry loading flow — port of the original route-transition controller
* (module 34841) for the entry case on "/":
*
* 1. entry:wait — curtain fully closed (initialProgress 1), centered
* 140px bar shows 50%·fontsReady + 50%·heavyLoadProgress.
* 2. readyToLoadHeavy && fontsReady → hold 250ms → bar fades (250ms)
* → 250ms later the curtain opens (0.8s customCubic radial hole +
* dot mask) — reveal phase.
* 3. Curtain reveal completes (+0.9s grace) → idle: unmount everything.
*/
export function LoadingOverlay() {
const heavy = useHeavyLoad();
const fontsReady = useFontsReady();
// Original useHomeLoadingGate: the entry curtain is a "/"-only flow —
// detail routes render with no loading curtain at all.
const pathname = usePathname();
// wait → fading → reveal → (unmount when reveal completes)
const [phase, setPhase] = useState<"wait" | "fading" | "reveal">("wait");
const [mounted, setMounted] = useState(true);
const progress = Math.round(clamp(50 * +fontsReady + heavy.progress / 2, 0, 100));
const assetsDone = heavy.ready && fontsReady;
useEffect(() => {
if (!assetsDone || phase !== "wait") return;
// Original: 250ms hold → fade the bar → 250ms later open the curtain.
const t1 = window.setTimeout(() => setPhase("fading"), 250);
return () => window.clearTimeout(t1);
}, [assetsDone, phase]);
useEffect(() => {
if (phase !== "fading") return;
const t2 = window.setTimeout(() => setPhase("reveal"), 250);
return () => window.clearTimeout(t2);
}, [phase]);
if (!mounted || pathname !== "/") return null;
return (
<>
<LoadingCurtain
open={phase === "reveal"}
duration={0.8}
initialProgress={1}
resetKey={`entry:${phase}`}
onComplete={(open) => {
if (open) {
// Reveal finished — a beat later the curtain canvas unmounts.
window.setTimeout(() => setMounted(false), 900);
}
}}
/>
{phase !== "reveal" && (
<ProgressBar progress={progress} fading={phase === "fading"} />
)}
</>
);
}
/** Centered 140px progress bar (original `b`). */
function ProgressBar({ progress, fading }: { progress: number; fading: boolean }) {
const clamped = clamp(progress, 0, 100);
return (
<div
aria-hidden="true"
className={`left-1/2 top-1/2 z-40 fixed flex h-4 w-[140px] -translate-x-1/2 -translate-y-1/2 items-center justify-center pointer-events-none ${
fading ? "opacity-0" : "opacity-100"
}`}
style={{ transition: "opacity 250ms cubic-bezier(0.25, 1, 0.5, 1)" }}
>
<div className="relative h-1.5 w-full overflow-hidden rounded-full bg-l3">
<div
className="absolute inset-y-0 left-0 rounded-full bg-l1"
style={{
width: `${clamped}%`,
transition: "width 520ms cubic-bezier(0.22, 1, 0.36, 1)",
willChange: "width",
}}
/>
</div>
</div>
);
}
export default LoadingOverlay;
+267 -107
View File
@@ -2,107 +2,258 @@
/**
* RouteTransitionOverlay — 1:1 port of the original orchestrator (chunk
* 3c6cc5b2fcccdee5.js `function M`, module 34841), simplified to the pixel
* wipe without the WebGL mask material:
* 3c6cc5b2fcccdee5.js `function M`, module 34841). ONE unified pinhole
* curtain drives BOTH the first-load entry and every route transition:
*
* startNavigation(href)
* → phase "cover" : b1-colored fixed layer wipes IN over the page
* (0.8s, cubic-bezier(0.66, 0, 0.01, 1)); on complete → router.push
* (or replace) to the target href.
* → phase "wait" : new page mounts; heavy assets may still load.
* → phase "reveal" : layer wipes OUT (same easing), then → idle and
* the overlay unmounts; scramble lines re-enabled 100ms in.
* → mode "route", phase "cover" : curtain CLOSES to the pinhole
* (0.8s customCubic radial hole + masked dots, same canvas as the
* loading curtain); on complete → router.push/replace + phase "wait".
* → phase "wait" : new page mounts. Reveal waits for
* the TARGET page's routeLoading gate (only "/" has one:
* readyToLoadHeavy && fontsReady).
* → phase "reveal" : curtain OPENS (0.8s); on complete →
* idle, navigation cleared. Scramble lines re-enabled 100ms into
* the reveal.
*
* The b1 background matches the page body so the wipe reads as the page
* turning into a blank sheet — the original achieves the same look via the
* WebGL mask + grid colors.
* The linear-DOM-wipe overlay this replaces did NOT match the original —
* the original never wipes; it pinholes through the masked-dots curtain.
*
* Entry mode (first mount of "/"): curtain starts fully closed
* (initialProgress 1) and the 140px progress bar shows
* 50%·fontsReady + 50%·heavyLoadProgress; reveal fires as soon as both
* gates pass (the bar fades in parallel — the original does NOT hold the
* reveal for the bar). Pages other than "/" have entryLoading disabled and
* flash through to idle invisibly. Detail pages never call
* setReadyToLoadHeavy, so their gates fall through to the disabled branch.
*/
import { useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import { useRouteTransitionController } from "@/lib/routeTransition";
import {
useRouteTransitionController,
useFullscreenTransitionController,
} from "@/lib/routeTransition";
import { loadingBus } from "@/lib/loadingBus";
import LoadingCurtain from "@/components/canvas/LoadingCurtain";
type Phase = "wait" | "cover" | "reveal";
type Mode = "idle" | "entry" | "route";
type Phase = "wait" | "cover" | "reveal";
type Transition = { mode: Mode; phase: Phase };
const DURATION_MS = 800;
const EASING = "cubic-bezier(0.66, 0, 0.01, 1)";
const BG = "var(--color-b1)";
/** Original `y` (defaults) + `x` ("/" only enables both gates). */
type PathLoadingConfig = {
entryLoading: { enabled: boolean };
routeLoading: { enabled: boolean };
};
const DEFAULT_CONFIG: PathLoadingConfig = {
entryLoading: { enabled: false },
routeLoading: { enabled: false },
};
const ROUTE_CONFIG: Record<string, PathLoadingConfig> = {
"/": {
entryLoading: { enabled: true },
routeLoading: { enabled: true },
},
};
function pathConfig(pathname: string | null): PathLoadingConfig {
if (!pathname) return DEFAULT_CONFIG;
return ROUTE_CONFIG[pathname] ?? DEFAULT_CONFIG;
}
function clamp(e: number, t: number, r: number) {
return Math.min(r, Math.max(t, e));
}
function targetPathname(href: string | null): string | null {
if (!href) return null;
if (href.startsWith("/")) {
const [p] = href.split("?");
return p || "/";
}
try {
return new URL(href, window.location.origin).pathname || "/";
} catch {
return null;
}
}
function useFontsReady(): boolean {
const [fontsReady, setFontsReady] = useState(false);
useEffect(() => {
let cancelled = false;
const fonts = (document as unknown as { fonts?: { ready: Promise<unknown> } })
.fonts;
if (!fonts) {
setFontsReady(true);
return;
}
fonts.ready.then(() => {
if (!cancelled) setFontsReady(true);
});
return () => {
cancelled = true;
};
}, []);
return fontsReady;
}
export default function RouteTransitionOverlay() {
const router = useRouter();
const pathname = usePathname();
const { targetHref, navigationReplace, clearNavigation, setAllowScrambleLines } =
useRouteTransitionController();
const {
targetHref,
navigationReplace,
clearNavigation,
readyToLoadHeavy,
setReadyToLoadHeavy,
heavyLoadProgress,
setHeavyLoadProgress,
setAllowScrambleLines,
} = useRouteTransitionController();
const { menuOpen } = useFullscreenTransitionController();
const fontsReady = useFontsReady();
const routeFrom = useRef<{ path: string | null; coverDone: boolean }>({
path: null,
coverDone: false,
});
const [mode, setMode] = useState<Mode>("idle");
const [phase, setPhase] = useState<Phase>("wait");
const [transition, setTransition] = useState<Transition>({
mode: "entry",
phase: "wait",
});
// Entry progress-bar fade state (original P/z).
const [barFading, setBarFading] = useState(false);
const [barGone, setBarGone] = useState(false);
const navigateRef = useRef<() => void>(() => {});
navigateRef.current = () => {
if (mode === "route" && phase === "cover") {
routeFrom.current.coverDone = true;
setAllowScrambleLines(false);
if (targetHref) {
if (navigationReplace) router.replace(targetHref);
else router.push(targetHref);
}
setPhase("wait");
}
};
const { mode, phase } = transition;
const fromConfig = useMemo(() => pathConfig(pathname), [pathname]);
const targetPath = useMemo(() => targetPathname(targetHref), [targetHref]);
const targetConfig = useMemo(
() => pathConfig(targetPath ?? pathname),
[targetPath, pathname]
);
const targetPath = useMemo(() => {
if (!targetHref) return null;
if (targetHref.startsWith("/")) {
const [p] = targetHref.split("?");
return p || "/";
}
try {
return new URL(targetHref, window.location.origin).pathname || "/";
} catch {
return null;
}
}, [targetHref]);
// Heavy-load bridge: the provider's readyToLoadHeavy/heavyLoadProgress is
// fed by the HOME canvas in the original (cV: models + image layers all
// loaded). Our equivalent is loadingBus — keep the provider in sync so
// the gates read exactly like the original.
useEffect(() => {
const sync = () => {
const snap = loadingBus.getSnapshot();
setHeavyLoadProgress(snap.progress);
if (snap.ready) setReadyToLoadHeavy(true);
};
sync();
const un = loadingBus.subscribe(sync);
return un;
}, [setHeavyLoadProgress, setReadyToLoadHeavy]);
// Intent → start cover.
// Intent → cover (original effect 1).
useEffect(() => {
if (targetHref && mode === "idle") {
routeFrom.current.path = pathname;
routeFrom.current.coverDone = false;
setMode("route");
setPhase("cover");
routeFrom.current = { path: pathname, coverDone: false };
setTransition({ mode: "route", phase: "cover" });
}
}, [targetHref, mode, pathname]);
// New page mounted → reveal.
// Entry wait → reveal (original effect 2): fires as soon as the gates
// pass — the reveal is NOT held for the progress-bar fade timers.
useEffect(() => {
if (
mode === "entry" &&
phase === "wait" &&
(!fromConfig.entryLoading.enabled || (readyToLoadHeavy && fontsReady))
) {
setTransition({ mode: "entry", phase: "reveal" });
}
}, [mode, phase, fromConfig.entryLoading.enabled, readyToLoadHeavy, fontsReady]);
// Route wait → reveal (original effect 3): new page mounted + target
// page's routeLoading gate satisfied.
useEffect(() => {
if (
mode === "route" &&
phase === "wait" &&
routeFrom.current.coverDone &&
routeFrom.current.path &&
pathname !== routeFrom.current.path
pathname !== routeFrom.current.path &&
(!targetConfig.routeLoading.enabled || (readyToLoadHeavy && fontsReady))
) {
setPhase("reveal");
setTransition({ mode: "route", phase: "reveal" });
}
}, [mode, phase, pathname]);
}, [
mode,
phase,
pathname,
targetConfig.routeLoading.enabled,
readyToLoadHeavy,
fontsReady,
]);
// Reveal finished → idle.
const onRevealComplete = () => {
if (mode !== "idle" && phase === "reveal") {
setMode("idle");
clearNavigation();
routeFrom.current.path = null;
routeFrom.current.coverDone = false;
}
};
// Progress bar: 100% → hold 250ms → fade → 250ms → remove (original P/z
// timers; entry gate `_` only).
const heavyPct = clamp(heavyLoadProgress, 0, 100);
const progress = fromConfig.entryLoading.enabled
? clamp(50 * +fontsReady + heavyPct / 2, 0, 100)
: heavyPct;
const entryGate =
mode === "entry" &&
fromConfig.entryLoading.enabled &&
(phase === "wait" || phase === "reveal") &&
!barGone;
useEffect(() => {
if (!entryGate || barFading || progress < 100) return;
let t2: number | undefined;
const t1 = window.setTimeout(() => {
setBarFading(true);
t2 = window.setTimeout(() => setBarGone(true), 250);
}, 250);
return () => {
window.clearTimeout(t1);
if (t2 !== undefined) window.clearTimeout(t2);
};
}, [entryGate, barFading, progress]);
// Scramble lines gate (original: idle → true immediately; 100ms after
// a reveal starts).
const onComplete = useCallback(
(open: boolean) => {
// Cover finished: navigate (original I, open branch).
if (
open &&
mode === "route" &&
phase === "cover"
) {
routeFrom.current.coverDone = true;
setAllowScrambleLines(false);
if (targetHref) {
if (navigationReplace) router.replace(targetHref);
else router.push(targetHref);
}
setTransition({ mode: "route", phase: "wait" });
return;
}
// Reveal finished: idle + clear (original I, !open non-idle branch).
if (!open && mode !== "idle" && phase === "reveal") {
setTransition({ mode: "idle", phase: "wait" });
clearNavigation();
routeFrom.current = { path: null, coverDone: false };
return;
}
},
[
mode,
phase,
targetHref,
navigationReplace,
router,
setAllowScrambleLines,
clearNavigation,
menuOpen,
]
);
// Scramble lines gate (original effect: idle → true now; reveal → +100ms).
useEffect(() => {
if (mode === "idle") {
setAllowScrambleLines(true);
@@ -113,52 +264,61 @@ export default function RouteTransitionOverlay() {
return () => window.clearTimeout(t);
}, [mode, phase, setAllowScrambleLines]);
const overlayVisible = mode !== "idle" && phase !== "wait";
const wipeIn = phase === "cover";
// open prop (original O): idle → menuOpen; else closed until reveal.
const open = mode === "idle" ? menuOpen : phase !== "reveal";
// initialProgress (original B): only entry:wait starts fully closed.
const initialProgress = mode === "entry" && phase === "wait" ? 1 : undefined;
const resetKey = `${mode}:${phase}:${targetHref ?? ""}:${menuOpen ? "1" : "0"}`;
// DELIBERATE DEVIATION from the original: the original unmounts the
// curtain canvas once idle (`canvas/set false`), which costs ~200ms per
// navigation in production — invisible there, but in dev the whole R3F
// canvas + EffectComposer remount takes ~600ms and swallows most of the
// cover animation (the user literally sees the detail page appear with
// no transition). The canvas stays mounted here: frameloop="demand"
// makes an idle curtain free, and the cover starts within one frame —
// matching the original's OBSERVED choreography (dots closing from the
// edges within ~180-400ms of the click).
return (
<>
<LoadingCurtain
open={open}
duration={0.8}
initialProgress={initialProgress}
resetKey={resetKey}
onComplete={onComplete}
/>
{entryGate && <ProgressBar progress={progress} fading={barFading} />}
</>
);
}
/** Centered 140px progress bar (original `b`). */
function ProgressBar({
progress,
fading,
}: {
progress: number;
fading: boolean;
}) {
return (
<div
aria-hidden={!overlayVisible}
style={{
position: "fixed",
inset: 0,
zIndex: 60,
background: BG,
pointerEvents: overlayVisible ? "auto" : "none",
opacity: overlayVisible ? 1 : 0,
visibility: overlayVisible ? "visible" : "hidden",
transition: overlayVisible
? `opacity 80ms linear`
: `opacity 200ms linear`,
clipPath: overlayVisible
? wipeIn
? "inset(0 0 100% 0)"
: "inset(0 0 0 0)"
: "inset(0 0 100% 0)",
...(overlayVisible
? {
animation: `route-wipe ${DURATION_MS}ms ${EASING} forwards`,
animationDirection: wipeIn ? "normal" : "reverse",
}
: {}),
}}
onAnimationEnd={(e) => {
if (e.animationName !== "route-wipe") return;
if (wipeIn) navigateRef.current();
else onRevealComplete();
}}
aria-hidden="true"
className={`left-1/2 top-1/2 z-40 fixed flex h-4 w-[140px] -translate-x-1/2 -translate-y-1/2 items-center justify-center pointer-events-none ${
fading ? "opacity-0" : "opacity-100"
}`}
style={{ transition: "opacity 250ms cubic-bezier(0.25, 1, 0.5, 1)" }}
>
<style>{`@keyframes route-wipe { from { clip-path: inset(0 0 100% 0); } to { clip-path: inset(0 0 0 0); } }`}</style>
{/* 16px checker texture (original pixelSize:16 maskCells) */}
<div
className="absolute inset-0 pointer-events-none"
style={{
opacity: 0.05,
backgroundImage:
"repeating-conic-gradient(var(--color-l1) 0% 25%, transparent 0% 50%)",
backgroundSize: "32px 32px",
}}
/>
<div className="relative h-1.5 w-full overflow-hidden rounded-full bg-l3">
<div
className="absolute inset-y-0 left-0 rounded-full bg-l1"
style={{
width: `${clamp(progress, 0, 100)}%`,
transition: "width 520ms cubic-bezier(0.22, 1, 0.36, 1)",
willChange: "width",
}}
/>
</div>
</div>
);
}
+173 -103
View File
@@ -1,19 +1,21 @@
"use client";
/**
* SliderCaptcha — 滑块拼图验证码(全屏居中弹层)。
* SliderCaptcha v2 — 图片化滑块验证(全屏居中弹层)。
*
* - 打开时向 /api/captcha/new 要 challenge:{ token, puzzleX }(缺口位置,
* 500 坐标系)。
* - 轨道点阵背景 + 缺口槽(虚线 lime 框);拖动滑块使图案连续对齐缺口。
* - 松手提交 { token, x } → 校验通过返回一次性 submitToken(5 分钟单次),
* 由父组件携带它提交咨询接口。
* - 校验失败抖动重置;challenge 失效自动换新。
* 与 v1 的区别:
* - 缺口位置由服务端烘进 PNG(bg 带缺口、piece 为裁片),JS 无答案,
* 脚本无法从响应反推位置。
* - 拖动过程按指针事件采样轨迹(时间 + 横坐标),verify 时提交服务端
* 做行为校验(时长 / 匀速直线 / 末点一致性),瞬间拖动直接拒绝。
* - verify 参数为 { challengeId, x, track };x 为 400 坐标系里的落点。
*/
import { useCallback, useEffect, useRef, useState } from "react";
const COORD_SPACE = 500; // 服务器缺口坐标系宽度
const PIECE_W = 48;
const IMG_W = 400;
const PIECE_W = 48; // 与服务端 lib/captchaImage 的 PIECE_W 一致
type TrackSample = { t: number; x: number };
export default function SliderCaptcha({
open,
@@ -24,35 +26,70 @@ export default function SliderCaptcha({
onClose: () => void;
onVerified: (submitToken: string) => void;
}) {
const [challenge, setChallenge] = useState<{
token: string;
puzzleX: number;
} | null>(null);
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 trackRef = useRef<HTMLDivElement | null>(null);
const trackPxRef = useRef(300);
const [trackPx, setTrackPx] = useState(300);
const [nonce, setNonce] = useState(0); // 失效后重取 challenge
const startXRef = useRef(0);
const startDragRef = useRef(0);
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;
(async () => {
void (async () => {
try {
const res = await fetch("/api/captcha/new", { method: "POST" });
const data = (await res.json()) as { token?: string; puzzleX?: number };
const data = (await res.json()) as {
challengeId?: number;
bg?: string;
piece?: string;
error?: string;
};
if (cancelled) return;
if (data.token && typeof data.puzzleX === "number") {
setChallenge({ token: data.token, puzzleX: data.puzzleX });
if (data.challengeId && data.bg && data.piece) {
setImgs({ bg: data.bg, piece: data.piece });
setChallengeId(data.challengeId);
} else {
setError("验证码加载失败");
setError(data.error ?? "验证码加载失败");
}
} catch {
if (!cancelled) setError("网络错误,请重试");
@@ -61,39 +98,49 @@ export default function SliderCaptcha({
return () => {
cancelled = true;
};
}, [open, nonce]);
}, [open]);
// 轨道实际像素宽度(500 坐标系缩放)——ResizeObserver 的初始通知是
// 异步派发的,不在 effect 里同步 setState。
// 轨道实际像素宽度(坐标换算基准)。初始测量走 ResizeObserver 的
// 异步首帧通知 + rAF,不在 effect 同步路径 setState。
useEffect(() => {
if (!open) return;
const el = trackRef.current;
if (!el) return;
const apply = (w: number) => {
const px = Math.round(w) || 300;
const px = Math.round(w);
trackPxRef.current = px;
setTrackPx(px);
};
// observe 的初始尺寸通知由浏览器异步派发,这里不手动同步测量
// (避免在 effect 内同步 setState 触发级联渲染)。
const ro = new ResizeObserver((entries) => {
apply(entries[0].contentRect.width);
});
ro.observe(el);
return () => ro.disconnect();
}, [open]);
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 (!challenge) return;
if (challengeId === null) return;
setStatus("checking");
const track = trackPxRef.current || 1;
const x = Math.round((finalDragX / track) * COORD_SPACE);
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({ token: challenge.token, x }),
body: JSON.stringify({ challengeId, x, track }),
});
const data = (await res.json()) as {
ok?: boolean;
@@ -106,15 +153,15 @@ export default function SliderCaptcha({
return;
}
setStatus("error");
setError(data.error ?? "位置不对,再试一次");
setError(data.error ?? "验证失败,请重试");
setShake(true);
window.setTimeout(() => setShake(false), 400);
if (data.error?.includes("失效") || data.error?.includes("过期")) {
setChallenge(null);
setDragX(0);
setNonce((n) => n + 1);
if (data.error?.includes("失效") || data.error?.includes("过期") || data.error?.includes("频繁")) {
void newChallenge();
} else {
setDragX(0);
trackSamplesRef.current = [];
pointerRef.current = null;
}
} catch {
setStatus("error");
@@ -122,34 +169,36 @@ export default function SliderCaptcha({
setDragX(0);
}
},
[challenge, onVerified]
[challengeId, onVerified, newChallenge]
);
if (!open) return null;
const slotX = challenge ? (challenge.puzzleX / COORD_SPACE) * trackPx : 0;
const maxDrag = Math.max(0, trackPx - PIECE_W);
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;
startDragRef.current = dragX;
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 next = startDragRef.current + (e.clientX - startXRef.current);
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;
void verify(dragX);
};
const dottedBg: React.CSSProperties = {
backgroundImage: "radial-gradient(var(--grid-dot) 1px, transparent 1px)",
backgroundSize: "12px 12px",
pointerRef.current = null;
void verify(pieceX);
};
return (
@@ -177,70 +226,91 @@ export default function SliderCaptcha({
</button>
</div>
{/* 拼图轨道 */}
{/* 拼图轨道(服务端渲染图:缺口位置在图里,不在 JS 里) */}
<div
ref={trackRef}
className="relative h-14 overflow-hidden border border-line bg-b1"
style={dottedBg}
className="relative h-[140px] overflow-hidden border border-line bg-b1"
>
{/* 缺口槽 */}
{challenge && (
<div
aria-hidden="true"
className="absolute top-0 h-full border-2 border-dashed border-(--selection-bg) bg-black/30"
style={{ left: slotX, width: PIECE_W }}
/>
{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
role="slider"
aria-label="拖动滑块完成拼图"
aria-valuenow={Math.round((dragX / maxDrag) * 100) || 0}
aria-valuemin={0}
aria-valuemax={100}
tabIndex={0}
className={`absolute top-0 h-full cursor-grab border-2 border-l1 bg-b1 active:cursor-grabbing ${
shake ? "animate-[vh-shake_0.35s_ease-in-out]" : ""
}`}
style={{
left: dragX,
width: PIECE_W,
...dottedBg,
backgroundPositionX: -dragX,
}}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
onKeyDown={(e) => {
if (e.key === "ArrowRight") {
e.preventDefault();
setDragX((x) => Math.min(maxDrag, x + PIECE_W));
void verify(Math.min(maxDrag, dragX + PIECE_W));
}
}}
>
<span className="pointer-events-none absolute inset-0 flex justify-center items-center font-mono text-l1">
➜
</span>
</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 ? (dragX / maxDrag) * 100 : 0}%` }}
style={{ width: `${maxDrag ? (pieceX / maxDrag) * 100 : 0}%` }}
/>
</div>
<p className="mt-3 font-mono-2 text-xs text-l2">
{status === "checking"
? "校验中…"
: error
? error
: "拖动滑块,将虚线框与图案对齐"}
</p>
<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>
);