diff --git a/doc/design/ext-web-go-rewrite.md b/doc/design/ext-web-go-rewrite.md index 719e7ee..558ef85 100644 --- a/doc/design/ext-web-go-rewrite.md +++ b/doc/design/ext-web-go-rewrite.md @@ -366,12 +366,10 @@ scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so | 组件 | 变更 | |------|------| -| 根 `Cargo.toml` workspace | 移除 `plugins/web` Rust member | +| 根 `Cargo.toml` workspace | 移除 `plugins/web` / `web-rust-archive` Rust member | | `tests/gold.rs` | `ensure_web_plugin_built()` → `scripts/build-web-plugin.sh` | +| `marqdo ext add web` | 构建回退:`scripts/build-web-plugin.sh`(Go);Release 仍下发预编译 native zip | | Release 脚本 | Go:`scripts/build-web-plugin.sh`;其它插件仍 `cargo build -p …` | - -| `marqdo ext add web` | 构建回退:有 Go 则 `go build`;Release 仍下发预编译 native zip | -| Release 脚本 | 增加 Go 交叉/本机编译 `libweb` 打包步骤 | | [ext-cli.md](ext-cli.md) / [ext-abi.md](ext-abi.md) | 注明 web 插件实现语言为 Go | ### 9.4 cgo / runtime 注意 @@ -400,7 +398,7 @@ scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so | **W-G10** | proxy + invoke + nested plugin | ✅ `web-proxy-invoke` / hosting live | | **W-G11** | 定制 C2–C4 shell/layout/style/nav | ✅ `web-c2`–`c4` | | **W-G12** | G 增强 WS rooms + Redis session/pubsub + API key 原语 | ✅ 单测 + `web-g12-api-key-smoke` | -| **W-G13** | 默认切换 Go `libweb`;归档 Rust;更新发版与 ext CLI | ✅ 离线 `tests/ext/web-*`(有 `# main`)全绿;`ext add`/`gold`/`release` 走 `scripts/build-web-plugin.sh`;Rust 移出 workspace | +| **W-G13** | 默认切换 Go `libweb`;归档 Rust;更新发版与 ext CLI | ✅ 离线+live gold(7 个 `*_live`)对 Go 全绿;`ext add`/`gold`/`release` 走 `scripts/build-web-plugin.sh`;Rust 移出 workspace;gold 强制 `MARQDO_WEB_PLUGIN` 避免 `~/.marqdo` 旧 so | | **W-G14** | anlian Marqdo 重写主路径(可分仓或 `examples/anlian-mq/`) | §8 矩阵主路径可演示 | 每波次:**先补 Go 实现 → 跑对应 gold → 再进入下一波**。禁止跨波次留下「注册了但返回 stub 错误」的 ABI(除 W-G0 明确的未实现探测)。 diff --git a/plugins/web/internal/httpx/helpers.go b/plugins/web/internal/httpx/helpers.go new file mode 100644 index 0000000..cbe0df3 --- /dev/null +++ b/plugins/web/internal/httpx/helpers.go @@ -0,0 +1,149 @@ +package httpx + +import ( + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/marqdo/marqdo/plugins/web/internal/session" +) + +func esc(s string) string { + s = strings.ReplaceAll(s, "&", "&") + s = strings.ReplaceAll(s, "<", "<") + s = strings.ReplaceAll(s, ">", ">") + return s +} + +func weakETag(bytes []byte) string { + var h uint64 = 0xcbf29ce484222325 + for _, b := range bytes { + h ^= uint64(b) + h *= 0x0100000001b3 + } + return fmt.Sprintf("W/\"%x-%d\"", h, len(bytes)) +} + +func jsonErr(w http.ResponseWriter, code int, msg string) { + writeJSON(w, code, map[string]any{"ok": false, "error": msg}) +} + +func routeMapOf(appBag map[string]any, key string) map[string]any { + if r, ok := appBag[key].(map[string]any); ok { + return r + } + return map[string]any{} +} + +func routePathKey(path string) string { + p := strings.TrimSpace(path) + if !strings.HasPrefix(p, "/") { + p = "/" + p + } + return p +} + +// goMuxPattern converts Marqdo route patterns (`{*key}`) to Go ServeMux (`{key...}`). +func goMuxPattern(path string) string { + out := path + for { + start := strings.Index(out, "{*") + if start < 0 { + break + } + end := strings.Index(out[start:], "}") + if end < 0 { + break + } + end += start + name := out[start+2 : end] + out = out[:start] + "{" + name + "...}" + out[end+1:] + } + return out +} + +func resolveSession(r *http.Request) (sid, csrf string, setCookie *string) { + cookieHdr := r.Header.Get("Cookie") + id, hadCookie := session.IDFromCookie(cookieHdr) + if hadCookie { + ok := true + if ok && id != "" { + sid = id + if tok, ok := session.CSRFFor(sid); ok { + csrf = tok + } + return sid, csrf, nil + } + } + sid = session.NewID(0) + tok, _ := session.CSRFFor(sid) + c := session.SessionCookie(sid, 0, false) + return sid, tok, &c +} + +func appendSetCookie(w http.ResponseWriter, setCookie *string) { + if setCookie != nil && *setCookie != "" { + w.Header().Add("Set-Cookie", *setCookie) + } +} + +func queryToMap(q string) map[string]any { + out := map[string]any{} + if q == "" { + return out + } + for _, pair := range strings.Split(q, "&") { + if pair == "" { + continue + } + k, v, _ := strings.Cut(pair, "=") + k, _ = url.QueryUnescape(k) + v, _ = url.QueryUnescape(v) + if k != "" { + out[k] = v + } + } + return out +} + +func formToMap(body []byte) map[string]any { + return queryToMap(string(body)) +} + +func jsonWrapInvokeValue(value any) (int, map[string]any, error) { + if value == nil { + return http.StatusInternalServerError, nil, fmt.Errorf("null result") + } + switch t := value.(type) { + case map[string]any: + return http.StatusOK, t, nil + default: + return http.StatusOK, map[string]any{"ok": true, "result": value}, nil + } +} + +func invokeArgsFromPayload(payload map[string]any) map[string]any { + args := map[string]any{} + for k, v := range payload { + args[k] = v + } + if _, ok := args["payload"]; !ok { + args["payload"] = payload + } + return args +} + +func readJSONBody(r *http.Request, max int64) (map[string]any, error) { + r.Body = http.MaxBytesReader(nil, r.Body, max) + defer r.Body.Close() + var raw map[string]any + if err := json.NewDecoder(r.Body).Decode(&raw); err != nil { + return nil, err + } + if raw == nil { + raw = map[string]any{} + } + return raw, nil +} diff --git a/plugins/web/internal/httpx/helpers_test.go b/plugins/web/internal/httpx/helpers_test.go new file mode 100644 index 0000000..0a36ede --- /dev/null +++ b/plugins/web/internal/httpx/helpers_test.go @@ -0,0 +1,12 @@ +package httpx + +import "testing" + +func TestGoMuxPattern(t *testing.T) { + if got := goMuxPattern("/_media/{*key}"); got != "/_media/{key...}" { + t.Fatalf("got %q", got) + } + if got := goMuxPattern("/post/{slug}"); got != "/post/{slug}" { + t.Fatalf("got %q", got) + } +} diff --git a/plugins/web/internal/httpx/listen.go b/plugins/web/internal/httpx/listen.go index 4d5cbdc..3e87abd 100644 --- a/plugins/web/internal/httpx/listen.go +++ b/plugins/web/internal/httpx/listen.go @@ -2,6 +2,7 @@ package httpx import ( + "bufio" "compress/gzip" "encoding/json" "fmt" @@ -16,10 +17,12 @@ import ( "time" "github.com/marqdo/marqdo/plugins/web/internal/app" + "github.com/marqdo/marqdo/plugins/web/internal/assets" "github.com/marqdo/marqdo/plugins/web/internal/db" "github.com/marqdo/marqdo/plugins/web/internal/form" "github.com/marqdo/marqdo/plugins/web/internal/middleware" "github.com/marqdo/marqdo/plugins/web/internal/render" + "github.com/marqdo/marqdo/plugins/web/internal/sitemap" ) // NewHandler builds the HTTP handler for an app bag (no listen). @@ -59,13 +62,31 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) { } mw := middleware.Parse(appBag) + siteHead := assets.HeadLinksFromJSON(appBag["site_head"]) + iconRoutes, err := iconRoutesFromBag(appBag, entryDir, staticDir) + if err != nil { + return nil, err + } st := &state{ - page: page, - dbURL: dbURL, - routes: routes, - forms: forms, - mw: mw, - entryDir: entryDir, + page: page, + dbURL: dbURL, + routes: routes, + forms: forms, + mw: mw, + entryDir: entryDir, + siteHead: siteHead, + iconRoutes: iconRoutes, + redirects: redirectsOf(appBag), + sitemapRoutes: sitemapRoutesOf(appBag), + robotsBody: robotsBodyOf(appBag), + page404: pageOf(appBag, "page_404"), + page500: pageOf(appBag, "page_500"), + uploadRoutes: routeMapOf(appBag, "upload_routes"), + downloadRoutes: routeMapOf(appBag, "download_routes"), + wsRoutes: routeMapOf(appBag, "ws_routes"), + galleryRoutes: routeMapOf(appBag, "gallery_routes"), + proxyRoutes: routeMapOf(appBag, "proxy_routes"), + invokeRoutes: routeMapOf(appBag, "invoke_routes"), } mux := http.NewServeMux() @@ -82,8 +103,8 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) { pageV = map[string]any{} } if strings.Contains(routePath, "{") { - mux.HandleFunc("GET "+routePath, st.makeDynamicPage(pageV, routePath)) - mux.HandleFunc("GET "+routePath+"/_part/{id}", st.makeDynamicPart(pageV, routePath)) + mux.HandleFunc("GET "+goMuxPattern(routePath), st.makeDynamicPage(pageV, routePath)) + mux.HandleFunc("GET "+goMuxPattern(routePath)+"/_part/{id}", st.makeDynamicPart(pageV, routePath)) } else { pv := pageV mux.HandleFunc("GET "+routePath, func(w http.ResponseWriter, r *http.Request) { @@ -112,6 +133,56 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) { mux.Handle("HEAD "+staticMount, fs) } + for _, ir := range iconRoutes { + url := ir.URL + path := ir.Path + ct := ir.ContentType + fmt.Fprintf(os.Stderr, "marqdo web icon: %s → %s (%s)\n", url, path, ct) + mux.HandleFunc("GET "+url, func(w http.ResponseWriter, r *http.Request) { + st.serveIcon(w, path, ct) + }) + mux.HandleFunc("HEAD "+url, func(w http.ResponseWriter, r *http.Request) { + st.serveIcon(w, path, ct) + }) + } + + for _, from := range sortedKeys(st.redirects) { + spec, _ := st.redirects[from].(map[string]any) + to := strOpt(spec, "to", "/") + permanent := boolish(spec["permanent"]) + mux.HandleFunc("GET "+from, func(w http.ResponseWriter, r *http.Request) { + code := http.StatusTemporaryRedirect + if permanent { + code = http.StatusMovedPermanently + } + http.Redirect(w, r, to, code) + }) + } + + for _, path := range sortedKeys(st.sitemapRoutes) { + cfg, _ := st.sitemapRoutes[path].(map[string]any) + mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) { + st.writeSitemap(w, cfg) + }) + } + + if st.robotsBody != "" { + body := st.robotsBody + mux.HandleFunc("GET /robots.txt", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + _, _ = io.WriteString(w, body) + }) + } + + st.mountWSRoutes(mux) + st.mountUploadRoutes(mux) + st.mountDownloadRoutes(mux) + st.mountGalleryRoutes(mux) + st.mountProxyRoutes(mux) + st.mountInvokeRoutes(mux) + + mux.HandleFunc("/{path...}", st.handleNotFound) + return withMiddleware(mux, mw), nil } @@ -155,12 +226,25 @@ func Listen(appBag map[string]any, entryDir string) (map[string]any, error) { } type state struct { - page map[string]any - dbURL string - routes map[string]any - forms map[string]any - mw middleware.Config - entryDir string + page map[string]any + dbURL string + routes map[string]any + forms map[string]any + mw middleware.Config + entryDir string + siteHead []assets.HeadLink + iconRoutes []assets.IconRoute + redirects map[string]any + sitemapRoutes map[string]any + robotsBody string + page404 map[string]any + page500 map[string]any + uploadRoutes map[string]any + downloadRoutes map[string]any + wsRoutes map[string]any + galleryRoutes map[string]any + proxyRoutes map[string]any + invokeRoutes map[string]any } func (st *state) handleHome(w http.ResponseWriter, r *http.Request) { @@ -171,18 +255,83 @@ func (st *state) handleHomePart(w http.ResponseWriter, r *http.Request) { st.writePart(w, st.page, r.PathValue("id")) } +func (st *state) preparePage(page map[string]any) map[string]any { + p := cloneMap(page) + assets.MergeSiteHead(p, st.siteHead) + return p +} + func (st *state) writePage(w http.ResponseWriter, page map[string]any) { - html := render.RenderPage(page, st.dbURL, "") + html := render.RenderPage(st.preparePage(page), st.dbURL, "") w.Header().Set("Content-Type", "text/html; charset=utf-8") _, _ = io.WriteString(w, html) } func (st *state) writePart(w http.ResponseWriter, page map[string]any, id string) { - html := render.RenderPage(page, st.dbURL, id) + html := render.RenderPage(st.preparePage(page), st.dbURL, id) w.Header().Set("Content-Type", "text/html; charset=utf-8") _, _ = io.WriteString(w, html) } +func (st *state) serveIcon(w http.ResponseWriter, path, contentType string) { + data, err := os.ReadFile(path) + if err != nil { + http.NotFound(w, nil) + return + } + w.Header().Set("Content-Type", contentType) + w.Header().Set("Cache-Control", "public, max-age=86400") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(data) +} + +func (st *state) writeSitemap(w http.ResponseWriter, cfg map[string]any) { + base := strOpt(cfg, "base", "") + items := cfg["items"] + if tbl, ok := cfg["table"].(string); ok && tbl != "" && st.dbURL != "" { + locCol := strOpt(cfg, "loc", "path") + limit := int64(1000) + if n, ok := cfg["limit"].(float64); ok && n > 0 { + limit = int64(n) + } + opts := db.SelectOpts{} + out, err := db.Select(st.dbURL, tbl, limit, opts) + if err == nil { + if rows, ok := out["rows"].([]any); ok { + norm := make([]any, 0, len(rows)) + for _, row := range rows { + m, ok := row.(map[string]any) + if !ok { + continue + } + cp := cloneMap(m) + if _, has := cp["loc"]; !has { + if v, ok := cp[locCol]; ok { + cp["loc"] = v + } + } + norm = append(norm, cp) + } + items = norm + } + } + } + xml := sitemap.BuildSitemap(base, items) + w.Header().Set("Content-Type", "application/xml; charset=utf-8") + _, _ = io.WriteString(w, xml) +} + +func (st *state) handleNotFound(w http.ResponseWriter, r *http.Request) { + if st.page404 != nil { + html := render.RenderPage(st.preparePage(st.page404), st.dbURL, "") + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(http.StatusNotFound) + _, _ = io.WriteString(w, html) + return + } + http.NotFound(w, r) +} + func (st *state) makeDynamicPage(page map[string]any, pattern string) http.HandlerFunc { paramNames := pathParamNames(pattern) return func(w http.ResponseWriter, r *http.Request) { @@ -280,6 +429,10 @@ func withMiddleware(next http.Handler, mw middleware.Config) http.Handler { limit := int64(*mw.BodyLimit) inner := h h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.ContentLength > limit { + http.Error(w, "request body too large", http.StatusRequestEntityTooLarge) + return + } r.Body = http.MaxBytesReader(w, r.Body, limit) inner.ServeHTTP(w, r) }) @@ -299,7 +452,7 @@ func withMiddleware(next http.Handler, mw middleware.Config) http.Handler { inner.ServeHTTP(w, r) return } - w.Header().Set("Content-Encoding", "gzip") + setHeader(w, "content-encoding", "gzip") w.Header().Add("Vary", "Accept-Encoding") gz := gzip.NewWriter(w) defer gz.Close() @@ -314,7 +467,7 @@ func withMiddleware(next http.Handler, mw middleware.Config) http.Handler { val := hv[1] inner := h h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set(name, val) + setHeader(w, strings.ToLower(name), val) inner.ServeHTTP(w, r) }) } @@ -346,33 +499,38 @@ func withMiddleware(next http.Handler, mw middleware.Config) http.Handler { func applyCORS(w http.ResponseWriter, r *http.Request, c *middleware.CORSConfig) { origin := r.Header.Get("Origin") if len(c.AllowOrigins) == 0 { - w.Header().Set("Access-Control-Allow-Origin", "*") + setHeader(w, "access-control-allow-origin", "*") } else if origin != "" { for _, o := range c.AllowOrigins { if o == origin { - w.Header().Set("Access-Control-Allow-Origin", origin) + setHeader(w, "access-control-allow-origin", origin) break } } } if len(c.Methods) == 0 { - w.Header().Set("Access-Control-Allow-Methods", "*") + setHeader(w, "access-control-allow-methods", "*") } else { - w.Header().Set("Access-Control-Allow-Methods", strings.Join(unique(c.Methods), ", ")) + setHeader(w, "access-control-allow-methods", strings.Join(unique(c.Methods), ", ")) } if len(c.Headers) == 0 { - w.Header().Set("Access-Control-Allow-Headers", "*") + setHeader(w, "access-control-allow-headers", "*") } else { - w.Header().Set("Access-Control-Allow-Headers", strings.Join(unique(c.Headers), ", ")) + setHeader(w, "access-control-allow-headers", strings.Join(unique(c.Headers), ", ")) } if len(c.ExposeHeaders) > 0 { - w.Header().Set("Access-Control-Expose-Headers", strings.Join(unique(c.ExposeHeaders), ", ")) + expose := strings.ToLower(strings.Join(unique(c.ExposeHeaders), ", ")) + setHeader(w, "access-control-expose-headers", expose) } if c.Credentials { - w.Header().Set("Access-Control-Allow-Credentials", "true") + setHeader(w, "access-control-allow-credentials", "true") } } +func setHeader(w http.ResponseWriter, name, value string) { + w.Header()[name] = []string{value} +} + func securityHeaderName(raw string) (string, bool) { n := strings.ToLower(strings.ReplaceAll(raw, "_", "-")) switch n { @@ -400,6 +558,13 @@ type gzipResponseWriter struct { func (g *gzipResponseWriter) Write(b []byte) (int, error) { return g.w.Write(b) } +func (g *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + if h, ok := g.ResponseWriter.(http.Hijacker); ok { + return h.Hijack() + } + return nil, nil, fmt.Errorf("underlying ResponseWriter does not support hijacking") +} + type statusRecorder struct { http.ResponseWriter status int @@ -410,6 +575,13 @@ func (s *statusRecorder) WriteHeader(code int) { s.ResponseWriter.WriteHeader(code) } +func (s *statusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) { + if h, ok := s.ResponseWriter.(http.Hijacker); ok { + return h.Hijack() + } + return nil, nil, fmt.Errorf("underlying ResponseWriter does not support hijacking") +} + func writeJSON(w http.ResponseWriter, code int, v any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(code) @@ -540,3 +712,90 @@ func unique(ss []string) []string { } return out } + +func boolish(v any) bool { + switch t := v.(type) { + case bool: + return t + case string: + return t == "true" || t == "True" || t == "1" || t == "yes" + case float64: + return t != 0 + } + return false +} + +func redirectsOf(appBag map[string]any) map[string]any { + if r, ok := appBag["redirects"].(map[string]any); ok { + return r + } + return map[string]any{} +} + +func sitemapRoutesOf(appBag map[string]any) map[string]any { + if r, ok := appBag["sitemap_routes"].(map[string]any); ok { + return r + } + return map[string]any{} +} + +func robotsBodyOf(appBag map[string]any) string { + if s, ok := appBag["robots_body"].(string); ok { + return s + } + return "" +} + +func pageOf(appBag map[string]any, key string) map[string]any { + if p, ok := appBag[key].(map[string]any); ok { + return p + } + return nil +} + +func iconRoutesFromBag(appBag map[string]any, entryDir, staticDir string) ([]assets.IconRoute, error) { + var routes []assets.IconRoute + if icons, ok := appBag["icons"].([]any); ok { + for _, ic := range icons { + m, ok := ic.(map[string]any) + if !ok { + continue + } + p := strOpt(m, "path", "") + url := strOpt(m, "url", "") + if p == "" || url == "" { + continue + } + if !strings.HasPrefix(url, "/") { + return nil, fmt.Errorf("icon url `%s` must start with /", url) + } + abs := resolvePath(p, entryDir) + fi, err := os.Stat(abs) + if err != nil || fi.IsDir() { + return nil, fmt.Errorf("icon file `%s` not found for `%s`", abs, url) + } + ct := strOpt(m, "type", "") + if ct == "" { + ct = assets.MimeForPath(p) + } + routes = append(routes, assets.IconRoute{ + URL: url, Path: abs, ContentType: ct, + }) + } + } + if len(routes) == 0 && staticDir != "" { + for _, name := range []string{"favicon.ico", "favicon.png", "favicon.svg"} { + p := filepath.Join(staticDir, name) + fi, err := os.Stat(p) + if err == nil && !fi.IsDir() { + routes = append(routes, assets.IconRoute{ + URL: "/favicon.ico", + Path: p, + ContentType: assets.MimeForPath(name), + }) + break + } + } + } + return routes, nil +} diff --git a/plugins/web/internal/httpx/listen_test.go b/plugins/web/internal/httpx/listen_test.go index 2dcbe92..19e3705 100644 --- a/plugins/web/internal/httpx/listen_test.go +++ b/plugins/web/internal/httpx/listen_test.go @@ -11,6 +11,7 @@ import ( "github.com/marqdo/marqdo/plugins/web/internal/app" "github.com/marqdo/marqdo/plugins/web/internal/httpx" + "github.com/marqdo/marqdo/plugins/web/internal/middleware" ) func TestNewHandlerHomeRoutesStatic(t *testing.T) { @@ -65,3 +66,86 @@ func TestNewHandlerHomeRoutesStatic(t *testing.T) { } } } + +func TestNewHandlerIconsRedirectSitemap404(t *testing.T) { + dir := t.TempDir() + iconPath := filepath.Join(dir, "favicon.png") + if err := os.WriteFile(iconPath, []byte("PNG"), 0o644); err != nil { + t.Fatal(err) + } + + page := map[string]any{"title": "W7", "intro": "

