An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Expire desktop workspace sessions after reopening https://github.com/siyuan-note/siyuan/issues/21042
Daniel754558f93660
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex ba69e6d7b4..6afebd532b 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -8363,6 +8363,12 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 校验锁屏密码并建立当前工作空间的会话。+ * rememberMe 为 true 时 Cookie 有效期为 30 天;否则使用浏览器会话 Cookie,+ * 本机桌面端登录还绑定本次内核启动,工作空间退出重开后须重新认证;隐藏窗口或取消退出不使会话失效。+ * 浏览器、移动端及旧版未携带启动批次的 Cookie 保持原有有效性;旧会话重新登录后应用上述规则。+ */"/api/system/loginAuth": {request: SystemLoginAuthRequestInput;response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -8391,6 +8397,9 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["public"];};+ /**+ * 发起 OIDC 登录;rememberMe 的会话有效期及本机桌面启动绑定与 loginAuth 一致。+ */"/api/system/oidc/start": {request: SystemOIDCStartRequestInput;response: { "code": 0; "data": SystemOIDCStartData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -8472,6 +8481,10 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 修改锁屏密码并更新当前会话;已有有效会话保留其启动绑定及记住策略。+ * 没有有效会话时,本机桌面端新建的会话绑定本次内核启动。+ */"/api/system/setAccessAuthCode": {request: SystemAccessAuthCodeRequestInput;response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/kernel/api/system.go b/kernel/api/system.goindex f8e0dffcf6..cd9c58b61a 100644--- a/kernel/api/system.go+++ b/kernel/api/system.go@@ -921,11 +921,14 @@ var setAccessAuthCode = contractHandler(apicontract.SystemSetAccessAuthCode, fun}}+ session := util.GetSession(c)+ workspaceSession := util.GetWorkspaceSession(session)+ if !model.IsWorkspaceSessionAuthenticated(workspaceSession) {+ model.BindDesktopSession(c, workspaceSession, false)+ }model.Conf.AccessAuthCode = aacmodel.Conf.Save()- session := util.GetSession(c)- workspaceSession := util.GetWorkspaceSession(session)workspaceSession.AccessAuthCode = aacsession.Save(c)go func() {diff --git a/kernel/api/system_test.go b/kernel/api/system_test.goindex 78a9e1a0c6..30efe723af 100644--- a/kernel/api/system_test.go+++ b/kernel/api/system_test.go@@ -10,6 +10,7 @@ import ("net/http/httptest""strings""testing"+ "time"ginSessions "github.com/gin-contrib/sessions""github.com/gin-contrib/sessions/cookie"@@ -19,6 +20,68 @@ import ("github.com/siyuan-note/siyuan/kernel/util")+func TestContractSetAccessAuthCodeDesktopSession(t *testing.T) {+ oldConf, oldReadonly, oldContainer, oldDir := model.Conf, util.ReadOnly, util.Container, util.WorkspaceDir+ t.Cleanup(func() {+ // 等待设置接口发出的延迟界面刷新,避免其读取后续测试的全局配置。+ time.Sleep(250 * time.Millisecond)+ model.Conf, util.ReadOnly, util.Container, util.WorkspaceDir = oldConf, oldReadonly, oldContainer, oldDir+ })+ util.ReadOnly, util.Container, util.WorkspaceDir = true, util.ContainerStd, "desktop-session-setting"+ for _, mode := range []string{"new", "bound", "remembered", "expired"} {+ t.Run(mode, func(t *testing.T) {+ model.Conf = model.NewAppConf()+ model.Conf.AccessAuthCode = "old-password"+ engine := gin.New()+ engine.Use(ginSessions.Sessions("siyuan", cookie.NewStore([]byte("desktop-setting-test-key"))))+ engine.GET("/seed", func(c *gin.Context) {+ session := util.GetSession(c)+ ws := util.GetWorkspaceSession(session)+ if mode != "new" {+ ws.AccessAuthCode = model.Conf.AccessAuthCode+ model.BindDesktopSession(c, ws, mode == "remembered")+ if mode == "expired" {+ ws.DesktopSessionID = "previous-boot"+ }+ }+ if err := session.Save(c); err != nil {+ t.Fatal(err)+ }+ })+ engine.POST("/api/system/setAccessAuthCode", setAccessAuthCode)+ engine.GET("/session", func(c *gin.Context) { c.JSON(200, util.GetWorkspaceSession(util.GetSession(c))) })+ call := func(method, path, body string, cookies []*http.Cookie) *httptest.ResponseRecorder {+ r := httptest.NewRequest(method, "http://127.0.0.1:6806"+path, strings.NewReader(body))+ r.RemoteAddr = "127.0.0.1:1234"+ r.Header.Set("User-Agent", "SiYuan/3.8.9 https://b3log.org/siyuan Electron Chrome/140")+ r.Header.Set("Content-Type", "application/json")+ for _, value := range cookies {+ r.AddCookie(value)+ }+ w := httptest.NewRecorder()+ engine.ServeHTTP(w, r)+ return w+ }+ seed := call("GET", "/seed", "", nil).Result().Cookies()+ if mode == "new" {+ model.Conf.AccessAuthCode = ""+ }+ result := call("POST", "/api/system/setAccessAuthCode", `{"accessAuthCode":"new-password"}`, seed)+ var response struct{ Code int }+ if err := json.Unmarshal(result.Body.Bytes(), &response); err != nil || response.Code != 0 {+ t.Fatalf("setting password failed: %s, %v", result.Body.String(), err)+ }+ var ws util.WorkspaceSession+ if err := json.Unmarshal(call("GET", "/session", "", result.Result().Cookies()).Body.Bytes(), &ws); err != nil {+ t.Fatal(err)+ }+ if (ws.DesktopSessionID != "") != (mode != "remembered") || !model.IsAccessCodeSessionAuthenticated(&ws) {+ t.Fatalf("password setting lost session policy: %+v", ws)+ }+ })+ }+}+func TestSetOIDCRejectsUnverifiedEnabledConfiguration(t *testing.T) {gin.SetMode(gin.TestMode)previousConf := model.Confdiff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex dfdbce023e..4cb1f21f81 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -1776,6 +1776,11 @@ var SystemGetWorkspaces = define[EmptyRequest, []*SystemWorkspace]("getWorkspacevar SystemImportConf = define[SystemImportConfRequest, Null]("importConf", "/api/system/importConf", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{Setting: SettingWrite{Namespace: "*"}}, "POST")var SystemImportCustomFont = define[SystemImportFileRequest, *SystemCustomFont]("importCustomFont", "/api/system/importCustomFont", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{AdditionalCodes: []int{400, 413}}, "POST")var SystemImportTLSCABundle = define[SystemImportFileRequest, SystemMessageData]("importTLSCABundle", "/api/system/importTLSCABundle", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{}, "POST")++// SystemLoginAuth 校验锁屏密码并建立当前工作空间的会话。+// rememberMe 为 true 时 Cookie 有效期为 30 天;否则使用浏览器会话 Cookie,+// 本机桌面端登录还绑定本次内核启动,工作空间退出重开后须重新认证;隐藏窗口或取消退出不使会话失效。+// 浏览器、移动端及旧版未携带启动批次的 Cookie 保持原有有效性;旧会话重新登录后应用上述规则。var SystemLoginAuth = define[SystemLoginAuthRequest, Null]("loginAuth", "/api/system/loginAuth", PublicAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")// SystemUploadLockScreenWallpaper 替换本工作空间唯一的壁纸文件,需管理员写权限。@@ -1794,6 +1799,8 @@ var SystemGetLockScreenWallpaper = define[EmptyRequest, BinaryContent]("getLockSvar SystemLogoutAuth = define[EmptyRequest, Null]("logoutAuth", "/api/system/logoutAuth", PublicAccess, NoBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var SystemOIDCMobileCallback = define[SystemOIDCMobileRequest, SystemOIDCMobileData]("oidcMobileCallback", "/api/system/oidc/mobileCallback", PublicAccess, StructJSONBody, ResponseOptions{}, "POST")var SystemOIDCPoll = define[SystemOIDCPollRequest, SystemOIDCPollData]("oidcPoll", "/api/system/oidc/poll", PublicAccess, StructJSONBody, ResponseOptions{}, "POST")++// SystemOIDCStart 发起 OIDC 登录;rememberMe 的会话有效期及本机桌面启动绑定与 loginAuth 一致。var SystemOIDCStart = define[SystemOIDCStartRequest, SystemOIDCStartData]("oidcStart", "/api/system/oidc/start", PublicAccess, StructJSONBody, ResponseOptions{}, "POST")var SystemOIDCValidateStart = define[SystemOIDCRequest, SystemOIDCStartData]("oidcValidateStart", "/api/system/oidc/validate", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{}, "POST")var SystemOIDCValidateActivate = define[SystemOIDCPollRequest, SystemOIDCActivateData]("oidcValidateActivate", "/api/system/oidc/validateActivate", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{}, "POST")@@ -1803,6 +1810,9 @@ var SystemRemoveCustomFont = define[SystemRemoveCustomFontRequest, SystemRemoveCvar SystemRemoveWorkspaceDir = define[SystemPathRequest, Null]("removeWorkspaceDir", "/api/system/removeWorkspaceDir", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var SystemRemoveWorkspaceDirPhysically = define[SystemPathRequest, Null]("removeWorkspaceDirPhysically", "/api/system/removeWorkspaceDirPhysically", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var SystemSetAPIToken = define[SystemAPITokenRequest, Null]("setAPIToken", "/api/system/setAPIToken", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")++// SystemSetAccessAuthCode 修改锁屏密码并更新当前会话;已有有效会话保留其启动绑定及记住策略。+// 没有有效会话时,本机桌面端新建的会话绑定本次内核启动。var SystemSetAccessAuthCode = define[SystemAccessAuthCodeRequest, Null]("setAccessAuthCode", "/api/system/setAccessAuthCode", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")var SystemSetAppearanceMode = define[SystemAppearanceModeRequest, SystemAppearanceData]("setAppearanceMode", "/api/system/setAppearanceMode", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "appearance"}}, "POST")var SystemSetOIDC = define[SystemOIDCRequest, *SystemOIDC]("setOIDC", "/api/system/setOIDC", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")diff --git a/kernel/model/auth_session.go b/kernel/model/auth_session.goindex ab354c6d85..65eea162ce 100644--- a/kernel/model/auth_session.go+++ b/kernel/model/auth_session.go@@ -6,9 +6,11 @@ package modelimport ("crypto/hmac"+ "crypto/rand""crypto/sha256""encoding/base64""net/http"+ "strings""github.com/88250/gulu"ginSessions "github.com/gin-contrib/sessions"@@ -17,6 +19,23 @@ import ("github.com/siyuan-note/siyuan/kernel/util")+var desktopSessionID = rand.Text()++// BindDesktopSession 将未记住的本机桌面登录绑定到本次内核启动;窗口隐藏及退出取消不改变绑定。+func BindDesktopSession(c *gin.Context, workspaceSession *util.WorkspaceSession, rememberMe bool) {+ workspaceSession.DesktopSessionID = ""+ if !rememberMe && util.Container == util.ContainerStd && IsLocalRequest(c) &&+ !util.IsBrowserRequest(c) && strings.Contains(c.GetHeader("User-Agent"), " Electron ") {+ workspaceSession.DesktopSessionID = desktopSessionID+ }+}++func isWorkspaceSessionCurrent(workspaceSession *util.WorkspaceSession) bool {+ // 旧版 Cookie 没有启动批次,保留其有效性;重新登录时按所选的记住策略建立绑定。+ return workspaceSession != nil && (workspaceSession.DesktopSessionID == "" ||+ hmac.Equal([]byte(workspaceSession.DesktopSessionID), []byte(desktopSessionID)))+}+func IsAccessAuthRequired() bool {return Conf.AccessAuthCode != "" || Conf.GetOIDC().Enabled}@@ -26,12 +45,12 @@ func IsWorkspaceSessionAuthenticated(workspaceSession *util.WorkspaceSession) bo}func IsAccessCodeSessionAuthenticated(workspaceSession *util.WorkspaceSession) bool {- return workspaceSession != nil && Conf.AccessAuthCode != "" &&+ return isWorkspaceSessionCurrent(workspaceSession) && Conf.AccessAuthCode != "" &&util.AuthCodeEquals(Conf.AccessAuthCode, workspaceSession.AccessAuthCode)}func IsOIDCSessionAuthenticated(workspaceSession *util.WorkspaceSession) bool {- return workspaceSession != nil && IsOIDCSessionVersionCurrent(workspaceSession.OIDCSessionVersion)+ return isWorkspaceSessionCurrent(workspaceSession) && IsOIDCSessionVersionCurrent(workspaceSession.OIDCSessionVersion)}func IsOIDCSessionVersionCurrent(version string) bool {@@ -40,6 +59,7 @@ func IsOIDCSessionVersionCurrent(version string) bool {func applyAuthenticatedSession(c *gin.Context, workspaceSession *util.WorkspaceSession, rememberMe bool) {workspaceSession.OIDCSessionVersion = oidcSessionVersion()+ BindDesktopSession(c, workspaceSession, rememberMe)maxAge := 0if rememberMe {maxAge = 60 * 60 * 24 * 30diff --git a/kernel/model/auth_session_test.go b/kernel/model/auth_session_test.gonew file mode 100644index 0000000000..8081ca0417--- /dev/null+++ b/kernel/model/auth_session_test.go@@ -0,0 +1,156 @@+// SiYuan - https://github.com/siyuan-note/siyuan+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package model++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ ginSessions "github.com/gin-contrib/sessions"+ "github.com/gin-contrib/sessions/cookie"+ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestDesktopSessionLifecycle(t *testing.T) {+ setupOIDCTest(t)+ oldID, oldDir, oldContainer, oldWrong := desktopSessionID, util.WorkspaceDir, util.Container, util.WrongAuthCount+ t.Cleanup(func() {+ desktopSessionID, util.WorkspaceDir, util.Container, util.WrongAuthCount = oldID, oldDir, oldContainer, oldWrong+ })+ Conf.AccessAuthCode = "desktop-password"+ util.WrongAuthCount = 0+ const desktopUA = "SiYuan/3.8.9 https://b3log.org/siyuan Electron Chrome/140"+ for _, method := range []string{"password", "oidc"} {+ for _, tc := range []struct {+ name, ua, address, container string+ remember, bound bool+ }{+ {"desktop session", desktopUA, "127.0.0.1:1234", util.ContainerStd, false, true},+ {"remembered desktop", desktopUA, "127.0.0.1:1234", util.ContainerStd, true, false},+ {"browser", "Mozilla/5.0", "127.0.0.1:1234", util.ContainerStd, false, false},+ {"remote desktop", desktopUA, "192.0.2.1:1234", util.ContainerStd, false, false},+ {"mobile", "SiYuan/3.8.9 Android", "127.0.0.1:1234", util.ContainerAndroid, false, false},+ {"server", desktopUA, "127.0.0.1:1234", util.ContainerDocker, false, false},+ } {+ t.Run(method+"/"+tc.name, func(t *testing.T) {+ util.Container, util.WorkspaceDir, desktopSessionID = tc.container, "Note1", "boot-one"+ engine := gin.New()+ engine.Use(ginSessions.Sessions("siyuan", cookie.NewStore([]byte("desktop-session-test-key"))))+ engine.POST("/login", func(c *gin.Context) {+ if method == "password" {+ result := LoginAuth(c, apicontract.SystemLoginAuthRequest{AuthCode: Conf.AccessAuthCode, RememberMe: tc.remember})+ if result.Code() != 0 {+ t.Fatalf("login failed: %+v", result)+ }+ } else if err := authenticateOIDCSession(c, tc.remember); err != nil {+ t.Fatal(err)+ }+ })+ engine.GET("/session", func(c *gin.Context) { c.JSON(200, util.GetWorkspaceSession(util.GetSession(c))) })+ engine.GET("/stage/build/app/", CheckAuth, func(c *gin.Context) { c.Status(http.StatusNoContent) })+ request := func(path string, cookies []*http.Cookie) *httptest.ResponseRecorder {+ verb := http.MethodGet+ if path == "/login" {+ verb = http.MethodPost+ }+ r := httptest.NewRequest(verb, "http://127.0.0.1:6806"+path, nil)+ r.RemoteAddr = tc.address+ r.Header.Set("User-Agent", tc.ua)+ for _, value := range cookies {+ r.AddCookie(value)+ }+ w := httptest.NewRecorder()+ engine.ServeHTTP(w, r)+ return w+ }+ login := request("/login", nil)+ cookies := login.Result().Cookies()+ if len(cookies) != 1 {+ t.Fatalf("expected a login cookie, got %d", len(cookies))+ }+ if (cookies[0].MaxAge == 2592000) != tc.remember {+ t.Fatal("remembered lifetime changed")+ }+ var session util.WorkspaceSession+ if err := json.Unmarshal(request("/session", cookies).Body.Bytes(), &session); err != nil {+ t.Fatal(err)+ }+ if (session.DesktopSessionID != "") != tc.bound {+ t.Fatalf("unexpected binding: %+v", session)+ }+ for range 2 {+ if got := request("/stage/build/app/", cookies); got.Code != http.StatusNoContent {+ t.Fatalf("same kernel (including hide/canceled exit) rejected session: %d", got.Code)+ }+ }+ desktopSessionID = "boot-two"+ got := request("/stage/build/app/", cookies)+ if tc.bound {+ if got.Code != http.StatusFound || !strings.HasPrefix(got.Header().Get("Location"), "/check-auth") {+ t.Fatalf("reopened workspace did not require authentication: %d %s", got.Code, got.Header().Get("Location"))+ }+ if IsAccessCodeSessionAuthenticated(&session) || IsOIDCSessionAuthenticated(&session) {+ t.Fatal("WebSocket authentication helpers accepted an expired session")+ }+ } else if got.Code != http.StatusNoContent {+ t.Fatalf("unbound session expired: %d", got.Code)+ }+ // 重新登录必须替换旧绑定;选择记住时也必须移除已有绑定。+ fresh := request("/login", cookies).Result().Cookies()+ if got := request("/stage/build/app/", fresh); got.Code != http.StatusNoContent {+ t.Fatal("relogin failed")+ }+ if tc.bound {+ tc.remember = true+ remembered := request("/login", fresh).Result().Cookies()+ desktopSessionID = "boot-three"+ if got := request("/stage/build/app/", remembered); got.Code != http.StatusNoContent {+ t.Fatal("remembered relogin retained the old desktop binding")+ }+ tc.remember = false+ unremembered := request("/login", remembered).Result().Cookies()+ desktopSessionID = "boot-four"+ if got := request("/stage/build/app/", unremembered); got.Code != http.StatusFound {+ t.Fatal("unremembered relogin did not restore the desktop binding")+ }+ }+ })+ }+ }+}++func TestDesktopSessionWorkspaceIsolationAndLegacyCookies(t *testing.T) {+ setupOIDCTest(t)+ oldDir, oldID := util.WorkspaceDir, desktopSessionID+ t.Cleanup(func() { util.WorkspaceDir, desktopSessionID = oldDir, oldID })+ Conf.AccessAuthCode = "password"+ var sessions util.SessionData+ if err := json.Unmarshal([]byte(`{"Workspaces":{"Note1":{"AccessAuthCode":"password","DesktopSessionID":"boot-one"},"Note2":{"AccessAuthCode":"password","DesktopSessionID":"boot-two"},"legacy":{"AccessAuthCode":"password"}}}`), &sessions); err != nil {+ t.Fatal(err)+ }+ for _, tc := range []struct {+ workspace, boot string+ valid bool+ }{+ {"Note1", "boot-one", true}, {"Note1", "reopened-one", false},+ {"Note2", "boot-two", true}, {"legacy", "reopened-one", true},+ } {+ util.WorkspaceDir, desktopSessionID = tc.workspace, tc.boot+ if IsWorkspaceSessionAuthenticated(util.GetWorkspaceSession(&sessions)) != tc.valid {+ t.Fatalf("unexpected authentication for %s at %s", tc.workspace, tc.boot)+ }+ }+ if len(sessions.Workspaces) != 3 || sessions.Workspaces["Note1"].DesktopSessionID != "boot-one" {+ t.Fatal("checking an expired workspace mutated the shared cookie")+ }+ if IsWorkspaceSessionAuthenticated(nil) {+ t.Fatal("nil session was authenticated")+ }+}diff --git a/kernel/model/session.go b/kernel/model/session.goindex 0227f242b5..6e8738a472 100644--- a/kernel/model/session.go+++ b/kernel/model/session.go@@ -112,6 +112,7 @@ func LoginAuth(c *gin.Context, request apicontract.SystemLoginAuthRequest) (retworkspaceSession.AccessAuthCode = authCodeworkspaceSession.OIDCSessionVersion = ""+ BindDesktopSession(c, workspaceSession, request.RememberMe)util.WrongAuthCount = 0util.AuthThrottleReset(c.ClientIP())workspaceSession.CaptchaID = ""diff --git a/kernel/server/serve_websocket_test.go b/kernel/server/serve_websocket_test.goindex d2f906012b..dabca0e9f4 100644--- a/kernel/server/serve_websocket_test.go+++ b/kernel/server/serve_websocket_test.go@@ -5,12 +5,16 @@package serverimport (+ "errors"+ "net""net/http""net/http/httptest""strings""testing""time"+ ginSessions "github.com/gin-contrib/sessions"+ "github.com/gin-contrib/sessions/cookie""github.com/gin-gonic/gin""github.com/gorilla/websocket""github.com/olahol/melody"@@ -19,6 +23,56 @@ import ("github.com/siyuan-note/siyuan/kernel/util")+func TestWebSocketDesktopSessionAuthentication(t *testing.T) {+ oldStore, oldDir, oldContainer := sessionStore, util.WorkspaceDir, util.Container+ t.Cleanup(func() { sessionStore, util.WorkspaceDir, util.Container = oldStore, oldDir, oldContainer })+ sessionStore = cookie.NewStore([]byte("desktop-websocket-session-test-key"))+ util.WorkspaceDir, util.Container = "Note1", util.ContainerStd+ srv := newWebSocketTestServer(t)+ model.Conf.AccessAuthCode = "desktop-password"+ for _, state := range []string{"current", "remembered", "expired"} {+ t.Run(state, func(t *testing.T) {+ engine := gin.New()+ engine.Use(ginSessions.Sessions("siyuan", sessionStore))+ engine.GET("/login", func(c *gin.Context) {+ session := util.GetSession(c)+ ws := util.GetWorkspaceSession(session)+ ws.AccessAuthCode = model.Conf.AccessAuthCode+ model.BindDesktopSession(c, ws, state == "remembered")+ if state == "expired" {+ ws.DesktopSessionID = "previous-kernel-boot"+ }+ if err := session.Save(c); err != nil {+ t.Fatal(err)+ }+ })+ r := httptest.NewRequest("GET", "http://127.0.0.1/login", nil)+ r.RemoteAddr = "127.0.0.1:1234"+ r.Header.Set("User-Agent", "SiYuan/3.8.9 https://b3log.org/siyuan Electron Chrome/140")+ w := httptest.NewRecorder()+ engine.ServeHTTP(w, r)+ cookies := w.Result().Cookies()+ if len(cookies) != 1 {+ t.Fatal("missing fixture cookie")+ }+ header := http.Header{"Cookie": []string{cookies[0].Name + "=" + cookies[0].Value}}+ connection := dialWebSocket(t, srv, state, header)+ if state != "expired" {+ waitWebSocketSession(t, connection, state)+ return+ }+ if err := connection.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {+ t.Fatal(err)+ }+ _, _, err := connection.ReadMessage()+ var networkErr net.Error+ if err == nil || (errors.As(err, &networkErr) && networkErr.Timeout()) {+ t.Fatalf("expired session was not closed by authentication: %v", err)+ }+ })+ }+}+func TestWebSocketRejectsMalformedMessages(t *testing.T) {server := melody.New()defer server.Close()diff --git a/kernel/util/session.go b/kernel/util/session.goindex e814d443a9..6bdd2a18f8 100644--- a/kernel/util/session.go+++ b/kernel/util/session.go@@ -146,6 +146,7 @@ type SessionData struct {type WorkspaceSession struct {AccessAuthCode stringOIDCSessionVersion string+ DesktopSessionID string `json:",omitempty"` // 未记住的本机桌面登录所属内核启动批次OIDCBinding stringCaptchaID string // 服务端验证码挑战 ID,验证码答案不写入会话}