platform

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 17 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

This section is empty.

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",
	"google":        "gemini",
	"cliproxyapi":   "cliproxyapi",
	"cpa":           "cliproxyapi",
	"cli-proxy-api": "cliproxyapi",
}

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 DetectPlatformByTitle

func DetectPlatformByTitle(rawURL string) string

DetectPlatformByTitle fetches the page title and matches it against known patterns. Returns the canonical platform name if a match is found.

func DetectPlatformByURLHint

func DetectPlatformByURLHint(rawURL string) string

DetectPlatformByURLHint detects platform from known URL patterns.

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 InitRegistry

func InitRegistry()

InitRegistry reorders the adapter registry to match the spec-required detection sequence. Call this once at startup after all packages have been imported. The order ensures: specific forks before generic adapters, OneApi last as catch-all.

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, 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 Register

func Register(a PlatformAdapter)

Register adds an adapter to the global registry. Called from adapter init() functions.

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.

func SolveAcwScV2

func SolveAcwScV2(html string) string

Resolution: Documented limitation. Shield-protected NewAPI sites require cookie import rather than credential-based login. See audit-platform-parity.md Section 3 for the full audit analysis.

Types

type AntigravityAdapter

type AntigravityAdapter struct {
	*BaseAdapter
}

AntigravityAdapter handles Google Antigravity platforms (OAuth-driven).

func (*AntigravityAdapter) Checkin

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

Checkin: not supported.

func (*AntigravityAdapter) Detect

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

Detect matches URL keyword: antigravity.

func (*AntigravityAdapter) GetBalance

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

GetBalance returns zero balance.

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.

func (*AntigravityAdapter) GetUserInfo

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

GetUserInfo returns nil.

func (*AntigravityAdapter) Login

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

Login: not supported.

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, url string) (bool, error)

Detect matches URL keywords: api.anthropic.com or anthropic.com/v1.

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.

type CodexAdapter

type CodexAdapter struct {
	*BaseAdapter
}

CodexAdapter handles chatgpt.com/backend-api/codex (OAuth-driven, all methods return empty/unsupported).

func (*CodexAdapter) Checkin

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

Checkin: not supported.

func (*CodexAdapter) Detect

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

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

func (*CodexAdapter) GetBalance

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

GetBalance returns zero balance.

func (*CodexAdapter) GetModels

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

GetModels returns empty list.

func (*CodexAdapter) GetUserInfo

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

GetUserInfo returns nil (OAuth-managed).

func (*CodexAdapter) Login

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

Login: OAuth only, not supported.

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 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 system_name is present.

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 without system_name). 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).

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 that success===true and system_name is absent.

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.

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.

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, url string) (bool, error)

Detect matches by URL keyword: api.openai.com.

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 DetectPlatform

func DetectPlatform(rawURL string) PlatformAdapter

DetectPlatform runs the 4-step detection pipeline to identify a platform from a URL.

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
}

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.

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 TitleHintPlatform

type TitleHintPlatform string

TitleHintPlatform is a platform identifier from page title detection.

const (
	TitleAnyRouter TitleHintPlatform = "anyrouter"
	TitleDoneHub   TitleHintPlatform = "done-hub"
	TitleOneHub    TitleHintPlatform = "one-hub"
	TitleVeloera   TitleHintPlatform = "veloera"
	TitleSub2Api   TitleHintPlatform = "sub2api"
	TitleNewApi    TitleHintPlatform = "new-api"
	TitleOneApi    TitleHintPlatform = "one-api"
)

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