Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:recycle: Migrate plugin private service contracts https://github.com/siyuan-note/siyuan/issues/19378

Danield5e7530c7e24
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 48620e972a..734b32640d 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -2011,7 +2011,6 @@ export type APILegacyGETPath =
"/api/system/getCaptcha" |
"/api/system/oidc/callback" |
"/es/broadcast/subscribe" |
- "/plugin/private/:name/*path" |
"/ws/broadcast";
export interface APIGETRoutes {
@@ -2071,6 +2070,13 @@ export interface APIGETRoutes {
output: "proxy";
proxy: {"kind":"eventSource","contentType":"text/event-stream","upstreamStatuses":true};
};
+ "/plugin/private/:name/*path": {
+ request: Blob;
+ response: Blob | JSONValue | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "raw";
+ output: "pluginService";
+ pluginService: {"variants":[{"mode":"JSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"JSONP","statusPolicy":"plugin","mediaTypes":["application/javascript","application/json"],"payload":"jsonp-or-json","headersOverrideMedia":true},{"mode":"AsciiJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"IndentedJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"PureJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"SecureJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"secure-json","headersOverrideMedia":true},{"mode":"XML","statusPolicy":"plugin","mediaTypes":["application/xml"],"payload":"xml","headersOverrideMedia":true},{"mode":"YAML","statusPolicy":"plugin","mediaTypes":["application/yaml"],"payload":"yaml","headersOverrideMedia":true},{"mode":"TOML","statusPolicy":"plugin","mediaTypes":["application/toml"],"payload":"toml","headersOverrideMedia":true},{"mode":"ProtoBuf","statusPolicy":"plugin","mediaTypes":["application/x-protobuf"],"payload":"protobuf","headersOverrideMedia":true},{"mode":"file","statusPolicy":"file","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"string","statusPolicy":"plugin","mediaTypes":["text/plain"],"payload":"text","headersOverrideMedia":true},{"mode":"raw","statusPolicy":"plugin","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"redirect","statusPolicy":"redirect","mediaTypes":["text/html"],"payload":"redirect","headersOverrideMedia":true},{"mode":"proxy","statusPolicy":"proxy","mediaTypes":["upstream"],"payload":"bytes","headersOverrideMedia":true},{"mode":"empty","statusPolicy":"plugin","mediaTypes":["optional"],"payload":"none","headersOverrideMedia":true},{"mode":"websocket","statusPolicy":"websocket","mediaTypes":["upgrade-or-text"],"payload":"frames","headersOverrideMedia":false},{"mode":"sse","statusPolicy":"sse","mediaTypes":["text/event-stream"],"payload":"events","headersOverrideMedia":false},{"mode":"admission","statusPolicy":"admission","mediaTypes":["text/plain"],"payload":"text","headersOverrideMedia":true}],"admissionStatuses":[400,404,500,503],"webSocketFrames":["text","binary","close","ping","pong"],"sseEventNames":"dynamic","sseData":"json-or-text","sseEvent":{"type":"object","properties":{"data":{"$ref":"#/$defs/JSONValue"},"event":{"type":"string"},"id":{"type":"string"},"retry":{"type":"integer"}},"required":["data"],"additionalProperties":false}};
+ };
"/ws/network/proxy": {
request: EmptyRequestInput;
response: Blob | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -2140,8 +2146,7 @@ export type APILegacyPOSTPath =
"/api/transactions/clearHistory" |
"/api/transactions/redo" |
"/api/transactions/undo" |
- "/api/transactions/undoState" |
- "/plugin/private/:name/*path";
+ "/api/transactions/undoState";
export interface APIPOSTRoutes {
"/api/account/checkActivationcode": {
@@ -4990,6 +4995,13 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "none";
};
+ "/plugin/private/:name/*path": {
+ request: Blob;
+ response: Blob | JSONValue | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "raw";
+ output: "pluginService";
+ pluginService: {"variants":[{"mode":"JSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"JSONP","statusPolicy":"plugin","mediaTypes":["application/javascript","application/json"],"payload":"jsonp-or-json","headersOverrideMedia":true},{"mode":"AsciiJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"IndentedJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"PureJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"SecureJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"secure-json","headersOverrideMedia":true},{"mode":"XML","statusPolicy":"plugin","mediaTypes":["application/xml"],"payload":"xml","headersOverrideMedia":true},{"mode":"YAML","statusPolicy":"plugin","mediaTypes":["application/yaml"],"payload":"yaml","headersOverrideMedia":true},{"mode":"TOML","statusPolicy":"plugin","mediaTypes":["application/toml"],"payload":"toml","headersOverrideMedia":true},{"mode":"ProtoBuf","statusPolicy":"plugin","mediaTypes":["application/x-protobuf"],"payload":"protobuf","headersOverrideMedia":true},{"mode":"file","statusPolicy":"file","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"string","statusPolicy":"plugin","mediaTypes":["text/plain"],"payload":"text","headersOverrideMedia":true},{"mode":"raw","statusPolicy":"plugin","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"redirect","statusPolicy":"redirect","mediaTypes":["text/html"],"payload":"redirect","headersOverrideMedia":true},{"mode":"proxy","statusPolicy":"proxy","mediaTypes":["upstream"],"payload":"bytes","headersOverrideMedia":true},{"mode":"empty","statusPolicy":"plugin","mediaTypes":["optional"],"payload":"none","headersOverrideMedia":true},{"mode":"websocket","statusPolicy":"websocket","mediaTypes":["upgrade-or-text"],"payload":"frames","headersOverrideMedia":false},{"mode":"sse","statusPolicy":"sse","mediaTypes":["text/event-stream"],"payload":"events","headersOverrideMedia":false},{"mode":"admission","statusPolicy":"admission","mediaTypes":["text/plain"],"payload":"text","headersOverrideMedia":true}],"admissionStatuses":[400,404,500,503],"webSocketFrames":["text","binary","close","ping","pong"],"sseEventNames":"dynamic","sseData":"json-or-text","sseEvent":{"type":"object","properties":{"data":{"$ref":"#/$defs/JSONValue"},"event":{"type":"string"},"id":{"type":"string"},"retry":{"type":"integer"}},"required":["data"],"additionalProperties":false}};
+ };
}
// 传输层合成的错误独立于业务错误;普通回调只接收消息处理后保留的非负错误码。
@@ -5038,7 +5050,7 @@ type APIPostEmptyResponse<C> = C extends {emptyResponseStatuses: infer S extends
? Exclude<S[number], 401 | 403 | 404> extends never ? never : "" : never;
type APIPostTail<C extends APIContract> = [
- cb?: (response: (C extends {output: "binary" | "proxy"} ? JSONValue : C extends {output: "directJSON"} ? APIDirectCallbackResponse<C["response"]> | (C extends {noContent: true} ? "" : never) : C extends {output: "sse"} ? string | APICallbackResponse<C["response"]> : APICallbackResponse<C["response"]>) | APIPostEmptyResponse<C>) => void,
+ cb?: (response: (C extends {output: "binary" | "proxy" | "pluginService"} ? JSONValue : C extends {output: "directJSON"} ? APIDirectCallbackResponse<C["response"]> | (C extends {noContent: true} ? "" : never) : C extends {output: "sse"} ? string | APICallbackResponse<C["response"]> : APICallbackResponse<C["response"]>) | APIPostEmptyResponse<C>) => void,
headers?: Record<string, string>,
failCallback?: (response: APIFetchFailure) => void,
signal?: AbortSignal,
@@ -5070,13 +5082,13 @@ export type FetchSyncPost<Legacy = APILegacyResponse> = <Path extends string>(
: Path extends APILegacyPOSTPath ? [data?: any, ...tail: APISyncTail]
: string extends Path ? [data?: any, ...tail: APISyncTail] : never
) => Promise<Path extends keyof APIPOSTRoutes
- ? APIPOSTRoutes[Path] extends {output: "binary" | "proxy"} ? JSONValue : APIPOSTRoutes[Path]["response"] | APITransportError
+ ? APIPOSTRoutes[Path] extends {output: "binary" | "proxy" | "pluginService"} ? JSONValue : APIPOSTRoutes[Path]["response"] | APITransportError
: Legacy>;
export type FetchGet<Legacy = APILegacyResponse | string> = <Path extends string>(
url: Path,
...args: Path extends keyof APIGETRoutes
- ? [cb: (response: APIGETRoutes[Path] extends {output: "binary" | "proxy"} ? JSONValue : APIGETRoutes[Path]["response"] | APIEmptyResponse<APIGETRoutes[Path]> | (APIGETRoutes[Path] extends {output: "websocket" | "sse"} ? string : never)) => void]
+ ? [cb: (response: APIGETRoutes[Path] extends {output: "binary" | "proxy" | "pluginService"} ? JSONValue : APIGETRoutes[Path]["response"] | APIEmptyResponse<APIGETRoutes[Path]> | (APIGETRoutes[Path] extends {output: "websocket" | "sse"} ? string : never)) => void]
: Path extends keyof APIPOSTRoutes ? never
: [cb: (response: Legacy) => void]
) => void;
diff --git a/app/tests/api-contract.types.ts b/app/tests/api-contract.types.ts
index a3fac5e5ca..9d5864d95f 100644
--- a/app/tests/api-contract.types.ts
+++ b/app/tests/api-contract.types.ts
@@ -473,3 +473,13 @@ fetchPost("/api/network/echo", {arbitrary: [1, true]}, response => {
});
const networkRawBody: APIPOSTRoutes["/api/network/proxy"]["request"] = new Blob(["raw"]);
void networkRawBody;
+
+const pluginServiceRawBody: APIPOSTRoutes["/plugin/private/:name/*path"]["request"] = new Blob(["plugin data"]);
+void pluginServiceRawBody;
+fetchPost("/plugin/private/:name/*path", {extension: [true, null, 1]}, response => {
+ const pluginPayload: JSONValue = response;
+ void pluginPayload;
+ // @ts-expect-error 插件服务载荷由插件决定,不能直接当作固定内核信封。
+ const code: number = response.code;
+ void code;
+});
diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.md
index 2c2cf839ab..37793c2dea 100644
--- a/docs/API-CONTRACTS.md
+++ b/docs/API-CONTRACTS.md
@@ -24,6 +24,8 @@ Encrypted notebook lifecycle endpoints use typed requests and responses while re
## Compatibility requirements
+Plugin private services declare their existing serialization modes, raw files, redirects, proxy responses, SSE events, and WebSocket frames. Plugin-defined payloads remain protocol extension data; branch-specific validation distinguishes serialized formats from arbitrary bytes. Request bodies, explicit response headers, admission failures, and cancellation retain the plugin service lifecycle.
+
Network contracts retain request bytes, multipart fields, headers, URL and TLS diagnostics, including complete certificate public-key structures and large integers. Forward proxy options preserve validation order, numeric truncation, response encodings, and protocol-defined JSON payloads. HTTP, EventSource, and WebSocket proxies retain upstream statuses and bytes, repeated-header behavior, security headers, stream cancellation, and connection cleanup. Echo wildcard paths bind their own adapter while sharing the same handler behavior.
Attribute-view contracts declare table, gallery, and kanban results separately and retain missing base fields, cell patches, and null values. Known patch fields retain their supplied presence without filling omitted fields with zero values. Current, history, and snapshot rendering use their corresponding request types; callers handle error payloads before updating views. Row sorting, publish admission, encrypted-notebook leases, and fast JSON rendering preserve their existing behavior. Shared frontend and plugin declarations reflect the fields actually present in each view and cell.
diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.md
index c0bbf91f2d..e18b02ed37 100644
--- a/docs/API-CONTRACTS.zh-CN.md
+++ b/docs/API-CONTRACTS.zh-CN.md
@@ -24,6 +24,8 @@
## 兼容要求
+插件私有服务声明现有序列化模式、原始文件、重定向、代理响应、SSE 事件和 WebSocket 帧。插件自行定义的载荷保留为协议扩展数据,并按实际分支分别校验序列化格式与任意字节。请求体、显式响应头、准入错误和取消处理保持插件服务原有生命周期。
+
网络契约保留请求字节、表单字段、请求头、URL 和 TLS 诊断信息,包括完整证书公钥结构与大整数。转发代理选项保留校验顺序、数字截断、响应编码及协议定义的 JSON 载荷。HTTP、EventSource 和 WebSocket 代理保留上游状态与字节、重复请求头行为、安全响应头、流取消和连接清理。回显通配路径绑定独立适配器,并共用相同业务处理。
数据库契约分别声明表格、画廊和看板结果,保留基础字段缺失、单元格局部修改及 null 值。已知修改字段保留传入状态,不以零值补齐未提供的字段。当前、历史和快照渲染使用对应请求类型,调用端先处理错误载荷再更新视图。行排序、发布准入、加密笔记本租约和快速 JSON 渲染保留既有行为。前端和插件的共享声明按视图及单元格实际提供的字段同步。
diff --git a/kernel/api/contract_plugin_service_test.go b/kernel/api/contract_plugin_service_test.go
new file mode 100644
index 0000000000..927df9e5d8
--- /dev/null
+++ b/kernel/api/contract_plugin_service_test.go
@@ -0,0 +1,41 @@
+package api
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+)
+
+func TestAPIContractPluginPrivateServiceAdmission(t *testing.T) {
+ bundle, err := apicontract.BuildBundle()
+ if err != nil {
+ t.Fatal(err)
+ }
+ engine := gin.New()
+ engine.Any("/plugin/private/:name/*path", pluginPrivateWebServer)
+ server := httptest.NewServer(engine)
+ defer server.Close()
+ for _, method := range []string{"GET", "POST", "HEAD", "PATCH", "DELETE", "OPTIONS", "PUT", "CONNECT", "TRACE"} {
+ request, _ := http.NewRequest(method, server.URL+"/plugin/private/contract-missing/value", strings.NewReader("raw non-JSON"))
+ response, err := http.DefaultClient.Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ payload, _ := io.ReadAll(response.Body)
+ response.Body.Close()
+ if response.StatusCode != 404 {
+ t.Fatalf("admission changed: %d %s", response.StatusCode, payload)
+ }
+ if err = bundle.ValidatePluginServiceResponse(method, "/plugin/private/:name/*path", apicontract.PluginServiceAdmission, response.StatusCode, response.Header.Get("Content-Type"), payload); err != nil {
+ t.Fatal(err)
+ }
+ if method != "HEAD" && string(payload) != "[plugin:contract-missing] not found" {
+ t.Fatalf("admission message changed: %s", payload)
+ }
+ }
+}
diff --git a/kernel/api/plugin.go b/kernel/api/plugin.go
index da6f388c08..add580f656 100644
--- a/kernel/api/plugin.go
+++ b/kernel/api/plugin.go
@@ -82,10 +82,4 @@ var pluginJsonRpcHttpByName = contractHandler(apicontract.PluginRPCHTTPByName, p
var pluginJsonRpcWebSocket = contractHandler(apicontract.PluginRPCWebSocket, plugin.OpenRPCWebSocket)
var pluginJsonRpcWebSocketByName = contractHandler(apicontract.PluginRPCWebSocketByName, plugin.OpenRPCWebSocket)
-// func pluginPublicWebServer(c *gin.Context) {
-// plugin.HandleHttpRequest(c, plugin.AccessScopePublic)
-// }
-
-func pluginPrivateWebServer(c *gin.Context) {
- plugin.HandleHttpRequest(c, plugin.AccessScopePrivate)
-}
+var pluginPrivateWebServer = contractHandler(apicontract.PluginPrivateService, plugin.PreparePrivateService)
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 39b911dd84..d513fc3932 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -42,6 +42,7 @@ type Definition struct {
WebSocket *WebSocketDefinition
SSE *SSEDefinition
Proxy *ProxyDefinition
+ PluginService *PluginServiceDefinition
ContentVariants []HTTPContentVariant
FastJSON bool
EmptyResponseStatuses []int
@@ -65,6 +66,7 @@ type ResponseOptions struct {
WebSocket *WebSocketDefinition
SSE *SSEDefinition
Proxy *ProxyDefinition
+ PluginService *PluginServiceDefinition
ContentVariants []HTTPContentVariant
FastJSON bool
EmptyResponseStatuses []int
@@ -122,7 +124,7 @@ func define[Request, Data any](name, path string, body BodyMode, response Respon
d := Definition{Name: name, Path: path, Methods: methods, Body: body,
Request: reflect.TypeFor[Request](), Data: reflect.TypeFor[Data](),
ErrorCodes: append([]int{-1}, response.AdditionalCodes...), ErrorText: response.Text, DataNonNullable: response.NonNullable, DataOnError: response.DataOnError,
- Output: response.Output, ErrorStatus: response.ErrorStatus, NoContent: response.NoContent, WebSocket: response.WebSocket, SSE: response.SSE, Proxy: response.Proxy,
+ Output: response.Output, ErrorStatus: response.ErrorStatus, NoContent: response.NoContent, WebSocket: response.WebSocket, SSE: response.SSE, Proxy: response.Proxy, PluginService: response.PluginService,
AdditionalErrorStatuses: append([]int(nil), response.AdditionalErrorStatuses...), ContentVariants: append([]HTTPContentVariant(nil), response.ContentVariants...), FastJSON: response.FastJSON,
EmptyResponseStatuses: append([]int(nil), response.EmptyResponseStatuses...)}
definitions = append(definitions, d)
@@ -942,3 +944,5 @@ var NetworkForwardProxy = define[NetworkForwardRequest, NetworkForwardData]("for
var NetworkHTTPProxy = define[EmptyRequest, ProxyFailure]("httpProxy", "/api/network/proxy", RawBody, ProxyOptions(HTTPProxy), "ANY")
var NetworkEventSourceProxy = define[EmptyRequest, ProxyFailure]("esProxy", "/es/network/proxy", NoBody, ProxyOptions(EventSourceProxy), "GET")
var NetworkWebSocketProxy = define[EmptyRequest, ProxyFailure]("wsProxy", "/ws/network/proxy", NoBody, ProxyOptions(WebSocketProxy), "GET")
+
+var PluginPrivateService = define[EmptyRequest, PluginServiceContent]("pluginPrivateWebServer", "/plugin/private/:name/*path", RawBody, PluginServiceOptions(), "ANY")
diff --git a/kernel/apicontract/legacy_routes.json b/kernel/apicontract/legacy_routes.json
index 46499fd179..8c02d01e03 100644
--- a/kernel/apicontract/legacy_routes.json
+++ b/kernel/apicontract/legacy_routes.json
@@ -1,5 +1,4 @@
[
- {"method":"ANY","path":"/plugin/private/:name/*path","handler":"pluginPrivateWebServer"},
{"method":"GET","path":"/api/icon/getDynamicIcon","handler":"getDynamicIcon"},
{"method":"GET","path":"/api/system/bootProgressSSE","handler":"bootProgressSSE"},
{"method":"GET","path":"/api/system/getBootAppearance","handler":"getBootAppearance"},
diff --git a/kernel/apicontract/plugin_service_protocol.go b/kernel/apicontract/plugin_service_protocol.go
new file mode 100644
index 0000000000..974c5761f8
--- /dev/null
+++ b/kernel/apicontract/plugin_service_protocol.go
@@ -0,0 +1,290 @@
+package apicontract
+
+import (
+ "encoding/json"
+ "encoding/xml"
+ "fmt"
+ "io"
+ "net/http"
+ "reflect"
+ "strings"
+
+ "github.com/pelletier/go-toml/v2"
+ "google.golang.org/protobuf/encoding/protowire"
+ "gopkg.in/yaml.v3"
+)
+
+const PluginServiceOutput OutputMode = "pluginService"
+
+type PluginServiceMode string
+
+const (
+ PluginServiceJSON PluginServiceMode = "JSON"
+ PluginServiceJSONP PluginServiceMode = "JSONP"
+ PluginServiceASCIIJSON PluginServiceMode = "AsciiJSON"
+ PluginServiceIndentedJSON PluginServiceMode = "IndentedJSON"
+ PluginServicePureJSON PluginServiceMode = "PureJSON"
+ PluginServiceSecureJSON PluginServiceMode = "SecureJSON"
+ PluginServiceXML PluginServiceMode = "XML"
+ PluginServiceYAML PluginServiceMode = "YAML"
+ PluginServiceTOML PluginServiceMode = "TOML"
+ PluginServiceProtoBuf PluginServiceMode = "ProtoBuf"
+ PluginServiceFile PluginServiceMode = "file"
+ PluginServiceString PluginServiceMode = "string"
+ PluginServiceRaw PluginServiceMode = "raw"
+ PluginServiceRedirect PluginServiceMode = "redirect"
+ PluginServiceProxy PluginServiceMode = "proxy"
+ PluginServiceEmpty PluginServiceMode = "empty"
+ PluginServiceWebSocket PluginServiceMode = "websocket"
+ PluginServiceSSE PluginServiceMode = "sse"
+ PluginServiceAdmission PluginServiceMode = "admission"
+)
+
+type PluginServiceVariant struct {
+ Mode PluginServiceMode `json:"mode"`
+ StatusPolicy string `json:"statusPolicy"`
+ MediaTypes []string `json:"mediaTypes"`
+ Payload string `json:"payload"`
+ HeadersOverrideMedia bool `json:"headersOverrideMedia"`
+}
+type PluginServiceDefinition struct {
+ Variants []PluginServiceVariant `json:"variants"`
+ AdmissionStatuses []int `json:"admissionStatuses"`
+ WebSocketFrames []string `json:"webSocketFrames"`
+ SSEEventNames string `json:"sseEventNames"`
+ SSEData string `json:"sseData"`
+ SSEEvent *Schema `json:"sseEvent"`
+}
+
+// PluginServiceContent 标记扩展服务载荷,具体模式由有限构造器写入响应的私有元数据。
+type PluginServiceContent struct{}
+
+func PluginServiceOptions() ResponseOptions {
+ variants := []PluginServiceVariant{
+ {PluginServiceJSON, "plugin", []string{"application/json"}, "json", true},
+ {PluginServiceJSONP, "plugin", []string{"application/javascript", "application/json"}, "jsonp-or-json", true},
+ {PluginServiceASCIIJSON, "plugin", []string{"application/json"}, "json", true},
+ {PluginServiceIndentedJSON, "plugin", []string{"application/json"}, "json", true},
+ {PluginServicePureJSON, "plugin", []string{"application/json"}, "json", true},
+ {PluginServiceSecureJSON, "plugin", []string{"application/json"}, "secure-json", true},
+ {PluginServiceXML, "plugin", []string{"application/xml"}, "xml", true},
+ {PluginServiceYAML, "plugin", []string{"application/yaml"}, "yaml", true},
+ {PluginServiceTOML, "plugin", []string{"application/toml"}, "toml", true},
+ {PluginServiceProtoBuf, "plugin", []string{"application/x-protobuf"}, "protobuf", true},
+ {PluginServiceFile, "file", []string{"dynamic"}, "bytes", true},
+ {PluginServiceString, "plugin", []string{"text/plain"}, "text", true},
+ {PluginServiceRaw, "plugin", []string{"dynamic"}, "bytes", true},
+ {PluginServiceRedirect, "redirect", []string{"text/html"}, "redirect", true},
+ {PluginServiceProxy, "proxy", []string{"upstream"}, "bytes", true},
+ {PluginServiceEmpty, "plugin", []string{"optional"}, "none", true},
+ {PluginServiceWebSocket, "websocket", []string{"upgrade-or-text"}, "frames", false},
+ {PluginServiceSSE, "sse", []string{"text/event-stream"}, "events", false},
+ {PluginServiceAdmission, "admission", []string{"text/plain"}, "text", true},
+ }
+ event := object(map[string]*Schema{"event": {Type: "string"}, "id": {Type: "string"}, "retry": {Type: "integer"}, "data": {Ref: "#/$defs/JSONValue"}}, "data")
+ return ResponseOptions{Output: PluginServiceOutput, PluginService: &PluginServiceDefinition{Variants: variants, AdmissionStatuses: []int{400, 404, 500, 503}, WebSocketFrames: []string{"text", "binary", "close", "ping", "pong"}, SSEEventNames: "dynamic", SSEData: "json-or-text", SSEEvent: event}}
+}
+
+func StreamPluginService(mode PluginServiceMode, status int, serve func(http.ResponseWriter, *http.Request)) Response[PluginServiceContent] {
+ if serve == nil {
+ panic("plugin service requires a lifecycle")
+ }
+ if status <= 0 {
+ status = 200
+ }
+ if err := validatePluginServiceStatus(mode, status); err != nil {
+ panic(err)
+ }
+ return Response[PluginServiceContent]{pluginServiceMode: mode, httpStatus: status, stream: serve}
+}
+
+func (e Endpoint[Request, Data]) pluginServiceStatus(response Response[Data]) int {
+ if e.definition.Output != PluginServiceOutput || e.definition.PluginService == nil {
+ panic("endpoint does not declare plugin service output")
+ }
+ if response.stream == nil {
+ if response.code == 0 {
+ panic("plugin service requires a selected response mode")
+ }
+ return 200
+ }
+ if err := validatePluginServiceStatus(response.pluginServiceMode, response.httpStatus); err != nil {
+ panic(err)
+ }
+ return response.httpStatus
+}
+
+func validatePluginServiceDefinition(definition Definition) error {
+ if (definition.Output == PluginServiceOutput) != (definition.PluginService != nil) {
+ return fmt.Errorf("plugin service output requires a protocol declaration")
+ }
+ if definition.PluginService == nil {
+ return nil
+ }
+ if definition.Data != reflect.TypeFor[PluginServiceContent]() || definition.SSE != nil || definition.Proxy != nil || definition.WebSocket != nil || definition.DataOnError || definition.ErrorStatus != 0 {
+ return fmt.Errorf("invalid plugin service response options")
+ }
+ if !reflect.DeepEqual(definition.PluginService, PluginServiceOptions().PluginService) {
+ return fmt.Errorf("invalid plugin service protocol variants")
+ }
+ return nil
+}
+
+func validatePluginServiceStatus(mode PluginServiceMode, status int) error {
+ if status < 100 || status > 999 {
+ return fmt.Errorf("invalid plugin service HTTP status: %d", status)
+ }
+ known := false
+ for _, variant := range PluginServiceOptions().PluginService.Variants {
+ if variant.Mode == mode {
+ known = true
+ break
+ }
+ }
+ if !known {
+ return fmt.Errorf("unknown plugin service mode: %s", mode)
+ }
+ switch mode {
+ case PluginServiceAdmission:
+ if status != 400 && status != 404 && status != 500 && status != 503 {
+ return fmt.Errorf("undeclared plugin admission status")
+ }
+ case PluginServiceRedirect:
+ if status != 201 && (status < 300 || status > 308) {
+ return fmt.Errorf("invalid plugin redirect status")
+ }
+ case PluginServiceWebSocket:
+ if status != 101 && status != 400 && status != 500 {
+ return fmt.Errorf("invalid plugin WebSocket status")
+ }
+ case PluginServiceSSE:
+ if status != 200 && status != 500 {
+ return fmt.Errorf("invalid plugin SSE status")
+ }
+ }
+ return nil
+}
+
+func (b *Bundle) validatePluginServiceHTTPResponse(endpoint EndpointSchema, status int, contentType string, payload []byte) error {
+ if status < 100 || status > 999 {
+ return fmt.Errorf("invalid plugin service HTTP status")
+ }
+ if endpoint.Method == "HEAD" || status < 200 || status == 204 || status == 304 {
+ if len(payload) > 0 {
+ return fmt.Errorf("plugin service response forbids a body")
+ }
+ return nil
+ }
+ // 原始文件、代理及插件自选媒体允许任意字节,具体分支由 ValidatePluginServiceResponse 校验。
+ return nil
+}
+
+func (b *Bundle) ValidatePluginServiceResponse(method, path string, mode PluginServiceMode, status int, contentType string, payload []byte) error {
+ var found bool
+ for _, endpoint := range b.Endpoints {
+ if endpoint.Method == method && endpoint.Path == path && endpoint.PluginService != nil {
+ found = true
+ break
+ }
+ }
+ if !found {
+ return fmt.Errorf("unregistered plugin service: %s %s", method, path)
+ }
+ if err := validatePluginServiceStatus(mode, status); err != nil {
+ return err
+ }
+ if method == "HEAD" || status < 200 || status == 204 || status == 304 {
+ if len(payload) != 0 {
+ return fmt.Errorf("plugin service response forbids a body")
+ }
+ return nil
+ }
+ switch mode {
+ case PluginServiceEmpty:
+ if len(payload) != 0 {
+ return fmt.Errorf("empty plugin response contains a body")
+ }
+ case PluginServiceJSON, PluginServiceASCIIJSON, PluginServiceIndentedJSON, PluginServicePureJSON:
+ if !json.Valid(payload) {
+ return fmt.Errorf("invalid plugin JSON response")
+ }
+ case PluginServiceJSONP:
+ valid := json.Valid(payload)
+ if tail, ok := strings.CutSuffix(string(payload), ");"); ok {
+ for index, char := range tail {
+ if char == '(' && json.Valid([]byte(tail[index+1:])) {
+ valid = true
+ break
+ }
+ }
+ }
+ if !valid {
+ return fmt.Errorf("invalid plugin JSONP response")
+ }
+ case PluginServiceSecureJSON:
+ if !json.Valid(payload) && !json.Valid([]byte(strings.TrimPrefix(string(payload), "while(1);"))) {
+ return fmt.Errorf("invalid plugin secure JSON response")
+ }
+ case PluginServiceWebSocket:
+ if status == 101 && len(payload) != 0 {
+ return fmt.Errorf("WebSocket handshake contains a body")
+ }
+ case PluginServiceXML:
+ decoder := xml.NewDecoder(strings.NewReader(string(payload)))
+ for {
+ if _, err := decoder.Token(); err != nil {
+ if err == io.EOF {
+ break
+ }
+ return err
+ }
+ }
+ case PluginServiceYAML:
+ var value yaml.Node
+ if err := yaml.Unmarshal(payload, &value); err != nil {
+ return err
+ }
+ case PluginServiceTOML:
+ var value map[string]any
+ if err := toml.Unmarshal(payload, &value); err != nil {
+ return err
+ }
+ case PluginServiceProtoBuf:
+ for len(payload) > 0 {
+ _, _, size := protowire.ConsumeField(payload)
+ if size < 0 {
+ return protowire.ParseError(size)
+ }
+ payload = payload[size:]
+ }
+ }
+ return nil
+}
+
+func (b *Bundle) ValidatePluginServiceFrame(method, path string, frameType int, payload []byte) error {
+ for _, endpoint := range b.Endpoints {
+ if endpoint.Method == method && endpoint.Path == path && endpoint.PluginService != nil {
+ if frameType != 1 && frameType != 2 && frameType != 8 && frameType != 9 && frameType != 10 {
+ return fmt.Errorf("undeclared plugin WebSocket frame: %d", frameType)
+ }
+ if frameType >= 8 && len(payload) > 125 {
+ return fmt.Errorf("plugin WebSocket control frame exceeds 125 bytes")
+ }
+ return nil
+ }
+ }
+ return fmt.Errorf("unregistered plugin service: %s %s", method, path)
+}
+
+func (b *Bundle) ValidatePluginServiceEvent(method, path string, payload []byte) error {
+ for _, endpoint := range b.Endpoints {
+ if endpoint.Method == method && endpoint.Path == path && endpoint.PluginService != nil {
+ var event any
+ if err := json.Unmarshal(payload, &event); err != nil {
+ return err
+ }
+ return b.validate(endpoint.PluginService.SSEEvent, event, "$")
+ }
+ }
+ return fmt.Errorf("unregistered plugin service: %s %s", method, path)
+}
diff --git a/kernel/apicontract/plugin_service_protocol_test.go b/kernel/apicontract/plugin_service_protocol_test.go
new file mode 100644
index 0000000000..93d78d4f6d
--- /dev/null
+++ b/kernel/apicontract/plugin_service_protocol_test.go
@@ -0,0 +1,106 @@
+package apicontract
+
+import (
+ "net/http"
+ "testing"
+)
+
+func TestPluginServiceProtocolVariants(t *testing.T) {
+ previous := definitions
+ t.Cleanup(func() { definitions = previous })
+ endpoint := define[EmptyRequest, PluginServiceContent]("pluginServiceTest", "/test/plugin/:name/*path", RawBody, PluginServiceOptions(), "ANY")
+ bundle, err := BuildBundle()
+ if err != nil {
+ t.Fatal(err)
+ }
+ seen := map[PluginServiceMode]bool{}
+ for _, variant := range endpoint.Definition().PluginService.Variants {
+ if seen[variant.Mode] {
+ t.Fatal("duplicate service mode")
+ }
+ seen[variant.Mode] = true
+ if variant.StatusPolicy == "" || len(variant.MediaTypes) == 0 || variant.Payload == "" {
+ t.Fatalf("incomplete mode declaration: %+v", variant)
+ }
+ }
+ if len(seen) != 19 {
+ t.Fatal("service modes missing")
+ }
+ for _, tt := range []struct {
+ mode PluginServiceMode
+ status int
+ body string
+ valid bool
+ }{
+ {PluginServiceJSON, 200, `{"extension":[true,null,1]}`, true},
+ {PluginServiceJSON, 700, `null`, true},
+ {PluginServiceJSON, 200, `invalid`, false},
+ {PluginServiceJSONP, 200, `callback({"a":1});`, true},
+ {PluginServiceJSONP, 200, `callback(invalid);`, false},
+ {PluginServiceXML, 200, `<value>x</value>`, true},
+ {PluginServiceXML, 200, `<value>`, false},
+ {PluginServiceYAML, 200, `key: [1, true]`, true},
+ {PluginServiceYAML, 200, `key: [`, false},
+ {PluginServiceTOML, 200, `key = "value"`, true},
+ {PluginServiceTOML, 200, `key = [`, false},
+ {PluginServiceProtoBuf, 200, "\n\x01x", true},
+ {PluginServiceProtoBuf, 200, "\xff", false},
+ {PluginServiceASCIIJSON, 200, `"\u0041"`, true},
+ {PluginServiceIndentedJSON, 200, "{\n\"a\":1\n}", true},
+ {PluginServicePureJSON, 200, "[1]\n", true},
+ {PluginServiceSecureJSON, 200, "while(1);[1]", true},
+ {PluginServiceSecureJSON, 200, "while(1);invalid", false},
+ {PluginServiceRaw, 999, "\x00\xff", true},
+ {PluginServiceProxy, 404, "upstream error", true},
+ {PluginServiceEmpty, 200, "", true},
+ {PluginServiceEmpty, 200, "unexpected", false},
+ {PluginServiceRaw, 204, "unexpected", false},
+ {PluginServiceAdmission, 404, "not found", true},
+ {PluginServiceAdmission, 502, "invalid admission", false},
+ {PluginServiceRedirect, 302, "redirect", true},
+ {PluginServiceRedirect, 200, "redirect", false},
+ {PluginServiceWebSocket, 101, "", true},
+ {PluginServiceWebSocket, 400, "upgrade failed", true},
+ {PluginServiceWebSocket, 200, "", false},
+ {PluginServiceSSE, 200, "event: custom\ndata: plain text\n\n", true},
+ {PluginServiceMode("unknown"), 200, "", false},
+ } {
+ err := bundle.ValidatePluginServiceResponse("GET", "/test/plugin/:name/*path", tt.mode, tt.status, "application/custom", []byte(tt.body))
+ if (err == nil) != tt.valid {
+ t.Errorf("%+v: %v", tt, err)
+ }
+ }
+ stream := StreamPluginService(PluginServiceRaw, 0, func(http.ResponseWriter, *http.Request) {})
+ if endpoint.Status(stream) != 200 || stream.Stream() == nil {
+ t.Fatal("default plugin status changed")
+ }
+ if _, err := stream.MarshalJSON(); err == nil {
+ t.Fatal("service stream serialized as envelope")
+ }
+ definition := endpoint.Definition()
+ definition.PluginService = &PluginServiceDefinition{}
+ if err := validatePluginServiceDefinition(definition); err == nil {
+ t.Fatal("incomplete service protocol accepted")
+ }
+ if err := bundle.ValidatePluginServiceResponse("HEAD", "/test/plugin/:name/*path", PluginServiceRaw, 200, "", []byte("body")); err == nil {
+ t.Fatal("HEAD body accepted")
+ }
+ for _, frame := range []int{1, 2, 8, 9, 10} {
+ if err := bundle.ValidatePluginServiceFrame("GET", "/test/plugin/:name/*path", frame, []byte("data")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := bundle.ValidatePluginServiceFrame("GET", "/test/plugin/:name/*path", 3, nil); err == nil {
+ t.Fatal("unknown frame accepted")
+ }
+ for _, event := range []string{`{"data":null}`, `{"event":"custom","id":"1","retry":100,"data":{"extension":[1,true]}}`} {
+ if err := bundle.ValidatePluginServiceEvent("GET", "/test/plugin/:name/*path", []byte(event)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, event := range []string{`{}`, `{"event":1,"data":null}`, `{"retry":"1","data":false}`} {
+ if err := bundle.ValidatePluginServiceEvent("GET", "/test/plugin/:name/*path", []byte(event)); err == nil {
+ t.Fatalf("invalid event accepted: %s", event)
+ }
+ }
+}
diff --git a/kernel/apicontract/response.go b/kernel/apicontract/response.go
index 68afe7d317..8ce3e1f253 100644
--- a/kernel/apicontract/response.go
+++ b/kernel/apicontract/response.go
@@ -33,6 +33,9 @@ func SuccessNoContent[Data any]() Response[Data] {
// Status 只为显式声明的非 JSON 协议使用独立错误状态。
func (e Endpoint[Request, Data]) Status(r Response[Data]) int {
+ if e.definition.Output == PluginServiceOutput {
+ return e.pluginServiceStatus(r)
+ }
if e.definition.Proxy != nil {
return e.proxyStatus(r)
}
@@ -139,20 +142,21 @@ func (Null) MarshalJSON() ([]byte, error) { return []byte("null"), nil }
// Response 的载荷仅能通过有类型的成功构造函数或明确的错误构造函数设置。
type Response[Data any] struct {
- code int
- msg string
- data any
- binary *BinaryContent
- queryLimit *SQLQueryLimit
- directJSON bool
- noContent bool
- upgrade func(http.ResponseWriter, *http.Request)
- stream func(http.ResponseWriter, *http.Request)
- websocketFailure bool
- httpStatus int
- afterWrite func()
- emptyStatus int
- redirect *HTTPRedirect
+ pluginServiceMode PluginServiceMode
+ code int
+ msg string
+ data any
+ binary *BinaryContent
+ queryLimit *SQLQueryLimit
+ directJSON bool
+ noContent bool
+ upgrade func(http.ResponseWriter, *http.Request)
+ stream func(http.ResponseWriter, *http.Request)
+ websocketFailure bool
+ httpStatus int
+ afterWrite func()
+ emptyStatus int
+ redirect *HTTPRedirect
}
// WithAfterWrite 将通知保留到响应写入完成后执行。
diff --git a/kernel/apicontract/schema.go b/kernel/apicontract/schema.go
index 94959599b5..830719ae44 100644
--- a/kernel/apicontract/schema.go
+++ b/kernel/apicontract/schema.go
@@ -27,21 +27,22 @@ type Schema struct {
}
type EndpointSchema struct {
- Method string `json:"method"`
- Path string `json:"path"`
- Handler string `json:"handler"`
- Body BodyMode `json:"body"`
- Request *Schema `json:"request"`
- Response *Schema `json:"response"`
- Output OutputMode `json:"output,omitempty"`
- ErrorStatus int `json:"errorStatus,omitempty"`
- NoContent bool `json:"noContent,omitempty"`
- WebSocket *WebSocketSchema `json:"websocket,omitempty"`
- SSE *SSESchema `json:"sse,omitempty"`
- Proxy *ProxyDefinition `json:"proxy,omitempty"`
- ContentVariants []HTTPContentVariant `json:"contentVariants,omitempty"`
- EmptyResponseStatuses []int `json:"emptyResponseStatuses,omitempty"`
- AdditionalErrorStatuses []int `json:"additionalErrorStatuses,omitempty"`
+ Method string `json:"method"`
+ Path string `json:"path"`
+ Handler string `json:"handler"`
+ Body BodyMode `json:"body"`
+ Request *Schema `json:"request"`
+ Response *Schema `json:"response"`
+ Output OutputMode `json:"output,omitempty"`
+ ErrorStatus int `json:"errorStatus,omitempty"`
+ NoContent bool `json:"noContent,omitempty"`
+ WebSocket *WebSocketSchema `json:"websocket,omitempty"`
+ SSE *SSESchema `json:"sse,omitempty"`
+ Proxy *ProxyDefinition `json:"proxy,omitempty"`
+ PluginService *PluginServiceDefinition `json:"pluginService,omitempty"`
+ ContentVariants []HTTPContentVariant `json:"contentVariants,omitempty"`
+ EmptyResponseStatuses []int `json:"emptyResponseStatuses,omitempty"`
+ AdditionalErrorStatuses []int `json:"additionalErrorStatuses,omitempty"`
}
type WebSocketSchema struct {
@@ -90,6 +91,13 @@ func nonnullable(schema *Schema) *Schema {
}
func (b *schemaBuilder) schema(t reflect.Type, input bool) (*Schema, error) {
+ if t == reflect.TypeFor[PluginServiceContent]() {
+ value, err := b.schema(reflect.TypeFor[JSONValue](), false)
+ if err != nil {
+ return nil, err
+ }
+ return &Schema{AnyOf: []*Schema{{Type: "string", Format: "binary"}, value}}, nil
+ }
if t == reflect.TypeFor[*NetworkEchoTLS]() || t == reflect.TypeFor[*NetworkEchoURL]() || t == reflect.TypeFor[*NetworkEchoCookies]() {
schema, err := networkEchoSchema(b, t.Elem())
if err != nil {
@@ -530,6 +538,9 @@ func BuildBundle() (*Bundle, error) {
b := &schemaBuilder{definitions: map[string]*Schema{}, owners: map[string]reflect.Type{}}
bundle := &Bundle{Dialect: "https://json-schema.org/draft/2020-12/schema", Definitions: b.definitions}
for _, definition := range Definitions() {
+ if err := validatePluginServiceDefinition(definition); err != nil {
+ return nil, err
+ }
if err := validateProxyDefinition(definition); err != nil {
return nil, err
}
@@ -549,7 +560,7 @@ func BuildBundle() (*Bundle, error) {
return nil, fmt.Errorf("invalid JSON error status: %s", definition.Name)
}
}
- if definition.Output != "" && definition.Output != BinaryOutput && definition.Output != DirectJSONOutput && definition.Output != WebSocketOutput && definition.Output != SSEOutput && definition.Output != ProxyOutput {
+ if definition.Output != "" && definition.Output != BinaryOutput && definition.Output != DirectJSONOutput && definition.Output != WebSocketOutput && definition.Output != SSEOutput && definition.Output != ProxyOutput && definition.Output != PluginServiceOutput {
return nil, fmt.Errorf("unsupported response output: %s", definition.Name)
}
if definition.NoContent && definition.Output != DirectJSONOutput {
@@ -639,7 +650,7 @@ func BuildBundle() (*Bundle, error) {
return nil, err
}
}
- if definition.Output == DirectJSONOutput || definition.Output == WebSocketOutput {
+ if definition.Output == DirectJSONOutput || definition.Output == WebSocketOutput || definition.Output == PluginServiceOutput {
success = data
}
if definition.Output == SSEOutput {
@@ -670,7 +681,7 @@ func BuildBundle() (*Bundle, error) {
for _, method := range ExpandMethods(definition.Methods) {
bundle.Endpoints = append(bundle.Endpoints, EndpointSchema{Method: method, Path: definition.Path, Handler: definition.Name,
Body: definition.Body, Request: request, Response: response, Output: definition.Output, ErrorStatus: definition.ErrorStatus, NoContent: definition.NoContent, WebSocket: websocket,
- AdditionalErrorStatuses: definition.AdditionalErrorStatuses, SSE: sse, Proxy: definition.Proxy, ContentVariants: definition.ContentVariants, EmptyResponseStatuses: definition.EmptyResponseStatuses})
+ AdditionalErrorStatuses: definition.AdditionalErrorStatuses, SSE: sse, Proxy: definition.Proxy, PluginService: definition.PluginService, ContentVariants: definition.ContentVariants, EmptyResponseStatuses: definition.EmptyResponseStatuses})
}
}
sort.Slice(bundle.Endpoints, func(i, j int) bool {
@@ -700,7 +711,7 @@ func (b *Bundle) ValidateResponse(method, path string, payload []byte) error {
}
for _, endpoint := range b.Endpoints {
if endpoint.Method == method && endpoint.Path == path {
- if endpoint.Output == BinaryOutput || endpoint.Output == WebSocketOutput || endpoint.Output == SSEOutput || endpoint.Output == ProxyOutput {
+ if endpoint.Output == BinaryOutput || endpoint.Output == WebSocketOutput || endpoint.Output == SSEOutput || endpoint.Output == ProxyOutput || endpoint.Output == PluginServiceOutput {
return fmt.Errorf("binary endpoint requires HTTP response validation")
}
return b.validate(endpoint.Response, value, "$")
@@ -715,6 +726,9 @@ func (b *Bundle) ValidateHTTPResponse(method, path string, status int, contentTy
if endpoint.Method != method || endpoint.Path != path {
continue
}
+ if endpoint.PluginService != nil {
+ return b.validatePluginServiceHTTPResponse(endpoint, status, contentType, payload)
+ }
if endpoint.Proxy != nil {
return b.validateProxyHTTPResponse(endpoint, status, contentType, payload)
}
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 36b1a4b433..0c004e10fa 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -42724,6 +42724,283 @@
"upstreamStatuses": true
}
},
+ {
+ "method": "CONNECT",
+ "path": "/plugin/private/:name/*path",
+ "handler": "pluginPrivateWebServer",
+ "body": "raw",
+ "request": {
+ "type": "string",
+ "format": "binary"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "binary"
+ },
+ {
+ "$ref": "#/$defs/JSONValue"
+ }
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ },
+ "output": "pluginService",
+ "pluginService": {
+ "variants": [
+ {
+ "mode": "JSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "JSONP",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/javascript",
+ "application/json"
+ ],
+ "payload": "jsonp-or-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "AsciiJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "IndentedJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "PureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "SecureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "secure-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "XML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/xml"
+ ],
+ "payload": "xml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "YAML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/yaml"
+ ],
+ "payload": "yaml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "TOML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/toml"
+ ],
+ "payload": "toml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "ProtoBuf",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/x-protobuf"
+ ],
+ "payload": "protobuf",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "file",
+ "statusPolicy": "file",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "string",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "raw",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "redirect",
+ "statusPolicy": "redirect",
+ "mediaTypes": [
+ "text/html"
+ ],
+ "payload": "redirect",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "proxy",
+ "statusPolicy": "proxy",
+ "mediaTypes": [
+ "upstream"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "empty",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "optional"
+ ],
+ "payload": "none",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "websocket",
+ "statusPolicy": "websocket",
+ "mediaTypes": [
+ "upgrade-or-text"
+ ],
+ "payload": "frames",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "sse",
+ "statusPolicy": "sse",
+ "mediaTypes": [
+ "text/event-stream"
+ ],
+ "payload": "events",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "admission",
+ "statusPolicy": "admission",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ }
+ ],
+ "admissionStatuses": [
+ 400,
+ 404,
+ 500,
+ 503
+ ],
+ "webSocketFrames": [
+ "text",
+ "binary",
+ "close",
+ "ping",
+ "pong"
+ ],
+ "sseEventNames": "dynamic",
+ "sseData": "json-or-text",
+ "sseEvent": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/$defs/JSONValue"
+ },
+ "event": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "retry": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "additionalProperties": false
+ }
+ }
+ },
{
"method": "DELETE",
"path": "/api/network/echo",
@@ -42939,6 +43216,283 @@
"upstreamStatuses": true
}
},
+ {
+ "method": "DELETE",
+ "path": "/plugin/private/:name/*path",
+ "handler": "pluginPrivateWebServer",
+ "body": "raw",
+ "request": {
+ "type": "string",
+ "format": "binary"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "binary"
+ },
+ {
+ "$ref": "#/$defs/JSONValue"
+ }
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ },
+ "output": "pluginService",
+ "pluginService": {
+ "variants": [
+ {
+ "mode": "JSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "JSONP",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/javascript",
+ "application/json"
+ ],
+ "payload": "jsonp-or-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "AsciiJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "IndentedJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "PureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "SecureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "secure-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "XML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/xml"
+ ],
+ "payload": "xml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "YAML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/yaml"
+ ],
+ "payload": "yaml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "TOML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/toml"
+ ],
+ "payload": "toml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "ProtoBuf",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/x-protobuf"
+ ],
+ "payload": "protobuf",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "file",
+ "statusPolicy": "file",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "string",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "raw",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "redirect",
+ "statusPolicy": "redirect",
+ "mediaTypes": [
+ "text/html"
+ ],
+ "payload": "redirect",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "proxy",
+ "statusPolicy": "proxy",
+ "mediaTypes": [
+ "upstream"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "empty",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "optional"
+ ],
+ "payload": "none",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "websocket",
+ "statusPolicy": "websocket",
+ "mediaTypes": [
+ "upgrade-or-text"
+ ],
+ "payload": "frames",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "sse",
+ "statusPolicy": "sse",
+ "mediaTypes": [
+ "text/event-stream"
+ ],
+ "payload": "events",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "admission",
+ "statusPolicy": "admission",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ }
+ ],
+ "admissionStatuses": [
+ 400,
+ 404,
+ 500,
+ 503
+ ],
+ "webSocketFrames": [
+ "text",
+ "binary",
+ "close",
+ "ping",
+ "pong"
+ ],
+ "sseEventNames": "dynamic",
+ "sseData": "json-or-text",
+ "sseEvent": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/$defs/JSONValue"
+ },
+ "event": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "retry": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "additionalProperties": false
+ }
+ }
+ },
{
"method": "GET",
"path": "/api/ai/mcp/oauth/callback/:flowID",
@@ -43702,6 +44256,283 @@
"upstreamStatuses": true
}
},
+ {
+ "method": "GET",
+ "path": "/plugin/private/:name/*path",
+ "handler": "pluginPrivateWebServer",
+ "body": "raw",
+ "request": {
+ "type": "string",
+ "format": "binary"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "binary"
+ },
+ {
+ "$ref": "#/$defs/JSONValue"
+ }
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ },
+ "output": "pluginService",
+ "pluginService": {
+ "variants": [
+ {
+ "mode": "JSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "JSONP",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/javascript",
+ "application/json"
+ ],
+ "payload": "jsonp-or-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "AsciiJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "IndentedJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "PureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "SecureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "secure-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "XML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/xml"
+ ],
+ "payload": "xml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "YAML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/yaml"
+ ],
+ "payload": "yaml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "TOML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/toml"
+ ],
+ "payload": "toml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "ProtoBuf",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/x-protobuf"
+ ],
+ "payload": "protobuf",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "file",
+ "statusPolicy": "file",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "string",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "raw",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "redirect",
+ "statusPolicy": "redirect",
+ "mediaTypes": [
+ "text/html"
+ ],
+ "payload": "redirect",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "proxy",
+ "statusPolicy": "proxy",
+ "mediaTypes": [
+ "upstream"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "empty",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "optional"
+ ],
+ "payload": "none",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "websocket",
+ "statusPolicy": "websocket",
+ "mediaTypes": [
+ "upgrade-or-text"
+ ],
+ "payload": "frames",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "sse",
+ "statusPolicy": "sse",
+ "mediaTypes": [
+ "text/event-stream"
+ ],
+ "payload": "events",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "admission",
+ "statusPolicy": "admission",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ }
+ ],
+ "admissionStatuses": [
+ 400,
+ 404,
+ 500,
+ 503
+ ],
+ "webSocketFrames": [
+ "text",
+ "binary",
+ "close",
+ "ping",
+ "pong"
+ ],
+ "sseEventNames": "dynamic",
+ "sseData": "json-or-text",
+ "sseEvent": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/$defs/JSONValue"
+ },
+ "event": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "retry": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "additionalProperties": false
+ }
+ }
+ },
{
"method": "GET",
"path": "/ws/network/proxy",
@@ -44184,9 +45015,9 @@
}
},
{
- "method": "OPTIONS",
- "path": "/api/network/echo",
- "handler": "echo",
+ "method": "HEAD",
+ "path": "/plugin/private/:name/*path",
+ "handler": "pluginPrivateWebServer",
"body": "raw",
"request": {
"type": "string",
@@ -44195,27 +45026,15 @@
"response": {
"anyOf": [
{
- "type": "object",
- "properties": {
- "code": {
- "type": "integer",
- "enum": [
- 0
- ]
- },
- "data": {
- "$ref": "#/$defs/NetworkEchoData"
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "binary"
},
- "msg": {
- "type": "string"
+ {
+ "$ref": "#/$defs/JSONValue"
}
- },
- "required": [
- "code",
- "msg",
- "data"
- ],
- "additionalProperties": false
+ ]
},
{
"type": "object",
@@ -44257,12 +45076,225 @@
"additionalProperties": true
}
]
+ },
+ "output": "pluginService",
+ "pluginService": {
+ "variants": [
+ {
+ "mode": "JSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "JSONP",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/javascript",
+ "application/json"
+ ],
+ "payload": "jsonp-or-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "AsciiJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "IndentedJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "PureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "SecureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "secure-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "XML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/xml"
+ ],
+ "payload": "xml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "YAML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/yaml"
+ ],
+ "payload": "yaml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "TOML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/toml"
+ ],
+ "payload": "toml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "ProtoBuf",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/x-protobuf"
+ ],
+ "payload": "protobuf",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "file",
+ "statusPolicy": "file",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "string",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "raw",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "redirect",
+ "statusPolicy": "redirect",
+ "mediaTypes": [
+ "text/html"
+ ],
+ "payload": "redirect",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "proxy",
+ "statusPolicy": "proxy",
+ "mediaTypes": [
+ "upstream"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "empty",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "optional"
+ ],
+ "payload": "none",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "websocket",
+ "statusPolicy": "websocket",
+ "mediaTypes": [
+ "upgrade-or-text"
+ ],
+ "payload": "frames",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "sse",
+ "statusPolicy": "sse",
+ "mediaTypes": [
+ "text/event-stream"
+ ],
+ "payload": "events",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "admission",
+ "statusPolicy": "admission",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ }
+ ],
+ "admissionStatuses": [
+ 400,
+ 404,
+ 500,
+ 503
+ ],
+ "webSocketFrames": [
+ "text",
+ "binary",
+ "close",
+ "ping",
+ "pong"
+ ],
+ "sseEventNames": "dynamic",
+ "sseData": "json-or-text",
+ "sseEvent": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/$defs/JSONValue"
+ },
+ "event": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "retry": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "additionalProperties": false
+ }
}
},
{
"method": "OPTIONS",
- "path": "/api/network/echo/*path",
- "handler": "echoPath",
+ "path": "/api/network/echo",
+ "handler": "echo",
"body": "raw",
"request": {
"type": "string",
@@ -44337,8 +45369,8 @@
},
{
"method": "OPTIONS",
- "path": "/api/network/proxy",
- "handler": "httpProxy",
+ "path": "/api/network/echo/*path",
+ "handler": "echoPath",
"body": "raw",
"request": {
"type": "string",
@@ -44347,8 +45379,84 @@
"response": {
"anyOf": [
{
- "type": "string",
- "format": "binary"
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/NetworkEchoData"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "OPTIONS",
+ "path": "/api/network/proxy",
+ "handler": "httpProxy",
+ "body": "raw",
+ "request": {
+ "type": "string",
+ "format": "binary"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "binary"
},
{
"type": "object",
@@ -44398,6 +45506,283 @@
"upstreamStatuses": true
}
},
+ {
+ "method": "OPTIONS",
+ "path": "/plugin/private/:name/*path",
+ "handler": "pluginPrivateWebServer",
+ "body": "raw",
+ "request": {
+ "type": "string",
+ "format": "binary"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "binary"
+ },
+ {
+ "$ref": "#/$defs/JSONValue"
+ }
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ },
+ "output": "pluginService",
+ "pluginService": {
+ "variants": [
+ {
+ "mode": "JSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "JSONP",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/javascript",
+ "application/json"
+ ],
+ "payload": "jsonp-or-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "AsciiJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "IndentedJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "PureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "SecureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "secure-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "XML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/xml"
+ ],
+ "payload": "xml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "YAML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/yaml"
+ ],
+ "payload": "yaml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "TOML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/toml"
+ ],
+ "payload": "toml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "ProtoBuf",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/x-protobuf"
+ ],
+ "payload": "protobuf",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "file",
+ "statusPolicy": "file",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "string",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "raw",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "redirect",
+ "statusPolicy": "redirect",
+ "mediaTypes": [
+ "text/html"
+ ],
+ "payload": "redirect",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "proxy",
+ "statusPolicy": "proxy",
+ "mediaTypes": [
+ "upstream"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "empty",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "optional"
+ ],
+ "payload": "none",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "websocket",
+ "statusPolicy": "websocket",
+ "mediaTypes": [
+ "upgrade-or-text"
+ ],
+ "payload": "frames",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "sse",
+ "statusPolicy": "sse",
+ "mediaTypes": [
+ "text/event-stream"
+ ],
+ "payload": "events",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "admission",
+ "statusPolicy": "admission",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ }
+ ],
+ "admissionStatuses": [
+ 400,
+ 404,
+ 500,
+ 503
+ ],
+ "webSocketFrames": [
+ "text",
+ "binary",
+ "close",
+ "ping",
+ "pong"
+ ],
+ "sseEventNames": "dynamic",
+ "sseData": "json-or-text",
+ "sseEvent": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/$defs/JSONValue"
+ },
+ "event": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "retry": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "additionalProperties": false
+ }
+ }
+ },
{
"method": "PATCH",
"path": "/api/network/echo",
@@ -44613,6 +45998,283 @@
"upstreamStatuses": true
}
},
+ {
+ "method": "PATCH",
+ "path": "/plugin/private/:name/*path",
+ "handler": "pluginPrivateWebServer",
+ "body": "raw",
+ "request": {
+ "type": "string",
+ "format": "binary"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "binary"
+ },
+ {
+ "$ref": "#/$defs/JSONValue"
+ }
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ },
+ "output": "pluginService",
+ "pluginService": {
+ "variants": [
+ {
+ "mode": "JSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "JSONP",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/javascript",
+ "application/json"
+ ],
+ "payload": "jsonp-or-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "AsciiJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "IndentedJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "PureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "SecureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "secure-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "XML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/xml"
+ ],
+ "payload": "xml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "YAML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/yaml"
+ ],
+ "payload": "yaml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "TOML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/toml"
+ ],
+ "payload": "toml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "ProtoBuf",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/x-protobuf"
+ ],
+ "payload": "protobuf",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "file",
+ "statusPolicy": "file",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "string",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "raw",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "redirect",
+ "statusPolicy": "redirect",
+ "mediaTypes": [
+ "text/html"
+ ],
+ "payload": "redirect",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "proxy",
+ "statusPolicy": "proxy",
+ "mediaTypes": [
+ "upstream"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "empty",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "optional"
+ ],
+ "payload": "none",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "websocket",
+ "statusPolicy": "websocket",
+ "mediaTypes": [
+ "upgrade-or-text"
+ ],
+ "payload": "frames",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "sse",
+ "statusPolicy": "sse",
+ "mediaTypes": [
+ "text/event-stream"
+ ],
+ "payload": "events",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "admission",
+ "statusPolicy": "admission",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ }
+ ],
+ "admissionStatuses": [
+ 400,
+ 404,
+ 500,
+ 503
+ ],
+ "webSocketFrames": [
+ "text",
+ "binary",
+ "close",
+ "ping",
+ "pong"
+ ],
+ "sseEventNames": "dynamic",
+ "sseData": "json-or-text",
+ "sseEvent": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/$defs/JSONValue"
+ },
+ "event": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "retry": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "additionalProperties": false
+ }
+ }
+ },
{
"method": "POST",
"path": "/api/account/checkActivationcode",
@@ -88723,6 +90385,283 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/plugin/private/:name/*path",
+ "handler": "pluginPrivateWebServer",
+ "body": "raw",
+ "request": {
+ "type": "string",
+ "format": "binary"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "binary"
+ },
+ {
+ "$ref": "#/$defs/JSONValue"
+ }
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ },
+ "output": "pluginService",
+ "pluginService": {
+ "variants": [
+ {
+ "mode": "JSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "JSONP",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/javascript",
+ "application/json"
+ ],
+ "payload": "jsonp-or-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "AsciiJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "IndentedJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "PureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "SecureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "secure-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "XML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/xml"
+ ],
+ "payload": "xml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "YAML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/yaml"
+ ],
+ "payload": "yaml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "TOML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/toml"
+ ],
+ "payload": "toml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "ProtoBuf",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/x-protobuf"
+ ],
+ "payload": "protobuf",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "file",
+ "statusPolicy": "file",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "string",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "raw",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "redirect",
+ "statusPolicy": "redirect",
+ "mediaTypes": [
+ "text/html"
+ ],
+ "payload": "redirect",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "proxy",
+ "statusPolicy": "proxy",
+ "mediaTypes": [
+ "upstream"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "empty",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "optional"
+ ],
+ "payload": "none",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "websocket",
+ "statusPolicy": "websocket",
+ "mediaTypes": [
+ "upgrade-or-text"
+ ],
+ "payload": "frames",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "sse",
+ "statusPolicy": "sse",
+ "mediaTypes": [
+ "text/event-stream"
+ ],
+ "payload": "events",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "admission",
+ "statusPolicy": "admission",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ }
+ ],
+ "admissionStatuses": [
+ 400,
+ 404,
+ 500,
+ 503
+ ],
+ "webSocketFrames": [
+ "text",
+ "binary",
+ "close",
+ "ping",
+ "pong"
+ ],
+ "sseEventNames": "dynamic",
+ "sseData": "json-or-text",
+ "sseEvent": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/$defs/JSONValue"
+ },
+ "event": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "retry": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "additionalProperties": false
+ }
+ }
+ },
{
"method": "PUT",
"path": "/api/network/echo",
@@ -88938,6 +90877,283 @@
"upstreamStatuses": true
}
},
+ {
+ "method": "PUT",
+ "path": "/plugin/private/:name/*path",
+ "handler": "pluginPrivateWebServer",
+ "body": "raw",
+ "request": {
+ "type": "string",
+ "format": "binary"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "binary"
+ },
+ {
+ "$ref": "#/$defs/JSONValue"
+ }
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ },
+ "output": "pluginService",
+ "pluginService": {
+ "variants": [
+ {
+ "mode": "JSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "JSONP",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/javascript",
+ "application/json"
+ ],
+ "payload": "jsonp-or-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "AsciiJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "IndentedJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "PureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "SecureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "secure-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "XML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/xml"
+ ],
+ "payload": "xml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "YAML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/yaml"
+ ],
+ "payload": "yaml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "TOML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/toml"
+ ],
+ "payload": "toml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "ProtoBuf",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/x-protobuf"
+ ],
+ "payload": "protobuf",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "file",
+ "statusPolicy": "file",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "string",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "raw",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "redirect",
+ "statusPolicy": "redirect",
+ "mediaTypes": [
+ "text/html"
+ ],
+ "payload": "redirect",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "proxy",
+ "statusPolicy": "proxy",
+ "mediaTypes": [
+ "upstream"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "empty",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "optional"
+ ],
+ "payload": "none",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "websocket",
+ "statusPolicy": "websocket",
+ "mediaTypes": [
+ "upgrade-or-text"
+ ],
+ "payload": "frames",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "sse",
+ "statusPolicy": "sse",
+ "mediaTypes": [
+ "text/event-stream"
+ ],
+ "payload": "events",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "admission",
+ "statusPolicy": "admission",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ }
+ ],
+ "admissionStatuses": [
+ 400,
+ 404,
+ 500,
+ 503
+ ],
+ "webSocketFrames": [
+ "text",
+ "binary",
+ "close",
+ "ping",
+ "pong"
+ ],
+ "sseEventNames": "dynamic",
+ "sseData": "json-or-text",
+ "sseEvent": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/$defs/JSONValue"
+ },
+ "event": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "retry": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "additionalProperties": false
+ }
+ }
+ },
{
"method": "TRACE",
"path": "/api/network/echo",
@@ -89152,6 +91368,283 @@
"contentType": "application/octet-stream",
"upstreamStatuses": true
}
+ },
+ {
+ "method": "TRACE",
+ "path": "/plugin/private/:name/*path",
+ "handler": "pluginPrivateWebServer",
+ "body": "raw",
+ "request": {
+ "type": "string",
+ "format": "binary"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "binary"
+ },
+ {
+ "$ref": "#/$defs/JSONValue"
+ }
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ },
+ "output": "pluginService",
+ "pluginService": {
+ "variants": [
+ {
+ "mode": "JSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "JSONP",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/javascript",
+ "application/json"
+ ],
+ "payload": "jsonp-or-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "AsciiJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "IndentedJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "PureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "SecureJSON",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/json"
+ ],
+ "payload": "secure-json",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "XML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/xml"
+ ],
+ "payload": "xml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "YAML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/yaml"
+ ],
+ "payload": "yaml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "TOML",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/toml"
+ ],
+ "payload": "toml",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "ProtoBuf",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "application/x-protobuf"
+ ],
+ "payload": "protobuf",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "file",
+ "statusPolicy": "file",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "string",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "raw",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "dynamic"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "redirect",
+ "statusPolicy": "redirect",
+ "mediaTypes": [
+ "text/html"
+ ],
+ "payload": "redirect",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "proxy",
+ "statusPolicy": "proxy",
+ "mediaTypes": [
+ "upstream"
+ ],
+ "payload": "bytes",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "empty",
+ "statusPolicy": "plugin",
+ "mediaTypes": [
+ "optional"
+ ],
+ "payload": "none",
+ "headersOverrideMedia": true
+ },
+ {
+ "mode": "websocket",
+ "statusPolicy": "websocket",
+ "mediaTypes": [
+ "upgrade-or-text"
+ ],
+ "payload": "frames",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "sse",
+ "statusPolicy": "sse",
+ "mediaTypes": [
+ "text/event-stream"
+ ],
+ "payload": "events",
+ "headersOverrideMedia": false
+ },
+ {
+ "mode": "admission",
+ "statusPolicy": "admission",
+ "mediaTypes": [
+ "text/plain"
+ ],
+ "payload": "text",
+ "headersOverrideMedia": true
+ }
+ ],
+ "admissionStatuses": [
+ 400,
+ 404,
+ 500,
+ 503
+ ],
+ "webSocketFrames": [
+ "text",
+ "binary",
+ "close",
+ "ping",
+ "pong"
+ ],
+ "sseEventNames": "dynamic",
+ "sseData": "json-or-text",
+ "sseEvent": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/$defs/JSONValue"
+ },
+ "event": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "retry": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "additionalProperties": false
+ }
+ }
}
]
}
diff --git a/kernel/apicontract/typescript.go b/kernel/apicontract/typescript.go
index 68ce5202c7..aa5afbf7bf 100644
--- a/kernel/apicontract/typescript.go
+++ b/kernel/apicontract/typescript.go
@@ -191,6 +191,10 @@ func (b *Bundle) TypeScript(legacy []Route) []byte {
protocol, _ := json.Marshal(proxy)
fmt.Fprintf(&output, " proxy: %s;\n", protocol)
}
+ if service := endpoint.PluginService; service != nil {
+ protocol, _ := json.Marshal(service)
+ fmt.Fprintf(&output, " pluginService: %s;\n", protocol)
+ }
output.WriteString(" };\n")
}
output.WriteString("}\n\n")
@@ -245,7 +249,7 @@ type APIPostEmptyResponse<C> = C extends {emptyResponseStatuses: infer S extends
? Exclude<S[number], 401 | 403 | 404> extends never ? never : "" : never;
type APIPostTail<C extends APIContract> = [
- cb?: (response: (C extends {output: "binary" | "proxy"} ? JSONValue : C extends {output: "directJSON"} ? APIDirectCallbackResponse<C["response"]> | (C extends {noContent: true} ? "" : never) : C extends {output: "sse"} ? string | APICallbackResponse<C["response"]> : APICallbackResponse<C["response"]>) | APIPostEmptyResponse<C>) => void,
+ cb?: (response: (C extends {output: "binary" | "proxy" | "pluginService"} ? JSONValue : C extends {output: "directJSON"} ? APIDirectCallbackResponse<C["response"]> | (C extends {noContent: true} ? "" : never) : C extends {output: "sse"} ? string | APICallbackResponse<C["response"]> : APICallbackResponse<C["response"]>) | APIPostEmptyResponse<C>) => void,
headers?: Record<string, string>,
failCallback?: (response: APIFetchFailure) => void,
signal?: AbortSignal,
@@ -277,13 +281,13 @@ export type FetchSyncPost<Legacy = APILegacyResponse> = <Path extends string>(
: Path extends APILegacyPOSTPath ? [data?: any, ...tail: APISyncTail]
: string extends Path ? [data?: any, ...tail: APISyncTail] : never
) => Promise<Path extends keyof APIPOSTRoutes
- ? APIPOSTRoutes[Path] extends {output: "binary" | "proxy"} ? JSONValue : APIPOSTRoutes[Path]["response"] | APITransportError
+ ? APIPOSTRoutes[Path] extends {output: "binary" | "proxy" | "pluginService"} ? JSONValue : APIPOSTRoutes[Path]["response"] | APITransportError
: Legacy>;
export type FetchGet<Legacy = APILegacyResponse | string> = <Path extends string>(
url: Path,
...args: Path extends keyof APIGETRoutes
- ? [cb: (response: APIGETRoutes[Path] extends {output: "binary" | "proxy"} ? JSONValue : APIGETRoutes[Path]["response"] | APIEmptyResponse<APIGETRoutes[Path]> | (APIGETRoutes[Path] extends {output: "websocket" | "sse"} ? string : never)) => void]
+ ? [cb: (response: APIGETRoutes[Path] extends {output: "binary" | "proxy" | "pluginService"} ? JSONValue : APIGETRoutes[Path]["response"] | APIEmptyResponse<APIGETRoutes[Path]> | (APIGETRoutes[Path] extends {output: "websocket" | "sse"} ? string : never)) => void]
: Path extends keyof APIPOSTRoutes ? never
: [cb: (response: Legacy) => void]
) => void;
diff --git a/kernel/plugin/server.go b/kernel/plugin/server.go
index 4551e5869b..6ce225c41b 100644
--- a/kernel/plugin/server.go
+++ b/kernel/plugin/server.go
@@ -422,127 +422,3 @@ func parseRequest(c *gin.Context) (request *Request, err error) {
}
return
}
-
-func HandleHttpRequest(c *gin.Context, scope AccessScope) {
- // /plugin/(public|private)/:name/*path
- name := c.Param("name")
- // path := c.Param("path")
-
- p := GetManager().GetPlugin(name)
- if p == nil {
- c.String(http.StatusNotFound, "[plugin:%s] not found", name)
- return
- }
- if p.State() != PluginStateRunning {
- c.String(http.StatusServiceUnavailable, "[plugin:%s] is not running", name)
- return
- }
-
- request, parseErr := parseRequest(c)
- if parseErr != nil {
- c.String(http.StatusBadRequest, "[plugin:%s] Error occurred while parsing HTTP request: %s", name, parseErr)
- return
- }
-
- if request.Context.IsWebsocket {
- handleErr := p.handleWebSocketRequest(c, request, scope)
- if handleErr != nil {
- msg := fmt.Sprintf("[plugin:%s] Error occurred while handling WebSocket request: %s", name, handleErr)
- logging.LogWarn(msg)
- c.String(http.StatusInternalServerError, msg)
- }
- return
- }
-
- if request.Context.IsSse {
- handleErr := p.handleServerSentEventRequest(c, request, scope)
- if handleErr != nil {
- msg := fmt.Sprintf("[plugin:%s] Error occurred while handling SSE request: %s", name, handleErr)
- logging.LogWarn(msg)
- c.String(http.StatusInternalServerError, msg)
- }
- return
- }
-
- response, handleErr := p.handleHttpRequest(c, request, scope)
- if handleErr != nil {
- msg := fmt.Sprintf("[plugin:%s] Error occurred while handling HTTP request: %s", name, handleErr)
- logging.LogWarn(msg)
- c.String(http.StatusInternalServerError, msg)
- return
- }
-
- // Set response headers
- for headerKey, headerValues := range response.Headers {
- for _, headerValue := range headerValues {
- c.Header(headerKey, headerValue)
- }
- }
-
- // Set response cookies
- for _, cookie := range response.Cookies {
- http.SetCookie(c.Writer, cookie)
- }
-
- // Write response body
- if response.Body != nil {
- if response.Body.Data != nil {
- // Serialized data
- switch response.Body.Data.Type {
- case SerializedTypeJSON:
- c.JSON(response.StatusCode, response.Body.Data.Data)
- case SerializedTypeJSONP:
- c.JSONP(response.StatusCode, response.Body.Data.Data)
- case SerializedTypeAsciiJSON:
- c.AsciiJSON(response.StatusCode, response.Body.Data.Data)
- case SerializedTypeIndentedJSON:
- c.IndentedJSON(response.StatusCode, response.Body.Data.Data)
- case SerializedTypePureJSON:
- c.PureJSON(response.StatusCode, response.Body.Data.Data)
- case SerializedTypeSecureJSON:
- c.SecureJSON(response.StatusCode, response.Body.Data.Data)
-
- case SerializedTypeXML:
- c.XML(response.StatusCode, response.Body.Data.Data)
- case SerializedTypeYAML:
- c.YAML(response.StatusCode, response.Body.Data.Data)
- case SerializedTypeTOML:
- c.TOML(response.StatusCode, response.Body.Data.Data)
- case SerializedTypeProtoBuf:
- c.ProtoBuf(response.StatusCode, response.Body.Data.Data)
-
- default:
- c.String(http.StatusInternalServerError, "[plugin:%s] Unsupported serialized data type [%s] in response", name, response.Body.Data.Type)
- }
- return
- } else if response.Body.File != nil {
- // If Path is not empty, use it as the file content and ignore Data.
- // This is for streaming large files without loading the whole content into memory.
- if response.Body.File.Name != "" {
- c.FileAttachment(response.Body.File.Path, response.Body.File.Name)
- } else {
- c.File(response.Body.File.Path)
- }
- return
- } else if response.Body.String != nil {
- // Format the string with the provided values and write it to the response.
- c.String(response.StatusCode, response.Body.String.Format, response.Body.String.Values...)
- return
- } else if response.Body.Raw != nil {
- // Raw data
- c.Data(response.StatusCode, response.Body.Raw.ContentType, response.Body.Raw.Data)
- return
- } else if response.Body.Redirect != nil {
- // Redirect
- c.Redirect(response.StatusCode, response.Body.Redirect.Location)
- return
- } else if response.Body.Proxy != nil {
- // Streaming proxy
- writeProxyResponse(c, response.Body.Proxy)
- return
- } else {
- // No body
- }
- }
- c.Status(response.StatusCode)
-}
diff --git a/kernel/plugin/service_contract.go b/kernel/plugin/service_contract.go
new file mode 100644
index 0000000000..6ee9d88981
--- /dev/null
+++ b/kernel/plugin/service_contract.go
@@ -0,0 +1,135 @@
+package plugin
+
+import (
+ "fmt"
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+)
+
+func PreparePrivateService(c *gin.Context, _ apicontract.EmptyRequest) apicontract.Response[apicontract.PluginServiceContent] {
+ return preparePluginService(c, AccessScopePrivate)
+}
+
+func pluginServiceStream(mode apicontract.PluginServiceMode, status int, write func()) apicontract.Response[apicontract.PluginServiceContent] {
+ return apicontract.StreamPluginService(mode, status, func(http.ResponseWriter, *http.Request) { write() })
+}
+
+func pluginServiceError(c *gin.Context, status int, message string) apicontract.Response[apicontract.PluginServiceContent] {
+ return pluginServiceStream(apicontract.PluginServiceAdmission, status, func() { c.String(status, "%s", message) })
+}
+
+func preparePluginService(c *gin.Context, scope AccessScope) apicontract.Response[apicontract.PluginServiceContent] {
+ name := c.Param("name")
+
+ p := GetManager().GetPlugin(name)
+ if p == nil {
+ return pluginServiceError(c, http.StatusNotFound, fmt.Sprintf("[plugin:%s] not found", name))
+ }
+ if p.State() != PluginStateRunning {
+ return pluginServiceError(c, http.StatusServiceUnavailable, fmt.Sprintf("[plugin:%s] is not running", name))
+ }
+
+ request, parseErr := parseRequest(c)
+ if parseErr != nil {
+ return pluginServiceError(c, http.StatusBadRequest, fmt.Sprintf("[plugin:%s] Error occurred while parsing HTTP request: %s", name, parseErr))
+ }
+
+ if request.Context.IsWebsocket {
+ return pluginServiceStream(apicontract.PluginServiceWebSocket, 101, func() {
+ handleErr := p.handleWebSocketRequest(c, request, scope)
+ if handleErr != nil {
+ msg := fmt.Sprintf("[plugin:%s] Error occurred while handling WebSocket request: %s", name, handleErr)
+ logging.LogWarn(msg)
+ c.String(http.StatusInternalServerError, msg)
+ }
+ })
+ }
+
+ if request.Context.IsSse {
+ return pluginServiceStream(apicontract.PluginServiceSSE, 200, func() {
+ handleErr := p.handleServerSentEventRequest(c, request, scope)
+ if handleErr != nil {
+ msg := fmt.Sprintf("[plugin:%s] Error occurred while handling SSE request: %s", name, handleErr)
+ logging.LogWarn(msg)
+ c.String(http.StatusInternalServerError, msg)
+ }
+ })
+ }
+
+ response, handleErr := p.handleHttpRequest(c, request, scope)
+ if handleErr != nil {
+ msg := fmt.Sprintf("[plugin:%s] Error occurred while handling HTTP request: %s", name, handleErr)
+ logging.LogWarn(msg)
+ return pluginServiceError(c, http.StatusInternalServerError, msg)
+ }
+
+ if response == nil {
+ return pluginServiceStream(apicontract.PluginServiceEmpty, 500, func() { c.Status(500) })
+ }
+ return pluginServiceHTTPResponse(c, name, response)
+}
+
+func pluginServiceHTTPResponse(c *gin.Context, name string, response *HttpResponse) apicontract.Response[apicontract.PluginServiceContent] {
+
+ // 插件头的重复值依次覆盖,Cookie 则逐个追加。
+ for headerKey, headerValues := range response.Headers {
+ for _, headerValue := range headerValues {
+ c.Header(headerKey, headerValue)
+ }
+ }
+
+ for _, cookie := range response.Cookies {
+ http.SetCookie(c.Writer, cookie)
+ }
+
+ // 按声明优先级选择唯一响应模式,流执行时使用对应序列化器。
+ if response.Body != nil {
+ if response.Body.Data != nil {
+ switch response.Body.Data.Type {
+ case SerializedTypeJSON:
+ return pluginServiceStream(apicontract.PluginServiceJSON, response.StatusCode, func() { c.JSON(response.StatusCode, response.Body.Data.Data) })
+ case SerializedTypeJSONP:
+ return pluginServiceStream(apicontract.PluginServiceJSONP, response.StatusCode, func() { c.JSONP(response.StatusCode, response.Body.Data.Data) })
+ case SerializedTypeAsciiJSON:
+ return pluginServiceStream(apicontract.PluginServiceASCIIJSON, response.StatusCode, func() { c.AsciiJSON(response.StatusCode, response.Body.Data.Data) })
+ case SerializedTypeIndentedJSON:
+ return pluginServiceStream(apicontract.PluginServiceIndentedJSON, response.StatusCode, func() { c.IndentedJSON(response.StatusCode, response.Body.Data.Data) })
+ case SerializedTypePureJSON:
+ return pluginServiceStream(apicontract.PluginServicePureJSON, response.StatusCode, func() { c.PureJSON(response.StatusCode, response.Body.Data.Data) })
+ case SerializedTypeSecureJSON:
+ return pluginServiceStream(apicontract.PluginServiceSecureJSON, response.StatusCode, func() { c.SecureJSON(response.StatusCode, response.Body.Data.Data) })
+
+ case SerializedTypeXML:
+ return pluginServiceStream(apicontract.PluginServiceXML, response.StatusCode, func() { c.XML(response.StatusCode, response.Body.Data.Data) })
+ case SerializedTypeYAML:
+ return pluginServiceStream(apicontract.PluginServiceYAML, response.StatusCode, func() { c.YAML(response.StatusCode, response.Body.Data.Data) })
+ case SerializedTypeTOML:
+ return pluginServiceStream(apicontract.PluginServiceTOML, response.StatusCode, func() { c.TOML(response.StatusCode, response.Body.Data.Data) })
+ case SerializedTypeProtoBuf:
+ return pluginServiceStream(apicontract.PluginServiceProtoBuf, response.StatusCode, func() { c.ProtoBuf(response.StatusCode, response.Body.Data.Data) })
+
+ default:
+ return pluginServiceError(c, http.StatusInternalServerError, fmt.Sprintf("[plugin:%s] Unsupported serialized data type [%s] in response", name, response.Body.Data.Type))
+ }
+ } else if response.Body.File != nil {
+ // 文件由 HTTP 文件服务处理范围请求和条件读取,不预先加载文件内容。
+ if response.Body.File.Name != "" {
+ return pluginServiceStream(apicontract.PluginServiceFile, 200, func() { c.FileAttachment(response.Body.File.Path, response.Body.File.Name) })
+ } else {
+ return pluginServiceStream(apicontract.PluginServiceFile, 200, func() { c.File(response.Body.File.Path) })
+ }
+ } else if response.Body.String != nil {
+ return pluginServiceStream(apicontract.PluginServiceString, response.StatusCode, func() { c.String(response.StatusCode, response.Body.String.Format, response.Body.String.Values...) })
+ } else if response.Body.Raw != nil {
+ return pluginServiceStream(apicontract.PluginServiceRaw, response.StatusCode, func() { c.Data(response.StatusCode, response.Body.Raw.ContentType, response.Body.Raw.Data) })
+ } else if response.Body.Redirect != nil {
+ return pluginServiceStream(apicontract.PluginServiceRedirect, response.StatusCode, func() { c.Redirect(response.StatusCode, response.Body.Redirect.Location) })
+ } else if response.Body.Proxy != nil {
+ return pluginServiceStream(apicontract.PluginServiceProxy, 200, func() { writeProxyResponse(c, response.Body.Proxy) })
+ }
+ }
+ return pluginServiceStream(apicontract.PluginServiceEmpty, response.StatusCode, func() { c.Status(response.StatusCode) })
+}
diff --git a/kernel/plugin/service_contract_test.go b/kernel/plugin/service_contract_test.go
new file mode 100644
index 0000000000..411c4a58d5
--- /dev/null
+++ b/kernel/plugin/service_contract_test.go
@@ -0,0 +1,284 @@
+package plugin
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/dop251/goja"
+ "github.com/dop251/goja_nodejs/eventloop"
+ "github.com/gin-gonic/gin"
+ "github.com/gorilla/websocket"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "google.golang.org/protobuf/types/known/wrapperspb"
+)
+
+func serviceTestWrite(c *gin.Context, response apicontract.Response[apicontract.PluginServiceContent]) {
+ _ = apicontract.PluginPrivateService.Status(response)
+ response.Stream()(c.Writer, c.Request)
+}
+func serviceTestHandler(c *gin.Context) {
+ serviceTestWrite(c, PreparePrivateService(c, apicontract.EmptyRequest{}))
+}
+
+func newServiceTestPlugin(t *testing.T, script string) (*KernelPlugin, context.CancelFunc) {
+ t.Helper()
+ ctx, cancel := context.WithCancel(context.Background())
+ p := &KernelPlugin{Petal: &model.Petal{Name: "contract-service"}, context: ctx}
+ p.state.Store(int64(PluginStateRunning))
+ loop := eventloop.NewEventLoop()
+ p.worker.Start(loop)
+ var runErr error
+ loop.Run(func(rt *goja.Runtime) {
+ rt.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
+ _, runErr = rt.RunString(script)
+ })
+ if runErr != nil {
+ cancel()
+ t.Fatal(runErr)
+ }
+ loop.Start()
+ GetManager().plugins.Store(p.Name, p)
+ t.Cleanup(func() { cancel(); loop.Stop(); GetManager().plugins.Delete(p.Name) })
+ return p, cancel
+}
+
+func TestPluginServiceHTTPBranches(t *testing.T) {
+ bundle, err := apicontract.BuildBundle()
+ if err != nil {
+ t.Fatal(err)
+ }
+ file := filepath.Join(t.TempDir(), "content.txt")
+ if err = os.WriteFile(file, []byte("file content"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ for _, tt := range []struct {
+ name string
+ mode apicontract.PluginServiceMode
+ body *ResponseBody
+ want string
+ }{
+ {"JSON", apicontract.PluginServiceJSON, &ResponseBody{Data: &ResponseSerializedData{Type: SerializedTypeJSON, Data: map[string]any{"extension": []any{nil, true, 1}}}}, `{"extension":[null,true,1]}`},
+ {"JSONP", apicontract.PluginServiceJSONP, &ResponseBody{Data: &ResponseSerializedData{Type: SerializedTypeJSONP, Data: 1}}, `callback(1);`},
+ {"ASCII", apicontract.PluginServiceASCIIJSON, &ResponseBody{Data: &ResponseSerializedData{Type: SerializedTypeAsciiJSON, Data: "A"}}, `"A"`},
+ {"Indented", apicontract.PluginServiceIndentedJSON, &ResponseBody{Data: &ResponseSerializedData{Type: SerializedTypeIndentedJSON, Data: []int{1}}}, "[\n 1\n]"},
+ {"Pure", apicontract.PluginServicePureJSON, &ResponseBody{Data: &ResponseSerializedData{Type: SerializedTypePureJSON, Data: "<tag>"}}, "\"<tag>\"\n"},
+ {"Secure", apicontract.PluginServiceSecureJSON, &ResponseBody{Data: &ResponseSerializedData{Type: SerializedTypeSecureJSON, Data: []int{1}}}, "while(1);[1]"},
+ {"XML", apicontract.PluginServiceXML, &ResponseBody{Data: &ResponseSerializedData{Type: SerializedTypeXML, Data: "value"}}, "<string>value</string>"},
+ {"YAML", apicontract.PluginServiceYAML, &ResponseBody{Data: &ResponseSerializedData{Type: SerializedTypeYAML, Data: map[string]string{"key": "value"}}}, "key: value\n"},
+ {"TOML", apicontract.PluginServiceTOML, &ResponseBody{Data: &ResponseSerializedData{Type: SerializedTypeTOML, Data: map[string]string{"key": "value"}}}, "key = 'value'\n"},
+ {"ProtoBuf", apicontract.PluginServiceProtoBuf, &ResponseBody{Data: &ResponseSerializedData{Type: SerializedTypeProtoBuf, Data: wrapperspb.String("x")}}, "\n\x01x"},
+ {"file", apicontract.PluginServiceFile, &ResponseBody{File: &ResponseFile{Path: file, Name: "download.txt"}}, "file content"},
+ {"string", apicontract.PluginServiceString, &ResponseBody{String: &ResponseString{Format: "value=%d", Values: []any{7}}}, "value=7"},
+ {"raw", apicontract.PluginServiceRaw, &ResponseBody{Raw: &ResponseRawData{ContentType: "application/custom", Data: []byte{0, 255}}}, string([]byte{0, 255})},
+ {"empty", apicontract.PluginServiceEmpty, nil, ""},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ engine := gin.New()
+ engine.GET("/plugin/private/:name/*path", func(c *gin.Context) {
+ serviceTestWrite(c, pluginServiceHTTPResponse(c, "test", &HttpResponse{StatusCode: 200, Headers: map[string][]string{"X-Value": {"first", "last"}}, Cookies: []*http.Cookie{{Name: "a", Value: "1"}, {Name: "b", Value: "2"}}, Body: tt.body}))
+ })
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("GET", "/plugin/private/test/value?callback=callback", nil))
+ if recorder.Body.String() != tt.want {
+ t.Fatalf("body changed: %q want %q", recorder.Body.String(), tt.want)
+ }
+ if recorder.Header().Get("X-Value") != "last" || len(recorder.Header().Values("Set-Cookie")) != 2 {
+ t.Fatal("plugin headers/cookies changed")
+ }
+ if err := bundle.ValidatePluginServiceResponse("GET", "/plugin/private/:name/*path", tt.mode, recorder.Code, recorder.Header().Get("Content-Type"), recorder.Body.Bytes()); err != nil {
+ t.Fatal(err)
+ }
+ })
+ }
+}
+
+func TestPluginServiceAdmissionAndDispatch(t *testing.T) {
+ p, _ := newServiceTestPlugin(t, `globalThis.siyuan={server:{private:{http:{handler:(r)=>({statusCode:207,headers:{"X-Path":[r.context.path]},body:{data:{type:"JSON",data:{method:r.request.method,cookie:r.request.cookies.test,authorization:r.request.headers.Authorization,path:r.context.path}}}})}}}};`)
+ engine := gin.New()
+ engine.Any("/plugin/private/:name/*path", serviceTestHandler)
+ request := httptest.NewRequest("POST", "/plugin/private/"+p.Name+"/value", strings.NewReader("raw body"))
+ request.Header.Set("Authorization", "secret")
+ request.AddCookie(&http.Cookie{Name: "test", Value: "cookie"})
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, request)
+ if recorder.Code != 207 || recorder.Header().Get("X-Path") != "/value" {
+ t.Fatalf("dispatch failed: %d %s", recorder.Code, recorder.Body.String())
+ }
+ var data struct {
+ Method string `json:"method"`
+ Cookie []string `json:"cookie"`
+ Authorization json.RawMessage `json:"authorization"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &data); err != nil {
+ t.Fatal(err)
+ }
+ if data.Method != "POST" || len(data.Cookie) != 1 || len(data.Authorization) != 0 {
+ t.Fatalf("request filtering changed: %s", recorder.Body.String())
+ }
+ for _, tt := range []struct {
+ name string
+ state PluginState
+ want int
+ }{{"missing", PluginStateRunning, 404}, {p.Name, PluginStateStopped, 503}} {
+ p.state.Store(int64(tt.state))
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("GET", "/plugin/private/"+tt.name+"/value", nil))
+ if recorder.Code != tt.want || !strings.HasPrefix(recorder.Header().Get("Content-Type"), "text/plain") {
+ t.Fatalf("admission changed: %d %s", recorder.Code, recorder.Body.String())
+ }
+ }
+}
+
+func TestPluginServiceCancelledHTTPResponse(t *testing.T) {
+ p, _ := newServiceTestPlugin(t, `globalThis.siyuan={server:{private:{http:{handler:()=>new Promise(()=>{})}}}};`)
+ engine := gin.New()
+ engine.Use(gin.Recovery())
+ engine.Any("/plugin/private/:name/*path", serviceTestHandler)
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ request := httptest.NewRequest("GET", "/plugin/private/"+p.Name+"/cancelled", nil).WithContext(ctx)
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, request)
+ if recorder.Code != 500 || recorder.Body.Len() != 0 {
+ t.Fatalf("cancelled HTTP response changed: %d %q", recorder.Code, recorder.Body.String())
+ }
+}
+
+func TestPluginServiceProxyAndFiles(t *testing.T) {
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/custom")
+ w.Header().Set("Set-Cookie", "upstream=secret")
+ w.Header().Set("Connection", "X-Hop")
+ w.Header().Set("X-Hop", "secret")
+ w.WriteHeader(206)
+ _, _ = w.Write([]byte{0, 255})
+ }))
+ defer upstream.Close()
+ engine := gin.New()
+ engine.Any("/plugin/private/:name/*path", func(c *gin.Context) {
+ serviceTestWrite(c, pluginServiceHTTPResponse(c, "test", &HttpResponse{StatusCode: 202, Body: &ResponseBody{Proxy: &ResponseProxy{URL: upstream.URL}}}))
+ })
+ for _, method := range []string{"GET", "HEAD", "POST"} {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(method, "/plugin/private/test/proxy", nil))
+ if method == "POST" {
+ if recorder.Code != 400 {
+ t.Fatal("proxy method restriction changed")
+ }
+ continue
+ }
+ if recorder.Code != 206 || recorder.Header().Get("Set-Cookie") != "" || recorder.Header().Get("X-Hop") != "" {
+ t.Fatal("proxy upstream status/header filtering changed")
+ }
+ if method == "HEAD" {
+ if recorder.Body.Len() != 0 {
+ t.Fatal("HEAD body changed")
+ }
+ } else if !bytes.Equal(recorder.Body.Bytes(), []byte{0, 255}) {
+ t.Fatal("proxy bytes changed")
+ }
+ }
+}
+
+func TestPluginServiceFileRangesRedirectAndPriority(t *testing.T) {
+ file := filepath.Join(t.TempDir(), "range.txt")
+ if err := os.WriteFile(file, []byte("0123456789"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ engine := gin.New()
+ engine.Any("/plugin/private/:name/*path", func(c *gin.Context) {
+ body := &ResponseBody{File: &ResponseFile{Path: file}}
+ status := 599
+ switch c.Param("path") {
+ case "/redirect":
+ status = 302
+ body = &ResponseBody{Redirect: &ResponseRedirect{Location: "/next"}}
+ case "/priority":
+ status = 200
+ body = &ResponseBody{Data: &ResponseSerializedData{Type: SerializedTypeJSON, Data: 1}, Raw: &ResponseRawData{Data: []byte("ignored")}}
+ }
+ serviceTestWrite(c, pluginServiceHTTPResponse(c, "test", &HttpResponse{StatusCode: status, Body: body}))
+ })
+ request := httptest.NewRequest("GET", "/plugin/private/test/range", nil)
+ request.Header.Set("Range", "bytes=2-4")
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, request)
+ if recorder.Code != 206 || recorder.Body.String() != "234" || recorder.Header().Get("Content-Range") != "bytes 2-4/10" {
+ t.Fatalf("file range changed: %d %s", recorder.Code, recorder.Body.String())
+ }
+ recorder = httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("GET", "/plugin/private/test/redirect", nil))
+ if recorder.Code != 302 || recorder.Header().Get("Location") != "/next" {
+ t.Fatal("redirect changed")
+ }
+ recorder = httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("GET", "/plugin/private/test/priority", nil))
+ if recorder.Body.String() != "1" {
+ t.Fatal("response body branch priority changed")
+ }
+}
+
+func TestPluginServiceStreamingLifecycle(t *testing.T) {
+ p, cancel := newServiceTestPlugin(t, `globalThis.siyuan={server:{private:{es:{handler:(r)=>{r.port.onopen=()=>{r.port.send({event:"custom",id:"7",data:{extension:[true,null,1]}});};}},ws:{handler:(r)=>{r.port.onmessage=(e)=>{r.port.send(e.data);};}}}}};`)
+ engine := gin.New()
+ engine.Any("/plugin/private/:name/*path", serviceTestHandler)
+ server := httptest.NewServer(engine)
+ defer server.Close()
+ request, _ := http.NewRequest("GET", server.URL+"/plugin/private/"+p.Name+"/events", nil)
+ request.Header.Set("Accept", "text/event-stream")
+ response, err := http.DefaultClient.Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ expected := "id:7\nevent:custom\ndata:{\"extension\":[true,null,1]}\n\n"
+ payload := make([]byte, len(expected))
+ if _, err = io.ReadFull(response.Body, payload); err != nil || string(payload) != expected {
+ t.Fatalf("SSE changed: %q %v", payload, err)
+ }
+ conn, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+"/plugin/private/"+p.Name+"/socket", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ _ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
+ if err = conn.WriteMessage(websocket.TextMessage, []byte("hello")); err != nil {
+ t.Fatal(err)
+ }
+ kind, data, err := conn.ReadMessage()
+ if err != nil || kind != websocket.TextMessage || string(data) != "hello" {
+ t.Fatalf("plugin frame changed: %d %s %v", kind, data, err)
+ }
+ foreign, denied, denialErr := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+"/plugin/private/"+p.Name+"/socket", http.Header{"Origin": []string{"https://foreign.invalid"}, "Sec-Fetch-Site": []string{"cross-site"}})
+ if foreign != nil {
+ foreign.Close()
+ }
+ if denied != nil {
+ denied.Body.Close()
+ }
+ if denialErr == nil || denied == nil || denied.StatusCode != 400 {
+ t.Fatalf("service origin admission changed: %+v %v", denied, denialErr)
+ }
+ cancel()
+ _ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
+ if _, _, err = conn.ReadMessage(); err == nil {
+ t.Fatal("plugin cancellation did not close websocket")
+ }
+ done := make(chan error, 1)
+ go func() { _, err := io.ReadAll(response.Body); done <- err }()
+ select {
+ case <-done:
+ case <-time.After(3 * time.Second):
+ t.Fatal("plugin cancellation did not close SSE")
+ }
+}