feat: sync deployed v1.0.0-rc.38-custom.42

Sync production source including routing, billing, Astra detection and public uptime. Update custom build instructions and license packaging.
This commit is contained in:
cneicy committed 2026-09-26 04:49:11 +08:00
1 parent aa6c3f50f4
commit ceddfd3d6b
828 files changed
+122253 -13702

No files matched your search

@@ -3,6 +3,11 @@ package billing_setting
// Built-in token prices use actual USD per million tokens. Keep new model
// defaults here instead of splitting them across the legacy ratio tables.
var builtinBillingExpr = map[string]string{
// https://developers.openai.com/api/docs/pricing (Standard, 2026-09-09).
// The Images API reports image output in output_tokens, normalized to c.
"gpt-image-2": `tier("standard", p * 5 + cr * 1.25 + img * 8 + img_cr * 2 + c * 30)`,
"gpt-image-2.5-sunburst": `tier("standard", p * 5 + cr * 1.25 + img * 8 + img_cr * 2 + c * 30)`,
"gpt-image-2.5-flare": `tier("standard", p * 5 + cr * 1.25 + img * 8 + img_cr * 2 + c * 30)`,
// https://developers.openai.com/api/docs/models/gpt-6-astra
// Standard pricing; the long-context rates apply to the whole request.
// Do not infer service-tier discounts from incoming request parameters:
@@ -109,3 +109,42 @@ func TestGPT6AstraBuiltinBilling(t *testing.T) {
})
}
}
func TestImageModelBuiltinPricesAndOverrides(t *testing.T) {
settings := config.GlobalConfig.Get("billing_setting").(*billing_setting.BillingSetting)
saved := *settings
savedRatios, savedPrices := ratio_setting.ModelRatio2JSONString(), ratio_setting.ModelPrice2JSONString()
t.Cleanup(func() {
*settings = saved
require.NoError(t, ratio_setting.UpdateModelRatioByJSONString(savedRatios))
require.NoError(t, ratio_setting.UpdateModelPriceByJSONString(savedPrices))
})
for _, name := range []string{"gpt-image-2", "gpt-image-2.5-sunburst", "gpt-image-2.5-flare"} {
t.Run(name, func(t *testing.T) {
*settings = billing_setting.BillingSetting{BillingMode: map[string]string{}, BillingExpr: map[string]string{}}
require.NoError(t, ratio_setting.UpdateModelRatioByJSONString(`{}`))
require.NoError(t, ratio_setting.UpdateModelPriceByJSONString(`{}`))
expression, ok := billing_setting.GetBillingExpr(name)
require.True(t, ok)
usage := &dto.Usage{PromptTokens: 1000, CompletionTokens: 100, PromptTokensDetails: dto.InputTokenDetails{
CachedTokens: 300, ImageTokens: 600, CachedTokensDetails: &dto.CachedTokenDetails{ImageTokens: common.GetPointer(200)},
}}
result, err := billingexpr.ComputeTieredQuota(&billingexpr.BillingSnapshot{ExprString: expression, ExprHash: billingexpr.ExprHashString(expression), GroupRatio: 1, QuotaPerUnit: 500000},
service.BuildTieredTokenParams(usage, false, billingexpr.UsedVars(expression)))
require.NoError(t, err)
assert.Equal(t, 4113, result.ActualQuotaAfterGroup)
encoded, err := common.Marshal(map[string]float64{name: 0})
require.NoError(t, err)
require.NoError(t, ratio_setting.UpdateModelRatioByJSONString(string(encoded)))
assert.Equal(t, "ratio", billing_setting.GetBillingMode(name))
require.NoError(t, ratio_setting.UpdateModelRatioByJSONString(`{}`))
require.NoError(t, ratio_setting.UpdateModelPriceByJSONString(string(encoded)))
assert.Equal(t, "ratio", billing_setting.GetBillingMode(name))
settings.BillingMode[name] = "tiered_expr"
settings.BillingExpr[name] = `tier("custom", p * 7)`
actual, ok := billing_setting.GetBillingExpr(name)
require.True(t, ok)
assert.Equal(t, settings.BillingExpr[name], actual)
})
}
}
+82 -10
View File
@@ -5,6 +5,7 @@ import (
"maps"
"math"
"sort"
"strings"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/pkg/billingexpr"
@@ -17,25 +18,29 @@ import (
)
const (
BillingModeRatio = "ratio"
BillingModeTieredExpr = "tiered_expr"
BillingModeField = "billing_mode"
BillingExprField = "billing_expr"
maxTaskExprSmokeTests = 64
BillingModeRatio = "ratio"
BillingModeTieredExpr = "tiered_expr"
BillingModeField = "billing_mode"
BillingExprField = "billing_expr"
PluginBillingExprOption = "billing_setting.plugin_billing_expr"
maxTaskExprSmokeTests = 64
)
// BillingSetting is managed by config.GlobalConfig.Register.
// DB keys: billing_setting.billing_mode, billing_setting.billing_expr
// DB keys: billing_setting.billing_mode, billing_setting.billing_expr,
// billing_setting.plugin_billing_expr
type BillingSetting struct {
BillingMode map[string]string `json:"billing_mode"`
BillingExpr map[string]string `json:"billing_expr"`
GroupBillingExpr map[string]map[string]string `json:"group_billing_expr"`
BillingMode map[string]string `json:"billing_mode"`
BillingExpr map[string]string `json:"billing_expr"`
PluginBillingExpr map[string]string `json:"plugin_billing_expr"`
}
var billingSetting = BillingSetting{
BillingMode: make(map[string]string),
BillingExpr: make(map[string]string),
GroupBillingExpr: make(map[string]map[string]string),
BillingMode: make(map[string]string),
BillingExpr: make(map[string]string),
PluginBillingExpr: make(map[string]string),
}
func init() {
@@ -80,6 +85,67 @@ func GetBuiltinBillingExpr(model string) (string, bool) {
return expression, ok
}
func PluginBillingExprKey(pluginKey, model string) string {
return pluginKey + "::" + model
}
func SplitPluginBillingExprKey(key string) (plugin, model string, ok bool) {
plugin, model, ok = strings.Cut(key, "::")
if !ok || !jsplugin.ValidPluginKey(plugin) || strings.TrimSpace(model) == "" {
return "", "", false
}
return plugin, model, true
}
func GetPluginBillingExprCopy() map[string]string {
return maps.Clone(billingSetting.PluginBillingExpr)
}
func GetPluginBillingExpr(pluginKey, model string) (string, bool) {
expression, ok := billingSetting.PluginBillingExpr[PluginBillingExprKey(pluginKey, model)]
return expression, ok
}
// ResolveTaskBillingExpr selects the executing plugin's override before the
// model expression, retaining the model alias fallback and explicit modes.
func ResolveTaskBillingExpr(pluginKey, model, mappedModel string) (string, bool) {
if pluginKey != "" {
if expr, ok := GetPluginBillingExpr(pluginKey, model); ok {
return expr, true
}
if mappedModel != "" && mappedModel != model {
if expr, ok := GetPluginBillingExpr(pluginKey, mappedModel); ok {
return expr, true
}
}
}
if GetBillingMode(model) == BillingModeTieredExpr {
return GetBillingExpr(model)
}
if mappedModel != "" && mappedModel != model && GetBillingMode(mappedModel) == BillingModeTieredExpr {
expression, ok := GetBillingExpr(mappedModel)
return expression, ok && strings.TrimSpace(expression) != ""
}
return "", false
}
// TaskExprCompatible checks the schema contract even for usage references in
// branches that the current request would not evaluate.
func TaskExprCompatible(expression string, schema map[string]jsplugin.UsageFieldSchema) bool {
if strings.TrimSpace(expression) == "" {
return false
}
if _, err := billingexpr.CompileFromCache(expression); err != nil {
return false
}
for key := range billingexpr.UsedUsageKeys(expression) {
if _, exists := schema[key]; !exists {
return false
}
}
return !billingexpr.UsesFixedPricing(expression)
}
func GetBuiltinBillingExprCopy() map[string]string {
return lo.Assign(builtinBillingExpr)
}
@@ -157,6 +223,9 @@ func smokeTestExpr(exprStr string) error {
{P: 1000, C: 1000, Len: 1000},
{P: 100000, C: 100000, Len: 100000},
{P: 1000000, C: 1000000, Len: 1000000},
{P: 300, C: 100, Len: 1000, CR: 100, Img: 400, ImgCR: 200},
{P: 800, C: 50, Len: 1000, AI: 200, AO: 50},
{Len: math.MaxInt32, ImgCR: math.MaxInt32},
}
for _, v := range vectors {
@@ -180,6 +249,9 @@ func SmokeTestTaskExpr(exprStr string, schema map[string]jsplugin.UsageFieldSche
if _, err := billingexpr.CompileFromCache(exprStr); err != nil {
return err
}
if billingexpr.UsesFixedPricing(exprStr) {
return fmt.Errorf("fixed pricing is not supported for task usage expressions")
}
for key := range billingexpr.UsedUsageKeys(exprStr) {
if _, declared := schema[key]; !declared {
return fmt.Errorf("usage key %q is not declared by the task plugin", key)
@@ -25,6 +25,12 @@ func TestSmokeTestTaskExprValidatesDeclaredUsageVectors(t *testing.T) {
expression string
expectedError string
}{
{
name: "fixed prices are not task usage prices",
schema: videoSchema,
expression: `true ? tier("normal", u("seconds") * 0.4) : tier("fixed", fixed(0.01))`,
expectedError: "fixed pricing is not supported for task usage expressions",
},
{
name: "declared numeric and enum facts",
schema: videoSchema,
@@ -21,6 +21,9 @@ type ChannelAffinityRule struct {
ParamOverrideTemplate map[string]any `json:"param_override_template,omitempty"`
SkipRetryOnFailure bool `json:"skip_retry_on_failure"`
// "inherit" uses the global default; off/prefer/strict override it.
// Empty preserves the legacy SkipRetryOnFailure behavior.
SessionMode string `json:"session_mode,omitempty"`
IncludeUsingGroup bool `json:"include_using_group"`
IncludeModelName bool `json:"include_model_name"`
@@ -28,7 +31,9 @@ type ChannelAffinityRule struct {
}
type ChannelAffinitySetting struct {
Enabled bool `json:"enabled"`
Enabled bool `json:"enabled"`
// Default for rules with SessionMode "inherit". Empty defaults to "prefer".
SessionMode string `json:"session_mode"`
SwitchOnSuccess bool `json:"switch_on_success"`
KeepOnChannelDisabled bool `json:"keep_on_channel_disabled"`
MaxEntries int `json:"max_entries"`
+7 -2
View File
@@ -4,6 +4,11 @@ import (
"github.com/QuantumNous/new-api/types"
)
const (
DefaultCacheRatio = 1.0
DefaultCreateCacheRatio = 1.25
)
var defaultCacheRatio = map[string]float64{
"gemini-3-flash-preview": 0.1,
"gemini-3-pro-preview": 0.1,
@@ -159,7 +164,7 @@ func UpdateCreateCacheRatioByJSONString(jsonStr string) error {
func GetCacheRatio(name string) (float64, bool) {
ratio, ok := cacheRatioMap.Get(name)
if !ok {
return 1, false // Default to 1 if not found
return DefaultCacheRatio, false
}
return ratio, true
}
@@ -167,7 +172,7 @@ func GetCacheRatio(name string) (float64, bool) {
func GetCreateCacheRatio(name string) (float64, bool) {
ratio, ok := createCacheRatioMap.Get(name)
if !ok {
return 1.25, false // Default to 1.25 if not found
return DefaultCreateCacheRatio, false
}
return ratio, true
}
+18 -25
View File
@@ -434,21 +434,7 @@ func UpdateCompletionRatioByJSONString(jsonStr string) error {
}
func GetCompletionRatio(name string) float64 {
name = FormatMatchingModelName(name)
if strings.Contains(name, "/") {
if ratio, ok := completionRatioMap.Get(name); ok {
return ratio
}
}
hardCodedRatio, contain := getHardcodedCompletionModelRatio(name)
if contain {
return hardCodedRatio
}
if ratio, ok := completionRatioMap.Get(name); ok {
return ratio
}
return hardCodedRatio
return GetCompletionRatioInfo(name).Ratio
}
type CompletionRatioInfo struct {
@@ -458,14 +444,19 @@ type CompletionRatioInfo struct {
func GetCompletionRatioInfo(name string) CompletionRatioInfo {
name = FormatMatchingModelName(name)
var configured *float64
if ratio, ok := completionRatioMap.Get(name); ok {
configured = &ratio
}
return ResolveCompletionRatio(name, configured)
}
if strings.Contains(name, "/") {
if ratio, ok := completionRatioMap.Get(name); ok {
return CompletionRatioInfo{
Ratio: ratio,
Locked: false,
}
}
// ResolveCompletionRatio applies relay's enforced and fallback ratios to a
// configuration snapshot or draft without consulting mutable saved settings.
func ResolveCompletionRatio(name string, configured *float64) CompletionRatioInfo {
name = FormatMatchingModelName(name)
if strings.Contains(name, "/") && configured != nil {
return CompletionRatioInfo{Ratio: *configured}
}
hardCodedRatio, locked := getHardcodedCompletionModelRatio(name)
@@ -476,9 +467,9 @@ func GetCompletionRatioInfo(name string) CompletionRatioInfo {
}
}
if ratio, ok := completionRatioMap.Get(name); ok {
if configured != nil {
return CompletionRatioInfo{
Ratio: ratio,
Ratio: *configured,
Locked: false,
}
}
@@ -664,10 +655,12 @@ func UpdateImageRatioByJSONString(jsonStr string) error {
return types.LoadFromJsonString(imageRatioMap, jsonStr)
}
const DefaultImageRatio = 1.0
func GetImageRatio(name string) (float64, bool) {
ratio, ok := imageRatioMap.Get(name)
if !ok {
return 1, false // Default to 1 if not found
return DefaultImageRatio, false
}
return ratio, true
}
+132 -13
View File
@@ -1,23 +1,138 @@
package system_setting
import (
"errors"
"net"
"net/url"
"slices"
"strings"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/setting/config"
"golang.org/x/net/idna"
"golang.org/x/net/publicsuffix"
)
type PasskeySettings struct {
Enabled bool `json:"enabled"`
RPDisplayName string `json:"rp_display_name"`
RPID string `json:"rp_id"`
LegacyRPIDs string `json:"legacy_rp_ids"`
Origins string `json:"origins"`
AllowInsecureOrigin bool `json:"allow_insecure_origin"`
UserVerification string `json:"user_verification"`
AttachmentPreference string `json:"attachment_preference"`
}
var ErrPasskeyRPIDInvalid = errors.New("Invalid Passkey domain. Enter a domain without a scheme, port, path or wildcard.")
var ErrPasskeyRPIDUnavailable = errors.New("This Passkey domain is not available on this website. Use its original website or another verification method.")
// PasskeySettingsSnapshot includes the effective defaults without sharing a
// mutable settings pointer with a WebAuthn ceremony.
func PasskeySettingsSnapshot() PasskeySettings {
common.OptionMapRWMutex.RLock()
settings, serverAddress := defaultPasskeySettings, ServerAddress
common.OptionMapRWMutex.RUnlock()
return settings.WithDefaults(serverAddress)
}
// EffectiveRPID preserves the existing default and port handling for settings
// created before explicit Passkey domains were introduced.
func (s PasskeySettings) EffectiveRPID() string {
rpID := strings.TrimSpace(s.RPID)
if rpID == "" {
for origin := range strings.SplitSeq(s.Origins, ",") {
if parsed, err := url.Parse(strings.TrimSpace(origin)); err == nil && parsed.Host != "" {
rpID = parsed.Host
break
}
}
}
if host, _, err := net.SplitHostPort(rpID); err == nil {
return host
}
return rpID
}
func NormalizePasskeyRPID(value string, configuredOrigins ...string) (string, error) {
rpID, err := idna.Lookup.ToASCII(strings.TrimSpace(value))
rpID = strings.ToLower(rpID)
if err != nil || rpID == "" || len(rpID) > 253 || strings.ContainsAny(rpID, ":/*@?#\\") || net.ParseIP(rpID) != nil {
return "", ErrPasskeyRPIDInvalid
}
for label := range strings.SplitSeq(rpID, ".") {
if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
return "", ErrPasskeyRPIDInvalid
}
for _, c := range label {
if c != '-' && (c < 'a' || c > 'z') && (c < '0' || c > '9') {
return "", ErrPasskeyRPIDInvalid
}
}
}
if rpID == "localhost" {
return rpID, nil
}
if _, err := publicsuffix.EffectiveTLDPlusOne(rpID); err == nil {
return rpID, nil
}
// An unknown single-label hostname is usable only at its exact, explicitly
// trusted HTTPS origin, never as a suffix of other hosts.
_, icann := publicsuffix.PublicSuffix(rpID)
if icann || strings.Contains(rpID, ".") {
return "", ErrPasskeyRPIDInvalid
}
for _, origins := range configuredOrigins {
for origin := range strings.SplitSeq(origins, ",") {
parsed, err := url.Parse(strings.TrimSpace(origin))
if err != nil || parsed.Scheme != "https" || parsed.User != nil || (parsed.Path != "" && parsed.Path != "/") || parsed.RawQuery != "" || parsed.Fragment != "" {
continue
}
if strings.EqualFold(parsed.Hostname(), rpID) {
return rpID, nil
}
}
}
return "", ErrPasskeyRPIDInvalid
}
func ParsePasskeyRPIDs(value string, configuredOrigins ...string) ([]string, error) {
ids := []string{}
for _, value := range strings.FieldsFunc(value, func(c rune) bool { return c == ',' || c == '\n' || c == '\r' }) {
if strings.TrimSpace(value) == "" {
continue
}
_, err := NormalizePasskeyRPID(value, configuredOrigins...)
if err != nil {
return nil, err
}
// Legacy credentials hash the exact RP ID supplied at registration.
// Validate the domain without changing that historical value.
id := strings.TrimSpace(value)
if !slices.Contains(ids, id) {
ids = append(ids, id)
}
}
return ids, nil
}
func (s PasskeySettings) RelyingPartyIDs() []string {
ids := []string{}
if primary := s.EffectiveRPID(); primary != "" {
ids = append(ids, primary)
}
legacy, err := ParsePasskeyRPIDs(s.LegacyRPIDs, s.Origins)
if err != nil {
return ids
}
for _, id := range legacy {
if !slices.Contains(ids, id) {
ids = append(ids, id)
}
}
return ids
}
var defaultPasskeySettings = PasskeySettings{
Enabled: false,
RPDisplayName: common.SystemName,
@@ -33,18 +148,22 @@ func init() {
}
func GetPasskeySettings() *PasskeySettings {
if defaultPasskeySettings.RPID == "" && ServerAddress != "" {
// 从ServerAddress提取域名作为RPID
// ServerAddress可能是 "https://newapi.pro" 这种格式
serverAddr := strings.TrimSpace(ServerAddress)
if parsed, err := url.Parse(serverAddr); err == nil && parsed.Host != "" {
defaultPasskeySettings.RPID = parsed.Host
} else {
defaultPasskeySettings.RPID = serverAddr
}
}
if defaultPasskeySettings.Origins == "" || defaultPasskeySettings.Origins == "[]" {
defaultPasskeySettings.Origins = ServerAddress
}
return &defaultPasskeySettings
}
func (s PasskeySettings) WithDefaults(serverAddress string) PasskeySettings {
if s.RPID == "" && serverAddress != "" {
// 从ServerAddress提取域名作为RPID
// ServerAddress可能是 "https://newapi.pro" 这种格式
serverAddr := strings.TrimSpace(serverAddress)
if parsed, err := url.Parse(serverAddr); err == nil && parsed.Host != "" {
s.RPID = parsed.Host
} else {
s.RPID = serverAddr
}
}
if s.Origins == "" || s.Origins == "[]" {
s.Origins = serverAddress
}
return s
}