An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:recycle: Migrate file API contracts https://github.com/siyuan-note/siyuan/issues/19378
Daniel91aa8af7b0f0
diff --git a/app/src/boot/onGetConfig.ts b/app/src/boot/onGetConfig.tsindex 4fe7de0529..81fe8e81c0 100644--- a/app/src/boot/onGetConfig.ts+++ b/app/src/boot/onGetConfig.ts@@ -285,6 +285,9 @@ ${response.data.replace("%pages", "<span class=totalPages></span>").replace("%pa});let pdfFilePath = path.join(savePath, replaceLocalPath(ipcData.rootTitle) + ".pdf");const responseUnique = await fetchSyncPost("/api/file/getUniqueFilename", {path: pdfFilePath});+ if (responseUnique.code !== 0 || !responseUnique.data) {+ return;+ }pdfFilePath = responseUnique.data.path;fetchPost("/api/export/exportHTML", {id: ipcData.rootId,diff --git a/app/src/plugin/index.ts b/app/src/plugin/index.tsindex be4e750def..d179e26bcf 100644--- a/app/src/plugin/index.ts+++ b/app/src/plugin/index.ts@@ -2,6 +2,7 @@ import {sendGlobalShortcut} from "../boot/globalEvent/globalShortcut";import type {App} from "../index";import {EventBus} from "./EventBus";import {fetchPost} from "../util/fetch";+import {ContractFormData} from "../util/contractFormData";import {isMobile, isWindow} from "../util/functions";import {getAllEditor, getAllModels} from "../layout/getAll";/// #if !MOBILE@@ -461,11 +462,12 @@ export class Plugin {});return;}- const formData = new FormData();- formData.append("path", pathString);- formData.append("file", file);- formData.append("isDir", "false");- formData.append("app", Constants.SIYUAN_APPID);+ const formData = new ContractFormData({+ path: pathString,+ file,+ isDir: "false",+ app: Constants.SIYUAN_APPID,+ });fetchPost("/api/file/putFile", formData, (response) => {this.data[storageName] = data;resolve(response);diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 79232a7630..aabead1cc0 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -132,6 +132,10 @@ export type CloudSync = { "cloudName": string; "hSize": string; "saveDir": strinexport type ContentWordCountRequestInput = { "content": string; "reqId"?: JSONValue | null; };+export type CopyFileRequestInput = { "dest": string; "src": string; };++export type CopyFilesRequestInput = { "destDir": string; "srcs": Array<string>; };+export type CopyStdMarkdownRequestInput = { "adjustHeadingLevel"?: boolean | null; "assetsDestSpace2Underscore"?: boolean | null; "fillCSSVar"?: boolean | null; "id": string; "imgTag"?: boolean | null; };export type CreateEncryptedNotebookRequestInput = { "name": string; "password": string; };@@ -164,6 +168,8 @@ export type DailyNoteBlockRequestInput = { "data": string; "dataType": string; "export type DeleteBlockRequestInput = { "id": string; };+export type DirectoryEntry = { "isDir": boolean; "isSymlink": boolean; "name": string; "updated": number; };+export type DocAttrView = { "id": string; "name": string; };export type DocHeadingLevelData = { "counts": Array<number>; "title": string; "transaction": BlockTransaction | null; "withSubheadingCounts": Array<number>; };@@ -190,6 +196,10 @@ export type EncryptedNotebookStatusData = { "boxes": Array<EncryptedNotebookStatexport type FileAnnotationRefRequestInput = { "id": string; "notebook"?: string | null; };+export type FilePathData = { "path": string; };++export type FilePathRequestInput = { "path": string; };+export type FullBlockInfo = { "box": string; "path": string; "rootChildID": string; "rootID": string; "rootIcon": string; "rootTitle": string; "rootTitleEmpty": boolean; };export type GetSnippetRequestInput = { "enabled": number; "keyword"?: string | null; "type": string; };@@ -328,6 +338,10 @@ export type PrependBlockRequestInput = { "data": string; "dataType": string; "paexport type PublishedBlockInfo = { "publishAccessRequired": true; "rootID": string; "rootIcon": string; "rootTitle": string; "rootTitleEmpty": boolean; };+export type PutFileRequestInput = { "app"?: string; "file"?: Blob; "isDir"?: string; "modTime"?: string; "path"?: string; };++export type ReadDirectoryRequestInput = { "path": string; };+export type RecentDoc = { "closedAt"?: number; "icon"?: string; "openAt"?: number; "rootID": string; "title"?: string; "viewedAt"?: number; };export type RecentDocUpdateRequestInput = { "rootID"?: string | null; };@@ -350,12 +364,16 @@ export type RemoveBookmarkRequestInput = { "bookmark": string; };export type RemoveCriterionRequestInput = { "name": string; };+export type RemoveFileRequestInput = { "app"?: string | null; "path": string; };+export type RemoveShorthandsRequestInput = { "ids": Array<string>; };export type RemoveTagRequestInput = { "label": string; };export type RenameBookmarkRequestInput = { "newBookmark": string; "oldBookmark": string; };+export type RenameFileRequestInput = { "newPath": string; "path": string; };+export type RenameNotebookRequestInput = { "name": string; "notebook": string; };export type RenameTagRequestInput = { "newLabel": string; "oldLabel": string; };@@ -682,15 +700,6 @@ export type APILegacyPOSTPath ="/api/export/preview" |"/api/export/processPDF" |"/api/extension/copy" |- "/api/file/copyFile" |- "/api/file/getFile" |- "/api/file/getUniqueFilename" |- "/api/file/globalCopyFiles" |- "/api/file/putFile" |- "/api/file/readDir" |- "/api/file/removeFile" |- "/api/file/renameFile" |- "/api/file/workspaceCopyFiles" |"/api/filetree/authFilePublishAccess" |"/api/filetree/changeSort" |"/api/filetree/createDailyNote" |@@ -1376,6 +1385,52 @@ export interface APIPOSTRoutes {response: { "code": 0; "data": PandocData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };body: "json";};+ "/api/file/copyFile": {+ request: CopyFileRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | -2; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/file/getFile": {+ request: FilePathRequestInput;+ response: Blob | { "code": -1 | -3 | 403 | 404 | 409 | 500 | 503; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ output: "binary";+ };+ "/api/file/getUniqueFilename": {+ request: FilePathRequestInput;+ response: { "code": 0; "data": FilePathData; "msg": string; } | { "code": -1 | -3; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/file/globalCopyFiles": {+ request: CopyFilesRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | -2 | -3 | 403; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/file/putFile": {+ request: PutFileRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | -3 | 400 | 403 | 500; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "form";+ };+ "/api/file/readDir": {+ request: ReadDirectoryRequestInput;+ response: { "code": 0; "data": Array<DirectoryEntry>; "msg": string; } | { "code": -1 | -3 | 403 | 404 | 409 | 500; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/file/removeFile": {+ request: RemoveFileRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | -3 | 403 | 404 | 500; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/file/renameFile": {+ request: RenameFileRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | -3 | 403 | 404 | 409 | 500; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/file/workspaceCopyFiles": {+ request: CopyFilesRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | -2 | -3 | 403; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };"/api/filetree/getPinnedDocs": {request: EmptyRequestInput;response: { "code": 0; "data": Array<PinnedDoc>; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -1970,7 +2025,7 @@ type APIContract = {request: unknown; response: unknown; body: string};export interface APIFormData<Request> extends FormData {readonly apiRequest: Request;}-type APIRequestArgs<C extends APIContract> = C["body"] extends "multipart"+type APIRequestArgs<C extends APIContract> = C["body"] extends "multipart" | "form"? [data: APIFormData<C["request"]>]: C["body"] extends "json" | "structJSON"? [data: C["request"]]@@ -1981,7 +2036,7 @@ export type APICallbackResponse<R> = R extends {code: infer C extends number}: never;type APIPostTail<C extends APIContract> = [- cb?: (response: APICallbackResponse<C["response"]>) => void,+ cb?: (response: C extends {output: "binary"} ? JSONValue : APICallbackResponse<C["response"]>) => void,headers?: Record<string, string>,failCallback?: (response: APIFetchFailure) => void,signal?: AbortSignal,@@ -2012,7 +2067,9 @@ export type FetchSyncPost<Legacy = APILegacyResponse> = <Path extends string>(? [...APIRequestArgs<APIPOSTRoutes[Path]>, ...APISyncTail]: Path extends APILegacyPOSTPath ? [data?: any, ...tail: APISyncTail]: string extends Path ? [data?: any, ...tail: APISyncTail] : never-) => Promise<Path extends keyof APIPOSTRoutes ? APIPOSTRoutes[Path]["response"] | APITransportError : Legacy>;+) => Promise<Path extends keyof APIPOSTRoutes+ ? APIPOSTRoutes[Path] extends {output: "binary"} ? JSONValue : APIPOSTRoutes[Path]["response"] | APITransportError+ : Legacy>;export type FetchGet<Legacy = APILegacyResponse | string> = <Path extends string>(url: Path,diff --git a/app/src/util/fetch.test.ts b/app/src/util/fetch.test.tsindex 0efa4acd47..ddaeb11afe 100644--- a/app/src/util/fetch.test.ts+++ b/app/src/util/fetch.test.ts@@ -96,7 +96,7 @@ it("preserves raw file text and routes HTTP 202 file errors to the failure callbassert.deepEqual(received, failure);});-it("preserves FormData request bodies for unmigrated upload endpoints", async () => {+it("preserves FormData request bodies for upload endpoints", async () => {const body = new FormData();body.append("path", "file.txt");const {fetchPost} = loadFetchPost(async (_url, options) => {diff --git a/app/tests/api-contract.types.ts b/app/tests/api-contract.types.tsindex 4b0c75f776..f7f1e4b29d 100644--- a/app/tests/api-contract.types.ts+++ b/app/tests/api-contract.types.ts@@ -1,4 +1,4 @@-import type {APIPOSTRoutes, FetchGet, FetchPost, FetchSyncPost} from "../src/types/api";+import type {APIPOSTRoutes, FetchGet, FetchPost, FetchSyncPost, JSONValue} from "../src/types/api";import {ContractFormData} from "../src/util/contractFormData";declare const fetchPost: FetchPost;@@ -6,6 +6,23 @@ declare const fetchGet: FetchGet;declare const fetchSyncPost: FetchSyncPost;declare const dynamicURL: string;+fetchPost("/api/file/getFile", {path: "data/storage/plugin.json"}, response => {+ const content: JSONValue = response;+ // @ts-expect-error 文件内容可能是文本、数组或空值,不能直接按信封读取。+ void response.data;+ void content;+});+// @ts-expect-error 文件路径不可缺省。+fetchPost("/api/file/getFile", {});+// @ts-expect-error 文件路径必须为字符串。+fetchPost("/api/file/getFile", {path: 1});+fetchPost("/api/file/putFile", new ContractFormData({path: "temp/dir", isDir: "true"}));+fetchPost("/api/file/putFile", new ContractFormData({path: "temp/file", file: new Blob()}));+// @ts-expect-error 上传文件字段必须为二进制文件。+fetchPost("/api/file/putFile", new ContractFormData({file: "file"}));+// @ts-expect-error 表单布尔值以字符串传输。+fetchPost("/api/file/putFile", new ContractFormData({isDir: true}));+fetchSyncPost("/api/notebook/importNotebookCryptoBackup", new ContractFormData({file: new Blob(), password: "password"}));// @ts-expect-error 上传请求必须包含文件。fetchSyncPost("/api/notebook/importNotebookCryptoBackup", new ContractFormData({password: "password"}));diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.mdindex 4688c01cae..0a87f0f5f2 100644--- a/docs/API-CONTRACTS.md+++ b/docs/API-CONTRACTS.md@@ -54,6 +54,10 @@ Storage contracts keep arbitrary JSON limited to storage values; keys, recent do## Multipart requests+`BinaryOutput` declares raw file responses with `BinaryContent` and `SuccessBinary`. The adapter preserves bytes and media type, while `ErrorStatus` declares the distinct HTTP status for JSON failures (`getFile` uses 202). The schema records binary success and typed JSON errors; `ValidateHTTPResponse` checks the status and media type before validating an error envelope. Generated route responses expose `Blob`, while the existing fetch helpers expose `JSONValue` because they parse file contents as text or JSON according to their existing behavior. JSON file contents can contain arbitrary JSON; this does not relax the structured error contract.++`FormBody` supports endpoints such as `putFile` that accept both URL-encoded and multipart forms. It preserves Gin `PostForm` parsing, including first-value selection and available fields after parsing errors. Conditional requirements and delayed validation remain in the handler: directory creation does not require a file, and modification-time validation occurs after writing. The generated caller type uses the same typed form interface as multipart uploads.+Use `MultipartBody` for file uploads. Request structs declare string fields and `*multipart.FileHeader` fields using their wire names; file schemas use `type: string` and `format: binary`, generating `Blob` declarations. The adapter retains Gin multipart parsing and binds the first value for repeated fields. File contents remain available through `Open`, so handlers preserve their read and recovery logic. Unsupported field types and binding options fail generation.Frontend callers construct `ContractFormData` from typed fields before passing it to the existing fetch functions. The generated signatures require the endpoint's fields and distinguish file values from strings; raw `FormData` cannot satisfy a migrated upload contract. Optional fields are omitted and string values are not trimmed. Plugin callers can implement the generated `APIFormData<Request>` interface when constructing their forms.diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.mdindex ec35a4d045..af4808599a 100644--- a/docs/API-CONTRACTS.zh-CN.md+++ b/docs/API-CONTRACTS.zh-CN.md@@ -54,6 +54,10 @@## 文件上传请求+`BinaryOutput` 通过 `BinaryContent` 和 `SuccessBinary` 声明原始文件响应。适配器保留字节和媒体类型,`ErrorStatus` 声明 JSON 失败响应使用的独立 HTTP 状态(`getFile` 使用 202)。schema 记录二进制成功响应和类型化 JSON 错误;`ValidateHTTPResponse` 先检查状态和媒体类型,再验证错误信封。生成的路由响应使用 `Blob`,现有 fetch 函数则使用 `JSONValue`,因为它们保留将文件内容解析为文本或 JSON 的行为。JSON 文件内容可以是任意 JSON,但结构化错误契约不因此放宽。++`FormBody` 用于 `putFile` 等同时接受 URL 编码表单和多部分表单的接口。它保留 Gin `PostForm` 的解析行为,包括重复字段取首值,以及解析失败后已经取得的字段。条件必填和延迟校验仍由处理函数负责:创建目录不要求上传文件,修改时间在写入后校验。生成的调用类型与多部分上传使用相同的类型化表单接口。+文件上传使用 `MultipartBody`。请求结构体以线协议字段名声明字符串和 `*multipart.FileHeader` 字段;文件 schema 使用 `type: string` 与 `format: binary`,生成 `Blob` 类型。适配器保留 Gin 的表单解析方式,重复字段取首值;文件内容继续通过 `Open` 读取,处理函数保留读取及恢复逻辑。未支持的字段类型和绑定选项会使生成失败。前端从类型化字段构造 `ContractFormData`,再交给现有请求函数。生成签名检查端点所需字段并区分文件与字符串,普通 `FormData` 不能满足已迁移上传接口的契约。可缺省字段不写入表单,字符串不裁剪空白。插件调用方构造表单时可实现生成的 `APIFormData<Request>` 接口。diff --git a/kernel/api/contract.go b/kernel/api/contract.goindex ce231a51a4..108e9300cd 100644--- a/kernel/api/contract.go+++ b/kernel/api/contract.go@@ -3,7 +3,7 @@ package apiimport ("encoding/base64""fmt"- "net/http"+ "mime/multipart""github.com/88250/gulu""github.com/gin-gonic/gin"@@ -41,16 +41,32 @@ func notebookConfContract(value *conf.BoxConf) *apicontract.NotebookConf {func contractHandler[Request, Data any](endpoint apicontract.Endpoint[Request, Data],handler func(*gin.Context, Request) apicontract.Response[Data], beforeDecode ...func(*gin.Context) *apicontract.Response[Data]) gin.HandlerFunc {return func(c *gin.Context) {+ writeResponse := func(response apicontract.Response[Data]) {+ status := endpoint.Status(response)+ if content := response.Binary(); content != nil {+ c.Data(status, content.ContentType, content.Bytes)+ return+ }+ c.JSON(status, response)+ }// 保留在读取请求体前完成的角色判断或大小限制,提前响应也使用相同的载荷类型。for _, before := range beforeDecode {if response := before(c); response != nil {- c.JSON(http.StatusOK, response)+ writeResponse(*response)return}}var request Requestvar err error- if endpoint.Definition().Body == apicontract.MultipartBody {+ if endpoint.Definition().Body == apicontract.FormBody {+ // 保留 PostForm 对普通表单、重复字段和解析失败后已有字段的处理。+ c.PostForm("")+ form := &multipart.Form{Value: c.Request.PostForm}+ if c.Request.MultipartForm != nil {+ form.File = c.Request.MultipartForm.File+ }+ request, err = endpoint.DecodeMultipart(form)+ } else if endpoint.Definition().Body == apicontract.MultipartBody {form, parseErr := c.MultipartForm()if parseErr != nil {err = parseErr@@ -61,10 +77,10 @@ func contractHandler[Request, Data any](endpoint apicontract.Endpoint[Request, Drequest, err = endpoint.Decode(c.Request.Body)}if err != nil {- c.JSON(http.StatusOK, endpoint.DecodeFailure(err))+ writeResponse(endpoint.DecodeFailure(err))return}- c.JSON(http.StatusOK, handler(c, request))+ writeResponse(handler(c, request))}}diff --git a/kernel/api/contract_file_test.go b/kernel/api/contract_file_test.gonew file mode 100644index 0000000000..08fd4d6055--- /dev/null+++ b/kernel/api/contract_file_test.go@@ -0,0 +1,236 @@+package api++import (+ "bytes"+ "encoding/json"+ "mime/multipart"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractFileMalformedBody(t *testing.T) {+ engine := gin.New()+ engine.POST("/api/file/readDir", readDir)+ engine.POST("/api/file/renameFile", renameFile)+ engine.POST("/api/file/removeFile", removeFile)+ engine.POST("/api/file/getUniqueFilename", getUniqueFilename)+ for _, path := range []string{"/api/file/readDir", "/api/file/renameFile", "/api/file/removeFile", "/api/file/getUniqueFilename"} {+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", path, strings.NewReader("{")))+ requireAPIContract(t, "POST", path, recorder)+ var response struct {+ Code int `json:"code"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != -1 {+ t.Fatalf("expected one valid error response: %s, %v", recorder.Body.String(), err)+ }+ }+}++func TestAPIContractGetFileTransport(t *testing.T) {+ originalWorkspace, originalData := util.WorkspaceDir, util.DataDir+ util.WorkspaceDir = t.TempDir()+ util.DataDir = filepath.Join(util.WorkspaceDir, "data")+ t.Cleanup(func() { util.WorkspaceDir, util.DataDir = originalWorkspace, originalData })+ engine := gin.New()+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleAdministrator) })+ engine.POST("/api/file/getFile", getFile)+ for _, entry := range []struct{ name, content, media string }{+ {"file.txt", "plain text", "text/plain"},+ {"file.json", `{"nested":[1,true,null]}`, "application/json"},+ {"file.bin", "\x00\xff\x01\x02", "application/octet-stream"},+ } {+ if err := os.WriteFile(filepath.Join(util.WorkspaceDir, entry.name), []byte(entry.content), 0644); err != nil {+ t.Fatal(err)+ }+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/file/getFile", strings.NewReader(`{"path":" `+entry.name+` "}`)))+ requireAPIContract(t, "POST", "/api/file/getFile", recorder)+ if recorder.Code != 200 || recorder.Body.String() != entry.content || !strings.HasPrefix(recorder.Header().Get("Content-Type"), entry.media) {+ t.Fatalf("raw response changed: %d %v %q", recorder.Code, recorder.Header(), recorder.Body.String())+ }+ }+ for _, entry := range []struct {+ body string+ code int+ }{+ {"{", -1}, {`{}`, -1}, {`{"path":null}`, -1}, {`{"path":false}`, -1},+ {`{"path":"missing.txt"}`, 404}, {`{"path":"."}`, 409},+ } {+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/file/getFile", strings.NewReader(entry.body)))+ requireAPIContract(t, "POST", "/api/file/getFile", recorder)+ var response struct {+ Code int `json:"code"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || recorder.Code != 202 || response.Code != entry.code {+ t.Fatalf("file failure changed: %d %s, %v", recorder.Code, recorder.Body.String(), err)+ }+ }+}++func TestAPIContractFileEncryptedPath(t *testing.T) {+ _, boxID := setupArchiveWorkspace(t)+ originalConf := model.Conf+ model.Conf = model.NewAppConf()+ t.Cleanup(func() { model.Conf = originalConf })+ filePath := "data/" + boxID + "/existing.sy"+ absPath := filepath.Join(util.WorkspaceDir, filePath)+ if err := os.WriteFile(absPath, []byte("ciphertext"), 0600); err != nil {+ t.Fatal(err)+ }+ engine := gin.New()+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleAdministrator) })+ engine.POST("/api/file/getFile", getFile)+ engine.POST("/api/file/putFile", putFile)+ engine.POST("/api/file/removeFile", removeFile)+ engine.POST("/api/file/renameFile", renameFile)+ engine.POST("/api/file/readDir", readDir)+ for _, entry := range []struct{ route, body, media string }{+ {"getFile", `{"path":"` + filePath + `"}`, "application/json"},+ {"putFile", "path=" + filePath + "&isDir=true", "application/x-www-form-urlencoded"},+ {"removeFile", `{"path":"` + filePath + `"}`, "application/json"},+ {"renameFile", `{"path":"` + filePath + `","newPath":"temp/moved.sy"}`, "application/json"},+ {"readDir", `{"path":"data/` + boxID + `"}`, "application/json"},+ } {+ path := "/api/file/" + entry.route+ request := httptest.NewRequest("POST", path, strings.NewReader(entry.body))+ request.Header.Set("Content-Type", entry.media)+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, request)+ requireAPIContract(t, "POST", path, recorder)+ var response struct {+ Code int `json:"code"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != -3 {+ t.Fatalf("encrypted path admitted by %s: %s, %v", path, recorder.Body.String(), err)+ }+ }+ content, err := os.ReadFile(absPath)+ if err != nil || string(content) != "ciphertext" {+ t.Fatalf("encrypted source changed: %q, %v", content, err)+ }+}++func TestAPIContractPutFileFormCompatibility(t *testing.T) {+ originalWorkspace := util.WorkspaceDir+ util.WorkspaceDir = t.TempDir()+ t.Cleanup(func() { util.WorkspaceDir = originalWorkspace })+ engine := gin.New()+ engine.POST("/api/file/putFile", putFile)+ for _, entry := range []struct {+ name, body, created string+ code int+ }{+ {"missing path", "isDir=true", "", 400},+ {"directory without file", "path=temp/first&path=temp/ignored&isDir=true&modTime=1700000000123", "temp/first", 0},+ {"invalid bool requires file", "path=temp/missing&isDir=invalid", "", 400},+ {"timestamp checked after creation", "path=temp/created&isDir=true&modTime=invalid", "temp/created", 500},+ } {+ t.Run(entry.name, func(t *testing.T) {+ request := httptest.NewRequest("POST", "/api/file/putFile", strings.NewReader(entry.body))+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, request)+ requireAPIContract(t, "POST", "/api/file/putFile", recorder)+ var response struct {+ Code int `json:"code"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != entry.code {+ t.Fatalf("unexpected form response: %s, %v", recorder.Body.String(), err)+ }+ if entry.created != "" {+ info, err := os.Stat(filepath.Join(util.WorkspaceDir, entry.created))+ if err != nil || !info.IsDir() {+ t.Fatalf("directory not created: %v", err)+ }+ if entry.code == 0 && info.ModTime().UnixMilli() != 1700000000123 {+ t.Fatalf("modification time changed: %s", info.ModTime())+ }+ }+ })+ }+ if _, err := os.Stat(filepath.Join(util.WorkspaceDir, "temp/ignored")); !os.IsNotExist(err) {+ t.Fatalf("repeated path must use first value: %v", err)+ }+}++func TestAPIContractPutFileMultipartCompatibility(t *testing.T) {+ originalWorkspace, originalData := util.WorkspaceDir, util.DataDir+ util.WorkspaceDir = t.TempDir()+ util.DataDir = filepath.Join(util.WorkspaceDir, "data")+ t.Cleanup(func() { util.WorkspaceDir, util.DataDir = originalWorkspace, originalData })+ var body bytes.Buffer+ writer := multipart.NewWriter(&body)+ for _, field := range [][2]string{{"path", " temp/upload.txt "}, {"isDir", "false"}, {"modTime", "1700000000123"}} {+ if err := writer.WriteField(field[0], field[1]); err != nil {+ t.Fatal(err)+ }+ }+ for _, content := range []string{"first file", "ignored file"} {+ part, err := writer.CreateFormFile("file", "upload.txt")+ if err != nil {+ t.Fatal(err)+ }+ if _, err = part.Write([]byte(content)); err != nil {+ t.Fatal(err)+ }+ }+ if err := writer.Close(); err != nil {+ t.Fatal(err)+ }+ engine := gin.New()+ engine.POST("/api/file/putFile", putFile)+ request := httptest.NewRequest("POST", "/api/file/putFile", &body)+ request.Header.Set("Content-Type", writer.FormDataContentType())+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, request)+ requireAPIContract(t, "POST", "/api/file/putFile", recorder)+ var response struct {+ Code int `json:"code"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 {+ t.Fatalf("upload failed: %s, %v", recorder.Body.String(), err)+ }+ path := filepath.Join(util.WorkspaceDir, "temp/upload.txt")+ content, err := os.ReadFile(path)+ if err != nil || string(content) != "first file" {+ t.Fatalf("uploaded content changed: %q, %v", content, err)+ }+ info, err := os.Stat(path)+ if err != nil || info.ModTime().UnixMilli() != 1700000000123 {+ t.Fatalf("uploaded modification time changed: %v, %v", info, err)+ }+}++func TestAPIContractFileCopyErrors(t *testing.T) {+ engine := gin.New()+ engine.POST("/api/file/globalCopyFiles", globalCopyFiles)+ engine.POST("/api/file/workspaceCopyFiles", workspaceCopyFiles)+ engine.POST("/api/file/copyFile", copyFile)+ for _, entry := range []struct{ path, body, message string }{+ {"/api/file/globalCopyFiles", `{"srcs":["relative.txt"],"destDir":""}`, "Field [srcs]: each path must be absolute"},+ {"/api/file/globalCopyFiles", `{"srcs":[],"destDir":""}`, "Field [srcs] must not be empty"},+ {"/api/file/workspaceCopyFiles", `{"srcs":[" "],"destDir":""}`, "Field [srcs]: path must not be empty"},+ {"/api/file/workspaceCopyFiles", `{"srcs":[null],"destDir":""}`, "Field [srcs]: each element should be of type [String]"},+ {"/api/file/copyFile", `{"src":"asset.png","dest":"relative.png"}`, "Field [dest]: path must be absolute"},+ } {+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", entry.path, strings.NewReader(entry.body)))+ requireAPIContract(t, "POST", entry.path, recorder)+ var response struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != -1 || response.Msg != entry.message {+ t.Fatalf("copy error changed: %s, %v", recorder.Body.String(), err)+ }+ }+}diff --git a/kernel/api/contract_test.go b/kernel/api/contract_test.goindex 656d92f726..547932b183 100644--- a/kernel/api/contract_test.go+++ b/kernel/api/contract_test.go@@ -3,7 +3,6 @@ package apiimport ("context""encoding/json"- "net/http""net/http/httptest""os""os/exec"@@ -25,14 +24,11 @@ import (func requireAPIContract(t *testing.T, method, path string, recorder *httptest.ResponseRecorder) {t.Helper()- if recorder.Code != http.StatusOK || !strings.HasPrefix(recorder.Header().Get("Content-Type"), "application/json") {- t.Fatalf("unexpected transport response for %s: %d %v", path, recorder.Code, recorder.Header())- }bundle, err := apicontract.BuildBundle()if err != nil {t.Fatal(err)}- if err := bundle.ValidateResponse(method, path, recorder.Body.Bytes()); err != nil {+ if err := bundle.ValidateHTTPResponse(method, path, recorder.Code, recorder.Header().Get("Content-Type"), recorder.Body.Bytes()); err != nil {t.Fatalf("response violates %s: %v\n%s", path, err, recorder.Body.String())}}diff --git a/kernel/api/file.go b/kernel/api/file.goindex 9577b0a2b2..97eac5cd9c 100644--- a/kernel/api/file.go+++ b/kernel/api/file.go@@ -33,6 +33,7 @@ import ("github.com/gin-gonic/gin""github.com/siyuan-note/filelock""github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/apicontract""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/util")@@ -97,31 +98,16 @@ func copyDecryptedAsset(src, dest string) error {return nil}-func getUniqueFilename(c *gin.Context) {+var getUniqueFilename = contractHandler(apicontract.GetUniqueFilename, func(c *gin.Context, request apicontract.FilePathRequest) apicontract.Response[apicontract.FilePathData] {ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)-- arg, ok := util.JsonArg(c, ret)- if !ok {- return- }-- var filePath string- if !util.ParseJsonArgs(arg, ret,- util.BindJsonArg("path", &filePath, true, true),- ) {- return- }-+ filePath := request.Pathif rejectEncryptedBoxPath(filePath) {ret.Code = -3ret.Msg = model.Conf.Language(321)- return- }- ret.Data = map[string]any{- "path": util.GetUniqueFilename(filePath),+ return contractFailure[apicontract.FilePathData](ret)}-}+ return apicontract.Success(apicontract.FilePathData{Path: util.GetUniqueFilename(filePath)})+})// prepareFileAssets 在原始文件 API 完成权限校验后补齐目录或文件的资源内容。func prepareFileAssets(absPath string) error {@@ -145,45 +131,20 @@ func prepareFileAssets(absPath string) error {return model.EnsureAssetPrefixLocal(absPath)}-func globalCopyFiles(c *gin.Context) {+var globalCopyFiles = contractHandler(apicontract.GlobalCopyFiles, func(c *gin.Context, request apicontract.CopyFilesRequest) apicontract.Response[apicontract.Null] {ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)var changedPaths []stringdefer func() {model.IncSyncIfNeeded(changedPaths...)}()- arg, ok := util.JsonArg(c, ret)- if !ok {- return- }-- var srcsArg []any- var destDirArg string- if !util.ParseJsonArgs(arg, ret,- util.BindJsonArg("srcs", &srcsArg, true, true), // 绝对路径- util.BindJsonArg("destDir", &destDirArg, true, false), // 相对于工作空间的路径- ) {- return- }-- var srcs []string- for _, s := range srcsArg {- str, elemOk := s.(string)- if !elemOk {- ret.Code = -1- ret.Msg = "Field [srcs]: each element should be of type [String]"- return- }- srcs = append(srcs, str)- }-+ srcs, destDirArg := request.Srcs, request.DestDirfor i, src := range srcs {if !filepath.IsAbs(src) {logging.LogErrorf("global copy files src [%s] is not an absolute path", src)ret.Code = -1ret.Msg = "Field [srcs]: each path must be absolute"- return+ return contractFailure[apicontract.Null](ret)}absSrc, _ := filepath.Abs(src)@@ -192,24 +153,24 @@ func globalCopyFiles(c *gin.Context) {logging.LogErrorf("refuse to copy sensitive file [%s]", src)ret.Code = -2ret.Msg = fmt.Sprintf("refuse to copy sensitive file [%s]", src)- return+ return contractFailure[apicontract.Null](ret)}if rejectEncryptedBoxPath(absSrc) {ret.Code = -3ret.Msg = model.Conf.Language(321)- return+ return contractFailure[apicontract.Null](ret)}if err := prepareFileAssets(absSrc); err != nil {ret.Code = -1ret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}if !filelock.IsExist(absSrc) {ret.Code = -1ret.Msg = fmt.Sprintf("file [%s] does not exist", src)- return+ return contractFailure[apicontract.Null](ret)}srcs[i] = absSrc}@@ -218,32 +179,32 @@ func globalCopyFiles(c *gin.Context) {if err != nil {ret.Code = http.StatusForbiddenret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}// 在 MkdirAll 前拒绝加密笔记本目录,避免在加密笔记本内创建明文目录if rejectEncryptedBoxPath(destDir) {ret.Code = -1ret.Msg = "copying encrypted notebook files is not supported via this API"- return+ return contractFailure[apicontract.Null](ret)}if filelock.IsExist(destDir) {destInfo, statErr := os.Stat(destDir)if statErr != nil {ret.Code = -1ret.Msg = statErr.Error()- return+ return contractFailure[apicontract.Null](ret)}if !destInfo.IsDir() {ret.Code = -1ret.Msg = fmt.Sprintf("Field [destDir]: path [%s] is not a directory", destDirArg)- return+ return contractFailure[apicontract.Null](ret)}} else {if err = os.MkdirAll(destDir, 0755); err != nil {logging.LogErrorf("make dir [%s] failed: %s", destDir, err)ret.Code = -1ret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}}@@ -252,91 +213,61 @@ func globalCopyFiles(c *gin.Context) {if rejectEncryptedBoxPath(dest) {ret.Code = -3ret.Msg = model.Conf.Language(321)- return+ return contractFailure[apicontract.Null](ret)}// 拒绝目标已存在的 symlink:os.Create 会跟随 symlink,可能写入加密笔记本内部if li, lerr := os.Lstat(dest); lerr == nil && li.Mode()&os.ModeSymlink != 0 {ret.Code = -1ret.Msg = "destination path is a symlink, which is not supported"- return+ return contractFailure[apicontract.Null](ret)}if err := filelock.Copy(src, dest); err != nil {logging.LogErrorf("copy file [%s] to [%s] failed: %s", src, dest, err)ret.Code = -1ret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}changedPaths = append(changedPaths, dest)}-}+ return apicontract.Success(apicontract.Null{})+})-func workspaceCopyFiles(c *gin.Context) {+var workspaceCopyFiles = contractHandler(apicontract.WorkspaceCopyFiles, func(c *gin.Context, request apicontract.CopyFilesRequest) apicontract.Response[apicontract.Null] {ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)var changedPaths []stringdefer func() {model.IncSyncIfNeeded(changedPaths...)}()- arg, ok := util.JsonArg(c, ret)- if !ok {- return- }-- var srcsArg []any- var destDirArg string- if !util.ParseJsonArgs(arg, ret,- util.BindJsonArg("srcs", &srcsArg, true, true), // 相对于工作空间的路径- util.BindJsonArg("destDir", &destDirArg, true, false), // 相对于工作空间的路径- ) {- return- }-- var relSrcs []string- for _, s := range srcsArg {- str, elemOk := s.(string)- if !elemOk {- ret.Code = -1- ret.Msg = "Field [srcs]: each element should be of type [String]"- return- }- str = strings.TrimSpace(str)- if str == "" {- ret.Code = -1- ret.Msg = "Field [srcs]: path must not be empty"- return- }- relSrcs = append(relSrcs, str)- }-+ relSrcs, destDirArg := request.Srcs, request.DestDirvar absSrcs []stringfor _, src := range relSrcs {absSrc, err := util.GetAbsPathInWorkspace(src)if err != nil {ret.Code = http.StatusForbiddenret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}if util.IsSensitivePath(absSrc) {logging.LogErrorf("refuse to copy sensitive file [%s]", src)ret.Code = -2ret.Msg = fmt.Sprintf("refuse to copy sensitive file [%s]", src)- return+ return contractFailure[apicontract.Null](ret)}if rejectEncryptedBoxPath(absSrc) {ret.Code = -3ret.Msg = model.Conf.Language(321)- return+ return contractFailure[apicontract.Null](ret)}if err = prepareFileAssets(absSrc); err != nil {ret.Code = -1ret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}if !filelock.IsExist(absSrc) {ret.Code = -1ret.Msg = fmt.Sprintf("file [%s] does not exist", src)- return+ return contractFailure[apicontract.Null](ret)}absSrcs = append(absSrcs, absSrc)}@@ -345,32 +276,32 @@ func workspaceCopyFiles(c *gin.Context) {if err != nil {ret.Code = http.StatusForbiddenret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}// 在 MkdirAll 前拒绝加密笔记本目录,避免在加密笔记本内创建明文目录if rejectEncryptedBoxPath(destDir) {ret.Code = -1ret.Msg = "copying encrypted notebook files is not supported via this API"- return+ return contractFailure[apicontract.Null](ret)}if filelock.IsExist(destDir) {destInfo, err := os.Stat(destDir)if err != nil {ret.Code = -1ret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}if !destInfo.IsDir() {ret.Code = -1ret.Msg = "Field [destDir]: path is not a directory"- return+ return contractFailure[apicontract.Null](ret)}} else {if err = os.MkdirAll(destDir, 0755); err != nil {logging.LogErrorf("make dir [%s] failed: %s", destDir, err)ret.Code = -1ret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}}@@ -379,46 +310,33 @@ func workspaceCopyFiles(c *gin.Context) {if rejectEncryptedBoxPath(dest) {ret.Code = -3ret.Msg = model.Conf.Language(321)- return+ return contractFailure[apicontract.Null](ret)}if li, lerr := os.Lstat(dest); lerr == nil && li.Mode()&os.ModeSymlink != 0 {ret.Code = -1ret.Msg = "destination path is a symlink, which is not supported"- return+ return contractFailure[apicontract.Null](ret)}if err := filelock.Copy(absSrc, dest); err != nil {logging.LogErrorf("copy file [%s] to [%s] failed: %s", absSrc, dest, err)ret.Code = -1ret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}changedPaths = append(changedPaths, dest)}-}+ return apicontract.Success(apicontract.Null{})+})-func copyFile(c *gin.Context) {+var copyFile = contractHandler(apicontract.CopyFile, func(c *gin.Context, request apicontract.CopyFileRequest) apicontract.Response[apicontract.Null] {ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)-- arg, ok := util.JsonArg(c, ret)- if !ok {- return- }-- var src, dest string- if !util.ParseJsonArgs(arg, ret,- util.BindJsonArg("src", &src, true, true), // 资源路径,由 GetAssetAbsPath 解析- util.BindJsonArg("dest", &dest, true, true), // 绝对路径- ) {- return- }+ src, dest := request.Src, request.Destif !filepath.IsAbs(dest) {logging.LogErrorf("copy file dest [%s] is not an absolute path", dest)ret.Code = -1ret.Msg = "Field [dest]: path must be absolute"- ret.Data = map[string]any{"closeTimeout": 5000}- return+ return apicontract.FailureWithTimeout[apicontract.Null](ret.Code, ret.Msg, 5000)}src, err := model.GetAssetAbsPathInBox(src, "")@@ -426,8 +344,7 @@ func copyFile(c *gin.Context) {logging.LogErrorf("get asset [%s] abs path failed: %s", src, err)ret.Code = -1ret.Msg = err.Error()- ret.Data = map[string]any{"closeTimeout": 5000}- return+ return apicontract.FailureWithTimeout[apicontract.Null](ret.Code, ret.Msg, 5000)}// 加密笔记本的文件不允许通过原始文件 API 复制(src 读出密文/明文,dest 写入破坏加密存储)@@ -439,93 +356,73 @@ func copyFile(c *gin.Context) {if err = holdEncryptedBoxRequest(c, boxID); err != nil {ret.Code = -1ret.Msg = model.Conf.Language(314)- return+ return contractFailure[apicontract.Null](ret)}if err = copyDecryptedAsset(src, dest); err != nil {ret.Code = -1ret.Msg = err.Error()- ret.Data = map[string]any{"closeTimeout": 5000}- return+ return apicontract.FailureWithTimeout[apicontract.Null](ret.Code, ret.Msg, 5000)}- return+ return apicontract.Success(apicontract.Null{})}ret.Code = -1ret.Msg = "copying encrypted notebook files is not supported via this API"- ret.Data = map[string]any{"closeTimeout": 5000}- return+ return apicontract.FailureWithTimeout[apicontract.Null](ret.Code, ret.Msg, 5000)}if err = prepareFileAssets(src); err != nil {ret.Code = -1ret.Msg = err.Error()- ret.Data = map[string]any{"closeTimeout": 7000}- return+ return apicontract.FailureWithTimeout[apicontract.Null](ret.Code, ret.Msg, 7000)}info, err := os.Stat(src)if err != nil {logging.LogErrorf("stat [%s] failed: %s", src, err)ret.Code = -1ret.Msg = err.Error()- ret.Data = map[string]any{"closeTimeout": 5000}- return+ return apicontract.FailureWithTimeout[apicontract.Null](ret.Code, ret.Msg, 5000)}if info.IsDir() {ret.Code = -1ret.Msg = "Field [src]: path is a directory"- ret.Data = map[string]any{"closeTimeout": 5000}- return+ return apicontract.FailureWithTimeout[apicontract.Null](ret.Code, ret.Msg, 5000)}if util.IsSensitivePath(dest) {logging.LogErrorf("refuse to copy sensitive file [%s]", dest)ret.Code = -2ret.Msg = fmt.Sprintf("refuse to copy sensitive file [%s]", dest)- return+ return contractFailure[apicontract.Null](ret)}if err = filelock.Copy(src, dest); err != nil {logging.LogErrorf("copy file [%s] to [%s] failed: %s", src, dest, err)ret.Code = -1ret.Msg = err.Error()- ret.Data = map[string]any{"closeTimeout": 5000}- return+ return apicontract.FailureWithTimeout[apicontract.Null](ret.Code, ret.Msg, 5000)}model.IncSyncIfNeeded(dest)-}+ return apicontract.Success(apicontract.Null{})+})-func getFile(c *gin.Context) {+var getFile = contractHandler(apicontract.GetFile, func(c *gin.Context, request apicontract.FilePathRequest) apicontract.Response[apicontract.BinaryContent] {ret := gulu.Ret.NewResult()- arg, ok := util.JsonArg(c, ret)- if !ok {- ret.Code = -1- c.JSON(http.StatusAccepted, ret)- return- }-- var filePath string- if !util.ParseJsonArgs(arg, ret,- util.BindJsonArg("path", &filePath, true, true),- ) {- c.JSON(http.StatusAccepted, ret)- return- }+ filePath := request.PathfileAbsPath, err := util.GetAbsPathInWorkspace(filePath)if err != nil {ret.Code = http.StatusForbiddenret.Msg = err.Error()- c.JSON(http.StatusAccepted, ret)- return+ return contractFailure[apicontract.BinaryContent](ret)}// 加密笔记本的任何文件都不允许通过原始文件 API 读取(不只 .sy):// 密文对插件无意义,且可能被误解析或泄漏;合法读取走专用 API(已加密感知)if rejectEncryptedBoxPath(fileAbsPath) {ret.Code = -3ret.Msg = model.Conf.Language(321)- c.JSON(http.StatusAccepted, ret)- return+ return contractFailure[apicontract.BinaryContent](ret)}// 解析符号链接(Windows 下含目录联接)后再做授权判断,防止 reader 通过 data/assets// 等目录下的链接读取工作空间外的文件(security advisory GHSA-g7gf-v79m-jwrm)@@ -534,15 +431,13 @@ func getFile(c *gin.Context) {logging.LogErrorf("resolve symlinks for [%s] failed: %s", fileAbsPath, err)ret.Code = http.StatusInternalServerErrorret.Msg = http.StatusText(http.StatusInternalServerError) + errMsgSeeKernelLog- c.JSON(http.StatusAccepted, ret)- return+ return contractFailure[apicontract.BinaryContent](ret)}// 符号链接指向加密笔记本时同样拒绝读取,防止密文泄漏if rejectEncryptedBoxPath(resolvedPath) {ret.Code = -3ret.Msg = model.Conf.Language(321)- c.JSON(http.StatusAccepted, ret)- return+ return contractFailure[apicontract.BinaryContent](ret)}fileAbsPath = resolvedPath@@ -553,11 +448,10 @@ func getFile(c *gin.Context) {if !gulu.File.IsSubPath(util.NormalizeAndResolve(util.WorkspaceDir), util.NormalizeAndResolve(fileAbsPath)) {ret.Code = http.StatusForbiddenret.Msg = http.StatusText(http.StatusForbidden)- c.JSON(http.StatusAccepted, ret)- return+ return contractFailure[apicontract.BinaryContent](ret)}if refuseToAccess(c, fileAbsPath, ret) {- return+ return contractFailure[apicontract.BinaryContent](ret)}}@@ -566,8 +460,7 @@ func getFile(c *gin.Context) {if !model.CheckAbsPathAccessableByPublishAccess(c, fileAbsPath, publishAccess) {ret.Code = http.StatusForbiddenret.Msg = http.StatusText(http.StatusForbidden)- c.JSON(http.StatusAccepted, ret)- return+ return contractFailure[apicontract.BinaryContent](ret)}}@@ -578,8 +471,7 @@ func getFile(c *gin.Context) {ret.Code = http.StatusNotFound}ret.Msg = err.Error()- c.JSON(http.StatusAccepted, ret)- return+ return contractFailure[apicontract.BinaryContent](ret)}}info, err := os.Stat(fileAbsPath)@@ -589,22 +481,19 @@ func getFile(c *gin.Context) {ret.Code = http.StatusNotFound}ret.Msg = err.Error()- c.JSON(http.StatusAccepted, ret)- return+ return contractFailure[apicontract.BinaryContent](ret)}if info.IsDir() {ret.Code = http.StatusConflictret.Msg = "path is a directory"- c.JSON(http.StatusAccepted, ret)- return+ return contractFailure[apicontract.BinaryContent](ret)}data, err := filelock.ReadFile(fileAbsPath)if err != nil {logging.LogErrorf("read file [%s] failed: %s", fileAbsPath, err)ret.Code = http.StatusInternalServerErrorret.Msg = err.Error()- c.JSON(http.StatusAccepted, ret)- return+ return contractFailure[apicontract.BinaryContent](ret)}contentType := mime.TypeByExtension(filepath.Ext(fileAbsPath))@@ -616,8 +505,8 @@ func getFile(c *gin.Context) {if "" == contentType {contentType = "application/octet-stream"}- c.Data(http.StatusOK, contentType, data)-}+ return apicontract.SuccessBinary(contentType, data)+})func refuseToAccess(c *gin.Context, fileAbsPath string, ret *gulu.Result) bool {// 禁止访问敏感文件(conf 目录下的 conf.json 与 TLS 密钥材料、data/snippets/conf.json、@@ -626,7 +515,6 @@ func refuseToAccess(c *gin.Context, fileAbsPath string, ret *gulu.Result) bool {if util.IsForbiddenAbsPath(fileAbsPath) {ret.Code = http.StatusForbiddenret.Msg = http.StatusText(http.StatusForbidden)- c.JSON(http.StatusAccepted, ret)return true}@@ -635,60 +523,45 @@ func refuseToAccess(c *gin.Context, fileAbsPath string, ret *gulu.Result) bool {if !model.CheckAbsPathAccessableByPublishAccess(c, fileAbsPath, publishAccess) {ret.Code = http.StatusForbiddenret.Msg = http.StatusText(http.StatusForbidden)- c.JSON(http.StatusAccepted, ret)return true}return false}-func readDir(c *gin.Context) {+var readDir = contractHandler(apicontract.ReadDirectory, func(c *gin.Context, request apicontract.ReadDirectoryRequest) apicontract.Response[[]apicontract.DirectoryEntry] {ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)-- arg, ok := util.JsonArg(c, ret)- if !ok {- c.JSON(http.StatusOK, ret)- return- }-- var dirPath string- if !util.ParseJsonArgs(arg, ret,- util.BindJsonArg("path", &dirPath, true, false),- ) {- return- }-+ dirPath := request.PathdirAbsPath, err := util.GetAbsPathInWorkspace(dirPath)if err != nil {ret.Code = http.StatusForbiddenret.Msg = err.Error()- return+ return contractFailure[[]apicontract.DirectoryEntry](ret)}// 加密笔记本的任何目录都不允许通过原始文件 API 枚举(不只 .sy):// 目录结构、文档 ID、随机化资产名和时间戳可能泄漏信息;合法读取走专用 API(已加密感知)if rejectEncryptedBoxPath(dirAbsPath) {ret.Code = -3ret.Msg = model.Conf.Language(321)- return+ return contractFailure[[]apicontract.DirectoryEntry](ret)}info, err := os.Stat(dirAbsPath)if os.IsNotExist(err) {ret.Code = http.StatusNotFoundret.Msg = "path does not exist"- return+ return contractFailure[[]apicontract.DirectoryEntry](ret)}if err != nil {logging.LogErrorf("stat [%s] failed: %s", dirAbsPath, err)ret.Code = http.StatusInternalServerErrorret.Msg = http.StatusText(http.StatusInternalServerError) + errMsgSeeKernelLog- return+ return contractFailure[[]apicontract.DirectoryEntry](ret)}if !info.IsDir() {logging.LogErrorf("file [%s] is not a directory", dirAbsPath)ret.Code = http.StatusConflictret.Msg = "path is not a directory"- return+ return contractFailure[[]apicontract.DirectoryEntry](ret)}entries, err := os.ReadDir(dirAbsPath)@@ -696,10 +569,10 @@ func readDir(c *gin.Context) {logging.LogErrorf("read dir [%s] failed: %s", dirAbsPath, err)ret.Code = http.StatusInternalServerErrorret.Msg = http.StatusText(http.StatusInternalServerError) + errMsgSeeKernelLog- return+ return contractFailure[[]apicontract.DirectoryEntry](ret)}- files := []map[string]any{}+ files := []apicontract.DirectoryEntry{}for _, entry := range entries {path := filepath.Join(dirAbsPath, entry.Name())info, err = os.Stat(path)@@ -707,54 +580,34 @@ func readDir(c *gin.Context) {logging.LogErrorf("stat [%s] failed: %s", path, err)ret.Code = http.StatusInternalServerErrorret.Msg = http.StatusText(http.StatusInternalServerError) + errMsgSeeKernelLog- return+ return contractFailure[[]apicontract.DirectoryEntry](ret)}- files = append(files, map[string]any{- "name": entry.Name(),- "isDir": info.IsDir(),- "isSymlink": util.IsSymlink(entry),- "updated": info.ModTime().Unix(),- })+ files = append(files, apicontract.DirectoryEntry{Name: entry.Name(), IsDir: info.IsDir(), IsSymlink: util.IsSymlink(entry), Updated: info.ModTime().Unix()})}- ret.Data = files-}+ return apicontract.Success(files)+})-func renameFile(c *gin.Context) {+var renameFile = contractHandler(apicontract.RenameFile, func(c *gin.Context, request apicontract.RenameFileRequest) apicontract.Response[apicontract.Null] {ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)-- arg, ok := util.JsonArg(c, ret)- if !ok {- c.JSON(http.StatusOK, ret)- return- }-- var srcPath, destPath string- if !util.ParseJsonArgs(arg, ret,- util.BindJsonArg("path", &srcPath, true, true),- util.BindJsonArg("newPath", &destPath, true, true),- ) {- return- }-+ srcPath, destPath := request.Path, request.NewPathsrcAbsPath, err := util.GetAbsPathInWorkspace(srcPath)if err != nil {ret.Code = http.StatusForbiddenret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}destAbsPath, err := util.GetAbsPathInWorkspace(destPath)if err != nil {ret.Code = http.StatusForbiddenret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}// 加密笔记本的文件不允许通过原始文件 API 重命名(会破坏加密存储结构/跨 box 搬运密文)if rejectEncryptedBoxPath(srcAbsPath) || rejectEncryptedBoxPath(destAbsPath) {ret.Code = -3ret.Msg = model.Conf.Language(321)- return+ return contractFailure[apicontract.Null](ret)}if err = prepareFileAssets(srcAbsPath); err == nil {err = prepareFileAssets(destAbsPath)@@ -762,7 +615,7 @@ func renameFile(c *gin.Context) {if err != nil {ret.Code = -1ret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}srcInfo, srcStatErr := os.Stat(srcAbsPath)if srcStatErr != nil {@@ -771,18 +624,18 @@ func renameFile(c *gin.Context) {ret.Code = http.StatusNotFound}ret.Msg = srcStatErr.Error()- return+ return contractFailure[apicontract.Null](ret)}if filelock.IsExist(destAbsPath) {ret.Code = http.StatusConflictret.Msg = "Field [newPath]: path already exists"- return+ return contractFailure[apicontract.Null](ret)}if srcInfo.IsDir() && gulu.File.IsSubPath(srcAbsPath, destAbsPath) {ret.Code = http.StatusConflictret.Msg = "Field [newPath]: cannot rename a directory into its own subdirectory"- return+ return contractFailure[apicontract.Null](ret)}affectsSync := model.PathsAffectSync(srcAbsPath)@@ -793,19 +646,19 @@ func renameFile(c *gin.Context) {logging.LogErrorf("stat [%s] failed: %s", destParent, statErr)ret.Code = http.StatusInternalServerErrorret.Msg = http.StatusText(http.StatusInternalServerError) + errMsgSeeKernelLog- return+ return contractFailure[apicontract.Null](ret)}if !parentInfo.IsDir() {ret.Code = http.StatusConflictret.Msg = fmt.Sprintf("Field [newPath]: parent path [%s] is not a directory", filepath.Dir(destPath))- return+ return contractFailure[apicontract.Null](ret)}} else {if err = os.MkdirAll(destParent, 0755); err != nil {logging.LogErrorf("make dir [%s] failed: %s", destParent, err)ret.Code = http.StatusInternalServerErrorret.Msg = http.StatusText(http.StatusInternalServerError) + errMsgSeeKernelLog- return+ return contractFailure[apicontract.Null](ret)}}@@ -813,61 +666,48 @@ func renameFile(c *gin.Context) {logging.LogErrorf("rename file failed: %s", err)ret.Code = http.StatusInternalServerErrorret.Msg = http.StatusText(http.StatusInternalServerError) + errMsgSeeKernelLog- return+ return contractFailure[apicontract.Null](ret)}if affectsSync || model.PathsAffectSync(destAbsPath) {model.IncSync()}-}+ return apicontract.Success(apicontract.Null{})+})-func removeFile(c *gin.Context) {+var removeFile = contractHandler(apicontract.RemoveFile, func(c *gin.Context, request apicontract.RemoveFileRequest) apicontract.Response[apicontract.Null] {ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)-- arg, ok := util.JsonArg(c, ret)- if !ok {- c.JSON(http.StatusOK, ret)- return- }-- var app, filePath string- if !util.ParseJsonArgs(arg, ret,- util.BindJsonArg("app", &app, false, false),- util.BindJsonArg("path", &filePath, true, true),- ) {- return- }+ app, filePath := request.App, request.Pathapp = resolveFileAPIAppID(c, app)fileAbsPath, err := util.GetAbsPathInWorkspace(filePath)if err != nil {ret.Code = http.StatusForbiddenret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}// 加密笔记本的文件不允许通过原始文件 API 删除(破坏加密存储结构)if rejectEncryptedBoxPath(fileAbsPath) {ret.Code = -3ret.Msg = model.Conf.Language(321)- return+ return contractFailure[apicontract.Null](ret)}if err = prepareFileAssets(fileAbsPath); err != nil {ret.Code = -1ret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}_, err = os.Stat(fileAbsPath)if os.IsNotExist(err) {ret.Code = http.StatusNotFoundret.Msg = "path does not exist"- return+ return contractFailure[apicontract.Null](ret)}if err != nil {logging.LogErrorf("stat [%s] failed: %s", fileAbsPath, err)ret.Code = http.StatusInternalServerErrorret.Msg = http.StatusText(http.StatusInternalServerError) + errMsgSeeKernelLog- return+ return contractFailure[apicontract.Null](ret)}affectsSync := model.PathsAffectSync(fileAbsPath)@@ -875,36 +715,36 @@ func removeFile(c *gin.Context) {logging.LogErrorf("remove [%s] failed: %s", fileAbsPath, err)ret.Code = http.StatusInternalServerErrorret.Msg = http.StatusText(http.StatusInternalServerError) + errMsgSeeKernelLog- return+ return contractFailure[apicontract.Null](ret)}model.PushPluginStorageDataChanged(fileAbsPath, app)if affectsSync {model.IncSync()}-}+ return apicontract.Success(apicontract.Null{})+})-func putFile(c *gin.Context) {+var putFile = contractHandler(apicontract.PutFile, func(c *gin.Context, request apicontract.PutFileRequest) apicontract.Response[apicontract.Null] {ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)- isDirStr := c.PostForm("isDir")+ isDirStr := request.IsDirisDir, _ := strconv.ParseBool(isDirStr)- app := resolveFileAPIAppID(c, c.PostForm("app"))+ app := resolveFileAPIAppID(c, request.App)var err error- filePath := c.PostForm("path")+ filePath := request.PathfilePath = strings.TrimSpace(filePath)if filePath == "" {ret.Code = http.StatusBadRequestret.Msg = "path must not be empty"- return+ return contractFailure[apicontract.Null](ret)}fileAbsPath, err := util.GetAbsPathInWorkspace(filePath)if err != nil {ret.Code = http.StatusForbiddenret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}// 加密笔记本的任何文件都不允许通过原始文件 API 写入(不只 .sy):@@ -912,7 +752,7 @@ func putFile(c *gin.Context) {if rejectEncryptedBoxPath(fileAbsPath) {ret.Code = -3ret.Msg = model.Conf.Language(321)- return+ return contractFailure[apicontract.Null](ret)}fileExists := filelock.IsExist(fileAbsPath)@@ -920,7 +760,7 @@ func putFile(c *gin.Context) {if !util.IsValidUploadFileName(filepath.Base(fileAbsPath)) { // Improve kernel API `/api/file/putFile` parameter validation https://github.com/siyuan-note/siyuan/issues/14658ret.Code = http.StatusBadRequestret.Msg = "invalid file path. For details, please check https://github.com/siyuan-note/siyuan/issues/14658"- return+ return contractFailure[apicontract.Null](ret)}} else {info, statErr := os.Stat(fileAbsPath)@@ -928,12 +768,12 @@ func putFile(c *gin.Context) {logging.LogErrorf("stat file [%s] failed: %s", fileAbsPath, statErr)ret.Code = http.StatusInternalServerErrorret.Msg = statErr.Error()- return+ return contractFailure[apicontract.Null](ret)}if info.IsDir() && !isDir {ret.Code = http.StatusBadRequestret.Msg = "path is a directory"- return+ return contractFailure[apicontract.Null](ret)}}@@ -943,12 +783,12 @@ func putFile(c *gin.Context) {logging.LogErrorf("make dir [%s] failed: %s", fileAbsPath, err)}} else {- fileHeader, _ := c.FormFile("file")+ fileHeader := request.Fileif nil == fileHeader {logging.LogErrorf("form file is nil [path=%s]", fileAbsPath)ret.Code = http.StatusBadRequestret.Msg = "Field [file] must not be empty"- return+ return contractFailure[apicontract.Null](ret)}for range 1 {@@ -982,10 +822,10 @@ func putFile(c *gin.Context) {if err != nil {ret.Code = -1ret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}- modTimeStr := c.PostForm("modTime")+ modTimeStr := request.ModTimemodTime := time.Now()if "" != modTimeStr {modTimeInt, parseErr := strconv.ParseInt(modTimeStr, 10, 64)@@ -993,7 +833,7 @@ func putFile(c *gin.Context) {logging.LogErrorf("parse mod time [%s] failed: %s", modTimeStr, parseErr)ret.Code = http.StatusInternalServerErrorret.Msg = parseErr.Error()- return+ return contractFailure[apicontract.Null](ret)}modTime = millisecond2Time(modTimeInt)}@@ -1001,14 +841,15 @@ func putFile(c *gin.Context) {logging.LogErrorf("change time failed: %s", err)ret.Code = http.StatusInternalServerErrorret.Msg = err.Error()- return+ return contractFailure[apicontract.Null](ret)}if !isDir {model.PushPluginStorageDataChanged(fileAbsPath, app)model.IncSyncIfNeeded(fileAbsPath)}-}+ return apicontract.Success(apicontract.Null{})+})func millisecond2Time(t int64) time.Time {sec := t / 1000diff --git a/kernel/apicontract/binary_test.go b/kernel/apicontract/binary_test.gonew file mode 100644index 0000000000..29a6390209--- /dev/null+++ b/kernel/apicontract/binary_test.go@@ -0,0 +1,41 @@+package apicontract++import (+ "encoding/json"+ "testing"+)++func TestBinaryResponseContract(t *testing.T) {+ bundle, err := BuildBundle()+ if err != nil {+ t.Fatal(err)+ }+ for _, entry := range []struct {+ status int+ media, body string+ valid bool+ }{+ {200, "application/octet-stream", "\x00\xff", true},+ {200, "application/json", `{"arbitrary":[true,null]}`, true},+ {202, "application/json; charset=utf-8", `{"code":404,"msg":"missing","data":null}`, true},+ {202, "application/json", `{"code":0,"msg":"","data":null}`, false},+ {202, "text/plain", `{"code":404,"msg":"missing","data":null}`, false},+ {404, "application/json", `{"code":404,"msg":"missing","data":null}`, false},+ {202, "application/json", `{"code":404,"msg":"missing","data":false}`, false},+ } {+ err := bundle.ValidateHTTPResponse("POST", "/api/file/getFile", entry.status, entry.media, []byte(entry.body))+ if (err == nil) != entry.valid {+ t.Fatalf("unexpected validation: %+v: %v", entry, err)+ }+ }+ response := SuccessBinary("application/octet-stream", []byte{0, 255})+ if GetFile.Status(response) != 200 || response.Binary().Bytes[1] != 255 {+ t.Fatal("binary response changed")+ }+ if _, err := json.Marshal(response); err == nil {+ t.Fatal("raw bytes must not be serialized into a JSON envelope")+ }+ if GetFile.Status(Failure[BinaryContent](404, "missing")) != 202 {+ t.Fatal("file failure status changed")+ }+}diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 97e11e4307..1f5db23dee 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -8,9 +8,14 @@ import (type BodyMode string+type OutputMode string++const BinaryOutput OutputMode = "binary"+const (JSONBody BodyMode = "json"MultipartBody BodyMode = "multipart"+ FormBody BodyMode = "form"StructJSONBody BodyMode = "structJSON"NoBody BodyMode = "none"LegacyOptionalBody BodyMode = "legacyOptional"@@ -27,6 +32,8 @@ type Definition struct {ErrorText boolDataNonNullable boolDataOnError bool+ Output OutputMode+ ErrorStatus int}type Endpoint[Request, Data any] struct {@@ -40,6 +47,8 @@ type ResponseOptions struct {Text boolNonNullable boolDataOnError bool+ Output OutputMode+ ErrorStatus int}var definitions []Definition@@ -92,7 +101,8 @@ var (func define[Request, Data any](name, path string, body BodyMode, response ResponseOptions, methods ...string) Endpoint[Request, Data] {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}+ ErrorCodes: append([]int{-1}, response.AdditionalCodes...), ErrorText: response.Text, DataNonNullable: response.NonNullable, DataOnError: response.DataOnError,+ Output: response.Output, ErrorStatus: response.ErrorStatus}definitions = append(definitions, d)return Endpoint[Request, Data]{definition: d}}@@ -449,7 +459,30 @@ var PrepareRichText = define[PrepareRichTextRequest, *RichClipboardPrepared]("prvar CleanupRichText = define[CleanupRichTextRequest, Null]("cleanupRichText", "/api/clipboard/cleanupRichText", JSONBody, ResponseOptions{}, "POST")var StartFreeTrial = define[EmptyRequest, Null]("startFreeTrial", "/api/account/startFreeTrial", NoBody, ResponseOptions{}, "POST")+var UseActivationCode = define[ActivationCodeRequest, Null]("useActivationcode", "/api/account/useActivationcode", JSONBody, ResponseOptions{}, "POST")+var CheckActivationCode = define[CheckActivationCodeRequest, Null]("checkActivationcode", "/api/account/checkActivationcode", JSONBody, ResponseOptions{AdditionalCodes: []int{1}, DataOnError: true}, "POST")+var DeactivateUser = define[EmptyRequest, Null]("deactivateUser", "/api/account/deactivate", NoBody, ResponseOptions{}, "POST")+var AccountLogin = define[AccountLoginRequest, *AccountLoginData]("login", "/api/account/login", JSONBody, ResponseOptions{AdditionalCodes: []int{1, 10}, DataOnError: true}, "POST")++var GetUniqueFilename = define[FilePathRequest, FilePathData]("getUniqueFilename", "/api/file/getUniqueFilename", JSONBody, ResponseOptions{AdditionalCodes: []int{-3}}, "POST")++var ReadDirectory = define[ReadDirectoryRequest, []DirectoryEntry]("readDir", "/api/file/readDir", JSONBody, ResponseOptions{AdditionalCodes: []int{-3, 403, 404, 409, 500}, NonNullable: true}, "POST")++var RenameFile = define[RenameFileRequest, Null]("renameFile", "/api/file/renameFile", JSONBody, ResponseOptions{AdditionalCodes: []int{-3, 403, 404, 409, 500}}, "POST")++var RemoveFile = define[RemoveFileRequest, Null]("removeFile", "/api/file/removeFile", JSONBody, ResponseOptions{AdditionalCodes: []int{-3, 403, 404, 500}}, "POST")++var GlobalCopyFiles = define[CopyFilesRequest, Null]("globalCopyFiles", "/api/file/globalCopyFiles", JSONBody, ResponseOptions{AdditionalCodes: []int{-2, -3, 403}}, "POST")++var WorkspaceCopyFiles = define[CopyFilesRequest, Null]("workspaceCopyFiles", "/api/file/workspaceCopyFiles", JSONBody, ResponseOptions{AdditionalCodes: []int{-2, -3, 403}}, "POST")++var CopyFile = define[CopyFileRequest, Null]("copyFile", "/api/file/copyFile", JSONBody, ResponseOptions{AdditionalCodes: []int{-2}}, "POST")++var PutFile = define[PutFileRequest, Null]("putFile", "/api/file/putFile", FormBody, ResponseOptions{AdditionalCodes: []int{-3, 400, 403, 500}}, "POST")++var GetFile = define[FilePathRequest, BinaryContent]("getFile", "/api/file/getFile", JSONBody,+ ResponseOptions{Output: BinaryOutput, ErrorStatus: 202, AdditionalCodes: []int{-3, 403, 404, 409, 500, 503}}, "POST")diff --git a/kernel/apicontract/file.go b/kernel/apicontract/file.gonew file mode 100644index 0000000000..a22d6c7c2d--- /dev/null+++ b/kernel/apicontract/file.go@@ -0,0 +1,45 @@+package apicontract++import "mime/multipart"++type PutFileRequest struct {+ IsDir string `json:"isDir" api:"optional"`+ App string `json:"app" api:"optional"`+ Path string `json:"path" api:"optional"`+ File *multipart.FileHeader `json:"file" api:"optional,nonnullable"`+ ModTime string `json:"modTime" api:"optional"`+}++type CopyFileRequest struct {+ Src string `json:"src" api:"trim"`+ Dest string `json:"dest" api:"trim"`+}++type CopyFilesRequest struct {+ Srcs []string `json:"srcs"`+ DestDir string `json:"destDir"`+}++type FilePathRequest struct {+ Path string `json:"path" api:"trim"`+}+type FilePathData struct {+ Path string `json:"path"`+}+type ReadDirectoryRequest struct {+ Path string `json:"path"`+}+type DirectoryEntry struct {+ Name string `json:"name"`+ IsDir bool `json:"isDir"`+ IsSymlink bool `json:"isSymlink"`+ Updated int64 `json:"updated"`+}+type RenameFileRequest struct {+ Path string `json:"path" api:"trim"`+ NewPath string `json:"newPath" api:"trim"`+}+type RemoveFileRequest struct {+ App string `json:"app" api:"optional,nullable"`+ Path string `json:"path" api:"trim"`+}diff --git a/kernel/apicontract/file_input.go b/kernel/apicontract/file_input.gonew file mode 100644index 0000000000..ce9fd35930--- /dev/null+++ b/kernel/apicontract/file_input.go@@ -0,0 +1,50 @@+package apicontract++import (+ "bytes"+ "encoding/json"+ "fmt"+ "io"+ "strings"+)++func decodeCopyFiles(reader io.Reader, path string, trim bool) (request CopyFilesRequest, err error) {+ fields, err := blockRequestFields(reader, path)+ if err != nil {+ return request, err+ }+ srcs, err := legacyField[[]json.RawMessage](fields, "srcs", "Array", true)+ if err != nil {+ return request, err+ }+ if len(srcs) == 0 {+ return request, fmt.Errorf("Field [srcs] must not be empty")+ }+ request.DestDir, err = legacyField[string](fields, "destDir", "String", true)+ if err != nil {+ return request, err+ }+ for _, raw := range srcs {+ var src string+ if bytes.Equal(raw, []byte("null")) || json.Unmarshal(raw, &src) != nil {+ return request, fmt.Errorf("Field [srcs]: each element should be of type [String]")+ }+ if trim {+ src = strings.TrimSpace(src)+ if src == "" {+ return request, fmt.Errorf("Field [srcs]: path must not be empty")+ }+ }+ request.Srcs = append(request.Srcs, src)+ }+ return+}++func init() {+ GlobalCopyFiles.decodeRequest = func(reader io.Reader) (CopyFilesRequest, error) {+ return decodeCopyFiles(reader, "/api/file/globalCopyFiles", false)+ }+ WorkspaceCopyFiles.decodeRequest = func(reader io.Reader) (CopyFilesRequest, error) {+ return decodeCopyFiles(reader, "/api/file/workspaceCopyFiles", true)+ }+}diff --git a/kernel/apicontract/legacy_routes.json b/kernel/apicontract/legacy_routes.jsonindex af46427ba3..38e1345b8b 100644--- a/kernel/apicontract/legacy_routes.json+++ b/kernel/apicontract/legacy_routes.json@@ -185,15 +185,6 @@{"method":"POST","path":"/api/export/preview","handler":"exportPreview"},{"method":"POST","path":"/api/export/processPDF","handler":"processPDF"},{"method":"POST","path":"/api/extension/copy","handler":"extensionCopy"},- {"method":"POST","path":"/api/file/copyFile","handler":"copyFile"},- {"method":"POST","path":"/api/file/getFile","handler":"getFile"},- {"method":"POST","path":"/api/file/getUniqueFilename","handler":"getUniqueFilename"},- {"method":"POST","path":"/api/file/globalCopyFiles","handler":"globalCopyFiles"},- {"method":"POST","path":"/api/file/putFile","handler":"putFile"},- {"method":"POST","path":"/api/file/readDir","handler":"readDir"},- {"method":"POST","path":"/api/file/removeFile","handler":"removeFile"},- {"method":"POST","path":"/api/file/renameFile","handler":"renameFile"},- {"method":"POST","path":"/api/file/workspaceCopyFiles","handler":"workspaceCopyFiles"},{"method":"POST","path":"/api/filetree/authFilePublishAccess","handler":"authFilePublishAccess"},{"method":"POST","path":"/api/filetree/changeSort","handler":"changeSort"},{"method":"POST","path":"/api/filetree/createDailyNote","handler":"createDailyNote"},diff --git a/kernel/apicontract/multipart.go b/kernel/apicontract/multipart.goindex 22b7f47b0f..37196b7fe7 100644--- a/kernel/apicontract/multipart.go+++ b/kernel/apicontract/multipart.go@@ -36,7 +36,7 @@ func validateMultipartRequest(t reflect.Type) error {// DecodeMultipart 保留表单重复字段取首值的行为,文件内容由业务入口按需读取。func (e Endpoint[Request, Data]) DecodeMultipart(form *multipart.Form) (request Request, err error) {- if e.definition.Body != MultipartBody {+ if e.definition.Body != MultipartBody && e.definition.Body != FormBody {return request, fmt.Errorf("endpoint does not accept multipart data")}if form == nil {diff --git a/kernel/apicontract/multipart_test.go b/kernel/apicontract/multipart_test.goindex 8e84294857..42ef4738f2 100644--- a/kernel/apicontract/multipart_test.go+++ b/kernel/apicontract/multipart_test.go@@ -31,3 +31,17 @@ func TestMultipartRequestCompatibility(t *testing.T) {t.Fatal("unsupported form field accepted")}}++func TestPutFileFormFields(t *testing.T) {+ first := &multipart.FileHeader{Filename: "first.txt"}+ request, err := PutFile.DecodeMultipart(&multipart.Form{+ Value: map[string][]string{"path": {" temp/file ", "ignored"}, "isDir": {"invalid"}},+ File: map[string][]*multipart.FileHeader{"file": {first, {Filename: "ignored.txt"}}},+ })+ if err != nil || request.Path != " temp/file " || request.IsDir != "invalid" || request.File != first {+ t.Fatalf("form fields must preserve first values without early validation: %+v, %v", request, err)+ }+ if _, err = PutFile.DecodeMultipart(&multipart.Form{}); err != nil {+ t.Fatalf("conditional field validation belongs to the handler: %v", err)+ }+}diff --git a/kernel/apicontract/response.go b/kernel/apicontract/response.goindex 1a7796db29..7c2396eab5 100644--- a/kernel/apicontract/response.go+++ b/kernel/apicontract/response.go@@ -1,6 +1,39 @@package apicontract-import "encoding/json"+import (+ "encoding/json"+ "fmt"+)++// BinaryContent 保留文件的原始字节和媒体类型,不经过 JSON 编码。+type BinaryContent struct {+ ContentType string+ Bytes []byte+}++func SuccessBinary(contentType string, data []byte) Response[BinaryContent] {+ return Response[BinaryContent]{binary: &BinaryContent{ContentType: contentType, Bytes: data}}+}++func (r Response[Data]) Binary() *BinaryContent { return r.binary }++// Status 只为显式声明的非 JSON 协议使用独立错误状态。+func (e Endpoint[Request, Data]) Status(r Response[Data]) int {+ if e.definition.Output == BinaryOutput {+ if r.binary != nil {+ return 200+ }+ if r.code == 0 {+ panic("binary response requires SuccessBinary")+ }+ if e.definition.ErrorStatus != 0 {+ return e.definition.ErrorStatus+ }+ } else if r.binary != nil {+ panic("JSON endpoint cannot return binary content")+ }+ return 200+}// DecodeFailure 保留端点在请求解析失败时声明的响应载荷。func (e Endpoint[Request, Data]) DecodeFailure(err error) Response[Data] {@@ -25,9 +58,10 @@ func (Null) MarshalJSON() ([]byte, error) { return []byte("null"), nil }// Response 的载荷仅能通过有类型的成功构造函数或明确的错误构造函数设置。type Response[Data any] struct {- code int- msg string- data any+ code int+ msg string+ data any+ binary *BinaryContent}func Success[Data any](data Data) Response[Data] { return Response[Data]{data: data} }@@ -48,6 +82,9 @@ func FailureWithTimeout[Data any](code int, msg string, milliseconds int) Respon}func (r Response[Data]) MarshalJSON() ([]byte, error) {+ if r.binary != nil {+ return nil, fmt.Errorf("binary response cannot be encoded as JSON")+ }return json.Marshal(struct {Code int `json:"code"`Msg string `json:"msg"`diff --git a/kernel/apicontract/schema.go b/kernel/apicontract/schema.goindex 3445d38923..919ef386c3 100644--- a/kernel/apicontract/schema.go+++ b/kernel/apicontract/schema.go@@ -4,6 +4,7 @@ import ("encoding/json""fmt""math"+ "mime""mime/multipart""reflect""sort"@@ -24,12 +25,14 @@ 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"`+ 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"`}type Bundle struct {@@ -72,6 +75,12 @@ func nonnullable(schema *Schema) *Schema {}func (b *schemaBuilder) schema(t reflect.Type, input bool) (*Schema, error) {+ if t == reflect.TypeFor[BinaryContent]() {+ if input {+ return nil, fmt.Errorf("binary content can only appear in responses")+ }+ return &Schema{Type: "string", Format: "binary"}, nil+ }if t == reflect.TypeFor[MultipartFields]() {if !input {return nil, fmt.Errorf("multipart fields can only appear in requests")@@ -311,10 +320,22 @@ 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 definition.Output != "" && definition.Output != BinaryOutput {+ return nil, fmt.Errorf("unsupported response output: %s", definition.Name)+ }+ if (definition.Output == BinaryOutput) != (definition.Data == reflect.TypeFor[BinaryContent]()) {+ return nil, fmt.Errorf("binary output requires BinaryContent: %s", definition.Name)+ }+ if definition.Output == BinaryOutput && (definition.DataOnError || definition.DataNonNullable) {+ return nil, fmt.Errorf("binary output cannot use JSON data options: %s", definition.Name)+ }+ if definition.Output == BinaryOutput && (definition.ErrorStatus < 201 || definition.ErrorStatus > 599) {+ return nil, fmt.Errorf("binary output requires a distinct error status: %s", definition.Name)+ }if definition.Request.Kind() != reflect.Struct {return nil, fmt.Errorf("request contract must be a struct: %s", definition.Name)}- if definition.Body == MultipartBody {+ if definition.Body == MultipartBody || definition.Body == FormBody {if err := validateMultipartRequest(definition.Request); err != nil {return nil, err}@@ -331,6 +352,13 @@ func BuildBundle() (*Bundle, error) {data = nonnullable(data)}success := object(map[string]*Schema{"code": {Type: "integer", Enum: []any{0}}, "msg": {Type: "string"}, "data": data}, "code", "msg", "data")+ if definition.Output == BinaryOutput {+ success = data+ // fetch 按媒体类型将文件读作文本或 JSON,JSON 文件本身没有信封约束。+ if _, err := b.schema(reflect.TypeFor[JSONValue](), false); err != nil {+ return nil, err+ }+ }var codes []anyfor _, code := range definition.ErrorCodes {codes = append(codes, code)@@ -348,7 +376,8 @@ func BuildBundle() (*Bundle, error) {failure.AdditionalProperties = trueresponse := &Schema{AnyOf: []*Schema{success, failure}}for _, method := range definition.Methods {- bundle.Endpoints = append(bundle.Endpoints, EndpointSchema{method, definition.Path, definition.Name, definition.Body, request, response})+ 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})}}sort.Slice(bundle.Endpoints, func(i, j int) bool {@@ -364,12 +393,48 @@ 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 {+ return fmt.Errorf("binary endpoint requires HTTP response validation")+ }return b.validate(endpoint.Response, value, "$")}}return fmt.Errorf("unregistered API contract: %s %s", method, path)}+// ValidateHTTPResponse 同时校验响应状态、媒体类型和对应的载荷,原始文件不尝试解析为 JSON。+func (b *Bundle) ValidateHTTPResponse(method, path string, status int, contentType string, payload []byte) error {+ for _, endpoint := range b.Endpoints {+ if endpoint.Method != method || endpoint.Path != path {+ continue+ }+ mediaType, _, err := mime.ParseMediaType(contentType)+ if err != nil {+ return fmt.Errorf("invalid response content type: %w", err)+ }+ if endpoint.Output == BinaryOutput && status == 200 {+ return nil+ }+ expectedStatus := 200+ response := endpoint.Response+ if endpoint.Output == BinaryOutput {+ if endpoint.ErrorStatus != 0 {+ expectedStatus = endpoint.ErrorStatus+ }+ response = endpoint.Response.AnyOf[1]+ }+ if status != expectedStatus || mediaType != "application/json" {+ return fmt.Errorf("unexpected response status or media type: %d %s", status, contentType)+ }+ var value any+ if err := json.Unmarshal(payload, &value); err != nil {+ return err+ }+ return b.validate(response, value, "$")+ }+ return fmt.Errorf("unregistered API contract: %s %s", method, path)+}+func (b *Bundle) validate(schema *Schema, value any, path string) error {if len(schema.Enum) > 0 {matched := falsediff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 62776579fd..58c747609c 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -1885,6 +1885,41 @@],"additionalProperties": false},+ "CopyFileRequestInput": {+ "type": "object",+ "properties": {+ "dest": {+ "type": "string"+ },+ "src": {+ "type": "string"+ }+ },+ "required": [+ "dest",+ "src"+ ],+ "additionalProperties": false+ },+ "CopyFilesRequestInput": {+ "type": "object",+ "properties": {+ "destDir": {+ "type": "string"+ },+ "srcs": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "destDir",+ "srcs"+ ],+ "additionalProperties": false+ },"CopyStdMarkdownRequestInput": {"type": "object","properties": {@@ -2904,6 +2939,30 @@],"additionalProperties": false},+ "DirectoryEntry": {+ "type": "object",+ "properties": {+ "isDir": {+ "type": "boolean"+ },+ "isSymlink": {+ "type": "boolean"+ },+ "name": {+ "type": "string"+ },+ "updated": {+ "type": "integer"+ }+ },+ "required": [+ "isDir",+ "isSymlink",+ "name",+ "updated"+ ],+ "additionalProperties": false+ },"DocAttrView": {"type": "object","properties": {@@ -3308,6 +3367,30 @@],"additionalProperties": false},+ "FilePathData": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string"+ }+ },+ "required": [+ "path"+ ],+ "additionalProperties": false+ },+ "FilePathRequestInput": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string"+ }+ },+ "required": [+ "path"+ ],+ "additionalProperties": false+ },"FullBlockInfo": {"type": "object","properties": {@@ -5659,6 +5742,40 @@],"additionalProperties": false},+ "PutFileRequestInput": {+ "type": "object",+ "properties": {+ "app": {+ "type": "string"+ },+ "file": {+ "type": "string",+ "format": "binary"+ },+ "isDir": {+ "type": "string"+ },+ "modTime": {+ "type": "string"+ },+ "path": {+ "type": "string"+ }+ },+ "additionalProperties": false+ },+ "ReadDirectoryRequestInput": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string"+ }+ },+ "required": [+ "path"+ ],+ "additionalProperties": false+ },"RecentDoc": {"type": "object","properties": {@@ -5906,6 +6023,28 @@],"additionalProperties": false},+ "RemoveFileRequestInput": {+ "type": "object",+ "properties": {+ "app": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "path": {+ "type": "string"+ }+ },+ "required": [+ "path"+ ],+ "additionalProperties": false+ },"RemoveShorthandsRequestInput": {"type": "object","properties": {@@ -5949,6 +6088,22 @@],"additionalProperties": false},+ "RenameFileRequestInput": {+ "type": "object",+ "properties": {+ "newPath": {+ "type": "string"+ },+ "path": {+ "type": "string"+ }+ },+ "required": [+ "newPath",+ "path"+ ],+ "additionalProperties": false+ },"RenameNotebookRequestInput": {"type": "object","properties": {@@ -15291,6 +15446,699 @@]}},+ {+ "method": "POST",+ "path": "/api/file/copyFile",+ "handler": "copyFile",+ "body": "json",+ "request": {+ "$ref": "#/$defs/CopyFileRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ -2+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/file/getFile",+ "handler": "getFile",+ "body": "json",+ "request": {+ "$ref": "#/$defs/FilePathRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "string",+ "format": "binary"+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ -3,+ 403,+ 404,+ 409,+ 500,+ 503+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ },+ "output": "binary",+ "errorStatus": 202+ },+ {+ "method": "POST",+ "path": "/api/file/getUniqueFilename",+ "handler": "getUniqueFilename",+ "body": "json",+ "request": {+ "$ref": "#/$defs/FilePathRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/FilePathData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ -3+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/file/globalCopyFiles",+ "handler": "globalCopyFiles",+ "body": "json",+ "request": {+ "$ref": "#/$defs/CopyFilesRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ -2,+ -3,+ 403+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/file/putFile",+ "handler": "putFile",+ "body": "form",+ "request": {+ "$ref": "#/$defs/PutFileRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ -3,+ 400,+ 403,+ 500+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/file/readDir",+ "handler": "readDir",+ "body": "json",+ "request": {+ "$ref": "#/$defs/ReadDirectoryRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/DirectoryEntry"+ }+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ -3,+ 403,+ 404,+ 409,+ 500+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/file/removeFile",+ "handler": "removeFile",+ "body": "json",+ "request": {+ "$ref": "#/$defs/RemoveFileRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ -3,+ 403,+ 404,+ 500+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/file/renameFile",+ "handler": "renameFile",+ "body": "json",+ "request": {+ "$ref": "#/$defs/RenameFileRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ -3,+ 403,+ 404,+ 409,+ 500+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/file/workspaceCopyFiles",+ "handler": "workspaceCopyFiles",+ "body": "json",+ "request": {+ "$ref": "#/$defs/CopyFilesRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ -2,+ -3,+ 403+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },{"method": "POST","path": "/api/filetree/getPinnedDocs",diff --git a/kernel/apicontract/typescript.go b/kernel/apicontract/typescript.goindex 4d17476641..45024c4cfa 100644--- a/kernel/apicontract/typescript.go+++ b/kernel/apicontract/typescript.go@@ -135,8 +135,12 @@ func (b *Bundle) TypeScript(legacy []Route) []byte {if endpoint.Method != method {continue}- fmt.Fprintf(&output, " %s: {\n request: %s;\n response: %s;\n body: %s;\n };\n",+ fmt.Fprintf(&output, " %s: {\n request: %s;\n response: %s;\n body: %s;\n",quote(endpoint.Path), b.typeScript(endpoint.Request), b.typeScript(endpoint.Response), quote(string(endpoint.Body)))+ if endpoint.Output != "" {+ fmt.Fprintf(&output, " output: %s;\n", quote(string(endpoint.Output)))+ }+ output.WriteString(" };\n")}output.WriteString("}\n\n")}@@ -171,7 +175,7 @@ type APIContract = {request: unknown; response: unknown; body: string};export interface APIFormData<Request> extends FormData {readonly apiRequest: Request;}-type APIRequestArgs<C extends APIContract> = C["body"] extends "multipart"+type APIRequestArgs<C extends APIContract> = C["body"] extends "multipart" | "form"? [data: APIFormData<C["request"]>]: C["body"] extends "json" | "structJSON"? [data: C["request"]]@@ -182,7 +186,7 @@ export type APICallbackResponse<R> = R extends {code: infer C extends number}: never;type APIPostTail<C extends APIContract> = [- cb?: (response: APICallbackResponse<C["response"]>) => void,+ cb?: (response: C extends {output: "binary"} ? JSONValue : APICallbackResponse<C["response"]>) => void,headers?: Record<string, string>,failCallback?: (response: APIFetchFailure) => void,signal?: AbortSignal,@@ -213,7 +217,9 @@ export type FetchSyncPost<Legacy = APILegacyResponse> = <Path extends string>(? [...APIRequestArgs<APIPOSTRoutes[Path]>, ...APISyncTail]: Path extends APILegacyPOSTPath ? [data?: any, ...tail: APISyncTail]: string extends Path ? [data?: any, ...tail: APISyncTail] : never-) => Promise<Path extends keyof APIPOSTRoutes ? APIPOSTRoutes[Path]["response"] | APITransportError : Legacy>;+) => Promise<Path extends keyof APIPOSTRoutes+ ? APIPOSTRoutes[Path] extends {output: "binary"} ? JSONValue : APIPOSTRoutes[Path]["response"] | APITransportError+ : Legacy>;export type FetchGet<Legacy = APILegacyResponse | string> = <Path extends string>(url: Path,