1
0
mirror of https://github.com/bestnite/sub2clash.git synced 2025-11-03 20:30:35 +00:00

6 Commits

32 changed files with 325 additions and 211 deletions

View File

@@ -45,7 +45,7 @@ jobs:
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v5
uses: docker/build-push-action@v6
with:
build-args: |
"version=${{ github.ref_name }}"
@@ -53,3 +53,5 @@ jobs:
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
platforms: linux/amd64,linux/arm64,linux/arm/v7
file: Containerfile

View File

@@ -13,13 +13,18 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Set up Go
uses: actions/setup-go@v4
uses: actions/setup-go@v5
- name: Install UPX
uses: crazy-max/ghaction-upx@v3
with:
install-only: true
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v5
uses: goreleaser/goreleaser-action@v6
with:
distribution: goreleaser
version: latest

View File

@@ -1,3 +1,4 @@
version: 2
project_name: sub2clash
builds:
- env:
@@ -9,19 +10,15 @@ builds:
goarch:
- amd64
- arm64
- arm
- "386"
goarm:
- "6"
- "7"
ldflags:
- -s -w -X sub2clash/constant.Version={{ .Version }}
- -s -w -X github.com/bestnite/sub2clash/constant.Version={{ .Version }}
flags:
- -trimpath
archives:
- format: tar.gz
- formats: ["tar.gz"]
format_overrides:
- format: zip
- formats: ["zip"]
goos: windows
wrap_in_directory: true
files:
@@ -30,3 +27,19 @@ archives:
- templates
release:
draft: true
upx:
- enabled: true
compress: best
nfpms:
- id: sub2clash
homepage: https://github.com/bestnite/sub2clash
maintainer: Nite <admin@nite07.com>
license: "MIT"
formats:
- apk
- deb
- rpm
- termux.deb
- archlinux
provides:
- sub2clash

47
API.md
View File

@@ -1,47 +0,0 @@
# `GET /clash`, `GET /meta`
获取 Clash/Clash.Meta 配置链接
| Query 参数 | 类型 | 是否必须 | 默认值 | 说明 |
| ------------ | ------ | ------------------------ | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| sub | string | sub/proxy 至少有一项存在 | - | 订阅链接,可以在链接结尾加上`#名称`,来给订阅中的节点加上统一前缀(可以输入多个,用 `,` 分隔) |
| proxy | string | sub/proxy 至少有一项存在 | - | 节点分享链接(可以输入多个,用 `,` 分隔) |
| refresh | bool | 否 | `false` | 强制刷新配置(默认缓存 5 分钟) |
| template | string | 否 | - | 外部模板链接或内部模板名称 |
| ruleProvider | string | 否 | - | 格式 `[Behavior,Url,Group,Prepend,Name],[Behavior,Url,Group,Prepend,Name]...`,其中 `Group` 是该规则集使用的策略组名,`Prepend` 为 bool 类型,如果为 `true` 规则将被添加到规则列表顶部,否则添加到规则列表底部(会调整到 MATCH 规则之前) |
| rule | string | 否 | - | 格式 `[Rule,Prepend],[Rule,Prepend]...`,其中 `Prepend` 为 bool 类型,如果为 `true` 规则将被添加到规则列表顶部,否则添加到规则列表底部(会调整到 MATCH 规则之前) |
| autoTest | bool | 否 | `false` | 国家策略组是否自动测速 |
| lazy | bool | 否 | `false` | 自动测速是否启用 lazy |
| sort | string | 否 | `nameasc` | 国家策略组排序策略,可选值 `nameasc``namedesc``sizeasc``sizedesc` |
| replace | string | 否 | - | 通过正则表达式重命名节点,格式 `[<ReplaceKey>,<ReplaceTo>],[<ReplaceKey>,<ReplaceTo>]...` |
| remove | string | 否 | - | 通过正则表达式删除节点 |
| nodeList | bool | 否 | `false` | 只输出节点 |
# `POST /short`
获取短链Content-Type 为 `application/json`
具体参考使用可以参考 [api\templates\index.html](api/static/index.html)
| Body 参数 | 类型 | 是否必须 | 默认值 | 说明 |
| --------- | ------ | -------- | ------ | ------------------------- |
| url | string | 是 | - | 需要转换的 Query 参数部分 |
| password | string | 否 | - | 短链密码 |
# `GET /s/:hash`
短链跳转
`hash` 为动态路由参数,可以通过 `/short` 接口获取
| Query 参数 | 类型 | 是否必须 | 默认值 | 说明 |
| ---------- | ------ | -------- | ------ | -------- |
| password | string | 否 | - | 短链密码 |
# `PUT /short`
更新短链Content-Type 为 `application/json`
| Body 参数 | 类型 | 是否必须 | 默认值 | 说明 |
| --------- | ------ | -------- | ------ | ------------------------- |
| url | string | 是 | - | 需要转换的 Query 参数部分 |
| password | string | 否 | - | 短链密码 |
| hash | string | 是 | - | 短链 hash |

