Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,7 @@ data/
token_estimator_test.go
skills-lock.json
.playwright-mcp
35sz-api
.gitignore

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 | 🔴 Critical | ⚡ Quick win

Remove the self-referential .gitignore entry.

Line 40 tells git to ignore the .gitignore file itself, which would prevent version control from tracking changes to the ignore rules. This line should be removed entirely.

🐛 Proposed fix
 35sz-api
-.gitignore
 35sz-api.pid
 35sz-api.log
🤖 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 @.gitignore at line 40, Remove the self-referential ignore entry that lists
".gitignore" so the repository will track changes to the ignore rules; locate
the literal ".gitignore" entry in the .gitignore file and delete that line
entirely (keep all other ignore patterns intact).

35sz-api.pid
35sz-api.log
67 changes: 67 additions & 0 deletions common/crypto.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
package common

import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
"os"

"golang.org/x/crypto/bcrypt"
)
Expand All @@ -30,3 +37,63 @@ func ValidatePasswordAndHash(password string, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}

func getPaymentEncryptionKey() []byte {
if key := os.Getenv("PAYMENT_CONFIG_ENCRYPTION_KEY"); len(key) == 32 {
return []byte(key)
}
h := sha256.Sum256([]byte(CryptoSecret))
return h[:]
Comment on lines +41 to +46

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

Fail fast on an invalid PAYMENT_CONFIG_ENCRYPTION_KEY.

A mis-sized env value currently falls back to sha256(CryptoSecret) silently. That means secrets can be encrypted with an unintended key, and once the operator fixes the env var later, previously stored ciphertext becomes undecryptable.

💡 Proposed fix
-func getPaymentEncryptionKey() []byte {
-	if key := os.Getenv("PAYMENT_CONFIG_ENCRYPTION_KEY"); len(key) == 32 {
-		return []byte(key)
-	}
-	h := sha256.Sum256([]byte(CryptoSecret))
-	return h[:]
+func getPaymentEncryptionKey() ([]byte, error) {
+	if key, ok := os.LookupEnv("PAYMENT_CONFIG_ENCRYPTION_KEY"); ok {
+		if len(key) != 32 {
+			return nil, fmt.Errorf("PAYMENT_CONFIG_ENCRYPTION_KEY must be exactly 32 bytes")
+		}
+		return []byte(key), nil
+	}
+	h := sha256.Sum256([]byte(CryptoSecret))
+	return h[:], nil
 }
-	block, err := aes.NewCipher(getPaymentEncryptionKey())
+	key, err := getPaymentEncryptionKey()
+	if err != nil {
+		return "", err
+	}
+	block, err := aes.NewCipher(key)
🤖 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 `@common/crypto.go` around lines 41 - 46, getPaymentEncryptionKey currently
silently falls back to sha256(CryptoSecret) when PAYMENT_CONFIG_ENCRYPTION_KEY
is the wrong length; change it to fail fast: if
os.Getenv("PAYMENT_CONFIG_ENCRYPTION_KEY") returns a non-empty value and len !=
32, immediately log.Fatal/ panic with a clear message (including the env var
name and expected length) so startup fails rather than continuing with an
unintended key; otherwise if len == 32 return []byte(key), and only compute
sha256(CryptoSecret) when the env var is unset/empty.

}

func EncryptPaymentSecret(plaintext string) (string, error) {
block, err := aes.NewCipher(getPaymentEncryptionKey())
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), []byte("payment-config"))
return base64.StdEncoding.EncodeToString(ciphertext), nil
}

func DecryptPaymentSecret(ciphertext string) (string, error) {
data, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
return "", err
}
block, err := aes.NewCipher(getPaymentEncryptionKey())
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonceSize := gcm.NonceSize()
if len(data) < nonceSize {
return "", fmt.Errorf("ciphertext too short")
}
plaintext, err := gcm.Open(nil, data[:nonceSize], data[nonceSize:], []byte("payment-config"))
if err != nil {
return "", err
}
return string(plaintext), nil
}

func MaskSecret(secret string) string {
if len(secret) <= 4 {
return "****"
}
return secret[:4] + "****"
}

