kek commited on
Commit ·
f606b10
0
Parent(s):
Fresh start: Go 1.23 + go-git/v5 compatibility
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitignoreAdded+56
- DockerfileAdded+30
- Dockerfile.hfAdded+27
- LICENSEAdded+22
- README.mdAdded+16
- cmd/server/main.goAdded+535
- config.example.yamlAdded+281
- config.yamlAdded+75
- go.modAdded+78
- go.sumAdded+196
- internal/access/config_access/provider.goAdded+112
- internal/access/reconcile.goAdded+270
- internal/api/handlers/management/api_tools.goAdded+538
- internal/api/handlers/management/auth_files.goAdded+2606
- internal/api/handlers/management/config_basic.goAdded+243
- internal/api/handlers/management/config_lists.goAdded+1090
- internal/api/handlers/management/handler.goAdded+277
- internal/api/handlers/management/logs.goAdded+592
- internal/api/handlers/management/oauth_callback.goAdded+100
- internal/api/handlers/management/oauth_sessions.goAdded+290
- internal/api/handlers/management/quota.goAdded+18
- internal/api/handlers/management/usage.goAdded+79
- internal/api/handlers/management/vertex_import.goAdded+156
- internal/api/middleware/request_logging.goAdded+122
- internal/api/middleware/response_writer.goAdded+382
- internal/api/modules/amp/amp.goAdded+428
- internal/api/modules/amp/amp_test.goAdded+352
- internal/api/modules/amp/fallback_handlers.goAdded+329
- internal/api/modules/amp/fallback_handlers_test.goAdded+73
- internal/api/modules/amp/gemini_bridge.goAdded+59
- internal/api/modules/amp/gemini_bridge_test.goAdded+93
- internal/api/modules/amp/model_mapping.goAdded+147
- internal/api/modules/amp/model_mapping_test.goAdded+283
- internal/api/modules/amp/proxy.goAdded+266
- internal/api/modules/amp/proxy_test.goAdded+657
- internal/api/modules/amp/response_rewriter.goAdded+160
- internal/api/modules/amp/routes.goAdded+334
- internal/api/modules/amp/routes_test.goAdded+381
- internal/api/modules/amp/secret.goAdded+248
- internal/api/modules/amp/secret_test.goAdded+366
- internal/api/modules/modules.goAdded+92
- internal/api/server.goAdded+1056
- internal/api/server_test.goAdded+111
- internal/auth/claude/anthropic.goAdded+32
- internal/auth/claude/anthropic_auth.goAdded+346
- internal/auth/claude/errors.goAdded+167
- internal/auth/claude/html_templates.goAdded+218
- internal/auth/claude/oauth_server.goAdded+331
- internal/auth/claude/pkce.goAdded+56
- internal/auth/claude/token.goAdded+73
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556# Binariescli-proxy-apicliproxy*.exe
# Configurationconfig.yaml.env
# Generated contentbin/*logs/*conv/*temp/*refs/*
# Storage backendspgstore/*gitstore/*objectstore/*
# Static assetsstatic/*
# Authentication dataauths/*!auths/.gitkeep
# Documentationdocs/*AGENTS.mdCLAUDE.mdGEMINI.md
# Tooling metadata.vscode/*.codex/*.claude/*.gemini/*.serena/*.agent/*.agents/*.agents/*.opencode/*.bmad/*_bmad/*_bmad-output/*.mcp/cache/
# macOS.DS_Store._*cli-proxy-api-plusCLIProxyAPIPlus_*.tar.gzcli-proxy-api-pluscli-proxy-api-plus123456789101112131415161718192021222324252627282930# 1. Schritt: Build des Go-ProxysFROM golang:1.23-alpine AS builderWORKDIR /appCOPY . .RUN go mod downloadRUN CGO_ENABLED=0 GOOS=linux go build -o /app/cliproxy ./cmd/server/
# 2. Schritt: Schlankes Runtime-ImageFROM alpine:latestRUN apk add --no-cache ca-certificates bash
# ArbeitsverzeichnisWORKDIR /app
# Kopiere den Proxy, die Config und den statischen Web-OrdnerCOPY --from=builder /app/cliproxy /app/cliproxyCOPY config.yaml /app/config.yamlCOPY static /app/static
# Start-SkriptRUN echo "#!/bin/bash" > /start.sh && \ echo "Starting CLI Proxy API on Port 7860..." >> /start.sh && \ echo "exec /app/cliproxy -config /app/config.yaml" >> /start.sh && \ chmod +x /start.sh
# Port 7860 ist Pflicht für Hugging FaceEXPOSE 7860
# Proxy startenENTRYPOINT ["/start.sh"]123456789101112131415161718192021222324252627# 1. Schritt: Wir bauen den Go-Proxy (CLIProxyAPIPlus)FROM golang:1.24-alpine AS builderWORKDIR /appCOPY . .RUN go mod downloadRUN CGO_ENABLED=0 GOOS=linux go build -o /app/cliproxy ./cmd/server/
# 2. Schritt: Wir nehmen Puter (den Desktop)FROM heyputer/puter:latest
USER root
# Proxy und Config kopierenCOPY --from=builder /app/cliproxy /usr/local/bin/cliproxyCOPY config.yaml /etc/cliproxy/config.yaml
# Start-Skript sauber erstellen (Alles in einer RUN-Anweisung)RUN echo "#!/bin/bash" > /start.sh && \ echo "echo 'Starting CLI Proxy...'" >> /start.sh && \ echo "/usr/local/bin/cliproxy -config /etc/cliproxy/config.yaml &" >> /start.sh && \ echo "echo 'Starting Puter on Port 7860...'" >> /start.sh && \ echo "exec python3 /opt/puter/puter/server.py --port 7860" >> /start.sh && \ chmod +x /start.sh
EXPOSE 7860
ENTRYPOINT ["/start.sh"]12345678910111213141516171819202122MIT License
Copyright (c) 2025-2005.9 Luis PaterCopyright (c) 2025.9-present Router-For.ME
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.12345678910111213141516---title: Socializer Adminemoji: 🚀colorFrom: bluecolorTo: purplesdk: dockerapp_port: 7860---
# CLIProxyAPI Plus (Socializer Admin)
English | [Chinese](README_CN.md)
This is the Plus version of [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI), adding support for third-party providers on top of the mainline project.
Running on Hugging Face Spaces with Puter OS.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535// Package main provides the entry point for the CLI Proxy API server.// This server acts as a proxy that provides OpenAI/Gemini/Claude compatible API interfaces// for CLI models, allowing CLI models to be used with tools and libraries designed for standard AI APIs.package main
import ( "context" "errors" "flag" "fmt" "io/fs" "net/url" "os" "path/filepath" "strings" "time"
"github.com/joho/godotenv" configaccess "github.com/router-for-me/CLIProxyAPI/v6/internal/access/config_access" "github.com/router-for-me/CLIProxyAPI/v6/internal/buildinfo" "github.com/router-for-me/CLIProxyAPI/v6/internal/cmd" "github.com/router-for-me/CLIProxyAPI/v6/internal/config" "github.com/router-for-me/CLIProxyAPI/v6/internal/logging" "github.com/router-for-me/CLIProxyAPI/v6/internal/managementasset" "github.com/router-for-me/CLIProxyAPI/v6/internal/misc" "github.com/router-for-me/CLIProxyAPI/v6/internal/store" _ "github.com/router-for-me/CLIProxyAPI/v6/internal/translator" "github.com/router-for-me/CLIProxyAPI/v6/internal/usage" "github.com/router-for-me/CLIProxyAPI/v6/internal/util" sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth" coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth" log "github.com/sirupsen/logrus")
var ( Version = "dev" Commit = "none" BuildDate = "unknown" DefaultConfigPath = "")
// init initializes the shared logger setup.func init() { logging.SetupBaseLogger() buildinfo.Version = Version buildinfo.Commit = Commit buildinfo.BuildDate = BuildDate}
// setKiroIncognitoMode sets the incognito browser mode for Kiro authentication.// Kiro defaults to incognito mode for multi-account support.// Users can explicitly override with --incognito or --no-incognito flags.func setKiroIncognitoMode(cfg *config.Config, useIncognito, noIncognito bool) { if useIncognito { cfg.IncognitoBrowser = true } else if noIncognito { cfg.IncognitoBrowser = false } else { cfg.IncognitoBrowser = true // Kiro default }}
// main is the entry point of the application.// It parses command-line flags, loads configuration, and starts the appropriate// service based on the provided flags (login, codex-login, or server mode).func main() { fmt.Printf("CLIProxyAPI Version: %s, Commit: %s, BuiltAt: %s\n", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate)
// Command-line flags to control the application's behavior. var login bool var codexLogin bool var claudeLogin bool var qwenLogin bool var iflowLogin bool var iflowCookie bool var noBrowser bool var antigravityLogin bool var kiroLogin bool var kiroGoogleLogin bool var kiroAWSLogin bool var kiroAWSAuthCode bool var kiroImport bool var githubCopilotLogin bool var projectID string var vertexImport string var configPath string var password string var noIncognito bool var useIncognito bool
// Define command-line flags for different operation modes. flag.BoolVar(&login, "login", false, "Login Google Account") flag.BoolVar(&codexLogin, "codex-login", false, "Login to Codex using OAuth") flag.BoolVar(&claudeLogin, "claude-login", false, "Login to Claude using OAuth") flag.BoolVar(&qwenLogin, "qwen-login", false, "Login to Qwen using OAuth") flag.BoolVar(&iflowLogin, "iflow-login", false, "Login to iFlow using OAuth") flag.BoolVar(&iflowCookie, "iflow-cookie", false, "Login to iFlow using Cookie") flag.BoolVar(&noBrowser, "no-browser", false, "Don't open browser automatically for OAuth") flag.BoolVar(&useIncognito, "incognito", false, "Open browser in incognito/private mode for OAuth (useful for multiple accounts)") flag.BoolVar(&noIncognito, "no-incognito", false, "Force disable incognito mode (uses existing browser session)") 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(&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)") flag.BoolVar(&githubCopilotLogin, "github-copilot-login", false, "Login to GitHub Copilot using device flow") flag.StringVar(&projectID, "project_id", "", "Project ID (Gemini only, not required)") flag.StringVar(&configPath, "config", DefaultConfigPath, "Configure File Path") flag.StringVar(&vertexImport, "vertex-import", "", "Import Vertex service account key JSON file") flag.StringVar(&password, "password", "", "")
flag.CommandLine.Usage = func() { out := flag.CommandLine.Output() _, _ = fmt.Fprintf(out, "Usage of %s\n", os.Args[0]) flag.CommandLine.VisitAll(func(f *flag.Flag) { if f.Name == "password" { return } s := fmt.Sprintf(" -%s", f.Name) name, unquoteUsage := flag.UnquoteUsage(f) if name != "" { s += " " + name } if len(s) <= 4 { s += " " } else { s += "\n " } if unquoteUsage != "" { s += unquoteUsage } if f.DefValue != "" && f.DefValue != "false" && f.DefValue != "0" { s += fmt.Sprintf(" (default %s)", f.DefValue) } _, _ = fmt.Fprint(out, s+"\n") }) }
// Parse the command-line flags. flag.Parse()
// Core application variables. var err error var cfg *config.Config var isCloudDeploy bool var ( usePostgresStore bool pgStoreDSN string pgStoreSchema string pgStoreLocalPath string pgStoreInst *store.PostgresStore useGitStore bool gitStoreRemoteURL string gitStoreUser string gitStorePassword string gitStoreLocalPath string gitStoreInst *store.GitTokenStore gitStoreRoot string useObjectStore bool objectStoreEndpoint string objectStoreAccess string objectStoreSecret string objectStoreBucket string objectStoreLocalPath string objectStoreInst *store.ObjectTokenStore )
wd, err := os.Getwd() if err != nil { log.Errorf("failed to get working directory: %v", err) return }
// Load environment variables from .env if present. if errLoad := godotenv.Load(filepath.Join(wd, ".env")); errLoad != nil { if !errors.Is(errLoad, os.ErrNotExist) { log.WithError(errLoad).Warn("failed to load .env file") } }
lookupEnv := func(keys ...string) (string, bool) { for _, key := range keys { if value, ok := os.LookupEnv(key); ok { if trimmed := strings.TrimSpace(value); trimmed != "" { return trimmed, true } } } return "", false } writableBase := util.WritablePath() if value, ok := lookupEnv("PGSTORE_DSN", "pgstore_dsn"); ok { usePostgresStore = true pgStoreDSN = value } if usePostgresStore { if value, ok := lookupEnv("PGSTORE_SCHEMA", "pgstore_schema"); ok { pgStoreSchema = value } if value, ok := lookupEnv("PGSTORE_LOCAL_PATH", "pgstore_local_path"); ok { pgStoreLocalPath = value } if pgStoreLocalPath == "" { if writableBase != "" { pgStoreLocalPath = writableBase } else { pgStoreLocalPath = wd } } useGitStore = false } if value, ok := lookupEnv("GITSTORE_GIT_URL", "gitstore_git_url"); ok { useGitStore = true gitStoreRemoteURL = value } if value, ok := lookupEnv("GITSTORE_GIT_USERNAME", "gitstore_git_username"); ok { gitStoreUser = value } if value, ok := lookupEnv("GITSTORE_GIT_TOKEN", "gitstore_git_token"); ok { gitStorePassword = value } if value, ok := lookupEnv("GITSTORE_LOCAL_PATH", "gitstore_local_path"); ok { gitStoreLocalPath = value } if value, ok := lookupEnv("OBJECTSTORE_ENDPOINT", "objectstore_endpoint"); ok { useObjectStore = true objectStoreEndpoint = value } if value, ok := lookupEnv("OBJECTSTORE_ACCESS_KEY", "objectstore_access_key"); ok { objectStoreAccess = value } if value, ok := lookupEnv("OBJECTSTORE_SECRET_KEY", "objectstore_secret_key"); ok { objectStoreSecret = value } if value, ok := lookupEnv("OBJECTSTORE_BUCKET", "objectstore_bucket"); ok { objectStoreBucket = value } if value, ok := lookupEnv("OBJECTSTORE_LOCAL_PATH", "objectstore_local_path"); ok { objectStoreLocalPath = value }
// Check for cloud deploy mode only on first execution // Read env var name in uppercase: DEPLOY deployEnv := os.Getenv("DEPLOY") if deployEnv == "cloud" { isCloudDeploy = true }
// Determine and load the configuration file. // Prefer the Postgres store when configured, otherwise fallback to git or local files. var configFilePath string if usePostgresStore { if pgStoreLocalPath == "" { pgStoreLocalPath = wd } pgStoreLocalPath = filepath.Join(pgStoreLocalPath, "pgstore") ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) pgStoreInst, err = store.NewPostgresStore(ctx, store.PostgresStoreConfig{ DSN: pgStoreDSN, Schema: pgStoreSchema, SpoolDir: pgStoreLocalPath, }) cancel() if err != nil { log.Errorf("failed to initialize postgres token store: %v", err) return } examplePath := filepath.Join(wd, "config.example.yaml") ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) if errBootstrap := pgStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil { cancel() log.Errorf("failed to bootstrap postgres-backed config: %v", errBootstrap) return } cancel() configFilePath = pgStoreInst.ConfigPath() cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy) if err == nil { cfg.AuthDir = pgStoreInst.AuthDir() log.Infof("postgres-backed token store enabled, workspace path: %s", pgStoreInst.WorkDir()) } } else if useObjectStore { if objectStoreLocalPath == "" { if writableBase != "" { objectStoreLocalPath = writableBase } else { objectStoreLocalPath = wd } } objectStoreRoot := filepath.Join(objectStoreLocalPath, "objectstore") resolvedEndpoint := strings.TrimSpace(objectStoreEndpoint) useSSL := true if strings.Contains(resolvedEndpoint, "://") { parsed, errParse := url.Parse(resolvedEndpoint) if errParse != nil { log.Errorf("failed to parse object store endpoint %q: %v", objectStoreEndpoint, errParse) return } switch strings.ToLower(parsed.Scheme) { case "http": useSSL = false case "https": useSSL = true default: log.Errorf("unsupported object store scheme %q (only http and https are allowed)", parsed.Scheme) return } if parsed.Host == "" { log.Errorf("object store endpoint %q is missing host information", objectStoreEndpoint) return } resolvedEndpoint = parsed.Host if parsed.Path != "" && parsed.Path != "/" { resolvedEndpoint = strings.TrimSuffix(parsed.Host+parsed.Path, "/") } } resolvedEndpoint = strings.TrimRight(resolvedEndpoint, "/") objCfg := store.ObjectStoreConfig{ Endpoint: resolvedEndpoint, Bucket: objectStoreBucket, AccessKey: objectStoreAccess, SecretKey: objectStoreSecret, LocalRoot: objectStoreRoot, UseSSL: useSSL, PathStyle: true, } objectStoreInst, err = store.NewObjectTokenStore(objCfg) if err != nil { log.Errorf("failed to initialize object token store: %v", err) return } examplePath := filepath.Join(wd, "config.example.yaml") ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) if errBootstrap := objectStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil { cancel() log.Errorf("failed to bootstrap object-backed config: %v", errBootstrap) return } cancel() configFilePath = objectStoreInst.ConfigPath() cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy) if err == nil { if cfg == nil { cfg = &config.Config{} } cfg.AuthDir = objectStoreInst.AuthDir() log.Infof("object-backed token store enabled, bucket: %s", objectStoreBucket) } } else if useGitStore { if gitStoreLocalPath == "" { if writableBase != "" { gitStoreLocalPath = writableBase } else { gitStoreLocalPath = wd } } gitStoreRoot = filepath.Join(gitStoreLocalPath, "gitstore") authDir := filepath.Join(gitStoreRoot, "auths") gitStoreInst = store.NewGitTokenStore(gitStoreRemoteURL, gitStoreUser, gitStorePassword) gitStoreInst.SetBaseDir(authDir) if errRepo := gitStoreInst.EnsureRepository(); errRepo != nil { log.Errorf("failed to prepare git token store: %v", errRepo) return } configFilePath = gitStoreInst.ConfigPath() if configFilePath == "" { configFilePath = filepath.Join(gitStoreRoot, "config", "config.yaml") } if _, statErr := os.Stat(configFilePath); errors.Is(statErr, fs.ErrNotExist) { examplePath := filepath.Join(wd, "config.example.yaml") if _, errExample := os.Stat(examplePath); errExample != nil { log.Errorf("failed to find template config file: %v", errExample) return } if errCopy := misc.CopyConfigTemplate(examplePath, configFilePath); errCopy != nil { log.Errorf("failed to bootstrap git-backed config: %v", errCopy) return } if errCommit := gitStoreInst.PersistConfig(context.Background()); errCommit != nil { log.Errorf("failed to commit initial git-backed config: %v", errCommit) return } log.Infof("git-backed config initialized from template: %s", configFilePath) } else if statErr != nil { log.Errorf("failed to inspect git-backed config: %v", statErr) return } cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy) if err == nil { cfg.AuthDir = gitStoreInst.AuthDir() log.Infof("git-backed token store enabled, repository path: %s", gitStoreRoot) } } else if configPath != "" { configFilePath = configPath cfg, err = config.LoadConfigOptional(configPath, isCloudDeploy) } else { wd, err = os.Getwd() if err != nil { log.Errorf("failed to get working directory: %v", err) return } configFilePath = filepath.Join(wd, "config.yaml") cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy) } if err != nil { log.Errorf("failed to load config: %v", err) return } if cfg == nil { cfg = &config.Config{} }
// In cloud deploy mode, check if we have a valid configuration var configFileExists bool if isCloudDeploy { if info, errStat := os.Stat(configFilePath); errStat != nil { // Don't mislead: API server will not start until configuration is provided. log.Info("Cloud deploy mode: No configuration file detected; standing by for configuration") configFileExists = false } else if info.IsDir() { log.Info("Cloud deploy mode: Config path is a directory; standing by for configuration") configFileExists = false } else if cfg.Port == 0 { // LoadConfigOptional returns empty config when file is empty or invalid. // Config file exists but is empty or invalid; treat as missing config log.Info("Cloud deploy mode: Configuration file is empty or invalid; standing by for valid configuration") configFileExists = false } else { log.Info("Cloud deploy mode: Configuration file detected; starting service") configFileExists = true } } usage.SetStatisticsEnabled(cfg.UsageStatisticsEnabled) coreauth.SetQuotaCooldownDisabled(cfg.DisableCooling)
if err = logging.ConfigureLogOutput(cfg); err != nil { log.Errorf("failed to configure log output: %v", err) return }
log.Infof("CLIProxyAPI Version: %s, Commit: %s, BuiltAt: %s", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate)
// Set the log level based on the configuration. util.SetLogLevel(cfg)
if resolvedAuthDir, errResolveAuthDir := util.ResolveAuthDir(cfg.AuthDir); errResolveAuthDir != nil { log.Errorf("failed to resolve auth directory: %v", errResolveAuthDir) return } else { cfg.AuthDir = resolvedAuthDir } managementasset.SetCurrentConfig(cfg)
// Create login options to be used in authentication flows. options := &cmd.LoginOptions{ NoBrowser: noBrowser, }
// Register the shared token store once so all components use the same persistence backend. if usePostgresStore { sdkAuth.RegisterTokenStore(pgStoreInst) } else if useObjectStore { sdkAuth.RegisterTokenStore(objectStoreInst) } else if useGitStore { sdkAuth.RegisterTokenStore(gitStoreInst) } else { sdkAuth.RegisterTokenStore(sdkAuth.NewFileTokenStore()) }
// Register built-in access providers before constructing services. configaccess.Register()
// Handle different command modes based on the provided flags.
if vertexImport != "" { // Handle Vertex service account import cmd.DoVertexImport(cfg, vertexImport) } else if login { // Handle Google/Gemini login cmd.DoLogin(cfg, projectID, options) } else if antigravityLogin { // Handle Antigravity login cmd.DoAntigravityLogin(cfg, options) } else if githubCopilotLogin { // Handle GitHub Copilot login cmd.DoGitHubCopilotLogin(cfg, options) } else if codexLogin { // Handle Codex login cmd.DoCodexLogin(cfg, options) } else if claudeLogin { // Handle Claude login cmd.DoClaudeLogin(cfg, options) } else if qwenLogin { cmd.DoQwenLogin(cfg, options) } else if iflowLogin { cmd.DoIFlowLogin(cfg, options) } else if iflowCookie { cmd.DoIFlowCookieAuth(cfg, options) } else if kiroLogin { // For Kiro auth, default to incognito mode for multi-account support // Users can explicitly override with --no-incognito // Note: This config mutation is safe - auth commands exit after completion // and don't share config with StartService (which is in the else branch) setKiroIncognitoMode(cfg, useIncognito, noIncognito) cmd.DoKiroLogin(cfg, options) } else if kiroGoogleLogin { // For Kiro auth, default to incognito mode for multi-account support // Users can explicitly override with --no-incognito // Note: This config mutation is safe - auth commands exit after completion setKiroIncognitoMode(cfg, useIncognito, noIncognito) cmd.DoKiroGoogleLogin(cfg, options) } else if kiroAWSLogin { // For Kiro auth, default to incognito mode for multi-account support // Users can explicitly override with --no-incognito setKiroIncognitoMode(cfg, useIncognito, noIncognito) cmd.DoKiroAWSLogin(cfg, options) } else if kiroAWSAuthCode { // For Kiro auth with authorization code flow (better UX) setKiroIncognitoMode(cfg, useIncognito, noIncognito) cmd.DoKiroAWSAuthCodeLogin(cfg, options) } else if kiroImport { cmd.DoKiroImport(cfg, options) } else { // In cloud deploy mode without config file, just wait for shutdown signals if isCloudDeploy && !configFileExists { // No config file available, just wait for shutdown cmd.WaitForCloudDeploy() return } // Start the main proxy service managementasset.StartAutoUpdater(context.Background(), configFilePath) cmd.StartService(cfg, configFilePath, password) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281# Server host/interface to bind to. Default is empty ("") to bind all interfaces (IPv4 + IPv6).# Use "127.0.0.1" or "localhost" to restrict access to local machine only.host: ""
# Server portport: 8317
# TLS settings for HTTPS. When enabled, the server listens with the provided certificate and key.tls: enable: false cert: "" key: ""
# Management API settingsremote-management: # Whether to allow remote (non-localhost) management access. # When false, only localhost can access management endpoints (a key is still required). allow-remote: false
# Management key. If a plaintext value is provided here, it will be hashed on startup. # All management requests (even from localhost) require this key. # Leave empty to disable the Management API entirely (404 for all /v0/management routes). secret-key: ""
# Disable the bundled management control panel asset download and HTTP route when true. disable-control-panel: false
# GitHub repository for the management control panel. Accepts a repository URL or releases API URL. panel-github-repository: "https://github.com/router-for-me/Cli-Proxy-API-Management-Center"
# Authentication directory (supports ~ for home directory)auth-dir: "~/.cli-proxy-api"
# API keys for authenticationapi-keys: - "your-api-key-1" - "your-api-key-2" - "your-api-key-3"
# Enable debug loggingdebug: false
# When true, disable high-overhead HTTP middleware features to reduce per-request memory usage under high concurrency.commercial-mode: false
# Open OAuth URLs in incognito/private browser mode.# Useful when you want to login with a different account without logging out from your current session.# Default: false (but Kiro auth defaults to true for multi-account support)incognito-browser: true
# When true, write application logs to rotating files instead of stdoutlogging-to-file: false
# Maximum total size (MB) of log files under the logs directory. When exceeded, the oldest log# files are deleted until within the limit. Set to 0 to disable.logs-max-total-size-mb: 0
# When false, disable in-memory usage statistics aggregationusage-statistics-enabled: false
# Proxy URL. Supports socks5/http/https protocols. Example: socks5://user:pass@192.168.1.1:1080/proxy-url: ""
# When true, unprefixed model requests only use credentials without a prefix (except when prefix == model name).force-model-prefix: false
# Number of times to retry a request. Retries will occur if the HTTP response code is 403, 408, 500, 502, 503, or 504.request-retry: 3
# Maximum wait time in seconds for a cooled-down credential before triggering a retry.max-retry-interval: 30
# Quota exceeded behaviorquota-exceeded: switch-project: true # Whether to automatically switch to another project when a quota is exceeded switch-preview-model: true # Whether to automatically switch to a preview model when a quota is exceeded
# Routing strategy for selecting credentials when multiple match.routing: strategy: "round-robin" # round-robin (default), fill-first
# When true, enable authentication for the WebSocket API (/v1/ws).ws-auth: false
# Streaming behavior (SSE keep-alives + safe bootstrap retries).# streaming:# keepalive-seconds: 15 # Default: 0 (disabled). <= 0 disables keep-alives.# bootstrap-retries: 1 # Default: 0 (disabled). Retries before first byte is sent.
# Gemini API keys# gemini-api-key:# - api-key: "AIzaSy...01"# prefix: "test" # optional: require calls like "test/gemini-3-pro-preview" to target this credential# base-url: "https://generativelanguage.googleapis.com"# headers:# X-Custom-Header: "custom-value"# proxy-url: "socks5://proxy.example.com:1080"# models:# - name: "gemini-2.5-flash" # upstream model name# alias: "gemini-flash" # client alias mapped to the upstream model# excluded-models:# - "gemini-2.5-pro" # exclude specific models from this provider (exact match)# - "gemini-2.5-*" # wildcard matching prefix (e.g. gemini-2.5-flash, gemini-2.5-pro)# - "*-preview" # wildcard matching suffix (e.g. gemini-3-pro-preview)# - "*flash*" # wildcard matching substring (e.g. gemini-2.5-flash-lite)# - api-key: "AIzaSy...02"
# Codex API keys# codex-api-key:# - api-key: "sk-atSM..."# prefix: "test" # optional: require calls like "test/gpt-5-codex" to target this credential# base-url: "https://www.example.com" # use the custom codex API endpoint# headers:# X-Custom-Header: "custom-value"# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override# models:# - name: "gpt-5-codex" # upstream model name# alias: "codex-latest" # client alias mapped to the upstream model# excluded-models:# - "gpt-5.1" # exclude specific models (exact match)# - "gpt-5-*" # wildcard matching prefix (e.g. gpt-5-medium, gpt-5-codex)# - "*-mini" # wildcard matching suffix (e.g. gpt-5-codex-mini)# - "*codex*" # wildcard matching substring (e.g. gpt-5-codex-low)
# Claude API keys# claude-api-key:# - api-key: "sk-atSM..." # use the official claude API key, no need to set the base url# - api-key: "sk-atSM..."# prefix: "test" # optional: require calls like "test/claude-sonnet-latest" to target this credential# base-url: "https://www.example.com" # use the custom claude API endpoint# headers:# X-Custom-Header: "custom-value"# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override# models:# - name: "claude-3-5-sonnet-20241022" # upstream model name# alias: "claude-sonnet-latest" # client alias mapped to the upstream model# excluded-models:# - "claude-opus-4-5-20251101" # exclude specific models (exact match)# - "claude-3-*" # wildcard matching prefix (e.g. claude-3-7-sonnet-20250219)# - "*-thinking" # wildcard matching suffix (e.g. claude-opus-4-5-thinking)# - "*haiku*" # wildcard matching substring (e.g. claude-3-5-haiku-20241022)
# Kiro (AWS CodeWhisperer) configuration# Note: Kiro API currently only operates in us-east-1 region#kiro:# - token-file: "~/.aws/sso/cache/kiro-auth-token.json" # path to Kiro token file# agent-task-type: "" # optional: "vibe" or empty (API default)# - access-token: "aoaAAAAA..." # or provide tokens directly# refresh-token: "aorAAAAA..."# profile-arn: "arn:aws:codewhisperer:us-east-1:..."# proxy-url: "socks5://proxy.example.com:1080" # optional: proxy override
# OpenAI compatibility providers# openai-compatibility:# - name: "openrouter" # The name of the provider; it will be used in the user agent and other places.# prefix: "test" # optional: require calls like "test/kimi-k2" to target this provider's credentials# base-url: "https://openrouter.ai/api/v1" # The base URL of the provider.# headers:# X-Custom-Header: "custom-value"# api-key-entries:# - api-key: "sk-or-v1-...b780"# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override# - api-key: "sk-or-v1-...b781" # without proxy-url# models: # The models supported by the provider.# - name: "moonshotai/kimi-k2:free" # The actual model name.# alias: "kimi-k2" # The alias used in the API.
# Vertex API keys (Vertex-compatible endpoints, use API key + base URL)# vertex-api-key:# - api-key: "vk-123..." # x-goog-api-key header# prefix: "test" # optional: require calls like "test/vertex-pro" to target this credential# base-url: "https://example.com/api" # e.g. https://zenmux.ai/api# proxy-url: "socks5://proxy.example.com:1080" # optional per-key proxy override# headers:# X-Custom-Header: "custom-value"# models: # optional: map aliases to upstream model names# - name: "gemini-2.5-flash" # upstream model name# alias: "vertex-flash" # client-visible alias# - name: "gemini-2.5-pro"# alias: "vertex-pro"
# Amp Integration# ampcode:# # Configure upstream URL for Amp CLI OAuth and management features# upstream-url: "https://ampcode.com"# # Optional: Override API key for Amp upstream (otherwise uses env or file)# upstream-api-key: ""# # Per-client upstream API key mapping# # Maps client API keys (from top-level api-keys) to different Amp upstream API keys.# # Useful when different clients need to use different Amp accounts/quotas.# # If a client key isn't mapped, falls back to upstream-api-key (default behavior).# upstream-api-keys:# - upstream-api-key: "amp_key_for_team_a" # Upstream key to use for these clients# api-keys: # Client keys that use this upstream key# - "your-api-key-1"# - "your-api-key-2"# - upstream-api-key: "amp_key_for_team_b"# api-keys:# - "your-api-key-3"# # Restrict Amp management routes (/api/auth, /api/user, etc.) to localhost only (default: false)# restrict-management-to-localhost: false# # Force model mappings to run before checking local API keys (default: false)# force-model-mappings: false# # Amp Model Mappings# # Route unavailable Amp models to alternative models available in your local proxy.# # Useful when Amp CLI requests models you don't have access to (e.g., Claude Opus 4.5)# # but you have a similar model available (e.g., Claude Sonnet 4).# model-mappings:# - from: "claude-opus-4-5-20251101" # Model requested by Amp CLI# to: "gemini-claude-opus-4-5-thinking" # Route to this available model instead# - from: "claude-sonnet-4-5-20250929"# to: "gemini-claude-sonnet-4-5-thinking"# - from: "claude-haiku-4-5-20251001"# to: "gemini-2.5-flash"
# Global OAuth model name mappings (per channel)# These mappings rename model IDs for both model listing and request routing.# Supported channels: gemini-cli, vertex, aistudio, antigravity, claude, codex, qwen, iflow.# NOTE: Mappings do not apply to gemini-api-key, codex-api-key, claude-api-key, openai-compatibility, vertex-api-key, or ampcode.# oauth-model-mappings:# gemini-cli:# - name: "gemini-2.5-pro" # original model name under this channel# alias: "g2.5p" # client-visible alias# vertex:# - name: "gemini-2.5-pro"# alias: "g2.5p"# aistudio:# - name: "gemini-2.5-pro"# alias: "g2.5p"# antigravity:# - name: "gemini-3-pro-preview"# alias: "g3p"# claude:# - name: "claude-sonnet-4-5-20250929"# alias: "cs4.5"# codex:# - name: "gpt-5"# alias: "g5"# qwen:# - name: "qwen3-coder-plus"# alias: "qwen-plus"# iflow:# - name: "glm-4.7"# alias: "glm-god"
# OAuth provider excluded models# oauth-excluded-models:# gemini-cli:# - "gemini-2.5-pro" # exclude specific models (exact match)# - "gemini-2.5-*" # wildcard matching prefix (e.g. gemini-2.5-flash, gemini-2.5-pro)# - "*-preview" # wildcard matching suffix (e.g. gemini-3-pro-preview)# - "*flash*" # wildcard matching substring (e.g. gemini-2.5-flash-lite)# vertex:# - "gemini-3-pro-preview"# aistudio:# - "gemini-3-pro-preview"# antigravity:# - "gemini-3-pro-preview"# claude:# - "claude-3-5-haiku-20241022"# codex:# - "gpt-5-codex-mini"# qwen:# - "vision-model"# iflow:# - "tstars2.0"
# Optional payload configuration# payload:# default: # Default rules only set parameters when they are missing in the payload.# - models:# - name: "gemini-2.5-pro" # Supports wildcards (e.g., "gemini-*")# protocol: "gemini" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex# params: # JSON path (gjson/sjson syntax) -> value# "generationConfig.thinkingConfig.thinkingBudget": 32768# override: # Override rules always set parameters, overwriting any existing values.# - models:# - name: "gpt-*" # Supports wildcards (e.g., "gpt-*")# protocol: "codex" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex# params: # JSON path (gjson/sjson syntax) -> value# "reasoning.effort": "high"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475# CLIProxyAPI Plus - Ultimate Power Confighost: ""port: 7860
# TLS settings (disabled for HF)tls: enable: false
# Management API settings (REMOTE ENABLED FOR HF)remote-management: allow-remote: true secret-key: "$2a$10$Yt27TytUvABKw192YdTW2urLkQ5oQkHGuSz6PrzFFlsNJ5TE1EOFe" disable-control-panel: false panel-github-repository: "https://github.com/router-for-me/Cli-Proxy-API-Management-Center"
# Storageauth-dir: "./auth"
# Client Keys for YOU to access the APIapi-keys: - "sk-admin-power-1" - "sk-client-key-custom"
# Performance & Loggingdebug: falsecommercial-mode: falseincognito-browser: truelogging-to-file: falseusage-statistics-enabled: true
# Networkproxy-url: ""
# Smart Routing & Retriesrequest-retry: 5max-retry-interval: 15routing: strategy: "round-robin" # Rotates through your 16 keys!
quota-exceeded: switch-project: true switch-preview-model: true
# --- PROVIDER SECTIONS (FILL THESE IN THE ADMIN PANEL) ---
# 1. Gemini API Keys (Google AI Studio)gemini-api-key: - api-key: "DEIN_GEMINI_KEY_1" - api-key: "DEIN_GEMINI_KEY_2"
# 2. Claude API Keys (Anthropic)claude-api-key: - api-key: "DEIN_CLAUDE_KEY_1"
# 3. OpenAI / Compatibility (OpenRouter, DeepSeek, Groq, etc.)openai-compatibility: - name: "openrouter" base-url: "https://openrouter.ai/api/v1" api-key-entries: - api-key: "DEIN_OPENROUTER_KEY" - name: "deepseek" base-url: "https://api.deepseek.com/v1" api-key-entries: - api-key: "DEIN_DEEPSEEK_KEY"
# 4. Global Model Mappings (Rename models for easier use)oauth-model-mappings: gemini-cli: - name: "gemini-2.5-pro" alias: "g-pro" - name: "gemini-2.5-flash" alias: "g-flash" claude: - name: "claude-3-5-sonnet-20241022" alias: "sonnet"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778module github.com/router-for-me/CLIProxyAPI/v6
go 1.23
require ( github.com/andybalholm/brotli v1.0.6 github.com/fsnotify/fsnotify v1.9.0 github.com/gin-gonic/gin v1.10.1 github.com/go-git/go-git/v5 v5.12.0 github.com/google/uuid v1.6.0 github.com/gorilla/websocket v1.5.3 github.com/jackc/pgx/v5 v5.7.0 github.com/joho/godotenv v1.5.1 github.com/klauspost/compress v1.17.4 github.com/minio/minio-go/v7 v7.0.66 github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c github.com/sirupsen/logrus v1.9.3 github.com/tidwall/gjson v1.18.0 github.com/tidwall/sjson v1.2.5 github.com/tiktoken-go/tokenizer v0.7.0 golang.org/x/crypto v0.46.0 golang.org/x/net v0.48.0 golang.org/x/oauth2 v0.21.0 golang.org/x/term v0.38.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 gopkg.in/yaml.v3 v3.0.1)
require ( cloud.google.com/go/compute/metadata v0.3.0 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect github.com/ProtonMail/go-crypto v1.3.0 // indirect github.com/bytedance/sonic v1.11.6 // indirect github.com/bytedance/sonic/loader v0.1.1 // indirect github.com/cloudflare/circl v1.6.1 // indirect github.com/cloudwego/base64x v0.1.4 // indirect github.com/cloudwego/iasm v0.2.0 // indirect github.com/cyphar/filepath-securejoin v0.6.1 // indirect github.com/dlclark/regexp2 v1.11.5 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/emirpasic/gods v1.18.1 // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/go-git/gcfg v2.0.2 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.20.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect github.com/google/go-cmp v0.6.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.1 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kevinburke/ssh_config v1.4.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/kr/text v0.2.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/minio/md5-simd v1.1.2 // indirect github.com/minio/sha256-simd v1.0.1 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.2.2 // indirect github.com/pjbgf/sha1cd v0.5.0 // indirect github.com/rs/xid v1.5.0 // indirect github.com/sergi/go-diff v1.4.0 // indirect github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect golang.org/x/arch v0.8.0 // indirect golang.org/x/sync v0.19.0 // indirect golang.org/x/sys v0.39.0 // indirect golang.org/x/text v0.32.0 // indirect google.golang.org/protobuf v1.34.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc=cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k=github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=github.com/ProtonMail/go-crypto v1.3.0 h1:ILq8+Sf5If5DCpHQp4PbZdS1J7HDFRXz/+xKBiRGFrw=github.com/ProtonMail/go-crypto v1.3.0/go.mod h1:9whxjD8Rbs29b4XWbB8irEcE8KHMqaR2e7GWU1R+/PE=github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI=github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=github.com/cloudflare/circl v1.6.1 h1:zqIqSPIndyBh1bjLVVDHMPpVKqp8Su/V+6MeDzzQBQ0=github.com/cloudflare/circl v1.6.1/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=github.com/cyphar/filepath-securejoin v0.6.1 h1:5CeZ1jPXEiYt3+Z6zqprSAgSWiggmpVyciv8syjIpVE=github.com/cyphar/filepath-securejoin v0.6.1/go.mod h1:A8hd4EnAeyujCJRrICiOWqjS1AX0a9kM5XL+NwKoYSc=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=github.com/gin-gonic/gin v1.10.1 h1:T0ujvqyCSqRopADpgPgiTT63DUQVSfojyME59Ei63pQ=github.com/gin-gonic/gin v1.10.1/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=github.com/go-git/gcfg/v2 v2.0.2 h1:MY5SIIfTGGEMhdA7d7JePuVVxtKL7Hp+ApGDJAJ7dpo=github.com/go-git/gcfg/v2 v2.0.2/go.mod h1:/lv2NsxvhepuMrldsFilrgct6pxzpGdSRC13ydTLSLs=github.com/go-git/go-billy/v6 v6.0.0-20251217170237-e9738f50a3cd h1:Gd/f9cGi/3h1JOPaa6er+CkKUGyGX2DBJdFbDKVO+R0=github.com/go-git/go-billy/v6 v6.0.0-20251217170237-e9738f50a3cd/go.mod h1:d3XQcsHu1idnquxt48kAv+h+1MUiYKLH/e7LAzjP+pI=github.com/go-git/go-git-fixtures/v5 v5.1.2-0.20251229094738-4b14af179146 h1:xYfxAopYyL44ot6dMBIb1Z1njFM0ZBQ99HdIB99KxLs=github.com/go-git/go-git-fixtures/v5 v5.1.2-0.20251229094738-4b14af179146/go.mod h1:QE/75B8tBSLNGyUUbA9tw3EGHoFtYOtypa2h8YJxsWI=github.com/go-git/go-git/v6 v6.0.0-20251231065035-29ae690a9f19 h1:0lz2eJScP8v5YZQsrEw+ggWC5jNySjg4bIZo5BIh6iI=github.com/go-git/go-git/v6 v6.0.0-20251231065035-29ae690a9f19/go.mod h1:L+Evfcs7EdTqxwv854354cb6+++7TFL3hJn3Wy4g+3w=github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=github.com/jackc/pgx/v5 v5.7.0 h1:FG6VLIdzvAPhnYqP14sQ2xhFLkiUQHCs6ySqO91kF4g=github.com/jackc/pgx/v5 v5.7.0/go.mod h1:awP1KNnjylvpxHuHP63gzjhnGkI1iw+PMoIwvoleN/8=github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=github.com/kevinburke/ssh_config v1.4.0 h1:6xxtP5bZ2E4NF5tuQulISpTO2z8XbtH8cg1PWkxoFkQ=github.com/kevinburke/ssh_config v1.4.0/go.mod h1:q2RIzfka+BXARoNexmF9gkxEX7DmvbW9P4hIVx2Kg4M=github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4=github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM=github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=github.com/minio/minio-go/v7 v7.0.66 h1:bnTOXOHjOqv/gcMuiVbN9o2ngRItvqE774dG9nq0Dzw=github.com/minio/minio-go/v7 v7.0.66/go.mod h1:DHAgmyQEGdW3Cif0UooKOyrT3Vxs82zNdV6tkKhRtbs=github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM=github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8=github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=github.com/pjbgf/sha1cd v0.5.0 h1:a+UkboSi1znleCDUNT3M5YxjOnN1fz2FhN48FlwCxs0=github.com/pjbgf/sha1cd v0.5.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc=github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=github.com/tiktoken-go/tokenizer v0.7.0 h1:VMu6MPT0bXFDHr7UPh9uii7CNItVt3X9K90omxL54vw=github.com/tiktoken-go/tokenizer v0.7.0/go.mod h1:6UCYI/DtOallbmL7sSy30p6YQv60qNyU/4aVigPOx6w=github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=golang.org/x/oauth2 v0.21.0 h1:tsimM75w1tF/uws5rbeHzIWxEqElMehnc+iW793zsZs=golang.org/x/oauth2 v0.21.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI=golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112package configaccess
import ( "context" "net/http" "strings" "sync"
sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access" sdkconfig "github.com/router-for-me/CLIProxyAPI/v6/sdk/config")
var registerOnce sync.Once
// Register ensures the config-access provider is available to the access manager.func Register() { registerOnce.Do(func() { sdkaccess.RegisterProvider(sdkconfig.AccessProviderTypeConfigAPIKey, newProvider) })}
type provider struct { name string keys map[string]struct{}}
func newProvider(cfg *sdkconfig.AccessProvider, _ *sdkconfig.SDKConfig) (sdkaccess.Provider, error) { name := cfg.Name if name == "" { name = sdkconfig.DefaultAccessProviderName } keys := make(map[string]struct{}, len(cfg.APIKeys)) for _, key := range cfg.APIKeys { if key == "" { continue } keys[key] = struct{}{} } return &provider{name: name, keys: keys}, nil}
func (p *provider) Identifier() string { if p == nil || p.name == "" { return sdkconfig.DefaultAccessProviderName } return p.name}
func (p *provider) Authenticate(_ context.Context, r *http.Request) (*sdkaccess.Result, error) { if p == nil { return nil, sdkaccess.ErrNotHandled } if len(p.keys) == 0 { return nil, sdkaccess.ErrNotHandled } authHeader := r.Header.Get("Authorization") authHeaderGoogle := r.Header.Get("X-Goog-Api-Key") authHeaderAnthropic := r.Header.Get("X-Api-Key") queryKey := "" queryAuthToken := "" if r.URL != nil { queryKey = r.URL.Query().Get("key") queryAuthToken = r.URL.Query().Get("auth_token") } if authHeader == "" && authHeaderGoogle == "" && authHeaderAnthropic == "" && queryKey == "" && queryAuthToken == "" { return nil, sdkaccess.ErrNoCredentials }
apiKey := extractBearerToken(authHeader)
candidates := []struct { value string source string }{ {apiKey, "authorization"}, {authHeaderGoogle, "x-goog-api-key"}, {authHeaderAnthropic, "x-api-key"}, {queryKey, "query-key"}, {queryAuthToken, "query-auth-token"}, }
for _, candidate := range candidates { if candidate.value == "" { continue } if _, ok := p.keys[candidate.value]; ok { return &sdkaccess.Result{ Provider: p.Identifier(), Principal: candidate.value, Metadata: map[string]string{ "source": candidate.source, }, }, nil } }
return nil, sdkaccess.ErrInvalidCredential}
func extractBearerToken(header string) string { if header == "" { return "" } parts := strings.SplitN(header, " ", 2) if len(parts) != 2 { return header } if strings.ToLower(parts[0]) != "bearer" { return header } return strings.TrimSpace(parts[1])}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270package access
import ( "fmt" "reflect" "sort" "strings"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config" sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access" sdkConfig "github.com/router-for-me/CLIProxyAPI/v6/sdk/config" log "github.com/sirupsen/logrus")
// ReconcileProviders builds the desired provider list by reusing existing providers when possible// and creating or removing providers only when their configuration changed. It returns the final// ordered provider slice along with the identifiers of providers that were added, updated, or// removed compared to the previous configuration.func ReconcileProviders(oldCfg, newCfg *config.Config, existing []sdkaccess.Provider) (result []sdkaccess.Provider, added, updated, removed []string, err error) { if newCfg == nil { return nil, nil, nil, nil, nil }
existingMap := make(map[string]sdkaccess.Provider, len(existing)) for _, provider := range existing { if provider == nil { continue } existingMap[provider.Identifier()] = provider }
oldCfgMap := accessProviderMap(oldCfg) newEntries := collectProviderEntries(newCfg)
result = make([]sdkaccess.Provider, 0, len(newEntries)) finalIDs := make(map[string]struct{}, len(newEntries))
isInlineProvider := func(id string) bool { return strings.EqualFold(id, sdkConfig.DefaultAccessProviderName) } appendChange := func(list *[]string, id string) { if isInlineProvider(id) { return } *list = append(*list, id) }
for _, providerCfg := range newEntries { key := providerIdentifier(providerCfg) if key == "" { continue }
forceRebuild := strings.EqualFold(strings.TrimSpace(providerCfg.Type), sdkConfig.AccessProviderTypeConfigAPIKey) if oldCfgProvider, ok := oldCfgMap[key]; ok { isAliased := oldCfgProvider == providerCfg if !forceRebuild && !isAliased && providerConfigEqual(oldCfgProvider, providerCfg) { if existingProvider, okExisting := existingMap[key]; okExisting { result = append(result, existingProvider) finalIDs[key] = struct{}{} continue } } }
provider, buildErr := sdkaccess.BuildProvider(providerCfg, &newCfg.SDKConfig) if buildErr != nil { return nil, nil, nil, nil, buildErr } if _, ok := oldCfgMap[key]; ok { if _, existed := existingMap[key]; existed { appendChange(&updated, key) } else { appendChange(&added, key) } } else { appendChange(&added, key) } result = append(result, provider) finalIDs[key] = struct{}{} }
if len(result) == 0 { if inline := sdkConfig.MakeInlineAPIKeyProvider(newCfg.APIKeys); inline != nil { key := providerIdentifier(inline) if key != "" { if oldCfgProvider, ok := oldCfgMap[key]; ok { if providerConfigEqual(oldCfgProvider, inline) { if existingProvider, okExisting := existingMap[key]; okExisting { result = append(result, existingProvider) finalIDs[key] = struct{}{} goto inlineDone } } } provider, buildErr := sdkaccess.BuildProvider(inline, &newCfg.SDKConfig) if buildErr != nil { return nil, nil, nil, nil, buildErr } if _, existed := existingMap[key]; existed { appendChange(&updated, key) } else if _, hadOld := oldCfgMap[key]; hadOld { appendChange(&updated, key) } else { appendChange(&added, key) } result = append(result, provider) finalIDs[key] = struct{}{} } } inlineDone: }
removedSet := make(map[string]struct{}) for id := range existingMap { if _, ok := finalIDs[id]; !ok { if isInlineProvider(id) { continue } removedSet[id] = struct{}{} } }
removed = make([]string, 0, len(removedSet)) for id := range removedSet { removed = append(removed, id) }
sort.Strings(added) sort.Strings(updated) sort.Strings(removed)
return result, added, updated, removed, nil}
// ApplyAccessProviders reconciles the configured access providers against the// currently registered providers and updates the manager. It logs a concise// summary of the detected changes and returns whether any provider changed.func ApplyAccessProviders(manager *sdkaccess.Manager, oldCfg, newCfg *config.Config) (bool, error) { if manager == nil || newCfg == nil { return false, nil }
existing := manager.Providers() providers, added, updated, removed, err := ReconcileProviders(oldCfg, newCfg, existing) if err != nil { log.Errorf("failed to reconcile request auth providers: %v", err) return false, fmt.Errorf("reconciling access providers: %w", err) }
manager.SetProviders(providers)
if len(added)+len(updated)+len(removed) > 0 { log.Debugf("auth providers reconciled (added=%d updated=%d removed=%d)", len(added), len(updated), len(removed)) log.Debugf("auth providers changes details - added=%v updated=%v removed=%v", added, updated, removed) return true, nil }
log.Debug("auth providers unchanged after config update") return false, nil}
func accessProviderMap(cfg *config.Config) map[string]*sdkConfig.AccessProvider { result := make(map[string]*sdkConfig.AccessProvider) if cfg == nil { return result } for i := range cfg.Access.Providers { providerCfg := &cfg.Access.Providers[i] if providerCfg.Type == "" { continue } key := providerIdentifier(providerCfg) if key == "" { continue } result[key] = providerCfg } if len(result) == 0 && len(cfg.APIKeys) > 0 { if provider := sdkConfig.MakeInlineAPIKeyProvider(cfg.APIKeys); provider != nil { if key := providerIdentifier(provider); key != "" { result[key] = provider } } } return result}
func collectProviderEntries(cfg *config.Config) []*sdkConfig.AccessProvider { entries := make([]*sdkConfig.AccessProvider, 0, len(cfg.Access.Providers)) for i := range cfg.Access.Providers { providerCfg := &cfg.Access.Providers[i] if providerCfg.Type == "" { continue } if key := providerIdentifier(providerCfg); key != "" { entries = append(entries, providerCfg) } } if len(entries) == 0 && len(cfg.APIKeys) > 0 { if inline := sdkConfig.MakeInlineAPIKeyProvider(cfg.APIKeys); inline != nil { entries = append(entries, inline) } } return entries}
func providerIdentifier(provider *sdkConfig.AccessProvider) string { if provider == nil { return "" } if name := strings.TrimSpace(provider.Name); name != "" { return name } typ := strings.TrimSpace(provider.Type) if typ == "" { return "" } if strings.EqualFold(typ, sdkConfig.AccessProviderTypeConfigAPIKey) { return sdkConfig.DefaultAccessProviderName } return typ}
func providerConfigEqual(a, b *sdkConfig.AccessProvider) bool { if a == nil || b == nil { return a == nil && b == nil } if !strings.EqualFold(strings.TrimSpace(a.Type), strings.TrimSpace(b.Type)) { return false } if strings.TrimSpace(a.SDK) != strings.TrimSpace(b.SDK) { return false } if !stringSetEqual(a.APIKeys, b.APIKeys) { return false } if len(a.Config) != len(b.Config) { return false } if len(a.Config) > 0 && !reflect.DeepEqual(a.Config, b.Config) { return false } return true}
func stringSetEqual(a, b []string) bool { if len(a) != len(b) { return false } if len(a) == 0 { return true } seen := make(map[string]int, len(a)) for _, val := range a { seen[val]++ } for _, val := range b { count := seen[val] if count == 0 { return false } if count == 1 { delete(seen, val) } else { seen[val] = count - 1 } } return len(seen) == 0}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538package management
import ( "context" "encoding/json" "fmt" "io" "net" "net/http" "net/url" "strings" "time"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/runtime/geminicli" coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth" log "github.com/sirupsen/logrus" "golang.org/x/net/proxy" "golang.org/x/oauth2" "golang.org/x/oauth2/google")
const defaultAPICallTimeout = 60 * time.Second
const ( geminiOAuthClientID = "YOUR_CLIENT_ID" geminiOAuthClientSecret = "YOUR_CLIENT_SECRET")
var geminiOAuthScopes = []string{ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile",}
type apiCallRequest struct { AuthIndexSnake *string `json:"auth_index"` AuthIndexCamel *string `json:"authIndex"` AuthIndexPascal *string `json:"AuthIndex"` Method string `json:"method"` URL string `json:"url"` Header map[string]string `json:"header"` Data string `json:"data"`}
type apiCallResponse struct { StatusCode int `json:"status_code"` Header map[string][]string `json:"header"` Body string `json:"body"`}
// APICall makes a generic HTTP request on behalf of the management API caller.// It is protected by the management middleware.//// Endpoint://// POST /v0/management/api-call//// Authentication://// Same as other management APIs (requires a management key and remote-management rules).// You can provide the key via:// - Authorization: Bearer <key>// - X-Management-Key: <key>//// Request JSON:// - auth_index / authIndex / AuthIndex (optional):// The credential "auth_index" from GET /v0/management/auth-files (or other endpoints returning it).// If omitted or not found, credential-specific proxy/token substitution is skipped.// - method (required): HTTP method, e.g. GET, POST, PUT, PATCH, DELETE.// - url (required): Absolute URL including scheme and host, e.g. "https://api.example.com/v1/ping".// - header (optional): Request headers map.// Supports magic variable "$TOKEN$" which is replaced using the selected credential:// 1) metadata.access_token// 2) attributes.api_key// 3) metadata.token / metadata.id_token / metadata.cookie// Example: {"Authorization":"Bearer $TOKEN$"}.// Note: if you need to override the HTTP Host header, set header["Host"].// - data (optional): Raw request body as string (useful for POST/PUT/PATCH).//// Proxy selection (highest priority first):// 1. Selected credential proxy_url// 2. Global config proxy-url// 3. Direct connect (environment proxies are not used)//// Response JSON (returned with HTTP 200 when the APICall itself succeeds):// - status_code: Upstream HTTP status code.// - header: Upstream response headers.// - body: Upstream response body as string.//// Example://// curl -sS -X POST "http://127.0.0.1:8317/v0/management/api-call" \// -H "Authorization: Bearer <MANAGEMENT_KEY>" \// -H "Content-Type: application/json" \// -d '{"auth_index":"<AUTH_INDEX>","method":"GET","url":"https://api.example.com/v1/ping","header":{"Authorization":"Bearer $TOKEN$"}}'//// curl -sS -X POST "http://127.0.0.1:8317/v0/management/api-call" \// -H "Authorization: Bearer 831227" \// -H "Content-Type: application/json" \// -d '{"auth_index":"<AUTH_INDEX>","method":"POST","url":"https://api.example.com/v1/fetchAvailableModels","header":{"Authorization":"Bearer $TOKEN$","Content-Type":"application/json","User-Agent":"cliproxyapi"},"data":"{}"}'func (h *Handler) APICall(c *gin.Context) { var body apiCallRequest if errBindJSON := c.ShouldBindJSON(&body); errBindJSON != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"}) return }
method := strings.ToUpper(strings.TrimSpace(body.Method)) if method == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "missing method"}) return }
urlStr := strings.TrimSpace(body.URL) if urlStr == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "missing url"}) return } parsedURL, errParseURL := url.Parse(urlStr) if errParseURL != nil || parsedURL.Scheme == "" || parsedURL.Host == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid url"}) return }
authIndex := firstNonEmptyString(body.AuthIndexSnake, body.AuthIndexCamel, body.AuthIndexPascal) auth := h.authByIndex(authIndex)
reqHeaders := body.Header if reqHeaders == nil { reqHeaders = map[string]string{} }
var hostOverride string var token string var tokenResolved bool var tokenErr error for key, value := range reqHeaders { if !strings.Contains(value, "$TOKEN$") { continue } if !tokenResolved { token, tokenErr = h.resolveTokenForAuth(c.Request.Context(), auth) tokenResolved = true } if auth != nil && token == "" { if tokenErr != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "auth token refresh failed"}) return } c.JSON(http.StatusBadRequest, gin.H{"error": "auth token not found"}) return } if token == "" { continue } reqHeaders[key] = strings.ReplaceAll(value, "$TOKEN$", token) }
var requestBody io.Reader if body.Data != "" { requestBody = strings.NewReader(body.Data) }
req, errNewRequest := http.NewRequestWithContext(c.Request.Context(), method, urlStr, requestBody) if errNewRequest != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "failed to build request"}) return }
for key, value := range reqHeaders { if strings.EqualFold(key, "host") { hostOverride = strings.TrimSpace(value) continue } req.Header.Set(key, value) } if hostOverride != "" { req.Host = hostOverride }
httpClient := &http.Client{ Timeout: defaultAPICallTimeout, } httpClient.Transport = h.apiCallTransport(auth)
resp, errDo := httpClient.Do(req) if errDo != nil { log.WithError(errDo).Debug("management APICall request failed") c.JSON(http.StatusBadGateway, gin.H{"error": "request failed"}) return } defer func() { if errClose := resp.Body.Close(); errClose != nil { log.Errorf("response body close error: %v", errClose) } }()
respBody, errReadAll := io.ReadAll(resp.Body) if errReadAll != nil { c.JSON(http.StatusBadGateway, gin.H{"error": "failed to read response"}) return }
c.JSON(http.StatusOK, apiCallResponse{ StatusCode: resp.StatusCode, Header: resp.Header, Body: string(respBody), })}
func firstNonEmptyString(values ...*string) string { for _, v := range values { if v == nil { continue } if out := strings.TrimSpace(*v); out != "" { return out } } return ""}
func tokenValueForAuth(auth *coreauth.Auth) string { if auth == nil { return "" } if v := tokenValueFromMetadata(auth.Metadata); v != "" { return v } if auth.Attributes != nil { if v := strings.TrimSpace(auth.Attributes["api_key"]); v != "" { return v } } if shared := geminicli.ResolveSharedCredential(auth.Runtime); shared != nil { if v := tokenValueFromMetadata(shared.MetadataSnapshot()); v != "" { return v } } return ""}
func (h *Handler) resolveTokenForAuth(ctx context.Context, auth *coreauth.Auth) (string, error) { if auth == nil { return "", nil }
provider := strings.ToLower(strings.TrimSpace(auth.Provider)) if provider == "gemini-cli" { token, errToken := h.refreshGeminiOAuthAccessToken(ctx, auth) return token, errToken }
return tokenValueForAuth(auth), nil}
func (h *Handler) refreshGeminiOAuthAccessToken(ctx context.Context, auth *coreauth.Auth) (string, error) { if ctx == nil { ctx = context.Background() } if auth == nil { return "", nil }
metadata, updater := geminiOAuthMetadata(auth) if len(metadata) == 0 { return "", fmt.Errorf("gemini oauth metadata missing") }
base := make(map[string]any) if tokenRaw, ok := metadata["token"].(map[string]any); ok && tokenRaw != nil { base = cloneMap(tokenRaw) }
var token oauth2.Token if len(base) > 0 { if raw, errMarshal := json.Marshal(base); errMarshal == nil { _ = json.Unmarshal(raw, &token) } }
if token.AccessToken == "" { token.AccessToken = stringValue(metadata, "access_token") } if token.RefreshToken == "" { token.RefreshToken = stringValue(metadata, "refresh_token") } if token.TokenType == "" { token.TokenType = stringValue(metadata, "token_type") } if token.Expiry.IsZero() { if expiry := stringValue(metadata, "expiry"); expiry != "" { if ts, errParseTime := time.Parse(time.RFC3339, expiry); errParseTime == nil { token.Expiry = ts } } }
conf := &oauth2.Config{ ClientID: geminiOAuthClientID, ClientSecret: geminiOAuthClientSecret, Scopes: geminiOAuthScopes, Endpoint: google.Endpoint, }
ctxToken := ctx httpClient := &http.Client{ Timeout: defaultAPICallTimeout, Transport: h.apiCallTransport(auth), } ctxToken = context.WithValue(ctxToken, oauth2.HTTPClient, httpClient)
src := conf.TokenSource(ctxToken, &token) currentToken, errToken := src.Token() if errToken != nil { return "", errToken }
merged := buildOAuthTokenMap(base, currentToken) fields := buildOAuthTokenFields(currentToken, merged) if updater != nil { updater(fields) } return strings.TrimSpace(currentToken.AccessToken), nil}
func geminiOAuthMetadata(auth *coreauth.Auth) (map[string]any, func(map[string]any)) { if auth == nil { return nil, nil } if shared := geminicli.ResolveSharedCredential(auth.Runtime); shared != nil { snapshot := shared.MetadataSnapshot() return snapshot, func(fields map[string]any) { shared.MergeMetadata(fields) } } return auth.Metadata, func(fields map[string]any) { if auth.Metadata == nil { auth.Metadata = make(map[string]any) } for k, v := range fields { auth.Metadata[k] = v } }}
func stringValue(metadata map[string]any, key string) string { if len(metadata) == 0 || key == "" { return "" } if v, ok := metadata[key].(string); ok { return strings.TrimSpace(v) } return ""}
func cloneMap(in map[string]any) map[string]any { if len(in) == 0 { return nil } out := make(map[string]any, len(in)) for k, v := range in { out[k] = v } return out}
func buildOAuthTokenMap(base map[string]any, tok *oauth2.Token) map[string]any { merged := cloneMap(base) if merged == nil { merged = make(map[string]any) } if tok == nil { return merged } if raw, errMarshal := json.Marshal(tok); errMarshal == nil { var tokenMap map[string]any if errUnmarshal := json.Unmarshal(raw, &tokenMap); errUnmarshal == nil { for k, v := range tokenMap { merged[k] = v } } } return merged}
func buildOAuthTokenFields(tok *oauth2.Token, merged map[string]any) map[string]any { fields := make(map[string]any, 5) if tok != nil && tok.AccessToken != "" { fields["access_token"] = tok.AccessToken } if tok != nil && tok.TokenType != "" { fields["token_type"] = tok.TokenType } if tok != nil && tok.RefreshToken != "" { fields["refresh_token"] = tok.RefreshToken } if tok != nil && !tok.Expiry.IsZero() { fields["expiry"] = tok.Expiry.Format(time.RFC3339) } if len(merged) > 0 { fields["token"] = cloneMap(merged) } return fields}
func tokenValueFromMetadata(metadata map[string]any) string { if len(metadata) == 0 { return "" } if v, ok := metadata["accessToken"].(string); ok && strings.TrimSpace(v) != "" { return strings.TrimSpace(v) } if v, ok := metadata["access_token"].(string); ok && strings.TrimSpace(v) != "" { return strings.TrimSpace(v) } if tokenRaw, ok := metadata["token"]; ok && tokenRaw != nil { switch typed := tokenRaw.(type) { case string: if v := strings.TrimSpace(typed); v != "" { return v } case map[string]any: if v, ok := typed["access_token"].(string); ok && strings.TrimSpace(v) != "" { return strings.TrimSpace(v) } if v, ok := typed["accessToken"].(string); ok && strings.TrimSpace(v) != "" { return strings.TrimSpace(v) } case map[string]string: if v := strings.TrimSpace(typed["access_token"]); v != "" { return v } if v := strings.TrimSpace(typed["accessToken"]); v != "" { return v } } } if v, ok := metadata["token"].(string); ok && strings.TrimSpace(v) != "" { return strings.TrimSpace(v) } if v, ok := metadata["id_token"].(string); ok && strings.TrimSpace(v) != "" { return strings.TrimSpace(v) } if v, ok := metadata["cookie"].(string); ok && strings.TrimSpace(v) != "" { return strings.TrimSpace(v) } return ""}
func (h *Handler) authByIndex(authIndex string) *coreauth.Auth { authIndex = strings.TrimSpace(authIndex) if authIndex == "" || h == nil || h.authManager == nil { return nil } auths := h.authManager.List() for _, auth := range auths { if auth == nil { continue } auth.EnsureIndex() if auth.Index == authIndex { return auth } } return nil}
func (h *Handler) apiCallTransport(auth *coreauth.Auth) http.RoundTripper { var proxyCandidates []string if auth != nil { if proxyStr := strings.TrimSpace(auth.ProxyURL); proxyStr != "" { proxyCandidates = append(proxyCandidates, proxyStr) } } if h != nil && h.cfg != nil { if proxyStr := strings.TrimSpace(h.cfg.ProxyURL); proxyStr != "" { proxyCandidates = append(proxyCandidates, proxyStr) } }
for _, proxyStr := range proxyCandidates { if transport := buildProxyTransport(proxyStr); transport != nil { return transport } }
transport, ok := http.DefaultTransport.(*http.Transport) if !ok || transport == nil { return &http.Transport{Proxy: nil} } clone := transport.Clone() clone.Proxy = nil return clone}
func buildProxyTransport(proxyStr string) *http.Transport { proxyStr = strings.TrimSpace(proxyStr) if proxyStr == "" { return nil }
proxyURL, errParse := url.Parse(proxyStr) if errParse != nil { log.WithError(errParse).Debug("parse proxy URL failed") return nil } if proxyURL.Scheme == "" || proxyURL.Host == "" { log.Debug("proxy URL missing scheme/host") return nil }
if proxyURL.Scheme == "socks5" { var proxyAuth *proxy.Auth if proxyURL.User != nil { username := proxyURL.User.Username() password, _ := proxyURL.User.Password() proxyAuth = &proxy.Auth{User: username, Password: password} } dialer, errSOCKS5 := proxy.SOCKS5("tcp", proxyURL.Host, proxyAuth, proxy.Direct) if errSOCKS5 != nil { log.WithError(errSOCKS5).Debug("create SOCKS5 dialer failed") return nil } return &http.Transport{ Proxy: nil, DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { return dialer.Dial(network, addr) }, } }
if proxyURL.Scheme == "http" || proxyURL.Scheme == "https" { return &http.Transport{Proxy: http.ProxyURL(proxyURL)} }
log.Debugf("unsupported proxy scheme: %s", proxyURL.Scheme) return nil}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606package management
import ( "bytes" "context" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/url" "os" "path/filepath" "sort" "strconv" "strings" "sync" "time"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/claude" "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/codex" geminiAuth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/gemini" iflowauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/iflow" kiroauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/kiro" "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/qwen" "github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v6/internal/misc" "github.com/router-for-me/CLIProxyAPI/v6/internal/registry" "github.com/router-for-me/CLIProxyAPI/v6/internal/util" sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth" coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth" log "github.com/sirupsen/logrus" "github.com/tidwall/gjson" "golang.org/x/oauth2" "golang.org/x/oauth2/google")
var lastRefreshKeys = []string{"last_refresh", "lastRefresh", "last_refreshed_at", "lastRefreshedAt"}
const ( anthropicCallbackPort = 54545 geminiCallbackPort = 8085 codexCallbackPort = 1455 geminiCLIEndpoint = "https://cloudcode-pa.googleapis.com" geminiCLIVersion = "v1internal" geminiCLIUserAgent = "google-api-nodejs-client/9.15.1" geminiCLIApiClient = "gl-node/22.17.0" geminiCLIClientMetadata = "ideType=IDE_UNSPECIFIED,platform=PLATFORM_UNSPECIFIED,pluginType=GEMINI")
type callbackForwarder struct { provider string server *http.Server done chan struct{}}
var ( callbackForwardersMu sync.Mutex callbackForwarders = make(map[int]*callbackForwarder))
func extractLastRefreshTimestamp(meta map[string]any) (time.Time, bool) { if len(meta) == 0 { return time.Time{}, false } for _, key := range lastRefreshKeys { if val, ok := meta[key]; ok { if ts, ok1 := parseLastRefreshValue(val); ok1 { return ts, true } } } return time.Time{}, false}
func parseLastRefreshValue(v any) (time.Time, bool) { switch val := v.(type) { case string: s := strings.TrimSpace(val) if s == "" { return time.Time{}, false } layouts := []string{time.RFC3339, time.RFC3339Nano, "2006-01-02 15:04:05", "2006-01-02T15:04:05Z07:00"} for _, layout := range layouts { if ts, err := time.Parse(layout, s); err == nil { return ts.UTC(), true } } if unix, err := strconv.ParseInt(s, 10, 64); err == nil && unix > 0 { return time.Unix(unix, 0).UTC(), true } case float64: if val <= 0 { return time.Time{}, false } return time.Unix(int64(val), 0).UTC(), true case int64: if val <= 0 { return time.Time{}, false } return time.Unix(val, 0).UTC(), true case int: if val <= 0 { return time.Time{}, false } return time.Unix(int64(val), 0).UTC(), true case json.Number: if i, err := val.Int64(); err == nil && i > 0 { return time.Unix(i, 0).UTC(), true } } return time.Time{}, false}
func isWebUIRequest(c *gin.Context) bool { raw := strings.TrimSpace(c.Query("is_webui")) if raw == "" { return false } switch strings.ToLower(raw) { case "1", "true", "yes", "on": return true default: return false }}
func startCallbackForwarder(port int, provider, targetBase string) (*callbackForwarder, error) { callbackForwardersMu.Lock() prev := callbackForwarders[port] if prev != nil { delete(callbackForwarders, port) } callbackForwardersMu.Unlock()
if prev != nil { stopForwarderInstance(port, prev) }
addr := fmt.Sprintf("127.0.0.1:%d", port) ln, err := net.Listen("tcp", addr) if err != nil { return nil, fmt.Errorf("failed to listen on %s: %w", addr, err) }
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { target := targetBase if raw := r.URL.RawQuery; raw != "" { if strings.Contains(target, "?") { target = target + "&" + raw } else { target = target + "?" + raw } } w.Header().Set("Cache-Control", "no-store") http.Redirect(w, r, target, http.StatusFound) })
srv := &http.Server{ Handler: handler, ReadHeaderTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, } done := make(chan struct{})
go func() { if errServe := srv.Serve(ln); errServe != nil && !errors.Is(errServe, http.ErrServerClosed) { log.WithError(errServe).Warnf("callback forwarder for %s stopped unexpectedly", provider) } close(done) }()
forwarder := &callbackForwarder{ provider: provider, server: srv, done: done, }
callbackForwardersMu.Lock() callbackForwarders[port] = forwarder callbackForwardersMu.Unlock()
log.Infof("callback forwarder for %s listening on %s", provider, addr)
return forwarder, nil}
func stopCallbackForwarder(port int) { callbackForwardersMu.Lock() forwarder := callbackForwarders[port] if forwarder != nil { delete(callbackForwarders, port) } callbackForwardersMu.Unlock()
stopForwarderInstance(port, forwarder)}
func stopCallbackForwarderInstance(port int, forwarder *callbackForwarder) { if forwarder == nil { return } callbackForwardersMu.Lock() if current := callbackForwarders[port]; current == forwarder { delete(callbackForwarders, port) } callbackForwardersMu.Unlock()
stopForwarderInstance(port, forwarder)}
func stopForwarderInstance(port int, forwarder *callbackForwarder) { if forwarder == nil || forwarder.server == nil { return }
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel()
if err := forwarder.server.Shutdown(ctx); err != nil && !errors.Is(err, http.ErrServerClosed) { log.WithError(err).Warnf("failed to shut down callback forwarder on port %d", port) }
select { case <-forwarder.done: case <-time.After(2 * time.Second): }
log.Infof("callback forwarder on port %d stopped", port)}
func sanitizeAntigravityFileName(email string) string { if strings.TrimSpace(email) == "" { return "antigravity.json" } replacer := strings.NewReplacer("@", "_", ".", "_") return fmt.Sprintf("antigravity-%s.json", replacer.Replace(email))}
func (h *Handler) managementCallbackURL(path string) (string, error) { if h == nil || h.cfg == nil || h.cfg.Port <= 0 { return "", fmt.Errorf("server port is not configured") } if !strings.HasPrefix(path, "/") { path = "/" + path } scheme := "http" if h.cfg.TLS.Enable { scheme = "https" } return fmt.Sprintf("%s://127.0.0.1:%d%s", scheme, h.cfg.Port, path), nil}
func (h *Handler) ListAuthFiles(c *gin.Context) { if h == nil { c.JSON(500, gin.H{"error": "handler not initialized"}) return } if h.authManager == nil { h.listAuthFilesFromDisk(c) return } auths := h.authManager.List() files := make([]gin.H, 0, len(auths)) for _, auth := range auths { if entry := h.buildAuthFileEntry(auth); entry != nil { files = append(files, entry) } } sort.Slice(files, func(i, j int) bool { nameI, _ := files[i]["name"].(string) nameJ, _ := files[j]["name"].(string) return strings.ToLower(nameI) < strings.ToLower(nameJ) }) c.JSON(200, gin.H{"files": files})}
// GetAuthFileModels returns the models supported by a specific auth filefunc (h *Handler) GetAuthFileModels(c *gin.Context) { name := c.Query("name") if name == "" { c.JSON(400, gin.H{"error": "name is required"}) return }
// Try to find auth ID via authManager var authID string if h.authManager != nil { auths := h.authManager.List() for _, auth := range auths { if auth.FileName == name || auth.ID == name { authID = auth.ID break } } }
if authID == "" { authID = name // fallback to filename as ID }
// Get models from registry reg := registry.GetGlobalRegistry() models := reg.GetModelsForClient(authID)
result := make([]gin.H, 0, len(models)) for _, m := range models { entry := gin.H{ "id": m.ID, } if m.DisplayName != "" { entry["display_name"] = m.DisplayName } if m.Type != "" { entry["type"] = m.Type } if m.OwnedBy != "" { entry["owned_by"] = m.OwnedBy } result = append(result, entry) }
c.JSON(200, gin.H{"models": result})}
// List auth files from disk when the auth manager is unavailable.func (h *Handler) listAuthFilesFromDisk(c *gin.Context) { entries, err := os.ReadDir(h.cfg.AuthDir) if err != nil { c.JSON(500, gin.H{"error": fmt.Sprintf("failed to read auth dir: %v", err)}) return } files := make([]gin.H, 0) for _, e := range entries { if e.IsDir() { continue } name := e.Name() if !strings.HasSuffix(strings.ToLower(name), ".json") { continue } if info, errInfo := e.Info(); errInfo == nil { fileData := gin.H{"name": name, "size": info.Size(), "modtime": info.ModTime()}
// Read file to get type field full := filepath.Join(h.cfg.AuthDir, name) if data, errRead := os.ReadFile(full); errRead == nil { typeValue := gjson.GetBytes(data, "type").String() emailValue := gjson.GetBytes(data, "email").String() fileData["type"] = typeValue fileData["email"] = emailValue }
files = append(files, fileData) } } c.JSON(200, gin.H{"files": files})}
func (h *Handler) buildAuthFileEntry(auth *coreauth.Auth) gin.H { if auth == nil { return nil } auth.EnsureIndex() runtimeOnly := isRuntimeOnlyAuth(auth) if runtimeOnly && (auth.Disabled || auth.Status == coreauth.StatusDisabled) { return nil } path := strings.TrimSpace(authAttribute(auth, "path")) if path == "" && !runtimeOnly { return nil } name := strings.TrimSpace(auth.FileName) if name == "" { name = auth.ID } entry := gin.H{ "id": auth.ID, "auth_index": auth.Index, "name": name, "type": strings.TrimSpace(auth.Provider), "provider": strings.TrimSpace(auth.Provider), "label": auth.Label, "status": auth.Status, "status_message": auth.StatusMessage, "disabled": auth.Disabled, "unavailable": auth.Unavailable, "runtime_only": runtimeOnly, "source": "memory", "size": int64(0), } if email := authEmail(auth); email != "" { entry["email"] = email } if accountType, account := auth.AccountInfo(); accountType != "" || account != "" { if accountType != "" { entry["account_type"] = accountType } if account != "" { entry["account"] = account } } if !auth.CreatedAt.IsZero() { entry["created_at"] = auth.CreatedAt } if !auth.UpdatedAt.IsZero() { entry["modtime"] = auth.UpdatedAt entry["updated_at"] = auth.UpdatedAt } if !auth.LastRefreshedAt.IsZero() { entry["last_refresh"] = auth.LastRefreshedAt } if path != "" { entry["path"] = path entry["source"] = "file" if info, err := os.Stat(path); err == nil { entry["size"] = info.Size() entry["modtime"] = info.ModTime() } else if os.IsNotExist(err) { // Hide credentials removed from disk but still lingering in memory. if !runtimeOnly && (auth.Disabled || auth.Status == coreauth.StatusDisabled || strings.EqualFold(strings.TrimSpace(auth.StatusMessage), "removed via management api")) { return nil } entry["source"] = "memory" } else { log.WithError(err).Warnf("failed to stat auth file %s", path) } } if claims := extractCodexIDTokenClaims(auth); claims != nil { entry["id_token"] = claims } return entry}
func extractCodexIDTokenClaims(auth *coreauth.Auth) gin.H { if auth == nil || auth.Metadata == nil { return nil } if !strings.EqualFold(strings.TrimSpace(auth.Provider), "codex") { return nil } idTokenRaw, ok := auth.Metadata["id_token"].(string) if !ok { return nil } idToken := strings.TrimSpace(idTokenRaw) if idToken == "" { return nil } claims, err := codex.ParseJWTToken(idToken) if err != nil || claims == nil { return nil }
result := gin.H{} if v := strings.TrimSpace(claims.CodexAuthInfo.ChatgptAccountID); v != "" { result["chatgpt_account_id"] = v } if v := strings.TrimSpace(claims.CodexAuthInfo.ChatgptPlanType); v != "" { result["plan_type"] = v }
if len(result) == 0 { return nil } return result}
func authEmail(auth *coreauth.Auth) string { if auth == nil { return "" } if auth.Metadata != nil { if v, ok := auth.Metadata["email"].(string); ok { return strings.TrimSpace(v) } } if auth.Attributes != nil { if v := strings.TrimSpace(auth.Attributes["email"]); v != "" { return v } if v := strings.TrimSpace(auth.Attributes["account_email"]); v != "" { return v } } return ""}
func authAttribute(auth *coreauth.Auth, key string) string { if auth == nil || len(auth.Attributes) == 0 { return "" } return auth.Attributes[key]}
func isRuntimeOnlyAuth(auth *coreauth.Auth) bool { if auth == nil || len(auth.Attributes) == 0 { return false } return strings.EqualFold(strings.TrimSpace(auth.Attributes["runtime_only"]), "true")}
// Download single auth file by namefunc (h *Handler) DownloadAuthFile(c *gin.Context) { name := c.Query("name") if name == "" || strings.Contains(name, string(os.PathSeparator)) { c.JSON(400, gin.H{"error": "invalid name"}) return } if !strings.HasSuffix(strings.ToLower(name), ".json") { c.JSON(400, gin.H{"error": "name must end with .json"}) return } full := filepath.Join(h.cfg.AuthDir, name) data, err := os.ReadFile(full) if err != nil { if os.IsNotExist(err) { c.JSON(404, gin.H{"error": "file not found"}) } else { c.JSON(500, gin.H{"error": fmt.Sprintf("failed to read file: %v", err)}) } return } c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", name)) c.Data(200, "application/json", data)}
// Upload auth file: multipart or raw JSON with ?name=func (h *Handler) UploadAuthFile(c *gin.Context) { if h.authManager == nil { c.JSON(http.StatusServiceUnavailable, gin.H{"error": "core auth manager unavailable"}) return } ctx := c.Request.Context() if file, err := c.FormFile("file"); err == nil && file != nil { name := filepath.Base(file.Filename) if !strings.HasSuffix(strings.ToLower(name), ".json") { c.JSON(400, gin.H{"error": "file must be .json"}) return } dst := filepath.Join(h.cfg.AuthDir, name) if !filepath.IsAbs(dst) { if abs, errAbs := filepath.Abs(dst); errAbs == nil { dst = abs } } if errSave := c.SaveUploadedFile(file, dst); errSave != nil { c.JSON(500, gin.H{"error": fmt.Sprintf("failed to save file: %v", errSave)}) return } data, errRead := os.ReadFile(dst) if errRead != nil { c.JSON(500, gin.H{"error": fmt.Sprintf("failed to read saved file: %v", errRead)}) return } if errReg := h.registerAuthFromFile(ctx, dst, data); errReg != nil { c.JSON(500, gin.H{"error": errReg.Error()}) return } c.JSON(200, gin.H{"status": "ok"}) return } name := c.Query("name") if name == "" || strings.Contains(name, string(os.PathSeparator)) { c.JSON(400, gin.H{"error": "invalid name"}) return } if !strings.HasSuffix(strings.ToLower(name), ".json") { c.JSON(400, gin.H{"error": "name must end with .json"}) return } data, err := io.ReadAll(c.Request.Body) if err != nil { c.JSON(400, gin.H{"error": "failed to read body"}) return } dst := filepath.Join(h.cfg.AuthDir, filepath.Base(name)) if !filepath.IsAbs(dst) { if abs, errAbs := filepath.Abs(dst); errAbs == nil { dst = abs } } if errWrite := os.WriteFile(dst, data, 0o600); errWrite != nil { c.JSON(500, gin.H{"error": fmt.Sprintf("failed to write file: %v", errWrite)}) return } if err = h.registerAuthFromFile(ctx, dst, data); err != nil { c.JSON(500, gin.H{"error": err.Error()}) return } c.JSON(200, gin.H{"status": "ok"})}
// Delete auth files: single by name or allfunc (h *Handler) DeleteAuthFile(c *gin.Context) { if h.authManager == nil { c.JSON(http.StatusServiceUnavailable, gin.H{"error": "core auth manager unavailable"}) return } ctx := c.Request.Context() if all := c.Query("all"); all == "true" || all == "1" || all == "*" { entries, err := os.ReadDir(h.cfg.AuthDir) if err != nil { c.JSON(500, gin.H{"error": fmt.Sprintf("failed to read auth dir: %v", err)}) return } deleted := 0 for _, e := range entries { if e.IsDir() { continue } name := e.Name() if !strings.HasSuffix(strings.ToLower(name), ".json") { continue } full := filepath.Join(h.cfg.AuthDir, name) if !filepath.IsAbs(full) { if abs, errAbs := filepath.Abs(full); errAbs == nil { full = abs } } if err = os.Remove(full); err == nil { if errDel := h.deleteTokenRecord(ctx, full); errDel != nil { c.JSON(500, gin.H{"error": errDel.Error()}) return } deleted++ h.disableAuth(ctx, full) } } c.JSON(200, gin.H{"status": "ok", "deleted": deleted}) return } name := c.Query("name") if name == "" || strings.Contains(name, string(os.PathSeparator)) { c.JSON(400, gin.H{"error": "invalid name"}) return } full := filepath.Join(h.cfg.AuthDir, filepath.Base(name)) if !filepath.IsAbs(full) { if abs, errAbs := filepath.Abs(full); errAbs == nil { full = abs } } if err := os.Remove(full); err != nil { if os.IsNotExist(err) { c.JSON(404, gin.H{"error": "file not found"}) } else { c.JSON(500, gin.H{"error": fmt.Sprintf("failed to remove file: %v", err)}) } return } if err := h.deleteTokenRecord(ctx, full); err != nil { c.JSON(500, gin.H{"error": err.Error()}) return } h.disableAuth(ctx, full) c.JSON(200, gin.H{"status": "ok"})}
func (h *Handler) authIDForPath(path string) string { path = strings.TrimSpace(path) if path == "" { return "" } if h == nil || h.cfg == nil { return path } authDir := strings.TrimSpace(h.cfg.AuthDir) if authDir == "" { return path } if rel, err := filepath.Rel(authDir, path); err == nil && rel != "" { return rel } return path}
func (h *Handler) registerAuthFromFile(ctx context.Context, path string, data []byte) error { if h.authManager == nil { return nil } if path == "" { return fmt.Errorf("auth path is empty") } if data == nil { var err error data, err = os.ReadFile(path) if err != nil { return fmt.Errorf("failed to read auth file: %w", err) } } metadata := make(map[string]any) if err := json.Unmarshal(data, &metadata); err != nil { return fmt.Errorf("invalid auth file: %w", err) } provider, _ := metadata["type"].(string) if provider == "" { provider = "unknown" } label := provider if email, ok := metadata["email"].(string); ok && email != "" { label = email } lastRefresh, hasLastRefresh := extractLastRefreshTimestamp(metadata)
authID := h.authIDForPath(path) if authID == "" { authID = path } attr := map[string]string{ "path": path, "source": path, } auth := &coreauth.Auth{ ID: authID, Provider: provider, FileName: filepath.Base(path), Label: label, Status: coreauth.StatusActive, Attributes: attr, Metadata: metadata, CreatedAt: time.Now(), UpdatedAt: time.Now(), } if hasLastRefresh { auth.LastRefreshedAt = lastRefresh } if existing, ok := h.authManager.GetByID(authID); ok { auth.CreatedAt = existing.CreatedAt if !hasLastRefresh { auth.LastRefreshedAt = existing.LastRefreshedAt } auth.NextRefreshAfter = existing.NextRefreshAfter auth.Runtime = existing.Runtime _, err := h.authManager.Update(ctx, auth) return err } _, err := h.authManager.Register(ctx, auth) return err}
func (h *Handler) disableAuth(ctx context.Context, id string) { if h == nil || h.authManager == nil { return } authID := h.authIDForPath(id) if authID == "" { authID = strings.TrimSpace(id) } if authID == "" { return } if auth, ok := h.authManager.GetByID(authID); ok { auth.Disabled = true auth.Status = coreauth.StatusDisabled auth.StatusMessage = "removed via management API" auth.UpdatedAt = time.Now() _, _ = h.authManager.Update(ctx, auth) }}
func (h *Handler) deleteTokenRecord(ctx context.Context, path string) error { if strings.TrimSpace(path) == "" { return fmt.Errorf("auth path is empty") } store := h.tokenStoreWithBaseDir() if store == nil { return fmt.Errorf("token store unavailable") } return store.Delete(ctx, path)}
func (h *Handler) tokenStoreWithBaseDir() coreauth.Store { if h == nil { return nil } store := h.tokenStore if store == nil { store = sdkAuth.GetTokenStore() h.tokenStore = store } if h.cfg != nil { if dirSetter, ok := store.(interface{ SetBaseDir(string) }); ok { dirSetter.SetBaseDir(h.cfg.AuthDir) } } return store}
func (h *Handler) saveTokenRecord(ctx context.Context, record *coreauth.Auth) (string, error) { if record == nil { return "", fmt.Errorf("token record is nil") } store := h.tokenStoreWithBaseDir() if store == nil { return "", fmt.Errorf("token store unavailable") } return store.Save(ctx, record)}
func (h *Handler) RequestAnthropicToken(c *gin.Context) { ctx := context.Background()
fmt.Println("Initializing Claude authentication...")
// Generate PKCE codes pkceCodes, err := claude.GeneratePKCECodes() if err != nil { log.Errorf("Failed to generate PKCE codes: %v", err) c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate PKCE codes"}) return }
// Generate random state parameter state, err := misc.GenerateRandomState() if err != nil { log.Errorf("Failed to generate state parameter: %v", err) c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate state parameter"}) return }
// Initialize Claude auth service anthropicAuth := claude.NewClaudeAuth(h.cfg)
// Generate authorization URL (then override redirect_uri to reuse server port) authURL, state, err := anthropicAuth.GenerateAuthURL(state, pkceCodes) if err != nil { log.Errorf("Failed to generate authorization URL: %v", err) c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate authorization url"}) return }
RegisterOAuthSession(state, "anthropic")
isWebUI := isWebUIRequest(c) var forwarder *callbackForwarder if isWebUI { targetURL, errTarget := h.managementCallbackURL("/anthropic/callback") if errTarget != nil { log.WithError(errTarget).Error("failed to compute anthropic callback target") c.JSON(http.StatusInternalServerError, gin.H{"error": "callback server unavailable"}) return } var errStart error if forwarder, errStart = startCallbackForwarder(anthropicCallbackPort, "anthropic", targetURL); errStart != nil { log.WithError(errStart).Error("failed to start anthropic callback forwarder") c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to start callback server"}) return } }
go func() { if isWebUI { defer stopCallbackForwarderInstance(anthropicCallbackPort, forwarder) }
// Helper: wait for callback file waitFile := filepath.Join(h.cfg.AuthDir, fmt.Sprintf(".oauth-anthropic-%s.oauth", state)) waitForFile := func(path string, timeout time.Duration) (map[string]string, error) { deadline := time.Now().Add(timeout) for { if !IsOAuthSessionPending(state, "anthropic") { return nil, errOAuthSessionNotPending } if time.Now().After(deadline) { SetOAuthSessionError(state, "Timeout waiting for OAuth callback") return nil, fmt.Errorf("timeout waiting for OAuth callback") } data, errRead := os.ReadFile(path) if errRead == nil { var m map[string]string _ = json.Unmarshal(data, &m) _ = os.Remove(path) return m, nil } time.Sleep(500 * time.Millisecond) } }
fmt.Println("Waiting for authentication callback...") // Wait up to 5 minutes resultMap, errWait := waitForFile(waitFile, 5*time.Minute) if errWait != nil { if errors.Is(errWait, errOAuthSessionNotPending) { return } authErr := claude.NewAuthenticationError(claude.ErrCallbackTimeout, errWait) log.Error(claude.GetUserFriendlyMessage(authErr)) return } if errStr := resultMap["error"]; errStr != "" { oauthErr := claude.NewOAuthError(errStr, "", http.StatusBadRequest) log.Error(claude.GetUserFriendlyMessage(oauthErr)) SetOAuthSessionError(state, "Bad request") return } if resultMap["state"] != state { authErr := claude.NewAuthenticationError(claude.ErrInvalidState, fmt.Errorf("expected %s, got %s", state, resultMap["state"])) log.Error(claude.GetUserFriendlyMessage(authErr)) SetOAuthSessionError(state, "State code error") return }
// Parse code (Claude may append state after '#') rawCode := resultMap["code"] code := strings.Split(rawCode, "#")[0]
// Exchange code for tokens (replicate logic using updated redirect_uri) // Extract client_id from the modified auth URL clientID := "" if u2, errP := url.Parse(authURL); errP == nil { clientID = u2.Query().Get("client_id") } // Build request bodyMap := map[string]any{ "code": code, "state": state, "grant_type": "authorization_code", "client_id": clientID, "redirect_uri": "http://localhost:54545/callback", "code_verifier": pkceCodes.CodeVerifier, } bodyJSON, _ := json.Marshal(bodyMap)
httpClient := util.SetProxy(&h.cfg.SDKConfig, &http.Client{}) req, _ := http.NewRequestWithContext(ctx, "POST", "https://console.anthropic.com/v1/oauth/token", strings.NewReader(string(bodyJSON))) req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") resp, errDo := httpClient.Do(req) if errDo != nil { authErr := claude.NewAuthenticationError(claude.ErrCodeExchangeFailed, errDo) log.Errorf("Failed to exchange authorization code for tokens: %v", authErr) SetOAuthSessionError(state, "Failed to exchange authorization code for tokens") return } defer func() { if errClose := resp.Body.Close(); errClose != nil { log.Errorf("failed to close response body: %v", errClose) } }() respBody, _ := io.ReadAll(resp.Body) if resp.StatusCode != http.StatusOK { log.Errorf("token exchange failed with status %d: %s", resp.StatusCode, string(respBody)) SetOAuthSessionError(state, fmt.Sprintf("token exchange failed with status %d", resp.StatusCode)) return } var tResp struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` ExpiresIn int `json:"expires_in"` Account struct { EmailAddress string `json:"email_address"` } `json:"account"` } if errU := json.Unmarshal(respBody, &tResp); errU != nil { log.Errorf("failed to parse token response: %v", errU) SetOAuthSessionError(state, "Failed to parse token response") return } bundle := &claude.ClaudeAuthBundle{ TokenData: claude.ClaudeTokenData{ AccessToken: tResp.AccessToken, RefreshToken: tResp.RefreshToken, Email: tResp.Account.EmailAddress, Expire: time.Now().Add(time.Duration(tResp.ExpiresIn) * time.Second).Format(time.RFC3339), }, LastRefresh: time.Now().Format(time.RFC3339), }
// Create token storage tokenStorage := anthropicAuth.CreateTokenStorage(bundle) record := &coreauth.Auth{ ID: fmt.Sprintf("claude-%s.json", tokenStorage.Email), Provider: "claude", FileName: fmt.Sprintf("claude-%s.json", tokenStorage.Email), Storage: tokenStorage, Metadata: map[string]any{"email": tokenStorage.Email}, } savedPath, errSave := h.saveTokenRecord(ctx, record) if errSave != nil { log.Errorf("Failed to save authentication tokens: %v", errSave) SetOAuthSessionError(state, "Failed to save authentication tokens") return }
fmt.Printf("Authentication successful! Token saved to %s\n", savedPath) if bundle.APIKey != "" { fmt.Println("API key obtained and saved") } fmt.Println("You can now use Claude services through this CLI") CompleteOAuthSession(state) CompleteOAuthSessionsByProvider("anthropic") }()
c.JSON(200, gin.H{"status": "ok", "url": authURL, "state": state})}
func (h *Handler) RequestGeminiCLIToken(c *gin.Context) { ctx := context.Background() proxyHTTPClient := util.SetProxy(&h.cfg.SDKConfig, &http.Client{}) ctx = context.WithValue(ctx, oauth2.HTTPClient, proxyHTTPClient)
// Optional project ID from query projectID := c.Query("project_id")
fmt.Println("Initializing Google authentication...")
// OAuth2 configuration (mirrors internal/auth/gemini) conf := &oauth2.Config{ ClientID: "YOUR_CLIENT_ID", ClientSecret: "YOUR_CLIENT_SECRET", RedirectURL: "http://localhost:8085/oauth2callback", Scopes: []string{ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", }, Endpoint: google.Endpoint, }
// Build authorization URL and return it immediately state := fmt.Sprintf("gem-%d", time.Now().UnixNano()) authURL := conf.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.SetAuthURLParam("prompt", "consent"))
RegisterOAuthSession(state, "gemini")
isWebUI := isWebUIRequest(c) var forwarder *callbackForwarder if isWebUI { targetURL, errTarget := h.managementCallbackURL("/google/callback") if errTarget != nil { log.WithError(errTarget).Error("failed to compute gemini callback target") c.JSON(http.StatusInternalServerError, gin.H{"error": "callback server unavailable"}) return } var errStart error if forwarder, errStart = startCallbackForwarder(geminiCallbackPort, "gemini", targetURL); errStart != nil { log.WithError(errStart).Error("failed to start gemini callback forwarder") c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to start callback server"}) return } }
go func() { if isWebUI { defer stopCallbackForwarderInstance(geminiCallbackPort, forwarder) }
// Wait for callback file written by server route waitFile := filepath.Join(h.cfg.AuthDir, fmt.Sprintf(".oauth-gemini-%s.oauth", state)) fmt.Println("Waiting for authentication callback...") deadline := time.Now().Add(5 * time.Minute) var authCode string for { if !IsOAuthSessionPending(state, "gemini") { return } if time.Now().After(deadline) { log.Error("oauth flow timed out") SetOAuthSessionError(state, "OAuth flow timed out") return } if data, errR := os.ReadFile(waitFile); errR == nil { var m map[string]string _ = json.Unmarshal(data, &m) _ = os.Remove(waitFile) if errStr := m["error"]; errStr != "" { log.Errorf("Authentication failed: %s", errStr) SetOAuthSessionError(state, "Authentication failed") return } authCode = m["code"] if authCode == "" { log.Errorf("Authentication failed: code not found") SetOAuthSessionError(state, "Authentication failed: code not found") return } break } time.Sleep(500 * time.Millisecond) }
// Exchange authorization code for token token, err := conf.Exchange(ctx, authCode) if err != nil { log.Errorf("Failed to exchange token: %v", err) SetOAuthSessionError(state, "Failed to exchange token") return }
requestedProjectID := strings.TrimSpace(projectID)
// Create token storage (mirrors internal/auth/gemini createTokenStorage) authHTTPClient := conf.Client(ctx, token) req, errNewRequest := http.NewRequestWithContext(ctx, "GET", "https://www.googleapis.com/oauth2/v1/userinfo?alt=json", nil) if errNewRequest != nil { log.Errorf("Could not get user info: %v", errNewRequest) SetOAuthSessionError(state, "Could not get user info") return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token.AccessToken))
resp, errDo := authHTTPClient.Do(req) if errDo != nil { log.Errorf("Failed to execute request: %v", errDo) SetOAuthSessionError(state, "Failed to execute request") return } defer func() { if errClose := resp.Body.Close(); errClose != nil { log.Printf("warn: failed to close response body: %v", errClose) } }()
bodyBytes, _ := io.ReadAll(resp.Body) if resp.StatusCode < 200 || resp.StatusCode >= 300 { log.Errorf("Get user info request failed with status %d: %s", resp.StatusCode, string(bodyBytes)) SetOAuthSessionError(state, fmt.Sprintf("Get user info request failed with status %d", resp.StatusCode)) return }
email := gjson.GetBytes(bodyBytes, "email").String() if email != "" { fmt.Printf("Authenticated user email: %s\n", email) } else { fmt.Println("Failed to get user email from token") }
// Marshal/unmarshal oauth2.Token to generic map and enrich fields var ifToken map[string]any jsonData, _ := json.Marshal(token) if errUnmarshal := json.Unmarshal(jsonData, &ifToken); errUnmarshal != nil { log.Errorf("Failed to unmarshal token: %v", errUnmarshal) SetOAuthSessionError(state, "Failed to unmarshal token") return }
ifToken["token_uri"] = "https://oauth2.googleapis.com/token" ifToken["client_id"] = "YOUR_CLIENT_ID" ifToken["client_secret"] = "YOUR_CLIENT_SECRET" ifToken["scopes"] = []string{ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", } ifToken["universe_domain"] = "googleapis.com"
ts := geminiAuth.GeminiTokenStorage{ Token: ifToken, ProjectID: requestedProjectID, Email: email, Auto: requestedProjectID == "", }
// Initialize authenticated HTTP client via GeminiAuth to honor proxy settings gemAuth := geminiAuth.NewGeminiAuth() gemClient, errGetClient := gemAuth.GetAuthenticatedClient(ctx, &ts, h.cfg, &geminiAuth.WebLoginOptions{ NoBrowser: true, }) if errGetClient != nil { log.Errorf("failed to get authenticated client: %v", errGetClient) SetOAuthSessionError(state, "Failed to get authenticated client") return } fmt.Println("Authentication successful.")
if strings.EqualFold(requestedProjectID, "ALL") { ts.Auto = false projects, errAll := onboardAllGeminiProjects(ctx, gemClient, &ts) if errAll != nil { log.Errorf("Failed to complete Gemini CLI onboarding: %v", errAll) SetOAuthSessionError(state, "Failed to complete Gemini CLI onboarding") return } if errVerify := ensureGeminiProjectsEnabled(ctx, gemClient, projects); errVerify != nil { log.Errorf("Failed to verify Cloud AI API status: %v", errVerify) SetOAuthSessionError(state, "Failed to verify Cloud AI API status") return } ts.ProjectID = strings.Join(projects, ",") ts.Checked = true } else { if errEnsure := ensureGeminiProjectAndOnboard(ctx, gemClient, &ts, requestedProjectID); errEnsure != nil { log.Errorf("Failed to complete Gemini CLI onboarding: %v", errEnsure) SetOAuthSessionError(state, "Failed to complete Gemini CLI onboarding") return }
if strings.TrimSpace(ts.ProjectID) == "" { log.Error("Onboarding did not return a project ID") SetOAuthSessionError(state, "Failed to resolve project ID") return }
isChecked, errCheck := checkCloudAPIIsEnabled(ctx, gemClient, ts.ProjectID) if errCheck != nil { log.Errorf("Failed to verify Cloud AI API status: %v", errCheck) SetOAuthSessionError(state, "Failed to verify Cloud AI API status") return } ts.Checked = isChecked if !isChecked { log.Error("Cloud AI API is not enabled for the selected project") SetOAuthSessionError(state, "Cloud AI API not enabled") return } }
recordMetadata := map[string]any{ "email": ts.Email, "project_id": ts.ProjectID, "auto": ts.Auto, "checked": ts.Checked, }
fileName := geminiAuth.CredentialFileName(ts.Email, ts.ProjectID, true) record := &coreauth.Auth{ ID: fileName, Provider: "gemini", FileName: fileName, Storage: &ts, Metadata: recordMetadata, } savedPath, errSave := h.saveTokenRecord(ctx, record) if errSave != nil { log.Errorf("Failed to save token to file: %v", errSave) SetOAuthSessionError(state, "Failed to save token to file") return }
CompleteOAuthSession(state) CompleteOAuthSessionsByProvider("gemini") fmt.Printf("You can now use Gemini CLI services through this CLI; token saved to %s\n", savedPath) }()
c.JSON(200, gin.H{"status": "ok", "url": authURL, "state": state})}
func (h *Handler) RequestCodexToken(c *gin.Context) { ctx := context.Background()
fmt.Println("Initializing Codex authentication...")
// Generate PKCE codes pkceCodes, err := codex.GeneratePKCECodes() if err != nil { log.Errorf("Failed to generate PKCE codes: %v", err) c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate PKCE codes"}) return }
// Generate random state parameter state, err := misc.GenerateRandomState() if err != nil { log.Errorf("Failed to generate state parameter: %v", err) c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate state parameter"}) return }
// Initialize Codex auth service openaiAuth := codex.NewCodexAuth(h.cfg)
// Generate authorization URL authURL, err := openaiAuth.GenerateAuthURL(state, pkceCodes) if err != nil { log.Errorf("Failed to generate authorization URL: %v", err) c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate authorization url"}) return }
RegisterOAuthSession(state, "codex")
isWebUI := isWebUIRequest(c) var forwarder *callbackForwarder if isWebUI { targetURL, errTarget := h.managementCallbackURL("/codex/callback") if errTarget != nil { log.WithError(errTarget).Error("failed to compute codex callback target") c.JSON(http.StatusInternalServerError, gin.H{"error": "callback server unavailable"}) return } var errStart error if forwarder, errStart = startCallbackForwarder(codexCallbackPort, "codex", targetURL); errStart != nil { log.WithError(errStart).Error("failed to start codex callback forwarder") c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to start callback server"}) return } }
go func() { if isWebUI { defer stopCallbackForwarderInstance(codexCallbackPort, forwarder) }
// Wait for callback file waitFile := filepath.Join(h.cfg.AuthDir, fmt.Sprintf(".oauth-codex-%s.oauth", state)) deadline := time.Now().Add(5 * time.Minute) var code string for { if !IsOAuthSessionPending(state, "codex") { return } if time.Now().After(deadline) { authErr := codex.NewAuthenticationError(codex.ErrCallbackTimeout, fmt.Errorf("timeout waiting for OAuth callback")) log.Error(codex.GetUserFriendlyMessage(authErr)) SetOAuthSessionError(state, "Timeout waiting for OAuth callback") return } if data, errR := os.ReadFile(waitFile); errR == nil { var m map[string]string _ = json.Unmarshal(data, &m) _ = os.Remove(waitFile) if errStr := m["error"]; errStr != "" { oauthErr := codex.NewOAuthError(errStr, "", http.StatusBadRequest) log.Error(codex.GetUserFriendlyMessage(oauthErr)) SetOAuthSessionError(state, "Bad Request") return } if m["state"] != state { authErr := codex.NewAuthenticationError(codex.ErrInvalidState, fmt.Errorf("expected %s, got %s", state, m["state"])) SetOAuthSessionError(state, "State code error") log.Error(codex.GetUserFriendlyMessage(authErr)) return } code = m["code"] break } time.Sleep(500 * time.Millisecond) }
log.Debug("Authorization code received, exchanging for tokens...") // Extract client_id from authURL clientID := "" if u2, errP := url.Parse(authURL); errP == nil { clientID = u2.Query().Get("client_id") } // Exchange code for tokens with redirect equal to mgmtRedirect form := url.Values{ "grant_type": {"authorization_code"}, "client_id": {clientID}, "code": {code}, "redirect_uri": {"http://localhost:1455/auth/callback"}, "code_verifier": {pkceCodes.CodeVerifier}, } httpClient := util.SetProxy(&h.cfg.SDKConfig, &http.Client{}) req, _ := http.NewRequestWithContext(ctx, "POST", "https://auth.openai.com/oauth/token", strings.NewReader(form.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Accept", "application/json") resp, errDo := httpClient.Do(req) if errDo != nil { authErr := codex.NewAuthenticationError(codex.ErrCodeExchangeFailed, errDo) SetOAuthSessionError(state, "Failed to exchange authorization code for tokens") log.Errorf("Failed to exchange authorization code for tokens: %v", authErr) return } defer func() { _ = resp.Body.Close() }() respBody, _ := io.ReadAll(resp.Body) if resp.StatusCode != http.StatusOK { SetOAuthSessionError(state, fmt.Sprintf("Token exchange failed with status %d", resp.StatusCode)) log.Errorf("token exchange failed with status %d: %s", resp.StatusCode, string(respBody)) return } var tokenResp struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` IDToken string `json:"id_token"` ExpiresIn int `json:"expires_in"` } if errU := json.Unmarshal(respBody, &tokenResp); errU != nil { SetOAuthSessionError(state, "Failed to parse token response") log.Errorf("failed to parse token response: %v", errU) return } claims, _ := codex.ParseJWTToken(tokenResp.IDToken) email := "" accountID := "" if claims != nil { email = claims.GetUserEmail() accountID = claims.GetAccountID() } // Build bundle compatible with existing storage bundle := &codex.CodexAuthBundle{ TokenData: codex.CodexTokenData{ IDToken: tokenResp.IDToken, AccessToken: tokenResp.AccessToken, RefreshToken: tokenResp.RefreshToken, AccountID: accountID, Email: email, Expire: time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second).Format(time.RFC3339), }, LastRefresh: time.Now().Format(time.RFC3339), }
// Create token storage and persist tokenStorage := openaiAuth.CreateTokenStorage(bundle) record := &coreauth.Auth{ ID: fmt.Sprintf("codex-%s.json", tokenStorage.Email), Provider: "codex", FileName: fmt.Sprintf("codex-%s.json", tokenStorage.Email), Storage: tokenStorage, Metadata: map[string]any{ "email": tokenStorage.Email, "account_id": tokenStorage.AccountID, }, } savedPath, errSave := h.saveTokenRecord(ctx, record) if errSave != nil { SetOAuthSessionError(state, "Failed to save authentication tokens") log.Errorf("Failed to save authentication tokens: %v", errSave) return } fmt.Printf("Authentication successful! Token saved to %s\n", savedPath) if bundle.APIKey != "" { fmt.Println("API key obtained and saved") } fmt.Println("You can now use Codex services through this CLI") CompleteOAuthSession(state) CompleteOAuthSessionsByProvider("codex") }()
c.JSON(200, gin.H{"status": "ok", "url": authURL, "state": state})}
func (h *Handler) RequestAntigravityToken(c *gin.Context) { const ( antigravityCallbackPort = 51121 antigravityClientID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com" antigravityClientSecret = "YOUR_ANTIGRAVITY_CLIENT_SECRET" ) var antigravityScopes = []string{ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/cclog", "https://www.googleapis.com/auth/experimentsandconfigs", }
ctx := context.Background()
fmt.Println("Initializing Antigravity authentication...")
state, errState := misc.GenerateRandomState() if errState != nil { log.Errorf("Failed to generate state parameter: %v", errState) c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate state parameter"}) return }
redirectURI := fmt.Sprintf("http://localhost:%d/oauth-callback", antigravityCallbackPort)
params := url.Values{} params.Set("access_type", "offline") params.Set("client_id", antigravityClientID) params.Set("prompt", "consent") params.Set("redirect_uri", redirectURI) params.Set("response_type", "code") params.Set("scope", strings.Join(antigravityScopes, " ")) params.Set("state", state) authURL := "https://accounts.google.com/o/oauth2/v2/auth?" + params.Encode()
RegisterOAuthSession(state, "antigravity")
isWebUI := isWebUIRequest(c) var forwarder *callbackForwarder if isWebUI { targetURL, errTarget := h.managementCallbackURL("/antigravity/callback") if errTarget != nil { log.WithError(errTarget).Error("failed to compute antigravity callback target") c.JSON(http.StatusInternalServerError, gin.H{"error": "callback server unavailable"}) return } var errStart error if forwarder, errStart = startCallbackForwarder(antigravityCallbackPort, "antigravity", targetURL); errStart != nil { log.WithError(errStart).Error("failed to start antigravity callback forwarder") c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to start callback server"}) return } }
go func() { if isWebUI { defer stopCallbackForwarderInstance(antigravityCallbackPort, forwarder) }
waitFile := filepath.Join(h.cfg.AuthDir, fmt.Sprintf(".oauth-antigravity-%s.oauth", state)) deadline := time.Now().Add(5 * time.Minute) var authCode string for { if !IsOAuthSessionPending(state, "antigravity") { return } if time.Now().After(deadline) { log.Error("oauth flow timed out") SetOAuthSessionError(state, "OAuth flow timed out") return } if data, errReadFile := os.ReadFile(waitFile); errReadFile == nil { var payload map[string]string _ = json.Unmarshal(data, &payload) _ = os.Remove(waitFile) if errStr := strings.TrimSpace(payload["error"]); errStr != "" { log.Errorf("Authentication failed: %s", errStr) SetOAuthSessionError(state, "Authentication failed") return } if payloadState := strings.TrimSpace(payload["state"]); payloadState != "" && payloadState != state { log.Errorf("Authentication failed: state mismatch") SetOAuthSessionError(state, "Authentication failed: state mismatch") return } authCode = strings.TrimSpace(payload["code"]) if authCode == "" { log.Error("Authentication failed: code not found") SetOAuthSessionError(state, "Authentication failed: code not found") return } break } time.Sleep(500 * time.Millisecond) }
httpClient := util.SetProxy(&h.cfg.SDKConfig, &http.Client{}) form := url.Values{} form.Set("code", authCode) form.Set("client_id", antigravityClientID) form.Set("client_secret", antigravityClientSecret) form.Set("redirect_uri", redirectURI) form.Set("grant_type", "authorization_code")
req, errNewRequest := http.NewRequestWithContext(ctx, http.MethodPost, "https://oauth2.googleapis.com/token", strings.NewReader(form.Encode())) if errNewRequest != nil { log.Errorf("Failed to build token request: %v", errNewRequest) SetOAuthSessionError(state, "Failed to build token request") return } req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, errDo := httpClient.Do(req) if errDo != nil { log.Errorf("Failed to execute token request: %v", errDo) SetOAuthSessionError(state, "Failed to exchange token") return } defer func() { if errClose := resp.Body.Close(); errClose != nil { log.Errorf("antigravity token exchange close error: %v", errClose) } }()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { bodyBytes, _ := io.ReadAll(resp.Body) log.Errorf("Antigravity token exchange failed with status %d: %s", resp.StatusCode, string(bodyBytes)) SetOAuthSessionError(state, fmt.Sprintf("Token exchange failed: %d", resp.StatusCode)) return }
var tokenResp struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` ExpiresIn int64 `json:"expires_in"` TokenType string `json:"token_type"` } if errDecode := json.NewDecoder(resp.Body).Decode(&tokenResp); errDecode != nil { log.Errorf("Failed to parse token response: %v", errDecode) SetOAuthSessionError(state, "Failed to parse token response") return }
email := "" if strings.TrimSpace(tokenResp.AccessToken) != "" { infoReq, errInfoReq := http.NewRequestWithContext(ctx, http.MethodGet, "https://www.googleapis.com/oauth2/v1/userinfo?alt=json", nil) if errInfoReq != nil { log.Errorf("Failed to build user info request: %v", errInfoReq) SetOAuthSessionError(state, "Failed to build user info request") return } infoReq.Header.Set("Authorization", "Bearer "+tokenResp.AccessToken)
infoResp, errInfo := httpClient.Do(infoReq) if errInfo != nil { log.Errorf("Failed to execute user info request: %v", errInfo) SetOAuthSessionError(state, "Failed to execute user info request") return } defer func() { if errClose := infoResp.Body.Close(); errClose != nil { log.Errorf("antigravity user info close error: %v", errClose) } }()
if infoResp.StatusCode >= http.StatusOK && infoResp.StatusCode < http.StatusMultipleChoices { var infoPayload struct { Email string `json:"email"` } if errDecodeInfo := json.NewDecoder(infoResp.Body).Decode(&infoPayload); errDecodeInfo == nil { email = strings.TrimSpace(infoPayload.Email) } } else { bodyBytes, _ := io.ReadAll(infoResp.Body) log.Errorf("User info request failed with status %d: %s", infoResp.StatusCode, string(bodyBytes)) SetOAuthSessionError(state, fmt.Sprintf("User info request failed: %d", infoResp.StatusCode)) return } }
projectID := "" if strings.TrimSpace(tokenResp.AccessToken) != "" { fetchedProjectID, errProject := sdkAuth.FetchAntigravityProjectID(ctx, tokenResp.AccessToken, httpClient) if errProject != nil { log.Warnf("antigravity: failed to fetch project ID: %v", errProject) } else { projectID = fetchedProjectID log.Infof("antigravity: obtained project ID %s", projectID) } }
now := time.Now() metadata := map[string]any{ "type": "antigravity", "access_token": tokenResp.AccessToken, "refresh_token": tokenResp.RefreshToken, "expires_in": tokenResp.ExpiresIn, "timestamp": now.UnixMilli(), "expired": now.Add(time.Duration(tokenResp.ExpiresIn) * time.Second).Format(time.RFC3339), } if email != "" { metadata["email"] = email } if projectID != "" { metadata["project_id"] = projectID }
fileName := sanitizeAntigravityFileName(email) label := strings.TrimSpace(email) if label == "" { label = "antigravity" }
record := &coreauth.Auth{ ID: fileName, Provider: "antigravity", FileName: fileName, Label: label, Metadata: metadata, } savedPath, errSave := h.saveTokenRecord(ctx, record) if errSave != nil { log.Errorf("Failed to save token to file: %v", errSave) SetOAuthSessionError(state, "Failed to save token to file") return }
CompleteOAuthSession(state) CompleteOAuthSessionsByProvider("antigravity") fmt.Printf("Authentication successful! Token saved to %s\n", savedPath) if projectID != "" { fmt.Printf("Using GCP project: %s\n", projectID) } fmt.Println("You can now use Antigravity services through this CLI") }()
c.JSON(200, gin.H{"status": "ok", "url": authURL, "state": state})}
func (h *Handler) RequestQwenToken(c *gin.Context) { ctx := context.Background()
fmt.Println("Initializing Qwen authentication...")
state := fmt.Sprintf("gem-%d", time.Now().UnixNano()) // Initialize Qwen auth service qwenAuth := qwen.NewQwenAuth(h.cfg)
// Generate authorization URL deviceFlow, err := qwenAuth.InitiateDeviceFlow(ctx) if err != nil { log.Errorf("Failed to generate authorization URL: %v", err) c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate authorization url"}) return } authURL := deviceFlow.VerificationURIComplete
RegisterOAuthSession(state, "qwen")
go func() { fmt.Println("Waiting for authentication...") tokenData, errPollForToken := qwenAuth.PollForToken(deviceFlow.DeviceCode, deviceFlow.CodeVerifier) if errPollForToken != nil { SetOAuthSessionError(state, "Authentication failed") fmt.Printf("Authentication failed: %v\n", errPollForToken) return }
// Create token storage tokenStorage := qwenAuth.CreateTokenStorage(tokenData)
tokenStorage.Email = fmt.Sprintf("qwen-%d", time.Now().UnixMilli()) record := &coreauth.Auth{ ID: fmt.Sprintf("qwen-%s.json", tokenStorage.Email), Provider: "qwen", FileName: fmt.Sprintf("qwen-%s.json", tokenStorage.Email), Storage: tokenStorage, Metadata: map[string]any{"email": tokenStorage.Email}, } savedPath, errSave := h.saveTokenRecord(ctx, record) if errSave != nil { log.Errorf("Failed to save authentication tokens: %v", errSave) SetOAuthSessionError(state, "Failed to save authentication tokens") return }
fmt.Printf("Authentication successful! Token saved to %s\n", savedPath) fmt.Println("You can now use Qwen services through this CLI") CompleteOAuthSession(state) }()
c.JSON(200, gin.H{"status": "ok", "url": authURL, "state": state})}
func (h *Handler) RequestIFlowToken(c *gin.Context) { ctx := context.Background()
fmt.Println("Initializing iFlow authentication...")
state := fmt.Sprintf("ifl-%d", time.Now().UnixNano()) authSvc := iflowauth.NewIFlowAuth(h.cfg) authURL, redirectURI := authSvc.AuthorizationURL(state, iflowauth.CallbackPort)
RegisterOAuthSession(state, "iflow")
isWebUI := isWebUIRequest(c) var forwarder *callbackForwarder if isWebUI { targetURL, errTarget := h.managementCallbackURL("/iflow/callback") if errTarget != nil { log.WithError(errTarget).Error("failed to compute iflow callback target") c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "callback server unavailable"}) return } var errStart error if forwarder, errStart = startCallbackForwarder(iflowauth.CallbackPort, "iflow", targetURL); errStart != nil { log.WithError(errStart).Error("failed to start iflow callback forwarder") c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "failed to start callback server"}) return } }
go func() { if isWebUI { defer stopCallbackForwarderInstance(iflowauth.CallbackPort, forwarder) } fmt.Println("Waiting for authentication...")
waitFile := filepath.Join(h.cfg.AuthDir, fmt.Sprintf(".oauth-iflow-%s.oauth", state)) deadline := time.Now().Add(5 * time.Minute) var resultMap map[string]string for { if !IsOAuthSessionPending(state, "iflow") { return } if time.Now().After(deadline) { SetOAuthSessionError(state, "Authentication failed") fmt.Println("Authentication failed: timeout waiting for callback") return } if data, errR := os.ReadFile(waitFile); errR == nil { _ = os.Remove(waitFile) _ = json.Unmarshal(data, &resultMap) break } time.Sleep(500 * time.Millisecond) }
if errStr := strings.TrimSpace(resultMap["error"]); errStr != "" { SetOAuthSessionError(state, "Authentication failed") fmt.Printf("Authentication failed: %s\n", errStr) return } if resultState := strings.TrimSpace(resultMap["state"]); resultState != state { SetOAuthSessionError(state, "Authentication failed") fmt.Println("Authentication failed: state mismatch") return }
code := strings.TrimSpace(resultMap["code"]) if code == "" { SetOAuthSessionError(state, "Authentication failed") fmt.Println("Authentication failed: code missing") return }
tokenData, errExchange := authSvc.ExchangeCodeForTokens(ctx, code, redirectURI) if errExchange != nil { SetOAuthSessionError(state, "Authentication failed") fmt.Printf("Authentication failed: %v\n", errExchange) return }
tokenStorage := authSvc.CreateTokenStorage(tokenData) identifier := strings.TrimSpace(tokenStorage.Email) if identifier == "" { identifier = fmt.Sprintf("iflow-%d", time.Now().UnixMilli()) tokenStorage.Email = identifier } record := &coreauth.Auth{ ID: fmt.Sprintf("iflow-%s.json", identifier), Provider: "iflow", FileName: fmt.Sprintf("iflow-%s.json", identifier), Storage: tokenStorage, Metadata: map[string]any{"email": identifier, "api_key": tokenStorage.APIKey}, Attributes: map[string]string{"api_key": tokenStorage.APIKey}, }
savedPath, errSave := h.saveTokenRecord(ctx, record) if errSave != nil { SetOAuthSessionError(state, "Failed to save authentication tokens") log.Errorf("Failed to save authentication tokens: %v", errSave) return }
fmt.Printf("Authentication successful! Token saved to %s\n", savedPath) if tokenStorage.APIKey != "" { fmt.Println("API key obtained and saved") } fmt.Println("You can now use iFlow services through this CLI") CompleteOAuthSession(state) CompleteOAuthSessionsByProvider("iflow") }()
c.JSON(http.StatusOK, gin.H{"status": "ok", "url": authURL, "state": state})}
func (h *Handler) RequestIFlowCookieToken(c *gin.Context) { ctx := context.Background()
var payload struct { Cookie string `json:"cookie"` } if err := c.ShouldBindJSON(&payload); err != nil { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "cookie is required"}) return }
cookieValue := strings.TrimSpace(payload.Cookie)
if cookieValue == "" { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "cookie is required"}) return }
cookieValue, errNormalize := iflowauth.NormalizeCookie(cookieValue) if errNormalize != nil { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": errNormalize.Error()}) return }
// Check for duplicate BXAuth before authentication bxAuth := iflowauth.ExtractBXAuth(cookieValue) if existingFile, err := iflowauth.CheckDuplicateBXAuth(h.cfg.AuthDir, bxAuth); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "failed to check duplicate"}) return } else if existingFile != "" { existingFileName := filepath.Base(existingFile) c.JSON(http.StatusConflict, gin.H{"status": "error", "error": "duplicate BXAuth found", "existing_file": existingFileName}) return }
authSvc := iflowauth.NewIFlowAuth(h.cfg) tokenData, errAuth := authSvc.AuthenticateWithCookie(ctx, cookieValue) if errAuth != nil { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": errAuth.Error()}) return }
tokenData.Cookie = cookieValue
tokenStorage := authSvc.CreateCookieTokenStorage(tokenData) email := strings.TrimSpace(tokenStorage.Email) if email == "" { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "failed to extract email from token"}) return }
fileName := iflowauth.SanitizeIFlowFileName(email) if fileName == "" { fileName = fmt.Sprintf("iflow-%d", time.Now().UnixMilli()) }
tokenStorage.Email = email timestamp := time.Now().Unix()
record := &coreauth.Auth{ ID: fmt.Sprintf("iflow-%s-%d.json", fileName, timestamp), Provider: "iflow", FileName: fmt.Sprintf("iflow-%s-%d.json", fileName, timestamp), Storage: tokenStorage, Metadata: map[string]any{ "email": email, "api_key": tokenStorage.APIKey, "expired": tokenStorage.Expire, "cookie": tokenStorage.Cookie, "type": tokenStorage.Type, "last_refresh": tokenStorage.LastRefresh, }, Attributes: map[string]string{ "api_key": tokenStorage.APIKey, }, }
savedPath, errSave := h.saveTokenRecord(ctx, record) if errSave != nil { c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "failed to save authentication tokens"}) return }
fmt.Printf("iFlow cookie authentication successful. Token saved to %s\n", savedPath) c.JSON(http.StatusOK, gin.H{ "status": "ok", "saved_path": savedPath, "email": email, "expired": tokenStorage.Expire, "type": tokenStorage.Type, })}
type projectSelectionRequiredError struct{}
func (e *projectSelectionRequiredError) Error() string { return "gemini cli: project selection required"}
func ensureGeminiProjectAndOnboard(ctx context.Context, httpClient *http.Client, storage *geminiAuth.GeminiTokenStorage, requestedProject string) error { if storage == nil { return fmt.Errorf("gemini storage is nil") }
trimmedRequest := strings.TrimSpace(requestedProject) if trimmedRequest == "" { projects, errProjects := fetchGCPProjects(ctx, httpClient) if errProjects != nil { return fmt.Errorf("fetch project list: %w", errProjects) } if len(projects) == 0 { return fmt.Errorf("no Google Cloud projects available for this account") } trimmedRequest = strings.TrimSpace(projects[0].ProjectID) if trimmedRequest == "" { return fmt.Errorf("resolved project id is empty") } storage.Auto = true } else { storage.Auto = false }
if err := performGeminiCLISetup(ctx, httpClient, storage, trimmedRequest); err != nil { return err }
if strings.TrimSpace(storage.ProjectID) == "" { storage.ProjectID = trimmedRequest }
return nil}
func onboardAllGeminiProjects(ctx context.Context, httpClient *http.Client, storage *geminiAuth.GeminiTokenStorage) ([]string, error) { projects, errProjects := fetchGCPProjects(ctx, httpClient) if errProjects != nil { return nil, fmt.Errorf("fetch project list: %w", errProjects) } if len(projects) == 0 { return nil, fmt.Errorf("no Google Cloud projects available for this account") } activated := make([]string, 0, len(projects)) seen := make(map[string]struct{}, len(projects)) for _, project := range projects { candidate := strings.TrimSpace(project.ProjectID) if candidate == "" { continue } if _, dup := seen[candidate]; dup { continue } if err := performGeminiCLISetup(ctx, httpClient, storage, candidate); err != nil { return nil, fmt.Errorf("onboard project %s: %w", candidate, err) } finalID := strings.TrimSpace(storage.ProjectID) if finalID == "" { finalID = candidate } activated = append(activated, finalID) seen[candidate] = struct{}{} } if len(activated) == 0 { return nil, fmt.Errorf("no Google Cloud projects available for this account") } return activated, nil}
func ensureGeminiProjectsEnabled(ctx context.Context, httpClient *http.Client, projectIDs []string) error { for _, pid := range projectIDs { trimmed := strings.TrimSpace(pid) if trimmed == "" { continue } isChecked, errCheck := checkCloudAPIIsEnabled(ctx, httpClient, trimmed) if errCheck != nil { return fmt.Errorf("project %s: %w", trimmed, errCheck) } if !isChecked { return fmt.Errorf("project %s: Cloud AI API not enabled", trimmed) } } return nil}
func performGeminiCLISetup(ctx context.Context, httpClient *http.Client, storage *geminiAuth.GeminiTokenStorage, requestedProject string) error { metadata := map[string]string{ "ideType": "IDE_UNSPECIFIED", "platform": "PLATFORM_UNSPECIFIED", "pluginType": "GEMINI", }
trimmedRequest := strings.TrimSpace(requestedProject) explicitProject := trimmedRequest != ""
loadReqBody := map[string]any{ "metadata": metadata, } if explicitProject { loadReqBody["cloudaicompanionProject"] = trimmedRequest }
var loadResp map[string]any if errLoad := callGeminiCLI(ctx, httpClient, "loadCodeAssist", loadReqBody, &loadResp); errLoad != nil { return fmt.Errorf("load code assist: %w", errLoad) }
tierID := "legacy-tier" if tiers, okTiers := loadResp["allowedTiers"].([]any); okTiers { for _, rawTier := range tiers { tier, okTier := rawTier.(map[string]any) if !okTier { continue } if isDefault, okDefault := tier["isDefault"].(bool); okDefault && isDefault { if id, okID := tier["id"].(string); okID && strings.TrimSpace(id) != "" { tierID = strings.TrimSpace(id) break } } } }
projectID := trimmedRequest if projectID == "" { if id, okProject := loadResp["cloudaicompanionProject"].(string); okProject { projectID = strings.TrimSpace(id) } if projectID == "" { if projectMap, okProject := loadResp["cloudaicompanionProject"].(map[string]any); okProject { if id, okID := projectMap["id"].(string); okID { projectID = strings.TrimSpace(id) } } } } if projectID == "" { return &projectSelectionRequiredError{} }
onboardReqBody := map[string]any{ "tierId": tierID, "metadata": metadata, "cloudaicompanionProject": projectID, }
storage.ProjectID = projectID
for { var onboardResp map[string]any if errOnboard := callGeminiCLI(ctx, httpClient, "onboardUser", onboardReqBody, &onboardResp); errOnboard != nil { return fmt.Errorf("onboard user: %w", errOnboard) }
if done, okDone := onboardResp["done"].(bool); okDone && done { responseProjectID := "" if resp, okResp := onboardResp["response"].(map[string]any); okResp { switch projectValue := resp["cloudaicompanionProject"].(type) { case map[string]any: if id, okID := projectValue["id"].(string); okID { responseProjectID = strings.TrimSpace(id) } case string: responseProjectID = strings.TrimSpace(projectValue) } }
finalProjectID := projectID if responseProjectID != "" { if explicitProject && !strings.EqualFold(responseProjectID, projectID) { log.Warnf("Gemini onboarding returned project %s instead of requested %s; keeping requested project ID.", responseProjectID, projectID) } else { finalProjectID = responseProjectID } }
storage.ProjectID = strings.TrimSpace(finalProjectID) if storage.ProjectID == "" { storage.ProjectID = strings.TrimSpace(projectID) } if storage.ProjectID == "" { return fmt.Errorf("onboard user completed without project id") } log.Infof("Onboarding complete. Using Project ID: %s", storage.ProjectID) return nil }
log.Println("Onboarding in progress, waiting 5 seconds...") time.Sleep(5 * time.Second) }}
func callGeminiCLI(ctx context.Context, httpClient *http.Client, endpoint string, body any, result any) error { endPointURL := fmt.Sprintf("%s/%s:%s", geminiCLIEndpoint, geminiCLIVersion, endpoint) if strings.HasPrefix(endpoint, "operations/") { endPointURL = fmt.Sprintf("%s/%s", geminiCLIEndpoint, endpoint) }
var reader io.Reader if body != nil { rawBody, errMarshal := json.Marshal(body) if errMarshal != nil { return fmt.Errorf("marshal request body: %w", errMarshal) } reader = bytes.NewReader(rawBody) }
req, errRequest := http.NewRequestWithContext(ctx, http.MethodPost, endPointURL, reader) if errRequest != nil { return fmt.Errorf("create request: %w", errRequest) } req.Header.Set("Content-Type", "application/json") req.Header.Set("User-Agent", geminiCLIUserAgent) req.Header.Set("X-Goog-Api-Client", geminiCLIApiClient) req.Header.Set("Client-Metadata", geminiCLIClientMetadata)
resp, errDo := httpClient.Do(req) if errDo != nil { return fmt.Errorf("execute request: %w", errDo) } defer func() { if errClose := resp.Body.Close(); errClose != nil { log.Errorf("response body close error: %v", errClose) } }()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { bodyBytes, _ := io.ReadAll(resp.Body) return fmt.Errorf("api request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes))) }
if result == nil { _, _ = io.Copy(io.Discard, resp.Body) return nil }
if errDecode := json.NewDecoder(resp.Body).Decode(result); errDecode != nil { return fmt.Errorf("decode response body: %w", errDecode) }
return nil}
func fetchGCPProjects(ctx context.Context, httpClient *http.Client) ([]interfaces.GCPProjectProjects, error) { req, errRequest := http.NewRequestWithContext(ctx, http.MethodGet, "https://cloudresourcemanager.googleapis.com/v1/projects", nil) if errRequest != nil { return nil, fmt.Errorf("could not create project list request: %w", errRequest) }
resp, errDo := httpClient.Do(req) if errDo != nil { return nil, fmt.Errorf("failed to execute project list request: %w", errDo) } defer func() { if errClose := resp.Body.Close(); errClose != nil { log.Errorf("response body close error: %v", errClose) } }()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { bodyBytes, _ := io.ReadAll(resp.Body) return nil, fmt.Errorf("project list request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes))) }
var projects interfaces.GCPProject if errDecode := json.NewDecoder(resp.Body).Decode(&projects); errDecode != nil { return nil, fmt.Errorf("failed to unmarshal project list: %w", errDecode) }
return projects.Projects, nil}
func checkCloudAPIIsEnabled(ctx context.Context, httpClient *http.Client, projectID string) (bool, error) { serviceUsageURL := "https://serviceusage.googleapis.com" requiredServices := []string{ "cloudaicompanion.googleapis.com", } for _, service := range requiredServices { checkURL := fmt.Sprintf("%s/v1/projects/%s/services/%s", serviceUsageURL, projectID, service) req, errRequest := http.NewRequestWithContext(ctx, http.MethodGet, checkURL, nil) if errRequest != nil { return false, fmt.Errorf("failed to create request: %w", errRequest) } req.Header.Set("Content-Type", "application/json") req.Header.Set("User-Agent", geminiCLIUserAgent) resp, errDo := httpClient.Do(req) if errDo != nil { return false, fmt.Errorf("failed to execute request: %w", errDo) }
if resp.StatusCode == http.StatusOK { bodyBytes, _ := io.ReadAll(resp.Body) if gjson.GetBytes(bodyBytes, "state").String() == "ENABLED" { _ = resp.Body.Close() continue } } _ = resp.Body.Close()
enableURL := fmt.Sprintf("%s/v1/projects/%s/services/%s:enable", serviceUsageURL, projectID, service) req, errRequest = http.NewRequestWithContext(ctx, http.MethodPost, enableURL, strings.NewReader("{}")) if errRequest != nil { return false, fmt.Errorf("failed to create request: %w", errRequest) } req.Header.Set("Content-Type", "application/json") req.Header.Set("User-Agent", geminiCLIUserAgent) resp, errDo = httpClient.Do(req) if errDo != nil { return false, fmt.Errorf("failed to execute request: %w", errDo) }
bodyBytes, _ := io.ReadAll(resp.Body) errMessage := string(bodyBytes) errMessageResult := gjson.GetBytes(bodyBytes, "error.message") if errMessageResult.Exists() { errMessage = errMessageResult.String() } if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusCreated { _ = resp.Body.Close() continue } else if resp.StatusCode == http.StatusBadRequest { _ = resp.Body.Close() if strings.Contains(strings.ToLower(errMessage), "already enabled") { continue } } _ = resp.Body.Close() return false, fmt.Errorf("project activation required: %s", errMessage) } return true, nil}
func (h *Handler) GetAuthStatus(c *gin.Context) { state := strings.TrimSpace(c.Query("state")) if state == "" { c.JSON(http.StatusOK, gin.H{"status": "ok"}) return } if err := ValidateOAuthState(state); err != nil { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "invalid state"}) return }
_, status, ok := GetOAuthSession(state) if !ok { c.JSON(http.StatusOK, gin.H{"status": "ok"}) return } if status != "" { if strings.HasPrefix(status, "device_code|") { parts := strings.SplitN(status, "|", 3) if len(parts) == 3 { c.JSON(http.StatusOK, gin.H{ "status": "device_code", "verification_url": parts[1], "user_code": parts[2], }) return } } if strings.HasPrefix(status, "auth_url|") { authURL := strings.TrimPrefix(status, "auth_url|") c.JSON(http.StatusOK, gin.H{ "status": "auth_url", "url": authURL, }) return } c.JSON(http.StatusOK, gin.H{"status": "error", "error": status}) return } c.JSON(http.StatusOK, gin.H{"status": "wait"})}
const kiroCallbackPort = 9876
func (h *Handler) RequestKiroToken(c *gin.Context) { ctx := context.Background()
// Get the login method from query parameter (default: aws for device code flow) method := strings.ToLower(strings.TrimSpace(c.Query("method"))) if method == "" { method = "aws" }
fmt.Println("Initializing Kiro authentication...")
state := fmt.Sprintf("kiro-%d", time.Now().UnixNano())
switch method { case "aws", "builder-id": RegisterOAuthSession(state, "kiro")
// AWS Builder ID uses device code flow (no callback needed) go func() { ssoClient := kiroauth.NewSSOOIDCClient(h.cfg)
// Step 1: Register client fmt.Println("Registering client...") regResp, errRegister := ssoClient.RegisterClient(ctx) if errRegister != nil { log.Errorf("Failed to register client: %v", errRegister) SetOAuthSessionError(state, "Failed to register client") return }
// Step 2: Start device authorization fmt.Println("Starting device authorization...") authResp, errAuth := ssoClient.StartDeviceAuthorization(ctx, regResp.ClientID, regResp.ClientSecret) if errAuth != nil { log.Errorf("Failed to start device auth: %v", errAuth) SetOAuthSessionError(state, "Failed to start device authorization") return }
// Store the verification URL for the frontend to display. // Using "|" as separator because URLs contain ":". SetOAuthSessionError(state, "device_code|"+authResp.VerificationURIComplete+"|"+authResp.UserCode)
// Step 3: Poll for token fmt.Println("Waiting for authorization...") interval := 5 * time.Second if authResp.Interval > 0 { interval = time.Duration(authResp.Interval) * time.Second } deadline := time.Now().Add(time.Duration(authResp.ExpiresIn) * time.Second)
for time.Now().Before(deadline) { select { case <-ctx.Done(): SetOAuthSessionError(state, "Authorization cancelled") return case <-time.After(interval): tokenResp, errToken := ssoClient.CreateToken(ctx, regResp.ClientID, regResp.ClientSecret, authResp.DeviceCode) if errToken != nil { errStr := errToken.Error() if strings.Contains(errStr, "authorization_pending") { continue } if strings.Contains(errStr, "slow_down") { interval += 5 * time.Second continue } log.Errorf("Token creation failed: %v", errToken) SetOAuthSessionError(state, "Token creation failed") return }
// Success! Save the token expiresAt := time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second) email := kiroauth.ExtractEmailFromJWT(tokenResp.AccessToken)
idPart := kiroauth.SanitizeEmailForFilename(email) if idPart == "" { idPart = fmt.Sprintf("%d", time.Now().UnixNano()%100000) }
now := time.Now() fileName := fmt.Sprintf("kiro-aws-%s.json", idPart)
record := &coreauth.Auth{ ID: fileName, Provider: "kiro", FileName: fileName, Metadata: map[string]any{ "type": "kiro", "access_token": tokenResp.AccessToken, "refresh_token": tokenResp.RefreshToken, "expires_at": expiresAt.Format(time.RFC3339), "auth_method": "builder-id", "provider": "AWS", "client_id": regResp.ClientID, "client_secret": regResp.ClientSecret, "email": email, "last_refresh": now.Format(time.RFC3339), }, }
savedPath, errSave := h.saveTokenRecord(ctx, record) if errSave != nil { log.Errorf("Failed to save authentication tokens: %v", errSave) SetOAuthSessionError(state, "Failed to save authentication tokens") return }
fmt.Printf("Authentication successful! Token saved to %s\n", savedPath) if email != "" { fmt.Printf("Authenticated as: %s\n", email) } CompleteOAuthSession(state) return } }
SetOAuthSessionError(state, "Authorization timed out") }()
// Return immediately with the state for polling c.JSON(http.StatusOK, gin.H{"status": "ok", "state": state, "method": "device_code"})
case "google", "github": RegisterOAuthSession(state, "kiro")
// Social auth uses protocol handler - for WEB UI we use a callback forwarder provider := "Google" if method == "github" { provider = "Github" }
isWebUI := isWebUIRequest(c) if isWebUI { targetURL, errTarget := h.managementCallbackURL("/kiro/callback") if errTarget != nil { log.WithError(errTarget).Error("failed to compute kiro callback target") c.JSON(http.StatusInternalServerError, gin.H{"error": "callback server unavailable"}) return } if _, errStart := startCallbackForwarder(kiroCallbackPort, "kiro", targetURL); errStart != nil { log.WithError(errStart).Error("failed to start kiro callback forwarder") c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to start callback server"}) return } }
go func() { if isWebUI { defer stopCallbackForwarder(kiroCallbackPort) }
socialClient := kiroauth.NewSocialAuthClient(h.cfg)
// Generate PKCE codes codeVerifier, codeChallenge, errPKCE := generateKiroPKCE() if errPKCE != nil { log.Errorf("Failed to generate PKCE: %v", errPKCE) SetOAuthSessionError(state, "Failed to generate PKCE") return }
// Build login URL authURL := fmt.Sprintf("%s/login?idp=%s&redirect_uri=%s&code_challenge=%s&code_challenge_method=S256&state=%s&prompt=select_account", "https://prod.us-east-1.auth.desktop.kiro.dev", provider, url.QueryEscape(kiroauth.KiroRedirectURI), codeChallenge, state, )
// Store auth URL for frontend. // Using "|" as separator because URLs contain ":". SetOAuthSessionError(state, "auth_url|"+authURL)
// Wait for callback file waitFile := filepath.Join(h.cfg.AuthDir, fmt.Sprintf(".oauth-kiro-%s.oauth", state)) deadline := time.Now().Add(5 * time.Minute)
for { if time.Now().After(deadline) { log.Error("oauth flow timed out") SetOAuthSessionError(state, "OAuth flow timed out") return } if data, errRead := os.ReadFile(waitFile); errRead == nil { var m map[string]string _ = json.Unmarshal(data, &m) _ = os.Remove(waitFile) if errStr := m["error"]; errStr != "" { log.Errorf("Authentication failed: %s", errStr) SetOAuthSessionError(state, "Authentication failed") return } if m["state"] != state { log.Errorf("State mismatch") SetOAuthSessionError(state, "State mismatch") return } code := m["code"] if code == "" { log.Error("No authorization code received") SetOAuthSessionError(state, "No authorization code received") return }
// Exchange code for tokens tokenReq := &kiroauth.CreateTokenRequest{ Code: code, CodeVerifier: codeVerifier, RedirectURI: kiroauth.KiroRedirectURI, }
tokenResp, errToken := socialClient.CreateToken(ctx, tokenReq) if errToken != nil { log.Errorf("Failed to exchange code for tokens: %v", errToken) SetOAuthSessionError(state, "Failed to exchange code for tokens") return }
// Save the token expiresIn := tokenResp.ExpiresIn if expiresIn <= 0 { expiresIn = 3600 } expiresAt := time.Now().Add(time.Duration(expiresIn) * time.Second) email := kiroauth.ExtractEmailFromJWT(tokenResp.AccessToken)
idPart := kiroauth.SanitizeEmailForFilename(email) if idPart == "" { idPart = fmt.Sprintf("%d", time.Now().UnixNano()%100000) }
now := time.Now() fileName := fmt.Sprintf("kiro-%s-%s.json", strings.ToLower(provider), idPart)
record := &coreauth.Auth{ ID: fileName, Provider: "kiro", FileName: fileName, Metadata: map[string]any{ "type": "kiro", "access_token": tokenResp.AccessToken, "refresh_token": tokenResp.RefreshToken, "profile_arn": tokenResp.ProfileArn, "expires_at": expiresAt.Format(time.RFC3339), "auth_method": "social", "provider": provider, "email": email, "last_refresh": now.Format(time.RFC3339), }, }
savedPath, errSave := h.saveTokenRecord(ctx, record) if errSave != nil { log.Errorf("Failed to save authentication tokens: %v", errSave) SetOAuthSessionError(state, "Failed to save authentication tokens") return }
fmt.Printf("Authentication successful! Token saved to %s\n", savedPath) if email != "" { fmt.Printf("Authenticated as: %s\n", email) } CompleteOAuthSession(state) return } time.Sleep(500 * time.Millisecond) } }()
c.JSON(http.StatusOK, gin.H{"status": "ok", "state": state, "method": "social"})
default: c.JSON(http.StatusBadRequest, gin.H{"error": "invalid method, use 'aws', 'google', or 'github'"}) }}
// generateKiroPKCE generates PKCE code verifier and challenge for Kiro OAuth.func generateKiroPKCE() (verifier, challenge string, err error) { b := make([]byte, 32) if _, errRead := io.ReadFull(rand.Reader, b); errRead != nil { return "", "", fmt.Errorf("failed to generate random bytes: %w", errRead) } verifier = base64.RawURLEncoding.EncodeToString(b)
h := sha256.Sum256([]byte(verifier)) challenge = base64.RawURLEncoding.EncodeToString(h[:])
return verifier, challenge, nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243package management
import ( "encoding/json" "fmt" "io" "net/http" "os" "path/filepath" "strings" "time"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/config" "github.com/router-for-me/CLIProxyAPI/v6/internal/util" sdkconfig "github.com/router-for-me/CLIProxyAPI/v6/sdk/config" log "github.com/sirupsen/logrus" "gopkg.in/yaml.v3")
const ( latestReleaseURL = "https://api.github.com/repos/router-for-me/CLIProxyAPIPlus/releases/latest" latestReleaseUserAgent = "CLIProxyAPIPlus")
func (h *Handler) GetConfig(c *gin.Context) { if h == nil || h.cfg == nil { c.JSON(200, gin.H{}) return } cfgCopy := *h.cfg c.JSON(200, &cfgCopy)}
type releaseInfo struct { TagName string `json:"tag_name"` Name string `json:"name"`}
// GetLatestVersion returns the latest release version from GitHub without downloading assets.func (h *Handler) GetLatestVersion(c *gin.Context) { client := &http.Client{Timeout: 10 * time.Second} proxyURL := "" if h != nil && h.cfg != nil { proxyURL = strings.TrimSpace(h.cfg.ProxyURL) } if proxyURL != "" { sdkCfg := &sdkconfig.SDKConfig{ProxyURL: proxyURL} util.SetProxy(sdkCfg, client) }
req, err := http.NewRequestWithContext(c.Request.Context(), http.MethodGet, latestReleaseURL, nil) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "request_create_failed", "message": err.Error()}) return } req.Header.Set("Accept", "application/vnd.github+json") req.Header.Set("User-Agent", latestReleaseUserAgent)
resp, err := client.Do(req) if err != nil { c.JSON(http.StatusBadGateway, gin.H{"error": "request_failed", "message": err.Error()}) return } defer func() { if errClose := resp.Body.Close(); errClose != nil { log.WithError(errClose).Debug("failed to close latest version response body") } }()
if resp.StatusCode != http.StatusOK { body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) c.JSON(http.StatusBadGateway, gin.H{"error": "unexpected_status", "message": fmt.Sprintf("status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))}) return }
var info releaseInfo if errDecode := json.NewDecoder(resp.Body).Decode(&info); errDecode != nil { c.JSON(http.StatusBadGateway, gin.H{"error": "decode_failed", "message": errDecode.Error()}) return }
version := strings.TrimSpace(info.TagName) if version == "" { version = strings.TrimSpace(info.Name) } if version == "" { c.JSON(http.StatusBadGateway, gin.H{"error": "invalid_response", "message": "missing release version"}) return }
c.JSON(http.StatusOK, gin.H{"latest-version": version})}
func WriteConfig(path string, data []byte) error { data = config.NormalizeCommentIndentation(data) f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { return err } if _, errWrite := f.Write(data); errWrite != nil { _ = f.Close() return errWrite } if errSync := f.Sync(); errSync != nil { _ = f.Close() return errSync } return f.Close()}
func (h *Handler) PutConfigYAML(c *gin.Context) { body, err := io.ReadAll(c.Request.Body) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_yaml", "message": "cannot read request body"}) return } var cfg config.Config if err = yaml.Unmarshal(body, &cfg); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_yaml", "message": err.Error()}) return } // Validate config using LoadConfigOptional with optional=false to enforce parsing tmpDir := filepath.Dir(h.configFilePath) tmpFile, err := os.CreateTemp(tmpDir, "config-validate-*.yaml") if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": err.Error()}) return } tempFile := tmpFile.Name() if _, errWrite := tmpFile.Write(body); errWrite != nil { _ = tmpFile.Close() _ = os.Remove(tempFile) c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": errWrite.Error()}) return } if errClose := tmpFile.Close(); errClose != nil { _ = os.Remove(tempFile) c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": errClose.Error()}) return } defer func() { _ = os.Remove(tempFile) }() _, err = config.LoadConfigOptional(tempFile, false) if err != nil { c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "invalid_config", "message": err.Error()}) return } h.mu.Lock() defer h.mu.Unlock() if WriteConfig(h.configFilePath, body) != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": "failed to write config"}) return } // Reload into handler to keep memory in sync newCfg, err := config.LoadConfig(h.configFilePath) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "reload_failed", "message": err.Error()}) return } h.cfg = newCfg c.JSON(http.StatusOK, gin.H{"ok": true, "changed": []string{"config"}})}
// GetConfigYAML returns the raw config.yaml file bytes without re-encoding.// It preserves comments and original formatting/styles.func (h *Handler) GetConfigYAML(c *gin.Context) { data, err := os.ReadFile(h.configFilePath) if err != nil { if os.IsNotExist(err) { c.JSON(http.StatusNotFound, gin.H{"error": "not_found", "message": "config file not found"}) return } c.JSON(http.StatusInternalServerError, gin.H{"error": "read_failed", "message": err.Error()}) return } c.Header("Content-Type", "application/yaml; charset=utf-8") c.Header("Cache-Control", "no-store") c.Header("X-Content-Type-Options", "nosniff") // Write raw bytes as-is _, _ = c.Writer.Write(data)}
// Debugfunc (h *Handler) GetDebug(c *gin.Context) { c.JSON(200, gin.H{"debug": h.cfg.Debug}) }func (h *Handler) PutDebug(c *gin.Context) { h.updateBoolField(c, func(v bool) { h.cfg.Debug = v }) }
// UsageStatisticsEnabledfunc (h *Handler) GetUsageStatisticsEnabled(c *gin.Context) { c.JSON(200, gin.H{"usage-statistics-enabled": h.cfg.UsageStatisticsEnabled})}func (h *Handler) PutUsageStatisticsEnabled(c *gin.Context) { h.updateBoolField(c, func(v bool) { h.cfg.UsageStatisticsEnabled = v })}
// UsageStatisticsEnabledfunc (h *Handler) GetLoggingToFile(c *gin.Context) { c.JSON(200, gin.H{"logging-to-file": h.cfg.LoggingToFile})}func (h *Handler) PutLoggingToFile(c *gin.Context) { h.updateBoolField(c, func(v bool) { h.cfg.LoggingToFile = v })}
// Request logfunc (h *Handler) GetRequestLog(c *gin.Context) { c.JSON(200, gin.H{"request-log": h.cfg.RequestLog}) }func (h *Handler) PutRequestLog(c *gin.Context) { h.updateBoolField(c, func(v bool) { h.cfg.RequestLog = v })}
// Websocket authfunc (h *Handler) GetWebsocketAuth(c *gin.Context) { c.JSON(200, gin.H{"ws-auth": h.cfg.WebsocketAuth})}func (h *Handler) PutWebsocketAuth(c *gin.Context) { h.updateBoolField(c, func(v bool) { h.cfg.WebsocketAuth = v })}
// Request retryfunc (h *Handler) GetRequestRetry(c *gin.Context) { c.JSON(200, gin.H{"request-retry": h.cfg.RequestRetry})}func (h *Handler) PutRequestRetry(c *gin.Context) { h.updateIntField(c, func(v int) { h.cfg.RequestRetry = v })}
// Max retry intervalfunc (h *Handler) GetMaxRetryInterval(c *gin.Context) { c.JSON(200, gin.H{"max-retry-interval": h.cfg.MaxRetryInterval})}func (h *Handler) PutMaxRetryInterval(c *gin.Context) { h.updateIntField(c, func(v int) { h.cfg.MaxRetryInterval = v })}
// Proxy URLfunc (h *Handler) GetProxyURL(c *gin.Context) { c.JSON(200, gin.H{"proxy-url": h.cfg.ProxyURL}) }func (h *Handler) PutProxyURL(c *gin.Context) { h.updateStringField(c, func(v string) { h.cfg.ProxyURL = v })}func (h *Handler) DeleteProxyURL(c *gin.Context) { h.cfg.ProxyURL = "" h.persist(c)}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090package management
import ( "encoding/json" "fmt" "strings"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/config")
// Generic helpers for list[string]func (h *Handler) putStringList(c *gin.Context, set func([]string), after func()) { data, err := c.GetRawData() if err != nil { c.JSON(400, gin.H{"error": "failed to read body"}) return } var arr []string if err = json.Unmarshal(data, &arr); err != nil { var obj struct { Items []string `json:"items"` } if err2 := json.Unmarshal(data, &obj); err2 != nil || len(obj.Items) == 0 { c.JSON(400, gin.H{"error": "invalid body"}) return } arr = obj.Items } set(arr) if after != nil { after() } h.persist(c)}
func (h *Handler) patchStringList(c *gin.Context, target *[]string, after func()) { var body struct { Old *string `json:"old"` New *string `json:"new"` Index *int `json:"index"` Value *string `json:"value"` } if err := c.ShouldBindJSON(&body); err != nil { c.JSON(400, gin.H{"error": "invalid body"}) return } if body.Index != nil && body.Value != nil && *body.Index >= 0 && *body.Index < len(*target) { (*target)[*body.Index] = *body.Value if after != nil { after() } h.persist(c) return } if body.Old != nil && body.New != nil { for i := range *target { if (*target)[i] == *body.Old { (*target)[i] = *body.New if after != nil { after() } h.persist(c) return } } *target = append(*target, *body.New) if after != nil { after() } h.persist(c) return } c.JSON(400, gin.H{"error": "missing fields"})}
func (h *Handler) deleteFromStringList(c *gin.Context, target *[]string, after func()) { if idxStr := c.Query("index"); idxStr != "" { var idx int _, err := fmt.Sscanf(idxStr, "%d", &idx) if err == nil && idx >= 0 && idx < len(*target) { *target = append((*target)[:idx], (*target)[idx+1:]...) if after != nil { after() } h.persist(c) return } } if val := strings.TrimSpace(c.Query("value")); val != "" { out := make([]string, 0, len(*target)) for _, v := range *target { if strings.TrimSpace(v) != val { out = append(out, v) } } *target = out if after != nil { after() } h.persist(c) return } c.JSON(400, gin.H{"error": "missing index or value"})}
// api-keysfunc (h *Handler) GetAPIKeys(c *gin.Context) { c.JSON(200, gin.H{"api-keys": h.cfg.APIKeys}) }func (h *Handler) PutAPIKeys(c *gin.Context) { h.putStringList(c, func(v []string) { h.cfg.APIKeys = append([]string(nil), v...) h.cfg.Access.Providers = nil }, nil)}func (h *Handler) PatchAPIKeys(c *gin.Context) { h.patchStringList(c, &h.cfg.APIKeys, func() { h.cfg.Access.Providers = nil })}func (h *Handler) DeleteAPIKeys(c *gin.Context) { h.deleteFromStringList(c, &h.cfg.APIKeys, func() { h.cfg.Access.Providers = nil })}
// gemini-api-key: []GeminiKeyfunc (h *Handler) GetGeminiKeys(c *gin.Context) { c.JSON(200, gin.H{"gemini-api-key": h.cfg.GeminiKey})}func (h *Handler) PutGeminiKeys(c *gin.Context) { data, err := c.GetRawData() if err != nil { c.JSON(400, gin.H{"error": "failed to read body"}) return } var arr []config.GeminiKey if err = json.Unmarshal(data, &arr); err != nil { var obj struct { Items []config.GeminiKey `json:"items"` } if err2 := json.Unmarshal(data, &obj); err2 != nil || len(obj.Items) == 0 { c.JSON(400, gin.H{"error": "invalid body"}) return } arr = obj.Items } h.cfg.GeminiKey = append([]config.GeminiKey(nil), arr...) h.cfg.SanitizeGeminiKeys() h.persist(c)}func (h *Handler) PatchGeminiKey(c *gin.Context) { type geminiKeyPatch struct { APIKey *string `json:"api-key"` Prefix *string `json:"prefix"` BaseURL *string `json:"base-url"` ProxyURL *string `json:"proxy-url"` Headers *map[string]string `json:"headers"` ExcludedModels *[]string `json:"excluded-models"` } var body struct { Index *int `json:"index"` Match *string `json:"match"` Value *geminiKeyPatch `json:"value"` } if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil { c.JSON(400, gin.H{"error": "invalid body"}) return } targetIndex := -1 if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.GeminiKey) { targetIndex = *body.Index } if targetIndex == -1 && body.Match != nil { match := strings.TrimSpace(*body.Match) if match != "" { for i := range h.cfg.GeminiKey { if h.cfg.GeminiKey[i].APIKey == match { targetIndex = i break } } } } if targetIndex == -1 { c.JSON(404, gin.H{"error": "item not found"}) return }
entry := h.cfg.GeminiKey[targetIndex] if body.Value.APIKey != nil { trimmed := strings.TrimSpace(*body.Value.APIKey) if trimmed == "" { h.cfg.GeminiKey = append(h.cfg.GeminiKey[:targetIndex], h.cfg.GeminiKey[targetIndex+1:]...) h.cfg.SanitizeGeminiKeys() h.persist(c) return } entry.APIKey = trimmed } if body.Value.Prefix != nil { entry.Prefix = strings.TrimSpace(*body.Value.Prefix) } if body.Value.BaseURL != nil { entry.BaseURL = strings.TrimSpace(*body.Value.BaseURL) } if body.Value.ProxyURL != nil { entry.ProxyURL = strings.TrimSpace(*body.Value.ProxyURL) } if body.Value.Headers != nil { entry.Headers = config.NormalizeHeaders(*body.Value.Headers) } if body.Value.ExcludedModels != nil { entry.ExcludedModels = config.NormalizeExcludedModels(*body.Value.ExcludedModels) } h.cfg.GeminiKey[targetIndex] = entry h.cfg.SanitizeGeminiKeys() h.persist(c)}
func (h *Handler) DeleteGeminiKey(c *gin.Context) { if val := strings.TrimSpace(c.Query("api-key")); val != "" { out := make([]config.GeminiKey, 0, len(h.cfg.GeminiKey)) for _, v := range h.cfg.GeminiKey { if v.APIKey != val { out = append(out, v) } } if len(out) != len(h.cfg.GeminiKey) { h.cfg.GeminiKey = out h.cfg.SanitizeGeminiKeys() h.persist(c) } else { c.JSON(404, gin.H{"error": "item not found"}) } return } if idxStr := c.Query("index"); idxStr != "" { var idx int if _, err := fmt.Sscanf(idxStr, "%d", &idx); err == nil && idx >= 0 && idx < len(h.cfg.GeminiKey) { h.cfg.GeminiKey = append(h.cfg.GeminiKey[:idx], h.cfg.GeminiKey[idx+1:]...) h.cfg.SanitizeGeminiKeys() h.persist(c) return } } c.JSON(400, gin.H{"error": "missing api-key or index"})}
// claude-api-key: []ClaudeKeyfunc (h *Handler) GetClaudeKeys(c *gin.Context) { c.JSON(200, gin.H{"claude-api-key": h.cfg.ClaudeKey})}func (h *Handler) PutClaudeKeys(c *gin.Context) { data, err := c.GetRawData() if err != nil { c.JSON(400, gin.H{"error": "failed to read body"}) return } var arr []config.ClaudeKey if err = json.Unmarshal(data, &arr); err != nil { var obj struct { Items []config.ClaudeKey `json:"items"` } if err2 := json.Unmarshal(data, &obj); err2 != nil || len(obj.Items) == 0 { c.JSON(400, gin.H{"error": "invalid body"}) return } arr = obj.Items } for i := range arr { normalizeClaudeKey(&arr[i]) } h.cfg.ClaudeKey = arr h.cfg.SanitizeClaudeKeys() h.persist(c)}func (h *Handler) PatchClaudeKey(c *gin.Context) { type claudeKeyPatch struct { APIKey *string `json:"api-key"` Prefix *string `json:"prefix"` BaseURL *string `json:"base-url"` ProxyURL *string `json:"proxy-url"` Models *[]config.ClaudeModel `json:"models"` Headers *map[string]string `json:"headers"` ExcludedModels *[]string `json:"excluded-models"` } var body struct { Index *int `json:"index"` Match *string `json:"match"` Value *claudeKeyPatch `json:"value"` } if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil { c.JSON(400, gin.H{"error": "invalid body"}) return } targetIndex := -1 if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.ClaudeKey) { targetIndex = *body.Index } if targetIndex == -1 && body.Match != nil { match := strings.TrimSpace(*body.Match) for i := range h.cfg.ClaudeKey { if h.cfg.ClaudeKey[i].APIKey == match { targetIndex = i break } } } if targetIndex == -1 { c.JSON(404, gin.H{"error": "item not found"}) return }
entry := h.cfg.ClaudeKey[targetIndex] if body.Value.APIKey != nil { entry.APIKey = strings.TrimSpace(*body.Value.APIKey) } if body.Value.Prefix != nil { entry.Prefix = strings.TrimSpace(*body.Value.Prefix) } if body.Value.BaseURL != nil { entry.BaseURL = strings.TrimSpace(*body.Value.BaseURL) } if body.Value.ProxyURL != nil { entry.ProxyURL = strings.TrimSpace(*body.Value.ProxyURL) } if body.Value.Models != nil { entry.Models = append([]config.ClaudeModel(nil), (*body.Value.Models)...) } if body.Value.Headers != nil { entry.Headers = config.NormalizeHeaders(*body.Value.Headers) } if body.Value.ExcludedModels != nil { entry.ExcludedModels = config.NormalizeExcludedModels(*body.Value.ExcludedModels) } normalizeClaudeKey(&entry) h.cfg.ClaudeKey[targetIndex] = entry h.cfg.SanitizeClaudeKeys() h.persist(c)}
func (h *Handler) DeleteClaudeKey(c *gin.Context) { if val := c.Query("api-key"); val != "" { out := make([]config.ClaudeKey, 0, len(h.cfg.ClaudeKey)) for _, v := range h.cfg.ClaudeKey { if v.APIKey != val { out = append(out, v) } } h.cfg.ClaudeKey = out h.cfg.SanitizeClaudeKeys() h.persist(c) return } if idxStr := c.Query("index"); idxStr != "" { var idx int _, err := fmt.Sscanf(idxStr, "%d", &idx) if err == nil && idx >= 0 && idx < len(h.cfg.ClaudeKey) { h.cfg.ClaudeKey = append(h.cfg.ClaudeKey[:idx], h.cfg.ClaudeKey[idx+1:]...) h.cfg.SanitizeClaudeKeys() h.persist(c) return } } c.JSON(400, gin.H{"error": "missing api-key or index"})}
// openai-compatibility: []OpenAICompatibilityfunc (h *Handler) GetOpenAICompat(c *gin.Context) { c.JSON(200, gin.H{"openai-compatibility": normalizedOpenAICompatibilityEntries(h.cfg.OpenAICompatibility)})}func (h *Handler) PutOpenAICompat(c *gin.Context) { data, err := c.GetRawData() if err != nil { c.JSON(400, gin.H{"error": "failed to read body"}) return } var arr []config.OpenAICompatibility if err = json.Unmarshal(data, &arr); err != nil { var obj struct { Items []config.OpenAICompatibility `json:"items"` } if err2 := json.Unmarshal(data, &obj); err2 != nil || len(obj.Items) == 0 { c.JSON(400, gin.H{"error": "invalid body"}) return } arr = obj.Items } filtered := make([]config.OpenAICompatibility, 0, len(arr)) for i := range arr { normalizeOpenAICompatibilityEntry(&arr[i]) if strings.TrimSpace(arr[i].BaseURL) != "" { filtered = append(filtered, arr[i]) } } h.cfg.OpenAICompatibility = filtered h.cfg.SanitizeOpenAICompatibility() h.persist(c)}func (h *Handler) PatchOpenAICompat(c *gin.Context) { type openAICompatPatch struct { Name *string `json:"name"` Prefix *string `json:"prefix"` BaseURL *string `json:"base-url"` APIKeyEntries *[]config.OpenAICompatibilityAPIKey `json:"api-key-entries"` Models *[]config.OpenAICompatibilityModel `json:"models"` Headers *map[string]string `json:"headers"` } var body struct { Name *string `json:"name"` Index *int `json:"index"` Value *openAICompatPatch `json:"value"` } if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil { c.JSON(400, gin.H{"error": "invalid body"}) return } targetIndex := -1 if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.OpenAICompatibility) { targetIndex = *body.Index } if targetIndex == -1 && body.Name != nil { match := strings.TrimSpace(*body.Name) for i := range h.cfg.OpenAICompatibility { if h.cfg.OpenAICompatibility[i].Name == match { targetIndex = i break } } } if targetIndex == -1 { c.JSON(404, gin.H{"error": "item not found"}) return }
entry := h.cfg.OpenAICompatibility[targetIndex] if body.Value.Name != nil { entry.Name = strings.TrimSpace(*body.Value.Name) } if body.Value.Prefix != nil { entry.Prefix = strings.TrimSpace(*body.Value.Prefix) } if body.Value.BaseURL != nil { trimmed := strings.TrimSpace(*body.Value.BaseURL) if trimmed == "" { h.cfg.OpenAICompatibility = append(h.cfg.OpenAICompatibility[:targetIndex], h.cfg.OpenAICompatibility[targetIndex+1:]...) h.cfg.SanitizeOpenAICompatibility() h.persist(c) return } entry.BaseURL = trimmed } if body.Value.APIKeyEntries != nil { entry.APIKeyEntries = append([]config.OpenAICompatibilityAPIKey(nil), (*body.Value.APIKeyEntries)...) } if body.Value.Models != nil { entry.Models = append([]config.OpenAICompatibilityModel(nil), (*body.Value.Models)...) } if body.Value.Headers != nil { entry.Headers = config.NormalizeHeaders(*body.Value.Headers) } normalizeOpenAICompatibilityEntry(&entry) h.cfg.OpenAICompatibility[targetIndex] = entry h.cfg.SanitizeOpenAICompatibility() h.persist(c)}
func (h *Handler) DeleteOpenAICompat(c *gin.Context) { if name := c.Query("name"); name != "" { out := make([]config.OpenAICompatibility, 0, len(h.cfg.OpenAICompatibility)) for _, v := range h.cfg.OpenAICompatibility { if v.Name != name { out = append(out, v) } } h.cfg.OpenAICompatibility = out h.cfg.SanitizeOpenAICompatibility() h.persist(c) return } if idxStr := c.Query("index"); idxStr != "" { var idx int _, err := fmt.Sscanf(idxStr, "%d", &idx) if err == nil && idx >= 0 && idx < len(h.cfg.OpenAICompatibility) { h.cfg.OpenAICompatibility = append(h.cfg.OpenAICompatibility[:idx], h.cfg.OpenAICompatibility[idx+1:]...) h.cfg.SanitizeOpenAICompatibility() h.persist(c) return } } c.JSON(400, gin.H{"error": "missing name or index"})}
// oauth-excluded-models: map[string][]stringfunc (h *Handler) GetOAuthExcludedModels(c *gin.Context) { c.JSON(200, gin.H{"oauth-excluded-models": config.NormalizeOAuthExcludedModels(h.cfg.OAuthExcludedModels)})}
func (h *Handler) PutOAuthExcludedModels(c *gin.Context) { data, err := c.GetRawData() if err != nil { c.JSON(400, gin.H{"error": "failed to read body"}) return } var entries map[string][]string if err = json.Unmarshal(data, &entries); err != nil { var wrapper struct { Items map[string][]string `json:"items"` } if err2 := json.Unmarshal(data, &wrapper); err2 != nil { c.JSON(400, gin.H{"error": "invalid body"}) return } entries = wrapper.Items } h.cfg.OAuthExcludedModels = config.NormalizeOAuthExcludedModels(entries) h.persist(c)}
func (h *Handler) PatchOAuthExcludedModels(c *gin.Context) { var body struct { Provider *string `json:"provider"` Models []string `json:"models"` } if err := c.ShouldBindJSON(&body); err != nil || body.Provider == nil { c.JSON(400, gin.H{"error": "invalid body"}) return } provider := strings.ToLower(strings.TrimSpace(*body.Provider)) if provider == "" { c.JSON(400, gin.H{"error": "invalid provider"}) return } normalized := config.NormalizeExcludedModels(body.Models) if len(normalized) == 0 { if h.cfg.OAuthExcludedModels == nil { c.JSON(404, gin.H{"error": "provider not found"}) return } if _, ok := h.cfg.OAuthExcludedModels[provider]; !ok { c.JSON(404, gin.H{"error": "provider not found"}) return } delete(h.cfg.OAuthExcludedModels, provider) if len(h.cfg.OAuthExcludedModels) == 0 { h.cfg.OAuthExcludedModels = nil } h.persist(c) return } if h.cfg.OAuthExcludedModels == nil { h.cfg.OAuthExcludedModels = make(map[string][]string) } h.cfg.OAuthExcludedModels[provider] = normalized h.persist(c)}
func (h *Handler) DeleteOAuthExcludedModels(c *gin.Context) { provider := strings.ToLower(strings.TrimSpace(c.Query("provider"))) if provider == "" { c.JSON(400, gin.H{"error": "missing provider"}) return } if h.cfg.OAuthExcludedModels == nil { c.JSON(404, gin.H{"error": "provider not found"}) return } if _, ok := h.cfg.OAuthExcludedModels[provider]; !ok { c.JSON(404, gin.H{"error": "provider not found"}) return } delete(h.cfg.OAuthExcludedModels, provider) if len(h.cfg.OAuthExcludedModels) == 0 { h.cfg.OAuthExcludedModels = nil } h.persist(c)}
// codex-api-key: []CodexKeyfunc (h *Handler) GetCodexKeys(c *gin.Context) { c.JSON(200, gin.H{"codex-api-key": h.cfg.CodexKey})}func (h *Handler) PutCodexKeys(c *gin.Context) { data, err := c.GetRawData() if err != nil { c.JSON(400, gin.H{"error": "failed to read body"}) return } var arr []config.CodexKey if err = json.Unmarshal(data, &arr); err != nil { var obj struct { Items []config.CodexKey `json:"items"` } if err2 := json.Unmarshal(data, &obj); err2 != nil || len(obj.Items) == 0 { c.JSON(400, gin.H{"error": "invalid body"}) return } arr = obj.Items } // Filter out codex entries with empty base-url (treat as removed) filtered := make([]config.CodexKey, 0, len(arr)) for i := range arr { entry := arr[i] normalizeCodexKey(&entry) if entry.BaseURL == "" { continue } filtered = append(filtered, entry) } h.cfg.CodexKey = filtered h.cfg.SanitizeCodexKeys() h.persist(c)}func (h *Handler) PatchCodexKey(c *gin.Context) { type codexKeyPatch struct { APIKey *string `json:"api-key"` Prefix *string `json:"prefix"` BaseURL *string `json:"base-url"` ProxyURL *string `json:"proxy-url"` Models *[]config.CodexModel `json:"models"` Headers *map[string]string `json:"headers"` ExcludedModels *[]string `json:"excluded-models"` } var body struct { Index *int `json:"index"` Match *string `json:"match"` Value *codexKeyPatch `json:"value"` } if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil { c.JSON(400, gin.H{"error": "invalid body"}) return } targetIndex := -1 if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.CodexKey) { targetIndex = *body.Index } if targetIndex == -1 && body.Match != nil { match := strings.TrimSpace(*body.Match) for i := range h.cfg.CodexKey { if h.cfg.CodexKey[i].APIKey == match { targetIndex = i break } } } if targetIndex == -1 { c.JSON(404, gin.H{"error": "item not found"}) return }
entry := h.cfg.CodexKey[targetIndex] if body.Value.APIKey != nil { entry.APIKey = strings.TrimSpace(*body.Value.APIKey) } if body.Value.Prefix != nil { entry.Prefix = strings.TrimSpace(*body.Value.Prefix) } if body.Value.BaseURL != nil { trimmed := strings.TrimSpace(*body.Value.BaseURL) if trimmed == "" { h.cfg.CodexKey = append(h.cfg.CodexKey[:targetIndex], h.cfg.CodexKey[targetIndex+1:]...) h.cfg.SanitizeCodexKeys() h.persist(c) return } entry.BaseURL = trimmed } if body.Value.ProxyURL != nil { entry.ProxyURL = strings.TrimSpace(*body.Value.ProxyURL) } if body.Value.Models != nil { entry.Models = append([]config.CodexModel(nil), (*body.Value.Models)...) } if body.Value.Headers != nil { entry.Headers = config.NormalizeHeaders(*body.Value.Headers) } if body.Value.ExcludedModels != nil { entry.ExcludedModels = config.NormalizeExcludedModels(*body.Value.ExcludedModels) } normalizeCodexKey(&entry) h.cfg.CodexKey[targetIndex] = entry h.cfg.SanitizeCodexKeys() h.persist(c)}
func (h *Handler) DeleteCodexKey(c *gin.Context) { if val := c.Query("api-key"); val != "" { out := make([]config.CodexKey, 0, len(h.cfg.CodexKey)) for _, v := range h.cfg.CodexKey { if v.APIKey != val { out = append(out, v) } } h.cfg.CodexKey = out h.cfg.SanitizeCodexKeys() h.persist(c) return } if idxStr := c.Query("index"); idxStr != "" { var idx int _, err := fmt.Sscanf(idxStr, "%d", &idx) if err == nil && idx >= 0 && idx < len(h.cfg.CodexKey) { h.cfg.CodexKey = append(h.cfg.CodexKey[:idx], h.cfg.CodexKey[idx+1:]...) h.cfg.SanitizeCodexKeys() h.persist(c) return } } c.JSON(400, gin.H{"error": "missing api-key or index"})}
func normalizeOpenAICompatibilityEntry(entry *config.OpenAICompatibility) { if entry == nil { return } // Trim base-url; empty base-url indicates provider should be removed by sanitization entry.BaseURL = strings.TrimSpace(entry.BaseURL) entry.Headers = config.NormalizeHeaders(entry.Headers) existing := make(map[string]struct{}, len(entry.APIKeyEntries)) for i := range entry.APIKeyEntries { trimmed := strings.TrimSpace(entry.APIKeyEntries[i].APIKey) entry.APIKeyEntries[i].APIKey = trimmed if trimmed != "" { existing[trimmed] = struct{}{} } }}
func normalizedOpenAICompatibilityEntries(entries []config.OpenAICompatibility) []config.OpenAICompatibility { if len(entries) == 0 { return nil } out := make([]config.OpenAICompatibility, len(entries)) for i := range entries { copyEntry := entries[i] if len(copyEntry.APIKeyEntries) > 0 { copyEntry.APIKeyEntries = append([]config.OpenAICompatibilityAPIKey(nil), copyEntry.APIKeyEntries...) } normalizeOpenAICompatibilityEntry(©Entry) out[i] = copyEntry } return out}
func normalizeClaudeKey(entry *config.ClaudeKey) { if entry == nil { return } entry.APIKey = strings.TrimSpace(entry.APIKey) entry.BaseURL = strings.TrimSpace(entry.BaseURL) entry.ProxyURL = strings.TrimSpace(entry.ProxyURL) entry.Headers = config.NormalizeHeaders(entry.Headers) entry.ExcludedModels = config.NormalizeExcludedModels(entry.ExcludedModels) if len(entry.Models) == 0 { return } normalized := make([]config.ClaudeModel, 0, len(entry.Models)) for i := range entry.Models { model := entry.Models[i] model.Name = strings.TrimSpace(model.Name) model.Alias = strings.TrimSpace(model.Alias) if model.Name == "" && model.Alias == "" { continue } normalized = append(normalized, model) } entry.Models = normalized}
func normalizeCodexKey(entry *config.CodexKey) { if entry == nil { return } entry.APIKey = strings.TrimSpace(entry.APIKey) entry.Prefix = strings.TrimSpace(entry.Prefix) entry.BaseURL = strings.TrimSpace(entry.BaseURL) entry.ProxyURL = strings.TrimSpace(entry.ProxyURL) entry.Headers = config.NormalizeHeaders(entry.Headers) entry.ExcludedModels = config.NormalizeExcludedModels(entry.ExcludedModels) if len(entry.Models) == 0 { return } normalized := make([]config.CodexModel, 0, len(entry.Models)) for i := range entry.Models { model := entry.Models[i] model.Name = strings.TrimSpace(model.Name) model.Alias = strings.TrimSpace(model.Alias) if model.Name == "" && model.Alias == "" { continue } normalized = append(normalized, model) } entry.Models = normalized}
// GetAmpCode returns the complete ampcode configuration.func (h *Handler) GetAmpCode(c *gin.Context) { if h == nil || h.cfg == nil { c.JSON(200, gin.H{"ampcode": config.AmpCode{}}) return } c.JSON(200, gin.H{"ampcode": h.cfg.AmpCode})}
// GetAmpUpstreamURL returns the ampcode upstream URL.func (h *Handler) GetAmpUpstreamURL(c *gin.Context) { if h == nil || h.cfg == nil { c.JSON(200, gin.H{"upstream-url": ""}) return } c.JSON(200, gin.H{"upstream-url": h.cfg.AmpCode.UpstreamURL})}
// PutAmpUpstreamURL updates the ampcode upstream URL.func (h *Handler) PutAmpUpstreamURL(c *gin.Context) { h.updateStringField(c, func(v string) { h.cfg.AmpCode.UpstreamURL = strings.TrimSpace(v) })}
// DeleteAmpUpstreamURL clears the ampcode upstream URL.func (h *Handler) DeleteAmpUpstreamURL(c *gin.Context) { h.cfg.AmpCode.UpstreamURL = "" h.persist(c)}
// GetAmpUpstreamAPIKey returns the ampcode upstream API key.func (h *Handler) GetAmpUpstreamAPIKey(c *gin.Context) { if h == nil || h.cfg == nil { c.JSON(200, gin.H{"upstream-api-key": ""}) return } c.JSON(200, gin.H{"upstream-api-key": h.cfg.AmpCode.UpstreamAPIKey})}
// PutAmpUpstreamAPIKey updates the ampcode upstream API key.func (h *Handler) PutAmpUpstreamAPIKey(c *gin.Context) { h.updateStringField(c, func(v string) { h.cfg.AmpCode.UpstreamAPIKey = strings.TrimSpace(v) })}
// DeleteAmpUpstreamAPIKey clears the ampcode upstream API key.func (h *Handler) DeleteAmpUpstreamAPIKey(c *gin.Context) { h.cfg.AmpCode.UpstreamAPIKey = "" h.persist(c)}
// GetAmpRestrictManagementToLocalhost returns the localhost restriction setting.func (h *Handler) GetAmpRestrictManagementToLocalhost(c *gin.Context) { if h == nil || h.cfg == nil { c.JSON(200, gin.H{"restrict-management-to-localhost": true}) return } c.JSON(200, gin.H{"restrict-management-to-localhost": h.cfg.AmpCode.RestrictManagementToLocalhost})}
// PutAmpRestrictManagementToLocalhost updates the localhost restriction setting.func (h *Handler) PutAmpRestrictManagementToLocalhost(c *gin.Context) { h.updateBoolField(c, func(v bool) { h.cfg.AmpCode.RestrictManagementToLocalhost = v })}
// GetAmpModelMappings returns the ampcode model mappings.func (h *Handler) GetAmpModelMappings(c *gin.Context) { if h == nil || h.cfg == nil { c.JSON(200, gin.H{"model-mappings": []config.AmpModelMapping{}}) return } c.JSON(200, gin.H{"model-mappings": h.cfg.AmpCode.ModelMappings})}
// PutAmpModelMappings replaces all ampcode model mappings.func (h *Handler) PutAmpModelMappings(c *gin.Context) { var body struct { Value []config.AmpModelMapping `json:"value"` } if err := c.ShouldBindJSON(&body); err != nil { c.JSON(400, gin.H{"error": "invalid body"}) return } h.cfg.AmpCode.ModelMappings = body.Value h.persist(c)}
// PatchAmpModelMappings adds or updates model mappings.func (h *Handler) PatchAmpModelMappings(c *gin.Context) { var body struct { Value []config.AmpModelMapping `json:"value"` } if err := c.ShouldBindJSON(&body); err != nil { c.JSON(400, gin.H{"error": "invalid body"}) return }
existing := make(map[string]int) for i, m := range h.cfg.AmpCode.ModelMappings { existing[strings.TrimSpace(m.From)] = i }
for _, newMapping := range body.Value { from := strings.TrimSpace(newMapping.From) if idx, ok := existing[from]; ok { h.cfg.AmpCode.ModelMappings[idx] = newMapping } else { h.cfg.AmpCode.ModelMappings = append(h.cfg.AmpCode.ModelMappings, newMapping) existing[from] = len(h.cfg.AmpCode.ModelMappings) - 1 } } h.persist(c)}
// DeleteAmpModelMappings removes specified model mappings by "from" field.func (h *Handler) DeleteAmpModelMappings(c *gin.Context) { var body struct { Value []string `json:"value"` } if err := c.ShouldBindJSON(&body); err != nil || len(body.Value) == 0 { h.cfg.AmpCode.ModelMappings = nil h.persist(c) return }
toRemove := make(map[string]bool) for _, from := range body.Value { toRemove[strings.TrimSpace(from)] = true }
newMappings := make([]config.AmpModelMapping, 0, len(h.cfg.AmpCode.ModelMappings)) for _, m := range h.cfg.AmpCode.ModelMappings { if !toRemove[strings.TrimSpace(m.From)] { newMappings = append(newMappings, m) } } h.cfg.AmpCode.ModelMappings = newMappings h.persist(c)}
// GetAmpForceModelMappings returns whether model mappings are forced.func (h *Handler) GetAmpForceModelMappings(c *gin.Context) { if h == nil || h.cfg == nil { c.JSON(200, gin.H{"force-model-mappings": false}) return } c.JSON(200, gin.H{"force-model-mappings": h.cfg.AmpCode.ForceModelMappings})}
// PutAmpForceModelMappings updates the force model mappings setting.func (h *Handler) PutAmpForceModelMappings(c *gin.Context) { h.updateBoolField(c, func(v bool) { h.cfg.AmpCode.ForceModelMappings = v })}
// GetAmpUpstreamAPIKeys returns the ampcode upstream API keys mapping.func (h *Handler) GetAmpUpstreamAPIKeys(c *gin.Context) { if h == nil || h.cfg == nil { c.JSON(200, gin.H{"upstream-api-keys": []config.AmpUpstreamAPIKeyEntry{}}) return } c.JSON(200, gin.H{"upstream-api-keys": h.cfg.AmpCode.UpstreamAPIKeys})}
// PutAmpUpstreamAPIKeys replaces all ampcode upstream API keys mappings.func (h *Handler) PutAmpUpstreamAPIKeys(c *gin.Context) { var body struct { Value []config.AmpUpstreamAPIKeyEntry `json:"value"` } if err := c.ShouldBindJSON(&body); err != nil { c.JSON(400, gin.H{"error": "invalid body"}) return } // Normalize entries: trim whitespace, filter empty normalized := normalizeAmpUpstreamAPIKeyEntries(body.Value) h.cfg.AmpCode.UpstreamAPIKeys = normalized h.persist(c)}
// PatchAmpUpstreamAPIKeys adds or updates upstream API keys entries.// Matching is done by upstream-api-key value.func (h *Handler) PatchAmpUpstreamAPIKeys(c *gin.Context) { var body struct { Value []config.AmpUpstreamAPIKeyEntry `json:"value"` } if err := c.ShouldBindJSON(&body); err != nil { c.JSON(400, gin.H{"error": "invalid body"}) return }
existing := make(map[string]int) for i, entry := range h.cfg.AmpCode.UpstreamAPIKeys { existing[strings.TrimSpace(entry.UpstreamAPIKey)] = i }
for _, newEntry := range body.Value { upstreamKey := strings.TrimSpace(newEntry.UpstreamAPIKey) if upstreamKey == "" { continue } normalizedEntry := config.AmpUpstreamAPIKeyEntry{ UpstreamAPIKey: upstreamKey, APIKeys: normalizeAPIKeysList(newEntry.APIKeys), } if idx, ok := existing[upstreamKey]; ok { h.cfg.AmpCode.UpstreamAPIKeys[idx] = normalizedEntry } else { h.cfg.AmpCode.UpstreamAPIKeys = append(h.cfg.AmpCode.UpstreamAPIKeys, normalizedEntry) existing[upstreamKey] = len(h.cfg.AmpCode.UpstreamAPIKeys) - 1 } } h.persist(c)}
// DeleteAmpUpstreamAPIKeys removes specified upstream API keys entries.// Body must be JSON: {"value": ["<upstream-api-key>", ...]}.// If "value" is an empty array, clears all entries.// If JSON is invalid or "value" is missing/null, returns 400 and does not persist any change.func (h *Handler) DeleteAmpUpstreamAPIKeys(c *gin.Context) { var body struct { Value []string `json:"value"` } if err := c.ShouldBindJSON(&body); err != nil { c.JSON(400, gin.H{"error": "invalid body"}) return }
if body.Value == nil { c.JSON(400, gin.H{"error": "missing value"}) return }
// Empty array means clear all if len(body.Value) == 0 { h.cfg.AmpCode.UpstreamAPIKeys = nil h.persist(c) return }
toRemove := make(map[string]bool) for _, key := range body.Value { trimmed := strings.TrimSpace(key) if trimmed == "" { continue } toRemove[trimmed] = true } if len(toRemove) == 0 { c.JSON(400, gin.H{"error": "empty value"}) return }
newEntries := make([]config.AmpUpstreamAPIKeyEntry, 0, len(h.cfg.AmpCode.UpstreamAPIKeys)) for _, entry := range h.cfg.AmpCode.UpstreamAPIKeys { if !toRemove[strings.TrimSpace(entry.UpstreamAPIKey)] { newEntries = append(newEntries, entry) } } h.cfg.AmpCode.UpstreamAPIKeys = newEntries h.persist(c)}
// normalizeAmpUpstreamAPIKeyEntries normalizes a list of upstream API key entries.func normalizeAmpUpstreamAPIKeyEntries(entries []config.AmpUpstreamAPIKeyEntry) []config.AmpUpstreamAPIKeyEntry { if len(entries) == 0 { return nil } out := make([]config.AmpUpstreamAPIKeyEntry, 0, len(entries)) for _, entry := range entries { upstreamKey := strings.TrimSpace(entry.UpstreamAPIKey) if upstreamKey == "" { continue } apiKeys := normalizeAPIKeysList(entry.APIKeys) out = append(out, config.AmpUpstreamAPIKeyEntry{ UpstreamAPIKey: upstreamKey, APIKeys: apiKeys, }) } if len(out) == 0 { return nil } return out}
// normalizeAPIKeysList trims and filters empty strings from a list of API keys.func normalizeAPIKeysList(keys []string) []string { if len(keys) == 0 { return nil } out := make([]string, 0, len(keys)) for _, k := range keys { trimmed := strings.TrimSpace(k) if trimmed != "" { out = append(out, trimmed) } } if len(out) == 0 { return nil } return out}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277// Package management provides the management API handlers and middleware// for configuring the server and managing auth files.package management
import ( "crypto/subtle" "fmt" "net/http" "os" "path/filepath" "strings" "sync" "time"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/buildinfo" "github.com/router-for-me/CLIProxyAPI/v6/internal/config" "github.com/router-for-me/CLIProxyAPI/v6/internal/usage" sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth" coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth" "golang.org/x/crypto/bcrypt")
type attemptInfo struct { count int blockedUntil time.Time}
// Handler aggregates config reference, persistence path and helpers.type Handler struct { cfg *config.Config configFilePath string mu sync.Mutex attemptsMu sync.Mutex failedAttempts map[string]*attemptInfo // keyed by client IP authManager *coreauth.Manager usageStats *usage.RequestStatistics tokenStore coreauth.Store localPassword string allowRemoteOverride bool envSecret string logDir string}
// NewHandler creates a new management handler instance.func NewHandler(cfg *config.Config, configFilePath string, manager *coreauth.Manager) *Handler { envSecret, _ := os.LookupEnv("MANAGEMENT_PASSWORD") envSecret = strings.TrimSpace(envSecret)
return &Handler{ cfg: cfg, configFilePath: configFilePath, failedAttempts: make(map[string]*attemptInfo), authManager: manager, usageStats: usage.GetRequestStatistics(), tokenStore: sdkAuth.GetTokenStore(), allowRemoteOverride: envSecret != "", envSecret: envSecret, }}
// NewHandler creates a new management handler instance.func NewHandlerWithoutConfigFilePath(cfg *config.Config, manager *coreauth.Manager) *Handler { return NewHandler(cfg, "", manager)}
// SetConfig updates the in-memory config reference when the server hot-reloads.func (h *Handler) SetConfig(cfg *config.Config) { h.cfg = cfg }
// SetAuthManager updates the auth manager reference used by management endpoints.func (h *Handler) SetAuthManager(manager *coreauth.Manager) { h.authManager = manager }
// SetUsageStatistics allows replacing the usage statistics reference.func (h *Handler) SetUsageStatistics(stats *usage.RequestStatistics) { h.usageStats = stats }
// SetLocalPassword configures the runtime-local password accepted for localhost requests.func (h *Handler) SetLocalPassword(password string) { h.localPassword = password }
// SetLogDirectory updates the directory where main.log should be looked up.func (h *Handler) SetLogDirectory(dir string) { if dir == "" { return } if !filepath.IsAbs(dir) { if abs, err := filepath.Abs(dir); err == nil { dir = abs } } h.logDir = dir}
// Middleware enforces access control for management endpoints.// All requests (local and remote) require a valid management key.// Additionally, remote access requires allow-remote-management=true.func (h *Handler) Middleware() gin.HandlerFunc { const maxFailures = 5 const banDuration = 30 * time.Minute
return func(c *gin.Context) { c.Header("X-CPA-VERSION", buildinfo.Version) c.Header("X-CPA-COMMIT", buildinfo.Commit) c.Header("X-CPA-BUILD-DATE", buildinfo.BuildDate)
clientIP := c.ClientIP() localClient := clientIP == "127.0.0.1" || clientIP == "::1" cfg := h.cfg var ( allowRemote bool secretHash string ) if cfg != nil { allowRemote = cfg.RemoteManagement.AllowRemote secretHash = cfg.RemoteManagement.SecretKey } if h.allowRemoteOverride { allowRemote = true } envSecret := h.envSecret
fail := func() {} if !localClient { h.attemptsMu.Lock() ai := h.failedAttempts[clientIP] if ai != nil { if !ai.blockedUntil.IsZero() { if time.Now().Before(ai.blockedUntil) { remaining := time.Until(ai.blockedUntil).Round(time.Second) h.attemptsMu.Unlock() c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": fmt.Sprintf("IP banned due to too many failed attempts. Try again in %s", remaining)}) return } // Ban expired, reset state ai.blockedUntil = time.Time{} ai.count = 0 } } h.attemptsMu.Unlock()
if !allowRemote { c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "remote management disabled"}) return }
fail = func() { h.attemptsMu.Lock() aip := h.failedAttempts[clientIP] if aip == nil { aip = &attemptInfo{} h.failedAttempts[clientIP] = aip } aip.count++ if aip.count >= maxFailures { aip.blockedUntil = time.Now().Add(banDuration) aip.count = 0 } h.attemptsMu.Unlock() } } if secretHash == "" && envSecret == "" { c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "remote management key not set"}) return }
// Accept either Authorization: Bearer <key> or X-Management-Key var provided string if ah := c.GetHeader("Authorization"); ah != "" { parts := strings.SplitN(ah, " ", 2) if len(parts) == 2 && strings.ToLower(parts[0]) == "bearer" { provided = parts[1] } else { provided = ah } } if provided == "" { provided = c.GetHeader("X-Management-Key") }
if provided == "" { if !localClient { fail() } c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing management key"}) return }
if localClient { if lp := h.localPassword; lp != "" { if subtle.ConstantTimeCompare([]byte(provided), []byte(lp)) == 1 { c.Next() return } } }
if envSecret != "" && subtle.ConstantTimeCompare([]byte(provided), []byte(envSecret)) == 1 { if !localClient { h.attemptsMu.Lock() if ai := h.failedAttempts[clientIP]; ai != nil { ai.count = 0 ai.blockedUntil = time.Time{} } h.attemptsMu.Unlock() } c.Next() return }
if secretHash == "" || bcrypt.CompareHashAndPassword([]byte(secretHash), []byte(provided)) != nil { if !localClient { fail() } c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid management key"}) return }
if !localClient { h.attemptsMu.Lock() if ai := h.failedAttempts[clientIP]; ai != nil { ai.count = 0 ai.blockedUntil = time.Time{} } h.attemptsMu.Unlock() }
c.Next() }}
// persist saves the current in-memory config to disk.func (h *Handler) persist(c *gin.Context) bool { h.mu.Lock() defer h.mu.Unlock() // Preserve comments when writing if err := config.SaveConfigPreserveComments(h.configFilePath, h.cfg); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to save config: %v", err)}) return false } c.JSON(http.StatusOK, gin.H{"status": "ok"}) return true}
// Helper methods for simple typesfunc (h *Handler) updateBoolField(c *gin.Context, set func(bool)) { var body struct { Value *bool `json:"value"` } if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"}) return } set(*body.Value) h.persist(c)}
func (h *Handler) updateIntField(c *gin.Context, set func(int)) { var body struct { Value *int `json:"value"` } if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"}) return } set(*body.Value) h.persist(c)}
func (h *Handler) updateStringField(c *gin.Context, set func(string)) { var body struct { Value *string `json:"value"` } if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"}) return } set(*body.Value) h.persist(c)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592package management
import ( "bufio" "fmt" "math" "net/http" "os" "path/filepath" "sort" "strconv" "strings" "time"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/util")
const ( defaultLogFileName = "main.log" logScannerInitialBuffer = 64 * 1024 logScannerMaxBuffer = 8 * 1024 * 1024)
// GetLogs returns log lines with optional incremental loading.func (h *Handler) GetLogs(c *gin.Context) { if h == nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"}) return } if h.cfg == nil { c.JSON(http.StatusServiceUnavailable, gin.H{"error": "configuration unavailable"}) return } if !h.cfg.LoggingToFile { c.JSON(http.StatusBadRequest, gin.H{"error": "logging to file disabled"}) return }
logDir := h.logDirectory() if strings.TrimSpace(logDir) == "" { c.JSON(http.StatusInternalServerError, gin.H{"error": "log directory not configured"}) return }
files, err := h.collectLogFiles(logDir) if err != nil { if os.IsNotExist(err) { cutoff := parseCutoff(c.Query("after")) c.JSON(http.StatusOK, gin.H{ "lines": []string{}, "line-count": 0, "latest-timestamp": cutoff, }) return } c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to list log files: %v", err)}) return }
limit, errLimit := parseLimit(c.Query("limit")) if errLimit != nil { c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("invalid limit: %v", errLimit)}) return }
cutoff := parseCutoff(c.Query("after")) acc := newLogAccumulator(cutoff, limit) for i := range files { if errProcess := acc.consumeFile(files[i]); errProcess != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log file %s: %v", files[i], errProcess)}) return } }
lines, total, latest := acc.result() if latest == 0 || latest < cutoff { latest = cutoff } c.JSON(http.StatusOK, gin.H{ "lines": lines, "line-count": total, "latest-timestamp": latest, })}
// DeleteLogs removes all rotated log files and truncates the active log.func (h *Handler) DeleteLogs(c *gin.Context) { if h == nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"}) return } if h.cfg == nil { c.JSON(http.StatusServiceUnavailable, gin.H{"error": "configuration unavailable"}) return } if !h.cfg.LoggingToFile { c.JSON(http.StatusBadRequest, gin.H{"error": "logging to file disabled"}) return }
dir := h.logDirectory() if strings.TrimSpace(dir) == "" { c.JSON(http.StatusInternalServerError, gin.H{"error": "log directory not configured"}) return }
entries, err := os.ReadDir(dir) if err != nil { if os.IsNotExist(err) { c.JSON(http.StatusNotFound, gin.H{"error": "log directory not found"}) return } c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to list log directory: %v", err)}) return }
removed := 0 for _, entry := range entries { if entry.IsDir() { continue } name := entry.Name() fullPath := filepath.Join(dir, name) if name == defaultLogFileName { if errTrunc := os.Truncate(fullPath, 0); errTrunc != nil && !os.IsNotExist(errTrunc) { c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to truncate log file: %v", errTrunc)}) return } continue } if isRotatedLogFile(name) { if errRemove := os.Remove(fullPath); errRemove != nil && !os.IsNotExist(errRemove) { c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to remove %s: %v", name, errRemove)}) return } removed++ } }
c.JSON(http.StatusOK, gin.H{ "success": true, "message": "Logs cleared successfully", "removed": removed, })}
// GetRequestErrorLogs lists error request log files when RequestLog is disabled.// It returns an empty list when RequestLog is enabled.func (h *Handler) GetRequestErrorLogs(c *gin.Context) { if h == nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"}) return } if h.cfg == nil { c.JSON(http.StatusServiceUnavailable, gin.H{"error": "configuration unavailable"}) return } if h.cfg.RequestLog { c.JSON(http.StatusOK, gin.H{"files": []any{}}) return }
dir := h.logDirectory() if strings.TrimSpace(dir) == "" { c.JSON(http.StatusInternalServerError, gin.H{"error": "log directory not configured"}) return }
entries, err := os.ReadDir(dir) if err != nil { if os.IsNotExist(err) { c.JSON(http.StatusOK, gin.H{"files": []any{}}) return } c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to list request error logs: %v", err)}) return }
type errorLog struct { Name string `json:"name"` Size int64 `json:"size"` Modified int64 `json:"modified"` }
files := make([]errorLog, 0, len(entries)) for _, entry := range entries { if entry.IsDir() { continue } name := entry.Name() if !strings.HasPrefix(name, "error-") || !strings.HasSuffix(name, ".log") { continue } info, errInfo := entry.Info() if errInfo != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log info for %s: %v", name, errInfo)}) return } files = append(files, errorLog{ Name: name, Size: info.Size(), Modified: info.ModTime().Unix(), }) }
sort.Slice(files, func(i, j int) bool { return files[i].Modified > files[j].Modified })
c.JSON(http.StatusOK, gin.H{"files": files})}
// GetRequestLogByID finds and downloads a request log file by its request ID.// The ID is matched against the suffix of log file names (format: *-{requestID}.log).func (h *Handler) GetRequestLogByID(c *gin.Context) { if h == nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"}) return } if h.cfg == nil { c.JSON(http.StatusServiceUnavailable, gin.H{"error": "configuration unavailable"}) return }
dir := h.logDirectory() if strings.TrimSpace(dir) == "" { c.JSON(http.StatusInternalServerError, gin.H{"error": "log directory not configured"}) return }
requestID := strings.TrimSpace(c.Param("id")) if requestID == "" { requestID = strings.TrimSpace(c.Query("id")) } if requestID == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "missing request ID"}) return } if strings.ContainsAny(requestID, "/\\") { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request ID"}) return }
entries, err := os.ReadDir(dir) if err != nil { if os.IsNotExist(err) { c.JSON(http.StatusNotFound, gin.H{"error": "log directory not found"}) return } c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to list log directory: %v", err)}) return }
suffix := "-" + requestID + ".log" var matchedFile string for _, entry := range entries { if entry.IsDir() { continue } name := entry.Name() if strings.HasSuffix(name, suffix) { matchedFile = name break } }
if matchedFile == "" { c.JSON(http.StatusNotFound, gin.H{"error": "log file not found for the given request ID"}) return }
dirAbs, errAbs := filepath.Abs(dir) if errAbs != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to resolve log directory: %v", errAbs)}) return } fullPath := filepath.Clean(filepath.Join(dirAbs, matchedFile)) prefix := dirAbs + string(os.PathSeparator) if !strings.HasPrefix(fullPath, prefix) { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file path"}) return }
info, errStat := os.Stat(fullPath) if errStat != nil { if os.IsNotExist(errStat) { c.JSON(http.StatusNotFound, gin.H{"error": "log file not found"}) return } c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log file: %v", errStat)}) return } if info.IsDir() { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file"}) return }
c.FileAttachment(fullPath, matchedFile)}
// DownloadRequestErrorLog downloads a specific error request log file by name.func (h *Handler) DownloadRequestErrorLog(c *gin.Context) { if h == nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"}) return } if h.cfg == nil { c.JSON(http.StatusServiceUnavailable, gin.H{"error": "configuration unavailable"}) return }
dir := h.logDirectory() if strings.TrimSpace(dir) == "" { c.JSON(http.StatusInternalServerError, gin.H{"error": "log directory not configured"}) return }
name := strings.TrimSpace(c.Param("name")) if name == "" || strings.Contains(name, "/") || strings.Contains(name, "\\") { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file name"}) return } if !strings.HasPrefix(name, "error-") || !strings.HasSuffix(name, ".log") { c.JSON(http.StatusNotFound, gin.H{"error": "log file not found"}) return }
dirAbs, errAbs := filepath.Abs(dir) if errAbs != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to resolve log directory: %v", errAbs)}) return } fullPath := filepath.Clean(filepath.Join(dirAbs, name)) prefix := dirAbs + string(os.PathSeparator) if !strings.HasPrefix(fullPath, prefix) { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file path"}) return }
info, errStat := os.Stat(fullPath) if errStat != nil { if os.IsNotExist(errStat) { c.JSON(http.StatusNotFound, gin.H{"error": "log file not found"}) return } c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log file: %v", errStat)}) return } if info.IsDir() { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file"}) return }
c.FileAttachment(fullPath, name)}
func (h *Handler) logDirectory() string { if h == nil { return "" } if h.logDir != "" { return h.logDir } if base := util.WritablePath(); base != "" { return filepath.Join(base, "logs") } if h.configFilePath != "" { dir := filepath.Dir(h.configFilePath) if dir != "" && dir != "." { return filepath.Join(dir, "logs") } } return "logs"}
func (h *Handler) collectLogFiles(dir string) ([]string, error) { entries, err := os.ReadDir(dir) if err != nil { return nil, err } type candidate struct { path string order int64 } cands := make([]candidate, 0, len(entries)) for _, entry := range entries { if entry.IsDir() { continue } name := entry.Name() if name == defaultLogFileName { cands = append(cands, candidate{path: filepath.Join(dir, name), order: 0}) continue } if order, ok := rotationOrder(name); ok { cands = append(cands, candidate{path: filepath.Join(dir, name), order: order}) } } if len(cands) == 0 { return []string{}, nil } sort.Slice(cands, func(i, j int) bool { return cands[i].order < cands[j].order }) paths := make([]string, 0, len(cands)) for i := len(cands) - 1; i >= 0; i-- { paths = append(paths, cands[i].path) } return paths, nil}
type logAccumulator struct { cutoff int64 limit int lines []string total int latest int64 include bool}
func newLogAccumulator(cutoff int64, limit int) *logAccumulator { capacity := 256 if limit > 0 && limit < capacity { capacity = limit } return &logAccumulator{ cutoff: cutoff, limit: limit, lines: make([]string, 0, capacity), }}
func (acc *logAccumulator) consumeFile(path string) error { file, err := os.Open(path) if err != nil { if os.IsNotExist(err) { return nil } return err } defer func() { _ = file.Close() }()
scanner := bufio.NewScanner(file) buf := make([]byte, 0, logScannerInitialBuffer) scanner.Buffer(buf, logScannerMaxBuffer) for scanner.Scan() { acc.addLine(scanner.Text()) } if errScan := scanner.Err(); errScan != nil { return errScan } return nil}
func (acc *logAccumulator) addLine(raw string) { line := strings.TrimRight(raw, "\r") acc.total++ ts := parseTimestamp(line) if ts > acc.latest { acc.latest = ts } if ts > 0 { acc.include = acc.cutoff == 0 || ts > acc.cutoff if acc.cutoff == 0 || acc.include { acc.append(line) } return } if acc.cutoff == 0 || acc.include { acc.append(line) }}
func (acc *logAccumulator) append(line string) { acc.lines = append(acc.lines, line) if acc.limit > 0 && len(acc.lines) > acc.limit { acc.lines = acc.lines[len(acc.lines)-acc.limit:] }}
func (acc *logAccumulator) result() ([]string, int, int64) { if acc.lines == nil { acc.lines = []string{} } return acc.lines, acc.total, acc.latest}
func parseCutoff(raw string) int64 { value := strings.TrimSpace(raw) if value == "" { return 0 } ts, err := strconv.ParseInt(value, 10, 64) if err != nil || ts <= 0 { return 0 } return ts}
func parseLimit(raw string) (int, error) { value := strings.TrimSpace(raw) if value == "" { return 0, nil } limit, err := strconv.Atoi(value) if err != nil { return 0, fmt.Errorf("must be a positive integer") } if limit <= 0 { return 0, fmt.Errorf("must be greater than zero") } return limit, nil}
func parseTimestamp(line string) int64 { if strings.HasPrefix(line, "[") { line = line[1:] } if len(line) < 19 { return 0 } candidate := line[:19] t, err := time.ParseInLocation("2006-01-02 15:04:05", candidate, time.Local) if err != nil { return 0 } return t.Unix()}
func isRotatedLogFile(name string) bool { if _, ok := rotationOrder(name); ok { return true } return false}
func rotationOrder(name string) (int64, bool) { if order, ok := numericRotationOrder(name); ok { return order, true } if order, ok := timestampRotationOrder(name); ok { return order, true } return 0, false}
func numericRotationOrder(name string) (int64, bool) { if !strings.HasPrefix(name, defaultLogFileName+".") { return 0, false } suffix := strings.TrimPrefix(name, defaultLogFileName+".") if suffix == "" { return 0, false } n, err := strconv.Atoi(suffix) if err != nil { return 0, false } return int64(n), true}
func timestampRotationOrder(name string) (int64, bool) { ext := filepath.Ext(defaultLogFileName) base := strings.TrimSuffix(defaultLogFileName, ext) if base == "" { return 0, false } prefix := base + "-" if !strings.HasPrefix(name, prefix) { return 0, false } clean := strings.TrimPrefix(name, prefix) if strings.HasSuffix(clean, ".gz") { clean = strings.TrimSuffix(clean, ".gz") } if ext != "" { if !strings.HasSuffix(clean, ext) { return 0, false } clean = strings.TrimSuffix(clean, ext) } if clean == "" { return 0, false } if idx := strings.IndexByte(clean, '.'); idx != -1 { clean = clean[:idx] } parsed, err := time.ParseInLocation("2006-01-02T15-04-05", clean, time.Local) if err != nil { return 0, false } return math.MaxInt64 - parsed.Unix(), true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100package management
import ( "errors" "net/http" "net/url" "strings"
"github.com/gin-gonic/gin")
type oauthCallbackRequest struct { Provider string `json:"provider"` RedirectURL string `json:"redirect_url"` Code string `json:"code"` State string `json:"state"` Error string `json:"error"`}
func (h *Handler) PostOAuthCallback(c *gin.Context) { if h == nil || h.cfg == nil { c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "handler not initialized"}) return }
var req oauthCallbackRequest if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "invalid body"}) return }
canonicalProvider, err := NormalizeOAuthProvider(req.Provider) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "unsupported provider"}) return }
state := strings.TrimSpace(req.State) code := strings.TrimSpace(req.Code) errMsg := strings.TrimSpace(req.Error)
if rawRedirect := strings.TrimSpace(req.RedirectURL); rawRedirect != "" { u, errParse := url.Parse(rawRedirect) if errParse != nil { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "invalid redirect_url"}) return } q := u.Query() if state == "" { state = strings.TrimSpace(q.Get("state")) } if code == "" { code = strings.TrimSpace(q.Get("code")) } if errMsg == "" { errMsg = strings.TrimSpace(q.Get("error")) if errMsg == "" { errMsg = strings.TrimSpace(q.Get("error_description")) } } }
if state == "" { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "state is required"}) return } if err := ValidateOAuthState(state); err != nil { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "invalid state"}) return } if code == "" && errMsg == "" { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "code or error is required"}) return }
sessionProvider, sessionStatus, ok := GetOAuthSession(state) if !ok { c.JSON(http.StatusNotFound, gin.H{"status": "error", "error": "unknown or expired state"}) return } if sessionStatus != "" { c.JSON(http.StatusConflict, gin.H{"status": "error", "error": "oauth flow is not pending"}) return } if !strings.EqualFold(sessionProvider, canonicalProvider) { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "provider does not match state"}) return }
if _, errWrite := WriteOAuthCallbackFileForPendingSession(h.cfg.AuthDir, canonicalProvider, state, code, errMsg); errWrite != nil { if errors.Is(errWrite, errOAuthSessionNotPending) { c.JSON(http.StatusConflict, gin.H{"status": "error", "error": "oauth flow is not pending"}) return } c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "failed to persist oauth callback"}) return }
c.JSON(http.StatusOK, gin.H{"status": "ok"})}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290package management
import ( "encoding/json" "errors" "fmt" "os" "path/filepath" "strings" "sync" "time")
const ( oauthSessionTTL = 10 * time.Minute maxOAuthStateLength = 128)
var ( errInvalidOAuthState = errors.New("invalid oauth state") errUnsupportedOAuthFlow = errors.New("unsupported oauth provider") errOAuthSessionNotPending = errors.New("oauth session is not pending"))
type oauthSession struct { Provider string Status string CreatedAt time.Time ExpiresAt time.Time}
type oauthSessionStore struct { mu sync.RWMutex ttl time.Duration sessions map[string]oauthSession}
func newOAuthSessionStore(ttl time.Duration) *oauthSessionStore { if ttl <= 0 { ttl = oauthSessionTTL } return &oauthSessionStore{ ttl: ttl, sessions: make(map[string]oauthSession), }}
func (s *oauthSessionStore) purgeExpiredLocked(now time.Time) { for state, session := range s.sessions { if !session.ExpiresAt.IsZero() && now.After(session.ExpiresAt) { delete(s.sessions, state) } }}
func (s *oauthSessionStore) Register(state, provider string) { state = strings.TrimSpace(state) provider = strings.ToLower(strings.TrimSpace(provider)) if state == "" || provider == "" { return } now := time.Now()
s.mu.Lock() defer s.mu.Unlock()
s.purgeExpiredLocked(now) s.sessions[state] = oauthSession{ Provider: provider, Status: "", CreatedAt: now, ExpiresAt: now.Add(s.ttl), }}
func (s *oauthSessionStore) SetError(state, message string) { state = strings.TrimSpace(state) message = strings.TrimSpace(message) if state == "" { return } if message == "" { message = "Authentication failed" } now := time.Now()
s.mu.Lock() defer s.mu.Unlock()
s.purgeExpiredLocked(now) session, ok := s.sessions[state] if !ok { return } session.Status = message session.ExpiresAt = now.Add(s.ttl) s.sessions[state] = session}
func (s *oauthSessionStore) Complete(state string) { state = strings.TrimSpace(state) if state == "" { return } now := time.Now()
s.mu.Lock() defer s.mu.Unlock()
s.purgeExpiredLocked(now) delete(s.sessions, state)}
func (s *oauthSessionStore) CompleteProvider(provider string) int { provider = strings.ToLower(strings.TrimSpace(provider)) if provider == "" { return 0 } now := time.Now()
s.mu.Lock() defer s.mu.Unlock()
s.purgeExpiredLocked(now) removed := 0 for state, session := range s.sessions { if strings.EqualFold(session.Provider, provider) { delete(s.sessions, state) removed++ } } return removed}
func (s *oauthSessionStore) Get(state string) (oauthSession, bool) { state = strings.TrimSpace(state) now := time.Now()
s.mu.Lock() defer s.mu.Unlock()
s.purgeExpiredLocked(now) session, ok := s.sessions[state] return session, ok}
func (s *oauthSessionStore) IsPending(state, provider string) bool { state = strings.TrimSpace(state) provider = strings.ToLower(strings.TrimSpace(provider)) now := time.Now()
s.mu.Lock() defer s.mu.Unlock()
s.purgeExpiredLocked(now) session, ok := s.sessions[state] if !ok { return false } if session.Status != "" { if !strings.EqualFold(session.Provider, "kiro") { return false } if !strings.HasPrefix(session.Status, "device_code|") && !strings.HasPrefix(session.Status, "auth_url|") { return false } } if provider == "" { return true } return strings.EqualFold(session.Provider, provider)}
var oauthSessions = newOAuthSessionStore(oauthSessionTTL)
func RegisterOAuthSession(state, provider string) { oauthSessions.Register(state, provider) }
func SetOAuthSessionError(state, message string) { oauthSessions.SetError(state, message) }
func CompleteOAuthSession(state string) { oauthSessions.Complete(state) }
func CompleteOAuthSessionsByProvider(provider string) int { return oauthSessions.CompleteProvider(provider)}
func GetOAuthSession(state string) (provider string, status string, ok bool) { session, ok := oauthSessions.Get(state) if !ok { return "", "", false } return session.Provider, session.Status, true}
func IsOAuthSessionPending(state, provider string) bool { return oauthSessions.IsPending(state, provider)}
func ValidateOAuthState(state string) error { trimmed := strings.TrimSpace(state) if trimmed == "" { return fmt.Errorf("%w: empty", errInvalidOAuthState) } if len(trimmed) > maxOAuthStateLength { return fmt.Errorf("%w: too long", errInvalidOAuthState) } if strings.Contains(trimmed, "/") || strings.Contains(trimmed, "\\") { return fmt.Errorf("%w: contains path separator", errInvalidOAuthState) } if strings.Contains(trimmed, "..") { return fmt.Errorf("%w: contains '..'", errInvalidOAuthState) } for _, r := range trimmed { switch { case r >= 'a' && r <= 'z': case r >= 'A' && r <= 'Z': case r >= '0' && r <= '9': case r == '-' || r == '_' || r == '.': default: return fmt.Errorf("%w: invalid character", errInvalidOAuthState) } } return nil}
func NormalizeOAuthProvider(provider string) (string, error) { switch strings.ToLower(strings.TrimSpace(provider)) { case "anthropic", "claude": return "anthropic", nil case "codex", "openai": return "codex", nil case "gemini", "google": return "gemini", nil case "iflow", "i-flow": return "iflow", nil case "antigravity", "anti-gravity": return "antigravity", nil case "qwen": return "qwen", nil case "kiro": return "kiro", nil default: return "", errUnsupportedOAuthFlow }}
type oauthCallbackFilePayload struct { Code string `json:"code"` State string `json:"state"` Error string `json:"error"`}
func WriteOAuthCallbackFile(authDir, provider, state, code, errorMessage string) (string, error) { if strings.TrimSpace(authDir) == "" { return "", fmt.Errorf("auth dir is empty") } canonicalProvider, err := NormalizeOAuthProvider(provider) if err != nil { return "", err } if err := ValidateOAuthState(state); err != nil { return "", err }
fileName := fmt.Sprintf(".oauth-%s-%s.oauth", canonicalProvider, state) filePath := filepath.Join(authDir, fileName) payload := oauthCallbackFilePayload{ Code: strings.TrimSpace(code), State: strings.TrimSpace(state), Error: strings.TrimSpace(errorMessage), } data, err := json.Marshal(payload) if err != nil { return "", fmt.Errorf("marshal oauth callback payload: %w", err) } if err := os.WriteFile(filePath, data, 0o600); err != nil { return "", fmt.Errorf("write oauth callback file: %w", err) } return filePath, nil}
func WriteOAuthCallbackFileForPendingSession(authDir, provider, state, code, errorMessage string) (string, error) { canonicalProvider, err := NormalizeOAuthProvider(provider) if err != nil { return "", err } if !IsOAuthSessionPending(state, canonicalProvider) { return "", errOAuthSessionNotPending } return WriteOAuthCallbackFile(authDir, canonicalProvider, state, code, errorMessage)}123456789101112131415161718package management
import "github.com/gin-gonic/gin"
// Quota exceeded togglesfunc (h *Handler) GetSwitchProject(c *gin.Context) { c.JSON(200, gin.H{"switch-project": h.cfg.QuotaExceeded.SwitchProject})}func (h *Handler) PutSwitchProject(c *gin.Context) { h.updateBoolField(c, func(v bool) { h.cfg.QuotaExceeded.SwitchProject = v })}
func (h *Handler) GetSwitchPreviewModel(c *gin.Context) { c.JSON(200, gin.H{"switch-preview-model": h.cfg.QuotaExceeded.SwitchPreviewModel})}func (h *Handler) PutSwitchPreviewModel(c *gin.Context) { h.updateBoolField(c, func(v bool) { h.cfg.QuotaExceeded.SwitchPreviewModel = v })}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879package management
import ( "encoding/json" "net/http" "time"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/usage")
type usageExportPayload struct { Version int `json:"version"` ExportedAt time.Time `json:"exported_at"` Usage usage.StatisticsSnapshot `json:"usage"`}
type usageImportPayload struct { Version int `json:"version"` Usage usage.StatisticsSnapshot `json:"usage"`}
// GetUsageStatistics returns the in-memory request statistics snapshot.func (h *Handler) GetUsageStatistics(c *gin.Context) { var snapshot usage.StatisticsSnapshot if h != nil && h.usageStats != nil { snapshot = h.usageStats.Snapshot() } c.JSON(http.StatusOK, gin.H{ "usage": snapshot, "failed_requests": snapshot.FailureCount, })}
// ExportUsageStatistics returns a complete usage snapshot for backup/migration.func (h *Handler) ExportUsageStatistics(c *gin.Context) { var snapshot usage.StatisticsSnapshot if h != nil && h.usageStats != nil { snapshot = h.usageStats.Snapshot() } c.JSON(http.StatusOK, usageExportPayload{ Version: 1, ExportedAt: time.Now().UTC(), Usage: snapshot, })}
// ImportUsageStatistics merges a previously exported usage snapshot into memory.func (h *Handler) ImportUsageStatistics(c *gin.Context) { if h == nil || h.usageStats == nil { c.JSON(http.StatusBadRequest, gin.H{"error": "usage statistics unavailable"}) return }
data, err := c.GetRawData() if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "failed to read request body"}) return }
var payload usageImportPayload if err := json.Unmarshal(data, &payload); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid json"}) return } if payload.Version != 0 && payload.Version != 1 { c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported version"}) return }
result := h.usageStats.MergeSnapshot(payload.Usage) snapshot := h.usageStats.Snapshot() c.JSON(http.StatusOK, gin.H{ "added": result.Added, "skipped": result.Skipped, "total_requests": snapshot.TotalRequests, "failed_requests": snapshot.FailureCount, })}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156package management
import ( "context" "encoding/json" "fmt" "io" "net/http" "strings"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/vertex" coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth")
// ImportVertexCredential handles uploading a Vertex service account JSON and saving it as an auth record.func (h *Handler) ImportVertexCredential(c *gin.Context) { if h == nil || h.cfg == nil { c.JSON(http.StatusServiceUnavailable, gin.H{"error": "config unavailable"}) return } if h.cfg.AuthDir == "" { c.JSON(http.StatusServiceUnavailable, gin.H{"error": "auth directory not configured"}) return }
fileHeader, err := c.FormFile("file") if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "file required"}) return }
file, err := fileHeader.Open() if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("failed to read file: %v", err)}) return } defer file.Close()
data, err := io.ReadAll(file) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("failed to read file: %v", err)}) return }
var serviceAccount map[string]any if err := json.Unmarshal(data, &serviceAccount); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid json", "message": err.Error()}) return }
normalizedSA, err := vertex.NormalizeServiceAccountMap(serviceAccount) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid service account", "message": err.Error()}) return } serviceAccount = normalizedSA
projectID := strings.TrimSpace(valueAsString(serviceAccount["project_id"])) if projectID == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "project_id missing"}) return } email := strings.TrimSpace(valueAsString(serviceAccount["client_email"]))
location := strings.TrimSpace(c.PostForm("location")) if location == "" { location = strings.TrimSpace(c.Query("location")) } if location == "" { location = "us-central1" }
fileName := fmt.Sprintf("vertex-%s.json", sanitizeVertexFilePart(projectID)) label := labelForVertex(projectID, email) storage := &vertex.VertexCredentialStorage{ ServiceAccount: serviceAccount, ProjectID: projectID, Email: email, Location: location, Type: "vertex", } metadata := map[string]any{ "service_account": serviceAccount, "project_id": projectID, "email": email, "location": location, "type": "vertex", "label": label, } record := &coreauth.Auth{ ID: fileName, Provider: "vertex", FileName: fileName, Storage: storage, Label: label, Metadata: metadata, }
ctx := context.Background() if reqCtx := c.Request.Context(); reqCtx != nil { ctx = reqCtx } savedPath, err := h.saveTokenRecord(ctx, record) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "save_failed", "message": err.Error()}) return }
c.JSON(http.StatusOK, gin.H{ "status": "ok", "auth-file": savedPath, "project_id": projectID, "email": email, "location": location, })}
func valueAsString(v any) string { if v == nil { return "" } switch t := v.(type) { case string: return t default: return fmt.Sprint(t) }}
func sanitizeVertexFilePart(s string) string { out := strings.TrimSpace(s) replacers := []string{"/", "_", "\\", "_", ":", "_", " ", "-"} for i := 0; i < len(replacers); i += 2 { out = strings.ReplaceAll(out, replacers[i], replacers[i+1]) } if out == "" { return "vertex" } return out}
func labelForVertex(projectID, email string) string { p := strings.TrimSpace(projectID) e := strings.TrimSpace(email) if p != "" && e != "" { return fmt.Sprintf("%s (%s)", p, e) } if p != "" { return p } if e != "" { return e } return "vertex"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122// Package middleware provides HTTP middleware components for the CLI Proxy API server.// This file contains the request logging middleware that captures comprehensive// request and response data when enabled through configuration.package middleware
import ( "bytes" "io" "net/http" "strings"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/logging" "github.com/router-for-me/CLIProxyAPI/v6/internal/util")
// RequestLoggingMiddleware creates a Gin middleware that logs HTTP requests and responses.// It captures detailed information about the request and response, including headers and body,// and uses the provided RequestLogger to record this data. When logging is disabled in the// logger, it still captures data so that upstream errors can be persisted.func RequestLoggingMiddleware(logger logging.RequestLogger) gin.HandlerFunc { return func(c *gin.Context) { if logger == nil { c.Next() return }
if c.Request.Method == http.MethodGet { c.Next() return }
path := c.Request.URL.Path if !shouldLogRequest(path) { c.Next() return }
// Capture request information requestInfo, err := captureRequestInfo(c) if err != nil { // Log error but continue processing // In a real implementation, you might want to use a proper logger here c.Next() return }
// Create response writer wrapper wrapper := NewResponseWriterWrapper(c.Writer, logger, requestInfo) if !logger.IsEnabled() { wrapper.logOnErrorOnly = true } c.Writer = wrapper
// Process the request c.Next()
// Finalize logging after request processing if err = wrapper.Finalize(c); err != nil { // Log error but don't interrupt the response // In a real implementation, you might want to use a proper logger here } }}
// captureRequestInfo extracts relevant information from the incoming HTTP request.// It captures the URL, method, headers, and body. The request body is read and then// restored so that it can be processed by subsequent handlers.func captureRequestInfo(c *gin.Context) (*RequestInfo, error) { // Capture URL with sensitive query parameters masked maskedQuery := util.MaskSensitiveQuery(c.Request.URL.RawQuery) url := c.Request.URL.Path if maskedQuery != "" { url += "?" + maskedQuery }
// Capture method method := c.Request.Method
// Capture headers headers := make(map[string][]string) for key, values := range c.Request.Header { headers[key] = values }
// Capture request body var body []byte if c.Request.Body != nil { // Read the body bodyBytes, err := io.ReadAll(c.Request.Body) if err != nil { return nil, err }
// Restore the body for the actual request processing c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) body = bodyBytes }
return &RequestInfo{ URL: url, Method: method, Headers: headers, Body: body, RequestID: logging.GetGinRequestID(c), }, nil}
// shouldLogRequest determines whether the request should be logged.// It skips management endpoints to avoid leaking secrets but allows// all other routes, including module-provided ones, to honor request-log.func shouldLogRequest(path string) bool { if strings.HasPrefix(path, "/v0/management") || strings.HasPrefix(path, "/management") { return false }
if strings.HasPrefix(path, "/api") { return strings.HasPrefix(path, "/api/provider") }
return true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382// Package middleware provides Gin HTTP middleware for the CLI Proxy API server.// It includes a sophisticated response writer wrapper designed to capture and log request and response data,// including support for streaming responses, without impacting latency.package middleware
import ( "bytes" "net/http" "strings"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v6/internal/logging")
// RequestInfo holds essential details of an incoming HTTP request for logging purposes.type RequestInfo struct { URL string // URL is the request URL. Method string // Method is the HTTP method (e.g., GET, POST). Headers map[string][]string // Headers contains the request headers. Body []byte // Body is the raw request body. RequestID string // RequestID is the unique identifier for the request.}
// ResponseWriterWrapper wraps the standard gin.ResponseWriter to intercept and log response data.// It is designed to handle both standard and streaming responses, ensuring that logging operations do not block the client response.type ResponseWriterWrapper struct { gin.ResponseWriter body *bytes.Buffer // body is a buffer to store the response body for non-streaming responses. isStreaming bool // isStreaming indicates whether the response is a streaming type (e.g., text/event-stream). streamWriter logging.StreamingLogWriter // streamWriter is a writer for handling streaming log entries. chunkChannel chan []byte // chunkChannel is a channel for asynchronously passing response chunks to the logger. streamDone chan struct{} // streamDone signals when the streaming goroutine completes. logger logging.RequestLogger // logger is the instance of the request logger service. requestInfo *RequestInfo // requestInfo holds the details of the original request. statusCode int // statusCode stores the HTTP status code of the response. headers map[string][]string // headers stores the response headers. logOnErrorOnly bool // logOnErrorOnly enables logging only when an error response is detected.}
// NewResponseWriterWrapper creates and initializes a new ResponseWriterWrapper.// It takes the original gin.ResponseWriter, a logger instance, and request information.//// Parameters:// - w: The original gin.ResponseWriter to wrap.// - logger: The logging service to use for recording requests.// - requestInfo: The pre-captured information about the incoming request.//// Returns:// - A pointer to a new ResponseWriterWrapper.func NewResponseWriterWrapper(w gin.ResponseWriter, logger logging.RequestLogger, requestInfo *RequestInfo) *ResponseWriterWrapper { return &ResponseWriterWrapper{ ResponseWriter: w, body: &bytes.Buffer{}, logger: logger, requestInfo: requestInfo, headers: make(map[string][]string), }}
// Write wraps the underlying ResponseWriter's Write method to capture response data.// For non-streaming responses, it writes to an internal buffer. For streaming responses,// it sends data chunks to a non-blocking channel for asynchronous logging.// CRITICAL: This method prioritizes writing to the client to ensure zero latency,// handling logging operations subsequently.func (w *ResponseWriterWrapper) Write(data []byte) (int, error) { // Ensure headers are captured before first write // This is critical because Write() may trigger WriteHeader() internally w.ensureHeadersCaptured()
// CRITICAL: Write to client first (zero latency) n, err := w.ResponseWriter.Write(data)
// THEN: Handle logging based on response type if w.isStreaming && w.chunkChannel != nil { // For streaming responses: Send to async logging channel (non-blocking) select { case w.chunkChannel <- append([]byte(nil), data...): // Non-blocking send with copy default: // Channel full, skip logging to avoid blocking } return n, err }
if w.shouldBufferResponseBody() { w.body.Write(data) }
return n, err}
func (w *ResponseWriterWrapper) shouldBufferResponseBody() bool { if w.logger != nil && w.logger.IsEnabled() { return true } if !w.logOnErrorOnly { return false } status := w.statusCode if status == 0 { if statusWriter, ok := w.ResponseWriter.(interface{ Status() int }); ok && statusWriter != nil { status = statusWriter.Status() } else { status = http.StatusOK } } return status >= http.StatusBadRequest}
// WriteString wraps the underlying ResponseWriter's WriteString method to capture response data.// Some handlers (and fmt/io helpers) write via io.StringWriter; without this override, those writes// bypass Write() and would be missing from request logs.func (w *ResponseWriterWrapper) WriteString(data string) (int, error) { w.ensureHeadersCaptured()
// CRITICAL: Write to client first (zero latency) n, err := w.ResponseWriter.WriteString(data)
// THEN: Capture for logging if w.isStreaming && w.chunkChannel != nil { select { case w.chunkChannel <- []byte(data): default: } return n, err }
if w.shouldBufferResponseBody() { w.body.WriteString(data) } return n, err}
// WriteHeader wraps the underlying ResponseWriter's WriteHeader method.// It captures the status code, detects if the response is streaming based on the Content-Type header,// and initializes the appropriate logging mechanism (standard or streaming).func (w *ResponseWriterWrapper) WriteHeader(statusCode int) { w.statusCode = statusCode
// Capture response headers using the new method w.captureCurrentHeaders()
// Detect streaming based on Content-Type contentType := w.ResponseWriter.Header().Get("Content-Type") w.isStreaming = w.detectStreaming(contentType)
// If streaming, initialize streaming log writer if w.isStreaming && w.logger.IsEnabled() { streamWriter, err := w.logger.LogStreamingRequest( w.requestInfo.URL, w.requestInfo.Method, w.requestInfo.Headers, w.requestInfo.Body, w.requestInfo.RequestID, ) if err == nil { w.streamWriter = streamWriter w.chunkChannel = make(chan []byte, 100) // Buffered channel for async writes doneChan := make(chan struct{}) w.streamDone = doneChan
// Start async chunk processor go w.processStreamingChunks(doneChan)
// Write status immediately _ = streamWriter.WriteStatus(statusCode, w.headers) } }
// Call original WriteHeader w.ResponseWriter.WriteHeader(statusCode)}
// ensureHeadersCaptured is a helper function to make sure response headers are captured.// It is safe to call this method multiple times; it will always refresh the headers// with the latest state from the underlying ResponseWriter.func (w *ResponseWriterWrapper) ensureHeadersCaptured() { // Always capture the current headers to ensure we have the latest state w.captureCurrentHeaders()}
// captureCurrentHeaders reads all headers from the underlying ResponseWriter and stores them// in the wrapper's headers map. It creates copies of the header values to prevent race conditions.func (w *ResponseWriterWrapper) captureCurrentHeaders() { // Initialize headers map if needed if w.headers == nil { w.headers = make(map[string][]string) }
// Capture all current headers from the underlying ResponseWriter for key, values := range w.ResponseWriter.Header() { // Make a copy of the values slice to avoid reference issues headerValues := make([]string, len(values)) copy(headerValues, values) w.headers[key] = headerValues }}
// detectStreaming determines if a response should be treated as a streaming response.// It checks for a "text/event-stream" Content-Type or a '"stream": true'// field in the original request body.func (w *ResponseWriterWrapper) detectStreaming(contentType string) bool { // Check Content-Type for Server-Sent Events if strings.Contains(contentType, "text/event-stream") { return true }
// If a concrete Content-Type is already set (e.g., application/json for error responses), // treat it as non-streaming instead of inferring from the request payload. if strings.TrimSpace(contentType) != "" { return false }
// Only fall back to request payload hints when Content-Type is not set yet. if w.requestInfo != nil && len(w.requestInfo.Body) > 0 { bodyStr := string(w.requestInfo.Body) return strings.Contains(bodyStr, `"stream": true`) || strings.Contains(bodyStr, `"stream":true`) }
return false}
// processStreamingChunks runs in a separate goroutine to process response chunks from the chunkChannel.// It asynchronously writes each chunk to the streaming log writer.func (w *ResponseWriterWrapper) processStreamingChunks(done chan struct{}) { if done == nil { return }
defer close(done)
if w.streamWriter == nil || w.chunkChannel == nil { return }
for chunk := range w.chunkChannel { w.streamWriter.WriteChunkAsync(chunk) }}
// Finalize completes the logging process for the request and response.// For streaming responses, it closes the chunk channel and the stream writer.// For non-streaming responses, it logs the complete request and response details,// including any API-specific request/response data stored in the Gin context.func (w *ResponseWriterWrapper) Finalize(c *gin.Context) error { if w.logger == nil { return nil }
finalStatusCode := w.statusCode if finalStatusCode == 0 { if statusWriter, ok := w.ResponseWriter.(interface{ Status() int }); ok { finalStatusCode = statusWriter.Status() } else { finalStatusCode = 200 } }
var slicesAPIResponseError []*interfaces.ErrorMessage apiResponseError, isExist := c.Get("API_RESPONSE_ERROR") if isExist { if apiErrors, ok := apiResponseError.([]*interfaces.ErrorMessage); ok { slicesAPIResponseError = apiErrors } }
hasAPIError := len(slicesAPIResponseError) > 0 || finalStatusCode >= http.StatusBadRequest forceLog := w.logOnErrorOnly && hasAPIError && !w.logger.IsEnabled() if !w.logger.IsEnabled() && !forceLog { return nil }
if w.isStreaming && w.streamWriter != nil { if w.chunkChannel != nil { close(w.chunkChannel) w.chunkChannel = nil }
if w.streamDone != nil { <-w.streamDone w.streamDone = nil }
// Write API Request and Response to the streaming log before closing apiRequest := w.extractAPIRequest(c) if len(apiRequest) > 0 { _ = w.streamWriter.WriteAPIRequest(apiRequest) } apiResponse := w.extractAPIResponse(c) if len(apiResponse) > 0 { _ = w.streamWriter.WriteAPIResponse(apiResponse) } if err := w.streamWriter.Close(); err != nil { w.streamWriter = nil return err } w.streamWriter = nil return nil }
return w.logRequest(finalStatusCode, w.cloneHeaders(), w.body.Bytes(), w.extractAPIRequest(c), w.extractAPIResponse(c), slicesAPIResponseError, forceLog)}
func (w *ResponseWriterWrapper) cloneHeaders() map[string][]string { w.ensureHeadersCaptured()
finalHeaders := make(map[string][]string, len(w.headers)) for key, values := range w.headers { headerValues := make([]string, len(values)) copy(headerValues, values) finalHeaders[key] = headerValues }
return finalHeaders}
func (w *ResponseWriterWrapper) extractAPIRequest(c *gin.Context) []byte { apiRequest, isExist := c.Get("API_REQUEST") if !isExist { return nil } data, ok := apiRequest.([]byte) if !ok || len(data) == 0 { return nil } return data}
func (w *ResponseWriterWrapper) extractAPIResponse(c *gin.Context) []byte { apiResponse, isExist := c.Get("API_RESPONSE") if !isExist { return nil } data, ok := apiResponse.([]byte) if !ok || len(data) == 0 { return nil } return data}
func (w *ResponseWriterWrapper) logRequest(statusCode int, headers map[string][]string, body []byte, apiRequestBody, apiResponseBody []byte, apiResponseErrors []*interfaces.ErrorMessage, forceLog bool) error { if w.requestInfo == nil { return nil }
var requestBody []byte if len(w.requestInfo.Body) > 0 { requestBody = w.requestInfo.Body }
if loggerWithOptions, ok := w.logger.(interface { LogRequestWithOptions(string, string, map[string][]string, []byte, int, map[string][]string, []byte, []byte, []byte, []*interfaces.ErrorMessage, bool, string) error }); ok { return loggerWithOptions.LogRequestWithOptions( w.requestInfo.URL, w.requestInfo.Method, w.requestInfo.Headers, requestBody, statusCode, headers, body, apiRequestBody, apiResponseBody, apiResponseErrors, forceLog, w.requestInfo.RequestID, ) }
return w.logger.LogRequest( w.requestInfo.URL, w.requestInfo.Method, w.requestInfo.Headers, requestBody, statusCode, headers, body, apiRequestBody, apiResponseBody, apiResponseErrors, w.requestInfo.RequestID, )}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428// Package amp implements the Amp CLI routing module, providing OAuth-based// integration with Amp CLI for ChatGPT and Anthropic subscriptions.package amp
import ( "fmt" "net/http/httputil" "strings" "sync"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/api/modules" "github.com/router-for-me/CLIProxyAPI/v6/internal/config" sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access" log "github.com/sirupsen/logrus")
// Option configures the AmpModule.type Option func(*AmpModule)
// AmpModule implements the RouteModuleV2 interface for Amp CLI integration.// It provides:// - Reverse proxy to Amp control plane for OAuth/management// - Provider-specific route aliases (/api/provider/{provider}/...)// - Automatic gzip decompression for misconfigured upstreams// - Model mapping for routing unavailable models to alternativestype AmpModule struct { secretSource SecretSource proxy *httputil.ReverseProxy proxyMu sync.RWMutex // protects proxy for hot-reload accessManager *sdkaccess.Manager authMiddleware_ gin.HandlerFunc modelMapper *DefaultModelMapper enabled bool registerOnce sync.Once
// restrictToLocalhost controls localhost-only access for management routes (hot-reloadable) restrictToLocalhost bool restrictMu sync.RWMutex
// configMu protects lastConfig for partial reload comparison configMu sync.RWMutex lastConfig *config.AmpCode}
// New creates a new Amp routing module with the given options.// This is the preferred constructor using the Option pattern.//// Example://// ampModule := amp.New(// amp.WithAccessManager(accessManager),// amp.WithAuthMiddleware(authMiddleware),// amp.WithSecretSource(customSecret),// )func New(opts ...Option) *AmpModule { m := &AmpModule{ secretSource: nil, // Will be created on demand if not provided } for _, opt := range opts { opt(m) } return m}
// NewLegacy creates a new Amp routing module using the legacy constructor signature.// This is provided for backwards compatibility.//// DEPRECATED: Use New with options instead.func NewLegacy(accessManager *sdkaccess.Manager, authMiddleware gin.HandlerFunc) *AmpModule { return New( WithAccessManager(accessManager), WithAuthMiddleware(authMiddleware), )}
// WithSecretSource sets a custom secret source for the module.func WithSecretSource(source SecretSource) Option { return func(m *AmpModule) { m.secretSource = source }}
// WithAccessManager sets the access manager for the module.func WithAccessManager(am *sdkaccess.Manager) Option { return func(m *AmpModule) { m.accessManager = am }}
// WithAuthMiddleware sets the authentication middleware for provider routes.func WithAuthMiddleware(middleware gin.HandlerFunc) Option { return func(m *AmpModule) { m.authMiddleware_ = middleware }}
// Name returns the module identifierfunc (m *AmpModule) Name() string { return "amp-routing"}
// forceModelMappings returns whether model mappings should take precedence over local API keysfunc (m *AmpModule) forceModelMappings() bool { m.configMu.RLock() defer m.configMu.RUnlock() if m.lastConfig == nil { return false } return m.lastConfig.ForceModelMappings}
// Register sets up Amp routes if configured.// This implements the RouteModuleV2 interface with Context.// Routes are registered only once via sync.Once for idempotent behavior.func (m *AmpModule) Register(ctx modules.Context) error { settings := ctx.Config.AmpCode upstreamURL := strings.TrimSpace(settings.UpstreamURL)
// Determine auth middleware (from module or context) auth := m.getAuthMiddleware(ctx)
// Use registerOnce to ensure routes are only registered once var regErr error m.registerOnce.Do(func() { // Initialize model mapper from config (for routing unavailable models to alternatives) m.modelMapper = NewModelMapper(settings.ModelMappings)
// Store initial config for partial reload comparison settingsCopy := settings m.lastConfig = &settingsCopy
// Initialize localhost restriction setting (hot-reloadable) m.setRestrictToLocalhost(settings.RestrictManagementToLocalhost)
// Always register provider aliases - these work without an upstream m.registerProviderAliases(ctx.Engine, ctx.BaseHandler, auth)
// Register management proxy routes once; middleware will gate access when upstream is unavailable. // Pass auth middleware to require valid API key for all management routes. m.registerManagementRoutes(ctx.Engine, ctx.BaseHandler, auth)
// If no upstream URL, skip proxy routes but provider aliases are still available if upstreamURL == "" { log.Debug("amp upstream proxy disabled (no upstream URL configured)") log.Debug("amp provider alias routes registered") m.enabled = false return }
if err := m.enableUpstreamProxy(upstreamURL, &settings); err != nil { regErr = fmt.Errorf("failed to create amp proxy: %w", err) return }
log.Debug("amp provider alias routes registered") })
return regErr}
// getAuthMiddleware returns the authentication middleware, preferring the// module's configured middleware, then the context middleware, then a fallback.func (m *AmpModule) getAuthMiddleware(ctx modules.Context) gin.HandlerFunc { if m.authMiddleware_ != nil { return m.authMiddleware_ } if ctx.AuthMiddleware != nil { return ctx.AuthMiddleware } // Fallback: no authentication (should not happen in production) log.Warn("amp module: no auth middleware provided, allowing all requests") return func(c *gin.Context) { c.Next() }}
// OnConfigUpdated handles configuration updates with partial reload support.// Only updates components that have actually changed to avoid unnecessary work.// Supports hot-reload for: model-mappings, upstream-api-key, upstream-url, restrict-management-to-localhost.func (m *AmpModule) OnConfigUpdated(cfg *config.Config) error { newSettings := cfg.AmpCode
// Get previous config for comparison m.configMu.RLock() oldSettings := m.lastConfig m.configMu.RUnlock()
if oldSettings != nil && oldSettings.RestrictManagementToLocalhost != newSettings.RestrictManagementToLocalhost { m.setRestrictToLocalhost(newSettings.RestrictManagementToLocalhost) }
newUpstreamURL := strings.TrimSpace(newSettings.UpstreamURL) oldUpstreamURL := "" if oldSettings != nil { oldUpstreamURL = strings.TrimSpace(oldSettings.UpstreamURL) }
if !m.enabled && newUpstreamURL != "" { if err := m.enableUpstreamProxy(newUpstreamURL, &newSettings); err != nil { log.Errorf("amp config: failed to enable upstream proxy for %s: %v", newUpstreamURL, err) } }
// Check model mappings change modelMappingsChanged := m.hasModelMappingsChanged(oldSettings, &newSettings) if modelMappingsChanged { if m.modelMapper != nil { m.modelMapper.UpdateMappings(newSettings.ModelMappings) } else if m.enabled { log.Warnf("amp model mapper not initialized, skipping model mapping update") } }
if m.enabled { // Check upstream URL change - now supports hot-reload if newUpstreamURL == "" && oldUpstreamURL != "" { m.setProxy(nil) m.enabled = false } else if oldUpstreamURL != "" && newUpstreamURL != oldUpstreamURL && newUpstreamURL != "" { // Recreate proxy with new URL proxy, err := createReverseProxy(newUpstreamURL, m.secretSource) if err != nil { log.Errorf("amp config: failed to create proxy for new upstream URL %s: %v", newUpstreamURL, err) } else { m.setProxy(proxy) } }
// Check API key change (both default and per-client mappings) apiKeyChanged := m.hasAPIKeyChanged(oldSettings, &newSettings) upstreamAPIKeysChanged := m.hasUpstreamAPIKeysChanged(oldSettings, &newSettings) if apiKeyChanged || upstreamAPIKeysChanged { if m.secretSource != nil { if ms, ok := m.secretSource.(*MappedSecretSource); ok { if apiKeyChanged { ms.UpdateDefaultExplicitKey(newSettings.UpstreamAPIKey) ms.InvalidateCache() } if upstreamAPIKeysChanged { ms.UpdateMappings(newSettings.UpstreamAPIKeys) } } else if ms, ok := m.secretSource.(*MultiSourceSecret); ok { ms.UpdateExplicitKey(newSettings.UpstreamAPIKey) ms.InvalidateCache() } } }
}
// Store current config for next comparison m.configMu.Lock() settingsCopy := newSettings // copy struct m.lastConfig = &settingsCopy m.configMu.Unlock()
return nil}
func (m *AmpModule) enableUpstreamProxy(upstreamURL string, settings *config.AmpCode) error { if m.secretSource == nil { // Create MultiSourceSecret as the default source, then wrap with MappedSecretSource defaultSource := NewMultiSourceSecret(settings.UpstreamAPIKey, 0 /* default 5min */) mappedSource := NewMappedSecretSource(defaultSource) mappedSource.UpdateMappings(settings.UpstreamAPIKeys) m.secretSource = mappedSource } else if ms, ok := m.secretSource.(*MappedSecretSource); ok { ms.UpdateDefaultExplicitKey(settings.UpstreamAPIKey) ms.InvalidateCache() ms.UpdateMappings(settings.UpstreamAPIKeys) } else if ms, ok := m.secretSource.(*MultiSourceSecret); ok { // Legacy path: wrap existing MultiSourceSecret with MappedSecretSource ms.UpdateExplicitKey(settings.UpstreamAPIKey) ms.InvalidateCache() mappedSource := NewMappedSecretSource(ms) mappedSource.UpdateMappings(settings.UpstreamAPIKeys) m.secretSource = mappedSource }
proxy, err := createReverseProxy(upstreamURL, m.secretSource) if err != nil { return err }
m.setProxy(proxy) m.enabled = true
log.Infof("amp upstream proxy enabled for: %s", upstreamURL) return nil}
// hasModelMappingsChanged compares old and new model mappings.func (m *AmpModule) hasModelMappingsChanged(old *config.AmpCode, new *config.AmpCode) bool { if old == nil { return len(new.ModelMappings) > 0 }
if len(old.ModelMappings) != len(new.ModelMappings) { return true }
// Build map for efficient and robust comparison type mappingInfo struct { to string regex bool } oldMap := make(map[string]mappingInfo, len(old.ModelMappings)) for _, mapping := range old.ModelMappings { oldMap[strings.TrimSpace(mapping.From)] = mappingInfo{ to: strings.TrimSpace(mapping.To), regex: mapping.Regex, } }
for _, mapping := range new.ModelMappings { from := strings.TrimSpace(mapping.From) to := strings.TrimSpace(mapping.To) if oldVal, exists := oldMap[from]; !exists || oldVal.to != to || oldVal.regex != mapping.Regex { return true } }
return false}
// hasAPIKeyChanged compares old and new API keys.func (m *AmpModule) hasAPIKeyChanged(old *config.AmpCode, new *config.AmpCode) bool { oldKey := "" if old != nil { oldKey = strings.TrimSpace(old.UpstreamAPIKey) } newKey := strings.TrimSpace(new.UpstreamAPIKey) return oldKey != newKey}
// hasUpstreamAPIKeysChanged compares old and new per-client upstream API key mappings.func (m *AmpModule) hasUpstreamAPIKeysChanged(old *config.AmpCode, new *config.AmpCode) bool { if old == nil { return len(new.UpstreamAPIKeys) > 0 }
if len(old.UpstreamAPIKeys) != len(new.UpstreamAPIKeys) { return true }
// Build map for comparison: upstreamKey -> set of clientKeys type entryInfo struct { upstreamKey string clientKeys map[string]struct{} } oldEntries := make([]entryInfo, len(old.UpstreamAPIKeys)) for i, entry := range old.UpstreamAPIKeys { clientKeys := make(map[string]struct{}, len(entry.APIKeys)) for _, k := range entry.APIKeys { trimmed := strings.TrimSpace(k) if trimmed == "" { continue } clientKeys[trimmed] = struct{}{} } oldEntries[i] = entryInfo{ upstreamKey: strings.TrimSpace(entry.UpstreamAPIKey), clientKeys: clientKeys, } }
for i, newEntry := range new.UpstreamAPIKeys { if i >= len(oldEntries) { return true } oldE := oldEntries[i] if strings.TrimSpace(newEntry.UpstreamAPIKey) != oldE.upstreamKey { return true } newKeys := make(map[string]struct{}, len(newEntry.APIKeys)) for _, k := range newEntry.APIKeys { trimmed := strings.TrimSpace(k) if trimmed == "" { continue } newKeys[trimmed] = struct{}{} } if len(newKeys) != len(oldE.clientKeys) { return true } for k := range newKeys { if _, ok := oldE.clientKeys[k]; !ok { return true } } }
return false}
// GetModelMapper returns the model mapper instance (for testing/debugging).func (m *AmpModule) GetModelMapper() *DefaultModelMapper { return m.modelMapper}
// getProxy returns the current proxy instance (thread-safe for hot-reload).func (m *AmpModule) getProxy() *httputil.ReverseProxy { m.proxyMu.RLock() defer m.proxyMu.RUnlock() return m.proxy}
// setProxy updates the proxy instance (thread-safe for hot-reload).func (m *AmpModule) setProxy(proxy *httputil.ReverseProxy) { m.proxyMu.Lock() defer m.proxyMu.Unlock() m.proxy = proxy}
// IsRestrictedToLocalhost returns whether management routes are restricted to localhost.func (m *AmpModule) IsRestrictedToLocalhost() bool { m.restrictMu.RLock() defer m.restrictMu.RUnlock() return m.restrictToLocalhost}
// setRestrictToLocalhost updates the localhost restriction setting.func (m *AmpModule) setRestrictToLocalhost(restrict bool) { m.restrictMu.Lock() defer m.restrictMu.Unlock() m.restrictToLocalhost = restrict}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352package amp
import ( "context" "net/http/httptest" "os" "path/filepath" "testing" "time"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/api/modules" "github.com/router-for-me/CLIProxyAPI/v6/internal/config" sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access" "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers")
func TestAmpModule_Name(t *testing.T) { m := New() if m.Name() != "amp-routing" { t.Fatalf("want amp-routing, got %s", m.Name()) }}
func TestAmpModule_New(t *testing.T) { accessManager := sdkaccess.NewManager() authMiddleware := func(c *gin.Context) { c.Next() }
m := NewLegacy(accessManager, authMiddleware)
if m.accessManager != accessManager { t.Fatal("accessManager not set") } if m.authMiddleware_ == nil { t.Fatal("authMiddleware not set") } if m.enabled { t.Fatal("enabled should be false initially") } if m.proxy != nil { t.Fatal("proxy should be nil initially") }}
func TestAmpModule_Register_WithUpstream(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New()
// Fake upstream to ensure URL is valid upstream := httptest.NewServer(nil) defer upstream.Close()
accessManager := sdkaccess.NewManager() base := &handlers.BaseAPIHandler{}
m := NewLegacy(accessManager, func(c *gin.Context) { c.Next() })
cfg := &config.Config{ AmpCode: config.AmpCode{ UpstreamURL: upstream.URL, UpstreamAPIKey: "test-key", }, }
ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }} if err := m.Register(ctx); err != nil { t.Fatalf("register error: %v", err) }
if !m.enabled { t.Fatal("module should be enabled with upstream URL") } if m.proxy == nil { t.Fatal("proxy should be initialized") } if m.secretSource == nil { t.Fatal("secretSource should be initialized") }}
func TestAmpModule_Register_WithoutUpstream(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New()
accessManager := sdkaccess.NewManager() base := &handlers.BaseAPIHandler{}
m := NewLegacy(accessManager, func(c *gin.Context) { c.Next() })
cfg := &config.Config{ AmpCode: config.AmpCode{ UpstreamURL: "", // No upstream }, }
ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }} if err := m.Register(ctx); err != nil { t.Fatalf("register should not error without upstream: %v", err) }
if m.enabled { t.Fatal("module should be disabled without upstream URL") } if m.proxy != nil { t.Fatal("proxy should not be initialized without upstream") }
// But provider aliases should still be registered req := httptest.NewRequest("GET", "/api/provider/openai/models", nil) w := httptest.NewRecorder() r.ServeHTTP(w, req)
if w.Code == 404 { t.Fatal("provider aliases should be registered even without upstream") }}
func TestAmpModule_Register_InvalidUpstream(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New()
accessManager := sdkaccess.NewManager() base := &handlers.BaseAPIHandler{}
m := NewLegacy(accessManager, func(c *gin.Context) { c.Next() })
cfg := &config.Config{ AmpCode: config.AmpCode{ UpstreamURL: "://invalid-url", }, }
ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }} if err := m.Register(ctx); err == nil { t.Fatal("expected error for invalid upstream URL") }}
func TestAmpModule_OnConfigUpdated_CacheInvalidation(t *testing.T) { tmpDir := t.TempDir() p := filepath.Join(tmpDir, "secrets.json") if err := os.WriteFile(p, []byte(`{"apiKey@https://ampcode.com/":"v1"}`), 0600); err != nil { t.Fatal(err) }
m := &AmpModule{enabled: true} ms := NewMultiSourceSecretWithPath("", p, time.Minute) m.secretSource = ms m.lastConfig = &config.AmpCode{ UpstreamAPIKey: "old-key", }
// Warm the cache if _, err := ms.Get(context.Background()); err != nil { t.Fatal(err) }
if ms.cache == nil { t.Fatal("expected cache to be set") }
// Update config - should invalidate cache if err := m.OnConfigUpdated(&config.Config{AmpCode: config.AmpCode{UpstreamURL: "http://x", UpstreamAPIKey: "new-key"}}); err != nil { t.Fatal(err) }
if ms.cache != nil { t.Fatal("expected cache to be invalidated") }}
func TestAmpModule_OnConfigUpdated_NotEnabled(t *testing.T) { m := &AmpModule{enabled: false}
// Should not error or panic when disabled if err := m.OnConfigUpdated(&config.Config{}); err != nil { t.Fatalf("unexpected error: %v", err) }}
func TestAmpModule_OnConfigUpdated_URLRemoved(t *testing.T) { m := &AmpModule{enabled: true} ms := NewMultiSourceSecret("", 0) m.secretSource = ms
// Config update with empty URL - should log warning but not error cfg := &config.Config{AmpCode: config.AmpCode{UpstreamURL: ""}}
if err := m.OnConfigUpdated(cfg); err != nil { t.Fatalf("unexpected error: %v", err) }}
func TestAmpModule_OnConfigUpdated_NonMultiSourceSecret(t *testing.T) { // Test that OnConfigUpdated doesn't panic with StaticSecretSource m := &AmpModule{enabled: true} m.secretSource = NewStaticSecretSource("static-key")
cfg := &config.Config{AmpCode: config.AmpCode{UpstreamURL: "http://example.com"}}
// Should not error or panic if err := m.OnConfigUpdated(cfg); err != nil { t.Fatalf("unexpected error: %v", err) }}
func TestAmpModule_AuthMiddleware_Fallback(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New()
// Create module with no auth middleware m := &AmpModule{authMiddleware_: nil}
// Get the fallback middleware via getAuthMiddleware ctx := modules.Context{Engine: r, AuthMiddleware: nil} middleware := m.getAuthMiddleware(ctx)
if middleware == nil { t.Fatal("getAuthMiddleware should return a fallback, not nil") }
// Test that it works called := false r.GET("/test", middleware, func(c *gin.Context) { called = true c.String(200, "ok") })
req := httptest.NewRequest("GET", "/test", nil) w := httptest.NewRecorder() r.ServeHTTP(w, req)
if !called { t.Fatal("fallback middleware should allow requests through") }}
func TestAmpModule_SecretSource_FromConfig(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New()
upstream := httptest.NewServer(nil) defer upstream.Close()
accessManager := sdkaccess.NewManager() base := &handlers.BaseAPIHandler{}
m := NewLegacy(accessManager, func(c *gin.Context) { c.Next() })
// Config with explicit API key cfg := &config.Config{ AmpCode: config.AmpCode{ UpstreamURL: upstream.URL, UpstreamAPIKey: "config-key", }, }
ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }} if err := m.Register(ctx); err != nil { t.Fatalf("register error: %v", err) }
// Secret source should be MultiSourceSecret with config key if m.secretSource == nil { t.Fatal("secretSource should be set") }
// Verify it returns the config key key, err := m.secretSource.Get(context.Background()) if err != nil { t.Fatalf("Get error: %v", err) } if key != "config-key" { t.Fatalf("want config-key, got %s", key) }}
func TestAmpModule_ProviderAliasesAlwaysRegistered(t *testing.T) { gin.SetMode(gin.TestMode)
scenarios := []struct { name string configURL string }{ {"with_upstream", "http://example.com"}, {"without_upstream", ""}, }
for _, scenario := range scenarios { t.Run(scenario.name, func(t *testing.T) { r := gin.New() accessManager := sdkaccess.NewManager() base := &handlers.BaseAPIHandler{}
m := NewLegacy(accessManager, func(c *gin.Context) { c.Next() })
cfg := &config.Config{AmpCode: config.AmpCode{UpstreamURL: scenario.configURL}}
ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }} if err := m.Register(ctx); err != nil && scenario.configURL != "" { t.Fatalf("register error: %v", err) }
// Provider aliases should always be available req := httptest.NewRequest("GET", "/api/provider/openai/models", nil) w := httptest.NewRecorder() r.ServeHTTP(w, req)
if w.Code == 404 { t.Fatal("provider aliases should be registered") } }) }}
func TestAmpModule_hasUpstreamAPIKeysChanged_DetectsRemovedKeyWithDuplicateInput(t *testing.T) { m := &AmpModule{}
oldCfg := &config.AmpCode{ UpstreamAPIKeys: []config.AmpUpstreamAPIKeyEntry{ {UpstreamAPIKey: "u1", APIKeys: []string{"k1", "k2"}}, }, } newCfg := &config.AmpCode{ UpstreamAPIKeys: []config.AmpUpstreamAPIKeyEntry{ {UpstreamAPIKey: "u1", APIKeys: []string{"k1", "k1"}}, }, }
if !m.hasUpstreamAPIKeysChanged(oldCfg, newCfg) { t.Fatal("expected change to be detected when k2 is removed but new list contains duplicates") }}
func TestAmpModule_hasUpstreamAPIKeysChanged_IgnoresEmptyAndWhitespaceKeys(t *testing.T) { m := &AmpModule{}
oldCfg := &config.AmpCode{ UpstreamAPIKeys: []config.AmpUpstreamAPIKeyEntry{ {UpstreamAPIKey: "u1", APIKeys: []string{"k1", "k2"}}, }, } newCfg := &config.AmpCode{ UpstreamAPIKeys: []config.AmpUpstreamAPIKeyEntry{ {UpstreamAPIKey: "u1", APIKeys: []string{" k1 ", "", "k2", " "}}, }, }
if m.hasUpstreamAPIKeysChanged(oldCfg, newCfg) { t.Fatal("expected no change when only whitespace/empty entries differ") }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329package amp
import ( "bytes" "io" "net/http/httputil" "strings" "time"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/util" log "github.com/sirupsen/logrus" "github.com/tidwall/gjson" "github.com/tidwall/sjson")
// AmpRouteType represents the type of routing decision made for an Amp requesttype AmpRouteType string
const ( // RouteTypeLocalProvider indicates the request is handled by a local OAuth provider (free) RouteTypeLocalProvider AmpRouteType = "LOCAL_PROVIDER" // RouteTypeModelMapping indicates the request was remapped to another available model (free) RouteTypeModelMapping AmpRouteType = "MODEL_MAPPING" // RouteTypeAmpCredits indicates the request is forwarded to ampcode.com (uses Amp credits) RouteTypeAmpCredits AmpRouteType = "AMP_CREDITS" // RouteTypeNoProvider indicates no provider or fallback available RouteTypeNoProvider AmpRouteType = "NO_PROVIDER")
// MappedModelContextKey is the Gin context key for passing mapped model names.const MappedModelContextKey = "mapped_model"
// logAmpRouting logs the routing decision for an Amp request with structured fieldsfunc logAmpRouting(routeType AmpRouteType, requestedModel, resolvedModel, provider, path string) { fields := log.Fields{ "component": "amp-routing", "route_type": string(routeType), "requested_model": requestedModel, "path": path, "timestamp": time.Now().Format(time.RFC3339), }
if resolvedModel != "" && resolvedModel != requestedModel { fields["resolved_model"] = resolvedModel } if provider != "" { fields["provider"] = provider }
switch routeType { case RouteTypeLocalProvider: fields["cost"] = "free" fields["source"] = "local_oauth" log.WithFields(fields).Debugf("amp using local provider for model: %s", requestedModel)
case RouteTypeModelMapping: fields["cost"] = "free" fields["source"] = "local_oauth" fields["mapping"] = requestedModel + " -> " + resolvedModel // model mapping already logged in mapper; avoid duplicate here
case RouteTypeAmpCredits: fields["cost"] = "amp_credits" fields["source"] = "ampcode.com" fields["model_id"] = requestedModel // Explicit model_id for easy config reference log.WithFields(fields).Warnf("forwarding to ampcode.com (uses amp credits) - model_id: %s | To use local provider, add to config: ampcode.model-mappings: [{from: \"%s\", to: \"<your-local-model>\"}]", requestedModel, requestedModel)
case RouteTypeNoProvider: fields["cost"] = "none" fields["source"] = "error" fields["model_id"] = requestedModel // Explicit model_id for easy config reference log.WithFields(fields).Warnf("no provider available for model_id: %s", requestedModel) }}
// FallbackHandler wraps a standard handler with fallback logic to ampcode.com// when the model's provider is not available in CLIProxyAPItype FallbackHandler struct { getProxy func() *httputil.ReverseProxy modelMapper ModelMapper forceModelMappings func() bool}
// NewFallbackHandler creates a new fallback handler wrapper// The getProxy function allows lazy evaluation of the proxy (useful when proxy is created after routes)func NewFallbackHandler(getProxy func() *httputil.ReverseProxy) *FallbackHandler { return &FallbackHandler{ getProxy: getProxy, forceModelMappings: func() bool { return false }, }}
// NewFallbackHandlerWithMapper creates a new fallback handler with model mapping supportfunc NewFallbackHandlerWithMapper(getProxy func() *httputil.ReverseProxy, mapper ModelMapper, forceModelMappings func() bool) *FallbackHandler { if forceModelMappings == nil { forceModelMappings = func() bool { return false } } return &FallbackHandler{ getProxy: getProxy, modelMapper: mapper, forceModelMappings: forceModelMappings, }}
// SetModelMapper sets the model mapper for this handler (allows late binding)func (fh *FallbackHandler) SetModelMapper(mapper ModelMapper) { fh.modelMapper = mapper}
// WrapHandler wraps a gin.HandlerFunc with fallback logic// If the model's provider is not configured in CLIProxyAPI, it forwards to ampcode.comfunc (fh *FallbackHandler) WrapHandler(handler gin.HandlerFunc) gin.HandlerFunc { return func(c *gin.Context) { requestPath := c.Request.URL.Path
// Read the request body to extract the model name bodyBytes, err := io.ReadAll(c.Request.Body) if err != nil { log.Errorf("amp fallback: failed to read request body: %v", err) handler(c) return }
// Restore the body for the handler to read c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
// Try to extract model from request body or URL path (for Gemini) modelName := extractModelFromRequest(bodyBytes, c) if modelName == "" { // Can't determine model, proceed with normal handler handler(c) return }
// Normalize model (handles dynamic thinking suffixes) normalizedModel, thinkingMetadata := util.NormalizeThinkingModel(modelName) thinkingSuffix := "" if thinkingMetadata != nil && strings.HasPrefix(modelName, normalizedModel) { thinkingSuffix = modelName[len(normalizedModel):] }
resolveMappedModel := func() (string, []string) { if fh.modelMapper == nil { return "", nil }
mappedModel := fh.modelMapper.MapModel(modelName) if mappedModel == "" { mappedModel = fh.modelMapper.MapModel(normalizedModel) } mappedModel = strings.TrimSpace(mappedModel) if mappedModel == "" { return "", nil }
// Preserve dynamic thinking suffix (e.g. "(xhigh)") when mapping applies, unless the target // already specifies its own thinking suffix. if thinkingSuffix != "" { _, mappedThinkingMetadata := util.NormalizeThinkingModel(mappedModel) if mappedThinkingMetadata == nil { mappedModel += thinkingSuffix } }
mappedBaseModel, _ := util.NormalizeThinkingModel(mappedModel) mappedProviders := util.GetProviderName(mappedBaseModel) if len(mappedProviders) == 0 { return "", nil }
return mappedModel, mappedProviders }
// Track resolved model for logging (may change if mapping is applied) resolvedModel := normalizedModel usedMapping := false var providers []string
// Check if model mappings should be forced ahead of local API keys forceMappings := fh.forceModelMappings != nil && fh.forceModelMappings()
if forceMappings { // FORCE MODE: Check model mappings FIRST (takes precedence over local API keys) // This allows users to route Amp requests to their preferred OAuth providers if mappedModel, mappedProviders := resolveMappedModel(); mappedModel != "" { // Mapping found and provider available - rewrite the model in request body bodyBytes = rewriteModelInRequest(bodyBytes, mappedModel) c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes)) // Store mapped model in context for handlers that check it (like gemini bridge) c.Set(MappedModelContextKey, mappedModel) resolvedModel = mappedModel usedMapping = true providers = mappedProviders }
// If no mapping applied, check for local providers if !usedMapping { providers = util.GetProviderName(normalizedModel) } } else { // DEFAULT MODE: Check local providers first, then mappings as fallback providers = util.GetProviderName(normalizedModel)
if len(providers) == 0 { // No providers configured - check if we have a model mapping if mappedModel, mappedProviders := resolveMappedModel(); mappedModel != "" { // Mapping found and provider available - rewrite the model in request body bodyBytes = rewriteModelInRequest(bodyBytes, mappedModel) c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes)) // Store mapped model in context for handlers that check it (like gemini bridge) c.Set(MappedModelContextKey, mappedModel) resolvedModel = mappedModel usedMapping = true providers = mappedProviders } } }
// If no providers available, fallback to ampcode.com if len(providers) == 0 { proxy := fh.getProxy() if proxy != nil { // Log: Forwarding to ampcode.com (uses Amp credits) logAmpRouting(RouteTypeAmpCredits, modelName, "", "", requestPath)
// Restore body again for the proxy c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
// Forward to ampcode.com proxy.ServeHTTP(c.Writer, c.Request) return }
// No proxy available, let the normal handler return the error logAmpRouting(RouteTypeNoProvider, modelName, "", "", requestPath) }
// Log the routing decision providerName := "" if len(providers) > 0 { providerName = providers[0] }
if usedMapping { // Log: Model was mapped to another model log.Debugf("amp model mapping: request %s -> %s", normalizedModel, resolvedModel) logAmpRouting(RouteTypeModelMapping, modelName, resolvedModel, providerName, requestPath) rewriter := NewResponseRewriter(c.Writer, modelName) c.Writer = rewriter // Filter Anthropic-Beta header only for local handling paths filterAntropicBetaHeader(c) c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes)) handler(c) rewriter.Flush() log.Debugf("amp model mapping: response %s -> %s", resolvedModel, modelName) } else if len(providers) > 0 { // Log: Using local provider (free) logAmpRouting(RouteTypeLocalProvider, modelName, resolvedModel, providerName, requestPath) // Filter Anthropic-Beta header only for local handling paths filterAntropicBetaHeader(c) c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes)) handler(c) } else { // No provider, no mapping, no proxy: fall back to the wrapped handler so it can return an error response c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes)) handler(c) } }}
// filterAntropicBetaHeader filters Anthropic-Beta header to remove features requiring special subscription// This is needed when using local providers (bypassing the Amp proxy)func filterAntropicBetaHeader(c *gin.Context) { if betaHeader := c.Request.Header.Get("Anthropic-Beta"); betaHeader != "" { if filtered := filterBetaFeatures(betaHeader, "context-1m-2025-08-07"); filtered != "" { c.Request.Header.Set("Anthropic-Beta", filtered) } else { c.Request.Header.Del("Anthropic-Beta") } }}
// rewriteModelInRequest replaces the model name in a JSON request bodyfunc rewriteModelInRequest(body []byte, newModel string) []byte { if !gjson.GetBytes(body, "model").Exists() { return body } result, err := sjson.SetBytes(body, "model", newModel) if err != nil { log.Warnf("amp model mapping: failed to rewrite model in request body: %v", err) return body } return result}
// extractModelFromRequest attempts to extract the model name from various request formatsfunc extractModelFromRequest(body []byte, c *gin.Context) string { // First try to parse from JSON body (OpenAI, Claude, etc.) // Check common model field names if result := gjson.GetBytes(body, "model"); result.Exists() && result.Type == gjson.String { return result.String() }
// For Gemini requests, model is in the URL path // Standard format: /models/{model}:generateContent -> :action parameter if action := c.Param("action"); action != "" { // Split by colon to get model name (e.g., "gemini-pro:generateContent" -> "gemini-pro") parts := strings.Split(action, ":") if len(parts) > 0 && parts[0] != "" { return parts[0] } }
// AMP CLI format: /publishers/google/models/{model}:method -> *path parameter // Example: /publishers/google/models/gemini-3-pro-preview:streamGenerateContent if path := c.Param("path"); path != "" { // Look for /models/{model}:method pattern if idx := strings.Index(path, "/models/"); idx >= 0 { modelPart := path[idx+8:] // Skip "/models/" // Split by colon to get model name if colonIdx := strings.Index(modelPart, ":"); colonIdx > 0 { return modelPart[:colonIdx] } } }
return ""}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273package amp
import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "net/http/httputil" "testing"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/config" "github.com/router-for-me/CLIProxyAPI/v6/internal/registry")
func TestFallbackHandler_ModelMapping_PreservesThinkingSuffixAndRewritesResponse(t *testing.T) { gin.SetMode(gin.TestMode)
reg := registry.GetGlobalRegistry() reg.RegisterClient("test-client-amp-fallback", "codex", []*registry.ModelInfo{ {ID: "test/gpt-5.2", OwnedBy: "openai", Type: "codex"}, }) defer reg.UnregisterClient("test-client-amp-fallback")
mapper := NewModelMapper([]config.AmpModelMapping{ {From: "gpt-5.2", To: "test/gpt-5.2"}, })
fallback := NewFallbackHandlerWithMapper(func() *httputil.ReverseProxy { return nil }, mapper, nil)
handler := func(c *gin.Context) { var req struct { Model string `json:"model"` } if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return }
c.JSON(http.StatusOK, gin.H{ "model": req.Model, "seen_model": req.Model, }) }
r := gin.New() r.POST("/chat/completions", fallback.WrapHandler(handler))
reqBody := []byte(`{"model":"gpt-5.2(xhigh)"}`) req := httptest.NewRequest(http.MethodPost, "/chat/completions", bytes.NewReader(reqBody)) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() r.ServeHTTP(w, req)
if w.Code != http.StatusOK { t.Fatalf("Expected status 200, got %d", w.Code) }
var resp struct { Model string `json:"model"` SeenModel string `json:"seen_model"` } if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { t.Fatalf("Failed to parse response JSON: %v", err) }
if resp.Model != "gpt-5.2(xhigh)" { t.Errorf("Expected response model gpt-5.2(xhigh), got %s", resp.Model) } if resp.SeenModel != "test/gpt-5.2(xhigh)" { t.Errorf("Expected handler to see test/gpt-5.2(xhigh), got %s", resp.SeenModel) }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859package amp
import ( "strings"
"github.com/gin-gonic/gin")
// createGeminiBridgeHandler creates a handler that bridges AMP CLI's non-standard Gemini paths// to our standard Gemini handler by rewriting the request context.//// AMP CLI format: /publishers/google/models/gemini-3-pro-preview:streamGenerateContent// Standard format: /models/gemini-3-pro-preview:streamGenerateContent//// This extracts the model+method from the AMP path and sets it as the :action parameter// so the standard Gemini handler can process it.//// The handler parameter should be a Gemini-compatible handler that expects the :action param.func createGeminiBridgeHandler(handler gin.HandlerFunc) gin.HandlerFunc { return func(c *gin.Context) { // Get the full path from the catch-all parameter path := c.Param("path")
// Extract model:method from AMP CLI path format // Example: /publishers/google/models/gemini-3-pro-preview:streamGenerateContent const modelsPrefix = "/models/" if idx := strings.Index(path, modelsPrefix); idx >= 0 { // Extract everything after modelsPrefix actionPart := path[idx+len(modelsPrefix):]
// Check if model was mapped by FallbackHandler if mappedModel, exists := c.Get(MappedModelContextKey); exists { if strModel, ok := mappedModel.(string); ok && strModel != "" { // Replace the model part in the action // actionPart is like "model-name:method" if colonIdx := strings.Index(actionPart, ":"); colonIdx > 0 { method := actionPart[colonIdx:] // ":method" actionPart = strModel + method } } }
// Set this as the :action parameter that the Gemini handler expects c.Params = append(c.Params, gin.Param{ Key: "action", Value: actionPart, })
// Call the handler handler(c) return }
// If we can't parse the path, return 400 c.JSON(400, gin.H{ "error": "Invalid Gemini API path format", }) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293package amp
import ( "net/http" "net/http/httptest" "testing"
"github.com/gin-gonic/gin")
func TestCreateGeminiBridgeHandler_ActionParameterExtraction(t *testing.T) { gin.SetMode(gin.TestMode)
tests := []struct { name string path string mappedModel string // empty string means no mapping expectedAction string }{ { name: "no_mapping_uses_url_model", path: "/publishers/google/models/gemini-pro:generateContent", mappedModel: "", expectedAction: "gemini-pro:generateContent", }, { name: "mapped_model_replaces_url_model", path: "/publishers/google/models/gemini-exp:generateContent", mappedModel: "gemini-2.0-flash", expectedAction: "gemini-2.0-flash:generateContent", }, { name: "mapping_preserves_method", path: "/publishers/google/models/gemini-2.5-preview:streamGenerateContent", mappedModel: "gemini-flash", expectedAction: "gemini-flash:streamGenerateContent", }, }
for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var capturedAction string
mockGeminiHandler := func(c *gin.Context) { capturedAction = c.Param("action") c.JSON(http.StatusOK, gin.H{"captured": capturedAction}) }
// Use the actual createGeminiBridgeHandler function bridgeHandler := createGeminiBridgeHandler(mockGeminiHandler)
r := gin.New() if tt.mappedModel != "" { r.Use(func(c *gin.Context) { c.Set(MappedModelContextKey, tt.mappedModel) c.Next() }) } r.POST("/api/provider/google/v1beta1/*path", bridgeHandler)
req := httptest.NewRequest(http.MethodPost, "/api/provider/google/v1beta1"+tt.path, nil) w := httptest.NewRecorder() r.ServeHTTP(w, req)
if w.Code != http.StatusOK { t.Fatalf("Expected status 200, got %d", w.Code) } if capturedAction != tt.expectedAction { t.Errorf("Expected action '%s', got '%s'", tt.expectedAction, capturedAction) } }) }}
func TestCreateGeminiBridgeHandler_InvalidPath(t *testing.T) { gin.SetMode(gin.TestMode)
mockHandler := func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"ok": true}) } bridgeHandler := createGeminiBridgeHandler(mockHandler)
r := gin.New() r.POST("/api/provider/google/v1beta1/*path", bridgeHandler)
req := httptest.NewRequest(http.MethodPost, "/api/provider/google/v1beta1/invalid/path", nil) w := httptest.NewRecorder() r.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest { t.Errorf("Expected status 400 for invalid path, got %d", w.Code) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147// Package amp provides model mapping functionality for routing Amp CLI requests// to alternative models when the requested model is not available locally.package amp
import ( "regexp" "strings" "sync"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config" "github.com/router-for-me/CLIProxyAPI/v6/internal/util" log "github.com/sirupsen/logrus")
// ModelMapper provides model name mapping/aliasing for Amp CLI requests.// When an Amp request comes in for a model that isn't available locally,// this mapper can redirect it to an alternative model that IS available.type ModelMapper interface { // MapModel returns the target model name if a mapping exists and the target // model has available providers. Returns empty string if no mapping applies. MapModel(requestedModel string) string
// UpdateMappings refreshes the mapping configuration (for hot-reload). UpdateMappings(mappings []config.AmpModelMapping)}
// DefaultModelMapper implements ModelMapper with thread-safe mapping storage.type DefaultModelMapper struct { mu sync.RWMutex mappings map[string]string // exact: from -> to (normalized lowercase keys) regexps []regexMapping // regex rules evaluated in order}
// NewModelMapper creates a new model mapper with the given initial mappings.func NewModelMapper(mappings []config.AmpModelMapping) *DefaultModelMapper { m := &DefaultModelMapper{ mappings: make(map[string]string), regexps: nil, } m.UpdateMappings(mappings) return m}
// MapModel checks if a mapping exists for the requested model and if the// target model has available local providers. Returns the mapped model name// or empty string if no valid mapping exists.func (m *DefaultModelMapper) MapModel(requestedModel string) string { if requestedModel == "" { return "" }
m.mu.RLock() defer m.mu.RUnlock()
// Normalize the requested model for lookup normalizedRequest := strings.ToLower(strings.TrimSpace(requestedModel))
// Check for direct mapping targetModel, exists := m.mappings[normalizedRequest] if !exists { // Try regex mappings in order base, _ := util.NormalizeThinkingModel(requestedModel) for _, rm := range m.regexps { if rm.re.MatchString(requestedModel) || (base != "" && rm.re.MatchString(base)) { targetModel = rm.to exists = true break } } if !exists { return "" } }
// Verify target model has available providers normalizedTarget, _ := util.NormalizeThinkingModel(targetModel) providers := util.GetProviderName(normalizedTarget) if len(providers) == 0 { log.Debugf("amp model mapping: target model %s has no available providers, skipping mapping", targetModel) return "" }
// Note: Detailed routing log is handled by logAmpRouting in fallback_handlers.go return targetModel}
// UpdateMappings refreshes the mapping configuration from config.// This is called during initialization and on config hot-reload.func (m *DefaultModelMapper) UpdateMappings(mappings []config.AmpModelMapping) { m.mu.Lock() defer m.mu.Unlock()
// Clear and rebuild mappings m.mappings = make(map[string]string, len(mappings)) m.regexps = make([]regexMapping, 0, len(mappings))
for _, mapping := range mappings { from := strings.TrimSpace(mapping.From) to := strings.TrimSpace(mapping.To)
if from == "" || to == "" { log.Warnf("amp model mapping: skipping invalid mapping (from=%q, to=%q)", from, to) continue }
if mapping.Regex { // Compile case-insensitive regex; wrap with (?i) to match behavior of exact lookups pattern := "(?i)" + from re, err := regexp.Compile(pattern) if err != nil { log.Warnf("amp model mapping: invalid regex %q: %v", from, err) continue } m.regexps = append(m.regexps, regexMapping{re: re, to: to}) log.Debugf("amp model regex mapping registered: /%s/ -> %s", from, to) } else { // Store with normalized lowercase key for case-insensitive lookup normalizedFrom := strings.ToLower(from) m.mappings[normalizedFrom] = to log.Debugf("amp model mapping registered: %s -> %s", from, to) } }
if len(m.mappings) > 0 { log.Infof("amp model mapping: loaded %d mapping(s)", len(m.mappings)) } if n := len(m.regexps); n > 0 { log.Infof("amp model mapping: loaded %d regex mapping(s)", n) }}
// GetMappings returns a copy of current mappings (for debugging/status).func (m *DefaultModelMapper) GetMappings() map[string]string { m.mu.RLock() defer m.mu.RUnlock()
result := make(map[string]string, len(m.mappings)) for k, v := range m.mappings { result[k] = v } return result}
type regexMapping struct { re *regexp.Regexp to string}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283package amp
import ( "testing"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config" "github.com/router-for-me/CLIProxyAPI/v6/internal/registry")
func TestNewModelMapper(t *testing.T) { mappings := []config.AmpModelMapping{ {From: "claude-opus-4.5", To: "claude-sonnet-4"}, {From: "gpt-5", To: "gemini-2.5-pro"}, }
mapper := NewModelMapper(mappings) if mapper == nil { t.Fatal("Expected non-nil mapper") }
result := mapper.GetMappings() if len(result) != 2 { t.Errorf("Expected 2 mappings, got %d", len(result)) }}
func TestNewModelMapper_Empty(t *testing.T) { mapper := NewModelMapper(nil) if mapper == nil { t.Fatal("Expected non-nil mapper") }
result := mapper.GetMappings() if len(result) != 0 { t.Errorf("Expected 0 mappings, got %d", len(result)) }}
func TestModelMapper_MapModel_NoProvider(t *testing.T) { mappings := []config.AmpModelMapping{ {From: "claude-opus-4.5", To: "claude-sonnet-4"}, }
mapper := NewModelMapper(mappings)
// Without a registered provider for the target, mapping should return empty result := mapper.MapModel("claude-opus-4.5") if result != "" { t.Errorf("Expected empty result when target has no provider, got %s", result) }}
func TestModelMapper_MapModel_WithProvider(t *testing.T) { // Register a mock provider for the target model reg := registry.GetGlobalRegistry() reg.RegisterClient("test-client", "claude", []*registry.ModelInfo{ {ID: "claude-sonnet-4", OwnedBy: "anthropic", Type: "claude"}, }) defer reg.UnregisterClient("test-client")
mappings := []config.AmpModelMapping{ {From: "claude-opus-4.5", To: "claude-sonnet-4"}, }
mapper := NewModelMapper(mappings)
// With a registered provider, mapping should work result := mapper.MapModel("claude-opus-4.5") if result != "claude-sonnet-4" { t.Errorf("Expected claude-sonnet-4, got %s", result) }}
func TestModelMapper_MapModel_TargetWithThinkingSuffix(t *testing.T) { reg := registry.GetGlobalRegistry() reg.RegisterClient("test-client-thinking", "codex", []*registry.ModelInfo{ {ID: "gpt-5.2", OwnedBy: "openai", Type: "codex"}, }) defer reg.UnregisterClient("test-client-thinking")
mappings := []config.AmpModelMapping{ {From: "gpt-5.2-alias", To: "gpt-5.2(xhigh)"}, }
mapper := NewModelMapper(mappings)
result := mapper.MapModel("gpt-5.2-alias") if result != "gpt-5.2(xhigh)" { t.Errorf("Expected gpt-5.2(xhigh), got %s", result) }}
func TestModelMapper_MapModel_CaseInsensitive(t *testing.T) { reg := registry.GetGlobalRegistry() reg.RegisterClient("test-client2", "claude", []*registry.ModelInfo{ {ID: "claude-sonnet-4", OwnedBy: "anthropic", Type: "claude"}, }) defer reg.UnregisterClient("test-client2")
mappings := []config.AmpModelMapping{ {From: "Claude-Opus-4.5", To: "claude-sonnet-4"}, }
mapper := NewModelMapper(mappings)
// Should match case-insensitively result := mapper.MapModel("claude-opus-4.5") if result != "claude-sonnet-4" { t.Errorf("Expected claude-sonnet-4, got %s", result) }}
func TestModelMapper_MapModel_NotFound(t *testing.T) { mappings := []config.AmpModelMapping{ {From: "claude-opus-4.5", To: "claude-sonnet-4"}, }
mapper := NewModelMapper(mappings)
// Unknown model should return empty result := mapper.MapModel("unknown-model") if result != "" { t.Errorf("Expected empty for unknown model, got %s", result) }}
func TestModelMapper_MapModel_EmptyInput(t *testing.T) { mappings := []config.AmpModelMapping{ {From: "claude-opus-4.5", To: "claude-sonnet-4"}, }
mapper := NewModelMapper(mappings)
result := mapper.MapModel("") if result != "" { t.Errorf("Expected empty for empty input, got %s", result) }}
func TestModelMapper_UpdateMappings(t *testing.T) { mapper := NewModelMapper(nil)
// Initially empty if len(mapper.GetMappings()) != 0 { t.Error("Expected 0 initial mappings") }
// Update with new mappings mapper.UpdateMappings([]config.AmpModelMapping{ {From: "model-a", To: "model-b"}, {From: "model-c", To: "model-d"}, })
result := mapper.GetMappings() if len(result) != 2 { t.Errorf("Expected 2 mappings after update, got %d", len(result)) }
// Update again should replace, not append mapper.UpdateMappings([]config.AmpModelMapping{ {From: "model-x", To: "model-y"}, })
result = mapper.GetMappings() if len(result) != 1 { t.Errorf("Expected 1 mapping after second update, got %d", len(result)) }}
func TestModelMapper_UpdateMappings_SkipsInvalid(t *testing.T) { mapper := NewModelMapper(nil)
mapper.UpdateMappings([]config.AmpModelMapping{ {From: "", To: "model-b"}, // Invalid: empty from {From: "model-a", To: ""}, // Invalid: empty to {From: " ", To: "model-b"}, // Invalid: whitespace from {From: "model-c", To: "model-d"}, // Valid })
result := mapper.GetMappings() if len(result) != 1 { t.Errorf("Expected 1 valid mapping, got %d", len(result)) }}
func TestModelMapper_GetMappings_ReturnsCopy(t *testing.T) { mappings := []config.AmpModelMapping{ {From: "model-a", To: "model-b"}, }
mapper := NewModelMapper(mappings)
// Get mappings and modify the returned map result := mapper.GetMappings() result["new-key"] = "new-value"
// Original should be unchanged original := mapper.GetMappings() if len(original) != 1 { t.Errorf("Expected original to have 1 mapping, got %d", len(original)) } if _, exists := original["new-key"]; exists { t.Error("Original map was modified") }}
func TestModelMapper_Regex_MatchBaseWithoutParens(t *testing.T) { reg := registry.GetGlobalRegistry() reg.RegisterClient("test-client-regex-1", "gemini", []*registry.ModelInfo{ {ID: "gemini-2.5-pro", OwnedBy: "google", Type: "gemini"}, }) defer reg.UnregisterClient("test-client-regex-1")
mappings := []config.AmpModelMapping{ {From: "^gpt-5$", To: "gemini-2.5-pro", Regex: true}, }
mapper := NewModelMapper(mappings)
// Incoming model has reasoning suffix but should match base via regex result := mapper.MapModel("gpt-5(high)") if result != "gemini-2.5-pro" { t.Errorf("Expected gemini-2.5-pro, got %s", result) }}
func TestModelMapper_Regex_ExactPrecedence(t *testing.T) { reg := registry.GetGlobalRegistry() reg.RegisterClient("test-client-regex-2", "claude", []*registry.ModelInfo{ {ID: "claude-sonnet-4", OwnedBy: "anthropic", Type: "claude"}, }) reg.RegisterClient("test-client-regex-3", "gemini", []*registry.ModelInfo{ {ID: "gemini-2.5-pro", OwnedBy: "google", Type: "gemini"}, }) defer reg.UnregisterClient("test-client-regex-2") defer reg.UnregisterClient("test-client-regex-3")
mappings := []config.AmpModelMapping{ {From: "gpt-5", To: "claude-sonnet-4"}, // exact {From: "^gpt-5.*$", To: "gemini-2.5-pro", Regex: true}, // regex }
mapper := NewModelMapper(mappings)
// Exact match should win over regex result := mapper.MapModel("gpt-5") if result != "claude-sonnet-4" { t.Errorf("Expected claude-sonnet-4, got %s", result) }}
func TestModelMapper_Regex_InvalidPattern_Skipped(t *testing.T) { // Invalid regex should be skipped and not cause panic mappings := []config.AmpModelMapping{ {From: "(", To: "target", Regex: true}, }
mapper := NewModelMapper(mappings)
result := mapper.MapModel("anything") if result != "" { t.Errorf("Expected empty result due to invalid regex, got %s", result) }}
func TestModelMapper_Regex_CaseInsensitive(t *testing.T) { reg := registry.GetGlobalRegistry() reg.RegisterClient("test-client-regex-4", "claude", []*registry.ModelInfo{ {ID: "claude-sonnet-4", OwnedBy: "anthropic", Type: "claude"}, }) defer reg.UnregisterClient("test-client-regex-4")
mappings := []config.AmpModelMapping{ {From: "^CLAUDE-OPUS-.*$", To: "claude-sonnet-4", Regex: true}, }
mapper := NewModelMapper(mappings)
result := mapper.MapModel("claude-opus-4.5") if result != "claude-sonnet-4" { t.Errorf("Expected claude-sonnet-4, got %s", result) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266package amp
import ( "bytes" "compress/gzip" "context" "errors" "fmt" "io" "net" "net/http" "net/http/httputil" "net/url" "strconv" "strings"
"github.com/gin-gonic/gin" log "github.com/sirupsen/logrus")
func removeQueryValuesMatching(req *http.Request, key string, match string) { if req == nil || req.URL == nil || match == "" { return }
q := req.URL.Query() values, ok := q[key] if !ok || len(values) == 0 { return }
kept := make([]string, 0, len(values)) for _, v := range values { if v == match { continue } kept = append(kept, v) }
if len(kept) == 0 { q.Del(key) } else { q[key] = kept } req.URL.RawQuery = q.Encode()}
// readCloser wraps a reader and forwards Close to a separate closer.// Used to restore peeked bytes while preserving upstream body Close behavior.type readCloser struct { r io.Reader c io.Closer}
func (rc *readCloser) Read(p []byte) (int, error) { return rc.r.Read(p) }func (rc *readCloser) Close() error { return rc.c.Close() }
// createReverseProxy creates a reverse proxy handler for Amp upstream// with automatic gzip decompression via ModifyResponsefunc createReverseProxy(upstreamURL string, secretSource SecretSource) (*httputil.ReverseProxy, error) { parsed, err := url.Parse(upstreamURL) if err != nil { return nil, fmt.Errorf("invalid amp upstream url: %w", err) }
proxy := httputil.NewSingleHostReverseProxy(parsed) originalDirector := proxy.Director
// Modify outgoing requests to inject API key and fix routing proxy.Director = func(req *http.Request) { originalDirector(req) req.Host = parsed.Host
// Remove client's Authorization header - it was only used for CLI Proxy API authentication // We will set our own Authorization using the configured upstream-api-key req.Header.Del("Authorization") req.Header.Del("X-Api-Key") req.Header.Del("X-Goog-Api-Key")
// Remove query-based credentials if they match the authenticated client API key. // This prevents leaking client auth material to the Amp upstream while avoiding // breaking unrelated upstream query parameters. clientKey := getClientAPIKeyFromContext(req.Context()) removeQueryValuesMatching(req, "key", clientKey) removeQueryValuesMatching(req, "auth_token", clientKey)
// Preserve correlation headers for debugging if req.Header.Get("X-Request-ID") == "" { // Could generate one here if needed }
// Note: We do NOT filter Anthropic-Beta headers in the proxy path // Users going through ampcode.com proxy are paying for the service and should get all features // including 1M context window (context-1m-2025-08-07)
// Inject API key from secret source (only uses upstream-api-key from config) if key, err := secretSource.Get(req.Context()); err == nil && key != "" { req.Header.Set("X-Api-Key", key) req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", key)) } else if err != nil { log.Warnf("amp secret source error (continuing without auth): %v", err) } }
// Modify incoming responses to handle gzip without Content-Encoding // This addresses the same issue as inline handler gzip handling, but at the proxy level proxy.ModifyResponse = func(resp *http.Response) error { // Log upstream error responses for diagnostics (502, 503, etc.) // These are NOT proxy connection errors - the upstream responded with an error status if resp.StatusCode >= 500 { log.Errorf("amp upstream responded with error [%d] for %s %s", resp.StatusCode, resp.Request.Method, resp.Request.URL.Path) } else if resp.StatusCode >= 400 { log.Warnf("amp upstream responded with client error [%d] for %s %s", resp.StatusCode, resp.Request.Method, resp.Request.URL.Path) }
// Only process successful responses for gzip decompression if resp.StatusCode < 200 || resp.StatusCode >= 300 { return nil }
// Skip if already marked as gzip (Content-Encoding set) if resp.Header.Get("Content-Encoding") != "" { return nil }
// Skip streaming responses (SSE, chunked) if isStreamingResponse(resp) { return nil }
// Save reference to original upstream body for proper cleanup originalBody := resp.Body
// Peek at first 2 bytes to detect gzip magic bytes header := make([]byte, 2) n, _ := io.ReadFull(originalBody, header)
// Check for gzip magic bytes (0x1f 0x8b) // If n < 2, we didn't get enough bytes, so it's not gzip if n >= 2 && header[0] == 0x1f && header[1] == 0x8b { // It's gzip - read the rest of the body rest, err := io.ReadAll(originalBody) if err != nil { // Restore what we read and return original body (preserve Close behavior) resp.Body = &readCloser{ r: io.MultiReader(bytes.NewReader(header[:n]), originalBody), c: originalBody, } return nil }
// Reconstruct complete gzipped data gzippedData := append(header[:n], rest...)
// Decompress gzipReader, err := gzip.NewReader(bytes.NewReader(gzippedData)) if err != nil { log.Warnf("amp proxy: gzip header detected but decompress failed: %v", err) // Close original body and return in-memory copy _ = originalBody.Close() resp.Body = io.NopCloser(bytes.NewReader(gzippedData)) return nil }
decompressed, err := io.ReadAll(gzipReader) _ = gzipReader.Close() if err != nil { log.Warnf("amp proxy: gzip decompress error: %v", err) // Close original body and return in-memory copy _ = originalBody.Close() resp.Body = io.NopCloser(bytes.NewReader(gzippedData)) return nil }
// Close original body since we're replacing with in-memory decompressed content _ = originalBody.Close()
// Replace body with decompressed content resp.Body = io.NopCloser(bytes.NewReader(decompressed)) resp.ContentLength = int64(len(decompressed))
// Update headers to reflect decompressed state resp.Header.Del("Content-Encoding") // No longer compressed resp.Header.Del("Content-Length") // Remove stale compressed length resp.Header.Set("Content-Length", strconv.FormatInt(resp.ContentLength, 10)) // Set decompressed length
log.Debugf("amp proxy: decompressed gzip response (%d -> %d bytes)", len(gzippedData), len(decompressed)) } else { // Not gzip - restore peeked bytes while preserving Close behavior // Handle edge cases: n might be 0, 1, or 2 depending on EOF resp.Body = &readCloser{ r: io.MultiReader(bytes.NewReader(header[:n]), originalBody), c: originalBody, } }
return nil }
// Error handler for proxy failures with detailed error classification for diagnostics proxy.ErrorHandler = func(rw http.ResponseWriter, req *http.Request, err error) { // Classify the error type for better diagnostics var errType string if errors.Is(err, context.DeadlineExceeded) { errType = "timeout" } else if errors.Is(err, context.Canceled) { errType = "canceled" } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() { errType = "dial_timeout" } else if _, ok := err.(net.Error); ok { errType = "network_error" } else { errType = "connection_error" }
// Don't log as error for context canceled - it's usually client closing connection if errors.Is(err, context.Canceled) { log.Debugf("amp upstream proxy [%s]: client canceled request for %s %s", errType, req.Method, req.URL.Path) } else { log.Errorf("amp upstream proxy error [%s] for %s %s: %v", errType, req.Method, req.URL.Path, err) }
rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(http.StatusBadGateway) _, _ = rw.Write([]byte(`{"error":"amp_upstream_proxy_error","message":"Failed to reach Amp upstream"}`)) }
return proxy, nil}
// isStreamingResponse detects if the response is streaming (SSE only)// Note: We only treat text/event-stream as streaming. Chunked transfer encoding// is a transport-level detail and doesn't mean we can't decompress the full response.// Many JSON APIs use chunked encoding for normal responses.func isStreamingResponse(resp *http.Response) bool { contentType := resp.Header.Get("Content-Type")
// Only Server-Sent Events are true streaming responses if strings.Contains(contentType, "text/event-stream") { return true }
return false}
// proxyHandler converts httputil.ReverseProxy to gin.HandlerFuncfunc proxyHandler(proxy *httputil.ReverseProxy) gin.HandlerFunc { return func(c *gin.Context) { proxy.ServeHTTP(c.Writer, c.Request) }}
// filterBetaFeatures removes a specific beta feature from comma-separated listfunc filterBetaFeatures(header, featureToRemove string) string { features := strings.Split(header, ",") filtered := make([]string, 0, len(features))
for _, feature := range features { trimmed := strings.TrimSpace(feature) if trimmed != "" && trimmed != featureToRemove { filtered = append(filtered, trimmed) } }
return strings.Join(filtered, ",")}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657package amp
import ( "bytes" "compress/gzip" "context" "fmt" "io" "net/http" "net/http/httptest" "strings" "testing"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config")
// Helper: compress data with gzipfunc gzipBytes(b []byte) []byte { var buf bytes.Buffer zw := gzip.NewWriter(&buf) zw.Write(b) zw.Close() return buf.Bytes()}
// Helper: create a mock http.Responsefunc mkResp(status int, hdr http.Header, body []byte) *http.Response { if hdr == nil { hdr = http.Header{} } return &http.Response{ StatusCode: status, Header: hdr, Body: io.NopCloser(bytes.NewReader(body)), ContentLength: int64(len(body)), }}
func TestCreateReverseProxy_ValidURL(t *testing.T) { proxy, err := createReverseProxy("http://example.com", NewStaticSecretSource("key")) if err != nil { t.Fatalf("expected no error, got: %v", err) } if proxy == nil { t.Fatal("expected proxy to be created") }}
func TestCreateReverseProxy_InvalidURL(t *testing.T) { _, err := createReverseProxy("://invalid", NewStaticSecretSource("key")) if err == nil { t.Fatal("expected error for invalid URL") }}
func TestModifyResponse_GzipScenarios(t *testing.T) { proxy, err := createReverseProxy("http://example.com", NewStaticSecretSource("k")) if err != nil { t.Fatal(err) }
goodJSON := []byte(`{"ok":true}`) good := gzipBytes(goodJSON) truncated := good[:10] corrupted := append([]byte{0x1f, 0x8b}, []byte("notgzip")...)
cases := []struct { name string header http.Header body []byte status int wantBody []byte wantCE string }{ { name: "decompresses_valid_gzip_no_header", header: http.Header{}, body: good, status: 200, wantBody: goodJSON, wantCE: "", }, { name: "skips_when_ce_present", header: http.Header{"Content-Encoding": []string{"gzip"}}, body: good, status: 200, wantBody: good, wantCE: "gzip", }, { name: "passes_truncated_unchanged", header: http.Header{}, body: truncated, status: 200, wantBody: truncated, wantCE: "", }, { name: "passes_corrupted_unchanged", header: http.Header{}, body: corrupted, status: 200, wantBody: corrupted, wantCE: "", }, { name: "non_gzip_unchanged", header: http.Header{}, body: []byte("plain"), status: 200, wantBody: []byte("plain"), wantCE: "", }, { name: "empty_body", header: http.Header{}, body: []byte{}, status: 200, wantBody: []byte{}, wantCE: "", }, { name: "single_byte_body", header: http.Header{}, body: []byte{0x1f}, status: 200, wantBody: []byte{0x1f}, wantCE: "", }, { name: "skips_non_2xx_status", header: http.Header{}, body: good, status: 404, wantBody: good, wantCE: "", }, }
for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { resp := mkResp(tc.status, tc.header, tc.body) if err := proxy.ModifyResponse(resp); err != nil { t.Fatalf("ModifyResponse error: %v", err) } got, err := io.ReadAll(resp.Body) if err != nil { t.Fatalf("ReadAll error: %v", err) } if !bytes.Equal(got, tc.wantBody) { t.Fatalf("body mismatch:\nwant: %q\ngot: %q", tc.wantBody, got) } if ce := resp.Header.Get("Content-Encoding"); ce != tc.wantCE { t.Fatalf("Content-Encoding: want %q, got %q", tc.wantCE, ce) } }) }}
func TestModifyResponse_UpdatesContentLengthHeader(t *testing.T) { proxy, err := createReverseProxy("http://example.com", NewStaticSecretSource("k")) if err != nil { t.Fatal(err) }
goodJSON := []byte(`{"message":"test response"}`) gzipped := gzipBytes(goodJSON)
// Simulate upstream response with gzip body AND Content-Length header // (this is the scenario the bot flagged - stale Content-Length after decompression) resp := mkResp(200, http.Header{ "Content-Length": []string{fmt.Sprintf("%d", len(gzipped))}, // Compressed size }, gzipped)
if err := proxy.ModifyResponse(resp); err != nil { t.Fatalf("ModifyResponse error: %v", err) }
// Verify body is decompressed got, _ := io.ReadAll(resp.Body) if !bytes.Equal(got, goodJSON) { t.Fatalf("body should be decompressed, got: %q, want: %q", got, goodJSON) }
// Verify Content-Length header is updated to decompressed size wantCL := fmt.Sprintf("%d", len(goodJSON)) gotCL := resp.Header.Get("Content-Length") if gotCL != wantCL { t.Fatalf("Content-Length header mismatch: want %q (decompressed), got %q", wantCL, gotCL) }
// Verify struct field also matches if resp.ContentLength != int64(len(goodJSON)) { t.Fatalf("resp.ContentLength mismatch: want %d, got %d", len(goodJSON), resp.ContentLength) }}
func TestModifyResponse_SkipsStreamingResponses(t *testing.T) { proxy, err := createReverseProxy("http://example.com", NewStaticSecretSource("k")) if err != nil { t.Fatal(err) }
goodJSON := []byte(`{"ok":true}`) gzipped := gzipBytes(goodJSON)
t.Run("sse_skips_decompression", func(t *testing.T) { resp := mkResp(200, http.Header{"Content-Type": []string{"text/event-stream"}}, gzipped) if err := proxy.ModifyResponse(resp); err != nil { t.Fatalf("ModifyResponse error: %v", err) } // SSE should NOT be decompressed got, _ := io.ReadAll(resp.Body) if !bytes.Equal(got, gzipped) { t.Fatal("SSE response should not be decompressed") } })}
func TestModifyResponse_DecompressesChunkedJSON(t *testing.T) { proxy, err := createReverseProxy("http://example.com", NewStaticSecretSource("k")) if err != nil { t.Fatal(err) }
goodJSON := []byte(`{"ok":true}`) gzipped := gzipBytes(goodJSON)
t.Run("chunked_json_decompresses", func(t *testing.T) { // Chunked JSON responses (like thread APIs) should be decompressed resp := mkResp(200, http.Header{"Transfer-Encoding": []string{"chunked"}}, gzipped) if err := proxy.ModifyResponse(resp); err != nil { t.Fatalf("ModifyResponse error: %v", err) } // Should decompress because it's not SSE got, _ := io.ReadAll(resp.Body) if !bytes.Equal(got, goodJSON) { t.Fatalf("chunked JSON should be decompressed, got: %q, want: %q", got, goodJSON) } })}
func TestReverseProxy_InjectsHeaders(t *testing.T) { gotHeaders := make(chan http.Header, 1) upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotHeaders <- r.Header.Clone() w.WriteHeader(200) w.Write([]byte(`ok`)) })) defer upstream.Close()
proxy, err := createReverseProxy(upstream.URL, NewStaticSecretSource("secret")) if err != nil { t.Fatal(err) }
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { proxy.ServeHTTP(w, r) })) defer srv.Close()
res, err := http.Get(srv.URL + "/test") if err != nil { t.Fatal(err) } res.Body.Close()
hdr := <-gotHeaders if hdr.Get("X-Api-Key") != "secret" { t.Fatalf("X-Api-Key missing or wrong, got: %q", hdr.Get("X-Api-Key")) } if hdr.Get("Authorization") != "Bearer secret" { t.Fatalf("Authorization missing or wrong, got: %q", hdr.Get("Authorization")) }}
func TestReverseProxy_EmptySecret(t *testing.T) { gotHeaders := make(chan http.Header, 1) upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotHeaders <- r.Header.Clone() w.WriteHeader(200) w.Write([]byte(`ok`)) })) defer upstream.Close()
proxy, err := createReverseProxy(upstream.URL, NewStaticSecretSource("")) if err != nil { t.Fatal(err) }
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { proxy.ServeHTTP(w, r) })) defer srv.Close()
res, err := http.Get(srv.URL + "/test") if err != nil { t.Fatal(err) } res.Body.Close()
hdr := <-gotHeaders // Should NOT inject headers when secret is empty if hdr.Get("X-Api-Key") != "" { t.Fatalf("X-Api-Key should not be set, got: %q", hdr.Get("X-Api-Key")) } if authVal := hdr.Get("Authorization"); authVal != "" && authVal != "Bearer " { t.Fatalf("Authorization should not be set, got: %q", authVal) }}
func TestReverseProxy_StripsClientCredentialsFromHeadersAndQuery(t *testing.T) { type captured struct { headers http.Header query string } got := make(chan captured, 1) upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { got <- captured{headers: r.Header.Clone(), query: r.URL.RawQuery} w.WriteHeader(200) w.Write([]byte(`ok`)) })) defer upstream.Close()
proxy, err := createReverseProxy(upstream.URL, NewStaticSecretSource("upstream")) if err != nil { t.Fatal(err) }
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Simulate clientAPIKeyMiddleware injection (per-request) ctx := context.WithValue(r.Context(), clientAPIKeyContextKey{}, "client-key") proxy.ServeHTTP(w, r.WithContext(ctx)) })) defer srv.Close()
req, err := http.NewRequest(http.MethodGet, srv.URL+"/test?key=client-key&key=keep&auth_token=client-key&foo=bar", nil) if err != nil { t.Fatal(err) } req.Header.Set("Authorization", "Bearer client-key") req.Header.Set("X-Api-Key", "client-key") req.Header.Set("X-Goog-Api-Key", "client-key")
res, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } res.Body.Close()
c := <-got
// These are client-provided credentials and must not reach the upstream. if v := c.headers.Get("X-Goog-Api-Key"); v != "" { t.Fatalf("X-Goog-Api-Key should be stripped, got: %q", v) }
// We inject upstream Authorization/X-Api-Key, so the client auth must not survive. if v := c.headers.Get("Authorization"); v != "Bearer upstream" { t.Fatalf("Authorization should be upstream-injected, got: %q", v) } if v := c.headers.Get("X-Api-Key"); v != "upstream" { t.Fatalf("X-Api-Key should be upstream-injected, got: %q", v) }
// Query-based credentials should be stripped only when they match the authenticated client key. // Should keep unrelated values and parameters. if strings.Contains(c.query, "auth_token=client-key") || strings.Contains(c.query, "key=client-key") { t.Fatalf("query credentials should be stripped, got raw query: %q", c.query) } if !strings.Contains(c.query, "key=keep") || !strings.Contains(c.query, "foo=bar") { t.Fatalf("expected query to keep non-credential params, got raw query: %q", c.query) }}
func TestReverseProxy_InjectsMappedSecret_FromRequestContext(t *testing.T) { gotHeaders := make(chan http.Header, 1) upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotHeaders <- r.Header.Clone() w.WriteHeader(200) w.Write([]byte(`ok`)) })) defer upstream.Close()
defaultSource := NewStaticSecretSource("default") mapped := NewMappedSecretSource(defaultSource) mapped.UpdateMappings([]config.AmpUpstreamAPIKeyEntry{ { UpstreamAPIKey: "u1", APIKeys: []string{"k1"}, }, })
proxy, err := createReverseProxy(upstream.URL, mapped) if err != nil { t.Fatal(err) }
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Simulate clientAPIKeyMiddleware injection (per-request) ctx := context.WithValue(r.Context(), clientAPIKeyContextKey{}, "k1") proxy.ServeHTTP(w, r.WithContext(ctx)) })) defer srv.Close()
res, err := http.Get(srv.URL + "/test") if err != nil { t.Fatal(err) } res.Body.Close()
hdr := <-gotHeaders if hdr.Get("X-Api-Key") != "u1" { t.Fatalf("X-Api-Key missing or wrong, got: %q", hdr.Get("X-Api-Key")) } if hdr.Get("Authorization") != "Bearer u1" { t.Fatalf("Authorization missing or wrong, got: %q", hdr.Get("Authorization")) }}
func TestReverseProxy_MappedSecret_FallsBackToDefault(t *testing.T) { gotHeaders := make(chan http.Header, 1) upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotHeaders <- r.Header.Clone() w.WriteHeader(200) w.Write([]byte(`ok`)) })) defer upstream.Close()
defaultSource := NewStaticSecretSource("default") mapped := NewMappedSecretSource(defaultSource) mapped.UpdateMappings([]config.AmpUpstreamAPIKeyEntry{ { UpstreamAPIKey: "u1", APIKeys: []string{"k1"}, }, })
proxy, err := createReverseProxy(upstream.URL, mapped) if err != nil { t.Fatal(err) }
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := context.WithValue(r.Context(), clientAPIKeyContextKey{}, "k2") proxy.ServeHTTP(w, r.WithContext(ctx)) })) defer srv.Close()
res, err := http.Get(srv.URL + "/test") if err != nil { t.Fatal(err) } res.Body.Close()
hdr := <-gotHeaders if hdr.Get("X-Api-Key") != "default" { t.Fatalf("X-Api-Key fallback missing or wrong, got: %q", hdr.Get("X-Api-Key")) } if hdr.Get("Authorization") != "Bearer default" { t.Fatalf("Authorization fallback missing or wrong, got: %q", hdr.Get("Authorization")) }}
func TestReverseProxy_ErrorHandler(t *testing.T) { // Point proxy to a non-routable address to trigger error proxy, err := createReverseProxy("http://127.0.0.1:1", NewStaticSecretSource("")) if err != nil { t.Fatal(err) }
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { proxy.ServeHTTP(w, r) })) defer srv.Close()
res, err := http.Get(srv.URL + "/any") if err != nil { t.Fatal(err) } body, _ := io.ReadAll(res.Body) res.Body.Close()
if res.StatusCode != http.StatusBadGateway { t.Fatalf("want 502, got %d", res.StatusCode) } if !bytes.Contains(body, []byte(`"amp_upstream_proxy_error"`)) { t.Fatalf("unexpected body: %s", body) } if ct := res.Header.Get("Content-Type"); ct != "application/json" { t.Fatalf("content-type: want application/json, got %s", ct) }}
func TestReverseProxy_FullRoundTrip_Gzip(t *testing.T) { // Upstream returns gzipped JSON without Content-Encoding header upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Write(gzipBytes([]byte(`{"upstream":"ok"}`))) })) defer upstream.Close()
proxy, err := createReverseProxy(upstream.URL, NewStaticSecretSource("key")) if err != nil { t.Fatal(err) }
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { proxy.ServeHTTP(w, r) })) defer srv.Close()
res, err := http.Get(srv.URL + "/test") if err != nil { t.Fatal(err) } body, _ := io.ReadAll(res.Body) res.Body.Close()
expected := []byte(`{"upstream":"ok"}`) if !bytes.Equal(body, expected) { t.Fatalf("want decompressed JSON, got: %s", body) }}
func TestReverseProxy_FullRoundTrip_PlainJSON(t *testing.T) { // Upstream returns plain JSON upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) w.Write([]byte(`{"plain":"json"}`)) })) defer upstream.Close()
proxy, err := createReverseProxy(upstream.URL, NewStaticSecretSource("key")) if err != nil { t.Fatal(err) }
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { proxy.ServeHTTP(w, r) })) defer srv.Close()
res, err := http.Get(srv.URL + "/test") if err != nil { t.Fatal(err) } body, _ := io.ReadAll(res.Body) res.Body.Close()
expected := []byte(`{"plain":"json"}`) if !bytes.Equal(body, expected) { t.Fatalf("want plain JSON unchanged, got: %s", body) }}
func TestIsStreamingResponse(t *testing.T) { cases := []struct { name string header http.Header want bool }{ { name: "sse", header: http.Header{"Content-Type": []string{"text/event-stream"}}, want: true, }, { name: "chunked_not_streaming", header: http.Header{"Transfer-Encoding": []string{"chunked"}}, want: false, // Chunked is transport-level, not streaming }, { name: "normal_json", header: http.Header{"Content-Type": []string{"application/json"}}, want: false, }, { name: "empty", header: http.Header{}, want: false, }, }
for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { resp := &http.Response{Header: tc.header} got := isStreamingResponse(resp) if got != tc.want { t.Fatalf("want %v, got %v", tc.want, got) } }) }}
func TestFilterBetaFeatures(t *testing.T) { tests := []struct { name string header string featureToRemove string expected string }{ { name: "Remove context-1m from middle", header: "fine-grained-tool-streaming-2025-05-14,context-1m-2025-08-07,oauth-2025-04-20", featureToRemove: "context-1m-2025-08-07", expected: "fine-grained-tool-streaming-2025-05-14,oauth-2025-04-20", }, { name: "Remove context-1m from start", header: "context-1m-2025-08-07,fine-grained-tool-streaming-2025-05-14", featureToRemove: "context-1m-2025-08-07", expected: "fine-grained-tool-streaming-2025-05-14", }, { name: "Remove context-1m from end", header: "fine-grained-tool-streaming-2025-05-14,context-1m-2025-08-07", featureToRemove: "context-1m-2025-08-07", expected: "fine-grained-tool-streaming-2025-05-14", }, { name: "Feature not present", header: "fine-grained-tool-streaming-2025-05-14,oauth-2025-04-20", featureToRemove: "context-1m-2025-08-07", expected: "fine-grained-tool-streaming-2025-05-14,oauth-2025-04-20", }, { name: "Only feature to remove", header: "context-1m-2025-08-07", featureToRemove: "context-1m-2025-08-07", expected: "", }, { name: "Empty header", header: "", featureToRemove: "context-1m-2025-08-07", expected: "", }, { name: "Header with spaces", header: "fine-grained-tool-streaming-2025-05-14, context-1m-2025-08-07 , oauth-2025-04-20", featureToRemove: "context-1m-2025-08-07", expected: "fine-grained-tool-streaming-2025-05-14,oauth-2025-04-20", }, }
for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := filterBetaFeatures(tt.header, tt.featureToRemove) if result != tt.expected { t.Errorf("filterBetaFeatures() = %q, want %q", result, tt.expected) } }) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160package amp
import ( "bytes" "net/http" "strings"
"github.com/gin-gonic/gin" log "github.com/sirupsen/logrus" "github.com/tidwall/gjson" "github.com/tidwall/sjson")
// ResponseRewriter wraps a gin.ResponseWriter to intercept and modify the response body// It's used to rewrite model names in responses when model mapping is usedtype ResponseRewriter struct { gin.ResponseWriter body *bytes.Buffer originalModel string isStreaming bool}
// NewResponseRewriter creates a new response rewriter for model name substitutionfunc NewResponseRewriter(w gin.ResponseWriter, originalModel string) *ResponseRewriter { return &ResponseRewriter{ ResponseWriter: w, body: &bytes.Buffer{}, originalModel: originalModel, }}
const maxBufferedResponseBytes = 2 * 1024 * 1024 // 2MB safety cap
func looksLikeSSEChunk(data []byte) bool { // Fallback detection: some upstreams may omit/lie about Content-Type, causing SSE to be buffered. // Heuristics are intentionally simple and cheap. return bytes.Contains(data, []byte("data:")) || bytes.Contains(data, []byte("event:")) || bytes.Contains(data, []byte("message_start")) || bytes.Contains(data, []byte("message_delta")) || bytes.Contains(data, []byte("content_block_start")) || bytes.Contains(data, []byte("content_block_delta")) || bytes.Contains(data, []byte("content_block_stop")) || bytes.Contains(data, []byte("\n\n"))}
func (rw *ResponseRewriter) enableStreaming(reason string) error { if rw.isStreaming { return nil } rw.isStreaming = true
// Flush any previously buffered data to avoid reordering or data loss. if rw.body != nil && rw.body.Len() > 0 { buf := rw.body.Bytes() // Copy before Reset() to keep bytes stable. toFlush := make([]byte, len(buf)) copy(toFlush, buf) rw.body.Reset()
if _, err := rw.ResponseWriter.Write(rw.rewriteStreamChunk(toFlush)); err != nil { return err } if flusher, ok := rw.ResponseWriter.(http.Flusher); ok { flusher.Flush() } }
log.Debugf("amp response rewriter: switched to streaming (%s)", reason) return nil}
// Write intercepts response writes and buffers them for model name replacementfunc (rw *ResponseRewriter) Write(data []byte) (int, error) { // Detect streaming on first write (header-based) if !rw.isStreaming && rw.body.Len() == 0 { contentType := rw.Header().Get("Content-Type") rw.isStreaming = strings.Contains(contentType, "text/event-stream") || strings.Contains(contentType, "stream") }
if !rw.isStreaming { // Content-based fallback: detect SSE-like chunks even if Content-Type is missing/wrong. if looksLikeSSEChunk(data) { if err := rw.enableStreaming("sse heuristic"); err != nil { return 0, err } } else if rw.body.Len()+len(data) > maxBufferedResponseBytes { // Safety cap: avoid unbounded buffering on large responses. log.Warnf("amp response rewriter: buffer exceeded %d bytes, switching to streaming", maxBufferedResponseBytes) if err := rw.enableStreaming("buffer limit"); err != nil { return 0, err } } }
if rw.isStreaming { n, err := rw.ResponseWriter.Write(rw.rewriteStreamChunk(data)) if err == nil { if flusher, ok := rw.ResponseWriter.(http.Flusher); ok { flusher.Flush() } } return n, err } return rw.body.Write(data)}
// Flush writes the buffered response with model names rewrittenfunc (rw *ResponseRewriter) Flush() { if rw.isStreaming { if flusher, ok := rw.ResponseWriter.(http.Flusher); ok { flusher.Flush() } return } if rw.body.Len() > 0 { if _, err := rw.ResponseWriter.Write(rw.rewriteModelInResponse(rw.body.Bytes())); err != nil { log.Warnf("amp response rewriter: failed to write rewritten response: %v", err) } }}
// modelFieldPaths lists all JSON paths where model name may appearvar modelFieldPaths = []string{"model", "modelVersion", "response.modelVersion", "message.model"}
// rewriteModelInResponse replaces all occurrences of the mapped model with the original model in JSONfunc (rw *ResponseRewriter) rewriteModelInResponse(data []byte) []byte { if rw.originalModel == "" { return data } for _, path := range modelFieldPaths { if gjson.GetBytes(data, path).Exists() { data, _ = sjson.SetBytes(data, path, rw.originalModel) } } return data}
// rewriteStreamChunk rewrites model names in SSE stream chunksfunc (rw *ResponseRewriter) rewriteStreamChunk(chunk []byte) []byte { if rw.originalModel == "" { return chunk }
// SSE format: "data: {json}\n\n" lines := bytes.Split(chunk, []byte("\n")) for i, line := range lines { if bytes.HasPrefix(line, []byte("data: ")) { jsonData := bytes.TrimPrefix(line, []byte("data: ")) if len(jsonData) > 0 && jsonData[0] == '{' { // Rewrite JSON in the data line rewritten := rw.rewriteModelInResponse(jsonData) lines[i] = append([]byte("data: "), rewritten...) } } }
return bytes.Join(lines, []byte("\n"))}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334package amp
import ( "context" "errors" "net" "net/http" "net/http/httputil" "strings"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/logging" "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers" "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/claude" "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/gemini" "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/openai" log "github.com/sirupsen/logrus")
// clientAPIKeyContextKey is the context key used to pass the client API key// from gin.Context to the request context for SecretSource lookup.type clientAPIKeyContextKey struct{}
// clientAPIKeyMiddleware injects the authenticated client API key from gin.Context["apiKey"]// into the request context so that SecretSource can look it up for per-client upstream routing.func clientAPIKeyMiddleware() gin.HandlerFunc { return func(c *gin.Context) { // Extract the client API key from gin context (set by AuthMiddleware) if apiKey, exists := c.Get("apiKey"); exists { if keyStr, ok := apiKey.(string); ok && keyStr != "" { // Inject into request context for SecretSource.Get(ctx) to read ctx := context.WithValue(c.Request.Context(), clientAPIKeyContextKey{}, keyStr) c.Request = c.Request.WithContext(ctx) } } c.Next() }}
// getClientAPIKeyFromContext retrieves the client API key from request context.// Returns empty string if not present.func getClientAPIKeyFromContext(ctx context.Context) string { if val := ctx.Value(clientAPIKeyContextKey{}); val != nil { if keyStr, ok := val.(string); ok { return keyStr } } return ""}
// localhostOnlyMiddleware returns a middleware that dynamically checks the module's// localhost restriction setting. This allows hot-reload of the restriction without restarting.func (m *AmpModule) localhostOnlyMiddleware() gin.HandlerFunc { return func(c *gin.Context) { // Check current setting (hot-reloadable) if !m.IsRestrictedToLocalhost() { c.Next() return }
// Use actual TCP connection address (RemoteAddr) to prevent header spoofing // This cannot be forged by X-Forwarded-For or other client-controlled headers remoteAddr := c.Request.RemoteAddr
// RemoteAddr format is "IP:port" or "[IPv6]:port", extract just the IP host, _, err := net.SplitHostPort(remoteAddr) if err != nil { // Try parsing as raw IP (shouldn't happen with standard HTTP, but be defensive) host = remoteAddr }
// Parse the IP to handle both IPv4 and IPv6 ip := net.ParseIP(host) if ip == nil { log.Warnf("amp management: invalid RemoteAddr %s, denying access", remoteAddr) c.AbortWithStatusJSON(403, gin.H{ "error": "Access denied: management routes restricted to localhost", }) return }
// Check if IP is loopback (127.0.0.1 or ::1) if !ip.IsLoopback() { log.Warnf("amp management: non-localhost connection from %s attempted access, denying", remoteAddr) c.AbortWithStatusJSON(403, gin.H{ "error": "Access denied: management routes restricted to localhost", }) return }
c.Next() }}
// noCORSMiddleware disables CORS for management routes to prevent browser-based attacks.// This overwrites any global CORS headers set by the server.func noCORSMiddleware() gin.HandlerFunc { return func(c *gin.Context) { // Remove CORS headers to prevent cross-origin access from browsers c.Header("Access-Control-Allow-Origin", "") c.Header("Access-Control-Allow-Methods", "") c.Header("Access-Control-Allow-Headers", "") c.Header("Access-Control-Allow-Credentials", "")
// For OPTIONS preflight, deny with 403 if c.Request.Method == "OPTIONS" { c.AbortWithStatus(403) return }
c.Next() }}
// managementAvailabilityMiddleware short-circuits management routes when the upstream// proxy is disabled, preventing noisy localhost warnings and accidental exposure.func (m *AmpModule) managementAvailabilityMiddleware() gin.HandlerFunc { return func(c *gin.Context) { if m.getProxy() == nil { logging.SkipGinRequestLogging(c) c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{ "error": "amp upstream proxy not available", }) return } c.Next() }}
// wrapManagementAuth skips auth for selected management paths while keeping authentication elsewhere.func wrapManagementAuth(auth gin.HandlerFunc, prefixes ...string) gin.HandlerFunc { return func(c *gin.Context) { path := c.Request.URL.Path for _, prefix := range prefixes { if strings.HasPrefix(path, prefix) && (len(path) == len(prefix) || path[len(prefix)] == '/') { c.Next() return } } auth(c) }}
// registerManagementRoutes registers Amp management proxy routes// These routes proxy through to the Amp control plane for OAuth, user management, etc.// Uses dynamic middleware and proxy getter for hot-reload support.// The auth middleware validates Authorization header against configured API keys.func (m *AmpModule) registerManagementRoutes(engine *gin.Engine, baseHandler *handlers.BaseAPIHandler, auth gin.HandlerFunc) { ampAPI := engine.Group("/api")
// Always disable CORS for management routes to prevent browser-based attacks ampAPI.Use(m.managementAvailabilityMiddleware(), noCORSMiddleware())
// Apply dynamic localhost-only restriction (hot-reloadable via m.IsRestrictedToLocalhost()) ampAPI.Use(m.localhostOnlyMiddleware())
// Apply authentication middleware - requires valid API key in Authorization header var authWithBypass gin.HandlerFunc if auth != nil { ampAPI.Use(auth) authWithBypass = wrapManagementAuth(auth, "/threads", "/auth", "/docs", "/settings") }
// Inject client API key into request context for per-client upstream routing ampAPI.Use(clientAPIKeyMiddleware())
// Dynamic proxy handler that uses m.getProxy() for hot-reload support proxyHandler := func(c *gin.Context) { // Swallow ErrAbortHandler panics from ReverseProxy copyResponse to avoid noisy stack traces defer func() { if rec := recover(); rec != nil { if err, ok := rec.(error); ok && errors.Is(err, http.ErrAbortHandler) { // Upstream already wrote the status (often 404) before the client/stream ended. return } panic(rec) } }()
proxy := m.getProxy() if proxy == nil { c.JSON(503, gin.H{"error": "amp upstream proxy not available"}) return } proxy.ServeHTTP(c.Writer, c.Request) }
// Management routes - these are proxied directly to Amp upstream ampAPI.Any("/internal", proxyHandler) ampAPI.Any("/internal/*path", proxyHandler) ampAPI.Any("/user", proxyHandler) ampAPI.Any("/user/*path", proxyHandler) ampAPI.Any("/auth", proxyHandler) ampAPI.Any("/auth/*path", proxyHandler) ampAPI.Any("/meta", proxyHandler) ampAPI.Any("/meta/*path", proxyHandler) ampAPI.Any("/ads", proxyHandler) ampAPI.Any("/telemetry", proxyHandler) ampAPI.Any("/telemetry/*path", proxyHandler) ampAPI.Any("/threads", proxyHandler) ampAPI.Any("/threads/*path", proxyHandler) ampAPI.Any("/otel", proxyHandler) ampAPI.Any("/otel/*path", proxyHandler) ampAPI.Any("/tab", proxyHandler) ampAPI.Any("/tab/*path", proxyHandler)
// Root-level routes that AMP CLI expects without /api prefix // These need the same security middleware as the /api/* routes (dynamic for hot-reload) rootMiddleware := []gin.HandlerFunc{m.managementAvailabilityMiddleware(), noCORSMiddleware(), m.localhostOnlyMiddleware()} if authWithBypass != nil { rootMiddleware = append(rootMiddleware, authWithBypass) } // Add clientAPIKeyMiddleware after auth for per-client upstream routing rootMiddleware = append(rootMiddleware, clientAPIKeyMiddleware()) engine.GET("/threads", append(rootMiddleware, proxyHandler)...) engine.GET("/threads/*path", append(rootMiddleware, proxyHandler)...) engine.GET("/docs", append(rootMiddleware, proxyHandler)...) engine.GET("/docs/*path", append(rootMiddleware, proxyHandler)...) engine.GET("/settings", append(rootMiddleware, proxyHandler)...) engine.GET("/settings/*path", append(rootMiddleware, proxyHandler)...)
engine.GET("/threads.rss", append(rootMiddleware, proxyHandler)...) engine.GET("/news.rss", append(rootMiddleware, proxyHandler)...)
// Root-level auth routes for CLI login flow // Amp uses multiple auth routes: /auth/cli-login, /auth/callback, /auth/sign-in, /auth/logout // We proxy all /auth/* to support the complete OAuth flow engine.Any("/auth", append(rootMiddleware, proxyHandler)...) engine.Any("/auth/*path", append(rootMiddleware, proxyHandler)...)
// Google v1beta1 passthrough with OAuth fallback // AMP CLI uses non-standard paths like /publishers/google/models/... // We bridge these to our standard Gemini handler to enable local OAuth. // If no local OAuth is available, falls back to ampcode.com proxy. geminiHandlers := gemini.NewGeminiAPIHandler(baseHandler) geminiBridge := createGeminiBridgeHandler(geminiHandlers.GeminiHandler) geminiV1Beta1Fallback := NewFallbackHandlerWithMapper(func() *httputil.ReverseProxy { return m.getProxy() }, m.modelMapper, m.forceModelMappings) geminiV1Beta1Handler := geminiV1Beta1Fallback.WrapHandler(geminiBridge)
// Route POST model calls through Gemini bridge with FallbackHandler. // FallbackHandler checks provider -> mapping -> proxy fallback automatically. // All other methods (e.g., GET model listing) always proxy to upstream to preserve Amp CLI behavior. ampAPI.Any("/provider/google/v1beta1/*path", func(c *gin.Context) { if c.Request.Method == "POST" { if path := c.Param("path"); strings.Contains(path, "/models/") { // POST with /models/ path -> use Gemini bridge with fallback handler // FallbackHandler will check provider/mapping and proxy if needed geminiV1Beta1Handler(c) return } } // Non-POST or no local provider available -> proxy upstream proxyHandler(c) })}
// registerProviderAliases registers /api/provider/{provider}/... routes// These allow Amp CLI to route requests like://// /api/provider/openai/v1/chat/completions// /api/provider/anthropic/v1/messages// /api/provider/google/v1beta/modelsfunc (m *AmpModule) registerProviderAliases(engine *gin.Engine, baseHandler *handlers.BaseAPIHandler, auth gin.HandlerFunc) { // Create handler instances for different providers openaiHandlers := openai.NewOpenAIAPIHandler(baseHandler) geminiHandlers := gemini.NewGeminiAPIHandler(baseHandler) claudeCodeHandlers := claude.NewClaudeCodeAPIHandler(baseHandler) openaiResponsesHandlers := openai.NewOpenAIResponsesAPIHandler(baseHandler)
// Create fallback handler wrapper that forwards to ampcode.com when provider not found // Uses m.getProxy() for hot-reload support (proxy can be updated at runtime) // Also includes model mapping support for routing unavailable models to alternatives fallbackHandler := NewFallbackHandlerWithMapper(func() *httputil.ReverseProxy { return m.getProxy() }, m.modelMapper, m.forceModelMappings)
// Provider-specific routes under /api/provider/:provider ampProviders := engine.Group("/api/provider") if auth != nil { ampProviders.Use(auth) } // Inject client API key into request context for per-client upstream routing ampProviders.Use(clientAPIKeyMiddleware())
provider := ampProviders.Group("/:provider")
// Dynamic models handler - routes to appropriate provider based on path parameter ampModelsHandler := func(c *gin.Context) { providerName := strings.ToLower(c.Param("provider"))
switch providerName { case "anthropic": claudeCodeHandlers.ClaudeModels(c) case "google": geminiHandlers.GeminiModels(c) default: // Default to OpenAI-compatible (works for openai, groq, cerebras, etc.) openaiHandlers.OpenAIModels(c) } }
// Root-level routes (for providers that omit /v1, like groq/cerebras) // Wrap handlers with fallback logic to forward to ampcode.com when provider not found provider.GET("/models", ampModelsHandler) // Models endpoint doesn't need fallback (no body to check) provider.POST("/chat/completions", fallbackHandler.WrapHandler(openaiHandlers.ChatCompletions)) provider.POST("/completions", fallbackHandler.WrapHandler(openaiHandlers.Completions)) provider.POST("/responses", fallbackHandler.WrapHandler(openaiResponsesHandlers.Responses))
// /v1 routes (OpenAI/Claude-compatible endpoints) v1Amp := provider.Group("/v1") { v1Amp.GET("/models", ampModelsHandler) // Models endpoint doesn't need fallback
// OpenAI-compatible endpoints with fallback v1Amp.POST("/chat/completions", fallbackHandler.WrapHandler(openaiHandlers.ChatCompletions)) v1Amp.POST("/completions", fallbackHandler.WrapHandler(openaiHandlers.Completions)) v1Amp.POST("/responses", fallbackHandler.WrapHandler(openaiResponsesHandlers.Responses))
// Claude/Anthropic-compatible endpoints with fallback v1Amp.POST("/messages", fallbackHandler.WrapHandler(claudeCodeHandlers.ClaudeMessages)) v1Amp.POST("/messages/count_tokens", fallbackHandler.WrapHandler(claudeCodeHandlers.ClaudeCountTokens)) }
// /v1beta routes (Gemini native API) // Note: Gemini handler extracts model from URL path, so fallback logic needs special handling v1betaAmp := provider.Group("/v1beta") { v1betaAmp.GET("/models", geminiHandlers.GeminiModels) v1betaAmp.POST("/models/*action", fallbackHandler.WrapHandler(geminiHandlers.GeminiHandler)) v1betaAmp.GET("/models/*action", geminiHandlers.GeminiGetHandler) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381package amp
import ( "net/http" "net/http/httptest" "testing"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers")
func TestRegisterManagementRoutes(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New()
// Create module with proxy for testing m := &AmpModule{ restrictToLocalhost: false, // disable localhost restriction for tests }
// Create a mock proxy that tracks calls proxyCalled := false mockProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { proxyCalled = true w.WriteHeader(200) w.Write([]byte("proxied")) })) defer mockProxy.Close()
// Create real proxy to mock server proxy, _ := createReverseProxy(mockProxy.URL, NewStaticSecretSource("")) m.setProxy(proxy)
base := &handlers.BaseAPIHandler{} m.registerManagementRoutes(r, base, nil) srv := httptest.NewServer(r) defer srv.Close()
managementPaths := []struct { path string method string }{ {"/api/internal", http.MethodGet}, {"/api/internal/some/path", http.MethodGet}, {"/api/user", http.MethodGet}, {"/api/user/profile", http.MethodGet}, {"/api/auth", http.MethodGet}, {"/api/auth/login", http.MethodGet}, {"/api/meta", http.MethodGet}, {"/api/telemetry", http.MethodGet}, {"/api/threads", http.MethodGet}, {"/threads/", http.MethodGet}, {"/threads.rss", http.MethodGet}, // Root-level route (no /api prefix) {"/api/otel", http.MethodGet}, {"/api/tab", http.MethodGet}, {"/api/tab/some/path", http.MethodGet}, {"/auth", http.MethodGet}, // Root-level auth route {"/auth/cli-login", http.MethodGet}, // CLI login flow {"/auth/callback", http.MethodGet}, // OAuth callback // Google v1beta1 bridge should still proxy non-model requests (GET) and allow POST {"/api/provider/google/v1beta1/models", http.MethodGet}, {"/api/provider/google/v1beta1/models", http.MethodPost}, }
for _, path := range managementPaths { t.Run(path.path, func(t *testing.T) { proxyCalled = false req, err := http.NewRequest(path.method, srv.URL+path.path, nil) if err != nil { t.Fatalf("failed to build request: %v", err) } resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("request failed: %v", err) } defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound { t.Fatalf("route %s not registered", path.path) } if !proxyCalled { t.Fatalf("proxy handler not called for %s", path.path) } }) }}
func TestRegisterProviderAliases_AllProvidersRegistered(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New()
// Minimal base handler setup (no need to initialize, just check routing) base := &handlers.BaseAPIHandler{}
// Track if auth middleware was called authCalled := false authMiddleware := func(c *gin.Context) { authCalled = true c.Header("X-Auth", "ok") // Abort with success to avoid calling the actual handler (which needs full setup) c.AbortWithStatus(http.StatusOK) }
m := &AmpModule{authMiddleware_: authMiddleware} m.registerProviderAliases(r, base, authMiddleware)
paths := []struct { path string method string }{ {"/api/provider/openai/models", http.MethodGet}, {"/api/provider/anthropic/models", http.MethodGet}, {"/api/provider/google/models", http.MethodGet}, {"/api/provider/groq/models", http.MethodGet}, {"/api/provider/openai/chat/completions", http.MethodPost}, {"/api/provider/anthropic/v1/messages", http.MethodPost}, {"/api/provider/google/v1beta/models", http.MethodGet}, }
for _, tc := range paths { t.Run(tc.path, func(t *testing.T) { authCalled = false req := httptest.NewRequest(tc.method, tc.path, nil) w := httptest.NewRecorder() r.ServeHTTP(w, req)
if w.Code == http.StatusNotFound { t.Fatalf("route %s %s not registered", tc.method, tc.path) } if !authCalled { t.Fatalf("auth middleware not executed for %s", tc.path) } if w.Header().Get("X-Auth") != "ok" { t.Fatalf("auth middleware header not set for %s", tc.path) } }) }}
func TestRegisterProviderAliases_DynamicModelsHandler(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New()
base := &handlers.BaseAPIHandler{}
m := &AmpModule{authMiddleware_: func(c *gin.Context) { c.AbortWithStatus(http.StatusOK) }} m.registerProviderAliases(r, base, func(c *gin.Context) { c.AbortWithStatus(http.StatusOK) })
providers := []string{"openai", "anthropic", "google", "groq", "cerebras"}
for _, provider := range providers { t.Run(provider, func(t *testing.T) { path := "/api/provider/" + provider + "/models" req := httptest.NewRequest(http.MethodGet, path, nil) w := httptest.NewRecorder() r.ServeHTTP(w, req)
// Should not 404 if w.Code == http.StatusNotFound { t.Fatalf("models route not found for provider: %s", provider) } }) }}
func TestRegisterProviderAliases_V1Routes(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New()
base := &handlers.BaseAPIHandler{}
m := &AmpModule{authMiddleware_: func(c *gin.Context) { c.AbortWithStatus(http.StatusOK) }} m.registerProviderAliases(r, base, func(c *gin.Context) { c.AbortWithStatus(http.StatusOK) })
v1Paths := []struct { path string method string }{ {"/api/provider/openai/v1/models", http.MethodGet}, {"/api/provider/openai/v1/chat/completions", http.MethodPost}, {"/api/provider/openai/v1/completions", http.MethodPost}, {"/api/provider/anthropic/v1/messages", http.MethodPost}, {"/api/provider/anthropic/v1/messages/count_tokens", http.MethodPost}, }
for _, tc := range v1Paths { t.Run(tc.path, func(t *testing.T) { req := httptest.NewRequest(tc.method, tc.path, nil) w := httptest.NewRecorder() r.ServeHTTP(w, req)
if w.Code == http.StatusNotFound { t.Fatalf("v1 route %s %s not registered", tc.method, tc.path) } }) }}
func TestRegisterProviderAliases_V1BetaRoutes(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New()
base := &handlers.BaseAPIHandler{}
m := &AmpModule{authMiddleware_: func(c *gin.Context) { c.AbortWithStatus(http.StatusOK) }} m.registerProviderAliases(r, base, func(c *gin.Context) { c.AbortWithStatus(http.StatusOK) })
v1betaPaths := []struct { path string method string }{ {"/api/provider/google/v1beta/models", http.MethodGet}, {"/api/provider/google/v1beta/models/generateContent", http.MethodPost}, }
for _, tc := range v1betaPaths { t.Run(tc.path, func(t *testing.T) { req := httptest.NewRequest(tc.method, tc.path, nil) w := httptest.NewRecorder() r.ServeHTTP(w, req)
if w.Code == http.StatusNotFound { t.Fatalf("v1beta route %s %s not registered", tc.method, tc.path) } }) }}
func TestRegisterProviderAliases_NoAuthMiddleware(t *testing.T) { // Test that routes still register even if auth middleware is nil (fallback behavior) gin.SetMode(gin.TestMode) r := gin.New()
base := &handlers.BaseAPIHandler{}
m := &AmpModule{authMiddleware_: nil} // No auth middleware m.registerProviderAliases(r, base, func(c *gin.Context) { c.AbortWithStatus(http.StatusOK) })
req := httptest.NewRequest(http.MethodGet, "/api/provider/openai/models", nil) w := httptest.NewRecorder() r.ServeHTTP(w, req)
// Should still work (with fallback no-op auth) if w.Code == http.StatusNotFound { t.Fatal("routes should register even without auth middleware") }}
func TestLocalhostOnlyMiddleware_PreventsSpoofing(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New()
// Create module with localhost restriction enabled m := &AmpModule{ restrictToLocalhost: true, }
// Apply dynamic localhost-only middleware r.Use(m.localhostOnlyMiddleware()) r.GET("/test", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
tests := []struct { name string remoteAddr string forwardedFor string expectedStatus int description string }{ { name: "spoofed_header_remote_connection", remoteAddr: "192.168.1.100:12345", forwardedFor: "127.0.0.1", expectedStatus: http.StatusForbidden, description: "Spoofed X-Forwarded-For header should be ignored", }, { name: "real_localhost_ipv4", remoteAddr: "127.0.0.1:54321", forwardedFor: "", expectedStatus: http.StatusOK, description: "Real localhost IPv4 connection should work", }, { name: "real_localhost_ipv6", remoteAddr: "[::1]:54321", forwardedFor: "", expectedStatus: http.StatusOK, description: "Real localhost IPv6 connection should work", }, { name: "remote_ipv4", remoteAddr: "203.0.113.42:8080", forwardedFor: "", expectedStatus: http.StatusForbidden, description: "Remote IPv4 connection should be blocked", }, { name: "remote_ipv6", remoteAddr: "[2001:db8::1]:9090", forwardedFor: "", expectedStatus: http.StatusForbidden, description: "Remote IPv6 connection should be blocked", }, { name: "spoofed_localhost_ipv6", remoteAddr: "203.0.113.42:8080", forwardedFor: "::1", expectedStatus: http.StatusForbidden, description: "Spoofed X-Forwarded-For with IPv6 localhost should be ignored", }, }
for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/test", nil) req.RemoteAddr = tt.remoteAddr if tt.forwardedFor != "" { req.Header.Set("X-Forwarded-For", tt.forwardedFor) }
w := httptest.NewRecorder() r.ServeHTTP(w, req)
if w.Code != tt.expectedStatus { t.Errorf("%s: expected status %d, got %d", tt.description, tt.expectedStatus, w.Code) } }) }}
func TestLocalhostOnlyMiddleware_HotReload(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New()
// Create module with localhost restriction initially enabled m := &AmpModule{ restrictToLocalhost: true, }
// Apply dynamic localhost-only middleware r.Use(m.localhostOnlyMiddleware()) r.GET("/test", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
// Test 1: Remote IP should be blocked when restriction is enabled req := httptest.NewRequest(http.MethodGet, "/test", nil) req.RemoteAddr = "192.168.1.100:12345" w := httptest.NewRecorder() r.ServeHTTP(w, req)
if w.Code != http.StatusForbidden { t.Errorf("Expected 403 when restriction enabled, got %d", w.Code) }
// Test 2: Hot-reload - disable restriction m.setRestrictToLocalhost(false)
req = httptest.NewRequest(http.MethodGet, "/test", nil) req.RemoteAddr = "192.168.1.100:12345" w = httptest.NewRecorder() r.ServeHTTP(w, req)
if w.Code != http.StatusOK { t.Errorf("Expected 200 after disabling restriction, got %d", w.Code) }
// Test 3: Hot-reload - re-enable restriction m.setRestrictToLocalhost(true)
req = httptest.NewRequest(http.MethodGet, "/test", nil) req.RemoteAddr = "192.168.1.100:12345" w = httptest.NewRecorder() r.ServeHTTP(w, req)
if w.Code != http.StatusForbidden { t.Errorf("Expected 403 after re-enabling restriction, got %d", w.Code) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248package amp
import ( "context" "encoding/json" "fmt" "os" "path/filepath" "strings" "sync" "time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config" log "github.com/sirupsen/logrus")
// SecretSource provides Amp API keys with configurable precedence and cachingtype SecretSource interface { Get(ctx context.Context) (string, error)}
// cachedSecret holds a secret value with expirationtype cachedSecret struct { value string expiresAt time.Time}
// MultiSourceSecret implements precedence-based secret lookup:// 1. Explicit config value (highest priority)// 2. Environment variable AMP_API_KEY// 3. File-based secret (lowest priority)type MultiSourceSecret struct { explicitKey string envKey string filePath string cacheTTL time.Duration
mu sync.RWMutex cache *cachedSecret}
// NewMultiSourceSecret creates a secret source with precedence and cachingfunc NewMultiSourceSecret(explicitKey string, cacheTTL time.Duration) *MultiSourceSecret { if cacheTTL == 0 { cacheTTL = 5 * time.Minute // Default 5 minute cache }
home, _ := os.UserHomeDir() filePath := filepath.Join(home, ".local", "share", "amp", "secrets.json")
return &MultiSourceSecret{ explicitKey: strings.TrimSpace(explicitKey), envKey: "AMP_API_KEY", filePath: filePath, cacheTTL: cacheTTL, }}
// NewMultiSourceSecretWithPath creates a secret source with a custom file path (for testing)func NewMultiSourceSecretWithPath(explicitKey string, filePath string, cacheTTL time.Duration) *MultiSourceSecret { if cacheTTL == 0 { cacheTTL = 5 * time.Minute }
return &MultiSourceSecret{ explicitKey: strings.TrimSpace(explicitKey), envKey: "AMP_API_KEY", filePath: filePath, cacheTTL: cacheTTL, }}
// Get retrieves the Amp API key using precedence: config > env > file// Results are cached for cacheTTL duration to avoid excessive file readsfunc (s *MultiSourceSecret) Get(ctx context.Context) (string, error) { // Precedence 1: Explicit config key (highest priority, no caching needed) if s.explicitKey != "" { return s.explicitKey, nil }
// Precedence 2: Environment variable if envValue := strings.TrimSpace(os.Getenv(s.envKey)); envValue != "" { return envValue, nil }
// Precedence 3: File-based secret (lowest priority, cached) // Check cache first s.mu.RLock() if s.cache != nil && time.Now().Before(s.cache.expiresAt) { value := s.cache.value s.mu.RUnlock() return value, nil } s.mu.RUnlock()
// Cache miss or expired - read from file key, err := s.readFromFile() if err != nil { // Cache empty result to avoid repeated file reads on missing files s.updateCache("") return "", err }
// Cache the result s.updateCache(key) return key, nil}
// readFromFile reads the Amp API key from the secrets filefunc (s *MultiSourceSecret) readFromFile() (string, error) { content, err := os.ReadFile(s.filePath) if err != nil { if os.IsNotExist(err) { return "", nil // Missing file is not an error, just no key available } return "", fmt.Errorf("failed to read amp secrets from %s: %w", s.filePath, err) }
var secrets map[string]string if err := json.Unmarshal(content, &secrets); err != nil { return "", fmt.Errorf("failed to parse amp secrets from %s: %w", s.filePath, err) }
key := strings.TrimSpace(secrets["apiKey@https://ampcode.com/"]) return key, nil}
// updateCache updates the cached secret valuefunc (s *MultiSourceSecret) updateCache(value string) { s.mu.Lock() defer s.mu.Unlock() s.cache = &cachedSecret{ value: value, expiresAt: time.Now().Add(s.cacheTTL), }}
// InvalidateCache clears the cached secret, forcing a fresh read on next Getfunc (s *MultiSourceSecret) InvalidateCache() { s.mu.Lock() defer s.mu.Unlock() s.cache = nil}
// UpdateExplicitKey refreshes the config-provided key and clears cache.func (s *MultiSourceSecret) UpdateExplicitKey(key string) { if s == nil { return } s.mu.Lock() s.explicitKey = strings.TrimSpace(key) s.cache = nil s.mu.Unlock()}
// StaticSecretSource returns a fixed API key (for testing)type StaticSecretSource struct { key string}
// NewStaticSecretSource creates a secret source with a fixed keyfunc NewStaticSecretSource(key string) *StaticSecretSource { return &StaticSecretSource{key: strings.TrimSpace(key)}}
// Get returns the static API keyfunc (s *StaticSecretSource) Get(ctx context.Context) (string, error) { return s.key, nil}
// MappedSecretSource wraps a default SecretSource and adds per-client API key mapping.// When a request context contains a client API key that matches a configured mapping,// the corresponding upstream key is returned. Otherwise, falls back to the default source.type MappedSecretSource struct { defaultSource SecretSource mu sync.RWMutex lookup map[string]string // clientKey -> upstreamKey}
// NewMappedSecretSource creates a MappedSecretSource wrapping the given default source.func NewMappedSecretSource(defaultSource SecretSource) *MappedSecretSource { return &MappedSecretSource{ defaultSource: defaultSource, lookup: make(map[string]string), }}
// Get retrieves the Amp API key, checking per-client mappings first.// If the request context contains a client API key that matches a configured mapping,// returns the corresponding upstream key. Otherwise, falls back to the default source.func (s *MappedSecretSource) Get(ctx context.Context) (string, error) { // Try to get client API key from request context clientKey := getClientAPIKeyFromContext(ctx) if clientKey != "" { s.mu.RLock() if upstreamKey, ok := s.lookup[clientKey]; ok && upstreamKey != "" { s.mu.RUnlock() return upstreamKey, nil } s.mu.RUnlock() }
// Fall back to default source return s.defaultSource.Get(ctx)}
// UpdateMappings rebuilds the client-to-upstream key mapping from configuration entries.// If the same client key appears in multiple entries, logs a warning and uses the first one.func (s *MappedSecretSource) UpdateMappings(entries []config.AmpUpstreamAPIKeyEntry) { newLookup := make(map[string]string)
for _, entry := range entries { upstreamKey := strings.TrimSpace(entry.UpstreamAPIKey) if upstreamKey == "" { continue } for _, clientKey := range entry.APIKeys { trimmedKey := strings.TrimSpace(clientKey) if trimmedKey == "" { continue } if _, exists := newLookup[trimmedKey]; exists { // Log warning for duplicate client key, first one wins log.Warnf("amp upstream-api-keys: client API key appears in multiple entries; using first mapping.") continue } newLookup[trimmedKey] = upstreamKey } }
s.mu.Lock() s.lookup = newLookup s.mu.Unlock()}
// UpdateDefaultExplicitKey updates the explicit key on the underlying MultiSourceSecret (if applicable).func (s *MappedSecretSource) UpdateDefaultExplicitKey(key string) { if ms, ok := s.defaultSource.(*MultiSourceSecret); ok { ms.UpdateExplicitKey(key) }}
// InvalidateCache invalidates cache on the underlying MultiSourceSecret (if applicable).func (s *MappedSecretSource) InvalidateCache() { if ms, ok := s.defaultSource.(*MultiSourceSecret); ok { ms.InvalidateCache() }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366package amp
import ( "context" "encoding/json" "os" "path/filepath" "sync" "testing" "time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config" log "github.com/sirupsen/logrus" "github.com/sirupsen/logrus/hooks/test")
func TestMultiSourceSecret_PrecedenceOrder(t *testing.T) { ctx := context.Background()
cases := []struct { name string configKey string envKey string fileJSON string want string }{ {"config_wins", "cfg", "env", `{"apiKey@https://ampcode.com/":"file"}`, "cfg"}, {"env_wins_when_no_cfg", "", "env", `{"apiKey@https://ampcode.com/":"file"}`, "env"}, {"file_when_no_cfg_env", "", "", `{"apiKey@https://ampcode.com/":"file"}`, "file"}, {"empty_cfg_trims_then_env", " ", "env", `{"apiKey@https://ampcode.com/":"file"}`, "env"}, {"empty_env_then_file", "", " ", `{"apiKey@https://ampcode.com/":"file"}`, "file"}, {"missing_file_returns_empty", "", "", "", ""}, {"all_empty_returns_empty", " ", " ", `{"apiKey@https://ampcode.com/":" "}`, ""}, }
for _, tc := range cases { tc := tc // capture range variable t.Run(tc.name, func(t *testing.T) { tmpDir := t.TempDir() secretsPath := filepath.Join(tmpDir, "secrets.json")
if tc.fileJSON != "" { if err := os.WriteFile(secretsPath, []byte(tc.fileJSON), 0600); err != nil { t.Fatal(err) } }
t.Setenv("AMP_API_KEY", tc.envKey)
s := NewMultiSourceSecretWithPath(tc.configKey, secretsPath, 100*time.Millisecond) got, err := s.Get(ctx) if err != nil && tc.fileJSON != "" && json.Valid([]byte(tc.fileJSON)) { t.Fatalf("unexpected error: %v", err) } if got != tc.want { t.Fatalf("want %q, got %q", tc.want, got) } }) }}
func TestMultiSourceSecret_CacheBehavior(t *testing.T) { ctx := context.Background() tmpDir := t.TempDir() p := filepath.Join(tmpDir, "secrets.json")
// Initial value if err := os.WriteFile(p, []byte(`{"apiKey@https://ampcode.com/":"v1"}`), 0600); err != nil { t.Fatal(err) }
s := NewMultiSourceSecretWithPath("", p, 50*time.Millisecond)
// First read - should return v1 got1, err := s.Get(ctx) if err != nil { t.Fatalf("Get failed: %v", err) } if got1 != "v1" { t.Fatalf("expected v1, got %s", got1) }
// Change file; within TTL we should still see v1 (cached) if err := os.WriteFile(p, []byte(`{"apiKey@https://ampcode.com/":"v2"}`), 0600); err != nil { t.Fatal(err) } got2, _ := s.Get(ctx) if got2 != "v1" { t.Fatalf("cache hit expected v1, got %s", got2) }
// After TTL expires, should see v2 time.Sleep(60 * time.Millisecond) got3, _ := s.Get(ctx) if got3 != "v2" { t.Fatalf("cache miss expected v2, got %s", got3) }
// Invalidate forces re-read immediately if err := os.WriteFile(p, []byte(`{"apiKey@https://ampcode.com/":"v3"}`), 0600); err != nil { t.Fatal(err) } s.InvalidateCache() got4, _ := s.Get(ctx) if got4 != "v3" { t.Fatalf("invalidate expected v3, got %s", got4) }}
func TestMultiSourceSecret_FileHandling(t *testing.T) { ctx := context.Background()
t.Run("missing_file_no_error", func(t *testing.T) { s := NewMultiSourceSecretWithPath("", "/nonexistent/path/secrets.json", 100*time.Millisecond) got, err := s.Get(ctx) if err != nil { t.Fatalf("expected no error for missing file, got: %v", err) } if got != "" { t.Fatalf("expected empty string, got %q", got) } })
t.Run("invalid_json", func(t *testing.T) { tmpDir := t.TempDir() p := filepath.Join(tmpDir, "secrets.json") if err := os.WriteFile(p, []byte(`{invalid json`), 0600); err != nil { t.Fatal(err) }
s := NewMultiSourceSecretWithPath("", p, 100*time.Millisecond) _, err := s.Get(ctx) if err == nil { t.Fatal("expected error for invalid JSON") } })
t.Run("missing_key_in_json", func(t *testing.T) { tmpDir := t.TempDir() p := filepath.Join(tmpDir, "secrets.json") if err := os.WriteFile(p, []byte(`{"other":"value"}`), 0600); err != nil { t.Fatal(err) }
s := NewMultiSourceSecretWithPath("", p, 100*time.Millisecond) got, err := s.Get(ctx) if err != nil { t.Fatalf("unexpected error: %v", err) } if got != "" { t.Fatalf("expected empty string for missing key, got %q", got) } })
t.Run("empty_key_value", func(t *testing.T) { tmpDir := t.TempDir() p := filepath.Join(tmpDir, "secrets.json") if err := os.WriteFile(p, []byte(`{"apiKey@https://ampcode.com/":" "}`), 0600); err != nil { t.Fatal(err) }
s := NewMultiSourceSecretWithPath("", p, 100*time.Millisecond) got, _ := s.Get(ctx) if got != "" { t.Fatalf("expected empty after trim, got %q", got) } })}
func TestMultiSourceSecret_Concurrency(t *testing.T) { tmpDir := t.TempDir() p := filepath.Join(tmpDir, "secrets.json") if err := os.WriteFile(p, []byte(`{"apiKey@https://ampcode.com/":"concurrent"}`), 0600); err != nil { t.Fatal(err) }
s := NewMultiSourceSecretWithPath("", p, 5*time.Second) ctx := context.Background()
// Spawn many goroutines calling Get concurrently const goroutines = 50 const iterations = 100
var wg sync.WaitGroup errors := make(chan error, goroutines)
for i := 0; i < goroutines; i++ { wg.Add(1) go func() { defer wg.Done() for j := 0; j < iterations; j++ { val, err := s.Get(ctx) if err != nil { errors <- err return } if val != "concurrent" { errors <- err return } } }() }
wg.Wait() close(errors)
for err := range errors { t.Errorf("concurrency error: %v", err) }}
func TestStaticSecretSource(t *testing.T) { ctx := context.Background()
t.Run("returns_provided_key", func(t *testing.T) { s := NewStaticSecretSource("test-key-123") got, err := s.Get(ctx) if err != nil { t.Fatalf("unexpected error: %v", err) } if got != "test-key-123" { t.Fatalf("want test-key-123, got %q", got) } })
t.Run("trims_whitespace", func(t *testing.T) { s := NewStaticSecretSource(" test-key ") got, err := s.Get(ctx) if err != nil { t.Fatalf("unexpected error: %v", err) } if got != "test-key" { t.Fatalf("want test-key, got %q", got) } })
t.Run("empty_string", func(t *testing.T) { s := NewStaticSecretSource("") got, err := s.Get(ctx) if err != nil { t.Fatalf("unexpected error: %v", err) } if got != "" { t.Fatalf("want empty string, got %q", got) } })}
func TestMultiSourceSecret_CacheEmptyResult(t *testing.T) { // Test that missing file results are cached to avoid repeated file reads tmpDir := t.TempDir() p := filepath.Join(tmpDir, "nonexistent.json")
s := NewMultiSourceSecretWithPath("", p, 100*time.Millisecond) ctx := context.Background()
// First call - file doesn't exist, should cache empty result got1, err := s.Get(ctx) if err != nil { t.Fatalf("expected no error for missing file, got: %v", err) } if got1 != "" { t.Fatalf("expected empty string, got %q", got1) }
// Create the file now if err := os.WriteFile(p, []byte(`{"apiKey@https://ampcode.com/":"new-value"}`), 0600); err != nil { t.Fatal(err) }
// Second call - should still return empty (cached), not read the new file got2, _ := s.Get(ctx) if got2 != "" { t.Fatalf("cache should return empty, got %q", got2) }
// After TTL expires, should see the new value time.Sleep(110 * time.Millisecond) got3, _ := s.Get(ctx) if got3 != "new-value" { t.Fatalf("after cache expiry, expected new-value, got %q", got3) }}
func TestMappedSecretSource_UsesMappingFromContext(t *testing.T) { defaultSource := NewStaticSecretSource("default") s := NewMappedSecretSource(defaultSource) s.UpdateMappings([]config.AmpUpstreamAPIKeyEntry{ { UpstreamAPIKey: "u1", APIKeys: []string{"k1"}, }, })
ctx := context.WithValue(context.Background(), clientAPIKeyContextKey{}, "k1") got, err := s.Get(ctx) if err != nil { t.Fatalf("unexpected error: %v", err) } if got != "u1" { t.Fatalf("want u1, got %q", got) }
ctx = context.WithValue(context.Background(), clientAPIKeyContextKey{}, "k2") got, err = s.Get(ctx) if err != nil { t.Fatalf("unexpected error: %v", err) } if got != "default" { t.Fatalf("want default fallback, got %q", got) }}
func TestMappedSecretSource_DuplicateClientKey_FirstWins(t *testing.T) { defaultSource := NewStaticSecretSource("default") s := NewMappedSecretSource(defaultSource) s.UpdateMappings([]config.AmpUpstreamAPIKeyEntry{ { UpstreamAPIKey: "u1", APIKeys: []string{"k1"}, }, { UpstreamAPIKey: "u2", APIKeys: []string{"k1"}, }, })
ctx := context.WithValue(context.Background(), clientAPIKeyContextKey{}, "k1") got, err := s.Get(ctx) if err != nil { t.Fatalf("unexpected error: %v", err) } if got != "u1" { t.Fatalf("want u1 (first wins), got %q", got) }}
func TestMappedSecretSource_DuplicateClientKey_LogsWarning(t *testing.T) { hook := test.NewLocal(log.StandardLogger()) defer hook.Reset()
defaultSource := NewStaticSecretSource("default") s := NewMappedSecretSource(defaultSource) s.UpdateMappings([]config.AmpUpstreamAPIKeyEntry{ { UpstreamAPIKey: "u1", APIKeys: []string{"k1"}, }, { UpstreamAPIKey: "u2", APIKeys: []string{"k1"}, }, })
foundWarning := false for _, entry := range hook.AllEntries() { if entry.Level == log.WarnLevel && entry.Message == "amp upstream-api-keys: client API key appears in multiple entries; using first mapping." { foundWarning = true break } } if !foundWarning { t.Fatal("expected warning log for duplicate client key, but none was found") }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192// Package modules provides a pluggable routing module system for extending// the API server with optional features without modifying core routing logic.package modules
import ( "fmt"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/config" "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers")
// Context encapsulates the dependencies exposed to routing modules during// registration. Modules can use the Gin engine to attach routes, the shared// BaseAPIHandler for constructing SDK-specific handlers, and the resolved// authentication middleware for protecting routes that require API keys.type Context struct { Engine *gin.Engine BaseHandler *handlers.BaseAPIHandler Config *config.Config AuthMiddleware gin.HandlerFunc}
// RouteModule represents a pluggable routing module that can register routes// and handle configuration updates independently of the core server.//// DEPRECATED: Use RouteModuleV2 for new modules. This interface is kept for// backwards compatibility and will be removed in a future version.type RouteModule interface { // Name returns a human-readable identifier for the module Name() string
// Register sets up routes and handlers for this module. // It receives the Gin engine, base handlers, and current configuration. // Returns an error if registration fails (errors are logged but don't stop the server). Register(engine *gin.Engine, baseHandler *handlers.BaseAPIHandler, cfg *config.Config) error
// OnConfigUpdated is called when the configuration is reloaded. // Modules can respond to configuration changes here. // Returns an error if the update cannot be applied. OnConfigUpdated(cfg *config.Config) error}
// RouteModuleV2 represents a pluggable bundle of routes that can integrate with// the API server without modifying its core routing logic. Implementations can// attach routes during Register and react to configuration updates via// OnConfigUpdated.//// This is the preferred interface for new modules. It uses Context for cleaner// dependency injection and supports idempotent registration.type RouteModuleV2 interface { // Name returns a unique identifier for logging and diagnostics. Name() string
// Register wires the module's routes into the provided Gin engine. Modules // should treat multiple calls as idempotent and avoid duplicate route // registration when invoked more than once. Register(ctx Context) error
// OnConfigUpdated notifies the module when the server configuration changes // via hot reload. Implementations can refresh cached state or emit warnings. OnConfigUpdated(cfg *config.Config) error}
// RegisterModule is a helper that registers a module using either the V1 or V2// interface. This allows gradual migration from V1 to V2 without breaking// existing modules.//// Example usage://// ctx := modules.Context{// Engine: engine,// BaseHandler: baseHandler,// Config: cfg,// AuthMiddleware: authMiddleware,// }// if err := modules.RegisterModule(ctx, ampModule); err != nil {// log.Errorf("Failed to register module: %v", err)// }func RegisterModule(ctx Context, mod interface{}) error { // Try V2 interface first (preferred) if v2, ok := mod.(RouteModuleV2); ok { return v2.Register(ctx) }
// Fall back to V1 interface for backwards compatibility if v1, ok := mod.(RouteModule); ok { return v1.Register(ctx.Engine, ctx.BaseHandler, ctx.Config) }
return fmt.Errorf("unsupported module type %T (must implement RouteModule or RouteModuleV2)", mod)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056// Package api provides the HTTP API server implementation for the CLI Proxy API.// It includes the main server struct, routing setup, middleware for CORS and authentication,// and integration with various AI API handlers (OpenAI, Claude, Gemini).// The server supports hot-reloading of clients and configuration.package api
import ( "context" "crypto/subtle" "errors" "fmt" "net/http" "os" "path/filepath" "strings" "sync" "sync/atomic" "time"
"github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v6/internal/access" managementHandlers "github.com/router-for-me/CLIProxyAPI/v6/internal/api/handlers/management" "github.com/router-for-me/CLIProxyAPI/v6/internal/api/middleware" "github.com/router-for-me/CLIProxyAPI/v6/internal/api/modules" ampmodule "github.com/router-for-me/CLIProxyAPI/v6/internal/api/modules/amp" "github.com/router-for-me/CLIProxyAPI/v6/internal/config" "github.com/router-for-me/CLIProxyAPI/v6/internal/logging" "github.com/router-for-me/CLIProxyAPI/v6/internal/managementasset" "github.com/router-for-me/CLIProxyAPI/v6/internal/usage" "github.com/router-for-me/CLIProxyAPI/v6/internal/util" sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access" "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers" "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/claude" "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/gemini" "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/openai" "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth" log "github.com/sirupsen/logrus" "gopkg.in/yaml.v3")
const oauthCallbackSuccessHTML = `<html><head><meta charset="utf-8"><title>Authentication successful</title><script>setTimeout(function(){window.close();},5000);</script></head><body><h1>Authentication successful!</h1><p>You can close this window.</p><p>This window will close automatically in 5 seconds.</p></body></html>`
type serverOptionConfig struct { extraMiddleware []gin.HandlerFunc engineConfigurator func(*gin.Engine) routerConfigurator func(*gin.Engine, *handlers.BaseAPIHandler, *config.Config) requestLoggerFactory func(*config.Config, string) logging.RequestLogger localPassword string keepAliveEnabled bool keepAliveTimeout time.Duration keepAliveOnTimeout func()}
// ServerOption customises HTTP server construction.type ServerOption func(*serverOptionConfig)
func defaultRequestLoggerFactory(cfg *config.Config, configPath string) logging.RequestLogger { configDir := filepath.Dir(configPath) if base := util.WritablePath(); base != "" { return logging.NewFileRequestLogger(cfg.RequestLog, filepath.Join(base, "logs"), configDir) } return logging.NewFileRequestLogger(cfg.RequestLog, "logs", configDir)}
// WithMiddleware appends additional Gin middleware during server construction.func WithMiddleware(mw ...gin.HandlerFunc) ServerOption { return func(cfg *serverOptionConfig) { cfg.extraMiddleware = append(cfg.extraMiddleware, mw...) }}
// WithEngineConfigurator allows callers to mutate the Gin engine prior to middleware setup.func WithEngineConfigurator(fn func(*gin.Engine)) ServerOption { return func(cfg *serverOptionConfig) { cfg.engineConfigurator = fn }}
// WithRouterConfigurator appends a callback after default routes are registered.func WithRouterConfigurator(fn func(*gin.Engine, *handlers.BaseAPIHandler, *config.Config)) ServerOption { return func(cfg *serverOptionConfig) { cfg.routerConfigurator = fn }}
// WithLocalManagementPassword stores a runtime-only management password accepted for localhost requests.func WithLocalManagementPassword(password string) ServerOption { return func(cfg *serverOptionConfig) { cfg.localPassword = password }}
// WithKeepAliveEndpoint enables a keep-alive endpoint with the provided timeout and callback.func WithKeepAliveEndpoint(timeout time.Duration, onTimeout func()) ServerOption { return func(cfg *serverOptionConfig) { if timeout <= 0 || onTimeout == nil { return } cfg.keepAliveEnabled = true cfg.keepAliveTimeout = timeout cfg.keepAliveOnTimeout = onTimeout }}
// WithRequestLoggerFactory customises request logger creation.func WithRequestLoggerFactory(factory func(*config.Config, string) logging.RequestLogger) ServerOption { return func(cfg *serverOptionConfig) { cfg.requestLoggerFactory = factory }}
// Server represents the main API server.// It encapsulates the Gin engine, HTTP server, handlers, and configuration.type Server struct { // engine is the Gin web framework engine instance. engine *gin.Engine
// server is the underlying HTTP server. server *http.Server
// handlers contains the API handlers for processing requests. handlers *handlers.BaseAPIHandler
// cfg holds the current server configuration. cfg *config.Config
// oldConfigYaml stores a YAML snapshot of the previous configuration for change detection. // This prevents issues when the config object is modified in place by Management API. oldConfigYaml []byte
// accessManager handles request authentication providers. accessManager *sdkaccess.Manager
// requestLogger is the request logger instance for dynamic configuration updates. requestLogger logging.RequestLogger loggerToggle func(bool)
// configFilePath is the absolute path to the YAML config file for persistence. configFilePath string
// currentPath is the absolute path to the current working directory. currentPath string
// wsRoutes tracks registered websocket upgrade paths. wsRouteMu sync.Mutex wsRoutes map[string]struct{} wsAuthChanged func(bool, bool) wsAuthEnabled atomic.Bool
// management handler mgmt *managementHandlers.Handler
// ampModule is the Amp routing module for model mapping hot-reload ampModule *ampmodule.AmpModule
// managementRoutesRegistered tracks whether the management routes have been attached to the engine. managementRoutesRegistered atomic.Bool // managementRoutesEnabled controls whether management endpoints serve real handlers. managementRoutesEnabled atomic.Bool
// envManagementSecret indicates whether MANAGEMENT_PASSWORD is configured. envManagementSecret bool
localPassword string
keepAliveEnabled bool keepAliveTimeout time.Duration keepAliveOnTimeout func() keepAliveHeartbeat chan struct{} keepAliveStop chan struct{}}
// NewServer creates and initializes a new API server instance.// It sets up the Gin engine, middleware, routes, and handlers.//// Parameters:// - cfg: The server configuration// - authManager: core runtime auth manager// - accessManager: request authentication manager//// Returns:// - *Server: A new server instancefunc NewServer(cfg *config.Config, authManager *auth.Manager, accessManager *sdkaccess.Manager, configFilePath string, opts ...ServerOption) *Server { optionState := &serverOptionConfig{ requestLoggerFactory: defaultRequestLoggerFactory, } for i := range opts { opts[i](optionState) } // Set gin mode if !cfg.Debug { gin.SetMode(gin.ReleaseMode) }
// Create gin engine engine := gin.New() if optionState.engineConfigurator != nil { optionState.engineConfigurator(engine) }
// Add middleware engine.Use(logging.GinLogrusLogger()) engine.Use(logging.GinLogrusRecovery()) for _, mw := range optionState.extraMiddleware { engine.Use(mw) }
// Add request logging middleware (positioned after recovery, before auth) // Resolve logs directory relative to the configuration file directory. var requestLogger logging.RequestLogger var toggle func(bool) if !cfg.CommercialMode { if optionState.requestLoggerFactory != nil { requestLogger = optionState.requestLoggerFactory(cfg, configFilePath) } if requestLogger != nil { engine.Use(middleware.RequestLoggingMiddleware(requestLogger)) if setter, ok := requestLogger.(interface{ SetEnabled(bool) }); ok { toggle = setter.SetEnabled } } }
engine.Use(corsMiddleware()) wd, err := os.Getwd() if err != nil { wd = configFilePath }
envAdminPassword, envAdminPasswordSet := os.LookupEnv("MANAGEMENT_PASSWORD") envAdminPassword = strings.TrimSpace(envAdminPassword) envManagementSecret := envAdminPasswordSet && envAdminPassword != ""
// Create server instance s := &Server{ engine: engine, handlers: handlers.NewBaseAPIHandlers(&cfg.SDKConfig, authManager), cfg: cfg, accessManager: accessManager, requestLogger: requestLogger, loggerToggle: toggle, configFilePath: configFilePath, currentPath: wd, envManagementSecret: envManagementSecret, wsRoutes: make(map[string]struct{}), } s.wsAuthEnabled.Store(cfg.WebsocketAuth) // Save initial YAML snapshot s.oldConfigYaml, _ = yaml.Marshal(cfg) s.applyAccessConfig(nil, cfg) if authManager != nil { authManager.SetRetryConfig(cfg.RequestRetry, time.Duration(cfg.MaxRetryInterval)*time.Second) } managementasset.SetCurrentConfig(cfg) auth.SetQuotaCooldownDisabled(cfg.DisableCooling) // Initialize management handler s.mgmt = managementHandlers.NewHandler(cfg, configFilePath, authManager) if optionState.localPassword != "" { s.mgmt.SetLocalPassword(optionState.localPassword) } logDir := filepath.Join(s.currentPath, "logs") if base := util.WritablePath(); base != "" { logDir = filepath.Join(base, "logs") } s.mgmt.SetLogDirectory(logDir) s.localPassword = optionState.localPassword
// Setup routes s.setupRoutes()
// Register Amp module using V2 interface with Context s.ampModule = ampmodule.NewLegacy(accessManager, AuthMiddleware(accessManager)) ctx := modules.Context{ Engine: engine, BaseHandler: s.handlers, Config: cfg, AuthMiddleware: AuthMiddleware(accessManager), } if err := modules.RegisterModule(ctx, s.ampModule); err != nil { log.Errorf("Failed to register Amp module: %v", err) }
// Apply additional router configurators from options if optionState.routerConfigurator != nil { optionState.routerConfigurator(engine, s.handlers, cfg) }
// Register management routes when configuration or environment secrets are available. hasManagementSecret := cfg.RemoteManagement.SecretKey != "" || envManagementSecret s.managementRoutesEnabled.Store(hasManagementSecret) if hasManagementSecret { s.registerManagementRoutes() }
if optionState.keepAliveEnabled { s.enableKeepAlive(optionState.keepAliveTimeout, optionState.keepAliveOnTimeout) }
// Create HTTP server s.server = &http.Server{ Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), Handler: engine, }
return s}
// setupRoutes configures the API routes for the server.// It defines the endpoints and associates them with their respective handlers.func (s *Server) setupRoutes() { s.engine.GET("/management.html", s.serveManagementControlPanel) openaiHandlers := openai.NewOpenAIAPIHandler(s.handlers) geminiHandlers := gemini.NewGeminiAPIHandler(s.handlers) geminiCLIHandlers := gemini.NewGeminiCLIAPIHandler(s.handlers) claudeCodeHandlers := claude.NewClaudeCodeAPIHandler(s.handlers) openaiResponsesHandlers := openai.NewOpenAIResponsesAPIHandler(s.handlers)
// OpenAI compatible API routes v1 := s.engine.Group("/v1") v1.Use(AuthMiddleware(s.accessManager)) { v1.GET("/models", s.unifiedModelsHandler(openaiHandlers, claudeCodeHandlers)) v1.POST("/chat/completions", openaiHandlers.ChatCompletions) v1.POST("/completions", openaiHandlers.Completions) v1.POST("/messages", claudeCodeHandlers.ClaudeMessages) v1.POST("/messages/count_tokens", claudeCodeHandlers.ClaudeCountTokens) v1.POST("/responses", openaiResponsesHandlers.Responses) }
// Gemini compatible API routes v1beta := s.engine.Group("/v1beta") v1beta.Use(AuthMiddleware(s.accessManager)) { v1beta.GET("/models", geminiHandlers.GeminiModels) v1beta.POST("/models/*action", geminiHandlers.GeminiHandler) v1beta.GET("/models/*action", geminiHandlers.GeminiGetHandler) }
// Root endpoint s.engine.GET("/", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "CLI Proxy API Server", "endpoints": []string{ "POST /v1/chat/completions", "POST /v1/completions", "GET /v1/models", }, }) })
// Event logging endpoint - handles Claude Code telemetry requests // Returns 200 OK to prevent 404 errors in logs s.engine.POST("/api/event_logging/batch", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"status": "ok"}) }) s.engine.POST("/v1internal:method", geminiCLIHandlers.CLIHandler)
// OAuth callback endpoints (reuse main server port) // These endpoints receive provider redirects and persist // the short-lived code/state for the waiting goroutine. s.engine.GET("/anthropic/callback", func(c *gin.Context) { code := c.Query("code") state := c.Query("state") errStr := c.Query("error") if errStr == "" { errStr = c.Query("error_description") } if state != "" { _, _ = managementHandlers.WriteOAuthCallbackFileForPendingSession(s.cfg.AuthDir, "anthropic", state, code, errStr) } c.Header("Content-Type", "text/html; charset=utf-8") c.String(http.StatusOK, oauthCallbackSuccessHTML) })
s.engine.GET("/codex/callback", func(c *gin.Context) { code := c.Query("code") state := c.Query("state") errStr := c.Query("error") if errStr == "" { errStr = c.Query("error_description") } if state != "" { _, _ = managementHandlers.WriteOAuthCallbackFileForPendingSession(s.cfg.AuthDir, "codex", state, code, errStr) } c.Header("Content-Type", "text/html; charset=utf-8") c.String(http.StatusOK, oauthCallbackSuccessHTML) })
s.engine.GET("/google/callback", func(c *gin.Context) { code := c.Query("code") state := c.Query("state") errStr := c.Query("error") if errStr == "" { errStr = c.Query("error_description") } if state != "" { _, _ = managementHandlers.WriteOAuthCallbackFileForPendingSession(s.cfg.AuthDir, "gemini", state, code, errStr) } c.Header("Content-Type", "text/html; charset=utf-8") c.String(http.StatusOK, oauthCallbackSuccessHTML) })
s.engine.GET("/iflow/callback", func(c *gin.Context) { code := c.Query("code") state := c.Query("state") errStr := c.Query("error") if errStr == "" { errStr = c.Query("error_description") } if state != "" { _, _ = managementHandlers.WriteOAuthCallbackFileForPendingSession(s.cfg.AuthDir, "iflow", state, code, errStr) } c.Header("Content-Type", "text/html; charset=utf-8") c.String(http.StatusOK, oauthCallbackSuccessHTML) })
s.engine.GET("/antigravity/callback", func(c *gin.Context) { code := c.Query("code") state := c.Query("state") errStr := c.Query("error") if errStr == "" { errStr = c.Query("error_description") } if state != "" { _, _ = managementHandlers.WriteOAuthCallbackFileForPendingSession(s.cfg.AuthDir, "antigravity", state, code, errStr) } c.Header("Content-Type", "text/html; charset=utf-8") c.String(http.StatusOK, oauthCallbackSuccessHTML) })
s.engine.GET("/kiro/callback", func(c *gin.Context) { code := c.Query("code") state := c.Query("state") errStr := c.Query("error") if errStr == "" { errStr = c.Query("error_description") } if state != "" { _, _ = managementHandlers.WriteOAuthCallbackFileForPendingSession(s.cfg.AuthDir, "kiro", state, code, errStr) } c.Header("Content-Type", "text/html; charset=utf-8") c.String(http.StatusOK, oauthCallbackSuccessHTML) })
// Management routes are registered lazily by registerManagementRoutes when a secret is configured.}
// AttachWebsocketRoute registers a websocket upgrade handler on the primary Gin engine.// The handler is served as-is without additional middleware beyond the standard stack already configured.func (s *Server) AttachWebsocketRoute(path string, handler http.Handler) { if s == nil || s.engine == nil || handler == nil { return } trimmed := strings.TrimSpace(path) if trimmed == "" { trimmed = "/v1/ws" } if !strings.HasPrefix(trimmed, "/") { trimmed = "/" + trimmed } s.wsRouteMu.Lock() if _, exists := s.wsRoutes[trimmed]; exists { s.wsRouteMu.Unlock() return } s.wsRoutes[trimmed] = struct{}{} s.wsRouteMu.Unlock()
authMiddleware := AuthMiddleware(s.accessManager) conditionalAuth := func(c *gin.Context) { if !s.wsAuthEnabled.Load() { c.Next() return } authMiddleware(c) } finalHandler := func(c *gin.Context) { handler.ServeHTTP(c.Writer, c.Request) c.Abort() }
s.engine.GET(trimmed, conditionalAuth, finalHandler)}
func (s *Server) registerManagementRoutes() { if s == nil || s.engine == nil || s.mgmt == nil { return } if !s.managementRoutesRegistered.CompareAndSwap(false, true) { return }
log.Info("management routes registered after secret key configuration")
mgmt := s.engine.Group("/v0/management") mgmt.Use(s.managementAvailabilityMiddleware(), s.mgmt.Middleware()) { mgmt.GET("/usage", s.mgmt.GetUsageStatistics) mgmt.GET("/usage/export", s.mgmt.ExportUsageStatistics) mgmt.POST("/usage/import", s.mgmt.ImportUsageStatistics) mgmt.GET("/config", s.mgmt.GetConfig) mgmt.GET("/config.yaml", s.mgmt.GetConfigYAML) mgmt.PUT("/config.yaml", s.mgmt.PutConfigYAML) mgmt.GET("/latest-version", s.mgmt.GetLatestVersion)
mgmt.GET("/debug", s.mgmt.GetDebug) mgmt.PUT("/debug", s.mgmt.PutDebug) mgmt.PATCH("/debug", s.mgmt.PutDebug)
mgmt.GET("/logging-to-file", s.mgmt.GetLoggingToFile) mgmt.PUT("/logging-to-file", s.mgmt.PutLoggingToFile) mgmt.PATCH("/logging-to-file", s.mgmt.PutLoggingToFile)
mgmt.GET("/usage-statistics-enabled", s.mgmt.GetUsageStatisticsEnabled) mgmt.PUT("/usage-statistics-enabled", s.mgmt.PutUsageStatisticsEnabled) mgmt.PATCH("/usage-statistics-enabled", s.mgmt.PutUsageStatisticsEnabled)
mgmt.GET("/proxy-url", s.mgmt.GetProxyURL) mgmt.PUT("/proxy-url", s.mgmt.PutProxyURL) mgmt.PATCH("/proxy-url", s.mgmt.PutProxyURL) mgmt.DELETE("/proxy-url", s.mgmt.DeleteProxyURL)
mgmt.POST("/api-call", s.mgmt.APICall)
mgmt.GET("/quota-exceeded/switch-project", s.mgmt.GetSwitchProject) mgmt.PUT("/quota-exceeded/switch-project", s.mgmt.PutSwitchProject) mgmt.PATCH("/quota-exceeded/switch-project", s.mgmt.PutSwitchProject)
mgmt.GET("/quota-exceeded/switch-preview-model", s.mgmt.GetSwitchPreviewModel) mgmt.PUT("/quota-exceeded/switch-preview-model", s.mgmt.PutSwitchPreviewModel) mgmt.PATCH("/quota-exceeded/switch-preview-model", s.mgmt.PutSwitchPreviewModel)
mgmt.GET("/api-keys", s.mgmt.GetAPIKeys) mgmt.PUT("/api-keys", s.mgmt.PutAPIKeys) mgmt.PATCH("/api-keys", s.mgmt.PatchAPIKeys) mgmt.DELETE("/api-keys", s.mgmt.DeleteAPIKeys)
mgmt.GET("/gemini-api-key", s.mgmt.GetGeminiKeys) mgmt.PUT("/gemini-api-key", s.mgmt.PutGeminiKeys) mgmt.PATCH("/gemini-api-key", s.mgmt.PatchGeminiKey) mgmt.DELETE("/gemini-api-key", s.mgmt.DeleteGeminiKey)
mgmt.GET("/logs", s.mgmt.GetLogs) mgmt.DELETE("/logs", s.mgmt.DeleteLogs) mgmt.GET("/request-error-logs", s.mgmt.GetRequestErrorLogs) mgmt.GET("/request-error-logs/:name", s.mgmt.DownloadRequestErrorLog) mgmt.GET("/request-log-by-id/:id", s.mgmt.GetRequestLogByID) mgmt.GET("/request-log", s.mgmt.GetRequestLog) mgmt.PUT("/request-log", s.mgmt.PutRequestLog) mgmt.PATCH("/request-log", s.mgmt.PutRequestLog) mgmt.GET("/ws-auth", s.mgmt.GetWebsocketAuth) mgmt.PUT("/ws-auth", s.mgmt.PutWebsocketAuth) mgmt.PATCH("/ws-auth", s.mgmt.PutWebsocketAuth)
mgmt.GET("/ampcode", s.mgmt.GetAmpCode) mgmt.GET("/ampcode/upstream-url", s.mgmt.GetAmpUpstreamURL) mgmt.PUT("/ampcode/upstream-url", s.mgmt.PutAmpUpstreamURL) mgmt.PATCH("/ampcode/upstream-url", s.mgmt.PutAmpUpstreamURL) mgmt.DELETE("/ampcode/upstream-url", s.mgmt.DeleteAmpUpstreamURL) mgmt.GET("/ampcode/upstream-api-key", s.mgmt.GetAmpUpstreamAPIKey) mgmt.PUT("/ampcode/upstream-api-key", s.mgmt.PutAmpUpstreamAPIKey) mgmt.PATCH("/ampcode/upstream-api-key", s.mgmt.PutAmpUpstreamAPIKey) mgmt.DELETE("/ampcode/upstream-api-key", s.mgmt.DeleteAmpUpstreamAPIKey) mgmt.GET("/ampcode/restrict-management-to-localhost", s.mgmt.GetAmpRestrictManagementToLocalhost) mgmt.PUT("/ampcode/restrict-management-to-localhost", s.mgmt.PutAmpRestrictManagementToLocalhost) mgmt.PATCH("/ampcode/restrict-management-to-localhost", s.mgmt.PutAmpRestrictManagementToLocalhost) mgmt.GET("/ampcode/model-mappings", s.mgmt.GetAmpModelMappings) mgmt.PUT("/ampcode/model-mappings", s.mgmt.PutAmpModelMappings) mgmt.PATCH("/ampcode/model-mappings", s.mgmt.PatchAmpModelMappings) mgmt.DELETE("/ampcode/model-mappings", s.mgmt.DeleteAmpModelMappings) mgmt.GET("/ampcode/force-model-mappings", s.mgmt.GetAmpForceModelMappings) mgmt.PUT("/ampcode/force-model-mappings", s.mgmt.PutAmpForceModelMappings) mgmt.PATCH("/ampcode/force-model-mappings", s.mgmt.PutAmpForceModelMappings) mgmt.GET("/ampcode/upstream-api-keys", s.mgmt.GetAmpUpstreamAPIKeys) mgmt.PUT("/ampcode/upstream-api-keys", s.mgmt.PutAmpUpstreamAPIKeys) mgmt.PATCH("/ampcode/upstream-api-keys", s.mgmt.PatchAmpUpstreamAPIKeys) mgmt.DELETE("/ampcode/upstream-api-keys", s.mgmt.DeleteAmpUpstreamAPIKeys)
mgmt.GET("/request-retry", s.mgmt.GetRequestRetry) mgmt.PUT("/request-retry", s.mgmt.PutRequestRetry) mgmt.PATCH("/request-retry", s.mgmt.PutRequestRetry) mgmt.GET("/max-retry-interval", s.mgmt.GetMaxRetryInterval) mgmt.PUT("/max-retry-interval", s.mgmt.PutMaxRetryInterval) mgmt.PATCH("/max-retry-interval", s.mgmt.PutMaxRetryInterval)
mgmt.GET("/claude-api-key", s.mgmt.GetClaudeKeys) mgmt.PUT("/claude-api-key", s.mgmt.PutClaudeKeys) mgmt.PATCH("/claude-api-key", s.mgmt.PatchClaudeKey) mgmt.DELETE("/claude-api-key", s.mgmt.DeleteClaudeKey)
mgmt.GET("/codex-api-key", s.mgmt.GetCodexKeys) mgmt.PUT("/codex-api-key", s.mgmt.PutCodexKeys) mgmt.PATCH("/codex-api-key", s.mgmt.PatchCodexKey) mgmt.DELETE("/codex-api-key", s.mgmt.DeleteCodexKey)
mgmt.GET("/openai-compatibility", s.mgmt.GetOpenAICompat) mgmt.PUT("/openai-compatibility", s.mgmt.PutOpenAICompat) mgmt.PATCH("/openai-compatibility", s.mgmt.PatchOpenAICompat) mgmt.DELETE("/openai-compatibility", s.mgmt.DeleteOpenAICompat)
mgmt.GET("/oauth-excluded-models", s.mgmt.GetOAuthExcludedModels) mgmt.PUT("/oauth-excluded-models", s.mgmt.PutOAuthExcludedModels) mgmt.PATCH("/oauth-excluded-models", s.mgmt.PatchOAuthExcludedModels) mgmt.DELETE("/oauth-excluded-models", s.mgmt.DeleteOAuthExcludedModels)
mgmt.GET("/auth-files", s.mgmt.ListAuthFiles) mgmt.GET("/auth-files/models", s.mgmt.GetAuthFileModels) mgmt.GET("/auth-files/download", s.mgmt.DownloadAuthFile) mgmt.POST("/auth-files", s.mgmt.UploadAuthFile) mgmt.DELETE("/auth-files", s.mgmt.DeleteAuthFile) mgmt.POST("/vertex/import", s.mgmt.ImportVertexCredential)
mgmt.GET("/anthropic-auth-url", s.mgmt.RequestAnthropicToken) mgmt.GET("/codex-auth-url", s.mgmt.RequestCodexToken) mgmt.GET("/gemini-cli-auth-url", s.mgmt.RequestGeminiCLIToken) mgmt.GET("/antigravity-auth-url", s.mgmt.RequestAntigravityToken) mgmt.GET("/qwen-auth-url", s.mgmt.RequestQwenToken) mgmt.GET("/iflow-auth-url", s.mgmt.RequestIFlowToken) mgmt.POST("/iflow-auth-url", s.mgmt.RequestIFlowCookieToken) mgmt.GET("/kiro-auth-url", s.mgmt.RequestKiroToken) mgmt.POST("/oauth-callback", s.mgmt.PostOAuthCallback) mgmt.GET("/get-auth-status", s.mgmt.GetAuthStatus) }}
func (s *Server) managementAvailabilityMiddleware() gin.HandlerFunc { return func(c *gin.Context) { if !s.managementRoutesEnabled.Load() { c.AbortWithStatus(http.StatusNotFound) return } c.Next() }}
func (s *Server) serveManagementControlPanel(c *gin.Context) { cfg := s.cfg if cfg == nil || cfg.RemoteManagement.DisableControlPanel { c.AbortWithStatus(http.StatusNotFound) return } filePath := managementasset.FilePath(s.configFilePath) if strings.TrimSpace(filePath) == "" { c.AbortWithStatus(http.StatusNotFound) return }
if _, err := os.Stat(filePath); err != nil { if os.IsNotExist(err) { go managementasset.EnsureLatestManagementHTML(context.Background(), managementasset.StaticDir(s.configFilePath), cfg.ProxyURL, cfg.RemoteManagement.PanelGitHubRepository) c.AbortWithStatus(http.StatusNotFound) return }
log.WithError(err).Error("failed to stat management control panel asset") c.AbortWithStatus(http.StatusInternalServerError) return }
c.File(filePath)}
func (s *Server) enableKeepAlive(timeout time.Duration, onTimeout func()) { if timeout <= 0 || onTimeout == nil { return }
s.keepAliveEnabled = true s.keepAliveTimeout = timeout s.keepAliveOnTimeout = onTimeout s.keepAliveHeartbeat = make(chan struct{}, 1) s.keepAliveStop = make(chan struct{}, 1)
s.engine.GET("/keep-alive", s.handleKeepAlive)
go s.watchKeepAlive()}
func (s *Server) handleKeepAlive(c *gin.Context) { if s.localPassword != "" { provided := strings.TrimSpace(c.GetHeader("Authorization")) if provided != "" { parts := strings.SplitN(provided, " ", 2) if len(parts) == 2 && strings.EqualFold(parts[0], "bearer") { provided = parts[1] } } if provided == "" { provided = strings.TrimSpace(c.GetHeader("X-Local-Password")) } if subtle.ConstantTimeCompare([]byte(provided), []byte(s.localPassword)) != 1 { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid password"}) return } }
s.signalKeepAlive() c.JSON(http.StatusOK, gin.H{"status": "ok"})}
func (s *Server) signalKeepAlive() { if !s.keepAliveEnabled { return } select { case s.keepAliveHeartbeat <- struct{}{}: default: }}
func (s *Server) watchKeepAlive() { if !s.keepAliveEnabled { return }
timer := time.NewTimer(s.keepAliveTimeout) defer timer.Stop()
for { select { case <-timer.C: log.Warnf("keep-alive endpoint idle for %s, shutting down", s.keepAliveTimeout) if s.keepAliveOnTimeout != nil { s.keepAliveOnTimeout() } return case <-s.keepAliveHeartbeat: if !timer.Stop() { select { case <-timer.C: default: } } timer.Reset(s.keepAliveTimeout) case <-s.keepAliveStop: return } }}
// unifiedModelsHandler creates a unified handler for the /v1/models endpoint// that routes to different handlers based on the User-Agent header.// If User-Agent starts with "claude-cli", it routes to Claude handler,// otherwise it routes to OpenAI handler.func (s *Server) unifiedModelsHandler(openaiHandler *openai.OpenAIAPIHandler, claudeHandler *claude.ClaudeCodeAPIHandler) gin.HandlerFunc { return func(c *gin.Context) { userAgent := c.GetHeader("User-Agent")
// Route to Claude handler if User-Agent starts with "claude-cli" if strings.HasPrefix(userAgent, "claude-cli") { // log.Debugf("Routing /v1/models to Claude handler for User-Agent: %s", userAgent) claudeHandler.ClaudeModels(c) } else { // log.Debugf("Routing /v1/models to OpenAI handler for User-Agent: %s", userAgent) openaiHandler.OpenAIModels(c) } }}
// Start begins listening for and serving HTTP or HTTPS requests.// It's a blocking call and will only return on an unrecoverable error.//// Returns:// - error: An error if the server fails to startfunc (s *Server) Start() error { if s == nil || s.server == nil { return fmt.Errorf("failed to start HTTP server: server not initialized") }
useTLS := s.cfg != nil && s.cfg.TLS.Enable if useTLS { cert := strings.TrimSpace(s.cfg.TLS.Cert) key := strings.TrimSpace(s.cfg.TLS.Key) if cert == "" || key == "" { return fmt.Errorf("failed to start HTTPS server: tls.cert or tls.key is empty") } log.Debugf("Starting API server on %s with TLS", s.server.Addr) if errServeTLS := s.server.ListenAndServeTLS(cert, key); errServeTLS != nil && !errors.Is(errServeTLS, http.ErrServerClosed) { return fmt.Errorf("failed to start HTTPS server: %v", errServeTLS) } return nil }
log.Debugf("Starting API server on %s", s.server.Addr) if errServe := s.server.ListenAndServe(); errServe != nil && !errors.Is(errServe, http.ErrServerClosed) { return fmt.Errorf("failed to start HTTP server: %v", errServe) }
return nil}
// Stop gracefully shuts down the API server without interrupting any// active connections.//// Parameters:// - ctx: The context for graceful shutdown//// Returns:// - error: An error if the server fails to stopfunc (s *Server) Stop(ctx context.Context) error { log.Debug("Stopping API server...")
if s.keepAliveEnabled { select { case s.keepAliveStop <- struct{}{}: default: } }
// Shutdown the HTTP server. if err := s.server.Shutdown(ctx); err != nil { return fmt.Errorf("failed to shutdown HTTP server: %v", err) }
log.Debug("API server stopped") return nil}
// corsMiddleware returns a Gin middleware handler that adds CORS headers// to every response, allowing cross-origin requests.//// Returns:// - gin.HandlerFunc: The CORS middleware handlerfunc corsMiddleware() gin.HandlerFunc { return func(c *gin.Context) { c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS") c.Header("Access-Control-Allow-Headers", "*")
if c.Request.Method == "OPTIONS" { c.AbortWithStatus(http.StatusNoContent) return }
c.Next() }}
func (s *Server) applyAccessConfig(oldCfg, newCfg *config.Config) { if s == nil || s.accessManager == nil || newCfg == nil { return } if _, err := access.ApplyAccessProviders(s.accessManager, oldCfg, newCfg); err != nil { return }}
// UpdateClients updates the server's client list and configuration.// This method is called when the configuration or authentication tokens change.//// Parameters:// - clients: The new slice of AI service clients// - cfg: The new application configurationfunc (s *Server) UpdateClients(cfg *config.Config) { // Reconstruct old config from YAML snapshot to avoid reference sharing issues var oldCfg *config.Config if len(s.oldConfigYaml) > 0 { _ = yaml.Unmarshal(s.oldConfigYaml, &oldCfg) }
// Update request logger enabled state if it has changed previousRequestLog := false if oldCfg != nil { previousRequestLog = oldCfg.RequestLog } if s.requestLogger != nil && (oldCfg == nil || previousRequestLog != cfg.RequestLog) { if s.loggerToggle != nil { s.loggerToggle(cfg.RequestLog) } else if toggler, ok := s.requestLogger.(interface{ SetEnabled(bool) }); ok { toggler.SetEnabled(cfg.RequestLog) } if oldCfg != nil { log.Debugf("request logging updated from %t to %t", previousRequestLog, cfg.RequestLog) } else { log.Debugf("request logging toggled to %t", cfg.RequestLog) } }
if oldCfg == nil || oldCfg.LoggingToFile != cfg.LoggingToFile || oldCfg.LogsMaxTotalSizeMB != cfg.LogsMaxTotalSizeMB { if err := logging.ConfigureLogOutput(cfg); err != nil { log.Errorf("failed to reconfigure log output: %v", err) } else { if oldCfg == nil { log.Debug("log output configuration refreshed") } else { if oldCfg.LoggingToFile != cfg.LoggingToFile { log.Debugf("logging_to_file updated from %t to %t", oldCfg.LoggingToFile, cfg.LoggingToFile) } if oldCfg.LogsMaxTotalSizeMB != cfg.LogsMaxTotalSizeMB { log.Debugf("logs_max_total_size_mb updated from %d to %d", oldCfg.LogsMaxTotalSizeMB, cfg.LogsMaxTotalSizeMB) } } } }
if oldCfg == nil || oldCfg.UsageStatisticsEnabled != cfg.UsageStatisticsEnabled { usage.SetStatisticsEnabled(cfg.UsageStatisticsEnabled) if oldCfg != nil { log.Debugf("usage_statistics_enabled updated from %t to %t", oldCfg.UsageStatisticsEnabled, cfg.UsageStatisticsEnabled) } else { log.Debugf("usage_statistics_enabled toggled to %t", cfg.UsageStatisticsEnabled) } }
if oldCfg == nil || oldCfg.DisableCooling != cfg.DisableCooling { auth.SetQuotaCooldownDisabled(cfg.DisableCooling) if oldCfg != nil { log.Debugf("disable_cooling updated from %t to %t", oldCfg.DisableCooling, cfg.DisableCooling) } else { log.Debugf("disable_cooling toggled to %t", cfg.DisableCooling) } } if s.handlers != nil && s.handlers.AuthManager != nil { s.handlers.AuthManager.SetRetryConfig(cfg.RequestRetry, time.Duration(cfg.MaxRetryInterval)*time.Second) }
// Update log level dynamically when debug flag changes if oldCfg == nil || oldCfg.Debug != cfg.Debug { util.SetLogLevel(cfg) if oldCfg != nil { log.Debugf("debug mode updated from %t to %t", oldCfg.Debug, cfg.Debug) } else { log.Debugf("debug mode toggled to %t", cfg.Debug) } }
prevSecretEmpty := true if oldCfg != nil { prevSecretEmpty = oldCfg.RemoteManagement.SecretKey == "" } newSecretEmpty := cfg.RemoteManagement.SecretKey == "" if s.envManagementSecret { s.registerManagementRoutes() if s.managementRoutesEnabled.CompareAndSwap(false, true) { log.Info("management routes enabled via MANAGEMENT_PASSWORD") } else { s.managementRoutesEnabled.Store(true) } } else { switch { case prevSecretEmpty && !newSecretEmpty: s.registerManagementRoutes() if s.managementRoutesEnabled.CompareAndSwap(false, true) { log.Info("management routes enabled after secret key update") } else { s.managementRoutesEnabled.Store(true) } case !prevSecretEmpty && newSecretEmpty: if s.managementRoutesEnabled.CompareAndSwap(true, false) { log.Info("management routes disabled after secret key removal") } else { s.managementRoutesEnabled.Store(false) } default: s.managementRoutesEnabled.Store(!newSecretEmpty) } }
s.applyAccessConfig(oldCfg, cfg) s.cfg = cfg s.wsAuthEnabled.Store(cfg.WebsocketAuth) if oldCfg != nil && s.wsAuthChanged != nil && oldCfg.WebsocketAuth != cfg.WebsocketAuth { s.wsAuthChanged(oldCfg.WebsocketAuth, cfg.WebsocketAuth) } managementasset.SetCurrentConfig(cfg) // Save YAML snapshot for next comparison s.oldConfigYaml, _ = yaml.Marshal(cfg)
s.handlers.UpdateClients(&cfg.SDKConfig)
if !cfg.RemoteManagement.DisableControlPanel { staticDir := managementasset.StaticDir(s.configFilePath) go managementasset.EnsureLatestManagementHTML(context.Background(), staticDir, cfg.ProxyURL, cfg.RemoteManagement.PanelGitHubRepository) } if s.mgmt != nil { s.mgmt.SetConfig(cfg) s.mgmt.SetAuthManager(s.handlers.AuthManager) }
// Notify Amp module of config changes (for model mapping hot-reload) if s.ampModule != nil { log.Debugf("triggering amp module config update") if err := s.ampModule.OnConfigUpdated(cfg); err != nil { log.Errorf("failed to update Amp module config: %v", err) } } else { log.Warnf("amp module is nil, skipping config update") }
// Count client sources from configuration and auth directory authFiles := util.CountAuthFiles(cfg.AuthDir) geminiAPIKeyCount := len(cfg.GeminiKey) claudeAPIKeyCount := len(cfg.ClaudeKey) codexAPIKeyCount := len(cfg.CodexKey) vertexAICompatCount := len(cfg.VertexCompatAPIKey) openAICompatCount := 0 for i := range cfg.OpenAICompatibility { entry := cfg.OpenAICompatibility[i] openAICompatCount += len(entry.APIKeyEntries) }
total := authFiles + geminiAPIKeyCount + claudeAPIKeyCount + codexAPIKeyCount + vertexAICompatCount + openAICompatCount fmt.Printf("server clients and configuration updated: %d clients (%d auth files + %d Gemini API keys + %d Claude API keys + %d Codex keys + %d Vertex-compat + %d OpenAI-compat)\n", total, authFiles, geminiAPIKeyCount, claudeAPIKeyCount, codexAPIKeyCount, vertexAICompatCount, openAICompatCount, )}
func (s *Server) SetWebsocketAuthChangeHandler(fn func(bool, bool)) { if s == nil { return } s.wsAuthChanged = fn}
// (management handlers moved to internal/api/handlers/management)
// AuthMiddleware returns a Gin middleware handler that authenticates requests// using the configured authentication providers. When no providers are available,// it allows all requests (legacy behaviour).func AuthMiddleware(manager *sdkaccess.Manager) gin.HandlerFunc { return func(c *gin.Context) { if manager == nil { c.Next() return }
result, err := manager.Authenticate(c.Request.Context(), c.Request) if err == nil { if result != nil { c.Set("apiKey", result.Principal) c.Set("accessProvider", result.Provider) if len(result.Metadata) > 0 { c.Set("accessMetadata", result.Metadata) } } c.Next() return }
switch { case errors.Is(err, sdkaccess.ErrNoCredentials): c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Missing API key"}) case errors.Is(err, sdkaccess.ErrInvalidCredential): c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid API key"}) default: log.Errorf("authentication middleware error: %v", err) c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Authentication service error"}) } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111package api
import ( "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing"
gin "github.com/gin-gonic/gin" proxyconfig "github.com/router-for-me/CLIProxyAPI/v6/internal/config" sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access" "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth" sdkconfig "github.com/router-for-me/CLIProxyAPI/v6/sdk/config")
func newTestServer(t *testing.T) *Server { t.Helper()
gin.SetMode(gin.TestMode)
tmpDir := t.TempDir() authDir := filepath.Join(tmpDir, "auth") if err := os.MkdirAll(authDir, 0o700); err != nil { t.Fatalf("failed to create auth dir: %v", err) }
cfg := &proxyconfig.Config{ SDKConfig: sdkconfig.SDKConfig{ APIKeys: []string{"test-key"}, }, Port: 0, AuthDir: authDir, Debug: true, LoggingToFile: false, UsageStatisticsEnabled: false, }
authManager := auth.NewManager(nil, nil, nil) accessManager := sdkaccess.NewManager()
configPath := filepath.Join(tmpDir, "config.yaml") return NewServer(cfg, authManager, accessManager, configPath)}
func TestAmpProviderModelRoutes(t *testing.T) { testCases := []struct { name string path string wantStatus int wantContains string }{ { name: "openai root models", path: "/api/provider/openai/models", wantStatus: http.StatusOK, wantContains: `"object":"list"`, }, { name: "groq root models", path: "/api/provider/groq/models", wantStatus: http.StatusOK, wantContains: `"object":"list"`, }, { name: "openai models", path: "/api/provider/openai/v1/models", wantStatus: http.StatusOK, wantContains: `"object":"list"`, }, { name: "anthropic models", path: "/api/provider/anthropic/v1/models", wantStatus: http.StatusOK, wantContains: `"data"`, }, { name: "google models v1", path: "/api/provider/google/v1/models", wantStatus: http.StatusOK, wantContains: `"models"`, }, { name: "google models v1beta", path: "/api/provider/google/v1beta/models", wantStatus: http.StatusOK, wantContains: `"models"`, }, }
for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { server := newTestServer(t)
req := httptest.NewRequest(http.MethodGet, tc.path, nil) req.Header.Set("Authorization", "Bearer test-key")
rr := httptest.NewRecorder() server.engine.ServeHTTP(rr, req)
if rr.Code != tc.wantStatus { t.Fatalf("unexpected status code for %s: got %d want %d; body=%s", tc.path, rr.Code, tc.wantStatus, rr.Body.String()) } if body := rr.Body.String(); !strings.Contains(body, tc.wantContains) { t.Fatalf("response body for %s missing %q: %s", tc.path, tc.wantContains, body) } }) }}1234567891011121314151617181920212223242526272829303132package claude
// PKCECodes holds PKCE verification codes for OAuth2 PKCE flowtype PKCECodes struct { // CodeVerifier is the cryptographically random string used to correlate // the authorization request to the token request CodeVerifier string `json:"code_verifier"` // CodeChallenge is the SHA256 hash of the code verifier, base64url-encoded CodeChallenge string `json:"code_challenge"`}
// ClaudeTokenData holds OAuth token information from Anthropictype ClaudeTokenData struct { // AccessToken is the OAuth2 access token for API access AccessToken string `json:"access_token"` // RefreshToken is used to obtain new access tokens RefreshToken string `json:"refresh_token"` // Email is the Anthropic account email Email string `json:"email"` // Expire is the timestamp of the token expire Expire string `json:"expired"`}
// ClaudeAuthBundle aggregates authentication data after OAuth flow completiontype ClaudeAuthBundle struct { // APIKey is the Anthropic API key obtained from token exchange APIKey string `json:"api_key"` // TokenData contains the OAuth tokens from the authentication flow TokenData ClaudeTokenData `json:"token_data"` // LastRefresh is the timestamp of the last token refresh LastRefresh string `json:"last_refresh"`}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346// Package claude provides OAuth2 authentication functionality for Anthropic's Claude API.// This package implements the complete OAuth2 flow with PKCE (Proof Key for Code Exchange)// for secure authentication with Claude API, including token exchange, refresh, and storage.package claude
import ( "context" "encoding/json" "fmt" "io" "net/http" "net/url" "strings" "time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config" "github.com/router-for-me/CLIProxyAPI/v6/internal/util" log "github.com/sirupsen/logrus")
const ( anthropicAuthURL = "https://claude.ai/oauth/authorize" anthropicTokenURL = "https://console.anthropic.com/v1/oauth/token" anthropicClientID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e" redirectURI = "http://localhost:54545/callback")
// tokenResponse represents the response structure from Anthropic's OAuth token endpoint.// It contains access token, refresh token, and associated user/organization information.type tokenResponse struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` TokenType string `json:"token_type"` ExpiresIn int `json:"expires_in"` Organization struct { UUID string `json:"uuid"` Name string `json:"name"` } `json:"organization"` Account struct { UUID string `json:"uuid"` EmailAddress string `json:"email_address"` } `json:"account"`}
// ClaudeAuth handles Anthropic OAuth2 authentication flow.// It provides methods for generating authorization URLs, exchanging codes for tokens,// and refreshing expired tokens using PKCE for enhanced security.type ClaudeAuth struct { httpClient *http.Client}
// NewClaudeAuth creates a new Anthropic authentication service.// It initializes the HTTP client with proxy settings from the configuration.//// Parameters:// - cfg: The application configuration containing proxy settings//// Returns:// - *ClaudeAuth: A new Claude authentication service instancefunc NewClaudeAuth(cfg *config.Config) *ClaudeAuth { return &ClaudeAuth{ httpClient: util.SetProxy(&cfg.SDKConfig, &http.Client{}), }}
// GenerateAuthURL creates the OAuth authorization URL with PKCE.// This method generates a secure authorization URL including PKCE challenge codes// for the OAuth2 flow with Anthropic's API.//// Parameters:// - state: A random state parameter for CSRF protection// - pkceCodes: The PKCE codes for secure code exchange//// Returns:// - string: The complete authorization URL// - string: The state parameter for verification// - error: An error if PKCE codes are missing or URL generation failsfunc (o *ClaudeAuth) GenerateAuthURL(state string, pkceCodes *PKCECodes) (string, string, error) { if pkceCodes == nil { return "", "", fmt.Errorf("PKCE codes are required") }
params := url.Values{ "code": {"true"}, "client_id": {anthropicClientID}, "response_type": {"code"}, "redirect_uri": {redirectURI}, "scope": {"org:create_api_key user:profile user:inference"}, "code_challenge": {pkceCodes.CodeChallenge}, "code_challenge_method": {"S256"}, "state": {state}, }
authURL := fmt.Sprintf("%s?%s", anthropicAuthURL, params.Encode()) return authURL, state, nil}
// parseCodeAndState extracts the authorization code and state from the callback response.// It handles the parsing of the code parameter which may contain additional fragments.//// Parameters:// - code: The raw code parameter from the OAuth callback//// Returns:// - parsedCode: The extracted authorization code// - parsedState: The extracted state parameter if presentfunc (c *ClaudeAuth) parseCodeAndState(code string) (parsedCode, parsedState string) { splits := strings.Split(code, "#") parsedCode = splits[0] if len(splits) > 1 { parsedState = splits[1] } return}
// ExchangeCodeForTokens exchanges authorization code for access tokens.// This method implements the OAuth2 token exchange flow using PKCE for security.// It sends the authorization code along with PKCE verifier to get access and refresh tokens.//// Parameters:// - ctx: The context for the request// - code: The authorization code received from OAuth callback// - state: The state parameter for verification// - pkceCodes: The PKCE codes for secure verification//// Returns:// - *ClaudeAuthBundle: The complete authentication bundle with tokens// - error: An error if token exchange failsfunc (o *ClaudeAuth) ExchangeCodeForTokens(ctx context.Context, code, state string, pkceCodes *PKCECodes) (*ClaudeAuthBundle, error) { if pkceCodes == nil { return nil, fmt.Errorf("PKCE codes are required for token exchange") } newCode, newState := o.parseCodeAndState(code)
// Prepare token exchange request reqBody := map[string]interface{}{ "code": newCode, "state": state, "grant_type": "authorization_code", "client_id": anthropicClientID, "redirect_uri": redirectURI, "code_verifier": pkceCodes.CodeVerifier, }
// Include state if present if newState != "" { reqBody["state"] = newState }
jsonBody, err := json.Marshal(reqBody) if err != nil { return nil, fmt.Errorf("failed to marshal request body: %w", err) }
// log.Debugf("Token exchange request: %s", string(jsonBody))
req, err := http.NewRequestWithContext(ctx, "POST", anthropicTokenURL, strings.NewReader(string(jsonBody))) if err != nil { return nil, fmt.Errorf("failed to create token request: %w", err) } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json")
resp, err := o.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("token exchange request failed: %w", err) } defer func() { if errClose := resp.Body.Close(); errClose != nil { log.Errorf("failed to close response body: %v", errClose) } }()
body, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("failed to read token response: %w", err) } // log.Debugf("Token response: %s", string(body))
if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("token exchange failed with status %d: %s", resp.StatusCode, string(body)) } // log.Debugf("Token response: %s", string(body))
var tokenResp tokenResponse if err = json.Unmarshal(body, &tokenResp); err != nil { return nil, fmt.Errorf("failed to parse token response: %w", err) }
// Create token data tokenData := ClaudeTokenData{ AccessToken: tokenResp.AccessToken, RefreshToken: tokenResp.RefreshToken, Email: tokenResp.Account.EmailAddress, Expire: time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second).Format(time.RFC3339), }
// Create auth bundle bundle := &ClaudeAuthBundle{ TokenData: tokenData, LastRefresh: time.Now().Format(time.RFC3339), }
return bundle, nil}
// RefreshTokens refreshes the access token using the refresh token.// This method exchanges a valid refresh token for a new access token,// extending the user's authenticated session.//// Parameters:// - ctx: The context for the request// - refreshToken: The refresh token to use for getting new access token//// Returns:// - *ClaudeTokenData: The new token data with updated access token// - error: An error if token refresh failsfunc (o *ClaudeAuth) RefreshTokens(ctx context.Context, refreshToken string) (*ClaudeTokenData, error) { if refreshToken == "" { return nil, fmt.Errorf("refresh token is required") }
reqBody := map[string]interface{}{ "client_id": anthropicClientID, "grant_type": "refresh_token", "refresh_token": refreshToken, }
jsonBody, err := json.Marshal(reqBody) if err != nil { return nil, fmt.Errorf("failed to marshal request body: %w", err) }
req, err := http.NewRequestWithContext(ctx, "POST", anthropicTokenURL, strings.NewReader(string(jsonBody))) if err != nil { return nil, fmt.Errorf("failed to create refresh request: %w", err) }
req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json")
resp, err := o.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("token refresh request failed: %w", err) } defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("failed to read refresh response: %w", err) }
if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("token refresh failed with status %d: %s", resp.StatusCode, string(body)) }
// log.Debugf("Token response: %s", string(body))
var tokenResp tokenResponse if err = json.Unmarshal(body, &tokenResp); err != nil { return nil, fmt.Errorf("failed to parse token response: %w", err) }
// Create token data return &ClaudeTokenData{ AccessToken: tokenResp.AccessToken, RefreshToken: tokenResp.RefreshToken, Email: tokenResp.Account.EmailAddress, Expire: time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second).Format(time.RFC3339), }, nil}
// CreateTokenStorage creates a new ClaudeTokenStorage from auth bundle and user info.// This method converts the authentication bundle into a token storage structure// suitable for persistence and later use.//// Parameters:// - bundle: The authentication bundle containing token data//// Returns:// - *ClaudeTokenStorage: A new token storage instancefunc (o *ClaudeAuth) CreateTokenStorage(bundle *ClaudeAuthBundle) *ClaudeTokenStorage { storage := &ClaudeTokenStorage{ AccessToken: bundle.TokenData.AccessToken, RefreshToken: bundle.TokenData.RefreshToken, LastRefresh: bundle.LastRefresh, Email: bundle.TokenData.Email, Expire: bundle.TokenData.Expire, }
return storage}
// RefreshTokensWithRetry refreshes tokens with automatic retry logic.// This method implements exponential backoff retry logic for token refresh operations,// providing resilience against temporary network or service issues.//// Parameters:// - ctx: The context for the request// - refreshToken: The refresh token to use// - maxRetries: The maximum number of retry attempts//// Returns:// - *ClaudeTokenData: The refreshed token data// - error: An error if all retry attempts failfunc (o *ClaudeAuth) RefreshTokensWithRetry(ctx context.Context, refreshToken string, maxRetries int) (*ClaudeTokenData, error) { var lastErr error
for attempt := 0; attempt < maxRetries; attempt++ { if attempt > 0 { // Wait before retry select { case <-ctx.Done(): return nil, ctx.Err() case <-time.After(time.Duration(attempt) * time.Second): } }
tokenData, err := o.RefreshTokens(ctx, refreshToken) if err == nil { return tokenData, nil }
lastErr = err log.Warnf("Token refresh attempt %d failed: %v", attempt+1, err) }
return nil, fmt.Errorf("token refresh failed after %d attempts: %w", maxRetries, lastErr)}
// UpdateTokenStorage updates an existing token storage with new token data.// This method refreshes the token storage with newly obtained access and refresh tokens,// updating timestamps and expiration information.//// Parameters:// - storage: The existing token storage to update// - tokenData: The new token data to applyfunc (o *ClaudeAuth) UpdateTokenStorage(storage *ClaudeTokenStorage, tokenData *ClaudeTokenData) { storage.AccessToken = tokenData.AccessToken storage.RefreshToken = tokenData.RefreshToken storage.LastRefresh = time.Now().Format(time.RFC3339) storage.Email = tokenData.Email storage.Expire = tokenData.Expire}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167// Package claude provides authentication and token management functionality// for Anthropic's Claude AI services. It handles OAuth2 token storage, serialization,// and retrieval for maintaining authenticated sessions with the Claude API.package claude
import ( "errors" "fmt" "net/http")
// OAuthError represents an OAuth-specific error.type OAuthError struct { // Code is the OAuth error code. Code string `json:"error"` // Description is a human-readable description of the error. Description string `json:"error_description,omitempty"` // URI is a URI identifying a human-readable web page with information about the error. URI string `json:"error_uri,omitempty"` // StatusCode is the HTTP status code associated with the error. StatusCode int `json:"-"`}
// Error returns a string representation of the OAuth error.func (e *OAuthError) Error() string { if e.Description != "" { return fmt.Sprintf("OAuth error %s: %s", e.Code, e.Description) } return fmt.Sprintf("OAuth error: %s", e.Code)}
// NewOAuthError creates a new OAuth error with the specified code, description, and status code.func NewOAuthError(code, description string, statusCode int) *OAuthError { return &OAuthError{ Code: code, Description: description, StatusCode: statusCode, }}
// AuthenticationError represents authentication-related errors.type AuthenticationError struct { // Type is the type of authentication error. Type string `json:"type"` // Message is a human-readable message describing the error. Message string `json:"message"` // Code is the HTTP status code associated with the error. Code int `json:"code"` // Cause is the underlying error that caused this authentication error. Cause error `json:"-"`}
// Error returns a string representation of the authentication error.func (e *AuthenticationError) Error() string { if e.Cause != nil { return fmt.Sprintf("%s: %s (caused by: %v)", e.Type, e.Message, e.Cause) } return fmt.Sprintf("%s: %s", e.Type, e.Message)}
// Common authentication error types.var ( // ErrTokenExpired = &AuthenticationError{ // Type: "token_expired", // Message: "Access token has expired", // Code: http.StatusUnauthorized, // }
// ErrInvalidState represents an error for invalid OAuth state parameter. ErrInvalidState = &AuthenticationError{ Type: "invalid_state", Message: "OAuth state parameter is invalid", Code: http.StatusBadRequest, }
// ErrCodeExchangeFailed represents an error when exchanging authorization code for tokens fails. ErrCodeExchangeFailed = &AuthenticationError{ Type: "code_exchange_failed", Message: "Failed to exchange authorization code for tokens", Code: http.StatusBadRequest, }
// ErrServerStartFailed represents an error when starting the OAuth callback server fails. ErrServerStartFailed = &AuthenticationError{ Type: "server_start_failed", Message: "Failed to start OAuth callback server", Code: http.StatusInternalServerError, }
// ErrPortInUse represents an error when the OAuth callback port is already in use. ErrPortInUse = &AuthenticationError{ Type: "port_in_use", Message: "OAuth callback port is already in use", Code: 13, // Special exit code for port-in-use }
// ErrCallbackTimeout represents an error when waiting for OAuth callback times out. ErrCallbackTimeout = &AuthenticationError{ Type: "callback_timeout", Message: "Timeout waiting for OAuth callback", Code: http.StatusRequestTimeout, })
// NewAuthenticationError creates a new authentication error with a cause based on a base error.func NewAuthenticationError(baseErr *AuthenticationError, cause error) *AuthenticationError { return &AuthenticationError{ Type: baseErr.Type, Message: baseErr.Message, Code: baseErr.Code, Cause: cause, }}
// IsAuthenticationError checks if an error is an authentication error.func IsAuthenticationError(err error) bool { var authenticationError *AuthenticationError ok := errors.As(err, &authenticationError) return ok}
// IsOAuthError checks if an error is an OAuth error.func IsOAuthError(err error) bool { var oAuthError *OAuthError ok := errors.As(err, &oAuthError) return ok}
// GetUserFriendlyMessage returns a user-friendly error message based on the error type.func GetUserFriendlyMessage(err error) string { switch { case IsAuthenticationError(err): var authErr *AuthenticationError errors.As(err, &authErr) switch authErr.Type { case "token_expired": return "Your authentication has expired. Please log in again." case "token_invalid": return "Your authentication is invalid. Please log in again." case "authentication_required": return "Please log in to continue." case "port_in_use": return "The required port is already in use. Please close any applications using port 3000 and try again." case "callback_timeout": return "Authentication timed out. Please try again." case "browser_open_failed": return "Could not open your browser automatically. Please copy and paste the URL manually." default: return "Authentication failed. Please try again." } case IsOAuthError(err): var oauthErr *OAuthError errors.As(err, &oauthErr) switch oauthErr.Code { case "access_denied": return "Authentication was cancelled or denied." case "invalid_request": return "Invalid authentication request. Please try again." case "server_error": return "Authentication server error. Please try again later." default: return fmt.Sprintf("Authentication failed: %s", oauthErr.Description) } default: return "An unexpected error occurred. Please try again." }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218// Package claude provides authentication and token management functionality// for Anthropic's Claude AI services. It handles OAuth2 token storage, serialization,// and retrieval for maintaining authenticated sessions with the Claude API.package claude
// LoginSuccessHtml is the HTML template displayed to users after successful OAuth authentication.// This template provides a user-friendly success page with options to close the window// or navigate to the Claude platform. It includes automatic window closing functionality// and keyboard accessibility features.const LoginSuccessHtml = `<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Authentication Successful - Claude</title> <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2310b981'%3E%3Cpath d='M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z'/%3E%3C/svg%3E"> <style> * { box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 1rem; } .container { text-align: center; background: white; padding: 2.5rem; border-radius: 12px; box-shadow: 0 10px 25px rgba(0,0,0,0.1); max-width: 480px; width: 100%; animation: slideIn 0.3s ease-out; } @keyframes slideIn { from { opacity: 0; transform: translateY(-20px); } to { opacity: 1; transform: translateY(0); } } .success-icon { width: 64px; height: 64px; margin: 0 auto 1.5rem; background: #10b981; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-size: 2rem; font-weight: bold; } h1 { color: #1f2937; margin-bottom: 1rem; font-size: 1.75rem; font-weight: 600; } .subtitle { color: #6b7280; margin-bottom: 1.5rem; font-size: 1rem; line-height: 1.5; } .setup-notice { background: #fef3c7; border: 1px solid #f59e0b; border-radius: 6px; padding: 1rem; margin: 1rem 0; } .setup-notice h3 { color: #92400e; margin: 0 0 0.5rem 0; font-size: 1rem; } .setup-notice p { color: #92400e; margin: 0; font-size: 0.875rem; } .setup-notice a { color: #1d4ed8; text-decoration: none; } .setup-notice a:hover { text-decoration: underline; } .actions { display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap; margin-top: 2rem; } .button { padding: 0.75rem 1.5rem; border-radius: 8px; font-size: 0.875rem; font-weight: 500; text-decoration: none; transition: all 0.2s; cursor: pointer; border: none; display: inline-flex; align-items: center; gap: 0.5rem; } .button-primary { background: #3b82f6; color: white; } .button-primary:hover { background: #2563eb; transform: translateY(-1px); } .button-secondary { background: #f3f4f6; color: #374151; border: 1px solid #d1d5db; } .button-secondary:hover { background: #e5e7eb; } .countdown { color: #9ca3af; font-size: 0.75rem; margin-top: 1rem; } .footer { margin-top: 2rem; padding-top: 1.5rem; border-top: 1px solid #e5e7eb; color: #9ca3af; font-size: 0.75rem; } .footer a { color: #3b82f6; text-decoration: none; } .footer a:hover { text-decoration: underline; } </style></head><body> <div class="container"> <div class="success-icon">✓</div> <h1>Authentication Successful!</h1> <p class="subtitle">You have successfully authenticated with Claude. You can now close this window and return to your terminal to continue.</p> {{SETUP_NOTICE}} <div class="actions"> <button class="button button-primary" onclick="window.close()"> <span>Close Window</span> </button> <a href="{{PLATFORM_URL}}" target="_blank" class="button button-secondary"> <span>Open Platform</span> <span>↗</span> </a> </div> <div class="countdown"> This window will close automatically in <span id="countdown">10</span> seconds </div> <div class="footer"> <p>Powered by <a href="https://chatgpt.com" target="_blank">ChatGPT</a></p> </div> </div> <script> let countdown = 10; const countdownElement = document.getElementById('countdown'); const timer = setInterval(() => { countdown--; countdownElement.textContent = countdown; if (countdown <= 0) { clearInterval(timer); window.close(); } }, 1000); // Close window when user presses Escape document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { window.close(); } }); // Focus the close button for keyboard accessibility document.querySelector('.button-primary').focus(); </script></body></html>`
// SetupNoticeHtml is the HTML template for the setup notice section.// This template is embedded within the success page to inform users about// additional setup steps required to complete their Claude account configuration.const SetupNoticeHtml = ` <div class="setup-notice"> <h3>Additional Setup Required</h3> <p>To complete your setup, please visit the <a href="{{PLATFORM_URL}}" target="_blank">Claude</a> to configure your account.</p> </div>`123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331// Package claude provides authentication and token management functionality// for Anthropic's Claude AI services. It handles OAuth2 token storage, serialization,// and retrieval for maintaining authenticated sessions with the Claude API.package claude
import ( "context" "errors" "fmt" "net" "net/http" "strings" "sync" "time"
log "github.com/sirupsen/logrus")
// OAuthServer handles the local HTTP server for OAuth callbacks.// It listens for the authorization code response from the OAuth provider// and captures the necessary parameters to complete the authentication flow.type OAuthServer struct { // server is the underlying HTTP server instance server *http.Server // port is the port number on which the server listens port int // resultChan is a channel for sending OAuth results resultChan chan *OAuthResult // errorChan is a channel for sending OAuth errors errorChan chan error // mu is a mutex for protecting server state mu sync.Mutex // running indicates whether the server is currently running running bool}
// OAuthResult contains the result of the OAuth callback.// It holds either the authorization code and state for successful authentication// or an error message if the authentication failed.type OAuthResult struct { // Code is the authorization code received from the OAuth provider Code string // State is the state parameter used to prevent CSRF attacks State string // Error contains any error message if the OAuth flow failed Error string}
// NewOAuthServer creates a new OAuth callback server.// It initializes the server with the specified port and creates channels// for handling OAuth results and errors.//// Parameters:// - port: The port number on which the server should listen//// Returns:// - *OAuthServer: A new OAuthServer instancefunc NewOAuthServer(port int) *OAuthServer { return &OAuthServer{ port: port, resultChan: make(chan *OAuthResult, 1), errorChan: make(chan error, 1), }}
// Start starts the OAuth callback server.// It sets up the HTTP handlers for the callback and success endpoints,// and begins listening on the specified port.//// Returns:// - error: An error if the server fails to startfunc (s *OAuthServer) Start() error { s.mu.Lock() defer s.mu.Unlock()
if s.running { return fmt.Errorf("server is already running") }
// Check if port is available if !s.isPortAvailable() { return fmt.Errorf("port %d is already in use", s.port) }
mux := http.NewServeMux() mux.HandleFunc("/callback", s.handleCallback) mux.HandleFunc("/success", s.handleSuccess)
s.server = &http.Server{ Addr: fmt.Sprintf(":%d", s.port), Handler: mux, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, }
s.running = true
// Start server in goroutine go func() { if err := s.server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { s.errorChan <- fmt.Errorf("server failed to start: %w", err) } }()
// Give server a moment to start time.Sleep(100 * time.Millisecond)
return nil}
// Stop gracefully stops the OAuth callback server.// It performs a graceful shutdown of the HTTP server with a timeout.//// Parameters:// - ctx: The context for controlling the shutdown process//// Returns:// - error: An error if the server fails to stop gracefullyfunc (s *OAuthServer) Stop(ctx context.Context) error { s.mu.Lock() defer s.mu.Unlock()
if !s.running || s.server == nil { return nil }
log.Debug("Stopping OAuth callback server")
// Create a context with timeout for shutdown shutdownCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel()
err := s.server.Shutdown(shutdownCtx) s.running = false s.server = nil
return err}
// WaitForCallback waits for the OAuth callback with a timeout.// It blocks until either an OAuth result is received, an error occurs,// or the specified timeout is reached.//// Parameters:// - timeout: The maximum time to wait for the callback//// Returns:// - *OAuthResult: The OAuth result if successful// - error: An error if the callback times out or an error occursfunc (s *OAuthServer) WaitForCallback(timeout time.Duration) (*OAuthResult, error) { select { case result := <-s.resultChan: return result, nil case err := <-s.errorChan: return nil, err case <-time.After(timeout): return nil, fmt.Errorf("timeout waiting for OAuth callback") }}
// handleCallback handles the OAuth callback endpoint.// It extracts the authorization code and state from the callback URL,// validates the parameters, and sends the result to the waiting channel.//// Parameters:// - w: The HTTP response writer// - r: The HTTP requestfunc (s *OAuthServer) handleCallback(w http.ResponseWriter, r *http.Request) { log.Debug("Received OAuth callback")
// Validate request method if r.Method != http.MethodGet { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return }
// Extract parameters query := r.URL.Query() code := query.Get("code") state := query.Get("state") errorParam := query.Get("error")
// Validate required parameters if errorParam != "" { log.Errorf("OAuth error received: %s", errorParam) result := &OAuthResult{ Error: errorParam, } s.sendResult(result) http.Error(w, fmt.Sprintf("OAuth error: %s", errorParam), http.StatusBadRequest) return }
if code == "" { log.Error("No authorization code received") result := &OAuthResult{ Error: "no_code", } s.sendResult(result) http.Error(w, "No authorization code received", http.StatusBadRequest) return }
if state == "" { log.Error("No state parameter received") result := &OAuthResult{ Error: "no_state", } s.sendResult(result) http.Error(w, "No state parameter received", http.StatusBadRequest) return }
// Send successful result result := &OAuthResult{ Code: code, State: state, } s.sendResult(result)
// Redirect to success page http.Redirect(w, r, "/success", http.StatusFound)}
// handleSuccess handles the success page endpoint.// It serves a user-friendly HTML page indicating that authentication was successful.//// Parameters:// - w: The HTTP response writer// - r: The HTTP requestfunc (s *OAuthServer) handleSuccess(w http.ResponseWriter, r *http.Request) { log.Debug("Serving success page")
w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusOK)
// Parse query parameters for customization query := r.URL.Query() setupRequired := query.Get("setup_required") == "true" platformURL := query.Get("platform_url") if platformURL == "" { platformURL = "https://console.anthropic.com/" }
// Validate platformURL to prevent XSS - only allow http/https URLs if !isValidURL(platformURL) { platformURL = "https://console.anthropic.com/" }
// Generate success page HTML with dynamic content successHTML := s.generateSuccessHTML(setupRequired, platformURL)
_, err := w.Write([]byte(successHTML)) if err != nil { log.Errorf("Failed to write success page: %v", err) }}
// isValidURL checks if the URL is a valid http/https URL to prevent XSSfunc isValidURL(urlStr string) bool { urlStr = strings.TrimSpace(urlStr) return strings.HasPrefix(urlStr, "https://") || strings.HasPrefix(urlStr, "http://")}
// generateSuccessHTML creates the HTML content for the success page.// It customizes the page based on whether additional setup is required// and includes a link to the platform.//// Parameters:// - setupRequired: Whether additional setup is required after authentication// - platformURL: The URL to the platform for additional setup//// Returns:// - string: The HTML content for the success pagefunc (s *OAuthServer) generateSuccessHTML(setupRequired bool, platformURL string) string { html := LoginSuccessHtml
// Replace platform URL placeholder html = strings.Replace(html, "{{PLATFORM_URL}}", platformURL, -1)
// Add setup notice if required if setupRequired { setupNotice := strings.Replace(SetupNoticeHtml, "{{PLATFORM_URL}}", platformURL, -1) html = strings.Replace(html, "{{SETUP_NOTICE}}", setupNotice, 1) } else { html = strings.Replace(html, "{{SETUP_NOTICE}}", "", 1) }
return html}
// sendResult sends the OAuth result to the waiting channel.// It ensures that the result is sent without blocking the handler.//// Parameters:// - result: The OAuth result to sendfunc (s *OAuthServer) sendResult(result *OAuthResult) { select { case s.resultChan <- result: log.Debug("OAuth result sent to channel") default: log.Warn("OAuth result channel is full, result dropped") }}
// isPortAvailable checks if the specified port is available.// It attempts to listen on the port to determine availability.//// Returns:// - bool: True if the port is available, false otherwisefunc (s *OAuthServer) isPortAvailable() bool { addr := fmt.Sprintf(":%d", s.port) listener, err := net.Listen("tcp", addr) if err != nil { return false } defer func() { _ = listener.Close() }() return true}
// IsRunning returns whether the server is currently running.//// Returns:// - bool: True if the server is running, false otherwisefunc (s *OAuthServer) IsRunning() bool { s.mu.Lock() defer s.mu.Unlock() return s.running}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556// Package claude provides authentication and token management functionality// for Anthropic's Claude AI services. It handles OAuth2 token storage, serialization,// and retrieval for maintaining authenticated sessions with the Claude API.package claude
import ( "crypto/rand" "crypto/sha256" "encoding/base64" "fmt")
// GeneratePKCECodes generates a PKCE code verifier and challenge pair// following RFC 7636 specifications for OAuth 2.0 PKCE extension.// This provides additional security for the OAuth flow by ensuring that// only the client that initiated the request can exchange the authorization code.//// Returns:// - *PKCECodes: A struct containing the code verifier and challenge// - error: An error if the generation fails, nil otherwisefunc GeneratePKCECodes() (*PKCECodes, error) { // Generate code verifier: 43-128 characters, URL-safe codeVerifier, err := generateCodeVerifier() if err != nil { return nil, fmt.Errorf("failed to generate code verifier: %w", err) }
// Generate code challenge using S256 method codeChallenge := generateCodeChallenge(codeVerifier)
return &PKCECodes{ CodeVerifier: codeVerifier, CodeChallenge: codeChallenge, }, nil}
// generateCodeVerifier creates a cryptographically random string// of 128 characters using URL-safe base64 encodingfunc generateCodeVerifier() (string, error) { // Generate 96 random bytes (will result in 128 base64 characters) bytes := make([]byte, 96) _, err := rand.Read(bytes) if err != nil { return "", fmt.Errorf("failed to generate random bytes: %w", err) }
// Encode to URL-safe base64 without padding return base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(bytes), nil}
// generateCodeChallenge creates a SHA256 hash of the code verifier// and encodes it using URL-safe base64 encoding without paddingfunc generateCodeChallenge(codeVerifier string) string { hash := sha256.Sum256([]byte(codeVerifier)) return base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(hash[:])}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273// Package claude provides authentication and token management functionality// for Anthropic's Claude AI services. It handles OAuth2 token storage, serialization,// and retrieval for maintaining authenticated sessions with the Claude API.package claude
import ( "encoding/json" "fmt" "os" "path/filepath"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc")
// ClaudeTokenStorage stores OAuth2 token information for Anthropic Claude API authentication.// It maintains compatibility with the existing auth system while adding Claude-specific fields// for managing access tokens, refresh tokens, and user account information.type ClaudeTokenStorage struct { // IDToken is the JWT ID token containing user claims and identity information. IDToken string `json:"id_token"`
// AccessToken is the OAuth2 access token used for authenticating API requests. AccessToken string `json:"access_token"`
// RefreshToken is used to obtain new access tokens when the current one expires. RefreshToken string `json:"refresh_token"`
// LastRefresh is the timestamp of the last token refresh operation. LastRefresh string `json:"last_refresh"`
// Email is the Anthropic account email address associated with this token. Email string `json:"email"`
// Type indicates the authentication provider type, always "claude" for this storage. Type string `json:"type"`
// Expire is the timestamp when the current access token expires. Expire string `json:"expired"`}
// SaveTokenToFile serializes the Claude token storage to a JSON file.// This method creates the necessary directory structure and writes the token// data in JSON format to the specified file path for persistent storage.//// Parameters:// - authFilePath: The full path where the token file should be saved//// Returns:// - error: An error if the operation fails, nil otherwisefunc (ts *ClaudeTokenStorage) SaveTokenToFile(authFilePath string) error { misc.LogSavingCredentials(authFilePath) ts.Type = "claude"
// Create directory structure if it doesn't exist if err := os.MkdirAll(filepath.Dir(authFilePath), 0700); err != nil { return fmt.Errorf("failed to create directory: %v", err) }
// Create the token file f, err := os.Create(authFilePath) if err != nil { return fmt.Errorf("failed to create token file: %w", err) } defer func() { _ = f.Close() }()
// Encode and write the token data as JSON if err = json.NewEncoder(f).Encode(ts); err != nil { return fmt.Errorf("failed to write token to file: %w", err) } return nil}.gitignoreAdded+56
DockerfileAdded+30
Dockerfile.hfAdded+27
LICENSEAdded+22
README.mdAdded+16
cmd/server/main.goAdded+535
config.example.yamlAdded+281
config.yamlAdded+75
go.modAdded+78
go.sumAdded+196
internal/access/config_access/provider.goAdded+112
internal/access/reconcile.goAdded+270
internal/api/handlers/management/api_tools.goAdded+538
internal/api/handlers/management/auth_files.goAdded+2606
internal/api/handlers/management/config_basic.goAdded+243
internal/api/handlers/management/config_lists.goAdded+1090
internal/api/handlers/management/handler.goAdded+277
internal/api/handlers/management/logs.goAdded+592
internal/api/handlers/management/oauth_callback.goAdded+100
internal/api/handlers/management/oauth_sessions.goAdded+290
internal/api/handlers/management/quota.goAdded+18
internal/api/handlers/management/usage.goAdded+79
internal/api/handlers/management/vertex_import.goAdded+156
internal/api/middleware/request_logging.goAdded+122
internal/api/middleware/response_writer.goAdded+382
internal/api/modules/amp/amp.goAdded+428
internal/api/modules/amp/amp_test.goAdded+352
internal/api/modules/amp/fallback_handlers.goAdded+329
internal/api/modules/amp/fallback_handlers_test.goAdded+73
internal/api/modules/amp/gemini_bridge.goAdded+59
internal/api/modules/amp/gemini_bridge_test.goAdded+93
internal/api/modules/amp/model_mapping.goAdded+147
internal/api/modules/amp/model_mapping_test.goAdded+283
internal/api/modules/amp/proxy.goAdded+266
internal/api/modules/amp/proxy_test.goAdded+657
internal/api/modules/amp/response_rewriter.goAdded+160
internal/api/modules/amp/routes.goAdded+334
internal/api/modules/amp/routes_test.goAdded+381
internal/api/modules/amp/secret.goAdded+248
internal/api/modules/amp/secret_test.goAdded+366
internal/api/modules/modules.goAdded+92
internal/api/server.goAdded+1056
internal/api/server_test.goAdded+111
internal/auth/claude/anthropic.goAdded+32
internal/auth/claude/anthropic_auth.goAdded+346
internal/auth/claude/errors.goAdded+167
internal/auth/claude/html_templates.goAdded+218
internal/auth/claude/oauth_server.goAdded+331
internal/auth/claude/pkce.goAdded+56
internal/auth/claude/token.goAdded+73