Skip to content

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

:sparkles: Support kernel plugin system (#17487)

Yingyi / 颖逸e564ce7b1fc5
diff --git a/kernel/api/broadcast.go b/kernel/api/broadcast.go
index 979a767125..9ccd49b568 100644
--- a/kernel/api/broadcast.go
+++ b/kernel/api/broadcast.go
@@ -524,10 +524,10 @@ func PruneBroadcastChannels() []string {
// "http://localhost:6806/es/broadcast/subscribe?retry=1000&channel=test1&channel=test2"
func broadcastSubscribe(c *gin.Context) {
// REF: https://github.com/gin-gonic/examples/blob/master/server-sent-event/main.go
- c.Writer.Header().Set("Content-Type", "text/event-stream")
- c.Writer.Header().Set("Cache-Control", "no-cache")
- c.Writer.Header().Set("Connection", "keep-alive")
- c.Writer.Header().Set("Transfer-Encoding", "chunked")
+ c.Header("Content-Type", "text/event-stream")
+ c.Header("Cache-Control", "no-cache")
+ c.Header("Connection", "keep-alive")
+ c.Header("Transfer-Encoding", "chunked")
defer UnifiedSSE.WaitGroup.Done()
UnifiedSSE.WaitGroup.Add(1)
diff --git a/kernel/api/network.go b/kernel/api/network.go
index 34f44a6c92..70561c6fb2 100644
--- a/kernel/api/network.go
+++ b/kernel/api/network.go
@@ -20,9 +20,9 @@ import (
"encoding/base32"
"encoding/base64"
"encoding/hex"
+ "encoding/json"
"fmt"
"io"
- "math"
"net"
"net/http"
"net/textproto"
@@ -33,6 +33,7 @@ import (
"github.com/88250/gulu"
"github.com/gin-gonic/gin"
+ "github.com/gorilla/websocket"
"github.com/imroc/req/v3"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/util"
@@ -56,13 +57,10 @@ func echo(c *gin.Context) {
var (
password string
- passwordSet bool
multipartForm *MultipartForm
rawData any
)
- password, passwordSet = c.Request.URL.User.Password()
-
if form, err := c.MultipartForm(); err != nil || nil == form {
multipartForm = nil
} else {
@@ -81,10 +79,10 @@ func echo(c *gin.Context) {
logging.LogWarnf("echo open form [%s] file [%s] error: %s", k, handler.Filename, err.Error())
} else {
content := make([]byte, handler.Size)
- if _, err := file.Read(content); err != nil {
+ if n, err := file.Read(content); err != nil {
logging.LogWarnf("echo read form [%s] file [%s] error: %s", k, handler.Filename, err.Error())
} else {
- files[i].Content = base64.StdEncoding.EncodeToString(content)
+ files[i].Content = base64.StdEncoding.EncodeToString(content[:n])
}
}
}
@@ -97,8 +95,8 @@ func echo(c *gin.Context) {
logging.LogWarnf("echo get raw data error: %s", err.Error())
rawData = nil
}
- c.Request.ParseForm()
- c.Request.ParseMultipartForm(math.MaxInt64)
+
+ username, password, ok := c.Request.BasicAuth()
ret.Data = map[string]any{
"Context": map[string]any{
@@ -144,10 +142,9 @@ func echo(c *gin.Context) {
"Port": c.Request.URL.Port(),
},
"User": map[string]any{
- "Username": c.Request.URL.User.Username(),
- "Password": password,
- "PasswordSet": passwordSet,
- "String": c.Request.URL.User.String(),
+ "Exists": ok,
+ "Username": username,
+ "Password": password,
},
}
}
@@ -278,7 +275,7 @@ func forwardProxy(c *gin.Context) {
return
}
- elapsed := time.Now().Sub(started)
+ elapsed := time.Since(started)
responseEncoding := "text"
if responseEncodingArg := arg["responseEncoding"]; nil != responseEncodingArg {
@@ -330,28 +327,31 @@ func forwardProxy(c *gin.Context) {
// elapsed.Seconds(), len(bodyData), data["url"], headers, contentType, arg["payload"], data["status"], shortBody)
}
-// 校验 IP 是否为私有内网地址
-func isPrivateIP(ip net.IP) bool {
- return ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsPrivate() || ip.IsUnspecified()
-}
-
-// 创建安全的 HTTP Client,防止 SSRF 和 DNS 重绑定
-func getSafeClient(timeout time.Duration) *req.Client {
- dialer := &net.Dialer{
+// ssrfSafeDialer returns a net.Dialer whose Control hook blocks private IPs.
+func ssrfSafeDialer(timeout time.Duration) *net.Dialer {
+ return &net.Dialer{
Timeout: timeout,
- // Control 函数在解析出 IP 后、建立连接前执行,是防御 DNS Rebinding 的关键
- Control: func(network, address string, c syscall.RawConn) error {
+ Control: func(network, address string, _ syscall.RawConn) error {
host, _, err := net.SplitHostPort(address)
if err != nil {
return err
}
- ip := net.ParseIP(host)
- if ip != nil && isPrivateIP(ip) {
+ if ip := net.ParseIP(host); ip != nil && isPrivateIP(ip) {
return fmt.Errorf("ip address [%s] is prohibited", host)
}
return nil
},
}
+}
+
+// 校验 IP 是否为私有内网地址
+func isPrivateIP(ip net.IP) bool {
+ return ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsPrivate() || ip.IsUnspecified()
+}
+
+// 创建安全的 HTTP Client,防止 SSRF 和 DNS 重绑定
+func getSafeClient(timeout time.Duration) *req.Client {
+ dialer := ssrfSafeDialer(timeout)
client := req.C()
client.SetTimeout(timeout)
@@ -359,3 +359,268 @@ func getSafeClient(timeout time.Duration) *req.Client {
client.SetRedirectPolicy(req.MaxRedirectPolicy(3))
return client
}
+
+// parseForwardProxyParams decodes the `u` and `h` query parameters.
+//
+// Query params:
+// - `u`: RawURLEncoding base64 of the target URL string.
+// - `h`: RawURLEncoding base64 of a JSON object map[string][]string.
+func parseForwardProxyParams(c *gin.Context) (parsedURL *url.URL, headers *http.Header, err error) {
+ uParam := c.Query("u")
+ if uParam == "" {
+ err = fmt.Errorf("missing query param [u]")
+ return
+ }
+ uBytes, decErr := base64.RawURLEncoding.DecodeString(uParam)
+ if decErr != nil {
+ err = fmt.Errorf("decode [u] failed: %s", decErr.Error())
+ return
+ }
+ parsedURL, err = url.ParseRequestURI(string(uBytes))
+ if err != nil {
+ err = fmt.Errorf("parse [u] failed: %s", err.Error())
+ return
+ }
+
+ h := http.Header{}
+ headers = &h
+ hParam := c.Query("h")
+ if hParam == "" {
+ return
+ }
+ hBytes, decErr := base64.RawURLEncoding.DecodeString(hParam)
+ if decErr != nil {
+ err = fmt.Errorf("decode [h] failed: %s", decErr.Error())
+ return
+ }
+ var record map[string][]string
+ if jsonErr := json.Unmarshal(hBytes, &record); jsonErr != nil {
+ err = fmt.Errorf("parse [h] failed: %s", jsonErr.Error())
+ return
+ }
+ for k, vs := range record {
+ for _, v := range vs {
+ h.Add(k, v)
+ }
+ }
+ return
+}
+
+// forwardResponseHeaders copies src headers into dst with a "Siyuan-Proxy-" prefix on each key.
+func forwardResponseHeaders(dst http.Header, src http.Header) {
+ for k, vs := range src {
+ for _, v := range vs {
+ dst.Add("Siyuan-Proxy-"+k, v)
+ }
+ }
+}
+
+// httpProxy proxies an HTTP request to a remote HTTP endpoint.
+//
+// Query params:
+// - u: RawURLEncoding base64 of the target http/https URL
+// - h: RawURLEncoding base64 of JSON map[string][]string forwarded as request headers
+//
+// The request method and body are taken from the incoming request.
+// Target response headers are forwarded with a "Siyuan-Proxy-" prefix.
+func httpProxy(c *gin.Context) {
+ targetURL, targetHeaders, err := parseForwardProxyParams(c)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"code": -1, "msg": err.Error()})
+ return
+ }
+
+ if targetURL.Scheme != "http" && targetURL.Scheme != "https" {
+ c.JSON(http.StatusBadRequest, gin.H{"code": -1, "msg": "only http/https is allowed"})
+ return
+ }
+
+ transport := &http.Transport{
+ DialContext: ssrfSafeDialer(30 * time.Second).DialContext,
+ }
+ httpClient := &http.Client{Transport: transport}
+
+ proxyReq, reqErr := http.NewRequestWithContext(c.Request.Context(), c.Request.Method, targetURL.String(), c.Request.Body)
+ if reqErr != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"code": -1, "msg": "create request failed: " + reqErr.Error()})
+ return
+ }
+
+ proxyReq.ContentLength = c.Request.ContentLength
+ proxyReq.Header.Set("Content-Type", c.ContentType())
+
+ for k, vs := range *targetHeaders {
+ for _, v := range vs {
+ proxyReq.Header.Add(k, v)
+ }
+ }
+
+ resp, respErr := httpClient.Do(proxyReq)
+ if respErr != nil {
+ c.JSON(http.StatusBadGateway, gin.H{"code": -1, "msg": "connect target failed: " + respErr.Error()})
+ return
+ }
+ defer resp.Body.Close()
+
+ forwardResponseHeaders(c.Writer.Header(), resp.Header)
+ c.Writer.WriteHeader(resp.StatusCode)
+ if _, err := io.Copy(c.Writer, resp.Body); err != nil {
+ logging.LogWarnf("http proxy copy response failed: %s", err.Error())
+ }
+}
+
+// wsProxy proxies a WebSocket connection to a remote WebSocket endpoint.
+//
+// Query params:
+// - u: RawURLEncoding base64 of the target ws/wss URL
+// - h: RawURLEncoding base64 of JSON map[string][]string forwarded as handshake headers
+//
+// Target response headers are forwarded with a "Siyuan-Proxy-" prefix.
+func wsProxy(c *gin.Context) {
+ targetURL, targetHeaders, err := parseForwardProxyParams(c)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"code": -1, "msg": err.Error()})
+ return
+ }
+
+ if targetURL.Scheme != "ws" && targetURL.Scheme != "wss" {
+ c.JSON(http.StatusBadRequest, gin.H{"code": -1, "msg": "only ws/wss is allowed"})
+ return
+ }
+
+ wsDialer := &websocket.Dialer{
+ NetDialContext: ssrfSafeDialer(30 * time.Second).DialContext,
+ HandshakeTimeout: 30 * time.Second,
+ }
+
+ targetConn, targetResp, dialErr := wsDialer.DialContext(c.Request.Context(), targetURL.String(), *targetHeaders)
+ if dialErr != nil {
+ c.JSON(http.StatusBadGateway, gin.H{"code": -1, "msg": "dial target failed: " + dialErr.Error()})
+ return
+ }
+ defer targetConn.Close()
+
+ upgradeHeaders := http.Header{}
+ if targetResp != nil {
+ forwardResponseHeaders(upgradeHeaders, targetResp.Header)
+ }
+ upgrader := websocket.Upgrader{
+ CheckOrigin: func(r *http.Request) bool { return true },
+ }
+ clientConn, upgradeErr := upgrader.Upgrade(c.Writer, c.Request, upgradeHeaders)
+ if upgradeErr != nil {
+ logging.LogErrorf("ws forward proxy upgrade failed: %s", upgradeErr.Error())
+ return
+ }
+ defer clientConn.Close()
+
+ errChan := make(chan error, 2)
+ go func() {
+ for {
+ msgType, msg, readErr := targetConn.ReadMessage()
+ if readErr != nil {
+ if closeError, ok := readErr.(*websocket.CloseError); ok {
+ clientConn.WriteMessage(
+ websocket.CloseMessage,
+ websocket.FormatCloseMessage(
+ closeError.Code,
+ closeError.Text,
+ ),
+ )
+ }
+ errChan <- readErr
+ return
+ }
+ if writeErr := clientConn.WriteMessage(msgType, msg); writeErr != nil {
+ errChan <- writeErr
+ return
+ }
+ }
+ }()
+ go func() {
+ for {
+ msgType, msg, readErr := clientConn.ReadMessage()
+ if readErr != nil {
+ if closeError, ok := readErr.(*websocket.CloseError); ok {
+ targetConn.WriteMessage(
+ websocket.CloseMessage,
+ websocket.FormatCloseMessage(
+ closeError.Code,
+ closeError.Text,
+ ),
+ )
+ }
+ errChan <- readErr
+ return
+ }
+ if writeErr := targetConn.WriteMessage(msgType, msg); writeErr != nil {
+ errChan <- writeErr
+ return
+ }
+ }
+ }()
+ <-errChan
+}
+
+// esProxy proxies an EventSource (SSE) stream from a remote HTTP endpoint.
+//
+// Query params:
+// - u: RawURLEncoding base64 of the target http/https URL
+// - h: RawURLEncoding base64 of JSON map[string][]string forwarded as request headers
+//
+// Target response headers are forwarded with a "Siyuan-Proxy-" prefix.
+func esProxy(c *gin.Context) {
+ targetURL, targetHeaders, err := parseForwardProxyParams(c)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"code": -1, "msg": err.Error()})
+ return
+ }
+
+ if targetURL.Scheme != "http" && targetURL.Scheme != "https" {
+ c.JSON(http.StatusBadRequest, gin.H{"code": -1, "msg": "only http/https is allowed"})
+ return
+ }
+
+ transport := &http.Transport{
+ DialContext: ssrfSafeDialer(30 * time.Second).DialContext,
+ }
+ httpClient := &http.Client{Transport: transport}
+
+ proxyReq, reqErr := http.NewRequestWithContext(c.Request.Context(), http.MethodGet, targetURL.String(), nil)
+ if reqErr != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"code": -1, "msg": "create request failed: " + reqErr.Error()})
+ return
+ }
+ for k, vs := range *targetHeaders {
+ for _, v := range vs {
+ proxyReq.Header.Add(k, v)
+ }
+ }
+ if proxyReq.Header.Get("Accept") == "" {
+ proxyReq.Header.Set("Accept", "text/event-stream")
+ }
+
+ resp, respErr := httpClient.Do(proxyReq)
+ if respErr != nil {
+ c.JSON(http.StatusBadGateway, gin.H{"code": -1, "msg": "connect target failed: " + respErr.Error()})
+ return
+ }
+ defer resp.Body.Close()
+
+ forwardResponseHeaders(c.Writer.Header(), resp.Header)
+ c.Writer.WriteHeader(resp.StatusCode)
+
+ buf := make([]byte, 4096)
+ for {
+ n, readErr := resp.Body.Read(buf)
+ if n > 0 {
+ if _, writeErr := c.Writer.Write(buf[:n]); writeErr != nil {
+ return
+ }
+ c.Writer.Flush()
+ }
+ if readErr != nil {
+ return
+ }
+ }
+}
diff --git a/kernel/api/plugin.go b/kernel/api/plugin.go
new file mode 100644
index 0000000000..6c7385fc77
--- /dev/null
+++ b/kernel/api/plugin.go
@@ -0,0 +1,80 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package api
+
+import (
+ "fmt"
+ "net/http"
+
+ "github.com/88250/gulu"
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/plugin"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func listLoadedPlugins(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ ret.Data = plugin.GetManager().GetLoadedPluginsInfo()
+}
+
+func getPluginName(c *gin.Context, ret *gulu.Result) (name string) {
+ name = util.GetRequestStringParam(c, "name", ret)
+ if name == "" {
+ if ret.Code == 0 {
+ ret.Code = -10
+ ret.Msg = "Plugin name is required"
+ }
+ }
+ return
+}
+
+func getLoadedPlugin(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ pluginName := getPluginName(c, ret)
+ if pluginName == "" {
+ return
+ }
+
+ pluginInfo, found := plugin.GetManager().GetLoadedPlugin(pluginName)
+ if !found {
+ ret.Code = -11
+ ret.Msg = fmt.Sprintf("Plugin [%s] not loaded", pluginName)
+ return
+ }
+
+ ret.Data = pluginInfo
+}
+
+func pluginJsonRpcHttp(c *gin.Context) {
+ plugin.HandleRpcHttp(c)
+}
+
+func pluginJsonRpcWebSocket(c *gin.Context) {
+ plugin.HandleRpcWebSocket(c)
+}
+
+// func pluginPublicWebServer(c *gin.Context) {
+// plugin.HandleHttpRequest(c, plugin.AccessScopePublic)
+// }
+
+func pluginPrivateWebServer(c *gin.Context) {
+ plugin.HandleHttpRequest(c, plugin.AccessScopePrivate)
+}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index dc8e6f5683..6ff38bb233 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -521,9 +521,29 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/petal/loadPetals", model.CheckAuth, loadPetals)
ginServer.Handle("POST", "/api/petal/setPetalEnabled", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setPetalEnabled)
+ ginServer.Handle("GET", "/api/plugin", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, listLoadedPlugins)
+ ginServer.Handle("GET", "/api/plugin/rpc", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, getLoadedPlugin)
+ ginServer.Handle("GET", "/api/plugin/rpc/:name", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, getLoadedPlugin)
+
+ ginServer.Handle("GET", "/ws/plugin/rpc", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, pluginJsonRpcWebSocket)
+ ginServer.Handle("GET", "/ws/plugin/rpc/:name", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, pluginJsonRpcWebSocket)
+
+ // ginServer.Any("/plugin/public/:name/*path", pluginPublicWebServer)
+ ginServer.Any("/plugin/private/:name/*path", model.CheckAuth, model.CheckAdminRole, pluginPrivateWebServer)
+
+ ginServer.Handle("POST", "/api/plugin/getLoadedPlugin", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, getLoadedPlugin)
+ ginServer.Handle("POST", "/api/plugin/listLoadedPlugins", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, listLoadedPlugins)
+ ginServer.Handle("POST", "/api/plugin/rpc", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, pluginJsonRpcHttp)
+ ginServer.Handle("POST", "/api/plugin/rpc/:name", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, pluginJsonRpcHttp)
+
ginServer.Any("/api/network/echo", model.CheckAuth, model.CheckAdminRole, echo)
+ ginServer.Any("/api/network/echo/*path", model.CheckAuth, model.CheckAdminRole, echo)
ginServer.Handle("POST", "/api/network/forwardProxy", model.CheckAuth, model.CheckAdminRole, forwardProxy)
+ ginServer.Any("/api/network/proxy", model.CheckAuth, model.CheckAdminRole, httpProxy)
+ ginServer.Handle("GET", "/ws/network/proxy", model.CheckAuth, model.CheckAdminRole, wsProxy)
+ ginServer.Handle("GET", "/es/network/proxy", model.CheckAuth, model.CheckAdminRole, esProxy)
+
ginServer.Handle("GET", "/ws/broadcast", model.CheckAuth, model.CheckAdminRole, broadcast)
ginServer.Handle("GET", "/es/broadcast/subscribe", model.CheckAuth, model.CheckAdminRole, broadcastSubscribe)
diff --git a/kernel/bazaar/package.go b/kernel/bazaar/package.go
index 85a9958ff1..b3814ceca6 100644
--- a/kernel/bazaar/package.go
+++ b/kernel/bazaar/package.go
@@ -47,6 +47,7 @@ type Package struct {
Version string `json:"version"`
MinAppVersion string `json:"minAppVersion"`
DisabledInPublish bool `json:"disabledInPublish"`
+ Kernels []string `json:"kernels"`
Backends []string `json:"backends"`
Frontends []string `json:"frontends"`
DisplayName LocaleStrings `json:"displayName"`
diff --git a/kernel/bazaar/plugin.go b/kernel/bazaar/plugin.go
index f425cc04c4..ef991dd52e 100644
--- a/kernel/bazaar/plugin.go
+++ b/kernel/bazaar/plugin.go
@@ -25,7 +25,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
-func ParseInstalledPlugin(name, frontend string) (found bool, displayName string, incompatible, disabledInPublish, disallowInstall bool) {
+func ParseInstalledPlugin(name, frontend string) (found bool, version, displayName string, incompatible, disabledInPublish, disallowInstall, kernelIncompatible bool) {
pluginsPath := filepath.Join(util.DataDir, "plugins")
if !util.IsPathRegularDirOrSymlinkDir(pluginsPath) {
return
@@ -52,10 +52,12 @@ func ParseInstalledPlugin(name, frontend string) (found bool, displayName string
}
found = true
+ version = plugin.Version
displayName = GetPreferredLocaleString(plugin.DisplayName, plugin.Name)
incompatible = IsIncompatiblePlugin(plugin, frontend)
disabledInPublish = plugin.DisabledInPublish
disallowInstall = isBelowRequiredAppVersion(plugin)
+ kernelIncompatible = IsIncompatibleKernelPlugin(plugin)
}
return
}
@@ -67,21 +69,31 @@ func IsIncompatiblePlugin(plugin *Package, frontend string) bool {
return false
}
- backend := getCurrentBackend()
- if !isTargetSupported(plugin.Backends, backend) {
+ backend := GetCurrentBackend()
+ if !IsTargetSupported(plugin.Backends, backend) {
return true
}
- if !isTargetSupported(plugin.Frontends, frontend) {
+ if !IsTargetSupported(plugin.Frontends, frontend) {
return true
}
return false
}
+// IsIncompatibleKernelPlugin 判断内核插件是否与当前环境不兼容
+func IsIncompatibleKernelPlugin(plugin *Package) bool {
+ // plugin.json 中 kernel 字段不存在时视为不兼容(允许安装插件但不启动其中的内核插件)
+ if len(plugin.Kernels) == 0 {
+ return true
+ }
+
+ return !IsTargetSupported(plugin.Kernels, GetCurrentBackend())
+}
+
var cachedBackend string
-func getCurrentBackend() string {
+func GetCurrentBackend() string {
if cachedBackend == "" {
if util.Container == util.ContainerStd {
cachedBackend = runtime.GOOS
@@ -92,8 +104,8 @@ func getCurrentBackend() string {
return cachedBackend
}
-// isTargetSupported 检查 platforms 中是否包含 target 或 "all"
-func isTargetSupported(platforms []string, target string) bool {
+// IsTargetSupported 检查 platforms 中是否包含 target 或 "all"
+func IsTargetSupported(platforms []string, target string) bool {
// 缺失字段时跳过检查,相当于 all
if len(platforms) == 0 {
return true
diff --git a/kernel/go.mod b/kernel/go.mod
index dc2ab677b0..ffc8609a08 100644
--- a/kernel/go.mod
+++ b/kernel/go.mod
@@ -22,6 +22,7 @@ require (
github.com/dgraph-io/ristretto v0.2.0
github.com/disintegration/imaging v1.6.2
github.com/djherbis/times v1.6.0
+ github.com/dop251/goja_nodejs v0.0.0-20260212111938-1f56ff5bcf14
github.com/edsrzf/mmap-go v1.2.0
github.com/emersion/go-ical v0.0.0-20250609112844-439c63cef608
github.com/emersion/go-vcard v0.0.0-20241024213814-c9703dde27ff
@@ -48,6 +49,7 @@ require (
github.com/json-iterator/go v1.1.12
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
github.com/klippa-app/go-pdfium v1.17.2
+ github.com/lxzan/gws v1.9.1
github.com/mattn/go-sqlite3 v2.0.3+incompatible
github.com/microcosm-cc/bluemonday v1.0.27
github.com/mitchellh/go-ps v1.0.0
@@ -57,9 +59,11 @@ require (
github.com/panjf2000/ants/v2 v2.12.0
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pdfcpu/pdfcpu v0.11.0
+ github.com/r3labs/sse/v2 v2.10.0
github.com/radovskyb/watcher v1.0.7
github.com/rqlite/sql v0.0.0-20251204023435-65660522892e
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06
+ github.com/samber/lo v1.53.0
github.com/sashabaranov/go-openai v1.41.2
github.com/shirou/gopsutil/v4 v4.26.3
github.com/siyuan-note/dataparser v0.0.0-20260115084335-b57cb8bc7c17
@@ -70,6 +74,7 @@ require (
github.com/siyuan-note/httpclient v0.0.0-20260408083825-43e4476ad2b3
github.com/siyuan-note/logging v0.0.0-20260117134552-88b424dfe7f1
github.com/siyuan-note/riff v0.0.0-20251022131846-228528e70754
+ github.com/smallnest/chanx v1.2.0
github.com/soheilhy/cmux v0.1.5
github.com/spf13/cast v1.10.0
github.com/steambap/captcha v1.4.1
@@ -88,6 +93,8 @@ require (
gopkg.in/yaml.v3 v3.0.1
)
+require gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
+
require (
dario.cat/mergo v1.0.2 // indirect
dmitri.shuralyov.com/font/woff2 v0.0.0-20180220214647-957792cbbdab // indirect
@@ -127,6 +134,8 @@ require (
github.com/clipperhouse/uax29/v2 v2.2.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/dlclark/regexp2 v1.11.5 // indirect
+ github.com/dop251/base64dec v0.0.0-20231022112746-c6c9f9a96217 // indirect
+ github.com/dop251/goja v0.0.0-20260311135729-065cd970411c
github.com/dsnet/compress v0.0.1 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/ebitengine/purego v0.10.0 // indirect
@@ -137,6 +146,7 @@ require (
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.28.0 // indirect
github.com/go-resty/resty/v2 v2.16.5 // indirect
+ github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect
github.com/go-sw/text-codec v0.0.1 // indirect
github.com/goccy/go-json v0.10.6 // indirect
github.com/goccy/go-yaml v1.18.0 // indirect
diff --git a/kernel/go.sum b/kernel/go.sum
index 00d02aa9c0..cb69be5afd 100644
--- a/kernel/go.sum
+++ b/kernel/go.sum
@@ -125,6 +125,12 @@ github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYC
github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc=
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
+github.com/dop251/base64dec v0.0.0-20231022112746-c6c9f9a96217 h1:16iT9CBDOniJwFGPI41MbUDfEk74hFaKTqudrX8kenY=
+github.com/dop251/base64dec v0.0.0-20231022112746-c6c9f9a96217/go.mod h1:eIb+f24U+eWQCIsj9D/ah+MD9UP+wdxuqzsdLD+mhGM=
+github.com/dop251/goja v0.0.0-20260311135729-065cd970411c h1:OcLmPfx1T1RmZVHHFwWMPaZDdRf0DBMZOFMVWJa7Pdk=
+github.com/dop251/goja v0.0.0-20260311135729-065cd970411c/go.mod h1:MxLav0peU43GgvwVgNbLAj1s/bSGboKkhuULvq/7hx4=
+github.com/dop251/goja_nodejs v0.0.0-20260212111938-1f56ff5bcf14 h1:3U8dTgyNBhEQ/GVw0jZW5q+93Zw2gAZPRWhJ9TwV3rM=
+github.com/dop251/goja_nodejs v0.0.0-20260212111938-1f56ff5bcf14/go.mod h1:Tb7Xxye4LX7cT3i8YLvmPMGCV92IOi4CDZvm/V8ylc0=
github.com/dsnet/compress v0.0.1 h1:PlZu0n3Tuv04TzpfPbrnI0HW/YwodEXDS+oPKahKF0Q=
github.com/dsnet/compress v0.0.1/go.mod h1:Aw8dCMJ7RioblQeTqt88akK31OvO8Dhf5JflhBbQEHo=
github.com/dsnet/golib v0.0.0-20171103203638-1ea166775780/go.mod h1:Lj+Z9rebOhdfkVLjJ8T6VcRQv3SXugXy999NBtR9aFY=
@@ -186,6 +192,8 @@ github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3
github.com/go-resty/resty/v2 v2.0.0/go.mod h1:dZGr0i9PLlaaTD4H/hoZIDjQ+r6xq8mgbRzHZf7f2J8=
github.com/go-resty/resty/v2 v2.16.5 h1:hBKqmWrr7uRc3euHVqmh1HTHcKn99Smr7o5spptdhTM=
github.com/go-resty/resty/v2 v2.16.5/go.mod h1:hkJtXbA2iKHzJheXYvQ8snQES5ZLGKMwQ07xAwp/fiA=
+github.com/go-sourcemap/sourcemap v2.1.4+incompatible h1:a+iTbH5auLKxaNwQFg0B+TCYl6lbukKPc7b5x0n1s6Q=
+github.com/go-sourcemap/sourcemap v2.1.4+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg=
github.com/go-sw/text-codec v0.0.1 h1:H+wnKj5TuvqYlfhMtbc52m1Oe0YnxD7QPzZPBE8QAn8=
github.com/go-sw/text-codec v0.0.1/go.mod h1:RTuIwijiCSy7wYLZd3h4RmWHBCD1bERsEST7vqnOzmo=
github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
@@ -282,6 +290,8 @@ github.com/levigross/exp-html v0.0.0-20120902181939-8df60c69a8f5 h1:W7p+m/AECTL3
github.com/levigross/exp-html v0.0.0-20120902181939-8df60c69a8f5/go.mod h1:QMe2wuKJ0o7zIVE8AqiT8rd8epmm6WDIZ2wyuBqYPzM=
github.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 h1:PwQumkgq4/acIiZhtifTV5OUqqiP82UAl0h87xj/l9k=
github.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
+github.com/lxzan/gws v1.9.1 h1:4lbIp4cW0hOLP3ejFHR/uWRy741AURx7oKkNNi2OT9o=
+github.com/lxzan/gws v1.9.1/go.mod h1:gXHSCPmTGryWJ4icuqy8Yho32E4YIMHH0fkDRYJRbdc=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
@@ -338,6 +348,8 @@ github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.58.0 h1:ggY2pvZaVdB9EyojxL1p+5mptkuHyX5MOSv4dgWF4Ug=
github.com/quic-go/quic-go v0.58.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
+github.com/r3labs/sse/v2 v2.10.0 h1:hFEkLLFY4LDifoHdiCN/LlGBAdVJYsANaLqNYa1l/v0=
+github.com/r3labs/sse/v2 v2.10.0/go.mod h1:Igau6Whc+F17QUgML1fYe1VPZzTV6EMCnYktEmkNJ7I=
github.com/radovskyb/watcher v1.0.7 h1:AYePLih6dpmS32vlHfhCeli8127LzkIgwJGcwwe8tUE=
github.com/radovskyb/watcher v1.0.7/go.mod h1:78okwvY5wPdzcb1UYnip1pvrZNIVEIh/Cm+ZuvsUYIg=
github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEvV+S9iJ2IdQo=
@@ -355,6 +367,8 @@ github.com/rqlite/sql v0.0.0-20251204023435-65660522892e h1:ccOm5zC6YqJtBrMmtiNc
github.com/rqlite/sql v0.0.0-20251204023435-65660522892e/go.mod h1:ib9zVtNgRKiGuoMyUqqL5aNpk+r+++YlyiVIkclVqPg=
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 h1:OkMGxebDjyw0ULyrTYWeN0UNCCkmCWfjPnIA2W6oviI=
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06/go.mod h1:+ePHsJ1keEjQtpvf9HHw0f4ZeJ0TLRsxhunSI2hYJSs=
+github.com/samber/lo v1.53.0 h1:t975lj2py4kJPQ6haz1QMgtId2gtmfktACxIXArw3HM=
+github.com/samber/lo v1.53.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
github.com/sashabaranov/go-openai v1.41.2 h1:vfPRBZNMpnqu8ELsclWcAvF19lDNgh1t6TVfFFOPiSM=
github.com/sashabaranov/go-openai v1.41.2/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
github.com/scylladb/termtables v0.0.0-20191203121021-c4c0b6d42ff4/go.mod h1:C1a7PQSMz9NShzorzCiG2fk9+xuCgLkPeCvMHYR2OWg=
@@ -381,6 +395,8 @@ github.com/siyuan-note/logging v0.0.0-20260117134552-88b424dfe7f1 h1:C2Y1XhBrrGe
github.com/siyuan-note/logging v0.0.0-20260117134552-88b424dfe7f1/go.mod h1:t3Tmt3DgQx0zqJmrckszJ+JBZ7iJrD1Ktp8FDBQ249E=
github.com/siyuan-note/riff v0.0.0-20251022131846-228528e70754 h1:6QYpy7s5HlRSge09TyM/mT0vz1RDcWYZdkxEh7hmbH4=
github.com/siyuan-note/riff v0.0.0-20251022131846-228528e70754/go.mod h1:/N7+N2CsZ0nleNPpP3b+06Bzqvuhy6GUmLY7Kug/zT0=
+github.com/smallnest/chanx v1.2.0 h1:RLyldZBbQZ4O0dSvdkTMHo4+mDw20Bc1jXXTHf+ymZo=
+github.com/smallnest/chanx v1.2.0/go.mod h1:+4nWMF0+CqEcU74SnX2NxaGqZ8zX4pcQ8Jcs77DbX5A=
github.com/soheilhy/cmux v0.1.5 h1:jjzc5WVemNEDTLwv9tlmemhC73tI08BNOIGwBOo10Js=
github.com/soheilhy/cmux v0.1.5/go.mod h1:T7TcVDs9LWfQgPlPsdngu6I6QIoyIFZDDC6sNE1GqG0=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
@@ -442,6 +458,8 @@ github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs=
go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8=
+go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
+go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
@@ -475,6 +493,7 @@ golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73r
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20191116160921-f9c825593386/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
@@ -554,6 +573,8 @@ golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
+gopkg.in/cenkalti/backoff.v1 v1.1.0 h1:Arh75ttbsvlpVA7WtVpH4u9h6Zl46xuptxqLxPiSo4Y=
+gopkg.in/cenkalti/backoff.v1 v1.1.0/go.mod h1:J6Vskwqd+OMVJl8C33mmtxTBs2gyzfv7UDAkHu8BrjI=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
diff --git a/kernel/main.go b/kernel/main.go
index 466b9ddb26..98c96d95db 100644
--- a/kernel/main.go
+++ b/kernel/main.go
@@ -22,6 +22,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/job"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/plugin"
"github.com/siyuan-note/siyuan/kernel/server"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/util"
@@ -30,6 +31,7 @@ import (
func main() {
util.Boot()
+ model.InitJwtKey()
model.InitConf()
go server.Serve(false, model.Conf.CookieKey)
model.InitAppearance()
@@ -52,6 +54,7 @@ func main() {
go model.AutoGenerateFileHistory()
go cache.LoadAssets()
go util.CheckFileSysStatus()
+ go plugin.InitManager()
model.WatchAssets()
model.WatchEmojis()
diff --git a/kernel/model/auth.go b/kernel/model/auth.go
index 470880fa14..66f2b0e18f 100644
--- a/kernel/model/auth.go
+++ b/kernel/model/auth.go
@@ -42,9 +42,7 @@ const (
ClaimsContextKey = "claims"
- iss = "siyuan-publish-reverse-proxy-server"
- sub = "publish"
- aud = "siyuan-kernel"
+ iss = "siyuan-kernel" // token 的发行者
ClaimsKeyRole string = "role"
)
@@ -57,6 +55,14 @@ var (
jwtKey = make([]byte, 32)
)
+func InitJwtKey() error {
+ if _, err := rand.Read(jwtKey); err != nil {
+ logging.LogErrorf("generate JWT signing key failed: %s", err)
+ return err
+ }
+ return nil
+}
+
func GetBasicAuthAccount(username string) *Account {
return accountsMap[username]
}
@@ -82,7 +88,7 @@ func DeleteSession(sessionID string) {
delete(sessionsMap, sessionID)
}
-func InitAccounts() {
+func InitPublishAccounts() {
accountsMap = AccountsMap{
"": &Account{}, // 匿名用户
}
@@ -93,10 +99,10 @@ func InitAccounts() {
}
}
- InitJWT()
+ InitPublishJWT()
}
-func InitJWT() {
+func InitPublishJWT() {
if _, err := rand.Read(jwtKey); err != nil {
logging.LogErrorf("generate JWT signing key failed: %s", err)
return
@@ -107,12 +113,12 @@ func InitJWT() {
t := jwt.NewWithClaims(
jwt.SigningMethodHS256,
jwt.MapClaims{
- "iss": iss,
- "sub": sub,
- "aud": aud,
- "jti": username,
+ "iss": iss, // token 的发行者
+ "sub": username, // token 代表的主体
+ "aud": "siyuan-publish-server", // token 的受众
+ "jti": uuid.New().String(), // token 的唯一标识
- ClaimsKeyRole: RoleReader,
+ ClaimsKeyRole: RoleReader, // 角色
},
)
if token, err := t.SignedString(jwtKey); err != nil {
@@ -124,6 +130,27 @@ func InitJWT() {
}
}
+// CreatePluginJWT 为指定名称的内核插件创建一个 JWT,包含管理员权限。插件使用这个 JWT 调用内核 API。
+func CreatePluginJWT(name string) (string, error) {
+ t := jwt.NewWithClaims(
+ jwt.SigningMethodHS256,
+ jwt.MapClaims{
+ "iss": iss,
+ "sub": name,
+ "aud": "siyuan-kernel-plugin",
+ "jti": uuid.New().String(),
+
+ ClaimsKeyRole: RoleAdministrator,
+ },
+ )
+ if token, err := t.SignedString(jwtKey); err != nil {
+ logging.LogErrorf("JWT signature failed: %s", err)
+ return "", err
+ } else {
+ return token, nil
+ }
+}
+
func ParseJWT(tokenString string) (*jwt.Token, error) {
// REF: https://golang-jwt.github.io/jwt/usage/parse/
return jwt.Parse(
@@ -132,8 +159,6 @@ func ParseJWT(tokenString string) (*jwt.Token, error) {
return jwtKey, nil
},
jwt.WithIssuer(iss),
- jwt.WithSubject(sub),
- jwt.WithAudience(aud),
)
}
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index c2622e003e..d9f7d88b3e 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -740,10 +740,16 @@ func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int) {
defer exitLock.Unlock()
logging.LogInfof("exiting kernel [force=%v, setCurrentWorkspace=%v, execInstallPkg=%d]", force, setCurrentWorkspace, execInstallPkg)
+
util.PushMsg(Conf.Language(95), 10000*60)
FlushTxQueue()
if !force {
+ // Stop kernel plugins early in shutdown
+ if OnKernelPluginShutdown != nil {
+ OnKernelPluginShutdown()
+ }
+
if Conf.Sync.Enabled && 3 != Conf.Sync.Mode &&
((IsSubscriber() && conf.ProviderSiYuan == Conf.Sync.Provider) || conf.ProviderSiYuan != Conf.Sync.Provider) {
syncData(true, false)
diff --git a/kernel/model/plugin.go b/kernel/model/plugin.go
index 56660015a5..c1160a98f1 100644
--- a/kernel/model/plugin.go
+++ b/kernel/model/plugin.go
@@ -36,20 +36,34 @@ import (
type Petal struct {
Name string `json:"name"` // Plugin name
DisplayName string `json:"displayName"` // Plugin display name
+ Version string `json:"version"` // Plugin version
Enabled bool `json:"enabled"` // Whether enabled
Incompatible bool `json:"incompatible"` // Whether incompatible
DisabledInPublish bool `json:"disabledInPublish"` // Whether disabled in publish mode
DisallowInstall bool `json:"disallowInstall"` // Whether disallow install
- JS string `json:"js"` // JS code
- CSS string `json:"css"` // CSS code
- I18n map[string]any `json:"i18n"` // i18n text
+ JS string `json:"js"` // JS code
+ CSS string `json:"css"` // CSS code
+ I18n map[string]any `json:"i18n"` // i18n text
+ Kernel KernelPetal `json:"kernel"` // Kernel plugin info
}
+type KernelPetal struct {
+ JS string `json:"js"` // Kernel JS code
+ Existed bool `json:"existed"` // Whether kernel.js is exist
+ Incompatible bool `json:"incompatible"` // Whether incompatible
+}
+
+var (
+ OnKernelPluginStart func(petal *Petal) // Called when a plugin is enabled (after loading and starting the plugin)
+ OnKernelPluginStop func(petal *Petal) // Called when a plugin is disabled (before stopping and unloading the plugin)
+ OnKernelPluginShutdown func() // Called when SiYuan is shutting down, before stopping all plugins
+)
+
func SetPetalEnabled(name string, enabled bool) (ret *Petal, err error) {
petals := getPetals()
- found, displayName, incompatible, disabledInPublish, disallowInstall := bazaar.ParseInstalledPlugin(name, "")
+ found, version, displayName, incompatible, disabledInPublish, disallowInstall, kernelIncompatible := bazaar.ParseInstalledPlugin(name, "")
if !found {
logging.LogErrorf("plugin [%s] not found", name)
return
@@ -62,11 +76,15 @@ func SetPetalEnabled(name string, enabled bool) (ret *Petal, err error) {
}
petals = append(petals, ret)
}
+ ret.Version = version
ret.DisplayName = displayName
ret.Enabled = enabled
ret.Incompatible = incompatible
ret.DisabledInPublish = disabledInPublish
ret.DisallowInstall = disallowInstall
+ ret.Kernel = KernelPetal{
+ Incompatible: kernelIncompatible,
+ }
if enabled && disallowInstall {
err = fmt.Errorf("require upgrade SiYuan to use this plugin [%s]", name)
@@ -75,7 +93,19 @@ func SetPetalEnabled(name string, enabled bool) (ret *Petal, err error) {
}
savePetals(petals)
+
loadCode(ret)
+
+ // Hook kernel plugin lifecycle (callbacks avoid circular import with plugin package)
+ if enabled {
+ if OnKernelPluginStart != nil {
+ OnKernelPluginStart(ret)
+ }
+ } else {
+ if OnKernelPluginStop != nil {
+ OnKernelPluginStop(ret)
+ }
+ }
return
}
@@ -91,11 +121,36 @@ func getPetalByName(name string, petals []*Petal) (ret *Petal) {
var loadPetalsFlight singleflight.Group
+// IsPetalsEnabled returns whether petals are enabled and trusted to be loaded
+func IsPetalsEnabled() bool {
+ if Conf.Bazaar.PetalDisabled {
+ return false
+ }
+
+ if !Conf.Bazaar.Trust {
+ // 移动端没有集市模块,所以要默认开启,桌面端和 Docker 容器需要用户手动确认过信任后才能开启
+ if util.Container == util.ContainerStd || util.Container == util.ContainerDocker {
+ return false
+ }
+ }
+ return true
+}
+
func LoadPetals(frontend string, isPublish bool) (ret []*Petal) {
// 调用 setPetalEnabled 接口之后推送消息到所有前端实例,接着会同时调用 loadPetals 接口,合并相同类型的请求为一次执行
key := "loadPetals:" + frontend + ":" + strconv.FormatBool(isPublish)
v, err, _ := loadPetalsFlight.Do(key, func() (any, error) {
- return loadPetals(frontend, isPublish), nil
+ return loadPetals(frontend, isPublish, false), nil
+ })
+ if err != nil {
+ return []*Petal{}
+ }
+ return v.([]*Petal)
+}
+
+func LoadKernelPetals() (ret []*Petal) {
+ v, err, _ := loadPetalsFlight.Do("loadKernelPetals", func() (any, error) {
+ return loadPetals("", false, true), nil
})
if err != nil {
return []*Petal{}
@@ -103,38 +158,61 @@ func LoadPetals(frontend string, isPublish bool) (ret []*Petal) {
return v.([]*Petal)
}
-func loadPetals(frontend string, isPublish bool) (ret []*Petal) {
+func loadPetals(frontend string, isPublish, isKernel bool) (ret []*Petal) {
ret = []*Petal{}
- if Conf.Bazaar.PetalDisabled {
+ if !IsPetalsEnabled() {
return
}
- if !Conf.Bazaar.Trust {
- // 移动端没有集市模块,所以要默认开启,桌面端和 Docker 容器需要用户手动确认过信任后才能开启
- if util.ContainerStd == util.Container || util.ContainerDocker == util.Container {
- return
- }
- }
-
var petalNames []string
petals := getPetals()
for _, petal := range petals {
- _, petal.DisplayName, petal.Incompatible, petal.DisabledInPublish, petal.DisallowInstall = bazaar.ParseInstalledPlugin(petal.Name, frontend)
- if !petal.Enabled || petal.Incompatible || (isPublish && petal.DisabledInPublish) || petal.DisallowInstall {
- if petal.DisallowInstall {
- SetPetalEnabled(petal.Name, false)
- logging.LogInfof("plugin [%s] disallowed install, auto disabled", petal.Name)
+ _, petal.Version, petal.DisplayName, petal.Incompatible, petal.DisabledInPublish, petal.DisallowInstall, petal.Kernel.Incompatible = bazaar.ParseInstalledPlugin(petal.Name, frontend)
+ if !petal.Enabled {
+ // disabled plugin
+ continue
+ }
+
+ if isKernel {
+ // kernel plugin
+ if petal.Kernel.Incompatible {
+ // incompatible kernel plugin
+ continue
+ }
+ } else {
+ // client plugin
+ if petal.Incompatible {
+ // incompatible client plugin
+ continue
}
+
+ if isPublish && petal.DisabledInPublish {
+ // disabled plugin in publish mode
+ continue
+ }
+ }
+
+ if petal.DisallowInstall {
+ // disallow install plugin (require upgrade SiYuan), auto disable it to avoid potential issues, and skip loading
+ SetPetalEnabled(petal.Name, false)
+ logging.LogInfof("plugin [%s] disallowed install, auto disabled", petal.Name)
continue
}
loadCode(petal)
+ if isKernel {
+ if !petal.Kernel.Existed {
+ logging.LogWarnf("plugin [%s] kernel.js not found, skip loading as kernel plugin", petal.Name)
+ continue
+ }
+ }
+
ret = append(ret, petal)
petalNames = append(petalNames, petal.Name)
}
- logging.LogDebugf("loaded petals [frontend=%s, isPublish=%v, petals=[%s]]", frontend, isPublish, strings.Join(petalNames, ","))
+ logging.LogInfof("loaded petals [frontend=%s, isPublish=%v, isKernel=%v, petals=[%s]]", frontend, isPublish, isKernel, strings.Join(petalNames, ","))
return
}
@@ -142,22 +220,33 @@ func loadCode(petal *Petal) {
pluginDir := filepath.Join(util.DataDir, "plugins", petal.Name)
jsPath := filepath.Join(pluginDir, "index.js")
if !filelock.IsExist(jsPath) {
- logging.LogErrorf("plugin [%s] js not found", petal.Name)
+ logging.LogErrorf("plugin [%s] index.js not found", petal.Name)
return
}
data, err := filelock.ReadFile(jsPath)
if err != nil {
- logging.LogErrorf("read plugin [%s] js failed: %s", petal.Name, err)
+ logging.LogErrorf("read plugin [%s] index.js failed: %s", petal.Name, err)
return
}
petal.JS = string(data)
+ kernelJsPath := filepath.Join(pluginDir, "kernel.js")
+ if filelock.IsExist(kernelJsPath) {
+ data, err = filelock.ReadFile(kernelJsPath)
+ if err != nil {
+ logging.LogErrorf("read plugin [%s] kernel.js failed: %s", petal.Name, err)
+ } else {
+ petal.Kernel.JS = string(data)
+ petal.Kernel.Existed = true
+ }
+ }
+
cssPath := filepath.Join(pluginDir, "index.css")
if filelock.IsExist(cssPath) {
data, err = filelock.ReadFile(cssPath)
if err != nil {
- logging.LogErrorf("read plugin [%s] css failed: %s", petal.Name, err)
+ logging.LogErrorf("read plugin [%s] index.css failed: %s", petal.Name, err)
} else {
petal.CSS = string(data)
}
diff --git a/kernel/plugin/api_client.go b/kernel/plugin/api_client.go
new file mode 100644
index 0000000000..d1377993e9
--- /dev/null
+++ b/kernel/plugin/api_client.go
@@ -0,0 +1,716 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "sync"
+ "sync/atomic"
+
+ "github.com/dop251/goja"
+ "github.com/lxzan/gws"
+ sse "github.com/r3labs/sse/v2"
+ "github.com/samber/lo"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// injectClient adds siyuan.server to the goja context.
+func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("injectClient: %v", r)
+ }
+ }()
+
+ client := rt.NewObject()
+
+ lo.Must0(client.Set("fetch", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (_ any, err error) {
+ var path string
+ if goja.IsString(call.Argument(0)) {
+ path = call.Argument(0).String()
+ } else {
+ err = fmt.Errorf("path required")
+ return
+ }
+
+ if !strings.HasPrefix(path, "/") {
+ err = fmt.Errorf("path must start with /")
+ return
+ }
+
+ method := "GET"
+ headers := map[string]string{}
+ var bodyString string
+ var bodyBytes []byte
+
+ if init := call.Argument(1); isJsValueNotNull(init) {
+ if initObj := init.ToObject(rt); initObj != nil {
+ if m := initObj.Get("method"); goja.IsString(m) {
+ method = m.String()
+ }
+
+ if h := initObj.Get("headers"); isJsValueNotNull(h) {
+ if exportErr := rt.ExportTo(h, &headers); exportErr != nil {
+ err = fmt.Errorf("failed to export headers: %w", exportErr)
+ return
+ }
+ }
+
+ if b := initObj.Get("body"); isJsValueNotNull(b) {
+
+ if goja.IsString(b) {
+ bodyString = b.String()
+ } else {
+ body := b.Export()
+ if arrayBuffer, ok := body.(goja.ArrayBuffer); ok {
+ src := arrayBuffer.Bytes()
+ bodyBytes = make([]byte, len(src))
+ copy(bodyBytes, src)
+ }
+ }
+ }
+ }
+ }
+
+ go func() {
+ var err error
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("panic during siyuan.client.fetch: %v", r)
+ }
+
+ if err != nil {
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.fetch reject: %v", p.Name, rejectErr)
+ }
+ return
+ }, nil)
+ }
+ }()
+
+ targetURL := fmt.Sprintf("http://127.0.0.1:%s%s", util.ServerPort, path)
+ r := httpClient.R()
+ for k, v := range headers {
+ r.SetHeader(k, v)
+ }
+ r.SetHeader(model.XAuthTokenKey, p.token)
+
+ if bodyString != "" {
+ r.SetBody(bodyString)
+ } else if len(bodyBytes) > 0 {
+ r.SetBody(bodyBytes)
+ }
+
+ resp, sendErr := r.Send(method, targetURL)
+ if sendErr != nil {
+ err = sendErr
+ return
+ }
+
+ defer resp.Body.Close()
+ body, readErr := io.ReadAll(resp.Body)
+ if readErr != nil {
+ err = fmt.Errorf("failed to read response body: %w", readErr)
+ return
+ }
+
+ responseHeader := map[string]string{}
+ for k, vs := range resp.Header {
+ responseHeader[k] = strings.Join(vs, ", ")
+ }
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ response := rt.NewObject()
+ lo.Must0(response.Set("url", rt.ToValue(path)))
+ lo.Must0(response.Set("ok", rt.ToValue(resp.StatusCode >= 200 && resp.StatusCode < 300)))
+ lo.Must0(response.Set("status", rt.ToValue(resp.StatusCode)))
+ lo.Must0(response.Set("statusText", rt.ToValue(resp.Status)))
+ lo.Must0(response.Set("headers", rt.ToValue(responseHeader)))
+ lo.Must0(ObjectSetDataMethods(p, rt, response, body))
+ result = response
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.fetch resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.fetch reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ err = runErr
+ return
+ }
+ }()
+
+ return
+ }, func(rt *goja.Runtime, _ any, err error) {
+ if !lo.IsNil(err) {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.fetch reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.fetch worker run: %v", p.Name, runErr)
+ if rejectErr := reject(rt.NewGoError(runErr)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.fetch reject: %v", p.Name, rejectErr)
+ }
+ }
+
+ return rt.ToValue(promise)
+ })))
+
+ lo.Must0(client.Set("socket", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ var path string
+ if goja.IsString(call.Argument(0)) {
+ path = call.Argument(0).String()
+ } else {
+ err = fmt.Errorf("path required")
+ return
+ }
+
+ if !strings.HasPrefix(path, "/") {
+ err = fmt.Errorf("path must start with /")
+ return
+ }
+
+ var protocols []string
+ if proto := call.Argument(1); isJsValueNotNull(proto) {
+ if protoObj := proto.ToObject(rt); protoObj != nil && protoObj.ClassName() == "Array" {
+ if arr, ok := proto.Export().([]interface{}); ok {
+ for _, v := range arr {
+ protocols = append(protocols, fmt.Sprintf("%v", v))
+ }
+ }
+ } else {
+ protocols = []string{proto.String()}
+ }
+ }
+
+ var gwsConn atomic.Pointer[gws.Conn]
+ var readyState atomic.Int64
+ var bufferedAmount atomic.Int64
+
+ readyState.Store(int64(WebSocketReadyStateConnecting))
+
+ wsURL := fmt.Sprintf("ws://127.0.0.1:%s%s", util.ServerPort, path)
+ wsHeader := http.Header{}
+ wsHeader.Set(model.XAuthTokenKey, p.token)
+ if len(protocols) > 0 {
+ wsHeader.Set("Sec-WebSocket-Protocol", strings.Join(protocols, ", "))
+ }
+
+ wsObj := rt.NewObject()
+
+ invokeHook := func(_ *goja.Runtime, name string, args ...goja.Value) {
+ hook := wsObj.Get(name)
+ if fn, ok := goja.AssertFunction(hook); ok {
+ if _, callErr := fn(wsObj, args...); callErr != nil {
+ logging.LogErrorf("[plugin:%s] ws hook %q: %v", p.Name, name, callErr)
+ }
+ }
+ }
+
+ setProtocol := func(rt *goja.Runtime, protocol string) {
+ wsObj.Set("protocol", rt.ToValue(protocol))
+ }
+
+ setReadyState := func(rt *goja.Runtime, state WebSocketState) {
+ readyState.Store(int64(state))
+ wsObj.Set("readyState", rt.ToValue(state))
+ }
+
+ updateBufferedAmount := func(rt *goja.Runtime, delta int) {
+ bufferedAmount.Add(int64(delta))
+ wsObj.Set("bufferedAmount", rt.ToValue(bufferedAmount.Load()))
+ }
+
+ h := &WsEventHandler{p: p}
+
+ manager := &WsManager{
+ BufferedAmount: &bufferedAmount,
+
+ InvokeHook: invokeHook,
+ SetProtocol: setProtocol,
+ SetReadyState: setReadyState,
+ }
+
+ h.BindOnOpen(manager)
+ h.BindOnClose(manager)
+ h.BindOnPing(manager)
+ h.BindOnPong(manager)
+ h.BindOnMessage(manager)
+
+ var openOnce sync.Once
+
+ ctx, cancel := context.WithCancel(p.context)
+ var closeOnce sync.Once
+ doClose := func() {
+ closeOnce.Do(func() {
+ cancel()
+ })
+ }
+
+ ws_open := rt.ToValue(func(openCall goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ openPromise, openResolve, openReject := rt.NewPromise()
+
+ openRunErr := p.worker.Run(func(rt *goja.Runtime) (opening any, err error) {
+ opening = false
+ openOnce.Do(func() {
+ opening = true
+ go func() {
+ conn, _, dialErr := gws.NewClient(h, &gws.ClientOption{
+ Addr: wsURL,
+ RequestHeader: wsHeader,
+ })
+ if dialErr != nil {
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ event := rt.NewObject()
+ event.Set("type", rt.ToValue("error"))
+ event.Set("error", rt.NewGoError(dialErr))
+ invokeHook(rt, "onerror", event)
+ return
+ }, nil)
+ p.worker.Run(func(rt *goja.Runtime) (_ any, dialErr2 error) {
+ dialErr2 = dialErr
+ return
+ }, func(rt *goja.Runtime, _ any, dialErr2 error) {
+ if rejectErr := openReject(rt.NewGoError(dialErr2)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.open reject: %v", p.Name, rejectErr)
+ }
+ })
+ doClose()
+ return
+ }
+ gwsConn.Store(conn)
+ go func() {
+ <-ctx.Done()
+ conn.NetConn().Close()
+ }()
+ // Resolve the open promise before starting ReadLoop so the caller
+ // can await open() and then rely on onopen for additional setup.
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ if resolveErr := openResolve(nil); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.open resolve: %v", p.Name, resolveErr)
+ }
+ return
+ }, nil)
+ conn.ReadLoop()
+ doClose()
+ }()
+ })
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if opening, ok := result.(bool); !ok || !opening {
+ if resolveErr := openResolve(nil); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.open resolve: %v", p.Name, resolveErr)
+ }
+ }
+ } else {
+ if rejectErr := openReject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.open reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if openRunErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.open worker run: %v", p.Name, openRunErr)
+ }
+
+ return rt.ToValue(openPromise)
+ })
+
+ ws_send := rt.ToValue(func(sendCall goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ sendPromise, sendResolve, sendReject := rt.NewPromise()
+
+ sendRunErr := p.worker.Run(func(rt *goja.Runtime) (_ any, err error) {
+ var messageData []byte
+ var opcode gws.Opcode
+ if data := sendCall.Argument(0); isJsValueNotNull(data) {
+ if arrayBuffer, ok := data.Export().(goja.ArrayBuffer); ok {
+ opcode = gws.OpcodeBinary
+ b := arrayBuffer.Bytes()
+ messageData = make([]byte, len(b))
+ copy(messageData, b) // ArrayBuffer.Bytes() points into JS engine memory; copy before async send
+ } else {
+ opcode = gws.OpcodeText
+ messageData = []byte(data.String())
+ }
+ }
+
+ state := WebSocketState(readyState.Load())
+ if state == WebSocketReadyStateClosing || state == WebSocketReadyStateClosed {
+ err = fmt.Errorf("WebSocket is not open (state: %d)", state)
+ return
+ }
+
+ c := gwsConn.Load()
+ if c == nil {
+ err = fmt.Errorf("WebSocket not yet connected")
+ return
+ }
+
+ updateBufferedAmount(rt, len(messageData))
+ c.WriteAsync(opcode, messageData, func(writeErr error) {
+ p.worker.Run(func(rt *goja.Runtime) (_ any, err error) {
+ if writeErr == nil {
+ updateBufferedAmount(rt, -len(messageData))
+ } else {
+ err = writeErr
+ }
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := sendResolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.send resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := sendReject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.send reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ })
+ return
+ }, func(rt *goja.Runtime, _ any, err error) {
+ if !lo.IsNil(err) {
+ if rejectErr := sendReject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.send reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if sendRunErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.send worker run: %v", p.Name, sendRunErr)
+ }
+
+ return rt.ToValue(sendPromise)
+ })
+
+ ws_ping := rt.ToValue(func(pingCall goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ pingPromise, pingResolve, pingReject := rt.NewPromise()
+
+ pingRunErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ var pingData string
+ if isJsValueNotNull(pingCall.Argument(0)) {
+ pingData = pingCall.Argument(0).String()
+ }
+ if c := gwsConn.Load(); c != nil {
+ err = c.WritePing([]byte(pingData))
+ } else {
+ err = fmt.Errorf("WebSocket not yet connected")
+ }
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := pingResolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.ping resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := pingReject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.ping reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if pingRunErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.ping worker run: %v", p.Name, pingRunErr)
+ }
+
+ return rt.ToValue(pingPromise)
+ })
+
+ ws_pong := rt.ToValue(func(pongCall goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ pongPromise, pongResolve, pongReject := rt.NewPromise()
+
+ pongRunErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ var pongData string
+ if isJsValueNotNull(pongCall.Argument(0)) {
+ pongData = pongCall.Argument(0).String()
+ }
+ if c := gwsConn.Load(); c != nil {
+ err = c.WritePong([]byte(pongData))
+ } else {
+ err = fmt.Errorf("WebSocket not yet connected")
+ }
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := pongResolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.pong resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := pongReject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.pong reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if pongRunErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.pong worker run: %v", p.Name, pongRunErr)
+ }
+
+ return rt.ToValue(pongPromise)
+ })
+
+ ws_close := rt.ToValue(func(closeCall goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ closePromise, closeResolve, closeReject := rt.NewPromise()
+
+ closeRunErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ code := uint16(1000)
+ var reason []byte
+ if isJsValueNotNull(closeCall.Argument(0)) {
+ code = uint16(closeCall.Argument(0).ToInteger())
+ }
+ if isJsValueNotNull(closeCall.Argument(1)) {
+ reason = []byte(closeCall.Argument(1).String())
+ }
+ if c := gwsConn.Load(); c != nil {
+ setReadyState(rt, WebSocketReadyStateClosing)
+ err = c.WriteClose(code, reason)
+ }
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := closeResolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.close resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := closeReject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.close reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if closeRunErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket.close worker run: %v", p.Name, closeRunErr)
+ }
+
+ return rt.ToValue(closePromise)
+ })
+
+ lo.Must0(wsObj.Set("binaryType", rt.ToValue("arraybuffer")))
+ lo.Must0(wsObj.Set("bufferedAmount", rt.ToValue(bufferedAmount.Load())))
+ lo.Must0(wsObj.Set("extensions", rt.ToValue("")))
+ lo.Must0(wsObj.Set("protocol", rt.ToValue("")))
+ lo.Must0(wsObj.Set("readyState", rt.ToValue(readyState.Load())))
+ lo.Must0(wsObj.Set("url", rt.ToValue(wsURL)))
+
+ lo.Must0(wsObj.Set("onopen", goja.Null()))
+ lo.Must0(wsObj.Set("onmessage", goja.Null()))
+ lo.Must0(wsObj.Set("onping", goja.Null()))
+ lo.Must0(wsObj.Set("onpong", goja.Null()))
+ lo.Must0(wsObj.Set("onclose", goja.Null()))
+ lo.Must0(wsObj.Set("onerror", goja.Null()))
+
+ lo.Must0(wsObj.Set("open", ws_open))
+ lo.Must0(wsObj.Set("send", ws_send))
+ lo.Must0(wsObj.Set("ping", ws_ping))
+ lo.Must0(wsObj.Set("pong", ws_pong))
+ lo.Must0(wsObj.Set("close", ws_close))
+
+ lo.Must0(ObjectSeal(rt, wsObj))
+
+ result = wsObj
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.socket worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ })))
+
+ lo.Must0(client.Set("event", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ var path string
+ if goja.IsString(call.Argument(0)) {
+ path = call.Argument(0).String()
+ } else {
+ err = fmt.Errorf("path required")
+ return
+ }
+
+ if !strings.HasPrefix(path, "/") {
+ err = fmt.Errorf("path must start with /")
+ return
+ }
+
+ var readyState atomic.Int64
+
+ readyState.Store(int64(EventSourceConnecting))
+
+ esURL := fmt.Sprintf("http://127.0.0.1:%s%s", util.ServerPort, path)
+
+ ctx, cancel := context.WithCancel(p.context)
+
+ var closeOnce sync.Once
+ doClose := func() {
+ closeOnce.Do(func() {
+ cancel()
+ })
+ }
+
+ esObj := rt.NewObject()
+
+ setReadyState := func(state EventSourceState) {
+ readyState.Store(int64(state))
+ esObj.Set("readyState", rt.ToValue(state))
+ }
+
+ invokeEsHook := func(name string, args ...goja.Value) {
+ hook := esObj.Get(name)
+ if fn, ok := goja.AssertFunction(hook); ok {
+ if _, callErr := fn(esObj, args...); callErr != nil {
+ logging.LogErrorf("[plugin:%s] es hook %q: %v", p.Name, name, callErr)
+ }
+ }
+ }
+
+ es_close := rt.ToValue(func(goja.FunctionCall) goja.Value {
+ setReadyState(EventSourceClosed)
+ doClose()
+ return goja.Undefined()
+ })
+
+ lo.Must0(esObj.Set("readyState", rt.ToValue(readyState.Load())))
+ lo.Must0(esObj.Set("url", rt.ToValue(path)))
+
+ lo.Must0(esObj.Set("onopen", goja.Null()))
+ lo.Must0(esObj.Set("onmessage", goja.Null()))
+ lo.Must0(esObj.Set("onclose", goja.Null()))
+ lo.Must0(esObj.Set("onerror", goja.Null()))
+
+ lo.Must0(esObj.Set("close", es_close))
+
+ lo.Must0(ObjectSeal(rt, esObj))
+
+ setReadyState(EventSourceConnecting)
+
+ go func() {
+ var err error
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("panic during siyuan.client.event: %v", r)
+ }
+
+ doClose()
+
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ if err != nil && !errors.Is(err, context.Canceled) {
+ event := rt.NewObject()
+ event.Set("type", rt.ToValue("error"))
+ event.Set("error", rt.NewGoError(err))
+ invokeEsHook("onerror", event)
+ }
+ if EventSourceState(readyState.Load()) != EventSourceClosed {
+ setReadyState(EventSourceClosed)
+ }
+ return
+ }, nil)
+ }()
+
+ sseClient := sse.NewClient(esURL)
+ sseClient.Headers[model.XAuthTokenKey] = p.token
+
+ sseClient.OnConnect(func(_ *sse.Client) {
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ setReadyState(EventSourceOpen)
+ event := rt.NewObject()
+ event.Set("type", rt.ToValue("open"))
+ invokeEsHook("onopen", event)
+ return
+ }, nil)
+ })
+
+ sseClient.OnDisconnect(func(_ *sse.Client) {
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ setReadyState(EventSourceClosed)
+ event := rt.NewObject()
+ event.Set("type", rt.ToValue("close"))
+ invokeEsHook("onclose", event)
+ return
+ }, nil)
+ })
+
+ err = sseClient.SubscribeRawWithContext(ctx, func(msg *sse.Event) {
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ typ := "message"
+ if len(msg.Event) > 0 {
+ typ = string(msg.Event)
+ }
+ event := rt.NewObject()
+ event.Set("type", rt.ToValue(typ))
+ event.Set("data", rt.ToValue(string(msg.Data)))
+ event.Set("lastEventId", rt.ToValue(string(msg.ID)))
+ invokeEsHook("onmessage", event)
+ return
+ }, nil)
+ })
+ }()
+
+ result = esObj
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.event resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.event reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.client.event worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ })))
+
+ lo.Must0(ObjectFreeze(rt, client))
+
+ lo.Must0(siyuan.Set("client", client))
+ return
+}
diff --git a/kernel/plugin/api_event.go b/kernel/plugin/api_event.go
new file mode 100644
index 0000000000..c5c71e3c9b
--- /dev/null
+++ b/kernel/plugin/api_event.go
@@ -0,0 +1,80 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "fmt"
+
+ "github.com/dop251/goja"
+ "github.com/samber/lo"
+ "github.com/siyuan-note/logging"
+)
+
+// injectEvent adds siyuan.event to the goja context.
+func injectEvent(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("injectEvent: %v", r)
+ }
+ }()
+
+ event := rt.NewObject()
+
+ lo.Must0(event.Set("handler", goja.Null()))
+
+ lo.Must0(event.Set("emit", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ if len(call.Arguments) < 2 {
+ err = fmt.Errorf("topic and event required")
+ return
+ }
+
+ topic := call.Argument(0).String()
+ if topic == "" {
+ err = fmt.Errorf("topic required")
+ return
+ }
+
+ event := call.Argument(1).Export()
+
+ p.bus.Publish(topic, event)
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.event.emit resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.event.emit reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.event.emit worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ })))
+
+ lo.Must0(ObjectSeal(rt, event))
+
+ lo.Must0(siyuan.Set("event", event))
+ return
+}
diff --git a/kernel/plugin/api_logger.go b/kernel/plugin/api_logger.go
new file mode 100644
index 0000000000..09ed5746c5
--- /dev/null
+++ b/kernel/plugin/api_logger.go
@@ -0,0 +1,129 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/dop251/goja"
+ "github.com/samber/lo"
+ "github.com/siyuan-note/logging"
+)
+
+type Printer struct {
+ name string // plugin name for log prefix
+}
+
+func (p *Printer) Log(s string) {
+ go print(p.name, s, logging.LogInfof)
+}
+
+func (p *Printer) Warn(s string) {
+ go print(p.name, s, logging.LogWarnf)
+}
+
+func (p *Printer) Error(s string) {
+ go print(p.name, s, logging.LogErrorf)
+}
+
+// print logs the message line by line with the plugin name as prefix, using the provided log function.
+func print(name, s string, logf func(format string, v ...interface{})) {
+ rows := strings.Split(s, "\n")
+ for _, row := range rows {
+ logf("[plugin:%s] %s", name, row)
+ }
+}
+
+// injectLogger adds siyuan.logger to the goja context.
+func injectLogger(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("injectLogger: %v", r)
+ }
+ }()
+
+ logger := rt.NewObject()
+
+ lo.Must0(logger.Set("trace", rt.ToValue(loggerWrapper(p, logging.LogTracef))))
+ lo.Must0(logger.Set("debug", rt.ToValue(loggerWrapper(p, logging.LogDebugf))))
+ lo.Must0(logger.Set("info", rt.ToValue(loggerWrapper(p, logging.LogInfof))))
+ lo.Must0(logger.Set("warn", rt.ToValue(loggerWrapper(p, logging.LogWarnf))))
+ lo.Must0(logger.Set("error", rt.ToValue(loggerWrapper(p, logging.LogErrorf))))
+
+ lo.Must0(ObjectFreeze(rt, logger))
+
+ lo.Must0(siyuan.Set("logger", logger))
+ return
+}
+
+// loggerWrapper returns a JS-callable function that logs a message at the given level.
+// Logging is synchronous (in-process, no I/O), so resolve is called inline without worker.Run.
+func loggerWrapper(p *KernelPlugin, logf func(format string, args ...any)) func(goja.FunctionCall, *goja.Runtime) goja.Value {
+ return func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ parts := make([]string, 0, len(call.Arguments))
+ for _, arg := range call.Arguments {
+ if goja.IsString(arg) {
+ parts = append(parts, arg.String())
+ continue
+ }
+
+ if arg == nil {
+ parts = append(parts, "null")
+ continue
+ }
+
+ if goja.IsUndefined(arg) || goja.IsNull(arg) {
+ parts = append(parts, arg.String())
+ continue
+ }
+
+ argObj := arg.ToObject(rt)
+ if argObj != nil {
+ if argJson, marshalErr := argObj.MarshalJSON(); marshalErr == nil {
+ parts = append(parts, string(argJson))
+ continue
+ }
+ }
+
+ parts = append(parts, arg.String())
+ }
+ msg := strings.Join(parts, " ")
+
+ go print(p.Name, msg, logf)
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.logger resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.logger reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.logger worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ }
+}
diff --git a/kernel/plugin/api_plugin.go b/kernel/plugin/api_plugin.go
new file mode 100644
index 0000000000..e82a01eb15
--- /dev/null
+++ b/kernel/plugin/api_plugin.go
@@ -0,0 +1,53 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "fmt"
+
+ "github.com/dop251/goja"
+ "github.com/samber/lo"
+ "github.com/siyuan-note/siyuan/kernel/bazaar"
+)
+
+// injectPlugin adds siyuan.plugin to the goja context.
+func injectPlugin(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("injectPlugin: %v", r)
+ }
+ }()
+
+ lifecycle := rt.NewObject()
+ lo.Must0(lifecycle.Set("onload", goja.Null()))
+ lo.Must0(lifecycle.Set("onloaded", goja.Null()))
+ lo.Must0(lifecycle.Set("onrunning", goja.Null()))
+ lo.Must0(lifecycle.Set("onunload", goja.Null()))
+ lo.Must0(ObjectSeal(rt, lifecycle))
+
+ plugin := rt.NewObject()
+ lo.Must0(plugin.Set("name", p.Name))
+ lo.Must0(plugin.Set("version", p.Version))
+ lo.Must0(plugin.Set("displayName", p.DisplayName))
+ lo.Must0(plugin.Set("platform", bazaar.GetCurrentBackend()))
+ lo.Must0(plugin.Set("i18n", p.I18n))
+ lo.Must0(plugin.Set("lifecycle", lifecycle))
+ lo.Must0(ObjectFreeze(rt, plugin))
+
+ lo.Must0(siyuan.Set("plugin", plugin))
+ return
+}
diff --git a/kernel/plugin/api_rpc.go b/kernel/plugin/api_rpc.go
new file mode 100644
index 0000000000..8d0d34b422
--- /dev/null
+++ b/kernel/plugin/api_rpc.go
@@ -0,0 +1,184 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "fmt"
+
+ "github.com/dop251/goja"
+ "github.com/samber/lo"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// injectRpc adds siyuan.rpc method for RPC method registration.
+func injectRpc(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("injectRpc: %v", r)
+ }
+ }()
+
+ rpc := rt.NewObject()
+
+ lo.Must0(rpc.Set("bind", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ var name string
+ var method goja.Callable
+ var descriptions []string
+
+ if len(call.Arguments) < 2 {
+ err = fmt.Errorf("method name and function required")
+ return
+ }
+ nameArg := call.Argument(0)
+ methodArg := call.Argument(1)
+ descArgs := call.Arguments[2:]
+
+ if goja.IsString(nameArg) {
+ name = nameArg.String()
+ } else {
+ err = fmt.Errorf("first argument must be method name string")
+ return
+ }
+
+ if methodJs, ok := goja.AssertFunction(methodArg); ok {
+ method = methodJs
+ } else {
+ err = fmt.Errorf("second argument must be a function")
+ }
+
+ descriptions = make([]string, len(descArgs))
+ for i, a := range descArgs {
+ descriptions[i] = a.String()
+ }
+
+ err = p.bindRpcMethod(name, method, descriptions...)
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.rpc.bind resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.rpc.bind reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.rpc.bind worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ })))
+
+ lo.Must0(rpc.Set("unbind", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ var name string
+ if len(call.Arguments) < 1 {
+ err = fmt.Errorf("method name required")
+ return
+ }
+
+ nameArg := call.Argument(0)
+ if goja.IsString(nameArg) {
+ name = nameArg.String()
+ } else {
+ err = fmt.Errorf("first argument must be method name string")
+ return
+ }
+
+ err = p.unbindRpcMethod(name)
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.rpc.unbind resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.rpc.unbind reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.rpc.unbind worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ })))
+
+ lo.Must0(rpc.Set("broadcast", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ if len(call.Arguments) < 1 {
+ err = fmt.Errorf("method required")
+ return
+ }
+
+ var method string
+ if m := call.Argument(0); goja.IsString(m) {
+ method = m.String()
+ }
+
+ var params util.Optional[any]
+ arg := call.Argument(1)
+ if goja.IsUndefined(arg) {
+ params.Value = nil
+ params.Exists = false
+ params.IsNull = false
+ } else if goja.IsNull(arg) {
+ params.Value = nil
+ params.Exists = true
+ params.IsNull = true
+ } else {
+ params.Value = arg.Export()
+ params.Exists = true
+ params.IsNull = false
+ }
+
+ p.BroadcastNotification(method, params)
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.rpc.broadcast resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.rpc.broadcast reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.rpc.broadcast worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ })))
+
+ lo.Must0(ObjectFreeze(rt, rpc))
+
+ lo.Must0(siyuan.Set("rpc", rpc))
+ return
+}
diff --git a/kernel/plugin/api_server.go b/kernel/plugin/api_server.go
new file mode 100644
index 0000000000..589ae64de3
--- /dev/null
+++ b/kernel/plugin/api_server.go
@@ -0,0 +1,62 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "fmt"
+
+ "github.com/dop251/goja"
+ "github.com/samber/lo"
+)
+
+// injectServer adds siyuan.server to the goja context.
+func injectServer(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("injectServer: %v", r)
+ }
+ }()
+
+ http := rt.NewObject()
+ ws := rt.NewObject()
+ es := rt.NewObject()
+
+ lo.Must0(http.Set("handler", goja.Null()))
+ lo.Must0(ws.Set("handler", goja.Null()))
+ lo.Must0(es.Set("handler", goja.Null()))
+
+ lo.Must0(ObjectSeal(rt, http))
+ lo.Must0(ObjectSeal(rt, ws))
+ lo.Must0(ObjectSeal(rt, es))
+
+ private := rt.NewObject()
+
+ lo.Must0(private.Set(string(RequestTypeHTTP), http))
+ lo.Must0(private.Set(string(RequestTypeWS), ws))
+ lo.Must0(private.Set(string(RequestTypeSSE), es))
+
+ lo.Must0(ObjectFreeze(rt, private))
+
+ server := rt.NewObject()
+
+ lo.Must0(server.Set("private", private))
+
+ lo.Must0(ObjectFreeze(rt, server))
+
+ lo.Must0(siyuan.Set("server", server))
+ return
+}
diff --git a/kernel/plugin/api_storage.go b/kernel/plugin/api_storage.go
new file mode 100644
index 0000000000..9927b24baf
--- /dev/null
+++ b/kernel/plugin/api_storage.go
@@ -0,0 +1,328 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/dop251/goja"
+ "github.com/samber/lo"
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// injectStorage adds siyuan.storage.* methods for scoped file CRUD.
+func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("injectStorage: %v", r)
+ }
+ }()
+
+ baseDir := filepath.Join(util.DataDir, "storage", "petal", p.Name)
+
+ resolvePath := func(relPath string) (abs string, err error) {
+ abs = filepath.Join(baseDir, filepath.Clean(relPath))
+ if !(abs == baseDir || strings.HasPrefix(abs, baseDir+string(filepath.Separator))) {
+ err = fmt.Errorf("siyuan.storage: path traversal not allowed")
+ }
+ return
+ }
+
+ storage := rt.NewObject()
+
+ // siyuan.storage.get(path) -> Promise<{text, json, arrayBuffer}>
+ lo.Must0(storage.Set("get", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ var path string
+ if len(call.Arguments) >= 1 && goja.IsString(call.Argument(0)) {
+ path = call.Argument(0).String()
+ } else {
+ err = fmt.Errorf("path required")
+ return
+ }
+
+ abs, resolveErr := resolvePath(path)
+ if resolveErr != nil {
+ err = resolveErr
+ return
+ }
+
+ go func() (result []byte, err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("panic during siyuan.storage.get: %v", r)
+ }
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ if err != nil {
+ return nil, err
+ }
+
+ content := rt.NewObject()
+ if err = ObjectSetDataMethods(p, rt, content, result); err != nil {
+ return nil, err
+ }
+
+ return content, nil
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.get resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.get reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ }()
+
+ data, readErr := filelock.ReadFile(abs)
+ if readErr != nil {
+ err = readErr
+ return
+ }
+
+ result = data
+ return
+ }()
+
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if !lo.IsNil(err) {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.get reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.get worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ })))
+
+ // siyuan.storage.put(path, content) -> Promise<void>
+ lo.Must0(storage.Set("put", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ if len(call.Arguments) < 2 {
+ err = fmt.Errorf("path and content required")
+ return
+ }
+ path := call.Argument(0).String()
+ content := call.Argument(1).String()
+ abs, resolveErr := resolvePath(path)
+ if resolveErr != nil {
+ err = resolveErr
+ return
+ }
+
+ go func() (result any, err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("panic during siyuan.storage.put: %v", r)
+ }
+
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.put resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.put reject: %v", p.Name, rejectErr)
+ }
+ }
+ return
+ }, nil)
+ }()
+
+ if mkdirErr := os.MkdirAll(filepath.Dir(abs), 0755); mkdirErr != nil {
+ err = fmt.Errorf("failed to make directory: %w", mkdirErr)
+ return
+ }
+ if writeErr := filelock.WriteFile(abs, []byte(content)); writeErr != nil {
+ err = fmt.Errorf("failed to write file: %w", writeErr)
+ return
+ }
+ return
+ }()
+
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if !lo.IsNil(err) {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.put reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.put worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ })))
+
+ // siyuan.storage.remove(path) -> Promise<void>
+ lo.Must0(storage.Set("remove", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ if len(call.Arguments) < 1 {
+ err = fmt.Errorf("path required")
+ return
+ }
+ path := call.Argument(0).String()
+ abs, resolveErr := resolvePath(path)
+ if resolveErr != nil {
+ err = resolveErr
+ return
+ }
+ if abs == baseDir {
+ err = fmt.Errorf("cannot remove storage root")
+ return
+ }
+
+ go func() (result any, err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("panic during siyuan.storage.remove: %v", r)
+ }
+
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.remove resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.remove reject: %v", p.Name, rejectErr)
+ }
+ }
+ return
+ }, nil)
+ }()
+
+ if removeErr := os.RemoveAll(abs); removeErr != nil {
+ err = fmt.Errorf("failed to remove: %w", removeErr)
+ return
+ }
+ return
+ }()
+
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if !lo.IsNil(err) {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.remove reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.remove worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ })))
+
+ // siyuan.storage.list(path) -> Promise<Entry[]>
+ lo.Must0(storage.Set("list", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ if len(call.Arguments) < 1 {
+ err = fmt.Errorf("path required")
+ return
+ }
+ path := call.Argument(0).String()
+ abs, resolveErr := resolvePath(path)
+ if resolveErr != nil {
+ err = resolveErr
+ return
+ }
+
+ go func() (result any, err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("panic during siyuan.storage.list: %v", r)
+ }
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.list resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.list reject: %v", p.Name, rejectErr)
+ }
+ }
+ return
+ }, nil)
+ }()
+
+ entries, readErr := os.ReadDir(abs)
+ if readErr != nil {
+ err = fmt.Errorf("failed to read directory: %w", readErr)
+ return
+ }
+
+ results := make([]R, 0, len(entries))
+ for _, entry := range entries {
+ info, infoErr := entry.Info()
+ if infoErr != nil {
+ continue
+ }
+ results = append(results, R{
+ "name": entry.Name(),
+ "isDir": info.IsDir(),
+ "isSymlink": util.IsSymlink(entry),
+ "updated": info.ModTime().Unix(),
+ })
+ }
+
+ result = results
+ return
+ }()
+
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if !lo.IsNil(err) {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.list reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.storage.list worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ })))
+
+ lo.Must0(ObjectFreeze(rt, storage))
+
+ lo.Must0(siyuan.Set("storage", storage))
+ return
+}
diff --git a/kernel/plugin/manager.go b/kernel/plugin/manager.go
new file mode 100644
index 0000000000..8d59a0ecc7
--- /dev/null
+++ b/kernel/plugin/manager.go
@@ -0,0 +1,235 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "sync"
+ "sync/atomic"
+
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+// PluginManager discovers, loads, starts, and stops kernel plugins.
+type PluginManager struct {
+ lifecycleMu sync.Mutex // protects the lifecycle state of the manager (starting/stopping), allowing concurrent start/stop of different plugins while preventing concurrent start/stop of the entire manager
+
+ plugins sync.Map // map[string]*KernelPlugin
+
+ pluginMu sync.Map // map[string]*sync.Mutex, one per plugin name, to serialize start/stop of the same plugin while allowing concurrent start/stop of different plugins
+}
+
+type PluginInfo struct {
+ Name string `json:"name"`
+ State string `json:"state"`
+ Methods []*RpcMethodInfo `json:"methods"`
+}
+
+var (
+ manager *PluginManager
+ managerOnce sync.Once
+)
+
+// InitManager initializes the global PluginManager singleton and starts it.
+func InitManager() {
+ m := GetManager()
+
+ model.OnKernelPluginStart = func(petal *model.Petal) { GetManager().StartPlugin(petal) }
+ model.OnKernelPluginStop = func(petal *model.Petal) { GetManager().StopPlugin(petal) }
+ model.OnKernelPluginShutdown = func() { GetManager().Stop() }
+
+ m.Start()
+}
+
+// GetManager returns the singleton PluginManager.
+func GetManager() *PluginManager {
+ managerOnce.Do(func() {
+ manager = &PluginManager{}
+ })
+ return manager
+}
+
+// Start loads and starts all kernel-eligible plugins.
+// Called from main.go after model initialization.
+func (m *PluginManager) Start() {
+ defer func() {
+ if r := recover(); r != nil {
+ logging.LogErrorf("kernel plugin manager failed to start: %v", r)
+ }
+ }()
+
+ m.lifecycleMu.Lock()
+ defer m.lifecycleMu.Unlock()
+
+ logging.LogInfof("kernel plugin manager starting")
+
+ petals := model.LoadKernelPetals()
+
+ all := len(petals)
+ counter := int64(0)
+
+ wg := sync.WaitGroup{}
+ for _, petal := range petals {
+ wg.Go(func() {
+ if ok := m.StartPlugin(petal); ok {
+ atomic.AddInt64(&counter, 1)
+ }
+ })
+ }
+ wg.Wait()
+
+ logging.LogInfof("kernel plugin manager started, %d/%d plugin(s) loaded", counter, all)
+}
+
+// Stop shuts down all running kernel plugins.
+// Called from model.Close() before process exit.
+func (m *PluginManager) Stop() {
+ defer func() {
+ if r := recover(); r != nil {
+ logging.LogErrorf("kernel plugin manager failed to stop: %v", r)
+ }
+ }()
+
+ m.lifecycleMu.Lock()
+ defer m.lifecycleMu.Unlock()
+
+ logging.LogInfof("kernel plugin manager stopping")
+
+ all := int64(0)
+ counter := int64(0)
+
+ wg := sync.WaitGroup{}
+ m.plugins.Range(func(key, value any) bool {
+ atomic.AddInt64(&all, 1)
+ p := value.(*KernelPlugin)
+ wg.Go(func() {
+ ok, err := p.stop()
+ if err != nil {
+ logging.LogErrorf("[plugin:%s] stop failed: %s", p.Name, err)
+ }
+ if ok {
+ atomic.AddInt64(&counter, 1)
+ }
+ })
+ return true
+ })
+ wg.Wait()
+
+ logging.LogInfof("kernel plugin manager stopped, %d/%d plugin(s) unloaded", counter, all)
+}
+
+// StartPlugin starts a single kernel plugin.
+// Called when a petal is enabled via SetPetalEnabled.
+func (m *PluginManager) StartPlugin(petal *model.Petal) (ok bool) {
+ defer func() {
+ if r := recover(); r != nil {
+ logging.LogErrorf("[plugin:%s] panic during start: %v", petal.Name, r)
+ ok = false
+ }
+ }()
+
+ pluginMu := m.getPluginMu(petal.Name)
+ pluginMu.Lock()
+ defer pluginMu.Unlock()
+
+ m.stopPlugin(petal)
+
+ p := NewKernelPlugin(petal)
+
+ m.plugins.Store(p.Name, p)
+
+ if err := p.start(); err != nil {
+ logging.LogErrorf("[plugin:%s] start failed: %s", p.Name, err)
+ ok = false
+ return
+ }
+
+ ok = true
+ return
+}
+
+// StopPlugin stops a single kernel plugin.
+// Called when a petal is disabled via SetPetalEnabled.
+func (m *PluginManager) StopPlugin(petal *model.Petal) {
+ defer func() {
+ if r := recover(); r != nil {
+ logging.LogErrorf("[plugin:%s] panic during stop: %v", petal.Name, r)
+ }
+ }()
+
+ pluginMu := m.getPluginMu(petal.Name)
+ pluginMu.Lock()
+ defer pluginMu.Unlock()
+
+ m.stopPlugin(petal)
+}
+
+// stopPlugin removes and stops the plugin without acquiring the per-plugin mutex.
+// Callers must hold the per-plugin mutex returned by getPluginMu.
+func (m *PluginManager) stopPlugin(petal *model.Petal) {
+ value, loaded := m.plugins.LoadAndDelete(petal.Name)
+
+ if loaded {
+ p := value.(*KernelPlugin)
+ if _, err := p.stop(); err != nil {
+ logging.LogErrorf("[plugin:%s] stop failed: %s", p.Name, err)
+ }
+ }
+}
+
+// getPluginMu returns the per-plugin mutex for the given name, creating it if needed.
+func (m *PluginManager) getPluginMu(name string) *sync.Mutex {
+ v, _ := m.pluginMu.LoadOrStore(name, &sync.Mutex{})
+ return v.(*sync.Mutex)
+}
+
+// GetPlugin returns a loaded KernelPlugin by name, or nil.
+func (m *PluginManager) GetPlugin(name string) *KernelPlugin {
+ value, loaded := m.plugins.Load(name)
+ if loaded {
+ return value.(*KernelPlugin)
+ }
+ return nil
+}
+
+// GetLoadedPlugin returns the plugin info for a loaded KernelPlugin by name, or nil.
+func (m *PluginManager) GetLoadedPlugin(name string) (plugin *PluginInfo, found bool) {
+ value, loaded := m.plugins.Load(name)
+ if loaded {
+ p := value.(*KernelPlugin)
+ return &PluginInfo{
+ Name: p.Name,
+ State: p.State().String(),
+ Methods: p.GetRpcMethodsInfo(),
+ }, true
+ }
+ return nil, false
+}
+
+// GetLoadedPluginInfo returns a list of all loaded plugins with their RPC method info.
+func (m *PluginManager) GetLoadedPluginsInfo() (plugins []*PluginInfo) {
+ m.plugins.Range(func(key, value any) bool {
+ p := value.(*KernelPlugin)
+ plugins = append(plugins, &PluginInfo{
+ Name: p.Name,
+ State: p.State().String(),
+ Methods: p.GetRpcMethodsInfo(),
+ })
+ return true
+ })
+ return plugins
+}
diff --git a/kernel/plugin/plugin.go b/kernel/plugin/plugin.go
new file mode 100644
index 0000000000..432f7d3461
--- /dev/null
+++ b/kernel/plugin/plugin.go
@@ -0,0 +1,1234 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sync"
+ "sync/atomic"
+
+ "github.com/asaskevich/EventBus"
+ "github.com/dop251/goja"
+ "github.com/dop251/goja_nodejs/eventloop"
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+ "github.com/lxzan/gws"
+ "github.com/samber/lo"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+ "github.com/smallnest/chanx"
+)
+
+type PluginState int64
+
+type RpcMethod struct {
+ Name string
+ Descriptions []string
+ Method goja.Callable
+}
+
+type RpcMethodInfo struct {
+ Name string `json:"name"`
+ Descriptions []string `json:"descriptions"`
+}
+
+type R map[string]any
+
+const (
+ EventBusTopicPlugin = "plugin" // Topic to kernel plugin
+ EventBusTopicRuntime = "runtime" // Topic to javascript runtime
+)
+
+const (
+ PluginStateReady PluginState = iota
+ PluginStateLoading
+ PluginStateLoaded
+ PluginStateRunning
+ PluginStateStopping
+ PluginStateStopped
+ PluginStateError
+)
+
+func (s PluginState) String() string {
+ switch s {
+ case PluginStateReady:
+ return "ready"
+ case PluginStateLoading:
+ return "loading"
+ case PluginStateLoaded:
+ return "loaded"
+ case PluginStateRunning:
+ return "running"
+ case PluginStateStopping:
+ return "stopping"
+ case PluginStateStopped:
+ return "stopped"
+ case PluginStateError:
+ return "error"
+ default:
+ return "unknown"
+ }
+}
+
+// KernelPlugin represents a single kernel-side plugin instance.
+type KernelPlugin struct {
+ *model.Petal
+ token string // JWT for this plugin
+ file string // kernel.js file path named in js runtime (e.g. "plugin-name/kernel.js")
+
+ worker Worker // Worker for serializing plugin js-call-go (e.g. logger) and go-call-js (e.g. RPC calls) tasks on a single goroutine
+ runtime *eventloop.EventLoop // goja event loop runtime for this plugin
+
+ state atomic.Int64 // PluginState
+
+ context context.Context // Context for managing plugin lifecycle and cancellation
+ cancel context.CancelFunc // Cancel function for managing plugin lifecycle and cancellation
+
+ bus EventBus.Bus // Event bus for plugin events and RPC request/response dispatch
+
+ rpcMethods sync.Map // string -> *RpcMethod, registered JSON-RPC methods
+
+ socketsMu sync.RWMutex // mutex for gwsSockets map
+ sockets map[*gws.Conn]bool // tracked gws WebSocket connections (true: RPC server, false: regular)
+}
+
+func NewKernelPlugin(petal *model.Petal) *KernelPlugin {
+ token, err := model.CreatePluginJWT(petal.Name)
+ if err != nil {
+ logging.LogErrorf("Failed to create plugin JWT for [%s]: %v", petal.Name, err)
+ }
+
+ plugin := &KernelPlugin{
+ Petal: petal,
+ token: token,
+ file: fmt.Sprintf("%s/kernel.js", petal.Name),
+
+ bus: EventBus.New(),
+
+ sockets: make(map[*gws.Conn]bool),
+ }
+
+ plugin.state.Store(int64(PluginStateReady))
+ return plugin
+}
+
+// State returns the current plugin state (safe for concurrent reads).
+func (p *KernelPlugin) State() PluginState {
+ return PluginState(p.state.Load())
+}
+
+// InitRuntime initializes the goja runtime and evaluates kernel.js.
+func (p *KernelPlugin) InitRuntime() (err error) {
+ p.runtime = eventloop.NewEventLoop(eventloop.EnableConsole(true))
+ p.worker.Start(p.runtime)
+
+ p.runtime.Run(func(rt *goja.Runtime) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("goja panic during event loop run: %v", r)
+ }
+ }()
+
+ // Use JSON struct tags for field name mapping, with fallback to original names if "json" tag is absent.
+ rt.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
+
+ if enableErr := EnableExtendModules(p, rt); enableErr != nil {
+ err = fmt.Errorf("EnableExtendModules: %v", enableErr)
+ return
+ }
+
+ if enableErr := EnableSiyuanModule(p, rt); enableErr != nil {
+ err = fmt.Errorf("EnableSiyuanModule: %v", enableErr)
+ return
+ }
+
+ if _, runErr := rt.RunScript(p.file, p.Kernel.JS); runErr != nil {
+ err = fmt.Errorf("RunScript: %v", runErr)
+ return
+ }
+ })
+ p.runtime.Start()
+ return
+}
+
+// Eval evaluates JavaScript code in the plugin's goja runtime, returning the result or error.
+func (p *KernelPlugin) Eval(rt *goja.Runtime, code string) (goja.Value, error) {
+ return rt.RunScript(p.file, code)
+}
+
+// close interrupts the goja runtime and clears the pointer.
+func (p *KernelPlugin) close() (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("goja panic during close runtime: %v", r)
+ }
+ }()
+
+ if p.runtime != nil {
+ p.runtime.Stop() // Stops the event loop and waits for it to finish.
+ // p.runtime.Terminate() // Interrupts the runtime and causes all executing code to throw an exception.
+ }
+ return
+}
+
+// error sets the plugin state to errored and frees the goja runtime.
+func (p *KernelPlugin) error() {
+ if err := p.close(); err != nil {
+ logging.LogErrorf("[plugin:%s] failed to close runtime during error handling: %v", p.Name, err)
+ }
+
+ p.state.Store(int64(PluginStateError))
+}
+
+// start creates the goja runtime, injects sandbox globals, and evaluates kernel.js.
+func (p *KernelPlugin) start() (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ p.error()
+ err = fmt.Errorf("goja panic during start: %v", r)
+ }
+ }()
+
+ p.state.Store(int64(PluginStateLoading))
+ p.context, p.cancel = context.WithCancel(context.Background())
+
+ baseDir := filepath.Join(util.DataDir, "storage", "petal", p.Name)
+ if err := os.MkdirAll(baseDir, 0755); err != nil {
+ return fmt.Errorf("create plugin dir [%s] failed: %s", baseDir, err)
+ }
+
+ if runtimeErr := p.InitRuntime(); runtimeErr != nil {
+ p.error()
+ return fmt.Errorf("start runtime: %v", runtimeErr)
+ }
+
+ if subscribeErr := p.subscribeEventHandlers(); subscribeErr != nil {
+ p.error()
+ return fmt.Errorf("subscribe plugin events: %v", subscribeErr)
+ }
+
+ p.onLoad()
+ p.state.Store(int64(PluginStateLoaded))
+ p.onLoaded()
+ p.state.Store(int64(PluginStateRunning))
+ p.onRunning()
+
+ p.bus.Publish(EventBusTopicRuntime, R{
+ "id": uuid.NewString(),
+ "type": "start",
+ })
+
+ logging.LogDebugf("[plugin:%s] started", p.Name)
+ return
+}
+
+// stop cleanly shuts down the plugin: closes sockets, frees goja runtime.
+func (p *KernelPlugin) stop() (ok bool, err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ p.error()
+ ok = false
+ err = fmt.Errorf("panic during plugin stop: %v", r)
+ }
+ }()
+
+ if p.State() != PluginStateRunning {
+ ok = false
+ return
+ }
+
+ p.bus.Publish(EventBusTopicRuntime, R{
+ "id": uuid.NewString(),
+ "type": "stop",
+ })
+
+ p.state.Store(int64(PluginStateStopping))
+
+ p.onUnload()
+
+ p.rpcMethods.Clear()
+
+ p.cancel()
+
+ p.socketsMu.Lock()
+ for c := range p.sockets {
+ delete(p.sockets, c)
+ }
+ p.socketsMu.Unlock()
+
+ p.unsubscribeEventHandlers()
+
+ p.close()
+ p.state.Store(int64(PluginStateStopped))
+
+ logging.LogDebugf("[plugin:%s] stopped", p.Name)
+
+ ok = true
+ return
+}
+
+// onLoad is called before plugin loaded.
+func (p *KernelPlugin) onLoad() {
+ if p.State() == PluginStateLoading {
+ p.invokeHook("onload")
+ }
+}
+
+// onLoaded is called after plugin loaded.
+func (p *KernelPlugin) onLoaded() {
+ if p.State() == PluginStateLoaded {
+ p.invokeHook("onloaded")
+ }
+}
+
+// onRunning is called after plugin running.
+func (p *KernelPlugin) onRunning() {
+ if p.State() == PluginStateRunning {
+ p.invokeHook("onrunning")
+ }
+}
+
+// onUnload is called before plugin stop.
+func (p *KernelPlugin) onUnload() {
+ if p.State() == PluginStateStopping {
+ p.invokeHook("onunload")
+ }
+}
+
+// bindRpcMethod add or updates a JS function as a named RPC method.
+func (p *KernelPlugin) bindRpcMethod(name string, method goja.Callable, descriptions ...string) error {
+ p.rpcMethods.Store(name, &RpcMethod{
+ Name: name,
+ Descriptions: descriptions,
+ Method: method,
+ })
+ return nil
+}
+
+// unbindRpcMethod removes a registered RPC method
+func (p *KernelPlugin) unbindRpcMethod(name string) error {
+ _, ok := p.rpcMethods.LoadAndDelete(name)
+ if !ok {
+ return nil
+ }
+ return nil
+}
+
+// runtimeEventHandler dispatches an event to the plugin's goja runtime
+func (p *KernelPlugin) runtimeEventHandler(event any) {
+ p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ return dispatchEvent(p, rt, event)
+ }, nil)
+}
+
+// pluginEventHandler handles events sent to the plugin
+func (p *KernelPlugin) pluginEventHandler(event any) {
+ logging.LogDebugf("[plugin:%s] receive event: %#v", p.Name, event)
+}
+
+// subscribeEventHandlers subscribes to plugin lifecycle and RPC events, dispatching them to the plugin's JS runtime.
+func (p *KernelPlugin) subscribeEventHandlers() (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = r.(error)
+ }
+ }()
+
+ lo.Must0(p.bus.Subscribe(EventBusTopicRuntime, p.runtimeEventHandler))
+ lo.Must0(p.bus.Subscribe(EventBusTopicPlugin, p.pluginEventHandler))
+ return
+}
+
+// unsubscribeEventHandlers unsubscribes from plugin events.
+func (p *KernelPlugin) unsubscribeEventHandlers() (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = r.(error)
+ }
+ }()
+
+ lo.Must0(p.bus.Unsubscribe(EventBusTopicRuntime, p.runtimeEventHandler))
+ lo.Must0(p.bus.Unsubscribe(EventBusTopicPlugin, p.pluginEventHandler))
+ return
+}
+
+// GetRpcMethodsInfo returns a list of registered RPC methods with their descriptions.
+func (p *KernelPlugin) GetRpcMethodsInfo() (methods []*RpcMethodInfo) {
+ p.rpcMethods.Range(func(name any, value any) bool {
+ if method, ok := value.(*RpcMethod); ok {
+ methods = append(methods, &RpcMethodInfo{
+ Name: method.Name,
+ Descriptions: method.Descriptions,
+ })
+ }
+ return true
+ })
+ return
+}
+
+// BroadcastNotification sends a JSON-RPC 2.0 notification to all inbound RPC WebSocket clients.
+func (p *KernelPlugin) BroadcastNotification(method string, params util.Optional[any]) {
+ notification := JsonRpcRequest{
+ JsonRpc: JsonRpcVersion,
+ Method: method,
+ Params: params,
+ }
+ data, err := json.Marshal(notification)
+ if err != nil {
+ logging.LogWarnf("[plugin:%s] broadcast marshal: %s", p.Name, err)
+ return
+ }
+
+ p.socketsMu.RLock()
+ conns := make([]*gws.Conn, 0, len(p.sockets))
+ for conn, isRpcConnection := range p.sockets {
+ if isRpcConnection {
+ conns = append(conns, conn)
+ }
+ }
+ p.socketsMu.RUnlock()
+
+ var wg sync.WaitGroup
+ for _, conn := range conns {
+ wg.Add(1)
+ c := conn
+ payload := make([]byte, len(data))
+ copy(payload, data) // each conn needs its own copy; WriteAsync is async and all conns share the same source slice
+ c.WriteAsync(gws.OpcodeText, payload, func(writeErr error) {
+ defer wg.Done()
+ if writeErr != nil {
+ logging.LogWarnf("[plugin:%s] RPC WebSocket notification write failed: %s", p.Name, writeErr)
+ }
+ })
+ }
+ wg.Wait()
+}
+
+// dispatchRpcRequests dispatches multiple JSON-RPC requests concurrently.
+// Returns responses in the same order as requests. Nil responses indicate notifications.
+func (p *KernelPlugin) dispatchRpcRequests(requests []*JsonRpcProcessingRequest) []*JsonRpcProcessingResponse {
+ responses := make([]*JsonRpcProcessingResponse, len(requests))
+ var wg sync.WaitGroup
+
+ for i, request := range requests {
+ // For requests that failed JSON parsing or validation, return the error immediately without dispatching.
+ if request.Error != nil {
+ responses[i] = &JsonRpcProcessingResponse{Error: request.Error}
+ continue
+ }
+
+ // For notifications, dispatch without waiting for a response.
+ if request.Request.IsNotification() {
+ go func(request *JsonRpcRequest) {
+ p.dispatchRpcRequest(request)
+ }(request.Request)
+ responses[i] = nil
+ continue
+ }
+
+ if request.Request == nil {
+ responses[i] = nil
+ continue
+ }
+
+ // For normal requests, dispatch concurrently and collect responses.
+ wg.Add(1)
+ go func(index int, request *JsonRpcRequest) {
+ defer wg.Done()
+ responses[index] = p.dispatchRpcRequest(request)
+ }(i, request.Request)
+ }
+
+ wg.Wait()
+ return responses
+}
+
+// dispatchRpcRequest routes a single JSON-RPC request to the plugin's registered JS method.
+// Returns nil for notifications (no ID field).
+func (p *KernelPlugin) dispatchRpcRequest(request *JsonRpcRequest) *JsonRpcProcessingResponse {
+ // Validate request structure
+ if rpcError := request.Validate(); rpcError != nil {
+ // For notifications, return nil (no response).
+ if request.IsNotification() {
+ return nil
+ }
+
+ // For invalid requests, return error response.
+ return &JsonRpcProcessingResponse{
+ Error: &JsonRpcErrorResponse{
+ JsonRpc: JsonRpcVersion,
+ Error: rpcError,
+ ID: request.ID,
+ },
+ }
+ }
+
+ // For notifications, call the method without waiting for a response and return nil.
+ if request.IsNotification() {
+ go p.callRpcMethod(request.Method, request.Params.Value)
+ return nil
+ }
+
+ // For normal requests, call the method and return response or error.
+ rpcResult, rpcError := p.callRpcMethod(request.Method, request.Params.Value)
+ if rpcError == nil {
+ return &JsonRpcProcessingResponse{
+ Response: &JsonRpcRequestResponse{
+ JsonRpc: JsonRpcVersion,
+ Result: rpcResult,
+ ID: request.ID,
+ },
+ }
+ } else {
+ return &JsonRpcProcessingResponse{
+ Error: &JsonRpcErrorResponse{
+ JsonRpc: JsonRpcVersion,
+ Error: rpcError,
+ ID: request.ID,
+ },
+ }
+ }
+}
+
+// callRpcMethod invokes a registered JS RPC method via the event bus and awaits the response.
+func (p *KernelPlugin) callRpcMethod(method string, params any) (rpcResult any, rpcError *JsonRpcError) {
+ defer func() {
+ if r := recover(); r != nil {
+ logging.LogDebugf("[plugin:%s] panic in RPC method [%s]: %v", p.Name, method, r)
+ rpcError = &JsonRpcError{
+ Code: JsonRpcErrorCodeInternalError,
+ Message: JsonRpcErrorInternalError.Message,
+ Data: fmt.Sprintf("goja panic in RPC method [%s]: %v", method, r),
+ }
+ }
+ }()
+
+ if p.State() != PluginStateRunning {
+ rpcError = &JsonRpcError{
+ Code: JsonRpcErrorCodeInternalError,
+ Message: JsonRpcErrorInternalError.Message,
+ Data: fmt.Sprintf("plugin [%s] not running (state: [%s])", p.Name, p.State()),
+ }
+ return
+ }
+
+ value, ok := p.rpcMethods.Load(method)
+ if !ok {
+ rpcError = &JsonRpcError{
+ Code: JsonRpcErrorCodeMethodNotFound,
+ Message: JsonRpcErrorMethodNotFound.Message,
+ Data: fmt.Sprintf("method [%s] not found in plugin [%s]", method, p.Name),
+ }
+ return
+ }
+
+ rpcMethod, ok := value.(*RpcMethod)
+ if !ok {
+ rpcError = &JsonRpcError{
+ Code: JsonRpcErrorCodeInternalError,
+ Message: JsonRpcErrorInternalError.Message,
+ Data: fmt.Sprintf("invalid method type for [%s]", method),
+ }
+ return
+ }
+
+ done := make(chan *TaskResult, 1)
+
+ p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ rpcParams := []goja.Value{}
+ jsParams := rt.ToValue(params)
+ if isJsArray(rt, jsParams) {
+ // If params is an array, convert to []goja.Value for variadic JS function calls.
+ rt.ForOf(jsParams, func(cur goja.Value) bool {
+ rpcParams = append(rpcParams, cur)
+ return true
+ })
+ } else if !goja.IsUndefined(jsParams) && !goja.IsNull(jsParams) {
+ // If params is not an array but is defined, pass as single argument.
+ rpcParams = append(rpcParams, jsParams)
+ } else {
+ // If params is undefined or null, pass no arguments.
+ }
+
+ invokeFunction(func(_ *goja.Runtime, result *CallResult) {
+ done <- result.TaskResult()
+ }, rt, true, rpcMethod.Method, rt.GlobalObject(), rpcParams...)
+ return
+ }, nil)
+
+ result := <-done
+ if result.err != nil {
+ rpcError = &JsonRpcError{
+ Code: JsonRpcErrorCodeInternalError,
+ Message: JsonRpcErrorInternalError.Message,
+ Data: fmt.Sprintf("error invoking method %q: %v", method, result.err),
+ }
+ return
+ }
+
+ rpcResult = result.value
+ return
+}
+
+// TrackRpcSocket adds a RPC WebSocket connection to the plugin's tracked list.
+func (p *KernelPlugin) TrackRpcSocket(conn *gws.Conn) {
+ if conn == nil {
+ return
+ }
+ p.socketsMu.Lock()
+ defer p.socketsMu.Unlock()
+ p.sockets[conn] = true
+}
+
+// UntrackRpcSocket removes a gws WebSocket connection from the plugin's tracked list.
+func (p *KernelPlugin) UntrackRpcSocket(conn *gws.Conn) {
+ if conn == nil {
+ return
+ }
+ p.socketsMu.Lock()
+ defer p.socketsMu.Unlock()
+ delete(p.sockets, conn)
+}
+
+// invokeHook calls a lifecycle hook (e.g. onload) if it exists, awaiting if it returns a Promise.
+func (p *KernelPlugin) invokeHook(name string) {
+ var err error
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("panic during lifecycle hook invocation: %v", r)
+ }
+
+ if err != nil {
+ logging.LogErrorf("[plugin:%s] lifecycle hook [%q] error: %v", p.Name, name, err)
+ }
+ }()
+
+ done := make(chan TaskResult, 1)
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (_ any, err error) {
+ lifecycle, err := getJsContextValue(rt, []any{"siyuan", "plugin", "lifecycle"})
+ if err != nil {
+ return
+ }
+ if lifecycle == nil {
+ err = fmt.Errorf("globalThis.siyuan.plugin.lifecycle not found")
+ return
+ }
+
+ pluginObj := lifecycle.ToObject(rt)
+ if pluginObj == nil {
+ err = fmt.Errorf("globalThis.siyuan.plugin.lifecycle is not an object")
+ return
+ }
+
+ hookValue := pluginObj.Get(name)
+ hook, ok := goja.AssertFunction(hookValue)
+ if !ok {
+ err = fmt.Errorf("globalThis.siyuan.plugin.lifecycle.%s not bound to a function", name)
+ return
+ }
+
+ invokeFunction(func(_ *goja.Runtime, result *CallResult) {
+ done <- *result.TaskResult()
+ }, rt, true, hook, lifecycle)
+ return
+ }, func(_ *goja.Runtime, _ any, err error) {
+ if err != nil {
+ done <- TaskResult{err: err}
+ }
+ })
+ if runErr != nil {
+ done <- TaskResult{err: runErr}
+ }
+
+ result := <-done
+ if result.err != nil {
+ err = result.err
+ }
+}
+
+// handleHttpRequest dispatches an HTTP request to the plugin's JS handler and returns the response.
+func (p *KernelPlugin) handleHttpRequest(c *gin.Context, request *Request, scope AccessScope) (response *HttpResponse, err error) {
+ type handleResult FunctionResult[*HttpResponse]
+ done := make(chan *handleResult, 1)
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (_ any, err error) {
+ handler, handlerObj, getHandlerErr := getRequestHandler(rt, scope, RequestTypeHTTP)
+ if getHandlerErr != nil {
+ err = getHandlerErr
+ return
+ }
+
+ jsRequest, convertErr := requestGoToJs(p, rt, request)
+ if convertErr != nil {
+ err = convertErr
+ return
+ }
+
+ invokeFunction(func(rt *goja.Runtime, result *CallResult) {
+ if result.Error != nil {
+ done <- &handleResult{Error: result.Error}
+ return
+ }
+
+ responseObj := result.Value.ToObject(rt)
+ if responseObj == nil {
+ done <- &handleResult{Error: fmt.Errorf("handler did not return an object")}
+ return
+ }
+
+ // convert response.body?.raw?.data from (string | Buffer | ArrayBuffer) to []byte
+ var raw *[]byte
+ if bodyValue := responseObj.Get("body"); isJsValueNotNull(bodyValue) {
+ // response.body
+ if bodyObj := bodyValue.ToObject(rt); bodyObj != nil {
+ if rawValue := bodyObj.Get("raw"); isJsValueNotNull(rawValue) {
+ // response.body.raw
+ if rawObj := rawValue.ToObject(rt); rawObj != nil {
+ if dataValue := rawObj.Get("data"); isJsValueNotNull(dataValue) {
+ // response.body.raw.data
+ dataBytes, convertErr := jsValueToBytes(rt, dataValue)
+ if convertErr == nil {
+ raw = &dataBytes
+ rawObj.Set("data", goja.Null())
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // ❌ panic: invalid memory address or nil pointer dereference
+ // response := HttpResponse{}
+ // if err := rt.ExportTo(responseObj, &response); err != nil {
+ // done <- &ServerHandlerResult{Error: fmt.Errorf("invalid response format: %v", err)}
+ // return
+ // }
+
+ resultJson, marshalErr := responseObj.MarshalJSON()
+ if marshalErr != nil {
+ done <- &handleResult{Error: marshalErr}
+ return
+ }
+
+ response := HttpResponse{}
+ if unmarshalErr := json.Unmarshal(resultJson, &response); unmarshalErr != nil {
+ done <- &handleResult{Error: fmt.Errorf("invalid response format: %v", unmarshalErr)}
+ return
+ }
+
+ if raw != nil && response.Body != nil && response.Body.Raw != nil {
+ response.Body.Raw.Data = *raw
+ }
+
+ done <- &handleResult{Value: &response}
+ }, rt, true, handler, handlerObj, jsRequest)
+ return
+ }, func(_ *goja.Runtime, _ any, err error) {
+ if err != nil {
+ done <- &handleResult{Error: err}
+ }
+ })
+ if runErr != nil {
+ done <- &handleResult{Error: runErr}
+ }
+
+ select {
+ case result := <-done:
+ if result.Error != nil {
+ err = result.Error
+ } else {
+ response = result.Value
+ }
+ case <-c.Request.Context().Done():
+ err = c.Request.Context().Err()
+ }
+ return
+}
+
+func (p *KernelPlugin) handleWebSocketRequest(c *gin.Context, request *Request, scope AccessScope) (err error) {
+ done := make(chan error, 1)
+ h := &WsEventHandler{p: p}
+ upgrader := gws.NewUpgrader(h, &gws.ServerOption{})
+
+ socket, upgradeErr := upgrader.Upgrade(c.Writer, c.Request)
+ if upgradeErr != nil {
+ err = upgradeErr
+ return
+ }
+
+ ctx, cancel := context.WithCancel(p.context)
+
+ var openOnce sync.Once
+ var closeOnce sync.Once
+
+ doOpen := func() {
+ go openOnce.Do(func() {
+ socket.ReadLoop()
+ cancel()
+ })
+ }
+
+ doClose := func() {
+ closeOnce.Do(func() {
+ socket.NetConn().Close()
+ cancel()
+ })
+ }
+ defer doClose()
+
+ var readyState atomic.Int64
+ var bufferedAmount atomic.Int64
+ readyState.Store(int64(WebSocketReadyStateConnecting))
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (_ any, err error) {
+ handler, handlerObj, getHandlerErr := getRequestHandler(rt, scope, RequestTypeWS)
+ if getHandlerErr != nil {
+ err = getHandlerErr
+ return
+ }
+
+ jsRequest, convertErr := requestGoToJs(p, rt, request)
+ if convertErr != nil {
+ err = convertErr
+ return
+ }
+
+ jsRequestObj := jsRequest.ToObject(rt)
+ if jsRequestObj == nil {
+ err = fmt.Errorf("failed to convert request value to object")
+ return
+ }
+
+ port := rt.NewObject()
+
+ invokePortHook := func(_ *goja.Runtime, name string, args ...goja.Value) {
+ hook := port.Get(name)
+ if fn, ok := goja.AssertFunction(hook); ok {
+ if _, callErr := fn(port, args...); callErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port hook %q: %v", p.Name, name, callErr)
+ }
+ }
+ }
+
+ setProtocol := func(rt *goja.Runtime, protocol string) {
+ port.Set("protocol", rt.ToValue(protocol))
+ }
+
+ setPortReadyState := func(rt *goja.Runtime, state WebSocketState) {
+ readyState.Store(int64(state))
+ port.Set("readyState", rt.ToValue(state))
+ }
+
+ updatePortBufferedAmount := func(rt *goja.Runtime, delta int) {
+ bufferedAmount.Add(int64(delta))
+ port.Set("bufferedAmount", rt.ToValue(bufferedAmount.Load()))
+ }
+
+ manager := &WsManager{
+ BufferedAmount: &bufferedAmount,
+
+ InvokeHook: invokePortHook,
+ SetProtocol: setProtocol,
+ SetReadyState: setPortReadyState,
+ }
+
+ h.BindOnOpen(manager)
+ h.BindOnClose(manager)
+ h.BindOnPing(manager)
+ h.BindOnPong(manager)
+ h.BindOnMessage(manager)
+
+ port_open := rt.ToValue(func(openCall goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ openPromise, openResolve, openReject := rt.NewPromise()
+
+ openRunErr := p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ doOpen()
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := openResolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.open resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := openReject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.open reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if openRunErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.open worker run: %v", p.Name, openRunErr)
+ }
+
+ return rt.ToValue(openPromise)
+ })
+
+ port_send := rt.ToValue(func(sendCall goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ sendPromise, sendResolve, sendReject := rt.NewPromise()
+
+ sendRunErr := p.worker.Run(func(rt *goja.Runtime) (_ any, err error) {
+ var messageData []byte
+ var opcode gws.Opcode
+ if len(sendCall.Arguments) >= 1 {
+ data := sendCall.Argument(0)
+ if arrayBuffer, ok := data.Export().(goja.ArrayBuffer); ok {
+ opcode = gws.OpcodeBinary
+ b := arrayBuffer.Bytes()
+ messageData = make([]byte, len(b))
+ copy(messageData, b) // ArrayBuffer.Bytes() points into JS engine memory; copy before async send
+ } else {
+ opcode = gws.OpcodeText
+ messageData = []byte(data.String())
+ }
+ }
+
+ state := WebSocketState(readyState.Load())
+ if state == WebSocketReadyStateClosing || state == WebSocketReadyStateClosed {
+ err = fmt.Errorf("WebSocket is not open (state: %d)", state)
+ return
+ }
+
+ updatePortBufferedAmount(rt, len(messageData))
+ socket.WriteAsync(opcode, messageData, func(writeErr error) {
+ p.worker.Run(func(rt *goja.Runtime) (_ any, err error) {
+ if writeErr == nil {
+ updatePortBufferedAmount(rt, -len(messageData))
+ } else {
+ err = writeErr
+ }
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := sendResolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.send resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := sendReject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.send reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ })
+ return
+ }, func(rt *goja.Runtime, _ any, err error) {
+ if !lo.IsNil(err) {
+ if rejectErr := sendReject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.send reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if sendRunErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.send worker run: %v", p.Name, sendRunErr)
+ }
+
+ return rt.ToValue(sendPromise)
+ })
+
+ port_ping := rt.ToValue(func(pingCall goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ pingPromise, pingResolve, pingReject := rt.NewPromise()
+
+ pingRunErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ var pingData string
+ if len(pingCall.Arguments) > 0 && !goja.IsUndefined(pingCall.Argument(0)) {
+ pingData = pingCall.Argument(0).String()
+ }
+ err = socket.WritePing([]byte(pingData))
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := pingResolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.ping resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := pingReject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.ping reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if pingRunErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.ping worker run: %v", p.Name, pingRunErr)
+ }
+
+ return rt.ToValue(pingPromise)
+ })
+
+ port_pong := rt.ToValue(func(pongCall goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ pongPromise, pongResolve, pongReject := rt.NewPromise()
+
+ pongRunErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ var pongData string
+ if len(pongCall.Arguments) > 0 && !goja.IsUndefined(pongCall.Argument(0)) {
+ pongData = pongCall.Argument(0).String()
+ }
+ err = socket.WritePong([]byte(pongData))
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := pongResolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.pong resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := pongReject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.pong reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if pongRunErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.pong worker run: %v", p.Name, pongRunErr)
+ }
+
+ return rt.ToValue(pongPromise)
+ })
+
+ port_close := rt.ToValue(func(closeCall goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ closePromise, closeResolve, closeReject := rt.NewPromise()
+
+ closeRunErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ code := uint16(1000)
+ var reason []byte
+ if isJsValueNotNull(closeCall.Argument(0)) {
+ code = uint16(closeCall.Argument(0).ToInteger())
+ }
+ if isJsValueNotNull(closeCall.Argument(1)) {
+ reason = []byte(closeCall.Argument(1).String())
+ }
+ setPortReadyState(rt, WebSocketReadyStateClosing)
+ err = socket.WriteClose(code, reason)
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := closeResolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.close resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := closeReject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.close reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if closeRunErr != nil {
+ logging.LogErrorf("[plugin:%s] ws server port.close worker run: %v", p.Name, closeRunErr)
+ }
+
+ return rt.ToValue(closePromise)
+ })
+
+ lo.Must0(port.Set("binaryType", rt.ToValue("arraybuffer")))
+ lo.Must0(port.Set("bufferedAmount", rt.ToValue(bufferedAmount.Load())))
+ lo.Must0(port.Set("protocol", rt.ToValue("")))
+ lo.Must0(port.Set("readyState", rt.ToValue(readyState.Load())))
+
+ lo.Must0(port.Set("onopen", goja.Null()))
+ lo.Must0(port.Set("onmessage", goja.Null()))
+ lo.Must0(port.Set("onping", goja.Null()))
+ lo.Must0(port.Set("onpong", goja.Null()))
+ lo.Must0(port.Set("onclose", goja.Null()))
+ lo.Must0(port.Set("onerror", goja.Null()))
+
+ lo.Must0(port.Set("open", port_open))
+ lo.Must0(port.Set("send", port_send))
+ lo.Must0(port.Set("ping", port_ping))
+ lo.Must0(port.Set("pong", port_pong))
+ lo.Must0(port.Set("close", port_close))
+
+ lo.Must0(ObjectSeal(rt, port))
+ lo.Must0(jsRequestObj.Set("port", port))
+
+ invokeFunction(func(_ *goja.Runtime, result *CallResult) {
+ if result.Error != nil {
+ // If the handler throws an error, close the connection and return the error.
+ select {
+ case done <- result.Error:
+ case <-ctx.Done():
+ }
+ return
+ }
+ // Auto-open if the handler did not call port.open() explicitly.
+ doOpen()
+ }, rt, true, handler, handlerObj, jsRequest)
+
+ return
+ }, func(_ *goja.Runtime, _ any, err error) {
+ if err != nil {
+ // If there is an error during the worker run (e.g. runtime panic), close the connection and return the error.
+ select {
+ case done <- err:
+ case <-ctx.Done():
+ }
+ }
+ })
+ if runErr != nil {
+ select {
+ case done <- runErr:
+ case <-ctx.Done():
+ }
+ }
+
+ select {
+ case err = <-done:
+ case <-ctx.Done():
+ }
+ return
+}
+
+// handleServerSentEventRequest dispatches an SSE request to the plugin's JS handler and streams events until completion or client disconnect.
+func (p *KernelPlugin) handleServerSentEventRequest(c *gin.Context, request *Request, scope AccessScope) (err error) {
+ type sseEvent struct {
+ name string
+ message any
+ }
+
+ ctx, cancel := context.WithCancel(p.context)
+
+ var closeOnce sync.Once
+ doClose := func() {
+ closeOnce.Do(func() {
+ cancel()
+ })
+ }
+ defer doClose()
+
+ events := chanx.NewUnboundedChan[sseEvent](ctx, 16)
+ done := make(chan error, 1) // using to receive handler error or close signal
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (_ any, err error) {
+ handler, handlerObj, getHandlerErr := getRequestHandler(rt, scope, RequestTypeSSE)
+ if getHandlerErr != nil {
+ err = getHandlerErr
+ return
+ }
+
+ jsRequest, convertErr := requestGoToJs(p, rt, request)
+ if convertErr != nil {
+ err = convertErr
+ return
+ }
+
+ jsRequestObj := jsRequest.ToObject(rt)
+ if jsRequestObj == nil {
+ err = fmt.Errorf("failed to convert request value to object")
+ return
+ }
+
+ port := rt.NewObject()
+
+ invokePortHook := func(name string, args ...goja.Value) {
+ hook := port.Get(name)
+ if fn, ok := goja.AssertFunction(hook); ok {
+ if _, callErr := fn(port, args...); callErr != nil {
+ logging.LogErrorf("[plugin:%s] sse server port hook %q: %v", p.Name, name, callErr)
+ }
+ }
+ }
+
+ port_send := rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ name := call.Argument(0).String()
+ message := call.Argument(1).Export()
+ events.In <- sseEvent{name, message}
+ return goja.Undefined()
+ })
+
+ port_close := rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ doClose()
+ return goja.Undefined()
+ })
+
+ lo.Must0(port.Set("onopen", goja.Null()))
+ lo.Must0(port.Set("onclose", goja.Null()))
+
+ lo.Must0(port.Set("send", port_send))
+ lo.Must0(port.Set("close", port_close))
+
+ lo.Must0(ObjectSeal(rt, port))
+
+ lo.Must0(jsRequestObj.Set("port", port))
+
+ invokeFunction(func(_ *goja.Runtime, result *CallResult) {
+ if result.Error != nil {
+ select {
+ case done <- result.Error:
+ case <-ctx.Done():
+ }
+ return
+ }
+ // Only start the onclose goroutine when the handler succeeds, so that
+ // onclose is never dispatched without a prior onopen.
+ go func() {
+ <-ctx.Done()
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ event := rt.NewObject()
+ event.Set("type", rt.ToValue("close"))
+ invokePortHook("onclose", event)
+ return
+ }, nil)
+ }()
+
+ // Fire onopen first; signal done only after onopen has executed so that
+ // any port.send() calls inside onopen are enqueued before streaming begins.
+ p.worker.Run(func(rt *goja.Runtime) (_ any, _ error) {
+ event := rt.NewObject()
+ event.Set("type", rt.ToValue("open"))
+ invokePortHook("onopen", event)
+ return
+ }, func(_ *goja.Runtime, _ any, err error) {
+ select {
+ case done <- err:
+ case <-ctx.Done():
+ }
+ })
+ }, rt, true, handler, handlerObj, jsRequest)
+
+ return
+ }, func(_ *goja.Runtime, _ any, err error) {
+ if err != nil {
+ select {
+ case done <- err:
+ case <-ctx.Done():
+ }
+ }
+ })
+ if runErr != nil {
+ select {
+ case done <- runErr:
+ case <-ctx.Done():
+ }
+ }
+
+ for {
+ select {
+ case e := <-events.Out:
+ c.SSEvent(e.name, e.message)
+ c.Writer.Flush()
+ case <-ctx.Done():
+ return
+ case <-c.Request.Context().Done():
+ err = c.Request.Context().Err()
+ return
+ case handlerErr := <-done:
+ if handlerErr != nil {
+ err = handlerErr
+ return
+ }
+ // Handler completed successfully; keep streaming until port.close() or client disconnect.
+ }
+ }
+}
diff --git a/kernel/plugin/rpc.go b/kernel/plugin/rpc.go
new file mode 100644
index 0000000000..64c0ef257a
--- /dev/null
+++ b/kernel/plugin/rpc.go
@@ -0,0 +1,503 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "sync"
+
+ "github.com/gin-gonic/gin"
+ "github.com/lxzan/gws"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type JsonRpcErrorCode int
+
+const (
+ JsonRpcVersion = "2.0"
+
+ JsonRpcErrorCodeParseError JsonRpcErrorCode = -32700
+ JsonRpcErrorCodeInvalidRequest JsonRpcErrorCode = -32600
+ JsonRpcErrorCodeMethodNotFound JsonRpcErrorCode = -32601
+ JsonRpcErrorCodeInvalidParams JsonRpcErrorCode = -32602
+ JsonRpcErrorCodeInternalError JsonRpcErrorCode = -32603
+
+ // Server-defined error codes (-32099 to -32000)
+ JsonRpcErrorCodePluginNotLoaded JsonRpcErrorCode = -32001
+ JsonRpcErrorCodePluginNotRunning JsonRpcErrorCode = -32002
+)
+
+var (
+ JsonRpcErrorParseError = &JsonRpcError{Code: JsonRpcErrorCodeParseError, Message: "Parse error"}
+ JsonRpcErrorInvalidRequest = &JsonRpcError{Code: JsonRpcErrorCodeInvalidRequest, Message: "Invalid Request"}
+ JsonRpcErrorMethodNotFound = &JsonRpcError{Code: JsonRpcErrorCodeMethodNotFound, Message: "Method not found"}
+ JsonRpcErrorInvalidParams = &JsonRpcError{Code: JsonRpcErrorCodeInvalidParams, Message: "Invalid params"}
+ JsonRpcErrorInternalError = &JsonRpcError{Code: JsonRpcErrorCodeInternalError, Message: "Internal error"}
+
+ JsonRpcErrorPluginNotLoaded = &JsonRpcError{Code: JsonRpcErrorCodePluginNotLoaded, Message: "Plugin not loaded"}
+ JsonRpcErrorPluginNotRunning = &JsonRpcError{Code: JsonRpcErrorCodePluginNotRunning, Message: "Plugin not running"}
+)
+
+func (e *JsonRpcError) Error() string {
+ return fmt.Sprintf("JSON RPC Error: %d %s", e.Code, e.Message)
+}
+
+// JsonRpcRequest represents a JSON-RPC 2.0 request.
+type JsonRpcRequest struct {
+ JsonRpc string `json:"jsonrpc"`
+ Method string `json:"method"`
+ Params util.Optional[any] `json:"params,omitempty"`
+ ID util.Optional[any] `json:"id,omitempty"`
+}
+
+func (r JsonRpcRequest) MarshalJSON() ([]byte, error) {
+ m := map[string]any{
+ "jsonrpc": r.JsonRpc,
+ "method": r.Method,
+ }
+ if r.Params.Exists {
+ if r.Params.IsNull {
+ m["params"] = nil
+ } else {
+ m["params"] = r.Params.Value
+ }
+ }
+ if r.ID.Exists {
+ if r.ID.IsNull {
+ m["id"] = nil
+ } else {
+ m["id"] = r.ID.Value
+ }
+ }
+ return json.Marshal(m)
+}
+
+func (r *JsonRpcRequest) UnmarshalJSON(data []byte) error {
+ decoder := json.NewDecoder(bytes.NewReader(data))
+ // decoder.DisallowUnknownFields() // Reject unknown fields violates the JSON-RPC spec
+ type JsonRpcRequestObject struct {
+ JsonRpc util.Optional[string] `json:"jsonrpc"`
+ Method util.Optional[string] `json:"method"`
+ Params util.Optional[any] `json:"params"`
+ ID util.Optional[any] `json:"id"`
+ }
+ request := JsonRpcRequestObject{}
+ if err := decoder.Decode(&request); err != nil {
+ return err
+ }
+
+ // Validate jsonrpc field
+ if !request.JsonRpc.Exists {
+ return fmt.Errorf("missing jsonrpc field")
+ }
+ if request.JsonRpc.Value != JsonRpcVersion {
+ return fmt.Errorf("invalid jsonrpc version: %s", request.JsonRpc.Value)
+ }
+
+ // Validate method field
+ if !request.Method.Exists {
+ return fmt.Errorf("missing method field")
+ }
+
+ // Validate id field
+ if !request.ID.Exists {
+ } else if request.ID.IsNull {
+ } else if _, ok := request.ID.Value.(string); ok {
+ } else if _, ok := request.ID.Value.(float64); ok {
+ } else {
+ return fmt.Errorf("invalid id field: must be string, number, null or omitted")
+ }
+
+ r.JsonRpc = request.JsonRpc.Value
+ r.Method = request.Method.Value
+ r.Params = request.Params
+ r.ID = request.ID
+ return nil
+}
+
+// IsNotification returns true if this request is a notification (no ID field).
+func (r *JsonRpcRequest) IsNotification() bool {
+ return r.ID.Exists == false
+}
+
+// Validate validates the JSON-RPC request structure.
+func (r *JsonRpcRequest) Validate() *JsonRpcError {
+ // params is optional, but if present must be either an array (for positional parameters) or an object (for named parameters)
+ if !r.Params.Exists {
+ } else if _, ok := r.Params.Value.([]any); ok {
+ } else if _, ok := r.Params.Value.(map[string]any); ok {
+ } else {
+ return &JsonRpcError{
+ Code: JsonRpcErrorCodeInvalidRequest,
+ Message: JsonRpcErrorInvalidRequest.Message,
+ Data: "Invalid params: must be array or object if present",
+ }
+ }
+
+ // ✅ jsonrpc, method and id fields are validated during unmarshaling, so do not need to validate again here.
+
+ // if r.JsonRpc != JsonRpcVersion {
+ // return JsonRpcErrorInvalidRequest
+ // }
+
+ // if !r.ID.Exists {
+ // } else if r.ID.IsNull {
+ // } else if _, ok := r.ID.Value.(string); ok {
+ // } else if _, ok := r.ID.Value.(float64); ok {
+ // } else {
+ // return JsonRpcErrorInvalidRequest
+ // }
+
+ return nil
+}
+
+// JsonRpcRequestResponse represents a JSON-RPC 2.0 success response.
+// result MUST be present (even if null); error MUST NOT be present.
+type JsonRpcRequestResponse struct {
+ JsonRpc string `json:"jsonrpc"`
+ Result any `json:"result"`
+ ID any `json:"id"`
+}
+
+// JsonRpcErrorResponse represents a JSON-RPC 2.0 error response.
+// error MUST be present; result MUST NOT be present.
+type JsonRpcErrorResponse struct {
+ JsonRpc string `json:"jsonrpc"`
+ Error *JsonRpcError `json:"error"`
+ ID any `json:"id"`
+}
+
+// JsonRpcError represents a JSON-RPC 2.0 error.
+type JsonRpcError struct {
+ Code JsonRpcErrorCode `json:"code"`
+ Message string `json:"message"`
+ Data any `json:"data,omitempty"`
+}
+
+// JsonRpcRequestProcessingResults represents the results of parsing and validating JSON-RPC requests, including any global error and the individual results for each request in a batch.
+type JsonRpcRequestProcessingResults struct {
+ Batch bool // Whether the original request was a batch (array) or single request
+ GlobalError *JsonRpcErrorResponse // If the entire request is invalid
+ Requests []*JsonRpcProcessingRequest
+}
+
+// JsonRpcProcessingRequest represents the result of parsing and validating a single JSON-RPC request, including any error if the request is invalid.
+type JsonRpcProcessingRequest struct {
+ Request *JsonRpcRequest // The parsed request, or nil if the request was invalid
+ Error *JsonRpcErrorResponse // The error if the request was invalid, or nil if the request is valid
+}
+
+// JsonRpcProcessingResponse represents the response to a JSON-RPC request, including either the success response or the error response (but not both).
+// - For notifications, both fields will be nil, indicating that no response should be sent.
+// - For successful requests, Response will be non-nil and Error will be nil.
+// - For failed requests, Error will be non-nil and Response will be nil.
+type JsonRpcProcessingResponse struct {
+ Response *JsonRpcRequestResponse // The success response, or nil if the request was a notification or the response is an error
+ Error *JsonRpcErrorResponse // The error response, or nil if the request was a notification or the response is a success
+}
+
+// JsonRpcResponse returns the appropriate response (either success or error) to be sent back to the client, or nil if this is a notification and no response should be sent.
+func (r *JsonRpcProcessingResponse) JsonRpcResponse() any {
+ if r.Response != nil {
+ return r.Response
+ }
+ if r.Error != nil {
+ return r.Error
+ }
+ return nil
+}
+
+// HandleRpcHttp handles POST /api/plugin/rpc/:name
+// Supports single call, batch call, and notification (no response for notification).
+func HandleRpcHttp(c *gin.Context) {
+ name := util.GetRequestUrlStringParam(c, "name")
+ p := resolveRunningPlugin(c, name, http.StatusOK)
+ if p == nil {
+ return
+ }
+
+ body, err := io.ReadAll(c.Request.Body)
+ if err != nil {
+ c.JSON(http.StatusOK, &JsonRpcErrorResponse{
+ JsonRpc: JsonRpcVersion,
+ Error: &JsonRpcError{
+ Code: JsonRpcErrorCodeInternalError,
+ Message: JsonRpcErrorInternalError.Message,
+ Data: fmt.Sprintf("Failed to read request body: %s", err),
+ },
+ ID: nil,
+ })
+ return
+ }
+
+ results := parseRpcRequests(body)
+ if results.GlobalError != nil {
+ c.JSON(http.StatusOK, results.GlobalError)
+ return
+ }
+
+ responses := p.dispatchRpcRequests(results.Requests)
+
+ if !results.Batch {
+ // Single request - return single response (or empty for notification)
+ if len(responses) > 0 && responses[0] != nil {
+ response := responses[0]
+ if response.Response != nil {
+ c.JSON(http.StatusOK, response.Response)
+ return
+ } else if response.Error != nil {
+ c.JSON(http.StatusOK, response.Error)
+ return
+ }
+ }
+ c.Status(http.StatusNoContent)
+ return
+ }
+
+ // Batch request - filter out nil responses (notifications) and return array
+ filtered := filterRpcResponses(responses)
+
+ if len(filtered) > 0 {
+ c.JSON(http.StatusOK, filtered)
+ } else {
+ // All notifications in batch - send nothing per spec (MUST NOT return empty array)
+ c.Status(http.StatusNoContent)
+ }
+}
+
+// HandleRpcWebSocket handles GET /ws/plugin/rpc/:name
+// Supports single call, batch call, notification, and server push notifications.
+func HandleRpcWebSocket(c *gin.Context) {
+ name := util.GetRequestUrlStringParam(c, "name")
+ p := resolveRunningPlugin(c, name, http.StatusNotFound)
+ if p == nil {
+ return
+ }
+
+ if c.IsWebsocket() == false {
+ c.String(http.StatusBadRequest, "This endpoint only accepts WebSocket connections")
+ return
+ }
+
+ h := &WsEventHandler{p: p}
+
+ h.onMessage = func(socket *gws.Conn, message *gws.Message) {
+ defer message.Close()
+
+ results := parseRpcRequests(message.Bytes())
+ if results.GlobalError != nil {
+ if respBytes, marshalErr := json.Marshal(results.GlobalError); marshalErr == nil {
+ socket.WriteAsync(gws.OpcodeText, respBytes, func(err error) {
+ if err != nil {
+ logging.LogWarnf("[plugin:%s] RPC WebSocket response write failed: %s", name, err)
+ }
+ })
+ } else {
+ logging.LogErrorf("[plugin:%s] RPC WebSocket response marshal failed: %s", name, marshalErr)
+ }
+ return
+ }
+
+ responses := p.dispatchRpcRequests(results.Requests)
+
+ var responseBytes []byte
+ var marshalErr error
+ var needToSend bool
+
+ if !results.Batch {
+ if len(responses) > 0 && responses[0] != nil {
+ if response := responses[0].JsonRpcResponse(); response != nil {
+ needToSend = true
+ responseBytes, marshalErr = json.Marshal(response)
+ }
+ }
+ } else {
+ filtered := filterRpcResponses(responses)
+ if len(filtered) > 0 {
+ needToSend = true
+ responseBytes, marshalErr = json.Marshal(filtered)
+ }
+ }
+
+ if needToSend {
+ if marshalErr != nil {
+ logging.LogErrorf("[plugin:%s] RPC response marshal failed: %s", name, marshalErr)
+ return
+ }
+ socket.WriteAsync(gws.OpcodeText, responseBytes, func(err error) {
+ if err != nil {
+ logging.LogWarnf("[plugin:%s] RPC WebSocket response write failed: %s", name, err)
+ }
+ })
+ }
+ }
+
+ upgrader := gws.NewUpgrader(h, &gws.ServerOption{})
+ socket, err := upgrader.Upgrade(c.Writer, c.Request)
+ if err != nil {
+ logging.LogErrorf("[plugin:%s] RPC WebSocket upgrade failed: %s", name, err)
+ return
+ }
+
+ ctx, cancel := context.WithCancel(p.context)
+
+ var openOnce sync.Once
+ var closeOnce sync.Once
+
+ doOpen := func() {
+ go openOnce.Do(func() {
+ p.TrackRpcSocket(socket)
+ socket.ReadLoop()
+ cancel()
+ })
+ }
+
+ doClose := func() {
+ closeOnce.Do(func() {
+ p.UntrackRpcSocket(socket)
+ socket.NetConn().Close()
+ cancel()
+ })
+ }
+
+ defer doClose()
+ doOpen()
+ <-ctx.Done()
+}
+
+// resolveRunningPlugin looks up the plugin by name and writes an error response if it is
+// not found (-32001) or not running (-32002). Returns nil when the caller should abort.
+func resolveRunningPlugin(c *gin.Context, name string, errStatus int) *KernelPlugin {
+ p := GetManager().GetPlugin(name)
+ if p == nil {
+ c.JSON(errStatus, &JsonRpcErrorResponse{
+ JsonRpc: JsonRpcVersion,
+ Error: JsonRpcErrorPluginNotLoaded,
+ })
+ return nil
+ }
+ if p.State() != PluginStateRunning {
+ c.JSON(errStatus, &JsonRpcErrorResponse{
+ JsonRpc: JsonRpcVersion,
+ Error: JsonRpcErrorPluginNotRunning,
+ })
+ return nil
+ }
+ return p
+}
+
+// parseRpcRequest parses a single JSON-RPC request from the given body. The body must be a JSON object.
+func parseRpcRequest(body []byte) (parsedRequest JsonRpcProcessingRequest) {
+ var request JsonRpcRequest
+ if !json.Valid(body) {
+ // Invalid JSON
+ parsedRequest.Error = &JsonRpcErrorResponse{
+ JsonRpc: JsonRpcVersion,
+ Error: &JsonRpcError{
+ Code: JsonRpcErrorCodeParseError,
+ Message: JsonRpcErrorParseError.Message,
+ Data: "RPC request is not valid JSON",
+ },
+ ID: nil,
+ }
+ return
+ }
+ if err := json.Unmarshal(body, &request); err != nil {
+ // Invalid request structure
+ parsedRequest.Error = &JsonRpcErrorResponse{
+ JsonRpc: JsonRpcVersion,
+ Error: &JsonRpcError{
+ Code: JsonRpcErrorCodeInvalidRequest,
+ Message: JsonRpcErrorInvalidRequest.Message,
+ Data: fmt.Sprintf("RPC request is not a valid JSON-RPC object: %s", err),
+ },
+ ID: nil,
+ }
+ return
+ }
+ parsedRequest.Request = &request
+ return
+}
+
+// parseRpcRequests parses the given body into one or more JSON-RPC requests, handling both single and batch requests.
+func parseRpcRequests(body []byte) (results JsonRpcRequestProcessingResults) {
+ if !json.Valid(body) {
+ // Invalid JSON
+ results.GlobalError = &JsonRpcErrorResponse{
+ JsonRpc: JsonRpcVersion,
+ Error: &JsonRpcError{
+ Code: JsonRpcErrorCodeParseError,
+ Message: JsonRpcErrorParseError.Message,
+ Data: "RPC request is not valid JSON",
+ },
+ ID: nil,
+ }
+ return
+ }
+
+ var jsonArray []json.RawMessage
+ if err := json.Unmarshal(body, &jsonArray); err != nil {
+ // single request
+ request := parseRpcRequest(body)
+ results.Requests = append(results.Requests, &request)
+ return
+ } else {
+ // batch request
+ if len(jsonArray) == 0 {
+ // per spec, an empty array is invalid
+ results.GlobalError = &JsonRpcErrorResponse{
+ JsonRpc: JsonRpcVersion,
+ Error: &JsonRpcError{
+ Code: JsonRpcErrorCodeInvalidRequest,
+ Message: JsonRpcErrorInvalidRequest.Message,
+ Data: "RPC request is not allowed to be an empty array",
+ },
+ ID: nil,
+ }
+ return
+ }
+
+ results.Batch = true
+ results.Requests = make([]*JsonRpcProcessingRequest, len(jsonArray))
+ for i, raw := range jsonArray {
+ request := parseRpcRequest(raw)
+ results.Requests[i] = &request
+ }
+ }
+ return
+}
+
+// filterRpcResponses filters out nil responses (for notifications) and extracts the actual response objects for non-nil responses.
+func filterRpcResponses(responses []*JsonRpcProcessingResponse) []any {
+ filtered := make([]any, 0, len(responses))
+ for _, response := range responses {
+ if response != nil {
+ if response.Response != nil {
+ filtered = append(filtered, response.Response)
+ } else if response.Error != nil {
+ filtered = append(filtered, response.Error)
+ }
+ }
+ }
+ return filtered
+}
diff --git a/kernel/plugin/sandbox.go b/kernel/plugin/sandbox.go
new file mode 100644
index 0000000000..a975c2cedb
--- /dev/null
+++ b/kernel/plugin/sandbox.go
@@ -0,0 +1,529 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "encoding/json"
+ "fmt"
+ "strconv"
+ "time"
+
+ "github.com/dop251/goja"
+ "github.com/dop251/goja_nodejs/buffer"
+ "github.com/dop251/goja_nodejs/console"
+ "github.com/dop251/goja_nodejs/require"
+ "github.com/dop251/goja_nodejs/url"
+ "github.com/imroc/req/v3"
+ "github.com/samber/lo"
+ "github.com/siyuan-note/logging"
+)
+
+type WebSocketState int64
+
+const (
+ WebSocketReadyStateConnecting WebSocketState = iota
+ WebSocketReadyStateOpen
+ WebSocketReadyStateClosing
+ WebSocketReadyStateClosed
+)
+
+type EventSourceState int64
+
+const (
+ EventSourceConnecting EventSourceState = iota
+ EventSourceOpen
+ EventSourceClosed
+)
+
+var (
+ httpClient *req.Client = req.C().SetTimeout(time.Minute)
+)
+
+type FunctionResult[T any] struct {
+ Value T
+ Error error
+}
+
+type CallResult FunctionResult[goja.Value]
+
+func (r *CallResult) TaskResult() *TaskResult {
+ if r.Error != nil {
+ return &TaskResult{err: r.Error}
+ }
+ return &TaskResult{value: r.Value.Export()}
+}
+
+// EnableExtendModules registers extended modules (e.g. url, buffer) to the plugin's goja runtime.
+func EnableExtendModules(p *KernelPlugin, rt *goja.Runtime) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("failed to enable extend modules: %v", r)
+ }
+ }()
+
+ registry := require.NewRegistry()
+
+ registry.Enable(rt)
+ registry.RegisterNativeModule(
+ console.ModuleName,
+ console.RequireWithPrinter(&Printer{name: p.Name}),
+ )
+
+ url.Enable(rt)
+ buffer.Enable(rt)
+ console.Enable(rt)
+ return
+}
+
+// EnableSiyuanModule injects all siyuan.* APIs into the plugin's goja global context.
+func EnableSiyuanModule(p *KernelPlugin, rt *goja.Runtime) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("failed to inject global context: %v", r)
+ }
+ }()
+
+ siyuan := rt.NewObject()
+
+ lo.Must0(injectPlugin(p, rt, siyuan))
+ lo.Must0(injectEvent(p, rt, siyuan))
+ lo.Must0(injectLogger(p, rt, siyuan))
+ lo.Must0(injectStorage(p, rt, siyuan))
+ lo.Must0(injectRpc(p, rt, siyuan))
+ lo.Must0(injectClient(p, rt, siyuan))
+ lo.Must0(injectServer(p, rt, siyuan))
+
+ lo.Must0(ObjectFreeze(rt, siyuan))
+
+ lo.Must0(rt.GlobalObject().Set("siyuan", siyuan))
+ return
+}
+
+// ObjectFreeze calls Object.freeze() on the given goja object.
+func ObjectFreeze(rt *goja.Runtime, obj *goja.Object) error {
+ Object := rt.GlobalObject().Get("Object").ToObject(rt)
+ if Object == nil {
+ return fmt.Errorf("globalThis.Object is not an object")
+ }
+
+ freeze, ok := goja.AssertFunction(Object.Get("freeze"))
+ if !ok {
+ return fmt.Errorf("globalThis.Object.freeze is not a function")
+ }
+
+ _, err := freeze(Object, obj)
+ return err
+}
+
+// ObjectSeal calls Object.seal() on the given goja object.
+func ObjectSeal(rt *goja.Runtime, obj *goja.Object) error {
+ Object := rt.GlobalObject().Get("Object").ToObject(rt)
+ if Object == nil {
+ return fmt.Errorf("globalThis.Object is not an object")
+ }
+
+ seal, ok := goja.AssertFunction(Object.Get("seal"))
+ if !ok {
+ return fmt.Errorf("globalThis.Object.seal is not a function")
+ }
+
+ _, err := seal(Object, obj)
+ return err
+}
+
+// ObjectSetDataMethods attaches text(), json(), buffer() and arrayBuffer() methods to a JS object,
+// each returning a Promise that resolves with the corresponding representation of data.
+func ObjectSetDataMethods(p *KernelPlugin, rt *goja.Runtime, object *goja.Object, data []byte) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("ObjectSetDataMethods: %v", r)
+ }
+ }()
+
+ lo.Must0(object.Set("text", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ result = string(data)
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] data.text() resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] data.text() reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] text worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ })))
+ lo.Must0(object.Set("json", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ var value any
+ if unmarshalErr := json.Unmarshal(data, &value); unmarshalErr != nil {
+ err = unmarshalErr
+ return
+ }
+
+ result = rt.ToValue(value)
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(result); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] data.json() resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] data.json() reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] json worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ })))
+ lo.Must0(object.Set("buffer", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ result = buffer.WrapBytes(rt, data)
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(rt.ToValue(result)); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] data.buffer() resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] data.buffer() reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] buffer worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ })))
+ lo.Must0(object.Set("arrayBuffer", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ promise, resolve, reject := rt.NewPromise()
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ result = rt.NewArrayBuffer(data)
+ return
+ }, func(rt *goja.Runtime, result any, err error) {
+ if lo.IsNil(err) {
+ if resolveErr := resolve(rt.ToValue(result)); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] data.arrayBuffer() resolve: %v", p.Name, resolveErr)
+ }
+ } else {
+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] data.arrayBuffer() reject: %v", p.Name, rejectErr)
+ }
+ }
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] arrayBuffer worker run: %v", p.Name, runErr)
+ }
+
+ return rt.ToValue(promise)
+ })))
+ return
+}
+
+// NewDataObject creates a new JS object with text(), json(), buffer() and arrayBuffer() methods for the given data.
+func NewDataObject(p *KernelPlugin, rt *goja.Runtime, data []byte) (*goja.Object, error) {
+ obj := rt.NewObject()
+ if err := ObjectSetDataMethods(p, rt, obj, data); err != nil {
+ return nil, err
+ }
+ return obj, nil
+}
+
+// getJsContextValue safely retrieves a nested value from the plugin's JS context, returning nil if any step fails.
+func getJsContextValue(rt *goja.Runtime, paths []any) (value goja.Value, err error) {
+ var cursor goja.Value = rt.GlobalObject()
+ var path string = "globalThis"
+
+ for _, key := range paths {
+ if cursor == nil {
+ err = fmt.Errorf("path %v: value is nil", key)
+ return
+ }
+
+ if goja.IsUndefined(cursor) || goja.IsNull(cursor) {
+ err = fmt.Errorf("path %v: value is %s", key, cursor.String())
+ return
+ }
+
+ obj := cursor.ToObject(rt)
+ if obj == nil {
+ err = fmt.Errorf("path %v: expected object, got %T", key, cursor)
+ return
+ }
+
+ switch k := key.(type) {
+ case string:
+ cursor = obj.Get(k)
+ path = fmt.Sprintf("%s.%s", path, k)
+ case int:
+ cursor = obj.Get(strconv.Itoa(k))
+ path = fmt.Sprintf("%s[%d]", path, k)
+ default:
+ err = fmt.Errorf("unsupported path type: %T", key)
+ return
+ }
+ }
+ value = cursor
+ return
+}
+
+// dispatchEvent calls the globalThis.siyuan.event.on hook with the given event object.
+func dispatchEvent(p *KernelPlugin, rt *goja.Runtime, e any) (async bool, err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("goja panic during dispatchEvent: %v", r)
+ }
+ }()
+
+ event, err := getJsContextValue(rt, []any{"siyuan", "event"})
+ if err != nil {
+ return
+ }
+ if event == nil {
+ err = fmt.Errorf("globalThis.siyuan.event not found")
+ return
+ }
+ if goja.IsUndefined(event) || goja.IsNull(event) {
+ err = fmt.Errorf("globalThis.siyuan.event is %s", event.String())
+ return
+ }
+
+ eventObj := event.ToObject(rt)
+ if eventObj == nil {
+ err = fmt.Errorf("globalThis.siyuan.event is not an object")
+ return
+ }
+
+ handlerValue := eventObj.Get("handler")
+ handler, ok := goja.AssertFunction(handlerValue)
+ if !ok {
+ return
+ }
+
+ eventJs := rt.ToValue(e)
+ invokeResult, invokeErr := handler(event, eventJs)
+ if invokeErr != nil {
+ err = invokeErr
+ return
+ }
+
+ async = isJsPromise(invokeResult)
+ return
+}
+
+// invokeFunction calls a goja.Callable with the given this and arguments, handling both synchronous return values and Promises.
+func invokeFunction(callback func(rt *goja.Runtime, result *CallResult), rt *goja.Runtime, async bool, fn goja.Callable, this goja.Value, args ...goja.Value) {
+ resultJs, invokeErr := fn(this, args...)
+ if callback == nil {
+ return
+ }
+
+ if invokeErr != nil {
+ callback(rt, &CallResult{Error: invokeErr})
+ return
+ }
+
+ result := resultJs.Export()
+ if isGoPromise(result) {
+ if !async {
+ panic(fmt.Errorf("synchronous function returned a Promise"))
+ }
+ resultObj := resultJs.ToObject(rt)
+ if resultObj == nil {
+ callback(rt, &CallResult{Error: fmt.Errorf("expected promise object, got %T", result)})
+ }
+
+ thenValue := resultObj.Get("then")
+ then, ok := goja.AssertFunction(thenValue)
+ if !ok {
+ callback(rt, &CallResult{Error: fmt.Errorf("'promise.then property is not a function")})
+ }
+
+ then(resultObj, rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) {
+ // ⚠️ call.Arguments always is an empty array.
+ promise, ok := result.(*goja.Promise)
+ if ok {
+ callback(rt, &CallResult{Value: promise.Result()})
+ } else {
+ callback(rt, &CallResult{Value: resultJs})
+ }
+ }), rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) {
+ callback(rt, &CallResult{Error: fmt.Errorf("promise rejected: %v", call.Argument(0).Export())})
+ }))
+ } else {
+ callback(rt, &CallResult{Value: resultJs})
+ }
+}
+
+// isJsPromise checks if a goja.Value is a JavaScript Promise.
+func isJsPromise(jsValue goja.Value) bool {
+ if jsValue == nil {
+ return false
+ }
+
+ goValue := jsValue.Export()
+ return isGoPromise(goValue)
+}
+
+// isGoPromise checks if a Go value is a *goja.Promise.
+func isGoPromise(goValue any) bool {
+ if goValue == nil {
+ return false
+ }
+
+ _, ok := goValue.(*goja.Promise)
+ return ok
+}
+
+// isJsArray checks if a goja.Value is a JavaScript Array.
+func isJsArray(rt *goja.Runtime, jsValue goja.Value) bool {
+ if jsValue == nil {
+ return false
+ }
+
+ if goja.IsUndefined(jsValue) || goja.IsNull(jsValue) {
+ return false
+ }
+
+ jsObject := jsValue.ToObject(rt)
+ return isJsObjectArray(jsObject)
+}
+
+// isJsObjectArray checks if a goja.Object is a JavaScript Array by inspecting its class name.
+func isJsObjectArray(jsObject *goja.Object) bool {
+ if jsObject == nil {
+ return false
+ }
+
+ switch jsObject.ClassName() {
+ case "Array":
+ return true
+ default:
+ return false
+ }
+}
+
+// isJsValueNotUndefined checks if a goja.Value is not nil and not undefined.
+func isJsValueNotUndefined(jsValue goja.Value) bool {
+ return jsValue != nil && !goja.IsUndefined(jsValue)
+}
+
+// isJsValueNotNull checks if a goja.Value is not nil, undefined or null.
+func isJsValueNotNull(jsValue goja.Value) bool {
+ return isJsValueNotUndefined(jsValue) && !goja.IsNull(jsValue)
+}
+
+// jsValueToBytes attempts to convert a goja.Value to a byte slice, supporting string, Buffer, ArrayBuffer, etc.
+func jsValueToBytes(rt *goja.Runtime, value goja.Value) (data []byte, err error) {
+ if goValue := value.Export(); goValue != nil {
+ switch d := goValue.(type) {
+ case string: // string
+ data = []byte(d)
+ case []byte: // Buffer
+ data = d
+ case goja.ArrayBuffer: // ArrayBuffer
+ data = d.Bytes()
+ case buffer.Buffer: // ?
+ data = buffer.Bytes(rt, value)
+ default:
+ err = fmt.Errorf("unsupported data type: %T", goValue)
+ }
+ return
+ }
+ err = fmt.Errorf("js value cannot be exported to a valid Go value")
+ return
+}
+
+// getRequestHandler retrieves the handler function and its containing object for a given scope and request type from the plugin's JS context.
+func getRequestHandler(rt *goja.Runtime, scope AccessScope, requestType RequestType) (handler goja.Callable, handlerObj *goja.Object, err error) {
+ // Get handler object: siyuan.server[scope][requestType]
+ handlerObjValue, getObjErr := getJsContextValue(rt, []any{"siyuan", "server", string(scope), string(requestType)})
+ if getObjErr != nil {
+ err = getObjErr
+ return
+ }
+
+ handlerObj = handlerObjValue.ToObject(rt)
+ if handlerObj == nil {
+ err = fmt.Errorf("globalThis.siyuan.server[%s][%s] is not an object", scope, requestType)
+ return
+ }
+
+ // Get handler: siyuan.server[scope][requestType].handler
+ handlerValue := handlerObj.Get("handler")
+ if !isJsValueNotNull(handlerValue) {
+ err = fmt.Errorf("siyuan.server[%s][%s].handler is not set", scope, requestType)
+ return
+ }
+
+ handler, ok := goja.AssertFunction(handlerValue)
+ if !ok {
+ err = fmt.Errorf("siyuan.server[%s][%s].handler is not a function", scope, requestType)
+ return
+ }
+
+ return
+}
+
+// requestGoToJs converts a Go Request to a JavaScript value.
+func requestGoToJs(p *KernelPlugin, rt *goja.Runtime, request *Request) (jsRequest goja.Value, err error) {
+ // convert body raw data to js object
+ if request.Request.Body.Data != nil {
+ request.Request.Body.Data, err = NewDataObject(p, rt, *request.Request.Body.Data.(*[]byte))
+ if err != nil {
+ return
+ }
+ }
+
+ // convert body form files data to js object
+ if request.Request.Body.Form != nil {
+ for _, fileList := range request.Request.Body.Form.File {
+ for _, file := range fileList {
+ if file.Data != nil {
+ file.Data, err = NewDataObject(p, rt, *file.Data.(*[]byte))
+ if err != nil {
+ return
+ }
+ }
+ }
+ }
+ }
+
+ jsRequest = rt.ToValue(request)
+ return
+}
diff --git a/kernel/plugin/server.go b/kernel/plugin/server.go
new file mode 100644
index 0000000000..9984945b75
--- /dev/null
+++ b/kernel/plugin/server.go
@@ -0,0 +1,416 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "fmt"
+ "net/http"
+
+ "github.com/dop251/goja"
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/logging"
+)
+
+const (
+ SseHeaderAcceptName = "Accept"
+ SseHeaderAcceptValue = "text/event-stream"
+)
+
+type AccessScope string
+type SerializedType string
+type RequestType string
+
+const (
+ AccessScopePublic AccessScope = "public"
+ AccessScopePrivate AccessScope = "private"
+
+ SerializedTypeJSON SerializedType = "JSON"
+ SerializedTypeJSONP SerializedType = "JSONP"
+ SerializedTypeAsciiJSON SerializedType = "AsciiJSON"
+ SerializedTypeIndentedJSON SerializedType = "IndentedJSON"
+ SerializedTypePureJSON SerializedType = "PureJSON"
+ SerializedTypeSecureJSON SerializedType = "SecureJSON"
+
+ SerializedTypeXML SerializedType = "XML"
+ SerializedTypeYAML SerializedType = "YAML"
+ SerializedTypeTOML SerializedType = "TOML"
+ SerializedTypeProtoBuf SerializedType = "ProtoBuf"
+
+ RequestTypeHTTP RequestType = "http"
+ RequestTypeWS RequestType = "ws"
+ RequestTypeSSE RequestType = "es"
+)
+
+type Request struct {
+ URL RequestUrl `json:"url"`
+ Request RequestContent `json:"request"`
+ Context RequestContext `json:"context"`
+ Port *goja.Object `json:"port"`
+}
+
+type RequestUrl struct {
+ User *RequestUser `json:"user"`
+ Host string `json:"host"` // e.g. 127.0.0.1:6806
+ Path string `json:"path"` // e.g. /plugin/public/sample/api/hello/a space
+ EscapedPath string `json:"pathname"` // e.g. /plugin/public/sample/api/hello/a%20space
+ Fragment string `json:"fragment"` // e.g. "hash abc"
+ EscapedFragment string `json:"hash"` // e.g. "hash%20abc"
+ RawQuery string `json:"search"` // e.g. a=1&b=2
+
+ Query map[string][]string `json:"query"` // e.g. {"a": ["1"], "b": ["2"]}
+}
+
+type RequestUser struct {
+ Username string `json:"username"` // e.g. "alice"
+ Password string `json:"password"` // e.g. "123456"
+}
+
+type RequestContent struct {
+ /* Request Line */
+ Method string `json:"method"` // e.g. "GET"
+ URI string `json:"uri"` // e.g. "/plugin/public/sample/api/hello?a=1&b=2"
+ Proto string `json:"proto"` // e.g. "HTTP/1.1"
+ ProtoMajor int `json:"protoMajor"` // e.g. 1
+ ProtoMinor int `json:"protoMinor"` // e.g. 1
+
+ /* Request Headers */
+ Headers map[string][]string `json:"headers"` // e.g. {"Content-Type": ["application/json"], "Accept": ["*/*"]}
+ Cookies map[string][]string `json:"cookies"` // e.g. {"siyuan": ["abc123"]}
+
+ ContentType string `json:"contentType"` // e.g. "application/json"
+ ContentLength int64 `json:"contentLength"` // e.g. 123
+ Referer string `json:"referer"` // e.g. "http://127.0.0.1:6806/stage/build/app/"
+ UserAgent string `json:"userAgent"` // e.g. "SiYuan/3.6.5 https://b3log.org/siyuan Electron Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) SiYuan/3.6.5 Chrome/144.0.7559.236 Electron/40.9.1 Safari/537.36"
+
+ /* Request Body */
+ Body RequestBody `json:"body"`
+}
+
+type RequestBody struct {
+ Form *RequestForm `json:"form"` // parsed form data if Content-Type is application/x-www-form-urlencoded or multipart/form-data
+ Data any `json:"data"` // *[]byte | *goja.Object, content of all request body (if form != nil, it will be an empty byte array)
+}
+
+type RequestForm struct {
+ Value map[string][]string `json:"values"` // e.g. {"field1": ["value1"], "field2": ["value2-1", "value2-2"]}
+ File map[string][]RequestFile `json:"files"` // e.g. {"file1": [{"Filename": "hello.txt", "Headers": {"Content-Disposition": ["form-data; name=\"file1\"; filename=\"hello.txt\""], "Content-Type": ["text/plain"]}, "Size": 123, "Data": []byte{...}}]}
+}
+
+type RequestFile struct {
+ Filename string `json:"filename"` // e.g. "hello.txt"
+ Headers map[string][]string `json:"headers"` // e.g. {"Content-Disposition": ["form-data; name=\"file1\"; filename=\"hello.txt\""], "Content-Type": ["text/plain"]}
+ Size int64 `json:"size"` // e.g. 123
+ Data any `json:"data"` // *[]byte | *goja.Object, content of the file
+}
+
+type RequestContext struct {
+ Path string `json:"path"` // e.g. "/api/hello"
+ FullPath string `json:"fullPath"` // e.g. "/plugin/public/:name/*path"
+
+ ClientIP string `json:"clientIp"` // e.g. "127.0.0.1"
+ RemoteIP string `json:"remoteIp"` // e.g. "127.0.0.1"
+ RemoteAddr string `json:"remoteAddr"` // e.g. "127.0.0.1:54321"
+
+ Params map[string][]string `json:"params"` // e.g. [{"Key": "name", "Value": "plugin-sample"}, {"Key": "path", "Value": "/api/hello"}]
+
+ IsWebsocket bool `json:"-"`
+ IsSse bool `json:"-"`
+}
+
+type HttpResponse struct {
+ StatusCode int `json:"statusCode"` // e.g. 200
+ Headers map[string][]string `json:"headers"` // e.g. {"Content-Type": ["application/json"], "Set-Cookie": ["siyuan=abc123; Path=/; HttpOnly"]}
+ Cookies []*http.Cookie `json:"cookies"` // e.g. [{"Name": "plugin-sample", "Value": "abc123", "Quoted": false, "Path": "/plugin/private/plugin-sample/", "Domain": "", "Expires": "0001-01-01T00:00:00Z", "RawExpires": "", "MaxAge": 0, "Secure": false, "HttpOnly": false, "SameSite": 0, "Partitioned": false, "Raw": "", "Unparsed": null}]
+ Body *ResponseBody `json:"body"` // response body, can be either raw data or a file
+}
+
+type ResponseBody struct {
+ Data *ResponseSerializedData `json:"data"` // if the response is serialized data, Data will be non-nil.
+ File *ResponseFile `json:"file"` // if the response is a file, File will be non-nil.
+ String *ResponseString `json:"string"` // if the response is a formatted string, String will be non-nil.
+ Raw *ResponseRawData `json:"raw"` // if the response is raw data, Raw will be non-nil.
+ Redirect *ResponseRedirect `json:"redirect"` // if the response is a redirect, Redirect will be non-nil.
+}
+
+type ResponseSerializedData struct {
+ Type SerializedType `json:"type"` // the serialization type, e.g. JSON, XML, etc.
+ Data any `json:"data"` // the data to be serialized and sent in the response body
+}
+
+type ResponseFile struct {
+ Name string `json:"name"` // e.g. "index.html". If Name is not empty, the file will be sent with Content-Disposition header.
+ Path string `json:"path"` // e.g. "/data/plugins/<plugin-name>/app/index.html"
+}
+
+type ResponseString struct {
+ Format string `json:"format"` // string formatting template (Go string formatting style)
+ Values []any `json:"values"` // the values to be formatted into the template
+}
+
+type ResponseRawData struct {
+ ContentType string `json:"contentType"` // e.g. "image/png"
+ Data []byte `json:"data"` // content of the response body
+}
+
+type ResponseRedirect struct {
+ Location string `json:"location"` // the URL to redirect to
+}
+
+// isSseRequest checks if the incoming HTTP request is a Server-Sent Events (SSE) request by inspecting the "Accept" header for the "text/event-stream" value.
+func isSseRequest(c *gin.Context) bool {
+ return c.GetHeader(SseHeaderAcceptName) == SseHeaderAcceptValue
+}
+
+func parseRequest(c *gin.Context) (request *Request, err error) {
+ var form *RequestForm
+ var data *[]byte
+ // c.MultipartForm() will parse application/x-www-form-urlencoded and multipart/form-data
+ if multipartForm, formErr := c.MultipartForm(); formErr != nil {
+ // Not a form request, do nothing and leave form as nil
+ } else if multipartForm != nil {
+ // multipart/form-data
+ form = &RequestForm{
+ Value: multipartForm.Value,
+ File: make(map[string][]RequestFile),
+ }
+
+ for partName, fileHandlers := range multipartForm.File {
+ files := make([]RequestFile, len(fileHandlers))
+ form.File[partName] = files
+ for i, handler := range fileHandlers {
+ files[i].Filename = handler.Filename
+ files[i].Headers = handler.Header
+ files[i].Size = handler.Size
+ if file, openErr := handler.Open(); openErr != nil {
+ err = fmt.Errorf("open form part [%s] file [%s] error: %s", partName, handler.Filename, openErr.Error())
+ return
+ } else {
+ content := make([]byte, handler.Size)
+ if n, readErr := file.Read(content); readErr != nil {
+ err = fmt.Errorf("read form part [%s] file [%s] error: %s", partName, handler.Filename, readErr.Error())
+ return
+ } else {
+ fileData := content[:n]
+ files[i].Data = &fileData
+ }
+ }
+ }
+ }
+ } else if len(c.Request.PostForm) > 0 {
+ // application/x-www-form-urlencoded
+ form = &RequestForm{
+ Value: c.Request.PostForm,
+ File: nil,
+ }
+ }
+
+ if form == nil {
+ // Not a form request, read raw body data
+ if rawData, readErr := c.GetRawData(); readErr != nil {
+ // request don't have body, do nothing
+ } else {
+ data = &rawData
+ }
+ }
+
+ var user *RequestUser
+ username, password, ok := c.Request.BasicAuth()
+ if ok {
+ user = &RequestUser{
+ Username: username,
+ Password: password,
+ }
+ }
+
+ headers := map[string][]string(c.Request.Header)
+ delete(headers, "Cookie")
+ delete(headers, "Authorization")
+
+ cookies := make(map[string][]string)
+ for _, cookie := range c.Request.Cookies() {
+ cookies[cookie.Name] = append(cookies[cookie.Name], cookie.Value)
+ }
+
+ params := make(map[string][]string)
+ for _, param := range c.Params {
+ params[param.Key] = append(params[param.Key], param.Value)
+ }
+
+ request = &Request{
+ URL: RequestUrl{
+ User: user,
+ Host: c.Request.Host,
+ Path: c.Request.URL.Path,
+ EscapedPath: c.Request.URL.EscapedPath(),
+ Fragment: c.Request.URL.Fragment,
+ EscapedFragment: c.Request.URL.EscapedFragment(),
+ RawQuery: c.Request.URL.RawQuery,
+ Query: c.Request.URL.Query(),
+ },
+ Request: RequestContent{
+ Method: c.Request.Method,
+ URI: c.Request.RequestURI,
+ Proto: c.Request.Proto,
+ ProtoMajor: c.Request.ProtoMajor,
+ ProtoMinor: c.Request.ProtoMinor,
+
+ Headers: headers,
+ Cookies: cookies,
+ ContentType: c.ContentType(),
+ ContentLength: c.Request.ContentLength,
+ Referer: c.Request.Referer(),
+ UserAgent: c.Request.UserAgent(),
+
+ Body: RequestBody{
+ Form: form,
+ Data: data,
+ },
+ },
+ Context: RequestContext{
+ Path: c.Param("path"),
+ FullPath: c.FullPath(),
+ ClientIP: c.ClientIP(),
+ RemoteIP: c.RemoteIP(),
+ RemoteAddr: c.Request.RemoteAddr,
+ Params: params,
+
+ IsWebsocket: c.IsWebsocket(),
+ IsSse: isSseRequest(c),
+ },
+ }
+ return
+}
+
+func HandleHttpRequest(c *gin.Context, scope AccessScope) {
+ // /plugin/(public|private)/:name/*path
+ name := c.Param("name")
+ // path := c.Param("path")
+
+ p := GetManager().GetPlugin(name)
+ if p == nil {
+ c.String(http.StatusNotFound, "[plugin:%s] not found", name)
+ return
+ }
+ if p.State() != PluginStateRunning {
+ c.String(http.StatusServiceUnavailable, "[plugin:%s] is not running", name)
+ return
+ }
+
+ request, parseErr := parseRequest(c)
+ if parseErr != nil {
+ c.String(http.StatusBadRequest, "[plugin:%s] Error occurred while parsing HTTP request: %s", name, parseErr)
+ return
+ }
+
+ if request.Context.IsWebsocket {
+ handleErr := p.handleWebSocketRequest(c, request, scope)
+ if handleErr != nil {
+ msg := fmt.Sprintf("[plugin:%s] Error occurred while handling WebSocket request: %s", name, handleErr)
+ logging.LogWarn(msg)
+ c.String(http.StatusInternalServerError, msg)
+ }
+ return
+ }
+
+ if request.Context.IsSse {
+ handleErr := p.handleServerSentEventRequest(c, request, scope)
+ if handleErr != nil {
+ msg := fmt.Sprintf("[plugin:%s] Error occurred while handling SSE request: %s", name, handleErr)
+ logging.LogWarn(msg)
+ c.String(http.StatusInternalServerError, msg)
+ }
+ return
+ }
+
+ response, handleErr := p.handleHttpRequest(c, request, scope)
+ if handleErr != nil {
+ msg := fmt.Sprintf("[plugin:%s] Error occurred while handling HTTP request: %s", name, handleErr)
+ logging.LogWarn(msg)
+ c.String(http.StatusInternalServerError, msg)
+ return
+ }
+
+ // Set response headers
+ for headerKey, headerValues := range response.Headers {
+ for _, headerValue := range headerValues {
+ c.Header(headerKey, headerValue)
+ }
+ }
+
+ // Set response cookies
+ for _, cookie := range response.Cookies {
+ http.SetCookie(c.Writer, cookie)
+ }
+
+ // Write response body
+ if response.Body != nil {
+ if response.Body.Data != nil {
+ // Serialized data
+ switch response.Body.Data.Type {
+ case SerializedTypeJSON:
+ c.JSON(response.StatusCode, response.Body.Data.Data)
+ case SerializedTypeJSONP:
+ c.JSONP(response.StatusCode, response.Body.Data.Data)
+ case SerializedTypeAsciiJSON:
+ c.AsciiJSON(response.StatusCode, response.Body.Data.Data)
+ case SerializedTypeIndentedJSON:
+ c.IndentedJSON(response.StatusCode, response.Body.Data.Data)
+ case SerializedTypePureJSON:
+ c.PureJSON(response.StatusCode, response.Body.Data.Data)
+ case SerializedTypeSecureJSON:
+ c.SecureJSON(response.StatusCode, response.Body.Data.Data)
+
+ case SerializedTypeXML:
+ c.XML(response.StatusCode, response.Body.Data.Data)
+ case SerializedTypeYAML:
+ c.YAML(response.StatusCode, response.Body.Data.Data)
+ case SerializedTypeTOML:
+ c.TOML(response.StatusCode, response.Body.Data.Data)
+ case SerializedTypeProtoBuf:
+ c.ProtoBuf(response.StatusCode, response.Body.Data.Data)
+
+ default:
+ c.String(http.StatusInternalServerError, "[plugin:%s] Unsupported serialized data type [%s] in response", name, response.Body.Data.Type)
+ }
+ return
+ } else if response.Body.File != nil {
+ // If Path is not empty, use it as the file content and ignore Data.
+ // This is for streaming large files without loading the whole content into memory.
+ if response.Body.File.Name != "" {
+ c.FileAttachment(response.Body.File.Path, response.Body.File.Name)
+ } else {
+ c.File(response.Body.File.Path)
+ }
+ return
+ } else if response.Body.String != nil {
+ // Format the string with the provided values and write it to the response.
+ c.String(response.StatusCode, response.Body.String.Format, response.Body.String.Values...)
+ return
+ } else if response.Body.Raw != nil {
+ // Raw data
+ c.Data(response.StatusCode, response.Body.Raw.ContentType, response.Body.Raw.Data)
+ return
+ } else if response.Body.Redirect != nil {
+ // Redirect
+ c.Redirect(response.StatusCode, response.Body.Redirect.Location)
+ return
+ } else {
+ // No body
+ }
+ }
+ c.Status(response.StatusCode)
+}
diff --git a/kernel/plugin/websocket.go b/kernel/plugin/websocket.go
new file mode 100644
index 0000000000..2cf33b47d4
--- /dev/null
+++ b/kernel/plugin/websocket.go
@@ -0,0 +1,177 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "sync/atomic"
+
+ "github.com/dop251/goja"
+ "github.com/lxzan/gws"
+ "github.com/siyuan-note/logging"
+)
+
+type WsManager struct {
+ BufferedAmount *atomic.Int64
+
+ InvokeHook func(rt *goja.Runtime, eventName string, args ...goja.Value)
+ SetProtocol func(rt *goja.Runtime, protocol string)
+ SetReadyState func(rt *goja.Runtime, state WebSocketState)
+}
+
+// WsEventHandler implements gws.Event with settable callback fields so closures
+// capturing the JS runtime context can be assigned after the upgrader/dialer is created.
+type WsEventHandler struct {
+ gws.BuiltinEventHandler
+ onOpen func(*gws.Conn)
+ onClose func(*gws.Conn, error)
+ onPing func(*gws.Conn, []byte)
+ onPong func(*gws.Conn, []byte)
+ onMessage func(*gws.Conn, *gws.Message)
+
+ p *KernelPlugin
+}
+
+func (h *WsEventHandler) OnOpen(socket *gws.Conn) {
+ if h.onOpen != nil {
+ h.onOpen(socket)
+ }
+}
+
+func (h *WsEventHandler) OnClose(socket *gws.Conn, err error) {
+ if h.onClose != nil {
+ h.onClose(socket, err)
+ }
+}
+
+func (h *WsEventHandler) OnPing(socket *gws.Conn, payload []byte) {
+ if h.onPing != nil {
+ h.onPing(socket, payload)
+ }
+}
+
+func (h *WsEventHandler) OnPong(socket *gws.Conn, payload []byte) {
+ if h.onPong != nil {
+ h.onPong(socket, payload)
+ }
+}
+
+func (h *WsEventHandler) OnMessage(socket *gws.Conn, message *gws.Message) {
+ defer message.Close()
+ if h.onMessage != nil {
+ h.onMessage(socket, message)
+ }
+}
+
+func (h *WsEventHandler) BindOnOpen(manager *WsManager) {
+ h.onOpen = func(conn *gws.Conn) {
+ _, runErr := h.p.worker.RunSync(func(rt *goja.Runtime) (_ any, _ error) {
+ manager.SetProtocol(rt, conn.SubProtocol())
+ manager.SetReadyState(rt, WebSocketReadyStateOpen)
+ event := rt.NewObject()
+ event.Set("type", rt.ToValue("open"))
+ manager.InvokeHook(rt, "onopen", event)
+ return
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] invoke websocket.onopen handler error: %v", h.p.Name, runErr)
+ }
+ }
+}
+
+func (h *WsEventHandler) BindOnClose(manager *WsManager) {
+ h.onClose = func(conn *gws.Conn, err error) {
+ _, runErr := h.p.worker.RunSync(func(rt *goja.Runtime) (_ any, _ error) {
+ if err != nil {
+ errEvent := rt.NewObject()
+ errEvent.Set("type", rt.ToValue("error"))
+ errEvent.Set("error", rt.NewGoError(err))
+ manager.InvokeHook(rt, "onerror", errEvent)
+ }
+
+ if closeError, ok := err.(*gws.CloseError); ok {
+ manager.SetReadyState(rt, WebSocketReadyStateClosing)
+ closeEvent := rt.NewObject()
+ closeEvent.Set("type", rt.ToValue("close"))
+ closeEvent.Set("code", rt.ToValue(closeError.Code))
+ closeEvent.Set("reason", rt.ToValue(string(closeError.Reason)))
+ closeEvent.Set("wasClean", rt.ToValue(manager.BufferedAmount.Load() == 0))
+ manager.InvokeHook(rt, "onclose", closeEvent)
+ }
+ manager.SetReadyState(rt, WebSocketReadyStateClosed)
+ return
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] invoke websocket.onclose handler error: %v", h.p.Name, runErr)
+ }
+ }
+}
+
+func (h *WsEventHandler) BindOnPing(manager *WsManager) {
+ h.onPing = func(conn *gws.Conn, payload []byte) {
+ _, runErr := h.p.worker.RunSync(func(rt *goja.Runtime) (_ any, _ error) {
+ event := rt.NewObject()
+ event.Set("type", rt.ToValue("ping"))
+ event.Set("data", rt.ToValue(string(payload)))
+ manager.InvokeHook(rt, "onping", event)
+ return
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] invoke websocket.onping handler error: %v", h.p.Name, runErr)
+ }
+ }
+}
+
+func (h *WsEventHandler) BindOnPong(manager *WsManager) {
+ h.onPong = func(conn *gws.Conn, payload []byte) {
+ _, runErr := h.p.worker.RunSync(func(rt *goja.Runtime) (_ any, _ error) {
+ event := rt.NewObject()
+ event.Set("type", rt.ToValue("pong"))
+ event.Set("data", rt.ToValue(string(payload)))
+ manager.InvokeHook(rt, "onpong", event)
+ return
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] invoke websocket.onpong handler error: %v", h.p.Name, runErr)
+ }
+ }
+}
+
+func (h *WsEventHandler) BindOnMessage(manager *WsManager) {
+ h.onMessage = func(conn *gws.Conn, message *gws.Message) {
+ opcode := message.Opcode
+ data := make([]byte, message.Data.Len())
+ copy(data, message.Bytes()) // message.Bytes() points into gws-managed memory reclaimed by message.Close() (deferred above)
+ _, runErr := h.p.worker.RunSync(func(rt *goja.Runtime) (_ any, _ error) {
+ event := rt.NewObject()
+ switch opcode {
+ case gws.OpcodeText:
+ event.Set("type", rt.ToValue("text"))
+ event.Set("data", rt.ToValue(string(data)))
+ case gws.OpcodeBinary:
+ event.Set("type", rt.ToValue("binary"))
+ event.Set("data", rt.ToValue(rt.NewArrayBuffer(data)))
+ default:
+ return
+ }
+ manager.InvokeHook(rt, "onmessage", event)
+ return
+ })
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] invoke websocket.onmessage handler error: %v", h.p.Name, runErr)
+ }
+ }
+}
diff --git a/kernel/plugin/worker.go b/kernel/plugin/worker.go
new file mode 100644
index 0000000000..991babcb9e
--- /dev/null
+++ b/kernel/plugin/worker.go
@@ -0,0 +1,92 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package plugin
+
+import (
+ "fmt"
+
+ "github.com/dop251/goja"
+ "github.com/dop251/goja_nodejs/eventloop"
+ "github.com/siyuan-note/logging"
+)
+
+type TaskExecutor func(rt *goja.Runtime) (result any, err error)
+type TaskCallback func(rt *goja.Runtime, result any, err error)
+
+type Worker struct {
+ loop *eventloop.EventLoop
+}
+
+type TaskResult struct {
+ value any
+ err error
+}
+
+func (w *Worker) Start(loop *eventloop.EventLoop) {
+ w.loop = loop
+}
+
+func (w *Worker) Run(executor TaskExecutor, callback TaskCallback) error {
+ if w.loop == nil {
+ return fmt.Errorf("worker event loop not initialized")
+ }
+
+ success := w.loop.RunOnLoop(func(rt *goja.Runtime) {
+ var result any
+ var err error
+
+ defer func() {
+ defer func() {
+ // catch panic from callback
+ if r := recover(); r != nil {
+ logging.LogErrorf("task callback panicked: %v\n", r)
+ }
+ }()
+
+ // catch panic from executor
+ if r := recover(); r != nil {
+ err = fmt.Errorf("task executor panicked: %v", r)
+ }
+ if callback != nil {
+ callback(rt, result, err)
+ }
+ }()
+
+ result, err = executor(rt)
+ })
+ if !success {
+ return fmt.Errorf("failed to run task on event loop")
+ }
+ return nil
+}
+
+func (w *Worker) RunSync(fn TaskExecutor) (result any, err error) {
+ response := make(chan TaskResult, 1)
+ err = w.Run(fn, func(rt *goja.Runtime, result any, err error) {
+ response <- TaskResult{result, err}
+ })
+
+ if err != nil {
+ close(response)
+ return
+ }
+
+ r := <-response
+ result = r.value
+ err = r.err
+ return
+}
diff --git a/kernel/server/proxy/publish.go b/kernel/server/proxy/publish.go
index c1f0a0e8d4..5baeaa2d2b 100644
--- a/kernel/server/proxy/publish.go
+++ b/kernel/server/proxy/publish.go
@@ -41,7 +41,7 @@ var (
)
func InitPublishService() (uint16, error) {
- model.InitAccounts()
+ model.InitPublishAccounts()
if listener != nil {
if !model.Conf.Publish.Enable {
diff --git a/kernel/util/misc.go b/kernel/util/misc.go
index 8ef925abfc..28d35fda1d 100644
--- a/kernel/util/misc.go
+++ b/kernel/util/misc.go
@@ -18,6 +18,7 @@ package util
import (
"bytes"
+ "encoding/json"
"fmt"
"math/rand"
"regexp"
@@ -30,6 +31,41 @@ import (
"github.com/siyuan-note/logging"
)
+// Optional is a generic type that represents an optional value, which can be in one of three states:
+// - not set (Exists=false)
+// - set to a non-null value (Exists=true, IsNull=false)
+// - explicitly set to null (Exists=true, IsNull=true).
+//
+// This allows distinguishing between "not provided" and "explicitly null" when unmarshaling JSON.
+type Optional[T any] struct {
+ Value T
+ Exists bool
+ IsNull bool
+}
+
+func (o Optional[T]) IsZero() bool { return !o.Exists }
+
+func (o Optional[T]) IsNullValue() bool { return o.Exists && o.IsNull }
+
+func (o Optional[T]) HasValue() bool { return o.Exists && !o.IsNull }
+
+func (o *Optional[T]) UnmarshalJSON(data []byte) error {
+ o.Exists = true
+ if string(data) == "null" {
+ o.IsNull = true
+ return nil
+ }
+ o.IsNull = false
+ return json.Unmarshal(data, &o.Value)
+}
+
+func (o Optional[T]) MarshalJSON() ([]byte, error) {
+ if !o.Exists || o.IsNull {
+ return []byte("null"), nil
+ }
+ return json.Marshal(o.Value)
+}
+
func GetDuplicateName(master string) (ret string) {
if "" == master {
return
diff --git a/kernel/util/net.go b/kernel/util/net.go
index 4af21fc487..6c924b3f53 100644
--- a/kernel/util/net.go
+++ b/kernel/util/net.go
@@ -220,6 +220,48 @@ func JsonArg(c *gin.Context, result *gulu.Result) (arg map[string]any, ok bool)
return
}
+// GetRequestUrlStringParam extracts a string parameter from URL (path or query parameters).
+func GetRequestUrlStringParam(c *gin.Context, key string) string {
+ // /path/:name
+ if value := c.Param(key); value != "" {
+ return value
+ }
+
+ // /path?name=xxx
+ if value := c.Query(key); value != "" {
+ return value
+ }
+
+ return ""
+}
+
+// GetRequestStringParam extracts a string parameter from the request (URL or JSON body), with validation and error handling.
+func GetRequestStringParam(c *gin.Context, key string, result *gulu.Result) string {
+ // /path/:name
+ if value := GetRequestUrlStringParam(c, key); value != "" {
+ return value
+ }
+
+ // /path with JSON body {key: "xxx"}
+ arg, ok := JsonArg(c, result)
+ if !ok {
+ return ""
+ }
+ if arg[key] == nil {
+ result.Code = -2
+ result.Msg = fmt.Sprintf("Request body prop [%s] does not exist", key)
+ return ""
+ }
+
+ value, ok := arg[key].(string)
+ if !ok {
+ result.Code = -3
+ result.Msg = fmt.Sprintf("Request body prop [%s] is not a string", key)
+ return ""
+ }
+ return value
+}
+
// ParseJsonArg 使用泛型从 JSON 参数中提取指定键的值。
// - 如果 required 为 true 但参数缺失,则会在 ret.Msg 中说明需要传入的键
// - 如果 rejectEmpty 为 true 但参数值为空,则会在 ret.Msg 中说明该键必须不为空(字符串去空白后、空数组、无任何键的对象)