platform

package
v0.17.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 22 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

BaseAdapter (base.go)
├── StandardAdapter (standard.go)
│ ├── OpenAiAdapter (openai.go)
│ ├── ClaudeAdapter (claude.go)
│ ├── GeminiAdapter (gemini.go)
│ │ └── GeminiCliAdapter (gemini_cli.go)
│ └── CliProxyApiAdapter (cliproxyapi.go)
├── CodexAdapter (codex.go)
├── AntigravityAdapter (antigravity.go)
├── OneApiAdapter (oneapi.go)
│ └── OneHubAdapter (onehub.go)
│ └── DoneHubAdapter (donehub.go)
├── VeloeraAdapter (veloera.go)
├── Sub2ApiAdapter (sub2api.go)
└── NewApiAdapter (newapi.go)
 └── AnyRouterAdapter (anyrouter.go)

Package platform implements adapters for 14 upstream AI API platforms.

Index

Constants

View Source
const ClaudeDefaultAnthropicVersion = "2023-06-01"

ClaudeDefaultAnthropicVersion is the anthropic-version header value used when a caller does not supply one. Single source of truth for every path that speaks the Anthropic-native protocol (platform adapters, OAuth flows, and the /v1 proxy data plane).

View Source
const DefaultBrowserUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"

DefaultBrowserUserAgent is the single fixed browser identity used for outbound requests to upstream sites. Adapter API calls (login/checkin/ balance/model pull) previously went out as Go's default "Go-http-client/1.1", which is a bright bot beacon for UA-denial WAF rules on NewAPI/OneAPI forks.

Keep the Chrome version bumped quarterly so the declared identity stays current with the real Chrome release cadence.

Variables

View Source
var PlatformAliases = map[string]string{
	"anyrouter":     "anyrouter",
	"vo-api":        "new-api",
	"super-api":     "new-api",
	"rix-api":       "new-api",
	"neo-api":       "new-api",
	"newapi":        "new-api",
	"new api":       "new-api",
	"new-api":       "new-api",
	"oneapi":        "one-api",
	"one api":       "one-api",
	"one-api":       "one-api",
	"onehub":        "one-hub",
	"one-hub":       "one-hub",
	"donehub":       "done-hub",
	"done-hub":      "done-hub",
	"veloera":       "veloera",
	"sub2api":       "sub2api",
	"openai":        "openai",
	"codex":         "codex",
	"chatgpt-codex": "codex",
	"chatgpt codex": "codex",
	"anthropic":     "claude",
	"claude":        "claude",
	"gemini":        "gemini",
	"gemini-cli":    "gemini-cli",
	"antigravity":   "antigravity",
	"anti-gravity":  "antigravity",
	"grok":          "grok",
	"xai":           "grok",
	"x.ai":          "grok",
	"google":        "gemini",
	"cliproxyapi":   "cliproxyapi",
	"cpa":           "cliproxyapi",
	"cli-proxy-api": "cliproxyapi",
	"sensetime":     "sensetime",
}

PLATFORM_ALIASES maps user-facing platform names to canonical identifiers.

Functions

func ApplyCustomHeaders

func ApplyCustomHeaders(req *http.Request, custom map[string]string)

ApplyCustomHeaders sets non-denied custom headers onto req using the default request-wins policy (does not overwrite existing request headers). Prefer ApplyCustomHeadersWithOptions when the site flag is known. Nil req or empty map is a no-op.

func ApplyCustomHeadersWithOptions

func ApplyCustomHeadersWithOptions(req *http.Request, custom map[string]string, opts ApplyCustomHeadersOptions)

ApplyCustomHeadersWithOptions sets non-denied custom headers onto req. OverrideRequest=true → site-wins (Header.Set). OverrideRequest=false → request-wins (skip when req already has a non-empty value for that header).

func ApplySiteIdentity added in v0.13.0

func ApplySiteIdentity(req *http.Request, proxyConfig *ProxyConfig)

ApplySiteIdentity injects a per-site Cloudflare clearance cookie and browser UA override into the request. The Cookie header is deny-listed in custom_headers for security, so cf_clearance flows through this dedicated typed field instead. Existing cookies are preserved via AddCookie.

func DoWithProxy

func DoWithProxy(ctx context.Context, req *http.Request, proxyConfig *ProxyConfig) (*http.Response, error)

DoWithProxy is a convenience function that works without a SiteProxy instance.

func DoWithProxyStream added in v0.16.18

func DoWithProxyStream(ctx context.Context, req *http.Request, proxyConfig *ProxyConfig) (*http.Response, error)

DoWithProxyStream is the SSE variant of DoWithProxy: the dispatched client carries no whole-request timeout so a healthy stream is not capped by PROXY_REQUEST_TIMEOUT_SEC while chunks keep flowing. Header wait remains bounded by the pooled transport's ResponseHeaderTimeout; body-phase liveness is enforced by the relay's idle guard. Non-streaming callers must keep using DoWithProxy.

func IsAuthRelatedUpstreamError

func IsAuthRelatedUpstreamError(httpStatus int, message string) bool

IsAuthRelatedUpstreamError is true for expired or other auth classes.

func IsDeniedCustomHeader

func IsDeniedCustomHeader(name string) bool

