mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-07-04 20:04:20 +00:00
41645255f1
* refactor(service): split client.go into focused files
client.go had grown to 4455 lines mixing ~10 responsibilities. Split it
verbatim into cohesive same-package files (no behavior change):
client.go foundation: ClientService, ClientWithAttachments,
ClientCreatePayload, ErrClientNotInInbound, sqlInChunk
client_locks.go inbound mutation locks, delete tombstones, compactOrphans
client_lookup.go read-only lookups (GetByID, List, EffectiveFlow, ...)
client_link.go inbound association sync (SyncInbound, DetachInbound, ...)
client_crud.go single-client CRUD + validation + protocol defaults
client_inbound_apply.go low-level inbound-settings mutators + by-email setters
client_bulk.go bulk attach/detach/adjust/delete/create + DelDepleted
client_traffic.go traffic-reset paths
client_groups.go client group management
client_paging.go paged listing, filtering, sorting, summary
Every declaration moved unchanged (verified: identical func/type/const/var
signature set before vs after). Imports redistributed per file via goimports.
go build ./..., go vet, and go test ./web/service/... all pass.
* refactor(service): split inbound.go into focused files
inbound.go was 4100 lines. Split it verbatim into cohesive same-package
files (no behavior change):
inbound.go core inbound CRUD + InboundService (keeps pkg doc)
inbound_protocol.go protocol / stream capability helpers
inbound_node.go node/runtime/remote coordination + online tracking
inbound_traffic.go traffic accounting, reset, client stats
inbound_client_ips.go per-client IP tracking
inbound_clients.go client lookups within inbounds + copy-clients
inbound_disable.go auto-disable invalid inbounds/clients
inbound_migration.go DB migrations
inbound_sublink.go subscription link providers
inbound_util.go generic slice/string helpers
Identical func/type/const/var signature set before vs after; package doc
comment preserved on inbound.go. Imports redistributed via goimports.
Build, vet, and go test ./web/service/... all pass.
* refactor(service): split tgbot.go into focused files
tgbot.go was 3738 lines dominated by a 1246-line answerCallback. Split it
verbatim into cohesive same-package files (no behavior change):
tgbot.go lifecycle, bot setup, caches, small utils
tgbot_router.go incoming update / command / callback dispatch
tgbot_send.go outbound messaging primitives
tgbot_client.go client views, actions, subscription links
tgbot_inbound.go inbound listing / pickers
tgbot_report.go server usage, exhausted, online, backups, notifications
Identical func/type/const/var signature set before vs after. Imports
redistributed via goimports. Build, vet, and go test ./web/service/... pass.
* refactor(client): dedupe single-field by-email setters
ResetClientIpLimitByEmail, ResetClientExpiryTimeByEmail, and
ResetClientTrafficLimitByEmail shared an identical ~50-line body that
resolves the inbound by email, confirms the client exists, rewrites a
single-client settings payload, and delegates to UpdateInboundClient.
Extract that into applyClientFieldByEmail(inboundSvc, email, mutate) and
reduce each setter to a 3-line wrapper. Behavior is unchanged: same checks
and error strings, same single-client payload contract, same totalGB guard.
SetClientTelegramUserID (resolves by traffic id, different error text) and
ToggleClientEnableByEmail/SetClientEnableByEmail (different return shape and
a pre-read of the old state) intentionally keep their own bodies.
* refactor(service): extract panel/ subpackage
Move the panel-administration leaf services out of the flat service
package into web/service/panel/ (package panel):
user.go UserService (auth / 2FA / LDAP)
panel.go PanelService (restart / self-update) + version helpers
panel_other.go non-unix RestartPanel
panel_unix.go unix RestartPanel
api_token.go ApiTokenService
websocket.go WebSocketService
panel_test.go version/shellQuote unit tests
These are leaves: they depend on core (SettingService, Release) but no
core file references them, so the extraction creates no import cycle.
Core references are now qualified (service.SettingService, service.Release);
callers in main.go, web/web.go, and web/controller/* updated to panel.*.
Build, vet, and go test ./web/... pass.
* refactor(service): extract integration/ subpackage
Move the external-provider integration leaves into web/service/integration/
(package integration):
warp.go WarpService (Cloudflare WARP)
nord.go NordService (NordVPN)
custom_geo.go CustomGeoService (custom geo asset management)
*_test.go custom_geo / panel-proxy tests
These depend on core (SettingService, ServerService, XraySettingService) but
no core file references them. xray_setting.go stays in core because it calls
the unexported SettingService.saveSetting. The shared isBlockedIP SSRF helper
(used by core url_safety.go and by custom_geo) now has a small copy in each
package rather than being exported. Core references qualified; callers in
web/web.go, web/job/*, and web/controller/* updated to integration.*.
Build, vet, and go test ./web/... pass.
* refactor(service): extract tgbot/ subpackage
Move the Telegram bot (6 files + test) into web/service/tgbot/ (package
tgbot). It is a leaf: it embeds five core services (Inbound/Client/Setting/
Server/Xray) and the core never references it, so no import cycle.
To support the package boundary without changing behavior:
- core exposes XrayProcess() *xray.Process so tgbot keeps calling the
exact same running-process methods it used via the package-level `p`;
- three core methods tgbot calls are exported: ClientService.checkIs-
EnabledByEmail -> CheckIsEnabledByEmail, InboundService.getAllEmails ->
GetAllEmails (callers updated in-package);
- tgbot's embedded-field types and the few core type refs (Status,
ClientCreatePayload, SanitizePublicHTTPURL) are now service-qualified.
Callers in main.go, web/web.go, web/job/*, and web/controller/* updated to
tgbot.*. Build, vet, and go test ./web/... pass.
* refactor(service): extract outbound/ subpackage
OutboundService (outbound.go) imports only neutral packages (config,
database, model, xray) and its production code is referenced by no core or
sibling service file — only by web/controller/xray_setting.go and
web/job/xray_traffic_job.go. Move it to web/service/outbound/ (package
outbound); no core qualification needed inside. Callers updated to outbound.*.
The one coupling was a tiny pure test helper, outboundsContainTag, used by
both outbound.go and the core outbound_subscription_test.go; it now has a
small copy in that test file rather than being shared across the boundary.
Build, vet, and go test ./web/... pass.
* refactor(util): move wireguard into its own subpackage
util/wireguard.go was the lone file of the root `util` package (24 lines,
one exported func GenerateWireguardKeypair), while every other util concern
lives in a focused subpackage (util/common, util/crypto, util/netsafe, ...).
Move it to util/wireguard/ (package wireguard) for consistency; its only
importer, web/service/integration/warp.go, is updated. The root `util`
package no longer exists.
* refactor(sub): drop redundant sub prefix from filenames
Inside package sub the subXxx.go prefix just repeats the package name
(like client_*.go did inside service). Rename for consistency; content and
type names are unchanged:
subController.go -> controller.go
subService.go -> service.go
subClashService.go -> clash_service.go
subJsonService.go -> json_service.go
(+ matching _test.go files)
* refactor(controller): rename xui.go -> spa.go
XUIController serves the panel's single-page-app shell; spa.go names that
role plainly (the other controller files are domain-named). File rename only
— the type stays XUIController. api_docs_test.go keys route base paths by
filename, so its "xui.go" case is updated to "spa.go".
* refactor: move backend packages under internal/
Adopt the idiomatic Go application layout: the backend packages now live
under internal/ (a boundary the toolchain enforces), signalling private
implementation instead of a library-style flat root. No runtime behavior
changes — only import paths and a few build/config paths move.
Moved: config, database, logger, mtproto, sub, util, web, xray -> internal/.
main.go stays at the repo root and tools/openapigen stays under tools/ (both
still import internal/* because the internal rule keys off the module root).
The module path github.com/mhsanaei/3x-ui/v3 is unchanged; 149 .go files had
their import prefix rewritten to .../internal/<pkg>.
Couplings the Go compiler can't see, updated to the new layout:
- frontend i18n imports of web/translation (react.ts, setup.components.ts)
- vite outDir + eslint/tsconfig ignore globs -> internal/web/dist
- Dockerfile COPY paths for web/dist and web/translation
- locale.go os.DirFS("web") disk fallback -> "internal/web"
- .gitignore and ci.yml go:embed stub for internal/web/dist
- api_docs_test.go repo-root relative walk (one level deeper)
- tools/openapigen filesystem package paths; ApiTokenView repointed to the
web/service/panel subpackage and codegen regenerated (clears a stale
type the ci.yml codegen check was failing on)
Verified: go build/vet/test (all packages), and frontend typecheck, lint,
vitest (478 tests), and production build into internal/web/dist.
* fix(config): keep test runs from writing logs into the source tree
GetLogFolder() returns a CWD-relative "./log" on Windows. Under `go test`
the working directory is each package's own folder, so InitLogger (called by
tests in web/job, web/service, xray, web/websocket) created stray log/
directories scattered through the source tree (e.g. internal/web/job/log/).
Redirect to a shared temp folder when testing.Testing() reports a test run.
Production behavior is unchanged: Windows still uses ./log next to the binary
and Linux /var/log/x-ui. The log files were always gitignored (*.log) and
never committed; this just stops the noise at the source.
* docs: move subscription-template guide out of root into docs/
sub_templates/ was a top-level folder holding only a README and no actual
templates (3x-ui ships none by design), referenced nowhere and unlinked from
any doc — it read like an empty placeholder cluttering the repo root.
Move the guide to docs/custom-subscription-templates.md (a proper docs home),
reword its intro to read as documentation rather than a folder note, link it
from the Features list in README.md, and drop the empty sub_templates/ folder.
* fix: update stale web/ path references after the internal/ move
The internal/ migration rewrote Go import paths but left some references to
the old top-level layout in docs, comments, and a few runtime disk paths.
Functional (dev-mode only): the disk-serving fallbacks that read the Vite
build from disk when running from source still pointed at web/dist/, which
moved to internal/web/dist/ — so `os.DirFS`/`os.Stat`/`os.ReadFile` in
internal/web/web.go and internal/sub/{sub,controller}.go are corrected.
Production was unaffected (it serves the embedded FS; verified by the Docker
build), but `go run` with a live frontend build silently fell back to embed.
Docs/comments: frontend/README.md, CONTRIBUTING.md, the claude-issue-bot and
release workflows, the openapigen -root help text, and assorted Go comments
now reference internal/web, internal/database, internal/sub, internal/xray,
etc. Package-name mentions (the "web" package), root paths (main.go,
frontend/, install scripts, /etc/x-ui), routes (/panel/api/xray), and the
historical "web/assets no longer exists" note were intentionally left as-is.
* refactor(web): remove the legacy /xui -> /panel redirect middleware
RedirectMiddleware existed only for backward compatibility with the old
`/xui` URL scheme (301-redirecting /xui and /xui/API to /panel and
/panel/api). That cutover was long ago, so drop the middleware, its
registration in initRouter, and the now-inaccurate "URL redirection"
mention in the middleware package doc. Old /xui URLs now 404 like any other
unknown path. HTTPS auto-redirect and auth redirects are unrelated and stay.
* build: fix .dockerignore for internal/ layout and exclude runtime dir
- web/dist -> internal/web/dist: the embedded frontend moved under internal/,
so the stale exclude no longer matched and the locally-built dist could be
sent to the build context (the frontend stage rebuilds it fresh anyway).
- exclude x-ui/: the local runtime directory (SQLite db, geo .dat files, xray
binaries, certs — ~150MB) was being shipped into the build context for no
reason. Verified the pattern excludes only the directory and still keeps
x-ui.sh, which the Dockerfile copies to /usr/bin/x-ui.
812 lines
21 KiB
Go
812 lines
21 KiB
Go
// Package link provides parsers for VPN share links (vmess://, vless://, etc.)
|
|
// and subscription bodies (typically base64-encoded newline lists of such links).
|
|
// The output shape matches the wire format used by the panel's Xray template
|
|
// outbounds array so that parsed objects can be injected directly.
|
|
package link
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/url"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// Outbound is the minimal shape we emit for each parsed link.
|
|
// Extra fields (mux, etc.) are carried inside settings/streamSettings.
|
|
type Outbound map[string]any
|
|
|
|
// ParseResult holds a parsed outbound together with a stable identity string
|
|
// that can be used to correlate the same logical server across refreshes
|
|
// (even if the remark changes).
|
|
type ParseResult struct {
|
|
Outbound Outbound
|
|
Identity string
|
|
}
|
|
|
|
// ParseSubscriptionBody accepts the raw body returned by a subscription URL.
|
|
// It handles the common case where the body is a base64-encoded blob of
|
|
// newline-separated links, and also tolerates an already-decoded text body.
|
|
// It returns the list of successfully parsed outbounds (in order) and their
|
|
// corresponding identities.
|
|
func ParseSubscriptionBody(body []byte) ([]Outbound, []string, error) {
|
|
text := strings.TrimSpace(string(body))
|
|
if text == "" {
|
|
return nil, nil, nil
|
|
}
|
|
|
|
// Try base64 decode first (standard and URL-safe variants).
|
|
if decoded, ok := tryBase64(text); ok {
|
|
text = strings.TrimSpace(decoded)
|
|
}
|
|
|
|
lines := splitLines(text)
|
|
var outbounds []Outbound
|
|
var identities []string
|
|
|
|
for _, ln := range lines {
|
|
ln = strings.TrimSpace(ln)
|
|
if ln == "" || strings.HasPrefix(ln, "#") {
|
|
continue
|
|
}
|
|
res, err := ParseLink(ln)
|
|
if err != nil || res == nil {
|
|
// Ignore unparseable lines (comments, unsupported protocols, etc.)
|
|
continue
|
|
}
|
|
outbounds = append(outbounds, res.Outbound)
|
|
identities = append(identities, res.Identity)
|
|
}
|
|
return outbounds, identities, nil
|
|
}
|
|
|
|
func tryBase64(s string) (string, bool) {
|
|
// Remove whitespace that some providers insert.
|
|
clean := strings.Map(func(r rune) rune {
|
|
if r == ' ' || r == '\n' || r == '\r' || r == '\t' {
|
|
return -1
|
|
}
|
|
return r
|
|
}, s)
|
|
|
|
// Common padding fix
|
|
for len(clean)%4 != 0 {
|
|
clean += "="
|
|
}
|
|
|
|
// Standard
|
|
if b, err := base64.StdEncoding.DecodeString(clean); err == nil {
|
|
return string(b), true
|
|
}
|
|
// URL-safe (no padding)
|
|
if b, err := base64.RawURLEncoding.DecodeString(clean); err == nil {
|
|
return string(b), true
|
|
}
|
|
// URL-safe with padding
|
|
if b, err := base64.URLEncoding.DecodeString(clean); err == nil {
|
|
return string(b), true
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
func splitLines(s string) []string {
|
|
// Accept \n, \r\n, and also some providers use literal \n in the text.
|
|
s = strings.ReplaceAll(s, `\n`, "\n")
|
|
return strings.FieldsFunc(s, func(r rune) bool { return r == '\n' || r == '\r' })
|
|
}
|
|
|
|
// ParseLink parses a single share link and returns the outbound object plus
|
|
// a stable identity for tag correlation. Supported schemes:
|
|
// - vmess://
|
|
// - vless://
|
|
// - trojan://
|
|
// - ss:// (modern and legacy)
|
|
// - hysteria2:// (also hy2://)
|
|
// - wireguard:// (also wg://)
|
|
func ParseLink(link string) (*ParseResult, error) {
|
|
link = strings.TrimSpace(link)
|
|
switch {
|
|
case strings.HasPrefix(link, "vmess://"):
|
|
return parseVmess(link)
|
|
case strings.HasPrefix(link, "vless://"):
|
|
return parseVless(link)
|
|
case strings.HasPrefix(link, "trojan://"):
|
|
return parseTrojan(link)
|
|
case strings.HasPrefix(link, "ss://"):
|
|
return parseShadowsocks(link)
|
|
case strings.HasPrefix(link, "hysteria2://"), strings.HasPrefix(link, "hy2://"):
|
|
return parseHysteria2(link)
|
|
case strings.HasPrefix(link, "wireguard://"), strings.HasPrefix(link, "wg://"):
|
|
return parseWireguard(link)
|
|
default:
|
|
return nil, fmt.Errorf("unsupported link scheme")
|
|
}
|
|
}
|
|
|
|
// --- vmess ---
|
|
|
|
func parseVmess(link string) (*ParseResult, error) {
|
|
b64 := strings.TrimPrefix(link, "vmess://")
|
|
// vmess:// base64(json)
|
|
raw, err := base64.StdEncoding.DecodeString(padBase64(b64))
|
|
if err != nil {
|
|
// Some providers use raw URL-safe
|
|
raw, err = base64.RawURLEncoding.DecodeString(b64)
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("vmess decode: %w", err)
|
|
}
|
|
var j map[string]any
|
|
if err := json.Unmarshal(raw, &j); err != nil {
|
|
return nil, fmt.Errorf("vmess json: %w", err)
|
|
}
|
|
|
|
identity := vmessIdentity(j)
|
|
|
|
network := getString(j, "net", "tcp")
|
|
security := "none"
|
|
if tls, _ := j["tls"].(string); tls == "tls" {
|
|
security = "tls"
|
|
}
|
|
stream := buildStream(network, security)
|
|
|
|
// Map known fields (best effort, matching frontend parser coverage)
|
|
switch network {
|
|
case "ws":
|
|
if host, ok := j["host"].(string); ok {
|
|
setWS(stream, host, getString(j, "path", "/"))
|
|
}
|
|
case "grpc":
|
|
svc := getString(j, "path", "")
|
|
if auth, ok := j["authority"].(string); ok && auth != "" {
|
|
(stream["grpcSettings"].(map[string]any))["authority"] = auth
|
|
}
|
|
(stream["grpcSettings"].(map[string]any))["serviceName"] = svc
|
|
(stream["grpcSettings"].(map[string]any))["multiMode"] = getString(j, "type", "") == "multi"
|
|
case "httpupgrade":
|
|
setHTTPUpgrade(stream, getString(j, "host", ""), getString(j, "path", "/"))
|
|
case "xhttp":
|
|
xh := stream["xhttpSettings"].(map[string]any)
|
|
xh["host"] = getString(j, "host", "")
|
|
xh["path"] = getString(j, "path", "/")
|
|
if m := getString(j, "mode", ""); m != "" {
|
|
xh["mode"] = m
|
|
}
|
|
// xhttp advanced keys are passed through if present in the json
|
|
for _, k := range []string{"xPaddingBytes", "scMaxEachPostBytes", "scMinPostsIntervalMs"} {
|
|
if v, ok := j[k]; ok {
|
|
xh[k] = v
|
|
}
|
|
}
|
|
case "tcp":
|
|
if getString(j, "type", "") == "http" {
|
|
stream["tcpSettings"] = map[string]any{
|
|
"header": map[string]any{
|
|
"type": "http",
|
|
"request": map[string]any{
|
|
"version": "1.1",
|
|
"method": "GET",
|
|
"path": splitComma(getString(j, "path", "/")),
|
|
"headers": map[string]any{"Host": splitComma(getString(j, "host", ""))},
|
|
},
|
|
},
|
|
}
|
|
}
|
|
}
|
|
|
|
if security == "tls" {
|
|
tls := stream["tlsSettings"].(map[string]any)
|
|
tls["serverName"] = getString(j, "sni", "")
|
|
tls["fingerprint"] = getString(j, "fp", "")
|
|
if alpn := getString(j, "alpn", ""); alpn != "" {
|
|
tls["alpn"] = splitComma(alpn)
|
|
}
|
|
}
|
|
|
|
port := num(j["port"])
|
|
ob := Outbound{
|
|
"protocol": "vmess",
|
|
"tag": getString(j, "ps", ""),
|
|
"settings": map[string]any{
|
|
"vnext": []any{
|
|
map[string]any{
|
|
"address": getString(j, "add", ""),
|
|
"port": port,
|
|
"users": []any{
|
|
map[string]any{
|
|
"id": getString(j, "id", ""),
|
|
"security": getString(j, "scy", "auto"),
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
"streamSettings": stream,
|
|
}
|
|
return &ParseResult{Outbound: ob, Identity: identity}, nil
|
|
}
|
|
|
|
func vmessIdentity(j map[string]any) string {
|
|
// Remove ps (remark) for identity
|
|
core := map[string]any{}
|
|
for k, v := range j {
|
|
if k == "ps" {
|
|
continue
|
|
}
|
|
core[k] = v
|
|
}
|
|
b, _ := json.Marshal(core)
|
|
return "vmess:" + string(b)
|
|
}
|
|
|
|
// --- vless / trojan (URL forms) ---
|
|
|
|
func parseVless(link string) (*ParseResult, error) {
|
|
u, err := url.Parse(link)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if u.Scheme != "vless" {
|
|
return nil, fmt.Errorf("not vless")
|
|
}
|
|
id := u.User.Username()
|
|
host := u.Hostname()
|
|
port := defaultPort(u.Port(), 443)
|
|
params := u.Query()
|
|
network := params.Get("type")
|
|
if network == "" {
|
|
network = "tcp"
|
|
}
|
|
security := params.Get("security")
|
|
if security == "" {
|
|
security = "none"
|
|
}
|
|
stream := buildStream(network, security)
|
|
applyTransport(stream, params)
|
|
applySecurity(stream, params)
|
|
applyFinalMask(stream, params)
|
|
|
|
identity := "vless:" + u.Scheme + "://" + id + "@" + host + ":" + strconv.Itoa(port) + "?" + canonicalQuery(params)
|
|
|
|
ob := Outbound{
|
|
"protocol": "vless",
|
|
"tag": decodeHash(u.Fragment),
|
|
"settings": map[string]any{
|
|
"address": host,
|
|
"port": port,
|
|
"id": id,
|
|
"flow": params.Get("flow"),
|
|
"encryption": firstNonEmpty(params.Get("encryption"), "none"),
|
|
},
|
|
"streamSettings": stream,
|
|
}
|
|
return &ParseResult{Outbound: ob, Identity: identity}, nil
|
|
}
|
|
|
|
func parseTrojan(link string) (*ParseResult, error) {
|
|
u, err := url.Parse(link)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if u.Scheme != "trojan" {
|
|
return nil, fmt.Errorf("not trojan")
|
|
}
|
|
pw := u.User.Username()
|
|
host := u.Hostname()
|
|
port := defaultPort(u.Port(), 443)
|
|
params := u.Query()
|
|
network := params.Get("type")
|
|
if network == "" {
|
|
network = "tcp"
|
|
}
|
|
security := params.Get("security")
|
|
if security == "" {
|
|
security = "tls"
|
|
}
|
|
stream := buildStream(network, security)
|
|
applyTransport(stream, params)
|
|
applySecurity(stream, params)
|
|
applyFinalMask(stream, params)
|
|
|
|
identity := "trojan:" + u.Scheme + "://" + pw + "@" + host + ":" + strconv.Itoa(port) + "?" + canonicalQuery(params)
|
|
|
|
ob := Outbound{
|
|
"protocol": "trojan",
|
|
"tag": decodeHash(u.Fragment),
|
|
"settings": map[string]any{
|
|
"servers": []any{
|
|
map[string]any{"address": host, "port": port, "password": pw},
|
|
},
|
|
},
|
|
"streamSettings": stream,
|
|
}
|
|
return &ParseResult{Outbound: ob, Identity: identity}, nil
|
|
}
|
|
|
|
// --- shadowsocks ---
|
|
|
|
func parseShadowsocks(link string) (*ParseResult, error) {
|
|
// Two shapes:
|
|
// ss://base64(method:pass)@host:port#remark
|
|
// ss://base64(method:pass@host:port)#remark
|
|
remark := ""
|
|
if i := strings.Index(link, "#"); i >= 0 {
|
|
remark, _ = url.QueryUnescape(link[i+1:])
|
|
link = link[:i]
|
|
}
|
|
core := strings.TrimPrefix(link, "ss://")
|
|
at := strings.Index(core, "@")
|
|
if at >= 0 {
|
|
// modern
|
|
userB64 := core[:at]
|
|
hp := core[at+1:]
|
|
userInfo, err := base64DecodeFlexible(userB64)
|
|
if err != nil {
|
|
userInfo = userB64 // not b64, rare
|
|
}
|
|
colon := strings.LastIndex(hp, ":")
|
|
if colon < 0 {
|
|
return nil, fmt.Errorf("bad ss host:port")
|
|
}
|
|
host := hp[:colon]
|
|
port, _ := strconv.Atoi(hp[colon+1:])
|
|
method, pass := splitMethodPass(userInfo)
|
|
identity := "ss:" + method + ":" + pass + "@" + host + ":" + strconv.Itoa(port)
|
|
ob := Outbound{
|
|
"protocol": "shadowsocks",
|
|
"tag": remark,
|
|
"settings": map[string]any{
|
|
"servers": []any{
|
|
map[string]any{"address": host, "port": port, "password": pass, "method": method},
|
|
},
|
|
},
|
|
}
|
|
return &ParseResult{Outbound: ob, Identity: identity}, nil
|
|
}
|
|
// legacy: whole thing b64
|
|
dec, err := base64DecodeFlexible(core)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
at = strings.Index(dec, "@")
|
|
if at < 0 {
|
|
return nil, fmt.Errorf("bad legacy ss")
|
|
}
|
|
userInfo := dec[:at]
|
|
hp := dec[at+1:]
|
|
colon := strings.LastIndex(hp, ":")
|
|
if colon < 0 {
|
|
return nil, fmt.Errorf("bad legacy ss hp")
|
|
}
|
|
host := hp[:colon]
|
|
port, _ := strconv.Atoi(hp[colon+1:])
|
|
method, pass := splitMethodPass(userInfo)
|
|
identity := "ss:" + method + ":" + pass + "@" + host + ":" + strconv.Itoa(port)
|
|
ob := Outbound{
|
|
"protocol": "shadowsocks",
|
|
"tag": remark,
|
|
"settings": map[string]any{
|
|
"servers": []any{
|
|
map[string]any{"address": host, "port": port, "password": pass, "method": method},
|
|
},
|
|
},
|
|
}
|
|
return &ParseResult{Outbound: ob, Identity: identity}, nil
|
|
}
|
|
|
|
func splitMethodPass(userInfo string) (string, string) {
|
|
colon := strings.Index(userInfo, ":")
|
|
if colon < 0 {
|
|
return "2022-blake3-aes-128-gcm", userInfo // guess
|
|
}
|
|
return userInfo[:colon], userInfo[colon+1:]
|
|
}
|
|
|
|
// --- hysteria2 ---
|
|
|
|
func parseHysteria2(link string) (*ParseResult, error) {
|
|
u, err := url.Parse(link)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if u.Scheme != "hysteria2" && u.Scheme != "hy2" {
|
|
return nil, fmt.Errorf("not hysteria2")
|
|
}
|
|
auth := u.User.Username()
|
|
host := u.Hostname()
|
|
port := defaultPort(u.Port(), 443)
|
|
params := u.Query()
|
|
|
|
stream := map[string]any{
|
|
"network": "hysteria",
|
|
"security": "tls",
|
|
"hysteriaSettings": map[string]any{
|
|
"version": 2,
|
|
"auth": auth,
|
|
"udpIdleTimeout": 60,
|
|
},
|
|
"tlsSettings": map[string]any{
|
|
"serverName": params.Get("sni"),
|
|
"alpn": splitCommaOrDefault(params.Get("alpn"), []string{"h3"}),
|
|
"fingerprint": params.Get("fp"),
|
|
"echConfigList": params.Get("ech"),
|
|
"verifyPeerCertByName": "",
|
|
"pinnedPeerCertSha256": params.Get("pinSHA256"),
|
|
},
|
|
}
|
|
applyFinalMask(stream, params)
|
|
|
|
identity := "hysteria2:" + auth + "@" + host + ":" + strconv.Itoa(port) + "?" + canonicalQuery(params)
|
|
|
|
ob := Outbound{
|
|
"protocol": "hysteria",
|
|
"tag": decodeHash(u.Fragment),
|
|
"settings": map[string]any{"address": host, "port": port, "version": 2},
|
|
"streamSettings": stream,
|
|
}
|
|
return &ParseResult{Outbound: ob, Identity: identity}, nil
|
|
}
|
|
|
|
// --- wireguard ---
|
|
|
|
func parseWireguard(link string) (*ParseResult, error) {
|
|
u, err := url.Parse(link)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if u.Scheme != "wireguard" && u.Scheme != "wg" {
|
|
return nil, fmt.Errorf("not wireguard")
|
|
}
|
|
secret, _ := url.QueryUnescape(u.User.Username())
|
|
params := u.Query()
|
|
host := u.Hostname()
|
|
portStr := u.Port()
|
|
endpoint := host
|
|
if portStr != "" {
|
|
endpoint = host + ":" + portStr
|
|
}
|
|
|
|
addrRaw := firstParam(params, "address", "ip")
|
|
allowedRaw := firstParam(params, "allowedips", "allowed_ips")
|
|
addrs := splitComma(addrRaw)
|
|
if len(addrs) == 0 {
|
|
addrs = []string{"0.0.0.0/0", "::/0"}
|
|
}
|
|
allowed := splitComma(allowedRaw)
|
|
if len(allowed) == 0 {
|
|
allowed = []string{"0.0.0.0/0", "::/0"}
|
|
}
|
|
|
|
peer := map[string]any{
|
|
"publicKey": firstParam(params, "publickey", "publicKey", "public_key", "peerPublicKey"),
|
|
"endpoint": endpoint,
|
|
"allowedIPs": allowed,
|
|
}
|
|
if psk := firstParam(params, "presharedkey", "preshared_key", "pre-shared-key", "psk"); psk != "" {
|
|
peer["preSharedKey"] = psk
|
|
}
|
|
if ka := firstParam(params, "keepalive", "persistentkeepalive", "persistent_keepalive"); ka != "" {
|
|
if n, err := strconv.Atoi(ka); err == nil {
|
|
peer["keepAlive"] = n
|
|
}
|
|
}
|
|
|
|
settings := map[string]any{
|
|
"secretKey": secret,
|
|
"address": addrs,
|
|
"peers": []any{peer},
|
|
}
|
|
if mtu := params.Get("mtu"); mtu != "" {
|
|
if n, err := strconv.Atoi(mtu); err == nil {
|
|
settings["mtu"] = n
|
|
}
|
|
}
|
|
if res := params.Get("reserved"); res != "" {
|
|
parts := splitComma(res)
|
|
var iv []int
|
|
for _, p := range parts {
|
|
if n, err := strconv.Atoi(strings.TrimSpace(p)); err == nil {
|
|
iv = append(iv, n)
|
|
}
|
|
}
|
|
if len(iv) > 0 {
|
|
settings["reserved"] = iv
|
|
}
|
|
}
|
|
|
|
identity := "wireguard:" + secret + "@" + endpoint + "?" + canonicalQuery(params)
|
|
|
|
ob := Outbound{
|
|
"protocol": "wireguard",
|
|
"tag": decodeHash(u.Fragment),
|
|
"settings": settings,
|
|
}
|
|
return &ParseResult{Outbound: ob, Identity: identity}, nil
|
|
}
|
|
|
|
// --- helpers ---
|
|
|
|
func buildStream(network, security string) map[string]any {
|
|
stream := map[string]any{"network": network, "security": security}
|
|
switch network {
|
|
case "tcp":
|
|
stream["tcpSettings"] = map[string]any{"header": map[string]any{"type": "none"}}
|
|
case "kcp":
|
|
stream["kcpSettings"] = map[string]any{
|
|
"mtu": 1350, "tti": 20, "uplinkCapacity": 5, "downlinkCapacity": 20,
|
|
"cwndMultiplier": 1, "maxSendingWindow": 2097152,
|
|
}
|
|
case "ws":
|
|
stream["wsSettings"] = map[string]any{"path": "/", "host": "", "headers": map[string]any{}, "heartbeatPeriod": 0}
|
|
case "grpc":
|
|
stream["grpcSettings"] = map[string]any{"serviceName": "", "authority": "", "multiMode": false}
|
|
case "httpupgrade":
|
|
stream["httpupgradeSettings"] = map[string]any{"path": "/", "host": "", "headers": map[string]any{}}
|
|
case "xhttp":
|
|
stream["xhttpSettings"] = map[string]any{
|
|
"path": "/", "host": "", "mode": "auto", "headers": map[string]any{},
|
|
"xPaddingBytes": "100-1000", "scMaxEachPostBytes": "1000000",
|
|
}
|
|
default:
|
|
stream["tcpSettings"] = map[string]any{"header": map[string]any{"type": "none"}}
|
|
}
|
|
switch security {
|
|
case "tls":
|
|
stream["tlsSettings"] = map[string]any{
|
|
"serverName": "", "alpn": []any{}, "fingerprint": "",
|
|
"echConfigList": "", "verifyPeerCertByName": "", "pinnedPeerCertSha256": "",
|
|
}
|
|
case "reality":
|
|
stream["realitySettings"] = map[string]any{
|
|
"publicKey": "", "fingerprint": "chrome", "serverName": "",
|
|
"shortId": "", "spiderX": "", "mldsa65Verify": "",
|
|
}
|
|
}
|
|
return stream
|
|
}
|
|
|
|
func setWS(stream map[string]any, host, path string) {
|
|
ws := stream["wsSettings"].(map[string]any)
|
|
ws["host"] = host
|
|
ws["path"] = path
|
|
}
|
|
|
|
func setHTTPUpgrade(stream map[string]any, host, path string) {
|
|
h := stream["httpupgradeSettings"].(map[string]any)
|
|
h["host"] = host
|
|
h["path"] = path
|
|
}
|
|
|
|
func applyTransport(stream map[string]any, p url.Values) {
|
|
net := stream["network"].(string)
|
|
host := p.Get("host")
|
|
path := firstNonEmpty(p.Get("path"), "/")
|
|
switch net {
|
|
case "ws":
|
|
setWS(stream, host, path)
|
|
case "grpc":
|
|
gs := stream["grpcSettings"].(map[string]any)
|
|
gs["serviceName"] = firstNonEmpty(p.Get("serviceName"), p.Get("path"))
|
|
gs["authority"] = p.Get("authority")
|
|
gs["multiMode"] = p.Get("mode") == "multi"
|
|
case "httpupgrade":
|
|
setHTTPUpgrade(stream, host, path)
|
|
case "xhttp":
|
|
xh := stream["xhttpSettings"].(map[string]any)
|
|
xh["host"] = host
|
|
xh["path"] = path
|
|
if m := p.Get("mode"); m != "" {
|
|
xh["mode"] = m
|
|
}
|
|
// A few advanced xhttp fields that are commonly carried
|
|
for _, k := range []string{"xPaddingBytes", "scMaxEachPostBytes", "scMinPostsIntervalMs", "uplinkChunkSize"} {
|
|
if v := p.Get(k); v != "" {
|
|
xh[k] = v
|
|
}
|
|
}
|
|
case "tcp":
|
|
if p.Get("headerType") == "http" || p.Get("type") == "http" {
|
|
stream["tcpSettings"] = map[string]any{
|
|
"header": map[string]any{
|
|
"type": "http",
|
|
"request": map[string]any{
|
|
"version": "1.1",
|
|
"method": "GET",
|
|
"path": splitComma(path),
|
|
"headers": map[string]any{"Host": splitComma(host)},
|
|
},
|
|
},
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func applySecurity(stream map[string]any, p url.Values) {
|
|
sec := stream["security"].(string)
|
|
switch sec {
|
|
case "tls":
|
|
tls := stream["tlsSettings"].(map[string]any)
|
|
tls["serverName"] = p.Get("sni")
|
|
tls["fingerprint"] = p.Get("fp")
|
|
if alpn := p.Get("alpn"); alpn != "" {
|
|
tls["alpn"] = splitComma(alpn)
|
|
}
|
|
tls["echConfigList"] = p.Get("ech")
|
|
tls["pinnedPeerCertSha256"] = p.Get("pcs")
|
|
case "reality":
|
|
re := stream["realitySettings"].(map[string]any)
|
|
re["serverName"] = p.Get("sni")
|
|
re["fingerprint"] = firstNonEmpty(p.Get("fp"), "chrome")
|
|
re["publicKey"] = p.Get("pbk")
|
|
re["shortId"] = p.Get("sid")
|
|
re["spiderX"] = p.Get("spx")
|
|
re["mldsa65Verify"] = p.Get("pqv")
|
|
}
|
|
}
|
|
|
|
func applyFinalMask(stream map[string]any, p url.Values) {
|
|
if fm := p.Get("fm"); fm != "" {
|
|
var parsed any
|
|
if json.Unmarshal([]byte(fm), &parsed) == nil {
|
|
stream["finalmask"] = parsed
|
|
}
|
|
}
|
|
}
|
|
|
|
func firstNonEmpty(a, b string) string {
|
|
if a != "" {
|
|
return a
|
|
}
|
|
return b
|
|
}
|
|
|
|
func firstParam(p url.Values, keys ...string) string {
|
|
for _, k := range keys {
|
|
if v := p.Get(k); v != "" {
|
|
return v
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func canonicalQuery(p url.Values) string {
|
|
// Sort keys for stable identity
|
|
keys := make([]string, 0, len(p))
|
|
for k := range p {
|
|
keys = append(keys, k)
|
|
}
|
|
// simple sort
|
|
for i := 0; i < len(keys); i++ {
|
|
for j := i + 1; j < len(keys); j++ {
|
|
if keys[j] < keys[i] {
|
|
keys[i], keys[j] = keys[j], keys[i]
|
|
}
|
|
}
|
|
}
|
|
parts := make([]string, 0, len(keys))
|
|
for _, k := range keys {
|
|
for _, v := range p[k] {
|
|
parts = append(parts, k+"="+v)
|
|
}
|
|
}
|
|
return strings.Join(parts, "&")
|
|
}
|
|
|
|
func decodeHash(h string) string {
|
|
if h == "" {
|
|
return ""
|
|
}
|
|
if dec, err := url.QueryUnescape(h); err == nil {
|
|
return dec
|
|
}
|
|
return h
|
|
}
|
|
|
|
func defaultPort(p string, def int) int {
|
|
if p == "" {
|
|
return def
|
|
}
|
|
n, err := strconv.Atoi(p)
|
|
if err != nil || n <= 0 {
|
|
return def
|
|
}
|
|
return n
|
|
}
|
|
|
|
func num(v any) int {
|
|
switch x := v.(type) {
|
|
case float64:
|
|
return int(x)
|
|
case int:
|
|
return x
|
|
case int64:
|
|
return int(x)
|
|
case string:
|
|
n, _ := strconv.Atoi(x)
|
|
return n
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func getString(m map[string]any, key, def string) string {
|
|
if v, ok := m[key]; ok {
|
|
if s, ok := v.(string); ok {
|
|
return s
|
|
}
|
|
}
|
|
return def
|
|
}
|
|
|
|
func splitComma(s string) []string {
|
|
if s == "" {
|
|
return nil
|
|
}
|
|
parts := strings.Split(s, ",")
|
|
out := make([]string, 0, len(parts))
|
|
for _, p := range parts {
|
|
p = strings.TrimSpace(p)
|
|
if p != "" {
|
|
out = append(out, p)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func splitCommaOrDefault(s string, def []string) []string {
|
|
if s == "" {
|
|
return def
|
|
}
|
|
return splitComma(s)
|
|
}
|
|
|
|
func padBase64(s string) string {
|
|
for len(s)%4 != 0 {
|
|
s += "="
|
|
}
|
|
return s
|
|
}
|
|
|
|
func base64DecodeFlexible(s string) (string, error) {
|
|
s = padBase64(s)
|
|
if b, err := base64.StdEncoding.DecodeString(s); err == nil {
|
|
return string(b), nil
|
|
}
|
|
if b, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(s, "=")); err == nil {
|
|
return string(b), nil
|
|
}
|
|
return "", fmt.Errorf("base64 decode failed")
|
|
}
|
|
|
|
// SlugRemark turns a free-form remark into a conservative DNS-ish tag segment.
|
|
var slugRe = regexp.MustCompile(`[^a-z0-9]+`)
|
|
|
|
func SlugRemark(remark string) string {
|
|
s := strings.ToLower(strings.TrimSpace(remark))
|
|
s = slugRe.ReplaceAllString(s, "-")
|
|
s = strings.Trim(s, "-")
|
|
if s == "" {
|
|
return ""
|
|
}
|
|
// collapse runs of dashes
|
|
for strings.Contains(s, "--") {
|
|
s = strings.ReplaceAll(s, "--", "-")
|
|
}
|
|
return s
|
|
}
|
|
|
|
// SuggestTag builds a tag from a prefix and a remark (or index fallback).
|
|
// It is intended for initial assignment; stability is handled by the service layer.
|
|
func SuggestTag(prefix, remark string, idx int) string {
|
|
base := SlugRemark(remark)
|
|
if base == "" {
|
|
base = fmt.Sprintf("%d", idx)
|
|
}
|
|
p := strings.TrimSuffix(prefix, "-")
|
|
if p != "" {
|
|
return p + "-" + base
|
|
}
|
|
return base
|
|
}
|