mirror of
https://github.com/Sagit-chu/flvx.git
synced 2026-11-16 09:34:22 +08:00
Compare commits
78 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a982c663d2 | |||
| 98b4d78b4d | |||
| 45d7970177 | |||
| 1b4500202a | |||
| 9a9e83dda0 | |||
| e5e22baf43 | |||
| 961c06655a | |||
| 8dc31383e0 | |||
| 184ac3c3e5 | |||
| 77dbd719ed | |||
| 04ce125416 | |||
| fd5cfc2a40 | |||
| 4e4193e0b0 | |||
| 3f80278dd4 | |||
| 6abe3e7713 | |||
| 47c05c3d02 | |||
| d05c8a2ea4 | |||
| e00e41bb64 | |||
| 5271efec1e | |||
| 2d39cb3005 | |||
| 3e52c8eace | |||
| 7808d57a79 | |||
| 46bc4ca6e4 | |||
| 28e66ab172 | |||
| f19bccec4c | |||
| e37d6cf666 | |||
| 177c2bc35f | |||
| 76c0978763 | |||
| fd1168d855 | |||
| 92c9590c1a | |||
| 2afb1d275a | |||
| 880cd4cac5 | |||
| a69a0f040b | |||
| cf6294a77d | |||
| 524ee4cd95 | |||
| c049ceaacf | |||
| 3424221176 | |||
| 5a9715eb26 | |||
| 1b79213aed | |||
| c0d71125f4 | |||
| f01c0481cd | |||
| f227ffddc3 | |||
| c4f14f985e | |||
| 3b294c6b9e | |||
| 641aa66afc | |||
| fea1bf52f3 | |||
| a72d84fa76 | |||
| 146821ebba | |||
| 0191f29cf1 | |||
| 149a841a49 | |||
| 229ae9e454 | |||
| ae8a3db3df | |||
| 51660c413e | |||
| 2d2ca389e3 | |||
| 3799729706 | |||
| 8628c35802 | |||
| acea5ea76c | |||
| 8652380da1 | |||
| dd206ced14 | |||
| f720b92f53 | |||
| f879a58bb4 | |||
| b11283d488 | |||
| 70f8dfeac1 | |||
| 37005a1954 | |||
| b55e056316 | |||
| b3b7f5e56d | |||
| d6ff6ea500 | |||
| 9ed875b7ef | |||
| 6387ce1816 | |||
| 219067a27c | |||
| 33678477aa | |||
| e33fbda8f4 | |||
| 62cb75f669 | |||
| f3260637db | |||
| e43c6bf840 | |||
| 025d0a3322 | |||
| 2dcfe15f00 | |||
| ecaae178b6 |
@@ -48,6 +48,43 @@ jobs:
|
|||||||
- name: Build
|
- name: Build
|
||||||
run: go build -v ./...
|
run: go build -v ./...
|
||||||
|
|
||||||
|
backend-postgres-contract:
|
||||||
|
name: Go Backend PostgreSQL Contract
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:17
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: flux_test
|
||||||
|
POSTGRES_PASSWORD: flux_test_pass
|
||||||
|
POSTGRES_DB: flux_test
|
||||||
|
ports:
|
||||||
|
- 5432:5432
|
||||||
|
options: >-
|
||||||
|
--health-cmd "pg_isready -U flux_test -d flux_test"
|
||||||
|
--health-interval 10s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 10
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: go-backend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.23'
|
||||||
|
cache-dependency-path: go-backend/go.sum
|
||||||
|
|
||||||
|
- name: Download dependencies
|
||||||
|
run: go mod download
|
||||||
|
|
||||||
|
- name: Run PostgreSQL contract test
|
||||||
|
env:
|
||||||
|
FLVX_POSTGRES_TEST_DSN: 'postgres://flux_test:flux_test_pass@127.0.0.1:5432/flux_test?sslmode=disable'
|
||||||
|
run: go test ./tests/contract -run TestPostgresNodeCreateRepairsMissingIDDefaultContract -count=1
|
||||||
|
|
||||||
agent:
|
agent:
|
||||||
name: Build Agent
|
name: Build Agent
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# PROJECT KNOWLEDGE BASE
|
# PROJECT KNOWLEDGE BASE
|
||||||
|
|
||||||
**Generated:** Mon Feb 02 2026
|
**Generated:** Sun Feb 15 2026
|
||||||
**Commit:** 7ca01ab
|
**Commit:** e5e22ba
|
||||||
**Branch:** beta
|
**Branch:** main
|
||||||
|
|
||||||
## OVERVIEW
|
## OVERVIEW
|
||||||
FLVX (formerly Flux Panel) is a traffic forwarding management system built on a forked GOST v3 stack. It ships as a Go-based admin API (SQLite) + Vite/React UI + Go forwarding agent, with optional mobile WebView wrappers.
|
FLVX (formerly Flux Panel) is a traffic forwarding management system built on a forked GOST v3 stack. It ships as a Go-based admin API (SQLite) + Vite/React UI + Go forwarding agent, with optional mobile WebView wrappers.
|
||||||
@@ -43,11 +43,17 @@ FLVX (formerly Flux Panel) is a traffic forwarding management system built on a
|
|||||||
|
|
||||||
|
|
||||||
## CONVENTIONS
|
## CONVENTIONS
|
||||||
- `Authorization` header carries the raw JWT token (no `Bearer` prefix) between `vite-frontend/` and `go-backend/`.
|
- **Auth**: `Authorization` header carries the raw JWT token (no `Bearer` prefix) between `vite-frontend/` and `go-backend/`.
|
||||||
- `go-gost/` uses `replace github.com/go-gost/x => ./x` and `go-gost/x/` is also its own Go module.
|
- **Module Fork**: `go-gost/` uses `replace github.com/go-gost/x => ./x` and `go-gost/x/` is also its own Go module.
|
||||||
|
- **Encryption**: Agent-to-panel communication uses AES encryption with node `secret` as PSK.
|
||||||
|
- **API Envelope**: All REST responses follow `{code, msg, data, ts}` structure (code 0 = success).
|
||||||
|
|
||||||
## ANTI-PATTERNS (THIS PROJECT)
|
## ANTI-PATTERNS (THIS PROJECT)
|
||||||
- Do not edit generated protobuf output: `go-gost/x/internal/util/grpc/proto/*.pb.go`, `go-gost/x/internal/util/grpc/proto/*_grpc.pb.go`.
|
- **DO NOT EDIT** generated protobuf output: `go-gost/x/internal/util/grpc/proto/*.pb.go`, `go-gost/x/internal/util/grpc/proto/*_grpc.pb.go`.
|
||||||
|
- **DO NOT ADD** `Bearer` prefix to Authorization header - expects raw JWT token.
|
||||||
|
- **DO NOT MODIFY** `install.sh` or `panel_install.sh` locally - CI overwrites these on release.
|
||||||
|
- **DO NOT USE** ORM in backend - uses raw SQL with `database/sql`.
|
||||||
|
- **DO NOT ADD** frontend tests - project has no test infrastructure (Vitest/Jest not configured).
|
||||||
|
|
||||||
## COMMANDS
|
## COMMANDS
|
||||||
```bash
|
```bash
|
||||||
@@ -65,6 +71,19 @@ docker compose -f docker-compose-v6.yml up -d
|
|||||||
(cd go-gost && go run .)
|
(cd go-gost && go run .)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## UNIQUE STYLES
|
||||||
|
- **Flat Monorepo**: Language-prefixed dirs (`go-backend`, `go-gost`, `vite-frontend`) instead of `apps/`/`libs/`.
|
||||||
|
- **Asymmetric Go Layout**: `go-backend` follows `cmd/<app>/main.go` while `go-gost` uses `root/main.go`.
|
||||||
|
- **Frontend Hybrid Mode**: `App.tsx` detects "H5 mode" (mobile WebView) vs desktop, dictating layout strategy.
|
||||||
|
|
||||||
## NOTES
|
## NOTES
|
||||||
- LSP servers are not installed in this environment (gopls/jdtls/typescript-language-server); rely on grep-based navigation.
|
- LSP servers are not installed in this environment (gopls/jdtls/typescript-language-server); rely on grep-based navigation.
|
||||||
- `vite-frontend/vite.config.ts` sets `minify: false` and disables treeshake; expect larger bundles.
|
- `vite-frontend/vite.config.ts` sets `minify: false` and disables treeshake; expect larger bundles.
|
||||||
|
- `vite-frontend` uses `rolldown-vite` (experimental Rust bundler) instead of standard Vite.
|
||||||
|
- Install scripts (`install.sh`, `panel_install.sh`) self-delete after execution - common pattern in one-liner installs.
|
||||||
|
- CI uses UPX compression (`--best --lzma`) on Go binaries before release.
|
||||||
|
- CI dynamically injects `PINNED_VERSION` into install scripts and docker-compose files during releases.
|
||||||
|
- `panel_install.sh` auto-detects IPv6 and modifies `/etc/docker/daemon.json` to enable IPv6 bridge.
|
||||||
|
- Download proxy `https://gcode.hostcentral.cc/` used for GitHub downloads in China/restricted environments.
|
||||||
|
- Backend has contract tests in `go-backend/tests/contract/` - frontend has no test infrastructure (Vitest/Jest not configured).
|
||||||
|
- `analysis/3x-ui/` contains a separate git repo for reference/comparison - not part of FLVX core.
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ curl -L https://github.com/Sagit-chu/flux-panel/releases/download/2.1.0/install.
|
|||||||
|
|
||||||
#### PostgreSQL 部署(Docker Compose)
|
#### PostgreSQL 部署(Docker Compose)
|
||||||
|
|
||||||
`docker-compose-v4.yml` / `docker-compose-v6.yml` 已包含 PostgreSQL 服务。默认仍使用 SQLite,切换到 PostgreSQL 只需要配置环境变量。
|
安装脚本会根据环境自动下载对应的 Compose 配置并保存为 `docker-compose.yml`。默认仍使用 SQLite,切换到 PostgreSQL 只需要配置环境变量。
|
||||||
|
|
||||||
1) 在 `docker-compose` 同目录创建或修改 `.env`:
|
1) 在 `docker-compose` 同目录创建或修改 `.env`:
|
||||||
|
|
||||||
@@ -61,47 +61,56 @@ POSTGRES_USER=flux_panel
|
|||||||
POSTGRES_PASSWORD=replace_with_strong_password
|
POSTGRES_PASSWORD=replace_with_strong_password
|
||||||
```
|
```
|
||||||
|
|
||||||
2) 启动(IPv4/IPv6 二选一):
|
> 📌 使用安装脚本部署时,`POSTGRES_PASSWORD` 会自动随机生成并写入 `.env`。
|
||||||
|
|
||||||
|
2) 启动服务:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose -f docker-compose-v4.yml up -d
|
docker compose up -d
|
||||||
```
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose -f docker-compose-v6.yml up -d
|
|
||||||
```
|
```
|
||||||
|
|
||||||
3) 如果你想继续使用 SQLite,保留 `DB_TYPE=sqlite`(或不设置 `DB_TYPE`)即可。
|
3) 如果你想继续使用 SQLite,保留 `DB_TYPE=sqlite`(或不设置 `DB_TYPE`)即可。
|
||||||
|
|
||||||
#### 从 SQLite 迁移到 PostgreSQL
|
#### 从 SQLite 迁移到 PostgreSQL
|
||||||
|
|
||||||
以下示例基于 Docker Volume `sqlite_data`(项目默认配置)与 `pgloader`:
|
如果你是通过 `panel_install.sh` 安装面板,推荐直接使用脚本菜单一键迁移:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./panel_install.sh
|
||||||
|
# 选择 4. 迁移到 PostgreSQL
|
||||||
|
```
|
||||||
|
|
||||||
|
脚本会自动完成 SQLite 备份、PostgreSQL 启动、`pgloader` 导入、`.env` 中 `DB_TYPE`/`DATABASE_URL` 更新,并重启服务。
|
||||||
|
|
||||||
|
如果你希望手动迁移,以下示例基于 Docker Volume `sqlite_data`(项目默认配置)与 `pgloader`:
|
||||||
|
|
||||||
1) 停止服务并备份 SQLite 数据:
|
1) 停止服务并备份 SQLite 数据:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose -f docker-compose-v4.yml down
|
docker compose down
|
||||||
docker run --rm -v sqlite_data:/data -v "$(pwd)":/backup alpine sh -c "cp /data/gost.db /backup/gost.db.bak"
|
docker run --rm -v sqlite_data:/data -v "$(pwd)":/backup alpine sh -c "cp /data/gost.db /backup/gost.db.bak"
|
||||||
```
|
```
|
||||||
|
|
||||||
2) 仅启动 PostgreSQL:
|
2) 仅启动 PostgreSQL:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose -f docker-compose-v4.yml up -d postgres
|
docker compose up -d postgres
|
||||||
```
|
```
|
||||||
|
|
||||||
3) 使用 `pgloader` 迁移:
|
3) 使用 `pgloader` 迁移:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker run --rm --network gost-network -v sqlite_data:/sqlite dimitri/pgloader:latest pgloader /sqlite/gost.db postgresql://flux_panel:replace_with_strong_password@postgres:5432/flux_panel
|
source .env
|
||||||
|
docker run --rm --network gost-network -v sqlite_data:/sqlite dimitri/pgloader:latest pgloader /sqlite/gost.db "postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}"
|
||||||
```
|
```
|
||||||
|
|
||||||
4) 切换后端到 PostgreSQL 并启动:
|
4) 切换后端到 PostgreSQL 并启动:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
source .env
|
||||||
export DB_TYPE=postgres
|
export DB_TYPE=postgres
|
||||||
export DATABASE_URL="postgres://flux_panel:replace_with_strong_password@postgres:5432/flux_panel?sslmode=disable"
|
export DATABASE_URL="postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}?sslmode=disable"
|
||||||
docker compose -f docker-compose-v4.yml up -d
|
docker compose up -d
|
||||||
```
|
```
|
||||||
|
|
||||||
5) 迁移完成后,登录面板检查用户、隧道、转发、节点数据是否正确。
|
5) 迁移完成后,登录面板检查用户、隧道、转发、节点数据是否正确。
|
||||||
@@ -138,7 +147,7 @@ The following major changes and additions have been made in this fork (FLVX):
|
|||||||
- **Removed**: `ios-app/` - Source code for the iOS client.
|
- **Removed**: `ios-app/` - Source code for the iOS client.
|
||||||
|
|
||||||
### 5. Infrastructure & Scripts
|
### 5. Infrastructure & Scripts
|
||||||
- **Modified**: `docker-compose-v4.yml`, `docker-compose-v6.yml` (Updated for Go backend).
|
- **Modified**: `docker-compose.yml` (installer output name, auto-selects IPv4/IPv6 template, updated for Go backend).
|
||||||
- **Modified**: `install.sh`, `panel_install.sh` (Updated installation logic).
|
- **Modified**: `install.sh`, `panel_install.sh` (Updated installation logic).
|
||||||
- **Added**: `AGENTS.md` (Project documentation).
|
- **Added**: `AGENTS.md` (Project documentation).
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -24,7 +24,7 @@
|
|||||||
**A**: 面板安装脚本会自动尝试配置 Docker 的 IPv6。如果失败,请手动检查 `/etc/docker/daemon.json` 配置,确保 `ipv6: true` 且分配了正确的 `fixed-cidr-v6` 子网。
|
**A**: 面板安装脚本会自动尝试配置 Docker 的 IPv6。如果失败,请手动检查 `/etc/docker/daemon.json` 配置,确保 `ipv6: true` 且分配了正确的 `fixed-cidr-v6` 子网。
|
||||||
|
|
||||||
### Q6: 如何切换到 PostgreSQL?
|
### Q6: 如何切换到 PostgreSQL?
|
||||||
**A**: 在 `.env` 文件中设置 `DB_TYPE=postgres` 并填写相关配置,然后重启服务即可。各变量默认值:`DATABASE_URL=postgres://flux_panel:replace_with_strong_password@postgres:5432/flux_panel?sslmode=disable`、`POSTGRES_DB=flux_panel`、`POSTGRES_USER=flux_panel`,`POSTGRES_PASSWORD` 需自行设置强密码。详见 [PostgreSQL 数据库指南](./postgresql.md)。
|
**A**: 在 `.env` 文件中设置 `DB_TYPE=postgres`,并让 `DATABASE_URL` 与 `POSTGRES_*` 保持一致,然后执行 `docker compose up -d` 重启服务即可。使用安装脚本部署时,`POSTGRES_PASSWORD` 会自动随机生成并写入 `.env`。详见 [PostgreSQL 数据库指南](./postgresql.md)。
|
||||||
|
|
||||||
### Q7: 从 SQLite 迁移到 PostgreSQL 后数据丢失?
|
### Q7: 从 SQLite 迁移到 PostgreSQL 后数据丢失?
|
||||||
**A**:
|
**A**:
|
||||||
|
|||||||
@@ -41,6 +41,8 @@ curl -L https://raw.githubusercontent.com/Sagit-chu/flux-panel/main/panel_instal
|
|||||||
1. 安装面板
|
1. 安装面板
|
||||||
2. 更新面板
|
2. 更新面板
|
||||||
3. 卸载面板
|
3. 卸载面板
|
||||||
|
4. 迁移到 PostgreSQL
|
||||||
|
5. 退出
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+30
-14
@@ -42,7 +42,7 @@ FLVX 默认使用 SQLite 作为数据库,同时也内置了对 PostgreSQL 的
|
|||||||
|
|
||||||
## 三、全新部署(Docker Compose + PostgreSQL)
|
## 三、全新部署(Docker Compose + PostgreSQL)
|
||||||
|
|
||||||
`docker-compose-v4.yml` / `docker-compose-v6.yml` 已包含 PostgreSQL 服务,默认使用 SQLite。只需配置环境变量即可切换到 PostgreSQL。
|
安装脚本会根据环境自动下载对应的 Compose 配置并保存为 `docker-compose.yml`。默认使用 SQLite,只需配置环境变量即可切换到 PostgreSQL。
|
||||||
|
|
||||||
### 1. 创建 `.env` 文件
|
### 1. 创建 `.env` 文件
|
||||||
|
|
||||||
@@ -67,14 +67,8 @@ POSTGRES_PASSWORD=替换为强密码
|
|||||||
|
|
||||||
### 2. 启动服务
|
### 2. 启动服务
|
||||||
|
|
||||||
IPv4 环境:
|
|
||||||
```bash
|
```bash
|
||||||
docker compose -f docker-compose-v4.yml up -d
|
docker compose up -d
|
||||||
```
|
|
||||||
|
|
||||||
IPv6 环境:
|
|
||||||
```bash
|
|
||||||
docker compose -f docker-compose-v6.yml up -d
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. 验证
|
### 3. 验证
|
||||||
@@ -96,11 +90,29 @@ docker logs flux-panel-postgres
|
|||||||
|
|
||||||
如果你已经在使用 SQLite 并且希望迁移到 PostgreSQL,请按照以下步骤操作。
|
如果你已经在使用 SQLite 并且希望迁移到 PostgreSQL,请按照以下步骤操作。
|
||||||
|
|
||||||
|
### 快速方式:脚本菜单一键迁移(推荐)
|
||||||
|
|
||||||
|
如果你是通过安装脚本部署面板,可直接执行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./panel_install.sh
|
||||||
|
# 选择 4. 迁移到 PostgreSQL
|
||||||
|
```
|
||||||
|
|
||||||
|
脚本会自动完成以下操作:
|
||||||
|
- 备份 SQLite 数据到当前目录(`gost.db.bak`)
|
||||||
|
- 启动并等待 PostgreSQL 健康检查通过
|
||||||
|
- 使用 `pgloader` 导入 SQLite 数据
|
||||||
|
- 自动写入 `.env` 的 `DB_TYPE=postgres` 与 `DATABASE_URL`
|
||||||
|
- 重启服务并等待后端健康检查
|
||||||
|
|
||||||
|
### 手动方式:按步骤迁移
|
||||||
|
|
||||||
### 1. 备份 SQLite 数据
|
### 1. 备份 SQLite 数据
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 停止所有服务
|
# 停止所有服务
|
||||||
docker compose -f docker-compose-v4.yml down
|
docker compose down
|
||||||
|
|
||||||
# 备份 SQLite 数据文件到当前目录
|
# 备份 SQLite 数据文件到当前目录
|
||||||
docker run --rm -v sqlite_data:/data -v "$(pwd)":/backup alpine sh -c "cp /data/gost.db /backup/gost.db.bak"
|
docker run --rm -v sqlite_data:/data -v "$(pwd)":/backup alpine sh -c "cp /data/gost.db /backup/gost.db.bak"
|
||||||
@@ -113,7 +125,7 @@ docker run --rm -v sqlite_data:/data -v "$(pwd)":/backup alpine sh -c "cp /data/
|
|||||||
### 3. 仅启动 PostgreSQL
|
### 3. 仅启动 PostgreSQL
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose -f docker-compose-v4.yml up -d postgres
|
docker compose up -d postgres
|
||||||
```
|
```
|
||||||
|
|
||||||
等待 PostgreSQL 完全就绪:
|
等待 PostgreSQL 完全就绪:
|
||||||
@@ -127,19 +139,23 @@ docker inspect --format='{{.State.Health.Status}}' flux-panel-postgres
|
|||||||
### 4. 使用 pgloader 迁移数据
|
### 4. 使用 pgloader 迁移数据
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
source .env
|
||||||
docker run --rm \
|
docker run --rm \
|
||||||
--network gost-network \
|
--network gost-network \
|
||||||
-v sqlite_data:/sqlite \
|
-v sqlite_data:/sqlite \
|
||||||
dimitri/pgloader:latest \
|
dimitri/pgloader:latest \
|
||||||
pgloader /sqlite/gost.db postgresql://flux_panel:你的密码@postgres:5432/flux_panel
|
pgloader /sqlite/gost.db "postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}"
|
||||||
```
|
```
|
||||||
|
|
||||||
> 📌 将 `你的密码` 替换为实际的 `POSTGRES_PASSWORD`。
|
> 📌 建议直接从 `.env` 读取 `POSTGRES_USER`、`POSTGRES_PASSWORD`、`POSTGRES_DB`,避免手填密码导致认证失败。
|
||||||
|
|
||||||
### 5. 启动全部服务
|
### 5. 启动全部服务
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose -f docker-compose-v4.yml up -d
|
source .env
|
||||||
|
export DB_TYPE=postgres
|
||||||
|
export DATABASE_URL="postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}?sslmode=disable"
|
||||||
|
docker compose up -d
|
||||||
```
|
```
|
||||||
|
|
||||||
### 6. 验证迁移
|
### 6. 验证迁移
|
||||||
@@ -182,7 +198,7 @@ DATABASE_URL=postgres://flux_panel:你的强密码@数据库地址:5432/flux_pan
|
|||||||
如果使用外部 PostgreSQL,可以在启动时不启动内置的 postgres 服务:
|
如果使用外部 PostgreSQL,可以在启动时不启动内置的 postgres 服务:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose -f docker-compose-v4.yml up -d backend frontend
|
docker compose up -d backend frontend
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -7,18 +7,17 @@ services:
|
|||||||
driver: json-file
|
driver: json-file
|
||||||
options:
|
options:
|
||||||
max-size: "20m"
|
max-size: "20m"
|
||||||
|
max-file: "3"
|
||||||
environment:
|
environment:
|
||||||
DB_TYPE: ${DB_TYPE:-sqlite}
|
DB_TYPE: ${DB_TYPE:-sqlite}
|
||||||
DB_PATH: /app/data/gost.db
|
DB_PATH: /app/data/gost.db
|
||||||
DATABASE_URL: ${DATABASE_URL:-}
|
DATABASE_URL: ${DATABASE_URL:-}
|
||||||
JWT_SECRET: ${JWT_SECRET}
|
JWT_SECRET: ${JWT_SECRET}
|
||||||
LOG_DIR: /app/logs
|
|
||||||
SERVER_ADDR: :6365
|
SERVER_ADDR: :6365
|
||||||
TZ: Asia/Shanghai
|
TZ: Asia/Shanghai
|
||||||
ports:
|
ports:
|
||||||
- "${BACKEND_PORT}:6365"
|
- "${BACKEND_PORT}:6365"
|
||||||
volumes:
|
volumes:
|
||||||
- backend_logs:/app/logs
|
|
||||||
- sqlite_data:/app/data
|
- sqlite_data:/app/data
|
||||||
networks:
|
networks:
|
||||||
- gost-network
|
- gost-network
|
||||||
@@ -63,6 +62,7 @@ services:
|
|||||||
driver: json-file
|
driver: json-file
|
||||||
options:
|
options:
|
||||||
max-size: "20m"
|
max-size: "20m"
|
||||||
|
max-file: "3"
|
||||||
ports:
|
ports:
|
||||||
- "${FRONTEND_PORT}:80"
|
- "${FRONTEND_PORT}:80"
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -79,9 +79,6 @@ volumes:
|
|||||||
postgres_data:
|
postgres_data:
|
||||||
name: postgres_data
|
name: postgres_data
|
||||||
driver: local
|
driver: local
|
||||||
backend_logs:
|
|
||||||
name: backend_logs
|
|
||||||
driver: local
|
|
||||||
|
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
@@ -90,4 +87,4 @@ networks:
|
|||||||
driver: bridge
|
driver: bridge
|
||||||
ipam:
|
ipam:
|
||||||
config:
|
config:
|
||||||
- subnet: 172.20.0.0/16
|
- subnet: 172.80.0.0/16
|
||||||
|
|||||||
@@ -7,18 +7,17 @@ services:
|
|||||||
driver: json-file
|
driver: json-file
|
||||||
options:
|
options:
|
||||||
max-size: "20m"
|
max-size: "20m"
|
||||||
|
max-file: "3"
|
||||||
environment:
|
environment:
|
||||||
DB_TYPE: ${DB_TYPE:-sqlite}
|
DB_TYPE: ${DB_TYPE:-sqlite}
|
||||||
DB_PATH: /app/data/gost.db
|
DB_PATH: /app/data/gost.db
|
||||||
DATABASE_URL: ${DATABASE_URL:-}
|
DATABASE_URL: ${DATABASE_URL:-}
|
||||||
JWT_SECRET: ${JWT_SECRET}
|
JWT_SECRET: ${JWT_SECRET}
|
||||||
LOG_DIR: /app/logs
|
|
||||||
SERVER_ADDR: :6365
|
SERVER_ADDR: :6365
|
||||||
TZ: Asia/Shanghai
|
TZ: Asia/Shanghai
|
||||||
ports:
|
ports:
|
||||||
- "${BACKEND_PORT}:6365"
|
- "${BACKEND_PORT}:6365"
|
||||||
volumes:
|
volumes:
|
||||||
- backend_logs:/app/logs
|
|
||||||
- sqlite_data:/app/data
|
- sqlite_data:/app/data
|
||||||
networks:
|
networks:
|
||||||
- gost-network
|
- gost-network
|
||||||
@@ -63,6 +62,7 @@ services:
|
|||||||
driver: json-file
|
driver: json-file
|
||||||
options:
|
options:
|
||||||
max-size: "20m"
|
max-size: "20m"
|
||||||
|
max-file: "3"
|
||||||
ports:
|
ports:
|
||||||
- "${FRONTEND_PORT}:80"
|
- "${FRONTEND_PORT}:80"
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -79,9 +79,6 @@ volumes:
|
|||||||
postgres_data:
|
postgres_data:
|
||||||
name: postgres_data
|
name: postgres_data
|
||||||
driver: local
|
driver: local
|
||||||
backend_logs:
|
|
||||||
name: backend_logs
|
|
||||||
driver: local
|
|
||||||
|
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
@@ -91,5 +88,5 @@ networks:
|
|||||||
enable_ipv6: true
|
enable_ipv6: true
|
||||||
ipam:
|
ipam:
|
||||||
config:
|
config:
|
||||||
- subnet: 172.20.0.0/16
|
- subnet: 172.80.0.0/16
|
||||||
- subnet: fd00:dead:beef::/48
|
- subnet: fd00:dead:beef::/48
|
||||||
|
|||||||
+10
-3
@@ -1,8 +1,8 @@
|
|||||||
# GO BACKEND KNOWLEDGE BASE
|
# GO BACKEND KNOWLEDGE BASE
|
||||||
|
|
||||||
## OVERVIEW
|
## OVERVIEW
|
||||||
Go-based Admin API for FLVX (formerly Flux Panel). Replaces the legacy Spring Boot backend.
|
Go-based Admin API for FLVX. Replaced legacy Spring Boot backend.
|
||||||
**Stack:** Go 1.23, net/http (std lib), SQLite (modernc.org/sqlite).
|
**Stack:** Go 1.23, net/http (std lib), SQLite/PostgreSQL (modernc.org/sqlite - CGO-free).
|
||||||
|
|
||||||
## STRUCTURE
|
## STRUCTURE
|
||||||
```
|
```
|
||||||
@@ -34,14 +34,21 @@ go-backend/
|
|||||||
|
|
||||||
## CONVENTIONS
|
## CONVENTIONS
|
||||||
- **No ORM**: Uses raw SQL with `database/sql` and `modernc.org/sqlite`.
|
- **No ORM**: Uses raw SQL with `database/sql` and `modernc.org/sqlite`.
|
||||||
|
- **CGO-Free SQLite**: `modernc.org/sqlite` instead of `mattn/go-sqlite3` - builds without CGO.
|
||||||
- **Standard Lib**: Uses `net/http` for routing (Go 1.22+ patterns).
|
- **Standard Lib**: Uses `net/http` for routing (Go 1.22+ patterns).
|
||||||
- **Auth**: Expects raw JWT in `Authorization` header (no `Bearer` prefix).
|
- **Auth**: Expects raw JWT in `Authorization` header (no `Bearer` prefix).
|
||||||
|
- **API Envelope**: All responses use `response.R{code, msg, data, ts}` structure.
|
||||||
- **Config**: Loaded from environment variables (see `cmd/paneld/main.go`).
|
- **Config**: Loaded from environment variables (see `cmd/paneld/main.go`).
|
||||||
|
- **SQL Idempotency**: Prefer `ON CONFLICT DO NOTHING` for inserts in migrations/sync.
|
||||||
|
|
||||||
|
## ANTI-PATTERNS
|
||||||
|
- **DO NOT USE** ORM - uses raw SQL throughout.
|
||||||
|
- **DO NOT CHANGE** handler signatures without updating `router.go`.
|
||||||
|
|
||||||
## COMMANDS
|
## COMMANDS
|
||||||
```bash
|
```bash
|
||||||
cd go-backend
|
cd go-backend
|
||||||
go run ./cmd/paneld
|
go run ./cmd/paneld # Default: SERVER_ADDR=:6365
|
||||||
go test ./...
|
go test ./...
|
||||||
make build
|
make build
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -77,6 +77,18 @@ type RuntimeDiagnoseRequest struct {
|
|||||||
Timeout int `json:"timeout"`
|
Timeout int `json:"timeout"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type RuntimeNodeCommandRequest struct {
|
||||||
|
CommandType string `json:"commandType"`
|
||||||
|
Data interface{} `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RuntimeNodeCommandResponse struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Success bool `json:"success"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data map[string]interface{} `json:"data,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
func NewFederationClient() *FederationClient {
|
func NewFederationClient() *FederationClient {
|
||||||
return &FederationClient{
|
return &FederationClient{
|
||||||
client: &http.Client{
|
client: &http.Client{
|
||||||
@@ -333,3 +345,42 @@ func (c *FederationClient) Diagnose(url, token, localDomain string, reqData Runt
|
|||||||
|
|
||||||
return res.Data, nil
|
return res.Data, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *FederationClient) Command(url, token, localDomain string, reqData RuntimeNodeCommandRequest) (*RuntimeNodeCommandResponse, error) {
|
||||||
|
url = strings.TrimSuffix(url, "/")
|
||||||
|
bodyBytes, _ := json.Marshal(reqData)
|
||||||
|
req, err := http.NewRequest("POST", url+"/api/v1/federation/runtime/command", strings.NewReader(string(bodyBytes)))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
if localDomain != "" {
|
||||||
|
req.Header.Set("X-Panel-Domain", localDomain)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
resp, err := c.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
return nil, fmt.Errorf("remote error %d: %s", resp.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
var res struct {
|
||||||
|
Code int `json:"code"`
|
||||||
|
Msg string `json:"msg"`
|
||||||
|
Data RuntimeNodeCommandResponse `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if res.Code != 0 {
|
||||||
|
return nil, fmt.Errorf("remote api error: %s", res.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &res.Data, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# BACKEND HTTP HANDLER KNOWLEDGE BASE
|
||||||
|
|
||||||
|
**Generated:** Sun Feb 15 2026
|
||||||
|
|
||||||
|
## OVERVIEW
|
||||||
|
HTTP request handlers for FLVX Admin API. Core business logic layer.
|
||||||
|
**Stack:** Go 1.23, net/http, raw SQL (no ORM).
|
||||||
|
|
||||||
|
## STRUCTURE
|
||||||
|
```
|
||||||
|
handler/
|
||||||
|
├── handler.go # Main Handler struct, login/captcha, job scheduling
|
||||||
|
├── control_plane.go # Node control plane API (add/delete/list)
|
||||||
|
├── federation.go # Federation/cluster sync API
|
||||||
|
├── flow_policy.go # Traffic policy API
|
||||||
|
├── jobs.go # Background job management (sync, cleanup)
|
||||||
|
├── mutations.go # CRUD for users, tunnels, forwards (largest: 100k+ LOC)
|
||||||
|
└── upgrade.go # System upgrade API
|
||||||
|
```
|
||||||
|
|
||||||
|
## WHERE TO LOOK
|
||||||
|
| Task | Location | Notes |
|
||||||
|
|------|----------|-------|
|
||||||
|
| **User/Tunnel CRUD** | `mutations.go` | Largest file; all create/update/delete ops |
|
||||||
|
| **Login/Captcha** | `handler.go` | Login flow, captcha verification |
|
||||||
|
| **Federation Sync** | `federation.go` | Panel-to-panel sync |
|
||||||
|
| **Traffic Policies** | `flow_policy.go` | Flow limiting, quota management |
|
||||||
|
| **Background Jobs** | `jobs.go` | Scheduled sync/cleanup tasks |
|
||||||
|
|
||||||
|
## CONVENTIONS
|
||||||
|
- Inherits from parent: raw SQL, no ORM, JWT in Authorization header.
|
||||||
|
- Large files expected (`mutations.go` 3716 LOC - central mutation hub).
|
||||||
|
- Uses `sqlite.Repository` for DB access via `repo.XXX()` methods.
|
||||||
|
- Domain-driven file split: one file per functional area (federation, jobs, etc.).
|
||||||
|
|
||||||
|
## ANTI-PATTERNS
|
||||||
|
- Do NOT add ORM here - uses raw SQL throughout.
|
||||||
|
- Do NOT change handler signatures without updating router.go.
|
||||||
|
|
||||||
|
## COMMANDS
|
||||||
|
```bash
|
||||||
|
cd go-backend
|
||||||
|
go test ./internal/http/handler/...
|
||||||
|
```
|
||||||
@@ -114,7 +114,7 @@ func (h *Handler) ensureTunnelPermission(userID int64, roleID int, tunnelID int6
|
|||||||
|
|
||||||
func (h *Handler) getForwardRecord(forwardID int64) (*forwardRecord, error) {
|
func (h *Handler) getForwardRecord(forwardID int64) (*forwardRecord, error) {
|
||||||
row := h.repo.DB().QueryRow(`
|
row := h.repo.DB().QueryRow(`
|
||||||
SELECT id, user_id, user_name, name, tunnel_id, remote_addr, strategy, status
|
SELECT id, user_id, user_name, name, tunnel_id, remote_addr, COALESCE(strategy, 'fifo'), status
|
||||||
FROM forward WHERE id = ? LIMIT 1
|
FROM forward WHERE id = ? LIMIT 1
|
||||||
`, forwardID)
|
`, forwardID)
|
||||||
var fr forwardRecord
|
var fr forwardRecord
|
||||||
@@ -152,7 +152,7 @@ func (h *Handler) getTunnelRecord(tunnelID int64) (*tunnelRecord, error) {
|
|||||||
|
|
||||||
func (h *Handler) listForwardsByTunnel(tunnelID int64) ([]forwardRecord, error) {
|
func (h *Handler) listForwardsByTunnel(tunnelID int64) ([]forwardRecord, error) {
|
||||||
rows, err := h.repo.DB().Query(`
|
rows, err := h.repo.DB().Query(`
|
||||||
SELECT id, user_id, user_name, name, tunnel_id, remote_addr, strategy, status
|
SELECT id, user_id, user_name, name, tunnel_id, remote_addr, COALESCE(strategy, 'fifo'), status
|
||||||
FROM forward
|
FROM forward
|
||||||
WHERE tunnel_id = ?
|
WHERE tunnel_id = ?
|
||||||
ORDER BY id ASC
|
ORDER BY id ASC
|
||||||
@@ -200,6 +200,26 @@ func (h *Handler) listForwardPorts(forwardID int64) ([]forwardPortRecord, error)
|
|||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *Handler) isTunnelSelectedTLSProtocol(tunnelID int64) (bool, error) {
|
||||||
|
row := h.repo.DB().QueryRow(`
|
||||||
|
SELECT protocol
|
||||||
|
FROM chain_tunnel
|
||||||
|
WHERE tunnel_id = ? AND chain_type = '3'
|
||||||
|
ORDER BY id ASC
|
||||||
|
LIMIT 1
|
||||||
|
`, tunnelID)
|
||||||
|
|
||||||
|
var protocol sql.NullString
|
||||||
|
if err := row.Scan(&protocol); err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return isTLSTunnelProtocol(protocol.String), nil
|
||||||
|
}
|
||||||
|
|
||||||
func (h *Handler) getNodeRecord(nodeID int64) (*nodeRecord, error) {
|
func (h *Handler) getNodeRecord(nodeID int64) (*nodeRecord, error) {
|
||||||
row := h.repo.DB().QueryRow(`
|
row := h.repo.DB().QueryRow(`
|
||||||
SELECT id, name, server_ip, server_ip_v4, server_ip_v6, status, port, tcp_listen_addr, udp_listen_addr, interface_name, is_remote, remote_url, remote_token, remote_config
|
SELECT id, name, server_ip, server_ip_v4, server_ip_v6, status, port, tcp_listen_addr, udp_listen_addr, interface_name, is_remote, remote_url, remote_token, remote_config
|
||||||
@@ -346,6 +366,10 @@ func (h *Handler) syncForwardServices(forward *forwardRecord, method string, all
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
serviceBase := buildForwardServiceBase(forward.ID, forward.UserID, userTunnelID)
|
serviceBase := buildForwardServiceBase(forward.ID, forward.UserID, userTunnelID)
|
||||||
|
tunnelTLSProtocol, err := h.isTunnelSelectedTLSProtocol(forward.TunnelID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
for _, fp := range ports {
|
for _, fp := range ports {
|
||||||
if limiterID != nil && speed != nil {
|
if limiterID != nil && speed != nil {
|
||||||
@@ -356,7 +380,7 @@ func (h *Handler) syncForwardServices(forward *forwardRecord, method string, all
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
services := buildForwardServiceConfigs(serviceBase, forward, tunnel, node, fp.Port, limiterID)
|
services := buildForwardServiceConfigs(serviceBase, forward, tunnel, node, fp.Port, limiterID, tunnelTLSProtocol)
|
||||||
_, err = h.sendNodeCommand(node.ID, method, services, true, false)
|
_, err = h.sendNodeCommand(node.ID, method, services, true, false)
|
||||||
if err != nil && allowFallbackAdd && method == "UpdateService" {
|
if err != nil && allowFallbackAdd && method == "UpdateService" {
|
||||||
_, err = h.sendNodeCommand(node.ID, "AddService", services, true, false)
|
_, err = h.sendNodeCommand(node.ID, "AddService", services, true, false)
|
||||||
@@ -457,7 +481,17 @@ func (h *Handler) applyNodeProtocolChange(nodeID int64, httpVal, tlsVal, socksVa
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) sendNodeCommand(nodeID int64, commandType string, data interface{}, tolerateExists bool, tolerateNotFound bool) (ws.CommandResult, error) {
|
func (h *Handler) sendNodeCommand(nodeID int64, commandType string, data interface{}, tolerateExists bool, tolerateNotFound bool) (ws.CommandResult, error) {
|
||||||
result, err := h.wsServer.SendCommand(nodeID, commandType, data, 12*time.Second)
|
var (
|
||||||
|
result ws.CommandResult
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
|
||||||
|
node, nodeErr := h.getNodeRecord(nodeID)
|
||||||
|
if nodeErr == nil && node != nil && node.IsRemote == 1 {
|
||||||
|
result, err = h.sendRemoteNodeCommand(node, commandType, data)
|
||||||
|
} else {
|
||||||
|
result, err = h.wsServer.SendCommand(nodeID, commandType, data, 12*time.Second)
|
||||||
|
}
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
@@ -475,6 +509,44 @@ func (h *Handler) sendNodeCommand(nodeID int64, commandType string, data interfa
|
|||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *Handler) sendRemoteNodeCommand(node *nodeRecord, commandType string, data interface{}) (ws.CommandResult, error) {
|
||||||
|
if node == nil {
|
||||||
|
return ws.CommandResult{}, errors.New("节点不存在")
|
||||||
|
}
|
||||||
|
remoteURL := strings.TrimSpace(node.RemoteURL)
|
||||||
|
remoteToken := strings.TrimSpace(node.RemoteToken)
|
||||||
|
if remoteURL == "" || remoteToken == "" {
|
||||||
|
return ws.CommandResult{}, errors.New("远程节点缺少共享配置")
|
||||||
|
}
|
||||||
|
|
||||||
|
fc := client.NewFederationClient()
|
||||||
|
res, err := fc.Command(remoteURL, remoteToken, h.federationLocalDomain(), client.RuntimeNodeCommandRequest{
|
||||||
|
CommandType: commandType,
|
||||||
|
Data: data,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return ws.CommandResult{}, err
|
||||||
|
}
|
||||||
|
if res == nil {
|
||||||
|
return ws.CommandResult{}, errors.New("远程节点未返回命令结果")
|
||||||
|
}
|
||||||
|
|
||||||
|
result := ws.CommandResult{
|
||||||
|
Type: res.Type,
|
||||||
|
Success: res.Success,
|
||||||
|
Message: res.Message,
|
||||||
|
Data: res.Data,
|
||||||
|
}
|
||||||
|
if !result.Success {
|
||||||
|
msg := strings.TrimSpace(result.Message)
|
||||||
|
if msg == "" {
|
||||||
|
msg = "命令执行失败"
|
||||||
|
}
|
||||||
|
return result, errors.New(msg)
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (h *Handler) diagnoseForwardRuntime(forward *forwardRecord) (map[string]interface{}, error) {
|
func (h *Handler) diagnoseForwardRuntime(forward *forwardRecord) (map[string]interface{}, error) {
|
||||||
if forward == nil {
|
if forward == nil {
|
||||||
return nil, errForwardNotFound
|
return nil, errForwardNotFound
|
||||||
@@ -889,11 +961,11 @@ func firstPortFromRange(portRange string) int {
|
|||||||
|
|
||||||
func (h *Handler) listChainNodesForTunnel(tunnelID int64) ([]chainNodeRecord, error) {
|
func (h *Handler) listChainNodesForTunnel(tunnelID int64) ([]chainNodeRecord, error) {
|
||||||
rows, err := h.repo.DB().Query(`
|
rows, err := h.repo.DB().Query(`
|
||||||
SELECT ct.chain_type, COALESCE(ct.inx, 0), ct.node_id, COALESCE(ct.port, 0), n.name, ct.protocol, ct.strategy
|
SELECT CAST(ct.chain_type AS INTEGER), COALESCE(ct.inx, 0), ct.node_id, COALESCE(ct.port, 0), n.name, ct.protocol, ct.strategy
|
||||||
FROM chain_tunnel ct
|
FROM chain_tunnel ct
|
||||||
LEFT JOIN node n ON n.id = ct.node_id
|
LEFT JOIN node n ON n.id = ct.node_id
|
||||||
WHERE ct.tunnel_id = ?
|
WHERE ct.tunnel_id = ?
|
||||||
ORDER BY ct.chain_type ASC, COALESCE(ct.inx, 0) ASC, ct.id ASC
|
ORDER BY CAST(ct.chain_type AS INTEGER) ASC, COALESCE(ct.inx, 0) ASC, ct.id ASC
|
||||||
`, tunnelID)
|
`, tunnelID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -1047,7 +1119,7 @@ func isNotFoundError(err error) bool {
|
|||||||
return strings.Contains(msg, "not found") || strings.Contains(msg, "不存在")
|
return strings.Contains(msg, "not found") || strings.Contains(msg, "不存在")
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildForwardServiceConfigs(baseName string, forward *forwardRecord, tunnel *tunnelRecord, node *nodeRecord, port int, limiterID *int64) []map[string]interface{} {
|
func buildForwardServiceConfigs(baseName string, forward *forwardRecord, tunnel *tunnelRecord, node *nodeRecord, port int, limiterID *int64, tunnelTLSProtocol bool) []map[string]interface{} {
|
||||||
protocols := []string{"tcp", "udp"}
|
protocols := []string{"tcp", "udp"}
|
||||||
services := make([]map[string]interface{}, 0, 2)
|
services := make([]map[string]interface{}, 0, 2)
|
||||||
targets := splitRemoteTargets(forward.RemoteAddr)
|
targets := splitRemoteTargets(forward.RemoteAddr)
|
||||||
@@ -1080,7 +1152,11 @@ func buildForwardServiceConfigs(baseName string, forward *forwardRecord, tunnel
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
if protocol == "udp" {
|
if protocol == "udp" {
|
||||||
service["listener"].(map[string]interface{})["metadata"] = map[string]interface{}{"keepAlive": true}
|
listenerMetadata := map[string]interface{}{"keepAlive": true}
|
||||||
|
if tunnelTLSProtocol {
|
||||||
|
listenerMetadata["ttl"] = "10s"
|
||||||
|
}
|
||||||
|
service["listener"].(map[string]interface{})["metadata"] = listenerMetadata
|
||||||
}
|
}
|
||||||
if tunnel != nil && tunnel.Type == 2 {
|
if tunnel != nil && tunnel.Type == 2 {
|
||||||
service["handler"].(map[string]interface{})["chain"] = fmt.Sprintf("chains_%d", forward.TunnelID)
|
service["handler"].(map[string]interface{})["chain"] = fmt.Sprintf("chains_%d", forward.TunnelID)
|
||||||
|
|||||||
@@ -0,0 +1,377 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// nodeSupportsV4 / nodeSupportsV6
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func TestNodeSupportsV4_Nil(t *testing.T) {
|
||||||
|
if nodeSupportsV4(nil) {
|
||||||
|
t.Fatal("nil node must not support v4")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeSupportsV6_Nil(t *testing.T) {
|
||||||
|
if nodeSupportsV6(nil) {
|
||||||
|
t.Fatal("nil node must not support v6")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeSupportsV4_ExplicitV4(t *testing.T) {
|
||||||
|
n := &nodeRecord{ServerIPv4: "10.0.0.1"}
|
||||||
|
if !nodeSupportsV4(n) {
|
||||||
|
t.Fatal("explicit server_ip_v4 must support v4")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeSupportsV6_ExplicitV6(t *testing.T) {
|
||||||
|
n := &nodeRecord{ServerIPv6: "2001:db8::1"}
|
||||||
|
if !nodeSupportsV6(n) {
|
||||||
|
t.Fatal("explicit server_ip_v6 must support v6")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeSupportsV4_OnlyV6Set(t *testing.T) {
|
||||||
|
n := &nodeRecord{ServerIPv6: "2001:db8::1"}
|
||||||
|
if nodeSupportsV4(n) {
|
||||||
|
t.Fatal("node with only v6 should not support v4")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeSupportsV6_OnlyV4Set(t *testing.T) {
|
||||||
|
n := &nodeRecord{ServerIPv4: "10.0.0.1"}
|
||||||
|
if nodeSupportsV6(n) {
|
||||||
|
t.Fatal("node with only v4 should not support v6")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeSupportsV4_DualStack(t *testing.T) {
|
||||||
|
n := &nodeRecord{ServerIPv4: "10.0.0.1", ServerIPv6: "2001:db8::1"}
|
||||||
|
if !nodeSupportsV4(n) {
|
||||||
|
t.Fatal("dual-stack node must support v4")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeSupportsV6_DualStack(t *testing.T) {
|
||||||
|
n := &nodeRecord{ServerIPv4: "10.0.0.1", ServerIPv6: "2001:db8::1"}
|
||||||
|
if !nodeSupportsV6(n) {
|
||||||
|
t.Fatal("dual-stack node must support v6")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeSupportsV4_LegacyV4Only(t *testing.T) {
|
||||||
|
n := &nodeRecord{ServerIP: "192.168.1.1"}
|
||||||
|
if !nodeSupportsV4(n) {
|
||||||
|
t.Fatal("legacy v4 ip in server_ip must support v4")
|
||||||
|
}
|
||||||
|
if nodeSupportsV6(n) {
|
||||||
|
t.Fatal("legacy v4 ip in server_ip must not support v6")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeSupportsV6_LegacyV6Only(t *testing.T) {
|
||||||
|
n := &nodeRecord{ServerIP: "2001:db8::1"}
|
||||||
|
if !nodeSupportsV6(n) {
|
||||||
|
t.Fatal("legacy v6 ip in server_ip must support v6")
|
||||||
|
}
|
||||||
|
if nodeSupportsV4(n) {
|
||||||
|
t.Fatal("legacy v6 ip in server_ip must not support v4")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeSupportsV4_EmptyNode(t *testing.T) {
|
||||||
|
n := &nodeRecord{}
|
||||||
|
if nodeSupportsV4(n) {
|
||||||
|
t.Fatal("empty node must not support v4")
|
||||||
|
}
|
||||||
|
if nodeSupportsV6(n) {
|
||||||
|
t.Fatal("empty node must not support v6")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeSupportsV4_LegacyBracketed(t *testing.T) {
|
||||||
|
n := &nodeRecord{ServerIP: "[::1]"}
|
||||||
|
if nodeSupportsV4(n) {
|
||||||
|
t.Fatal("bracketed ipv6 must not support v4")
|
||||||
|
}
|
||||||
|
if !nodeSupportsV6(n) {
|
||||||
|
t.Fatal("bracketed ipv6 must support v6")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// pickNodeAddressV4 / pickNodeAddressV6
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func TestPickNodeAddressV4_Nil(t *testing.T) {
|
||||||
|
if pickNodeAddressV4(nil) != "" {
|
||||||
|
t.Fatal("nil node must return empty")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPickNodeAddressV6_Nil(t *testing.T) {
|
||||||
|
if pickNodeAddressV6(nil) != "" {
|
||||||
|
t.Fatal("nil node must return empty")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPickNodeAddressV4_PreferExplicit(t *testing.T) {
|
||||||
|
n := &nodeRecord{ServerIPv4: "10.0.0.1", ServerIP: "192.168.0.1"}
|
||||||
|
got := pickNodeAddressV4(n)
|
||||||
|
if got != "10.0.0.1" {
|
||||||
|
t.Fatalf("expected explicit v4 10.0.0.1, got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPickNodeAddressV4_FallbackLegacy(t *testing.T) {
|
||||||
|
n := &nodeRecord{ServerIP: "192.168.0.1"}
|
||||||
|
got := pickNodeAddressV4(n)
|
||||||
|
if got != "192.168.0.1" {
|
||||||
|
t.Fatalf("expected legacy 192.168.0.1, got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPickNodeAddressV6_PreferExplicit(t *testing.T) {
|
||||||
|
n := &nodeRecord{ServerIPv6: "2001:db8::1", ServerIP: "::1"}
|
||||||
|
got := pickNodeAddressV6(n)
|
||||||
|
if got != "2001:db8::1" {
|
||||||
|
t.Fatalf("expected explicit v6 2001:db8::1, got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPickNodeAddressV6_FallbackLegacy(t *testing.T) {
|
||||||
|
n := &nodeRecord{ServerIP: "::1"}
|
||||||
|
got := pickNodeAddressV6(n)
|
||||||
|
if got != "::1" {
|
||||||
|
t.Fatalf("expected legacy ::1, got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// selectTunnelDialHost — core IP preference selection logic
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func dualStackNode(name, v4, v6 string) *nodeRecord {
|
||||||
|
return &nodeRecord{
|
||||||
|
Name: name,
|
||||||
|
ServerIPv4: v4,
|
||||||
|
ServerIPv6: v6,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func v4OnlyNode(name, v4 string) *nodeRecord {
|
||||||
|
return &nodeRecord{
|
||||||
|
Name: name,
|
||||||
|
ServerIPv4: v4,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func v6OnlyNode(name, v6 string) *nodeRecord {
|
||||||
|
return &nodeRecord{
|
||||||
|
Name: name,
|
||||||
|
ServerIPv6: v6,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectTunnelDialHost_NilNodes(t *testing.T) {
|
||||||
|
_, err := selectTunnelDialHost(nil, nil, "")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for nil nodes")
|
||||||
|
}
|
||||||
|
_, err = selectTunnelDialHost(dualStackNode("a", "1.1.1.1", "::1"), nil, "")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for nil toNode")
|
||||||
|
}
|
||||||
|
_, err = selectTunnelDialHost(nil, dualStackNode("b", "1.1.1.1", "::1"), "")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for nil fromNode")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectTunnelDialHost_DualStack_DefaultPreference(t *testing.T) {
|
||||||
|
from := dualStackNode("from", "10.0.0.1", "2001:db8::1")
|
||||||
|
to := dualStackNode("to", "10.0.0.2", "2001:db8::2")
|
||||||
|
|
||||||
|
host, err := selectTunnelDialHost(from, to, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
// Default prefers v4 when both available
|
||||||
|
if host != "10.0.0.2" {
|
||||||
|
t.Fatalf("default preference should pick v4, got %q", host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectTunnelDialHost_DualStack_PreferV4(t *testing.T) {
|
||||||
|
from := dualStackNode("from", "10.0.0.1", "2001:db8::1")
|
||||||
|
to := dualStackNode("to", "10.0.0.2", "2001:db8::2")
|
||||||
|
|
||||||
|
host, err := selectTunnelDialHost(from, to, "v4")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if host != "10.0.0.2" {
|
||||||
|
t.Fatalf("v4 preference should pick v4 address, got %q", host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectTunnelDialHost_DualStack_PreferV6(t *testing.T) {
|
||||||
|
from := dualStackNode("from", "10.0.0.1", "2001:db8::1")
|
||||||
|
to := dualStackNode("to", "10.0.0.2", "2001:db8::2")
|
||||||
|
|
||||||
|
host, err := selectTunnelDialHost(from, to, "v6")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if host != "2001:db8::2" {
|
||||||
|
t.Fatalf("v6 preference should pick v6 address, got %q", host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectTunnelDialHost_V4Only_PreferV6Fallback(t *testing.T) {
|
||||||
|
from := v4OnlyNode("from", "10.0.0.1")
|
||||||
|
to := v4OnlyNode("to", "10.0.0.2")
|
||||||
|
|
||||||
|
// User prefers v6, but both nodes are v4-only — should fallback to v4
|
||||||
|
host, err := selectTunnelDialHost(from, to, "v6")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if host != "10.0.0.2" {
|
||||||
|
t.Fatalf("v6 preference on v4-only nodes should fallback to v4, got %q", host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectTunnelDialHost_V6Only_PreferV4Fallback(t *testing.T) {
|
||||||
|
from := v6OnlyNode("from", "2001:db8::1")
|
||||||
|
to := v6OnlyNode("to", "2001:db8::2")
|
||||||
|
|
||||||
|
// User prefers v4, but both nodes are v6-only — should fallback to v6
|
||||||
|
host, err := selectTunnelDialHost(from, to, "v4")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if host != "2001:db8::2" {
|
||||||
|
t.Fatalf("v4 preference on v6-only nodes should fallback to v6, got %q", host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectTunnelDialHost_Incompatible(t *testing.T) {
|
||||||
|
from := v4OnlyNode("from", "10.0.0.1")
|
||||||
|
to := v6OnlyNode("to", "2001:db8::2")
|
||||||
|
|
||||||
|
_, err := selectTunnelDialHost(from, to, "")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for incompatible nodes (v4-only -> v6-only)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectTunnelDialHost_Incompatible_Reverse(t *testing.T) {
|
||||||
|
from := v6OnlyNode("from", "2001:db8::1")
|
||||||
|
to := v4OnlyNode("to", "10.0.0.2")
|
||||||
|
|
||||||
|
_, err := selectTunnelDialHost(from, to, "")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for incompatible nodes (v6-only -> v4-only)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectTunnelDialHost_WhitespacePreference(t *testing.T) {
|
||||||
|
from := dualStackNode("from", "10.0.0.1", "2001:db8::1")
|
||||||
|
to := dualStackNode("to", "10.0.0.2", "2001:db8::2")
|
||||||
|
|
||||||
|
// Whitespace should be trimmed, treated as "v6"
|
||||||
|
host, err := selectTunnelDialHost(from, to, " v6 ")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if host != "2001:db8::2" {
|
||||||
|
t.Fatalf("trimmed v6 preference should pick v6 address, got %q", host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectTunnelDialHost_MixedStack_FromDualToV4(t *testing.T) {
|
||||||
|
from := dualStackNode("from", "10.0.0.1", "2001:db8::1")
|
||||||
|
to := v4OnlyNode("to", "10.0.0.2")
|
||||||
|
|
||||||
|
// v6 preferred, but target only has v4 — should succeed with v4
|
||||||
|
host, err := selectTunnelDialHost(from, to, "v6")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if host != "10.0.0.2" {
|
||||||
|
t.Fatalf("should fallback to v4 when target is v4-only, got %q", host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectTunnelDialHost_MixedStack_FromDualToV6(t *testing.T) {
|
||||||
|
from := dualStackNode("from", "10.0.0.1", "2001:db8::1")
|
||||||
|
to := v6OnlyNode("to", "2001:db8::2")
|
||||||
|
|
||||||
|
// v4 preferred, but target only has v6 — should succeed with v6
|
||||||
|
host, err := selectTunnelDialHost(from, to, "v4")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if host != "2001:db8::2" {
|
||||||
|
t.Fatalf("should fallback to v6 when target is v6-only, got %q", host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectTunnelDialHost_MixedStack_FromV4ToDual(t *testing.T) {
|
||||||
|
from := v4OnlyNode("from", "10.0.0.1")
|
||||||
|
to := dualStackNode("to", "10.0.0.2", "2001:db8::2")
|
||||||
|
|
||||||
|
// v6 preferred, but from only has v4 — should use v4 (from can only reach v4 of target)
|
||||||
|
host, err := selectTunnelDialHost(from, to, "v6")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if host != "10.0.0.2" {
|
||||||
|
t.Fatalf("should use v4 when from is v4-only, got %q", host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectTunnelDialHost_MixedStack_FromV6ToDual(t *testing.T) {
|
||||||
|
from := v6OnlyNode("from", "2001:db8::1")
|
||||||
|
to := dualStackNode("to", "10.0.0.2", "2001:db8::2")
|
||||||
|
|
||||||
|
// v4 preferred, but from only has v6 — should use v6
|
||||||
|
host, err := selectTunnelDialHost(from, to, "v4")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if host != "2001:db8::2" {
|
||||||
|
t.Fatalf("should use v6 when from is v6-only, got %q", host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// nodeDisplayName
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func TestNodeDisplayName_Nil(t *testing.T) {
|
||||||
|
got := nodeDisplayName(nil)
|
||||||
|
if got != "node" {
|
||||||
|
t.Fatalf("nil node display name should be 'node', got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeDisplayName_Named(t *testing.T) {
|
||||||
|
n := &nodeRecord{ID: 42, Name: "hk-node"}
|
||||||
|
got := nodeDisplayName(n)
|
||||||
|
if got != "hk-node" {
|
||||||
|
t.Fatalf("expected 'hk-node', got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeDisplayName_Unnamed(t *testing.T) {
|
||||||
|
n := &nodeRecord{ID: 42}
|
||||||
|
got := nodeDisplayName(n)
|
||||||
|
if got != "node_42" {
|
||||||
|
t.Fatalf("expected 'node_42', got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -91,6 +92,11 @@ type federationRuntimeDiagnoseRequest struct {
|
|||||||
Timeout int `json:"timeout"`
|
Timeout int `json:"timeout"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type federationRuntimeCommandRequest struct {
|
||||||
|
CommandType string `json:"commandType"`
|
||||||
|
Data interface{} `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
type peerShareUsedPort struct {
|
type peerShareUsedPort struct {
|
||||||
RuntimeID int64 `json:"runtimeId"`
|
RuntimeID int64 `json:"runtimeId"`
|
||||||
Port int `json:"port"`
|
Port int `json:"port"`
|
||||||
@@ -293,13 +299,20 @@ func (h *Handler) federationShareDelete(w http.ResponseWriter, r *http.Request)
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
share, _ := h.repo.GetPeerShare(req.ID)
|
||||||
|
|
||||||
h.cleanupPeerShareRuntimes(req.ID)
|
h.cleanupPeerShareRuntimes(req.ID)
|
||||||
|
h.cleanupFederationTunnels(req.ID)
|
||||||
|
|
||||||
if err := h.repo.DeletePeerShare(req.ID); err != nil {
|
if err := h.repo.DeletePeerShare(req.ID); err != nil {
|
||||||
response.WriteJSON(w, response.Err(-2, err.Error()))
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if share != nil && h.wsServer != nil {
|
||||||
|
h.wsServer.SendCommand(share.NodeID, "reload", nil, time.Second*5)
|
||||||
|
}
|
||||||
|
|
||||||
response.WriteJSON(w, response.OKEmpty())
|
response.WriteJSON(w, response.OKEmpty())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -538,6 +551,28 @@ func (h *Handler) federationRemoteUsageList(w http.ResponseWriter, r *http.Reque
|
|||||||
response.WriteJSON(w, response.OK(items))
|
response.WriteJSON(w, response.OK(items))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func remoteNodePortRange(node *nodeRecord) (int, int) {
|
||||||
|
if node == nil || node.IsRemote != 1 || node.RemoteConfig == "" {
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
_, _, _, _, portRangeStart, portRangeEnd := parseRemoteShareUsageConfig(node.RemoteConfig)
|
||||||
|
return portRangeStart, portRangeEnd
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateRemoteNodePort(node *nodeRecord, port int) error {
|
||||||
|
if node == nil || node.IsRemote != 1 || port <= 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
start, end := remoteNodePortRange(node)
|
||||||
|
if start <= 0 || end <= 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if port < start || port > end {
|
||||||
|
return fmt.Errorf("远程节点端口 %d 超出允许范围 %d-%d", port, start, end)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func parseRemoteShareUsageConfig(raw string) (int64, int64, int64, int64, int, int) {
|
func parseRemoteShareUsageConfig(raw string) (int64, int64, int64, int64, int, int) {
|
||||||
raw = strings.TrimSpace(raw)
|
raw = strings.TrimSpace(raw)
|
||||||
if raw == "" {
|
if raw == "" {
|
||||||
@@ -774,9 +809,6 @@ func (h *Handler) federationTunnelCreate(w http.ResponseWriter, r *http.Request)
|
|||||||
}
|
}
|
||||||
|
|
||||||
tunnelType := 1
|
tunnelType := 1
|
||||||
if strings.ToLower(req.Protocol) == "udp" {
|
|
||||||
tunnelType = 2
|
|
||||||
}
|
|
||||||
|
|
||||||
tx, err := h.repo.DB().Begin()
|
tx, err := h.repo.DB().Begin()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -799,7 +831,7 @@ func (h *Handler) federationTunnelCreate(w http.ResponseWriter, r *http.Request)
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = tx.Exec(`INSERT INTO chain_tunnel (tunnel_id, chain_type, node_id, port, strategy, inx, protocol) VALUES (?, 1, ?, ?, 'fifo', 0, ?)`,
|
_, err = tx.Exec(`INSERT INTO chain_tunnel (tunnel_id, chain_type, node_id, port, strategy, inx, protocol) VALUES (?, '1', ?, ?, 'fifo', 0, ?)`,
|
||||||
tunnelID,
|
tunnelID,
|
||||||
share.NodeID,
|
share.NodeID,
|
||||||
req.RemotePort,
|
req.RemotePort,
|
||||||
@@ -977,6 +1009,13 @@ func (h *Handler) federationRuntimeApplyRole(w http.ResponseWriter, r *http.Requ
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if share.PortRangeStart > 0 && share.PortRangeEnd > 0 && runtime.Port > 0 {
|
||||||
|
if runtime.Port < share.PortRangeStart || runtime.Port > share.PortRangeEnd {
|
||||||
|
response.WriteJSON(w, response.Err(403, fmt.Sprintf("port %d out of allowed range %d-%d", runtime.Port, share.PortRangeStart, share.PortRangeEnd)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
node, err := h.getNodeRecord(share.NodeID)
|
node, err := h.getNodeRecord(share.NodeID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
response.WriteJSON(w, response.ErrDefault(err.Error()))
|
response.WriteJSON(w, response.ErrDefault(err.Error()))
|
||||||
@@ -1000,14 +1039,19 @@ func (h *Handler) federationRuntimeApplyRole(w http.ResponseWriter, r *http.Requ
|
|||||||
response.WriteJSON(w, response.ErrDefault("Invalid target"))
|
response.WriteJSON(w, response.ErrDefault("Invalid target"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
targetProtocol := defaultString(target.Protocol, protocol)
|
||||||
|
connector := map[string]interface{}{
|
||||||
|
"type": "relay",
|
||||||
|
}
|
||||||
|
if isTLSTunnelProtocol(targetProtocol) {
|
||||||
|
connector["metadata"] = map[string]interface{}{"nodelay": true}
|
||||||
|
}
|
||||||
nodeItems = append(nodeItems, map[string]interface{}{
|
nodeItems = append(nodeItems, map[string]interface{}{
|
||||||
"name": fmt.Sprintf("node_%d", i+1),
|
"name": fmt.Sprintf("node_%d", i+1),
|
||||||
"addr": processServerAddress(fmt.Sprintf("%s:%d", host, target.Port)),
|
"addr": processServerAddress(fmt.Sprintf("%s:%d", host, target.Port)),
|
||||||
"connector": map[string]interface{}{
|
"connector": connector,
|
||||||
"type": "relay",
|
|
||||||
},
|
|
||||||
"dialer": map[string]interface{}{
|
"dialer": map[string]interface{}{
|
||||||
"type": defaultString(target.Protocol, protocol),
|
"type": targetProtocol,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1046,6 +1090,9 @@ func (h *Handler) federationRuntimeApplyRole(w http.ResponseWriter, r *http.Requ
|
|||||||
"type": protocol,
|
"type": protocol,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
if isTLSTunnelProtocol(protocol) {
|
||||||
|
service["handler"].(map[string]interface{})["metadata"] = map[string]interface{}{"nodelay": true}
|
||||||
|
}
|
||||||
if req.Role == "middle" {
|
if req.Role == "middle" {
|
||||||
service["handler"].(map[string]interface{})["chain"] = chainName
|
service["handler"].(map[string]interface{})["chain"] = chainName
|
||||||
}
|
}
|
||||||
@@ -1191,6 +1238,107 @@ func (h *Handler) federationRuntimeDiagnose(w http.ResponseWriter, r *http.Reque
|
|||||||
response.WriteJSON(w, response.OK(res.Data))
|
response.WriteJSON(w, response.OK(res.Data))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *Handler) federationRuntimeCommand(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
response.WriteJSON(w, response.ErrDefault("Invalid method"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
token := extractBearerToken(r)
|
||||||
|
share, err := h.repo.GetPeerShareByToken(token)
|
||||||
|
if err != nil || share == nil {
|
||||||
|
response.WriteJSON(w, response.Err(401, "Unauthorized"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req federationRuntimeCommandRequest
|
||||||
|
if err := decodeJSON(r.Body, &req); err != nil {
|
||||||
|
response.WriteJSON(w, response.ErrDefault("Invalid JSON"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cmd := strings.TrimSpace(req.CommandType)
|
||||||
|
if cmd == "" {
|
||||||
|
response.WriteJSON(w, response.ErrDefault("commandType is required"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !isFederationRuntimeCommandAllowed(cmd) {
|
||||||
|
response.WriteJSON(w, response.ErrDefault("command not allowed"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if isFederationServiceCommand(cmd) {
|
||||||
|
if err := validateFederationCommandPorts(share, req.Data); err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(403, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err := h.sendNodeCommand(share.NodeID, cmd, req.Data, false, false)
|
||||||
|
if err != nil {
|
||||||
|
response.WriteJSON(w, response.ErrDefault(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response.WriteJSON(w, response.OK(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
func isFederationRuntimeCommandAllowed(commandType string) bool {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(commandType)) {
|
||||||
|
case "addservice", "updateservice", "deleteservice", "pauseservice", "resumeservice", "addchains", "deletechains", "addlimiters", "deletelimiters", "tcpping", "reload":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isFederationServiceCommand(commandType string) bool {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(commandType)) {
|
||||||
|
case "addservice", "updateservice":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateFederationCommandPorts(share *sqlite.PeerShare, data interface{}) error {
|
||||||
|
if share == nil || (share.PortRangeStart <= 0 && share.PortRangeEnd <= 0) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
dataMap, ok := data.(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if services, ok := dataMap["services"]; ok {
|
||||||
|
serviceList, ok := services.([]interface{})
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("invalid services format")
|
||||||
|
}
|
||||||
|
for _, svc := range serviceList {
|
||||||
|
svcMap, ok := svc.(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("invalid service entry format")
|
||||||
|
}
|
||||||
|
addr, ok := svcMap["addr"].(string)
|
||||||
|
if !ok || addr == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
_, portStr, err := net.SplitHostPort(addr)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid service address: %s", addr)
|
||||||
|
}
|
||||||
|
port, err := strconv.Atoi(portStr)
|
||||||
|
if err != nil || port <= 0 {
|
||||||
|
return fmt.Errorf("invalid port in service address: %s", addr)
|
||||||
|
}
|
||||||
|
if port < share.PortRangeStart || port > share.PortRangeEnd {
|
||||||
|
return fmt.Errorf("port %d out of allowed range %d-%d", port, share.PortRangeStart, share.PortRangeEnd)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (h *Handler) pickPeerSharePort(share *sqlite.PeerShare, requestedPort int) (int, error) {
|
func (h *Handler) pickPeerSharePort(share *sqlite.PeerShare, requestedPort int) (int, error) {
|
||||||
if share == nil {
|
if share == nil {
|
||||||
return 0, fmt.Errorf("share not found")
|
return 0, fmt.Errorf("share not found")
|
||||||
@@ -1348,7 +1496,7 @@ func parseIPLiteral(raw string) net.IP {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ip := net.ParseIP(value); ip != nil {
|
if ip := net.ParseIP(value); ip != nil {
|
||||||
return ip
|
return normalizeIPAddress(ip)
|
||||||
}
|
}
|
||||||
|
|
||||||
host, _, err := net.SplitHostPort(value)
|
host, _, err := net.SplitHostPort(value)
|
||||||
@@ -1360,7 +1508,17 @@ func parseIPLiteral(raw string) net.IP {
|
|||||||
if host == "" {
|
if host == "" {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return net.ParseIP(host)
|
return normalizeIPAddress(net.ParseIP(host))
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeIPAddress(ip net.IP) net.IP {
|
||||||
|
if ip == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if v4 := ip.To4(); v4 != nil {
|
||||||
|
return v4
|
||||||
|
}
|
||||||
|
return ip.To16()
|
||||||
}
|
}
|
||||||
|
|
||||||
func isTrustedProxyIP(ip net.IP) bool {
|
func isTrustedProxyIP(ip net.IP) bool {
|
||||||
@@ -1491,3 +1649,27 @@ func (h *Handler) cleanupPeerShareRuntimes(shareID int64) {
|
|||||||
_ = h.repo.MarkPeerShareRuntimeReleased(runtime.ID, now)
|
_ = h.repo.MarkPeerShareRuntimeReleased(runtime.ID, now)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *Handler) cleanupFederationTunnels(shareID int64) {
|
||||||
|
if h == nil || h.repo == nil || shareID <= 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
namePrefix := fmt.Sprintf("Share-%d-Port-", shareID)
|
||||||
|
rows, err := h.repo.DB().Query(`SELECT id FROM tunnel WHERE name LIKE ?`, namePrefix+"%")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var tunnelIDs []int64
|
||||||
|
for rows.Next() {
|
||||||
|
var id int64
|
||||||
|
if err := rows.Scan(&id); err == nil {
|
||||||
|
tunnelIDs = append(tunnelIDs, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tid := range tunnelIDs {
|
||||||
|
_ = h.deleteTunnelByID(tid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -56,14 +56,35 @@ func TestPickPeerSharePortUsesRuntimeReservations(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestApplyTunnelRuntimeSkipsRemoteNodes(t *testing.T) {
|
func TestApplyTunnelRuntimeSkipsRemoteChainAndOutNodes(t *testing.T) {
|
||||||
h := &Handler{}
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "rt-skip.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open repo: %v", err)
|
||||||
|
}
|
||||||
|
defer repo.Close()
|
||||||
|
|
||||||
|
h := &Handler{repo: repo}
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
for _, n := range []struct {
|
||||||
|
id int64
|
||||||
|
name string
|
||||||
|
ip string
|
||||||
|
}{
|
||||||
|
{12, "remote-chain", "10.99.0.2"},
|
||||||
|
{13, "remote-out", "10.99.0.3"},
|
||||||
|
} {
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(id, name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx, is_remote, remote_url, remote_token)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, n.id, n.name, n.name+"-secret", n.ip, n.ip, "", "40000-40010", "", "v1", 1, 1, 1, now, now, 1, "[::]", "[::]", 0, 1, "http://remote-peer", "remote-token"); err != nil {
|
||||||
|
t.Fatalf("insert node %s: %v", n.name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
state := &tunnelCreateState{
|
state := &tunnelCreateState{
|
||||||
TunnelID: 1,
|
TunnelID: 1,
|
||||||
Type: 2,
|
Type: 2,
|
||||||
InNodes: []tunnelRuntimeNode{
|
InNodes: []tunnelRuntimeNode{},
|
||||||
{NodeID: 11, ChainType: 1, Protocol: "tls"},
|
|
||||||
},
|
|
||||||
ChainHops: [][]tunnelRuntimeNode{
|
ChainHops: [][]tunnelRuntimeNode{
|
||||||
{
|
{
|
||||||
{NodeID: 12, ChainType: 2, Inx: 1, Port: 41000, Protocol: "tls", Strategy: "round"},
|
{NodeID: 12, ChainType: 2, Inx: 1, Port: 41000, Protocol: "tls", Strategy: "round"},
|
||||||
@@ -73,9 +94,8 @@ func TestApplyTunnelRuntimeSkipsRemoteNodes(t *testing.T) {
|
|||||||
{NodeID: 13, ChainType: 3, Port: 42000, Protocol: "tls", Strategy: "round"},
|
{NodeID: 13, ChainType: 3, Port: 42000, Protocol: "tls", Strategy: "round"},
|
||||||
},
|
},
|
||||||
Nodes: map[int64]*nodeRecord{
|
Nodes: map[int64]*nodeRecord{
|
||||||
11: {ID: 11, Name: "remote-in", IsRemote: 1},
|
12: {ID: 12, Name: "remote-chain", IsRemote: 1, ServerIPv4: "10.99.0.2"},
|
||||||
12: {ID: 12, Name: "remote-chain", IsRemote: 1},
|
13: {ID: 13, Name: "remote-out", IsRemote: 1, ServerIPv4: "10.99.0.3"},
|
||||||
13: {ID: 13, Name: "remote-out", IsRemote: 1},
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,10 +104,10 @@ func TestApplyTunnelRuntimeSkipsRemoteNodes(t *testing.T) {
|
|||||||
t.Fatalf("apply runtime: %v", err)
|
t.Fatalf("apply runtime: %v", err)
|
||||||
}
|
}
|
||||||
if len(chains) != 0 {
|
if len(chains) != 0 {
|
||||||
t.Fatalf("expected no local chains created, got %d", len(chains))
|
t.Fatalf("expected no local chains for remote-only nodes, got %d", len(chains))
|
||||||
}
|
}
|
||||||
if len(services) != 0 {
|
if len(services) != 0 {
|
||||||
t.Fatalf("expected no local services created, got %d", len(services))
|
t.Fatalf("expected no local services for remote-only nodes, got %d", len(services))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,6 +172,71 @@ func TestPrepareTunnelCreateStateRemoteAutoPortDefersToFederation(t *testing.T)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPrepareTunnelCreateStateAllowsOfflineRemoteMiddleNode(t *testing.T) {
|
||||||
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open repo: %v", err)
|
||||||
|
}
|
||||||
|
defer repo.Close()
|
||||||
|
|
||||||
|
h := &Handler{repo: repo}
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
insertNode := func(name string, status int, portRange string, isRemote int) int64 {
|
||||||
|
res, execErr := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx, is_remote, remote_url, remote_token, remote_config)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, name, name+"-secret", "10.0.0.1", "10.0.0.1", "", portRange, "", "v1", 1, 1, 1, now, now, status, "[::]", "[::]", 0, isRemote, "http://peer", "peer-token", `{"shareId":2}`)
|
||||||
|
if execErr != nil {
|
||||||
|
t.Fatalf("insert node %s: %v", name, execErr)
|
||||||
|
}
|
||||||
|
id, idErr := res.LastInsertId()
|
||||||
|
if idErr != nil {
|
||||||
|
t.Fatalf("node id %s: %v", name, idErr)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
entryID := insertNode("entry-local", 1, "32000-32010", 0)
|
||||||
|
remoteMiddleID := insertNode("middle-remote", 0, "33000-33010", 1)
|
||||||
|
outID := insertNode("out-local", 1, "34000-34010", 0)
|
||||||
|
|
||||||
|
tx, err := repo.DB().Begin()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("begin tx: %v", err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
req := map[string]interface{}{
|
||||||
|
"name": "remote-middle-offline-status",
|
||||||
|
"inNodeId": []interface{}{
|
||||||
|
map[string]interface{}{"nodeId": float64(entryID), "protocol": "tls", "strategy": "round"},
|
||||||
|
},
|
||||||
|
"chainNodes": []interface{}{
|
||||||
|
[]interface{}{
|
||||||
|
map[string]interface{}{"nodeId": float64(remoteMiddleID), "protocol": "tls", "strategy": "round", "port": float64(0)},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"outNodeId": []interface{}{
|
||||||
|
map[string]interface{}{"nodeId": float64(outID), "protocol": "tls", "strategy": "round", "port": float64(0)},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
state, err := h.prepareTunnelCreateState(tx, req, 2, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("prepare state should allow offline remote middle node: %v", err)
|
||||||
|
}
|
||||||
|
if len(state.ChainHops) != 1 || len(state.ChainHops[0]) != 1 {
|
||||||
|
t.Fatalf("expected one middle hop node, got %+v", state.ChainHops)
|
||||||
|
}
|
||||||
|
if state.ChainHops[0][0].NodeID != remoteMiddleID {
|
||||||
|
t.Fatalf("expected remote middle node id %d, got %d", remoteMiddleID, state.ChainHops[0][0].NodeID)
|
||||||
|
}
|
||||||
|
if state.Nodes[remoteMiddleID] == nil || state.Nodes[remoteMiddleID].IsRemote != 1 {
|
||||||
|
t.Fatalf("expected remote middle node metadata in state")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestFederationRuntimeReservePortRejectsWhenShareFlowExceeded(t *testing.T) {
|
func TestFederationRuntimeReservePortRejectsWhenShareFlowExceeded(t *testing.T) {
|
||||||
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
repo, err := sqlite.Open(filepath.Join(t.TempDir(), "panel.db"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -567,6 +567,13 @@ func TestAuthPeerAllowedIPs(t *testing.T) {
|
|||||||
xff: "198.51.100.20, 172.20.0.3",
|
xff: "198.51.100.20, 172.20.0.3",
|
||||||
wantAllowed: true,
|
wantAllowed: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "ipv4-mapped proxy xff allowed",
|
||||||
|
allowedIPs: "198.51.100.20",
|
||||||
|
remoteAddr: "[::ffff:172.20.0.3]:34567",
|
||||||
|
xff: "198.51.100.20, 172.20.0.3",
|
||||||
|
wantAllowed: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "non whitelisted ip denied",
|
name: "non whitelisted ip denied",
|
||||||
allowedIPs: "203.0.113.10",
|
allowedIPs: "203.0.113.10",
|
||||||
|
|||||||
@@ -251,7 +251,7 @@ func (h *Handler) pauseForwardRecords(forwards []forwardRecord, now int64) {
|
|||||||
|
|
||||||
func (h *Handler) listActiveForwardsByUser(userID int64) ([]forwardRecord, error) {
|
func (h *Handler) listActiveForwardsByUser(userID int64) ([]forwardRecord, error) {
|
||||||
rows, err := h.repo.DB().Query(`
|
rows, err := h.repo.DB().Query(`
|
||||||
SELECT id, user_id, user_name, name, tunnel_id, remote_addr, strategy, status
|
SELECT id, user_id, user_name, name, tunnel_id, remote_addr, COALESCE(strategy, 'fifo'), status
|
||||||
FROM forward
|
FROM forward
|
||||||
WHERE user_id = ? AND status = 1
|
WHERE user_id = ? AND status = 1
|
||||||
ORDER BY id ASC
|
ORDER BY id ASC
|
||||||
@@ -266,7 +266,7 @@ func (h *Handler) listActiveForwardsByUser(userID int64) ([]forwardRecord, error
|
|||||||
|
|
||||||
func (h *Handler) listActiveForwardsByUserTunnel(userID int64, tunnelID int64) ([]forwardRecord, error) {
|
func (h *Handler) listActiveForwardsByUserTunnel(userID int64, tunnelID int64) ([]forwardRecord, error) {
|
||||||
rows, err := h.repo.DB().Query(`
|
rows, err := h.repo.DB().Query(`
|
||||||
SELECT id, user_id, user_name, name, tunnel_id, remote_addr, strategy, status
|
SELECT id, user_id, user_name, name, tunnel_id, remote_addr, COALESCE(strategy, 'fifo'), status
|
||||||
FROM forward
|
FROM forward
|
||||||
WHERE user_id = ? AND tunnel_id = ? AND status = 1
|
WHERE user_id = ? AND tunnel_id = ? AND status = 1
|
||||||
ORDER BY id ASC
|
ORDER BY id ASC
|
||||||
|
|||||||
@@ -93,6 +93,12 @@ func (h *Handler) Register(mux *http.ServeMux) {
|
|||||||
mux.HandleFunc("/api/v1/config/list", h.getConfigs)
|
mux.HandleFunc("/api/v1/config/list", h.getConfigs)
|
||||||
mux.HandleFunc("/api/v1/config/update", h.updateConfigs)
|
mux.HandleFunc("/api/v1/config/update", h.updateConfigs)
|
||||||
mux.HandleFunc("/api/v1/config/update-single", h.updateSingleConfig)
|
mux.HandleFunc("/api/v1/config/update-single", h.updateSingleConfig)
|
||||||
|
mux.HandleFunc("/api/v1/backup/export", h.backupExport)
|
||||||
|
mux.HandleFunc("/api/v1/backup/import", h.backupImport)
|
||||||
|
mux.HandleFunc("/api/v1/backup/restore", h.backupImport)
|
||||||
|
mux.HandleFunc("/api/v1/api/v1/backup/export", h.backupExport)
|
||||||
|
mux.HandleFunc("/api/v1/api/v1/backup/import", h.backupImport)
|
||||||
|
mux.HandleFunc("/api/v1/api/v1/backup/restore", h.backupImport)
|
||||||
mux.HandleFunc("/api/v1/captcha/check", h.checkCaptcha)
|
mux.HandleFunc("/api/v1/captcha/check", h.checkCaptcha)
|
||||||
mux.HandleFunc("/api/v1/captcha/verify", h.captchaVerify)
|
mux.HandleFunc("/api/v1/captcha/verify", h.captchaVerify)
|
||||||
mux.HandleFunc("/api/v1/user/package", h.userPackage)
|
mux.HandleFunc("/api/v1/user/package", h.userPackage)
|
||||||
@@ -169,7 +175,10 @@ func (h *Handler) Register(mux *http.ServeMux) {
|
|||||||
mux.HandleFunc("/api/v1/federation/runtime/apply-role", h.authPeer(h.federationRuntimeApplyRole))
|
mux.HandleFunc("/api/v1/federation/runtime/apply-role", h.authPeer(h.federationRuntimeApplyRole))
|
||||||
mux.HandleFunc("/api/v1/federation/runtime/release-role", h.authPeer(h.federationRuntimeReleaseRole))
|
mux.HandleFunc("/api/v1/federation/runtime/release-role", h.authPeer(h.federationRuntimeReleaseRole))
|
||||||
mux.HandleFunc("/api/v1/federation/runtime/diagnose", h.authPeer(h.federationRuntimeDiagnose))
|
mux.HandleFunc("/api/v1/federation/runtime/diagnose", h.authPeer(h.federationRuntimeDiagnose))
|
||||||
|
mux.HandleFunc("/api/v1/federation/runtime/command", h.authPeer(h.federationRuntimeCommand))
|
||||||
mux.HandleFunc("/api/v1/federation/node/import", h.nodeImport)
|
mux.HandleFunc("/api/v1/federation/node/import", h.nodeImport)
|
||||||
|
mux.HandleFunc("/api/v1/announcement/get", h.getAnnouncement)
|
||||||
|
mux.HandleFunc("/api/v1/announcement/update", h.updateAnnouncement)
|
||||||
|
|
||||||
mux.HandleFunc("/flow/test", h.flowTest)
|
mux.HandleFunc("/flow/test", h.flowTest)
|
||||||
mux.HandleFunc("/flow/config", h.flowConfig)
|
mux.HandleFunc("/flow/config", h.flowConfig)
|
||||||
@@ -306,11 +315,35 @@ func (h *Handler) userList(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var req struct {
|
||||||
|
Current int `json:"current"`
|
||||||
|
Size int `json:"size"`
|
||||||
|
Keyword string `json:"keyword"`
|
||||||
|
}
|
||||||
|
if err := decodeJSON(r.Body, &req); err != nil && err != io.EOF {
|
||||||
|
response.WriteJSON(w, response.ErrDefault("请求参数错误"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
users, err := h.repo.ListUsers()
|
users, err := h.repo.ListUsers()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
response.WriteJSON(w, response.Err(-2, err.Error()))
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
keyword := strings.ToLower(strings.TrimSpace(req.Keyword))
|
||||||
|
if keyword != "" {
|
||||||
|
filtered := make([]map[string]interface{}, 0, len(users))
|
||||||
|
for _, item := range users {
|
||||||
|
username := strings.ToLower(strings.TrimSpace(fmt.Sprint(item["user"])))
|
||||||
|
displayName := strings.ToLower(strings.TrimSpace(fmt.Sprint(item["name"])))
|
||||||
|
if strings.Contains(username, keyword) || strings.Contains(displayName, keyword) {
|
||||||
|
filtered = append(filtered, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
users = filtered
|
||||||
|
}
|
||||||
|
|
||||||
response.WriteJSON(w, response.OK(users))
|
response.WriteJSON(w, response.OK(users))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1116,3 +1149,134 @@ func (h *Handler) verifyCloudflareTurnstile(token, secretKey string) bool {
|
|||||||
}
|
}
|
||||||
return body.Success
|
return body.Success
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type backupExportRequest struct {
|
||||||
|
Types []string `json:"types"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) backupExport(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
response.WriteJSON(w, response.ErrDefault("请求失败"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req backupExportRequest
|
||||||
|
if err := decodeJSON(r.Body, &req); err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(500, "请求参数错误"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var backup interface{}
|
||||||
|
var err error
|
||||||
|
|
||||||
|
if len(req.Types) == 0 {
|
||||||
|
backup, err = h.repo.ExportAll()
|
||||||
|
} else {
|
||||||
|
backup, err = h.repo.ExportPartial(req.Types)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Disposition", "attachment; filename=backup.json")
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
if err := json.NewEncoder(w).Encode(backup); err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type backupImportRequest struct {
|
||||||
|
Types []string `json:"types"`
|
||||||
|
sqlite.BackupData
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) backupImport(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
response.WriteJSON(w, response.ErrDefault("请求失败"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req backupImportRequest
|
||||||
|
if err := decodeJSON(r.Body, &req); err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(500, "请求参数错误"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(req.Types) == 0 {
|
||||||
|
response.WriteJSON(w, response.Err(500, "请选择要导入的数据类型"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
autoBackup, err := h.repo.ExportAll()
|
||||||
|
if err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(-2, fmt.Sprintf("导入前自动备份失败: %v", err)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.BackupData.Version == "" {
|
||||||
|
response.WriteJSON(w, response.Err(500, "备份数据格式错误"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := h.repo.Import(&req.BackupData, req.Types)
|
||||||
|
if err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(-2, fmt.Sprintf("导入失败: %v", err)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
result.AutoBackup = autoBackup
|
||||||
|
response.WriteJSON(w, response.OK(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) getAnnouncement(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
response.WriteJSON(w, response.ErrDefault("请求失败"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ann, err := h.repo.GetAnnouncement()
|
||||||
|
if err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(-1, fmt.Sprintf("获取公告失败: %v", err)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if ann == nil {
|
||||||
|
response.WriteJSON(w, response.OK(map[string]interface{}{
|
||||||
|
"content": "",
|
||||||
|
"enabled": 0,
|
||||||
|
}))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
response.WriteJSON(w, response.OK(map[string]interface{}{
|
||||||
|
"content": ann.Content,
|
||||||
|
"enabled": ann.Enabled,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) updateAnnouncement(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
response.WriteJSON(w, response.ErrDefault("请求失败"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req struct {
|
||||||
|
Content string `json:"content"`
|
||||||
|
Enabled int `json:"enabled"`
|
||||||
|
}
|
||||||
|
if err := decodeJSON(r.Body, &req); err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(500, "请求参数错误"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
if err := h.repo.UpsertAnnouncement(req.Content, req.Enabled, now); err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(-1, fmt.Sprintf("更新公告失败: %v", err)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
response.WriteJSON(w, response.OKEmpty())
|
||||||
|
}
|
||||||
|
|||||||
@@ -497,6 +497,7 @@ func (h *Handler) tunnelCreate(w http.ResponseWriter, r *http.Request) {
|
|||||||
status := asInt(req["status"], 1)
|
status := asInt(req["status"], 1)
|
||||||
trafficRatio := asFloat(req["trafficRatio"], 1.0)
|
trafficRatio := asFloat(req["trafficRatio"], 1.0)
|
||||||
inIP := asString(req["inIp"])
|
inIP := asString(req["inIp"])
|
||||||
|
ipPreference := asString(req["ipPreference"])
|
||||||
now := time.Now().UnixMilli()
|
now := time.Now().UnixMilli()
|
||||||
inx := nextIndex(h.repo.DB(), "tunnel")
|
inx := nextIndex(h.repo.DB(), "tunnel")
|
||||||
|
|
||||||
@@ -512,6 +513,7 @@ func (h *Handler) tunnelCreate(w http.ResponseWriter, r *http.Request) {
|
|||||||
response.WriteJSON(w, response.ErrDefault(err.Error()))
|
response.WriteJSON(w, response.ErrDefault(err.Error()))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
runtimeState.IPPreference = ipPreference
|
||||||
if strings.TrimSpace(inIP) == "" {
|
if strings.TrimSpace(inIP) == "" {
|
||||||
inIP = buildTunnelInIP(runtimeState.InNodes, runtimeState.Nodes)
|
inIP = buildTunnelInIP(runtimeState.InNodes, runtimeState.Nodes)
|
||||||
}
|
}
|
||||||
@@ -545,6 +547,11 @@ func (h *Handler) tunnelCreate(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if targetPort > 0 && targetAddr != "" {
|
if targetPort > 0 && targetAddr != "" {
|
||||||
|
inNodeRec := runtimeState.Nodes[firstNodeID]
|
||||||
|
if err := validateRemoteNodePort(inNodeRec, targetPort); err != nil {
|
||||||
|
response.WriteJSON(w, response.ErrDefault(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
domainCfg, _ := h.repo.GetConfigByName("panel_domain")
|
domainCfg, _ := h.repo.GetConfigByName("panel_domain")
|
||||||
localDomain := ""
|
localDomain := ""
|
||||||
if domainCfg != nil {
|
if domainCfg != nil {
|
||||||
@@ -560,8 +567,8 @@ func (h *Handler) tunnelCreate(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tunnelID, err := tx.ExecReturningID(`INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
tunnelID, err := tx.ExecReturningID(`INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx, ip_preference) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||||
name, trafficRatio, typeVal, "tls", flow, now, now, status, nullableText(inIP), inx)
|
name, trafficRatio, typeVal, "tls", flow, now, now, status, nullableText(inIP), inx, ipPreference)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
response.WriteJSON(w, response.Err(-2, err.Error()))
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
return
|
return
|
||||||
@@ -569,12 +576,10 @@ func (h *Handler) tunnelCreate(w http.ResponseWriter, r *http.Request) {
|
|||||||
runtimeState.TunnelID = tunnelID
|
runtimeState.TunnelID = tunnelID
|
||||||
var federationBindings []sqlite.FederationTunnelBinding
|
var federationBindings []sqlite.FederationTunnelBinding
|
||||||
var federationReleaseRefs []federationRuntimeReleaseRef
|
var federationReleaseRefs []federationRuntimeReleaseRef
|
||||||
if typeVal == 2 {
|
federationBindings, federationReleaseRefs, err = h.applyFederationRuntime(runtimeState)
|
||||||
federationBindings, federationReleaseRefs, err = h.applyFederationRuntime(runtimeState)
|
if err != nil {
|
||||||
if err != nil {
|
response.WriteJSON(w, response.ErrDefault(err.Error()))
|
||||||
response.WriteJSON(w, response.ErrDefault(err.Error()))
|
return
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
applyTunnelPortsToRequest(req, runtimeState)
|
applyTunnelPortsToRequest(req, runtimeState)
|
||||||
if err := replaceTunnelChainsTx(tx, tunnelID, req); err != nil {
|
if err := replaceTunnelChainsTx(tx, tunnelID, req); err != nil {
|
||||||
@@ -674,6 +679,7 @@ func (h *Handler) tunnelUpdate(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
now := time.Now().UnixMilli()
|
now := time.Now().UnixMilli()
|
||||||
typeVal := asInt(req["type"], 1)
|
typeVal := asInt(req["type"], 1)
|
||||||
|
ipPreference := asString(req["ipPreference"])
|
||||||
|
|
||||||
tx, err := h.repo.DB().Begin()
|
tx, err := h.repo.DB().Begin()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -688,19 +694,21 @@ func (h *Handler) tunnelUpdate(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
runtimeState.TunnelID = id
|
runtimeState.TunnelID = id
|
||||||
|
runtimeState.IPPreference = ipPreference
|
||||||
|
|
||||||
|
inIp := buildTunnelInIP(runtimeState.InNodes, runtimeState.Nodes)
|
||||||
|
|
||||||
var federationBindings []sqlite.FederationTunnelBinding
|
var federationBindings []sqlite.FederationTunnelBinding
|
||||||
var federationReleaseRefs []federationRuntimeReleaseRef
|
var federationReleaseRefs []federationRuntimeReleaseRef
|
||||||
if typeVal == 2 {
|
federationBindings, federationReleaseRefs, err = h.applyFederationRuntime(runtimeState)
|
||||||
federationBindings, federationReleaseRefs, err = h.applyFederationRuntime(runtimeState)
|
if err != nil {
|
||||||
if err != nil {
|
response.WriteJSON(w, response.ErrDefault(err.Error()))
|
||||||
response.WriteJSON(w, response.ErrDefault(err.Error()))
|
return
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
applyTunnelPortsToRequest(req, runtimeState)
|
applyTunnelPortsToRequest(req, runtimeState)
|
||||||
|
|
||||||
_, err = tx.Exec(`UPDATE tunnel SET name=?, type=?, flow=?, traffic_ratio=?, status=?, in_ip=?, updated_time=? WHERE id=?`,
|
_, err = tx.Exec(`UPDATE tunnel SET name=?, type=?, flow=?, traffic_ratio=?, status=?, in_ip=?, ip_preference=?, updated_time=? WHERE id=?`,
|
||||||
asString(req["name"]), typeVal, asInt64(req["flow"], 1), asFloat(req["trafficRatio"], 1.0), asInt(req["status"], 1), nullableText(asString(req["inIp"])), now, id)
|
asString(req["name"]), typeVal, asInt64(req["flow"], 1), asFloat(req["trafficRatio"], 1.0), asInt(req["status"], 1), nullableText(inIp), ipPreference, now, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
response.WriteJSON(w, response.Err(-2, err.Error()))
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
return
|
return
|
||||||
@@ -834,14 +842,18 @@ func (h *Handler) reconstructTunnelState(tunnelID int64) (*tunnelCreateState, er
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var ipPreference string
|
||||||
|
_ = h.repo.DB().QueryRow(`SELECT COALESCE(ip_preference, '') FROM tunnel WHERE id = ?`, tunnelID).Scan(&ipPreference)
|
||||||
|
|
||||||
state := &tunnelCreateState{
|
state := &tunnelCreateState{
|
||||||
TunnelID: tunnelID,
|
TunnelID: tunnelID,
|
||||||
Type: tunnel.Type,
|
Type: tunnel.Type,
|
||||||
InNodes: make([]tunnelRuntimeNode, 0),
|
IPPreference: ipPreference,
|
||||||
ChainHops: make([][]tunnelRuntimeNode, 0),
|
InNodes: make([]tunnelRuntimeNode, 0),
|
||||||
OutNodes: make([]tunnelRuntimeNode, 0),
|
ChainHops: make([][]tunnelRuntimeNode, 0),
|
||||||
Nodes: make(map[int64]*nodeRecord),
|
OutNodes: make([]tunnelRuntimeNode, 0),
|
||||||
NodeIDList: make([]int64, 0),
|
Nodes: make(map[int64]*nodeRecord),
|
||||||
|
NodeIDList: make([]int64, 0),
|
||||||
}
|
}
|
||||||
|
|
||||||
inNodes, chainHops, outNodes := splitChainNodeGroups(chainRows)
|
inNodes, chainHops, outNodes := splitChainNodeGroups(chainRows)
|
||||||
@@ -1106,6 +1118,17 @@ func (h *Handler) forwardCreate(w http.ResponseWriter, r *http.Request) {
|
|||||||
if port <= 0 {
|
if port <= 0 {
|
||||||
port = 10000
|
port = 10000
|
||||||
}
|
}
|
||||||
|
entryNodes, _ := h.tunnelEntryNodeIDs(tunnelID)
|
||||||
|
for _, nodeID := range entryNodes {
|
||||||
|
node, nodeErr := h.getNodeRecord(nodeID)
|
||||||
|
if nodeErr != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := validateRemoteNodePort(node, port); err != nil {
|
||||||
|
response.WriteJSON(w, response.ErrDefault(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
now := time.Now().UnixMilli()
|
now := time.Now().UnixMilli()
|
||||||
inx := nextIndex(h.repo.DB(), "forward")
|
inx := nextIndex(h.repo.DB(), "forward")
|
||||||
var userName string
|
var userName string
|
||||||
@@ -1127,7 +1150,6 @@ func (h *Handler) forwardCreate(w http.ResponseWriter, r *http.Request) {
|
|||||||
response.WriteJSON(w, response.Err(-2, err.Error()))
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
entryNodes, _ := h.tunnelEntryNodeIDs(tunnelID)
|
|
||||||
for _, nodeID := range entryNodes {
|
for _, nodeID := range entryNodes {
|
||||||
_, _ = tx.Exec(`INSERT INTO forward_port(forward_id, node_id, port) VALUES(?, ?, ?)`, forwardID, nodeID, port)
|
_, _ = tx.Exec(`INSERT INTO forward_port(forward_id, node_id, port) VALUES(?, ?, ?)`, forwardID, nodeID, port)
|
||||||
}
|
}
|
||||||
@@ -1217,6 +1239,17 @@ func (h *Handler) forwardUpdate(w http.ResponseWriter, r *http.Request) {
|
|||||||
port = h.pickTunnelPort(tunnelID)
|
port = h.pickTunnelPort(tunnelID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
fwdEntryNodes, _ := h.tunnelEntryNodeIDs(tunnelID)
|
||||||
|
for _, nodeID := range fwdEntryNodes {
|
||||||
|
node, nodeErr := h.getNodeRecord(nodeID)
|
||||||
|
if nodeErr != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := validateRemoteNodePort(node, port); err != nil {
|
||||||
|
response.WriteJSON(w, response.ErrDefault(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
now := time.Now().UnixMilli()
|
now := time.Now().UnixMilli()
|
||||||
_, err = h.repo.DB().Exec(`
|
_, err = h.repo.DB().Exec(`
|
||||||
UPDATE forward SET name = ?, tunnel_id = ?, remote_addr = ?, strategy = ?, updated_time = ? WHERE id = ?
|
UPDATE forward SET name = ?, tunnel_id = ?, remote_addr = ?, strategy = ?, updated_time = ? WHERE id = ?
|
||||||
@@ -1541,6 +1574,22 @@ func (h *Handler) forwardBatchChangeTunnel(w http.ResponseWriter, r *http.Reques
|
|||||||
if p <= 0 {
|
if p <= 0 {
|
||||||
p = h.pickTunnelPort(req.TargetTunnelID)
|
p = h.pickTunnelPort(req.TargetTunnelID)
|
||||||
}
|
}
|
||||||
|
bctEntryNodes, _ := h.tunnelEntryNodeIDs(req.TargetTunnelID)
|
||||||
|
portRangeOk := true
|
||||||
|
for _, nid := range bctEntryNodes {
|
||||||
|
nd, ndErr := h.getNodeRecord(nid)
|
||||||
|
if ndErr != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if validateRemoteNodePort(nd, p) != nil {
|
||||||
|
portRangeOk = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !portRangeOk {
|
||||||
|
fail++
|
||||||
|
continue
|
||||||
|
}
|
||||||
if err := h.replaceForwardPorts(id, req.TargetTunnelID, p); err != nil {
|
if err := h.replaceForwardPorts(id, req.TargetTunnelID, p); err != nil {
|
||||||
h.rollbackForwardMutation(forward, oldPorts)
|
h.rollbackForwardMutation(forward, oldPorts)
|
||||||
fail++
|
fail++
|
||||||
@@ -1710,10 +1759,19 @@ func (h *Handler) groupUserAssign(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer func() { _ = tx.Rollback() }()
|
defer func() { _ = tx.Rollback() }()
|
||||||
|
previousUserIDs, err := queryInt64ListTx(tx, `SELECT user_id FROM user_group_user WHERE user_group_id = ?`, req.GroupID)
|
||||||
|
if err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
_, _ = tx.Exec(`DELETE FROM user_group_user WHERE user_group_id = ?`, req.GroupID)
|
_, _ = tx.Exec(`DELETE FROM user_group_user WHERE user_group_id = ?`, req.GroupID)
|
||||||
for _, uid := range req.UserIDs {
|
for _, uid := range req.UserIDs {
|
||||||
_, _ = tx.Exec(`INSERT INTO user_group_user(user_group_id, user_id, created_time) VALUES(?, ?, ?) ON CONFLICT DO NOTHING`, req.GroupID, uid, time.Now().UnixMilli())
|
_, _ = tx.Exec(`INSERT INTO user_group_user(user_group_id, user_id, created_time) VALUES(?, ?, ?) ON CONFLICT DO NOTHING`, req.GroupID, uid, time.Now().UnixMilli())
|
||||||
}
|
}
|
||||||
|
if err := revokeGroupGrantsForRemovedUsersTx(tx, req.GroupID, previousUserIDs, req.UserIDs); err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
if err := tx.Commit(); err != nil {
|
if err := tx.Commit(); err != nil {
|
||||||
response.WriteJSON(w, response.Err(-2, err.Error()))
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
return
|
return
|
||||||
@@ -1745,10 +1803,35 @@ func (h *Handler) groupPermissionRemove(w http.ResponseWriter, r *http.Request)
|
|||||||
if id <= 0 {
|
if id <= 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
tx, err := h.repo.DB().Begin()
|
||||||
|
if err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer func() { _ = tx.Rollback() }()
|
||||||
|
|
||||||
var ug, tg int64
|
var ug, tg int64
|
||||||
_ = h.repo.DB().QueryRow(`SELECT user_group_id, tunnel_group_id FROM group_permission WHERE id = ?`, id).Scan(&ug, &tg)
|
err = tx.QueryRow(`SELECT user_group_id, tunnel_group_id FROM group_permission WHERE id = ?`, id).Scan(&ug, &tg)
|
||||||
_, _ = h.repo.DB().Exec(`DELETE FROM group_permission WHERE id = ?`, id)
|
if err != nil && err != sql.ErrNoRows {
|
||||||
_, _ = h.repo.DB().Exec(`DELETE FROM group_permission_grant WHERE user_group_id = ? AND tunnel_group_id = ?`, ug, tg)
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := tx.Exec(`DELETE FROM group_permission WHERE id = ?`, id); err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
if err := revokeGroupPermissionPairTx(tx, ug, tg); err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
response.WriteJSON(w, response.Err(-2, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
response.WriteJSON(w, response.OKEmpty())
|
response.WriteJSON(w, response.OKEmpty())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1905,6 +1988,144 @@ func queryInt64List(db *store.DB, q string, args ...interface{}) ([]int64, error
|
|||||||
return out, rows.Err()
|
return out, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func queryInt64ListTx(tx *store.Tx, q string, args ...interface{}) ([]int64, error) {
|
||||||
|
rows, err := tx.Query(q, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := make([]int64, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var v int64
|
||||||
|
if err := rows.Scan(&v); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, v)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func revokeGroupGrantsForRemovedUsersTx(tx *store.Tx, userGroupID int64, previousUserIDs, currentUserIDs []int64) error {
|
||||||
|
currentSet := make(map[int64]struct{}, len(currentUserIDs))
|
||||||
|
for _, uid := range currentUserIDs {
|
||||||
|
if uid > 0 {
|
||||||
|
currentSet[uid] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
removedUserIDs := make([]int64, 0)
|
||||||
|
for _, uid := range previousUserIDs {
|
||||||
|
if uid <= 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := currentSet[uid]; !ok {
|
||||||
|
removedUserIDs = append(removedUserIDs, uid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(removedUserIDs) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, userID := range removedUserIDs {
|
||||||
|
rows, err := tx.Query(`
|
||||||
|
SELECT g.user_tunnel_id, g.created_by_group
|
||||||
|
FROM group_permission_grant g
|
||||||
|
JOIN user_tunnel ut ON ut.id = g.user_tunnel_id
|
||||||
|
WHERE g.user_group_id = ? AND ut.user_id = ?
|
||||||
|
`, userGroupID, userID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
groupCreatedTunnelIDs := make(map[int64]struct{})
|
||||||
|
for rows.Next() {
|
||||||
|
var userTunnelID int64
|
||||||
|
var createdByGroup int
|
||||||
|
if err := rows.Scan(&userTunnelID, &createdByGroup); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if createdByGroup == 1 && userTunnelID > 0 {
|
||||||
|
groupCreatedTunnelIDs[userTunnelID] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
|
||||||
|
if _, err := tx.Exec(`
|
||||||
|
DELETE FROM group_permission_grant
|
||||||
|
WHERE user_group_id = ?
|
||||||
|
AND user_tunnel_id IN (SELECT id FROM user_tunnel WHERE user_id = ?)
|
||||||
|
`, userGroupID, userID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for userTunnelID := range groupCreatedTunnelIDs {
|
||||||
|
var remaining int
|
||||||
|
if err := tx.QueryRow(`SELECT COUNT(1) FROM group_permission_grant WHERE user_tunnel_id = ?`, userTunnelID).Scan(&remaining); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if remaining == 0 {
|
||||||
|
if _, err := tx.Exec(`DELETE FROM user_tunnel WHERE id = ?`, userTunnelID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func revokeGroupPermissionPairTx(tx *store.Tx, userGroupID, tunnelGroupID int64) error {
|
||||||
|
rows, err := tx.Query(`
|
||||||
|
SELECT user_tunnel_id, created_by_group
|
||||||
|
FROM group_permission_grant
|
||||||
|
WHERE user_group_id = ? AND tunnel_group_id = ?
|
||||||
|
`, userGroupID, tunnelGroupID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
groupCreatedTunnelIDs := make(map[int64]struct{})
|
||||||
|
for rows.Next() {
|
||||||
|
var userTunnelID int64
|
||||||
|
var createdByGroup int
|
||||||
|
if err := rows.Scan(&userTunnelID, &createdByGroup); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if createdByGroup == 1 && userTunnelID > 0 {
|
||||||
|
groupCreatedTunnelIDs[userTunnelID] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
|
||||||
|
if _, err := tx.Exec(`DELETE FROM group_permission_grant WHERE user_group_id = ? AND tunnel_group_id = ?`, userGroupID, tunnelGroupID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for userTunnelID := range groupCreatedTunnelIDs {
|
||||||
|
var remaining int
|
||||||
|
if err := tx.QueryRow(`SELECT COUNT(1) FROM group_permission_grant WHERE user_tunnel_id = ?`, userTunnelID).Scan(&remaining); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if remaining == 0 {
|
||||||
|
if _, err := tx.Exec(`DELETE FROM user_tunnel WHERE id = ?`, userTunnelID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func queryPairs(db *store.DB, q string, args ...interface{}) ([][2]int64, error) {
|
func queryPairs(db *store.DB, q string, args ...interface{}) ([][2]int64, error) {
|
||||||
rows, err := db.Query(q, args...)
|
rows, err := db.Query(q, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -1932,13 +2153,14 @@ type tunnelRuntimeNode struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type tunnelCreateState struct {
|
type tunnelCreateState struct {
|
||||||
TunnelID int64
|
TunnelID int64
|
||||||
Type int
|
Type int
|
||||||
InNodes []tunnelRuntimeNode
|
IPPreference string // "" = auto, "v4" = prefer IPv4, "v6" = prefer IPv6
|
||||||
ChainHops [][]tunnelRuntimeNode
|
InNodes []tunnelRuntimeNode
|
||||||
OutNodes []tunnelRuntimeNode
|
ChainHops [][]tunnelRuntimeNode
|
||||||
Nodes map[int64]*nodeRecord
|
OutNodes []tunnelRuntimeNode
|
||||||
NodeIDList []int64
|
Nodes map[int64]*nodeRecord
|
||||||
|
NodeIDList []int64
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) prepareTunnelCreateState(tx *store.Tx, req map[string]interface{}, tunnelType int, excludeTunnelID int64) (*tunnelCreateState, error) {
|
func (h *Handler) prepareTunnelCreateState(tx *store.Tx, req map[string]interface{}, tunnelType int, excludeTunnelID int64) (*tunnelCreateState, error) {
|
||||||
@@ -2058,12 +2280,25 @@ func (h *Handler) prepareTunnelCreateState(tx *store.Tx, req map[string]interfac
|
|||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if node.Status != 1 {
|
if node.IsRemote != 1 && node.Status != 1 {
|
||||||
return nil, errors.New("部分节点不在线")
|
return nil, errors.New("部分节点不在线")
|
||||||
}
|
}
|
||||||
state.Nodes[nodeID] = node
|
state.Nodes[nodeID] = node
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for _, outNode := range state.OutNodes {
|
||||||
|
if err := validateRemoteNodePort(state.Nodes[outNode.NodeID], outNode.Port); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, hop := range state.ChainHops {
|
||||||
|
for _, chainNode := range hop {
|
||||||
|
if err := validateRemoteNodePort(state.Nodes[chainNode.NodeID], chainNode.Port); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return state, nil
|
return state, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2165,7 +2400,7 @@ func (h *Handler) federationLocalDomain() string {
|
|||||||
func (h *Handler) applyFederationRuntime(state *tunnelCreateState) ([]sqlite.FederationTunnelBinding, []federationRuntimeReleaseRef, error) {
|
func (h *Handler) applyFederationRuntime(state *tunnelCreateState) ([]sqlite.FederationTunnelBinding, []federationRuntimeReleaseRef, error) {
|
||||||
bindings := make([]sqlite.FederationTunnelBinding, 0)
|
bindings := make([]sqlite.FederationTunnelBinding, 0)
|
||||||
releaseRefs := make([]federationRuntimeReleaseRef, 0)
|
releaseRefs := make([]federationRuntimeReleaseRef, 0)
|
||||||
if h == nil || state == nil || state.Type != 2 {
|
if h == nil || state == nil {
|
||||||
return bindings, releaseRefs, nil
|
return bindings, releaseRefs, nil
|
||||||
}
|
}
|
||||||
fc := client.NewFederationClient()
|
fc := client.NewFederationClient()
|
||||||
@@ -2287,7 +2522,7 @@ func (h *Handler) applyFederationRuntime(state *tunnelCreateState) ([]sqlite.Fed
|
|||||||
h.releaseFederationRuntimeRefs(releaseRefs)
|
h.releaseFederationRuntimeRefs(releaseRefs)
|
||||||
return nil, nil, errors.New("节点不存在")
|
return nil, nil, errors.New("节点不存在")
|
||||||
}
|
}
|
||||||
host, hostErr := selectTunnelDialHost(node, targetNode)
|
host, hostErr := selectTunnelDialHost(node, targetNode, state.IPPreference)
|
||||||
if hostErr != nil {
|
if hostErr != nil {
|
||||||
h.releaseFederationRuntimeRefs(releaseRefs)
|
h.releaseFederationRuntimeRefs(releaseRefs)
|
||||||
return nil, nil, hostErr
|
return nil, nil, hostErr
|
||||||
@@ -2438,18 +2673,19 @@ func (h *Handler) applyTunnelRuntime(state *tunnelCreateState) ([]int64, []int64
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, inNode := range state.InNodes {
|
for _, inNode := range state.InNodes {
|
||||||
if node := state.Nodes[inNode.NodeID]; node != nil && node.IsRemote == 1 {
|
node := state.Nodes[inNode.NodeID]
|
||||||
continue
|
|
||||||
}
|
|
||||||
targets := state.OutNodes
|
targets := state.OutNodes
|
||||||
if len(state.ChainHops) > 0 {
|
if len(state.ChainHops) > 0 {
|
||||||
targets = state.ChainHops[0]
|
targets = state.ChainHops[0]
|
||||||
}
|
}
|
||||||
chainData, err := buildTunnelChainConfig(state.TunnelID, inNode.NodeID, targets, state.Nodes)
|
chainData, err := buildTunnelChainConfig(state.TunnelID, inNode.NodeID, targets, state.Nodes, state.IPPreference)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return createdChains, createdServices, err
|
return createdChains, createdServices, err
|
||||||
}
|
}
|
||||||
if _, err := h.sendNodeCommand(inNode.NodeID, "AddChains", chainData, true, false); err != nil {
|
if _, err := h.sendNodeCommand(inNode.NodeID, "AddChains", chainData, true, false); err != nil {
|
||||||
|
if node != nil && node.IsRemote == 1 && shouldDeferTunnelRuntimeApplyError(err) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
return createdChains, createdServices, fmt.Errorf("入口节点 %s 下发转发链失败: %w", nodeDisplayName(state.Nodes[inNode.NodeID]), err)
|
return createdChains, createdServices, fmt.Errorf("入口节点 %s 下发转发链失败: %w", nodeDisplayName(state.Nodes[inNode.NodeID]), err)
|
||||||
}
|
}
|
||||||
createdChains = append(createdChains, inNode.NodeID)
|
createdChains = append(createdChains, inNode.NodeID)
|
||||||
@@ -2464,7 +2700,7 @@ func (h *Handler) applyTunnelRuntime(state *tunnelCreateState) ([]int64, []int64
|
|||||||
if node := state.Nodes[chainNode.NodeID]; node != nil && node.IsRemote == 1 {
|
if node := state.Nodes[chainNode.NodeID]; node != nil && node.IsRemote == 1 {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
chainData, err := buildTunnelChainConfig(state.TunnelID, chainNode.NodeID, nextTargets, state.Nodes)
|
chainData, err := buildTunnelChainConfig(state.TunnelID, chainNode.NodeID, nextTargets, state.Nodes, state.IPPreference)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return createdChains, createdServices, err
|
return createdChains, createdServices, err
|
||||||
}
|
}
|
||||||
@@ -2539,7 +2775,7 @@ func shouldDeferTunnelRuntimeApplyError(err error) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildTunnelChainConfig(tunnelID int64, fromNodeID int64, targets []tunnelRuntimeNode, nodes map[int64]*nodeRecord) (map[string]interface{}, error) {
|
func buildTunnelChainConfig(tunnelID int64, fromNodeID int64, targets []tunnelRuntimeNode, nodes map[int64]*nodeRecord, ipPreference string) (map[string]interface{}, error) {
|
||||||
fromNode := nodes[fromNodeID]
|
fromNode := nodes[fromNodeID]
|
||||||
if fromNode == nil {
|
if fromNode == nil {
|
||||||
return nil, errors.New("节点不存在")
|
return nil, errors.New("节点不存在")
|
||||||
@@ -2553,7 +2789,7 @@ func buildTunnelChainConfig(tunnelID int64, fromNodeID int64, targets []tunnelRu
|
|||||||
if targetNode == nil {
|
if targetNode == nil {
|
||||||
return nil, errors.New("节点不存在")
|
return nil, errors.New("节点不存在")
|
||||||
}
|
}
|
||||||
host, err := selectTunnelDialHost(fromNode, targetNode)
|
host, err := selectTunnelDialHost(fromNode, targetNode, ipPreference)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -2561,14 +2797,19 @@ func buildTunnelChainConfig(tunnelID int64, fromNodeID int64, targets []tunnelRu
|
|||||||
if port <= 0 {
|
if port <= 0 {
|
||||||
return nil, errors.New("节点端口不能为空")
|
return nil, errors.New("节点端口不能为空")
|
||||||
}
|
}
|
||||||
|
protocol := defaultString(target.Protocol, "tls")
|
||||||
|
connector := map[string]interface{}{
|
||||||
|
"type": "relay",
|
||||||
|
}
|
||||||
|
if isTLSTunnelProtocol(protocol) {
|
||||||
|
connector["metadata"] = map[string]interface{}{"nodelay": true}
|
||||||
|
}
|
||||||
nodeItems = append(nodeItems, map[string]interface{}{
|
nodeItems = append(nodeItems, map[string]interface{}{
|
||||||
"name": fmt.Sprintf("node_%d", idx+1),
|
"name": fmt.Sprintf("node_%d", idx+1),
|
||||||
"addr": processServerAddress(fmt.Sprintf("%s:%d", host, port)),
|
"addr": processServerAddress(fmt.Sprintf("%s:%d", host, port)),
|
||||||
"connector": map[string]interface{}{
|
"connector": connector,
|
||||||
"type": "relay",
|
|
||||||
},
|
|
||||||
"dialer": map[string]interface{}{
|
"dialer": map[string]interface{}{
|
||||||
"type": defaultString(target.Protocol, "tls"),
|
"type": protocol,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -2597,14 +2838,19 @@ func buildTunnelChainServiceConfig(tunnelID int64, chainNode tunnelRuntimeNode,
|
|||||||
if node == nil {
|
if node == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
protocol := defaultString(chainNode.Protocol, "tls")
|
||||||
|
handlerCfg := map[string]interface{}{
|
||||||
|
"type": "relay",
|
||||||
|
}
|
||||||
|
if isTLSTunnelProtocol(protocol) {
|
||||||
|
handlerCfg["metadata"] = map[string]interface{}{"nodelay": true}
|
||||||
|
}
|
||||||
service := map[string]interface{}{
|
service := map[string]interface{}{
|
||||||
"name": fmt.Sprintf("%d_tls", tunnelID),
|
"name": fmt.Sprintf("%d_tls", tunnelID),
|
||||||
"addr": fmt.Sprintf("%s:%d", node.TCPListenAddr, chainNode.Port),
|
"addr": fmt.Sprintf("%s:%d", node.TCPListenAddr, chainNode.Port),
|
||||||
"handler": map[string]interface{}{
|
"handler": handlerCfg,
|
||||||
"type": "relay",
|
|
||||||
},
|
|
||||||
"listener": map[string]interface{}{
|
"listener": map[string]interface{}{
|
||||||
"type": defaultString(chainNode.Protocol, "tls"),
|
"type": protocol,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
if chainNode.ChainType == 2 {
|
if chainNode.ChainType == 2 {
|
||||||
@@ -2616,7 +2862,7 @@ func buildTunnelChainServiceConfig(tunnelID int64, chainNode tunnelRuntimeNode,
|
|||||||
return []map[string]interface{}{service}
|
return []map[string]interface{}{service}
|
||||||
}
|
}
|
||||||
|
|
||||||
func selectTunnelDialHost(fromNode, toNode *nodeRecord) (string, error) {
|
func selectTunnelDialHost(fromNode, toNode *nodeRecord, ipPreference string) (string, error) {
|
||||||
if fromNode == nil || toNode == nil {
|
if fromNode == nil || toNode == nil {
|
||||||
return "", errors.New("节点不存在")
|
return "", errors.New("节点不存在")
|
||||||
}
|
}
|
||||||
@@ -2625,16 +2871,39 @@ func selectTunnelDialHost(fromNode, toNode *nodeRecord) (string, error) {
|
|||||||
toV4 := nodeSupportsV4(toNode)
|
toV4 := nodeSupportsV4(toNode)
|
||||||
toV6 := nodeSupportsV6(toNode)
|
toV6 := nodeSupportsV6(toNode)
|
||||||
|
|
||||||
if fromV4 && toV4 {
|
switch strings.TrimSpace(ipPreference) {
|
||||||
host := pickNodeAddressV4(toNode)
|
case "v6":
|
||||||
if host != "" {
|
if fromV6 && toV6 {
|
||||||
return host, nil
|
if host := pickNodeAddressV6(toNode); host != "" {
|
||||||
|
return host, nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
if fromV4 && toV4 {
|
||||||
if fromV6 && toV6 {
|
if host := pickNodeAddressV4(toNode); host != "" {
|
||||||
host := pickNodeAddressV6(toNode)
|
return host, nil
|
||||||
if host != "" {
|
}
|
||||||
return host, nil
|
}
|
||||||
|
case "v4":
|
||||||
|
if fromV4 && toV4 {
|
||||||
|
if host := pickNodeAddressV4(toNode); host != "" {
|
||||||
|
return host, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if fromV6 && toV6 {
|
||||||
|
if host := pickNodeAddressV6(toNode); host != "" {
|
||||||
|
return host, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if fromV4 && toV4 {
|
||||||
|
if host := pickNodeAddressV4(toNode); host != "" {
|
||||||
|
return host, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if fromV6 && toV6 {
|
||||||
|
if host := pickNodeAddressV6(toNode); host != "" {
|
||||||
|
return host, nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return "", fmt.Errorf("节点链路不兼容:%s(v4=%t,v6=%t) -> %s(v4=%t,v6=%t)", nodeDisplayName(fromNode), fromV4, fromV6, nodeDisplayName(toNode), toV4, toV6)
|
return "", fmt.Errorf("节点链路不兼容:%s(v4=%t,v6=%t) -> %s(v4=%t,v6=%t)", nodeDisplayName(fromNode), fromV4, fromV6, nodeDisplayName(toNode), toV4, toV6)
|
||||||
@@ -2650,6 +2919,10 @@ func nodeDisplayName(node *nodeRecord) string {
|
|||||||
return fmt.Sprintf("node_%d", node.ID)
|
return fmt.Sprintf("node_%d", node.ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isTLSTunnelProtocol(protocol string) bool {
|
||||||
|
return strings.EqualFold(strings.TrimSpace(defaultString(protocol, "tls")), "tls")
|
||||||
|
}
|
||||||
|
|
||||||
func nodeSupportsV4(node *nodeRecord) bool {
|
func nodeSupportsV4(node *nodeRecord) bool {
|
||||||
if node == nil {
|
if node == nil {
|
||||||
return false
|
return false
|
||||||
@@ -2846,8 +3119,8 @@ func replaceTunnelChainsTx(tx *store.Tx, tunnelID int64, req map[string]interfac
|
|||||||
if nodeID <= 0 {
|
if nodeID <= 0 {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
_, err := tx.Exec(`INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol) VALUES(?, 1, ?, NULL, NULL, 0, ?)`,
|
_, err := tx.Exec(`INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol) VALUES(?, '1', ?, NULL, ?, 0, ?)`,
|
||||||
tunnelID, nodeID, defaultString(asString(n["protocol"]), "tls"))
|
tunnelID, nodeID, defaultString(asString(n["strategy"]), "round"), defaultString(asString(n["protocol"]), "tls"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -2865,7 +3138,7 @@ func replaceTunnelChainsTx(tx *store.Tx, tunnelID int64, req map[string]interfac
|
|||||||
return pickErr
|
return pickErr
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_, err := tx.Exec(`INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol) VALUES(?, 3, ?, ?, ?, 0, ?)`,
|
_, err := tx.Exec(`INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol) VALUES(?, '3', ?, ?, ?, 0, ?)`,
|
||||||
tunnelID, nodeID, port, defaultString(asString(n["strategy"]), "round"), defaultString(asString(n["protocol"]), "tls"))
|
tunnelID, nodeID, port, defaultString(asString(n["strategy"]), "round"), defaultString(asString(n["protocol"]), "tls"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -2886,7 +3159,7 @@ func replaceTunnelChainsTx(tx *store.Tx, tunnelID int64, req map[string]interfac
|
|||||||
return pickErr
|
return pickErr
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_, err := tx.Exec(`INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol) VALUES(?, 2, ?, ?, ?, ?, ?)`,
|
_, err := tx.Exec(`INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol) VALUES(?, '2', ?, ?, ?, ?, ?)`,
|
||||||
tunnelID, nodeID, port, defaultString(asString(n["strategy"]), "round"), i+1, defaultString(asString(n["protocol"]), "tls"))
|
tunnelID, nodeID, port, defaultString(asString(n["strategy"]), "round"), i+1, defaultString(asString(n["protocol"]), "tls"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -2972,7 +3245,7 @@ func (h *Handler) batchForwardStatus(ids []int64, status int) (int, int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) tunnelEntryNodeIDs(tunnelID int64) ([]int64, error) {
|
func (h *Handler) tunnelEntryNodeIDs(tunnelID int64) ([]int64, error) {
|
||||||
rows, err := h.repo.DB().Query(`SELECT node_id FROM chain_tunnel WHERE tunnel_id = ? AND chain_type = 1 ORDER BY inx ASC, id ASC`, tunnelID)
|
rows, err := h.repo.DB().Query(`SELECT node_id FROM chain_tunnel WHERE tunnel_id = ? AND chain_type = '1' ORDER BY inx ASC, id ASC`, tunnelID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -93,6 +93,8 @@ func shouldSkip(path string) bool {
|
|||||||
return true
|
return true
|
||||||
case path == "/api/v1/federation/runtime/diagnose":
|
case path == "/api/v1/federation/runtime/diagnose":
|
||||||
return true
|
return true
|
||||||
|
case path == "/api/v1/federation/runtime/command":
|
||||||
|
return true
|
||||||
default:
|
default:
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -115,6 +117,14 @@ func requiresAdmin(path string) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if strings.HasPrefix(path, "/api/v1/backup/") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.HasPrefix(path, "/api/v1/api/v1/backup/") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
if strings.HasPrefix(path, "/api/v1/tunnel/") {
|
if strings.HasPrefix(path, "/api/v1/tunnel/") {
|
||||||
if strings.HasPrefix(path, "/api/v1/tunnel/user/tunnel") {
|
if strings.HasPrefix(path, "/api/v1/tunnel/user/tunnel") {
|
||||||
return false
|
return false
|
||||||
@@ -127,6 +137,8 @@ func requiresAdmin(path string) bool {
|
|||||||
return true
|
return true
|
||||||
case "/api/v1/config/update", "/api/v1/config/update-single":
|
case "/api/v1/config/update", "/api/v1/config/update-single":
|
||||||
return true
|
return true
|
||||||
|
case "/api/v1/announcement/update":
|
||||||
|
return true
|
||||||
default:
|
default:
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|||||||
+234
-48
@@ -4,7 +4,7 @@ package store
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"fmt"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -98,7 +98,7 @@ func (db *DB) Begin() (*Tx, error) {
|
|||||||
func (db *DB) ExecReturningID(query string, args ...any) (int64, error) {
|
func (db *DB) ExecReturningID(query string, args ...any) (int64, error) {
|
||||||
q := db.rewrite(query)
|
q := db.rewrite(query)
|
||||||
if db.dialect == DialectPostgres {
|
if db.dialect == DialectPostgres {
|
||||||
q = strings.TrimRight(q, "; \t\n") + " RETURNING id"
|
q = ensureReturningID(q)
|
||||||
var id int64
|
var id int64
|
||||||
if err := db.raw.QueryRow(q, args...).Scan(&id); err != nil {
|
if err := db.raw.QueryRow(q, args...).Scan(&id); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
@@ -143,7 +143,7 @@ func (tx *Tx) Rollback() error { return tx.raw.Rollback() }
|
|||||||
func (tx *Tx) ExecReturningID(query string, args ...any) (int64, error) {
|
func (tx *Tx) ExecReturningID(query string, args ...any) (int64, error) {
|
||||||
q := rewriteQuery(tx.dialect, query)
|
q := rewriteQuery(tx.dialect, query)
|
||||||
if tx.dialect == DialectPostgres {
|
if tx.dialect == DialectPostgres {
|
||||||
q = strings.TrimRight(q, "; \t\n") + " RETURNING id"
|
q = ensureReturningID(q)
|
||||||
var id int64
|
var id int64
|
||||||
if err := tx.raw.QueryRow(q, args...).Scan(&id); err != nil {
|
if err := tx.raw.QueryRow(q, args...).Scan(&id); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
@@ -174,35 +174,15 @@ func rewriteQuery(dialect Dialect, query string) string {
|
|||||||
func rewriteUserIdentifier(query string) string {
|
func rewriteUserIdentifier(query string) string {
|
||||||
var buf strings.Builder
|
var buf strings.Builder
|
||||||
buf.Grow(len(query) + 16)
|
buf.Grow(len(query) + 16)
|
||||||
inSingle := false
|
|
||||||
inDouble := false
|
|
||||||
i := 0
|
i := 0
|
||||||
for i < len(query) {
|
for i < len(query) {
|
||||||
ch := query[i]
|
if end, ok := skipSQLProtectedSegment(query, i); ok {
|
||||||
if ch == '\'' && !inDouble {
|
buf.WriteString(query[i:end])
|
||||||
if inSingle && i+1 < len(query) && query[i+1] == '\'' {
|
i = end
|
||||||
buf.WriteByte(ch)
|
|
||||||
buf.WriteByte(query[i+1])
|
|
||||||
i += 2
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
inSingle = !inSingle
|
|
||||||
buf.WriteByte(ch)
|
|
||||||
i++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if ch == '"' && !inSingle {
|
|
||||||
inDouble = !inDouble
|
|
||||||
buf.WriteByte(ch)
|
|
||||||
i++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if inSingle || inDouble {
|
|
||||||
buf.WriteByte(ch)
|
|
||||||
i++
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ch := query[i]
|
||||||
if isIdentifierChar(ch) {
|
if isIdentifierChar(ch) {
|
||||||
j := i + 1
|
j := i + 1
|
||||||
for j < len(query) && isIdentifierChar(query[j]) {
|
for j < len(query) && isIdentifierChar(query[j]) {
|
||||||
@@ -238,39 +218,43 @@ func isIdentifierChar(ch byte) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func rewriteInsertOrIgnore(query string) string {
|
func rewriteInsertOrIgnore(query string) string {
|
||||||
upper := strings.ToUpper(query)
|
start, end, ok := findKeywordSequenceOutside(query, []string{"INSERT", "OR", "IGNORE", "INTO"}, 0)
|
||||||
idx := strings.Index(upper, "INSERT OR IGNORE INTO")
|
if !ok {
|
||||||
if idx < 0 {
|
|
||||||
return query
|
return query
|
||||||
}
|
}
|
||||||
prefix := query[:idx]
|
|
||||||
suffix := query[idx+len("INSERT OR IGNORE INTO"):]
|
|
||||||
result := prefix + "INSERT INTO" + suffix
|
|
||||||
|
|
||||||
trimmed := strings.TrimRight(result, "; \t\n")
|
rewritten := query[:start] + "INSERT INTO" + query[end:]
|
||||||
return trimmed + " ON CONFLICT DO NOTHING"
|
rewritten = strings.TrimRight(rewritten, "; \t\n")
|
||||||
|
|
||||||
|
insertIntoEnd := start + len("INSERT INTO")
|
||||||
|
if _, _, hasOnConflict := findKeywordSequenceOutside(rewritten, []string{"ON", "CONFLICT"}, insertIntoEnd); hasOnConflict {
|
||||||
|
return rewritten
|
||||||
|
}
|
||||||
|
|
||||||
|
if retStart, _, hasReturning := findKeywordSequenceOutside(rewritten, []string{"RETURNING"}, insertIntoEnd); hasReturning {
|
||||||
|
prefix := strings.TrimRight(rewritten[:retStart], " \t\n")
|
||||||
|
suffix := strings.TrimLeft(rewritten[retStart:], " \t\n")
|
||||||
|
return prefix + " ON CONFLICT DO NOTHING " + suffix
|
||||||
|
}
|
||||||
|
|
||||||
|
return rewritten + " ON CONFLICT DO NOTHING"
|
||||||
}
|
}
|
||||||
|
|
||||||
func rewritePlaceholders(query string) string {
|
func rewritePlaceholders(query string) string {
|
||||||
var buf strings.Builder
|
var buf strings.Builder
|
||||||
buf.Grow(len(query) + 16)
|
buf.Grow(len(query) + 16)
|
||||||
n := 1
|
n := 1
|
||||||
inString := false
|
|
||||||
for i := 0; i < len(query); i++ {
|
for i := 0; i < len(query); i++ {
|
||||||
ch := query[i]
|
if end, ok := skipSQLProtectedSegment(query, i); ok {
|
||||||
if ch == '\'' {
|
buf.WriteString(query[i:end])
|
||||||
if inString && i+1 < len(query) && query[i+1] == '\'' {
|
i = end - 1
|
||||||
buf.WriteByte(ch)
|
|
||||||
buf.WriteByte(query[i+1])
|
|
||||||
i++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
inString = !inString
|
|
||||||
buf.WriteByte(ch)
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if ch == '?' && !inString {
|
|
||||||
buf.WriteString(fmt.Sprintf("$%d", n))
|
ch := query[i]
|
||||||
|
if ch == '?' {
|
||||||
|
buf.WriteByte('$')
|
||||||
|
buf.WriteString(strconv.Itoa(n))
|
||||||
n++
|
n++
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -278,3 +262,205 @@ func rewritePlaceholders(query string) string {
|
|||||||
}
|
}
|
||||||
return buf.String()
|
return buf.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ensureReturningID(query string) string {
|
||||||
|
trimmed := strings.TrimRight(query, "; \t\n")
|
||||||
|
if _, _, ok := findKeywordSequenceOutside(trimmed, []string{"RETURNING"}, 0); ok {
|
||||||
|
return trimmed
|
||||||
|
}
|
||||||
|
return trimmed + " RETURNING id"
|
||||||
|
}
|
||||||
|
|
||||||
|
func findKeywordSequenceOutside(query string, keywords []string, from int) (int, int, bool) {
|
||||||
|
if len(keywords) == 0 {
|
||||||
|
return 0, 0, false
|
||||||
|
}
|
||||||
|
if from < 0 {
|
||||||
|
from = 0
|
||||||
|
}
|
||||||
|
if from >= len(query) {
|
||||||
|
return 0, 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
matched := 0
|
||||||
|
seqStart := -1
|
||||||
|
|
||||||
|
for i := from; i < len(query); {
|
||||||
|
if end, ok := skipSQLProtectedSegment(query, i); ok {
|
||||||
|
i = end
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
ch := query[i]
|
||||||
|
if isIdentifierChar(ch) {
|
||||||
|
j := i + 1
|
||||||
|
for j < len(query) && isIdentifierChar(query[j]) {
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
tok := query[i:j]
|
||||||
|
|
||||||
|
if strings.EqualFold(tok, keywords[matched]) {
|
||||||
|
if matched == 0 {
|
||||||
|
seqStart = i
|
||||||
|
}
|
||||||
|
matched++
|
||||||
|
if matched == len(keywords) {
|
||||||
|
return seqStart, j, true
|
||||||
|
}
|
||||||
|
} else if strings.EqualFold(tok, keywords[0]) {
|
||||||
|
seqStart = i
|
||||||
|
matched = 1
|
||||||
|
} else {
|
||||||
|
matched = 0
|
||||||
|
seqStart = -1
|
||||||
|
}
|
||||||
|
|
||||||
|
i = j
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if !isSQLSpace(ch) {
|
||||||
|
matched = 0
|
||||||
|
seqStart = -1
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0, 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func skipSQLProtectedSegment(query string, i int) (int, bool) {
|
||||||
|
if i < 0 || i >= len(query) {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
switch query[i] {
|
||||||
|
case '\'':
|
||||||
|
return skipSingleQuotedLiteral(query, i), true
|
||||||
|
case '"':
|
||||||
|
return skipDoubleQuotedIdentifier(query, i), true
|
||||||
|
case '-':
|
||||||
|
if i+1 < len(query) && query[i+1] == '-' {
|
||||||
|
return skipLineComment(query, i), true
|
||||||
|
}
|
||||||
|
case '/':
|
||||||
|
if i+1 < len(query) && query[i+1] == '*' {
|
||||||
|
return skipBlockComment(query, i), true
|
||||||
|
}
|
||||||
|
case '$':
|
||||||
|
if end, ok := skipDollarQuotedLiteral(query, i); ok {
|
||||||
|
return end, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func skipSingleQuotedLiteral(query string, i int) int {
|
||||||
|
for j := i + 1; j < len(query); j++ {
|
||||||
|
if query[j] != '\'' {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if j+1 < len(query) && query[j+1] == '\'' {
|
||||||
|
j++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return j + 1
|
||||||
|
}
|
||||||
|
return len(query)
|
||||||
|
}
|
||||||
|
|
||||||
|
func skipDoubleQuotedIdentifier(query string, i int) int {
|
||||||
|
for j := i + 1; j < len(query); j++ {
|
||||||
|
if query[j] != '"' {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if j+1 < len(query) && query[j+1] == '"' {
|
||||||
|
j++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return j + 1
|
||||||
|
}
|
||||||
|
return len(query)
|
||||||
|
}
|
||||||
|
|
||||||
|
func skipLineComment(query string, i int) int {
|
||||||
|
for j := i + 2; j < len(query); j++ {
|
||||||
|
if query[j] == '\n' {
|
||||||
|
return j
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return len(query)
|
||||||
|
}
|
||||||
|
|
||||||
|
func skipBlockComment(query string, i int) int {
|
||||||
|
depth := 1
|
||||||
|
for j := i + 2; j < len(query)-1; j++ {
|
||||||
|
if query[j] == '/' && query[j+1] == '*' {
|
||||||
|
depth++
|
||||||
|
j++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if query[j] == '*' && query[j+1] == '/' {
|
||||||
|
depth--
|
||||||
|
j++
|
||||||
|
if depth == 0 {
|
||||||
|
return j + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return len(query)
|
||||||
|
}
|
||||||
|
|
||||||
|
func skipDollarQuotedLiteral(query string, i int) (int, bool) {
|
||||||
|
if i < 0 || i >= len(query) || query[i] != '$' {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
if i+1 >= len(query) {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
var endTag int
|
||||||
|
if query[i+1] == '$' {
|
||||||
|
endTag = i + 1
|
||||||
|
} else {
|
||||||
|
if !isDollarTagStart(query[i+1]) {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
j := i + 2
|
||||||
|
for j < len(query) && isDollarTagChar(query[j]) {
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
if j >= len(query) || query[j] != '$' {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
endTag = j
|
||||||
|
}
|
||||||
|
|
||||||
|
tag := query[i : endTag+1]
|
||||||
|
if closeIdx := strings.Index(query[endTag+1:], tag); closeIdx >= 0 {
|
||||||
|
return endTag + 1 + closeIdx + len(tag), true
|
||||||
|
}
|
||||||
|
return len(query), true
|
||||||
|
}
|
||||||
|
|
||||||
|
func isDollarTagStart(ch byte) bool {
|
||||||
|
return ch == '_' || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
|
||||||
|
}
|
||||||
|
|
||||||
|
func isDollarTagChar(ch byte) bool {
|
||||||
|
if isDollarTagStart(ch) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return ch >= '0' && ch <= '9'
|
||||||
|
}
|
||||||
|
|
||||||
|
func isSQLSpace(ch byte) bool {
|
||||||
|
switch ch {
|
||||||
|
case ' ', '\t', '\n', '\r', '\f':
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestRewritePlaceholdersSkipsProtectedSegments(t *testing.T) {
|
||||||
|
q := `SELECT ?, '?', "id?", $$body ? $$, $tag$X?$tag$, col -- comment ?
|
||||||
|
FROM t /* block ? */ WHERE id = ?`
|
||||||
|
got := rewritePlaceholders(q)
|
||||||
|
want := `SELECT $1, '?', "id?", $$body ? $$, $tag$X?$tag$, col -- comment ?
|
||||||
|
FROM t /* block ? */ WHERE id = $2`
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("unexpected rewrite\nwant: %s\ngot: %s", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRewriteInsertOrIgnoreBasic(t *testing.T) {
|
||||||
|
q := `INSERT OR IGNORE INTO user_group_user(user_group_id, user_id, created_time) VALUES(?, ?, ?)`
|
||||||
|
got := rewriteInsertOrIgnore(q)
|
||||||
|
want := `INSERT INTO user_group_user(user_group_id, user_id, created_time) VALUES(?, ?, ?) ON CONFLICT DO NOTHING`
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("unexpected rewrite\nwant: %s\ngot: %s", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRewriteInsertOrIgnoreBeforeReturning(t *testing.T) {
|
||||||
|
q := `INSERT OR IGNORE INTO x(a) VALUES(?) RETURNING id`
|
||||||
|
got := rewriteInsertOrIgnore(q)
|
||||||
|
want := `INSERT INTO x(a) VALUES(?) ON CONFLICT DO NOTHING RETURNING id`
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("unexpected rewrite\nwant: %s\ngot: %s", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRewriteInsertOrIgnoreNotDuplicatingOnConflict(t *testing.T) {
|
||||||
|
q := `INSERT OR IGNORE INTO x(a) VALUES(?) ON CONFLICT(a) DO UPDATE SET a=excluded.a`
|
||||||
|
got := rewriteInsertOrIgnore(q)
|
||||||
|
want := `INSERT INTO x(a) VALUES(?) ON CONFLICT(a) DO UPDATE SET a=excluded.a`
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("unexpected rewrite\nwant: %s\ngot: %s", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureReturningID(t *testing.T) {
|
||||||
|
if got := ensureReturningID(`INSERT INTO x(a) VALUES($1)`); got != `INSERT INTO x(a) VALUES($1) RETURNING id` {
|
||||||
|
t.Fatalf("missing RETURNING append: %s", got)
|
||||||
|
}
|
||||||
|
if got := ensureReturningID(`INSERT INTO x(a) VALUES($1) RETURNING other_id`); got != `INSERT INTO x(a) VALUES($1) RETURNING other_id` {
|
||||||
|
t.Fatalf("RETURNING should not be duplicated: %s", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRewriteUserIdentifierSafety(t *testing.T) {
|
||||||
|
q := `SELECT user, user_id, 'user', "user", note FROM user -- user
|
||||||
|
WHERE owner='user'`
|
||||||
|
got := rewriteUserIdentifier(q)
|
||||||
|
want := `SELECT "user", user_id, 'user', "user", note FROM "user" -- user
|
||||||
|
WHERE owner='user'`
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("unexpected rewrite\nwant: %s\ngot: %s", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRewriteQueryPostgresPipeline(t *testing.T) {
|
||||||
|
q := `INSERT OR IGNORE INTO user(name, note) VALUES(?, '?')`
|
||||||
|
got := rewriteQuery(DialectPostgres, q)
|
||||||
|
want := `INSERT INTO "user"(name, note) VALUES($1, '?') ON CONFLICT DO NOTHING`
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("unexpected rewrite\nwant: %s\ngot: %s", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRewriteInsertOrIgnoreSkipsStringLiteral(t *testing.T) {
|
||||||
|
q := `SELECT 'INSERT OR IGNORE INTO t(a) VALUES(?)' AS q`
|
||||||
|
got := rewriteInsertOrIgnore(q)
|
||||||
|
if got != q {
|
||||||
|
t.Fatalf("string literal should stay unchanged\nwant: %s\ngot: %s", q, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRewriteInsertOrIgnoreSkipsCommentedKeyword(t *testing.T) {
|
||||||
|
q := `-- INSERT OR IGNORE INTO ignored(a) VALUES(?)
|
||||||
|
INSERT OR IGNORE INTO real_t(a) VALUES(?)`
|
||||||
|
got := rewriteInsertOrIgnore(q)
|
||||||
|
want := `-- INSERT OR IGNORE INTO ignored(a) VALUES(?)
|
||||||
|
INSERT INTO real_t(a) VALUES(?) ON CONFLICT DO NOTHING`
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("unexpected rewrite\nwant: %s\ngot: %s", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRewritePlaceholdersSkipsNestedBlockComment(t *testing.T) {
|
||||||
|
q := `SELECT ? /* outer ? /* inner ? */ still_outer ? */ FROM t WHERE id = ?`
|
||||||
|
got := rewritePlaceholders(q)
|
||||||
|
want := `SELECT $1 /* outer ? /* inner ? */ still_outer ? */ FROM t WHERE id = $2`
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("unexpected rewrite\nwant: %s\ngot: %s", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRewritePlaceholdersSkipsUnterminatedBlockComment(t *testing.T) {
|
||||||
|
q := `SELECT ? /* unterminated ? comment`
|
||||||
|
got := rewritePlaceholders(q)
|
||||||
|
want := `SELECT $1 /* unterminated ? comment`
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("unexpected rewrite\nwant: %s\ngot: %s", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRewriteUserIdentifierSkipsDollarQuotedAndComment(t *testing.T) {
|
||||||
|
q := `SELECT user, $$user ?$$ AS body, col FROM user /* user */ -- user`
|
||||||
|
got := rewriteUserIdentifier(q)
|
||||||
|
want := `SELECT "user", $$user ?$$ AS body, col FROM "user" /* user */ -- user`
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("unexpected rewrite\nwant: %s\ngot: %s", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -77,7 +77,8 @@ CREATE TABLE IF NOT EXISTS tunnel (
|
|||||||
updated_time BIGINT NOT NULL,
|
updated_time BIGINT NOT NULL,
|
||||||
status INTEGER NOT NULL,
|
status INTEGER NOT NULL,
|
||||||
in_ip TEXT,
|
in_ip TEXT,
|
||||||
inx INTEGER NOT NULL DEFAULT 0
|
inx INTEGER NOT NULL DEFAULT 0,
|
||||||
|
ip_preference VARCHAR(10) NOT NULL DEFAULT ''
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS chain_tunnel (
|
CREATE TABLE IF NOT EXISTS chain_tunnel (
|
||||||
@@ -239,3 +240,11 @@ CREATE TABLE IF NOT EXISTS federation_tunnel_binding (
|
|||||||
|
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_federation_tunnel_binding_unique ON federation_tunnel_binding(tunnel_id, node_id, chain_type, hop_inx);
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_federation_tunnel_binding_unique ON federation_tunnel_binding(tunnel_id, node_id, chain_type, hop_inx);
|
||||||
CREATE INDEX IF NOT EXISTS idx_federation_tunnel_binding_tunnel ON federation_tunnel_binding(tunnel_id, status);
|
CREATE INDEX IF NOT EXISTS idx_federation_tunnel_binding_tunnel ON federation_tunnel_binding(tunnel_id, status);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS announcement (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
enabled INTEGER NOT NULL DEFAULT 1,
|
||||||
|
created_time BIGINT NOT NULL,
|
||||||
|
updated_time BIGINT
|
||||||
|
);
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,78 @@
|
|||||||
|
package sqlite
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"go-backend/internal/store"
|
||||||
|
|
||||||
|
_ "modernc.org/sqlite"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMigrateSchemaRunsPostgresIDRepairEvenAtCurrentVersion(t *testing.T) {
|
||||||
|
raw, err := sql.Open("sqlite", ":memory:")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open sqlite: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = raw.Close()
|
||||||
|
})
|
||||||
|
|
||||||
|
db := store.Wrap(raw, store.DialectPostgres)
|
||||||
|
if _, err := db.Exec(`CREATE TABLE schema_version (version INTEGER NOT NULL DEFAULT 0)`); err != nil {
|
||||||
|
t.Fatalf("create schema_version: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := db.Exec(`INSERT INTO schema_version(version) VALUES(?)`, currentSchemaVersion); err != nil {
|
||||||
|
t.Fatalf("seed schema_version: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
called := 0
|
||||||
|
original := ensurePostgresIDDefaultsFn
|
||||||
|
ensurePostgresIDDefaultsFn = func(db *store.DB) error {
|
||||||
|
called++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
ensurePostgresIDDefaultsFn = original
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := migrateSchema(db); err != nil {
|
||||||
|
t.Fatalf("migrateSchema: %v", err)
|
||||||
|
}
|
||||||
|
if called != 1 {
|
||||||
|
t.Fatalf("expected postgres id repair to run once, got %d", called)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMigrateSchemaReturnsPostgresIDRepairError(t *testing.T) {
|
||||||
|
raw, err := sql.Open("sqlite", ":memory:")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open sqlite: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = raw.Close()
|
||||||
|
})
|
||||||
|
|
||||||
|
db := store.Wrap(raw, store.DialectPostgres)
|
||||||
|
if _, err := db.Exec(`CREATE TABLE schema_version (version INTEGER NOT NULL DEFAULT 0)`); err != nil {
|
||||||
|
t.Fatalf("create schema_version: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := db.Exec(`INSERT INTO schema_version(version) VALUES(?)`, currentSchemaVersion); err != nil {
|
||||||
|
t.Fatalf("seed schema_version: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
wantErr := errors.New("repair failed")
|
||||||
|
original := ensurePostgresIDDefaultsFn
|
||||||
|
ensurePostgresIDDefaultsFn = func(db *store.DB) error {
|
||||||
|
return wantErr
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
ensurePostgresIDDefaultsFn = original
|
||||||
|
})
|
||||||
|
|
||||||
|
err = migrateSchema(db)
|
||||||
|
if !errors.Is(err, wantErr) {
|
||||||
|
t.Fatalf("expected error %v, got %v", wantErr, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -80,7 +80,8 @@ CREATE TABLE IF NOT EXISTS tunnel (
|
|||||||
updated_time INTEGER NOT NULL,
|
updated_time INTEGER NOT NULL,
|
||||||
status INTEGER NOT NULL,
|
status INTEGER NOT NULL,
|
||||||
in_ip TEXT,
|
in_ip TEXT,
|
||||||
inx INTEGER NOT NULL DEFAULT 0
|
inx INTEGER NOT NULL DEFAULT 0,
|
||||||
|
ip_preference VARCHAR(10) NOT NULL DEFAULT ''
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS chain_tunnel (
|
CREATE TABLE IF NOT EXISTS chain_tunnel (
|
||||||
@@ -243,3 +244,11 @@ CREATE TABLE IF NOT EXISTS federation_tunnel_binding (
|
|||||||
|
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_federation_tunnel_binding_unique ON federation_tunnel_binding(tunnel_id, node_id, chain_type, hop_inx);
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_federation_tunnel_binding_unique ON federation_tunnel_binding(tunnel_id, node_id, chain_type, hop_inx);
|
||||||
CREATE INDEX IF NOT EXISTS idx_federation_tunnel_binding_tunnel ON federation_tunnel_binding(tunnel_id, status);
|
CREATE INDEX IF NOT EXISTS idx_federation_tunnel_binding_tunnel ON federation_tunnel_binding(tunnel_id, status);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS announcement (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
enabled INTEGER NOT NULL DEFAULT 1,
|
||||||
|
created_time INTEGER NOT NULL,
|
||||||
|
updated_time INTEGER
|
||||||
|
);
|
||||||
|
|||||||
@@ -78,6 +78,8 @@ func TestFederationDualPanelMiddleExitAutoPortContract(t *testing.T) {
|
|||||||
middleRemoteNodeID := queryRemoteNodeIDByToken(t, consumerRepo, "share-middle-token")
|
middleRemoteNodeID := queryRemoteNodeIDByToken(t, consumerRepo, "share-middle-token")
|
||||||
exitRemoteNodeID := queryRemoteNodeIDByToken(t, consumerRepo, "share-exit-token")
|
exitRemoteNodeID := queryRemoteNodeIDByToken(t, consumerRepo, "share-exit-token")
|
||||||
|
|
||||||
|
stopEntry := startMockNodeSession(t, providerServer.URL, "provider-entry-secret")
|
||||||
|
defer stopEntry()
|
||||||
stopMiddle := startMockNodeSession(t, providerServer.URL, "provider-middle-secret")
|
stopMiddle := startMockNodeSession(t, providerServer.URL, "provider-middle-secret")
|
||||||
defer stopMiddle()
|
defer stopMiddle()
|
||||||
stopExit := startMockNodeSession(t, providerServer.URL, "provider-exit-secret")
|
stopExit := startMockNodeSession(t, providerServer.URL, "provider-exit-secret")
|
||||||
@@ -148,6 +150,23 @@ func TestFederationDualPanelMiddleExitAutoPortContract(t *testing.T) {
|
|||||||
assertTunnelPortInRange(t, consumerRepo, secondTunnelID, 2, middleRemoteNodeID, 44000, 44010)
|
assertTunnelPortInRange(t, consumerRepo, secondTunnelID, 2, middleRemoteNodeID, 44000, 44010)
|
||||||
assertTunnelPortInRange(t, consumerRepo, secondTunnelID, 3, exitRemoteNodeID, 45000, 45010)
|
assertTunnelPortInRange(t, consumerRepo, secondTunnelID, 3, exitRemoteNodeID, 45000, 45010)
|
||||||
|
|
||||||
|
forwardPayload := map[string]interface{}{
|
||||||
|
"name": "dual-panel-remote-entry-forward",
|
||||||
|
"tunnelId": secondTunnelID,
|
||||||
|
"remoteAddr": "1.1.1.1:443",
|
||||||
|
"strategy": "fifo",
|
||||||
|
}
|
||||||
|
forwardBody, err := json.Marshal(forwardPayload)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal forward payload: %v", err)
|
||||||
|
}
|
||||||
|
forwardReq := httptest.NewRequest(http.MethodPost, "/api/v1/forward/create", bytes.NewReader(forwardBody))
|
||||||
|
forwardReq.Header.Set("Authorization", consumerAdminToken)
|
||||||
|
forwardReq.Header.Set("Content-Type", "application/json")
|
||||||
|
forwardRes := httptest.NewRecorder()
|
||||||
|
consumerRouter.ServeHTTP(forwardRes, forwardReq)
|
||||||
|
assertCode(t, forwardRes, 0)
|
||||||
|
|
||||||
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ? AND status = 1 AND applied = 1`, middleShareID, 1)
|
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ? AND status = 1 AND applied = 1`, middleShareID, 1)
|
||||||
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ? AND status = 1 AND applied = 1`, exitShareID, 1)
|
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ? AND status = 1 AND applied = 1`, exitShareID, 1)
|
||||||
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ?`, entryShareID, 0)
|
assertCount(t, providerRepo, `SELECT COUNT(1) FROM peer_share_runtime WHERE share_id = ?`, entryShareID, 0)
|
||||||
@@ -297,6 +316,136 @@ func TestFederationDualPanelRemoteDiagnosisContract(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestFederationDualPanelRemoteEntryRuntimeContract(t *testing.T) {
|
||||||
|
providerSecret := "provider-contract-jwt"
|
||||||
|
providerRouter, providerRepo := setupContractRouter(t, providerSecret)
|
||||||
|
providerServer := httptest.NewServer(providerRouter)
|
||||||
|
defer providerServer.Close()
|
||||||
|
|
||||||
|
consumerSecret := "consumer-contract-jwt"
|
||||||
|
consumerRouter, consumerRepo := setupContractRouter(t, consumerSecret)
|
||||||
|
|
||||||
|
consumerAdminToken, err := auth.GenerateToken(1, "consumer-admin", 0, consumerSecret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate consumer admin token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
providerEntryNodeID := insertContractNode(t, providerRepo, "provider-entry-rt", "198.51.100.21", "43020-43030", "provider-entry-rt-secret", 1)
|
||||||
|
providerMiddleNodeID := insertContractNode(t, providerRepo, "provider-middle-rt", "198.51.100.22", "44020-44030", "provider-middle-rt-secret", 1)
|
||||||
|
providerExitNodeID := insertContractNode(t, providerRepo, "provider-exit-rt", "198.51.100.23", "45020-45030", "provider-exit-rt-secret", 1)
|
||||||
|
|
||||||
|
insertPeerShare(t, providerRepo, &sqlite.PeerShare{
|
||||||
|
Name: "entry-share-rt",
|
||||||
|
NodeID: providerEntryNodeID,
|
||||||
|
Token: "share-entry-rt-token",
|
||||||
|
PortRangeStart: 43020,
|
||||||
|
PortRangeEnd: 43030,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
})
|
||||||
|
insertPeerShare(t, providerRepo, &sqlite.PeerShare{
|
||||||
|
Name: "middle-share-rt",
|
||||||
|
NodeID: providerMiddleNodeID,
|
||||||
|
Token: "share-middle-rt-token",
|
||||||
|
PortRangeStart: 44020,
|
||||||
|
PortRangeEnd: 44030,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
})
|
||||||
|
insertPeerShare(t, providerRepo, &sqlite.PeerShare{
|
||||||
|
Name: "exit-share-rt",
|
||||||
|
NodeID: providerExitNodeID,
|
||||||
|
Token: "share-exit-rt-token",
|
||||||
|
PortRangeStart: 45020,
|
||||||
|
PortRangeEnd: 45030,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
})
|
||||||
|
|
||||||
|
importRemoteNodeForContract(t, consumerRouter, consumerAdminToken, providerServer.URL, "share-entry-rt-token")
|
||||||
|
importRemoteNodeForContract(t, consumerRouter, consumerAdminToken, providerServer.URL, "share-middle-rt-token")
|
||||||
|
importRemoteNodeForContract(t, consumerRouter, consumerAdminToken, providerServer.URL, "share-exit-rt-token")
|
||||||
|
|
||||||
|
entryRemoteNodeID := queryRemoteNodeIDByToken(t, consumerRepo, "share-entry-rt-token")
|
||||||
|
middleRemoteNodeID := queryRemoteNodeIDByToken(t, consumerRepo, "share-middle-rt-token")
|
||||||
|
exitRemoteNodeID := queryRemoteNodeIDByToken(t, consumerRepo, "share-exit-rt-token")
|
||||||
|
|
||||||
|
var commandMu sync.Mutex
|
||||||
|
entryCommands := make([]string, 0, 8)
|
||||||
|
stopEntry := startMockNodeSessionWithHook(t, providerServer.URL, "provider-entry-rt-secret", func(cmdType string) {
|
||||||
|
commandMu.Lock()
|
||||||
|
entryCommands = append(entryCommands, cmdType)
|
||||||
|
commandMu.Unlock()
|
||||||
|
})
|
||||||
|
defer stopEntry()
|
||||||
|
stopMiddle := startMockNodeSession(t, providerServer.URL, "provider-middle-rt-secret")
|
||||||
|
defer stopMiddle()
|
||||||
|
stopExit := startMockNodeSession(t, providerServer.URL, "provider-exit-rt-secret")
|
||||||
|
defer stopExit()
|
||||||
|
|
||||||
|
createTunnel := func(name string) int64 {
|
||||||
|
payload := map[string]interface{}{
|
||||||
|
"name": name,
|
||||||
|
"type": 2,
|
||||||
|
"flow": 99999,
|
||||||
|
"status": 1,
|
||||||
|
"inNodeId": []map[string]interface{}{
|
||||||
|
{"nodeId": entryRemoteNodeID, "protocol": "tls", "strategy": "round"},
|
||||||
|
},
|
||||||
|
"chainNodes": [][]map[string]interface{}{
|
||||||
|
{{"nodeId": middleRemoteNodeID, "protocol": "tls", "strategy": "round"}},
|
||||||
|
},
|
||||||
|
"outNodeId": []map[string]interface{}{
|
||||||
|
{"nodeId": exitRemoteNodeID, "protocol": "tls", "strategy": "round"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
body, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal create payload: %v", err)
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/tunnel/create", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Authorization", consumerAdminToken)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
consumerRouter.ServeHTTP(res, req)
|
||||||
|
assertCode(t, res, 0)
|
||||||
|
|
||||||
|
var tunnelID int64
|
||||||
|
if err := consumerRepo.DB().QueryRow(`SELECT id FROM tunnel WHERE name = ? ORDER BY id DESC LIMIT 1`, name).Scan(&tunnelID); err != nil {
|
||||||
|
t.Fatalf("query tunnel id (%s): %v", name, err)
|
||||||
|
}
|
||||||
|
if tunnelID <= 0 {
|
||||||
|
t.Fatalf("invalid tunnel id for %s", name)
|
||||||
|
}
|
||||||
|
return tunnelID
|
||||||
|
}
|
||||||
|
|
||||||
|
createTunnel("dual-panel-remote-entry-online")
|
||||||
|
|
||||||
|
commandMu.Lock()
|
||||||
|
seenAddChains := false
|
||||||
|
seenCommands := append([]string(nil), entryCommands...)
|
||||||
|
for _, cmdType := range entryCommands {
|
||||||
|
if strings.EqualFold(strings.TrimSpace(cmdType), "AddChains") {
|
||||||
|
seenAddChains = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
commandMu.Unlock()
|
||||||
|
if !seenAddChains {
|
||||||
|
t.Fatalf("expected entry remote node to receive AddChains, commands=%v", seenCommands)
|
||||||
|
}
|
||||||
|
|
||||||
|
stopEntry()
|
||||||
|
waitNodeStatus(t, providerRepo, providerEntryNodeID, 0)
|
||||||
|
|
||||||
|
createTunnel("dual-panel-remote-entry-offline")
|
||||||
|
}
|
||||||
|
|
||||||
func insertContractNode(t *testing.T, repo *sqlite.Repository, name, ip, portRange, secret string, status int) int64 {
|
func insertContractNode(t *testing.T, repo *sqlite.Repository, name, ip, portRange, secret string, status int) int64 {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
now := time.Now().UnixMilli()
|
now := time.Now().UnixMilli()
|
||||||
@@ -390,6 +539,10 @@ func assertCount(t *testing.T, repo *sqlite.Repository, query string, arg interf
|
|||||||
}
|
}
|
||||||
|
|
||||||
func startMockNodeSession(t *testing.T, baseURL string, nodeSecret string) func() {
|
func startMockNodeSession(t *testing.T, baseURL string, nodeSecret string) func() {
|
||||||
|
return startMockNodeSessionWithHook(t, baseURL, nodeSecret, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func startMockNodeSessionWithHook(t *testing.T, baseURL string, nodeSecret string, onCommand func(cmdType string)) func() {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
u, err := url.Parse(baseURL)
|
u, err := url.Parse(baseURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -449,6 +602,9 @@ func startMockNodeSession(t *testing.T, baseURL string, nodeSecret string) func(
|
|||||||
if strings.TrimSpace(cmd.RequestID) == "" {
|
if strings.TrimSpace(cmd.RequestID) == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if onCommand != nil {
|
||||||
|
onCommand(strings.TrimSpace(cmd.Type))
|
||||||
|
}
|
||||||
|
|
||||||
respType := fmt.Sprintf("%sResponse", cmd.Type)
|
respType := fmt.Sprintf("%sResponse", cmd.Type)
|
||||||
respPayload := map[string]interface{}{
|
respPayload := map[string]interface{}{
|
||||||
@@ -473,9 +629,27 @@ func startMockNodeSession(t *testing.T, baseURL string, nodeSecret string) func(
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
var stopOnce sync.Once
|
||||||
return func() {
|
return func() {
|
||||||
_ = conn.Close()
|
stopOnce.Do(func() {
|
||||||
wg.Wait()
|
_ = conn.Close()
|
||||||
|
wg.Wait()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitNodeStatus(t *testing.T, repo *sqlite.Repository, nodeID int64, expectedStatus int) {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(2 * time.Second)
|
||||||
|
for {
|
||||||
|
var status int
|
||||||
|
if err := repo.DB().QueryRow(`SELECT status FROM node WHERE id = ?`, nodeID).Scan(&status); err == nil && status == expectedStatus {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatalf("node %d status did not reach %d before timeout", nodeID, expectedStatus)
|
||||||
|
}
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -514,3 +688,112 @@ func valueAsBool(v interface{}) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestFederationRuntimeCommandPortRangeEnforcement(t *testing.T) {
|
||||||
|
providerSecret := "provider-portrange-jwt"
|
||||||
|
providerRouter, providerRepo := setupContractRouter(t, providerSecret)
|
||||||
|
providerServer := httptest.NewServer(providerRouter)
|
||||||
|
defer providerServer.Close()
|
||||||
|
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
providerNodeID := insertContractNode(t, providerRepo, "provider-portrange-node", "198.51.100.50", "44000-44010", "provider-portrange-secret", 1)
|
||||||
|
|
||||||
|
insertPeerShare(t, providerRepo, &sqlite.PeerShare{
|
||||||
|
Name: "portrange-share",
|
||||||
|
NodeID: providerNodeID,
|
||||||
|
Token: "share-portrange-token",
|
||||||
|
PortRangeStart: 44000,
|
||||||
|
PortRangeEnd: 44010,
|
||||||
|
IsActive: 1,
|
||||||
|
CreatedTime: now,
|
||||||
|
UpdatedTime: now,
|
||||||
|
})
|
||||||
|
|
||||||
|
stopNode := startMockNodeSession(t, providerServer.URL, "provider-portrange-secret")
|
||||||
|
defer stopNode()
|
||||||
|
|
||||||
|
sendCommand := func(token string, cmdType string, data interface{}) *httptest.ResponseRecorder {
|
||||||
|
payload := map[string]interface{}{
|
||||||
|
"commandType": cmdType,
|
||||||
|
"data": data,
|
||||||
|
}
|
||||||
|
body, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal command payload: %v", err)
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/federation/runtime/command", bytes.NewReader(body))
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
providerRouter.ServeHTTP(res, req)
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test: AddService with port OUTSIDE allowed range should be rejected
|
||||||
|
outOfRangeData := map[string]interface{}{
|
||||||
|
"services": []map[string]interface{}{
|
||||||
|
{
|
||||||
|
"name": "test_service_tcp",
|
||||||
|
"addr": "[::]:55555",
|
||||||
|
"handler": map[string]interface{}{
|
||||||
|
"type": "tcp",
|
||||||
|
},
|
||||||
|
"listener": map[string]interface{}{
|
||||||
|
"type": "tcp",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
res := sendCommand("share-portrange-token", "AddService", outOfRangeData)
|
||||||
|
var out response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if out.Code != 403 {
|
||||||
|
t.Fatalf("expected code 403 for out-of-range port, got %d (msg: %s)", out.Code, out.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test: UpdateService with port OUTSIDE allowed range should be rejected
|
||||||
|
res = sendCommand("share-portrange-token", "UpdateService", outOfRangeData)
|
||||||
|
out = response.R{}
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if out.Code != 403 {
|
||||||
|
t.Fatalf("expected code 403 for out-of-range UpdateService, got %d (msg: %s)", out.Code, out.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test: AddService with port INSIDE allowed range should succeed
|
||||||
|
inRangeData := map[string]interface{}{
|
||||||
|
"services": []map[string]interface{}{
|
||||||
|
{
|
||||||
|
"name": "test_service_ok_tcp",
|
||||||
|
"addr": "[::]:44005",
|
||||||
|
"handler": map[string]interface{}{
|
||||||
|
"type": "tcp",
|
||||||
|
},
|
||||||
|
"listener": map[string]interface{}{
|
||||||
|
"type": "tcp",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
res = sendCommand("share-portrange-token", "AddService", inRangeData)
|
||||||
|
out = response.R{}
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if out.Code != 0 {
|
||||||
|
t.Fatalf("expected code 0 for in-range port, got %d (msg: %s)", out.Code, out.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test: Non-service commands should pass through without port validation
|
||||||
|
res = sendCommand("share-portrange-token", "reload", nil)
|
||||||
|
out = response.R{}
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if out.Code != 0 {
|
||||||
|
t.Fatalf("expected code 0 for reload command, got %d (msg: %s)", out.Code, out.Msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,219 @@
|
|||||||
|
package contract_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-backend/internal/auth"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGroupUserUnbindRevokesInheritedTunnelPermission(t *testing.T) {
|
||||||
|
secret := "contract-jwt-secret"
|
||||||
|
router, repo := setupContractRouter(t, secret)
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO user(id, user, pwd, role_id, exp_time, flow, in_flow, out_flow, flow_reset_time, num, created_time, updated_time, status)
|
||||||
|
VALUES(200, 'group_user_contract', '3c85cdebade1c51cf64ca9f3c09d182d', 1, 2727251700000, 99999, 0, 0, 1, 99999, ?, ?, 1)
|
||||||
|
`, now, now); err != nil {
|
||||||
|
t.Fatalf("insert test user: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tunnelRes, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx)
|
||||||
|
VALUES('group-contract-tunnel', 1.0, 1, 'tls', 99999, ?, ?, 1, NULL, 0)
|
||||||
|
`, now, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel: %v", err)
|
||||||
|
}
|
||||||
|
tunnelID, err := tunnelRes.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read tunnel id: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ugRes, err := repo.DB().Exec(`INSERT INTO user_group(name, created_time, updated_time, status) VALUES('ug-contract', ?, ?, 1)`, now, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert user_group: %v", err)
|
||||||
|
}
|
||||||
|
userGroupID, err := ugRes.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read user_group id: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tgRes, err := repo.DB().Exec(`INSERT INTO tunnel_group(name, created_time, updated_time, status) VALUES('tg-contract', ?, ?, 1)`, now, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel_group: %v", err)
|
||||||
|
}
|
||||||
|
tunnelGroupID, err := tgRes.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read tunnel_group id: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`INSERT INTO tunnel_group_tunnel(tunnel_group_id, tunnel_id, created_time) VALUES(?, ?, ?)`, tunnelGroupID, tunnelID, now); err != nil {
|
||||||
|
t.Fatalf("insert tunnel_group_tunnel: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.DB().Exec(`INSERT INTO group_permission(user_group_id, tunnel_group_id, created_time) VALUES(?, ?, ?)`, userGroupID, tunnelGroupID, now); err != nil {
|
||||||
|
t.Fatalf("insert group_permission: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
adminToken, err := auth.GenerateToken(1, "admin_user", 0, secret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate admin token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
bindReq := httptest.NewRequest(http.MethodPost, "/api/v1/group/user/assign", bytes.NewBufferString(`{"groupId":`+jsonNumber(userGroupID)+`,"userIds":[200]}`))
|
||||||
|
bindReq.Header.Set("Authorization", adminToken)
|
||||||
|
bindRes := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(bindRes, bindReq)
|
||||||
|
assertCode(t, bindRes, 0)
|
||||||
|
|
||||||
|
var userTunnelID int64
|
||||||
|
if err := repo.DB().QueryRow(`SELECT id FROM user_tunnel WHERE user_id = 200 AND tunnel_id = ?`, tunnelID).Scan(&userTunnelID); err != nil {
|
||||||
|
t.Fatalf("query user_tunnel after bind: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var grantCount int
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COUNT(1) FROM group_permission_grant WHERE user_tunnel_id = ?`, userTunnelID).Scan(&grantCount); err != nil {
|
||||||
|
t.Fatalf("query group_permission_grant after bind: %v", err)
|
||||||
|
}
|
||||||
|
if grantCount == 0 {
|
||||||
|
t.Fatalf("expected non-zero grants after bind")
|
||||||
|
}
|
||||||
|
|
||||||
|
unbindReq := httptest.NewRequest(http.MethodPost, "/api/v1/group/user/assign", bytes.NewBufferString(`{"groupId":`+jsonNumber(userGroupID)+`,"userIds":[]}`))
|
||||||
|
unbindReq.Header.Set("Authorization", adminToken)
|
||||||
|
unbindRes := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(unbindRes, unbindReq)
|
||||||
|
assertCode(t, unbindRes, 0)
|
||||||
|
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COUNT(1) FROM group_permission_grant WHERE user_tunnel_id = ?`, userTunnelID).Scan(&grantCount); err != nil {
|
||||||
|
t.Fatalf("query group_permission_grant after unbind: %v", err)
|
||||||
|
}
|
||||||
|
if grantCount != 0 {
|
||||||
|
t.Fatalf("expected grants revoked after unbind, got %d", grantCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
var userTunnelCount int
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COUNT(1) FROM user_tunnel WHERE id = ?`, userTunnelID).Scan(&userTunnelCount); err != nil {
|
||||||
|
t.Fatalf("query user_tunnel after unbind: %v", err)
|
||||||
|
}
|
||||||
|
if userTunnelCount != 0 {
|
||||||
|
t.Fatalf("expected user_tunnel revoked after unbind, got %d", userTunnelCount)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGroupPermissionRemoveRevokesInheritedTunnelPermission(t *testing.T) {
|
||||||
|
secret := "contract-jwt-secret"
|
||||||
|
router, repo := setupContractRouter(t, secret)
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO user(id, user, pwd, role_id, exp_time, flow, in_flow, out_flow, flow_reset_time, num, created_time, updated_time, status)
|
||||||
|
VALUES(201, 'group_user_permission_remove', '3c85cdebade1c51cf64ca9f3c09d182d', 1, 2727251700000, 99999, 0, 0, 1, 99999, ?, ?, 1)
|
||||||
|
`, now, now); err != nil {
|
||||||
|
t.Fatalf("insert test user: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tunnelRes, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx)
|
||||||
|
VALUES('group-remove-tunnel', 1.0, 1, 'tls', 99999, ?, ?, 1, NULL, 0)
|
||||||
|
`, now, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel: %v", err)
|
||||||
|
}
|
||||||
|
tunnelID, err := tunnelRes.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read tunnel id: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ugRes, err := repo.DB().Exec(`INSERT INTO user_group(name, created_time, updated_time, status) VALUES('ug-remove-contract', ?, ?, 1)`, now, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert user_group: %v", err)
|
||||||
|
}
|
||||||
|
userGroupID, err := ugRes.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read user_group id: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tgRes, err := repo.DB().Exec(`INSERT INTO tunnel_group(name, created_time, updated_time, status) VALUES('tg-remove-contract', ?, ?, 1)`, now, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel_group: %v", err)
|
||||||
|
}
|
||||||
|
tunnelGroupID, err := tgRes.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read tunnel_group id: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
adminToken, err := auth.GenerateToken(1, "admin_user", 0, secret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate admin token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
assignTunnelReq := httptest.NewRequest(http.MethodPost, "/api/v1/group/tunnel/assign", bytes.NewBufferString(`{"groupId":`+jsonNumber(tunnelGroupID)+`,"tunnelIds":[`+jsonNumber(tunnelID)+`]}`))
|
||||||
|
assignTunnelReq.Header.Set("Authorization", adminToken)
|
||||||
|
assignTunnelRes := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(assignTunnelRes, assignTunnelReq)
|
||||||
|
assertCode(t, assignTunnelRes, 0)
|
||||||
|
|
||||||
|
assignUserReq := httptest.NewRequest(http.MethodPost, "/api/v1/group/user/assign", bytes.NewBufferString(`{"groupId":`+jsonNumber(userGroupID)+`,"userIds":[201]}`))
|
||||||
|
assignUserReq.Header.Set("Authorization", adminToken)
|
||||||
|
assignUserRes := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(assignUserRes, assignUserReq)
|
||||||
|
assertCode(t, assignUserRes, 0)
|
||||||
|
|
||||||
|
assignPermissionReq := httptest.NewRequest(http.MethodPost, "/api/v1/group/permission/assign", bytes.NewBufferString(`{"userGroupId":`+jsonNumber(userGroupID)+`,"tunnelGroupId":`+jsonNumber(tunnelGroupID)+`}`))
|
||||||
|
assignPermissionReq.Header.Set("Authorization", adminToken)
|
||||||
|
assignPermissionRes := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(assignPermissionRes, assignPermissionReq)
|
||||||
|
assertCode(t, assignPermissionRes, 0)
|
||||||
|
|
||||||
|
var permissionID int64
|
||||||
|
if err := repo.DB().QueryRow(`SELECT id FROM group_permission WHERE user_group_id = ? AND tunnel_group_id = ?`, userGroupID, tunnelGroupID).Scan(&permissionID); err != nil {
|
||||||
|
t.Fatalf("query group_permission id: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var userTunnelID int64
|
||||||
|
if err := repo.DB().QueryRow(`SELECT id FROM user_tunnel WHERE user_id = 201 AND tunnel_id = ?`, tunnelID).Scan(&userTunnelID); err != nil {
|
||||||
|
t.Fatalf("query user_tunnel after assign: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var grantCount int
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COUNT(1) FROM group_permission_grant WHERE user_tunnel_id = ?`, userTunnelID).Scan(&grantCount); err != nil {
|
||||||
|
t.Fatalf("query group_permission_grant after assign: %v", err)
|
||||||
|
}
|
||||||
|
if grantCount == 0 {
|
||||||
|
t.Fatalf("expected non-zero grants after permission assign")
|
||||||
|
}
|
||||||
|
|
||||||
|
removeReq := httptest.NewRequest(http.MethodPost, "/api/v1/group/permission/remove", bytes.NewBufferString(`{"id":`+jsonNumber(permissionID)+`}`))
|
||||||
|
removeReq.Header.Set("Authorization", adminToken)
|
||||||
|
removeRes := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(removeRes, removeReq)
|
||||||
|
assertCode(t, removeRes, 0)
|
||||||
|
|
||||||
|
var permissionCount int
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COUNT(1) FROM group_permission WHERE id = ?`, permissionID).Scan(&permissionCount); err != nil {
|
||||||
|
t.Fatalf("query group_permission after remove: %v", err)
|
||||||
|
}
|
||||||
|
if permissionCount != 0 {
|
||||||
|
t.Fatalf("expected group_permission removed, got %d", permissionCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COUNT(1) FROM group_permission_grant WHERE user_tunnel_id = ?`, userTunnelID).Scan(&grantCount); err != nil {
|
||||||
|
t.Fatalf("query group_permission_grant after remove: %v", err)
|
||||||
|
}
|
||||||
|
if grantCount != 0 {
|
||||||
|
t.Fatalf("expected grants removed after permission remove, got %d", grantCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
var userTunnelCount int
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COUNT(1) FROM user_tunnel WHERE id = ?`, userTunnelID).Scan(&userTunnelCount); err != nil {
|
||||||
|
t.Fatalf("query user_tunnel after permission remove: %v", err)
|
||||||
|
}
|
||||||
|
if userTunnelCount != 0 {
|
||||||
|
t.Fatalf("expected user_tunnel revoked after permission remove, got %d", userTunnelCount)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -203,6 +203,399 @@ func TestSpeedLimitTunnelsRouteAlias(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestBackupExportImportRestoreContracts(t *testing.T) {
|
||||||
|
secret := "contract-jwt-secret"
|
||||||
|
router, repo := setupContractRouter(t, secret)
|
||||||
|
|
||||||
|
adminToken, err := auth.GenerateToken(1, "admin_user", 0, secret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate admin token: %v", err)
|
||||||
|
}
|
||||||
|
userToken, err := auth.GenerateToken(2, "normal_user", 1, secret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate user token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
key := "backup_contract_key"
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO vite_config(name, value, time)
|
||||||
|
VALUES(?, ?, ?)
|
||||||
|
ON CONFLICT(name) DO UPDATE SET value = excluded.value, time = excluded.time
|
||||||
|
`, key, "v1", time.Now().UnixMilli()); err != nil {
|
||||||
|
t.Fatalf("seed config for backup contract: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("non-admin is blocked on backup export", func(t *testing.T) {
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/backup/export", nil)
|
||||||
|
req.Header.Set("Authorization", userToken)
|
||||||
|
resp := httptest.NewRecorder()
|
||||||
|
|
||||||
|
router.ServeHTTP(resp, req)
|
||||||
|
assertCodeMsg(t, resp, 403, "权限不足,仅管理员可操作")
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("standard and duplicate export routes both work", func(t *testing.T) {
|
||||||
|
payloadA := exportBackupPayload(t, router, "/api/v1/backup/export", adminToken)
|
||||||
|
if len(payloadA.Configs) == 0 {
|
||||||
|
t.Fatalf("expected exported configs, got none")
|
||||||
|
}
|
||||||
|
if _, ok := payloadA.Configs[key]; !ok {
|
||||||
|
t.Fatalf("expected %q in exported configs", key)
|
||||||
|
}
|
||||||
|
|
||||||
|
payloadB := exportBackupPayload(t, router, "/api/v1/api/v1/backup/export", adminToken)
|
||||||
|
if len(payloadB.Configs) == 0 {
|
||||||
|
t.Fatalf("expected exported configs from duplicate-prefix route, got none")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("backup import applies exported data", func(t *testing.T) {
|
||||||
|
payload := exportBackupPayload(t, router, "/api/v1/backup/export", adminToken)
|
||||||
|
payload.Configs[key] = "v2"
|
||||||
|
raw, err := json.Marshal(backupImportPayload{Types: []string{"configs"}, backupExportPayload: payload})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal import payload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/backup/import", bytes.NewReader(raw))
|
||||||
|
req.Header.Set("Authorization", adminToken)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
resp := httptest.NewRecorder()
|
||||||
|
|
||||||
|
router.ServeHTTP(resp, req)
|
||||||
|
var out response.R
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode import response: %v", err)
|
||||||
|
}
|
||||||
|
if out.Code != 0 {
|
||||||
|
t.Fatalf("expected import code 0, got %d (%s)", out.Code, out.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := repo.GetConfigByName(key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("query imported config: %v", err)
|
||||||
|
}
|
||||||
|
if cfg == nil || cfg.Value != "v2" {
|
||||||
|
t.Fatalf("expected imported config value v2, got %+v", cfg)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("backup restore alias applies exported data", func(t *testing.T) {
|
||||||
|
payload := exportBackupPayload(t, router, "/api/v1/backup/export", adminToken)
|
||||||
|
payload.Configs[key] = "v3"
|
||||||
|
raw, err := json.Marshal(backupImportPayload{Types: []string{"configs"}, backupExportPayload: payload})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal restore payload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/backup/restore", bytes.NewReader(raw))
|
||||||
|
req.Header.Set("Authorization", adminToken)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
resp := httptest.NewRecorder()
|
||||||
|
|
||||||
|
router.ServeHTTP(resp, req)
|
||||||
|
var out response.R
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode restore response: %v", err)
|
||||||
|
}
|
||||||
|
if out.Code != 0 {
|
||||||
|
t.Fatalf("expected restore code 0, got %d (%s)", out.Code, out.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := repo.GetConfigByName(key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("query restored config: %v", err)
|
||||||
|
}
|
||||||
|
if cfg == nil || cfg.Value != "v3" {
|
||||||
|
t.Fatalf("expected restored config value v3, got %+v", cfg)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("backup export and import preserve forward ports", func(t *testing.T) {
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
tunnelRes, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, "backup-forward-tunnel", 1.0, 1, "tls", 0, now, now, 1, "", 88)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("seed tunnel for forward backup: %v", err)
|
||||||
|
}
|
||||||
|
tunnelID, err := tunnelRes.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read tunnel id for forward backup: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
forwardRes, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO forward(user_id, user_name, name, tunnel_id, remote_addr, strategy, in_flow, out_flow, created_time, updated_time, status, inx)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, 1, "admin_user", "backup-forward", tunnelID, "127.0.0.1:9000", "fifo", 0, 0, now, now, 1, 88)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("seed forward for backup: %v", err)
|
||||||
|
}
|
||||||
|
forwardID, err := forwardRes.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read forward id for backup: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
expected := map[int64]int{
|
||||||
|
2001: 21001,
|
||||||
|
2002: 21002,
|
||||||
|
}
|
||||||
|
for nodeID, port := range expected {
|
||||||
|
if _, err := repo.DB().Exec(`INSERT INTO forward_port(forward_id, node_id, port) VALUES(?, ?, ?)`, forwardID, nodeID, port); err != nil {
|
||||||
|
t.Fatalf("seed forward_port %d:%d: %v", nodeID, port, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
exportReq := httptest.NewRequest(http.MethodPost, "/api/v1/backup/export", bytes.NewBufferString(`{"types":["forwards"]}`))
|
||||||
|
exportReq.Header.Set("Authorization", adminToken)
|
||||||
|
exportReq.Header.Set("Content-Type", "application/json")
|
||||||
|
exportResp := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(exportResp, exportReq)
|
||||||
|
|
||||||
|
if exportResp.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected export status 200, got %d", exportResp.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
exportBody, err := io.ReadAll(exportResp.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read forwards backup body: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload map[string]interface{}
|
||||||
|
if err := json.Unmarshal(exportBody, &payload); err != nil {
|
||||||
|
t.Fatalf("decode forwards backup payload: %v", err)
|
||||||
|
}
|
||||||
|
version, _ := payload["version"].(string)
|
||||||
|
if strings.TrimSpace(version) == "" {
|
||||||
|
t.Fatalf("expected backup payload version, body=%s", string(exportBody))
|
||||||
|
}
|
||||||
|
|
||||||
|
forwardsRaw, ok := payload["forwards"].([]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected forwards array in payload, body=%s", string(exportBody))
|
||||||
|
}
|
||||||
|
|
||||||
|
foundForward := false
|
||||||
|
foundPorts := map[int64]int{}
|
||||||
|
for _, item := range forwardsRaw {
|
||||||
|
forwardMap, ok := item.(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
idValue, ok := forwardMap["id"].(float64)
|
||||||
|
if !ok || int64(idValue) != forwardID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
foundForward = true
|
||||||
|
|
||||||
|
portsRaw, ok := forwardMap["forwardPorts"].([]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected forwardPorts for forward %d in payload", forwardID)
|
||||||
|
}
|
||||||
|
for _, p := range portsRaw {
|
||||||
|
portMap, ok := p.(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
nodeID, nodeOK := portMap["nodeId"].(float64)
|
||||||
|
port, portOK := portMap["port"].(float64)
|
||||||
|
if nodeOK && portOK {
|
||||||
|
foundPorts[int64(nodeID)] = int(port)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if !foundForward {
|
||||||
|
t.Fatalf("expected forward %d in exported forwards payload", forwardID)
|
||||||
|
}
|
||||||
|
if len(foundPorts) != len(expected) {
|
||||||
|
t.Fatalf("expected %d exported forward ports, got %d", len(expected), len(foundPorts))
|
||||||
|
}
|
||||||
|
for nodeID, port := range expected {
|
||||||
|
if got, ok := foundPorts[nodeID]; !ok || got != port {
|
||||||
|
t.Fatalf("expected exported forward port node=%d port=%d, got %v", nodeID, port, foundPorts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`DELETE FROM forward_port WHERE forward_id = ?`, forwardID); err != nil {
|
||||||
|
t.Fatalf("clear forward_port before import: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.DB().Exec(`INSERT INTO forward_port(forward_id, node_id, port) VALUES(?, ?, ?)`, forwardID, 9999, 39999); err != nil {
|
||||||
|
t.Fatalf("seed wrong forward_port before import: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
payload["types"] = []string{"forwards"}
|
||||||
|
importBody, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal forwards import payload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
importReq := httptest.NewRequest(http.MethodPost, "/api/v1/backup/import", bytes.NewReader(importBody))
|
||||||
|
importReq.Header.Set("Authorization", adminToken)
|
||||||
|
importReq.Header.Set("Content-Type", "application/json")
|
||||||
|
importResp := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(importResp, importReq)
|
||||||
|
|
||||||
|
var out response.R
|
||||||
|
if err := json.NewDecoder(importResp.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode forwards import response: %v", err)
|
||||||
|
}
|
||||||
|
if out.Code != 0 {
|
||||||
|
t.Fatalf("expected forwards import code 0, got %d (%s)", out.Code, out.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, err := repo.DB().Query(`SELECT node_id, port FROM forward_port WHERE forward_id = ? ORDER BY id ASC`, forwardID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("query forward ports after import: %v", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
after := make(map[int64]int)
|
||||||
|
for rows.Next() {
|
||||||
|
var nodeID int64
|
||||||
|
var port int
|
||||||
|
if err := rows.Scan(&nodeID, &port); err != nil {
|
||||||
|
t.Fatalf("scan forward_port row: %v", err)
|
||||||
|
}
|
||||||
|
after[nodeID] = port
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
t.Fatalf("iterate forward_port rows: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(after) != len(expected) {
|
||||||
|
t.Fatalf("expected %d forward ports after import, got %d (%v)", len(expected), len(after), after)
|
||||||
|
}
|
||||||
|
for nodeID, port := range expected {
|
||||||
|
if got, ok := after[nodeID]; !ok || got != port {
|
||||||
|
t.Fatalf("expected forward_port node=%d port=%d after import, got %v", nodeID, port, after)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("backup export tolerates nullable legacy tunnel chain fields", func(t *testing.T) {
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
res, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, "legacy-null-chain", 1.0, 1, "tls", 1000, now, now, 1, nil, 1)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("seed tunnel for nullable chain export: %v", err)
|
||||||
|
}
|
||||||
|
tunnelID, err := res.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read tunnel id for nullable chain export: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO chain_tunnel(tunnel_id, chain_type, node_id, port, strategy, inx, protocol)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, tunnelID, "1", 1, nil, nil, nil, nil); err != nil {
|
||||||
|
t.Fatalf("seed nullable chain_tunnel row: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/backup/export", bytes.NewBufferString(`{"types":["tunnels"]}`))
|
||||||
|
req.Header.Set("Authorization", adminToken)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
resp := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(resp, req)
|
||||||
|
|
||||||
|
if resp.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status 200, got %d", resp.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
Tunnels []struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
ChainTunnels []struct {
|
||||||
|
Inx int `json:"inx"`
|
||||||
|
Strategy string `json:"strategy"`
|
||||||
|
Protocol string `json:"protocol"`
|
||||||
|
} `json:"chainTunnels"`
|
||||||
|
} `json:"tunnels"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
|
||||||
|
t.Fatalf("decode tunnels backup payload: %v", err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(payload.Version) == "" {
|
||||||
|
t.Fatalf("expected backup payload version, got empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
found := false
|
||||||
|
for _, tunnel := range payload.Tunnels {
|
||||||
|
if tunnel.ID != tunnelID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(tunnel.ChainTunnels) != 1 {
|
||||||
|
t.Fatalf("expected one chain tunnel for seeded tunnel %d, got %d", tunnelID, len(tunnel.ChainTunnels))
|
||||||
|
}
|
||||||
|
if tunnel.ChainTunnels[0].Inx != 0 {
|
||||||
|
t.Fatalf("expected nullable chain inx to export as 0, got %d", tunnel.ChainTunnels[0].Inx)
|
||||||
|
}
|
||||||
|
if tunnel.ChainTunnels[0].Strategy != "" {
|
||||||
|
t.Fatalf("expected nullable chain strategy to export as empty string, got %q", tunnel.ChainTunnels[0].Strategy)
|
||||||
|
}
|
||||||
|
if tunnel.ChainTunnels[0].Protocol != "" {
|
||||||
|
t.Fatalf("expected nullable chain protocol to export as empty string, got %q", tunnel.ChainTunnels[0].Protocol)
|
||||||
|
}
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatalf("expected seeded tunnel %d in backup export", tunnelID)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type backupExportPayload struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
ExportedAt int64 `json:"exportedAt"`
|
||||||
|
Configs map[string]string `json:"configs"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type backupImportPayload struct {
|
||||||
|
Types []string `json:"types"`
|
||||||
|
backupExportPayload
|
||||||
|
}
|
||||||
|
|
||||||
|
func exportBackupPayload(t *testing.T, router http.Handler, path, token string) backupExportPayload {
|
||||||
|
t.Helper()
|
||||||
|
req := httptest.NewRequest(http.MethodPost, path, bytes.NewBufferString(`{"types":["configs"]}`))
|
||||||
|
req.Header.Set("Authorization", token)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
resp := httptest.NewRecorder()
|
||||||
|
|
||||||
|
router.ServeHTTP(resp, req)
|
||||||
|
if resp.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status 200 on %s, got %d", path, resp.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read backup payload from %s: %v", path, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload backupExportPayload
|
||||||
|
if err := json.Unmarshal(body, &payload); err != nil {
|
||||||
|
t.Fatalf("decode backup payload from %s: %v", path, err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(payload.Version) == "" {
|
||||||
|
var out response.R
|
||||||
|
if err := json.Unmarshal(body, &out); err == nil {
|
||||||
|
t.Fatalf("expected backup payload on %s, got envelope code=%d msg=%q", path, out.Code, out.Msg)
|
||||||
|
}
|
||||||
|
t.Fatalf("expected non-empty backup payload version on %s, body=%s", path, string(body))
|
||||||
|
}
|
||||||
|
if payload.Configs == nil {
|
||||||
|
t.Fatalf("expected configs map in backup payload on %s", path)
|
||||||
|
}
|
||||||
|
return payload
|
||||||
|
}
|
||||||
|
|
||||||
func setupContractRouter(t *testing.T, jwtSecret string) (http.Handler, *sqlite.Repository) {
|
func setupContractRouter(t *testing.T, jwtSecret string) (http.Handler, *sqlite.Repository) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
dbPath := filepath.Join(t.TempDir(), "contract.db")
|
dbPath := filepath.Join(t.TempDir(), "contract.db")
|
||||||
|
|||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package contract_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
_ "github.com/jackc/pgx/v5/stdlib"
|
||||||
|
|
||||||
|
"go-backend/internal/auth"
|
||||||
|
httpserver "go-backend/internal/http"
|
||||||
|
"go-backend/internal/http/handler"
|
||||||
|
"go-backend/internal/store/sqlite"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPostgresNodeCreateRepairsMissingIDDefaultContract(t *testing.T) {
|
||||||
|
baseDSN := strings.TrimSpace(os.Getenv("FLVX_POSTGRES_TEST_DSN"))
|
||||||
|
if baseDSN == "" {
|
||||||
|
t.Skip("set FLVX_POSTGRES_TEST_DSN to run postgres contract tests")
|
||||||
|
}
|
||||||
|
|
||||||
|
schemaName := "contract_node_id_" + strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||||
|
adminDB, err := sql.Open("pgx", baseDSN)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open postgres admin connection: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_, _ = adminDB.Exec(`DROP SCHEMA IF EXISTS "` + schemaName + `" CASCADE`)
|
||||||
|
_ = adminDB.Close()
|
||||||
|
})
|
||||||
|
|
||||||
|
if _, err := adminDB.Exec(`CREATE SCHEMA "` + schemaName + `"`); err != nil {
|
||||||
|
t.Fatalf("create schema %s: %v", schemaName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testDSN, err := withSearchPath(baseDSN, schemaName)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("build schema dsn: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
repo, err := sqlite.OpenPostgres(testDSN)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open postgres repository: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.DB().Exec(`ALTER TABLE node ALTER COLUMN id DROP DEFAULT`); err != nil {
|
||||||
|
_ = repo.Close()
|
||||||
|
t.Fatalf("drop node.id default to simulate drift: %v", err)
|
||||||
|
}
|
||||||
|
if err := repo.Close(); err != nil {
|
||||||
|
t.Fatalf("close repository before reopen: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
repo, err = sqlite.OpenPostgres(testDSN)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reopen postgres repository: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = repo.Close()
|
||||||
|
})
|
||||||
|
|
||||||
|
var columnDefault sql.NullString
|
||||||
|
if err := repo.DB().QueryRow(`
|
||||||
|
SELECT column_default
|
||||||
|
FROM information_schema.columns
|
||||||
|
WHERE table_schema = current_schema()
|
||||||
|
AND table_name = 'node'
|
||||||
|
AND column_name = 'id'
|
||||||
|
LIMIT 1
|
||||||
|
`).Scan(&columnDefault); err != nil {
|
||||||
|
t.Fatalf("query node.id default: %v", err)
|
||||||
|
}
|
||||||
|
if !columnDefault.Valid || !strings.Contains(strings.ToLower(columnDefault.String), "nextval(") {
|
||||||
|
t.Fatalf("expected node.id default to be nextval(...), got %q", columnDefault.String)
|
||||||
|
}
|
||||||
|
|
||||||
|
jwtSecret := "postgres-contract-secret"
|
||||||
|
router := httpserver.NewRouter(handler.New(repo, jwtSecret), jwtSecret)
|
||||||
|
token, err := auth.GenerateToken(1, "admin_user", 0, jwtSecret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate admin token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
body := strings.NewReader(`{"name":"pg-repair-node","serverIp":"10.77.0.10"}`)
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/node/create", body)
|
||||||
|
req.Header.Set("Authorization", token)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
resp := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(resp, req)
|
||||||
|
assertCode(t, resp, 0)
|
||||||
|
|
||||||
|
var nodeID int64
|
||||||
|
if err := repo.DB().QueryRow(`SELECT id FROM node WHERE name = ? ORDER BY id DESC LIMIT 1`, "pg-repair-node").Scan(&nodeID); err != nil {
|
||||||
|
t.Fatalf("query created node: %v", err)
|
||||||
|
}
|
||||||
|
if nodeID <= 0 {
|
||||||
|
t.Fatalf("expected positive node id, got %d", nodeID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func withSearchPath(dsn, schema string) (string, error) {
|
||||||
|
u, err := url.Parse(dsn)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
q := u.Query()
|
||||||
|
q.Set("search_path", schema)
|
||||||
|
u.RawQuery = q.Encode()
|
||||||
|
return u.String(), nil
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package contract_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"database/sql"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
@@ -144,6 +145,17 @@ func TestTunnelUpdateAssignsChainPortsContract(t *testing.T) {
|
|||||||
if outPort <= 0 {
|
if outPort <= 0 {
|
||||||
t.Fatalf("expected out node port to be assigned, got %d", outPort)
|
t.Fatalf("expected out node port to be assigned, got %d", outPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var entryStrategy sql.NullString
|
||||||
|
if err := repo.DB().QueryRow(`SELECT strategy FROM chain_tunnel WHERE tunnel_id = ? AND chain_type = 1 LIMIT 1`, tunnelID).Scan(&entryStrategy); err != nil {
|
||||||
|
t.Fatalf("query entry strategy: %v", err)
|
||||||
|
}
|
||||||
|
if !entryStrategy.Valid || strings.TrimSpace(entryStrategy.String) == "" {
|
||||||
|
t.Fatalf("expected entry strategy to be non-null and non-empty")
|
||||||
|
}
|
||||||
|
if entryStrategy.String != "round" {
|
||||||
|
t.Fatalf("expected entry strategy round, got %q", entryStrategy.String)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func jsonInt(v int64) string {
|
func jsonInt(v int64) string {
|
||||||
|
|||||||
@@ -0,0 +1,301 @@
|
|||||||
|
package contract_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-backend/internal/auth"
|
||||||
|
"go-backend/internal/http/response"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTunnelCreateWithIPPreferenceContract(t *testing.T) {
|
||||||
|
secret := "contract-jwt-secret"
|
||||||
|
router, repo := setupContractRouter(t, secret)
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
adminToken, err := auth.GenerateToken(1, "admin_user", 0, secret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate admin token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
insertDualStackNode := func(name, v4, v6, portRange string) int64 {
|
||||||
|
res, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, name, name+"-secret", v4, v4, v6, portRange, "", "v1", 1, 1, 1, now, now, 1, "[::]", "[::]", 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert node %s: %v", name, err)
|
||||||
|
}
|
||||||
|
id, err := res.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get node id %s: %v", name, err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
entryID := insertDualStackNode("ip-pref-entry", "10.50.0.1", "2001:db8::1", "50000-50010")
|
||||||
|
exitID := insertDualStackNode("ip-pref-exit", "10.50.0.2", "2001:db8::2", "51000-51010")
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
preference string
|
||||||
|
}{
|
||||||
|
{"v4-preference", "v4"},
|
||||||
|
{"v6-preference", "v6"},
|
||||||
|
{"empty-preference", ""},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
payload := `{"name":"tunnel-` + tc.name + `","type":2,"flow":99999,"status":1,"ipPreference":"` + tc.preference + `","inNodeId":[{"nodeId":` + jsonInt(entryID) + `,"protocol":"tls"}],"chainNodes":[],"outNodeId":[{"nodeId":` + jsonInt(exitID) + `,"protocol":"tls"}]}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/tunnel/create", bytes.NewBufferString(payload))
|
||||||
|
req.Header.Set("Authorization", adminToken)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(res, req)
|
||||||
|
|
||||||
|
var out response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var stored string
|
||||||
|
err := repo.DB().QueryRow(`SELECT COALESCE(ip_preference, '') FROM tunnel WHERE name = ?`, "tunnel-"+tc.name).Scan(&stored)
|
||||||
|
if err != nil {
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
t.Skipf("tunnel not created (nodes offline), skipping DB verification")
|
||||||
|
}
|
||||||
|
t.Fatalf("query ip_preference: %v", err)
|
||||||
|
}
|
||||||
|
if stored != tc.preference {
|
||||||
|
t.Fatalf("expected ip_preference=%q in DB, got %q", tc.preference, stored)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTunnelUpdateIPPreferenceContract(t *testing.T) {
|
||||||
|
secret := "contract-jwt-secret"
|
||||||
|
router, repo := setupContractRouter(t, secret)
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
adminToken, err := auth.GenerateToken(1, "admin_user", 0, secret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate admin token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
insertDualStackNode := func(name, v4, v6, portRange string) int64 {
|
||||||
|
res, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, name, name+"-secret", v4, v4, v6, portRange, "", "v1", 1, 1, 1, now, now, 1, "[::]", "[::]", 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert node %s: %v", name, err)
|
||||||
|
}
|
||||||
|
id, err := res.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get node id %s: %v", name, err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
entryID := insertDualStackNode("upd-entry", "10.60.0.1", "2001:db8:1::1", "60000-60010")
|
||||||
|
exitID := insertDualStackNode("upd-exit", "10.60.0.2", "2001:db8:1::2", "61000-61010")
|
||||||
|
|
||||||
|
tunnelRes, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx, ip_preference)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, "update-ip-pref-tunnel", 1.0, 1, "tls", 99999, now, now, 1, nil, 0, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel: %v", err)
|
||||||
|
}
|
||||||
|
tunnelID, err := tunnelRes.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get tunnel id: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
payload := `{"id":` + jsonInt(tunnelID) + `,"name":"update-ip-pref-tunnel","type":2,"flow":99999,"trafficRatio":1.0,"status":1,"ipPreference":"v6","inNodeId":[{"nodeId":` + jsonInt(entryID) + `,"protocol":"tls"}],"chainNodes":[],"outNodeId":[{"nodeId":` + jsonInt(exitID) + `,"protocol":"tls"}]}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/tunnel/update", bytes.NewBufferString(payload))
|
||||||
|
req.Header.Set("Authorization", adminToken)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(res, req)
|
||||||
|
|
||||||
|
var out response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var stored string
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COALESCE(ip_preference, '') FROM tunnel WHERE id = ?`, tunnelID).Scan(&stored); err != nil {
|
||||||
|
t.Fatalf("query ip_preference: %v", err)
|
||||||
|
}
|
||||||
|
if stored != "v6" {
|
||||||
|
t.Fatalf("expected ip_preference='v6' after update, got %q", stored)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTunnelListReturnsIPPreferenceContract(t *testing.T) {
|
||||||
|
secret := "contract-jwt-secret"
|
||||||
|
router, repo := setupContractRouter(t, secret)
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
adminToken, err := auth.GenerateToken(1, "admin_user", 0, secret)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("generate admin token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = repo.DB().Exec(`
|
||||||
|
INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx, ip_preference)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, "list-ip-pref-tunnel", 1.0, 2, "tls", 99999, now, now, 1, nil, 0, "v6")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/tunnel/list", nil)
|
||||||
|
req.Header.Set("Authorization", adminToken)
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(res, req)
|
||||||
|
|
||||||
|
var out response.R
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if out.Code != 0 {
|
||||||
|
t.Fatalf("expected code 0, got %d (msg=%s)", out.Code, out.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
tunnels, ok := out.Data.([]interface{})
|
||||||
|
if !ok || len(tunnels) == 0 {
|
||||||
|
t.Fatalf("expected non-empty tunnel list, got %v", out.Data)
|
||||||
|
}
|
||||||
|
|
||||||
|
found := false
|
||||||
|
for _, raw := range tunnels {
|
||||||
|
tm, ok := raw.(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if tm["name"] == "list-ip-pref-tunnel" {
|
||||||
|
found = true
|
||||||
|
pref, _ := tm["ipPreference"].(string)
|
||||||
|
if pref != "v6" {
|
||||||
|
t.Fatalf("expected ipPreference='v6' in list response, got %q", pref)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatal("tunnel 'list-ip-pref-tunnel' not found in list response")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIPPreferenceColumnDefaultContract(t *testing.T) {
|
||||||
|
_, repo := setupContractRouter(t, "contract-jwt-secret")
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
_, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, "no-pref-tunnel", 1.0, 2, "tls", 99999, now, now, 1, nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel without ip_preference: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var stored string
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COALESCE(ip_preference, '') FROM tunnel WHERE name = ?`, "no-pref-tunnel").Scan(&stored); err != nil {
|
||||||
|
t.Fatalf("query ip_preference: %v", err)
|
||||||
|
}
|
||||||
|
if stored != "" {
|
||||||
|
t.Fatalf("expected default ip_preference='', got %q", stored)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIPPreferenceColumnMigrationContract(t *testing.T) {
|
||||||
|
_, repo := setupContractRouter(t, "contract-jwt-secret")
|
||||||
|
|
||||||
|
var colCount int
|
||||||
|
err := repo.DB().QueryRow(`SELECT COUNT(*) FROM pragma_table_info('tunnel') WHERE name = 'ip_preference'`).Scan(&colCount)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("check column existence: %v", err)
|
||||||
|
}
|
||||||
|
if colCount != 1 {
|
||||||
|
t.Fatalf("expected ip_preference column to exist in tunnel table, found %d", colCount)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIPPreferenceCoalesceNullSafety(t *testing.T) {
|
||||||
|
_, repo := setupContractRouter(t, "contract-jwt-secret")
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
_, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx, ip_preference)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)
|
||||||
|
`, "null-pref-tunnel", 1.0, 2, "tls", 99999, now, now, 1, nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Skipf("DB does not allow NULL ip_preference (NOT NULL constraint): %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var stored string
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COALESCE(ip_preference, '') FROM tunnel WHERE name = ?`, "null-pref-tunnel").Scan(&stored); err != nil {
|
||||||
|
t.Fatalf("query ip_preference: %v", err)
|
||||||
|
}
|
||||||
|
if stored != "" {
|
||||||
|
t.Fatalf("COALESCE should convert NULL to empty string, got %q", stored)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDualStackNodeIPFieldsStoredContract(t *testing.T) {
|
||||||
|
_, repo := setupContractRouter(t, "contract-jwt-secret")
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
_, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO node(name, secret, server_ip, server_ip_v4, server_ip_v6, port, interface_name, version, http, tls, socks, created_time, updated_time, status, tcp_listen_addr, udp_listen_addr, inx)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, "ds-verify-node", "ds-secret", "10.70.0.1", "10.70.0.1", "2001:db8:2::1", "70000-70010", "", "v1", 1, 1, 1, now, now, 1, "[::]", "[::]", 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert dual-stack node: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var v4, v6 sql.NullString
|
||||||
|
if err := repo.DB().QueryRow(`SELECT server_ip_v4, server_ip_v6 FROM node WHERE name = ?`, "ds-verify-node").Scan(&v4, &v6); err != nil {
|
||||||
|
t.Fatalf("query node IPs: %v", err)
|
||||||
|
}
|
||||||
|
if !v4.Valid || v4.String != "10.70.0.1" {
|
||||||
|
t.Fatalf("expected server_ip_v4='10.70.0.1', got %v", v4)
|
||||||
|
}
|
||||||
|
if !v6.Valid || v6.String != "2001:db8:2::1" {
|
||||||
|
t.Fatalf("expected server_ip_v6='2001:db8:2::1', got %v", v6)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIPPreferenceValidValuesContract(t *testing.T) {
|
||||||
|
_, repo := setupContractRouter(t, "contract-jwt-secret")
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
|
||||||
|
for _, pref := range []string{"", "v4", "v6"} {
|
||||||
|
name := "valid-pref-" + pref
|
||||||
|
if pref == "" {
|
||||||
|
name = "valid-pref-empty"
|
||||||
|
}
|
||||||
|
_, err := repo.DB().Exec(`
|
||||||
|
INSERT INTO tunnel(name, traffic_ratio, type, protocol, flow, created_time, updated_time, status, in_ip, inx, ip_preference)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, name, 1.0, 2, "tls", 99999, now, now, 1, nil, 0, pref)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("insert tunnel with ip_preference=%q: %v", pref, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var stored string
|
||||||
|
if err := repo.DB().QueryRow(`SELECT COALESCE(ip_preference, '') FROM tunnel WHERE name = ?`, name).Scan(&stored); err != nil {
|
||||||
|
t.Fatalf("query ip_preference for %s: %v", name, err)
|
||||||
|
}
|
||||||
|
if stored != pref {
|
||||||
|
t.Fatalf("expected ip_preference=%q, got %q for %s", pref, stored, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-1
@@ -1,6 +1,6 @@
|
|||||||
# GO-GOST SERVICE KNOWLEDGE BASE
|
# GO-GOST SERVICE KNOWLEDGE BASE
|
||||||
|
|
||||||
**Generated:** Mon Feb 02 2026
|
**Generated:** Sun Feb 15 2026
|
||||||
|
|
||||||
## OVERVIEW
|
## OVERVIEW
|
||||||
Forwarding agent built on GOST v3 with a local fork of `github.com/go-gost/x` under `x/`.
|
Forwarding agent built on GOST v3 with a local fork of `github.com/go-gost/x` under `x/`.
|
||||||
@@ -27,6 +27,11 @@ go-gost/
|
|||||||
## CONVENTIONS
|
## CONVENTIONS
|
||||||
- Two configs exist: panel integration uses `config.json`; forwarding services use GOST config (defaults to `gost.{json,yaml}` via viper search paths).
|
- Two configs exist: panel integration uses `config.json`; forwarding services use GOST config (defaults to `gost.{json,yaml}` via viper search paths).
|
||||||
- `go-gost/x/` is the primary extension surface; avoid editing vendored deps.
|
- `go-gost/x/` is the primary extension surface; avoid editing vendored deps.
|
||||||
|
- Agent communicates with panel via WebSocket (real-time commands) + HTTP (batch traffic reports).
|
||||||
|
- All panel communication uses AES encryption with node `secret` as PSK.
|
||||||
|
|
||||||
|
## ANTI-PATTERNS
|
||||||
|
- **DO NOT EDIT** generated protobuf in `x/internal/util/grpc/proto/`.
|
||||||
|
|
||||||
## COMMANDS
|
## COMMANDS
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
+3
-1
@@ -1,7 +1,7 @@
|
|||||||
# GO-GOST/X KNOWLEDGE BASE
|
# GO-GOST/X KNOWLEDGE BASE
|
||||||
|
|
||||||
## OVERVIEW
|
## OVERVIEW
|
||||||
Local fork of `github.com/go-gost/x` used by `go-gost/` via `replace github.com/go-gost/x => ./x`. Most protocol/runtime behavior changes happen here.
|
Local fork of `github.com/go-gost/x` used by `go-gost/` via `replace github.com/go-gost/x => ./x`. Most protocol/runtime behavior changes happen here. 30+ top-level packages - framework-style layout.
|
||||||
|
|
||||||
## STRUCTURE
|
## STRUCTURE
|
||||||
```
|
```
|
||||||
@@ -31,6 +31,8 @@ go-gost/x/
|
|||||||
## CONVENTIONS
|
## CONVENTIONS
|
||||||
- `go-gost/x/` is a standalone Go module (`go-gost/x/go.mod`); run go tooling from this dir when debugging module resolution.
|
- `go-gost/x/` is a standalone Go module (`go-gost/x/go.mod`); run go tooling from this dir when debugging module resolution.
|
||||||
- Generated gRPC/proto code lives under `go-gost/x/internal/util/grpc/proto/`.
|
- Generated gRPC/proto code lives under `go-gost/x/internal/util/grpc/proto/`.
|
||||||
|
- Handlers/listeners/dialers follow consistent pattern: `{type}.go` + `metadata.go` per protocol.
|
||||||
|
- OS-specific code uses `name_[os].go` suffix (e.g., `tun_linux.go`, `tun_darwin.go`).
|
||||||
|
|
||||||
## ANTI-PATTERNS
|
## ANTI-PATTERNS
|
||||||
- Do not edit generated files in `go-gost/x/internal/util/grpc/proto/` (`*.pb.go`, `*_grpc.pb.go`).
|
- Do not edit generated files in `go-gost/x/internal/util/grpc/proto/` (`*.pb.go`, `*_grpc.pb.go`).
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# GOST CONNECTOR KNOWLEDGE BASE
|
||||||
|
|
||||||
|
**Generated:** Fri Feb 13 2026
|
||||||
|
|
||||||
|
## OVERVIEW
|
||||||
|
Connection initiators (clients) for various protocols in GOST forwarding.
|
||||||
|
**Stack:** Go, GOST core.
|
||||||
|
|
||||||
|
## STRUCTURE
|
||||||
|
```
|
||||||
|
connector/
|
||||||
|
├── direct/ # Direct connection
|
||||||
|
├── forward/ # Forward proxy
|
||||||
|
├── http/ # HTTP connector
|
||||||
|
├── http2/ # HTTP/2 connector
|
||||||
|
├── relay/ # Relay protocol
|
||||||
|
├── router/ # Router connector
|
||||||
|
├── serial/ # Serial port
|
||||||
|
├── sni/ # SNI routing
|
||||||
|
├── socks/ # SOCKS4/5
|
||||||
|
├── ss/ # Shadowsocks
|
||||||
|
├── sshd/ # SSH daemon
|
||||||
|
├── tcp/ # TCP connector
|
||||||
|
├── tunnel/ # Tunnel mode
|
||||||
|
└── unix/ # Unix socket
|
||||||
|
```
|
||||||
|
|
||||||
|
## CONVENTIONS
|
||||||
|
- Inherits from parent `go-gost/x/` conventions.
|
||||||
|
- Each subdir implements `Connector` interface from GOST core.
|
||||||
|
|
||||||
|
## ANTI-PATTERNS
|
||||||
|
- DO NOT EDIT generated protobuf in `go-gost/x/internal/util/grpc/proto/`.
|
||||||
|
|
||||||
|
## COMMANDS
|
||||||
|
```bash
|
||||||
|
cd go-gost
|
||||||
|
go test ./x/connector/...
|
||||||
|
```
|
||||||
@@ -54,10 +54,10 @@ var needWrap = false
|
|||||||
|
|
||||||
// SetProtocolBlock sets protocol blocking switches and recomputes wrapper need
|
// SetProtocolBlock sets protocol blocking switches and recomputes wrapper need
|
||||||
func SetProtocolBlock(httpOn int, tlsOn int, socksOn int) {
|
func SetProtocolBlock(httpOn int, tlsOn int, socksOn int) {
|
||||||
isHttp = httpOn
|
isHttp = httpOn
|
||||||
isTls = tlsOn
|
isTls = tlsOn
|
||||||
isSocks = socksOn
|
isSocks = socksOn
|
||||||
needWrap = isTls+isSocks+isHttp > 0
|
needWrap = isTls+isSocks+isHttp > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
type Option func(opts *options)
|
type Option func(opts *options)
|
||||||
@@ -292,7 +292,9 @@ func (s *defaultService) Serve() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err := s.handler.Handle(ctx, conn); err != nil {
|
if err := s.handler.Handle(ctx, conn); err != nil {
|
||||||
log.Error(err)
|
if !errors.Is(err, net.ErrClosed) {
|
||||||
|
log.Error(err)
|
||||||
|
}
|
||||||
if v := xmetrics.GetCounter(xmetrics.MetricServiceHandlerErrorsCounter,
|
if v := xmetrics.GetCounter(xmetrics.MetricServiceHandlerErrorsCounter,
|
||||||
metrics.Labels{"service": s.name, "client": clientIP}); v != nil {
|
metrics.Labels{"service": s.name, "client": clientIP}); v != nil {
|
||||||
v.Inc()
|
v.Inc()
|
||||||
@@ -403,12 +405,12 @@ func (s *defaultService) observeStats(ctx context.Context) {
|
|||||||
TotalErrs: st.Get(stats.KindTotalErrs),
|
TotalErrs: st.Get(stats.KindTotalErrs),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// 将流量累积到全局管理器,而不是立即上报
|
// 将流量累积到全局管理器,而不是立即上报
|
||||||
if outputBytes > 0 || inputBytes > 0 {
|
if outputBytes > 0 || inputBytes > 0 {
|
||||||
globalManager := GetGlobalTrafficManager()
|
globalManager := GetGlobalTrafficManager()
|
||||||
globalManager.AddTraffic(s.name, int64(outputBytes), int64(inputBytes))
|
globalManager.AddTraffic(s.name, int64(outputBytes), int64(inputBytes))
|
||||||
|
|
||||||
// 立即重置流量计数(因为已经记录到全局管理器中)
|
// 立即重置流量计数(因为已经记录到全局管理器中)
|
||||||
if xstats, ok := st.(*xstats.Stats); ok {
|
if xstats, ok := st.(*xstats.Stats); ok {
|
||||||
xstats.ResetTraffic(st.Get(stats.KindInputBytes)-inputBytes, st.Get(stats.KindOutputBytes)-outputBytes)
|
xstats.ResetTraffic(st.Get(stats.KindInputBytes)-inputBytes, st.Get(stats.KindOutputBytes)-outputBytes)
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# GOST SOCKET KNOWLEDGE BASE
|
||||||
|
|
||||||
|
**Generated:** Sun Feb 15 2026
|
||||||
|
|
||||||
|
## OVERVIEW
|
||||||
|
WebSocket reporter and socket utilities for panel integration.
|
||||||
|
**Stack:** Go, GOST core, gorilla/websocket.
|
||||||
|
|
||||||
|
## STRUCTURE
|
||||||
|
```
|
||||||
|
socket/
|
||||||
|
├── websocket_reporter.go # Agent-to-panel telemetry (1504 LOC)
|
||||||
|
├── service.go # Socket service orchestration (534 LOC)
|
||||||
|
├── socket.go # Core socket interface
|
||||||
|
├── udp.go # UDP socket handling
|
||||||
|
├── packet.go # Packet framing
|
||||||
|
└── packetconn.go # Packet connection wrapper
|
||||||
|
```
|
||||||
|
|
||||||
|
## WHERE TO LOOK
|
||||||
|
| Task | Location | Notes |
|
||||||
|
|------|----------|-------|
|
||||||
|
| **Panel Reporting** | `websocket_reporter.go` | Real-time system info (CPU, mem, uptime) every 2s |
|
||||||
|
| **Command Handling** | `websocket_reporter.go` | Processes `AddService`, `UpgradeAgent`, etc. |
|
||||||
|
|
||||||
|
## CONVENTIONS
|
||||||
|
- Inherits from parent `go-gost/x/` conventions.
|
||||||
|
- Low-level network primitives.
|
||||||
|
- All panel communication is AES-encrypted using node `secret`.
|
||||||
|
|
||||||
|
## ANTI-PATTERNS
|
||||||
|
- DO NOT EDIT generated protobuf.
|
||||||
|
|
||||||
|
## COMMANDS
|
||||||
|
```bash
|
||||||
|
cd go-gost
|
||||||
|
go test ./x/socket/...
|
||||||
|
```
|
||||||
+236
-34
@@ -203,7 +203,8 @@ show_menu() {
|
|||||||
echo "1. 安装面板"
|
echo "1. 安装面板"
|
||||||
echo "2. 更新面板"
|
echo "2. 更新面板"
|
||||||
echo "3. 卸载面板"
|
echo "3. 卸载面板"
|
||||||
echo "4. 退出"
|
echo "4. 迁移到 PostgreSQL"
|
||||||
|
echo "5. 退出"
|
||||||
echo "==============================================="
|
echo "==============================================="
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,6 +233,92 @@ upsert_env_var() {
|
|||||||
mv "$tmp_file" "$file"
|
mv "$tmp_file" "$file"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get_env_var() {
|
||||||
|
local key="$1"
|
||||||
|
local file="${2:-.env}"
|
||||||
|
|
||||||
|
if [[ ! -f "$file" ]]; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
grep -m1 "^${key}=" "$file" | cut -d= -f2-
|
||||||
|
}
|
||||||
|
|
||||||
|
get_current_db_type() {
|
||||||
|
local db_type database_url
|
||||||
|
|
||||||
|
db_type=$(get_env_var "DB_TYPE")
|
||||||
|
database_url=$(get_env_var "DATABASE_URL")
|
||||||
|
|
||||||
|
if [[ "$db_type" == "sqlite" ]]; then
|
||||||
|
echo "sqlite"
|
||||||
|
elif [[ "$db_type" == "postgres" || "$database_url" == postgres://* || "$database_url" == postgresql://* ]]; then
|
||||||
|
echo "postgres"
|
||||||
|
else
|
||||||
|
echo "sqlite"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_for_postgres_healthy() {
|
||||||
|
local pg_health
|
||||||
|
|
||||||
|
echo "🔍 检查 PostgreSQL 服务状态..."
|
||||||
|
for i in {1..90}; do
|
||||||
|
if docker ps --format "{{.Names}}" | grep -q "^flux-panel-postgres$"; then
|
||||||
|
pg_health=$(docker inspect -f '{{.State.Health.Status}}' flux-panel-postgres 2>/dev/null || echo "unknown")
|
||||||
|
if [[ "$pg_health" == "healthy" ]]; then
|
||||||
|
echo "✅ PostgreSQL 服务健康检查通过"
|
||||||
|
return 0
|
||||||
|
elif [[ "$pg_health" == "unhealthy" ]]; then
|
||||||
|
echo "⚠️ PostgreSQL 健康状态:$pg_health"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
pg_health="not_running"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ $i -eq 90 ]; then
|
||||||
|
echo "❌ PostgreSQL 启动超时(90秒)"
|
||||||
|
echo "🔍 当前状态:$(docker inspect -f '{{.State.Health.Status}}' flux-panel-postgres 2>/dev/null || echo '容器不存在')"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ $((i % 15)) -eq 1 ]; then
|
||||||
|
echo "⏳ 等待 PostgreSQL 启动... ($i/90) 状态:${pg_health:-unknown}"
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_for_backend_healthy() {
|
||||||
|
local backend_health
|
||||||
|
|
||||||
|
echo "🔍 检查后端服务状态..."
|
||||||
|
for i in {1..90}; do
|
||||||
|
if docker ps --format "{{.Names}}" | grep -q "^flux-panel-backend$"; then
|
||||||
|
backend_health=$(docker inspect -f '{{.State.Health.Status}}' flux-panel-backend 2>/dev/null || echo "unknown")
|
||||||
|
if [[ "$backend_health" == "healthy" ]]; then
|
||||||
|
echo "✅ 后端服务健康检查通过"
|
||||||
|
return 0
|
||||||
|
elif [[ "$backend_health" == "unhealthy" ]]; then
|
||||||
|
echo "⚠️ 后端健康状态:$backend_health"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
backend_health="not_running"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ $i -eq 90 ]; then
|
||||||
|
echo "❌ 后端服务启动超时(90秒)"
|
||||||
|
echo "🔍 当前状态:$(docker inspect -f '{{.State.Health.Status}}' flux-panel-backend 2>/dev/null || echo '容器不存在')"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ $((i % 15)) -eq 1 ]; then
|
||||||
|
echo "⏳ 等待后端服务启动... ($i/90) 状态:${backend_health:-unknown}"
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
# 删除脚本自身
|
# 删除脚本自身
|
||||||
delete_self() {
|
delete_self() {
|
||||||
echo ""
|
echo ""
|
||||||
@@ -253,6 +340,33 @@ get_config_params() {
|
|||||||
read -p "后端端口(默认 6365): " BACKEND_PORT
|
read -p "后端端口(默认 6365): " BACKEND_PORT
|
||||||
BACKEND_PORT=${BACKEND_PORT:-6365}
|
BACKEND_PORT=${BACKEND_PORT:-6365}
|
||||||
|
|
||||||
|
echo "请选择数据库类型:"
|
||||||
|
echo "1. SQLite(默认)"
|
||||||
|
echo "2. PostgreSQL"
|
||||||
|
read -p "数据库类型(1/2,默认 1): " DB_CHOICE
|
||||||
|
case "$DB_CHOICE" in
|
||||||
|
2)
|
||||||
|
DB_TYPE="postgres"
|
||||||
|
;;
|
||||||
|
""|1)
|
||||||
|
DB_TYPE="sqlite"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "⚠️ 输入无效,默认使用 SQLite"
|
||||||
|
DB_TYPE="sqlite"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
POSTGRES_DB="flux_panel"
|
||||||
|
POSTGRES_USER="flux_panel"
|
||||||
|
POSTGRES_PASSWORD=$(generate_random)
|
||||||
|
|
||||||
|
if [[ "$DB_TYPE" == "postgres" ]]; then
|
||||||
|
DATABASE_URL="postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}?sslmode=disable"
|
||||||
|
else
|
||||||
|
DATABASE_URL=""
|
||||||
|
fi
|
||||||
|
|
||||||
# 生成JWT密钥
|
# 生成JWT密钥
|
||||||
JWT_SECRET=$(generate_random)
|
JWT_SECRET=$(generate_random)
|
||||||
}
|
}
|
||||||
@@ -280,10 +394,23 @@ JWT_SECRET=$JWT_SECRET
|
|||||||
FRONTEND_PORT=$FRONTEND_PORT
|
FRONTEND_PORT=$FRONTEND_PORT
|
||||||
BACKEND_PORT=$BACKEND_PORT
|
BACKEND_PORT=$BACKEND_PORT
|
||||||
FLUX_VERSION=$RESOLVED_VERSION
|
FLUX_VERSION=$RESOLVED_VERSION
|
||||||
|
|
||||||
|
DB_TYPE=$DB_TYPE
|
||||||
|
DATABASE_URL=$DATABASE_URL
|
||||||
|
|
||||||
|
POSTGRES_DB=$POSTGRES_DB
|
||||||
|
POSTGRES_USER=$POSTGRES_USER
|
||||||
|
POSTGRES_PASSWORD=$POSTGRES_PASSWORD
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
echo "🚀 启动 docker 服务..."
|
echo "🚀 启动 docker 服务..."
|
||||||
$DOCKER_CMD up -d
|
if [[ "$DB_TYPE" == "postgres" ]]; then
|
||||||
|
$DOCKER_CMD up -d postgres
|
||||||
|
wait_for_postgres_healthy
|
||||||
|
$DOCKER_CMD up -d backend frontend
|
||||||
|
else
|
||||||
|
$DOCKER_CMD up -d backend frontend
|
||||||
|
fi
|
||||||
|
|
||||||
echo "🎉 部署完成"
|
echo "🎉 部署完成"
|
||||||
echo "🌐 访问地址: http://服务器IP:$FRONTEND_PORT"
|
echo "🌐 访问地址: http://服务器IP:$FRONTEND_PORT"
|
||||||
@@ -300,6 +427,12 @@ update_panel() {
|
|||||||
echo "🔄 开始更新面板..."
|
echo "🔄 开始更新面板..."
|
||||||
check_docker
|
check_docker
|
||||||
|
|
||||||
|
if [[ ! -f ".env" ]]; then
|
||||||
|
echo "⚠️ 未找到 .env,默认按 SQLite 模式更新"
|
||||||
|
fi
|
||||||
|
CURRENT_DB_TYPE=$(get_current_db_type)
|
||||||
|
echo "🗄️ 当前数据库类型:$CURRENT_DB_TYPE"
|
||||||
|
|
||||||
echo "🔍 获取最新版本号..."
|
echo "🔍 获取最新版本号..."
|
||||||
LATEST_VERSION=$(resolve_latest_release_tag) || {
|
LATEST_VERSION=$(resolve_latest_release_tag) || {
|
||||||
echo "❌ 无法获取最新版本号,更新终止"
|
echo "❌ 无法获取最新版本号,更新终止"
|
||||||
@@ -333,49 +466,113 @@ update_panel() {
|
|||||||
$DOCKER_CMD down
|
$DOCKER_CMD down
|
||||||
|
|
||||||
echo "⬇️ 拉取最新镜像..."
|
echo "⬇️ 拉取最新镜像..."
|
||||||
$DOCKER_CMD pull
|
if [[ "$CURRENT_DB_TYPE" == "postgres" ]]; then
|
||||||
|
$DOCKER_CMD pull backend frontend postgres
|
||||||
|
else
|
||||||
|
$DOCKER_CMD pull backend frontend
|
||||||
|
fi
|
||||||
|
|
||||||
echo "🚀 启动更新后的服务..."
|
echo "🚀 启动更新后的服务..."
|
||||||
$DOCKER_CMD up -d
|
if [[ "$CURRENT_DB_TYPE" == "postgres" ]]; then
|
||||||
|
$DOCKER_CMD up -d postgres
|
||||||
|
wait_for_postgres_healthy
|
||||||
|
$DOCKER_CMD up -d backend frontend
|
||||||
|
else
|
||||||
|
$DOCKER_CMD up -d backend frontend
|
||||||
|
fi
|
||||||
|
|
||||||
# 等待服务启动
|
# 等待服务启动
|
||||||
echo "⏳ 等待服务启动..."
|
echo "⏳ 等待服务启动..."
|
||||||
|
|
||||||
# 检查后端容器健康状态
|
if ! wait_for_backend_healthy; then
|
||||||
echo "🔍 检查后端服务状态..."
|
echo "🛑 更新终止"
|
||||||
for i in {1..90}; do
|
return 1
|
||||||
if docker ps --format "{{.Names}}" | grep -q "^flux-panel-backend$"; then
|
fi
|
||||||
BACKEND_HEALTH=$(docker inspect -f '{{.State.Health.Status}}' flux-panel-backend 2>/dev/null || echo "unknown")
|
|
||||||
if [[ "$BACKEND_HEALTH" == "healthy" ]]; then
|
|
||||||
echo "✅ 后端服务健康检查通过"
|
|
||||||
break
|
|
||||||
elif [[ "$BACKEND_HEALTH" == "starting" ]]; then
|
|
||||||
# 继续等待
|
|
||||||
:
|
|
||||||
elif [[ "$BACKEND_HEALTH" == "unhealthy" ]]; then
|
|
||||||
echo "⚠️ 后端健康状态:$BACKEND_HEALTH"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
echo "⚠️ 后端容器未找到或未运行"
|
|
||||||
BACKEND_HEALTH="not_running"
|
|
||||||
fi
|
|
||||||
if [ $i -eq 90 ]; then
|
|
||||||
echo "❌ 后端服务启动超时(90秒)"
|
|
||||||
echo "🔍 当前状态:$(docker inspect -f '{{.State.Health.Status}}' flux-panel-backend 2>/dev/null || echo '容器不存在')"
|
|
||||||
echo "🛑 更新终止"
|
|
||||||
return 1
|
|
||||||
fi
|
|
||||||
# 每15秒显示一次进度
|
|
||||||
if [ $((i % 15)) -eq 1 ]; then
|
|
||||||
echo "⏳ 等待后端服务启动... ($i/90) 状态:${BACKEND_HEALTH:-unknown}"
|
|
||||||
fi
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
|
|
||||||
echo "✅ 更新完成"
|
echo "✅ 更新完成"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
migrate_to_postgres() {
|
||||||
|
local current_db_type postgres_db postgres_user postgres_password database_url
|
||||||
|
|
||||||
|
echo "🔄 开始迁移 SQLite -> PostgreSQL..."
|
||||||
|
check_docker
|
||||||
|
|
||||||
|
if [[ ! -f ".env" ]]; then
|
||||||
|
echo "❌ 未找到 .env 文件,请先安装面板"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ ! -f "docker-compose.yml" ]]; then
|
||||||
|
echo "⚠️ 未找到 docker-compose.yml 文件,正在下载..."
|
||||||
|
DOCKER_COMPOSE_URL=$(get_docker_compose_url)
|
||||||
|
echo "📡 选择配置文件:$(basename "$DOCKER_COMPOSE_URL")"
|
||||||
|
curl -L -o docker-compose.yml "$DOCKER_COMPOSE_URL"
|
||||||
|
echo "✅ docker-compose.yml 下载完成"
|
||||||
|
fi
|
||||||
|
|
||||||
|
current_db_type=$(get_current_db_type)
|
||||||
|
if [[ "$current_db_type" == "postgres" ]]; then
|
||||||
|
echo "ℹ️ 当前已使用 PostgreSQL,无需迁移"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
postgres_db=$(get_env_var "POSTGRES_DB")
|
||||||
|
postgres_user=$(get_env_var "POSTGRES_USER")
|
||||||
|
postgres_password=$(get_env_var "POSTGRES_PASSWORD")
|
||||||
|
|
||||||
|
postgres_db=${postgres_db:-flux_panel}
|
||||||
|
postgres_user=${postgres_user:-flux_panel}
|
||||||
|
postgres_password=${postgres_password:-$(generate_random)}
|
||||||
|
|
||||||
|
upsert_env_var ".env" "POSTGRES_DB" "$postgres_db"
|
||||||
|
upsert_env_var ".env" "POSTGRES_USER" "$postgres_user"
|
||||||
|
upsert_env_var ".env" "POSTGRES_PASSWORD" "$postgres_password"
|
||||||
|
|
||||||
|
echo "🛑 停止当前服务..."
|
||||||
|
docker stop -t 30 flux-panel-backend 2>/dev/null || true
|
||||||
|
docker stop -t 10 vite-frontend 2>/dev/null || true
|
||||||
|
echo "⏳ 等待数据同步..."
|
||||||
|
sleep 5
|
||||||
|
$DOCKER_CMD down
|
||||||
|
|
||||||
|
echo "💾 备份 SQLite 数据到当前目录..."
|
||||||
|
if ! docker run --rm -v sqlite_data:/data -v "$(pwd)":/backup alpine sh -c "cp /data/gost.db /backup/gost.db.bak"; then
|
||||||
|
echo "❌ SQLite 备份失败,迁移终止"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "🚀 启动 PostgreSQL..."
|
||||||
|
$DOCKER_CMD up -d postgres
|
||||||
|
if ! wait_for_postgres_healthy; then
|
||||||
|
echo "🛑 PostgreSQL 未就绪,迁移终止"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "🔄 执行 pgloader 迁移..."
|
||||||
|
if ! docker run --rm --network gost-network -v sqlite_data:/sqlite dimitri/pgloader:latest pgloader /sqlite/gost.db "postgresql://${postgres_user}:${postgres_password}@postgres:5432/${postgres_db}"; then
|
||||||
|
echo "❌ pgloader 迁移失败,迁移终止(如报 28P01,可执行 docker volume rm postgres_data 后重试)"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
database_url="postgresql://${postgres_user}:${postgres_password}@postgres:5432/${postgres_db}?sslmode=disable"
|
||||||
|
upsert_env_var ".env" "DB_TYPE" "postgres"
|
||||||
|
upsert_env_var ".env" "DATABASE_URL" "$database_url"
|
||||||
|
|
||||||
|
echo "🚀 启动迁移后的服务..."
|
||||||
|
$DOCKER_CMD up -d postgres backend frontend
|
||||||
|
|
||||||
|
echo "⏳ 等待服务启动..."
|
||||||
|
if ! wait_for_backend_healthy; then
|
||||||
|
echo "🛑 迁移后服务启动失败"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "✅ SQLite -> PostgreSQL 迁移完成"
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# 卸载功能
|
# 卸载功能
|
||||||
uninstall_panel() {
|
uninstall_panel() {
|
||||||
@@ -428,6 +625,11 @@ main() {
|
|||||||
exit 0
|
exit 0
|
||||||
;;
|
;;
|
||||||
4)
|
4)
|
||||||
|
migrate_to_postgres
|
||||||
|
delete_self
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
5)
|
||||||
echo "👋 退出脚本"
|
echo "👋 退出脚本"
|
||||||
delete_self
|
delete_self
|
||||||
exit 0
|
exit 0
|
||||||
|
|||||||
+14
-4
@@ -1,10 +1,10 @@
|
|||||||
# VITE FRONTEND KNOWLEDGE BASE
|
# VITE FRONTEND KNOWLEDGE BASE
|
||||||
|
|
||||||
**Generated:** Mon Feb 02 2026
|
**Generated:** Sun Feb 15 2026
|
||||||
|
|
||||||
## OVERVIEW
|
## OVERVIEW
|
||||||
Web management console for FLVX (formerly Flux Panel).
|
Web management console for FLVX.
|
||||||
**Stack:** React 18, Vite 5, TypeScript, TailwindCSS 4, HeroUI.
|
**Stack:** React 18, Vite 5 (rolldown-vite), TypeScript, TailwindCSS 4, HeroUI.
|
||||||
|
|
||||||
## STRUCTURE
|
## STRUCTURE
|
||||||
```
|
```
|
||||||
@@ -37,9 +37,19 @@ vite-frontend/
|
|||||||
|
|
||||||
## CONVENTIONS
|
## CONVENTIONS
|
||||||
- **Auth**: JWT stored as `localStorage.token`. Sent in `Authorization` header (no "Bearer" prefix).
|
- **Auth**: JWT stored as `localStorage.token`. Sent in `Authorization` header (no "Bearer" prefix).
|
||||||
- **API**: Default base URL is `/api/v1/`.
|
- **API**: Default base URL is `/api/v1/`. Responses follow `{code, msg, data, ts}` structure.
|
||||||
- **WebView**: In WebView mode, base URL is derived from selected panel address. If unset, API returns `code: -1`.
|
- **WebView**: In WebView mode, base URL is derived from selected panel address. If unset, API returns `code: -1`.
|
||||||
- **Routing**: URL query param `h5=true` forces mobile layout.
|
- **Routing**: URL query param `h5=true` forces mobile layout.
|
||||||
|
- **Build**: `minify: false`, `treeshake: false` - unoptimized production bundles for debugging.
|
||||||
|
- **ESLint**: `react-hooks/exhaustive-deps` disabled, unused vars starting with `_` ignored.
|
||||||
|
- **Large Pages**: `forward.tsx` (3263 LOC), `tunnel.tsx` (2552 LOC), `node.tsx` (2194 LOC).
|
||||||
|
|
||||||
|
## ANTI-PATTERNS
|
||||||
|
- **DO NOT ADD** tests - no test infrastructure (Vitest/Jest not configured).
|
||||||
|
|
||||||
|
## NOTES
|
||||||
|
- Uses `rolldown-vite` (experimental Rust bundler) instead of standard Vite.
|
||||||
|
- ESLint Flat Config format with custom import ordering rules.
|
||||||
|
|
||||||
## COMMANDS
|
## COMMANDS
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -40,7 +40,7 @@
|
|||||||
"@heroui/system": "2.4.19",
|
"@heroui/system": "2.4.19",
|
||||||
"@heroui/table": "^2.2.24",
|
"@heroui/table": "^2.2.24",
|
||||||
"@heroui/tabs": "^2.2.27",
|
"@heroui/tabs": "^2.2.27",
|
||||||
"@heroui/theme": "2.4.19",
|
"@heroui/theme": "2.4.24",
|
||||||
"@heroui/use-theme": "2.1.10",
|
"@heroui/use-theme": "2.1.10",
|
||||||
"@marsidev/react-turnstile": "^1.1.0",
|
"@marsidev/react-turnstile": "^1.1.0",
|
||||||
"@nextui-org/system": "^2.4.6",
|
"@nextui-org/system": "^2.4.6",
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import axios from "axios";
|
||||||
|
|
||||||
import Network from "./network";
|
import Network from "./network";
|
||||||
|
|
||||||
// 登陆相关接口
|
// 登陆相关接口
|
||||||
@@ -42,9 +44,17 @@ export const checkNodeStatus = (nodeId?: number) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const upgradeNode = (id: number, version?: string) =>
|
export const upgradeNode = (id: number, version?: string) =>
|
||||||
Network.post("/node/upgrade", { id, version: version || "" }, { timeout: 5 * 60 * 1000 });
|
Network.post(
|
||||||
|
"/node/upgrade",
|
||||||
|
{ id, version: version || "" },
|
||||||
|
{ timeout: 5 * 60 * 1000 },
|
||||||
|
);
|
||||||
export const batchUpgradeNodes = (ids: number[], version?: string) =>
|
export const batchUpgradeNodes = (ids: number[], version?: string) =>
|
||||||
Network.post("/node/batch-upgrade", { ids, version: version || "" }, { timeout: 15 * 60 * 1000 });
|
Network.post(
|
||||||
|
"/node/batch-upgrade",
|
||||||
|
{ ids, version: version || "" },
|
||||||
|
{ timeout: 15 * 60 * 1000 },
|
||||||
|
);
|
||||||
export const getNodeReleases = () => Network.post("/node/releases");
|
export const getNodeReleases = () => Network.post("/node/releases");
|
||||||
export const rollbackNode = (id: number) =>
|
export const rollbackNode = (id: number) =>
|
||||||
Network.post("/node/rollback", { id });
|
Network.post("/node/rollback", { id });
|
||||||
@@ -130,6 +140,10 @@ export const updateConfigs = (configMap: Record<string, string>) =>
|
|||||||
export const updateConfig = (name: string, value: string) =>
|
export const updateConfig = (name: string, value: string) =>
|
||||||
Network.post("/config/update-single", { name, value });
|
Network.post("/config/update-single", { name, value });
|
||||||
|
|
||||||
|
export const exportBackupData = () => Network.post("/backup/export");
|
||||||
|
export const importBackupData = (data: any) => Network.post("/backup/import", data);
|
||||||
|
export const restoreBackupData = (data: any) => Network.post("/backup/restore", data);
|
||||||
|
|
||||||
// 验证码相关接口
|
// 验证码相关接口
|
||||||
export const checkCaptcha = () => Network.post("/captcha/check");
|
export const checkCaptcha = () => Network.post("/captcha/check");
|
||||||
export const generateCaptcha = () => Network.post(`/captcha/generate`);
|
export const generateCaptcha = () => Network.post(`/captcha/generate`);
|
||||||
@@ -224,7 +238,58 @@ export const resetPeerShareFlow = (id: number) =>
|
|||||||
Network.post("/federation/share/reset-flow", { id });
|
Network.post("/federation/share/reset-flow", { id });
|
||||||
export const getPeerRemoteUsageList = () =>
|
export const getPeerRemoteUsageList = () =>
|
||||||
Network.post("/federation/share/remote-usage/list");
|
Network.post("/federation/share/remote-usage/list");
|
||||||
export const importRemoteNode = (data: {
|
export const importRemoteNode = (data: { remoteUrl: string; token: string }) =>
|
||||||
remoteUrl: string;
|
Network.post("/federation/node/import", data);
|
||||||
token: string;
|
|
||||||
}) => Network.post("/federation/node/import", data);
|
export interface BackupTypes {
|
||||||
|
users?: boolean;
|
||||||
|
nodes?: boolean;
|
||||||
|
tunnels?: boolean;
|
||||||
|
forwards?: boolean;
|
||||||
|
userTunnels?: boolean;
|
||||||
|
speedLimits?: boolean;
|
||||||
|
tunnelGroups?: boolean;
|
||||||
|
userGroups?: boolean;
|
||||||
|
permissions?: boolean;
|
||||||
|
configs?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const exportBackup = async (types: string[] = []) => {
|
||||||
|
const token = window.localStorage.getItem("token");
|
||||||
|
const baseURL = axios.defaults.baseURL || "/api/v1/";
|
||||||
|
|
||||||
|
const response = await axios.post(
|
||||||
|
`${baseURL}/backup/export`,
|
||||||
|
{ types },
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: token,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
responseType: "blob",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||||
|
const link = document.createElement("a");
|
||||||
|
|
||||||
|
link.href = url;
|
||||||
|
const timestamp = new Date().toISOString().slice(0, 19).replace(/[:-]/g, "");
|
||||||
|
|
||||||
|
link.setAttribute("download", `backup_${timestamp}.json`);
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
document.body.removeChild(link);
|
||||||
|
window.URL.revokeObjectURL(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const importBackup = (data: { types: string[]; [key: string]: any }) =>
|
||||||
|
Network.post("/backup/import", data);
|
||||||
|
|
||||||
|
export interface AnnouncementData {
|
||||||
|
content: string;
|
||||||
|
enabled: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getAnnouncement = () => Network.get<AnnouncementData>("/announcement/get");
|
||||||
|
export const updateAnnouncement = (data: AnnouncementData) => Network.post("/announcement/update", data);
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect, useRef } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { Button } from "@heroui/button";
|
import { Button } from "@heroui/button";
|
||||||
import { Card, CardBody, CardHeader } from "@heroui/card";
|
import { Card, CardBody, CardHeader } from "@heroui/card";
|
||||||
import { Input } from "@heroui/input";
|
import { Input } from "@heroui/input";
|
||||||
|
import { Textarea } from "@heroui/input";
|
||||||
import { Spinner } from "@heroui/spinner";
|
import { Spinner } from "@heroui/spinner";
|
||||||
import { Divider } from "@heroui/divider";
|
import { Divider } from "@heroui/divider";
|
||||||
import { Switch } from "@heroui/switch";
|
import { Switch } from "@heroui/switch";
|
||||||
import { Select, SelectItem } from "@heroui/select";
|
import { Select, SelectItem } from "@heroui/select";
|
||||||
|
import { Checkbox, CheckboxGroup } from "@heroui/checkbox";
|
||||||
import toast from "react-hot-toast";
|
import toast from "react-hot-toast";
|
||||||
|
|
||||||
import { updateConfigs } from "@/api";
|
import { updateConfigs, exportBackup, importBackup, getAnnouncement, updateAnnouncement, type AnnouncementData } from "@/api";
|
||||||
import { SettingsIcon } from "@/components/icons";
|
import { SettingsIcon } from "@/components/icons";
|
||||||
import { isAdmin } from "@/utils/auth";
|
import { isAdmin } from "@/utils/auth";
|
||||||
import {
|
import {
|
||||||
@@ -130,12 +132,26 @@ export default function ConfigPage() {
|
|||||||
useState<Record<string, string>>(initialConfigs);
|
useState<Record<string, string>>(initialConfigs);
|
||||||
const [loading, setLoading] = useState(
|
const [loading, setLoading] = useState(
|
||||||
Object.keys(initialConfigs).length === 0,
|
Object.keys(initialConfigs).length === 0,
|
||||||
); // 如果有缓存数据,不显示loading
|
);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [hasChanges, setHasChanges] = useState(false);
|
const [hasChanges, setHasChanges] = useState(false);
|
||||||
const [originalConfigs, setOriginalConfigs] =
|
const [originalConfigs, setOriginalConfigs] =
|
||||||
useState<Record<string, string>>(initialConfigs);
|
useState<Record<string, string>>(initialConfigs);
|
||||||
|
|
||||||
|
const [exportTypes, setExportTypes] = useState<string[]>([]);
|
||||||
|
const [importTypes, setImportTypes] = useState<string[]>([]);
|
||||||
|
const [exporting, setExporting] = useState(false);
|
||||||
|
const [importing, setImporting] = useState(false);
|
||||||
|
const [importFileName, setImportFileName] = useState("");
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const [announcement, setAnnouncement] = useState<AnnouncementData>({
|
||||||
|
content: "",
|
||||||
|
enabled: 0,
|
||||||
|
});
|
||||||
|
const [announcementLoading, setAnnouncementLoading] = useState(true);
|
||||||
|
const [announcementSaving, setAnnouncementSaving] = useState(false);
|
||||||
|
|
||||||
// 权限检查
|
// 权限检查
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isAdmin()) {
|
if (!isAdmin()) {
|
||||||
@@ -180,21 +196,51 @@ export default function ConfigPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// 延迟加载,避免阻塞初始渲染
|
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
loadConfigs(initialConfigs);
|
loadConfigs(initialConfigs);
|
||||||
|
loadAnnouncement();
|
||||||
}, 100);
|
}, 100);
|
||||||
|
|
||||||
return () => clearTimeout(timer);
|
return () => clearTimeout(timer);
|
||||||
}, []); // 只在组件挂载时执行一次
|
}, []);
|
||||||
|
|
||||||
|
const loadAnnouncement = async () => {
|
||||||
|
setAnnouncementLoading(true);
|
||||||
|
try {
|
||||||
|
const res = await getAnnouncement();
|
||||||
|
|
||||||
|
if (res.code === 0 && res.data) {
|
||||||
|
setAnnouncement(res.data);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to load announcement:", error);
|
||||||
|
} finally {
|
||||||
|
setAnnouncementLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveAnnouncement = async () => {
|
||||||
|
setAnnouncementSaving(true);
|
||||||
|
try {
|
||||||
|
const res = await updateAnnouncement(announcement);
|
||||||
|
|
||||||
|
if (res.code === 0) {
|
||||||
|
toast.success("公告保存成功");
|
||||||
|
} else {
|
||||||
|
toast.error(res.msg || "保存失败");
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
toast.error("保存公告失败,请重试");
|
||||||
|
} finally {
|
||||||
|
setAnnouncementSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// 处理配置项变更
|
|
||||||
const handleConfigChange = (key: string, value: string) => {
|
const handleConfigChange = (key: string, value: string) => {
|
||||||
const newConfigs = { ...configs, [key]: value };
|
const newConfigs = { ...configs, [key]: value };
|
||||||
|
|
||||||
setConfigs(newConfigs);
|
setConfigs(newConfigs);
|
||||||
|
|
||||||
// 检查是否有变更
|
|
||||||
const hasChangesNow =
|
const hasChangesNow =
|
||||||
Object.keys(newConfigs).some(
|
Object.keys(newConfigs).some(
|
||||||
(k) => newConfigs[k] !== originalConfigs[k],
|
(k) => newConfigs[k] !== originalConfigs[k],
|
||||||
@@ -331,6 +377,63 @@ export default function ConfigPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleExport = async () => {
|
||||||
|
if (exportTypes.length === 0) {
|
||||||
|
toast.error("请至少选择一种数据类型");
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setExporting(true);
|
||||||
|
try {
|
||||||
|
await exportBackup(exportTypes);
|
||||||
|
toast.success("导出成功");
|
||||||
|
} catch {
|
||||||
|
toast.error("导出失败,请重试");
|
||||||
|
} finally {
|
||||||
|
setExporting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
if (importTypes.length === 0) {
|
||||||
|
toast.error("请先选择要导入的数据类型");
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setImportFileName(file.name);
|
||||||
|
setImporting(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const text = await file.text();
|
||||||
|
const data = JSON.parse(text);
|
||||||
|
|
||||||
|
const response = await importBackup({
|
||||||
|
types: importTypes,
|
||||||
|
...data,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.code === 0) {
|
||||||
|
toast.success(`导入成功: ${JSON.stringify(response.data)}`);
|
||||||
|
setImportTypes([]);
|
||||||
|
setImportFileName("");
|
||||||
|
} else {
|
||||||
|
toast.error("导入失败: " + response.msg);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
toast.error("导入失败,请检查文件格式");
|
||||||
|
} finally {
|
||||||
|
setImporting(false);
|
||||||
|
if (fileInputRef.current) {
|
||||||
|
fileInputRef.current.value = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center justify-center min-h-[400px]">
|
<div className="flex items-center justify-center min-h-[400px]">
|
||||||
@@ -414,7 +517,6 @@ export default function ConfigPage() {
|
|||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* 操作提示 */}
|
|
||||||
{hasChanges && (
|
{hasChanges && (
|
||||||
<Card className="mt-4 bg-warning-50 dark:bg-warning-900/20 border-warning-200 dark:border-warning-800">
|
<Card className="mt-4 bg-warning-50 dark:bg-warning-900/20 border-warning-200 dark:border-warning-800">
|
||||||
<CardBody className="py-3">
|
<CardBody className="py-3">
|
||||||
@@ -427,6 +529,203 @@ export default function ConfigPage() {
|
|||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<Card className="mt-6 shadow-md">
|
||||||
|
<CardHeader className="pb-4">
|
||||||
|
<div className="flex justify-between items-center w-full">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-xl font-semibold">公告管理</h2>
|
||||||
|
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||||
|
设置首页显示的公告内容
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<Divider />
|
||||||
|
|
||||||
|
<CardBody className="space-y-4 pt-6">
|
||||||
|
{announcementLoading ? (
|
||||||
|
<div className="flex justify-center py-8">
|
||||||
|
<Spinner size="lg" />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Switch
|
||||||
|
isSelected={announcement.enabled === 1}
|
||||||
|
onValueChange={(checked) =>
|
||||||
|
setAnnouncement({ ...announcement, enabled: checked ? 1 : 0 })
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<span className="text-sm text-gray-700 dark:text-gray-300">
|
||||||
|
{announcement.enabled === 1 ? "已启用" : "已禁用"}
|
||||||
|
</span>
|
||||||
|
</Switch>
|
||||||
|
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||||
|
启用后,公告将在首页顶部显示
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Textarea
|
||||||
|
label="公告内容"
|
||||||
|
placeholder="请输入公告内容"
|
||||||
|
value={announcement.content}
|
||||||
|
variant="bordered"
|
||||||
|
minRows={4}
|
||||||
|
onChange={(e) =>
|
||||||
|
setAnnouncement({ ...announcement, content: e.target.value })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<Button
|
||||||
|
color="primary"
|
||||||
|
isLoading={announcementSaving}
|
||||||
|
startContent={<SaveIcon className="w-4 h-4" />}
|
||||||
|
onClick={saveAnnouncement}
|
||||||
|
>
|
||||||
|
保存公告
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</CardBody>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* 备份与恢复 */}
|
||||||
|
<Card className="mt-6 shadow-md">
|
||||||
|
<CardHeader className="pb-4">
|
||||||
|
<div className="flex justify-between items-center w-full">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-xl font-semibold">数据备份与恢复</h2>
|
||||||
|
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||||
|
导出或导入系统数据,支持选择特定数据类型
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<Divider />
|
||||||
|
|
||||||
|
<CardBody className="space-y-6 pt-6">
|
||||||
|
{/* 导出部分 */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-lg font-medium">导出数据</h3>
|
||||||
|
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||||
|
选择要导出的数据类型,导出为 JSON 格式文件
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<CheckboxGroup
|
||||||
|
classNames={{
|
||||||
|
wrapper: "gap-4",
|
||||||
|
}}
|
||||||
|
label="选择导出内容"
|
||||||
|
orientation="horizontal"
|
||||||
|
value={exportTypes}
|
||||||
|
onValueChange={(values) => setExportTypes(values as string[])}
|
||||||
|
>
|
||||||
|
<Checkbox value="users">用户</Checkbox>
|
||||||
|
<Checkbox value="nodes">节点</Checkbox>
|
||||||
|
<Checkbox value="tunnels">隧道</Checkbox>
|
||||||
|
<Checkbox value="forwards">转发</Checkbox>
|
||||||
|
<Checkbox value="userTunnels">用户隧道权限</Checkbox>
|
||||||
|
<Checkbox value="speedLimits">限速规则</Checkbox>
|
||||||
|
<Checkbox value="tunnelGroups">隧道分组</Checkbox>
|
||||||
|
<Checkbox value="userGroups">用户分组</Checkbox>
|
||||||
|
<Checkbox value="permissions">分组权限</Checkbox>
|
||||||
|
<Checkbox value="configs">系统配置</Checkbox>
|
||||||
|
</CheckboxGroup>
|
||||||
|
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Button
|
||||||
|
color="primary"
|
||||||
|
isLoading={exporting}
|
||||||
|
onPress={handleExport}
|
||||||
|
>
|
||||||
|
{exporting ? "导出中..." : "导出数据"}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="bordered"
|
||||||
|
onPress={() => {
|
||||||
|
setExportTypes([
|
||||||
|
"users",
|
||||||
|
"nodes",
|
||||||
|
"tunnels",
|
||||||
|
"forwards",
|
||||||
|
"userTunnels",
|
||||||
|
"speedLimits",
|
||||||
|
"tunnelGroups",
|
||||||
|
"userGroups",
|
||||||
|
"permissions",
|
||||||
|
"configs",
|
||||||
|
]);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
全选
|
||||||
|
</Button>
|
||||||
|
<Button variant="flat" onPress={() => setExportTypes([])}>
|
||||||
|
清空
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Divider />
|
||||||
|
|
||||||
|
{/* 导入部分 */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-lg font-medium">导入数据</h3>
|
||||||
|
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||||
|
选择要导入的数据类型,支持从备份文件恢复数据
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<CheckboxGroup
|
||||||
|
classNames={{
|
||||||
|
wrapper: "gap-4",
|
||||||
|
}}
|
||||||
|
label="选择导入内容"
|
||||||
|
orientation="horizontal"
|
||||||
|
value={importTypes}
|
||||||
|
onValueChange={(values) => setImportTypes(values as string[])}
|
||||||
|
>
|
||||||
|
<Checkbox value="users">用户</Checkbox>
|
||||||
|
<Checkbox value="nodes">节点</Checkbox>
|
||||||
|
<Checkbox value="tunnels">隧道</Checkbox>
|
||||||
|
<Checkbox value="forwards">转发</Checkbox>
|
||||||
|
<Checkbox value="userTunnels">用户隧道权限</Checkbox>
|
||||||
|
<Checkbox value="speedLimits">限速规则</Checkbox>
|
||||||
|
<Checkbox value="tunnelGroups">隧道分组</Checkbox>
|
||||||
|
<Checkbox value="userGroups">用户分组</Checkbox>
|
||||||
|
<Checkbox value="permissions">分组权限</Checkbox>
|
||||||
|
<Checkbox value="configs">系统配置</Checkbox>
|
||||||
|
</CheckboxGroup>
|
||||||
|
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
accept=".json"
|
||||||
|
className="hidden"
|
||||||
|
type="file"
|
||||||
|
onChange={handleFileChange}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Button
|
||||||
|
color="primary"
|
||||||
|
isLoading={importing}
|
||||||
|
variant="flat"
|
||||||
|
onPress={() => fileInputRef.current?.click()}
|
||||||
|
>
|
||||||
|
{importing ? "导入中..." : "选择文件导入"}
|
||||||
|
</Button>
|
||||||
|
{importFileName && (
|
||||||
|
<span className="self-center text-sm text-gray-600 dark:text-gray-400">
|
||||||
|
已选择: {importFileName}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardBody>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
ResponsiveContainer,
|
ResponsiveContainer,
|
||||||
} from "recharts";
|
} from "recharts";
|
||||||
|
|
||||||
import { getUserPackageInfo } from "@/api";
|
import { getUserPackageInfo, getAnnouncement, type AnnouncementData } from "@/api";
|
||||||
|
|
||||||
interface UserInfo {
|
interface UserInfo {
|
||||||
flow: number;
|
flow: number;
|
||||||
@@ -71,6 +71,7 @@ export default function DashboardPage() {
|
|||||||
const [forwardList, setForwardList] = useState<Forward[]>([]);
|
const [forwardList, setForwardList] = useState<Forward[]>([]);
|
||||||
const [statisticsFlows, setStatisticsFlows] = useState<StatisticsFlow[]>([]);
|
const [statisticsFlows, setStatisticsFlows] = useState<StatisticsFlow[]>([]);
|
||||||
const [isAdmin, setIsAdmin] = useState(false);
|
const [isAdmin, setIsAdmin] = useState(false);
|
||||||
|
const [announcement, setAnnouncement] = useState<AnnouncementData | null>(null);
|
||||||
|
|
||||||
const [addressModalOpen, setAddressModalOpen] = useState(false);
|
const [addressModalOpen, setAddressModalOpen] = useState(false);
|
||||||
const [addressModalTitle, setAddressModalTitle] = useState("");
|
const [addressModalTitle, setAddressModalTitle] = useState("");
|
||||||
@@ -170,22 +171,33 @@ export default function DashboardPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// 重置状态并加载数据,防止页面切换时显示旧数据
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setUserInfo({} as UserInfo);
|
setUserInfo({} as UserInfo);
|
||||||
setUserTunnels([]);
|
setUserTunnels([]);
|
||||||
setForwardList([]);
|
setForwardList([]);
|
||||||
setStatisticsFlows([]);
|
setStatisticsFlows([]);
|
||||||
|
|
||||||
// 检查用户是否是管理员
|
|
||||||
const adminStatus = localStorage.getItem("admin");
|
const adminStatus = localStorage.getItem("admin");
|
||||||
|
|
||||||
setIsAdmin(adminStatus === "true");
|
setIsAdmin(adminStatus === "true");
|
||||||
|
|
||||||
loadPackageData();
|
loadPackageData();
|
||||||
|
loadAnnouncement();
|
||||||
localStorage.setItem("e", "/dashboard");
|
localStorage.setItem("e", "/dashboard");
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const loadAnnouncement = async () => {
|
||||||
|
try {
|
||||||
|
const res = await getAnnouncement();
|
||||||
|
|
||||||
|
if (res.code === 0 && res.data && res.data.enabled === 1) {
|
||||||
|
setAnnouncement(res.data);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to load announcement:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const loadPackageData = async () => {
|
const loadPackageData = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
@@ -703,7 +715,35 @@ export default function DashboardPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="px-3 lg:px-6 py-2 lg:py-4">
|
<div className="px-3 lg:px-6 py-2 lg:py-4">
|
||||||
{/* 响应式统计卡片 */}
|
{announcement && announcement.content && (
|
||||||
|
<Card className="mb-4 lg:mb-6 border border-blue-200 dark:border-blue-500/30 bg-gradient-to-r from-blue-50 to-purple-50 dark:from-blue-500/10 dark:to-purple-500/10">
|
||||||
|
<CardBody className="p-4">
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<div className="p-2 bg-blue-100 dark:bg-blue-500/20 rounded-lg flex-shrink-0">
|
||||||
|
<svg
|
||||||
|
className="w-5 h-5 text-blue-600 dark:text-blue-400"
|
||||||
|
fill="currentColor"
|
||||||
|
viewBox="0 0 20 20"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
clipRule="evenodd"
|
||||||
|
d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
|
||||||
|
fillRule="evenodd"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<h3 className="text-sm lg:text-base font-semibold text-blue-900 dark:text-blue-100 mb-1">
|
||||||
|
公告
|
||||||
|
</h3>
|
||||||
|
<p className="text-xs lg:text-sm text-blue-800 dark:text-blue-200 whitespace-pre-wrap break-words">
|
||||||
|
{announcement.content}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardBody>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 lg:gap-4 mb-6 lg:mb-8">
|
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 lg:gap-4 mb-6 lg:mb-8">
|
||||||
<Card className="border border-gray-200 dark:border-default-200 shadow-md hover:shadow-lg transition-shadow">
|
<Card className="border border-gray-200 dark:border-default-200 shadow-md hover:shadow-lg transition-shadow">
|
||||||
<CardBody className="p-3 lg:p-4">
|
<CardBody className="p-3 lg:p-4">
|
||||||
|
|||||||
@@ -83,8 +83,9 @@ export default function IndexPage() {
|
|||||||
if (response.code !== 0) {
|
if (response.code !== 0) {
|
||||||
toast.error(response.msg || "登录失败");
|
toast.error(response.msg || "登录失败");
|
||||||
if (showCaptcha) {
|
if (showCaptcha) {
|
||||||
setForm((prev) => ({ ...prev, captchaId: "" }));
|
setForm((prev) => ({ ...prev, captchaId: "" }));
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,11 +139,7 @@ export default function IndexPage() {
|
|||||||
} else {
|
} else {
|
||||||
const configResp = await getConfigByName("cloudflare_site_key");
|
const configResp = await getConfigByName("cloudflare_site_key");
|
||||||
|
|
||||||
if (
|
if (configResp.code === 0 && configResp.data && configResp.data.value) {
|
||||||
configResp.code === 0 &&
|
|
||||||
configResp.data &&
|
|
||||||
configResp.data.value
|
|
||||||
) {
|
|
||||||
setSiteKey(configResp.data.value);
|
setSiteKey(configResp.data.value);
|
||||||
setShowCaptcha(true);
|
setShowCaptcha(true);
|
||||||
} else {
|
} else {
|
||||||
@@ -241,8 +238,10 @@ export default function IndexPage() {
|
|||||||
{showCaptcha && siteKey && (
|
{showCaptcha && siteKey && (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
||||||
{/* 背景遮罩层 - 模糊效果,暗黑模式下更深 */}
|
{/* 背景遮罩层 - 模糊效果,暗黑模式下更深 */}
|
||||||
<div
|
<div
|
||||||
className="absolute inset-0 bg-black/60 dark:bg-black/80 backdrop-blur-sm captcha-backdrop-enter"
|
className="absolute inset-0 bg-black/60 dark:bg-black/80 backdrop-blur-sm captcha-backdrop-enter"
|
||||||
|
role="button"
|
||||||
|
tabIndex={0}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setShowCaptcha(false);
|
setShowCaptcha(false);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
@@ -253,32 +252,35 @@ export default function IndexPage() {
|
|||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
role="button"
|
|
||||||
tabIndex={0}
|
|
||||||
/>
|
/>
|
||||||
{/* 验证码容器 */}
|
{/* 验证码容器 */}
|
||||||
<div className="mb-4 relative z-50 bg-white dark:bg-zinc-900 p-6 rounded-lg shadow-xl">
|
<div className="mb-4 relative z-50 bg-white dark:bg-zinc-900 p-6 rounded-lg shadow-xl">
|
||||||
<div className="mb-4 text-center text-sm font-medium text-gray-700 dark:text-gray-200">请完成安全验证</div>
|
<div className="mb-4 text-center text-sm font-medium text-gray-700 dark:text-gray-200">
|
||||||
|
请完成安全验证
|
||||||
|
</div>
|
||||||
<div className="flex justify-center">
|
<div className="flex justify-center">
|
||||||
<Turnstile
|
<Turnstile
|
||||||
siteKey={siteKey}
|
options={{
|
||||||
onSuccess={(token) => {
|
theme: (document.documentElement.classList.contains(
|
||||||
setForm((prev) => ({ ...prev, captchaId: token }));
|
"dark",
|
||||||
void performLogin(token);
|
) ||
|
||||||
|
document.documentElement.getAttribute("data-theme") ===
|
||||||
|
"dark" ||
|
||||||
|
window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||||
|
? "dark"
|
||||||
|
: "light") as "light" | "dark" | "auto",
|
||||||
}}
|
}}
|
||||||
|
siteKey={siteKey}
|
||||||
onError={() => {
|
onError={() => {
|
||||||
toast.error("验证失败,请刷新重试");
|
toast.error("验证失败,请刷新重试");
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}}
|
}}
|
||||||
onExpire={() => {
|
onExpire={() => {
|
||||||
setForm((prev) => ({ ...prev, captchaId: "" }));
|
setForm((prev) => ({ ...prev, captchaId: "" }));
|
||||||
}}
|
}}
|
||||||
options={{
|
onSuccess={(token) => {
|
||||||
theme: (document.documentElement.classList.contains("dark") ||
|
setForm((prev) => ({ ...prev, captchaId: token }));
|
||||||
document.documentElement.getAttribute("data-theme") === "dark" ||
|
void performLogin(token);
|
||||||
window.matchMedia("(prefers-color-scheme: dark)").matches
|
|
||||||
? "dark"
|
|
||||||
: "light") as "light" | "dark" | "auto"
|
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+378
-316
@@ -125,7 +125,12 @@ const SortableItem = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div ref={setNodeRef} style={style} {...attributes} className="overflow-hidden">
|
<div
|
||||||
|
ref={setNodeRef}
|
||||||
|
style={style}
|
||||||
|
{...attributes}
|
||||||
|
className="overflow-hidden"
|
||||||
|
>
|
||||||
{children(listeners)}
|
{children(listeners)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -174,13 +179,26 @@ export default function NodePage() {
|
|||||||
|
|
||||||
// 升级相关状态
|
// 升级相关状态
|
||||||
const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);
|
const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);
|
||||||
const [upgradeTarget, setUpgradeTarget] = useState<"single" | "batch">("single");
|
const [upgradeTarget, setUpgradeTarget] = useState<"single" | "batch">(
|
||||||
const [upgradeTargetNodeId, setUpgradeTargetNodeId] = useState<number | null>(null);
|
"single",
|
||||||
const [releases, setReleases] = useState<Array<{ version: string; name: string; publishedAt: string; prerelease: boolean }>>([]);
|
);
|
||||||
|
const [upgradeTargetNodeId, setUpgradeTargetNodeId] = useState<number | null>(
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
const [releases, setReleases] = useState<
|
||||||
|
Array<{
|
||||||
|
version: string;
|
||||||
|
name: string;
|
||||||
|
publishedAt: string;
|
||||||
|
prerelease: boolean;
|
||||||
|
}>
|
||||||
|
>([]);
|
||||||
const [releasesLoading, setReleasesLoading] = useState(false);
|
const [releasesLoading, setReleasesLoading] = useState(false);
|
||||||
const [selectedVersion, setSelectedVersion] = useState("");
|
const [selectedVersion, setSelectedVersion] = useState("");
|
||||||
const [batchUpgradeLoading, setBatchUpgradeLoading] = useState(false);
|
const [batchUpgradeLoading, setBatchUpgradeLoading] = useState(false);
|
||||||
const [upgradeProgress, setUpgradeProgress] = useState<Record<number, { stage: string; percent: number; message: string }>>({});
|
const [upgradeProgress, setUpgradeProgress] = useState<
|
||||||
|
Record<number, { stage: string; percent: number; message: string }>
|
||||||
|
>({});
|
||||||
|
|
||||||
const websocketRef = useRef<WebSocket | null>(null);
|
const websocketRef = useRef<WebSocket | null>(null);
|
||||||
const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);
|
const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
@@ -237,7 +255,11 @@ export default function NodePage() {
|
|||||||
const nodesData: Node[] = (res.data || []).map((node: any) => ({
|
const nodesData: Node[] = (res.data || []).map((node: any) => ({
|
||||||
...node,
|
...node,
|
||||||
inx: node.inx ?? 0,
|
inx: node.inx ?? 0,
|
||||||
connectionStatus: node.syncError ? "offline" : node.status === 1 ? "online" : "offline",
|
connectionStatus: node.syncError
|
||||||
|
? "offline"
|
||||||
|
: node.status === 1
|
||||||
|
? "online"
|
||||||
|
: "offline",
|
||||||
syncError: node.syncError || undefined,
|
syncError: node.syncError || undefined,
|
||||||
systemInfo: null,
|
systemInfo: null,
|
||||||
copyLoading: false,
|
copyLoading: false,
|
||||||
@@ -444,7 +466,11 @@ export default function NodePage() {
|
|||||||
);
|
);
|
||||||
} else if (type === "upgrade_progress") {
|
} else if (type === "upgrade_progress") {
|
||||||
try {
|
try {
|
||||||
const progressData = typeof messageData === "string" ? JSON.parse(messageData) : messageData;
|
const progressData =
|
||||||
|
typeof messageData === "string"
|
||||||
|
? JSON.parse(messageData)
|
||||||
|
: messageData;
|
||||||
|
|
||||||
if (progressData?.data) {
|
if (progressData?.data) {
|
||||||
setUpgradeProgress((prev) => ({
|
setUpgradeProgress((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
@@ -803,10 +829,11 @@ export default function NodePage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// 打开版本选择弹窗
|
// 打开版本选择弹窗
|
||||||
const openUpgradeModal = async (target: "single" | "batch", nodeId?: number) => {
|
const openUpgradeModal = async (
|
||||||
|
target: "single" | "batch",
|
||||||
|
nodeId?: number,
|
||||||
|
) => {
|
||||||
setUpgradeTarget(target);
|
setUpgradeTarget(target);
|
||||||
setUpgradeTargetNodeId(nodeId || null);
|
setUpgradeTargetNodeId(nodeId || null);
|
||||||
setSelectedVersion("");
|
setSelectedVersion("");
|
||||||
@@ -814,6 +841,7 @@ export default function NodePage() {
|
|||||||
setReleasesLoading(true);
|
setReleasesLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await getNodeReleases();
|
const res = await getNodeReleases();
|
||||||
|
|
||||||
if (res.code === 0 && Array.isArray(res.data)) {
|
if (res.code === 0 && Array.isArray(res.data)) {
|
||||||
setReleases(res.data);
|
setReleases(res.data);
|
||||||
} else {
|
} else {
|
||||||
@@ -829,16 +857,21 @@ export default function NodePage() {
|
|||||||
// 确认升级(从版本弹窗)
|
// 确认升级(从版本弹窗)
|
||||||
const handleConfirmUpgrade = async () => {
|
const handleConfirmUpgrade = async () => {
|
||||||
const version = selectedVersion || undefined;
|
const version = selectedVersion || undefined;
|
||||||
|
|
||||||
if (upgradeTarget === "single" && upgradeTargetNodeId) {
|
if (upgradeTarget === "single" && upgradeTargetNodeId) {
|
||||||
setUpgradeModalOpen(false);
|
setUpgradeModalOpen(false);
|
||||||
// Find the node
|
// Find the node
|
||||||
const node = nodeList.find((n) => n.id === upgradeTargetNodeId);
|
const node = nodeList.find((n) => n.id === upgradeTargetNodeId);
|
||||||
|
|
||||||
if (!node) return;
|
if (!node) return;
|
||||||
setNodeList((prev) =>
|
setNodeList((prev) =>
|
||||||
prev.map((n) => (n.id === upgradeTargetNodeId ? { ...n, upgradeLoading: true } : n)),
|
prev.map((n) =>
|
||||||
|
n.id === upgradeTargetNodeId ? { ...n, upgradeLoading: true } : n,
|
||||||
|
),
|
||||||
);
|
);
|
||||||
try {
|
try {
|
||||||
const res = await upgradeNode(upgradeTargetNodeId, version);
|
const res = await upgradeNode(upgradeTargetNodeId, version);
|
||||||
|
|
||||||
if (res.code === 0) {
|
if (res.code === 0) {
|
||||||
toast.success(`节点升级命令已发送,节点将自动重启`);
|
toast.success(`节点升级命令已发送,节点将自动重启`);
|
||||||
} else {
|
} else {
|
||||||
@@ -848,7 +881,9 @@ export default function NodePage() {
|
|||||||
toast.error("网络错误,请重试");
|
toast.error("网络错误,请重试");
|
||||||
} finally {
|
} finally {
|
||||||
setNodeList((prev) =>
|
setNodeList((prev) =>
|
||||||
prev.map((n) => (n.id === upgradeTargetNodeId ? { ...n, upgradeLoading: false } : n)),
|
prev.map((n) =>
|
||||||
|
n.id === upgradeTargetNodeId ? { ...n, upgradeLoading: false } : n,
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else if (upgradeTarget === "batch") {
|
} else if (upgradeTarget === "batch") {
|
||||||
@@ -856,6 +891,7 @@ export default function NodePage() {
|
|||||||
setUpgradeModalOpen(false);
|
setUpgradeModalOpen(false);
|
||||||
try {
|
try {
|
||||||
const res = await batchUpgradeNodes(Array.from(selectedIds), version);
|
const res = await batchUpgradeNodes(Array.from(selectedIds), version);
|
||||||
|
|
||||||
if (res.code === 0) {
|
if (res.code === 0) {
|
||||||
toast.success(`批量升级命令已发送到 ${selectedIds.size} 个节点`);
|
toast.success(`批量升级命令已发送到 ${selectedIds.size} 个节点`);
|
||||||
} else {
|
} else {
|
||||||
@@ -876,6 +912,7 @@ export default function NodePage() {
|
|||||||
);
|
);
|
||||||
try {
|
try {
|
||||||
const res = await rollbackNode(node.id);
|
const res = await rollbackNode(node.id);
|
||||||
|
|
||||||
if (res.code === 0) {
|
if (res.code === 0) {
|
||||||
toast.success(`节点 ${node.name} 回退命令已发送,节点将自动重启`);
|
toast.success(`节点 ${node.name} 回退命令已发送,节点将自动重启`);
|
||||||
} else {
|
} else {
|
||||||
@@ -885,7 +922,9 @@ export default function NodePage() {
|
|||||||
toast.error("网络错误,请重试");
|
toast.error("网络错误,请重试");
|
||||||
} finally {
|
} finally {
|
||||||
setNodeList((prev) =>
|
setNodeList((prev) =>
|
||||||
prev.map((n) => (n.id === node.id ? { ...n, rollbackLoading: false } : n)),
|
prev.map((n) =>
|
||||||
|
n.id === node.id ? { ...n, rollbackLoading: false } : n,
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -1251,332 +1290,349 @@ export default function NodePage() {
|
|||||||
return (
|
return (
|
||||||
<SortableItem key={node.id} id={node.id}>
|
<SortableItem key={node.id} id={node.id}>
|
||||||
{(listeners) => (
|
{(listeners) => (
|
||||||
<Card
|
<Card
|
||||||
key={node.id}
|
key={node.id}
|
||||||
className="group shadow-sm border border-divider hover:shadow-md transition-shadow duration-200 overflow-hidden"
|
className="group shadow-sm border border-divider hover:shadow-md transition-shadow duration-200 overflow-hidden"
|
||||||
>
|
>
|
||||||
<CardHeader className="pb-2">
|
<CardHeader className="pb-2">
|
||||||
<div className="flex justify-between items-start w-full">
|
<div className="flex justify-between items-start w-full">
|
||||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||||
{selectMode && (
|
{selectMode && (
|
||||||
<Checkbox
|
<Checkbox
|
||||||
isSelected={selectedIds.has(node.id)}
|
isSelected={selectedIds.has(node.id)}
|
||||||
onValueChange={() => toggleSelect(node.id)}
|
onValueChange={() => toggleSelect(node.id)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<h3 className="font-semibold text-foreground truncate text-sm">
|
<h3 className="font-semibold text-foreground truncate text-sm">
|
||||||
{node.name}
|
{node.name}
|
||||||
</h3>
|
</h3>
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-1.5 ml-2">
|
|
||||||
<div
|
|
||||||
className="cursor-grab active:cursor-grabbing p-2 text-default-400 hover:text-default-600 transition-colors touch-manipulation opacity-100 sm:opacity-0 sm:group-hover:opacity-100"
|
|
||||||
{...listeners}
|
|
||||||
style={{ touchAction: "none" }}
|
|
||||||
title="拖拽排序"
|
|
||||||
>
|
|
||||||
<svg
|
|
||||||
className="w-4 h-4"
|
|
||||||
fill="currentColor"
|
|
||||||
viewBox="0 0 20 20"
|
|
||||||
>
|
|
||||||
<path d="M7 2a2 2 0 1 1 .001 4.001A2 2 0 0 1 7 2zm0 6a2 2 0 1 1 .001 4.001A2 2 0 0 1 7 8zm0 6a2 2 0 1 1 .001 4.001A2 2 0 0 1 7 14zm6-8a2 2 0 1 1-.001-4.001A2 2 0 0 1 13 6zm0 2a2 2 0 1 1 .001 4.001A2 2 0 0 1 13 8zm0 6a2 2 0 1 1 .001 4.001A2 2 0 0 1 13 14z" />
|
|
||||||
</svg>
|
|
||||||
</div>
|
</div>
|
||||||
{isRemoteNode && (
|
<div className="flex items-center gap-1.5 ml-2">
|
||||||
|
<div
|
||||||
|
className="cursor-grab active:cursor-grabbing p-2 text-default-400 hover:text-default-600 transition-colors touch-manipulation opacity-100 sm:opacity-0 sm:group-hover:opacity-100"
|
||||||
|
{...listeners}
|
||||||
|
style={{ touchAction: "none" }}
|
||||||
|
title="拖拽排序"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
className="w-4 h-4"
|
||||||
|
fill="currentColor"
|
||||||
|
viewBox="0 0 20 20"
|
||||||
|
>
|
||||||
|
<path d="M7 2a2 2 0 1 1 .001 4.001A2 2 0 0 1 7 2zm0 6a2 2 0 1 1 .001 4.001A2 2 0 0 1 7 8zm0 6a2 2 0 1 1 .001 4.001A2 2 0 0 1 7 14zm6-8a2 2 0 1 1-.001-4.001A2 2 0 0 1 13 6zm0 2a2 2 0 1 1 .001 4.001A2 2 0 0 1 13 8zm0 6a2 2 0 1 1 .001 4.001A2 2 0 0 1 13 14z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
{isRemoteNode && (
|
||||||
|
<Chip
|
||||||
|
className="text-xs"
|
||||||
|
color="secondary"
|
||||||
|
size="sm"
|
||||||
|
variant="flat"
|
||||||
|
>
|
||||||
|
远程
|
||||||
|
</Chip>
|
||||||
|
)}
|
||||||
<Chip
|
<Chip
|
||||||
className="text-xs"
|
className="text-xs"
|
||||||
color="secondary"
|
color={
|
||||||
|
node.connectionStatus === "online"
|
||||||
|
? "success"
|
||||||
|
: "danger"
|
||||||
|
}
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="flat"
|
variant="flat"
|
||||||
>
|
>
|
||||||
远程
|
{node.connectionStatus === "online"
|
||||||
|
? "在线"
|
||||||
|
: "离线"}
|
||||||
</Chip>
|
</Chip>
|
||||||
)}
|
|
||||||
<Chip
|
|
||||||
className="text-xs"
|
|
||||||
color={
|
|
||||||
node.connectionStatus === "online"
|
|
||||||
? "success"
|
|
||||||
: "danger"
|
|
||||||
}
|
|
||||||
size="sm"
|
|
||||||
variant="flat"
|
|
||||||
>
|
|
||||||
{node.connectionStatus === "online"
|
|
||||||
? "在线"
|
|
||||||
: "离线"}
|
|
||||||
</Chip>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
|
|
||||||
<CardBody className="pt-0 pb-3">
|
|
||||||
{isRemoteNode && node.syncError && (
|
|
||||||
<div className="mb-3 px-2 py-1.5 rounded-md bg-warning-50 dark:bg-warning-100/10 text-warning-700 dark:text-warning-400 text-xs">
|
|
||||||
{node.syncError === "provider_share_deleted"
|
|
||||||
? "提供方已删除该分享"
|
|
||||||
: node.syncError === "provider_share_disabled"
|
|
||||||
? "提供方已禁用该分享"
|
|
||||||
: node.syncError === "provider_share_expired"
|
|
||||||
? "提供方分享已过期"
|
|
||||||
: `远程同步失败: ${node.syncError}`}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{/* 基础信息 */}
|
|
||||||
<div className="space-y-2 mb-4">
|
|
||||||
<div className="flex justify-between items-center text-sm min-w-0">
|
|
||||||
<span className="text-default-600 flex-shrink-0">
|
|
||||||
IP
|
|
||||||
</span>
|
|
||||||
<div className="text-right text-xs min-w-0 flex-1 ml-2">
|
|
||||||
{node.serverIpV4?.trim() ||
|
|
||||||
node.serverIpV6?.trim() ? (
|
|
||||||
<div className="space-y-0.5">
|
|
||||||
{node.serverIpV4?.trim() && (
|
|
||||||
<span
|
|
||||||
className="font-mono truncate block"
|
|
||||||
title={node.serverIpV4.trim()}
|
|
||||||
>
|
|
||||||
{node.serverIpV4.trim()}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{node.serverIpV6?.trim() && (
|
|
||||||
<span
|
|
||||||
className="font-mono truncate block"
|
|
||||||
title={node.serverIpV6.trim()}
|
|
||||||
>
|
|
||||||
{node.serverIpV6.trim()}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<span
|
|
||||||
className="font-mono truncate block"
|
|
||||||
title={node.serverIp.trim()}
|
|
||||||
>
|
|
||||||
{node.serverIp.trim()}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardBody className="pt-0 pb-3">
|
||||||
|
{isRemoteNode && node.syncError && (
|
||||||
|
<div className="mb-3 px-2 py-1.5 rounded-md bg-warning-50 dark:bg-warning-100/10 text-warning-700 dark:text-warning-400 text-xs">
|
||||||
|
{node.syncError === "provider_share_deleted"
|
||||||
|
? "提供方已删除该分享"
|
||||||
|
: node.syncError === "provider_share_disabled"
|
||||||
|
? "提供方已禁用该分享"
|
||||||
|
: node.syncError === "provider_share_expired"
|
||||||
|
? "提供方分享已过期"
|
||||||
|
: `远程同步失败: ${node.syncError}`}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{/* 基础信息 */}
|
||||||
|
<div className="space-y-2 mb-4">
|
||||||
|
<div className="flex justify-between items-center text-sm min-w-0">
|
||||||
|
<span className="text-default-600 flex-shrink-0">
|
||||||
|
IP
|
||||||
|
</span>
|
||||||
|
<div className="text-right text-xs min-w-0 flex-1 ml-2">
|
||||||
|
{node.serverIpV4?.trim() ||
|
||||||
|
node.serverIpV6?.trim() ? (
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
{node.serverIpV4?.trim() && (
|
||||||
|
<span
|
||||||
|
className="font-mono truncate block"
|
||||||
|
title={node.serverIpV4.trim()}
|
||||||
|
>
|
||||||
|
{node.serverIpV4.trim()}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{node.serverIpV6?.trim() && (
|
||||||
|
<span
|
||||||
|
className="font-mono truncate block"
|
||||||
|
title={node.serverIpV6.trim()}
|
||||||
|
>
|
||||||
|
{node.serverIpV6.trim()}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span
|
||||||
|
className="font-mono truncate block"
|
||||||
|
title={node.serverIp.trim()}
|
||||||
|
>
|
||||||
|
{node.serverIp.trim()}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{!isRemoteNode && (
|
||||||
|
<>
|
||||||
|
<div className="flex justify-between text-sm">
|
||||||
|
<span className="text-default-600">版本</span>
|
||||||
|
<span className="text-xs">
|
||||||
|
{node.version || "未知"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{upgradeProgress[node.id] &&
|
||||||
|
upgradeProgress[node.id].percent < 100 && (
|
||||||
|
<div className="mt-1">
|
||||||
|
<Progress
|
||||||
|
showValueLabel
|
||||||
|
aria-label="升级进度"
|
||||||
|
color="warning"
|
||||||
|
label={upgradeProgress[node.id].message}
|
||||||
|
size="sm"
|
||||||
|
value={upgradeProgress[node.id].percent}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex justify-between text-sm">
|
||||||
|
<span className="text-default-600">
|
||||||
|
开机时间
|
||||||
|
</span>
|
||||||
|
<span className="text-xs">
|
||||||
|
{node.connectionStatus === "online" &&
|
||||||
|
node.systemInfo
|
||||||
|
? formatUptime(node.systemInfo.uptime)
|
||||||
|
: "-"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
{!isRemoteNode && (
|
{!isRemoteNode && (
|
||||||
<>
|
<>
|
||||||
<div className="flex justify-between text-sm">
|
{/* 系统监控 */}
|
||||||
<span className="text-default-600">版本</span>
|
<div className="space-y-3 mb-4">
|
||||||
<span className="text-xs">
|
<div className="grid grid-cols-2 gap-3">
|
||||||
{node.version || "未知"}
|
<div>
|
||||||
</span>
|
<div className="flex justify-between text-xs mb-1">
|
||||||
</div>
|
<span>CPU</span>
|
||||||
{upgradeProgress[node.id] && upgradeProgress[node.id].percent < 100 && (
|
<span className="font-mono">
|
||||||
<div className="mt-1">
|
{node.connectionStatus === "online" &&
|
||||||
<Progress
|
node.systemInfo
|
||||||
aria-label="升级进度"
|
? `${node.systemInfo.cpuUsage.toFixed(1)}%`
|
||||||
color="warning"
|
: "-"}
|
||||||
label={upgradeProgress[node.id].message}
|
</span>
|
||||||
showValueLabel
|
</div>
|
||||||
size="sm"
|
<Progress
|
||||||
value={upgradeProgress[node.id].percent}
|
aria-label="CPU使用率"
|
||||||
/>
|
color={getProgressColor(
|
||||||
|
node.connectionStatus === "online" &&
|
||||||
|
node.systemInfo
|
||||||
|
? node.systemInfo.cpuUsage
|
||||||
|
: 0,
|
||||||
|
node.connectionStatus !== "online",
|
||||||
|
)}
|
||||||
|
size="sm"
|
||||||
|
value={
|
||||||
|
node.connectionStatus === "online" &&
|
||||||
|
node.systemInfo
|
||||||
|
? node.systemInfo.cpuUsage
|
||||||
|
: 0
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="flex justify-between text-xs mb-1">
|
||||||
|
<span>内存</span>
|
||||||
|
<span className="font-mono">
|
||||||
|
{node.connectionStatus === "online" &&
|
||||||
|
node.systemInfo
|
||||||
|
? `${node.systemInfo.memoryUsage.toFixed(1)}%`
|
||||||
|
: "-"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<Progress
|
||||||
|
aria-label="内存使用率"
|
||||||
|
color={getProgressColor(
|
||||||
|
node.connectionStatus === "online" &&
|
||||||
|
node.systemInfo
|
||||||
|
? node.systemInfo.memoryUsage
|
||||||
|
: 0,
|
||||||
|
node.connectionStatus !== "online",
|
||||||
|
)}
|
||||||
|
size="sm"
|
||||||
|
value={
|
||||||
|
node.connectionStatus === "online" &&
|
||||||
|
node.systemInfo
|
||||||
|
? node.systemInfo.memoryUsage
|
||||||
|
: 0
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-2 text-xs">
|
||||||
|
<div className="text-center p-2 bg-default-50 dark:bg-default-100 rounded">
|
||||||
|
<div className="text-default-600 mb-0.5">
|
||||||
|
上传
|
||||||
|
</div>
|
||||||
|
<div className="font-mono">
|
||||||
|
{node.connectionStatus === "online" &&
|
||||||
|
node.systemInfo
|
||||||
|
? formatSpeed(
|
||||||
|
node.systemInfo.uploadSpeed,
|
||||||
|
)
|
||||||
|
: "-"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-center p-2 bg-default-50 dark:bg-default-100 rounded">
|
||||||
|
<div className="text-default-600 mb-0.5">
|
||||||
|
下载
|
||||||
|
</div>
|
||||||
|
<div className="font-mono">
|
||||||
|
{node.connectionStatus === "online" &&
|
||||||
|
node.systemInfo
|
||||||
|
? formatSpeed(
|
||||||
|
node.systemInfo.downloadSpeed,
|
||||||
|
)
|
||||||
|
: "-"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 流量统计 */}
|
||||||
|
<div className="grid grid-cols-2 gap-2 text-xs">
|
||||||
|
<div className="text-center p-2 bg-primary-50 dark:bg-primary-100/20 rounded border border-primary-200 dark:border-primary-300/20">
|
||||||
|
<div className="text-primary-600 dark:text-primary-400 mb-0.5">
|
||||||
|
↑ 上行流量
|
||||||
|
</div>
|
||||||
|
<div className="font-mono text-primary-700 dark:text-primary-300">
|
||||||
|
{node.connectionStatus === "online" &&
|
||||||
|
node.systemInfo
|
||||||
|
? formatTraffic(
|
||||||
|
node.systemInfo.uploadTraffic,
|
||||||
|
)
|
||||||
|
: "-"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-center p-2 bg-success-50 dark:bg-success-100/20 rounded border border-success-200 dark:border-success-300/20">
|
||||||
|
<div className="text-success-600 dark:text-success-400 mb-0.5">
|
||||||
|
↓ 下行流量
|
||||||
|
</div>
|
||||||
|
<div className="font-mono text-success-700 dark:text-success-300">
|
||||||
|
{node.connectionStatus === "online" &&
|
||||||
|
node.systemInfo
|
||||||
|
? formatTraffic(
|
||||||
|
node.systemInfo.downloadTraffic,
|
||||||
|
)
|
||||||
|
: "-"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
<div className="flex justify-between text-sm">
|
|
||||||
<span className="text-default-600">开机时间</span>
|
|
||||||
<span className="text-xs">
|
|
||||||
{node.connectionStatus === "online" &&
|
|
||||||
node.systemInfo
|
|
||||||
? formatUptime(node.systemInfo.uptime)
|
|
||||||
: "-"}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
|
||||||
|
|
||||||
{!isRemoteNode && (
|
{/* 操作按钮 */}
|
||||||
<>
|
<div className="space-y-1.5">
|
||||||
{/* 系统监控 */}
|
|
||||||
<div className="space-y-3 mb-4">
|
|
||||||
<div className="grid grid-cols-2 gap-3">
|
|
||||||
<div>
|
|
||||||
<div className="flex justify-between text-xs mb-1">
|
|
||||||
<span>CPU</span>
|
|
||||||
<span className="font-mono">
|
|
||||||
{node.connectionStatus === "online" &&
|
|
||||||
node.systemInfo
|
|
||||||
? `${node.systemInfo.cpuUsage.toFixed(1)}%`
|
|
||||||
: "-"}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<Progress
|
|
||||||
aria-label="CPU使用率"
|
|
||||||
color={getProgressColor(
|
|
||||||
node.connectionStatus === "online" &&
|
|
||||||
node.systemInfo
|
|
||||||
? node.systemInfo.cpuUsage
|
|
||||||
: 0,
|
|
||||||
node.connectionStatus !== "online",
|
|
||||||
)}
|
|
||||||
size="sm"
|
|
||||||
value={
|
|
||||||
node.connectionStatus === "online" &&
|
|
||||||
node.systemInfo
|
|
||||||
? node.systemInfo.cpuUsage
|
|
||||||
: 0
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<div className="flex justify-between text-xs mb-1">
|
|
||||||
<span>内存</span>
|
|
||||||
<span className="font-mono">
|
|
||||||
{node.connectionStatus === "online" &&
|
|
||||||
node.systemInfo
|
|
||||||
? `${node.systemInfo.memoryUsage.toFixed(1)}%`
|
|
||||||
: "-"}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<Progress
|
|
||||||
aria-label="内存使用率"
|
|
||||||
color={getProgressColor(
|
|
||||||
node.connectionStatus === "online" &&
|
|
||||||
node.systemInfo
|
|
||||||
? node.systemInfo.memoryUsage
|
|
||||||
: 0,
|
|
||||||
node.connectionStatus !== "online",
|
|
||||||
)}
|
|
||||||
size="sm"
|
|
||||||
value={
|
|
||||||
node.connectionStatus === "online" &&
|
|
||||||
node.systemInfo
|
|
||||||
? node.systemInfo.memoryUsage
|
|
||||||
: 0
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-2 text-xs">
|
|
||||||
<div className="text-center p-2 bg-default-50 dark:bg-default-100 rounded">
|
|
||||||
<div className="text-default-600 mb-0.5">
|
|
||||||
上传
|
|
||||||
</div>
|
|
||||||
<div className="font-mono">
|
|
||||||
{node.connectionStatus === "online" &&
|
|
||||||
node.systemInfo
|
|
||||||
? formatSpeed(node.systemInfo.uploadSpeed)
|
|
||||||
: "-"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="text-center p-2 bg-default-50 dark:bg-default-100 rounded">
|
|
||||||
<div className="text-default-600 mb-0.5">
|
|
||||||
下载
|
|
||||||
</div>
|
|
||||||
<div className="font-mono">
|
|
||||||
{node.connectionStatus === "online" &&
|
|
||||||
node.systemInfo
|
|
||||||
? formatSpeed(node.systemInfo.downloadSpeed)
|
|
||||||
: "-"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 流量统计 */}
|
|
||||||
<div className="grid grid-cols-2 gap-2 text-xs">
|
|
||||||
<div className="text-center p-2 bg-primary-50 dark:bg-primary-100/20 rounded border border-primary-200 dark:border-primary-300/20">
|
|
||||||
<div className="text-primary-600 dark:text-primary-400 mb-0.5">
|
|
||||||
↑ 上行流量
|
|
||||||
</div>
|
|
||||||
<div className="font-mono text-primary-700 dark:text-primary-300">
|
|
||||||
{node.connectionStatus === "online" &&
|
|
||||||
node.systemInfo
|
|
||||||
? formatTraffic(node.systemInfo.uploadTraffic)
|
|
||||||
: "-"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="text-center p-2 bg-success-50 dark:bg-success-100/20 rounded border border-success-200 dark:border-success-300/20">
|
|
||||||
<div className="text-success-600 dark:text-success-400 mb-0.5">
|
|
||||||
↓ 下行流量
|
|
||||||
</div>
|
|
||||||
<div className="font-mono text-success-700 dark:text-success-300">
|
|
||||||
{node.connectionStatus === "online" &&
|
|
||||||
node.systemInfo
|
|
||||||
? formatTraffic(
|
|
||||||
node.systemInfo.downloadTraffic,
|
|
||||||
)
|
|
||||||
: "-"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* 操作按钮 */}
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
{!isRemoteNode && (
|
|
||||||
<div className="grid grid-cols-3 gap-1.5">
|
|
||||||
<Button
|
|
||||||
className="min-h-8"
|
|
||||||
color="success"
|
|
||||||
isLoading={node.copyLoading}
|
|
||||||
size="sm"
|
|
||||||
variant="flat"
|
|
||||||
onPress={() => handleCopyInstallCommand(node)}
|
|
||||||
>
|
|
||||||
安装
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
className="min-h-8"
|
|
||||||
color="warning"
|
|
||||||
isDisabled={node.connectionStatus !== "online"}
|
|
||||||
isLoading={node.upgradeLoading}
|
|
||||||
size="sm"
|
|
||||||
variant="flat"
|
|
||||||
onPress={() => openUpgradeModal("single", node.id)}
|
|
||||||
>
|
|
||||||
升级
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
className="min-h-8"
|
|
||||||
color="secondary"
|
|
||||||
isDisabled={node.connectionStatus !== "online"}
|
|
||||||
isLoading={node.rollbackLoading}
|
|
||||||
size="sm"
|
|
||||||
variant="flat"
|
|
||||||
onPress={() => handleRollbackNode(node)}
|
|
||||||
>
|
|
||||||
回退
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className={`grid gap-1.5 ${isRemoteNode ? "grid-cols-1" : "grid-cols-2"}`}>
|
|
||||||
{!isRemoteNode && (
|
{!isRemoteNode && (
|
||||||
|
<div className="grid grid-cols-3 gap-1.5">
|
||||||
|
<Button
|
||||||
|
className="min-h-8"
|
||||||
|
color="success"
|
||||||
|
isLoading={node.copyLoading}
|
||||||
|
size="sm"
|
||||||
|
variant="flat"
|
||||||
|
onPress={() => handleCopyInstallCommand(node)}
|
||||||
|
>
|
||||||
|
安装
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
className="min-h-8"
|
||||||
|
color="warning"
|
||||||
|
isDisabled={
|
||||||
|
node.connectionStatus !== "online"
|
||||||
|
}
|
||||||
|
isLoading={node.upgradeLoading}
|
||||||
|
size="sm"
|
||||||
|
variant="flat"
|
||||||
|
onPress={() =>
|
||||||
|
openUpgradeModal("single", node.id)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
升级
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
className="min-h-8"
|
||||||
|
color="secondary"
|
||||||
|
isDisabled={
|
||||||
|
node.connectionStatus !== "online"
|
||||||
|
}
|
||||||
|
isLoading={node.rollbackLoading}
|
||||||
|
size="sm"
|
||||||
|
variant="flat"
|
||||||
|
onPress={() => handleRollbackNode(node)}
|
||||||
|
>
|
||||||
|
回退
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div
|
||||||
|
className={`grid gap-1.5 ${isRemoteNode ? "grid-cols-1" : "grid-cols-2"}`}
|
||||||
|
>
|
||||||
|
{!isRemoteNode && (
|
||||||
|
<Button
|
||||||
|
className="min-h-8"
|
||||||
|
color="primary"
|
||||||
|
size="sm"
|
||||||
|
variant="flat"
|
||||||
|
onPress={() => handleEdit(node)}
|
||||||
|
>
|
||||||
|
编辑
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
<Button
|
<Button
|
||||||
className="min-h-8"
|
className="min-h-8"
|
||||||
color="primary"
|
color="danger"
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="flat"
|
variant="flat"
|
||||||
onPress={() => handleEdit(node)}
|
onPress={() => handleDelete(node)}
|
||||||
>
|
>
|
||||||
编辑
|
删除
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
</div>
|
||||||
<Button
|
|
||||||
className="min-h-8"
|
|
||||||
color="danger"
|
|
||||||
size="sm"
|
|
||||||
variant="flat"
|
|
||||||
onPress={() => handleDelete(node)}
|
|
||||||
>
|
|
||||||
删除
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</CardBody>
|
||||||
</CardBody>
|
</Card>
|
||||||
</Card>
|
)}
|
||||||
)}
|
</SortableItem>
|
||||||
</SortableItem>
|
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
@@ -2041,6 +2097,7 @@ export default function NodePage() {
|
|||||||
selectedKeys={selectedVersion ? [selectedVersion] : []}
|
selectedKeys={selectedVersion ? [selectedVersion] : []}
|
||||||
onSelectionChange={(keys) => {
|
onSelectionChange={(keys) => {
|
||||||
const selected = Array.from(keys)[0] as string;
|
const selected = Array.from(keys)[0] as string;
|
||||||
|
|
||||||
setSelectedVersion(selected || "");
|
setSelectedVersion(selected || "");
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -2053,7 +2110,12 @@ export default function NodePage() {
|
|||||||
? new Date(r.publishedAt).toLocaleDateString()
|
? new Date(r.publishedAt).toLocaleDateString()
|
||||||
: ""}
|
: ""}
|
||||||
{r.prerelease && (
|
{r.prerelease && (
|
||||||
<Chip className="ml-1" color="warning" size="sm" variant="flat">
|
<Chip
|
||||||
|
className="ml-1"
|
||||||
|
color="warning"
|
||||||
|
size="sm"
|
||||||
|
variant="flat"
|
||||||
|
>
|
||||||
预览
|
预览
|
||||||
</Chip>
|
</Chip>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
} from "@heroui/modal";
|
} from "@heroui/modal";
|
||||||
import { Select, SelectItem } from "@heroui/select";
|
import { Select, SelectItem } from "@heroui/select";
|
||||||
import { toast } from "react-hot-toast";
|
import { toast } from "react-hot-toast";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
getNodeList,
|
getNodeList,
|
||||||
createPeerShare,
|
createPeerShare,
|
||||||
@@ -128,6 +129,7 @@ export default function PanelSharingPage() {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await getPeerShareList();
|
const res = await getPeerShareList();
|
||||||
|
|
||||||
if (res.code === 0) {
|
if (res.code === 0) {
|
||||||
setShares(res.data || []);
|
setShares(res.data || []);
|
||||||
} else {
|
} else {
|
||||||
@@ -141,10 +143,12 @@ export default function PanelSharingPage() {
|
|||||||
const loadNodes = useCallback(async () => {
|
const loadNodes = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const res = await getNodeList();
|
const res = await getNodeList();
|
||||||
|
|
||||||
if (res.code === 0) {
|
if (res.code === 0) {
|
||||||
const localNodes: Node[] = (res.data || []).filter(
|
const localNodes: Node[] = (res.data || []).filter(
|
||||||
(node: Node) => (node?.isRemote ?? 0) !== 1,
|
(node: Node) => (node?.isRemote ?? 0) !== 1,
|
||||||
);
|
);
|
||||||
|
|
||||||
setNodes(localNodes);
|
setNodes(localNodes);
|
||||||
setShareForm((prev) => {
|
setShareForm((prev) => {
|
||||||
if (!prev.nodeId) {
|
if (!prev.nodeId) {
|
||||||
@@ -153,6 +157,7 @@ export default function PanelSharingPage() {
|
|||||||
const hasSelectedNode = localNodes.some(
|
const hasSelectedNode = localNodes.some(
|
||||||
(node: Node) => String(node.id) === prev.nodeId,
|
(node: Node) => String(node.id) === prev.nodeId,
|
||||||
);
|
);
|
||||||
|
|
||||||
return hasSelectedNode ? prev : { ...prev, nodeId: "" };
|
return hasSelectedNode ? prev : { ...prev, nodeId: "" };
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -165,6 +170,7 @@ export default function PanelSharingPage() {
|
|||||||
setRemoteUsageLoading(true);
|
setRemoteUsageLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await getPeerRemoteUsageList();
|
const res = await getPeerRemoteUsageList();
|
||||||
|
|
||||||
if (res.code === 0) {
|
if (res.code === 0) {
|
||||||
setRemoteUsageNodes(res.data || []);
|
setRemoteUsageNodes(res.data || []);
|
||||||
} else {
|
} else {
|
||||||
@@ -179,6 +185,7 @@ export default function PanelSharingPage() {
|
|||||||
if (selectedTab === "my-shares") {
|
if (selectedTab === "my-shares") {
|
||||||
loadShares();
|
loadShares();
|
||||||
loadNodes();
|
loadNodes();
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (selectedTab === "remote-nodes") {
|
if (selectedTab === "remote-nodes") {
|
||||||
@@ -189,15 +196,19 @@ export default function PanelSharingPage() {
|
|||||||
const handleCreateShare = async () => {
|
const handleCreateShare = async () => {
|
||||||
if (!shareForm.name || !shareForm.nodeId) {
|
if (!shareForm.name || !shareForm.nodeId) {
|
||||||
toast.error("请填写必要信息");
|
toast.error("请填写必要信息");
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const nodeId = parseInt(shareForm.nodeId, 10);
|
const nodeId = parseInt(shareForm.nodeId, 10);
|
||||||
|
|
||||||
if (Number.isNaN(nodeId) || !nodes.some((node) => node.id === nodeId)) {
|
if (Number.isNaN(nodeId) || !nodes.some((node) => node.id === nodeId)) {
|
||||||
toast.error("仅可选择本地节点");
|
toast.error("仅可选择本地节点");
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (shareForm.maxBandwidth < 0) {
|
if (shareForm.maxBandwidth < 0) {
|
||||||
toast.error("流量上限不能为负数");
|
toast.error("流量上限不能为负数");
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -213,6 +224,7 @@ export default function PanelSharingPage() {
|
|||||||
allowedDomains: shareForm.allowedDomains,
|
allowedDomains: shareForm.allowedDomains,
|
||||||
allowedIps: shareForm.allowedIps,
|
allowedIps: shareForm.allowedIps,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res.code === 0) {
|
if (res.code === 0) {
|
||||||
toast.success("创建成功");
|
toast.success("创建成功");
|
||||||
setCreateShareOpen(false);
|
setCreateShareOpen(false);
|
||||||
@@ -228,6 +240,7 @@ export default function PanelSharingPage() {
|
|||||||
const handleDeleteShare = async (id: number) => {
|
const handleDeleteShare = async (id: number) => {
|
||||||
try {
|
try {
|
||||||
const res = await deletePeerShare(id);
|
const res = await deletePeerShare(id);
|
||||||
|
|
||||||
if (res.code === 0) {
|
if (res.code === 0) {
|
||||||
toast.success("删除成功");
|
toast.success("删除成功");
|
||||||
loadShares();
|
loadShares();
|
||||||
@@ -242,6 +255,7 @@ export default function PanelSharingPage() {
|
|||||||
const handleResetShareFlow = async (id: number) => {
|
const handleResetShareFlow = async (id: number) => {
|
||||||
try {
|
try {
|
||||||
const res = await resetPeerShareFlow(id);
|
const res = await resetPeerShareFlow(id);
|
||||||
|
|
||||||
if (res.code === 0) {
|
if (res.code === 0) {
|
||||||
toast.success("共享流量已重置");
|
toast.success("共享流量已重置");
|
||||||
loadShares();
|
loadShares();
|
||||||
@@ -257,7 +271,10 @@ export default function PanelSharingPage() {
|
|||||||
setEditForm({
|
setEditForm({
|
||||||
id: share.id,
|
id: share.id,
|
||||||
name: share.name,
|
name: share.name,
|
||||||
maxBandwidth: share.maxBandwidth > 0 ? Math.round(share.maxBandwidth / (1024 * 1024 * 1024)) : 0,
|
maxBandwidth:
|
||||||
|
share.maxBandwidth > 0
|
||||||
|
? Math.round(share.maxBandwidth / (1024 * 1024 * 1024))
|
||||||
|
: 0,
|
||||||
expiryTime: share.expiryTime,
|
expiryTime: share.expiryTime,
|
||||||
portRangeStart: share.portRangeStart,
|
portRangeStart: share.portRangeStart,
|
||||||
portRangeEnd: share.portRangeEnd,
|
portRangeEnd: share.portRangeEnd,
|
||||||
@@ -270,10 +287,12 @@ export default function PanelSharingPage() {
|
|||||||
const handleEditShare = async () => {
|
const handleEditShare = async () => {
|
||||||
if (!editForm.name) {
|
if (!editForm.name) {
|
||||||
toast.error("名称不能为空");
|
toast.error("名称不能为空");
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (editForm.maxBandwidth < 0) {
|
if (editForm.maxBandwidth < 0) {
|
||||||
toast.error("流量上限不能为负数");
|
toast.error("流量上限不能为负数");
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -287,6 +306,7 @@ export default function PanelSharingPage() {
|
|||||||
allowedDomains: editForm.allowedDomains,
|
allowedDomains: editForm.allowedDomains,
|
||||||
allowedIps: editForm.allowedIps,
|
allowedIps: editForm.allowedIps,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res.code === 0) {
|
if (res.code === 0) {
|
||||||
toast.success("编辑成功");
|
toast.success("编辑成功");
|
||||||
setEditShareOpen(false);
|
setEditShareOpen(false);
|
||||||
@@ -302,19 +322,22 @@ export default function PanelSharingPage() {
|
|||||||
const handleImportNode = async () => {
|
const handleImportNode = async () => {
|
||||||
if (!importForm.remoteUrl || !importForm.token) {
|
if (!importForm.remoteUrl || !importForm.token) {
|
||||||
toast.error("请填写完整信息");
|
toast.error("请填写完整信息");
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
// Automatically add http/https if missing
|
// Automatically add http/https if missing
|
||||||
let url = importForm.remoteUrl.trim();
|
let url = importForm.remoteUrl.trim();
|
||||||
|
|
||||||
if (!url.startsWith("http")) {
|
if (!url.startsWith("http")) {
|
||||||
url = "http://" + url;
|
url = "http://" + url;
|
||||||
}
|
}
|
||||||
|
|
||||||
const res = await importRemoteNode({
|
const res = await importRemoteNode({
|
||||||
remoteUrl: url,
|
remoteUrl: url,
|
||||||
token: importForm.token.trim(),
|
token: importForm.token.trim(),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res.code === 0) {
|
if (res.code === 0) {
|
||||||
toast.success("导入成功,请前往节点列表查看");
|
toast.success("导入成功,请前往节点列表查看");
|
||||||
setImportNodeOpen(false);
|
setImportNodeOpen(false);
|
||||||
@@ -341,6 +364,7 @@ export default function PanelSharingPage() {
|
|||||||
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + " KB";
|
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + " KB";
|
||||||
if (bytes < 1024 * 1024 * 1024)
|
if (bytes < 1024 * 1024 * 1024)
|
||||||
return (bytes / (1024 * 1024)).toFixed(2) + " MB";
|
return (bytes / (1024 * 1024)).toFixed(2) + " MB";
|
||||||
|
|
||||||
return (bytes / (1024 * 1024 * 1024)).toFixed(2) + " GB";
|
return (bytes / (1024 * 1024 * 1024)).toFixed(2) + " GB";
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -351,6 +375,7 @@ export default function PanelSharingPage() {
|
|||||||
if (chainType === 3) {
|
if (chainType === 3) {
|
||||||
return "出口节点";
|
return "出口节点";
|
||||||
}
|
}
|
||||||
|
|
||||||
return "未知链路";
|
return "未知链路";
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -370,11 +395,14 @@ export default function PanelSharingPage() {
|
|||||||
<Card>
|
<Card>
|
||||||
<CardBody>
|
<CardBody>
|
||||||
<div className="mb-4">
|
<div className="mb-4">
|
||||||
<Button color="primary" onPress={() => setCreateShareOpen(true)}>
|
<Button
|
||||||
|
color="primary"
|
||||||
|
onPress={() => setCreateShareOpen(true)}
|
||||||
|
>
|
||||||
创建分享
|
创建分享
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="text-center py-10 text-gray-500">加载中...</div>
|
<div className="text-center py-10 text-gray-500">加载中...</div>
|
||||||
) : shares.length === 0 ? (
|
) : shares.length === 0 ? (
|
||||||
@@ -382,7 +410,10 @@ export default function PanelSharingPage() {
|
|||||||
) : (
|
) : (
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||||
{shares.map((share) => (
|
{shares.map((share) => (
|
||||||
<Card key={share.id} className="border border-divider shadow-sm">
|
<Card
|
||||||
|
key={share.id}
|
||||||
|
className="border border-divider shadow-sm"
|
||||||
|
>
|
||||||
<CardHeader className="flex justify-between">
|
<CardHeader className="flex justify-between">
|
||||||
<h3 className="font-bold">{share.name}</h3>
|
<h3 className="font-bold">{share.name}</h3>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
@@ -400,29 +431,67 @@ export default function PanelSharingPage() {
|
|||||||
>
|
>
|
||||||
重置流量
|
重置流量
|
||||||
</Button>
|
</Button>
|
||||||
<Button size="sm" color="danger" variant="flat" onPress={() => handleDeleteShare(share.id)}>删除</Button>
|
<Button
|
||||||
|
color="danger"
|
||||||
|
size="sm"
|
||||||
|
variant="flat"
|
||||||
|
onPress={() => handleDeleteShare(share.id)}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardBody className="text-sm space-y-2">
|
<CardBody className="text-sm space-y-2">
|
||||||
<p>端口范围: {share.portRangeStart} - {share.portRangeEnd}</p>
|
<p>
|
||||||
<p>流量上限: {share.maxBandwidth > 0 ? formatFlowGB(share.maxBandwidth) : "不限制"}</p>
|
端口范围: {share.portRangeStart} -{" "}
|
||||||
|
{share.portRangeEnd}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
流量上限:{" "}
|
||||||
|
{share.maxBandwidth > 0
|
||||||
|
? formatFlowGB(share.maxBandwidth)
|
||||||
|
: "不限制"}
|
||||||
|
</p>
|
||||||
<p>当前流量: {formatFlowGB(share.currentFlow || 0)}</p>
|
<p>当前流量: {formatFlowGB(share.currentFlow || 0)}</p>
|
||||||
<p>远程占用端口: {share.usedPorts && share.usedPorts.length > 0 ? share.usedPorts.join(", ") : "暂无"}</p>
|
<p>
|
||||||
{share.usedPortDetails && share.usedPortDetails.length > 0 && (
|
远程占用端口:{" "}
|
||||||
<div className="flex flex-wrap gap-2">
|
{share.usedPorts && share.usedPorts.length > 0
|
||||||
{share.usedPortDetails.map((item) => (
|
? share.usedPorts.join(", ")
|
||||||
<span key={item.runtimeId} className="text-xs rounded-full px-2 py-1 bg-default-100">
|
: "暂无"}
|
||||||
{item.port} / {item.role || "reserved"}
|
</p>
|
||||||
</span>
|
{share.usedPortDetails &&
|
||||||
))}
|
share.usedPortDetails.length > 0 && (
|
||||||
</div>
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{share.usedPortDetails.map((item) => (
|
||||||
|
<span
|
||||||
|
key={item.runtimeId}
|
||||||
|
className="text-xs rounded-full px-2 py-1 bg-default-100"
|
||||||
|
>
|
||||||
|
{item.port} / {item.role || "reserved"}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{share.allowedDomains && (
|
||||||
|
<p>允许域名: {share.allowedDomains}</p>
|
||||||
)}
|
)}
|
||||||
{share.allowedDomains && <p>允许域名: {share.allowedDomains}</p>}
|
{share.allowedIps && (
|
||||||
{share.allowedIps && <p>允许API IP: {share.allowedIps}</p>}
|
<p>允许API IP: {share.allowedIps}</p>
|
||||||
<p>过期时间: {share.expiryTime === 0 ? "永久" : new Date(share.expiryTime).toLocaleDateString()}</p>
|
)}
|
||||||
|
<p>
|
||||||
|
过期时间:{" "}
|
||||||
|
{share.expiryTime === 0
|
||||||
|
? "永久"
|
||||||
|
: new Date(share.expiryTime).toLocaleDateString()}
|
||||||
|
</p>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Input readOnly size="sm" value={share.token} />
|
<Input readOnly size="sm" value={share.token} />
|
||||||
<Button size="sm" onPress={() => copyToken(share.token)}>复制</Button>
|
<Button
|
||||||
|
size="sm"
|
||||||
|
onPress={() => copyToken(share.token)}
|
||||||
|
>
|
||||||
|
复制
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -436,7 +505,10 @@ export default function PanelSharingPage() {
|
|||||||
<Card>
|
<Card>
|
||||||
<CardBody>
|
<CardBody>
|
||||||
<div className="mb-4">
|
<div className="mb-4">
|
||||||
<Button color="secondary" onPress={() => setImportNodeOpen(true)}>
|
<Button
|
||||||
|
color="secondary"
|
||||||
|
onPress={() => setImportNodeOpen(true)}
|
||||||
|
>
|
||||||
导入远程节点
|
导入远程节点
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
@@ -446,15 +518,22 @@ export default function PanelSharingPage() {
|
|||||||
) : remoteUsageNodes.length === 0 ? (
|
) : remoteUsageNodes.length === 0 ? (
|
||||||
<div className="text-center py-10 text-gray-500">
|
<div className="text-center py-10 text-gray-500">
|
||||||
<p>暂无远程节点占用记录。</p>
|
<p>暂无远程节点占用记录。</p>
|
||||||
<p className="mt-2">导入远程节点并创建隧道后,这里会显示远端端口占用情况。</p>
|
<p className="mt-2">
|
||||||
|
导入远程节点并创建隧道后,这里会显示远端端口占用情况。
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
{remoteUsageNodes.map((node) => (
|
{remoteUsageNodes.map((node) => (
|
||||||
<Card key={node.nodeId} className="border border-divider shadow-sm">
|
<Card
|
||||||
|
key={node.nodeId}
|
||||||
|
className="border border-divider shadow-sm"
|
||||||
|
>
|
||||||
<CardHeader className="flex justify-between">
|
<CardHeader className="flex justify-between">
|
||||||
<h3 className="font-bold">{node.nodeName}</h3>
|
<h3 className="font-bold">{node.nodeName}</h3>
|
||||||
<span className="text-xs text-default-500">绑定 {node.activeBindingNum || 0}</span>
|
<span className="text-xs text-default-500">
|
||||||
|
绑定 {node.activeBindingNum || 0}
|
||||||
|
</span>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardBody className="text-sm space-y-2">
|
<CardBody className="text-sm space-y-2">
|
||||||
{node.syncError && (
|
{node.syncError && (
|
||||||
@@ -470,18 +549,40 @@ export default function PanelSharingPage() {
|
|||||||
)}
|
)}
|
||||||
{node.remoteUrl && <p>远程地址: {node.remoteUrl}</p>}
|
{node.remoteUrl && <p>远程地址: {node.remoteUrl}</p>}
|
||||||
<p>共享ID: {node.shareId || "-"}</p>
|
<p>共享ID: {node.shareId || "-"}</p>
|
||||||
<p>端口范围: {node.portRangeStart > 0 && node.portRangeEnd > 0 ? `${node.portRangeStart} - ${node.portRangeEnd}` : "-"}</p>
|
<p>
|
||||||
<p>共享流量: {node.maxBandwidth > 0 ? `${formatFlowGB(node.currentFlow || 0)} / ${formatFlowGB(node.maxBandwidth)}` : `${formatFlowGB(node.currentFlow || 0)} / 不限制`}</p>
|
端口范围:{" "}
|
||||||
<p>远端占用端口: {node.usedPorts && node.usedPorts.length > 0 ? node.usedPorts.join(", ") : "暂无"}</p>
|
{node.portRangeStart > 0 && node.portRangeEnd > 0
|
||||||
|
? `${node.portRangeStart} - ${node.portRangeEnd}`
|
||||||
|
: "-"}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
共享流量:{" "}
|
||||||
|
{node.maxBandwidth > 0
|
||||||
|
? `${formatFlowGB(node.currentFlow || 0)} / ${formatFlowGB(node.maxBandwidth)}`
|
||||||
|
: `${formatFlowGB(node.currentFlow || 0)} / 不限制`}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
远端占用端口:{" "}
|
||||||
|
{node.usedPorts && node.usedPorts.length > 0
|
||||||
|
? node.usedPorts.join(", ")
|
||||||
|
: "暂无"}
|
||||||
|
</p>
|
||||||
{node.bindings && node.bindings.length > 0 && (
|
{node.bindings && node.bindings.length > 0 && (
|
||||||
<div className="space-y-1 pt-1">
|
<div className="space-y-1 pt-1">
|
||||||
{node.bindings.map((binding) => (
|
{node.bindings.map((binding) => (
|
||||||
<p key={binding.bindingId} className="text-xs text-default-600">
|
<p
|
||||||
隧道 {binding.tunnelName || `#${binding.tunnelId}`}
|
key={binding.bindingId}
|
||||||
|
className="text-xs text-default-600"
|
||||||
|
>
|
||||||
|
隧道{" "}
|
||||||
|
{binding.tunnelName || `#${binding.tunnelId}`}
|
||||||
{" · "}
|
{" · "}
|
||||||
端口 {binding.allocatedPort}
|
端口 {binding.allocatedPort}
|
||||||
{" · "}
|
{" · "}
|
||||||
{formatChainType(binding.chainType, binding.hopInx)}
|
{formatChainType(
|
||||||
|
binding.chainType,
|
||||||
|
binding.hopInx,
|
||||||
|
)}
|
||||||
</p>
|
</p>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -505,13 +606,17 @@ export default function PanelSharingPage() {
|
|||||||
label="名称"
|
label="名称"
|
||||||
placeholder="备注名称"
|
placeholder="备注名称"
|
||||||
value={shareForm.name}
|
value={shareForm.name}
|
||||||
onChange={(e) => setShareForm({ ...shareForm, name: e.target.value })}
|
onChange={(e) =>
|
||||||
|
setShareForm({ ...shareForm, name: e.target.value })
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<Select
|
<Select
|
||||||
label="选择节点"
|
label="选择节点"
|
||||||
placeholder="选择要分享的本地节点"
|
placeholder="选择要分享的本地节点"
|
||||||
selectedKeys={shareForm.nodeId ? [shareForm.nodeId] : []}
|
selectedKeys={shareForm.nodeId ? [shareForm.nodeId] : []}
|
||||||
onChange={(e) => setShareForm({ ...shareForm, nodeId: e.target.value })}
|
onChange={(e) =>
|
||||||
|
setShareForm({ ...shareForm, nodeId: e.target.value })
|
||||||
|
}
|
||||||
>
|
>
|
||||||
{nodes.map((node) => (
|
{nodes.map((node) => (
|
||||||
<SelectItem key={node.id} textValue={node.name}>
|
<SelectItem key={node.id} textValue={node.name}>
|
||||||
@@ -524,47 +629,73 @@ export default function PanelSharingPage() {
|
|||||||
label="起始端口"
|
label="起始端口"
|
||||||
type="number"
|
type="number"
|
||||||
value={shareForm.portRangeStart.toString()}
|
value={shareForm.portRangeStart.toString()}
|
||||||
onChange={(e) => setShareForm({ ...shareForm, portRangeStart: parseInt(e.target.value) })}
|
onChange={(e) =>
|
||||||
|
setShareForm({
|
||||||
|
...shareForm,
|
||||||
|
portRangeStart: parseInt(e.target.value),
|
||||||
|
})
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<Input
|
<Input
|
||||||
label="结束端口"
|
label="结束端口"
|
||||||
type="number"
|
type="number"
|
||||||
value={shareForm.portRangeEnd.toString()}
|
value={shareForm.portRangeEnd.toString()}
|
||||||
onChange={(e) => setShareForm({ ...shareForm, portRangeEnd: parseInt(e.target.value) })}
|
onChange={(e) =>
|
||||||
|
setShareForm({
|
||||||
|
...shareForm,
|
||||||
|
portRangeEnd: parseInt(e.target.value),
|
||||||
|
})
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<Input
|
<Input
|
||||||
|
description="0 表示永久"
|
||||||
label="有效期 (天)"
|
label="有效期 (天)"
|
||||||
type="number"
|
type="number"
|
||||||
description="0 表示永久"
|
|
||||||
value={shareForm.expiryDays.toString()}
|
value={shareForm.expiryDays.toString()}
|
||||||
onChange={(e) => setShareForm({ ...shareForm, expiryDays: parseInt(e.target.value) })}
|
onChange={(e) =>
|
||||||
|
setShareForm({
|
||||||
|
...shareForm,
|
||||||
|
expiryDays: parseInt(e.target.value),
|
||||||
|
})
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<Input
|
<Input
|
||||||
|
description="0 表示不限流量"
|
||||||
label="流量上限 (GB)"
|
label="流量上限 (GB)"
|
||||||
type="number"
|
type="number"
|
||||||
description="0 表示不限流量"
|
|
||||||
value={shareForm.maxBandwidth.toString()}
|
value={shareForm.maxBandwidth.toString()}
|
||||||
onChange={(e) => setShareForm({ ...shareForm, maxBandwidth: parseInt(e.target.value, 10) || 0 })}
|
onChange={(e) =>
|
||||||
|
setShareForm({
|
||||||
|
...shareForm,
|
||||||
|
maxBandwidth: parseInt(e.target.value, 10) || 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<Input
|
<Input
|
||||||
|
description="限制使用此Token的来源面板域名,多个域名用逗号分隔,留空不限制"
|
||||||
label="允许的域名 (可选)"
|
label="允许的域名 (可选)"
|
||||||
placeholder="example.com, panel.test.com"
|
placeholder="example.com, panel.test.com"
|
||||||
description="限制使用此Token的来源面板域名,多个域名用逗号分隔,留空不限制"
|
|
||||||
value={shareForm.allowedDomains}
|
value={shareForm.allowedDomains}
|
||||||
onChange={(e) => setShareForm({ ...shareForm, allowedDomains: e.target.value })}
|
onChange={(e) =>
|
||||||
|
setShareForm({ ...shareForm, allowedDomains: e.target.value })
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<Input
|
<Input
|
||||||
|
description="仅白名单IP可导入此分享,支持IPv4/IPv6/CIDR,多个用逗号分隔"
|
||||||
label="允许的API IP (可选)"
|
label="允许的API IP (可选)"
|
||||||
placeholder="203.0.113.10, 2001:db8::10, 198.51.100.0/24"
|
placeholder="203.0.113.10, 2001:db8::10, 198.51.100.0/24"
|
||||||
description="仅白名单IP可导入此分享,支持IPv4/IPv6/CIDR,多个用逗号分隔"
|
|
||||||
value={shareForm.allowedIps}
|
value={shareForm.allowedIps}
|
||||||
onChange={(e) => setShareForm({ ...shareForm, allowedIps: e.target.value })}
|
onChange={(e) =>
|
||||||
|
setShareForm({ ...shareForm, allowedIps: e.target.value })
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</ModalBody>
|
</ModalBody>
|
||||||
<ModalFooter>
|
<ModalFooter>
|
||||||
<Button onPress={() => setCreateShareOpen(false)}>取消</Button>
|
<Button onPress={() => setCreateShareOpen(false)}>取消</Button>
|
||||||
<Button color="primary" onPress={handleCreateShare}>创建</Button>
|
<Button color="primary" onPress={handleCreateShare}>
|
||||||
|
创建
|
||||||
|
</Button>
|
||||||
</ModalFooter>
|
</ModalFooter>
|
||||||
</ModalContent>
|
</ModalContent>
|
||||||
</Modal>
|
</Modal>
|
||||||
@@ -578,54 +709,88 @@ export default function PanelSharingPage() {
|
|||||||
label="名称"
|
label="名称"
|
||||||
placeholder="备注名称"
|
placeholder="备注名称"
|
||||||
value={editForm.name}
|
value={editForm.name}
|
||||||
onChange={(e) => setEditForm({ ...editForm, name: e.target.value })}
|
onChange={(e) =>
|
||||||
|
setEditForm({ ...editForm, name: e.target.value })
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<div className="flex gap-4">
|
<div className="flex gap-4">
|
||||||
<Input
|
<Input
|
||||||
label="起始端口"
|
label="起始端口"
|
||||||
type="number"
|
type="number"
|
||||||
value={editForm.portRangeStart.toString()}
|
value={editForm.portRangeStart.toString()}
|
||||||
onChange={(e) => setEditForm({ ...editForm, portRangeStart: parseInt(e.target.value) || 0 })}
|
onChange={(e) =>
|
||||||
|
setEditForm({
|
||||||
|
...editForm,
|
||||||
|
portRangeStart: parseInt(e.target.value) || 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<Input
|
<Input
|
||||||
label="结束端口"
|
label="结束端口"
|
||||||
type="number"
|
type="number"
|
||||||
value={editForm.portRangeEnd.toString()}
|
value={editForm.portRangeEnd.toString()}
|
||||||
onChange={(e) => setEditForm({ ...editForm, portRangeEnd: parseInt(e.target.value) || 0 })}
|
onChange={(e) =>
|
||||||
|
setEditForm({
|
||||||
|
...editForm,
|
||||||
|
portRangeEnd: parseInt(e.target.value) || 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<Input
|
<Input
|
||||||
|
description="0 表示不限流量"
|
||||||
label="流量上限 (GB)"
|
label="流量上限 (GB)"
|
||||||
type="number"
|
type="number"
|
||||||
description="0 表示不限流量"
|
|
||||||
value={editForm.maxBandwidth.toString()}
|
value={editForm.maxBandwidth.toString()}
|
||||||
onChange={(e) => setEditForm({ ...editForm, maxBandwidth: parseInt(e.target.value, 10) || 0 })}
|
onChange={(e) =>
|
||||||
|
setEditForm({
|
||||||
|
...editForm,
|
||||||
|
maxBandwidth: parseInt(e.target.value, 10) || 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<Input
|
<Input
|
||||||
|
description="留空或清除表示永久有效"
|
||||||
label="过期时间"
|
label="过期时间"
|
||||||
type="datetime-local"
|
type="datetime-local"
|
||||||
description="留空或清除表示永久有效"
|
value={
|
||||||
value={editForm.expiryTime > 0 ? new Date(editForm.expiryTime).toISOString().slice(0, 16) : ""}
|
editForm.expiryTime > 0
|
||||||
onChange={(e) => setEditForm({ ...editForm, expiryTime: e.target.value ? new Date(e.target.value).getTime() : 0 })}
|
? new Date(editForm.expiryTime).toISOString().slice(0, 16)
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
onChange={(e) =>
|
||||||
|
setEditForm({
|
||||||
|
...editForm,
|
||||||
|
expiryTime: e.target.value
|
||||||
|
? new Date(e.target.value).getTime()
|
||||||
|
: 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<Input
|
<Input
|
||||||
|
description="限制使用此Token的来源面板域名,多个域名用逗号分隔,留空不限制"
|
||||||
label="允许的域名 (可选)"
|
label="允许的域名 (可选)"
|
||||||
placeholder="example.com, panel.test.com"
|
placeholder="example.com, panel.test.com"
|
||||||
description="限制使用此Token的来源面板域名,多个域名用逗号分隔,留空不限制"
|
|
||||||
value={editForm.allowedDomains}
|
value={editForm.allowedDomains}
|
||||||
onChange={(e) => setEditForm({ ...editForm, allowedDomains: e.target.value })}
|
onChange={(e) =>
|
||||||
|
setEditForm({ ...editForm, allowedDomains: e.target.value })
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<Input
|
<Input
|
||||||
|
description="仅白名单IP可导入此分享,支持IPv4/IPv6/CIDR,多个用逗号分隔"
|
||||||
label="允许的API IP (可选)"
|
label="允许的API IP (可选)"
|
||||||
placeholder="203.0.113.10, 2001:db8::10, 198.51.100.0/24"
|
placeholder="203.0.113.10, 2001:db8::10, 198.51.100.0/24"
|
||||||
description="仅白名单IP可导入此分享,支持IPv4/IPv6/CIDR,多个用逗号分隔"
|
|
||||||
value={editForm.allowedIps}
|
value={editForm.allowedIps}
|
||||||
onChange={(e) => setEditForm({ ...editForm, allowedIps: e.target.value })}
|
onChange={(e) =>
|
||||||
|
setEditForm({ ...editForm, allowedIps: e.target.value })
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</ModalBody>
|
</ModalBody>
|
||||||
<ModalFooter>
|
<ModalFooter>
|
||||||
<Button onPress={() => setEditShareOpen(false)}>取消</Button>
|
<Button onPress={() => setEditShareOpen(false)}>取消</Button>
|
||||||
<Button color="primary" onPress={handleEditShare}>保存</Button>
|
<Button color="primary" onPress={handleEditShare}>
|
||||||
|
保存
|
||||||
|
</Button>
|
||||||
</ModalFooter>
|
</ModalFooter>
|
||||||
</ModalContent>
|
</ModalContent>
|
||||||
</Modal>
|
</Modal>
|
||||||
@@ -639,18 +804,24 @@ export default function PanelSharingPage() {
|
|||||||
label="远程面板地址"
|
label="远程面板地址"
|
||||||
placeholder="http://panel.example.com:8088"
|
placeholder="http://panel.example.com:8088"
|
||||||
value={importForm.remoteUrl}
|
value={importForm.remoteUrl}
|
||||||
onChange={(e) => setImportForm({ ...importForm, remoteUrl: e.target.value })}
|
onChange={(e) =>
|
||||||
|
setImportForm({ ...importForm, remoteUrl: e.target.value })
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<Input
|
<Input
|
||||||
label="Token"
|
label="Token"
|
||||||
placeholder="Bearer Token"
|
placeholder="Bearer Token"
|
||||||
value={importForm.token}
|
value={importForm.token}
|
||||||
onChange={(e) => setImportForm({ ...importForm, token: e.target.value })}
|
onChange={(e) =>
|
||||||
|
setImportForm({ ...importForm, token: e.target.value })
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</ModalBody>
|
</ModalBody>
|
||||||
<ModalFooter>
|
<ModalFooter>
|
||||||
<Button onPress={() => setImportNodeOpen(false)}>取消</Button>
|
<Button onPress={() => setImportNodeOpen(false)}>取消</Button>
|
||||||
<Button color="secondary" onPress={handleImportNode}>导入</Button>
|
<Button color="secondary" onPress={handleImportNode}>
|
||||||
|
导入
|
||||||
|
</Button>
|
||||||
</ModalFooter>
|
</ModalFooter>
|
||||||
</ModalContent>
|
</ModalContent>
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ interface Tunnel {
|
|||||||
protocol?: string;
|
protocol?: string;
|
||||||
flow: number; // 1: 单向, 2: 双向
|
flow: number; // 1: 单向, 2: 双向
|
||||||
trafficRatio: number;
|
trafficRatio: number;
|
||||||
|
ipPreference?: string;
|
||||||
status: number;
|
status: number;
|
||||||
createdTime: string;
|
createdTime: string;
|
||||||
}
|
}
|
||||||
@@ -87,6 +88,7 @@ interface TunnelForm {
|
|||||||
flow: number;
|
flow: number;
|
||||||
trafficRatio: number;
|
trafficRatio: number;
|
||||||
inIp: string; // 入口IP
|
inIp: string; // 入口IP
|
||||||
|
ipPreference: string;
|
||||||
status: number;
|
status: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,6 +143,7 @@ export default function TunnelPage() {
|
|||||||
flow: 1,
|
flow: 1,
|
||||||
trafficRatio: 1.0,
|
trafficRatio: 1.0,
|
||||||
inIp: "",
|
inIp: "",
|
||||||
|
ipPreference: "",
|
||||||
status: 1,
|
status: 1,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -301,6 +304,7 @@ export default function TunnelPage() {
|
|||||||
flow: 1,
|
flow: 1,
|
||||||
trafficRatio: 1.0,
|
trafficRatio: 1.0,
|
||||||
inIp: "",
|
inIp: "",
|
||||||
|
ipPreference: "",
|
||||||
status: 1,
|
status: 1,
|
||||||
});
|
});
|
||||||
setErrors({});
|
setErrors({});
|
||||||
@@ -313,21 +317,22 @@ export default function TunnelPage() {
|
|||||||
|
|
||||||
// 直接使用列表数据,getAllTunnels 已经包含完整的节点信息
|
// 直接使用列表数据,getAllTunnels 已经包含完整的节点信息
|
||||||
setForm({
|
setForm({
|
||||||
id: tunnel.id,
|
id: tunnel.id,
|
||||||
name: tunnel.name,
|
name: tunnel.name,
|
||||||
type: tunnel.type,
|
type: tunnel.type,
|
||||||
inNodeId: tunnel.inNodeId || [],
|
inNodeId: tunnel.inNodeId || [],
|
||||||
outNodeId: tunnel.outNodeId || [],
|
outNodeId: tunnel.outNodeId || [],
|
||||||
chainNodes: tunnel.chainNodes || [],
|
chainNodes: tunnel.chainNodes || [],
|
||||||
flow: tunnel.flow,
|
flow: tunnel.flow,
|
||||||
trafficRatio: tunnel.trafficRatio,
|
trafficRatio: tunnel.trafficRatio,
|
||||||
inIp: tunnel.inIp
|
inIp: tunnel.inIp
|
||||||
? tunnel.inIp
|
? tunnel.inIp
|
||||||
.split(",")
|
.split(",")
|
||||||
.map((ip) => ip.trim())
|
.map((ip: string) => ip.trim())
|
||||||
.join("\n")
|
.join("\n")
|
||||||
: "",
|
: "",
|
||||||
status: tunnel.status,
|
ipPreference: tunnel.ipPreference || "",
|
||||||
|
status: tunnel.status,
|
||||||
});
|
});
|
||||||
setErrors({});
|
setErrors({});
|
||||||
setModalOpen(true);
|
setModalOpen(true);
|
||||||
@@ -1045,7 +1050,7 @@ export default function TunnelPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 流量配置 */}
|
{/* 流量配置 */}
|
||||||
<div className="grid grid-cols-2 gap-2">
|
<div className={`grid gap-2 ${tunnel.type === 2 && tunnel.ipPreference ? "grid-cols-3" : "grid-cols-2"}`}>
|
||||||
<div className="text-center p-1.5 bg-default-50 dark:bg-default-100/30 rounded">
|
<div className="text-center p-1.5 bg-default-50 dark:bg-default-100/30 rounded">
|
||||||
<div className="text-xs text-default-500">
|
<div className="text-xs text-default-500">
|
||||||
流量计算
|
流量计算
|
||||||
@@ -1062,6 +1067,16 @@ export default function TunnelPage() {
|
|||||||
{tunnel.trafficRatio}x
|
{tunnel.trafficRatio}x
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{tunnel.type === 2 && tunnel.ipPreference && (
|
||||||
|
<div className="text-center p-1.5 bg-default-50 dark:bg-default-100/30 rounded">
|
||||||
|
<div className="text-xs text-default-500">
|
||||||
|
连接偏好
|
||||||
|
</div>
|
||||||
|
<div className="text-sm font-semibold text-foreground mt-0.5">
|
||||||
|
{tunnel.ipPreference === "v4" ? "IPv4" : "IPv6"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1293,6 +1308,27 @@ export default function TunnelPage() {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{form.type === 2 && (
|
||||||
|
<Select
|
||||||
|
description="当节点同时拥有IPv4和IPv6地址时,选择隧道连接使用的地址类型"
|
||||||
|
label="隧道连接地址偏好"
|
||||||
|
selectedKeys={[form.ipPreference || ""]}
|
||||||
|
variant="bordered"
|
||||||
|
onSelectionChange={(keys) => {
|
||||||
|
const selectedKey = Array.from(keys)[0] as string;
|
||||||
|
|
||||||
|
setForm((prev) => ({
|
||||||
|
...prev,
|
||||||
|
ipPreference: selectedKey || "",
|
||||||
|
}));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SelectItem key="">自动选择</SelectItem>
|
||||||
|
<SelectItem key="v4">优先IPv4</SelectItem>
|
||||||
|
<SelectItem key="v6">优先IPv6</SelectItem>
|
||||||
|
</Select>
|
||||||
|
)}
|
||||||
|
|
||||||
<Divider />
|
<Divider />
|
||||||
<h3 className="text-lg font-semibold">入口配置</h3>
|
<h3 className="text-lg font-semibold">入口配置</h3>
|
||||||
|
|
||||||
|
|||||||
@@ -46,6 +46,28 @@ html, body {
|
|||||||
--safe-area-bottom: env(safe-area-inset-bottom, 0px);
|
--safe-area-bottom: env(safe-area-inset-bottom, 0px);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[data-slot="input-wrapper"] {
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-slot="input-wrapper"]:focus-within:not([data-invalid="true"]),
|
||||||
|
[data-slot="input-wrapper"][data-focus="true"]:not([data-invalid="true"]),
|
||||||
|
[data-slot="input-wrapper"][data-focused="true"]:not([data-invalid="true"]),
|
||||||
|
button[data-slot="trigger"][data-focus="true"]:not([data-invalid="true"]),
|
||||||
|
button[data-slot="trigger"][data-open="true"]:not([data-invalid="true"]) {
|
||||||
|
border-color: var(--heroui-default-200, #e5e7eb) !important;
|
||||||
|
outline: none !important;
|
||||||
|
outline-offset: 0 !important;
|
||||||
|
box-shadow: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-slot="input-wrapper"] input:focus,
|
||||||
|
[data-slot="input-wrapper"] textarea:focus {
|
||||||
|
outline: none !important;
|
||||||
|
box-shadow: none !important;
|
||||||
|
border-color: transparent !important;
|
||||||
|
}
|
||||||
|
|
||||||
.safe-top {
|
.safe-top {
|
||||||
padding-top: var(--safe-area-top);
|
padding-top: var(--safe-area-top);
|
||||||
}
|
}
|
||||||
@@ -85,4 +107,4 @@ html, body {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@config "../../tailwind.config.js"
|
@config "../../tailwind.config.js"
|
||||||
|
|||||||
Reference in New Issue
Block a user