middleware

package
v0.2.0-beta.7 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: AGPL-3.0 Imports: 49 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EditionFull = "full"
	EditionLAN  = "lan"
)

Distribution editions are intentionally small and independent from the frontend build flag. The backend guard below is the security boundary for the LAN distribution; hiding a menu item in React is not sufficient.

View Source
const (
	EmailVerificationRateLimitMark = "EV"
	EmailVerificationMaxRequests   = 2  // 30秒内最多2次
	EmailVerificationDuration      = 30 // 30秒时间窗口
)
View Source
const (
	ModelRequestRateLimitCountMark        = "MRRL"
	ModelRequestRateLimitSuccessCountMark = "MRRLS"
)
View Source
const (
	RouteTagKey = "route_tag"
)
View Source
const SecurityProofScopeCodexLocalImport = "channel.codex.local_import"

Variables

This section is empty.

Functions

func AdminAuth

func AdminAuth() func(c *gin.Context)

func AnonymousRequestBodyLimit

func AnonymousRequestBodyLimit() gin.HandlerFunc

func BodyStorageCleanup

func BodyStorageCleanup() gin.HandlerFunc

BodyStorageCleanup 请求体存储清理中间件 在请求处理完成后自动清理磁盘/内存缓存

func CORS

func CORS() gin.HandlerFunc

func Cache

func Cache() func(c *gin.Context)

func CodexLocalImportVerificationRequired

func CodexLocalImportVerificationRequired() gin.HandlerFunc

CodexLocalImportVerificationRequired protects the operation that copies a password-equivalent Codex credential from the backend host into a channel.

func ConfigureTrustedProxies

func ConfigureTrustedProxies(engine *gin.Engine) error

func CriticalRateLimit

func CriticalRateLimit() func(c *gin.Context)

func CurrentEdition

func CurrentEdition() string

CurrentEdition returns the normalized MYAPI_EDITION value. Unknown and empty values fail open to the full edition for backwards compatibility.

func DashboardSessionOriginGuard

func DashboardSessionOriginGuard() gin.HandlerFunc

DashboardSessionOriginGuard always enforces an exact browser origin for high-risk dashboard operations, including local credential import. Unlike SessionCookieOriginGuard it remains active for loopback HTTP development.

func DecompressRequestMiddleware

func DecompressRequestMiddleware() gin.HandlerFunc

func DeleteAllFullContentLogFiles

func DeleteAllFullContentLogFiles() (int, int64, error)

DeleteAllFullContentLogFiles closes every active writer and removes all managed JSONL files while holding the lifecycle lock.

func DeleteFullContentLogFile

func DeleteFullContentLogFile(filename string) (int64, error)

DeleteFullContentLogFile safely closes a matching active writer before the file is removed. Future writes automatically open a new file.

func DisableCache

func DisableCache() gin.HandlerFunc

func Distribute

func Distribute() func(c *gin.Context)

func DownloadRateLimit

func DownloadRateLimit() func(c *gin.Context)

func EditionGuard

func EditionGuard() gin.HandlerFunc

EditionGuard enforces LAN edition's reduced surface at the HTTP boundary. API relay routes, setup, authentication, keys and channel management remain available; billing, public registration and external OAuth are disabled.

func EmailVerificationRateLimit

func EmailVerificationRateLimit() gin.HandlerFunc

func EnforceAccessPolicyForSelectedGroup

func EnforceAccessPolicyForSelectedGroup(c *gin.Context, usingGroup, usingModel string) *types.NewAPIError

EnforceAccessPolicyForSelectedGroup returns a non-retryable 403 error when the final selected group and model are outside scoped D04 entitlements. It is used by controller retry paths, which must return their normal protocol error instead of having middleware write a second response.

func FullContentLogDirectory

func FullContentLogDirectory() string

FullContentLogDirectory returns the directory shared by the logger and the administrator log viewer.

func FullContentLogEnabled

func FullContentLogEnabled() bool

FullContentLogEnabled reports whether complete relay content logging is on.

func FullContentLogFilePath

func FullContentLogFilePath(filename string) (string, error)

FullContentLogFilePath resolves a managed JSONL file without allowing path traversal or non-log files.

func FullContentLogger

func FullContentLogger() gin.HandlerFunc

func GetAuthIdentity

func GetAuthIdentity(c *gin.Context) (service.AuthIdentity, bool)

GetAuthIdentity returns a dashboard session identity. PAT-authenticated requests intentionally have no SessionID and cannot manage browser sessions.

func GetLanguage

func GetLanguage(c *gin.Context) string

GetLanguage returns the current language from gin context

func GetSessionAuthIdentity

func GetSessionAuthIdentity(c *gin.Context) (service.AuthIdentity, bool)

GetSessionAuthIdentity returns only identities backed by a live dashboard session. PAT-authenticated requests intentionally fail this check.

func GetTaskOperationTokenID

func GetTaskOperationTokenID(c *gin.Context) (int, bool)

GetTaskOperationTokenID returns an API-token owner scope. Dashboard session requests return false and must be queried by user ID only. Once marked token scoped, an invalid ID is returned with true so the controller fails closed instead of silently broadening the lookup to the whole user.

func GlobalAPIRateLimit

func GlobalAPIRateLimit() func(c *gin.Context)

func GlobalWebRateLimit

func GlobalWebRateLimit() func(c *gin.Context)

func HeaderNavModuleAuth

