File size: 7,600 Bytes
ca50bff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package internal

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"sync"
	"time"

	fhttp "github.com/bogdanfinn/fhttp"
)

const anonymousAuthURL = "https://chat.z.ai/api/v1/auths/"

type AnonymousAuthResponse struct {
	Token string `json:"token"`
}

// UpstreamZaiCredentialConfigured 已配置 z.ai 上游凭证(TokenManager 有效 token 或 BACKUP_TOKEN)时返回 true,此时不维护匿名 token 池,GetAnonymousToken 每次直连拉取。
func UpstreamZaiCredentialConfigured() bool {
	if Cfg == nil {
		return false
	}
	if len(Cfg.BackupTokens) > 0 {
		return true
	}
	return GetTokenManager().HasValidUpstreamTokens()
}

type anonPoolSlot struct {
	token   string
	expires time.Time
}

var (
	anonPoolMu    sync.Mutex
	anonPoolSlots []anonPoolSlot
	anonPoolNext  int
	poolTTL       time.Duration
	refreshEvery  time.Duration
	maxRetries    int
	poolOnce      sync.Once
)

// StartAnonymousTokenPool 启动后台周期性补全匿名 token 池;无上游 token 时预取,有上游 token 时清空池且不预取。
func StartAnonymousTokenPool() {
	poolOnce.Do(func() {
		size := 4
		if Cfg != nil && Cfg.AnonymousPoolSize > 0 {
			size = Cfg.AnonymousPoolSize
		}
		if size < 1 {
			size = 1
		}
		if size > 16 {
			size = 16
		}
		poolTTL = 20 * time.Minute
		if Cfg != nil && Cfg.AnonymousTokenTTLSeconds > 0 {
			poolTTL = time.Duration(Cfg.AnonymousTokenTTLSeconds) * time.Second
		}
		if poolTTL < 5*time.Minute {
			poolTTL = 5 * time.Minute
		}
		refreshEvery = 90 * time.Second
		if Cfg != nil && Cfg.AnonymousRefreshIntervalSeconds > 0 {
			refreshEvery = time.Duration(Cfg.AnonymousRefreshIntervalSeconds) * time.Second
		}
		if refreshEvery < 30*time.Second {
			refreshEvery = 30 * time.Second
		}
		maxRetries = 3
		if Cfg != nil && Cfg.AnonymousFetchMaxRetries > 0 {
			maxRetries = Cfg.AnonymousFetchMaxRetries
		}
		if maxRetries > 8 {
			maxRetries = 8
		}

		anonPoolMu.Lock()
		anonPoolSlots = make([]anonPoolSlot, size)
		anonPoolNext = 0
		anonPoolMu.Unlock()

		go anonymousPoolLoop()
		LogInfo("匿名 token 池已启动: size=%d ttl=%v refresh=%v", size, poolTTL, refreshEvery)
	})
}

func anonymousPoolLoop() {
	refillAnonymousPool()
	ticker := time.NewTicker(refreshEvery)
	defer ticker.Stop()
	for range ticker.C {
		refillAnonymousPool()
	}
}

// invalidateAnonymousPoolSlots 清空池中条目(例如 TokenManager 刚加载到有效 token 时)
func invalidateAnonymousPoolSlots() {
	anonPoolMu.Lock()
	defer anonPoolMu.Unlock()
	if len(anonPoolSlots) == 0 {
		return
	}
	for i := range anonPoolSlots {
		anonPoolSlots[i] = anonPoolSlot{}
	}
}

func refillAnonymousPool() {
	if UpstreamZaiCredentialConfigured() {
		anonPoolMu.Lock()
		for i := range anonPoolSlots {
			anonPoolSlots[i] = anonPoolSlot{}
		}
		anonPoolMu.Unlock()
		return
	}
	for i := range anonPoolSlots {
		need := false
		anonPoolMu.Lock()
		if i < len(anonPoolSlots) {
			s := &anonPoolSlots[i]
			if s.token == "" || time.Now().After(s.expires) {
				need = true
			}
		}
		anonPoolMu.Unlock()
		if !need {
			continue
		}
		tok, exp, err := fetchAnonymousTokenOnce()
		if err != nil {
			LogDebug("[anon-pool] slot %d: %v", i, err)
			time.Sleep(250 * time.Millisecond)
			continue
		}
		anonPoolMu.Lock()
		if !UpstreamZaiCredentialConfigured() && i < len(anonPoolSlots) {
			anonPoolSlots[i] = anonPoolSlot{token: tok, expires: exp}
		}
		anonPoolMu.Unlock()
	}
}