View File

@@ -1,4 +1,4 @@
FROM golang:1.21-alpine as builder
FROM golang:1.25 as builder
LABEL authors="nite07"
WORKDIR /app
COPY . .

View File

@@ -59,7 +59,80 @@
### API
[API 文档](./API.md)
#### `GET /convert/:config`
获取 Clash/Clash.Meta 配置链接
| Path 参数 | 类型 | 说明 |
| --------- | ------ | ---------------------------------------------- |
| config | string | Base64 URL Safe 编码后的 JSON 字符串,格式如下 |
##### `config` JSON 结构
| Query 参数 | 类型 | 是否必须 | 默认值 | 说明 |
| ------------------ | ----------------- | ------------------------ | --------- | -------------------------------------------------------------------------------------------------------- |
| clashType | int | 是 | 1 | 配置文件类型 (1: Clash, 2: Clash.Meta) |
| subscriptions | []string | sub/proxy 至少有一项存在 | - | 订阅链接v2ray 或 clash 格式),可以在链接结尾加上`#名称`,来给订阅中的节点加上统一前缀(可以输入多个) |
| proxies | []string | sub/proxy 至少有一项存在 | - | 节点分享链接(可以输入多个) |
| refresh | bool | 否 | `false` | 强制刷新配置(默认缓存 5 分钟) |
| template | string | 否 | - | 外部模板链接或内部模板名称 |
| ruleProviders | []RuleProvider | 否 | - | 规则 |
| rules | []Rule | 否 | - | 规则 |
| autoTest | bool | 否 | `false` | 国家策略组是否自动测速 |
| lazy | bool | 否 | `false` | 自动测速是否启用 lazy |
| sort | string | 否 | `nameasc` | 国家策略组排序策略,可选值 `nameasc``namedesc``sizeasc``sizedesc` |
| replace | map[string]string | 否 | - | 通过正则表达式重命名节点 |
| remove | string | 否 | - | 通过正则表达式删除节点 |
| nodeList | bool | 否 | `false` | 只输出节点 |
| ignoreCountryGroup | bool | 否 | `false` | 是否忽略国家分组 |
| userAgent | string | 否 | - | 订阅 user-agent |
| useUDP | bool | 否 | `false` | 是否使用 UDP |
###### `RuleProvider` 结构
| 字段 | 类型 | 说明 |
| -------- | ------ | ---------------------------------------------------------------- |
| behavior | string | rule-set 的 behavior |
| url | string | rule-set 的 url |
| group | string | 该规则集使用的策略组名 |
| prepend | bool | 如果为 `true` 规则将被添加到规则列表顶部,否则添加到规则列表底部 |
| name | string | 该 rule-provider 的名称,不能重复 |
###### `Rule` 结构
| 字段 | 类型 | 说明 |
| ------- | ------ | ---------------------------------------------------------------- |
| rule | string | 规则 |
| prepend | bool | 如果为 `true` 规则将被添加到规则列表顶部,否则添加到规则列表底部 |
#### `POST /short`
获取短链Content-Type 为 `application/json`
具体参考使用可以参考 [api\templates\index.html](api/static/index.html)
| Body 参数 | 类型 | 是否必须 | 默认值 | 说明 |
| --------- | ------ | -------- | ------ | ------------------------- |
| url | string | 是 | - | 需要转换的 Query 参数部分 |
| password | string | 否 | - | 短链密码 |
#### `GET /s/:hash`
短链跳转
`hash` 为动态路由参数,可以通过 `/short` 接口获取
| Query 参数 | 类型 | 是否必须 | 默认值 | 说明 |
| ---------- | ------ | -------- | ------ | -------- |
| password | string | 否 | - | 短链密码 |
#### `PUT /short`
更新短链Content-Type 为 `application/json`
| Body 参数 | 类型 | 是否必须 | 默认值 | 说明 |
| --------- | ------ | -------- | ------ | ------------------------- |
| url | string | 是 | - | 需要转换的 Query 参数部分 |
| password | string | 否 | - | 短链密码 |
| hash | string | 是 | - | 短链 hash |
### 模板