func HeaderNavModuleAuth(module string) gin.HandlerFunc

func HeaderNavModulePublicOrUserAuth

func HeaderNavModulePublicOrUserAuth(module string) gin.HandlerFunc

func I18n

func I18n() gin.HandlerFunc

I18n middleware detects and sets the language preference for the request

func IsLANEdition

func IsLANEdition() bool

func JimengRequestConvert

func JimengRequestConvert() func(c *gin.Context)

func KlingRequestConvert

func KlingRequestConvert() func(c *gin.Context)

func ModelRequestRateLimit

func ModelRequestRateLimit() func(c *gin.Context)

ModelRequestRateLimit 模型请求限流中间件

func RelayPanicRecover

func RelayPanicRecover() gin.HandlerFunc

func RequestId

func RequestId() func(c *gin.Context)

func RequirePermission

func RequirePermission(permission authz.Permission) func(c *gin.Context)

func RequireSecurityProof

func RequireSecurityProof(c *gin.Context, requiredScope string, allowedMethods []string) bool

RequireSecurityProof validates a proof against the authenticated dashboard session and writes the shared proof error contract on failure.

func RootAuth

func RootAuth() func(c *gin.Context)

func RouteTag

func RouteTag(tag string) gin.HandlerFunc

func SearchRateLimit

func SearchRateLimit() func(c *gin.Context)

SearchRateLimit returns a per-user rate limiter for search endpoints. Configurable via SEARCH_RATE_LIMIT_ENABLE / SEARCH_RATE_LIMIT / SEARCH_RATE_LIMIT_DURATION.

func SecureVerificationRequired

func SecureVerificationRequired() gin.HandlerFunc

SecureVerificationRequired protects channel key disclosure. Other sensitive operations validate their narrower proof scopes in their controller.

func SessionCookieOriginGuard

func SessionCookieOriginGuard() gin.HandlerFunc

SessionCookieOriginGuard protects cookie-authenticated refresh/logout endpoints when secure cookie mode is enabled. In insecure local development mode it preserves the legacy behavior and intentionally performs no Origin validation. It never adds CORS response headers and must not be installed on relay routes.

func SetUpLogger

func SetUpLogger(server *gin.Engine)

func SetupContextForChannelTest

func SetupContextForChannelTest(c *gin.Context, channel *model.Channel, modelName string) *types.NewAPIError

SetupContextForChannelTest allows an explicit administrator diagnostic to probe a held account. Ordinary relay dispatch still uses the quota gate; the independent WHAM sampler also remains able to observe recovery.

func SetupContextForFixedChannelKey

func SetupContextForFixedChannelKey(c *gin.Context, channel *model.Channel, modelName string, index int) *types.NewAPIError

SetupContextForFixedChannelKey restores a trusted execution's exact key position without advancing round-robin state. It keeps the normal disabled key and provider-quota gates; callers must still authorize channel/model.

func SetupContextForSelectedChannel

func SetupContextForSelectedChannel(c *gin.Context, channel *model.Channel, modelName string) *types.NewAPIError

func SetupContextForToken

func SetupContextForToken(c *gin.Context, token *model.Token, parts ...string) error

func StatsMiddleware

func StatsMiddleware() gin.HandlerFunc

StatsMiddleware 统计中间件

func SystemPerformanceCheck

func SystemPerformanceCheck() gin.HandlerFunc

SystemPerformanceCheck 检查系统性能中间件

func TaskOperationAuth

func TaskOperationAuth() gin.HandlerFunc

TaskOperationAuth authenticates either a live dashboard session or an API token for the isolated read-only task-operation route. Relay TokenAuth and TokenAuthReadOnly are intentionally not reused: this endpoint allows expired/exhausted tokens while requiring an authoritative primary-database token lookup and continuing to reject disabled, deleted and unknown tokens.

func TokenAuth

func TokenAuth() func(c *gin.Context)

func TokenAuthReadOnly

func TokenAuthReadOnly() func(c *gin.Context)

TokenAuthReadOnly 宽松版本的令牌认证中间件,用于只读查询接口。 只验证令牌 key 是否存在,不检查令牌状态、过期时间和额度。 即使令牌已过期、已耗尽或已禁用,也允许访问。 仍然检查用户是否被封禁。

func TokenOrUserAuth

func TokenOrUserAuth() func(c *gin.Context)

TokenOrUserAuth allows either session-based user auth or API token auth. Used for endpoints that need to be accessible from both the dashboard and API clients.

func TryUserAuth

func TryUserAuth() func(c *gin.Context)

func TurnstileCheck

func TurnstileCheck() gin.HandlerFunc

func UploadRateLimit

func UploadRateLimit() func(c *gin.Context)

func UserAuth

func UserAuth() func(c *gin.Context)

func UserCriticalRateLimit

func UserCriticalRateLimit(scope string) func(c *gin.Context)

func Version

func Version() gin.HandlerFunc

func WssAuth

func WssAuth(c *gin.Context)

Types

type HTTPStats

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

HTTPStats 存储HTTP统计信息

type ModelRequest

type ModelRequest struct {
	Model string `json:"model"`
	Group string `json:"group,omitempty"`
}

type StatsInfo

type StatsInfo struct {
	ActiveConnections int64 `json:"active_connections"`
}

StatsInfo 统计信息结构

func GetStats

func GetStats() StatsInfo

GetStats 获取统计信息

Jump to

Keyboard shortcuts

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