Compare commits
31
Commits
db0603a124
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f96f964a58 | ||
|
|
6daf5e90a2 | ||
|
|
53628476d7 | ||
|
|
18cf15c43a | ||
|
|
16311b3bd6 | ||
|
|
e7893110a3 | ||
|
|
84ca36b10b | ||
|
|
6ca418fb42 | ||
|
|
427d4878c7 | ||
|
|
4b538f613c | ||
|
|
b7599f6ea0 | ||
|
|
a537958550 | ||
|
|
a478bf1cf2 | ||
|
|
f3002f23c2 | ||
|
|
1164b51c64 | ||
|
|
d1cd371061 | ||
|
|
8f3fe7141c | ||
|
|
cb122b5b07 | ||
|
|
236ff19413 | ||
|
|
dbe9b58b0c | ||
|
|
d56958727c | ||
|
|
e7b9fd923b | ||
|
|
a7fca6ee57 | ||
|
|
cfab8ce3ac | ||
|
|
387ed937f8 | ||
|
|
fbbf3e8204 | ||
|
|
655b7faf57 | ||
|
|
356d3ab62c | ||
|
|
a4f8a99093 | ||
|
|
16e517c69e | ||
|
|
29279e8c56 |
No files matched your search
@@ -0,0 +1,232 @@
|
|||||||
|
# 2026-11-06 t3修复稿(未合入,需Token+Secrets后由用户合入):REGISTRY主迁127.0.0.1:5001;新增Secrets非空门槛
|
||||||
|
# =============================================================================
|
||||||
|
# TIANAI CAPTCHA PLATFORM — 测试环境自动部署
|
||||||
|
# 触发:push 到 master(或手动 workflow_dispatch)
|
||||||
|
# 流程:checkout → Maven 容器构建 jar → docker build → 推 Registry(:test + :sha-x)
|
||||||
|
# → SSH 到测试机(156.233.226.86) 重建容器 → 健康检查
|
||||||
|
# 架构参考:perler-lab deploy-test.yml
|
||||||
|
# =============================================================================
|
||||||
|
name: deploy-test
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [master]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: deploy-test-master
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: 156.233.226.46:5000
|
||||||
|
IMAGE: 156.233.226.46:5000/tianai-captcha-platform
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-deploy-test:
|
||||||
|
runs-on: [ubuntu-latest, hk-ci]
|
||||||
|
steps:
|
||||||
|
- name: Checkout master
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: master
|
||||||
|
|
||||||
|
- name: Setup SSH key (from secrets)
|
||||||
|
run: |
|
||||||
|
mkdir -p ~/.ssh
|
||||||
|
# T_DEPLOY_KEY=服务器钥匙(2026-11-06 队长注入,可登.86;原CAPTCHA_DEPLOY_KEY远端为空导致run#267 47s挂)
|
||||||
|
printf '%s\n' "${{ secrets.T_DEPLOY_KEY }}" > ~/.ssh/id_ed25519_deploy
|
||||||
|
chmod 600 ~/.ssh/id_ed25519_deploy
|
||||||
|
ssh-keygen -lf ~/.ssh/id_ed25519_deploy
|
||||||
|
ssh-keyscan -p 48222 -H 156.233.226.86 >> ~/.ssh/known_hosts 2>/dev/null
|
||||||
|
echo "SSH 密钥就绪"
|
||||||
|
|
||||||
|
- name: Validate required secrets
|
||||||
|
run: |
|
||||||
|
test -n "${{ secrets.T_DEPLOY_KEY }}" || { echo "ERROR: CAPTCHA_DEPLOY_KEY为空(run#134曾6s卡死于此)"; exit 1; }
|
||||||
|
test -n "156.233.226.86" || { echo "ERROR: CAPTCHA_TEST_HOST为空"; exit 1; }
|
||||||
|
test -n "${{ secrets.CAPTCHA_PROD_HOST }}" || { echo "ERROR: CAPTCHA_PROD_HOST为空"; exit 1; }
|
||||||
|
echo "Secrets非空校验通过"
|
||||||
|
|
||||||
|
- name: Build jar (Maven + JDK21 in docker, 带依赖缓存卷)
|
||||||
|
# 注意: job 容器内的路径对宿主机 daemon 不可见, 不能用 -v "$PWD" 挂载;
|
||||||
|
# 用 docker cp 流式传文件(与 build context 同机制)
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
docker volume create tianai-maven-cache >/dev/null 2>&1 || true
|
||||||
|
docker rm -f mvnbuild 2>/dev/null || true
|
||||||
|
docker run -d --name mvnbuild -v tianai-maven-cache:/root/.m2 -w /ws \
|
||||||
|
maven:3.9-eclipse-temurin-21 sleep infinity
|
||||||
|
docker cp "$GITHUB_WORKSPACE/." mvnbuild:/ws/
|
||||||
|
docker exec mvnbuild mvn -q package -DskipTests
|
||||||
|
docker cp mvnbuild:/ws/tianai-captcha-platform/target/tianai-captcha-platform-2.0.0-SNAPSHOT.jar \
|
||||||
|
"$GITHUB_WORKSPACE/tianai-captcha-platform/tianai-captcha-platform-2.0.0-SNAPSHOT.jar"
|
||||||
|
docker rm -f mvnbuild
|
||||||
|
ls -la tianai-captcha-platform/*.jar
|
||||||
|
|
||||||
|
- name: Build frontend SDK (webpack)
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
docker rm -f tacbuild 2>/dev/null || true
|
||||||
|
docker run -d --name tacbuild -w /ws node:20-alpine sleep infinity
|
||||||
|
docker cp "$GITHUB_WORKSPACE/tianai-captcha-web-sdk/." tacbuild:/ws/
|
||||||
|
docker exec tacbuild sh -c "npm install --prefer-offline && npm run buildprod"
|
||||||
|
docker cp tacbuild:/ws/dist "$GITHUB_WORKSPACE/tac-dist"
|
||||||
|
docker rm -f tacbuild
|
||||||
|
echo "=== 构建产物 ==="
|
||||||
|
ls -la "$GITHUB_WORKSPACE/tac-dist/tac/js/" "$GITHUB_WORKSPACE/tac-dist/tac/css/" 2>/dev/null
|
||||||
|
|
||||||
|
- name: Build admin dashboard (Vue3 + Vite)
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
docker rm -f adminbuild 2>/dev/null || true
|
||||||
|
docker run -d --name adminbuild -w /ws node:20-alpine sleep infinity
|
||||||
|
docker cp "$GITHUB_WORKSPACE/tianai-captcha-platform-ui/." adminbuild:/ws/
|
||||||
|
docker exec adminbuild sh -c "npm install --prefer-offline && npm run build"
|
||||||
|
docker cp adminbuild:/ws/dist "$GITHUB_WORKSPACE/admin-dist"
|
||||||
|
docker rm -f adminbuild
|
||||||
|
echo "=== 管理后台构建产物 ==="
|
||||||
|
ls -la "$GITHUB_WORKSPACE/admin-dist/" 2>/dev/null
|
||||||
|
|
||||||
|
- name: Build & push image
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
SHA=$(echo "$GITHUB_SHA" | cut -c1-8)
|
||||||
|
docker build -t $IMAGE:test -t $IMAGE:sha-$SHA tianai-captcha-platform
|
||||||
|
docker push $IMAGE:test
|
||||||
|
docker push $IMAGE:sha-$SHA
|
||||||
|
echo "已推送 $IMAGE:test 和 $IMAGE:sha-$SHA"
|
||||||
|
|
||||||
|
- name: Deploy to test env
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
SSH_CMD="ssh -p 48222 -i $HOME/.ssh/id_ed25519_deploy root@156.233.226.86"
|
||||||
|
$SSH_CMD '
|
||||||
|
set -e
|
||||||
|
echo "===== 拉取镜像 ====="
|
||||||
|
docker pull 127.0.0.1:5001/tianai-captcha-platform:test
|
||||||
|
echo "===== 重建后端容器 ====="
|
||||||
|
docker rm -f tianai-captcha 2>/dev/null || true
|
||||||
|
docker run -d --name tianai-captcha \
|
||||||
|
--network mw \
|
||||||
|
--restart unless-stopped \
|
||||||
|
-p 127.0.0.1:18200:18200 \
|
||||||
|
-v /opt/tianai/config:/app/config \
|
||||||
|
127.0.0.1:5001/tianai-captcha-platform:test
|
||||||
|
echo "===== 部署前端 SDK ====="
|
||||||
|
mkdir -p /opt/tianai/web/tac
|
||||||
|
'
|
||||||
|
# 上传前端 SDK 构建产物
|
||||||
|
scp -P 48222 -i $HOME/.ssh/id_ed25519_deploy -r "$GITHUB_WORKSPACE/tac-dist/tac"/* \
|
||||||
|
root@156.233.226.86:/opt/tianai/web/tac/
|
||||||
|
# 上传管理后台构建产物
|
||||||
|
mkdir -p /tmp/admin-dist
|
||||||
|
cp -r "$GITHUB_WORKSPACE/admin-dist/"* /tmp/admin-dist/
|
||||||
|
scp -P 48222 -i $HOME/.ssh/id_ed25519_deploy -r /tmp/admin-dist/* \
|
||||||
|
root@156.233.226.86:/opt/tianai/web/admin/
|
||||||
|
# 上传 nginx 配置
|
||||||
|
cat > /tmp/captcha-nginx.conf <<'NGINX_EOF'
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
gzip on;
|
||||||
|
gzip_static on;
|
||||||
|
gzip_types text/plain text/css application/json application/javascript text/xml image/svg+xml;
|
||||||
|
gzip_min_length 256;
|
||||||
|
|
||||||
|
# 管理后台入口文件不缓存
|
||||||
|
location = /admin/index.html {
|
||||||
|
alias /usr/share/nginx/html/admin/index.html;
|
||||||
|
add_header Cache-Control "no-cache, must-revalidate";
|
||||||
|
}
|
||||||
|
|
||||||
|
# 管理后台 (Vue3 SPA)
|
||||||
|
location /admin/ {
|
||||||
|
alias /usr/share/nginx/html/admin/;
|
||||||
|
try_files $uri $uri/ /admin/index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 后端 SDK 静态文件
|
||||||
|
location /tac/ {
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
try_files $uri $uri/ =404;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 后端 API 反代 (前端 SDK 调用)
|
||||||
|
location ^~ /tac/api/ {
|
||||||
|
proxy_pass http://tianai-captcha:18200/api/;
|
||||||
|
proxy_set_header Host $http_host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 管理后台 API 反代
|
||||||
|
location ^~ /admin/api/ {
|
||||||
|
proxy_pass http://tianai-captcha:18200/api/;
|
||||||
|
proxy_set_header Host $http_host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
NGINX_EOF
|
||||||
|
scp -P 48222 -i $HOME/.ssh/id_ed25519_deploy /tmp/captcha-nginx.conf \
|
||||||
|
root@156.233.226.86:/opt/tianai/web/nginx.conf
|
||||||
|
$SSH_CMD '
|
||||||
|
echo "===== 重建 nginx 容器 ====="
|
||||||
|
docker rm -f tianai-web 2>/dev/null || true
|
||||||
|
docker run -d --name tianai-web \
|
||||||
|
--network mw \
|
||||||
|
--restart unless-stopped \
|
||||||
|
-p 0.0.0.0:8080:80 \
|
||||||
|
-v /opt/tianai/web:/usr/share/nginx/html:ro \
|
||||||
|
-v /opt/tianai/web/nginx.conf:/etc/nginx/conf.d/default.conf:ro \
|
||||||
|
nginx:alpine
|
||||||
|
sleep 3
|
||||||
|
docker ps --filter name=tianai-web --format "{{.Names}} {{.Status}}"
|
||||||
|
'
|
||||||
|
|
||||||
|
- name: Health check (generate API + 前端页面)
|
||||||
|
env:
|
||||||
|
TEST_SITE_KEY: 6a062b70-c0b3-428e-8f1b-cca402e67ddd
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
SSH_CMD="ssh -p 48222 -i $HOME/.ssh/id_ed25519_deploy root@156.233.226.86"
|
||||||
|
OK=0
|
||||||
|
CODE=000
|
||||||
|
for i in $(seq 1 24); do
|
||||||
|
CODE=$($SSH_CMD "curl -s -X POST 'http://127.0.0.1:18200/api/challenge/generate' -H 'X-Site-Key: $TEST_SITE_KEY'" | python3 -c "import json,sys; print(json.load(sys.stdin).get('code'))" 2>/dev/null || echo 000)
|
||||||
|
if [ "$CODE" = "200" ]; then OK=1; break; fi
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
if [ "$OK" != "1" ]; then
|
||||||
|
echo "后端 API 健康检查失败 (code=$CODE)"
|
||||||
|
$SSH_CMD 'docker logs tianai-captcha --tail 30' || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "后端 API 健康检查 OK (code=$CODE)"
|
||||||
|
# 检查前端 SDK
|
||||||
|
HTTP_CODE=$($SSH_CMD "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/tac/js/tac.min.js" 2>/dev/null || echo 000)
|
||||||
|
if [ "$HTTP_CODE" = "200" ]; then
|
||||||
|
echo "前端 SDK 部署 OK (http_code=$HTTP_CODE)"
|
||||||
|
else
|
||||||
|
echo "前端 SDK 部署异常 (http_code=$HTTP_CODE)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
# 检查管理后台
|
||||||
|
ADMIN_CODE=$($SSH_CMD "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/admin/" 2>/dev/null || echo 000)
|
||||||
|
if [ "$ADMIN_CODE" = "200" ]; then
|
||||||
|
echo "管理后台部署 OK (http_code=$ADMIN_CODE)"
|
||||||
|
else
|
||||||
|
echo "管理后台部署异常 (http_code=$ADMIN_CODE)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Deployment summary
|
||||||
|
if: always()
|
||||||
|
run: |
|
||||||
|
echo "commit: $GITHUB_SHA"
|
||||||
|
echo "后端 API: http://<test-ip>:8080/tac/api/... (proxy → tianai-captcha:18200)"
|
||||||
|
echo "前端 SDK: http://<test-ip>:8080/tac/js/tac.min.js"
|
||||||
|
echo "管理后台: http://<test-ip>:8080/admin/"
|
||||||
|
echo "晋升生产: Gitea → 仓库 → Actions → promote-prod → 输入 yes"
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
# =============================================================================
|
||||||
|
# TIANAI CAPTCHA PLATFORM — 生产环境晋升(手动触发器)
|
||||||
|
# 触发:Gitea Actions 页面手动 workflow_dispatch,confirm 必须输入 yes
|
||||||
|
# 流程:从测试机导出当前 :test 镜像 → scp 到 prod1 → docker load
|
||||||
|
# → 备份旧镜像 → 重建容器 → 健康检查
|
||||||
|
# 说明:prod1 的 docker daemon 未配置 insecure-registries(改它需要重启 daemon
|
||||||
|
# = 重启全部生产容器),因此不走 registry pull,用 save/scp/load 传递镜像。
|
||||||
|
# =============================================================================
|
||||||
|
name: promote-prod
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
confirm:
|
||||||
|
description: '确认部署到生产环境(prod1)? 输入 yes'
|
||||||
|
required: true
|
||||||
|
default: 'no'
|
||||||
|
|
||||||
|
env:
|
||||||
|
IMAGE: 38.76.218.110:5000/tianai-captcha-platform
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
promote-prod:
|
||||||
|
runs-on: [ubuntu-latest, hk-ci]
|
||||||
|
# job 级 env: shell 变量不跨 step, 必须在这里声明才能在所有 step 中使用
|
||||||
|
env:
|
||||||
|
TEST: ${{ secrets.CAPTCHA_TEST_HOST }}
|
||||||
|
PROD: ${{ secrets.CAPTCHA_PROD_HOST }}
|
||||||
|
if: github.event.inputs.confirm == 'yes'
|
||||||
|
steps:
|
||||||
|
- name: Setup SSH key (from secrets)
|
||||||
|
run: |
|
||||||
|
mkdir -p ~/.ssh
|
||||||
|
printf '%s\n' "${{ secrets.CAPTCHA_DEPLOY_KEY }}" > ~/.ssh/id_ed25519_deploy
|
||||||
|
chmod 600 ~/.ssh/id_ed25519_deploy
|
||||||
|
ssh-keyscan -H ${{ secrets.CAPTCHA_TEST_HOST }} >> ~/.ssh/known_hosts 2>/dev/null
|
||||||
|
ssh-keyscan -H ${{ secrets.CAPTCHA_PROD_HOST }} >> ~/.ssh/known_hosts 2>/dev/null
|
||||||
|
echo "SSH 密钥就绪"
|
||||||
|
|
||||||
|
- name: Export test image (test → runner)
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
SSH_KEY="$HOME/.ssh/id_ed25519_deploy"
|
||||||
|
ssh -p 48222 -i $SSH_KEY root@$TEST \
|
||||||
|
"docker pull $IMAGE:test >/dev/null && docker save $IMAGE:test | gzip > /tmp/tianai-promote.tar.gz && ls -la /tmp/tianai-promote.tar.gz"
|
||||||
|
scp -P 48222 -i $SSH_KEY root@$TEST:/tmp/tianai-promote.tar.gz /tmp/tianai-promote.tar.gz
|
||||||
|
echo "镜像已下载到 runner"
|
||||||
|
|
||||||
|
- name: Transfer to prod1 (runner → prod1)
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
SSH_KEY="$HOME/.ssh/id_ed25519_deploy"
|
||||||
|
scp -P 48222 -i $SSH_KEY /tmp/tianai-promote.tar.gz root@$PROD:/tmp/
|
||||||
|
ssh -p 48222 -i $SSH_KEY root@$TEST 'rm -f /tmp/tianai-promote.tar.gz'
|
||||||
|
rm -f /tmp/tianai-promote.tar.gz
|
||||||
|
echo "镜像已传输到 prod1"
|
||||||
|
|
||||||
|
- name: Load & restart container on prod1
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
SSH_KEY="$HOME/.ssh/id_ed25519_deploy"
|
||||||
|
ssh -p 48222 -i $SSH_KEY root@$PROD '
|
||||||
|
set -e
|
||||||
|
echo "===== 备份当前生产镜像 ====="
|
||||||
|
docker tag tianai-captcha-platform:latest tianai-captcha-platform:backup-$(date +%Y%m%d-%H%M) 2>/dev/null \
|
||||||
|
&& echo "已备份" || echo "无旧镜像可备份"
|
||||||
|
echo "===== 加载新镜像 ====="
|
||||||
|
docker load < /tmp/tianai-promote.tar.gz
|
||||||
|
docker tag '"$IMAGE"':test tianai-captcha-platform:latest
|
||||||
|
rm -f /tmp/tianai-promote.tar.gz
|
||||||
|
echo "===== 重建容器 ====="
|
||||||
|
docker rm -f tianai-captcha 2>/dev/null || true
|
||||||
|
docker run -d --name tianai-captcha \
|
||||||
|
--network middleware \
|
||||||
|
--restart unless-stopped \
|
||||||
|
-p 18200:18200 \
|
||||||
|
-v /opt/tianai/config:/app/config \
|
||||||
|
tianai-captcha-platform:latest
|
||||||
|
sleep 15
|
||||||
|
docker ps --filter name=tianai-captcha --format "{{.Names}} {{.Status}}"
|
||||||
|
docker logs tianai-captcha 2>&1 | tail -3
|
||||||
|
'
|
||||||
|
|
||||||
|
- name: Health check prod (generate API, 校验 JSON code 而非 HTTP 状态)
|
||||||
|
env:
|
||||||
|
PROD_SITE_KEY: 6796bad8-4369-492f-a4d7-643a93bb07f3
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
SSH_KEY="$HOME/.ssh/id_ed25519_deploy"
|
||||||
|
OK=0
|
||||||
|
CODE=000
|
||||||
|
for i in $(seq 1 24); do
|
||||||
|
CODE=$(ssh -p 48222 -i $SSH_KEY root@$PROD "curl -s -X POST 'http://127.0.0.1:18200/api/challenge/generate' -H 'X-Site-Key: $PROD_SITE_KEY'" | python3 -c "import json,sys; print(json.load(sys.stdin).get('code'))" 2>/dev/null || echo 000)
|
||||||
|
if [ "$CODE" = "200" ]; then OK=1; break; fi
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
if [ "$OK" != "1" ]; then
|
||||||
|
echo "生产健康检查失败 (code=$CODE)"
|
||||||
|
ssh -p 48222 -i $SSH_KEY root@$PROD 'docker logs tianai-captcha --tail 30' || true
|
||||||
|
echo "如需回滚: ssh prod1 后执行 docker rm -f tianai-captcha 并用 backup-xxx 标签重建容器"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "生产环境健康检查 OK (code=$CODE)"
|
||||||
|
|
||||||
|
- name: Promotion summary
|
||||||
|
if: always()
|
||||||
|
run: |
|
||||||
|
echo "生产访问: prod1 :18200 (middleware 网络: tianai-captcha:18200)"
|
||||||
|
echo "回滚方式: prod1 上 docker tag tianai-captcha-platform:backup-YYYYMMDD-HHMM tianai-captcha-platform:latest 后重建容器"
|
||||||
@@ -26,3 +26,10 @@ target
|
|||||||
|
|
||||||
.flattened-pom.xml
|
.flattened-pom.xml
|
||||||
**/.flattened-pom.xml
|
**/.flattened-pom.xml
|
||||||
|
|
||||||
|
### 本地环境 ###
|
||||||
|
node_modules/
|
||||||
|
*.log
|
||||||
|
.omo/
|
||||||
|
.codegraph/
|
||||||
|
tianai-captcha-platform-ui/dist/
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
# AGENTS.md - tianai-captcha-enhanced
|
||||||
|
|
||||||
|
## 项目概述
|
||||||
|
|
||||||
|
基于 tianai-captcha 1.5.5 开源版的增强版行为验证码,目标是复现增强版全部功能并自建验证码服务平台。
|
||||||
|
|
||||||
|
## 技术栈
|
||||||
|
|
||||||
|
| 组件 | 版本 |
|
||||||
|
|------|------|
|
||||||
|
| JDK | 21 (Microsoft OpenJDK 21.0.11 LTS) |
|
||||||
|
| Maven | 3.9.16 |
|
||||||
|
| Spring Boot | 3.4.5 |
|
||||||
|
| Lombok | 1.18.42 (后续逐步移除) |
|
||||||
|
| SLF4J | 2.0.17 |
|
||||||
|
| ONNX Runtime | 1.22.0 (ML推理,待引入) |
|
||||||
|
|
||||||
|
## 环境路径
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:JAVA_HOME = "C:\Users\USER879511\.jdks\ms-21.0.11"
|
||||||
|
$env:PATH = "$env:JAVA_HOME\bin;$env:PATH"
|
||||||
|
$Maven = "D:\Middleware\environment\apache-maven-3.9.16\bin\mvn.cmd"
|
||||||
|
```
|
||||||
|
|
||||||
|
## 构建 & 验证
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:JAVA_HOME = "C:\Users\USER879511\.jdks\ms-21.0.11"
|
||||||
|
& "D:\Middleware\environment\apache-maven-3.9.16\bin\mvn.cmd" -f "D:\tianai-captcha-enhanced\pom.xml" compile
|
||||||
|
& "D:\Middleware\environment\apache-maven-3.9.16\bin\mvn.cmd" -f "D:\tianai-captcha-enhanced\pom.xml" package -DskipTests
|
||||||
|
```
|
||||||
|
|
||||||
|
## 项目版本
|
||||||
|
|
||||||
|
从 `1.5.5` 升级到 `2.0.0-SNAPSHOT`,表示这是增强版的开发版本。
|
||||||
|
|
||||||
|
## 模块结构
|
||||||
|
|
||||||
|
```
|
||||||
|
tianai-captcha-enhanced/
|
||||||
|
├── tianai-captcha/ # 核心模块 (JDK 21, Spring Boot 3.4)
|
||||||
|
├── tianai-captcha-springboot-starter/ # Spring Boot Starter (3.4.5)
|
||||||
|
├── tianai-captcha-web-sdk/ # 前端SDK (待增强)
|
||||||
|
├── tianai-captcha-platform/ # 管理平台后端 (待创建)
|
||||||
|
└── tianai-captcha-platform-ui/ # 管理平台前端 (待创建)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 增强版功能计划
|
||||||
|
|
||||||
|
### 验证码类型 (对标官网16种)
|
||||||
|
|
||||||
|
| 类型 | 常量 | 开源版 | 增强版 | 优先级 |
|
||||||
|
|------|------|:------:|:------:|:------:|
|
||||||
|
| 滑块验证 | SLIDER | ✅ | ✅ | P0 |
|
||||||
|
| 滑块验证V2 | SLIDER_V2 | ❌ | 🔜 | P1 |
|
||||||
|
| 曲线滑块 | CURVE_SLIDER | ❌ | 🔜 | P1 |
|
||||||
|
| 曲线滑块V2 | CURVE_SLIDER_V2 | ❌ | 🔜 | P2 |
|
||||||
|
| 曲线滑块V3 | CURVE_SLIDER_V3 | ❌ | 🔜 | P2 |
|
||||||
|
| 旋转验证 | ROTATE | ✅ | ✅ | P0 |
|
||||||
|
| 滑动还原 | CONCAT | ✅ | ✅ | P0 |
|
||||||
|
| 角度验证 | ANGLE | ❌ | 🔜 | P1 |
|
||||||
|
| 刮刮乐 | SCRATCH | ❌ | 🔜 | P1 |
|
||||||
|
| 文字点选 | WORD_IMAGE_CLICK | ✅ | ✅ | P0 |
|
||||||
|
| 图标点选 | ICON_CLICK | ❌ | 🔜 | P1 |
|
||||||
|
| 语序点选 | WORD_ORDER_CLICK | ❌ | 🔜 | P1 |
|
||||||
|
| 乱序拼图 | JIGSAW | ❌ | 🔜 | P1 |
|
||||||
|
| 曲线绘制 | CURVE_DRAW | ❌ | 🔜 | P2 |
|
||||||
|
| 工作量证明 | PROOF_OF_WORK | ❌ | 🔜 | P2 |
|
||||||
|
| 随机 | RANDOM | ✅ | ✅ | P0 |
|
||||||
|
|
||||||
|
### 增强功能 (对标付费版10项)
|
||||||
|
|
||||||
|
| 功能 | 优先级 | 状态 |
|
||||||
|
|------|:------:|:----:|
|
||||||
|
| 全新加密算法 (AES-256 + RSA-4096 + SHA256) | P0 | 🔜 |
|
||||||
|
| ML轨迹校验器 (规则引擎 + ONNX) | P0 | 🔜 |
|
||||||
|
| 位置校验 (动态容错) | P0 | ✅ 已有基础 |
|
||||||
|
| 验证码背景乱序 | P1 | 🔜 |
|
||||||
|
| 差异校验 (防重放) | P1 | 🔜 |
|
||||||
|
| 请求次数校验 (滑动窗口限流) | P1 | 🔜 |
|
||||||
|
| 点选类图片背景扭曲 | P1 | 🔜 |
|
||||||
|
| IP禁用 | P1 | 🔜 |
|
||||||
|
| 轨迹相似性校验 (DTW) | P2 | 🔜 |
|
||||||
|
| 轨迹段落区分 | P2 | 🔜 |
|
||||||
|
|
||||||
|
### 平台化功能
|
||||||
|
|
||||||
|
| 功能 | 状态 |
|
||||||
|
|------|:----:|
|
||||||
|
| 站点管理 (SiteKey/SecretKey) | 🔜 |
|
||||||
|
| verifyToken 一次性消费 | 🔜 |
|
||||||
|
| 前端SDK (兼容TPCaptcha API) | 🔜 |
|
||||||
|
| 管理后台 | 🔜 |
|
||||||
|
| 统计监控 | 🔜 |
|
||||||
|
|
||||||
|
## 编码规范
|
||||||
|
|
||||||
|
- 包结构遵循开源版: application/generator/validator/resource/interceptor/cache/common
|
||||||
|
- 新增包: crypto/obfuscator/risk/site/ml
|
||||||
|
- API 响应统一使用 ApiResponse<T>
|
||||||
|
- 暂时保留 Lombok,后续逐步替换为手写 getter/setter
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
必须用中文回复我
|
||||||
|
## Project Overview
|
||||||
|
|
||||||
|
tianai-captcha (天爱验证码/TAC) is a Java-based behavioral CAPTCHA library supporting multiple verification types:
|
||||||
|
- **SLIDER**: Slide-to-fit puzzle captcha
|
||||||
|
- **ROTATE**: Rotation verification captcha
|
||||||
|
- **CONCAT**: Slide-to-restore captcha
|
||||||
|
- **WORD_IMAGE_CLICK**: Text-click verification captcha
|
||||||
|
|
||||||
|
The project is a multi-module Maven project with Java 8 compatibility.
|
||||||
|
|
||||||
|
## Build Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Build the entire project (skips tests by default)
|
||||||
|
mvn clean install
|
||||||
|
|
||||||
|
# Build without skipping tests
|
||||||
|
mvn clean install -DskipTests=false
|
||||||
|
|
||||||
|
# Build specific module
|
||||||
|
cd tianai-captcha
|
||||||
|
mvn clean install
|
||||||
|
|
||||||
|
# Package for deployment
|
||||||
|
mvn clean package
|
||||||
|
|
||||||
|
# Generate javadoc
|
||||||
|
mvn javadoc:javadoc
|
||||||
|
```
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Run all tests
|
||||||
|
mvn test
|
||||||
|
|
||||||
|
# Run tests for specific module
|
||||||
|
cd tianai-captcha
|
||||||
|
mvn test
|
||||||
|
|
||||||
|
# Run a specific test class
|
||||||
|
mvn test -Dtest=TACBuilderTest
|
||||||
|
|
||||||
|
# Run a specific test method
|
||||||
|
mvn test -Dtest=TACBuilderTest#testMethod
|
||||||
|
```
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
### Modules
|
||||||
|
|
||||||
|
1. **tianai-captcha** (core module)
|
||||||
|
- Core captcha generation and validation logic
|
||||||
|
- Generator implementations for each captcha type
|
||||||
|
- Resource management system
|
||||||
|
- Cache and storage abstractions
|
||||||
|
|
||||||
|
2. **tianai-captcha-springboot-starter**
|
||||||
|
- Spring Boot auto-configuration
|
||||||
|
- Redis integration support
|
||||||
|
- Configuration properties binding
|
||||||
|
|
||||||
|
3. **tianai-captcha-solon-plugin**
|
||||||
|
- Solon framework integration
|
||||||
|
|
||||||
|
4. **tianai-captcha-web-sdk**
|
||||||
|
- Frontend JavaScript SDK
|
||||||
|
|
||||||
|
## Core Architecture
|
||||||
|
|
||||||
|
### Key Components
|
||||||
|
|
||||||
|
**ImageCaptchaApplication** (cloud.tianai.captcha.application.ImageCaptchaApplication)
|
||||||
|
- Main entry point for captcha operations
|
||||||
|
- Handles captcha generation via `generateCaptcha(type)`
|
||||||
|
- Handles validation via `matching(id, matchParam)`
|
||||||
|
- Manages lifecycle of generators, validators, and cache
|
||||||
|
|
||||||
|
**TACBuilder** (cloud.tianai.captcha.application.TACBuilder)
|
||||||
|
- Builder pattern for constructing ImageCaptchaApplication
|
||||||
|
- Fluent API for configuration
|
||||||
|
- Key methods:
|
||||||
|
- `addDefaultTemplate()`: Load built-in templates
|
||||||
|
- `addResource(type, resource)`: Add background images
|
||||||
|
- `addTemplate(type, resourceMap)`: Add custom templates
|
||||||
|
- `addFont(resource)`: Add fonts for WORD_IMAGE_CLICK
|
||||||
|
- `cached(size, waitTime, period, expireTime)`: Enable pre-generation cache
|
||||||
|
- `setCacheStore(store)`: Set cache implementation (local or distributed)
|
||||||
|
- `setResourceStore(store)`: Set resource storage
|
||||||
|
- `setTransform(transform)`: Set image transformation (default: Base64)
|
||||||
|
|
||||||
|
### Generator Layer
|
||||||
|
|
||||||
|
**MultiImageCaptchaGenerator** (cloud.tianai.captcha.generator.impl.MultiImageCaptchaGenerator)
|
||||||
|
- Delegates to specific generators based on captcha type
|
||||||
|
- Manages resource loading and image transformation
|
||||||
|
|
||||||
|
**Specific Generators**:
|
||||||
|
- `StandardSliderImageCaptchaGenerator`: Generates slider puzzles
|
||||||
|
- `StandardRotateImageCaptchaGenerator`: Generates rotation captchas
|
||||||
|
- `StandardConcatImageCaptchaGenerator`: Generates slide-to-restore captchas
|
||||||
|
- `StandardWordClickImageCaptchaGenerator`: Generates text-click captchas
|
||||||
|
|
||||||
|
**CacheImageCaptchaGenerator** (cloud.tianai.captcha.generator.impl.CacheImageCaptchaGenerator)
|
||||||
|
- Wrapper that pre-generates captchas for improved performance
|
||||||
|
- Configurable cache size and refresh intervals
|
||||||
|
|
||||||
|
### Validator Layer
|
||||||
|
|
||||||
|
**ImageCaptchaValidator** (cloud.tianai.captcha.validator.ImageCaptchaValidator)
|
||||||
|
- Interface for captcha validation logic
|
||||||
|
- Default implementation: `SimpleImageCaptchaValidator`
|
||||||
|
|
||||||
|
**BasicCaptchaTrackValidator** (cloud.tianai.captcha.validator.impl.BasicCaptchaTrackValidator)
|
||||||
|
- Validates mouse/touch track data
|
||||||
|
- Checks for suspicious behavior patterns
|
||||||
|
|
||||||
|
### Resource Management
|
||||||
|
|
||||||
|
**ResourceStore** (cloud.tianai.captcha.resource.ResourceStore)
|
||||||
|
- Abstraction for storing captcha resources (images, templates)
|
||||||
|
- Implementations:
|
||||||
|
- `LocalMemoryResourceStore`: In-memory storage
|
||||||
|
- Custom implementations for distributed scenarios
|
||||||
|
|
||||||
|
**ImageCaptchaResourceManager** (cloud.tianai.captcha.resource.ImageCaptchaResourceManager)
|
||||||
|
- Manages resource loading and retrieval
|
||||||
|
- Default implementation: `DefaultImageCaptchaResourceManager`
|
||||||
|
|
||||||
|
**Resource** (cloud.tianai.captcha.resource.common.model.dto.Resource)
|
||||||
|
- Represents a resource with type and location
|
||||||
|
- Types: "classpath", "file", "url"
|
||||||
|
|
||||||
|
### Cache Layer
|
||||||
|
|
||||||
|
**CacheStore** (cloud.tianai.captcha.cache.CacheStore)
|
||||||
|
- Abstraction for caching captcha data
|
||||||
|
- Implementations:
|
||||||
|
- `LocalCacheStore`: Local in-memory cache
|
||||||
|
- Redis-based implementation in Spring Boot starter
|
||||||
|
|
||||||
|
### Image Transformation
|
||||||
|
|
||||||
|
**ImageTransform** (cloud.tianai.captcha.generator.ImageTransform)
|
||||||
|
- Converts generated images to desired format
|
||||||
|
- Default: `Base64ImageTransform` (JPG for background, PNG for template)
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
### Non-Spring Projects
|
||||||
|
|
||||||
|
Use TACBuilder to configure:
|
||||||
|
|
||||||
|
```java
|
||||||
|
ImageCaptchaApplication app = TACBuilder.builder()
|
||||||
|
.addDefaultTemplate()
|
||||||
|
.addResource("SLIDER", new Resource("classpath", "path/to/image.jpg"))
|
||||||
|
.cached(20, 5000, 2000, 120000L)
|
||||||
|
.build();
|
||||||
|
```
|
||||||
|
|
||||||
|
### Spring Boot Projects
|
||||||
|
|
||||||
|
Configure via application.yml:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
captcha:
|
||||||
|
prefix: captcha # Cache key prefix
|
||||||
|
expire:
|
||||||
|
default: 120000 # Default expiration (ms)
|
||||||
|
WORD_IMAGE_CLICK: 180000 # Type-specific expiration
|
||||||
|
init-default-resource: false # Load built-in resources
|
||||||
|
local-cache-enabled: true # Enable pre-generation cache
|
||||||
|
local-cache-size: 20 # Cache size
|
||||||
|
local-cache-wait-time: 5000 # Wait time on cache miss (ms)
|
||||||
|
local-cache-period: 2000 # Cache refresh interval (ms)
|
||||||
|
font-path: # Font files for WORD_IMAGE_CLICK
|
||||||
|
- classpath:font/simhei.ttf
|
||||||
|
```
|
||||||
|
|
||||||
|
## Important Constants
|
||||||
|
|
||||||
|
**CaptchaTypeConstant** (cloud.tianai.captcha.common.constant.CaptchaTypeConstant)
|
||||||
|
- `SLIDER`: Slide-to-fit captcha
|
||||||
|
- `ROTATE`: Rotation captcha
|
||||||
|
- `CONCAT`: Slide-to-restore captcha
|
||||||
|
- `WORD_IMAGE_CLICK`: Text-click captcha
|
||||||
|
|
||||||
|
**ParamKeyEnum** (cloud.tianai.captcha.generator.common.model.dto.ParamKeyEnum)
|
||||||
|
- `TOLERANT`: Configurable tolerance value for validation (added in recent commit)
|
||||||
|
|
||||||
|
## Key Data Flow
|
||||||
|
|
||||||
|
### Generation Flow
|
||||||
|
1. Client calls `ImageCaptchaApplication.generateCaptcha(type)`
|
||||||
|
2. `MultiImageCaptchaGenerator` selects appropriate generator
|
||||||
|
3. Generator loads resources via `ImageCaptchaResourceManager`
|
||||||
|
4. Generator creates captcha with random parameters
|
||||||
|
5. `ImageTransform` converts images to Base64 (or custom format)
|
||||||
|
6. Captcha data cached in `CacheStore` with unique ID
|
||||||
|
7. Returns `ImageCaptchaVO` with ID and image data
|
||||||
|
|
||||||
|
### Validation Flow
|
||||||
|
1. Client submits ID and track data via `matching(id, matchParam)`
|
||||||
|
2. Application retrieves cached captcha data by ID
|
||||||
|
3. `ImageCaptchaValidator` validates track against expected answer
|
||||||
|
4. `BasicCaptchaTrackValidator` checks track behavior patterns
|
||||||
|
5. Returns `ApiResponse` with success/failure status
|
||||||
|
|
||||||
|
## Extension Points
|
||||||
|
|
||||||
|
- **Custom Generators**: Implement `ImageCaptchaGenerator` interface
|
||||||
|
- **Custom Validators**: Implement `ImageCaptchaValidator` interface
|
||||||
|
- **Custom Cache**: Implement `CacheStore` (e.g., Redis, Memcached)
|
||||||
|
- **Custom Resources**: Implement `ResourceStore` for centralized resource management
|
||||||
|
- **Custom Transform**: Implement `ImageTransform` for different image formats
|
||||||
|
- **Interceptors**: Implement `CaptchaInterceptor` for pre/post processing
|
||||||
|
|
||||||
|
## Recent Changes
|
||||||
|
|
||||||
|
- Added support for Spring Boot 4 (commit: db0603a, 7c8730f)
|
||||||
|
- Fixed resource leak issues (commits: 16e517c, 29279e8)
|
||||||
|
- Added configurable tolerance value via `ParamKeyEnum.TOLERANT` (commit: a4f8a99)
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
- Online Demo: http://captcha.tianai.cloud
|
||||||
|
- Online Documentation: http://doc.captcha.tianai.cloud
|
||||||
|
- License: MulanPSL-2.0
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
[{"name":"speedPhaseCorrelation","weight":0.6909424674992277,"hMean":0.955714239708839,"bMean":0.37967247512170127,"hStd":0.7442769634838727,"bStd":0.7631401323344459,"lowThreshold":-1.1466077895471904,"highThreshold":1.905952739790593,"separation":0.38188493499845555},{"name":"yDirectionChanges","weight":0.6565594255113425,"hMean":0.16129032258064516,"bMean":0.0,"hStd":0.5141089500164266,"bStd":0.0,"lowThreshold":0.0,"highThreshold":0.0,"separation":0.31311885102268494},{"name":"startOffset","weight":0.6133086990872181,"hMean":54.39618866626594,"bMean":14.656055315776996,"hStd":125.3553265098474,"bStd":50.005908122726716,"lowThreshold":-85.35576092967644,"highThreshold":114.66787156123043,"separation":0.22661739817443616},{"name":"xUniformity","weight":0.6037572020042908,"hMean":41.97851401736458,"bMean":16.237024125419424,"hStd":93.48773946787334,"bStd":30.558022562586117,"lowThreshold":-44.87902099975281,"highThreshold":77.35306925059166,"separation":0.2075144040085817},{"name":"speedVariance","weight":0.5856956110673432,"hMean":74.39660229654821,"bMean":530.9315858041267,"hStd":295.3999286413061,"bStd":2368.3001513872487,"lowThreshold":-516.403254986064,"highThreshold":665.1964595791603,"separation":0.17139122213468655},{"name":"accelerationVariance","weight":0.5814165154169918,"hMean":128.33025463499524,"bMean":1173.3393963589565,"hStd":549.7412804607712,"bStd":5867.930696402256,"lowThreshold":-971.1523062865472,"highThreshold":1227.8128155565378,"separation":0.16283303083398368},{"name":"totalDuration","weight":0.5686726385595083,"hMean":3488.8387096774195,"bMean":33173.4367816092,"hStd":3768.1041018491687,"bStd":212363.08407772906,"lowThreshold":-4047.369494020918,"highThreshold":11025.046913375758,"separation":0.13734527711901662},{"name":"pauses","weight":0.568510610386744,"hMean":6.32258064516129,"bMean":4.873563218390805,"hStd":4.222727270181567,"bStd":6.35140422106299,"lowThreshold":-7.829245223735175,"highThreshold":17.576371660516784,"separation":0.13702122077348794},{"name":"pathEfficiency","weight":0.5649463332759833,"hMean":0.765124453338266,"bMean":0.6726903175221292,"hStd":0.32528093053197915,"bStd":0.38533842620173075,"lowThreshold":-0.09798653488133235,"highThreshold":1.4433671699255908,"separation":0.12989266655196666},{"name":"overshootRatio","weight":0.5606943125493219,"hMean":0.10818778344940755,"bMean":5.116671776291968,"hStd":0.3023070391177473,"bStd":40.95660498948067,"lowThreshold":-0.4964262947860871,"highThreshold":0.7128018616849021,"separation":0.12138862509864388},{"name":"totalPoints","weight":0.5332468203395597,"hMean":76.93548387096774,"bMean":89.47126436781609,"hStd":71.92017774381091,"bStd":116.60482818422503,"lowThreshold":-66.90487161665408,"highThreshold":220.77583935858956,"separation":0.06649364067911935},{"name":"speedSkewness","weight":0.531573374575929,"hMean":2.6601663008886245,"bMean":2.2463177619223123,"hStd":3.3705027899373414,"bStd":3.1822556303270444,"lowThreshold":-4.1181934987317765,"highThreshold":8.6108290225764,"separation":0.06314674915185799},{"name":"maxJumpDistance","weight":0.5295855247419992,"hMean":113.78601562767373,"bMean":97.8237766984338,"hStd":158.22646306898454,"bStd":111.53687385656968,"lowThreshold":-125.24997101470557,"highThreshold":320.89752441157316,"separation":0.059171049483998206},{"name":"straightness","weight":0.503498502203403,"hMean":0.16895565571775595,"bMean":0.17599076422921264,"hStd":0.6278592842222325,"bStd":0.37658648977407716,"lowThreshold":-1.086762912726709,"highThreshold":1.4246742241622208,"separation":0.0069970044068060466}]
|
||||||
@@ -12,27 +12,27 @@
|
|||||||
<modules>
|
<modules>
|
||||||
<module>tianai-captcha</module>
|
<module>tianai-captcha</module>
|
||||||
<module>tianai-captcha-springboot-starter</module>
|
<module>tianai-captcha-springboot-starter</module>
|
||||||
<module>tianai-captcha-solon-plugin</module>
|
<module>tianai-captcha-platform</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<revision>1.5.3</revision>
|
<revision>2.0.0-SNAPSHOT</revision>
|
||||||
<java.version>1.8</java.version>
|
<java.version>21</java.version>
|
||||||
<!-- 打包跳过单元测试 -->
|
<maven.compiler.source>21</maven.compiler.source>
|
||||||
|
<maven.compiler.target>21</maven.compiler.target>
|
||||||
|
<maven.compiler.release>21</maven.compiler.release>
|
||||||
<skipTests>true</skipTests>
|
<skipTests>true</skipTests>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||||
|
|
||||||
<skip.nexus>false</skip.nexus>
|
<spring-boot.version>3.4.5</spring-boot.version>
|
||||||
<serverId>ossrh</serverId>
|
<lombok.version>1.18.42</lombok.version>
|
||||||
<deplay.repository>https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/</deplay.repository>
|
<slf4j.version>2.0.17</slf4j.version>
|
||||||
<deplay.snapshotRepository>https://s01.oss.sonatype.org/content/repositories/snapshots</deplay.snapshotRepository>
|
<gson.version>2.13.1</gson.version>
|
||||||
|
<onnx-runtime.version>1.22.0</onnx-runtime.version>
|
||||||
|
|
||||||
<!-- 私服 -->
|
<skip.nexus>true</skip.nexus>
|
||||||
<!-- <skip.nexus>true</skip.nexus>-->
|
<serverId>ossrh</serverId>
|
||||||
<!-- <deplay.id>smart</deplay.id>-->
|
|
||||||
<!-- <deplay.repository>http://192.168.3.10:6061/repository/smart_hosted/</deplay.repository>-->
|
|
||||||
<!-- <deplay.snapshotRepository>http://192.168.3.10:6061/repository/smart_hosted/</deplay.snapshotRepository>-->
|
|
||||||
</properties>
|
</properties>
|
||||||
<licenses>
|
<licenses>
|
||||||
<license>
|
<license>
|
||||||
@@ -69,11 +69,10 @@
|
|||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<!-- 统一版本号管理 -->
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.codehaus.mojo</groupId>
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
<artifactId>flatten-maven-plugin</artifactId>
|
<artifactId>flatten-maven-plugin</artifactId>
|
||||||
<version>1.2.7</version>
|
<version>1.7.0</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<updatePomFile>true</updatePomFile>
|
<updatePomFile>true</updatePomFile>
|
||||||
<flattenMode>resolveCiFriendliesOnly</flattenMode>
|
<flattenMode>resolveCiFriendliesOnly</flattenMode>
|
||||||
@@ -97,75 +96,23 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-javadoc-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>2.9.1</version>
|
<version>3.14.0</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<!-- 统一生成聚合文档,解决 mvn package 时控制台发出 javadoc 警告的问题 -->
|
<release>21</release>
|
||||||
<aggregate>true</aggregate>
|
<compilerArgument>-parameters</compilerArgument>
|
||||||
<failOnError>false</failOnError>
|
<annotationProcessorPaths>
|
||||||
<detectLinks>false</detectLinks>
|
<path>
|
||||||
</configuration>
|
<groupId>org.projectlombok</groupId>
|
||||||
<executions>
|
<artifactId>lombok</artifactId>
|
||||||
<execution>
|
<version>${lombok.version}</version>
|
||||||
<id>attach-javadocs</id>
|
</path>
|
||||||
<goals>
|
</annotationProcessorPaths>
|
||||||
<goal>jar</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<additionalparam>-Xdoclint:none</additionalparam>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-source-plugin</artifactId>
|
|
||||||
<version>2.2.1</version>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<id>attach-sources</id>
|
|
||||||
<goals>
|
|
||||||
<goal>jar-no-fork</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-gpg-plugin</artifactId>
|
|
||||||
<version>1.5</version>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<id>sign-artifacts</id>
|
|
||||||
<phase>verify</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>sign</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-resources-plugin</artifactId>
|
|
||||||
<version>2.6</version>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.sonatype.central</groupId>
|
|
||||||
<artifactId>central-publishing-maven-plugin</artifactId>
|
|
||||||
<version>0.5.0</version>
|
|
||||||
<extensions>true</extensions>
|
|
||||||
<configuration>
|
|
||||||
<publishingServerId>ossrh</publishingServerId>
|
|
||||||
<!-- <tokenAuth>true</tokenAuth>-->
|
|
||||||
<autoPublish>true</autoPublish>
|
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
<pluginManagement>
|
<pluginManagement>
|
||||||
<plugins>
|
<plugins>
|
||||||
|
|
||||||
|
|
||||||
</plugins>
|
</plugins>
|
||||||
</pluginManagement>
|
</pluginManagement>
|
||||||
</build>
|
</build>
|
||||||
|
|||||||
@@ -32,7 +32,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>cloud.tianai.captcha</groupId>
|
<groupId>cloud.tianai.captcha</groupId>
|
||||||
<artifactId>tianai-captcha-springboot-starter</artifactId>
|
<artifactId>tianai-captcha-springboot-starter</artifactId>
|
||||||
<version>1.5.3</version>
|
<version>1.5.5</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -109,7 +109,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>cloud.tianai.captcha</groupId>
|
<groupId>cloud.tianai.captcha</groupId>
|
||||||
<artifactId>tianai-captcha</artifactId>
|
<artifactId>tianai-captcha</artifactId>
|
||||||
<version>1.5.3</version>
|
<version>1.5.4</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -167,7 +167,7 @@ public class ApplicationTest {
|
|||||||
|
|
||||||
### 安装
|
### 安装
|
||||||
|
|
||||||
1. 将打包好的`tac`目录放到自己项目中,如果是vue、react等框架,将tac目录放到public目录中、或者放到某个可以访问到地方,比如oss之类的可以被浏览器访问到的地方 (tac下载地址 [https://gitee.com/dromara/tianai-captcha/releases/tag/tianai-captcha-1.5.3](https://gitee.com/dromara/tianai-captcha/releases/tag/tianai-captcha-1.5.3))
|
1. 将打包好的`tac`目录放到自己项目中,如果是vue、react等框架,将tac目录放到public目录中、或者放到某个可以访问到地方,比如oss之类的可以被浏览器访问到的地方 (tac下载地址 [https://gitee.com/dromara/tianai-captcha/releases/tag/tianai-captcha-1.5.4](https://gitee.com/dromara/tianai-captcha/releases/tag/tianai-captcha-1.5.4))
|
||||||
|
|
||||||
2. 引入初始化函数 (load.js下载地址 [https://minio.tianai.cloud/public/static/captcha/js/load.min.js](https://minio.tianai.cloud/public/static/captcha/js/load.min.js)) 可自己将load.js下载到本地
|
2. 引入初始化函数 (load.js下载地址 [https://minio.tianai.cloud/public/static/captcha/js/load.min.js](https://minio.tianai.cloud/public/static/captcha/js/load.min.js)) 可自己将load.js下载到本地
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
$JAVA_HOME = "C:\Users\USER879511\.jdks\ms-21.0.11"
|
||||||
|
$MVN = "D:\Middleware\environment\apache-maven-3.9.16\bin\mvn.cmd"
|
||||||
|
$PG_PSQL = "D:\Middleware\gostgresql\bin\psql.exe"
|
||||||
|
$PG_PASSWORD = "XGYnJPysCNJsLeea"
|
||||||
|
$PROJECT_DIR = "D:\tianai-captcha-enhanced"
|
||||||
|
$JAR_PATH = "$PROJECT_DIR\tianai-captcha-platform\target\tianai-captcha-platform-2.0.0-SNAPSHOT.jar"
|
||||||
|
$PID_FILE = "$PROJECT_DIR\captcha-platform.pid"
|
||||||
|
$LOG_FILE = "$PROJECT_DIR\captcha-platform.log"
|
||||||
|
$DB_NAME = "captcha_forge"
|
||||||
|
|
||||||
|
function Ensure-Database {
|
||||||
|
Write-Host "[1/3] Checking database '$DB_NAME'..." -ForegroundColor Cyan
|
||||||
|
$env:PGPASSWORD = $PG_PASSWORD
|
||||||
|
$result = & $PG_PSQL -U postgres -h localhost -t -c "SELECT 1 FROM pg_database WHERE datname = '$DB_NAME'" 2>&1
|
||||||
|
if ($result -match "1 row" -or $result -match "1") {
|
||||||
|
Write-Host " Database '$DB_NAME' exists." -ForegroundColor Green
|
||||||
|
} else {
|
||||||
|
& $PG_PSQL -U postgres -h localhost -c "CREATE DATABASE $DB_NAME" 2>&1
|
||||||
|
Write-Host " Database '$DB_NAME' created." -ForegroundColor Green
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Build-Project {
|
||||||
|
Write-Host "[2/3] Building project..." -ForegroundColor Cyan
|
||||||
|
$env:JAVA_HOME = $JAVA_HOME
|
||||||
|
& $MVN -f "$PROJECT_DIR\pom.xml" package -DskipTests -q
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
Write-Host " BUILD FAILED!" -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
Write-Host " Build successful." -ForegroundColor Green
|
||||||
|
}
|
||||||
|
|
||||||
|
function Start-Platform {
|
||||||
|
Write-Host "[3/3] Starting captcha platform..." -ForegroundColor Cyan
|
||||||
|
|
||||||
|
if (Test-Path $PID_FILE) {
|
||||||
|
$oldPid = Get-Content $PID_FILE
|
||||||
|
$oldProc = Get-Process -Id $oldPid -ErrorAction SilentlyContinue
|
||||||
|
if ($oldProc) {
|
||||||
|
Write-Host " Stopping old process (PID $oldPid)..." -ForegroundColor Yellow
|
||||||
|
Stop-Process -Id $oldPid -Force
|
||||||
|
Start-Sleep -Seconds 2
|
||||||
|
}
|
||||||
|
Remove-Item $PID_FILE -Force
|
||||||
|
}
|
||||||
|
|
||||||
|
$env:JAVA_HOME = $JAVA_HOME
|
||||||
|
$env:PATH = "$JAVA_HOME\bin;$env:PATH"
|
||||||
|
|
||||||
|
$proc = Start-Process -FilePath "$JAVA_HOME\bin\java.exe" `
|
||||||
|
-ArgumentList "-jar", $JAR_PATH, `
|
||||||
|
"--spring.datasource.url=jdbc:postgresql://localhost:5432/$DB_NAME", `
|
||||||
|
"--spring.datasource.password=$PG_PASSWORD", `
|
||||||
|
"--spring.sql.init.mode=always" `
|
||||||
|
-RedirectStandardOutput $LOG_FILE `
|
||||||
|
-RedirectStandardError "$PROJECT_DIR\captcha-platform-err.log" `
|
||||||
|
-NoNewWindow -PassThru
|
||||||
|
|
||||||
|
$proc.Id | Set-Content $PID_FILE
|
||||||
|
Write-Host " Started! PID=$($proc.Id)" -ForegroundColor Green
|
||||||
|
Write-Host " Log: $LOG_FILE" -ForegroundColor Gray
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Waiting for startup (max 60s)..." -ForegroundColor Yellow
|
||||||
|
|
||||||
|
for ($i = 0; $i -lt 30; $i++) {
|
||||||
|
Start-Sleep -Seconds 2
|
||||||
|
try {
|
||||||
|
$resp = Invoke-WebRequest -Uri "http://localhost:18109/api/admin/sites" -Method GET -ErrorAction Stop
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Platform is UP!" -ForegroundColor Green
|
||||||
|
Write-Host " API: http://localhost:18109/api" -ForegroundColor Cyan
|
||||||
|
Write-Host " Site: http://localhost:18109/api/challenge/generate" -ForegroundColor Cyan
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Existing sites in DB:" -ForegroundColor Yellow
|
||||||
|
$env:PGPASSWORD = $PG_PASSWORD
|
||||||
|
& $PG_PSQL -U postgres -h localhost -d $DB_NAME -c "SELECT id, name, domain, site_key, verify_level, is_enabled FROM sites" 2>&1
|
||||||
|
return
|
||||||
|
} catch {}
|
||||||
|
Write-Host "." -NoNewline
|
||||||
|
}
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Startup may still be in progress. Check: $LOG_FILE" -ForegroundColor Yellow
|
||||||
|
}
|
||||||
|
|
||||||
|
function Stop-Platform {
|
||||||
|
Write-Host "Stopping captcha platform..." -ForegroundColor Yellow
|
||||||
|
if (Test-Path $PID_FILE) {
|
||||||
|
$pid = Get-Content $PID_FILE
|
||||||
|
$proc = Get-Process -Id $pid -ErrorAction SilentlyContinue
|
||||||
|
if ($proc) {
|
||||||
|
Stop-Process -Id $pid -Force
|
||||||
|
Write-Host " Stopped (PID $pid)." -ForegroundColor Green
|
||||||
|
} else {
|
||||||
|
Write-Host " Process not running." -ForegroundColor Gray
|
||||||
|
}
|
||||||
|
Remove-Item $PID_FILE -Force
|
||||||
|
} else {
|
||||||
|
Write-Host " No PID file found." -ForegroundColor Gray
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "============================================" -ForegroundColor Cyan
|
||||||
|
Write-Host " tianai-captcha-enhanced Launcher v2.0.0" -ForegroundColor Cyan
|
||||||
|
Write-Host " JDK 21 | Spring Boot 3.4 | PostgreSQL" -ForegroundColor Gray
|
||||||
|
Write-Host "============================================" -ForegroundColor Cyan
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
if ($args[0] -eq "stop") {
|
||||||
|
Stop-Platform
|
||||||
|
} else {
|
||||||
|
Ensure-Database
|
||||||
|
Build-Project
|
||||||
|
Start-Platform
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
FROM node:20-alpine AS builder
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
FROM nginx:alpine
|
||||||
|
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
EXPOSE 80
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
||||||
|
<title>tianai-captcha 管理平台</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>史诗质感 - 真·双剑与盾行为验证 (强效魔法脉冲版)</title>
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
height: 100vh;
|
||||||
|
background-color: #0f172a;
|
||||||
|
font-family: system-ui, -apple-system, sans-serif;
|
||||||
|
margin: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.captcha-container {
|
||||||
|
position: relative;
|
||||||
|
width: 180px;
|
||||||
|
height: 180px;
|
||||||
|
margin-bottom: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.captcha-icon {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- 1. 盾牌过渡 --- */
|
||||||
|
.shield-shard {
|
||||||
|
transform-origin: 50px 50px;
|
||||||
|
transition: transform 0.7s cubic-bezier(0.22, 1, 0.36, 1), fill 0.4s ease, opacity 0.5s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- 2. 强效魔法结界脉冲 --- */
|
||||||
|
.ward-group {
|
||||||
|
transition: opacity 0.4s ease;
|
||||||
|
}
|
||||||
|
.ward-pulse {
|
||||||
|
transform-origin: 50px 50px;
|
||||||
|
/* 加快了一点点脉冲节奏,显得能量更活跃 */
|
||||||
|
animation: pulse-ward 2s cubic-bezier(0.1, 0.7, 0.3, 1) infinite;
|
||||||
|
}
|
||||||
|
.ward-pulse.delay {
|
||||||
|
/* 延迟时间调整,形成错落有致的双重波纹 */
|
||||||
|
animation-delay: 1s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 核心修改:大幅增加粗细、透明度和放大倍率 */
|
||||||
|
@keyframes pulse-ward {
|
||||||
|
0% { transform: scale(0.4); opacity: 1; stroke-width: 16px; }
|
||||||
|
50% { opacity: 0.8; }
|
||||||
|
100% { transform: scale(1.7); opacity: 0; stroke-width: 2px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- 3. 巨剑插入动画 --- */
|
||||||
|
.sword-slide {
|
||||||
|
transform: translateY(-85px);
|
||||||
|
opacity: 0;
|
||||||
|
transition: transform 0.6s cubic-bezier(0.175, 0.885, 0.32, 1.4), opacity 0.4s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sword-anchor-a { transform-origin: 50px 50px; transform: rotate(-45deg); }
|
||||||
|
.sword-anchor-b { transform-origin: 50px 50px; transform: rotate(45deg); }
|
||||||
|
|
||||||
|
|
||||||
|
/* --- 4. 状态控制 --- */
|
||||||
|
.state-wait .ward-group { opacity: 1; }
|
||||||
|
.state-wait .shield-shard {
|
||||||
|
fill: url(#metalBlueGrad);
|
||||||
|
transform: translate(0, 0) scale(1) rotate(0deg);
|
||||||
|
opacity: 1;
|
||||||
|
/* 盾牌本身也加上强力的魔法蓝光阴影 */
|
||||||
|
filter: drop-shadow(0 0 20px rgba(56, 189, 248, 0.6));
|
||||||
|
}
|
||||||
|
|
||||||
|
.state-success .ward-group { opacity: 0; }
|
||||||
|
.state-success .shield-shard {
|
||||||
|
fill: url(#metalGreenGrad);
|
||||||
|
transform: translate(0, 0) scale(1) rotate(0deg);
|
||||||
|
opacity: 1;
|
||||||
|
filter: drop-shadow(0 6px 8px rgba(0,0,0,0.5));
|
||||||
|
}
|
||||||
|
.state-success .sword-slide { transform: translateY(-15px); opacity: 1; }
|
||||||
|
|
||||||
|
.state-fail .ward-group { opacity: 0; }
|
||||||
|
.state-fail .shield-shard { fill: url(#metalRedGrad); opacity: 0.9; filter: none;}
|
||||||
|
.state-fail .shard-tl { transform: translate(-25px, -30px) scale(0.9) rotateX(30deg) rotateY(-20deg) rotateZ(-15deg); opacity: 0.7; }
|
||||||
|
.state-fail .shard-tr { transform: translate(25px, -30px) scale(0.9) rotateX(30deg) rotateY(20deg) rotateZ(15deg); opacity: 0.7; }
|
||||||
|
.state-fail .shard-b { transform: translate(0, 35px) scale(0.8) rotateX(-20deg) rotateZ(5deg); opacity: 0.5; }
|
||||||
|
|
||||||
|
|
||||||
|
.controls { display: flex; gap: 15px; }
|
||||||
|
.controls button {
|
||||||
|
padding: 12px 24px; font-size: 14px; font-weight: bold; cursor: pointer;
|
||||||
|
border: 2px solid transparent; border-radius: 8px; background: #1e293b; color: #f1f5f9;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
.controls button:hover { background: #334155; transform: translateY(-2px); }
|
||||||
|
.controls button:active { transform: translateY(1px); }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div class="captcha-container">
|
||||||
|
<svg id="captcha-svg" class="captcha-icon state-wait" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="metalBlueGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#3B82F6" /><stop offset="50%" stop-color="#1E40AF" /><stop offset="100%" stop-color="#60A5FA" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="metalGreenGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#10B981" /><stop offset="50%" stop-color="#047857" /><stop offset="100%" stop-color="#34D399" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="metalRedGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#EF4444" /><stop offset="50%" stop-color="#B91C1C" /><stop offset="100%" stop-color="#F87171" />
|
||||||
|
</linearGradient>
|
||||||
|
|
||||||
|
<linearGradient id="bladeLight" x1="0%" y1="0%" x2="100%" y2="0%">
|
||||||
|
<stop offset="0%" stop-color="#f8fafc" /><stop offset="100%" stop-color="#94a3b8" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="bladeDark" x1="0%" y1="0%" x2="100%" y2="0%">
|
||||||
|
<stop offset="0%" stop-color="#64748b" /><stop offset="100%" stop-color="#334155" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="goldGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#FDE047" /><stop offset="50%" stop-color="#EAB308" /><stop offset="100%" stop-color="#A16207" />
|
||||||
|
</linearGradient>
|
||||||
|
|
||||||
|
<filter id="swordShadow" x="-20%" y="-20%" width="140%" height="140%">
|
||||||
|
<feDropShadow dx="3" dy="5" stdDeviation="2.5" flood-color="#000000" flood-opacity="0.7"/>
|
||||||
|
</filter>
|
||||||
|
|
||||||
|
<filter id="epicMagicGlow" x="-50%" y="-50%" width="200%" height="200%">
|
||||||
|
<feGaussianBlur in="SourceGraphic" stdDeviation="2" result="blur1" />
|
||||||
|
<feGaussianBlur in="SourceGraphic" stdDeviation="6" result="blur2" />
|
||||||
|
<feMerge>
|
||||||
|
<feMergeNode in="blur2" />
|
||||||
|
<feMergeNode in="blur1" />
|
||||||
|
<feMergeNode in="SourceGraphic" />
|
||||||
|
</feMerge>
|
||||||
|
</filter>
|
||||||
|
|
||||||
|
<g id="epic-sword" filter="url(#swordShadow)">
|
||||||
|
<polygon points="43,26 50,26 50,115" fill="url(#bladeLight)" />
|
||||||
|
<polygon points="50,26 57,26 50,115" fill="url(#bladeDark)" />
|
||||||
|
<rect x="45" y="4" width="10" height="22" fill="#1e293b" />
|
||||||
|
<path d="M 45 6 L 55 10 M 45 12 L 55 16 M 45 18 L 55 22 M 45 24 L 55 28" stroke="#475569" stroke-width="2" />
|
||||||
|
<polygon points="20,22 50,26 80,22 80,27 50,32 20,27" fill="#713F12" />
|
||||||
|
<polygon points="20,22 50,26 80,22 50,24" fill="url(#goldGrad)" />
|
||||||
|
<polygon points="50,-6 57,0 50,6 43,0" fill="url(#goldGrad)" />
|
||||||
|
<polygon points="50,-6 57,0 50,6" fill="rgba(0,0,0,0.25)" />
|
||||||
|
</g>
|
||||||
|
</defs>
|
||||||
|
|
||||||
|
<g class="ward-group" filter="url(#epicMagicGlow)">
|
||||||
|
<circle class="ward-pulse" cx="50" cy="50" r="30" fill="rgba(56, 189, 248, 0.15)" stroke="#38BDF8" stroke-linecap="round" />
|
||||||
|
<circle class="ward-pulse delay" cx="50" cy="50" r="30" fill="rgba(56, 189, 248, 0.15)" stroke="#38BDF8" stroke-linecap="round" />
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<g class="shield-main-group">
|
||||||
|
<path class="shield-shard shard-tl" d="M 50 12 L 18 28 L 18 52 L 50 48 Z" fill="url(#metalBlueGrad)" />
|
||||||
|
<path class="shield-shard shard-tr" d="M 50 12 L 82 28 L 82 52 L 50 48 Z" fill="url(#metalBlueGrad)" />
|
||||||
|
<path class="shield-shard shard-b" d="M 18 52 C 18 78 50 92 50 92 C 50 92 82 78 82 52 L 50 48 Z" fill="url(#metalBlueGrad)" />
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<g class="sword-anchor-a">
|
||||||
|
<g class="sword-slide">
|
||||||
|
<use href="#epic-sword" />
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<g class="sword-anchor-b">
|
||||||
|
<g class="sword-slide">
|
||||||
|
<use href="#epic-sword" />
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="controls">
|
||||||
|
<button onclick="changeState('state-wait')" style="border-color: #3B82F6;">🛡️ 结界维持中...</button>
|
||||||
|
<button onclick="changeState('state-success')" style="border-color: #10B981; color: #10B981;">⚔️ 史诗验证成功</button>
|
||||||
|
<button onclick="changeState('state-fail')" style="border-color: #EF4444; color: #EF4444;">💥 盾牌碎裂</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function changeState(newStateClass) {
|
||||||
|
const svg = document.getElementById('captcha-svg');
|
||||||
|
svg.classList.remove('state-wait', 'state-success', 'state-fail');
|
||||||
|
svg.classList.add(newStateClass);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
|
||||||
|
<defs>
|
||||||
|
<!-- 渐变色定义 -->
|
||||||
|
<linearGradient id="shieldGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#4F46E5" /> <!-- 科技靛蓝 -->
|
||||||
|
<stop offset="100%" stop-color="#06B6D4" /> <!-- 灵动青色 -->
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="ringGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#10B981" /> <!-- 安全绿 -->
|
||||||
|
<stop offset="100%" stop-color="#3B82F6" /> <!-- 信任蓝 -->
|
||||||
|
</linearGradient>
|
||||||
|
<!-- 发光滤镜 -->
|
||||||
|
<filter id="glow" x="-20%" y="-20%" width="140%" height="140%">
|
||||||
|
<feGaussianBlur stdDeviation="2" result="blur" />
|
||||||
|
<feComposite in="SourceGraphic" in2="blur" operator="over" />
|
||||||
|
</filter>
|
||||||
|
</defs>
|
||||||
|
|
||||||
|
<!-- 外部盾牌形状 (象征安全防护) -->
|
||||||
|
<path d="M 50 10 L 85 25 L 85 50 C 85 75 50 90 50 90 C 50 90 15 75 15 50 L 15 25 Z"
|
||||||
|
fill="none"
|
||||||
|
stroke="url(#shieldGrad)"
|
||||||
|
stroke-width="4"
|
||||||
|
stroke-linejoin="round" />
|
||||||
|
|
||||||
|
<!-- 内部动态扫描环 (象征行为分析与智能验证) -->
|
||||||
|
<circle cx="50" cy="50" r="16"
|
||||||
|
fill="none"
|
||||||
|
stroke="url(#ringGrad)"
|
||||||
|
stroke-width="4"
|
||||||
|
stroke-dasharray="60 40"
|
||||||
|
stroke-linecap="round"
|
||||||
|
filter="url(#glow)">
|
||||||
|
<animateTransform attributeName="transform" type="rotate" from="0 50 50" to="360 50 50" dur="1.5s" repeatCount="indefinite" />
|
||||||
|
</circle>
|
||||||
|
|
||||||
|
<!-- 中心脉冲核心 (象征触控/鼠标焦点) -->
|
||||||
|
<circle cx="50" cy="50" r="4" fill="#06B6D4">
|
||||||
|
<animate attributeName="r" values="3; 6; 3" dur="1.5s" repeatCount="indefinite" />
|
||||||
|
<animate attributeName="opacity" values="0.4; 1; 0.4" dur="1.5s" repeatCount="indefinite" />
|
||||||
|
</circle>
|
||||||
|
|
||||||
|
<!-- 上下装饰轨迹线 (象征运动轨迹) -->
|
||||||
|
<path d="M 35 38 Q 50 28 65 38" fill="none" stroke="#4F46E5" stroke-width="2" stroke-linecap="round" opacity="0.6">
|
||||||
|
<animate attributeName="opacity" values="0.2; 0.8; 0.2" dur="2s" repeatCount="indefinite" />
|
||||||
|
</path>
|
||||||
|
<path d="M 35 62 Q 50 72 65 62" fill="none" stroke="#4F46E5" stroke-width="2" stroke-linecap="round" opacity="0.6">
|
||||||
|
<animate attributeName="opacity" values="0.8; 0.2; 0.8" dur="2s" repeatCount="indefinite" />
|
||||||
|
</path>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 2.4 KiB |
@@ -0,0 +1,192 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>史诗质感 - 真·双剑与盾行为验证 (锐利光环版)</title>
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
height: 100vh;
|
||||||
|
background-color: #0f172a;
|
||||||
|
font-family: system-ui, -apple-system, sans-serif;
|
||||||
|
margin: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.captcha-container {
|
||||||
|
position: relative;
|
||||||
|
width: 180px;
|
||||||
|
height: 180px;
|
||||||
|
margin-bottom: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.captcha-icon {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- 1. 盾牌过渡 --- */
|
||||||
|
.shield-shard {
|
||||||
|
transform-origin: 50px 50px;
|
||||||
|
transition: transform 0.7s cubic-bezier(0.22, 1, 0.36, 1), fill 0.4s ease, opacity 0.5s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- 2. 纯净空心脉冲 --- */
|
||||||
|
.ward-group {
|
||||||
|
transition: opacity 0.4s ease;
|
||||||
|
}
|
||||||
|
.ward-pulse {
|
||||||
|
opacity: 0;
|
||||||
|
transform-origin: 50px 50px;
|
||||||
|
animation: pulse-ward 2s cubic-bezier(0.1, 0.7, 0.3, 1) infinite;
|
||||||
|
}
|
||||||
|
.ward-pulse.delay {
|
||||||
|
animation-delay: 1s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 移除了夸张的缩放和粗细变化,改为更清爽的光圈扩散 */
|
||||||
|
@keyframes pulse-ward {
|
||||||
|
0% { transform: scale(1.0); opacity: 1; stroke-width: 6px; }
|
||||||
|
100% { transform: scale(1.8); opacity: 0; stroke-width: 1px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- 3. 巨剑插入动画 --- */
|
||||||
|
.sword-slide {
|
||||||
|
transform: translateY(-85px);
|
||||||
|
opacity: 0;
|
||||||
|
transition: transform 0.6s cubic-bezier(0.175, 0.885, 0.32, 1.4), opacity 0.4s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sword-anchor-a { transform-origin: 50px 50px; transform: rotate(-45deg); }
|
||||||
|
.sword-anchor-b { transform-origin: 50px 50px; transform: rotate(45deg); }
|
||||||
|
|
||||||
|
|
||||||
|
/* --- 4. 状态控制 --- */
|
||||||
|
.state-wait .ward-group { opacity: 1; }
|
||||||
|
.state-wait .shield-shard {
|
||||||
|
fill: url(#metalBlueGrad);
|
||||||
|
transform: translate(0, 0) scale(1) rotate(0deg);
|
||||||
|
opacity: 1;
|
||||||
|
/* 【核心修复】:移除发光,改回黑色的物理实体阴影,保证盾牌边缘极其锐利 */
|
||||||
|
filter: drop-shadow(0 6px 8px rgba(0,0,0,0.6));
|
||||||
|
}
|
||||||
|
|
||||||
|
.state-success .ward-group { opacity: 0; }
|
||||||
|
.state-success .shield-shard {
|
||||||
|
fill: url(#metalGreenGrad);
|
||||||
|
transform: translate(0, 0) scale(1) rotate(0deg);
|
||||||
|
opacity: 1;
|
||||||
|
filter: drop-shadow(0 6px 8px rgba(0,0,0,0.6));
|
||||||
|
}
|
||||||
|
.state-success .sword-slide { transform: translateY(-15px); opacity: 1; }
|
||||||
|
|
||||||
|
.state-fail .ward-group { opacity: 0; }
|
||||||
|
.state-fail .shield-shard { fill: url(#metalRedGrad); opacity: 0.9; filter: none;}
|
||||||
|
.state-fail .shard-tl { transform: translate(-25px, -30px) scale(0.9) rotateX(30deg) rotateY(-20deg) rotateZ(-15deg); opacity: 0.7; }
|
||||||
|
.state-fail .shard-tr { transform: translate(25px, -30px) scale(0.9) rotateX(30deg) rotateY(20deg) rotateZ(15deg); opacity: 0.7; }
|
||||||
|
.state-fail .shard-b { transform: translate(0, 35px) scale(0.8) rotateX(-20deg) rotateZ(5deg); opacity: 0.5; }
|
||||||
|
|
||||||
|
|
||||||
|
.controls { display: flex; gap: 15px; }
|
||||||
|
.controls button {
|
||||||
|
padding: 12px 24px; font-size: 14px; font-weight: bold; cursor: pointer;
|
||||||
|
border: 2px solid transparent; border-radius: 8px; background: #1e293b; color: #f1f5f9;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
.controls button:hover { background: #334155; transform: translateY(-2px); }
|
||||||
|
.controls button:active { transform: translateY(1px); }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div class="captcha-container">
|
||||||
|
<svg id="captcha-svg" class="captcha-icon state-wait" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="metalBlueGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#3B82F6" /><stop offset="50%" stop-color="#1E40AF" /><stop offset="100%" stop-color="#60A5FA" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="metalGreenGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#10B981" /><stop offset="50%" stop-color="#047857" /><stop offset="100%" stop-color="#34D399" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="metalRedGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#EF4444" /><stop offset="50%" stop-color="#B91C1C" /><stop offset="100%" stop-color="#F87171" />
|
||||||
|
</linearGradient>
|
||||||
|
|
||||||
|
<linearGradient id="bladeLight" x1="0%" y1="0%" x2="100%" y2="0%">
|
||||||
|
<stop offset="0%" stop-color="#f8fafc" /><stop offset="100%" stop-color="#94a3b8" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="bladeDark" x1="0%" y1="0%" x2="100%" y2="0%">
|
||||||
|
<stop offset="0%" stop-color="#64748b" /><stop offset="100%" stop-color="#334155" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="goldGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#FDE047" /><stop offset="50%" stop-color="#EAB308" /><stop offset="100%" stop-color="#A16207" />
|
||||||
|
</linearGradient>
|
||||||
|
|
||||||
|
<filter id="swordShadow" x="-20%" y="-20%" width="140%" height="140%">
|
||||||
|
<feDropShadow dx="3" dy="5" stdDeviation="2.5" flood-color="#000000" flood-opacity="0.7"/>
|
||||||
|
</filter>
|
||||||
|
|
||||||
|
<filter id="cleanMagicGlow" x="-50%" y="-50%" width="200%" height="200%">
|
||||||
|
<feGaussianBlur in="SourceGraphic" stdDeviation="2" result="blur" />
|
||||||
|
<feMerge>
|
||||||
|
<feMergeNode in="blur" />
|
||||||
|
<feMergeNode in="SourceGraphic" />
|
||||||
|
</feMerge>
|
||||||
|
</filter>
|
||||||
|
|
||||||
|
<g id="epic-sword" filter="url(#swordShadow)">
|
||||||
|
<polygon points="43,26 50,26 50,115" fill="url(#bladeLight)" />
|
||||||
|
<polygon points="50,26 57,26 50,115" fill="url(#bladeDark)" />
|
||||||
|
<rect x="45" y="4" width="10" height="22" fill="#1e293b" />
|
||||||
|
<path d="M 45 6 L 55 10 M 45 12 L 55 16 M 45 18 L 55 22 M 45 24 L 55 28" stroke="#475569" stroke-width="2" />
|
||||||
|
<polygon points="20,22 50,26 80,22 80,27 50,32 20,27" fill="#713F12" />
|
||||||
|
<polygon points="20,22 50,26 80,22 50,24" fill="url(#goldGrad)" />
|
||||||
|
<polygon points="50,-6 57,0 50,6 43,0" fill="url(#goldGrad)" />
|
||||||
|
<polygon points="50,-6 57,0 50,6" fill="rgba(0,0,0,0.25)" />
|
||||||
|
</g>
|
||||||
|
</defs>
|
||||||
|
|
||||||
|
<g class="ward-group" filter="url(#cleanMagicGlow)">
|
||||||
|
<circle class="ward-pulse" cx="50" cy="50" r="35" fill="none" stroke="#38BDF8" stroke-linecap="round" />
|
||||||
|
<circle class="ward-pulse delay" cx="50" cy="50" r="35" fill="none" stroke="#38BDF8" stroke-linecap="round" />
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<g class="shield-main-group">
|
||||||
|
<path class="shield-shard shard-tl" d="M 50 12 L 18 28 L 18 52 L 50 48 Z" fill="url(#metalBlueGrad)" />
|
||||||
|
<path class="shield-shard shard-tr" d="M 50 12 L 82 28 L 82 52 L 50 48 Z" fill="url(#metalBlueGrad)" />
|
||||||
|
<path class="shield-shard shard-b" d="M 18 52 C 18 78 50 92 50 92 C 50 92 82 78 82 52 L 50 48 Z" fill="url(#metalBlueGrad)" />
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<g class="sword-anchor-a">
|
||||||
|
<g class="sword-slide">
|
||||||
|
<use href="#epic-sword" />
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<g class="sword-anchor-b">
|
||||||
|
<g class="sword-slide">
|
||||||
|
<use href="#epic-sword" />
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="controls">
|
||||||
|
<button onclick="changeState('state-wait')" style="border-color: #3B82F6;">🛡️ 结界维持中...</button>
|
||||||
|
<button onclick="changeState('state-success')" style="border-color: #10B981; color: #10B981;">⚔️ 史诗验证成功</button>
|
||||||
|
<button onclick="changeState('state-fail')" style="border-color: #EF4444; color: #EF4444;">💥 盾牌碎裂</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function changeState(newStateClass) {
|
||||||
|
const svg = document.getElementById('captcha-svg');
|
||||||
|
svg.classList.remove('state-wait', 'state-success', 'state-fail');
|
||||||
|
svg.classList.add(newStateClass);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name localhost;
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /api/ {
|
||||||
|
proxy_pass http://captcha-platform:18200/api/;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
}
|
||||||
|
}
|
||||||
+1986
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"name": "tianai-captcha-platform-ui",
|
||||||
|
"version": "2.0.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"vue": "^3.5.13",
|
||||||
|
"vue-router": "^4.5.0",
|
||||||
|
"pinia": "^2.3.0",
|
||||||
|
"element-plus": "^2.9.1",
|
||||||
|
"axios": "^1.7.9",
|
||||||
|
"echarts": "^5.5.1",
|
||||||
|
"@element-plus/icons-vue": "^2.3.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@vitejs/plugin-vue": "^5.2.1",
|
||||||
|
"vite": "^6.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
|
||||||
|
<defs>
|
||||||
|
<!-- 渐变色定义 -->
|
||||||
|
<linearGradient id="shieldGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#4F46E5" /> <!-- 科技靛蓝 -->
|
||||||
|
<stop offset="100%" stop-color="#06B6D4" /> <!-- 灵动青色 -->
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="ringGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#10B981" /> <!-- 安全绿 -->
|
||||||
|
<stop offset="100%" stop-color="#3B82F6" /> <!-- 信任蓝 -->
|
||||||
|
</linearGradient>
|
||||||
|
<!-- 发光滤镜 -->
|
||||||
|
<filter id="glow" x="-20%" y="-20%" width="140%" height="140%">
|
||||||
|
<feGaussianBlur stdDeviation="2" result="blur" />
|
||||||
|
<feComposite in="SourceGraphic" in2="blur" operator="over" />
|
||||||
|
</filter>
|
||||||
|
</defs>
|
||||||
|
|
||||||
|
<!-- 外部盾牌形状 (象征安全防护) -->
|
||||||
|
<path d="M 50 10 L 85 25 L 85 50 C 85 75 50 90 50 90 C 50 90 15 75 15 50 L 15 25 Z"
|
||||||
|
fill="none"
|
||||||
|
stroke="url(#shieldGrad)"
|
||||||
|
stroke-width="4"
|
||||||
|
stroke-linejoin="round" />
|
||||||
|
|
||||||
|
<!-- 内部动态扫描环 (象征行为分析与智能验证) -->
|
||||||
|
<circle cx="50" cy="50" r="16"
|
||||||
|
fill="none"
|
||||||
|
stroke="url(#ringGrad)"
|
||||||
|
stroke-width="4"
|
||||||
|
stroke-dasharray="60 40"
|
||||||
|
stroke-linecap="round"
|
||||||
|
filter="url(#glow)">
|
||||||
|
<animateTransform attributeName="transform" type="rotate" from="0 50 50" to="360 50 50" dur="1.5s" repeatCount="indefinite" />
|
||||||
|
</circle>
|
||||||
|
|
||||||
|
<!-- 中心脉冲核心 (象征触控/鼠标焦点) -->
|
||||||
|
<circle cx="50" cy="50" r="4" fill="#06B6D4">
|
||||||
|
<animate attributeName="r" values="3; 6; 3" dur="1.5s" repeatCount="indefinite" />
|
||||||
|
<animate attributeName="opacity" values="0.4; 1; 0.4" dur="1.5s" repeatCount="indefinite" />
|
||||||
|
</circle>
|
||||||
|
|
||||||
|
<!-- 上下装饰轨迹线 (象征运动轨迹) -->
|
||||||
|
<path d="M 35 38 Q 50 28 65 38" fill="none" stroke="#4F46E5" stroke-width="2" stroke-linecap="round" opacity="0.6">
|
||||||
|
<animate attributeName="opacity" values="0.2; 0.8; 0.2" dur="2s" repeatCount="indefinite" />
|
||||||
|
</path>
|
||||||
|
<path d="M 35 62 Q 50 72 65 62" fill="none" stroke="#4F46E5" stroke-width="2" stroke-linecap="round" opacity="0.6">
|
||||||
|
<animate attributeName="opacity" values="0.8; 0.2; 0.8" dur="2s" repeatCount="indefinite" />
|
||||||
|
</path>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 2.4 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.4 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.5 MiB |
@@ -0,0 +1,746 @@
|
|||||||
|
/**
|
||||||
|
* tianai-captcha-enhanced SDK
|
||||||
|
* 兼容 TPCaptcha API (TPCaptcha.init / onSuccess / verifyToken)
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* TACaptcha.init({
|
||||||
|
* elId: 'captcha-box',
|
||||||
|
* siteKey: 'your-site-key',
|
||||||
|
* type: 'SLIDER', // optional
|
||||||
|
* scene: 'login', // optional
|
||||||
|
* serverUrl: 'https://your-server/api', // optional
|
||||||
|
* onSuccess: (result) => { console.log(result.data.verifyToken); },
|
||||||
|
* onFail: () => { console.log('failed'); }
|
||||||
|
* });
|
||||||
|
*/
|
||||||
|
(function (global) {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const INSTANCES = new Map();
|
||||||
|
|
||||||
|
class TACaptchaInstance {
|
||||||
|
constructor(options) {
|
||||||
|
this.options = Object.assign({
|
||||||
|
elId: null,
|
||||||
|
siteKey: '',
|
||||||
|
mode: 'click',
|
||||||
|
type: null,
|
||||||
|
scene: 'default',
|
||||||
|
serverUrl: '/api',
|
||||||
|
onSuccess: null,
|
||||||
|
onFail: null,
|
||||||
|
onOpen: null,
|
||||||
|
onClose: null,
|
||||||
|
onRefresh: null,
|
||||||
|
}, options);
|
||||||
|
|
||||||
|
this.container = null;
|
||||||
|
this.modal = null;
|
||||||
|
this.captchaData = null;
|
||||||
|
this.verifyToken = null;
|
||||||
|
this.isDragging = false;
|
||||||
|
this.startX = 0;
|
||||||
|
this.currentX = 0;
|
||||||
|
this.trackList = [];
|
||||||
|
this.startTime = 0;
|
||||||
|
this.isDark = this._detectTheme();
|
||||||
|
this._themeObserver = null;
|
||||||
|
|
||||||
|
this._init();
|
||||||
|
}
|
||||||
|
|
||||||
|
_detectTheme() {
|
||||||
|
if (this.options.theme === 'dark') return true;
|
||||||
|
if (this.options.theme === 'light') return false;
|
||||||
|
if (document.body.classList.contains('dark') || document.documentElement.classList.contains('dark')) return true;
|
||||||
|
if (document.documentElement.getAttribute('data-theme') === 'dark') return true;
|
||||||
|
if (document.documentElement.getAttribute('color-scheme') === 'dark') return true;
|
||||||
|
if (document.documentElement.style.colorScheme === 'dark') return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_watchTheme() {
|
||||||
|
if (this._themeObserver) this._themeObserver.disconnect();
|
||||||
|
const targets = [document.body, document.documentElement];
|
||||||
|
this._themeObserver = new MutationObserver(() => {
|
||||||
|
const newDark = this._detectTheme();
|
||||||
|
if (newDark !== this.isDark) {
|
||||||
|
this.isDark = newDark;
|
||||||
|
this._createTriggerButton();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
targets.forEach(t => {
|
||||||
|
if (t) this._themeObserver.observe(t, { attributes: true, attributeFilter: ['class', 'data-theme', 'color-scheme'] });
|
||||||
|
});
|
||||||
|
if (window.matchMedia) {
|
||||||
|
const mq = window.matchMedia('(prefers-color-scheme: dark)');
|
||||||
|
this._mqHandler = () => {
|
||||||
|
const newDark = this._detectTheme();
|
||||||
|
if (newDark !== this.isDark) {
|
||||||
|
this.isDark = newDark;
|
||||||
|
this._createTriggerButton();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
mq.addEventListener('change', this._mqHandler);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_init() {
|
||||||
|
if (this.options.mode === 'event') {
|
||||||
|
this._createModal();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this._createTriggerButton();
|
||||||
|
this._createModal();
|
||||||
|
this._watchTheme();
|
||||||
|
}
|
||||||
|
|
||||||
|
_createTriggerButton() {
|
||||||
|
const el = document.getElementById(this.options.elId);
|
||||||
|
if (!el) return;
|
||||||
|
this.container = el;
|
||||||
|
|
||||||
|
const typeLabel = this.options.type || '智能验证';
|
||||||
|
|
||||||
|
// 注入呼吸灯 + 盾牌动画样式
|
||||||
|
if (!document.getElementById('tacaptcha-breathing-style')) {
|
||||||
|
const style = document.createElement('style');
|
||||||
|
style.id = 'tacaptcha-breathing-style';
|
||||||
|
style.textContent =
|
||||||
|
'@keyframes tacaptcha-breathe{0%,100%{box-shadow:0 0 0 0 rgba(82,196,26,0.4)}50%{box-shadow:0 0 0 6px rgba(82,196,26,0)}}' +
|
||||||
|
'.tacaptcha-dot{width:8px;height:8px;border-radius:50%;background:#52c41a;animation:tacaptcha-breathe 2s ease-in-out infinite}' +
|
||||||
|
'.tacaptcha-shield .shield-shard{transform-origin:50px 50px;transition:transform 2s cubic-bezier(0.22,1,0.36,1),fill 2s ease,opacity 2s ease}' +
|
||||||
|
'.tacaptcha-shield .ward-group{transition:opacity 2s ease}' +
|
||||||
|
'.tacaptcha-shield .ward-pulse{transform-origin:50px 50px;animation:pulse-ward 2s cubic-bezier(0.1,0.7,0.3,1) infinite}' +
|
||||||
|
'.tacaptcha-shield .ward-pulse.delay{animation-delay:1s}' +
|
||||||
|
'@keyframes pulse-ward{0%{transform:scale(0.6);opacity:1;stroke-width:6px}100%{transform:scale(1.8);opacity:0;stroke-width:1px}}' +
|
||||||
|
'.tacaptcha-shield .sword-slide{transform:translateY(-85px);opacity:0;transition:transform 2s cubic-bezier(0.175,0.885,0.32,1.4),opacity 2s ease}' +
|
||||||
|
'.tacaptcha-shield .sword-anchor-a{transform-origin:50px 50px;transform:rotate(-45deg)}' +
|
||||||
|
'.tacaptcha-shield .sword-anchor-b{transform-origin:50px 50px;transform:rotate(45deg)}' +
|
||||||
|
'.tacaptcha-shield.state-wait .ward-group{opacity:1}' +
|
||||||
|
'.tacaptcha-shield.state-success .ward-group,.tacaptcha-shield.state-fail .ward-group{opacity:0}' +
|
||||||
|
'.tacaptcha-shield.state-success .ward-pulse,.tacaptcha-shield.state-fail .ward-pulse{animation:none}' +
|
||||||
|
'.tacaptcha-shield.state-wait .shield-shard{fill:url(#tacaptcha-mb);transform:translate(0,0) scale(1) rotate(0deg);opacity:1;filter:drop-shadow(0 6px 8px rgba(0,0,0,0.6))}' +
|
||||||
|
'.tacaptcha-shield.state-success .shield-shard{fill:url(#tacaptcha-mg);transform:translate(0,0) scale(1) rotate(0deg);opacity:1;filter:drop-shadow(0 6px 8px rgba(0,0,0,0.6))}' +
|
||||||
|
'.tacaptcha-shield.state-success .sword-slide{transform:translateY(-15px);opacity:1}' +
|
||||||
|
'.tacaptcha-shield.state-fail .shield-shard{fill:url(#tacaptcha-mr);opacity:0.9;filter:none}' +
|
||||||
|
'.tacaptcha-shield.state-fail .shard-tl{transform:translate(-25px,-30px) scale(0.9) rotateX(30deg) rotateY(-20deg) rotateZ(-15deg);opacity:0.7}' +
|
||||||
|
'.tacaptcha-shield.state-fail .shard-tr{transform:translate(25px,-30px) scale(0.9) rotateX(30deg) rotateY(20deg) rotateZ(15deg);opacity:0.7}' +
|
||||||
|
'.tacaptcha-shield.state-fail .shard-b{transform:translate(0,35px) scale(0.8) rotateX(-20deg) rotateZ(5deg);opacity:0.5}';
|
||||||
|
document.head.appendChild(style);
|
||||||
|
}
|
||||||
|
|
||||||
|
const bgColor = this.isDark ? '#1a1a2e' : '#fff';
|
||||||
|
const borderColor = this.isDark ? '#2a2a4a' : '#e8e8e8';
|
||||||
|
const textColor = this.isDark ? '#e0e0e0' : '#333';
|
||||||
|
const subColor = this.isDark ? '#888' : '#999';
|
||||||
|
const btnBg = this.isDark ? '#16213e' : '#fafafa';
|
||||||
|
const btnBorder = this.isDark ? '#0f3460' : '#d9d9d9';
|
||||||
|
const btnColor = this.isDark ? '#aaa' : '#666';
|
||||||
|
const shadow = this.isDark ? '0 2px 8px rgba(0,0,0,0.3)' : '0 1px 4px rgba(0,0,0,0.06)';
|
||||||
|
|
||||||
|
const shieldSvg = this._createShieldSvg('state-wait');
|
||||||
|
|
||||||
|
const btn = document.createElement('div');
|
||||||
|
btn.style.cssText = 'display:flex;align-items:center;gap:10px;padding:12px 16px;border:1px solid ' + borderColor + ';border-radius:8px;cursor:pointer;user-select:none;transition:all 0.2s;font-size:14px;color:' + textColor + ';background:' + bgColor + ';box-shadow:' + shadow + ';';
|
||||||
|
btn.innerHTML =
|
||||||
|
shieldSvg +
|
||||||
|
'<span style="flex:1;color:' + textColor + ';white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">点击进行验证</span>' +
|
||||||
|
'<span style="color:' + subColor + ';font-size:12px;white-space:nowrap;flex-shrink:0;">' + typeLabel + '</span>' +
|
||||||
|
'<span style="display:inline-flex;align-items:center;gap:5px;padding:4px 12px;border:1px solid ' + btnBorder + ';border-radius:4px;font-size:12px;color:' + btnColor + ';background:' + btnBg + ';">' +
|
||||||
|
'<span class="tacaptcha-dot"></span>点击验证</span>';
|
||||||
|
|
||||||
|
btn.addEventListener('mouseenter', () => { btn.style.borderColor = '#1890ff'; });
|
||||||
|
btn.addEventListener('mouseleave', () => { btn.style.borderColor = borderColor; });
|
||||||
|
btn.addEventListener('click', () => this._openCaptcha());
|
||||||
|
|
||||||
|
el.appendChild(btn);
|
||||||
|
this.triggerBtn = btn;
|
||||||
|
}
|
||||||
|
|
||||||
|
_createShieldSvg(stateClass) {
|
||||||
|
return '<svg class="tacaptcha-shield ' + stateClass + '" width="32" height="32" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="flex-shrink:0;">' +
|
||||||
|
'<defs>' +
|
||||||
|
'<linearGradient id="tacaptcha-mb" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="#3B82F6"/><stop offset="50%" stop-color="#1E40AF"/><stop offset="100%" stop-color="#60A5FA"/></linearGradient>' +
|
||||||
|
'<linearGradient id="tacaptcha-mg" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="#10B981"/><stop offset="50%" stop-color="#047857"/><stop offset="100%" stop-color="#34D399"/></linearGradient>' +
|
||||||
|
'<linearGradient id="tacaptcha-mr" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="#EF4444"/><stop offset="50%" stop-color="#B91C1C"/><stop offset="100%" stop-color="#F87171"/></linearGradient>' +
|
||||||
|
'<linearGradient id="tacaptcha-bl" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="0%" stop-color="#f8fafc"/><stop offset="100%" stop-color="#94a3b8"/></linearGradient>' +
|
||||||
|
'<linearGradient id="tacaptcha-bd" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="0%" stop-color="#64748b"/><stop offset="100%" stop-color="#334155"/></linearGradient>' +
|
||||||
|
'<linearGradient id="tacaptcha-gold" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="#FDE047"/><stop offset="50%" stop-color="#EAB308"/><stop offset="100%" stop-color="#A16207"/></linearGradient>' +
|
||||||
|
'<filter id="tacaptcha-ss"><feDropShadow dx="2" dy="3" stdDeviation="1.5" flood-color="#000" flood-opacity="0.5"/></filter>' +
|
||||||
|
'<filter id="tacaptcha-mg2"><feGaussianBlur stdDeviation="2" result="blur"/><feComposite in="SourceGraphic" in2="blur" operator="over"/></filter>' +
|
||||||
|
'<filter id="tacaptcha-emg" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur in="SourceGraphic" stdDeviation="2" result="blur"/><feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge></filter>' +
|
||||||
|
'<g id="tacaptcha-sw" filter="url(#tacaptcha-ss)"><polygon points="43,26 50,26 50,115" fill="url(#tacaptcha-bl)"/><polygon points="50,26 57,26 50,115" fill="url(#tacaptcha-bd)"/><rect x="45" y="4" width="10" height="22" fill="#1e293b"/><polygon points="20,22 50,26 80,22 80,27 50,32 20,27" fill="#713F12"/><polygon points="20,22 50,26 80,22 50,24" fill="url(#tacaptcha-gold)"/><polygon points="50,-6 57,0 50,6 43,0" fill="url(#tacaptcha-gold)"/></g>' +
|
||||||
|
'</defs>' +
|
||||||
|
'<g class="ward-group" filter="url(#tacaptcha-emg)"><circle class="ward-pulse" cx="50" cy="50" r="35" fill="none" stroke="#38BDF8" stroke-linecap="round"/><circle class="ward-pulse delay" cx="50" cy="50" r="35" fill="none" stroke="#38BDF8" stroke-linecap="round"/></g>' +
|
||||||
|
'<g class="shield-main-group"><path class="shield-shard shard-tl" d="M 50 12 L 18 28 L 18 52 L 50 48 Z" fill="url(#tacaptcha-mb)"/><path class="shield-shard shard-tr" d="M 50 12 L 82 28 L 82 52 L 50 48 Z" fill="url(#tacaptcha-mb)"/><path class="shield-shard shard-b" d="M 18 52 C 18 78 50 92 50 92 C 50 92 82 78 82 52 L 50 48 Z" fill="url(#tacaptcha-mb)"/></g>' +
|
||||||
|
'<g class="sword-anchor-a"><g class="sword-slide"><use href="#tacaptcha-sw"/></g></g>' +
|
||||||
|
'<g class="sword-anchor-b"><g class="sword-slide"><use href="#tacaptcha-sw"/></g></g>' +
|
||||||
|
'</svg>';
|
||||||
|
}
|
||||||
|
|
||||||
|
_setShieldState(state) {
|
||||||
|
if (!this.triggerBtn) return;
|
||||||
|
const svg = this.triggerBtn.querySelector('.tacaptcha-shield');
|
||||||
|
if (svg) {
|
||||||
|
svg.classList.remove('state-wait', 'state-success', 'state-fail');
|
||||||
|
const pulses = svg.querySelectorAll('.ward-pulse');
|
||||||
|
pulses.forEach(p => { p.style.animation = 'none'; });
|
||||||
|
void svg.offsetWidth;
|
||||||
|
svg.classList.add('state-' + state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_createModal() {
|
||||||
|
const panelBg = this.isDark ? '#1a1a2e' : '#fff';
|
||||||
|
const textColor = this.isDark ? '#e0e0e0' : '#333';
|
||||||
|
const subColor = this.isDark ? '#666' : '#999';
|
||||||
|
const overlayBg = this.isDark ? 'rgba(0,0,0,0.5)' : 'rgba(0,0,0,0.3)';
|
||||||
|
const shadow = this.isDark ? '0 4px 20px rgba(0,0,0,0.4)' : '0 4px 20px rgba(0,0,0,0.15)';
|
||||||
|
|
||||||
|
this.modal = document.createElement('div');
|
||||||
|
this.modal.style.cssText = 'display:none;position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;';
|
||||||
|
|
||||||
|
const overlay = document.createElement('div');
|
||||||
|
overlay.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;background:' + overlayBg + ';';
|
||||||
|
overlay.addEventListener('click', () => this._closeCaptcha());
|
||||||
|
|
||||||
|
const panel = document.createElement('div');
|
||||||
|
panel.style.cssText = 'position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:' + panelBg + ';border-radius:8px;padding:20px;box-shadow:' + shadow + ';min-width:340px;';
|
||||||
|
|
||||||
|
this.captchaPanel = panel;
|
||||||
|
|
||||||
|
const header = document.createElement('div');
|
||||||
|
header.style.cssText = 'display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;';
|
||||||
|
header.innerHTML = '<span style="font-weight:600;font-size:15px;color:' + textColor + ';">请完成安全验证</span>';
|
||||||
|
|
||||||
|
const refreshBtn = document.createElement('span');
|
||||||
|
refreshBtn.textContent = '↻';
|
||||||
|
refreshBtn.style.cssText = 'cursor:pointer;font-size:18px;color:' + subColor + ';';
|
||||||
|
refreshBtn.addEventListener('click', () => this._loadCaptcha());
|
||||||
|
header.appendChild(refreshBtn);
|
||||||
|
|
||||||
|
const closeBtn = document.createElement('span');
|
||||||
|
closeBtn.textContent = '✕';
|
||||||
|
closeBtn.style.cssText = 'cursor:pointer;font-size:16px;color:' + subColor + ';margin-left:12px;';
|
||||||
|
closeBtn.addEventListener('click', () => this._closeCaptcha());
|
||||||
|
header.appendChild(closeBtn);
|
||||||
|
|
||||||
|
this.captchaContent = document.createElement('div');
|
||||||
|
this.captchaContent.style.cssText = 'position:relative;';
|
||||||
|
|
||||||
|
this.statusBar = document.createElement('div');
|
||||||
|
this.statusBar.style.cssText = 'margin-top:12px;text-align:center;font-size:13px;color:' + subColor + ';';
|
||||||
|
|
||||||
|
panel.appendChild(header);
|
||||||
|
panel.appendChild(this.captchaContent);
|
||||||
|
panel.appendChild(this.statusBar);
|
||||||
|
|
||||||
|
this.modal.appendChild(overlay);
|
||||||
|
this.modal.appendChild(panel);
|
||||||
|
document.body.appendChild(this.modal);
|
||||||
|
}
|
||||||
|
|
||||||
|
async _openCaptcha() {
|
||||||
|
this.modal.style.display = 'block';
|
||||||
|
if (this.options.onOpen) this.options.onOpen();
|
||||||
|
await this._loadCaptcha();
|
||||||
|
}
|
||||||
|
|
||||||
|
_closeCaptcha() {
|
||||||
|
this.modal.style.display = 'none';
|
||||||
|
if (this.options.onClose) this.options.onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
async _loadCaptcha() {
|
||||||
|
this.statusBar.textContent = '加载中...';
|
||||||
|
this.captchaContent.innerHTML = '';
|
||||||
|
this.verifyToken = null;
|
||||||
|
this._setShieldState('wait');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = `${this.options.serverUrl}/challenge/generate`;
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (this.options.type) params.set('type', this.options.type);
|
||||||
|
params.set('scene', this.options.scene);
|
||||||
|
|
||||||
|
const resp = await fetch(url + '?' + params.toString(), {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'X-Site-Key': this.options.siteKey }
|
||||||
|
});
|
||||||
|
const result = await resp.json();
|
||||||
|
|
||||||
|
if (result.code !== 200) {
|
||||||
|
this.statusBar.textContent = result.msg || '加载失败';
|
||||||
|
if (this.options.onFail) this.options.onFail(result);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.captchaData = result.data;
|
||||||
|
console.log('[ROTATE-INIT] degree=' + result.data.degree + ' type=' + result.data.type + ' tplW=' + result.data.templateImageWidth + ' tplH=' + result.data.templateImageHeight);
|
||||||
|
this._renderCaptcha();
|
||||||
|
this.statusBar.textContent = '请完成验证';
|
||||||
|
} catch (e) {
|
||||||
|
this.statusBar.textContent = '网络错误';
|
||||||
|
if (this.options.onFail) this.options.onFail({ code: 10000, msg: e.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_isClickType(type) {
|
||||||
|
return type === 'WORD_IMAGE_CLICK' || type === 'ICON_CLICK' || type === 'WORD_ORDER_CLICK';
|
||||||
|
}
|
||||||
|
|
||||||
|
_renderCaptcha() {
|
||||||
|
this.captchaContent.innerHTML = '';
|
||||||
|
const data = this.captchaData;
|
||||||
|
if (!data) return;
|
||||||
|
const isRotate = data.type === 'ROTATE';
|
||||||
|
const isConcat = data.type === 'CONCAT';
|
||||||
|
const isCurveDraw = data.type === 'CURVE_DRAW';
|
||||||
|
const isClick = this._isClickType(data.type);
|
||||||
|
|
||||||
|
if (isClick) {
|
||||||
|
this._renderClickCaptcha();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isCurveDraw) {
|
||||||
|
this._renderDrawCaptcha();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bgImg = document.createElement('img');
|
||||||
|
bgImg.src = data.backgroundImage;
|
||||||
|
bgImg.style.cssText = 'width:100%;display:block;border-radius:4px;';
|
||||||
|
|
||||||
|
const wrapper = document.createElement('div');
|
||||||
|
wrapper.style.cssText = 'position:relative;border-radius:4px;';
|
||||||
|
wrapper.appendChild(bgImg);
|
||||||
|
|
||||||
|
let tplImg = null;
|
||||||
|
let concatTopLayer = null;
|
||||||
|
let concatRandomY = 0;
|
||||||
|
if (isConcat) {
|
||||||
|
concatRandomY = (data.data && data.data.randomY) ? data.data.randomY : Math.round(data.backgroundImageHeight / 2);
|
||||||
|
wrapper.innerHTML = '';
|
||||||
|
wrapper.style.cssText = 'position:relative;border-radius:4px;overflow:hidden;width:100%;height:180px;';
|
||||||
|
const bgLayer = document.createElement('div');
|
||||||
|
bgLayer.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;z-index:1;background-image:url(' + data.backgroundImage + ');background-size:100% 180px;background-position:0 0;background-repeat:no-repeat;';
|
||||||
|
wrapper.appendChild(bgLayer);
|
||||||
|
const overlayHeight = ((data.backgroundImageHeight - concatRandomY) / data.backgroundImageHeight) * 180;
|
||||||
|
concatTopLayer = document.createElement('div');
|
||||||
|
concatTopLayer.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:' + overlayHeight + 'px;z-index:2;overflow:hidden;background-image:url(' + data.backgroundImage + ');background-size:100% 180px;background-position:0 0;background-repeat:no-repeat;';
|
||||||
|
wrapper.appendChild(concatTopLayer);
|
||||||
|
} else if (data.templateImage) {
|
||||||
|
tplImg = document.createElement('img');
|
||||||
|
tplImg.src = data.templateImage;
|
||||||
|
if (isRotate) {
|
||||||
|
const holeLeft = ((data.backgroundImageWidth - data.templateImageWidth) / 2 / data.backgroundImageWidth * 100);
|
||||||
|
const holeTop = ((data.backgroundImageHeight - data.templateImageHeight) / 2 / data.backgroundImageHeight * 100);
|
||||||
|
tplImg.style.cssText = 'position:absolute;left:' + holeLeft + '%;top:' + holeTop + '%;width:' + (data.templateImageWidth / data.backgroundImageWidth * 100) + '%;pointer-events:none;transform:rotate(0deg);transform-origin:center center;z-index:1;';
|
||||||
|
} else {
|
||||||
|
tplImg.style.cssText = 'position:absolute;top:0;left:0;height:100%;pointer-events:none;transition:none;';
|
||||||
|
}
|
||||||
|
wrapper.appendChild(tplImg);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.captchaContent.appendChild(wrapper);
|
||||||
|
|
||||||
|
const sliderBar = document.createElement('div');
|
||||||
|
const barBg = this.isDark ? '#2a2a4a' : '#f0f0f0';
|
||||||
|
sliderBar.style.cssText = 'position:relative;height:40px;width:100%;background:' + barBg + ';border-radius:4px;margin-top:8px;overflow:hidden;';
|
||||||
|
|
||||||
|
const sliderTrack = document.createElement('div');
|
||||||
|
sliderTrack.style.cssText = 'position:absolute;top:0;left:0;height:100%;width:0;background:linear-gradient(90deg,#52c41a,#73d13d);border-radius:4px;transition:none;';
|
||||||
|
|
||||||
|
const sliderBtnBg = this.isDark ? '#1a1a2e' : '#fff';
|
||||||
|
const sliderBtn = document.createElement('div');
|
||||||
|
sliderBtn.style.cssText = 'position:absolute;top:2px;left:0;width:36px;height:36px;background:' + sliderBtnBg + ';border-radius:4px;box-shadow:0 1px 4px rgba(0,0,0,0.15);cursor:grab;display:flex;align-items:center;justify-content:center;font-size:16px;color:#999;transition:none;';
|
||||||
|
sliderBtn.textContent = isRotate ? '↻' : '→';
|
||||||
|
|
||||||
|
sliderBar.appendChild(sliderTrack);
|
||||||
|
sliderBar.appendChild(sliderBtn);
|
||||||
|
this.captchaContent.appendChild(sliderBar);
|
||||||
|
|
||||||
|
this.startX = 0;
|
||||||
|
this.currentX = 0;
|
||||||
|
this.trackList = [];
|
||||||
|
this.startTime = Date.now();
|
||||||
|
|
||||||
|
const getBarWidth = () => sliderBar.offsetWidth;
|
||||||
|
|
||||||
|
const onMove = (e) => {
|
||||||
|
if (!this.isDragging) return;
|
||||||
|
const barWidth = getBarWidth();
|
||||||
|
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
|
||||||
|
const dx = clientX - this.startX;
|
||||||
|
const maxX = barWidth - 36;
|
||||||
|
this.currentX = Math.max(0, Math.min(dx, maxX));
|
||||||
|
|
||||||
|
sliderBtn.style.left = this.currentX + 'px';
|
||||||
|
sliderTrack.style.width = (this.currentX + 18) + 'px';
|
||||||
|
|
||||||
|
const ratio = this.currentX / barWidth;
|
||||||
|
let scaledX;
|
||||||
|
if (isRotate && tplImg) {
|
||||||
|
const bgW = this.captchaData.backgroundImageWidth;
|
||||||
|
const cssDegree = (this.currentX / barWidth) * 360;
|
||||||
|
tplImg.style.transform = 'rotate(' + cssDegree + 'deg)';
|
||||||
|
scaledX = Math.round(ratio * bgW);
|
||||||
|
} else if (isConcat && concatTopLayer) {
|
||||||
|
const moveX = ratio * wrapper.offsetWidth;
|
||||||
|
concatTopLayer.style.backgroundPositionX = moveX + 'px';
|
||||||
|
scaledX = Math.round(ratio * this.captchaData.backgroundImageWidth);
|
||||||
|
} else if (tplImg) {
|
||||||
|
tplImg.style.left = (ratio * 100) + '%';
|
||||||
|
scaledX = Math.round(ratio * this.captchaData.backgroundImageWidth);
|
||||||
|
} else {
|
||||||
|
scaledX = Math.round(ratio * this.captchaData.backgroundImageWidth);
|
||||||
|
}
|
||||||
|
this.trackList.push({
|
||||||
|
x: scaledX,
|
||||||
|
y: 0,
|
||||||
|
t: Date.now() - this.startTime,
|
||||||
|
type: 'MOVE'
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const onUp = async () => {
|
||||||
|
if (!this.isDragging) return;
|
||||||
|
this.isDragging = false;
|
||||||
|
sliderBtn.style.cursor = 'grab';
|
||||||
|
document.removeEventListener('mousemove', onMove);
|
||||||
|
document.removeEventListener('mouseup', onUp);
|
||||||
|
document.removeEventListener('touchmove', onMove);
|
||||||
|
document.removeEventListener('touchend', onUp);
|
||||||
|
|
||||||
|
const barWidth = getBarWidth();
|
||||||
|
const ratio = this.currentX / barWidth;
|
||||||
|
const scaledX = Math.round(ratio * this.captchaData.backgroundImageWidth);
|
||||||
|
this.trackList.push({
|
||||||
|
x: scaledX,
|
||||||
|
y: 0,
|
||||||
|
t: Date.now() - this.startTime,
|
||||||
|
type: 'UP'
|
||||||
|
});
|
||||||
|
|
||||||
|
this.statusBar.textContent = '验证中...';
|
||||||
|
this.statusBar.style.color = '#999';
|
||||||
|
|
||||||
|
await this._verify();
|
||||||
|
};
|
||||||
|
|
||||||
|
sliderBtn.addEventListener('mousedown', (e) => {
|
||||||
|
this.isDragging = true;
|
||||||
|
this.startX = e.clientX - this.currentX;
|
||||||
|
this.trackList = [{ x: 0, y: 0, t: 0, type: 'DOWN' }];
|
||||||
|
this.startTime = Date.now();
|
||||||
|
sliderBtn.style.cursor = 'grabbing';
|
||||||
|
document.addEventListener('mousemove', onMove);
|
||||||
|
document.addEventListener('mouseup', onUp);
|
||||||
|
});
|
||||||
|
|
||||||
|
sliderBtn.addEventListener('touchstart', (e) => {
|
||||||
|
this.isDragging = true;
|
||||||
|
this.startX = e.touches[0].clientX - this.currentX;
|
||||||
|
this.trackList = [{ x: 0, y: 0, t: 0, type: 'DOWN' }];
|
||||||
|
this.startTime = Date.now();
|
||||||
|
document.addEventListener('touchmove', onMove, { passive: false });
|
||||||
|
document.addEventListener('touchend', onUp);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
_renderClickCaptcha() {
|
||||||
|
const data = this.captchaData;
|
||||||
|
const isWordOrder = data.type === 'WORD_ORDER_CLICK';
|
||||||
|
const tipText = isWordOrder ? '请依次点击' : '请依次点击图中文字';
|
||||||
|
|
||||||
|
const tipBar = document.createElement('div');
|
||||||
|
tipBar.style.cssText = 'display:flex;align-items:center;justify-content:space-between;height:40px;margin-bottom:8px;';
|
||||||
|
|
||||||
|
const tipLabel = document.createElement('span');
|
||||||
|
tipLabel.style.cssText = 'font-size:14px;color:' + (this.isDark ? '#e0e0e0' : '#333') + ';';
|
||||||
|
tipLabel.textContent = tipText;
|
||||||
|
|
||||||
|
tipBar.appendChild(tipLabel);
|
||||||
|
|
||||||
|
if (data.templateImage) {
|
||||||
|
const tipImg = document.createElement('img');
|
||||||
|
tipImg.src = data.templateImage;
|
||||||
|
tipImg.style.cssText = 'height:35px;max-width:200px;';
|
||||||
|
tipBar.appendChild(tipImg);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.captchaContent.appendChild(tipBar);
|
||||||
|
|
||||||
|
const wrapper = document.createElement('div');
|
||||||
|
wrapper.style.cssText = 'position:relative;border-radius:4px;overflow:hidden;cursor:crosshair;';
|
||||||
|
|
||||||
|
const bgImg = document.createElement('img');
|
||||||
|
bgImg.src = data.backgroundImage;
|
||||||
|
bgImg.style.cssText = 'width:100%;display:block;border-radius:4px;';
|
||||||
|
wrapper.appendChild(bgImg);
|
||||||
|
|
||||||
|
const clickMask = document.createElement('div');
|
||||||
|
clickMask.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;';
|
||||||
|
wrapper.appendChild(clickMask);
|
||||||
|
|
||||||
|
this.captchaContent.appendChild(wrapper);
|
||||||
|
|
||||||
|
const confirmBtn = document.createElement('div');
|
||||||
|
confirmBtn.style.cssText = 'width:100%;height:35px;border-radius:4px;background:linear-gradient(173deg,#e8a838 0%,#f0c060 100%);font-size:15px;text-align:center;line-height:35px;color:#fff;margin-top:8px;cursor:pointer;';
|
||||||
|
confirmBtn.textContent = '确认';
|
||||||
|
this.captchaContent.appendChild(confirmBtn);
|
||||||
|
|
||||||
|
this.trackList = [];
|
||||||
|
this.startTime = Date.now();
|
||||||
|
this.clickCount = 0;
|
||||||
|
this.clickMarkers = [];
|
||||||
|
|
||||||
|
clickMask.addEventListener('click', (e) => {
|
||||||
|
if (e.target.className === 'tacaptcha-click-marker') return;
|
||||||
|
const rect = bgImg.getBoundingClientRect();
|
||||||
|
const clickX = Math.round(e.clientX - rect.left);
|
||||||
|
const clickY = Math.round(e.clientY - rect.top);
|
||||||
|
const displayW = rect.width;
|
||||||
|
const displayH = rect.height;
|
||||||
|
const scaledX = Math.round((clickX / displayW) * data.backgroundImageWidth);
|
||||||
|
const scaledY = Math.round((clickY / displayH) * data.backgroundImageHeight);
|
||||||
|
|
||||||
|
this.clickCount++;
|
||||||
|
if (this.clickCount === 1) {
|
||||||
|
this.startTime = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.trackList.push({
|
||||||
|
x: scaledX,
|
||||||
|
y: scaledY,
|
||||||
|
t: Date.now() - this.startTime,
|
||||||
|
type: 'CLICK'
|
||||||
|
});
|
||||||
|
|
||||||
|
const marker = document.createElement('span');
|
||||||
|
marker.className = 'tacaptcha-click-marker';
|
||||||
|
marker.textContent = this.clickCount;
|
||||||
|
const left = clickX - 11;
|
||||||
|
const top = clickY - 11;
|
||||||
|
marker.style.cssText = 'position:absolute;left:' + left + 'px;top:' + top + 'px;border-radius:50%;background:#409eff;width:22px;height:22px;text-align:center;line-height:22px;color:#fff;border:2px solid #fff;box-sizing:content-box;font-size:12px;pointer-events:none;z-index:2;';
|
||||||
|
clickMask.appendChild(marker);
|
||||||
|
this.clickMarkers.push(marker);
|
||||||
|
});
|
||||||
|
|
||||||
|
confirmBtn.addEventListener('click', async () => {
|
||||||
|
if (this.clickCount === 0) return;
|
||||||
|
this.statusBar.textContent = '验证中...';
|
||||||
|
this.statusBar.style.color = '#999';
|
||||||
|
await this._verify();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
_renderDrawCaptcha() {
|
||||||
|
const data = this.captchaData;
|
||||||
|
|
||||||
|
const wrapper = document.createElement('div');
|
||||||
|
wrapper.style.cssText = 'position:relative;border-radius:4px;overflow:hidden;';
|
||||||
|
|
||||||
|
const bgImg = document.createElement('img');
|
||||||
|
bgImg.src = data.backgroundImage;
|
||||||
|
bgImg.style.cssText = 'width:100%;display:block;border-radius:4px;';
|
||||||
|
wrapper.appendChild(bgImg);
|
||||||
|
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
canvas.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;touch-action:none;cursor:crosshair;';
|
||||||
|
wrapper.appendChild(canvas);
|
||||||
|
|
||||||
|
const tip = document.createElement('div');
|
||||||
|
tip.textContent = '请在图上绘制曲线';
|
||||||
|
tip.style.cssText = 'position:absolute;top:8px;left:50%;transform:translateX(-50%);background:rgba(0,0,0,0.6);color:#fff;padding:4px 12px;border-radius:4px;font-size:13px;pointer-events:none;z-index:2;';
|
||||||
|
wrapper.appendChild(tip);
|
||||||
|
|
||||||
|
this.captchaContent.appendChild(wrapper);
|
||||||
|
|
||||||
|
const confirmBtn = document.createElement('div');
|
||||||
|
confirmBtn.style.cssText = 'width:100%;height:35px;border-radius:4px;background:linear-gradient(173deg,#e8a838 0%,#f0c060 100%);font-size:15px;text-align:center;line-height:35px;color:#fff;margin-top:8px;cursor:pointer;';
|
||||||
|
confirmBtn.textContent = '确认';
|
||||||
|
this.captchaContent.appendChild(confirmBtn);
|
||||||
|
|
||||||
|
this.trackList = [];
|
||||||
|
this.startTime = Date.now();
|
||||||
|
this.isDrawing = false;
|
||||||
|
|
||||||
|
let ctx = null;
|
||||||
|
|
||||||
|
const getPoint = (e) => {
|
||||||
|
const rect = bgImg.getBoundingClientRect();
|
||||||
|
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
|
||||||
|
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
|
||||||
|
const x = clientX - rect.left;
|
||||||
|
const y = clientY - rect.top;
|
||||||
|
const scaledX = Math.round((x / rect.width) * data.backgroundImageWidth);
|
||||||
|
const scaledY = Math.round((y / rect.height) * data.backgroundImageHeight);
|
||||||
|
return { x, y, scaledX, scaledY };
|
||||||
|
};
|
||||||
|
|
||||||
|
const startDraw = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
this.isDrawing = true;
|
||||||
|
const p = getPoint(e);
|
||||||
|
this.trackList.push({ x: p.scaledX, y: p.scaledY, t: 0, type: 'DOWN' });
|
||||||
|
|
||||||
|
const rect = wrapper.getBoundingClientRect();
|
||||||
|
canvas.width = rect.width;
|
||||||
|
canvas.height = rect.height;
|
||||||
|
ctx = canvas.getContext('2d');
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(p.x, p.y);
|
||||||
|
ctx.lineWidth = 3;
|
||||||
|
ctx.lineCap = 'round';
|
||||||
|
ctx.lineJoin = 'round';
|
||||||
|
ctx.strokeStyle = 'rgba(64, 158, 255, 0.9)';
|
||||||
|
tip.style.display = 'none';
|
||||||
|
};
|
||||||
|
|
||||||
|
const moveDraw = (e) => {
|
||||||
|
if (!this.isDrawing) return;
|
||||||
|
e.preventDefault();
|
||||||
|
const p = getPoint(e);
|
||||||
|
this.trackList.push({ x: p.scaledX, y: p.scaledY, t: Date.now() - this.startTime, type: 'MOVE' });
|
||||||
|
if (ctx) {
|
||||||
|
ctx.lineTo(p.x, p.y);
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const endDraw = (e) => {
|
||||||
|
if (!this.isDrawing) return;
|
||||||
|
this.isDrawing = false;
|
||||||
|
let clientX, clientY;
|
||||||
|
if (e.changedTouches && e.changedTouches.length > 0) {
|
||||||
|
clientX = e.changedTouches[0].clientX;
|
||||||
|
clientY = e.changedTouches[0].clientY;
|
||||||
|
} else {
|
||||||
|
clientX = e.clientX;
|
||||||
|
clientY = e.clientY;
|
||||||
|
}
|
||||||
|
const rect = bgImg.getBoundingClientRect();
|
||||||
|
const x = clientX - rect.left;
|
||||||
|
const y = clientY - rect.top;
|
||||||
|
const scaledX = Math.round((x / rect.width) * data.backgroundImageWidth);
|
||||||
|
const scaledY = Math.round((y / rect.height) * data.backgroundImageHeight);
|
||||||
|
this.trackList.push({ x: scaledX, y: scaledY, t: Date.now() - this.startTime, type: 'UP' });
|
||||||
|
};
|
||||||
|
|
||||||
|
canvas.addEventListener('mousedown', startDraw);
|
||||||
|
canvas.addEventListener('mousemove', moveDraw);
|
||||||
|
canvas.addEventListener('mouseup', endDraw);
|
||||||
|
canvas.addEventListener('touchstart', startDraw, { passive: false });
|
||||||
|
canvas.addEventListener('touchmove', moveDraw, { passive: false });
|
||||||
|
canvas.addEventListener('touchend', endDraw);
|
||||||
|
|
||||||
|
confirmBtn.addEventListener('click', async () => {
|
||||||
|
if (this.trackList.length === 0) return;
|
||||||
|
this.statusBar.textContent = '验证中...';
|
||||||
|
this.statusBar.style.color = '#999';
|
||||||
|
await this._verify();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async _verify() {
|
||||||
|
if (!this.captchaData) return;
|
||||||
|
this.statusBar.textContent = '验证中...';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const trackData = {
|
||||||
|
bgImageWidth: this.captchaData.backgroundImageWidth,
|
||||||
|
bgImageHeight: this.captchaData.backgroundImageHeight,
|
||||||
|
templateImageWidth: this.captchaData.templateImageWidth,
|
||||||
|
templateImageHeight: this.captchaData.templateImageHeight,
|
||||||
|
startTime: this.startTime,
|
||||||
|
stopTime: Date.now(),
|
||||||
|
trackList: this.trackList
|
||||||
|
};
|
||||||
|
|
||||||
|
const resp = await fetch(`${this.options.serverUrl}/challenge/verify`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-Site-Key': this.options.siteKey
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
id: this.captchaData.id,
|
||||||
|
data: trackData
|
||||||
|
})
|
||||||
|
});
|
||||||
|
const result = await resp.json();
|
||||||
|
|
||||||
|
if (result.code === 200 && result.data && result.data.verifyToken) {
|
||||||
|
this.verifyToken = result.data.verifyToken;
|
||||||
|
this.statusBar.textContent = '验证成功';
|
||||||
|
this.statusBar.style.color = '#52c41a';
|
||||||
|
if (this.options.onSuccess) {
|
||||||
|
this.options.onSuccess({
|
||||||
|
code: 200,
|
||||||
|
msg: '操作成功',
|
||||||
|
data: { verifyToken: this.verifyToken }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
setTimeout(() => {
|
||||||
|
this._closeCaptcha();
|
||||||
|
this._setShieldState('success');
|
||||||
|
}, 400);
|
||||||
|
} else {
|
||||||
|
this._setShieldState('fail');
|
||||||
|
this.statusBar.textContent = '验证失败,请重试';
|
||||||
|
this.statusBar.style.color = '#ff4d4f';
|
||||||
|
if (this.options.onFail) this.options.onFail(result);
|
||||||
|
setTimeout(() => this._loadCaptcha(), 1500);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
this.statusBar.textContent = '网络错误';
|
||||||
|
if (this.options.onFail) this.options.onFail({ code: 10000, msg: e.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async show() {
|
||||||
|
await this._openCaptcha();
|
||||||
|
}
|
||||||
|
|
||||||
|
destroy() {
|
||||||
|
if (this.modal && this.modal.parentNode) {
|
||||||
|
this.modal.parentNode.removeChild(this.modal);
|
||||||
|
}
|
||||||
|
if (this.options.elId) {
|
||||||
|
INSTANCES.delete(this.options.elId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const TACaptcha = {
|
||||||
|
async init(options) {
|
||||||
|
const elId = options.elId || ('_tac_' + Date.now());
|
||||||
|
if (INSTANCES.has(elId)) {
|
||||||
|
INSTANCES.get(elId).destroy();
|
||||||
|
}
|
||||||
|
const instance = new TACaptchaInstance(options);
|
||||||
|
INSTANCES.set(elId, instance);
|
||||||
|
return instance;
|
||||||
|
},
|
||||||
|
|
||||||
|
refresh(elId) {
|
||||||
|
const inst = INSTANCES.get(elId);
|
||||||
|
if (inst) inst._loadCaptcha();
|
||||||
|
},
|
||||||
|
|
||||||
|
show(elId) {
|
||||||
|
const inst = INSTANCES.get(elId);
|
||||||
|
if (inst) return inst.show();
|
||||||
|
return Promise.reject(new Error('Instance not found'));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (typeof module !== 'undefined' && module.exports) {
|
||||||
|
module.exports = TACaptcha;
|
||||||
|
} else {
|
||||||
|
global.TACaptcha = TACaptcha;
|
||||||
|
}
|
||||||
|
})(typeof window !== 'undefined' ? window : this);
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<template>
|
||||||
|
<router-view />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
html, body {
|
||||||
|
height: 100%;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import axios from 'axios'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
|
||||||
|
const api = axios.create({
|
||||||
|
baseURL: '/admin/api',
|
||||||
|
timeout: 10000
|
||||||
|
})
|
||||||
|
|
||||||
|
// 请求拦截器
|
||||||
|
api.interceptors.request.use(
|
||||||
|
config => {
|
||||||
|
const token = localStorage.getItem('token')
|
||||||
|
if (token) {
|
||||||
|
config.headers.Authorization = `Bearer ${token}`
|
||||||
|
}
|
||||||
|
return config
|
||||||
|
},
|
||||||
|
error => Promise.reject(error)
|
||||||
|
)
|
||||||
|
|
||||||
|
// 响应拦截器
|
||||||
|
api.interceptors.response.use(
|
||||||
|
response => {
|
||||||
|
const data = response.data
|
||||||
|
if (data.code && data.code !== 200) {
|
||||||
|
ElMessage.error(data.msg || '请求失败')
|
||||||
|
return Promise.reject(data)
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
},
|
||||||
|
error => {
|
||||||
|
if (error.response?.status === 401) {
|
||||||
|
localStorage.removeItem('token')
|
||||||
|
window.location.href = '/admin/login'
|
||||||
|
}
|
||||||
|
ElMessage.error(error.message || '网络错误')
|
||||||
|
return Promise.reject(error)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// 认证 API
|
||||||
|
export const authApi = {
|
||||||
|
login: (data) => api.post('/auth/login', data),
|
||||||
|
getMe: () => api.get('/auth/me')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 站点 API
|
||||||
|
export const siteApi = {
|
||||||
|
list: (params) => api.get('/admin/sites', { params }),
|
||||||
|
get: (id) => api.get(`/admin/sites/${id}`),
|
||||||
|
create: (data) => api.post('/admin/sites', data),
|
||||||
|
update: (id, data) => api.put(`/admin/sites/${id}`, data),
|
||||||
|
delete: (id) => api.delete(`/admin/sites/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 统计 API
|
||||||
|
export const statsApi = {
|
||||||
|
get: (params) => api.get('/admin/stats', { params })
|
||||||
|
}
|
||||||
|
|
||||||
|
// 日志 API
|
||||||
|
export const logApi = {
|
||||||
|
list: (params) => api.get('/admin/logs', { params })
|
||||||
|
}
|
||||||
|
|
||||||
|
// IP 黑名单 API
|
||||||
|
export const ipBlacklistApi = {
|
||||||
|
ban: (data) => api.post('/admin/ip-blacklist', data),
|
||||||
|
unban: (ip) => api.delete(`/admin/ip-blacklist/${ip}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 套餐 API
|
||||||
|
export const planApi = {
|
||||||
|
list: () => api.get('/admin/plans'),
|
||||||
|
get: (id) => api.get(`/admin/plans/${id}`),
|
||||||
|
create: (data) => api.post('/admin/plans', data),
|
||||||
|
update: (id, data) => api.put(`/admin/plans/${id}`, data),
|
||||||
|
delete: (id) => api.delete(`/admin/plans/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default api
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
<template>
|
||||||
|
<el-container class="main-layout">
|
||||||
|
<el-aside width="220px" class="sidebar">
|
||||||
|
<div class="logo">
|
||||||
|
<h2>TianAI Captcha</h2>
|
||||||
|
</div>
|
||||||
|
<el-menu
|
||||||
|
:default-active="route.path"
|
||||||
|
router
|
||||||
|
background-color="#304156"
|
||||||
|
text-color="#bfcbd9"
|
||||||
|
active-text-color="#409eff"
|
||||||
|
>
|
||||||
|
<el-menu-item index="/dashboard">
|
||||||
|
<el-icon><DataBoard /></el-icon>
|
||||||
|
<span>首页大盘</span>
|
||||||
|
</el-menu-item>
|
||||||
|
<el-menu-item index="/sites">
|
||||||
|
<el-icon><OfficeBuilding /></el-icon>
|
||||||
|
<span>站点管理</span>
|
||||||
|
</el-menu-item>
|
||||||
|
<el-menu-item index="/logs">
|
||||||
|
<el-icon><Document /></el-icon>
|
||||||
|
<span>验证码日志</span>
|
||||||
|
</el-menu-item>
|
||||||
|
<el-menu-item index="/ip-blacklist">
|
||||||
|
<el-icon><CircleCloseFilled /></el-icon>
|
||||||
|
<span>IP黑名单</span>
|
||||||
|
</el-menu-item>
|
||||||
|
<el-menu-item index="/plans">
|
||||||
|
<el-icon><Ticket /></el-icon>
|
||||||
|
<span>套餐管理</span>
|
||||||
|
</el-menu-item>
|
||||||
|
<el-menu-item index="/settings">
|
||||||
|
<el-icon><Setting /></el-icon>
|
||||||
|
<span>系统设置</span>
|
||||||
|
</el-menu-item>
|
||||||
|
</el-menu>
|
||||||
|
</el-aside>
|
||||||
|
<el-container>
|
||||||
|
<el-header class="header">
|
||||||
|
<div class="header-left">
|
||||||
|
<el-breadcrumb separator="/">
|
||||||
|
<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
|
||||||
|
<el-breadcrumb-item>{{ route.meta.title }}</el-breadcrumb-item>
|
||||||
|
</el-breadcrumb>
|
||||||
|
</div>
|
||||||
|
<div class="header-right">
|
||||||
|
<el-dropdown @command="handleCommand">
|
||||||
|
<span class="user-info">
|
||||||
|
<el-icon><User /></el-icon>
|
||||||
|
{{ userStore.username }}
|
||||||
|
<el-icon class="el-icon--right"><ArrowDown /></el-icon>
|
||||||
|
</span>
|
||||||
|
<template #dropdown>
|
||||||
|
<el-dropdown-menu>
|
||||||
|
<el-dropdown-item command="logout">退出登录</el-dropdown-item>
|
||||||
|
</el-dropdown-menu>
|
||||||
|
</template>
|
||||||
|
</el-dropdown>
|
||||||
|
</div>
|
||||||
|
</el-header>
|
||||||
|
<el-main class="main-content">
|
||||||
|
<router-view />
|
||||||
|
</el-main>
|
||||||
|
</el-container>
|
||||||
|
</el-container>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
|
import { useUserStore } from '../store/user'
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
|
const userStore = useUserStore()
|
||||||
|
|
||||||
|
const handleCommand = (command) => {
|
||||||
|
if (command === 'logout') {
|
||||||
|
userStore.logout()
|
||||||
|
router.push('/login')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.main-layout {
|
||||||
|
height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar {
|
||||||
|
background-color: #304156;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
height: 60px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background-color: #263445;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo h2 {
|
||||||
|
color: #fff;
|
||||||
|
font-size: 18px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
background: #fff;
|
||||||
|
box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-info {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
cursor: pointer;
|
||||||
|
color: #606266;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-content {
|
||||||
|
background-color: #f0f2f5;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { createApp } from 'vue'
|
||||||
|
import ElementPlus from 'element-plus'
|
||||||
|
import 'element-plus/dist/index.css'
|
||||||
|
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||||
|
import { createPinia } from 'pinia'
|
||||||
|
import App from './App.vue'
|
||||||
|
import router from './router'
|
||||||
|
|
||||||
|
const app = createApp(App)
|
||||||
|
|
||||||
|
// 注册所有 Element Plus 图标
|
||||||
|
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||||
|
app.component(key, component)
|
||||||
|
}
|
||||||
|
|
||||||
|
app.use(ElementPlus)
|
||||||
|
app.use(createPinia())
|
||||||
|
app.use(router)
|
||||||
|
app.mount('#app')
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { createRouter, createWebHistory } from 'vue-router'
|
||||||
|
|
||||||
|
const routes = [
|
||||||
|
{
|
||||||
|
path: '/login',
|
||||||
|
name: 'Login',
|
||||||
|
component: () => import('../views/login/Login.vue')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/',
|
||||||
|
component: () => import('../layouts/MainLayout.vue'),
|
||||||
|
redirect: '/dashboard',
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
path: 'dashboard',
|
||||||
|
name: 'Dashboard',
|
||||||
|
component: () => import('../views/dashboard/Dashboard.vue'),
|
||||||
|
meta: { title: '首页大盘' }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'sites',
|
||||||
|
name: 'Sites',
|
||||||
|
component: () => import('../views/sites/Sites.vue'),
|
||||||
|
meta: { title: '站点管理' }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'logs',
|
||||||
|
name: 'Logs',
|
||||||
|
component: () => import('../views/logs/Logs.vue'),
|
||||||
|
meta: { title: '验证码日志' }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'ip-blacklist',
|
||||||
|
name: 'IpBlacklist',
|
||||||
|
component: () => import('../views/ip-blacklist/IpBlacklist.vue'),
|
||||||
|
meta: { title: 'IP黑名单' }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'plans',
|
||||||
|
name: 'Plans',
|
||||||
|
component: () => import('../views/plans/Plans.vue'),
|
||||||
|
meta: { title: '套餐管理' }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'settings',
|
||||||
|
name: 'Settings',
|
||||||
|
component: () => import('../views/settings/Settings.vue'),
|
||||||
|
meta: { title: '系统设置' }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
const router = createRouter({
|
||||||
|
history: createWebHistory('/admin/'),
|
||||||
|
routes
|
||||||
|
})
|
||||||
|
|
||||||
|
// 路由守卫
|
||||||
|
router.beforeEach((to, from, next) => {
|
||||||
|
const token = localStorage.getItem('token')
|
||||||
|
if (to.path !== '/login' && !token) {
|
||||||
|
next('/login')
|
||||||
|
} else {
|
||||||
|
next()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
export default router
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import { authApi } from '../api'
|
||||||
|
|
||||||
|
export const useUserStore = defineStore('user', () => {
|
||||||
|
const token = ref(localStorage.getItem('token') || '')
|
||||||
|
const username = ref(localStorage.getItem('username') || '')
|
||||||
|
const role = ref(localStorage.getItem('role') || '')
|
||||||
|
|
||||||
|
const login = async (loginData) => {
|
||||||
|
const res = await authApi.login(loginData)
|
||||||
|
if (res.data) {
|
||||||
|
token.value = res.data.token
|
||||||
|
username.value = res.data.username
|
||||||
|
role.value = res.data.role
|
||||||
|
localStorage.setItem('token', res.data.token)
|
||||||
|
localStorage.setItem('username', res.data.username)
|
||||||
|
localStorage.setItem('role', res.data.role)
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
const logout = () => {
|
||||||
|
token.value = ''
|
||||||
|
username.value = ''
|
||||||
|
role.value = ''
|
||||||
|
localStorage.removeItem('token')
|
||||||
|
localStorage.removeItem('username')
|
||||||
|
localStorage.removeItem('role')
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchUser = async () => {
|
||||||
|
try {
|
||||||
|
const res = await authApi.getMe()
|
||||||
|
if (res.data) {
|
||||||
|
username.value = res.data.username
|
||||||
|
role.value = res.data.role
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logout()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { token, username, role, login, logout, fetchUser }
|
||||||
|
})
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<template>
|
||||||
|
<div class="dashboard">
|
||||||
|
<el-row :gutter="20">
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<template #header>总请求量</template>
|
||||||
|
<div class="stat-value">{{ stats.total || 0 }}</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<template #header>成功次数</template>
|
||||||
|
<div class="stat-value" style="color: #67c23a">{{ stats.success || 0 }}</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<template #header>失败次数</template>
|
||||||
|
<div class="stat-value" style="color: #f56c6c">{{ stats.fail || 0 }}</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<template #header>成功率</template>
|
||||||
|
<div class="stat-value" style="color: #409eff">{{ stats.passRate || '0%' }}</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<el-row :gutter="20" style="margin-top: 20px">
|
||||||
|
<el-col :span="12">
|
||||||
|
<el-card>
|
||||||
|
<template #header>站点数量</template>
|
||||||
|
<div class="stat-value">{{ siteCount }}</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="12">
|
||||||
|
<el-card>
|
||||||
|
<template #header>活跃套餐</template>
|
||||||
|
<div class="stat-value">{{ planCount }}</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import { statsApi, siteApi, planApi } from '../../api'
|
||||||
|
|
||||||
|
const stats = ref({})
|
||||||
|
const siteCount = ref(0)
|
||||||
|
const planCount = ref(0)
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
try {
|
||||||
|
const [statsRes, sitesRes, plansRes] = await Promise.all([
|
||||||
|
statsApi.get({ days: 7 }),
|
||||||
|
siteApi.list({ page: 0, size: 1 }),
|
||||||
|
planApi.list()
|
||||||
|
])
|
||||||
|
stats.value = statsRes.data || {}
|
||||||
|
siteCount.value = sitesRes.data?.totalElements || 0
|
||||||
|
planCount.value = plansRes.data?.length || 0
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to load dashboard data', e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.stat-value {
|
||||||
|
font-size: 32px;
|
||||||
|
font-weight: bold;
|
||||||
|
text-align: center;
|
||||||
|
padding: 20px 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
<template>
|
||||||
|
<div class="ip-blacklist">
|
||||||
|
<el-card>
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>IP黑名单</span>
|
||||||
|
<el-button type="primary" @click="showDialog">封禁IP</el-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<el-table :data="blacklist" v-loading="loading" border>
|
||||||
|
<el-table-column prop="ip" label="IP地址" />
|
||||||
|
<el-table-column prop="reason" label="原因" />
|
||||||
|
<el-table-column prop="banUntil" label="封禁至" />
|
||||||
|
<el-table-column label="操作" width="120">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button size="small" type="danger" @click="handleUnban(row.ip)">解封</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<el-dialog v-model="dialogVisible" title="封禁IP" width="400px">
|
||||||
|
<el-form :model="form" label-width="80px">
|
||||||
|
<el-form-item label="IP地址">
|
||||||
|
<el-input v-model="form.ip" placeholder="例如: 192.168.1.1" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="原因">
|
||||||
|
<el-input v-model="form.reason" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="封禁时长">
|
||||||
|
<el-select v-model="form.durationMs">
|
||||||
|
<el-option label="1小时" :value="3600000" />
|
||||||
|
<el-option label="24小时" :value="86400000" />
|
||||||
|
<el-option label="7天" :value="604800000" />
|
||||||
|
<el-option label="永久" :value="31536000000" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="handleBan">确定</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, reactive, onMounted } from 'vue'
|
||||||
|
import { ipBlacklistApi } from '../../api'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
|
||||||
|
const blacklist = ref([])
|
||||||
|
const loading = ref(false)
|
||||||
|
const dialogVisible = ref(false)
|
||||||
|
const form = reactive({ ip: '', reason: '', durationMs: 3600000 })
|
||||||
|
|
||||||
|
const showDialog = () => {
|
||||||
|
form.ip = ''
|
||||||
|
form.reason = ''
|
||||||
|
form.durationMs = 3600000
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleBan = async () => {
|
||||||
|
await ipBlacklistApi.ban(form)
|
||||||
|
ElMessage.success('封禁成功')
|
||||||
|
dialogVisible.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleUnban = async (ip) => {
|
||||||
|
await ipBlacklistApi.unban(ip)
|
||||||
|
ElMessage.success('解封成功')
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.card-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
<template>
|
||||||
|
<div class="login-container">
|
||||||
|
<div class="login-card">
|
||||||
|
<div class="login-header">
|
||||||
|
<h2>TianAI Captcha 管理平台</h2>
|
||||||
|
</div>
|
||||||
|
<el-form ref="formRef" :model="form" :rules="rules" label-width="0">
|
||||||
|
<el-form-item prop="username">
|
||||||
|
<el-input v-model="form.username" placeholder="用户名" prefix-icon="User" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item prop="password">
|
||||||
|
<el-input v-model="form.password" type="password" placeholder="密码" prefix-icon="Lock" show-password />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item>
|
||||||
|
<el-button type="primary" :loading="loading" @click="handleLogin" style="width: 100%">
|
||||||
|
登录
|
||||||
|
</el-button>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, reactive } from 'vue'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
import { useUserStore } from '../../store/user'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const formRef = ref(null)
|
||||||
|
const loading = ref(false)
|
||||||
|
|
||||||
|
const form = reactive({
|
||||||
|
username: '',
|
||||||
|
password: ''
|
||||||
|
})
|
||||||
|
|
||||||
|
const rules = {
|
||||||
|
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
|
||||||
|
password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleLogin = async () => {
|
||||||
|
const valid = await formRef.value.validate().catch(() => false)
|
||||||
|
if (!valid) return
|
||||||
|
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
await userStore.login(form)
|
||||||
|
ElMessage.success('登录成功')
|
||||||
|
router.push('/')
|
||||||
|
} catch (e) {
|
||||||
|
ElMessage.error(e.msg || '登录失败')
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.login-container {
|
||||||
|
height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-card {
|
||||||
|
width: 400px;
|
||||||
|
padding: 40px;
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-header {
|
||||||
|
text-align: center;
|
||||||
|
margin-bottom: 30px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-header h2 {
|
||||||
|
color: #303133;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
<template>
|
||||||
|
<div class="logs">
|
||||||
|
<el-card>
|
||||||
|
<template #header>验证码日志</template>
|
||||||
|
|
||||||
|
<el-form :inline="true" :model="filters" style="margin-bottom: 20px">
|
||||||
|
<el-form-item label="验证码类型">
|
||||||
|
<el-select v-model="filters.captchaType" clearable placeholder="全部">
|
||||||
|
<el-option label="滑块验证" value="SLIDER" />
|
||||||
|
<el-option label="旋转验证" value="ROTATE" />
|
||||||
|
<el-option label="文字点选" value="WORD_IMAGE_CLICK" />
|
||||||
|
<el-option label="图标点选" value="ICON_CLICK" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="结果">
|
||||||
|
<el-select v-model="filters.isPass" clearable placeholder="全部">
|
||||||
|
<el-option label="成功" :value="true" />
|
||||||
|
<el-option label="失败" :value="false" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item>
|
||||||
|
<el-button type="primary" @click="loadLogs">查询</el-button>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
|
||||||
|
<el-table :data="logs" v-loading="loading" border>
|
||||||
|
<el-table-column prop="id" label="ID" width="80" />
|
||||||
|
<el-table-column prop="captchaType" label="类型" width="120" />
|
||||||
|
<el-table-column prop="ip" label="IP地址" width="140" />
|
||||||
|
<el-table-column prop="isPass" label="结果" width="80">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="row.isPass ? 'success' : 'danger'">
|
||||||
|
{{ row.isPass ? '成功' : '失败' }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="costTime" label="耗时(ms)" width="100" />
|
||||||
|
<el-table-column prop="scene" label="场景" width="100" />
|
||||||
|
<el-table-column prop="createdAt" label="时间">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ formatTime(row.createdAt) }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="page"
|
||||||
|
:page-size="20"
|
||||||
|
:total="total"
|
||||||
|
layout="total, prev, pager, next"
|
||||||
|
@current-change="loadLogs"
|
||||||
|
style="margin-top: 20px; justify-content: flex-end"
|
||||||
|
/>
|
||||||
|
</el-card>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, reactive, onMounted } from 'vue'
|
||||||
|
|
||||||
|
const logs = ref([])
|
||||||
|
const loading = ref(false)
|
||||||
|
const page = ref(1)
|
||||||
|
const total = ref(0)
|
||||||
|
const filters = reactive({ captchaType: '', isPass: null })
|
||||||
|
|
||||||
|
onMounted(() => loadLogs())
|
||||||
|
|
||||||
|
const loadLogs = async () => {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
// 模拟数据
|
||||||
|
logs.value = []
|
||||||
|
total.value = 0
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatTime = (t) => t ? new Date(t).toLocaleString() : '-'
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
<template>
|
||||||
|
<div class="plans">
|
||||||
|
<el-card>
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>套餐管理</span>
|
||||||
|
<el-button type="primary" @click="showDialog()">新增套餐</el-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<el-table :data="plans" v-loading="loading" border>
|
||||||
|
<el-table-column prop="id" label="ID" width="80" />
|
||||||
|
<el-table-column prop="name" label="套餐名称" />
|
||||||
|
<el-table-column prop="description" label="描述" />
|
||||||
|
<el-table-column prop="dailyQuota" label="每日配额" />
|
||||||
|
<el-table-column prop="qpsLimit" label="QPS限制" />
|
||||||
|
<el-table-column prop="siteLimit" label="站点限制" />
|
||||||
|
<el-table-column prop="isActive" label="状态" width="80">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="row.isActive ? 'success' : 'danger'">
|
||||||
|
{{ row.isActive ? '启用' : '禁用' }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="200">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button size="small" @click="showDialog(row)">编辑</el-button>
|
||||||
|
<el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<el-dialog v-model="dialogVisible" :title="editingPlan ? '编辑套餐' : '新增套餐'" width="500px">
|
||||||
|
<el-form :model="form" label-width="100px">
|
||||||
|
<el-form-item label="套餐名称">
|
||||||
|
<el-input v-model="form.name" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="描述">
|
||||||
|
<el-input v-model="form.description" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="每日配额">
|
||||||
|
<el-input-number v-model="form.dailyQuota" :min="1" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="QPS限制">
|
||||||
|
<el-input-number v-model="form.qpsLimit" :min="1" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="站点限制">
|
||||||
|
<el-input-number v-model="form.siteLimit" :min="1" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="handleSave">确定</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, reactive, onMounted } from 'vue'
|
||||||
|
import { planApi } from '../../api'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
|
||||||
|
const plans = ref([])
|
||||||
|
const loading = ref(false)
|
||||||
|
const dialogVisible = ref(false)
|
||||||
|
const editingPlan = ref(null)
|
||||||
|
const form = reactive({
|
||||||
|
name: '', description: '', dailyQuota: 500, qpsLimit: 10, siteLimit: 5
|
||||||
|
})
|
||||||
|
|
||||||
|
onMounted(() => loadPlans())
|
||||||
|
|
||||||
|
const loadPlans = async () => {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await planApi.list()
|
||||||
|
plans.value = res.data || []
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const showDialog = (plan) => {
|
||||||
|
editingPlan.value = plan
|
||||||
|
if (plan) {
|
||||||
|
Object.assign(form, plan)
|
||||||
|
} else {
|
||||||
|
form.name = ''
|
||||||
|
form.description = ''
|
||||||
|
form.dailyQuota = 500
|
||||||
|
form.qpsLimit = 10
|
||||||
|
form.siteLimit = 5
|
||||||
|
}
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
try {
|
||||||
|
if (editingPlan.value) {
|
||||||
|
await planApi.update(editingPlan.value.id, { ...form, id: editingPlan.value.id })
|
||||||
|
} else {
|
||||||
|
await planApi.create(form)
|
||||||
|
}
|
||||||
|
ElMessage.success('保存成功')
|
||||||
|
dialogVisible.value = false
|
||||||
|
loadPlans()
|
||||||
|
} catch (e) {
|
||||||
|
ElMessage.error('保存失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = async (id) => {
|
||||||
|
await ElMessageBox.confirm('确定删除该套餐?', '提示', { type: 'warning' })
|
||||||
|
await planApi.delete(id)
|
||||||
|
ElMessage.success('删除成功')
|
||||||
|
loadPlans()
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.card-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<template>
|
||||||
|
<div class="settings">
|
||||||
|
<el-card>
|
||||||
|
<template #header>系统设置</template>
|
||||||
|
<el-form :model="settings" label-width="120px" style="max-width: 600px">
|
||||||
|
<el-form-item label="验证码前缀">
|
||||||
|
<el-input v-model="settings.prefix" disabled />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="默认过期时间">
|
||||||
|
<el-input v-model="settings.expireDefault" disabled />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="本地缓存">
|
||||||
|
<el-switch v-model="settings.localCacheEnabled" disabled />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="缓存大小">
|
||||||
|
<el-input v-model="settings.localCacheSize" disabled />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</el-card>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { reactive } from 'vue'
|
||||||
|
|
||||||
|
const settings = reactive({
|
||||||
|
prefix: 'captcha',
|
||||||
|
expireDefault: '120000ms',
|
||||||
|
localCacheEnabled: true,
|
||||||
|
localCacheSize: 20
|
||||||
|
})
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
<template>
|
||||||
|
<div class="sites">
|
||||||
|
<el-card>
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>站点管理</span>
|
||||||
|
<el-button type="primary" @click="showDialog()">新增站点</el-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<el-table :data="sites" v-loading="loading" border>
|
||||||
|
<el-table-column prop="id" label="ID" width="80" />
|
||||||
|
<el-table-column prop="name" label="站点名称" />
|
||||||
|
<el-table-column prop="domain" label="域名" />
|
||||||
|
<el-table-column prop="siteKey" label="Site Key">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-text truncated>{{ row.siteKey }}</el-text>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="isEnabled" label="状态" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="row.isEnabled ? 'success' : 'danger'">
|
||||||
|
{{ row.isEnabled ? '启用' : '禁用' }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="200">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button size="small" @click="showDialog(row)">编辑</el-button>
|
||||||
|
<el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="page"
|
||||||
|
:page-size="20"
|
||||||
|
:total="total"
|
||||||
|
layout="total, prev, pager, next"
|
||||||
|
@current-change="loadSites"
|
||||||
|
style="margin-top: 20px; justify-content: flex-end"
|
||||||
|
/>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<el-dialog v-model="dialogVisible" :title="editingSite ? '编辑站点' : '新增站点'" width="500px">
|
||||||
|
<el-form :model="form" label-width="100px">
|
||||||
|
<el-form-item label="站点名称">
|
||||||
|
<el-input v-model="form.name" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="域名">
|
||||||
|
<el-input v-model="form.domain" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="启用">
|
||||||
|
<el-switch v-model="form.isEnabled" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="handleSave">确定</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, reactive, onMounted } from 'vue'
|
||||||
|
import { siteApi } from '../../api'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
|
||||||
|
const sites = ref([])
|
||||||
|
const loading = ref(false)
|
||||||
|
const page = ref(1)
|
||||||
|
const total = ref(0)
|
||||||
|
const dialogVisible = ref(false)
|
||||||
|
const editingSite = ref(null)
|
||||||
|
const form = reactive({ name: '', domain: '', isEnabled: true })
|
||||||
|
|
||||||
|
onMounted(() => loadSites())
|
||||||
|
|
||||||
|
const loadSites = async () => {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await siteApi.list({ page: page.value - 1, size: 20 })
|
||||||
|
sites.value = res.data?.content || []
|
||||||
|
total.value = res.data?.totalElements || 0
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const showDialog = (site) => {
|
||||||
|
editingSite.value = site
|
||||||
|
if (site) {
|
||||||
|
form.name = site.name
|
||||||
|
form.domain = site.domain
|
||||||
|
form.isEnabled = site.isEnabled
|
||||||
|
} else {
|
||||||
|
form.name = ''
|
||||||
|
form.domain = ''
|
||||||
|
form.isEnabled = true
|
||||||
|
}
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
try {
|
||||||
|
if (editingSite.value) {
|
||||||
|
await siteApi.update(editingSite.value.id, { ...form, id: editingSite.value.id })
|
||||||
|
} else {
|
||||||
|
await siteApi.create(form)
|
||||||
|
}
|
||||||
|
ElMessage.success('保存成功')
|
||||||
|
dialogVisible.value = false
|
||||||
|
loadSites()
|
||||||
|
} catch (e) {
|
||||||
|
ElMessage.error('保存失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = async (id) => {
|
||||||
|
await ElMessageBox.confirm('确定删除该站点?', '提示', { type: 'warning' })
|
||||||
|
await siteApi.delete(id)
|
||||||
|
ElMessage.success('删除成功')
|
||||||
|
loadSites()
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.card-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import vue from '@vitejs/plugin-vue'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [vue()],
|
||||||
|
base: '/admin/',
|
||||||
|
server: {
|
||||||
|
port: 5174,
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: 'http://localhost:18200',
|
||||||
|
changeOrigin: true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
FROM eclipse-temurin:21-jre-alpine
|
||||||
|
|
||||||
|
RUN apk add --no-cache fontconfig ttf-dejavu
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY tianai-captcha-platform-2.0.0-SNAPSHOT.jar /app/captcha-platform.jar
|
||||||
|
|
||||||
|
EXPOSE 18200
|
||||||
|
|
||||||
|
ENTRYPOINT ["java", "-jar", "/app/captcha-platform.jar"]
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
container_name: captcha-postgres
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: captcha_forge
|
||||||
|
POSTGRES_USER: pgsql
|
||||||
|
POSTGRES_PASSWORD: ${PG_PASSWORD:-tianai-captcha-pg}
|
||||||
|
ports:
|
||||||
|
- "5432:5432"
|
||||||
|
volumes:
|
||||||
|
- pg-data:/var/lib/postgresql/data
|
||||||
|
- ./sql/init.sql:/docker-entrypoint-initdb.d/01-init.sql
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U pgsql -d captcha_forge"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
container_name: captcha-redis
|
||||||
|
ports:
|
||||||
|
- "6379:6379"
|
||||||
|
volumes:
|
||||||
|
- redis-data:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
minio:
|
||||||
|
image: minio/minio:latest
|
||||||
|
container_name: captcha-minio
|
||||||
|
environment:
|
||||||
|
MINIO_ROOT_USER: ${MINIO_USER:-minioadmin}
|
||||||
|
MINIO_ROOT_PASSWORD: ${MINIO_PASSWORD:-minioadmin}
|
||||||
|
ports:
|
||||||
|
- "9000:9000"
|
||||||
|
- "9001:9001"
|
||||||
|
volumes:
|
||||||
|
- minio-data:/data
|
||||||
|
command: server /data --console-address ":9001"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "mc", "ready", "local"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
captcha-platform:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: captcha-platform
|
||||||
|
environment:
|
||||||
|
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/captcha_forge
|
||||||
|
SPRING_DATASOURCE_USERNAME: pgsql
|
||||||
|
SPRING_DATASOURCE_PASSWORD: ${PG_PASSWORD:-tianai-captcha-pg}
|
||||||
|
SPRING_DATA_REDIS_HOST: redis
|
||||||
|
SPRING_DATA_REDIS_PORT: 6379
|
||||||
|
MINIO_ENDPOINT: http://minio:9000
|
||||||
|
MINIO_ACCESS_KEY: ${MINIO_USER:-minioadmin}
|
||||||
|
MINIO_SECRET_KEY: ${MINIO_PASSWORD:-minioadmin}
|
||||||
|
JWT_SECRET: ${JWT_SECRET:-tianai-captcha-jwt-secret-key-must-be-at-least-256-bits-long-for-hs256}
|
||||||
|
ports:
|
||||||
|
- "18200:18200"
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
minio:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "curl -f http://localhost:18200/api/admin/stats || exit 1"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
|
||||||
|
captcha-admin:
|
||||||
|
build:
|
||||||
|
context: ../tianai-captcha-platform-ui
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: captcha-admin
|
||||||
|
ports:
|
||||||
|
- "3000:80"
|
||||||
|
depends_on:
|
||||||
|
- captcha-platform
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
pg-data:
|
||||||
|
redis-data:
|
||||||
|
minio-data:
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent>
|
||||||
|
<groupId>cloud.tianai.captcha</groupId>
|
||||||
|
<artifactId>tianai-captcha-parent</artifactId>
|
||||||
|
<version>${revision}</version>
|
||||||
|
<relativePath>../pom.xml</relativePath>
|
||||||
|
</parent>
|
||||||
|
<artifactId>tianai-captcha-platform</artifactId>
|
||||||
|
<name>tianai-captcha-platform</name>
|
||||||
|
<description>验证码服务平台后端</description>
|
||||||
|
|
||||||
|
<dependencyManagement>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-dependencies</artifactId>
|
||||||
|
<version>${spring-boot.version}</version>
|
||||||
|
<type>pom</type>
|
||||||
|
<scope>import</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</dependencyManagement>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.postgresql</groupId>
|
||||||
|
<artifactId>postgresql</artifactId>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cloud.tianai.captcha</groupId>
|
||||||
|
<artifactId>tianai-captcha-springboot-starter</artifactId>
|
||||||
|
<version>${revision}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.code.gson</groupId>
|
||||||
|
<artifactId>gson</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.jsonwebtoken</groupId>
|
||||||
|
<artifactId>jjwt-api</artifactId>
|
||||||
|
<version>0.12.6</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.jsonwebtoken</groupId>
|
||||||
|
<artifactId>jjwt-impl</artifactId>
|
||||||
|
<version>0.12.6</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.jsonwebtoken</groupId>
|
||||||
|
<artifactId>jjwt-jackson</artifactId>
|
||||||
|
<version>0.12.6</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-security</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.minio</groupId>
|
||||||
|
<artifactId>minio</artifactId>
|
||||||
|
<version>8.5.7</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-aop</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
<version>${spring-boot.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>repackage</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.14.0</version>
|
||||||
|
<configuration>
|
||||||
|
<release>21</release>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
DROP TABLE IF EXISTS verification_logs CASCADE;
|
||||||
|
DROP TABLE IF EXISTS track_samples CASCADE;
|
||||||
|
DROP TABLE IF EXISTS captcha_challenges CASCADE;
|
||||||
|
DROP TABLE IF EXISTS captcha_categories CASCADE;
|
||||||
|
DROP TABLE IF EXISTS sites CASCADE;
|
||||||
|
DROP TABLE IF EXISTS plans CASCADE;
|
||||||
|
DROP TABLE IF EXISTS users CASCADE;
|
||||||
|
DROP TABLE IF EXISTS announcements CASCADE;
|
||||||
|
DROP TABLE IF EXISTS captcha_ip_blacklist CASCADE;
|
||||||
|
|
||||||
|
CREATE TABLE users (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
username VARCHAR(64) NOT NULL UNIQUE,
|
||||||
|
email VARCHAR(128),
|
||||||
|
password VARCHAR(256) NOT NULL,
|
||||||
|
role VARCHAR(16) DEFAULT 'USER',
|
||||||
|
site_amount INT DEFAULT 0,
|
||||||
|
is_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
is_system BOOLEAN DEFAULT FALSE,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE plans (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
name VARCHAR(64) NOT NULL,
|
||||||
|
description VARCHAR(256),
|
||||||
|
qps INT DEFAULT 10,
|
||||||
|
daily_limit INT DEFAULT 500,
|
||||||
|
captcha_types TEXT[] DEFAULT '{SLIDER,PUZZLE,TEXT_CLICK,ICON_CLICK,ICON_UNDERSTAND}',
|
||||||
|
custom_style BOOLEAN DEFAULT FALSE,
|
||||||
|
is_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
is_system BOOLEAN DEFAULT FALSE,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE sites (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
user_id INT REFERENCES users(id),
|
||||||
|
name VARCHAR(64) NOT NULL,
|
||||||
|
domain VARCHAR(256),
|
||||||
|
favicon VARCHAR(512),
|
||||||
|
logo VARCHAR(512),
|
||||||
|
site_key UUID DEFAULT gen_random_uuid() UNIQUE,
|
||||||
|
secret_key UUID DEFAULT gen_random_uuid() UNIQUE,
|
||||||
|
verify_level VARCHAR(16) DEFAULT 'MEDIUM',
|
||||||
|
qps INT DEFAULT 10,
|
||||||
|
daily_limit INT DEFAULT 500,
|
||||||
|
captcha_types TEXT[] DEFAULT '{SLIDER,PUZZLE,TEXT_CLICK,ICON_CLICK,ICON_UNDERSTAND}',
|
||||||
|
plan_id INT REFERENCES plans(id),
|
||||||
|
plan_expire_at TIMESTAMPTZ,
|
||||||
|
is_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
rsa_public_key TEXT,
|
||||||
|
rsa_private_key TEXT,
|
||||||
|
aes_key VARCHAR(256),
|
||||||
|
signing_key VARCHAR(256),
|
||||||
|
track_validation_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
track_human_threshold FLOAT DEFAULT 0.5,
|
||||||
|
obfuscation_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
encryption_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE captcha_categories (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
name VARCHAR(64) NOT NULL,
|
||||||
|
label VARCHAR(64) NOT NULL,
|
||||||
|
items TEXT[] NOT NULL DEFAULT '{}',
|
||||||
|
is_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE captcha_challenges (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
category_id INT REFERENCES captcha_categories(id) ON DELETE CASCADE,
|
||||||
|
prompt TEXT NOT NULL,
|
||||||
|
correct_items TEXT[] NOT NULL DEFAULT '{}',
|
||||||
|
difficulty VARCHAR(16) DEFAULT 'MEDIUM',
|
||||||
|
is_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
use_count INT DEFAULT 0,
|
||||||
|
success_rate DOUBLE PRECISION DEFAULT 0.5,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE verification_logs (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
site_id INT REFERENCES sites(id),
|
||||||
|
site_key UUID,
|
||||||
|
captcha_type VARCHAR(32),
|
||||||
|
scene VARCHAR(64) DEFAULT 'default',
|
||||||
|
ip VARCHAR(45),
|
||||||
|
is_pass BOOLEAN,
|
||||||
|
behavior_score DOUBLE PRECISION,
|
||||||
|
risk_level VARCHAR(16),
|
||||||
|
cost_time INT,
|
||||||
|
captcha_id VARCHAR(128),
|
||||||
|
user_agent TEXT,
|
||||||
|
track_score FLOAT,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE track_samples (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
site_id INT REFERENCES sites(id),
|
||||||
|
captcha_type VARCHAR(32),
|
||||||
|
is_human BOOLEAN,
|
||||||
|
ml_score DOUBLE PRECISION,
|
||||||
|
basic_pass BOOLEAN,
|
||||||
|
total_points INT,
|
||||||
|
total_duration BIGINT,
|
||||||
|
displacement_x FLOAT,
|
||||||
|
displacement_y FLOAT,
|
||||||
|
displacement_x_ratio FLOAT,
|
||||||
|
total_path_length DOUBLE PRECISION,
|
||||||
|
path_efficiency DOUBLE PRECISION,
|
||||||
|
avg_speed FLOAT,
|
||||||
|
max_speed FLOAT,
|
||||||
|
min_speed FLOAT,
|
||||||
|
speed_variance DOUBLE PRECISION,
|
||||||
|
speed_std_dev DOUBLE PRECISION,
|
||||||
|
speed_skewness DOUBLE PRECISION,
|
||||||
|
avg_acceleration FLOAT,
|
||||||
|
max_acceleration FLOAT,
|
||||||
|
min_acceleration FLOAT,
|
||||||
|
acceleration_variance DOUBLE PRECISION,
|
||||||
|
direction_changes INT,
|
||||||
|
y_direction_changes INT,
|
||||||
|
pauses INT,
|
||||||
|
start_offset DOUBLE PRECISION,
|
||||||
|
straightness DOUBLE PRECISION,
|
||||||
|
x_uniformity DOUBLE PRECISION,
|
||||||
|
y_uniformity DOUBLE PRECISION,
|
||||||
|
avg_point_interval FLOAT,
|
||||||
|
speed_phase_correlation DOUBLE PRECISION,
|
||||||
|
max_jump_distance DOUBLE PRECISION,
|
||||||
|
overshoot_ratio DOUBLE PRECISION,
|
||||||
|
track_json TEXT,
|
||||||
|
ip VARCHAR(45),
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE announcements (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
title VARCHAR(256) NOT NULL,
|
||||||
|
content TEXT,
|
||||||
|
is_pinned BOOLEAN DEFAULT FALSE,
|
||||||
|
is_published BOOLEAN DEFAULT TRUE,
|
||||||
|
sort_order INT DEFAULT 0,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE captcha_ip_blacklist (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
ip VARCHAR(64) NOT NULL,
|
||||||
|
reason VARCHAR(256),
|
||||||
|
ban_until TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_sites_key ON sites(site_key);
|
||||||
|
CREATE INDEX idx_sites_user ON sites(user_id);
|
||||||
|
CREATE INDEX idx_challenges_category ON captcha_challenges(category_id);
|
||||||
|
CREATE INDEX idx_challenges_difficulty ON captcha_challenges(difficulty);
|
||||||
|
CREATE INDEX idx_logs_site ON verification_logs(site_id);
|
||||||
|
CREATE INDEX idx_logs_time ON verification_logs(created_at);
|
||||||
|
CREATE INDEX idx_logs_type ON verification_logs(captcha_type);
|
||||||
|
CREATE INDEX idx_logs_pass ON verification_logs(is_pass);
|
||||||
|
CREATE INDEX idx_ip_blacklist_ip ON captcha_ip_blacklist(ip);
|
||||||
|
CREATE INDEX idx_track_human ON track_samples(is_human);
|
||||||
|
CREATE INDEX idx_track_type ON track_samples(captcha_type);
|
||||||
|
CREATE INDEX idx_track_time ON track_samples(created_at);
|
||||||
|
CREATE INDEX idx_track_score ON track_samples(ml_score);
|
||||||
|
|
||||||
|
INSERT INTO users (username, email, password, role, site_amount, is_enabled, is_system)
|
||||||
|
VALUES ('admin', 'admin@captchaforge.local', '$2a$10$85QOiy3qD5KPuxyrrN/LcuZe3ty/OrTk6yEKAJEGtJKk97ukw2yPG', 'ADMIN', 999, TRUE, TRUE);
|
||||||
|
|
||||||
|
INSERT INTO plans (name, description, qps, daily_limit, is_enabled, is_system) VALUES
|
||||||
|
('免费套餐', '默认免费套餐', 5, 500, TRUE, TRUE),
|
||||||
|
('基础套餐', '适合中小站点', 20, 5000, TRUE, TRUE),
|
||||||
|
('专业套餐', '适合大型站点', 100, 50000, TRUE, TRUE);
|
||||||
|
|
||||||
|
INSERT INTO captcha_categories (name, label, items) VALUES
|
||||||
|
('animals', '动物', '{"🐶","🐱","🐭","🐹","🐰","🦊","🐻","🐼","🐨","🐯","🦁","🐮","🐷","🐸","🐵","🐔","🐧","🐦","🦅","🦆","🦉","🐴","🦄","🐝","🐛","🦋","🐌","🐞","🐢","🐍","🦎","🐙","🦑","🦐","🦀","🐠","🐟","🐬","🐳","🐊","🐘","🦏","🐪","🦒","🐕","🐈","🐓","🦃","🦚","🦜","🐇","🦔","🐺","🐗"}'),
|
||||||
|
('food', '食物饮品', '{"🍎","🍐","🍊","🍋","🍌","🍉","🍇","🍓","🍒","🍑","🥭","🍍","🥥","🥝","🍅","🍆","🥑","🥦","🌽","🥕","🍞","🧀","🍳","🍔","🍟","🍕","🌮","🍣","🍜","🍩","🍪","🎂","🍫","🍭","☕","🍵","🧃","🥤","🍺","🍷"}'),
|
||||||
|
('vehicles', '交通工具', '{"🚗","🚕","🚙","🚌","🏎","🚓","🚑","🚒","🚐","🚚","🚛","🚜","🚲","🛵","🏍","🚨","🚔","🚡","🚠","🚃","🚋","🚄","🚅","🚂","✈️","🛩","🚀","🛸","🚁","⛵","🚤","🛳","⛴","🚢"}'),
|
||||||
|
('nature', '天气自然', '{"☀️","🌤","⛅","🌥","☁️","🌦","🌧","⛈","🌩","🌨","❄️","☃️","🌪","🌈","🌊","💧","🔥","⭐","🌟","✨","⚡","☄️","🌸","🌺","🌻","🌹","🌷","🌱","🌿","🍀","🍁","🍂","🍃","🌴","🌵"}'),
|
||||||
|
('sports', '运动娱乐', '{"⚽","🏀","🏈","⚾","🎾","🏐","🏉","🎱","🏓","🏸","🏒","🏑","🥍","🎯","🎳","🎮","🎲","♟","🧩","🪀","🪁","🎪","🤹","🎭","🎨","🎬","🎤","🎧","🎹","🥁","🎸","🎻"}'),
|
||||||
|
('buildings', '建筑地点', '{"🏠","🏡","🏢","🏣","🏤","🏥","🏦","🏨","🏩","🏪","🏫","🏬","🏭","🏯","🏰","💒","🗼","🗽","⛪","🕌","🛕","🕍","⛩","🕋","⛲","⛺","🏕"}'),
|
||||||
|
('objects', '电子物品', '{"⌚","📱","💻","⌨️","🖥","🖨","🖱","🖲","💾","💿","📷","📹","🎥","📞","📺","📻","🔋","🔌","💡","🔦","🕯","🔑","🔒","🔓","📧","📮","📦","📋","📁","✏️","🖊","🖋","✒️","🖌","📝","🔍","📎","📐","📌","✂️","🧲","🔧","🔨","⚙️","💊","💉","🩺","🧬","🔭","🔬","🧪"}'),
|
||||||
|
('gestures', '手势动作', '{"👋","🤚","🖐","✋","🖖","👌","🤌","🤏","✌","🤞","🤟","🤘","🤙","👈","👉","👆","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","✍️","💅","🤳","💪"}');
|
||||||
|
|
||||||
|
INSERT INTO captcha_challenges (category_id, prompt, correct_items, difficulty) VALUES
|
||||||
|
(1, '请点击所有的猫科动物', '{"🐱","🐯","🦁","🐈"}', 'MEDIUM'),
|
||||||
|
(1, '请点击所有的犬科动物', '{"🐶","🐺","🐕"}', 'MEDIUM'),
|
||||||
|
(1, '请点击所有的鸟类', '{"🐔","🐧","🐦","🦅","🦆","🦉","🦜","🦚","🦃"}', 'MEDIUM'),
|
||||||
|
(1, '请点击所有的水生动物', '{"🐙","🦑","🦐","🦀","🐠","🐟","🐬","🐳"}', 'MEDIUM'),
|
||||||
|
(1, '请点击所有的昆虫', '{"🐝","🐛","🦋","🐌","🐞","🦟"}', 'MEDIUM'),
|
||||||
|
(2, '请点击所有的水果', '{"🍎","🍐","🍊","🍋","🍌","🍉","🍇","🍓","🍒","🍑","🥭","🍍","🥝"}', 'MEDIUM'),
|
||||||
|
(2, '请点击所有的蔬菜', '{"🍅","🍆","🥑","🥦","🌽","🥕"}', 'MEDIUM'),
|
||||||
|
(2, '请点击所有的饮品', '{"☕","🍵","🧃","🥤","🍺","🍷"}', 'MEDIUM'),
|
||||||
|
(2, '请点击所有的甜点', '{"🍩","🍪","🎂","🍫","🍭"}', 'MEDIUM'),
|
||||||
|
(3, '请点击所有的汽车', '{"🚗","🚕","🚙","🏎","🚓","🚑","🚒","🚐"}', 'MEDIUM'),
|
||||||
|
(3, '请点击所有的飞行器', '{"✈️","🛩","🚀","🛸","🚁"}', 'MEDIUM'),
|
||||||
|
(3, '请点击所有的船只', '{"⛵","🚤","🛳","⛴","🚢"}', 'MEDIUM'),
|
||||||
|
(4, '请点击所有与降水相关的', '{"🌦","🌧","⛈","🌩","🌨"}', 'MEDIUM'),
|
||||||
|
(4, '请点击所有的花卉', '{"🌸","🌺","🌻","🌹","🌷"}', 'MEDIUM'),
|
||||||
|
(4, '请点击所有的天体', '{"☀️","⭐","🌟","✨","⚡","☄️"}', 'MEDIUM'),
|
||||||
|
(5, '请点击所有的球类运动', '{"⚽","🏀","🏈","⚾","🎾","🏐","🏉"}', 'MEDIUM'),
|
||||||
|
(5, '请点击所有的音乐相关', '{"🎤","🎧","🎹","🥁","🎸","🎻"}', 'MEDIUM'),
|
||||||
|
(5, '请点击所有的棋牌游戏', '{"🎲","♟","🧩","🎮","🎯","🎱"}', 'MEDIUM'),
|
||||||
|
(1, '请点击所有的动物', '{"🐶","🐱","🐭","🐹","🐰","🦊","🐻","🐼","🐨","🐯","🦁","🐮","🐷","🐸","🐵","🐔","🐧","🐦","🦅","🦆","🦉","🐴","🦄","🐝","🐛","🦋","🐌","🐞","🐢","🐍","🦎","🐙","🦑","🦐","🦀","🐠","🐟","🐬","🐳","🐊","🐘","🦏","🐪","🦒","🐕","🐈","🐓","🦃","🦚","🦜","🐇","🦔","🐺","🐗"}', 'LOW'),
|
||||||
|
(2, '请点击所有的食物饮品', '{"🍎","🍐","🍊","🍋","🍌","🍉","🍇","🍓","🍒","🍑","🥭","🍍","🥥","🥝","🍅","🍆","🥑","🥦","🌽","🥕","🍞","🧀","🍳","🍔","🍟","🍕","🌮","🍣","🍜","🍩","🍪","🎂","🍫","🍭","☕","🍵","🧃","🥤","🍺","🍷"}', 'LOW'),
|
||||||
|
(3, '请点击所有的交通工具', '{"🚗","🚕","🚙","🚌","🏎","🚓","🚑","🚒","🚐","🚚","🚛","🚜","🚲","🛵","🏍","🚨","🚔","🚡","🚠","🚃","🚋","🚄","🚅","🚂","✈️","🛩","🚀","🛸","🚁","⛵","🚤","🛳","⛴","🚢"}', 'LOW'),
|
||||||
|
(4, '请点击所有的天气自然', '{"☀️","🌤","⛅","🌥","☁️","🌦","🌧","⛈","🌩","🌨","❄️","☃️","🌪","🌈","🌊","💧","🔥","⭐","🌟","✨","⚡","☄️","🌸","🌺","🌻","🌹","🌷","🌱","🌿","🍀","🍁","🍂","🍃","🌴","🌵"}', 'LOW');
|
||||||
|
|
||||||
|
INSERT INTO announcements (title, content, is_pinned, is_published, sort_order) VALUES
|
||||||
|
('tianai-captcha-enhanced 2.0.0 上线', '# tianai-captcha-enhanced
|
||||||
|
|
||||||
|
基于 tianai-captcha 开源版的增强版行为验证码平台
|
||||||
|
|
||||||
|
## 特性
|
||||||
|
- 16种验证码类型
|
||||||
|
- ML轨迹校验器(28维特征+14条规则)
|
||||||
|
- 对抗扰动防YOLO
|
||||||
|
- 行为风控引擎
|
||||||
|
- 端到端加密(AES-256+RSA-4096)
|
||||||
|
- 背景乱序/正弦扭曲/噪声注入
|
||||||
|
- IP黑名单+滑动窗口限流', TRUE, TRUE, 0);
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package cloud.tianai.captcha.platform;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||||
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
|
|
||||||
|
@SpringBootApplication(scanBasePackages = {"cloud.tianai.captcha"})
|
||||||
|
@EnableJpaRepositories(basePackages = "cloud.tianai.captcha.platform.mapper")
|
||||||
|
@EnableScheduling
|
||||||
|
public class CaptchaPlatformApplication {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(CaptchaPlatformApplication.class, args);
|
||||||
|
}
|
||||||
|
}
|
||||||
+100
@@ -0,0 +1,100 @@
|
|||||||
|
package cloud.tianai.captcha.platform.aspect;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.platform.entity.CaptchaLog;
|
||||||
|
import cloud.tianai.captcha.platform.mapper.CaptchaLogRepository;
|
||||||
|
import cloud.tianai.captcha.platform.service.RealtimeStatsService;
|
||||||
|
import org.aspectj.lang.ProceedingJoinPoint;
|
||||||
|
import org.aspectj.lang.annotation.*;
|
||||||
|
import org.aspectj.lang.reflect.MethodSignature;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.context.request.RequestContextHolder;
|
||||||
|
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
@Aspect
|
||||||
|
@Component
|
||||||
|
public class CaptchaLogAspect {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(CaptchaLogAspect.class);
|
||||||
|
private final CaptchaLogRepository logRepository;
|
||||||
|
private final RealtimeStatsService statsService;
|
||||||
|
|
||||||
|
public CaptchaLogAspect(CaptchaLogRepository logRepository, RealtimeStatsService statsService) {
|
||||||
|
this.logRepository = logRepository;
|
||||||
|
this.statsService = statsService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Around("execution(* cloud.tianai.captcha.platform.controller.CaptchaApiController.*(..))")
|
||||||
|
public Object logCaptchaRequest(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||||
|
long startTime = System.currentTimeMillis();
|
||||||
|
Object result = joinPoint.proceed();
|
||||||
|
long duration = System.currentTimeMillis() - startTime;
|
||||||
|
|
||||||
|
try {
|
||||||
|
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||||
|
String methodName = signature.getName();
|
||||||
|
|
||||||
|
String ip = extractIp();
|
||||||
|
String siteKey = extractSiteKey(joinPoint.getArgs());
|
||||||
|
|
||||||
|
Map<String, Object> stats = new ConcurrentHashMap<>();
|
||||||
|
stats.put("method", methodName);
|
||||||
|
stats.put("duration", duration);
|
||||||
|
stats.put("ip", ip);
|
||||||
|
stats.put("siteKey", siteKey);
|
||||||
|
|
||||||
|
if ("verify".equals(methodName) && result instanceof cloud.tianai.captcha.common.response.ApiResponse<?> response) {
|
||||||
|
stats.put("success", response.isSuccess());
|
||||||
|
stats.put("captchaType", "VERIFY");
|
||||||
|
statsService.recordVerifyAttempt(response.isSuccess(), ip, siteKey);
|
||||||
|
} else if ("generate".equals(methodName)) {
|
||||||
|
stats.put("success", true);
|
||||||
|
stats.put("captchaType", "GENERATE");
|
||||||
|
statsService.recordGenerate(ip, siteKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
statsService.incrementTotalRequests();
|
||||||
|
|
||||||
|
log.debug("[CAPTCHA-AOP] {} took {}ms ip={}", methodName, duration, ip);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("[CAPTCHA-AOP] Failed to log stats: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String extractIp() {
|
||||||
|
try {
|
||||||
|
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||||
|
if (attrs != null) {
|
||||||
|
HttpServletRequest request = attrs.getRequest();
|
||||||
|
String xff = request.getHeader("X-Forwarded-For");
|
||||||
|
if (xff != null && !xff.isEmpty()) {
|
||||||
|
return xff.split(",")[0].trim();
|
||||||
|
}
|
||||||
|
String xreal = request.getHeader("X-Real-IP");
|
||||||
|
if (xreal != null && !xreal.isEmpty()) {
|
||||||
|
return xreal;
|
||||||
|
}
|
||||||
|
return request.getRemoteAddr();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
return "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
private String extractSiteKey(Object[] args) {
|
||||||
|
for (Object arg : args) {
|
||||||
|
if (arg instanceof String s && s != null && s.length() > 10) {
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "unknown";
|
||||||
|
}
|
||||||
|
}
|
||||||
+105
@@ -0,0 +1,105 @@
|
|||||||
|
package cloud.tianai.captcha.platform.config;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.application.ImageCaptchaApplication;
|
||||||
|
import cloud.tianai.captcha.cache.CacheStore;
|
||||||
|
import cloud.tianai.captcha.cache.impl.LocalCacheStore;
|
||||||
|
import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
|
||||||
|
import cloud.tianai.captcha.resource.CrudResourceStore;
|
||||||
|
import cloud.tianai.captcha.resource.ResourceStore;
|
||||||
|
import cloud.tianai.captcha.resource.common.model.dto.Resource;
|
||||||
|
import cloud.tianai.captcha.resource.common.model.dto.ResourceMap;
|
||||||
|
import cloud.tianai.captcha.risk.IpBlacklist;
|
||||||
|
import cloud.tianai.captcha.risk.RiskEngine;
|
||||||
|
import cloud.tianai.captcha.site.TokenService;
|
||||||
|
import cloud.tianai.captcha.validator.ImageCaptchaValidator;
|
||||||
|
import cloud.tianai.captcha.validator.impl.EnhancedTrackValidator;
|
||||||
|
import org.springframework.boot.CommandLineRunner;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static cloud.tianai.captcha.common.constant.CommonConstant.DEFAULT_TAG;
|
||||||
|
import static cloud.tianai.captcha.generator.impl.StandardSliderImageCaptchaGenerator.TEMPLATE_ACTIVE_IMAGE_NAME;
|
||||||
|
import static cloud.tianai.captcha.generator.impl.StandardSliderImageCaptchaGenerator.TEMPLATE_FIXED_IMAGE_NAME;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class CaptchaPlatformConfig {
|
||||||
|
|
||||||
|
private static final String TP = "META-INF/cut-image/template";
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public CacheStore cacheStore() {
|
||||||
|
return new LocalCacheStore();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public RiskEngine riskEngine() {
|
||||||
|
return new RiskEngine();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public IpBlacklist ipBlacklist() {
|
||||||
|
return new IpBlacklist();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public TokenService tokenService(CacheStore cacheStore) {
|
||||||
|
return new TokenService(cacheStore);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ImageCaptchaValidator captchaValidator() {
|
||||||
|
return new EnhancedTrackValidator();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public CommandLineRunner initCaptchaResources(ResourceStore resourceStore) {
|
||||||
|
return args -> {
|
||||||
|
if (resourceStore instanceof CrudResourceStore crud) {
|
||||||
|
List<String> bgTypes = List.of(
|
||||||
|
CaptchaTypeConstant.SLIDER,
|
||||||
|
CaptchaTypeConstant.SLIDER_V2,
|
||||||
|
CaptchaTypeConstant.ROTATE,
|
||||||
|
CaptchaTypeConstant.CONCAT,
|
||||||
|
CaptchaTypeConstant.WORD_IMAGE_CLICK,
|
||||||
|
CaptchaTypeConstant.ICON_CLICK,
|
||||||
|
CaptchaTypeConstant.WORD_ORDER_CLICK,
|
||||||
|
CaptchaTypeConstant.CURVE_SLIDER,
|
||||||
|
CaptchaTypeConstant.CURVE_SLIDER_V2,
|
||||||
|
CaptchaTypeConstant.CURVE_SLIDER_V3,
|
||||||
|
CaptchaTypeConstant.ANGLE,
|
||||||
|
CaptchaTypeConstant.SCRATCH,
|
||||||
|
CaptchaTypeConstant.JIGSAW,
|
||||||
|
CaptchaTypeConstant.CURVE_DRAW
|
||||||
|
);
|
||||||
|
for (String type : bgTypes) {
|
||||||
|
crud.addResource(type, new Resource("classpath", "META-INF/cut-image/resource/1.jpg"));
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> sliderAliasTypes = List.of(
|
||||||
|
CaptchaTypeConstant.SLIDER_V2,
|
||||||
|
CaptchaTypeConstant.CONCAT,
|
||||||
|
CaptchaTypeConstant.CURVE_SLIDER,
|
||||||
|
CaptchaTypeConstant.CURVE_SLIDER_V2,
|
||||||
|
CaptchaTypeConstant.CURVE_SLIDER_V3,
|
||||||
|
CaptchaTypeConstant.ANGLE,
|
||||||
|
CaptchaTypeConstant.SCRATCH,
|
||||||
|
CaptchaTypeConstant.JIGSAW,
|
||||||
|
CaptchaTypeConstant.CURVE_DRAW
|
||||||
|
);
|
||||||
|
for (String type : sliderAliasTypes) {
|
||||||
|
ResourceMap t1 = new ResourceMap(DEFAULT_TAG, 4);
|
||||||
|
t1.put(TEMPLATE_ACTIVE_IMAGE_NAME, new Resource("classpath", TP + "/slider_1/active.png"));
|
||||||
|
t1.put(TEMPLATE_FIXED_IMAGE_NAME, new Resource("classpath", TP + "/slider_1/fixed.png"));
|
||||||
|
crud.addTemplate(type, t1);
|
||||||
|
|
||||||
|
ResourceMap t2 = new ResourceMap(DEFAULT_TAG, 4);
|
||||||
|
t2.put(TEMPLATE_ACTIVE_IMAGE_NAME, new Resource("classpath", TP + "/slider_2/active.png"));
|
||||||
|
t2.put(TEMPLATE_FIXED_IMAGE_NAME, new Resource("classpath", TP + "/slider_2/fixed.png"));
|
||||||
|
crud.addTemplate(type, t2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
package cloud.tianai.captcha.platform.config;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class CorsConfig implements WebMvcConfigurer {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addCorsMappings(CorsRegistry registry) {
|
||||||
|
registry.addMapping("/api/**")
|
||||||
|
.allowedOriginPatterns("*")
|
||||||
|
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
|
||||||
|
.allowedHeaders("*")
|
||||||
|
.allowCredentials(true)
|
||||||
|
.maxAge(3600);
|
||||||
|
}
|
||||||
|
}
|
||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
package cloud.tianai.captcha.platform.config;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.platform.service.JwtService;
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Collections;
|
||||||
|
|
||||||
|
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
private final JwtService jwtService;
|
||||||
|
|
||||||
|
public JwtAuthenticationFilter(JwtService jwtService) {
|
||||||
|
this.jwtService = jwtService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||||
|
throws ServletException, IOException {
|
||||||
|
String header = request.getHeader("Authorization");
|
||||||
|
|
||||||
|
if (header != null && header.startsWith("Bearer ")) {
|
||||||
|
String token = header.substring(7);
|
||||||
|
try {
|
||||||
|
if (jwtService.validateToken(token)) {
|
||||||
|
String username = jwtService.getUsernameFromToken(token);
|
||||||
|
Integer userId = jwtService.getUserIdFromToken(token);
|
||||||
|
String role = jwtService.getRoleFromToken(token);
|
||||||
|
|
||||||
|
UsernamePasswordAuthenticationToken authentication =
|
||||||
|
new UsernamePasswordAuthenticationToken(
|
||||||
|
userId,
|
||||||
|
null,
|
||||||
|
Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + role))
|
||||||
|
);
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
SecurityContextHolder.clearContext();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
+67
@@ -0,0 +1,67 @@
|
|||||||
|
package cloud.tianai.captcha.platform.config;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.platform.service.JwtService;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||||
|
import org.springframework.web.cors.CorsConfiguration;
|
||||||
|
import org.springframework.web.cors.CorsConfigurationSource;
|
||||||
|
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSecurity
|
||||||
|
public class SecurityConfig {
|
||||||
|
|
||||||
|
private final JwtService jwtService;
|
||||||
|
|
||||||
|
public SecurityConfig(JwtService jwtService) {
|
||||||
|
this.jwtService = jwtService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public PasswordEncoder passwordEncoder() {
|
||||||
|
return new BCryptPasswordEncoder();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public JwtAuthenticationFilter jwtAuthenticationFilter() {
|
||||||
|
return new JwtAuthenticationFilter(jwtService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||||
|
http
|
||||||
|
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||||
|
.csrf(csrf -> csrf.disable())
|
||||||
|
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||||
|
.authorizeHttpRequests(auth -> auth
|
||||||
|
.requestMatchers("/api/auth/**").permitAll()
|
||||||
|
.requestMatchers("/api/captcha/**").permitAll()
|
||||||
|
.requestMatchers("/api/admin/**").authenticated()
|
||||||
|
.anyRequest().permitAll()
|
||||||
|
)
|
||||||
|
.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
|
||||||
|
|
||||||
|
return http.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public CorsConfigurationSource corsConfigurationSource() {
|
||||||
|
CorsConfiguration configuration = new CorsConfiguration();
|
||||||
|
configuration.setAllowedOrigins(List.of("*"));
|
||||||
|
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
|
||||||
|
configuration.setAllowedHeaders(List.of("*"));
|
||||||
|
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||||
|
source.registerCorsConfiguration("/**", configuration);
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
}
|
||||||
+101
@@ -0,0 +1,101 @@
|
|||||||
|
package cloud.tianai.captcha.platform.controller;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.common.response.ApiResponse;
|
||||||
|
import cloud.tianai.captcha.platform.entity.User;
|
||||||
|
import cloud.tianai.captcha.platform.mapper.UserRepository;
|
||||||
|
import cloud.tianai.captcha.platform.service.JwtService;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/auth")
|
||||||
|
public class AuthController {
|
||||||
|
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
private final JwtService jwtService;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
|
public AuthController(UserRepository userRepository, JwtService jwtService, PasswordEncoder passwordEncoder) {
|
||||||
|
this.userRepository = userRepository;
|
||||||
|
this.jwtService = jwtService;
|
||||||
|
this.passwordEncoder = passwordEncoder;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/login")
|
||||||
|
public ApiResponse<?> login(@RequestBody Map<String, String> body) {
|
||||||
|
String username = body.get("username");
|
||||||
|
String password = body.get("password");
|
||||||
|
|
||||||
|
if (username == null || password == null) {
|
||||||
|
return ApiResponse.of(400, "missing_params", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
User user = userRepository.findByUsername(username).orElse(null);
|
||||||
|
if (user == null || !passwordEncoder.matches(password, user.getPasswordHash())) {
|
||||||
|
return ApiResponse.of(401, "invalid_credentials", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user.getIsEnabled()) {
|
||||||
|
return ApiResponse.of(403, "account_disabled", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
String token = jwtService.generateToken(user.getId(), user.getUsername(), user.getRole());
|
||||||
|
Map<String, Object> data = new HashMap<>();
|
||||||
|
data.put("token", token);
|
||||||
|
data.put("username", user.getUsername());
|
||||||
|
data.put("role", user.getRole());
|
||||||
|
return ApiResponse.ofSuccess(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/register")
|
||||||
|
public ApiResponse<?> register(@RequestBody Map<String, String> body) {
|
||||||
|
String username = body.get("username");
|
||||||
|
String password = body.get("password");
|
||||||
|
String email = body.get("email");
|
||||||
|
|
||||||
|
if (username == null || password == null) {
|
||||||
|
return ApiResponse.of(400, "missing_params", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (userRepository.existsByUsername(username)) {
|
||||||
|
return ApiResponse.of(409, "username_exists", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
User user = new User();
|
||||||
|
user.setUsername(username);
|
||||||
|
user.setPasswordHash(passwordEncoder.encode(password));
|
||||||
|
user.setEmail(email);
|
||||||
|
user.setRole("USER");
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
return ApiResponse.ofSuccess("Registration successful");
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/me")
|
||||||
|
public ApiResponse<?> getCurrentUser(@RequestHeader("Authorization") String authHeader) {
|
||||||
|
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
||||||
|
return ApiResponse.of(401, "unauthorized", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
String token = authHeader.substring(7);
|
||||||
|
if (!jwtService.validateToken(token)) {
|
||||||
|
return ApiResponse.of(401, "invalid_token", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
Integer userId = jwtService.getUserIdFromToken(token);
|
||||||
|
User user = userRepository.findById(userId).orElse(null);
|
||||||
|
if (user == null) {
|
||||||
|
return ApiResponse.of(404, "user_not_found", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> data = new HashMap<>();
|
||||||
|
data.put("id", user.getId());
|
||||||
|
data.put("username", user.getUsername());
|
||||||
|
data.put("email", user.getEmail());
|
||||||
|
data.put("role", user.getRole());
|
||||||
|
return ApiResponse.ofSuccess(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
+65
@@ -0,0 +1,65 @@
|
|||||||
|
package cloud.tianai.captcha.platform.controller;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.application.ImageCaptchaApplication;
|
||||||
|
import cloud.tianai.captcha.application.vo.ImageCaptchaVO;
|
||||||
|
import cloud.tianai.captcha.common.response.ApiResponse;
|
||||||
|
import cloud.tianai.captcha.platform.service.CaptchaPlatformService;
|
||||||
|
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
|
||||||
|
import cloud.tianai.captcha.validator.common.model.dto.MatchParam;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api")
|
||||||
|
public class CaptchaApiController {
|
||||||
|
|
||||||
|
private final CaptchaPlatformService platformService;
|
||||||
|
|
||||||
|
public CaptchaApiController(CaptchaPlatformService platformService) {
|
||||||
|
this.platformService = platformService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/challenge/generate")
|
||||||
|
public ApiResponse<ImageCaptchaVO> generate(
|
||||||
|
@RequestHeader(value = "X-Site-Key", required = false) String siteKey,
|
||||||
|
@RequestParam(value = "type", required = false) String type,
|
||||||
|
@RequestParam(value = "scene", required = false, defaultValue = "default") String scene,
|
||||||
|
@RequestHeader(value = "X-Real-IP", required = false) String ip,
|
||||||
|
@RequestHeader(value = "X-Forwarded-For", required = false) String forwardedFor) {
|
||||||
|
String clientIp = resolveIp(ip, forwardedFor);
|
||||||
|
return platformService.generateCaptcha(siteKey, type, scene, clientIp);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/challenge/verify")
|
||||||
|
public ApiResponse<?> verify(
|
||||||
|
@RequestHeader(value = "X-Site-Key", required = false) String siteKey,
|
||||||
|
@RequestBody Map<String, Object> body) {
|
||||||
|
String captchaId = (String) body.get("id");
|
||||||
|
Object trackData = body.get("data");
|
||||||
|
String ip = (String) body.getOrDefault("ip", "unknown");
|
||||||
|
return platformService.verifyCaptcha(siteKey, captchaId, trackData, ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/challenge/secondary-verify")
|
||||||
|
public ApiResponse<?> secondaryVerify(
|
||||||
|
@RequestBody Map<String, Object> body) {
|
||||||
|
String siteKey = (String) body.get("siteKey");
|
||||||
|
String secretKey = (String) body.get("secretKey");
|
||||||
|
String verifyToken = (String) body.get("verifyToken");
|
||||||
|
return platformService.secondaryVerify(siteKey, secretKey, verifyToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/challenge/public-key")
|
||||||
|
public ApiResponse<?> getPublicKey(
|
||||||
|
@RequestHeader(value = "X-Site-Key", required = false) String siteKey) {
|
||||||
|
return platformService.getPublicKey(siteKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String resolveIp(String ip, String forwardedFor) {
|
||||||
|
if (forwardedFor != null && !forwardedFor.isEmpty()) {
|
||||||
|
return forwardedFor.split(",")[0].trim();
|
||||||
|
}
|
||||||
|
return ip != null ? ip : "unknown";
|
||||||
|
}
|
||||||
|
}
|
||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
package cloud.tianai.captcha.platform.controller;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.common.response.ApiResponse;
|
||||||
|
import cloud.tianai.captcha.platform.entity.Plan;
|
||||||
|
import cloud.tianai.captcha.platform.mapper.PlanRepository;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/admin/plans")
|
||||||
|
public class PlanController {
|
||||||
|
|
||||||
|
private final PlanRepository planRepository;
|
||||||
|
|
||||||
|
public PlanController(PlanRepository planRepository) {
|
||||||
|
this.planRepository = planRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public ApiResponse<List<Plan>> listPlans() {
|
||||||
|
return ApiResponse.ofSuccess(planRepository.findAll());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/active")
|
||||||
|
public ApiResponse<List<Plan>> listActivePlans() {
|
||||||
|
return ApiResponse.ofSuccess(planRepository.findByIsActiveTrue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public ApiResponse<Plan> getPlan(@PathVariable Integer id) {
|
||||||
|
Plan plan = planRepository.findById(id).orElse(null);
|
||||||
|
if (plan == null) {
|
||||||
|
return ApiResponse.of(404, "plan_not_found", null);
|
||||||
|
}
|
||||||
|
return ApiResponse.ofSuccess(plan);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public ApiResponse<Plan> createPlan(@RequestBody Plan plan) {
|
||||||
|
plan.setId(null);
|
||||||
|
return ApiResponse.ofSuccess(planRepository.save(plan));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public ApiResponse<Plan> updatePlan(@PathVariable Integer id, @RequestBody Plan plan) {
|
||||||
|
Plan existing = planRepository.findById(id).orElse(null);
|
||||||
|
if (existing == null) {
|
||||||
|
return ApiResponse.of(404, "plan_not_found", null);
|
||||||
|
}
|
||||||
|
plan.setId(id);
|
||||||
|
return ApiResponse.ofSuccess(planRepository.save(plan));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public ApiResponse<?> deletePlan(@PathVariable Integer id) {
|
||||||
|
planRepository.deleteById(id);
|
||||||
|
return ApiResponse.ofSuccess();
|
||||||
|
}
|
||||||
|
}
|
||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
package cloud.tianai.captcha.platform.controller;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.common.response.ApiResponse;
|
||||||
|
import cloud.tianai.captcha.platform.service.MinioStorageService;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/admin/resources")
|
||||||
|
public class ResourceController {
|
||||||
|
|
||||||
|
private final MinioStorageService storageService;
|
||||||
|
|
||||||
|
public ResourceController(MinioStorageService storageService) {
|
||||||
|
this.storageService = storageService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/upload")
|
||||||
|
public ApiResponse<?> uploadFile(
|
||||||
|
@RequestParam("file") MultipartFile file,
|
||||||
|
@RequestParam(value = "prefix", defaultValue = "general") String prefix) {
|
||||||
|
try {
|
||||||
|
String url = storageService.uploadFile(file, prefix);
|
||||||
|
Map<String, Object> data = new HashMap<>();
|
||||||
|
data.put("url", url);
|
||||||
|
data.put("filename", file.getOriginalFilename());
|
||||||
|
data.put("size", file.getSize());
|
||||||
|
return ApiResponse.ofSuccess(data);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ApiResponse.of(500, "upload_failed", null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping
|
||||||
|
public ApiResponse<?> deleteFile(@RequestParam String objectName) {
|
||||||
|
try {
|
||||||
|
storageService.deleteFile(objectName);
|
||||||
|
return ApiResponse.ofSuccess();
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ApiResponse.of(500, "delete_failed", null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/presigned-url")
|
||||||
|
public ApiResponse<?> getPresignedUrl(
|
||||||
|
@RequestParam String objectName,
|
||||||
|
@RequestParam(defaultValue = "3600") int expirySeconds) {
|
||||||
|
try {
|
||||||
|
String url = storageService.getPresignedUrl(objectName, expirySeconds);
|
||||||
|
Map<String, Object> data = new HashMap<>();
|
||||||
|
data.put("url", url);
|
||||||
|
return ApiResponse.ofSuccess(data);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ApiResponse.of(500, "url_generation_failed", null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+98
@@ -0,0 +1,98 @@
|
|||||||
|
package cloud.tianai.captcha.platform.controller;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.common.response.ApiResponse;
|
||||||
|
import cloud.tianai.captcha.platform.entity.CaptchaSite;
|
||||||
|
import cloud.tianai.captcha.platform.service.CaptchaPlatformService;
|
||||||
|
import cloud.tianai.captcha.platform.service.TrackLearningService;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/admin")
|
||||||
|
public class SiteAdminController {
|
||||||
|
|
||||||
|
private final CaptchaPlatformService platformService;
|
||||||
|
private final TrackLearningService trackLearningService;
|
||||||
|
|
||||||
|
public SiteAdminController(CaptchaPlatformService platformService, TrackLearningService trackLearningService) {
|
||||||
|
this.platformService = platformService;
|
||||||
|
this.trackLearningService = trackLearningService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/sites")
|
||||||
|
public ApiResponse<CaptchaSite> createSite(@RequestBody Map<String, Object> body) {
|
||||||
|
String name = (String) body.get("name");
|
||||||
|
String domain = (String) body.get("domain");
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Set<String> captchaTypes = body.get("captchaTypes") != null
|
||||||
|
? Set.copyOf((java.util.List<String>) body.get("captchaTypes"))
|
||||||
|
: null;
|
||||||
|
if (captchaTypes == null && body.get("allowedTypes") != null) {
|
||||||
|
captchaTypes = Set.copyOf((java.util.List<String>) body.get("allowedTypes"));
|
||||||
|
}
|
||||||
|
CaptchaSite site = platformService.createSite(name, domain, captchaTypes);
|
||||||
|
return ApiResponse.ofSuccess(site);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/sites")
|
||||||
|
public ApiResponse<Page<CaptchaSite>> listSites(
|
||||||
|
@RequestParam(defaultValue = "0") int page,
|
||||||
|
@RequestParam(defaultValue = "20") int size) {
|
||||||
|
return ApiResponse.ofSuccess(platformService.listSites(PageRequest.of(page, size)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/sites/{siteId}")
|
||||||
|
public ApiResponse<CaptchaSite> getSite(@PathVariable Integer siteId) {
|
||||||
|
return ApiResponse.ofSuccess(platformService.getSite(siteId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/sites/{siteId}")
|
||||||
|
public ApiResponse<CaptchaSite> updateSite(@PathVariable Integer siteId, @RequestBody CaptchaSite site) {
|
||||||
|
site.setId(siteId);
|
||||||
|
return ApiResponse.ofSuccess(platformService.updateSite(site));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/sites/{siteId}")
|
||||||
|
public ApiResponse<?> deleteSite(@PathVariable Integer siteId) {
|
||||||
|
platformService.deleteSite(siteId);
|
||||||
|
return ApiResponse.ofSuccess();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/stats")
|
||||||
|
public ApiResponse<?> getStats(
|
||||||
|
@RequestParam(required = false) Integer siteId,
|
||||||
|
@RequestParam(defaultValue = "7") int days) {
|
||||||
|
return ApiResponse.ofSuccess(platformService.getStats(siteId, days));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/ip-blacklist")
|
||||||
|
public ApiResponse<?> banIp(@RequestBody Map<String, Object> body) {
|
||||||
|
String ip = (String) body.get("ip");
|
||||||
|
String reason = (String) body.get("reason");
|
||||||
|
long durationMs = body.get("durationMs") != null
|
||||||
|
? ((Number) body.get("durationMs")).longValue()
|
||||||
|
: 3600000L;
|
||||||
|
platformService.banIp(ip, reason, durationMs);
|
||||||
|
return ApiResponse.ofSuccess();
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/ip-blacklist/{ip}")
|
||||||
|
public ApiResponse<?> unbanIp(@PathVariable String ip) {
|
||||||
|
platformService.unbanIp(ip);
|
||||||
|
return ApiResponse.ofSuccess();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/ml/status")
|
||||||
|
public ApiResponse<?> getMlStatus() {
|
||||||
|
return ApiResponse.ofSuccess(trackLearningService.getStatus());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/ml/train")
|
||||||
|
public ApiResponse<?> triggerTraining() {
|
||||||
|
return ApiResponse.ofSuccess(trackLearningService.trainIfNeeded());
|
||||||
|
}
|
||||||
|
}
|
||||||
+91
@@ -0,0 +1,91 @@
|
|||||||
|
package cloud.tianai.captcha.platform.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "verification_logs")
|
||||||
|
public class CaptchaLog {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Integer id;
|
||||||
|
|
||||||
|
@Column(name = "site_id")
|
||||||
|
private Integer siteId;
|
||||||
|
|
||||||
|
@Column(name = "site_key")
|
||||||
|
private java.util.UUID siteKey;
|
||||||
|
|
||||||
|
@Column(name = "captcha_type", length = 32)
|
||||||
|
private String captchaType;
|
||||||
|
|
||||||
|
@Column(length = 64)
|
||||||
|
private String scene = "default";
|
||||||
|
|
||||||
|
@Column(length = 45)
|
||||||
|
private String ip;
|
||||||
|
|
||||||
|
@Column(name = "is_pass")
|
||||||
|
private Boolean isPass;
|
||||||
|
|
||||||
|
@Column(name = "behavior_score")
|
||||||
|
private Double behaviorScore;
|
||||||
|
|
||||||
|
@Column(name = "risk_level", length = 16)
|
||||||
|
private String riskLevel;
|
||||||
|
|
||||||
|
@Column(name = "cost_time")
|
||||||
|
private Integer costTime;
|
||||||
|
|
||||||
|
@Column(name = "captcha_id", length = 128)
|
||||||
|
private String captchaId;
|
||||||
|
|
||||||
|
@Column(name = "user_agent", columnDefinition = "TEXT")
|
||||||
|
private String userAgent;
|
||||||
|
|
||||||
|
@Column(name = "track_score")
|
||||||
|
private Double trackScore;
|
||||||
|
|
||||||
|
@Column(name = "created_at")
|
||||||
|
private OffsetDateTime createdAt;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
protected void onCreate() { createdAt = OffsetDateTime.now(); }
|
||||||
|
|
||||||
|
public Integer getId() { return id; }
|
||||||
|
public void setId(Integer id) { this.id = id; }
|
||||||
|
public Integer getSiteId() { return siteId; }
|
||||||
|
public void setSiteId(Integer v) { this.siteId = v; }
|
||||||
|
public java.util.UUID getSiteKey() { return siteKey; }
|
||||||
|
public void setSiteKey(java.util.UUID v) { this.siteKey = v; }
|
||||||
|
public String getCaptchaType() { return captchaType; }
|
||||||
|
public void setCaptchaType(String v) { this.captchaType = v; }
|
||||||
|
public String getScene() { return scene; }
|
||||||
|
public void setScene(String v) { this.scene = v; }
|
||||||
|
public String getIp() { return ip; }
|
||||||
|
public void setIp(String v) { this.ip = v; }
|
||||||
|
public Boolean getIsPass() { return isPass; }
|
||||||
|
public void setIsPass(Boolean v) { this.isPass = v; }
|
||||||
|
public Double getBehaviorScore() { return behaviorScore; }
|
||||||
|
public void setBehaviorScore(Double v) { this.behaviorScore = v; }
|
||||||
|
public String getRiskLevel() { return riskLevel; }
|
||||||
|
public void setRiskLevel(String v) { this.riskLevel = v; }
|
||||||
|
public Integer getCostTime() { return costTime; }
|
||||||
|
public void setCostTime(Integer v) { this.costTime = v; }
|
||||||
|
public String getCaptchaId() { return captchaId; }
|
||||||
|
public void setCaptchaId(String v) { this.captchaId = v; }
|
||||||
|
public String getUserAgent() { return userAgent; }
|
||||||
|
public void setUserAgent(String v) { this.userAgent = v; }
|
||||||
|
public Double getTrackScore() { return trackScore; }
|
||||||
|
public void setTrackScore(Double v) { this.trackScore = v; }
|
||||||
|
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||||
|
public void setCreatedAt(OffsetDateTime v) { this.createdAt = v; }
|
||||||
|
|
||||||
|
public String getResult() { return isPass != null && isPass ? "SUCCESS" : "FAIL"; }
|
||||||
|
public void setResult(String v) { this.isPass = "SUCCESS".equals(v); }
|
||||||
|
public String getType() { return captchaType; }
|
||||||
|
public void setType(String v) { this.captchaType = v; }
|
||||||
|
public Long getDurationMs() { return costTime != null ? costTime.longValue() : null; }
|
||||||
|
public void setDurationMs(Long v) { this.costTime = v != null ? v.intValue() : null; }
|
||||||
|
}
|
||||||
+158
@@ -0,0 +1,158 @@
|
|||||||
|
package cloud.tianai.captcha.platform.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "sites")
|
||||||
|
public class CaptchaSite {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Integer id;
|
||||||
|
|
||||||
|
@Column(name = "user_id")
|
||||||
|
private Integer userId;
|
||||||
|
|
||||||
|
@Column(length = 64, nullable = false)
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Column(length = 256)
|
||||||
|
private String domain;
|
||||||
|
|
||||||
|
@Column(length = 512)
|
||||||
|
private String favicon;
|
||||||
|
|
||||||
|
@Column(length = 512)
|
||||||
|
private String logo;
|
||||||
|
|
||||||
|
@Column(name = "site_key", unique = true)
|
||||||
|
private java.util.UUID siteKey;
|
||||||
|
|
||||||
|
@Column(name = "secret_key", unique = true)
|
||||||
|
private java.util.UUID secretKey;
|
||||||
|
|
||||||
|
@Column(name = "verify_level", length = 16)
|
||||||
|
private String verifyLevel = "MEDIUM";
|
||||||
|
|
||||||
|
@Column
|
||||||
|
private Integer qps = 10;
|
||||||
|
|
||||||
|
@Column(name = "daily_limit")
|
||||||
|
private Integer dailyLimit = 500;
|
||||||
|
|
||||||
|
@Column(name = "captcha_types", columnDefinition = "TEXT[]")
|
||||||
|
private Set<String> captchaTypes;
|
||||||
|
|
||||||
|
@Column(name = "plan_id")
|
||||||
|
private Integer planId;
|
||||||
|
|
||||||
|
@Column(name = "plan_expire_at")
|
||||||
|
private OffsetDateTime planExpireAt;
|
||||||
|
|
||||||
|
@Column(name = "is_enabled")
|
||||||
|
private Boolean isEnabled = true;
|
||||||
|
|
||||||
|
@Column(name = "rsa_public_key", columnDefinition = "TEXT")
|
||||||
|
private String rsaPublicKey;
|
||||||
|
|
||||||
|
@Column(name = "rsa_private_key", columnDefinition = "TEXT")
|
||||||
|
private String rsaPrivateKey;
|
||||||
|
|
||||||
|
@Column(name = "aes_key", length = 256)
|
||||||
|
private String aesKey;
|
||||||
|
|
||||||
|
@Column(name = "signing_key", length = 256)
|
||||||
|
private String signingKey;
|
||||||
|
|
||||||
|
@Column(name = "track_validation_enabled")
|
||||||
|
private Boolean trackValidationEnabled = true;
|
||||||
|
|
||||||
|
@Column(name = "track_human_threshold")
|
||||||
|
private Double trackHumanThreshold = 0.5;
|
||||||
|
|
||||||
|
@Column(name = "obfuscation_enabled")
|
||||||
|
private Boolean obfuscationEnabled = true;
|
||||||
|
|
||||||
|
@Column(name = "encryption_enabled")
|
||||||
|
private Boolean encryptionEnabled = true;
|
||||||
|
|
||||||
|
@Column(name = "created_at")
|
||||||
|
private OffsetDateTime createdAt;
|
||||||
|
|
||||||
|
@Column(name = "updated_at")
|
||||||
|
private OffsetDateTime updatedAt;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
protected void onCreate() {
|
||||||
|
createdAt = OffsetDateTime.now();
|
||||||
|
updatedAt = OffsetDateTime.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreUpdate
|
||||||
|
protected void onUpdate() {
|
||||||
|
updatedAt = OffsetDateTime.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getId() { return id; }
|
||||||
|
public void setId(Integer id) { this.id = id; }
|
||||||
|
public Integer getUserId() { return userId; }
|
||||||
|
public void setUserId(Integer userId) { this.userId = userId; }
|
||||||
|
public String getName() { return name; }
|
||||||
|
public void setName(String name) { this.name = name; }
|
||||||
|
public String getDomain() { return domain; }
|
||||||
|
public void setDomain(String domain) { this.domain = domain; }
|
||||||
|
public String getFavicon() { return favicon; }
|
||||||
|
public void setFavicon(String favicon) { this.favicon = favicon; }
|
||||||
|
public String getLogo() { return logo; }
|
||||||
|
public void setLogo(String logo) { this.logo = logo; }
|
||||||
|
public java.util.UUID getSiteKey() { return siteKey; }
|
||||||
|
public void setSiteKey(java.util.UUID siteKey) { this.siteKey = siteKey; }
|
||||||
|
public java.util.UUID getSecretKey() { return secretKey; }
|
||||||
|
public void setSecretKey(java.util.UUID secretKey) { this.secretKey = secretKey; }
|
||||||
|
public String getVerifyLevel() { return verifyLevel; }
|
||||||
|
public void setVerifyLevel(String verifyLevel) { this.verifyLevel = verifyLevel; }
|
||||||
|
public Integer getQps() { return qps; }
|
||||||
|
public void setQps(Integer qps) { this.qps = qps; }
|
||||||
|
public Integer getDailyLimit() { return dailyLimit; }
|
||||||
|
public void setDailyLimit(Integer dailyLimit) { this.dailyLimit = dailyLimit; }
|
||||||
|
public Set<String> getCaptchaTypes() { return captchaTypes; }
|
||||||
|
public void setCaptchaTypes(Set<String> captchaTypes) { this.captchaTypes = captchaTypes; }
|
||||||
|
public Integer getPlanId() { return planId; }
|
||||||
|
public void setPlanId(Integer planId) { this.planId = planId; }
|
||||||
|
public OffsetDateTime getPlanExpireAt() { return planExpireAt; }
|
||||||
|
public void setPlanExpireAt(OffsetDateTime planExpireAt) { this.planExpireAt = planExpireAt; }
|
||||||
|
public Boolean getIsEnabled() { return isEnabled; }
|
||||||
|
public void setIsEnabled(Boolean isEnabled) { this.isEnabled = isEnabled; }
|
||||||
|
public String getRsaPublicKey() { return rsaPublicKey; }
|
||||||
|
public void setRsaPublicKey(String v) { this.rsaPublicKey = v; }
|
||||||
|
public String getRsaPrivateKey() { return rsaPrivateKey; }
|
||||||
|
public void setRsaPrivateKey(String v) { this.rsaPrivateKey = v; }
|
||||||
|
public String getAesKey() { return aesKey; }
|
||||||
|
public void setAesKey(String v) { this.aesKey = v; }
|
||||||
|
public String getSigningKey() { return signingKey; }
|
||||||
|
public void setSigningKey(String v) { this.signingKey = v; }
|
||||||
|
public Boolean getTrackValidationEnabled() { return trackValidationEnabled; }
|
||||||
|
public void setTrackValidationEnabled(Boolean v) { this.trackValidationEnabled = v; }
|
||||||
|
public Double getTrackHumanThreshold() { return trackHumanThreshold; }
|
||||||
|
public void setTrackHumanThreshold(Double v) { this.trackHumanThreshold = v; }
|
||||||
|
public Boolean getObfuscationEnabled() { return obfuscationEnabled; }
|
||||||
|
public void setObfuscationEnabled(Boolean v) { this.obfuscationEnabled = v; }
|
||||||
|
public Boolean getEncryptionEnabled() { return encryptionEnabled; }
|
||||||
|
public void setEncryptionEnabled(Boolean v) { this.encryptionEnabled = v; }
|
||||||
|
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||||
|
public void setCreatedAt(OffsetDateTime v) { this.createdAt = v; }
|
||||||
|
public OffsetDateTime getUpdatedAt() { return updatedAt; }
|
||||||
|
public void setUpdatedAt(OffsetDateTime v) { this.updatedAt = v; }
|
||||||
|
|
||||||
|
public Boolean getEnabled() { return isEnabled; }
|
||||||
|
public void setEnabled(Boolean v) { this.isEnabled = v; }
|
||||||
|
public Set<String> getAllowedTypes() { return captchaTypes; }
|
||||||
|
public void setAllowedTypes(Set<String> v) { this.captchaTypes = v; }
|
||||||
|
public String getLevel() { return verifyLevel; }
|
||||||
|
public void setLevel(String v) { this.verifyLevel = v; }
|
||||||
|
public Integer getMaxQps() { return qps; }
|
||||||
|
public void setMaxQps(Integer v) { this.qps = v; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package cloud.tianai.captcha.platform.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "plans")
|
||||||
|
public class Plan {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Integer id;
|
||||||
|
|
||||||
|
@Column(length = 64, nullable = false)
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Column(length = 256)
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
@Column(nullable = false, precision = 10, scale = 2)
|
||||||
|
private BigDecimal price;
|
||||||
|
|
||||||
|
@Column(name = "daily_quota", nullable = false)
|
||||||
|
private Integer dailyQuota;
|
||||||
|
|
||||||
|
@Column(name = "qps_limit", nullable = false)
|
||||||
|
private Integer qpsLimit;
|
||||||
|
|
||||||
|
@Column(name = "site_limit", nullable = false)
|
||||||
|
private Integer siteLimit;
|
||||||
|
|
||||||
|
@Column(name = "features", columnDefinition = "TEXT[]")
|
||||||
|
private java.util.Set<String> features;
|
||||||
|
|
||||||
|
@Column(name = "is_active")
|
||||||
|
private Boolean isActive = true;
|
||||||
|
|
||||||
|
@Column(name = "created_at")
|
||||||
|
private OffsetDateTime createdAt;
|
||||||
|
|
||||||
|
@Column(name = "updated_at")
|
||||||
|
private OffsetDateTime updatedAt;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
protected void onCreate() {
|
||||||
|
createdAt = OffsetDateTime.now();
|
||||||
|
updatedAt = OffsetDateTime.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreUpdate
|
||||||
|
protected void onUpdate() {
|
||||||
|
updatedAt = OffsetDateTime.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getId() { return id; }
|
||||||
|
public void setId(Integer id) { this.id = id; }
|
||||||
|
public String getName() { return name; }
|
||||||
|
public void setName(String name) { this.name = name; }
|
||||||
|
public String getDescription() { return description; }
|
||||||
|
public void setDescription(String description) { this.description = description; }
|
||||||
|
public BigDecimal getPrice() { return price; }
|
||||||
|
public void setPrice(BigDecimal price) { this.price = price; }
|
||||||
|
public Integer getDailyQuota() { return dailyQuota; }
|
||||||
|
public void setDailyQuota(Integer dailyQuota) { this.dailyQuota = dailyQuota; }
|
||||||
|
public Integer getQpsLimit() { return qpsLimit; }
|
||||||
|
public void setQpsLimit(Integer qpsLimit) { this.qpsLimit = qpsLimit; }
|
||||||
|
public Integer getSiteLimit() { return siteLimit; }
|
||||||
|
public void setSiteLimit(Integer siteLimit) { this.siteLimit = siteLimit; }
|
||||||
|
public java.util.Set<String> getFeatures() { return features; }
|
||||||
|
public void setFeatures(java.util.Set<String> features) { this.features = features; }
|
||||||
|
public Boolean getIsActive() { return isActive; }
|
||||||
|
public void setIsActive(Boolean isActive) { this.isActive = isActive; }
|
||||||
|
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||||
|
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
|
||||||
|
public OffsetDateTime getUpdatedAt() { return updatedAt; }
|
||||||
|
public void setUpdatedAt(OffsetDateTime updatedAt) { this.updatedAt = updatedAt; }
|
||||||
|
}
|
||||||
+239
@@ -0,0 +1,239 @@
|
|||||||
|
package cloud.tianai.captcha.platform.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "track_samples")
|
||||||
|
public class TrackSample {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Integer id;
|
||||||
|
|
||||||
|
@Column(name = "site_id")
|
||||||
|
private Integer siteId;
|
||||||
|
|
||||||
|
@Column(name = "captcha_type", length = 32)
|
||||||
|
private String captchaType;
|
||||||
|
|
||||||
|
@Column(name = "is_human")
|
||||||
|
private Boolean isHuman;
|
||||||
|
|
||||||
|
@Column(name = "ml_score")
|
||||||
|
private Double mlScore;
|
||||||
|
|
||||||
|
@Column(name = "basic_pass")
|
||||||
|
private Boolean basicPass;
|
||||||
|
|
||||||
|
@Column(name = "total_points")
|
||||||
|
private Integer totalPoints;
|
||||||
|
|
||||||
|
@Column(name = "total_duration")
|
||||||
|
private Long totalDuration;
|
||||||
|
|
||||||
|
@Column(name = "displacement_x")
|
||||||
|
private Float displacementX;
|
||||||
|
|
||||||
|
@Column(name = "displacement_y")
|
||||||
|
private Float displacementY;
|
||||||
|
|
||||||
|
@Column(name = "displacement_x_ratio")
|
||||||
|
private Float displacementXRatio;
|
||||||
|
|
||||||
|
@Column(name = "total_path_length")
|
||||||
|
private Double totalPathLength;
|
||||||
|
|
||||||
|
@Column(name = "path_efficiency")
|
||||||
|
private Double pathEfficiency;
|
||||||
|
|
||||||
|
@Column(name = "avg_speed")
|
||||||
|
private Float avgSpeed;
|
||||||
|
|
||||||
|
@Column(name = "max_speed")
|
||||||
|
private Float maxSpeed;
|
||||||
|
|
||||||
|
@Column(name = "min_speed")
|
||||||
|
private Float minSpeed;
|
||||||
|
|
||||||
|
@Column(name = "speed_variance")
|
||||||
|
private Double speedVariance;
|
||||||
|
|
||||||
|
@Column(name = "speed_std_dev")
|
||||||
|
private Double speedStdDev;
|
||||||
|
|
||||||
|
@Column(name = "speed_skewness")
|
||||||
|
private Double speedSkewness;
|
||||||
|
|
||||||
|
@Column(name = "avg_acceleration")
|
||||||
|
private Float avgAcceleration;
|
||||||
|
|
||||||
|
@Column(name = "max_acceleration")
|
||||||
|
private Float maxAcceleration;
|
||||||
|
|
||||||
|
@Column(name = "min_acceleration")
|
||||||
|
private Float minAcceleration;
|
||||||
|
|
||||||
|
@Column(name = "acceleration_variance")
|
||||||
|
private Double accelerationVariance;
|
||||||
|
|
||||||
|
@Column(name = "direction_changes")
|
||||||
|
private Integer directionChanges;
|
||||||
|
|
||||||
|
@Column(name = "y_direction_changes")
|
||||||
|
private Integer yDirectionChanges;
|
||||||
|
|
||||||
|
@Column(name = "pauses")
|
||||||
|
private Integer pauses;
|
||||||
|
|
||||||
|
@Column(name = "start_offset")
|
||||||
|
private Double startOffset;
|
||||||
|
|
||||||
|
@Column(name = "straightness")
|
||||||
|
private Double straightness;
|
||||||
|
|
||||||
|
@Column(name = "x_uniformity")
|
||||||
|
private Double xUniformity;
|
||||||
|
|
||||||
|
@Column(name = "y_uniformity")
|
||||||
|
private Double yUniformity;
|
||||||
|
|
||||||
|
@Column(name = "avg_point_interval")
|
||||||
|
private Float avgPointInterval;
|
||||||
|
|
||||||
|
@Column(name = "speed_phase_correlation")
|
||||||
|
private Double speedPhaseCorrelation;
|
||||||
|
|
||||||
|
@Column(name = "max_jump_distance")
|
||||||
|
private Double maxJumpDistance;
|
||||||
|
|
||||||
|
@Column(name = "overshoot_ratio")
|
||||||
|
private Double overshootRatio;
|
||||||
|
|
||||||
|
@Column(name = "track_json", columnDefinition = "TEXT")
|
||||||
|
private String trackJson;
|
||||||
|
|
||||||
|
@Column(length = 45)
|
||||||
|
private String ip;
|
||||||
|
|
||||||
|
@Column(name = "created_at")
|
||||||
|
private OffsetDateTime createdAt;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
protected void onCreate() { createdAt = OffsetDateTime.now(); }
|
||||||
|
|
||||||
|
public static TrackSample fromFeatures(cloud.tianai.captcha.ml.TrackFeatures f, Boolean isHuman, Double mlScore, Boolean basicPass, String captchaType, Integer siteId, String trackJson, String ip) {
|
||||||
|
TrackSample s = new TrackSample();
|
||||||
|
s.isHuman = isHuman;
|
||||||
|
s.mlScore = mlScore;
|
||||||
|
s.basicPass = basicPass;
|
||||||
|
s.captchaType = captchaType;
|
||||||
|
s.siteId = siteId;
|
||||||
|
s.trackJson = trackJson;
|
||||||
|
s.ip = ip;
|
||||||
|
s.totalPoints = f.totalPoints;
|
||||||
|
s.totalDuration = f.totalDuration;
|
||||||
|
s.displacementX = f.displacementX;
|
||||||
|
s.displacementY = f.displacementY;
|
||||||
|
s.displacementXRatio = f.displacementXRatio;
|
||||||
|
s.totalPathLength = f.totalPathLength;
|
||||||
|
s.pathEfficiency = f.pathEfficiency;
|
||||||
|
s.avgSpeed = f.avgSpeed;
|
||||||
|
s.maxSpeed = f.maxSpeed;
|
||||||
|
s.minSpeed = f.minSpeed;
|
||||||
|
s.speedVariance = f.speedVariance;
|
||||||
|
s.speedStdDev = f.speedStdDev;
|
||||||
|
s.speedSkewness = f.speedSkewness;
|
||||||
|
s.avgAcceleration = f.avgAcceleration;
|
||||||
|
s.maxAcceleration = f.maxAcceleration;
|
||||||
|
s.minAcceleration = f.minAcceleration;
|
||||||
|
s.accelerationVariance = f.accelerationVariance;
|
||||||
|
s.directionChanges = f.directionChanges;
|
||||||
|
s.yDirectionChanges = f.yDirectionChanges;
|
||||||
|
s.pauses = f.pauses;
|
||||||
|
s.startOffset = f.startOffset;
|
||||||
|
s.straightness = f.straightness;
|
||||||
|
s.xUniformity = f.xUniformity;
|
||||||
|
s.yUniformity = f.yUniformity;
|
||||||
|
s.avgPointInterval = f.avgPointInterval;
|
||||||
|
s.speedPhaseCorrelation = f.speedPhaseCorrelation;
|
||||||
|
s.maxJumpDistance = f.maxJumpDistance;
|
||||||
|
s.overshootRatio = f.overshootRatio;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getId() { return id; }
|
||||||
|
public void setId(Integer id) { this.id = id; }
|
||||||
|
public Integer getSiteId() { return siteId; }
|
||||||
|
public void setSiteId(Integer siteId) { this.siteId = siteId; }
|
||||||
|
public String getCaptchaType() { return captchaType; }
|
||||||
|
public void setCaptchaType(String captchaType) { this.captchaType = captchaType; }
|
||||||
|
public Boolean getIsHuman() { return isHuman; }
|
||||||
|
public void setIsHuman(Boolean isHuman) { this.isHuman = isHuman; }
|
||||||
|
public Double getMlScore() { return mlScore; }
|
||||||
|
public void setMlScore(Double mlScore) { this.mlScore = mlScore; }
|
||||||
|
public Boolean getBasicPass() { return basicPass; }
|
||||||
|
public void setBasicPass(Boolean basicPass) { this.basicPass = basicPass; }
|
||||||
|
public Integer getTotalPoints() { return totalPoints; }
|
||||||
|
public void setTotalPoints(Integer totalPoints) { this.totalPoints = totalPoints; }
|
||||||
|
public Long getTotalDuration() { return totalDuration; }
|
||||||
|
public void setTotalDuration(Long totalDuration) { this.totalDuration = totalDuration; }
|
||||||
|
public Float getDisplacementX() { return displacementX; }
|
||||||
|
public void setDisplacementX(Float displacementX) { this.displacementX = displacementX; }
|
||||||
|
public Float getDisplacementY() { return displacementY; }
|
||||||
|
public void setDisplacementY(Float displacementY) { this.displacementY = displacementY; }
|
||||||
|
public Float getDisplacementXRatio() { return displacementXRatio; }
|
||||||
|
public void setDisplacementXRatio(Float displacementXRatio) { this.displacementXRatio = displacementXRatio; }
|
||||||
|
public Double getTotalPathLength() { return totalPathLength; }
|
||||||
|
public void setTotalPathLength(Double totalPathLength) { this.totalPathLength = totalPathLength; }
|
||||||
|
public Double getPathEfficiency() { return pathEfficiency; }
|
||||||
|
public void setPathEfficiency(Double pathEfficiency) { this.pathEfficiency = pathEfficiency; }
|
||||||
|
public Float getAvgSpeed() { return avgSpeed; }
|
||||||
|
public void setAvgSpeed(Float avgSpeed) { this.avgSpeed = avgSpeed; }
|
||||||
|
public Float getMaxSpeed() { return maxSpeed; }
|
||||||
|
public void setMaxSpeed(Float maxSpeed) { this.maxSpeed = maxSpeed; }
|
||||||
|
public Float getMinSpeed() { return minSpeed; }
|
||||||
|
public void setMinSpeed(Float minSpeed) { this.minSpeed = minSpeed; }
|
||||||
|
public Double getSpeedVariance() { return speedVariance; }
|
||||||
|
public void setSpeedVariance(Double speedVariance) { this.speedVariance = speedVariance; }
|
||||||
|
public Double getSpeedStdDev() { return speedStdDev; }
|
||||||
|
public void setSpeedStdDev(Double speedStdDev) { this.speedStdDev = speedStdDev; }
|
||||||
|
public Double getSpeedSkewness() { return speedSkewness; }
|
||||||
|
public void setSpeedSkewness(Double speedSkewness) { this.speedSkewness = speedSkewness; }
|
||||||
|
public Float getAvgAcceleration() { return avgAcceleration; }
|
||||||
|
public void setAvgAcceleration(Float avgAcceleration) { this.avgAcceleration = avgAcceleration; }
|
||||||
|
public Float getMaxAcceleration() { return maxAcceleration; }
|
||||||
|
public void setMaxAcceleration(Float maxAcceleration) { this.maxAcceleration = maxAcceleration; }
|
||||||
|
public Float getMinAcceleration() { return minAcceleration; }
|
||||||
|
public void setMinAcceleration(Float minAcceleration) { this.minAcceleration = minAcceleration; }
|
||||||
|
public Double getAccelerationVariance() { return accelerationVariance; }
|
||||||
|
public void setAccelerationVariance(Double accelerationVariance) { this.accelerationVariance = accelerationVariance; }
|
||||||
|
public Integer getDirectionChanges() { return directionChanges; }
|
||||||
|
public void setDirectionChanges(Integer directionChanges) { this.directionChanges = directionChanges; }
|
||||||
|
public Integer getYDirectionChanges() { return yDirectionChanges; }
|
||||||
|
public void setYDirectionChanges(Integer yDirectionChanges) { this.yDirectionChanges = yDirectionChanges; }
|
||||||
|
public Integer getPauses() { return pauses; }
|
||||||
|
public void setPauses(Integer pauses) { this.pauses = pauses; }
|
||||||
|
public Double getStartOffset() { return startOffset; }
|
||||||
|
public void setStartOffset(Double startOffset) { this.startOffset = startOffset; }
|
||||||
|
public Double getStraightness() { return straightness; }
|
||||||
|
public void setStraightness(Double straightness) { this.straightness = straightness; }
|
||||||
|
public Double getXUniformity() { return xUniformity; }
|
||||||
|
public void setXUniformity(Double xUniformity) { this.xUniformity = xUniformity; }
|
||||||
|
public Double getYUniformity() { return yUniformity; }
|
||||||
|
public void setYUniformity(Double yUniformity) { this.yUniformity = yUniformity; }
|
||||||
|
public Float getAvgPointInterval() { return avgPointInterval; }
|
||||||
|
public void setAvgPointInterval(Float avgPointInterval) { this.avgPointInterval = avgPointInterval; }
|
||||||
|
public Double getSpeedPhaseCorrelation() { return speedPhaseCorrelation; }
|
||||||
|
public void setSpeedPhaseCorrelation(Double speedPhaseCorrelation) { this.speedPhaseCorrelation = speedPhaseCorrelation; }
|
||||||
|
public Double getMaxJumpDistance() { return maxJumpDistance; }
|
||||||
|
public void setMaxJumpDistance(Double maxJumpDistance) { this.maxJumpDistance = maxJumpDistance; }
|
||||||
|
public Double getOvershootRatio() { return overshootRatio; }
|
||||||
|
public void setOvershootRatio(Double overshootRatio) { this.overshootRatio = overshootRatio; }
|
||||||
|
public String getTrackJson() { return trackJson; }
|
||||||
|
public void setTrackJson(String trackJson) { this.trackJson = trackJson; }
|
||||||
|
public String getIp() { return ip; }
|
||||||
|
public void setIp(String ip) { this.ip = ip; }
|
||||||
|
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||||
|
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package cloud.tianai.captcha.platform.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "users")
|
||||||
|
public class User {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Integer id;
|
||||||
|
|
||||||
|
@Column(length = 64, unique = true, nullable = false)
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
@Column(name = "password", length = 256, nullable = false)
|
||||||
|
private String passwordHash;
|
||||||
|
|
||||||
|
@Column(length = 128)
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
@Column(length = 32)
|
||||||
|
private String role = "USER";
|
||||||
|
|
||||||
|
@Column(name = "is_enabled")
|
||||||
|
private Boolean isEnabled = true;
|
||||||
|
|
||||||
|
@Column(name = "created_at")
|
||||||
|
private OffsetDateTime createdAt;
|
||||||
|
|
||||||
|
@Column(name = "updated_at")
|
||||||
|
private OffsetDateTime updatedAt;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
protected void onCreate() {
|
||||||
|
createdAt = OffsetDateTime.now();
|
||||||
|
updatedAt = OffsetDateTime.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreUpdate
|
||||||
|
protected void onUpdate() {
|
||||||
|
updatedAt = OffsetDateTime.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getId() { return id; }
|
||||||
|
public void setId(Integer id) { this.id = id; }
|
||||||
|
public String getUsername() { return username; }
|
||||||
|
public void setUsername(String username) { this.username = username; }
|
||||||
|
public String getPasswordHash() { return passwordHash; }
|
||||||
|
public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; }
|
||||||
|
public String getEmail() { return email; }
|
||||||
|
public void setEmail(String email) { this.email = email; }
|
||||||
|
public String getRole() { return role; }
|
||||||
|
public void setRole(String role) { this.role = role; }
|
||||||
|
public Boolean getIsEnabled() { return isEnabled; }
|
||||||
|
public void setIsEnabled(Boolean isEnabled) { this.isEnabled = isEnabled; }
|
||||||
|
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||||
|
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
|
||||||
|
public OffsetDateTime getUpdatedAt() { return updatedAt; }
|
||||||
|
public void setUpdatedAt(OffsetDateTime updatedAt) { this.updatedAt = updatedAt; }
|
||||||
|
}
|
||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
package cloud.tianai.captcha.platform.mapper;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.platform.entity.CaptchaLog;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface CaptchaLogRepository extends JpaRepository<CaptchaLog, Integer> {
|
||||||
|
long countByIsPass(Boolean isPass);
|
||||||
|
|
||||||
|
long countBySiteIdAndCreatedAtBetween(Integer siteId, OffsetDateTime start, OffsetDateTime end);
|
||||||
|
|
||||||
|
long countBySiteIdAndIsPassAndCreatedAtBetween(Integer siteId, Boolean isPass, OffsetDateTime start, OffsetDateTime end);
|
||||||
|
|
||||||
|
long countBySiteIdAndCaptchaTypeAndCreatedAtBetween(Integer siteId, String captchaType, OffsetDateTime start, OffsetDateTime end);
|
||||||
|
|
||||||
|
long countByIpAndCreatedAtBetween(String ip, OffsetDateTime start, OffsetDateTime end);
|
||||||
|
|
||||||
|
@Query("SELECT l.captchaType, COUNT(l) FROM CaptchaLog l WHERE l.siteId = :siteId AND l.createdAt BETWEEN :start AND :end GROUP BY l.captchaType")
|
||||||
|
List<Object[]> countByTypeGrouped(@Param("siteId") Integer siteId, @Param("start") OffsetDateTime start, @Param("end") OffsetDateTime end);
|
||||||
|
|
||||||
|
@Query("SELECT l.ip, COUNT(l) FROM CaptchaLog l WHERE l.createdAt BETWEEN :start AND :end GROUP BY l.ip ORDER BY COUNT(l) DESC")
|
||||||
|
List<Object[]> topIpStats(@Param("start") OffsetDateTime start, @Param("end") OffsetDateTime end);
|
||||||
|
|
||||||
|
@Query("SELECT FUNCTION('DATE', l.createdAt), COUNT(l), SUM(CASE WHEN l.isPass = true THEN 1 ELSE 0 END) FROM CaptchaLog l WHERE l.siteId = :siteId AND l.createdAt BETWEEN :start AND :end GROUP BY FUNCTION('DATE', l.createdAt) ORDER BY FUNCTION('DATE', l.createdAt)")
|
||||||
|
List<Object[]> dailyStats(@Param("siteId") Integer siteId, @Param("start") OffsetDateTime start, @Param("end") OffsetDateTime end);
|
||||||
|
|
||||||
|
List<CaptchaLog> findTop100BySiteIdOrderByCreatedAtDesc(Integer siteId);
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
package cloud.tianai.captcha.platform.mapper;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.platform.entity.CaptchaSite;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface CaptchaSiteRepository extends JpaRepository<CaptchaSite, Integer> {
|
||||||
|
Optional<CaptchaSite> findBySiteKey(UUID siteKey);
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
package cloud.tianai.captcha.platform.mapper;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.platform.entity.Plan;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface PlanRepository extends JpaRepository<Plan, Integer> {
|
||||||
|
List<Plan> findByIsActiveTrue();
|
||||||
|
}
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
package cloud.tianai.captcha.platform.mapper;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.platform.entity.TrackSample;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface TrackSampleRepository extends JpaRepository<TrackSample, Integer> {
|
||||||
|
|
||||||
|
long countByIsHuman(Boolean isHuman);
|
||||||
|
|
||||||
|
@Query("SELECT COUNT(s) FROM TrackSample s WHERE s.createdAt > :since")
|
||||||
|
long countRecentSamples(@Param("since") OffsetDateTime since);
|
||||||
|
|
||||||
|
@Query("SELECT s FROM TrackSample s ORDER BY s.createdAt DESC LIMIT :limit")
|
||||||
|
List<TrackSample> findRecentSamples(@Param("limit") int limit);
|
||||||
|
|
||||||
|
@Query("SELECT s FROM TrackSample s WHERE s.isHuman = :isHuman ORDER BY s.createdAt DESC LIMIT :limit")
|
||||||
|
List<TrackSample> findByIsHuman(@Param("isHuman") Boolean isHuman, @Param("limit") int limit);
|
||||||
|
}
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
package cloud.tianai.captcha.platform.mapper;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.platform.entity.User;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public interface UserRepository extends JpaRepository<User, Integer> {
|
||||||
|
Optional<User> findByUsername(String username);
|
||||||
|
Boolean existsByUsername(String username);
|
||||||
|
}
|
||||||
+97
@@ -0,0 +1,97 @@
|
|||||||
|
package cloud.tianai.captcha.platform.service;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.platform.entity.CaptchaLog;
|
||||||
|
import cloud.tianai.captcha.platform.mapper.CaptchaLogRepository;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class AnomalyDetectionService {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(AnomalyDetectionService.class);
|
||||||
|
private static final double FAIL_RATE_THRESHOLD = 0.7;
|
||||||
|
private static final int IP_FREQ_THRESHOLD = 100;
|
||||||
|
|
||||||
|
private final CaptchaLogRepository logRepository;
|
||||||
|
private final Map<String, AnomalyAlert> activeAlerts = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
public AnomalyDetectionService(CaptchaLogRepository logRepository) {
|
||||||
|
this.logRepository = logRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(fixedRate = 60000)
|
||||||
|
public void detectAnomalies() {
|
||||||
|
try {
|
||||||
|
OffsetDateTime oneHourAgo = OffsetDateTime.now(ZoneOffset.UTC).minusHours(1);
|
||||||
|
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
|
||||||
|
|
||||||
|
List<Object[]> topIps = logRepository.topIpStats(oneHourAgo, now);
|
||||||
|
for (Object[] row : topIps) {
|
||||||
|
String ip = (String) row[0];
|
||||||
|
long count = ((Number) row[1]).longValue();
|
||||||
|
if (count > IP_FREQ_THRESHOLD) {
|
||||||
|
triggerAlert("IP_FREQ", ip, "High request frequency: " + count + " requests/hour");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Object[]> typeStats = logRepository.countByTypeGrouped(null, oneHourAgo, now);
|
||||||
|
for (Object[] row : typeStats) {
|
||||||
|
String type = (String) row[0];
|
||||||
|
long total = ((Number) row[1]).longValue();
|
||||||
|
if (total > 100) {
|
||||||
|
long fails = logRepository.countByIsPass(false);
|
||||||
|
double failRate = (double) fails / total;
|
||||||
|
if (failRate > FAIL_RATE_THRESHOLD) {
|
||||||
|
triggerAlert("HIGH_FAIL_RATE", type, "Fail rate: " + String.format("%.1f%%", failRate * 100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("[ANOMALY] Detection failed: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void triggerAlert(String type, String target, String message) {
|
||||||
|
String alertKey = type + ":" + target;
|
||||||
|
if (!activeAlerts.containsKey(alertKey)) {
|
||||||
|
AnomalyAlert alert = new AnomalyAlert(type, target, message);
|
||||||
|
activeAlerts.put(alertKey, alert);
|
||||||
|
log.warn("[ANOMALY] Alert triggered: {} - {} - {}", type, target, message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<AnomalyAlert> getActiveAlerts() {
|
||||||
|
return new ArrayList<>(activeAlerts.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void clearAlert(String alertKey) {
|
||||||
|
activeAlerts.remove(alertKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class AnomalyAlert {
|
||||||
|
private final String type;
|
||||||
|
private final String target;
|
||||||
|
private final String message;
|
||||||
|
private final long timestamp;
|
||||||
|
|
||||||
|
public AnomalyAlert(String type, String target, String message) {
|
||||||
|
this.type = type;
|
||||||
|
this.target = target;
|
||||||
|
this.message = message;
|
||||||
|
this.timestamp = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getType() { return type; }
|
||||||
|
public String getTarget() { return target; }
|
||||||
|
public String getMessage() { return message; }
|
||||||
|
public long getTimestamp() { return timestamp; }
|
||||||
|
}
|
||||||
|
}
|
||||||
+242
@@ -0,0 +1,242 @@
|
|||||||
|
package cloud.tianai.captcha.platform.service;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.application.ImageCaptchaApplication;
|
||||||
|
import cloud.tianai.captcha.application.vo.ImageCaptchaVO;
|
||||||
|
import cloud.tianai.captcha.common.AnyMap;
|
||||||
|
import cloud.tianai.captcha.common.response.ApiResponse;
|
||||||
|
import cloud.tianai.captcha.platform.entity.CaptchaLog;
|
||||||
|
import cloud.tianai.captcha.platform.entity.CaptchaSite;
|
||||||
|
import cloud.tianai.captcha.platform.mapper.CaptchaLogRepository;
|
||||||
|
import cloud.tianai.captcha.platform.mapper.CaptchaSiteRepository;
|
||||||
|
import cloud.tianai.captcha.risk.IpBlacklist;
|
||||||
|
import cloud.tianai.captcha.risk.RiskEngine;
|
||||||
|
import cloud.tianai.captcha.site.TokenService;
|
||||||
|
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
|
||||||
|
import cloud.tianai.captcha.validator.common.model.dto.MatchParam;
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import com.google.gson.reflect.TypeToken;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.lang.reflect.Type;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class CaptchaPlatformService {
|
||||||
|
|
||||||
|
private final ImageCaptchaApplication captchaApplication;
|
||||||
|
private final CaptchaSiteRepository siteRepository;
|
||||||
|
private final CaptchaLogRepository logRepository;
|
||||||
|
private final TokenService tokenService;
|
||||||
|
private final RiskEngine riskEngine;
|
||||||
|
private final IpBlacklist ipBlacklist;
|
||||||
|
private final TrackLearningService trackLearningService;
|
||||||
|
private final Gson gson = new Gson();
|
||||||
|
|
||||||
|
public CaptchaPlatformService(ImageCaptchaApplication captchaApplication,
|
||||||
|
CaptchaSiteRepository siteRepository,
|
||||||
|
CaptchaLogRepository logRepository,
|
||||||
|
TokenService tokenService,
|
||||||
|
RiskEngine riskEngine,
|
||||||
|
IpBlacklist ipBlacklist,
|
||||||
|
TrackLearningService trackLearningService) {
|
||||||
|
this.captchaApplication = captchaApplication;
|
||||||
|
this.siteRepository = siteRepository;
|
||||||
|
this.logRepository = logRepository;
|
||||||
|
this.tokenService = tokenService;
|
||||||
|
this.riskEngine = riskEngine;
|
||||||
|
this.ipBlacklist = ipBlacklist;
|
||||||
|
this.trackLearningService = trackLearningService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiResponse<ImageCaptchaVO> generateCaptcha(String siteKeyStr, String type, String scene, String ip) {
|
||||||
|
CaptchaSite site = validateSite(siteKeyStr);
|
||||||
|
if (site == null) {
|
||||||
|
return ApiResponse.of(10001, "site_auth_fail", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ipBlacklist.isBanned(ip)) {
|
||||||
|
return ApiResponse.of(10005, "ip_banned", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!riskEngine.getRateLimiter().allow("ip:" + ip)) {
|
||||||
|
return ApiResponse.of(10007, "rate_limit", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == null) {
|
||||||
|
Set<String> allowed = site.getCaptchaTypes();
|
||||||
|
if (allowed != null && !allowed.isEmpty()) {
|
||||||
|
List<String> list = new ArrayList<>(allowed);
|
||||||
|
type = list.get(ThreadLocalRandom.current().nextInt(list.size()));
|
||||||
|
} else {
|
||||||
|
type = "SLIDER";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (site.getCaptchaTypes() != null && !site.getCaptchaTypes().isEmpty()
|
||||||
|
&& !site.getCaptchaTypes().contains(type)) {
|
||||||
|
return ApiResponse.of(10006, "type_not_supported", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
ApiResponse<ImageCaptchaVO> response = captchaApplication.generateCaptcha(type);
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
String cid = response.getData() != null ? response.getData().getId() : null;
|
||||||
|
System.out.println("[CAPTCHA-DEBUG] generateCaptcha type=" + type + " captchaId=" + cid);
|
||||||
|
CaptchaLog log = new CaptchaLog();
|
||||||
|
log.setSiteId(site.getId());
|
||||||
|
log.setSiteKey(site.getSiteKey());
|
||||||
|
log.setCaptchaId(response.getData() != null ? response.getData().getId() : null);
|
||||||
|
log.setCaptchaType(type);
|
||||||
|
log.setScene(scene);
|
||||||
|
log.setIp(ip);
|
||||||
|
log.setIsPass(null);
|
||||||
|
logRepository.save(log);
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiResponse<?> verifyCaptcha(String siteKeyStr, String captchaId, Object trackData, String ip) {
|
||||||
|
CaptchaSite site = validateSite(siteKeyStr);
|
||||||
|
if (site == null) {
|
||||||
|
return ApiResponse.of(10001, "site_auth_fail", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("[CAPTCHA-DEBUG] verifyCaptcha captchaId=" + captchaId + " trackData class=" + (trackData != null ? trackData.getClass().getName() : "null"));
|
||||||
|
|
||||||
|
ImageCaptchaTrack track;
|
||||||
|
if (trackData instanceof Map) {
|
||||||
|
Type mapType = new TypeToken<Map<String, Object>>() {}.getType();
|
||||||
|
String json = gson.toJson(trackData);
|
||||||
|
System.out.println("[CAPTCHA-DEBUG] track json=" + json);
|
||||||
|
track = gson.fromJson(json, ImageCaptchaTrack.class);
|
||||||
|
} else if (trackData instanceof ImageCaptchaTrack) {
|
||||||
|
track = (ImageCaptchaTrack) trackData;
|
||||||
|
} else {
|
||||||
|
return ApiResponse.of(10004, "invalid_param", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("[CAPTCHA-DEBUG] track.bgImageWidth=" + track.getBgImageWidth()
|
||||||
|
+ " trackList.size=" + (track.getTrackList() != null ? track.getTrackList().size() : 0));
|
||||||
|
|
||||||
|
MatchParam matchParam = new MatchParam(track);
|
||||||
|
AnyMap extData = new AnyMap();
|
||||||
|
extData.put("ip", ip);
|
||||||
|
matchParam.putAll(extData);
|
||||||
|
|
||||||
|
long startTime = System.currentTimeMillis();
|
||||||
|
ApiResponse<?> result = captchaApplication.matching(captchaId, matchParam);
|
||||||
|
long duration = System.currentTimeMillis() - startTime;
|
||||||
|
|
||||||
|
System.out.println("[CAPTCHA-DEBUG] matching result code=" + result.getCode() + " msg=" + result.getMsg() + " success=" + result.isSuccess());
|
||||||
|
|
||||||
|
CaptchaLog log = new CaptchaLog();
|
||||||
|
log.setSiteId(site.getId());
|
||||||
|
log.setSiteKey(site.getSiteKey());
|
||||||
|
log.setCaptchaId(captchaId);
|
||||||
|
log.setCaptchaType(trackData != null ? "VERIFY" : "UNKNOWN");
|
||||||
|
log.setIp(ip);
|
||||||
|
log.setIsPass(result.isSuccess());
|
||||||
|
log.setCostTime((int) duration);
|
||||||
|
logRepository.save(log);
|
||||||
|
|
||||||
|
trackLearningService.collectSample(track, result.isSuccess(), "SLIDER", site.getId(), ip);
|
||||||
|
|
||||||
|
if (result.isSuccess()) {
|
||||||
|
String token = tokenService.generateToken(siteKeyStr, captchaId);
|
||||||
|
Map<String, Object> data = new HashMap<>();
|
||||||
|
data.put("verifyToken", token);
|
||||||
|
return ApiResponse.ofSuccess(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!result.isSuccess()) {
|
||||||
|
riskEngine.recordFail(ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiResponse<?> secondaryVerify(String siteKeyStr, String secretKeyStr, String verifyToken) {
|
||||||
|
CaptchaSite site = siteRepository.findBySiteKey(java.util.UUID.fromString(siteKeyStr)).orElse(null);
|
||||||
|
if (site == null || !site.getSecretKey().toString().equals(secretKeyStr)) {
|
||||||
|
return ApiResponse.of(10001, "site_auth_fail", null);
|
||||||
|
}
|
||||||
|
AnyMap tokenData = tokenService.consumeToken(verifyToken);
|
||||||
|
if (tokenData == null) {
|
||||||
|
return ApiResponse.of(403, "token_invalid", null);
|
||||||
|
}
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("verifyResult", true);
|
||||||
|
return ApiResponse.ofSuccess(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiResponse<?> getPublicKey(String siteKeyStr) {
|
||||||
|
CaptchaSite site = validateSite(siteKeyStr);
|
||||||
|
if (site == null) {
|
||||||
|
return ApiResponse.of(10001, "site_auth_fail", null);
|
||||||
|
}
|
||||||
|
Map<String, Object> data = new HashMap<>();
|
||||||
|
data.put("publicKey", site.getRsaPublicKey());
|
||||||
|
return ApiResponse.ofSuccess(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CaptchaSite createSite(String name, String domain, Set<String> captchaTypes) {
|
||||||
|
CaptchaSite site = new CaptchaSite();
|
||||||
|
site.setSiteKey(java.util.UUID.randomUUID());
|
||||||
|
site.setSecretKey(java.util.UUID.randomUUID());
|
||||||
|
site.setName(name);
|
||||||
|
site.setDomain(domain);
|
||||||
|
site.setCaptchaTypes(captchaTypes);
|
||||||
|
try {
|
||||||
|
java.security.KeyPair keyPair = cloud.tianai.captcha.crypto.RsaEncryptor.generateKeyPair();
|
||||||
|
site.setRsaPublicKey(cloud.tianai.captcha.crypto.RsaEncryptor.publicKeyToBase64(keyPair.getPublic()));
|
||||||
|
site.setRsaPrivateKey(cloud.tianai.captcha.crypto.RsaEncryptor.privateKeyToBase64(keyPair.getPrivate()));
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to generate RSA key pair", e);
|
||||||
|
}
|
||||||
|
byte[] aesKey = cloud.tianai.captcha.crypto.AesEncryptor.generateKey();
|
||||||
|
site.setAesKey(Base64.getEncoder().encodeToString(aesKey));
|
||||||
|
byte[] signingKey = new byte[32];
|
||||||
|
new SecureRandom().nextBytes(signingKey);
|
||||||
|
site.setSigningKey(Base64.getEncoder().encodeToString(signingKey));
|
||||||
|
return siteRepository.save(site);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Page<CaptchaSite> listSites(Pageable pageable) {
|
||||||
|
return siteRepository.findAll(pageable);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CaptchaSite getSite(Integer siteId) { return siteRepository.findById(siteId).orElse(null); }
|
||||||
|
public CaptchaSite updateSite(CaptchaSite site) { return siteRepository.save(site); }
|
||||||
|
public void deleteSite(Integer siteId) { siteRepository.deleteById(siteId); }
|
||||||
|
|
||||||
|
public Map<String, Object> getStats(Integer siteId, int days) {
|
||||||
|
long total = logRepository.count();
|
||||||
|
long success = logRepository.countByIsPass(true);
|
||||||
|
long fail = logRepository.countByIsPass(false);
|
||||||
|
Map<String, Object> stats = new HashMap<>();
|
||||||
|
stats.put("total", total);
|
||||||
|
stats.put("success", success);
|
||||||
|
stats.put("fail", fail);
|
||||||
|
stats.put("passRate", total > 0 ? String.format("%.2f%%", success * 100.0 / total) : "0%");
|
||||||
|
return stats;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void banIp(String ip, String reason, long durationMs) { ipBlacklist.ban(ip, durationMs); }
|
||||||
|
public void unbanIp(String ip) { ipBlacklist.unban(ip); }
|
||||||
|
|
||||||
|
private CaptchaSite validateSite(String siteKeyStr) {
|
||||||
|
if (siteKeyStr == null) return null;
|
||||||
|
try {
|
||||||
|
java.util.UUID uuid = java.util.UUID.fromString(siteKeyStr);
|
||||||
|
Optional<CaptchaSite> opt = siteRepository.findBySiteKey(uuid);
|
||||||
|
return opt.filter(site -> site.getIsEnabled()).orElse(null);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+99
@@ -0,0 +1,99 @@
|
|||||||
|
package cloud.tianai.captcha.platform.service;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.platform.entity.CaptchaLog;
|
||||||
|
import cloud.tianai.captcha.platform.mapper.CaptchaLogRepository;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class HistoryStatsService {
|
||||||
|
|
||||||
|
private final CaptchaLogRepository logRepository;
|
||||||
|
|
||||||
|
public HistoryStatsService(CaptchaLogRepository logRepository) {
|
||||||
|
this.logRepository = logRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> getDailyStats(Integer siteId, int days) {
|
||||||
|
OffsetDateTime start = OffsetDateTime.now(ZoneOffset.UTC).minusDays(days);
|
||||||
|
OffsetDateTime end = OffsetDateTime.now(ZoneOffset.UTC);
|
||||||
|
|
||||||
|
List<Object[]> rows = logRepository.dailyStats(siteId, start, end);
|
||||||
|
|
||||||
|
List<String> dates = new ArrayList<>();
|
||||||
|
List<Long> totals = new ArrayList<>();
|
||||||
|
List<Long> successes = new ArrayList<>();
|
||||||
|
|
||||||
|
for (Object[] row : rows) {
|
||||||
|
dates.add(String.valueOf(row[0]));
|
||||||
|
totals.add(((Number) row[1]).longValue());
|
||||||
|
successes.add(((Number) row[2]).longValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
|
result.put("dates", dates);
|
||||||
|
result.put("totals", totals);
|
||||||
|
result.put("successes", successes);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> getTypeDistribution(Integer siteId, int days) {
|
||||||
|
OffsetDateTime start = OffsetDateTime.now(ZoneOffset.UTC).minusDays(days);
|
||||||
|
OffsetDateTime end = OffsetDateTime.now(ZoneOffset.UTC);
|
||||||
|
|
||||||
|
List<Object[]> rows = logRepository.countByTypeGrouped(siteId, start, end);
|
||||||
|
|
||||||
|
Map<String, Long> distribution = new LinkedHashMap<>();
|
||||||
|
long total = 0;
|
||||||
|
for (Object[] row : rows) {
|
||||||
|
String type = (String) row[0];
|
||||||
|
long count = ((Number) row[1]).longValue();
|
||||||
|
distribution.put(type, count);
|
||||||
|
total += count;
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
|
result.put("distribution", distribution);
|
||||||
|
result.put("total", total);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Map<String, Object>> getTopIps(int days, int limit) {
|
||||||
|
OffsetDateTime start = OffsetDateTime.now(ZoneOffset.UTC).minusDays(days);
|
||||||
|
OffsetDateTime end = OffsetDateTime.now(ZoneOffset.UTC);
|
||||||
|
|
||||||
|
List<Object[]> rows = logRepository.topIpStats(start, end);
|
||||||
|
|
||||||
|
return rows.stream()
|
||||||
|
.limit(limit)
|
||||||
|
.map(row -> {
|
||||||
|
Map<String, Object> item = new LinkedHashMap<>();
|
||||||
|
item.put("ip", row[0]);
|
||||||
|
item.put("count", ((Number) row[1]).longValue());
|
||||||
|
return item;
|
||||||
|
})
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> getHourlyDistribution(Integer siteId, int days) {
|
||||||
|
OffsetDateTime start = OffsetDateTime.now(ZoneOffset.UTC).minusDays(days);
|
||||||
|
OffsetDateTime end = OffsetDateTime.now(ZoneOffset.UTC);
|
||||||
|
|
||||||
|
List<CaptchaLog> logs = logRepository.findTop100BySiteIdOrderByCreatedAtDesc(siteId);
|
||||||
|
|
||||||
|
Map<Integer, Long> hourly = logs.stream()
|
||||||
|
.filter(l -> l.getCreatedAt() != null && l.getCreatedAt().isAfter(start))
|
||||||
|
.collect(Collectors.groupingBy(
|
||||||
|
l -> l.getCreatedAt().getHour(),
|
||||||
|
Collectors.counting()
|
||||||
|
));
|
||||||
|
|
||||||
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
|
result.put("hours", hourly);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
+72
@@ -0,0 +1,72 @@
|
|||||||
|
package cloud.tianai.captcha.platform.service;
|
||||||
|
|
||||||
|
import io.jsonwebtoken.Claims;
|
||||||
|
import io.jsonwebtoken.Jwts;
|
||||||
|
import io.jsonwebtoken.SignatureAlgorithm;
|
||||||
|
import io.jsonwebtoken.security.Keys;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import javax.crypto.SecretKey;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class JwtService {
|
||||||
|
|
||||||
|
@Value("${jwt.secret:tianai-captcha-secret-key-must-be-at-least-256-bits-long!!}")
|
||||||
|
private String secret;
|
||||||
|
|
||||||
|
@Value("${jwt.expiration:86400000}")
|
||||||
|
private long expiration;
|
||||||
|
|
||||||
|
private SecretKey getSigningKey() {
|
||||||
|
return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String generateToken(Integer userId, String username, String role) {
|
||||||
|
Map<String, Object> claims = new HashMap<>();
|
||||||
|
claims.put("userId", userId);
|
||||||
|
claims.put("username", username);
|
||||||
|
claims.put("role", role);
|
||||||
|
|
||||||
|
return Jwts.builder()
|
||||||
|
.setClaims(claims)
|
||||||
|
.setSubject(username)
|
||||||
|
.setIssuedAt(new Date())
|
||||||
|
.setExpiration(new Date(System.currentTimeMillis() + expiration))
|
||||||
|
.signWith(getSigningKey(), SignatureAlgorithm.HS256)
|
||||||
|
.compact();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Claims parseToken(String token) {
|
||||||
|
return Jwts.parser()
|
||||||
|
.verifyWith(getSigningKey())
|
||||||
|
.build()
|
||||||
|
.parseSignedClaims(token)
|
||||||
|
.getBody();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean validateToken(String token) {
|
||||||
|
try {
|
||||||
|
Claims claims = parseToken(token);
|
||||||
|
return !claims.getExpiration().before(new Date());
|
||||||
|
} catch (Exception e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUsernameFromToken(String token) {
|
||||||
|
return parseToken(token).getSubject();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getUserIdFromToken(String token) {
|
||||||
|
return (Integer) parseToken(token).get("userId");
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getRoleFromToken(String token) {
|
||||||
|
return (String) parseToken(token).get("role");
|
||||||
|
}
|
||||||
|
}
|
||||||
+106
@@ -0,0 +1,106 @@
|
|||||||
|
package cloud.tianai.captcha.platform.service;
|
||||||
|
|
||||||
|
import io.minio.*;
|
||||||
|
import io.minio.http.Method;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import jakarta.annotation.PostConstruct;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class MinioStorageService {
|
||||||
|
|
||||||
|
@Value("${minio.endpoint:http://localhost:9000}")
|
||||||
|
private String endpoint;
|
||||||
|
|
||||||
|
@Value("${minio.access-key:minioadmin}")
|
||||||
|
private String accessKey;
|
||||||
|
|
||||||
|
@Value("${minio.secret-key:minioadmin}")
|
||||||
|
private String secretKey;
|
||||||
|
|
||||||
|
@Value("${minio.bucket:captcha-resources}")
|
||||||
|
private String bucket;
|
||||||
|
|
||||||
|
private MinioClient minioClient;
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
public void init() {
|
||||||
|
try {
|
||||||
|
minioClient = MinioClient.builder()
|
||||||
|
.endpoint(endpoint)
|
||||||
|
.credentials(accessKey, secretKey)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
// 确保bucket存在
|
||||||
|
boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
|
||||||
|
if (!exists) {
|
||||||
|
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.err.println("Failed to initialize MinIO client: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String uploadFile(MultipartFile file, String prefix) {
|
||||||
|
try {
|
||||||
|
String objectName = prefix + "/" + UUID.randomUUID().toString() + getExtension(file.getOriginalFilename());
|
||||||
|
|
||||||
|
minioClient.putObject(PutObjectArgs.builder()
|
||||||
|
.bucket(bucket)
|
||||||
|
.object(objectName)
|
||||||
|
.stream(file.getInputStream(), file.getSize(), -1)
|
||||||
|
.contentType(file.getContentType())
|
||||||
|
.build());
|
||||||
|
|
||||||
|
return endpoint + "/" + bucket + "/" + objectName;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to upload file to MinIO", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public InputStream downloadFile(String objectName) {
|
||||||
|
try {
|
||||||
|
return minioClient.getObject(GetObjectArgs.builder()
|
||||||
|
.bucket(bucket)
|
||||||
|
.object(objectName)
|
||||||
|
.build());
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to download file from MinIO", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deleteFile(String objectName) {
|
||||||
|
try {
|
||||||
|
minioClient.removeObject(RemoveObjectArgs.builder()
|
||||||
|
.bucket(bucket)
|
||||||
|
.object(objectName)
|
||||||
|
.build());
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to delete file from MinIO", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPresignedUrl(String objectName, int expirySeconds) {
|
||||||
|
try {
|
||||||
|
return minioClient.getPresignedObjectUrl(
|
||||||
|
GetPresignedObjectUrlArgs.builder()
|
||||||
|
.method(Method.GET)
|
||||||
|
.bucket(bucket)
|
||||||
|
.object(objectName)
|
||||||
|
.expiry(expirySeconds)
|
||||||
|
.build());
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Failed to generate presigned URL", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getExtension(String filename) {
|
||||||
|
if (filename == null) return ".bin";
|
||||||
|
int dotIndex = filename.lastIndexOf('.');
|
||||||
|
return dotIndex >= 0 ? filename.substring(dotIndex) : ".bin";
|
||||||
|
}
|
||||||
|
}
|
||||||
+165
@@ -0,0 +1,165 @@
|
|||||||
|
package cloud.tianai.captcha.platform.service;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class RealtimeStatsService {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(RealtimeStatsService.class);
|
||||||
|
private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||||
|
|
||||||
|
private final StringRedisTemplate redisTemplate;
|
||||||
|
private final AtomicLong totalRequests = new AtomicLong(0);
|
||||||
|
private final AtomicLong totalGenerate = new AtomicLong(0);
|
||||||
|
private final AtomicLong totalVerify = new AtomicLong(0);
|
||||||
|
private final AtomicLong totalSuccess = new AtomicLong(0);
|
||||||
|
private final AtomicLong totalFail = new AtomicLong(0);
|
||||||
|
private final Map<String, AtomicLong> ipRequestCounts = new ConcurrentHashMap<>();
|
||||||
|
private final Map<String, AtomicLong> siteRequestCounts = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
public RealtimeStatsService(StringRedisTemplate redisTemplate) {
|
||||||
|
this.redisTemplate = redisTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void incrementTotalRequests() {
|
||||||
|
totalRequests.incrementAndGet();
|
||||||
|
incrementRedis("stats:total:" + todayKey());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void recordGenerate(String ip, String siteKey) {
|
||||||
|
totalGenerate.incrementAndGet();
|
||||||
|
incrementRedis("stats:generate:" + todayKey());
|
||||||
|
incrementIpCount(ip);
|
||||||
|
incrementSiteCount(siteKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void recordVerifyAttempt(boolean success, String ip, String siteKey) {
|
||||||
|
if (success) {
|
||||||
|
totalSuccess.incrementAndGet();
|
||||||
|
incrementRedis("stats:success:" + todayKey());
|
||||||
|
} else {
|
||||||
|
totalFail.incrementAndGet();
|
||||||
|
incrementRedis("stats:fail:" + todayKey());
|
||||||
|
}
|
||||||
|
totalVerify.incrementAndGet();
|
||||||
|
incrementRedis("stats:verify:" + todayKey());
|
||||||
|
incrementIpCount(ip);
|
||||||
|
incrementSiteCount(siteKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> getRealtimeStats() {
|
||||||
|
Map<String, Object> stats = new LinkedHashMap<>();
|
||||||
|
String key = todayKey();
|
||||||
|
stats.put("date", LocalDate.now().toString());
|
||||||
|
stats.put("totalRequests", getTotalRedis("stats:total:" + key));
|
||||||
|
stats.put("generateCount", getTotalRedis("stats:generate:" + key));
|
||||||
|
stats.put("verifyCount", getTotalRedis("stats:verify:" + key));
|
||||||
|
stats.put("successCount", getTotalRedis("stats:success:" + key));
|
||||||
|
stats.put("failCount", getTotalRedis("stats:fail:" + key));
|
||||||
|
long total = getTotalRedis("stats:verify:" + key);
|
||||||
|
long success = getTotalRedis("stats:success:" + key);
|
||||||
|
stats.put("passRate", total > 0 ? String.format("%.2f%%", success * 100.0 / total) : "0%");
|
||||||
|
return stats;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> getDashboardStats(Integer siteId, int days) {
|
||||||
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
|
result.put("realtime", getRealtimeStats());
|
||||||
|
|
||||||
|
Map<String, Long> dailyTotals = new LinkedHashMap<>();
|
||||||
|
Map<String, Long> dailySuccess = new LinkedHashMap<>();
|
||||||
|
for (int i = days - 1; i >= 0; i--) {
|
||||||
|
String dayKey = LocalDate.now().minusDays(i).format(DATE_FMT);
|
||||||
|
dailyTotals.put(dayKey, getTotalRedis("stats:verify:" + dayKey));
|
||||||
|
dailySuccess.put(dayKey, getTotalRedis("stats:success:" + dayKey));
|
||||||
|
}
|
||||||
|
result.put("dailyTotals", dailyTotals);
|
||||||
|
result.put("dailySuccess", dailySuccess);
|
||||||
|
|
||||||
|
List<Map<String, Object>> topIps = new ArrayList<>();
|
||||||
|
ipRequestCounts.entrySet().stream()
|
||||||
|
.sorted((a, b) -> Long.compare(b.getValue().get(), a.getValue().get()))
|
||||||
|
.limit(10)
|
||||||
|
.forEach(e -> {
|
||||||
|
Map<String, Object> ipStat = new LinkedHashMap<>();
|
||||||
|
ipStat.put("ip", e.getKey());
|
||||||
|
ipStat.put("count", e.getValue().get());
|
||||||
|
topIps.add(ipStat);
|
||||||
|
});
|
||||||
|
result.put("topIps", topIps);
|
||||||
|
|
||||||
|
List<Map<String, Object>> topSites = new ArrayList<>();
|
||||||
|
siteRequestCounts.entrySet().stream()
|
||||||
|
.sorted((a, b) -> Long.compare(b.getValue().get(), a.getValue().get()))
|
||||||
|
.limit(10)
|
||||||
|
.forEach(e -> {
|
||||||
|
Map<String, Object> siteStat = new LinkedHashMap<>();
|
||||||
|
siteStat.put("siteKey", e.getKey());
|
||||||
|
siteStat.put("count", e.getValue().get());
|
||||||
|
topSites.add(siteStat);
|
||||||
|
});
|
||||||
|
result.put("topSites", topSites);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void incrementRedis(String key) {
|
||||||
|
try {
|
||||||
|
redisTemplate.opsForValue().increment(key);
|
||||||
|
redisTemplate.expire(key, java.time.Duration.ofDays(35));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("Redis increment failed for {}: {}", key, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private long getTotalRedis(String key) {
|
||||||
|
try {
|
||||||
|
String val = redisTemplate.opsForValue().get(key);
|
||||||
|
return val != null ? Long.parseLong(val) : 0;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("Redis get failed for {}: {}", key, e.getMessage());
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void incrementIpCount(String ip) {
|
||||||
|
if (ip != null) {
|
||||||
|
ipRequestCounts.computeIfAbsent(ip, k -> new AtomicLong(0)).incrementAndGet();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void incrementSiteCount(String siteKey) {
|
||||||
|
if (siteKey != null) {
|
||||||
|
siteRequestCounts.computeIfAbsent(siteKey, k -> new AtomicLong(0)).incrementAndGet();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String todayKey() {
|
||||||
|
return LocalDate.now().format(DATE_FMT);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(fixedRate = 300000)
|
||||||
|
public void syncToRedis() {
|
||||||
|
try {
|
||||||
|
String key = todayKey();
|
||||||
|
redisTemplate.opsForValue().set("stats:total:" + key, String.valueOf(totalRequests.get()));
|
||||||
|
redisTemplate.opsForValue().set("stats:generate:" + key, String.valueOf(totalGenerate.get()));
|
||||||
|
redisTemplate.opsForValue().set("stats:verify:" + key, String.valueOf(totalVerify.get()));
|
||||||
|
redisTemplate.opsForValue().set("stats:success:" + key, String.valueOf(totalSuccess.get()));
|
||||||
|
redisTemplate.opsForValue().set("stats:fail:" + key, String.valueOf(totalFail.get()));
|
||||||
|
log.debug("[STATS] Synced to Redis: total={}", totalRequests.get());
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("[STATS] Failed to sync to Redis: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+329
@@ -0,0 +1,329 @@
|
|||||||
|
package cloud.tianai.captcha.platform.service;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.ml.TrackFeatureExtractor;
|
||||||
|
import cloud.tianai.captcha.ml.TrackFeatures;
|
||||||
|
import cloud.tianai.captcha.ml.TrackRuleEngine;
|
||||||
|
import cloud.tianai.captcha.ml.TrackRuleEngine.Rule;
|
||||||
|
import cloud.tianai.captcha.ml.TrackRuleEngine.RuleResult;
|
||||||
|
import cloud.tianai.captcha.ml.TrackRuleEngine.TrackVerdict;
|
||||||
|
import cloud.tianai.captcha.platform.entity.TrackSample;
|
||||||
|
import cloud.tianai.captcha.platform.mapper.TrackSampleRepository;
|
||||||
|
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
|
||||||
|
import cloud.tianai.captcha.validator.impl.EnhancedTrackValidator;
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.boot.CommandLineRunner;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.io.*;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class TrackLearningService implements CommandLineRunner {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(TrackLearningService.class);
|
||||||
|
private static final String MODEL_PATH = "ml-model/track-rules.json";
|
||||||
|
private static final int MIN_SAMPLES_FOR_TRAINING = 20;
|
||||||
|
|
||||||
|
private final TrackSampleRepository sampleRepository;
|
||||||
|
private final TrackFeatureExtractor featureExtractor = new TrackFeatureExtractor();
|
||||||
|
private TrackRuleEngine ruleEngine;
|
||||||
|
private final EnhancedTrackValidator validator;
|
||||||
|
private final Gson gson = new Gson();
|
||||||
|
|
||||||
|
private final AtomicBoolean trainingInProgress = new AtomicBoolean(false);
|
||||||
|
private final AtomicInteger totalSamples = new AtomicInteger(0);
|
||||||
|
private final AtomicInteger humanSamples = new AtomicInteger(0);
|
||||||
|
private final AtomicInteger botSamples = new AtomicInteger(0);
|
||||||
|
private final AtomicLong lastTrainingTime = new AtomicLong(0);
|
||||||
|
private volatile String lastTrainingSummary = "未训练";
|
||||||
|
|
||||||
|
public TrackLearningService(TrackSampleRepository sampleRepository, EnhancedTrackValidator validator) {
|
||||||
|
this.sampleRepository = sampleRepository;
|
||||||
|
this.validator = validator;
|
||||||
|
this.ruleEngine = validator.getRuleEngine();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void collectSample(ImageCaptchaTrack track, boolean basicPass, String captchaType, Integer siteId, String ip) {
|
||||||
|
try {
|
||||||
|
TrackFeatures features = featureExtractor.extract(track);
|
||||||
|
TrackVerdict verdict = ruleEngine.evaluate(features);
|
||||||
|
boolean isHuman = basicPass && verdict.isHuman;
|
||||||
|
|
||||||
|
String trackJson = gson.toJson(track);
|
||||||
|
TrackSample sample = TrackSample.fromFeatures(features, isHuman, verdict.score, basicPass, captchaType, siteId, trackJson, ip);
|
||||||
|
sampleRepository.save(sample);
|
||||||
|
|
||||||
|
totalSamples.incrementAndGet();
|
||||||
|
if (isHuman) humanSamples.incrementAndGet();
|
||||||
|
else botSamples.incrementAndGet();
|
||||||
|
|
||||||
|
log.debug("[ML] 收集轨迹样本 isHuman={} mlScore={:.3f} basicPass={}", isHuman, verdict.score, basicPass);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("[ML] 收集轨迹样本失败: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(fixedDelay = 300000, initialDelay = 60000)
|
||||||
|
public void scheduledTraining() {
|
||||||
|
trainIfNeeded();
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized Map<String, Object> trainIfNeeded() {
|
||||||
|
long total = sampleRepository.count();
|
||||||
|
if (total < MIN_SAMPLES_FOR_TRAINING) {
|
||||||
|
lastTrainingSummary = "样本不足 (" + total + "/" + MIN_SAMPLES_FOR_TRAINING + "),跳过训练";
|
||||||
|
return Map.of("status", "skipped", "reason", lastTrainingSummary);
|
||||||
|
}
|
||||||
|
if (!trainingInProgress.compareAndSet(false, true)) {
|
||||||
|
return Map.of("status", "busy", "reason", "训练正在进行中");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Map<String, Object> result = doTrain();
|
||||||
|
lastTrainingTime.set(System.currentTimeMillis());
|
||||||
|
return result;
|
||||||
|
} finally {
|
||||||
|
trainingInProgress.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> doTrain() {
|
||||||
|
List<TrackSample> allSamples = sampleRepository.findAll();
|
||||||
|
List<TrackSample> humanList = new ArrayList<>();
|
||||||
|
List<TrackSample> botList = new ArrayList<>();
|
||||||
|
for (TrackSample s : allSamples) {
|
||||||
|
if (s.getIsHuman() != null) {
|
||||||
|
if (s.getIsHuman()) humanList.add(s);
|
||||||
|
else botList.add(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (humanList.size() < 5 || botList.size() < 5) {
|
||||||
|
lastTrainingSummary = String.format("正负样本不均衡 human=%d bot=%d", humanList.size(), botList.size());
|
||||||
|
return Map.of("status", "skipped", "reason", lastTrainingSummary);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, double[]> humanStats = computeStats(humanList);
|
||||||
|
Map<String, double[]> botStats = computeStats(botList);
|
||||||
|
|
||||||
|
List<LearnedRule> learnedRules = new ArrayList<>();
|
||||||
|
String[] featureNames = {
|
||||||
|
"totalDuration", "totalPoints", "startOffset", "speedVariance",
|
||||||
|
"straightness", "yDirectionChanges", "speedPhaseCorrelation",
|
||||||
|
"maxJumpDistance", "pauses", "overshootRatio",
|
||||||
|
"accelerationVariance", "xUniformity", "speedSkewness", "pathEfficiency"
|
||||||
|
};
|
||||||
|
|
||||||
|
for (String name : featureNames) {
|
||||||
|
double[] hStat = humanStats.get(name);
|
||||||
|
double[] bStat = botStats.get(name);
|
||||||
|
if (hStat == null || bStat == null) continue;
|
||||||
|
|
||||||
|
double hMean = hStat[0], hStd = hStat[1];
|
||||||
|
double bMean = bStat[0], bStd = bStat[1];
|
||||||
|
|
||||||
|
double separation = Math.abs(hMean - bMean) / (hStd + bStd + 0.001);
|
||||||
|
double weight = Math.min(2.0, 0.5 + separation * 0.5);
|
||||||
|
|
||||||
|
double lowThreshold, highThreshold;
|
||||||
|
if (hMean < bMean) {
|
||||||
|
lowThreshold = hMean - 2 * hStd;
|
||||||
|
highThreshold = hMean + 2 * hStd;
|
||||||
|
} else {
|
||||||
|
lowThreshold = bMean - 2 * bStd;
|
||||||
|
highThreshold = bMean + 2 * bStd;
|
||||||
|
}
|
||||||
|
|
||||||
|
learnedRules.add(new LearnedRule(name, weight, hMean, bMean, hStd, bStd, lowThreshold, highThreshold, separation));
|
||||||
|
}
|
||||||
|
|
||||||
|
learnedRules.sort((a, b) -> Double.compare(b.separation, a.separation));
|
||||||
|
|
||||||
|
saveModel(learnedRules);
|
||||||
|
applyModel(learnedRules);
|
||||||
|
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
sb.append(String.format("训练完成: %d样本(human=%d,bot=%d), Top规则:\n", allSamples.size(), humanList.size(), botList.size()));
|
||||||
|
for (int i = 0; i < Math.min(5, learnedRules.size()); i++) {
|
||||||
|
LearnedRule r = learnedRules.get(i);
|
||||||
|
sb.append(String.format(" %d. %s (分离度=%.2f, 权重=%.2f)\n", i + 1, r.name, r.separation, r.weight));
|
||||||
|
}
|
||||||
|
lastTrainingSummary = sb.toString();
|
||||||
|
log.info("[ML] {}", lastTrainingSummary);
|
||||||
|
|
||||||
|
return Map.of(
|
||||||
|
"status", "trained",
|
||||||
|
"totalSamples", allSamples.size(),
|
||||||
|
"humanSamples", humanList.size(),
|
||||||
|
"botSamples", botList.size(),
|
||||||
|
"rules", learnedRules.size(),
|
||||||
|
"topRules", learnedRules.subList(0, Math.min(5, learnedRules.size()))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, double[]> computeStats(List<TrackSample> samples) {
|
||||||
|
Map<String, List<Double>> buckets = new LinkedHashMap<>();
|
||||||
|
String[] featureNames = {
|
||||||
|
"totalDuration", "totalPoints", "startOffset", "speedVariance",
|
||||||
|
"straightness", "yDirectionChanges", "speedPhaseCorrelation",
|
||||||
|
"maxJumpDistance", "pauses", "overshootRatio",
|
||||||
|
"accelerationVariance", "xUniformity", "speedSkewness", "pathEfficiency"
|
||||||
|
};
|
||||||
|
for (String name : featureNames) buckets.put(name, new ArrayList<>());
|
||||||
|
|
||||||
|
for (TrackSample s : samples) {
|
||||||
|
addVal(buckets, "totalDuration", s.getTotalDuration());
|
||||||
|
addVal(buckets, "totalPoints", s.getTotalPoints());
|
||||||
|
addVal(buckets, "startOffset", s.getStartOffset());
|
||||||
|
addVal(buckets, "speedVariance", s.getSpeedVariance());
|
||||||
|
addVal(buckets, "straightness", s.getStraightness());
|
||||||
|
addVal(buckets, "yDirectionChanges", s.getYDirectionChanges());
|
||||||
|
addVal(buckets, "speedPhaseCorrelation", s.getSpeedPhaseCorrelation());
|
||||||
|
addVal(buckets, "maxJumpDistance", s.getMaxJumpDistance());
|
||||||
|
addVal(buckets, "pauses", s.getPauses());
|
||||||
|
addVal(buckets, "overshootRatio", s.getOvershootRatio());
|
||||||
|
addVal(buckets, "accelerationVariance", s.getAccelerationVariance());
|
||||||
|
addVal(buckets, "xUniformity", s.getXUniformity());
|
||||||
|
addVal(buckets, "speedSkewness", s.getSpeedSkewness());
|
||||||
|
addVal(buckets, "pathEfficiency", s.getPathEfficiency());
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, double[]> stats = new LinkedHashMap<>();
|
||||||
|
for (Map.Entry<String, List<Double>> e : buckets.entrySet()) {
|
||||||
|
List<Double> vals = e.getValue();
|
||||||
|
if (vals.isEmpty()) { stats.put(e.getKey(), new double[]{0, 0}); continue; }
|
||||||
|
double mean = vals.stream().mapToDouble(d -> d).average().orElse(0);
|
||||||
|
double std = Math.sqrt(vals.stream().mapToDouble(d -> (d - mean) * (d - mean)).average().orElse(0));
|
||||||
|
stats.put(e.getKey(), new double[]{mean, std});
|
||||||
|
}
|
||||||
|
return stats;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addVal(Map<String, List<Double>> buckets, String key, Number val) {
|
||||||
|
if (val != null) buckets.get(key).add(val.doubleValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void applyModel(List<LearnedRule> learnedRules) {
|
||||||
|
ruleEngine.getRules().clear();
|
||||||
|
for (LearnedRule lr : learnedRules) {
|
||||||
|
ruleEngine.addRule(new Rule("learned_" + lr.name, lr.weight, f -> {
|
||||||
|
double val = getFeatureValue(f, lr.name);
|
||||||
|
if (lr.hMean < lr.bMean) {
|
||||||
|
if (val < lr.lowThreshold) return new RuleResult(0, lr.name + " too low: " + String.format("%.3f", val));
|
||||||
|
if (val > lr.highThreshold) return new RuleResult(0.3, lr.name + " high: " + String.format("%.3f", val));
|
||||||
|
return new RuleResult(1, lr.name + " OK: " + String.format("%.3f", val));
|
||||||
|
} else {
|
||||||
|
if (val > lr.highThreshold) return new RuleResult(0, lr.name + " too high: " + String.format("%.3f", val));
|
||||||
|
if (val < lr.lowThreshold) return new RuleResult(0.3, lr.name + " low: " + String.format("%.3f", val));
|
||||||
|
return new RuleResult(1, lr.name + " OK: " + String.format("%.3f", val));
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
log.info("[ML] 已应用 {} 条学习规则到 TrackRuleEngine", learnedRules.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
private double getFeatureValue(TrackFeatures f, String name) {
|
||||||
|
return switch (name) {
|
||||||
|
case "totalDuration" -> f.totalDuration;
|
||||||
|
case "totalPoints" -> f.totalPoints;
|
||||||
|
case "startOffset" -> f.startOffset;
|
||||||
|
case "speedVariance" -> f.speedVariance;
|
||||||
|
case "straightness" -> f.straightness;
|
||||||
|
case "yDirectionChanges" -> f.yDirectionChanges;
|
||||||
|
case "speedPhaseCorrelation" -> f.speedPhaseCorrelation;
|
||||||
|
case "maxJumpDistance" -> f.maxJumpDistance;
|
||||||
|
case "pauses" -> f.pauses;
|
||||||
|
case "overshootRatio" -> f.overshootRatio;
|
||||||
|
case "accelerationVariance" -> f.accelerationVariance;
|
||||||
|
case "xUniformity" -> f.xUniformity;
|
||||||
|
case "speedSkewness" -> f.speedSkewness;
|
||||||
|
case "pathEfficiency" -> f.pathEfficiency;
|
||||||
|
default -> 0;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saveModel(List<LearnedRule> rules) {
|
||||||
|
try {
|
||||||
|
Path dir = Paths.get(MODEL_PATH).getParent();
|
||||||
|
if (dir != null) Files.createDirectories(dir);
|
||||||
|
String json = gson.toJson(rules);
|
||||||
|
Files.writeString(Paths.get(MODEL_PATH), json);
|
||||||
|
log.info("[ML] 模型已保存到 {}", MODEL_PATH);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("[ML] 保存模型失败: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void loadModel() {
|
||||||
|
try {
|
||||||
|
Path path = Paths.get(MODEL_PATH);
|
||||||
|
if (!Files.exists(path)) {
|
||||||
|
log.info("[ML] 无已保存模型,使用默认规则");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String json = Files.readString(path);
|
||||||
|
List<LearnedRule> rules = gson.fromJson(json, new com.google.gson.reflect.TypeToken<List<LearnedRule>>() {}.getType());
|
||||||
|
if (rules != null && !rules.isEmpty()) {
|
||||||
|
applyModel(rules);
|
||||||
|
log.info("[ML] 已从 {} 加载 {} 条学习规则", MODEL_PATH, rules.size());
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("[ML] 加载模型失败: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> getStatus() {
|
||||||
|
Map<String, Object> status = new LinkedHashMap<>();
|
||||||
|
status.put("totalSamples", totalSamples.get());
|
||||||
|
status.put("humanSamples", humanSamples.get());
|
||||||
|
status.put("botSamples", botSamples.get());
|
||||||
|
status.put("lastTrainingTime", lastTrainingTime.get());
|
||||||
|
status.put("lastTrainingSummary", lastTrainingSummary);
|
||||||
|
status.put("trainingInProgress", trainingInProgress.get());
|
||||||
|
status.put("activeRuleCount", ruleEngine.getRules().size());
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run(String... args) {
|
||||||
|
try {
|
||||||
|
totalSamples.set((int) sampleRepository.count());
|
||||||
|
humanSamples.set((int) sampleRepository.countByIsHuman(true));
|
||||||
|
botSamples.set((int) sampleRepository.countByIsHuman(false));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("[ML] 初始化样本统计失败(表可能尚未创建): {}", e.getMessage());
|
||||||
|
}
|
||||||
|
loadModel();
|
||||||
|
log.info("[ML] 轨迹学习服务启动 样本总数={} human={} bot={}", totalSamples.get(), humanSamples.get(), botSamples.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class LearnedRule {
|
||||||
|
String name;
|
||||||
|
double weight;
|
||||||
|
double hMean, bMean, hStd, bStd;
|
||||||
|
double lowThreshold, highThreshold;
|
||||||
|
double separation;
|
||||||
|
|
||||||
|
LearnedRule() {}
|
||||||
|
|
||||||
|
LearnedRule(String name, double weight, double hMean, double bMean, double hStd, double bStd, double lowThreshold, double highThreshold, double separation) {
|
||||||
|
this.name = name;
|
||||||
|
this.weight = weight;
|
||||||
|
this.hMean = hMean;
|
||||||
|
this.bMean = bMean;
|
||||||
|
this.hStd = hStd;
|
||||||
|
this.bStd = bStd;
|
||||||
|
this.lowThreshold = lowThreshold;
|
||||||
|
this.highThreshold = highThreshold;
|
||||||
|
this.separation = separation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
server:
|
||||||
|
port: 18200
|
||||||
|
|
||||||
|
spring:
|
||||||
|
datasource:
|
||||||
|
url: jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:captcha_forge}
|
||||||
|
username: ${DB_USER:pgsql}
|
||||||
|
password: ${DB_PASS:}
|
||||||
|
driver-class-name: org.postgresql.Driver
|
||||||
|
jpa:
|
||||||
|
hibernate:
|
||||||
|
ddl-auto: none
|
||||||
|
show-sql: false
|
||||||
|
properties:
|
||||||
|
hibernate:
|
||||||
|
dialect: org.hibernate.dialect.PostgreSQLDialect
|
||||||
|
sql:
|
||||||
|
init:
|
||||||
|
mode: never
|
||||||
|
|
||||||
|
data:
|
||||||
|
redis:
|
||||||
|
host: ${REDIS_HOST:localhost}
|
||||||
|
port: ${REDIS_PORT:6379}
|
||||||
|
password: ${REDIS_PASS:}
|
||||||
|
database: ${REDIS_DB:0}
|
||||||
|
|
||||||
|
jackson:
|
||||||
|
date-format: yyyy-MM-dd HH:mm:ss
|
||||||
|
time-zone: Asia/Shanghai
|
||||||
|
|
||||||
|
captcha:
|
||||||
|
prefix: captcha
|
||||||
|
expire:
|
||||||
|
default: 120000
|
||||||
|
init-default-resource: true
|
||||||
|
local-cache-enabled: true
|
||||||
|
local-cache-size: 20
|
||||||
|
|
||||||
|
jwt:
|
||||||
|
secret: ${JWT_SECRET:tianai-captcha-jwt-secret-key-must-be-at-least-256-bits-long-for-hs256}
|
||||||
|
expiration: ${JWT_EXPIRATION:86400000}
|
||||||
|
|
||||||
|
minio:
|
||||||
|
endpoint: ${MINIO_ENDPOINT:http://localhost:9000}
|
||||||
|
access-key: ${MINIO_ACCESS_KEY:minioadmin}
|
||||||
|
secret-key: ${MINIO_SECRET_KEY:minioadmin}
|
||||||
|
bucket: ${MINIO_BUCKET:tianai-captcha}
|
||||||
|
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
cloud.tianai.captcha: INFO
|
||||||
|
root: WARN
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
server:
|
||||||
|
port: 18200
|
||||||
|
|
||||||
|
spring:
|
||||||
|
datasource:
|
||||||
|
url: jdbc:postgresql://localhost:5432/captcha_forge
|
||||||
|
username: postgres
|
||||||
|
password: XGYnJPysCNJsLeea
|
||||||
|
driver-class-name: org.postgresql.Driver
|
||||||
|
jpa:
|
||||||
|
hibernate:
|
||||||
|
ddl-auto: none
|
||||||
|
show-sql: false
|
||||||
|
properties:
|
||||||
|
hibernate:
|
||||||
|
dialect: org.hibernate.dialect.PostgreSQLDialect
|
||||||
|
sql:
|
||||||
|
init:
|
||||||
|
mode: always
|
||||||
|
|
||||||
|
data:
|
||||||
|
redis:
|
||||||
|
host: localhost
|
||||||
|
port: 6379
|
||||||
|
|
||||||
|
captcha:
|
||||||
|
prefix: captcha
|
||||||
|
expire:
|
||||||
|
default: 120000
|
||||||
|
init-default-resource: true
|
||||||
|
local-cache-enabled: true
|
||||||
|
local-cache-size: 20
|
||||||
|
|
||||||
|
jwt:
|
||||||
|
secret: tianai-captcha-jwt-secret-key-must-be-at-least-256-bits-long-for-hs256
|
||||||
|
expiration: 86400000
|
||||||
|
|
||||||
|
minio:
|
||||||
|
endpoint: http://localhost:9000
|
||||||
|
access-key: minioadmin
|
||||||
|
secret-key: minioadmin
|
||||||
|
bucket: captcha-resources
|
||||||
|
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
cloud.tianai.captcha: INFO
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
DROP TABLE IF EXISTS verification_logs CASCADE;
|
||||||
|
DROP TABLE IF EXISTS track_samples CASCADE;
|
||||||
|
DROP TABLE IF EXISTS captcha_challenges CASCADE;
|
||||||
|
DROP TABLE IF EXISTS captcha_categories CASCADE;
|
||||||
|
DROP TABLE IF EXISTS sites CASCADE;
|
||||||
|
DROP TABLE IF EXISTS plans CASCADE;
|
||||||
|
DROP TABLE IF EXISTS users CASCADE;
|
||||||
|
DROP TABLE IF EXISTS announcements CASCADE;
|
||||||
|
DROP TABLE IF EXISTS captcha_ip_blacklist CASCADE;
|
||||||
|
|
||||||
|
CREATE TABLE users (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
username VARCHAR(64) NOT NULL UNIQUE,
|
||||||
|
email VARCHAR(128),
|
||||||
|
password VARCHAR(256) NOT NULL,
|
||||||
|
role VARCHAR(16) DEFAULT 'USER',
|
||||||
|
site_amount INT DEFAULT 0,
|
||||||
|
is_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
is_system BOOLEAN DEFAULT FALSE,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE plans (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
name VARCHAR(64) NOT NULL,
|
||||||
|
description VARCHAR(256),
|
||||||
|
qps INT DEFAULT 10,
|
||||||
|
daily_limit INT DEFAULT 500,
|
||||||
|
captcha_types TEXT[] DEFAULT '{SLIDER,PUZZLE,TEXT_CLICK,ICON_CLICK,ICON_UNDERSTAND}',
|
||||||
|
custom_style BOOLEAN DEFAULT FALSE,
|
||||||
|
is_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
is_system BOOLEAN DEFAULT FALSE,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE sites (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
user_id INT REFERENCES users(id),
|
||||||
|
name VARCHAR(64) NOT NULL,
|
||||||
|
domain VARCHAR(256),
|
||||||
|
favicon VARCHAR(512),
|
||||||
|
logo VARCHAR(512),
|
||||||
|
site_key UUID DEFAULT gen_random_uuid() UNIQUE,
|
||||||
|
secret_key UUID DEFAULT gen_random_uuid() UNIQUE,
|
||||||
|
verify_level VARCHAR(16) DEFAULT 'MEDIUM',
|
||||||
|
qps INT DEFAULT 10,
|
||||||
|
daily_limit INT DEFAULT 500,
|
||||||
|
captcha_types TEXT[] DEFAULT '{SLIDER,PUZZLE,TEXT_CLICK,ICON_CLICK,ICON_UNDERSTAND}',
|
||||||
|
plan_id INT REFERENCES plans(id),
|
||||||
|
plan_expire_at TIMESTAMPTZ,
|
||||||
|
is_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
rsa_public_key TEXT,
|
||||||
|
rsa_private_key TEXT,
|
||||||
|
aes_key VARCHAR(256),
|
||||||
|
signing_key VARCHAR(256),
|
||||||
|
track_validation_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
track_human_threshold FLOAT DEFAULT 0.5,
|
||||||
|
obfuscation_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
encryption_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE captcha_categories (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
name VARCHAR(64) NOT NULL,
|
||||||
|
label VARCHAR(64) NOT NULL,
|
||||||
|
items TEXT[] NOT NULL DEFAULT '{}',
|
||||||
|
is_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE captcha_challenges (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
category_id INT REFERENCES captcha_categories(id) ON DELETE CASCADE,
|
||||||
|
prompt TEXT NOT NULL,
|
||||||
|
correct_items TEXT[] NOT NULL DEFAULT '{}',
|
||||||
|
difficulty VARCHAR(16) DEFAULT 'MEDIUM',
|
||||||
|
is_enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
use_count INT DEFAULT 0,
|
||||||
|
success_rate DOUBLE PRECISION DEFAULT 0.5,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE verification_logs (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
site_id INT REFERENCES sites(id),
|
||||||
|
site_key UUID,
|
||||||
|
captcha_type VARCHAR(32),
|
||||||
|
scene VARCHAR(64) DEFAULT 'default',
|
||||||
|
ip VARCHAR(45),
|
||||||
|
is_pass BOOLEAN,
|
||||||
|
behavior_score DOUBLE PRECISION,
|
||||||
|
risk_level VARCHAR(16),
|
||||||
|
cost_time INT,
|
||||||
|
captcha_id VARCHAR(128),
|
||||||
|
user_agent TEXT,
|
||||||
|
track_score FLOAT,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE track_samples (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
site_id INT REFERENCES sites(id),
|
||||||
|
captcha_type VARCHAR(32),
|
||||||
|
is_human BOOLEAN,
|
||||||
|
ml_score DOUBLE PRECISION,
|
||||||
|
basic_pass BOOLEAN,
|
||||||
|
total_points INT,
|
||||||
|
total_duration BIGINT,
|
||||||
|
displacement_x FLOAT,
|
||||||
|
displacement_y FLOAT,
|
||||||
|
displacement_x_ratio FLOAT,
|
||||||
|
total_path_length DOUBLE PRECISION,
|
||||||
|
path_efficiency DOUBLE PRECISION,
|
||||||
|
avg_speed FLOAT,
|
||||||
|
max_speed FLOAT,
|
||||||
|
min_speed FLOAT,
|
||||||
|
speed_variance DOUBLE PRECISION,
|
||||||
|
speed_std_dev DOUBLE PRECISION,
|
||||||
|
speed_skewness DOUBLE PRECISION,
|
||||||
|
avg_acceleration FLOAT,
|
||||||
|
max_acceleration FLOAT,
|
||||||
|
min_acceleration FLOAT,
|
||||||
|
acceleration_variance DOUBLE PRECISION,
|
||||||
|
direction_changes INT,
|
||||||
|
y_direction_changes INT,
|
||||||
|
pauses INT,
|
||||||
|
start_offset DOUBLE PRECISION,
|
||||||
|
straightness DOUBLE PRECISION,
|
||||||
|
x_uniformity DOUBLE PRECISION,
|
||||||
|
y_uniformity DOUBLE PRECISION,
|
||||||
|
avg_point_interval FLOAT,
|
||||||
|
speed_phase_correlation DOUBLE PRECISION,
|
||||||
|
max_jump_distance DOUBLE PRECISION,
|
||||||
|
overshoot_ratio DOUBLE PRECISION,
|
||||||
|
track_json TEXT,
|
||||||
|
ip VARCHAR(45),
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE announcements (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
title VARCHAR(256) NOT NULL,
|
||||||
|
content TEXT,
|
||||||
|
is_pinned BOOLEAN DEFAULT FALSE,
|
||||||
|
is_published BOOLEAN DEFAULT TRUE,
|
||||||
|
sort_order INT DEFAULT 0,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE captcha_ip_blacklist (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
ip VARCHAR(64) NOT NULL,
|
||||||
|
reason VARCHAR(256),
|
||||||
|
ban_until TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_sites_key ON sites(site_key);
|
||||||
|
CREATE INDEX idx_sites_user ON sites(user_id);
|
||||||
|
CREATE INDEX idx_challenges_category ON captcha_challenges(category_id);
|
||||||
|
CREATE INDEX idx_challenges_difficulty ON captcha_challenges(difficulty);
|
||||||
|
CREATE INDEX idx_logs_site ON verification_logs(site_id);
|
||||||
|
CREATE INDEX idx_logs_time ON verification_logs(created_at);
|
||||||
|
CREATE INDEX idx_logs_type ON verification_logs(captcha_type);
|
||||||
|
CREATE INDEX idx_logs_pass ON verification_logs(is_pass);
|
||||||
|
CREATE INDEX idx_ip_blacklist_ip ON captcha_ip_blacklist(ip);
|
||||||
|
CREATE INDEX idx_track_human ON track_samples(is_human);
|
||||||
|
CREATE INDEX idx_track_type ON track_samples(captcha_type);
|
||||||
|
CREATE INDEX idx_track_time ON track_samples(created_at);
|
||||||
|
CREATE INDEX idx_track_score ON track_samples(ml_score);
|
||||||
|
|
||||||
|
INSERT INTO users (username, email, password, role, site_amount, is_enabled, is_system)
|
||||||
|
VALUES ('admin', 'admin@captchaforge.local', '$2a$10$85QOiy3qD5KPuxyrrN/LcuZe3ty/OrTk6yEKAJEGtJKk97ukw2yPG', 'ADMIN', 999, TRUE, TRUE);
|
||||||
|
|
||||||
|
INSERT INTO plans (name, description, qps, daily_limit, is_enabled, is_system) VALUES
|
||||||
|
('免费套餐', '默认免费套餐', 5, 500, TRUE, TRUE),
|
||||||
|
('基础套餐', '适合中小站点', 20, 5000, TRUE, TRUE),
|
||||||
|
('专业套餐', '适合大型站点', 100, 50000, TRUE, TRUE);
|
||||||
|
|
||||||
|
INSERT INTO captcha_categories (name, label, items) VALUES
|
||||||
|
('animals', '动物', '{"🐶","🐱","🐭","🐹","🐰","🦊","🐻","🐼","🐨","🐯","🦁","🐮","🐷","🐸","🐵","🐔","🐧","🐦","🦅","🦆","🦉","🐴","🦄","🐝","🐛","🦋","🐌","🐞","🐢","🐍","🦎","🐙","🦑","🦐","🦀","🐠","🐟","🐬","🐳","🐊","🐘","🦏","🐪","🦒","🐕","🐈","🐓","🦃","🦚","🦜","🐇","🦔","🐺","🐗"}'),
|
||||||
|
('food', '食物饮品', '{"🍎","🍐","🍊","🍋","🍌","🍉","🍇","🍓","🍒","🍑","🥭","🍍","🥥","🥝","🍅","🍆","🥑","🥦","🌽","🥕","🍞","🧀","🍳","🍔","🍟","🍕","🌮","🍣","🍜","🍩","🍪","🎂","🍫","🍭","☕","🍵","🧃","🥤","🍺","🍷"}'),
|
||||||
|
('vehicles', '交通工具', '{"🚗","🚕","🚙","🚌","🏎","🚓","🚑","🚒","🚐","🚚","🚛","🚜","🚲","🛵","🏍","🚨","🚔","🚡","🚠","🚃","🚋","🚄","🚅","🚂","✈️","🛩","🚀","🛸","🚁","⛵","🚤","🛳","⛴","🚢"}'),
|
||||||
|
('nature', '天气自然', '{"☀️","🌤","⛅","🌥","☁️","🌦","🌧","⛈","🌩","🌨","❄️","☃️","🌪","🌈","🌊","💧","🔥","⭐","🌟","✨","⚡","☄️","🌸","🌺","🌻","🌹","🌷","🌱","🌿","🍀","🍁","🍂","🍃","🌴","🌵"}'),
|
||||||
|
('sports', '运动娱乐', '{"⚽","🏀","🏈","⚾","🎾","🏐","🏉","🎱","🏓","🏸","🏒","🏑","🥍","🎯","🎳","🎮","🎲","♟","🧩","🪀","🪁","🎪","🤹","🎭","🎨","🎬","🎤","🎧","🎹","🥁","🎸","🎻"}'),
|
||||||
|
('buildings', '建筑地点', '{"🏠","🏡","🏢","🏣","🏤","🏥","🏦","🏨","🏩","🏪","🏫","🏬","🏭","🏯","🏰","💒","🗼","🗽","⛪","🕌","🛕","🕍","⛩","🕋","⛲","⛺","🏕"}'),
|
||||||
|
('objects', '电子物品', '{"⌚","📱","💻","⌨️","🖥","🖨","🖱","🖲","💾","💿","📷","📹","🎥","📞","📺","📻","🔋","🔌","💡","🔦","🕯","🔑","🔒","🔓","📧","📮","📦","📋","📁","✏️","🖊","🖋","✒️","🖌","📝","🔍","📎","📐","📌","✂️","🧲","🔧","🔨","⚙️","💊","💉","🩺","🧬","🔭","🔬","🧪"}'),
|
||||||
|
('gestures', '手势动作', '{"👋","🤚","🖐","✋","🖖","👌","🤌","🤏","✌","🤞","🤟","🤘","🤙","👈","👉","👆","👇","☝️","👍","👎","✊","👊","🤛","🤜","👏","🙌","👐","🤲","🤝","🙏","✍️","💅","🤳","💪"}');
|
||||||
|
|
||||||
|
INSERT INTO captcha_challenges (category_id, prompt, correct_items, difficulty) VALUES
|
||||||
|
(1, '请点击所有的猫科动物', '{"🐱","🐯","🦁","🐈"}', 'MEDIUM'),
|
||||||
|
(1, '请点击所有的犬科动物', '{"🐶","🐺","🐕"}', 'MEDIUM'),
|
||||||
|
(1, '请点击所有的鸟类', '{"🐔","🐧","🐦","🦅","🦆","🦉","🦜","🦚","🦃"}', 'MEDIUM'),
|
||||||
|
(1, '请点击所有的水生动物', '{"🐙","🦑","🦐","🦀","🐠","🐟","🐬","🐳"}', 'MEDIUM'),
|
||||||
|
(1, '请点击所有的昆虫', '{"🐝","🐛","🦋","🐌","🐞","🦟"}', 'MEDIUM'),
|
||||||
|
(2, '请点击所有的水果', '{"🍎","🍐","🍊","🍋","🍌","🍉","🍇","🍓","🍒","🍑","🥭","🍍","🥝"}', 'MEDIUM'),
|
||||||
|
(2, '请点击所有的蔬菜', '{"🍅","🍆","🥑","🥦","🌽","🥕"}', 'MEDIUM'),
|
||||||
|
(2, '请点击所有的饮品', '{"☕","🍵","🧃","🥤","🍺","🍷"}', 'MEDIUM'),
|
||||||
|
(2, '请点击所有的甜点', '{"🍩","🍪","🎂","🍫","🍭"}', 'MEDIUM'),
|
||||||
|
(3, '请点击所有的汽车', '{"🚗","🚕","🚙","🏎","🚓","🚑","🚒","🚐"}', 'MEDIUM'),
|
||||||
|
(3, '请点击所有的飞行器', '{"✈️","🛩","🚀","🛸","🚁"}', 'MEDIUM'),
|
||||||
|
(3, '请点击所有的船只', '{"⛵","🚤","🛳","⛴","🚢"}', 'MEDIUM'),
|
||||||
|
(4, '请点击所有与降水相关的', '{"🌦","🌧","⛈","🌩","🌨"}', 'MEDIUM'),
|
||||||
|
(4, '请点击所有的花卉', '{"🌸","🌺","🌻","🌹","🌷"}', 'MEDIUM'),
|
||||||
|
(4, '请点击所有的天体', '{"☀️","⭐","🌟","✨","⚡","☄️"}', 'MEDIUM'),
|
||||||
|
(5, '请点击所有的球类运动', '{"⚽","🏀","🏈","⚾","🎾","🏐","🏉"}', 'MEDIUM'),
|
||||||
|
(5, '请点击所有的音乐相关', '{"🎤","🎧","🎹","🥁","🎸","🎻"}', 'MEDIUM'),
|
||||||
|
(5, '请点击所有的棋牌游戏', '{"🎲","♟","🧩","🎮","🎯","🎱"}', 'MEDIUM'),
|
||||||
|
(1, '请点击所有的动物', '{"🐶","🐱","🐭","🐹","🐰","🦊","🐻","🐼","🐨","🐯","🦁","🐮","🐷","🐸","🐵","🐔","🐧","🐦","🦅","🦆","🦉","🐴","🦄","🐝","🐛","🦋","🐌","🐞","🐢","🐍","🦎","🐙","🦑","🦐","🦀","🐠","🐟","🐬","🐳","🐊","🐘","🦏","🐪","🦒","🐕","🐈","🐓","🦃","🦚","🦜","🐇","🦔","🐺","🐗"}', 'LOW'),
|
||||||
|
(2, '请点击所有的食物饮品', '{"🍎","🍐","🍊","🍋","🍌","🍉","🍇","🍓","🍒","🍑","🥭","🍍","🥥","🥝","🍅","🍆","🥑","🥦","🌽","🥕","🍞","🧀","🍳","🍔","🍟","🍕","🌮","🍣","🍜","🍩","🍪","🎂","🍫","🍭","☕","🍵","🧃","🥤","🍺","🍷"}', 'LOW'),
|
||||||
|
(3, '请点击所有的交通工具', '{"🚗","🚕","🚙","🚌","🏎","🚓","🚑","🚒","🚐","🚚","🚛","🚜","🚲","🛵","🏍","🚨","🚔","🚡","🚠","🚃","🚋","🚄","🚅","🚂","✈️","🛩","🚀","🛸","🚁","⛵","🚤","🛳","⛴","🚢"}', 'LOW'),
|
||||||
|
(4, '请点击所有的天气自然', '{"☀️","🌤","⛅","🌥","☁️","🌦","🌧","⛈","🌩","🌨","❄️","☃️","🌪","🌈","🌊","💧","🔥","⭐","🌟","✨","⚡","☄️","🌸","🌺","🌻","🌹","🌷","🌱","🌿","🍀","🍁","🍂","🍃","🌴","🌵"}', 'LOW');
|
||||||
|
|
||||||
|
INSERT INTO announcements (title, content, is_pinned, is_published, sort_order) VALUES
|
||||||
|
('tianai-captcha-enhanced 2.0.0 上线', '# tianai-captcha-enhanced
|
||||||
|
|
||||||
|
基于 tianai-captcha 开源版的增强版行为验证码平台
|
||||||
|
|
||||||
|
## 特性
|
||||||
|
- 16种验证码类型
|
||||||
|
- ML轨迹校验器(28维特征+14条规则)
|
||||||
|
- 对抗扰动防YOLO
|
||||||
|
- 行为风控引擎
|
||||||
|
- 端到端加密(AES-256+RSA-4096)
|
||||||
|
- 背景乱序/正弦扭曲/噪声注入
|
||||||
|
- IP黑名单+滑动窗口限流', TRUE, TRUE, 0);
|
||||||
+74
@@ -0,0 +1,74 @@
|
|||||||
|
package cloud.tianai.captcha.platform;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||||
|
import org.springframework.http.*;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
class CaptchaApiIntegrationTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private TestRestTemplate restTemplate;
|
||||||
|
|
||||||
|
private String jwtToken;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void login() {
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
HttpEntity<Map<String, String>> request = new HttpEntity<>(
|
||||||
|
Map.of("username", "admin", "password", "admin"), headers);
|
||||||
|
var response = restTemplate.postForEntity("/api/auth/login", request, Map.class);
|
||||||
|
if (response.getBody() != null && response.getBody().get("data") != null) {
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, Object> data = (Map<String, Object>) response.getBody().get("data");
|
||||||
|
if (data != null && data.get("token") != null) {
|
||||||
|
jwtToken = (String) data.get("token");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private HttpHeaders authHeaders() {
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
if (jwtToken != null) {
|
||||||
|
headers.setBearerAuth(jwtToken);
|
||||||
|
}
|
||||||
|
return headers;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void contextLoads() {
|
||||||
|
assertNotNull(restTemplate);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void loginReturnsToken() {
|
||||||
|
assertNotNull(jwtToken, "JWT token should not be null after login");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void statsEndpointReturnsData() {
|
||||||
|
HttpEntity<Void> entity = new HttpEntity<>(authHeaders());
|
||||||
|
var response = restTemplate.exchange("/api/admin/stats", HttpMethod.GET, entity, Map.class);
|
||||||
|
assertEquals(200, response.getStatusCode().value());
|
||||||
|
assertNotNull(response.getBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void siteListEndpointReturnsData() {
|
||||||
|
HttpEntity<Void> entity = new HttpEntity<>(authHeaders());
|
||||||
|
var response = restTemplate.exchange("/api/admin/sites?page=0&size=10", HttpMethod.GET, entity, Map.class);
|
||||||
|
assertEquals(200, response.getStatusCode().value());
|
||||||
|
assertNotNull(response.getBody());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
spring:
|
||||||
|
datasource:
|
||||||
|
url: jdbc:h2:mem:testdb;MODE=PostgreSQL
|
||||||
|
driver-class-name: org.h2.Driver
|
||||||
|
username: sa
|
||||||
|
password:
|
||||||
|
jpa:
|
||||||
|
hibernate:
|
||||||
|
ddl-auto: validate
|
||||||
|
show-sql: false
|
||||||
|
properties:
|
||||||
|
hibernate:
|
||||||
|
dialect: org.hibernate.dialect.H2Dialect
|
||||||
|
h2:
|
||||||
|
console:
|
||||||
|
enabled: false
|
||||||
|
data:
|
||||||
|
redis:
|
||||||
|
host: localhost
|
||||||
|
port: 6379
|
||||||
|
|
||||||
|
jwt:
|
||||||
|
secret: test-secret-key-must-be-at-least-256-bits-long-for-hs256
|
||||||
|
expiration: 86400000
|
||||||
|
|
||||||
|
captcha:
|
||||||
|
prefix: captcha
|
||||||
|
expire:
|
||||||
|
default: 120000
|
||||||
|
init-default-resource: false
|
||||||
|
local-cache-enabled: false
|
||||||
|
|
||||||
|
minio:
|
||||||
|
endpoint: http://localhost:9000
|
||||||
|
access-key: minioadmin
|
||||||
|
secret-key: minioadmin
|
||||||
|
bucket: captcha-resources
|
||||||
|
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
cloud.tianai.captcha: DEBUG
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"name": "tianai-captcha-sdk",
|
||||||
|
"version": "2.0.0",
|
||||||
|
"description": "tianai-captcha-enhanced 前端SDK,兼容TPCaptcha API",
|
||||||
|
"main": "dist/captcha.min.js",
|
||||||
|
"scripts": {
|
||||||
|
"build": "terser src/captcha.js -o dist/captcha.min.js -c -m",
|
||||||
|
"dev": "echo 'Copy src/captcha.js to your project for development'"
|
||||||
|
},
|
||||||
|
"keywords": ["captcha", "slider", "puzzle", "tianai", "verification"],
|
||||||
|
"license": "Apache-2.0"
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,63 +0,0 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<parent>
|
|
||||||
<groupId>cloud.tianai.captcha</groupId>
|
|
||||||
<artifactId>tianai-captcha-parent</artifactId>
|
|
||||||
<version>${revision}</version>
|
|
||||||
</parent>
|
|
||||||
<artifactId>tianai-captcha-solon-plugin</artifactId>
|
|
||||||
<name>tianai-captcha-solon-plugin</name>
|
|
||||||
<description>行为验证码的solon插件</description>
|
|
||||||
<url>https://gitee.com/tianai/tianai-captcha-solon-plugin</url>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<solon.version>3.5.2</solon.version>
|
|
||||||
<maven.compiler.source>8</maven.compiler.source>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
|
|
||||||
<java.version>1.8</java.version>
|
|
||||||
<!-- 打包跳过单元测试 -->
|
|
||||||
<skipTests>true</skipTests>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
|
||||||
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.noear</groupId>
|
|
||||||
<artifactId>solon</artifactId>
|
|
||||||
<version>${solon.version}</version>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.noear</groupId>
|
|
||||||
<artifactId>solon-web</artifactId>
|
|
||||||
<version>${solon.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>cloud.tianai.captcha</groupId>
|
|
||||||
<artifactId>tianai-captcha</artifactId>
|
|
||||||
<version>${revision}</version>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<configuration>
|
|
||||||
<source>8</source>
|
|
||||||
<target>8</target>
|
|
||||||
<compilerArgument>-parameters</compilerArgument>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
</project>
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
package cloud.tianai.captcha.solon;
|
|
||||||
|
|
||||||
import cloud.tianai.captcha.solon.config.ImageCaptchaAutoConfiguration;
|
|
||||||
import cloud.tianai.captcha.solon.properties.CaptchaProperties;
|
|
||||||
import org.noear.solon.core.AppContext;
|
|
||||||
import org.noear.solon.core.Plugin;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 插件启动类
|
|
||||||
* @Author XT
|
|
||||||
* @Date 2024.09.03
|
|
||||||
*/
|
|
||||||
public class XPluginImp implements Plugin {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void start(AppContext context) {
|
|
||||||
context.beanMake(CaptchaProperties.class);
|
|
||||||
context.beanMake(ImageCaptchaAutoConfiguration.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
-95
@@ -1,95 +0,0 @@
|
|||||||
package cloud.tianai.captcha.solon.config;
|
|
||||||
|
|
||||||
import cloud.tianai.captcha.application.ImageCaptchaApplication;
|
|
||||||
import cloud.tianai.captcha.application.TACBuilder;
|
|
||||||
import cloud.tianai.captcha.cache.CacheStore;
|
|
||||||
import cloud.tianai.captcha.cache.impl.LocalCacheStore;
|
|
||||||
import cloud.tianai.captcha.resource.common.model.dto.Resource;
|
|
||||||
import cloud.tianai.captcha.solon.plugins.secondary.SecondaryVerificationApplication;
|
|
||||||
import cloud.tianai.captcha.solon.properties.CaptchaProperties;
|
|
||||||
import cloud.tianai.captcha.solon.service.CaptchaRedisCacheService;
|
|
||||||
import org.noear.solon.annotation.Bean;
|
|
||||||
import org.noear.solon.annotation.Configuration;
|
|
||||||
import org.noear.solon.annotation.Inject;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @Author XT
|
|
||||||
* @Date 2024.09.03
|
|
||||||
*/
|
|
||||||
@Configuration
|
|
||||||
public class ImageCaptchaAutoConfiguration {
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
public ImageCaptchaApplication imageCaptchaApplication(CaptchaProperties captchaProperties, @Inject(required = false) CaptchaRedisCacheService cacheService) {
|
|
||||||
TACBuilder tacBuilder = TACBuilder.builder();
|
|
||||||
tacBuilder.addDefaultTemplate();
|
|
||||||
tacBuilder.expire("default", captchaProperties.getExpire());
|
|
||||||
tacBuilder.prefix(captchaProperties.getPrefix());
|
|
||||||
// 注入背景图资源
|
|
||||||
if (captchaProperties.getResources().getAuto()) {
|
|
||||||
String[] split = captchaProperties.getResources().getAutoType().split(",");
|
|
||||||
List<String> wordImageClickList = captchaProperties.getResources().getImages();
|
|
||||||
for (String type : split) {
|
|
||||||
for (String path : wordImageClickList) {
|
|
||||||
tacBuilder.addResource(type, new Resource("classpath", path));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
List<String> wordImageClickList = captchaProperties.getResources().getWORD_IMAGE_CLICK();
|
|
||||||
if (!wordImageClickList.isEmpty()) {
|
|
||||||
for (String path : wordImageClickList) {
|
|
||||||
tacBuilder.addResource("WORD_IMAGE_CLICK", new Resource("classpath", path));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
List<String> concatList = captchaProperties.getResources().getCONCAT();
|
|
||||||
if (!concatList.isEmpty()) {
|
|
||||||
for (String path : concatList) {
|
|
||||||
tacBuilder.addResource("CONCAT", new Resource("classpath", path));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
List<String> sliderList = captchaProperties.getResources().getSLIDER();
|
|
||||||
if (!sliderList.isEmpty()) {
|
|
||||||
for (String path : sliderList) {
|
|
||||||
tacBuilder.addResource("SLIDER", new Resource("classpath", path));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
List<String> rotateList = captchaProperties.getResources().getROTATE();
|
|
||||||
if (!rotateList.isEmpty()) {
|
|
||||||
for (String path : rotateList) {
|
|
||||||
tacBuilder.addResource("ROTATE", new Resource("classpath", path));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 注入字体包
|
|
||||||
if (null != captchaProperties.getFontPath()) {
|
|
||||||
List<String> fontPathList = captchaProperties.getFontPath();
|
|
||||||
if (!fontPathList.isEmpty()) {
|
|
||||||
for (String path : fontPathList) {
|
|
||||||
try {
|
|
||||||
tacBuilder.addFont(new Resource("classpath", path));
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new RuntimeException("读取字体包失败,path=" + path, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
CacheStore cacheStore = cacheService;
|
|
||||||
// 注入缓存器
|
|
||||||
if (null == cacheStore) {
|
|
||||||
cacheStore = new LocalCacheStore();
|
|
||||||
}
|
|
||||||
tacBuilder.setCacheStore(cacheStore);
|
|
||||||
ImageCaptchaApplication target = tacBuilder.build();
|
|
||||||
|
|
||||||
// 二次验证
|
|
||||||
if (captchaProperties.getSecondary().getEnabled()) {
|
|
||||||
target = new SecondaryVerificationApplication(target, captchaProperties, cacheStore);
|
|
||||||
}
|
|
||||||
return target;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
-109
@@ -1,109 +0,0 @@
|
|||||||
package cloud.tianai.captcha.solon.plugins.secondary;
|
|
||||||
|
|
||||||
import cloud.tianai.captcha.application.FilterImageCaptchaApplication;
|
|
||||||
import cloud.tianai.captcha.application.ImageCaptchaApplication;
|
|
||||||
import cloud.tianai.captcha.application.vo.ImageCaptchaVO;
|
|
||||||
import cloud.tianai.captcha.cache.CacheStore;
|
|
||||||
import cloud.tianai.captcha.common.AnyMap;
|
|
||||||
import cloud.tianai.captcha.common.exception.ImageCaptchaException;
|
|
||||||
import cloud.tianai.captcha.common.response.ApiResponse;
|
|
||||||
import cloud.tianai.captcha.solon.properties.CaptchaLimit;
|
|
||||||
import cloud.tianai.captcha.solon.properties.CaptchaProperties;
|
|
||||||
import cloud.tianai.captcha.solon.properties.CaptchaSecondary;
|
|
||||||
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
|
|
||||||
import org.noear.solon.core.handle.Context;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @Author XT
|
|
||||||
* @Date 2024.09.03
|
|
||||||
*/
|
|
||||||
public class SecondaryVerificationApplication extends FilterImageCaptchaApplication {
|
|
||||||
|
|
||||||
private final CaptchaSecondary prop;
|
|
||||||
private final CaptchaProperties captchaProperties;
|
|
||||||
private final CacheStore redisCacheService;
|
|
||||||
|
|
||||||
public SecondaryVerificationApplication(ImageCaptchaApplication target, CaptchaProperties captchaProperties, CacheStore redisCacheService) {
|
|
||||||
super(target);
|
|
||||||
this.captchaProperties = captchaProperties;
|
|
||||||
this.prop = captchaProperties.getSecondary();
|
|
||||||
this.redisCacheService = redisCacheService;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public ApiResponse<ImageCaptchaVO> generateCaptcha(String type) {
|
|
||||||
// 检查是否每分钟超过限制
|
|
||||||
CaptchaLimit limit = captchaProperties.getLimit();
|
|
||||||
if (null != limit && limit.getEnable()) {
|
|
||||||
Context current = Context.current();
|
|
||||||
String errLimitKey = getLimitKey(current, "error");
|
|
||||||
Long errLimit = redisCacheService.getLong(errLimitKey);
|
|
||||||
if (null != errLimit && errLimit >= limit.getErrorLimit()) {
|
|
||||||
throw new ImageCaptchaException("验证次数过多,请稍后再试");
|
|
||||||
}
|
|
||||||
String reqLimitKey = getLimitKey(current, "req");
|
|
||||||
Long reqLimit = redisCacheService.getLong(reqLimitKey);
|
|
||||||
if (null != reqLimit && reqLimit >= limit.getReqLimit()) {
|
|
||||||
throw new ImageCaptchaException("获取验证码频繁,请稍后再试");
|
|
||||||
}
|
|
||||||
redisCacheService.incr(reqLimitKey, 1, 60L, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
return super.generateCaptcha(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public ApiResponse<?> matching(String id, ImageCaptchaTrack imageCaptchaTrack) {
|
|
||||||
ApiResponse<?> match = super.matching(id, imageCaptchaTrack);
|
|
||||||
if (match.isSuccess()) {
|
|
||||||
// 如果匹配成功, 添加二次验证记录
|
|
||||||
addSecondaryVerification(id + getRemoteId(Context.current()), imageCaptchaTrack);
|
|
||||||
} else {
|
|
||||||
CaptchaLimit limit = captchaProperties.getLimit();
|
|
||||||
if (null != limit && limit.getEnable()) {
|
|
||||||
Context current = Context.current();
|
|
||||||
String limitKey = getLimitKey(current, "error");
|
|
||||||
redisCacheService.incr(limitKey, 1, 60L, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return match;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 二次缓存验证
|
|
||||||
* @param id id
|
|
||||||
* @return boolean
|
|
||||||
*/
|
|
||||||
public boolean secondaryVerification(String id) {
|
|
||||||
Map<String, Object> cache = target.getCacheStore().getAndRemoveCache(getKey(id + getRemoteId(Context.current())));
|
|
||||||
return cache != null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 添加二次缓存验证记录
|
|
||||||
* @param id id
|
|
||||||
* @param imageCaptchaTrack sliderCaptchaTrack
|
|
||||||
*/
|
|
||||||
protected void addSecondaryVerification(String id, ImageCaptchaTrack imageCaptchaTrack) {
|
|
||||||
target.getCacheStore().setCache(getKey(id), new AnyMap(), prop.getExpire(), TimeUnit.MILLISECONDS);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected String getKey(String id) {
|
|
||||||
return prop.getKeyPrefix().concat(":").concat(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected String getLimitKey(Context ctx, String type) {
|
|
||||||
return prop.getKeyPrefix().concat(":limit:")
|
|
||||||
.concat(type)
|
|
||||||
.concat(":")
|
|
||||||
.concat(getRemoteId(ctx));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public static String getRemoteId(Context ctx) {
|
|
||||||
return ctx.realIp() + ctx.userAgent();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
-38
@@ -1,38 +0,0 @@
|
|||||||
package cloud.tianai.captcha.solon.properties;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @Author XT
|
|
||||||
* @Date 2024.09.04
|
|
||||||
*/
|
|
||||||
public class CaptchaLimit {
|
|
||||||
|
|
||||||
private Boolean enable;
|
|
||||||
|
|
||||||
private Long reqLimit;
|
|
||||||
|
|
||||||
private Long errorLimit;
|
|
||||||
|
|
||||||
public Boolean getEnable() {
|
|
||||||
return enable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setEnable(Boolean enable) {
|
|
||||||
this.enable = enable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getReqLimit() {
|
|
||||||
return reqLimit;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setReqLimit(Long reqLimit) {
|
|
||||||
this.reqLimit = reqLimit;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getErrorLimit() {
|
|
||||||
return errorLimit;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setErrorLimit(Long errorLimit) {
|
|
||||||
this.errorLimit = errorLimit;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-93
@@ -1,93 +0,0 @@
|
|||||||
package cloud.tianai.captcha.solon.properties;
|
|
||||||
|
|
||||||
import org.noear.solon.annotation.Configuration;
|
|
||||||
import org.noear.solon.annotation.Inject;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @Author XT
|
|
||||||
* @Date 2024.09.03
|
|
||||||
*/
|
|
||||||
@Inject("${captcha}")
|
|
||||||
@Configuration
|
|
||||||
public class CaptchaProperties {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* redis 前缀
|
|
||||||
*/
|
|
||||||
private String prefix;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 有效期
|
|
||||||
*/
|
|
||||||
private Long expire;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 字体路径
|
|
||||||
*/
|
|
||||||
private List<String> fontPath;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 资源路径
|
|
||||||
*/
|
|
||||||
private CaptchaResource resources;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 二次验证
|
|
||||||
*/
|
|
||||||
private CaptchaSecondary secondary;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 每分限流
|
|
||||||
*/
|
|
||||||
private CaptchaLimit limit;
|
|
||||||
|
|
||||||
public String getPrefix() {
|
|
||||||
return prefix;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPrefix(String prefix) {
|
|
||||||
this.prefix = prefix;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getExpire() {
|
|
||||||
return expire;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExpire(Long expire) {
|
|
||||||
this.expire = expire;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<String> getFontPath() {
|
|
||||||
return fontPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setFontPath(List<String> fontPath) {
|
|
||||||
this.fontPath = fontPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
public CaptchaResource getResources() {
|
|
||||||
return resources;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setResources(CaptchaResource resources) {
|
|
||||||
this.resources = resources;
|
|
||||||
}
|
|
||||||
|
|
||||||
public CaptchaSecondary getSecondary() {
|
|
||||||
return secondary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSecondary(CaptchaSecondary secondary) {
|
|
||||||
this.secondary = secondary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public CaptchaLimit getLimit() {
|
|
||||||
return limit;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setLimit(CaptchaLimit limit) {
|
|
||||||
this.limit = limit;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-80
@@ -1,80 +0,0 @@
|
|||||||
package cloud.tianai.captcha.solon.properties;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @Author XT
|
|
||||||
* @Date 2024.09.03
|
|
||||||
*/
|
|
||||||
public class CaptchaResource {
|
|
||||||
|
|
||||||
private Boolean auto;
|
|
||||||
|
|
||||||
private String autoType;
|
|
||||||
|
|
||||||
private List<String> images;
|
|
||||||
|
|
||||||
private List<String> SLIDER;
|
|
||||||
|
|
||||||
private List<String> WORD_IMAGE_CLICK;
|
|
||||||
|
|
||||||
private List<String> ROTATE;
|
|
||||||
|
|
||||||
private List<String> CONCAT;
|
|
||||||
|
|
||||||
public List<String> getSLIDER() {
|
|
||||||
return SLIDER;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSLIDER(List<String> SLIDER) {
|
|
||||||
this.SLIDER = SLIDER;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<String> getWORD_IMAGE_CLICK() {
|
|
||||||
return WORD_IMAGE_CLICK;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setWORD_IMAGE_CLICK(List<String> WORD_IMAGE_CLICK) {
|
|
||||||
this.WORD_IMAGE_CLICK = WORD_IMAGE_CLICK;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<String> getROTATE() {
|
|
||||||
return ROTATE;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setROTATE(List<String> ROTATE) {
|
|
||||||
this.ROTATE = ROTATE;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<String> getCONCAT() {
|
|
||||||
return CONCAT;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCONCAT(List<String> CONCAT) {
|
|
||||||
this.CONCAT = CONCAT;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getAuto() {
|
|
||||||
return auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAuto(Boolean auto) {
|
|
||||||
this.auto = auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAutoType() {
|
|
||||||
return autoType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAutoType(String autoType) {
|
|
||||||
this.autoType = autoType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<String> getImages() {
|
|
||||||
return images;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setImages(List<String> images) {
|
|
||||||
this.images = images;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-38
@@ -1,38 +0,0 @@
|
|||||||
package cloud.tianai.captcha.solon.properties;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @Author XT
|
|
||||||
* @Date 2024.09.03
|
|
||||||
*/
|
|
||||||
public class CaptchaSecondary {
|
|
||||||
|
|
||||||
private Boolean enabled;
|
|
||||||
|
|
||||||
private Long expire;
|
|
||||||
|
|
||||||
private String keyPrefix;
|
|
||||||
|
|
||||||
public Boolean getEnabled() {
|
|
||||||
return enabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setEnabled(Boolean enabled) {
|
|
||||||
this.enabled = enabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getExpire() {
|
|
||||||
return expire;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExpire(Long expire) {
|
|
||||||
this.expire = expire;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getKeyPrefix() {
|
|
||||||
return keyPrefix;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setKeyPrefix(String keyPrefix) {
|
|
||||||
this.keyPrefix = keyPrefix;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-7
@@ -1,7 +0,0 @@
|
|||||||
package cloud.tianai.captcha.solon.service;
|
|
||||||
|
|
||||||
import cloud.tianai.captcha.cache.CacheStore;
|
|
||||||
|
|
||||||
public interface CaptchaRedisCacheService extends CacheStore {
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-dependencies</artifactId>
|
<artifactId>spring-boot-dependencies</artifactId>
|
||||||
<version>2.2.7.RELEASE</version>
|
<version>${spring-boot.version}</version>
|
||||||
<type>pom</type>
|
<type>pom</type>
|
||||||
<scope>import</scope>
|
<scope>import</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
@@ -25,9 +25,7 @@
|
|||||||
</dependencyManagement>
|
</dependencyManagement>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<java.version>1.8</java.version>
|
<java.version>21</java.version>
|
||||||
<commons-lang3.version>3.7</commons-lang3.version>
|
|
||||||
<!-- 打包跳过单元测试 -->
|
|
||||||
<skipTests>true</skipTests>
|
<skipTests>true</skipTests>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||||
@@ -43,7 +41,6 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-lang3</artifactId>
|
<artifactId>commons-lang3</artifactId>
|
||||||
<version>${commons-lang3.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.code.gson</groupId>
|
<groupId>com.google.code.gson</groupId>
|
||||||
@@ -65,18 +62,14 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
<optional>true</optional>
|
<version>${lombok.version}</version>
|
||||||
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>cloud.tianai.captcha</groupId>
|
<groupId>cloud.tianai.captcha</groupId>
|
||||||
<artifactId>tianai-captcha</artifactId>
|
<artifactId>tianai-captcha</artifactId>
|
||||||
<version>${revision}</version>
|
<version>${revision}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- <dependency>-->
|
|
||||||
<!-- <groupId>jakarta.validation</groupId>-->
|
|
||||||
<!-- <artifactId>jakarta.validation-api</artifactId>-->
|
|
||||||
<!-- </dependency>-->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
@@ -87,20 +80,22 @@
|
|||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.14.0</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>8</source>
|
<release>21</release>
|
||||||
<target>8</target>
|
|
||||||
<compilerArgument>-parameters</compilerArgument>
|
<compilerArgument>-parameters</compilerArgument>
|
||||||
|
<annotationProcessorPaths>
|
||||||
|
<path>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>${lombok.version}</version>
|
||||||
|
</path>
|
||||||
|
</annotationProcessorPaths>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
</project>
|
</project>
|
||||||
+18
-2
@@ -2,6 +2,9 @@ package cloud.tianai.captcha.spring.autoconfiguration;
|
|||||||
|
|
||||||
import cloud.tianai.captcha.cache.CacheStore;
|
import cloud.tianai.captcha.cache.CacheStore;
|
||||||
import cloud.tianai.captcha.cache.impl.LocalCacheStore;
|
import cloud.tianai.captcha.cache.impl.LocalCacheStore;
|
||||||
|
import cloud.tianai.captcha.resource.ResourceStore;
|
||||||
|
import cloud.tianai.captcha.resource.impl.LocalMemoryResourceStore;
|
||||||
|
import cloud.tianai.captcha.spring.plugins.RedisResourceStore;
|
||||||
import cloud.tianai.captcha.spring.store.impl.RedisCacheStore;
|
import cloud.tianai.captcha.spring.store.impl.RedisCacheStore;
|
||||||
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||||
@@ -33,13 +36,20 @@ public class CacheStoreAutoConfiguration {
|
|||||||
@ConditionalOnClass(StringRedisTemplate.class)
|
@ConditionalOnClass(StringRedisTemplate.class)
|
||||||
public static class RedisCacheStoreConfiguration {
|
public static class RedisCacheStoreConfiguration {
|
||||||
|
|
||||||
@Bean
|
@Bean(destroyMethod = "close")
|
||||||
@ConditionalOnBean(StringRedisTemplate.class)
|
@ConditionalOnBean(StringRedisTemplate.class)
|
||||||
@ConditionalOnMissingBean(CacheStore.class)
|
@ConditionalOnMissingBean(CacheStore.class)
|
||||||
public CacheStore redis(StringRedisTemplate redisTemplate) {
|
public CacheStore redis(StringRedisTemplate redisTemplate) {
|
||||||
return new RedisCacheStore(redisTemplate);
|
return new RedisCacheStore(redisTemplate);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnBean(StringRedisTemplate.class)
|
||||||
|
@ConditionalOnMissingBean(ResourceStore.class)
|
||||||
|
public ResourceStore redisResourceStore(StringRedisTemplate redisTemplate) {
|
||||||
|
return new RedisResourceStore(redisTemplate);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -52,12 +62,18 @@ public class CacheStoreAutoConfiguration {
|
|||||||
@Configuration(proxyBeanMethods = false)
|
@Configuration(proxyBeanMethods = false)
|
||||||
public static class LocalCacheStoreConfiguration {
|
public static class LocalCacheStoreConfiguration {
|
||||||
|
|
||||||
@Bean
|
@Bean(destroyMethod = "close")
|
||||||
@ConditionalOnMissingBean(CacheStore.class)
|
@ConditionalOnMissingBean(CacheStore.class)
|
||||||
public CacheStore local() {
|
public CacheStore local() {
|
||||||
return new LocalCacheStore();
|
return new LocalCacheStore();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean(ResourceStore.class)
|
||||||
|
public ResourceStore resourceStore() {
|
||||||
|
return new LocalMemoryResourceStore();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
+20
-23
@@ -4,33 +4,31 @@ package cloud.tianai.captcha.spring.autoconfiguration;
|
|||||||
import cloud.tianai.captcha.application.ImageCaptchaApplication;
|
import cloud.tianai.captcha.application.ImageCaptchaApplication;
|
||||||
import cloud.tianai.captcha.application.TACBuilder;
|
import cloud.tianai.captcha.application.TACBuilder;
|
||||||
import cloud.tianai.captcha.cache.CacheStore;
|
import cloud.tianai.captcha.cache.CacheStore;
|
||||||
import cloud.tianai.captcha.common.util.CollectionUtils;
|
|
||||||
import cloud.tianai.captcha.generator.ImageCaptchaGenerator;
|
import cloud.tianai.captcha.generator.ImageCaptchaGenerator;
|
||||||
import cloud.tianai.captcha.generator.ImageTransform;
|
import cloud.tianai.captcha.generator.ImageTransform;
|
||||||
import cloud.tianai.captcha.generator.impl.transform.Base64ImageTransform;
|
import cloud.tianai.captcha.generator.impl.transform.Base64ImageTransform;
|
||||||
import cloud.tianai.captcha.interceptor.CaptchaInterceptor;
|
import cloud.tianai.captcha.interceptor.CaptchaInterceptor;
|
||||||
import cloud.tianai.captcha.interceptor.CaptchaInterceptorGroup;
|
import cloud.tianai.captcha.interceptor.EmptyCaptchaInterceptor;
|
||||||
import cloud.tianai.captcha.interceptor.impl.ParamCheckCaptchaInterceptor;
|
|
||||||
import cloud.tianai.captcha.resource.ImageCaptchaResourceManager;
|
import cloud.tianai.captcha.resource.ImageCaptchaResourceManager;
|
||||||
import cloud.tianai.captcha.resource.ResourceProviders;
|
import cloud.tianai.captcha.resource.ResourceProviders;
|
||||||
import cloud.tianai.captcha.resource.ResourceStore;
|
import cloud.tianai.captcha.resource.ResourceStore;
|
||||||
import cloud.tianai.captcha.resource.impl.DefaultImageCaptchaResourceManager;
|
import cloud.tianai.captcha.resource.impl.DefaultImageCaptchaResourceManager;
|
||||||
import cloud.tianai.captcha.resource.impl.LocalMemoryResourceStore;
|
import cloud.tianai.captcha.spring.common.util.URL;
|
||||||
import cloud.tianai.captcha.spring.plugins.SpringMultiImageCaptchaGenerator;
|
import cloud.tianai.captcha.spring.plugins.SpringMultiImageCaptchaGenerator;
|
||||||
import cloud.tianai.captcha.spring.plugins.secondary.SecondaryVerificationApplication;
|
import cloud.tianai.captcha.spring.plugins.secondary.SecondaryVerificationApplication;
|
||||||
import cloud.tianai.captcha.validator.ImageCaptchaValidator;
|
import cloud.tianai.captcha.validator.ImageCaptchaValidator;
|
||||||
import cloud.tianai.captcha.validator.impl.SimpleImageCaptchaValidator;
|
import cloud.tianai.captcha.validator.impl.SimpleImageCaptchaValidator;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.beans.factory.BeanFactory;
|
import org.springframework.beans.factory.BeanFactory;
|
||||||
import org.springframework.beans.factory.config.BeanDefinition;
|
|
||||||
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
import org.springframework.context.ApplicationContext;
|
import org.springframework.context.ApplicationContext;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.context.annotation.Role;
|
|
||||||
import org.springframework.core.annotation.Order;
|
import org.springframework.core.annotation.Order;
|
||||||
|
import org.springframework.util.CollectionUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @Author: 天爱有情
|
* @Author: 天爱有情
|
||||||
@@ -44,17 +42,13 @@ import org.springframework.core.annotation.Order;
|
|||||||
@EnableConfigurationProperties({SpringImageCaptchaProperties.class})
|
@EnableConfigurationProperties({SpringImageCaptchaProperties.class})
|
||||||
public class ImageCaptchaAutoConfiguration {
|
public class ImageCaptchaAutoConfiguration {
|
||||||
|
|
||||||
@Bean
|
|
||||||
@ConditionalOnMissingBean
|
|
||||||
public ResourceStore resourceStore() {
|
|
||||||
return new LocalMemoryResourceStore();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
|
@ConditionalOnBean(ResourceStore.class)
|
||||||
public ImageCaptchaResourceManager imageCaptchaResourceManager(ResourceStore resourceStore) {
|
public ImageCaptchaResourceManager imageCaptchaResourceManager(ResourceStore resourceStore) {
|
||||||
ResourceProviders resourceProviders = new ResourceProviders();
|
ResourceProviders resourceProviders = new ResourceProviders();
|
||||||
return new DefaultImageCaptchaResourceManager(resourceStore,resourceProviders);
|
return new DefaultImageCaptchaResourceManager(resourceStore, resourceProviders);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@@ -70,7 +64,9 @@ public class ImageCaptchaAutoConfiguration {
|
|||||||
ImageCaptchaResourceManager captchaResourceManager,
|
ImageCaptchaResourceManager captchaResourceManager,
|
||||||
ImageTransform imageTransform,
|
ImageTransform imageTransform,
|
||||||
BeanFactory beanFactory) {
|
BeanFactory beanFactory) {
|
||||||
return new SpringMultiImageCaptchaGenerator(captchaResourceManager, imageTransform, beanFactory);
|
// 构建多验证码生成器
|
||||||
|
ImageCaptchaGenerator captchaGenerator = new SpringMultiImageCaptchaGenerator(captchaResourceManager, imageTransform, beanFactory);
|
||||||
|
return captchaGenerator;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@@ -80,26 +76,24 @@ public class ImageCaptchaAutoConfiguration {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
public CaptchaInterceptor captchaInterceptor() {
|
public CaptchaInterceptor captchaInterceptor() {
|
||||||
CaptchaInterceptorGroup group = new CaptchaInterceptorGroup();
|
return new EmptyCaptchaInterceptor();
|
||||||
group.addInterceptor(new ParamCheckCaptchaInterceptor());
|
|
||||||
// group.addInterceptor(new BasicTrackCaptchaInterceptor());
|
|
||||||
return group;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Bean(destroyMethod = "close")
|
||||||
@Bean
|
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
|
@ConditionalOnBean(CacheStore.class)
|
||||||
public ImageCaptchaApplication imageCaptchaApplication(ImageCaptchaGenerator captchaGenerator,
|
public ImageCaptchaApplication imageCaptchaApplication(ImageCaptchaGenerator captchaGenerator,
|
||||||
ImageCaptchaValidator imageCaptchaValidator,
|
ImageCaptchaValidator imageCaptchaValidator,
|
||||||
CacheStore cacheStore,
|
CacheStore cacheStore,
|
||||||
ResourceStore resourceStore,
|
ResourceStore resourceStore,
|
||||||
SpringImageCaptchaProperties prop,
|
SpringImageCaptchaProperties prop,
|
||||||
CaptchaInterceptor captchaInterceptor,
|
CaptchaInterceptor captchaInterceptor,
|
||||||
ApplicationContext applicationContext) {
|
ApplicationContext applicationContext
|
||||||
TACBuilder tacBuilder = TACBuilder.builder(resourceStore)
|
) {
|
||||||
|
TACBuilder tacBuilder = TACBuilder.builder()
|
||||||
|
.setResourceStore(resourceStore)
|
||||||
.setGenerator(captchaGenerator)
|
.setGenerator(captchaGenerator)
|
||||||
.setValidator(imageCaptchaValidator)
|
.setValidator(imageCaptchaValidator)
|
||||||
.setCacheStore(cacheStore)
|
.setCacheStore(cacheStore)
|
||||||
@@ -116,7 +110,10 @@ public class ImageCaptchaAutoConfiguration {
|
|||||||
String[] split = index > 0 ? new String[]{fontPath.substring(0, index), fontPath.substring(index + 1)} : new String[]{"", fontPath};
|
String[] split = index > 0 ? new String[]{fontPath.substring(0, index), fontPath.substring(index + 1)} : new String[]{"", fontPath};
|
||||||
String type = split[0];
|
String type = split[0];
|
||||||
String path = split[1];
|
String path = split[1];
|
||||||
tacBuilder.addFont(new cloud.tianai.captcha.resource.common.model.dto.Resource(type, path));
|
|
||||||
|
URL fontUrl = URL.valueOf(fontPath);
|
||||||
|
String tag = fontUrl.getParam(URL.PARAM_TAG_KEY, null);
|
||||||
|
tacBuilder.addFont(new cloud.tianai.captcha.resource.common.model.dto.Resource(type, path, tag));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ImageCaptchaApplication target = tacBuilder.build();
|
ImageCaptchaApplication target = tacBuilder.build();
|
||||||
|
|||||||
+59
@@ -0,0 +1,59 @@
|
|||||||
|
package cloud.tianai.captcha.spring.common.util;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class URL {
|
||||||
|
|
||||||
|
public static final String PARAM_TAG_KEY = "tag";
|
||||||
|
|
||||||
|
private String protocol;
|
||||||
|
private String path;
|
||||||
|
private Map<String, String> params;
|
||||||
|
|
||||||
|
public String getParam(String key, String defaultValue) {
|
||||||
|
return params.getOrDefault(key, defaultValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static URL valueOf(String input) {
|
||||||
|
// 分割协议和剩余部分
|
||||||
|
String[] parts = input.split(":", 2);
|
||||||
|
String protocol = parts[0];
|
||||||
|
String remaining = parts[1];
|
||||||
|
|
||||||
|
// 分割路径和查询参数
|
||||||
|
String path;
|
||||||
|
String query = null;
|
||||||
|
|
||||||
|
if (remaining.contains("?")) {
|
||||||
|
String[] pathQuerySplit = remaining.split("\\?", 2);
|
||||||
|
path = pathQuerySplit[0];
|
||||||
|
query = pathQuerySplit[1];
|
||||||
|
} else {
|
||||||
|
path = remaining;
|
||||||
|
}
|
||||||
|
if (path.startsWith("//")) {
|
||||||
|
path = path.substring(2);
|
||||||
|
}
|
||||||
|
// 处理查询参数,提取键值对
|
||||||
|
Map<String, String> queryParams = new HashMap<>();
|
||||||
|
if (query != null) {
|
||||||
|
for (String param : query.split("&")) {
|
||||||
|
String[] keyValue = param.split("=", 2);
|
||||||
|
String key = keyValue[0];
|
||||||
|
String value = keyValue.length > 1 ? keyValue[1] : "";
|
||||||
|
queryParams.put(key, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new URL(protocol, path, queryParams);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
-41
@@ -1,41 +0,0 @@
|
|||||||
package cloud.tianai.captcha.spring.exception;
|
|
||||||
|
|
||||||
import cloud.tianai.captcha.common.exception.ImageCaptchaException;
|
|
||||||
import lombok.Getter;
|
|
||||||
import lombok.Setter;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @Author: 天爱有情
|
|
||||||
* @Date 2020/6/19 16:36
|
|
||||||
* @Description 验证码验证失败异常
|
|
||||||
*/
|
|
||||||
@Getter
|
|
||||||
@Setter
|
|
||||||
public class CaptchaValidException extends ImageCaptchaException {
|
|
||||||
|
|
||||||
private String captchaType;
|
|
||||||
private Integer code;
|
|
||||||
public CaptchaValidException() {
|
|
||||||
}
|
|
||||||
|
|
||||||
public CaptchaValidException(String captchaType,String message) {
|
|
||||||
super(message);
|
|
||||||
this.captchaType = captchaType;
|
|
||||||
}
|
|
||||||
public CaptchaValidException(String captchaType,Integer code, String message) {
|
|
||||||
super(message);
|
|
||||||
this.code = code;
|
|
||||||
this.captchaType = captchaType;
|
|
||||||
}
|
|
||||||
public CaptchaValidException(String message, Throwable cause) {
|
|
||||||
super(message, cause);
|
|
||||||
}
|
|
||||||
|
|
||||||
public CaptchaValidException(Throwable cause) {
|
|
||||||
super(cause);
|
|
||||||
}
|
|
||||||
|
|
||||||
public CaptchaValidException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
|
|
||||||
super(message, cause, enableSuppression, writableStackTrace);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+286
@@ -0,0 +1,286 @@
|
|||||||
|
package cloud.tianai.captcha.spring.plugins;
|
||||||
|
|
||||||
|
import cloud.tianai.captcha.common.constant.CommonConstant;
|
||||||
|
import cloud.tianai.captcha.common.util.CollectionUtils;
|
||||||
|
import cloud.tianai.captcha.resource.CrudResourceStore;
|
||||||
|
import cloud.tianai.captcha.resource.ImageCaptchaResourceManager;
|
||||||
|
import cloud.tianai.captcha.resource.common.model.dto.Resource;
|
||||||
|
import cloud.tianai.captcha.resource.common.model.dto.ResourceMap;
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @Author: 天爱有情
|
||||||
|
* @date 2023/8/23 10:52
|
||||||
|
* @Description 基于redis的store
|
||||||
|
*/
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class RedisResourceStore implements CrudResourceStore {
|
||||||
|
|
||||||
|
|
||||||
|
private final StringRedisTemplate redisTemplate;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
private String resourcePrefix = "captcha:config:resource:";
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
private String templatePrefix = "captcha:config:template:";
|
||||||
|
private Gson gson = new Gson();
|
||||||
|
|
||||||
|
public String joinResourceKey(String type, String tag) {
|
||||||
|
if (tag == null) {
|
||||||
|
tag = CommonConstant.DEFAULT_TAG;
|
||||||
|
}
|
||||||
|
type = type.toUpperCase();
|
||||||
|
return resourcePrefix + tag + ":" + type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String joinTemplateKey(String type, String tag) {
|
||||||
|
if (tag == null) {
|
||||||
|
tag = CommonConstant.DEFAULT_TAG;
|
||||||
|
}
|
||||||
|
type = type.toUpperCase();
|
||||||
|
return templatePrefix + tag + ":" + type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Resource> getResources(String type, String tag) {
|
||||||
|
String key = joinResourceKey(type, tag);
|
||||||
|
Long size = redisTemplate.opsForList().size(key);
|
||||||
|
if (size == null || size < 1) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
List<String> range = redisTemplate.opsForList().range(key, 0, size);
|
||||||
|
List<Resource> result = new ArrayList<>(range.size());
|
||||||
|
for (String json : range) {
|
||||||
|
result.add(gson.fromJson(json, Resource.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<ResourceMap> getTemplates(String type, String tag) {
|
||||||
|
String key = joinTemplateKey(type, tag);
|
||||||
|
Long size = redisTemplate.opsForList().size(key);
|
||||||
|
if (size == null || size < 1) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
List<String> range = redisTemplate.opsForList().range(key, 0, size);
|
||||||
|
List<ResourceMap> result = new ArrayList<>(range.size());
|
||||||
|
for (String json : range) {
|
||||||
|
result.add(gson.fromJson(json, ResourceMap.class));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public void setResources(String type, String tag, List<Resource> resources) {
|
||||||
|
String key = joinResourceKey(type, tag);
|
||||||
|
Long size = redisTemplate.opsForList().size(key);
|
||||||
|
if (size != null && size > 0) {
|
||||||
|
redisTemplate.delete(key);
|
||||||
|
}
|
||||||
|
for (Resource resource : resources) {
|
||||||
|
addResource(type, resource);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTemplates(String type, String tag, List<ResourceMap> templates) {
|
||||||
|
String key = joinTemplateKey(type, tag);
|
||||||
|
Long size = redisTemplate.opsForList().size(key);
|
||||||
|
if (size != null && size > 0) {
|
||||||
|
redisTemplate.delete(key);
|
||||||
|
}
|
||||||
|
for (ResourceMap template : templates) {
|
||||||
|
addTemplate(type, template);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addResource(String type, Resource resource) {
|
||||||
|
// 添加tag标签字典
|
||||||
|
redisTemplate.opsForList().rightPush(joinResourceKey(type, resource.getTag()), gson.toJson(resource));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addTemplate(String type, ResourceMap template) {
|
||||||
|
// 添加tag标签字典
|
||||||
|
redisTemplate.opsForList().rightPush(joinTemplateKey(type, template.getTag()), gson.toJson(template));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Resource deleteResource(String type, String id) {
|
||||||
|
Set<String> keys = redisTemplate.keys(joinResourceKey(type, "*"));
|
||||||
|
if (!CollectionUtils.isEmpty(keys)) {
|
||||||
|
for (String key : keys) {
|
||||||
|
Long size = redisTemplate.opsForList().size(key);
|
||||||
|
if (size == null || size < 1) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
List<String> range = redisTemplate.opsForList().range(key, 0, size);
|
||||||
|
if (range != null) {
|
||||||
|
for (String json : range) {
|
||||||
|
Resource resource = gson.fromJson(json, Resource.class);
|
||||||
|
if (resource.getId().equals(id)) {
|
||||||
|
redisTemplate.opsForList().remove(key, 1, json);
|
||||||
|
return resource;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ResourceMap deleteTemplate(String type, String id) {
|
||||||
|
Set<String> keys = redisTemplate.keys(joinTemplateKey(type, "*"));
|
||||||
|
if (!CollectionUtils.isEmpty(keys)) {
|
||||||
|
for (String key : keys) {
|
||||||
|
Long size = redisTemplate.opsForList().size(key);
|
||||||
|
if (size == null || size < 1) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
List<String> range = redisTemplate.opsForList().range(key, 0, size);
|
||||||
|
if (range != null) {
|
||||||
|
for (String json : range) {
|
||||||
|
ResourceMap resourceMap = gson.fromJson(json, ResourceMap.class);
|
||||||
|
if (resourceMap.getId().equals(id)) {
|
||||||
|
redisTemplate.opsForList().remove(key, 1, json);
|
||||||
|
return resourceMap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Resource> listResourcesByTypeAndTag(String type, String tag) {
|
||||||
|
if (StringUtils.isNotBlank(tag)) {
|
||||||
|
return getResources(type, tag);
|
||||||
|
}
|
||||||
|
Set<String> keys = redisTemplate.keys(joinResourceKey(type, "*"));
|
||||||
|
if (!CollectionUtils.isEmpty(keys)) {
|
||||||
|
List<Resource> resources = new ArrayList<>();
|
||||||
|
for (String key : keys) {
|
||||||
|
Long size1 = redisTemplate.opsForList().size(key);
|
||||||
|
if (size1 == null || size1 < 1) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
List<String> range = redisTemplate.opsForList().range(key, 0, size1);
|
||||||
|
if (range != null) {
|
||||||
|
for (String json : range) {
|
||||||
|
Resource resource = gson.fromJson(json, Resource.class);
|
||||||
|
resources.add(resource);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return resources;
|
||||||
|
}
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<ResourceMap> listTemplatesByTypeAndTag(String type, String tag) {
|
||||||
|
if (StringUtils.isNotBlank(tag)) {
|
||||||
|
return getTemplates(type, tag);
|
||||||
|
}
|
||||||
|
Set<String> keys = redisTemplate.keys(joinTemplateKey(type, "*"));
|
||||||
|
if (!CollectionUtils.isEmpty(keys)) {
|
||||||
|
List<ResourceMap> templates = new ArrayList<>();
|
||||||
|
for (String key : keys) {
|
||||||
|
Long size1 = redisTemplate.opsForList().size(key);
|
||||||
|
if (size1 == null || size1 < 1) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
List<String> range = redisTemplate.opsForList().range(key, 0, size1);
|
||||||
|
if (range != null) {
|
||||||
|
for (String json : range) {
|
||||||
|
ResourceMap template = gson.fromJson(json, ResourceMap.class);
|
||||||
|
templates.add(template);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return templates;
|
||||||
|
}
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void init(ImageCaptchaResourceManager resourceManager) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Resource> randomGetResourceByTypeAndTag(String type, String tag, Integer quantity) {
|
||||||
|
String key = joinResourceKey(type, tag);
|
||||||
|
Long size = redisTemplate.opsForList().size(key);
|
||||||
|
if (size == null || quantity > size) {
|
||||||
|
throw new IllegalArgumentException("请求的资源数量超过可用资源总数");
|
||||||
|
}
|
||||||
|
|
||||||
|
Set<Long> indexes = new HashSet<>(quantity);
|
||||||
|
while (indexes.size() < quantity) {
|
||||||
|
indexes.add(ThreadLocalRandom.current().nextLong(size));
|
||||||
|
}
|
||||||
|
List<Resource> result = new ArrayList<>(quantity);
|
||||||
|
for (Long index : indexes) {
|
||||||
|
String resourceJson = redisTemplate.opsForList().index(key, index);
|
||||||
|
result.add(gson.fromJson(resourceJson, Resource.class));
|
||||||
|
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<ResourceMap> randomGetTemplateByTypeAndTag(String type, String tag, Integer quantity) {
|
||||||
|
String key = joinTemplateKey(type, tag);
|
||||||
|
Long size = redisTemplate.opsForList().size(key);
|
||||||
|
if (size == null || size < 1) {
|
||||||
|
throw new IllegalStateException("随机获取模板错误,store中模板为空, type:" + type);
|
||||||
|
}
|
||||||
|
if (quantity > size) {
|
||||||
|
throw new IllegalArgumentException("请求的模板数量超过可用模板总数");
|
||||||
|
}
|
||||||
|
|
||||||
|
Set<Long> indexes = new HashSet<>(quantity);
|
||||||
|
while (indexes.size() < quantity) {
|
||||||
|
indexes.add(ThreadLocalRandom.current().nextLong(size));
|
||||||
|
}
|
||||||
|
|
||||||
|
List<ResourceMap> result = new ArrayList<>(quantity);
|
||||||
|
|
||||||
|
for (Long index : indexes) {
|
||||||
|
String resourceJson = redisTemplate.opsForList().index(key, index);
|
||||||
|
result.add(gson.fromJson(resourceJson, ResourceMap.class));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void clearAllTemplates() {
|
||||||
|
Set<String> keys = redisTemplate.keys(templatePrefix + "*");
|
||||||
|
if (!CollectionUtils.isEmpty(keys)) {
|
||||||
|
redisTemplate.delete(keys);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void clearAllResources() {
|
||||||
|
Set<String> keys = redisTemplate.keys(resourcePrefix + "*");
|
||||||
|
if (!CollectionUtils.isEmpty(keys)) {
|
||||||
|
redisTemplate.delete(keys);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+5
@@ -68,4 +68,9 @@ public class RedisCacheStore implements CacheStore {
|
|||||||
}
|
}
|
||||||
return Long.valueOf(value);
|
return Long.valueOf(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() throws Exception {
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Generated
+513
-36
@@ -8,6 +8,9 @@
|
|||||||
"name": "webpack-demo",
|
"name": "webpack-demo",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"sass": "^1.103.1"
|
||||||
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@babel/core": "^7.22.17",
|
"@babel/core": "^7.22.17",
|
||||||
"@babel/preset-env": "^7.22.15",
|
"@babel/preset-env": "^7.22.15",
|
||||||
@@ -1904,6 +1907,312 @@
|
|||||||
"integrity": "sha512-Hcv+nVC0kZnQ3tD9GVu5xSMR4VVYOteQIr/hwFPVEvPdlXqgGEuRjiheChHgdM+JyqdgNcmzZOX/tnl0JOiI7A==",
|
"integrity": "sha512-Hcv+nVC0kZnQ3tD9GVu5xSMR4VVYOteQIr/hwFPVEvPdlXqgGEuRjiheChHgdM+JyqdgNcmzZOX/tnl0JOiI7A==",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
|
"node_modules/@parcel/watcher": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher/-/watcher-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==",
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"detect-libc": "^2.0.3",
|
||||||
|
"is-glob": "^4.0.3",
|
||||||
|
"node-addon-api": "^7.0.0",
|
||||||
|
"picomatch": "^4.0.4"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/parcel"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@parcel/watcher-android-arm64": "2.6.0",
|
||||||
|
"@parcel/watcher-darwin-arm64": "2.6.0",
|
||||||
|
"@parcel/watcher-darwin-x64": "2.6.0",
|
||||||
|
"@parcel/watcher-freebsd-x64": "2.6.0",
|
||||||
|
"@parcel/watcher-linux-arm-glibc": "2.6.0",
|
||||||
|
"@parcel/watcher-linux-arm-musl": "2.6.0",
|
||||||
|
"@parcel/watcher-linux-arm64-glibc": "2.6.0",
|
||||||
|
"@parcel/watcher-linux-arm64-musl": "2.6.0",
|
||||||
|
"@parcel/watcher-linux-x64-glibc": "2.6.0",
|
||||||
|
"@parcel/watcher-linux-x64-musl": "2.6.0",
|
||||||
|
"@parcel/watcher-win32-arm64": "2.6.0",
|
||||||
|
"@parcel/watcher-win32-x64": "2.6.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@parcel/watcher-android-arm64": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"android"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/parcel"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@parcel/watcher-darwin-arm64": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/parcel"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@parcel/watcher-darwin-x64": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/parcel"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@parcel/watcher-freebsd-x64": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"freebsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/parcel"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@parcel/watcher-linux-arm-glibc": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"libc": [
|
||||||
|
"glibc"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/parcel"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@parcel/watcher-linux-arm-musl": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"libc": [
|
||||||
|
"musl"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/parcel"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@parcel/watcher-linux-arm64-glibc": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"libc": [
|
||||||
|
"glibc"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/parcel"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@parcel/watcher-linux-arm64-musl": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"libc": [
|
||||||
|
"musl"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/parcel"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@parcel/watcher-linux-x64-glibc": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"libc": [
|
||||||
|
"glibc"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/parcel"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@parcel/watcher-linux-x64-musl": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"libc": [
|
||||||
|
"musl"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/parcel"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@parcel/watcher-win32-arm64": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/parcel"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@parcel/watcher-win32-x64": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/parcel"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@parcel/watcher/node_modules/picomatch": {
|
||||||
|
"version": "4.0.5",
|
||||||
|
"resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.5.tgz",
|
||||||
|
"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/jonschlinkert"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@polka/url": {
|
"node_modules/@polka/url": {
|
||||||
"version": "1.0.0-next.23",
|
"version": "1.0.0-next.23",
|
||||||
"resolved": "https://registry.npmmirror.com/@polka/url/-/url-1.0.0-next.23.tgz",
|
"resolved": "https://registry.npmmirror.com/@polka/url/-/url-1.0.0-next.23.tgz",
|
||||||
@@ -3284,6 +3593,16 @@
|
|||||||
"npm": "1.2.8000 || >= 1.4.16"
|
"npm": "1.2.8000 || >= 1.4.16"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/detect-libc": {
|
||||||
|
"version": "2.1.2",
|
||||||
|
"resolved": "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.1.2.tgz",
|
||||||
|
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/detect-node": {
|
"node_modules/detect-node": {
|
||||||
"version": "2.1.0",
|
"version": "2.1.0",
|
||||||
"resolved": "https://registry.npmmirror.com/detect-node/-/detect-node-2.1.0.tgz",
|
"resolved": "https://registry.npmmirror.com/detect-node/-/detect-node-2.1.0.tgz",
|
||||||
@@ -4300,12 +4619,10 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/immutable": {
|
"node_modules/immutable": {
|
||||||
"version": "4.3.6",
|
"version": "5.1.9",
|
||||||
"resolved": "https://registry.npmmirror.com/immutable/-/immutable-4.3.6.tgz",
|
"resolved": "https://registry.npmmirror.com/immutable/-/immutable-5.1.9.tgz",
|
||||||
"integrity": "sha512-Ju0+lEMyzMVZarkTn/gqRpdqd5dOPaz1mCZ0SH3JV6iFw81PldE/PEB1hWVEA288HPt4WXW8O7AWxB10M+03QQ==",
|
"integrity": "sha512-m8nVez3rwrgmWxtLMt1ZYXB2Lv7OKYn/disyxAlSDYAlKSlFoPPfIAmAM/M5xqL4m4C/wAPw7S2/CNaUii1Hxg==",
|
||||||
"dev": true,
|
"license": "MIT"
|
||||||
"optional": true,
|
|
||||||
"peer": true
|
|
||||||
},
|
},
|
||||||
"node_modules/import-local": {
|
"node_modules/import-local": {
|
||||||
"version": "3.1.0",
|
"version": "3.1.0",
|
||||||
@@ -4428,7 +4745,7 @@
|
|||||||
"version": "2.1.1",
|
"version": "2.1.1",
|
||||||
"resolved": "https://registry.npmmirror.com/is-extglob/-/is-extglob-2.1.1.tgz",
|
"resolved": "https://registry.npmmirror.com/is-extglob/-/is-extglob-2.1.1.tgz",
|
||||||
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
|
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
|
||||||
"dev": true,
|
"devOptional": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
@@ -4449,7 +4766,7 @@
|
|||||||
"version": "4.0.3",
|
"version": "4.0.3",
|
||||||
"resolved": "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.3.tgz",
|
"resolved": "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.3.tgz",
|
||||||
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
|
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
|
||||||
"dev": true,
|
"devOptional": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"is-extglob": "^2.1.1"
|
"is-extglob": "^2.1.1"
|
||||||
},
|
},
|
||||||
@@ -5224,6 +5541,13 @@
|
|||||||
"tslib": "^2.0.3"
|
"tslib": "^2.0.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/node-addon-api": {
|
||||||
|
"version": "7.1.1",
|
||||||
|
"resolved": "https://registry.npmmirror.com/node-addon-api/-/node-addon-api-7.1.1.tgz",
|
||||||
|
"integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
"node_modules/node-forge": {
|
"node_modules/node-forge": {
|
||||||
"version": "1.3.1",
|
"version": "1.3.1",
|
||||||
"resolved": "https://registry.npmmirror.com/node-forge/-/node-forge-1.3.1.tgz",
|
"resolved": "https://registry.npmmirror.com/node-forge/-/node-forge-1.3.1.tgz",
|
||||||
@@ -6021,22 +6345,23 @@
|
|||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"node_modules/sass": {
|
"node_modules/sass": {
|
||||||
"version": "1.77.4",
|
"version": "1.103.1",
|
||||||
"resolved": "https://registry.npmmirror.com/sass/-/sass-1.77.4.tgz",
|
"resolved": "https://registry.npmmirror.com/sass/-/sass-1.103.1.tgz",
|
||||||
"integrity": "sha512-vcF3Ckow6g939GMA4PeU7b2K/9FALXk2KF9J87txdHzXbUF9XRQRwSxcAs/fGaTnJeBFd7UoV22j3lzMLdM0Pw==",
|
"integrity": "sha512-9icZURbP51S6S0QGoyaeqk9uB06GNWxsFYWfH5RgpFgqK5FA8tJcM3AdVxrZEVJ7dz+L87nG95gBKf4VuaMHGw==",
|
||||||
"dev": true,
|
"license": "MIT",
|
||||||
"optional": true,
|
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"chokidar": ">=3.0.0 <4.0.0",
|
"chokidar": "^5.0.0",
|
||||||
"immutable": "^4.0.0",
|
"immutable": "^5.1.5",
|
||||||
"source-map-js": ">=0.6.2 <2.0.0"
|
"source-map-js": ">=0.6.2 <2.0.0"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"sass": "sass.js"
|
"sass": "sass.js"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=14.0.0"
|
"node": ">=20.19.0"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@parcel/watcher": "^2.4.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/sass-loader": {
|
"node_modules/sass-loader": {
|
||||||
@@ -6072,6 +6397,34 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/sass/node_modules/chokidar": {
|
||||||
|
"version": "5.0.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/chokidar/-/chokidar-5.0.0.tgz",
|
||||||
|
"integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"readdirp": "^5.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 20.19.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://paulmillr.com/funding/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/sass/node_modules/readdirp": {
|
||||||
|
"version": "5.1.1",
|
||||||
|
"resolved": "https://registry.npmmirror.com/readdirp/-/readdirp-5.1.1.tgz",
|
||||||
|
"integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 20.19.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "individual",
|
||||||
|
"url": "https://paulmillr.com/funding/"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/schema-utils": {
|
"node_modules/schema-utils": {
|
||||||
"version": "3.3.0",
|
"version": "3.3.0",
|
||||||
"resolved": "https://registry.npmmirror.com/schema-utils/-/schema-utils-3.3.0.tgz",
|
"resolved": "https://registry.npmmirror.com/schema-utils/-/schema-utils-3.3.0.tgz",
|
||||||
@@ -6336,7 +6689,6 @@
|
|||||||
"version": "1.0.2",
|
"version": "1.0.2",
|
||||||
"resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.0.2.tgz",
|
"resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.0.2.tgz",
|
||||||
"integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==",
|
"integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==",
|
||||||
"dev": true,
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
@@ -8624,6 +8976,110 @@
|
|||||||
"integrity": "sha512-Hcv+nVC0kZnQ3tD9GVu5xSMR4VVYOteQIr/hwFPVEvPdlXqgGEuRjiheChHgdM+JyqdgNcmzZOX/tnl0JOiI7A==",
|
"integrity": "sha512-Hcv+nVC0kZnQ3tD9GVu5xSMR4VVYOteQIr/hwFPVEvPdlXqgGEuRjiheChHgdM+JyqdgNcmzZOX/tnl0JOiI7A==",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
|
"@parcel/watcher": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher/-/watcher-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==",
|
||||||
|
"optional": true,
|
||||||
|
"requires": {
|
||||||
|
"@parcel/watcher-android-arm64": "2.6.0",
|
||||||
|
"@parcel/watcher-darwin-arm64": "2.6.0",
|
||||||
|
"@parcel/watcher-darwin-x64": "2.6.0",
|
||||||
|
"@parcel/watcher-freebsd-x64": "2.6.0",
|
||||||
|
"@parcel/watcher-linux-arm-glibc": "2.6.0",
|
||||||
|
"@parcel/watcher-linux-arm-musl": "2.6.0",
|
||||||
|
"@parcel/watcher-linux-arm64-glibc": "2.6.0",
|
||||||
|
"@parcel/watcher-linux-arm64-musl": "2.6.0",
|
||||||
|
"@parcel/watcher-linux-x64-glibc": "2.6.0",
|
||||||
|
"@parcel/watcher-linux-x64-musl": "2.6.0",
|
||||||
|
"@parcel/watcher-win32-arm64": "2.6.0",
|
||||||
|
"@parcel/watcher-win32-x64": "2.6.0",
|
||||||
|
"detect-libc": "^2.0.3",
|
||||||
|
"is-glob": "^4.0.3",
|
||||||
|
"node-addon-api": "^7.0.0",
|
||||||
|
"picomatch": "^4.0.4"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"picomatch": {
|
||||||
|
"version": "4.0.5",
|
||||||
|
"resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.5.tgz",
|
||||||
|
"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"@parcel/watcher-android-arm64": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA==",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@parcel/watcher-darwin-arm64": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw==",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@parcel/watcher-darwin-x64": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw==",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@parcel/watcher-freebsd-x64": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ==",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@parcel/watcher-linux-arm-glibc": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg==",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@parcel/watcher-linux-arm-musl": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw==",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@parcel/watcher-linux-arm64-glibc": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g==",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@parcel/watcher-linux-arm64-musl": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA==",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@parcel/watcher-linux-x64-glibc": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A==",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@parcel/watcher-linux-x64-musl": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw==",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@parcel/watcher-win32-arm64": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ==",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@parcel/watcher-win32-x64": {
|
||||||
|
"version": "2.6.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.6.0.tgz",
|
||||||
|
"integrity": "sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A==",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
"@polka/url": {
|
"@polka/url": {
|
||||||
"version": "1.0.0-next.23",
|
"version": "1.0.0-next.23",
|
||||||
"resolved": "https://registry.npmmirror.com/@polka/url/-/url-1.0.0-next.23.tgz",
|
"resolved": "https://registry.npmmirror.com/@polka/url/-/url-1.0.0-next.23.tgz",
|
||||||
@@ -9792,6 +10248,12 @@
|
|||||||
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
|
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
|
"detect-libc": {
|
||||||
|
"version": "2.1.2",
|
||||||
|
"resolved": "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.1.2.tgz",
|
||||||
|
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
"detect-node": {
|
"detect-node": {
|
||||||
"version": "2.1.0",
|
"version": "2.1.0",
|
||||||
"resolved": "https://registry.npmmirror.com/detect-node/-/detect-node-2.1.0.tgz",
|
"resolved": "https://registry.npmmirror.com/detect-node/-/detect-node-2.1.0.tgz",
|
||||||
@@ -10608,12 +11070,9 @@
|
|||||||
"requires": {}
|
"requires": {}
|
||||||
},
|
},
|
||||||
"immutable": {
|
"immutable": {
|
||||||
"version": "4.3.6",
|
"version": "5.1.9",
|
||||||
"resolved": "https://registry.npmmirror.com/immutable/-/immutable-4.3.6.tgz",
|
"resolved": "https://registry.npmmirror.com/immutable/-/immutable-5.1.9.tgz",
|
||||||
"integrity": "sha512-Ju0+lEMyzMVZarkTn/gqRpdqd5dOPaz1mCZ0SH3JV6iFw81PldE/PEB1hWVEA288HPt4WXW8O7AWxB10M+03QQ==",
|
"integrity": "sha512-m8nVez3rwrgmWxtLMt1ZYXB2Lv7OKYn/disyxAlSDYAlKSlFoPPfIAmAM/M5xqL4m4C/wAPw7S2/CNaUii1Hxg=="
|
||||||
"dev": true,
|
|
||||||
"optional": true,
|
|
||||||
"peer": true
|
|
||||||
},
|
},
|
||||||
"import-local": {
|
"import-local": {
|
||||||
"version": "3.1.0",
|
"version": "3.1.0",
|
||||||
@@ -10709,7 +11168,7 @@
|
|||||||
"version": "2.1.1",
|
"version": "2.1.1",
|
||||||
"resolved": "https://registry.npmmirror.com/is-extglob/-/is-extglob-2.1.1.tgz",
|
"resolved": "https://registry.npmmirror.com/is-extglob/-/is-extglob-2.1.1.tgz",
|
||||||
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
|
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
|
||||||
"dev": true
|
"devOptional": true
|
||||||
},
|
},
|
||||||
"is-generator-function": {
|
"is-generator-function": {
|
||||||
"version": "1.0.10",
|
"version": "1.0.10",
|
||||||
@@ -10724,7 +11183,7 @@
|
|||||||
"version": "4.0.3",
|
"version": "4.0.3",
|
||||||
"resolved": "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.3.tgz",
|
"resolved": "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.3.tgz",
|
||||||
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
|
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
|
||||||
"dev": true,
|
"devOptional": true,
|
||||||
"requires": {
|
"requires": {
|
||||||
"is-extglob": "^2.1.1"
|
"is-extglob": "^2.1.1"
|
||||||
}
|
}
|
||||||
@@ -11330,6 +11789,12 @@
|
|||||||
"tslib": "^2.0.3"
|
"tslib": "^2.0.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node-addon-api": {
|
||||||
|
"version": "7.1.1",
|
||||||
|
"resolved": "https://registry.npmmirror.com/node-addon-api/-/node-addon-api-7.1.1.tgz",
|
||||||
|
"integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
"node-forge": {
|
"node-forge": {
|
||||||
"version": "1.3.1",
|
"version": "1.3.1",
|
||||||
"resolved": "https://registry.npmmirror.com/node-forge/-/node-forge-1.3.1.tgz",
|
"resolved": "https://registry.npmmirror.com/node-forge/-/node-forge-1.3.1.tgz",
|
||||||
@@ -11954,16 +12419,29 @@
|
|||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"sass": {
|
"sass": {
|
||||||
"version": "1.77.4",
|
"version": "1.103.1",
|
||||||
"resolved": "https://registry.npmmirror.com/sass/-/sass-1.77.4.tgz",
|
"resolved": "https://registry.npmmirror.com/sass/-/sass-1.103.1.tgz",
|
||||||
"integrity": "sha512-vcF3Ckow6g939GMA4PeU7b2K/9FALXk2KF9J87txdHzXbUF9XRQRwSxcAs/fGaTnJeBFd7UoV22j3lzMLdM0Pw==",
|
"integrity": "sha512-9icZURbP51S6S0QGoyaeqk9uB06GNWxsFYWfH5RgpFgqK5FA8tJcM3AdVxrZEVJ7dz+L87nG95gBKf4VuaMHGw==",
|
||||||
"dev": true,
|
|
||||||
"optional": true,
|
|
||||||
"peer": true,
|
|
||||||
"requires": {
|
"requires": {
|
||||||
"chokidar": ">=3.0.0 <4.0.0",
|
"@parcel/watcher": "^2.4.1",
|
||||||
"immutable": "^4.0.0",
|
"chokidar": "^5.0.0",
|
||||||
|
"immutable": "^5.1.5",
|
||||||
"source-map-js": ">=0.6.2 <2.0.0"
|
"source-map-js": ">=0.6.2 <2.0.0"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"chokidar": {
|
||||||
|
"version": "5.0.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/chokidar/-/chokidar-5.0.0.tgz",
|
||||||
|
"integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==",
|
||||||
|
"requires": {
|
||||||
|
"readdirp": "^5.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"readdirp": {
|
||||||
|
"version": "5.1.1",
|
||||||
|
"resolved": "https://registry.npmmirror.com/readdirp/-/readdirp-5.1.1.tgz",
|
||||||
|
"integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"sass-loader": {
|
"sass-loader": {
|
||||||
@@ -12197,8 +12675,7 @@
|
|||||||
"source-map-js": {
|
"source-map-js": {
|
||||||
"version": "1.0.2",
|
"version": "1.0.2",
|
||||||
"resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.0.2.tgz",
|
"resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.0.2.tgz",
|
||||||
"integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==",
|
"integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw=="
|
||||||
"dev": true
|
|
||||||
},
|
},
|
||||||
"source-map-support": {
|
"source-map-support": {
|
||||||
"version": "0.5.21",
|
"version": "0.5.21",
|
||||||
|
|||||||
@@ -29,5 +29,8 @@
|
|||||||
"webpack-bundle-analyzer": "^4.9.1",
|
"webpack-bundle-analyzer": "^4.9.1",
|
||||||
"webpack-cli": "^5.1.4",
|
"webpack-cli": "^5.1.4",
|
||||||
"webpack-dev-server": "^4.15.1"
|
"webpack-dev-server": "^4.15.1"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"sass": "^1.103.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,101 +1,325 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="zh-CN">
|
||||||
|
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>Document</title>
|
<title>TianAI Captcha - 行为验证码演示</title>
|
||||||
<style>
|
<style>
|
||||||
#login-div {
|
* {
|
||||||
width: 500px;
|
margin: 0;
|
||||||
height: 500px;
|
padding: 0;
|
||||||
border: 1px solid #ff5d39;
|
box-sizing: border-box;
|
||||||
position: relative;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
h1 {
|
body {
|
||||||
text-align: center;
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
padding: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.input {
|
.demo-container {
|
||||||
height: 50px;
|
background: #fff;
|
||||||
|
border-radius: 16px;
|
||||||
|
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
|
||||||
|
overflow: hidden;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
border: 1px solid #ccc;
|
max-width: 480px;
|
||||||
border-radius: 6px;
|
|
||||||
margin: 20px auto;
|
|
||||||
color: #ccc;
|
|
||||||
line-height: 50px;
|
|
||||||
text-align: left;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.input-left {
|
.demo-header {
|
||||||
border-right: 1px solid #ccc;
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
text-align: center;
|
|
||||||
width: 100px;
|
|
||||||
display: inline-block;
|
|
||||||
}
|
|
||||||
|
|
||||||
.login-btn {
|
|
||||||
/*margin: 0 auto;*/
|
|
||||||
display: inline-block;
|
|
||||||
width: 160px;
|
|
||||||
height: 50px;
|
|
||||||
background-color: #4BC065;
|
|
||||||
color: #fff;
|
color: #fff;
|
||||||
line-height: 50px;
|
padding: 30px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
border-radius: 6px;
|
}
|
||||||
|
|
||||||
|
.demo-header h1 {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 600;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.demo-header p {
|
||||||
|
font-size: 14px;
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.demo-body {
|
||||||
|
padding: 30px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.captcha-type-selector {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, 1fr);
|
||||||
|
gap: 12px;
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.type-btn {
|
||||||
|
padding: 12px 16px;
|
||||||
|
border: 2px solid #e0e0e0;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #fff;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 500;
|
||||||
|
color: #666;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.type-btn:hover {
|
||||||
|
border-color: #667eea;
|
||||||
|
color: #667eea;
|
||||||
|
background: #f8f9ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.type-btn.active {
|
||||||
|
border-color: #667eea;
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.captcha-wrapper {
|
||||||
|
position: relative;
|
||||||
|
min-height: 340px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
background: #f8f9fa;
|
||||||
|
border-radius: 12px;
|
||||||
|
margin-bottom: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
#captcha-box {
|
#captcha-box {
|
||||||
position: absolute;
|
position: relative;
|
||||||
left: 78px;
|
}
|
||||||
top: 83px;
|
|
||||||
|
.login-form {
|
||||||
|
margin-top: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
display: block;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 500;
|
||||||
|
color: #333;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 12px 16px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 14px;
|
||||||
|
transition: border-color 0.3s;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input:focus {
|
||||||
|
border-color: #667eea;
|
||||||
|
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-btn {
|
||||||
|
width: 100%;
|
||||||
|
padding: 14px;
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
color: #fff;
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: transform 0.2s, box-shadow 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-btn:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-btn:active {
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-btn:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
transform: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-toast {
|
||||||
|
position: fixed;
|
||||||
|
top: 20px;
|
||||||
|
left: 50%;
|
||||||
|
transform: translateX(-50%) translateY(-100px);
|
||||||
|
padding: 16px 24px;
|
||||||
|
border-radius: 8px;
|
||||||
|
color: #fff;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 500;
|
||||||
|
z-index: 10000;
|
||||||
|
transition: transform 0.3s ease;
|
||||||
|
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-toast.show {
|
||||||
|
transform: translateX(-50%) translateY(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-toast.success {
|
||||||
|
background: #10b981;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-toast.error {
|
||||||
|
background: #ef4444;
|
||||||
|
}
|
||||||
|
|
||||||
|
.demo-footer {
|
||||||
|
padding: 16px 30px;
|
||||||
|
background: #f8f9fa;
|
||||||
|
border-top: 1px solid #eee;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #999;
|
||||||
|
}
|
||||||
|
|
||||||
|
.demo-footer a {
|
||||||
|
color: #667eea;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.demo-footer a:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.demo-container {
|
||||||
|
border-radius: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.demo-header {
|
||||||
|
padding: 24px 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.demo-header h1 {
|
||||||
|
font-size: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.demo-body {
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.captcha-type-selector {
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.type-btn {
|
||||||
|
padding: 10px 12px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<!-- 验证码存放的div块 -->
|
<div class="demo-container">
|
||||||
<div id="login-div">
|
<div class="demo-header">
|
||||||
<!-- 装载验证码的DIV -->
|
<h1>TianAI Captcha</h1>
|
||||||
<div id="captcha-box"></div>
|
<p>行为验证码 SDK 演示</p>
|
||||||
<h1>用户登录</h1>
|
</div>
|
||||||
<div class="input">
|
|
||||||
<span class="input-left">用户名</span>
|
<div class="demo-body">
|
||||||
xxxxx
|
<div class="captcha-type-selector">
|
||||||
|
<div class="type-btn active" data-type="SLIDER">滑块验证</div>
|
||||||
|
<div class="type-btn" data-type="ROTATE">旋转验证</div>
|
||||||
|
<div class="type-btn" data-type="CONCAT">滑动还原</div>
|
||||||
|
<div class="type-btn" data-type="WORD_IMAGE_CLICK">文字点选</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="captcha-wrapper">
|
||||||
|
<div id="captcha-box"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="login-form">
|
||||||
|
<div class="form-group">
|
||||||
|
<label>用户名</label>
|
||||||
|
<input type="text" placeholder="请输入用户名">
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>密码</label>
|
||||||
|
<input type="password" placeholder="请输入密码">
|
||||||
|
</div>
|
||||||
|
<button class="login-btn">登录</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="demo-footer">
|
||||||
|
Powered by <a href="https://github.com/dromara/tianai-captcha" target="_blank">TianAI Captcha</a>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="input">
|
|
||||||
<span class="input-left">密码</span>
|
<script src="tac/js/tac.min.js"></script>
|
||||||
xxxxx
|
<link href="tac/css/tac.css" rel="stylesheet">
|
||||||
</div>
|
<script>
|
||||||
<div class="login-btn" data-type="ROTATE">登录(旋转)</div>
|
let currentType = 'SLIDER';
|
||||||
<div class="login-btn" data-type="CONCAT">登录(拼接)</div>
|
let captchaInstance = null;
|
||||||
<div class="login-btn" data-type="WORD_IMAGE_CLICK">登录(汉字点选)</div>
|
|
||||||
<div class="login-btn" data-type="SLIDER">登录(滑块拼图)</div>
|
function initCaptcha(type) {
|
||||||
</div>
|
currentType = type;
|
||||||
|
const box = document.getElementById('captcha-box');
|
||||||
|
box.innerHTML = '';
|
||||||
|
|
||||||
<script>
|
|
||||||
document.querySelectorAll(".login-btn").forEach(el => {
|
|
||||||
el.addEventListener("click", e => {
|
|
||||||
// 样式配置
|
|
||||||
const config = {
|
const config = {
|
||||||
requestCaptchaDataUrl: "http://localhost:8080/gen?type=" + el.dataset.type,
|
requestCaptchaDataUrl: `http://localhost:8080/gen?type=${type}`,
|
||||||
validCaptchaUrl: "http://localhost:8080/check",
|
validCaptchaUrl: "http://localhost:8080/check",
|
||||||
bindEl: "#captcha-box"
|
bindEl: "#captcha-box",
|
||||||
}
|
validSuccess: (res, c, tac) => {
|
||||||
// const style = {
|
alert('验证成功!');
|
||||||
// logoUrl : null
|
},
|
||||||
//
|
validFail: (res, c, tac) => {
|
||||||
// }
|
alert('验证失败,请重试');
|
||||||
|
tac.reloadCaptcha();
|
||||||
|
},
|
||||||
|
btnRefreshFun: (el, tac) => {
|
||||||
|
tac.reloadCaptcha();
|
||||||
|
},
|
||||||
|
btnCloseFun: (el, tac) => {
|
||||||
|
tac.destroyWindow();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const captcha = new TAC(config, null);
|
const style = {
|
||||||
captcha.init();
|
logoUrl: null
|
||||||
})
|
};
|
||||||
})
|
|
||||||
|
|
||||||
|
window.initTAC("./tac", config, style).then(tac => {
|
||||||
|
captchaInstance = tac;
|
||||||
|
tac.init();
|
||||||
|
}).catch(e => {
|
||||||
|
console.error("初始化TAC失败", e);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
</script>
|
document.querySelectorAll('.type-btn').forEach(btn => {
|
||||||
|
btn.addEventListener('click', function() {
|
||||||
|
document.querySelectorAll('.type-btn').forEach(b => b.classList.remove('active'));
|
||||||
|
this.classList.add('active');
|
||||||
|
initCaptcha(this.dataset.type);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
initCaptcha('SLIDER');
|
||||||
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
|
||||||
</html>
|
</html>
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
import "./angle.scss"
|
||||||
|
import {Dom, CommonCaptcha, destroyEvent} from "../common/common.js"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 角度验证验证码 - 用户需要旋转图片到正确角度
|
||||||
|
*/
|
||||||
|
|
||||||
|
const TYPE = "ANGLE"
|
||||||
|
function getTemplate(styleConfig) {
|
||||||
|
return `
|
||||||
|
<div id="tianai-captcha" class="tianai-captcha-slider tianai-captcha-angle">
|
||||||
|
<div class="click-tip">
|
||||||
|
<span id="tianai-captcha-click-track-font" style="font-size: ${styleConfig.i18n?.angle_title_size || '14px'}">${styleConfig.i18n?.angle_title || '旋转图片到正确角度'}</span>
|
||||||
|
</div>
|
||||||
|
<div class="content">
|
||||||
|
<div class="rotate-container">
|
||||||
|
<div class="rotate-img" id="rotate-img">
|
||||||
|
<img id="tianai-captcha-rotate-bg-img" src="" alt/>
|
||||||
|
</div>
|
||||||
|
<div class="rotate-indicator" id="rotate-indicator">
|
||||||
|
<div class="indicator-line" id="indicator-line"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="slider-bar" id="tianai-captcha-slider-bar">
|
||||||
|
<div class="slider-bar-bg"></div>
|
||||||
|
<div class="slider-bar-track" id="tianai-captcha-slider-track"></div>
|
||||||
|
<div class="slider-bar-btn" id="tianai-captcha-slider-btn">
|
||||||
|
<div class="slider-btn-icon"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="tianai-captcha-tips" id="tianai-captcha-tips"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
class Angle extends CommonCaptcha{
|
||||||
|
constructor(boxEl, styleConfig) {
|
||||||
|
super();
|
||||||
|
this.boxEl = boxEl;
|
||||||
|
this.styleConfig = styleConfig;
|
||||||
|
this.type = TYPE;
|
||||||
|
this.currentCaptchaData = {};
|
||||||
|
this.isDragging = false;
|
||||||
|
this.startX = 0;
|
||||||
|
this.currentAngle = 0;
|
||||||
|
}
|
||||||
|
init(captchaData, endCallback, loadSuccessCallback) {
|
||||||
|
// 重载样式
|
||||||
|
this.destroy();
|
||||||
|
this.boxEl.append(getTemplate(this.styleConfig));
|
||||||
|
this.el = this.boxEl.find("#tianai-captcha");
|
||||||
|
// 载入验证码
|
||||||
|
this.loadCaptchaForData(this, captchaData);
|
||||||
|
this.endCallback = endCallback;
|
||||||
|
|
||||||
|
if (loadSuccessCallback) {
|
||||||
|
// 加载成功
|
||||||
|
loadSuccessCallback(this);
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
bindDragEvents() {
|
||||||
|
const sliderBtn = document.getElementById('tianai-captcha-slider-btn');
|
||||||
|
const rotateImg = document.getElementById('rotate-img');
|
||||||
|
if (!sliderBtn || !rotateImg) return;
|
||||||
|
|
||||||
|
// 鼠标按下
|
||||||
|
sliderBtn.addEventListener('mousedown', (e) => {
|
||||||
|
this.isDragging = true;
|
||||||
|
this.startX = e.pageX;
|
||||||
|
this.currentCaptchaData.startTime = new Date();
|
||||||
|
e.preventDefault();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 鼠标移动
|
||||||
|
document.addEventListener('mousemove', (e) => {
|
||||||
|
if (!this.isDragging) return;
|
||||||
|
const moveX = e.pageX - this.startX;
|
||||||
|
const sliderBar = document.getElementById('tianai-captcha-slider-bar');
|
||||||
|
const barWidth = sliderBar ? sliderBar.offsetWidth - 40 : 200;
|
||||||
|
const left = Math.max(0, Math.min(moveX, barWidth));
|
||||||
|
|
||||||
|
sliderBtn.style.left = left + 'px';
|
||||||
|
document.getElementById('tianai-captcha-slider-track').style.width = (left + 20) + 'px';
|
||||||
|
|
||||||
|
// 计算旋转角度
|
||||||
|
this.currentAngle = (left / barWidth) * 360;
|
||||||
|
rotateImg.style.transform = 'rotate(' + this.currentAngle + 'deg)';
|
||||||
|
|
||||||
|
// 更新指示器
|
||||||
|
this.updateIndicator();
|
||||||
|
|
||||||
|
// 记录轨迹
|
||||||
|
if (!this.currentCaptchaData.trackList) {
|
||||||
|
this.currentCaptchaData.trackList = [];
|
||||||
|
}
|
||||||
|
this.currentCaptchaData.trackList.push({
|
||||||
|
x: e.pageX,
|
||||||
|
y: e.pageY,
|
||||||
|
angle: this.currentAngle,
|
||||||
|
t: new Date().getTime() - this.currentCaptchaData.startTime.getTime()
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 鼠标松开
|
||||||
|
document.addEventListener('mouseup', () => {
|
||||||
|
if (!this.isDragging) return;
|
||||||
|
this.isDragging = false;
|
||||||
|
this.currentCaptchaData.stopTime = new Date();
|
||||||
|
this.currentCaptchaData.currentAngle = this.currentAngle;
|
||||||
|
this.endCallback(this.currentCaptchaData, this);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 触摸事件
|
||||||
|
sliderBtn.addEventListener('touchstart', (e) => {
|
||||||
|
this.isDragging = true;
|
||||||
|
this.startX = e.touches[0].pageX;
|
||||||
|
this.currentCaptchaData.startTime = new Date();
|
||||||
|
e.preventDefault();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('touchmove', (e) => {
|
||||||
|
if (!this.isDragging) return;
|
||||||
|
const moveX = e.touches[0].pageX - this.startX;
|
||||||
|
const sliderBar = document.getElementById('tianai-captcha-slider-bar');
|
||||||
|
const barWidth = sliderBar ? sliderBar.offsetWidth - 40 : 200;
|
||||||
|
const left = Math.max(0, Math.min(moveX, barWidth));
|
||||||
|
|
||||||
|
sliderBtn.style.left = left + 'px';
|
||||||
|
document.getElementById('tianai-captcha-slider-track').style.width = (left + 20) + 'px';
|
||||||
|
|
||||||
|
this.currentAngle = (left / barWidth) * 360;
|
||||||
|
rotateImg.style.transform = 'rotate(' + this.currentAngle + 'deg)';
|
||||||
|
this.updateIndicator();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('touchend', () => {
|
||||||
|
if (!this.isDragging) return;
|
||||||
|
this.isDragging = false;
|
||||||
|
this.currentCaptchaData.stopTime = new Date();
|
||||||
|
this.currentCaptchaData.currentAngle = this.currentAngle;
|
||||||
|
this.endCallback(this.currentCaptchaData, this);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
updateIndicator() {
|
||||||
|
const indicatorLine = document.getElementById('indicator-line');
|
||||||
|
if (indicatorLine) {
|
||||||
|
indicatorLine.style.transform = 'rotate(' + this.currentAngle + 'deg)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
destroy () {
|
||||||
|
const existsCaptchaEl = this.boxEl.children("#tianai-captcha");
|
||||||
|
if (existsCaptchaEl) {
|
||||||
|
existsCaptchaEl.remove();
|
||||||
|
}
|
||||||
|
destroyEvent();
|
||||||
|
}
|
||||||
|
|
||||||
|
loadCaptchaForData (that, data) {
|
||||||
|
const bgImg = that.el.find("#tianai-captcha-rotate-bg-img");
|
||||||
|
bgImg.on("load",() => {
|
||||||
|
that.currentCaptchaData = {
|
||||||
|
bgImageWidth: bgImg.width(),
|
||||||
|
bgImageHeight: bgImg.height(),
|
||||||
|
startTime: new Date(),
|
||||||
|
trackList: [],
|
||||||
|
targetAngle: data.data.targetAngle || 0,
|
||||||
|
currentAngle: 0
|
||||||
|
};
|
||||||
|
that.currentCaptchaData.currentCaptchaId = data.data.id;
|
||||||
|
// 绑定滑动事件
|
||||||
|
setTimeout(() => that.bindDragEvents(), 100);
|
||||||
|
})
|
||||||
|
bgImg.attr("src", data.data.backgroundImage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Angle;
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
#tianai-captcha.tianai-captcha-angle {
|
||||||
|
box-sizing: border-box;
|
||||||
|
|
||||||
|
.click-tip {
|
||||||
|
position: relative;
|
||||||
|
height: 40px;
|
||||||
|
width: 100%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
|
||||||
|
#tianai-captcha-click-track-font {
|
||||||
|
font-size: 14px;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.content {
|
||||||
|
.rotate-container {
|
||||||
|
position: relative;
|
||||||
|
width: 200px;
|
||||||
|
height: 200px;
|
||||||
|
margin: 0 auto;
|
||||||
|
border-radius: 50%;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 3px solid #e8e8e8;
|
||||||
|
|
||||||
|
.rotate-img {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
transition: transform 0.1s;
|
||||||
|
|
||||||
|
img {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.rotate-indicator {
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
left: 50%;
|
||||||
|
width: 2px;
|
||||||
|
height: 50%;
|
||||||
|
background-color: transparent;
|
||||||
|
transform-origin: bottom center;
|
||||||
|
transform: translate(-50%, -100%);
|
||||||
|
|
||||||
|
.indicator-line {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
background-color: #ff4444;
|
||||||
|
transform-origin: bottom center;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.slider-bar {
|
||||||
|
position: relative;
|
||||||
|
height: 40px;
|
||||||
|
margin-top: 3px;
|
||||||
|
|
||||||
|
.slider-bar-bg {
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
top: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
border-radius: 4px;
|
||||||
|
background-color: #e8e8e8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slider-bar-track {
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
top: 0;
|
||||||
|
bottom: 0;
|
||||||
|
border-radius: 4px;
|
||||||
|
background-image: linear-gradient(90deg, #409eff, #66b1ff);
|
||||||
|
transition: width 0.1s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slider-bar-btn {
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
top: 0;
|
||||||
|
bottom: 0;
|
||||||
|
width: 40px;
|
||||||
|
border-radius: 4px;
|
||||||
|
background-image: linear-gradient(173deg, hsl(38.09deg 91% 57.89%) 0%, hsl(38.09deg 89.38% 71.74%) 100%);
|
||||||
|
cursor: move;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
z-index: 10;
|
||||||
|
|
||||||
|
.slider-btn-icon {
|
||||||
|
width: 0;
|
||||||
|
height: 0;
|
||||||
|
border-style: solid;
|
||||||
|
border-width: 6px 0 6px 8px;
|
||||||
|
border-color: transparent transparent transparent #fff;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,14 @@ import Rotate from "./rotate/rotate";
|
|||||||
import Concat from "./concat/concat";
|
import Concat from "./concat/concat";
|
||||||
import Disable from "./disable/disable";
|
import Disable from "./disable/disable";
|
||||||
import WordImageClick from "./word_image_click/word_image_click";
|
import WordImageClick from "./word_image_click/word_image_click";
|
||||||
|
import IconClick from "./icon_click/icon_click";
|
||||||
|
import WordOrderClick from "./word_order_click/word_order_click";
|
||||||
|
import Scratch from "./scratch/scratch";
|
||||||
|
import Jigsaw from "./jigsaw/jigsaw";
|
||||||
|
import CurveSlider from "./curve_slider/curve_slider";
|
||||||
|
import Angle from "./angle/angle";
|
||||||
|
import CurveDraw from "./curve_draw/curve_draw";
|
||||||
|
import ProofOfWork from "./proof_of_work/proof_of_work";
|
||||||
import {CaptchaConfig, wrapConfig, wrapStyle} from "./config/config";
|
import {CaptchaConfig, wrapConfig, wrapStyle} from "./config/config";
|
||||||
import {clearAllPreventDefault} from "./common/common";
|
import {clearAllPreventDefault} from "./common/common";
|
||||||
const template =
|
const template =
|
||||||
@@ -11,13 +19,30 @@ const template =
|
|||||||
<div id="tianai-captcha-parent">
|
<div id="tianai-captcha-parent">
|
||||||
<div id="tianai-captcha-bg-img"></div>
|
<div id="tianai-captcha-bg-img"></div>
|
||||||
<div id="tianai-captcha-box">
|
<div id="tianai-captcha-box">
|
||||||
<div id="tianai-captcha-loading" class="loading"></div>
|
<div id="tianai-captcha-loading" class="loading">
|
||||||
|
<div class="loading-spinner"></div>
|
||||||
|
<div class="loading-text">加载中...</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<!-- 底部 -->
|
<!-- 底部 -->
|
||||||
<div class="slider-bottom">
|
<div class="slider-bottom">
|
||||||
<img class="logo" id="tianai-captcha-logo" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAMAAAAM7l6QAAAAMFBMVEVHcEz3tkX3tkX3tkX3tkX3tkX3tkX3tkX3tkX3tkX3tkX3tkX3tkX3tkX3tkX3tkVmTmjZAAAAD3RSTlMASbTm8wh12hOGoCNiyTV98jvOAAABB0lEQVR42nVT0aIFEQiMorD0/397Lc5a7J0n1UylgIniLRKyDcbBDudZH2DYCAabn3PmTrjeUX+7rJGWx0SqVpzReAfTtKU5fgVCNfxWjB69USUDGwoOiauHpZEpSr0tCx8ILb3Dm3WgBbAlifAJk6+Ww6wqEUmpmIorQVZ1JtqKnDMjkb7AgIpO/wMCaQbuBuEtsBUxhuD9daUaZnApiQB8NAKotMwirGGr6mbXpPnHLHDmy6oy3FgP+1j8IBdVklFc01xUJwv3NR0rIeXV5zpzdlruiijzNq/ufOeKWzZLP3160u5P8RjT1M+HHFtx+PwGyOZqT/D8ROOfjOInTLBIHjy/hvwHxkwPu5cCE1QAAAAASUVORK5CYII=" id="tianai-captcha-logo"></img>
|
<div class="bottom-left">
|
||||||
<div class="close-btn" id="tianai-captcha-slider-close-btn"></div>
|
<img class="logo" id="tianai-captcha-logo" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 120 28'%3E%3Ctext x='0' y='22' font-family='Arial,sans-serif' font-size='18' font-weight='bold' fill='%23667eea'%3ETianAI%3C/text%3E%3C/svg%3E" id="tianai-captcha-logo">
|
||||||
<div class="refresh-btn" id="tianai-captcha-slider-refresh-btn"></div>
|
</div>
|
||||||
|
<div class="bottom-right">
|
||||||
|
<div class="icon-btn refresh-btn" id="tianai-captcha-slider-refresh-btn" title="刷新">
|
||||||
|
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2">
|
||||||
|
<path d="M23 4v6h-6M1 20v-6h6"/>
|
||||||
|
<path d="M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15"/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div class="icon-btn close-btn" id="tianai-captcha-slider-close-btn" title="关闭">
|
||||||
|
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2">
|
||||||
|
<line x1="18" y1="6" x2="6" y2="18"/>
|
||||||
|
<line x1="6" y1="6" x2="18" y2="18"/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
@@ -33,6 +58,22 @@ function createCaptchaByType(type, tac) {
|
|||||||
return new Concat(box, styleConfig);
|
return new Concat(box, styleConfig);
|
||||||
case "WORD_IMAGE_CLICK":
|
case "WORD_IMAGE_CLICK":
|
||||||
return new WordImageClick(box, styleConfig);
|
return new WordImageClick(box, styleConfig);
|
||||||
|
case "ICON_CLICK":
|
||||||
|
return new IconClick(box, styleConfig);
|
||||||
|
case "WORD_ORDER_CLICK":
|
||||||
|
return new WordOrderClick(box, styleConfig);
|
||||||
|
case "SCRATCH":
|
||||||
|
return new Scratch(box, styleConfig);
|
||||||
|
case "JIGSAW":
|
||||||
|
return new Jigsaw(box, styleConfig);
|
||||||
|
case "CURVE_SLIDER":
|
||||||
|
return new CurveSlider(box, styleConfig);
|
||||||
|
case "ANGLE":
|
||||||
|
return new Angle(box, styleConfig);
|
||||||
|
case "CURVE_DRAW":
|
||||||
|
return new CurveDraw(box, styleConfig);
|
||||||
|
case "PROOF_OF_WORK":
|
||||||
|
return new ProofOfWork(box, styleConfig);
|
||||||
case "DISABLED":
|
case "DISABLED":
|
||||||
return new Disable(box, styleConfig);
|
return new Disable(box, styleConfig);
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -1,39 +1,58 @@
|
|||||||
#tianai-captcha-parent {
|
#tianai-captcha-parent {
|
||||||
box-shadow: 0 0 11px 0 #999999;
|
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
|
||||||
width: 318px;
|
width: 318px;
|
||||||
height: 318px;
|
height: 318px;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
position: relative;
|
position: relative;
|
||||||
z-index: 997;
|
z-index: 997;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
border-radius: 5px;
|
border-radius: 8px;
|
||||||
padding: 8px;
|
padding: 8px;
|
||||||
|
|
||||||
#tianai-captcha-box {
|
#tianai-captcha-box {
|
||||||
height: 260px;
|
height: 260px;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
position: relative;
|
position: relative;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
|
border-radius: 6px;
|
||||||
|
|
||||||
.loading {
|
.loading {
|
||||||
width: 120px;
|
width: 100%;
|
||||||
height: 20px;
|
height: 100%;
|
||||||
-webkit-mask: linear-gradient(90deg, #000 70%, #0000 0) 0/20%;
|
display: flex;
|
||||||
background: linear-gradient(#f7b645 0 0) 0 / 0% no-repeat #dddddd6b;
|
flex-direction: column;
|
||||||
animation: cartoon 1s infinite steps(6);
|
justify-content: center;
|
||||||
margin: 120px auto;
|
align-items: center;
|
||||||
@keyframes cartoon {
|
background: #fafafa;
|
||||||
100% {
|
|
||||||
background-size: 120%;
|
.loading-spinner {
|
||||||
}
|
width: 36px;
|
||||||
|
height: 36px;
|
||||||
|
border: 3px solid #f0f0f0;
|
||||||
|
border-top-color: #f7b645;
|
||||||
|
border-radius: 50%;
|
||||||
|
animation: tianai-spin 0.8s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading-text {
|
||||||
|
margin-top: 12px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #999;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@keyframes tianai-spin {
|
||||||
|
to { transform: rotate(360deg); }
|
||||||
|
}
|
||||||
|
|
||||||
#tianai-captcha {
|
#tianai-captcha {
|
||||||
transform-style: preserve-3d;
|
transform-style: preserve-3d;
|
||||||
will-change: transform;
|
will-change: transform;
|
||||||
transition-duration: .45s;
|
transition-duration: 0.45s;
|
||||||
//transition-timing-function: cubic-bezier(0.36, 0.3, 0.42, 1.5);
|
|
||||||
transform: translateX(-300px);
|
transform: translateX(-300px);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#tianai-captcha-bg-img {
|
#tianai-captcha-bg-img {
|
||||||
background-color: #fff;
|
background-color: #fff;
|
||||||
background-position: top;
|
background-position: top;
|
||||||
@@ -44,11 +63,54 @@
|
|||||||
top: 0;
|
top: 0;
|
||||||
left: 0;
|
left: 0;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
border-radius: 6px;
|
border-radius: 8px;
|
||||||
//background-image: url("");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.slider-bottom {
|
.slider-bottom {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
height: 26px;
|
||||||
|
width: 100%;
|
||||||
|
padding: 0 2px;
|
||||||
|
|
||||||
|
.bottom-left {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
height: 22px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.bottom-right {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
|
||||||
|
.icon-btn {
|
||||||
|
width: 22px;
|
||||||
|
height: 22px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border-radius: 4px;
|
||||||
|
cursor: pointer;
|
||||||
|
color: #999;
|
||||||
|
transition: all 0.2s;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: #f0f0f0;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
svg {
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.close-btn {
|
.close-btn {
|
||||||
width: 20px;
|
width: 20px;
|
||||||
height: 20px;
|
height: 20px;
|
||||||
@@ -59,6 +121,7 @@
|
|||||||
margin-right: 2px;
|
margin-right: 2px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.refresh-btn {
|
.refresh-btn {
|
||||||
width: 20px;
|
width: 20px;
|
||||||
height: 20px;
|
height: 20px;
|
||||||
@@ -69,13 +132,16 @@
|
|||||||
margin-right: 10px;
|
margin-right: 10px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.logo {
|
.logo {
|
||||||
height: 30px;
|
height: 30px;
|
||||||
float: left;
|
float: left;
|
||||||
}
|
}
|
||||||
|
|
||||||
height: 19px;
|
height: 19px;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.slider-move-shadow {
|
.slider-move-shadow {
|
||||||
animation: myanimation 2s infinite;
|
animation: myanimation 2s infinite;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
@@ -88,20 +154,18 @@
|
|||||||
box-shadow: 1px 1px 1px #fff;
|
box-shadow: 1px 1px 1px #fff;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
}
|
}
|
||||||
|
|
||||||
#tianai-captcha-slider-move-track-mask {
|
#tianai-captcha-slider-move-track-mask {
|
||||||
border-width: 1px;
|
border-width: 1px;
|
||||||
border-style: solid;
|
border-style: solid;
|
||||||
border-color: #00f4ab;
|
border-color: #00f4ab;
|
||||||
|
|
||||||
width: 0;
|
width: 0;
|
||||||
height: 32px;
|
height: 32px;
|
||||||
background-color: #a9ffe5;
|
background-color: #a9ffe5;
|
||||||
opacity: .5;
|
opacity: 0.5;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: -1px;
|
top: -1px;
|
||||||
left: -1px;
|
left: -1px;
|
||||||
border-radius: 5px;
|
border-radius: 5px;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
import "./curve_draw.scss"
|
||||||
|
import {Dom, CommonCaptcha, destroyEvent} from "../common/common.js"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 曲线绘制验证码 - 用户需要绘制指定曲线
|
||||||
|
*/
|
||||||
|
|
||||||
|
const TYPE = "CURVE_DRAW"
|
||||||
|
function getTemplate(styleConfig) {
|
||||||
|
return `
|
||||||
|
<div id="tianai-captcha" class="tianai-captcha-slider tianai-captcha-curve-draw">
|
||||||
|
<div class="click-tip">
|
||||||
|
<span id="tianai-captcha-click-track-font" style="font-size: ${styleConfig.i18n?.curve_draw_title_size || '14px'}">${styleConfig.i18n?.curve_draw_title || '请沿虚线绘制曲线'}</span>
|
||||||
|
</div>
|
||||||
|
<div class="content">
|
||||||
|
<div class="draw-container" id="draw-container">
|
||||||
|
<canvas id="tianai-captcha-draw-canvas" class="draw-canvas"></canvas>
|
||||||
|
</div>
|
||||||
|
<div class="draw-actions">
|
||||||
|
<button class="draw-btn reset-btn" id="draw-reset-btn">重绘</button>
|
||||||
|
<button class="draw-btn confirm-btn" id="draw-confirm-btn">确定</button>
|
||||||
|
</div>
|
||||||
|
<div class="tianai-captcha-tips" id="tianai-captcha-tips"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
class CurveDraw extends CommonCaptcha{
|
||||||
|
constructor(boxEl, styleConfig) {
|
||||||
|
super();
|
||||||
|
this.boxEl = boxEl;
|
||||||
|
this.styleConfig = styleConfig;
|
||||||
|
this.type = TYPE;
|
||||||
|
this.currentCaptchaData = {};
|
||||||
|
this.isDrawing = false;
|
||||||
|
this.drawPoints = [];
|
||||||
|
}
|
||||||
|
init(captchaData, endCallback, loadSuccessCallback) {
|
||||||
|
// 重载样式
|
||||||
|
this.destroy();
|
||||||
|
this.boxEl.append(getTemplate(this.styleConfig));
|
||||||
|
this.el = this.boxEl.find("#tianai-captcha");
|
||||||
|
// 载入验证码
|
||||||
|
this.loadCaptchaForData(this, captchaData);
|
||||||
|
this.endCallback = endCallback;
|
||||||
|
|
||||||
|
if (loadSuccessCallback) {
|
||||||
|
// 加载成功
|
||||||
|
loadSuccessCallback(this);
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
initCanvas() {
|
||||||
|
const canvas = document.getElementById('tianai-captcha-draw-canvas');
|
||||||
|
const container = document.getElementById('draw-container');
|
||||||
|
if (!canvas || !container) return;
|
||||||
|
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
const rect = container.getBoundingClientRect();
|
||||||
|
canvas.width = rect.width;
|
||||||
|
canvas.height = rect.height;
|
||||||
|
|
||||||
|
// 绘制提示曲线(虚线)
|
||||||
|
this.drawGuideCurve(ctx, canvas.width, canvas.height);
|
||||||
|
|
||||||
|
// 绑定绘制事件
|
||||||
|
this.bindDrawEvents(canvas, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
drawGuideCurve(ctx, width, height) {
|
||||||
|
const curveData = this.currentCaptchaData.curveData;
|
||||||
|
if (!curveData || curveData.length < 2) return;
|
||||||
|
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.strokeStyle = 'rgba(64, 158, 255, 0.5)';
|
||||||
|
ctx.lineWidth = 2;
|
||||||
|
ctx.setLineDash([5, 5]);
|
||||||
|
|
||||||
|
ctx.moveTo(curveData[0].x * width, curveData[0].y * height);
|
||||||
|
for (let i = 1; i < curveData.length; i++) {
|
||||||
|
ctx.lineTo(curveData[i].x * width, curveData[i].y * height);
|
||||||
|
}
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
bindDrawEvents(canvas, ctx) {
|
||||||
|
const draw = (e) => {
|
||||||
|
if (!this.isDrawing) return;
|
||||||
|
const rect = canvas.getBoundingClientRect();
|
||||||
|
let x, y;
|
||||||
|
if (e.touches) {
|
||||||
|
x = e.touches[0].clientX - rect.left;
|
||||||
|
y = e.touches[0].clientY - rect.top;
|
||||||
|
} else {
|
||||||
|
x = e.offsetX;
|
||||||
|
y = e.offsetY;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.drawPoints.push({x, y});
|
||||||
|
|
||||||
|
ctx.globalCompositeOperation = 'source-over';
|
||||||
|
ctx.strokeStyle = '#409eff';
|
||||||
|
ctx.lineWidth = 3;
|
||||||
|
ctx.lineCap = 'round';
|
||||||
|
ctx.lineJoin = 'round';
|
||||||
|
|
||||||
|
if (this.drawPoints.length > 1) {
|
||||||
|
const prev = this.drawPoints[this.drawPoints.length - 2];
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(prev.x, prev.y);
|
||||||
|
ctx.lineTo(x, y);
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 鼠标事件
|
||||||
|
canvas.addEventListener('mousedown', (e) => {
|
||||||
|
this.isDrawing = true;
|
||||||
|
this.currentCaptchaData.startTime = new Date();
|
||||||
|
this.drawPoints = [];
|
||||||
|
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||||
|
this.drawGuideCurve(ctx, canvas.width, canvas.height);
|
||||||
|
draw(e);
|
||||||
|
});
|
||||||
|
canvas.addEventListener('mousemove', draw);
|
||||||
|
canvas.addEventListener('mouseup', () => {
|
||||||
|
this.isDrawing = false;
|
||||||
|
});
|
||||||
|
canvas.addEventListener('mouseleave', () => {
|
||||||
|
this.isDrawing = false;
|
||||||
|
});
|
||||||
|
|
||||||
|
// 触摸事件
|
||||||
|
canvas.addEventListener('touchstart', (e) => {
|
||||||
|
this.isDrawing = true;
|
||||||
|
this.currentCaptchaData.startTime = new Date();
|
||||||
|
this.drawPoints = [];
|
||||||
|
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||||
|
this.drawGuideCurve(ctx, canvas.width, canvas.height);
|
||||||
|
e.preventDefault();
|
||||||
|
draw(e);
|
||||||
|
});
|
||||||
|
canvas.addEventListener('touchmove', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
draw(e);
|
||||||
|
});
|
||||||
|
canvas.addEventListener('touchend', () => {
|
||||||
|
this.isDrawing = false;
|
||||||
|
});
|
||||||
|
|
||||||
|
// 重绘按钮
|
||||||
|
const resetBtn = document.getElementById('draw-reset-btn');
|
||||||
|
if (resetBtn) {
|
||||||
|
resetBtn.addEventListener('click', () => {
|
||||||
|
this.drawPoints = [];
|
||||||
|
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||||
|
this.drawGuideCurve(ctx, canvas.width, canvas.height);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 确定按钮
|
||||||
|
const confirmBtn = document.getElementById('draw-confirm-btn');
|
||||||
|
if (confirmBtn) {
|
||||||
|
confirmBtn.addEventListener('click', () => {
|
||||||
|
if (this.drawPoints.length > 0) {
|
||||||
|
this.currentCaptchaData.stopTime = new Date();
|
||||||
|
this.currentCaptchaData.drawPoints = this.drawPoints;
|
||||||
|
this.endCallback(this.currentCaptchaData, this);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
destroy () {
|
||||||
|
const existsCaptchaEl = this.boxEl.children("#tianai-captcha");
|
||||||
|
if (existsCaptchaEl) {
|
||||||
|
existsCaptchaEl.remove();
|
||||||
|
}
|
||||||
|
destroyEvent();
|
||||||
|
}
|
||||||
|
|
||||||
|
loadCaptchaForData (that, data) {
|
||||||
|
that.currentCaptchaData = {
|
||||||
|
startTime: new Date(),
|
||||||
|
drawPoints: [],
|
||||||
|
curveData: data.data.curveData || []
|
||||||
|
};
|
||||||
|
that.currentCaptchaData.currentCaptchaId = data.data.id;
|
||||||
|
// 初始化Canvas
|
||||||
|
setTimeout(() => that.initCanvas(), 100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default CurveDraw;
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
#tianai-captcha.tianai-captcha-curve-draw {
|
||||||
|
box-sizing: border-box;
|
||||||
|
|
||||||
|
.click-tip {
|
||||||
|
position: relative;
|
||||||
|
height: 40px;
|
||||||
|
width: 100%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
|
||||||
|
#tianai-captcha-click-track-font {
|
||||||
|
font-size: 14px;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.content {
|
||||||
|
.draw-container {
|
||||||
|
width: 100%;
|
||||||
|
height: 180px;
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
border-radius: 4px;
|
||||||
|
border: 1px solid #e8e8e8;
|
||||||
|
|
||||||
|
.draw-canvas {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
cursor: crosshair;
|
||||||
|
touch-action: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.draw-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
margin-top: 8px;
|
||||||
|
|
||||||
|
.draw-btn {
|
||||||
|
flex: 1;
|
||||||
|
height: 32px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 14px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: opacity 0.2s;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.reset-btn {
|
||||||
|
background-color: #e8e8e8;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.confirm-btn {
|
||||||
|
background-image: linear-gradient(173deg, hsl(38.09deg 91% 57.89%) 0%, hsl(38.09deg 89.38% 71.74%) 100%);
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
import "./curve_slider.scss"
|
||||||
|
import {Dom, CommonCaptcha, destroyEvent} from "../common/common.js"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 曲线滑块验证码 - 用户需要沿曲线轨迹滑动
|
||||||
|
*/
|
||||||
|
|
||||||
|
const TYPE = "CURVE_SLIDER"
|
||||||
|
function getTemplate(styleConfig) {
|
||||||
|
return `
|
||||||
|
<div id="tianai-captcha" class="tianai-captcha-slider tianai-captcha-curve-slider">
|
||||||
|
<div class="click-tip">
|
||||||
|
<span id="tianai-captcha-click-track-font" style="font-size: ${styleConfig.i18n?.curve_slider_title_size || '14px'}">${styleConfig.i18n?.curve_slider_title || '沿曲线轨迹滑动到终点'}</span>
|
||||||
|
</div>
|
||||||
|
<div class="content">
|
||||||
|
<div class="bg-img-div">
|
||||||
|
<img id="tianai-captcha-slider-bg-img" src="" alt/>
|
||||||
|
<canvas id="tianai-captcha-curve-canvas" class="curve-canvas"></canvas>
|
||||||
|
<div class="curve-point" id="curve-point"></div>
|
||||||
|
<div class="curve-end-point" id="curve-end-point"></div>
|
||||||
|
</div>
|
||||||
|
<div class="slider-bar" id="tianai-captcha-slider-bar">
|
||||||
|
<div class="slider-bar-bg"></div>
|
||||||
|
<div class="slider-bar-track" id="tianai-captcha-slider-track"></div>
|
||||||
|
<div class="slider-bar-btn" id="tianai-captcha-slider-btn">
|
||||||
|
<div class="slider-btn-icon"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="tianai-captcha-tips" id="tianai-captcha-tips"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
class CurveSlider extends CommonCaptcha{
|
||||||
|
constructor(boxEl, styleConfig) {
|
||||||
|
super();
|
||||||
|
this.boxEl = boxEl;
|
||||||
|
this.styleConfig = styleConfig;
|
||||||
|
this.type = TYPE;
|
||||||
|
this.currentCaptchaData = {};
|
||||||
|
this.isDragging = false;
|
||||||
|
this.startX = 0;
|
||||||
|
}
|
||||||
|
init(captchaData, endCallback, loadSuccessCallback) {
|
||||||
|
// 重载样式
|
||||||
|
this.destroy();
|
||||||
|
this.boxEl.append(getTemplate(this.styleConfig));
|
||||||
|
this.el = this.boxEl.find("#tianai-captcha");
|
||||||
|
// 载入验证码
|
||||||
|
this.loadCaptchaForData(this, captchaData);
|
||||||
|
this.endCallback = endCallback;
|
||||||
|
|
||||||
|
if (loadSuccessCallback) {
|
||||||
|
// 加载成功
|
||||||
|
loadSuccessCallback(this);
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
initCanvas() {
|
||||||
|
const canvas = document.getElementById('tianai-captcha-curve-canvas');
|
||||||
|
const bgImg = document.getElementById('tianai-captcha-slider-bg-img');
|
||||||
|
if (!canvas || !bgImg) return;
|
||||||
|
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
canvas.width = bgImg.width;
|
||||||
|
canvas.height = bgImg.height;
|
||||||
|
|
||||||
|
// 绘制曲线
|
||||||
|
this.drawCurve(ctx, canvas.width, canvas.height);
|
||||||
|
|
||||||
|
// 绑定滑动事件
|
||||||
|
this.bindDragEvents(canvas);
|
||||||
|
}
|
||||||
|
|
||||||
|
drawCurve(ctx, width, height) {
|
||||||
|
const curveData = this.currentCaptchaData.curveData;
|
||||||
|
if (!curveData || curveData.length < 2) return;
|
||||||
|
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.strokeStyle = 'rgba(255, 165, 0, 0.8)';
|
||||||
|
ctx.lineWidth = 3;
|
||||||
|
ctx.setLineDash([5, 5]);
|
||||||
|
|
||||||
|
ctx.moveTo(curveData[0].x, curveData[0].y);
|
||||||
|
for (let i = 1; i < curveData.length; i++) {
|
||||||
|
ctx.lineTo(curveData[i].x, curveData[i].y);
|
||||||
|
}
|
||||||
|
ctx.stroke();
|
||||||
|
|
||||||
|
// 绘制起点
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.fillStyle = '#409eff';
|
||||||
|
ctx.arc(curveData[0].x, curveData[0].y, 8, 0, Math.PI * 2);
|
||||||
|
ctx.fill();
|
||||||
|
|
||||||
|
// 绘制终点
|
||||||
|
const endPoint = curveData[curveData.length - 1];
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.fillStyle = '#ff4444';
|
||||||
|
ctx.arc(endPoint.x, endPoint.y, 8, 0, Math.PI * 2);
|
||||||
|
ctx.fill();
|
||||||
|
}
|
||||||
|
|
||||||
|
bindDragEvents(canvas) {
|
||||||
|
const point = document.getElementById('curve-point');
|
||||||
|
const sliderBtn = document.getElementById('tianai-captcha-slider-btn');
|
||||||
|
if (!point || !sliderBtn) return;
|
||||||
|
|
||||||
|
// 鼠标按下
|
||||||
|
sliderBtn.addEventListener('mousedown', (e) => {
|
||||||
|
this.isDragging = true;
|
||||||
|
this.startX = e.pageX;
|
||||||
|
this.currentCaptchaData.startTime = new Date();
|
||||||
|
e.preventDefault();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 鼠标移动
|
||||||
|
document.addEventListener('mousemove', (e) => {
|
||||||
|
if (!this.isDragging) return;
|
||||||
|
const moveX = e.pageX - this.startX;
|
||||||
|
const sliderBar = document.getElementById('tianai-captcha-slider-bar');
|
||||||
|
const barWidth = sliderBar ? sliderBar.offsetWidth - 40 : 200;
|
||||||
|
const left = Math.max(0, Math.min(moveX, barWidth));
|
||||||
|
|
||||||
|
sliderBtn.style.left = left + 'px';
|
||||||
|
document.getElementById('tianai-captcha-slider-track').style.width = (left + 20) + 'px';
|
||||||
|
|
||||||
|
// 记录轨迹
|
||||||
|
if (!this.currentCaptchaData.trackList) {
|
||||||
|
this.currentCaptchaData.trackList = [];
|
||||||
|
}
|
||||||
|
this.currentCaptchaData.trackList.push({
|
||||||
|
x: e.pageX,
|
||||||
|
y: e.pageY,
|
||||||
|
t: new Date().getTime() - this.currentCaptchaData.startTime.getTime()
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 鼠标松开
|
||||||
|
document.addEventListener('mouseup', () => {
|
||||||
|
if (!this.isDragging) return;
|
||||||
|
this.isDragging = false;
|
||||||
|
this.currentCaptchaData.stopTime = new Date();
|
||||||
|
const sliderBtn = document.getElementById('tianai-captcha-slider-btn');
|
||||||
|
this.currentCaptchaData.left = sliderBtn ? sliderBtn.offsetLeft : 0;
|
||||||
|
this.endCallback(this.currentCaptchaData, this);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 触摸事件
|
||||||
|
sliderBtn.addEventListener('touchstart', (e) => {
|
||||||
|
this.isDragging = true;
|
||||||
|
this.startX = e.touches[0].pageX;
|
||||||
|
this.currentCaptchaData.startTime = new Date();
|
||||||
|
e.preventDefault();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('touchmove', (e) => {
|
||||||
|
if (!this.isDragging) return;
|
||||||
|
const moveX = e.touches[0].pageX - this.startX;
|
||||||
|
const sliderBar = document.getElementById('tianai-captcha-slider-bar');
|
||||||
|
const barWidth = sliderBar ? sliderBar.offsetWidth - 40 : 200;
|
||||||
|
const left = Math.max(0, Math.min(moveX, barWidth));
|
||||||
|
|
||||||
|
sliderBtn.style.left = left + 'px';
|
||||||
|
document.getElementById('tianai-captcha-slider-track').style.width = (left + 20) + 'px';
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('touchend', () => {
|
||||||
|
if (!this.isDragging) return;
|
||||||
|
this.isDragging = false;
|
||||||
|
this.currentCaptchaData.stopTime = new Date();
|
||||||
|
const sliderBtn = document.getElementById('tianai-captcha-slider-btn');
|
||||||
|
this.currentCaptchaData.left = sliderBtn ? sliderBtn.offsetLeft : 0;
|
||||||
|
this.endCallback(this.currentCaptchaData, this);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
destroy () {
|
||||||
|
const existsCaptchaEl = this.boxEl.children("#tianai-captcha");
|
||||||
|
if (existsCaptchaEl) {
|
||||||
|
existsCaptchaEl.remove();
|
||||||
|
}
|
||||||
|
destroyEvent();
|
||||||
|
}
|
||||||
|
|
||||||
|
loadCaptchaForData (that, data) {
|
||||||
|
const bgImg = that.el.find("#tianai-captcha-slider-bg-img");
|
||||||
|
bgImg.on("load",() => {
|
||||||
|
that.currentCaptchaData = {
|
||||||
|
bgImageWidth: bgImg.width(),
|
||||||
|
bgImageHeight: bgImg.height(),
|
||||||
|
startTime: new Date(),
|
||||||
|
trackList: [],
|
||||||
|
curveData: data.data.curveData || []
|
||||||
|
};
|
||||||
|
that.currentCaptchaData.currentCaptchaId = data.data.id;
|
||||||
|
// 初始化Canvas
|
||||||
|
setTimeout(() => that.initCanvas(), 100);
|
||||||
|
})
|
||||||
|
bgImg.attr("src", data.data.backgroundImage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default CurveSlider;
|
||||||
Loaded 100 of 221 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user