From 3636be31d6c01fb47199a77159de306c38cb87ac Mon Sep 17 00:00:00 2001 From: RCD <90105158+Finesssee@users.noreply.github.com> Date: Mon, 11 May 2026 07:51:59 +0000 Subject: [PATCH] fix: make Kiro auth fallback safe and document Claude limits Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .gitignore | 4 +- README.md | 6 +- cmd/server/main.go | 4 +- docs/claude-code-local-proxy.md | 13 +++ docs/cli.md | 10 +- internal/cmd/kiro_login.go | 53 ++-------- internal/registry/model_updater.go | 13 +++ internal/registry/model_updater_test.go | 35 +++++++ internal/runtime/executor/kiro_executor.go | 9 +- sdk/auth/kiro.go | 112 +-------------------- sdk/cliproxy/service.go | 5 + sdk/cliproxy/service_kiro_test.go | 30 ++++++ 12 files changed, 127 insertions(+), 167 deletions(-) create mode 100644 internal/registry/model_updater_test.go create mode 100644 sdk/cliproxy/service_kiro_test.go diff --git a/.gitignore b/.gitignore index 4e1ed6a4..984773ca 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ # Binaries -cli-proxy-api -cliproxy +/cli-proxy-api +/cliproxy proxypilot-linux proxypilot-darwin proxypilot-windows diff --git a/README.md b/README.md index 58374e86..b9becd60 100644 --- a/README.md +++ b/README.md @@ -107,8 +107,8 @@ Run OAuth login for your provider: ./proxypilot --claude-login # Claude ./proxypilot --codex-login # OpenAI/Codex ./proxypilot --login # Gemini -./proxypilot --kiro-login # Kiro (Google OAuth) -./proxypilot --kiro-aws-login # Kiro (AWS Builder ID) +./proxypilot --kiro-login # Kiro (AWS Builder ID) +./proxypilot --kiro-aws-login # Kiro (AWS Builder ID device code) ./proxypilot --qwen-login # Qwen ./proxypilot --antigravity-login # Antigravity @@ -122,6 +122,8 @@ Run OAuth login for your provider: OAuth tokens are stored locally and auto-refreshed before expiry. +Kiro Google/GitHub OAuth is not currently supported because AWS Cognito rejects third-party localhost callbacks. Use AWS Builder ID (`--kiro-login` / `--kiro-aws-login`) or import from the official Kiro IDE. + ### Security Defaults (Auth + CORS) - Proxy requests require API keys by default. To allow unauthenticated access (not recommended), set `allow-unauthenticated: true` in `config.yaml`. diff --git a/cmd/server/main.go b/cmd/server/main.go index 8cfa722e..d75be624 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -163,8 +163,8 @@ func main() { flag.BoolVar(&noIncognito, "no-incognito", false, "Force disable incognito mode (uses existing browser session)") flag.IntVar(&oauthCallbackPort, "oauth-callback-port", 0, "Override OAuth callback port (defaults to provider-specific port)") flag.BoolVar(&antigravityLogin, "antigravity-login", false, "Login to Antigravity using OAuth") - flag.BoolVar(&kiroLogin, "kiro-login", false, "Login to Kiro using Google OAuth") - flag.BoolVar(&kiroGoogleLogin, "kiro-google-login", false, "Login to Kiro using Google OAuth (same as --kiro-login)") + flag.BoolVar(&kiroLogin, "kiro-login", false, "Login to Kiro using AWS Builder ID") + flag.BoolVar(&kiroGoogleLogin, "kiro-google-login", false, "Show Kiro Google OAuth limitation and supported alternatives") flag.BoolVar(&kiroAWSLogin, "kiro-aws-login", false, "Login to Kiro using AWS Builder ID (device code flow)") flag.BoolVar(&kiroAWSAuthCode, "kiro-aws-authcode", false, "Login to Kiro using AWS Builder ID (authorization code flow, better UX)") flag.BoolVar(&kiroImport, "kiro-import", false, "Import Kiro token from Kiro IDE (~/.aws/sso/cache/kiro-auth-token.json)") diff --git a/docs/claude-code-local-proxy.md b/docs/claude-code-local-proxy.md index c75983e8..a17286cb 100644 --- a/docs/claude-code-local-proxy.md +++ b/docs/claude-code-local-proxy.md @@ -32,6 +32,19 @@ Important: - Avoid Claude Code “Auth conflict”: do **not** set both `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_API_KEY` at the same time. - Restart Claude Code after editing settings so the new env vars take effect. +## Claude OAuth quota limitation + +Anthropic currently treats third-party app traffic differently from regular Claude.ai or Claude Code subscription usage. If a Claude OAuth request fails with: + +```text +Third-party apps now draw from your extra usage, not your plan limits. +Add more at claude.ai/settings/usage and keep going. +``` + +that response is coming from Anthropic, not ProxyPilot. It means the OAuth credential is valid, but Anthropic is requiring paid extra usage for this third-party API path. ProxyPilot cannot make those requests draw from normal Claude.ai subscription quota. + +For Claude through ProxyPilot, either add extra usage in Anthropic settings, use a supported API-key billing path, or route the client to another provider/model alias such as Antigravity, Codex, Gemini, or Kiro. + ## Server-side model aliasing (Claude handler) CLIProxyAPI rewrites common Claude Code model aliases to locally-available models before routing: diff --git a/docs/cli.md b/docs/cli.md index 29f4e188..1e2badb9 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -57,12 +57,14 @@ proxypilot --codex-login # Login to Codex using OAuth proxypilot --claude-login # Login to Claude using OAuth proxypilot --qwen-login # Login to Qwen using OAuth proxypilot --antigravity-login # Login to Antigravity using OAuth -proxypilot --kiro-login # Login to Kiro using Google OAuth -proxypilot --kiro-aws-login # Login to Kiro using AWS Builder ID +proxypilot --kiro-login # Login to Kiro using AWS Builder ID +proxypilot --kiro-aws-login # Login to Kiro using AWS Builder ID device code proxypilot --minimax-login # Add MiniMax API key proxypilot --zhipu-login # Add Zhipu AI API key ``` +Kiro Google/GitHub OAuth is not currently supported because AWS Cognito rejects third-party localhost callbacks. Use AWS Builder ID or import a token from the official Kiro IDE instead. + ### Login Options ```bash @@ -309,8 +311,8 @@ proxypilot --codex-login # Codex OAuth proxypilot --claude-login # Claude OAuth proxypilot --qwen-login # Qwen OAuth proxypilot --antigravity-login # Antigravity OAuth -proxypilot --kiro-login # Kiro Google OAuth -proxypilot --kiro-aws-login # Kiro AWS Builder ID +proxypilot --kiro-login # Kiro AWS Builder ID +proxypilot --kiro-aws-login # Kiro AWS Builder ID device code # Agent Detection & Setup proxypilot --detect-agents # Detect installed agents diff --git a/internal/cmd/kiro_login.go b/internal/cmd/kiro_login.go index b33065b7..334f59f7 100644 --- a/internal/cmd/kiro_login.go +++ b/internal/cmd/kiro_login.go @@ -9,63 +9,28 @@ import ( log "github.com/sirupsen/logrus" ) -// DoKiroLogin triggers the Kiro authentication flow with Google OAuth. -// This is the default login method (same as --kiro-google-login). +// DoKiroLogin triggers the Kiro authentication flow with AWS Builder ID. // // Parameters: // - cfg: The application configuration // - options: Login options including Prompt field func DoKiroLogin(cfg *config.Config, options *LoginOptions) { - // Use Google login as default - DoKiroGoogleLogin(cfg, options) + DoKiroAWSLogin(cfg, options) } // DoKiroGoogleLogin triggers Kiro authentication with Google OAuth. -// This uses a custom protocol handler (kiro://) to receive the callback. // // Parameters: // - cfg: The application configuration // - options: Login options including prompts func DoKiroGoogleLogin(cfg *config.Config, options *LoginOptions) { - if options == nil { - options = &LoginOptions{} - } - - // Note: Kiro defaults to incognito mode for multi-account support. - // Users can override with --no-incognito if they want to use existing browser sessions. - - manager := newAuthManager() - - // Use KiroAuthenticator with Google login - authenticator := sdkAuth.NewKiroAuthenticator() - record, err := authenticator.LoginWithGoogle(context.Background(), cfg, &sdkAuth.LoginOptions{ - NoBrowser: options.NoBrowser, - Metadata: map[string]string{}, - Prompt: options.Prompt, - }) - if err != nil { - log.Errorf("Kiro Google authentication failed: %v", err) - fmt.Println("\nTroubleshooting:") - fmt.Println("1. Make sure the protocol handler is installed") - fmt.Println("2. Complete the Google login in the browser") - fmt.Println("3. If callback fails, try: --kiro-import (after logging in via Kiro IDE)") - return - } - - // Save the auth record - savedPath, err := manager.SaveAuth(record, cfg) - if err != nil { - log.Errorf("Failed to save auth: %v", err) - return - } - - if savedPath != "" { - fmt.Printf("Authentication saved to %s\n", savedPath) - } - if record != nil && record.Label != "" { - fmt.Printf("Authenticated as %s\n", record.Label) - } - fmt.Println("Kiro Google authentication successful!") + log.Warn("Kiro Google OAuth is disabled because AWS Cognito rejects third-party localhost callbacks") + fmt.Println("\nKiro Google login is not currently supported by ProxyPilot.") + fmt.Println("AWS Cognito rejects ProxyPilot's localhost redirect URI with redirect_mismatch.") + fmt.Println("\nUse one of these supported alternatives:") + fmt.Println("1. --kiro-aws-login for AWS Builder ID device authorization") + fmt.Println("2. --kiro-aws-authcode for AWS Builder ID browser callback") + fmt.Println("3. --kiro-import after signing in with the official Kiro IDE") } // DoKiroAWSLogin triggers Kiro authentication with AWS Builder ID. diff --git a/internal/registry/model_updater.go b/internal/registry/model_updater.go index 197f6044..7c9581c7 100644 --- a/internal/registry/model_updater.go +++ b/internal/registry/model_updater.go @@ -179,6 +179,7 @@ func fetchModelsFromRemote(ctx context.Context) (*staticModelsJSON, string) { log.Warnf("models parse failed from %s: %v", url, err) continue } + mergeMissingForkModelSections(&parsed, getModels()) if err := validateModelsCatalog(&parsed); err != nil { log.Warnf("models validate failed from %s: %v", url, err) continue @@ -349,6 +350,18 @@ func validateModelsCatalog(data *staticModelsJSON) error { return nil } +func mergeMissingForkModelSections(data, fallback *staticModelsJSON) { + if data == nil || fallback == nil { + return + } + if len(data.Qwen) == 0 { + data.Qwen = cloneModelInfos(fallback.Qwen) + } + if len(data.IFlow) == 0 { + data.IFlow = cloneModelInfos(fallback.IFlow) + } +} + func validateModelSection(section string, models []*ModelInfo) error { if len(models) == 0 { return fmt.Errorf("%s section is empty", section) diff --git a/internal/registry/model_updater_test.go b/internal/registry/model_updater_test.go new file mode 100644 index 00000000..c11cfd7a --- /dev/null +++ b/internal/registry/model_updater_test.go @@ -0,0 +1,35 @@ +package registry + +import "testing" + +func TestMergeMissingForkModelSectionsPreservesQwenAndIFlow(t *testing.T) { + data := &staticModelsJSON{ + Claude: []*ModelInfo{{ID: "claude-1"}}, + Gemini: []*ModelInfo{{ID: "gemini-1"}}, + Vertex: []*ModelInfo{{ID: "vertex-1"}}, + GeminiCLI: []*ModelInfo{{ID: "gemini-cli-1"}}, + AIStudio: []*ModelInfo{{ID: "aistudio-1"}}, + CodexFree: []*ModelInfo{{ID: "codex-free-1"}}, + CodexTeam: []*ModelInfo{{ID: "codex-team-1"}}, + CodexPlus: []*ModelInfo{{ID: "codex-plus-1"}}, + CodexPro: []*ModelInfo{{ID: "codex-pro-1"}}, + Kimi: []*ModelInfo{{ID: "kimi-1"}}, + Antigravity: []*ModelInfo{{ID: "antigravity-1"}}, + } + fallback := &staticModelsJSON{ + Qwen: []*ModelInfo{{ID: "qwen-fallback"}}, + IFlow: []*ModelInfo{{ID: "iflow-fallback"}}, + } + + mergeMissingForkModelSections(data, fallback) + + if err := validateModelsCatalog(data); err != nil { + t.Fatalf("expected merged catalog to validate: %v", err) + } + if got := data.Qwen[0].ID; got != "qwen-fallback" { + t.Fatalf("expected qwen fallback model, got %q", got) + } + if got := data.IFlow[0].ID; got != "iflow-fallback" { + t.Fatalf("expected iflow fallback model, got %q", got) + } +} diff --git a/internal/runtime/executor/kiro_executor.go b/internal/runtime/executor/kiro_executor.go index f1b6b2fc..de25b544 100644 --- a/internal/runtime/executor/kiro_executor.go +++ b/internal/runtime/executor/kiro_executor.go @@ -519,7 +519,7 @@ func (e *KiroExecutor) executeWithRetry(ctx context.Context, auth *cliproxyauth. // ExecuteStream handles streaming requests to Kiro API. // Supports automatic token refresh on 401/403 errors and quota fallback on 429. -func (e *KiroExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (stream <-chan cliproxyexecutor.StreamChunk, err error) { +func (e *KiroExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (_ *cliproxyexecutor.StreamResult, err error) { accessToken, profileArn := kiroCredentials(auth) if accessToken == "" { return nil, fmt.Errorf("kiro: access token not found in auth") @@ -586,7 +586,7 @@ func (e *KiroExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Aut } // executeStreamWithRetry performs the streaming HTTP request with automatic retry on auth errors. -func (e *KiroExecutor) executeStreamWithRetry(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, accessToken, profileArn string, kiroPayload, body []byte, from sdktranslator.Format, reporter *usageReporter, currentOrigin, kiroModelID string, isAgentic, isChatOnly bool, tokenKey string) (<-chan cliproxyexecutor.StreamChunk, error) { +func (e *KiroExecutor) executeStreamWithRetry(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, accessToken, profileArn string, kiroPayload, body []byte, from sdktranslator.Format, reporter *usageReporter, currentOrigin, kiroModelID string, isAgentic, isChatOnly bool, tokenKey string) (*cliproxyexecutor.StreamResult, error) { maxRetries := 2 rateLimiter := kiroauth.GetGlobalRateLimiter() cooldownMgr := kiroauth.GetGlobalCooldownManager() @@ -831,7 +831,10 @@ func (e *KiroExecutor) executeStreamWithRetry(ctx context.Context, auth *cliprox e.streamToChannel(ctx, resp.Body, out, from, req.Model, opts.OriginalRequest, body, reporter, thinkingEnabled) }(httpResp, thinkingEnabled) - return out, nil + return &cliproxyexecutor.StreamResult{ + Headers: httpResp.Header.Clone(), + Chunks: out, + }, nil } } diff --git a/sdk/auth/kiro.go b/sdk/auth/kiro.go index 464668b4..1ee959ad 100644 --- a/sdk/auth/kiro.go +++ b/sdk/auth/kiro.go @@ -222,61 +222,7 @@ func (a *KiroAuthenticator) LoginWithGoogle(ctx context.Context, cfg *config.Con if cfg == nil { return nil, fmt.Errorf("kiro auth: configuration is required") } - - oauth := kiroauth.NewKiroOAuth(cfg) - - // Use Google OAuth flow with protocol handler - tokenData, err := oauth.LoginWithGoogle(ctx) - if err != nil { - return nil, fmt.Errorf("google login failed: %w", err) - } - - // Parse expires_at - expiresAt, err := time.Parse(time.RFC3339, tokenData.ExpiresAt) - if err != nil { - expiresAt = time.Now().Add(1 * time.Hour) - } - - // Extract identifier for file naming - idPart := extractKiroIdentifier(tokenData.Email, tokenData.ProfileArn) - - now := time.Now() - fileName := fmt.Sprintf("kiro-google-%s.json", idPart) - - record := &coreauth.Auth{ - ID: fileName, - Provider: "kiro", - FileName: fileName, - Label: "kiro-google", - Status: coreauth.StatusActive, - CreatedAt: now, - UpdatedAt: now, - Metadata: map[string]any{ - "type": "kiro", - "access_token": tokenData.AccessToken, - "refresh_token": tokenData.RefreshToken, - "profile_arn": tokenData.ProfileArn, - "expires_at": tokenData.ExpiresAt, - "auth_method": tokenData.AuthMethod, - "provider": tokenData.Provider, - "email": tokenData.Email, - }, - Attributes: map[string]string{ - "profile_arn": tokenData.ProfileArn, - "source": "google-oauth", - "email": tokenData.Email, - }, - // NextRefreshAfter is aligned with RefreshLead (5min) - NextRefreshAfter: expiresAt.Add(-5 * time.Minute), - } - - if tokenData.Email != "" { - fmt.Printf("\n✓ Kiro Google authentication completed successfully! (Account: %s)\n", tokenData.Email) - } else { - fmt.Println("\n✓ Kiro Google authentication completed successfully!") - } - - return record, nil + return nil, fmt.Errorf("kiro google login is not supported: AWS Cognito rejects third-party localhost callbacks; use AWS Builder ID or import from Kiro IDE") } // LoginWithGitHub performs OAuth login for Kiro with GitHub. @@ -285,61 +231,7 @@ func (a *KiroAuthenticator) LoginWithGitHub(ctx context.Context, cfg *config.Con if cfg == nil { return nil, fmt.Errorf("kiro auth: configuration is required") } - - oauth := kiroauth.NewKiroOAuth(cfg) - - // Use GitHub OAuth flow with protocol handler - tokenData, err := oauth.LoginWithGitHub(ctx) - if err != nil { - return nil, fmt.Errorf("github login failed: %w", err) - } - - // Parse expires_at - expiresAt, err := time.Parse(time.RFC3339, tokenData.ExpiresAt) - if err != nil { - expiresAt = time.Now().Add(1 * time.Hour) - } - - // Extract identifier for file naming - idPart := extractKiroIdentifier(tokenData.Email, tokenData.ProfileArn) - - now := time.Now() - fileName := fmt.Sprintf("kiro-github-%s.json", idPart) - - record := &coreauth.Auth{ - ID: fileName, - Provider: "kiro", - FileName: fileName, - Label: "kiro-github", - Status: coreauth.StatusActive, - CreatedAt: now, - UpdatedAt: now, - Metadata: map[string]any{ - "type": "kiro", - "access_token": tokenData.AccessToken, - "refresh_token": tokenData.RefreshToken, - "profile_arn": tokenData.ProfileArn, - "expires_at": tokenData.ExpiresAt, - "auth_method": tokenData.AuthMethod, - "provider": tokenData.Provider, - "email": tokenData.Email, - }, - Attributes: map[string]string{ - "profile_arn": tokenData.ProfileArn, - "source": "github-oauth", - "email": tokenData.Email, - }, - // NextRefreshAfter is aligned with RefreshLead (5min) - NextRefreshAfter: expiresAt.Add(-5 * time.Minute), - } - - if tokenData.Email != "" { - fmt.Printf("\n✓ Kiro GitHub authentication completed successfully! (Account: %s)\n", tokenData.Email) - } else { - fmt.Println("\n✓ Kiro GitHub authentication completed successfully!") - } - - return record, nil + return nil, fmt.Errorf("kiro github login is not supported: AWS Cognito rejects third-party localhost callbacks; use AWS Builder ID or import from Kiro IDE") } // ImportFromKiroIDE imports token from Kiro IDE's token file. diff --git a/sdk/cliproxy/service.go b/sdk/cliproxy/service.go index 89a480b5..3f957197 100644 --- a/sdk/cliproxy/service.go +++ b/sdk/cliproxy/service.go @@ -429,6 +429,8 @@ func (s *Service) ensureExecutorsForAuthWithMode(a *coreauth.Auth, forceReplace s.coreManager.RegisterExecutor(executor.NewAntigravityExecutor(s.cfg)) case "claude": s.coreManager.RegisterExecutor(executor.NewClaudeExecutor(s.cfg)) + case "kiro": + s.coreManager.RegisterExecutor(executor.NewKiroExecutor(s.cfg)) case "kimi": s.coreManager.RegisterExecutor(executor.NewKimiExecutor(s.cfg)) default: @@ -1101,6 +1103,9 @@ func (s *Service) registerModelsForAuth(a *coreauth.Auth) { } } models = applyExcludedModels(models, excluded) + case "kiro": + models = registry.GetKiroModels() + models = applyExcludedModels(models, excluded) case "codex": codexPlanType := "" if a.Attributes != nil { diff --git a/sdk/cliproxy/service_kiro_test.go b/sdk/cliproxy/service_kiro_test.go new file mode 100644 index 00000000..8d687e30 --- /dev/null +++ b/sdk/cliproxy/service_kiro_test.go @@ -0,0 +1,30 @@ +package cliproxy + +import ( + "testing" + + coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v7/sdk/config" +) + +func TestRegisterModelsForAuth_KiroRegistersStaticModels(t *testing.T) { + service := &Service{cfg: &config.Config{}} + auth := &coreauth.Auth{ + ID: "auth-kiro", + Provider: "kiro", + Status: coreauth.StatusActive, + } + + registry := GlobalModelRegistry() + registry.UnregisterClient(auth.ID) + t.Cleanup(func() { + registry.UnregisterClient(auth.ID) + }) + + service.registerModelsForAuth(auth) + + models := registry.GetAvailableModelsByProvider("kiro") + if len(models) == 0 { + t.Fatal("expected kiro models to be registered") + } +}