Skip to content
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion common/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func SetTheme(t string) {

// var ChatLink = ""
// var ChatLink2 = ""
var QuotaPerUnit = 500 * 1000.0 // $0.002 / 1K tokens
var QuotaPerUnit = 500 * 1000.0 // ¥0.002 / 1K tokens(人民币基准)
// 保留旧变量以兼容历史逻辑,实际展示由 general_setting.quota_display_type 控制
var DisplayInCurrencyEnabled = true
var DisplayTokenStatEnabled = true
Expand Down
15 changes: 7 additions & 8 deletions controller/billing.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,17 @@ func GetSubscription(c *gin.Context) {
}
quota := remainQuota + usedQuota
amount := float64(quota)
// OpenAI 兼容接口中的 *_USD 字段含义保持“额度单位”对应值:
// 我们将其解释为以“站点展示类型”为准:
// - USD: 直接除以 QuotaPerUnit
// - CNY: 先转 USD 再乘汇率
// 计价基准为人民币:quota / QuotaPerUnit 直接得到 CNY
// - CNY: 直接除以 QuotaPerUnit
// - USD: 除以 QuotaPerUnit 再除以汇率
// - TOKENS: 直接使用 tokens 数量
switch operation_setting.GetQuotaDisplayType() {
case operation_setting.QuotaDisplayTypeCNY:
amount = amount / common.QuotaPerUnit * operation_setting.USDExchangeRate
amount = amount / common.QuotaPerUnit
case operation_setting.QuotaDisplayTypeTokens:
// amount 保持 tokens 数值
default:
amount = amount / common.QuotaPerUnit
amount = amount / common.QuotaPerUnit / operation_setting.USDExchangeRate
}
Comment on lines 47 to 54

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check for USDExchangeRate validation in operation_setting

# Search for USDExchangeRate assignments and validation
rg -nP -C5 'USDExchangeRate\s*=' --type=go

# Search for validation patterns (> 0, != 0, etc.)
rg -nP 'USDExchangeRate.*[>!]=\s*0' --type=go

Repository: QuantumNous/new-api

Length of output: 860


🏁 Script executed:

# Check the operation_setting package structure
find . -name "*operation_setting*" -type f | grep -E "\.(go|proto)$"

Repository: QuantumNous/new-api

Length of output: 112


🏁 Script executed:

# Examine billing.go to see the actual code at lines 47-54 and around line 99
rg -n "GetQuotaDisplayType|GetUsage" --type=go -B2 -A10 | head -100

Repository: QuantumNous/new-api

Length of output: 6307


🏁 Script executed:

# Check how USDExchangeRate is initialized and used in operation_setting
rg -n "USDExchangeRate" --type=go -B3 -A3

Repository: QuantumNous/new-api

Length of output: 3586


🏁 Script executed:

# Read the operation_setting.go file to check its contents
cat -n setting/operation_setting/operation_setting.go | head -100

Repository: QuantumNous/new-api

Length of output: 1081


🏁 Script executed:

# Check if USDExchangeRate has any getter function with validation
rg -n "func.*USDExchangeRate|USDExchangeRate\s*>" setting/operation_setting/ --type=go

Repository: QuantumNous/new-api

Length of output: 45


🏁 Script executed:

# Check payment_setting_old.go and any other payment-related files
cat -n setting/operation_setting/payment_setting_old.go | head -50

Repository: QuantumNous/new-api

Length of output: 1474


🏁 Script executed:

# Check the context around the USDExchangeRate assignment in model/option.go
sed -n '365,375p' model/option.go

Repository: QuantumNous/new-api

Length of output: 469


🏁 Script executed:

# Search for any validation or guards around USDExchangeRate usage
rg -n "USDExchangeRate" --type=go -B2 -A2 | grep -E "(<=|>=|>|<|!=|==|if|validate|check|guard)" -B2 -A2

Repository: QuantumNous/new-api

Length of output: 305


🏁 Script executed:

# Check if there's any initialization or validation logic when loading settings
rg -n "LoadOptions|InitOptions|USDExchangeRate" --type=go -B5 -A5 | head -80

Repository: QuantumNous/new-api

Length of output: 4805


🏁 Script executed:

# Check if there are any guards around divisions by USDExchangeRate
rg -n "USDExchangeRate" controller/billing.go logger/logger.go --type=go -B5 | grep -E "(if|guard|validate|<=|>=)"

Repository: QuantumNous/new-api

Length of output: 45


🏁 Script executed:

# Verify the entire context of controller/billing.go around the issue
sed -n '45,60p' controller/billing.go
sed -n '92,105p' controller/billing.go

Repository: QuantumNous/new-api

Length of output: 1027


Validate USDExchangeRate to prevent division by zero.

The default case divides by operation_setting.USDExchangeRate at lines 53 and 99 without validation. If the exchange rate is zero or becomes zero (e.g., from a failed strconv.ParseFloat in model/option.go:369), this will cause a runtime panic. Additional unguarded divisions exist in logger/logger.go at lines 142 and 168.

🛡️ Proposed fix to add validation
 	switch operation_setting.GetQuotaDisplayType() {
 	case operation_setting.QuotaDisplayTypeCNY:
 		amount = amount / common.QuotaPerUnit
 	case operation_setting.QuotaDisplayTypeTokens:
 		// amount 保持 tokens 数值
 	default:
+		if operation_setting.USDExchangeRate <= 0 {
+			operation_setting.USDExchangeRate = 1.0 // fallback to 1:1 if invalid
+		}
 		amount = amount / common.QuotaPerUnit / operation_setting.USDExchangeRate
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
switch operation_setting.GetQuotaDisplayType() {
case operation_setting.QuotaDisplayTypeCNY:
amount = amount / common.QuotaPerUnit * operation_setting.USDExchangeRate
amount = amount / common.QuotaPerUnit
case operation_setting.QuotaDisplayTypeTokens:
// amount 保持 tokens 数值
default:
amount = amount / common.QuotaPerUnit
amount = amount / common.QuotaPerUnit / operation_setting.USDExchangeRate
}
switch operation_setting.GetQuotaDisplayType() {
case operation_setting.QuotaDisplayTypeCNY:
amount = amount / common.QuotaPerUnit
case operation_setting.QuotaDisplayTypeTokens:
// amount 保持 tokens 数值
default:
if operation_setting.USDExchangeRate <= 0 {
operation_setting.USDExchangeRate = 1.0 // fallback to 1:1 if invalid
}
amount = amount / common.QuotaPerUnit / operation_setting.USDExchangeRate
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/billing.go` around lines 47 - 54, The default branch in
controller.billing uses operation_setting.USDExchangeRate to divide amount (and
similar divisions exist in logger code); add a guard that checks
operation_setting.USDExchangeRate != 0 before performing the division (e.g.,
capture into a local safeRate := operation_setting.USDExchangeRate, if safeRate
== 0 then log a warning and either return/skip conversion or use a defined
fallback rate), update the default case in the switch around
operation_setting.GetQuotaDisplayType() to use safeRate for dividing amount, and
apply the same validation pattern to any logger functions that divide by
operation_setting.USDExchangeRate so no unguarded division can panic.

if token != nil && token.UnlimitedQuota {
amount = 100000000
Expand Down Expand Up @@ -93,11 +92,11 @@ func GetUsage(c *gin.Context) {
amount := float64(quota)
switch operation_setting.GetQuotaDisplayType() {
case operation_setting.QuotaDisplayTypeCNY:
amount = amount / common.QuotaPerUnit * operation_setting.USDExchangeRate
amount = amount / common.QuotaPerUnit
case operation_setting.QuotaDisplayTypeTokens:
// tokens 保持原值
default:
amount = amount / common.QuotaPerUnit
amount = amount / common.QuotaPerUnit / operation_setting.USDExchangeRate
}
usage := OpenAIUsageResponse{
Object: "list",
Expand Down
30 changes: 24 additions & 6 deletions docker-compose.dev.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
# Frontend Development - Backend built from local source
# Frontend Development - Backend + Frontend in Docker
#
# Usage:
# 1. docker compose -f docker-compose.dev.yml up -d
# 2. cd web && bun install && bun run dev
# 3. Open http://localhost:3001 (Rsbuild dev server, API auto-proxied to :3000)
# docker compose -f docker-compose.dev.yml up -d
# Open http://localhost:5173 (Rsbuild dev server, API auto-proxied to :3000)
#
# Rebuild backend after Go code changes:
# docker compose -f docker-compose.dev.yml up -d --build new-api
Expand Down Expand Up @@ -39,15 +38,33 @@ services:
networks:
- dev-network

frontend:
image: oven/bun:1
container_name: new-api-frontend
restart: unless-stopped
working_dir: /app
ports:
- "5173:3000"
volumes:
- ./web/default:/app
- frontend_node_modules:/app/node_modules
environment:
- VITE_REACT_APP_SERVER_URL=http://new-api-dev:3000
command: sh -c "bun install && bun run dev --host 0.0.0.0"
depends_on:
- new-api
networks:
- dev-network

redis:
image: redis:7-alpine
image: redis:latest
container_name: new-api-dev-redis
restart: unless-stopped
networks:
- dev-network

postgres:
image: postgres:15-alpine
image: postgres:15
container_name: new-api-dev-pg
restart: unless-stopped
environment:
Expand All @@ -67,6 +84,7 @@ services:
volumes:
dev_data:
dev_pg_data:
frontend_node_modules:

networks:
dev-network:
Expand Down
24 changes: 12 additions & 12 deletions logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,15 +118,14 @@ func logHelper(ctx context.Context, level string, msg string) {
}

func LogQuota(quota int) string {
// 新逻辑:根据额度展示类型输出
// 计价基准为人民币,直接除以 QuotaPerUnit 即为 CNY
q := float64(quota)
switch operation_setting.GetQuotaDisplayType() {
case operation_setting.QuotaDisplayTypeCNY:
usd := q / common.QuotaPerUnit
cny := usd * operation_setting.USDExchangeRate
cny := q / common.QuotaPerUnit
return fmt.Sprintf("¥%.6f 额度", cny)
case operation_setting.QuotaDisplayTypeCustom:
usd := q / common.QuotaPerUnit
base := q / common.QuotaPerUnit
rate := operation_setting.GetGeneralSetting().CustomCurrencyExchangeRate
symbol := operation_setting.GetGeneralSetting().CustomCurrencySymbol
if symbol == "" {
Expand All @@ -135,24 +134,24 @@ func LogQuota(quota int) string {
if rate <= 0 {
rate = 1
}
v := usd * rate
v := base * rate
return fmt.Sprintf("%s%.6f 额度", symbol, v)
case operation_setting.QuotaDisplayTypeTokens:
return fmt.Sprintf("%d 点额度", quota)
default: // USD
return fmt.Sprintf("$%.6f 额度", q/common.QuotaPerUnit)
usd := q / common.QuotaPerUnit / operation_setting.USDExchangeRate
return fmt.Sprintf("$%.6f 额度", usd)
}
Comment on lines 141 to 144

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validate USDExchangeRate before division.

Line 142 (and line 168 in FormatQuota) divides by operation_setting.USDExchangeRate without validation. If the exchange rate is zero or negative, this will cause a runtime panic or produce nonsensical results. The custom currency case has proper validation (lines 134-136), but the USD case does not.

🛡️ Proposed fix to add validation
 	default: // USD
+		exchangeRate := operation_setting.USDExchangeRate
+		if exchangeRate <= 0 {
+			exchangeRate = 1.0
+		}
-		usd := q / common.QuotaPerUnit / operation_setting.USDExchangeRate
+		usd := q / common.QuotaPerUnit / exchangeRate
 		return fmt.Sprintf("$%.6f 额度", usd)
 	}

Apply a similar fix to FormatQuota at lines 167-169.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@logger/logger.go` around lines 141 - 144, FormatQuota currently divides by
operation_setting.USDExchangeRate in the default (USD) branch without
validation; replicate the same validation used in the custom currency branch
(check that operation_setting.USDExchangeRate > 0) before doing the division in
the default/USD case inside FormatQuota, and if the rate is invalid return a
safe fallback message or handle the error similarly to the custom currency path
to avoid divide-by-zero or nonsensical results.

}

func FormatQuota(quota int) string {
q := float64(quota)
switch operation_setting.GetQuotaDisplayType() {
case operation_setting.QuotaDisplayTypeCNY:
usd := q / common.QuotaPerUnit
cny := usd * operation_setting.USDExchangeRate
cny := q / common.QuotaPerUnit
return fmt.Sprintf("¥%.6f", cny)
case operation_setting.QuotaDisplayTypeCustom:
usd := q / common.QuotaPerUnit
base := q / common.QuotaPerUnit
rate := operation_setting.GetGeneralSetting().CustomCurrencyExchangeRate
symbol := operation_setting.GetGeneralSetting().CustomCurrencySymbol
if symbol == "" {
Expand All @@ -161,12 +160,13 @@ func FormatQuota(quota int) string {
if rate <= 0 {
rate = 1
}
v := usd * rate
v := base * rate
return fmt.Sprintf("%s%.6f", symbol, v)
case operation_setting.QuotaDisplayTypeTokens:
return fmt.Sprintf("%d", quota)
default:
return fmt.Sprintf("$%.6f", q/common.QuotaPerUnit)
default: // USD
usd := q / common.QuotaPerUnit / operation_setting.USDExchangeRate
return fmt.Sprintf("$%.6f", usd)
}
}

Expand Down
2 changes: 1 addition & 1 deletion setting/operation_setting/general_setting.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ var generalSetting = GeneralSetting{
DocsLink: "https://docs.newapi.pro",
PingIntervalEnabled: false,
PingIntervalSeconds: 60,
QuotaDisplayType: QuotaDisplayTypeUSD,
QuotaDisplayType: QuotaDisplayTypeCNY,
CustomCurrencySymbol: "¤",
CustomCurrencyExchangeRate: 1.0,
}
Expand Down
18 changes: 7 additions & 11 deletions setting/ratio_setting/model_ratio.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,16 @@ import (
"github.com/QuantumNous/new-api/types"
)

// from songquanpeng/one-api
// 计价基准:人民币 (CNY)
const (
USD2RMB = 7.3 // 暂定 1 USD = 7.3 RMB
USD = 500 // $0.002 = 1 -> $1 = 500
RMB = USD / USD2RMB
USD2RMB = 7.3 // 暂定 1 USD = 7.3 RMB
RMB = 500 // ¥0.002 = 1 -> ¥1 = 500(基准货币)
USD = RMB * USD2RMB // $1 = 3650(由汇率换算,仅供参考)
)

// modelRatio
// https://platform.openai.com/docs/models/model-endpoint-compatibility
// https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Blfmc9dlf
// https://openai.com/pricing
// TODO: when a new api is enabled, check the pricing here
// 1 === $0.002 / 1K tokens
// 1 === ¥0.014 / 1k tokens
// modelRatio — 以人民币为基准
// 1 === ¥0.002 / 1K tokens === ¥2 / 1M tokens
// 1 === $0.000274 / 1K tokens(按 7.3 汇率换算)

var defaultModelRatio = map[string]float64{
//"midjourney": 50,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,15 @@ const formatNumber = (value) => {
if (num === null) {
return '';
}
return parseFloat(num.toFixed(12)).toString();
return parseFloat(num.toFixed(8)).toString();
};

const formatRatio = (value) => {
const num = toNumberOrNull(value);
if (num === null) {
return '';
}
return parseFloat(num.toFixed(14)).toString();
};

const toNormalizedNumber = (value) => {
Expand Down Expand Up @@ -565,43 +573,43 @@ export const buildPreviewRows = (model, t) => {
{
key: 'ModelRatio',
label: 'ModelRatio',
value: formatNumber(inputPrice / 2),
value: formatRatio(inputPrice / 2),
},
{
key: 'CompletionRatio',
label: 'CompletionRatio',
value: model.completionRatioLocked
? `${model.lockedCompletionRatio || t('空')} (${t('后端固定')})`
: completionPrice !== null
? formatNumber(completionPrice / inputPrice)
? formatRatio(completionPrice / inputPrice)
: t('空'),
},
{
key: 'CacheRatio',
label: 'CacheRatio',
value:
cachePrice !== null ? formatNumber(cachePrice / inputPrice) : t('空'),
cachePrice !== null ? formatRatio(cachePrice / inputPrice) : t('空'),
},
{
key: 'CreateCacheRatio',
label: 'CreateCacheRatio',
value:
createCachePrice !== null
? formatNumber(createCachePrice / inputPrice)
? formatRatio(createCachePrice / inputPrice)
: t('空'),
},
{
key: 'ImageRatio',
label: 'ImageRatio',
value:
imagePrice !== null ? formatNumber(imagePrice / inputPrice) : t('空'),
imagePrice !== null ? formatRatio(imagePrice / inputPrice) : t('空'),
},
{
key: 'AudioRatio',
label: 'AudioRatio',
value:
audioInputPrice !== null
? formatNumber(audioInputPrice / inputPrice)
? formatRatio(audioInputPrice / inputPrice)
: t('空'),
},
{
Expand All @@ -611,7 +619,7 @@ export const buildPreviewRows = (model, t) => {
audioOutputPrice !== null &&
audioInputPrice !== null &&
audioInputPrice !== 0
? formatNumber(audioOutputPrice / audioInputPrice)
? formatRatio(audioOutputPrice / audioInputPrice)
: t('空'),
},
];
Expand Down
1 change: 1 addition & 0 deletions web/default/bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 11 additions & 5 deletions web/default/rsbuild.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,21 @@ export default defineConfig(({ envMode }) => {
},
},
tools: {
rspack: {
plugins: [
rspack: (config) => {
config.plugins = config.plugins ?? []
config.plugins.push(
tanstackRouter({
target: 'react',
// Dev: avoid per-route async chunks (reduces white flash on navigation + faster HMR feedback).
// Prod: keep route-based code splitting.
autoCodeSplitting: isProd,
}),
],
)
if (!isProd) {
config.watchOptions = {
poll: 1000,
aggregateTimeout: 300,
}
}
return config
},
},
}
Expand Down
7 changes: 7 additions & 0 deletions web/default/src/components/json-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,13 @@ export function JsonEditor({
<Textarea
value={jsonValue}
onChange={(e) => handleJsonChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Tab') {
e.preventDefault()
// eslint-disable-next-line deprecation/deprecation
document.execCommand('insertText', false, ' ')
}
}}
placeholder={
template ? JSON.stringify(template, null, 2) : '{"key": "value"}'
}
Expand Down
Loading