View File

@@ -133,8 +133,8 @@ func NewTemplateLoadError(template string, cause error) *CommonError {
return NewError(ErrTemplateLoad, fmt.Sprintf("failed to load template: %s", template), cause)
}
func NewTemplateParseError(cause error) *CommonError {
return NewError(ErrTemplateParse, "failed to parse template", cause)
func NewTemplateParseError(data []byte, cause error) *CommonError {
return NewError(ErrTemplateParse, fmt.Sprintf("failed to parse template: %s", data), cause)
}
// Subscription errors
@@ -142,8 +142,8 @@ func NewSubscriptionLoadError(url string, cause error) *CommonError {
return NewError(ErrSubscriptionLoad, fmt.Sprintf("failed to load subscription: %s", url), cause)
}
func NewSubscriptionParseError(cause error) *CommonError {
return NewError(ErrSubscriptionParse, "failed to parse subscription", cause)
func NewSubscriptionParseError(data []byte, cause error) *CommonError {
return NewError(ErrSubscriptionParse, fmt.Sprintf("failed to parse subscription: %s", string(data)), cause)
}
// Regex errors

View File

@@ -129,22 +129,22 @@ func BuildSub(clashType model.ClashType, query model.ConvertConfig, template str
err = yaml.Unmarshal(templateBytes, &temp)
if err != nil {
logger.Logger.Debug("parse template failed", zap.Error(err))
return nil, NewTemplateParseError(err)
return nil, NewTemplateParseError(templateBytes, err)
}
var proxyList []P.Proxy
for i := range query.Subs {
data, err := LoadSubscription(query.Subs[i], query.Refresh, query.UserAgent, cacheExpire, retryTimes)
subName := ""
if strings.Contains(query.Subs[i], "#") {
subName = query.Subs[i][strings.LastIndex(query.Subs[i], "#")+1:]
}
if err != nil {
logger.Logger.Debug(
"load subscription failed", zap.String("url", query.Subs[i]), zap.Error(err),
)
return nil, NewSubscriptionLoadError(query.Subs[i], err)
}
subName := ""
if strings.Contains(query.Subs[i], "#") {
subName = query.Subs[i][strings.LastIndex(query.Subs[i], "#")+1:]
}
err = yaml.Unmarshal(data, &sub)
var newProxies []P.Proxy
@@ -161,14 +161,14 @@ func BuildSub(clashType model.ClashType, query model.ConvertConfig, template str
}
newProxies = p
} else {
base64, err := utils.DecodeBase64(string(data), true)
base64, err := utils.DecodeBase64(string(data), false)
if err != nil {
logger.Logger.Debug(
"parse subscription failed", zap.String("url", query.Subs[i]),
zap.String("data", string(data)),
zap.Error(err),
)
return nil, NewSubscriptionParseError(err)
return nil, NewSubscriptionParseError(data, err)
}
p, err := parser.ParseProxies(parser.ParseConfig{UseUDP: query.UseUDP}, strings.Split(base64, "\n")...)
if err != nil {

View File

@@ -3,11 +3,27 @@ package common
import (
"io"
"os"
"path/filepath"
"strings"
)
func LoadTemplate(templatePath string) ([]byte, error) {
if _, err := os.Stat(templatePath); err == nil {
file, err := os.Open(templatePath)
const templatesDir = "templates"
// LoadTemplate 只读取运行目录下的 templates 目录,防止其他文件内容泄漏
func LoadTemplate(templateName string) ([]byte, error) {
// 清理路径,防止目录遍历攻击
cleanTemplateName := filepath.Clean(templateName)
// 检查是否尝试访问父目录
if strings.HasPrefix(cleanTemplateName, "..") || strings.Contains(cleanTemplateName, string(filepath.Separator)+".."+string(filepath.Separator)) {
return nil, NewFileNotFoundError(templateName) // 拒绝包含父目录的路径
}
// 构建完整路径,确保只从 templates 目录读取
fullPath := filepath.Join(templatesDir, cleanTemplateName)
if _, err := os.Stat(fullPath); err == nil {
file, err := os.Open(fullPath)
if err != nil {
return nil, err
}
@@ -22,5 +38,5 @@ func LoadTemplate(templatePath string) ([]byte, error) {
}
return result, nil
}
return nil, NewFileNotFoundError(templatePath)
return nil, NewFileNotFoundError(templateName)
}

4
go.mod
View File

@@ -1,8 +1,6 @@
module github.com/bestnite/sub2clash
go 1.21.0
toolchain go1.24.3
go 1.25
require (
github.com/gin-gonic/gin v1.10.1

View File

@@ -3,7 +3,7 @@ package proxy
// https://github.com/MetaCubeX/mihomo/blob/Meta/adapter/outbound/anytls.go
type Anytls struct {
Server string `yaml:"server"`
Port int `yaml:"port"`
Port IntOrString `yaml:"port"`
Password string `yaml:"password"`
ALPN []string `yaml:"alpn,omitempty"`
SNI string `yaml:"sni,omitempty"`

View File

@@ -3,7 +3,7 @@ package proxy
// https://github.com/MetaCubeX/mihomo/blob/Meta/adapter/outbound/hysteria.go
type Hysteria struct {
Server string `yaml:"server"`
Port int `yaml:"port,omitempty"`
Port IntOrString `yaml:"port,omitempty"`
Ports string `yaml:"ports,omitempty"`
Protocol string `yaml:"protocol,omitempty"`
ObfsProtocol string `yaml:"obfs-protocol,omitempty"` // compatible with Stash

View File

@@ -3,7 +3,7 @@ package proxy
// https://github.com/MetaCubeX/mihomo/blob/Meta/adapter/outbound/hysteria2.go
type Hysteria2 struct {
Server string `yaml:"server"`
Port int `yaml:"port,omitempty"`
Port IntOrString `yaml:"port,omitempty"`
Ports string `yaml:"ports,omitempty"`
HopInterval int `yaml:"hop-interval,omitempty"`
Up string `yaml:"up,omitempty"`

View File

@@ -2,10 +2,31 @@ package proxy
import (
"fmt"
"strconv"
"gopkg.in/yaml.v3"
)
type IntOrString int
func (i *IntOrString) UnmarshalYAML(value *yaml.Node) error {
intVal := 0
err := yaml.Unmarshal([]byte(value.Value), &intVal)
if err == nil {
*i = IntOrString(intVal)
}
strVal := ""
err = yaml.Unmarshal([]byte(value.Value), &strVal)
if err == nil {
_int, err := strconv.ParseInt(strVal, 10, 64)
if err != nil {
*i = IntOrString(_int)
}
return err
}
return nil
}
type HTTPOptions struct {
Method string `yaml:"method,omitempty"`
Path []string `yaml:"path,omitempty"`

View File

@@ -3,7 +3,7 @@ package proxy
// https://github.com/MetaCubeX/mihomo/blob/Meta/adapter/outbound/shadowsocks.go
type ShadowSocks struct {
Server string `yaml:"server"`
Port int `yaml:"port"`
Port IntOrString `yaml:"port"`
Password string `yaml:"password"`
Cipher string `yaml:"cipher"`
UDP bool `yaml:"udp,omitempty"`

View File

@@ -3,7 +3,7 @@ package proxy
// https://github.com/MetaCubeX/mihomo/blob/Meta/adapter/outbound/shadowsocksr.go
type ShadowSocksR struct {
Server string `yaml:"server"`
Port int `yaml:"port"`
Port IntOrString `yaml:"port"`
Password string `yaml:"password"`
Cipher string `yaml:"cipher"`
Obfs string `yaml:"obfs"`

View File

@@ -3,7 +3,7 @@ package proxy
// https://github.com/MetaCubeX/mihomo/blob/Meta/adapter/outbound/socks5.go
type Socks struct {
Server string `yaml:"server"`
Port int `yaml:"port"`
Port IntOrString `yaml:"port"`
UserName string `yaml:"username,omitempty"`
Password string `yaml:"password,omitempty"`
TLS bool `yaml:"tls,omitempty"`

View File

@@ -3,7 +3,7 @@ package proxy
// https://github.com/MetaCubeX/mihomo/blob/Meta/adapter/outbound/trojan.go
type Trojan struct {
Server string `yaml:"server"`
Port int `yaml:"port"`
Port IntOrString `yaml:"port"`
Password string `yaml:"password"`
ALPN []string `yaml:"alpn,omitempty"`
SNI string `yaml:"sni,omitempty"`

View File

@@ -3,7 +3,7 @@ package proxy
// https://github.com/MetaCubeX/mihomo/blob/Meta/adapter/outbound/vless.go
type Vless struct {
Server string `yaml:"server"`
Port int `yaml:"port"`
Port IntOrString `yaml:"port"`
UUID string `yaml:"uuid"`
Flow string `yaml:"flow,omitempty"`
TLS bool `yaml:"tls,omitempty"`

View File

@@ -3,9 +3,9 @@ package proxy
// https://github.com/MetaCubeX/mihomo/blob/Meta/adapter/outbound/vmess.go
type Vmess struct {
Server string `yaml:"server"`
Port int `yaml:"port"`
Port IntOrString `yaml:"port"`
UUID string `yaml:"uuid"`
AlterID int `yaml:"alterId"`
AlterID IntOrString `yaml:"alterId"`
Cipher string `yaml:"cipher"`
UDP bool `yaml:"udp,omitempty"`
Network string `yaml:"network,omitempty"`

View File

@@ -14,11 +14,11 @@ type NodeList struct {
// https://github.com/MetaCubeX/mihomo/blob/Meta/config/config.go RawConfig
type Subscription struct {
Port int `yaml:"port,omitempty" json:"port"`
SocksPort int `yaml:"socks-port,omitempty" json:"socks-port"`
RedirPort int `yaml:"redir-port,omitempty" json:"redir-port"`
TProxyPort int `yaml:"tproxy-port,omitempty" json:"tproxy-port"`
MixedPort int `yaml:"mixed-port,omitempty" json:"mixed-port"`
Port proxy.IntOrString `yaml:"port,omitempty" json:"port"`
SocksPort proxy.IntOrString `yaml:"socks-port,omitempty" json:"socks-port"`
RedirPort proxy.IntOrString `yaml:"redir-port,omitempty" json:"redir-port"`
TProxyPort proxy.IntOrString `yaml:"tproxy-port,omitempty" json:"tproxy-port"`
MixedPort proxy.IntOrString `yaml:"mixed-port,omitempty" json:"mixed-port"`
ShadowSocksConfig string `yaml:"ss-config,omitempty" json:"ss-config"`
VmessConfig string `yaml:"vmess-config,omitempty" json:"vmess-config"`
InboundTfo bool `yaml:"inbound-tfo,omitempty" json:"inbound-tfo"`

View File

@@ -68,7 +68,7 @@ func (p *AnytlsParser) Parse(config ParseConfig, proxy string) (P.Proxy, error)
Name: remarks,
Anytls: P.Anytls{
Server: server,
Port: port,
Port: P.IntOrString(port),
Password: password,
SNI: sni,
SkipCertVerify: insecureBool,

View File

@@ -76,7 +76,7 @@ func (p *HysteriaParser) Parse(config ParseConfig, proxy string) (P.Proxy, error
Name: remarks,
Hysteria: P.Hysteria{
Server: server,
Port: port,
Port: P.IntOrString(port),
Up: upmbps,
Down: downmbps,
Auth: auth,

View File

@@ -68,7 +68,7 @@ func (p *Hysteria2Parser) Parse(config ParseConfig, proxy string) (P.Proxy, erro
Name: remarks,
Hysteria2: P.Hysteria2{
Server: server,
Port: port,
Port: P.IntOrString(port),
Password: password,
Obfs: obfs,
ObfsPassword: obfsPassword,

View File

@@ -108,7 +108,7 @@ func (p *ShadowsocksParser) Parse(config ParseConfig, proxy string) (P.Proxy, er
Cipher: method,
Password: password,
Server: server,
Port: port,
Port: P.IntOrString(port),
UDP: config.UseUDP,
},
}

View File

@@ -94,7 +94,7 @@ func (p *ShadowsocksRParser) Parse(config ParseConfig, proxy string) (P.Proxy, e
Name: remarks,
ShadowSocksR: P.ShadowSocksR{
Server: server,
Port: port,
Port: P.IntOrString(port),
Protocol: protocol,
Cipher: method,
Obfs: obfs,

View File

@@ -79,7 +79,7 @@ func (p *SocksParser) Parse(config ParseConfig, proxy string) (P.Proxy, error) {
Name: remarks,
Socks: P.Socks{
Server: server,
Port: port,
Port: P.IntOrString(port),
UserName: username,
Password: password,
TLS: tls == "true",

View File

@@ -63,7 +63,7 @@ func (p *TrojanParser) Parse(config ParseConfig, proxy string) (P.Proxy, error)
insecureBool := insecure == "1"
result := P.Trojan{
Server: server,
Port: port,
Port: P.IntOrString(port),
Password: password,
Network: network,
UDP: udp == "true",

View File

@@ -66,7 +66,7 @@ func (p *VlessParser) Parse(config ParseConfig, proxy string) (P.Proxy, error) {
result := P.Vless{
Server: server,
Port: port,
Port: P.IntOrString(port),
UUID: uuid,
Flow: flow,
UDP: udp == "true",

View File

@@ -109,9 +109,9 @@ func (p *VmessParser) Parse(config ParseConfig, proxy string) (P.Proxy, error) {
result := P.Vmess{
Server: vmess.Add,
Port: port,
Port: P.IntOrString(port),
UUID: vmess.Id,
AlterID: aid,
AlterID: P.IntOrString(aid),
Cipher: vmess.Scy,
UDP: config.UseUDP,
}

View File

@@ -89,7 +89,7 @@
<!-- Template -->
<div class="form-group mb-3">
<label for="template">模板链接或名称:</label>
<input class="form-control" id="template" name="template" placeholder="输入外部模板链接或内部模板名称(可选)" type="text" />
<input class="form-control" id="template" name="template" placeholder="输入模板链接(可选)" type="text" />
</div>
<!-- Subscription Link -->
<div class="form-group mb-3">

33
test/yaml_test.go Normal file
View File

@@ -0,0 +1,33 @@
package test
import (
"testing"
"github.com/bestnite/sub2clash/model/proxy"
"gopkg.in/yaml.v3"
)
type testStruct struct {
A proxy.IntOrString `yaml:"a"`
}
func TestUnmarshal(t *testing.T) {
yamlData1 := `a: 123`
res := testStruct{}
err := yaml.Unmarshal([]byte(yamlData1), &res)
if err != nil {
t.Errorf("failed to unmarshal yaml: %v", err)
}
if res.A != 123 {
t.Errorf("expected 123, but got %v", res.A)
}
yamlData2 := `a: "123"`
err = yaml.Unmarshal([]byte(yamlData2), &res)
if err != nil {
t.Errorf("failed to unmarshal yaml: %v", err)
}
if res.A != 123 {
t.Errorf("expected 123, but got %v", res.A)
}
}