feat(*): 插件中心与模型协议 - 完善声明式协议运行时并增加功能开放控制

This commit is contained in:
ddCat
2026-08-23 23:19:27 +08:00
parent 7cc6021f6e
commit 919037e5d9
106 changed files with 8817 additions and 500 deletions

View File

@@ -736,13 +736,71 @@ func RegisterSystemProxyRoutes(r *gin.RouterGroup, svc *service.Service) {
})
}
// SystemProxyNoRouteHandler handles the short public proxy form
// /api/{channelId}/{providerPath}. It deliberately runs from NoRoute so it
// cannot shadow existing business routes such as /api/tasks or /api/plugins.
func SystemProxyNoRouteHandler(svc *service.Service) gin.HandlerFunc {
return func(c *gin.Context) {
channelID, providerPath, ok := shortSystemProxyPath(c.Request.URL.Path)
if !ok {
fail(c, http.StatusNotFound, errors.New("请求不存在"))
return
}
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
return
}
channel, err := svc.SystemChannel(channelID)
if err != nil {
fail(c, http.StatusNotFound, errors.New("系统渠道不存在或已停用"))
return
}
proxySystemRequestPath(c, svc, user, channel, providerPath)
}
}
func shortSystemProxyPath(rawPath string) (string, string, bool) {
const prefix = "/api/"
if !strings.HasPrefix(rawPath, prefix) {
return "", "", false
}
remainder := strings.TrimPrefix(rawPath, prefix)
separator := strings.IndexByte(remainder, '/')
if separator <= 0 || separator == len(remainder)-1 {
return "", "", false
}
channelID := remainder[:separator]
providerPath := remainder[separator:]
if strings.ContainsAny(channelID, "?#\\") || strings.Contains(providerPath, "\\") || isReservedAPIPathPrefix(channelID) {
return "", "", false
}
return channelID, providerPath, true
}
// NoRoute also sees unmatched descendants of registered API routes. Keep the
// short proxy from interpreting /api/tasks/unknown (or /api/plugins/unknown)
// as a channel request when a business route returns 404.
func isReservedAPIPathPrefix(value string) bool {
switch strings.ToLower(strings.TrimSpace(value)) {
case "admin", "ai", "announcements", "assets", "auth", "canvas-projects", "channels", "features", "files", "model-catalog", "models", "oauth", "plugins", "projects", "protocols", "public", "resources", "sessions", "settings", "skills", "style-profiles", "tasks", "user-data", "voice-profiles", "wallet":
return true
default:
return false
}
}
func proxySystemRequest(c *gin.Context, svc *service.Service, user *model.User, channel *model.ModelChannel) {
proxySystemRequestPath(c, svc, user, channel, c.Param("path"))
}
func proxySystemRequestPath(c *gin.Context, svc *service.Service, user *model.User, channel *model.ModelChannel, providerPath string) {
startedAt := time.Now()
policy, available := loadRuntimePolicy(c, svc)
if !available || !enforceRateLimit(c, "system-proxy:"+user.ID, policy.Request.SystemRelayPerMinute, time.Minute) {
return
}
path := c.Param("path")
path := providerPath
if path == "" {
path = "/"
}
@@ -796,7 +854,7 @@ func proxySystemRequest(c *gin.Context, svc *service.Service, user *model.User,
for _, key := range []string{"key", "api_key", "access_token", "token"} {
query.Del(key)
}
target := strings.TrimRight(channel.BaseURL, "/") + path
target := service.ChannelAPIURLForProtocol(channel.BaseURL, path, protocol)
if encodedQuery := query.Encode(); encodedQuery != "" {
target += "?" + encodedQuery
}
@@ -852,6 +910,9 @@ func proxySystemRequest(c *gin.Context, svc *service.Service, user *model.User,
service.ApplyDefaultOutboundHeaders(upstreamReq)
if protocol == model.ChannelInterfaceGeminiVeo || protocol == model.ChannelInterfaceGeminiImage {
upstreamReq.Header.Set("x-goog-api-key", channel.APIKey)
} else if protocol == model.ChannelInterfaceClaudeAPI {
upstreamReq.Header.Set("x-api-key", channel.APIKey)
upstreamReq.Header.Set("anthropic-version", "2023-06-01")
} else {
upstreamReq.Header.Set("Authorization", "Bearer "+channel.APIKey)
}

View File

@@ -120,6 +120,9 @@ func proxyCustomRelayRequestWithService(c *gin.Context, policy service.RuntimeRe
service.ApplyDefaultOutboundHeaders(upstreamReq)
if apiFormat == "gemini" {
upstreamReq.Header.Set("x-goog-api-key", apiKey)
} else if apiFormat == "claude" {
upstreamReq.Header.Set("x-api-key", apiKey)
upstreamReq.Header.Set("anthropic-version", "2023-06-01")
} else {
upstreamReq.Header.Set("Authorization", "Bearer "+apiKey)
}

View File

@@ -126,6 +126,45 @@ func TestCustomRelayConvertsGeminiAuthentication(t *testing.T) {
}
}
func TestCustomRelayConvertsClaudeAuthentication(t *testing.T) {
gin.SetMode(gin.TestMode)
const apiKey = "claude-secret-key"
upstream := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/messages" {
t.Errorf("path = %q", r.URL.Path)
}
if r.Header.Get("x-api-key") != apiKey {
t.Errorf("x-api-key = %q", r.Header.Get("x-api-key"))
}
if r.Header.Get("Authorization") != "" {
t.Errorf("Authorization should not be forwarded, got %q", r.Header.Get("Authorization"))
}
if r.Header.Get("anthropic-version") != "2023-06-01" {
t.Errorf("anthropic-version = %q", r.Header.Get("anthropic-version"))
}
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"content":[{"type":"text","text":"claude relay works"}]}`)
}))
defer upstream.Close()
useCustomRelayTestClient(t, upstream.Client())
t.Setenv("CANVAS_ALLOWED_PRIVATE_UPSTREAM_HOSTS", "127.0.0.1")
request := httptest.NewRequest(http.MethodPost, "/api/ai/custom", strings.NewReader(`{"model":"claude-test","messages":[]}`))
request.Header.Set("Authorization", "Bearer "+apiKey)
request.Header.Set("Content-Type", "application/json")
request.Header.Set("X-Canvas-Upstream-URL", upstream.URL+"/v1/messages")
request.Header.Set("X-Canvas-Upstream-Format", "claude")
markDesktopLocalRelayTestRequest(request, upstream.URL)
response := httptest.NewRecorder()
context, _ := gin.CreateTestContext(response)
context.Request = request
proxyCustomRelayRequestWithCapabilities(context, defaultCustomRelayTestPolicy(), true)
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "claude relay works") {
t.Fatalf("status = %d, body = %s", response.Code, response.Body.String())
}
}
func TestCustomRelayStreamsBeforeUpstreamCompletes(t *testing.T) {
gin.SetMode(gin.TestMode)
const apiKey = "stream-secret"

View File

@@ -1,16 +1,89 @@
package handler
import (
"io"
"net/http"
"strconv"
"strings"
"infinite-canvas/backend/internal/model"
"infinite-canvas/backend/internal/service"
"github.com/gin-gonic/gin"
)
func RegisterPluginRoutes(r *gin.RouterGroup, svc *service.Service) {
r.GET("/plugins/eagle/library", func(c *gin.Context) {
pluginRoutes := r.Group("/plugins")
pluginRoutes.Use(requirePluginCenterAccess(svc))
// The frontend plugin center is the single management surface. Protocol
// plugins are returned as kind=protocol records alongside UI plugins.
pluginRoutes.GET("", func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
return
}
plugins, err := svc.PluginsForUser(user)
if err != nil {
failService(c, err)
return
}
ok(c, gin.H{"plugins": plugins})
})
pluginRoutes.POST("", func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
return
}
if err := svc.RequireAdmin(user); err != nil {
failService(c, err)
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 512<<10)
var data []byte
if strings.HasPrefix(strings.ToLower(c.GetHeader("Content-Type")), "multipart/form-data") {
file, _, fileErr := c.Request.FormFile("file")
if fileErr != nil {
fail(c, http.StatusBadRequest, fileErr)
return
}
defer file.Close()
data, err = io.ReadAll(io.LimitReader(file, 512<<10+1))
} else {
data, err = io.ReadAll(io.LimitReader(c.Request.Body, 512<<10+1))
}
if err != nil {
fail(c, http.StatusBadRequest, err)
return
}
plugin, err := svc.InstallPlugin(data)
if err != nil {
failService(c, err)
return
}
ok(c, gin.H{"plugin": plugin})
})
pluginRoutes.POST("/:id/enable", pluginToggle(svc, true))
pluginRoutes.POST("/:id/disable", pluginToggle(svc, false))
pluginRoutes.DELETE("/:id", func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
return
}
if err := svc.RequireAdmin(user); err != nil {
failService(c, err)
return
}
if err := svc.UninstallPlugin(c.Param("id")); err != nil {
failService(c, err)
return
}
ok(c, gin.H{"deleted": true})
})
pluginRoutes.GET("/eagle/library", func(c *gin.Context) {
if _, err := currentUser(c, svc); err != nil {
failService(c, err)
return
@@ -23,7 +96,7 @@ func RegisterPluginRoutes(r *gin.RouterGroup, svc *service.Service) {
library.LibraryPath = ""
ok(c, gin.H{"library": library})
})
r.GET("/plugins/eagle/items", func(c *gin.Context) {
pluginRoutes.GET("/eagle/items", func(c *gin.Context) {
if _, err := currentUser(c, svc); err != nil {
failService(c, err)
return
@@ -37,7 +110,7 @@ func RegisterPluginRoutes(r *gin.RouterGroup, svc *service.Service) {
}
ok(c, gin.H{"items": items})
})
r.GET("/plugins/eagle/items/:itemId/file", func(c *gin.Context) {
pluginRoutes.GET("/eagle/items/:itemId/file", func(c *gin.Context) {
if _, err := currentUser(c, svc); err != nil {
failService(c, err)
return
@@ -53,7 +126,7 @@ func RegisterPluginRoutes(r *gin.RouterGroup, svc *service.Service) {
c.Header("Content-Disposition", "attachment; filename=\""+file.Name+"\"")
c.DataFromReader(http.StatusOK, file.Size, file.MimeType, file.Body, nil)
})
r.GET("/plugins/eagle/items/:itemId/thumbnail", func(c *gin.Context) {
pluginRoutes.GET("/eagle/items/:itemId/thumbnail", func(c *gin.Context) {
if _, err := currentUser(c, svc); err != nil {
failService(c, err)
return
@@ -68,7 +141,7 @@ func RegisterPluginRoutes(r *gin.RouterGroup, svc *service.Service) {
c.Header("X-Content-Type-Options", "nosniff")
c.DataFromReader(http.StatusOK, file.Size, file.MimeType, file.Body, nil)
})
r.POST("/plugins/eagle/items", func(c *gin.Context) {
pluginRoutes.POST("/eagle/items", func(c *gin.Context) {
if _, err := currentUser(c, svc); err != nil {
failService(c, err)
return
@@ -86,7 +159,7 @@ func RegisterPluginRoutes(r *gin.RouterGroup, svc *service.Service) {
}
ok(c, gin.H{"item": item})
})
r.POST("/plugins/eagle/folders", func(c *gin.Context) {
pluginRoutes.POST("/eagle/folders", func(c *gin.Context) {
if _, err := currentUser(c, svc); err != nil {
failService(c, err)
return
@@ -107,3 +180,44 @@ func RegisterPluginRoutes(r *gin.RouterGroup, svc *service.Service) {
ok(c, gin.H{"created": true})
})
}
func requirePluginCenterAccess(svc *service.Service) gin.HandlerFunc {
return func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
c.Abort()
return
}
if user.Role == model.UserRoleAdmin {
c.Next()
return
}
if err := svc.RequireFeature(service.FeaturePluginCenter); err != nil {
failService(c, err)
c.Abort()
return
}
c.Next()
}
}
func pluginToggle(svc *service.Service, enabled bool) gin.HandlerFunc {
return func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
return
}
if err := svc.RequireAdmin(user); err != nil {
failService(c, err)
return
}
plugin, err := svc.SetPluginEnabled(c.Param("id"), enabled)
if err != nil {
failService(c, err)
return
}
ok(c, gin.H{"plugin": plugin})
}
}

View File

@@ -0,0 +1,35 @@
package handler
import (
"strings"
"infinite-canvas/backend/internal/service"
"github.com/gin-gonic/gin"
)
func RegisterProtocolRoutes(r *gin.RouterGroup, svc *service.Service) {
r.GET("/protocols", func(c *gin.Context) {
if _, err := currentUser(c, svc); err != nil {
failService(c, err)
return
}
scope := strings.TrimSpace(c.DefaultQuery("scope", "user.custom-channel"))
capability := strings.TrimSpace(c.Query("capability"))
ok(c, gin.H{"protocols": svc.ProtocolCatalog(scope, capability, false)})
})
r.GET("/admin/protocols", func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
return
}
if err := svc.RequireAdmin(user); err != nil {
failService(c, err)
return
}
includeUnavailable := c.Query("includeUnavailable") == "1"
capability := strings.TrimSpace(c.Query("capability"))
ok(c, gin.H{"protocols": svc.ProtocolCatalog("admin.system-channel", capability, includeUnavailable)})
})
}

View File

@@ -36,7 +36,7 @@ var (
systemMiniMaxTaskPath = regexp.MustCompile(`^/v2/query/video_generation/[^/]+$`)
openAIPostEndpoints = map[string]bool{
"/responses": true, "/chat/completions": true, "/images/generations": true, "/images/edits": true,
"/audio/speech": true,
"/audio/speech": true, "/messages": true,
}
)
@@ -61,7 +61,7 @@ func authorizeCustomRelay(method string, target *url.URL, apiFormat string, cont
}
apiFormat = strings.ToLower(strings.TrimSpace(apiFormat))
if apiFormat != "openai" && apiFormat != "gemini" {
if apiFormat != "openai" && apiFormat != "gemini" && apiFormat != "claude" {
return errors.New("自定义渠道调用格式无效")
}
if method == http.MethodGet {
@@ -74,7 +74,7 @@ func authorizeCustomRelay(method string, target *url.URL, apiFormat string, cont
allowed := requestPath == "/models" || strings.HasSuffix(requestPath, "/models")
if apiFormat == "openai" {
allowed = allowed || customVideoTaskPath.MatchString(requestPath) || customXAIVideoTaskPath.MatchString(requestPath) || customVideoContentPath.MatchString(requestPath) || customArkVideoTaskPath.MatchString(requestPath) || customMiniMaxTaskPath.MatchString(requestPath)
} else {
} else if apiFormat == "gemini" {
allowed = allowed || customGeminiOperationPath.MatchString(requestPath)
}
if len(query) != 0 || !allowed {
@@ -97,6 +97,12 @@ func authorizeCustomRelay(method string, target *url.URL, apiFormat string, cont
}
return nil
}
if apiFormat == "claude" {
if mediaType != "application/json" || !strings.HasSuffix(requestPath, "/messages") {
return errors.New("Claude 自定义渠道只允许 application/json 的 /messages 请求")
}
return nil
}
if mediaType != "application/json" {
return errors.New("Gemini 自定义渠道生成请求必须使用 application/json")
}
@@ -209,6 +215,8 @@ func interfaceAllowsProxyPath(interfaceType model.ChannelInterfaceType, requestP
return requestPath == "/chat/completions"
case model.ChannelInterfaceOpenAIResponse:
return requestPath == "/responses"
case model.ChannelInterfaceClaudeAPI:
return requestPath == "/messages"
case model.ChannelInterfaceOpenAIImage, model.ChannelInterfaceGrokImage:
return requestPath == "/images/generations" || requestPath == "/images/edits"
case model.ChannelInterfaceVolcengineArkImage:

View File

@@ -36,6 +36,7 @@ func TestAuthorizeCustomRelayAllowsModelsAndAgentEndpoints(t *testing.T) {
{method: http.MethodGet, target: "https://api.example.com/v1/models", apiFormat: "openai"},
{method: http.MethodPost, target: "https://api.example.com/v1/responses", apiFormat: "openai", contentType: "application/json"},
{method: http.MethodPost, target: "https://api.example.com/v1/chat/completions", apiFormat: "openai", contentType: "application/json; charset=utf-8"},
{method: http.MethodPost, target: "https://api.anthropic.com/v1/messages", apiFormat: "claude", contentType: "application/json"},
{method: http.MethodPost, target: "https://api.example.com/v1/audio/speech", apiFormat: "openai", contentType: "application/json"},
{method: http.MethodPost, target: "https://api.example.com/v1/images/edits", apiFormat: "openai", contentType: "multipart/form-data; boundary=test"},
{method: http.MethodPost, target: "https://api.example.com/v1/images/edits", apiFormat: "openai", contentType: "application/json"},
@@ -77,6 +78,8 @@ func TestAuthorizeCustomRelayRejectsArbitraryRequestsAndCredentialQueries(t *tes
{method: http.MethodGet, target: "https://api.example.com/account", apiFormat: "openai"},
{method: http.MethodGet, target: "https://api.example.com/v1/models?api_key=secret", apiFormat: "openai"},
{method: http.MethodPost, target: "https://api.example.com/v1/responses", apiFormat: "openai", contentType: "text/plain"},
{method: http.MethodPost, target: "https://api.anthropic.com/v1/messages", apiFormat: "claude", contentType: "text/plain"},
{method: http.MethodGet, target: "https://api.anthropic.com/v1/messages", apiFormat: "claude"},
{method: http.MethodPost, target: "https://api.example.com/v1/account", apiFormat: "openai", contentType: "multipart/form-data; boundary=test"},
{method: http.MethodPost, target: "https://api.example.com/v1/../account/chat/completions", apiFormat: "openai", contentType: "application/json"},
{method: http.MethodPost, target: "https://api.example.com/v1/models/gemini:streamGenerateContent?alt=sse&token=secret", apiFormat: "gemini", contentType: "application/json"},

View File

@@ -0,0 +1,25 @@
package handler
import "testing"
func TestShortSystemProxyPath(t *testing.T) {
tests := []struct {
path string
channel string
provider string
ok bool
}{
{path: "/api/channel-1/chat/completions", channel: "channel-1", provider: "/chat/completions", ok: true},
{path: "/api/channel-1/v1/models", channel: "channel-1", provider: "/v1/models", ok: true},
{path: "/api/tasks/123", ok: false},
{path: "/api/channel-1", ok: false},
{path: "/api//chat/completions", ok: false},
{path: "/other/channel-1/chat/completions", ok: false},
}
for _, test := range tests {
channel, provider, ok := shortSystemProxyPath(test.path)
if ok != test.ok || channel != test.channel || provider != test.provider {
t.Errorf("shortSystemProxyPath(%q) = (%q, %q, %v), want (%q, %q, %v)", test.path, channel, provider, ok, test.channel, test.provider, test.ok)
}
}
}