release: v1.0.1 — fix Go libweb dynamic-route query, Markdown, CSS false positives

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-15 14:48:47 +08:00
1 parent 761b92afce
commit 3eb8e732ea
17 files changed
+375 -43

No files matched your search

+27 -15
View File
@@ -462,18 +462,8 @@ fn select_page_data(
offset: i64,
) -> Value {
let mut where_v = args.get("query").cloned();
if let Some(m) = where_v.as_ref().and_then(|v| v.as_object()) {
if m.iter().any(|(_, v)| v.as_str().is_some_and(|s| s.contains('{'))) {
let mut resolved = Map::new();
for (k, v) in m {
let v = match v {
Value::String(s) => Value::String(resolve_params(s.as_str(), args)),
other => other.clone(),
};
resolved.insert(k.clone(), v);
}
where_v = Some(Value::Object(resolved));
}
if let Some(v) = where_v.take() {
where_v = Some(resolve_placeholders(v, args));
}
let order = args.get("order").and_then(|v| v.as_str());
let paginate = args.get("paginate").is_some();
@@ -493,6 +483,26 @@ fn select_page_data(
.unwrap_or(json!({ "rows": [] }))
}
/// Recursively replace `{param}` in all string leaves (columnar / row tables).
fn resolve_placeholders(v: Value, args: &Value) -> Value {
match v {
Value::String(s) => Value::String(resolve_params(&s, args)),
Value::Array(arr) => Value::Array(
arr.into_iter()
.map(|x| resolve_placeholders(x, args))
.collect(),
),
Value::Object(map) => {
let mut out = Map::new();
for (k, val) in map {
out.insert(k, resolve_placeholders(val, args));
}
Value::Object(out)
}
other => other,
}
}
/// Replace `{param}` placeholders with values from `args["params"]` (a map).
fn resolve_params(s: &str, args: &Value) -> String {
let params = args
@@ -532,8 +542,11 @@ fn field_css(obj: &Map<String, Value>, field: &str) -> String {
}
fn part_src_prefix(args: &Value) -> String {
match args.get("_route").and_then(|v| v.as_str()) {
Some(r) if !r.is_empty() && r != "/" => {
let raw = args.get("_route").and_then(|v| v.as_str()).unwrap_or("");
let resolved = resolve_params(raw, args);
match resolved.as_str() {
"" | "/" => String::new(),
r => {
let mut p = r.to_string();
while p.len() > 1 && p.ends_with('/') {
p.pop();
@@ -544,7 +557,6 @@ fn part_src_prefix(args: &Value) -> String {
format!("/{p}")
}
}
_ => String::new(),
}
}
+2 -3
View File
@@ -475,10 +475,9 @@ pub fn as_css_named_checked(name: &str, table: &Value, strict: bool) -> Result<S
}
fn css_value_suspicious(v: &Value) -> Option<&'static str> {
// Numbers are normal CSS (z-index, opacity, …). Do not treat Markup-evaluated
// ints/floats as bare `/` division false positives.
match v {
Value::Number(_) => Some(
"numeric CSS value (likely bare `/` division such as `1 / 5`; quote the cell, e.g. `\"1 / 5\"`)",
),
Value::Bool(_) => Some("boolean CSS value (quote the cell if intentional)"),
_ => None,
}
+1
View File
@@ -18,6 +18,7 @@ require (
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/yuin/goldmark v1.7.8 // indirect
github.com/yuin/gopher-lua v1.1.1 // indirect
go.uber.org/atomic v1.11.0 // indirect
golang.org/x/sys v0.47.0 // indirect
+2
View File
@@ -34,6 +34,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic=
github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
+35 -9
View File
@@ -136,19 +136,17 @@ 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)
fs := http.StripPrefix(staticMount, http.FileServer(http.Dir(staticDir)))
mux.Handle("GET "+staticMount+"/", fs)
mux.Handle("HEAD "+staticMount+"/", fs)
mux.Handle("GET "+staticMount, fs)
mux.Handle("HEAD "+staticMount, fs)
}
// 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 {
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)
continue
}
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)
@@ -158,6 +156,27 @@ 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)
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).
mux.Handle(staticMount+"/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
fs.ServeHTTP(w, r)
}))
mux.Handle(staticMount, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
fs.ServeHTTP(w, r)
}))
}
for _, from := range sortedKeys(st.redirects) {
spec, _ := st.redirects[from].(map[string]any)
to := strOpt(spec, "to", "/")
@@ -625,11 +644,18 @@ func collectPageForms(page map[string]any, forms map[string]any) {
func injectParams(page map[string]any, params map[string]any) {
page["params"] = params
// Stamp concrete path onto `_route` so part slot URLs use /post/slug not /post/{slug}.
if r, ok := page["_route"].(string); ok && r != "" && len(params) > 0 {
page["_route"] = render.ResolveRouteParams(r, params)
}
if parts, ok := page["parts"].(map[string]any); ok {
for k, cfg := range parts {
if m, ok := cfg.(map[string]any); ok {
cp := cloneMap(m)
cp["params"] = params
if r, ok := cp["_route"].(string); ok && r != "" {
cp["_route"] = render.ResolveRouteParams(r, params)
}
parts[k] = cp
}
}
+38
View File
@@ -0,0 +1,38 @@
package render
import (
"bytes"
"strings"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/renderer/html"
)
// markdownToHTML renders article body Markdown to HTML (GFM subset), matching
// the Rust web plugin's pulldown-cmark path.
func markdownToHTML(md string) string {
md = strings.TrimSpace(md)
if md == "" {
return ""
}
gm := goldmark.New(
goldmark.WithExtensions(
extension.GFM,
extension.Strikethrough,
),
goldmark.WithParserOptions(
parser.WithAutoHeadingID(),
),
goldmark.WithRendererOptions(
html.WithHardWraps(),
html.WithXHTML(),
),
)
var buf bytes.Buffer
if err := gm.Convert([]byte(md), &buf); err != nil {
return `<div class="article-body"><p class="article-p">` + esc(md) + `</p></div>`
}
return `<div class="article-body md">` + buf.String() + `</div>`
}
+80 -3
View File
@@ -191,7 +191,8 @@ func navWhenVisible(when navWhen, auth *bool) bool {
func selectPageData(url, tableName string, page map[string]any, limit, offset int64) map[string]any {
var where any
if q, ok := page["query"]; ok {
where = q
// Expand `{param}` placeholders from dynamic route params (ABI: 查询条件).
where = resolvePlaceholders(q, pageParams(page))
}
order, _ := page["order"].(string)
opts := db.SelectOpts{Where: where, Order: order}
@@ -205,6 +206,78 @@ func selectPageData(url, tableName string, page map[string]any, limit, offset in
return out
}
func pageParams(page map[string]any) map[string]any {
if page == nil {
return nil
}
p, _ := page["params"].(map[string]any)
return p
}
// resolvePlaceholders walks query / route values and replaces `{name}` with
// page.params[name]. Unmatched placeholders are left as `{name}` for debugging.
func resolvePlaceholders(v any, params map[string]any) any {
if len(params) == 0 {
return v
}
switch t := v.(type) {
case string:
return resolveParamsString(t, params)
case map[string]any:
out := make(map[string]any, len(t))
for k, val := range t {
out[k] = resolvePlaceholders(val, params)
}
return out
case []any:
out := make([]any, len(t))
for i, val := range t {
out[i] = resolvePlaceholders(val, params)
}
return out
default:
return v
}
}
// ResolveRouteParams substitutes `{name}` in a route pattern using params.
func ResolveRouteParams(pattern string, params map[string]any) string {
return resolveParamsString(pattern, params)
}
func resolveParamsString(s string, params map[string]any) string {
if !strings.Contains(s, "{") || len(params) == 0 {
return s
}
var out strings.Builder
rest := s
for {
start := strings.Index(rest, "{")
if start < 0 {
out.WriteString(rest)
break
}
out.WriteString(rest[:start])
rest = rest[start+1:]
end := strings.Index(rest, "}")
if end < 0 {
out.WriteByte('{')
out.WriteString(rest)
break
}
key := rest[:end]
if val, ok := params[key]; ok {
out.WriteString(text(val))
} else {
out.WriteByte('{')
out.WriteString(key)
out.WriteByte('}')
}
rest = rest[end+1:]
}
return out.String()
}
func resolveLinks(raw any, dbURL string, page map[string]any) []navLink {
if raw == nil {
return nil
@@ -400,6 +473,7 @@ func fieldCSS(obj map[string]any, field string) string {
func partSrcPrefix(page map[string]any) string {
r, _ := page["_route"].(string)
r = resolveParamsString(r, pageParams(page))
if r == "" || r == "/" {
return ""
}
@@ -479,6 +553,10 @@ const shellWidgets = `
.site-form { margin-top:1.25rem; max-width:28rem; }
.article { background:#fff; border:1px solid var(--line); border-radius:8px; padding:2rem; margin-top:1.5rem; }
.article-title { margin:0 0 .75rem; font-size:2rem; }
.article-body { line-height:1.75; color:var(--ink); }
.article-body.md { line-height: 1.75; }
.article-body.md pre { background:#f5f5f4; border:1px solid var(--line); border-radius:6px; padding:1rem; overflow-x:auto; }
.article-body.md code { font-size:.9em; }
.pagination { display:flex; gap:1rem; align-items:center; margin:1.5rem 0; font-size:.95rem; }
`
@@ -624,8 +702,7 @@ func renderArticle(it map[string]any) string {
s.WriteString(fmt.Sprintf(`<div class="article-tags">%s</div>`, esc(tag)))
}
if body != "" {
// Minimal: escape as paragraphs (full markdown deferred).
s.WriteString(fmt.Sprintf(`<div class="article-body"><p class="article-p">%s</p></div>`, esc(body)))
s.WriteString(markdownToHTML(body))
}
s.WriteString("</article>")
return s.String()
@@ -227,3 +227,33 @@ func TestRenderPageNavChrome(t *testing.T) {
}
}
}
func TestResolveRouteParams(t *testing.T) {
got := render.ResolveRouteParams("/post/{slug}", map[string]any{"slug": "hello-marqdo"})
if got != "/post/hello-marqdo" {
t.Fatalf("got %q", got)
}
got = render.ResolveRouteParams("/post/{slug}", map[string]any{})
if got != "/post/{slug}" {
t.Fatalf("unmatched must stay: %q", got)
}
}
func TestPartSlotSrcUsesResolvedRoute(t *testing.T) {
page := map[string]any{
"title": "post",
"intro": "",
"_route": "/post/{slug}",
"params": map[string]any{"slug": "hello-marqdo"},
"parts": map[string]any{
"index": map[string]any{"slot": "main"},
},
}
html := render.RenderPage(page, "", "")
if strings.Contains(html, "/post/{slug}/_part/") {
t.Fatalf("slot src still has placeholder: %s", html)
}
if !strings.Contains(html, `data-slot-src="/post/hello-marqdo/_part/index"`) {
t.Fatalf("missing resolved slot src: %s", html)
}
}
@@ -0,0 +1,105 @@
package render
import (
"path/filepath"
"strings"
"testing"
"github.com/marqdo/marqdo/plugins/web/internal/db"
)
func TestResolvePlaceholdersColumnarAndRows(t *testing.T) {
params := map[string]any{"slug": "hello-marqdo"}
col := map[string]any{
"字段": []any{"slug"},
"操作": []any{"="},
"值": []any{"{slug}"},
}
got := resolvePlaceholders(col, params).(map[string]any)
vals := got["值"].([]any)
if vals[0] != "hello-marqdo" {
t.Fatalf("columnar 值=%v", vals)
}
rows := []any{
map[string]any{"字段": "slug", "操作": "=", "值": "{slug}"},
}
gotRows := resolvePlaceholders(rows, params).([]any)
m := gotRows[0].(map[string]any)
if m["值"] != "hello-marqdo" {
t.Fatalf("row 值=%v", m["值"])
}
top := map[string]any{"slug": "{slug}"}
gotTop := resolvePlaceholders(top, params).(map[string]any)
if gotTop["slug"] != "hello-marqdo" {
t.Fatalf("map string=%v", gotTop["slug"])
}
}
func TestSelectPageDataResolvesSlug(t *testing.T) {
dir := t.TempDir()
dbPath := filepath.Join(dir, "t.db")
url := "sqlite:" + dbPath
t.Cleanup(db.ResetPool)
fields := []any{
map[string]any{"name": "slug", "type": "text", "nullable": false},
map[string]any{"name": "title", "type": "text", "nullable": false},
map[string]any{"name": "body", "type": "text", "nullable": true},
}
if _, err := db.Init(url, "posts", fields); err != nil {
t.Fatal(err)
}
if _, err := db.Insert(url, "posts", []any{
map[string]any{"slug": "hello-marqdo", "title": "Hello", "body": "## Hi\n\n*world*"},
}); err != nil {
t.Fatal(err)
}
page := map[string]any{
"title": "post",
"detail": true,
"_route": "/post/{slug}",
"params": map[string]any{"slug": "hello-marqdo"},
"query": map[string]any{
"字段": []any{"slug"},
"操作": []any{"="},
"值": []any{"{slug}"},
},
"main": []any{
map[string]any{"front": "title", "back": "posts.title"},
map[string]any{"front": "body", "back": "posts.body"},
},
"parts": map[string]any{
"index": map[string]any{"slot": "main"},
},
}
html := RenderPage(page, url, "")
if !strings.Contains(html, `class="article-title"`) || !strings.Contains(html, "Hello") {
t.Fatalf("missing article title: %s", html)
}
if !strings.Contains(html, `class="article-body md"`) {
t.Fatalf("missing markdown body wrapper: %s", html)
}
if !strings.Contains(html, "world") {
t.Fatalf("missing markdown content: %s", html)
}
if strings.Contains(html, "{slug}") {
t.Fatalf("literal {slug} still present: %s", html)
}
if !strings.Contains(html, `/post/hello-marqdo/_part/`) {
t.Fatalf("slot prefix not resolved: %s", html)
}
}
func TestMarkdownToHTML(t *testing.T) {
out := markdownToHTML("## Title\n\n**bold** and `code`")
if !strings.Contains(out, `class="article-body md"`) {
t.Fatalf("%s", out)
}
if !strings.Contains(out, "<h2") || !strings.Contains(out, "<strong>bold</strong>") {
t.Fatalf("%s", out)
}
}
+20 -2
View File
@@ -38,12 +38,30 @@ func TestStyleStrictKeepsQuotedSlash(t *testing.T) {
}
}
func TestStyleStrictRejectsNumeric(t *testing.T) {
func TestStyleStrictAllowsNumeric(t *testing.T) {
css, err := style.Style(map[string]any{
"name": "x",
"strict": true,
"table": []any{
map[string]any{"选择器": ".x", "属性": "z-index", "值": float64(20)},
map[string]any{"选择器": ".y", "属性": "opacity", "值": float64(0.5)},
map[string]any{"选择器": ".z", "属性": "font-weight", "值": float64(700)},
},
})
if err != nil {
t.Fatalf("numeric CSS must not be suspicious: %v", err)
}
if !strings.Contains(css, "z-index: 20") || !strings.Contains(css, "opacity: 0.5") {
t.Fatalf("%q", css)
}
}
func TestStyleStrictRejectsBoolean(t *testing.T) {
_, err := style.Style(map[string]any{
"name": "x",
"strict": true,
"table": []any{
map[string]any{"选择器": ".x", "属性": "grid-column", "值": float64(0)},
map[string]any{"选择器": ".x", "属性": "display", "值": true},
},
})
if err == nil || !strings.Contains(err.Error(), "suspicious") {
+2 -2
View File
@@ -693,9 +693,9 @@ func AsCSSNamedChecked(name string, table any, strict bool) (string, error) {
}
func cssValueSuspicious(v any) string {
// Numbers are normal CSS (z-index, opacity, font-weight, unitless 0).
// Do not treat Markup-evaluated ints/floats as "bare `/` division".
switch v.(type) {
case float64, int, int64:
return "numeric CSS value (likely bare `/` division such as `1 / 5`; quote the cell, e.g. `\"1 / 5\"`)"
case bool:
return "boolean CSS value (quote the cell if intentional)"
default: