Wei-Shaw/sub2api
Sub2API-CRS2 一站式开源中转服务,让 Claude、Openai 、Gemini、Antigravity订阅统一接入,支持拼车共享,更高效分摊成本,原生工具无缝使用。
Mixed signals — read the receipts
worst of 4 axescopyleft license (LGPL-3.0) — review compatibility; no tests detected
Has a license, tests, and CI — clean foundation to fork and modify.
Documented and popular — useful reference codebase to read through.
No critical CVEs, sane security posture — runnable as-is.
- ✓Last commit today
- ✓16 active contributors
- ✓LGPL-3.0 licensed
Show 4 more →Show less
- ✓CI configured
- ⚠Concentrated ownership — top contributor handles 56% of recent commits
- ⚠LGPL-3.0 is copyleft — check downstream compatibility
- ⚠No test directory detected
What would change the summary?
- →Use as dependency Concerns → Mixed 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.
[](https://repopilot.app/r/wei-shaw/sub2api)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/wei-shaw/sub2api on X, Slack, or LinkedIn.
Onboarding doc
Onboarding: Wei-Shaw/sub2api
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:
- 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. - 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.
- Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/Wei-Shaw/sub2api 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 — Mixed signals — read the receipts
- Last commit today
- 16 active contributors
- LGPL-3.0 licensed
- CI configured
- ⚠ Concentrated ownership — top contributor handles 56% of recent commits
- ⚠ LGPL-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 Wei-Shaw/sub2api
repo on your machine still matches what RepoPilot saw. If any fail,
the artifact is stale — regenerate it at
repopilot.app/r/Wei-Shaw/sub2api.
What it runs against: a local clone of Wei-Shaw/sub2api — 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 Wei-Shaw/sub2api | Confirms the artifact applies here, not a fork |
| 2 | License is still LGPL-3.0 | Catches relicense before you depend on it |
| 3 | Default branch main exists | Catches branch renames |
| 4 | Last commit ≤ 30 days ago | Catches sudden abandonment since generation |
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of Wei-Shaw/sub2api. If you don't
# have one yet, run these first:
#
# git clone https://github.com/Wei-Shaw/sub2api.git
# cd sub2api
#
# 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 Wei-Shaw/sub2api and re-run."
exit 2
fi
# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "Wei-Shaw/sub2api(\\.git)?\\b" \\
&& ok "origin remote is Wei-Shaw/sub2api" \\
|| miss "origin remote is not Wei-Shaw/sub2api (artifact may be from a fork)"
# 2. License matches what RepoPilot saw
(grep -qiE "^(LGPL-3\\.0)" LICENSE 2>/dev/null \\
|| grep -qiE "\"license\"\\s*:\\s*\"LGPL-3\\.0\"" package.json 2>/dev/null) \\
&& ok "license is LGPL-3.0" \\
|| miss "license drift — was LGPL-3.0 at generation time"
# 3. Default branch
git rev-parse --verify main >/dev/null 2>&1 \\
&& ok "default branch main exists" \\
|| miss "default branch main no longer exists"
# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 30 ]; then
ok "last commit was $days_since_last days ago (artifact saw ~0d)"
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/Wei-Shaw/sub2api"
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).
⚡TL;DR
Sub2API is an AI API gateway and quota distribution platform that lets users share Claude, OpenAI, Gemini, and other AI service subscriptions through unified API keys. Built in Go with PostgreSQL and Redis, it handles multi-account authentication, token-level billing, intelligent load balancing, and built-in payment processing (Stripe, Alipay, WeChat Pay, EasyPay) so users can self-serve top-ups without a separate payment service. Monorepo split into backend/ (Go server, ent ORM schemas in backend/ent/) and frontend (Vue 3 + TypeScript dashboard in separate frontend/ directory). backend/cmd/server/ contains the HTTP gateway entry point; backend/ent/ auto-generated database models from entity definitions. Wire dependency injection used for bootstrap (wire_gen.go).
👥Who it's for
Platform operators and SaaS teams who want to resell AI API access with granular per-user quota limits and billing; Claude/OpenAI/Gemini subscribers looking to share costs via pooled accounts; developers building on top of the gateway who need OAuth/API key management at scale.
🌱Maturity & risk
Actively maintained and production-ready. Multiple language READMEs (CN, JA), CI/CD pipelines (backend-ci, security-scan, release), CLA enforcement, and structured Dockerfile releases indicate serious project maturity. Go 1.26 with modern ent ORM and testcontainers integration suggest well-tested infrastructure code.
Relatively low risk for core functionality—pinned Go versions, comprehensive dependency lock (go.mod has 40+ direct deps), and CI/CD coverage visible. Main risks: single organization (Wei-Shaw) maintains it, payment integration complexity (4 providers = more surface area), and the fact that it sits in the critical path between users and expensive upstream APIs means a bug could leak quotas or cause billing disputes.
Active areas of work
Active development indicated by recent Go 1.26 support, testcontainers integration for integration tests, and security scan workflows. The .goreleaser configs and Dockerfile.goreleaser suggest ongoing release automation. Payment system appears actively expanded (4 payment provider integrations present).
🚀Get running
git clone https://github.com/Wei-Shaw/sub2api.git && cd backend && go mod download && make build (uses Makefile in backend/). For frontend: cd to frontend directory and npm install && npm run dev. See DEV_GUIDE.md for full setup with PostgreSQL 15+ and Redis 7+.
Daily commands: Backend server: cd backend && make run (runs cmd/server/main.go via wire injection). Frontend dev: cd frontend && npm run dev (Vue dev server on port 5173, typically). Production: docker build -t sub2api . && docker run with env vars for DB_URL, REDIS_URL, JWT_SECRET. See Dockerfile and backend/.dockerignore for container details.
🗺️Map of the codebase
- backend/cmd/server/main.go: Entry point for the API gateway; initializes Gin router, wire dependencies, and HTTP server startup
- backend/ent/schema/: ent schema definitions (Account, AccountGroup, etc.); defines database models and relationships
- backend/cmd/server/wire.go: Dependency injection wiring configuration; declares how all services are constructed and composed
- Makefile: Build automation; defines targets like build, test, lint, docker that are essential for CI/CD
- .github/workflows/backend-ci.yml: CI pipeline; runs tests, linting, security scans on every commit to ensure code quality
- backend/.golangci.yml: Go linter config; enforces code style and catches bugs at pre-commit time
- DEV_GUIDE.md: Onboarding documentation; describes local setup, database migration, and development workflow
🛠️How to make changes
API routes: backend/cmd/server/main.go or handlers in backend/internal/ (infer from wire_gen.go imports). Database schema: edit backend/ent/schema/*.go files, then run ent code generation (entgo.io/ent/cmd/ent generate ./...). Frontend UI: Vue components in frontend/src/components. Payment logic: backend/internal/payment/ or service layer. Add tests alongside using testcontainers (see backend/cmd/server/wire_gen_test.go pattern).
🪤Traps & gotchas
Go 1.26+ is required (check backend/go.mod)—older versions will fail. PostgreSQL 15+ and Redis 7+ versions are hardcoded in dependencies; using older versions may cause compatibility issues. JWT secret generation via cmd/jwtgen/main.go required before server startup (see DEV_GUIDE). Ent code generation must be run manually after schema changes (entgo.io/ent install and run generate). Payment provider API keys (Stripe, Alipay, WeChat Pay) must be set as environment variables; missing keys will silently disable that payment method. Wire dependency injection requires running 'go generate ./...' in backend/cmd/server if you add new providers.
💡Concepts to learn
- Token bucket rate limiting — Sub2API uses token buckets (visible from rate-limiting dependencies and billing logic) to enforce per-user and per-account request/token quotas without burst penalties—core to fair-use SaaS billing.
- Sticky session load balancing — The README mentions 'sticky sessions' for account selection; this ensures a user's requests stay routed to the same upstream account to preserve conversation state in Claude/ChatGPT APIs.
- Dependency injection with code generation — Sub2API uses google/wire to auto-generate wire_gen.go from wire.go; understanding how DI reduces boilerplate and enables testability is essential for extending the service graph.
- Entity-driven ORM code generation — Schemas in backend/ent/schema/*.go are auto-compiled to CRUD code by ent; understanding the ent contract (hooks, mixins, edges) is necessary to modify the data model.
- Precision decimal arithmetic for billing — Sub2API uses shopspring/decimal instead of float64 for token costs and user balances; floating-point rounding errors can cause monetary disputes at scale.
- OAuth multi-provider account federation — The codebase supports 'OAuth, API Key' account types for upstream services; integrating a new provider (e.g., Anthropic direct API) requires understanding how account credentials are encrypted and rotated.
- WebSocket proxying with concurrent rate limits — Sub2API proxies WebSocket streams (visible from coder/websocket and gorilla/websocket dependencies) for streaming Claude responses while enforcing per-user concurrency caps—complex because TCP state is persistent.
🔗Related repos
openai/openai-forward— Similar API gateway for OpenAI with quota management; different architecture (Python-based) but solves the same problem of request routing and billing.buxuku/openai-sb— Another Go-based OpenAI gateway with load balancing; smaller scope but shares the same core challenge of multi-account failover.cloudwego/hertz— High-performance Go HTTP framework (lighter than Gin); Sub2API could migrate to this for lower latency on gateway operations if needed.ent/ent— The official ent repository; Sub2API depends on ent for code-gen ORM, so understanding ent internals is crucial for schema changes.google/wire— Official Google dependency injection tool; Sub2API uses wire for provider composition, so understanding wire's code generation is essential for adding new services.
🪄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 integration tests for backend wire dependency injection setup
The repo uses Google Wire for dependency injection (backend/cmd/server/wire.go exists), but wire_gen_test.go is present with likely incomplete coverage. The complex initialization chain involving PostgreSQL, Redis, JWT, payment processors (Stripe, WeChat Pay, Alipay), and S3 clients needs integration tests to catch circular dependency issues and initialization failures early. This is critical for a multi-tenant API gateway.
- [ ] Expand backend/cmd/server/wire_gen_test.go with container-based tests using testcontainers (PostgreSQL and Redis modules already in go.mod)
- [ ] Add test cases for each major payment processor initialization path (Stripe, WeChat Pay, Alipay from dependencies)
- [ ] Add tests verifying AWS S3 client configuration with different credential scenarios
- [ ] Test JWT token generation service initialization using backend/cmd/jwtgen
- [ ] Verify all database entity relationships (Account, AccountGroup, Announcement, etc.) initialize correctly
Add unit tests for backend ent schema and query builders
The ent ORM schema files exist (backend/ent/account.go, backend/ent/accountgroup.go, etc.) with corresponding query and update builders, but there's no visible test coverage for these auto-generated files. With complex domain models (accounts, groups, announcements, reading tracking), schema mutations and query filtering need validation to prevent silent data corruption.
- [ ] Create backend/ent/{entity}_test.go files for Account, AccountGroup, Announcement, AnnouncementRead entities
- [ ] Add tests for update builders using DATA-DOG/go-sqlmock (already in go.mod) to mock database interactions
- [ ] Test query filters (Where conditions in backend/ent/{entity}/where.go) with edge cases
- [ ] Add tests for cascade behavior when deleting parent entities (e.g., deleting an Account and related AccountGroups)
- [ ] Verify JSON marshaling/unmarshaling for API responses using real entity instances
Add end-to-end API tests for payment webhook handlers and subscription lifecycle
The repo integrates three payment processors (Stripe, WeChat Pay, Alipay) but backend test coverage for webhook validation, idempotency, and subscription state transitions is likely missing. Webhooks are critical for financial accuracy and need isolated test coverage separate from integration tests.
- [ ] Create backend/test/webhooks directory with test fixtures for each payment processor
- [ ] Add tests validating webhook signature verification for Stripe (stripe-go/v85), WeChat Pay (wechatpay-go), and Alipay (smartwalle/alipay/v3) using actual SDK methods
- [ ] Test idempotent webhook processing (same webhook received twice should not double-charge or double-credit)
- [ ] Add tests for subscription state transitions: pending → active → expired → renewed with concurrent webhook scenarios
- [ ] Test error handling when webhook processing fails (database unavailable, invalid state transition) to ensure eventual consistency
🌿Good first issues
- Add integration test suite for the payment layer (backend/internal/payment/*) using testcontainers pattern shown in wire_gen_test.go—currently only unit test stubs exist, so write E2E tests against mock Stripe/Alipay APIs.
- Document the ent schema relationship diagram (e.g. Account → AccountGroup → User) in a diagram file (docs/SCHEMA.md) by parsing backend/ent/schema/*.go files and rendering as Mermaid ER diagram; this will unblock contributors trying to understand data flow.
- Add missing rate-limit configuration tests to backend/internal/ratelimit/ (infer from imports in wire_gen.go); currently the package exists but test coverage is sparse, so write unit tests for token bucket and per-user concurrency limits.
⭐Top contributors
Click to expand
Top contributors
- @Wei-Shaw — 56 commits
- @lyen1688 — 11 commits
- @github-actions[bot] — 6 commits
- @alfadb — 6 commits
- @Jlypx — 3 commits
📝Recent commits
Click to expand
Recent commits
dbc8ae6— chore: update sponsors (Wei-Shaw)33db04f— chore: 修复 CI 安全与 lint 检查 (Wei-Shaw)fda1ed4— feat: 优化 OAuth 账号导入流程 (Wei-Shaw)a466e80— chore: sync VERSION to 0.1.125 [skip ci] (github-actions[bot])8a835b2— ci: fix lint and test failures (Wei-Shaw)57fd799— fix(gateway): stop default redact thinking beta injection (Wei-Shaw)e872cbe— feat: 添加登录注册条款确认 (Wei-Shaw)6681aee— 更新账号模型白名单 (Wei-Shaw)0eca600— fix moderation key handling and key UI (Wei-Shaw)f3577bc— chore: sync VERSION to 0.1.124 [skip ci] (github-actions[bot])
🔒Security observations
- High · Outdated Go Version in Dockerfile —
Dockerfile (ARG GOLANG_IMAGE=golang:1.26.3-alpine). The Dockerfile specifies golang:1.26.3-alpine, but Go 1.26.3 does not exist as a stable release. The latest stable Go version is 1.23.x. This indicates either a typo or use of an unreleased/unstable version, which may contain unpatched security vulnerabilities. Fix: Update to a stable Go version (e.g., golang:1.23-alpine or latest stable). Verify the Go version matches the go.mod file (currently shows 'go 1.26.3' which is also invalid). - High · Mismatched Go Version in go.mod —
go.mod (go 1.26.3). The go.mod file specifies 'go 1.26.3', which is not a valid released Go version. This creates confusion, build reproducibility issues, and may cause dependencies to fail validation. Fix: Update to a valid Go version (e.g., 'go 1.23'). Ensure consistency between go.mod, Dockerfile, and README badge versions. - High · Incomplete Dependency Declaration —
go.mod (require section cut off). The go.mod file is truncated at 'github.com/agext/levenshtein' with no closing. This indicates incomplete or corrupted dependency file, which could hide security-critical dependencies or cause build failures. Fix: Provide the complete go.mod file. Run 'go mod tidy' to regenerate and verify all dependencies. Review the go.sum file for integrity. - Medium · Weak Cryptography Library - golang.org/x/crypto —
go.mod (golang.org/x/crypto v0.50.0). The version golang.org/x/crypto v0.50.0 is used without context on whether all cryptographic primitives are using secure algorithms. Legacy or weaker crypto functions could be exposed. Fix: Audit code for use of DES, MD5, or SHA1. Ensure only modern algorithms (AES-256, SHA-256+, bcrypt, scrypt) are used for sensitive operations like password hashing and data encryption. - Medium · JWT Secret Management Not Visible —
backend/cmd/jwtgen/main.go, backend/cmd/server/main.go. The codebase includes JWT functionality (github.com/golang-jwt/jwt/v5 and jwtgen command), but no secure secret management pattern is visible. Secrets may be hardcoded or stored insecurely. Fix: Implement secure JWT secret management using environment variables, HashiCorp Vault, or cloud KMS. Never commit secrets to version control. Rotate secrets regularly. - Medium · WebSocket Implementation with Multiple Libraries —
go.mod dependencies. The codebase uses both github.com/coder/websocket (v1.8.14) and github.com/gorilla/websocket (v1.5.3). Dual implementations increase attack surface and may lead to inconsistent security handling. Fix: Consolidate to a single WebSocket library. Audit both implementations for CSRF protection, input validation, and proper error handling. Ensure WebSocket servers validate origins. - Medium · Redis/Database Credentials in Configuration —
backend/cmd/server/main.go (config initialization via wire.go). The codebase uses Redis and PostgreSQL but no visible secure credential management is evident. Configuration likely uses environment variables or config files that may be exposed. Fix: Use environment variables with.envin .gitignore. Implement secret rotation. Use cloud provider credential managers (AWS Secrets Manager, Google Secret Manager). Never log credentials. - Medium · Third-Party Payment Integrations - Stripe and Alipay —
go.mod (stripe-go/v85, alipay/v3). The codebase integrates Stripe (v85.0.0) and Alipay (v3.2.29) payment processors. API keys and webhook secrets may be exposed in configuration or logs. Fix: Store payment API keys in secure vaults. Validate all webhook signatures. Implement rate limiting on payment endpoints
LLM-derived; treat as a starting point, not a security audit.
👉Where to read next
- Open issues — current backlog
- Recent PRs — what's actively shipping
- Source on GitHub
Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.