RepoPilotOpen in app →

Jrohy/trojan

trojan多用户管理部署程序, 支持web页面管理

Mixed

Stale — last commit 2y ago

weakest axis
Use as dependencyConcerns

copyleft license (GPL-3.0) — review compatibility; last commit was 2y ago…

Fork & modifyHealthy

Has a license, tests, and CI — clean foundation to fork and modify.

Learn fromHealthy

Documented and popular — useful reference codebase to read through.

Deploy as-isHealthy

No critical CVEs, sane security posture — runnable as-is.

  • 2 active contributors
  • GPL-3.0 licensed
  • CI configured
Show all 8 evidence items →
  • Stale — last commit 2y ago
  • Small team — 2 contributors active in recent commits
  • Single-maintainer risk — top contributor 99% of recent commits
  • GPL-3.0 is copyleft — check downstream compatibility
  • No test directory detected
What would change the summary?
  • Use as dependency ConcernsMixed if: relicense under MIT/Apache-2.0 (rare for established libs)

Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests

Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.

Embed the "Forkable" badge

Paste into your README — live-updates from the latest cached analysis.

Variant:
RepoPilot: Forkable
[![RepoPilot: Forkable](https://repopilot.app/api/badge/jrohy/trojan?axis=fork)](https://repopilot.app/r/jrohy/trojan)

Paste at the top of your README.md — renders inline like a shields.io badge.

Preview social card (1200×630)

This card auto-renders when someone shares https://repopilot.app/r/jrohy/trojan on X, Slack, or LinkedIn.

Onboarding doc

Onboarding: Jrohy/trojan

Generated by RepoPilot · 2026-05-09 · Source

🤖Agent protocol

If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:

  1. Verify the contract. Run the bash script in Verify before trusting below. If any check returns FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding.
  2. Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
  3. Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/Jrohy/trojan shows verifiable citations alongside every claim.

If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.

🎯Verdict

WAIT — Stale — last commit 2y ago

  • 2 active contributors
  • GPL-3.0 licensed
  • CI configured
  • ⚠ Stale — last commit 2y ago
  • ⚠ Small team — 2 contributors active in recent commits
  • ⚠ Single-maintainer risk — top contributor 99% of recent commits
  • ⚠ GPL-3.0 is copyleft — check downstream compatibility
  • ⚠ No test directory detected

<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>

Verify before trusting

This artifact was generated by RepoPilot at a point in time. Before an agent acts on it, the checks below confirm that the live Jrohy/trojan repo on your machine still matches what RepoPilot saw. If any fail, the artifact is stale — regenerate it at repopilot.app/r/Jrohy/trojan.

What it runs against: a local clone of Jrohy/trojan — the script inspects git remote, the LICENSE file, file paths in the working tree, and git log. Read-only; no mutations.

| # | What we check | Why it matters | |---|---|---| | 1 | You're in Jrohy/trojan | Confirms the artifact applies here, not a fork | | 2 | License is still GPL-3.0 | Catches relicense before you depend on it | | 3 | Default branch master exists | Catches branch renames | | 4 | 5 critical file paths still exist | Catches refactors that moved load-bearing code | | 5 | Last commit ≤ 783 days ago | Catches sudden abandonment since generation |

<details> <summary><b>Run all checks</b> — paste this script from inside your clone of <code>Jrohy/trojan</code></summary>
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of Jrohy/trojan. If you don't
# have one yet, run these first:
#
#   git clone https://github.com/Jrohy/trojan.git
#   cd trojan
#
# Then paste this script. Every check is read-only — no mutations.

set +e
fail=0
ok()   { echo "ok:   $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }

# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
  echo "FAIL: not inside a git repository. cd into your clone of Jrohy/trojan and re-run."
  exit 2
fi

# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "Jrohy/trojan(\\.git)?\\b" \\
  && ok "origin remote is Jrohy/trojan" \\
  || miss "origin remote is not Jrohy/trojan (artifact may be from a fork)"

# 2. License matches what RepoPilot saw
(grep -qiE "^(GPL-3\\.0)" LICENSE 2>/dev/null \\
   || grep -qiE "\"license\"\\s*:\\s*\"GPL-3\\.0\"" package.json 2>/dev/null) \\
  && ok "license is GPL-3.0" \\
  || miss "license drift — was GPL-3.0 at generation time"

# 3. Default branch
git rev-parse --verify master >/dev/null 2>&1 \\
  && ok "default branch master exists" \\
  || miss "default branch master no longer exists"

# 4. Critical files exist
test -f "main.go" \\
  && ok "main.go" \\
  || miss "missing critical file: main.go"
test -f "cmd/root.go" \\
  && ok "cmd/root.go" \\
  || miss "missing critical file: cmd/root.go"
test -f "core/server.go" \\
  && ok "core/server.go" \\
  || miss "missing critical file: core/server.go"
test -f "core/client.go" \\
  && ok "core/client.go" \\
  || miss "missing critical file: core/client.go"
test -f "web/web.go" \\
  && ok "web/web.go" \\
  || miss "missing critical file: web/web.go"

# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 783 ]; then
  ok "last commit was $days_since_last days ago (artifact saw ~753d)"
else
  miss "last commit was $days_since_last days ago — artifact may be stale"
fi

echo
if [ "$fail" -eq 0 ]; then
  echo "artifact verified (0 failures) — safe to trust"
else
  echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/Jrohy/trojan"
  exit 1
fi

Each check prints ok: or FAIL:. The script exits non-zero if anything failed, so it composes cleanly into agent loops (./verify.sh || regenerate-and-retry).

</details>

TL;DR

Trojan is a Go-based multi-user proxy server management and deployment platform with integrated web dashboard. It wraps the Trojan protocol implementation to provide user management, traffic statistics/limits, certificate automation (via acme.sh), and real-time log viewing—enabling administrators to deploy and monitor Trojan servers without manual configuration. The project includes a companion frontend (trojan-web) for browser-based administration. Monolithic CLI + web server structure: cmd/ contains 15+ Cobra CLI commands wrapping business logic in trojan/ (install, user mgmt, web service). Core protocols and storage abstraction in core/ (base.go, client.go, server.go). Utility helpers in util/ (command execution, Linux specifics). Asset files (certificates, config templates) in asset/. Main entry at main.go delegates to Cobra root command.

👥Who it's for

System administrators and DevOps engineers deploying Trojan proxy servers who need multi-user account management, traffic monitoring, and automated certificate renewal without writing configuration files manually. Users range from individuals setting up personal servers to managing multiple accounts via web UI or CLI commands.

🌱Maturity & risk

Actively maintained with 91.3KB of Go code, CI/CD pipeline (docker-publish.yml workflow), and Docker image distribution (docker.io/jrohy/trojan). The project includes install/update scripts and clear versioning, indicating production readiness. However, test coverage is not explicitly mentioned in the file structure, suggesting incomplete test suite.

Single-maintainer risk (Jrohy as primary author) with dependency on external services (acme.sh for certificates, MySQL/MariaDB for data). The codebase uses both LevelDB and MySQL as optional storage backends (core/leveldb.go, core/mysql.go), introducing potential compatibility issues. Moderate dependency count (~15 direct Go dependencies) with older packages like gopsutil v3.21.11 that may have known vulnerabilities.

Active areas of work

Active development with recent updates to web management (cmd/updateWeb.go) and Docker publishing workflow (.github/workflows/docker-publish.yml). The companion frontend trojan-web is actively separate but referenced in docs. Version management and upgrade paths suggest ongoing compatibility work across Trojan protocol versions.

🚀Get running

git clone https://github.com/Jrohy/trojan.git
cd trojan
go mod download
go build -o trojan main.go
./trojan --help

Or use the one-liner: source <(curl -sL https://git.io/trojan-install) (Linux only, runs install.sh).

Daily commands: Development: go run main.go enters interactive CLI or go run main.go web starts web server (Gin default :8080, HTTPS on :443 in production). Production: systemctl start trojan-web (uses trojan-web.service) or docker run -it --net=host jrohy/trojan init for containerized setup with MariaDB backend.

🗺️Map of the codebase

  • main.go — Application entry point that initializes the CLI framework and routes all commands; essential for understanding how the program starts.
  • cmd/root.go — Root Cobra command that defines the CLI structure and global flags; all subcommands are registered here.
  • core/server.go — Core server logic that manages trojan process lifecycle, configuration, and communication; handles the primary service operations.
  • core/client.go — User/client management abstraction layer that interfaces with both LevelDB and MySQL backends; critical for multi-user operations.
  • web/web.go — Gin web server setup and route registration for the management dashboard; entry point for all HTTP/WebSocket handlers.
  • trojan/trojan.go — High-level trojan installation, configuration, and process management; bridges CLI commands with core server operations.
  • core/base.go — Abstract base interface for database backends; defines the contract that MySQL and LevelDB implementations must follow.

🛠️How to make changes

Add a new CLI command

  1. Create a new file in cmd/ directory following the naming pattern cmd/yourcommand.go (cmd/yourcommand.go)
  2. Define a Cobra command struct with Run function that calls trojan package functions (cmd/yourcommand.go)
  3. Register the command in cmd/root.go by adding rootCmd.AddCommand(yourCmd) in the init function (cmd/root.go)
  4. If command needs business logic, add methods to trojan/trojan.go or relevant trojan package file (trojan/trojan.go)

Add a new web API endpoint

  1. Create handler function in the appropriate controller file (e.g., web/controller/user.go for user operations) (web/controller/user.go)
  2. Register the route in web/web.go using gin router methods (e.g., r.POST("/api/users", handler)) (web/web.go)
  3. Apply authentication middleware by placing route in an authenticated group (typically under authMiddleware.MiddlewareFunc()) (web/auth.go)
  4. Implement the business logic by calling functions from core/client.go or trojan/ package modules (core/client.go)

Add support for a new database backend

  1. Create new file implementing the base.Base interface defined in core/base.go (e.g., core/postgres.go) (core/base.go)
  2. Implement all required methods (ListClient, AddClient, DeleteClient, UpdateClient, etc.) (core/postgres.go)
  3. Update core/client.go to instantiate the new backend based on configuration flag (core/client.go)
  4. Add initialization logic in trojan/trojan.go to support the new backend parameter (trojan/trojan.go)

Add a new real-time monitoring feature

  1. Create data collection function in web/controller/data.go to gather metrics from system (web/controller/data.go)
  2. Implement WebSocket handler in util/websocket.go or create new handler using gorilla/websocket (util/websocket.go)
  3. Register WebSocket route in web/web.go using gin websocket adapter (web/web.go)
  4. Use goroutines to push updates at intervals (see gopsutil integration pattern for system metrics) (web/controller/data.go)

🔧Why these technologies

  • Cobra (CLI Framework) — Provides structured command-line interface with auto-completion, subcommands, and flags; essential for complex CLI management tool.
  • Gin (Web Framework) — Lightweight, high-performance HTTP router with built-in middleware support; ideal for real-time API and WebSocket requirements.
  • LevelDB & MySQL (Dual Backends) — LevelDB for simple embedded deployments; MySQL for distributed multi-server setups; abstraction allows runtime backend switching.
  • JWT Authentication (gin-jwt) — Stateless token-based auth suitable for web dashboard; integrates directly with Gin middleware pipeline.
  • WebSocket (gorilla/websocket) — Enables real-time log streaming and bidirectional communication; critical for live dashboard updates without polling.
  • Cron (robfig/cron) — Scheduled traffic reset and maintenance tasks; decoupled from main request loop via goroutine scheduler.

⚖️Trade-offs already made

  • Single binary with embedded assets instead of separate frontend

    • Why: Simplifies deployment and distribution; no need for separate web server or frontend build pipeline.
    • Consequence: Frontend (trojan-web) must be built separately and embedded; updates require recompilation.
  • Dual database backend (LevelDB/MySQL) with runtime selection

    • Why: Supports both simple single-server and complex multi-server deployments without code duplication.
    • Consequence: Added abstraction layer complexity; synchronization issues if schema changes across deployments.
  • Process management via shell commands (systemctl, direct process execution)

    • Why: Avoids hard dependency on systemd; works on any Linux distribution.
    • Consequence: Error handling and process state tracking less robust than native OS integration; platform-specific code in util/linux.go.
  • Trojan binary wrapped and managed as external process

    • Why: Decouples this tool from trojan version changes; users can swap trojan/trojan-go binaries.
    • Consequence: Config file format must match trojan's expected JSON; breaking changes in trojan config require tool updates.

🚫Non-goals (don't propose these)

  • Does not implement trojan protocol itself; acts as management layer for external trojan/trojan-go binaries
  • Does not handle certificate generation directly; delegates to integrated acme.sh
  • Not designed for Windows; Linux/systemd

🪤Traps & gotchas

TLS requirement: Trojan protocol requires valid HTTPS certificates; acme.sh integration assumes let's Encrypt compatibility and port 80/443 access. Database coupling: Web mode requires MySQL/MariaDB running on 127.0.0.1:3306 (or configured host); CLI mode works with embedded LevelDB but web mode is database-only. systemd assumption: install.sh creates trojan-web.service assuming systemd init system; not portable to Alpine/OpenRC without modification. Go module vendoring: go.sum has specific transitive dependencies (e.g., sonic, cpuid/v2); upgrading Go versions may break builds. Trojan binary independence: The tool wraps external trojan/trojan-go binaries downloaded at install time; if upstream removes versions, deployment breaks.

🏗️Architecture

💡Concepts to learn

  • Trojan Protocol — Core protocol this project wraps and manages; understanding Trojan's TLS-mimicry approach and proxy semantics is essential for debugging user issues and extending functionality
  • JWT Token-Based Authentication — trojan/web.go uses appleboy/gin-jwt for stateless API auth; necessary for web dashboard security and multi-client access control
  • LevelDB (Log-Structured Merge Tree) — Default storage backend (core/leveldb.go) for embedded deployments; understanding LSM performance characteristics helps optimize traffic stat queries
  • WebSocket Real-Time Streaming — trojan/web.go uses gorilla/websocket to stream live Trojan logs to browser; critical for real-time log viewing feature
  • systemd Service Units — asset/trojan-web.service defines production deployment behavior; knowledge of ExecStart, Restart policies, and socket activation is needed for ops/debugging
  • Traffic Rate Limiting and Quotas — trojan/user.go implements per-user traffic caps and accounting; essential for multi-tenant fairness and understanding bandwidth management internals
  • Cobra CLI Framework — All 15+ commands (cmd/*.go) use Spf13/Cobra for parsing and dispatch; modifying CLI requires understanding Cobra's command hierarchies and middleware pattern
  • Jrohy/trojan-web — Official companion frontend Vue.js application providing the browser-based dashboard referenced throughout README; paired with this backend for full web experience
  • trojan-gfw/trojan — Original upstream Trojan protocol implementation (C++); this Go project wraps and manages binaries built from this repository
  • p4gefau1t/trojan-go — Go-native Trojan implementation that trojan CLI can switch to via cmd/upgrade.go; drop-in alternative protocol handler
  • acmesh-official/acme.sh — TLS certificate automation tool integrated in trojan/install.go for Let's Encrypt certificate provisioning without external scripts
  • containerd/containerd — Container runtime; complementary to Jrohy/trojan's Docker deployment method (asset/Dockerfile) for self-hosted proxy infrastructure

🪄PR ideas

To work on one of these in Claude Code or Cursor, paste: Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.

Add unit tests for core/client.go and core/server.go database operations

The core package handles critical user and server management through leveldb and mysql backends (core/leveldb.go, core/mysql.go), but there are no visible test files (*_test.go). Adding tests for CRUD operations on clients and servers would catch regressions when modifying database logic and improve code confidence for contributors.

  • [ ] Create core/client_test.go with tests for client creation, retrieval, update, and deletion operations
  • [ ] Create core/server_test.go with tests for server configuration changes
  • [ ] Test both leveldb and mysql implementations using interfaces (core/base.go likely defines contracts)
  • [ ] Add test fixtures for sample trojan configurations using asset/client.json as reference
  • [ ] Run tests in CI pipeline by updating .github/workflows/docker-publish.yml

Add integration tests for web API endpoints in web/controller/user.go and web/controller/trojan.go

The web package exposes critical REST APIs (user management, trojan operations) but lacks visible test coverage. With JWT auth (github.com/appleboy/gin-jwt), database operations, and websocket support (util/websocket.go), integration tests would prevent API breaking changes and ensure request/response contracts are maintained.

  • [ ] Create web/controller/user_test.go testing user add/delete/edit endpoints with valid and invalid JWT tokens
  • [ ] Create web/controller/trojan_test.go testing start/stop/restart/status operations
  • [ ] Use httptest package to mock Gin router and test auth middleware (web/auth.go)
  • [ ] Test error handling for database failures (simulate leveldb/mysql errors)
  • [ ] Add test cases for concurrent requests to ensure thread safety in web/controller/data.go

Add CLI command tests for cmd/ package with example scenarios

The cmd/ package contains 18+ command files (add.go, del.go, export.go, etc.) that directly manipulate trojan configuration, but lacks automated tests. This creates risk when refactoring cobra command definitions or core business logic. Testing these commands ensures the CLI contract remains stable.

  • [ ] Create cmd/add_test.go testing user addition with valid/invalid parameters and database persistence
  • [ ] Create cmd/export_test.go testing config file generation (verify against asset/client.json format)
  • [ ] Create cmd/tls_test.go testing certificate operations and acme.sh integration
  • [ ] Mock the core.Server interface to isolate CLI logic from actual trojan process management
  • [ ] Add snapshot tests for generated configs to catch unexpected format changes in output

🌿Good first issues

  • Add unit tests for cmd/add.go and cmd/del.go user management commands—currently no *_test.go files in cmd/ directory; test flag parsing and database interactions.
  • Document the database schema in README—cmd/import.go and cmd/export.go reference SQL files but no .sql schema is provided in asset/; create and commit trojan.sql with CREATE TABLE statements for users, traffic logs, etc.
  • Implement graceful shutdown for trojan/web.go Gin server—current web.go lacks context-based shutdown; add signal handling (SIGTERM) to close database connections cleanly on systemctl stop trojan-web.

Top contributors

Click to expand

📝Recent commits

Click to expand

🔒Security observations

  • High · SQL Injection Risk in Database Operations — core/mysql.go, web/controller/user.go, web/controller/trojan.go. The codebase includes MySQL database operations (core/mysql.go) that may be vulnerable to SQL injection. Without visible parameterized query usage in the file structure, there's a significant risk of SQL injection attacks when handling user input for trojan user management. Fix: Ensure all SQL queries use prepared statements with parameterized queries. Use database/sql package with proper placeholder usage (?) and bind variables instead of string concatenation.
  • High · Authentication Bypass via JWT Misconfiguration — web/auth.go, web/web.go. The application uses appleboy/gin-jwt for authentication (web/auth.go). JWT implementations are prone to misconfigurations such as: weak secret keys, missing algorithm verification, or improper token validation that could allow attackers to forge tokens. Fix: Verify JWT secret uses strong cryptographic keys (minimum 256 bits), enforce specific signing algorithms (avoid 'none'), implement proper token expiration, and validate all claims server-side.
  • High · WebSocket Security Vulnerabilities — util/websocket.go, web/controller/common.go. The application uses gorilla/websocket (util/websocket.go) for real-time communication. WebSocket implementations commonly suffer from origin validation bypass, message injection, or lack of proper authentication checks on WebSocket connections. Fix: Implement strict origin validation for WebSocket connections, enforce authentication before establishing WebSocket connections, validate and sanitize all incoming WebSocket messages, and use WSS (WebSocket Secure) in production.
  • High · Potential Remote Code Execution via Command Injection — util/command.go, util/linux.go, cmd/. The codebase includes command execution utilities (util/command.go, util/linux.go) that interface with system commands. If user input is passed to these command utilities without proper sanitization, it could lead to command injection attacks. Fix: Never pass unsanitized user input to command execution functions. Use parameterized/escaped command arguments, whitelist allowed commands, and avoid shell interpretation. Use os/exec with explicit argument arrays rather than shell strings.
  • High · Exposed Sensitive Configuration in Web Service — web/controller/trojan.go, web/controller/user.go, web/controller/data.go. The web management interface exposes trojan configuration, TLS certificates, and user credentials through API endpoints. Insufficient access controls or authorization checks could expose sensitive configuration data. Fix: Implement proper role-based access control (RBAC), add authorization checks before returning sensitive data, use HTTPS only, implement rate limiting, and validate all input parameters.
  • Medium · Missing Security Headers in Web Application — web/web.go, web/auth.go. The Gin-based web application (web/web.go) may be missing critical security headers such as Content-Security-Policy, X-Frame-Options, X-Content-Type-Options, and Strict-Transport-Security. Fix: Add security headers middleware to enforce: HSTS, CSP, X-Frame-Options (DENY), X-Content-Type-Options (nosniff), X-XSS-Protection, and Referrer-Policy headers.
  • Medium · Insecure Data Storage without Encryption — core/leveldb.go, core/mysql.go, core/client.go. User credentials and trojan configuration are stored in LevelDB (core/leveldb.go) or MySQL (core/mysql.go) without indication of encryption at rest. Sensitive data like passwords and traffic limits should be encrypted. Fix: Implement encryption for sensitive fields (passwords, tokens) using industry-standard encryption libraries. Use bcrypt or argon2 for password hashing, and encrypt sensitive configuration data at rest.
  • Medium · Potential Cross-Site Scripting (XSS) in Web UI — web/controller/user.go, web/controller/common.go. The web interface generates client configurations and shares trojan:// links and QR codes. If these are not properly HTML-escaped when displayed, stored XSS vulnerabilities could exist, especially in data display and export functionalities. Fix: Ensure all user-

LLM-derived; treat as a starting point, not a security audit.


Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.

Mixed signals · Jrohy/trojan — RepoPilot