Skip to content

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

:recycle: Correct no-body API request contracts https://github.com/siyuan-note/siyuan/issues/20375

Daniel3e341554c271
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 0df6a87801..9b0d3139fa 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -950,8 +950,6 @@ export type DownloadInstallPkgRequestInput = { "downloadInstallPkg": boolean; };
export type DuplicateAttributeViewBlockRequestInput = { "avID": string; };
-export type DynamicIconRequestInput = { "color"?: string; "content"?: string; "date"?: string; "id"?: string; "lang"?: string; "type"?: string; "weekdayType"?: string; };
-
export type EditorReadOnlyRequestInput = { "readonly": boolean; };
export type EmbedBlock = { "allowChildOperation": boolean; "block": SearchBlock | null; "blockPaths": Array<BlockPath | null> | null; };
@@ -2264,8 +2262,6 @@ export type SystemOIDC = { "allowAll": boolean; "claimRules": Array<SystemOIDCCl
export type SystemOIDCActivateData = { "config": SystemOIDC | null; "status": "completed"; };
-export type SystemOIDCCallbackRequestInput = { "code"?: string | null; "error"?: string | null; "state"?: string | null; };
-
export type SystemOIDCClaimRule = { "claim": string; "operator": string; "values": Array<string> | null; };
export type SystemOIDCClaimRuleInput = { "claim"?: string | null; "operator"?: string | null; "values"?: Array<string> | null; };
@@ -2322,8 +2318,6 @@ export type SystemTypeFilter = { "blockquote": boolean; "callout": boolean; "cod
export type SystemUILayoutRequestInput = { "layout"?: { [key: string]: JSONValue } | null; };
-export type SystemUIProcessRequestInput = { "pid"?: string | null; };
-
export type SystemWebDAV = { "concurrentReqs": number; "endpoint": string; "password": string; "skipTlsVerify": boolean; "timeout": number; "username": string; };
export type SystemWorkspace = { "closed": boolean; "path": string; };
@@ -2521,7 +2515,7 @@ export interface APIGETRoutes {
contentVariants: [{"status":200,"contentType":"text/html"},{"status":400,"contentType":"text/html"},{"status":403,"contentType":"text/plain"}];
};
"/api/icon/getDynamicIcon": {
- request: DynamicIconRequestInput;
+ request: EmptyRequestInput;
response: Blob | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "none";
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
@@ -2609,7 +2603,7 @@ export interface APIGETRoutes {
contentVariants: [{"status":200,"contentType":"image/png"}];
};
"/api/system/oidc/callback": {
- request: SystemOIDCCallbackRequestInput;
+ request: EmptyRequestInput;
response: Blob | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "none";
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
@@ -7197,7 +7191,7 @@ export interface APIPOSTRoutes {
authorization?: readonly ["authenticated","admin","writable"];
};
"/api/system/uiproc": {
- request: SystemUIProcessRequestInput;
+ request: EmptyRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "none";
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
diff --git a/kernel/api/contract_system_test.go b/kernel/api/contract_system_test.go
index a5597f0ac6..eb44186a05 100644
--- a/kernel/api/contract_system_test.go
+++ b/kernel/api/contract_system_test.go
@@ -229,6 +229,26 @@ func TestAPIContractSystemRawResponses(t *testing.T) {
requireAPIContract(t, "GET", "/api/system/bootProgressSSE", recorder)
}
+func TestAPIContractUIProcessQueryParameters(t *testing.T) {
+ const pid = "2147483001"
+ util.UIProcessIDs.Delete(pid)
+ t.Cleanup(func() { util.UIProcessIDs.Delete(pid) })
+ engine := gin.New()
+ engine.POST("/api/system/uiproc", addUIProcess)
+ for _, query := range []string{"", "?pid=" + pid} {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/system/uiproc"+query, strings.NewReader(`{"pid":"`+pid+`"}`)))
+ requireAPIContract(t, "POST", "/api/system/uiproc", recorder)
+ if recorder.Code != http.StatusOK || recorder.Body.Len() != 0 {
+ t.Fatalf("UI registration response changed: %d %s", recorder.Code, recorder.Body.String())
+ }
+ _, registered := util.UIProcessIDs.Load(pid)
+ if registered != (query != "") {
+ t.Fatalf("registration must use URL query parameters: query=%q registered=%v", query, registered)
+ }
+ }
+}
+
func TestAPIContractSystemUploadErrors(t *testing.T) {
previousConf := model.Conf
model.Conf = model.NewAppConf()
diff --git a/kernel/api/icon.go b/kernel/api/icon.go
index 8d2ae96d1d..95f0eb11bd 100644
--- a/kernel/api/icon.go
+++ b/kernel/api/icon.go
@@ -117,7 +117,7 @@ func darkenColor(hexColor string, factor float64) string {
return fmt.Sprintf("#%02X%02X%02X", r, g, b)
}
-var getDynamicIcon = contractHandler(apicontract.GetDynamicIcon, func(c *gin.Context, request apicontract.DynamicIconRequest) apicontract.Response[apicontract.BinaryContent] {
+var getDynamicIcon = contractHandler(apicontract.GetDynamicIcon, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.BinaryContent] {
// Add internal kernel API `/api/icon/getDynamicIcon` https://github.com/siyuan-note/siyuan/pull/12939
iconType := c.Query("type")
diff --git a/kernel/api/system.go b/kernel/api/system.go
index a2540e68ba..af1a44876e 100644
--- a/kernel/api/system.go
+++ b/kernel/api/system.go
@@ -1356,9 +1356,8 @@ var setNetworkProxy = contractHandler(apicontract.SetNetworkProxy, func(c *gin.C
return apicontract.Success(apicontract.Null{})
})
-var addUIProcess = contractHandler(apicontract.SystemAddUIProcess, func(c *gin.Context, request apicontract.SystemUIProcessRequest) apicontract.Response[apicontract.Null] {
- request.PID = c.Query("pid")
- pidInt, err := strconv.Atoi(request.PID)
+var addUIProcess = contractHandler(apicontract.SystemAddUIProcess, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.Null] {
+ pidInt, err := strconv.Atoi(c.Query("pid"))
if err != nil || 0 >= pidInt {
return apicontract.EmptyHTTPResponse[apicontract.Null](http.StatusOK)
}
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 1e1db8cd04..5ddbbe1457 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -1084,14 +1084,19 @@ var NetworkWebSocketProxy = define[EmptyRequest, ProxyFailure]("wsProxy", "/ws/n
var PluginPrivateService = define[EmptyRequest, PluginServiceContent]("pluginPrivateWebServer", "/plugin/private/:name/*path", AuthenticatedAccess|AdminAccess|WritableAccess, RawBody, PluginServiceOptions(), "ANY")
-var GetDynamicIcon = define[DynamicIconRequest, BinaryContent]("getDynamicIcon", "/api/icon/getDynamicIcon", AuthenticatedAccess, NoBody, ResponseOptions{Output: BinaryOutput, ErrorStatus: 200, ContentVariants: []HTTPContentVariant{{Status: 200, ContentType: "image/svg+xml"}}, EmptyResponseStatuses: []int{500}}, "GET")
+// GetDynamicIcon 从 URL 查询参数读取 type、color、date、lang、weekdayType、content 和 id,不读取请求体。
+// type 默认 1,lang 默认内核语言,weekdayType 默认 1;文字图标(type=8)跟随全局字体列表和首选字重。
+// 日期类图标使用内置字体和常规字重;未配置全局字体时使用内置列表,缺失字体由客户端继续回退。
+var GetDynamicIcon = define[EmptyRequest, BinaryContent]("getDynamicIcon", "/api/icon/getDynamicIcon", AuthenticatedAccess, NoBody, ResponseOptions{Output: BinaryOutput, ErrorStatus: 200, ContentVariants: []HTTPContentVariant{{Status: 200, ContentType: "image/svg+xml"}}, EmptyResponseStatuses: []int{500}}, "GET")
var ExtensionCopy = define[ExtensionCopyRequest, *ExtensionCopyData]("extensionCopy", "/api/extension/copy", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{DataOnError: true}, "POST")
var SystemBootProgressSSE = define[EmptyRequest, Null]("bootProgressSSE", "/api/system/bootProgressSSE", PublicAccess, NoBody, SSEOptions(SSEEvent[BootProgressData]("")), "GET")
var SystemGetBootAppearance = define[EmptyRequest, *SettingBootAppearance]("getBootAppearance", "/api/system/getBootAppearance", PublicAccess, NoBody, ResponseOptions{EmptyResponseStatuses: []int{403}}, "GET")
var SystemGetCaptcha = define[EmptyRequest, BinaryContent]("getCaptcha", "/api/system/getCaptcha", PublicAccess, NoBody, ResponseOptions{Output: BinaryOutput, ErrorStatus: 200, ContentVariants: []HTTPContentVariant{{Status: 200, ContentType: "image/png"}}, EmptyResponseStatuses: []int{500}}, "GET")
-var SystemOIDCCallback = define[SystemOIDCCallbackRequest, BinaryContent]("oidcCallback", "/api/system/oidc/callback", PublicAccess, NoBody, HTTPContentOptions(HTTPContentVariant{Status: 200, ContentType: "text/html"}), "GET")
+
+// SystemOIDCCallback 从 URL 查询参数读取 state、code 和 error,验证登录事务及会话绑定,不读取请求体。
+var SystemOIDCCallback = define[EmptyRequest, BinaryContent]("oidcCallback", "/api/system/oidc/callback", PublicAccess, NoBody, HTTPContentOptions(HTTPContentVariant{Status: 200, ContentType: "text/html"}), "GET")
var SystemAddCustomEmoji = define[SystemCustomEmojiRequest, SystemPathData]("addCustomEmoji", "/api/system/addCustomEmoji", AuthenticatedAccess|AdminAccess|WritableAccess, FormBody, ResponseOptions{AdditionalCodes: []int{400, 413}}, "POST")
var SystemCheckUpdate = define[SystemCheckUpdateRequest, Null]("checkUpdate", "/api/system/checkUpdate", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")
var SystemCheckWorkspaceDir = define[SystemPathRequest, SystemWorkspaceCheckData]("checkWorkspaceDir", "/api/system/checkWorkspaceDir", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
@@ -1131,7 +1136,9 @@ var SystemSetAppearanceMode = define[SystemAppearanceModeRequest, SystemAppearan
var SystemSetOIDC = define[SystemOIDCRequest, *SystemOIDC]("setOIDC", "/api/system/setOIDC", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{}, "POST")
var SystemSetUILayout = define[SystemUILayoutRequest, Null]("setUILayout", "/api/system/setUILayout", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
var SystemSetWorkspaceDir = define[SystemPathRequest, Null]("setWorkspaceDir", "/api/system/setWorkspaceDir", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
-var SystemAddUIProcess = define[SystemUIProcessRequest, Null]("addUIProcess", "/api/system/uiproc", AuthenticatedAccess, NoBody, ResponseOptions{EmptyResponseStatuses: []int{200}}, "POST")
+
+// SystemAddUIProcess 从 URL 查询参数读取正整数 pid,不读取请求体;无效 pid 或注册表已满时返回空 200。
+var SystemAddUIProcess = define[EmptyRequest, Null]("addUIProcess", "/api/system/uiproc", AuthenticatedAccess, NoBody, ResponseOptions{EmptyResponseStatuses: []int{200}}, "POST")
var PerformTransactions = define[PerformTransactionsRequest, []*Transaction]("performTransactions", "/api/transactions", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
var UndoState = define[TransactionUndoStateRequest, TransactionUndoState]("undoState", "/api/transactions/undoState", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")
diff --git a/kernel/apicontract/icon.go b/kernel/apicontract/icon.go
deleted file mode 100644
index 136236a26e..0000000000
--- a/kernel/apicontract/icon.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package apicontract
-
-// DynamicIconRequest 生成动态图标 SVG。文字图标(type=8)跟随全局默认字体列表和首选字重,日期类图标使用内置字体和常规字重。
-// 未配置全局字体时使用内置字体列表;字体由客户端解析,不嵌入字体文件,缺失字体时继续回退。
-type DynamicIconRequest struct {
- Type string `json:"type" api:"optional"`
- Color string `json:"color" api:"optional"`
- Date string `json:"date" api:"optional"`
- Lang string `json:"lang" api:"optional"`
- WeekdayType string `json:"weekdayType" api:"optional"`
- Content string `json:"content" api:"optional"`
- ID string `json:"id" api:"optional"`
-}
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 18519ccd68..19460de95d 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -23188,33 +23188,6 @@
],
"additionalProperties": false
},
- "DynamicIconRequestInput": {
- "type": "object",
- "properties": {
- "color": {
- "type": "string"
- },
- "content": {
- "type": "string"
- },
- "date": {
- "type": "string"
- },
- "id": {
- "type": "string"
- },
- "lang": {
- "type": "string"
- },
- "type": {
- "type": "string"
- },
- "weekdayType": {
- "type": "string"
- }
- },
- "additionalProperties": false
- },
"EditorReadOnlyRequestInput": {
"type": "object",
"properties": {
@@ -51303,42 +51276,6 @@
],
"additionalProperties": false
},
- "SystemOIDCCallbackRequestInput": {
- "type": "object",
- "properties": {
- "code": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ]
- },
- "error": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ]
- },
- "state": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ]
- }
- },
- "additionalProperties": false
- },
"SystemOIDCClaimRule": {
"type": "object",
"properties": {
@@ -52232,22 +52169,6 @@
},
"additionalProperties": false
},
- "SystemUIProcessRequestInput": {
- "type": "object",
- "properties": {
- "pid": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ]
- }
- },
- "additionalProperties": false
- },
"SystemWebDAV": {
"type": "object",
"properties": {
@@ -116204,7 +116125,7 @@
],
"body": "none",
"request": {
- "$ref": "#/$defs/DynamicIconRequestInput"
+ "$ref": "#/$defs/EmptyRequestInput"
},
"response": {
"anyOf": [
@@ -117076,7 +116997,7 @@
],
"body": "none",
"request": {
- "$ref": "#/$defs/SystemOIDCCallbackRequestInput"
+ "$ref": "#/$defs/EmptyRequestInput"
},
"response": {
"anyOf": [
@@ -172334,7 +172255,7 @@
],
"body": "none",
"request": {
- "$ref": "#/$defs/SystemUIProcessRequestInput"
+ "$ref": "#/$defs/EmptyRequestInput"
},
"response": {
"anyOf": [
diff --git a/kernel/apicontract/system.go b/kernel/apicontract/system.go
index 9dd44db6d4..63305e512e 100644
--- a/kernel/apicontract/system.go
+++ b/kernel/apicontract/system.go
@@ -115,9 +115,6 @@ type SystemAppearanceModeRequest struct {
type SystemAppearanceData struct {
Appearance *SettingAppearance `json:"appearance"`
}
-type SystemUIProcessRequest struct {
- PID string `json:"pid" api:"optional,nullable"`
-}
type SystemExitRequest struct {
Force bool `json:"force" api:"optional,nullable"`
ExecInstallPkg float64 `json:"execInstallPkg" api:"optional,nullable"`
@@ -148,11 +145,6 @@ type SystemOIDCStartData struct {
ExpiresIn int `json:"expiresIn"`
PollToken string `json:"pollToken,omitempty"`
}
-type SystemOIDCCallbackRequest struct {
- State string `json:"state" api:"optional,nullable"`
- Code string `json:"code" api:"optional,nullable"`
- Error string `json:"error" api:"optional,nullable"`
-}
type SystemOIDCMobileRequest struct {
CallbackURL string `json:"callbackURL" api:"optional,nullable"`
parseError error
diff --git a/kernel/apicontract/system_test.go b/kernel/apicontract/system_test.go
index b0a92a956c..801628d37b 100644
--- a/kernel/apicontract/system_test.go
+++ b/kernel/apicontract/system_test.go
@@ -8,6 +8,14 @@ import (
"testing"
)
+func TestNoBodyContractRequests(t *testing.T) {
+ for _, definition := range Definitions() {
+ if definition.Body == NoBody && definition.Request != reflect.TypeFor[EmptyRequest]() {
+ t.Errorf("no-body endpoint %s declares request fields: %v", definition.Path, definition.Request)
+ }
+ }
+}
+
func TestAPIContractSystemRequestCompatibility(t *testing.T) {
for _, body := range []string{`{}`, `null`, `{"force":null}`, `{"force":true}`, `{"force":true} {}`, `{"unknown":1e1000}`, ``} {
var legacy map[string]interface{}
diff --git a/kernel/model/oidc.go b/kernel/model/oidc.go
index 4c8f4a8409..ce2875735c 100644
--- a/kernel/model/oidc.go
+++ b/kernel/model/oidc.go
@@ -230,11 +230,8 @@ func OIDCStart(c *gin.Context, request apicontract.SystemOIDCStartRequest) (ret
return apicontract.Success(data)
}
-func OIDCCallback(c *gin.Context, request apicontract.SystemOIDCCallbackRequest) apicontract.Response[apicontract.BinaryContent] {
- request.State = c.Query("state")
- request.Code = c.Query("code")
- request.Error = c.Query("error")
- state := request.State
+func OIDCCallback(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.BinaryContent] {
+ state := c.Query("state")
workspaceSession := util.GetWorkspaceSession(util.GetSession(c))
transaction, repeated, err := claimOIDCTransaction(c.Request.Context(), state, workspaceSession.OIDCBinding, true)
if err != nil {
@@ -255,13 +252,13 @@ func OIDCCallback(c *gin.Context, request apicontract.SystemOIDCCallbackRequest)
return writeOIDCCallbackPage(c, false, oidcUserMessage())
}
}
- if providerError := request.Error; providerError != "" {
+ if providerError := c.Query("error"); providerError != "" {
logging.LogWarnf("OIDC provider rejected the login: %s", providerError)
message := oidcUserMessage()
completeOIDCTransaction(transaction.State, false, message)
return writeOIDCCallbackPage(c, false, message)
}
- if err = finishOIDCExchange(c, transaction, request.Code); err != nil {
+ if err = finishOIDCExchange(c, transaction, c.Query("code")); err != nil {
logging.LogErrorf("finish OIDC authorization code exchange failed: %s", err)
completeOIDCTransaction(transaction.State, false, oidcUserMessage())
return writeOIDCCallbackPage(c, false, oidcUserMessage())