IsDeniedCustomHeader reports whether a site custom_headers entry must not be forwarded upstream. Blocks identity, framing, content-coding, hop-by-hop, cookies, Proxy-*, and Metapi control preference headers.

Security: custom Authorization must never override the Bearer set from the selected account token; Host/Connection/etc. must not be attacker-controlled.

func IsTokenExpiredError

func IsTokenExpiredError(httpStatus int, message string) bool

IsTokenExpiredError reports whether the signal is a confirmed expired/invalid stored credential. This matches mark policy (ClassExpired only). Auto-relogin callers that need broader 401/unauthorized heuristics must use local shouldAttemptAutoRelogin* patterns, not this gate. Mirrors historical TS isTokenExpiredError() with non-auth + generic-401 guards.

func NormalizePlatformAlias

func NormalizePlatformAlias(platform string) string

NormalizePlatformAlias maps a raw platform string to its canonical form.

func RejectCrossOriginRedirect

func RejectCrossOriginRedirect(req *http.Request, via []*http.Request) error

RejectCrossOriginRedirect is the shared CheckRedirect policy for outbound HTTP clients that talk to operator-configured upstream sites.

It refuses:

  • more than 5 redirects
  • https → non-https scheme downgrades
  • any host change (blocks 302 to metadata / loopback / private SSRF targets)

Same-origin redirects remain allowed so normal upstream path hops still work. Used by platform.DoWithProxy, proxy.RuntimeExecutor, and residual bare clients (health probe / admin harness / defaultUpstreamClient).

func ShouldMarkAccountExpired

func ShouldMarkAccountExpired(httpStatus int, message string) bool

ShouldMarkAccountExpired is the guard used before writing accounts.status='expired'. Only ClassExpired (confirmed credential invalid/expiry wording) may mark. Generic 401/unauthorized, network, 429, and 5xx must return false.

Types

type AntigravityAdapter

type AntigravityAdapter struct {
	*StandardAdapter
}

AntigravityAdapter handles Google Antigravity platforms (OAuth-driven). StandardAdapter provides the "not supported"/empty defaults for auth, checkin and balance methods.

func (*AntigravityAdapter) Detect

func (a *AntigravityAdapter) Detect(ctx context.Context, urlStr string) (bool, error)

Detect matches the antigravity host only. The bare "antigravity" substring previously matched any URL whose path contained /antigravity (e.g. Sub2API model endpoints), swallowing them before sub2api was reached.

func (*AntigravityAdapter) GetModels

