An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
♻️ Migrate account API contracts https://github.com/siyuan-note/siyuan/issues/19378
Daniel82de061aebef
diff --git a/app/src/config/tabs/accountUi.ts b/app/src/config/tabs/accountUi.tsindex 94f8c0586e..77734a9bb1 100644--- a/app/src/config/tabs/accountUi.ts+++ b/app/src/config/tabs/accountUi.ts@@ -477,7 +477,7 @@ const bindAccountAuthForm = (}, (loginResponse) => {if (loginResponse.code === 1) {showMessage(loginResponse.msg);- needCaptcha = loginResponse.data.needCaptcha;+ needCaptcha = loginResponse.data && "needCaptcha" in loginResponse.data ? loginResponse.data.needCaptcha || "" : "";if (needCaptcha) {// 验证码captchaInput.value = "";@@ -487,6 +487,9 @@ const bindAccountAuthForm = (return;}if (loginResponse.code === 10) {+ if (!loginResponse.data || !("token" in loginResponse.data) || !loginResponse.data.token) {+ return;+ }// 两步验证authFormRoot.querySelector("#form1")?.classList.add("fn__none");authFormRoot.querySelector("#form2")?.classList.remove("fn__none");diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex ec72a43357..79232a7630 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -1,5 +1,11 @@// 此文件由内核契约生成,请运行 pnpm run api:generate 更新。+export type AccountLoginData = { "needCaptcha": string | null; "token": string | null; "userName": string | null; };++export type AccountLoginRequestInput = { "captcha": string; "cloudRegion": number; "userName": string; "userPassword": string; };++export type ActivationCodeRequestInput = { "data": string; };+export type AppendBlockRequestInput = { "data": string; "dataType": string; "parentID": string; };export type AppendHeadingChildrenRequestInput = { "childrenDOM": string; "id": string; };@@ -98,6 +104,8 @@ export type ChangeMasterPasswordRequestInput = { "newPassword": string; "oldPassexport type ChangeSortNotebookRequestInput = { "notebooks": Array<string>; };+export type CheckActivationCodeRequestInput = { "data": string; };+export type CheckBlockRefRequestInput = { "deletedIDs"?: Array<string>; "exactIDs"?: Array<string>; "id"?: string | null; "ids"?: Array<string>; "notebook"?: string | null; "paths"?: Array<string>; "scope"?: string; };export type CheckBlocksExistRequestInput = { "id"?: string | null; "ids": Array<JSONValue>; "notebook"?: string | null; };@@ -507,11 +515,6 @@ export interface APIGETRoutes {}export type APILegacyPOSTPath =- "/api/account/checkActivationcode" |- "/api/account/deactivate" |- "/api/account/login" |- "/api/account/startFreeTrial" |- "/api/account/useActivationcode" |"/api/ai/agent/browserCapabilityResult" |"/api/ai/agent/chat" |"/api/ai/agent/confirm" |@@ -923,6 +926,31 @@ export type APILegacyPOSTPath ="/plugin/private/:name/*path";export interface APIPOSTRoutes {+ "/api/account/checkActivationcode": {+ request: CheckActivationCodeRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null | null; "msg": string; };+ body: "json";+ };+ "/api/account/deactivate": {+ request: EmptyRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "none";+ };+ "/api/account/login": {+ request: AccountLoginRequestInput;+ response: { "code": 0; "data": AccountLoginData | null; "msg": string; } | { "code": -1 | 1 | 10; "data": { "closeTimeout": number; } | null | AccountLoginData | null; "msg": string; };+ body: "json";+ };+ "/api/account/startFreeTrial": {+ request: EmptyRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "none";+ };+ "/api/account/useActivationcode": {+ request: ActivationCodeRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };"/api/archive/unzip": {request: UnzipRequestInput;response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/kernel/api/account.go b/kernel/api/account.goindex 0c3a9ab0d7..5c9a407b0e 100644--- a/kernel/api/account.go+++ b/kernel/api/account.go@@ -17,87 +17,49 @@package apiimport (- "net/http"+ "encoding/json""github.com/88250/gulu""github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract""github.com/siyuan-note/siyuan/kernel/model"- "github.com/siyuan-note/siyuan/kernel/util")-func startFreeTrial(c *gin.Context) {- ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)-- err := model.StartFreeTrial()- if err != nil {- ret.Code = -1- ret.Msg = err.Error()- return- }-}--func useActivationcode(c *gin.Context) {- ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)-- arg, ok := util.JsonArg(c, ret)- if !ok {- return+var startFreeTrial = contractHandler(apicontract.StartFreeTrial, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.Null] {+ if err := model.StartFreeTrial(); err != nil {+ return apicontract.Failure[apicontract.Null](-1, err.Error())}-- var code string- if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("data", &code, true, true)) {- return+ return apicontract.Success(apicontract.Null{})+})+var useActivationcode = contractHandler(apicontract.UseActivationCode, func(c *gin.Context, request apicontract.ActivationCodeRequest) apicontract.Response[apicontract.Null] {+ if err := model.UseActivationcode(request.Data); err != nil {+ return apicontract.Failure[apicontract.Null](-1, err.Error())}- err := model.UseActivationcode(code)- if err != nil {- ret.Code = -1- ret.Msg = err.Error()- return+ return apicontract.Success(apicontract.Null{})+})+var checkActivationcode = contractHandler(apicontract.CheckActivationCode, func(c *gin.Context, request apicontract.CheckActivationCodeRequest) apicontract.Response[apicontract.Null] {+ code, msg := model.CheckActivationcode(request.Data)+ return apicontract.CheckActivationCode.FailureWithData(code, msg, apicontract.Null{})+})+var deactivateUser = contractHandler(apicontract.DeactivateUser, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.Null] {+ if err := model.DeactivateUser(); err != nil {+ return apicontract.Failure[apicontract.Null](-1, err.Error())}-}--func checkActivationcode(c *gin.Context) {- ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)+ return apicontract.Success(apicontract.Null{})+})+var login = contractHandler(apicontract.AccountLogin, func(c *gin.Context, request apicontract.AccountLoginRequest) apicontract.Response[*apicontract.AccountLoginData] {+ result := model.Login(request.UserName, request.UserPassword, request.Captcha, int(request.CloudRegion))+ return accountLoginResponse(result)+})- arg, ok := util.JsonArg(c, ret)- if !ok {- return- }-- var code string- if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("data", &code, true, false)) {- return- }- ret.Code, ret.Msg = model.CheckActivationcode(code)-}--func deactivateUser(c *gin.Context) {- ret := gulu.Ret.NewResult()- defer c.JSON(http.StatusOK, ret)-- err := model.DeactivateUser()+func accountLoginResponse(result *gulu.Result) apicontract.Response[*apicontract.AccountLoginData] {+ raw, err := json.Marshal(result.Data)if err != nil {- ret.Code = -1- ret.Msg = err.Error()- return+ return apicontract.Failure[*apicontract.AccountLoginData](-1, err.Error())}-}--func login(c *gin.Context) {- ret := gulu.Ret.NewResult()- arg, ok := util.JsonArg(c, ret)- if !ok {- c.JSON(http.StatusOK, ret)- return+ var data *apicontract.AccountLoginData+ if err = json.Unmarshal(raw, &data); err != nil {+ return apicontract.Failure[*apicontract.AccountLoginData](-1, err.Error())}-- name := arg["userName"].(string)- password := arg["userPassword"].(string)- captcha := arg["captcha"].(string)- cloudRegion := int(arg["cloudRegion"].(float64))- ret = model.Login(name, password, captcha, cloudRegion)- c.JSON(http.StatusOK, ret)+ return apicontract.AccountLogin.FailureWithData(result.Code, result.Msg, data)}diff --git a/kernel/api/contract_account_test.go b/kernel/api/contract_account_test.gonew file mode 100644index 0000000000..e210cfaeae--- /dev/null+++ b/kernel/api/contract_account_test.go@@ -0,0 +1,51 @@+package api++import (+ "encoding/json"+ "github.com/88250/gulu"+ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "net/http/httptest"+ "reflect"+ "strings"+ "testing"+)++func TestAPIContractAccountLoginResponses(t *testing.T) {+ for _, result := range []*gulu.Result{+ {Code: -1, Msg: "offline"},+ {Code: 1, Msg: "captcha", Data: map[string]any{"userName": nil, "token": nil, "needCaptcha": "user-id"}},+ {Code: 10, Data: map[string]any{"userName": nil, "token": "second-factor", "needCaptcha": nil}},+ {Code: 0, Data: map[string]any{"userName": "user", "token": "token", "needCaptcha": nil}},+ } {+ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)+ context.JSON(200, accountLoginResponse(result))+ requireAPIContract(t, "POST", "/api/account/login", recorder)+ original, _ := json.Marshal(result)+ var before, after map[string]any+ if err := json.Unmarshal(original, &before); err != nil {+ t.Fatal(err)+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &after); err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(before, after) {+ t.Fatalf("login response changed: %s != %s", original, recorder.Body.String())+ }+ }+}++func TestAPIContractAccountArguments(t *testing.T) {+ request, err := apicontract.AccountLogin.Decode(strings.NewReader(`{"userName":" user ","userPassword":" password ","captcha":" code ","cloudRegion":1.9}`))+ if err != nil || request.UserName != " user " || request.UserPassword != " password " || request.Captcha != " code " || int(request.CloudRegion) != 1 {+ t.Fatalf("login arguments changed: %#v, %v", request, err)+ }+ if _, err := apicontract.UseActivationCode.Decode(strings.NewReader(`{"data":" "}`)); err == nil {+ t.Fatal("blank activation code accepted")+ }+ check, err := apicontract.CheckActivationCode.Decode(strings.NewReader(`{"data":" "}`))+ if err != nil || check.Data != " " {+ t.Fatalf("activation check must retain blank input: %#v, %v", check, err)+ }+}diff --git a/kernel/apicontract/account.go b/kernel/apicontract/account.gonew file mode 100644index 0000000000..2628da4bff--- /dev/null+++ b/kernel/apicontract/account.go@@ -0,0 +1,19 @@+package apicontract++type ActivationCodeRequest struct {+ Data string `json:"data" api:"trim"`+}+type CheckActivationCodeRequest struct {+ Data string `json:"data"`+}+type AccountLoginRequest struct {+ UserName string `json:"userName"`+ UserPassword string `json:"userPassword"`+ Captcha string `json:"captcha"`+ CloudRegion float64 `json:"cloudRegion"`+}+type AccountLoginData struct {+ UserName *string `json:"userName"`+ Token *string `json:"token"`+ NeedCaptcha *string `json:"needCaptcha"`+}diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex ae2a400791..97e11e4307 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -447,3 +447,9 @@ var ReadClipboardFilePaths = define[EmptyRequest, []ClipboardFile]("readFilePathvar WriteClipboardFilePath = define[ClipboardPathRequest, Null]("writeFilePath", "/api/clipboard/writeFilePath", JSONBody, ResponseOptions{}, "POST")var PrepareRichText = define[PrepareRichTextRequest, *RichClipboardPrepared]("prepareRichText", "/api/clipboard/prepareRichText", JSONBody, ResponseOptions{}, "POST")var 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")diff --git a/kernel/apicontract/legacy_routes.json b/kernel/apicontract/legacy_routes.jsonindex b2fa78556e..af46427ba3 100644--- a/kernel/apicontract/legacy_routes.json+++ b/kernel/apicontract/legacy_routes.json@@ -18,11 +18,6 @@{"method":"GET","path":"/ws/network/proxy","handler":"wsProxy"},{"method":"GET","path":"/ws/plugin/rpc","handler":"pluginJsonRpcWebSocket"},{"method":"GET","path":"/ws/plugin/rpc/:name","handler":"pluginJsonRpcWebSocket"},- {"method":"POST","path":"/api/account/checkActivationcode","handler":"checkActivationcode"},- {"method":"POST","path":"/api/account/deactivate","handler":"deactivateUser"},- {"method":"POST","path":"/api/account/login","handler":"login"},- {"method":"POST","path":"/api/account/startFreeTrial","handler":"startFreeTrial"},- {"method":"POST","path":"/api/account/useActivationcode","handler":"useActivationcode"},{"method":"POST","path":"/api/ai/agent/browserCapabilityResult","handler":"agentChatBrowserCapabilityResult"},{"method":"POST","path":"/api/ai/agent/chat","handler":"agentChat"},{"method":"POST","path":"/api/ai/agent/confirm","handler":"agentChatConfirm"},diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 10f716a0e7..62776579fd 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -1,6 +1,83 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","$defs": {+ "AccountLoginData": {+ "type": "object",+ "properties": {+ "needCaptcha": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "token": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "userName": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "needCaptcha",+ "token",+ "userName"+ ],+ "additionalProperties": false+ },+ "AccountLoginRequestInput": {+ "type": "object",+ "properties": {+ "captcha": {+ "type": "string"+ },+ "cloudRegion": {+ "type": "number"+ },+ "userName": {+ "type": "string"+ },+ "userPassword": {+ "type": "string"+ }+ },+ "required": [+ "captcha",+ "cloudRegion",+ "userName",+ "userPassword"+ ],+ "additionalProperties": false+ },+ "ActivationCodeRequestInput": {+ "type": "object",+ "properties": {+ "data": {+ "type": "string"+ }+ },+ "required": [+ "data"+ ],+ "additionalProperties": false+ },"AppendBlockRequestInput": {"type": "object","properties": {@@ -1444,6 +1521,18 @@],"additionalProperties": false},+ "CheckActivationCodeRequestInput": {+ "type": "object",+ "properties": {+ "data": {+ "type": "string"+ }+ },+ "required": [+ "data"+ ],+ "additionalProperties": false+ },"CheckBlockRefRequestInput": {"type": "object","properties": {@@ -7907,6 +7996,404 @@]}},+ {+ "method": "POST",+ "path": "/api/account/checkActivationcode",+ "handler": "checkActivationcode",+ "body": "json",+ "request": {+ "$ref": "#/$defs/CheckActivationCodeRequestInput"+ },+ "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,+ 1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/account/deactivate",+ "handler": "deactivateUser",+ "body": "none",+ "request": {+ "$ref": "#/$defs/EmptyRequestInput"+ },+ "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+ ]+ },+ "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/account/login",+ "handler": "login",+ "body": "json",+ "request": {+ "$ref": "#/$defs/AccountLoginRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "anyOf": [+ {+ "$ref": "#/$defs/AccountLoginData"+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ 1,+ 10+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ },+ {+ "anyOf": [+ {+ "$ref": "#/$defs/AccountLoginData"+ },+ {+ "type": "null"+ }+ ]+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/account/startFreeTrial",+ "handler": "startFreeTrial",+ "body": "none",+ "request": {+ "$ref": "#/$defs/EmptyRequestInput"+ },+ "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+ ]+ },+ "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/account/useActivationcode",+ "handler": "useActivationcode",+ "body": "json",+ "request": {+ "$ref": "#/$defs/ActivationCodeRequestInput"+ },+ "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+ ]+ },+ "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/archive/unzip",