Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ ACCOUNT_ORDER=
# 上游返回 403、5xx 等非额度错误时一个请求最多换几次账户重试,0 为不换号;额度用尽不计入
MAX_ACCOUNT_SWITCHES=3

# 控制账户会话失效(上游 401 等)后的恢复:true 时自动读取已保存的续签材料为账户原地续签并重放请求;false 时账户直接标为需要重新登录,由人工登录。DBSC 会话的主动刷新与人工登录、导入按原有规则执行。修改后重启生成服务生效
AUTH_RECOVERY=true

# 生成请求使用的上游通道:playground、build(旧通道,上游已停用其生成),逗号分隔
UPSTREAM_CHANNELS=playground

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -648,6 +648,7 @@ cp .env.example .env
| `ROUTING_STRATEGY` | `round-robin` | `round-robin` 轮询;`fill-first` 账号粘性优先 |
| `ACCOUNT_ORDER` | 空 | `fill-first` 依次使用的账户,逗号分隔,未列出的账户排在后面并按 ID 排序;也可在设置页调整,保存后立即生效 |
| `MAX_ACCOUNT_SWITCHES` | `3` | 上游返回 403、5xx 等非额度错误时一个请求最多换几次账户重试,`0` 为不换号;额度用尽不计入,照常依次尝试其余账户 |
| `AUTH_RECOVERY` | `true` | 控制账户会话失效(上游 401 等)后的恢复:`true` 时自动读取已保存的续签材料为账户原地续签并重放请求;`false` 时账户直接标为“需要重新登录”,由人工在账户页重新登录。DBSC 会话的主动刷新与人工登录、导入按原有规则执行。修改后重启生成服务生效 |
| `UPSTREAM_CHANNELS` | `playground` | 生成请求使用的上游通道,`playground`、`build` 逗号分隔;`build` 为旧通道,上游已停用其生成 |
| `MODEL_MAPPING` | 空 | 客户端模型名到目录模型的映射,每项写成 `别名:模型 ID`,逗号分隔多项 |
| `MODEL_CHANNELS` | 空 | 限定模型只走一个通道,每项写成 `模型 ID:playground` 或 `模型 ID:build`;也可在“模型目录”的模型详情中选择,保存后立即生效 |
Expand Down
1 change: 1 addition & 0 deletions README_en.md
Original file line number Diff line number Diff line change
Expand Up @@ -648,6 +648,7 @@ Process environment variables override the same keys in `.env`, and those settin
| `ROUTING_STRATEGY` | `round-robin` | `round-robin` rotates accounts; `fill-first` reuses the first available account |
| `ACCOUNT_ORDER` | empty | Accounts `fill-first` uses in order, comma-separated; unlisted accounts follow in ID order. Also adjustable on the Settings page, applied on save |
| `MAX_ACCOUNT_SWITCHES` | `3` | How many times a request moves to another account after a non-quota upstream error such as 403 or 5xx; `0` disables switching. Quota errors do not count, and the remaining accounts are still tried in turn |
| `AUTH_RECOVERY` | `true` | Controls recovery after an account session is judged expired (upstream 401 and similar): `true` renews in place from the account's saved renewal material and replays the request; `false` marks the account as sign-in required for a manual re-login on the Accounts page. Proactive DBSC refresh and manual sign-in/import follow their existing lifecycle. Applies when the generation service restarts |
| `UPSTREAM_CHANNELS` | `playground` | Upstream channels for generation requests, `playground` and `build` comma separated; `build` is the legacy channel whose generation upstream has disabled |
| `MODEL_MAPPING` | empty | Client model names mapped to catalog models, each item `alias:model ID`, comma separated |
| `MODEL_CHANNELS` | empty | Limit a model to one channel, each item `model ID:playground` or `model ID:build`; also selectable in model details on the Model catalog page, applied on save |
Expand Down
1 change: 1 addition & 0 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ Camoufox 由 Go 通过 WebDriver BiDi 直接管理。启动数据面时,服务
| `ROUTING_STRATEGY` | 账户轮询 `round-robin` 或粘性优先 `fill-first` | `round-robin` |
| `ACCOUNT_ORDER` | 逗号分隔的账户 ID,`fill-first` 依次使用并按此顺序预热,未列出的账户排在后面并按 ID 排序;保存后立即生效 | 空 |
| `MAX_ACCOUNT_SWITCHES` | 一个请求因上游 401、403、404、5xx、连接断开等非额度失败换号的次数上限,`0` 为不换号;额度失败不计入;保存后停止再启动生成服务生效 | `3` |
| `AUTH_RECOVERY` | 控制账户会话失效(上游 401 等)后的恢复:`true` 时自动读取已保存的续签材料原地续签;`false` 时账户直接标记需要重新登录,由人工登录。DBSC 会话的主动刷新与人工登录、导入按原有规则执行;修改后重启生成服务生效 | `true` |
| `UPSTREAM_CHANNELS` | 生成请求的上游通道 `playground`、`build`(旧通道,上游已停用其生成),逗号分隔 | `playground` |
| `MODEL_MAPPING` | 逗号分隔,每项以最后一个 `:` 分成别名与模型 ID | 空 |
| `MODEL_CHANNELS` | 逗号分隔,每项以最后一个 `:` 分成模型 ID 与通道 `playground` 或 `build`;保存后立即生效 | 空 |
Expand Down
1 change: 1 addition & 0 deletions internal/api/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ type RuntimeConfig struct {
AdminPassword *string `json:"admin_password,omitempty"`
AdminPasswordSet bool `json:"admin_password_set"`
SavedAdminPassword string `json:"-"`
SavedAuthRecovery bool `json:"-"`
BuildNativeNonstream bool `json:"build_native_nonstream"`
NonstreamKeepalive bool `json:"nonstream_keepalive"`
FakeStream bool `json:"fake_stream"`
Expand Down
2 changes: 2 additions & 0 deletions internal/app/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -1158,6 +1158,7 @@ func (admin *runtimeAdmin) UpdateRuntimeConfig(_ context.Context, value api.Runt
RoutingStrategy: value.RoutingStrategy,
AccountOrder: strings.TrimSpace(value.AccountOrder),
MaxAccountSwitches: value.MaxAccountSwitches,
AuthRecovery: saved.AuthRecovery,
UpstreamChannels: value.UpstreamChannels,
ModelMapping: strings.TrimSpace(value.ModelMapping),
ModelChannels: strings.TrimSpace(value.ModelChannels),
Expand Down Expand Up @@ -1460,6 +1461,7 @@ func runtimeConfigDTO(cfg config.Config) api.RuntimeConfig {
LogFile: cfg.LogFile, LogMaxTotalMB: cfg.LogMaxTotalMB,
AdminAuthEnabled: cfg.AdminAuthEnabled, AdminUsername: cfg.AdminUsername,
AdminPasswordSet: cfg.AdminPassword != "", SavedAdminPassword: cfg.AdminPassword,
SavedAuthRecovery: cfg.AuthRecovery,
BuildNativeNonstream: cfg.BuildNativeNonstream,
NonstreamKeepalive: cfg.NonstreamKeepalive, FakeStream: cfg.FakeStream, YouTubeLinks: cfg.YouTubeLinks,
SearchModelAliases: cfg.SearchModelAliases, DiscoverHiddenModels: cfg.DiscoverHiddenModels, GoogleSearch: cfg.GoogleSearch, StripThoughtSignatures: cfg.StripThoughtSignatures,
Expand Down
65 changes: 65 additions & 0 deletions internal/app/admin_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
Expand Down Expand Up @@ -72,3 +73,67 @@ func TestAdminConfig(t *testing.T) {
t.Fatal(err)
}
}

// TestAuthRecoveryLifecycle 核对保存与运行的 AUTH_RECOVERY 不一致的两个方向都标为需要重启,一致则不标,无关保存保留 .env 与环境变量取值
func TestAuthRecoveryLifecycle(t *testing.T) {
path := filepath.Join(t.TempDir(), ".env")
cfg := config.Default()
cfg.AuthRecovery = false
if err := cfg.Save(path); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
pool := aistudio.NewAccountPool(nil, 1)
admin := &runtimeAdmin{configPath: path, requests: newRequestRegistry(ctx), pool: pool, service: &trackedService{pool: pool}}
manager := &runtimeManager{}

value, err := admin.RuntimeConfig(ctx)
if err != nil {
t.Fatal(err)
}
if value.SavedAuthRecovery {
t.Fatal("SavedAuthRecovery 未载入保存值")
}
raw, err := json.Marshal(value)
if err != nil || strings.Contains(string(raw), "saved_auth_recovery") {
t.Fatalf("保存值泄漏到前端配置: %s", raw)
}

active := config.Default()
if decorated := manager.decorateRuntimeConfig(value, active); !decorated.ServiceRestartRequired {
t.Fatal("保存 false、运行 true 未标为需要重启")
}
active.AuthRecovery = false
if decorated := manager.decorateRuntimeConfig(value, active); decorated.ServiceRestartRequired {
t.Fatal("保存与运行一致仍标为需要重启")
}

t.Setenv("AUTH_RECOVERY", "true")
value, err = admin.RuntimeConfig(ctx)
if err != nil {
t.Fatal(err)
}
if !value.SavedAuthRecovery {
t.Fatal("环境变量决定的 AUTH_RECOVERY 未进入重启判定")
}
if decorated := manager.decorateRuntimeConfig(value, active); !decorated.ServiceRestartRequired {
t.Fatal("环境变量 true、运行 false 未标为需要重启")
}
value.AutoStart = true
updated, err := admin.UpdateRuntimeConfig(ctx, value)
if err != nil {
t.Fatal(err)
}
if !updated.SavedAuthRecovery {
t.Fatal("无关保存丢失了环境变量决定的 AUTH_RECOVERY")
}
saved, err := config.Load(path)
if err != nil || !saved.AuthRecovery {
t.Fatalf("保存值被改写: %+v err=%v", saved, err)
}
content, err := os.ReadFile(path)
if err != nil || !strings.Contains(string(content), "AUTH_RECOVERY=false") {
t.Fatalf(".env 原值被改写: %s err=%v", content, err)
}
}
11 changes: 9 additions & 2 deletions internal/app/auth_retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ type authRuntimeRefresher struct {
boundLocks sync.Map
globalProxy string
requests *requestRegistry
// authRecovery 为 false 时账户认证失败不读取续签材料,直接标记需要重新登录
authRecovery bool
}

// authRetryTransport 为普通 RPC 执行一次认证续签重试
Expand Down Expand Up @@ -156,14 +158,16 @@ func newAuthRuntimeRefresher(
workers *accountWorkerManager,
requests *requestRegistry,
globalProxy string,
authRecovery bool,
) *authRuntimeRefresher {
return &authRuntimeRefresher{
pool: workers.pool,
refresh: chromeauth.Refresh, importCurrent: importCurrentChromeState, chromeHas: chromeIdentityImportable,
reset: workers.Reset, prepareWorker: workers.prepareUpdate,
rotate: chromeauth.RotateBoundCookies, mergeWorker: workers.MergeCookies,
globalProxy: globalProxy,
requests: requests,
globalProxy: globalProxy,
requests: requests,
authRecovery: authRecovery,
}
}

Expand Down Expand Up @@ -249,6 +253,9 @@ func (refresher *authRuntimeRefresher) Recover(ctx context.Context, cause error,
if errors.As(cause, &startup) && startup.authHandled {
return cause
}
if !refresher.authRecovery {
return refresher.markAuthenticationRequired(ctx, cause)
}
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
if refresher.Available(ctx) {
if err := refresher.Refresh(ctx, generation); err == nil {
return nil
Expand Down
103 changes: 103 additions & 0 deletions internal/app/auth_retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ package app

import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"testing"

"github.com/Mag1cFall/AIStudio2API/internal/aistudio"
"github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative"
)

// TestAuthRefreshWithoutExtension 验证缺少续签扩展的账户从当前 Chrome 导入同一邮箱并写回扩展,重新登录保留扩展
Expand Down Expand Up @@ -73,3 +76,103 @@ func TestAuthRefreshWithoutExtension(t *testing.T) {
t.Fatalf("重新登录丢失续签扩展: %+v", kept)
}
}

// newAuthRecoveryFixture 创建有一个账户、已注入账户租约上下文的续签测试环境
func newAuthRecoveryFixture(t *testing.T) (*aistudio.Account, *aistudio.AccountLease, *aistudio.AccountPool, context.Context) {
t.Helper()
directory := t.TempDir()
storage := filepath.Join(directory, "storage-state.json")
state := `{"cookies":[{"name":"SAPISID","value":"old","domain":".google.com","path":"/","secure":true,"sameSite":"Lax"}],"origins":[]}`
if err := os.WriteFile(storage, []byte(state), 0o600); err != nil {
t.Fatal(err)
}
loaded, err := aistudio.LoadStorageState(storage)
if err != nil {
t.Fatal(err)
}
account := &aistudio.Account{
ID: "user@example.com", Directory: directory, StoragePath: storage,
RuntimePath: filepath.Join(directory, "runtime-state.json"), StorageState: loaded,
Config: aistudio.DefaultAccountConfig("user@example.com"),
}
pool := aistudio.NewAccountPool([]*aistudio.Account{account}, 1)
lease, err := pool.AcquireAccount(t.Context(), account.ID)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { lease.Release() })
return account, lease, pool, aistudio.ContextWithAccountLease(t.Context(), lease)
}

// TestAuthRecoveryDisabledMarksRequired 验证关闭续签时认证失败不读取续签材料,账户仍按官网确认的结果标记为需要重新登录
func TestAuthRecoveryDisabledMarksRequired(t *testing.T) {
account, lease, pool, ctx := newAuthRecoveryFixture(t)
used := false
refresher := &authRuntimeRefresher{
pool: pool, requests: newRequestRegistry(t.Context()), authRecovery: false,
refresh: func(context.Context, aistudio.AuthSource, aistudio.ChromeOAuthMaterial, string) ([]aistudio.StateCookie, *aistudio.BoundSession, error) {
used = true
return nil, nil, nil
},
importCurrent: func(context.Context, aistudio.AuthSource, *aistudio.ChromeOAuthMaterial, string) (aistudio.StorageState, error) {
used = true
return aistudio.StorageState{}, nil
},
chromeHas: func(email string) bool { return email == account.ID },
reset: func(string) error { return nil },
}
if !refresher.Available(ctx) {
t.Fatal("账户在 Chrome 中登录但被判定为不可续签")
}
cause := fmt.Errorf("%w: test", camoufoxnative.ErrAuthenticationRequired)
err := refresher.Recover(ctx, cause, lease.AuthGeneration())
if err == nil || !errors.Is(err, camoufoxnative.ErrAuthenticationRequired) {
t.Fatalf("Recover err = %v", err)
}
if used {
t.Fatal("关闭续签后仍读取了续签材料")
}
if account.State != aistudio.AccountAuthRequired {
t.Fatalf("account.State = %v", account.State)
}
}

// TestAuthRecoveryEnabledRenews 验证默认开启续签时认证失败按账户保存的材料原地续签
func TestAuthRecoveryEnabledRenews(t *testing.T) {
account, lease, pool, ctx := newAuthRecoveryFixture(t)
var cookies []aistudio.StateCookie
for _, name := range []string{"SAPISID", "__Secure-1PAPISID", "__Secure-3PAPISID"} {
cookies = append(cookies, aistudio.StateCookie{Name: name, Value: "renewed", Domain: ".google.com", Path: "/", Expires: -1, Secure: true, SameSite: "Lax"})
}
imported := false
refresher := &authRuntimeRefresher{
pool: pool, requests: newRequestRegistry(t.Context()), authRecovery: true,
refresh: func(context.Context, aistudio.AuthSource, aistudio.ChromeOAuthMaterial, string) ([]aistudio.StateCookie, *aistudio.BoundSession, error) {
return nil, nil, fmt.Errorf("没有 OAuth 材料时不应调用 refresh")
},
importCurrent: func(_ context.Context, source aistudio.AuthSource, _ *aistudio.ChromeOAuthMaterial, _ string) (aistudio.StorageState, error) {
imported = true
updated := aistudio.StorageState{Cookies: cookies}
updated.SetAuthExtension(aistudio.AuthExtension{
Source: source, OAuth: &aistudio.ChromeOAuthMaterial{GaiaID: "gaia", RefreshToken: "token"},
})
return updated, nil
},
chromeHas: func(email string) bool { return email == account.ID },
reset: func(string) error { return nil },
}
cause := fmt.Errorf("%w: test", camoufoxnative.ErrAuthenticationRequired)
if err := refresher.Recover(ctx, cause, lease.AuthGeneration()); err != nil {
t.Fatal(err)
}
if !imported {
t.Fatal("开启续签时认证失败没有读取续签材料")
}
stored, err := aistudio.LoadStorageState(account.StoragePath)
if err != nil {
t.Fatal(err)
}
if len(stored.Cookies) == 0 || stored.Cookies[0].Value != "renewed" {
t.Fatalf("续签结果 cookies = %+v", stored.Cookies)
}
}
2 changes: 2 additions & 0 deletions internal/app/lifecycle.go
Original file line number Diff line number Diff line change
Expand Up @@ -723,6 +723,7 @@ func sameDataConfig(value api.RuntimeConfig, active config.Config, overrides dat
UpstreamChannels: value.UpstreamChannels,
ModelMapping: value.ModelMapping,
MaxAccountSwitches: value.MaxAccountSwitches,
AuthRecovery: value.SavedAuthRecovery,
WAABackend: value.WAABackend,
BuildNativeNonstream: value.BuildNativeNonstream,
NonstreamKeepalive: value.NonstreamKeepalive,
Expand All @@ -743,6 +744,7 @@ func sameDataConfig(value api.RuntimeConfig, active config.Config, overrides dat
saved.InitTimeout == active.InitTimeout && saved.RequestTimeout == active.RequestTimeout &&
slices.Equal(saved.UpstreamChannels, active.UpstreamChannels) && saved.ModelMapping == active.ModelMapping &&
saved.MaxAccountSwitches == active.MaxAccountSwitches &&
saved.AuthRecovery == active.AuthRecovery &&
saved.WAABackend == active.WAABackend &&
saved.BuildNativeNonstream == active.BuildNativeNonstream &&
saved.NonstreamKeepalive == active.NonstreamKeepalive && saved.FakeStream == active.FakeStream &&
Expand Down
2 changes: 1 addition & 1 deletion internal/app/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func newRuntime(
protected := aistudio.NewWorkerProtectedTransport(aistudio.WorkerProtectedTransportOptions{
Transport: transport, Workers: workers, SetupTimeout: cfg.InitTimeout,
})
refresher := newAuthRuntimeRefresher(workers, requests, globalProxy)
refresher := newAuthRuntimeRefresher(workers, requests, globalProxy, cfg.AuthRecovery)
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
workers.refresher = refresher
client := aistudio.NewClient(aistudio.ClientOptions{
Transport: &authRetryTransport{transport: transport, refresher: refresher},
Expand Down
5 changes: 5 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ var configKeys = [...]string{
"ROUTING_STRATEGY",
"ACCOUNT_ORDER",
"MAX_ACCOUNT_SWITCHES",
"AUTH_RECOVERY",
"UPSTREAM_CHANNELS",
"MODEL_MAPPING",
"MODEL_CHANNELS",
Expand Down Expand Up @@ -146,6 +147,7 @@ type Config struct {
RoutingStrategy string
AccountOrder string
MaxAccountSwitches int
AuthRecovery bool
UpstreamChannels []string
ModelMapping string
ModelChannels string
Expand Down Expand Up @@ -195,6 +197,7 @@ func Default() Config {
PerAccountConcurrency: defaultAccountConcurrency,
RoutingStrategy: "round-robin",
MaxAccountSwitches: DefaultMaxAccountSwitches,
AuthRecovery: true,
UpstreamChannels: []string{"playground"},
WAABackend: WAABackendSpiderMonkey,
MediaOutput: MediaOutputInline,
Expand Down Expand Up @@ -241,6 +244,7 @@ var configSetters = map[string]func(*Config, string) error{
"WARM_STARTUP_CONCURRENCY": intSetter("WARM_STARTUP_CONCURRENCY", func(c *Config) *int { return &c.WarmStartupConcurrency }),
"PER_ACCOUNT_CONCURRENCY": intSetter("PER_ACCOUNT_CONCURRENCY", func(c *Config) *int { return &c.PerAccountConcurrency }),
"MAX_ACCOUNT_SWITCHES": setMaxAccountSwitches,
"AUTH_RECOVERY": boolSetter("AUTH_RECOVERY", func(c *Config) *bool { return &c.AuthRecovery }),
"INIT_TIMEOUT": durationSetter("INIT_TIMEOUT", func(c *Config) *time.Duration { return &c.InitTimeout }),
"REQUEST_TIMEOUT": durationSetter("REQUEST_TIMEOUT", func(c *Config) *time.Duration { return &c.RequestTimeout }),
"ADMIN_USERNAME": textSetter(func(c *Config) *string { return &c.AdminUsername }, strings.TrimSpace),
Expand Down Expand Up @@ -626,6 +630,7 @@ func (c Config) envValues() map[string]string {
"ROUTING_STRATEGY": c.RoutingStrategy,
"ACCOUNT_ORDER": c.AccountOrder,
"MAX_ACCOUNT_SWITCHES": strconv.Itoa(c.MaxAccountSwitches),
"AUTH_RECOVERY": strconv.FormatBool(c.AuthRecovery),
"UPSTREAM_CHANNELS": strings.Join(c.UpstreamChannels, ","),
"MODEL_MAPPING": c.ModelMapping,
"MODEL_CHANNELS": c.ModelChannels,
Expand Down
Loading