func (a *AntigravityAdapter) GetModels(ctx context.Context, baseURL string, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels fetches from /v1internal:fetchAvailableModels with Antigravity-specific headers.

type AnyRouterAdapter

type AnyRouterAdapter struct {
	*NewApiAdapter
}

AnyRouterAdapter reuses NewAPI-compatible session operations, but token management is intentionally disabled because AnyRouter's API-key workflow is not the NewAPI /api/token/ contract.

func (*AnyRouterAdapter) CreateAPIToken

func (a *AnyRouterAdapter) CreateAPIToken(ctx context.Context, url, accessToken string, platformUserId *int, options *CreateAPITokenOptions, proxy *ProxyConfig) (bool, error)

func (*AnyRouterAdapter) DeleteAPIToken

func (a *AnyRouterAdapter) DeleteAPIToken(ctx context.Context, url, accessToken, tokenKey string, platformUserId *int, proxy *ProxyConfig) error

func (*AnyRouterAdapter) Detect

func (a *AnyRouterAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect matches URL keyword "anyrouter" (case-insensitive).

func (*AnyRouterAdapter) GetAPIToken

func (a *AnyRouterAdapter) GetAPIToken(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*string, error)

func (*AnyRouterAdapter) GetAPITokens

func (a *AnyRouterAdapter) GetAPITokens(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]ApiTokenInfo, error)

type ApiTokenInfo

type ApiTokenInfo struct {
	Name       string `json:"name"`
	Key        string `json:"key"`
	Enabled    bool   `json:"enabled"`
	TokenGroup string `json:"tokenGroup,omitempty"`
}

ApiTokenInfo describes a single API key/token.

type ApplyCustomHeadersOptions

type ApplyCustomHeadersOptions struct {
	OverrideRequest bool
}

ApplyCustomHeadersOptions controls collision policy for site custom headers. When OverrideRequest is false (default, request-wins), a site header is applied only if the request does not already carry that header. When true (site-wins), site headers always Set over existing request values — matching the upstream customHeadersOverrideRequestHeaders=true behavior.

type BalanceInfo

type BalanceInfo struct {
	Balance               float64              `json:"balance"`
	Used                  float64              `json:"used"`
	Quota                 float64              `json:"quota"`
	TodayIncome           *float64             `json:"todayIncome,omitempty"`
	TodayQuotaConsumption *float64             `json:"todayQuotaConsumption,omitempty"`
	SubscriptionSummary   *SubscriptionSummary `json:"subscriptionSummary,omitempty"`
}

BalanceInfo holds balance and usage information in USD.

type BaseAdapter

type BaseAdapter struct {
	// contains filtered or unexported fields
}

BaseAdapter provides default implementations for PlatformAdapter methods. Concrete adapters embed this and override specific methods as needed.

func NewBaseAdapter

func NewBaseAdapter(name string) *BaseAdapter

NewBaseAdapter creates a BaseAdapter with the given platform name.

func (*BaseAdapter) Checkin

func (b *BaseAdapter) Checkin(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)

Checkin returns unsupported by default.

func (*BaseAdapter) CreateAPIToken

func (b *BaseAdapter) CreateAPIToken(ctx context.Context, url, accessToken string, platformUserId *int, options *CreateAPITokenOptions, proxy *ProxyConfig) (bool, error)

CreateAPIToken returns false by default.

func (*BaseAdapter) DeleteAPIToken

func (b *BaseAdapter) DeleteAPIToken(ctx context.Context, url, accessToken string, tokenKey string, platformUserId *int, proxy *ProxyConfig) error

DeleteAPIToken returns nil (no-op) by default.

func (*BaseAdapter) Detect

func (b *BaseAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect must be implemented by concrete adapters.

func (*BaseAdapter) GetAPIToken

func (b *BaseAdapter) GetAPIToken(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*string, error)

GetAPIToken returns nil by default.

func (*BaseAdapter) GetAPITokens

func (b *BaseAdapter) GetAPITokens(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]ApiTokenInfo, error)

GetAPITokens returns a single-item list if GetAPIToken finds one.

func (*BaseAdapter) GetBalance

func (b *BaseAdapter) GetBalance(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

GetBalance returns zero balance by default.

func (*BaseAdapter) GetModels

func (b *BaseAdapter) GetModels(ctx context.Context, url, token string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels returns empty list by default.

func (*BaseAdapter) GetSiteAnnouncements

func (b *BaseAdapter) GetSiteAnnouncements(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]SiteAnnouncement, error)

GetSiteAnnouncements returns empty list by default.

func (*BaseAdapter) GetUserGroups

func (b *BaseAdapter) GetUserGroups(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetUserGroups returns ["default"] by default.

func (*BaseAdapter) GetUserInfo

func (b *BaseAdapter) GetUserInfo(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*UserInfo, error)

GetUserInfo provides a default implementation: GET /api/user/self with Bearer auth.

func (*BaseAdapter) Login

func (b *BaseAdapter) Login(ctx context.Context, url, username, password string, platformUserId *int, proxy *ProxyConfig) (*LoginResult, error)

Login provides a default login implementation: POST /api/user/login.

func (*BaseAdapter) PlatformName

func (b *BaseAdapter) PlatformName() string

PlatformName returns the platform identifier.

func (*BaseAdapter) VerifyToken

func (b *BaseAdapter) VerifyToken(ctx context.Context, url, token string, platformUserId *int, proxy *ProxyConfig) (*TokenVerifyResult, error)

VerifyToken provides default token verification (session + apikey paths).

type CheckinResult

type CheckinResult struct {
	Success bool
	Message string
	Reward  string // optional
}

CheckinResult is the outcome of a daily checkin.

type ClaudeAdapter

type ClaudeAdapter struct {
	*StandardAdapter
}

ClaudeAdapter handles api.anthropic.com platforms (native + OpenAI-compat gateways).

func (*ClaudeAdapter) Detect

func (c *ClaudeAdapter) Detect(ctx context.Context, urlStr string) (bool, error)

Detect matches the exact api.anthropic.com host, or anthropic.com with a /v1 path prefix (avoids anthropic.com/v1-docs style false positives).

func (*ClaudeAdapter) GetModels

func (c *ClaudeAdapter) GetModels(ctx context.Context, baseURL string, token string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels tries native Anthropic endpoint first, then falls back to OpenAI-compat by stripping the /anthropic suffix from the base URL.

type CliProxyApiAdapter

type CliProxyApiAdapter struct {
	*StandardAdapter
}

CliProxyApiAdapter handles CLIProxy API (port 8317 + x-cpa-* headers).

func (*CliProxyApiAdapter) Detect

func (c *CliProxyApiAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect uses 3 conditions: port 8317, "cliproxy" keyword, or HTTP probe with x-cpa-* headers.

func (*CliProxyApiAdapter) GetModels

func (c *CliProxyApiAdapter) GetModels(ctx context.Context, baseURL string, apiToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels fetches models from the standard /v1/models endpoint.

func (*CliProxyApiAdapter) VerifyToken added in v0.14.0

func (c *CliProxyApiAdapter) VerifyToken(ctx context.Context, baseURL, token string, platformUserId *int, proxy *ProxyConfig) (*TokenVerifyResult, error)

VerifyToken verifies a pasted CLIProxyAPI credential.

CliProxyApiAdapter deliberately overrides VerifyToken instead of inheriting BaseAdapter.VerifyToken: the base implementation statically dispatches to one-api style GET /api/user/self (absent on CLIProxyAPI) and reports every credential as "unknown". CLIProxyAPI credentials are keys: a provider API key whose models are served through /v1/models, or the management key (validated against the /v0/management API).

type CodexAdapter

type CodexAdapter struct {
	*StandardAdapter
}

CodexAdapter handles chatgpt.com/backend-api/codex (OAuth-driven). StandardAdapter provides the "not supported"/empty defaults for auth, checkin and balance methods.

func (*CodexAdapter) Detect

func (c *CodexAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect matches URL keyword: chatgpt.com/backend-api/codex.

type CreateAPITokenOptions

type CreateAPITokenOptions struct {
	Name               string
	Group              string
	UnlimitedQuota     bool    // default true
	RemainQuota        float64 // default 0
	ExpiredTime        int64   // Unix timestamp, -1 = never expire
	AllowIPs           string
	ModelLimitsEnabled bool
	ModelLimits        string
}

CreateAPITokenOptions holds parameters for creating a new API key.

type CredentialMode

type CredentialMode int

CredentialMode indicates the credential type preference.

const (
	CredentialAuto    CredentialMode = iota // auto-detect (session first, then apikey)
	CredentialSession                       // only session token
	CredentialAPIKey                        // only API key
)

type DoneHubAdapter

type DoneHubAdapter struct {
	*OneHubAdapter
}

DoneHubAdapter extends OneHubAdapter with checkin unsupported, remaining-quota balance, and /api/notice.

func (*DoneHubAdapter) Checkin

func (d *DoneHubAdapter) Checkin(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)

Checkin: always unsupported for DoneHub.

func (*DoneHubAdapter) Detect

func (d *DoneHubAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect: URL keyword match "donehub" or "done-hub" (title-first platform).

func (*DoneHubAdapter) GetBalance

func (d *DoneHubAdapter) GetBalance(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

GetBalance: quota=remaining, total=quota+used, divisor=500000.

func (*DoneHubAdapter) GetSiteAnnouncements

func (d *DoneHubAdapter) GetSiteAnnouncements(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]SiteAnnouncement, error)

GetSiteAnnouncements: GET /api/notice.

type GeminiAdapter

type GeminiAdapter struct {
	*StandardAdapter
}

GeminiAdapter handles Google Gemini API platforms with 3-path model discovery.

func (*GeminiAdapter) Detect

func (g *GeminiAdapter) Detect(ctx context.Context, urlStr string) (bool, error)

Detect matches URL keywords: generativelanguage.googleapis.com, googleapis.com/v1beta/openai, gemini.google.com.

func (*GeminiAdapter) GetModels

func (g *GeminiAdapter) GetModels(ctx context.Context, baseURL string, apiToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels uses 3-path discovery: OpenAI-compat (if on /openai/ path) -> native Gemini -> OpenAI-compat fallback.

type GeminiCliAdapter

type GeminiCliAdapter struct {
	*GeminiAdapter
}

GeminiCliAdapter extends GeminiAdapter with its own detect for cloudcode-pa.googleapis.com.

func (*GeminiCliAdapter) Detect

func (g *GeminiCliAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect overrides GeminiAdapter's detect: matches cloudcode-pa.googleapis.com only.

type GrokAdapter added in v0.13.0

type GrokAdapter struct {
	*StandardAdapter
}

GrokAdapter handles xAI Grok platforms (api.x.ai, OAuth-driven). StandardAdapter provides the "not supported"/empty defaults for auth, checkin and balance methods — Grok credentials are managed via the Device OAuth flow registered in service/oauth/grok.go.

func (*GrokAdapter) Detect added in v0.13.0

func (g *GrokAdapter) Detect(ctx context.Context, urlStr string) (bool, error)

Detect matches the xAI API host. xAI serves its public API from api.x.ai; the bare x.ai host is also accepted so users may register either form.

func (*GrokAdapter) GetModels added in v0.13.0

func (g *GrokAdapter) GetModels(ctx context.Context, baseURL string, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels returns the hardcoded Grok seed model list. xAI's public API does expose /v1/models, but the seed list keeps detection/verification working without a live upstream call (mirrors the Codex "empty by default" contract while still surfacing a useful model catalog for auto-complete).

type LoginResult

type LoginResult struct {
	Success     bool
	AccessToken string
	Username    string
	Message     string
}

LoginResult is the outcome of a login attempt.

type NewApiAdapter

type NewApiAdapter struct {
	*BaseAdapter
}

NewApiAdapter handles NewAPI platforms with full cookie fallback, shield challenge, user-ID probing, and 7-header injection. Serves as the base for AnyRouterAdapter.

func (*NewApiAdapter) Checkin

func (n *NewApiAdapter) Checkin(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)

func (*NewApiAdapter) CreateAPIToken

func (n *NewApiAdapter) CreateAPIToken(ctx context.Context, baseURL, accessToken string, platformUserId *int, options *CreateAPITokenOptions, proxy *ProxyConfig) (bool, error)

func (*NewApiAdapter) DeleteAPIToken

func (n *NewApiAdapter) DeleteAPIToken(ctx context.Context, baseURL, accessToken, tokenKey string, platformUserId *int, proxy *ProxyConfig) error

func (*NewApiAdapter) Detect

func (n *NewApiAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect probes GET /api/status and checks success===true and that data.system_name's value names a NewAPI fork. one-api v0.6.10 also ships system_name (default "One API"), so mere presence of the key misdetects one-api as new-api; the value-based check keeps the two apart. Known NewAPI fork aliases (vo-api/super-api/rix-api/neo-api) short-circuit via URL keyword so shield/WAF-fronted deployments whose /api/status probe is blocked still get detected. Operators who rename SYSTEM_NAME to something unrelated degrade to manual platform selection — acceptable for an auto-detect heuristic.

func (*NewApiAdapter) GetAPIToken

func (n *NewApiAdapter) GetAPIToken(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*string, error)

func (*NewApiAdapter) GetAPITokens

func (n *NewApiAdapter) GetAPITokens(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]ApiTokenInfo, error)

func (*NewApiAdapter) GetBalance

func (n *NewApiAdapter) GetBalance(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

func (*NewApiAdapter) GetModels

func (n *NewApiAdapter) GetModels(ctx context.Context, baseURL, token string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

func (*NewApiAdapter) GetSiteAnnouncements

func (n *NewApiAdapter) GetSiteAnnouncements(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]SiteAnnouncement, error)

func (*NewApiAdapter) GetUserGroups

func (n *NewApiAdapter) GetUserGroups(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

func (*NewApiAdapter) GetUserInfo

func (n *NewApiAdapter) GetUserInfo(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*UserInfo, error)

func (*NewApiAdapter) Login

func (n *NewApiAdapter) Login(ctx context.Context, baseURL, username, password string, platformUserId *int, proxy *ProxyConfig) (*LoginResult, error)

func (*NewApiAdapter) VerifyToken

func (n *NewApiAdapter) VerifyToken(ctx context.Context, baseURL, token string, platformUserId *int, proxy *ProxyConfig) (*TokenVerifyResult, error)

type OneApiAdapter

type OneApiAdapter struct {
	*BaseAdapter
}

OneApiAdapter handles OneAPI platforms (detect: /api/status by version + system_name value discriminator against new-api). Serves as the base for OneHubAdapter and DoneHubAdapter.

func (*OneApiAdapter) Checkin

func (o *OneApiAdapter) Checkin(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)

Checkin: POST /api/user/checkin. Bearer auth first; session-cookie credentials (one-api v0.6.10 login) fall back to a Cookie header.

func (*OneApiAdapter) CreateAPIToken

func (o *OneApiAdapter) CreateAPIToken(ctx context.Context, baseURL, accessToken string, platformUserId *int, options *CreateAPITokenOptions, proxy *ProxyConfig) (bool, error)

CreateAPIToken: POST /api/token/ (Bearer auth).

func (*OneApiAdapter) DeleteAPIToken

func (o *OneApiAdapter) DeleteAPIToken(ctx context.Context, baseURL, accessToken, tokenKey string, platformUserId *int, proxy *ProxyConfig) error

DeleteAPIToken: list -> find key -> DELETE /api/token/{id} (with trailing-slash fallback).

func (*OneApiAdapter) Detect

func (o *OneApiAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect probes GET /api/status and checks success===true, data.version is present, and system_name (when present) names one-api. one-api v0.5.x has no system_name (legacy shape); v0.6.10+ ships system_name (default "One API"). The value check keeps new-api (default "New API") and one-api apart. Requiring version keeps unrelated /api/status endpoints from being labeled one-api. Operators who rename SYSTEM_NAME to something unrelated degrade to manual platform selection — acceptable for an auto-detect heuristic.

func (*OneApiAdapter) GetAPIToken

func (o *OneApiAdapter) GetAPIToken(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*string, error)

GetAPIToken returns the first enabled token.

func (*OneApiAdapter) GetAPITokens

func (o *OneApiAdapter) GetAPITokens(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]ApiTokenInfo, error)

GetAPITokens: GET /api/token/?p=0&size=100 (Bearer auth).

func (*OneApiAdapter) GetBalance

func (o *OneApiAdapter) GetBalance(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

GetBalance: quota=total, balance=quota-used, divisor=500000. Bearer auth first; session-cookie credentials fall back to a Cookie header.

func (*OneApiAdapter) GetModels

func (o *OneApiAdapter) GetModels(ctx context.Context, baseURL string, apiToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels: GET /v1/models (Bearer auth).

func (*OneApiAdapter) GetUserGroups

func (o *OneApiAdapter) GetUserGroups(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetUserGroups: GET /api/user_group_map, fallback /api/user/self/groups.

func (*OneApiAdapter) GetUserInfo added in v0.14.0

func (o *OneApiAdapter) GetUserInfo(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*UserInfo, error)

GetUserInfo: GET /api/user/self with Bearer auth first; session-cookie credentials fall back to a Cookie header (one-api v0.6.10 login).

func (*OneApiAdapter) Login added in v0.14.0

func (o *OneApiAdapter) Login(ctx context.Context, baseURL, username, password string, platformUserId *int, proxy *ProxyConfig) (*LoginResult, error)

Login POSTs /api/user/login and accepts either a legacy data.access_token or a captured session cookie. one-api v0.6.10 returns success:true with an EMPTY data.access_token and authenticates via a Set-Cookie session cookie, so the cookie header becomes the stored credential. Mirrors NewApiAdapter.Login (same fetchLoginResponse + hasUsableSessionCookie flow).

func (*OneApiAdapter) VerifyToken added in v0.14.0

func (o *OneApiAdapter) VerifyToken(ctx context.Context, baseURL, token string, platformUserId *int, proxy *ProxyConfig) (*TokenVerifyResult, error)

VerifyToken mirrors BaseAdapter.VerifyToken but dispatches to the cookie-aware overrides above. BaseAdapter.VerifyToken calls its own Bearer-only GetUserInfo/GetBalance (Go static dispatch on the embedded receiver), which would reject session-cookie credentials stored by the v0.6.10 login; this override routes through o.GetUserInfo/o.GetBalance instead.

type OneHubAdapter

type OneHubAdapter struct {
	*OneApiAdapter
}

OneHubAdapter extends OneApiAdapter with title-first detect and /api/available_model fallback.

func (*OneHubAdapter) Detect

func (o *OneHubAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect: URL keyword match "onehub" or "one-hub" (case-insensitive, title-first platform).

func (*OneHubAdapter) GetModels

func (o *OneHubAdapter) GetModels(ctx context.Context, baseURL string, apiToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels: try /v1/models (OneApi), fall back to /api/available_model.

func (*OneHubAdapter) GetUserGroups

func (o *OneHubAdapter) GetUserGroups(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetUserGroups: /api/user_group_map with data-object keys, fallback to OneApi's implementation.

type OpenAiAdapter

type OpenAiAdapter struct {
	*StandardAdapter
}

OpenAiAdapter handles api.openai.com platforms.

func (*OpenAiAdapter) Detect

func (o *OpenAiAdapter) Detect(ctx context.Context, urlStr string) (bool, error)

Detect matches the exact api.openai.com host (avoids suffix confusion such as api.openai.com.evil.example).

func (*OpenAiAdapter) GetModels

func (o *OpenAiAdapter) GetModels(ctx context.Context, baseURL string, token string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels fetches models from the standard /v1/models OpenAI endpoint.

type PlatformAdapter

type PlatformAdapter interface {
	PlatformName() string

	// Detect returns true if the given URL can be handled by this adapter.
	Detect(ctx context.Context, url string) (bool, error)

	// Session management.
	// platformUserId is for NewApi-fork platforms' cookie-based auth fallback.
	Login(ctx context.Context, url, username, password string, platformUserId *int, proxy *ProxyConfig) (*LoginResult, error)
	GetUserInfo(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*UserInfo, error)
	VerifyToken(ctx context.Context, url, token string, platformUserId *int, proxy *ProxyConfig) (*TokenVerifyResult, error)

	// Daily operations.
	Checkin(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)
	GetBalance(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

	// Model discovery: returns model ID strings.
	GetModels(ctx context.Context, url, token string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

	// Token management (NewAPI-style platforms).
	GetAPIToken(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*string, error)
	GetAPITokens(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]ApiTokenInfo, error)
	CreateAPIToken(ctx context.Context, url, accessToken string, platformUserId *int, options *CreateAPITokenOptions, proxy *ProxyConfig) (bool, error)
	DeleteAPIToken(ctx context.Context, url, accessToken string, tokenKey string, platformUserId *int, proxy *ProxyConfig) error

	// Announcements and groups.
	GetSiteAnnouncements(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]SiteAnnouncement, error)
	GetUserGroups(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)
}

PlatformAdapter is the interface every platform adapter must implement.

func GetAdapter

func GetAdapter(platform string) PlatformAdapter

GetAdapter returns the registered adapter for a given canonical platform name.

func ListAdapters

func ListAdapters() []PlatformAdapter

ListAdapters returns all registered adapters (for diagnostics).

type ProxyConfig

type ProxyConfig struct {
	ProxyURL      string
	CustomHeaders map[string]string
	// CustomHeadersOverrideRequest: when true, site custom headers overwrite
	// same-name request headers (site-wins opt-in). Default
	// false = request-wins (only fill missing headers).
	CustomHeadersOverrideRequest bool
	UseSystemProxy               bool
	InsecureSkipTLS              bool
	// ClearanceCookie is a per-site Cloudflare cf_clearance value injected as
	// a Cookie header on outbound requests to bypass CF challenges.
	ClearanceCookie string
	// BrowserUA overrides the global browser User-Agent for a specific site
	// (used to match the UA of a harvested cf_clearance cookie).
	BrowserUA string
	// ResinAccount records the Resin business-identity used for this request
	// (set by BuildPlatformProxyConfig when the resin forward proxy is active).
	// Downstream code (e.g. native wss reverse-proxy) can read this to set the
	// X-Resin-Account header on paths that bypass the HTTP forward proxy.
	ResinAccount string
	// UseUTLS switches the transport to a uTLS-backed DialTLSContext that
	// mimics Chrome's ClientHello (HelloChrome_Auto), masking the JA3/JA4
	// fingerprint that Cloudflare and similar WAFs use to block automated
	// traffic. When false (default) the standard crypto/tls transport is
	// used. Resolved from site-level use_utls or the global UTLS_ENABLED flag
	// by service.BuildPlatformProxyConfig; the platform layer only reads
	// the resolved bool.
	UseUTLS bool
}

ProxyConfig carries optional proxy settings for a single request.

type SiteAnnouncement

type SiteAnnouncement struct {
	SourceKey         string          `json:"sourceKey"`
	Title             string          `json:"title"`
	Content           string          `json:"content"`
	Level             string          `json:"level"` // "info", "warning", "error"
	SourceURL         string          `json:"sourceUrl,omitempty"`
	StartsAt          string          `json:"startsAt,omitempty"`
	EndsAt            string          `json:"endsAt,omitempty"`
	UpstreamCreatedAt string          `json:"upstreamCreatedAt,omitempty"`
	UpstreamUpdatedAt string          `json:"upstreamUpdatedAt,omitempty"`
	RawPayload        json.RawMessage `json:"rawPayload,omitempty"`
}

SiteAnnouncement is a notice or announcement from the upstream platform.

type SiteProxy

type SiteProxy struct {
	// contains filtered or unexported fields
}

SiteProxy is the outbound HTTP client with SOCKS/HTTP proxy support.

func NewSiteProxy

func NewSiteProxy(systemProxyURL string) *SiteProxy

NewSiteProxy creates a new SiteProxy.

func (*SiteProxy) Do

func (sp *SiteProxy) Do(ctx context.Context, req *http.Request, proxyConfig *ProxyConfig) (*http.Response, error)

Do executes an HTTP request through the site proxy layer.

type SiteProxyConfig

type SiteProxyConfig struct {
	ProxyURL       string
	UseSystemProxy bool
	CustomHeaders  map[string]string
}

SiteProxyConfig holds proxy configuration for a site.

type StandardAdapter

type StandardAdapter struct {
	*BaseAdapter
	LoginUnsupportedMessage   string
	CheckinUnsupportedMessage string
}

StandardAdapter is the base for standard API providers (OpenAI, Claude, Gemini, CliProxyApi). It provides sane "not supported" defaults for login/checkin/getBalance/getUserInfo.

func NewStandardAdapter

func NewStandardAdapter(name string) *StandardAdapter

NewStandardAdapter creates a StandardAdapter.

func (*StandardAdapter) Checkin

func (s *StandardAdapter) Checkin(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)

Checkin returns unsupported.

func (*StandardAdapter) GetBalance

func (s *StandardAdapter) GetBalance(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

GetBalance returns zero balance.

func (*StandardAdapter) GetUserInfo

func (s *StandardAdapter) GetUserInfo(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*UserInfo, error)

GetUserInfo returns nil.

func (*StandardAdapter) Login

func (s *StandardAdapter) Login(ctx context.Context, url, username, password string, platformUserId *int, proxy *ProxyConfig) (*LoginResult, error)

Login returns unsupported.

type Sub2ApiAdapter

type Sub2ApiAdapter struct {
	*BaseAdapter
}

Sub2ApiAdapter handles Sub2API platforms (JWT auth, {code, message, data} envelope). Directly extends BaseAdapter. Does NOT support login or checkin.

func (*Sub2ApiAdapter) Checkin

func (s *Sub2ApiAdapter) Checkin(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)

Checkin: not supported.

func (*Sub2ApiAdapter) CreateAPIToken

func (s *Sub2ApiAdapter) CreateAPIToken(ctx context.Context, baseURL, accessToken string, platformUserId *int, options *CreateAPITokenOptions, proxy *ProxyConfig) (bool, error)

CreateAPIToken: POST /api/v1/keys + POST /api/v1/api-keys.

func (*Sub2ApiAdapter) DeleteAPIToken

func (s *Sub2ApiAdapter) DeleteAPIToken(ctx context.Context, baseURL, accessToken, tokenKey string, platformUserId *int, proxy *ProxyConfig) error

DeleteAPIToken: list -> find key -> DELETE /api/v1/keys/{id} + /api/v1/api-keys/{id}.

func (*Sub2ApiAdapter) Detect

func (s *Sub2ApiAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect uses a multi-path approach: URL keyword, /api/v1/auth/me probe, /v1/models probe, root title.

func (*Sub2ApiAdapter) GetAPIToken

func (s *Sub2ApiAdapter) GetAPIToken(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*string, error)

GetAPIToken: returns first enabled token.

func (*Sub2ApiAdapter) GetAPITokens

func (s *Sub2ApiAdapter) GetAPITokens(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]ApiTokenInfo, error)

GetAPITokens: GET /api/v1/keys?page=1&page_size=100 + /api/v1/api-keys?page=1&page_size=100.

func (*Sub2ApiAdapter) GetBalance

func (s *Sub2ApiAdapter) GetBalance(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

GetBalance: USD balance from /api/v1/auth/me, converted to quota, plus subscription summary.

func (*Sub2ApiAdapter) GetModels

func (s *Sub2ApiAdapter) GetModels(ctx context.Context, baseURL, apiToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels: standard OpenAI-compat endpoints, with API key discovery fallback.

func (*Sub2ApiAdapter) GetSiteAnnouncements

func (s *Sub2ApiAdapter) GetSiteAnnouncements(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]SiteAnnouncement, error)

GetSiteAnnouncements: GET /api/v1/announcements?page=1&page_size=100.

func (*Sub2ApiAdapter) GetUserGroups

func (s *Sub2ApiAdapter) GetUserGroups(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetUserGroups: 5 endpoint fallback + key-based inference.

func (*Sub2ApiAdapter) GetUserInfo

func (s *Sub2ApiAdapter) GetUserInfo(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*UserInfo, error)

GetUserInfo: GET /api/v1/auth/me.

func (*Sub2ApiAdapter) Login

func (s *Sub2ApiAdapter) Login(ctx context.Context, url, username, password string, platformUserId *int, proxy *ProxyConfig) (*LoginResult, error)

Login: JWT-only, always unsupported.

func (*Sub2ApiAdapter) VerifyToken added in v0.14.0

func (s *Sub2ApiAdapter) VerifyToken(ctx context.Context, baseURL, token string, platformUserId *int, proxy *ProxyConfig) (*TokenVerifyResult, error)

VerifyToken verifies a pasted Sub2API credential.

Sub2ApiAdapter deliberately overrides VerifyToken instead of inheriting BaseAdapter.VerifyToken: the base implementation dispatches statically to BaseAdapter.GetUserInfo (one-api style GET /api/user/self, which does not exist on Sub2API) and BaseAdapter.GetModels (always empty), so an inherited implementation would report every Sub2API credential as "unknown".

The session path validates the JWT against /api/v1/auth/me and resolves user info, balance and the first API key; a pasted API key (sk-...) falls back to /v1/models verification with the key-discovery fallback.

type SubscriptionPlanSummary

type SubscriptionPlanSummary struct {
	ID              *int     `json:"id,omitempty"`
	GroupID         *int     `json:"groupId,omitempty"`
	GroupName       string   `json:"groupName,omitempty"`
	Status          string   `json:"status,omitempty"`
	ExpiresAt       string   `json:"expiresAt,omitempty"`
	DailyUsedUsd    *float64 `json:"dailyUsedUsd,omitempty"`
	DailyLimitUsd   *float64 `json:"dailyLimitUsd,omitempty"`
	WeeklyUsedUsd   *float64 `json:"weeklyUsedUsd,omitempty"`
	WeeklyLimitUsd  *float64 `json:"weeklyLimitUsd,omitempty"`
	MonthlyUsedUsd  *float64 `json:"monthlyUsedUsd,omitempty"`
	MonthlyLimitUsd *float64 `json:"monthlyLimitUsd,omitempty"`
}

SubscriptionPlanSummary describes a single subscription plan.

type SubscriptionSummary

type SubscriptionSummary struct {
	ActiveCount   int
	TotalUsedUsd  float64
	Subscriptions []SubscriptionPlanSummary
}

SubscriptionSummary aggregates subscription data.

type TokenVerifyResult

type TokenVerifyResult struct {
	TokenType string // "session", "apikey", "unknown"
	UserInfo  *UserInfo
	Balance   *BalanceInfo
	APIToken  string // first discovered API key (optional)
	Models    []string
}

TokenVerifyResult reports the result of token verification.

type UpstreamErrorClass

type UpstreamErrorClass string

UpstreamErrorClass is the high-level class for upstream failure signals. Used for account-status decisions, retry UX, and residual-risk documentation.

const (
	// ClassExpired means the upstream credential/session looks expired or invalid.
	// Only this class may mark accounts.status = 'expired'.
	ClassExpired UpstreamErrorClass = "expired"
	// ClassAuth means an auth/session problem that is not clearly token expiry.
	ClassAuth UpstreamErrorClass = "auth"
	// ClassBilling means payment / quota / credit failures.
	ClassBilling UpstreamErrorClass = "billing"
	// ClassModel means model capability / unsupported-model failures.
	ClassModel UpstreamErrorClass = "model"
	// ClassValidation means request validation / argument errors.
	ClassValidation UpstreamErrorClass = "validation"
	// ClassTransient means rate-limit / timeout / 5xx / network-like failures.
	ClassTransient UpstreamErrorClass = "transient"
	// ClassUnknown is the residual bucket.
	ClassUnknown UpstreamErrorClass = "unknown"
)

func ClassifyUpstreamError

func ClassifyUpstreamError(httpStatus int, message string) UpstreamErrorClass

ClassifyUpstreamError maps an upstream HTTP status + message to a class. Classification is intentionally conservative for ClassExpired: non-auth 401/403 bodies (billing, model, validation, rate-limit) must not mark keys expired.

type UserInfo

type UserInfo struct {
	Username    string `json:"username"`
	DisplayName string `json:"displayName,omitempty"`
	Email       string `json:"email,omitempty"`
	Role        *int   `json:"role,omitempty"`
}

UserInfo holds the authenticated user's profile.

type VeloeraAdapter

type VeloeraAdapter struct {
	*BaseAdapter
}

VeloeraAdapter handles Veloera platforms (1M divisor + Veloera-User header). Directly extends BaseAdapter, NOT NewApiAdapter.

func (*VeloeraAdapter) Checkin

func (v *VeloeraAdapter) Checkin(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)

Checkin: POST /api/user/checkin (veloeraHeaders, requires platformUserId).

func (*VeloeraAdapter) Detect

func (v *VeloeraAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect probes GET /api/status and checks for "veloera" in system_name or version.

func (*VeloeraAdapter) GetBalance

func (v *VeloeraAdapter) GetBalance(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

GetBalance: quota=total, balance=quota-used, divisor=1,000,000 (NOT 500,000!).

func (*VeloeraAdapter) GetModels

func (v *VeloeraAdapter) GetModels(ctx context.Context, baseURL string, apiToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels: GET /v1/models (Bearer auth only, no Veloera headers).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL