Repository navigation
Expand file tree
/
Copy pathparser.go
More file actions
221 lines (198 loc) · 6.11 KB
/
Copy pathparser.go
File metadata and controls
221 lines (198 loc) · 6.11 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
package codexswitch
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
)
type authFile struct {
AuthMode *string `json:"auth_mode"`
OpenAIAPIKey *string `json:"OPENAI_API_KEY"`
Tokens *tokenData `json:"tokens"`
LastRefresh *string `json:"last_refresh"`
}
type tokenData struct {
IDToken string `json:"id_token"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
AccountID string `json:"account_id"`
}
type idTokenClaims struct {
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Profile struct {
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
} `json:"https://api.openai.com/profile"`
Auth struct {
ChatGPTPlanType string `json:"chatgpt_plan_type"`
ChatGPTUserID string `json:"chatgpt_user_id"`
UserID string `json:"user_id"`
ChatGPTAccountID string `json:"chatgpt_account_id"`
} `json:"https://api.openai.com/auth"`
}
type accessTokenClaims struct {
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
ClientID string `json:"client_id"`
Profile struct {
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
} `json:"https://api.openai.com/profile"`
Auth struct {
ChatGPTPlanType string `json:"chatgpt_plan_type"`
ChatGPTUserID string `json:"chatgpt_user_id"`
UserID string `json:"user_id"`
ChatGPTAccountID string `json:"chatgpt_account_id"`
} `json:"https://api.openai.com/auth"`
}
func buildProfileSnapshot(authRaw, configRaw, source string, now time.Time) (*profileSnapshot, error) {
normalizedAuthRaw, _, err := normalizeAuthJSON(authRaw)
if err != nil {
return nil, err
}
var auth authFile
if err := json.Unmarshal([]byte(normalizedAuthRaw), &auth); err != nil {
return nil, fmt.Errorf("auth.json 解析失败: %w", err)
}
config := parseConfigTOML(configRaw)
profileType := detectProfileType(auth)
meta := ProfileMeta{
Type: profileType,
Model: strings.TrimSpace(config.Model),
ModelReasoningEffort: strings.TrimSpace(config.ModelReasoningEffort),
BaseURL: strings.TrimSpace(config.BaseURL),
Source: source,
IsValid: profileType != ProfileTypeUnknown,
ContentHash: computeContentHash(normalizedAuthRaw, configRaw),
CreatedAt: now.UTC().Format(time.RFC3339),
UpdatedAt: now.UTC().Format(time.RFC3339),
RateLimits: RateLimitState{
Status: RateLimitStatusIdle,
},
LatencyTest: LatencyTestState{
Status: LatencyTestStatusIdle,
},
}
switch profileType {
case ProfileTypeOfficial:
if err := fillOfficialProfileMeta(&meta, auth); err != nil {
return nil, err
}
case ProfileTypeAPI:
fillAPIProfileMeta(&meta, auth)
default:
meta.DisplayName = "未识别配置"
}
stableIdentity := selectStableIdentity(meta, auth)
if stableIdentity == "" {
stableIdentity = meta.ContentHash
}
meta.StableKeyHash = sha256Hex(stableIdentity)
meta.ID = buildProfileID(meta.Type, stableIdentity)
return &profileSnapshot{
Meta: meta,
AuthRaw: normalizedAuthRaw,
ConfigRaw: configRaw,
}, nil
}
func detectProfileType(auth authFile) ProfileType {
if auth.AuthMode != nil {
mode := strings.ToLower(strings.TrimSpace(*auth.AuthMode))
switch {
case strings.HasPrefix(mode, "chatgpt"):
return ProfileTypeOfficial
case strings.Contains(mode, "api"):
return ProfileTypeAPI
default:
return ProfileTypeUnknown
}
}
if auth.OpenAIAPIKey != nil && strings.TrimSpace(*auth.OpenAIAPIKey) != "" {
return ProfileTypeAPI
}
if auth.Tokens != nil {
return ProfileTypeOfficial
}
return ProfileTypeUnknown
}
func fillOfficialProfileMeta(meta *ProfileMeta, auth authFile) error {
if auth.Tokens == nil {
return errors.New("官方配置缺少 tokens 字段")
}
var idClaims idTokenClaims
var accessClaims accessTokenClaims
if strings.TrimSpace(auth.Tokens.IDToken) != "" {
if err := decodeJWTClaims(auth.Tokens.IDToken, &idClaims); err != nil {
return fmt.Errorf("id_token 解析失败: %w", err)
}
}
if strings.TrimSpace(auth.Tokens.AccessToken) != "" {
if err := decodeJWTClaims(auth.Tokens.AccessToken, &accessClaims); err != nil {
return fmt.Errorf("access_token 解析失败: %w", err)
}
}
meta.Email = strings.ToLower(trimmedFirst(
idClaims.Email,
idClaims.Profile.Email,
accessClaims.Email,
accessClaims.Profile.Email,
))
meta.EmailVerified = idClaims.EmailVerified || idClaims.Profile.EmailVerified ||
accessClaims.EmailVerified || accessClaims.Profile.EmailVerified
meta.PlanType = strings.ToLower(trimmedFirst(
idClaims.Auth.ChatGPTPlanType,
accessClaims.Auth.ChatGPTPlanType,
))
meta.ChatGPTUserID = trimmedFirst(
idClaims.Auth.ChatGPTUserID,
idClaims.Auth.UserID,
accessClaims.Auth.ChatGPTUserID,
accessClaims.Auth.UserID,
)
meta.ChatGPTAccountID = trimmedFirst(
auth.Tokens.AccountID,
idClaims.Auth.ChatGPTAccountID,
accessClaims.Auth.ChatGPTAccountID,
)
meta.ClientID = trimmedFirst(accessClaims.ClientID)
meta.DisplayName = trimmedFirst(meta.Email, meta.ChatGPTAccountID, meta.ChatGPTUserID, "官方账号")
return nil
}
func fillAPIProfileMeta(meta *ProfileMeta, auth authFile) {
apiKey := ""
if auth.OpenAIAPIKey != nil {
apiKey = strings.TrimSpace(*auth.OpenAIAPIKey)
}
meta.MaskedAPIKey = maskAPIKey(apiKey)
meta.DisplayName = trimmedFirst(meta.MaskedAPIKey, meta.BaseURL, "API 配置")
}
func selectStableIdentity(meta ProfileMeta, auth authFile) string {
switch meta.Type {
case ProfileTypeOfficial:
return trimmedFirst(
strings.ToLower(meta.Email),
meta.ChatGPTAccountID,
meta.ChatGPTUserID,
meta.ContentHash,
)
case ProfileTypeAPI:
if auth.OpenAIAPIKey != nil {
return trimmedFirst(*auth.OpenAIAPIKey, meta.ContentHash)
}
}
return meta.ContentHash
}
func decodeJWTClaims(token string, dest any) error {
parts := strings.Split(token, ".")
if len(parts) < 2 {
return errors.New("JWT 格式无效")
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return err
}
return json.Unmarshal(payload, dest)
}