diff --git a/plugins/web/abi_w6.go b/plugins/web/abi_w6.go new file mode 100644 index 0000000..b26291b --- /dev/null +++ b/plugins/web/abi_w6.go @@ -0,0 +1,361 @@ +package main + +/* +#cgo CFLAGS: -I${SRCDIR}/abi +#include "marqdo_abi_cgo.h" + +extern int web_storage_new(char *args_json, char **out_json, char **err_msg); +extern int web_storage_put(char *args_json, char **out_json, char **err_msg); +extern int web_storage_get(char *args_json, char **out_json, char **err_msg); +extern int web_storage_delete(char *args_json, char **out_json, char **err_msg); +extern int web_storage_list(char *args_json, char **out_json, char **err_msg); +extern int web_media_new(char *args_json, char **out_json, char **err_msg); +extern int web_upload_validate(char *args_json, char **out_json, char **err_msg); +extern int web_upload_save(char *args_json, char **out_json, char **err_msg); +extern int web_app_upload(char *args_json, char **out_json, char **err_msg); +extern int web_app_download(char *args_json, char **out_json, char **err_msg); +extern int web_app_gallery(char *args_json, char **out_json, char **err_msg); +extern int web_page_meta(char *args_json, char **out_json, char **err_msg); +extern int web_page_head(char *args_json, char **out_json, char **err_msg); +extern int web_page_images(char *args_json, char **out_json, char **err_msg); +extern int web_head(char *args_json, char **out_json, char **err_msg); +extern int web_images(char *args_json, char **out_json, char **err_msg); +extern int web_app_icons(char *args_json, char **out_json, char **err_msg); +*/ +import "C" + +import ( + "fmt" + + "github.com/marqdo/marqdo/plugins/web/internal/app" + "github.com/marqdo/marqdo/plugins/web/internal/assets" + "github.com/marqdo/marqdo/plugins/web/internal/storage" + "github.com/marqdo/marqdo/plugins/web/internal/upload" +) + +func storageURLOf(args map[string]any, keys ...string) (string, error) { + for _, k := range keys { + if v, ok := args[k]; ok { + if s, err := app.StorageURL(v); err == nil { + return s, nil + } + } + } + return "", fmt.Errorf("missing storage url") +} + +//export web_storage_new +func web_storage_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + url, _ := argStr(args, "url", "地址") + if url == "" { + url = "file:data/blobs" + } + out, err := storage.Open(url) + return replyJSON(outJSON, errMsg, out, err) +} + +//export web_storage_put +func web_storage_put(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + url, err := argStrReq(args, "url") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + key, err := argStrReq(args, "key", "键") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + var body, path, ct *string + if s, ok := argStr(args, "body", "正文"); ok { + body = &s + } + if s, ok := argStr(args, "path", "路径"); ok { + path = &s + } + if s, ok := argStr(args, "content_type", "类型"); ok { + ct = &s + } + out, err := storage.Put(url, key, body, path, ct) + return replyJSON(outJSON, errMsg, out, err) +} + +//export web_storage_get +func web_storage_get(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + url, err := argStrReq(args, "url") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + key, err := argStrReq(args, "key", "键") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + out, err := storage.Get(url, key) + return replyJSON(outJSON, errMsg, out, err) +} + +//export web_storage_delete +func web_storage_delete(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + url, err := argStrReq(args, "url") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + key, err := argStrReq(args, "key", "键") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + out, err := storage.Delete(url, key) + return replyJSON(outJSON, errMsg, out, err) +} + +//export web_storage_list +func web_storage_list(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + url, err := argStrReq(args, "url") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + prefix, _ := argStr(args, "prefix", "前缀") + out, err := storage.List(url, prefix) + return replyJSON(outJSON, errMsg, out, err) +} + +//export web_media_new +func web_media_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + st := args["storage"] + if st == nil { + st = args["存储"] + } + return replyJSON(outJSON, errMsg, map[string]any{"_type": "media", "storage": st}, nil) +} + +//export web_upload_validate +func web_upload_validate(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + filename, err := argStrReq(args, "filename", "文件名") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + ct, _ := argStr(args, "content_type", "类型") + if ct == "" { + ct = "application/octet-stream" + } + size := argUint64(args, 0, "size", "大小") + if size == 0 { + return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `size`")) + } + maxBytes := argUint64(args, 5_242_880, "max_bytes", "最大字节") + types := args["types"] + if types == nil { + types = args["允许"] + } + out := upload.Validate(filename, ct, size, maxBytes, types) + return replyJSON(outJSON, errMsg, out, nil) +} + +//export web_upload_save +func web_upload_save(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + storageURL, err := storageURLOf(args, "storage", "url", "storage_url") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + path, err := argStrReq(args, "path", "路径") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + var key, ct, prefix *string + if s, ok := argStr(args, "key", "键"); ok && s != "" { + key = &s + } + if s, ok := argStr(args, "content_type", "类型"); ok { + ct = &s + } + if s, ok := argStr(args, "prefix", "前缀"); ok { + prefix = &s + } + out, err := upload.Save(storageURL, key, path, ct, prefix) + return replyJSON(outJSON, errMsg, out, err) +} + +//export web_app_upload +func web_app_upload(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + path, _ := argStr(args, "path", "路径") + field, _ := argStr(args, "field") + storageURL, err := storageURLOf(args, "storage", "存储") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + prefix, _ := argStr(args, "prefix", "前缀") + maxBytes := argUint64(args, 5_242_880, "max_bytes", "最大字节") + types := args["types"] + if types == nil { + types = args["允许"] + } + if types == nil { + types = nil // explicit null ok + } + out, err := app.Upload(asPageMap(args["app"]), path, field, storageURL, prefix, maxBytes, types) + return replyJSON(outJSON, errMsg, out, err) +} + +//export web_app_download +func web_app_download(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + path, _ := argStr(args, "path", "路径") + storageURL, err := storageURLOf(args, "storage", "存储") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + disposition, _ := argStr(args, "disposition") + out, err := app.Download(asPageMap(args["app"]), path, storageURL, disposition) + return replyJSON(outJSON, errMsg, out, err) +} + +//export web_app_gallery +func web_app_gallery(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + path, _ := argStr(args, "path", "路径") + storageURL, err := storageURLOf(args, "storage", "存储") + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + prefix, _ := argStr(args, "prefix", "前缀") + title, _ := argStr(args, "title", "标题") + downloadBase, _ := argStr(args, "download_base", "media", "下载基址") + out, err := app.Gallery(asPageMap(args["app"]), path, storageURL, prefix, title, downloadBase) + return replyJSON(outJSON, errMsg, out, err) +} + +//export web_page_meta +func web_page_meta(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + pageBag := asPageMap(args["page"]) + meta := args["meta"] + if meta == nil { + meta = args["table"] + } + if meta == nil { + meta = args["元数据"] + } + out := assets.AttachMeta(pageBag, meta) + return replyJSON(outJSON, errMsg, out, nil) +} + +//export web_page_head +func web_page_head(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + pageBag := asPageMap(args["page"]) + table := args["table"] + if table == nil { + table = args["head"] + } + if table == nil { + table = args["表"] + } + out := assets.AttachHead(pageBag, table) + return replyJSON(outJSON, errMsg, out, nil) +} + +//export web_page_images +func web_page_images(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + pageBag := asPageMap(args["page"]) + table := args["table"] + if table == nil { + table = args["images"] + } + out := assets.AttachImages(pageBag, table) + return replyJSON(outJSON, errMsg, out, nil) +} + +//export web_head +func web_head(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + table := args["table"] + if table == nil { + table = args["head"] + } + if table == nil { + table = args["表"] + } + html := assets.MakeHeadHTML(table) + return replyJSON(outJSON, errMsg, html, nil) +} + +//export web_images +func web_images(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + table := args["table"] + if table == nil { + table = args["images"] + } + html := assets.MakeImagesHTML(table) + return replyJSON(outJSON, errMsg, html, nil) +} + +//export web_app_icons +func web_app_icons(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + table := args["table"] + if table == nil { + table = args["icons"] + } + out, err := app.Icons(asPageMap(args["app"]), table) + return replyJSON(outJSON, errMsg, out, err) +} diff --git a/plugins/web/internal/app/app.go b/plugins/web/internal/app/app.go index 3f235a0..c597cc5 100644 --- a/plugins/web/internal/app/app.go +++ b/plugins/web/internal/app/app.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/marqdo/marqdo/plugins/web/internal/assets" "github.com/marqdo/marqdo/plugins/web/internal/session" ) @@ -421,3 +422,134 @@ func boolish(v any) bool { } return false } + +// StorageURL extracts a storage url string or handle map. +func StorageURL(v any) (string, error) { + if v == nil { + return "", fmt.Errorf("missing storage") + } + if s, ok := v.(string); ok && strings.TrimSpace(s) != "" { + return strings.TrimSpace(s), nil + } + if m, ok := v.(map[string]any); ok { + if s, ok := m["url"].(string); ok && strings.TrimSpace(s) != "" { + return strings.TrimSpace(s), nil + } + } + return "", fmt.Errorf("storage must be a url string or storage handle") +} + +// Upload registers an upload route on the app bag (offline stub; live HTTP in listen). +func Upload(appBag map[string]any, path, field, storageURL, prefix string, maxBytes uint64, types any) (map[string]any, error) { + out := clone(appBag) + if path == "" { + path = "/_upload" + } + path, err := NormalizeRoutePath(path, out) + if err != nil { + return nil, err + } + if field == "" { + field = "file" + } + if prefix == "" { + prefix = "uploads/" + } + routes := map[string]any{} + if r, ok := out["upload_routes"].(map[string]any); ok { + routes = clone(r) + } + entry := map[string]any{ + "field": field, + "storage_url": storageURL, + "prefix": prefix, + "max_bytes": float64(maxBytes), + } + if types != nil { + entry["types"] = types + } + routes[path] = entry + out["upload_routes"] = routes + return out, nil +} + +// Download registers a media download route with {key} capture. +func Download(appBag map[string]any, path, storageURL, disposition string) (map[string]any, error) { + path = strings.TrimSpace(path) + if path == "" { + path = "/_media/{*key}" + } + if !strings.HasPrefix(path, "/") { + path = "/" + path + } + for len(path) > 1 && strings.HasSuffix(path, "/") { + path = strings.TrimSuffix(path, "/") + } + if !strings.Contains(path, "{") { + return nil, fmt.Errorf("download path must include a `{key}` or `{*key}` capture") + } + if disposition == "" { + disposition = "attachment" + } + if strings.TrimSpace(storageURL) == "" { + return nil, fmt.Errorf("missing storage") + } + out := clone(appBag) + routes := map[string]any{} + if r, ok := out["download_routes"].(map[string]any); ok { + routes = clone(r) + } + routes[path] = map[string]any{ + "storage_url": storageURL, + "disposition": disposition, + } + out["download_routes"] = routes + return out, nil +} + +// Gallery registers a gallery page route (offline bag; live HTML in listen). +func Gallery(appBag map[string]any, path, storageURL, prefix, title, downloadBase string) (map[string]any, error) { + out := clone(appBag) + if path == "" { + path = "/gallery" + } + var err error + path, err = NormalizeRoutePath(path, out) + if err != nil { + return nil, err + } + if prefix == "" { + prefix = "uploads/" + } + if title == "" { + title = "Gallery" + } + if downloadBase == "" { + downloadBase = "/_media" + } + storageURL, err = StorageURL(storageURL) + if err != nil { + return nil, err + } + routes := map[string]any{} + if r, ok := out["gallery_routes"].(map[string]any); ok { + routes = clone(r) + } + routes[path] = map[string]any{ + "storage": storageURL, + "prefix": prefix, + "title": title, + "download_base": downloadBase, + } + out["gallery_routes"] = routes + return out, nil +} + +// Icons normalizes icons table → app.icons + app.site_head. +func Icons(appBag map[string]any, table any) (map[string]any, error) { + out := clone(appBag) + icons, siteHead, _ := assets.NormalizeIcons(table) + out["icons"] = icons + out["site_head"] = assets.HeadLinksToJSON(siteHead) + return out, nil +} diff --git a/plugins/web/internal/assets/assets.go b/plugins/web/internal/assets/assets.go new file mode 100644 index 0000000..431374c --- /dev/null +++ b/plugins/web/internal/assets/assets.go @@ -0,0 +1,585 @@ +// Package assets ports head/images/icons HTML assembly (W8 / W-G6). +package assets + +import ( + "fmt" + "path" + "strings" + + "github.com/marqdo/marqdo/plugins/web/internal/table" +) + +// HeadLink is one or `, esc(href)) + s.WriteString(tag) + continue + } + tag := fmt.Sprintf(``, esc(loading)) + inner := img + if href != "" { + inner = fmt.Sprintf(`%s`, esc(href), img) + } + figClass := "mq-img" + if class != "" { + figClass = "mq-img " + class + } + figures.WriteString(fmt.Sprintf(`
%s`, figClass, inner)) + if caption != "" { + figures.WriteString(fmt.Sprintf("
%s
", esc(caption))) + } + figures.WriteString("
") + } + if figures.Len() == 0 { + return "" + } + return `
` + figures.String() + `
` +} + +// AttachHead merges head table links onto page.head. +func AttachHead(page map[string]any, table any) map[string]any { + out := cloneMap(page) + links := AsHeadLinks(table) + existing := HeadLinksFromJSON(out["head"]) + for _, link := range links { + dup := false + for _, e := range existing { + if e.Href == link.Href && strings.EqualFold(e.Rel, link.Rel) { + dup = true + break + } + } + if !dup { + existing = append(existing, link) + } + } + out["head"] = HeadLinksToJSON(existing) + return out +} + +// AttachImages appends images_html on page. +func AttachImages(page map[string]any, table any) map[string]any { + out := cloneMap(page) + html := MakeImagesHTML(table) + prev, _ := out["images_html"].(string) + switch { + case prev == "": + out["images_html"] = html + case html == "": + out["images_html"] = prev + default: + out["images_html"] = prev + html + } + return out +} + +// AttachMeta sets page.meta from SEO table. +func AttachMeta(page map[string]any, meta any) map[string]any { + out := cloneMap(page) + out["meta"] = table.AsMetaMap(meta) + return out +} + +func cloneMap(m map[string]any) map[string]any { + if m == nil { + return map[string]any{} + } + out := make(map[string]any, len(m)) + for k, v := range m { + out[k] = v + } + return out +} diff --git a/plugins/web/internal/assets/assets_test.go b/plugins/web/internal/assets/assets_test.go new file mode 100644 index 0000000..3f80d2a --- /dev/null +++ b/plugins/web/internal/assets/assets_test.go @@ -0,0 +1,72 @@ +package assets + +import ( + "strings" + "testing" +) + +func TestImagesBasic(t *testing.T) { + table := []any{ + map[string]any{"源": "/a.png", "替代": "A", "类": "logo", "加载": "eager"}, + } + h := MakeImagesHTML(table) + if !strings.Contains(h, "mq-images") { + t.Fatalf("missing mq-images: %s", h) + } + if !strings.Contains(h, `src="/a.png"`) { + t.Fatalf("missing src: %s", h) + } + if !strings.Contains(h, `loading="eager"`) { + t.Fatalf("missing loading: %s", h) + } + if !strings.Contains(h, `class="mq-img logo"`) { + t.Fatalf("missing class: %s", h) + } +} + +func TestHeadScriptAndIcon(t *testing.T) { + table := []any{ + map[string]any{"关系": "icon", "地址": "/favicon.ico", "类型": "image/x-icon"}, + map[string]any{"关系": "script", "地址": "/static/a.js"}, + } + h := MakeHeadHTML(table) + if !strings.Contains(h, `rel="icon"`) { + t.Fatalf("missing icon: %s", h) + } + if !strings.Contains(h, ``) { + t.Fatalf("missing script: %s", h) + } + if strings.Contains(h, " defer") { + t.Fatalf("unexpected defer: %s", h) + } +} + +func TestHeadDeferVersion(t *testing.T) { + table := []any{ + map[string]any{"关系": "script", "地址": "/static/a.js", "推迟": true, "版本": "3"}, + } + links := AsHeadLinks(table) + h := RenderHeadLinksWithVersion(links, "2026-09-04") + if !strings.Contains(h, ``) { + t.Fatalf("defer+version: %s", h) + } +} + +func TestNormalizeIcons(t *testing.T) { + table := []any{ + map[string]any{ + "path": "web-fixtures/public/favicon.png", "rel": "icon", + "type": "image/png", "sizes": "32x32", "url": "/favicon.ico", + }, + } + icons, head, routes := NormalizeIcons(table) + if len(icons) != 1 { + t.Fatalf("icons=%d", len(icons)) + } + if len(head) == 0 { + t.Fatal("expected site head") + } + if len(routes) == 0 { + t.Fatal("expected routes") + } +} diff --git a/plugins/web/internal/storage/storage.go b/plugins/web/internal/storage/storage.go new file mode 100644 index 0000000..cd6c752 --- /dev/null +++ b/plugins/web/internal/storage/storage.go @@ -0,0 +1,281 @@ +// Package storage ports file: blob storage from the Rust web plugin (W-G6). +package storage + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "unicode/utf8" +) + +func isFile(url string) bool { + u := strings.ToLower(strings.TrimSpace(url)) + return strings.HasPrefix(u, "file:") || strings.HasPrefix(u, "file://") +} + +func isS3(url string) bool { + return strings.HasPrefix(strings.ToLower(strings.TrimSpace(url)), "s3://") +} + +func fileRoot(url string) (string, error) { + raw := strings.TrimSpace(url) + raw = strings.TrimPrefix(raw, "file://") + raw = strings.TrimPrefix(raw, "file:") + if raw == "" { + return "", nil + } + if err := os.MkdirAll(raw, 0o755); err != nil { + return "", fmt.Errorf("storage mkdir: %w", err) + } + return raw, nil +} + +func safeKey(key string) (string, error) { + k := strings.TrimPrefix(strings.TrimSpace(key), "/") + if k == "" { + return "", fmt.Errorf("storage key is empty") + } + if strings.Contains(k, "..") { + return "", fmt.Errorf("storage key must not contain `..`") + } + return strings.ReplaceAll(k, `\`, "/"), nil +} + +func pathFor(root, key string) (string, error) { + k, err := safeKey(key) + if err != nil { + return "", err + } + return filepath.Join(root, filepath.FromSlash(k)), nil +} + +func ctypePath(dest string) string { + return dest + ".ctype" +} + +// Open validates and describes a storage backend. +func Open(url string) (map[string]any, error) { + url = strings.TrimSpace(url) + if isFile(url) { + if _, err := fileRoot(url); err != nil { + return nil, err + } + return map[string]any{ + "_type": "storage", + "url": url, + "backend": "file", + }, nil + } + if isS3(url) { + rest := strings.TrimPrefix(url, "s3://") + rest = strings.TrimPrefix(rest, "S3://") + bucket := rest + if i := strings.IndexByte(bucket, '?'); i >= 0 { + bucket = bucket[:i] + } + if bucket == "" { + return nil, fmt.Errorf("s3 url missing bucket (s3://bucket?endpoint=…)") + } + return map[string]any{ + "_type": "storage", + "url": url, + "backend": "s3", + }, nil + } + return nil, fmt.Errorf("storage url must be `file:…` or `s3://bucket?…`, got `%s`", url) +} + +func loadBytes(body *string, path *string) ([]byte, error) { + if path != nil && *path != "" { + b, err := os.ReadFile(*path) + if err != nil { + return nil, fmt.Errorf("read path `%s`: %w", *path, err) + } + return b, nil + } + if body != nil { + return []byte(*body), nil + } + return nil, fmt.Errorf("storage.put needs `body` or `path`") +} + +// Put stores bytes from body or local path. +func Put(url, key string, body, path, contentType *string) (map[string]any, error) { + bytes, err := loadBytes(body, path) + if err != nil { + return nil, err + } + ct := "application/octet-stream" + if contentType != nil && strings.TrimSpace(*contentType) != "" { + ct = strings.TrimSpace(*contentType) + } + return PutBytes(url, key, bytes, ct) +} + +// PutBytes persists raw bytes (multipart upload / binary save). +func PutBytes(url, key string, data []byte, contentType string) (map[string]any, error) { + ct := strings.TrimSpace(contentType) + if ct == "" { + ct = "application/octet-stream" + } + if isFile(url) { + root, err := fileRoot(url) + if err != nil { + return nil, err + } + dest, err := pathFor(root, key) + if err != nil { + return nil, err + } + if parent := filepath.Dir(dest); parent != "" && parent != "." { + if err := os.MkdirAll(parent, 0o755); err != nil { + return nil, err + } + } + if err := os.WriteFile(dest, data, 0o644); err != nil { + return nil, err + } + _ = os.WriteFile(ctypePath(dest), []byte(ct), 0o644) + return map[string]any{ + "ok": true, + "key": key, + "size": float64(len(data)), + "content_type": ct, + }, nil + } + if isS3(url) { + return nil, fmt.Errorf("s3 put not implemented in Go plugin yet") + } + return nil, fmt.Errorf("unknown storage backend") +} + +// Get reads an object; JSON shape matches Rust gold. +func Get(url, key string) (map[string]any, error) { + if isFile(url) { + root, err := fileRoot(url) + if err != nil { + return nil, err + } + dest, err := pathFor(root, key) + if err != nil { + return nil, err + } + info, err := os.Stat(dest) + if err != nil || info.IsDir() { + return map[string]any{"ok": false}, nil + } + bytes, err := os.ReadFile(dest) + if err != nil { + return nil, err + } + ctBytes, err := os.ReadFile(ctypePath(dest)) + ct := "application/octet-stream" + if err == nil { + ct = string(ctBytes) + } + if utf8.Valid(bytes) { + s := string(bytes) + return map[string]any{ + "ok": true, + "key": key, + "body": s, + "content_type": ct, + "size": float64(len(s)), + }, nil + } + return map[string]any{ + "ok": true, + "key": key, + "path": dest, + "content_type": ct, + "size": float64(len(bytes)), + "binary": true, + }, nil + } + if isS3(url) { + return nil, fmt.Errorf("s3 get not implemented in Go plugin yet") + } + return nil, fmt.Errorf("unknown storage backend") +} + +// Delete removes an object if present. +func Delete(url, key string) (map[string]any, error) { + if isFile(url) { + root, err := fileRoot(url) + if err != nil { + return nil, err + } + dest, err := pathFor(root, key) + if err != nil { + return nil, err + } + info, err := os.Stat(dest) + ok := false + if err == nil && !info.IsDir() { + if err := os.Remove(dest); err != nil { + return nil, err + } + _ = os.Remove(ctypePath(dest)) + ok = true + } + return map[string]any{"ok": ok}, nil + } + if isS3(url) { + return nil, fmt.Errorf("s3 delete not implemented in Go plugin yet") + } + return nil, 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), "/") + if isFile(url) { + root, err := fileRoot(url) + if err != nil { + return nil, err + } + var keys []string + if err := walkKeys(root, root, prefix, &keys); err != nil { + return nil, err + } + return map[string]any{ + "ok": true, + "keys": keys, + "count": float64(len(keys)), + }, nil + } + if isS3(url) { + return nil, fmt.Errorf("s3 list not implemented in Go plugin yet") + } + return nil, fmt.Errorf("unknown storage backend") +} + +func walkKeys(root, dir, prefix string, out *[]string) error { + entries, err := os.ReadDir(dir) + if err != nil { + return nil + } + for _, ent := range entries { + name := ent.Name() + if strings.HasSuffix(name, ".ctype") { + continue + } + path := filepath.Join(dir, name) + if ent.IsDir() { + if err := walkKeys(root, path, prefix, out); err != nil { + return err + } + continue + } + rel, err := filepath.Rel(root, path) + if err != nil { + return err + } + rel = filepath.ToSlash(rel) + if prefix == "" || strings.HasPrefix(rel, prefix) { + *out = append(*out, rel) + } + } + return nil +} diff --git a/plugins/web/internal/storage/storage_test.go b/plugins/web/internal/storage/storage_test.go new file mode 100644 index 0000000..21d023d --- /dev/null +++ b/plugins/web/internal/storage/storage_test.go @@ -0,0 +1,62 @@ +package storage + +import ( + "os" + "path/filepath" + "testing" +) + +func TestFilePutGetListDelete(t *testing.T) { + dir := t.TempDir() + url := "file:" + dir + if _, err := Open(url); err != nil { + t.Fatal(err) + } + body := "hi" + if _, err := Put(url, "a/hello.txt", &body, nil, strPtr("text/plain")); err != nil { + t.Fatal(err) + } + got, err := Get(url, "a/hello.txt") + if err != nil { + t.Fatal(err) + } + if got["ok"] != true || got["body"] != "hi" { + t.Fatalf("get: %#v", got) + } + ls, err := List(url, "a/") + if err != nil { + t.Fatal(err) + } + if ls["count"].(float64) != 1 { + t.Fatalf("list: %#v", ls) + } + if _, err := Delete(url, "a/hello.txt"); err != nil { + t.Fatal(err) + } + got2, _ := Get(url, "a/hello.txt") + if got2["ok"] != false { + t.Fatalf("expected missing after delete: %#v", got2) + } +} + +func TestPutFromPath(t *testing.T) { + dir := t.TempDir() + src := filepath.Join(dir, "src.txt") + if err := os.WriteFile(src, []byte("hello-upload"), 0o644); err != nil { + t.Fatal(err) + } + url := "file:" + filepath.Join(dir, "blobs") + p := src + if _, err := Put(url, "x.txt", nil, &p, strPtr("text/plain")); err != nil { + t.Fatal(err) + } + got, err := Get(url, "x.txt") + if err != nil { + t.Fatal(err) + } + if got["body"] != "hello-upload" { + t.Fatalf("body=%v", got["body"]) + } +} + +func strPtr(s string) *string { return &s } diff --git a/plugins/web/internal/upload/upload.go b/plugins/web/internal/upload/upload.go new file mode 100644 index 0000000..dde0cf6 --- /dev/null +++ b/plugins/web/internal/upload/upload.go @@ -0,0 +1,273 @@ +// Package upload ports media validation and offline save (W-G6). +package upload + +import ( + "crypto/rand" + "encoding/hex" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "github.com/marqdo/marqdo/plugins/web/internal/storage" +) + +// Validate checks size / MIME / extension against optional allowlist table. +func Validate(filename, contentType string, size, maxBytes uint64, types any) map[string]any { + if size > maxBytes { + return map[string]any{ + "ok": false, + "error": fmt.Sprintf("file too large: %d > %d", size, maxBytes), + } + } + name := strings.TrimSpace(filename) + if name == "" { + return map[string]any{"ok": false, "error": "empty filename"} + } + if strings.Contains(name, "..") || strings.Contains(name, "/") || strings.Contains(name, `\`) { + return map[string]any{"ok": false, "error": "unsafe filename"} + } + ct := strings.ToLower(strings.TrimSpace(contentType)) + if i := strings.IndexByte(ct, ';'); i >= 0 { + ct = strings.TrimSpace(ct[:i]) + } + ext := "" + if i := strings.LastIndexByte(name, '.'); i >= 0 && i < len(name)-1 { + ext = strings.ToLower(name[i+1:]) + } + if types != nil && !typesAllow(types, ct, ext) { + return map[string]any{ + "ok": false, + "error": fmt.Sprintf("type not allowed: content_type=%s ext=%s", ct, ext), + } + } + outCT := ct + if outCT == "" { + outCT = "application/octet-stream" + } + return map[string]any{ + "ok": true, + "filename": name, + "content_type": outCT, + "size": float64(size), + "ext": ext, + } +} + +func typesAllow(types any, contentType, ext string) bool { + if types == nil { + return true + } + switch t := types.(type) { + case string: + s := strings.TrimSpace(t) + if s == "" { + return true + } + for _, p := range strings.Split(s, ",") { + p = strings.ToLower(strings.TrimSpace(p)) + if p != "" && p == contentType { + return true + } + } + return false + case []any: + if len(t) == 0 { + return true + } + for _, row := range t { + if rowAllows(row, contentType, ext) { + return true + } + } + return false + case map[string]any: + colMime := first(t, "类型", "type", "mime") + colExt := first(t, "扩展名", "ext", "extension") + if ma, ok := colMime.([]any); ok { + var exts []string + switch ev := colExt.(type) { + case []any: + for _, x := range ev { + exts = append(exts, strings.ToLower(cellStr(x))) + } + case string: + exts = []string{strings.ToLower(ev)} + } + if len(ma) == 0 { + return true + } + for i, mimeV := range ma { + mime := strings.ToLower(strings.TrimSpace(cellStr(mimeV))) + rowExt := "" + if i < len(exts) { + rowExt = exts[i] + } + mimeOK := mime == "" || mime == contentType + extOK := rowExt == "" || extMatches(rowExt, ext) + if mimeOK && extOK { + return true + } + } + return false + } + if colMime != nil || colExt != nil { + return rowAllows(t, contentType, ext) + } + if len(t) == 0 { + return true + } + for mime, extsV := range t { + exts := extList(extsV) + mimeOK := strings.TrimSpace(mime) == "" || strings.EqualFold(mime, contentType) + extOK := exts == "" || extMatches(exts, ext) + if mimeOK && extOK { + return true + } + } + return false + default: + return true + } +} + +func rowAllows(row any, contentType, ext string) bool { + switch t := row.(type) { + case string: + return strings.EqualFold(strings.TrimSpace(t), contentType) + case map[string]any: + mime := strings.ToLower(strings.TrimSpace(firstStr(t, "类型", "type", "mime"))) + exts := strings.ToLower(strings.TrimSpace(firstStr(t, "扩展名", "ext", "extension"))) + mimeOK := mime == "" || mime == contentType + extOK := exts == "" || extMatches(exts, ext) + return mimeOK && extOK + default: + return false + } +} + +func extMatches(exts, ext string) bool { + for _, e := range strings.Split(exts, ",") { + e = strings.TrimSpace(strings.TrimPrefix(e, ".")) + if e == ext { + return true + } + } + return false +} + +func extList(v any) string { + switch t := v.(type) { + case string: + return strings.ToLower(strings.TrimSpace(t)) + case []any: + parts := make([]string, 0, len(t)) + for _, x := range t { + if s, ok := x.(string); ok { + parts = append(parts, s) + } + } + return strings.ToLower(strings.Join(parts, ",")) + default: + return "" + } +} + +func first(m map[string]any, keys ...string) any { + for _, k := range keys { + if v, ok := m[k]; ok { + return v + } + } + return nil +} + +func firstStr(m map[string]any, keys ...string) string { + return cellStr(first(m, keys...)) +} + +func cellStr(v any) string { + switch t := v.(type) { + case nil: + return "" + case string: + return t + case float64: + if t == float64(int64(t)) { + return fmt.Sprintf("%d", int64(t)) + } + return fmt.Sprintf("%v", t) + case bool: + if t { + return "true" + } + return "false" + default: + return fmt.Sprint(t) + } +} + +// MakeKey builds prefix + timestamp-random + sanitized basename. +func MakeKey(prefix, filename string) (string, error) { + base := filename + if i := strings.LastIndexAny(filename, `/\`); i >= 0 { + base = filename[i+1:] + } + base = strings.TrimSpace(base) + if base == "" { + return "", fmt.Errorf("empty filename") + } + var safe strings.Builder + for _, c := range base { + if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || + c == '.' || c == '-' || c == '_' { + safe.WriteRune(c) + } else { + safe.WriteRune('_') + } + } + s := safe.String() + if strings.Contains(s, "..") { + return "", fmt.Errorf("unsafe filename") + } + pref := strings.ReplaceAll(strings.TrimPrefix(strings.TrimSpace(prefix), "/"), `\`, "/") + if pref != "" && !strings.HasSuffix(pref, "/") { + pref += "/" + } + if strings.Contains(pref, "..") { + return "", fmt.Errorf("prefix must not contain `..`") + } + rnd := make([]byte, 4) + if _, err := rand.Read(rnd); err != nil { + return "", err + } + return fmt.Sprintf("%s%d-%s-%s", pref, time.Now().Unix(), hex.EncodeToString(rnd), s), nil +} + +// Save reads local path bytes into storage under key (or auto key). +func Save(storageURL string, key *string, path string, contentType, prefix *string) (map[string]any, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("read `%s`: %w", path, err) + } + filename := filepath.Base(path) + ct := "application/octet-stream" + if contentType != nil && strings.TrimSpace(*contentType) != "" { + ct = strings.TrimSpace(*contentType) + } + objectKey := "" + if key != nil && strings.TrimSpace(*key) != "" { + objectKey = *key + } else { + p := "uploads/" + if prefix != nil && strings.TrimSpace(*prefix) != "" { + p = *prefix + } + objectKey, err = MakeKey(p, filename) + if err != nil { + return nil, err + } + } + return storage.PutBytes(storageURL, objectKey, data, ct) +} diff --git a/plugins/web/internal/upload/upload_test.go b/plugins/web/internal/upload/upload_test.go new file mode 100644 index 0000000..8b2232d --- /dev/null +++ b/plugins/web/internal/upload/upload_test.go @@ -0,0 +1,48 @@ +package upload + +import ( + "os" + "path/filepath" + "testing" +) + +func TestValidateAllowReject(t *testing.T) { + types := []any{ + map[string]any{"类型": "image/png", "扩展名": "png"}, + map[string]any{"类型": "text/plain", "扩展名": "txt"}, + } + ok := Validate("a.png", "image/png", 100, 1000, types) + if ok["ok"] != true { + t.Fatalf("expected ok: %#v", ok) + } + bad := Validate("a.exe", "application/octet-stream", 100, 1000, types) + if bad["ok"] != false { + t.Fatalf("expected reject: %#v", bad) + } + big := Validate("a.png", "image/png", 9000, 1000, types) + if big["ok"] != false { + t.Fatalf("expected size reject: %#v", big) + } +} + +func TestSaveRoundtrip(t *testing.T) { + dir := t.TempDir() + src := filepath.Join(dir, "sample.txt") + if err := os.WriteFile(src, []byte("hello-upload"), 0o644); err != nil { + t.Fatal(err) + } + url := "file:" + filepath.Join(dir, "blobs") + prefix := "smoke/" + ct := "text/plain" + saved, err := Save(url, nil, src, &ct, &prefix) + if err != nil { + t.Fatal(err) + } + if saved["ok"] != true { + t.Fatalf("save: %#v", saved) + } + key, _ := saved["key"].(string) + if key == "" { + t.Fatal("missing key") + } +} diff --git a/plugins/web/plugin.go b/plugins/web/plugin.go index 2a144cb..a0cef35 100644 --- a/plugins/web/plugin.go +++ b/plugins/web/plugin.go @@ -97,6 +97,23 @@ extern int web_auth_logout(char *args_json, char **out_json, char **err_msg); extern int web_auth_new(char *args_json, char **out_json, char **err_msg); extern int web_app_auth(char *args_json, char **out_json, char **err_msg); extern int web_app_gate(char *args_json, char **out_json, char **err_msg); +extern int web_storage_new(char *args_json, char **out_json, char **err_msg); +extern int web_storage_put(char *args_json, char **out_json, char **err_msg); +extern int web_storage_get(char *args_json, char **out_json, char **err_msg); +extern int web_storage_delete(char *args_json, char **out_json, char **err_msg); +extern int web_storage_list(char *args_json, char **out_json, char **err_msg); +extern int web_media_new(char *args_json, char **out_json, char **err_msg); +extern int web_upload_validate(char *args_json, char **out_json, char **err_msg); +extern int web_upload_save(char *args_json, char **out_json, char **err_msg); +extern int web_app_upload(char *args_json, char **out_json, char **err_msg); +extern int web_app_download(char *args_json, char **out_json, char **err_msg); +extern int web_app_gallery(char *args_json, char **out_json, char **err_msg); +extern int web_page_meta(char *args_json, char **out_json, char **err_msg); +extern int web_page_head(char *args_json, char **out_json, char **err_msg); +extern int web_page_images(char *args_json, char **out_json, char **err_msg); +extern int web_head(char *args_json, char **out_json, char **err_msg); +extern int web_images(char *args_json, char **out_json, char **err_msg); +extern int web_app_icons(char *args_json, char **out_json, char **err_msg); static int register_core(void) { if (host_register((char *)"web_go_ready", (char *)"", web_go_ready) != 0) return 1; @@ -147,6 +164,23 @@ static int register_core(void) { if (host_register((char *)"web_auth_new", (char *)"users,session_ttl", web_auth_new) != 0) return 1; if (host_register((char *)"web_app_auth", (char *)"app,users,session_ttl,admin_prefix,login_redirect,logout_redirect,login_path", web_app_auth) != 0) return 1; if (host_register((char *)"web_app_gate", (char *)"app,path,roles,match,on_deny,exclude", web_app_gate) != 0) return 1; + if (host_register((char *)"web_storage_new", (char *)"url", web_storage_new) != 0) return 1; + if (host_register((char *)"web_storage_put", (char *)"url,key,body,path,content_type", web_storage_put) != 0) return 1; + if (host_register((char *)"web_storage_get", (char *)"url,key", web_storage_get) != 0) return 1; + if (host_register((char *)"web_storage_delete", (char *)"url,key", web_storage_delete) != 0) return 1; + if (host_register((char *)"web_storage_list", (char *)"url,prefix", web_storage_list) != 0) return 1; + if (host_register((char *)"web_media_new", (char *)"storage", web_media_new) != 0) return 1; + if (host_register((char *)"web_upload_validate", (char *)"filename,content_type,size,max_bytes,types", web_upload_validate) != 0) return 1; + if (host_register((char *)"web_upload_save", (char *)"storage,path,key,content_type,prefix", web_upload_save) != 0) return 1; + if (host_register((char *)"web_app_upload", (char *)"app,path,field,storage,prefix,max_bytes,types", web_app_upload) != 0) return 1; + if (host_register((char *)"web_app_download", (char *)"app,path,storage,disposition", web_app_download) != 0) return 1; + if (host_register((char *)"web_app_gallery", (char *)"app,path,storage,prefix,title,download_base", web_app_gallery) != 0) return 1; + if (host_register((char *)"web_page_meta", (char *)"page,meta", web_page_meta) != 0) return 1; + if (host_register((char *)"web_page_head", (char *)"page,table", web_page_head) != 0) return 1; + if (host_register((char *)"web_page_images", (char *)"page,table", web_page_images) != 0) return 1; + if (host_register((char *)"web_head", (char *)"table", web_head) != 0) return 1; + if (host_register((char *)"web_images", (char *)"table", web_images) != 0) return 1; + if (host_register((char *)"web_app_icons", (char *)"app,table", web_app_icons) != 0) return 1; return 0; } */