feat: 登录/注册接入 tianai-captcha 人机行为验证
- 后端: auth/captcha.ts 二次核验(secondary-verify 一次性核销), login/register 前置校验, TAC_ENABLED 开关 - 前端: useCaptcha hook(React 版), AuthModal 验证按钮(通过变绿), verifyToken 随提交携带, 失败/切换自动重置 - nginx: /tac/api/ 同源反代 prod1:18200; public/tac/ 静态资源(load.min.js + sdk) - 复用 HomeCentral 站点凭证(平台不校验域名, 已从源码确认) - 本地开发 .env.development 关闭验证; 测试环境 compose 注入 TAC_* 全开 - prod1 DOCKER_USER 链已加 .86 白名单(运行时+持久化)
This commit is contained in:
1 parent
ef9b95f85c
commit
7c3d2cfdef
19 files changed
+350
-22
No files matched your search
@@ -83,6 +83,10 @@ jobs:
|
||||
PORT: "8788"
|
||||
DATABASE_URL: postgres://perler:7c5608fe52a5223a6c6107b6@postgres:5432/perler_lab
|
||||
JWT_SECRET: "4c695e86451281112d20aae50f1fbde5a30d10f77ce4f750c1873b2d25549c81"
|
||||
TAC_ENABLED: "true"
|
||||
TAC_API_BASE: "http://38.76.218.110:18200"
|
||||
TAC_SITE_KEY: "6796bad8-4369-492f-a4d7-643a93bb07f3"
|
||||
TAC_SECRET_KEY: "dae2c135-4e61-4249-a5bb-a15081b1a2b6"
|
||||
volumes:
|
||||
- db-data:/app/data
|
||||
networks: [perler-net]
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* tianai-captcha 人机验证二次核验(对齐 HomeCentral 的 TianaiCaptchaVerificationService)。
|
||||
*
|
||||
* 链路:
|
||||
* 1. 前端滑块校验通过 → 平台 POST /api/challenge/verify 签发 verifyToken
|
||||
* 2. 登录/注册请求体携带 captchaToken = verifyToken
|
||||
* 3. 此处调平台 POST /api/challenge/secondary-verify {siteKey, secretKey, verifyToken}
|
||||
* 一次性核销(重复使用返回 token_invalid)
|
||||
*
|
||||
* 环境变量:
|
||||
* TAC_ENABLED = "true" 启用(默认关闭,本地/单测跳过)
|
||||
* TAC_API_BASE = 平台地址(默认 http://38.76.218.110:18200)
|
||||
* TAC_SITE_KEY = 站点 siteKey
|
||||
* TAC_SECRET_KEY = 站点 secretKey
|
||||
*
|
||||
* 平台响应契约(CaptchaPlatformService.secondaryVerify):
|
||||
* 通过 → HTTP 200 + data.verifyResult = true
|
||||
* 凭证错 → code 10001 site_auth_fail
|
||||
* 无效票 → code 403 token_invalid
|
||||
*/
|
||||
|
||||
import { AuthError } from "./service.js";
|
||||
|
||||
const TAC_ENABLED = process.env["TAC_ENABLED"] === "true";
|
||||
const TAC_API_BASE = process.env["TAC_API_BASE"] ?? "http://38.76.218.110:18200";
|
||||
const TAC_SITE_KEY = process.env["TAC_SITE_KEY"] ?? "";
|
||||
const TAC_SECRET_KEY = process.env["TAC_SECRET_KEY"] ?? "";
|
||||
|
||||
/** 人机验证是否启用。 */
|
||||
export function captchaEnabled(): boolean {
|
||||
return TAC_ENABLED;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验请求体中的 captchaToken。未启用时直接放行;
|
||||
* 启用后缺失/无效/平台不可用一律抛 AuthError(由路由统一转响应)。
|
||||
*/
|
||||
export async function requireCaptcha(body: unknown): Promise<void> {
|
||||
if (!TAC_ENABLED) return;
|
||||
|
||||
const b = (body ?? {}) as { captchaToken?: unknown };
|
||||
const token = typeof b.captchaToken === "string" ? b.captchaToken.trim() : "";
|
||||
if (token === "") {
|
||||
throw new AuthError("请先完成人机验证", 401, "CAPTCHA_MISSING");
|
||||
}
|
||||
|
||||
if (TAC_SITE_KEY === "" || TAC_SECRET_KEY === "") {
|
||||
console.error("[captcha] TAC_ENABLED=true 但未配置 TAC_SITE_KEY/TAC_SECRET_KEY");
|
||||
throw new AuthError("人机验证服务未配置,请稍后重试", 503, "CAPTCHA_MISCONFIGURED");
|
||||
}
|
||||
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`${TAC_API_BASE}/api/challenge/secondary-verify`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
siteKey: TAC_SITE_KEY,
|
||||
secretKey: TAC_SECRET_KEY,
|
||||
verifyToken: token,
|
||||
}),
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[captcha] secondary-verify 请求失败:", err);
|
||||
throw new AuthError("人机验证服务暂不可用,请稍后重试", 503, "CAPTCHA_UNAVAILABLE");
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new AuthError("人机验证失败,请重新验证", 401, "CAPTCHA_INVALID");
|
||||
}
|
||||
|
||||
const data = (await res.json().catch(() => null)) as {
|
||||
data?: { verifyResult?: unknown };
|
||||
} | null;
|
||||
if (data?.data?.verifyResult !== true) {
|
||||
throw new AuthError("人机验证失败,请重新验证", 401, "CAPTCHA_INVALID");
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import type { Request, Response } from "express";
|
||||
import type { Db } from "../db/index.js";
|
||||
import { getDb } from "../db/index.js";
|
||||
import { AuthError, AUTH_ERRORS, findUserById, loginUser, registerUser } from "./service.js";
|
||||
import { requireCaptcha } from "./captcha.js";
|
||||
import { signToken } from "./jwt.js";
|
||||
import { requireAuth } from "./middleware.js";
|
||||
import { createRateLimiter } from "../security/rate-limit.js";
|
||||
@@ -49,6 +50,7 @@ export function createAuthRouter(injectedDb?: Db): Router {
|
||||
/** POST /api/auth/register */
|
||||
router.post("/register", registerLimiter, async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
await requireCaptcha(req.body);
|
||||
const { phone, password } = parseCredentials(req.body);
|
||||
const b = (req.body ?? {}) as { nickname?: unknown };
|
||||
const nickname =
|
||||
@@ -70,6 +72,7 @@ export function createAuthRouter(injectedDb?: Db): Router {
|
||||
/** POST /api/auth/login */
|
||||
router.post("/login", loginLimiter, async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
await requireCaptcha(req.body);
|
||||
const { phone, password } = parseCredentials(req.body);
|
||||
const db = resolveDb(injectedDb);
|
||||
const user = await loginUser(db, phone, password);
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# 本地开发覆盖:办公网络到不了 prod1:18200(安全组未放行),关闭人机验证
|
||||
VITE_CAPTCHA_ENABLED=false
|
||||
@@ -11,6 +11,7 @@
|
||||
href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700;800&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<script src="/tac/load.min.js"></script>
|
||||
<title>PERLER LAB · 拼豆图纸生成器</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -16,6 +16,11 @@ upstream backend {
|
||||
server server:8788;
|
||||
}
|
||||
|
||||
upstream captcha-platform {
|
||||
# tianai-captcha 自托管平台(prod1),安全组仅放行本服务器 IP
|
||||
server 38.76.218.110:18200;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80 default_server;
|
||||
server_name _;
|
||||
@@ -85,6 +90,17 @@ server {
|
||||
proxy_buffering off;
|
||||
}
|
||||
|
||||
# ── TAC 人机验证:同源反代 → tianai-captcha 平台(generate/verify 用 X-Site-Key 头) ──
|
||||
location /tac/api/ {
|
||||
proxy_pass http://captcha-platform;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_read_timeout 15s;
|
||||
proxy_send_timeout 15s;
|
||||
}
|
||||
|
||||
# ── 健康检查端点 ──
|
||||
location = /healthz {
|
||||
access_log off;
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
#tianai-captcha-parent{box-shadow:0 0 11px 0 #999;width:318px;height:318px;overflow:hidden;position:relative;z-index:997;box-sizing:border-box;border-radius:5px;padding:8px}#tianai-captcha-parent #tianai-captcha-box{height:260px;width:100%;position:relative;overflow:hidden}#tianai-captcha-parent #tianai-captcha-box .loading{width:120px;height:20px;-webkit-mask:linear-gradient(90deg, #000 70%, rgba(0, 0, 0, 0) 0) 0/20%;background:linear-gradient(#f7b645 0 0) 0/0% no-repeat rgba(221,221,221,.4196078431);animation:cartoon 1s infinite steps(6);margin:120px auto}@keyframes cartoon{100%{background-size:120%}}#tianai-captcha-parent #tianai-captcha-box #tianai-captcha{transform-style:preserve-3d;will-change:transform;transition-duration:.45s;transform:translateX(-300px)}#tianai-captcha-parent #tianai-captcha-bg-img{background-color:#fff;background-position:top;background-size:cover;z-index:-1;width:100%;height:100%;top:0;left:0;position:absolute;border-radius:6px}#tianai-captcha-parent .slider-bottom .close-btn{width:20px;height:20px;background-image:url(../../tac/images/icon.png);background-repeat:no-repeat;background-position:0 -14px;float:right;margin-right:2px;cursor:pointer}#tianai-captcha-parent .slider-bottom .refresh-btn{width:20px;height:20px;background-image:url(../../tac/images/icon.png);background-position:0 -167px;background-repeat:no-repeat;float:right;margin-right:10px;cursor:pointer}#tianai-captcha-parent .slider-bottom .logo{height:30px;float:left}#tianai-captcha-parent .slider-bottom{height:19px;width:100%}#tianai-captcha-parent .slider-move-shadow{animation:myanimation 2s infinite;height:100%;width:5px;background-color:#fff;position:absolute;top:0;left:0;filter:opacity(0.5);box-shadow:1px 1px 1px #fff;border-radius:50%}#tianai-captcha-parent #tianai-captcha-slider-move-track-mask{border-width:1px;border-style:solid;border-color:#00f4ab;width:0;height:32px;background-color:#a9ffe5;opacity:.5;position:absolute;top:-1px;left:-1px;border-radius:5px}
|
||||
#tianai-captcha{text-align:left;box-sizing:content-box;width:300px;height:260px;z-index:999}#tianai-captcha .slider-bottom .logo{height:30px}#tianai-captcha .slider-bottom{height:19px;width:100%}#tianai-captcha .content .tianai-captcha-tips{height:25px;width:100%;position:absolute;bottom:-25px;left:0;z-index:999;font-size:15px;line-height:25px;color:#fff;text-align:center;transition:bottom .3s ease-in-out}#tianai-captcha .content .tianai-captcha-tips.tianai-captcha-tips-error{background-color:#ff5d39}#tianai-captcha .content .tianai-captcha-tips.tianai-captcha-tips-success{background-color:#39c522}#tianai-captcha .content .tianai-captcha-tips.tianai-captcha-tips-on{bottom:0}#tianai-captcha .content #tianai-captcha-loading{z-index:9999;background-color:#f5f5f5;text-align:center;height:100%;overflow:hidden;position:relative;display:flex;justify-content:center;align-items:center}#tianai-captcha .content #tianai-captcha-loading img{display:block;width:45px;height:45px}#tianai-captcha #tianai-captcha-slider-bg-canvas{position:absolute;left:0;top:0;width:100%;height:100%;border-radius:5px}#tianai-captcha #tianai-captcha-slider-bg-div{position:absolute;left:0;top:0;width:100%;height:100%;border-radius:5px}#tianai-captcha #tianai-captcha-slider-bg-div .tianai-captcha-slider-bg-div-slice{position:absolute}@keyframes myanimation{from{left:0}to{left:289px}}
|
||||
#tianai-captcha.tianai-captcha-slider{z-index:999;position:absolute;left:0;top:0}#tianai-captcha.tianai-captcha-slider .content{width:100%;height:180px;position:relative;overflow:hidden}#tianai-captcha.tianai-captcha-slider .bg-img-div{width:100%;height:100%;position:absolute;transform:translate(0px, 0px)}#tianai-captcha.tianai-captcha-slider .bg-img-div img{height:100%;width:100%;border-radius:5px}#tianai-captcha.tianai-captcha-slider .slider-img-div{height:100%;position:absolute;left:0;transform:translate(0px, 0px)}#tianai-captcha.tianai-captcha-slider .slider-img-div #tianai-captcha-slider-move-img{height:100%}#tianai-captcha.tianai-captcha-slider .slider-move{height:34px;width:100%;margin:11px 0;position:relative}#tianai-captcha.tianai-captcha-slider .slider-move-track{position:relative;height:32px;line-height:32px;text-align:center;background:#f5f5f5;color:#999;transition:0s;font-size:14px;box-sizing:content-box;border:1px solid #f5f5f5;border-radius:4px}#tianai-captcha.tianai-captcha-slider .refresh-btn,#tianai-captcha.tianai-captcha-slider .close-btn{display:inline-block}#tianai-captcha.tianai-captcha-slider .slider-move{line-height:38px;font-size:14px;text-align:center;white-space:nowrap;color:#88949d;-moz-user-select:none;-webkit-user-select:none;user-select:none;filter:opacity(0.8)}#tianai-captcha.tianai-captcha-slider .slider-move .slider-move-btn{transform:translate(0px, 0px);position:absolute;top:-6px;left:0;width:63px;height:45px;background-color:#fff;background-repeat:no-repeat;background-size:contain;border-radius:5px}#tianai-captcha.tianai-captcha-slider .slider-tip{margin-bottom:5px;font-weight:bold;font-size:15px;line-height:normal;color:#000}#tianai-captcha.tianai-captcha-slider .slider-move-btn:hover{cursor:pointer}#tianai-captcha.tianai-captcha-slider{user-select:none}
|
||||
#tianai-captcha.tianai-captcha-rotate .rotate-img-div{height:100%;text-align:center}#tianai-captcha.tianai-captcha-rotate .rotate-img-div img{height:100%;transform:rotate(0deg);display:inline-block}
|
||||
#tianai-captcha.tianai-captcha-concat .tianai-captcha-slider-concat-img-div{background-size:100% 180px;position:absolute;transform:translate(0px, 0px);z-index:1;width:100%}#tianai-captcha.tianai-captcha-concat .tianai-captcha-slider-concat-bg-img{width:100%;height:100%;position:absolute;transform:translate(0px, 0px);background-size:100% 180px}
|
||||
#tianai-captcha.tianai-captcha-disable{z-index:999;position:absolute;left:0;top:0}#tianai-captcha.tianai-captcha-disable .content{width:100%;height:180px;position:relative;overflow:hidden}#tianai-captcha.tianai-captcha-disable .content .bg-img-div{background-image:url(../../tac/images/dun.jpeg);width:100%;height:100%;overflow:hidden}#tianai-captcha.tianai-captcha-disable .content .bg-img-div #content-span{color:#fff;overflow:hidden;margin-top:132px;display:block;text-align:center}
|
||||
#tianai-captcha.tianai-captcha-word-click{box-sizing:border-box}#tianai-captcha.tianai-captcha-word-click .click-tip{position:relative;height:40px;width:100%}#tianai-captcha.tianai-captcha-word-click .click-tip .tip-img{height:35px;position:absolute;right:15px}#tianai-captcha.tianai-captcha-word-click .click-tip #tianai-captcha-click-track-font{font-size:18px;display:inline-block;height:40px;line-height:40px;position:absolute}#tianai-captcha.tianai-captcha-word-click .slider-bottom{position:relative;top:6px}#tianai-captcha.tianai-captcha-word-click .content #bg-img-click-mask{width:100%;height:100%;position:absolute;left:0;top:0}#tianai-captcha.tianai-captcha-word-click .content #bg-img-click-mask .click-span{position:absolute;left:0;top:0;border-radius:50px;background-color:#409eff;width:20px;height:20px;text-align:center;line-height:20px;color:#fff;border:2px solid #fff;box-sizing:content-box}#tianai-captcha.tianai-captcha-word-click .click-confirm-btn{width:100%;height:35px;border-radius:4px;background-image:linear-gradient(173deg, hsl(38.09, 91%, 57.89%) 0%, hsl(38.09, 89.38%, 71.74%) 100%);font-size:15px;text-align:center;box-sizing:border-box;line-height:35px;color:#fff;margin-top:3px}#tianai-captcha.tianai-captcha-word-click .click-confirm-btn:hover{cursor:pointer}
|
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 8.1 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.0 KiB |
Vendored
+1
@@ -0,0 +1 @@
|
||||
(()=>{"use strict";var t,e,a={783:(t,e,a)=>{var i=a(618),n=Object.create(null),r="undefined"==typeof document,s=Array.prototype.forEach;function c(){}function o(t,e){if(!e){if(!t.href)return;e=t.href.split("?")[0]}if(l(e)&&!1!==t.isLoaded&&e&&e.indexOf(".css")>-1){t.visited=!0;var a=t.cloneNode();a.isLoaded=!1,a.addEventListener("load",(function(){a.isLoaded||(a.isLoaded=!0,t.parentNode.removeChild(t))})),a.addEventListener("error",(function(){a.isLoaded||(a.isLoaded=!0,t.parentNode.removeChild(t))})),a.href="".concat(e,"?").concat(Date.now()),t.nextSibling?t.parentNode.insertBefore(a,t.nextSibling):t.parentNode.appendChild(a)}}function d(t){if(!t)return!1;var e=document.querySelectorAll("link"),a=!1;return s.call(e,(function(e){if(e.href){var n=function(t,e){var a;return t=i(t),e.some((function(i){t.indexOf(e)>-1&&(a=i)})),a}(e.href,t);l(n)&&!0!==e.visited&&n&&(o(e,n),a=!0)}})),a}function h(){var t=document.querySelectorAll("link");s.call(t,(function(t){!0!==t.visited&&o(t)}))}function l(t){return!!/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t)}t.exports=function(t,e){if(r)return c;var a,s,o,l=function(t){var e=n[t];if(!e){if(document.currentScript)e=document.currentScript.src;else{var a=document.getElementsByTagName("script"),r=a[a.length-1];r&&(e=r.src)}n[t]=e}return function(t){if(!e)return null;var a=e.split(/([^\\/]+)\.js$/),n=a&&a[1];return n&&t?t.split(",").map((function(t){var a=new RegExp("".concat(n,"\\.js$"),"g");return i(e.replace(a,"".concat(t.replace(/{fileName}/g,n),".css")))})):[e.replace(".js",".css")]}}(t);return a=function(){var t=d(l(e.filename));e.locals?h():t||h()},s=50,o=0,function(){var t=this,e=arguments;clearTimeout(o),o=setTimeout((function(){return a.apply(t,e)}),s)}}},618:t=>{t.exports=function(t){if(t=t.trim(),/^data:/i.test(t))return t;var e=-1!==t.indexOf("//")?t.split("//")[0]+"//":"",a=t.replace(new RegExp(e,"i"),"").split("/"),i=a[0].toLowerCase().replace(/\.$/,"");return a[0]="",e+i+a.reduce((function(t,e){switch(e){case"..":t.pop();break;case".":break;default:t.push(e)}return t}),[]).join("/")}},488:(t,e,a)=>{var i=a(783)(t.id,{locals:!1});t.hot.dispose(i),t.hot.accept(void 0,i)},523:(t,e,a)=>{var i=a(783)(t.id,{locals:!1});t.hot.dispose(i),t.hot.accept(void 0,i)},991:(t,e,a)=>{var i=a(783)(t.id,{locals:!1});t.hot.dispose(i),t.hot.accept(void 0,i)},2:(t,e,a)=>{var i=a(783)(t.id,{locals:!1});t.hot.dispose(i),t.hot.accept(void 0,i)},492:(t,e,a)=>{var i=a(783)(t.id,{locals:!1});t.hot.dispose(i),t.hot.accept(void 0,i)},305:(t,e,a)=>{var i=a(783)(t.id,{locals:!1});t.hot.dispose(i),t.hot.accept(void 0,i)},444:(t,e,a)=>{var i=a(783)(t.id,{locals:!1});t.hot.dispose(i),t.hot.accept(void 0,i)},687:(t,e,a)=>{a(488),a(523),a(444);function i(t){t.preventDefault&&t.preventDefault()}function n(t){f(t).each((t=>{t.addEventListener("touchmove",i,{passive:!1}),t.addEventListener("mousemove",i,{passive:!1})}))}function r(t){if(null!==t.pageX&&void 0!==t.pageX)return{x:Math.round(t.pageX),y:Math.round(t.pageY)};let e;return t.changedTouches?e=t.changedTouches:t.targetTouches?e=t.targetTouches:t.originalEvent&&t.originalEvent.targetTouches&&(e=t.originalEvent.targetTouches),null!==e[0].pageX&&void 0!==e[0].pageX?{x:Math.round(e[0].pageX),y:Math.round(e[0].pageY)}:{x:Math.round(e[0].clientX),y:Math.round(e[0].clientY)}}function s(t,e){const a=r(e);let i=a.x,n=a.y;t.currentCaptchaData.startX=i,t.currentCaptchaData.startY=n;const s=t.currentCaptchaData.trackList;t.currentCaptchaData.startTime=new Date;const o=t.currentCaptchaData.startTime;s.push({x:a.x,y:a.y,type:"down",t:(new Date).getTime()-o.getTime()}),t.__m__=c.bind(null,t),t.__u__=d.bind(null,t),window.addEventListener("mousemove",t.__m__),window.addEventListener("mouseup",t.__u__),window.addEventListener("touchmove",t.__m__,!1),window.addEventListener("touchend",t.__u__,!1),t&&t.doDown&&t.doDown(e,t)}function c(t,e){e.touches&&e.touches.length>0&&(e=e.touches[0]);const a=r(e);let i=a.x,n=a.y;const s=t.currentCaptchaData.startX,c=t.currentCaptchaData.startY,o=t.currentCaptchaData.startTime,d=t.currentCaptchaData.end,h=(t.currentCaptchaData.bgImageWidth,t.currentCaptchaData.trackList);let l=i-s,p=n-c;const u={x:a.x,y:a.y,type:"move",t:(new Date).getTime()-o.getTime()};h.push(u),l<0?l=0:l>d&&(l=d),t.currentCaptchaData.moveX=l,t.currentCaptchaData.moveY=p,t.doMove&&t.doMove(e,t)}function o(t){t&&(t.__m__&&(window.removeEventListener("mousemove",t.__m__),window.removeEventListener("touchmove",t.__m__)),t.__u__&&(window.removeEventListener("mouseup",t.__u__),window.removeEventListener("touchend",t.__u__)))}function d(t,e){o(t);const a=r(e);t.currentCaptchaData.stopTime=new Date;const i=t.currentCaptchaData.startTime,n=t.currentCaptchaData.trackList,s={x:a.x,y:a.y,type:"up",t:(new Date).getTime()-i.getTime()};n.push(s),t.doUp&&t.doUp(e,t),t.endCallback(t.currentCaptchaData,t)}function h(t,e,a,i,n){const r={startTime:new Date,trackList:[],movePercent:0,clickCount:0,bgImageWidth:Math.round(t),bgImageHeight:Math.round(e),templateImageWidth:Math.round(a),tLine truncated
|
||||
Binary file not shown.
Vendored
+1
@@ -0,0 +1 @@
|
||||
const Math=window.Math,head=document.getElementsByTagName("head")[0],TIMEOUT=1e4,TAC_LOADING_DIV='<div id="tac-loading" style="\n border: 1px solid #eee;\n /* background-color: #409EFF; */\n border-radius: 5px;\n width: 318px;\n height: 318px;\n line-height: 318px;\n color: #606266;\n text-align: center;\n position: relative;\n box-sizing: border-box;\n">请稍等...</div>';function showLoading(e){var t=document.querySelector(e);t&&(t.innerHTML=TAC_LOADING_DIV)}function hideLoading(e){let t=document.querySelector(e);t&&(t.innerHTML="")}function loadCaptchaScript(e,t,n,r,o){const i=e.scriptUrls,c=e.cssUrls,l=e.timeout||TIMEOUT;let s=i.length+c.length;function d(e,i){if(s--,e&&0===s){if(hideLoading(t.bindEl),!window.TAC)throw new Error("TAC未加载,请检查地址是否正确");r(new TAC(t,n))}else e||(hideLoading(t.bindEl),o(i))}setTimeout(()=>{0!==s&&showLoading(t.bindEl)},10),i.forEach(function(e){loadResource("string"==typeof e?{url:e}:e,d,"script",l)}),c.forEach(function(e){loadResource("string"==typeof e?{url:e}:e,d,"link",l)})}function loadResource(e,t,n="script",r){if(document.querySelector(`${n}[${"script"===n?"src":"href"}="${e.url}"]`))return void t(!0,e);let o=!1;const i=document.createElement(n);"link"===n?i.rel="stylesheet":i.async=!0,i["script"===n?"src":"href"]=e.url;let c;i.onload=i.onreadystatechange=(()=>{o||i.readyState&&"loaded"!==i.readyState&&"complete"!==i.readyState||function t(n){e.checkOnReady?c=setTimeout(()=>{e.checkOnReady()?n():t(n)},10):n()}(()=>{o=!0,setTimeout(()=>t(o,e),0)})}),i.onerror=(()=>{t(o=!1,e)}),head.appendChild(i),setTimeout(()=>{o||(c&&clearTimeout(c),i.onload=i.onerror=null,i.remove&&i.remove(),t(o,e))},r||TIMEOUT)}function loadTAC(e,t,n){return new Promise((r,o)=>{let i={..."string"==typeof e?{url:e}:e};i.url&&(i.url.endsWith("/")||(i.url+="/"),i.scriptUrls||(i.scriptUrls=[i.url+"js/tac.min.js"]),i.cssUrls||(i.cssUrls=[i.url+"css/tac.css"])),i.scriptUrls&&i.cssUrls?loadCaptchaScript(i,t,n,r,o):o("请按照文档配置tac")})}setTimeout(()=>{let e=document.scripts,t=null;for(let n=0;n<e.length;n++)if(e[n].src.indexOf("load.js")>1||e[n].src.indexOf("load.min.js")>1){t=e[n].src.substring(e[n].src.indexOf("/"),e[n].src.lastIndexOf("/"));break}},100),window.loadCaptchaScript=loadCaptchaScript,window.loadTAC=loadTAC,window.initTAC=loadTAC;
|
||||
Binary file not shown.
@@ -11,6 +11,7 @@
|
||||
import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react';
|
||||
import { useT } from '../i18n';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { useCaptcha } from '../lib/useCaptcha';
|
||||
|
||||
interface AuthModalProps {
|
||||
open: boolean;
|
||||
@@ -28,14 +29,16 @@ export default function AuthModal({ open, onClose }: AuthModalProps) {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const captcha = useCaptcha('auth');
|
||||
const phoneRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// 打开时焦点落到第一个输入框
|
||||
// 打开时重置表单与人机验证状态
|
||||
useEffect(() => {
|
||||
if (!open) return undefined;
|
||||
captcha.reset();
|
||||
const raf = requestAnimationFrame(() => phoneRef.current?.focus());
|
||||
return () => cancelAnimationFrame(raf);
|
||||
}, [open]);
|
||||
}, [open]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// ESC 关闭
|
||||
useEffect(() => {
|
||||
@@ -50,7 +53,8 @@ export default function AuthModal({ open, onClose }: AuthModalProps) {
|
||||
const switchMode = useCallback(() => {
|
||||
setMode((m) => (m === 'login' ? 'register' : 'login'));
|
||||
setError(null);
|
||||
}, []);
|
||||
captcha.reset();
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (e: FormEvent) => {
|
||||
@@ -64,22 +68,29 @@ export default function AuthModal({ open, onClose }: AuthModalProps) {
|
||||
setError('密码至少需要 6 位');
|
||||
return;
|
||||
}
|
||||
const captchaToken = captcha.consumeToken();
|
||||
if (captchaToken === null) {
|
||||
setError('请先完成人机验证');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
try {
|
||||
if (mode === 'login') {
|
||||
await login(phone.trim(), password);
|
||||
await login(phone.trim(), password, captchaToken);
|
||||
} else {
|
||||
await register(phone.trim(), password, nickname.trim() || undefined);
|
||||
await register(phone.trim(), password, nickname.trim() || undefined, captchaToken);
|
||||
}
|
||||
// 成功后由 useAuth 更新状态,关闭弹窗
|
||||
onClose();
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : '操作失败,请稍后重试');
|
||||
} finally {
|
||||
// verifyToken 一次性核销:无论成败,下次提交都要重新验证
|
||||
captcha.reset();
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[mode, phone, password, nickname, login, register, onClose],
|
||||
[mode, phone, password, nickname, login, register, onClose, captcha],
|
||||
);
|
||||
|
||||
if (!open) return null;
|
||||
@@ -162,6 +173,24 @@ export default function AuthModal({ open, onClose }: AuthModalProps) {
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* 人机验证(TAC 滑块,通过后变绿) */}
|
||||
<div className="field">
|
||||
<div id={captcha.containerId} className="captcha-box">
|
||||
<button
|
||||
type="button"
|
||||
className={`captcha-btn${captcha.verified ? ' captcha-btn--passed' : ''}`}
|
||||
onClick={() => void captcha.show()}
|
||||
disabled={captcha.state === 'loading'}
|
||||
>
|
||||
{captcha.state === 'passed'
|
||||
? '人机验证通过'
|
||||
: captcha.state === 'loading'
|
||||
? '验证组件加载中...'
|
||||
: '点击完成人机验证'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 提交 */}
|
||||
<button type="submit" className="btn-block regen-btn" disabled={loading}>
|
||||
{loading ? (
|
||||
|
||||
+34
-16
@@ -83,23 +83,28 @@ export function clearAuth(): void {
|
||||
// API
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 注册。 */
|
||||
/** 注册。captchaToken:人机验证通过后平台签发的 verifyToken。 */
|
||||
export async function register(
|
||||
phone: string,
|
||||
password: string,
|
||||
nickname?: string,
|
||||
captchaToken?: string | null,
|
||||
): Promise<AuthResponse> {
|
||||
return request<AuthResponse>('/api/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ phone, password, nickname }),
|
||||
body: JSON.stringify({ phone, password, nickname, captchaToken }),
|
||||
});
|
||||
}
|
||||
|
||||
/** 登录。 */
|
||||
export async function login(phone: string, password: string): Promise<AuthResponse> {
|
||||
/** 登录。captchaToken:人机验证通过后平台签发的 verifyToken。 */
|
||||
export async function login(
|
||||
phone: string,
|
||||
password: string,
|
||||
captchaToken?: string | null,
|
||||
): Promise<AuthResponse> {
|
||||
return request<AuthResponse>('/api/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ phone, password }),
|
||||
body: JSON.stringify({ phone, password, captchaToken }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -117,8 +122,13 @@ export async function fetchMe(token: string): Promise<{ user: AuthUser }> {
|
||||
export interface UseAuth {
|
||||
user: AuthUser | null;
|
||||
token: string | null;
|
||||
login: (phone: string, password: string) => Promise<AuthUser>;
|
||||
register: (phone: string, password: string, nickname?: string) => Promise<AuthUser>;
|
||||
login: (phone: string, password: string, captchaToken?: string | null) => Promise<AuthUser>;
|
||||
register: (
|
||||
phone: string,
|
||||
password: string,
|
||||
nickname?: string,
|
||||
captchaToken?: string | null,
|
||||
) => Promise<AuthUser>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
@@ -130,17 +140,25 @@ export function useAuth(): UseAuth {
|
||||
const [user, setUser] = useState<AuthUser | null>(() => getCachedUser());
|
||||
const [token, setToken] = useState<string | null>(() => getToken());
|
||||
|
||||
const doLogin = useCallback(async (phone: string, password: string): Promise<AuthUser> => {
|
||||
const res = await login(phone, password);
|
||||
persistAuth(res.token, res.user);
|
||||
setToken(res.token);
|
||||
setUser(res.user);
|
||||
return res.user;
|
||||
}, []);
|
||||
const doLogin = useCallback(
|
||||
async (phone: string, password: string, captchaToken?: string | null): Promise<AuthUser> => {
|
||||
const res = await login(phone, password, captchaToken);
|
||||
persistAuth(res.token, res.user);
|
||||
setToken(res.token);
|
||||
setUser(res.user);
|
||||
return res.user;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const doRegister = useCallback(
|
||||
async (phone: string, password: string, nickname?: string): Promise<AuthUser> => {
|
||||
const res = await register(phone, password, nickname);
|
||||
async (
|
||||
phone: string,
|
||||
password: string,
|
||||
nickname?: string,
|
||||
captchaToken?: string | null,
|
||||
): Promise<AuthUser> => {
|
||||
const res = await register(phone, password, nickname, captchaToken);
|
||||
persistAuth(res.token, res.user);
|
||||
setToken(res.token);
|
||||
setUser(res.user);
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* useCaptcha —— TAC(tianai-captcha 自托管)人机验证 React hook。
|
||||
*
|
||||
* 链路(与 perler-lab-server 的 requireCaptcha 对应):
|
||||
* 1. 用户点击验证按钮 → 滑块弹窗 → 平台 POST /tac/api/challenge/verify 签发 verifyToken
|
||||
* 2. 登录/注册接口携带 captchaToken = verifyToken
|
||||
* 3. 后端调平台 secondary-verify 一次性核销
|
||||
*
|
||||
* 静态资源:/tac/load.min.js(public/tac/,来源 tianai-captcha-web-sdk dist)
|
||||
* API 代理:/tac/api/** → prod1:18200/api/**(nginx 同源反代,无 CORS)
|
||||
* 站点凭证:复用 tianai-captcha-platform 站点「HomeCentral」(平台不校验域名)
|
||||
*
|
||||
* 开关:VITE_CAPTCHA_ENABLED=false 时跳过验证直接置为已通过
|
||||
* (本地开发注入,测试/生产构建不注入保持验证)
|
||||
*/
|
||||
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
|
||||
interface TacCaptchaResponse {
|
||||
code: number;
|
||||
msg?: string;
|
||||
data?: { verifyToken?: string };
|
||||
}
|
||||
|
||||
/** 对应 tianai-captcha-web-sdk 的 CaptchaConfig */
|
||||
interface TacConfig {
|
||||
bindEl: string;
|
||||
requestCaptchaDataUrl: string;
|
||||
validCaptchaUrl: string;
|
||||
requestHeaders?: Record<string, string>;
|
||||
validSuccess?: (res: TacCaptchaResponse, c: unknown, tac: TacInstance) => void;
|
||||
validFail?: (res: TacCaptchaResponse, c: unknown, tac: TacInstance) => void;
|
||||
}
|
||||
|
||||
interface TacInstance {
|
||||
init: () => TacInstance;
|
||||
reloadCaptcha: () => void;
|
||||
destroyWindow: () => void;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
loadTAC?: (url: string, config: TacConfig, style?: unknown) => Promise<TacInstance>;
|
||||
}
|
||||
}
|
||||
|
||||
/** tianai-captcha-platform 站点「HomeCentral」的 siteKey(公开标识,可暴露) */
|
||||
const SITE_KEY = '6796bad8-4369-492f-a4d7-643a93bb07f3';
|
||||
const TAC_BASE = '/tac/';
|
||||
const GENERATE_URL = '/tac/api/challenge/generate';
|
||||
const VERIFY_URL = '/tac/api/challenge/verify';
|
||||
|
||||
const CAPTCHA_ENABLED = import.meta.env.VITE_CAPTCHA_ENABLED !== 'false';
|
||||
|
||||
export type CaptchaState = 'idle' | 'loading' | 'passed';
|
||||
|
||||
export function useCaptcha(scene: string = 'auth') {
|
||||
const [state, setState] = useState<CaptchaState>('idle');
|
||||
const verifyTokenRef = useRef<string | null>(null);
|
||||
const containerId = `captcha-box-${scene}`;
|
||||
|
||||
const tacInstanceRef = useRef<TacInstance | null>(null);
|
||||
const instancePromiseRef = useRef<Promise<TacInstance> | null>(null);
|
||||
|
||||
/** 打开验证弹窗(懒加载 TAC 脚本,首次点击才拉取) */
|
||||
const show = useCallback(async () => {
|
||||
if (state === 'passed') return;
|
||||
if (!window.loadTAC) {
|
||||
console.error('[TAC] load.min.js 未加载,请检查 /tac/load.min.js 可访问性');
|
||||
return;
|
||||
}
|
||||
setState('loading');
|
||||
try {
|
||||
if (!tacInstanceRef.current) {
|
||||
instancePromiseRef.current =
|
||||
instancePromiseRef.current ||
|
||||
window.loadTAC(TAC_BASE, {
|
||||
bindEl: `#${containerId}`,
|
||||
requestCaptchaDataUrl: GENERATE_URL,
|
||||
validCaptchaUrl: VERIFY_URL,
|
||||
requestHeaders: { 'X-Site-Key': SITE_KEY },
|
||||
// 滑块校验通过:平台已签发 verifyToken → 记录、关弹窗、按钮变绿
|
||||
validSuccess: (res, _c, tac) => {
|
||||
verifyTokenRef.current = res?.data?.verifyToken ?? null;
|
||||
tac.destroyWindow();
|
||||
setState('passed');
|
||||
},
|
||||
// 校验失败:弹窗内自动刷新重试
|
||||
validFail: (_res, _c, tac) => {
|
||||
tac.reloadCaptcha();
|
||||
},
|
||||
});
|
||||
tacInstanceRef.current = await instancePromiseRef.current;
|
||||
}
|
||||
tacInstanceRef.current.init();
|
||||
} catch (err) {
|
||||
console.error('[TAC] 初始化失败:', err);
|
||||
instancePromiseRef.current = null;
|
||||
tacInstanceRef.current = null;
|
||||
setState('idle');
|
||||
}
|
||||
}, [containerId, state]);
|
||||
|
||||
/** 登录失败/切换模式后调用:verifyToken 已被消费,必须重新验证 */
|
||||
const reset = useCallback(() => {
|
||||
if (!CAPTCHA_ENABLED) return;
|
||||
verifyTokenRef.current = null;
|
||||
setState('idle');
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 提交前调用:返回 captchaToken(未启用时返回 'captcha-disabled' 占位,
|
||||
* 未通过时返回 null 由调用方提示)。
|
||||
*/
|
||||
const consumeToken = useCallback((): string | null => {
|
||||
if (!CAPTCHA_ENABLED) return 'captcha-disabled';
|
||||
return verifyTokenRef.current;
|
||||
}, []);
|
||||
|
||||
return { state, verified: state === 'passed', containerId, show, reset, consumeToken };
|
||||
}
|
||||
@@ -1434,6 +1434,42 @@ a {
|
||||
margin-top: var(--space-4);
|
||||
}
|
||||
|
||||
/* ── 人机验证按钮(TAC 滑块入口) ── */
|
||||
.captcha-btn {
|
||||
width: 100%;
|
||||
min-height: var(--touch-min);
|
||||
border: 1.5px solid var(--border-strong);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--bg-card);
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--text-sm);
|
||||
font-weight: var(--weight-medium);
|
||||
transition: border-color var(--dur-fast) ease, color var(--dur-fast) ease,
|
||||
transform var(--dur-fast) var(--ease-out);
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.captcha-btn:hover:not(:disabled) {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent-ink);
|
||||
}
|
||||
}
|
||||
|
||||
.captcha-btn:active:not(:disabled) {
|
||||
transform: scale(0.97);
|
||||
}
|
||||
|
||||
.captcha-btn:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: var(--focus-ring);
|
||||
}
|
||||
|
||||
.captcha-btn--passed {
|
||||
border-color: var(--success);
|
||||
color: var(--success);
|
||||
background: rgba(47, 158, 119, 0.06);
|
||||
}
|
||||
|
||||
/* 表单字段(AuthModal 等使用,DESIGN.md §3.2) */
|
||||
.field {
|
||||
display: flex;
|
||||
|
||||
@@ -7,4 +7,14 @@ export default defineConfig({
|
||||
target: 'es2020',
|
||||
outDir: 'dist',
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
// 本地开发:TAC 验证码 API 同源代理(需本机可访问 prod1:18200)
|
||||
'/tac/api': {
|
||||
target: 'http://38.76.218.110:18200',
|
||||
changeOrigin: true,
|
||||
rewrite: (p) => p.replace(/^\/tac\/api/, ''),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user