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:
@@ -2,7 +2,6 @@ import SmoothScroller from "@/components/dom/SmoothScroller";
|
|||||||
import Header from "@/components/dom/Header";
|
import Header from "@/components/dom/Header";
|
||||||
import BackgroundGrid from "@/components/dom/BackgroundGrid";
|
import BackgroundGrid from "@/components/dom/BackgroundGrid";
|
||||||
import CustomScrollbar from "@/components/dom/CustomScrollbar";
|
import CustomScrollbar from "@/components/dom/CustomScrollbar";
|
||||||
import LoadingOverlay from "@/components/dom/LoadingOverlay";
|
|
||||||
import { HeroScene } from "@/components/canvas/HeroScene";
|
import { HeroScene } from "@/components/canvas/HeroScene";
|
||||||
import { PasscodeAccessProvider } from "@/components/dom/PasscodeAccess";
|
import { PasscodeAccessProvider } from "@/components/dom/PasscodeAccess";
|
||||||
import { FullscreenTransitionProvider } from "@/lib/routeTransition";
|
import { FullscreenTransitionProvider } from "@/lib/routeTransition";
|
||||||
@@ -84,7 +83,6 @@ export default async function SiteLayout({
|
|||||||
{children}
|
{children}
|
||||||
<CustomScrollbar />
|
<CustomScrollbar />
|
||||||
<RouteTransitionOverlay />
|
<RouteTransitionOverlay />
|
||||||
<LoadingOverlay />
|
|
||||||
</FullscreenTransitionProvider>
|
</FullscreenTransitionProvider>
|
||||||
</PasscodeAccessProvider>
|
</PasscodeAccessProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -43,6 +43,9 @@ export default function ServicesClient({
|
|||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [contact, setContact] = useState("");
|
const [contact, setContact] = useState("");
|
||||||
const [message, setMessage] = useState("");
|
const [message, setMessage] = useState("");
|
||||||
|
// 蜜罐:人类不可见(CSS 藏 + tabIndex=-1 + autocomplete 关闭),
|
||||||
|
// 群发机器人会把它当普通字段填上 —— 提交接口静默丢弃。
|
||||||
|
const [honeypot, setHoneypot] = useState("");
|
||||||
const [captchaOpen, setCaptchaOpen] = useState(false);
|
const [captchaOpen, setCaptchaOpen] = useState(false);
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -72,6 +75,7 @@ export default function ServicesClient({
|
|||||||
serviceSlug: selected.slug,
|
serviceSlug: selected.slug,
|
||||||
serviceTitle: selected.title,
|
serviceTitle: selected.title,
|
||||||
message: message.trim(),
|
message: message.trim(),
|
||||||
|
website: honeypot,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
const data = (await res.json()) as { id?: number; error?: string };
|
const data = (await res.json()) as { id?: number; error?: string };
|
||||||
@@ -89,7 +93,7 @@ export default function ServicesClient({
|
|||||||
setSubmitting(false);
|
setSubmitting(false);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[selected, name, contact, message]
|
[selected, name, contact, message, honeypot]
|
||||||
);
|
);
|
||||||
|
|
||||||
if (doneId !== null) {
|
if (doneId !== null) {
|
||||||
@@ -164,8 +168,10 @@ export default function ServicesClient({
|
|||||||
</p>
|
</p>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
{/* 服务菜单 */}
|
{/* 双栏:左服务菜单 / 右表单(lg+ 并排,移动端上下堆叠) */}
|
||||||
<section className="mt-12" aria-label="服务列表">
|
<div className="mt-12 grid grid-cols-1 lg:grid-cols-12 gap-10 lg:gap-8 items-start">
|
||||||
|
{/* 服务菜单(左栏) */}
|
||||||
|
<section className="lg:col-span-6 xl:col-span-7" aria-label="服务列表">
|
||||||
{services.length === 0 ? (
|
{services.length === 0 ? (
|
||||||
<p className="font-mono-2 text-sm text-l2 border border-dashed border-line p-8 text-center">
|
<p className="font-mono-2 text-sm text-l2 border border-dashed border-line p-8 text-center">
|
||||||
服务清单整理中——有需要可直接写邮件给我。
|
服务清单整理中——有需要可直接写邮件给我。
|
||||||
@@ -221,8 +227,11 @@ export default function ServicesClient({
|
|||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{/* 留言表单 */}
|
{/* 留言表单(右栏,lg+ sticky 跟随) */}
|
||||||
<section className="mt-12 flex flex-col gap-5" aria-label="咨询表单">
|
<section
|
||||||
|
className="lg:col-span-6 xl:col-span-5 flex flex-col gap-5 lg:sticky lg:top-24"
|
||||||
|
aria-label="咨询表单"
|
||||||
|
>
|
||||||
<p className="font-mono-2 text-xs text-l3 uppercase tracking-widest">
|
<p className="font-mono-2 text-xs text-l3 uppercase tracking-widest">
|
||||||
{selected ? `咨询:${selected.title}` : "留言"}
|
{selected ? `咨询:${selected.title}` : "留言"}
|
||||||
</p>
|
</p>
|
||||||
@@ -273,6 +282,20 @@ export default function ServicesClient({
|
|||||||
<p className="mt-1.5 font-mono-2 text-xs text-l3">{submitNote}</p>
|
<p className="mt-1.5 font-mono-2 text-xs text-l3">{submitNote}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* 蜜罐字段 — 人类不可见;机器人填了就被服务端静默丢弃 */}
|
||||||
|
<div aria-hidden="true" className="absolute left-[-9999px] top-auto h-px w-px overflow-hidden">
|
||||||
|
<label htmlFor="svc-website">网站(勿填)</label>
|
||||||
|
<input
|
||||||
|
id="svc-website"
|
||||||
|
type="text"
|
||||||
|
name="website"
|
||||||
|
tabIndex={-1}
|
||||||
|
autoComplete="off"
|
||||||
|
value={honeypot}
|
||||||
|
onChange={(e) => setHoneypot(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<p className="border-l-2 border-selection pl-2 text-sm text-l1" role="alert">
|
<p className="border-l-2 border-selection pl-2 text-sm text-l1" role="alert">
|
||||||
{error}
|
{error}
|
||||||
@@ -288,6 +311,7 @@ export default function ServicesClient({
|
|||||||
{submitting ? "提交中…" : "提交(需完成滑块验证)"}
|
{submitting ? "提交中…" : "提交(需完成滑块验证)"}
|
||||||
</button>
|
</button>
|
||||||
</section>
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
<SliderCaptcha
|
<SliderCaptcha
|
||||||
open={captchaOpen}
|
open={captchaOpen}
|
||||||
|
|||||||
@@ -1,10 +1,21 @@
|
|||||||
/** /api/captcha/new — 生成滑块挑战(公开)。 */
|
/**
|
||||||
|
* /api/captcha/new — 生成滑块挑战(公开)。
|
||||||
|
* v2:返回烘好缺口的服务端 PNG(bg + piece),答案坐标不出服务端。
|
||||||
|
* 限流:15 次 / 10 分钟 / IP。
|
||||||
|
*/
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { createCaptchaChallenge } from "@/lib/captcha";
|
import { createCaptchaChallenge } from "@/lib/captcha";
|
||||||
|
|
||||||
export const runtime = "nodejs";
|
export const runtime = "nodejs";
|
||||||
|
|
||||||
export async function POST() {
|
export async function POST(req: Request) {
|
||||||
const challenge = createCaptchaChallenge();
|
const result = createCaptchaChallenge(req);
|
||||||
return NextResponse.json(challenge);
|
if (!result.ok) {
|
||||||
|
return NextResponse.json({ error: result.error }, { status: 429 });
|
||||||
|
}
|
||||||
|
return NextResponse.json({
|
||||||
|
challengeId: result.challengeId,
|
||||||
|
bg: result.bg,
|
||||||
|
piece: result.piece,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,29 @@
|
|||||||
/** /api/captcha/verify — 校验滑块位置,通过则签发一次性提交令牌。 */
|
/**
|
||||||
|
* /api/captcha/verify — 校验滑块(v2:行为轨迹 + 位置 + 限流)。
|
||||||
|
* 通过后签发一次性提交令牌(5 分钟、单次消费)。
|
||||||
|
*/
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { verifyCaptcha } from "@/lib/captcha";
|
import { verifyCaptcha, type TrackSample } from "@/lib/captcha";
|
||||||
|
|
||||||
export const runtime = "nodejs";
|
export const runtime = "nodejs";
|
||||||
|
|
||||||
export async function POST(req: Request) {
|
export async function POST(req: Request) {
|
||||||
let body: { token?: string; x?: number };
|
let body: { challengeId?: number; x?: number; track?: TrackSample[] };
|
||||||
try {
|
try {
|
||||||
body = await req.json();
|
body = await req.json();
|
||||||
} catch {
|
} catch {
|
||||||
return NextResponse.json({ error: "请求格式错误" }, { status: 400 });
|
return NextResponse.json({ error: "请求格式错误" }, { status: 400 });
|
||||||
}
|
}
|
||||||
const token = String(body.token ?? "");
|
const challengeId = Number(body.challengeId);
|
||||||
const x = Number(body.x);
|
const x = Number(body.x);
|
||||||
if (!token || !Number.isFinite(x)) {
|
const track = body.track;
|
||||||
|
if (!Number.isInteger(challengeId) || !Number.isFinite(x) || !Array.isArray(track)) {
|
||||||
return NextResponse.json({ error: "参数错误" }, { status: 400 });
|
return NextResponse.json({ error: "参数错误" }, { status: 400 });
|
||||||
}
|
}
|
||||||
const result = verifyCaptcha(token, Math.round(x));
|
if (x < -10 || x > 500) {
|
||||||
|
return NextResponse.json({ error: "参数错误" }, { status: 400 });
|
||||||
|
}
|
||||||
|
const result = verifyCaptcha(req, challengeId, Math.round(x), track);
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
return NextResponse.json({ error: result.error }, { status: 400 });
|
return NextResponse.json({ error: result.error }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
* 状态记录在 inquiries.email_sent / email_error,后台留言箱可见)。
|
* 状态记录在 inquiries.email_sent / email_error,后台留言箱可见)。
|
||||||
*/
|
*/
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { consumeSubmitToken } from "@/lib/captcha";
|
import { consumeSubmitToken, clientFingerprint } from "@/lib/captcha";
|
||||||
import { createInquiry, markInquiryEmail } from "@/lib/siteConfig";
|
import { createInquiry, markInquiryEmail } from "@/lib/siteConfig";
|
||||||
import { sendInquiryNotification } from "@/lib/mailer";
|
import { sendInquiryNotification } from "@/lib/mailer";
|
||||||
|
|
||||||
@@ -15,6 +15,21 @@ const NAME_MAX = 40;
|
|||||||
const CONTACT_MAX = 80;
|
const CONTACT_MAX = 80;
|
||||||
const MESSAGE_MAX = 2000;
|
const MESSAGE_MAX = 2000;
|
||||||
|
|
||||||
|
// 提交限流桶(单实例内存实现,重启清零可接受)。
|
||||||
|
const submitBuckets = new Map<string, number[]>();
|
||||||
|
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) {
|
export async function POST(req: Request) {
|
||||||
let body: {
|
let body: {
|
||||||
submitToken?: string;
|
submitToken?: string;
|
||||||
@@ -23,6 +38,8 @@ export async function POST(req: Request) {
|
|||||||
serviceSlug?: string;
|
serviceSlug?: string;
|
||||||
serviceTitle?: string;
|
serviceTitle?: string;
|
||||||
message?: string;
|
message?: string;
|
||||||
|
/** 蜜罐:人类不可见不填写;机器人会全字段填充 */
|
||||||
|
website?: string;
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
body = await req.json();
|
body = await req.json();
|
||||||
@@ -30,6 +47,21 @@ export async function POST(req: Request) {
|
|||||||
return NextResponse.json({ error: "请求格式错误" }, { status: 400 });
|
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 name = String(body.name ?? "").trim();
|
||||||
const contact = String(body.contact ?? "").trim();
|
const contact = String(body.contact ?? "").trim();
|
||||||
const message = String(body.message ?? "").trim();
|
const message = String(body.message ?? "").trim();
|
||||||
|
|||||||
@@ -416,31 +416,39 @@ export function LoadingCurtain({
|
|||||||
onComplete?: (open: boolean) => void;
|
onComplete?: (open: boolean) => void;
|
||||||
}) {
|
}) {
|
||||||
const materialRef = useRef<any>(null);
|
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 (
|
return (
|
||||||
<Canvas
|
<div className="fixed inset-0 z-[60] pointer-events-none">
|
||||||
dpr={[1, 2]}
|
<Canvas
|
||||||
frameloop="demand"
|
dpr={[1, 2]}
|
||||||
gl={{
|
frameloop="demand"
|
||||||
alpha: true,
|
style={{ pointerEvents: "none" }}
|
||||||
antialias: false,
|
gl={{
|
||||||
premultipliedAlpha: true,
|
alpha: true,
|
||||||
depth: false,
|
antialias: false,
|
||||||
stencil: false,
|
premultipliedAlpha: true,
|
||||||
powerPreference: "high-performance",
|
depth: false,
|
||||||
preserveDrawingBuffer: false,
|
stencil: false,
|
||||||
}}
|
powerPreference: "high-performance",
|
||||||
className="fixed inset-0 z-[60] pointer-events-none"
|
preserveDrawingBuffer: false,
|
||||||
>
|
}}
|
||||||
<RadialHoleMask
|
>
|
||||||
open={open}
|
<RadialHoleMask
|
||||||
duration={duration}
|
open={open}
|
||||||
initialProgress={initialProgress}
|
duration={duration}
|
||||||
resetKey={resetKey}
|
initialProgress={initialProgress}
|
||||||
onComplete={onComplete}
|
resetKey={resetKey}
|
||||||
materialRef={materialRef}
|
onComplete={onComplete}
|
||||||
/>
|
materialRef={materialRef}
|
||||||
<DotsPost materialRef={materialRef} />
|
/>
|
||||||
</Canvas>
|
<DotsPost materialRef={materialRef} />
|
||||||
|
</Canvas>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,42 +1,28 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState, useSyncExternalStore } from "react";
|
import { useEffect, useSyncExternalStore } from "react";
|
||||||
import { usePathname } from "next/navigation";
|
|
||||||
import { loadingBus } from "@/lib/loadingBus";
|
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). */
|
/** Stable server snapshot (must be cached — a fresh object would loop). */
|
||||||
const SERVER_SNAPSHOT = { progress: 0, ready: false };
|
const SERVER_SNAPSHOT = { progress: 0, ready: false };
|
||||||
|
|
||||||
function useHeavyLoad() {
|
export function useHeavyLoad() {
|
||||||
return useSyncExternalStore(
|
return useSyncExternalStore(
|
||||||
loadingBus.subscribe,
|
loadingBusSubscribe,
|
||||||
loadingBus.getSnapshot,
|
loadingBusGetSnapshot,
|
||||||
() => SERVER_SNAPSHOT
|
() => SERVER_SNAPSHOT
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function useFontsReady() {
|
const loadingBusSubscribe = loadingBus.subscribe;
|
||||||
const [fontsReady, setFontsReady] = useState(false);
|
const loadingBusGetSnapshot = loadingBus.getSnapshot;
|
||||||
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));
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Heavy-asset readiness for the camera intro dolly (original cV's `p`:
|
* Heavy-asset readiness for the camera intro dolly (original cV's `p`:
|
||||||
@@ -53,91 +39,3 @@ export function useAppReady(): boolean {
|
|||||||
|
|
||||||
return heavy.ready;
|
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;
|
|
||||||
|
|||||||
@@ -2,107 +2,258 @@
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* RouteTransitionOverlay — 1:1 port of the original orchestrator (chunk
|
* RouteTransitionOverlay — 1:1 port of the original orchestrator (chunk
|
||||||
* 3c6cc5b2fcccdee5.js `function M`, module 34841), simplified to the pixel
|
* 3c6cc5b2fcccdee5.js `function M`, module 34841). ONE unified pinhole
|
||||||
* wipe without the WebGL mask material:
|
* curtain drives BOTH the first-load entry and every route transition:
|
||||||
*
|
*
|
||||||
* startNavigation(href)
|
* startNavigation(href)
|
||||||
* → phase "cover" : b1-colored fixed layer wipes IN over the page
|
* → mode "route", phase "cover" : curtain CLOSES to the pinhole
|
||||||
* (0.8s, cubic-bezier(0.66, 0, 0.01, 1)); on complete → router.push
|
* (0.8s customCubic radial hole + masked dots, same canvas as the
|
||||||
* (or replace) to the target href.
|
* loading curtain); on complete → router.push/replace + phase "wait".
|
||||||
* → phase "wait" : new page mounts; heavy assets may still load.
|
* → phase "wait" : new page mounts. Reveal waits for
|
||||||
* → phase "reveal" : layer wipes OUT (same easing), then → idle and
|
* the TARGET page's routeLoading gate (only "/" has one:
|
||||||
* the overlay unmounts; scramble lines re-enabled 100ms in.
|
* 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
|
* The linear-DOM-wipe overlay this replaces did NOT match the original —
|
||||||
* turning into a blank sheet — the original achieves the same look via the
|
* the original never wipes; it pinholes through the masked-dots curtain.
|
||||||
* WebGL mask + grid colors.
|
*
|
||||||
|
* 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 { 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 Mode = "idle" | "entry" | "route";
|
||||||
|
type Phase = "wait" | "cover" | "reveal";
|
||||||
|
type Transition = { mode: Mode; phase: Phase };
|
||||||
|
|
||||||
const DURATION_MS = 800;
|
/** Original `y` (defaults) + `x` ("/" only enables both gates). */
|
||||||
const EASING = "cubic-bezier(0.66, 0, 0.01, 1)";
|
type PathLoadingConfig = {
|
||||||
const BG = "var(--color-b1)";
|
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() {
|
export default function RouteTransitionOverlay() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const { targetHref, navigationReplace, clearNavigation, setAllowScrambleLines } =
|
const {
|
||||||
useRouteTransitionController();
|
targetHref,
|
||||||
|
navigationReplace,
|
||||||
|
clearNavigation,
|
||||||
|
readyToLoadHeavy,
|
||||||
|
setReadyToLoadHeavy,
|
||||||
|
heavyLoadProgress,
|
||||||
|
setHeavyLoadProgress,
|
||||||
|
setAllowScrambleLines,
|
||||||
|
} = useRouteTransitionController();
|
||||||
|
const { menuOpen } = useFullscreenTransitionController();
|
||||||
|
const fontsReady = useFontsReady();
|
||||||
|
|
||||||
const routeFrom = useRef<{ path: string | null; coverDone: boolean }>({
|
const routeFrom = useRef<{ path: string | null; coverDone: boolean }>({
|
||||||
path: null,
|
path: null,
|
||||||
coverDone: false,
|
coverDone: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
const [mode, setMode] = useState<Mode>("idle");
|
const [transition, setTransition] = useState<Transition>({
|
||||||
const [phase, setPhase] = useState<Phase>("wait");
|
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>(() => {});
|
const { mode, phase } = transition;
|
||||||
navigateRef.current = () => {
|
const fromConfig = useMemo(() => pathConfig(pathname), [pathname]);
|
||||||
if (mode === "route" && phase === "cover") {
|
const targetPath = useMemo(() => targetPathname(targetHref), [targetHref]);
|
||||||
routeFrom.current.coverDone = true;
|
const targetConfig = useMemo(
|
||||||
setAllowScrambleLines(false);
|
() => pathConfig(targetPath ?? pathname),
|
||||||
if (targetHref) {
|
[targetPath, pathname]
|
||||||
if (navigationReplace) router.replace(targetHref);
|
);
|
||||||
else router.push(targetHref);
|
|
||||||
}
|
|
||||||
setPhase("wait");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const targetPath = useMemo(() => {
|
// Heavy-load bridge: the provider's readyToLoadHeavy/heavyLoadProgress is
|
||||||
if (!targetHref) return null;
|
// fed by the HOME canvas in the original (cV: models + image layers all
|
||||||
if (targetHref.startsWith("/")) {
|
// loaded). Our equivalent is loadingBus — keep the provider in sync so
|
||||||
const [p] = targetHref.split("?");
|
// the gates read exactly like the original.
|
||||||
return p || "/";
|
useEffect(() => {
|
||||||
}
|
const sync = () => {
|
||||||
try {
|
const snap = loadingBus.getSnapshot();
|
||||||
return new URL(targetHref, window.location.origin).pathname || "/";
|
setHeavyLoadProgress(snap.progress);
|
||||||
} catch {
|
if (snap.ready) setReadyToLoadHeavy(true);
|
||||||
return null;
|
};
|
||||||
}
|
sync();
|
||||||
}, [targetHref]);
|
const un = loadingBus.subscribe(sync);
|
||||||
|
return un;
|
||||||
|
}, [setHeavyLoadProgress, setReadyToLoadHeavy]);
|
||||||
|
|
||||||
// Intent → start cover.
|
// Intent → cover (original effect 1).
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (targetHref && mode === "idle") {
|
if (targetHref && mode === "idle") {
|
||||||
routeFrom.current.path = pathname;
|
routeFrom.current = { path: pathname, coverDone: false };
|
||||||
routeFrom.current.coverDone = false;
|
setTransition({ mode: "route", phase: "cover" });
|
||||||
setMode("route");
|
|
||||||
setPhase("cover");
|
|
||||||
}
|
}
|
||||||
}, [targetHref, mode, pathname]);
|
}, [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(() => {
|
useEffect(() => {
|
||||||
if (
|
if (
|
||||||
mode === "route" &&
|
mode === "route" &&
|
||||||
phase === "wait" &&
|
phase === "wait" &&
|
||||||
routeFrom.current.coverDone &&
|
routeFrom.current.coverDone &&
|
||||||
routeFrom.current.path &&
|
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.
|
// Progress bar: 100% → hold 250ms → fade → 250ms → remove (original P/z
|
||||||
const onRevealComplete = () => {
|
// timers; entry gate `_` only).
|
||||||
if (mode !== "idle" && phase === "reveal") {
|
const heavyPct = clamp(heavyLoadProgress, 0, 100);
|
||||||
setMode("idle");
|
const progress = fromConfig.entryLoading.enabled
|
||||||
clearNavigation();
|
? clamp(50 * +fontsReady + heavyPct / 2, 0, 100)
|
||||||
routeFrom.current.path = null;
|
: heavyPct;
|
||||||
routeFrom.current.coverDone = false;
|
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
|
const onComplete = useCallback(
|
||||||
// a reveal starts).
|
(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(() => {
|
useEffect(() => {
|
||||||
if (mode === "idle") {
|
if (mode === "idle") {
|
||||||
setAllowScrambleLines(true);
|
setAllowScrambleLines(true);
|
||||||
@@ -113,52 +264,61 @@ export default function RouteTransitionOverlay() {
|
|||||||
return () => window.clearTimeout(t);
|
return () => window.clearTimeout(t);
|
||||||
}, [mode, phase, setAllowScrambleLines]);
|
}, [mode, phase, setAllowScrambleLines]);
|
||||||
|
|
||||||
const overlayVisible = mode !== "idle" && phase !== "wait";
|
// open prop (original O): idle → menuOpen; else closed until reveal.
|
||||||
const wipeIn = phase === "cover";
|
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 (
|
return (
|
||||||
<div
|
<div
|
||||||
aria-hidden={!overlayVisible}
|
aria-hidden="true"
|
||||||
style={{
|
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 ${
|
||||||
position: "fixed",
|
fading ? "opacity-0" : "opacity-100"
|
||||||
inset: 0,
|
}`}
|
||||||
zIndex: 60,
|
style={{ transition: "opacity 250ms cubic-bezier(0.25, 1, 0.5, 1)" }}
|
||||||
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();
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<style>{`@keyframes route-wipe { from { clip-path: inset(0 0 100% 0); } to { clip-path: inset(0 0 0 0); } }`}</style>
|
<div className="relative h-1.5 w-full overflow-hidden rounded-full bg-l3">
|
||||||
{/* 16px checker texture (original pixelSize:16 maskCells) */}
|
<div
|
||||||
<div
|
className="absolute inset-y-0 left-0 rounded-full bg-l1"
|
||||||
className="absolute inset-0 pointer-events-none"
|
style={{
|
||||||
style={{
|
width: `${clamp(progress, 0, 100)}%`,
|
||||||
opacity: 0.05,
|
transition: "width 520ms cubic-bezier(0.22, 1, 0.36, 1)",
|
||||||
backgroundImage:
|
willChange: "width",
|
||||||
"repeating-conic-gradient(var(--color-l1) 0% 25%, transparent 0% 50%)",
|
}}
|
||||||
backgroundSize: "32px 32px",
|
/>
|
||||||
}}
|
</div>
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+173
-103
@@ -1,19 +1,21 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SliderCaptcha — 滑块拼图验证码(全屏居中弹层)。
|
* SliderCaptcha v2 — 图片化滑块验证(全屏居中弹层)。
|
||||||
*
|
*
|
||||||
* - 打开时向 /api/captcha/new 要 challenge:{ token, puzzleX }(缺口位置,
|
* 与 v1 的区别:
|
||||||
* 500 坐标系)。
|
* - 缺口位置由服务端烘进 PNG(bg 带缺口、piece 为裁片),JS 无答案,
|
||||||
* - 轨道点阵背景 + 缺口槽(虚线 lime 框);拖动滑块使图案连续对齐缺口。
|
* 脚本无法从响应反推位置。
|
||||||
* - 松手提交 { token, x } → 校验通过返回一次性 submitToken(5 分钟单次),
|
* - 拖动过程按指针事件采样轨迹(时间 + 横坐标),verify 时提交服务端
|
||||||
* 由父组件携带它提交咨询接口。
|
* 做行为校验(时长 / 匀速直线 / 末点一致性),瞬间拖动直接拒绝。
|
||||||
* - 校验失败抖动重置;challenge 失效自动换新。
|
* - verify 参数为 { challengeId, x, track };x 为 400 坐标系里的落点。
|
||||||
*/
|
*/
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
const COORD_SPACE = 500; // 服务器缺口坐标系宽度
|
const IMG_W = 400;
|
||||||
const PIECE_W = 48;
|
const PIECE_W = 48; // 与服务端 lib/captchaImage 的 PIECE_W 一致
|
||||||
|
|
||||||
|
type TrackSample = { t: number; x: number };
|
||||||
|
|
||||||
export default function SliderCaptcha({
|
export default function SliderCaptcha({
|
||||||
open,
|
open,
|
||||||
@@ -24,35 +26,70 @@ export default function SliderCaptcha({
|
|||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onVerified: (submitToken: string) => void;
|
onVerified: (submitToken: string) => void;
|
||||||
}) {
|
}) {
|
||||||
const [challenge, setChallenge] = useState<{
|
const [imgs, setImgs] = useState<{ bg: string; piece: string } | null>(null);
|
||||||
token: string;
|
const [challengeId, setChallengeId] = useState<number | null>(null);
|
||||||
puzzleX: number;
|
const [trackPx, setTrackPx] = useState(360);
|
||||||
} | null>(null);
|
|
||||||
const [dragX, setDragX] = useState(0);
|
const [dragX, setDragX] = useState(0);
|
||||||
const [status, setStatus] = useState<"idle" | "dragging" | "checking" | "error">(
|
const [status, setStatus] = useState<"idle" | "dragging" | "checking" | "error">(
|
||||||
"idle"
|
"idle"
|
||||||
);
|
);
|
||||||
const [error, setError] = useState<string | null>(null);
|
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 [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(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
(async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/captcha/new", { method: "POST" });
|
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 (cancelled) return;
|
||||||
if (data.token && typeof data.puzzleX === "number") {
|
if (data.challengeId && data.bg && data.piece) {
|
||||||
setChallenge({ token: data.token, puzzleX: data.puzzleX });
|
setImgs({ bg: data.bg, piece: data.piece });
|
||||||
|
setChallengeId(data.challengeId);
|
||||||
} else {
|
} else {
|
||||||
setError("验证码加载失败");
|
setError(data.error ?? "验证码加载失败");
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
if (!cancelled) setError("网络错误,请重试");
|
if (!cancelled) setError("网络错误,请重试");
|
||||||
@@ -61,39 +98,49 @@ export default function SliderCaptcha({
|
|||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
};
|
};
|
||||||
}, [open, nonce]);
|
}, [open]);
|
||||||
|
|
||||||
// 轨道实际像素宽度(500 坐标系缩放)——ResizeObserver 的初始通知是
|
// 轨道实际像素宽度(坐标换算基准)。初始测量走 ResizeObserver 的
|
||||||
// 异步派发的,不在 effect 里同步 setState。
|
// 异步首帧通知 + rAF,不在 effect 同步路径 setState。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
const el = trackRef.current;
|
const el = trackRef.current;
|
||||||
if (!el) return;
|
if (!el) return;
|
||||||
const apply = (w: number) => {
|
const apply = (w: number) => {
|
||||||
const px = Math.round(w) || 300;
|
const px = Math.round(w);
|
||||||
trackPxRef.current = px;
|
trackPxRef.current = px;
|
||||||
setTrackPx(px);
|
setTrackPx(px);
|
||||||
};
|
};
|
||||||
// observe 的初始尺寸通知由浏览器异步派发,这里不手动同步测量
|
|
||||||
// (避免在 effect 内同步 setState 触发级联渲染)。
|
|
||||||
const ro = new ResizeObserver((entries) => {
|
const ro = new ResizeObserver((entries) => {
|
||||||
apply(entries[0].contentRect.width);
|
apply(entries[0].contentRect.width);
|
||||||
});
|
});
|
||||||
ro.observe(el);
|
ro.observe(el);
|
||||||
return () => ro.disconnect();
|
const raf = requestAnimationFrame(() => apply(el.clientWidth));
|
||||||
}, [open]);
|
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(
|
const verify = useCallback(
|
||||||
async (finalDragX: number) => {
|
async (finalDragX: number) => {
|
||||||
if (!challenge) return;
|
if (challengeId === null) return;
|
||||||
setStatus("checking");
|
setStatus("checking");
|
||||||
const track = trackPxRef.current || 1;
|
const scaleToImg = IMG_W / (trackPxRef.current || 1);
|
||||||
const x = Math.round((finalDragX / track) * COORD_SPACE);
|
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 {
|
try {
|
||||||
const res = await fetch("/api/captcha/verify", {
|
const res = await fetch("/api/captcha/verify", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "content-type": "application/json" },
|
headers: { "content-type": "application/json" },
|
||||||
body: JSON.stringify({ token: challenge.token, x }),
|
body: JSON.stringify({ challengeId, x, track }),
|
||||||
});
|
});
|
||||||
const data = (await res.json()) as {
|
const data = (await res.json()) as {
|
||||||
ok?: boolean;
|
ok?: boolean;
|
||||||
@@ -106,15 +153,15 @@ export default function SliderCaptcha({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setStatus("error");
|
setStatus("error");
|
||||||
setError(data.error ?? "位置不对,再试一次");
|
setError(data.error ?? "验证失败,请重试");
|
||||||
setShake(true);
|
setShake(true);
|
||||||
window.setTimeout(() => setShake(false), 400);
|
window.setTimeout(() => setShake(false), 400);
|
||||||
if (data.error?.includes("失效") || data.error?.includes("过期")) {
|
if (data.error?.includes("失效") || data.error?.includes("过期") || data.error?.includes("频繁")) {
|
||||||
setChallenge(null);
|
void newChallenge();
|
||||||
setDragX(0);
|
|
||||||
setNonce((n) => n + 1);
|
|
||||||
} else {
|
} else {
|
||||||
setDragX(0);
|
setDragX(0);
|
||||||
|
trackSamplesRef.current = [];
|
||||||
|
pointerRef.current = null;
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
setStatus("error");
|
setStatus("error");
|
||||||
@@ -122,34 +169,36 @@ export default function SliderCaptcha({
|
|||||||
setDragX(0);
|
setDragX(0);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[challenge, onVerified]
|
[challengeId, onVerified, newChallenge]
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!open) return null;
|
if (!open) return null;
|
||||||
|
|
||||||
const slotX = challenge ? (challenge.puzzleX / COORD_SPACE) * trackPx : 0;
|
const pieceX = Math.max(0, Math.min(maxDrag, dragX));
|
||||||
const maxDrag = Math.max(0, trackPx - PIECE_W);
|
|
||||||
|
|
||||||
const onPointerDown = (e: React.PointerEvent) => {
|
const onPointerDown = (e: React.PointerEvent) => {
|
||||||
if (status === "checking") return;
|
if (status === "checking") return;
|
||||||
(e.target as HTMLElement).setPointerCapture?.(e.pointerId);
|
(e.target as HTMLElement).setPointerCapture?.(e.pointerId);
|
||||||
startXRef.current = e.clientX;
|
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");
|
setStatus("dragging");
|
||||||
};
|
};
|
||||||
const onPointerMove = (e: React.PointerEvent) => {
|
const onPointerMove = (e: React.PointerEvent) => {
|
||||||
if (status !== "dragging") return;
|
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)));
|
setDragX(Math.max(0, Math.min(maxDrag, next)));
|
||||||
};
|
};
|
||||||
const onPointerUp = () => {
|
const onPointerUp = () => {
|
||||||
if (status !== "dragging") return;
|
if (status !== "dragging") return;
|
||||||
void verify(dragX);
|
pointerRef.current = null;
|
||||||
};
|
void verify(pieceX);
|
||||||
|
|
||||||
const dottedBg: React.CSSProperties = {
|
|
||||||
backgroundImage: "radial-gradient(var(--grid-dot) 1px, transparent 1px)",
|
|
||||||
backgroundSize: "12px 12px",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -177,70 +226,91 @@ export default function SliderCaptcha({
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 拼图轨道 */}
|
{/* 拼图轨道(服务端渲染图:缺口位置在图里,不在 JS 里) */}
|
||||||
<div
|
<div
|
||||||
ref={trackRef}
|
ref={trackRef}
|
||||||
className="relative h-14 overflow-hidden border border-line bg-b1"
|
className="relative h-[140px] overflow-hidden border border-line bg-b1"
|
||||||
style={dottedBg}
|
|
||||||
>
|
>
|
||||||
{/* 缺口槽 */}
|
{imgs ? (
|
||||||
{challenge && (
|
<>
|
||||||
<div
|
{/* eslint-disable-next-line @next/next/no-img-element -- 动态验证码图 */}
|
||||||
aria-hidden="true"
|
<img
|
||||||
className="absolute top-0 h-full border-2 border-dashed border-(--selection-bg) bg-black/30"
|
src={imgs.bg}
|
||||||
style={{ left: slotX, width: PIECE_W }}
|
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>
|
||||||
|
|
||||||
{/* 进度条 */}
|
{/* 进度条 */}
|
||||||
<div className="mt-3 h-1 w-full bg-line">
|
<div className="mt-3 h-1 w-full bg-line">
|
||||||
<div
|
<div
|
||||||
className="h-full bg-(--selection-bg) transition-[width] duration-75"
|
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>
|
</div>
|
||||||
|
|
||||||
<p className="mt-3 font-mono-2 text-xs text-l2">
|
<div className="mt-3 flex items-center justify-between gap-3">
|
||||||
{status === "checking"
|
<p className="font-mono-2 text-xs text-l2">
|
||||||
? "校验中…"
|
{status === "checking"
|
||||||
: error
|
? "校验中…"
|
||||||
? error
|
: error && status === "error"
|
||||||
: "拖动滑块,将虚线框与图案对齐"}
|
? error
|
||||||
</p>
|
: "拖动拼块,对齐缺口图案"}
|
||||||
|
</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>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
+131
-23
@@ -1,51 +1,149 @@
|
|||||||
/**
|
/**
|
||||||
* 滑块验证码 — 服务端Challenge/Verify。
|
* 滑块验证码 v2 — 图片化挑战 + 行为轨迹校验 + 限流。
|
||||||
*
|
*
|
||||||
* 生成:随机缺口位置(80-420px)+ 一次性 token(10 分钟有效)。
|
* 与 v1 的区别(防脚本):
|
||||||
* 校验:客户端提交拖动终点 x,|x - answer| <= CAPTCHA_TOLERANCE 即通过;
|
* 1. 答案坐标不再下发——缺口位置由服务端烘进 PNG(lib/captchaImage),
|
||||||
* 通过后签发一次性 submitToken(5 分钟、单次消费),提交接口凭它放行。
|
* JS 里没有答案,脚本必须做图像识别才能定位。
|
||||||
* 失败计数 5 次作废 challenge,防暴力枚举。
|
* 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 crypto from "node:crypto";
|
||||||
import { db } from "@/lib/db";
|
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 CHALLENGE_TTL_MIN = 10;
|
||||||
const SUBMIT_TOKEN_TTL_MIN = 5;
|
const SUBMIT_TOKEN_TTL_MIN = 5;
|
||||||
const MAX_ATTEMPTS = 5;
|
const MAX_ATTEMPTS = 5;
|
||||||
|
|
||||||
export function createCaptchaChallenge(): {
|
// 限流阈值(按 IP 哈希)
|
||||||
id: number;
|
const RL_CHALLENGE = { max: 15, windowMin: 10 };
|
||||||
puzzleX: number; // 缺口随机位置(前端展示用)
|
const RL_VERIFY = { max: 30, windowMin: 10 };
|
||||||
trackWidth: number;
|
|
||||||
token: string;
|
export type TrackSample = { t: number; x: number };
|
||||||
} {
|
|
||||||
const puzzleX = 80 + crypto.randomInt(0, 341); // 80..420
|
// 复用 captcha_challenges 表:answer_x 存缺口位置,extra 存限流指纹。
|
||||||
|
// 限流走独立小表(内存实现即可——单实例部署,重启清零可接受)。
|
||||||
|
const rateLimitBuckets = new Map<string, number[]>();
|
||||||
|
|
||||||
|
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");
|
const token = crypto.randomBytes(24).toString("hex");
|
||||||
db.prepare(
|
db.prepare(
|
||||||
`INSERT INTO captcha_challenges (token, answer_x, expires_at)
|
`INSERT INTO captcha_challenges (token, answer_x, expires_at)
|
||||||
VALUES (?, ?, datetime('now', '+${CHALLENGE_TTL_MIN} minutes'))`
|
VALUES (?, ?, datetime('now', '+${CHALLENGE_TTL_MIN} minutes'))`
|
||||||
).run(token, puzzleX);
|
).run(token, answerX);
|
||||||
const row = db
|
const row = db
|
||||||
.prepare("SELECT id FROM captcha_challenges WHERE token = ?")
|
.prepare("SELECT id FROM captcha_challenges WHERE token = ?")
|
||||||
.get(token) as { id: number };
|
.get(token) as { id: number };
|
||||||
db.prepare("DELETE FROM captcha_challenges WHERE expires_at < datetime('now')").run();
|
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(
|
export function verifyCaptcha(
|
||||||
token: string,
|
req: Request,
|
||||||
answerX: number
|
challengeId: number,
|
||||||
|
x: number,
|
||||||
|
track: TrackSample[]
|
||||||
): { ok: true; submitToken: string } | { ok: false; error: string } {
|
): { 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
|
const row = db
|
||||||
.prepare(
|
.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
|
.get(challengeId) as
|
||||||
| { id: number; answer_x: number; consumed: number; attempts: number; expires_at: string }
|
| { id: number; answer_x: number; consumed: number; attempts: number; expires_at: string; token: string }
|
||||||
| undefined;
|
| 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()) {
|
if (new Date(row.expires_at + "Z") < new Date()) {
|
||||||
return { ok: false, error: "验证已过期,请刷新重试" };
|
return { ok: false, error: "验证已过期,请刷新重试" };
|
||||||
}
|
}
|
||||||
@@ -54,16 +152,26 @@ export function verifyCaptcha(
|
|||||||
return { ok: false, error: "尝试次数过多,请刷新重试" };
|
return { ok: false, error: "尝试次数过多,请刷新重试" };
|
||||||
}
|
}
|
||||||
|
|
||||||
const delta = Math.abs(answerX - row.answer_x);
|
if (Math.abs(x - row.answer_x) > CAPTCHA_TOLERANCE) {
|
||||||
if (delta > CAPTCHA_TOLERANCE) {
|
|
||||||
db.prepare(
|
db.prepare(
|
||||||
"UPDATE captcha_challenges SET attempts = attempts + 1 WHERE id = ?"
|
"UPDATE captcha_challenges SET attempts = attempts + 1 WHERE id = ?"
|
||||||
).run(row.id);
|
).run(row.id);
|
||||||
return { ok: false, error: "位置不对,再试一次" };
|
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);
|
db.prepare("UPDATE captcha_challenges SET consumed = 1 WHERE id = ?").run(row.id);
|
||||||
const submitToken = crypto.randomBytes(24).toString("hex");
|
const submitToken = crypto.randomBytes(24).toString("hex");
|
||||||
|
// 令牌签发:重置 consumed(上面 verify 成功时置 1 了),单次消费由
|
||||||
|
// consumeSubmitToken 在提交接口完成。
|
||||||
db.prepare(
|
db.prepare(
|
||||||
`UPDATE captcha_challenges SET token = ?, consumed = 0, expires_at = datetime('now', '+${SUBMIT_TOKEN_TTL_MIN} minutes') WHERE id = ?`
|
`UPDATE captcha_challenges SET token = ?, consumed = 0, expires_at = datetime('now', '+${SUBMIT_TOKEN_TTL_MIN} minutes') WHERE id = ?`
|
||||||
).run(`submit:${submitToken}`, row.id);
|
).run(`submit:${submitToken}`, row.id);
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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)),
|
||||||
|
]);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user