config.example.yaml 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  1. # Sub2API Configuration File
  2. # Sub2API 配置文件
  3. #
  4. # Copy this file to /etc/sub2api/config.yaml and modify as needed
  5. # 复制此文件到 /etc/sub2api/config.yaml 并根据需要修改
  6. #
  7. # Documentation / 文档: https://github.com/Wei-Shaw/sub2api
  8. # =============================================================================
  9. # Server Configuration
  10. # 服务器配置
  11. # =============================================================================
  12. server:
  13. # Bind address (0.0.0.0 for all interfaces)
  14. # 绑定地址(0.0.0.0 表示监听所有网络接口)
  15. host: "0.0.0.0"
  16. # Port to listen on
  17. # 监听端口
  18. port: 8080
  19. # Mode: "debug" for development, "release" for production
  20. # 运行模式:"debug" 用于开发,"release" 用于生产环境
  21. mode: "release"
  22. # Return Server-Timing for authenticated requests made by the Admin web UI
  23. # 为管理端 Web 页面发出的已认证请求返回 Server-Timing
  24. enable_server_timing: false
  25. # Frontend base URL used to generate external links in emails (e.g. password reset)
  26. # 用于生成邮件中的外部链接(例如:重置密码链接)的前端基础地址
  27. # Example: "https://example.com"
  28. frontend_url: ""
  29. # Maximum time to receive complete request headers. Does not limit response streams.
  30. # 完整读取请求头的最大时间;不限制响应流持续时间。
  31. read_header_timeout: 10
  32. # Request header limit in bytes (64 KiB); also bounds the HTTP/2 header list.
  33. # 请求头上限(字节,默认 64 KiB);同时约束 HTTP/2 header list。
  34. max_header_bytes: 65536
  35. # Keep-alive idle timeout in seconds.
  36. # Keep-Alive 空闲连接超时(秒)。
  37. idle_timeout: 120
  38. # Trusted proxies used when security.trust_forwarded_ip_for_api_key_acl is false.
  39. # List only the exact proxy addresses that connect directly to Sub2API.
  40. # Set [] explicitly to disable forwarded-IP trust in high-security mode.
  41. # security.trust_forwarded_ip_for_api_key_acl=false 时使用的可信代理。
  42. # 只填写直接连接 Sub2API 的精确代理地址;显式设置 [] 可在高安全模式下
  43. # 禁用转发 IP 信任。
  44. trusted_proxies:
  45. - 127.0.0.1/32
  46. - ::1/128
  47. # Global max request body size in bytes (default: 256MB)
  48. # 全局最大请求体大小(字节,默认 256MB)
  49. # Applies to all requests, especially important for h2c first request memory protection
  50. # 适用于所有请求,对 h2c 第一请求的内存保护尤为重要
  51. max_request_body_size: 268435456
  52. # HTTP/2 Cleartext (h2c) configuration
  53. # HTTP/2 Cleartext (h2c) 配置
  54. h2c:
  55. # Enable HTTP/2 Cleartext for client connections
  56. # 启用 HTTP/2 Cleartext 客户端连接
  57. enabled: true
  58. # Max concurrent streams per connection
  59. # 每个连接的最大并发流数量
  60. max_concurrent_streams: 50
  61. # Idle timeout for connections (seconds)
  62. # 连接空闲超时时间(秒)
  63. idle_timeout: 75
  64. # Max frame size in bytes (default: 1MB)
  65. # 最大帧大小(字节,默认 1MB)
  66. max_read_frame_size: 1048576
  67. # Max upload buffer per connection in bytes (default: 2MB)
  68. # 每个连接的最大上传缓冲区(字节,默认 2MB)
  69. max_upload_buffer_per_connection: 2097152
  70. # Max upload buffer per stream in bytes (default: 512KB)
  71. # 每个流的最大上传缓冲区(字节,默认 512KB)
  72. max_upload_buffer_per_stream: 524288
  73. # =============================================================================
  74. # WebAuthn / Passkey Configuration
  75. # WebAuthn / Passkey 配置
  76. # =============================================================================
  77. # Passkeys require HTTPS in production. The RP ID is the domain only (no scheme
  78. # or port), while RP origins are exact browser origins.
  79. # Passkey 在生产环境要求 HTTPS。RP ID 只填写域名(不含协议和端口),RP origins
  80. # 填写浏览器访问使用的完整 Origin。
  81. webauthn:
  82. enabled: false
  83. rp_display_name: "Sub2API"
  84. # Example / 示例: "sub2api.example.com"
  85. rp_id: ""
  86. # Example / 示例: ["https://sub2api.example.com"]
  87. rp_origins: []
  88. # =============================================================================
  89. # Run Mode Configuration
  90. # 运行模式配置
  91. # =============================================================================
  92. # Run mode: "standard" (default) or "simple" (for internal use)
  93. # 运行模式:"standard"(默认)或 "simple"(内部使用)
  94. # - standard: Full SaaS features with billing/balance checks
  95. # - standard: 完整 SaaS 功能,包含计费和余额校验
  96. # - simple: Hides SaaS features and skips billing/balance checks
  97. # - simple: 隐藏 SaaS 功能,跳过计费和余额校验
  98. run_mode: "standard"
  99. # =============================================================================
  100. # CORS Configuration
  101. # 跨域资源共享 (CORS) 配置
  102. # =============================================================================
  103. cors:
  104. # Allowed origins list. Leave empty to disable cross-origin requests.
  105. # 允许的来源列表。留空则禁用跨域请求。
  106. allowed_origins: []
  107. # Allow credentials (cookies/authorization headers). Cannot be used with "*".
  108. # 允许携带凭证(cookies/授权头)。不能与 "*" 通配符同时使用。
  109. allow_credentials: true
  110. # =============================================================================
  111. # Security Configuration
  112. # 安全配置
  113. # =============================================================================
  114. security:
  115. # Legacy compatibility switch. When true, raw forwarded headers take over
  116. # server.trusted_proxies. Set false to enforce the trusted proxy chain above.
  117. # 旧版兼容开关。开启时原始转发头会接管 server.trusted_proxies;关闭后严格
  118. # 使用上方配置的可信代理链。示例配置采用高安全模式。
  119. trust_forwarded_ip_for_api_key_acl: false
  120. # Optional client-IP headers for third-party CDNs, checked in list order before
  121. # CF-Connecting-IP, X-Real-IP, and X-Forwarded-For. Valid only while the legacy
  122. # compatibility switch above is true; maximum 16 unique HTTP header names.
  123. # 第三方 CDN 的可选客户端 IP 请求头,按列表顺序优先于内置请求头解析。
  124. # 仅在上方旧版兼容开关为 true 时生效;最多配置 16 个不重复的合法 HTTP 头名。
  125. # Environment / 环境变量: SECURITY_FORWARDED_CLIENT_IP_HEADERS=True-Client-IP,X-CDN-Client-IP
  126. forwarded_client_ip_headers: []
  127. # Example / 示例:
  128. # forwarded_client_ip_headers:
  129. # - "True-Client-IP"
  130. # - "X-CDN-Client-IP"
  131. url_allowlist:
  132. # Enable URL allowlist validation (disable to skip all URL checks)
  133. # 启用 URL 白名单验证(禁用则跳过所有 URL 检查)
  134. enabled: false
  135. # Allowed upstream hosts for API proxying
  136. # 允许代理的上游 API 主机列表
  137. upstream_hosts:
  138. - "api.openai.com"
  139. - "api.anthropic.com"
  140. - "api.kimi.com"
  141. - "api.moonshot.ai"
  142. - "api.moonshot.cn"
  143. - "open.bigmodel.cn"
  144. - "api.minimaxi.com"
  145. - "generativelanguage.googleapis.com"
  146. - "cloudcode-pa.googleapis.com"
  147. - "*.openai.azure.com"
  148. # Allowed hosts for pricing data download
  149. # 允许下载定价数据的主机列表
  150. pricing_hosts:
  151. - "raw.githubusercontent.com"
  152. # Allowed hosts for CRS sync (required when using CRS sync)
  153. # 允许 CRS 同步的主机列表(使用 CRS 同步功能时必须配置)
  154. crs_hosts: []
  155. # Allow localhost/private IPs for upstream/pricing/CRS (use only in trusted networks)
  156. # 允许本地/私有 IP 地址用于上游/定价/CRS(仅在可信网络中使用)
  157. allow_private_hosts: true
  158. # Allow http:// URLs when allowlist is disabled (default: true; set to false to require https)
  159. # 白名单禁用时是否允许 http:// URL(默认: true,设为 false 则仅允许 https)
  160. allow_insecure_http: true
  161. response_headers:
  162. # Enable configurable response header filtering (default: true)
  163. # 启用可配置的响应头过滤(默认启用,过滤上游敏感响应头)
  164. enabled: true
  165. # Extra allowed response headers from upstream
  166. # 额外允许的上游响应头
  167. additional_allowed: []
  168. # Force-remove response headers from upstream
  169. # 强制移除的上游响应头
  170. force_remove: []
  171. csp:
  172. # Enable Content-Security-Policy header
  173. # 启用内容安全策略 (CSP) 响应头
  174. enabled: true
  175. # Default CSP policy (override if you host assets on other domains)
  176. # 默认 CSP 策略(如果静态资源托管在其他域名,请自行覆盖)
  177. # Note: __CSP_NONCE__ will be replaced with 'nonce-xxx' at request time for inline script security
  178. # 注意:__CSP_NONCE__ 会在请求时被替换为 'nonce-xxx',用于内联脚本安全
  179. policy: "default-src 'self'; worker-src 'self' blob:; script-src 'self' __CSP_NONCE__ https://challenges.cloudflare.com https://*.alicdn.com https://static.cloudflareinsights.com https://turing.captcha.qcloud.com https://turing.captcha.gtimg.com https://ca.turing.captcha.qcloud.com https://global.turing.captcha.gtimg.com https://www.tycaptcha.com https://cloudcache.tencentcs.com https://*.stripe.com https://static.airwallex.com https://checkout.airwallex.com https://static-demo.airwallex.com https://checkout-demo.airwallex.com; style-src 'self' 'unsafe-inline' https://*.captcha.gtimg.com https://fonts.googleapis.com https://*.alicdn.com https://static.airwallex.com https://checkout.airwallex.com https://static-demo.airwallex.com https://checkout-demo.airwallex.com; img-src 'self' data: blob: https:; font-src 'self' data: https://fonts.gstatic.com; connect-src 'self' https://turing.captcha.qcloud.com https://www.tycaptcha.com https://rce.tencentrio.com https:; frame-src 'self' https://challenges.cloudflare.com https://turing.captcha.qcloud.com https://ca.turing.captcha.qcloud.com https://www.tycaptcha.com https://*.stripe.com https://checkout.airwallex.com https://checkout-demo.airwallex.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"
  180. proxy_probe:
  181. # Allow skipping TLS verification for proxy probe (debug only)
  182. # 允许代理探测时跳过 TLS 证书验证(仅用于调试)
  183. insecure_skip_verify: false
  184. # Optional ordered probe targets. Leave empty to use the built-in ip-api/ipify fallback.
  185. # parser supports: ip-api, ipify, chatgpt-trace
  186. # 可选的有序探测目标。留空时使用内置 ip-api/ipify 回退。
  187. # parser 支持:ip-api、ipify、chatgpt-trace
  188. urls: []
  189. # urls:
  190. # - url: "https://chatgpt.com/cdn-cgi/trace"
  191. # parser: "chatgpt-trace"
  192. # - url: "https://api64.ipify.org?format=json"
  193. # parser: "ipify"
  194. proxy_fallback:
  195. # Allow auxiliary services (update check, pricing data) to fallback to direct
  196. # connection when proxy initialization fails. Does NOT affect AI gateway connections.
  197. # 辅助服务(更新检查、定价数据拉取)代理初始化失败时是否允许回退直连。
  198. # 不影响 AI 账号网关连接。默认 false:fail-fast 防止 IP 泄露。
  199. allow_direct_on_error: false
  200. # =============================================================================
  201. # Gateway Configuration
  202. # 网关配置
  203. # =============================================================================
  204. gateway:
  205. # Timeout for waiting upstream response headers (seconds)
  206. # 等待上游响应头超时时间(秒)
  207. response_header_timeout: 600
  208. # OpenAI/Codex upstream response header timeout (seconds, 0=disabled)
  209. # OpenAI/Codex 等待上游响应头超时时间(秒,0=禁用本地响应头超时)
  210. openai_response_header_timeout: 0
  211. # Grok text Responses first-byte timeout (seconds, 0=disabled; default 120)
  212. # Grok 文本 Responses 首字节超时时间(秒,0=禁用;默认 120)
  213. grok_response_header_timeout: 120
  214. # Native OpenAI HTTP Responses first semantic output timeout (seconds, 0=disabled)
  215. # Includes response-header wait; does not apply to passthrough or WebSocket transports.
  216. # A timed-out request may already have incurred upstream usage; account failover can therefore duplicate upstream billing.
  217. # 超时请求可能已产生上游用量;切换账号重试可能导致上游重复计费。
  218. # Pre-output attempt staging is capped at 8 MiB; overflow fails over without exposing partial SSE data.
  219. # 首次输出前的单次尝试暂存上限为 8 MiB;溢出时切号且不暴露不完整 SSE 数据。
  220. openai_first_output_timeout_seconds: 0
  221. # Optional high/xhigh/max override (seconds, 0=use the standard timeout)
  222. openai_high_effort_first_output_timeout_seconds: 0
  223. # Max request body size in bytes (default: 256MB)
  224. # 请求体最大字节数(默认 256MB)
  225. max_body_size: 268435456
  226. # Pure-text endpoint body limit (embeddings and alpha/search), default 32 MiB.
  227. # 纯文本端点请求体上限(embeddings、alpha/search),默认 32 MiB。
  228. text_max_body_size: 33554432
  229. # Max bytes to read for non-stream upstream responses (default: 8MB)
  230. # 非流式上游响应体读取上限(默认 8MB)
  231. upstream_response_read_max_bytes: 8388608
  232. # Max bytes to read for upstream model-list responses (default: 8MB)
  233. # 上游模型列表响应体读取上限(默认 8MB)
  234. models_list_read_max_bytes: 8388608
  235. # Max bytes to read for proxy probe responses (default: 1MB)
  236. # 代理探测响应体读取上限(默认 1MB)
  237. proxy_probe_response_read_max_bytes: 1048576
  238. # Enable Gemini upstream response header debug logs (default: false)
  239. # 是否开启 Gemini 上游响应头调试日志(默认 false)
  240. gemini_debug_response_headers: false
  241. # Connection pool isolation strategy:
  242. # 连接池隔离策略:
  243. # - proxy: Isolate by proxy, same proxy shares connection pool (suitable for few proxies, many accounts)
  244. # - proxy: 按代理隔离,同一代理共享连接池(适合代理少、账户多)
  245. # - account: Isolate by account, same account shares connection pool (suitable for few accounts, strict isolation)
  246. # - account: 按账户隔离,同一账户共享连接池(适合账户少、需严格隔离)
  247. # - account_proxy: Isolate by account+proxy combination (default, finest granularity)
  248. # - account_proxy: 按账户+代理组合隔离(默认,最细粒度)
  249. connection_pool_isolation: "account_proxy"
  250. # Force Codex CLI mode: treat all /openai/v1/responses requests as Codex CLI.
  251. # 强制按 Codex CLI 处理 /openai/v1/responses 请求(用于网关未透传/改写 User-Agent 的兜底)。
  252. #
  253. # 注意:开启后会影响所有客户端的行为(不仅限于 VS Code / Codex CLI),请谨慎开启。
  254. force_codex_cli: false
  255. # Stop rewriting load-shed Codex originators to the official CLI identity.
  256. # 关闭「把落在上游降载桶的 Codex originator 改写为官方 CLI 身份(codex_cli_rs)」。
  257. #
  258. # 上游 /backend-api/codex 按 originator 分桶调度容量:命中降载桶的请求即使 HTTP 200,
  259. # 也会立刻推 server_is_overloaded 错误事件,网关据此判定瞬时上游故障并冷却账号,
  260. # 对外表现为 Codex 账号频繁过载不可用。归一化只替换身份段,保留版本/OS/架构/终端指纹,
  261. # 改写后 originator 与 User-Agent 首段仍然配套。
  262. #
  263. # 默认 false(即归一化开启);仅当上游调整分桶、使归一化反而落入降载桶时才置 true。
  264. disable_codex_originator_normalization: false
  265. # Enable Codex image-generation bridge injection for /openai/v1/responses.
  266. # 是否为 Codex /responses 请求自动注入 image_generation 工具与桥接指令。
  267. #
  268. # Default false keeps text-only Codex requests text-only. Explicit client-provided
  269. # image_generation tools are still forwarded when the group allows image generation.
  270. # 默认 false:保持纯文本 Codex 请求不被改写;客户端显式提供 image_generation tool 时,
  271. # 仍会在分组允许图片生成的情况下正常转发。
  272. codex_image_generation_bridge_enabled: false
  273. # Optional: template file used to build the final top-level Codex `instructions`.
  274. # 可选:用于构建最终 Codex 顶层 `instructions` 的模板文件路径。
  275. #
  276. # This is applied on the `/v1/messages -> Responses/Codex` conversion path,
  277. # after Claude `system` has already been normalized into Codex `instructions`.
  278. # 该模板作用于 `/v1/messages -> Responses/Codex` 转换链路,且发生在 Claude `system`
  279. # 已经被归一化为 Codex `instructions` 之后。
  280. #
  281. # The template can reference:
  282. # 模板可引用:
  283. # - {{ .ExistingInstructions }} : converted client instructions/system
  284. # - {{ .OriginalModel }} : original requested model
  285. # - {{ .NormalizedModel }} : normalized routing model
  286. # - {{ .BillingModel }} : billing model
  287. # - {{ .UpstreamModel }} : final upstream model
  288. #
  289. # If you want to preserve client system prompts, keep {{ .ExistingInstructions }}
  290. # somewhere in the template. If omitted, the template output fully replaces it.
  291. # 如需保留客户端 system 提示词,请在模板中显式包含 {{ .ExistingInstructions }}。
  292. # 若省略,则模板输出会完全覆盖它。
  293. #
  294. # Docker users can mount a host file to /app/data/codex-instructions.md.tmpl
  295. # and point this field there.
  296. # Docker 用户可将宿主机文件挂载到 /app/data/codex-instructions.md.tmpl,
  297. # 然后把本字段指向该路径。
  298. forced_codex_instructions_template_file: ""
  299. # OpenAI 透传模式是否放行客户端超时头(如 x-stainless-timeout)
  300. # 默认 false:过滤超时头,降低上游提前断流风险。
  301. openai_passthrough_allow_timeout_headers: false
  302. # Model used for OpenAI /responses/compact upstream requests (default: gpt-5.4).
  303. # OpenAI /responses/compact 上游模型(默认 gpt-5.4)。
  304. # Use this to avoid compact failures when newer models are not yet supported by the compact endpoint.
  305. # 当 compact 端点暂未支持更新模型时,可通过这里降级规避失败。
  306. openai_compact_model: "gpt-5.4"
  307. # ChatGPT Frameless Live 单会话硬上限(秒)。
  308. live:
  309. max_session_duration_seconds: 3600
  310. # OpenAI Responses WebSocket 配置(默认开启,可按需回滚到 HTTP)
  311. openai_ws:
  312. # 新版 WS mode 路由(默认关闭)。关闭时忽略账号级 WS mode(包括 http_bridge),保持 legacy ctx_pool 行为。
  313. # 环境变量:GATEWAY_OPENAI_WS_MODE_ROUTER_V2_ENABLED=true
  314. mode_router_v2_enabled: false
  315. # ingress 默认模式:off|ctx_pool|passthrough|http_bridge(仅 mode_router_v2_enabled=true 生效;关闭时账号级 WS mode 被忽略)
  316. # 兼容旧值:shared/dedicated 会按 ctx_pool 处理。
  317. ingress_mode_default: ctx_pool
  318. # 完整读取并解压首条客户端消息的总超时(秒);大请求或慢链路可调高到 120-300。
  319. client_first_message_timeout_seconds: 30
  320. # Close a client WebSocket that stays idle between completed turns (seconds). Set 0 to disable.
  321. ingress_inter_turn_idle_timeout_seconds: 300
  322. # Limit live client WebSocket ingress sessions per API key across all instances. Set 0 to disable.
  323. max_ingress_connections_per_api_key: 64
  324. # 全局总开关,默认 true;关闭时所有请求保持原有 HTTP/SSE 路由
  325. enabled: true
  326. # 按账号类型细分开关
  327. oauth_enabled: true
  328. apikey_enabled: true
  329. # 全局强制 OpenAI Responses 上游使用 HTTP/SSE,不使用 WebSocket(紧急回滚开关)。
  330. # 此开关不强制 HTTP/1.1;HTTP/2 由 gateway.openai_http2 单独控制。
  331. force_http: false
  332. # 允许在 WSv2 下按策略恢复 store=true(默认 false)
  333. allow_store_recovery: false
  334. # ingress 模式收到 previous_response_not_found 时,自动去掉 previous_response_id 重试一次(默认 true)
  335. ingress_previous_response_recovery_enabled: true
  336. # store=false 且无可复用会话连接时的策略:
  337. # strict=强制新建连接(隔离优先),adaptive=仅在高风险失败后强制新建,off=尽量复用(性能优先)
  338. store_disabled_conn_mode: strict
  339. # store=false 且无可复用会话连接时,是否强制新建连接(默认 true,优先会话隔离)
  340. # 兼容旧配置:仅在 store_disabled_conn_mode 未配置时生效
  341. store_disabled_force_new_conn: true
  342. # 是否启用 WSv2 generate=false 预热(默认 false)
  343. prewarm_generate_enabled: false
  344. # 协议 feature 开关,v2 优先于 v1
  345. responses_websockets: false
  346. responses_websockets_v2: true
  347. # 连接池参数(按账号池化复用)
  348. max_conns_per_account: 128
  349. min_idle_per_account: 4
  350. max_idle_per_account: 12
  351. # 是否按账号并发动态计算连接池上限:
  352. # effective_max_conns = min(max_conns_per_account, ceil(account.concurrency * factor))
  353. dynamic_max_conns_by_account_concurrency_enabled: true
  354. # 按账号类型分别设置系数(OAuth / API Key)
  355. oauth_max_conns_factor: 1.0
  356. apikey_max_conns_factor: 1.0
  357. dial_timeout_seconds: 10
  358. read_timeout_seconds: 900
  359. write_timeout_seconds: 120
  360. pool_target_utilization: 0.7
  361. queue_limit_per_conn: 64
  362. # 流式写出批量 flush 参数
  363. event_flush_batch_size: 1
  364. event_flush_interval_ms: 10
  365. # 预热触发冷却(毫秒)
  366. prewarm_cooldown_ms: 300
  367. # WS 回退到 HTTP 后的冷却时间(秒),用于避免 WS/HTTP 来回抖动;0 表示关闭冷却
  368. fallback_cooldown_seconds: 30
  369. # WS 重试退避参数(毫秒)
  370. retry_backoff_initial_ms: 120
  371. retry_backoff_max_ms: 2000
  372. # 抖动比例(0-1)
  373. retry_jitter_ratio: 0.2
  374. # 单次请求 WS 重试总预算(毫秒);建议设置为有限值,避免重试拉高 TTFT 长尾
  375. retry_total_budget_ms: 5000
  376. # payload_schema 日志采样率(0-1);降低热路径日志放大
  377. payload_log_sample_rate: 0.2
  378. # 调度与粘连参数
  379. lb_top_k: 7
  380. sticky_session_ttl_seconds: 3600
  381. # 会话哈希迁移兼容开关:新 key 未命中时回退读取旧 SHA-256 key
  382. session_hash_read_old_fallback: true
  383. # 会话哈希迁移兼容开关:写入时双写旧 SHA-256 key(短 TTL)
  384. session_hash_dual_write_old: true
  385. # context 元数据迁移兼容开关:保留旧 ctxkey.* 读取/注入桥接
  386. metadata_bridge_enabled: true
  387. sticky_response_id_ttl_seconds: 3600
  388. # 兼容旧键:当 sticky_response_id_ttl_seconds 缺失时回退该值
  389. sticky_previous_response_ttl_seconds: 3600
  390. scheduler_score_weights:
  391. priority: 1.0
  392. load: 1.0
  393. queue: 0.7
  394. error_rate: 0.8
  395. ttft: 0.5
  396. # use-it-or-lose-it:倾向「会话窗口最早重置」的账号,剩余重置时间越短得分越高。
  397. # 0 表示关闭(默认,不改变原有行为);调大可让即将重置的账号被优先用尽。
  398. reset: 0.0
  399. # 倾向 7d 剩余额度更健康的账号;0 表示关闭(默认,不改变原有行为),小流量灰度可设为 0.3。
  400. quota_headroom: 0.0
  401. # 倾向上游声明倍率更低的账号;0 表示关闭(默认),建议启用时从 1.5 开始。
  402. upstream_cost: 0.0
  403. # OpenAI 高级调度器补充配置
  404. openai_scheduler:
  405. # 是否允许 session_hash sticky 在账号健康度恶化时临时逃逸;false 可一键回退旧行为
  406. sticky_escape_enabled: true
  407. # TTFT EWMA 超过该阈值(毫秒)时跳过 sticky,默认 15s,避免轻微抖动就逃逸
  408. sticky_escape_ttft_ms: 15000
  409. # 错误率 EWMA 超过该阈值时跳过 sticky,默认 0.5,仅在明显降级时触发
  410. sticky_escape_error_rate: 0.5
  411. # OpenAI HTTP upstream protocol strategy.
  412. # OpenAI HTTP 上游协议策略(默认 HTTP/2;代理明确不兼容时可临时回退 HTTP/1.1)。
  413. openai_http2:
  414. enabled: true
  415. allow_proxy_fallback_to_http1: true
  416. fallback_error_threshold: 2
  417. fallback_window_seconds: 60
  418. fallback_ttl_seconds: 600
  419. # OpenAI Responses SSE 代理断流熔断;按 proxy_id 跨账号隔离,仅影响下一次调度。
  420. # 隔离是偏好而非硬闸:当全部候选账号都在被隔离代理下时自动放行(fail-open),
  421. # 不会因熔断而返回"无可用账号"。3 秒内的并发断流合并为一次失败事件。
  422. openai_proxy_stream_circuit:
  423. disabled: false
  424. failure_threshold: 2
  425. window_seconds: 60
  426. ttl_seconds: 600
  427. # Grok free-tier local soft gate (scheduler filter only; admin QueryQuota/import probe bypasses it).
  428. # Enabled by default because free detection requires an explicit subscription_tier/plan_type of "free".
  429. # Stats/query failures fail open so DB issues do not block all Grok traffic.
  430. grok:
  431. # Email/password OAuth is off by default and hidden in the admin UI.
  432. # Setting true enables POST /admin/grok/oauth/password (password → SSO → Build OAuth).
  433. # Prefer SSO cookie, browser OAuth, or refresh_token re-auth in production.
  434. password_auth_enabled: false
  435. free_quota_soft_gate_enabled: true
  436. free_quota_token_limit: 500000
  437. free_quota_soft_gate_percent: 95
  438. free_quota_window_hours: 24
  439. # Stats cache for free-tier soft gate. Hot path never waits on DB: misses
  440. # fail open and refresh in the background. Prefer >= 60s in production.
  441. free_quota_stats_cache_seconds: 60
  442. # HTTP upstream connection pool settings (HTTP/2 + multi-proxy scenario defaults)
  443. # HTTP 上游连接池配置(HTTP/2 + 多代理场景默认值)
  444. # Max idle connections across all hosts
  445. # 所有主机的最大空闲连接数
  446. max_idle_conns: 2560
  447. # Max idle connections per host
  448. # 每个主机的最大空闲连接数
  449. max_idle_conns_per_host: 120
  450. # Max connections per host
  451. # 每个主机的最大连接数
  452. max_conns_per_host: 1024
  453. # Idle connection timeout (seconds)
  454. # 空闲连接超时时间(秒)
  455. idle_conn_timeout_seconds: 90
  456. # Upstream client cache settings
  457. # 上游连接池客户端缓存配置
  458. # max_upstream_clients: Max cached clients, evicts least recently used when exceeded
  459. # max_upstream_clients: 最大缓存客户端数量,超出后淘汰最久未使用的
  460. max_upstream_clients: 5000
  461. # client_idle_ttl_seconds: Client idle reclaim threshold (seconds), reclaimed when idle and no active requests
  462. # client_idle_ttl_seconds: 客户端空闲回收阈值(秒),超时且无活跃请求时回收
  463. client_idle_ttl_seconds: 900
  464. # Concurrency slot expiration time (minutes)
  465. # 并发槽位过期时间(分钟)
  466. concurrency_slot_ttl_minutes: 30
  467. # Stream data interval timeout (seconds), 0=disable
  468. # 流数据间隔超时(秒),0=禁用
  469. stream_data_interval_timeout: 180
  470. # Stream keepalive interval (seconds), 0=disable
  471. # 流式 keepalive 间隔(秒),0=禁用
  472. stream_keepalive_interval: 10
  473. # Image stream data interval timeout (seconds), 0=disable; independent from ordinary text streams
  474. # 图片流数据间隔超时(秒),0=禁用;独立于普通文本流式
  475. image_stream_data_interval_timeout: 900
  476. # Image stream keepalive interval (seconds), 0=disable; independent from ordinary text streams
  477. # 图片流式 keepalive 间隔(秒),0=禁用;独立于普通文本流式
  478. image_stream_keepalive_interval: 10
  479. # Non-streaming Images JSON keepalive interval (seconds), 0=disable; commits HTTP 200 after the first heartbeat
  480. # 图片非流式 JSON keepalive 间隔(秒),0=禁用;首个心跳后 HTTP 状态会固化为 200
  481. image_nonstream_keepalive_interval: 0
  482. # Image generation independent concurrency limiter (process-local, default disabled)
  483. # 图片生成独立并发限制(进程级,默认关闭;多实例总上限约为实例数×该值)
  484. image_concurrency:
  485. # Enable image-only concurrency protection; false keeps existing behavior unchanged
  486. # 是否启用图片独立并发保护;false 保持现有行为不变
  487. enabled: false
  488. # Max concurrent image generation requests in this process, 0=unlimited
  489. # 当前进程允许同时处理的图片生成请求数,0=不限制
  490. max_concurrent_requests: 0
  491. # Overflow mode when the image concurrency limit is full: reject/wait
  492. # 图片并发满时的处理方式:reject=立即拒绝,wait=等待槽位
  493. overflow_mode: "reject"
  494. # Wait timeout for overflow_mode=wait (seconds), 0=do not wait
  495. # wait 模式等待图片并发槽位的超时时间(秒),0=不等待
  496. wait_timeout_seconds: 30
  497. # Max image requests waiting in this process when overflow_mode=wait, 0=unlimited
  498. # wait 模式当前进程允许排队等待的图片请求数,0=不限制
  499. max_waiting_requests: 100
  500. # SSE max line size in bytes (default: 40MB)
  501. # SSE 单行最大字节数(默认 40MB)
  502. max_line_size: 41943040
  503. # Log upstream error response body summary (safe/truncated; does not log request content)
  504. # 记录上游错误响应体摘要(安全/截断;不记录请求内容)
  505. log_upstream_error_body: true
  506. # Max bytes to log from upstream error body
  507. # 记录上游错误响应体的最大字节数
  508. log_upstream_error_body_max_bytes: 2048
  509. # Auto inject anthropic-beta header for API-key accounts when needed (default: off)
  510. # 需要时自动为 API-key 账户注入 anthropic-beta 头(默认:关闭)
  511. inject_beta_for_apikey: false
  512. # Allow failover on selected 400 errors (default: off)
  513. # 允许在特定 400 错误时进行故障转移(默认:关闭)
  514. failover_on_400: false
  515. # Scheduling configuration
  516. # 调度配置
  517. scheduling:
  518. # Sticky session max waiting queue size
  519. # 粘性会话最大排队长度
  520. sticky_session_max_waiting: 3
  521. # Sticky session wait timeout (duration)
  522. # 粘性会话等待超时(时间段)
  523. sticky_session_wait_timeout: 120s
  524. # Fallback wait timeout (duration)
  525. # 兜底排队等待超时(时间段)
  526. fallback_wait_timeout: 30s
  527. # Fallback max waiting queue size
  528. # 兜底最大排队长度
  529. fallback_max_waiting: 100
  530. # Prefer the account whose session window resets soonest (use-it-or-lose-it).
  531. # 负载感知选择时优先用尽「会话窗口最早重置」的账号;false 保持
  532. # 原有「优先级 → 负载率 → LRU」行为(默认)。
  533. prefer_soonest_reset: false
  534. # Enable batch load calculation for scheduling
  535. # 启用调度批量负载计算
  536. load_batch_enabled: true
  537. # Tiny in-process TTL for batch load reads in milliseconds (0 disables)
  538. # 调度批量负载读取的进程内短缓存 TTL(毫秒,0 表示禁用)
  539. load_batch_cache_ttl_ms: 200
  540. # Slot cleanup interval (duration)
  541. # 并发槽位清理周期(时间段)
  542. slot_cleanup_interval: 30s
  543. # 是否允许受控回源到 DB(默认 true,保持现有行为)
  544. db_fallback_enabled: true
  545. # 受控回源超时(秒),0 表示不额外收紧超时
  546. db_fallback_timeout_seconds: 0
  547. # 受控回源限流(实例级 QPS),0 表示不限制
  548. db_fallback_max_qps: 0
  549. # outbox 轮询周期(秒)
  550. outbox_poll_interval_seconds: 1
  551. # outbox 滞后告警阈值(秒)
  552. outbox_lag_warn_seconds: 5
  553. # outbox 触发强制重建阈值(秒)
  554. outbox_lag_rebuild_seconds: 10
  555. # outbox 连续滞后触发次数
  556. outbox_lag_rebuild_failures: 3
  557. # outbox 积压触发重建阈值(行数)
  558. outbox_backlog_rebuild_rows: 10000
  559. # 全量重建周期(秒),0 表示禁用
  560. full_rebuild_interval_seconds: 300
  561. # TLS fingerprint simulation / TLS 指纹伪装
  562. # Default profile "claude_cli_v2" simulates Node.js 20.x
  563. # 默认模板 "claude_cli_v2" 模拟 Node.js 20.x 指纹
  564. tls_fingerprint:
  565. enabled: true
  566. # profiles:
  567. # profile_1:
  568. # name: "Custom Profile 1"
  569. # profile_2:
  570. # name: "Custom Profile 2"
  571. # =============================================================================
  572. # Logging Configuration
  573. # 日志配置
  574. # =============================================================================
  575. log:
  576. # Log level: debug/info/warn/error
  577. # 日志级别:debug/info/warn/error
  578. level: "info"
  579. # Log format: json/console
  580. # 日志格式:json/console
  581. format: "console"
  582. # Service name field written into each log line
  583. # 每条日志都会附带 service 字段
  584. service_name: "sub2api"
  585. # Environment field written into each log line
  586. # 每条日志都会附带 env 字段
  587. env: "production"
  588. # Include caller information
  589. # 是否输出调用方位置信息
  590. caller: true
  591. # Stacktrace threshold: none/error/fatal
  592. # 堆栈输出阈值:none/error/fatal
  593. stacktrace_level: "error"
  594. output:
  595. # Keep stdout/stderr output for container log collection
  596. # 保持标准输出用于容器日志采集
  597. to_stdout: true
  598. # Enable file output (default path auto-derived)
  599. # 启用文件输出(默认路径自动推导)
  600. to_file: true
  601. # Empty means:
  602. # - DATA_DIR set: {{DATA_DIR}}/logs/sub2api.log
  603. # - otherwise: /app/data/logs/sub2api.log
  604. # 留空时:
  605. # - 设置 DATA_DIR:{{DATA_DIR}}/logs/sub2api.log
  606. # - 否则:/app/data/logs/sub2api.log
  607. file_path: ""
  608. rotation:
  609. # Max file size before rotation (MB)
  610. # 单文件滚动阈值(MB)
  611. max_size_mb: 100
  612. # Number of rotated files to keep (0 means unlimited)
  613. # 保留历史文件数量(0 表示不限制)
  614. max_backups: 10
  615. # Number of days to keep old log files (0 means unlimited)
  616. # 历史日志保留天数(0 表示不限制)
  617. max_age_days: 7
  618. # Compress rotated files
  619. # 是否压缩历史日志
  620. compress: true
  621. # Use local time for timestamp in rotated filename
  622. # 滚动文件名时间戳使用本地时区
  623. local_time: true
  624. sampling:
  625. # Enable zap sampler (reduce high-frequency repetitive logs)
  626. # 启用 zap 采样(减少高频重复日志)
  627. enabled: false
  628. # Number of first entries per second to always log
  629. # 每秒无采样保留的前 N 条日志
  630. initial: 100
  631. # Thereafter keep 1 out of N entries per second
  632. # 之后每 N 条保留 1 条
  633. thereafter: 100
  634. # Token refresh behavior
  635. # token 刷新行为控制
  636. token_refresh:
  637. # Candidate accounts loaded per cursor page (maximum 1000)
  638. # 每个游标分页加载的候选账号数量(最大 1000)
  639. candidate_page_size: 200
  640. # Maximum concurrent refresh attempts per provider (maximum 32)
  641. # 每个平台的最大并发刷新数(最大 32)
  642. provider_concurrency: 4
  643. # Per-provider refresh requests per second in each server process (maximum 100)
  644. # 每个服务进程中每个平台每秒允许的刷新请求数(最大 100)
  645. provider_qps: 2
  646. # Consecutive transient failures that contain a provider for the current cycle (maximum 100)
  647. # 当前周期内触发平台级熔断的连续临时失败次数(最大 100)
  648. provider_failure_threshold: 3
  649. # Timeout for one upstream refresh attempt, in seconds (maximum 300)
  650. # 单次上游刷新尝试的超时时间(秒,最大 300)
  651. attempt_timeout_seconds: 15
  652. # Total timeout for one background refresh cycle, in seconds (maximum 3600)
  653. # 单个后台刷新周期的总超时时间(秒,最大 3600)
  654. cycle_timeout_seconds: 240
  655. # =============================================================================
  656. # API Key Auth Cache Configuration
  657. # API Key 认证缓存配置
  658. # =============================================================================
  659. api_key_auth_cache:
  660. # L1 cache size (entries), in-process LRU/TTL cache
  661. # L1 缓存容量(条目数),进程内 LRU/TTL 缓存
  662. l1_size: 65535
  663. # L1 cache TTL (seconds)
  664. # L1 缓存 TTL(秒)
  665. l1_ttl_seconds: 15
  666. # L2 cache TTL (seconds), stored in Redis
  667. # L2 缓存 TTL(秒),Redis 中存储
  668. l2_ttl_seconds: 300
  669. # Negative cache TTL (seconds)
  670. # 负缓存 TTL(秒)
  671. negative_ttl_seconds: 30
  672. # TTL jitter percent (0-100)
  673. # TTL 抖动百分比(0-100)
  674. jitter_percent: 10
  675. # Enable singleflight for cache misses
  676. # 缓存未命中时启用 singleflight 合并回源
  677. singleflight: true
  678. # Maximum concurrent database lookups for authentication cache misses
  679. # 认证缓存未命中时允许并发回源数据库的最大数量
  680. lookup_concurrency: 64
  681. # Process-local invalid-auth abuse protection. Counts only missing, malformed,
  682. # deprecated-query, and confirmed invalid credentials; valid requests and
  683. # Redis/DB failures do not consume the budget.
  684. # 本机无效鉴权防护:仅统计缺失、格式错误、废弃 query 及确认无效的凭据。
  685. invalid_abuse:
  686. enabled: true
  687. # Invalid attempts per trusted client IP (IPv6 grouped by /64) per window.
  688. # 每个可信客户端 IP(IPv6 按 /64 聚合)在窗口内允许的无效次数。
  689. threshold: 120
  690. window_seconds: 60
  691. block_seconds: 60
  692. # Maximum tracked client identities per process; memory remains bounded.
  693. # 每进程最多跟踪的客户端身份数量,确保内存有界。
  694. capacity: 16384
  695. # =============================================================================
  696. # Dashboard Cache Configuration
  697. # 仪表盘缓存配置
  698. # =============================================================================
  699. dashboard_cache:
  700. # Enable dashboard cache
  701. # 启用仪表盘缓存
  702. enabled: true
  703. # Redis key prefix for multi-environment isolation
  704. # Redis key 前缀,用于多环境隔离
  705. key_prefix: "sub2api:"
  706. # Fresh TTL (seconds); within this window cached stats are considered fresh
  707. # 新鲜阈值(秒);命中后处于该窗口视为新鲜数据
  708. stats_fresh_ttl_seconds: 15
  709. # Cache TTL (seconds) stored in Redis
  710. # Redis 缓存 TTL(秒)
  711. stats_ttl_seconds: 30
  712. # Async refresh timeout (seconds)
  713. # 异步刷新超时(秒)
  714. stats_refresh_timeout_seconds: 30
  715. # =============================================================================
  716. # Dashboard Aggregation Configuration
  717. # 仪表盘预聚合配置(重启生效)
  718. # =============================================================================
  719. dashboard_aggregation:
  720. # Enable aggregation job
  721. # 启用聚合作业
  722. enabled: true
  723. # Refresh interval (seconds)
  724. # 刷新间隔(秒)
  725. interval_seconds: 60
  726. # Lookback window (seconds) for late-arriving data
  727. # 回看窗口(秒),处理迟到数据
  728. lookback_seconds: 120
  729. # Allow manual backfill
  730. # 允许手动回填
  731. backfill_enabled: false
  732. # Backfill max range (days)
  733. # 回填最大跨度(天)
  734. backfill_max_days: 31
  735. # Recompute recent N days on startup
  736. # 启动时重算最近 N 天
  737. recompute_days: 2
  738. # Retention windows (days)
  739. # 保留窗口(天)
  740. retention:
  741. # Raw usage_logs retention
  742. # 原始 usage_logs 保留天数
  743. usage_logs_days: 90
  744. # Hourly aggregation retention
  745. # 小时聚合保留天数
  746. hourly_days: 180
  747. # Daily aggregation retention
  748. # 日聚合保留天数
  749. daily_days: 730
  750. # =============================================================================
  751. # Usage Cleanup Task Configuration
  752. # 使用记录清理任务配置(重启生效)
  753. # =============================================================================
  754. usage_cleanup:
  755. # Enable cleanup task worker
  756. # 启用清理任务执行器
  757. enabled: true
  758. # Max date range (days) per task
  759. # 单次任务最大时间跨度(天)
  760. max_range_days: 31
  761. # Batch delete size
  762. # 单批删除数量
  763. batch_size: 5000
  764. # Worker interval (seconds)
  765. # 执行器轮询间隔(秒)
  766. worker_interval_seconds: 10
  767. # Task execution timeout (seconds)
  768. # 单次任务最大执行时长(秒)
  769. task_timeout_seconds: 1800
  770. # =============================================================================
  771. # HTTP 写接口幂等配置
  772. # Idempotency Configuration
  773. # =============================================================================
  774. idempotency:
  775. # Observe-only 模式:
  776. # true: 观察期,不带 Idempotency-Key 仍放行(但会记录)
  777. # false: 强制期,不带 Idempotency-Key 直接拒绝(仅对接入幂等保护的接口生效)
  778. observe_only: true
  779. # 关键写接口幂等记录 TTL(秒)
  780. default_ttl_seconds: 86400
  781. # 系统操作接口(update/rollback/restart)幂等记录 TTL(秒)
  782. system_operation_ttl_seconds: 3600
  783. # processing 锁超时(秒)
  784. processing_timeout_seconds: 30
  785. # 可重试失败退避窗口(秒)
  786. failed_retry_backoff_seconds: 5
  787. # 持久化响应体最大长度(字节)
  788. max_stored_response_len: 65536
  789. # 过期幂等记录清理周期(秒)
  790. cleanup_interval_seconds: 60
  791. # 每轮清理最大删除条数
  792. cleanup_batch_size: 500
  793. # =============================================================================
  794. # Concurrency Wait Configuration
  795. # 并发等待配置
  796. # =============================================================================
  797. concurrency:
  798. # SSE ping interval during concurrency wait (seconds)
  799. # 并发等待期间的 SSE ping 间隔(秒)
  800. ping_interval: 10
  801. # =============================================================================
  802. # Database Configuration (PostgreSQL)
  803. # 数据库配置 (PostgreSQL)
  804. # =============================================================================
  805. database:
  806. # Database host address
  807. # 数据库主机地址
  808. host: "localhost"
  809. # Database port
  810. # 数据库端口
  811. port: 5432
  812. # Database username
  813. # 数据库用户名
  814. user: "postgres"
  815. # Database password
  816. # 数据库密码
  817. password: "your_secure_password_here"
  818. # Database name
  819. # 数据库名称
  820. dbname: "sub2api"
  821. # SSL mode: disable, prefer, require, verify-ca, verify-full
  822. # SSL 模式:disable(禁用), prefer(优先加密,默认), require(要求), verify-ca(验证CA), verify-full(完全验证)
  823. # 默认值为 "prefer",数据库支持 SSL 时自动使用加密连接,不支持时回退明文
  824. sslmode: "prefer"
  825. # Max open connections (高并发场景建议 256+,需配合 PostgreSQL max_connections 调整)
  826. # 最大打开连接数
  827. max_open_conns: 256
  828. # Max idle connections (建议为 max_open_conns 的 50%,减少频繁建连开销)
  829. # 最大空闲连接数
  830. max_idle_conns: 128
  831. # Connection max lifetime (minutes)
  832. # 连接最大存活时间(分钟)
  833. conn_max_lifetime_minutes: 30
  834. # Connection max idle time (minutes)
  835. # 空闲连接最大存活时间(分钟)
  836. conn_max_idle_time_minutes: 5
  837. # =============================================================================
  838. # Redis Configuration
  839. # Redis 配置
  840. # =============================================================================
  841. redis:
  842. # Redis host address
  843. # Redis 主机地址
  844. host: "localhost"
  845. # Redis port
  846. # Redis 端口
  847. port: 6379
  848. # Redis ACL username (leave empty for default user)
  849. # Redis ACL 用户名(使用默认用户时留空)
  850. username: ""
  851. # Redis password (leave empty if no password is set)
  852. # Redis 密码(如果未设置密码则留空)
  853. password: ""
  854. # Database number (0-15)
  855. # 数据库编号(0-15)
  856. db: 0
  857. # Connection pool size (max concurrent connections)
  858. # 连接池大小(最大并发连接数)
  859. pool_size: 1024
  860. # Minimum number of idle connections (高并发场景建议 128+,保持足够热连接)
  861. # 最小空闲连接数
  862. min_idle_conns: 128
  863. # Enable TLS/SSL connection
  864. # 是否启用 TLS/SSL 连接
  865. enable_tls: false
  866. # =============================================================================
  867. # Ops Monitoring (Optional)
  868. # 运维监控 (可选)
  869. # =============================================================================
  870. ops:
  871. # Enable ops monitoring features (background jobs and APIs)
  872. # 是否启用运维监控功能(后台任务和接口)
  873. # Set to false to hide ops menu in sidebar and disable all ops features
  874. # 设置为 false 可在左侧栏隐藏运维监控菜单并禁用所有运维监控功能
  875. # Other detailed settings (cleanup, aggregation, etc.) are configured in ops settings dialog
  876. # 其他详细设置(数据清理、预聚合等)在运维监控设置对话框中配置
  877. enabled: true
  878. # =============================================================================
  879. # JWT Configuration
  880. # JWT 配置
  881. # =============================================================================
  882. jwt:
  883. # IMPORTANT: Change this to a random string in production!
  884. # 重要:生产环境中请更改为随机字符串!
  885. # Generate with / 生成命令: openssl rand -hex 32
  886. secret: "change-this-to-a-secure-random-string"
  887. # Token expiration time in hours (max 168)
  888. # 令牌过期时间(小时,最大 168)
  889. expire_hour: 24
  890. # Access Token 过期时间(分钟)
  891. # 优先级说明:
  892. # - >0: 按分钟生效(优先于 expire_hour)
  893. # - =0: 回退使用 expire_hour
  894. access_token_expire_minutes: 0
  895. # =============================================================================
  896. # TOTP (2FA) Configuration
  897. # TOTP 双因素认证配置
  898. # =============================================================================
  899. totp:
  900. # IMPORTANT: Set a fixed encryption key for TOTP secrets.
  901. # 重要:设置固定的 TOTP 加密密钥。
  902. # If left empty, a random key will be generated on each startup, causing all
  903. # existing TOTP configurations to become invalid (users won't be able to
  904. # login with 2FA).
  905. # 如果留空,每次启动将生成随机密钥,导致现有的 TOTP 配置失效(用户无法使用
  906. # 双因素认证登录)。
  907. # Generate with / 生成命令: openssl rand -hex 32
  908. encryption_key: ""
  909. # =============================================================================
  910. # LinuxDo Connect OAuth Login (SSO)
  911. # LinuxDo Connect OAuth 登录(用于 Sub2API 用户登录)
  912. # =============================================================================
  913. linuxdo_connect:
  914. enabled: false
  915. client_id: ""
  916. client_secret: ""
  917. authorize_url: "https://connect.linux.do/oauth2/authorize"
  918. token_url: "https://connect.linux.do/oauth2/token"
  919. userinfo_url: "https://connect.linux.do/api/user"
  920. scopes: "user"
  921. # 示例: "https://your-domain.com/api/v1/auth/oauth/linuxdo/callback"
  922. redirect_url: ""
  923. # 安全提示:
  924. # - 建议使用同源相对路径(以 / 开头),避免把 token 重定向到意外的第三方域名
  925. # - 该地址不应包含 #fragment(本实现使用 URL fragment 传递 access_token)
  926. frontend_redirect_url: "/auth/linuxdo/callback"
  927. token_auth_method: "client_secret_post" # client_secret_post | client_secret_basic | none
  928. # 注意:当 token_auth_method=none(public client)时,必须启用 PKCE
  929. use_pkce: true
  930. userinfo_email_path: ""
  931. userinfo_id_path: ""
  932. userinfo_username_path: ""
  933. # =============================================================================
  934. # Generic OIDC OAuth Login (SSO)
  935. # 通用 OIDC OAuth 登录(用于 Sub2API 用户登录)
  936. # =============================================================================
  937. oidc_connect:
  938. enabled: false
  939. provider_name: "OIDC"
  940. client_id: ""
  941. client_secret: ""
  942. # 例如: "https://keycloak.example.com/realms/myrealm"
  943. issuer_url: ""
  944. # 可选: OIDC Discovery URL。为空时可手动填写 authorize/token/userinfo/jwks
  945. discovery_url: ""
  946. authorize_url: ""
  947. token_url: ""
  948. # 可选(仅补充 email/username,不用于 sub 可信绑定)
  949. userinfo_url: ""
  950. # validate_id_token=true 时必填
  951. jwks_url: ""
  952. scopes: "openid email profile"
  953. # 示例: "https://your-domain.com/api/v1/auth/oauth/oidc/callback"
  954. redirect_url: ""
  955. # 安全提示:
  956. # - 建议使用同源相对路径(以 / 开头),避免把 token 重定向到意外的第三方域名
  957. # - 该地址不应包含 #fragment(本实现使用 URL fragment 传递 access_token)
  958. frontend_redirect_url: "/auth/oidc/callback"
  959. token_auth_method: "client_secret_post" # client_secret_post | client_secret_basic | none
  960. # 注意:当 token_auth_method=none(public client)时,必须启用 PKCE
  961. use_pkce: false
  962. # 开启后强制校验 id_token 的签名和 claims(推荐)
  963. validate_id_token: true
  964. allowed_signing_algs: "RS256,ES256,PS256"
  965. # 允许的时钟偏移(秒)
  966. clock_skew_seconds: 120
  967. # 若 Provider 返回 email_verified=false,是否拒绝登录
  968. require_email_verified: false
  969. userinfo_email_path: ""
  970. userinfo_id_path: ""
  971. userinfo_username_path: ""
  972. # =============================================================================
  973. # Default Settings
  974. # 默认设置
  975. # =============================================================================
  976. default:
  977. # Initial admin account (created on first run)
  978. # 初始管理员账户(首次运行时创建)
  979. admin_email: "admin@example.com"
  980. admin_password: "admin123"
  981. # Default settings for new users
  982. # 新用户默认设置
  983. # Max concurrent requests per user
  984. # 每用户最大并发请求数
  985. user_concurrency: 5
  986. # Initial balance for new users
  987. # 新用户初始余额
  988. user_balance: 0
  989. # API key settings
  990. # API 密钥设置
  991. # Prefix for generated API keys
  992. # 生成的 API 密钥前缀
  993. api_key_prefix: "sk-"
  994. # Rate multiplier (affects billing calculation)
  995. # 费率倍数(影响计费计算)
  996. rate_multiplier: 1.0
  997. # =============================================================================
  998. # Rate Limiting
  999. # 速率限制
  1000. # =============================================================================
  1001. rate_limit:
  1002. # Cooldown time (in minutes) when upstream returns 529 (overloaded)
  1003. # 上游返回 529(过载)时的冷却时间(分钟)
  1004. overload_cooldown_minutes: 10
  1005. # =============================================================================
  1006. # Local OAuth Transport Plugins (Optional)
  1007. # 本地 OAuth 出站传输插件(可选)
  1008. # =============================================================================
  1009. plugins:
  1010. # Empty means {{DATA_DIR}}/plugins, or ./data/plugins when DATA_DIR is unset.
  1011. # 留空时使用 {{DATA_DIR}}/plugins;未设置 DATA_DIR 时使用 ./data/plugins。
  1012. data_dir: ""
  1013. # Keep false in production. Enable only for local development packages you built yourself.
  1014. # 生产环境应保持 false;仅调试自己构建的本地插件时临时开启。
  1015. allow_unsigned: false
  1016. # Additional Ed25519 public keys indexed by signature.json key_id.
  1017. # OpenAI Transport's public key is built in; this map only adds third-party publishers.
  1018. # 以 signature.json 中 key_id 为索引的额外 Ed25519 公钥。
  1019. # OpenAI Transport 公钥已内置,此处只需添加第三方发布者。
  1020. trusted_publishers: {}
  1021. max_upload_bytes: 134217728
  1022. max_uncompressed_bytes: 268435456
  1023. start_timeout_seconds: 15
  1024. # =============================================================================
  1025. # Pricing Data Source (Optional)
  1026. # 定价数据源(可选)
  1027. # =============================================================================
  1028. pricing:
  1029. # URL to fetch model pricing data (default: model-price-repo main branch)
  1030. # 获取模型定价数据的 URL(默认:model-price-repo main 分支)
  1031. remote_url: "https://raw.githubusercontent.com/Wei-Shaw/model-price-repo/refs/heads/main//model_prices_and_context_window.json"
  1032. # Hash verification URL (optional)
  1033. # 哈希校验 URL(可选)
  1034. hash_url: "https://raw.githubusercontent.com/Wei-Shaw/model-price-repo/refs/heads/main//model_prices_and_context_window.sha256"
  1035. # Local data directory for caching
  1036. # 本地数据缓存目录
  1037. data_dir: "./data"
  1038. # Fallback pricing file: fills in models missing from the catalog. Edits are
  1039. # detected by content hash at the next hash check and reloaded without restart.
  1040. # 备用定价文件:只补目录缺失的模型。修改后在下一次哈希检查时按内容哈希自动重载,无需重启。
  1041. fallback_file: "./resources/model-pricing/model_prices_and_context_window.json"
  1042. # Override patch file (optional, highest priority): entries are shallow-merged
  1043. # field-by-field over catalog/fallback data; a null field value removes that field.
  1044. # Model names must match catalog keys exactly. Edits are detected by content hash
  1045. # at the next hash check and reloaded without restart.
  1046. # 覆盖补丁文件(可选,优先级最高):条目按字段浅合并覆盖目录/回退数据,
  1047. # 字段值为 null 表示删除该字段。模型名须与目录键完全一致。
  1048. # 修改后在下一次哈希检查时按内容哈希自动重载,无需重启。
  1049. # override_file: "./data/model_pricing_overrides.json"
  1050. # Update interval in hours
  1051. # 更新间隔(小时)
  1052. update_interval_hours: 24
  1053. # Hash check interval in minutes. Each check compares the remote catalog hash and
  1054. # the local fallback/override file contents. Deleting a local file drops its
  1055. # entries at the next check; a present but non-JSON file keeps the previous data
  1056. # and is retried next check.
  1057. # 哈希检查间隔(分钟)。每次检查同时比对远程目录哈希与本地 fallback/override 文件内容;
  1058. # 删除本地文件会在下次检查时移除其条目,文件存在但不是 JSON 时保留旧数据、下次检查再试。
  1059. hash_check_interval_minutes: 10
  1060. # =============================================================================
  1061. # Billing Configuration
  1062. # 计费配置
  1063. # =============================================================================
  1064. billing:
  1065. circuit_breaker:
  1066. # Enable circuit breaker for billing service
  1067. # 启用计费服务熔断器
  1068. enabled: true
  1069. # Number of failures before opening circuit
  1070. # 触发熔断的失败次数阈值
  1071. failure_threshold: 5
  1072. # Time to wait before attempting reset (seconds)
  1073. # 熔断后重试等待时间(秒)
  1074. reset_timeout_seconds: 30
  1075. # Number of requests to allow in half-open state
  1076. # 半开状态允许通过的请求数
  1077. half_open_requests: 3
  1078. # Conservative minimum balance required before forwarding balance-billed requests.
  1079. # Set to 0 to only require balance > 0.
  1080. # 余额计费请求转发前要求的保守最小余额;设为 0 则仅要求余额 > 0。
  1081. minimum_balance_reserve: 0.000001
  1082. # Cache TTL (seconds) for per-user × per-platform quota records
  1083. # 用户 × 平台 quota 缓存 TTL(秒),默认 86400=1天,覆盖典型 daily 窗口
  1084. user_platform_quota_cache_ttl_seconds: 86400
  1085. # =============================================================================
  1086. # Turnstile Configuration
  1087. # Turnstile 人机验证配置
  1088. # =============================================================================
  1089. turnstile:
  1090. # Require Turnstile in release mode (when enabled, login/register will fail if not configured)
  1091. # 在 release 模式下要求 Turnstile 验证(启用后,若未配置则登录/注册会失败)
  1092. required: false
  1093. # =============================================================================
  1094. # Gemini OAuth (Required for Gemini accounts)
  1095. # Gemini OAuth 配置(Gemini 账户必需)
  1096. # =============================================================================
  1097. # Sub2API supports TWO Gemini OAuth modes:
  1098. # Sub2API 支持两种 Gemini OAuth 模式:
  1099. #
  1100. # 1. Code Assist OAuth (requires GCP project_id)
  1101. # 1. Code Assist OAuth(需要 GCP project_id)
  1102. # - Uses: cloudcode-pa.googleapis.com (Code Assist API)
  1103. # - 使用:cloudcode-pa.googleapis.com(Code Assist API)
  1104. #
  1105. # 2. AI Studio OAuth (no project_id needed)
  1106. # 2. AI Studio OAuth(不需要 project_id)
  1107. # - Uses: generativelanguage.googleapis.com (AI Studio API)
  1108. # - 使用:generativelanguage.googleapis.com(AI Studio API)
  1109. #
  1110. # Default: Uses Gemini CLI's public OAuth credentials (same as Google's official CLI tool)
  1111. # 默认:使用 Gemini CLI 的公开 OAuth 凭证(与 Google 官方 CLI 工具相同)
  1112. gemini:
  1113. oauth:
  1114. # OAuth 客户端配置说明:
  1115. # 1) 留空 client_id/client_secret:使用 Gemini CLI 内置 OAuth Client(其 client_secret 需通过环境变量注入)
  1116. # - GEMINI_CLI_OAUTH_CLIENT_SECRET
  1117. # 2) 同时设置 client_id/client_secret:使用你自建的 OAuth Client(推荐,权限更完整)
  1118. #
  1119. # 注意:client_id 与 client_secret 必须同时为空或同时非空。
  1120. client_id: ""
  1121. client_secret: ""
  1122. # Optional scopes (space-separated). Leave empty to auto-select based on oauth_type.
  1123. # 可选的权限范围(空格分隔)。留空则根据 oauth_type 自动选择。
  1124. scopes: ""
  1125. quota:
  1126. # Optional: local quota simulation for Gemini Code Assist (local billing).
  1127. # 可选:Gemini Code Assist 本地配额模拟(本地计费)。
  1128. # These values are used for UI progress + precheck scheduling, not official Google quotas.
  1129. # 这些值用于 UI 进度显示和预检调度,并非 Google 官方配额。
  1130. tiers:
  1131. LEGACY:
  1132. # Pro model requests per day
  1133. # Pro 模型每日请求数
  1134. pro_rpd: 50
  1135. # Flash model requests per day
  1136. # Flash 模型每日请求数
  1137. flash_rpd: 1500
  1138. # Cooldown time (minutes) after hitting quota
  1139. # 达到配额后的冷却时间(分钟)
  1140. cooldown_minutes: 30
  1141. PRO:
  1142. # Pro model requests per day
  1143. # Pro 模型每日请求数
  1144. pro_rpd: 1500
  1145. # Flash model requests per day
  1146. # Flash 模型每日请求数
  1147. flash_rpd: 4000
  1148. # Cooldown time (minutes) after hitting quota
  1149. # 达到配额后的冷却时间(分钟)
  1150. cooldown_minutes: 5
  1151. ULTRA:
  1152. # Pro model requests per day
  1153. # Pro 模型每日请求数
  1154. pro_rpd: 2000
  1155. # Flash model requests per day (0 = unlimited)
  1156. # Flash 模型每日请求数(0 = 无限制)
  1157. flash_rpd: 0
  1158. # Cooldown time (minutes) after hitting quota
  1159. # 达到配额后的冷却时间(分钟)
  1160. cooldown_minutes: 5
  1161. # =============================================================================
  1162. # Update Configuration (在线更新配置)
  1163. # =============================================================================
  1164. update:
  1165. # Proxy URL for accessing GitHub (used for online updates and pricing data)
  1166. # 用于访问 GitHub 的代理地址(用于在线更新和定价数据获取)
  1167. # Supports: http, https, socks5, socks5h
  1168. # Examples:
  1169. # - HTTP proxy: "http://127.0.0.1:7890"
  1170. # - SOCKS5 proxy: "socks5://127.0.0.1:1080"
  1171. # - With authentication: "http://user:pass@proxy.example.com:8080"
  1172. # Leave empty for direct connection (recommended for overseas servers)
  1173. # 留空表示直连(适用于海外服务器)
  1174. proxy_url: ""
  1175. # =============================================================================
  1176. # Image Storage (异步图片任务结果对象存储)
  1177. # =============================================================================
  1178. # 长耗时生图套 Cloudflare 会 524 超时,异步图片任务接口(/v1/images/generations/async
  1179. # 等)先返回 task_id,再由客户端轮询 /v1/images/tasks/{task_id} 获取结果。
  1180. #
  1181. # 这里配置一个 S3 兼容对象存储(AWS S3 / Cloudflare R2 / 阿里云 OSS / MinIO 等),
  1182. # 任务完成后把生成的图片上传到对象存储,只在 Redis 存一个短链接,避免 gpt-image-1 等
  1183. # 返回的大 base64 结果把 Redis 撑爆。
  1184. #
  1185. # enabled 同时是异步图片任务功能的总开关:为 false 或凭证未配全时,异步生图接口
  1186. # 整体返回 404、不创建任务、不写 Redis。
  1187. #
  1188. # 换其它厂商对象存储:只要它兼容 S3 API 即可直接用;如需完全自定义,实现
  1189. # service.ImageStorage 接口(Save(ctx, key, contentType, data) -> url)即可。
  1190. image_storage:
  1191. enabled: false
  1192. # S3 兼容端点。AWS 官方可留空;R2 形如 https://<account_id>.r2.cloudflarestorage.com
  1193. endpoint: ""
  1194. # 区域。Cloudflare R2 用 "auto"
  1195. region: "auto"
  1196. bucket: ""
  1197. access_key_id: ""
  1198. secret_access_key: ""
  1199. # 对象 key 前缀
  1200. prefix: "images/"
  1201. # MinIO / 需要路径风格(path-style)访问的桶设为 true
  1202. force_path_style: false
  1203. # 若填写公开桶 / CDN 域名,则返回 public_base_url/key 永久直链;
  1204. # 留空则返回带过期时间的 presigned 临时链接
  1205. public_base_url: ""
  1206. # public_base_url 为空时,presigned 链接的有效时长(小时)
  1207. presign_expiry_hours: 24
  1208. # 当上游返回的是图片 url 时,下载该图片再转存的字节上限(默认 32MB)
  1209. max_download_bytes: 33554432