Compare commits
99 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8901581d0c | ||
|
|
c6bab83e24 | ||
|
|
9cd74b43d0 | ||
|
|
2d8cc8ebe5 | ||
| 58bb324d82 | |||
| bed78a36d0 | |||
| e4999abf47 | |||
| 937536e422 | |||
| 838bde28f0 | |||
| 743b91f3bf | |||
| 5a03d9e1f1 | |||
| dcfd2f4466 | |||
| f13dc2451c | |||
| 1c71a7633b | |||
| b7a1a249a4 | |||
| 5cee8daabc | |||
|
|
a9ca714b24 | ||
|
|
d6627a292d | ||
| e0d88e9ad7 | |||
|
|
ba9edd3c02 | ||
|
|
e40d079f7a | ||
|
|
8ce5b149f7 | ||
|
|
0a41e10793 | ||
|
|
3386b0fcb6 | ||
|
|
98a5525e6d | ||
|
|
5c8020d5fb | ||
|
|
a2773aa1a7 | ||
|
|
9cc2fa8076 | ||
|
|
1890cad8d9 | ||
|
|
11572f132c | ||
|
|
9f13b0d4e9 | ||
|
|
7cddb7b3e7 | ||
|
|
d1058f9e89 | ||
|
|
06dfcfaff3 | ||
|
|
67c41cde5c | ||
|
|
4500f48d4c | ||
|
|
381c6911af | ||
|
|
42445d18eb | ||
|
|
d3969079a5 | ||
|
|
6496d56e0e | ||
|
|
23fa089608 | ||
| 7d9ad44856 | |||
| 6670b3ea35 | |||
| 498d20e3fe | |||
| ad727aff3a | |||
| cfcfc3839c | |||
| 955bf2b8dd | |||
| a8f034a112 | |||
| 294718dd7e | |||
| 27f958b981 | |||
| 7c572ad20e | |||
| 381e751c56 | |||
| 3fe3686e29 | |||
| 431780774f | |||
| cb0f8df0d8 | |||
| 1c190330d9 | |||
| 24b3b47ccd | |||
| 47603b0574 | |||
| d09104f89b | |||
| 98f633ebde | |||
| ec4fb51aaa | |||
| ad07527909 | |||
| de206bf85a | |||
| c1f6e0bdcf | |||
| cbd3ba0a4f | |||
| 65ad881c79 | |||
| 007c8ed440 | |||
| 02f8c521c2 | |||
| 78982a26b0 | |||
| 458bb35005 | |||
| d6bde71c94 | |||
| 08262654d6 | |||
| ae6cb9d422 | |||
| f2720a3d15 | |||
| 2f98e1ac7d | |||
| d2ca3fa2b9 | |||
| 6de57a284d | |||
| 46f912423e | |||
| 5836393f1a | |||
| 2aa4abb88e | |||
| 183215f410 | |||
| 73fd44ce9c | |||
| 0dfd14ab5c | |||
| 5c2727e342 | |||
| 0389437fdb | |||
| d63ff7169e | |||
| 790c004f6e | |||
| f4de49681d | |||
| 7475957195 | |||
| f58cab4e56 | |||
| f46741a84b | |||
| 82c1a6a266 | |||
| 3f7b72a0aa | |||
| 0c00a9ffdc | |||
|
|
76fde41e48 | ||
|
|
cfdb890cf0 | ||
|
|
13a94f666c | ||
|
|
afcc54e039 | ||
| 913e9c304b |
208
.gitea/workflows/Create Release.yml
Normal file
208
.gitea/workflows/Create Release.yml
Normal file
@@ -0,0 +1,208 @@
|
||||
name: Create Release
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: 'Release version (e.g., v1.0.0)'
|
||||
required: true
|
||||
type: string
|
||||
release_notes:
|
||||
description: 'Release notes (optional)'
|
||||
required: false
|
||||
type: string
|
||||
prerelease:
|
||||
description: 'Is this a pre-release?'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
draft:
|
||||
description: 'Create as draft?'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
jobs:
|
||||
create-release:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Validate version format
|
||||
run: |
|
||||
VERSION="${{ inputs.version }}"
|
||||
if [[ ! $VERSION =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.]+)?$ ]]; then
|
||||
echo "Error: Version must be in format vX.Y.Z or vX.Y.Z-suffix"
|
||||
echo "Examples: v1.0.0, v2.1.3, v1.0.0-beta.1"
|
||||
exit 1
|
||||
fi
|
||||
echo "Version format is valid: $VERSION"
|
||||
|
||||
- name: Check if tag exists
|
||||
id: check_tag
|
||||
run: |
|
||||
if git rev-parse "${{ inputs.version }}" >/dev/null 2>&1; then
|
||||
echo "exists=true" >> $GITHUB_OUTPUT
|
||||
echo "Tag ${{ inputs.version }} already exists"
|
||||
else
|
||||
echo "exists=false" >> $GITHUB_OUTPUT
|
||||
echo "Tag ${{ inputs.version }} does not exist, will create it"
|
||||
fi
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.24'
|
||||
cache: true
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: web/package-lock.json
|
||||
|
||||
- name: Build frontend
|
||||
run: |
|
||||
cd web
|
||||
npm ci
|
||||
npm run build
|
||||
mkdir -p ../internal/server/app/dist
|
||||
cp -r dist/* ../internal/server/app/dist/
|
||||
cd ..
|
||||
echo "Frontend build completed"
|
||||
ls -la internal/server/app/dist/
|
||||
|
||||
- name: Build all platforms
|
||||
run: |
|
||||
mkdir -p dist
|
||||
VERSION="${{ inputs.version }}"
|
||||
LDFLAGS="-s -w -X main.Version=${VERSION}"
|
||||
|
||||
echo "Building for all platforms with version ${VERSION}..."
|
||||
|
||||
# Linux amd64
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="${LDFLAGS}" \
|
||||
-o dist/gotunnel-server-linux-amd64 ./cmd/server
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="${LDFLAGS}" \
|
||||
-o dist/gotunnel-client-linux-amd64 ./cmd/client
|
||||
|
||||
# Linux arm64
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="${LDFLAGS}" \
|
||||
-o dist/gotunnel-server-linux-arm64 ./cmd/server
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="${LDFLAGS}" \
|
||||
-o dist/gotunnel-client-linux-arm64 ./cmd/client
|
||||
|
||||
# Darwin amd64
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags="${LDFLAGS}" \
|
||||
-o dist/gotunnel-server-darwin-amd64 ./cmd/server
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags="${LDFLAGS}" \
|
||||
-o dist/gotunnel-client-darwin-amd64 ./cmd/client
|
||||
|
||||
# Darwin arm64
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="${LDFLAGS}" \
|
||||
-o dist/gotunnel-server-darwin-arm64 ./cmd/server
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="${LDFLAGS}" \
|
||||
-o dist/gotunnel-client-darwin-arm64 ./cmd/client
|
||||
|
||||
# Windows amd64
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="${LDFLAGS}" \
|
||||
-o dist/gotunnel-server-windows-amd64.exe ./cmd/server
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="${LDFLAGS}" \
|
||||
-o dist/gotunnel-client-windows-amd64.exe ./cmd/client
|
||||
|
||||
- name: Generate checksums
|
||||
run: |
|
||||
cd dist
|
||||
sha256sum * > SHA256SUMS
|
||||
cat SHA256SUMS
|
||||
cd ..
|
||||
|
||||
- name: Create compressed archives
|
||||
run: |
|
||||
cd dist
|
||||
VERSION="${{ inputs.version }}"
|
||||
|
||||
# Linux
|
||||
tar -czf gotunnel-server-${VERSION}-linux-amd64.tar.gz gotunnel-server-linux-amd64
|
||||
tar -czf gotunnel-client-${VERSION}-linux-amd64.tar.gz gotunnel-client-linux-amd64
|
||||
tar -czf gotunnel-server-${VERSION}-linux-arm64.tar.gz gotunnel-server-linux-arm64
|
||||
tar -czf gotunnel-client-${VERSION}-linux-arm64.tar.gz gotunnel-client-linux-arm64
|
||||
|
||||
# Darwin
|
||||
tar -czf gotunnel-server-${VERSION}-darwin-amd64.tar.gz gotunnel-server-darwin-amd64
|
||||
tar -czf gotunnel-client-${VERSION}-darwin-amd64.tar.gz gotunnel-client-darwin-amd64
|
||||
tar -czf gotunnel-server-${VERSION}-darwin-arm64.tar.gz gotunnel-server-darwin-arm64
|
||||
tar -czf gotunnel-client-${VERSION}-darwin-arm64.tar.gz gotunnel-client-darwin-arm64
|
||||
|
||||
# Windows
|
||||
zip gotunnel-server-${VERSION}-windows-amd64.zip gotunnel-server-windows-amd64.exe
|
||||
zip gotunnel-client-${VERSION}-windows-amd64.zip gotunnel-client-windows-amd64.exe
|
||||
|
||||
# Clean up raw binaries, keep only archives and checksums
|
||||
find . -type f ! -name "*.tar.gz" ! -name "*.zip" ! -name "SHA256SUMS" -delete
|
||||
|
||||
cd ..
|
||||
|
||||
- name: List release assets
|
||||
run: |
|
||||
echo "Release assets to be uploaded:"
|
||||
ls -lah dist/
|
||||
|
||||
- name: Create tag
|
||||
if: steps.check_tag.outputs.exists == 'false'
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git tag -a ${{ inputs.version }} -m "Release ${{ inputs.version }}"
|
||||
git push origin ${{ inputs.version }}
|
||||
|
||||
- name: Prepare release notes
|
||||
id: release_notes
|
||||
run: |
|
||||
if [ -n "${{ inputs.release_notes }}" ]; then
|
||||
# 使用用户输入的 release notes
|
||||
echo "${{ inputs.release_notes }}" > release_notes.md
|
||||
else
|
||||
# 使用最近一次 commit message 作为 release notes
|
||||
echo "## Release ${{ inputs.version }}" > release_notes.md
|
||||
echo "" >> release_notes.md
|
||||
echo "### Changes" >> release_notes.md
|
||||
echo "" >> release_notes.md
|
||||
# 获取最近一次 commit 的完整 message
|
||||
git log -1 --pretty=format:"%B" >> release_notes.md
|
||||
echo "" >> release_notes.md
|
||||
echo "" >> release_notes.md
|
||||
echo "---" >> release_notes.md
|
||||
echo "" >> release_notes.md
|
||||
echo "### Assets" >> release_notes.md
|
||||
echo "" >> release_notes.md
|
||||
echo "- **Linux (amd64/arm64)**: \`.tar.gz\` files" >> release_notes.md
|
||||
echo "- **macOS (amd64/arm64)**: \`.tar.gz\` files" >> release_notes.md
|
||||
echo "- **Windows (amd64)**: \`.zip\` files" >> release_notes.md
|
||||
echo "" >> release_notes.md
|
||||
echo "Verify downloads with \`SHA256SUMS\`" >> release_notes.md
|
||||
fi
|
||||
echo "=== Release Notes ==="
|
||||
cat release_notes.md
|
||||
|
||||
- name: Create Release
|
||||
uses: akkuman/gitea-release-action@v1
|
||||
with:
|
||||
tag_name: ${{ inputs.version }}
|
||||
name: Release ${{ inputs.version }}
|
||||
body_path: release_notes.md
|
||||
files: |-
|
||||
dist/*.tar.gz
|
||||
dist/*.zip
|
||||
dist/SHA256SUMS
|
||||
draft: ${{ inputs.draft }}
|
||||
prerelease: ${{ inputs.prerelease }}
|
||||
token: ${{ secrets.ACCOUNT_TOKEN }}
|
||||
|
||||
- name: Release created successfully
|
||||
run: |
|
||||
echo "✅ Release ${{ inputs.version }} created successfully!"
|
||||
echo "🔗 View it at: ${{ github.server_url }}/${{ github.repository }}/releases/tag/${{ inputs.version }}"
|
||||
@@ -9,17 +9,28 @@ on:
|
||||
- '.gitea/workflows/**'
|
||||
|
||||
jobs:
|
||||
# --- 任务 1: 构建前端 ---
|
||||
build-frontend:
|
||||
runs-on: node-latest
|
||||
runs-on: node
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# 直接挂载宿主机的缓存目录
|
||||
- name: Build Frontend
|
||||
run: |
|
||||
cd web
|
||||
npm ci
|
||||
# 使用共享的 node_modules 缓存
|
||||
if [ -d /data/cache/node_modules_cache ]; then
|
||||
echo "Restoring node_modules from cache..."
|
||||
cp -r /data/cache/node_modules_cache/node_modules . 2>/dev/null || true
|
||||
fi
|
||||
|
||||
npm ci --prefer-offline --no-audit
|
||||
|
||||
# 保存缓存
|
||||
mkdir -p /data/cache/node_modules_cache
|
||||
cp -r node_modules /data/cache/node_modules_cache/ 2>/dev/null || true
|
||||
|
||||
npm run build
|
||||
|
||||
- name: Upload Frontend Artifact
|
||||
@@ -29,35 +40,27 @@ jobs:
|
||||
path: web/dist
|
||||
retention-days: 1
|
||||
|
||||
# --- 任务 2: 构建多平台二进制文件 ---
|
||||
build-binaries:
|
||||
needs: build-frontend
|
||||
runs-on: golang-latest
|
||||
runs-on: golang
|
||||
strategy:
|
||||
fail-fast: false # 即使某个平台失败,也继续构建其他平台
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
# Linux 平台
|
||||
- { goos: linux, goarch: amd64, target: server, upx: true }
|
||||
- { goos: linux, goarch: amd64, target: client, upx: true }
|
||||
- { goos: linux, goarch: arm64, target: server, upx: true } # ARMv8 64-bit
|
||||
- { goos: linux, goarch: arm64, target: server, upx: true }
|
||||
- { goos: linux, goarch: arm64, target: client, upx: true }
|
||||
# 针对 ARMv8 (v8l) 32位模式,使用 GOARM=7 确保最大兼容性
|
||||
- { goos: linux, goarch: arm, goarm: 7, target: server, upx: true }
|
||||
- { goos: linux, goarch: arm, goarm: 7, target: client, upx: true }
|
||||
|
||||
# Windows 平台
|
||||
- { goos: windows, goarch: amd64, target: server, upx: true }
|
||||
- { goos: windows, goarch: amd64, target: client, upx: true }
|
||||
- { goos: windows, goarch: arm64, target: server, upx: false }
|
||||
|
||||
# Darwin (macOS) 平台
|
||||
- { goos: darwin, goarch: amd64, target: server, upx: false }
|
||||
- { goos: darwin, goarch: arm64, target: server, upx: false }
|
||||
|
||||
|
||||
steps:
|
||||
# 关键步骤:在 checkout 之前安装 Node.js,否则 checkout@v4 会报错
|
||||
- name: Install Node.js & UPX
|
||||
- name: Install Dependencies
|
||||
run: |
|
||||
if command -v apk > /dev/null; then
|
||||
apk add --no-cache nodejs upx
|
||||
@@ -66,16 +69,39 @@ jobs:
|
||||
else
|
||||
echo "Unsupported package manager" && exit 1
|
||||
fi
|
||||
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
|
||||
# 使用挂载卷缓存 Go 模块
|
||||
- name: Setup Go Cache
|
||||
run: |
|
||||
# 创建缓存目录
|
||||
mkdir -p /data/cache/go-pkg-mod
|
||||
mkdir -p /data/cache/go-build-cache
|
||||
mkdir -p ~/go/pkg/mod
|
||||
mkdir -p ~/.cache/go-build
|
||||
|
||||
# 恢复缓存(使用硬链接以节省空间和时间)
|
||||
if [ -d /data/cache/go-pkg-mod ] && [ "$(ls -A /data/cache/go-pkg-mod)" ]; then
|
||||
echo "Restoring Go pkg cache..."
|
||||
cp -al /data/cache/go-pkg-mod/* ~/go/pkg/mod/ 2>/dev/null || true
|
||||
fi
|
||||
|
||||
if [ -d /data/cache/go-build-cache ] && [ "$(ls -A /data/cache/go-build-cache)" ]; then
|
||||
echo "Restoring Go build cache..."
|
||||
cp -al /data/cache/go-build-cache/* ~/.cache/go-build/ 2>/dev/null || true
|
||||
fi
|
||||
|
||||
- name: Download Go dependencies
|
||||
run: go mod download
|
||||
|
||||
- name: Download Frontend Artifact
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: frontend-dist
|
||||
path: internal/server/app/dist
|
||||
|
||||
|
||||
- name: Build Binary
|
||||
env:
|
||||
GOOS: ${{ matrix.goos }}
|
||||
@@ -83,33 +109,37 @@ jobs:
|
||||
GOARM: ${{ matrix.goarm }}
|
||||
CGO_ENABLED: 0
|
||||
run: |
|
||||
# 处理文件名后缀
|
||||
ARM_VAL=""
|
||||
if [ "${{ matrix.goarch }}" = "arm" ]; then
|
||||
ARM_VAL="v${{ matrix.goarm }}"
|
||||
fi
|
||||
[ "${{ matrix.goarch }}" = "arm" ] && ARM_VAL="v${{ matrix.goarm }}"
|
||||
|
||||
EXT=""
|
||||
if [ "${{ matrix.goos }}" = "windows" ]; then
|
||||
EXT=".exe"
|
||||
fi
|
||||
[ "${{ matrix.goos }}" = "windows" ] && EXT=".exe"
|
||||
|
||||
FILENAME="${{ matrix.target }}-${{ matrix.goos }}-${{ matrix.goarch }}${ARM_VAL}${EXT}"
|
||||
FILENAME="gotunnel-${{ matrix.target }}-${{ matrix.goos }}-${{ matrix.goarch }}${ARM_VAL}${EXT}"
|
||||
|
||||
# 执行编译
|
||||
go build -ldflags="-s -w" -o "${FILENAME}" ./cmd/${{ matrix.target }}
|
||||
go build -trimpath -ldflags="-s -w" -o "${FILENAME}" ./cmd/${{ matrix.target }}
|
||||
|
||||
# 记录文件名供后续步骤使用
|
||||
echo "CURRENT_FILENAME=${FILENAME}" >> $GITHUB_ENV
|
||||
|
||||
|
||||
# 保存 Go 缓存(异步,不阻塞主流程)
|
||||
- name: Save Go Cache
|
||||
if: always()
|
||||
run: |
|
||||
# 只在缓存有更新时保存(使用 rsync 可以更高效)
|
||||
rsync -a --delete ~/go/pkg/mod/ /data/cache/go-pkg-mod/ 2>/dev/null || \
|
||||
cp -r ~/go/pkg/mod/* /data/cache/go-pkg-mod/ 2>/dev/null || true
|
||||
|
||||
rsync -a --delete ~/.cache/go-build/ /data/cache/go-build-cache/ 2>/dev/null || \
|
||||
cp -r ~/.cache/go-build/* /data/cache/go-build-cache/ 2>/dev/null || true
|
||||
|
||||
- name: Run UPX Compression
|
||||
if: matrix.upx == true
|
||||
run: |
|
||||
# 尝试压缩,即使失败也不中断工作流(某些架构不支持 UPX)
|
||||
upx -9 "${{ env.CURRENT_FILENAME }}" || echo "UPX skipped for this platform"
|
||||
|
||||
upx --best --lzma "${{ env.CURRENT_FILENAME }}" || echo "UPX skipped for this platform"
|
||||
|
||||
- name: Upload Binary
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: ${{ env.CURRENT_FILENAME }}
|
||||
path: ${{ env.CURRENT_FILENAME }}
|
||||
path: ${{ env.CURRENT_FILENAME }}
|
||||
retention-days: 7
|
||||
117
.github/workflows/build.yml
vendored
Normal file
117
.github/workflows/build.yml
vendored
Normal file
@@ -0,0 +1,117 @@
|
||||
name: CI Build
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
frontend:
|
||||
name: Build frontend
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: npm
|
||||
cache-dependency-path: web/package-lock.json
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: web
|
||||
run: npm ci
|
||||
|
||||
- name: Build frontend
|
||||
working-directory: web
|
||||
run: npm run build
|
||||
|
||||
- name: Upload frontend artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: frontend-dist
|
||||
path: web/dist
|
||||
retention-days: 1
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.goos }}/${{ matrix.goarch }}
|
||||
needs: frontend
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: ubuntu-latest
|
||||
goos: linux
|
||||
goarch: amd64
|
||||
- runner: ubuntu-latest
|
||||
goos: linux
|
||||
goarch: arm64
|
||||
- runner: windows-latest
|
||||
goos: windows
|
||||
goarch: amd64
|
||||
- runner: macos-latest
|
||||
goos: darwin
|
||||
goarch: amd64
|
||||
- runner: macos-latest
|
||||
goos: darwin
|
||||
goarch: arm64
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: Download frontend artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: frontend-dist
|
||||
path: internal/server/app/dist
|
||||
|
||||
- name: Download Go modules
|
||||
run: go mod download
|
||||
|
||||
- name: Build server and client
|
||||
shell: bash
|
||||
env:
|
||||
GOOS: ${{ matrix.goos }}
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
CGO_ENABLED: 0
|
||||
run: |
|
||||
mkdir -p build/${GOOS}_${GOARCH}
|
||||
EXT=""
|
||||
if [ "$GOOS" = "windows" ]; then
|
||||
EXT=".exe"
|
||||
fi
|
||||
|
||||
BUILD_TIME="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
|
||||
GIT_COMMIT="${GITHUB_SHA::7}"
|
||||
VERSION="${GITHUB_REF_NAME}"
|
||||
if [ "${GITHUB_REF_TYPE}" != "tag" ]; then
|
||||
VERSION="${GITHUB_SHA::7}"
|
||||
fi
|
||||
|
||||
LDFLAGS="-s -w -X 'main.Version=${VERSION}' -X 'main.BuildTime=${BUILD_TIME}' -X 'main.GitCommit=${GIT_COMMIT}'"
|
||||
|
||||
go build -trimpath -ldflags "$LDFLAGS" -o "build/${GOOS}_${GOARCH}/server${EXT}" ./cmd/server
|
||||
go build -trimpath -ldflags "$LDFLAGS" -o "build/${GOOS}_${GOARCH}/client${EXT}" ./cmd/client
|
||||
|
||||
- name: Upload binaries artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: gotunnel-${{ matrix.goos }}-${{ matrix.goarch }}
|
||||
path: build/${{ matrix.goos }}_${{ matrix.goarch }}/
|
||||
retention-days: 7
|
||||
214
.github/workflows/release.yml
vendored
Normal file
214
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,214 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag to publish, e.g. v1.2.3'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.event.inputs.tag || github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
frontend:
|
||||
name: Build frontend
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: npm
|
||||
cache-dependency-path: web/package-lock.json
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: web
|
||||
run: npm ci
|
||||
|
||||
- name: Build frontend
|
||||
working-directory: web
|
||||
run: npm run build
|
||||
|
||||
- name: Upload frontend artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: frontend-dist
|
||||
path: web/dist
|
||||
retention-days: 1
|
||||
|
||||
build-assets:
|
||||
name: Package ${{ matrix.component }} ${{ matrix.goos }}/${{ matrix.goarch }}
|
||||
needs: frontend
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- component: server
|
||||
goos: linux
|
||||
goarch: amd64
|
||||
archive_ext: tar.gz
|
||||
- component: client
|
||||
goos: linux
|
||||
goarch: amd64
|
||||
archive_ext: tar.gz
|
||||
- component: server
|
||||
goos: linux
|
||||
goarch: arm64
|
||||
archive_ext: tar.gz
|
||||
- component: client
|
||||
goos: linux
|
||||
goarch: arm64
|
||||
archive_ext: tar.gz
|
||||
- component: server
|
||||
goos: darwin
|
||||
goarch: amd64
|
||||
archive_ext: tar.gz
|
||||
- component: client
|
||||
goos: darwin
|
||||
goarch: amd64
|
||||
archive_ext: tar.gz
|
||||
- component: server
|
||||
goos: darwin
|
||||
goarch: arm64
|
||||
archive_ext: tar.gz
|
||||
- component: client
|
||||
goos: darwin
|
||||
goarch: arm64
|
||||
archive_ext: tar.gz
|
||||
- component: server
|
||||
goos: windows
|
||||
goarch: amd64
|
||||
archive_ext: zip
|
||||
- component: client
|
||||
goos: windows
|
||||
goarch: amd64
|
||||
archive_ext: zip
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: Download frontend artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: frontend-dist
|
||||
path: internal/server/app/dist
|
||||
|
||||
- name: Download Go modules
|
||||
run: go mod download
|
||||
|
||||
- name: Resolve release metadata
|
||||
id: meta
|
||||
shell: bash
|
||||
run: |
|
||||
if [ "${GITHUB_EVENT_NAME}" = "workflow_dispatch" ]; then
|
||||
TAG="${{ github.event.inputs.tag }}"
|
||||
else
|
||||
TAG="${GITHUB_REF_NAME}"
|
||||
fi
|
||||
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
|
||||
echo "commit=${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
|
||||
echo "build_time=$(date -u '+%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build binary
|
||||
shell: bash
|
||||
env:
|
||||
GOOS: ${{ matrix.goos }}
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
CGO_ENABLED: 0
|
||||
VERSION: ${{ steps.meta.outputs.tag }}
|
||||
GIT_COMMIT: ${{ steps.meta.outputs.commit }}
|
||||
BUILD_TIME: ${{ steps.meta.outputs.build_time }}
|
||||
run: |
|
||||
mkdir -p dist/package
|
||||
EXT=""
|
||||
if [ "$GOOS" = "windows" ]; then
|
||||
EXT=".exe"
|
||||
fi
|
||||
|
||||
OUTPUT_NAME="${{ matrix.component }}${EXT}"
|
||||
LDFLAGS="-s -w -X 'main.Version=${VERSION}' -X 'main.BuildTime=${BUILD_TIME}' -X 'main.GitCommit=${GIT_COMMIT}'"
|
||||
go build -trimpath -ldflags "$LDFLAGS" -o "dist/package/${OUTPUT_NAME}" ./cmd/${{ matrix.component }}
|
||||
|
||||
- name: Create release archive
|
||||
id: package
|
||||
shell: bash
|
||||
run: |
|
||||
TAG="${{ steps.meta.outputs.tag }}"
|
||||
ARCHIVE="gotunnel-${{ matrix.component }}-${TAG}-${{ matrix.goos }}-${{ matrix.goarch }}.${{ matrix.archive_ext }}"
|
||||
mkdir -p dist/out
|
||||
if [ "${{ matrix.archive_ext }}" = "zip" ]; then
|
||||
(cd dist/package && zip -r "../out/${ARCHIVE}" .)
|
||||
else
|
||||
tar -C dist/package -czf "dist/out/${ARCHIVE}" .
|
||||
fi
|
||||
echo "archive=dist/out/${ARCHIVE}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Upload release asset artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-${{ matrix.component }}-${{ matrix.goos }}-${{ matrix.goarch }}
|
||||
path: ${{ steps.package.outputs.archive }}
|
||||
retention-days: 1
|
||||
|
||||
publish:
|
||||
name: Publish release
|
||||
needs: build-assets
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Download packaged assets
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: release-artifacts
|
||||
pattern: release-*
|
||||
merge-multiple: true
|
||||
|
||||
- name: Resolve release metadata
|
||||
id: meta
|
||||
shell: bash
|
||||
run: |
|
||||
if [ "${GITHUB_EVENT_NAME}" = "workflow_dispatch" ]; then
|
||||
TAG="${{ github.event.inputs.tag }}"
|
||||
else
|
||||
TAG="${GITHUB_REF_NAME}"
|
||||
fi
|
||||
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Generate checksums
|
||||
shell: bash
|
||||
run: |
|
||||
cd release-artifacts
|
||||
sha256sum * > SHA256SUMS.txt
|
||||
|
||||
- name: Create or update GitHub release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.meta.outputs.tag }}
|
||||
target_commitish: ${{ github.sha }}
|
||||
generate_release_notes: true
|
||||
fail_on_unmatched_files: true
|
||||
files: |
|
||||
release-artifacts/*
|
||||
10
.gitignore
vendored
10
.gitignore
vendored
@@ -26,10 +26,11 @@ Thumbs.db
|
||||
# 前端 node_modules
|
||||
web/node_modules/
|
||||
|
||||
# 构建产物 (源码在 web/dist,嵌入用的在 pkg/webserver/dist)
|
||||
# 构建产物 (源码在 web/dist,嵌入用的在 internal/server/app/dist)
|
||||
web/dist/
|
||||
pkg/webserver/dist/
|
||||
**/dist/**
|
||||
internal/server/app/dist/*
|
||||
!internal/server/app/dist/.gitkeep
|
||||
build/**
|
||||
|
||||
# 日志
|
||||
@@ -38,3 +39,8 @@ build/**
|
||||
# 配置文件 (包含敏感信息)
|
||||
server.yaml
|
||||
client.yaml
|
||||
|
||||
# 临时文件
|
||||
*.tmp
|
||||
*.temp
|
||||
.claude/*
|
||||
113
AGENTS.md
Normal file
113
AGENTS.md
Normal file
@@ -0,0 +1,113 @@
|
||||
# AGENTS.md
|
||||
|
||||
This file provides guidance to Codex (Codex.ai/code) when working with code in this repository.
|
||||
|
||||
## Build Commands
|
||||
|
||||
```bash
|
||||
# Build server and client binaries
|
||||
go build -o server ./cmd/server
|
||||
go build -o client ./cmd/client
|
||||
|
||||
# Run server (zero-config, auto-generates token and TLS cert)
|
||||
./server
|
||||
./server -c server.yaml # with config file
|
||||
|
||||
# Run client
|
||||
./client -s <server>:7000 -t <token>
|
||||
|
||||
# Web UI development (in web/ directory)
|
||||
cd web && npm install && npm run dev # development server
|
||||
cd web && npm run build # production build (outputs to web/dist/)
|
||||
|
||||
# Cross-platform build (Windows PowerShell)
|
||||
.\scripts\build.ps1
|
||||
|
||||
# Cross-platform build (Linux/Mac)
|
||||
./scripts/build.sh all
|
||||
```
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
GoTunnel is an intranet penetration tool (similar to frp) with **server-centric configuration** - clients require zero configuration and receive mapping rules from the server after authentication.
|
||||
|
||||
### Core Design
|
||||
|
||||
- **Yamux Multiplexing**: Single TCP connection carries both control (auth, config, heartbeat) and data channels
|
||||
- **Binary Protocol**: `[Type(1 byte)][Length(4 bytes)][Payload(JSON)]` - see `pkg/protocol/message.go`
|
||||
- **TLS by Default**: Auto-generated self-signed ECDSA P-256 certificates, no manual setup required
|
||||
- **Embedded Web UI**: Vue.js SPA embedded in server binary via `//go:embed`
|
||||
- **JS Plugin System**: Extensible plugin system using goja JavaScript runtime
|
||||
|
||||
### Package Structure
|
||||
|
||||
```
|
||||
cmd/server/ # Server entry point
|
||||
cmd/client/ # Client entry point
|
||||
internal/server/
|
||||
├── tunnel/ # Core tunnel server, client session management
|
||||
├── config/ # YAML configuration loading
|
||||
├── db/ # SQLite storage (ClientStore, JSPluginStore interfaces)
|
||||
├── app/ # Web server, SPA handler
|
||||
├── router/ # REST API endpoints (Swagger documented)
|
||||
└── plugin/ # Server-side JS plugin manager
|
||||
internal/client/
|
||||
└── tunnel/ # Client tunnel logic, auto-reconnect, plugin execution
|
||||
pkg/
|
||||
├── protocol/ # Message types and serialization
|
||||
├── crypto/ # TLS certificate generation
|
||||
├── relay/ # Bidirectional data relay (32KB buffers)
|
||||
├── auth/ # JWT authentication
|
||||
├── utils/ # Port availability checking
|
||||
├── version/ # Version info and update checking (Gitea API)
|
||||
└── update/ # Shared update logic (download, extract tar.gz/zip)
|
||||
web/ # Vue 3 + TypeScript frontend (Vite + naive-ui)
|
||||
scripts/ # Build scripts (build.sh, build.ps1)
|
||||
```
|
||||
|
||||
### Key Interfaces
|
||||
|
||||
- `ClientStore` (internal/server/db/): Database abstraction for client rules storage
|
||||
- `ServerInterface` (internal/server/router/handler/): API handler interface
|
||||
|
||||
### Proxy Types
|
||||
|
||||
1. **TCP** (default): Direct port forwarding (remote_port → local_ip:local_port)
|
||||
2. **UDP**: UDP port forwarding
|
||||
3. **HTTP**: HTTP proxy through client network
|
||||
4. **HTTPS**: HTTPS proxy through client network
|
||||
5. **SOCKS5**: SOCKS5 proxy through client network
|
||||
|
||||
### Data Flow
|
||||
|
||||
External User → Server Port → Yamux Stream → Client → Local Service
|
||||
|
||||
### Configuration
|
||||
|
||||
- Server: YAML config + SQLite database for client rules and JS plugins
|
||||
- Client: Command-line flags only (server address, token)
|
||||
- Default ports: 7000 (tunnel), 7500 (web console)
|
||||
|
||||
## API Documentation
|
||||
|
||||
The server provides Swagger-documented REST APIs at `/api/`.
|
||||
|
||||
### Key Endpoints
|
||||
|
||||
- `POST /api/auth/login` - JWT authentication
|
||||
- `GET /api/clients` - List all clients
|
||||
- `GET /api/client/{id}` - Get client details
|
||||
- `PUT /api/client/{id}` - Update client config
|
||||
- `POST /api/client/{id}/push` - Push config to online client
|
||||
- `POST /api/client/{id}/plugin/{name}/{action}` - Plugin actions (start/stop/restart/delete)
|
||||
- `GET /api/plugins` - List registered plugins
|
||||
- `GET /api/update/check/server` - Check server updates
|
||||
- `POST /api/update/apply/server` - Apply server update
|
||||
|
||||
## Update System
|
||||
|
||||
Both server and client support self-update from Gitea releases.
|
||||
|
||||
- Release assets are compressed archives (`.tar.gz` for Linux/Mac, `.zip` for Windows)
|
||||
- The `pkg/update/` package handles download, extraction, and binary replacement
|
||||
- Updates can be triggered from the Web UI at `/update` page
|
||||
81
CLAUDE.md
81
CLAUDE.md
@@ -14,12 +14,17 @@ go build -o client ./cmd/client
|
||||
./server -c server.yaml # with config file
|
||||
|
||||
# Run client
|
||||
./client -s <server>:7000 -t <token> -id <client-id>
|
||||
./client -s <server>:7000 -t <token> -id <client-id> -no-tls # disable TLS
|
||||
./client -s <server>:7000 -t <token>
|
||||
|
||||
# Web UI development (in web/ directory)
|
||||
cd web && npm install && npm run dev # development server
|
||||
cd web && npm run build # production build (outputs to web/dist/)
|
||||
|
||||
# Cross-platform build (Windows PowerShell)
|
||||
.\scripts\build.ps1
|
||||
|
||||
# Cross-platform build (Linux/Mac)
|
||||
./scripts/build.sh all
|
||||
```
|
||||
|
||||
## Architecture Overview
|
||||
@@ -32,6 +37,7 @@ GoTunnel is an intranet penetration tool (similar to frp) with **server-centric
|
||||
- **Binary Protocol**: `[Type(1 byte)][Length(4 bytes)][Payload(JSON)]` - see `pkg/protocol/message.go`
|
||||
- **TLS by Default**: Auto-generated self-signed ECDSA P-256 certificates, no manual setup required
|
||||
- **Embedded Web UI**: Vue.js SPA embedded in server binary via `//go:embed`
|
||||
- **JS Plugin System**: Extensible plugin system using goja JavaScript runtime
|
||||
|
||||
### Package Structure
|
||||
|
||||
@@ -41,45 +47,36 @@ cmd/client/ # Client entry point
|
||||
internal/server/
|
||||
├── tunnel/ # Core tunnel server, client session management
|
||||
├── config/ # YAML configuration loading
|
||||
├── db/ # SQLite storage (ClientStore interface)
|
||||
├── db/ # SQLite storage (ClientStore, JSPluginStore interfaces)
|
||||
├── app/ # Web server, SPA handler
|
||||
├── router/ # REST API endpoints
|
||||
└── plugin/ # Server-side plugin manager
|
||||
├── router/ # REST API endpoints (Swagger documented)
|
||||
└── plugin/ # Server-side JS plugin manager
|
||||
internal/client/
|
||||
├── tunnel/ # Client tunnel logic, auto-reconnect
|
||||
└── plugin/ # Client-side plugin manager and cache
|
||||
└── tunnel/ # Client tunnel logic, auto-reconnect, plugin execution
|
||||
pkg/
|
||||
├── protocol/ # Message types and serialization
|
||||
├── crypto/ # TLS certificate generation
|
||||
├── proxy/ # Legacy proxy implementations
|
||||
├── relay/ # Bidirectional data relay (32KB buffers)
|
||||
├── auth/ # JWT authentication
|
||||
├── utils/ # Port availability checking
|
||||
└── plugin/ # Plugin system core
|
||||
├── types.go # ProxyHandler interface, PluginMetadata
|
||||
├── registry.go # Plugin registry
|
||||
├── builtin/ # Built-in plugins (socks5, http)
|
||||
├── wasm/ # WASM runtime (wazero)
|
||||
└── store/ # Plugin persistence (SQLite)
|
||||
web/ # Vue 3 + TypeScript frontend (Vite)
|
||||
├── version/ # Version info and update checking (Gitea API)
|
||||
└── update/ # Shared update logic (download, extract tar.gz/zip)
|
||||
web/ # Vue 3 + TypeScript frontend (Vite + naive-ui)
|
||||
scripts/ # Build scripts (build.sh, build.ps1)
|
||||
```
|
||||
|
||||
### Key Interfaces
|
||||
|
||||
- `ClientStore` (internal/server/db/): Database abstraction for client rules storage
|
||||
- `ServerInterface` (internal/server/router/): API handler interface
|
||||
- `ProxyHandler` (pkg/plugin/): Plugin interface for proxy handlers
|
||||
- `PluginStore` (pkg/plugin/store/): Plugin persistence interface
|
||||
- `ServerInterface` (internal/server/router/handler/): API handler interface
|
||||
|
||||
### Proxy Types
|
||||
|
||||
**内置类型** (直接在 tunnel 中处理):
|
||||
1. **TCP** (default): Direct port forwarding (remote_port → local_ip:local_port)
|
||||
2. **UDP**: UDP port forwarding
|
||||
3. **HTTP**: HTTP proxy through client network
|
||||
4. **HTTPS**: HTTPS proxy through client network
|
||||
|
||||
**插件类型** (通过 plugin 系统提供):
|
||||
- **SOCKS5**: Full SOCKS5 protocol (official plugin)
|
||||
5. **SOCKS5**: SOCKS5 proxy through client network
|
||||
|
||||
### Data Flow
|
||||
|
||||
@@ -87,32 +84,30 @@ External User → Server Port → Yamux Stream → Client → Local Service
|
||||
|
||||
### Configuration
|
||||
|
||||
- Server: YAML config + SQLite database for client rules
|
||||
- Client: Command-line flags only (server address, token, client ID)
|
||||
- Server: YAML config + SQLite database for client rules and JS plugins
|
||||
- Client: Command-line flags only (server address, token)
|
||||
- Default ports: 7000 (tunnel), 7500 (web console)
|
||||
|
||||
## Plugin System
|
||||
## API Documentation
|
||||
|
||||
GoTunnel supports a WASM-based plugin system for extensible proxy handlers.
|
||||
The server provides Swagger-documented REST APIs at `/api/`.
|
||||
|
||||
### Plugin Architecture
|
||||
### Key Endpoints
|
||||
|
||||
- **内置类型**: tcp, udp, http, https 直接在 tunnel 代码中处理
|
||||
- **Official Plugin**: SOCKS5 作为官方 plugin 提供
|
||||
- **WASM Plugins**: 自定义 plugins 可通过 wazero 运行时动态加载
|
||||
- **Hybrid Distribution**: 内置 plugins 离线可用;WASM plugins 可从服务端下载
|
||||
- `POST /api/auth/login` - JWT authentication
|
||||
- `GET /api/clients` - List all clients
|
||||
- `GET /api/client/{id}` - Get client details
|
||||
- `PUT /api/client/{id}` - Update client config
|
||||
- `POST /api/client/{id}/push` - Push config to online client
|
||||
- `POST /api/client/{id}/plugin/{name}/{action}` - Plugin actions (start/stop/restart/delete)
|
||||
- `GET /api/plugins` - List registered plugins
|
||||
- `GET /api/update/check/server` - Check server updates
|
||||
- `POST /api/update/apply/server` - Apply server update
|
||||
|
||||
### ProxyHandler Interface
|
||||
## Update System
|
||||
|
||||
```go
|
||||
type ProxyHandler interface {
|
||||
Metadata() PluginMetadata
|
||||
Init(config map[string]string) error
|
||||
HandleConn(conn net.Conn, dialer Dialer) error
|
||||
Close() error
|
||||
}
|
||||
```
|
||||
Both server and client support self-update from Gitea releases.
|
||||
|
||||
### Creating a Built-in Plugin
|
||||
|
||||
See `pkg/plugin/builtin/socks5.go` as reference implementation.
|
||||
- Release assets are compressed archives (`.tar.gz` for Linux/Mac, `.zip` for Windows)
|
||||
- The `pkg/update/` package handles download, extraction, and binary replacement
|
||||
- Updates can be triggered from the Web UI at `/update` page
|
||||
|
||||
88
Makefile
Normal file
88
Makefile
Normal file
@@ -0,0 +1,88 @@
|
||||
# GoTunnel Makefile
|
||||
|
||||
.PHONY: all build-frontend sync-frontend build-server build-client clean help
|
||||
|
||||
# 默认目标
|
||||
all: build-frontend sync-frontend build-server build-client
|
||||
|
||||
# 构建前端
|
||||
build-frontend:
|
||||
@echo "Building frontend..."
|
||||
cd web && npm ci && npm run build
|
||||
|
||||
# 同步前端到 embed 目录
|
||||
sync-frontend:
|
||||
@echo "Syncing frontend to embed directory..."
|
||||
ifeq ($(OS),Windows_NT)
|
||||
if exist internal\server\app\dist rmdir /s /q internal\server\app\dist
|
||||
xcopy /E /I /Y web\dist internal\server\app\dist
|
||||
else
|
||||
rm -rf internal/server/app/dist
|
||||
cp -r web/dist internal/server/app/dist
|
||||
endif
|
||||
|
||||
# 仅同步(不重新构建前端)
|
||||
sync-only:
|
||||
@echo "Syncing existing frontend build..."
|
||||
ifeq ($(OS),Windows_NT)
|
||||
if exist internal\server\app\dist rmdir /s /q internal\server\app\dist
|
||||
xcopy /E /I /Y web\dist internal\server\app\dist
|
||||
else
|
||||
rm -rf internal/server/app/dist
|
||||
cp -r web/dist internal/server/app/dist
|
||||
endif
|
||||
|
||||
# 构建服务端(当前平台)
|
||||
build-server:
|
||||
@echo "Building server..."
|
||||
go build -ldflags="-s -w" -o gotunnel-server ./cmd/server
|
||||
|
||||
# 构建客户端(当前平台)
|
||||
build-client:
|
||||
@echo "Building client..."
|
||||
go build -ldflags="-s -w" -o gotunnel-client ./cmd/client
|
||||
|
||||
# 构建 Linux ARM64 服务端
|
||||
build-server-linux-arm64: sync-only
|
||||
@echo "Building server for Linux ARM64..."
|
||||
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -ldflags="-s -w" -o gotunnel-server-linux-arm64 ./cmd/server
|
||||
|
||||
# 构建 Linux AMD64 服务端
|
||||
build-server-linux-amd64: sync-only
|
||||
@echo "Building server for Linux AMD64..."
|
||||
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags="-s -w" -o gotunnel-server-linux-amd64 ./cmd/server
|
||||
|
||||
# 完整构建(包含前端)
|
||||
full-build: build-frontend sync-frontend build-server build-client
|
||||
|
||||
# 开发模式:快速构建(假设前端已构建)
|
||||
dev-build: sync-only build-server
|
||||
|
||||
# 清理构建产物
|
||||
clean:
|
||||
@echo "Cleaning..."
|
||||
ifeq ($(OS),Windows_NT)
|
||||
if exist gotunnel-server del gotunnel-server
|
||||
if exist gotunnel-client del gotunnel-client
|
||||
if exist gotunnel-server.exe del gotunnel-server.exe
|
||||
if exist gotunnel-client.exe del gotunnel-client.exe
|
||||
if exist gotunnel-server-* del gotunnel-server-*
|
||||
if exist gotunnel-client-* del gotunnel-client-*
|
||||
else
|
||||
rm -f gotunnel-server gotunnel-client gotunnel-server-* gotunnel-client-*
|
||||
endif
|
||||
|
||||
# 帮助
|
||||
help:
|
||||
@echo "Available targets:"
|
||||
@echo " all - Build frontend, sync, and build binaries"
|
||||
@echo " build-frontend - Build frontend (npm)"
|
||||
@echo " sync-frontend - Sync web/dist to internal/server/app/dist"
|
||||
@echo " sync-only - Sync without rebuilding frontend"
|
||||
@echo " build-server - Build server for current platform"
|
||||
@echo " build-client - Build client for current platform"
|
||||
@echo " build-server-linux-arm64 - Cross-compile server for Linux ARM64"
|
||||
@echo " build-server-linux-amd64 - Cross-compile server for Linux AMD64"
|
||||
@echo " full-build - Complete build with frontend"
|
||||
@echo " dev-build - Quick build (assumes frontend exists)"
|
||||
@echo " clean - Remove build artifacts"
|
||||
560
PLUGINS.md
560
PLUGINS.md
@@ -1,560 +0,0 @@
|
||||
# GoTunnel 插件开发指南
|
||||
|
||||
本文档介绍如何为 GoTunnel 开发 JS 插件。
|
||||
|
||||
## 目录
|
||||
|
||||
- [快速开始](#快速开始)
|
||||
- [插件结构](#插件结构)
|
||||
- [API 参考](#api-参考)
|
||||
- [示例插件](#示例插件)
|
||||
- [插件签名](#插件签名)
|
||||
- [发布到商店](#发布到商店)
|
||||
|
||||
---
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 最小插件示例
|
||||
|
||||
```javascript
|
||||
// 必须:定义插件元数据
|
||||
function metadata() {
|
||||
return {
|
||||
name: "my-plugin",
|
||||
version: "1.0.0",
|
||||
type: "app",
|
||||
description: "My first plugin",
|
||||
author: "Your Name"
|
||||
};
|
||||
}
|
||||
|
||||
// 可选:插件启动时调用
|
||||
function start() {
|
||||
log("Plugin started");
|
||||
}
|
||||
|
||||
// 必须:处理连接
|
||||
function handleConn(conn) {
|
||||
// 处理连接逻辑
|
||||
conn.Close();
|
||||
}
|
||||
|
||||
// 可选:插件停止时调用
|
||||
function stop() {
|
||||
log("Plugin stopped");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 插件结构
|
||||
|
||||
### 生命周期函数
|
||||
|
||||
| 函数 | 必须 | 说明 |
|
||||
|------|------|------|
|
||||
| `metadata()` | 否 | 返回插件元数据,不定义则使用默认值 |
|
||||
| `start()` | 否 | 插件启动时调用 |
|
||||
| `handleConn(conn)` | 是 | 处理每个连接 |
|
||||
| `stop()` | 否 | 插件停止时调用 |
|
||||
|
||||
### 元数据字段
|
||||
|
||||
```javascript
|
||||
function metadata() {
|
||||
return {
|
||||
name: "plugin-name", // 插件名称
|
||||
version: "1.0.0", // 版本号
|
||||
type: "app", // 类型: "app" 或 "proxy"
|
||||
run_at: "client", // 运行位置: "client" 或 "server"
|
||||
description: "描述", // 插件描述
|
||||
author: "作者" // 作者名称
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## API 参考
|
||||
|
||||
### 基础 API
|
||||
|
||||
#### `log(message)`
|
||||
|
||||
输出日志信息。
|
||||
|
||||
```javascript
|
||||
log("Hello, World!");
|
||||
// 输出: [JS:plugin-name] Hello, World!
|
||||
```
|
||||
|
||||
#### `config(key)`
|
||||
|
||||
获取插件配置值。
|
||||
|
||||
```javascript
|
||||
var port = config("port");
|
||||
var host = config("host") || "127.0.0.1";
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 连接 API (conn)
|
||||
|
||||
`handleConn` 函数接收的 `conn` 对象提供以下方法:
|
||||
|
||||
#### `conn.Read(size)`
|
||||
|
||||
读取数据,返回字节数组,失败返回 `null`。
|
||||
|
||||
```javascript
|
||||
var data = conn.Read(1024);
|
||||
if (data) {
|
||||
log("Received " + data.length + " bytes");
|
||||
}
|
||||
```
|
||||
|
||||
#### `conn.Write(data)`
|
||||
|
||||
写入数据,返回写入的字节数。
|
||||
|
||||
```javascript
|
||||
var written = conn.Write(data);
|
||||
log("Wrote " + written + " bytes");
|
||||
```
|
||||
|
||||
#### `conn.Close()`
|
||||
|
||||
关闭连接。
|
||||
|
||||
```javascript
|
||||
conn.Close();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 文件系统 API (fs)
|
||||
|
||||
所有文件操作都在沙箱中执行,有路径和大小限制。
|
||||
|
||||
#### `fs.readFile(path)`
|
||||
|
||||
读取文件内容。
|
||||
|
||||
```javascript
|
||||
var result = fs.readFile("/path/to/file.txt");
|
||||
if (result.error) {
|
||||
log("Error: " + result.error);
|
||||
} else {
|
||||
log("Content: " + result.data);
|
||||
}
|
||||
```
|
||||
|
||||
#### `fs.writeFile(path, content)`
|
||||
|
||||
写入文件内容。
|
||||
|
||||
```javascript
|
||||
var result = fs.writeFile("/path/to/file.txt", "Hello");
|
||||
if (result.ok) {
|
||||
log("File written");
|
||||
} else {
|
||||
log("Error: " + result.error);
|
||||
}
|
||||
```
|
||||
|
||||
#### `fs.readDir(path)`
|
||||
|
||||
读取目录内容。
|
||||
|
||||
```javascript
|
||||
var result = fs.readDir("/path/to/dir");
|
||||
if (!result.error) {
|
||||
for (var i = 0; i < result.entries.length; i++) {
|
||||
var entry = result.entries[i];
|
||||
log(entry.name + " - " + (entry.isDir ? "DIR" : entry.size + " bytes"));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### `fs.stat(path)`
|
||||
|
||||
获取文件信息。
|
||||
|
||||
```javascript
|
||||
var result = fs.stat("/path/to/file");
|
||||
if (!result.error) {
|
||||
log("Name: " + result.name);
|
||||
log("Size: " + result.size);
|
||||
log("IsDir: " + result.isDir);
|
||||
log("ModTime: " + result.modTime);
|
||||
}
|
||||
```
|
||||
|
||||
#### `fs.exists(path)`
|
||||
|
||||
检查文件是否存在。
|
||||
|
||||
```javascript
|
||||
var result = fs.exists("/path/to/file");
|
||||
if (result.exists) {
|
||||
log("File exists");
|
||||
}
|
||||
```
|
||||
|
||||
#### `fs.mkdir(path)`
|
||||
|
||||
创建目录。
|
||||
|
||||
```javascript
|
||||
var result = fs.mkdir("/path/to/new/dir");
|
||||
if (result.ok) {
|
||||
log("Directory created");
|
||||
}
|
||||
```
|
||||
|
||||
#### `fs.remove(path)`
|
||||
|
||||
删除文件或目录。
|
||||
|
||||
```javascript
|
||||
var result = fs.remove("/path/to/file");
|
||||
if (result.ok) {
|
||||
log("Removed");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### HTTP API (http)
|
||||
|
||||
用于构建简单的 HTTP 服务。
|
||||
|
||||
#### `http.serve(conn, handler)`
|
||||
|
||||
处理 HTTP 请求。
|
||||
|
||||
```javascript
|
||||
function handleConn(conn) {
|
||||
http.serve(conn, function(req) {
|
||||
return {
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: http.json({ message: "Hello", path: req.path })
|
||||
};
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
**请求对象 (req):**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `method` | string | HTTP 方法 (GET, POST, etc.) |
|
||||
| `path` | string | 请求路径 |
|
||||
| `body` | string | 请求体 |
|
||||
|
||||
**响应对象:**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `status` | number | HTTP 状态码 (默认 200) |
|
||||
| `contentType` | string | Content-Type (默认 application/json) |
|
||||
| `body` | string | 响应体 |
|
||||
|
||||
#### `http.json(data)`
|
||||
|
||||
将对象序列化为 JSON 字符串。
|
||||
|
||||
```javascript
|
||||
var jsonStr = http.json({ name: "test", value: 123 });
|
||||
// 返回: '{"name":"test","value":123}'
|
||||
```
|
||||
|
||||
#### `http.sendFile(conn, filePath)`
|
||||
|
||||
发送文件作为 HTTP 响应。
|
||||
|
||||
```javascript
|
||||
function handleConn(conn) {
|
||||
http.sendFile(conn, "/path/to/index.html");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 示例插件
|
||||
|
||||
### Echo 服务
|
||||
|
||||
```javascript
|
||||
function metadata() {
|
||||
return {
|
||||
name: "echo",
|
||||
version: "1.0.0",
|
||||
type: "app",
|
||||
description: "Echo back received data"
|
||||
};
|
||||
}
|
||||
|
||||
function handleConn(conn) {
|
||||
while (true) {
|
||||
var data = conn.Read(4096);
|
||||
if (!data || data.length === 0) {
|
||||
break;
|
||||
}
|
||||
conn.Write(data);
|
||||
}
|
||||
conn.Close();
|
||||
}
|
||||
```
|
||||
|
||||
### HTTP 文件服务器
|
||||
|
||||
```javascript
|
||||
function metadata() {
|
||||
return {
|
||||
name: "file-server",
|
||||
version: "1.0.0",
|
||||
type: "app",
|
||||
description: "Simple HTTP file server"
|
||||
};
|
||||
}
|
||||
|
||||
var rootDir = "";
|
||||
|
||||
function start() {
|
||||
rootDir = config("root") || "/tmp";
|
||||
log("Serving files from: " + rootDir);
|
||||
}
|
||||
|
||||
function handleConn(conn) {
|
||||
http.serve(conn, function(req) {
|
||||
if (req.method === "GET") {
|
||||
var filePath = rootDir + req.path;
|
||||
if (req.path === "/") {
|
||||
filePath = rootDir + "/index.html";
|
||||
}
|
||||
|
||||
var stat = fs.stat(filePath);
|
||||
if (stat.error) {
|
||||
return { status: 404, body: "Not Found" };
|
||||
}
|
||||
|
||||
if (stat.isDir) {
|
||||
return listDirectory(filePath);
|
||||
}
|
||||
|
||||
var file = fs.readFile(filePath);
|
||||
if (file.error) {
|
||||
return { status: 500, body: file.error };
|
||||
}
|
||||
|
||||
return {
|
||||
status: 200,
|
||||
contentType: "text/html",
|
||||
body: file.data
|
||||
};
|
||||
}
|
||||
return { status: 405, body: "Method Not Allowed" };
|
||||
});
|
||||
}
|
||||
|
||||
function listDirectory(path) {
|
||||
var result = fs.readDir(path);
|
||||
if (result.error) {
|
||||
return { status: 500, body: result.error };
|
||||
}
|
||||
|
||||
var html = "<html><body><h1>Directory Listing</h1><ul>";
|
||||
for (var i = 0; i < result.entries.length; i++) {
|
||||
var e = result.entries[i];
|
||||
html += "<li><a href='" + e.name + "'>" + e.name + "</a></li>";
|
||||
}
|
||||
html += "</ul></body></html>";
|
||||
|
||||
return { status: 200, contentType: "text/html", body: html };
|
||||
}
|
||||
```
|
||||
|
||||
### JSON API 服务
|
||||
|
||||
```javascript
|
||||
function metadata() {
|
||||
return {
|
||||
name: "api-server",
|
||||
version: "1.0.0",
|
||||
type: "app",
|
||||
description: "JSON API server"
|
||||
};
|
||||
}
|
||||
|
||||
var counter = 0;
|
||||
|
||||
function handleConn(conn) {
|
||||
http.serve(conn, function(req) {
|
||||
if (req.path === "/api/status") {
|
||||
return {
|
||||
status: 200,
|
||||
body: http.json({
|
||||
status: "ok",
|
||||
counter: counter++,
|
||||
timestamp: Date.now()
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
if (req.path === "/api/echo" && req.method === "POST") {
|
||||
return {
|
||||
status: 200,
|
||||
body: http.json({
|
||||
received: req.body
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: 404,
|
||||
body: http.json({ error: "Not Found" })
|
||||
};
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 插件签名
|
||||
|
||||
为了安全,JS 插件需要官方签名才能运行。
|
||||
|
||||
### 签名格式
|
||||
|
||||
签名文件 (`.sig`) 包含 Base64 编码的签名数据:
|
||||
|
||||
```json
|
||||
{
|
||||
"payload": {
|
||||
"name": "plugin-name",
|
||||
"version": "1.0.0",
|
||||
"checksum": "sha256-hash",
|
||||
"key_id": "official-v1"
|
||||
},
|
||||
"signature": "base64-signature"
|
||||
}
|
||||
```
|
||||
|
||||
### 获取签名
|
||||
|
||||
1. 提交插件到官方仓库
|
||||
2. 通过审核后获得签名
|
||||
3. 将 `.js` 和 `.sig` 文件一起分发
|
||||
|
||||
---
|
||||
|
||||
## 发布到商店
|
||||
|
||||
### 商店 JSON 格式
|
||||
|
||||
插件商店使用 `store.json` 文件索引所有插件:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"name": "echo",
|
||||
"version": "1.0.0",
|
||||
"type": "app",
|
||||
"description": "Echo service plugin",
|
||||
"author": "GoTunnel",
|
||||
"icon": "https://example.com/icon.png",
|
||||
"download_url": "https://example.com/plugins/echo.js"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### 提交流程
|
||||
|
||||
1. Fork 官方插件仓库
|
||||
2. 添加插件文件到 `plugins/` 目录
|
||||
3. 更新 `store.json`
|
||||
4. 提交 Pull Request
|
||||
5. 等待审核和签名
|
||||
|
||||
---
|
||||
|
||||
## 沙箱限制
|
||||
|
||||
为了安全,JS 插件运行在沙箱环境中:
|
||||
|
||||
| 限制项 | 默认值 |
|
||||
|--------|--------|
|
||||
| 最大读取文件大小 | 10 MB |
|
||||
| 最大写入文件大小 | 10 MB |
|
||||
| 允许读取路径 | 插件数据目录 |
|
||||
| 允许写入路径 | 插件数据目录 |
|
||||
|
||||
---
|
||||
|
||||
## 调试技巧
|
||||
|
||||
### 日志输出
|
||||
|
||||
使用 `log()` 函数输出调试信息:
|
||||
|
||||
```javascript
|
||||
log("Debug: variable = " + JSON.stringify(variable));
|
||||
```
|
||||
|
||||
### 错误处理
|
||||
|
||||
始终检查 API 返回的错误:
|
||||
|
||||
```javascript
|
||||
var result = fs.readFile(path);
|
||||
if (result.error) {
|
||||
log("Error reading file: " + result.error);
|
||||
return;
|
||||
}
|
||||
```
|
||||
|
||||
### 配置测试
|
||||
|
||||
在服务端配置中测试插件:
|
||||
|
||||
```yaml
|
||||
js_plugins:
|
||||
- name: my-plugin
|
||||
path: /path/to/my-plugin.js
|
||||
sig_path: /path/to/my-plugin.js.sig
|
||||
config:
|
||||
debug: "true"
|
||||
port: "8080"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 常见问题
|
||||
|
||||
**Q: 插件无法加载?**
|
||||
|
||||
A: 检查签名文件是否存在且有效。
|
||||
|
||||
**Q: 文件操作失败?**
|
||||
|
||||
A: 确认路径在沙箱允许范围内。
|
||||
|
||||
**Q: 如何获取客户端 IP?**
|
||||
|
||||
A: 目前 API 不支持,计划在后续版本添加。
|
||||
|
||||
---
|
||||
|
||||
## 更新日志
|
||||
|
||||
### v1.0.0
|
||||
|
||||
- 初始版本
|
||||
- 支持基础 API: log, config
|
||||
- 支持连接 API: Read, Write, Close
|
||||
- 支持文件系统 API: fs.*
|
||||
- 支持 HTTP API: http.*
|
||||
73
README.md
73
README.md
@@ -17,7 +17,7 @@ GoTunnel 是一个类似 frp 的内网穿透解决方案,核心特点是**服
|
||||
| TLS 证书 | 自动生成,零配置 | 需手动配置 |
|
||||
| 管理界面 | 内置 Web 控制台 (naive-ui) | 需额外部署 Dashboard |
|
||||
| 客户端部署 | 仅需 2 个参数 | 需配置文件 |
|
||||
| 客户端 ID | 可选,服务端自动分配 | 需手动配置 |
|
||||
| 客户端 ID | 自动根据设备标识计算 | 需手动配置 |
|
||||
|
||||
### 架构设计
|
||||
|
||||
@@ -50,6 +50,7 @@ GoTunnel 是一个类似 frp 的内网穿透解决方案,核心特点是**服
|
||||
- **多客户端支持** - 支持多个客户端同时连接,每个客户端独立的映射规则
|
||||
- **端口冲突检测** - 自动检测系统端口占用和客户端间端口冲突
|
||||
- **SOCKS5/HTTP 代理** - 支持通过客户端网络访问任意网站
|
||||
- **自动更新** - 服务端和客户端支持从 Web 界面一键更新
|
||||
|
||||
### 安全性
|
||||
|
||||
@@ -110,14 +111,9 @@ go build -o client ./cmd/client
|
||||
### 客户端启动
|
||||
|
||||
```bash
|
||||
# 最简启动(ID 由服务端自动分配)
|
||||
# 最简启动(ID 由客户端根据设备标识自动计算)
|
||||
./client -s <服务器IP>:7000 -t <Token>
|
||||
|
||||
# 指定客户端 ID
|
||||
./client -s <服务器IP>:7000 -t <Token> -id <客户端ID>
|
||||
|
||||
# 禁用 TLS(需服务端也禁用)
|
||||
./client -s <服务器IP>:7000 -t <Token> -no-tls
|
||||
```
|
||||
|
||||
**参数说明:**
|
||||
@@ -126,9 +122,6 @@ go build -o client ./cmd/client
|
||||
|------|------|------|
|
||||
| `-s` | 服务器地址 (ip:port) | 是 |
|
||||
| `-t` | 认证 Token | 是 |
|
||||
| `-id` | 客户端 ID | 否(服务端自动分配) |
|
||||
| `-no-tls` | 禁用 TLS 加密 | 否 |
|
||||
| `-skip-verify` | 跳过证书验证(不安全,仅测试用) | 否 |
|
||||
|
||||
## 配置系统
|
||||
|
||||
@@ -192,11 +185,7 @@ web:
|
||||
| `http` | HTTP 代理 | 通过客户端网络访问 HTTP/HTTPS |
|
||||
| `https` | HTTPS 代理 | 同 HTTP,支持 CONNECT 方法 |
|
||||
|
||||
### 插件类型
|
||||
|
||||
| 类型 | 说明 | 示例用途 |
|
||||
|------|------|----------|
|
||||
| `socks5` | SOCKS5 代理(官方插件) | 通过客户端网络访问任意地址 |
|
||||
| `socks5` | SOCKS5 代理 | 通过客户端网络访问任意地址 |
|
||||
|
||||
**规则配置示例(通过 Web API):**
|
||||
|
||||
@@ -226,9 +215,11 @@ GoTunnel/
|
||||
│ │ ├── config/ # 配置管理
|
||||
│ │ ├── db/ # 数据库存储
|
||||
│ │ ├── app/ # Web 服务
|
||||
│ │ └── router/ # API 路由
|
||||
│ │ ├── router/ # API 路由
|
||||
│ │ └── plugin/ # 服务端插件管理
|
||||
│ └── client/
|
||||
│ └── tunnel/ # 客户端隧道
|
||||
│ ├── tunnel/ # 客户端隧道
|
||||
│ └── plugin/ # 客户端插件管理和缓存
|
||||
├── pkg/
|
||||
│ ├── protocol/ # 通信协议
|
||||
│ ├── crypto/ # TLS 加密
|
||||
@@ -236,32 +227,31 @@ GoTunnel/
|
||||
│ ├── relay/ # 数据转发
|
||||
│ ├── auth/ # JWT 认证
|
||||
│ ├── utils/ # 工具函数
|
||||
│ └── plugin/ # 插件系统核心
|
||||
│ ├── builtin/ # 内置插件 (socks5)
|
||||
│ ├── wasm/ # WASM 运行时 (wazero)
|
||||
│ ├── version/ # 版本信息和更新检查
|
||||
│ ├── update/ # 共享更新逻辑 (下载、解压)
|
||||
│ └── plugin/ # JS 插件系统核心 (goja)
|
||||
│ └── store/ # 插件持久化 (SQLite)
|
||||
├── web/ # Vue 3 + naive-ui 前端
|
||||
├── scripts/ # 构建脚本
|
||||
│ └── build.sh # 跨平台构建脚本
|
||||
│ ├── build.sh # Linux/macOS 构建脚本
|
||||
│ └── build.ps1 # Windows 构建脚本
|
||||
└── go.mod
|
||||
```
|
||||
|
||||
## 插件系统
|
||||
|
||||
GoTunnel 支持灵活的插件系统,可扩展代理协议和应用功能。
|
||||
GoTunnel 支持灵活的 JS 插件系统,可扩展代理协议和应用功能。
|
||||
|
||||
### 插件类型
|
||||
|
||||
| 类型 | 说明 | 运行位置 |
|
||||
|------|------|----------|
|
||||
| `proxy` | 代理协议插件 (如 SOCKS5) | 服务端 |
|
||||
| `app` | 应用插件 (如 HTTP 文件服务) | 客户端 |
|
||||
| `app` | 应用插件 (如 HTTP 文件服务、Echo 服务) | 客户端 |
|
||||
|
||||
### 插件来源
|
||||
|
||||
- **内置插件**: 编译在二进制中,离线可用
|
||||
- **JS 插件**: 基于 goja 运行时,支持动态加载和热更新
|
||||
- **扩展商店**: 从官方商店浏览和安装插件
|
||||
- **插件商店**: 从服务端管理的插件商店浏览和安装
|
||||
|
||||
### 开发 JS 插件
|
||||
|
||||
@@ -390,7 +380,7 @@ curl -X POST http://server:7500/api/clients \
|
||||
-d '{"id":"home","rules":[{"name":"web","type":"tcp","local_ip":"127.0.0.1","local_port":80,"remote_port":8080}]}'
|
||||
|
||||
# 客户端连接
|
||||
./client -s server:7000 -t <token> -id home
|
||||
./client -s server:7000 -t <token>
|
||||
|
||||
# 访问:http://server:8080 -> 内网 127.0.0.1:80
|
||||
```
|
||||
@@ -413,7 +403,7 @@ A: 在 Web 控制台点击客户端详情,进入编辑模式即可设置昵称
|
||||
|
||||
**Q: 如何禁用 TLS?**
|
||||
|
||||
A: 服务端配置 `tls_disabled: true`,客户端使用 `-no-tls` 参数。
|
||||
A: 客户端命令行默认使用 TLS;如需兼容旧的非 TLS 部署,请改用客户端配置文件中的 `no_tls: true`。
|
||||
|
||||
**Q: 端口被占用怎么办?**
|
||||
|
||||
@@ -421,12 +411,18 @@ A: 服务端会自动检测端口冲突,请检查日志并更换端口。
|
||||
|
||||
**Q: 客户端 ID 是如何分配的?**
|
||||
|
||||
A: 如果客户端未指定 `-id` 参数,服务端会自动生成 16 位随机 ID。
|
||||
A: 客户端会把系统机器 ID、全部可用 MAC、主机名和网卡名等稳定标识组合后再进行哈希,得到固定客户端 ID;服务端不再为客户端分配或修正 ID。
|
||||
|
||||
**Q: 如何更新服务端/客户端?**
|
||||
|
||||
A: 在 Web 控制台的"更新"页面,可以检查并应用更新。服务端/客户端会自动从 Release 下载压缩包、解压并重启。
|
||||
|
||||
## 构建
|
||||
|
||||
使用构建脚本可以一键构建前后端:
|
||||
|
||||
**Linux/macOS:**
|
||||
|
||||
```bash
|
||||
# 构建当前平台
|
||||
./scripts/build.sh current
|
||||
@@ -444,6 +440,25 @@ A: 如果客户端未指定 `-id` 参数,服务端会自动生成 16 位随机
|
||||
VERSION=1.0.0 ./scripts/build.sh all
|
||||
```
|
||||
|
||||
**Windows (PowerShell):**
|
||||
|
||||
```powershell
|
||||
# 构建当前平台
|
||||
.\scripts\build.ps1 current
|
||||
|
||||
# 构建所有平台
|
||||
.\scripts\build.ps1 all
|
||||
|
||||
# 仅构建 Web UI
|
||||
.\scripts\build.ps1 web
|
||||
|
||||
# 清理构建产物
|
||||
.\scripts\build.ps1 clean
|
||||
|
||||
# 指定版本号
|
||||
$env:VERSION="1.0.0"; .\scripts\build.ps1 all
|
||||
```
|
||||
|
||||
构建产物输出到 `build/<os>_<arch>/` 目录。
|
||||
|
||||
## 架构时序图
|
||||
|
||||
Binary file not shown.
@@ -1,15 +0,0 @@
|
||||
server:
|
||||
bind_addr: "0.0.0.0" # 监听地址
|
||||
bind_port: 7001 # 监听端口
|
||||
token: "flik1513." # 认证 Token(不配置则自动生成)
|
||||
heartbeat_sec: 30 # 心跳间隔(秒)
|
||||
heartbeat_timeout: 90 # 心跳超时(秒)
|
||||
db_path: "gotunnel.db" # 数据库路径
|
||||
tls_disabled: false # 是否禁用 TLS(默认启用)
|
||||
|
||||
web:
|
||||
enabled: true # 启用 Web 控制台
|
||||
bind_addr: "0.0.0.0"
|
||||
bind_port: 7500
|
||||
username: "admin" # 可选,设置后启用认证
|
||||
password: "password"
|
||||
Binary file not shown.
Binary file not shown.
@@ -3,52 +3,61 @@ package main
|
||||
import (
|
||||
"flag"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/gotunnel/internal/client/config"
|
||||
"github.com/gotunnel/internal/client/tunnel"
|
||||
"github.com/gotunnel/pkg/crypto"
|
||||
"github.com/gotunnel/pkg/plugin"
|
||||
"github.com/gotunnel/pkg/plugin/builtin"
|
||||
"github.com/gotunnel/pkg/version"
|
||||
)
|
||||
|
||||
// 版本信息(通过 ldflags 注入)
|
||||
var Version string
|
||||
var BuildTime string
|
||||
var GitCommit string
|
||||
|
||||
func init() {
|
||||
version.SetVersion(Version)
|
||||
version.SetBuildInfo(GitCommit, BuildTime)
|
||||
}
|
||||
|
||||
func main() {
|
||||
server := flag.String("s", "", "server address (ip:port)")
|
||||
token := flag.String("t", "", "auth token")
|
||||
id := flag.String("id", "", "client id (optional, auto-assigned if empty)")
|
||||
noTLS := flag.Bool("no-tls", false, "disable TLS")
|
||||
skipVerify := flag.Bool("skip-verify", false, "skip TLS certificate verification (insecure)")
|
||||
configPath := flag.String("c", "", "config file path")
|
||||
flag.Parse()
|
||||
|
||||
if *server == "" || *token == "" {
|
||||
log.Fatal("Usage: client -s <server:port> -t <token> [-id <client_id>] [-no-tls] [-skip-verify]")
|
||||
// 优先加载配置文件
|
||||
var cfg *config.ClientConfig
|
||||
if *configPath != "" {
|
||||
var err error
|
||||
cfg, err = config.LoadClientConfig(*configPath)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to load config: %v", err)
|
||||
}
|
||||
} else {
|
||||
cfg = &config.ClientConfig{}
|
||||
}
|
||||
|
||||
client := tunnel.NewClient(*server, *token, *id)
|
||||
// 命令行参数覆盖配置文件
|
||||
if *server != "" {
|
||||
cfg.Server = *server
|
||||
}
|
||||
if *token != "" {
|
||||
cfg.Token = *token
|
||||
}
|
||||
|
||||
// TLS 默认启用,使用 TOFU 验证
|
||||
if !*noTLS {
|
||||
if cfg.Server == "" || cfg.Token == "" {
|
||||
log.Fatal("Usage: client [-c config.yaml] | [-s <server:port> -t <token>]")
|
||||
}
|
||||
|
||||
client := tunnel.NewClient(cfg.Server, cfg.Token)
|
||||
|
||||
// TLS 默认启用,默认跳过证书验证(类似 frp)
|
||||
if !cfg.NoTLS {
|
||||
client.TLSEnabled = true
|
||||
// 获取数据目录
|
||||
home, _ := os.UserHomeDir()
|
||||
dataDir := filepath.Join(home, ".gotunnel")
|
||||
client.TLSConfig = crypto.ClientTLSConfigWithTOFU(*server, dataDir, *skipVerify)
|
||||
if *skipVerify {
|
||||
log.Printf("[Client] TLS enabled (certificate verification DISABLED - insecure)")
|
||||
} else {
|
||||
log.Printf("[Client] TLS enabled with TOFU certificate verification")
|
||||
}
|
||||
client.TLSConfig = crypto.ClientTLSConfig()
|
||||
log.Printf("[Client] TLS enabled")
|
||||
}
|
||||
|
||||
// 初始化插件系统
|
||||
registry := plugin.NewRegistry()
|
||||
for _, h := range builtin.GetClientPlugins() {
|
||||
if err := registry.RegisterClient(h); err != nil {
|
||||
log.Fatalf("[Plugin] Register error: %v", err)
|
||||
}
|
||||
}
|
||||
client.SetPluginRegistry(registry)
|
||||
log.Printf("[Plugin] Registered %d plugins", len(builtin.GetClientPlugins()))
|
||||
|
||||
client.Run()
|
||||
}
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
package main
|
||||
|
||||
// @title GoTunnel API
|
||||
// @version 1.0
|
||||
// @description GoTunnel 内网穿透服务器 API
|
||||
// @host localhost:7500
|
||||
// @BasePath /
|
||||
// @securityDefinitions.apikey Bearer
|
||||
// @in header
|
||||
// @name Authorization
|
||||
// @description JWT Bearer token
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
@@ -9,16 +19,26 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
_ "github.com/gotunnel/docs" // Swagger docs
|
||||
|
||||
"github.com/gotunnel/internal/server/app"
|
||||
"github.com/gotunnel/internal/server/config"
|
||||
"github.com/gotunnel/internal/server/db"
|
||||
"github.com/gotunnel/internal/server/tunnel"
|
||||
"github.com/gotunnel/pkg/crypto"
|
||||
"github.com/gotunnel/pkg/plugin"
|
||||
"github.com/gotunnel/pkg/plugin/builtin"
|
||||
"github.com/gotunnel/pkg/plugin/sign"
|
||||
"github.com/gotunnel/pkg/version"
|
||||
)
|
||||
|
||||
// 版本信息(通过 ldflags 注入)
|
||||
var Version string
|
||||
var BuildTime string
|
||||
var GitCommit string
|
||||
|
||||
func init() {
|
||||
version.SetVersion(Version)
|
||||
version.SetBuildInfo(GitCommit, BuildTime)
|
||||
}
|
||||
|
||||
func main() {
|
||||
configPath := flag.String("c", "server.yaml", "config file path")
|
||||
flag.Parse()
|
||||
@@ -59,26 +79,15 @@ func main() {
|
||||
log.Printf("[Server] TLS enabled")
|
||||
}
|
||||
|
||||
// 初始化插件系统
|
||||
registry := plugin.NewRegistry()
|
||||
if err := registry.RegisterAllServer(builtin.GetServerPlugins()); err != nil {
|
||||
log.Fatalf("[Plugin] Register error: %v", err)
|
||||
}
|
||||
server.SetPluginRegistry(registry)
|
||||
log.Printf("[Plugin] Registered %d plugins", len(builtin.GetServerPlugins()))
|
||||
|
||||
// 加载 JS 插件配置
|
||||
if len(cfg.JSPlugins) > 0 {
|
||||
jsPlugins := loadJSPlugins(cfg.JSPlugins)
|
||||
server.LoadJSPlugins(jsPlugins)
|
||||
}
|
||||
// 设置流量存储,用于记录流量统计
|
||||
server.SetTrafficStore(clientStore)
|
||||
|
||||
// 启动 Web 控制台
|
||||
if cfg.Web.Enabled {
|
||||
if cfg.Server.Web.Enabled {
|
||||
// 强制生成 Web 凭据(如果未配置)
|
||||
if config.GenerateWebCredentials(cfg) {
|
||||
log.Printf("[Web] Auto-generated credentials - Username: %s, Password: %s",
|
||||
cfg.Web.Username, cfg.Web.Password)
|
||||
cfg.Server.Web.Username, cfg.Server.Web.Password)
|
||||
log.Printf("[Web] Please save these credentials and update your config file")
|
||||
// 保存配置以持久化凭据
|
||||
if err := config.SaveServerConfig(*configPath, cfg); err != nil {
|
||||
@@ -87,11 +96,11 @@ func main() {
|
||||
}
|
||||
|
||||
ws := app.NewWebServer(clientStore, server, cfg, *configPath, clientStore)
|
||||
addr := fmt.Sprintf("%s:%d", cfg.Web.BindAddr, cfg.Web.BindPort)
|
||||
addr := fmt.Sprintf("%s:%d", cfg.Server.BindAddr, cfg.Server.Web.BindPort)
|
||||
|
||||
go func() {
|
||||
// 始终使用 JWT 认证
|
||||
err := ws.RunWithJWT(addr, cfg.Web.Username, cfg.Web.Password, cfg.Server.Token)
|
||||
err := ws.RunWithJWT(addr, cfg.Server.Web.Username, cfg.Server.Web.Password, cfg.Server.Token)
|
||||
if err != nil {
|
||||
log.Printf("[Web] Server error: %v", err)
|
||||
}
|
||||
@@ -112,69 +121,3 @@ func main() {
|
||||
|
||||
log.Fatal(server.Run())
|
||||
}
|
||||
|
||||
// loadJSPlugins 加载 JS 插件文件
|
||||
func loadJSPlugins(configs []config.JSPluginConfig) []tunnel.JSPluginEntry {
|
||||
var plugins []tunnel.JSPluginEntry
|
||||
|
||||
for _, cfg := range configs {
|
||||
source, err := os.ReadFile(cfg.Path)
|
||||
if err != nil {
|
||||
log.Printf("[JSPlugin] Failed to load %s: %v", cfg.Path, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// 加载签名文件
|
||||
sigPath := cfg.SigPath
|
||||
if sigPath == "" {
|
||||
sigPath = cfg.Path + ".sig"
|
||||
}
|
||||
signature, err := os.ReadFile(sigPath)
|
||||
if err != nil {
|
||||
log.Printf("[JSPlugin] Failed to load signature for %s: %v", cfg.Name, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// 服务端也验证签名,防止配置文件被篡改
|
||||
if err := verifyPluginSignature(cfg.Name, string(source), string(signature)); err != nil {
|
||||
log.Printf("[JSPlugin] Signature verification failed for %s: %v", cfg.Name, err)
|
||||
continue
|
||||
}
|
||||
|
||||
plugins = append(plugins, tunnel.JSPluginEntry{
|
||||
Name: cfg.Name,
|
||||
Source: string(source),
|
||||
Signature: string(signature),
|
||||
AutoPush: cfg.AutoPush,
|
||||
Config: cfg.Config,
|
||||
AutoStart: cfg.AutoStart,
|
||||
})
|
||||
|
||||
log.Printf("[JSPlugin] Loaded: %s from %s (verified)", cfg.Name, cfg.Path)
|
||||
}
|
||||
|
||||
return plugins
|
||||
}
|
||||
|
||||
// verifyPluginSignature 验证插件签名
|
||||
func verifyPluginSignature(name, source, signature string) error {
|
||||
// 解码签名
|
||||
signed, err := sign.DecodeSignedPlugin(signature)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode signature: %w", err)
|
||||
}
|
||||
|
||||
// 获取公钥
|
||||
pubKey, err := sign.GetPublicKeyByID(signed.Payload.KeyID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 验证插件名称
|
||||
if signed.Payload.Name != name {
|
||||
return fmt.Errorf("name mismatch: %s vs %s", signed.Payload.Name, name)
|
||||
}
|
||||
|
||||
// 验证签名
|
||||
return sign.VerifyPlugin(pubKey, signed, source)
|
||||
}
|
||||
|
||||
2398
docs/docs.go
Normal file
2398
docs/docs.go
Normal file
File diff suppressed because it is too large
Load Diff
2374
docs/swagger.json
Normal file
2374
docs/swagger.json
Normal file
File diff suppressed because it is too large
Load Diff
1500
docs/swagger.yaml
Normal file
1500
docs/swagger.yaml
Normal file
File diff suppressed because it is too large
Load Diff
70
go.mod
70
go.mod
@@ -3,25 +3,81 @@ module github.com/gotunnel
|
||||
go 1.24.0
|
||||
|
||||
require (
|
||||
github.com/gin-gonic/gin v1.11.0
|
||||
github.com/go-playground/validator/v10 v10.30.1
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/hashicorp/yamux v0.1.1
|
||||
github.com/kbinani/screenshot v0.0.0-20250624051815-089614a94018
|
||||
github.com/shirou/gopsutil/v3 v3.24.5
|
||||
github.com/swaggo/files v1.0.1
|
||||
github.com/swaggo/gin-swagger v1.6.1
|
||||
github.com/swaggo/swag v1.16.6
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
modernc.org/sqlite v1.41.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/dlclark/regexp2 v1.11.4 // indirect
|
||||
github.com/dop251/goja v0.0.0-20251201205617-2bb4c724c0f9 // indirect
|
||||
github.com/KyleBanks/depth v1.2.1 // indirect
|
||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||
github.com/bytedance/sonic v1.14.2 // indirect
|
||||
github.com/bytedance/sonic/loader v0.4.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||
github.com/gen2brain/shm v0.1.0 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-ole/go-ole v1.2.6 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.22.4 // indirect
|
||||
github.com/go-openapi/jsonreference v0.21.4 // indirect
|
||||
github.com/go-openapi/spec v0.22.3 // indirect
|
||||
github.com/go-openapi/swag/conv v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/jsonname v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/jsonutils v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/loading v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/stringutils v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/typeutils v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/yamlutils v0.25.4 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/goccy/go-yaml v1.19.1 // indirect
|
||||
github.com/godbus/dbus/v5 v5.1.0 // indirect
|
||||
github.com/jezek/xgb v1.1.1 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
||||
github.com/lxn/win v0.0.0-20210218163916-a377121e959e // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.58.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/shoenig/go-m1cpu v0.1.7 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.12 // indirect
|
||||
github.com/tklauser/numcpus v0.6.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.1 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
go.uber.org/mock v0.6.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/arch v0.23.0 // indirect
|
||||
golang.org/x/crypto v0.46.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
|
||||
golang.org/x/sys v0.38.0 // indirect
|
||||
golang.org/x/text v0.3.8 // indirect
|
||||
golang.org/x/mod v0.31.0 // indirect
|
||||
golang.org/x/net v0.48.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
golang.org/x/text v0.32.0 // indirect
|
||||
golang.org/x/tools v0.40.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
modernc.org/libc v1.66.10 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
|
||||
216
go.sum
216
go.sum
@@ -1,40 +1,222 @@
|
||||
github.com/dlclark/regexp2 v1.11.4 h1:rPYF9/LECdNymJufQKmri9gV604RvvABwgOA8un7yAo=
|
||||
github.com/dlclark/regexp2 v1.11.4/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
github.com/dop251/goja v0.0.0-20251201205617-2bb4c724c0f9 h1:3uSSOd6mVlwcX3k5OYOpiDqFgRmaE2dBfLvVIFWWHrw=
|
||||
github.com/dop251/goja v0.0.0-20251201205617-2bb4c724c0f9/go.mod h1:MxLav0peU43GgvwVgNbLAj1s/bSGboKkhuULvq/7hx4=
|
||||
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
|
||||
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
|
||||
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
|
||||
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
|
||||
github.com/bytedance/sonic v1.14.2 h1:k1twIoe97C1DtYUo+fZQy865IuHia4PR5RPiuGPPIIE=
|
||||
github.com/bytedance/sonic v1.14.2/go.mod h1:T80iDELeHiHKSc0C9tubFygiuXoGzrkjKzX2quAx980=
|
||||
github.com/bytedance/sonic/loader v0.4.0 h1:olZ7lEqcxtZygCK9EKYKADnpQoYkRQxaeY2NYzevs+o=
|
||||
github.com/bytedance/sonic/loader v0.4.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/go-sourcemap/sourcemap v2.1.3+incompatible h1:W1iEw64niKVGogNgBN3ePyLFfuisuzeidWPMPWmECqU=
|
||||
github.com/go-sourcemap/sourcemap v2.1.3+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gen2brain/shm v0.1.0 h1:MwPeg+zJQXN0RM9o+HqaSFypNoNEcNpeoGp0BTSx2YY=
|
||||
github.com/gen2brain/shm v0.1.0/go.mod h1:UgIcVtvmOu+aCJpqJX7GOtiN7X2ct+TKLg4RTxwPIUA=
|
||||
github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4=
|
||||
github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
|
||||
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
|
||||
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
|
||||
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||
github.com/go-openapi/jsonpointer v0.22.4 h1:dZtK82WlNpVLDW2jlA1YCiVJFVqkED1MegOUy9kR5T4=
|
||||
github.com/go-openapi/jsonpointer v0.22.4/go.mod h1:elX9+UgznpFhgBuaMQ7iu4lvvX1nvNsesQ3oxmYTw80=
|
||||
github.com/go-openapi/jsonreference v0.21.4 h1:24qaE2y9bx/q3uRK/qN+TDwbok1NhbSmGjjySRCHtC8=
|
||||
github.com/go-openapi/jsonreference v0.21.4/go.mod h1:rIENPTjDbLpzQmQWCj5kKj3ZlmEh+EFVbz3RTUh30/4=
|
||||
github.com/go-openapi/spec v0.22.3 h1:qRSmj6Smz2rEBxMnLRBMeBWxbbOvuOoElvSvObIgwQc=
|
||||
github.com/go-openapi/spec v0.22.3/go.mod h1:iIImLODL2loCh3Vnox8TY2YWYJZjMAKYyLH2Mu8lOZs=
|
||||
github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=
|
||||
github.com/go-openapi/swag/conv v0.25.4 h1:/Dd7p0LZXczgUcC/Ikm1+YqVzkEeCc9LnOWjfkpkfe4=
|
||||
github.com/go-openapi/swag/conv v0.25.4/go.mod h1:3LXfie/lwoAv0NHoEuY1hjoFAYkvlqI/Bn5EQDD3PPU=
|
||||
github.com/go-openapi/swag/jsonname v0.25.4 h1:bZH0+MsS03MbnwBXYhuTttMOqk+5KcQ9869Vye1bNHI=
|
||||
github.com/go-openapi/swag/jsonname v0.25.4/go.mod h1:GPVEk9CWVhNvWhZgrnvRA6utbAltopbKwDu8mXNUMag=
|
||||
github.com/go-openapi/swag/jsonutils v0.25.4 h1:VSchfbGhD4UTf4vCdR2F4TLBdLwHyUDTd1/q4i+jGZA=
|
||||
github.com/go-openapi/swag/jsonutils v0.25.4/go.mod h1:7OYGXpvVFPn4PpaSdPHJBtF0iGnbEaTk8AvBkoWnaAY=
|
||||
github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4 h1:IACsSvBhiNJwlDix7wq39SS2Fh7lUOCJRmx/4SN4sVo=
|
||||
github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4/go.mod h1:Mt0Ost9l3cUzVv4OEZG+WSeoHwjWLnarzMePNDAOBiM=
|
||||
github.com/go-openapi/swag/loading v0.25.4 h1:jN4MvLj0X6yhCDduRsxDDw1aHe+ZWoLjW+9ZQWIKn2s=
|
||||
github.com/go-openapi/swag/loading v0.25.4/go.mod h1:rpUM1ZiyEP9+mNLIQUdMiD7dCETXvkkC30z53i+ftTE=
|
||||
github.com/go-openapi/swag/stringutils v0.25.4 h1:O6dU1Rd8bej4HPA3/CLPciNBBDwZj9HiEpdVsb8B5A8=
|
||||
github.com/go-openapi/swag/stringutils v0.25.4/go.mod h1:GTsRvhJW5xM5gkgiFe0fV3PUlFm0dr8vki6/VSRaZK0=
|
||||
github.com/go-openapi/swag/typeutils v0.25.4 h1:1/fbZOUN472NTc39zpa+YGHn3jzHWhv42wAJSN91wRw=
|
||||
github.com/go-openapi/swag/typeutils v0.25.4/go.mod h1:Ou7g//Wx8tTLS9vG0UmzfCsjZjKhpjxayRKTHXf2pTE=
|
||||
github.com/go-openapi/swag/yamlutils v0.25.4 h1:6jdaeSItEUb7ioS9lFoCZ65Cne1/RZtPBZ9A56h92Sw=
|
||||
github.com/go-openapi/swag/yamlutils v0.25.4/go.mod h1:MNzq1ulQu+yd8Kl7wPOut/YHAAU/H6hL91fF+E2RFwc=
|
||||
github.com/go-openapi/testify/enable/yaml/v2 v2.0.2 h1:0+Y41Pz1NkbTHz8NngxTuAXxEodtNSI1WG1c/m5Akw4=
|
||||
github.com/go-openapi/testify/enable/yaml/v2 v2.0.2/go.mod h1:kme83333GCtJQHXQ8UKX3IBZu6z8T5Dvy5+CW3NLUUg=
|
||||
github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls=
|
||||
github.com/go-openapi/testify/v2 v2.0.2/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
|
||||
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-yaml v1.19.1 h1:3rG3+v8pkhRqoQ/88NYNMHYVGYztCOCIZ7UQhu7H+NE=
|
||||
github.com/goccy/go-yaml v1.19.1/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
|
||||
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE=
|
||||
github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ=
|
||||
github.com/jezek/xgb v1.1.1 h1:bE/r8ZZtSv7l9gk6nU0mYx51aXrvnyb44892TwSaqS4=
|
||||
github.com/jezek/xgb v1.1.1/go.mod h1:nrhwO0FX/enq75I7Y7G8iN1ubpSGZEiA3v9e9GyRFlk=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/kbinani/screenshot v0.0.0-20250624051815-089614a94018 h1:NQYgMY188uWrS+E/7xMVpydsI48PMHcc7SfR4OxkDF4=
|
||||
github.com/kbinani/screenshot v0.0.0-20250624051815-089614a94018/go.mod h1:Pmpz2BLf55auQZ67u3rvyI2vAQvNetkK/4zYUmpauZQ=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
|
||||
github.com/lxn/win v0.0.0-20210218163916-a377121e959e h1:H+t6A/QJMbhCSEH5rAuRxh+CtW96g0Or0Fxa9IKr4uc=
|
||||
github.com/lxn/win v0.0.0-20210218163916-a377121e959e/go.mod h1:KxxjdtRkfNoYDCUP5ryK7XJJNTnpC8atvtmTheChOtk=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw=
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/quic-go/quic-go v0.58.0 h1:ggY2pvZaVdB9EyojxL1p+5mptkuHyX5MOSv4dgWF4Ug=
|
||||
github.com/quic-go/quic-go v0.58.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||
github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI=
|
||||
github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk=
|
||||
github.com/shoenig/go-m1cpu v0.1.7 h1:C76Yd0ObKR82W4vhfjZiCp0HxcSZ8Nqd84v+HZ0qyI0=
|
||||
github.com/shoenig/go-m1cpu v0.1.7/go.mod h1:KkDOw6m3ZJQAPHbrzkZki4hnx+pDRR1Lo+ldA56wD5w=
|
||||
github.com/shoenig/test v1.7.0 h1:eWcHtTXa6QLnBvm0jgEabMRN/uJ4DMV3M8xUGgRkZmk=
|
||||
github.com/shoenig/test v1.7.0/go.mod h1:UxJ6u/x2v/TNs/LoLxBNJRV9DiwBBKYxXSyczsBHFoI=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE=
|
||||
github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg=
|
||||
github.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs7cY=
|
||||
github.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw=
|
||||
github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
|
||||
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
|
||||
github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU=
|
||||
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
|
||||
github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=
|
||||
github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
|
||||
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
|
||||
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
|
||||
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/arch v0.23.0 h1:lKF64A2jF6Zd8L0knGltUnegD62JMFBiCPBmQpToHhg=
|
||||
golang.org/x/arch v0.23.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
|
||||
golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ=
|
||||
golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc=
|
||||
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
|
||||
golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
|
||||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
|
||||
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
|
||||
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/cc/v4 v4.26.5 h1:xM3bX7Mve6G8K8b+T11ReenJOT+BmVqQj0FY5T4+5Y4=
|
||||
|
||||
29
internal/client/config/config.go
Normal file
29
internal/client/config/config.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// ClientConfig 客户端配置
|
||||
type ClientConfig struct {
|
||||
Server string `yaml:"server"` // 服务器地址
|
||||
Token string `yaml:"token"` // 认证 Token
|
||||
NoTLS bool `yaml:"no_tls"` // 禁用 TLS
|
||||
}
|
||||
|
||||
// LoadClientConfig 加载客户端配置
|
||||
func LoadClientConfig(path string) (*ClientConfig, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var cfg ClientConfig
|
||||
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &cfg, nil
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
|
||||
"github.com/gotunnel/pkg/plugin"
|
||||
"github.com/gotunnel/pkg/plugin/builtin"
|
||||
)
|
||||
|
||||
// Manager 客户端 plugin 管理器
|
||||
type Manager struct {
|
||||
registry *plugin.Registry
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewManager 创建客户端 plugin 管理器
|
||||
func NewManager() (*Manager, error) {
|
||||
registry := plugin.NewRegistry()
|
||||
|
||||
m := &Manager{
|
||||
registry: registry,
|
||||
}
|
||||
|
||||
if err := m.registerBuiltins(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// registerBuiltins 注册内置 plugins
|
||||
func (m *Manager) registerBuiltins() error {
|
||||
for _, h := range builtin.GetClientPlugins() {
|
||||
if err := m.registry.RegisterClient(h); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
log.Printf("[Plugin] Registered %d client plugins", len(builtin.GetClientPlugins()))
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetClient 返回客户端插件
|
||||
func (m *Manager) GetClient(name string) (plugin.ClientPlugin, error) {
|
||||
return m.registry.GetClient(name)
|
||||
}
|
||||
|
||||
// GetRegistry 返回插件注册表
|
||||
func (m *Manager) GetRegistry() *plugin.Registry {
|
||||
return m.registry
|
||||
}
|
||||
@@ -1,20 +1,24 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gotunnel/pkg/plugin"
|
||||
"github.com/gotunnel/pkg/plugin/script"
|
||||
"github.com/gotunnel/pkg/plugin/sign"
|
||||
"github.com/gotunnel/pkg/protocol"
|
||||
"github.com/gotunnel/pkg/relay"
|
||||
"github.com/gotunnel/pkg/update"
|
||||
"github.com/gotunnel/pkg/utils"
|
||||
"github.com/gotunnel/pkg/version"
|
||||
"github.com/hashicorp/yamux"
|
||||
)
|
||||
|
||||
@@ -26,97 +30,112 @@ const (
|
||||
reconnectDelay = 5 * time.Second
|
||||
disconnectDelay = 3 * time.Second
|
||||
udpBufferSize = 65535
|
||||
idFileName = ".gotunnel_id"
|
||||
)
|
||||
|
||||
// Client 隧道客户端
|
||||
type Client struct {
|
||||
ServerAddr string
|
||||
Token string
|
||||
ID string
|
||||
TLSEnabled bool
|
||||
TLSConfig *tls.Config
|
||||
DataDir string // 数据目录
|
||||
session *yamux.Session
|
||||
rules []protocol.ProxyRule
|
||||
mu sync.RWMutex
|
||||
pluginRegistry *plugin.Registry
|
||||
runningPlugins map[string]plugin.ClientPlugin
|
||||
versionStore *PluginVersionStore
|
||||
pluginMu sync.RWMutex
|
||||
ServerAddr string
|
||||
Token string
|
||||
ID string
|
||||
Name string // 客户端名称(主机名)
|
||||
TLSEnabled bool
|
||||
TLSConfig *tls.Config
|
||||
DataDir string // 数据目录
|
||||
session *yamux.Session
|
||||
rules []protocol.ProxyRule
|
||||
mu sync.RWMutex
|
||||
logger *Logger // 日志收集器
|
||||
}
|
||||
|
||||
// NewClient 创建客户端
|
||||
func NewClient(serverAddr, token, id string) *Client {
|
||||
if id == "" {
|
||||
id = loadClientID()
|
||||
func NewClient(serverAddr, token string) *Client {
|
||||
// 默认数据目录:优先使用用户主目录,失败时回退到当前工作目录
|
||||
var dataDir string
|
||||
if home, err := os.UserHomeDir(); err == nil && home != "" {
|
||||
dataDir = filepath.Join(home, ".gotunnel")
|
||||
} else {
|
||||
// UserHomeDir 失败(如 Android adb shell 环境),使用当前工作目录
|
||||
if cwd, err := os.Getwd(); err == nil {
|
||||
dataDir = filepath.Join(cwd, ".gotunnel")
|
||||
log.Printf("[Client] UserHomeDir unavailable, using current directory: %s", dataDir)
|
||||
} else {
|
||||
// 最后回退到相对路径
|
||||
dataDir = ".gotunnel"
|
||||
log.Printf("[Client] Warning: using relative path for data directory")
|
||||
}
|
||||
}
|
||||
|
||||
// 默认数据目录
|
||||
home, _ := os.UserHomeDir()
|
||||
dataDir := filepath.Join(home, ".gotunnel")
|
||||
// 确保数据目录存在
|
||||
if err := os.MkdirAll(dataDir, 0755); err != nil {
|
||||
log.Printf("Failed to create data dir: %v", err)
|
||||
}
|
||||
|
||||
// ID 优先级:命令行参数 > 机器ID
|
||||
id := getMachineID()
|
||||
|
||||
// 获取主机名作为客户端名称
|
||||
hostname, _ := os.Hostname()
|
||||
|
||||
// 初始化日志收集器
|
||||
logger, err := NewLogger(dataDir)
|
||||
if err != nil {
|
||||
log.Printf("Failed to initialize logger: %v", err)
|
||||
}
|
||||
|
||||
return &Client{
|
||||
ServerAddr: serverAddr,
|
||||
Token: token,
|
||||
ID: id,
|
||||
DataDir: dataDir,
|
||||
runningPlugins: make(map[string]plugin.ClientPlugin),
|
||||
ServerAddr: serverAddr,
|
||||
Token: token,
|
||||
ID: id,
|
||||
Name: hostname,
|
||||
DataDir: dataDir,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// InitVersionStore 初始化版本存储
|
||||
func (c *Client) InitVersionStore() error {
|
||||
store, err := NewPluginVersionStore(c.DataDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.versionStore = store
|
||||
return nil
|
||||
}
|
||||
|
||||
// getIDFilePath 获取 ID 文件路径
|
||||
func getIDFilePath() string {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return idFileName
|
||||
}
|
||||
return filepath.Join(home, idFileName)
|
||||
}
|
||||
|
||||
// loadClientID 从本地文件加载客户端 ID
|
||||
func loadClientID() string {
|
||||
data, err := os.ReadFile(getIDFilePath())
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
// saveClientID 保存客户端 ID 到本地文件
|
||||
func saveClientID(id string) {
|
||||
if err := os.WriteFile(getIDFilePath(), []byte(id), 0600); err != nil {
|
||||
log.Printf("[Client] Failed to save client ID: %v", err)
|
||||
// logf 安全地记录日志(同时输出到标准日志和日志收集器)
|
||||
func (c *Client) logf(format string, args ...interface{}) {
|
||||
msg := fmt.Sprintf(format, args...)
|
||||
log.Print(msg)
|
||||
if c.logger != nil {
|
||||
c.logger.Printf(msg)
|
||||
}
|
||||
}
|
||||
|
||||
// SetPluginRegistry 设置插件注册表
|
||||
func (c *Client) SetPluginRegistry(registry *plugin.Registry) {
|
||||
c.pluginRegistry = registry
|
||||
// logErrorf 安全地记录错误日志
|
||||
func (c *Client) logErrorf(format string, args ...interface{}) {
|
||||
msg := fmt.Sprintf(format, args...)
|
||||
log.Print(msg)
|
||||
if c.logger != nil {
|
||||
c.logger.Errorf(msg)
|
||||
}
|
||||
}
|
||||
|
||||
// logWarnf 安全地记录警告日志
|
||||
func (c *Client) logWarnf(format string, args ...interface{}) {
|
||||
msg := fmt.Sprintf(format, args...)
|
||||
log.Print(msg)
|
||||
if c.logger != nil {
|
||||
c.logger.Warnf(msg)
|
||||
}
|
||||
}
|
||||
|
||||
// Run 启动客户端(带断线重连)
|
||||
func (c *Client) Run() error {
|
||||
for {
|
||||
if err := c.connect(); err != nil {
|
||||
log.Printf("[Client] Connect error: %v", err)
|
||||
log.Printf("[Client] Reconnecting in %v...", reconnectDelay)
|
||||
c.logErrorf("Connect error: %v", err)
|
||||
c.logf("Reconnecting in %v...", reconnectDelay)
|
||||
time.Sleep(reconnectDelay)
|
||||
continue
|
||||
}
|
||||
|
||||
c.handleSession()
|
||||
log.Printf("[Client] Disconnected, reconnecting...")
|
||||
c.logWarnf("Disconnected, reconnecting...")
|
||||
time.Sleep(disconnectDelay)
|
||||
}
|
||||
}
|
||||
@@ -136,7 +155,14 @@ func (c *Client) connect() error {
|
||||
return err
|
||||
}
|
||||
|
||||
authReq := protocol.AuthRequest{ClientID: c.ID, Token: c.Token}
|
||||
authReq := protocol.AuthRequest{
|
||||
ClientID: c.ID,
|
||||
Token: c.Token,
|
||||
Name: c.Name,
|
||||
OS: runtime.GOOS,
|
||||
Arch: runtime.GOARCH,
|
||||
Version: version.Version,
|
||||
}
|
||||
msg, _ := protocol.NewMessage(protocol.MsgTypeAuth, authReq)
|
||||
if err := protocol.WriteMessage(conn, msg); err != nil {
|
||||
conn.Close()
|
||||
@@ -159,14 +185,13 @@ func (c *Client) connect() error {
|
||||
return fmt.Errorf("auth failed: %s", authResp.Message)
|
||||
}
|
||||
|
||||
// 如果服务端分配了新 ID,则更新并保存
|
||||
// 如果服务端分配了新 ID,则更新
|
||||
if authResp.ClientID != "" && authResp.ClientID != c.ID {
|
||||
c.ID = authResp.ClientID
|
||||
saveClientID(c.ID)
|
||||
log.Printf("[Client] New ID assigned and saved: %s", c.ID)
|
||||
conn.Close()
|
||||
return fmt.Errorf("server returned unexpected client id: %s", authResp.ClientID)
|
||||
}
|
||||
|
||||
log.Printf("[Client] Authenticated as %s", c.ID)
|
||||
c.logf("Authenticated as %s", c.ID)
|
||||
|
||||
session, err := yamux.Client(conn, nil)
|
||||
if err != nil {
|
||||
@@ -204,8 +229,7 @@ func (c *Client) handleStream(stream net.Conn) {
|
||||
|
||||
switch msg.Type {
|
||||
case protocol.MsgTypeProxyConfig:
|
||||
defer stream.Close()
|
||||
c.handleProxyConfig(msg)
|
||||
c.handleProxyConfig(stream, msg)
|
||||
case protocol.MsgTypeNewProxy:
|
||||
defer stream.Close()
|
||||
c.handleNewProxy(stream, msg)
|
||||
@@ -216,23 +240,30 @@ func (c *Client) handleStream(stream net.Conn) {
|
||||
c.handleProxyConnect(stream, msg)
|
||||
case protocol.MsgTypeUDPData:
|
||||
c.handleUDPData(stream, msg)
|
||||
case protocol.MsgTypePluginConfig:
|
||||
defer stream.Close()
|
||||
c.handlePluginConfig(msg)
|
||||
case protocol.MsgTypeClientPluginStart:
|
||||
c.handleClientPluginStart(stream, msg)
|
||||
case protocol.MsgTypeClientPluginConn:
|
||||
c.handleClientPluginConn(stream, msg)
|
||||
case protocol.MsgTypeJSPluginInstall:
|
||||
c.handleJSPluginInstall(stream, msg)
|
||||
case protocol.MsgTypeClientRestart:
|
||||
c.handleClientRestart(stream, msg)
|
||||
case protocol.MsgTypeUpdateDownload:
|
||||
c.handleUpdateDownload(stream, msg)
|
||||
case protocol.MsgTypeLogRequest:
|
||||
go c.handleLogRequest(stream, msg)
|
||||
case protocol.MsgTypeLogStop:
|
||||
c.handleLogStop(stream, msg)
|
||||
case protocol.MsgTypeSystemStatsRequest:
|
||||
c.handleSystemStatsRequest(stream, msg)
|
||||
case protocol.MsgTypeScreenshotRequest:
|
||||
c.handleScreenshotRequest(stream, msg)
|
||||
case protocol.MsgTypeShellExecuteRequest:
|
||||
c.handleShellExecuteRequest(stream, msg)
|
||||
}
|
||||
}
|
||||
|
||||
// handleProxyConfig 处理代理配置
|
||||
func (c *Client) handleProxyConfig(msg *protocol.Message) {
|
||||
func (c *Client) handleProxyConfig(stream net.Conn, msg *protocol.Message) {
|
||||
defer stream.Close()
|
||||
|
||||
var cfg protocol.ProxyConfig
|
||||
if err := msg.ParsePayload(&cfg); err != nil {
|
||||
log.Printf("[Client] Parse proxy config error: %v", err)
|
||||
c.logErrorf("Parse proxy config error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -240,17 +271,21 @@ func (c *Client) handleProxyConfig(msg *protocol.Message) {
|
||||
c.rules = cfg.Rules
|
||||
c.mu.Unlock()
|
||||
|
||||
log.Printf("[Client] Received %d proxy rules", len(cfg.Rules))
|
||||
c.logf("Received %d proxy rules", len(cfg.Rules))
|
||||
for _, r := range cfg.Rules {
|
||||
log.Printf("[Client] %s: %s:%d", r.Name, r.LocalIP, r.LocalPort)
|
||||
c.logf(" %s: %s:%d", r.Name, r.LocalIP, r.LocalPort)
|
||||
}
|
||||
|
||||
// 发送配置确认
|
||||
ack := &protocol.Message{Type: protocol.MsgTypeProxyReady}
|
||||
protocol.WriteMessage(stream, ack)
|
||||
}
|
||||
|
||||
// handleNewProxy 处理新代理请求
|
||||
func (c *Client) handleNewProxy(stream net.Conn, msg *protocol.Message) {
|
||||
var req protocol.NewProxyRequest
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
log.Printf("[Client] Parse new proxy request error: %v", err)
|
||||
c.logErrorf("Parse new proxy request error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -265,14 +300,14 @@ func (c *Client) handleNewProxy(stream net.Conn, msg *protocol.Message) {
|
||||
c.mu.RUnlock()
|
||||
|
||||
if rule == nil {
|
||||
log.Printf("[Client] Unknown port %d", req.RemotePort)
|
||||
c.logWarnf("Unknown port %d", req.RemotePort)
|
||||
return
|
||||
}
|
||||
|
||||
localAddr := fmt.Sprintf("%s:%d", rule.LocalIP, rule.LocalPort)
|
||||
localConn, err := net.DialTimeout("tcp", localAddr, localDialTimeout)
|
||||
if err != nil {
|
||||
log.Printf("[Client] Connect %s error: %v", localAddr, err)
|
||||
c.logErrorf("Connect %s error: %v", localAddr, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -378,234 +413,428 @@ func (c *Client) findRuleByPort(port int) *protocol.ProxyRule {
|
||||
return nil
|
||||
}
|
||||
|
||||
// handlePluginConfig 处理插件配置同步
|
||||
func (c *Client) handlePluginConfig(msg *protocol.Message) {
|
||||
var cfg protocol.PluginConfigSync
|
||||
if err := msg.ParsePayload(&cfg); err != nil {
|
||||
log.Printf("[Client] Parse plugin config error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("[Client] Received config for plugin: %s", cfg.PluginName)
|
||||
|
||||
// 应用配置到插件
|
||||
if c.pluginRegistry != nil {
|
||||
handler, err := c.pluginRegistry.GetClient(cfg.PluginName)
|
||||
if err != nil {
|
||||
log.Printf("[Client] Plugin %s not found: %v", cfg.PluginName, err)
|
||||
return
|
||||
}
|
||||
if err := handler.Init(cfg.Config); err != nil {
|
||||
log.Printf("[Client] Plugin %s init error: %v", cfg.PluginName, err)
|
||||
return
|
||||
}
|
||||
log.Printf("[Client] Plugin %s config applied", cfg.PluginName)
|
||||
}
|
||||
}
|
||||
|
||||
// handleClientPluginStart 处理客户端插件启动请求
|
||||
func (c *Client) handleClientPluginStart(stream net.Conn, msg *protocol.Message) {
|
||||
// handleClientRestart 处理客户端重启请求
|
||||
func (c *Client) handleClientRestart(stream net.Conn, msg *protocol.Message) {
|
||||
defer stream.Close()
|
||||
|
||||
var req protocol.ClientPluginStartRequest
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
c.sendPluginStatus(stream, req.PluginName, req.RuleName, false, "", err.Error())
|
||||
return
|
||||
var req protocol.ClientRestartRequest
|
||||
msg.ParsePayload(&req)
|
||||
|
||||
c.logf("Restart requested: %s", req.Reason)
|
||||
|
||||
// 发送响应
|
||||
resp := protocol.ClientRestartResponse{
|
||||
Success: true,
|
||||
Message: "restarting",
|
||||
}
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeClientRestart, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
|
||||
log.Printf("[Client] Starting plugin %s for rule %s", req.PluginName, req.RuleName)
|
||||
|
||||
// 获取插件
|
||||
if c.pluginRegistry == nil {
|
||||
c.sendPluginStatus(stream, req.PluginName, req.RuleName, false, "", "plugin registry not set")
|
||||
return
|
||||
// 停止所有运行中的插件
|
||||
// 关闭会话(会触发重连)
|
||||
if c.session != nil {
|
||||
c.session.Close()
|
||||
}
|
||||
|
||||
handler, err := c.pluginRegistry.GetClient(req.PluginName)
|
||||
if err != nil {
|
||||
c.sendPluginStatus(stream, req.PluginName, req.RuleName, false, "", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 初始化并启动
|
||||
if err := handler.Init(req.Config); err != nil {
|
||||
c.sendPluginStatus(stream, req.PluginName, req.RuleName, false, "", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
localAddr, err := handler.Start()
|
||||
if err != nil {
|
||||
c.sendPluginStatus(stream, req.PluginName, req.RuleName, false, "", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 保存运行中的插件
|
||||
key := req.PluginName + ":" + req.RuleName
|
||||
c.pluginMu.Lock()
|
||||
c.runningPlugins[key] = handler
|
||||
c.pluginMu.Unlock()
|
||||
|
||||
log.Printf("[Client] Plugin %s started at %s", req.PluginName, localAddr)
|
||||
c.sendPluginStatus(stream, req.PluginName, req.RuleName, true, localAddr, "")
|
||||
}
|
||||
|
||||
// sendPluginStatus 发送插件状态响应
|
||||
func (c *Client) sendPluginStatus(stream net.Conn, pluginName, ruleName string, running bool, localAddr, errMsg string) {
|
||||
resp := protocol.ClientPluginStatusResponse{
|
||||
PluginName: pluginName,
|
||||
RuleName: ruleName,
|
||||
Running: running,
|
||||
LocalAddr: localAddr,
|
||||
Error: errMsg,
|
||||
// handleUpdateDownload 处理更新下载请求
|
||||
func (c *Client) handleUpdateDownload(stream net.Conn, msg *protocol.Message) {
|
||||
defer stream.Close()
|
||||
|
||||
var req protocol.UpdateDownloadRequest
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
c.logErrorf("Parse update request error: %v", err)
|
||||
c.sendUpdateResult(stream, false, "invalid request")
|
||||
return
|
||||
}
|
||||
msg, _ := protocol.NewMessage(protocol.MsgTypeClientPluginStatus, resp)
|
||||
|
||||
c.logf("Update download requested: %s", req.DownloadURL)
|
||||
|
||||
// 异步执行更新
|
||||
go func() {
|
||||
if err := c.performSelfUpdate(req.DownloadURL); err != nil {
|
||||
c.logErrorf("Update failed: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
c.sendUpdateResult(stream, true, "update started")
|
||||
}
|
||||
|
||||
// sendUpdateResult 发送更新结果
|
||||
func (c *Client) sendUpdateResult(stream net.Conn, success bool, message string) {
|
||||
result := protocol.UpdateResultResponse{
|
||||
Success: success,
|
||||
Message: message,
|
||||
}
|
||||
msg, _ := protocol.NewMessage(protocol.MsgTypeUpdateResult, result)
|
||||
protocol.WriteMessage(stream, msg)
|
||||
}
|
||||
|
||||
// handleClientPluginConn 处理客户端插件连接
|
||||
func (c *Client) handleClientPluginConn(stream net.Conn, msg *protocol.Message) {
|
||||
var req protocol.ClientPluginConnRequest
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
stream.Close()
|
||||
return
|
||||
}
|
||||
// performSelfUpdate 执行自更新
|
||||
func (c *Client) performSelfUpdate(downloadURL string) error {
|
||||
c.logf("Starting self-update from: %s", downloadURL)
|
||||
|
||||
key := req.PluginName + ":" + req.RuleName
|
||||
c.pluginMu.RLock()
|
||||
handler, ok := c.runningPlugins[key]
|
||||
c.pluginMu.RUnlock()
|
||||
|
||||
if !ok {
|
||||
log.Printf("[Client] Plugin %s not running", key)
|
||||
stream.Close()
|
||||
return
|
||||
}
|
||||
|
||||
// 让插件处理连接
|
||||
handler.HandleConn(stream)
|
||||
}
|
||||
|
||||
// handleJSPluginInstall 处理 JS 插件安装请求
|
||||
func (c *Client) handleJSPluginInstall(stream net.Conn, msg *protocol.Message) {
|
||||
defer stream.Close()
|
||||
|
||||
var req protocol.JSPluginInstallRequest
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
c.sendJSPluginResult(stream, "", false, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("[Client] Installing JS plugin: %s", req.PluginName)
|
||||
|
||||
// 验证官方签名
|
||||
if err := c.verifyJSPluginSignature(req.PluginName, req.Source, req.Signature); err != nil {
|
||||
log.Printf("[Client] JS plugin %s signature verification failed: %v", req.PluginName, err)
|
||||
c.sendJSPluginResult(stream, req.PluginName, false, "signature verification failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
log.Printf("[Client] JS plugin %s signature verified", req.PluginName)
|
||||
|
||||
// 创建 JS 插件
|
||||
jsPlugin, err := script.NewJSPlugin(req.PluginName, req.Source)
|
||||
// 获取当前可执行文件路径
|
||||
currentPath, err := os.Executable()
|
||||
if err != nil {
|
||||
c.sendJSPluginResult(stream, req.PluginName, false, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 注册到 registry
|
||||
if c.pluginRegistry != nil {
|
||||
c.pluginRegistry.RegisterClient(jsPlugin)
|
||||
}
|
||||
|
||||
log.Printf("[Client] JS plugin %s installed", req.PluginName)
|
||||
c.sendJSPluginResult(stream, req.PluginName, true, "")
|
||||
|
||||
// 保存版本信息(防止降级攻击)
|
||||
if c.versionStore != nil {
|
||||
signed, _ := sign.DecodeSignedPlugin(req.Signature)
|
||||
if signed != nil {
|
||||
c.versionStore.SetVersion(req.PluginName, signed.Payload.Version)
|
||||
}
|
||||
}
|
||||
|
||||
// 自动启动
|
||||
if req.AutoStart {
|
||||
c.startJSPlugin(jsPlugin, req)
|
||||
}
|
||||
}
|
||||
|
||||
// sendJSPluginResult 发送 JS 插件安装结果
|
||||
func (c *Client) sendJSPluginResult(stream net.Conn, name string, success bool, errMsg string) {
|
||||
result := protocol.JSPluginInstallResult{
|
||||
PluginName: name,
|
||||
Success: success,
|
||||
Error: errMsg,
|
||||
}
|
||||
msg, _ := protocol.NewMessage(protocol.MsgTypeJSPluginResult, result)
|
||||
protocol.WriteMessage(stream, msg)
|
||||
}
|
||||
|
||||
// startJSPlugin 启动 JS 插件
|
||||
func (c *Client) startJSPlugin(handler plugin.ClientPlugin, req protocol.JSPluginInstallRequest) {
|
||||
if err := handler.Init(req.Config); err != nil {
|
||||
log.Printf("[Client] JS plugin %s init error: %v", req.PluginName, err)
|
||||
return
|
||||
}
|
||||
|
||||
localAddr, err := handler.Start()
|
||||
if err != nil {
|
||||
log.Printf("[Client] JS plugin %s start error: %v", req.PluginName, err)
|
||||
return
|
||||
}
|
||||
|
||||
key := req.PluginName + ":" + req.RuleName
|
||||
c.pluginMu.Lock()
|
||||
c.runningPlugins[key] = handler
|
||||
c.pluginMu.Unlock()
|
||||
|
||||
log.Printf("[Client] JS plugin %s started at %s", req.PluginName, localAddr)
|
||||
}
|
||||
|
||||
// verifyJSPluginSignature 验证 JS 插件签名
|
||||
func (c *Client) verifyJSPluginSignature(pluginName, source, signature string) error {
|
||||
if signature == "" {
|
||||
return fmt.Errorf("missing signature")
|
||||
}
|
||||
|
||||
// 解码签名
|
||||
signed, err := sign.DecodeSignedPlugin(signature)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode signature: %w", err)
|
||||
}
|
||||
|
||||
// 根据 KeyID 获取对应公钥
|
||||
pubKey, err := sign.GetPublicKeyByID(signed.Payload.KeyID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get public key: %w", err)
|
||||
}
|
||||
|
||||
// 验证插件名称匹配
|
||||
if signed.Payload.Name != pluginName {
|
||||
return fmt.Errorf("plugin name mismatch: expected %s, got %s",
|
||||
pluginName, signed.Payload.Name)
|
||||
}
|
||||
|
||||
// 验证签名和源码哈希
|
||||
if err := sign.VerifyPlugin(pubKey, signed, source); err != nil {
|
||||
c.logErrorf("Update failed: cannot get executable path: %v", err)
|
||||
return err
|
||||
}
|
||||
currentPath, _ = filepath.EvalSymlinks(currentPath)
|
||||
|
||||
// 检查版本降级攻击
|
||||
if c.versionStore != nil {
|
||||
currentVer := c.versionStore.GetVersion(pluginName)
|
||||
if currentVer != "" {
|
||||
cmp := sign.CompareVersions(signed.Payload.Version, currentVer)
|
||||
if cmp < 0 {
|
||||
return fmt.Errorf("version downgrade rejected: %s < %s",
|
||||
signed.Payload.Version, currentVer)
|
||||
// 预检查:验证是否有写权限(在下载前检查,避免浪费带宽)
|
||||
// Windows 跳过预检查,因为 Windows 更新通过 batch 脚本以提升权限执行
|
||||
// 非 Windows:原始路径 → DataDir → 临时目录,逐级回退
|
||||
fallbackDir := ""
|
||||
if runtime.GOOS != "windows" {
|
||||
if err := c.checkUpdatePermissions(currentPath); err != nil {
|
||||
// 尝试 DataDir
|
||||
fallbackDir = c.DataDir
|
||||
testFile := filepath.Join(fallbackDir, ".gotunnel_update_test")
|
||||
if f, err := os.Create(testFile); err != nil {
|
||||
// DataDir 也不可写,回退到临时目录
|
||||
fallbackDir = os.TempDir()
|
||||
c.logf("DataDir not writable, falling back to temp directory: %s", fallbackDir)
|
||||
} else {
|
||||
f.Close()
|
||||
os.Remove(testFile)
|
||||
c.logf("Original path not writable, falling back to data directory: %s", fallbackDir)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 使用共享的下载和解压逻辑
|
||||
c.logf("Downloading update package...")
|
||||
binaryPath, cleanup, err := update.DownloadAndExtract(downloadURL, "client")
|
||||
if err != nil {
|
||||
c.logErrorf("Update failed: download/extract error: %v", err)
|
||||
return err
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
// Windows 需要特殊处理
|
||||
if runtime.GOOS == "windows" {
|
||||
return performWindowsClientUpdate(binaryPath, currentPath, c.ServerAddr, c.Token)
|
||||
}
|
||||
|
||||
// 确定目标路径
|
||||
targetPath := currentPath
|
||||
if fallbackDir != "" {
|
||||
targetPath = filepath.Join(fallbackDir, filepath.Base(currentPath))
|
||||
c.logf("Will install to fallback path: %s", targetPath)
|
||||
}
|
||||
|
||||
if fallbackDir == "" {
|
||||
// 原地替换:备份 → 复制 → 清理
|
||||
backupPath := currentPath + ".bak"
|
||||
|
||||
c.logf("Backing up current binary...")
|
||||
if err := os.Rename(currentPath, backupPath); err != nil {
|
||||
c.logErrorf("Update failed: cannot backup current binary: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
c.logf("Installing new binary...")
|
||||
if err := update.CopyFile(binaryPath, currentPath); err != nil {
|
||||
os.Rename(backupPath, currentPath)
|
||||
c.logErrorf("Update failed: cannot install new binary: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.Chmod(currentPath, 0755); err != nil {
|
||||
os.Rename(backupPath, currentPath)
|
||||
c.logErrorf("Update failed: cannot set execute permission: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
os.Remove(backupPath)
|
||||
} else {
|
||||
// 回退路径:直接复制到回退目录
|
||||
c.logf("Installing new binary to data directory...")
|
||||
if err := update.CopyFile(binaryPath, targetPath); err != nil {
|
||||
c.logErrorf("Update failed: cannot install new binary: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.Chmod(targetPath, 0755); err != nil {
|
||||
c.logErrorf("Update failed: cannot set execute permission: %v", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
c.logf("Update completed successfully, restarting...")
|
||||
|
||||
// 重启进程(从新路径启动)
|
||||
restartClientProcess(targetPath, c.ServerAddr, c.Token)
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkUpdatePermissions 检查是否有更新权限
|
||||
func (c *Client) checkUpdatePermissions(execPath string) error {
|
||||
// 检查可执行文件所在目录是否可写
|
||||
dir := filepath.Dir(execPath)
|
||||
testFile := filepath.Join(dir, ".gotunnel_update_test")
|
||||
|
||||
f, err := os.Create(testFile)
|
||||
if err != nil {
|
||||
c.logErrorf("No write permission to directory: %s", dir)
|
||||
return err
|
||||
}
|
||||
f.Close()
|
||||
os.Remove(testFile)
|
||||
|
||||
// 检查可执行文件本身是否可写
|
||||
f, err = os.OpenFile(execPath, os.O_WRONLY, 0)
|
||||
if err != nil {
|
||||
c.logErrorf("No write permission to executable: %s", execPath)
|
||||
return err
|
||||
}
|
||||
f.Close()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// performWindowsClientUpdate Windows 平台更新
|
||||
func performWindowsClientUpdate(newFile, currentPath, serverAddr, token string) error {
|
||||
// 创建批处理脚本
|
||||
args := fmt.Sprintf(`-s "%s" -t "%s"`, serverAddr, token)
|
||||
batchScript := fmt.Sprintf(`@echo off
|
||||
:: Check for admin rights, request UAC elevation if needed
|
||||
net session >nul 2>&1
|
||||
if %%errorlevel%% neq 0 (
|
||||
powershell -Command "Start-Process cmd -ArgumentList '/C \\"\"%%~f0\"\"' -Verb RunAs"
|
||||
exit /b
|
||||
)
|
||||
ping 127.0.0.1 -n 2 > nul
|
||||
del "%s"
|
||||
move "%s" "%s"
|
||||
start "" "%s" %s
|
||||
del "%%~f0"
|
||||
`, currentPath, newFile, currentPath, currentPath, args)
|
||||
|
||||
batchPath := filepath.Join(os.TempDir(), "gotunnel_client_update.bat")
|
||||
if err := os.WriteFile(batchPath, []byte(batchScript), 0755); err != nil {
|
||||
return fmt.Errorf("write batch: %w", err)
|
||||
}
|
||||
|
||||
cmd := exec.Command("cmd", "/C", "start", "/MIN", batchPath)
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("start batch: %w", err)
|
||||
}
|
||||
|
||||
// 退出当前进程
|
||||
os.Exit(0)
|
||||
return nil
|
||||
}
|
||||
|
||||
// restartClientProcess 重启客户端进程
|
||||
func restartClientProcess(path, serverAddr, token string) {
|
||||
args := []string{"-s", serverAddr, "-t", token}
|
||||
|
||||
cmd := exec.Command(path, args...)
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
cmd.Start()
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// handleLogRequest 处理日志请求
|
||||
func (c *Client) handleLogRequest(stream net.Conn, msg *protocol.Message) {
|
||||
if c.logger == nil {
|
||||
stream.Close()
|
||||
return
|
||||
}
|
||||
|
||||
var req protocol.LogRequest
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
stream.Close()
|
||||
return
|
||||
}
|
||||
|
||||
c.logger.Printf("Log request received: session=%s, follow=%v", req.SessionID, req.Follow)
|
||||
|
||||
// 发送历史日志
|
||||
entries := c.logger.GetRecentLogs(req.Lines, req.Level)
|
||||
if len(entries) > 0 {
|
||||
data := protocol.LogData{
|
||||
SessionID: req.SessionID,
|
||||
Entries: entries,
|
||||
EOF: !req.Follow,
|
||||
}
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeLogData, data)
|
||||
if err := protocol.WriteMessage(stream, respMsg); err != nil {
|
||||
stream.Close()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 如果不需要持续推送,关闭流
|
||||
if !req.Follow {
|
||||
stream.Close()
|
||||
return
|
||||
}
|
||||
|
||||
// 订阅新日志
|
||||
ch := c.logger.Subscribe(req.SessionID)
|
||||
defer c.logger.Unsubscribe(req.SessionID)
|
||||
defer stream.Close()
|
||||
|
||||
// 持续推送新日志
|
||||
for entry := range ch {
|
||||
// 应用级别过滤
|
||||
if req.Level != "" && entry.Level != req.Level {
|
||||
continue
|
||||
}
|
||||
|
||||
data := protocol.LogData{
|
||||
SessionID: req.SessionID,
|
||||
Entries: []protocol.LogEntry{entry},
|
||||
EOF: false,
|
||||
}
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeLogData, data)
|
||||
if err := protocol.WriteMessage(stream, respMsg); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleLogStop 处理停止日志流请求
|
||||
func (c *Client) handleLogStop(stream net.Conn, msg *protocol.Message) {
|
||||
defer stream.Close()
|
||||
|
||||
if c.logger == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var req protocol.LogStopRequest
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
c.logger.Unsubscribe(req.SessionID)
|
||||
}
|
||||
|
||||
// handleSystemStatsRequest 处理系统状态请求
|
||||
func (c *Client) handleSystemStatsRequest(stream net.Conn, msg *protocol.Message) {
|
||||
defer stream.Close()
|
||||
|
||||
stats, err := utils.GetSystemStats()
|
||||
if err != nil {
|
||||
log.Printf("Failed to get system stats: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
resp := protocol.SystemStatsResponse{
|
||||
CPUUsage: stats.CPUUsage,
|
||||
MemoryTotal: stats.MemoryTotal,
|
||||
MemoryUsed: stats.MemoryUsed,
|
||||
MemoryUsage: stats.MemoryUsage,
|
||||
DiskTotal: stats.DiskTotal,
|
||||
DiskUsed: stats.DiskUsed,
|
||||
DiskUsage: stats.DiskUsage,
|
||||
}
|
||||
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeSystemStatsResponse, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
}
|
||||
|
||||
// handleScreenshotRequest 处理截图请求
|
||||
func (c *Client) handleScreenshotRequest(stream net.Conn, msg *protocol.Message) {
|
||||
defer stream.Close()
|
||||
|
||||
var req protocol.ScreenshotRequest
|
||||
msg.ParsePayload(&req)
|
||||
|
||||
// 捕获截图
|
||||
data, width, height, err := utils.CaptureScreenshot(req.Quality)
|
||||
if err != nil {
|
||||
c.logErrorf("Screenshot capture failed: %v", err)
|
||||
resp := protocol.ScreenshotResponse{Error: err.Error()}
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeScreenshotResponse, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
return
|
||||
}
|
||||
|
||||
// 编码为 Base64
|
||||
base64Data := base64.StdEncoding.EncodeToString(data)
|
||||
|
||||
resp := protocol.ScreenshotResponse{
|
||||
Data: base64Data,
|
||||
Width: width,
|
||||
Height: height,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
}
|
||||
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeScreenshotResponse, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
}
|
||||
|
||||
// handleShellExecuteRequest 处理 Shell 执行请求
|
||||
func (c *Client) handleShellExecuteRequest(stream net.Conn, msg *protocol.Message) {
|
||||
defer stream.Close()
|
||||
|
||||
var req protocol.ShellExecuteRequest
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
resp := protocol.ShellExecuteResponse{Error: err.Error(), ExitCode: -1}
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeShellExecuteResponse, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
return
|
||||
}
|
||||
|
||||
// 设置默认超时
|
||||
timeout := req.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = 30
|
||||
}
|
||||
|
||||
c.logf("Executing shell command: %s", req.Command)
|
||||
|
||||
// 根据操作系统选择 shell
|
||||
var cmd *exec.Cmd
|
||||
if runtime.GOOS == "windows" {
|
||||
cmd = exec.Command("cmd", "/C", req.Command)
|
||||
} else {
|
||||
cmd = exec.Command("sh", "-c", req.Command)
|
||||
}
|
||||
|
||||
// 设置超时上下文
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
|
||||
defer cancel()
|
||||
cmd = exec.CommandContext(ctx, cmd.Path, cmd.Args[1:]...)
|
||||
|
||||
// 执行命令并获取输出
|
||||
output, err := cmd.CombinedOutput()
|
||||
|
||||
exitCode := 0
|
||||
if err != nil {
|
||||
if exitErr, ok := err.(*exec.ExitError); ok {
|
||||
exitCode = exitErr.ExitCode()
|
||||
} else if ctx.Err() == context.DeadlineExceeded {
|
||||
resp := protocol.ShellExecuteResponse{
|
||||
Output: string(output),
|
||||
ExitCode: -1,
|
||||
Error: "command timeout",
|
||||
}
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeShellExecuteResponse, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
return
|
||||
} else {
|
||||
resp := protocol.ShellExecuteResponse{
|
||||
Output: string(output),
|
||||
ExitCode: -1,
|
||||
Error: err.Error(),
|
||||
}
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeShellExecuteResponse, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
resp := protocol.ShellExecuteResponse{
|
||||
Output: string(output),
|
||||
ExitCode: exitCode,
|
||||
}
|
||||
|
||||
respMsg, _ := protocol.NewMessage(protocol.MsgTypeShellExecuteResponse, resp)
|
||||
protocol.WriteMessage(stream, respMsg)
|
||||
}
|
||||
|
||||
236
internal/client/tunnel/logger.go
Normal file
236
internal/client/tunnel/logger.go
Normal file
@@ -0,0 +1,236 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"container/ring"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gotunnel/pkg/protocol"
|
||||
)
|
||||
|
||||
const (
|
||||
maxBufferSize = 1000 // 环形缓冲区最大条目数
|
||||
logFilePattern = "client.%s.log" // 日志文件名模式
|
||||
)
|
||||
|
||||
// LogLevel 日志级别
|
||||
type LogLevel int
|
||||
|
||||
const (
|
||||
LevelDebug LogLevel = iota
|
||||
LevelInfo
|
||||
LevelWarn
|
||||
LevelError
|
||||
)
|
||||
|
||||
// Logger 客户端日志收集器
|
||||
type Logger struct {
|
||||
dataDir string
|
||||
buffer *ring.Ring
|
||||
bufferMu sync.RWMutex
|
||||
file *os.File
|
||||
fileMu sync.Mutex
|
||||
fileDate string
|
||||
subscribers map[string]chan protocol.LogEntry
|
||||
subMu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewLogger 创建新的日志收集器
|
||||
func NewLogger(dataDir string) (*Logger, error) {
|
||||
l := &Logger{
|
||||
dataDir: dataDir,
|
||||
buffer: ring.New(maxBufferSize),
|
||||
subscribers: make(map[string]chan protocol.LogEntry),
|
||||
}
|
||||
|
||||
// 确保日志目录存在
|
||||
logDir := filepath.Join(dataDir, "logs")
|
||||
if err := os.MkdirAll(logDir, 0755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// Printf 记录日志 (兼容 log.Printf)
|
||||
func (l *Logger) Printf(format string, args ...interface{}) {
|
||||
l.log(LevelInfo, "client", format, args...)
|
||||
}
|
||||
|
||||
// Infof 记录信息日志
|
||||
func (l *Logger) Infof(format string, args ...interface{}) {
|
||||
l.log(LevelInfo, "client", format, args...)
|
||||
}
|
||||
|
||||
// Warnf 记录警告日志
|
||||
func (l *Logger) Warnf(format string, args ...interface{}) {
|
||||
l.log(LevelWarn, "client", format, args...)
|
||||
}
|
||||
|
||||
// Errorf 记录错误日志
|
||||
func (l *Logger) Errorf(format string, args ...interface{}) {
|
||||
l.log(LevelError, "client", format, args...)
|
||||
}
|
||||
|
||||
// Debugf 记录调试日志
|
||||
func (l *Logger) Debugf(format string, args ...interface{}) {
|
||||
l.log(LevelDebug, "client", format, args...)
|
||||
}
|
||||
|
||||
// PluginLog 记录插件日志
|
||||
func (l *Logger) PluginLog(pluginName, level, format string, args ...interface{}) {
|
||||
var lvl LogLevel
|
||||
switch level {
|
||||
case "debug":
|
||||
lvl = LevelDebug
|
||||
case "warn":
|
||||
lvl = LevelWarn
|
||||
case "error":
|
||||
lvl = LevelError
|
||||
default:
|
||||
lvl = LevelInfo
|
||||
}
|
||||
l.log(lvl, "plugin:"+pluginName, format, args...)
|
||||
}
|
||||
|
||||
func (l *Logger) log(level LogLevel, source, format string, args ...interface{}) {
|
||||
entry := protocol.LogEntry{
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
Level: levelToString(level),
|
||||
Message: fmt.Sprintf(format, args...),
|
||||
Source: source,
|
||||
}
|
||||
|
||||
// 注意:不在这里输出到标准输出,因为调用方(logf/logErrorf/logWarnf)已经调用了 log.Print
|
||||
// 这里只负责:缓冲区存储、文件写入、订阅者通知
|
||||
|
||||
// 添加到环形缓冲区
|
||||
l.bufferMu.Lock()
|
||||
l.buffer.Value = entry
|
||||
l.buffer = l.buffer.Next()
|
||||
l.bufferMu.Unlock()
|
||||
|
||||
// 写入文件
|
||||
l.writeToFile(entry)
|
||||
|
||||
// 通知订阅者
|
||||
l.notifySubscribers(entry)
|
||||
}
|
||||
|
||||
// Subscribe 订阅日志流
|
||||
func (l *Logger) Subscribe(sessionID string) <-chan protocol.LogEntry {
|
||||
ch := make(chan protocol.LogEntry, 100)
|
||||
l.subMu.Lock()
|
||||
l.subscribers[sessionID] = ch
|
||||
l.subMu.Unlock()
|
||||
return ch
|
||||
}
|
||||
|
||||
// Unsubscribe 取消订阅
|
||||
func (l *Logger) Unsubscribe(sessionID string) {
|
||||
l.subMu.Lock()
|
||||
if ch, ok := l.subscribers[sessionID]; ok {
|
||||
close(ch)
|
||||
delete(l.subscribers, sessionID)
|
||||
}
|
||||
l.subMu.Unlock()
|
||||
}
|
||||
|
||||
// GetRecentLogs 获取最近的日志
|
||||
func (l *Logger) GetRecentLogs(lines int, level string) []protocol.LogEntry {
|
||||
l.bufferMu.RLock()
|
||||
defer l.bufferMu.RUnlock()
|
||||
|
||||
var entries []protocol.LogEntry
|
||||
l.buffer.Do(func(v interface{}) {
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
entry := v.(protocol.LogEntry)
|
||||
// 应用级别过滤
|
||||
if level != "" && entry.Level != level {
|
||||
return
|
||||
}
|
||||
entries = append(entries, entry)
|
||||
})
|
||||
|
||||
// 如果指定了行数,返回最后 N 行
|
||||
if lines > 0 && len(entries) > lines {
|
||||
entries = entries[len(entries)-lines:]
|
||||
}
|
||||
|
||||
return entries
|
||||
}
|
||||
|
||||
// Close 关闭日志收集器
|
||||
func (l *Logger) Close() {
|
||||
l.fileMu.Lock()
|
||||
if l.file != nil {
|
||||
l.file.Close()
|
||||
l.file = nil
|
||||
}
|
||||
l.fileMu.Unlock()
|
||||
|
||||
l.subMu.Lock()
|
||||
for _, ch := range l.subscribers {
|
||||
close(ch)
|
||||
}
|
||||
l.subscribers = make(map[string]chan protocol.LogEntry)
|
||||
l.subMu.Unlock()
|
||||
}
|
||||
|
||||
func (l *Logger) writeToFile(entry protocol.LogEntry) {
|
||||
l.fileMu.Lock()
|
||||
defer l.fileMu.Unlock()
|
||||
|
||||
today := time.Now().Format("2006-01-02")
|
||||
if l.fileDate != today {
|
||||
if l.file != nil {
|
||||
l.file.Close()
|
||||
}
|
||||
|
||||
logPath := filepath.Join(l.dataDir, "logs", fmt.Sprintf(logFilePattern, today))
|
||||
f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
l.file = f
|
||||
l.fileDate = today
|
||||
}
|
||||
|
||||
if l.file != nil {
|
||||
fmt.Fprintf(l.file, "%d|%s|%s|%s\n",
|
||||
entry.Timestamp, entry.Level, entry.Source, entry.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Logger) notifySubscribers(entry protocol.LogEntry) {
|
||||
l.subMu.RLock()
|
||||
defer l.subMu.RUnlock()
|
||||
|
||||
for _, ch := range l.subscribers {
|
||||
select {
|
||||
case ch <- entry:
|
||||
default:
|
||||
// 订阅者太慢,丢弃日志
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func levelToString(level LogLevel) string {
|
||||
switch level {
|
||||
case LevelDebug:
|
||||
return "debug"
|
||||
case LevelInfo:
|
||||
return "info"
|
||||
case LevelWarn:
|
||||
return "warn"
|
||||
case LevelError:
|
||||
return "error"
|
||||
default:
|
||||
return "info"
|
||||
}
|
||||
}
|
||||
152
internal/client/tunnel/machine_id.go
Normal file
152
internal/client/tunnel/machine_id.go
Normal file
@@ -0,0 +1,152 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// getMachineID builds a stable fingerprint from multiple host identifiers
|
||||
// and hashes the combined result into the client ID we expose externally.
|
||||
func getMachineID() string {
|
||||
return hashID(strings.Join(collectMachineIDParts(), "|"))
|
||||
}
|
||||
|
||||
func collectMachineIDParts() []string {
|
||||
parts := []string{"os=" + runtime.GOOS, "arch=" + runtime.GOARCH}
|
||||
|
||||
if id := getSystemMachineID(); id != "" {
|
||||
parts = append(parts, "system="+id)
|
||||
}
|
||||
|
||||
if hostname, err := os.Hostname(); err == nil && hostname != "" {
|
||||
parts = append(parts, "host="+hostname)
|
||||
}
|
||||
|
||||
if macs := getMACAddresses(); len(macs) > 0 {
|
||||
parts = append(parts, "macs="+strings.Join(macs, ","))
|
||||
}
|
||||
|
||||
if names := getInterfaceNames(); len(names) > 0 {
|
||||
parts = append(parts, "ifaces="+strings.Join(names, ","))
|
||||
}
|
||||
|
||||
return parts
|
||||
}
|
||||
|
||||
func getSystemMachineID() string {
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
return getLinuxMachineID()
|
||||
case "darwin":
|
||||
return getDarwinMachineID()
|
||||
case "windows":
|
||||
return getWindowsMachineID()
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func getLinuxMachineID() string {
|
||||
if data, err := os.ReadFile("/etc/machine-id"); err == nil {
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
if data, err := os.ReadFile("/var/lib/dbus/machine-id"); err == nil {
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func getDarwinMachineID() string {
|
||||
cmd := exec.Command("ioreg", "-rd1", "-c", "IOPlatformExpertDevice")
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
for _, line := range strings.Split(string(output), "\n") {
|
||||
if !strings.Contains(line, "IOPlatformUUID") {
|
||||
continue
|
||||
}
|
||||
|
||||
parts := strings.Split(line, "=")
|
||||
if len(parts) != 2 {
|
||||
continue
|
||||
}
|
||||
|
||||
uuid := strings.TrimSpace(parts[1])
|
||||
return strings.Trim(uuid, "\"")
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func getWindowsMachineID() string {
|
||||
cmd := exec.Command("reg", "query", `HKLM\SOFTWARE\Microsoft\Cryptography`, "/v", "MachineGuid")
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
for _, line := range strings.Split(string(output), "\n") {
|
||||
if !strings.Contains(line, "MachineGuid") {
|
||||
continue
|
||||
}
|
||||
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) >= 3 {
|
||||
return fields[len(fields)-1]
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func getMACAddresses() []string {
|
||||
interfaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
macs := make([]string, 0, len(interfaces))
|
||||
for _, iface := range interfaces {
|
||||
if iface.Flags&net.FlagLoopback != 0 {
|
||||
continue
|
||||
}
|
||||
if len(iface.HardwareAddr) == 0 {
|
||||
continue
|
||||
}
|
||||
macs = append(macs, iface.HardwareAddr.String())
|
||||
}
|
||||
|
||||
sort.Strings(macs)
|
||||
return macs
|
||||
}
|
||||
|
||||
func getInterfaceNames() []string {
|
||||
interfaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
names := make([]string, 0, len(interfaces))
|
||||
for _, iface := range interfaces {
|
||||
if iface.Flags&net.FlagLoopback != 0 {
|
||||
continue
|
||||
}
|
||||
names = append(names, iface.Name)
|
||||
}
|
||||
|
||||
sort.Strings(names)
|
||||
return names
|
||||
}
|
||||
|
||||
func hashID(id string) string {
|
||||
hash := sha256.Sum256([]byte(id))
|
||||
return hex.EncodeToString(hash[:])[:16]
|
||||
}
|
||||
@@ -2,10 +2,8 @@ package app
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gotunnel/internal/server/config"
|
||||
"github.com/gotunnel/internal/server/db"
|
||||
@@ -13,86 +11,52 @@ import (
|
||||
"github.com/gotunnel/pkg/auth"
|
||||
)
|
||||
|
||||
//go:embed dist/*
|
||||
//go:embed all:dist/*
|
||||
var staticFiles embed.FS
|
||||
|
||||
// spaHandler SPA路由处理器
|
||||
type spaHandler struct {
|
||||
fs http.FileSystem
|
||||
}
|
||||
|
||||
func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Path
|
||||
f, err := h.fs.Open(path)
|
||||
if err != nil {
|
||||
f, err = h.fs.Open("index.html")
|
||||
if err != nil {
|
||||
http.Error(w, "Not Found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
stat, _ := f.Stat()
|
||||
if stat.IsDir() {
|
||||
f, err = h.fs.Open(path + "/index.html")
|
||||
if err != nil {
|
||||
f, _ = h.fs.Open("index.html")
|
||||
}
|
||||
}
|
||||
http.ServeContent(w, r, path, stat.ModTime(), f.(io.ReadSeeker))
|
||||
}
|
||||
|
||||
// WebServer Web控制台服务
|
||||
type WebServer struct {
|
||||
ClientStore db.ClientStore
|
||||
Server router.ServerInterface
|
||||
Config *config.ServerConfig
|
||||
ConfigPath string
|
||||
JSPluginStore db.JSPluginStore
|
||||
ClientStore db.ClientStore
|
||||
Server router.ServerInterface
|
||||
Config *config.ServerConfig
|
||||
ConfigPath string
|
||||
TrafficStore db.TrafficStore
|
||||
}
|
||||
|
||||
// NewWebServer 创建Web服务
|
||||
func NewWebServer(cs db.ClientStore, srv router.ServerInterface, cfg *config.ServerConfig, cfgPath string, jsStore db.JSPluginStore) *WebServer {
|
||||
func NewWebServer(cs db.ClientStore, srv router.ServerInterface, cfg *config.ServerConfig, cfgPath string, store db.Store) *WebServer {
|
||||
return &WebServer{
|
||||
ClientStore: cs,
|
||||
Server: srv,
|
||||
Config: cfg,
|
||||
ConfigPath: cfgPath,
|
||||
JSPluginStore: jsStore,
|
||||
ClientStore: cs,
|
||||
Server: srv,
|
||||
Config: cfg,
|
||||
ConfigPath: cfgPath,
|
||||
TrafficStore: store,
|
||||
}
|
||||
}
|
||||
|
||||
// Run 启动Web服务
|
||||
// Run 启动Web服务 (无认证,仅用于开发)
|
||||
func (w *WebServer) Run(addr string) error {
|
||||
r := router.New()
|
||||
router.RegisterRoutes(r, w)
|
||||
|
||||
// 使用默认凭据和 JWT
|
||||
jwtAuth := auth.NewJWTAuth("dev-secret", 24)
|
||||
r.SetupRoutes(w, jwtAuth, "admin", "admin")
|
||||
|
||||
// 静态文件
|
||||
staticFS, err := fs.Sub(staticFiles, "dist")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.Handle("/", spaHandler{fs: http.FS(staticFS)})
|
||||
r.SetupStaticFiles(staticFS)
|
||||
|
||||
log.Printf("[Web] Console listening on %s", addr)
|
||||
return http.ListenAndServe(addr, r.Handler())
|
||||
return r.Engine.Run(addr)
|
||||
}
|
||||
|
||||
// RunWithAuth 启动带认证的Web服务
|
||||
// RunWithAuth 启动带 Basic Auth 的 Web 服务 (已废弃,使用 RunWithJWT)
|
||||
func (w *WebServer) RunWithAuth(addr, username, password string) error {
|
||||
r := router.New()
|
||||
router.RegisterRoutes(r, w)
|
||||
|
||||
staticFS, err := fs.Sub(staticFiles, "dist")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.Handle("/", spaHandler{fs: http.FS(staticFS)})
|
||||
|
||||
auth := &router.AuthConfig{Username: username, Password: password}
|
||||
handler := router.BasicAuthMiddleware(auth, r.Handler())
|
||||
log.Printf("[Web] Console listening on %s (auth enabled)", addr)
|
||||
return http.ListenAndServe(addr, handler)
|
||||
// 转发到 JWT 认证
|
||||
return w.RunWithJWT(addr, username, password, "auto-generated-secret")
|
||||
}
|
||||
|
||||
// RunWithJWT 启动带 JWT 认证的 Web 服务
|
||||
@@ -102,26 +66,18 @@ func (w *WebServer) RunWithJWT(addr, username, password, jwtSecret string) error
|
||||
// JWT 认证器
|
||||
jwtAuth := auth.NewJWTAuth(jwtSecret, 24) // 24小时过期
|
||||
|
||||
// 注册认证路由(不需要认证)
|
||||
authHandler := router.NewAuthHandler(username, password, jwtAuth)
|
||||
router.RegisterAuthRoutes(r, authHandler)
|
||||
|
||||
// 注册业务路由
|
||||
router.RegisterRoutes(r, w)
|
||||
// 设置所有路由
|
||||
r.SetupRoutes(w, jwtAuth, username, password)
|
||||
|
||||
// 静态文件
|
||||
staticFS, err := fs.Sub(staticFiles, "dist")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.Handle("/", spaHandler{fs: http.FS(staticFS)})
|
||||
|
||||
// JWT 中间件,只对 /api/ 路径进行认证(排除 /api/auth/)
|
||||
skipPaths := []string{"/api/auth/"}
|
||||
handler := router.JWTMiddleware(jwtAuth, skipPaths, r.Handler())
|
||||
r.SetupStaticFiles(staticFS)
|
||||
|
||||
log.Printf("[Web] Console listening on %s (JWT auth enabled)", addr)
|
||||
return http.ListenAndServe(addr, handler)
|
||||
return r.Engine.Run(addr)
|
||||
}
|
||||
|
||||
// GetClientStore 获取客户端存储
|
||||
@@ -149,7 +105,7 @@ func (w *WebServer) SaveConfig() error {
|
||||
return config.SaveServerConfig(w.ConfigPath, w.Config)
|
||||
}
|
||||
|
||||
// GetJSPluginStore 获取 JS 插件存储
|
||||
func (w *WebServer) GetJSPluginStore() db.JSPluginStore {
|
||||
return w.JSPluginStore
|
||||
// GetTrafficStore 获取流量存储
|
||||
func (w *WebServer) GetTrafficStore() db.TrafficStore {
|
||||
return w.TrafficStore
|
||||
}
|
||||
|
||||
@@ -10,53 +10,24 @@ import (
|
||||
|
||||
// ServerConfig 服务端配置
|
||||
type ServerConfig struct {
|
||||
Server ServerSettings `yaml:"server"`
|
||||
Web WebSettings `yaml:"web"`
|
||||
PluginStore PluginStoreSettings `yaml:"plugin_store"`
|
||||
JSPlugins []JSPluginConfig `yaml:"js_plugins,omitempty"`
|
||||
}
|
||||
|
||||
// JSPluginConfig JS 插件配置
|
||||
type JSPluginConfig struct {
|
||||
Name string `yaml:"name"`
|
||||
Path string `yaml:"path"` // JS 文件路径
|
||||
SigPath string `yaml:"sig_path,omitempty"` // 签名文件路径 (默认为 path + ".sig")
|
||||
AutoPush []string `yaml:"auto_push,omitempty"` // 自动推送到的客户端 ID 列表
|
||||
Config map[string]string `yaml:"config,omitempty"` // 插件配置
|
||||
AutoStart bool `yaml:"auto_start,omitempty"` // 是否自动启动
|
||||
}
|
||||
|
||||
// PluginStoreSettings 插件仓库设置
|
||||
type PluginStoreSettings struct {
|
||||
URL string `yaml:"url"` // 插件仓库 URL,为空则使用默认值
|
||||
}
|
||||
|
||||
// 默认插件仓库 URL
|
||||
const DefaultPluginStoreURL = "https://git.92coco.cn:8443/flik/GoTunnel-Plugins/raw/branch/main/store.json"
|
||||
|
||||
// GetPluginStoreURL 获取插件仓库 URL
|
||||
func (s *PluginStoreSettings) GetPluginStoreURL() string {
|
||||
if s.URL != "" {
|
||||
return s.URL
|
||||
}
|
||||
return DefaultPluginStoreURL
|
||||
Server ServerSettings `yaml:"server"`
|
||||
}
|
||||
|
||||
// ServerSettings 服务端设置
|
||||
type ServerSettings struct {
|
||||
BindAddr string `yaml:"bind_addr"`
|
||||
BindPort int `yaml:"bind_port"`
|
||||
Token string `yaml:"token"`
|
||||
HeartbeatSec int `yaml:"heartbeat_sec"`
|
||||
HeartbeatTimeout int `yaml:"heartbeat_timeout"`
|
||||
DBPath string `yaml:"db_path"`
|
||||
TLSDisabled bool `yaml:"tls_disabled"` // 默认启用 TLS,设置为 true 禁用
|
||||
BindAddr string `yaml:"bind_addr"`
|
||||
BindPort int `yaml:"bind_port"`
|
||||
Token string `yaml:"token"`
|
||||
HeartbeatSec int `yaml:"heartbeat_sec"`
|
||||
HeartbeatTimeout int `yaml:"heartbeat_timeout"`
|
||||
DBPath string `yaml:"db_path"`
|
||||
TLSDisabled bool `yaml:"tls_disabled"`
|
||||
Web WebSettings `yaml:"web"`
|
||||
}
|
||||
|
||||
// WebSettings Web控制台设置
|
||||
type WebSettings struct {
|
||||
Enabled bool `yaml:"enabled"`
|
||||
BindAddr string `yaml:"bind_addr"`
|
||||
BindPort int `yaml:"bind_port"`
|
||||
Username string `yaml:"username"`
|
||||
Password string `yaml:"password"`
|
||||
@@ -99,12 +70,9 @@ func setDefaults(cfg *ServerConfig) {
|
||||
}
|
||||
|
||||
// Web 默认启用
|
||||
if cfg.Web.BindAddr == "" {
|
||||
cfg.Web.BindAddr = "0.0.0.0"
|
||||
}
|
||||
if cfg.Web.BindPort == 0 {
|
||||
cfg.Web.BindPort = 7500
|
||||
cfg.Web.Enabled = true
|
||||
if cfg.Server.Web.BindPort == 0 {
|
||||
cfg.Server.Web.BindPort = 7500
|
||||
cfg.Server.Web.Enabled = true
|
||||
}
|
||||
|
||||
// Token 未配置时自动生成 32 位
|
||||
@@ -126,11 +94,11 @@ func generateToken(length int) string {
|
||||
|
||||
// GenerateWebCredentials 生成 Web 控制台凭据
|
||||
func GenerateWebCredentials(cfg *ServerConfig) bool {
|
||||
if cfg.Web.Username == "" {
|
||||
cfg.Web.Username = "admin"
|
||||
if cfg.Server.Web.Username == "" {
|
||||
cfg.Server.Web.Username = "admin"
|
||||
}
|
||||
if cfg.Web.Password == "" {
|
||||
cfg.Web.Password = generateToken(16)
|
||||
if cfg.Server.Web.Password == "" {
|
||||
cfg.Server.Web.Password = generateToken(16)
|
||||
return true // 表示生成了新密码
|
||||
}
|
||||
return false
|
||||
|
||||
45
internal/server/db/install_token.go
Normal file
45
internal/server/db/install_token.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package db
|
||||
|
||||
// CreateInstallToken 创建安装token
|
||||
func (s *SQLiteStore) CreateInstallToken(token *InstallToken) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
_, err := s.db.Exec(`INSERT INTO install_tokens (token, client_id, created_at, used) VALUES (?, '', ?, ?)`,
|
||||
token.Token, token.CreatedAt, 0)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetInstallToken 获取安装token
|
||||
func (s *SQLiteStore) GetInstallToken(token string) (*InstallToken, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
var t InstallToken
|
||||
var used int
|
||||
err := s.db.QueryRow(`SELECT token, created_at, used FROM install_tokens WHERE token = ?`, token).
|
||||
Scan(&t.Token, &t.CreatedAt, &used)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.Used = used == 1
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
// MarkTokenUsed 标记token已使用
|
||||
func (s *SQLiteStore) MarkTokenUsed(token string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
_, err := s.db.Exec(`UPDATE install_tokens SET used = 1 WHERE token = ?`, token)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteExpiredTokens 删除过期token
|
||||
func (s *SQLiteStore) DeleteExpiredTokens(expireTime int64) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
_, err := s.db.Exec(`DELETE FROM install_tokens WHERE created_at < ?`, expireTime)
|
||||
return err
|
||||
}
|
||||
@@ -2,48 +2,11 @@ package db
|
||||
|
||||
import "github.com/gotunnel/pkg/protocol"
|
||||
|
||||
// ClientPlugin 客户端已安装的插件
|
||||
type ClientPlugin struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Config map[string]string `json:"config,omitempty"` // 插件配置
|
||||
}
|
||||
|
||||
// Client 客户端数据
|
||||
type Client struct {
|
||||
ID string `json:"id"`
|
||||
Nickname string `json:"nickname,omitempty"`
|
||||
Rules []protocol.ProxyRule `json:"rules"`
|
||||
Plugins []ClientPlugin `json:"plugins,omitempty"` // 已安装的插件
|
||||
}
|
||||
|
||||
// PluginData 插件数据
|
||||
type PluginData struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
Type string `json:"type"`
|
||||
Source string `json:"source"`
|
||||
Description string `json:"description"`
|
||||
Author string `json:"author"`
|
||||
Icon string `json:"icon"`
|
||||
Checksum string `json:"checksum"`
|
||||
Size int64 `json:"size"`
|
||||
Enabled bool `json:"enabled"`
|
||||
WASMData []byte `json:"-"`
|
||||
}
|
||||
|
||||
// JSPlugin JS 插件数据
|
||||
type JSPlugin struct {
|
||||
Name string `json:"name"`
|
||||
Source string `json:"source"`
|
||||
Signature string `json:"signature"` // 官方签名 (Base64)
|
||||
Description string `json:"description"`
|
||||
Author string `json:"author"`
|
||||
AutoPush []string `json:"auto_push"`
|
||||
Config map[string]string `json:"config"`
|
||||
AutoStart bool `json:"auto_start"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// ClientStore 客户端存储接口
|
||||
@@ -58,29 +21,39 @@ type ClientStore interface {
|
||||
Close() error
|
||||
}
|
||||
|
||||
// PluginStore 插件存储接口
|
||||
type PluginStore interface {
|
||||
GetAllPlugins() ([]PluginData, error)
|
||||
GetPlugin(name string) (*PluginData, error)
|
||||
SavePlugin(p *PluginData) error
|
||||
DeletePlugin(name string) error
|
||||
SetPluginEnabled(name string, enabled bool) error
|
||||
GetPluginWASM(name string) ([]byte, error)
|
||||
}
|
||||
|
||||
// JSPluginStore JS 插件存储接口
|
||||
type JSPluginStore interface {
|
||||
GetAllJSPlugins() ([]JSPlugin, error)
|
||||
GetJSPlugin(name string) (*JSPlugin, error)
|
||||
SaveJSPlugin(p *JSPlugin) error
|
||||
DeleteJSPlugin(name string) error
|
||||
SetJSPluginEnabled(name string, enabled bool) error
|
||||
}
|
||||
|
||||
// Store 统一存储接口
|
||||
type Store interface {
|
||||
ClientStore
|
||||
PluginStore
|
||||
JSPluginStore
|
||||
TrafficStore
|
||||
Close() error
|
||||
}
|
||||
|
||||
// TrafficRecord 流量记录
|
||||
type TrafficRecord struct {
|
||||
Timestamp int64 `json:"timestamp"` // Unix 时间戳(小时级别)
|
||||
Inbound int64 `json:"inbound"` // 入站流量(字节)
|
||||
Outbound int64 `json:"outbound"` // 出站流量(字节)
|
||||
}
|
||||
|
||||
// TrafficStore 流量存储接口
|
||||
type TrafficStore interface {
|
||||
AddTraffic(inbound, outbound int64) error
|
||||
GetTotalTraffic() (inbound, outbound int64, err error)
|
||||
Get24HourTraffic() (inbound, outbound int64, err error)
|
||||
GetHourlyTraffic(hours int) ([]TrafficRecord, error)
|
||||
}
|
||||
|
||||
// InstallToken 安装token
|
||||
type InstallToken struct {
|
||||
Token string `json:"token"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
Used bool `json:"used"`
|
||||
}
|
||||
|
||||
// InstallTokenStore 安装token存储接口
|
||||
type InstallTokenStore interface {
|
||||
CreateInstallToken(token *InstallToken) error
|
||||
GetInstallToken(token string) (*InstallToken, error)
|
||||
MarkTokenUsed(token string) error
|
||||
DeleteExpiredTokens(expireTime int64) error
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
|
||||
@@ -39,8 +40,7 @@ func (s *SQLiteStore) init() error {
|
||||
CREATE TABLE IF NOT EXISTS clients (
|
||||
id TEXT PRIMARY KEY,
|
||||
nickname TEXT NOT NULL DEFAULT '',
|
||||
rules TEXT NOT NULL DEFAULT '[]',
|
||||
plugins TEXT NOT NULL DEFAULT '[]'
|
||||
rules TEXT NOT NULL DEFAULT '[]'
|
||||
)
|
||||
`)
|
||||
if err != nil {
|
||||
@@ -49,52 +49,46 @@ func (s *SQLiteStore) init() error {
|
||||
|
||||
// 迁移:添加 nickname 列
|
||||
s.db.Exec(`ALTER TABLE clients ADD COLUMN nickname TEXT NOT NULL DEFAULT ''`)
|
||||
// 迁移:添加 plugins 列
|
||||
s.db.Exec(`ALTER TABLE clients ADD COLUMN plugins TEXT NOT NULL DEFAULT '[]'`)
|
||||
|
||||
// 创建插件表
|
||||
// 创建流量统计表
|
||||
_, err = s.db.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS plugins (
|
||||
name TEXT PRIMARY KEY,
|
||||
version TEXT NOT NULL,
|
||||
type TEXT NOT NULL DEFAULT 'proxy',
|
||||
source TEXT NOT NULL DEFAULT 'wasm',
|
||||
description TEXT,
|
||||
author TEXT,
|
||||
icon TEXT,
|
||||
checksum TEXT,
|
||||
size INTEGER DEFAULT 0,
|
||||
enabled INTEGER DEFAULT 1,
|
||||
wasm_data BLOB
|
||||
CREATE TABLE IF NOT EXISTS traffic_stats (
|
||||
hour_ts INTEGER PRIMARY KEY,
|
||||
inbound INTEGER NOT NULL DEFAULT 0,
|
||||
outbound INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 迁移:添加 icon 列
|
||||
s.db.Exec(`ALTER TABLE plugins ADD COLUMN icon TEXT`)
|
||||
|
||||
// 创建 JS 插件表
|
||||
// 创建总流量表
|
||||
_, err = s.db.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS js_plugins (
|
||||
name TEXT PRIMARY KEY,
|
||||
source TEXT NOT NULL,
|
||||
description TEXT,
|
||||
author TEXT,
|
||||
auto_push TEXT NOT NULL DEFAULT '[]',
|
||||
config TEXT NOT NULL DEFAULT '',
|
||||
auto_start INTEGER DEFAULT 1,
|
||||
enabled INTEGER DEFAULT 1,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
CREATE TABLE IF NOT EXISTS traffic_total (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
inbound INTEGER NOT NULL DEFAULT 0,
|
||||
outbound INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 迁移:添加 signature 列
|
||||
s.db.Exec(`ALTER TABLE js_plugins ADD COLUMN signature TEXT NOT NULL DEFAULT ''`)
|
||||
// 初始化总流量记录
|
||||
s.db.Exec(`INSERT OR IGNORE INTO traffic_total (id, inbound, outbound) VALUES (1, 0, 0)`)
|
||||
|
||||
// 创建安装token表
|
||||
_, err = s.db.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS install_tokens (
|
||||
token TEXT PRIMARY KEY,
|
||||
client_id TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL,
|
||||
used INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -109,7 +103,7 @@ func (s *SQLiteStore) GetAllClients() ([]Client, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
rows, err := s.db.Query(`SELECT id, nickname, rules, plugins FROM clients`)
|
||||
rows, err := s.db.Query(`SELECT id, nickname, rules FROM clients`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -118,16 +112,13 @@ func (s *SQLiteStore) GetAllClients() ([]Client, error) {
|
||||
var clients []Client
|
||||
for rows.Next() {
|
||||
var c Client
|
||||
var rulesJSON, pluginsJSON string
|
||||
if err := rows.Scan(&c.ID, &c.Nickname, &rulesJSON, &pluginsJSON); err != nil {
|
||||
var rulesJSON string
|
||||
if err := rows.Scan(&c.ID, &c.Nickname, &rulesJSON); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := json.Unmarshal([]byte(rulesJSON), &c.Rules); err != nil {
|
||||
c.Rules = []protocol.ProxyRule{}
|
||||
}
|
||||
if err := json.Unmarshal([]byte(pluginsJSON), &c.Plugins); err != nil {
|
||||
c.Plugins = []ClientPlugin{}
|
||||
}
|
||||
clients = append(clients, c)
|
||||
}
|
||||
return clients, nil
|
||||
@@ -139,17 +130,14 @@ func (s *SQLiteStore) GetClient(id string) (*Client, error) {
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
var c Client
|
||||
var rulesJSON, pluginsJSON string
|
||||
err := s.db.QueryRow(`SELECT id, nickname, rules, plugins FROM clients WHERE id = ?`, id).Scan(&c.ID, &c.Nickname, &rulesJSON, &pluginsJSON)
|
||||
var rulesJSON string
|
||||
err := s.db.QueryRow(`SELECT id, nickname, rules FROM clients WHERE id = ?`, id).Scan(&c.ID, &c.Nickname, &rulesJSON)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := json.Unmarshal([]byte(rulesJSON), &c.Rules); err != nil {
|
||||
c.Rules = []protocol.ProxyRule{}
|
||||
}
|
||||
if err := json.Unmarshal([]byte(pluginsJSON), &c.Plugins); err != nil {
|
||||
c.Plugins = []ClientPlugin{}
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
@@ -162,12 +150,8 @@ func (s *SQLiteStore) CreateClient(c *Client) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pluginsJSON, err := json.Marshal(c.Plugins)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.Exec(`INSERT INTO clients (id, nickname, rules, plugins) VALUES (?, ?, ?, ?)`,
|
||||
c.ID, c.Nickname, string(rulesJSON), string(pluginsJSON))
|
||||
_, err = s.db.Exec(`INSERT INTO clients (id, nickname, rules) VALUES (?, ?, ?)`,
|
||||
c.ID, c.Nickname, string(rulesJSON))
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -180,12 +164,8 @@ func (s *SQLiteStore) UpdateClient(c *Client) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pluginsJSON, err := json.Marshal(c.Plugins)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.Exec(`UPDATE clients SET nickname = ?, rules = ?, plugins = ? WHERE id = ?`,
|
||||
c.Nickname, string(rulesJSON), string(pluginsJSON), c.ID)
|
||||
_, err = s.db.Exec(`UPDATE clients SET nickname = ?, rules = ? WHERE id = ?`,
|
||||
c.Nickname, string(rulesJSON), c.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -217,205 +197,99 @@ func (s *SQLiteStore) GetClientRules(id string) ([]protocol.ProxyRule, error) {
|
||||
return c.Rules, nil
|
||||
}
|
||||
|
||||
// ========== 插件存储方法 ==========
|
||||
// ========== 流量统计方法 ==========
|
||||
|
||||
// GetAllPlugins 获取所有插件
|
||||
func (s *SQLiteStore) GetAllPlugins() ([]PluginData, error) {
|
||||
// getHourTimestamp 获取当前小时的时间戳
|
||||
func getHourTimestamp() int64 {
|
||||
now := time.Now()
|
||||
return time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, now.Location()).Unix()
|
||||
}
|
||||
|
||||
// AddTraffic 添加流量记录
|
||||
func (s *SQLiteStore) AddTraffic(inbound, outbound int64) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
hourTs := getHourTimestamp()
|
||||
|
||||
// 更新小时统计
|
||||
_, err := s.db.Exec(`
|
||||
INSERT INTO traffic_stats (hour_ts, inbound, outbound) VALUES (?, ?, ?)
|
||||
ON CONFLICT(hour_ts) DO UPDATE SET inbound = inbound + ?, outbound = outbound + ?
|
||||
`, hourTs, inbound, outbound, inbound, outbound)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 更新总流量
|
||||
_, err = s.db.Exec(`
|
||||
UPDATE traffic_total SET inbound = inbound + ?, outbound = outbound + ? WHERE id = 1
|
||||
`, inbound, outbound)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetTotalTraffic 获取总流量
|
||||
func (s *SQLiteStore) GetTotalTraffic() (inbound, outbound int64, err error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
err = s.db.QueryRow(`SELECT inbound, outbound FROM traffic_total WHERE id = 1`).Scan(&inbound, &outbound)
|
||||
return
|
||||
}
|
||||
|
||||
// Get24HourTraffic 获取24小时流量
|
||||
func (s *SQLiteStore) Get24HourTraffic() (inbound, outbound int64, err error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
cutoff := time.Now().Add(-24 * time.Hour).Unix()
|
||||
err = s.db.QueryRow(`
|
||||
SELECT COALESCE(SUM(inbound), 0), COALESCE(SUM(outbound), 0)
|
||||
FROM traffic_stats WHERE hour_ts >= ?
|
||||
`, cutoff).Scan(&inbound, &outbound)
|
||||
return
|
||||
}
|
||||
|
||||
// GetHourlyTraffic 获取每小时流量记录(始终返回完整的 hours 小时数据)
|
||||
func (s *SQLiteStore) GetHourlyTraffic(hours int) ([]TrafficRecord, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
// 计算当前小时的起始时间戳
|
||||
now := time.Now()
|
||||
currentHour := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, now.Location())
|
||||
|
||||
// 查询数据库中的记录
|
||||
cutoff := currentHour.Add(-time.Duration(hours-1) * time.Hour).Unix()
|
||||
rows, err := s.db.Query(`
|
||||
SELECT name, version, type, source, description, author, icon, checksum, size, enabled
|
||||
FROM plugins
|
||||
`)
|
||||
SELECT hour_ts, inbound, outbound FROM traffic_stats
|
||||
WHERE hour_ts >= ? ORDER BY hour_ts ASC
|
||||
`, cutoff)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var plugins []PluginData
|
||||
// 将数据库记录放入 map 以便快速查找
|
||||
dbRecords := make(map[int64]TrafficRecord)
|
||||
for rows.Next() {
|
||||
var p PluginData
|
||||
var enabled int
|
||||
var icon sql.NullString
|
||||
err := rows.Scan(&p.Name, &p.Version, &p.Type, &p.Source,
|
||||
&p.Description, &p.Author, &icon, &p.Checksum, &p.Size, &enabled)
|
||||
if err != nil {
|
||||
var r TrafficRecord
|
||||
if err := rows.Scan(&r.Timestamp, &r.Inbound, &r.Outbound); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Enabled = enabled == 1
|
||||
p.Icon = icon.String
|
||||
plugins = append(plugins, p)
|
||||
dbRecords[r.Timestamp] = r
|
||||
}
|
||||
return plugins, nil
|
||||
}
|
||||
|
||||
// GetPlugin 获取单个插件
|
||||
func (s *SQLiteStore) GetPlugin(name string) (*PluginData, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
var p PluginData
|
||||
var enabled int
|
||||
var icon sql.NullString
|
||||
err := s.db.QueryRow(`
|
||||
SELECT name, version, type, source, description, author, icon, checksum, size, enabled
|
||||
FROM plugins WHERE name = ?
|
||||
`, name).Scan(&p.Name, &p.Version, &p.Type, &p.Source,
|
||||
&p.Description, &p.Author, &icon, &p.Checksum, &p.Size, &enabled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Enabled = enabled == 1
|
||||
p.Icon = icon.String
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
// SavePlugin 保存插件
|
||||
func (s *SQLiteStore) SavePlugin(p *PluginData) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
enabled := 0
|
||||
if p.Enabled {
|
||||
enabled = 1
|
||||
}
|
||||
_, err := s.db.Exec(`
|
||||
INSERT OR REPLACE INTO plugins
|
||||
(name, version, type, source, description, author, icon, checksum, size, enabled, wasm_data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`, p.Name, p.Version, p.Type, p.Source, p.Description, p.Author,
|
||||
p.Icon, p.Checksum, p.Size, enabled, p.WASMData)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeletePlugin 删除插件
|
||||
func (s *SQLiteStore) DeletePlugin(name string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
_, err := s.db.Exec(`DELETE FROM plugins WHERE name = ?`, name)
|
||||
return err
|
||||
}
|
||||
|
||||
// SetPluginEnabled 设置插件启用状态
|
||||
func (s *SQLiteStore) SetPluginEnabled(name string, enabled bool) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
val := 0
|
||||
if enabled {
|
||||
val = 1
|
||||
}
|
||||
_, err := s.db.Exec(`UPDATE plugins SET enabled = ? WHERE name = ?`, val, name)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetPluginWASM 获取插件 WASM 数据
|
||||
func (s *SQLiteStore) GetPluginWASM(name string) ([]byte, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
var data []byte
|
||||
err := s.db.QueryRow(`SELECT wasm_data FROM plugins WHERE name = ?`, name).Scan(&data)
|
||||
return data, err
|
||||
}
|
||||
|
||||
// ========== JS 插件存储方法 ==========
|
||||
|
||||
// GetAllJSPlugins 获取所有 JS 插件
|
||||
func (s *SQLiteStore) GetAllJSPlugins() ([]JSPlugin, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
rows, err := s.db.Query(`
|
||||
SELECT name, source, signature, description, author, auto_push, config, auto_start, enabled
|
||||
FROM js_plugins
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var plugins []JSPlugin
|
||||
for rows.Next() {
|
||||
var p JSPlugin
|
||||
var autoPushJSON, configJSON string
|
||||
var autoStart, enabled int
|
||||
err := rows.Scan(&p.Name, &p.Source, &p.Signature, &p.Description, &p.Author,
|
||||
&autoPushJSON, &configJSON, &autoStart, &enabled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
// 生成完整的 hours 小时数据
|
||||
records := make([]TrafficRecord, hours)
|
||||
for i := 0; i < hours; i++ {
|
||||
ts := currentHour.Add(-time.Duration(hours-1-i) * time.Hour).Unix()
|
||||
if r, ok := dbRecords[ts]; ok {
|
||||
records[i] = r
|
||||
} else {
|
||||
records[i] = TrafficRecord{Timestamp: ts, Inbound: 0, Outbound: 0}
|
||||
}
|
||||
json.Unmarshal([]byte(autoPushJSON), &p.AutoPush)
|
||||
json.Unmarshal([]byte(configJSON), &p.Config)
|
||||
p.AutoStart = autoStart == 1
|
||||
p.Enabled = enabled == 1
|
||||
plugins = append(plugins, p)
|
||||
}
|
||||
return plugins, nil
|
||||
}
|
||||
|
||||
// GetJSPlugin 获取单个 JS 插件
|
||||
func (s *SQLiteStore) GetJSPlugin(name string) (*JSPlugin, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
var p JSPlugin
|
||||
var autoPushJSON, configJSON string
|
||||
var autoStart, enabled int
|
||||
err := s.db.QueryRow(`
|
||||
SELECT name, source, signature, description, author, auto_push, config, auto_start, enabled
|
||||
FROM js_plugins WHERE name = ?
|
||||
`, name).Scan(&p.Name, &p.Source, &p.Signature, &p.Description, &p.Author,
|
||||
&autoPushJSON, &configJSON, &autoStart, &enabled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
json.Unmarshal([]byte(autoPushJSON), &p.AutoPush)
|
||||
json.Unmarshal([]byte(configJSON), &p.Config)
|
||||
p.AutoStart = autoStart == 1
|
||||
p.Enabled = enabled == 1
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
// SaveJSPlugin 保存 JS 插件
|
||||
func (s *SQLiteStore) SaveJSPlugin(p *JSPlugin) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
autoPushJSON, _ := json.Marshal(p.AutoPush)
|
||||
configJSON, _ := json.Marshal(p.Config)
|
||||
autoStart, enabled := 0, 0
|
||||
if p.AutoStart {
|
||||
autoStart = 1
|
||||
}
|
||||
if p.Enabled {
|
||||
enabled = 1
|
||||
}
|
||||
|
||||
_, err := s.db.Exec(`
|
||||
INSERT OR REPLACE INTO js_plugins
|
||||
(name, source, signature, description, author, auto_push, config, auto_start, enabled)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`, p.Name, p.Source, p.Signature, p.Description, p.Author,
|
||||
string(autoPushJSON), string(configJSON), autoStart, enabled)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteJSPlugin 删除 JS 插件
|
||||
func (s *SQLiteStore) DeleteJSPlugin(name string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
_, err := s.db.Exec(`DELETE FROM js_plugins WHERE name = ?`, name)
|
||||
return err
|
||||
}
|
||||
|
||||
// SetJSPluginEnabled 设置 JS 插件启用状态
|
||||
func (s *SQLiteStore) SetJSPluginEnabled(name string, enabled bool) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
val := 0
|
||||
if enabled {
|
||||
val = 1
|
||||
}
|
||||
_, err := s.db.Exec(`UPDATE js_plugins SET enabled = ? WHERE name = ?`, val, name)
|
||||
return err
|
||||
return records, nil
|
||||
}
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
|
||||
"github.com/gotunnel/pkg/plugin"
|
||||
"github.com/gotunnel/pkg/plugin/builtin"
|
||||
)
|
||||
|
||||
// Manager 服务端 plugin 管理器
|
||||
type Manager struct {
|
||||
registry *plugin.Registry
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewManager 创建 plugin 管理器
|
||||
func NewManager() (*Manager, error) {
|
||||
registry := plugin.NewRegistry()
|
||||
|
||||
m := &Manager{
|
||||
registry: registry,
|
||||
}
|
||||
|
||||
if err := m.registerBuiltins(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// registerBuiltins 注册内置 plugins
|
||||
func (m *Manager) registerBuiltins() error {
|
||||
if err := m.registry.RegisterAllServer(builtin.GetServerPlugins()); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, h := range builtin.GetClientPlugins() {
|
||||
if err := m.registry.RegisterClient(h); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
log.Printf("[Plugin] Registered %d server, %d client plugins",
|
||||
len(builtin.GetServerPlugins()), len(builtin.GetClientPlugins()))
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetServer 返回服务端插件
|
||||
func (m *Manager) GetServer(name string) (plugin.ServerPlugin, error) {
|
||||
return m.registry.GetServer(name)
|
||||
}
|
||||
|
||||
// ListPlugins 返回所有插件
|
||||
func (m *Manager) ListPlugins() []plugin.Info {
|
||||
return m.registry.List()
|
||||
}
|
||||
|
||||
// GetRegistry 返回插件注册表
|
||||
func (m *Manager) GetRegistry() *plugin.Registry {
|
||||
return m.registry
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,108 +0,0 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/gotunnel/pkg/auth"
|
||||
"github.com/gotunnel/pkg/security"
|
||||
)
|
||||
|
||||
// AuthHandler 认证处理器
|
||||
type AuthHandler struct {
|
||||
username string
|
||||
password string
|
||||
jwtAuth *auth.JWTAuth
|
||||
}
|
||||
|
||||
// NewAuthHandler 创建认证处理器
|
||||
func NewAuthHandler(username, password string, jwtAuth *auth.JWTAuth) *AuthHandler {
|
||||
return &AuthHandler{
|
||||
username: username,
|
||||
password: password,
|
||||
jwtAuth: jwtAuth,
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterAuthRoutes 注册认证路由
|
||||
func RegisterAuthRoutes(r *Router, h *AuthHandler) {
|
||||
r.HandleFunc("/api/auth/login", h.handleLogin)
|
||||
r.HandleFunc("/api/auth/check", h.handleCheck)
|
||||
}
|
||||
|
||||
// handleLogin 处理登录请求
|
||||
func (h *AuthHandler) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, `{"error":"invalid request"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 验证用户名密码
|
||||
userMatch := subtle.ConstantTimeCompare([]byte(req.Username), []byte(h.username)) == 1
|
||||
passMatch := subtle.ConstantTimeCompare([]byte(req.Password), []byte(h.password)) == 1
|
||||
|
||||
if !userMatch || !passMatch {
|
||||
security.LogWebLogin(r.RemoteAddr, req.Username, false)
|
||||
http.Error(w, `{"error":"invalid credentials"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// 生成 token
|
||||
token, err := h.jwtAuth.GenerateToken(req.Username)
|
||||
if err != nil {
|
||||
http.Error(w, `{"error":"failed to generate token"}`, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
security.LogWebLogin(r.RemoteAddr, req.Username, true)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"token": token,
|
||||
})
|
||||
}
|
||||
|
||||
// handleCheck 检查 token 是否有效
|
||||
func (h *AuthHandler) handleCheck(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// 从 Authorization header 获取 token
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
http.Error(w, `{"error":"missing authorization header"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// 解析 Bearer token
|
||||
const prefix = "Bearer "
|
||||
if len(authHeader) < len(prefix) || authHeader[:len(prefix)] != prefix {
|
||||
http.Error(w, `{"error":"invalid authorization format"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
tokenStr := authHeader[len(prefix):]
|
||||
|
||||
// 验证 token
|
||||
claims, err := h.jwtAuth.ValidateToken(tokenStr)
|
||||
if err != nil {
|
||||
http.Error(w, `{"error":"invalid token"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"valid": true,
|
||||
"username": claims.Username,
|
||||
})
|
||||
}
|
||||
46
internal/server/router/dto/client.go
Normal file
46
internal/server/router/dto/client.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"github.com/gotunnel/pkg/protocol"
|
||||
)
|
||||
|
||||
// CreateClientRequest 创建客户端请求
|
||||
// @Description 创建新客户端的请求体
|
||||
type CreateClientRequest struct {
|
||||
ID string `json:"id" binding:"required,min=1,max=64" example:"client-001"`
|
||||
Rules []protocol.ProxyRule `json:"rules"`
|
||||
}
|
||||
|
||||
// UpdateClientRequest 更新客户端请求
|
||||
// @Description 更新客户端配置的请求体
|
||||
type UpdateClientRequest struct {
|
||||
Nickname string `json:"nickname" binding:"max=128" example:"My Client"`
|
||||
Rules []protocol.ProxyRule `json:"rules"`
|
||||
}
|
||||
|
||||
// ClientResponse 客户端详情响应
|
||||
// @Description 客户端详细信息
|
||||
type ClientResponse struct {
|
||||
ID string `json:"id" example:"client-001"`
|
||||
Nickname string `json:"nickname,omitempty" example:"My Client"`
|
||||
Rules []protocol.ProxyRule `json:"rules"`
|
||||
Online bool `json:"online" example:"true"`
|
||||
LastPing string `json:"last_ping,omitempty" example:"2025-01-02T10:30:00Z"`
|
||||
RemoteAddr string `json:"remote_addr,omitempty" example:"192.168.1.100:54321"`
|
||||
OS string `json:"os,omitempty" example:"linux"`
|
||||
Arch string `json:"arch,omitempty" example:"amd64"`
|
||||
Version string `json:"version,omitempty" example:"1.0.0"`
|
||||
}
|
||||
|
||||
// ClientListItem 客户端列表项
|
||||
// @Description 客户端列表中的单个项目
|
||||
type ClientListItem struct {
|
||||
ID string `json:"id" example:"client-001"`
|
||||
Nickname string `json:"nickname,omitempty" example:"My Client"`
|
||||
Online bool `json:"online" example:"true"`
|
||||
LastPing string `json:"last_ping,omitempty"`
|
||||
RemoteAddr string `json:"remote_addr,omitempty"`
|
||||
RuleCount int `json:"rule_count" example:"3"`
|
||||
OS string `json:"os,omitempty" example:"linux"`
|
||||
Arch string `json:"arch,omitempty" example:"amd64"`
|
||||
}
|
||||
47
internal/server/router/dto/config.go
Normal file
47
internal/server/router/dto/config.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package dto
|
||||
|
||||
// UpdateServerConfigRequest is the config update payload.
|
||||
type UpdateServerConfigRequest struct {
|
||||
Server *ServerConfigPart `json:"server"`
|
||||
Web *WebConfigPart `json:"web"`
|
||||
}
|
||||
|
||||
// ServerConfigPart is the server config subset.
|
||||
type ServerConfigPart struct {
|
||||
BindAddr string `json:"bind_addr" binding:"omitempty"`
|
||||
BindPort int `json:"bind_port" binding:"omitempty,min=1,max=65535"`
|
||||
Token string `json:"token" binding:"omitempty,min=8"`
|
||||
HeartbeatSec int `json:"heartbeat_sec" binding:"omitempty,min=1,max=300"`
|
||||
HeartbeatTimeout int `json:"heartbeat_timeout" binding:"omitempty,min=1,max=600"`
|
||||
}
|
||||
|
||||
// WebConfigPart is the web console config subset.
|
||||
type WebConfigPart struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
BindPort int `json:"bind_port" binding:"omitempty,min=1,max=65535"`
|
||||
Username string `json:"username" binding:"omitempty,min=3,max=32"`
|
||||
Password string `json:"password" binding:"omitempty,min=6,max=64"`
|
||||
}
|
||||
|
||||
// ServerConfigResponse is the config response payload.
|
||||
type ServerConfigResponse struct {
|
||||
Server ServerConfigInfo `json:"server"`
|
||||
Web WebConfigInfo `json:"web"`
|
||||
}
|
||||
|
||||
// ServerConfigInfo describes the server config.
|
||||
type ServerConfigInfo struct {
|
||||
BindAddr string `json:"bind_addr"`
|
||||
BindPort int `json:"bind_port"`
|
||||
Token string `json:"token"`
|
||||
HeartbeatSec int `json:"heartbeat_sec"`
|
||||
HeartbeatTimeout int `json:"heartbeat_timeout"`
|
||||
}
|
||||
|
||||
// WebConfigInfo describes the web console config.
|
||||
type WebConfigInfo struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
BindPort int `json:"bind_port"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
77
internal/server/router/dto/update.go
Normal file
77
internal/server/router/dto/update.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package dto
|
||||
|
||||
// CheckUpdateResponse 检查更新响应
|
||||
// @Description 更新检查结果
|
||||
type CheckUpdateResponse struct {
|
||||
HasUpdate bool `json:"has_update"`
|
||||
CurrentVersion string `json:"current_version"`
|
||||
LatestVersion string `json:"latest_version,omitempty"`
|
||||
DownloadURL string `json:"download_url,omitempty"`
|
||||
ReleaseNotes string `json:"release_notes,omitempty"`
|
||||
PublishedAt string `json:"published_at,omitempty"`
|
||||
}
|
||||
|
||||
// CheckClientUpdateQuery 检查客户端更新查询参数
|
||||
// @Description 检查客户端更新的查询参数
|
||||
type CheckClientUpdateQuery struct {
|
||||
OS string `form:"os" binding:"omitempty,oneof=linux darwin windows"`
|
||||
Arch string `form:"arch" binding:"omitempty,oneof=amd64 arm64 386 arm"`
|
||||
}
|
||||
|
||||
// ApplyServerUpdateRequest 应用服务端更新请求
|
||||
// @Description 应用服务端更新
|
||||
type ApplyServerUpdateRequest struct {
|
||||
DownloadURL string `json:"download_url" binding:"required,url"`
|
||||
Restart bool `json:"restart"`
|
||||
}
|
||||
|
||||
// ApplyClientUpdateRequest 应用客户端更新请求
|
||||
// @Description 推送更新到客户端
|
||||
type ApplyClientUpdateRequest struct {
|
||||
ClientID string `json:"client_id" binding:"required"`
|
||||
DownloadURL string `json:"download_url" binding:"required,url"`
|
||||
}
|
||||
|
||||
// VersionInfo 版本信息
|
||||
// @Description 当前版本信息
|
||||
type VersionInfo struct {
|
||||
Version string `json:"version"`
|
||||
GitCommit string `json:"git_commit,omitempty"`
|
||||
BuildTime string `json:"build_time,omitempty"`
|
||||
GoVersion string `json:"go_version,omitempty"`
|
||||
OS string `json:"os,omitempty"`
|
||||
Arch string `json:"arch,omitempty"`
|
||||
}
|
||||
|
||||
// StatusResponse 服务器状态响应
|
||||
// @Description 服务器状态信息
|
||||
type StatusResponse struct {
|
||||
Server ServerStatus `json:"server"`
|
||||
ClientCount int `json:"client_count"`
|
||||
}
|
||||
|
||||
// ServerStatus 服务器状态
|
||||
type ServerStatus struct {
|
||||
BindAddr string `json:"bind_addr"`
|
||||
BindPort int `json:"bind_port"`
|
||||
}
|
||||
|
||||
// LoginRequest 登录请求
|
||||
// @Description 用户登录
|
||||
type LoginRequest struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
// LoginResponse 登录响应
|
||||
// @Description 登录成功返回
|
||||
type LoginResponse struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// TokenCheckResponse Token 检查响应
|
||||
// @Description Token 验证结果
|
||||
type TokenCheckResponse struct {
|
||||
Valid bool `json:"valid"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
106
internal/server/router/errors.go
Normal file
106
internal/server/router/errors.go
Normal file
@@ -0,0 +1,106 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
// ValidationError 验证错误详情
|
||||
type ValidationError struct {
|
||||
Field string `json:"field"` // 字段名
|
||||
Message string `json:"message"` // 错误消息
|
||||
}
|
||||
|
||||
// HandleValidationError 处理验证错误并返回统一格式
|
||||
func HandleValidationError(c *gin.Context, err error) {
|
||||
var ve validator.ValidationErrors
|
||||
if errors.As(err, &ve) {
|
||||
errs := make([]ValidationError, len(ve))
|
||||
for i, fe := range ve {
|
||||
errs[i] = ValidationError{
|
||||
Field: fe.Field(),
|
||||
Message: getValidationMessage(fe),
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusBadRequest, Response{
|
||||
Code: CodeBadRequest,
|
||||
Message: "validation failed",
|
||||
Data: errs,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 非验证错误,返回通用错误消息
|
||||
BadRequest(c, err.Error())
|
||||
}
|
||||
|
||||
// getValidationMessage 根据验证标签返回友好的错误消息
|
||||
func getValidationMessage(fe validator.FieldError) string {
|
||||
switch fe.Tag() {
|
||||
case "required":
|
||||
return "this field is required"
|
||||
case "min":
|
||||
return "value is too short or too small"
|
||||
case "max":
|
||||
return "value is too long or too large"
|
||||
case "email":
|
||||
return "invalid email format"
|
||||
case "url":
|
||||
return "invalid URL format"
|
||||
case "oneof":
|
||||
return "value must be one of: " + fe.Param()
|
||||
case "alphanum":
|
||||
return "must contain only letters and numbers"
|
||||
case "alphanumunicode":
|
||||
return "must contain only letters, numbers and unicode characters"
|
||||
case "ip":
|
||||
return "invalid IP address"
|
||||
case "hostname":
|
||||
return "invalid hostname"
|
||||
case "clientid":
|
||||
return "must be 1-64 alphanumeric characters, underscore or hyphen"
|
||||
case "gte":
|
||||
return "value must be greater than or equal to " + fe.Param()
|
||||
case "lte":
|
||||
return "value must be less than or equal to " + fe.Param()
|
||||
case "gt":
|
||||
return "value must be greater than " + fe.Param()
|
||||
case "lt":
|
||||
return "value must be less than " + fe.Param()
|
||||
default:
|
||||
return "validation failed on " + fe.Tag()
|
||||
}
|
||||
}
|
||||
|
||||
// BindJSON 绑定 JSON 并自动处理验证错误
|
||||
// 返回 true 表示绑定成功,false 表示已处理错误响应
|
||||
func BindJSON(c *gin.Context, obj interface{}) bool {
|
||||
if err := c.ShouldBindJSON(obj); err != nil {
|
||||
HandleValidationError(c, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// BindQuery 绑定查询参数并自动处理验证错误
|
||||
// 返回 true 表示绑定成功,false 表示已处理错误响应
|
||||
func BindQuery(c *gin.Context, obj interface{}) bool {
|
||||
if err := c.ShouldBindQuery(obj); err != nil {
|
||||
HandleValidationError(c, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// BindURI 绑定 URI 参数并自动处理验证错误
|
||||
// 返回 true 表示绑定成功,false 表示已处理错误响应
|
||||
func BindURI(c *gin.Context, obj interface{}) bool {
|
||||
if err := c.ShouldBindUri(obj); err != nil {
|
||||
HandleValidationError(c, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
100
internal/server/router/handler/auth.go
Normal file
100
internal/server/router/handler/auth.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
// removed router import
|
||||
"github.com/gotunnel/internal/server/router/dto"
|
||||
"github.com/gotunnel/pkg/auth"
|
||||
"github.com/gotunnel/pkg/security"
|
||||
)
|
||||
|
||||
// AuthHandler 认证处理器
|
||||
type AuthHandler struct {
|
||||
username string
|
||||
password string
|
||||
jwtAuth *auth.JWTAuth
|
||||
}
|
||||
|
||||
// NewAuthHandler 创建认证处理器
|
||||
func NewAuthHandler(username, password string, jwtAuth *auth.JWTAuth) *AuthHandler {
|
||||
return &AuthHandler{
|
||||
username: username,
|
||||
password: password,
|
||||
jwtAuth: jwtAuth,
|
||||
}
|
||||
}
|
||||
|
||||
// Login 用户登录
|
||||
// @Summary 用户登录
|
||||
// @Description 使用用户名密码登录,返回 JWT token
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body dto.LoginRequest true "登录信息"
|
||||
// @Success 200 {object} Response{data=dto.LoginResponse}
|
||||
// @Failure 400 {object} Response
|
||||
// @Failure 401 {object} Response
|
||||
// @Router /api/auth/login [post]
|
||||
func (h *AuthHandler) Login(c *gin.Context) {
|
||||
var req dto.LoginRequest
|
||||
if !BindJSON(c, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
// 验证用户名密码 (使用常量时间比较防止时序攻击)
|
||||
userMatch := subtle.ConstantTimeCompare([]byte(req.Username), []byte(h.username)) == 1
|
||||
passMatch := subtle.ConstantTimeCompare([]byte(req.Password), []byte(h.password)) == 1
|
||||
|
||||
if !userMatch || !passMatch {
|
||||
security.LogWebLogin(c.ClientIP(), req.Username, false)
|
||||
Unauthorized(c, "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
// 生成 token
|
||||
token, err := h.jwtAuth.GenerateToken(req.Username)
|
||||
if err != nil {
|
||||
InternalError(c, "failed to generate token")
|
||||
return
|
||||
}
|
||||
|
||||
security.LogWebLogin(c.ClientIP(), req.Username, true)
|
||||
Success(c, dto.LoginResponse{Token: token})
|
||||
}
|
||||
|
||||
// Check 检查 token 是否有效
|
||||
// @Summary 检查 Token
|
||||
// @Description 验证 JWT token 是否有效
|
||||
// @Tags 认证
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Success 200 {object} Response{data=dto.TokenCheckResponse}
|
||||
// @Failure 401 {object} Response
|
||||
// @Router /api/auth/check [get]
|
||||
func (h *AuthHandler) Check(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
Unauthorized(c, "missing authorization header")
|
||||
return
|
||||
}
|
||||
|
||||
const prefix = "Bearer "
|
||||
if len(authHeader) < len(prefix) || authHeader[:len(prefix)] != prefix {
|
||||
Unauthorized(c, "invalid authorization format")
|
||||
return
|
||||
}
|
||||
tokenStr := authHeader[len(prefix):]
|
||||
|
||||
claims, err := h.jwtAuth.ValidateToken(tokenStr)
|
||||
if err != nil {
|
||||
Unauthorized(c, "invalid token")
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, dto.TokenCheckResponse{
|
||||
Valid: true,
|
||||
Username: claims.Username,
|
||||
})
|
||||
}
|
||||
342
internal/server/router/handler/client.go
Normal file
342
internal/server/router/handler/client.go
Normal file
@@ -0,0 +1,342 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gotunnel/internal/server/db"
|
||||
"github.com/gotunnel/internal/server/router/dto"
|
||||
)
|
||||
|
||||
// ClientHandler 客户端处理器
|
||||
type ClientHandler struct {
|
||||
app AppInterface
|
||||
}
|
||||
|
||||
// NewClientHandler 创建客户端处理器
|
||||
func NewClientHandler(app AppInterface) *ClientHandler {
|
||||
return &ClientHandler{app: app}
|
||||
}
|
||||
|
||||
// List 获取客户端列表
|
||||
// @Summary 获取所有客户端
|
||||
// @Description 返回所有注册客户端的列表及其在线状态
|
||||
// @Tags 客户端
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Success 200 {object} Response{data=[]dto.ClientListItem}
|
||||
// @Router /api/clients [get]
|
||||
func (h *ClientHandler) List(c *gin.Context) {
|
||||
clients, err := h.app.GetClientStore().GetAllClients()
|
||||
if err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
statusMap := h.app.GetServer().GetAllClientStatus()
|
||||
result := make([]dto.ClientListItem, 0, len(clients))
|
||||
|
||||
for _, client := range clients {
|
||||
item := dto.ClientListItem{
|
||||
ID: client.ID,
|
||||
Nickname: client.Nickname,
|
||||
RuleCount: len(client.Rules),
|
||||
}
|
||||
if status, ok := statusMap[client.ID]; ok {
|
||||
item.Online = status.Online
|
||||
item.LastPing = status.LastPing
|
||||
item.RemoteAddr = status.RemoteAddr
|
||||
item.OS = status.OS
|
||||
item.Arch = status.Arch
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
|
||||
Success(c, result)
|
||||
}
|
||||
|
||||
// Create 创建客户端
|
||||
// @Summary 创建新客户端
|
||||
// @Description 创建一个新的客户端配置
|
||||
// @Tags 客户端
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param request body dto.CreateClientRequest true "客户端信息"
|
||||
// @Success 200 {object} Response
|
||||
// @Failure 400 {object} Response
|
||||
// @Failure 409 {object} Response
|
||||
// @Router /api/clients [post]
|
||||
func (h *ClientHandler) Create(c *gin.Context) {
|
||||
var req dto.CreateClientRequest
|
||||
if !BindJSON(c, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
// 验证客户端 ID 格式
|
||||
if !validateClientID(req.ID) {
|
||||
BadRequest(c, "invalid client id: must be 1-64 alphanumeric characters, underscore or hyphen")
|
||||
return
|
||||
}
|
||||
|
||||
// 检查客户端是否已存在
|
||||
exists, _ := h.app.GetClientStore().ClientExists(req.ID)
|
||||
if exists {
|
||||
Conflict(c, "client already exists")
|
||||
return
|
||||
}
|
||||
|
||||
client := &db.Client{ID: req.ID, Rules: req.Rules}
|
||||
if err := h.app.GetClientStore().CreateClient(client); err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, gin.H{"status": "ok"})
|
||||
}
|
||||
|
||||
// Get 获取单个客户端
|
||||
// @Summary 获取客户端详情
|
||||
// @Description 获取指定客户端的详细信息
|
||||
// @Tags 客户端
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param id path string true "客户端ID"
|
||||
// @Success 200 {object} Response{data=dto.ClientResponse}
|
||||
// @Failure 404 {object} Response
|
||||
// @Router /api/client/{id} [get]
|
||||
func (h *ClientHandler) Get(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
|
||||
client, err := h.app.GetClientStore().GetClient(clientID)
|
||||
if err != nil {
|
||||
NotFound(c, "client not found")
|
||||
return
|
||||
}
|
||||
|
||||
online, lastPing, remoteAddr, clientName, clientOS, clientArch, clientVersion := h.app.GetServer().GetClientStatus(clientID)
|
||||
|
||||
// 如果客户端在线且有名称,优先使用在线名称
|
||||
nickname := client.Nickname
|
||||
if online && clientName != "" && nickname == "" {
|
||||
nickname = clientName
|
||||
}
|
||||
|
||||
resp := dto.ClientResponse{
|
||||
ID: client.ID,
|
||||
Nickname: nickname,
|
||||
Rules: client.Rules,
|
||||
Online: online,
|
||||
LastPing: lastPing,
|
||||
RemoteAddr: remoteAddr,
|
||||
OS: clientOS,
|
||||
Arch: clientArch,
|
||||
Version: clientVersion,
|
||||
}
|
||||
|
||||
Success(c, resp)
|
||||
}
|
||||
|
||||
// Update 更新客户端
|
||||
// @Summary 更新客户端配置
|
||||
// @Description 更新指定客户端的配置信息
|
||||
// @Tags 客户端
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param id path string true "客户端ID"
|
||||
// @Param request body dto.UpdateClientRequest true "更新内容"
|
||||
// @Success 200 {object} Response
|
||||
// @Failure 400 {object} Response
|
||||
// @Failure 404 {object} Response
|
||||
// @Router /api/client/{id} [put]
|
||||
func (h *ClientHandler) Update(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
|
||||
var req dto.UpdateClientRequest
|
||||
if !BindJSON(c, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
client, err := h.app.GetClientStore().GetClient(clientID)
|
||||
if err != nil {
|
||||
NotFound(c, "client not found")
|
||||
return
|
||||
}
|
||||
|
||||
client.Nickname = req.Nickname
|
||||
client.Rules = req.Rules
|
||||
|
||||
if err := h.app.GetClientStore().UpdateClient(client); err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, gin.H{"status": "ok"})
|
||||
}
|
||||
|
||||
// Delete 删除客户端
|
||||
// @Summary 删除客户端
|
||||
// @Description 删除指定的客户端配置
|
||||
// @Tags 客户端
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param id path string true "客户端ID"
|
||||
// @Success 200 {object} Response
|
||||
// @Failure 404 {object} Response
|
||||
// @Router /api/client/{id} [delete]
|
||||
func (h *ClientHandler) Delete(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
|
||||
exists, _ := h.app.GetClientStore().ClientExists(clientID)
|
||||
if !exists {
|
||||
NotFound(c, "client not found")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.app.GetClientStore().DeleteClient(clientID); err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, gin.H{"status": "ok"})
|
||||
}
|
||||
|
||||
// PushConfig 推送配置到客户端
|
||||
// @Summary 推送配置
|
||||
// @Description 将配置推送到在线客户端
|
||||
// @Tags 客户端
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param id path string true "客户端ID"
|
||||
// @Success 200 {object} Response
|
||||
// @Failure 400 {object} Response
|
||||
// @Router /api/client/{id}/push [post]
|
||||
func (h *ClientHandler) PushConfig(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
|
||||
if !h.app.GetServer().IsClientOnline(clientID) {
|
||||
ClientNotOnline(c)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.app.GetServer().PushConfigToClient(clientID); err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, gin.H{"status": "ok"})
|
||||
}
|
||||
|
||||
// Disconnect 断开客户端连接
|
||||
// @Summary 断开连接
|
||||
// @Description 强制断开客户端连接
|
||||
// @Tags 客户端
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param id path string true "客户端ID"
|
||||
// @Success 200 {object} Response
|
||||
// @Router /api/client/{id}/disconnect [post]
|
||||
func (h *ClientHandler) Disconnect(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
|
||||
if err := h.app.GetServer().DisconnectClient(clientID); err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, gin.H{"status": "ok"})
|
||||
}
|
||||
|
||||
// Restart 重启客户端
|
||||
// @Summary 重启客户端
|
||||
// @Description 发送重启命令到客户端
|
||||
// @Tags 客户端
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param id path string true "客户端ID"
|
||||
// @Success 200 {object} Response
|
||||
// @Router /api/client/{id}/restart [post]
|
||||
func (h *ClientHandler) Restart(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
|
||||
if err := h.app.GetServer().RestartClient(clientID); err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
SuccessWithMessage(c, gin.H{"status": "ok"}, "client restart initiated")
|
||||
}
|
||||
|
||||
// @Failure 400 {object} Response
|
||||
// @Router /api/client/{id}/install-plugins [post]
|
||||
|
||||
// @Failure 400 {object} Response
|
||||
// @Router /api/client/{id}/plugin/{pluginID}/{action} [post]
|
||||
|
||||
|
||||
// GetSystemStats 获取客户端系统状态
|
||||
func (h *ClientHandler) GetSystemStats(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
stats, err := h.app.GetServer().GetClientSystemStats(clientID)
|
||||
if err != nil {
|
||||
ClientNotOnline(c)
|
||||
return
|
||||
}
|
||||
Success(c, stats)
|
||||
}
|
||||
|
||||
// GetScreenshot 获取客户端截图
|
||||
func (h *ClientHandler) GetScreenshot(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
quality := 0
|
||||
if q, ok := c.GetQuery("quality"); ok {
|
||||
fmt.Sscanf(q, "%d", &quality)
|
||||
}
|
||||
|
||||
screenshot, err := h.app.GetServer().GetClientScreenshot(clientID, quality)
|
||||
if err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, screenshot)
|
||||
}
|
||||
|
||||
// ExecuteShellRequest Shell 执行请求体
|
||||
type ExecuteShellRequest struct {
|
||||
Command string `json:"command" binding:"required"`
|
||||
Timeout int `json:"timeout"`
|
||||
}
|
||||
|
||||
// ExecuteShell 执行 Shell 命令
|
||||
func (h *ClientHandler) ExecuteShell(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
var req ExecuteShellRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
BadRequest(c, "Invalid request: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.app.GetServer().ExecuteClientShell(clientID, req.Command, req.Timeout)
|
||||
if err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, result)
|
||||
}
|
||||
|
||||
// validateClientID 验证客户端 ID 格式
|
||||
func validateClientID(id string) bool {
|
||||
if len(id) < 1 || len(id) > 64 {
|
||||
return false
|
||||
}
|
||||
for _, c := range id {
|
||||
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
|
||||
(c >= '0' && c <= '9') || c == '_' || c == '-') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
127
internal/server/router/handler/config.go
Normal file
127
internal/server/router/handler/config.go
Normal file
@@ -0,0 +1,127 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
// removed router import
|
||||
"github.com/gotunnel/internal/server/router/dto"
|
||||
)
|
||||
|
||||
// ConfigHandler 配置处理器
|
||||
type ConfigHandler struct {
|
||||
app AppInterface
|
||||
}
|
||||
|
||||
// NewConfigHandler 创建配置处理器
|
||||
func NewConfigHandler(app AppInterface) *ConfigHandler {
|
||||
return &ConfigHandler{app: app}
|
||||
}
|
||||
|
||||
// Get 获取服务器配置
|
||||
// @Summary 获取配置
|
||||
// @Description 返回服务器配置(敏感信息脱敏)
|
||||
// @Tags 配置
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Success 200 {object} Response{data=dto.ServerConfigResponse}
|
||||
// @Router /api/config [get]
|
||||
func (h *ConfigHandler) Get(c *gin.Context) {
|
||||
cfg := h.app.GetConfig()
|
||||
|
||||
// Token 脱敏处理,只显示前4位
|
||||
maskedToken := cfg.Server.Token
|
||||
if len(maskedToken) > 4 {
|
||||
maskedToken = maskedToken[:4] + "****"
|
||||
}
|
||||
|
||||
resp := dto.ServerConfigResponse{
|
||||
Server: dto.ServerConfigInfo{
|
||||
BindAddr: cfg.Server.BindAddr,
|
||||
BindPort: cfg.Server.BindPort,
|
||||
Token: maskedToken,
|
||||
HeartbeatSec: cfg.Server.HeartbeatSec,
|
||||
HeartbeatTimeout: cfg.Server.HeartbeatTimeout,
|
||||
},
|
||||
Web: dto.WebConfigInfo{
|
||||
Enabled: cfg.Server.Web.Enabled,
|
||||
BindPort: cfg.Server.Web.BindPort,
|
||||
Username: cfg.Server.Web.Username,
|
||||
Password: "****",
|
||||
},
|
||||
}
|
||||
|
||||
Success(c, resp)
|
||||
}
|
||||
|
||||
// Update 更新服务器配置
|
||||
// @Summary 更新配置
|
||||
// @Description 更新服务器配置
|
||||
// @Tags 配置
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param request body dto.UpdateServerConfigRequest true "配置内容"
|
||||
// @Success 200 {object} Response
|
||||
// @Failure 400 {object} Response
|
||||
// @Router /api/config [put]
|
||||
func (h *ConfigHandler) Update(c *gin.Context) {
|
||||
var req dto.UpdateServerConfigRequest
|
||||
if !BindJSON(c, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
cfg := h.app.GetConfig()
|
||||
|
||||
// 更新 Server 配置
|
||||
if req.Server != nil {
|
||||
if req.Server.BindAddr != "" {
|
||||
cfg.Server.BindAddr = req.Server.BindAddr
|
||||
}
|
||||
if req.Server.BindPort > 0 {
|
||||
cfg.Server.BindPort = req.Server.BindPort
|
||||
}
|
||||
if req.Server.Token != "" {
|
||||
cfg.Server.Token = req.Server.Token
|
||||
}
|
||||
if req.Server.HeartbeatSec > 0 {
|
||||
cfg.Server.HeartbeatSec = req.Server.HeartbeatSec
|
||||
}
|
||||
if req.Server.HeartbeatTimeout > 0 {
|
||||
cfg.Server.HeartbeatTimeout = req.Server.HeartbeatTimeout
|
||||
}
|
||||
}
|
||||
|
||||
// 更新 Web 配置
|
||||
if req.Web != nil {
|
||||
cfg.Server.Web.Enabled = req.Web.Enabled
|
||||
if req.Web.BindPort > 0 {
|
||||
cfg.Server.Web.BindPort = req.Web.BindPort
|
||||
}
|
||||
cfg.Server.Web.Username = req.Web.Username
|
||||
cfg.Server.Web.Password = req.Web.Password
|
||||
}
|
||||
|
||||
if err := h.app.SaveConfig(); err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, gin.H{"status": "ok"})
|
||||
}
|
||||
|
||||
// Reload 重新加载配置
|
||||
// @Summary 重新加载配置
|
||||
// @Description 重新加载服务器配置
|
||||
// @Tags 配置
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Success 200 {object} Response
|
||||
// @Failure 500 {object} Response
|
||||
// @Router /api/config/reload [post]
|
||||
func (h *ConfigHandler) Reload(c *gin.Context) {
|
||||
if err := h.app.GetServer().ReloadConfig(); err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, gin.H{"status": "ok"})
|
||||
}
|
||||
207
internal/server/router/handler/helpers.go
Normal file
207
internal/server/router/handler/helpers.go
Normal file
@@ -0,0 +1,207 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/gotunnel/pkg/update"
|
||||
"github.com/gotunnel/pkg/version"
|
||||
)
|
||||
|
||||
// UpdateInfo 更新信息
|
||||
type UpdateInfo struct {
|
||||
Available bool `json:"available"`
|
||||
Current string `json:"current"`
|
||||
Latest string `json:"latest"`
|
||||
ReleaseNote string `json:"release_note"`
|
||||
DownloadURL string `json:"download_url"`
|
||||
AssetName string `json:"asset_name"`
|
||||
AssetSize int64 `json:"asset_size"`
|
||||
}
|
||||
|
||||
// checkUpdateForComponent 检查组件更新
|
||||
func checkUpdateForComponent(component string) (*UpdateInfo, error) {
|
||||
release, err := version.GetLatestRelease()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get latest release: %w", err)
|
||||
}
|
||||
|
||||
latestVersion := release.TagName
|
||||
currentVersion := version.Version
|
||||
available := version.CompareVersions(currentVersion, latestVersion) < 0
|
||||
|
||||
// 查找对应平台的资产
|
||||
var downloadURL string
|
||||
var assetName string
|
||||
var assetSize int64
|
||||
|
||||
if asset := findAssetForPlatform(release.Assets, component, runtime.GOOS, runtime.GOARCH); asset != nil {
|
||||
downloadURL = asset.BrowserDownloadURL
|
||||
assetName = asset.Name
|
||||
assetSize = asset.Size
|
||||
}
|
||||
|
||||
return &UpdateInfo{
|
||||
Available: available,
|
||||
Current: currentVersion,
|
||||
Latest: latestVersion,
|
||||
ReleaseNote: release.Body,
|
||||
DownloadURL: downloadURL,
|
||||
AssetName: assetName,
|
||||
AssetSize: assetSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// checkClientUpdateForPlatform 检查指定平台的客户端更新
|
||||
func checkClientUpdateForPlatform(osName, arch string) (*UpdateInfo, error) {
|
||||
if osName == "" {
|
||||
osName = runtime.GOOS
|
||||
}
|
||||
if arch == "" {
|
||||
arch = runtime.GOARCH
|
||||
}
|
||||
|
||||
release, err := version.GetLatestRelease()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get latest release: %w", err)
|
||||
}
|
||||
|
||||
latestVersion := release.TagName
|
||||
|
||||
// 查找对应平台的资产
|
||||
var downloadURL string
|
||||
var assetName string
|
||||
var assetSize int64
|
||||
|
||||
if asset := findAssetForPlatform(release.Assets, "client", osName, arch); asset != nil {
|
||||
downloadURL = asset.BrowserDownloadURL
|
||||
assetName = asset.Name
|
||||
assetSize = asset.Size
|
||||
}
|
||||
|
||||
return &UpdateInfo{
|
||||
Available: true,
|
||||
Current: "",
|
||||
Latest: latestVersion,
|
||||
ReleaseNote: release.Body,
|
||||
DownloadURL: downloadURL,
|
||||
AssetName: assetName,
|
||||
AssetSize: assetSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// findAssetForPlatform 在 Release 资产中查找匹配的文件
|
||||
// CI 格式: gotunnel-server-v1.0.0-linux-amd64.tar.gz
|
||||
// 或者: gotunnel-client-v1.0.0-windows-amd64.zip
|
||||
func findAssetForPlatform(assets []version.ReleaseAsset, component, osName, arch string) *version.ReleaseAsset {
|
||||
prefix := fmt.Sprintf("gotunnel-%s-", component)
|
||||
suffix := fmt.Sprintf("-%s-%s", osName, arch)
|
||||
|
||||
for i := range assets {
|
||||
name := assets[i].Name
|
||||
// 检查是否匹配 gotunnel-{component}-{version}-{os}-{arch}.{ext}
|
||||
if strings.HasPrefix(name, prefix) && strings.Contains(name, suffix) {
|
||||
return &assets[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// performSelfUpdate 执行自更新
|
||||
func performSelfUpdate(downloadURL string, restart bool) error {
|
||||
// 使用共享的下载和解压逻辑
|
||||
binaryPath, cleanup, err := update.DownloadAndExtract(downloadURL, "server")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
// 获取当前可执行文件路径
|
||||
currentPath, err := os.Executable()
|
||||
if err != nil {
|
||||
return fmt.Errorf("get executable: %w", err)
|
||||
}
|
||||
currentPath, _ = filepath.EvalSymlinks(currentPath)
|
||||
|
||||
// Windows 需要特殊处理(运行中的文件无法直接替换)
|
||||
if runtime.GOOS == "windows" {
|
||||
return performWindowsUpdate(binaryPath, currentPath, restart)
|
||||
}
|
||||
|
||||
// Linux/Mac: 直接替换
|
||||
backupPath := currentPath + ".bak"
|
||||
|
||||
// 备份当前文件
|
||||
if err := os.Rename(currentPath, backupPath); err != nil {
|
||||
return fmt.Errorf("backup current: %w", err)
|
||||
}
|
||||
|
||||
// 复制新文件(不能用 rename,可能跨文件系统)
|
||||
if err := update.CopyFile(binaryPath, currentPath); err != nil {
|
||||
os.Rename(backupPath, currentPath)
|
||||
return fmt.Errorf("replace binary: %w", err)
|
||||
}
|
||||
|
||||
// 设置执行权限
|
||||
if err := os.Chmod(currentPath, 0755); err != nil {
|
||||
os.Rename(backupPath, currentPath)
|
||||
return fmt.Errorf("chmod new binary: %w", err)
|
||||
}
|
||||
|
||||
// 删除备份
|
||||
os.Remove(backupPath)
|
||||
|
||||
if restart {
|
||||
restartProcess(currentPath)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// performWindowsUpdate Windows 平台更新
|
||||
func performWindowsUpdate(newFile, currentPath string, restart bool) error {
|
||||
batchScript := fmt.Sprintf(`@echo off
|
||||
:: Check for admin rights, request UAC elevation if needed
|
||||
net session >nul 2>&1
|
||||
if %%errorlevel%% neq 0 (
|
||||
powershell -Command "Start-Process cmd -ArgumentList '/C \\"\"%%~f0\"\"' -Verb RunAs"
|
||||
exit /b
|
||||
)
|
||||
ping 127.0.0.1 -n 2 > nul
|
||||
del "%s"
|
||||
move "%s" "%s"
|
||||
`, currentPath, newFile, currentPath)
|
||||
|
||||
if restart {
|
||||
batchScript += fmt.Sprintf(`start "" "%s"
|
||||
`, currentPath)
|
||||
}
|
||||
|
||||
batchScript += "del \"%~f0\"\n"
|
||||
|
||||
batchPath := filepath.Join(os.TempDir(), "gotunnel_update.bat")
|
||||
if err := os.WriteFile(batchPath, []byte(batchScript), 0755); err != nil {
|
||||
return fmt.Errorf("write batch: %w", err)
|
||||
}
|
||||
|
||||
cmd := exec.Command("cmd", "/C", "start", "/MIN", batchPath)
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("start batch: %w", err)
|
||||
}
|
||||
|
||||
os.Exit(0)
|
||||
return nil
|
||||
}
|
||||
|
||||
// restartProcess 重启进程
|
||||
func restartProcess(path string) {
|
||||
cmd := exec.Command(path, os.Args[1:]...)
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
cmd.Start()
|
||||
os.Exit(0)
|
||||
}
|
||||
89
internal/server/router/handler/install.go
Normal file
89
internal/server/router/handler/install.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gotunnel/internal/server/db"
|
||||
)
|
||||
|
||||
// InstallHandler 安装处理器
|
||||
type InstallHandler struct {
|
||||
app AppInterface
|
||||
}
|
||||
|
||||
// NewInstallHandler 创建安装处理器
|
||||
func NewInstallHandler(app AppInterface) *InstallHandler {
|
||||
return &InstallHandler{app: app}
|
||||
}
|
||||
|
||||
// InstallCommandResponse 安装命令响应
|
||||
type InstallCommandResponse struct {
|
||||
Token string `json:"token"`
|
||||
Commands map[string]string `json:"commands"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
ServerAddr string `json:"server_addr"`
|
||||
}
|
||||
|
||||
// GenerateInstallCommand 生成安装命令
|
||||
// @Summary 生成客户端安装命令
|
||||
// @Tags install
|
||||
// @Produce json
|
||||
// @Success 200 {object} InstallCommandResponse
|
||||
// @Router /api/install/generate [post]
|
||||
func (h *InstallHandler) GenerateInstallCommand(c *gin.Context) {
|
||||
// 生成随机token
|
||||
tokenBytes := make([]byte, 32)
|
||||
if _, err := rand.Read(tokenBytes); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "生成token失败"})
|
||||
return
|
||||
}
|
||||
token := hex.EncodeToString(tokenBytes)
|
||||
|
||||
// 保存到数据库
|
||||
now := time.Now().Unix()
|
||||
installToken := &db.InstallToken{
|
||||
Token: token,
|
||||
CreatedAt: now,
|
||||
Used: false,
|
||||
}
|
||||
|
||||
store, ok := h.app.GetClientStore().(db.InstallTokenStore)
|
||||
if !ok {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "存储不支持安装token"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := store.CreateInstallToken(installToken); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存token失败"})
|
||||
return
|
||||
}
|
||||
|
||||
// 获取服务器地址
|
||||
serverAddr := fmt.Sprintf("%s:%d", h.app.GetConfig().Server.BindAddr, h.app.GetServer().GetBindPort())
|
||||
if h.app.GetConfig().Server.BindAddr == "" || h.app.GetConfig().Server.BindAddr == "0.0.0.0" {
|
||||
serverAddr = fmt.Sprintf("your-server-ip:%d", h.app.GetServer().GetBindPort())
|
||||
}
|
||||
|
||||
// 生成安装命令
|
||||
expiresAt := now + 3600 // 1小时过期
|
||||
commands := map[string]string{
|
||||
"linux": fmt.Sprintf("curl -fsSL https://raw.githubusercontent.com/gotunnel/gotunnel/main/scripts/install.sh | bash -s -- -s %s -t %s",
|
||||
serverAddr, token),
|
||||
"macos": fmt.Sprintf("curl -fsSL https://raw.githubusercontent.com/gotunnel/gotunnel/main/scripts/install.sh | bash -s -- -s %s -t %s",
|
||||
serverAddr, token),
|
||||
"windows": fmt.Sprintf("powershell -c \"irm https://raw.githubusercontent.com/gotunnel/gotunnel/main/scripts/install.ps1 | iex; Install-GoTunnel -Server '%s' -Token '%s'\"",
|
||||
serverAddr, token),
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, InstallCommandResponse{
|
||||
Token: token,
|
||||
Commands: commands,
|
||||
ExpiresAt: expiresAt,
|
||||
ServerAddr: serverAddr,
|
||||
})
|
||||
}
|
||||
50
internal/server/router/handler/interfaces.go
Normal file
50
internal/server/router/handler/interfaces.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/gotunnel/internal/server/config"
|
||||
"github.com/gotunnel/internal/server/db"
|
||||
"github.com/gotunnel/pkg/protocol"
|
||||
)
|
||||
|
||||
// AppInterface 应用接口
|
||||
type AppInterface interface {
|
||||
GetClientStore() db.ClientStore
|
||||
GetServer() ServerInterface
|
||||
GetConfig() *config.ServerConfig
|
||||
GetConfigPath() string
|
||||
SaveConfig() error
|
||||
GetTrafficStore() db.TrafficStore
|
||||
}
|
||||
|
||||
// ServerInterface 服务端接口
|
||||
type ServerInterface interface {
|
||||
IsClientOnline(clientID string) bool
|
||||
GetClientStatus(clientID string) (online bool, lastPing, remoteAddr, clientName, clientOS, clientArch, clientVersion string)
|
||||
GetAllClientStatus() map[string]struct {
|
||||
Online bool
|
||||
LastPing string
|
||||
RemoteAddr string
|
||||
Name string
|
||||
OS string
|
||||
Arch string
|
||||
Version string
|
||||
}
|
||||
ReloadConfig() error
|
||||
GetBindAddr() string
|
||||
GetBindPort() int
|
||||
PushConfigToClient(clientID string) error
|
||||
DisconnectClient(clientID string) error
|
||||
RestartClient(clientID string) error
|
||||
SendUpdateToClient(clientID, downloadURL string) error
|
||||
// 日志流
|
||||
StartClientLogStream(clientID, sessionID string, lines int, follow bool, level string) (<-chan protocol.LogEntry, error)
|
||||
StopClientLogStream(sessionID string)
|
||||
// 端口检查
|
||||
IsPortAvailable(port int, excludeClientID string) bool
|
||||
// 系统状态
|
||||
GetClientSystemStats(clientID string) (*protocol.SystemStatsResponse, error)
|
||||
// 截图
|
||||
GetClientScreenshot(clientID string, quality int) (*protocol.ScreenshotResponse, error)
|
||||
// Shell 执行
|
||||
ExecuteClientShell(clientID, command string, timeout int) (*protocol.ShellExecuteResponse, error)
|
||||
}
|
||||
95
internal/server/router/handler/log.go
Normal file
95
internal/server/router/handler/log.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"io"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// LogHandler 日志处理器
|
||||
type LogHandler struct {
|
||||
app AppInterface
|
||||
}
|
||||
|
||||
// NewLogHandler 创建日志处理器
|
||||
func NewLogHandler(app AppInterface) *LogHandler {
|
||||
return &LogHandler{app: app}
|
||||
}
|
||||
|
||||
// StreamLogs 流式传输客户端日志
|
||||
// @Summary 流式传输客户端日志
|
||||
// @Description 通过 Server-Sent Events 实时接收客户端日志
|
||||
// @Tags Logs
|
||||
// @Produce text/event-stream
|
||||
// @Security Bearer
|
||||
// @Param id path string true "客户端 ID"
|
||||
// @Param lines query int false "初始日志行数" default(100)
|
||||
// @Param follow query bool false "是否持续推送新日志" default(true)
|
||||
// @Param level query string false "日志级别过滤 (info, warn, error)"
|
||||
// @Success 200 {object} protocol.LogEntry
|
||||
// @Router /api/client/{id}/logs [get]
|
||||
func (h *LogHandler) StreamLogs(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
|
||||
// 检查客户端是否在线
|
||||
if !h.app.GetServer().IsClientOnline(clientID) {
|
||||
c.JSON(400, gin.H{"code": 400, "message": "client not online"})
|
||||
return
|
||||
}
|
||||
|
||||
// 解析查询参数
|
||||
lines := 100
|
||||
if v := c.Query("lines"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil {
|
||||
lines = n
|
||||
}
|
||||
}
|
||||
|
||||
follow := true
|
||||
if v := c.Query("follow"); v == "false" {
|
||||
follow = false
|
||||
}
|
||||
|
||||
level := c.Query("level")
|
||||
|
||||
// 生成会话 ID
|
||||
sessionID := uuid.New().String()
|
||||
|
||||
// 启动日志流
|
||||
logCh, err := h.app.GetServer().StartClientLogStream(clientID, sessionID, lines, follow, level)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"code": 500, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// 设置 SSE 响应头
|
||||
c.Writer.Header().Set("Content-Type", "text/event-stream")
|
||||
c.Writer.Header().Set("Cache-Control", "no-cache")
|
||||
c.Writer.Header().Set("Connection", "keep-alive")
|
||||
c.Writer.Header().Set("X-Accel-Buffering", "no")
|
||||
|
||||
// 获取客户端断开信号
|
||||
clientGone := c.Request.Context().Done()
|
||||
|
||||
// 流式传输日志
|
||||
c.Stream(func(w io.Writer) bool {
|
||||
select {
|
||||
case <-clientGone:
|
||||
h.app.GetServer().StopClientLogStream(sessionID)
|
||||
return false
|
||||
case entry, ok := <-logCh:
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
c.SSEvent("log", entry)
|
||||
return true
|
||||
case <-time.After(30 * time.Second):
|
||||
// 发送心跳
|
||||
c.SSEvent("heartbeat", gin.H{"ts": time.Now().UnixMilli()})
|
||||
return true
|
||||
}
|
||||
})
|
||||
}
|
||||
159
internal/server/router/handler/response.go
Normal file
159
internal/server/router/handler/response.go
Normal file
@@ -0,0 +1,159 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
// Response 统一 API 响应结构
|
||||
type Response struct {
|
||||
Code int `json:"code"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// 业务错误码定义
|
||||
const (
|
||||
CodeSuccess = 0
|
||||
CodeBadRequest = 400
|
||||
CodeUnauthorized = 401
|
||||
CodeForbidden = 403
|
||||
CodeNotFound = 404
|
||||
CodeConflict = 409
|
||||
CodeInternalError = 500
|
||||
CodeBadGateway = 502
|
||||
|
||||
CodeClientNotOnline = 1001
|
||||
CodePluginNotFound = 1002
|
||||
CodeInvalidClientID = 1003
|
||||
CodePluginDisabled = 1004
|
||||
CodeConfigSyncFailed = 1005
|
||||
)
|
||||
|
||||
// Success 成功响应
|
||||
func Success(c *gin.Context, data interface{}) {
|
||||
c.JSON(http.StatusOK, Response{
|
||||
Code: CodeSuccess,
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
// SuccessWithMessage 成功响应带消息
|
||||
func SuccessWithMessage(c *gin.Context, data interface{}, message string) {
|
||||
c.JSON(http.StatusOK, Response{
|
||||
Code: CodeSuccess,
|
||||
Data: data,
|
||||
Message: message,
|
||||
})
|
||||
}
|
||||
|
||||
// Error 错误响应
|
||||
func Error(c *gin.Context, httpCode int, bizCode int, message string) {
|
||||
c.JSON(httpCode, Response{
|
||||
Code: bizCode,
|
||||
Message: message,
|
||||
})
|
||||
}
|
||||
|
||||
// BadRequest 400 错误
|
||||
func BadRequest(c *gin.Context, message string) {
|
||||
Error(c, http.StatusBadRequest, CodeBadRequest, message)
|
||||
}
|
||||
|
||||
// Unauthorized 401 错误
|
||||
func Unauthorized(c *gin.Context, message string) {
|
||||
Error(c, http.StatusUnauthorized, CodeUnauthorized, message)
|
||||
}
|
||||
|
||||
// NotFound 404 错误
|
||||
func NotFound(c *gin.Context, message string) {
|
||||
Error(c, http.StatusNotFound, CodeNotFound, message)
|
||||
}
|
||||
|
||||
// Conflict 409 错误
|
||||
func Conflict(c *gin.Context, message string) {
|
||||
Error(c, http.StatusConflict, CodeConflict, message)
|
||||
}
|
||||
|
||||
// InternalError 500 错误
|
||||
func InternalError(c *gin.Context, message string) {
|
||||
Error(c, http.StatusInternalServerError, CodeInternalError, message)
|
||||
}
|
||||
|
||||
// BadGateway 502 错误
|
||||
func BadGateway(c *gin.Context, message string) {
|
||||
Error(c, http.StatusBadGateway, CodeBadGateway, message)
|
||||
}
|
||||
|
||||
// ClientNotOnline 客户端不在线错误
|
||||
func ClientNotOnline(c *gin.Context) {
|
||||
Error(c, http.StatusBadRequest, CodeClientNotOnline, "client not online")
|
||||
}
|
||||
|
||||
// PartialSuccess 部分成功响应
|
||||
func PartialSuccess(c *gin.Context, data interface{}, message string) {
|
||||
c.JSON(http.StatusOK, Response{
|
||||
Code: CodeConfigSyncFailed,
|
||||
Data: data,
|
||||
Message: message,
|
||||
})
|
||||
}
|
||||
|
||||
// BindJSON 绑定 JSON 并自动处理验证错误
|
||||
func BindJSON(c *gin.Context, obj interface{}) bool {
|
||||
if err := c.ShouldBindJSON(obj); err != nil {
|
||||
handleValidationError(c, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// BindQuery 绑定查询参数并自动处理验证错误
|
||||
func BindQuery(c *gin.Context, obj interface{}) bool {
|
||||
if err := c.ShouldBindQuery(obj); err != nil {
|
||||
handleValidationError(c, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// handleValidationError 处理验证错误
|
||||
func handleValidationError(c *gin.Context, err error) {
|
||||
var ve validator.ValidationErrors
|
||||
if errors.As(err, &ve) {
|
||||
errs := make([]map[string]string, len(ve))
|
||||
for i, fe := range ve {
|
||||
errs[i] = map[string]string{
|
||||
"field": fe.Field(),
|
||||
"message": getValidationMessage(fe),
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusBadRequest, Response{
|
||||
Code: CodeBadRequest,
|
||||
Message: "validation failed",
|
||||
Data: errs,
|
||||
})
|
||||
return
|
||||
}
|
||||
BadRequest(c, err.Error())
|
||||
}
|
||||
|
||||
func getValidationMessage(fe validator.FieldError) string {
|
||||
switch fe.Tag() {
|
||||
case "required":
|
||||
return "this field is required"
|
||||
case "min":
|
||||
return "value is too short or too small"
|
||||
case "max":
|
||||
return "value is too long or too large"
|
||||
case "url":
|
||||
return "invalid URL format"
|
||||
case "oneof":
|
||||
return "value must be one of: " + fe.Param()
|
||||
default:
|
||||
return "validation failed on " + fe.Tag()
|
||||
}
|
||||
}
|
||||
51
internal/server/router/handler/status.go
Normal file
51
internal/server/router/handler/status.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
// removed router import
|
||||
"github.com/gotunnel/internal/server/router/dto"
|
||||
)
|
||||
|
||||
// StatusHandler 状态处理器
|
||||
type StatusHandler struct {
|
||||
app AppInterface
|
||||
}
|
||||
|
||||
// NewStatusHandler 创建状态处理器
|
||||
func NewStatusHandler(app AppInterface) *StatusHandler {
|
||||
return &StatusHandler{app: app}
|
||||
}
|
||||
|
||||
// GetStatus 获取服务器状态
|
||||
// @Summary 获取服务器状态
|
||||
// @Description 返回服务器运行状态和客户端数量
|
||||
// @Tags 状态
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Success 200 {object} Response{data=dto.StatusResponse}
|
||||
// @Router /api/status [get]
|
||||
func (h *StatusHandler) GetStatus(c *gin.Context) {
|
||||
clients, _ := h.app.GetClientStore().GetAllClients()
|
||||
|
||||
status := dto.StatusResponse{
|
||||
Server: dto.ServerStatus{
|
||||
BindAddr: h.app.GetServer().GetBindAddr(),
|
||||
BindPort: h.app.GetServer().GetBindPort(),
|
||||
},
|
||||
ClientCount: len(clients),
|
||||
}
|
||||
|
||||
Success(c, status)
|
||||
}
|
||||
|
||||
// GetVersion 获取版本信息
|
||||
// @Summary 获取版本信息
|
||||
// @Description 返回服务器版本信息
|
||||
// @Tags 状态
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Success 200 {object} Response{data=dto.VersionInfo}
|
||||
// @Router /api/update/version [get]
|
||||
func (h *StatusHandler) GetVersion(c *gin.Context) {
|
||||
Success(c, getVersionInfo())
|
||||
}
|
||||
76
internal/server/router/handler/traffic.go
Normal file
76
internal/server/router/handler/traffic.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// TrafficHandler 流量统计处理器
|
||||
type TrafficHandler struct {
|
||||
app AppInterface
|
||||
}
|
||||
|
||||
// NewTrafficHandler 创建流量统计处理器
|
||||
func NewTrafficHandler(app AppInterface) *TrafficHandler {
|
||||
return &TrafficHandler{app: app}
|
||||
}
|
||||
|
||||
// GetStats 获取流量统计
|
||||
// @Summary 获取流量统计
|
||||
// @Description 获取24小时和总流量统计
|
||||
// @Tags 流量
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Success 200 {object} Response
|
||||
// @Router /api/traffic/stats [get]
|
||||
func (h *TrafficHandler) GetStats(c *gin.Context) {
|
||||
store := h.app.GetTrafficStore()
|
||||
|
||||
// 获取24小时流量
|
||||
in24h, out24h, err := store.Get24HourTraffic()
|
||||
if err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 获取总流量
|
||||
inTotal, outTotal, err := store.GetTotalTraffic()
|
||||
if err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, gin.H{
|
||||
"traffic_24h": gin.H{
|
||||
"inbound": in24h,
|
||||
"outbound": out24h,
|
||||
},
|
||||
"traffic_total": gin.H{
|
||||
"inbound": inTotal,
|
||||
"outbound": outTotal,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// GetHourly 获取每小时流量
|
||||
// @Summary 获取每小时流量
|
||||
// @Description 获取最近N小时的流量记录
|
||||
// @Tags 流量
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param hours query int false "小时数" default(24)
|
||||
// @Success 200 {object} Response
|
||||
// @Router /api/traffic/hourly [get]
|
||||
func (h *TrafficHandler) GetHourly(c *gin.Context) {
|
||||
hours := 24
|
||||
|
||||
store := h.app.GetTrafficStore()
|
||||
records, err := store.GetHourlyTraffic(hours)
|
||||
if err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, gin.H{
|
||||
"records": records,
|
||||
})
|
||||
}
|
||||
133
internal/server/router/handler/update.go
Normal file
133
internal/server/router/handler/update.go
Normal file
@@ -0,0 +1,133 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
// removed router import
|
||||
"github.com/gotunnel/internal/server/router/dto"
|
||||
"github.com/gotunnel/pkg/version"
|
||||
)
|
||||
|
||||
// UpdateHandler 更新处理器
|
||||
type UpdateHandler struct {
|
||||
app AppInterface
|
||||
}
|
||||
|
||||
// NewUpdateHandler 创建更新处理器
|
||||
func NewUpdateHandler(app AppInterface) *UpdateHandler {
|
||||
return &UpdateHandler{app: app}
|
||||
}
|
||||
|
||||
// CheckServer 检查服务端更新
|
||||
// @Summary 检查服务端更新
|
||||
// @Description 检查是否有新的服务端版本可用
|
||||
// @Tags 更新
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Success 200 {object} Response{data=dto.CheckUpdateResponse}
|
||||
// @Router /api/update/check/server [get]
|
||||
func (h *UpdateHandler) CheckServer(c *gin.Context) {
|
||||
updateInfo, err := checkUpdateForComponent("server")
|
||||
if err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, updateInfo)
|
||||
}
|
||||
|
||||
// CheckClient 检查客户端更新
|
||||
// @Summary 检查客户端更新
|
||||
// @Description 检查是否有新的客户端版本可用
|
||||
// @Tags 更新
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param os query string false "操作系统" Enums(linux, darwin, windows)
|
||||
// @Param arch query string false "架构" Enums(amd64, arm64, 386, arm)
|
||||
// @Success 200 {object} Response{data=dto.CheckUpdateResponse}
|
||||
// @Router /api/update/check/client [get]
|
||||
func (h *UpdateHandler) CheckClient(c *gin.Context) {
|
||||
var query dto.CheckClientUpdateQuery
|
||||
if !BindQuery(c, &query) {
|
||||
return
|
||||
}
|
||||
|
||||
updateInfo, err := checkClientUpdateForPlatform(query.OS, query.Arch)
|
||||
if err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, updateInfo)
|
||||
}
|
||||
|
||||
// ApplyServer 应用服务端更新
|
||||
// @Summary 应用服务端更新
|
||||
// @Description 下载并应用服务端更新,服务器将自动重启
|
||||
// @Tags 更新
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param request body dto.ApplyServerUpdateRequest true "更新请求"
|
||||
// @Success 200 {object} Response
|
||||
// @Failure 400 {object} Response
|
||||
// @Router /api/update/apply/server [post]
|
||||
func (h *UpdateHandler) ApplyServer(c *gin.Context) {
|
||||
var req dto.ApplyServerUpdateRequest
|
||||
if !BindJSON(c, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
// 异步执行更新
|
||||
go func() {
|
||||
if err := performSelfUpdate(req.DownloadURL, req.Restart); err != nil {
|
||||
println("[Update] Server update failed:", err.Error())
|
||||
}
|
||||
}()
|
||||
|
||||
Success(c, gin.H{
|
||||
"success": true,
|
||||
"message": "Update started, server will restart shortly",
|
||||
})
|
||||
}
|
||||
|
||||
// ApplyClient 应用客户端更新
|
||||
// @Summary 推送客户端更新
|
||||
// @Description 向指定客户端推送更新命令
|
||||
// @Tags 更新
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security Bearer
|
||||
// @Param request body dto.ApplyClientUpdateRequest true "更新请求"
|
||||
// @Success 200 {object} Response
|
||||
// @Failure 400 {object} Response
|
||||
// @Router /api/update/apply/client [post]
|
||||
func (h *UpdateHandler) ApplyClient(c *gin.Context) {
|
||||
var req dto.ApplyClientUpdateRequest
|
||||
if !BindJSON(c, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
// 发送更新命令到客户端
|
||||
if err := h.app.GetServer().SendUpdateToClient(req.ClientID, req.DownloadURL); err != nil {
|
||||
InternalError(c, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, gin.H{
|
||||
"success": true,
|
||||
"message": "Update command sent to client",
|
||||
})
|
||||
}
|
||||
|
||||
// getVersionInfo 获取版本信息
|
||||
func getVersionInfo() dto.VersionInfo {
|
||||
info := version.GetInfo()
|
||||
return dto.VersionInfo{
|
||||
Version: info.Version,
|
||||
GitCommit: info.GitCommit,
|
||||
BuildTime: info.BuildTime,
|
||||
GoVersion: info.GoVersion,
|
||||
OS: info.OS,
|
||||
Arch: info.Arch,
|
||||
}
|
||||
}
|
||||
28
internal/server/router/middleware/cors.go
Normal file
28
internal/server/router/middleware/cors.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CORS 跨域中间件
|
||||
func CORS() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
origin := c.GetHeader("Origin")
|
||||
if origin == "" {
|
||||
origin = "*"
|
||||
}
|
||||
|
||||
c.Header("Access-Control-Allow-Origin", origin)
|
||||
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS")
|
||||
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization, X-Request-ID")
|
||||
c.Header("Access-Control-Allow-Credentials", "true")
|
||||
c.Header("Access-Control-Max-Age", "86400")
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
57
internal/server/router/middleware/jwt.go
Normal file
57
internal/server/router/middleware/jwt.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gotunnel/pkg/auth"
|
||||
)
|
||||
|
||||
// JWTAuth JWT 认证中间件
|
||||
func JWTAuth(jwtAuth *auth.JWTAuth) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
|
||||
// 支持从 query 参数获取 token (用于 SSE 等不支持自定义 header 的场景)
|
||||
if authHeader == "" {
|
||||
if token := c.Query("token"); token != "" {
|
||||
authHeader = "Bearer " + token
|
||||
}
|
||||
}
|
||||
|
||||
if authHeader == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"code": 401,
|
||||
"message": "missing authorization header",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"code": 401,
|
||||
"message": "invalid authorization format",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
token := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
claims, err := jwtAuth.ValidateToken(token)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"code": 401,
|
||||
"message": "invalid or expired token",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 将用户信息存入上下文
|
||||
c.Set("username", claims.Username)
|
||||
c.Set("claims", claims)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
58
internal/server/router/middleware/logger.go
Normal file
58
internal/server/router/middleware/logger.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// 静态资源扩展名
|
||||
var staticExtensions = []string{
|
||||
".js", ".css", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico",
|
||||
".woff", ".woff2", ".ttf", ".eot", ".map", ".json", ".html",
|
||||
}
|
||||
|
||||
// isStaticRequest 检查是否是静态资源请求
|
||||
func isStaticRequest(path string) bool {
|
||||
// 检查 /assets/ 路径
|
||||
if strings.HasPrefix(path, "/assets/") {
|
||||
return true
|
||||
}
|
||||
// 检查文件扩展名
|
||||
for _, ext := range staticExtensions {
|
||||
if strings.HasSuffix(path, ext) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Logger 请求日志中间件
|
||||
func Logger() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
path := c.Request.URL.Path
|
||||
query := c.Request.URL.RawQuery
|
||||
method := c.Request.Method
|
||||
|
||||
c.Next()
|
||||
|
||||
// 跳过静态资源请求的日志
|
||||
if isStaticRequest(path) {
|
||||
return
|
||||
}
|
||||
|
||||
latency := time.Since(start)
|
||||
status := c.Writer.Status()
|
||||
clientIP := c.ClientIP()
|
||||
|
||||
if query != "" {
|
||||
path = path + "?" + query
|
||||
}
|
||||
|
||||
log.Printf("[API] %s %s %d %v %s",
|
||||
method, path, status, latency, clientIP)
|
||||
}
|
||||
}
|
||||
26
internal/server/router/middleware/recovery.go
Normal file
26
internal/server/router/middleware/recovery.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Recovery 自定义恢复中间件(返回统一格式)
|
||||
func Recovery() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Printf("[PANIC] %v\n%s", err, debug.Stack())
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"code": 500,
|
||||
"message": "internal server error",
|
||||
})
|
||||
c.Abort()
|
||||
}
|
||||
}()
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
116
internal/server/router/response.go
Normal file
116
internal/server/router/response.go
Normal file
@@ -0,0 +1,116 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Response 统一 API 响应结构
|
||||
type Response struct {
|
||||
Code int `json:"code"` // 业务状态码: 0=成功, 非0=错误
|
||||
Data interface{} `json:"data,omitempty"` // 响应数据
|
||||
Message string `json:"message,omitempty"` // 提示信息
|
||||
}
|
||||
|
||||
// 业务错误码定义
|
||||
const (
|
||||
CodeSuccess = 0 // 成功
|
||||
CodeBadRequest = 400 // 请求参数错误
|
||||
CodeUnauthorized = 401 // 未授权
|
||||
CodeForbidden = 403 // 禁止访问
|
||||
CodeNotFound = 404 // 资源不存在
|
||||
CodeConflict = 409 // 资源冲突
|
||||
CodeInternalError = 500 // 服务器内部错误
|
||||
CodeBadGateway = 502 // 网关错误
|
||||
|
||||
// 业务错误码 (1000+)
|
||||
CodeClientNotOnline = 1001 // 客户端不在线
|
||||
CodePluginNotFound = 1002 // 插件不存在
|
||||
CodeInvalidClientID = 1003 // 无效的客户端ID
|
||||
CodePluginDisabled = 1004 // 插件已禁用
|
||||
CodeConfigSyncFailed = 1005 // 配置同步失败
|
||||
)
|
||||
|
||||
// Success 成功响应
|
||||
func Success(c *gin.Context, data interface{}) {
|
||||
c.JSON(http.StatusOK, Response{
|
||||
Code: CodeSuccess,
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
// SuccessWithMessage 成功响应带消息
|
||||
func SuccessWithMessage(c *gin.Context, data interface{}, message string) {
|
||||
c.JSON(http.StatusOK, Response{
|
||||
Code: CodeSuccess,
|
||||
Data: data,
|
||||
Message: message,
|
||||
})
|
||||
}
|
||||
|
||||
// Error 错误响应
|
||||
func Error(c *gin.Context, httpCode int, bizCode int, message string) {
|
||||
c.JSON(httpCode, Response{
|
||||
Code: bizCode,
|
||||
Message: message,
|
||||
})
|
||||
}
|
||||
|
||||
// ErrorWithData 错误响应带数据
|
||||
func ErrorWithData(c *gin.Context, httpCode int, bizCode int, message string, data interface{}) {
|
||||
c.JSON(httpCode, Response{
|
||||
Code: bizCode,
|
||||
Message: message,
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
// BadRequest 400 错误
|
||||
func BadRequest(c *gin.Context, message string) {
|
||||
Error(c, http.StatusBadRequest, CodeBadRequest, message)
|
||||
}
|
||||
|
||||
// Unauthorized 401 错误
|
||||
func Unauthorized(c *gin.Context, message string) {
|
||||
Error(c, http.StatusUnauthorized, CodeUnauthorized, message)
|
||||
}
|
||||
|
||||
// Forbidden 403 错误
|
||||
func Forbidden(c *gin.Context, message string) {
|
||||
Error(c, http.StatusForbidden, CodeForbidden, message)
|
||||
}
|
||||
|
||||
// NotFound 404 错误
|
||||
func NotFound(c *gin.Context, message string) {
|
||||
Error(c, http.StatusNotFound, CodeNotFound, message)
|
||||
}
|
||||
|
||||
// Conflict 409 错误
|
||||
func Conflict(c *gin.Context, message string) {
|
||||
Error(c, http.StatusConflict, CodeConflict, message)
|
||||
}
|
||||
|
||||
// InternalError 500 错误
|
||||
func InternalError(c *gin.Context, message string) {
|
||||
Error(c, http.StatusInternalServerError, CodeInternalError, message)
|
||||
}
|
||||
|
||||
// BadGateway 502 错误
|
||||
func BadGateway(c *gin.Context, message string) {
|
||||
Error(c, http.StatusBadGateway, CodeBadGateway, message)
|
||||
}
|
||||
|
||||
// ClientNotOnline 客户端不在线错误
|
||||
func ClientNotOnline(c *gin.Context) {
|
||||
Error(c, http.StatusBadRequest, CodeClientNotOnline, "client not online")
|
||||
}
|
||||
|
||||
// PartialSuccess 部分成功响应
|
||||
func PartialSuccess(c *gin.Context, data interface{}, message string) {
|
||||
c.JSON(http.StatusOK, Response{
|
||||
Code: CodeConfigSyncFailed,
|
||||
Data: data,
|
||||
Message: message,
|
||||
})
|
||||
}
|
||||
@@ -1,123 +1,180 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
swaggerFiles "github.com/swaggo/files"
|
||||
ginSwagger "github.com/swaggo/gin-swagger"
|
||||
|
||||
"github.com/gotunnel/internal/server/router/handler"
|
||||
"github.com/gotunnel/internal/server/router/middleware"
|
||||
"github.com/gotunnel/pkg/auth"
|
||||
)
|
||||
|
||||
// Router 路由管理器
|
||||
type Router struct {
|
||||
mux *http.ServeMux
|
||||
// GinRouter Gin 路由管理器
|
||||
type GinRouter struct {
|
||||
Engine *gin.Engine
|
||||
}
|
||||
|
||||
// AuthConfig 认证配置
|
||||
type AuthConfig struct {
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
// New 创建路由管理器
|
||||
func New() *Router {
|
||||
return &Router{
|
||||
mux: http.NewServeMux(),
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 注册路由处理器
|
||||
func (r *Router) Handle(pattern string, handler http.Handler) {
|
||||
r.mux.Handle(pattern, handler)
|
||||
}
|
||||
|
||||
// HandleFunc 注册路由处理函数
|
||||
func (r *Router) HandleFunc(pattern string, handler http.HandlerFunc) {
|
||||
r.mux.HandleFunc(pattern, handler)
|
||||
}
|
||||
|
||||
// Group 创建路由组
|
||||
func (r *Router) Group(prefix string) *RouteGroup {
|
||||
return &RouteGroup{
|
||||
router: r,
|
||||
prefix: prefix,
|
||||
}
|
||||
}
|
||||
|
||||
// RouteGroup 路由组
|
||||
type RouteGroup struct {
|
||||
router *Router
|
||||
prefix string
|
||||
}
|
||||
|
||||
// HandleFunc 注册路由组处理函数
|
||||
func (g *RouteGroup) HandleFunc(pattern string, handler http.HandlerFunc) {
|
||||
g.router.mux.HandleFunc(g.prefix+pattern, handler)
|
||||
// New 创建 Gin 路由管理器
|
||||
func New() *GinRouter {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
engine := gin.New()
|
||||
return &GinRouter{Engine: engine}
|
||||
}
|
||||
|
||||
// Handler 返回 http.Handler
|
||||
func (r *Router) Handler() http.Handler {
|
||||
return r.mux
|
||||
func (r *GinRouter) Handler() http.Handler {
|
||||
return r.Engine
|
||||
}
|
||||
|
||||
// BasicAuthMiddleware 基础认证中间件
|
||||
func BasicAuthMiddleware(auth *AuthConfig, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if auth == nil || (auth.Username == "" && auth.Password == "") {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
// SetupRoutes 配置所有路由
|
||||
func (r *GinRouter) SetupRoutes(app handler.AppInterface, jwtAuth *auth.JWTAuth, username, password string) {
|
||||
engine := r.Engine
|
||||
|
||||
user, pass, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="GoTunnel"`)
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
// 全局中间件
|
||||
engine.Use(middleware.Recovery())
|
||||
engine.Use(middleware.Logger())
|
||||
engine.Use(middleware.CORS())
|
||||
|
||||
userMatch := subtle.ConstantTimeCompare([]byte(user), []byte(auth.Username)) == 1
|
||||
passMatch := subtle.ConstantTimeCompare([]byte(pass), []byte(auth.Password)) == 1
|
||||
// Swagger 文档
|
||||
engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
|
||||
|
||||
if !userMatch || !passMatch {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="GoTunnel"`)
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
// 认证路由 (无需 JWT)
|
||||
authHandler := handler.NewAuthHandler(username, password, jwtAuth)
|
||||
engine.POST("/api/auth/login", authHandler.Login)
|
||||
engine.GET("/api/auth/check", authHandler.Check)
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
// API 路由 (需要 JWT)
|
||||
api := engine.Group("/api")
|
||||
api.Use(middleware.JWTAuth(jwtAuth))
|
||||
{
|
||||
// 状态
|
||||
statusHandler := handler.NewStatusHandler(app)
|
||||
api.GET("/status", statusHandler.GetStatus)
|
||||
api.GET("/update/version", statusHandler.GetVersion)
|
||||
|
||||
// 客户端管理
|
||||
clientHandler := handler.NewClientHandler(app)
|
||||
api.GET("/clients", clientHandler.List)
|
||||
api.POST("/clients", clientHandler.Create)
|
||||
api.GET("/client/:id", clientHandler.Get)
|
||||
api.PUT("/client/:id", clientHandler.Update)
|
||||
api.DELETE("/client/:id", clientHandler.Delete)
|
||||
api.POST("/client/:id/push", clientHandler.PushConfig)
|
||||
api.POST("/client/:id/disconnect", clientHandler.Disconnect)
|
||||
api.POST("/client/:id/restart", clientHandler.Restart)
|
||||
api.GET("/client/:id/system-stats", clientHandler.GetSystemStats)
|
||||
api.GET("/client/:id/screenshot", clientHandler.GetScreenshot)
|
||||
api.POST("/client/:id/shell", clientHandler.ExecuteShell)
|
||||
|
||||
// 配置管理
|
||||
configHandler := handler.NewConfigHandler(app)
|
||||
api.GET("/config", configHandler.Get)
|
||||
api.PUT("/config", configHandler.Update)
|
||||
api.POST("/config/reload", configHandler.Reload)
|
||||
|
||||
// 更新管理
|
||||
updateHandler := handler.NewUpdateHandler(app)
|
||||
api.GET("/update/check/server", updateHandler.CheckServer)
|
||||
api.GET("/update/check/client", updateHandler.CheckClient)
|
||||
api.POST("/update/apply/server", updateHandler.ApplyServer)
|
||||
api.POST("/update/apply/client", updateHandler.ApplyClient)
|
||||
|
||||
// 日志管理
|
||||
logHandler := handler.NewLogHandler(app)
|
||||
api.GET("/client/:id/logs", logHandler.StreamLogs)
|
||||
|
||||
// 流量统计
|
||||
trafficHandler := handler.NewTrafficHandler(app)
|
||||
api.GET("/traffic/stats", trafficHandler.GetStats)
|
||||
api.GET("/traffic/hourly", trafficHandler.GetHourly)
|
||||
|
||||
// 安装命令生成
|
||||
installHandler := handler.NewInstallHandler(app)
|
||||
api.POST("/install/generate", installHandler.GenerateInstallCommand)
|
||||
}
|
||||
}
|
||||
|
||||
// JWTMiddleware JWT 认证中间件
|
||||
func JWTMiddleware(jwtAuth *auth.JWTAuth, skipPaths []string, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// 只对 /api/ 路径进行认证
|
||||
if !strings.HasPrefix(r.URL.Path, "/api/") {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// 检查是否跳过认证
|
||||
for _, path := range skipPaths {
|
||||
if strings.HasPrefix(r.URL.Path, path) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 从 Header 获取 token
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
|
||||
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
token := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
if _, err := jwtAuth.ValidateToken(token); err != nil {
|
||||
http.Error(w, `{"error":"invalid token"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
// SetupStaticFiles 配置静态文件处理
|
||||
func (r *GinRouter) SetupStaticFiles(staticFS fs.FS) {
|
||||
// 使用 NoRoute 处理 SPA 路由
|
||||
r.Engine.NoRoute(gin.WrapH(&spaHandler{fs: http.FS(staticFS)}))
|
||||
}
|
||||
|
||||
// spaHandler SPA 路由处理器
|
||||
type spaHandler struct {
|
||||
fs http.FileSystem
|
||||
}
|
||||
|
||||
func (h *spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Path
|
||||
|
||||
// API 请求不应该返回 SPA 页面
|
||||
if len(path) >= 4 && path[:4] == "/api" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
w.Write([]byte(`{"code":404,"message":"Not Found"}`))
|
||||
return
|
||||
}
|
||||
|
||||
// 尝试打开请求的文件
|
||||
f, err := h.fs.Open(path)
|
||||
if err != nil {
|
||||
// 文件不存在时,检查是否是静态资源请求
|
||||
// 静态资源(js, css, 图片等)应该返回 404,而不是 index.html
|
||||
if isStaticAsset(path) {
|
||||
http.Error(w, "Not Found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
// 其他路径返回 index.html(SPA 路由)
|
||||
f, err = h.fs.Open("index.html")
|
||||
if err != nil {
|
||||
http.Error(w, "Not Found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
stat, err := f.Stat()
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if stat.IsDir() {
|
||||
f.Close()
|
||||
f, err = h.fs.Open(path + "/index.html")
|
||||
if err != nil {
|
||||
f, _ = h.fs.Open("index.html")
|
||||
}
|
||||
stat, _ = f.Stat()
|
||||
}
|
||||
|
||||
if seeker, ok := f.(io.ReadSeeker); ok {
|
||||
http.ServeContent(w, r, path, stat.ModTime(), seeker)
|
||||
}
|
||||
}
|
||||
|
||||
// isStaticAsset 检查路径是否是静态资源
|
||||
func isStaticAsset(path string) bool {
|
||||
staticExtensions := []string{
|
||||
".js", ".css", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico",
|
||||
".woff", ".woff2", ".ttf", ".eot", ".map", ".json",
|
||||
}
|
||||
for _, ext := range staticExtensions {
|
||||
if len(path) > len(ext) && path[len(path)-len(ext):] == ext {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Re-export types from handler package for backward compatibility
|
||||
type (
|
||||
ServerInterface = handler.ServerInterface
|
||||
AppInterface = handler.AppInterface
|
||||
)
|
||||
|
||||
155
internal/server/tunnel/log_session.go
Normal file
155
internal/server/tunnel/log_session.go
Normal file
@@ -0,0 +1,155 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/gotunnel/pkg/protocol"
|
||||
)
|
||||
|
||||
// LogSessionManager 管理所有活跃的日志会话
|
||||
type LogSessionManager struct {
|
||||
sessions map[string]*LogSession
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// LogSession 日志流会话
|
||||
type LogSession struct {
|
||||
ID string
|
||||
ClientID string
|
||||
Stream net.Conn
|
||||
listeners []chan protocol.LogEntry
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
}
|
||||
|
||||
// NewLogSessionManager 创建日志会话管理器
|
||||
func NewLogSessionManager() *LogSessionManager {
|
||||
return &LogSessionManager{
|
||||
sessions: make(map[string]*LogSession),
|
||||
}
|
||||
}
|
||||
|
||||
// CreateSession 创建日志会话
|
||||
func (m *LogSessionManager) CreateSession(clientID, sessionID string, stream net.Conn) *LogSession {
|
||||
session := &LogSession{
|
||||
ID: sessionID,
|
||||
ClientID: clientID,
|
||||
Stream: stream,
|
||||
listeners: make([]chan protocol.LogEntry, 0),
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
m.sessions[sessionID] = session
|
||||
m.mu.Unlock()
|
||||
|
||||
return session
|
||||
}
|
||||
|
||||
// GetSession 获取会话
|
||||
func (m *LogSessionManager) GetSession(sessionID string) *LogSession {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return m.sessions[sessionID]
|
||||
}
|
||||
|
||||
// RemoveSession 移除会话
|
||||
func (m *LogSessionManager) RemoveSession(sessionID string) {
|
||||
m.mu.Lock()
|
||||
if session, ok := m.sessions[sessionID]; ok {
|
||||
session.Close()
|
||||
delete(m.sessions, sessionID)
|
||||
}
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
// GetSessionsByClient 获取客户端的所有会话
|
||||
func (m *LogSessionManager) GetSessionsByClient(clientID string) []*LogSession {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
var sessions []*LogSession
|
||||
for _, session := range m.sessions {
|
||||
if session.ClientID == clientID {
|
||||
sessions = append(sessions, session)
|
||||
}
|
||||
}
|
||||
return sessions
|
||||
}
|
||||
|
||||
// CleanupClientSessions 清理客户端的所有会话
|
||||
func (m *LogSessionManager) CleanupClientSessions(clientID string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
for id, session := range m.sessions {
|
||||
if session.ClientID == clientID {
|
||||
session.Close()
|
||||
delete(m.sessions, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AddListener 添加监听器
|
||||
func (s *LogSession) AddListener() <-chan protocol.LogEntry {
|
||||
ch := make(chan protocol.LogEntry, 100)
|
||||
s.mu.Lock()
|
||||
s.listeners = append(s.listeners, ch)
|
||||
s.mu.Unlock()
|
||||
return ch
|
||||
}
|
||||
|
||||
// RemoveListener 移除监听器
|
||||
func (s *LogSession) RemoveListener(ch <-chan protocol.LogEntry) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for i, listener := range s.listeners {
|
||||
if listener == ch {
|
||||
close(listener)
|
||||
s.listeners = append(s.listeners[:i], s.listeners[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Broadcast 广播日志条目到所有监听器
|
||||
func (s *LogSession) Broadcast(entry protocol.LogEntry) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for _, ch := range s.listeners {
|
||||
select {
|
||||
case ch <- entry:
|
||||
default:
|
||||
// 监听器太慢,丢弃日志
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Close 关闭会话
|
||||
func (s *LogSession) Close() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.closed {
|
||||
return
|
||||
}
|
||||
s.closed = true
|
||||
|
||||
for _, ch := range s.listeners {
|
||||
close(ch)
|
||||
}
|
||||
s.listeners = nil
|
||||
|
||||
if s.Stream != nil {
|
||||
s.Stream.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// IsClosed 检查会话是否已关闭
|
||||
func (s *LogSession) IsClosed() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.closed
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
146
internal/server/tunnel/websocket.go
Normal file
146
internal/server/tunnel/websocket.go
Normal file
@@ -0,0 +1,146 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/gotunnel/pkg/protocol"
|
||||
"github.com/gotunnel/pkg/relay"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
return true // 允许所有跨域请求
|
||||
},
|
||||
}
|
||||
|
||||
// WSConnAdapter 适配器:将 websocket.Conn 适配为 io.ReadWriter
|
||||
type WSConnAdapter struct {
|
||||
conn *websocket.Conn
|
||||
// 读缓冲
|
||||
reader io.Reader
|
||||
}
|
||||
|
||||
func NewWSConnAdapter(conn *websocket.Conn) *WSConnAdapter {
|
||||
return &WSConnAdapter{
|
||||
conn: conn,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *WSConnAdapter) Read(p []byte) (n int, err error) {
|
||||
if a.reader == nil {
|
||||
messageType, reader, err := a.conn.NextReader()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if messageType != websocket.BinaryMessage && messageType != websocket.TextMessage {
|
||||
// 忽略非数据消息
|
||||
return 0, nil
|
||||
}
|
||||
a.reader = reader
|
||||
}
|
||||
n, err = a.reader.Read(p)
|
||||
if err == io.EOF {
|
||||
a.reader = nil
|
||||
err = nil // 当前消息读完,不代表连接断开
|
||||
// 如果读到了0字节,尝试读下一个消息,避免因为返回 (0, nil) 导致调用方以为无数据空转
|
||||
if n == 0 {
|
||||
return a.Read(p)
|
||||
}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (a *WSConnAdapter) Write(p []byte) (n int, err error) {
|
||||
err = a.conn.WriteMessage(websocket.BinaryMessage, p)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (a *WSConnAdapter) Close() error {
|
||||
return a.conn.Close()
|
||||
}
|
||||
|
||||
func (a *WSConnAdapter) LocalAddr() net.Addr {
|
||||
return a.conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (a *WSConnAdapter) RemoteAddr() net.Addr {
|
||||
return a.conn.RemoteAddr()
|
||||
}
|
||||
|
||||
func (a *WSConnAdapter) SetDeadline(t time.Time) error {
|
||||
if err := a.conn.SetReadDeadline(t); err != nil {
|
||||
return err
|
||||
}
|
||||
return a.conn.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
func (a *WSConnAdapter) SetReadDeadline(t time.Time) error {
|
||||
return a.conn.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (a *WSConnAdapter) SetWriteDeadline(t time.Time) error {
|
||||
return a.conn.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
// acceptWebsocketConns 接受 Websocket 连接
|
||||
func (s *Server) acceptWebsocketConns(cs *ClientSession, ln net.Listener, rule protocol.ProxyRule) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
wsConn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Printf("[Server] Websocket upgrade error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
conn := NewWSConnAdapter(wsConn)
|
||||
// 这里的 conn 并没有实现 net.Conn 接口的全部方法 (LocalAddr, RemoteAddr 等),
|
||||
// Relay 函数如果需要 net.Conn,可能需要更完整的适配器。
|
||||
// 查看 relay.Relay 签名:func Relay(c1, c2 io.ReadWriteCloser)
|
||||
// 假设 relay.Relay 接受 io.ReadWriteCloser。
|
||||
|
||||
go s.handleWebsocketProxyConn(cs, conn, rule)
|
||||
})
|
||||
|
||||
server := &http.Server{
|
||||
Handler: mux,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
// 这里不需要协程,因为 startProxyListeners 中已经是 go s.acceptWebsocketConns(...) 调用了?
|
||||
// 不,startProxyListeners 中 iterate rules。如果是 acceptWebsocketConns,应该是在那里 go。
|
||||
// 检查 caller 逻辑。
|
||||
|
||||
if err := server.Serve(ln); err != nil && err != http.ErrServerClosed {
|
||||
log.Printf("[Server] Websocket server error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// handleWebsocketProxyConn 处理 Websocket 代理连接
|
||||
func (s *Server) handleWebsocketProxyConn(cs *ClientSession, conn net.Conn, rule protocol.ProxyRule) {
|
||||
defer conn.Close()
|
||||
|
||||
stream, err := cs.Session.Open()
|
||||
if err != nil {
|
||||
log.Printf("[Server] Open stream error: %v", err)
|
||||
return
|
||||
}
|
||||
defer stream.Close()
|
||||
|
||||
// 发送新代理连接请求,告知客户端连接到哪里
|
||||
req := protocol.NewProxyRequest{RemotePort: rule.RemotePort}
|
||||
msg, _ := protocol.NewMessage(protocol.MsgTypeNewProxy, req)
|
||||
if err := protocol.WriteMessage(stream, msg); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
relay.RelayWithStats(conn, stream, s.recordTraffic)
|
||||
}
|
||||
120
internal/server/tunnel/websocket_test.go
Normal file
120
internal/server/tunnel/websocket_test.go
Normal file
@@ -0,0 +1,120 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
func TestWSConnAdapter(t *testing.T) {
|
||||
// 1. 设置测试服务器
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
upgrader := websocket.Upgrader{}
|
||||
c, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
t.Errorf("upgrade error: %v", err)
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
adapter := NewWSConnAdapter(c)
|
||||
defer adapter.Close()
|
||||
|
||||
// Echo server
|
||||
buf := make([]byte, 1024)
|
||||
for {
|
||||
n, err := adapter.Read(buf)
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
// websocket close might cause normal error locally
|
||||
}
|
||||
break
|
||||
}
|
||||
_, err = adapter.Write(buf[:n])
|
||||
if err != nil {
|
||||
t.Errorf("write error: %v", err)
|
||||
break
|
||||
}
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
// 2. 客户端连接
|
||||
u := "ws" + strings.TrimPrefix(server.URL, "http")
|
||||
ws, _, err := websocket.DefaultDialer.Dial(u, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("dial error: %v", err)
|
||||
}
|
||||
defer ws.Close()
|
||||
|
||||
// 3. 发送数据
|
||||
message := []byte("hello websocket")
|
||||
err = ws.WriteMessage(websocket.BinaryMessage, message)
|
||||
if err != nil {
|
||||
t.Fatalf("write message error: %v", err)
|
||||
}
|
||||
|
||||
// 4. 接收响应
|
||||
_, p, err := ws.ReadMessage()
|
||||
if err != nil {
|
||||
t.Fatalf("read message error: %v", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(message, p) {
|
||||
t.Errorf("expected %s, got %s", message, p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWSConnAdapter_ReadMultiFrame(t *testing.T) {
|
||||
// 测试多次 Read 调用读取一个 frame,或者一个 Read 读取多个 frame (net.Conn 语义)
|
||||
// WSConnAdapter 实现是 Read 对应 NextReader,如果 buffer 小,可能一部分一部分读。
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
upgrader := websocket.Upgrader{}
|
||||
c, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
adapter := NewWSConnAdapter(c)
|
||||
|
||||
// 只要收到数据就这就验证通过
|
||||
buf := make([]byte, 10)
|
||||
n, err := adapter.Read(buf)
|
||||
if err != nil {
|
||||
t.Errorf("read error: %v", err)
|
||||
}
|
||||
if n != 5 { // "hello"
|
||||
t.Errorf("expected 5 bytes, got %d", n)
|
||||
}
|
||||
|
||||
// 读剩下的 "world"
|
||||
n, err = adapter.Read(buf)
|
||||
if err != nil {
|
||||
t.Errorf("read 2 error: %v", err)
|
||||
}
|
||||
if n != 5 {
|
||||
t.Errorf("expected 5 bytes, got %d", n)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
u := "ws" + strings.TrimPrefix(server.URL, "http")
|
||||
ws, _, err := websocket.DefaultDialer.Dial(u, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("dial error: %v", err)
|
||||
}
|
||||
defer ws.Close()
|
||||
|
||||
// 发送两个 BinaryMessage
|
||||
ws.WriteMessage(websocket.BinaryMessage, []byte("hello"))
|
||||
ws.WriteMessage(websocket.BinaryMessage, []byte("world"))
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -19,6 +18,7 @@ import (
|
||||
)
|
||||
|
||||
// GenerateTLSConfig 生成内存中的自签名证书并返回 TLS 配置
|
||||
// 证书不限定具体 IP 地址,客户端使用 InsecureSkipVerify 跳过主机名验证(类似 frp)
|
||||
func GenerateTLSConfig() (*tls.Config, error) {
|
||||
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
@@ -41,8 +41,7 @@ func GenerateTLSConfig() (*tls.Config, error) {
|
||||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
BasicConstraintsValid: true,
|
||||
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
|
||||
DNSNames: []string{"localhost"},
|
||||
// 不限定 IP 地址和域名,客户端通过 InsecureSkipVerify + TOFU 验证
|
||||
}
|
||||
|
||||
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// EventType 审计事件类型
|
||||
type EventType string
|
||||
|
||||
const (
|
||||
EventPluginInstall EventType = "plugin_install"
|
||||
EventPluginUninstall EventType = "plugin_uninstall"
|
||||
EventPluginStart EventType = "plugin_start"
|
||||
EventPluginStop EventType = "plugin_stop"
|
||||
EventPluginVerify EventType = "plugin_verify"
|
||||
EventPluginReject EventType = "plugin_reject"
|
||||
EventConfigChange EventType = "config_change"
|
||||
)
|
||||
|
||||
// Event 审计事件
|
||||
type Event struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Type EventType `json:"type"`
|
||||
PluginName string `json:"plugin_name,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
ClientID string `json:"client_id,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Details map[string]string `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// Logger 审计日志记录器
|
||||
type Logger struct {
|
||||
path string
|
||||
file *os.File
|
||||
mu sync.Mutex
|
||||
enabled bool
|
||||
}
|
||||
|
||||
var (
|
||||
defaultLogger *Logger
|
||||
loggerOnce sync.Once
|
||||
)
|
||||
|
||||
// NewLogger 创建审计日志记录器
|
||||
func NewLogger(dataDir string) (*Logger, error) {
|
||||
path := filepath.Join(dataDir, "audit.log")
|
||||
dir := filepath.Dir(path)
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Logger{path: path, file: file, enabled: true}, nil
|
||||
}
|
||||
|
||||
// InitDefault 初始化默认日志记录器
|
||||
func InitDefault(dataDir string) error {
|
||||
var err error
|
||||
loggerOnce.Do(func() {
|
||||
defaultLogger, err = NewLogger(dataDir)
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// Log 记录审计事件
|
||||
func (l *Logger) Log(event Event) {
|
||||
if l == nil || !l.enabled {
|
||||
return
|
||||
}
|
||||
|
||||
event.Timestamp = time.Now()
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
data, err := json.Marshal(event)
|
||||
if err != nil {
|
||||
log.Printf("[Audit] Marshal error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := l.file.Write(append(data, '\n')); err != nil {
|
||||
log.Printf("[Audit] Write error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Close 关闭日志文件
|
||||
func (l *Logger) Close() error {
|
||||
if l == nil || l.file == nil {
|
||||
return nil
|
||||
}
|
||||
return l.file.Close()
|
||||
}
|
||||
|
||||
// LogEvent 使用默认记录器记录事件
|
||||
func LogEvent(event Event) {
|
||||
if defaultLogger != nil {
|
||||
defaultLogger.Log(event)
|
||||
}
|
||||
}
|
||||
|
||||
// LogPluginInstall 记录插件安装事件
|
||||
func LogPluginInstall(pluginName, version, clientID string, success bool, msg string) {
|
||||
LogEvent(Event{
|
||||
Type: EventPluginInstall,
|
||||
PluginName: pluginName,
|
||||
Version: version,
|
||||
ClientID: clientID,
|
||||
Success: success,
|
||||
Message: msg,
|
||||
})
|
||||
}
|
||||
|
||||
// LogPluginVerify 记录插件验证事件
|
||||
func LogPluginVerify(pluginName, version string, success bool, msg string) {
|
||||
LogEvent(Event{
|
||||
Type: EventPluginVerify,
|
||||
PluginName: pluginName,
|
||||
Version: version,
|
||||
Success: success,
|
||||
Message: msg,
|
||||
})
|
||||
}
|
||||
|
||||
// LogPluginReject 记录插件拒绝事件
|
||||
func LogPluginReject(pluginName, version, reason string) {
|
||||
LogEvent(Event{
|
||||
Type: EventPluginReject,
|
||||
PluginName: pluginName,
|
||||
Version: version,
|
||||
Success: false,
|
||||
Message: reason,
|
||||
})
|
||||
}
|
||||
|
||||
// LogWithDetails 记录带详情的事件
|
||||
func LogWithDetails(eventType EventType, pluginName string, success bool, msg string, details map[string]string) {
|
||||
LogEvent(Event{
|
||||
Type: eventType,
|
||||
PluginName: pluginName,
|
||||
Success: success,
|
||||
Message: msg,
|
||||
Details: details,
|
||||
})
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/gotunnel/pkg/plugin"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterClient(NewEchoPlugin())
|
||||
}
|
||||
|
||||
// EchoPlugin 回显插件 - 客户端插件示例
|
||||
type EchoPlugin struct {
|
||||
config map[string]string
|
||||
listener net.Listener
|
||||
running bool
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// NewEchoPlugin 创建 Echo 插件
|
||||
func NewEchoPlugin() *EchoPlugin {
|
||||
return &EchoPlugin{}
|
||||
}
|
||||
|
||||
// Metadata 返回插件信息
|
||||
func (p *EchoPlugin) Metadata() plugin.Metadata {
|
||||
return plugin.Metadata{
|
||||
Name: "echo",
|
||||
Version: "1.0.0",
|
||||
Type: plugin.PluginTypeApp,
|
||||
Source: plugin.PluginSourceBuiltin,
|
||||
RunAt: plugin.SideClient,
|
||||
Description: "Echo server (client plugin example)",
|
||||
Author: "GoTunnel",
|
||||
RuleSchema: &plugin.RuleSchema{
|
||||
NeedsLocalAddr: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Init 初始化插件
|
||||
func (p *EchoPlugin) Init(config map[string]string) error {
|
||||
p.config = config
|
||||
return nil
|
||||
}
|
||||
|
||||
// Start 启动服务
|
||||
func (p *EchoPlugin) Start() (string, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if p.running {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
p.listener = ln
|
||||
p.running = true
|
||||
|
||||
log.Printf("[Echo] Started on %s", ln.Addr().String())
|
||||
return ln.Addr().String(), nil
|
||||
}
|
||||
|
||||
// HandleConn 处理连接
|
||||
func (p *EchoPlugin) HandleConn(conn net.Conn) error {
|
||||
defer conn.Close()
|
||||
log.Printf("[Echo] New connection from tunnel")
|
||||
_, err := io.Copy(conn, conn)
|
||||
return err
|
||||
}
|
||||
|
||||
// Stop 停止服务
|
||||
func (p *EchoPlugin) Stop() error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if !p.running {
|
||||
return nil
|
||||
}
|
||||
|
||||
if p.listener != nil {
|
||||
p.listener.Close()
|
||||
}
|
||||
p.running = false
|
||||
log.Printf("[Echo] Stopped")
|
||||
return nil
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import "github.com/gotunnel/pkg/plugin"
|
||||
|
||||
var (
|
||||
serverPlugins []plugin.ServerPlugin
|
||||
clientPlugins []plugin.ClientPlugin
|
||||
)
|
||||
|
||||
// RegisterServer 注册服务端插件
|
||||
func RegisterServer(handler plugin.ServerPlugin) {
|
||||
serverPlugins = append(serverPlugins, handler)
|
||||
}
|
||||
|
||||
// RegisterClient 注册客户端插件
|
||||
func RegisterClient(handler plugin.ClientPlugin) {
|
||||
clientPlugins = append(clientPlugins, handler)
|
||||
}
|
||||
|
||||
// GetServerPlugins 返回所有服务端插件
|
||||
func GetServerPlugins() []plugin.ServerPlugin {
|
||||
return serverPlugins
|
||||
}
|
||||
|
||||
// GetClientPlugins 返回所有客户端插件
|
||||
func GetClientPlugins() []plugin.ClientPlugin {
|
||||
return clientPlugins
|
||||
}
|
||||
@@ -1,262 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
"github.com/gotunnel/pkg/plugin"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterServer(NewSOCKS5Plugin())
|
||||
}
|
||||
|
||||
const (
|
||||
socks5Version = 0x05
|
||||
noAuth = 0x00
|
||||
userPassAuth = 0x02
|
||||
noAcceptable = 0xFF
|
||||
userPassAuthVer = 0x01
|
||||
authSuccess = 0x00
|
||||
authFailure = 0x01
|
||||
cmdConnect = 0x01
|
||||
atypIPv4 = 0x01
|
||||
atypDomain = 0x03
|
||||
atypIPv6 = 0x04
|
||||
)
|
||||
|
||||
// SOCKS5Plugin 将现有 SOCKS5 实现封装为 plugin
|
||||
type SOCKS5Plugin struct {
|
||||
config map[string]string
|
||||
}
|
||||
|
||||
// NewSOCKS5Plugin 创建 SOCKS5 plugin
|
||||
func NewSOCKS5Plugin() *SOCKS5Plugin {
|
||||
return &SOCKS5Plugin{}
|
||||
}
|
||||
|
||||
// Metadata 返回 plugin 信息
|
||||
func (p *SOCKS5Plugin) Metadata() plugin.Metadata {
|
||||
return plugin.Metadata{
|
||||
Name: "socks5",
|
||||
Version: "1.0.0",
|
||||
Type: plugin.PluginTypeProxy,
|
||||
Source: plugin.PluginSourceBuiltin,
|
||||
RunAt: plugin.SideServer,
|
||||
Description: "SOCKS5 proxy protocol handler",
|
||||
Author: "GoTunnel",
|
||||
RuleSchema: &plugin.RuleSchema{
|
||||
NeedsLocalAddr: false,
|
||||
},
|
||||
ConfigSchema: []plugin.ConfigField{
|
||||
{
|
||||
Key: "auth",
|
||||
Label: "认证方式",
|
||||
Type: plugin.ConfigFieldSelect,
|
||||
Default: "none",
|
||||
Options: []string{"none", "password"},
|
||||
},
|
||||
{
|
||||
Key: "username",
|
||||
Label: "用户名",
|
||||
Type: plugin.ConfigFieldString,
|
||||
},
|
||||
{
|
||||
Key: "password",
|
||||
Label: "密码",
|
||||
Type: plugin.ConfigFieldPassword,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Init 初始化 plugin
|
||||
func (p *SOCKS5Plugin) Init(config map[string]string) error {
|
||||
p.config = config
|
||||
return nil
|
||||
}
|
||||
|
||||
// HandleConn 处理 SOCKS5 连接
|
||||
func (p *SOCKS5Plugin) HandleConn(conn net.Conn, dialer plugin.Dialer) error {
|
||||
defer conn.Close()
|
||||
|
||||
// 握手阶段
|
||||
if err := p.handshake(conn); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 获取请求
|
||||
target, err := p.readRequest(conn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 连接目标
|
||||
remote, err := dialer.Dial("tcp", target)
|
||||
if err != nil {
|
||||
p.sendReply(conn, 0x05) // Connection refused
|
||||
return err
|
||||
}
|
||||
defer remote.Close()
|
||||
|
||||
// 发送成功响应
|
||||
if err := p.sendReply(conn, 0x00); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 双向转发
|
||||
go io.Copy(remote, conn)
|
||||
io.Copy(conn, remote)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close 释放资源
|
||||
func (p *SOCKS5Plugin) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// handshake 处理握手
|
||||
func (p *SOCKS5Plugin) handshake(conn net.Conn) error {
|
||||
buf := make([]byte, 2)
|
||||
if _, err := io.ReadFull(conn, buf); err != nil {
|
||||
return err
|
||||
}
|
||||
if buf[0] != socks5Version {
|
||||
return errors.New("unsupported SOCKS version")
|
||||
}
|
||||
|
||||
nmethods := int(buf[1])
|
||||
methods := make([]byte, nmethods)
|
||||
if _, err := io.ReadFull(conn, methods); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 检查是否需要密码认证
|
||||
if p.config["auth"] == "password" {
|
||||
// 检查客户端是否支持用户名密码认证
|
||||
supported := false
|
||||
for _, m := range methods {
|
||||
if m == userPassAuth {
|
||||
supported = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !supported {
|
||||
conn.Write([]byte{socks5Version, noAcceptable})
|
||||
return errors.New("client does not support password auth")
|
||||
}
|
||||
|
||||
// 选择用户名密码认证
|
||||
if _, err := conn.Write([]byte{socks5Version, userPassAuth}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 执行用户名密码认证
|
||||
return p.authenticateUserPass(conn)
|
||||
}
|
||||
|
||||
// 无认证
|
||||
_, err := conn.Write([]byte{socks5Version, noAuth})
|
||||
return err
|
||||
}
|
||||
|
||||
// readRequest 读取请求
|
||||
func (p *SOCKS5Plugin) readRequest(conn net.Conn) (string, error) {
|
||||
buf := make([]byte, 4)
|
||||
if _, err := io.ReadFull(conn, buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if buf[0] != socks5Version || buf[1] != cmdConnect {
|
||||
return "", errors.New("unsupported command")
|
||||
}
|
||||
|
||||
var host string
|
||||
switch buf[3] {
|
||||
case atypIPv4:
|
||||
ip := make([]byte, 4)
|
||||
if _, err := io.ReadFull(conn, ip); err != nil {
|
||||
return "", err
|
||||
}
|
||||
host = net.IP(ip).String()
|
||||
case atypDomain:
|
||||
lenBuf := make([]byte, 1)
|
||||
if _, err := io.ReadFull(conn, lenBuf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
domain := make([]byte, lenBuf[0])
|
||||
if _, err := io.ReadFull(conn, domain); err != nil {
|
||||
return "", err
|
||||
}
|
||||
host = string(domain)
|
||||
case atypIPv6:
|
||||
ip := make([]byte, 16)
|
||||
if _, err := io.ReadFull(conn, ip); err != nil {
|
||||
return "", err
|
||||
}
|
||||
host = net.IP(ip).String()
|
||||
default:
|
||||
return "", errors.New("unsupported address type")
|
||||
}
|
||||
|
||||
portBuf := make([]byte, 2)
|
||||
if _, err := io.ReadFull(conn, portBuf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
port := binary.BigEndian.Uint16(portBuf)
|
||||
|
||||
return fmt.Sprintf("%s:%d", host, port), nil
|
||||
}
|
||||
|
||||
// authenticateUserPass 用户名密码认证
|
||||
func (p *SOCKS5Plugin) authenticateUserPass(conn net.Conn) error {
|
||||
// 读取认证版本
|
||||
buf := make([]byte, 2)
|
||||
if _, err := io.ReadFull(conn, buf); err != nil {
|
||||
return err
|
||||
}
|
||||
if buf[0] != userPassAuthVer {
|
||||
return errors.New("unsupported auth version")
|
||||
}
|
||||
|
||||
// 读取用户名
|
||||
ulen := int(buf[1])
|
||||
username := make([]byte, ulen)
|
||||
if _, err := io.ReadFull(conn, username); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 读取密码长度和密码
|
||||
plenBuf := make([]byte, 1)
|
||||
if _, err := io.ReadFull(conn, plenBuf); err != nil {
|
||||
return err
|
||||
}
|
||||
plen := int(plenBuf[0])
|
||||
password := make([]byte, plen)
|
||||
if _, err := io.ReadFull(conn, password); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 验证用户名密码
|
||||
expectedUser := p.config["username"]
|
||||
expectedPass := p.config["password"]
|
||||
|
||||
if string(username) == expectedUser && string(password) == expectedPass {
|
||||
conn.Write([]byte{userPassAuthVer, authSuccess})
|
||||
return nil
|
||||
}
|
||||
|
||||
conn.Write([]byte{userPassAuthVer, authFailure})
|
||||
return errors.New("authentication failed")
|
||||
}
|
||||
|
||||
// sendReply 发送响应
|
||||
func (p *SOCKS5Plugin) sendReply(conn net.Conn, rep byte) error {
|
||||
reply := []byte{socks5Version, rep, 0x00, atypIPv4, 0, 0, 0, 0, 0, 0}
|
||||
_, err := conn.Write(reply)
|
||||
return err
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
|
||||
"github.com/gotunnel/pkg/plugin"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterServer(NewVNCPlugin())
|
||||
}
|
||||
|
||||
// VNCPlugin VNC 远程桌面插件
|
||||
type VNCPlugin struct {
|
||||
config map[string]string
|
||||
}
|
||||
|
||||
// NewVNCPlugin 创建 VNC plugin
|
||||
func NewVNCPlugin() *VNCPlugin {
|
||||
return &VNCPlugin{}
|
||||
}
|
||||
|
||||
// Metadata 返回 plugin 信息
|
||||
func (p *VNCPlugin) Metadata() plugin.Metadata {
|
||||
return plugin.Metadata{
|
||||
Name: "vnc",
|
||||
Version: "1.0.0",
|
||||
Type: plugin.PluginTypeApp,
|
||||
Source: plugin.PluginSourceBuiltin,
|
||||
RunAt: plugin.SideServer,
|
||||
Description: "VNC remote desktop relay",
|
||||
Author: "GoTunnel",
|
||||
RuleSchema: &plugin.RuleSchema{
|
||||
NeedsLocalAddr: false,
|
||||
ExtraFields: []plugin.ConfigField{
|
||||
{
|
||||
Key: "vnc_addr",
|
||||
Label: "VNC 地址",
|
||||
Type: plugin.ConfigFieldString,
|
||||
Default: "127.0.0.1:5900",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Init 初始化 plugin
|
||||
func (p *VNCPlugin) Init(config map[string]string) error {
|
||||
p.config = config
|
||||
return nil
|
||||
}
|
||||
|
||||
// HandleConn 处理 VNC 连接
|
||||
// 将外部 VNC 客户端连接转发到客户端本地的 VNC 服务
|
||||
func (p *VNCPlugin) HandleConn(conn net.Conn, dialer plugin.Dialer) error {
|
||||
defer conn.Close()
|
||||
|
||||
// 默认连接客户端本地的 VNC 服务 (5900)
|
||||
vncAddr := "127.0.0.1:5900"
|
||||
if addr, ok := p.config["vnc_addr"]; ok && addr != "" {
|
||||
vncAddr = addr
|
||||
}
|
||||
|
||||
log.Printf("[VNC] New connection from %s, forwarding to %s", conn.RemoteAddr(), vncAddr)
|
||||
|
||||
// 通过隧道连接到客户端本地的 VNC 服务
|
||||
remote, err := dialer.Dial("tcp", vncAddr)
|
||||
if err != nil {
|
||||
log.Printf("[VNC] Failed to connect to %s: %v", vncAddr, err)
|
||||
return err
|
||||
}
|
||||
defer remote.Close()
|
||||
|
||||
// 双向转发 VNC 流量
|
||||
errCh := make(chan error, 2)
|
||||
go func() {
|
||||
_, err := io.Copy(remote, conn)
|
||||
errCh <- err
|
||||
}()
|
||||
go func() {
|
||||
_, err := io.Copy(conn, remote)
|
||||
errCh <- err
|
||||
}()
|
||||
|
||||
// 等待任一方向完成
|
||||
<-errCh
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close 释放资源
|
||||
func (p *VNCPlugin) Close() error {
|
||||
return nil
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Registry 管理可用的 plugins
|
||||
type Registry struct {
|
||||
serverPlugins map[string]ServerPlugin // 服务端插件
|
||||
clientPlugins map[string]ClientPlugin // 客户端插件
|
||||
enabled map[string]bool // 启用状态
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewRegistry 创建 plugin 注册表
|
||||
func NewRegistry() *Registry {
|
||||
return &Registry{
|
||||
serverPlugins: make(map[string]ServerPlugin),
|
||||
clientPlugins: make(map[string]ClientPlugin),
|
||||
enabled: make(map[string]bool),
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterServer 注册服务端插件
|
||||
func (r *Registry) RegisterServer(handler ServerPlugin) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
meta := handler.Metadata()
|
||||
if meta.Name == "" {
|
||||
return fmt.Errorf("plugin name cannot be empty")
|
||||
}
|
||||
|
||||
if _, exists := r.serverPlugins[meta.Name]; exists {
|
||||
return fmt.Errorf("plugin %s already registered", meta.Name)
|
||||
}
|
||||
|
||||
r.serverPlugins[meta.Name] = handler
|
||||
r.enabled[meta.Name] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// RegisterClient 注册客户端插件
|
||||
func (r *Registry) RegisterClient(handler ClientPlugin) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
meta := handler.Metadata()
|
||||
if meta.Name == "" {
|
||||
return fmt.Errorf("plugin name cannot be empty")
|
||||
}
|
||||
|
||||
if _, exists := r.clientPlugins[meta.Name]; exists {
|
||||
return fmt.Errorf("client plugin %s already registered", meta.Name)
|
||||
}
|
||||
|
||||
r.clientPlugins[meta.Name] = handler
|
||||
r.enabled[meta.Name] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetServer 返回服务端插件
|
||||
func (r *Registry) GetServer(name string) (ServerPlugin, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
if handler, ok := r.serverPlugins[name]; ok {
|
||||
if !r.enabled[name] {
|
||||
return nil, fmt.Errorf("plugin %s is disabled", name)
|
||||
}
|
||||
return handler, nil
|
||||
}
|
||||
return nil, fmt.Errorf("plugin %s not found", name)
|
||||
}
|
||||
|
||||
// GetClient 返回客户端插件
|
||||
func (r *Registry) GetClient(name string) (ClientPlugin, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
if handler, ok := r.clientPlugins[name]; ok {
|
||||
if !r.enabled[name] {
|
||||
return nil, fmt.Errorf("client plugin %s is disabled", name)
|
||||
}
|
||||
return handler, nil
|
||||
}
|
||||
return nil, fmt.Errorf("client plugin %s not found", name)
|
||||
}
|
||||
|
||||
// List 返回所有可用的 plugins
|
||||
func (r *Registry) List() []Info {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
var plugins []Info
|
||||
|
||||
for name, handler := range r.serverPlugins {
|
||||
plugins = append(plugins, Info{
|
||||
Metadata: handler.Metadata(),
|
||||
Loaded: true,
|
||||
Enabled: r.enabled[name],
|
||||
})
|
||||
}
|
||||
|
||||
for name, handler := range r.clientPlugins {
|
||||
plugins = append(plugins, Info{
|
||||
Metadata: handler.Metadata(),
|
||||
Loaded: true,
|
||||
Enabled: r.enabled[name],
|
||||
})
|
||||
}
|
||||
|
||||
return plugins
|
||||
}
|
||||
|
||||
// Has 检查 plugin 是否存在
|
||||
func (r *Registry) Has(name string) bool {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
_, ok1 := r.serverPlugins[name]
|
||||
_, ok2 := r.clientPlugins[name]
|
||||
return ok1 || ok2
|
||||
}
|
||||
|
||||
// Close 关闭所有 plugins
|
||||
func (r *Registry) Close(ctx context.Context) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
var lastErr error
|
||||
for name, handler := range r.serverPlugins {
|
||||
if err := handler.Close(); err != nil {
|
||||
lastErr = fmt.Errorf("failed to close plugin %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
for name, handler := range r.clientPlugins {
|
||||
if err := handler.Stop(); err != nil {
|
||||
lastErr = fmt.Errorf("failed to stop client plugin %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return lastErr
|
||||
}
|
||||
|
||||
// Enable 启用插件
|
||||
func (r *Registry) Enable(name string) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
if !r.has(name) {
|
||||
return fmt.Errorf("plugin %s not found", name)
|
||||
}
|
||||
r.enabled[name] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// Disable 禁用插件
|
||||
func (r *Registry) Disable(name string) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
if !r.has(name) {
|
||||
return fmt.Errorf("plugin %s not found", name)
|
||||
}
|
||||
r.enabled[name] = false
|
||||
return nil
|
||||
}
|
||||
|
||||
// has 内部检查(无锁)
|
||||
func (r *Registry) has(name string) bool {
|
||||
_, ok1 := r.serverPlugins[name]
|
||||
_, ok2 := r.clientPlugins[name]
|
||||
return ok1 || ok2
|
||||
}
|
||||
|
||||
// IsEnabled 检查插件是否启用
|
||||
func (r *Registry) IsEnabled(name string) bool {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
return r.enabled[name]
|
||||
}
|
||||
|
||||
// RegisterAllServer 批量注册服务端插件
|
||||
func (r *Registry) RegisterAllServer(handlers []ServerPlugin) error {
|
||||
for _, handler := range handlers {
|
||||
if err := r.RegisterServer(handler); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,474 +0,0 @@
|
||||
package script
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/dop251/goja"
|
||||
"github.com/gotunnel/pkg/plugin"
|
||||
)
|
||||
|
||||
// JSPlugin JavaScript 脚本插件
|
||||
type JSPlugin struct {
|
||||
name string
|
||||
source string
|
||||
vm *goja.Runtime
|
||||
metadata plugin.Metadata
|
||||
config map[string]string
|
||||
sandbox *Sandbox
|
||||
running bool
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// NewJSPlugin 从 JS 源码创建插件
|
||||
func NewJSPlugin(name, source string) (*JSPlugin, error) {
|
||||
p := &JSPlugin{
|
||||
name: name,
|
||||
source: source,
|
||||
vm: goja.New(),
|
||||
sandbox: DefaultSandbox(),
|
||||
}
|
||||
|
||||
if err := p.init(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// SetSandbox 设置沙箱配置
|
||||
func (p *JSPlugin) SetSandbox(sandbox *Sandbox) {
|
||||
p.sandbox = sandbox
|
||||
}
|
||||
|
||||
// init 初始化 JS 运行时
|
||||
func (p *JSPlugin) init() error {
|
||||
// 设置栈深度限制(防止递归攻击)
|
||||
if p.sandbox.MaxStackDepth > 0 {
|
||||
p.vm.SetMaxCallStackSize(p.sandbox.MaxStackDepth)
|
||||
}
|
||||
|
||||
// 注入基础 API
|
||||
p.vm.Set("log", p.jsLog)
|
||||
p.vm.Set("config", p.jsGetConfig)
|
||||
|
||||
// 注入文件 API
|
||||
p.vm.Set("fs", p.createFsAPI())
|
||||
|
||||
// 注入 HTTP API
|
||||
p.vm.Set("http", p.createHttpAPI())
|
||||
|
||||
// 执行脚本
|
||||
_, err := p.vm.RunString(p.source)
|
||||
if err != nil {
|
||||
return fmt.Errorf("run script: %w", err)
|
||||
}
|
||||
|
||||
// 获取元数据
|
||||
if err := p.loadMetadata(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadMetadata 从 JS 获取元数据
|
||||
func (p *JSPlugin) loadMetadata() error {
|
||||
fn, ok := goja.AssertFunction(p.vm.Get("metadata"))
|
||||
if !ok {
|
||||
// 使用默认元数据
|
||||
p.metadata = plugin.Metadata{
|
||||
Name: p.name,
|
||||
Type: plugin.PluginTypeApp,
|
||||
Source: plugin.PluginSourceScript,
|
||||
RunAt: plugin.SideClient,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
result, err := fn(goja.Undefined())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
obj := result.ToObject(p.vm)
|
||||
p.metadata = plugin.Metadata{
|
||||
Name: getString(obj, "name", p.name),
|
||||
Version: getString(obj, "version", "1.0.0"),
|
||||
Type: plugin.PluginType(getString(obj, "type", "app")),
|
||||
Source: plugin.PluginSourceScript,
|
||||
RunAt: plugin.Side(getString(obj, "run_at", "client")),
|
||||
Description: getString(obj, "description", ""),
|
||||
Author: getString(obj, "author", ""),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Metadata 返回插件元数据
|
||||
func (p *JSPlugin) Metadata() plugin.Metadata {
|
||||
return p.metadata
|
||||
}
|
||||
|
||||
// Init 初始化插件配置
|
||||
func (p *JSPlugin) Init(config map[string]string) error {
|
||||
p.config = config
|
||||
p.vm.Set("config", config)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Start 启动插件
|
||||
func (p *JSPlugin) Start() (string, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if p.running {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
fn, ok := goja.AssertFunction(p.vm.Get("start"))
|
||||
if ok {
|
||||
_, err := fn(goja.Undefined())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
p.running = true
|
||||
return "script-plugin", nil
|
||||
}
|
||||
|
||||
// HandleConn 处理连接
|
||||
func (p *JSPlugin) HandleConn(conn net.Conn) error {
|
||||
defer conn.Close()
|
||||
|
||||
// 创建连接包装器
|
||||
jsConn := newJSConn(conn)
|
||||
p.vm.Set("conn", jsConn)
|
||||
|
||||
fn, ok := goja.AssertFunction(p.vm.Get("handleConn"))
|
||||
if !ok {
|
||||
return fmt.Errorf("handleConn not defined")
|
||||
}
|
||||
|
||||
_, err := fn(goja.Undefined(), p.vm.ToValue(jsConn))
|
||||
return err
|
||||
}
|
||||
|
||||
// Stop 停止插件
|
||||
func (p *JSPlugin) Stop() error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if !p.running {
|
||||
return nil
|
||||
}
|
||||
|
||||
fn, ok := goja.AssertFunction(p.vm.Get("stop"))
|
||||
if ok {
|
||||
fn(goja.Undefined())
|
||||
}
|
||||
|
||||
p.running = false
|
||||
return nil
|
||||
}
|
||||
|
||||
// jsLog JS 日志函数
|
||||
func (p *JSPlugin) jsLog(msg string) {
|
||||
fmt.Printf("[JS:%s] %s\n", p.name, msg)
|
||||
}
|
||||
|
||||
// jsGetConfig 获取配置
|
||||
func (p *JSPlugin) jsGetConfig(key string) string {
|
||||
if p.config == nil {
|
||||
return ""
|
||||
}
|
||||
return p.config[key]
|
||||
}
|
||||
|
||||
// getString 从 JS 对象获取字符串
|
||||
func getString(obj *goja.Object, key, def string) string {
|
||||
v := obj.Get(key)
|
||||
if v == nil || goja.IsUndefined(v) {
|
||||
return def
|
||||
}
|
||||
return v.String()
|
||||
}
|
||||
|
||||
// jsConn JS 连接包装器
|
||||
type jsConn struct {
|
||||
conn net.Conn
|
||||
}
|
||||
|
||||
func newJSConn(conn net.Conn) *jsConn {
|
||||
return &jsConn{conn: conn}
|
||||
}
|
||||
|
||||
func (c *jsConn) Read(size int) []byte {
|
||||
buf := make([]byte, size)
|
||||
n, err := c.conn.Read(buf)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return buf[:n]
|
||||
}
|
||||
|
||||
func (c *jsConn) Write(data []byte) int {
|
||||
n, _ := c.conn.Write(data)
|
||||
return n
|
||||
}
|
||||
|
||||
func (c *jsConn) Close() {
|
||||
c.conn.Close()
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 文件系统 API
|
||||
// =============================================================================
|
||||
|
||||
// createFsAPI 创建文件系统 API
|
||||
func (p *JSPlugin) createFsAPI() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"readFile": p.fsReadFile,
|
||||
"writeFile": p.fsWriteFile,
|
||||
"readDir": p.fsReadDir,
|
||||
"stat": p.fsStat,
|
||||
"exists": p.fsExists,
|
||||
"mkdir": p.fsMkdir,
|
||||
"remove": p.fsRemove,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *JSPlugin) fsReadFile(path string) map[string]interface{} {
|
||||
if err := p.sandbox.ValidateReadPath(path); err != nil {
|
||||
return map[string]interface{}{"error": err.Error(), "data": ""}
|
||||
}
|
||||
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return map[string]interface{}{"error": err.Error(), "data": ""}
|
||||
}
|
||||
if info.Size() > p.sandbox.MaxReadSize {
|
||||
return map[string]interface{}{"error": "file too large", "data": ""}
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return map[string]interface{}{"error": err.Error(), "data": ""}
|
||||
}
|
||||
return map[string]interface{}{"error": "", "data": string(data)}
|
||||
}
|
||||
|
||||
func (p *JSPlugin) fsWriteFile(path, content string) map[string]interface{} {
|
||||
if err := p.sandbox.ValidateWritePath(path); err != nil {
|
||||
return map[string]interface{}{"error": err.Error(), "ok": false}
|
||||
}
|
||||
|
||||
if int64(len(content)) > p.sandbox.MaxWriteSize {
|
||||
return map[string]interface{}{"error": "content too large", "ok": false}
|
||||
}
|
||||
|
||||
err := os.WriteFile(path, []byte(content), 0644)
|
||||
if err != nil {
|
||||
return map[string]interface{}{"error": err.Error(), "ok": false}
|
||||
}
|
||||
return map[string]interface{}{"error": "", "ok": true}
|
||||
}
|
||||
|
||||
func (p *JSPlugin) fsReadDir(path string) map[string]interface{} {
|
||||
if err := p.sandbox.ValidateReadPath(path); err != nil {
|
||||
return map[string]interface{}{"error": err.Error(), "entries": nil}
|
||||
}
|
||||
|
||||
entries, err := os.ReadDir(path)
|
||||
if err != nil {
|
||||
return map[string]interface{}{"error": err.Error(), "entries": nil}
|
||||
}
|
||||
var result []map[string]interface{}
|
||||
for _, e := range entries {
|
||||
info, _ := e.Info()
|
||||
result = append(result, map[string]interface{}{
|
||||
"name": e.Name(),
|
||||
"isDir": e.IsDir(),
|
||||
"size": info.Size(),
|
||||
})
|
||||
}
|
||||
return map[string]interface{}{"error": "", "entries": result}
|
||||
}
|
||||
|
||||
func (p *JSPlugin) fsStat(path string) map[string]interface{} {
|
||||
if err := p.sandbox.ValidateReadPath(path); err != nil {
|
||||
return map[string]interface{}{"error": err.Error()}
|
||||
}
|
||||
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return map[string]interface{}{"error": err.Error()}
|
||||
}
|
||||
return map[string]interface{}{
|
||||
"error": "",
|
||||
"name": info.Name(),
|
||||
"size": info.Size(),
|
||||
"isDir": info.IsDir(),
|
||||
"modTime": info.ModTime().Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
func (p *JSPlugin) fsExists(path string) map[string]interface{} {
|
||||
if err := p.sandbox.ValidateReadPath(path); err != nil {
|
||||
return map[string]interface{}{"error": err.Error(), "exists": false}
|
||||
}
|
||||
_, err := os.Stat(path)
|
||||
return map[string]interface{}{"error": "", "exists": err == nil}
|
||||
}
|
||||
|
||||
func (p *JSPlugin) fsMkdir(path string) map[string]interface{} {
|
||||
if err := p.sandbox.ValidateWritePath(path); err != nil {
|
||||
return map[string]interface{}{"error": err.Error(), "ok": false}
|
||||
}
|
||||
err := os.MkdirAll(path, 0755)
|
||||
if err != nil {
|
||||
return map[string]interface{}{"error": err.Error(), "ok": false}
|
||||
}
|
||||
return map[string]interface{}{"error": "", "ok": true}
|
||||
}
|
||||
|
||||
func (p *JSPlugin) fsRemove(path string) map[string]interface{} {
|
||||
if err := p.sandbox.ValidateWritePath(path); err != nil {
|
||||
return map[string]interface{}{"error": err.Error(), "ok": false}
|
||||
}
|
||||
err := os.RemoveAll(path)
|
||||
if err != nil {
|
||||
return map[string]interface{}{"error": err.Error(), "ok": false}
|
||||
}
|
||||
return map[string]interface{}{"error": "", "ok": true}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// HTTP 服务 API
|
||||
// =============================================================================
|
||||
|
||||
// createHttpAPI 创建 HTTP API
|
||||
func (p *JSPlugin) createHttpAPI() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"serve": p.httpServe,
|
||||
"json": p.httpJSON,
|
||||
"sendFile": p.httpSendFile,
|
||||
}
|
||||
}
|
||||
|
||||
// httpServe 启动 HTTP 服务处理连接
|
||||
func (p *JSPlugin) httpServe(conn net.Conn, handler func(map[string]interface{}) map[string]interface{}) {
|
||||
defer conn.Close()
|
||||
|
||||
buf := make([]byte, 4096)
|
||||
n, err := conn.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
req := parseHTTPRequest(buf[:n])
|
||||
resp := handler(req)
|
||||
writeHTTPResponse(conn, resp)
|
||||
}
|
||||
|
||||
func (p *JSPlugin) httpJSON(data interface{}) string {
|
||||
b, _ := json.Marshal(data)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func (p *JSPlugin) httpSendFile(conn net.Conn, filePath string) {
|
||||
f, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
conn.Write([]byte("HTTP/1.1 404 Not Found\r\n\r\n"))
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
info, _ := f.Stat()
|
||||
contentType := getContentType(filePath)
|
||||
|
||||
header := fmt.Sprintf("HTTP/1.1 200 OK\r\nContent-Type: %s\r\nContent-Length: %d\r\n\r\n",
|
||||
contentType, info.Size())
|
||||
conn.Write([]byte(header))
|
||||
io.Copy(conn, f)
|
||||
}
|
||||
|
||||
// parseHTTPRequest 解析 HTTP 请求
|
||||
func parseHTTPRequest(data []byte) map[string]interface{} {
|
||||
lines := string(data)
|
||||
req := map[string]interface{}{
|
||||
"method": "GET",
|
||||
"path": "/",
|
||||
"body": "",
|
||||
}
|
||||
|
||||
// 解析请求行
|
||||
if idx := indexOf(lines, " "); idx > 0 {
|
||||
req["method"] = lines[:idx]
|
||||
rest := lines[idx+1:]
|
||||
if idx2 := indexOf(rest, " "); idx2 > 0 {
|
||||
req["path"] = rest[:idx2]
|
||||
}
|
||||
}
|
||||
|
||||
// 解析 body
|
||||
if idx := indexOf(lines, "\r\n\r\n"); idx > 0 {
|
||||
req["body"] = lines[idx+4:]
|
||||
}
|
||||
|
||||
return req
|
||||
}
|
||||
|
||||
// writeHTTPResponse 写入 HTTP 响应
|
||||
func writeHTTPResponse(conn net.Conn, resp map[string]interface{}) {
|
||||
status := 200
|
||||
if s, ok := resp["status"].(int); ok {
|
||||
status = s
|
||||
}
|
||||
|
||||
body := ""
|
||||
if b, ok := resp["body"].(string); ok {
|
||||
body = b
|
||||
}
|
||||
|
||||
contentType := "application/json"
|
||||
if ct, ok := resp["contentType"].(string); ok {
|
||||
contentType = ct
|
||||
}
|
||||
|
||||
header := fmt.Sprintf("HTTP/1.1 %d OK\r\nContent-Type: %s\r\nContent-Length: %d\r\n\r\n",
|
||||
status, contentType, len(body))
|
||||
conn.Write([]byte(header + body))
|
||||
}
|
||||
|
||||
func indexOf(s, substr string) int {
|
||||
for i := 0; i <= len(s)-len(substr); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func getContentType(path string) string {
|
||||
ext := filepath.Ext(path)
|
||||
types := map[string]string{
|
||||
".html": "text/html",
|
||||
".css": "text/css",
|
||||
".js": "application/javascript",
|
||||
".json": "application/json",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".gif": "image/gif",
|
||||
".txt": "text/plain",
|
||||
}
|
||||
if ct, ok := types[ext]; ok {
|
||||
return ct
|
||||
}
|
||||
return "application/octet-stream"
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
package script
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Sandbox 插件沙箱配置
|
||||
type Sandbox struct {
|
||||
// 允许访问的路径列表(绝对路径)
|
||||
AllowedPaths []string
|
||||
// 允许写入的路径列表(必须是 AllowedPaths 的子集)
|
||||
WritablePaths []string
|
||||
// 禁止访问的路径(黑名单,优先级高于白名单)
|
||||
DeniedPaths []string
|
||||
// 是否允许网络访问
|
||||
AllowNetwork bool
|
||||
// 最大文件读取大小 (bytes)
|
||||
MaxReadSize int64
|
||||
// 最大文件写入大小 (bytes)
|
||||
MaxWriteSize int64
|
||||
// 最大内存使用量 (bytes),0 表示不限制
|
||||
MaxMemory int64
|
||||
// 最大调用栈深度
|
||||
MaxStackDepth int
|
||||
}
|
||||
|
||||
// DefaultSandbox 返回默认沙箱配置(最小权限)
|
||||
func DefaultSandbox() *Sandbox {
|
||||
return &Sandbox{
|
||||
AllowedPaths: []string{},
|
||||
WritablePaths: []string{},
|
||||
DeniedPaths: defaultDeniedPaths(),
|
||||
AllowNetwork: false,
|
||||
MaxReadSize: 10 * 1024 * 1024, // 10MB
|
||||
MaxWriteSize: 1 * 1024 * 1024, // 1MB
|
||||
MaxMemory: 64 * 1024 * 1024, // 64MB
|
||||
MaxStackDepth: 1000, // 最大调用栈深度
|
||||
}
|
||||
}
|
||||
|
||||
// defaultDeniedPaths 返回默认禁止访问的路径
|
||||
func defaultDeniedPaths() []string {
|
||||
home, _ := os.UserHomeDir()
|
||||
denied := []string{
|
||||
"/etc/passwd",
|
||||
"/etc/shadow",
|
||||
"/etc/sudoers",
|
||||
"/root",
|
||||
"/.ssh",
|
||||
"/.gnupg",
|
||||
"/.aws",
|
||||
"/.kube",
|
||||
"/proc",
|
||||
"/sys",
|
||||
}
|
||||
if home != "" {
|
||||
denied = append(denied,
|
||||
filepath.Join(home, ".ssh"),
|
||||
filepath.Join(home, ".gnupg"),
|
||||
filepath.Join(home, ".aws"),
|
||||
filepath.Join(home, ".kube"),
|
||||
filepath.Join(home, ".config"),
|
||||
filepath.Join(home, ".local"),
|
||||
)
|
||||
}
|
||||
return denied
|
||||
}
|
||||
|
||||
// ValidateReadPath 验证读取路径是否允许
|
||||
func (s *Sandbox) ValidateReadPath(path string) error {
|
||||
return s.validatePath(path, false)
|
||||
}
|
||||
|
||||
// ValidateWritePath 验证写入路径是否允许
|
||||
func (s *Sandbox) ValidateWritePath(path string) error {
|
||||
return s.validatePath(path, true)
|
||||
}
|
||||
|
||||
func (s *Sandbox) validatePath(path string, write bool) error {
|
||||
// 清理路径,防止路径遍历攻击
|
||||
cleanPath, err := s.cleanPath(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 检查黑名单(优先级最高)
|
||||
if s.isDenied(cleanPath) {
|
||||
return fmt.Errorf("access denied: path is in denied list")
|
||||
}
|
||||
|
||||
// 检查白名单
|
||||
allowedList := s.AllowedPaths
|
||||
if write {
|
||||
allowedList = s.WritablePaths
|
||||
}
|
||||
|
||||
if len(allowedList) == 0 {
|
||||
return fmt.Errorf("access denied: no paths allowed")
|
||||
}
|
||||
|
||||
if !s.isAllowed(cleanPath, allowedList) {
|
||||
if write {
|
||||
return fmt.Errorf("access denied: path not in writable list")
|
||||
}
|
||||
return fmt.Errorf("access denied: path not in allowed list")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// cleanPath 清理并验证路径
|
||||
func (s *Sandbox) cleanPath(path string) (string, error) {
|
||||
// 转换为绝对路径
|
||||
absPath, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid path: %w", err)
|
||||
}
|
||||
|
||||
// 清理路径(解析 .. 和 .)
|
||||
cleanPath := filepath.Clean(absPath)
|
||||
|
||||
// 检查符号链接(防止通过符号链接绕过限制)
|
||||
realPath, err := filepath.EvalSymlinks(cleanPath)
|
||||
if err != nil {
|
||||
// 文件可能不存在,使用清理后的路径
|
||||
if !os.IsNotExist(err) {
|
||||
return "", fmt.Errorf("invalid path: %w", err)
|
||||
}
|
||||
realPath = cleanPath
|
||||
}
|
||||
|
||||
// 再次检查路径遍历
|
||||
if strings.Contains(realPath, "..") {
|
||||
return "", fmt.Errorf("path traversal detected")
|
||||
}
|
||||
|
||||
return realPath, nil
|
||||
}
|
||||
|
||||
// isDenied 检查路径是否在黑名单中
|
||||
func (s *Sandbox) isDenied(path string) bool {
|
||||
for _, denied := range s.DeniedPaths {
|
||||
if strings.HasPrefix(path, denied) || path == denied {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isAllowed 检查路径是否在白名单中
|
||||
func (s *Sandbox) isAllowed(path string, allowedList []string) bool {
|
||||
for _, allowed := range allowedList {
|
||||
if strings.HasPrefix(path, allowed) || path == allowed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package sign
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// 官方固定公钥(客户端内置)
|
||||
const OfficialPublicKeyBase64 = "0A0xRthj0wgPg8X8GJZ6/EnNpAUw5v7O//XLty+P5Yw="
|
||||
|
||||
var (
|
||||
officialPubKey ed25519.PublicKey
|
||||
officialPubKeyOnce sync.Once
|
||||
officialPubKeyErr error
|
||||
)
|
||||
|
||||
// initOfficialKey 初始化官方公钥
|
||||
func initOfficialKey() {
|
||||
officialPubKey, officialPubKeyErr = DecodePublicKey(OfficialPublicKeyBase64)
|
||||
}
|
||||
|
||||
// GetOfficialPublicKey 获取官方公钥
|
||||
func GetOfficialPublicKey() (ed25519.PublicKey, error) {
|
||||
officialPubKeyOnce.Do(initOfficialKey)
|
||||
return officialPubKey, officialPubKeyErr
|
||||
}
|
||||
|
||||
// GetPublicKeyByID 根据 ID 获取公钥(兼容旧接口,忽略 keyID)
|
||||
func GetPublicKeyByID(keyID string) (ed25519.PublicKey, error) {
|
||||
return GetOfficialPublicKey()
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
package sign
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PluginPayload 插件签名载荷
|
||||
type PluginPayload struct {
|
||||
Name string `json:"name"` // 插件名称
|
||||
Version string `json:"version"` // 版本号
|
||||
SourceHash string `json:"source_hash"` // 源码 SHA256
|
||||
KeyID string `json:"key_id"` // 签名密钥 ID
|
||||
Timestamp int64 `json:"timestamp"` // 签名时间戳
|
||||
}
|
||||
|
||||
// SignedPlugin 已签名的插件
|
||||
type SignedPlugin struct {
|
||||
Payload PluginPayload `json:"payload"`
|
||||
Signature string `json:"signature"` // Base64 签名
|
||||
}
|
||||
|
||||
// NormalizeSource 规范化源码(统一换行符)
|
||||
func NormalizeSource(source string) string {
|
||||
// 统一换行符为 LF
|
||||
normalized := strings.ReplaceAll(source, "\r\n", "\n")
|
||||
normalized = strings.ReplaceAll(normalized, "\r", "\n")
|
||||
// 去除尾部空白
|
||||
normalized = strings.TrimRight(normalized, " \t\n")
|
||||
return normalized
|
||||
}
|
||||
|
||||
// HashSource 计算源码哈希
|
||||
func HashSource(source string) string {
|
||||
normalized := NormalizeSource(source)
|
||||
hash := sha256.Sum256([]byte(normalized))
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
|
||||
// CreatePayload 创建签名载荷
|
||||
func CreatePayload(name, version, source, keyID string) *PluginPayload {
|
||||
return &PluginPayload{
|
||||
Name: name,
|
||||
Version: version,
|
||||
SourceHash: HashSource(source),
|
||||
KeyID: keyID,
|
||||
Timestamp: time.Now().Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
// SignPlugin 签名插件
|
||||
func SignPlugin(priv ed25519.PrivateKey, payload *PluginPayload) (*SignedPlugin, error) {
|
||||
// 序列化载荷
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal payload: %w", err)
|
||||
}
|
||||
|
||||
// 签名
|
||||
sig := SignBase64(priv, data)
|
||||
|
||||
return &SignedPlugin{
|
||||
Payload: *payload,
|
||||
Signature: sig,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// VerifyPlugin 验证插件签名
|
||||
func VerifyPlugin(pub ed25519.PublicKey, signed *SignedPlugin, source string) error {
|
||||
// 验证源码哈希
|
||||
expectedHash := HashSource(source)
|
||||
if signed.Payload.SourceHash != expectedHash {
|
||||
return fmt.Errorf("source hash mismatch")
|
||||
}
|
||||
|
||||
// 序列化载荷
|
||||
data, err := json.Marshal(signed.Payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal payload: %w", err)
|
||||
}
|
||||
|
||||
// 验证签名
|
||||
return VerifyBase64(pub, data, signed.Signature)
|
||||
}
|
||||
|
||||
// EncodeSignedPlugin 编码已签名插件为 JSON
|
||||
func EncodeSignedPlugin(sp *SignedPlugin) (string, error) {
|
||||
data, err := json.Marshal(sp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
// DecodeSignedPlugin 从 JSON 解码已签名插件
|
||||
func DecodeSignedPlugin(data string) (*SignedPlugin, error) {
|
||||
var sp SignedPlugin
|
||||
if err := json.Unmarshal([]byte(data), &sp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &sp, nil
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package sign
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidSignature = errors.New("invalid signature")
|
||||
ErrInvalidPublicKey = errors.New("invalid public key")
|
||||
ErrInvalidPrivateKey = errors.New("invalid private key")
|
||||
)
|
||||
|
||||
// KeyPair Ed25519 密钥对
|
||||
type KeyPair struct {
|
||||
PublicKey ed25519.PublicKey
|
||||
PrivateKey ed25519.PrivateKey
|
||||
}
|
||||
|
||||
// GenerateKeyPair 生成新的密钥对
|
||||
func GenerateKeyPair() (*KeyPair, error) {
|
||||
pub, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generate key: %w", err)
|
||||
}
|
||||
return &KeyPair{PublicKey: pub, PrivateKey: priv}, nil
|
||||
}
|
||||
|
||||
// Sign 使用私钥签名数据
|
||||
func Sign(privateKey ed25519.PrivateKey, data []byte) []byte {
|
||||
return ed25519.Sign(privateKey, data)
|
||||
}
|
||||
|
||||
// Verify 使用公钥验证签名
|
||||
func Verify(publicKey ed25519.PublicKey, data, signature []byte) bool {
|
||||
return ed25519.Verify(publicKey, data, signature)
|
||||
}
|
||||
|
||||
// SignBase64 签名并返回 Base64 编码
|
||||
func SignBase64(privateKey ed25519.PrivateKey, data []byte) string {
|
||||
sig := Sign(privateKey, data)
|
||||
return base64.StdEncoding.EncodeToString(sig)
|
||||
}
|
||||
|
||||
// VerifyBase64 验证 Base64 编码的签名
|
||||
func VerifyBase64(publicKey ed25519.PublicKey, data []byte, sigB64 string) error {
|
||||
sig, err := base64.StdEncoding.DecodeString(sigB64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode signature: %w", err)
|
||||
}
|
||||
if !Verify(publicKey, data, sig) {
|
||||
return ErrInvalidSignature
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// EncodePublicKey 编码公钥为 Base64
|
||||
func EncodePublicKey(pub ed25519.PublicKey) string {
|
||||
return base64.StdEncoding.EncodeToString(pub)
|
||||
}
|
||||
|
||||
// DecodePublicKey 从 Base64 解码公钥
|
||||
func DecodePublicKey(s string) (ed25519.PublicKey, error) {
|
||||
data, err := base64.StdEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(data) != ed25519.PublicKeySize {
|
||||
return nil, ErrInvalidPublicKey
|
||||
}
|
||||
return ed25519.PublicKey(data), nil
|
||||
}
|
||||
|
||||
// EncodePrivateKey 编码私钥为 Base64
|
||||
func EncodePrivateKey(priv ed25519.PrivateKey) string {
|
||||
return base64.StdEncoding.EncodeToString(priv)
|
||||
}
|
||||
|
||||
// DecodePrivateKey 从 Base64 解码私钥
|
||||
func DecodePrivateKey(s string) (ed25519.PrivateKey, error) {
|
||||
data, err := base64.StdEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(data) != ed25519.PrivateKeySize {
|
||||
return nil, ErrInvalidPrivateKey
|
||||
}
|
||||
return ed25519.PrivateKey(data), nil
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package sign
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CompareVersions 比较两个版本号
|
||||
// 返回: -1 (v1 < v2), 0 (v1 == v2), 1 (v1 > v2)
|
||||
func CompareVersions(v1, v2 string) int {
|
||||
parts1 := parseVersion(v1)
|
||||
parts2 := parseVersion(v2)
|
||||
|
||||
maxLen := len(parts1)
|
||||
if len(parts2) > maxLen {
|
||||
maxLen = len(parts2)
|
||||
}
|
||||
|
||||
for i := 0; i < maxLen; i++ {
|
||||
var p1, p2 int
|
||||
if i < len(parts1) {
|
||||
p1 = parts1[i]
|
||||
}
|
||||
if i < len(parts2) {
|
||||
p2 = parts2[i]
|
||||
}
|
||||
|
||||
if p1 < p2 {
|
||||
return -1
|
||||
}
|
||||
if p1 > p2 {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func parseVersion(v string) []int {
|
||||
v = strings.TrimPrefix(v, "v")
|
||||
parts := strings.Split(v, ".")
|
||||
result := make([]int, len(parts))
|
||||
for i, p := range parts {
|
||||
n, _ := strconv.Atoi(p)
|
||||
result[i] = n
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// 基础类型
|
||||
// =============================================================================
|
||||
|
||||
// Side 运行侧
|
||||
type Side string
|
||||
|
||||
const (
|
||||
SideServer Side = "server"
|
||||
SideClient Side = "client"
|
||||
)
|
||||
|
||||
// PluginType 插件类别
|
||||
type PluginType string
|
||||
|
||||
const (
|
||||
PluginTypeProxy PluginType = "proxy" // 代理协议 (SOCKS5 等)
|
||||
PluginTypeApp PluginType = "app" // 应用服务 (VNC, Echo 等)
|
||||
)
|
||||
|
||||
// PluginSource 插件来源
|
||||
type PluginSource string
|
||||
|
||||
const (
|
||||
PluginSourceBuiltin PluginSource = "builtin" // 内置编译
|
||||
PluginSourceScript PluginSource = "script" // 脚本插件
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// 配置相关
|
||||
// =============================================================================
|
||||
|
||||
// ConfigFieldType 配置字段类型
|
||||
type ConfigFieldType string
|
||||
|
||||
const (
|
||||
ConfigFieldString ConfigFieldType = "string"
|
||||
ConfigFieldNumber ConfigFieldType = "number"
|
||||
ConfigFieldBool ConfigFieldType = "bool"
|
||||
ConfigFieldSelect ConfigFieldType = "select"
|
||||
ConfigFieldPassword ConfigFieldType = "password"
|
||||
)
|
||||
|
||||
// ConfigField 配置字段定义
|
||||
type ConfigField struct {
|
||||
Key string `json:"key"`
|
||||
Label string `json:"label"`
|
||||
Type ConfigFieldType `json:"type"`
|
||||
Default string `json:"default,omitempty"`
|
||||
Required bool `json:"required,omitempty"`
|
||||
Options []string `json:"options,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
}
|
||||
|
||||
// RuleSchema 规则表单模式
|
||||
type RuleSchema struct {
|
||||
NeedsLocalAddr bool `json:"needs_local_addr"`
|
||||
ExtraFields []ConfigField `json:"extra_fields,omitempty"`
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 元数据
|
||||
// =============================================================================
|
||||
|
||||
// Metadata 插件元数据
|
||||
type Metadata struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
Type PluginType `json:"type"`
|
||||
Source PluginSource `json:"source"`
|
||||
RunAt Side `json:"run_at"`
|
||||
Description string `json:"description"`
|
||||
Author string `json:"author,omitempty"`
|
||||
ConfigSchema []ConfigField `json:"config_schema,omitempty"`
|
||||
RuleSchema *RuleSchema `json:"rule_schema,omitempty"`
|
||||
}
|
||||
|
||||
// Info 插件运行时信息
|
||||
type Info struct {
|
||||
Metadata Metadata `json:"metadata"`
|
||||
Loaded bool `json:"loaded"`
|
||||
Enabled bool `json:"enabled"`
|
||||
LoadedAt time.Time `json:"loaded_at,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 核心接口
|
||||
// =============================================================================
|
||||
|
||||
// Dialer 网络拨号接口
|
||||
type Dialer interface {
|
||||
Dial(network, address string) (net.Conn, error)
|
||||
}
|
||||
|
||||
// ServerPlugin 服务端插件接口
|
||||
// 运行在服务端,处理外部连接并通过隧道转发到客户端
|
||||
type ServerPlugin interface {
|
||||
Metadata() Metadata
|
||||
Init(config map[string]string) error
|
||||
HandleConn(conn net.Conn, dialer Dialer) error
|
||||
Close() error
|
||||
}
|
||||
|
||||
// ClientPlugin 客户端插件接口
|
||||
// 运行在客户端,提供本地服务
|
||||
type ClientPlugin interface {
|
||||
Metadata() Metadata
|
||||
Init(config map[string]string) error
|
||||
Start() (localAddr string, err error)
|
||||
HandleConn(conn net.Conn) error
|
||||
Stop() error
|
||||
}
|
||||
@@ -26,28 +26,36 @@ const (
|
||||
MsgTypeProxyConnect uint8 = 9 // 代理连接请求 (SOCKS5/HTTP)
|
||||
MsgTypeProxyResult uint8 = 10 // 代理连接结果
|
||||
|
||||
// Plugin 相关消息
|
||||
MsgTypePluginList uint8 = 20 // 请求/响应可用 plugins
|
||||
MsgTypePluginDownload uint8 = 21 // 请求下载 plugin
|
||||
MsgTypePluginData uint8 = 22 // Plugin 二进制数据(分块)
|
||||
MsgTypePluginReady uint8 = 23 // Plugin 加载确认
|
||||
|
||||
// UDP 相关消息
|
||||
MsgTypeUDPData uint8 = 30 // UDP 数据包
|
||||
|
||||
// 插件安装消息
|
||||
MsgTypeInstallPlugins uint8 = 24 // 服务端推送安装插件列表
|
||||
MsgTypePluginConfig uint8 = 25 // 插件配置同步
|
||||
// 客户端控制消息
|
||||
MsgTypeClientRestart uint8 = 60 // 重启客户端
|
||||
|
||||
// 客户端插件消息
|
||||
MsgTypeClientPluginStart uint8 = 40 // 启动客户端插件
|
||||
MsgTypeClientPluginStop uint8 = 41 // 停止客户端插件
|
||||
MsgTypeClientPluginStatus uint8 = 42 // 客户端插件状态
|
||||
MsgTypeClientPluginConn uint8 = 43 // 客户端插件连接请求
|
||||
// 更新相关消息
|
||||
MsgTypeUpdateCheck uint8 = 70 // 检查更新请求
|
||||
MsgTypeUpdateInfo uint8 = 71 // 更新信息响应
|
||||
MsgTypeUpdateDownload uint8 = 72 // 下载更新请求
|
||||
MsgTypeUpdateApply uint8 = 73 // 应用更新请求
|
||||
MsgTypeUpdateProgress uint8 = 74 // 更新进度
|
||||
MsgTypeUpdateResult uint8 = 75 // 更新结果
|
||||
|
||||
// JS 插件动态安装
|
||||
MsgTypeJSPluginInstall uint8 = 50 // 安装 JS 插件
|
||||
MsgTypeJSPluginResult uint8 = 51 // 安装结果
|
||||
// 日志相关消息
|
||||
MsgTypeLogRequest uint8 = 80 // 请求客户端日志
|
||||
MsgTypeLogData uint8 = 81 // 日志数据
|
||||
MsgTypeLogStop uint8 = 82 // 停止日志流
|
||||
|
||||
// 系统状态消息
|
||||
MsgTypeSystemStatsRequest uint8 = 100 // 请求系统状态
|
||||
MsgTypeSystemStatsResponse uint8 = 101 // 系统状态响应
|
||||
|
||||
// 截图消息
|
||||
MsgTypeScreenshotRequest uint8 = 102 // 请求截图
|
||||
MsgTypeScreenshotResponse uint8 = 103 // 截图响应
|
||||
|
||||
// Shell 执行消息
|
||||
MsgTypeShellExecuteRequest uint8 = 104 // 执行 Shell 命令
|
||||
MsgTypeShellExecuteResponse uint8 = 105 // Shell 执行结果
|
||||
)
|
||||
|
||||
// Message 基础消息结构
|
||||
@@ -60,6 +68,10 @@ type Message struct {
|
||||
type AuthRequest struct {
|
||||
ClientID string `json:"client_id"`
|
||||
Token string `json:"token"`
|
||||
Name string `json:"name,omitempty"` // 客户端名称(主机名)
|
||||
OS string `json:"os,omitempty"` // 客户端操作系统
|
||||
Arch string `json:"arch,omitempty"` // 客户端架构
|
||||
Version string `json:"version,omitempty"` // 客户端版本
|
||||
}
|
||||
|
||||
// AuthResponse 认证响应
|
||||
@@ -72,15 +84,17 @@ type AuthResponse struct {
|
||||
// ProxyRule 代理规则
|
||||
type ProxyRule struct {
|
||||
Name string `json:"name" yaml:"name"`
|
||||
Type string `json:"type" yaml:"type"` // 内置: tcp, udp, http, https; 插件: socks5 等
|
||||
LocalIP string `json:"local_ip" yaml:"local_ip"` // tcp/udp 模式使用
|
||||
LocalPort int `json:"local_port" yaml:"local_port"` // tcp/udp 模式使用
|
||||
RemotePort int `json:"remote_port" yaml:"remote_port"` // 服务端监听端口
|
||||
Type string `json:"type" yaml:"type"` // tcp, udp, http, https, socks5
|
||||
LocalIP string `json:"local_ip" yaml:"local_ip"` // tcp/udp 模式使用
|
||||
LocalPort int `json:"local_port" yaml:"local_port"` // tcp/udp 模式使用
|
||||
RemotePort int `json:"remote_port" yaml:"remote_port"` // 服务端监听端口
|
||||
Enabled *bool `json:"enabled,omitempty" yaml:"enabled"` // 是否启用,默认为 true
|
||||
// Plugin 支持字段
|
||||
PluginName string `json:"plugin_name,omitempty" yaml:"plugin_name"`
|
||||
PluginVersion string `json:"plugin_version,omitempty" yaml:"plugin_version"`
|
||||
PluginConfig map[string]string `json:"plugin_config,omitempty" yaml:"plugin_config"`
|
||||
// HTTP Basic Auth 字段
|
||||
AuthEnabled bool `json:"auth_enabled,omitempty" yaml:"auth_enabled"`
|
||||
AuthUsername string `json:"auth_username,omitempty" yaml:"auth_username"`
|
||||
AuthPassword string `json:"auth_password,omitempty" yaml:"auth_password"`
|
||||
// 端口状态: "listening", "failed: <error message>", ""
|
||||
PortStatus string `json:"port_status,omitempty" yaml:"-"`
|
||||
}
|
||||
|
||||
// IsEnabled 检查规则是否启用,默认为 true
|
||||
@@ -118,60 +132,6 @@ type ProxyConnectResult struct {
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// PluginMetadata Plugin 元数据(协议层)
|
||||
type PluginMetadata struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
Checksum string `json:"checksum"`
|
||||
Size int64 `json:"size"`
|
||||
Description string `json:"description,omitempty"`
|
||||
}
|
||||
|
||||
// PluginListRequest 请求可用 plugins
|
||||
type PluginListRequest struct {
|
||||
ClientVersion string `json:"client_version"`
|
||||
}
|
||||
|
||||
// PluginListResponse 返回可用 plugins
|
||||
type PluginListResponse struct {
|
||||
Plugins []PluginMetadata `json:"plugins"`
|
||||
}
|
||||
|
||||
// PluginDownloadRequest 请求下载 plugin
|
||||
type PluginDownloadRequest struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
// PluginDataChunk Plugin 二进制数据块
|
||||
type PluginDataChunk struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
ChunkIndex int `json:"chunk_index"`
|
||||
TotalChunks int `json:"total_chunks"`
|
||||
Data []byte `json:"data"`
|
||||
Checksum string `json:"checksum,omitempty"`
|
||||
}
|
||||
|
||||
// PluginReadyNotification Plugin 加载确认
|
||||
type PluginReadyNotification struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
Success bool `json:"success"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// InstallPluginsRequest 安装插件请求
|
||||
type InstallPluginsRequest struct {
|
||||
Plugins []string `json:"plugins"` // 要安装的插件名称列表
|
||||
}
|
||||
|
||||
// PluginConfigSync 插件配置同步
|
||||
type PluginConfigSync struct {
|
||||
PluginName string `json:"plugin_name"` // 插件名称
|
||||
Config map[string]string `json:"config"` // 配置内容
|
||||
}
|
||||
|
||||
// UDPPacket UDP 数据包
|
||||
type UDPPacket struct {
|
||||
RemotePort int `json:"remote_port"` // 服务端监听端口
|
||||
@@ -179,51 +139,83 @@ type UDPPacket struct {
|
||||
Data []byte `json:"data"` // UDP 数据
|
||||
}
|
||||
|
||||
// ClientPluginStartRequest 启动客户端插件请求
|
||||
type ClientPluginStartRequest struct {
|
||||
PluginName string `json:"plugin_name"` // 插件名称
|
||||
RuleName string `json:"rule_name"` // 规则名称
|
||||
RemotePort int `json:"remote_port"` // 服务端监听端口
|
||||
Config map[string]string `json:"config"` // 插件配置
|
||||
// ClientRestartRequest 客户端重启请求
|
||||
type ClientRestartRequest struct {
|
||||
Reason string `json:"reason,omitempty"` // 重启原因
|
||||
}
|
||||
|
||||
// ClientPluginStopRequest 停止客户端插件请求
|
||||
type ClientPluginStopRequest struct {
|
||||
PluginName string `json:"plugin_name"` // 插件名称
|
||||
RuleName string `json:"rule_name"` // 规则名称
|
||||
// ClientRestartResponse 客户端重启响应
|
||||
type ClientRestartResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// ClientPluginStatusResponse 客户端插件状态响应
|
||||
type ClientPluginStatusResponse struct {
|
||||
PluginName string `json:"plugin_name"` // 插件名称
|
||||
RuleName string `json:"rule_name"` // 规则名称
|
||||
Running bool `json:"running"` // 是否运行中
|
||||
LocalAddr string `json:"local_addr"` // 本地监听地址
|
||||
Error string `json:"error"` // 错误信息
|
||||
// UpdateCheckRequest 更新检查请求
|
||||
type UpdateCheckRequest struct {
|
||||
Component string `json:"component"` // "server" 或 "client"
|
||||
}
|
||||
|
||||
// ClientPluginConnRequest 客户端插件连接请求
|
||||
type ClientPluginConnRequest struct {
|
||||
PluginName string `json:"plugin_name"` // 插件名称
|
||||
RuleName string `json:"rule_name"` // 规则名称
|
||||
// UpdateInfoResponse 更新信息响应
|
||||
type UpdateInfoResponse struct {
|
||||
Available bool `json:"available"`
|
||||
Current string `json:"current"`
|
||||
Latest string `json:"latest"`
|
||||
ReleaseNote string `json:"release_note"`
|
||||
DownloadURL string `json:"download_url"`
|
||||
AssetName string `json:"asset_name"`
|
||||
AssetSize int64 `json:"asset_size"`
|
||||
}
|
||||
|
||||
// JSPluginInstallRequest JS 插件安装请求
|
||||
type JSPluginInstallRequest struct {
|
||||
PluginName string `json:"plugin_name"` // 插件名称
|
||||
Source string `json:"source"` // JS 源码
|
||||
Signature string `json:"signature"` // 官方签名 (Base64)
|
||||
RuleName string `json:"rule_name"` // 规则名称
|
||||
RemotePort int `json:"remote_port"` // 服务端监听端口
|
||||
Config map[string]string `json:"config"` // 插件配置
|
||||
AutoStart bool `json:"auto_start"` // 是否自动启动
|
||||
// UpdateDownloadRequest 下载更新请求
|
||||
type UpdateDownloadRequest struct {
|
||||
DownloadURL string `json:"download_url"`
|
||||
}
|
||||
|
||||
// JSPluginInstallResult JS 插件安装结果
|
||||
type JSPluginInstallResult struct {
|
||||
PluginName string `json:"plugin_name"`
|
||||
Success bool `json:"success"`
|
||||
Error string `json:"error,omitempty"`
|
||||
// UpdateApplyRequest 应用更新请求
|
||||
type UpdateApplyRequest struct {
|
||||
Restart bool `json:"restart"` // 是否自动重启
|
||||
}
|
||||
|
||||
// UpdateProgressResponse 更新进度响应
|
||||
type UpdateProgressResponse struct {
|
||||
Downloaded int64 `json:"downloaded"`
|
||||
Total int64 `json:"total"`
|
||||
Percent int `json:"percent"`
|
||||
Status string `json:"status"` // downloading, applying, completed, failed
|
||||
}
|
||||
|
||||
// UpdateResultResponse 更新结果响应
|
||||
type UpdateResultResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// LogRequest 日志请求
|
||||
type LogRequest struct {
|
||||
SessionID string `json:"session_id"` // 会话 ID
|
||||
Lines int `json:"lines"` // 请求的日志行数
|
||||
Follow bool `json:"follow"` // 是否持续推送新日志
|
||||
Level string `json:"level"` // 日志级别过滤
|
||||
}
|
||||
|
||||
// LogEntry 日志条目
|
||||
type LogEntry struct {
|
||||
Timestamp int64 `json:"ts"` // Unix 时间戳 (毫秒)
|
||||
Level string `json:"level"` // 日志级别: debug, info, warn, error
|
||||
Message string `json:"msg"` // 日志消息
|
||||
Source string `json:"src"` // 来源: client
|
||||
}
|
||||
|
||||
// LogData 日志数据
|
||||
type LogData struct {
|
||||
SessionID string `json:"session_id"` // 会话 ID
|
||||
Entries []LogEntry `json:"entries"` // 日志条目
|
||||
EOF bool `json:"eof"` // 是否结束
|
||||
}
|
||||
|
||||
// LogStopRequest 停止日志流请求
|
||||
type LogStopRequest struct {
|
||||
SessionID string `json:"session_id"` // 会话 ID
|
||||
}
|
||||
|
||||
// WriteMessage 写入消息到 writer
|
||||
@@ -280,3 +272,44 @@ func NewMessage(msgType uint8, data interface{}) (*Message, error) {
|
||||
func (m *Message) ParsePayload(v interface{}) error {
|
||||
return json.Unmarshal(m.Payload, v)
|
||||
}
|
||||
|
||||
// SystemStatsRequest 系统状态请求
|
||||
type SystemStatsRequest struct{}
|
||||
|
||||
// SystemStatsResponse 系统状态响应
|
||||
type SystemStatsResponse struct {
|
||||
CPUUsage float64 `json:"cpu_usage"` // CPU 使用率 (0-100)
|
||||
MemoryTotal uint64 `json:"memory_total"` // 总内存 (字节)
|
||||
MemoryUsed uint64 `json:"memory_used"` // 已用内存 (字节)
|
||||
MemoryUsage float64 `json:"memory_usage"` // 内存使用率 (0-100)
|
||||
DiskTotal uint64 `json:"disk_total"` // 总磁盘 (字节)
|
||||
DiskUsed uint64 `json:"disk_used"` // 已用磁盘 (字节)
|
||||
DiskUsage float64 `json:"disk_usage"` // 磁盘使用率 (0-100)
|
||||
}
|
||||
|
||||
// ScreenshotRequest 截图请求
|
||||
type ScreenshotRequest struct {
|
||||
Quality int `json:"quality"` // JPEG 质量 1-100, 0 使用默认值
|
||||
}
|
||||
|
||||
// ScreenshotResponse 截图响应
|
||||
type ScreenshotResponse struct {
|
||||
Data string `json:"data"` // Base64 编码的 JPEG 图片
|
||||
Width int `json:"width"` // 图片宽度
|
||||
Height int `json:"height"` // 图片高度
|
||||
Timestamp int64 `json:"timestamp"` // 截图时间戳
|
||||
Error string `json:"error,omitempty"` // 错误信息
|
||||
}
|
||||
|
||||
// ShellExecuteRequest Shell 执行请求
|
||||
type ShellExecuteRequest struct {
|
||||
Command string `json:"command"` // 要执行的命令
|
||||
Timeout int `json:"timeout"` // 超时秒数, 0 使用默认值 (30秒)
|
||||
}
|
||||
|
||||
// ShellExecuteResponse Shell 执行响应
|
||||
type ShellExecuteResponse struct {
|
||||
Output string `json:"output"` // stdout + stderr 组合输出
|
||||
ExitCode int `json:"exit_code"` // 进程退出码
|
||||
Error string `json:"error,omitempty"` // 错误信息
|
||||
}
|
||||
|
||||
@@ -2,20 +2,27 @@ package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gotunnel/pkg/relay"
|
||||
)
|
||||
|
||||
// HTTPServer HTTP 代理服务
|
||||
type HTTPServer struct {
|
||||
dialer Dialer
|
||||
dialer Dialer
|
||||
onStats func(in, out int64) // 流量统计回调
|
||||
username string
|
||||
password string
|
||||
}
|
||||
|
||||
// NewHTTPServer 创建 HTTP 代理服务
|
||||
func NewHTTPServer(dialer Dialer) *HTTPServer {
|
||||
return &HTTPServer{dialer: dialer}
|
||||
func NewHTTPServer(dialer Dialer, onStats func(in, out int64), username, password string) *HTTPServer {
|
||||
return &HTTPServer{dialer: dialer, onStats: onStats, username: username, password: password}
|
||||
}
|
||||
|
||||
// HandleConn 处理 HTTP 代理连接
|
||||
@@ -28,12 +35,45 @@ func (h *HTTPServer) HandleConn(conn net.Conn) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 检查认证
|
||||
if h.username != "" && h.password != "" {
|
||||
if !h.checkAuth(req) {
|
||||
conn.Write([]byte("HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm=\"proxy\"\r\n\r\n"))
|
||||
return errors.New("authentication required")
|
||||
}
|
||||
}
|
||||
|
||||
if req.Method == http.MethodConnect {
|
||||
return h.handleConnect(conn, req)
|
||||
}
|
||||
return h.handleHTTP(conn, req, reader)
|
||||
}
|
||||
|
||||
// checkAuth 检查 Proxy-Authorization 头
|
||||
func (h *HTTPServer) checkAuth(req *http.Request) bool {
|
||||
auth := req.Header.Get("Proxy-Authorization")
|
||||
if auth == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
const prefix = "Basic "
|
||||
if !strings.HasPrefix(auth, prefix) {
|
||||
return false
|
||||
}
|
||||
|
||||
decoded, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
credentials := strings.SplitN(string(decoded), ":", 2)
|
||||
if len(credentials) != 2 {
|
||||
return false
|
||||
}
|
||||
|
||||
return credentials[0] == h.username && credentials[1] == h.password
|
||||
}
|
||||
|
||||
// handleConnect 处理 CONNECT 方法 (HTTPS)
|
||||
func (h *HTTPServer) handleConnect(conn net.Conn, req *http.Request) error {
|
||||
target := req.Host
|
||||
@@ -50,8 +90,8 @@ func (h *HTTPServer) handleConnect(conn net.Conn, req *http.Request) error {
|
||||
|
||||
conn.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n"))
|
||||
|
||||
go io.Copy(remote, conn)
|
||||
io.Copy(conn, remote)
|
||||
// 双向转发 (带流量统计)
|
||||
relay.RelayWithStats(conn, remote, h.onStats)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -82,7 +122,10 @@ func (h *HTTPServer) handleHTTP(conn net.Conn, req *http.Request, reader *bufio.
|
||||
return err
|
||||
}
|
||||
|
||||
// 转发响应
|
||||
_, err = io.Copy(conn, remote)
|
||||
// 转发响应 (带流量统计)
|
||||
n, err := io.Copy(conn, remote)
|
||||
if h.onStats != nil && n > 0 {
|
||||
h.onStats(0, n) // 响应数据为出站流量
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -14,10 +14,10 @@ type Server struct {
|
||||
}
|
||||
|
||||
// NewServer 创建代理服务器
|
||||
func NewServer(typ string, dialer Dialer) *Server {
|
||||
func NewServer(typ string, dialer Dialer, onStats func(in, out int64), username, password string) *Server {
|
||||
return &Server{
|
||||
socks5: NewSOCKS5Server(dialer),
|
||||
http: NewHTTPServer(dialer),
|
||||
socks5: NewSOCKS5Server(dialer, onStats, username, password),
|
||||
http: NewHTTPServer(dialer, onStats, username, password),
|
||||
typ: typ,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,11 +6,14 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
"github.com/gotunnel/pkg/relay"
|
||||
)
|
||||
|
||||
const (
|
||||
socks5Version = 0x05
|
||||
noAuth = 0x00
|
||||
userPassAuth = 0x02
|
||||
cmdConnect = 0x01
|
||||
atypIPv4 = 0x01
|
||||
atypDomain = 0x03
|
||||
@@ -19,7 +22,10 @@ const (
|
||||
|
||||
// SOCKS5Server SOCKS5 代理服务
|
||||
type SOCKS5Server struct {
|
||||
dialer Dialer
|
||||
dialer Dialer
|
||||
onStats func(in, out int64) // 流量统计回调
|
||||
username string
|
||||
password string
|
||||
}
|
||||
|
||||
// Dialer 连接拨号器接口
|
||||
@@ -28,8 +34,8 @@ type Dialer interface {
|
||||
}
|
||||
|
||||
// NewSOCKS5Server 创建 SOCKS5 服务
|
||||
func NewSOCKS5Server(dialer Dialer) *SOCKS5Server {
|
||||
return &SOCKS5Server{dialer: dialer}
|
||||
func NewSOCKS5Server(dialer Dialer, onStats func(in, out int64), username, password string) *SOCKS5Server {
|
||||
return &SOCKS5Server{dialer: dialer, onStats: onStats, username: username, password: password}
|
||||
}
|
||||
|
||||
// HandleConn 处理 SOCKS5 连接
|
||||
@@ -60,9 +66,8 @@ func (s *SOCKS5Server) HandleConn(conn net.Conn) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 双向转发
|
||||
go io.Copy(remote, conn)
|
||||
io.Copy(conn, remote)
|
||||
// 双向转发 (带流量统计)
|
||||
relay.RelayWithStats(conn, remote, s.onStats)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -83,11 +88,54 @@ func (s *SOCKS5Server) handshake(conn net.Conn) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 响应:使用无认证
|
||||
// 如果配置了用户名密码,要求认证
|
||||
if s.username != "" && s.password != "" {
|
||||
_, err := conn.Write([]byte{socks5Version, userPassAuth})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.authenticate(conn)
|
||||
}
|
||||
|
||||
// 无认证
|
||||
_, err := conn.Write([]byte{socks5Version, noAuth})
|
||||
return err
|
||||
}
|
||||
|
||||
// authenticate 处理用户名密码认证
|
||||
func (s *SOCKS5Server) authenticate(conn net.Conn) error {
|
||||
buf := make([]byte, 2)
|
||||
if _, err := io.ReadFull(conn, buf); err != nil {
|
||||
return err
|
||||
}
|
||||
if buf[0] != 0x01 {
|
||||
return errors.New("unsupported auth version")
|
||||
}
|
||||
|
||||
ulen := int(buf[1])
|
||||
username := make([]byte, ulen)
|
||||
if _, err := io.ReadFull(conn, username); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
plen := make([]byte, 1)
|
||||
if _, err := io.ReadFull(conn, plen); err != nil {
|
||||
return err
|
||||
}
|
||||
password := make([]byte, plen[0])
|
||||
if _, err := io.ReadFull(conn, password); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if string(username) == s.username && string(password) == s.password {
|
||||
conn.Write([]byte{0x01, 0x00}) // 认证成功
|
||||
return nil
|
||||
}
|
||||
|
||||
conn.Write([]byte{0x01, 0x01}) // 认证失败
|
||||
return errors.New("authentication failed")
|
||||
}
|
||||
|
||||
// readRequest 读取请求
|
||||
func (s *SOCKS5Server) readRequest(conn net.Conn) (string, error) {
|
||||
buf := make([]byte, 4)
|
||||
|
||||
@@ -4,10 +4,17 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
const bufferSize = 32 * 1024
|
||||
|
||||
// TrafficStats 流量统计
|
||||
type TrafficStats struct {
|
||||
Inbound int64
|
||||
Outbound int64
|
||||
}
|
||||
|
||||
// Relay 双向数据转发
|
||||
func Relay(c1, c2 net.Conn) {
|
||||
var wg sync.WaitGroup
|
||||
@@ -17,7 +24,6 @@ func Relay(c1, c2 net.Conn) {
|
||||
defer wg.Done()
|
||||
buf := make([]byte, bufferSize)
|
||||
_, _ = io.CopyBuffer(dst, src, buf)
|
||||
// 关闭写端,通知对方数据传输完成
|
||||
if tc, ok := dst.(*net.TCPConn); ok {
|
||||
tc.CloseWrite()
|
||||
}
|
||||
@@ -27,3 +33,36 @@ func Relay(c1, c2 net.Conn) {
|
||||
go copyConn(c2, c1)
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// RelayWithStats 带流量统计的双向数据转发
|
||||
func RelayWithStats(c1, c2 net.Conn, onStats func(in, out int64)) {
|
||||
var wg sync.WaitGroup
|
||||
var inbound, outbound int64
|
||||
wg.Add(2)
|
||||
|
||||
copyWithCount := func(dst, src net.Conn, counter *int64) {
|
||||
defer wg.Done()
|
||||
buf := make([]byte, bufferSize)
|
||||
for {
|
||||
n, err := src.Read(buf)
|
||||
if n > 0 {
|
||||
atomic.AddInt64(counter, int64(n))
|
||||
dst.Write(buf[:n])
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if tc, ok := dst.(*net.TCPConn); ok {
|
||||
tc.CloseWrite()
|
||||
}
|
||||
}
|
||||
|
||||
go copyWithCount(c1, c2, &inbound)
|
||||
go copyWithCount(c2, c1, &outbound)
|
||||
wg.Wait()
|
||||
|
||||
if onStats != nil {
|
||||
onStats(inbound, outbound)
|
||||
}
|
||||
}
|
||||
|
||||
253
pkg/update/update.go
Normal file
253
pkg/update/update.go
Normal file
@@ -0,0 +1,253 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"archive/zip"
|
||||
"compress/gzip"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// GetArchiveExt 根据 URL 获取压缩包扩展名
|
||||
func GetArchiveExt(url string) string {
|
||||
if strings.HasSuffix(url, ".tar.gz") {
|
||||
return ".tar.gz"
|
||||
}
|
||||
if strings.HasSuffix(url, ".zip") {
|
||||
return ".zip"
|
||||
}
|
||||
// 默认根据平台
|
||||
if runtime.GOOS == "windows" {
|
||||
return ".zip"
|
||||
}
|
||||
return ".tar.gz"
|
||||
}
|
||||
|
||||
// ExtractArchive 解压压缩包
|
||||
func ExtractArchive(archivePath, destDir string) error {
|
||||
if strings.HasSuffix(archivePath, ".tar.gz") {
|
||||
return ExtractTarGz(archivePath, destDir)
|
||||
}
|
||||
if strings.HasSuffix(archivePath, ".zip") {
|
||||
return ExtractZip(archivePath, destDir)
|
||||
}
|
||||
return fmt.Errorf("unsupported archive format")
|
||||
}
|
||||
|
||||
// ExtractTarGz 解压 tar.gz 文件
|
||||
func ExtractTarGz(archivePath, destDir string) error {
|
||||
file, err := os.Open(archivePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
gzReader, err := gzip.NewReader(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer gzReader.Close()
|
||||
|
||||
tarReader := tar.NewReader(gzReader)
|
||||
|
||||
for {
|
||||
header, err := tarReader.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
targetPath := filepath.Join(destDir, header.Name)
|
||||
|
||||
switch header.Typeflag {
|
||||
case tar.TypeDir:
|
||||
if err := os.MkdirAll(targetPath, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
case tar.TypeReg:
|
||||
outFile, err := os.Create(targetPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := io.Copy(outFile, tarReader); err != nil {
|
||||
outFile.Close()
|
||||
return err
|
||||
}
|
||||
outFile.Close()
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ExtractZip 解压 zip 文件
|
||||
func ExtractZip(archivePath, destDir string) error {
|
||||
reader, err := zip.OpenReader(archivePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
for _, file := range reader.File {
|
||||
targetPath := filepath.Join(destDir, file.Name)
|
||||
|
||||
if file.FileInfo().IsDir() {
|
||||
if err := os.MkdirAll(targetPath, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
srcFile, err := file.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dstFile, err := os.Create(targetPath)
|
||||
if err != nil {
|
||||
srcFile.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = io.Copy(dstFile, srcFile)
|
||||
srcFile.Close()
|
||||
dstFile.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// FindExtractedBinary 在解压目录中查找可执行文件
|
||||
func FindExtractedBinary(extractDir, component string) (string, error) {
|
||||
var binaryPath string
|
||||
prefix := "gotunnel-" + component
|
||||
|
||||
err := filepath.Walk(extractDir, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
name := info.Name()
|
||||
// 匹配 gotunnel-server-* 或 gotunnel-client-*
|
||||
if strings.HasPrefix(name, prefix) {
|
||||
// 排除压缩包本身
|
||||
if !strings.HasSuffix(name, ".tar.gz") && !strings.HasSuffix(name, ".zip") {
|
||||
binaryPath = path
|
||||
return filepath.SkipAll
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil && err != filepath.SkipAll {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if binaryPath == "" {
|
||||
return "", fmt.Errorf("binary not found in archive")
|
||||
}
|
||||
|
||||
return binaryPath, nil
|
||||
}
|
||||
|
||||
// CopyFile 复制文件
|
||||
func CopyFile(src, dst string) error {
|
||||
srcFile, err := os.Open(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer srcFile.Close()
|
||||
|
||||
dstFile, err := os.Create(dst)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dstFile.Close()
|
||||
|
||||
_, err = io.Copy(dstFile, srcFile)
|
||||
return err
|
||||
}
|
||||
|
||||
// DownloadFile 下载文件
|
||||
func DownloadFile(url, dest string) error {
|
||||
client := &http.Client{Timeout: 10 * time.Minute}
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("download failed: %s", resp.Status)
|
||||
}
|
||||
|
||||
out, err := os.Create(dest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
_, err = io.Copy(out, resp.Body)
|
||||
return err
|
||||
}
|
||||
|
||||
// DownloadAndExtract 下载并解压压缩包,返回解压后的可执行文件路径
|
||||
func DownloadAndExtract(downloadURL, component string) (binaryPath string, cleanup func(), err error) {
|
||||
tempDir := os.TempDir()
|
||||
timestamp := time.Now().Format("20060102150405")
|
||||
archivePath := filepath.Join(tempDir, "gotunnel_update_"+timestamp+GetArchiveExt(downloadURL))
|
||||
|
||||
if err := DownloadFile(downloadURL, archivePath); err != nil {
|
||||
return "", nil, fmt.Errorf("download update: %w", err)
|
||||
}
|
||||
|
||||
extractDir := filepath.Join(tempDir, "gotunnel_extract_"+timestamp)
|
||||
if err := os.MkdirAll(extractDir, 0755); err != nil {
|
||||
os.Remove(archivePath)
|
||||
return "", nil, fmt.Errorf("create extract dir: %w", err)
|
||||
}
|
||||
|
||||
cleanup = func() {
|
||||
os.Remove(archivePath)
|
||||
os.RemoveAll(extractDir)
|
||||
}
|
||||
|
||||
if err := ExtractArchive(archivePath, extractDir); err != nil {
|
||||
cleanup()
|
||||
return "", nil, fmt.Errorf("extract archive: %w", err)
|
||||
}
|
||||
|
||||
binaryPath, err = FindExtractedBinary(extractDir, component)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return "", nil, fmt.Errorf("find binary: %w", err)
|
||||
}
|
||||
|
||||
// 设置执行权限
|
||||
if runtime.GOOS != "windows" {
|
||||
if err := os.Chmod(binaryPath, 0755); err != nil {
|
||||
cleanup()
|
||||
return "", nil, fmt.Errorf("chmod: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return binaryPath, cleanup, nil
|
||||
}
|
||||
98
pkg/utils/screenshot.go
Normal file
98
pkg/utils/screenshot.go
Normal file
@@ -0,0 +1,98 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
|
||||
"github.com/kbinani/screenshot"
|
||||
)
|
||||
|
||||
// CaptureScreenshot 捕获主屏幕截图
|
||||
// quality: JPEG 质量 (1-100), 0 使用默认值 (75)
|
||||
// 返回: JPEG 图片数据, 宽度, 高度, 错误
|
||||
func CaptureScreenshot(quality int) ([]byte, int, int, error) {
|
||||
// 默认质量
|
||||
if quality <= 0 || quality > 100 {
|
||||
quality = 75
|
||||
}
|
||||
|
||||
// 获取活动显示器数量
|
||||
n := screenshot.NumActiveDisplays()
|
||||
if n == 0 {
|
||||
return nil, 0, 0, fmt.Errorf("no active display found")
|
||||
}
|
||||
|
||||
// 获取主显示器边界
|
||||
bounds := screenshot.GetDisplayBounds(0)
|
||||
if bounds.Empty() {
|
||||
return nil, 0, 0, fmt.Errorf("failed to get display bounds")
|
||||
}
|
||||
|
||||
// 捕获屏幕
|
||||
img, err := screenshot.CaptureRect(bounds)
|
||||
if err != nil {
|
||||
return nil, 0, 0, fmt.Errorf("capture screen: %w", err)
|
||||
}
|
||||
|
||||
// 编码为 JPEG
|
||||
var buf bytes.Buffer
|
||||
opts := &jpeg.Options{Quality: quality}
|
||||
if err := jpeg.Encode(&buf, img, opts); err != nil {
|
||||
return nil, 0, 0, fmt.Errorf("encode jpeg: %w", err)
|
||||
}
|
||||
|
||||
return buf.Bytes(), bounds.Dx(), bounds.Dy(), nil
|
||||
}
|
||||
|
||||
// CaptureAllScreens 捕获所有屏幕并拼接
|
||||
// quality: JPEG 质量 (1-100), 0 使用默认值 (75)
|
||||
// 返回: JPEG 图片数据, 宽度, 高度, 错误
|
||||
func CaptureAllScreens(quality int) ([]byte, int, int, error) {
|
||||
// 默认质量
|
||||
if quality <= 0 || quality > 100 {
|
||||
quality = 75
|
||||
}
|
||||
|
||||
// 获取活动显示器数量
|
||||
n := screenshot.NumActiveDisplays()
|
||||
if n == 0 {
|
||||
return nil, 0, 0, fmt.Errorf("no active display found")
|
||||
}
|
||||
|
||||
// 计算所有屏幕的总边界
|
||||
var totalBounds image.Rectangle
|
||||
for i := 0; i < n; i++ {
|
||||
bounds := screenshot.GetDisplayBounds(i)
|
||||
totalBounds = totalBounds.Union(bounds)
|
||||
}
|
||||
|
||||
// 创建总画布
|
||||
totalImg := image.NewRGBA(totalBounds)
|
||||
|
||||
// 捕获每个屏幕并绘制到总画布
|
||||
for i := 0; i < n; i++ {
|
||||
bounds := screenshot.GetDisplayBounds(i)
|
||||
img, err := screenshot.CaptureRect(bounds)
|
||||
if err != nil {
|
||||
continue // 跳过失败的屏幕
|
||||
}
|
||||
|
||||
// 绘制到总画布
|
||||
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
|
||||
for x := bounds.Min.X; x < bounds.Max.X; x++ {
|
||||
totalImg.Set(x, y, img.At(x-bounds.Min.X, y-bounds.Min.Y))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 编码为 JPEG
|
||||
var buf bytes.Buffer
|
||||
opts := &jpeg.Options{Quality: quality}
|
||||
if err := jpeg.Encode(&buf, totalImg, opts); err != nil {
|
||||
return nil, 0, 0, fmt.Errorf("encode jpeg: %w", err)
|
||||
}
|
||||
|
||||
return buf.Bytes(), totalBounds.Dx(), totalBounds.Dy(), nil
|
||||
}
|
||||
61
pkg/utils/sysinfo.go
Normal file
61
pkg/utils/sysinfo.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"os"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/shirou/gopsutil/v3/cpu"
|
||||
"github.com/shirou/gopsutil/v3/disk"
|
||||
"github.com/shirou/gopsutil/v3/mem"
|
||||
)
|
||||
|
||||
// SystemStats 系统状态信息
|
||||
type SystemStats struct {
|
||||
CPUUsage float64 `json:"cpu_usage"`
|
||||
MemoryTotal uint64 `json:"memory_total"`
|
||||
MemoryUsed uint64 `json:"memory_used"`
|
||||
MemoryUsage float64 `json:"memory_usage"`
|
||||
DiskTotal uint64 `json:"disk_total"`
|
||||
DiskUsed uint64 `json:"disk_used"`
|
||||
DiskUsage float64 `json:"disk_usage"`
|
||||
}
|
||||
|
||||
// GetSystemStats 获取系统状态信息
|
||||
func GetSystemStats() (*SystemStats, error) {
|
||||
stats := &SystemStats{}
|
||||
|
||||
// CPU 使用率
|
||||
cpuPercent, err := cpu.Percent(time.Second, false)
|
||||
if err == nil && len(cpuPercent) > 0 {
|
||||
stats.CPUUsage = cpuPercent[0]
|
||||
}
|
||||
|
||||
// 内存信息
|
||||
memInfo, err := mem.VirtualMemory()
|
||||
if err == nil {
|
||||
stats.MemoryTotal = memInfo.Total
|
||||
stats.MemoryUsed = memInfo.Used
|
||||
stats.MemoryUsage = memInfo.UsedPercent
|
||||
}
|
||||
|
||||
// 磁盘信息 - 获取根目录或当前工作目录所在磁盘
|
||||
diskPath := "/"
|
||||
if runtime.GOOS == "windows" {
|
||||
// Windows 使用当前工作目录所在盘符
|
||||
if wd, err := os.Getwd(); err == nil && len(wd) >= 2 {
|
||||
diskPath = wd[:2] + "\\"
|
||||
} else {
|
||||
diskPath = "C:\\"
|
||||
}
|
||||
}
|
||||
|
||||
diskInfo, err := disk.Usage(diskPath)
|
||||
if err == nil {
|
||||
stats.DiskTotal = diskInfo.Total
|
||||
stats.DiskUsed = diskInfo.Used
|
||||
stats.DiskUsage = diskInfo.UsedPercent
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
249
pkg/version/version.go
Normal file
249
pkg/version/version.go
Normal file
@@ -0,0 +1,249 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 版本信息
|
||||
var Version = "1.0.0"
|
||||
var GitCommit = ""
|
||||
var BuildTime = ""
|
||||
|
||||
// SetVersion 设置版本号(由 main 包在初始化时调用)
|
||||
func SetVersion(v string) {
|
||||
if v != "" {
|
||||
Version = v
|
||||
}
|
||||
}
|
||||
|
||||
// SetBuildInfo 设置构建信息(由 main 包在初始化时调用)
|
||||
func SetBuildInfo(gitCommit, buildTime string) {
|
||||
if gitCommit != "" {
|
||||
GitCommit = gitCommit
|
||||
}
|
||||
if buildTime != "" {
|
||||
BuildTime = buildTime
|
||||
}
|
||||
}
|
||||
|
||||
// 仓库信息
|
||||
const (
|
||||
RepoURL = "https://git.92coco.cn/flik/GoTunnel"
|
||||
APIBaseURL = "https://git.92coco.cn/api/v1"
|
||||
RepoOwner = "flik"
|
||||
RepoName = "GoTunnel"
|
||||
)
|
||||
|
||||
// Info 版本详细信息
|
||||
type Info struct {
|
||||
Version string `json:"version"`
|
||||
GitCommit string `json:"git_commit"`
|
||||
BuildTime string `json:"build_time"`
|
||||
GoVersion string `json:"go_version"`
|
||||
OS string `json:"os"`
|
||||
Arch string `json:"arch"`
|
||||
}
|
||||
|
||||
// GetInfo 获取版本信息
|
||||
func GetInfo() Info {
|
||||
return Info{
|
||||
Version: Version,
|
||||
GitCommit: GitCommit,
|
||||
BuildTime: BuildTime,
|
||||
GoVersion: runtime.Version(),
|
||||
OS: runtime.GOOS,
|
||||
Arch: runtime.GOARCH,
|
||||
}
|
||||
}
|
||||
|
||||
// ReleaseInfo Release 信息
|
||||
type ReleaseInfo struct {
|
||||
TagName string `json:"tag_name"`
|
||||
Name string `json:"name"`
|
||||
Body string `json:"body"`
|
||||
PublishedAt string `json:"published_at"`
|
||||
Assets []ReleaseAsset `json:"assets"`
|
||||
}
|
||||
|
||||
// ReleaseAsset Release 资产
|
||||
type ReleaseAsset struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
BrowserDownloadURL string `json:"browser_download_url"`
|
||||
}
|
||||
|
||||
// UpdateInfo 更新信息
|
||||
type UpdateInfo struct {
|
||||
Latest string `json:"latest"`
|
||||
ReleaseNote string `json:"release_note"`
|
||||
DownloadURL string `json:"download_url"`
|
||||
AssetName string `json:"asset_name"`
|
||||
AssetSize int64 `json:"asset_size"`
|
||||
}
|
||||
|
||||
// GetLatestRelease 获取最新 Release
|
||||
// Gitea 兼容:先尝试 /releases/latest,失败则尝试 /releases 取第一个
|
||||
func GetLatestRelease() (*ReleaseInfo, error) {
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
|
||||
// 首先尝试 /releases/latest 端点(GitHub 兼容)
|
||||
latestURL := fmt.Sprintf("%s/repos/%s/%s/releases/latest", APIBaseURL, RepoOwner, RepoName)
|
||||
resp, err := client.Get(latestURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
var release ReleaseInfo
|
||||
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
|
||||
return nil, fmt.Errorf("decode response: %w", err)
|
||||
}
|
||||
return &release, nil
|
||||
}
|
||||
|
||||
// 如果 /releases/latest 不可用,尝试 /releases 并取第一个
|
||||
resp.Body.Close()
|
||||
listURL := fmt.Sprintf("%s/repos/%s/%s/releases?limit=1", APIBaseURL, RepoOwner, RepoName)
|
||||
resp, err = client.Get(listURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("API error: %s - %s", resp.Status, string(body))
|
||||
}
|
||||
|
||||
var releases []ReleaseInfo
|
||||
if err := json.NewDecoder(resp.Body).Decode(&releases); err != nil {
|
||||
return nil, fmt.Errorf("decode response: %w", err)
|
||||
}
|
||||
|
||||
if len(releases) == 0 {
|
||||
return nil, fmt.Errorf("no releases found in repository")
|
||||
}
|
||||
|
||||
return &releases[0], nil
|
||||
}
|
||||
|
||||
// CheckUpdate 检查更新(返回最新版本信息)
|
||||
func CheckUpdate(component string) (*UpdateInfo, error) {
|
||||
release, err := GetLatestRelease()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get latest release: %w", err)
|
||||
}
|
||||
|
||||
// 查找对应平台的资产
|
||||
var downloadURL string
|
||||
var assetName string
|
||||
var assetSize int64
|
||||
|
||||
if asset := findAssetForPlatform(release.Assets, component, runtime.GOOS, runtime.GOARCH); asset != nil {
|
||||
downloadURL = asset.BrowserDownloadURL
|
||||
assetName = asset.Name
|
||||
assetSize = asset.Size
|
||||
}
|
||||
|
||||
return &UpdateInfo{
|
||||
Latest: release.TagName,
|
||||
ReleaseNote: release.Body,
|
||||
DownloadURL: downloadURL,
|
||||
AssetName: assetName,
|
||||
AssetSize: assetSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CheckUpdateForPlatform 检查指定平台的更新
|
||||
func CheckUpdateForPlatform(component, osName, arch string) (*UpdateInfo, error) {
|
||||
release, err := GetLatestRelease()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get latest release: %w", err)
|
||||
}
|
||||
|
||||
// 查找对应平台的资产
|
||||
var downloadURL string
|
||||
var assetName string
|
||||
var assetSize int64
|
||||
|
||||
if asset := findAssetForPlatform(release.Assets, component, osName, arch); asset != nil {
|
||||
downloadURL = asset.BrowserDownloadURL
|
||||
assetName = asset.Name
|
||||
assetSize = asset.Size
|
||||
}
|
||||
|
||||
return &UpdateInfo{
|
||||
Latest: release.TagName,
|
||||
ReleaseNote: release.Body,
|
||||
DownloadURL: downloadURL,
|
||||
AssetName: assetName,
|
||||
AssetSize: assetSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// findAssetForPlatform 在 Release 资产中查找匹配的文件
|
||||
func findAssetForPlatform(assets []ReleaseAsset, component, osName, arch string) *ReleaseAsset {
|
||||
// 构建匹配模式
|
||||
// CI 格式: gotunnel-server-v1.0.0-linux-amd64.tar.gz
|
||||
// 或者: gotunnel-client-v1.0.0-windows-amd64.zip
|
||||
prefix := fmt.Sprintf("gotunnel-%s-", component)
|
||||
suffix := fmt.Sprintf("-%s-%s", osName, arch)
|
||||
|
||||
for i := range assets {
|
||||
name := assets[i].Name
|
||||
// 检查是否匹配 gotunnel-{component}-{version}-{os}-{arch}.{ext}
|
||||
if strings.HasPrefix(name, prefix) && strings.Contains(name, suffix) {
|
||||
return &assets[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CompareVersions 比较版本号
|
||||
// 返回: -1 (v1 < v2), 0 (v1 == v2), 1 (v1 > v2)
|
||||
func CompareVersions(v1, v2 string) int {
|
||||
parts1 := parseVersionParts(v1)
|
||||
parts2 := parseVersionParts(v2)
|
||||
|
||||
maxLen := len(parts1)
|
||||
if len(parts2) > maxLen {
|
||||
maxLen = len(parts2)
|
||||
}
|
||||
|
||||
for i := 0; i < maxLen; i++ {
|
||||
var p1, p2 int
|
||||
if i < len(parts1) {
|
||||
p1 = parts1[i]
|
||||
}
|
||||
if i < len(parts2) {
|
||||
p2 = parts2[i]
|
||||
}
|
||||
|
||||
if p1 < p2 {
|
||||
return -1
|
||||
}
|
||||
if p1 > p2 {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func parseVersionParts(v string) []int {
|
||||
v = strings.TrimPrefix(v, "v")
|
||||
parts := strings.Split(v, ".")
|
||||
result := make([]int, len(parts))
|
||||
for i, p := range parts {
|
||||
n, _ := strconv.Atoi(p)
|
||||
result[i] = n
|
||||
}
|
||||
return result
|
||||
}
|
||||
426
plan.md
426
plan.md
@@ -1,426 +0,0 @@
|
||||
# GoTunnel 架构修复计划
|
||||
|
||||
> 面向 100 万用户发布前的安全与稳定性修复方案
|
||||
|
||||
## 问题概览
|
||||
|
||||
| 严重程度 | 数量 | 状态 |
|
||||
|---------|------|------|
|
||||
| P0 严重 | 5 | ✅ 已修复 |
|
||||
| P1 高 | 5 | ✅ 已修复 |
|
||||
| P2 中 | 13 | 计划中 |
|
||||
| P3 低 | 15 | 后续迭代 |
|
||||
|
||||
---
|
||||
|
||||
## 修复完成总结
|
||||
|
||||
### P0 严重问题 (已全部修复)
|
||||
|
||||
| 编号 | 问题 | 修复文件 | 状态 |
|
||||
|-----|------|---------|------|
|
||||
| 1.1 | TLS 证书验证 | `pkg/crypto/tls.go` | ✅ TOFU 机制 |
|
||||
| 1.2 | Web 控制台无认证 | `cmd/server/main.go`, `config/config.go` | ✅ 强制认证 |
|
||||
| 1.3 | 认证检查端点失效 | `router/auth.go` | ✅ 实际验证 JWT |
|
||||
| 1.4 | Token 生成错误 | `config/config.go` | ✅ 错误检查 |
|
||||
| 1.5 | 客户端 ID 未验证 | `tunnel/server.go` | ✅ 正则验证 |
|
||||
|
||||
### P1 高优先级问题 (已全部修复)
|
||||
|
||||
| 编号 | 问题 | 修复文件 | 状态 |
|
||||
|-----|------|---------|------|
|
||||
| 2.1 | 无连接数限制 | `tunnel/server.go` | ✅ 10000 上限 |
|
||||
| 2.3 | 无优雅关闭 | `tunnel/server.go`, `cmd/server/main.go` | ✅ 信号处理 |
|
||||
| 2.4 | 消息大小未验证 | `protocol/message.go` | ✅ 已有验证 |
|
||||
| 2.5 | 无安全事件日志 | `pkg/security/audit.go` | ✅ 新增模块 |
|
||||
|
||||
---
|
||||
|
||||
## 第一阶段:P0 严重问题 (发布前必须修复)
|
||||
|
||||
### 1.1 TLS 证书验证被禁用
|
||||
|
||||
**文件**: `pkg/crypto/tls.go`
|
||||
|
||||
**问题**: `InsecureSkipVerify: true` 导致中间人攻击风险
|
||||
|
||||
**修复方案**:
|
||||
- 添加服务端证书指纹验证机制
|
||||
- 客户端首次连接时保存服务端证书指纹
|
||||
- 后续连接验证指纹是否匹配(Trust On First Use)
|
||||
- 提供 `--skip-verify` 参数供测试环境使用
|
||||
|
||||
**修改内容**:
|
||||
```go
|
||||
// pkg/crypto/tls.go
|
||||
func ClientTLSConfig(serverFingerprint string) *tls.Config {
|
||||
return &tls.Config{
|
||||
MinVersion: tls.VersionTLS12,
|
||||
InsecureSkipVerify: true, // 仍需要,因为是自签名证书
|
||||
VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
|
||||
// 验证证书指纹
|
||||
return verifyCertFingerprint(rawCerts, serverFingerprint)
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.2 Web 控制台无认证
|
||||
|
||||
**文件**: `cmd/server/main.go`
|
||||
|
||||
**问题**: 默认配置下 Web 控制台完全开放
|
||||
|
||||
**修复方案**:
|
||||
- 首次启动时自动生成随机密码
|
||||
- 强制要求配置用户名密码
|
||||
- 无认证时拒绝启动 Web 服务
|
||||
|
||||
**修改内容**:
|
||||
```go
|
||||
// cmd/server/main.go
|
||||
if cfg.Web.Enabled {
|
||||
if cfg.Web.Username == "" || cfg.Web.Password == "" {
|
||||
// 自动生成凭据
|
||||
cfg.Web.Username = "admin"
|
||||
cfg.Web.Password = generateSecurePassword(16)
|
||||
log.Printf("[Web] 自动生成凭据 - 用户名: %s, 密码: %s",
|
||||
cfg.Web.Username, cfg.Web.Password)
|
||||
// 保存到配置文件
|
||||
saveConfig(cfg)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.3 认证检查端点失效
|
||||
|
||||
**文件**: `internal/server/router/auth.go`
|
||||
|
||||
**问题**: `/auth/check` 始终返回 `valid: true`
|
||||
|
||||
**修复方案**:
|
||||
- 实际验证 JWT Token
|
||||
- 返回真实的验证结果
|
||||
|
||||
**修改内容**:
|
||||
```go
|
||||
// internal/server/router/auth.go
|
||||
func (h *AuthHandler) handleCheck(w http.ResponseWriter, r *http.Request) {
|
||||
// 从 Authorization header 获取 token
|
||||
token := extractToken(r)
|
||||
if token == "" {
|
||||
jsonError(w, "missing token", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// 验证 token
|
||||
claims, err := h.validateToken(token)
|
||||
if err != nil {
|
||||
jsonError(w, "invalid token", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"valid": true,
|
||||
"user": claims.Username,
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.4 Token 生成错误未处理
|
||||
|
||||
**文件**: `internal/server/config/config.go`
|
||||
|
||||
**问题**: `rand.Read()` 错误被忽略,可能生成弱 Token
|
||||
|
||||
**修复方案**:
|
||||
- 检查 `rand.Read()` 返回值
|
||||
- 失败时 panic 或返回错误
|
||||
- 增加 Token 强度验证
|
||||
|
||||
**修改内容**:
|
||||
```go
|
||||
// internal/server/config/config.go
|
||||
func generateToken(length int) (string, error) {
|
||||
bytes := make([]byte, length/2)
|
||||
n, err := rand.Read(bytes)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to generate token: %w", err)
|
||||
}
|
||||
if n != len(bytes) {
|
||||
return "", fmt.Errorf("insufficient random bytes: got %d, want %d", n, len(bytes))
|
||||
}
|
||||
return hex.EncodeToString(bytes), nil
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.5 客户端 ID 未验证
|
||||
|
||||
**文件**: `internal/server/tunnel/server.go`
|
||||
|
||||
**问题**: tunnel server 中未使用已有的 ID 验证函数
|
||||
|
||||
**修复方案**:
|
||||
- 在 handleConnection 中验证 clientID
|
||||
- 拒绝非法格式的 ID
|
||||
- 记录安全日志
|
||||
|
||||
**修改内容**:
|
||||
```go
|
||||
// internal/server/tunnel/server.go
|
||||
func (s *Server) handleConnection(conn net.Conn) {
|
||||
// ... 读取认证消息后
|
||||
|
||||
clientID := authReq.ClientID
|
||||
if clientID != "" && !isValidClientID(clientID) {
|
||||
log.Printf("[Security] Invalid client ID format from %s: %s",
|
||||
conn.RemoteAddr(), clientID)
|
||||
sendAuthResponse(conn, false, "invalid client id format")
|
||||
return
|
||||
}
|
||||
// ...
|
||||
}
|
||||
|
||||
var clientIDRegex = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`)
|
||||
|
||||
func isValidClientID(id string) bool {
|
||||
return clientIDRegex.MatchString(id)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 第二阶段:P1 高优先级问题 (发布前建议修复)
|
||||
|
||||
### 2.1 无连接数限制
|
||||
|
||||
**文件**: `internal/server/tunnel/server.go`
|
||||
|
||||
**修复方案**:
|
||||
- 添加全局最大连接数限制
|
||||
- 添加单客户端连接数限制
|
||||
- 使用 semaphore 控制并发
|
||||
|
||||
**修改内容**:
|
||||
```go
|
||||
type Server struct {
|
||||
// ...
|
||||
maxConns int
|
||||
connSem chan struct{} // semaphore
|
||||
clientConns map[string]int
|
||||
}
|
||||
|
||||
func (s *Server) handleConnection(conn net.Conn) {
|
||||
select {
|
||||
case s.connSem <- struct{}{}:
|
||||
defer func() { <-s.connSem }()
|
||||
default:
|
||||
conn.Close()
|
||||
log.Printf("[Server] Connection rejected: max connections reached")
|
||||
return
|
||||
}
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.2 Goroutine 泄漏
|
||||
|
||||
**文件**: 多个文件
|
||||
|
||||
**修复方案**:
|
||||
- 使用 context 控制 goroutine 生命周期
|
||||
- 添加 goroutine 池
|
||||
- 确保所有 goroutine 有退出机制
|
||||
|
||||
---
|
||||
|
||||
### 2.3 无优雅关闭
|
||||
|
||||
**文件**: `cmd/server/main.go`
|
||||
|
||||
**修复方案**:
|
||||
- 监听 SIGTERM/SIGINT 信号
|
||||
- 关闭所有监听器
|
||||
- 等待现有连接完成
|
||||
- 设置关闭超时
|
||||
|
||||
**修改内容**:
|
||||
```go
|
||||
// cmd/server/main.go
|
||||
func main() {
|
||||
// ...
|
||||
|
||||
// 优雅关闭
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
go func() {
|
||||
<-quit
|
||||
log.Println("[Server] Shutting down...")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
server.Shutdown(ctx)
|
||||
webServer.Shutdown(ctx)
|
||||
}()
|
||||
|
||||
server.Run()
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.4 消息大小未验证
|
||||
|
||||
**文件**: `pkg/protocol/message.go`
|
||||
|
||||
**修复方案**:
|
||||
- 在 ReadMessage 中检查消息长度
|
||||
- 超过限制时返回错误
|
||||
|
||||
---
|
||||
|
||||
### 2.5 无读写超时
|
||||
|
||||
**文件**: `internal/server/tunnel/server.go`
|
||||
|
||||
**修复方案**:
|
||||
- 所有连接设置读写超时
|
||||
- 使用 SetDeadline 而非一次性设置
|
||||
|
||||
---
|
||||
|
||||
### 2.6 竞态条件
|
||||
|
||||
**文件**: `internal/server/tunnel/server.go`
|
||||
|
||||
**修复方案**:
|
||||
- 使用 sync.Map 替代 map + mutex
|
||||
- 或确保所有 map 访问都在锁保护下
|
||||
|
||||
---
|
||||
|
||||
### 2.7 无安全事件日志
|
||||
|
||||
**修复方案**:
|
||||
- 添加安全日志模块
|
||||
- 记录认证失败、异常访问等事件
|
||||
- 支持日志轮转
|
||||
|
||||
---
|
||||
|
||||
## 第三阶段:P2 中优先级问题 (发布后迭代)
|
||||
|
||||
| 编号 | 问题 | 文件 |
|
||||
|-----|------|------|
|
||||
| 3.1 | 配置文件权限过宽 (0644) | config/config.go |
|
||||
| 3.2 | 心跳机制不完善 | tunnel/server.go |
|
||||
| 3.3 | HTTP 代理无 SSRF 防护 | proxy/http.go |
|
||||
| 3.4 | SOCKS5 代理无验证 | proxy/socks5.go |
|
||||
| 3.5 | 数据库操作无超时 | db/sqlite.go |
|
||||
| 3.6 | 错误处理不一致 | 多个文件 |
|
||||
| 3.7 | UDP 缓冲区无限制 | tunnel/server.go |
|
||||
| 3.8 | 代理规则无验证 | tunnel/server.go |
|
||||
| 3.9 | 客户端注册竞态 | tunnel/server.go |
|
||||
| 3.10 | Relay 资源泄漏 | relay/relay.go |
|
||||
| 3.11 | 插件配置无验证 | tunnel/server.go |
|
||||
| 3.12 | 端口号无边界检查 | tunnel/server.go |
|
||||
| 3.13 | 插件商店 URL 硬编码 | config/config.go |
|
||||
|
||||
---
|
||||
|
||||
## 第四阶段:P3 低优先级问题 (后续优化)
|
||||
|
||||
| 编号 | 问题 | 建议 |
|
||||
|-----|------|------|
|
||||
| 4.1 | 无结构化日志 | 引入 zap/zerolog |
|
||||
| 4.2 | 无连接池 | 实现连接池 |
|
||||
| 4.3 | 线性查找规则 | 使用 map 索引 |
|
||||
| 4.4 | 无数据库缓存 | 添加内存缓存 |
|
||||
| 4.5 | 魔法数字 | 提取为常量 |
|
||||
| 4.6 | 无 godoc 注释 | 补充文档 |
|
||||
| 4.7 | 配置无验证 | 添加验证逻辑 |
|
||||
|
||||
---
|
||||
|
||||
## 修复顺序
|
||||
|
||||
```
|
||||
Week 1: P0 问题 (5个)
|
||||
├── Day 1-2: 1.1 TLS 证书验证
|
||||
├── Day 2-3: 1.2 Web 控制台认证
|
||||
├── Day 3-4: 1.3 认证检查端点
|
||||
├── Day 4: 1.4 Token 生成
|
||||
└── Day 5: 1.5 客户端 ID 验证
|
||||
|
||||
Week 2: P1 问题 (7个)
|
||||
├── Day 1-2: 2.1 连接数限制
|
||||
├── Day 2-3: 2.2 Goroutine 泄漏
|
||||
├── Day 3-4: 2.3 优雅关闭
|
||||
├── Day 4: 2.4 消息大小验证
|
||||
├── Day 5: 2.5 读写超时
|
||||
└── Day 5: 2.6-2.7 竞态条件 + 安全日志
|
||||
|
||||
Week 3+: P2/P3 问题
|
||||
└── 按优先级逐步修复
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 测试计划
|
||||
|
||||
### 安全测试
|
||||
- [ ] TLS 中间人攻击测试
|
||||
- [ ] 认证绕过测试
|
||||
- [ ] 注入攻击测试
|
||||
- [ ] DoS 攻击测试
|
||||
|
||||
### 稳定性测试
|
||||
- [ ] 长时间运行测试 (72h+)
|
||||
- [ ] 高并发连接测试 (10000+)
|
||||
- [ ] 内存泄漏测试
|
||||
- [ ] Goroutine 泄漏测试
|
||||
|
||||
### 性能测试
|
||||
- [ ] 吞吐量基准测试
|
||||
- [ ] 延迟基准测试
|
||||
- [ ] 资源使用监控
|
||||
|
||||
---
|
||||
|
||||
## 回滚方案
|
||||
|
||||
如发布后发现严重问题:
|
||||
|
||||
1. **立即回滚**: 保留上一版本二进制文件
|
||||
2. **热修复**: 针对特定问题发布补丁
|
||||
3. **降级运行**: 禁用问题功能模块
|
||||
|
||||
---
|
||||
|
||||
## 监控告警
|
||||
|
||||
发布后需要监控的指标:
|
||||
|
||||
- 连接数 / 活跃客户端数
|
||||
- 内存使用 / Goroutine 数量
|
||||
- 认证失败率
|
||||
- 错误日志频率
|
||||
- 响应延迟 P99
|
||||
|
||||
---
|
||||
|
||||
*文档版本: 1.0*
|
||||
*创建时间: 2025-12-29*
|
||||
*状态: 待审核*
|
||||
@@ -1,30 +0,0 @@
|
||||
// Echo JS Plugin - 回显插件示例
|
||||
function metadata() {
|
||||
return {
|
||||
name: "echo-js",
|
||||
version: "1.0.0",
|
||||
type: "app",
|
||||
run_at: "client",
|
||||
description: "Echo plugin written in JavaScript",
|
||||
author: "GoTunnel"
|
||||
};
|
||||
}
|
||||
|
||||
function start() {
|
||||
log("Echo JS plugin started");
|
||||
}
|
||||
|
||||
function handleConn(conn) {
|
||||
log("New connection");
|
||||
while (true) {
|
||||
var data = conn.Read(4096);
|
||||
if (!data || data.length === 0) {
|
||||
break;
|
||||
}
|
||||
conn.Write(data);
|
||||
}
|
||||
}
|
||||
|
||||
function stop() {
|
||||
log("Echo JS plugin stopped");
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
// FileManager JS Plugin - 文件管理插件
|
||||
// 提供 HTTP API 管理客户端本地文件
|
||||
|
||||
var authToken = "";
|
||||
var basePath = "/";
|
||||
|
||||
function metadata() {
|
||||
return {
|
||||
name: "filemanager",
|
||||
version: "1.0.0",
|
||||
type: "app",
|
||||
run_at: "client",
|
||||
description: "File manager with HTTP API",
|
||||
author: "GoTunnel"
|
||||
};
|
||||
}
|
||||
|
||||
function start() {
|
||||
authToken = config("auth_token") || "admin";
|
||||
basePath = config("base_path") || "/";
|
||||
log("FileManager started, base: " + basePath);
|
||||
}
|
||||
|
||||
function stop() {
|
||||
log("FileManager stopped");
|
||||
}
|
||||
|
||||
// 处理连接
|
||||
function handleConn(conn) {
|
||||
var data = conn.Read(4096);
|
||||
if (!data) return;
|
||||
|
||||
var req = parseRequest(String.fromCharCode.apply(null, data));
|
||||
var resp = handleRequest(req);
|
||||
conn.Write(stringToBytes(resp));
|
||||
}
|
||||
|
||||
// 解析 HTTP 请求
|
||||
function parseRequest(raw) {
|
||||
var lines = raw.split("\r\n");
|
||||
var first = lines[0].split(" ");
|
||||
var req = {
|
||||
method: first[0] || "GET",
|
||||
path: first[1] || "/",
|
||||
headers: {},
|
||||
body: ""
|
||||
};
|
||||
|
||||
var bodyStart = raw.indexOf("\r\n\r\n");
|
||||
if (bodyStart > 0) {
|
||||
req.body = raw.substring(bodyStart + 4);
|
||||
}
|
||||
return req;
|
||||
}
|
||||
|
||||
// 处理请求
|
||||
function handleRequest(req) {
|
||||
// 检查认证
|
||||
if (req.path.indexOf("?token=" + authToken) < 0) {
|
||||
return httpResponse(401, {error: "Unauthorized"});
|
||||
}
|
||||
|
||||
var path = req.path.split("?")[0];
|
||||
|
||||
if (path === "/api/list") {
|
||||
return handleList(req);
|
||||
} else if (path === "/api/read") {
|
||||
return handleRead(req);
|
||||
} else if (path === "/api/write") {
|
||||
return handleWrite(req);
|
||||
} else if (path === "/api/delete") {
|
||||
return handleDelete(req);
|
||||
}
|
||||
|
||||
return httpResponse(404, {error: "Not found"});
|
||||
}
|
||||
|
||||
// 获取查询参数
|
||||
function getQueryParam(req, name) {
|
||||
var query = req.path.split("?")[1] || "";
|
||||
var params = query.split("&");
|
||||
for (var i = 0; i < params.length; i++) {
|
||||
var pair = params[i].split("=");
|
||||
if (pair[0] === name) {
|
||||
return decodeURIComponent(pair[1] || "");
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// 安全路径检查
|
||||
function safePath(path) {
|
||||
if (!path) return basePath;
|
||||
// 防止路径遍历
|
||||
if (path.indexOf("..") >= 0) return null;
|
||||
if (path.charAt(0) !== "/") {
|
||||
path = basePath + "/" + path;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
// 列出目录
|
||||
function handleList(req) {
|
||||
var dir = safePath(getQueryParam(req, "path"));
|
||||
if (!dir) {
|
||||
return httpResponse(400, {error: "Invalid path"});
|
||||
}
|
||||
|
||||
var entries = fs.readDir(dir);
|
||||
if (!entries) {
|
||||
return httpResponse(404, {error: "Directory not found"});
|
||||
}
|
||||
|
||||
return httpResponse(200, {path: dir, entries: entries});
|
||||
}
|
||||
|
||||
// 读取文件
|
||||
function handleRead(req) {
|
||||
var file = safePath(getQueryParam(req, "path"));
|
||||
if (!file) {
|
||||
return httpResponse(400, {error: "Invalid path"});
|
||||
}
|
||||
|
||||
var stat = fs.stat(file);
|
||||
if (!stat) {
|
||||
return httpResponse(404, {error: "File not found"});
|
||||
}
|
||||
if (stat.isDir) {
|
||||
return httpResponse(400, {error: "Cannot read directory"});
|
||||
}
|
||||
|
||||
var content = fs.readFile(file);
|
||||
return httpResponse(200, {path: file, content: content, size: stat.size});
|
||||
}
|
||||
|
||||
// 写入文件
|
||||
function handleWrite(req) {
|
||||
var file = safePath(getQueryParam(req, "path"));
|
||||
if (!file) {
|
||||
return httpResponse(400, {error: "Invalid path"});
|
||||
}
|
||||
|
||||
if (req.method !== "POST") {
|
||||
return httpResponse(405, {error: "Method not allowed"});
|
||||
}
|
||||
|
||||
if (fs.writeFile(file, req.body)) {
|
||||
return httpResponse(200, {success: true, path: file});
|
||||
}
|
||||
return httpResponse(500, {error: "Write failed"});
|
||||
}
|
||||
|
||||
// 删除文件
|
||||
function handleDelete(req) {
|
||||
var file = safePath(getQueryParam(req, "path"));
|
||||
if (!file) {
|
||||
return httpResponse(400, {error: "Invalid path"});
|
||||
}
|
||||
|
||||
if (!fs.exists(file)) {
|
||||
return httpResponse(404, {error: "File not found"});
|
||||
}
|
||||
|
||||
if (fs.remove(file)) {
|
||||
return httpResponse(200, {success: true, path: file});
|
||||
}
|
||||
return httpResponse(500, {error: "Delete failed"});
|
||||
}
|
||||
|
||||
// 构建 HTTP 响应
|
||||
function httpResponse(status, data) {
|
||||
var body = JSON.stringify(data);
|
||||
var statusText = status === 200 ? "OK" :
|
||||
status === 400 ? "Bad Request" :
|
||||
status === 401 ? "Unauthorized" :
|
||||
status === 404 ? "Not Found" :
|
||||
status === 405 ? "Method Not Allowed" :
|
||||
status === 500 ? "Internal Server Error" : "Unknown";
|
||||
|
||||
return "HTTP/1.1 " + status + " " + statusText + "\r\n" +
|
||||
"Content-Type: application/json\r\n" +
|
||||
"Content-Length: " + body.length + "\r\n" +
|
||||
"Access-Control-Allow-Origin: *\r\n" +
|
||||
"\r\n" + body;
|
||||
}
|
||||
|
||||
// 字符串转字节数组
|
||||
function stringToBytes(str) {
|
||||
var bytes = [];
|
||||
for (var i = 0; i < str.length; i++) {
|
||||
bytes.push(str.charCodeAt(i));
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
19
scripts/build.bat
Normal file
19
scripts/build.bat
Normal file
@@ -0,0 +1,19 @@
|
||||
@echo off
|
||||
REM GoTunnel Build Script Launcher for Windows
|
||||
REM This script launches the PowerShell build script
|
||||
|
||||
setlocal
|
||||
|
||||
set SCRIPT_DIR=%~dp0
|
||||
|
||||
REM Check if PowerShell is available
|
||||
where powershell >nul 2>nul
|
||||
if %ERRORLEVEL% neq 0 (
|
||||
echo ERROR: PowerShell is not available
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
REM Pass all arguments to PowerShell script
|
||||
powershell -ExecutionPolicy Bypass -File "%SCRIPT_DIR%build.ps1" %*
|
||||
|
||||
endlocal
|
||||
295
scripts/build.ps1
Normal file
295
scripts/build.ps1
Normal file
@@ -0,0 +1,295 @@
|
||||
# GoTunnel Build Script for Windows
|
||||
# Usage: .\build.ps1 [command]
|
||||
# Commands: all, current, web, server, client, clean, help
|
||||
|
||||
param(
|
||||
[Parameter(Position=0)]
|
||||
[string]$Command = "all",
|
||||
|
||||
[string]$Version = "dev",
|
||||
|
||||
[switch]$NoUPX
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
# 项目根目录
|
||||
$RootDir = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
|
||||
if (-not $RootDir) {
|
||||
$RootDir = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
|
||||
}
|
||||
$BuildDir = Join-Path $RootDir "build"
|
||||
|
||||
# 版本信息
|
||||
$BuildTime = (Get-Date -Format "yyyy-MM-dd HH:mm:ss")
|
||||
try {
|
||||
$GitCommit = (git -C $RootDir rev-parse --short HEAD 2>$null)
|
||||
if (-not $GitCommit) { $GitCommit = "unknown" }
|
||||
} catch {
|
||||
$GitCommit = "unknown"
|
||||
}
|
||||
|
||||
# 目标平台
|
||||
$Platforms = @(
|
||||
@{OS="windows"; Arch="amd64"},
|
||||
@{OS="linux"; Arch="amd64"},
|
||||
@{OS="linux"; Arch="arm64"},
|
||||
@{OS="darwin"; Arch="amd64"},
|
||||
@{OS="darwin"; Arch="arm64"}
|
||||
)
|
||||
)
|
||||
|
||||
# 颜色输出函数
|
||||
function Write-Info {
|
||||
param([string]$Message)
|
||||
Write-Host "[INFO] " -ForegroundColor Green -NoNewline
|
||||
Write-Host $Message
|
||||
}
|
||||
|
||||
function Write-Warn {
|
||||
param([string]$Message)
|
||||
Write-Host "[WARN] " -ForegroundColor Yellow -NoNewline
|
||||
Write-Host $Message
|
||||
}
|
||||
|
||||
function Write-Err {
|
||||
param([string]$Message)
|
||||
Write-Host "[ERROR] " -ForegroundColor Red -NoNewline
|
||||
Write-Host $Message
|
||||
}
|
||||
|
||||
# 检查 UPX 是否可用
|
||||
function Test-UPX {
|
||||
try {
|
||||
$null = Get-Command upx -ErrorAction Stop
|
||||
return $true
|
||||
} catch {
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
# UPX 压缩二进制
|
||||
function Compress-Binary {
|
||||
param([string]$FilePath, [string]$OS)
|
||||
|
||||
if ($NoUPX) { return }
|
||||
if (-not (Test-UPX)) {
|
||||
Write-Warn "UPX not found, skipping compression"
|
||||
return
|
||||
}
|
||||
# macOS 二进制不支持 UPX
|
||||
if ($OS -eq "darwin") {
|
||||
Write-Warn "Skipping UPX for macOS binary: $FilePath"
|
||||
return
|
||||
}
|
||||
|
||||
Write-Info "Compressing $FilePath with UPX..."
|
||||
try {
|
||||
& upx -9 -q $FilePath 2>$null
|
||||
} catch {
|
||||
Write-Warn "UPX compression failed for $FilePath"
|
||||
}
|
||||
}
|
||||
|
||||
# 构建 Web UI
|
||||
function Build-Web {
|
||||
Write-Info "Building web UI..."
|
||||
|
||||
$WebDir = Join-Path $RootDir "web"
|
||||
Push-Location $WebDir
|
||||
|
||||
try {
|
||||
if (-not (Test-Path "node_modules")) {
|
||||
Write-Info "Installing npm dependencies..."
|
||||
& npm install
|
||||
if ($LASTEXITCODE -ne 0) { throw "npm install failed" }
|
||||
}
|
||||
|
||||
& npm run build
|
||||
if ($LASTEXITCODE -ne 0) { throw "npm build failed" }
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
# 复制到 embed 目录
|
||||
Write-Info "Copying dist to embed directory..."
|
||||
$DistSource = Join-Path $WebDir "dist"
|
||||
$DistDest = Join-Path $RootDir "internal\server\app\dist"
|
||||
|
||||
if (Test-Path $DistDest) {
|
||||
Remove-Item -Recurse -Force $DistDest
|
||||
}
|
||||
Copy-Item -Recurse $DistSource $DistDest
|
||||
|
||||
Write-Info "Web UI built successfully"
|
||||
}
|
||||
|
||||
# 构建单个二进制
|
||||
function Build-Binary {
|
||||
param(
|
||||
[string]$OS,
|
||||
[string]$Arch,
|
||||
[string]$Component # server 或 client
|
||||
)
|
||||
|
||||
$OutputName = $Component
|
||||
if ($OS -eq "windows") {
|
||||
$OutputName = "$Component.exe"
|
||||
}
|
||||
|
||||
$OutputDir = Join-Path $BuildDir "${OS}_${Arch}"
|
||||
if (-not (Test-Path $OutputDir)) {
|
||||
New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null
|
||||
}
|
||||
|
||||
Write-Info "Building $Component for $OS/$Arch..."
|
||||
|
||||
$env:GOOS = $OS
|
||||
$env:GOARCH = $Arch
|
||||
$env:CGO_ENABLED = "0"
|
||||
|
||||
$LDFlags = "-s -w -X 'github.com/gotunnel/pkg/version.Version=$Version' -X 'github.com/gotunnel/pkg/version.BuildTime=$BuildTime' -X 'github.com/gotunnel/pkg/version.GitCommit=$GitCommit'"
|
||||
$OutputPath = Join-Path $OutputDir $OutputName
|
||||
$SourcePath = Join-Path $RootDir "cmd\$Component"
|
||||
|
||||
& go build -ldflags $LDFlags -o $OutputPath $SourcePath
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Build failed for $Component $OS/$Arch"
|
||||
}
|
||||
|
||||
# UPX 压缩
|
||||
Compress-Binary -FilePath $OutputPath -OS $OS
|
||||
|
||||
# 显示文件大小
|
||||
$FileSize = (Get-Item $OutputPath).Length / 1MB
|
||||
Write-Info " -> $OutputPath ({0:N2} MB)" -f $FileSize
|
||||
}
|
||||
|
||||
# 构建所有平台
|
||||
function Build-All {
|
||||
foreach ($Platform in $Platforms) {
|
||||
Build-Binary -OS $Platform.OS -Arch $Platform.Arch -Component "server"
|
||||
Build-Binary -OS $Platform.OS -Arch $Platform.Arch -Component "client"
|
||||
}
|
||||
|
||||
Write-Info ""
|
||||
Write-Info "Build completed! Output directory: $BuildDir"
|
||||
Write-Info ""
|
||||
Write-Info "Built files:"
|
||||
Get-ChildItem -Recurse $BuildDir -File | ForEach-Object {
|
||||
$RelPath = $_.FullName.Replace($BuildDir, "").TrimStart("\")
|
||||
$Size = "{0:N2} MB" -f ($_.Length / 1MB)
|
||||
Write-Host " $RelPath ($Size)"
|
||||
}
|
||||
}
|
||||
|
||||
# 仅构建当前平台
|
||||
function Build-Current {
|
||||
$OS = go env GOOS
|
||||
$Arch = go env GOARCH
|
||||
|
||||
Build-Binary -OS $OS -Arch $Arch -Component "server"
|
||||
Build-Binary -OS $OS -Arch $Arch -Component "client"
|
||||
|
||||
Write-Info "Binaries built in $BuildDir\${OS}_${Arch}\"
|
||||
}
|
||||
|
||||
# 清理构建产物
|
||||
function Clean-Build {
|
||||
Write-Info "Cleaning build directory..."
|
||||
if (Test-Path $BuildDir) {
|
||||
Remove-Item -Recurse -Force $BuildDir
|
||||
}
|
||||
Write-Info "Clean completed"
|
||||
}
|
||||
|
||||
# 显示帮助
|
||||
function Show-Help {
|
||||
Write-Host @"
|
||||
GoTunnel Build Script for Windows
|
||||
|
||||
Usage: .\build.ps1 [command] [-Version <version>] [-NoUPX]
|
||||
|
||||
Commands:
|
||||
all Build web UI + all platforms (default)
|
||||
current Build web UI + current platform only
|
||||
web Build web UI only
|
||||
server Build server for current platform
|
||||
client Build client for current platform
|
||||
clean Clean build directory
|
||||
help Show this help message
|
||||
|
||||
Options:
|
||||
-Version Set version string (default: dev)
|
||||
-NoUPX Disable UPX compression
|
||||
|
||||
Target platforms:
|
||||
- windows/amd64
|
||||
- linux/amd64
|
||||
- linux/arm64
|
||||
- darwin/amd64 (macOS Intel)
|
||||
- darwin/arm64 (macOS Apple Silicon)
|
||||
|
||||
Examples:
|
||||
.\build.ps1 # Build all platforms
|
||||
.\build.ps1 all -Version 1.0.0 # Build with version
|
||||
.\build.ps1 current # Build current platform only
|
||||
.\build.ps1 clean # Clean build directory
|
||||
"@
|
||||
}
|
||||
|
||||
# 主函数
|
||||
function Main {
|
||||
Push-Location $RootDir
|
||||
|
||||
try {
|
||||
Write-Info "GoTunnel Build Script"
|
||||
Write-Info "Version: $Version | Commit: $GitCommit"
|
||||
Write-Info ""
|
||||
|
||||
switch ($Command.ToLower()) {
|
||||
"all" {
|
||||
Build-Web
|
||||
Build-All
|
||||
}
|
||||
"current" {
|
||||
Build-Web
|
||||
Build-Current
|
||||
}
|
||||
"web" {
|
||||
Build-Web
|
||||
}
|
||||
"server" {
|
||||
$OS = go env GOOS
|
||||
$Arch = go env GOARCH
|
||||
Build-Binary -OS $OS -Arch $Arch -Component "server"
|
||||
}
|
||||
"client" {
|
||||
$OS = go env GOOS
|
||||
$Arch = go env GOARCH
|
||||
Build-Binary -OS $OS -Arch $Arch -Component "client"
|
||||
}
|
||||
"clean" {
|
||||
Clean-Build
|
||||
}
|
||||
{ $_ -in "help", "--help", "-h", "/?" } {
|
||||
Show-Help
|
||||
return
|
||||
}
|
||||
default {
|
||||
Write-Err "Unknown command: $Command"
|
||||
Show-Help
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
Write-Info ""
|
||||
Write-Info "Done!"
|
||||
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
|
||||
Main
|
||||
5
web/components.d.ts
vendored
5
web/components.d.ts
vendored
@@ -11,7 +11,12 @@ export {}
|
||||
/* prettier-ignore */
|
||||
declare module 'vue' {
|
||||
export interface GlobalComponents {
|
||||
GlassModal: typeof import('./src/components/GlassModal.vue')['default']
|
||||
GlassSwitch: typeof import('./src/components/GlassSwitch.vue')['default']
|
||||
GlassTag: typeof import('./src/components/GlassTag.vue')['default']
|
||||
HelloWorld: typeof import('./src/components/HelloWorld.vue')['default']
|
||||
InlineLogPanel: typeof import('./src/components/InlineLogPanel.vue')['default']
|
||||
LogViewer: typeof import('./src/components/LogViewer.vue')['default']
|
||||
RouterLink: typeof import('vue-router')['RouterLink']
|
||||
RouterView: typeof import('vue-router')['RouterView']
|
||||
}
|
||||
|
||||
1708
web/package-lock.json
generated
1708
web/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "webui",
|
||||
"name": "GoTunnel",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -11,17 +11,18 @@
|
||||
"dependencies": {
|
||||
"@vicons/ionicons5": "^0.13.0",
|
||||
"axios": "^1.13.2",
|
||||
"naive-ui": "^2.43.2",
|
||||
"vue": "^3.5.24",
|
||||
"vue-router": "^4.6.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4.1.18",
|
||||
"@types/node": "^24.10.1",
|
||||
"@vitejs/plugin-vue": "^6.0.1",
|
||||
"@vue/tsconfig": "^0.8.1",
|
||||
"autoprefixer": "^10.4.23",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "^4.1.18",
|
||||
"typescript": "~5.9.3",
|
||||
"unplugin-auto-import": "^20.3.0",
|
||||
"unplugin-vue-components": "^30.0.0",
|
||||
"vite": "^7.2.4",
|
||||
"vue-tsc": "^3.1.4"
|
||||
}
|
||||
|
||||
5
web/postcss.config.js
Normal file
5
web/postcss.config.js
Normal file
@@ -0,0 +1,5 @@
|
||||
export default {
|
||||
plugins: {
|
||||
'@tailwindcss/postcss': {},
|
||||
},
|
||||
}
|
||||
586
web/src/App.vue
586
web/src/App.vue
@@ -1,105 +1,533 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, computed, h, watch } from 'vue'
|
||||
import { RouterView, useRouter, useRoute } from 'vue-router'
|
||||
import { NLayout, NLayoutHeader, NLayoutContent, NMenu, NButton, NSpace, NTag, NIcon, NConfigProvider, NMessageProvider, NDialogProvider } from 'naive-ui'
|
||||
import { HomeOutline, ExtensionPuzzleOutline, LogOutOutline } from '@vicons/ionicons5'
|
||||
import type { MenuOption } from 'naive-ui'
|
||||
import { getServerStatus, removeToken, getToken } from './api'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { RouterView, useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
ContrastOutline,
|
||||
DesktopOutline,
|
||||
HomeOutline,
|
||||
LogOutOutline,
|
||||
MoonOutline,
|
||||
PersonCircleOutline,
|
||||
SettingsOutline,
|
||||
SunnyOutline,
|
||||
SyncOutline,
|
||||
} from '@vicons/ionicons5'
|
||||
import GlassModal from './components/GlassModal.vue'
|
||||
import { applyServerUpdate, checkServerUpdate, getServerStatus, getToken, getVersionInfo, removeToken, type UpdateInfo } from './api'
|
||||
import { useConfirm } from './composables/useConfirm'
|
||||
import { useTheme, type ThemeMode } from './composables/useTheme'
|
||||
import { useToast } from './composables/useToast'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const serverInfo = ref({ bind_addr: '', bind_port: 0 })
|
||||
const clientCount = ref(0)
|
||||
const message = useToast()
|
||||
const dialog = useConfirm()
|
||||
const { themeMode, setTheme } = useTheme()
|
||||
|
||||
const shellInfo = ref({ bind_addr: '', bind_port: 0, client_count: 0, version: '' })
|
||||
const updateInfo = ref<UpdateInfo | null>(null)
|
||||
const showThemeMenu = ref(false)
|
||||
const showUserMenu = ref(false)
|
||||
const showUpdateModal = ref(false)
|
||||
const updatingServer = ref(false)
|
||||
const themeMenuRef = ref<HTMLElement | null>(null)
|
||||
const userMenuRef = ref<HTMLElement | null>(null)
|
||||
|
||||
const isLoginPage = computed(() => route.path === '/login')
|
||||
|
||||
const menuOptions: MenuOption[] = [
|
||||
{
|
||||
label: '客户端',
|
||||
key: '/',
|
||||
icon: () => h(NIcon, null, { default: () => h(HomeOutline) })
|
||||
},
|
||||
{
|
||||
label: '插件',
|
||||
key: '/plugins',
|
||||
icon: () => h(NIcon, null, { default: () => h(ExtensionPuzzleOutline) })
|
||||
}
|
||||
const navItems = [
|
||||
{ key: 'home', label: '控制台', icon: HomeOutline, path: '/' },
|
||||
{ key: 'clients', label: '客户端', icon: DesktopOutline, path: '/clients' },
|
||||
{ key: 'settings', label: '设置', icon: SettingsOutline, path: '/settings' },
|
||||
]
|
||||
|
||||
const activeKey = computed(() => {
|
||||
if (route.path.startsWith('/client/')) return '/'
|
||||
return route.path
|
||||
const activeNav = computed(() => {
|
||||
if (route.path.startsWith('/client') || route.path === '/clients') return 'clients'
|
||||
if (route.path === '/settings') return 'settings'
|
||||
return 'home'
|
||||
})
|
||||
|
||||
const handleMenuUpdate = (key: string) => {
|
||||
router.push(key)
|
||||
}
|
||||
const themeIcon = computed(() => {
|
||||
if (themeMode.value === 'light') return SunnyOutline
|
||||
if (themeMode.value === 'dark') return MoonOutline
|
||||
return ContrastOutline
|
||||
})
|
||||
|
||||
const fetchServerStatus = async () => {
|
||||
if (isLoginPage.value || !getToken()) return
|
||||
const updateBadgeText = computed(() => {
|
||||
if (!updateInfo.value) return '未检查更新'
|
||||
return updateInfo.value.available ? `可升级到 ${updateInfo.value.latest}` : '已是最新版本'
|
||||
})
|
||||
|
||||
const loadShellInfo = async () => {
|
||||
if (!getToken() || isLoginPage.value) return
|
||||
try {
|
||||
const { data } = await getServerStatus()
|
||||
serverInfo.value = data.server
|
||||
clientCount.value = data.client_count
|
||||
} catch (e) {
|
||||
console.error('Failed to get server status', e)
|
||||
const [statusResult, versionResult, updateResult] = await Promise.allSettled([
|
||||
getServerStatus(),
|
||||
getVersionInfo(),
|
||||
checkServerUpdate(),
|
||||
])
|
||||
|
||||
if (statusResult.status === 'fulfilled') {
|
||||
shellInfo.value.bind_addr = statusResult.value.data.server.bind_addr
|
||||
shellInfo.value.bind_port = statusResult.value.data.server.bind_port
|
||||
shellInfo.value.client_count = statusResult.value.data.client_count
|
||||
}
|
||||
|
||||
if (versionResult.status === 'fulfilled') {
|
||||
shellInfo.value.version = versionResult.value.data.version || ''
|
||||
}
|
||||
|
||||
if (updateResult.status === 'fulfilled') {
|
||||
updateInfo.value = updateResult.value.data
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load shell info', error)
|
||||
}
|
||||
}
|
||||
|
||||
// 监听路由变化,离开登录页时获取状态
|
||||
watch(() => route.path, (newPath, oldPath) => {
|
||||
if (oldPath === '/login' && newPath !== '/login') {
|
||||
fetchServerStatus()
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
fetchServerStatus()
|
||||
})
|
||||
const selectTheme = (mode: ThemeMode) => {
|
||||
setTheme(mode)
|
||||
showThemeMenu.value = false
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
removeToken()
|
||||
router.push('/login')
|
||||
}
|
||||
|
||||
const formatBytes = (bytes: number) => {
|
||||
if (!bytes) return '0 B'
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
const index = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1)
|
||||
return `${(bytes / Math.pow(1024, index)).toFixed(index === 0 ? 0 : 1)} ${units[index] ?? 'B'}`
|
||||
}
|
||||
|
||||
const handleApplyServerUpdate = () => {
|
||||
if (!updateInfo.value?.download_url) {
|
||||
message.error('没有可用的更新包')
|
||||
return
|
||||
}
|
||||
|
||||
dialog.warning({
|
||||
title: '确认升级服务端',
|
||||
content: `即将升级到 ${updateInfo.value.latest},服务端会自动重启。是否继续?`,
|
||||
positiveText: '立即升级',
|
||||
negativeText: '取消',
|
||||
onPositiveClick: async () => {
|
||||
updatingServer.value = true
|
||||
try {
|
||||
await applyServerUpdate(updateInfo.value!.download_url)
|
||||
message.success('升级任务已提交,页面将在 5 秒后尝试刷新')
|
||||
showUpdateModal.value = false
|
||||
window.setTimeout(() => window.location.reload(), 5000)
|
||||
} catch (error: any) {
|
||||
message.error(error.response?.data || '升级失败')
|
||||
updatingServer.value = false
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const closeMenus = (event: MouseEvent) => {
|
||||
const target = event.target as Node
|
||||
if (themeMenuRef.value && !themeMenuRef.value.contains(target)) showThemeMenu.value = false
|
||||
if (userMenuRef.value && !userMenuRef.value.contains(target)) showUserMenu.value = false
|
||||
}
|
||||
|
||||
watch(() => route.fullPath, () => {
|
||||
showThemeMenu.value = false
|
||||
showUserMenu.value = false
|
||||
if (!isLoginPage.value) loadShellInfo()
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('click', closeMenus)
|
||||
loadShellInfo()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener('click', closeMenus)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<n-config-provider>
|
||||
<n-dialog-provider>
|
||||
<n-message-provider>
|
||||
<n-layout v-if="!isLoginPage" style="min-height: 100vh;">
|
||||
<n-layout-header bordered style="height: 64px; padding: 0 24px; display: flex; align-items: center; justify-content: space-between;">
|
||||
<div style="display: flex; align-items: center; gap: 32px;">
|
||||
<div style="font-size: 20px; font-weight: 600; color: #18a058; cursor: pointer;" @click="router.push('/')">
|
||||
GoTunnel
|
||||
<RouterView v-if="isLoginPage" />
|
||||
<div v-else class="app-shell">
|
||||
<aside class="app-sidebar glass-card">
|
||||
<div class="brand-block">
|
||||
<span class="brand-mark">GT</span>
|
||||
<div>
|
||||
<strong>GoTunnel</strong>
|
||||
<p>内网穿透控制台</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav class="sidebar-nav">
|
||||
<router-link
|
||||
v-for="item in navItems"
|
||||
:key="item.key"
|
||||
:to="item.path"
|
||||
class="nav-link"
|
||||
:class="{ active: activeNav === item.key }"
|
||||
>
|
||||
<component :is="item.icon" class="nav-link__icon" />
|
||||
<span>{{ item.label }}</span>
|
||||
</router-link>
|
||||
</nav>
|
||||
|
||||
<div class="sidebar-card">
|
||||
<span class="sidebar-card__label">服务监听</span>
|
||||
<strong>{{ shellInfo.bind_addr || '0.0.0.0' }}:{{ shellInfo.bind_port || '—' }}</strong>
|
||||
<p>在线客户端 {{ shellInfo.client_count }}</p>
|
||||
</div>
|
||||
|
||||
<div class="sidebar-card update-card" @click="showUpdateModal = true">
|
||||
<span class="sidebar-card__label">更新状态</span>
|
||||
<strong>{{ updateBadgeText }}</strong>
|
||||
<p>{{ shellInfo.version ? `当前 ${shellInfo.version}` : '点击查看详情' }}</p>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div class="app-main">
|
||||
<header class="app-topbar glass-card">
|
||||
<div>
|
||||
<span class="topbar-label">Workspace</span>
|
||||
<h1>{{ navItems.find((item) => item.key === activeNav)?.label || '控制台' }}</h1>
|
||||
</div>
|
||||
|
||||
<div class="topbar-actions">
|
||||
<button class="topbar-icon-btn" @click="loadShellInfo">
|
||||
<SyncOutline />
|
||||
</button>
|
||||
|
||||
<div ref="themeMenuRef" class="menu-wrap">
|
||||
<button class="topbar-icon-btn" @click.stop="showThemeMenu = !showThemeMenu">
|
||||
<component :is="themeIcon" />
|
||||
</button>
|
||||
<div v-if="showThemeMenu" class="floating-menu">
|
||||
<button class="floating-menu__item" :class="{ active: themeMode === 'light' }" @click="selectTheme('light')">
|
||||
<SunnyOutline /> 浅色
|
||||
</button>
|
||||
<button class="floating-menu__item" :class="{ active: themeMode === 'dark' }" @click="selectTheme('dark')">
|
||||
<MoonOutline /> 深色
|
||||
</button>
|
||||
<button class="floating-menu__item" :class="{ active: themeMode === 'auto' }" @click="selectTheme('auto')">
|
||||
<ContrastOutline /> 自动
|
||||
</button>
|
||||
</div>
|
||||
<n-menu
|
||||
mode="horizontal"
|
||||
:options="menuOptions"
|
||||
:value="activeKey"
|
||||
@update:value="handleMenuUpdate"
|
||||
/>
|
||||
</div>
|
||||
<n-space align="center" :size="16">
|
||||
<n-tag type="info" round>
|
||||
{{ serverInfo.bind_addr }}:{{ serverInfo.bind_port }}
|
||||
</n-tag>
|
||||
<n-tag type="success" round>
|
||||
{{ clientCount }} 客户端
|
||||
</n-tag>
|
||||
<n-button quaternary circle @click="logout">
|
||||
<template #icon>
|
||||
<n-icon><LogOutOutline /></n-icon>
|
||||
</template>
|
||||
</n-button>
|
||||
</n-space>
|
||||
</n-layout-header>
|
||||
<n-layout-content content-style="padding: 24px; max-width: 1200px; margin: 0 auto; width: 100%;">
|
||||
<RouterView />
|
||||
</n-layout-content>
|
||||
</n-layout>
|
||||
<RouterView v-else />
|
||||
</n-message-provider>
|
||||
</n-dialog-provider>
|
||||
</n-config-provider>
|
||||
|
||||
<div ref="userMenuRef" class="menu-wrap">
|
||||
<button class="profile-button" @click.stop="showUserMenu = !showUserMenu">
|
||||
<PersonCircleOutline />
|
||||
<span>管理员</span>
|
||||
</button>
|
||||
<div v-if="showUserMenu" class="floating-menu floating-menu--right">
|
||||
<button class="floating-menu__item" @click="logout">
|
||||
<LogOutOutline /> 退出登录
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="app-content">
|
||||
<RouterView />
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<GlassModal :show="showUpdateModal" title="服务端更新" width="560px" @close="showUpdateModal = false">
|
||||
<div v-if="updateInfo" class="update-grid">
|
||||
<div><span>当前版本</span><strong>{{ updateInfo.current }}</strong></div>
|
||||
<div><span>最新版本</span><strong>{{ updateInfo.latest }}</strong></div>
|
||||
<div><span>文件名</span><strong>{{ updateInfo.asset_name || '未提供' }}</strong></div>
|
||||
<div><span>文件大小</span><strong>{{ formatBytes(updateInfo.asset_size) }}</strong></div>
|
||||
</div>
|
||||
<div v-if="updateInfo?.release_note" class="release-note">{{ updateInfo.release_note }}</div>
|
||||
<template #footer>
|
||||
<button class="glass-btn" @click="showUpdateModal = false">关闭</button>
|
||||
<button v-if="updateInfo?.available" class="glass-btn primary" :disabled="updatingServer" @click="handleApplyServerUpdate">
|
||||
{{ updatingServer ? '升级中...' : '立即升级' }}
|
||||
</button>
|
||||
</template>
|
||||
</GlassModal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.app-shell {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
grid-template-columns: 260px minmax(0, 1fr);
|
||||
gap: 20px;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.app-sidebar,
|
||||
.app-topbar {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.app-sidebar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
position: sticky;
|
||||
top: 20px;
|
||||
height: calc(100vh - 40px);
|
||||
}
|
||||
|
||||
.brand-block {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.brand-mark {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 14px;
|
||||
background: var(--gradient-accent);
|
||||
color: white;
|
||||
font-weight: 700;
|
||||
box-shadow: 0 8px 20px var(--color-accent-glow);
|
||||
}
|
||||
|
||||
.brand-block strong {
|
||||
color: var(--color-text-primary);
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.brand-block p,
|
||||
.sidebar-card p,
|
||||
.topbar-label {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.sidebar-nav {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 14px;
|
||||
border-radius: 14px;
|
||||
text-decoration: none;
|
||||
color: var(--color-text-secondary);
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.nav-link:hover,
|
||||
.nav-link.active {
|
||||
color: var(--color-text-primary);
|
||||
background: var(--glass-bg-light);
|
||||
}
|
||||
|
||||
.nav-link.active {
|
||||
box-shadow: inset 0 0 0 1px rgba(59, 130, 246, 0.18);
|
||||
}
|
||||
|
||||
.nav-link__icon {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.sidebar-card {
|
||||
padding: 18px;
|
||||
border-radius: 18px;
|
||||
background: var(--glass-bg-light);
|
||||
border: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
.sidebar-card__label {
|
||||
display: block;
|
||||
margin-bottom: 10px;
|
||||
color: var(--color-text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.sidebar-card strong {
|
||||
display: block;
|
||||
color: var(--color-text-primary);
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.update-card {
|
||||
margin-top: auto;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.app-main {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.app-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.app-topbar h1 {
|
||||
margin: 6px 0 0;
|
||||
font-size: 24px;
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
|
||||
.topbar-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.topbar-icon-btn,
|
||||
.profile-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
height: 42px;
|
||||
padding: 0 14px;
|
||||
border-radius: 12px;
|
||||
border: 1px solid var(--color-border);
|
||||
background: var(--glass-bg-light);
|
||||
color: var(--color-text-primary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.topbar-icon-btn svg,
|
||||
.profile-button svg,
|
||||
.floating-menu__item svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.menu-wrap {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.floating-menu {
|
||||
position: absolute;
|
||||
top: calc(100% + 10px);
|
||||
left: 0;
|
||||
min-width: 168px;
|
||||
padding: 8px;
|
||||
border-radius: 16px;
|
||||
background: var(--glass-bg);
|
||||
border: 1px solid var(--color-border);
|
||||
box-shadow: var(--shadow-lg);
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.floating-menu--right {
|
||||
right: 0;
|
||||
left: auto;
|
||||
}
|
||||
|
||||
.floating-menu__item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
padding: 10px 12px;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
background: transparent;
|
||||
color: var(--color-text-primary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.floating-menu__item.active,
|
||||
.floating-menu__item:hover {
|
||||
background: var(--glass-bg-light);
|
||||
}
|
||||
|
||||
.app-content {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.update-grid {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.update-grid div {
|
||||
padding: 14px;
|
||||
border-radius: 14px;
|
||||
background: var(--glass-bg-light);
|
||||
border: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
.update-grid span {
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.update-grid strong {
|
||||
color: var(--color-text-primary);
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.release-note {
|
||||
margin-top: 16px;
|
||||
padding: 14px;
|
||||
border-radius: 14px;
|
||||
background: var(--glass-bg-light);
|
||||
border: 1px solid var(--color-border-light);
|
||||
color: var(--color-text-secondary);
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
@media (max-width: 1080px) {
|
||||
.app-shell {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.app-sidebar {
|
||||
position: static;
|
||||
height: auto;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.app-shell {
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.app-sidebar,
|
||||
.app-topbar {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.app-topbar {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.topbar-actions {
|
||||
width: 100%;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.profile-button {
|
||||
flex: 1;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.update-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { get, post, put, del } from '../config/axios'
|
||||
import type { ClientConfig, ClientStatus, ClientDetail, ServerStatus, PluginInfo, StorePluginInfo, PluginConfigResponse, JSPlugin } from '../types'
|
||||
import { get, post, put, del, getToken } from '../config/axios'
|
||||
import type { ClientConfig, ClientStatus, ClientDetail, ServerStatus, LogEntry, LogStreamOptions, InstallCommandResponse } from '../types'
|
||||
|
||||
// 重新导出 token 管理方法
|
||||
export { getToken, setToken, removeToken } from '../config/axios'
|
||||
@@ -23,30 +23,158 @@ export const reloadConfig = () => post('/config/reload')
|
||||
// 客户端控制
|
||||
export const pushConfigToClient = (id: string) => post(`/client/${id}/push`)
|
||||
export const disconnectClient = (id: string) => post(`/client/${id}/disconnect`)
|
||||
export const installPluginsToClient = (id: string, plugins: string[]) =>
|
||||
post(`/client/${id}/install-plugins`, { plugins })
|
||||
export const restartClient = (id: string) => post(`/client/${id}/restart`)
|
||||
|
||||
// 插件管理
|
||||
export const getPlugins = () => get<PluginInfo[]>('/plugins')
|
||||
export const enablePlugin = (name: string) => post(`/plugin/${name}/enable`)
|
||||
export const disablePlugin = (name: string) => post(`/plugin/${name}/disable`)
|
||||
// 更新管理
|
||||
export interface UpdateInfo {
|
||||
available: boolean
|
||||
current: string
|
||||
latest: string
|
||||
release_note: string
|
||||
download_url: string
|
||||
asset_name: string
|
||||
asset_size: number
|
||||
}
|
||||
|
||||
// 扩展商店
|
||||
export const getStorePlugins = () => get<{ plugins: StorePluginInfo[] }>('/store/plugins')
|
||||
export const installStorePlugin = (pluginName: string, downloadUrl: string, signatureUrl: string, clientId: string) =>
|
||||
post('/store/install', { plugin_name: pluginName, download_url: downloadUrl, signature_url: signatureUrl, client_id: clientId })
|
||||
export interface VersionInfo {
|
||||
version: string
|
||||
git_commit: string
|
||||
build_time: string
|
||||
go_version: string
|
||||
os: string
|
||||
arch: string
|
||||
}
|
||||
|
||||
// 客户端插件配置
|
||||
export const getClientPluginConfig = (clientId: string, pluginName: string) =>
|
||||
get<PluginConfigResponse>(`/client-plugin/${clientId}/${pluginName}/config`)
|
||||
export const updateClientPluginConfig = (clientId: string, pluginName: string, config: Record<string, string>) =>
|
||||
put(`/client-plugin/${clientId}/${pluginName}/config`, { config })
|
||||
export const getVersionInfo = () => get<VersionInfo>('/update/version')
|
||||
export const checkServerUpdate = () => get<UpdateInfo>('/update/check/server')
|
||||
export const checkClientUpdate = (os?: string, arch?: string) => {
|
||||
const params = new URLSearchParams()
|
||||
if (os) params.append('os', os)
|
||||
if (arch) params.append('arch', arch)
|
||||
const query = params.toString()
|
||||
return get<UpdateInfo>(`/update/check/client${query ? '?' + query : ''}`)
|
||||
}
|
||||
export const applyServerUpdate = (downloadUrl: string, restart: boolean = true) =>
|
||||
post('/update/apply/server', { download_url: downloadUrl, restart })
|
||||
export const applyClientUpdate = (clientId: string, downloadUrl: string) =>
|
||||
post('/update/apply/client', { client_id: clientId, download_url: downloadUrl })
|
||||
|
||||
// JS 插件管理
|
||||
export const getJSPlugins = () => get<JSPlugin[]>('/js-plugins')
|
||||
export const createJSPlugin = (plugin: JSPlugin) => post('/js-plugins', plugin)
|
||||
export const getJSPlugin = (name: string) => get<JSPlugin>(`/js-plugin/${name}`)
|
||||
export const updateJSPlugin = (name: string, plugin: JSPlugin) => put(`/js-plugin/${name}`, plugin)
|
||||
export const deleteJSPlugin = (name: string) => del(`/js-plugin/${name}`)
|
||||
export const pushJSPluginToClient = (pluginName: string, clientId: string) =>
|
||||
post(`/js-plugin/${pluginName}/push/${clientId}`)
|
||||
// 日志流
|
||||
export const createLogStream = (
|
||||
clientId: string,
|
||||
options: LogStreamOptions = {},
|
||||
onLog: (entry: LogEntry) => void,
|
||||
onError?: (error: Event) => void
|
||||
): EventSource => {
|
||||
const token = getToken()
|
||||
const params = new URLSearchParams()
|
||||
if (token) params.append('token', token)
|
||||
if (options.lines !== undefined) params.append('lines', String(options.lines))
|
||||
if (options.follow !== undefined) params.append('follow', String(options.follow))
|
||||
if (options.level) params.append('level', options.level)
|
||||
|
||||
const url = `/api/client/${clientId}/logs?${params.toString()}`
|
||||
const eventSource = new EventSource(url)
|
||||
|
||||
eventSource.addEventListener('log', (event) => {
|
||||
try {
|
||||
const entry = JSON.parse((event as MessageEvent).data) as LogEntry
|
||||
onLog(entry)
|
||||
} catch (e) {
|
||||
console.error('Failed to parse log entry', e)
|
||||
}
|
||||
})
|
||||
|
||||
eventSource.addEventListener('heartbeat', () => {
|
||||
// Keep-alive, no action needed
|
||||
})
|
||||
|
||||
if (onError) {
|
||||
eventSource.onerror = onError
|
||||
}
|
||||
|
||||
return eventSource
|
||||
}
|
||||
|
||||
// 流量统计
|
||||
export interface TrafficStats {
|
||||
traffic_24h: { inbound: number; outbound: number }
|
||||
traffic_total: { inbound: number; outbound: number }
|
||||
}
|
||||
|
||||
export interface TrafficRecord {
|
||||
timestamp: number
|
||||
inbound: number
|
||||
outbound: number
|
||||
}
|
||||
|
||||
export const getTrafficStats = () => get<TrafficStats>('/traffic/stats')
|
||||
export const getTrafficHourly = () => get<{ records: TrafficRecord[] }>('/traffic/hourly')
|
||||
|
||||
// 客户端系统状态
|
||||
export interface SystemStats {
|
||||
cpu_usage: number
|
||||
memory_total: number
|
||||
memory_used: number
|
||||
memory_usage: number
|
||||
disk_total: number
|
||||
disk_used: number
|
||||
disk_usage: number
|
||||
}
|
||||
|
||||
export const getClientSystemStats = (clientId: string) => get<SystemStats>(`/client/${clientId}/system-stats`)
|
||||
|
||||
// 客户端截图
|
||||
export interface ScreenshotData {
|
||||
data: string // Base64 JPEG
|
||||
width: number
|
||||
height: number
|
||||
timestamp: number
|
||||
error?: string
|
||||
}
|
||||
|
||||
export const getClientScreenshot = (clientId: string, quality?: number) =>
|
||||
get<ScreenshotData>(`/client/${clientId}/screenshot${quality ? '?quality=' + quality : ''}`)
|
||||
|
||||
// Shell 执行
|
||||
export interface ShellResult {
|
||||
output: string
|
||||
exit_code: number
|
||||
error?: string
|
||||
}
|
||||
|
||||
export const executeClientShell = (clientId: string, command: string, timeout?: number) =>
|
||||
post<ShellResult>(`/client/${clientId}/shell`, { command, timeout: timeout || 30 })
|
||||
|
||||
// 服务器配置
|
||||
export interface ServerConfigInfo {
|
||||
bind_addr: string
|
||||
bind_port: number
|
||||
token: string
|
||||
heartbeat_sec: number
|
||||
heartbeat_timeout: number
|
||||
}
|
||||
|
||||
export interface WebConfigInfo {
|
||||
enabled: boolean
|
||||
bind_port: number
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
export interface ServerConfigResponse {
|
||||
server: ServerConfigInfo
|
||||
web: WebConfigInfo
|
||||
}
|
||||
|
||||
export interface UpdateServerConfigRequest {
|
||||
server?: Partial<ServerConfigInfo>
|
||||
web?: Partial<WebConfigInfo>
|
||||
}
|
||||
|
||||
export const getServerConfig = () => get<ServerConfigResponse>('/config')
|
||||
export const updateServerConfig = (config: UpdateServerConfigRequest) => put('/config', config)
|
||||
|
||||
// 安装命令生成
|
||||
export const generateInstallCommand = () =>
|
||||
post<InstallCommandResponse>('/install/generate')
|
||||
|
||||
128
web/src/components/GlassModal.vue
Normal file
128
web/src/components/GlassModal.vue
Normal file
@@ -0,0 +1,128 @@
|
||||
<script setup lang="ts">
|
||||
import { CloseOutline } from '@vicons/ionicons5'
|
||||
|
||||
defineProps<{
|
||||
show: boolean
|
||||
title: string
|
||||
width?: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'close'): void
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div v-if="show" class="modal-overlay" @click.self="emit('close')">
|
||||
<div class="modal-container" :style="{ maxWidth: width || '500px' }">
|
||||
<div class="modal-header">
|
||||
<h3>{{ title }}</h3>
|
||||
<button class="close-btn" @click="emit('close')">
|
||||
<CloseOutline />
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<slot />
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<slot name="footer" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.modal-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
backdrop-filter: blur(4px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.modal-container {
|
||||
width: 100%;
|
||||
background: var(--glass-bg);
|
||||
backdrop-filter: var(--glass-blur);
|
||||
-webkit-backdrop-filter: var(--glass-blur);
|
||||
border-radius: 16px;
|
||||
border: 1px solid var(--color-border);
|
||||
overflow: hidden;
|
||||
box-shadow: var(--shadow-lg), var(--shadow-glow);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* 顶部高光 */
|
||||
.modal-container::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 15%;
|
||||
right: 15%;
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg,
|
||||
transparent 0%,
|
||||
rgba(255, 255, 255, 0.15) 50%,
|
||||
transparent 100%);
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
.modal-header h3 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
background: var(--glass-bg-light);
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
padding: 6px;
|
||||
color: var(--color-text-secondary);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.close-btn:hover {
|
||||
background: rgba(239, 68, 68, 0.15);
|
||||
color: var(--color-error);
|
||||
}
|
||||
|
||||
.close-btn svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.modal-body {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.modal-footer {
|
||||
padding: 16px 20px;
|
||||
border-top: 1px solid var(--color-border-light);
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.modal-footer:empty {
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
85
web/src/components/GlassSwitch.vue
Normal file
85
web/src/components/GlassSwitch.vue
Normal file
@@ -0,0 +1,85 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
modelValue?: boolean
|
||||
size?: 'small' | 'medium'
|
||||
disabled?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', value: boolean): void
|
||||
}>()
|
||||
|
||||
const toggle = () => {
|
||||
if (!props.disabled) {
|
||||
emit('update:modelValue', !props.modelValue)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
class="glass-switch"
|
||||
:class="[size || 'small', { active: modelValue, disabled }]"
|
||||
@click="toggle"
|
||||
:disabled="disabled"
|
||||
>
|
||||
<span class="switch-thumb"></span>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.glass-switch {
|
||||
position: relative;
|
||||
width: 36px;
|
||||
height: 20px;
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.glass-switch.small {
|
||||
width: 32px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.glass-switch:hover:not(.disabled) {
|
||||
background: rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
|
||||
.glass-switch.active {
|
||||
background: linear-gradient(135deg, #60a5fa 0%, #a78bfa 100%);
|
||||
}
|
||||
|
||||
.glass-switch.disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.switch-thumb {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
left: 2px;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
background: white;
|
||||
border-radius: 50%;
|
||||
transition: transform 0.2s;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.glass-switch.small .switch-thumb {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
}
|
||||
|
||||
.glass-switch.active .switch-thumb {
|
||||
transform: translateX(16px);
|
||||
}
|
||||
|
||||
.glass-switch.small.active .switch-thumb {
|
||||
transform: translateX(14px);
|
||||
}
|
||||
</style>
|
||||
60
web/src/components/GlassTag.vue
Normal file
60
web/src/components/GlassTag.vue
Normal file
@@ -0,0 +1,60 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
type?: 'default' | 'success' | 'warning' | 'error' | 'info'
|
||||
size?: 'small' | 'medium'
|
||||
round?: boolean
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="glass-tag" :class="[type || 'default', size || 'small', { round }]">
|
||||
<slot />
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.glass-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
}
|
||||
|
||||
.glass-tag.round {
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
.glass-tag.medium {
|
||||
padding: 4px 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.glass-tag.success {
|
||||
background: rgba(52, 211, 153, 0.15);
|
||||
border-color: rgba(52, 211, 153, 0.3);
|
||||
color: #34d399;
|
||||
}
|
||||
|
||||
.glass-tag.warning {
|
||||
background: rgba(251, 191, 36, 0.15);
|
||||
border-color: rgba(251, 191, 36, 0.3);
|
||||
color: #fbbf24;
|
||||
}
|
||||
|
||||
.glass-tag.error {
|
||||
background: rgba(239, 68, 68, 0.15);
|
||||
border-color: rgba(239, 68, 68, 0.3);
|
||||
color: #f87171;
|
||||
}
|
||||
|
||||
.glass-tag.info {
|
||||
background: rgba(96, 165, 250, 0.15);
|
||||
border-color: rgba(96, 165, 250, 0.3);
|
||||
color: #60a5fa;
|
||||
}
|
||||
</style>
|
||||
300
web/src/components/InlineLogPanel.vue
Normal file
300
web/src/components/InlineLogPanel.vue
Normal file
@@ -0,0 +1,300 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
|
||||
import { PlayOutline, StopOutline, TrashOutline } from '@vicons/ionicons5'
|
||||
import { createLogStream } from '../api'
|
||||
import type { LogEntry } from '../types'
|
||||
|
||||
const props = defineProps<{
|
||||
clientId: string
|
||||
}>()
|
||||
|
||||
const logs = ref<LogEntry[]>([])
|
||||
const isStreaming = ref(false)
|
||||
const autoScroll = ref(true)
|
||||
const loading = ref(false)
|
||||
|
||||
let eventSource: EventSource | null = null
|
||||
const logContainer = ref<HTMLElement | null>(null)
|
||||
|
||||
const startStream = () => {
|
||||
if (eventSource) {
|
||||
eventSource.close()
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
isStreaming.value = true
|
||||
|
||||
eventSource = createLogStream(
|
||||
props.clientId,
|
||||
{ lines: 100, follow: true, level: '' },
|
||||
(entry) => {
|
||||
logs.value.push(entry)
|
||||
if (logs.value.length > 500) {
|
||||
logs.value = logs.value.slice(-300)
|
||||
}
|
||||
if (autoScroll.value) {
|
||||
nextTick(() => scrollToBottom())
|
||||
}
|
||||
loading.value = false
|
||||
},
|
||||
() => {
|
||||
isStreaming.value = false
|
||||
loading.value = false
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
const stopStream = () => {
|
||||
if (eventSource) {
|
||||
eventSource.close()
|
||||
eventSource = null
|
||||
}
|
||||
isStreaming.value = false
|
||||
}
|
||||
|
||||
const clearLogs = () => {
|
||||
logs.value = []
|
||||
}
|
||||
|
||||
const scrollToBottom = () => {
|
||||
if (logContainer.value) {
|
||||
logContainer.value.scrollTop = logContainer.value.scrollHeight
|
||||
}
|
||||
}
|
||||
|
||||
const getLevelColor = (level: string): string => {
|
||||
switch (level) {
|
||||
case 'error': return '#fca5a5'
|
||||
case 'warn': return '#fcd34d'
|
||||
case 'info': return '#60a5fa'
|
||||
case 'debug': return '#9ca3af'
|
||||
default: return 'rgba(255,255,255,0.7)'
|
||||
}
|
||||
}
|
||||
|
||||
const formatTime = (ts: number): string => {
|
||||
return new Date(ts).toLocaleTimeString('en-US', { hour12: false })
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
startStream()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
stopStream()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="inline-log-panel">
|
||||
<div class="log-toolbar">
|
||||
<div class="toolbar-left">
|
||||
<span class="log-title">实时日志</span>
|
||||
<span v-if="isStreaming" class="streaming-badge">
|
||||
<span class="streaming-dot"></span>
|
||||
实时
|
||||
</span>
|
||||
</div>
|
||||
<div class="toolbar-right">
|
||||
<button v-if="!isStreaming" class="tool-btn" @click="startStream" title="开始">
|
||||
<PlayOutline class="tool-icon" />
|
||||
</button>
|
||||
<button v-else class="tool-btn" @click="stopStream" title="停止">
|
||||
<StopOutline class="tool-icon" />
|
||||
</button>
|
||||
<button class="tool-btn" @click="clearLogs" title="清空">
|
||||
<TrashOutline class="tool-icon" />
|
||||
</button>
|
||||
<label class="auto-scroll-toggle">
|
||||
<input type="checkbox" v-model="autoScroll" />
|
||||
<span>自动滚动</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div ref="logContainer" class="log-content">
|
||||
<div v-if="loading && logs.length === 0" class="log-loading">
|
||||
连接中...
|
||||
</div>
|
||||
<div v-else-if="logs.length === 0" class="log-empty">
|
||||
暂无日志
|
||||
</div>
|
||||
<div v-else class="log-lines">
|
||||
<div v-for="(log, index) in logs" :key="index" class="log-line">
|
||||
<span class="log-time">{{ formatTime(log.ts) }}</span>
|
||||
<span class="log-level" :style="{ color: getLevelColor(log.level) }">
|
||||
[{{ log.level.toUpperCase() }}]
|
||||
</span>
|
||||
<span class="log-src">[{{ log.src }}]</span>
|
||||
<span class="log-msg">{{ log.msg }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.inline-log-panel {
|
||||
background: var(--glass-bg);
|
||||
border-radius: 12px;
|
||||
border: 1px solid var(--color-border);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.log-toolbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
background: var(--glass-bg-light);
|
||||
}
|
||||
|
||||
.toolbar-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.log-title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
|
||||
.streaming-badge {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 11px;
|
||||
color: var(--color-success);
|
||||
background: rgba(16, 185, 129, 0.15);
|
||||
padding: 2px 8px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.streaming-dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: var(--color-success);
|
||||
animation: pulse 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.4; }
|
||||
}
|
||||
|
||||
.toolbar-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.tool-btn {
|
||||
background: var(--color-border);
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 6px;
|
||||
color: var(--color-text-secondary);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.tool-btn:hover {
|
||||
background: var(--color-bg-elevated);
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
|
||||
.tool-icon {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
.auto-scroll-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--color-text-secondary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.auto-scroll-toggle input {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
accent-color: var(--color-accent);
|
||||
}
|
||||
|
||||
.log-content {
|
||||
height: 200px;
|
||||
overflow-y: auto;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
background: var(--color-bg-elevated);
|
||||
}
|
||||
|
||||
.log-loading,
|
||||
.log-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
color: var(--color-text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.log-lines {
|
||||
padding: 8px 12px;
|
||||
}
|
||||
|
||||
.log-line {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding: 2px 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.log-time {
|
||||
color: var(--color-text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.log-level {
|
||||
flex-shrink: 0;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.log-src {
|
||||
color: var(--color-text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.log-msg {
|
||||
color: var(--color-text-secondary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* Scrollbar */
|
||||
.log-content::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
.log-content::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.log-content::-webkit-scrollbar-thumb {
|
||||
background: var(--color-border);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.log-content::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--color-text-muted);
|
||||
}
|
||||
</style>
|
||||
479
web/src/components/LogViewer.vue
Normal file
479
web/src/components/LogViewer.vue
Normal file
@@ -0,0 +1,479 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
|
||||
import {
|
||||
PlayOutline, StopOutline, TrashOutline, DownloadOutline, CloseOutline
|
||||
} from '@vicons/ionicons5'
|
||||
import { createLogStream } from '../api'
|
||||
import type { LogEntry } from '../types'
|
||||
|
||||
const props = defineProps<{
|
||||
clientId: string
|
||||
visible: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'close'): void
|
||||
}>()
|
||||
|
||||
const logs = ref<LogEntry[]>([])
|
||||
const isStreaming = ref(false)
|
||||
const autoScroll = ref(true)
|
||||
const levelFilter = ref<string>('')
|
||||
const searchText = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
let eventSource: EventSource | null = null
|
||||
const logContainer = ref<HTMLElement | null>(null)
|
||||
|
||||
const startStream = () => {
|
||||
if (eventSource) {
|
||||
eventSource.close()
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
isStreaming.value = true
|
||||
|
||||
eventSource = createLogStream(
|
||||
props.clientId,
|
||||
{ lines: 500, follow: true, level: levelFilter.value },
|
||||
(entry) => {
|
||||
logs.value.push(entry)
|
||||
// 限制内存中的日志数量
|
||||
if (logs.value.length > 2000) {
|
||||
logs.value = logs.value.slice(-1000)
|
||||
}
|
||||
if (autoScroll.value) {
|
||||
nextTick(() => scrollToBottom())
|
||||
}
|
||||
loading.value = false
|
||||
},
|
||||
() => {
|
||||
isStreaming.value = false
|
||||
loading.value = false
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
const stopStream = () => {
|
||||
if (eventSource) {
|
||||
eventSource.close()
|
||||
eventSource = null
|
||||
}
|
||||
isStreaming.value = false
|
||||
}
|
||||
|
||||
const clearLogs = () => {
|
||||
logs.value = []
|
||||
}
|
||||
|
||||
const scrollToBottom = () => {
|
||||
if (logContainer.value) {
|
||||
logContainer.value.scrollTop = logContainer.value.scrollHeight
|
||||
}
|
||||
}
|
||||
|
||||
const downloadLogs = () => {
|
||||
const content = logs.value.map(l =>
|
||||
`${new Date(l.ts).toISOString()} [${l.level.toUpperCase()}] [${l.src}] ${l.msg}`
|
||||
).join('\n')
|
||||
|
||||
const blob = new Blob([content], { type: 'text/plain' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `${props.clientId}-logs-${new Date().toISOString().slice(0, 10)}.txt`
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
const filteredLogs = computed(() => {
|
||||
if (!searchText.value) return logs.value
|
||||
const search = searchText.value.toLowerCase()
|
||||
return logs.value.filter(l => l.msg.toLowerCase().includes(search))
|
||||
})
|
||||
|
||||
const getLevelColor = (level: string): string => {
|
||||
switch (level) {
|
||||
case 'error': return '#e88080'
|
||||
case 'warn': return '#e8b880'
|
||||
case 'info': return '#80b8e8'
|
||||
case 'debug': return '#808080'
|
||||
default: return '#ffffff'
|
||||
}
|
||||
}
|
||||
|
||||
const formatTime = (ts: number): string => {
|
||||
return new Date(ts).toLocaleTimeString('en-US', { hour12: false })
|
||||
}
|
||||
|
||||
watch(() => props.visible, (visible) => {
|
||||
if (visible) {
|
||||
startStream()
|
||||
} else {
|
||||
stopStream()
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
if (props.visible) {
|
||||
startStream()
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
stopStream()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="log-overlay" @click.self="emit('close')">
|
||||
<div class="log-modal">
|
||||
<!-- Header -->
|
||||
<div class="log-header">
|
||||
<h3>客户端日志</h3>
|
||||
<div class="log-controls">
|
||||
<select v-model="levelFilter" class="log-select" @change="() => { stopStream(); logs = []; startStream(); }">
|
||||
<option value="">所有级别</option>
|
||||
<option value="info">Info</option>
|
||||
<option value="warn">Warning</option>
|
||||
<option value="error">Error</option>
|
||||
<option value="debug">Debug</option>
|
||||
</select>
|
||||
<input v-model="searchText" type="text" class="log-input" placeholder="搜索..." />
|
||||
<label class="log-toggle">
|
||||
<input type="checkbox" v-model="autoScroll" />
|
||||
<span>自动滚动</span>
|
||||
</label>
|
||||
<button class="icon-btn" @click="clearLogs" title="清空">
|
||||
<TrashOutline />
|
||||
</button>
|
||||
<button class="icon-btn" @click="downloadLogs" title="下载">
|
||||
<DownloadOutline />
|
||||
</button>
|
||||
<button class="action-btn" :class="isStreaming ? 'danger' : 'success'" @click="isStreaming ? stopStream() : startStream()">
|
||||
<StopOutline v-if="isStreaming" />
|
||||
<PlayOutline v-else />
|
||||
<span>{{ isStreaming ? '停止' : '开始' }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<button class="close-btn" @click="emit('close')">
|
||||
<CloseOutline />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Content -->
|
||||
<div class="log-body">
|
||||
<div v-if="loading && logs.length === 0" class="log-loading">加载中...</div>
|
||||
<div ref="logContainer" class="log-container">
|
||||
<div v-if="filteredLogs.length === 0" class="log-empty">暂无日志</div>
|
||||
<div v-for="(log, i) in filteredLogs" :key="i" class="log-line">
|
||||
<span class="log-time">{{ formatTime(log.ts) }}</span>
|
||||
<span class="log-level" :style="{ color: getLevelColor(log.level) }">[{{ log.level.toUpperCase() }}]</span>
|
||||
<span class="log-src">[{{ log.src }}]</span>
|
||||
<span class="log-msg">{{ log.msg }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* Overlay */
|
||||
.log-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
backdrop-filter: blur(4px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
/* Modal */
|
||||
.log-modal {
|
||||
width: 100%;
|
||||
max-width: 900px;
|
||||
max-height: 80vh;
|
||||
background: rgba(30, 27, 75, 0.95);
|
||||
backdrop-filter: blur(20px);
|
||||
-webkit-backdrop-filter: blur(20px);
|
||||
border-radius: 16px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Header */
|
||||
.log-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.log-header h3 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: white;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.log-controls {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* Select */
|
||||
.log-select {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
border-radius: 6px;
|
||||
padding: 6px 12px;
|
||||
color: white;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.log-select option {
|
||||
background: #1e1b4b;
|
||||
color: white;
|
||||
}
|
||||
|
||||
/* Input */
|
||||
.log-input {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
border-radius: 6px;
|
||||
padding: 6px 12px;
|
||||
color: white;
|
||||
font-size: 13px;
|
||||
width: 150px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.log-input::placeholder {
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
|
||||
.log-input:focus {
|
||||
border-color: rgba(167, 139, 250, 0.5);
|
||||
}
|
||||
|
||||
/* Toggle */
|
||||
.log-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.log-toggle input[type="checkbox"] {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
accent-color: #a78bfa;
|
||||
}
|
||||
|
||||
/* Icon Button */
|
||||
.icon-btn {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 6px;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.icon-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.icon-btn svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
/* Action Button */
|
||||
.action-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
border-radius: 6px;
|
||||
padding: 6px 12px;
|
||||
color: white;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.action-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.action-btn svg {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
.action-btn.success {
|
||||
background: rgba(52, 211, 153, 0.2);
|
||||
border-color: rgba(52, 211, 153, 0.3);
|
||||
color: #34d399;
|
||||
}
|
||||
|
||||
.action-btn.danger {
|
||||
background: rgba(239, 68, 68, 0.2);
|
||||
border-color: rgba(239, 68, 68, 0.3);
|
||||
color: #fca5a5;
|
||||
}
|
||||
|
||||
/* Close Button */
|
||||
.close-btn {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 6px;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.close-btn:hover {
|
||||
background: rgba(239, 68, 68, 0.2);
|
||||
color: #fca5a5;
|
||||
}
|
||||
|
||||
.close-btn svg {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
/* Body */
|
||||
.log-body {
|
||||
flex: 1;
|
||||
padding: 16px;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.log-loading {
|
||||
text-align: center;
|
||||
padding: 32px;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
/* Container */
|
||||
.log-container {
|
||||
flex: 1;
|
||||
height: 400px;
|
||||
overflow-y: auto;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
padding: 12px;
|
||||
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
|
||||
font-size: 12px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.log-empty {
|
||||
text-align: center;
|
||||
padding: 48px;
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
|
||||
/* Log Line */
|
||||
.log-line {
|
||||
line-height: 1.8;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
.log-time {
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.log-level {
|
||||
margin-right: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.log-src {
|
||||
color: rgba(167, 139, 250, 0.8);
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.log-msg {
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
}
|
||||
|
||||
/* Scrollbar */
|
||||
.log-container::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
.log-container::-webkit-scrollbar-track {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.log-container::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.log-container::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
|
||||
/* Responsive */
|
||||
@media (max-width: 768px) {
|
||||
.log-overlay {
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.log-modal {
|
||||
max-height: 90vh;
|
||||
}
|
||||
|
||||
.log-header {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.log-controls {
|
||||
order: 1;
|
||||
width: 100%;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.log-input {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
62
web/src/components/MetricCard.vue
Normal file
62
web/src/components/MetricCard.vue
Normal file
@@ -0,0 +1,62 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
label: string
|
||||
value: string | number
|
||||
hint?: string
|
||||
tone?: 'default' | 'success' | 'warning' | 'info'
|
||||
}>()
|
||||
|
||||
const toneClass = props.tone || 'default'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article class="metric-card" :class="`metric-card--${toneClass}`">
|
||||
<span class="metric-card__label">{{ label }}</span>
|
||||
<strong class="metric-card__value">{{ value }}</strong>
|
||||
<span v-if="hint" class="metric-card__hint">{{ hint }}</span>
|
||||
</article>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.metric-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 18px;
|
||||
min-height: 128px;
|
||||
border-radius: 20px;
|
||||
background: var(--glass-bg-card);
|
||||
border: 1px solid var(--color-border);
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
|
||||
.metric-card__label {
|
||||
font-size: 13px;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.metric-card__value {
|
||||
font-size: clamp(26px, 4vw, 34px);
|
||||
line-height: 1;
|
||||
color: var(--color-text-primary);
|
||||
letter-spacing: -0.04em;
|
||||
}
|
||||
|
||||
.metric-card__hint {
|
||||
margin-top: auto;
|
||||
font-size: 13px;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.metric-card--success {
|
||||
border-color: rgba(16, 185, 129, 0.24);
|
||||
}
|
||||
|
||||
.metric-card--warning {
|
||||
border-color: rgba(245, 158, 11, 0.24);
|
||||
}
|
||||
|
||||
.metric-card--info {
|
||||
border-color: rgba(6, 182, 212, 0.24);
|
||||
}
|
||||
</style>
|
||||
154
web/src/components/PageShell.vue
Normal file
154
web/src/components/PageShell.vue
Normal file
@@ -0,0 +1,154 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
title: string
|
||||
subtitle?: string
|
||||
eyebrow?: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="page-shell">
|
||||
<div class="page-shell__glow page-shell__glow--primary"></div>
|
||||
<div class="page-shell__glow page-shell__glow--secondary"></div>
|
||||
|
||||
<header class="page-shell__header">
|
||||
<div class="page-shell__heading">
|
||||
<span v-if="eyebrow" class="page-shell__eyebrow">{{ eyebrow }}</span>
|
||||
<h1>{{ title }}</h1>
|
||||
<p v-if="subtitle">{{ subtitle }}</p>
|
||||
</div>
|
||||
<div v-if="$slots.actions" class="page-shell__actions">
|
||||
<slot name="actions" />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div v-if="$slots.metrics" class="page-shell__metrics">
|
||||
<slot name="metrics" />
|
||||
</div>
|
||||
|
||||
<div class="page-shell__content">
|
||||
<slot />
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page-shell {
|
||||
position: relative;
|
||||
padding: 32px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.page-shell__glow {
|
||||
position: absolute;
|
||||
border-radius: 999px;
|
||||
filter: blur(80px);
|
||||
opacity: 0.18;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.page-shell__glow--primary {
|
||||
width: 320px;
|
||||
height: 320px;
|
||||
top: -120px;
|
||||
right: -80px;
|
||||
background: var(--color-accent);
|
||||
}
|
||||
|
||||
.page-shell__glow--secondary {
|
||||
width: 280px;
|
||||
height: 280px;
|
||||
bottom: -120px;
|
||||
left: -40px;
|
||||
background: #8b5cf6;
|
||||
}
|
||||
|
||||
.page-shell__header,
|
||||
.page-shell__metrics,
|
||||
.page-shell__content {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.page-shell__header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 20px;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.page-shell__heading {
|
||||
max-width: 720px;
|
||||
}
|
||||
|
||||
.page-shell__eyebrow {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px 10px;
|
||||
margin-bottom: 12px;
|
||||
border-radius: 999px;
|
||||
background: rgba(59, 130, 246, 0.12);
|
||||
border: 1px solid rgba(59, 130, 246, 0.18);
|
||||
color: var(--color-accent);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.page-shell__heading h1 {
|
||||
margin: 0;
|
||||
font-size: clamp(28px, 4vw, 40px);
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.03em;
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
|
||||
.page-shell__heading p {
|
||||
margin: 10px 0 0;
|
||||
max-width: 640px;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 15px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.page-shell__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.page-shell__metrics {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.page-shell__content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.page-shell {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.page-shell__header {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.page-shell__actions {
|
||||
width: 100%;
|
||||
justify-content: stretch;
|
||||
}
|
||||
|
||||
.page-shell__actions :deep(*) {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user