func IsMaskedSecret(secret string) bool {
return len(secret) > 4 && secret[len(secret)-4:] == "****"
Comment on lines +90 to +98

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 | 🟡 Minor | ⚡ Quick win

MaskSecret and IsMaskedSecret disagree for short secrets.

MaskSecret("abcd") returns "****", but IsMaskedSecret("****") is false. Any update flow that preserves masked values will treat a 4-character secret as a brand-new literal and overwrite the stored secret.

💡 Proposed fix
 func IsMaskedSecret(secret string) bool {
-	return len(secret) > 4 && secret[len(secret)-4:] == "****"
+	return secret == "****" || (len(secret) > 4 && secret[len(secret)-4:] == "****")
 }
📝 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
func MaskSecret(secret string) string {
if len(secret) <= 4 {
return "****"
}
return secret[:4] + "****"
}
func IsMaskedSecret(secret string) bool {
return len(secret) > 4 && secret[len(secret)-4:] == "****"
func MaskSecret(secret string) string {
if len(secret) <= 4 {
return "****"
}
return secret[:4] + "****"
}
func IsMaskedSecret(secret string) bool {
return secret == "****" || (len(secret) > 4 && secret[len(secret)-4:] == "****")
}
🤖 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 `@common/crypto.go` around lines 90 - 98, MaskSecret and IsMaskedSecret
disagree for short secrets; update MaskSecret (function MaskSecret) so that for
secrets with length <= 4 it returns the entire secret concatenated with "****"
(e.g., secret + "****") instead of just "****", while keeping the existing
behavior for longer secrets (secret[:4] + "****"); this makes IsMaskedSecret
(which checks suffix == "****") correctly detect masked short secrets without
changing IsMaskedSecret logic.

}
39 changes: 39 additions & 0 deletions common/payment_crypto_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package common

import "testing"

func TestEncryptPaymentSecretRoundTrip(t *testing.T) {
plaintext := "merchant-private-key"

ciphertext, err := EncryptPaymentSecret(plaintext)
if err != nil {
t.Fatalf("EncryptPaymentSecret returned error: %v", err)
}
if ciphertext == "" {
t.Fatal("EncryptPaymentSecret returned empty ciphertext")
}
if ciphertext == plaintext {
t.Fatal("EncryptPaymentSecret returned plaintext")
}

decrypted, err := DecryptPaymentSecret(ciphertext)
if err != nil {
t.Fatalf("DecryptPaymentSecret returned error: %v", err)
}
if decrypted != plaintext {
t.Fatalf("decrypted secret = %q, want %q", decrypted, plaintext)
}
}

func TestMaskPaymentSecret(t *testing.T) {
masked := MaskSecret("abcdef")
if masked != "abcd****" {
t.Fatalf("MaskSecret returned %q", masked)
}
if !IsMaskedSecret(masked) {
t.Fatalf("IsMaskedSecret(%q) = false", masked)
}
if IsMaskedSecret("abcdef") {
t.Fatal("IsMaskedSecret returned true for an unmasked secret")
}
}
104 changes: 80 additions & 24 deletions controller/channel-test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,27 +121,37 @@ func testChannel(channel *model.Channel, testUserID int, testModel string, endpo
} else {
// 如果没有指定端点类型,使用原有的自动检测逻辑

if strings.Contains(strings.ToLower(testModel), "rerank") {
requestPath = "/v1/rerank"
metadataEndpointResolved := false
if modelType := getModelTypeForTest(testModel); modelType != "" {
if endpointInfo, ok := common.GetDefaultEndpointInfo(endpointTypeFromModelType(modelType)); ok {
requestPath = endpointInfo.Path
metadataEndpointResolved = true
}
}

// 先判断是否为 Embedding 模型
if strings.Contains(strings.ToLower(testModel), "embedding") ||
strings.HasPrefix(testModel, "m3e") || // m3e 系列模型
strings.Contains(testModel, "bge-") || // bge 系列模型
strings.Contains(testModel, "embed") ||
channel.Type == constant.ChannelTypeMokaAI { // 其他 embedding 模型
requestPath = "/v1/embeddings" // 修改请求路径
}
if !metadataEndpointResolved {
if strings.Contains(strings.ToLower(testModel), "rerank") {
requestPath = "/v1/rerank"
}

// VolcEngine 图像生成模型
if channel.Type == constant.ChannelTypeVolcEngine && strings.Contains(testModel, "seedream") {
requestPath = "/v1/images/generations"
}
// 先判断是否为 Embedding 模型
if strings.Contains(strings.ToLower(testModel), "embedding") ||
strings.HasPrefix(testModel, "m3e") || // m3e 系列模型
strings.Contains(testModel, "bge-") || // bge 系列模型
strings.Contains(testModel, "embed") ||
channel.Type == constant.ChannelTypeMokaAI { // 其他 embedding 模型
requestPath = "/v1/embeddings" // 修改请求路径
}

// VolcEngine 图像生成模型
if channel.Type == constant.ChannelTypeVolcEngine && strings.Contains(testModel, "seedream") {
requestPath = "/v1/images/generations"
}
Comment on lines +146 to +149

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

Make Seedream path detection case-insensitive.

This branch is currently case-sensitive, while buildImageTestRequest() and the later automatic request fallback both lowercase the model name. A model like Doubao-Seedream-... can therefore keep /v1/chat/completions here but still build a *dto.ImageRequest, which breaks channel tests with a relay/request-type mismatch.

🐛 Suggested change
-			if channel.Type == constant.ChannelTypeVolcEngine && strings.Contains(testModel, "seedream") {
+			if channel.Type == constant.ChannelTypeVolcEngine && strings.Contains(strings.ToLower(testModel), "seedream") {
 				requestPath = "/v1/images/generations"
 			}
🤖 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/channel-test.go` around lines 146 - 149, The branch detecting
Seedream is currently case-sensitive and should match model names like
"Doubao-Seedream-..."; in controller/channel-test.go update the check that sets
requestPath (the if using channel.Type, constant.ChannelTypeVolcEngine, and
testModel) to perform a case-insensitive match (e.g. compare a lowercased
testModel to "seedream") so it aligns with buildImageTestRequest() and the later
fallback logic and avoids relay/request-type mismatches.


// responses-only models
if strings.Contains(strings.ToLower(testModel), "codex") {
requestPath = "/v1/responses"
// responses-only models
if strings.Contains(strings.ToLower(testModel), "codex") {
requestPath = "/v1/responses"
}
}

// responses compaction models (must use /v1/responses/compact)
Expand Down Expand Up @@ -696,6 +706,43 @@ func detectErrorMessageFromJSONBytes(jsonBytes []byte) string {
return message
}

func endpointTypeFromModelType(modelType string) constant.EndpointType {
switch model.NormalizeModelType(modelType) {
case model.ModelTypeEmbedding:
return constant.EndpointTypeEmbeddings
case model.ModelTypeImage:
return constant.EndpointTypeImageGeneration
case model.ModelTypeFile:
return constant.EndpointTypeOpenAIResponse
default:
return constant.EndpointTypeOpenAI
}
}

func getModelTypeForTest(modelName string) string {
if model.DB == nil {
return ""
}
var m model.Model
if err := model.DB.Where("model_name = ?", modelName).First(&m).Error; err != nil {
return ""
}
return m.ModelType
}

func buildImageTestRequest(modelName string, channel *model.Channel) *dto.ImageRequest {
size := "1024x1024"
if channel != nil && channel.Type == constant.ChannelTypeVolcEngine && strings.Contains(strings.ToLower(modelName), "seedream") {
size = "2K"
}
return &dto.ImageRequest{
Model: modelName,
Prompt: "a cute cat",
N: lo.ToPtr(uint(1)),
Size: size,
}
}

func buildTestRequest(model string, endpointType string, channel *model.Channel, isStream bool) dto.Request {
testResponsesInput := json.RawMessage(`[{"role":"user","content":"hi"}]`)

Expand All @@ -709,13 +756,7 @@ func buildTestRequest(model string, endpointType string, channel *model.Channel,
Input: []any{"hello world"},
}
case constant.EndpointTypeImageGeneration:
// 返回 ImageRequest
return &dto.ImageRequest{
Model: model,
Prompt: "a cute cat",
N: lo.ToPtr(uint(1)),
Size: "1024x1024",
}
return buildImageTestRequest(model, channel)
case constant.EndpointTypeJinaRerank:
// 返回 RerankRequest
return &dto.RerankRequest{
Expand Down Expand Up @@ -762,6 +803,17 @@ func buildTestRequest(model string, endpointType string, channel *model.Channel,
}

// 自动检测逻辑(保持原有行为)
if modelType := getModelTypeForTest(model); modelType != "" {
switch endpointTypeFromModelType(modelType) {
case constant.EndpointTypeEmbeddings:
return &dto.EmbeddingRequest{Model: model, Input: []any{"hello world"}}
case constant.EndpointTypeImageGeneration:
return buildImageTestRequest(model, channel)
case constant.EndpointTypeOpenAIResponse:
return &dto.OpenAIResponsesRequest{Model: model, Input: json.RawMessage(`[{"role":"user","content":"hi"}]`), Stream: lo.ToPtr(isStream)}
}
}

if strings.Contains(strings.ToLower(model), "rerank") {
return &dto.RerankRequest{
Model: model,
Expand Down Expand Up @@ -799,6 +851,10 @@ func buildTestRequest(model string, endpointType string, channel *model.Channel,
}
}

if channel != nil && channel.Type == constant.ChannelTypeVolcEngine && strings.Contains(strings.ToLower(model), "seedream") {
return buildImageTestRequest(model, channel)
}

// Chat/Completion 请求 - 返回 GeneralOpenAIRequest
testRequest := &dto.GeneralOpenAIRequest{
Model: model,
Expand Down
33 changes: 33 additions & 0 deletions controller/channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,35 @@ import (
"gorm.io/gorm"
)

func syncChannelModelMetadata(channel *model.Channel) {
if channel == nil {
return
}
var settings map[string]any
if strings.TrimSpace(channel.OtherSettings) != "" {
_ = common.UnmarshalJsonStr(channel.OtherSettings, &settings)
}
modelType := model.ModelTypeText
if settings != nil {
if raw, ok := settings["model_type"].(string); ok {
modelType = model.NormalizeModelType(raw)
}
}
for _, modelName := range strings.Split(channel.Models, ",") {
modelName = strings.TrimSpace(modelName)
if modelName == "" {
continue
}
var existing model.Model
if err := model.DB.Where("model_name = ?", modelName).First(&existing).Error; err == nil {
existing.ModelType = modelType
_ = existing.Update()
continue
}
_ = (&model.Model{ModelName: modelName, ModelType: modelType, Status: 1}).Insert()
Comment on lines +45 to +50

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

Don’t swallow model-metadata write failures.

existing.Update() and Insert() are both ignored here, so AddChannel/UpdateChannel can return success while the new model_type never reaches model.Model. That leaves the new model-type filters and badges out of sync with the saved channel state.

Suggested fix
-func syncChannelModelMetadata(channel *model.Channel) {
+func syncChannelModelMetadata(channel *model.Channel) error {
 	if channel == nil {
-		return
+		return nil
 	}
 	var settings map[string]any
 	if strings.TrimSpace(channel.OtherSettings) != "" {
-		_ = common.UnmarshalJsonStr(channel.OtherSettings, &settings)
+		if err := common.UnmarshalJsonStr(channel.OtherSettings, &settings); err != nil {
+			return err
+		}
 	}
 	modelType := model.ModelTypeText
 	if settings != nil {
 		if raw, ok := settings["model_type"].(string); ok {
 			modelType = model.NormalizeModelType(raw)
@@
 		var existing model.Model
 		if err := model.DB.Where("model_name = ?", modelName).First(&existing).Error; err == nil {
 			existing.ModelType = modelType
-			_ = existing.Update()
-			continue
+			if err := existing.Update(); err != nil {
+				return err
+			}
+		} else {
+			if err := (&model.Model{ModelName: modelName, ModelType: modelType, Status: 1}).Insert(); err != nil {
+				return err
+			}
 		}
-		_ = (&model.Model{ModelName: modelName, ModelType: modelType, Status: 1}).Insert()
 	}
+	return nil
 }
-	for i := range channels {
-		syncChannelModelMetadata(&channels[i])
-	}
+	for i := range channels {
+		if err := syncChannelModelMetadata(&channels[i]); err != nil {
+			common.ApiError(c, err)
+			return
+		}
+	}
-	syncChannelModelMetadata(&channel.Channel)
+	if err := syncChannelModelMetadata(&channel.Channel); err != nil {
+		common.ApiError(c, err)
+		return
+	}
📝 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
if err := model.DB.Where("model_name = ?", modelName).First(&existing).Error; err == nil {
existing.ModelType = modelType
_ = existing.Update()
continue
}
_ = (&model.Model{ModelName: modelName, ModelType: modelType, Status: 1}).Insert()
if err := model.DB.Where("model_name = ?", modelName).First(&existing).Error; err == nil {
existing.ModelType = modelType
if err := existing.Update(); err != nil {
return err
}
} else {
if err := (&model.Model{ModelName: modelName, ModelType: modelType, Status: 1}).Insert(); err != nil {
return err
}
}
🤖 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/channel.go` around lines 45 - 50, The code currently ignores
errors from existing.Update() and the Insert() call, so AddChannel/UpdateChannel
can succeed while model metadata writes fail; modify the block that finds or
creates model.Model (the model.DB.Where(...).First(&existing).Error branch) to
check the returned error from existing.Update() and from
(&model.Model{ModelName: modelName, ModelType: modelType, Status: 1}).Insert(),
and propagate or return those errors (or log and fail the channel operation)
instead of discarding them; ensure callers AddChannel/UpdateChannel
receive/handle the error so model_type stays in sync with saved channel state.

}
}

type OpenAIModel struct {
ID string `json:"id"`
Object string `json:"object"`
Expand Down Expand Up @@ -676,6 +705,9 @@ func AddChannel(c *gin.Context) {
common.ApiError(c, err)
return
}
for i := range channels {
syncChannelModelMetadata(&channels[i])
}
service.ResetProxyClientCache()
c.JSON(http.StatusOK, gin.H{
"success": true,
Expand Down Expand Up @@ -979,6 +1011,7 @@ func UpdateChannel(c *gin.Context) {
common.ApiError(c, err)
return
}
syncChannelModelMetadata(&channel.Channel)
model.InitChannelCache()
service.ResetProxyClientCache()
channel.Key = ""
Expand Down
46 changes: 46 additions & 0 deletions controller/channel_test_model_type_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package controller

import (
"testing"

"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/model"
)

func TestBuildTestRequestAutoVolcSeedreamUsesImageRequest(t *testing.T) {
ch := &model.Channel{Type: constant.ChannelTypeVolcEngine}
req := buildTestRequest("doubao-seedream-4-5-251128", "", ch, false)
img, ok := req.(*dto.ImageRequest)
if !ok {
t.Fatalf("buildTestRequest returned %T, want *dto.ImageRequest", req)
}
if img.Size != "2K" {
t.Fatalf("seedream image test size = %q, want 2K", img.Size)
}
}

func TestBuildImageTestRequestUsesOpenAICompatibleDefaultSize(t *testing.T) {
ch := &model.Channel{Type: constant.ChannelTypeOpenAI}
req := buildImageTestRequest("gpt-image-1", ch)
if req.Size != "1024x1024" {
t.Fatalf("openai image test size = %q, want 1024x1024", req.Size)
}
}

func TestEndpointTypeFromModelType(t *testing.T) {
cases := map[string]constant.EndpointType{
model.ModelTypeText: constant.EndpointTypeOpenAI,
model.ModelTypeEmbedding: constant.EndpointTypeEmbeddings,
model.ModelTypeImage: constant.EndpointTypeImageGeneration,
model.ModelTypeFile: constant.EndpointTypeOpenAIResponse,
model.ModelTypeAudio: constant.EndpointTypeOpenAI,
model.ModelTypeVideo: constant.EndpointTypeOpenAI,
}
for modelType, want := range cases {
got := endpointTypeFromModelType(modelType)
if got != want {
t.Fatalf("endpointTypeFromModelType(%q) = %q, want %q", modelType, got, want)
}
}
}
Loading