-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubscription.go
More file actions
245 lines (216 loc) · 6.43 KB
/
Copy pathsubscription.go
File metadata and controls
245 lines (216 loc) · 6.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package service
import (
"encoding/json"
"fmt"
"net"
"strings"
"time"
"clash-config-store/internal/model"
"clash-config-store/internal/repository"
"clash-config-store/internal/util"
)
// GenerateYAML 根据订阅 token 和客户端 IP 生成完整的 mihomo YAML 配置
// 返回 (yamlBytes, subscriptionID, allowed, denyReason, error)
func GenerateYAML(token string, clientIP string) ([]byte, uint, bool, string, error) {
var sub model.Subscription
if err := repository.DB.
Preload("CustomConfig").
Preload("ConfigTemplate").
Where("token = ?", token).
First(&sub).Error; err != nil {
return nil, 0, false, "", fmt.Errorf("订阅不存在")
}
if sub.TokenExpiredAt != nil && time.Now().After(*sub.TokenExpiredAt) {
return nil, sub.ID, false, "token 已过期", nil
}
var restrictions []model.AccessRestriction
repository.DB.Where("subscription_id = ?", sub.ID).Find(&restrictions)
allowed, denyReason := checkAccess(clientIP, restrictions)
if !allowed {
return nil, sub.ID, false, denyReason, nil
}
// 解析启用的 Provider IDs
var providerIDs []uint
if sub.EnabledProviderIDs != "" {
_ = json.Unmarshal([]byte(sub.EnabledProviderIDs), &providerIDs)
}
var providers []model.Provider
if len(providerIDs) > 0 {
repository.DB.Where("id IN ?", providerIDs).Find(&providers)
}
// 收集 provider 代理节点,同时记录每个 provider 的节点名列表(供 use: 展开)
providerProxies := make([]interface{}, 0)
providerNodeNames := make(map[string][]string) // providerName -> []nodeName(含前缀)
for _, p := range providers {
if IsCacheStale(&p) {
AsyncRefresh(p.ID)
}
proxies, err := util.ParseProxiesFromContent(p.CacheContent)
if err != nil || proxies == nil {
continue
}
if sub.ProxyPrefixEnabled {
proxies = util.PrefixProxies(proxies, p.Name)
}
providerProxies = append(providerProxies, proxies...)
// 提取本 provider 所有节点名,供 proxy-group use: 展开
names := make([]string, 0, len(proxies))
for _, px := range proxies {
if pm, ok := px.(map[string]interface{}); ok {
if name, ok := pm["name"].(string); ok && name != "" {
names = append(names, name)
}
}
}
providerNodeNames[p.Name] = names
}
// 读取 CustomConfig 结构化数据
var customProxies []map[string]interface{}
var customGroups []map[string]interface{}
var customRules []string
var ruleProviderInputs []util.RuleProviderInput
var err error
if sub.CustomConfig != nil {
customProxies = sub.CustomConfig.Proxies
customGroups = sub.CustomConfig.ProxyGroups
customRules = sub.CustomConfig.Rules
ruleProviderInputs, err = loadSubscriptionRuleProviderInputs(
sub.UserID,
sub.CustomConfig.RuleProviderIDs,
sub.CustomConfig.HostedRuleSetIDs,
)
if err != nil {
return nil, sub.ID, true, "", err
}
}
// 读取 ConfigTemplate 内容
var configTemplateContent string
if sub.ConfigTemplate != nil {
configTemplateContent = sub.ConfigTemplate.Content
}
yamlBytes, err := util.BuildMihomoConfig(
configTemplateContent,
providerProxies,
customProxies,
customGroups,
customRules,
string(sub.RuleInsertMode),
ruleProviderInputs,
providerNodeNames,
)
if err != nil {
return nil, sub.ID, true, "", fmt.Errorf("构建配置失败: %w", err)
}
return yamlBytes, sub.ID, true, "", nil
}
func loadSubscriptionRuleProviderInputs(userID uint, ruleProviderIDs []uint, hostedRuleSetIDs []uint) ([]util.RuleProviderInput, error) {
inputs := make([]util.RuleProviderInput, 0, len(ruleProviderIDs)+len(hostedRuleSetIDs))
names := make(map[string]struct{}, len(ruleProviderIDs)+len(hostedRuleSetIDs))
hostedSeen := make(map[uint]struct{}, len(hostedRuleSetIDs))
for _, id := range hostedRuleSetIDs {
hostedSeen[id] = struct{}{}
}
if len(ruleProviderIDs) > 0 {
var rps []model.RuleProvider
if err := repository.DB.
Where("id IN ?", ruleProviderIDs).
Where("user_id = ? OR is_preset = ?", userID, true).
Find(&rps).Error; err != nil {
return nil, err
}
for _, rp := range rps {
if _, exists := names[rp.Name]; exists {
return nil, fmt.Errorf("规则集名称 %q 重复", rp.Name)
}
names[rp.Name] = struct{}{}
inputs = append(inputs, util.RuleProviderInput{
Name: rp.Name,
Type: rp.Type,
URL: rp.URL,
Behavior: rp.Behavior,
Format: rp.Format,
Interval: rp.Interval,
})
}
}
if len(hostedSeen) > 0 {
ids := make([]uint, 0, len(hostedSeen))
for id := range hostedSeen {
ids = append(ids, id)
}
var hosted []model.HostedRuleSet
if err := repository.DB.Where("id IN ? AND user_id = ?", ids, userID).Find(&hosted).Error; err != nil {
return nil, err
}
for _, hrs := range hosted {
if _, exists := names[hrs.Name]; exists {
return nil, fmt.Errorf("规则集名称 %q 重复", hrs.Name)
}
names[hrs.Name] = struct{}{}
inputs = append(inputs, util.RuleProviderInput{
Name: hrs.Name,
Type: "http",
URL: util.RuleSetPublicURL(hrs.Token, hrs.Name),
Behavior: hrs.Behavior,
Format: hrs.Format,
Interval: 86400,
})
}
}
return inputs, nil
}
// checkAccess 根据访问限制规则判断客户端 IP 是否允许访问
func checkAccess(clientIP string, restrictions []model.AccessRestriction) (bool, string) {
if len(restrictions) == 0 {
return true, ""
}
var allowRules []model.AccessRestriction
var denyRules []model.AccessRestriction
for _, r := range restrictions {
if r.Mode == model.RestrictionAllow {
allowRules = append(allowRules, r)
} else {
denyRules = append(denyRules, r)
}
}
var geoInfo *util.GeoInfo
for _, r := range restrictions {
if r.Type == model.RestrictionTypeCountry {
geoInfo = util.LookupIP(clientIP)
break
}
}
matchRule := func(r model.AccessRestriction) bool {
switch r.Type {
case model.RestrictionTypeIP:
return clientIP == r.Value
case model.RestrictionTypeCIDR:
_, cidr, err := net.ParseCIDR(r.Value)
if err != nil {
return false
}
ip := net.ParseIP(clientIP)
return ip != nil && cidr.Contains(ip)
case model.RestrictionTypeCountry:
if geoInfo == nil {
return false
}
return strings.EqualFold(geoInfo.CountryCode, r.Value)
}
return false
}
for _, r := range denyRules {
if matchRule(r) {
return false, fmt.Sprintf("IP 已被拒绝访问 (%s: %s)", r.Type, r.Value)
}
}
if len(allowRules) > 0 {
for _, r := range allowRules {
if matchRule(r) {
return true, ""
}
}
return false, "IP 不在允许访问列表中"
}
return true, ""
}