// GetUpstreamTokenForModelAPI 拉模型列表等:优先 TokenManager / BACKUP,否则匿名(可走池)。
func GetUpstreamTokenForModelAPI() (string, error) {
	if t := GetTokenManager().GetToken(); t != "" {
		return t, nil
	}
	if t := GetBackupToken(); t != "" {
		return t, nil
	}
	return GetAnonymousToken()
}

// GetAnonymousToken 返回用于 z.ai 上游的匿名 token:已配置上游 token 时每次直连;否则从池 next 轮询取用,池空或过期则临时直连拉取。
func GetAnonymousToken() (string, error) {
	if UpstreamZaiCredentialConfigured() {
		tok, _, err := fetchAnonymousTokenOnce()
		return tok, err
	}
	StartAnonymousTokenPool()

	anonPoolMu.Lock()
	n := len(anonPoolSlots)
	if n == 0 {
		anonPoolMu.Unlock()
		tok, _, err := fetchAnonymousTokenOnce()
		return tok, err
	}
	now := time.Now()
	for attempt := 0; attempt < n; attempt++ {
		idx := (anonPoolNext + attempt) % n
		s := &anonPoolSlots[idx]
		if s.token != "" && now.Before(s.expires) {
			tok := s.token
			anonPoolNext = (idx + 1) % n
			anonPoolMu.Unlock()
			return tok, nil
		}
	}
	anonPoolMu.Unlock()

	tok, _, err := fetchAnonymousTokenOnce()
	return tok, err
}

func jwtExpiryIfAny(token string) (time.Time, bool) {
	parts := strings.Split(token, ".")
	if len(parts) < 2 {
		return time.Time{}, false
	}
	raw, err := base64.RawURLEncoding.DecodeString(parts[1])
	if err != nil {
		return time.Time{}, false
	}
	var claims struct {
		Exp int64 `json:"exp"`
	}
	if err := json.Unmarshal(raw, &claims); err != nil || claims.Exp == 0 {
		return time.Time{}, false
	}
	return time.Unix(claims.Exp, 0), true
}

func computeAnonTokenExpiry(token string) time.Time {
	now := time.Now()
	ttl := poolTTL
	if ttl < 5*time.Minute {
		if Cfg != nil && Cfg.AnonymousTokenTTLSeconds > 0 {
			ttl = time.Duration(Cfg.AnonymousTokenTTLSeconds) * time.Second
		}
		if ttl < 5*time.Minute {
			ttl = 20 * time.Minute
		}
	}
	byTTL := now.Add(ttl)
	if jwtExp, ok := jwtExpiryIfAny(token); ok {
		jwtCut := jwtExp.Add(-90 * time.Second)
		if jwtCut.Before(now.Add(2 * time.Minute)) {
			return byTTL
		}
		if jwtCut.Before(byTTL) {
			return jwtCut
		}
	}
	return byTTL
}

func fetchAnonymousTokenOnce() (token string, expires time.Time, err error) {
	var lastErr error
	for attempt := 0; attempt < maxRetries; attempt++ {
		if attempt > 0 {
			time.Sleep(time.Duration(200*(attempt+1)) * time.Millisecond)
		}
		tok, e := fetchAnonymousTokenHTTP()
		if e == nil && tok != "" {
			return tok, computeAnonTokenExpiry(tok), nil
		}
		lastErr = e
	}
	if lastErr == nil {
		lastErr = fmt.Errorf("empty token")
	}
	return "", time.Time{}, lastErr
}

func fetchAnonymousTokenHTTP() (string, error) {
	client, err := TLSHTTPClient(15 * time.Second)
	if err != nil {
		return "", err
	}
	req, err := fhttp.NewRequest("GET", anonymousAuthURL, nil)
	if err != nil {
		return "", err
	}
	ApplyBrowserFingerprintHeaders(req.Header)
	req.Header.Set("Accept", "application/json, text/plain, */*")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
	req.Header.Set("Referer", "https://chat.z.ai/")
	req.Header.Set("Origin", "https://chat.z.ai")
	req.Header.Set("Sec-Fetch-Dest", "empty")
	req.Header.Set("Sec-Fetch-Mode", "cors")
	req.Header.Set("Sec-Fetch-Site", "same-origin")

	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	if resp.StatusCode != http.StatusOK {
		preview := string(body)
		if len(preview) > 200 {
			preview = preview[:200] + "..."
		}
		return "", fmt.Errorf("status %d: %s", resp.StatusCode, preview)
	}
	var authResp AnonymousAuthResponse
	if err := json.Unmarshal(body, &authResp); err != nil {
		return "", fmt.Errorf("decode: %w", err)
	}
	if authResp.Token == "" {
		return "", fmt.Errorf("empty token in response")
	}
	return authResp.Token, nil
}