feat(web): W-G14 anlian-mq acceptance and auth/session listen fixes

Add a GFM-first anlian rewrite under examples/anlian-mq to exercise Go
libweb (lists, detail, gates, login, WS). Wire RBAC/login into listen,
page query/order/detail ABIs, and stop issuing Max-Age=0 CSRF cookies so
browser login sessions stick.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-10 21:20:11 +08:00
1 parent e20cf8b386
commit ce195998c1
22 files changed
+1454 -20

No files matched your search

+77
View File
@@ -0,0 +1,77 @@
package main
/*
#cgo CFLAGS: -I${SRCDIR}/abi
#include "marqdo_abi_cgo.h"
extern int web_page_query(char *args_json, char **out_json, char **err_msg);
extern int web_page_order(char *args_json, char **out_json, char **err_msg);
extern int web_page_link_prefix(char *args_json, char **out_json, char **err_msg);
extern int web_page_css(char *args_json, char **out_json, char **err_msg);
extern int web_page_detail(char *args_json, char **out_json, char **err_msg);
*/
import "C"
import (
"github.com/marqdo/marqdo/plugins/web/internal/page"
)
//export web_page_query
func web_page_query(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
out := page.SetQuery(asPageMap(args["page"]), args["query"])
return replyJSON(outJSON, errMsg, out, nil)
}
//export web_page_order
func web_page_order(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
order, _ := argStr(args, "order", "排序")
out := page.SetOrder(asPageMap(args["page"]), order)
return replyJSON(outJSON, errMsg, out, nil)
}
//export web_page_link_prefix
func web_page_link_prefix(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
prefix, err := argStrReq(args, "prefix", "前缀")
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
out := page.SetLinkPrefix(asPageMap(args["page"]), prefix)
return replyJSON(outJSON, errMsg, out, nil)
}
//export web_page_css
func web_page_css(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
css, _ := argStr(args, "css", "样式")
out := page.AppendCSS(asPageMap(args["page"]), css)
return replyJSON(outJSON, errMsg, out, nil)
}
//export web_page_detail
func web_page_detail(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
on := page.AsBool(args["detail"], true)
if v, ok := args["详情"]; ok {
on = page.AsBool(v, on)
}
out := page.SetDetail(asPageMap(args["page"]), on)
return replyJSON(outJSON, errMsg, out, nil)
}
+506
View File
@@ -0,0 +1,506 @@
package httpx
import (
"fmt"
"io"
"net"
"net/http"
"strings"
"github.com/marqdo/marqdo/plugins/web/internal/app"
"github.com/marqdo/marqdo/plugins/web/internal/auth"
"github.com/marqdo/marqdo/plugins/web/internal/ratelimit"
"github.com/marqdo/marqdo/plugins/web/internal/session"
)
type gateMatch int
const (
gateMatchPrefix gateMatch = 0
gateMatchExact gateMatch = 1
)
type onDeny int
const (
onDenyForbid onDeny = 0
onDenyRedirect onDeny = 1
)
type gate struct {
path string
roles []string
matchMode gateMatch
onDeny onDeny
exclude []string
}
type authConfig struct {
users any
sessionTTL uint64
cookieSecure bool
admin bool
adminPrefix string
loginPath string
loginRedirect string
logoutRedirect string
gates []gate
}
func authConfigOf(appBag map[string]any) authConfig {
cfg := authConfig{
admin: boolish(appBag["admin"]),
adminPrefix: app.AdminPrefix(appBag),
sessionTTL: 3600,
}
cfg.loginPath = strOpt(appBag, "login_path", "")
if cfg.loginPath == "" {
cfg.loginPath = cfg.adminPrefix + "/login"
}
cfg.loginRedirect = strOpt(appBag, "login_redirect", "")
if cfg.loginRedirect == "" {
cfg.loginRedirect = cfg.adminPrefix
}
cfg.logoutRedirect = strOpt(appBag, "logout_redirect", "")
if cfg.logoutRedirect == "" {
cfg.logoutRedirect = cfg.loginPath
}
if v, ok := appBag["cookie_secure"].(bool); ok {
cfg.cookieSecure = v
}
if authBag, ok := appBag["auth"].(map[string]any); ok {
cfg.users = authBag["users"]
if n, ok := asUint64(authBag["session_ttl"]); ok && n > 0 {
cfg.sessionTTL = n
} else if n, ok := asUint64(authBag["ttl"]); ok && n > 0 {
cfg.sessionTTL = n
}
}
cfg.gates = parseGates(appBag["gates"])
return cfg
}
func parseGates(v any) []gate {
arr, ok := v.([]any)
if !ok {
return nil
}
out := make([]gate, 0, len(arr))
for _, item := range arr {
m, ok := item.(map[string]any)
if !ok {
continue
}
path := strings.TrimSpace(strOpt(m, "path", ""))
if path == "" {
path = strings.TrimSpace(strOpt(m, "路径", ""))
}
if path == "" {
continue
}
starred := strings.HasSuffix(path, "*")
if starred {
path = strings.TrimSuffix(path, "*")
}
roles := parseGateRoles(m["roles"])
if roles == nil {
roles = parseGateRoles(m["角色"])
}
if len(roles) == 0 {
roles = []string{"admin"}
}
matchS := strings.ToLower(strings.TrimSpace(strOpt(m, "match", "")))
if matchS == "" {
matchS = strings.ToLower(strings.TrimSpace(strOpt(m, "匹配", "")))
}
matchMode := gateMatchPrefix
switch matchS {
case "exact", "精确":
matchMode = gateMatchExact
case "prefix", "前缀":
matchMode = gateMatchPrefix
default:
if starred {
matchMode = gateMatchPrefix
}
}
denyS := strings.ToLower(strings.TrimSpace(strOpt(m, "on_deny", "")))
if denyS == "" {
denyS = strings.ToLower(strings.TrimSpace(strOpt(m, "拒绝", "")))
}
on := onDenyForbid
switch denyS {
case "redirect", "重定向", "login":
on = onDenyRedirect
case "forbid", "禁止", "403":
on = onDenyForbid
}
out = append(out, gate{
path: path,
roles: roles,
matchMode: matchMode,
onDeny: on,
exclude: parseExclude(m["exclude"], m["排除"]),
})
}
return out
}
func parseGateRoles(v any) []string {
switch t := v.(type) {
case string:
return session.ParseRolesCSV(t)
case []any:
var out []string
for _, item := range t {
if s, ok := item.(string); ok && strings.TrimSpace(s) != "" {
out = append(out, strings.ToLower(strings.TrimSpace(s)))
}
}
return out
case []string:
var out []string
for _, s := range t {
if strings.TrimSpace(s) != "" {
out = append(out, strings.ToLower(strings.TrimSpace(s)))
}
}
return out
default:
return nil
}
}
func parseExclude(primary, alt any) []string {
if primary == nil {
primary = alt
}
switch t := primary.(type) {
case string:
var out []string
for _, part := range strings.Split(t, ",") {
part = strings.TrimSpace(part)
if part != "" {
out = append(out, part)
}
}
return out
case []any:
var out []string
for _, item := range t {
if s, ok := item.(string); ok {
s = strings.TrimSpace(s)
if s != "" {
out = append(out, s)
}
}
}
return out
default:
return nil
}
}
func gateMatches(path string, g gate) bool {
pat := strings.TrimRight(strings.TrimSuffix(g.path, "*"), "/")
if pat == "" {
pat = "/"
}
switch g.matchMode {
case gateMatchExact:
return path == pat || path == g.path
default:
return path == pat || strings.HasPrefix(path, pat+"/")
}
}
func pathExcluded(path string, exclude []string, loginPath string) bool {
if path == loginPath || strings.HasPrefix(path, loginPath+"?") {
return true
}
for _, ex := range exclude {
ex = strings.TrimRight(strings.TrimSuffix(ex, "*"), "/")
if ex == "" {
continue
}
if path == ex || strings.HasPrefix(path, ex+"/") {
return true
}
}
return false
}
func withRBAC(next http.Handler, gates []gate, loginPath string) http.Handler {
if len(gates) == 0 {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
cookie := r.Header.Get("Cookie")
for _, g := range gates {
if !gateMatches(path, g) {
continue
}
if pathExcluded(path, g.exclude, loginPath) {
break
}
role := session.RoleFromCookie(cookie)
if !session.RoleAllowed(role, g.roles) {
if role == "visitor" && g.onDeny == onDenyRedirect {
nextQ := urlEncodePath(path)
dest := loginPath
if nextQ != "" && path != loginPath {
dest = loginPath + "?next=" + nextQ
}
http.Redirect(w, r, dest, http.StatusSeeOther)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusForbidden)
_, _ = io.WriteString(w, fmt.Sprintf(
"<!doctype html><html><body><h1>403 Forbidden</h1><p>Role `%s` cannot access `%s`.</p></body></html>",
esc(role), esc(path)))
return
}
break
}
next.ServeHTTP(w, r)
})
}
func urlEncodePath(path string) string {
var out strings.Builder
for _, b := range []byte(path) {
switch {
case b >= 'A' && b <= 'Z', b >= 'a' && b <= 'z', b >= '0' && b <= '9',
b == '-', b == '_', b == '.', b == '~', b == '/':
out.WriteByte(b)
default:
out.WriteString(fmt.Sprintf("%%%02X", b))
}
}
return out.String()
}
func withNavAuth(page map[string]any, cookieHeader string) {
sid, ok := session.IDFromCookie(cookieHeader)
loggedIn := false
var username string
if ok && sid != "" {
if v, has := session.GetValue(sid, "username"); has {
if u, ok := v.(string); ok && u != "" {
loggedIn = true
username = u
}
}
}
page["_logged_in"] = loggedIn
if loggedIn {
page["_nav_user"] = username
} else {
delete(page, "_nav_user")
}
}
func (st *state) mountAuthRoutes(mux *http.ServeMux) {
if st.auth.users == nil {
return
}
lp := st.auth.loginPath
mux.HandleFunc("GET "+lp, st.handleLoginGet)
mux.HandleFunc("POST "+lp, st.handleLoginPost)
altLogin := strings.TrimRight(st.auth.adminPrefix, "/") + "/login"
if altLogin != lp {
mux.HandleFunc("GET "+altLogin, st.handleLoginGet)
mux.HandleFunc("POST "+altLogin, st.handleLoginPost)
}
if st.auth.admin {
logoutPath := strings.TrimRight(st.auth.adminPrefix, "/") + "/logout"
mux.HandleFunc("GET "+logoutPath, st.handleLogout)
adminHome := strings.TrimRight(st.auth.adminPrefix, "/")
if adminHome == "" {
adminHome = "/admin"
}
mux.HandleFunc("GET "+adminHome+"/{$}", st.handleAdminHome)
}
}
func (st *state) handleLoginGet(w http.ResponseWriter, r *http.Request) {
if st.auth.users == nil {
http.Redirect(w, r, st.auth.loginRedirect, http.StatusSeeOther)
return
}
cookieHdr := r.Header.Get("Cookie")
if session.RoleFromCookie(cookieHdr) != "visitor" {
http.Redirect(w, r, loginDest(r, st.auth.loginRedirect), http.StatusSeeOther)
return
}
_, csrf, setCookie := resolveSession(r)
html := loginPageHTML(st.auth.loginPath, nil, csrf, r.URL.Query().Get("next"))
w.Header().Set("Content-Type", "text/html; charset=utf-8")
appendSetCookie(w, setCookie)
_, _ = io.WriteString(w, html)
}
func (st *state) handleLoginPost(w http.ResponseWriter, r *http.Request) {
if st.auth.users == nil {
http.Redirect(w, r, st.auth.loginRedirect, http.StatusSeeOther)
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
cookieHdr := r.Header.Get("Cookie")
sid, csrf, setCookie := resolveSession(r)
_, hadCookie := session.IDFromCookie(cookieHdr)
csrfToken := r.FormValue("_csrf")
if csrfToken != "" || hadCookie {
if !session.ValidateCSRF(sid, csrfToken) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
appendSetCookie(w, setCookie)
_, _ = io.WriteString(w, "<p class=\"flash err\">Invalid or missing CSRF token. Refresh and try again.</p>")
return
}
}
username := r.FormValue("username")
password := r.FormValue("password")
ip := clientIP(r)
if err := ratelimit.Check(ip, username); err != nil {
msg := err.Error()
w.Header().Set("Content-Type", "text/html; charset=utf-8")
appendSetCookie(w, setCookie)
_, _ = io.WriteString(w, loginPageHTML(st.auth.loginPath, &msg, csrf, r.FormValue("next")))
return
}
res := auth.Login(username, password, st.auth.users, st.auth.sessionTTL)
if ok, _ := res["ok"].(bool); !ok {
ratelimit.RecordFailure(ip, username)
errMsg := "Invalid username or password."
w.Header().Set("Content-Type", "text/html; charset=utf-8")
appendSetCookie(w, setCookie)
_, _ = io.WriteString(w, loginPageHTML(st.auth.loginPath, &errMsg, csrf, r.FormValue("next")))
return
}
ratelimit.ClearSuccess(ip, username)
sessID, _ := res["session_id"].(string)
dest := loginDest(r, st.auth.loginRedirect)
w.Header().Add("Set-Cookie", session.IssueCookie(sessID))
http.Redirect(w, r, dest, http.StatusSeeOther)
}
func (st *state) handleLogout(w http.ResponseWriter, r *http.Request) {
if sid, ok := session.IDFromCookie(r.Header.Get("Cookie")); ok {
auth.Logout(sid)
}
w.Header().Add("Set-Cookie", session.ClearCookie())
http.Redirect(w, r, st.auth.logoutRedirect, http.StatusSeeOther)
}
func (st *state) handleAdminHome(w http.ResponseWriter, r *http.Request) {
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>")
}
func loginDest(r *http.Request, fallback string) string {
next := strings.TrimSpace(r.FormValue("next"))
if next == "" {
next = strings.TrimSpace(r.URL.Query().Get("next"))
}
if next != "" && strings.HasPrefix(next, "/") && !strings.HasPrefix(next, "//") {
return next
}
return fallback
}
func loginPageHTML(loginAction string, errMsg *string, csrf string, next string) string {
errHTML := ""
if errMsg != nil && *errMsg != "" {
errHTML = fmt.Sprintf("<p class=\"flash err\">%s</p>", esc(*errMsg))
}
csrfField := ""
if csrf != "" {
csrfField = fmt.Sprintf("<input type=\"hidden\" name=\"_csrf\" value=\"%s\"/>", esc(csrf))
}
nextField := ""
if next != "" && strings.HasPrefix(next, "/") && !strings.HasPrefix(next, "//") {
nextField = fmt.Sprintf("<input type=\"hidden\" name=\"next\" value=\"%s\"/>", esc(next))
}
return fmt.Sprintf(`<!DOCTYPE html>
<html lang="zh-CN"><head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Admin Login</title>
<style>
:root { --ink:#1c1917; --muted:#78716c; --paper:#fafaf9; --line:#e7e5e4; --accent:#0f766e; --err:#b91c1c; }
* { box-sizing:border-box; }
body { margin:0; min-height:100vh; display:grid; place-items:center; background:var(--paper); color:var(--ink); font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; }
.login { background:#fff; border:1px solid var(--line); border-radius:10px; padding:2rem 2.25rem; width:min(92vw,22rem); box-shadow:0 8px 24px rgba(0,0,0,.05); }
.login h1 { margin:0 0 .25rem; font-size:1.4rem; }
.login .sub { color:var(--muted); margin:0 0 1.25rem; font-size:.9rem; }
.login form { display:grid; gap:.9rem; }
.login label { display:grid; gap:.25rem; font-size:.9rem; }
.login input { padding:.55rem .65rem; border:1px solid var(--line); border-radius:6px; font:inherit; }
.login button { background:var(--accent); color:#fff; border:0; padding:.6rem 1rem; border-radius:6px; cursor:pointer; font:inherit; }
.login button:hover { filter:brightness(1.05); }
.flash.err { background:#fef2f2; color:var(--err); border:1px solid #fecaca; padding:.6rem .8rem; border-radius:6px; margin:0 0 .9rem; font-size:.9rem; }
</style>
</head>
<body>
<div class="login">
<h1>Admin</h1>
<p class="sub">Sign in to manage this site.</p>
%s
<form method="post" action="%s">
%s%s
<label>Username<input name="username" autocomplete="username" required autofocus/></label>
<label>Password<input name="password" type="password" autocomplete="current-password" required/></label>
<button type="submit">Sign in</button>
</form>
</div>
</body></html>`, errHTML, esc(loginAction), csrfField, nextField)
}
func clientIP(r *http.Request) string {
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
if i := strings.Index(xff, ","); i >= 0 {
return strings.TrimSpace(xff[:i])
}
return strings.TrimSpace(xff)
}
if xri := r.Header.Get("X-Real-IP"); xri != "" {
return strings.TrimSpace(xri)
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
}
func asUint64(v any) (uint64, bool) {
switch t := v.(type) {
case float64:
if t > 0 {
return uint64(t), true
}
case int:
if t > 0 {
return uint64(t), true
}
case int64:
if t > 0 {
return uint64(t), true
}
case uint64:
if t > 0 {
return t, true
}
case string:
var n uint64
if _, err := fmt.Sscanf(strings.TrimSpace(t), "%d", &n); err == nil && n > 0 {
return n, true
}
}
return 0, false
}
+72
View File
@@ -0,0 +1,72 @@
package httpx
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/marqdo/marqdo/plugins/web/internal/auth"
"github.com/marqdo/marqdo/plugins/web/internal/session"
)
func TestGateMatchesAndRBAC(t *testing.T) {
session.Configure(session.Config{TTLSec: 3600})
session.Reset(3600)
gates := []gate{{
path: "/write",
roles: []string{"admin"},
matchMode: gateMatchPrefix,
onDeny: onDenyRedirect,
exclude: []string{"/admin/login"},
}}
mux := http.NewServeMux()
mux.HandleFunc("GET /write", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
handler := withRBAC(mux, gates, "/admin/login")
req := httptest.NewRequest(http.MethodGet, "/write", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusSeeOther {
t.Fatalf("anonymous /write: got %d", rec.Code)
}
loc := rec.Header().Get("Location")
if loc != "/admin/login?next=/write" {
t.Fatalf("location=%q", loc)
}
res := auth.Login("admin", "secret", []any{
map[string]any{"username": "admin", "password": "secret", "role": "admin"},
}, 3600)
sid, _ := res["session_id"].(string)
req2 := httptest.NewRequest(http.MethodGet, "/write", nil)
req2.Header.Set("Cookie", "marqdo_sid="+sid)
rec2 := httptest.NewRecorder()
handler.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusOK {
t.Fatalf("authed /write: got %d", rec2.Code)
}
}
func TestWithNavAuth(t *testing.T) {
session.Configure(session.Config{TTLSec: 3600})
session.Reset(3600)
page := map[string]any{}
withNavAuth(page, "")
if page["_logged_in"] != false {
t.Fatalf("expected logged out")
}
res := auth.Login("u", "p", []any{
map[string]any{"username": "u", "password": "p"},
}, 3600)
sid, _ := res["session_id"].(string)
withNavAuth(page, "marqdo_sid="+sid)
if page["_logged_in"] != true {
t.Fatalf("expected logged in")
}
if page["_nav_user"] != "u" {
t.Fatalf("nav user=%v", page["_nav_user"])
}
}
+3 -1
View File
@@ -79,7 +79,9 @@ func resolveSession(r *http.Request) (sid, csrf string, setCookie *string) {
}
sid = session.NewID(0)
tok, _ := session.CSRFFor(sid)
c := session.SessionCookie(sid, 0, false)
// Use configured session TTL (never Max-Age=0): browsers drop Max-Age=0
// immediately, so CSRF cookies from GET /login would never stick.
c := session.IssueCookie(sid)
return sid, tok, &c
}
+33 -14
View File
@@ -21,7 +21,9 @@ import (
"github.com/marqdo/marqdo/plugins/web/internal/db"
"github.com/marqdo/marqdo/plugins/web/internal/form"
"github.com/marqdo/marqdo/plugins/web/internal/middleware"
"github.com/marqdo/marqdo/plugins/web/internal/ratelimit"
"github.com/marqdo/marqdo/plugins/web/internal/render"
"github.com/marqdo/marqdo/plugins/web/internal/session"
"github.com/marqdo/marqdo/plugins/web/internal/sitemap"
)
@@ -31,11 +33,20 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
if appBag == nil {
appBag = map[string]any{}
}
authCfg := authConfigOf(appBag)
dbURL := dbURLOf(appBag)
session.Configure(session.Config{
DBURL: dbURL,
TTLSec: authCfg.sessionTTL,
CookieSecure: authCfg.cookieSecure,
})
session.Reset(authCfg.sessionTTL)
ratelimit.Reset()
page, _ := appBag["page"].(map[string]any)
if page == nil {
page = map[string]any{}
}
dbURL := dbURLOf(appBag)
routes := map[string]any{}
if r, ok := appBag["routes"].(map[string]any); ok {
routes = r
@@ -87,6 +98,7 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
galleryRoutes: routeMapOf(appBag, "gallery_routes"),
proxyRoutes: routeMapOf(appBag, "proxy_routes"),
invokeRoutes: routeMapOf(appBag, "invoke_routes"),
auth: authCfg,
}
mux := http.NewServeMux()
@@ -108,10 +120,10 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
} else {
pv := pageV
mux.HandleFunc("GET "+routePath, func(w http.ResponseWriter, r *http.Request) {
st.writePage(w, pv)
st.writePage(w, r, pv)
})
mux.HandleFunc("GET "+routePath+"/_part/{id}", func(w http.ResponseWriter, r *http.Request) {
st.writePart(w, pv, r.PathValue("id"))
st.writePart(w, r, pv, r.PathValue("id"))
})
}
}
@@ -180,10 +192,13 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
st.mountGalleryRoutes(mux)
st.mountProxyRoutes(mux)
st.mountInvokeRoutes(mux)
st.mountAuthRoutes(mux)
mux.HandleFunc("/{path...}", st.handleNotFound)
return withMiddleware(mux, mw), nil
handler := withMiddleware(mux, mw)
handler = withRBAC(handler, authCfg.gates, authCfg.loginPath)
return handler, nil
}
// Listen binds host:port from the app bag and serves until interrupt/kill.
@@ -245,30 +260,34 @@ type state struct {
galleryRoutes map[string]any
proxyRoutes map[string]any
invokeRoutes map[string]any
auth authConfig
}
func (st *state) handleHome(w http.ResponseWriter, r *http.Request) {
st.writePage(w, st.page)
st.writePage(w, r, st.page)
}
func (st *state) handleHomePart(w http.ResponseWriter, r *http.Request) {
st.writePart(w, st.page, r.PathValue("id"))
st.writePart(w, r, st.page, r.PathValue("id"))
}
func (st *state) preparePage(page map[string]any) map[string]any {
func (st *state) preparePage(page map[string]any, r *http.Request) map[string]any {
p := cloneMap(page)
assets.MergeSiteHead(p, st.siteHead)
if r != nil {
withNavAuth(p, r.Header.Get("Cookie"))
}
return p
}
func (st *state) writePage(w http.ResponseWriter, page map[string]any) {
html := render.RenderPage(st.preparePage(page), st.dbURL, "")
func (st *state) writePage(w http.ResponseWriter, r *http.Request, page map[string]any) {
html := render.RenderPage(st.preparePage(page, r), st.dbURL, "")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = io.WriteString(w, html)
}
func (st *state) writePart(w http.ResponseWriter, page map[string]any, id string) {
html := render.RenderPage(st.preparePage(page), st.dbURL, id)
func (st *state) writePart(w http.ResponseWriter, r *http.Request, page map[string]any, id string) {
html := render.RenderPage(st.preparePage(page, r), st.dbURL, id)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = io.WriteString(w, html)
}
@@ -323,7 +342,7 @@ func (st *state) writeSitemap(w http.ResponseWriter, cfg map[string]any) {
func (st *state) handleNotFound(w http.ResponseWriter, r *http.Request) {
if st.page404 != nil {
html := render.RenderPage(st.preparePage(st.page404), st.dbURL, "")
html := render.RenderPage(st.preparePage(st.page404, r), st.dbURL, "")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
_, _ = io.WriteString(w, html)
@@ -341,7 +360,7 @@ func (st *state) makeDynamicPage(page map[string]any, pattern string) http.Handl
params[name] = r.PathValue(name)
}
injectParams(p, params)
st.writePage(w, p)
st.writePage(w, r, p)
}
}
@@ -354,7 +373,7 @@ func (st *state) makeDynamicPart(page map[string]any, pattern string) http.Handl
params[name] = r.PathValue(name)
}
injectParams(p, params)
st.writePart(w, p, r.PathValue("id"))
st.writePart(w, r, p, r.PathValue("id"))
}
}
+82 -5
View File
@@ -1,6 +1,9 @@
package page
import "strconv"
import (
"strconv"
"strings"
)
// New builds a page bag (ABI web_page_new), matching the Rust plugin shape.
func New(args map[string]any) map[string]any {
@@ -24,10 +27,7 @@ func New(args map[string]any) map[string]any {
// Paginate stamps page.paginate with offset/limit/path (Rust web_page_paginate).
func Paginate(page map[string]any, offset, limit int64, path string) map[string]any {
out := map[string]any{}
for k, v := range page {
out[k] = v
}
out := clone(page)
if path == "" {
path = "/"
}
@@ -39,6 +39,61 @@ func Paginate(page map[string]any, offset, limit int64, path string) map[string]
return out
}
// SetQuery stamps page.query (Rust web_page_query).
func SetQuery(page map[string]any, query any) map[string]any {
out := clone(page)
if query == nil {
query = map[string]any{}
}
out["query"] = query
return out
}
// SetOrder stamps page.order (Rust web_page_order).
func SetOrder(page map[string]any, order string) map[string]any {
out := clone(page)
out["order"] = order
return out
}
// SetLinkPrefix stamps page.link_prefix (Rust web_page_link_prefix).
func SetLinkPrefix(page map[string]any, prefix string) map[string]any {
out := clone(page)
out["link_prefix"] = prefix
return out
}
// AppendCSS appends raw CSS to page.styles_css (Rust web_page_css).
func AppendCSS(page map[string]any, css string) map[string]any {
out := clone(page)
css = strings.TrimSpace(css)
if css == "" {
return out
}
prev, _ := out["styles_css"].(string)
if prev == "" {
out["styles_css"] = css
} else {
out["styles_css"] = prev + "\n" + css
}
return out
}
// SetDetail stamps page.detail bool (Rust web_page_detail).
func SetDetail(page map[string]any, on bool) map[string]any {
out := clone(page)
out["detail"] = on
return out
}
func clone(page map[string]any) map[string]any {
out := map[string]any{}
for k, v := range page {
out[k] = v
}
return out
}
func strOpt(args map[string]any, key, def string) string {
if s, ok := strAny(args, key); ok {
return s
@@ -66,3 +121,25 @@ func strAny(args map[string]any, keys ...string) (string, bool) {
}
return "", false
}
// AsBool interprets ABI detail flags (bool / 0|1 / 真|是|true).
func AsBool(v any, def bool) bool {
if v == nil {
return def
}
switch t := v.(type) {
case bool:
return t
case float64:
return t != 0
case string:
s := strings.TrimSpace(t)
switch s {
case "1", "true", "True", "yes", "on", "真", "是":
return true
case "0", "false", "False", "no", "off", "假", "否", "":
return false
}
}
return def
}
@@ -0,0 +1,38 @@
package render
import (
"fmt"
"strings"
"testing"
"github.com/marqdo/marqdo/plugins/web/internal/compose"
"github.com/marqdo/marqdo/plugins/web/internal/db"
"github.com/marqdo/marqdo/plugins/web/internal/table"
)
func TestAnlianPostsResolve(t *testing.T) {
url := "sqlite:/home/cflmy/work/marqdo/examples/anlian-mq/data/anlian-mq.db"
card := map[string]any{
"属性": []any{"title", "body", "meta", "href"},
"值": []any{"posts.title", "posts.summary", "posts.board", "posts.slug"},
"样式": []any{"", "", "", ""},
}
page, err := compose.ComposeMain(map[string]any{"title": "帖子", "intro": "<h1>帖子</h1>"}, card, func(path string) (any, error) {
return nil, fmt.Errorf("no lib %s", path)
})
if err != nil {
t.Fatal(err)
}
pm := page.(map[string]any)
binds, _ := table.AsBind(pm["main"]).([]any)
tn, ok := table.BindTableName(binds)
t.Logf("table=%v BindTableName=%q ok=%v main=%v", pm["table"], tn, ok, pm["main"])
out, err := db.Select(url, tn, 200, db.SelectOpts{Order: "-created_at"})
t.Logf("select err=%v rows=%v", err, out["rows"])
intro, items, _ := resolveMain(pm, url)
t.Logf("intro=%q items=%d", intro, len(items))
html := RenderPage(pm, url, "")
if !strings.Contains(html, "欢迎") {
t.Fatalf("missing 欢迎 in html:\n%s", html)
}
}
+38
View File
@@ -537,7 +537,15 @@ func ValidateCSRF(id, token string) bool {
}
// SessionCookie builds Set-Cookie for marqdo_sid.
// ttlSec 0 means the configured default (never Max-Age=0 — that clears cookies;
// use ClearCookie for logout).
func SessionCookie(id string, ttlSec uint64, secure bool) string {
if ttlSec == 0 {
ttlSec = getCfg().TTLSec
if ttlSec == 0 {
ttlSec = defaultTTL
}
}
s := fmt.Sprintf("marqdo_sid=%s; HttpOnly; Path=/; SameSite=Lax; Max-Age=%d", id, ttlSec)
if secure {
s += "; Secure"
@@ -545,6 +553,17 @@ func SessionCookie(id string, ttlSec uint64, secure bool) string {
return s
}
// IssueCookie builds Set-Cookie using Configure'd TTL and CookieSecure.
func IssueCookie(id string) string {
c := getCfg()
return SessionCookie(id, c.TTLSec, c.CookieSecure)
}
// ClearCookie is the Set-Cookie value that expires marqdo_sid immediately.
func ClearCookie() string {
return "marqdo_sid=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax"
}
// IDFromCookie parses marqdo_sid from a Cookie header.
func IDFromCookie(cookieHeader string) (string, bool) {
if cookieHeader == "" {
@@ -574,6 +593,25 @@ func ParseRolesCSV(raw string) []string {
return out
}
// RoleFromCookie returns session role (visitor when anonymous or missing).
func RoleFromCookie(cookieHeader string) string {
sid, ok := IDFromCookie(cookieHeader)
if !ok {
return "visitor"
}
if v, ok := GetValue(sid, "role"); ok {
if s, ok := v.(string); ok && s != "" {
return strings.ToLower(s)
}
}
if v, ok := GetValue(sid, "username"); ok {
if s, ok := v.(string); ok && s != "" {
return "admin"
}
}
return "visitor"
}
// RoleAllowed reports whether role is in allowed (empty allowed = all).
func RoleAllowed(role string, allowed []string) bool {
if len(allowed) == 0 {
@@ -3,6 +3,7 @@ package session_test
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/alicebob/miniredis/v2"
@@ -57,6 +58,13 @@ func TestCSRFAndCookie(t *testing.T) {
if !ok || got != id {
t.Fatalf("cookie parse %q != %q", got, id)
}
zero := session.SessionCookie(id, 0, false)
if strings.Contains(zero, "Max-Age=0") {
t.Fatalf("ttl 0 must not clear cookie: %s", zero)
}
if !strings.Contains(session.ClearCookie(), "Max-Age=0") {
t.Fatal("ClearCookie should expire")
}
}
func TestSessionPersistsInSQLite(t *testing.T) {
+10
View File
@@ -51,6 +51,11 @@ static int host_query(char *name, char *args_json, char **out_json, char **err_m
extern int web_go_ready(char *args_json, char **out_json, char **err_msg);
extern int web_page_new(char *args_json, char **out_json, char **err_msg);
extern int web_page_query(char *args_json, char **out_json, char **err_msg);
extern int web_page_order(char *args_json, char **out_json, char **err_msg);
extern int web_page_link_prefix(char *args_json, char **out_json, char **err_msg);
extern int web_page_css(char *args_json, char **out_json, char **err_msg);
extern int web_page_detail(char *args_json, char **out_json, char **err_msg);
extern int web_style(char *args_json, char **out_json, char **err_msg);
extern int web_compose_components(char *args_json, char **out_json, char **err_msg);
extern int web_compose_main(char *args_json, char **out_json, char **err_msg);
@@ -138,6 +143,11 @@ extern int web_api_key_check(char *args_json, char **out_json, char **err_msg);
static int register_core(void) {
if (host_register((char *)"web_go_ready", (char *)"", web_go_ready) != 0) return 1;
if (host_register((char *)"web_page_new", (char *)"title,intro,shell_css,layout,asset_version", web_page_new) != 0) return 1;
if (host_register((char *)"web_page_query", (char *)"page,query", web_page_query) != 0) return 1;
if (host_register((char *)"web_page_order", (char *)"page,order", web_page_order) != 0) return 1;
if (host_register((char *)"web_page_link_prefix", (char *)"page,prefix", web_page_link_prefix) != 0) return 1;
if (host_register((char *)"web_page_css", (char *)"page,css", web_page_css) != 0) return 1;
if (host_register((char *)"web_page_detail", (char *)"page,detail", web_page_detail) != 0) return 1;
if (host_register((char *)"web_style", (char *)"name,table,strict", web_style) != 0) return 1;
if (host_register((char *)"web_compose_components", (char *)"page,components", web_compose_components) != 0) return 1;
if (host_register((char *)"web_compose_main", (char *)"page,main", web_compose_main) != 0) return 1;