Release 2.7.0: executable handbooks and native user-site workflows
This commit is contained in:
1 parent
aa0c4d0f55
commit
d9aef957f7
562 files changed
+21064
-20387
No files matched your search
+60
-29
@@ -35,10 +35,6 @@ func web_render_nodes(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
frag, err := artifact.RenderNodes(args["nodes"])
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
pg := asPageMap(args["page"])
|
||||
title := ""
|
||||
if pg != nil {
|
||||
@@ -49,7 +45,8 @@ func web_render_nodes(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int
|
||||
if t, ok := argStr(args, "title"); ok && t != "" {
|
||||
title = t
|
||||
}
|
||||
return replyJSON(outJSON, errMsg, artifact.RenderHTMLPage(title, frag), nil)
|
||||
html, err := artifact.RenderViewDocument(title, args["nodes"], nil)
|
||||
return replyJSON(outJSON, errMsg, html, err)
|
||||
}
|
||||
|
||||
//export web_render_document
|
||||
@@ -88,26 +85,23 @@ func web_dom_markdown(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int
|
||||
return replyJSON(outJSON, errMsg, artifact.MarkdownHTML(text), nil)
|
||||
}
|
||||
|
||||
//export web_serve_root
|
||||
func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
// prepareArtifactApp shares discovery and startup assembly between direct serving
|
||||
// and resource composition. Listening starts only after resources have been bound.
|
||||
func prepareArtifactApp(args map[string]any) (map[string]any, error) {
|
||||
root, _ := argStr(args, "root")
|
||||
if root == "" {
|
||||
root = "."
|
||||
}
|
||||
abs, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
return nil, err
|
||||
}
|
||||
if st, err := os.Stat(abs); err != nil || !st.IsDir() {
|
||||
return replyJSON(outJSON, errMsg, nil, fmt.Errorf("web.serve: root not a directory: %s", abs))
|
||||
return nil, fmt.Errorf("web.prepare: root not a directory: %s", abs)
|
||||
}
|
||||
files, err := artifact.ScanRoot(abs)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
return nil, err
|
||||
}
|
||||
host, _ := argStr(args, "host")
|
||||
if host == "" {
|
||||
@@ -129,14 +123,23 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
if title == "" {
|
||||
title = f.Meta["标题"]
|
||||
}
|
||||
body, structured, err := artifact.RenderFile(f, plugin.RunArtifact)
|
||||
nodes, structured, err := artifact.AssembleView(f, func(path string, args map[string]any) (any, error) {
|
||||
return plugin.RunArtifactAtRoot(path, args, abs)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pg := page.New(map[string]any{"title": title, "intro": body})
|
||||
pg := page.New(map[string]any{"title": title, "intro": artifact.MarkdownHTML(f.Body)})
|
||||
stampArtifactData(pg, f.Meta)
|
||||
if structured {
|
||||
pg["artifact_html"] = artifact.RenderHTMLPage(title, body)
|
||||
// Validate structure and Resource contracts without querying or posting.
|
||||
if _, err := artifact.CollectDocumentHead(nodes); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", f.Rel, err)
|
||||
}
|
||||
if _, err := artifact.RenderNodesWithResources(nodes, httpx.ValidateViewResource); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", f.Rel, err)
|
||||
}
|
||||
pg["artifact_nodes"] = nodes
|
||||
}
|
||||
return pg, nil
|
||||
}
|
||||
@@ -145,7 +148,7 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
if f.Kind == "web" && f.Route == "/" {
|
||||
home, err = documentPage(f)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
return nil, err
|
||||
}
|
||||
break
|
||||
}
|
||||
@@ -164,11 +167,11 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
}
|
||||
pg, err := documentPage(f)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
return nil, err
|
||||
}
|
||||
out, err := app.Route(a, f.Route, pg)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
return nil, err
|
||||
}
|
||||
a = out
|
||||
continue
|
||||
@@ -209,20 +212,49 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
if mw := args["middleware"]; mw != nil {
|
||||
out, err := middleware.Configure(a, map[string]any{"security": mw})
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
return nil, err
|
||||
}
|
||||
a = out
|
||||
}
|
||||
if sd, ok := argStr(args, "static_dir"); ok && sd != "" {
|
||||
out, err := app.Static(a, sd, "/static")
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
return nil, err
|
||||
}
|
||||
a = out
|
||||
}
|
||||
a["artifact_declared"] = artifact.InspectBag(nil, files)["declared"]
|
||||
a["inspect"] = artifact.InspectBag(a, files)
|
||||
_, err = httpx.Listen(a, abs)
|
||||
return replyJSON(outJSON, errMsg, map[string]any{"ok": true, "value": a["inspect"], "error": nil}, err)
|
||||
a["artifact_root"] = abs
|
||||
return a, nil
|
||||
}
|
||||
|
||||
//export web_prepare_root
|
||||
func web_prepare_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
a, err := prepareArtifactApp(args)
|
||||
return replyJSON(outJSON, errMsg, a, err)
|
||||
}
|
||||
|
||||
//export web_serve_root
|
||||
func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
a, err := prepareArtifactApp(args)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
inspection, err := httpx.InspectApp(a)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
_, err = httpx.Listen(a, a["artifact_root"].(string))
|
||||
return replyJSON(outJSON, errMsg, map[string]any{"ok": true, "value": inspection, "error": nil}, err)
|
||||
}
|
||||
|
||||
//export web_inspect
|
||||
@@ -239,12 +271,11 @@ func web_inspect(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
return replyJSON(outJSON, errMsg, artifact.InspectBag(nil, files), nil)
|
||||
}
|
||||
a := asPageMap(args["app"])
|
||||
if a != nil {
|
||||
if insp, ok := a["inspect"].(map[string]any); ok {
|
||||
return replyJSON(outJSON, errMsg, insp, nil)
|
||||
}
|
||||
if a == nil {
|
||||
return replyJSON(outJSON, errMsg, artifact.InspectBag(nil, nil), nil)
|
||||
}
|
||||
return replyJSON(outJSON, errMsg, artifact.InspectBag(a, nil), nil)
|
||||
inspection, err := httpx.InspectApp(a)
|
||||
return replyJSON(outJSON, errMsg, inspection, err)
|
||||
}
|
||||
|
||||
//export web_app_use
|
||||
|
||||
@@ -345,7 +345,14 @@ func web_listen(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
if len(appBag) == 0 {
|
||||
appBag = args
|
||||
}
|
||||
out, err := httpx.Listen(appBag, entryDir())
|
||||
root := entryDir()
|
||||
if artifactRoot, ok := appBag["artifact_root"].(string); ok && artifactRoot != "" {
|
||||
root = artifactRoot
|
||||
}
|
||||
if _, err := httpx.InspectApp(appBag); err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
out, err := httpx.Listen(appBag, root)
|
||||
return replyJSON(outJSON, errMsg, out, err)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Package apikey implements Bearer API key verification (G-API1).
|
||||
//
|
||||
// Hash formula: sha256 hex of pepper + ":" + key (documented for anlian apikeys).
|
||||
// Hash formula: sha256 hex of pepper + ":" + key.
|
||||
package apikey
|
||||
|
||||
import (
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
package artifact
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/render"
|
||||
@@ -94,9 +96,17 @@ func ParseFrontmatter(src string) (meta map[string]string, body string) {
|
||||
// RenderNodes renders the existing five-column View schema recursively. Container
|
||||
// value cells hold more View rows; markdown leaves hold ordinary Markdown text.
|
||||
func RenderNodes(nodes any) (string, error) {
|
||||
return RenderNodesWithResources(nodes, nil)
|
||||
}
|
||||
|
||||
// ResourceRenderer resolves a typed Resource at the request boundary.
|
||||
// Ordinary View construction remains pure; a nil renderer never starts IO.
|
||||
type ResourceRenderer func(map[string]any) (string, error)
|
||||
|
||||
func RenderNodesWithResources(nodes any, resources ResourceRenderer) (string, error) {
|
||||
var b strings.Builder
|
||||
b.WriteString(`<style>` + LayoutCSS + `</style><div class="mq-view">`)
|
||||
if err := renderNodes(&b, nodes, 0); err != nil {
|
||||
if err := renderNodes(&b, nodes, 0, resources); err != nil {
|
||||
return "", err
|
||||
}
|
||||
b.WriteString(`</div>`)
|
||||
@@ -105,7 +115,7 @@ func RenderNodes(nodes any) (string, error) {
|
||||
|
||||
// Fixed runtime geometry, shared by offline previews and served Documents.
|
||||
// Authors choose row/column instead of embedding CSS or HTML in content cells.
|
||||
const LayoutCSS = `.mq-view{max-width:72rem;margin:auto;padding:1.5rem;line-height:1.6;font-family:system-ui,sans-serif}.mq-view *{box-sizing:border-box}.mq-view .mq-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,16rem),1fr));gap:1.5rem}.mq-view .mq-column{display:flex;flex-direction:column;gap:1.5rem}.mq-view .mq-node{min-width:0}.mq-view nav,.mq-view footer{padding-block:1rem}.mq-view footer{border-top:1px solid #d5dce5}.mq-view a{color:#2457a7}.mq-view img{max-width:100%;height:auto}.mq-view pre{overflow:auto}`
|
||||
const LayoutCSS = `.mq-view{max-width:72rem;margin:auto;padding:1.5rem;line-height:1.6;font-family:system-ui,sans-serif}.mq-view *{box-sizing:border-box}.mq-view .mq-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,16rem),1fr));gap:1.5rem}.mq-view .mq-column{display:flex;flex-direction:column;gap:1.5rem}.mq-view .mq-node{min-width:0;overflow-wrap:anywhere}.mq-view nav,.mq-view footer{padding-block:1rem}.mq-view footer{border-top:1px solid #d5dce5}.mq-view a{color:#2457a7}.mq-view img{max-width:100%;height:auto}.mq-view pre{overflow:auto}.mq-view input,.mq-view textarea,.mq-view select{max-width:100%;font:inherit}.mq-view textarea{width:100%}`
|
||||
|
||||
// Preserve typed value cells when normalizing column tables. General AsRows
|
||||
// treats @ cells as text, which would stringify nested component tables.
|
||||
@@ -148,7 +158,85 @@ func viewRows(nodes any) ([]any, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func renderNodes(b *strings.Builder, nodes any, depth int) error {
|
||||
func containerTag(kind string) (string, string) {
|
||||
switch kind {
|
||||
case "row", "横排":
|
||||
return "div", " mq-row"
|
||||
case "column", "纵排":
|
||||
return "div", " mq-column"
|
||||
case "nav", "导航":
|
||||
return "nav", ""
|
||||
case "header", "页头":
|
||||
return "header", ""
|
||||
case "footer", "页脚":
|
||||
return "footer", ""
|
||||
case "section", "区域":
|
||||
return "section", ""
|
||||
case "aside", "侧栏":
|
||||
return "aside", ""
|
||||
case "form", "表单":
|
||||
return "form", ""
|
||||
case "list", "列表":
|
||||
return "ul", ""
|
||||
case "item", "列表项":
|
||||
return "li", ""
|
||||
case "select", "选择":
|
||||
return "select", ""
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
// FindSlot selects one declared View region without resolving any Resources.
|
||||
// Container traversal is identical to rendering and never descends into a
|
||||
// Resource's private map as if it were another View table.
|
||||
func FindSlot(nodes any, slot string) (any, bool, error) {
|
||||
var selected []any
|
||||
var walk func(any, int) error
|
||||
walk = func(nodes any, depth int) error {
|
||||
if depth > 64 {
|
||||
return fmt.Errorf("View: nesting exceeds 64 levels")
|
||||
}
|
||||
rows, err := viewRows(nodes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, value := range rows {
|
||||
row, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return fmt.Errorf("View slot: expected a row map")
|
||||
}
|
||||
if first(row, "slot", "槽") == slot {
|
||||
selected = append(selected, row)
|
||||
}
|
||||
kind := strings.ToLower(first(row, "type", "类型"))
|
||||
if tag, _ := containerTag(kind); tag != "" {
|
||||
children := row["value"]
|
||||
if children == nil {
|
||||
children = row["值"]
|
||||
}
|
||||
if children == nil {
|
||||
return fmt.Errorf("View %s: missing child rows", kind)
|
||||
}
|
||||
if err := walk(children, depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := walk(nodes, 0); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if len(selected) > 1 {
|
||||
return nil, false, fmt.Errorf("View slot %q is ambiguous", slot)
|
||||
}
|
||||
if len(selected) == 0 {
|
||||
return nil, false, nil
|
||||
}
|
||||
return selected, true, nil
|
||||
}
|
||||
|
||||
func renderNodes(b *strings.Builder, nodes any, depth int, resources ResourceRenderer) error {
|
||||
if depth > 64 {
|
||||
return fmt.Errorf("View: nesting exceeds 64 levels")
|
||||
}
|
||||
@@ -165,6 +253,10 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error {
|
||||
slot := first(row, "slot", "槽")
|
||||
val := first(row, "value", "值")
|
||||
attrs := first(row, "attrs", "属性")
|
||||
attributes, err := renderAttributes(row)
|
||||
if err != nil {
|
||||
return fmt.Errorf("View row %d: %w", i+1, err)
|
||||
}
|
||||
style := first(row, "style", "样式")
|
||||
class := "mq-node"
|
||||
if style != "" {
|
||||
@@ -173,25 +265,8 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error {
|
||||
if slot != "" {
|
||||
class += " slot-" + html.EscapeString(slot)
|
||||
}
|
||||
tag := ""
|
||||
switch ty {
|
||||
case "row", "横排":
|
||||
tag = "div"
|
||||
class += " mq-row"
|
||||
case "column", "纵排":
|
||||
tag = "div"
|
||||
class += " mq-column"
|
||||
case "nav", "导航":
|
||||
tag = "nav"
|
||||
case "header", "页头":
|
||||
tag = "header"
|
||||
case "footer", "页脚":
|
||||
tag = "footer"
|
||||
case "section", "区域":
|
||||
tag = "section"
|
||||
case "aside", "侧栏":
|
||||
tag = "aside"
|
||||
}
|
||||
tag, geometry := containerTag(ty)
|
||||
class += geometry
|
||||
if tag != "" {
|
||||
children := row["value"]
|
||||
if children == nil {
|
||||
@@ -200,23 +275,72 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error {
|
||||
if children == nil {
|
||||
return fmt.Errorf("View row %d (%s): missing child rows in value", i+1, ty)
|
||||
}
|
||||
b.WriteString(`<` + tag + ` class="` + class + `">`)
|
||||
if err := renderNodes(b, children, depth+1); err != nil {
|
||||
b.WriteString(`<` + tag + ` class="` + class + `"` + attributes + `>`)
|
||||
if err := renderNodes(b, children, depth+1, resources); err != nil {
|
||||
return fmt.Errorf("View %s/%s: %w", ty, slot, err)
|
||||
}
|
||||
b.WriteString(`</` + tag + `>`)
|
||||
continue
|
||||
}
|
||||
switch ty {
|
||||
case "resource", "资源":
|
||||
value := row["value"]
|
||||
if value == nil {
|
||||
value = row["值"]
|
||||
}
|
||||
resource, ok := value.(map[string]any)
|
||||
if !ok || first(resource, "_type") == "" {
|
||||
return fmt.Errorf("View row %d: resource value must be a typed Resource", i+1)
|
||||
}
|
||||
if first(resource, "_type") == "document_head" {
|
||||
if _, err := ParseDocumentHead(resource); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if resources == nil {
|
||||
return fmt.Errorf("View row %d: resource requires an explicit request renderer", i+1)
|
||||
}
|
||||
fragment, err := resources(resource)
|
||||
if err != nil {
|
||||
return fmt.Errorf("View resource %s: %w", slot, err)
|
||||
}
|
||||
b.WriteString(`<section class="` + class + `"` + attributes + `>` + fragment + `</section>`)
|
||||
case "markdown", "正文":
|
||||
b.WriteString(`<div class="` + class + `">` + render.MarkdownToHTML(val) + `</div>`)
|
||||
b.WriteString(`<div class="` + class + `"` + attributes + `>` + render.MarkdownToHTML(val) + `</div>`)
|
||||
case "title", "标题":
|
||||
b.WriteString(`<h1 class="` + class + `">` + inline(val) + `</h1>`)
|
||||
b.WriteString(`<h1 class="` + class + `"` + attributes + `>` + inline(val) + `</h1>`)
|
||||
case "link", "链接":
|
||||
if attrs == "" {
|
||||
attrs = "#"
|
||||
if !hasAttributeMap(row) {
|
||||
if attrs == "" {
|
||||
attrs = "#"
|
||||
}
|
||||
attributes = ` href="` + html.EscapeString(attrs) + `"`
|
||||
}
|
||||
b.WriteString(`<a class="` + class + `"` + attributes + `>` + inline(val) + `</a>`)
|
||||
case "input", "输入":
|
||||
b.WriteString(`<input class="` + class + `"` + attributes + ` value="` + html.EscapeString(val) + `">`)
|
||||
case "button", "按钮", "textarea", "多行输入", "label", "标签", "pre", "预格式", "option", "选项":
|
||||
tags := map[string]string{"button": "button", "按钮": "button", "textarea": "textarea", "多行输入": "textarea", "label": "label", "标签": "label", "pre": "pre", "预格式": "pre", "option": "option", "选项": "option"}
|
||||
tag := tags[ty]
|
||||
b.WriteString(`<` + tag + ` class="` + class + `"` + attributes + `>` + html.EscapeString(val) + `</` + tag + `>`)
|
||||
case "script", "脚本", "stylesheet", "样式表":
|
||||
url := strings.ToLower(strings.TrimSpace(val))
|
||||
if url == "" || strings.ContainsAny(url, "\r\n\t") || strings.HasPrefix(url, "javascript:") || strings.HasPrefix(url, "vbscript:") {
|
||||
return fmt.Errorf("View row %d: resource requires a nonempty non-script URL", i+1)
|
||||
}
|
||||
if attrs, ok := attributeValue(row).(map[string]any); ok {
|
||||
for _, reserved := range []string{"href", "src", "rel"} {
|
||||
if _, exists := attrs[reserved]; exists {
|
||||
return fmt.Errorf("View row %d: resource URL and relation belong to its kind/value, not attrs.%s", i+1, reserved)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ty == "script" || ty == "脚本" {
|
||||
b.WriteString(`<script src="` + html.EscapeString(val) + `"` + attributes + `></script>`)
|
||||
} else {
|
||||
b.WriteString(`<link rel="stylesheet" href="` + html.EscapeString(val) + `"` + attributes + `>`)
|
||||
}
|
||||
b.WriteString(`<a class="` + class + `" href="` + html.EscapeString(attrs) + `">` + inline(val) + `</a>`)
|
||||
case "html", "原文":
|
||||
b.WriteString(`<div class="` + class + `">` + val + `</div>`)
|
||||
default:
|
||||
@@ -228,31 +352,137 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error {
|
||||
case []any, map[string]any:
|
||||
return fmt.Errorf("View row %d: unknown structural type %q", i+1, ty)
|
||||
}
|
||||
b.WriteString(`<p class="` + class + `">` + inline(val) + `</p>`)
|
||||
b.WriteString(`<p class="` + class + `"` + attributes + `>` + inline(val) + `</p>`)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Attribute records keep controls in the same five-column View schema.
|
||||
// Legacy link rows may still carry a plain href string. Names and scalar values
|
||||
// are checked before emission; handlers and inline style remain explicit escapes.
|
||||
func attributeValue(row map[string]any) any {
|
||||
if value, ok := row["attrs"]; ok && value != nil {
|
||||
return value
|
||||
}
|
||||
return row["属性"]
|
||||
}
|
||||
|
||||
func hasAttributeMap(row map[string]any) bool {
|
||||
_, ok := attributeValue(row).(map[string]any)
|
||||
return ok
|
||||
}
|
||||
|
||||
func renderAttributes(row map[string]any) (string, error) {
|
||||
value := attributeValue(row)
|
||||
if value == nil || value == "" {
|
||||
return "", nil
|
||||
}
|
||||
attrs, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
if _, legacy := value.(string); legacy {
|
||||
return "", nil
|
||||
}
|
||||
return "", fmt.Errorf("attrs must be a scalar attribute record or legacy link URL")
|
||||
}
|
||||
allowed := map[string]bool{
|
||||
"id": true, "title": true, "role": true, "name": true, "type": true,
|
||||
"href": true, "src": true, "action": true, "method": true, "enctype": true,
|
||||
"placeholder": true, "for": true, "rows": true, "cols": true, "size": true,
|
||||
"min": true, "max": true, "step": true, "minlength": true, "maxlength": true,
|
||||
"pattern": true, "autocomplete": true, "target": true, "rel": true,
|
||||
"tabindex": true, "download": true, "accept": true, "alt": true,
|
||||
"integrity": true, "crossorigin": true, "media": true, "referrerpolicy": true,
|
||||
}
|
||||
booleans := map[string]bool{"hidden": true, "disabled": true, "required": true, "readonly": true, "checked": true, "selected": true, "multiple": true, "autofocus": true, "async": true, "defer": true, "nomodule": true}
|
||||
keys := make([]string, 0, len(attrs))
|
||||
for name := range attrs {
|
||||
keys = append(keys, name)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
var out strings.Builder
|
||||
for _, name := range keys {
|
||||
if !(allowed[name] || booleans[name] || validCustomAttribute(name)) {
|
||||
return "", fmt.Errorf("unsupported attribute %q; use attrs data/aria keys for client state", name)
|
||||
}
|
||||
v := attrs[name]
|
||||
if v == nil {
|
||||
continue
|
||||
}
|
||||
if booleans[name] {
|
||||
flag, ok := v.(bool)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("attribute %s requires a boolean", name)
|
||||
}
|
||||
if flag {
|
||||
out.WriteString(" " + name)
|
||||
}
|
||||
continue
|
||||
}
|
||||
switch v.(type) {
|
||||
case string, bool, float64, int, int64, json.Number:
|
||||
default:
|
||||
return "", fmt.Errorf("attribute %s requires a scalar value", name)
|
||||
}
|
||||
text := fmt.Sprint(v)
|
||||
if name == "href" || name == "src" || name == "action" {
|
||||
url := strings.ToLower(strings.TrimSpace(text))
|
||||
if strings.HasPrefix(url, "javascript:") || strings.HasPrefix(url, "vbscript:") {
|
||||
return "", fmt.Errorf("attribute %s cannot execute a script URL", name)
|
||||
}
|
||||
}
|
||||
out.WriteString(" " + name + `="` + html.EscapeString(text) + `"`)
|
||||
}
|
||||
return out.String(), nil
|
||||
}
|
||||
|
||||
func validCustomAttribute(name string) bool {
|
||||
if !(strings.HasPrefix(name, "data-") || strings.HasPrefix(name, "aria-")) {
|
||||
return false
|
||||
}
|
||||
if strings.HasSuffix(name, "-") {
|
||||
return false
|
||||
}
|
||||
for _, char := range name {
|
||||
if !(char >= 'a' && char <= 'z' || char >= '0' && char <= '9' || char == '-' || char == '_') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// RenderFile explicitly opts a Document into startup-time component assembly.
|
||||
// Documents without view: main retain their existing Markdown/data-source path.
|
||||
func RenderFile(f ArtifactFile, run func(string, map[string]any) (any, error)) (string, bool, error) {
|
||||
// AssembleView runs the existing startup entry once and retains typed rows.
|
||||
// Request resources are deliberately not resolved during assembly.
|
||||
func AssembleView(f ArtifactFile, run func(string, map[string]any) (any, error)) (any, bool, error) {
|
||||
view := metaString(f.Meta, "view", "视图")
|
||||
if view == "" {
|
||||
return MarkdownHTML(f.Body), false, nil
|
||||
return nil, false, nil
|
||||
}
|
||||
if view != "main" {
|
||||
return "", false, fmt.Errorf("%s: view/视图 must be main", f.Rel)
|
||||
return nil, false, fmt.Errorf("%s: view/视图 must be main", f.Rel)
|
||||
}
|
||||
if metaString(f.Meta, "data_source", "数据源") != "" {
|
||||
return "", false, fmt.Errorf("%s: view main is startup assembly; use an ordinary Document for automatic data_source binding", f.Rel)
|
||||
return nil, false, fmt.Errorf("%s: view main is startup assembly; use an ordinary Document for automatic data_source binding", f.Rel)
|
||||
}
|
||||
nodes, err := run(f.Path, nil)
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("%s: view main: %w", f.Rel, err)
|
||||
return nil, false, fmt.Errorf("%s: view main: %w", f.Rel, err)
|
||||
}
|
||||
if nodes == nil {
|
||||
return "", false, fmt.Errorf("%s: view main must return View rows", f.Rel)
|
||||
return nil, false, fmt.Errorf("%s: view main must return View rows", f.Rel)
|
||||
}
|
||||
return nodes, true, nil
|
||||
}
|
||||
|
||||
func RenderFile(f ArtifactFile, run func(string, map[string]any) (any, error)) (string, bool, error) {
|
||||
nodes, structured, err := AssembleView(f, run)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if !structured {
|
||||
return MarkdownHTML(f.Body), false, nil
|
||||
}
|
||||
html, err := RenderNodes(nodes)
|
||||
if err != nil {
|
||||
@@ -285,8 +515,12 @@ func RenderHTMLPage(title, innerHTML string) string {
|
||||
if t == "" {
|
||||
t = "Marqdo"
|
||||
}
|
||||
return "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>" + t +
|
||||
"</title></head><body class=\"mq-document\"><main>" + innerHTML + "</main></body></html>"
|
||||
return renderHTMLPageWithHead("<title>"+t+"</title>", innerHTML)
|
||||
}
|
||||
|
||||
func renderHTMLPageWithHead(head, innerHTML string) string {
|
||||
return "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" + head +
|
||||
"</head><body class=\"mq-document\"><main>" + innerHTML + "</main></body></html>"
|
||||
}
|
||||
|
||||
// MarkdownHTML exposes render helper.
|
||||
@@ -385,6 +619,7 @@ func SystemRoutes() []map[string]any {
|
||||
return []map[string]any{
|
||||
{"method": "GET", "path": "/_part/*", "kind": "system"},
|
||||
{"method": "GET|POST", "path": "/_form/*", "kind": "system"},
|
||||
{"method": "POST", "path": "/_md", "kind": "system"},
|
||||
{"method": "POST", "path": "/_runtime/tasks", "kind": "system"},
|
||||
{"method": "GET", "path": "/_runtime/tasks/{id}", "kind": "system"},
|
||||
{"method": "POST", "path": "/_runtime/tasks/{id}/cancel", "kind": "system"},
|
||||
@@ -392,55 +627,85 @@ func SystemRoutes() []map[string]any {
|
||||
}
|
||||
}
|
||||
|
||||
// InspectBag builds {declared, system} from an app bag and/or scanned files.
|
||||
// InspectBag reads declarations only. A prepared app's actual handler inventory
|
||||
// is generated by httpx.InspectApp through the same registrar as NewHandler.
|
||||
func InspectBag(app map[string]any, declared []ArtifactFile) map[string]any {
|
||||
var dec []map[string]any
|
||||
for _, a := range declared {
|
||||
dec = append(dec, map[string]any{
|
||||
"method": a.Method,
|
||||
"path": a.Route,
|
||||
"kind": a.Kind,
|
||||
"file": a.Rel,
|
||||
})
|
||||
entries := map[string]map[string]any{}
|
||||
add := func(row map[string]any) {
|
||||
path := first(row, "path")
|
||||
method := first(row, "method")
|
||||
if method == "" {
|
||||
method = "GET"
|
||||
}
|
||||
if path == "" {
|
||||
return
|
||||
}
|
||||
key := method + " " + path
|
||||
if _, exists := entries[key]; !exists {
|
||||
entries[key] = row
|
||||
}
|
||||
}
|
||||
for _, file := range declared {
|
||||
add(map[string]any{"method": file.Method, "path": file.Route, "kind": file.Kind, "file": file.Rel})
|
||||
}
|
||||
if app != nil {
|
||||
switch rows := app["artifact_declared"].(type) {
|
||||
case []map[string]any:
|
||||
for _, row := range rows {
|
||||
add(row)
|
||||
}
|
||||
case []any:
|
||||
for _, value := range rows {
|
||||
if row, ok := value.(map[string]any); ok {
|
||||
add(row)
|
||||
}
|
||||
}
|
||||
}
|
||||
if app["page"] != nil {
|
||||
add(map[string]any{"method": "GET", "path": "/", "kind": "document"})
|
||||
}
|
||||
if routes, ok := app["routes"].(map[string]any); ok {
|
||||
for path := range routes {
|
||||
dec = append(dec, map[string]any{"method": "GET", "path": path, "kind": "declared"})
|
||||
add(map[string]any{"method": "GET", "path": path, "kind": "document"})
|
||||
}
|
||||
}
|
||||
if inv, ok := app["invoke_routes"].(map[string]any); ok {
|
||||
for key, v := range inv {
|
||||
row := map[string]any{"path": key, "kind": "endpoint"}
|
||||
if m, ok := v.(map[string]any); ok {
|
||||
if c, ok := m["class"].(string); ok && c != "" {
|
||||
row["class"] = c
|
||||
for _, group := range []string{"artifact_routes", "invoke_routes"} {
|
||||
if routes, ok := app[group].(map[string]any); ok {
|
||||
for key, value := range routes {
|
||||
spec, _ := value.(map[string]any)
|
||||
method, path := first(spec, "method"), first(spec, "path")
|
||||
if parts := strings.SplitN(key, " ", 2); len(parts) == 2 {
|
||||
if method == "" {
|
||||
method = parts[0]
|
||||
}
|
||||
if path == "" {
|
||||
path = parts[1]
|
||||
}
|
||||
} else if path == "" {
|
||||
path = key
|
||||
}
|
||||
if method, ok := m["method"].(string); ok && method != "" {
|
||||
row["method"] = method
|
||||
if method == "" {
|
||||
method = "GET"
|
||||
}
|
||||
if fn, ok := m["fn"].(string); ok && fn != "" {
|
||||
row["fn"] = fn
|
||||
row := map[string]any{"method": method, "path": path, "kind": "endpoint"}
|
||||
for _, name := range []string{"file", "class", "fn"} {
|
||||
if value := first(spec, name); value != "" {
|
||||
row[name] = value
|
||||
}
|
||||
}
|
||||
add(row)
|
||||
}
|
||||
dec = append(dec, row)
|
||||
}
|
||||
}
|
||||
if art, ok := app["artifact_routes"].(map[string]any); ok {
|
||||
for key, v := range art {
|
||||
m, _ := v.(map[string]any)
|
||||
dec = append(dec, map[string]any{
|
||||
"path": key,
|
||||
"kind": "endpoint",
|
||||
"method": fmt.Sprint(m["method"]),
|
||||
"file": fmt.Sprint(m["file"]),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
return map[string]any{
|
||||
"_type": "web_inspection",
|
||||
"declared": dec,
|
||||
"system": SystemRoutes(),
|
||||
keys := make([]string, 0, len(entries))
|
||||
for key := range entries {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
rows := make([]map[string]any, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
rows = append(rows, entries[key])
|
||||
}
|
||||
return map[string]any{"_type": "web_inspection", "scope": "metadata", "declared": rows, "system": SystemRoutes()}
|
||||
}
|
||||
@@ -142,3 +142,48 @@ func TestViewDocumentRejectsAnEmptyAssemblyAndAutomaticDataSource(t *testing.T)
|
||||
t.Fatalf("data source silently ignored: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInteractiveControlsUseTypedAttributesAndEscapedText(t *testing.T) {
|
||||
nodes := []any{map[string]any{"type":"form", "attrs":map[string]any{"id":"editor", "method":"post", "action":"/save"}, "value":[]any{
|
||||
map[string]any{"type":"label", "value":"Title", "attrs":map[string]any{"for":"title"}},
|
||||
map[string]any{"type":"input", "value":`"><script>alert(1)</script>`, "attrs":map[string]any{"id":"title", "name":"title", "required":true, "disabled":false, "maxlength":float64(120)}},
|
||||
map[string]any{"type":"textarea", "value":"</textarea><script>x</script>", "attrs":map[string]any{"id":"doc", "rows":float64(16), "aria-label":"Document"}},
|
||||
map[string]any{"type":"button", "value":"Save & return", "attrs":map[string]any{"type":"submit", "data-action":"save"}},
|
||||
map[string]any{"类型":"预格式", "值":"<waiting>", "属性":map[string]any{"id":"log","hidden":false}},
|
||||
}}}
|
||||
got,err := RenderNodes(nodes)
|
||||
if err != nil { t.Fatal(err) }
|
||||
for _, expected := range []string{`<form`,`action="/save"`,`for="title"`,`maxlength="120"`,` required`,`rows="16"`,`aria-label="Document"`,`data-action="save"`,`Save & return`,`</textarea>`,`<waiting>`} {
|
||||
if !strings.Contains(got,expected) { t.Fatalf("missing %s: %s",expected,got) }
|
||||
}
|
||||
if strings.Contains(got,"<script>") || strings.Contains(got," disabled") || strings.Contains(got," hidden") || strings.Contains(got,"map[") { t.Fatalf("control values leaked into markup: %s",got) }
|
||||
}
|
||||
func TestAttributeRecordsApplyToContainersAndLinks(t *testing.T) {
|
||||
got,err:=RenderNodes([]any{map[string]any{"type":"section","attrs":map[string]any{"id":"view-detail","hidden":true},"value":[]any{
|
||||
map[string]any{"type":"link","value":"Open","attrs":map[string]any{"href":"/a?x=1&y=2","title":"Detail"}},
|
||||
}}})
|
||||
if err != nil || !strings.Contains(got,`id="view-detail"`) || !strings.Contains(got," hidden") || !strings.Contains(got,`href="/a?x=1&y=2"`) { t.Fatalf("%v: %s",err,got) }
|
||||
for _,attrs:=range []map[string]any{
|
||||
{"onclick":"alert(1)"},{"style":"position:fixed"},{"data-x\" onload":"x"},{"href":"javascript:alert(1)"},{"required":"true"},{"title":[]any{"nested"}},
|
||||
} {
|
||||
if _,err:=RenderNodes([]any{map[string]any{"type":"button","value":"Run","attrs":attrs}});err==nil { t.Fatalf("accepted invalid attributes: %v",attrs) }
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourcesStayStructuredAndEscapeTheirURLs(t *testing.T) {
|
||||
got,err:=RenderNodes([]any{
|
||||
map[string]any{"type":"script","value":"/static/marqdo-bridge.js","attrs":map[string]any{"type":"module","data-mq-wasm":"/static/runtime.wasm","data-mq-source-url":"/static/client.mq.md"}},
|
||||
map[string]any{"type":"stylesheet","value":"/static/theme.css?x=1&y=2"},
|
||||
})
|
||||
if err!=nil {t.Fatal(err)}
|
||||
for _,want:=range []string{`<script src="/static/marqdo-bridge.js"`,`type="module"`,`data-mq-source-url="/static/client.mq.md"`,`<link rel="stylesheet" href="/static/theme.css?x=1&y=2"`} {
|
||||
if !strings.Contains(got,want) {t.Fatalf("missing %s: %s",want,got)}
|
||||
}
|
||||
for _,node:=range []map[string]any{
|
||||
{"type":"script","value":"javascript:alert(1)"},
|
||||
{"type":"script","value":"/static/a.js","attrs":map[string]any{"src":"/other.js"}},
|
||||
{"type":"stylesheet","value":"/theme.css","attrs":map[string]any{"rel":"preload"}},
|
||||
} {
|
||||
if _,err:=RenderNodes([]any{node});err==nil {t.Fatalf("accepted invalid resource: %v",node)}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package artifact
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/assets"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/render"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/table"
|
||||
)
|
||||
|
||||
// DocumentHead is a closed, pure View Resource. It contributes only metadata
|
||||
// and existing native head links; it cannot mutate page layout or server state.
|
||||
type DocumentHead struct {
|
||||
Meta map[string]any
|
||||
Links []assets.HeadLink
|
||||
}
|
||||
|
||||
func headRows(value any) ([]map[string]any, error) {
|
||||
if value == nil {
|
||||
return nil, nil
|
||||
}
|
||||
switch data := value.(type) {
|
||||
case []any:
|
||||
rows := make([]map[string]any, 0, len(data))
|
||||
for _, value := range data {
|
||||
row, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("document_head: expected table records")
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
return rows, nil
|
||||
case map[string]any:
|
||||
if len(data) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
arrays, scalars, count := 0, 0, -1
|
||||
for _, value := range data {
|
||||
if column, ok := value.([]any); ok {
|
||||
arrays++
|
||||
if count >= 0 && count != len(column) {
|
||||
return nil, fmt.Errorf("document_head: column lengths differ")
|
||||
}
|
||||
count = len(column)
|
||||
} else {
|
||||
scalars++
|
||||
}
|
||||
}
|
||||
if arrays > 0 && scalars > 0 {
|
||||
return nil, fmt.Errorf("document_head: mixed column and scalar cells")
|
||||
}
|
||||
if arrays > 0 && count == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
rows, _ := table.AsRows(data).([]any)
|
||||
return headRows(rows)
|
||||
default:
|
||||
return nil, fmt.Errorf("document_head: expected a table or None")
|
||||
}
|
||||
}
|
||||
|
||||
func headURL(raw string) error {
|
||||
if raw == "" || strings.ContainsAny(raw, "\r\n\t") || raw != strings.TrimSpace(raw) ||
|
||||
strings.Contains(raw, "\\") || strings.HasPrefix(raw, "//") {
|
||||
return fmt.Errorf("document_head: resource URL must be site-relative or http(s)")
|
||||
}
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil || parsed == nil {
|
||||
return fmt.Errorf("document_head: invalid resource URL")
|
||||
}
|
||||
if parsed.Scheme == "" {
|
||||
if !strings.HasPrefix(raw, "/") {
|
||||
return fmt.Errorf("document_head: relative URL must start with /")
|
||||
}
|
||||
} else if (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
|
||||
return fmt.Errorf("document_head: resource URL must be site-relative or http(s)")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseDocumentHead validates before either preview or listening. No URL is
|
||||
// fetched and no script is executed by this native projection.
|
||||
func ParseDocumentHead(resource map[string]any) (DocumentHead, error) {
|
||||
out := DocumentHead{Meta: map[string]any{}}
|
||||
if first(resource, "_type") != "document_head" {
|
||||
return out, fmt.Errorf("document_head: incorrect resource type")
|
||||
}
|
||||
for key := range resource {
|
||||
if key != "_type" && key != "meta" && key != "links" {
|
||||
return out, fmt.Errorf("document_head: unsupported field %q", key)
|
||||
}
|
||||
}
|
||||
rows, err := headRows(resource["meta"])
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
for key, value := range row {
|
||||
if key != "key" && key != "键" && key != "name" && key != "value" && key != "值" && key != "@" && key != "行" && key != "row" && key != "id" {
|
||||
return out, fmt.Errorf("document_head: unsupported metadata field %q", key)
|
||||
}
|
||||
switch value.(type) {
|
||||
case nil, string, bool, float64:
|
||||
default:
|
||||
return out, fmt.Errorf("document_head: metadata cells must be scalar values")
|
||||
}
|
||||
}
|
||||
key := first(row, "键", "key", "name")
|
||||
value := first(row, "值", "value")
|
||||
if key == "" {
|
||||
return out, fmt.Errorf("document_head: metadata requires key/value rows")
|
||||
}
|
||||
if strings.EqualFold(key, "charset") || strings.EqualFold(key, "viewport") || strings.EqualFold(key, "csrf-token") {
|
||||
return out, fmt.Errorf("document_head: %s is owned by the document runtime", key)
|
||||
}
|
||||
if key == "canonical" || key == "icon" || key == "favicon" {
|
||||
if err := headURL(value); err != nil {
|
||||
return out, err
|
||||
}
|
||||
}
|
||||
if existing, ok := out.Meta[key]; ok && existing != value {
|
||||
return out, fmt.Errorf("document_head: conflicting metadata %q", key)
|
||||
}
|
||||
out.Meta[key] = value
|
||||
}
|
||||
rows, err = headRows(resource["links"])
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
// Use the same link field aliases and native rendering as ordinary Documents.
|
||||
for _, row := range rows {
|
||||
for key, value := range row {
|
||||
switch value.(type) {
|
||||
case nil, string, bool, float64:
|
||||
default:
|
||||
return out, fmt.Errorf("document_head: link cells must be scalar values")
|
||||
}
|
||||
if value == nil {
|
||||
continue
|
||||
}
|
||||
switch key {
|
||||
case "关系", "rel", "Rel", "地址", "href", "src", "url", "Href", "Src", "URL",
|
||||
"类型", "type", "Type", "尺寸", "sizes", "Sizes", "媒体", "media", "Media",
|
||||
"作为", "as", "As", "跨域", "crossorigin", "crossOrigin",
|
||||
"推迟", "defer", "Defer", "异步", "async", "Async", "版本", "version", "Version", "v", "@", "行", "row", "id":
|
||||
default:
|
||||
return out, fmt.Errorf("document_head: unsupported link field %q", key)
|
||||
}
|
||||
}
|
||||
if err := headURL(first(row, "地址", "href", "src", "url", "Href", "Src", "URL")); err != nil {
|
||||
return out, err
|
||||
}
|
||||
links := assets.AsHeadLinks([]any{row})
|
||||
if len(links) != 1 {
|
||||
return out, fmt.Errorf("document_head: each link requires href")
|
||||
}
|
||||
if err := headURL(links[0].Href); err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Links = append(out.Links, links[0])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CollectDocumentHead traverses only real View containers. Resource private
|
||||
// records are never interpreted as nodes, and conflicting declarations fail.
|
||||
func CollectDocumentHead(nodes any) (DocumentHead, error) {
|
||||
out := DocumentHead{Meta: map[string]any{}}
|
||||
var walk func(any, int) error
|
||||
walk = func(nodes any, depth int) error {
|
||||
if depth > 64 {
|
||||
return fmt.Errorf("View: nesting exceeds 64 levels")
|
||||
}
|
||||
rows, err := viewRows(nodes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, value := range rows {
|
||||
row, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return fmt.Errorf("View: expected row map")
|
||||
}
|
||||
kind := strings.ToLower(first(row, "type", "类型"))
|
||||
child := row["value"]
|
||||
if child == nil {
|
||||
child = row["值"]
|
||||
}
|
||||
if tag, _ := containerTag(kind); tag != "" {
|
||||
if child == nil {
|
||||
return fmt.Errorf("View %s: missing child rows", kind)
|
||||
}
|
||||
if err := walk(child, depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if kind == "resource" || kind == "资源" {
|
||||
resource, ok := child.(map[string]any)
|
||||
if !ok || first(resource, "_type") != "document_head" {
|
||||
continue
|
||||
}
|
||||
head, err := ParseDocumentHead(resource)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for key, value := range head.Meta {
|
||||
if existing, ok := out.Meta[key]; ok && existing != value {
|
||||
return fmt.Errorf("document_head: conflicting metadata %q", key)
|
||||
}
|
||||
out.Meta[key] = value
|
||||
}
|
||||
for _, link := range head.Links {
|
||||
duplicate := false
|
||||
for _, existing := range out.Links {
|
||||
if reflect.DeepEqual(existing, link) {
|
||||
duplicate = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !duplicate {
|
||||
out.Links = append(out.Links, link)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
err := walk(nodes, 0)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// RenderViewDocument shares a single pure shell for offline and request-time
|
||||
// nodes. Metadata never becomes visible content or a fragment response.
|
||||
func RenderViewDocument(title string, nodes any, resources ResourceRenderer) (string, error) {
|
||||
head, err := CollectDocumentHead(nodes)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
body, err := RenderNodesWithResources(nodes, resources)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return renderHTMLPageWithHead(render.DocumentHead(title, head.Meta, head.Links), body), nil
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package artifact
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func headNode(meta, links any) any {
|
||||
return map[string]any{"type": "resource", "slot": "head", "value": map[string]any{"_type": "document_head", "meta": meta, "links": links}}
|
||||
}
|
||||
|
||||
func TestDocumentHeadPreservesMetadataAndLinksInTheActualHeadOnly(t *testing.T) {
|
||||
meta := map[string]any{"key": []any{"description", "og:title", "canonical"}, "value": []any{`Text <tag> "quote" & literal`, "Actual OG", "/articles"}}
|
||||
links := []any{
|
||||
map[string]any{"关系": "preconnect", "地址": "https://fonts.example.test", "跨域": "anonymous"},
|
||||
map[string]any{"rel": "stylesheet", "href": "/theme.css?x=1&y=2"},
|
||||
map[string]any{"rel": "module", "href": "/client.js", "defer": false},
|
||||
}
|
||||
// Repeated imports should deduplicate equal links, including boolean flags.
|
||||
nodes := []any{map[string]any{"type": "column", "value": []any{
|
||||
headNode(meta, links), headNode(nil, links),
|
||||
map[string]any{"type": "markdown", "value": "# Actual page"},
|
||||
}}}
|
||||
got, err := RenderViewDocument("Actual document", nodes, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head, body, ok := strings.Cut(got, "</head>")
|
||||
if !ok {
|
||||
t.Fatal(got)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"<title>Actual document</title>", `<meta name="description" content="Text <tag> "quote" & literal"`,
|
||||
`<meta property="og:title" content="Actual OG"`, `<link rel="canonical" href="/articles"`,
|
||||
`<link rel="preconnect" href="https://fonts.example.test" crossorigin="anonymous"`,
|
||||
`<link rel="stylesheet" href="/theme.css?x=1&y=2"`, `<script type="module" src="/client.js"></script>`,
|
||||
} {
|
||||
if !strings.Contains(head, want) {
|
||||
t.Fatalf("missing %s: %s", want, head)
|
||||
}
|
||||
}
|
||||
if strings.Count(head, `href="/theme.css`) != 1 || strings.Count(head, `src="/client.js"`) != 1 {
|
||||
t.Fatal("duplicate head resource: " + head)
|
||||
}
|
||||
if strings.Contains(body, "Actual OG") || strings.Contains(body, "fonts.example") || strings.Contains(body, "slot-head") || !strings.Contains(body, "Actual page") {
|
||||
t.Fatal(body)
|
||||
}
|
||||
calls := 0
|
||||
fragment, err := RenderNodesWithResources(nodes, func(map[string]any) (string, error) { calls++; return "unexpected", nil })
|
||||
if err != nil || calls != 0 || strings.Contains(fragment, "<meta") || strings.Contains(fragment, "fonts.example") {
|
||||
t.Fatalf("%d %v %s", calls, err, fragment)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocumentHeadRejectsConflictsMalformedTablesAndOpaqueMutation(t *testing.T) {
|
||||
valid := map[string]any{"_type": "document_head", "meta": nil, "links": nil}
|
||||
for _, resource := range []map[string]any{
|
||||
{"_type": "other"},
|
||||
{"_type": "document_head", "html": "<script>x</script>"},
|
||||
{"_type": "document_head", "body_class": "admin"},
|
||||
{"_type": "document_head", "meta": []any{42}},
|
||||
{"_type": "document_head", "meta": map[string]any{"key": []any{"a", "b"}, "value": []any{"one"}}},
|
||||
{"_type": "document_head", "meta": map[string]any{"key": "description", "value": []any{"nested"}}},
|
||||
{"_type": "document_head", "meta": map[string]any{"key": "viewport", "value": "owned"}},
|
||||
{"_type": "document_head", "meta": []any{map[string]any{"key": "description", "value": "a"}, map[string]any{"key": "description", "value": "b"}}},
|
||||
{"_type": "document_head", "links": []any{map[string]any{"rel": "script", "href": "/a.js", "onclick": "x"}}},
|
||||
{"_type": "document_head", "links": []any{map[string]any{"rel": "stylesheet", "href": "/a.css", "media": map[string]any{"x": "nested"}}}},
|
||||
{"_type": "document_head", "links": []any{map[string]any{"rel": "stylesheet"}}},
|
||||
} {
|
||||
if _, err := ParseDocumentHead(resource); err == nil {
|
||||
t.Fatalf("accepted %#v", resource)
|
||||
}
|
||||
}
|
||||
if _, err := ParseDocumentHead(valid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, url := range []string{"javascript:alert(1)", "data:text/javascript,x", "//other.test/a", "relative.css", "/\\other.test/a", "https://", "/a\n.js"} {
|
||||
for _, resource := range []map[string]any{
|
||||
{"_type": "document_head", "links": []any{map[string]any{"rel": "script", "href": url}}},
|
||||
{"_type": "document_head", "meta": map[string]any{"key": "canonical", "value": url}},
|
||||
} {
|
||||
if _, err := ParseDocumentHead(resource); err == nil {
|
||||
t.Fatalf("accepted %q", url)
|
||||
}
|
||||
}
|
||||
}
|
||||
conflict := []any{headNode(map[string]any{"key": "description", "value": "first"}, nil),
|
||||
map[string]any{"类型": "纵排", "值": []any{headNode(map[string]any{"键": "description", "值": "second"}, nil)}}}
|
||||
if _, err := CollectDocumentHead(conflict); err == nil {
|
||||
t.Fatal("nested head conflict silently overwrote metadata")
|
||||
}
|
||||
private := []any{map[string]any{"type": "resource", "value": map[string]any{"_type": "data_query", "where": headNode(nil, nil)}}}
|
||||
head, err := CollectDocumentHead(private)
|
||||
if err != nil || len(head.Links) != 0 || len(head.Meta) != 0 {
|
||||
t.Fatalf("walked private Resource: %v %#v", err, head)
|
||||
}
|
||||
var deep any = []any{headNode(nil, nil)}
|
||||
for i := 0; i < 66; i++ {
|
||||
deep = []any{map[string]any{"type": "row", "value": deep}}
|
||||
}
|
||||
if _, err := CollectDocumentHead(deep); err == nil {
|
||||
t.Fatal("unbounded head traversal")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package artifact
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFindSlotKeepsNestedTypedResourcesAndRejectsAmbiguity(t *testing.T) {
|
||||
descriptor := map[string]any{"_type": "data_query", "source": "articles", "slot": "not-a-view-slot"}
|
||||
nodes := []any{map[string]any{"type": "row", "slot": "layout", "value": []any{
|
||||
map[string]any{"类型": "纵排", "槽": "main", "值": []any{
|
||||
map[string]any{"type": "resource", "slot": "articles", "value": descriptor},
|
||||
}},
|
||||
map[string]any{"type": "markdown", "slot": "sidebar", "value": "Separate"},
|
||||
}}}
|
||||
selected, found, err := FindSlot(nodes, "articles")
|
||||
if err != nil || !found {
|
||||
t.Fatalf("%v %v", found, err)
|
||||
}
|
||||
calls := 0
|
||||
html, err := RenderNodesWithResources(selected, func(value map[string]any) (string, error) {
|
||||
calls++
|
||||
if value["source"] != "articles" {
|
||||
t.Fatal(value)
|
||||
}
|
||||
return "<p>Actual request value</p>", nil
|
||||
})
|
||||
if err != nil || calls != 1 || !strings.Contains(html, "Actual request value") || strings.Contains(html, "Separate") {
|
||||
t.Fatalf("%d %v %s", calls, err, html)
|
||||
}
|
||||
if _, found, err := FindSlot(nodes, "not-a-view-slot"); err != nil || found {
|
||||
t.Fatalf("walked Resource internals: %v %v", found, err)
|
||||
}
|
||||
duplicate := append(nodes, map[string]any{"type": "text", "slot": "articles", "value": "Ambiguous"})
|
||||
if _, _, err := FindSlot(duplicate, "articles"); err == nil {
|
||||
t.Fatal("duplicate slot accepted")
|
||||
}
|
||||
if _, _, err := FindSlot([]any{42}, "articles"); err == nil {
|
||||
t.Fatal("malformed View accepted")
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,13 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/app"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/auth"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/db"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/password"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/ratelimit"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/rbac"
|
||||
@@ -372,7 +374,7 @@ func (st *state) hasPageRoute(path string) bool {
|
||||
return ok
|
||||
}
|
||||
|
||||
func (st *state) mountAuthRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountAuthRoutes(mux routeRegistrar) {
|
||||
st.mountOIDCRoutes(mux)
|
||||
if st.auth.users == nil && !(st.auth.rbac && st.auth.register) && !st.oidcEnabled() {
|
||||
return
|
||||
@@ -416,6 +418,9 @@ func (st *state) mountAuthRoutes(mux *http.ServeMux) {
|
||||
if adminHome == "" {
|
||||
adminHome = "/admin"
|
||||
}
|
||||
// The canonical no-slash path must be registered too: the global
|
||||
// trailing-slash normalizer otherwise triggers a ServeMux redirect loop.
|
||||
mux.HandleFunc("GET "+adminHome, st.handleAdminHome)
|
||||
mux.HandleFunc("GET "+adminHome+"/{$}", st.handleAdminHome)
|
||||
}
|
||||
}
|
||||
@@ -501,7 +506,6 @@ func (st *state) handleLoginPost(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, dest, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
|
||||
// tryLogin: GFM users first, then web_users when RBAC is on.
|
||||
func (st *state) tryLogin(username, password string) map[string]any {
|
||||
if st.auth.users != nil {
|
||||
@@ -558,8 +562,45 @@ func (st *state) handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (st *state) handleAdminHome(w http.ResponseWriter, r *http.Request) {
|
||||
// Only explicitly mounted forms expose their associated business tables.
|
||||
// Never enumerate session/credential tables just because they share a DB.
|
||||
var body strings.Builder
|
||||
body.WriteString(`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Admin</title></head><body><h1>Admin</h1><p>Mounted forms and their current business records (up to 100 rows per table).</p><nav><a href="/">Site</a></nav>`)
|
||||
seen := map[string]bool{}
|
||||
for _, id := range sortedKeys(st.forms) {
|
||||
selected, ok := st.forms[id].(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
tableName, _ := selected["table"].(string)
|
||||
fmt.Fprintf(&body, `<section><h2>%s</h2><p><a href="/_form/%s">Open form</a></p>`, esc(id), esc(url.PathEscape(id)))
|
||||
if tableName != "" && st.dbURL != "" && !seen[tableName] {
|
||||
current, err := db.Select(st.dbURL, tableName, 100, db.SelectOpts{})
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
var data strings.Builder
|
||||
encoder := json.NewEncoder(&data)
|
||||
encoder.SetIndent("", " ")
|
||||
encoder.SetEscapeHTML(false)
|
||||
if err := encoder.Encode(current["rows"]); err != nil {
|
||||
http.Error(w, "cannot encode admin records", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// Escape once for HTML, preserving readable literal angle brackets
|
||||
// instead of displaying JSON's optional Unicode escape sequences.
|
||||
fmt.Fprintf(&body, `<h3>%s</h3><pre style="white-space:pre-wrap;overflow-wrap:anywhere">%s</pre>`, esc(tableName), esc(data.String()))
|
||||
seen[tableName] = true
|
||||
}
|
||||
body.WriteString("</section>")
|
||||
}
|
||||
if len(st.forms) == 0 {
|
||||
body.WriteString("<p>No forms are mounted.</p>")
|
||||
}
|
||||
body.WriteString("</body></html>")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, "<!doctype html><html><body><h1>Admin</h1><p>Site administration.</p></body></html>")
|
||||
_, _ = io.WriteString(w, body.String())
|
||||
}
|
||||
|
||||
func loginDest(r *http.Request, fallback string) string {
|
||||
|
||||
@@ -114,7 +114,7 @@ func (st *state) writeRegisterFailure(w http.ResponseWriter, r *http.Request, ms
|
||||
_, _ = io.WriteString(w, registerPageHTML(st.auth.registerPath, &loc, csrf))
|
||||
}
|
||||
|
||||
func (st *state) mountExtraLoginPosts(mux *http.ServeMux, already map[string]bool) {
|
||||
func (st *state) mountExtraLoginPosts(mux routeRegistrar, already map[string]bool) {
|
||||
for path, pageV := range st.routes {
|
||||
if already[path] {
|
||||
continue
|
||||
|
||||
@@ -74,7 +74,7 @@ func (st *state) oidcFallbackNext(r *http.Request) string {
|
||||
return "/"
|
||||
}
|
||||
|
||||
func (st *state) mountOIDCRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountOIDCRoutes(mux routeRegistrar) {
|
||||
if !st.oidcEnabled() {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -56,4 +56,3 @@ func TestResolveSessionReplacesStaleCookie(t *testing.T) {
|
||||
t.Fatalf("live session should not Set-Cookie again")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/app"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/artifact"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/middleware"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/oidc"
|
||||
)
|
||||
|
||||
type recordedMux struct {
|
||||
validate *http.ServeMux
|
||||
patterns []string
|
||||
}
|
||||
|
||||
func (mux *recordedMux) Handle(pattern string, _ http.Handler) {
|
||||
// Validate registration conflicts without retaining or running handlers.
|
||||
mux.validate.HandleFunc(pattern, func(http.ResponseWriter, *http.Request) {})
|
||||
mux.patterns = append(mux.patterns, pattern)
|
||||
}
|
||||
func (mux *recordedMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
|
||||
mux.Handle(pattern, http.HandlerFunc(handler))
|
||||
}
|
||||
|
||||
var tailWildcard = regexp.MustCompile(`\{([^{}]+)\.\.\.\}`)
|
||||
|
||||
func inspectionPath(path string) string {
|
||||
path = strings.TrimSuffix(path, "{$}")
|
||||
return tailWildcard.ReplaceAllString(path, "{*$1}")
|
||||
}
|
||||
|
||||
// InspectApp executes only trusted registration logic. It does not create a
|
||||
// session, reset global runtime state, query a DB, run Documents or listen.
|
||||
func InspectApp(bag map[string]any) (report map[string]any, err error) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
report = nil
|
||||
err = fmt.Errorf("web.inspect: invalid route registration: %v", recovered)
|
||||
}
|
||||
}()
|
||||
if bag == nil {
|
||||
bag = map[string]any{}
|
||||
}
|
||||
routes := routeMapOf(bag, "routes")
|
||||
page, _ := bag["page"].(map[string]any)
|
||||
forms := map[string]any{}
|
||||
if existing, ok := bag["forms"].(map[string]any); ok {
|
||||
for key, value := range existing {
|
||||
forms[key] = value
|
||||
}
|
||||
}
|
||||
collectPageForms(page, forms)
|
||||
for _, value := range routes {
|
||||
if page, ok := value.(map[string]any); ok {
|
||||
collectPageForms(page, forms)
|
||||
}
|
||||
}
|
||||
root := strOpt(bag, "artifact_root", "")
|
||||
staticDir := strOpt(bag, "static_dir", "")
|
||||
if staticDir != "" {
|
||||
staticDir = resolvePath(staticDir, root)
|
||||
}
|
||||
icons, err := iconRoutesFromBag(bag, root, staticDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st := &state{
|
||||
page: page, routes: routes, forms: forms, mw: middleware.Parse(bag), entryDir: root,
|
||||
iconRoutes: icons, redirects: redirectsOf(bag), sitemapRoutes: sitemapRoutesOf(bag),
|
||||
robotsBody: robotsBodyOf(bag), page404: pageOf(bag, "page_404"), page500: pageOf(bag, "page_500"),
|
||||
uploadRoutes: routeMapOf(bag, "upload_routes"), downloadRoutes: routeMapOf(bag, "download_routes"),
|
||||
wsRoutes: routeMapOf(bag, "ws_routes"), galleryRoutes: routeMapOf(bag, "gallery_routes"),
|
||||
proxyRoutes: routeMapOf(bag, "proxy_routes"), invokeRoutes: routeMapOf(bag, "invoke_routes"),
|
||||
artifactRoutes: routeMapOf(bag, "artifact_routes"), auth: authConfigOf(bag), oidc: oidc.ParseConfig(bag),
|
||||
}
|
||||
// Only a nonempty DB URL determines whether DB-backed routes are enabled.
|
||||
// Its existence and contents are intentionally not inspected here.
|
||||
st.dbURL = dbURLOf(bag)
|
||||
staticMount := app.NormalizeStaticMount(strOpt(bag, "static_mount", "/static"))
|
||||
mux := &recordedMux{validate: http.NewServeMux()}
|
||||
st.registerRoutes(mux, staticDir, staticMount, false)
|
||||
report = artifact.InspectBag(bag, nil)
|
||||
declarations := map[string]map[string]any{}
|
||||
byPath := map[string]map[string]any{}
|
||||
for _, row := range report["declared"].([]map[string]any) {
|
||||
path := inspectionPath(goMuxPattern(fmt.Sprint(row["path"])))
|
||||
method := fmt.Sprint(row["method"])
|
||||
declarations[method+" "+path] = row
|
||||
if _, exists := byPath[path]; !exists {
|
||||
byPath[path] = row
|
||||
}
|
||||
}
|
||||
// Classification uses the explicitly supplied Resource paths; the method
|
||||
// and presence still come from the actual recorded registration.
|
||||
for group, kind := range map[string]string{
|
||||
"ws_routes": "websocket", "upload_routes": "upload", "download_routes": "download",
|
||||
"gallery_routes": "gallery", "proxy_routes": "proxy", "redirects": "redirect", "sitemap_routes": "sitemap",
|
||||
} {
|
||||
for key, value := range routeMapOf(bag, group) {
|
||||
spec, _ := value.(map[string]any)
|
||||
path := strOpt(spec, "path", key)
|
||||
if parts := strings.SplitN(path, " ", 2); len(parts) == 2 {
|
||||
path = parts[1]
|
||||
}
|
||||
path = inspectionPath(goMuxPattern(path))
|
||||
byPath[path] = map[string]any{"path": path, "kind": kind}
|
||||
}
|
||||
}
|
||||
for _, query := range st.mw.JSONRoutes {
|
||||
row := map[string]any{"path": query.Path, "method": query.Method, "kind": "data_query"}
|
||||
declarations[query.Method+" "+query.Path] = row
|
||||
}
|
||||
var declared, system []map[string]any
|
||||
seen := map[string]bool{}
|
||||
for _, pattern := range mux.patterns {
|
||||
method, path := "*", pattern
|
||||
if parts := strings.SplitN(pattern, " ", 2); len(parts) == 2 {
|
||||
method, path = parts[0], parts[1]
|
||||
}
|
||||
path = inspectionPath(path)
|
||||
if method == "*" && (path == staticMount || path == staticMount+"/") && strOpt(bag, "static_dir", "") != "" {
|
||||
method = "GET|HEAD"
|
||||
}
|
||||
key := method + " " + path
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
row := map[string]any{"method": method, "path": path, "kind": "system"}
|
||||
source, found := declarations[key]
|
||||
if !found {
|
||||
source, found = byPath[path]
|
||||
}
|
||||
if found {
|
||||
for key, value := range source {
|
||||
if key != "method" && key != "path" {
|
||||
row[key] = value
|
||||
}
|
||||
}
|
||||
declared = append(declared, row)
|
||||
} else {
|
||||
system = append(system, row)
|
||||
}
|
||||
}
|
||||
less := func(rows []map[string]any) {
|
||||
sort.Slice(rows, func(i, j int) bool {
|
||||
a, b := fmt.Sprint(rows[i]["path"]), fmt.Sprint(rows[j]["path"])
|
||||
if a != b {
|
||||
return a < b
|
||||
}
|
||||
return fmt.Sprint(rows[i]["method"]) < fmt.Sprint(rows[j]["method"])
|
||||
})
|
||||
}
|
||||
less(declared)
|
||||
less(system)
|
||||
if declared == nil {
|
||||
declared = []map[string]any{}
|
||||
}
|
||||
if system == nil {
|
||||
system = []map[string]any{}
|
||||
}
|
||||
report["scope"] = "registered"
|
||||
report["declared"] = declared
|
||||
report["system"] = system
|
||||
return report, nil
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/app"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/form"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/session"
|
||||
)
|
||||
|
||||
func TestInspectionUsesActualRegistrationsAfterResourceBindingsWithoutExecutingThem(t *testing.T) {
|
||||
filename := filepath.Join(t.TempDir(), "must-not-create.db")
|
||||
bag := app.New(map[string]any{"page": map[string]any{"title": "Home"},
|
||||
"db": map[string]any{"url": "sqlite:" + filename}, "admin": true})
|
||||
bag["artifact_declared"] = []any{map[string]any{"method": "GET", "path": "/", "kind": "web", "file": "index.mq.md"}}
|
||||
// A cached observation is deliberately stale and must never be returned.
|
||||
bag["inspect"] = map[string]any{"declared": []any{map[string]any{"path": "/stale"}}}
|
||||
var err error
|
||||
bag, err = app.Route(bag, "/post/{id}", map[string]any{"title": "Post"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := InspectApp(bag)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bag, err = app.Auth(bag, []any{map[string]any{"username": "fixture", "password": "never-return-this-secret"}}, map[string]any{"login_path": "/members/login"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bag, err = app.MountForm(bag, "article", form.New("articles", "insert", ""))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bag["ws_routes"] = map[string]any{"/live/{id}": map[string]any{"mode": "echo"}}
|
||||
bag["middleware"] = map[string]any{"json_routes": map[string]any{"api/items": map[string]any{"table": "items", "method": "GET"}}}
|
||||
bag["artifact_routes"] = map[string]any{"GET /api/ping": map[string]any{"method": "GET", "path": "/api/ping", "file": "/never-run.mq.md"}}
|
||||
bag["static_dir"] = "."
|
||||
bag["static_mount"] = "/assets"
|
||||
session.Configure(session.Config{TTLSec: 3600})
|
||||
session.Reset(3600)
|
||||
sid := session.NewID(3600)
|
||||
session.SetValue(sid, "inspection_marker", "retained")
|
||||
report, err := InspectApp(bag)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if report["scope"] != "registered" {
|
||||
t.Fatal(report)
|
||||
}
|
||||
type route struct{ method, path string }
|
||||
observed := map[route]string{}
|
||||
for _, group := range []string{"declared", "system"} {
|
||||
for _, row := range report[group].([]map[string]any) {
|
||||
key := route{row["method"].(string), row["path"].(string)}
|
||||
if _, seen := observed[key]; seen {
|
||||
t.Fatalf("duplicate registered route: %#v", key)
|
||||
}
|
||||
observed[key] = group
|
||||
}
|
||||
}
|
||||
for _, key := range []route{{"GET", "/"}, {"GET", "/post/{id}"}, {"GET", "/live/{id}"}, {"GET", "/api/items"}, {"GET", "/api/ping"}} {
|
||||
if observed[key] != "declared" {
|
||||
t.Fatalf("missing current Resource declaration %#v: %#v", key, report)
|
||||
}
|
||||
}
|
||||
for _, key := range []route{{"POST", "/_md"}, {"GET", "/_form/{id}"}, {"POST", "/_form/{id}"},
|
||||
{"GET", "/post/{id}/_part/{part}"}, {"GET", "/members/login"}, {"POST", "/members/login"},
|
||||
{"GET", "/admin/login"}, {"GET", "/admin"}, {"GET", "/admin/"}, {"GET|HEAD", "/assets/"}} {
|
||||
if observed[key] != "system" {
|
||||
t.Fatalf("missing actual system route %#v: %#v", key, report)
|
||||
}
|
||||
}
|
||||
encoded, _ := json.Marshal(report)
|
||||
if strings.Contains(string(encoded), "never-return-this-secret") || strings.Contains(string(encoded), "/stale") {
|
||||
t.Fatalf("inspection leaked unrelated app state: %s", encoded)
|
||||
}
|
||||
if value, ok := session.GetValue(sid, "inspection_marker"); !ok || value != "retained" {
|
||||
t.Fatal("inspection reset runtime sessions")
|
||||
}
|
||||
if _, err := os.Stat(filename); !os.IsNotExist(err) {
|
||||
t.Fatalf("inspection opened a database: %v", err)
|
||||
}
|
||||
prior, _ := json.Marshal(before)
|
||||
if strings.Contains(string(prior), "/live/") {
|
||||
t.Fatal("inspection mutated an earlier returned observation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectionRejectsActualRouteConflictsWithoutStartingTheServer(t *testing.T) {
|
||||
bag := app.New(map[string]any{"page": map[string]any{}})
|
||||
bag["routes"] = map[string]any{"/_md": map[string]any{}}
|
||||
bag["artifact_routes"] = map[string]any{"POST /_md": map[string]any{"method": "POST", "path": "/_md", "file": "never-run.mq.md"}}
|
||||
if _, err := InspectApp(bag); err == nil || !strings.Contains(err.Error(), "invalid route registration") {
|
||||
t.Fatalf("conflicting routes were advertised as usable: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/app"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/artifact"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/assets"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/db"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/form"
|
||||
@@ -129,6 +130,23 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
st.registerRoutes(mux, staticDir, staticMount, true)
|
||||
|
||||
handler := withMiddleware(mux, mw)
|
||||
handler = withRBAC(handler, authCfg.gates, authCfg.loginPath)
|
||||
handler = withTenant(handler, st.tenant)
|
||||
handler = withStripTrailingSlash(handler)
|
||||
return handler, nil
|
||||
}
|
||||
|
||||
// routeRegistrar is shared by the real server and its read-only inventory.
|
||||
// Recording registrations does not invoke any captured handler.
|
||||
type routeRegistrar interface {
|
||||
Handle(string, http.Handler)
|
||||
HandleFunc(string, func(http.ResponseWriter, *http.Request))
|
||||
}
|
||||
|
||||
func (st *state) registerRoutes(mux routeRegistrar, staticDir, staticMount string, logSetup bool) {
|
||||
mux.HandleFunc("GET /{$}", st.handleHome)
|
||||
// Part slot uses {part} (not {id}) so dynamic routes like /desk/posts/{id}
|
||||
// do not collide with Go ServeMux duplicate wildcard names.
|
||||
@@ -137,10 +155,10 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
mux.HandleFunc("POST /_form/{id}", st.handleFormPost)
|
||||
mux.HandleFunc("POST /_md", st.handleMarkdownPreview)
|
||||
|
||||
paths := sortedKeys(routes)
|
||||
paths := sortedKeys(st.routes)
|
||||
for _, p := range paths {
|
||||
routePath := p
|
||||
pageV, _ := routes[routePath].(map[string]any)
|
||||
pageV, _ := st.routes[routePath].(map[string]any)
|
||||
if pageV == nil {
|
||||
pageV = map[string]any{}
|
||||
}
|
||||
@@ -158,7 +176,7 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
}
|
||||
}
|
||||
|
||||
for _, jr := range mw.JSONRoutes {
|
||||
for _, jr := range st.mw.JSONRoutes {
|
||||
route := jr
|
||||
pattern := route.Method + " " + route.Path
|
||||
mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -168,16 +186,20 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
|
||||
// Icon routes before the static prefix so /static/favicon.svg does not
|
||||
// conflict with Go 1.22+ ServeMux method/path overlap rules.
|
||||
for _, ir := range iconRoutes {
|
||||
for _, ir := range st.iconRoutes {
|
||||
url := ir.URL
|
||||
path := ir.Path
|
||||
ct := ir.ContentType
|
||||
if staticDir != "" && (url == staticMount || strings.HasPrefix(url, staticMount+"/")) {
|
||||
// FileServer under staticMount already serves these paths.
|
||||
fmt.Fprintf(os.Stderr, "marqdo web icon: %s → static %s (via %s)\n", url, path, staticMount)
|
||||
if logSetup {
|
||||
fmt.Fprintf(os.Stderr, "marqdo web icon: %s → static %s (via %s)\n", url, path, staticMount)
|
||||
}
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "marqdo web icon: %s → %s (%s)\n", url, path, ct)
|
||||
if logSetup {
|
||||
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)
|
||||
})
|
||||
@@ -187,7 +209,9 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
}
|
||||
|
||||
if staticDir != "" {
|
||||
fmt.Fprintf(os.Stderr, "marqdo web static: %s → %s\n", staticMount, staticDir)
|
||||
if logSetup {
|
||||
fmt.Fprintf(os.Stderr, "marqdo web static: %s → %s\n", staticMount, staticDir)
|
||||
}
|
||||
fs := http.StripPrefix(staticMount, http.FileServer(http.Dir(staticDir)))
|
||||
// Register without method so GET+HEAD share one pattern (avoids conflicts
|
||||
// with more-specific GET/HEAD icon paths under the same prefix).
|
||||
@@ -245,11 +269,6 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
|
||||
mux.HandleFunc("/{path...}", st.handleNotFound)
|
||||
|
||||
handler := withMiddleware(mux, mw)
|
||||
handler = withRBAC(handler, authCfg.gates, authCfg.loginPath)
|
||||
handler = withTenant(handler, st.tenant)
|
||||
handler = withStripTrailingSlash(handler)
|
||||
return handler, nil
|
||||
}
|
||||
|
||||
// Listen binds host:port from the app bag and serves until interrupt/kill.
|
||||
@@ -392,7 +411,19 @@ func (st *state) writePage(w http.ResponseWriter, r *http.Request, page map[stri
|
||||
p["_auth_next"] = next
|
||||
}
|
||||
setCookie := st.attachCSRF(p, r)
|
||||
html := render.RenderPage(p, st.dbURL, "")
|
||||
html := ""
|
||||
if nodes, ok := p["artifact_nodes"]; ok {
|
||||
document, err := artifact.RenderViewDocument(strOpt(p, "title", ""), nodes, func(resource map[string]any) (string, error) {
|
||||
return st.renderViewResource(resource, p, r)
|
||||
})
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
html = document
|
||||
} else {
|
||||
html = render.RenderPage(p, st.dbURL, "")
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
appendSetCookie(w, setCookie)
|
||||
_, _ = io.WriteString(w, html)
|
||||
@@ -401,7 +432,32 @@ func (st *state) writePage(w http.ResponseWriter, r *http.Request, page map[stri
|
||||
func (st *state) writePart(w http.ResponseWriter, r *http.Request, page map[string]any, id string) {
|
||||
p := st.preparePage(page, r)
|
||||
setCookie := st.attachCSRF(p, r)
|
||||
html := render.RenderPage(p, st.dbURL, id)
|
||||
html := ""
|
||||
if nodes, ok := p["artifact_nodes"]; ok {
|
||||
selected, found, err := artifact.FindSlot(nodes, id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
if id != "main" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
// Keep the existing main-fragment fallback for a View without a
|
||||
// named main region; never expose the Document's program source.
|
||||
selected = nodes
|
||||
}
|
||||
html, err = artifact.RenderNodesWithResources(selected, func(resource map[string]any) (string, error) {
|
||||
return st.renderViewResource(resource, p, r)
|
||||
})
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
html = render.RenderPage(p, st.dbURL, id)
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
appendSetCookie(w, setCookie)
|
||||
_, _ = io.WriteString(w, html)
|
||||
@@ -500,7 +556,11 @@ func (st *state) handleFormGet(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = io.WriteString(w, fmt.Sprintf("<p>unknown form %s</p>", id))
|
||||
return
|
||||
}
|
||||
html := form.Render(frm, id, nil, nil, "")
|
||||
page := map[string]any{}
|
||||
setCookie := st.attachCSRF(page, r)
|
||||
csrf, _ := page["_csrf"].(string)
|
||||
html := form.Render(frm, id, nil, nil, csrf)
|
||||
appendSetCookie(w, setCookie)
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, html)
|
||||
}
|
||||
@@ -522,6 +582,19 @@ func (st *state) handleFormPost(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
csrf := ""
|
||||
if st.auth.users != nil || st.auth.rbac || st.oidcEnabled() {
|
||||
sid, token, setCookie := resolveSession(r)
|
||||
appendSetCookie(w, setCookie)
|
||||
csrf = token
|
||||
_, hadCookie := session.IDFromCookie(r.Header.Get("Cookie"))
|
||||
if hadCookie || r.FormValue("_csrf") != "" {
|
||||
if !session.ValidateCSRF(sid, r.FormValue("_csrf")) {
|
||||
http.Error(w, "Invalid or missing CSRF token", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
data := map[string]any{}
|
||||
for k, vs := range r.PostForm {
|
||||
if len(vs) > 0 {
|
||||
@@ -547,13 +620,13 @@ func (st *state) handleFormPost(w http.ResponseWriter, r *http.Request) {
|
||||
// Prefer an explicit form redirect (e.g. cancel_href list URL) over the
|
||||
// composing page path stamped as _mq_return.
|
||||
redir := strOpt(res, "redirect", "/")
|
||||
if (redir == "" || redir == "/") && ctx.ReturnPath != "" {
|
||||
if (redir == "" || redir == "/") && ctx.ReturnPath != "" && strOpt(frm, "cancel_href", "") == "" {
|
||||
redir = ctx.ReturnPath
|
||||
}
|
||||
http.Redirect(w, r, redir, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
html := form.RenderBodyCtx(frm, id, data, res["errors"], "", ctx)
|
||||
html := form.RenderBodyCtx(frm, id, data, res["errors"], csrf, ctx)
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, html)
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ func parseArtifactRoute(v any) artifactRoute {
|
||||
}
|
||||
}
|
||||
|
||||
func (st *state) mountArtifactRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountArtifactRoutes(mux routeRegistrar) {
|
||||
for _, key := range sortedKeys(st.artifactRoutes) {
|
||||
cfg := parseArtifactRoute(st.artifactRoutes[key])
|
||||
if cfg.File == "" || cfg.Path == "" {
|
||||
@@ -131,7 +131,7 @@ func (st *state) handleArtifact(w http.ResponseWriter, r *http.Request, route ar
|
||||
}
|
||||
}
|
||||
|
||||
value, err := plugin.RunArtifact(route.File, payload)
|
||||
value, err := plugin.RunArtifactAtRoot(route.File, payload, st.entryDir)
|
||||
if err != nil {
|
||||
jsonErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
|
||||
@@ -63,7 +63,7 @@ func parseInvokeRoute(v any) invokeRoute {
|
||||
}
|
||||
}
|
||||
|
||||
func (st *state) mountInvokeRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountInvokeRoutes(mux routeRegistrar) {
|
||||
for _, key := range sortedKeys(st.invokeRoutes) {
|
||||
cfg := parseInvokeRoute(st.invokeRoutes[key])
|
||||
path := routePathKey(key)
|
||||
|
||||
@@ -47,7 +47,7 @@ func parseDownloadRoute(v any) downloadRoute {
|
||||
}
|
||||
}
|
||||
|
||||
func (st *state) mountUploadRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountUploadRoutes(mux routeRegistrar) {
|
||||
for _, path := range sortedKeys(st.uploadRoutes) {
|
||||
routePath := path
|
||||
cfg := parseUploadRoute(st.uploadRoutes[path])
|
||||
@@ -57,7 +57,7 @@ func (st *state) mountUploadRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
}
|
||||
|
||||
func (st *state) mountDownloadRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountDownloadRoutes(mux routeRegistrar) {
|
||||
for _, path := range sortedKeys(st.downloadRoutes) {
|
||||
routePath := path
|
||||
cfg := parseDownloadRoute(st.downloadRoutes[path])
|
||||
@@ -68,7 +68,7 @@ func (st *state) mountDownloadRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
}
|
||||
|
||||
func (st *state) mountGalleryRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountGalleryRoutes(mux routeRegistrar) {
|
||||
for _, path := range sortedKeys(st.galleryRoutes) {
|
||||
cfg, _ := st.galleryRoutes[path].(map[string]any)
|
||||
mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -90,7 +90,7 @@ func parseHeadersFromEnvStr(s string) []envHeader {
|
||||
return out
|
||||
}
|
||||
|
||||
func (st *state) mountProxyRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountProxyRoutes(mux routeRegistrar) {
|
||||
for _, key := range sortedKeys(st.proxyRoutes) {
|
||||
cfg := parseProxyRoute(st.proxyRoutes[key])
|
||||
path := routePathKey(key)
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
// System runtime control routes (M-R3 / M-R4). Cancel and event replay do not
|
||||
// enter the Marqdo interpreter lock.
|
||||
func (st *state) mountRuntimeRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountRuntimeRoutes(mux routeRegistrar) {
|
||||
mux.HandleFunc("POST /_runtime/tasks", st.handleRuntimeAdmit)
|
||||
mux.HandleFunc("GET /_runtime/tasks/{id}", st.handleRuntimeGet)
|
||||
mux.HandleFunc("POST /_runtime/tasks/{id}/cancel", st.handleRuntimeCancel)
|
||||
|
||||
@@ -28,7 +28,7 @@ func sameOrigin(r *http.Request) bool {
|
||||
return err == nil && strings.EqualFold(u.Host, r.Host)
|
||||
}
|
||||
|
||||
func (st *state) mountWSRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountWSRoutes(mux routeRegistrar) {
|
||||
for _, path := range sortedKeys(st.wsRoutes) {
|
||||
spec := ws.ParseRouteSpec(st.wsRoutes[path]) // mode + optional room_key / on_message
|
||||
routePath := path
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/artifact"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/db"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/form"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/render"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/tenant"
|
||||
)
|
||||
|
||||
// ValidateViewResource validates the closed Resource contracts without IO.
|
||||
// Assembly calls this before listening; request rendering validates again.
|
||||
func ValidateViewResource(resource map[string]any) (string, error) {
|
||||
kind, _ := resource["_type"].(string)
|
||||
switch kind {
|
||||
case "document_head":
|
||||
_, err := artifact.ParseDocumentHead(resource)
|
||||
return "", err
|
||||
case "data_query":
|
||||
if source, ok := resource["source"].(string); !ok || strings.TrimSpace(source) == "" {
|
||||
return "", fmt.Errorf("data_query: source must be a nonempty table name")
|
||||
}
|
||||
for _, key := range []string{"order", "link_prefix"} {
|
||||
if value, exists := resource[key]; exists {
|
||||
if _, ok := value.(string); !ok {
|
||||
return "", fmt.Errorf("data_query: %s must be text", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"detail", "tenant_scope"} {
|
||||
if value, exists := resource[key]; exists {
|
||||
if _, ok := value.(bool); !ok {
|
||||
return "", fmt.Errorf("data_query: %s must be boolean", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
if raw, exists := resource["limit"]; exists {
|
||||
n, ok := raw.(float64)
|
||||
if !ok || n < 1 || n > 1000 || n != float64(int64(n)) {
|
||||
return "", fmt.Errorf("data_query: limit must be an integer in 1..1000")
|
||||
}
|
||||
}
|
||||
if prefix, _ := resource["link_prefix"].(string); prefix != "" && (!strings.HasPrefix(prefix, "/") || strings.HasPrefix(prefix, "//")) {
|
||||
return "", fmt.Errorf("data_query: link_prefix must be site-relative")
|
||||
}
|
||||
if where := resource["where"]; where != nil {
|
||||
switch where.(type) {
|
||||
case map[string]any, []any:
|
||||
default:
|
||||
return "", fmt.Errorf("data_query: where must be a native condition map or list")
|
||||
}
|
||||
}
|
||||
case "form_ref":
|
||||
if id, ok := resource["id"].(string); !ok || strings.TrimSpace(id) == "" {
|
||||
return "", fmt.Errorf("form_ref: id must name an explicitly mounted form")
|
||||
}
|
||||
case "view_navigation":
|
||||
region, _ := resource["region"].(string)
|
||||
if region != "nav" && region != "sidebar" && region != "footer" {
|
||||
return "", fmt.Errorf("view_navigation: region must be nav, sidebar or footer")
|
||||
}
|
||||
switch resource["items"].(type) {
|
||||
case map[string]any, []any:
|
||||
default:
|
||||
return "", fmt.Errorf("view_navigation: items must be link records")
|
||||
}
|
||||
default:
|
||||
return "", fmt.Errorf("unsupported View Resource %q", kind)
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
var viewParameter = regexp.MustCompile(`\{([^{}]+)\}`)
|
||||
|
||||
// Copy parameterized conditions without mutating the retained startup nodes.
|
||||
func resourceWhere(value any, params map[string]any) (any, error) {
|
||||
switch value := value.(type) {
|
||||
case string:
|
||||
var missing string
|
||||
out := viewParameter.ReplaceAllStringFunc(value, func(token string) string {
|
||||
key := token[1 : len(token)-1]
|
||||
actual, ok := params[key]
|
||||
if !ok {
|
||||
missing = key
|
||||
return token
|
||||
}
|
||||
return fmt.Sprint(actual)
|
||||
})
|
||||
if missing != "" {
|
||||
return nil, fmt.Errorf("data_query: missing route parameter %q", missing)
|
||||
}
|
||||
return out, nil
|
||||
case map[string]any:
|
||||
out := make(map[string]any, len(value))
|
||||
for key, item := range value {
|
||||
resolved, err := resourceWhere(item, params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[key] = resolved
|
||||
}
|
||||
return out, nil
|
||||
case []any:
|
||||
out := make([]any, len(value))
|
||||
for i, item := range value {
|
||||
resolved, err := resourceWhere(item, params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[i] = resolved
|
||||
}
|
||||
return out, nil
|
||||
default:
|
||||
return value, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (st *state) renderViewResource(resource, page map[string]any, request *http.Request) (string, error) {
|
||||
if _, err := ValidateViewResource(resource); err != nil {
|
||||
return "", err
|
||||
}
|
||||
switch resource["_type"] {
|
||||
case "document_head":
|
||||
return "", nil
|
||||
case "data_query":
|
||||
if st.dbURL == "" {
|
||||
return "", fmt.Errorf("data_query: the application has no database resource")
|
||||
}
|
||||
params, _ := page["params"].(map[string]any)
|
||||
where, err := resourceWhere(resource["where"], params)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
scoped, _ := resource["tenant_scope"].(bool)
|
||||
if scoped && !st.tenant.Enabled() {
|
||||
return "", fmt.Errorf("data_query: scoped query requires a tenant policy")
|
||||
}
|
||||
if scoped || st.tenant.DefaultScope {
|
||||
id := tenant.FromContext(request.Context())
|
||||
if id == "" {
|
||||
return "", fmt.Errorf("data_query: tenant required")
|
||||
}
|
||||
where = tenant.MergeWhere(where, st.tenant.Column, id)
|
||||
}
|
||||
limit := int64(50)
|
||||
if n, ok := resource["limit"].(float64); ok {
|
||||
limit = int64(n)
|
||||
}
|
||||
order, _ := resource["order"].(string)
|
||||
rows, err := db.Select(st.dbURL, resource["source"].(string), limit, db.SelectOpts{Where: where, Order: order})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
detail, _ := resource["detail"].(bool)
|
||||
prefix, _ := resource["link_prefix"].(string)
|
||||
return render.RenderQueryRows(rows["rows"], detail, prefix), nil
|
||||
case "form_ref":
|
||||
id := resource["id"].(string)
|
||||
selected, ok := st.forms[id].(map[string]any)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("form_ref: form %q was not explicitly mounted", id)
|
||||
}
|
||||
csrf, _ := page["_csrf"].(string)
|
||||
return form.RenderBodyCtx(selected, id, nil, nil, csrf, st.requestContext(request, nil)), nil
|
||||
case "view_navigation":
|
||||
region := resource["region"].(string)
|
||||
navigation := map[string]any{region: resource["items"]}
|
||||
if region == "nav" {
|
||||
navigation["nav"] = resource["items"]
|
||||
}
|
||||
if logged, ok := page["_logged_in"]; ok {
|
||||
navigation["_logged_in"] = logged
|
||||
}
|
||||
if user, ok := page["_nav_user"]; ok {
|
||||
navigation["_nav_user"] = user
|
||||
}
|
||||
return render.RenderPage(navigation, "", region), nil
|
||||
}
|
||||
return "", fmt.Errorf("unsupported View Resource")
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/app"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/artifact"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/db"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/form"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/session"
|
||||
)
|
||||
|
||||
func resourceNode(resource map[string]any) map[string]any {
|
||||
return map[string]any{"type": "resource", "value": resource, "slot": "content"}
|
||||
}
|
||||
|
||||
func TestViewResourcesObserveRequestsFormsAndNavigation(t *testing.T) {
|
||||
uri := "sqlite:" + filepath.Join(t.TempDir(), "view.db")
|
||||
fields := []any{
|
||||
map[string]any{"name": "id", "type": "integer", "nullable": false},
|
||||
map[string]any{"name": "title", "type": "text", "nullable": false},
|
||||
map[string]any{"name": "slug", "type": "text", "nullable": true},
|
||||
map[string]any{"name": "summary", "type": "text", "nullable": true},
|
||||
map[string]any{"name": "body", "type": "text", "nullable": true},
|
||||
}
|
||||
if _, err := db.Init(uri, "articles", fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Insert(uri, "articles", map[string]any{
|
||||
"title": "Original <title>", "slug": "first", "summary": "Short summary", "body": "Full article body",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
query := map[string]any{"_type": "data_query", "source": "articles", "limit": float64(50), "link_prefix": "/post/"}
|
||||
navigation := map[string]any{"_type": "view_navigation", "region": "nav", "items": []any{
|
||||
map[string]any{"label": "Guest login", "href": "/admin/login", "when": "guest"},
|
||||
map[string]any{"label": "Private desk", "href": "/admin", "when": "auth"},
|
||||
}}
|
||||
page := map[string]any{"title": "View resources", "artifact_nodes": []any{
|
||||
resourceNode(navigation), resourceNode(query),
|
||||
resourceNode(map[string]any{"_type": "form_ref", "id": "article"}),
|
||||
}}
|
||||
bag := app.New(map[string]any{"page": page, "db": map[string]any{"url": uri}})
|
||||
var err error
|
||||
bag, err = app.Auth(bag, []any{map[string]any{"username": "admin", "password": "secret", "role": "admin"}}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
selected := form.SetFields(form.New("articles", "insert", ""), fields[1:2])
|
||||
selected = form.SetRules(selected, []any{map[string]any{"field": "title", "rule": "required", "message": "Title required"}})
|
||||
selected = form.SetLabels(selected, "Publish", "Cancel", "/")
|
||||
bag, err = app.MountForm(bag, "article", selected)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detailed := map[string]any{"_type": "data_query", "source": "articles", "detail": true,
|
||||
"where": map[string]any{"slug": "{slug}"}}
|
||||
bag, err = app.Route(bag, "/post/{slug}", map[string]any{"title": "Article", "artifact_nodes": []any{resourceNode(detailed)}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler, err := NewHandler(bag, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
call := func(method, path, body, cookie string) *httptest.ResponseRecorder {
|
||||
request := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
if cookie != "" {
|
||||
request.Header.Set("Cookie", cookie)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
return recorder
|
||||
}
|
||||
initial := call("GET", "/", "", "")
|
||||
if initial.Code != http.StatusOK {
|
||||
t.Fatalf("initial: %d %s", initial.Code, initial.Body.String())
|
||||
}
|
||||
text := initial.Body.String()
|
||||
if !strings.Contains(text, "Guest login") || strings.Contains(text, "Private desk") ||
|
||||
!strings.Contains(text, "Short summary") || strings.Contains(text, "Full article body") ||
|
||||
!strings.Contains(text, "Original <title>") {
|
||||
t.Fatal(text)
|
||||
}
|
||||
cookies := initial.Result().Cookies()
|
||||
if len(cookies) == 0 {
|
||||
t.Fatal("rendered form has no actual session cookie")
|
||||
}
|
||||
cookie := cookies[0].Name + "=" + cookies[0].Value
|
||||
match := regexp.MustCompile(`name="_csrf" value="([^"]+)"`).FindStringSubmatch(text)
|
||||
if len(match) != 2 {
|
||||
t.Fatal("resource form omitted its CSRF token")
|
||||
}
|
||||
token := match[1]
|
||||
bad := call("POST", "/_form/article", "title=Rejected&_csrf=wrong", cookie)
|
||||
if bad.Code != http.StatusForbidden {
|
||||
t.Fatalf("bad csrf accepted: %d %s", bad.Code, bad.Body.String())
|
||||
}
|
||||
invalid := call("POST", "/_form/article", url.Values{"_csrf": {token}, "title": {""}}.Encode(), cookie)
|
||||
if invalid.Code != http.StatusOK || !strings.Contains(invalid.Body.String(), "Title required") ||
|
||||
!strings.Contains(invalid.Body.String(), `name="_csrf" value="`+token+`"`) {
|
||||
t.Fatalf("validation retry: %d %s", invalid.Code, invalid.Body.String())
|
||||
}
|
||||
valid := call("POST", "/_form/article", url.Values{"_csrf": {token}, "title": {"Inserted after startup"}, "_mq_return": {"/new"}}.Encode(), cookie)
|
||||
if valid.Code != http.StatusSeeOther || valid.Header().Get("Location") != "/" {
|
||||
t.Fatalf("submit: %d %s", valid.Code, valid.Body.String())
|
||||
}
|
||||
current := call("GET", "/", "", cookie)
|
||||
if !strings.Contains(current.Body.String(), "Inserted after startup") {
|
||||
t.Fatal("query cached startup rows")
|
||||
}
|
||||
fragment := call("GET", "/_part/main", "", cookie)
|
||||
if fragment.Code != http.StatusOK || !strings.Contains(fragment.Body.String(), "Inserted after startup") ||
|
||||
!strings.Contains(fragment.Body.String(), `name="_csrf" value="`+token+`"`) ||
|
||||
strings.Contains(fragment.Body.String(), "<!DOCTYPE") {
|
||||
t.Fatalf("request fragment lost context: %d %s", fragment.Code, fragment.Body.String())
|
||||
}
|
||||
unknown := call("GET", "/_part/not-declared", "", cookie)
|
||||
if unknown.Code != http.StatusNotFound {
|
||||
t.Fatalf("unknown View slot: %d", unknown.Code)
|
||||
}
|
||||
|
||||
detail := call("GET", "/post/first?slug=other", "", cookie)
|
||||
if detail.Code != http.StatusOK || !strings.Contains(detail.Body.String(), "Full article body") ||
|
||||
strings.Contains(detail.Body.String(), "Short summary") {
|
||||
t.Fatal(detail.Body.String())
|
||||
}
|
||||
if detailed["where"].(map[string]any)["slug"] != "{slug}" {
|
||||
t.Fatal("request mutated retained Resource")
|
||||
}
|
||||
sid, ok := session.IDFromCookie(cookie)
|
||||
if !ok || !session.SetValue(sid, "username", "admin") {
|
||||
t.Fatal("could not establish fixture session")
|
||||
}
|
||||
logged := call("GET", "/", "", cookie)
|
||||
if strings.Contains(logged.Body.String(), "Guest login") || !strings.Contains(logged.Body.String(), "Private desk") {
|
||||
t.Fatal(logged.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestViewResourceValidationDoesNotQueryAndFailuresRemainVisible(t *testing.T) {
|
||||
query := map[string]any{"_type": "data_query", "source": "missing"}
|
||||
if _, err := artifact.RenderNodesWithResources([]any{resourceNode(query)}, ValidateViewResource); err != nil {
|
||||
t.Fatalf("startup unexpectedly queried missing DB: %v", err)
|
||||
}
|
||||
for _, resource := range []map[string]any{
|
||||
{"_type": "invented"}, {"_type": "data_query", "source": "items", "limit": 1.5},
|
||||
{"_type": "data_query", "source": "items", "link_prefix": "javascript:"},
|
||||
{"_type": "form_ref", "id": ""},
|
||||
} {
|
||||
if _, err := ValidateViewResource(resource); err == nil {
|
||||
t.Fatalf("bad resource accepted: %#v", resource)
|
||||
}
|
||||
}
|
||||
if _, err := artifact.RenderNodes([]any{resourceNode(query)}); err == nil {
|
||||
t.Fatal("offline render invented request context")
|
||||
}
|
||||
bag := app.New(map[string]any{"page": map[string]any{"artifact_nodes": []any{resourceNode(query)}}})
|
||||
handler, err := NewHandler(bag, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, httptest.NewRequest("GET", "/", nil))
|
||||
if response.Code != http.StatusInternalServerError || !strings.Contains(response.Body.String(), "no database") {
|
||||
t.Fatalf("missing backend became successful empty content: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestViewHeadResourcesServeInHeadAndNeverLeakIntoFragments(t *testing.T) {
|
||||
nodes := []any{
|
||||
map[string]any{"type": "resource", "value": map[string]any{"_type": "document_head", "meta": map[string]any{"key": "description", "value": "Actual SEO"}, "links": []any{map[string]any{"rel": "stylesheet", "href": "/theme.css"}}}},
|
||||
map[string]any{"type": "markdown", "slot": "content", "value": "# Real content"},
|
||||
}
|
||||
bag := app.New(map[string]any{"page": map[string]any{"title": "Head test", "artifact_nodes": nodes}})
|
||||
handler, err := NewHandler(bag, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, path := range []string{"/", "/_part/main", "/_part/content"} {
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, httptest.NewRequest("GET", path, nil))
|
||||
body := response.Body.String()
|
||||
if response.Code != http.StatusOK || !strings.Contains(body, "Real content") {
|
||||
t.Fatalf("%s %d %s", path, response.Code, body)
|
||||
}
|
||||
if path == "/" {
|
||||
head, rest, _ := strings.Cut(body, "</head>")
|
||||
if !strings.Contains(head, `<meta name="description" content="Actual SEO"`) || !strings.Contains(head, `href="/theme.css"`) || strings.Contains(rest, "Actual SEO") {
|
||||
t.Fatal(body)
|
||||
}
|
||||
} else if strings.Contains(body, "Actual SEO") || strings.Contains(body, "<head") || strings.Contains(body, "theme.css") {
|
||||
t.Fatal(body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,15 @@ func CallLibPath(path string, args map[string]any) (any, error) {
|
||||
// RunArtifact loads and runs a Document/Endpoint `.mq.md` (ADR 0007).
|
||||
// Request fields are passed as Metadata Binding overlays (`arg` / `--bind`).
|
||||
func RunArtifact(path string, args map[string]any) (any, error) {
|
||||
return RunArtifactAtRoot(path, args, "")
|
||||
}
|
||||
|
||||
// RunArtifactAtRoot retains a selected site directory within the host's grant.
|
||||
func RunArtifactAtRoot(path string, args map[string]any, root string) (any, error) {
|
||||
payload := map[string]any{"path": path}
|
||||
if root != "" {
|
||||
payload["root"] = root
|
||||
}
|
||||
if len(args) > 0 {
|
||||
payload["args"] = args
|
||||
}
|
||||
|
||||
+2
-2
@@ -11,8 +11,8 @@ import (
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/table"
|
||||
)
|
||||
|
||||
func TestAnlianPostsResolve(t *testing.T) {
|
||||
url := "sqlite:" + filepath.Join(t.TempDir(), "anlian.db")
|
||||
func TestDocumentPostsResolve(t *testing.T) {
|
||||
url := "sqlite:" + filepath.Join(t.TempDir(), "posts.db")
|
||||
fields := []any{
|
||||
map[string]any{"name": "title", "type": "text", "nullable": false},
|
||||
map[string]any{"name": "summary", "type": "text"},
|
||||
@@ -3,6 +3,7 @@ package render
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/assets"
|
||||
@@ -846,6 +847,15 @@ func resolveLayout(page map[string]any) string {
|
||||
return normalizeLayout(raw)
|
||||
}
|
||||
|
||||
// DocumentHead reuses ordinary Document metadata, links and native head boot
|
||||
// helpers without adding application configuration or a second HTML dialect.
|
||||
func DocumentHead(title string, meta map[string]any, links []assets.HeadLink) string {
|
||||
if title == "" {
|
||||
title = "Marqdo"
|
||||
}
|
||||
return headHTML(map[string]any{"meta": meta, "head": assets.HeadLinksToJSON(links)}, title)
|
||||
}
|
||||
|
||||
func headHTML(page map[string]any, defaultTitle string) string {
|
||||
pageTitle := defaultTitle
|
||||
if meta, ok := page["meta"].(map[string]any); ok {
|
||||
@@ -859,7 +869,13 @@ func headHTML(page map[string]any, defaultTitle string) string {
|
||||
s.WriteString(fmt.Sprintf(`<meta name="csrf-token" content="%s"/>`, esc(strings.TrimSpace(csrf))))
|
||||
}
|
||||
if meta, ok := page["meta"].(map[string]any); ok {
|
||||
for k, v := range meta {
|
||||
keys := make([]string, 0, len(meta))
|
||||
for key := range meta {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
v := meta[k]
|
||||
if k == "title" {
|
||||
continue
|
||||
}
|
||||
@@ -1361,6 +1377,39 @@ func renderFragment(page map[string]any, dbURL, slot string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// RenderQueryRows projects native database records into existing card/article
|
||||
// rendering. Query failures remain with the Resource caller, never empty success.
|
||||
func RenderQueryRows(rows any, detail bool, prefix string) string {
|
||||
raw, _ := rows.([]any)
|
||||
var body strings.Builder
|
||||
if !detail {
|
||||
body.WriteString(`<section class="content cards">`)
|
||||
}
|
||||
for _, row := range raw {
|
||||
item := projectArtifactRow(row)
|
||||
if item == nil {
|
||||
continue
|
||||
}
|
||||
if detail {
|
||||
if object, ok := row.(map[string]any); ok {
|
||||
if full, exists := object["body"]; exists {
|
||||
item["body"] = text(full)
|
||||
}
|
||||
if full, exists := object["content"]; exists {
|
||||
item["body"] = text(full)
|
||||
}
|
||||
}
|
||||
body.WriteString(renderArticle(item))
|
||||
break
|
||||
}
|
||||
body.WriteString(renderCard(map[string]any{"link_prefix": prefix}, item))
|
||||
}
|
||||
if !detail {
|
||||
body.WriteString("</section>")
|
||||
}
|
||||
return body.String()
|
||||
}
|
||||
|
||||
// RenderPage builds full-page HTML (or a part fragment when partID is set).
|
||||
func RenderPage(page map[string]any, dbURL string, partID string) string {
|
||||
// Explicit View Documents already own their structure and document shell.
|
||||
|
||||
@@ -163,6 +163,7 @@ extern int web_render_nodes(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_render_document(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_dom_markdown(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_serve_root(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_prepare_root(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_inspect(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_app_use(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_route_use(char *args_json, char **out_json, char **err_msg);
|
||||
@@ -272,6 +273,7 @@ static int register_core(void) {
|
||||
if (host_register((char *)"web_render_document", (char *)"page,body,db,title", web_render_document) != 0) return 1;
|
||||
if (host_register((char *)"web_dom_markdown", (char *)"text", web_dom_markdown) != 0) return 1;
|
||||
if (host_register((char *)"web_serve_root", (char *)"root,host,port,db,static_dir,middleware", web_serve_root) != 0) return 1;
|
||||
if (host_register((char *)"web_prepare_root", (char *)"root,host,port,db,static_dir,middleware", web_prepare_root) != 0) return 1;
|
||||
if (host_register((char *)"web_inspect", (char *)"app,root", web_inspect) != 0) return 1;
|
||||
if (host_register((char *)"web_app_use", (char *)"app,middleware", web_app_use) != 0) return 1;
|
||||
if (host_register((char *)"web_route_use", (char *)"route,middleware", web_route_use) != 0) return 1;
|
||||
|
||||
Reference in new issue
Block a user