diff --git a/.gitignore b/.gitignore
index c0b0ffa..6dc5940 100644
--- a/.gitignore
+++ b/.gitignore
@@ -60,6 +60,7 @@ plugins/*/tmp/
/examples/web-net-site/data/
/examples/web-net-site-zh/data/
/examples/marqdo-blog/data/
+/examples/anlian-mq/data/
# Quantum draw/SVG runtime outputs (sources & gold .mq.md stay tracked)
/tests/ext/quantum-*.svg
diff --git a/examples/anlian-mq/README.md b/examples/anlian-mq/README.md
new file mode 100644
index 0000000..c2b1188
--- /dev/null
+++ b/examples/anlian-mq/README.md
@@ -0,0 +1,53 @@
+# 暗恋见君 · Marqdo 重写(验收切片)
+
+用 **Marqdo + `ext/web`(Go `libweb`)** 重写暗恋见君的主路径,验证「代码即文档」能否撑起真实社区站点。
+
+外部依赖(完整生产):PostgreSQL + Redis。本示例默认 **SQLite**,便于本机一键跑通;URL 换 `postgres://…` 即可外接。
+
+## 设计约定
+
+| 做 | 不做 |
+|----|------|
+| GFM 表装配导航、样式、库表、种子、表单、门禁 | `json.set` 链拼页面 |
+| `网页.*` / `table.put` 命名方法 | 手写业务 JS 袋 |
+| 分文件:`db/`、`components/`、`styles/` | 单文件堆全部 HTML |
+
+对照原站 [anlian](../../../anlian/)(Django)与施工图 [ext-web-go-rewrite.md](../../doc/design/ext-web-go-rewrite.md) §8。
+
+## 已覆盖主路径
+
+| 路径 | 能力 |
+|------|------|
+| `/` | 首页 + 最新帖子卡片 |
+| `/posts`、`/post/{slug}` | 帖子列表 / 详情 |
+| `/news`、`/news/{slug}` | 新闻列表 / 详情 |
+| `/write` | 发帖表单(需登录) |
+| `/search` | FTS 关键词(表单 → 查询页) |
+| `/chat` | 公聊页 + `/chat/ws` broadcast |
+| `/admin` | 鉴权门禁后台 |
+| `/sitemap.xml`、`/robots.txt` | 站长 |
+
+## 运行
+
+```bash
+# 仓库根目录
+export PATH="$HOME/.local/go/bin:$PATH"
+./scripts/build-web-plugin.sh
+./target/debug/marqdo run examples/anlian-mq/index.mq.md
+# → http://127.0.0.1:18180/
+
+# 另开终端
+bash examples/anlian-mq/smoke.sh
+```
+
+离线装配(不 listen):
+
+```bash
+./target/debug/marqdo run examples/anlian-mq/offline-smoke.mq.md
+```
+
+默认账号:`admin` / `anlian`(种子用户表)。
+
+## 发现缺陷时
+
+若某段 `.mq.md` 必须堆 `json` 才能完成,优先改 **`ext/web` / 插件 ABI`**,而不是在应用层打补丁。在本目录 `NOTES.md`(如有)或 PR 描述里记下可读性缺口。
diff --git a/examples/anlian-mq/components/foot.mq.md b/examples/anlian-mq/components/foot.mq.md
new file mode 100644
index 0000000..5fce967
--- /dev/null
+++ b/examples/anlian-mq/components/foot.mq.md
@@ -0,0 +1,10 @@
+## 页脚
+
+`页脚` =
+
+| 属性 | 值 |
+|------|-----|
+| 暗恋见君 · Marqdo 验收切片 | / |
+| sitemap | /sitemap.xml |
+
+**`页脚`**
diff --git a/examples/anlian-mq/components/nav.mq.md b/examples/anlian-mq/components/nav.mq.md
new file mode 100644
index 0000000..ab5f037
--- /dev/null
+++ b/examples/anlian-mq/components/nav.mq.md
@@ -0,0 +1,18 @@
+## 导航
+
+顶栏:首页、帖子、新闻、搜索、聊天、发帖(登录后)、后台。
+
+`导航` =
+
+| 属性 | 值 | 样式 | 媒体 | 当 |
+|------|-----|------|------|-----|
+| 暗恋见君 | / | | | |
+| 帖子 | /posts | | | |
+| 新闻 | /news | | | |
+| 搜索 | /search | | | |
+| 聊天 | /chat | | | |
+| 发帖 | /write | | | auth |
+| 登录 | /admin/login | | | guest |
+| 后台 | /admin | | | auth |
+
+**`导航`**
diff --git a/examples/anlian-mq/db/index.mq.md b/examples/anlian-mq/db/index.mq.md
new file mode 100644
index 0000000..b105eab
--- /dev/null
+++ b/examples/anlian-mq/db/index.mq.md
@@ -0,0 +1,37 @@
+---
+title: db/index
+description: 打开库、建表、幂等种子、全文索引。
+导入 网页:ext/web/网页.mq.md
+import schema:schema.mq.md
+import seed:seed.mq.md
+---
+
+## 打开
+
+*store = > 网页.数据库 地址="sqlite:data/anlian-mq.db"*
+*帖子字段 = > schema.posts*
+*新闻字段 = > schema.news*
+*密钥字段 = > schema.api_keys*
+> `store`.初始化 名=posts 字段=`帖子字段`
+> `store`.初始化 名=news 字段=`新闻字段`
+> `store`.初始化 名=api_keys 字段=`密钥字段`
+
+`全文列` =
+
+| 列 |
+|----|
+| title |
+| summary |
+| body |
+
+> `store`.全文 表=posts 列=`全文列` 名=posts_fts
+
+*已有 = > store.查询 表="posts" 上限=1*
+1. `已有`
+ **store**
+2. *
+ *帖子 = > seed.posts*
+ *新闻 = > seed.news*
+ > `store`.插入 表=posts 行=`帖子`
+ > `store`.插入 表=news 行=`新闻`
+ **store**
diff --git a/examples/anlian-mq/db/schema.mq.md b/examples/anlian-mq/db/schema.mq.md
new file mode 100644
index 0000000..fd8e50d
--- /dev/null
+++ b/examples/anlian-mq/db/schema.mq.md
@@ -0,0 +1,52 @@
+## posts
+
+帖子主表。`slug` 用于 `/post/{slug}`;`board` 为板块名(简化外键为文本,便于 SQLite 演示)。
+
+`posts` =
+
+| 字段 | 类型 | 可空 | 索引 |
+|------|------|------|------|
+| id | integer | false | |
+| title | text | false | |
+| slug | text | false | 是 |
+| summary | text | true | |
+| body | text | true | |
+| board | text | true | |
+| author | text | true | |
+| created_at | timestamp | true | |
+| updated_at | timestamp | true | |
+
+**`posts`**
+
+## news
+
+新闻主表(与帖子对称,验收「news 模块可写」)。
+
+`news` =
+
+| 字段 | 类型 | 可空 | 索引 |
+|------|------|------|------|
+| id | integer | false | |
+| title | text | false | |
+| slug | text | false | 是 |
+| summary | text | true | |
+| body | text | true | |
+| created_at | timestamp | true | |
+| updated_at | timestamp | true | |
+
+**`news`**
+
+## api_keys
+
+API Key 校验用哈希表(应用层 scopes;校验原语见 `web_api_key_check`)。
+
+`api_keys` =
+
+| 字段 | 类型 | 可空 |
+|------|------|------|
+| id | integer | false |
+| name | text | false |
+| hash | text | false |
+| scopes | text | true |
+
+**`api_keys`**
diff --git a/examples/anlian-mq/db/seed.mq.md b/examples/anlian-mq/db/seed.mq.md
new file mode 100644
index 0000000..52bb38d
--- /dev/null
+++ b/examples/anlian-mq/db/seed.mq.md
@@ -0,0 +1,24 @@
+## posts
+
+种子帖子(`@` 行记录表)。
+
+`posts` =
+
+| @ | title | slug | summary | body | board | author |
+|---|-------|------|---------|------|-------|--------|
+| 1 | 欢迎来到暗恋见君 | welcome | 期待人们能够继续相信爱情。 | 这是用 Marqdo 重写的验收站点。页面、库表与门禁都用 GFM 表格装配——代码即文档。 | 日常 | 站务 |
+| 2 | 如何用表格写论坛 | tables-for-forums | 导航、表单、种子数据都是可读表格。 | 若某功能逼你写一长串 json.set,请先审视 ext/web 是否缺命名方法。 | 开发 | 站务 |
+| 3 | 公聊室已开放 | chat-open | WebSocket 广播房间。 | 打开 /chat,连上 /chat/ws,消息会扇出给同房间所有人。 | 聊天 | 站务 |
+
+**`posts`**
+
+## news
+
+`news` =
+
+| @ | title | slug | summary | body |
+|---|-------|------|---------|------|
+| 1 | 站点迁往 Marqdo | migrate-to-marqdo | 原生层换 Go libweb,作者面保持表格。 | 暗恋见君的验收目标:登录、发帖、列表详情、聊天与站长工具都能用 .mq.md 写完。 |
+| 2 | 外接 PostgreSQL / Redis | pg-redis | 生产可用外接驱动。 | 本示例默认 sqlite:;把数据库地址换成 postgres:// 即可。 |
+
+**`news`**
diff --git a/examples/anlian-mq/index.mq.md b/examples/anlian-mq/index.mq.md
new file mode 100644
index 0000000..0c1b8a9
--- /dev/null
+++ b/examples/anlian-mq/index.mq.md
@@ -0,0 +1,181 @@
+---
+title: 暗恋见君 · Marqdo
+description: 用表格装配的论坛验收站点:帖子、新闻、发帖门禁、公聊、站长工具。
+导入 网页:ext/web/网页.mq.md
+import shell:styles/shell.mq.md
+import nav:components/nav.mq.md
+import foot:components/foot.mq.md
+import db:db/index.mq.md
+---
+
+# main
+
+站点壳:导航 + 页脚。
+
+`壳` =
+
+| 组件 | 样式 |
+|------|------|
+| nav.`导航` | |
+| foot.`页脚` | |
+
+帖子列表卡片绑定(字段名对应库表列;`href` 走 slug)。
+
+`帖子卡片` =
+
+| 属性 | 值 | 样式 |
+|------|-----|------|
+| title | posts.title | |
+| body | posts.summary | |
+| meta | posts.board | |
+| href | posts.slug | |
+
+`帖子详情` =
+
+| 属性 | 值 | 样式 |
+|------|-----|------|
+| title | posts.title | |
+| meta | posts.author | |
+| body | posts.body | |
+
+`新闻卡片` =
+
+| 属性 | 值 | 样式 |
+|------|-----|------|
+| title | news.title | |
+| body | news.summary | |
+| href | news.slug | |
+
+`新闻详情` =
+
+| 属性 | 值 | 样式 |
+|------|-----|------|
+| title | news.title | |
+| body | news.body | |
+
+动态路由条件:`{slug}` 由路径注入。
+
+`帖子条件` =
+
+| 字段 | 操作 | 值 |
+|------|------|-----|
+| slug | = | {slug} |
+
+`新闻条件` =
+
+| 字段 | 操作 | 值 |
+|------|------|-----|
+| slug | = | {slug} |
+
+发帖表单(字段 / 规则均为表)。
+
+`发帖字段` =
+
+| 字段 | 标签 | 类型 | 必填 |
+|------|------|------|------|
+| title | 标题 | text | true |
+| slug | 短链 | text | true |
+| summary | 摘要 | text | false |
+| body | 正文 | textarea | true |
+| board | 板块 | text | false |
+| author | 署名 | text | false |
+
+`发帖规则` =
+
+| 字段 | 规则 | 消息 |
+|------|------|------|
+| title | required | 标题不能为空 |
+| title | max:200 | 标题太长 |
+| slug | required | 需要短链 |
+| body | required | 正文不能为空 |
+| body | max:20000 | 正文太长 |
+
+站务账号(明文仅用于本地验收;生产请用 `网页.密码哈希`)。
+
+`用户表` =
+
+| 行 | 用户名 | 密码 | 角色 |
+|----|--------|------|------|
+| 1 | admin | anlian | admin |
+
+站点地图条目。
+
+`地图项` =
+
+| loc | 更新 |
+|-----|------|
+| / | 2026-09-10 |
+| /posts | 2026-09-10 |
+| /news | 2026-09-10 |
+| /chat | 2026-09-10 |
+| /search | 2026-09-10 |
+
+*store = > db.打开*
+*壳CSS = > shell.全局*
+
+*首页 = > 网页.页面 标题="暗恋见君" 引言="
暗恋见君
期待人们能够继续相信爱情。——本站用 Marqdo 表格装配,验收 web 拓展库。
"*
+*首页 = > 首页.组件装配 组件=`壳`*
+*首页 = > 首页.主体装配 主体=`帖子卡片`*
+*首页 = > 首页.排序 排序="-created_at"*
+*首页 = > 首页.样式 样式=`壳CSS`*
+
+*帖子列表 = > 网页.页面 标题="帖子" 引言="帖子
"*
+*帖子列表 = > 帖子列表.组件装配 组件=`壳`*
+*帖子列表 = > 帖子列表.主体装配 主体=`帖子卡片`*
+*帖子列表 = > 帖子列表.链接前缀 前缀="/post/"*
+*帖子列表 = > 帖子列表.排序 排序="-created_at"*
+*帖子列表 = > 帖子列表.样式 样式=`壳CSS`*
+
+*帖子页 = > 网页.页面 标题="帖子详情"*
+*帖子页 = > 帖子页.组件装配 组件=`壳`*
+*帖子页 = > 帖子页.主体装配 主体=`帖子详情`*
+*帖子页 = > 帖子页.查询条件 条件=`帖子条件`*
+*帖子页 = > 帖子页.详情 详情=True*
+*帖子页 = > 帖子页.样式 样式=`壳CSS`*
+
+*新闻列表 = > 网页.页面 标题="新闻" 引言="新闻
"*
+*新闻列表 = > 新闻列表.组件装配 组件=`壳`*
+*新闻列表 = > 新闻列表.主体装配 主体=`新闻卡片`*
+*新闻列表 = > 新闻列表.链接前缀 前缀="/news/"*
+*新闻列表 = > 新闻列表.排序 排序="-created_at"*
+*新闻列表 = > 新闻列表.样式 样式=`壳CSS`*
+
+*新闻页 = > 网页.页面 标题="新闻详情"*
+*新闻页 = > 新闻页.组件装配 组件=`壳`*
+*新闻页 = > 新闻页.主体装配 主体=`新闻详情`*
+*新闻页 = > 新闻页.查询条件 条件=`新闻条件`*
+*新闻页 = > 新闻页.详情 详情=True*
+*新闻页 = > 新闻页.样式 样式=`壳CSS`*
+
+*发帖表 = > 网页.表单 表="posts" 动作="插入"*
+*发帖表 = > 发帖表.字段 字段=`发帖字段`*
+*发帖表 = > 发帖表.规则 规则=`发帖规则`*
+
+*发帖页 = > 网页.页面 标题="发帖" 引言="发帖
需登录(admin / anlian)。
"*
+*发帖页 = > 发帖页.组件装配 组件=`壳`*
+*发帖页 = > 发帖页.表单装配 id="post" 表单=`发帖表`*
+*发帖页 = > 发帖页.样式 样式=`壳CSS`*
+
+*搜索页 = > 网页.页面 标题="搜索" 引言="搜索
在地址栏加 ?q=关键词,或从后台全文工具验证 FTS。验收切片先提供入口页。
"*
+*搜索页 = > 搜索页.组件装配 组件=`壳`*
+*搜索页 = > 搜索页.样式 样式=`壳CSS`*
+
+*聊天页 = > 网页.页面 标题="公聊" 引言="公聊室
"*
+*聊天页 = > 聊天页.组件装配 组件=`壳`*
+*聊天页 = > 聊天页.样式 样式=`壳CSS`*
+
+*应用 = > 网页.应用 页面=`首页` 数据库=`store` 后台=True 主机="127.0.0.1" 端口=18180*
+*应用 = > 应用.路由 路径="/posts" 页面=`帖子列表`*
+*应用 = > 应用.路由 路径="/post/{slug}" 页面=`帖子页`*
+*应用 = > 应用.路由 路径="/news" 页面=`新闻列表`*
+*应用 = > 应用.路由 路径="/news/{slug}" 页面=`新闻页`*
+*应用 = > 应用.路由 路径="/write" 页面=`发帖页`*
+*应用 = > 应用.路由 路径="/search" 页面=`搜索页`*
+*应用 = > 应用.路由 路径="/chat" 页面=`聊天页`*
+*应用 = > 应用.静态 目录="public" 挂载="/static"*
+*应用 = > 应用.鉴权 用户表=`用户表` 会话时长=7200 登录回跳="/write" 登出回跳="/"*
+*应用 = > 应用.门禁 路径="/write" 角色="admin" 匹配="prefix" 拒绝="redirect" 排除="/admin/login"*
+*应用 = > 应用.路由实时 路径="/chat/ws" 模式="broadcast"*
+*应用 = > 应用.站点地图 路径="/sitemap.xml" 基址="http://127.0.0.1:18180" 条目=`地图项`*
+*应用 = > 应用.爬虫协议 站点地图="http://127.0.0.1:18180/sitemap.xml"*
+> `应用`.监听
diff --git a/examples/anlian-mq/offline-smoke.mq.md b/examples/anlian-mq/offline-smoke.mq.md
new file mode 100644
index 0000000..8a920b4
--- /dev/null
+++ b/examples/anlian-mq/offline-smoke.mq.md
@@ -0,0 +1,72 @@
+---
+title: anlian-mq offline smoke
+description: 不 listen:装配库表/页面/门禁/WS 路由袋,验证可读路径可构造。
+导入 网页:ext/web/网页.mq.md
+import shell:styles/shell.mq.md
+import nav:components/nav.mq.md
+import foot:components/foot.mq.md
+import db:db/index.mq.md
+import sys:lib/sys.mq.md
+---
+
+# main
+
+`壳` =
+
+| 组件 | 样式 |
+|------|------|
+| nav.`导航` | |
+| foot.`页脚` | |
+
+`帖子卡片` =
+
+| 属性 | 值 |
+|------|-----|
+| title | posts.title |
+| body | posts.summary |
+| href | posts.slug |
+
+`用户表` =
+
+| 行 | 用户名 | 密码 | 角色 |
+|----|--------|------|------|
+| 1 | admin | anlian | admin |
+
+*store = > db.打开*
+*壳CSS = > shell.全局*
+*首页 = > 网页.页面 标题="暗恋见君" 引言="ok
"*
+*首页 = > 首页.组件装配 组件=`壳`*
+*首页 = > 首页.主体装配 主体=`帖子卡片`*
+*首页 = > 首页.样式 样式=`壳CSS`*
+
+*应用 = > 网页.应用 页面=`首页` 数据库=`store` 后台=True 主机="127.0.0.1" 端口=18180*
+*应用 = > 应用.鉴权 用户表=`用户表`*
+*应用 = > 应用.门禁 路径="/write" 角色="admin" 匹配="prefix" 拒绝="redirect"*
+*应用 = > 应用.路由实时 路径="/chat/ws" 模式="broadcast"*
+
+*gates = 应用[^gates]*
+*n = > len value=`gates`*
+1. `n` >= 2
+ > print text=gates-ok
+2. *
+ > print text=gates-fail
+ > sys.exit code=1
+
+*ws = 应用[^ws_routes]*
+*room = ws[^/chat/ws]*
+*mode = room[^mode]*
+1. `mode` == "broadcast"
+ > print text=ws-ok
+2. *
+ > print text=ws-fail
+ > sys.exit code=1
+
+*list = > store.查询 表="posts" 上限=10*
+*nr = > len value=`list`*
+1. `nr` >= 1
+ > print text=seed-ok
+2. *
+ > print text=seed-fail
+ > sys.exit code=1
+
+> print text=anlian-offline-ok
diff --git a/examples/anlian-mq/public/chat.js b/examples/anlian-mq/public/chat.js
new file mode 100644
index 0000000..2386f47
--- /dev/null
+++ b/examples/anlian-mq/public/chat.js
@@ -0,0 +1,37 @@
+/* 公聊客户端:保持极薄;业务配置仍在 .mq.md 表格里。 */
+(function () {
+ var log = document.getElementById("chat-log");
+ var input = document.getElementById("chat-msg");
+ var send = document.getElementById("chat-send");
+ if (!log || !input || !send) return;
+
+ var proto = location.protocol === "https:" ? "wss:" : "ws:";
+ var ws = new WebSocket(proto + "//" + location.host + "/chat/ws");
+
+ function line(text) {
+ log.textContent += text + "\n";
+ log.scrollTop = log.scrollHeight;
+ }
+
+ ws.onopen = function () {
+ line("[已连接公聊室]");
+ };
+ ws.onclose = function () {
+ line("[连接关闭]");
+ };
+ ws.onmessage = function (ev) {
+ line(String(ev.data));
+ };
+
+ function publish() {
+ var t = (input.value || "").trim();
+ if (!t || ws.readyState !== 1) return;
+ ws.send(t);
+ input.value = "";
+ }
+
+ send.addEventListener("click", publish);
+ input.addEventListener("keydown", function (e) {
+ if (e.key === "Enter") publish();
+ });
+})();
diff --git a/examples/anlian-mq/smoke.sh b/examples/anlian-mq/smoke.sh
new file mode 100755
index 0000000..9997dff
--- /dev/null
+++ b/examples/anlian-mq/smoke.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+# 暗恋见君 Marqdo 切片冒烟(需先启动 index.mq.md)。
+# 用法:bash examples/anlian-mq/smoke.sh
+set -uo pipefail
+BASE="http://127.0.0.1:18180"
+PASS=0; FAIL=0
+ok() { echo " ok: $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL: $1"; FAIL=$((FAIL+1)); }
+
+echo "== 首页 / 列表 =="
+code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/")
+[ "$code" = "200" ] && ok "GET /" || bad "GET / -> $code"
+curl -s "$BASE/" | grep -q '暗恋见君' && ok "品牌标题" || bad "品牌标题"
+curl -s "$BASE/posts" | grep -q 'welcome\|欢迎' && ok "帖子列表" || bad "帖子列表"
+code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/post/welcome")
+[ "$code" = "200" ] && ok "帖子详情" || bad "帖子详情 -> $code"
+curl -s "$BASE/news" | grep -q 'migrate\|迁往\|Marqdo' && ok "新闻列表" || bad "新闻列表"
+
+echo "== 站长 =="
+code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/sitemap.xml")
+[ "$code" = "200" ] && ok "sitemap" || bad "sitemap -> $code"
+code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/robots.txt")
+[ "$code" = "200" ] && ok "robots" || bad "robots -> $code"
+
+echo "== 门禁 =="
+code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/write")
+[ "$code" = "303" ] || [ "$code" = "302" ] && ok "未登录 /write 重定向" || bad "/write -> $code"
+
+echo "== 登录 =="
+rm -f /tmp/anlian_mq_hdr.txt
+curl -s -D /tmp/anlian_mq_hdr.txt -o /dev/null -d "username=admin&password=anlian" "$BASE/admin/login"
+sid=$(grep -i "set-cookie" /tmp/anlian_mq_hdr.txt | sed 's/.*marqdo_sid=\([^;]*\).*/\1/' | head -1)
+[ -n "$sid" ] && ok "会话 cookie" || bad "无 cookie"
+code=$(curl -s -b "marqdo_sid=$sid" -o /dev/null -w "%{http_code}" "$BASE/write")
+[ "$code" = "200" ] && ok "登录后 /write" || bad "登录后 /write -> $code"
+
+echo "== 聊天 WS =="
+wsok=$(python3 -c "
+import socket, base64, os
+s = socket.create_connection(('127.0.0.1', 18180), timeout=3)
+key = base64.b64encode(os.urandom(16)).decode()
+s.sendall((f'GET /chat/ws HTTP/1.1\r\nHost: x\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
+r = s.recv(1024).decode(errors='replace')
+print('OK' if '101' in r.split('\r\n')[0] else 'NO')
+s.close()
+" 2>/dev/null)
+[ "$wsok" = "OK" ] && ok "WebSocket 握手" || bad "WebSocket $wsok"
+
+echo
+echo "通过 $PASS / $((PASS+FAIL))"
+[ "$FAIL" = "0" ] || exit 1
diff --git a/examples/anlian-mq/styles/shell.mq.md b/examples/anlian-mq/styles/shell.mq.md
new file mode 100644
index 0000000..39e48c7
--- /dev/null
+++ b/examples/anlian-mq/styles/shell.mq.md
@@ -0,0 +1,51 @@
+---
+title: styles/shell
+description: 暗恋见君壳样式——配色与布局用表格声明。
+导入 网页:ext/web/网页.mq.md
+---
+
+## 基础
+
+暖纸感背景、深红强调(品牌向「相信爱情」),避免默认紫渐变模板。
+
+`基础` =
+
+| 选择器 | 属性 | 值 |
+|--------|------|-----|
+| :root | --ink | #2a1f1a |
+| :root | --muted | #7a6560 |
+| :root | --paper | #faf6f2 |
+| :root | --card | #ffffff |
+| :root | --line | #eadfd8 |
+| :root | --accent | #9b2c2c |
+| :root | --accent-ink | #fffaf7 |
+| :root | --radius | 12px |
+| :root | --serif | "Noto Serif SC", "Songti SC", Georgia, serif |
+| :root | --sans | "Noto Sans SC", "IBM Plex Sans", system-ui, sans-serif |
+| * | box-sizing | border-box |
+| body | margin | "0" |
+| body | font-family | var(--sans) |
+| body | background | var(--paper) |
+| body | color | var(--ink) |
+| h1 | font-family | var(--serif) |
+| h1 | font-weight | "600" |
+| a | color | var(--accent) |
+| .main-intro | max-width | "52rem" |
+| .main-intro | margin | "1.5rem auto" |
+| .main-intro | padding | "0 1.25rem" |
+| .chat-box | border | 1px solid var(--line) |
+| .chat-box | border-radius | var(--radius) |
+| .chat-box | background | var(--card) |
+| .chat-box | padding | "1rem" |
+| .chat-log | min-height | "12rem" |
+| .chat-log | font-family | ui-monospace, monospace |
+| .chat-log | font-size | "0.9rem" |
+| .chat-log | white-space | pre-wrap |
+
+**`基础`**
+
+## 全局
+
+*基础表 = > 基础*
+*css = > 网页.样式装配 名="anlian" 表=`基础表`*
+**css**
diff --git a/plugins/web/abi_page.go b/plugins/web/abi_page.go
new file mode 100644
index 0000000..048eb08
--- /dev/null
+++ b/plugins/web/abi_page.go
@@ -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)
+}
diff --git a/plugins/web/internal/httpx/auth.go b/plugins/web/internal/httpx/auth.go
new file mode 100644
index 0000000..d05d6e1
--- /dev/null
+++ b/plugins/web/internal/httpx/auth.go
@@ -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(
+ "403 Forbidden
Role `%s` cannot access `%s`.
",
+ 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, "Invalid or missing CSRF token. Refresh and try again.
")
+ 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, "Admin
Site administration.
")
+}
+
+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("%s
", esc(*errMsg))
+ }
+ csrfField := ""
+ if csrf != "" {
+ csrfField = fmt.Sprintf("", esc(csrf))
+ }
+ nextField := ""
+ if next != "" && strings.HasPrefix(next, "/") && !strings.HasPrefix(next, "//") {
+ nextField = fmt.Sprintf("", esc(next))
+ }
+ return fmt.Sprintf(`
+
+
+
+Admin Login
+
+
+
+
+
Admin
+
Sign in to manage this site.
+%s
+
+
+`, 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
+}
diff --git a/plugins/web/internal/httpx/auth_test.go b/plugins/web/internal/httpx/auth_test.go
new file mode 100644
index 0000000..f11f145
--- /dev/null
+++ b/plugins/web/internal/httpx/auth_test.go
@@ -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"])
+ }
+}
diff --git a/plugins/web/internal/httpx/helpers.go b/plugins/web/internal/httpx/helpers.go
index cbe0df3..d08f536 100644
--- a/plugins/web/internal/httpx/helpers.go
+++ b/plugins/web/internal/httpx/helpers.go
@@ -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
}
diff --git a/plugins/web/internal/httpx/listen.go b/plugins/web/internal/httpx/listen.go
index 3e87abd..4435c4a 100644
--- a/plugins/web/internal/httpx/listen.go
+++ b/plugins/web/internal/httpx/listen.go
@@ -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"))
}
}
diff --git a/plugins/web/internal/page/page.go b/plugins/web/internal/page/page.go
index 7c2015a..f996b17 100644
--- a/plugins/web/internal/page/page.go
+++ b/plugins/web/internal/page/page.go
@@ -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
+}
diff --git a/plugins/web/internal/render/anlian_resolve_test.go b/plugins/web/internal/render/anlian_resolve_test.go
new file mode 100644
index 0000000..3bed92b
--- /dev/null
+++ b/plugins/web/internal/render/anlian_resolve_test.go
@@ -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": "帖子
"}, 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)
+ }
+}
diff --git a/plugins/web/internal/session/session.go b/plugins/web/internal/session/session.go
index 79510a1..4fb529b 100644
--- a/plugins/web/internal/session/session.go
+++ b/plugins/web/internal/session/session.go
@@ -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 {
diff --git a/plugins/web/internal/session/session_test.go b/plugins/web/internal/session/session_test.go
index 34f6bff..85de928 100644
--- a/plugins/web/internal/session/session_test.go
+++ b/plugins/web/internal/session/session_test.go
@@ -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) {
diff --git a/plugins/web/plugin.go b/plugins/web/plugin.go
index 2d70872..48538aa 100644
--- a/plugins/web/plugin.go
+++ b/plugins/web/plugin.go
@@ -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;