From bededec29c02fefac4282ea9842277766c3f3bf1 Mon Sep 17 00:00:00 2001
From: chenchun
Date: Wed, 2 Sep 2026 19:12:54 +0800
Subject: [PATCH] =?UTF-8?q?feat:=20=E6=9C=8D=E5=8A=A1=E9=A1=B5=E5=8F=8C?=
=?UTF-8?q?=E6=A0=8F=E5=B8=83=E5=B1=80=20+=20=E6=BB=91=E5=9D=97=E9=AA=8C?=
=?UTF-8?q?=E8=AF=81=E7=A0=81=20v2=EF=BC=88=E5=9B=BE=E7=89=87=E5=8C=96?=
=?UTF-8?q?=E6=8C=91=E6=88=98/=E8=A1=8C=E4=B8=BA=E6=A0=A1=E9=AA=8C/?=
=?UTF-8?q?=E9=99=90=E6=B5=81/=E8=9C=9C=E7=BD=90=EF=BC=89?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
服务页(/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 真发正常。
---
app/(site)/layout.tsx | 2 -
app/(site)/services/ServicesClient.tsx | 34 +-
app/api/captcha/new/route.ts | 19 +-
app/api/captcha/verify/route.ts | 19 +-
app/api/inquiry/route.ts | 34 +-
components/canvas/LoadingCurtain.tsx | 56 ++--
components/dom/LoadingOverlay.tsx | 128 +-------
components/dom/RouteTransitionOverlay.tsx | 374 +++++++++++++++-------
components/dom/SliderCaptcha.tsx | 276 ++++++++++------
lib/captcha.ts | 154 +++++++--
lib/captchaImage.ts | 99 ++++++
lib/pngEncoder.ts | 62 ++++
12 files changed, 867 insertions(+), 390 deletions(-)
create mode 100644 lib/captchaImage.ts
create mode 100644 lib/pngEncoder.ts
diff --git a/app/(site)/layout.tsx b/app/(site)/layout.tsx
index 216bb33..6a0cde6 100644
--- a/app/(site)/layout.tsx
+++ b/app/(site)/layout.tsx
@@ -2,7 +2,6 @@ import SmoothScroller from "@/components/dom/SmoothScroller";
import Header from "@/components/dom/Header";
import BackgroundGrid from "@/components/dom/BackgroundGrid";
import CustomScrollbar from "@/components/dom/CustomScrollbar";
-import LoadingOverlay from "@/components/dom/LoadingOverlay";
import { HeroScene } from "@/components/canvas/HeroScene";
import { PasscodeAccessProvider } from "@/components/dom/PasscodeAccess";
import { FullscreenTransitionProvider } from "@/lib/routeTransition";
@@ -84,7 +83,6 @@ export default async function SiteLayout({
{children}
-
);
diff --git a/app/(site)/services/ServicesClient.tsx b/app/(site)/services/ServicesClient.tsx
index 9ca79f1..49c2c1e 100644
--- a/app/(site)/services/ServicesClient.tsx
+++ b/app/(site)/services/ServicesClient.tsx
@@ -43,6 +43,9 @@ export default function ServicesClient({
const [name, setName] = useState("");
const [contact, setContact] = useState("");
const [message, setMessage] = useState("");
+ // 蜜罐:人类不可见(CSS 藏 + tabIndex=-1 + autocomplete 关闭),
+ // 群发机器人会把它当普通字段填上 —— 提交接口静默丢弃。
+ const [honeypot, setHoneypot] = useState("");
const [captchaOpen, setCaptchaOpen] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState(null);
@@ -72,6 +75,7 @@ export default function ServicesClient({
serviceSlug: selected.slug,
serviceTitle: selected.title,
message: message.trim(),
+ website: honeypot,
}),
});
const data = (await res.json()) as { id?: number; error?: string };
@@ -89,7 +93,7 @@ export default function ServicesClient({
setSubmitting(false);
}
},
- [selected, name, contact, message]
+ [selected, name, contact, message, honeypot]
);
if (doneId !== null) {
@@ -164,8 +168,10 @@ export default function ServicesClient({
- {/* 服务菜单 */}
-
+ {/* 双栏:左服务菜单 / 右表单(lg+ 并排,移动端上下堆叠) */}
+
+ {/* 服务菜单(左栏) */}
+
{services.length === 0 ? (
服务清单整理中——有需要可直接写邮件给我。
@@ -221,8 +227,11 @@ export default function ServicesClient({
)}
- {/* 留言表单 */}
-
+ {/* 留言表单(右栏,lg+ sticky 跟随) */}
+
{selected ? `咨询:${selected.title}` : "留言"}
@@ -273,6 +282,20 @@ export default function ServicesClient({
{submitNote}
+ {/* 蜜罐字段 — 人类不可见;机器人填了就被服务端静默丢弃 */}
+
+
+ setHoneypot(e.target.value)}
+ />
+
+
{error && (
{error}
@@ -288,6 +311,7 @@ export default function ServicesClient({
{submitting ? "提交中…" : "提交(需完成滑块验证)"}
+
500) {
+ return NextResponse.json({ error: "参数错误" }, { status: 400 });
+ }
+ const result = verifyCaptcha(req, challengeId, Math.round(x), track);
if (!result.ok) {
return NextResponse.json({ error: result.error }, { status: 400 });
}
diff --git a/app/api/inquiry/route.ts b/app/api/inquiry/route.ts
index dc56e08..8b30ea2 100644
--- a/app/api/inquiry/route.ts
+++ b/app/api/inquiry/route.ts
@@ -5,7 +5,7 @@
* 状态记录在 inquiries.email_sent / email_error,后台留言箱可见)。
*/
import { NextResponse } from "next/server";
-import { consumeSubmitToken } from "@/lib/captcha";
+import { consumeSubmitToken, clientFingerprint } from "@/lib/captcha";
import { createInquiry, markInquiryEmail } from "@/lib/siteConfig";
import { sendInquiryNotification } from "@/lib/mailer";
@@ -15,6 +15,21 @@ const NAME_MAX = 40;
const CONTACT_MAX = 80;
const MESSAGE_MAX = 2000;
+// 提交限流桶(单实例内存实现,重启清零可接受)。
+const submitBuckets = new Map();
+function submitRateLimit(fp: string): boolean {
+ const now = Date.now();
+ const windowMs = 60 * 60_000;
+ const arr = (submitBuckets.get(fp) ?? []).filter((t) => now - t < windowMs);
+ if (arr.length >= 3) {
+ submitBuckets.set(fp, arr);
+ return false;
+ }
+ arr.push(now);
+ submitBuckets.set(fp, arr);
+ return true;
+}
+
export async function POST(req: Request) {
let body: {
submitToken?: string;
@@ -23,6 +38,8 @@ export async function POST(req: Request) {
serviceSlug?: string;
serviceTitle?: string;
message?: string;
+ /** 蜜罐:人类不可见不填写;机器人会全字段填充 */
+ website?: string;
};
try {
body = await req.json();
@@ -30,6 +47,21 @@ export async function POST(req: Request) {
return NextResponse.json({ error: "请求格式错误" }, { status: 400 });
}
+ // 蜜罐命中:静默丢弃(不告诉机器人被识别)
+ if (typeof body.website === "string" && body.website.trim() !== "") {
+ return NextResponse.json({ ok: true, id: 0 });
+ }
+
+ // 提交限流:3 次 / 小时 / IP(与验证码限流独立)
+ const fp = clientFingerprint(req);
+ const rl = submitRateLimit(fp);
+ if (!rl) {
+ return NextResponse.json(
+ { error: "提交过于频繁,请稍后再试" },
+ { status: 429 }
+ );
+ }
+
const name = String(body.name ?? "").trim();
const contact = String(body.contact ?? "").trim();
const message = String(body.message ?? "").trim();
diff --git a/components/canvas/LoadingCurtain.tsx b/components/canvas/LoadingCurtain.tsx
index 1aeff5d..8244a83 100644
--- a/components/canvas/LoadingCurtain.tsx
+++ b/components/canvas/LoadingCurtain.tsx
@@ -416,31 +416,39 @@ export function LoadingCurtain({
onComplete?: (open: boolean) => void;
}) {
const materialRef = useRef(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 (
-
+
+
+
);
}
diff --git a/components/dom/LoadingOverlay.tsx b/components/dom/LoadingOverlay.tsx
index e9fbfa4..c86992d 100644
--- a/components/dom/LoadingOverlay.tsx
+++ b/components/dom/LoadingOverlay.tsx
@@ -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 (
- <>
- {
- if (open) {
- // Reveal finished — a beat later the curtain canvas unmounts.
- window.setTimeout(() => setMounted(false), 900);
- }
- }}
- />
- {phase !== "reveal" && (
-
- )}
- >
- );
-}
-
-/** Centered 140px progress bar (original `b`). */
-function ProgressBar({ progress, fading }: { progress: number; fading: boolean }) {
- const clamped = clamp(progress, 0, 100);
- return (
-
- );
-}
-
-export default LoadingOverlay;
diff --git a/components/dom/RouteTransitionOverlay.tsx b/components/dom/RouteTransitionOverlay.tsx
index 3ce3a8e..4b7bd30 100644
--- a/components/dom/RouteTransitionOverlay.tsx
+++ b/components/dom/RouteTransitionOverlay.tsx
@@ -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 = {
+ "/": {
+ 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 } })
+ .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("idle");
- const [phase, setPhase] = useState("wait");
+ const [transition, setTransition] = useState({
+ 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 (
+ <>
+
+ {entryGate && }
+ >
+ );
+}
+
+/** Centered 140px progress bar (original `b`). */
+function ProgressBar({
+ progress,
+ fading,
+}: {
+ progress: number;
+ fading: boolean;
+}) {
return (
{
- 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)" }}
>
-
- {/* 16px checker texture (original pixelSize:16 maskCells) */}
-
+
);
}
diff --git a/components/dom/SliderCaptcha.tsx b/components/dom/SliderCaptcha.tsx
index 46f7b4e..b441e66 100644
--- a/components/dom/SliderCaptcha.tsx
+++ b/components/dom/SliderCaptcha.tsx
@@ -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(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 trackRef = useRef(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(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;
- (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({
- {/* 拼图轨道 */}
+ {/* 拼图轨道(服务端渲染图:缺口位置在图里,不在 JS 里) */}
- {/* 缺口槽 */}
- {challenge && (
-
+ {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 : "加载中…"}
+
)}
- {/* 可拖动滑块(点阵与轨道同源,拖到缺口处图案连续) */}
-
{
- if (e.key === "ArrowRight") {
- e.preventDefault();
- setDragX((x) => Math.min(maxDrag, x + PIECE_W));
- void verify(Math.min(maxDrag, dragX + PIECE_W));
- }
- }}
- >
-
- ➜
-
-
{/* 进度条 */}
-
- {status === "checking"
- ? "校验中…"
- : error
- ? error
- : "拖动滑块,将虚线框与图案对齐"}
-
+
+
+ {status === "checking"
+ ? "校验中…"
+ : error && status === "error"
+ ? error
+ : "拖动拼块,对齐缺口图案"}
+
+
+
);
diff --git a/lib/captcha.ts b/lib/captcha.ts
index 15c7e46..6ab9226 100644
--- a/lib/captcha.ts
+++ b/lib/captcha.ts
@@ -1,51 +1,149 @@
/**
- * 滑块验证码 — 服务端Challenge/Verify。
+ * 滑块验证码 v2 — 图片化挑战 + 行为轨迹校验 + 限流。
*
- * 生成:随机缺口位置(80-420px)+ 一次性 token(10 分钟有效)。
- * 校验:客户端提交拖动终点 x,|x - answer| <= CAPTCHA_TOLERANCE 即通过;
- * 通过后签发一次性 submitToken(5 分钟、单次消费),提交接口凭它放行。
- * 失败计数 5 次作废 challenge,防暴力枚举。
+ * 与 v1 的区别(防脚本):
+ * 1. 答案坐标不再下发——缺口位置由服务端烘进 PNG(lib/captchaImage),
+ * JS 里没有答案,脚本必须做图像识别才能定位。
+ * 2. verify 需提交拖动轨迹样本 track:[{t,x}...],服务端做行为校验:
+ * - 样本数 ≥ 6(真人拖动必然产生采样)
+ * - 总时长 ≥ 1200ms 且 ≤ 10s(瞬间完成 = 脚本;超时 = 挑战过期)
+ * - 轨迹与最终答案一致(末样本 ≈ 提交的 x)
+ * - 存在速度波动(峰值速度 > 平均速度×1.8,匀速直线 = 机械拖动)
+ * - 位置容差 ±10px
+ * 3. 失败 5 次作废挑战;挑战 10 分钟过期。
+ * 4. IP 哈希限流(蜜罐行不再单独依赖):
+ * - new challenge ≤ 15 次 / 10 分钟 / IP
+ * - verify ≤ 30 次 / 10 分钟 / IP
+ * 5. submitToken 单次消费 + 5 分钟过期(提交接口校验)。
+ * 6. 表单蜜罐字段在提交 API 校验(见 app/api/inquiry)。
*/
import crypto from "node:crypto";
import { db } from "@/lib/db";
+import { renderCaptchaImages } from "@/lib/captchaImage";
-export const CAPTCHA_TOLERANCE = 8;
+export const CAPTCHA_TOLERANCE = 10;
const CHALLENGE_TTL_MIN = 10;
const SUBMIT_TOKEN_TTL_MIN = 5;
const MAX_ATTEMPTS = 5;
-export function createCaptchaChallenge(): {
- id: number;
- puzzleX: number; // 缺口随机位置(前端展示用)
- trackWidth: number;
- token: string;
-} {
- const puzzleX = 80 + crypto.randomInt(0, 341); // 80..420
+// 限流阈值(按 IP 哈希)
+const RL_CHALLENGE = { max: 15, windowMin: 10 };
+const RL_VERIFY = { max: 30, windowMin: 10 };
+
+export type TrackSample = { t: number; x: number };
+
+// 复用 captcha_challenges 表:answer_x 存缺口位置,extra 存限流指纹。
+// 限流走独立小表(内存实现即可——单实例部署,重启清零可接受)。
+const rateLimitBuckets = new Map();
+
+function rateLimit(key: string, max: number, windowMin: number): boolean {
+ const now = Date.now();
+ const windowMs = windowMin * 60_000;
+ const arr = (rateLimitBuckets.get(key) ?? []).filter((t) => now - t < windowMs);
+ if (arr.length >= max) {
+ rateLimitBuckets.set(key, arr);
+ return false;
+ }
+ arr.push(now);
+ rateLimitBuckets.set(key, arr);
+ return true;
+}
+
+export function clientFingerprint(req: Request): string {
+ const ip =
+ req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
+ req.headers.get("x-real-ip") ||
+ "local";
+ // 只存哈希,不落原始 IP(隐私 + 表里不留 PII)
+ return crypto.createHash("sha256").update(ip).digest("hex").slice(0, 24);
+}
+
+export function createCaptchaChallenge(req: Request): {
+ ok: true;
+ challengeId: number;
+ bg: string;
+ piece: string;
+} | { ok: false; error: string } {
+ const fp = clientFingerprint(req);
+ if (!rateLimit(`new:${fp}`, RL_CHALLENGE.max, RL_CHALLENGE.windowMin)) {
+ return { ok: false, error: "尝试过于频繁,请稍后再试" };
+ }
+
+ const answerX = 60 + crypto.randomInt(0, 233); // 60..292(400 宽画布)
const token = crypto.randomBytes(24).toString("hex");
db.prepare(
`INSERT INTO captcha_challenges (token, answer_x, expires_at)
VALUES (?, ?, datetime('now', '+${CHALLENGE_TTL_MIN} minutes'))`
- ).run(token, puzzleX);
+ ).run(token, answerX);
const row = db
.prepare("SELECT id FROM captcha_challenges WHERE token = ?")
.get(token) as { id: number };
db.prepare("DELETE FROM captcha_challenges WHERE expires_at < datetime('now')").run();
- return { id: row.id, puzzleX, trackWidth: 500, token };
+
+ const { bg, piece } = renderCaptchaImages(answerX);
+ return { ok: true, challengeId: row.id, bg, piece };
}
+/**
+ * 行为校验 + 位置校验。通过后签发一次性 submitToken。
+ */
export function verifyCaptcha(
- token: string,
- answerX: number
+ req: Request,
+ challengeId: number,
+ x: number,
+ track: TrackSample[]
): { ok: true; submitToken: string } | { ok: false; error: string } {
+ const fp = clientFingerprint(req);
+ if (!rateLimit(`verify:${fp}`, RL_VERIFY.max, RL_VERIFY.windowMin)) {
+ return { ok: false, error: "尝试过于频繁,请稍后再试" };
+ }
+
+ // 轨迹基础校验
+ if (!Array.isArray(track) || track.length < 6) {
+ return { ok: false, error: "验证失败,请重试" };
+ }
+ const t0 = track[0].t;
+ const tN = track[track.length - 1].t;
+ const duration = tN - t0;
+ if (duration < 1200) {
+ return { ok: false, error: "验证失败,请重试" };
+ }
+ if (duration > 10_000) {
+ return { ok: false, error: "验证已过期,请刷新重试" };
+ }
+ // 时间戳必须单调递增且合理(防止伪造负值/乱序)
+ for (let i = 1; i < track.length; i++) {
+ if (track[i].t < track[i - 1].t) {
+ return { ok: false, error: "验证失败,请重试" };
+ }
+ }
+ // 速度波动:真人拖动有加减速,匀速直线 = 脚本特征
+ let maxSpeed = 0;
+ let totalDist = 0;
+ for (let i = 1; i < track.length; i++) {
+ const dt = track[i].t - track[i - 1].t;
+ const dx = Math.abs(track[i].x - track[i - 1].x);
+ if (dt <= 0) return { ok: false, error: "验证失败,请重试" };
+ const speed = dx / dt;
+ totalDist += dx;
+ if (speed > maxSpeed) maxSpeed = speed;
+ }
+ if (totalDist <= 0) return { ok: false, error: "验证失败,请重试" };
+ if (maxSpeed < (totalDist / duration) * 1.8) {
+ return { ok: false, error: "验证失败,请重试" };
+ }
+
const row = db
.prepare(
- "SELECT id, answer_x, consumed, attempts, expires_at FROM captcha_challenges WHERE token = ?"
+ "SELECT id, answer_x, consumed, attempts, expires_at, token FROM captcha_challenges WHERE id = ?"
)
- .get(token) as
- | { id: number; answer_x: number; consumed: number; attempts: number; expires_at: string }
+ .get(challengeId) as
+ | { id: number; answer_x: number; consumed: number; attempts: number; expires_at: string; token: string }
| undefined;
- if (!row || row.consumed) return { ok: false, error: "验证已失效,请刷新重试" };
+ if (!row || row.consumed || row.token.startsWith("submit:")) {
+ return { ok: false, error: "验证已失效,请刷新重试" };
+ }
if (new Date(row.expires_at + "Z") < new Date()) {
return { ok: false, error: "验证已过期,请刷新重试" };
}
@@ -54,16 +152,26 @@ export function verifyCaptcha(
return { ok: false, error: "尝试次数过多,请刷新重试" };
}
- const delta = Math.abs(answerX - row.answer_x);
- if (delta > CAPTCHA_TOLERANCE) {
+ if (Math.abs(x - row.answer_x) > CAPTCHA_TOLERANCE) {
db.prepare(
"UPDATE captcha_challenges SET attempts = attempts + 1 WHERE id = ?"
).run(row.id);
return { ok: false, error: "位置不对,再试一次" };
}
+ // 末样本应接近提交的 x(轨迹与答案一致性)
+ const lastSample = track[track.length - 1].x;
+ if (Math.abs(lastSample - x) > 14) {
+ db.prepare(
+ "UPDATE captcha_challenges SET attempts = attempts + 1 WHERE id = ?"
+ ).run(row.id);
+ return { ok: false, error: "验证失败,请重试" };
+ }
+
db.prepare("UPDATE captcha_challenges SET consumed = 1 WHERE id = ?").run(row.id);
const submitToken = crypto.randomBytes(24).toString("hex");
+ // 令牌签发:重置 consumed(上面 verify 成功时置 1 了),单次消费由
+ // consumeSubmitToken 在提交接口完成。
db.prepare(
`UPDATE captcha_challenges SET token = ?, consumed = 0, expires_at = datetime('now', '+${SUBMIT_TOKEN_TTL_MIN} minutes') WHERE id = ?`
).run(`submit:${submitToken}`, row.id);
diff --git a/lib/captchaImage.ts b/lib/captchaImage.ts
new file mode 100644
index 0000000..c2cc9dc
--- /dev/null
+++ b/lib/captchaImage.ts
@@ -0,0 +1,99 @@
+/**
+ * 滑块验证码绘图 — 服务端把「缺口位置」直接烘进图片里。
+ *
+ * 关键安全点:答案坐标不出服务端。客户端只拿到两张图:
+ * - bg:点阵背景,缺口槽已画在秘密位置(深色凹陷 + lime 描边)
+ * - piece:拼块(全局点阵在 answerX 处的裁片 + lime 描边)
+ *
+ * 每个挑战的点阵相位(ox/oy)随机——拼块的纹理相位与缺口位置绑定,
+ * 但相位本身是秘密,脚本不做人眼/模板识别就无法反推缺口位置。
+ */
+import crypto from "node:crypto";
+import { encodePng } from "@/lib/pngEncoder";
+
+export const CAPTCHA_W = 400;
+export const CAPTCHA_H = 140;
+export const PIECE_W = 48;
+
+const INK: [number, number, number] = [16, 18, 14];
+const HOLE: [number, number, number] = [7, 8, 6];
+const DOT: [number, number, number] = [56, 62, 52];
+const LIME: [number, number, number] = [192, 254, 4];
+
+type RGB = [number, number, number];
+
+class Canvas {
+ data: Uint8Array;
+ constructor(public w: number, public h: number, bg: RGB) {
+ this.data = new Uint8Array(w * h * 3);
+ for (let i = 0; i < w * h; i++) {
+ this.data[i * 3] = bg[0];
+ this.data[i * 3 + 1] = bg[1];
+ this.data[i * 3 + 2] = bg[2];
+ }
+ }
+ px(x: number, y: number, [r, g, b]: RGB) {
+ if (x < 0 || y < 0 || x >= this.w || y >= this.h) return;
+ const i = (y * this.w + x) * 3;
+ this.data[i] = r;
+ this.data[i + 1] = g;
+ this.data[i + 2] = b;
+ }
+ rect(x0: number, y0: number, w: number, h: number, c: RGB) {
+ for (let y = y0; y < y0 + h; y++) {
+ for (let x = x0; x < x0 + w; x++) this.px(x, y, c);
+ }
+ }
+}
+
+export function renderCaptchaImages(answerX: number): {
+ bg: string;
+ piece: string;
+} {
+ const spacing = 14;
+ const ox = crypto.randomInt(0, spacing);
+ const oy = crypto.randomInt(0, spacing);
+ const isDot = (x: number, y: number) =>
+ (x + ox) % spacing === 0 && (y + oy) % spacing === 0;
+
+ // 背景:点阵 + 缺口槽
+ const bg = new Canvas(CAPTCHA_W, CAPTCHA_H, INK);
+ for (let y = 0; y < CAPTCHA_H; y++) {
+ for (let x = 0; x < CAPTCHA_W; x++) {
+ if (isDot(x, y)) bg.px(x, y, DOT);
+ }
+ }
+ bg.rect(answerX, 2, PIECE_W, CAPTCHA_H - 4, HOLE);
+ // 槽描边(lime):左右 2px 立柱 + 上下横线
+ bg.rect(answerX - 3, 0, 2, CAPTCHA_H, LIME);
+ bg.rect(answerX + PIECE_W + 1, 0, 2, CAPTCHA_H, LIME);
+ bg.rect(answerX - 1, 0, PIECE_W + 2, 2, LIME);
+ bg.rect(answerX - 1, CAPTCHA_H - 2, PIECE_W + 2, 2, LIME);
+
+ // 拼块:全局点阵在 answerX 处的裁片(相位与缺口对齐)+ lime 描边
+ const piece = new Canvas(PIECE_W, CAPTCHA_H, INK);
+ for (let y = 0; y < CAPTCHA_H; y++) {
+ for (let i = 0; i < PIECE_W; i++) {
+ if (isDot(answerX + i, y)) piece.px(i, y, DOT);
+ }
+ }
+ piece.rect(0, 0, 2, CAPTCHA_H, LIME);
+ piece.rect(PIECE_W - 2, 0, 2, CAPTCHA_H, LIME);
+ piece.rect(0, 0, PIECE_W, 2, LIME);
+ piece.rect(0, CAPTCHA_H - 2, PIECE_W, 2, LIME);
+ // 中缝箭头提示(可拖拽的视觉 affordance)
+ for (let d = 0; d < 8; d++) {
+ piece.px(PIECE_W / 2 - 6 + d, CAPTCHA_H / 2 - d, LIME);
+ piece.px(PIECE_W / 2 - 6 + d, CAPTCHA_H / 2 + d, LIME);
+ }
+
+ return {
+ bg: `data:image/png;base64,${encodePng(CAPTCHA_W, CAPTCHA_H, bg.data).toString("base64")}`,
+ piece: `data:image/png;base64,${encodePng(PIECE_W, CAPTCHA_H, piece.data).toString("base64")}`,
+ };
+}
+
+/** 缺口随机位置(留出描边与拖拽起点空间)。 */
+export function randomAnswerX(): number {
+ return crypto.randomInt(60, CAPTCHA_W - 60 - PIECE_W + 1);
+}
diff --git a/lib/pngEncoder.ts b/lib/pngEncoder.ts
new file mode 100644
index 0000000..d9473a9
--- /dev/null
+++ b/lib/pngEncoder.ts
@@ -0,0 +1,62 @@
+/**
+ * 极简 PNG 编码器(RGB 8-bit,无压缩滤波)— 验证码图片专用。
+ * node:zlib + 手写 CRC32,零依赖;输出为标准 PNG。
+ */
+import zlib from "node:zlib";
+
+const CRC_TABLE = (() => {
+ const table = new Uint32Array(256);
+ for (let n = 0; n < 256; n++) {
+ let c = n;
+ for (let k = 0; k < 8; k++) {
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ }
+ table[n] = c >>> 0;
+ }
+ return table;
+})();
+
+function crc32(buf: Buffer): number {
+ let c = 0xffffffff;
+ for (let i = 0; i < buf.length; i++) {
+ c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
+ }
+ return (c ^ 0xffffffff) >>> 0;
+}
+
+function chunk(type: string, data: Buffer): Buffer {
+ const len = Buffer.alloc(4);
+ len.writeUInt32BE(data.length, 0);
+ const typeBuf = Buffer.from(type, "ascii");
+ const crc = Buffer.alloc(4);
+ crc.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);
+ return Buffer.concat([len, typeBuf, data, crc]);
+}
+
+export function encodePng(
+ width: number,
+ height: number,
+ rgb: Uint8Array
+): Buffer {
+ const rowBytes = width * 3;
+ const raw = Buffer.alloc((rowBytes + 1) * height);
+ for (let y = 0; y < height; y++) {
+ raw[y * (rowBytes + 1)] = 0; // filter: none
+ raw.set(
+ rgb.subarray(y * rowBytes, (y + 1) * rowBytes),
+ y * (rowBytes + 1) + 1
+ );
+ }
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(width, 0);
+ ihdr.writeUInt32BE(height, 4);
+ ihdr[8] = 8; // bit depth
+ ihdr[9] = 2; // color type: truecolor RGB
+ const sig = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+ return Buffer.concat([
+ sig,
+ chunk("IHDR", ihdr),
+ chunk("IDAT", zlib.deflateSync(raw, { level: 9 })),
+ chunk("IEND", Buffer.alloc(0)),
+ ]);
+}