home

"} + nf := map[string]any{"title": "Not Found Page", "intro": "

missing

"} + a := app.New(map[string]any{"page": page}) + a, err := app.Icons(a, []any{ + map[string]any{"path": iconPath, "rel": "icon", "type": "image/png", "url": "/favicon.ico"}, + }) + if err != nil { + t.Fatal(err) + } + a, err = app.Redirect(a, "/legacy", "/", true) + if err != nil { + t.Fatal(err) + } + a, err = app.ErrorPage(a, 404, nf) + if err != nil { + t.Fatal(err) + } + items := []any{map[string]any{"loc": "/"}, map[string]any{"loc": "/about"}} + a, err = app.Sitemap(a, "/sitemap.xml", "http://example.com", "", "path", 100, items) + if err != nil { + t.Fatal(err) + } + a, err = app.Robots(a, "", "http://example.com/sitemap.xml") + if err != nil { + t.Fatal(err) + } + a, err = middleware.Configure(a, map[string]any{"cache_control": "public, max-age=120"}) + if err != nil { + t.Fatal(err) + } + + h, err := httpx.NewHandler(a, dir) + if err != nil { + t.Fatal(err) + } + + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/favicon.ico", nil)) + if rec.Code != 200 || !strings.Contains(rec.Header().Get("Content-Type"), "image/") { + t.Fatalf("favicon code=%d ct=%q", rec.Code, rec.Header().Get("Content-Type")) + } + + rec = httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/legacy", nil)) + if rec.Code != http.StatusMovedPermanently { + t.Fatalf("redirect code=%d", rec.Code) + } + + rec = httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/sitemap.xml", nil)) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), " 0 { + csrfToken = vals[0] + } + + var fileName, fileCT string + fileCT = "application/octet-stream" + var fileBytes []byte + + if files := r.MultipartForm.File[cfg.Field]; len(files) > 0 { + fh := files[0] + fileName = fh.Filename + if fh.Header != nil { + if ct := fh.Header.Get("Content-Type"); ct != "" { + fileCT = ct + } + } + f, err := fh.Open() + if err != nil { + jsonErr(w, http.StatusBadRequest, fmt.Sprintf("open file: %v", err)) + return + } + defer f.Close() + b, err := io.ReadAll(f) + if err != nil { + jsonErr(w, http.StatusBadRequest, fmt.Sprintf("read file: %v", err)) + return + } + fileBytes = b + } else { + // Fallback: walk File map keys. + for name, fhs := range r.MultipartForm.File { + if name == cfg.Field && len(fhs) > 0 { + fh := fhs[0] + fileName = fh.Filename + f, err := fh.Open() + if err != nil { + jsonErr(w, http.StatusBadRequest, fmt.Sprintf("open file: %v", err)) + return + } + defer f.Close() + fileBytes, err = io.ReadAll(f) + if err != nil { + jsonErr(w, http.StatusBadRequest, fmt.Sprintf("read file: %v", err)) + return + } + break + } + } + } + + if hadCookie && !session.ValidateCSRF(sid, csrfToken) { + jsonErr(w, http.StatusForbidden, "Invalid or missing CSRF token") + return + } + + if len(fileBytes) == 0 { + jsonErr(w, http.StatusBadRequest, "missing file field") + return + } + + size := uint64(len(fileBytes)) + check := upload.Validate(fileName, fileCT, size, cfg.MaxBytes, cfg.Types) + if ok, _ := check["ok"].(bool); !ok { + errMsg := strOpt(check, "error", "validation failed") + jsonErr(w, http.StatusBadRequest, errMsg) + return + } + ct := strOpt(check, "content_type", fileCT) + + key, err := upload.MakeKey(cfg.Prefix, fileName) + if err != nil { + jsonErr(w, http.StatusBadRequest, err.Error()) + return + } + saved, err := storage.PutBytes(cfg.StorageURL, key, fileBytes, ct) + if err != nil { + jsonErr(w, http.StatusInternalServerError, err.Error()) + return + } + + body := map[string]any{ + "ok": true, + "key": key, + "size": float64(size), + "content_type": ct, + } + if sz, ok := saved["size"]; ok { + body["size"] = sz + } + appendSetCookie(w, setCookie) + writeJSON(w, http.StatusOK, body) +} + +func (st *state) handleDownload(w http.ResponseWriter, r *http.Request, routePath string, cfg downloadRoute) { + key := downloadKeyFromRequest(r, routePath) + if key == "" { + jsonErr(w, http.StatusBadRequest, "missing key") + return + } + + bytes, contentType, filename, found, err := storage.ReadBytes(cfg.StorageURL, key) + if err != nil { + jsonErr(w, http.StatusInternalServerError, err.Error()) + return + } + if !found { + jsonErr(w, http.StatusNotFound, "not found") + return + } + + etag := weakETag(bytes) + if inm := r.Header.Get("If-None-Match"); inm != "" { + for _, part := range strings.Split(inm, ",") { + if strings.TrimSpace(part) == etag { + w.WriteHeader(http.StatusNotModified) + return + } + } + } + + disp := "attachment" + if strings.EqualFold(cfg.Disposition, "inline") { + disp = "inline" + } + safeName := strings.ReplaceAll(filename, `"`, "_") + w.Header().Set("Content-Type", contentType) + w.Header().Set("Content-Disposition", fmt.Sprintf("%s; filename=\"%s\"", disp, safeName)) + w.Header().Set("ETag", etag) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(bytes) +} + +func downloadKeyFromRequest(r *http.Request, routePath string) string { + for _, name := range downloadParamNames(routePath) { + if v := strings.TrimPrefix(r.PathValue(name), "/"); v != "" { + return v + } + } + if v := strings.TrimPrefix(r.PathValue("key"), "/"); v != "" { + return v + } + return "" +} + +func downloadParamNames(routePath string) []string { + var names []string + for _, seg := range strings.Split(routePath, "/") { + if strings.HasPrefix(seg, "{*") && strings.HasSuffix(seg, "}") { + names = append(names, strings.TrimSuffix(strings.TrimPrefix(seg, "{*"), "}")) + } else if strings.HasPrefix(seg, "{") && strings.HasSuffix(seg, "}") { + inner := strings.TrimSuffix(strings.TrimPrefix(seg, "{"), "}") + if strings.HasSuffix(inner, "...") { + inner = strings.TrimSuffix(inner, "...") + } + if inner != "" { + names = append(names, inner) + } + } + } + return names +} + +func (st *state) writeGallery(w http.ResponseWriter, cfg map[string]any) { + storageURL := strOpt(cfg, "storage", "") + prefix := strOpt(cfg, "prefix", "") + title := strOpt(cfg, "title", "Gallery") + downloadBase := strOpt(cfg, "download_base", "/_media") + + listed, err := storage.List(storageURL, prefix) + keys := []any{} + if err == nil { + if k, ok := listed["keys"].([]string); ok { + for _, s := range k { + keys = append(keys, s) + } + } else if k, ok := listed["keys"].([]any); ok { + keys = k + } + } + + var items strings.Builder + for _, k := range keys { + key, _ := k.(string) + if key == "" { + continue + } + href := downloadBase + "/" + strings.TrimPrefix(key, "/") + name := key + if i := strings.LastIndexByte(key, '/'); i >= 0 { + name = key[i+1:] + } + lower := strings.ToLower(name) + isImg := strings.HasSuffix(lower, ".png") || strings.HasSuffix(lower, ".jpg") || + strings.HasSuffix(lower, ".jpeg") || strings.HasSuffix(lower, ".gif") || + strings.HasSuffix(lower, ".webp") || strings.HasSuffix(lower, ".svg") + if isImg { + items.WriteString(fmt.Sprintf( + "
\"%s\"/
%s
", + esc(href), esc(href), esc(name), esc(name))) + } else { + items.WriteString(fmt.Sprintf( + "
%s
", + esc(href), esc(name))) + } + } + itemHTML := items.String() + if itemHTML == "" { + itemHTML = "

