diff --git a/internal/aistudio/auth.go b/internal/aistudio/auth.go index 2b10775d..8f7b1cde 100644 --- a/internal/aistudio/auth.go +++ b/internal/aistudio/auth.go @@ -13,6 +13,7 @@ import ( "strings" "time" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative" ) @@ -198,6 +199,15 @@ func WriteStorageState(filePath string, state StorageState) error { // Validate 校验 storage state 的浏览器字段 func (s StorageState) Validate() error { + if buildpolicy.Conservative { + extension, exists, err := s.AuthExtension() + if err != nil { + return err + } + if exists && (extension.OAuth != nil || extension.Bound != nil) { + return fmt.Errorf("Chrome OAuth and device-bound renewal material are disabled in the conservative trial") + } + } for index, cookie := range s.Cookies { if strings.TrimSpace(cookie.Name) == "" || strings.TrimSpace(cookie.Domain) == "" { return fmt.Errorf("storage state Cookie %d 缺少名称或域", index) @@ -220,6 +230,25 @@ func (s StorageState) Validate() error { return nil } +// ValidateRuntimeState rejects copied states at the live service boundary while +// allowing generic parsers and fixtures to validate their storage shape. +func ValidateRuntimeState(s StorageState) error { + if !buildpolicy.Conservative { + return nil + } + extension, exists, err := s.AuthExtension() + if err != nil { + return err + } + if !exists || extension.Source.Browser != "camoufox" { + return fmt.Errorf("this trial requires state created by sign-in in its runtime browser") + } + if extension.OAuth != nil || extension.Bound != nil { + return fmt.Errorf("Chrome OAuth and device-bound renewal material are disabled in the conservative trial") + } + return nil +} + // CookieHeader 为目标 URL 构造当前有效的 Cookie 请求头 func (s StorageState) CookieHeader(targetURL string, now time.Time) (string, error) { target, err := url.Parse(targetURL) diff --git a/internal/aistudio/conservative_test.go b/internal/aistudio/conservative_test.go new file mode 100644 index 00000000..4aad5bb2 --- /dev/null +++ b/internal/aistudio/conservative_test.go @@ -0,0 +1,30 @@ +//go:build conservative + +package aistudio + +import "testing" + +func TestConservativeAllowsBrowserLoginStateOnlyWithoutRenewalKeys(t *testing.T) { + state := StorageState{Cookies: []StateCookie{{Name: "fixture", Value: "fixture", Domain: ".google.com", Path: "/"}}} + if err := state.Validate(); err != nil { + t.Fatal(err) + } + if err := ValidateRuntimeState(state); err == nil { + t.Fatal("copied cookies accepted at runtime") + } + state.SetAuthExtension(AuthExtension{Source: AuthSource{Browser: "camoufox", Email: "fixture@example.invalid"}}) + if err := state.Validate(); err != nil { + t.Fatal(err) + } + if err := ValidateRuntimeState(state); err != nil { + t.Fatal(err) + } + state.SetAuthExtension(AuthExtension{Source: AuthSource{Browser: "camoufox"}, OAuth: &ChromeOAuthMaterial{RefreshToken: "fixture"}}) + if err := state.Validate(); err == nil { + t.Fatal("OAuth material accepted") + } + state.SetAuthExtension(AuthExtension{Source: AuthSource{Browser: "camoufox"}, Bound: &BoundSession{ID: "fixture"}}) + if err := state.Validate(); err == nil { + t.Fatal("bound renewal accepted") + } +} diff --git a/internal/api/conservative_test.go b/internal/api/conservative_test.go new file mode 100644 index 00000000..4e836c57 --- /dev/null +++ b/internal/api/conservative_test.go @@ -0,0 +1,26 @@ +//go:build conservative + +package api + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestConservativeRejectsPairing(t *testing.T) { + handler := NewHandler(nil, Config{}) + for _, request := range []*http.Request{ + httptest.NewRequest(http.MethodPost, "/api/pairing", nil), + httptest.NewRequest(http.MethodGet, "/api/pairing", nil), + httptest.NewRequest(http.MethodPost, "/api/pairing/accounts", strings.NewReader(`{}`)), + httptest.NewRequest(http.MethodPut, "/api/pairing/accounts/account/cookies", strings.NewReader(`{}`)), + } { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + if recorder.Code != http.StatusForbidden { + t.Fatalf("%s %s = %d", request.Method, request.URL.Path, recorder.Code) + } + } +} diff --git a/internal/api/pairing.go b/internal/api/pairing.go index 27525885..a1262857 100644 --- a/internal/api/pairing.go +++ b/internal/api/pairing.go @@ -10,6 +10,7 @@ import ( "time" "github.com/Mag1cFall/AIStudio2API/internal/aistudio" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" ) // pairingTokenLifetime 是远程配对令牌的有效期 @@ -74,6 +75,10 @@ func (tokens *pairingTokens) valid(token string, now time.Time) bool { // handleActivePairing 返回仍在有效期内的远程配对令牌,没有时返回 404 func (s *server) handleActivePairing(w http.ResponseWriter, _ *http.Request) { + if buildpolicy.Conservative { + writeAdminError(w, http.StatusForbidden, "conservative_trial", "Remote pairing is disabled") + return + } token, ok := s.pairing.active(time.Now()) if !ok { writeAdminError(w, http.StatusNotFound, "pairing_token_missing", "No active pairing token") @@ -84,11 +89,19 @@ func (s *server) handleActivePairing(w http.ResponseWriter, _ *http.Request) { // handleCreatePairing 生成远程配对令牌 func (s *server) handleCreatePairing(w http.ResponseWriter, _ *http.Request) { + if buildpolicy.Conservative { + writeAdminError(w, http.StatusForbidden, "conservative_trial", "Remote pairing is disabled") + return + } writeJSON(w, http.StatusCreated, s.pairing.issue(time.Now())) } // handlePairingAccount 凭配对令牌导入一个账户,不经过管理会话 func (s *server) handlePairingAccount(w http.ResponseWriter, r *http.Request) { + if buildpolicy.Conservative { + writeAdminError(w, http.StatusForbidden, "conservative_trial", "Remote pairing is disabled") + return + } w.Header().Set("Cache-Control", "no-store") token, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") if !s.pairing.valid(strings.TrimSpace(token), time.Now()) { @@ -112,6 +125,10 @@ func (s *server) handlePairingAccount(w http.ResponseWriter, r *http.Request) { // handlePairingRenewal 凭配对上传时签发的续签凭据替换该账户的会话 Cookie,不经过管理会话 func (s *server) handlePairingRenewal(w http.ResponseWriter, r *http.Request) { + if buildpolicy.Conservative { + writeAdminError(w, http.StatusForbidden, "conservative_trial", "Remote renewal is disabled") + return + } w.Header().Set("Cache-Control", "no-store") token, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") r.Body = http.MaxBytesReader(w, r.Body, 1<<20) diff --git a/internal/api/pairing_test.go b/internal/api/pairing_test.go index 2a0cabd8..c37450b5 100644 --- a/internal/api/pairing_test.go +++ b/internal/api/pairing_test.go @@ -1,3 +1,5 @@ +//go:build !conservative + package api import ( diff --git a/internal/app/admin.go b/internal/app/admin.go index 127eafd7..67d6ba56 100644 --- a/internal/app/admin.go +++ b/internal/app/admin.go @@ -16,6 +16,7 @@ import ( "github.com/Mag1cFall/AIStudio2API/internal/aistudio" "github.com/Mag1cFall/AIStudio2API/internal/api" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative" "github.com/Mag1cFall/AIStudio2API/internal/chromeauth" "github.com/Mag1cFall/AIStudio2API/internal/config" @@ -217,6 +218,9 @@ func (admin *runtimeAdmin) ChromeImportProfiles(context.Context) ([]api.ChromeIm // CookieBrowsers 列出本机开启远程调试的浏览器,读取其 Cookie 并识别其中各会话登录 AI Studio 的账户,每个账户一项 func (admin *runtimeAdmin) CookieBrowsers(ctx context.Context) ([]api.CookieBrowser, error) { + if buildpolicy.Conservative { + return nil, invalidAccount(fmt.Errorf("browser discovery is disabled; sign in in the runtime browser")) + } addresses, err := chromeauth.DebugAddresses(ctx) if err != nil { return nil, err @@ -263,6 +267,9 @@ func (admin *runtimeAdmin) readCookieBrowser(ctx context.Context, browser *api.C // DiscoverCookieAccounts 解析粘贴的 Cookie,返回其中各会话登录 AI Studio 的账户 func (admin *runtimeAdmin) DiscoverCookieAccounts(ctx context.Context, input api.CookieImportInput) ([]api.CookieBrowser, error) { + if buildpolicy.Conservative { + return nil, invalidAccount(fmt.Errorf("cross-browser cookie import is disabled; sign in in the runtime browser")) + } state, err := aistudio.ParseCookieText(input.Cookies) if err != nil { return nil, &adminOperationError{status: http.StatusBadRequest, code: "invalid_cookies", message: err.Error()} @@ -368,6 +375,9 @@ func (admin *runtimeAdmin) ImportChromeAccounts(ctx context.Context, input api.C // ImportAccountState 导入远程配对上传或 Cookie 导入的认证状态与 Camoufox 指纹,未给标签时以 Cookie 中第 auth_user 个会话登录的账户邮箱为标签 func (admin *runtimeAdmin) ImportAccountState(ctx context.Context, input api.AccountStateInput) (api.AdminAccount, error) { + if buildpolicy.Conservative { + return api.AdminAccount{}, invalidAccount(fmt.Errorf("external state import is disabled; sign in in the runtime browser")) + } timezone, err := accountTimezone(input.Timezone) if err != nil { return api.AdminAccount{}, invalidAccount(err) @@ -1044,6 +1054,9 @@ func (admin *runtimeAdmin) UpdateRuntimeConfig(_ context.Context, value api.Runt if err := cfg.Validate(); err != nil { return api.RuntimeConfig{}, invalidConfigError(err) } + if err := config.ValidateRuntimePolicy(cfg); err != nil { + return api.RuntimeConfig{}, invalidConfigError(err) + } if err := cfg.Save(admin.configPath); err != nil { return api.RuntimeConfig{}, err } diff --git a/internal/app/admin_config_test.go b/internal/app/admin_config_test.go index fb709a3f..3313a7b1 100644 --- a/internal/app/admin_config_test.go +++ b/internal/app/admin_config_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/Mag1cFall/AIStudio2API/internal/aistudio" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/Mag1cFall/AIStudio2API/internal/config" ) @@ -20,6 +21,7 @@ func TestAdminConfig(t *testing.T) { cfg.AdminAuthEnabled = true cfg.AdminUsername = "operator" cfg.AdminPassword = "test-password" + cfg.ProxyAPIKey = "fixture-key" if err := cfg.Save(path); err != nil { t.Fatal(err) } @@ -68,7 +70,12 @@ func TestAdminConfig(t *testing.T) { t.Fatalf("empty enabled password error = %v", err) } value.AdminAuthEnabled = false - if _, err := admin.UpdateRuntimeConfig(ctx, value); err != nil { + _, err = admin.UpdateRuntimeConfig(ctx, value) + if buildpolicy.Conservative { + if !errors.As(err, &status) || status.HTTPStatus() != http.StatusBadRequest { + t.Fatalf("disabled conservative admin auth error = %v", err) + } + } else if err != nil { t.Fatal(err) } } diff --git a/internal/app/app.go b/internal/app/app.go index 969cbc22..262e1575 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -201,6 +201,9 @@ func parseFlags(args []string, cfg *config.Config) (commandOptions, error) { if err := cfg.Validate(); err != nil { return commandOptions{}, err } + if err := config.ValidateRuntimePolicy(*cfg); err != nil { + return commandOptions{}, err + } options := commandOptions{openUI: *openUI} flags.Visit(func(value *flag.Flag) { switch value.Name { diff --git a/internal/app/auth_retry.go b/internal/app/auth_retry.go index 76a73f1a..908e7cdf 100644 --- a/internal/app/auth_retry.go +++ b/internal/app/auth_retry.go @@ -12,6 +12,7 @@ import ( "github.com/Mag1cFall/AIStudio2API/internal/aistudio" "github.com/Mag1cFall/AIStudio2API/internal/api" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative" "github.com/Mag1cFall/AIStudio2API/internal/chromeauth" ) @@ -274,7 +275,7 @@ func (refresher *authRuntimeRefresher) do(ctx context.Context, method string, se if !aistudio.DefinitiveAuthenticationFailure(err) { return response, err } - if attempt == 1 { + if !authenticationRecoveryAllowed(attempt) { return nil, refresher.markAuthenticationRequired(ctx, err) } if err := refresher.Recover(ctx, err, generation); err != nil { @@ -283,6 +284,10 @@ func (refresher *authRuntimeRefresher) do(ctx context.Context, method string, se } } +func authenticationRecoveryAllowed(attempt int) bool { + return !buildpolicy.Conservative && attempt < 1 +} + // Do 在 401 后续签同一账户并重放一次请求 func (transport *authRetryTransport) Do(ctx context.Context, request aistudio.RPCRequest) (*aistudio.RPCResponse, error) { return transport.refresher.do(ctx, request.Method, func() (*aistudio.RPCResponse, error) { diff --git a/internal/app/auth_retry_test.go b/internal/app/auth_retry_test.go index 35fb4425..076968ca 100644 --- a/internal/app/auth_retry_test.go +++ b/internal/app/auth_retry_test.go @@ -1,3 +1,5 @@ +//go:build !conservative + package app import ( diff --git a/internal/app/conservative_maintenance_test.go b/internal/app/conservative_maintenance_test.go new file mode 100644 index 00000000..c7c84580 --- /dev/null +++ b/internal/app/conservative_maintenance_test.go @@ -0,0 +1,90 @@ +//go:build conservative + +package app + +import ( + "context" + "testing" + "testing/synctest" + "time" + + "github.com/Mag1cFall/AIStudio2API/internal/aistudio" +) + +type conservativeMaintenanceCatalog struct { + modelCatalogService + models []aistudio.Model + refreshed int + expired int + idle int + patrolled int +} + +func (catalog *conservativeMaintenanceCatalog) RefreshAccountModels(context.Context, string, bool) ([]aistudio.Model, error) { + catalog.refreshed++ + return catalog.models, nil +} + +func (catalog *conservativeMaintenanceCatalog) CachedModels() []aistudio.Model { + return catalog.models +} + +func (catalog *conservativeMaintenanceCatalog) ReclaimExpiredResources(context.Context) error { + catalog.expired++ + return nil +} + +func (catalog *conservativeMaintenanceCatalog) ReclaimIdleAssistantApplets(context.Context) error { + catalog.idle++ + return nil +} + +func (catalog *conservativeMaintenanceCatalog) RefreshAccountState(context.Context, string, bool) (aistudio.AccountRefresh, error) { + catalog.patrolled++ + return aistudio.AccountRefresh{}, nil +} + +func TestConservativeMaintenanceRecoversCatalogAndReclaims(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + catalog := &conservativeMaintenanceCatalog{models: []aistudio.Model{{ID: "fixture-model"}}} + account := &aistudio.Account{ID: "fixture", Config: aistudio.DefaultAccountConfig("fixture"), State: aistudio.AccountReady} + service := &trackedService{ + lifecycle: ctx, catalog: catalog, pool: aistudio.NewAccountPool([]*aistudio.Account{account}, 1), + requests: newRequestRegistry(ctx), timeout: time.Minute, + modelRetries: map[string]struct{}{account.ID: {}}, + } + done := make(chan struct{}) + go func() { + service.retryModelCatalogs(ctx, time.Now()) + close(done) + }() + synctest.Wait() + if catalog.expired != 1 || catalog.idle != 1 { + t.Fatalf("startup cleanup: expired=%d idle=%d", catalog.expired, catalog.idle) + } + time.Sleep(modelCatalogRetryInterval) + synctest.Wait() + if catalog.refreshed != 1 || service.modelRetryPending(account.ID) || len(service.modelSnapshot()) != 1 { + t.Fatalf("pending catalog did not recover: refreshed=%d pending=%t models=%d", catalog.refreshed, service.modelRetryPending(account.ID), len(service.modelSnapshot())) + } + time.Sleep(idleResourceReclaimInterval - modelCatalogRetryInterval) + synctest.Wait() + if catalog.expired != 2 || catalog.idle != 2 || catalog.refreshed != 1 { + t.Fatalf("periodic cleanup: expired=%d idle=%d refreshed=%d", catalog.expired, catalog.idle, catalog.refreshed) + } + time.Sleep(accountStateRefreshInterval) + synctest.Wait() + if catalog.patrolled != 0 || catalog.refreshed != 1 { + t.Fatalf("unsolicited account polling: patrolled=%d refreshed=%d", catalog.patrolled, catalog.refreshed) + } + cancel() + synctest.Wait() + select { + case <-done: + default: + t.Fatal("maintenance did not stop on cancellation") + } + }) +} diff --git a/internal/app/conservative_test.go b/internal/app/conservative_test.go new file mode 100644 index 00000000..eef51fd5 --- /dev/null +++ b/internal/app/conservative_test.go @@ -0,0 +1,46 @@ +//go:build conservative + +package app + +import ( + "errors" + "fmt" + "net/http" + "testing" + "time" + + "github.com/Mag1cFall/AIStudio2API/internal/aistudio" +) + +func TestConservativeAllowsOnlyQuotaAccountFallback(t *testing.T) { + if authenticationRecoveryAllowed(0) { + t.Fatal("authentication recovery enabled") + } + if !generationAttemptAllowed(0, nil) { + t.Fatal("first generation disabled") + } + planLimit := &aistudio.RPCError{StatusCode: http.StatusTooManyRequests, Message: "You have reached your usage limit"} + dailyLimit := &aistudio.RPCError{StatusCode: http.StatusTooManyRequests, Metadata: map[string]string{"quota_metric": "generate_requests_per_day"}} + for name, test := range map[string]struct { + err error + allowed bool + }{ + "plan": {planLimit, true}, + "daily": {dailyLimit, true}, + "wrapped": {fmt.Errorf("attempt failed: %w", planLimit), true}, + "network": {errors.New("connection reset"), false}, + "auth": {&aistudio.RPCError{StatusCode: http.StatusUnauthorized}, false}, + "server": {&aistudio.RPCError{StatusCode: http.StatusBadGateway}, false}, + "shortQuota": {&aistudio.RPCError{StatusCode: http.StatusTooManyRequests, RetryDelay: time.Minute}, false}, + "noFailure": {nil, false}, + } { + t.Run(name, func(t *testing.T) { + if got := generationAttemptAllowed(1, test.err); got != test.allowed { + t.Fatalf("generation retry allowed = %v, want %v", got, test.allowed) + } + }) + } + if !generationAttemptAllowed(1, planLimit) || generationAttemptAllowed(2, errors.New("connection reset")) { + t.Fatal("an earlier quota failure authorized a later non-quota replay") + } +} diff --git a/internal/app/lifecycle.go b/internal/app/lifecycle.go index 927cac07..a4732a69 100644 --- a/internal/app/lifecycle.go +++ b/internal/app/lifecycle.go @@ -186,6 +186,10 @@ func (manager *runtimeManager) startService(ctx context.Context) (api.AdminStatu manager.finishStart(launchCancel) return api.AdminStatus{}, err } + if err := config.ValidateRuntimePolicy(cfg); err != nil { + manager.finishStart(launchCancel) + return api.AdminStatus{}, err + } next, err := manager.factory(launchCtx, manager.lifecycle, cfg, manager.requests) if err != nil { diff --git a/internal/app/runtime.go b/internal/app/runtime.go index 331e49e4..8248b21a 100644 --- a/internal/app/runtime.go +++ b/internal/app/runtime.go @@ -17,6 +17,7 @@ import ( "github.com/Mag1cFall/AIStudio2API/internal/aistudio" "github.com/Mag1cFall/AIStudio2API/internal/api" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/Mag1cFall/AIStudio2API/internal/config" ) @@ -37,6 +38,11 @@ func newRuntime( if err != nil { return nil, nil, nil, err } + for _, account := range accounts { + if err := aistudio.ValidateRuntimeState(account.StorageState); err != nil { + return nil, nil, nil, fmt.Errorf("account %s: %w", account.ID, err) + } + } if err := launchCtx.Err(); err != nil { return nil, nil, nil, err } @@ -839,7 +845,9 @@ func (service *trackedService) syncAccountModels(ctx context.Context, accountID func (service *trackedService) retryModelCatalogs(ctx context.Context, startedAt time.Time) { var patrol sync.WaitGroup defer patrol.Wait() - patrol.Go(func() { service.patrolAccountStates(ctx, startedAt) }) + if !buildpolicy.Conservative { + patrol.Go(func() { service.patrolAccountStates(ctx, startedAt) }) + } service.reclaimIdleAssistantApplets(ctx) service.reclaimExpiredResources(ctx) ticker := time.NewTicker(modelCatalogRetryInterval) @@ -1802,7 +1810,7 @@ func (service *trackedService) generateWithRetry( var activity *upstreamActivity var err error copyFiles := false - for attempt := 0; attempt < retry.maxAttempts; attempt++ { + for attempt := 0; attempt < retry.maxAttempts && generationAttemptAllowed(attempt, err); attempt++ { selectionAccountID := requestedAccountID recoveringAccount := retry.recoveryAccountID != "" if retry.recoveryAccountID != "" { @@ -2005,6 +2013,16 @@ func (service *trackedService) generateWithRetry( ) } +func generationAttemptAllowed(attempt int, lastError error) bool { + if !buildpolicy.Conservative || attempt == 0 { + return true + } + // Only the immediately preceding plan/daily rejection permits another account. + // An earlier quota failure must not authorize a later non-quota replay. + cooldown, quotaFailure := aistudio.QuotaCooldownForError(lastError, time.Now()) + return quotaFailure && aistudio.RequestQuotaCooldown(cooldown.Reason) +} + // markAttemptAccount 把访问日志与活动请求的执行账户与通道记为该租约 func (service *trackedService) markAttemptAccount(requestCtx context.Context, requestID, modelID string, lease *aistudio.AccountLease) { label := lease.Account().Config.Label @@ -2170,6 +2188,9 @@ func (service *trackedService) settleAttempt( retry *generateRetry, mayRecover bool, ) attemptOutcome { + if buildpolicy.Conservative { + mayRecover = false + } err := attempt.err lease := attempt.lease accountID, accountLabel := lease.Account().ID, attempt.accountLabel diff --git a/internal/app/update.go b/internal/app/update.go index 047e187c..2822e61f 100644 --- a/internal/app/update.go +++ b/internal/app/update.go @@ -29,6 +29,7 @@ import ( "golang.org/x/mod/semver" "github.com/Mag1cFall/AIStudio2API/internal/api" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" ) // releaseAPI 为 GitHub 最新发行版本接口 @@ -88,6 +89,9 @@ func newSelfUpdater(version, executable string, proxy func() string, log func(le // updateMode 返回更新方式:managed 由分发方更新,binary 可原地替换,container 随镜像更新,development 为源码构建 func updateMode(version string) string { + if buildpolicy.Conservative { + return "development" + } if managedBy != "" { return "managed" } diff --git a/internal/buildpolicy/conservative.go b/internal/buildpolicy/conservative.go new file mode 100644 index 00000000..4a746b01 --- /dev/null +++ b/internal/buildpolicy/conservative.go @@ -0,0 +1,6 @@ +//go:build conservative + +package buildpolicy + +// Conservative is a local trial profile, not an upstream release policy. +const Conservative = true diff --git a/internal/buildpolicy/default.go b/internal/buildpolicy/default.go new file mode 100644 index 00000000..8d0c908a --- /dev/null +++ b/internal/buildpolicy/default.go @@ -0,0 +1,5 @@ +//go:build !conservative + +package buildpolicy + +const Conservative = false diff --git a/internal/camoufoxnative/conservative_test.go b/internal/camoufoxnative/conservative_test.go new file mode 100644 index 00000000..3c0ab897 --- /dev/null +++ b/internal/camoufoxnative/conservative_test.go @@ -0,0 +1,16 @@ +//go:build conservative + +package camoufoxnative + +import ( + "context" + "testing" +) + +func TestConservativeSkipsDriveConsent(t *testing.T) { + called := false + err := optionalDriveAuthorization(context.Background(), "fixture@example.invalid", func(context.Context, string) error { called = true; return nil }) + if err != nil || called { + t.Fatalf("unexpected authorization: called=%v err=%v", called, err) + } +} diff --git a/internal/camoufoxnative/login.go b/internal/camoufoxnative/login.go index 41dc679d..c7cc37a2 100644 --- a/internal/camoufoxnative/login.go +++ b/internal/camoufoxnative/login.go @@ -14,6 +14,7 @@ import ( "strings" "time" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/gorilla/websocket" ) @@ -100,7 +101,7 @@ func Login(ctx context.Context, options LoginOptions) (result LoginResult, err e if email == "" { return LoginResult{}, errors.New("AI Studio 页面没有登录邮箱") } - driveErr := session.authorizeDrive(loginCtx, email) + driveErr := optionalDriveAuthorization(loginCtx, email, session.authorizeDrive) if err := loginCtx.Err(); err != nil { return LoginResult{}, err } @@ -129,6 +130,13 @@ func errorText(err error) string { return err.Error() } +func optionalDriveAuthorization(ctx context.Context, email string, authorize func(context.Context, string) error) error { + if buildpolicy.Conservative { + return nil + } + return authorize(ctx, email) +} + func startLoginSession(ctx context.Context, options LoginOptions, state storageState) (*loginSession, error) { ffVersion := camoufoxFirefoxMajor fingerprintPath := filepath.Join(options.Directory, "storage-state.json") diff --git a/internal/chromeauth/abe_unsupported.go b/internal/chromeauth/abe_unsupported.go index 6f93c0aa..6487e2a1 100644 --- a/internal/chromeauth/abe_unsupported.go +++ b/internal/chromeauth/abe_unsupported.go @@ -1,4 +1,4 @@ -//go:build !windows || !amd64 +//go:build (!windows || !amd64) && !conservative package chromeauth diff --git a/internal/chromeauth/abe_windows_amd64.go b/internal/chromeauth/abe_windows_amd64.go index 4657254a..87cbd552 100644 --- a/internal/chromeauth/abe_windows_amd64.go +++ b/internal/chromeauth/abe_windows_amd64.go @@ -1,4 +1,4 @@ -//go:build windows && amd64 +//go:build windows && amd64 && !conservative package chromeauth diff --git a/internal/chromeauth/cdp.go b/internal/chromeauth/cdp.go index 96601d54..27eb4e62 100644 --- a/internal/chromeauth/cdp.go +++ b/internal/chromeauth/cdp.go @@ -11,6 +11,7 @@ import ( "slices" "strings" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/gorilla/websocket" ) @@ -23,6 +24,9 @@ type CDPBrowser struct { // ReadCDPBrowser 经 Chromium 远程调试地址读取浏览器全部未分区 Cookie,并在第一个页面中读取 navigator.language 与 Intl 时区,没有页面时语言与时区为空 func ReadCDPBrowser(ctx context.Context, address string) (CDPBrowser, error) { + if buildpolicy.Conservative { + return CDPBrowser{}, fmt.Errorf("browser cookie extraction is disabled in the conservative trial") + } endpoint, err := cdpBrowserEndpoint(ctx, address) if err != nil { return CDPBrowser{}, err diff --git a/internal/chromeauth/conservative_test.go b/internal/chromeauth/conservative_test.go new file mode 100644 index 00000000..750da387 --- /dev/null +++ b/internal/chromeauth/conservative_test.go @@ -0,0 +1,29 @@ +//go:build conservative + +package chromeauth + +import ( + "context" + "testing" +) + +func TestConservativeRejectsCredentialAccess(t *testing.T) { + if Supported { + t.Fatal("Chrome import advertised") + } + if _, err := DefaultChromeRoot(); err == nil { + t.Fatal("profile lookup enabled") + } + if _, err := Discover("must-not-be-read"); err == nil { + t.Fatal("discovery enabled") + } + if _, err := retrieveV20Key("must-not-be-read"); err == nil { + t.Fatal("ABE access enabled") + } + if _, err := openDeviceBindingKey([]byte("fixture")); err == nil { + t.Fatal("device key access enabled") + } + if _, err := ReadCDPBrowser(context.Background(), "http://127.0.0.1:1"); err == nil { + t.Fatal("CDP cookie import enabled") + } +} diff --git a/internal/chromeauth/ncrypt_other.go b/internal/chromeauth/ncrypt_other.go index 6f9e1607..f992f8a3 100644 --- a/internal/chromeauth/ncrypt_other.go +++ b/internal/chromeauth/ncrypt_other.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build !windows && !conservative package chromeauth diff --git a/internal/chromeauth/ncrypt_windows.go b/internal/chromeauth/ncrypt_windows.go index 33ab2673..f870e340 100644 --- a/internal/chromeauth/ncrypt_windows.go +++ b/internal/chromeauth/ncrypt_windows.go @@ -1,4 +1,4 @@ -//go:build windows +//go:build windows && !conservative package chromeauth diff --git a/internal/chromeauth/platform_conservative.go b/internal/chromeauth/platform_conservative.go new file mode 100644 index 00000000..3e00adf2 --- /dev/null +++ b/internal/chromeauth/platform_conservative.go @@ -0,0 +1,18 @@ +//go:build conservative + +package chromeauth + +import "errors" + +const Supported = false + +var errConservative = errors.New("this trial requires login in its own browser; Chrome profile/key extraction and OAuth recovery are disabled") + +func DefaultChromeRoot() (string, error) { return "", errConservative } +func ensurePlatformImport() error { return errConservative } +func Discover(string) ([]Account, error) { return nil, errConservative } +func readTokenService(string, string, string) (string, []byte, []byte, error) { + return "", nil, nil, errConservative +} +func retrieveV20Key(string) ([]byte, error) { return nil, errConservative } +func openDeviceBindingKey([]byte) (deviceBindingKey, error) { return nil, errConservative } diff --git a/internal/chromeauth/platform_other.go b/internal/chromeauth/platform_other.go index aeec9b15..552c5d3d 100644 --- a/internal/chromeauth/platform_other.go +++ b/internal/chromeauth/platform_other.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build !windows && !conservative package chromeauth diff --git a/internal/chromeauth/platform_windows.go b/internal/chromeauth/platform_windows.go index 0861af92..949f84f2 100644 --- a/internal/chromeauth/platform_windows.go +++ b/internal/chromeauth/platform_windows.go @@ -1,4 +1,4 @@ -//go:build windows +//go:build windows && !conservative package chromeauth diff --git a/internal/chromeauth/platform_windows_test.go b/internal/chromeauth/platform_windows_test.go index 0b37752b..02319049 100644 --- a/internal/chromeauth/platform_windows_test.go +++ b/internal/chromeauth/platform_windows_test.go @@ -1,4 +1,4 @@ -//go:build windows +//go:build windows && !conservative package chromeauth diff --git a/internal/config/config.go b/internal/config/config.go index 77e3ee1d..bf122946 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -4,6 +4,7 @@ import ( "bufio" "bytes" "fmt" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "net" "net/url" "os" @@ -158,7 +159,7 @@ var workerDefaultKeys = []string{"WARM_WORKER_LIMIT", "MAX_ACTIVE_WORKERS"} // defaultsFor 返回 WAA 后端为 backend 时的默认配置,Camoufox 后端的常驻预热账户数与活动 Worker 上限较小 func defaultsFor(backend string) Config { cfg := Default() - if backend == WAABackendCamoufox { + if backend == WAABackendCamoufox && !buildpolicy.Conservative { cfg.WarmWorkerLimit, cfg.MaxActiveWorkers = camoufoxWarmWorkerLimit, camoufoxMaxActiveWorkers } return cfg @@ -166,7 +167,7 @@ func defaultsFor(backend string) Config { // Default 返回可直接启动的默认配置 func Default() Config { - return Config{ + cfg := Config{ AdminUsername: "admin", LogFile: true, LogMaxTotalMB: 500, @@ -191,6 +192,17 @@ func Default() Config { WAABackend: WAABackendSpiderMonkey, MediaOutput: MediaOutputInline, } + if buildpolicy.Conservative { + cfg.AdminAuthEnabled = true + cfg.WAABackend = WAABackendCamoufox + cfg.FirstEventHedge = FirstEventHedgeOff + cfg.PerAccountConcurrency, cfg.WarmStartupConcurrency = 1, 1 + cfg.WarmWorkerLimit, cfg.MaxActiveWorkers = 1, 1 + cfg.SearchModelAliases, cfg.ContinuationRewrite = false, false + cfg.LogMaxTotalMB = 20 + cfg.RoutingStrategy = "fill-first" + } + return cfg } // InvalidValue 是加载时取值无效、改用默认值的配置项 @@ -664,6 +676,9 @@ func appendEnv(path, key, value string) error { // Validate 校验配置值是否能用于服务启动 func (c Config) Validate() error { + if err := validateConservative(c); err != nil { + return err + } if c.AdminAuthEnabled && (strings.TrimSpace(c.AdminUsername) == "" || strings.TrimSpace(c.AdminPassword) == "") { return fmt.Errorf("开启管理登录需要 ADMIN_USERNAME 与 ADMIN_PASSWORD") } diff --git a/internal/config/conservative.go b/internal/config/conservative.go new file mode 100644 index 00000000..e110eacf --- /dev/null +++ b/internal/config/conservative.go @@ -0,0 +1,54 @@ +package config + +import ( + "fmt" + "net" + "strings" + + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" +) + +func validateConservative(c Config) error { + if !buildpolicy.Conservative { + return nil + } + for _, address := range []string{c.ListenAddr, c.PreviewListenAddr} { + host, _, err := net.SplitHostPort(address) + if err != nil || net.ParseIP(host) == nil || !net.ParseIP(host).IsLoopback() { + return fmt.Errorf("conservative trial requires literal loopback listeners") + } + } + if !c.AdminAuthEnabled || strings.TrimSpace(c.AdminPassword) == "" { + return fmt.Errorf("conservative trial requires separate management authentication") + } + switch { + case c.WAABackend != WAABackendCamoufox: + return fmt.Errorf("conservative trial requires WAA_BACKEND=camoufox") + case c.FirstEventHedge != FirstEventHedgeOff: + return fmt.Errorf("conservative trial requires FIRST_EVENT_HEDGE=off") + case c.PerAccountConcurrency != 1: + return fmt.Errorf("conservative trial requires PER_ACCOUNT_CONCURRENCY=1") + case c.MaxActiveWorkers != 1: + return fmt.Errorf("conservative trial requires MAX_ACTIVE_WORKERS=1") + case c.WarmStartupConcurrency != 1: + return fmt.Errorf("conservative trial requires WARM_STARTUP_CONCURRENCY=1") + case c.WarmWorkerLimit > 1: + return fmt.Errorf("conservative trial requires WARM_WORKER_LIMIT<=1") + } + if c.RequestBodyLog || c.FakeStream || c.StripThoughtSignatures || c.ContinuationRewrite || len(c.UpstreamChannels) != 1 || c.UpstreamChannels[0] != "playground" { + return fmt.Errorf("conservative trial requires native Playground responses and disabled body logging") + } + return nil +} + +// ValidateRuntimePolicy covers the credential-independent Config structure and +// the secret that must be present before the local service can start or persist. +func ValidateRuntimePolicy(c Config) error { + if err := validateConservative(c); err != nil { + return err + } + if buildpolicy.Conservative && strings.TrimSpace(c.ProxyAPIKey) == "" { + return fmt.Errorf("conservative trial requires a local API key") + } + return nil +} diff --git a/internal/config/conservative_test.go b/internal/config/conservative_test.go new file mode 100644 index 00000000..9cc2eb2e --- /dev/null +++ b/internal/config/conservative_test.go @@ -0,0 +1,72 @@ +//go:build conservative + +package config + +import ( + "strings" + "testing" +) + +func TestConservativeConfiguration(t *testing.T) { + base := Default() + base.ProxyAPIKey = "fixture" + base.AdminPassword = "separate-management-secret" + if err := base.Validate(); err != nil { + t.Fatal(err) + } + if err := ValidateRuntimePolicy(base); err != nil { + t.Fatal(err) + } + for name, change := range map[string]func(*Config){ + "public": func(c *Config) { c.ListenAddr = "0.0.0.0:2048" }, + "preview": func(c *Config) { c.PreviewListenAddr = "0.0.0.0:2050" }, + "adminAuth": func(c *Config) { c.AdminAuthEnabled = false }, + "adminSecret": func(c *Config) { c.AdminPassword = "" }, + "hedge": func(c *Config) { c.FirstEventHedge = "auto" }, + "concurrency": func(c *Config) { c.PerAccountConcurrency = 2 }, + "workers": func(c *Config) { c.MaxActiveWorkers = 2 }, + "emulation": func(c *Config) { c.WAABackend = WAABackendSpiderMonkey }, + "bodylog": func(c *Config) { c.RequestBodyLog = true }, + "fakeStream": func(c *Config) { c.FakeStream = true }, + "signatures": func(c *Config) { c.StripThoughtSignatures = true }, + "rewrite": func(c *Config) { c.ContinuationRewrite = true }, + "build": func(c *Config) { c.UpstreamChannels = []string{"build"} }, + } { + t.Run(name, func(t *testing.T) { + cfg := base + change(&cfg) + if err := ValidateRuntimePolicy(cfg); err == nil { + t.Fatal("restriction not enforced") + } + }) + } + base.ProxyAPIKey = "" + if err := base.Validate(); err != nil { + t.Fatal(err) + } + if err := ValidateRuntimePolicy(base); err == nil { + t.Fatal("empty API key accepted at runtime") + } +} + +func TestConservativeReportsInvalidWorkerSetting(t *testing.T) { + for key, change := range map[string]func(*Config){ + "WAA_BACKEND": func(c *Config) { c.WAABackend = WAABackendSpiderMonkey }, + "FIRST_EVENT_HEDGE": func(c *Config) { c.FirstEventHedge = "auto" }, + "PER_ACCOUNT_CONCURRENCY": func(c *Config) { c.PerAccountConcurrency = 2 }, + "MAX_ACTIVE_WORKERS": func(c *Config) { c.MaxActiveWorkers = 2 }, + "WARM_STARTUP_CONCURRENCY": func(c *Config) { c.WarmStartupConcurrency = 2 }, + "WARM_WORKER_LIMIT": func(c *Config) { c.WarmWorkerLimit = 2 }, + } { + t.Run(key, func(t *testing.T) { + cfg := Default() + cfg.AdminPassword = "fixture-management-secret" + cfg.ProxyAPIKey = "fixture-key" + change(&cfg) + err := ValidateRuntimePolicy(cfg) + if err == nil || !strings.Contains(err.Error(), key) { + t.Fatalf("expected actionable %s error, got %v", key, err) + } + }) + } +} diff --git a/internal/config/env_test.go b/internal/config/env_test.go index b7a1e511..870f203f 100644 --- a/internal/config/env_test.go +++ b/internal/config/env_test.go @@ -1,3 +1,5 @@ +//go:build !conservative + package config import ( diff --git a/internal/setup/setup.go b/internal/setup/setup.go index d16d7e76..965d9aa1 100644 --- a/internal/setup/setup.go +++ b/internal/setup/setup.go @@ -20,6 +20,7 @@ import ( "github.com/Mag1cFall/AIStudio2API/internal/aistudio" "github.com/Mag1cFall/AIStudio2API/internal/api" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative" "github.com/Mag1cFall/AIStudio2API/internal/chromeauth" "github.com/Mag1cFall/AIStudio2API/internal/config" @@ -73,6 +74,9 @@ func Run(ctx context.Context, cfg config.Config, args []string) error { if err != nil { return err } + if buildpolicy.Conservative && (!options.login || options.remote != "" || options.renew) { + return fmt.Errorf("conservative trial supports only local setup --login; browser extraction, cookie copying and remote renewal are disabled") + } client := &http.Client{Timeout: cfg.RequestTimeout, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} diff --git a/web/src/components/AccountsPanel.vue b/web/src/components/AccountsPanel.vue index 3eb94ee0..2bdff9b1 100644 --- a/web/src/components/AccountsPanel.vue +++ b/web/src/components/AccountsPanel.vue @@ -740,6 +740,8 @@ async function importBrowserAccounts(): Promise { } } +const conservativeTrial = import.meta.env.VITE_CONSERVATIVE === '1' + // addMethods 是“添加账户”菜单中的导入方式,顺序按常用程度;服务所在平台不能从 Chrome 导入时该项不可选并说明原因 const addMethods = computed< { @@ -987,7 +989,7 @@ async function refreshAccounts(accounts: Account[]): Promise { class="z-[60] max-h-[var(--reka-dropdown-menu-content-available-height)] w-72 max-w-[calc(100vw-2rem)] overflow-y-auto rounded-lg border border-line bg-panel p-1 shadow-xl" >