Compare commits
20
Commits
d56958727c
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f96f964a58 | ||
|
|
6daf5e90a2 | ||
|
|
53628476d7 | ||
|
|
18cf15c43a | ||
|
|
16311b3bd6 | ||
|
|
e7893110a3 | ||
|
|
84ca36b10b | ||
|
|
6ca418fb42 | ||
|
|
427d4878c7 | ||
|
|
4b538f613c | ||
|
|
b7599f6ea0 | ||
|
|
a537958550 | ||
|
|
a478bf1cf2 | ||
|
|
f3002f23c2 | ||
|
|
1164b51c64 | ||
|
|
d1cd371061 | ||
|
|
8f3fe7141c | ||
|
|
cb122b5b07 | ||
|
|
236ff19413 | ||
|
|
dbe9b58b0c |
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
|
||||
|
||||
### 本地环境 ###
|
||||
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 @@
|
||||
[{"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}]
|
||||
@@ -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
Generated
+513
-36
@@ -8,6 +8,9 @@
|
||||
"name": "webpack-demo",
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"sass": "^1.103.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.22.17",
|
||||
"@babel/preset-env": "^7.22.15",
|
||||
@@ -1904,6 +1907,312 @@
|
||||
"integrity": "sha512-Hcv+nVC0kZnQ3tD9GVu5xSMR4VVYOteQIr/hwFPVEvPdlXqgGEuRjiheChHgdM+JyqdgNcmzZOX/tnl0JOiI7A==",
|
||||
"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": {
|
||||
"version": "1.0.0-next.23",
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"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": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmmirror.com/detect-node/-/detect-node-2.1.0.tgz",
|
||||
@@ -4300,12 +4619,10 @@
|
||||
}
|
||||
},
|
||||
"node_modules/immutable": {
|
||||
"version": "4.3.6",
|
||||
"resolved": "https://registry.npmmirror.com/immutable/-/immutable-4.3.6.tgz",
|
||||
"integrity": "sha512-Ju0+lEMyzMVZarkTn/gqRpdqd5dOPaz1mCZ0SH3JV6iFw81PldE/PEB1hWVEA288HPt4WXW8O7AWxB10M+03QQ==",
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"peer": true
|
||||
"version": "5.1.9",
|
||||
"resolved": "https://registry.npmmirror.com/immutable/-/immutable-5.1.9.tgz",
|
||||
"integrity": "sha512-m8nVez3rwrgmWxtLMt1ZYXB2Lv7OKYn/disyxAlSDYAlKSlFoPPfIAmAM/M5xqL4m4C/wAPw7S2/CNaUii1Hxg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/import-local": {
|
||||
"version": "3.1.0",
|
||||
@@ -4428,7 +4745,7 @@
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmmirror.com/is-extglob/-/is-extglob-2.1.1.tgz",
|
||||
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
|
||||
"dev": true,
|
||||
"devOptional": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
@@ -4449,7 +4766,7 @@
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.3.tgz",
|
||||
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
|
||||
"dev": true,
|
||||
"devOptional": true,
|
||||
"dependencies": {
|
||||
"is-extglob": "^2.1.1"
|
||||
},
|
||||
@@ -5224,6 +5541,13 @@
|
||||
"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": {
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmmirror.com/node-forge/-/node-forge-1.3.1.tgz",
|
||||
@@ -6021,22 +6345,23 @@
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/sass": {
|
||||
"version": "1.77.4",
|
||||
"resolved": "https://registry.npmmirror.com/sass/-/sass-1.77.4.tgz",
|
||||
"integrity": "sha512-vcF3Ckow6g939GMA4PeU7b2K/9FALXk2KF9J87txdHzXbUF9XRQRwSxcAs/fGaTnJeBFd7UoV22j3lzMLdM0Pw==",
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"version": "1.103.1",
|
||||
"resolved": "https://registry.npmmirror.com/sass/-/sass-1.103.1.tgz",
|
||||
"integrity": "sha512-9icZURbP51S6S0QGoyaeqk9uB06GNWxsFYWfH5RgpFgqK5FA8tJcM3AdVxrZEVJ7dz+L87nG95gBKf4VuaMHGw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"chokidar": ">=3.0.0 <4.0.0",
|
||||
"immutable": "^4.0.0",
|
||||
"chokidar": "^5.0.0",
|
||||
"immutable": "^5.1.5",
|
||||
"source-map-js": ">=0.6.2 <2.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"sass": "sass.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@parcel/watcher": "^2.4.1"
|
||||
}
|
||||
},
|
||||
"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": {
|
||||
"version": "3.3.0",
|
||||
"resolved": "https://registry.npmmirror.com/schema-utils/-/schema-utils-3.3.0.tgz",
|
||||
@@ -6336,7 +6689,6 @@
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.0.2.tgz",
|
||||
"integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
@@ -8624,6 +8976,110 @@
|
||||
"integrity": "sha512-Hcv+nVC0kZnQ3tD9GVu5xSMR4VVYOteQIr/hwFPVEvPdlXqgGEuRjiheChHgdM+JyqdgNcmzZOX/tnl0JOiI7A==",
|
||||
"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": {
|
||||
"version": "1.0.0-next.23",
|
||||
"resolved": "https://registry.npmmirror.com/@polka/url/-/url-1.0.0-next.23.tgz",
|
||||
@@ -9792,6 +10248,12 @@
|
||||
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
|
||||
"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": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmmirror.com/detect-node/-/detect-node-2.1.0.tgz",
|
||||
@@ -10608,12 +11070,9 @@
|
||||
"requires": {}
|
||||
},
|
||||
"immutable": {
|
||||
"version": "4.3.6",
|
||||
"resolved": "https://registry.npmmirror.com/immutable/-/immutable-4.3.6.tgz",
|
||||
"integrity": "sha512-Ju0+lEMyzMVZarkTn/gqRpdqd5dOPaz1mCZ0SH3JV6iFw81PldE/PEB1hWVEA288HPt4WXW8O7AWxB10M+03QQ==",
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"peer": true
|
||||
"version": "5.1.9",
|
||||
"resolved": "https://registry.npmmirror.com/immutable/-/immutable-5.1.9.tgz",
|
||||
"integrity": "sha512-m8nVez3rwrgmWxtLMt1ZYXB2Lv7OKYn/disyxAlSDYAlKSlFoPPfIAmAM/M5xqL4m4C/wAPw7S2/CNaUii1Hxg=="
|
||||
},
|
||||
"import-local": {
|
||||
"version": "3.1.0",
|
||||
@@ -10709,7 +11168,7 @@
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmmirror.com/is-extglob/-/is-extglob-2.1.1.tgz",
|
||||
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
|
||||
"dev": true
|
||||
"devOptional": true
|
||||
},
|
||||
"is-generator-function": {
|
||||
"version": "1.0.10",
|
||||
@@ -10724,7 +11183,7 @@
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.3.tgz",
|
||||
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
|
||||
"dev": true,
|
||||
"devOptional": true,
|
||||
"requires": {
|
||||
"is-extglob": "^2.1.1"
|
||||
}
|
||||
@@ -11330,6 +11789,12 @@
|
||||
"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": {
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmmirror.com/node-forge/-/node-forge-1.3.1.tgz",
|
||||
@@ -11954,16 +12419,29 @@
|
||||
"dev": true
|
||||
},
|
||||
"sass": {
|
||||
"version": "1.77.4",
|
||||
"resolved": "https://registry.npmmirror.com/sass/-/sass-1.77.4.tgz",
|
||||
"integrity": "sha512-vcF3Ckow6g939GMA4PeU7b2K/9FALXk2KF9J87txdHzXbUF9XRQRwSxcAs/fGaTnJeBFd7UoV22j3lzMLdM0Pw==",
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"version": "1.103.1",
|
||||
"resolved": "https://registry.npmmirror.com/sass/-/sass-1.103.1.tgz",
|
||||
"integrity": "sha512-9icZURbP51S6S0QGoyaeqk9uB06GNWxsFYWfH5RgpFgqK5FA8tJcM3AdVxrZEVJ7dz+L87nG95gBKf4VuaMHGw==",
|
||||
"requires": {
|
||||
"chokidar": ">=3.0.0 <4.0.0",
|
||||
"immutable": "^4.0.0",
|
||||
"@parcel/watcher": "^2.4.1",
|
||||
"chokidar": "^5.0.0",
|
||||
"immutable": "^5.1.5",
|
||||
"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": {
|
||||
@@ -12197,8 +12675,7 @@
|
||||
"source-map-js": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.0.2.tgz",
|
||||
"integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==",
|
||||
"dev": true
|
||||
"integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw=="
|
||||
},
|
||||
"source-map-support": {
|
||||
"version": "0.5.21",
|
||||
|
||||
@@ -29,5 +29,8 @@
|
||||
"webpack-bundle-analyzer": "^4.9.1",
|
||||
"webpack-cli": "^5.1.4",
|
||||
"webpack-dev-server": "^4.15.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"sass": "^1.103.1"
|
||||
}
|
||||
}
|
||||
@@ -1,101 +1,325 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Document</title>
|
||||
<title>TianAI Captcha - 行为验证码演示</title>
|
||||
<style>
|
||||
#login-div {
|
||||
width: 500px;
|
||||
height: 500px;
|
||||
border: 1px solid #ff5d39;
|
||||
position: relative;
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
h1 {
|
||||
text-align: center;
|
||||
body {
|
||||
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 {
|
||||
height: 50px;
|
||||
.demo-container {
|
||||
background: #fff;
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 6px;
|
||||
margin: 20px auto;
|
||||
color: #ccc;
|
||||
line-height: 50px;
|
||||
text-align: left;
|
||||
max-width: 480px;
|
||||
}
|
||||
|
||||
.input-left {
|
||||
border-right: 1px solid #ccc;
|
||||
text-align: center;
|
||||
width: 100px;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.login-btn {
|
||||
/*margin: 0 auto;*/
|
||||
display: inline-block;
|
||||
width: 160px;
|
||||
height: 50px;
|
||||
background-color: #4BC065;
|
||||
.demo-header {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: #fff;
|
||||
line-height: 50px;
|
||||
padding: 30px;
|
||||
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 {
|
||||
position: absolute;
|
||||
left: 78px;
|
||||
top: 83px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.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>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<!-- 验证码存放的div块 -->
|
||||
<div id="login-div">
|
||||
<!-- 装载验证码的DIV -->
|
||||
<div id="captcha-box"></div>
|
||||
<h1>用户登录</h1>
|
||||
<div class="input">
|
||||
<span class="input-left">用户名</span>
|
||||
xxxxx
|
||||
<div class="demo-container">
|
||||
<div class="demo-header">
|
||||
<h1>TianAI Captcha</h1>
|
||||
<p>行为验证码 SDK 演示</p>
|
||||
</div>
|
||||
|
||||
<div class="demo-body">
|
||||
<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 class="input">
|
||||
<span class="input-left">密码</span>
|
||||
xxxxx
|
||||
</div>
|
||||
<div class="login-btn" data-type="ROTATE">登录(旋转)</div>
|
||||
<div class="login-btn" data-type="CONCAT">登录(拼接)</div>
|
||||
<div class="login-btn" data-type="WORD_IMAGE_CLICK">登录(汉字点选)</div>
|
||||
<div class="login-btn" data-type="SLIDER">登录(滑块拼图)</div>
|
||||
</div>
|
||||
|
||||
<script src="tac/js/tac.min.js"></script>
|
||||
<link href="tac/css/tac.css" rel="stylesheet">
|
||||
<script>
|
||||
let currentType = 'SLIDER';
|
||||
let captchaInstance = null;
|
||||
|
||||
function initCaptcha(type) {
|
||||
currentType = type;
|
||||
const box = document.getElementById('captcha-box');
|
||||
box.innerHTML = '';
|
||||
|
||||
<script>
|
||||
document.querySelectorAll(".login-btn").forEach(el => {
|
||||
el.addEventListener("click", e => {
|
||||
// 样式配置
|
||||
const config = {
|
||||
requestCaptchaDataUrl: "http://localhost:8080/gen?type=" + el.dataset.type,
|
||||
requestCaptchaDataUrl: `http://localhost:8080/gen?type=${type}`,
|
||||
validCaptchaUrl: "http://localhost:8080/check",
|
||||
bindEl: "#captcha-box"
|
||||
}
|
||||
// const style = {
|
||||
// logoUrl : null
|
||||
//
|
||||
// }
|
||||
bindEl: "#captcha-box",
|
||||
validSuccess: (res, c, tac) => {
|
||||
alert('验证成功!');
|
||||
},
|
||||
validFail: (res, c, tac) => {
|
||||
alert('验证失败,请重试');
|
||||
tac.reloadCaptcha();
|
||||
},
|
||||
btnRefreshFun: (el, tac) => {
|
||||
tac.reloadCaptcha();
|
||||
},
|
||||
btnCloseFun: (el, tac) => {
|
||||
tac.destroyWindow();
|
||||
}
|
||||
};
|
||||
|
||||
const captcha = new TAC(config, null);
|
||||
captcha.init();
|
||||
})
|
||||
})
|
||||
const style = {
|
||||
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>
|
||||
|
||||
</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 Disable from "./disable/disable";
|
||||
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 {clearAllPreventDefault} from "./common/common";
|
||||
const template =
|
||||
@@ -11,13 +19,30 @@ const template =
|
||||
<div id="tianai-captcha-parent">
|
||||
<div id="tianai-captcha-bg-img"></div>
|
||||
<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 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="close-btn" id="tianai-captcha-slider-close-btn"></div>
|
||||
<div class="refresh-btn" id="tianai-captcha-slider-refresh-btn"></div>
|
||||
<div class="bottom-left">
|
||||
<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>
|
||||
<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>
|
||||
`;
|
||||
@@ -33,6 +58,22 @@ function createCaptchaByType(type, tac) {
|
||||
return new Concat(box, styleConfig);
|
||||
case "WORD_IMAGE_CLICK":
|
||||
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":
|
||||
return new Disable(box, styleConfig);
|
||||
default:
|
||||
|
||||
@@ -1,39 +1,58 @@
|
||||
#tianai-captcha-parent {
|
||||
box-shadow: 0 0 11px 0 #999999;
|
||||
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
|
||||
width: 318px;
|
||||
height: 318px;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
z-index: 997;
|
||||
box-sizing: border-box;
|
||||
border-radius: 5px;
|
||||
border-radius: 8px;
|
||||
padding: 8px;
|
||||
|
||||
#tianai-captcha-box {
|
||||
height: 260px;
|
||||
width: 100%;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 6px;
|
||||
|
||||
.loading {
|
||||
width: 120px;
|
||||
height: 20px;
|
||||
-webkit-mask: linear-gradient(90deg, #000 70%, #0000 0) 0/20%;
|
||||
background: linear-gradient(#f7b645 0 0) 0 / 0% no-repeat #dddddd6b;
|
||||
animation: cartoon 1s infinite steps(6);
|
||||
margin: 120px auto;
|
||||
@keyframes cartoon {
|
||||
100% {
|
||||
background-size: 120%;
|
||||
}
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
background: #fafafa;
|
||||
|
||||
.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 {
|
||||
transform-style: preserve-3d;
|
||||
will-change: transform;
|
||||
transition-duration: .45s;
|
||||
//transition-timing-function: cubic-bezier(0.36, 0.3, 0.42, 1.5);
|
||||
transition-duration: 0.45s;
|
||||
transform: translateX(-300px);
|
||||
}
|
||||
}
|
||||
|
||||
#tianai-captcha-bg-img {
|
||||
background-color: #fff;
|
||||
background-position: top;
|
||||
@@ -44,11 +63,54 @@
|
||||
top: 0;
|
||||
left: 0;
|
||||
position: absolute;
|
||||
border-radius: 6px;
|
||||
//background-image: url("");
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.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 {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
@@ -59,6 +121,7 @@
|
||||
margin-right: 2px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.refresh-btn {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
@@ -69,13 +132,16 @@
|
||||
margin-right: 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 30px;
|
||||
float: left;
|
||||
}
|
||||
|
||||
height: 19px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.slider-move-shadow {
|
||||
animation: myanimation 2s infinite;
|
||||
height: 100%;
|
||||
@@ -88,20 +154,18 @@
|
||||
box-shadow: 1px 1px 1px #fff;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
#tianai-captcha-slider-move-track-mask {
|
||||
border-width: 1px;
|
||||
border-style: solid;
|
||||
border-color: #00f4ab;
|
||||
|
||||
width: 0;
|
||||
height: 32px;
|
||||
background-color: #a9ffe5;
|
||||
opacity: .5;
|
||||
opacity: 0.5;
|
||||
position: absolute;
|
||||
top: -1px;
|
||||
left: -1px;
|
||||
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;
|
||||
@@ -0,0 +1,114 @@
|
||||
#tianai-captcha.tianai-captcha-curve-slider {
|
||||
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 {
|
||||
.bg-img-div {
|
||||
position: relative;
|
||||
height: 180px;
|
||||
overflow: hidden;
|
||||
border-radius: 4px;
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.curve-canvas {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.curve-point {
|
||||
position: absolute;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-radius: 50%;
|
||||
background-color: #409eff;
|
||||
border: 2px solid #fff;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.3);
|
||||
transform: translate(-50%, -50%);
|
||||
display: none;
|
||||
}
|
||||
|
||||
.curve-end-point {
|
||||
position: absolute;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-radius: 50%;
|
||||
background-color: #ff4444;
|
||||
border: 2px solid #fff;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.3);
|
||||
transform: translate(-50%, -50%);
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.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;
|
||||
transition: transform 0.1s;
|
||||
|
||||
.slider-btn-icon {
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-style: solid;
|
||||
border-width: 6px 0 6px 8px;
|
||||
border-color: transparent transparent transparent #fff;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import "./icon_click.scss"
|
||||
import {Dom, CommonCaptcha, move, initConfig, destroyEvent} from "../common/common.js"
|
||||
|
||||
/**
|
||||
* 图标点选验证码
|
||||
*/
|
||||
|
||||
const TYPE = "ICON_CLICK"
|
||||
function getTemplate(styleConfig) {
|
||||
return `
|
||||
<div id="tianai-captcha" class="tianai-captcha-slider tianai-captcha-icon-click">
|
||||
<div class="click-tip">
|
||||
<span id="tianai-captcha-click-track-font" style="font-size: ${styleConfig.i18n?.icon_click_title_size || '14px'}">${styleConfig.i18n?.icon_click_title || '请依次点击图中的图标'}</span>
|
||||
<img src="" id="tianai-captcha-tip-img" class="tip-img">
|
||||
</div>
|
||||
<div class="content">
|
||||
<div class="bg-img-div">
|
||||
<img id="tianai-captcha-slider-bg-img" src="" alt/>
|
||||
<canvas id="tianai-captcha-slider-bg-canvas"></canvas>
|
||||
<div id="bg-img-click-mask"></div>
|
||||
</div>
|
||||
<div class="tianai-captcha-tips" id="tianai-captcha-tips"></div>
|
||||
</div>
|
||||
<div class="click-confirm-btn">确定</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
class IconClick extends CommonCaptcha{
|
||||
constructor(boxEl, styleConfig) {
|
||||
super();
|
||||
this.boxEl = boxEl;
|
||||
this.styleConfig = styleConfig;
|
||||
this.type = TYPE;
|
||||
this.currentCaptchaData = {}
|
||||
}
|
||||
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;
|
||||
const moveFun = move.bind(null, this);
|
||||
// 绑定事件
|
||||
this.el.find("#bg-img-click-mask").click((event) => {
|
||||
if(event.target.className === "click-span") {
|
||||
return;
|
||||
}
|
||||
this.currentCaptchaData.clickCount++;
|
||||
const trackList = this.currentCaptchaData.trackList;
|
||||
if (this.currentCaptchaData.clickCount === 1) {
|
||||
this.currentCaptchaData.startTime = new Date();
|
||||
// move 轨迹
|
||||
window.addEventListener("mousemove", moveFun);
|
||||
this.currentCaptchaData.startX = event.offsetX;
|
||||
this.currentCaptchaData.startY = event.offsetY;
|
||||
}
|
||||
const startTime = this.currentCaptchaData.startTime;
|
||||
trackList.push({
|
||||
x: Math.round(event.offsetX),
|
||||
y: Math.round(event.offsetY),
|
||||
type: "click",
|
||||
t: (new Date().getTime() - startTime.getTime())
|
||||
});
|
||||
const left = event.offsetX - 12;
|
||||
const top = event.offsetY - 12;
|
||||
this.el.find("#bg-img-click-mask").append("<span class='click-span' style='left:" + left + "px;top: " + top + "px'>" + this.currentCaptchaData.clickCount + "</span>")
|
||||
});
|
||||
this.el.find(".click-confirm-btn").click(() => {
|
||||
if (this.currentCaptchaData.clickCount > 0) {
|
||||
// 校验
|
||||
this.currentCaptchaData.stopTime = new Date();
|
||||
window.removeEventListener("mousemove", moveFun);
|
||||
this.endCallback(this.currentCaptchaData,this);
|
||||
}
|
||||
});
|
||||
|
||||
if (loadSuccessCallback) {
|
||||
// 加载成功
|
||||
loadSuccessCallback(this);
|
||||
}
|
||||
return 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");
|
||||
const tipImg = that.el.find("#tianai-captcha-tip-img");
|
||||
bgImg.on("load",() => {
|
||||
that.currentCaptchaData = initConfig(bgImg.width(), bgImg.height(), tipImg.width(), tipImg.height());
|
||||
that.currentCaptchaData.currentCaptchaId = data.data.id;
|
||||
})
|
||||
bgImg.attr("src", data.data.backgroundImage);
|
||||
tipImg.attr("src", data.data.templateImage);
|
||||
}
|
||||
}
|
||||
|
||||
export default IconClick;
|
||||
@@ -0,0 +1,75 @@
|
||||
#tianai-captcha.tianai-captcha-icon-click {
|
||||
box-sizing: border-box;
|
||||
|
||||
.click-tip {
|
||||
position: relative;
|
||||
height: 40px;
|
||||
width: 100%;
|
||||
.tip-img {
|
||||
height: 35px;
|
||||
position: absolute;
|
||||
right: 15px;
|
||||
}
|
||||
#tianai-captcha-click-track-font {
|
||||
font-size: 14px;
|
||||
display: inline-block;
|
||||
height: 40px;
|
||||
line-height: 40px;
|
||||
position: absolute;
|
||||
color: #333;
|
||||
}
|
||||
}
|
||||
|
||||
.slider-bottom {
|
||||
position: relative;
|
||||
top: 6px;
|
||||
}
|
||||
|
||||
.content {
|
||||
#bg-img-click-mask {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
cursor: pointer;
|
||||
|
||||
.click-span {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
border-radius: 50%;
|
||||
background-color: #409eff;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
text-align: center;
|
||||
line-height: 24px;
|
||||
color: #fff;
|
||||
border: 2px solid #fff;
|
||||
box-sizing: content-box;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.click-confirm-btn {
|
||||
width: 100%;
|
||||
height: 35px;
|
||||
border-radius: 4px;
|
||||
background-image: linear-gradient(173deg, hsl(38.09deg 91% 57.89%) 0%, hsl(38.09deg 89.38% 71.74%) 100%);
|
||||
font-size: 15px;
|
||||
text-align: center;
|
||||
box-sizing: border-box;
|
||||
line-height: 35px;
|
||||
color: #fff;
|
||||
margin-top: 3px;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s;
|
||||
|
||||
&:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import "./jigsaw.scss"
|
||||
import {Dom, CommonCaptcha, move, initConfig, destroyEvent} from "../common/common.js"
|
||||
|
||||
/**
|
||||
* 乱序拼图验证码 - 用户需要拖动拼图块到正确位置
|
||||
*/
|
||||
|
||||
const TYPE = "JIGSAW"
|
||||
function getTemplate(styleConfig) {
|
||||
return `
|
||||
<div id="tianai-captcha" class="tianai-captcha-slider tianai-captcha-jigsaw">
|
||||
<div class="click-tip">
|
||||
<span id="tianai-captcha-click-track-font" style="font-size: ${styleConfig.i18n?.jigsaw_title_size || '14px'}">${styleConfig.i18n?.jigsaw_title || '拖动拼图块到正确位置'}</span>
|
||||
</div>
|
||||
<div class="content">
|
||||
<div class="bg-img-div">
|
||||
<img id="tianai-captcha-slider-bg-img" src="" alt/>
|
||||
<div class="jigsaw-block" id="jigsaw-block"></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 class="click-mask-btn" id="tianai-captcha-click-mask-btn"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tianai-captcha-tips" id="tianai-captcha-tips"></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
class Jigsaw extends CommonCaptcha{
|
||||
constructor(boxEl, styleConfig) {
|
||||
super();
|
||||
this.boxEl = boxEl;
|
||||
this.styleConfig = styleConfig;
|
||||
this.type = TYPE;
|
||||
this.currentCaptchaData = {};
|
||||
}
|
||||
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;
|
||||
const moveFun = move.bind(null, this);
|
||||
|
||||
// 绑定事件
|
||||
this.el.find("#tianai-captcha-click-mask-btn").mousedown((event) => {
|
||||
this.currentCaptchaData.moveFlag = true;
|
||||
this.currentCaptchaData.startTime = new Date();
|
||||
// move 轨迹
|
||||
window.addEventListener("mousemove", moveFun);
|
||||
this.currentCaptchaData.startX = event.pageX;
|
||||
this.currentCaptchaData.startY = event.pageY;
|
||||
this.el.find("#tianai-captcha-click-mask-btn").css("transition", "none");
|
||||
});
|
||||
window.addEventListener("mouseup", (event) => {
|
||||
if (!this.currentCaptchaData.moveFlag) {
|
||||
return;
|
||||
}
|
||||
this.currentCaptchaData.moveFlag = false;
|
||||
this.currentCaptchaData.stopTime = new Date();
|
||||
window.removeEventListener("mousemove", moveFun);
|
||||
const left = this.el.find("#tianai-captcha-slider-btn").css("left") ? this.el.find("#tianai-captcha-slider-btn").css("left").split("px")[0] : 0;
|
||||
this.currentCaptchaData.left = left;
|
||||
this.endCallback(this.currentCaptchaData,this);
|
||||
});
|
||||
|
||||
if (loadSuccessCallback) {
|
||||
// 加载成功
|
||||
loadSuccessCallback(this);
|
||||
}
|
||||
return 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 = initConfig(bgImg.width(), bgImg.height(), data.data.blockSize, data.data.blockSize);
|
||||
that.currentCaptchaData.currentCaptchaId = data.data.id;
|
||||
// 设置拼图块位置
|
||||
that.el.find("#jigsaw-block").css({
|
||||
"width": data.data.blockSize + "px",
|
||||
"height": data.data.blockSize + "px",
|
||||
"left": data.data.blockPositionX + "px",
|
||||
"top": data.data.blockPositionY + "px",
|
||||
"background-image": "url(" + data.data.blockImage + ")",
|
||||
"background-size": bgImg.width() + "px " + bgImg.height() + "px",
|
||||
"background-position": "-" + data.data.blockPositionX + "px -" + data.data.blockPositionY + "px"
|
||||
});
|
||||
that.el.find("#tianai-captcha-slider-track").css("height", that.el.find("#tianai-captcha-slider-bar").outerHeight() + "px");
|
||||
})
|
||||
bgImg.attr("src", data.data.backgroundImage);
|
||||
}
|
||||
}
|
||||
|
||||
export default Jigsaw;
|
||||
@@ -0,0 +1,114 @@
|
||||
#tianai-captcha.tianai-captcha-jigsaw {
|
||||
box-sizing: border-box;
|
||||
|
||||
.click-tip {
|
||||
position: relative;
|
||||
height: 40px;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
|
||||
#tianai-captcha-click-track-font {
|
||||
font-size: 14px;
|
||||
color: #333;
|
||||
}
|
||||
}
|
||||
|
||||
.content {
|
||||
position: relative;
|
||||
|
||||
.bg-img-div {
|
||||
position: relative;
|
||||
height: 180px;
|
||||
overflow: hidden;
|
||||
border-radius: 4px;
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.jigsaw-block {
|
||||
position: absolute;
|
||||
cursor: move;
|
||||
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
|
||||
border-radius: 4px;
|
||||
transition: box-shadow 0.2s;
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.4);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.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;
|
||||
transition: transform 0.1s;
|
||||
|
||||
.slider-btn-icon {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
display: block;
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-style: solid;
|
||||
border-width: 6px 0 6px 8px;
|
||||
border-color: transparent transparent transparent #fff;
|
||||
}
|
||||
}
|
||||
|
||||
.click-mask-btn {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
left: 0;
|
||||
top: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import "./proof_of_work.scss"
|
||||
import {Dom, CommonCaptcha, destroyEvent} from "../common/common.js"
|
||||
|
||||
/**
|
||||
* 工作量证明验证码 - 用户需要完成计算工作
|
||||
*/
|
||||
|
||||
const TYPE = "PROOF_OF_WORK"
|
||||
function getTemplate(styleConfig) {
|
||||
return `
|
||||
<div id="tianai-captcha" class="tianai-captcha-slider tianai-captcha-proof-of-work">
|
||||
<div class="click-tip">
|
||||
<span id="tianai-captcha-click-track-font" style="font-size: ${styleConfig.i18n?.proof_of_work_title_size || '14px'}">${styleConfig.i18n?.proof_of_work_title || '请完成工作量证明'}</span>
|
||||
</div>
|
||||
<div class="content">
|
||||
<div class="pow-container">
|
||||
<div class="pow-info">
|
||||
<div class="pow-challenge" id="pow-challenge">
|
||||
<span class="label">挑战:</span>
|
||||
<span class="value" id="pow-challenge-value">-</span>
|
||||
</div>
|
||||
<div class="pow-difficulty" id="pow-difficulty">
|
||||
<span class="label">难度:</span>
|
||||
<span class="value" id="pow-difficulty-value">-</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pow-progress">
|
||||
<div class="progress-bar" id="pow-progress-bar"></div>
|
||||
<span class="progress-text" id="pow-progress-text">0%</span>
|
||||
</div>
|
||||
<div class="pow-status" id="pow-status">等待开始...</div>
|
||||
</div>
|
||||
<div class="pow-actions">
|
||||
<button class="pow-btn start-btn" id="pow-start-btn">开始计算</button>
|
||||
</div>
|
||||
<div class="tianai-captcha-tips" id="tianai-captcha-tips"></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
class ProofOfWork extends CommonCaptcha{
|
||||
constructor(boxEl, styleConfig) {
|
||||
super();
|
||||
this.boxEl = boxEl;
|
||||
this.styleConfig = styleConfig;
|
||||
this.type = TYPE;
|
||||
this.currentCaptchaData = {};
|
||||
this.isComputing = false;
|
||||
this.worker = null;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
bindEvents() {
|
||||
const startBtn = document.getElementById('pow-start-btn');
|
||||
if (!startBtn) return;
|
||||
|
||||
startBtn.addEventListener('click', () => {
|
||||
if (this.isComputing) return;
|
||||
this.startComputation();
|
||||
});
|
||||
}
|
||||
|
||||
startComputation() {
|
||||
this.isComputing = true;
|
||||
this.currentCaptchaData.startTime = new Date();
|
||||
|
||||
const startBtn = document.getElementById('pow-start-btn');
|
||||
if (startBtn) {
|
||||
startBtn.disabled = true;
|
||||
startBtn.textContent = '计算中...';
|
||||
}
|
||||
|
||||
// 更新状态
|
||||
this.updateStatus('正在计算工作量证明...');
|
||||
|
||||
// 模拟计算过程(实际应用中应使用Web Worker)
|
||||
this.simulateComputation();
|
||||
}
|
||||
|
||||
simulateComputation() {
|
||||
const challenge = this.currentCaptchaData.challenge || 'demo';
|
||||
const difficulty = this.currentCaptchaData.difficulty || 4;
|
||||
let nonce = 0;
|
||||
const target = '0'.repeat(difficulty);
|
||||
|
||||
const compute = () => {
|
||||
if (!this.isComputing) return;
|
||||
|
||||
// 简单的SHA-256模拟(实际应用中应使用真实的SHA-256)
|
||||
const hash = this.simpleHash(challenge + nonce);
|
||||
|
||||
// 更新进度
|
||||
const progress = Math.min(99, (nonce / 10000) * 100);
|
||||
this.updateProgress(progress);
|
||||
|
||||
if (hash.startsWith(target)) {
|
||||
// 找到解决方案
|
||||
this.currentCaptchaData.nonce = nonce;
|
||||
this.currentCaptchaData.hash = hash;
|
||||
this.currentCaptchaData.stopTime = new Date();
|
||||
this.updateProgress(100);
|
||||
this.updateStatus('计算完成!');
|
||||
this.endCallback(this.currentCaptchaData, this);
|
||||
} else {
|
||||
nonce++;
|
||||
if (nonce % 100 === 0) {
|
||||
// 每100次更新一次UI
|
||||
setTimeout(compute, 0);
|
||||
} else {
|
||||
compute();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
compute();
|
||||
}
|
||||
|
||||
simpleHash(str) {
|
||||
// 简单的哈希函数(仅用于演示)
|
||||
let hash = 0;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const char = str.charCodeAt(i);
|
||||
hash = ((hash << 5) - hash) + char;
|
||||
hash = hash & hash;
|
||||
}
|
||||
// 转换为16进制字符串
|
||||
return Math.abs(hash).toString(16).padStart(8, '0');
|
||||
}
|
||||
|
||||
updateProgress(percent) {
|
||||
const progressBar = document.getElementById('pow-progress-bar');
|
||||
const progressText = document.getElementById('pow-progress-text');
|
||||
if (progressBar) {
|
||||
progressBar.style.width = percent + '%';
|
||||
}
|
||||
if (progressText) {
|
||||
progressText.textContent = Math.round(percent) + '%';
|
||||
}
|
||||
}
|
||||
|
||||
updateStatus(text) {
|
||||
const statusEl = document.getElementById('pow-status');
|
||||
if (statusEl) {
|
||||
statusEl.textContent = text;
|
||||
}
|
||||
}
|
||||
|
||||
destroy () {
|
||||
this.isComputing = false;
|
||||
const existsCaptchaEl = this.boxEl.children("#tianai-captcha");
|
||||
if (existsCaptchaEl) {
|
||||
existsCaptchaEl.remove();
|
||||
}
|
||||
destroyEvent();
|
||||
}
|
||||
|
||||
loadCaptchaForData (that, data) {
|
||||
that.currentCaptchaData = {
|
||||
startTime: new Date(),
|
||||
challenge: data.data.challenge || 'demo_challenge',
|
||||
difficulty: data.data.difficulty || 4,
|
||||
nonce: 0,
|
||||
hash: ''
|
||||
};
|
||||
that.currentCaptchaData.currentCaptchaId = data.data.id;
|
||||
|
||||
// 更新UI
|
||||
const challengeValue = document.getElementById('pow-challenge-value');
|
||||
const difficultyValue = document.getElementById('pow-difficulty-value');
|
||||
if (challengeValue) {
|
||||
challengeValue.textContent = that.currentCaptchaData.challenge.substring(0, 20) + '...';
|
||||
}
|
||||
if (difficultyValue) {
|
||||
difficultyValue.textContent = that.currentCaptchaData.difficulty;
|
||||
}
|
||||
|
||||
// 绑定事件
|
||||
setTimeout(() => that.bindEvents(), 100);
|
||||
}
|
||||
}
|
||||
|
||||
export default ProofOfWork;
|
||||
@@ -0,0 +1,104 @@
|
||||
#tianai-captcha.tianai-captcha-proof-of-work {
|
||||
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 {
|
||||
.pow-container {
|
||||
background-color: #f5f5f5;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin-bottom: 12px;
|
||||
|
||||
.pow-info {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 12px;
|
||||
|
||||
.pow-challenge,
|
||||
.pow-difficulty {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
|
||||
.label {
|
||||
margin-right: 4px;
|
||||
}
|
||||
|
||||
.value {
|
||||
color: #333;
|
||||
font-family: monospace;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.pow-progress {
|
||||
position: relative;
|
||||
height: 20px;
|
||||
background-color: #e8e8e8;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 8px;
|
||||
|
||||
.progress-bar {
|
||||
height: 100%;
|
||||
background-image: linear-gradient(90deg, #409eff, #66b1ff);
|
||||
transition: width 0.3s;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
font-size: 11px;
|
||||
color: #333;
|
||||
font-weight: bold;
|
||||
}
|
||||
}
|
||||
|
||||
.pow-status {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
.pow-actions {
|
||||
.pow-btn {
|
||||
width: 100%;
|
||||
height: 35px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s;
|
||||
|
||||
&:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
&.start-btn {
|
||||
background-image: linear-gradient(173deg, hsl(38.09deg 91% 57.89%) 0%, hsl(38.09deg 89.38% 71.74%) 100%);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import "./scratch.scss"
|
||||
import {Dom, CommonCaptcha, destroyEvent} from "../common/common.js"
|
||||
|
||||
/**
|
||||
* 刮刮乐验证码 - 用户需要刮开涂层
|
||||
*/
|
||||
|
||||
const TYPE = "SCRATCH"
|
||||
function getTemplate(styleConfig) {
|
||||
return `
|
||||
<div id="tianai-captcha" class="tianai-captcha-slider tianai-captcha-scratch">
|
||||
<div class="scratch-tip">
|
||||
<span id="tianai-captcha-scratch-track-font" style="font-size: ${styleConfig.i18n?.scratch_title_size || '14px'}">${styleConfig.i18n?.scratch_title || '请刮开涂层完成验证'}</span>
|
||||
<span class="scratch-progress" id="scratch-progress">0%</span>
|
||||
</div>
|
||||
<div class="content">
|
||||
<div class="scratch-container" id="scratch-container">
|
||||
<img id="tianai-captcha-scratch-bg-img" src="" alt class="scratch-bg-img"/>
|
||||
<canvas id="tianai-captcha-scratch-canvas" class="scratch-canvas"></canvas>
|
||||
</div>
|
||||
<div class="tianai-captcha-tips" id="tianai-captcha-tips"></div>
|
||||
</div>
|
||||
<div class="click-confirm-btn">确定</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
class Scratch extends CommonCaptcha{
|
||||
constructor(boxEl, styleConfig) {
|
||||
super();
|
||||
this.boxEl = boxEl;
|
||||
this.styleConfig = styleConfig;
|
||||
this.type = TYPE;
|
||||
this.currentCaptchaData = {};
|
||||
this.isDrawing = false;
|
||||
this.scratchPercentage = 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-scratch-canvas');
|
||||
const container = document.getElementById('scratch-container');
|
||||
if (!canvas || !container) return;
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
const rect = container.getBoundingClientRect();
|
||||
canvas.width = rect.width;
|
||||
canvas.height = rect.height;
|
||||
|
||||
// 绘制灰色遮罩层
|
||||
ctx.fillStyle = '#c0c0c0';
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
// 绘制提示文字
|
||||
ctx.fillStyle = '#999';
|
||||
ctx.font = '14px Arial';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText('请用鼠标刮开此区域', canvas.width / 2, canvas.height / 2);
|
||||
|
||||
// 绑定刮擦事件
|
||||
this.bindScratchEvents(canvas, ctx);
|
||||
}
|
||||
|
||||
bindScratchEvents(canvas, ctx) {
|
||||
const scratch = (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;
|
||||
}
|
||||
|
||||
ctx.globalCompositeOperation = 'destination-out';
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y, 15, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
|
||||
this.calculateScratchPercentage(canvas, ctx);
|
||||
};
|
||||
|
||||
// 鼠标事件
|
||||
canvas.addEventListener('mousedown', (e) => {
|
||||
this.isDrawing = true;
|
||||
this.currentCaptchaData.startTime = new Date();
|
||||
scratch(e);
|
||||
});
|
||||
canvas.addEventListener('mousemove', scratch);
|
||||
canvas.addEventListener('mouseup', () => {
|
||||
this.isDrawing = false;
|
||||
});
|
||||
canvas.addEventListener('mouseleave', () => {
|
||||
this.isDrawing = false;
|
||||
});
|
||||
|
||||
// 触摸事件
|
||||
canvas.addEventListener('touchstart', (e) => {
|
||||
this.isDrawing = true;
|
||||
this.currentCaptchaData.startTime = new Date();
|
||||
e.preventDefault();
|
||||
scratch(e);
|
||||
});
|
||||
canvas.addEventListener('touchmove', (e) => {
|
||||
e.preventDefault();
|
||||
scratch(e);
|
||||
});
|
||||
canvas.addEventListener('touchend', () => {
|
||||
this.isDrawing = false;
|
||||
});
|
||||
}
|
||||
|
||||
calculateScratchPercentage(canvas, ctx) {
|
||||
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
const pixels = imageData.data;
|
||||
let transparent = 0;
|
||||
const total = pixels.length / 4;
|
||||
|
||||
for (let i = 3; i < pixels.length; i += 4) {
|
||||
if (pixels[i] === 0) {
|
||||
transparent++;
|
||||
}
|
||||
}
|
||||
|
||||
this.scratchPercentage = Math.round((transparent / total) * 100);
|
||||
const progressEl = this.el.find("#scratch-progress");
|
||||
progressEl.text(this.scratchPercentage + '%');
|
||||
|
||||
// 超过60%自动完成
|
||||
if (this.scratchPercentage >= 60 && !this.currentCaptchaData.verified) {
|
||||
this.currentCaptchaData.verified = true;
|
||||
this.currentCaptchaData.stopTime = new Date();
|
||||
this.currentCaptchaData.scratchPercentage = this.scratchPercentage;
|
||||
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-scratch-bg-img");
|
||||
bgImg.on("load",() => {
|
||||
that.currentCaptchaData = {
|
||||
bgImageWidth: bgImg.width(),
|
||||
bgImageHeight: bgImg.height(),
|
||||
startTime: new Date(),
|
||||
trackList: [],
|
||||
verified: false,
|
||||
scratchPercentage: 0
|
||||
};
|
||||
that.currentCaptchaData.currentCaptchaId = data.data.id;
|
||||
// 初始化Canvas
|
||||
setTimeout(() => that.initCanvas(), 100);
|
||||
})
|
||||
bgImg.attr("src", data.data.backgroundImage);
|
||||
}
|
||||
}
|
||||
|
||||
export default Scratch;
|
||||
@@ -0,0 +1,73 @@
|
||||
#tianai-captcha.tianai-captcha-scratch {
|
||||
box-sizing: border-box;
|
||||
|
||||
.scratch-tip {
|
||||
position: relative;
|
||||
height: 40px;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
|
||||
#tianai-captcha-scratch-track-font {
|
||||
font-size: 14px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.scratch-progress {
|
||||
font-size: 13px;
|
||||
color: #409eff;
|
||||
font-weight: bold;
|
||||
}
|
||||
}
|
||||
|
||||
.slider-bottom {
|
||||
position: relative;
|
||||
top: 6px;
|
||||
}
|
||||
|
||||
.content {
|
||||
.scratch-container {
|
||||
width: 100%;
|
||||
height: 180px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 4px;
|
||||
|
||||
.scratch-bg-img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.scratch-canvas {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
cursor: pointer;
|
||||
touch-action: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.click-confirm-btn {
|
||||
width: 100%;
|
||||
height: 35px;
|
||||
border-radius: 4px;
|
||||
background-image: linear-gradient(173deg, hsl(38.09deg 91% 57.89%) 0%, hsl(38.09deg 89.38% 71.74%) 100%);
|
||||
font-size: 15px;
|
||||
text-align: center;
|
||||
box-sizing: border-box;
|
||||
line-height: 35px;
|
||||
color: #fff;
|
||||
margin-top: 3px;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s;
|
||||
|
||||
&:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import "./word_order_click.scss"
|
||||
import {Dom, CommonCaptcha, move, initConfig, destroyEvent} from "../common/common.js"
|
||||
|
||||
/**
|
||||
* 语序点选验证码 - 用户需要按顺序点击文字
|
||||
*/
|
||||
|
||||
const TYPE = "WORD_ORDER_CLICK"
|
||||
function getTemplate(styleConfig) {
|
||||
return `
|
||||
<div id="tianai-captcha" class="tianai-captcha-slider tianai-captcha-word-order-click">
|
||||
<div class="click-tip">
|
||||
<span id="tianai-captcha-click-track-font" style="font-size: ${styleConfig.i18n?.word_order_click_title_size || '14px'}">${styleConfig.i18n?.word_order_click_title || '请按顺序点击文字'}</span>
|
||||
<div class="word-order-hint" id="word-order-hint"></div>
|
||||
</div>
|
||||
<div class="content">
|
||||
<div class="bg-img-div">
|
||||
<img id="tianai-captcha-slider-bg-img" src="" alt/>
|
||||
<canvas id="tianai-captcha-slider-bg-canvas"></canvas>
|
||||
<div id="bg-img-click-mask"></div>
|
||||
</div>
|
||||
<div class="tianai-captcha-tips" id="tianai-captcha-tips"></div>
|
||||
</div>
|
||||
<div class="click-confirm-btn">确定</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
class WordOrderClick extends CommonCaptcha{
|
||||
constructor(boxEl, styleConfig) {
|
||||
super();
|
||||
this.boxEl = boxEl;
|
||||
this.styleConfig = styleConfig;
|
||||
this.type = TYPE;
|
||||
this.currentCaptchaData = {}
|
||||
}
|
||||
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;
|
||||
const moveFun = move.bind(null, this);
|
||||
|
||||
// 初始化点击顺序提示
|
||||
this.updateOrderHint();
|
||||
|
||||
// 绑定事件
|
||||
this.el.find("#bg-img-click-mask").click((event) => {
|
||||
if(event.target.className === "click-span") {
|
||||
return;
|
||||
}
|
||||
this.currentCaptchaData.clickCount++;
|
||||
const trackList = this.currentCaptchaData.trackList;
|
||||
if (this.currentCaptchaData.clickCount === 1) {
|
||||
this.currentCaptchaData.startTime = new Date();
|
||||
// move 轨迹
|
||||
window.addEventListener("mousemove", moveFun);
|
||||
this.currentCaptchaData.startX = event.offsetX;
|
||||
this.currentCaptchaData.startY = event.offsetY;
|
||||
}
|
||||
const startTime = this.currentCaptchaData.startTime;
|
||||
trackList.push({
|
||||
x: Math.round(event.offsetX),
|
||||
y: Math.round(event.offsetY),
|
||||
type: "click",
|
||||
t: (new Date().getTime() - startTime.getTime())
|
||||
});
|
||||
const left = event.offsetX - 12;
|
||||
const top = event.offsetY - 12;
|
||||
this.el.find("#bg-img-click-mask").append("<span class='click-span' style='left:" + left + "px;top: " + top + "px'>" + this.currentCaptchaData.clickCount + "</span>")
|
||||
this.updateOrderHint();
|
||||
});
|
||||
|
||||
// 重新开始按钮
|
||||
this.el.find(".click-reset-btn").click(() => {
|
||||
this.currentCaptchaData.clickCount = 0;
|
||||
this.currentCaptchaData.trackList = [];
|
||||
this.el.find("#bg-img-click-mask").find(".click-span").remove();
|
||||
this.updateOrderHint();
|
||||
});
|
||||
|
||||
this.el.find(".click-confirm-btn").click(() => {
|
||||
if (this.currentCaptchaData.clickCount > 0) {
|
||||
// 校验
|
||||
this.currentCaptchaData.stopTime = new Date();
|
||||
window.removeEventListener("mousemove", moveFun);
|
||||
this.endCallback(this.currentCaptchaData,this);
|
||||
}
|
||||
});
|
||||
|
||||
if (loadSuccessCallback) {
|
||||
// 加载成功
|
||||
loadSuccessCallback(this);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
updateOrderHint() {
|
||||
const hintEl = this.el.find("#word-order-hint");
|
||||
const count = this.currentCaptchaData.clickCount || 0;
|
||||
const maxCount = this.currentCaptchaData.maxClickCount || 4;
|
||||
let html = '';
|
||||
for (let i = 1; i <= maxCount; i++) {
|
||||
if (i <= count) {
|
||||
html += '<span class="hint-dot active">' + i + '</span>';
|
||||
} else {
|
||||
html += '<span class="hint-dot">' + i + '</span>';
|
||||
}
|
||||
}
|
||||
hintEl.html(html);
|
||||
}
|
||||
|
||||
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 = initConfig(bgImg.width(), bgImg.height(), 0, 0);
|
||||
that.currentCaptchaData.currentCaptchaId = data.data.id;
|
||||
that.currentCaptchaData.maxClickCount = data.data.maxClickCount || 4;
|
||||
})
|
||||
bgImg.attr("src", data.data.backgroundImage);
|
||||
}
|
||||
}
|
||||
|
||||
export default WordOrderClick;
|
||||
@@ -0,0 +1,105 @@
|
||||
#tianai-captcha.tianai-captcha-word-order-click {
|
||||
box-sizing: border-box;
|
||||
|
||||
.click-tip {
|
||||
position: relative;
|
||||
height: 40px;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
|
||||
#tianai-captcha-click-track-font {
|
||||
font-size: 14px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.word-order-hint {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
|
||||
.hint-dot {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
background-color: #e0e0e0;
|
||||
color: #999;
|
||||
font-size: 11px;
|
||||
line-height: 20px;
|
||||
text-align: center;
|
||||
transition: all 0.2s;
|
||||
|
||||
&.active {
|
||||
background-color: #409eff;
|
||||
color: #fff;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.slider-bottom {
|
||||
position: relative;
|
||||
top: 6px;
|
||||
}
|
||||
|
||||
.content {
|
||||
#bg-img-click-mask {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
cursor: pointer;
|
||||
|
||||
.click-span {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
border-radius: 50%;
|
||||
background-color: #409eff;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
text-align: center;
|
||||
line-height: 24px;
|
||||
color: #fff;
|
||||
border: 2px solid #fff;
|
||||
box-sizing: content-box;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.click-confirm-btn {
|
||||
width: 100%;
|
||||
height: 35px;
|
||||
border-radius: 4px;
|
||||
background-image: linear-gradient(173deg, hsl(38.09deg 91% 57.89%) 0%, hsl(38.09deg 89.38% 71.74%) 100%);
|
||||
font-size: 15px;
|
||||
text-align: center;
|
||||
box-sizing: border-box;
|
||||
line-height: 35px;
|
||||
color: #fff;
|
||||
margin-top: 3px;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s;
|
||||
|
||||
&:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
}
|
||||
|
||||
.click-reset-btn {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: 0;
|
||||
font-size: 12px;
|
||||
color: #409eff;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package cloud.tianai.captcha.crypto;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
public class AesEncryptor {
|
||||
|
||||
private static final String ALGORITHM = "AES/GCM/NoPadding";
|
||||
private static final int GCM_IV_LENGTH = 12;
|
||||
private static final int GCM_TAG_LENGTH = 128;
|
||||
private final SecureRandom secureRandom = new SecureRandom();
|
||||
|
||||
private final SecretKeySpec key;
|
||||
|
||||
public AesEncryptor(byte[] keyBytes) {
|
||||
if (keyBytes.length != 32) {
|
||||
throw new IllegalArgumentException("AES-256 key must be 32 bytes, got " + keyBytes.length);
|
||||
}
|
||||
this.key = new SecretKeySpec(keyBytes, "AES");
|
||||
}
|
||||
|
||||
public AesEncryptor(String base64Key) {
|
||||
this(Base64.getDecoder().decode(base64Key));
|
||||
}
|
||||
|
||||
public String encrypt(String plaintext) {
|
||||
try {
|
||||
byte[] iv = new byte[GCM_IV_LENGTH];
|
||||
secureRandom.nextBytes(iv);
|
||||
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
||||
GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key, gcmSpec);
|
||||
byte[] ciphertext = cipher.doFinal(plaintext.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
byte[] combined = new byte[iv.length + ciphertext.length];
|
||||
System.arraycopy(iv, 0, combined, 0, iv.length);
|
||||
System.arraycopy(ciphertext, 0, combined, iv.length, ciphertext.length);
|
||||
return Base64.getEncoder().encodeToString(combined);
|
||||
} catch (Exception e) {
|
||||
throw new CryptoException("AES encryption failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
public String decrypt(String encrypted) {
|
||||
try {
|
||||
byte[] combined = Base64.getDecoder().decode(encrypted);
|
||||
if (combined.length < GCM_IV_LENGTH) {
|
||||
throw new CryptoException("Encrypted data too short");
|
||||
}
|
||||
byte[] iv = new byte[GCM_IV_LENGTH];
|
||||
System.arraycopy(combined, 0, iv, 0, GCM_IV_LENGTH);
|
||||
byte[] ciphertext = new byte[combined.length - GCM_IV_LENGTH];
|
||||
System.arraycopy(combined, GCM_IV_LENGTH, ciphertext, 0, ciphertext.length);
|
||||
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
||||
GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
|
||||
cipher.init(Cipher.DECRYPT_MODE, key, gcmSpec);
|
||||
byte[] plaintext = cipher.doFinal(ciphertext);
|
||||
return new String(plaintext, java.nio.charset.StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
throw new CryptoException("AES decryption failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] generateKey() {
|
||||
byte[] key = new byte[32];
|
||||
new SecureRandom().nextBytes(key);
|
||||
return key;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package cloud.tianai.captcha.crypto;
|
||||
|
||||
public class CryptoException extends RuntimeException {
|
||||
|
||||
public CryptoException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public CryptoException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package cloud.tianai.captcha.crypto;
|
||||
|
||||
import java.security.KeyPair;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class CryptoService {
|
||||
|
||||
private final AesEncryptor aesEncryptor;
|
||||
private final RsaEncryptor rsaEncryptor;
|
||||
private final Signer signer;
|
||||
private final String secretKey;
|
||||
|
||||
public CryptoService(byte[] aesKey, KeyPair rsaKeyPair, String secretKey) {
|
||||
this.aesEncryptor = new AesEncryptor(aesKey);
|
||||
try {
|
||||
this.rsaEncryptor = new RsaEncryptor(
|
||||
RsaEncryptor.publicKeyToBase64(rsaKeyPair.getPublic()),
|
||||
RsaEncryptor.privateKeyToBase64(rsaKeyPair.getPrivate())
|
||||
);
|
||||
} catch (Exception e) {
|
||||
throw new CryptoException("Failed to initialize RSA encryptor", e);
|
||||
}
|
||||
this.signer = new Signer();
|
||||
this.secretKey = secretKey;
|
||||
}
|
||||
|
||||
public CryptoService(String base64AesKey, String base64PublicKey, String base64PrivateKey, String secretKey) {
|
||||
this.aesEncryptor = new AesEncryptor(base64AesKey);
|
||||
try {
|
||||
this.rsaEncryptor = new RsaEncryptor(base64PublicKey, base64PrivateKey);
|
||||
} catch (Exception e) {
|
||||
throw new CryptoException("Failed to initialize RSA encryptor", e);
|
||||
}
|
||||
this.signer = new Signer();
|
||||
this.secretKey = secretKey;
|
||||
}
|
||||
|
||||
public EncryptedPayload encrypt(String plaintext) {
|
||||
String nonce = signer.generateNonce();
|
||||
long timestamp = System.currentTimeMillis();
|
||||
|
||||
String aesEncrypted = aesEncryptor.encrypt(plaintext);
|
||||
String signature = signer.signWithTimestamp(aesEncrypted + "|" + nonce, secretKey, timestamp);
|
||||
|
||||
EncryptedPayload payload = new EncryptedPayload();
|
||||
payload.data = aesEncrypted;
|
||||
payload.nonce = nonce;
|
||||
payload.timestamp = timestamp;
|
||||
payload.signature = signature;
|
||||
return payload;
|
||||
}
|
||||
|
||||
public String decrypt(EncryptedPayload payload) {
|
||||
if (!signer.verifyWithTimestamp(
|
||||
payload.data + "|" + payload.nonce,
|
||||
secretKey,
|
||||
payload.signature,
|
||||
payload.timestamp,
|
||||
300000
|
||||
)) {
|
||||
throw new CryptoException("Signature verification failed or timestamp expired");
|
||||
}
|
||||
return aesEncryptor.decrypt(payload.data);
|
||||
}
|
||||
|
||||
public String encryptAesKeyForTransport(byte[] aesKey) {
|
||||
return rsaEncryptor.encrypt(Base64.getEncoder().encodeToString(aesKey));
|
||||
}
|
||||
|
||||
public String decryptAesKeyFromTransport(String encryptedAesKey) {
|
||||
return rsaEncryptor.decrypt(encryptedAesKey);
|
||||
}
|
||||
|
||||
public String getPublicKeyBase64() {
|
||||
return RsaEncryptor.publicKeyToBase64(rsaEncryptor.getPublicKey());
|
||||
}
|
||||
|
||||
public static CryptoService generate() throws Exception {
|
||||
byte[] aesKey = AesEncryptor.generateKey();
|
||||
KeyPair rsaKeyPair = RsaEncryptor.generateKeyPair();
|
||||
byte[] secretKeyBytes = new byte[32];
|
||||
new java.security.SecureRandom().nextBytes(secretKeyBytes);
|
||||
String secretKey = Base64.getEncoder().encodeToString(secretKeyBytes);
|
||||
return new CryptoService(aesKey, rsaKeyPair, secretKey);
|
||||
}
|
||||
|
||||
public static class EncryptedPayload {
|
||||
public String data;
|
||||
public String nonce;
|
||||
public long timestamp;
|
||||
public String signature;
|
||||
|
||||
public Map<String, Object> toMap() {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("data", data);
|
||||
map.put("nonce", nonce);
|
||||
map.put("ts", timestamp);
|
||||
map.put("sig", signature);
|
||||
return map;
|
||||
}
|
||||
|
||||
public static EncryptedPayload fromMap(Map<String, Object> map) {
|
||||
EncryptedPayload payload = new EncryptedPayload();
|
||||
payload.data = (String) map.get("data");
|
||||
payload.nonce = (String) map.get("nonce");
|
||||
payload.timestamp = map.get("ts") instanceof Number
|
||||
? ((Number) map.get("ts")).longValue()
|
||||
: Long.parseLong(String.valueOf(map.get("ts")));
|
||||
payload.signature = (String) map.get("sig");
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package cloud.tianai.captcha.crypto;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.spec.MGF1ParameterSpec;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import javax.crypto.spec.OAEPParameterSpec;
|
||||
import javax.crypto.spec.PSource;
|
||||
import java.util.Base64;
|
||||
|
||||
public class RsaEncryptor {
|
||||
|
||||
private static final String ALGORITHM = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
|
||||
private static final int KEY_SIZE = 4096;
|
||||
private static final int MAX_ENCRYPT_BLOCK = 446;
|
||||
|
||||
private final PublicKey publicKey;
|
||||
private final PrivateKey privateKey;
|
||||
|
||||
public PublicKey getPublicKey() {
|
||||
return publicKey;
|
||||
}
|
||||
|
||||
public PrivateKey getPrivateKey() {
|
||||
return privateKey;
|
||||
}
|
||||
|
||||
public RsaEncryptor(PublicKey publicKey, PrivateKey privateKey) {
|
||||
this.publicKey = publicKey;
|
||||
this.privateKey = privateKey;
|
||||
}
|
||||
|
||||
public RsaEncryptor(String base64PublicKey, String base64PrivateKey) throws Exception {
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
this.publicKey = base64PublicKey != null
|
||||
? keyFactory.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey)))
|
||||
: null;
|
||||
this.privateKey = base64PrivateKey != null
|
||||
? keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64PrivateKey)))
|
||||
: null;
|
||||
}
|
||||
|
||||
public String encrypt(String plaintext) {
|
||||
if (publicKey == null) {
|
||||
throw new CryptoException("Public key not available for encryption");
|
||||
}
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
||||
OAEPParameterSpec oaepSpec = new OAEPParameterSpec(
|
||||
"SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT
|
||||
);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, publicKey, oaepSpec);
|
||||
byte[] encrypted = cipher.doFinal(plaintext.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
return Base64.getEncoder().encodeToString(encrypted);
|
||||
} catch (Exception e) {
|
||||
throw new CryptoException("RSA encryption failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
public String decrypt(String encrypted) {
|
||||
if (privateKey == null) {
|
||||
throw new CryptoException("Private key not available for decryption");
|
||||
}
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
||||
OAEPParameterSpec oaepSpec = new OAEPParameterSpec(
|
||||
"SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT
|
||||
);
|
||||
cipher.init(Cipher.DECRYPT_MODE, privateKey, oaepSpec);
|
||||
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encrypted));
|
||||
return new String(decrypted, java.nio.charset.StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
throw new CryptoException("RSA decryption failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static KeyPair generateKeyPair() throws Exception {
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
generator.initialize(KEY_SIZE);
|
||||
return generator.generateKeyPair();
|
||||
}
|
||||
|
||||
public static String publicKeyToBase64(PublicKey key) {
|
||||
return Base64.getEncoder().encodeToString(key.getEncoded());
|
||||
}
|
||||
|
||||
public static String privateKeyToBase64(PrivateKey key) {
|
||||
return Base64.getEncoder().encodeToString(key.getEncoded());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package cloud.tianai.captcha.crypto;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
public class Signer {
|
||||
|
||||
private static final String ALGORITHM = "SHA-256";
|
||||
private final SecureRandom secureRandom = new SecureRandom();
|
||||
|
||||
public String sign(String data, String secretKey) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance(ALGORITHM);
|
||||
String payload = secretKey + data + secretKey;
|
||||
byte[] hash = digest.digest(payload.getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getEncoder().encodeToString(hash);
|
||||
} catch (Exception e) {
|
||||
throw new CryptoException("Signing failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean verify(String data, String secretKey, String signature) {
|
||||
String expected = sign(data, secretKey);
|
||||
return constantTimeEquals(expected, signature);
|
||||
}
|
||||
|
||||
public String signWithTimestamp(String data, String secretKey, long timestamp) {
|
||||
return sign(data + "|" + timestamp, secretKey);
|
||||
}
|
||||
|
||||
public boolean verifyWithTimestamp(String data, String secretKey, String signature, long timestamp, long toleranceMs) {
|
||||
long now = System.currentTimeMillis();
|
||||
if (Math.abs(now - timestamp) > toleranceMs) {
|
||||
return false;
|
||||
}
|
||||
return verify(data + "|" + timestamp, secretKey, signature);
|
||||
}
|
||||
|
||||
public String generateNonce() {
|
||||
byte[] nonce = new byte[16];
|
||||
secureRandom.nextBytes(nonce);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(nonce);
|
||||
}
|
||||
|
||||
private boolean constantTimeEquals(String a, String b) {
|
||||
if (a.length() != b.length()) {
|
||||
return false;
|
||||
}
|
||||
int result = 0;
|
||||
for (int i = 0; i < a.length(); i++) {
|
||||
result |= a.charAt(i) ^ b.charAt(i);
|
||||
}
|
||||
return result == 0;
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package cloud.tianai.captcha.generator.impl;
|
||||
|
||||
import cloud.tianai.captcha.generator.AbstractImageCaptchaGenerator;
|
||||
import cloud.tianai.captcha.generator.ImageTransform;
|
||||
import cloud.tianai.captcha.generator.common.model.dto.*;
|
||||
import cloud.tianai.captcha.generator.common.util.CaptchaImageUtils;
|
||||
import cloud.tianai.captcha.interceptor.CaptchaInterceptor;
|
||||
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 java.awt.*;
|
||||
import java.awt.geom.AffineTransform;
|
||||
import java.awt.image.BufferedImage;
|
||||
|
||||
public class AngleRotateImageCaptchaGenerator extends AbstractImageCaptchaGenerator {
|
||||
|
||||
public static String TEMPLATE_ACTIVE_IMAGE_NAME = "active.png";
|
||||
public static String TEMPLATE_FIXED_IMAGE_NAME = "fixed.png";
|
||||
|
||||
public AngleRotateImageCaptchaGenerator(ImageCaptchaResourceManager rm) {
|
||||
super(rm);
|
||||
}
|
||||
|
||||
public AngleRotateImageCaptchaGenerator(ImageCaptchaResourceManager rm, ImageTransform transform) {
|
||||
super(rm);
|
||||
setImageTransform(transform);
|
||||
}
|
||||
|
||||
public AngleRotateImageCaptchaGenerator(ImageCaptchaResourceManager rm, ImageTransform transform, CaptchaInterceptor interceptor) {
|
||||
super(rm);
|
||||
setImageTransform(transform);
|
||||
setInterceptor(interceptor);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doInit() {}
|
||||
|
||||
@Override
|
||||
public void doGenerateCaptchaImage(CaptchaExchange captchaExchange) {
|
||||
GenerateParam param = captchaExchange.getParam();
|
||||
ResourceMap templateResource = requiredRandomGetTemplate(param.getType(), param.getTemplateImageTag());
|
||||
Resource resourceImage = requiredRandomGetResource(param.getType(), param.getBackgroundImageTag());
|
||||
BufferedImage background = getResourceImage(resourceImage);
|
||||
BufferedImage activeTemplate = getTemplateImage(templateResource, TEMPLATE_ACTIVE_IMAGE_NAME);
|
||||
BufferedImage fixedTemplate = getTemplateImage(templateResource, TEMPLATE_FIXED_IMAGE_NAME);
|
||||
|
||||
int centerX = background.getWidth() / 2;
|
||||
int centerY = background.getHeight() / 2;
|
||||
|
||||
int targetAngle = randomInt(30, 330);
|
||||
double radians = Math.toRadians(targetAngle);
|
||||
|
||||
BufferedImage rotatedActive = rotateImage(activeTemplate, -radians);
|
||||
|
||||
int templateSize = activeTemplate.getWidth();
|
||||
int drawX = centerX - templateSize / 2;
|
||||
int drawY = centerY - templateSize / 2;
|
||||
|
||||
CaptchaImageUtils.overlayImage(background, fixedTemplate, drawX, drawY);
|
||||
|
||||
BufferedImage matrixTemplate = CaptchaImageUtils.createTransparentImage(templateSize, background.getHeight());
|
||||
CaptchaImageUtils.overlayImage(matrixTemplate, rotatedActive, 0, drawY);
|
||||
|
||||
captchaExchange.setBackgroundImage(background);
|
||||
captchaExchange.setTemplateImage(matrixTemplate);
|
||||
captchaExchange.setTemplateResource(templateResource);
|
||||
captchaExchange.setResourceImage(resourceImage);
|
||||
captchaExchange.setTransferData(new AngleData(targetAngle));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ImageCaptchaInfo doWrapImageCaptchaInfo(CaptchaExchange captchaExchange) {
|
||||
GenerateParam param = captchaExchange.getParam();
|
||||
BufferedImage backgroundImage = captchaExchange.getBackgroundImage();
|
||||
BufferedImage templateImage = captchaExchange.getTemplateImage();
|
||||
Resource resourceImage = captchaExchange.getResourceImage();
|
||||
ResourceMap templateResource = captchaExchange.getTemplateResource();
|
||||
CustomData customData = captchaExchange.getCustomData();
|
||||
AngleData angleData = (AngleData) captchaExchange.getTransferData();
|
||||
ImageTransformData transform = getImageTransform().transform(param, backgroundImage, templateImage, resourceImage, templateResource, customData);
|
||||
|
||||
RotateImageCaptchaInfo info = RotateImageCaptchaInfo.of((double) angleData.angle, 0,
|
||||
transform.getBackgroundImageUrl(), transform.getTemplateImageUrl(),
|
||||
resourceImage.getTag(), templateResource.getTag(),
|
||||
backgroundImage.getWidth(), backgroundImage.getHeight(),
|
||||
templateImage.getWidth(), templateImage.getHeight());
|
||||
info.setData(customData);
|
||||
return info;
|
||||
}
|
||||
|
||||
private BufferedImage rotateImage(BufferedImage image, double radians) {
|
||||
int w = image.getWidth();
|
||||
int h = image.getHeight();
|
||||
int newW = (int) Math.ceil(Math.abs(w * Math.cos(radians)) + Math.abs(h * Math.sin(radians)));
|
||||
int newH = (int) Math.ceil(Math.abs(h * Math.cos(radians)) + Math.abs(w * Math.sin(radians)));
|
||||
BufferedImage result = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
|
||||
Graphics2D g2d = result.createGraphics();
|
||||
try {
|
||||
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
|
||||
AffineTransform at = new AffineTransform();
|
||||
at.translate((double) newW / 2, (double) newH / 2);
|
||||
at.rotate(radians);
|
||||
at.translate((double) -w / 2, (double) -h / 2);
|
||||
g2d.drawRenderedImage(image, at);
|
||||
} finally {
|
||||
g2d.dispose();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static class AngleData {
|
||||
public int angle;
|
||||
public AngleData(int angle) { this.angle = angle; }
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package cloud.tianai.captcha.generator.impl;
|
||||
|
||||
import cloud.tianai.captcha.generator.AbstractImageCaptchaGenerator;
|
||||
import cloud.tianai.captcha.generator.ImageTransform;
|
||||
import cloud.tianai.captcha.generator.common.model.dto.*;
|
||||
import cloud.tianai.captcha.interceptor.CaptchaInterceptor;
|
||||
import cloud.tianai.captcha.resource.ImageCaptchaResourceManager;
|
||||
import cloud.tianai.captcha.resource.common.model.dto.Resource;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.geom.CubicCurve2D;
|
||||
import java.awt.geom.Point2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public class CurveDrawImageCaptchaGenerator extends AbstractImageCaptchaGenerator {
|
||||
|
||||
public CurveDrawImageCaptchaGenerator(ImageCaptchaResourceManager rm) { super(rm); }
|
||||
public CurveDrawImageCaptchaGenerator(ImageCaptchaResourceManager rm, ImageTransform t) { super(rm); setImageTransform(t); }
|
||||
public CurveDrawImageCaptchaGenerator(ImageCaptchaResourceManager rm, ImageTransform t, CaptchaInterceptor i) { super(rm); setImageTransform(t); setInterceptor(i); }
|
||||
|
||||
@Override
|
||||
protected void doInit() {}
|
||||
|
||||
@Override
|
||||
public void doGenerateCaptchaImage(CaptchaExchange captchaExchange) {
|
||||
GenerateParam param = captchaExchange.getParam();
|
||||
Resource resourceImage = requiredRandomGetResource(param.getType(), param.getBackgroundImageTag());
|
||||
BufferedImage background = getResourceImage(resourceImage);
|
||||
int width = background.getWidth();
|
||||
int height = background.getHeight();
|
||||
|
||||
ThreadLocalRandom random = ThreadLocalRandom.current();
|
||||
double x0 = random.nextDouble(width * 0.05, width * 0.15);
|
||||
double y0 = random.nextDouble(height * 0.3, height * 0.7);
|
||||
double x3 = random.nextDouble(width * 0.85, width * 0.95);
|
||||
double y3 = random.nextDouble(height * 0.3, height * 0.7);
|
||||
double x1 = random.nextDouble(width * 0.25, width * 0.45);
|
||||
double y1 = random.nextDouble(height * 0.1, height * 0.9);
|
||||
double x2 = random.nextDouble(width * 0.55, width * 0.75);
|
||||
double y2 = random.nextDouble(height * 0.1, height * 0.9);
|
||||
|
||||
Graphics2D g2d = background.createGraphics();
|
||||
try {
|
||||
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g2d.setColor(new Color(50, 50, 200, 180));
|
||||
g2d.setStroke(new BasicStroke(3));
|
||||
CubicCurve2D curve = new CubicCurve2D.Double(x0, y0, x1, y1, x2, y2, x3, y3);
|
||||
g2d.draw(curve);
|
||||
g2d.setColor(new Color(200, 50, 50, 200));
|
||||
g2d.fillOval((int) x0 - 5, (int) y0 - 5, 10, 10);
|
||||
g2d.fillOval((int) x3 - 5, (int) y3 - 5, 10, 10);
|
||||
} finally {
|
||||
g2d.dispose();
|
||||
}
|
||||
|
||||
captchaExchange.setBackgroundImage(background);
|
||||
captchaExchange.setTemplateImage(null);
|
||||
captchaExchange.setResourceImage(resourceImage);
|
||||
CurveDrawData curveData = new CurveDrawData(x0, y0, x1, y1, x2, y2, x3, y3);
|
||||
// 在曲线上均匀采样点用于验证
|
||||
List<Point2D.Double> samplePoints = new ArrayList<>();
|
||||
int sampleCount = 10;
|
||||
for (int i = 0; i < sampleCount; i++) {
|
||||
double t = (double) i / (sampleCount - 1);
|
||||
double sx = cubicBezier(t, x0, x1, x2, x3);
|
||||
double sy = cubicBezier(t, y0, y1, y2, y3);
|
||||
samplePoints.add(new Point2D.Double(sx, sy));
|
||||
}
|
||||
curveData.setSamplePoints(samplePoints);
|
||||
captchaExchange.setTransferData(curveData);
|
||||
}
|
||||
|
||||
private static double cubicBezier(double t, double p0, double p1, double p2, double p3) {
|
||||
double oneMinusT = 1.0 - t;
|
||||
return oneMinusT * oneMinusT * oneMinusT * p0 +
|
||||
3.0 * oneMinusT * oneMinusT * t * p1 +
|
||||
3.0 * oneMinusT * t * t * p2 +
|
||||
t * t * t * p3;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ImageCaptchaInfo doWrapImageCaptchaInfo(CaptchaExchange captchaExchange) {
|
||||
GenerateParam param = captchaExchange.getParam();
|
||||
BufferedImage bg = captchaExchange.getBackgroundImage();
|
||||
Resource resImg = captchaExchange.getResourceImage();
|
||||
CustomData customData = captchaExchange.getCustomData();
|
||||
ImageTransformData transform = getImageTransform().transform(param, bg, null, resImg, null, customData);
|
||||
|
||||
ImageCaptchaInfo info = ImageCaptchaInfo.of(
|
||||
transform.getBackgroundImageUrl(), null,
|
||||
resImg.getTag(), null,
|
||||
bg.getWidth(), bg.getHeight(), 0, 0,
|
||||
0, "CURVE_DRAW");
|
||||
// 将 CurveDrawData 设置到 customData.expand 中
|
||||
CurveDrawData curveData = (CurveDrawData) captchaExchange.getTransferData();
|
||||
if (customData == null) {
|
||||
customData = new CustomData();
|
||||
}
|
||||
customData.setExpand(curveData);
|
||||
info.setData(customData);
|
||||
return info;
|
||||
}
|
||||
|
||||
public static class CurveDrawData {
|
||||
public double x0, y0, x1, y1, x2, y2, x3, y3;
|
||||
public List<Point2D.Double> samplePoints;
|
||||
public CurveDrawData(double x0, double y0, double x1, double y1, double x2, double y2, double x3, double y3) {
|
||||
this.x0 = x0; this.y0 = y0; this.x1 = x1; this.y1 = y1;
|
||||
this.x2 = x2; this.y2 = y2; this.x3 = x3; this.y3 = y3;
|
||||
}
|
||||
public List<Point2D.Double> getSamplePoints() { return samplePoints; }
|
||||
public void setSamplePoints(List<Point2D.Double> samplePoints) { this.samplePoints = samplePoints; }
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package cloud.tianai.captcha.generator.impl;
|
||||
|
||||
import cloud.tianai.captcha.generator.AbstractImageCaptchaGenerator;
|
||||
import cloud.tianai.captcha.generator.ImageTransform;
|
||||
import cloud.tianai.captcha.generator.common.model.dto.*;
|
||||
import cloud.tianai.captcha.generator.common.util.CaptchaImageUtils;
|
||||
import cloud.tianai.captcha.interceptor.CaptchaInterceptor;
|
||||
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 java.awt.*;
|
||||
import java.awt.geom.CubicCurve2D;
|
||||
import java.awt.geom.FlatteningPathIterator;
|
||||
import java.awt.geom.PathIterator;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public class CurveSliderImageCaptchaGenerator extends AbstractImageCaptchaGenerator {
|
||||
|
||||
public static String TEMPLATE_ACTIVE_IMAGE_NAME = "active.png";
|
||||
public static String TEMPLATE_FIXED_IMAGE_NAME = "fixed.png";
|
||||
public static String TEMPLATE_MASK_IMAGE_NAME = "mask.png";
|
||||
|
||||
public CurveSliderImageCaptchaGenerator(ImageCaptchaResourceManager rm) { super(rm); }
|
||||
public CurveSliderImageCaptchaGenerator(ImageCaptchaResourceManager rm, ImageTransform t) { super(rm); setImageTransform(t); }
|
||||
public CurveSliderImageCaptchaGenerator(ImageCaptchaResourceManager rm, ImageTransform t, CaptchaInterceptor i) { super(rm); setImageTransform(t); setInterceptor(i); }
|
||||
|
||||
@Override
|
||||
protected void doInit() {}
|
||||
|
||||
@Override
|
||||
public void doGenerateCaptchaImage(CaptchaExchange captchaExchange) {
|
||||
GenerateParam param = captchaExchange.getParam();
|
||||
ResourceMap templateResource = requiredRandomGetTemplate(param.getType(), param.getTemplateImageTag());
|
||||
Resource resourceImage = requiredRandomGetResource(param.getType(), param.getBackgroundImageTag());
|
||||
BufferedImage background = getResourceImage(resourceImage);
|
||||
BufferedImage fixedTemplate = getTemplateImage(templateResource, TEMPLATE_FIXED_IMAGE_NAME);
|
||||
BufferedImage activeTemplate = getTemplateImage(templateResource, TEMPLATE_ACTIVE_IMAGE_NAME);
|
||||
BufferedImage maskTemplate = getTemplateImageOfOptional(templateResource, TEMPLATE_MASK_IMAGE_NAME).orElse(fixedTemplate);
|
||||
|
||||
int bgWidth = background.getWidth();
|
||||
int bgHeight = background.getHeight();
|
||||
int tplWidth = fixedTemplate.getWidth();
|
||||
|
||||
ThreadLocalRandom random = ThreadLocalRandom.current();
|
||||
double x0 = random.nextDouble(0, bgWidth * 0.1);
|
||||
double y0 = random.nextDouble(bgHeight * 0.3, bgHeight * 0.7);
|
||||
double x3 = random.nextDouble(bgWidth * 0.85, bgWidth * 0.95);
|
||||
double y3 = random.nextDouble(bgHeight * 0.3, bgHeight * 0.7);
|
||||
double x1 = random.nextDouble(bgWidth * 0.25, bgWidth * 0.45);
|
||||
double y1 = random.nextDouble(bgHeight * 0.1, bgHeight * 0.9);
|
||||
double x2 = random.nextDouble(bgWidth * 0.55, bgWidth * 0.75);
|
||||
double y2 = random.nextDouble(bgHeight * 0.1, bgHeight * 0.9);
|
||||
|
||||
CubicCurve2D curve = new CubicCurve2D.Double(x0, y0, x1, y1, x2, y2, x3, y3);
|
||||
List<Point> pathPoints = sampleCurve(curve, bgWidth);
|
||||
|
||||
double targetRatio = random.nextDouble(0.35, 0.75);
|
||||
int targetIndex = (int) (pathPoints.size() * targetRatio);
|
||||
Point targetPoint = pathPoints.get(targetIndex);
|
||||
|
||||
int randomX = targetPoint.x;
|
||||
int randomY = Math.max(0, Math.min(bgHeight - tplWidth, targetPoint.y - tplWidth / 2));
|
||||
|
||||
BufferedImage cutImage = CaptchaImageUtils.cutImage(background, maskTemplate, randomX, randomY);
|
||||
CaptchaImageUtils.overlayImage(background, fixedTemplate, randomX, randomY);
|
||||
CaptchaImageUtils.overlayImage(cutImage, activeTemplate, 0, 0);
|
||||
|
||||
BufferedImage matrixTemplate = CaptchaImageUtils.createTransparentImage(activeTemplate.getWidth(), background.getHeight());
|
||||
CaptchaImageUtils.overlayImage(matrixTemplate, cutImage, 0, randomY);
|
||||
|
||||
captchaExchange.setBackgroundImage(background);
|
||||
captchaExchange.setTemplateImage(matrixTemplate);
|
||||
captchaExchange.setTemplateResource(templateResource);
|
||||
captchaExchange.setResourceImage(resourceImage);
|
||||
captchaExchange.setTransferData(new CurveData(randomX, randomY, pathPoints));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SliderImageCaptchaInfo doWrapImageCaptchaInfo(CaptchaExchange captchaExchange) {
|
||||
GenerateParam param = captchaExchange.getParam();
|
||||
BufferedImage bg = captchaExchange.getBackgroundImage();
|
||||
BufferedImage tpl = captchaExchange.getTemplateImage();
|
||||
Resource resImg = captchaExchange.getResourceImage();
|
||||
ResourceMap tplRes = captchaExchange.getTemplateResource();
|
||||
CustomData customData = captchaExchange.getCustomData();
|
||||
CurveData curveData = (CurveData) captchaExchange.getTransferData();
|
||||
ImageTransformData transform = getImageTransform().transform(param, bg, tpl, resImg, tplRes, customData);
|
||||
|
||||
SliderImageCaptchaInfo info = SliderImageCaptchaInfo.of(curveData.x, curveData.y,
|
||||
transform.getBackgroundImageUrl(), transform.getTemplateImageUrl(),
|
||||
resImg.getTag(), tplRes.getTag(),
|
||||
bg.getWidth(), bg.getHeight(), tpl.getWidth(), tpl.getHeight());
|
||||
info.setData(customData);
|
||||
return info;
|
||||
}
|
||||
|
||||
private List<Point> sampleCurve(CubicCurve2D curve, int bgWidth) {
|
||||
List<Point> points = new ArrayList<>();
|
||||
PathIterator pi = curve.getPathIterator(null, 0.5);
|
||||
FlatteningPathIterator fpi = new FlatteningPathIterator(pi, 0.5);
|
||||
double[] coords = new double[6];
|
||||
while (!fpi.isDone()) {
|
||||
int type = fpi.currentSegment(coords);
|
||||
if (type == PathIterator.SEG_LINETO || type == PathIterator.SEG_MOVETO) {
|
||||
points.add(new Point((int) coords[0], (int) coords[1]));
|
||||
}
|
||||
fpi.next();
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
public static class CurveData {
|
||||
public int x;
|
||||
public int y;
|
||||
public List<Point> pathPoints;
|
||||
public CurveData(int x, int y, List<Point> pathPoints) {
|
||||
this.x = x; this.y = y; this.pathPoints = pathPoints;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 166 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user