No media yet.

" + } + + html := fmt.Sprintf(` + + +%s + +

%s

%s
`, + esc(title), esc(title), itemHTML) + + etag := weakETag([]byte(html)) + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("ETag", etag) + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, html) +} diff --git a/plugins/web/internal/httpx/routes_proxy.go b/plugins/web/internal/httpx/routes_proxy.go new file mode 100644 index 0000000..e0c9047 --- /dev/null +++ b/plugins/web/internal/httpx/routes_proxy.go @@ -0,0 +1,285 @@ +package httpx + +import ( + "bytes" + "fmt" + "io" + "net/http" + "os" + "strings" + "time" +) + +type proxyRoute struct { + Upstream string + Stream bool + StripPrefix string + Methods []string + HeadersFromEnv []envHeader + TimeoutMs uint64 +} + +type envHeader struct { + Env string + Header string +} + +func parseProxyRoute(v any) proxyRoute { + m, _ := v.(map[string]any) + stream := true + if s, ok := m["stream"].(bool); ok { + stream = s + } + timeout := uint64(120_000) + if n, ok := m["timeout_ms"].(float64); ok && n > 0 { + timeout = uint64(n) + } + var methods []string + if arr, ok := m["methods"].([]any); ok { + for _, x := range arr { + if s, ok := x.(string); ok && s != "" { + methods = append(methods, strings.ToUpper(s)) + } + } + } + if len(methods) == 0 { + methods = []string{"POST"} + } + return proxyRoute{ + Upstream: strOpt(m, "upstream", ""), + Stream: stream, + StripPrefix: strOpt(m, "strip_prefix", ""), + Methods: methods, + HeadersFromEnv: parseHeadersFromEnv(m["headers_from_env"]), + TimeoutMs: timeout, + } +} + +func parseHeadersFromEnv(v any) []envHeader { + switch t := v.(type) { + case string: + return parseHeadersFromEnvStr(t) + case []any: + var out []envHeader + for _, x := range t { + if s, ok := x.(string); ok { + out = append(out, parseHeadersFromEnvStr(s)...) + } + } + return out + default: + return nil + } +} + +func parseHeadersFromEnvStr(s string) []envHeader { + var out []envHeader + for _, part := range strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == ';' }) { + part = strings.TrimSpace(part) + if part == "" { + continue + } + env, hdr, _ := strings.Cut(part, "=") + env = strings.TrimSpace(env) + hdr = strings.TrimSpace(hdr) + if env == "" || hdr == "" { + continue + } + out = append(out, envHeader{Env: env, Header: hdr}) + } + return out +} + +func (st *state) mountProxyRoutes(mux *http.ServeMux) { + for _, key := range sortedKeys(st.proxyRoutes) { + cfg := parseProxyRoute(st.proxyRoutes[key]) + path := routePathKey(key) + for _, method := range cfg.Methods { + pattern := method + " " + path + routeCfg := cfg + mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { + if r.Method != method { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + st.handleProxy(w, r, routeCfg) + }) + } + } +} + +func (st *state) handleProxy(w http.ResponseWriter, r *http.Request, route proxyRoute) { + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64<<20)) + if err != nil { + http.Error(w, fmt.Sprintf("read body: %v", err), http.StatusBadRequest) + return + } + + target, err := buildUpstreamURL(route, r.URL.Path, r.URL.RawQuery) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + + timeout := time.Duration(route.TimeoutMs) * time.Millisecond + client := &http.Client{Timeout: timeout} + + req, err := http.NewRequestWithContext(r.Context(), r.Method, target, nil) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + if len(body) > 0 { + req.Body = io.NopCloser(bytes.NewReader(body)) + req.ContentLength = int64(len(body)) + } + + for name, vals := range r.Header { + lname := strings.ToLower(name) + if isHopByHop(lname) || lname == "host" { + continue + } + for _, v := range vals { + req.Header.Add(name, v) + } + } + + for _, eh := range route.HeadersFromEnv { + val := os.Getenv(eh.Env) + if val == "" { + continue + } + if strings.EqualFold(eh.Header, "authorization") && + !strings.HasPrefix(strings.ToLower(val), "bearer ") { + val = "Bearer " + val + } + req.Header.Set(eh.Header, val) + } + + resp, err := client.Do(req) + if err != nil { + http.Error(w, fmt.Sprintf("upstream: %v", err), http.StatusBadGateway) + return + } + defer resp.Body.Close() + + for name, vals := range resp.Header { + lname := strings.ToLower(name) + if isHopByHop(lname) { + continue + } + for _, v := range vals { + w.Header().Add(name, v) + } + } + if route.Stream { + w.Header().Set("Cache-Control", "no-cache, no-transform") + w.Header().Set("X-Accel-Buffering", "no") + } + w.WriteHeader(resp.StatusCode) + if route.Stream { + _, _ = io.Copy(w, resp.Body) + return + } + out, err := io.ReadAll(resp.Body) + if err != nil { + return + } + _, _ = w.Write(out) +} + +func buildUpstreamURL(route proxyRoute, reqPath, query string) (string, error) { + base := expandEnv(route.Upstream) + if base == "" { + return "", fmt.Errorf("proxy upstream empty after env expand") + } + path := reqPath + strip := strings.TrimSpace(route.StripPrefix) + if strip != "" { + stripN := routePathKey(strip) + if strings.HasPrefix(path, stripN) { + path = path[len(stripN):] + if path == "" { + path = "/" + } else if !strings.HasPrefix(path, "/") { + path = "/" + path + } + } + } + + if !strings.Contains(base, "://") { + return "", fmt.Errorf("proxy upstream must be absolute URL, got `%s`", base) + } + + trimmed := strings.TrimRight(base, "/") + idx := strings.Index(trimmed, "://") + after := "" + if idx >= 0 { + after = trimmed[idx+3:] + } + var url string + if strings.Contains(after, "/") { + if path == "/" { + url = trimmed + } else { + url = trimmed + path + } + } else { + url = trimmed + path + } + + if query != "" { + if strings.Contains(url, "?") { + url += "&" + query + } else { + url += "?" + query + } + } + return url, nil +} + +func expandEnv(s string) string { + var out strings.Builder + b := s + i := 0 + for i < len(b) { + if b[i] == '$' { + if i+1 < len(b) && b[i+1] == '{' { + if end := strings.Index(b[i+2:], "}"); end >= 0 { + name := b[i+2 : i+2+end] + out.WriteString(os.Getenv(name)) + i += 3 + end + continue + } + } else { + start := i + 1 + end := start + for end < len(b) && (isAlnum(b[end]) || b[end] == '_') { + end++ + } + if end > start { + out.WriteString(os.Getenv(b[start:end])) + i = end + continue + } + } + } + out.WriteByte(b[i]) + i++ + } + return out.String() +} + +func isAlnum(c byte) bool { + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') +} + +func isHopByHop(name string) bool { + switch name { + case "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", + "te", "trailers", "transfer-encoding", "upgrade", "content-length": + return true + default: + return false + } +} diff --git a/plugins/web/internal/httpx/routes_ws.go b/plugins/web/internal/httpx/routes_ws.go new file mode 100644 index 0000000..aad8946 --- /dev/null +++ b/plugins/web/internal/httpx/routes_ws.go @@ -0,0 +1,93 @@ +package httpx + +import ( + "net/http" + + "github.com/gorilla/websocket" + "github.com/marqdo/marqdo/plugins/web/internal/ws" +) + +var wsUpgrader = websocket.Upgrader{ + CheckOrigin: func(r *http.Request) bool { return true }, +} + +func (st *state) mountWSRoutes(mux *http.ServeMux) { + for _, path := range sortedKeys(st.wsRoutes) { + spec := ws.ParseRouteSpec(st.wsRoutes[path]) // mode + optional room_key + routePath := path + mux.HandleFunc("GET "+routePath, func(w http.ResponseWriter, r *http.Request) { + st.handleWS(w, r, routePath, spec) + }) + } +} + +func (st *state) handleWS(w http.ResponseWriter, r *http.Request, path string, spec ws.RouteSpec) { + conn, err := wsUpgrader.Upgrade(w, r, nil) + if err != nil { + return + } + defer conn.Close() + + switch spec.Mode { + case ws.ModeEcho: + for { + mt, data, err := conn.ReadMessage() + if err != nil { + return + } + if mt == websocket.TextMessage { + if err := conn.WriteMessage(websocket.TextMessage, data); err != nil { + return + } + } else if mt == websocket.CloseMessage { + return + } + } + case ws.ModeDrain: + for { + mt, _, err := conn.ReadMessage() + if err != nil || mt == websocket.CloseMessage { + return + } + } + case ws.ModeBroadcast, ws.ModeRoom: + room := path + if spec.RoomKey != "" { + room = spec.RoomKey + } + ch := ws.JoinRoom(room) + defer ws.LeaveRoom(room, ch) + + done := make(chan struct{}) + go func() { + defer close(done) + for { + mt, data, err := conn.ReadMessage() + if err != nil { + return + } + if mt == websocket.TextMessage { + ws.PublishRoom(room, string(data)) + } else if mt == websocket.CloseMessage { + return + } + } + }() + + for { + select { + case <-done: + return + case text, ok := <-ch: + if !ok { + return + } + if err := conn.WriteMessage(websocket.TextMessage, []byte(text)); err != nil { + return + } + } + } + default: + return + } +} diff --git a/plugins/web/internal/plugin/host.go b/plugins/web/internal/plugin/host.go index ef72762..764dda9 100644 --- a/plugins/web/internal/plugin/host.go +++ b/plugins/web/internal/plugin/host.go @@ -1,5 +1,7 @@ package plugin +import "encoding/json" + // HostFns holds callbacks into the Marqdo host (valid after marqdo_plugin_init). type HostFns struct { Query func(name, argsJSON string) (string, error) @@ -26,3 +28,24 @@ func Query(name, argsJSON string) (string, error) { type errString string func (e errString) Error() string { return string(e) } + +// CallLibPath invokes `lib.member` on the site entry module (optional named args). +func CallLibPath(path string, args map[string]any) (any, error) { + payload := map[string]any{"path": path} + if len(args) > 0 { + payload["args"] = args + } + raw, err := json.Marshal(payload) + if err != nil { + return nil, err + } + out, err := Query("call_lib_path", string(raw)) + if err != nil { + return nil, err + } + var v any + if err := json.Unmarshal([]byte(out), &v); err != nil { + return nil, err + } + return v, nil +} diff --git a/plugins/web/internal/storage/storage.go b/plugins/web/internal/storage/storage.go index cd6c752..004bf33 100644 --- a/plugins/web/internal/storage/storage.go +++ b/plugins/web/internal/storage/storage.go @@ -227,6 +227,49 @@ func Delete(url, key string) (map[string]any, error) { return nil, fmt.Errorf("unknown storage backend") } +// ReadBytes loads raw object bytes for HTTP download. +// Returns found=false when the object is missing. +func ReadBytes(url, key string) ([]byte, string, string, bool, error) { + k, err := safeKey(key) + if err != nil { + return nil, "", "", false, err + } + filename := k + if i := strings.LastIndexByte(k, '/'); i >= 0 && i < len(k)-1 { + filename = k[i+1:] + } + if filename == "" { + filename = "download" + } + if isFile(url) { + root, err := fileRoot(url) + if err != nil { + return nil, "", "", false, err + } + dest, err := pathFor(root, k) + if err != nil { + return nil, "", "", false, err + } + info, err := os.Stat(dest) + if err != nil || info.IsDir() { + return nil, "", "", false, nil + } + bytes, err := os.ReadFile(dest) + if err != nil { + return nil, "", "", false, err + } + ct := "application/octet-stream" + if ctBytes, err := os.ReadFile(ctypePath(dest)); err == nil { + ct = string(ctBytes) + } + return bytes, ct, filename, true, nil + } + if isS3(url) { + return nil, "", "", false, fmt.Errorf("s3 read not implemented in Go plugin yet") + } + return nil, "", "", false, fmt.Errorf("unknown storage backend") +} + // List returns keys under optional prefix. func List(url, prefix string) (map[string]any, error) { prefix = strings.TrimPrefix(strings.TrimSpace(prefix), "/") diff --git a/plugins/web/internal/ws/route.go b/plugins/web/internal/ws/route.go index f8f93a7..08d583f 100644 --- a/plugins/web/internal/ws/route.go +++ b/plugins/web/internal/ws/route.go @@ -100,6 +100,11 @@ func RouteSpecOf(appBag map[string]any, path string) (RouteSpec, error) { return parseRouteSpec(spec), nil } +// ParseRouteSpec reads mode and room_key from a ws_routes value. +func ParseRouteSpec(spec any) RouteSpec { + return parseRouteSpec(spec) +} + func parseRouteSpec(spec any) RouteSpec { out := RouteSpec{Mode: ModeEcho} switch t := spec.(type) { diff --git a/tests/gold.rs b/tests/gold.rs index dd1dcb3..fe9d866 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -38,6 +38,8 @@ fn assert_out(path: &str, expect: &str) { } /// Build Go `plugins/web/build/libweb.so` once per test process (W-G13). +/// Also sets `MARQDO_WEB_PLUGIN` so child `marqdo` processes do not pick up a +/// stale Rust `libweb.so` from `~/.marqdo/ext`. fn ensure_web_plugin_built() { use std::sync::Once; static ONCE: Once = Once::new(); @@ -53,6 +55,22 @@ fn ensure_web_plugin_built() { status.success(), "failed to build Go libweb via scripts/build-web-plugin.sh" ); + let lib = if cfg!(windows) { + root.join("plugins").join("web").join("build").join("web.dll") + } else if cfg!(target_os = "macos") { + root.join("plugins") + .join("web") + .join("build") + .join("libweb.dylib") + } else { + root.join("plugins") + .join("web") + .join("build") + .join("libweb.so") + }; + assert!(lib.is_file(), "missing Go web plugin at {}", lib.display()); + // SAFETY: single-threaded Once; children inherit for the rest of the test process. + std::env::set_var("MARQDO_WEB_PLUGIN", &lib); }); } @@ -1902,21 +1920,25 @@ fn ext_web_middleware_live() { ); // CORS on the JSON endpoint (matching origin → allow headers). + // Compare case-insensitively: Go net/http canonicalizes header names. + let header_has = |headers: &str, needle: &str| -> bool { + headers.to_ascii_lowercase().contains(&needle.to_ascii_lowercase()) + }; let out = code(&[ "-s", "-D", "-", "-o", "/dev/null", &format!("{base}/api/posts"), "-H", "Origin: https://a.example", ]); let headers = String::from_utf8_lossy(&out.stdout); assert!( - headers.contains("access-control-allow-origin: https://a.example"), + header_has(&headers, "access-control-allow-origin: https://a.example"), "cors allow-origin headers={headers}" ); assert!( - headers.contains("access-control-allow-credentials: true"), + header_has(&headers, "access-control-allow-credentials: true"), "cors credentials headers={headers}" ); assert!( - headers.contains("access-control-expose-headers: x-total"), + header_has(&headers, "access-control-expose-headers: x-total"), "cors expose headers={headers}" ); @@ -1929,11 +1951,11 @@ fn ext_web_middleware_live() { ]); let headers = String::from_utf8_lossy(&out.stdout); assert!( - headers.contains("access-control-allow-methods: GET"), + header_has(&headers, "access-control-allow-methods: GET"), "cors preflight headers={headers}" ); assert!( - headers.contains("access-control-allow-origin"), + header_has(&headers, "access-control-allow-origin"), "cors preflight origin headers={headers}" ); @@ -1941,11 +1963,11 @@ fn ext_web_middleware_live() { let out = code(&["-s", "-D", "-", "-o", "/dev/null", &format!("{base}/")]); let headers = String::from_utf8_lossy(&out.stdout); assert!( - headers.contains("x-frame-options: DENY"), + header_has(&headers, "x-frame-options: DENY"), "security headers={headers}" ); assert!( - headers.contains("x-content-type-options: nosniff"), + header_has(&headers, "x-content-type-options: nosniff"), "security headers={headers}" ); @@ -1956,7 +1978,7 @@ fn ext_web_middleware_live() { ]); let headers = String::from_utf8_lossy(&out.stdout); assert!( - headers.contains("content-encoding: gzip"), + header_has(&headers, "content-encoding: gzip"), "gzip headers={headers}" );