Compare commits
3
Commits
ext-v1.0.4
...
ext-v1.0.5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb30cd3db3 | ||
|
|
584cb9ac9d | ||
|
|
428ee141e1 |
No files matched your search
@@ -8,6 +8,26 @@
|
||||
|
||||
### Changed
|
||||
|
||||
## Ext pack v1.0.5 — 2026-09-18
|
||||
|
||||
### Highlights
|
||||
|
||||
**ext/web 请求上下文与表单来源(CLI 仍为 v1.0.3)**:字段 `来源`/`source`(session / route / now)、server-only 盖戳、页面 `列表装配`/`compose_list`;禁止按业务表特判。安装:
|
||||
|
||||
```bash
|
||||
marqdo ext add web # CDN latest → 1.0.5
|
||||
```
|
||||
|
||||
### Added
|
||||
- **Request context**:表单提交携带 `_mq_params` / `_mq_return`;`ApplySources` 从 session/route/now 写入。
|
||||
- **字段来源列**:`client`(默认)/ `session.username` / `route.NAME` / `now`;非 client 不渲染且覆盖客户端伪造。
|
||||
- **列表装配**:`compose_list` / `列表装配`(副绑定 + 条件/排序/插槽),详情页可同页渲染子列表。
|
||||
- 设计文:[ext-web-request-context.md](doc/design/ext-web-request-context.md);金样 `ext_web_form_source_live`。
|
||||
|
||||
### Changed
|
||||
- 扩展包 SemVer **1.0.5**(`ext/VERSION`);与 CLI **v1.0.3** 可独立安装。
|
||||
- 移除评论表名特判(`enrichCommentSubmit`)。
|
||||
|
||||
## Ext pack v1.0.4 — 2026-09-17
|
||||
|
||||
### Highlights
|
||||
|
||||
Vendored
+7
@@ -1,3 +1,10 @@
|
||||
marqdo (1.0.3-1ppa2) noble; urgency=medium
|
||||
|
||||
* Fix Launchpad build: dh_clean -Xvendor/ so cargo vendor checksums keep
|
||||
Cargo.toml.orig (debian-only; reuse published 1.0.3.orig.tar.xz).
|
||||
|
||||
-- cflmy <pingan@cflmy.cn> Thu, 17 Sep 2026 21:28:00 +0800
|
||||
|
||||
marqdo (1.0.3-1ppa1) noble; urgency=medium
|
||||
|
||||
* Marqdo 1.0.3: PPA + ext CDN; unbound GFM tables; bundled Rust for noble.
|
||||
|
||||
Vendored
+5
@@ -46,6 +46,11 @@ override_dh_auto_install:
|
||||
install -m 0755 $(CURDIR)/target/release/marqdo \
|
||||
$(CURDIR)/debian/marqdo/usr/bin/marqdo
|
||||
|
||||
# dh_clean deletes *.orig by default; cargo vendor checksums require
|
||||
# vendor/**/Cargo.toml.orig. Exclude the vendored tree from that purge.
|
||||
override_dh_clean:
|
||||
dh_clean -Xvendor/
|
||||
|
||||
override_dh_auto_clean:
|
||||
dh_auto_clean
|
||||
rm -rf debian/cargo_home
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# ext/web:请求上下文与表单字段来源
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Accepted** |
|
||||
| 日期 | 2026-09-18 |
|
||||
| 相关 | [ext-web.md](ext-web.md) §5.5 · 对照 Django `request.user` / URL kwargs |
|
||||
| 动机 | 禁止扩展库按业务表名(如 `comments`)特判填字段;身份与路由键属于请求上下文 |
|
||||
|
||||
---
|
||||
|
||||
## 0. 原则
|
||||
|
||||
1. **扩展库提供机制,站点表达领域** — 不得出现 `if table == "comments"`。
|
||||
2. **身份只从 session 来,且服务端盖戳** — 客户端提交的 `author` 等不可信。
|
||||
3. **资源键从路由参数来** — 页面已在 `/post/{slug}` 时,表单继承该页 `params`,不解析 Referer 猜 slug。
|
||||
4. **非 `client` 来源的字段默认不渲染** — 服务端在校验前写入;若 POST 带同名键,一律覆盖丢弃。
|
||||
|
||||
---
|
||||
|
||||
## 1. 请求上下文(Request)
|
||||
|
||||
每次处理 HTTP 请求时,框架逻辑上持有:
|
||||
|
||||
| 键 | 含义 |
|
||||
|----|------|
|
||||
| `user` / `username` | 登录名;访客为空 |
|
||||
| `params` | 动态路由捕获(如 `{slug}`) |
|
||||
| `path` | 请求路径 |
|
||||
| `method` | GET / POST / … |
|
||||
| `query` | URL 查询(可选) |
|
||||
|
||||
与 Django 对应:`request.user`、`request.resolver_match.kwargs`、`request.path`。
|
||||
|
||||
页面渲染时已有 `page.params`(`injectParams`)。表单提交时通过隐藏字段 `_mq_params`(JSON)与 `_mq_return`(回跳路径)把**渲染该表单时的页上下文**带回 POST,避免依赖 Referer。
|
||||
|
||||
---
|
||||
|
||||
## 2. 字段表「来源」列
|
||||
|
||||
字段表增加可选列 `来源` / `source`(缺省 = `client`):
|
||||
|
||||
```markdown
|
||||
| 字段 | 标签 | 类型 | 必填 | 默认 | 来源 |
|
||||
|------|------|------|------|------|------|
|
||||
| body | 写下你的想法 | textarea | true | | client |
|
||||
| author | | | true | | session.username |
|
||||
| post_slug | | | true | | route.slug |
|
||||
| created_at | | | false | | now |
|
||||
```
|
||||
|
||||
| 来源值 | 含义 | 渲染 |
|
||||
|--------|------|------|
|
||||
| `client` / 空 | 用户填写 | 正常控件 |
|
||||
| `session.username` / `session.user` / `user` | 当前登录用户名 | 不渲染 |
|
||||
| `route.NAME` / `param.NAME` / `params.NAME` | `params[NAME]` | 不渲染 |
|
||||
| `now` / `utc.now` / `server.now` | UTC `YYYY-MM-DD HH:MM:SS` | 不渲染 |
|
||||
|
||||
`类型=hidden` 仍可显式使用;与 `来源≠client` 叠加时仍不依赖客户端值(服务端覆盖)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 提交管线
|
||||
|
||||
```
|
||||
ParseForm → 去掉来源≠client 的 POST 键
|
||||
→ 按字段来源从 Request 写入
|
||||
→ validate → insert/update
|
||||
→ 回跳:优先 _mq_return(同站路径),否则 form.redirect
|
||||
```
|
||||
|
||||
伪造 `author` / `post_slug` 无效。
|
||||
|
||||
---
|
||||
|
||||
## 4. 页面列表装配(副绑定)
|
||||
|
||||
详情页可附加与主主体**不同查询条件**的列表绑定(如评论):
|
||||
|
||||
```markdown
|
||||
**post = > post.列表装配 主体=`评论卡片` 条件=`评论条件` 排序="-created_at"**
|
||||
```
|
||||
|
||||
条件值同样支持 `{slug}`。渲染在主文章/卡片区之后,无需为子资源单独写 JSON API + 前端过滤。
|
||||
|
||||
---
|
||||
|
||||
## 5. 非目标
|
||||
|
||||
- 不在扩展库内实现「评论」领域类型。
|
||||
- 不把 Referer 解析当作正式 params 来源(仅兼容期可作 `_mq_params` 缺失时的弱回退,金样不依赖)。
|
||||
@@ -3,8 +3,8 @@
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Accepted · W0–W7 + P3 + W8(站点图标/Head/图片装配)完结**(SQLite/Postgres 作者面:页面装配 / db CRUD+`where` / form / 嵌入主区 / `app.route` / 路由 `/_part` / admin UI / RBAC / 上传相册 / SEO·RSS·sitemap / **favicon·头资源·图片装配**;Postgres 等见 §9) |
|
||||
| 日期 | 2026-08-11(W8:2026-08-29) |
|
||||
| 相关 | [markdown-mapping.md](markdown-mapping.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [stdlib-i18n.md](stdlib-i18n.md) · [web-assets-and-images.md](web-assets-and-images.md) |
|
||||
| 日期 | 2026-08-11(W8:2026-08-29;请求上下文:2026-09-18) |
|
||||
| 相关 | [markdown-mapping.md](markdown-mapping.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [stdlib-i18n.md](stdlib-i18n.md) · [web-assets-and-images.md](web-assets-and-images.md) · **[ext-web-request-context.md](ext-web-request-context.md)** |
|
||||
| 安装(目标) | `marqdo ext add web`(中英:`web` / `网页`) |
|
||||
| 本文目的 | 锁定**作者面**与**类 API**;指导实现 |
|
||||
|
||||
@@ -247,6 +247,7 @@ import db:db/index.mq.md
|
||||
|------|------|
|
||||
| compose_components / 组件装配 | 解析组件·样式路径 → 填 nav/sidebar/footer → CSS → 登记 part |
|
||||
| compose_main / 主体装配 | 解析库字段与样式路径 → 填 main → 登记 part(如 id=`index`) |
|
||||
| compose_list / 列表装配 | 副绑定(独立 query/order);可选 target 注入引言元素;见 [ext-web-request-context.md](ext-web-request-context.md) |
|
||||
|
||||
**槽位推断:** 由组件导出名决定(`nav`→顶栏,`side`→侧栏,`foot`→底栏;其余→main)。
|
||||
|
||||
@@ -423,6 +424,7 @@ import db:db/index.mq.md
|
||||
| `类型` | 控件/值类型:`text` `textarea` `number` `email` `url` `checkbox` `select` … |
|
||||
| `必填` | 是否必填 |
|
||||
| `默认` | 可选默认值 |
|
||||
| `来源` / `source` | 可选;见 [ext-web-request-context.md](ext-web-request-context.md):`client`(默认)/ `session.username` / `route.NAME` / `now`;非 client 不渲染且服务端盖戳 |
|
||||
|
||||
#### 5.5.2 校验表(作者面)
|
||||
|
||||
|
||||
@@ -74,6 +74,8 @@ Watch: https://launchpad.net/~cflmy/+archive/ubuntu/marqdo/+builds
|
||||
| Symptom | Fix |
|
||||
|---------|-----|
|
||||
| `lock file version 4 requires -Znext-lockfile-bump` | Rebuild with current `ppa-build-source.sh` (bundles Rust); bump `1ppaN` |
|
||||
| `failed to calculate checksum of: …/vendor/…/Cargo.toml.orig` | `dh_clean` purged `*.orig`; fixed via `dh_clean -Xvendor/` (+ strip `.orig` only when **creating a new** orig); bump `1ppaN` with **`-sd`** |
|
||||
| `orig.tar.xz already exists … different contents` | Never rewrite an uploaded upstream `.orig`; reuse PPA file (`ppa-build-source.sh` downloads it) and `debuild -S -sd` |
|
||||
| Same version rejected by Launchpad | Bump `debian/changelog` (`1ppa2`, …) |
|
||||
| Wrong series | Enable series on PPA; rebuild with that series name |
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
1.0.4
|
||||
1.0.5
|
||||
@@ -242,6 +242,17 @@ Assemble main from a bind table (`|属性|值|样式|` or `|front|back|css|`).
|
||||
|
||||
*> web_compose_main page=`self` main=`main`*
|
||||
|
||||
## compose_list
|
||||
+ `main`
|
||||
+ `query`=None
|
||||
+ `order`=""
|
||||
+ `target`=""
|
||||
|
||||
Secondary list bind (e.g. comments on a detail page). Same bind shape as compose_main.
|
||||
Optional query supports route param placeholders; optional target injects into an intro element id.
|
||||
|
||||
*> web_compose_list page=`self` main=`main` query=`query` order=`order` target=`target`*
|
||||
|
||||
## compose_intro
|
||||
+ `intro`
|
||||
|
||||
|
||||
@@ -227,6 +227,17 @@ import table:lib/table.mq.md
|
||||
|
||||
*> web_compose_main page=`self` main=`主体`*
|
||||
|
||||
## 列表装配
|
||||
+ `主体`
|
||||
+ `条件`=None
|
||||
+ `排序`=""
|
||||
+ `插槽`=""
|
||||
|
||||
详情页副绑定(如评论列表)。绑定表形同 `主体装配`;`条件` 支持 `{参数}`;
|
||||
可选 `插槽`(元素 id)把列表注入引言 HTML(同表单插槽)。
|
||||
|
||||
*> web_compose_list page=`self` main=`主体` query=`条件` order=`排序` target=`插槽`*
|
||||
|
||||
## 引言装配
|
||||
+ `引言`
|
||||
|
||||
|
||||
@@ -152,14 +152,10 @@ func ComposeComponents(page any, layout any, callLib CallLib) (any, error) {
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
// ComposeMain merges a main bind table into a page bag.
|
||||
func ComposeMain(page any, mainTable any, callLib CallLib) (any, error) {
|
||||
obj := asObject(page)
|
||||
func resolveBinds(mainTable any, callLib CallLib) (binds []any, css string, err error) {
|
||||
raw := table.AsBind(mainTable)
|
||||
arr, _ := raw.([]any)
|
||||
binds := make([]any, 0, len(arr))
|
||||
css := strField(obj, "styles_css")
|
||||
|
||||
binds = make([]any, 0, len(arr))
|
||||
for _, b := range arr {
|
||||
bm, ok := b.(map[string]any)
|
||||
if !ok {
|
||||
@@ -191,7 +187,7 @@ func ComposeMain(page any, mainTable any, callLib CallLib) (any, error) {
|
||||
case table.SitePathLibMember:
|
||||
st, err := callLib(sp.Lib + "." + sp.Member)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
css += table.AsCSSNamed(sp.Member, st)
|
||||
cssName = sp.Member
|
||||
@@ -207,6 +203,17 @@ func ComposeMain(page any, mainTable any, callLib CallLib) (any, error) {
|
||||
"css": cssName,
|
||||
})
|
||||
}
|
||||
return binds, css, nil
|
||||
}
|
||||
|
||||
// ComposeMain merges a main bind table into a page bag.
|
||||
func ComposeMain(page any, mainTable any, callLib CallLib) (any, error) {
|
||||
obj := asObject(page)
|
||||
binds, cssExtra, err := resolveBinds(mainTable, callLib)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
css := strField(obj, "styles_css") + cssExtra
|
||||
|
||||
if t, ok := table.BindTableName(binds); ok {
|
||||
obj["table"] = t
|
||||
@@ -234,6 +241,41 @@ func ComposeMain(page any, mainTable any, callLib CallLib) (any, error) {
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
// ComposeList appends a secondary bind (detail + child list), with optional
|
||||
// query/order/target (inject into intro element id, same as form_target).
|
||||
func ComposeList(page any, mainTable any, query any, order, target string, callLib CallLib) (any, error) {
|
||||
obj := asObject(page)
|
||||
binds, cssExtra, err := resolveBinds(mainTable, callLib)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cssExtra != "" {
|
||||
prev := strField(obj, "styles_css")
|
||||
if prev != "" {
|
||||
obj["styles_css"] = prev + cssExtra
|
||||
} else {
|
||||
obj["styles_css"] = cssExtra
|
||||
}
|
||||
}
|
||||
entry := map[string]any{"main": binds}
|
||||
if query != nil {
|
||||
entry["query"] = query
|
||||
}
|
||||
if strings.TrimSpace(order) != "" {
|
||||
entry["order"] = strings.TrimSpace(order)
|
||||
}
|
||||
if t := strings.TrimSpace(target); t != "" {
|
||||
entry["target"] = t
|
||||
}
|
||||
lists := []any{}
|
||||
if existing, ok := obj["lists"].([]any); ok {
|
||||
lists = append(lists, existing...)
|
||||
}
|
||||
lists = append(lists, entry)
|
||||
obj["lists"] = lists
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
// ComposeForm embeds a form into the page main slot.
|
||||
func ComposeForm(page any, form any, formID string, formTarget *string) (any, error) {
|
||||
id := strings.TrimSpace(formID)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package compose
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestComposeListAppends(t *testing.T) {
|
||||
page := map[string]any{"title": "p"}
|
||||
main := []any{
|
||||
map[string]any{"front": "title", "back": "comments.author", "css": ""},
|
||||
map[string]any{"front": "body", "back": "comments.body", "css": ""},
|
||||
}
|
||||
q := []any{map[string]any{"field": "post_slug", "op": "=", "value": "{slug}"}}
|
||||
out, err := ComposeList(page, main, q, "-created_at", "#comment-list", func(string) (any, error) {
|
||||
return nil, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := out.(map[string]any)
|
||||
lists, ok := m["lists"].([]any)
|
||||
if !ok || len(lists) != 1 {
|
||||
t.Fatalf("lists=%v", m["lists"])
|
||||
}
|
||||
entry := lists[0].(map[string]any)
|
||||
if entry["order"] != "-created_at" || entry["target"] != "#comment-list" {
|
||||
t.Fatalf("entry=%v", entry)
|
||||
}
|
||||
if entry["query"] == nil {
|
||||
t.Fatal("missing query")
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
package form
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -17,6 +18,7 @@ var (
|
||||
typeKeys = []string{"类型", "type"}
|
||||
reqKeys = []string{"必填", "required"}
|
||||
defKeys = []string{"默认", "default"}
|
||||
sourceKeys = []string{"来源", "source"}
|
||||
ruleFieldKeys = []string{"字段", "field", "name"}
|
||||
ruleKeys = []string{"规则", "rule"}
|
||||
msgKeys = []string{"消息", "message", "msg"}
|
||||
@@ -177,12 +179,19 @@ func asFormFields(fields any) []any {
|
||||
if v, ok := pick(m, defKeys); ok {
|
||||
def = cellStr(v)
|
||||
}
|
||||
source := "client"
|
||||
if v, ok := pick(m, sourceKeys); ok {
|
||||
if s := strings.TrimSpace(cellStr(v)); s != "" {
|
||||
source = s
|
||||
}
|
||||
}
|
||||
item := map[string]any{
|
||||
"name": name,
|
||||
"label": label,
|
||||
"type": ty,
|
||||
"required": required,
|
||||
"default": def,
|
||||
"source": normalizeSource(source),
|
||||
}
|
||||
if v, ok := m["pk"]; ok {
|
||||
item["pk"] = boolish(v)
|
||||
@@ -211,6 +220,10 @@ func asFormFields(fields any) []any {
|
||||
if v, ok := pick(t, defKeys); ok {
|
||||
defs = asStrList(v)
|
||||
}
|
||||
sources := []string{}
|
||||
if v, ok := pick(t, sourceKeys); ok {
|
||||
sources = asStrList(v)
|
||||
}
|
||||
var out []any
|
||||
for i, nameRaw := range names {
|
||||
name := table.NormalizeRef(nameRaw)
|
||||
@@ -233,12 +246,17 @@ func asFormFields(fields any) []any {
|
||||
if i < len(defs) {
|
||||
def = defs[i]
|
||||
}
|
||||
source := "client"
|
||||
if i < len(sources) && strings.TrimSpace(sources[i]) != "" {
|
||||
source = sources[i]
|
||||
}
|
||||
out = append(out, map[string]any{
|
||||
"name": name,
|
||||
"label": label,
|
||||
"type": ty,
|
||||
"required": required,
|
||||
"default": def,
|
||||
"source": normalizeSource(source),
|
||||
})
|
||||
}
|
||||
return out
|
||||
@@ -614,6 +632,11 @@ func strOf(m map[string]any, key, def string) string {
|
||||
|
||||
// RenderBody emits form markup only (no document shell).
|
||||
func RenderBody(formBag map[string]any, formID string, data, errors any, csrf string) string {
|
||||
return RenderBodyCtx(formBag, formID, data, errors, csrf, nil)
|
||||
}
|
||||
|
||||
// RenderBodyCtx is RenderBody plus request-context hidden fields for POST.
|
||||
func RenderBodyCtx(formBag map[string]any, formID string, data, errors any, csrf string, ctx *RequestContext) string {
|
||||
fields := fieldSlice(formBag)
|
||||
dataM := map[string]any{}
|
||||
if data != nil {
|
||||
@@ -680,6 +703,20 @@ func RenderBody(formBag map[string]any, formID string, data, errors any, csrf st
|
||||
if action == "update" && rowID != "" {
|
||||
fmt.Fprintf(&body, `<input type="hidden" name="id" value="%s"/>`, esc(rowID))
|
||||
}
|
||||
if ctx != nil {
|
||||
if len(ctx.Params) > 0 {
|
||||
if b, err := json.Marshal(ctx.Params); err == nil {
|
||||
fmt.Fprintf(&body, `<input type="hidden" name="_mq_params" value="%s"/>`, esc(string(b)))
|
||||
}
|
||||
}
|
||||
ret := strings.TrimSpace(ctx.ReturnPath)
|
||||
if ret == "" {
|
||||
ret = strings.TrimSpace(ctx.Path)
|
||||
}
|
||||
if ret != "" && strings.HasPrefix(ret, "/") && !strings.HasPrefix(ret, "//") {
|
||||
fmt.Fprintf(&body, `<input type="hidden" name="_mq_return" value="%s"/>`, esc(ret))
|
||||
}
|
||||
}
|
||||
for _, f := range fields {
|
||||
fm, ok := f.(map[string]any)
|
||||
if !ok {
|
||||
@@ -689,6 +726,9 @@ func RenderBody(formBag map[string]any, formID string, data, errors any, csrf st
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
if !IsClientSource(strOf(fm, "source", "client")) {
|
||||
continue
|
||||
}
|
||||
label := strOf(fm, "label", name)
|
||||
ty := strOf(fm, "type", "text")
|
||||
required, _ := fm["required"].(bool)
|
||||
@@ -712,6 +752,10 @@ func RenderBody(formBag map[string]any, formID string, data, errors any, csrf st
|
||||
if required {
|
||||
reqAttr = " required"
|
||||
}
|
||||
if ty == "hidden" {
|
||||
fmt.Fprintf(&body, `<input type="hidden" name="%s" value="%s"/>`, esc(name), esc(value))
|
||||
continue
|
||||
}
|
||||
body.WriteString("<label>")
|
||||
body.WriteString(esc(label))
|
||||
if ty == "textarea" {
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package form
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func normalizeSource(raw string) string {
|
||||
s := strings.TrimSpace(raw)
|
||||
if s == "" {
|
||||
return "client"
|
||||
}
|
||||
switch strings.ToLower(s) {
|
||||
case "client", "用户", "input", "form":
|
||||
return "client"
|
||||
case "user", "username", "session.user", "session.username", "用户名":
|
||||
return "session.username"
|
||||
case "now", "utc.now", "server.now", "时间", "utc":
|
||||
return "now"
|
||||
default:
|
||||
return s
|
||||
}
|
||||
}
|
||||
|
||||
// IsClientSource reports whether the field is filled by the browser.
|
||||
func IsClientSource(source string) bool {
|
||||
return normalizeSource(source) == "client"
|
||||
}
|
||||
|
||||
// RequestContext carries session user and route params for form source stamping
|
||||
// (design: ext-web-request-context.md). Domain-agnostic — no table-name branches.
|
||||
type RequestContext struct {
|
||||
Username string
|
||||
Params map[string]any
|
||||
ReturnPath string
|
||||
Path string
|
||||
Method string
|
||||
}
|
||||
|
||||
// ApplySources strips client-supplied values for non-client fields, then stamps
|
||||
// from ctx. Always overwrites server-owned keys.
|
||||
func ApplySources(formBag map[string]any, data map[string]any, ctx *RequestContext) {
|
||||
if data == nil {
|
||||
return
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = &RequestContext{}
|
||||
}
|
||||
for _, f := range fieldSlice(formBag) {
|
||||
fm, ok := f.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
name, _ := fm["name"].(string)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
src := normalizeSource(strOf(fm, "source", "client"))
|
||||
if src == "client" {
|
||||
continue
|
||||
}
|
||||
delete(data, name)
|
||||
if v, ok := resolveSource(src, ctx); ok {
|
||||
data[name] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func resolveSource(src string, ctx *RequestContext) (any, bool) {
|
||||
src = normalizeSource(src)
|
||||
switch src {
|
||||
case "client":
|
||||
return nil, false
|
||||
case "session.username":
|
||||
if ctx.Username == "" {
|
||||
return nil, false
|
||||
}
|
||||
return ctx.Username, true
|
||||
case "now":
|
||||
return time.Now().UTC().Format("2006-01-02 15:04:05"), true
|
||||
}
|
||||
lower := strings.ToLower(src)
|
||||
for _, prefix := range []string{"route.", "param.", "params."} {
|
||||
if strings.HasPrefix(lower, prefix) {
|
||||
key := src[len(prefix):]
|
||||
if key == "" || ctx.Params == nil {
|
||||
return nil, false
|
||||
}
|
||||
if v, ok := ctx.Params[key]; ok {
|
||||
return v, true
|
||||
}
|
||||
for k, v := range ctx.Params {
|
||||
if strings.EqualFold(k, key) {
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// ParseMQParams decodes the hidden `_mq_params` JSON posted with forms.
|
||||
func ParseMQParams(raw string) map[string]any {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return nil
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal([]byte(raw), &out); err != nil {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package form
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestApplySourcesOverwritesClient(t *testing.T) {
|
||||
frm := SetFields(New("comments", "insert", "c"), []any{
|
||||
map[string]any{"字段": "body", "标签": "body", "类型": "textarea", "必填": true, "来源": "client"},
|
||||
map[string]any{"字段": "author", "标签": "a", "类型": "text", "必填": true, "来源": "session.username"},
|
||||
map[string]any{"字段": "post_slug", "标签": "s", "类型": "text", "必填": true, "来源": "route.slug"},
|
||||
map[string]any{"字段": "created_at", "标签": "t", "类型": "text", "来源": "now"},
|
||||
})
|
||||
data := map[string]any{
|
||||
"body": "hi",
|
||||
"author": "forged",
|
||||
"post_slug": "evil",
|
||||
}
|
||||
ApplySources(frm, data, &RequestContext{
|
||||
Username: "alice",
|
||||
Params: map[string]any{"slug": "hello"},
|
||||
})
|
||||
if data["author"] != "alice" {
|
||||
t.Fatalf("author=%v", data["author"])
|
||||
}
|
||||
if data["post_slug"] != "hello" {
|
||||
t.Fatalf("slug=%v", data["post_slug"])
|
||||
}
|
||||
if data["body"] != "hi" {
|
||||
t.Fatalf("body=%v", data["body"])
|
||||
}
|
||||
if data["created_at"] == nil || data["created_at"] == "" {
|
||||
t.Fatalf("created_at missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderSkipsServerSources(t *testing.T) {
|
||||
frm := SetFields(New("comments", "insert", "c"), []any{
|
||||
map[string]any{"字段": "body", "标签": "Body", "类型": "textarea", "必填": true},
|
||||
map[string]any{"字段": "author", "标签": "Author", "类型": "text", "来源": "session.username"},
|
||||
})
|
||||
html := RenderBodyCtx(frm, "c", nil, nil, "", &RequestContext{
|
||||
Username: "alice",
|
||||
Params: map[string]any{"slug": "x"},
|
||||
ReturnPath: "/post/x",
|
||||
})
|
||||
if stringsContains(html, `name="author"`) {
|
||||
t.Fatalf("author field should not render: %s", html)
|
||||
}
|
||||
if !stringsContains(html, `name="body"`) {
|
||||
t.Fatalf("body missing")
|
||||
}
|
||||
if !stringsContains(html, `_mq_params`) || !stringsContains(html, `_mq_return`) {
|
||||
t.Fatalf("missing mq context fields: %s", html)
|
||||
}
|
||||
}
|
||||
|
||||
func stringsContains(s, sub string) bool {
|
||||
return len(s) >= len(sub) && (s == sub || len(sub) == 0 ||
|
||||
(func() bool {
|
||||
for i := 0; i+len(sub) <= len(s); i++ {
|
||||
if s[i:i+len(sub)] == sub {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})())
|
||||
}
|
||||
@@ -355,17 +355,30 @@ func withNavAuth(page map[string]any, cookieHeader string) {
|
||||
}
|
||||
}
|
||||
|
||||
func (st *state) hasPageRoute(path string) bool {
|
||||
if path == "" || st.routes == nil {
|
||||
return false
|
||||
}
|
||||
_, ok := st.routes[path]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (st *state) mountAuthRoutes(mux *http.ServeMux) {
|
||||
if st.auth.users == nil && !(st.auth.rbac && st.auth.register) {
|
||||
return
|
||||
}
|
||||
if st.auth.users != nil || st.auth.rbac {
|
||||
lp := st.auth.loginPath
|
||||
mux.HandleFunc("GET "+lp, st.handleLoginGet)
|
||||
// Site pages may own GET /login (or /desk/login); always keep POST for auth.
|
||||
if !st.hasPageRoute(lp) {
|
||||
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)
|
||||
if !st.hasPageRoute(altLogin) {
|
||||
mux.HandleFunc("GET "+altLogin, st.handleLoginGet)
|
||||
}
|
||||
mux.HandleFunc("POST "+altLogin, st.handleLoginPost)
|
||||
}
|
||||
logoutPath := strings.TrimRight(st.auth.adminPrefix, "/") + "/logout"
|
||||
@@ -373,7 +386,9 @@ func (st *state) mountAuthRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
if st.auth.register && st.auth.rbac {
|
||||
rp := st.auth.registerPath
|
||||
mux.HandleFunc("GET "+rp, st.handleRegisterGet)
|
||||
if !st.hasPageRoute(rp) {
|
||||
mux.HandleFunc("GET "+rp, st.handleRegisterGet)
|
||||
}
|
||||
mux.HandleFunc("POST "+rp, st.handleRegisterPost)
|
||||
}
|
||||
if st.auth.rbac && st.dbURL != "" {
|
||||
@@ -455,6 +470,10 @@ func (st *state) handleLoginPost(w http.ResponseWriter, r *http.Request) {
|
||||
role, _ := res["role"].(string)
|
||||
st.attachLoginPermissions(sessID, username, role)
|
||||
dest := loginDest(r, st.auth.loginRedirect)
|
||||
held := session.PermissionsFromSession(sessID)
|
||||
if strings.HasPrefix(dest, "/desk") && !session.PermissionAllowed(held, []string{"desk:access"}) {
|
||||
dest = "/"
|
||||
}
|
||||
w.Header().Add("Set-Cookie", session.IssueCookie(sessID))
|
||||
http.Redirect(w, r, dest, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
@@ -447,6 +448,11 @@ func (st *state) handleFormPost(w http.ResponseWriter, r *http.Request) {
|
||||
data = tenant.StampRow(data, st.tenant.Column, tid)
|
||||
}
|
||||
}
|
||||
ctx := st.requestContext(r, data)
|
||||
delete(data, "_mq_params")
|
||||
delete(data, "_mq_return")
|
||||
delete(data, "_csrf")
|
||||
form.ApplySources(frm, data, ctx)
|
||||
res, err := form.Submit(frm, data, st.dbURL)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
@@ -454,14 +460,68 @@ func (st *state) handleFormPost(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
if ok, _ := res["ok"].(bool); ok {
|
||||
redir := strOpt(res, "redirect", "/")
|
||||
if ctx.ReturnPath != "" {
|
||||
redir = ctx.ReturnPath
|
||||
}
|
||||
http.Redirect(w, r, redir, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
html := form.Render(frm, id, data, res["errors"], "")
|
||||
html := form.RenderBodyCtx(frm, id, data, res["errors"], "", ctx)
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, html)
|
||||
}
|
||||
|
||||
func (st *state) requestContext(r *http.Request, data map[string]any) *form.RequestContext {
|
||||
ctx := &form.RequestContext{
|
||||
Username: session.UsernameFromCookie(r.Header.Get("Cookie")),
|
||||
Path: r.URL.Path,
|
||||
Method: r.Method,
|
||||
}
|
||||
if data != nil {
|
||||
if p := form.ParseMQParams(fmt.Sprint(data["_mq_params"])); len(p) > 0 {
|
||||
ctx.Params = p
|
||||
}
|
||||
if ret, ok := data["_mq_return"].(string); ok {
|
||||
if back := sameHostPath(ret, r.Host); back != "" {
|
||||
ctx.ReturnPath = back
|
||||
} else if strings.HasPrefix(ret, "/") && !strings.HasPrefix(ret, "//") {
|
||||
ctx.ReturnPath = ret
|
||||
}
|
||||
}
|
||||
}
|
||||
if ctx.ReturnPath == "" {
|
||||
if back := sameHostPath(r.Referer(), r.Host); back != "" {
|
||||
ctx.ReturnPath = back
|
||||
}
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
func sameHostPath(raw, host string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u == nil {
|
||||
return ""
|
||||
}
|
||||
if u.Host != "" && host != "" && !strings.EqualFold(u.Host, host) {
|
||||
return ""
|
||||
}
|
||||
path := u.Path
|
||||
if path == "" {
|
||||
path = "/"
|
||||
}
|
||||
if u.RawQuery != "" {
|
||||
path += "?" + u.RawQuery
|
||||
}
|
||||
if !strings.HasPrefix(path, "/") || strings.HasPrefix(path, "//") {
|
||||
return ""
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func (st *state) handleJSON(w http.ResponseWriter, r *http.Request, route middleware.JSONRouteMount) {
|
||||
if st.dbURL == "" {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "no database"})
|
||||
|
||||
@@ -462,6 +462,120 @@ func resolveMain(page map[string]any, dbURL string) (intro string, items []map[s
|
||||
return intro, items, total
|
||||
}
|
||||
|
||||
// listBind is one secondary page list (compose_list / 列表装配).
|
||||
type listBind struct {
|
||||
Items []map[string]any
|
||||
Target string
|
||||
HTML string
|
||||
}
|
||||
|
||||
func resolveLists(page map[string]any, dbURL string) []listBind {
|
||||
raw, ok := page["lists"].([]any)
|
||||
if !ok || len(raw) == 0 || dbURL == "" {
|
||||
return nil
|
||||
}
|
||||
var out []listBind
|
||||
for _, entry := range raw {
|
||||
em, ok := entry.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
bindsAny := table.AsBind(em["main"])
|
||||
arr, _ := bindsAny.([]any)
|
||||
if len(arr) == 0 {
|
||||
continue
|
||||
}
|
||||
tn, ok := table.BindTableName(arr)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
sub := map[string]any{"params": pageParams(page)}
|
||||
if q, ok := em["query"]; ok {
|
||||
sub["query"] = q
|
||||
}
|
||||
if o, ok := em["order"].(string); ok {
|
||||
sub["order"] = o
|
||||
}
|
||||
data := selectPageData(dbURL, tn, sub, 200, 0)
|
||||
rawRows, _ := data["rows"].([]any)
|
||||
projected := table.ProjectRows(arr, rawRows)
|
||||
parr, _ := projected.([]any)
|
||||
var items []map[string]any
|
||||
for _, v := range parr {
|
||||
if m, ok := v.(map[string]any); ok {
|
||||
items = append(items, m)
|
||||
}
|
||||
}
|
||||
lb := listBind{Items: items}
|
||||
if t, ok := em["target"].(string); ok {
|
||||
lb.Target = t
|
||||
}
|
||||
lb.HTML = renderListSection(page, items)
|
||||
out = append(out, lb)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func renderListSection(page map[string]any, items []map[string]any) string {
|
||||
var s strings.Builder
|
||||
s.WriteString(`<div class="list-bind" aria-live="polite">`)
|
||||
if len(items) == 0 {
|
||||
s.WriteString(`<p class="list-empty comment-empty">还没有条目。</p>`)
|
||||
} else {
|
||||
s.WriteString(`<ul class="list-thread comment-thread">`)
|
||||
for _, it := range items {
|
||||
s.WriteString(renderListItem(page, it))
|
||||
}
|
||||
s.WriteString(`</ul>`)
|
||||
}
|
||||
s.WriteString(`</div>`)
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func renderListItem(page map[string]any, it map[string]any) string {
|
||||
title := text(it["title"])
|
||||
body := text(it["body"])
|
||||
meta := text(it["meta"])
|
||||
href := text(it["href"])
|
||||
if href != "" {
|
||||
return `<li class="list-item">` + renderCard(page, it) + `</li>`
|
||||
}
|
||||
var s strings.Builder
|
||||
s.WriteString(`<li class="list-item comment-item">`)
|
||||
s.WriteString(`<div class="comment-meta">`)
|
||||
if title != "" {
|
||||
s.WriteString(fmt.Sprintf(`<span class="comment-author">%s</span>`, esc(title)))
|
||||
}
|
||||
if meta != "" {
|
||||
s.WriteString(fmt.Sprintf(`<time>%s</time>`, esc(meta)))
|
||||
}
|
||||
s.WriteString(`</div>`)
|
||||
if body != "" {
|
||||
escaped := esc(body)
|
||||
escaped = strings.ReplaceAll(escaped, "\n", "<br>")
|
||||
s.WriteString(fmt.Sprintf(`<p class="comment-body">%s</p>`, escaped))
|
||||
}
|
||||
s.WriteString(`</li>`)
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func applyListTargets(intro string, lists []listBind) (string, string) {
|
||||
rest := strings.Builder{}
|
||||
for _, lb := range lists {
|
||||
if lb.HTML == "" {
|
||||
continue
|
||||
}
|
||||
if lb.Target != "" && intro != "" {
|
||||
if injected, ok := injectHTMLIntoID(intro, lb.Target, lb.HTML); ok {
|
||||
intro = injected
|
||||
continue
|
||||
}
|
||||
}
|
||||
rest.WriteString(lb.HTML)
|
||||
}
|
||||
return intro, rest.String()
|
||||
}
|
||||
|
||||
func fieldCSS(obj map[string]any, field string) string {
|
||||
css, _ := obj["_css"].(map[string]any)
|
||||
if css == nil {
|
||||
@@ -846,7 +960,17 @@ func pageFormHTML(page map[string]any) (formID string, html string) {
|
||||
if !ok || frm == nil {
|
||||
return "", ""
|
||||
}
|
||||
return id, form.RenderBody(frm, id, nil, nil, "")
|
||||
ctx := &form.RequestContext{
|
||||
Params: pageParams(page),
|
||||
}
|
||||
if u, ok := page["_nav_user"].(string); ok {
|
||||
ctx.Username = u
|
||||
}
|
||||
if r, ok := page["_route"].(string); ok && r != "" {
|
||||
ctx.ReturnPath = r
|
||||
ctx.Path = r
|
||||
}
|
||||
return id, form.RenderBodyCtx(frm, id, nil, nil, "", ctx)
|
||||
}
|
||||
|
||||
func pushIntro(buf *strings.Builder, intro string) {
|
||||
@@ -906,19 +1030,26 @@ func renderFragment(page map[string]any, dbURL, slot string) string {
|
||||
)
|
||||
default:
|
||||
intro, items, _ := resolveMain(page, dbURL)
|
||||
lists := resolveLists(page, dbURL)
|
||||
intro, listRest := applyListTargets(intro, lists)
|
||||
isDetail, _ := page["detail"].(bool)
|
||||
var body strings.Builder
|
||||
pushIntroAndForm(&body, intro, page)
|
||||
if len(items) > 0 {
|
||||
isDetail, _ := page["detail"].(bool)
|
||||
if isDetail {
|
||||
if isDetail {
|
||||
if len(items) > 0 {
|
||||
body.WriteString(renderArticle(items[0]))
|
||||
} else {
|
||||
}
|
||||
body.WriteString(listRest)
|
||||
pushIntroAndForm(&body, intro, page)
|
||||
} else {
|
||||
pushIntroAndForm(&body, intro, page)
|
||||
if len(items) > 0 {
|
||||
body.WriteString(`<section class="content cards">`)
|
||||
for _, it := range items {
|
||||
body.WriteString(renderCard(page, it))
|
||||
}
|
||||
body.WriteString(`</section>`)
|
||||
}
|
||||
body.WriteString(listRest)
|
||||
}
|
||||
return fmt.Sprintf(`<main class="main" data-slot="main">%s</main>`, body.String())
|
||||
}
|
||||
@@ -1011,21 +1142,31 @@ func RenderPage(page map[string]any, dbURL string, partID string) string {
|
||||
if images, ok := page["images_html"].(string); ok && images != "" {
|
||||
mainHTML.WriteString(images)
|
||||
}
|
||||
pushIntroAndForm(&mainHTML, intro, page)
|
||||
if len(items) > 0 {
|
||||
isDetail, _ := page["detail"].(bool)
|
||||
if isDetail {
|
||||
lists := resolveLists(page, dbURL)
|
||||
intro, listRest := applyListTargets(intro, lists)
|
||||
isDetail, _ := page["detail"].(bool)
|
||||
if isDetail {
|
||||
if len(items) > 0 {
|
||||
mainHTML.WriteString(renderArticle(items[0]))
|
||||
} else {
|
||||
if total != nil {
|
||||
mainHTML.WriteString(renderPagination(page, *total, len(items)))
|
||||
}
|
||||
}
|
||||
mainHTML.WriteString(listRest)
|
||||
pushIntroAndForm(&mainHTML, intro, page)
|
||||
} else {
|
||||
pushIntroAndForm(&mainHTML, intro, page)
|
||||
if len(items) > 0 {
|
||||
mainHTML.WriteString(`<section class="content cards">`)
|
||||
for _, it := range items {
|
||||
mainHTML.WriteString(renderCard(page, it))
|
||||
}
|
||||
mainHTML.WriteString(`</section>`)
|
||||
if total != nil {
|
||||
mainHTML.WriteString(renderPagination(page, *total, len(items)))
|
||||
}
|
||||
}
|
||||
if total != nil {
|
||||
mainHTML.WriteString(renderPagination(page, *total, len(items)))
|
||||
}
|
||||
mainHTML.WriteString(listRest)
|
||||
}
|
||||
|
||||
styleBlock := ""
|
||||
|
||||
@@ -60,6 +60,7 @@ extern int web_page_chrome(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);
|
||||
extern int web_compose_list(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_compose_intro(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_intro(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_render(char *args_json, char **out_json, char **err_msg);
|
||||
@@ -164,6 +165,7 @@ static int register_core(void) {
|
||||
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;
|
||||
if (host_register((char *)"web_compose_list", (char *)"page,main,query,order,target", web_compose_list) != 0) return 1;
|
||||
if (host_register((char *)"web_compose_intro", (char *)"page,intro", web_compose_intro) != 0) return 1;
|
||||
if (host_register((char *)"web_intro", (char *)"table", web_intro) != 0) return 1;
|
||||
if (host_register((char *)"web_compose_form", (char *)"page,form,id,target", web_compose_form) != 0) return 1;
|
||||
@@ -533,6 +535,30 @@ func web_compose_main(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int
|
||||
return replyJSON(outJSON, errMsg, out, err)
|
||||
}
|
||||
|
||||
//export web_compose_list
|
||||
func web_compose_list(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
pageBag := asPageMap(args["page"])
|
||||
main := args["main"]
|
||||
if main == nil {
|
||||
main = args["主体"]
|
||||
}
|
||||
if main == nil {
|
||||
return replyJSON(outJSON, errMsg, nil, fmt.Errorf("missing `main`"))
|
||||
}
|
||||
query := args["query"]
|
||||
if query == nil {
|
||||
query = args["条件"]
|
||||
}
|
||||
order, _ := argStr(args, "order", "排序")
|
||||
target, _ := argStr(args, "target", "插槽", "表单插槽")
|
||||
out, err := compose.ComposeList(pageBag, main, query, order, target, callLib)
|
||||
return replyJSON(outJSON, errMsg, out, err)
|
||||
}
|
||||
|
||||
//export web_compose_intro
|
||||
func web_compose_intro(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
|
||||
+183
-58
@@ -4,10 +4,15 @@
|
||||
# Example: ./scripts/ppa-build-source.sh noble
|
||||
#
|
||||
# Launchpad builders have no network and noble's cargo (1.75) cannot read
|
||||
# Cargo.lock v4. This script therefore:
|
||||
# Cargo.lock v4. For a *new* upstream SemVer this script:
|
||||
# 1) cargo vendor → vendor/
|
||||
# 2) installs a modern Rust toolchain into third_party/rust (cached)
|
||||
# 3) packs both into the .orig.tar.xz for offline debuild on Launchpad
|
||||
#
|
||||
# For debian-only bumps (same upstream X.Y.Z already in the PPA):
|
||||
# - Reuse the published marqdo_X.Y.Z.orig.tar.xz (never rewrite it)
|
||||
# - debuild -S -sd (do not re-upload .orig)
|
||||
# Override: MARQDO_PPA_FORCE_ORIG=1 rebuilds orig; MARQDO_PPA_ORIG=/path uses that file.
|
||||
set -euo pipefail
|
||||
|
||||
SERIES="${1:-noble}"
|
||||
@@ -47,20 +52,175 @@ RUST_NAME="rust-${RUST_VER}-${RUST_TRIPLE}"
|
||||
RUST_CACHE="${MARQDO_PPA_RUST_CACHE:-${HOME}/.cache/marqdo-ppa}"
|
||||
RUST_TARBALL="${RUST_CACHE}/${RUST_NAME}.tar.gz"
|
||||
RUST_URL="${MARQDO_PPA_RUST_URL:-https://static.rust-lang.org/dist/${RUST_NAME}.tar.gz}"
|
||||
PPA_OWNER="${MARQDO_PPA_OWNER:-cflmy}"
|
||||
PPA_NAME="${MARQDO_PPA_NAME:-marqdo}"
|
||||
ORIG_NAME="marqdo_${VER}.orig.tar.xz"
|
||||
FORCE_ORIG="${MARQDO_PPA_FORCE_ORIG:-0}"
|
||||
|
||||
resolve_existing_orig() {
|
||||
local candidate
|
||||
if [ -n "${MARQDO_PPA_ORIG:-}" ]; then
|
||||
candidate="${MARQDO_PPA_ORIG}"
|
||||
if [ ! -f "$candidate" ]; then
|
||||
echo "error: MARQDO_PPA_ORIG not a file: $candidate" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "$candidate"
|
||||
return 0
|
||||
fi
|
||||
for candidate in \
|
||||
"$BUILD_AREA/$ORIG_NAME" \
|
||||
"$RUST_CACHE/$ORIG_NAME" \
|
||||
"$HOME/.cache/marqdo-ppa/$ORIG_NAME"
|
||||
do
|
||||
if [ -f "$candidate" ]; then
|
||||
echo "$candidate"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
download_published_orig() {
|
||||
local dest="$1"
|
||||
local urls=(
|
||||
"https://ppa.launchpadcontent.net/${PPA_OWNER}/${PPA_NAME}/ubuntu/pool/main/m/marqdo/${ORIG_NAME}"
|
||||
"https://launchpad.net/~${PPA_OWNER}/+archive/ubuntu/${PPA_NAME}/+files/${ORIG_NAME}"
|
||||
)
|
||||
local url
|
||||
mkdir -p "$(dirname "$dest")"
|
||||
for url in "${urls[@]}"; do
|
||||
echo " trying ${url}"
|
||||
if curl -fL --retry 3 --retry-delay 2 --connect-timeout 30 \
|
||||
-o "${dest}.partial" "$url"; then
|
||||
mv "${dest}.partial" "$dest"
|
||||
return 0
|
||||
fi
|
||||
rm -f "${dest}.partial"
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
echo "==> upstream ${VER} → debian ${DEB_VER} (${SERIES})"
|
||||
rm -rf "$PKG_ROOT"
|
||||
mkdir -p "$PKG_ROOT" "$BUILD_AREA" "$RUST_CACHE"
|
||||
|
||||
# Clean export of sources (no target/, .git)
|
||||
if command -v git >/dev/null && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
git archive --format=tar HEAD | tar -x -C "$PKG_ROOT"
|
||||
else
|
||||
rsync -a --exclude target --exclude .git --exclude build-area "$ROOT"/ "$PKG_ROOT"/
|
||||
REUSE_ORIG=0
|
||||
ORIG_SRC=""
|
||||
if [ "$FORCE_ORIG" != "1" ]; then
|
||||
# Prefer the bytes already accepted by Launchpad (rewriting .orig is rejected).
|
||||
if download_published_orig "$RUST_CACHE/$ORIG_NAME"; then
|
||||
ORIG_SRC="$RUST_CACHE/$ORIG_NAME"
|
||||
elif ORIG_SRC="$(resolve_existing_orig)"; then
|
||||
echo "warning: could not fetch PPA ${ORIG_NAME}; using local ${ORIG_SRC}" >&2
|
||||
echo "warning: if its sha256 differs from the archive, Launchpad will reject the upload" >&2
|
||||
fi
|
||||
if [ -n "$ORIG_SRC" ]; then
|
||||
REUSE_ORIG=1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Ensure debian/ from working tree (may be newer than last commit)
|
||||
rsync -a "$ROOT/debian/" "$PKG_ROOT/debian/"
|
||||
if [ "$REUSE_ORIG" -eq 1 ]; then
|
||||
echo "==> reusing published ${ORIG_NAME} (debian-only bump; do not rewrite orig)"
|
||||
echo " source: ${ORIG_SRC}"
|
||||
sha256sum "$ORIG_SRC"
|
||||
cp -f "$ORIG_SRC" "$BUILD_AREA/$ORIG_NAME"
|
||||
# Unpack orig (top dir is usually ${VER} or marqdo-${VER})
|
||||
tar -xJf "$BUILD_AREA/$ORIG_NAME" -C "$(dirname "$PKG_ROOT")"
|
||||
if [ ! -d "$PKG_ROOT" ]; then
|
||||
# Some tarballs use marqdo-${VER}/
|
||||
if [ -d "$(dirname "$PKG_ROOT")/marqdo-${VER}" ]; then
|
||||
mv "$(dirname "$PKG_ROOT")/marqdo-${VER}" "$PKG_ROOT"
|
||||
else
|
||||
echo "error: unpack did not create ${PKG_ROOT}" >&2
|
||||
tar -tJf "$BUILD_AREA/$ORIG_NAME" | head -5 >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
rsync -a "$ROOT/debian/" "$PKG_ROOT/debian/"
|
||||
else
|
||||
echo "==> building fresh ${ORIG_NAME} (new upstream or MARQDO_PPA_FORCE_ORIG=1)"
|
||||
# Clean export of sources (no target/, .git)
|
||||
if command -v git >/dev/null && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
git archive --format=tar HEAD | tar -x -C "$PKG_ROOT"
|
||||
else
|
||||
rsync -a --exclude target --exclude .git --exclude build-area "$ROOT"/ "$PKG_ROOT"/
|
||||
fi
|
||||
rsync -a "$ROOT/debian/" "$PKG_ROOT/debian/"
|
||||
|
||||
cd "$PKG_ROOT"
|
||||
echo "==> cargo vendor (Launchpad offline)"
|
||||
mkdir -p .cargo
|
||||
cargo vendor --locked vendor >/tmp/marqdo-cargo-vendor.conf
|
||||
cat > .cargo/config.toml <<'EOF'
|
||||
[source.crates-io]
|
||||
replace-with = "vendored-sources"
|
||||
|
||||
[source.vendored-sources]
|
||||
directory = "vendor"
|
||||
EOF
|
||||
# dh_clean removes *.orig; drop those paths from vendor checksums so a
|
||||
# stray clean (or older rules) cannot break `cargo --offline` on Launchpad.
|
||||
python3 - <<'PY'
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
root = Path("vendor")
|
||||
if not root.is_dir():
|
||||
raise SystemExit("vendor/ missing after cargo vendor")
|
||||
n_files = 0
|
||||
n_json = 0
|
||||
for checksum in root.rglob(".cargo-checksum.json"):
|
||||
data = json.loads(checksum.read_text(encoding="utf-8"))
|
||||
files = data.get("files") or {}
|
||||
drop = [name for name in files if name.endswith(".orig") or name.endswith(".rej")]
|
||||
if not drop:
|
||||
continue
|
||||
for name in drop:
|
||||
del files[name]
|
||||
path = checksum.parent / name
|
||||
if path.is_file():
|
||||
path.unlink()
|
||||
n_files += 1
|
||||
checksum.write_text(json.dumps(data, indent=4) + "\n", encoding="utf-8")
|
||||
n_json += 1
|
||||
print(f"stripped {n_files} *.orig/*.rej from {n_json} vendor checksums")
|
||||
PY
|
||||
|
||||
echo "==> bundle Rust ${RUST_VER} (${RUST_TRIPLE}) for Launchpad"
|
||||
if [ ! -f "$RUST_TARBALL" ]; then
|
||||
echo " downloading ${RUST_URL}"
|
||||
curl -fL --retry 3 --retry-delay 2 -o "${RUST_TARBALL}.partial" "$RUST_URL"
|
||||
mv "${RUST_TARBALL}.partial" "$RUST_TARBALL"
|
||||
else
|
||||
echo " cache hit ${RUST_TARBALL}"
|
||||
fi
|
||||
rm -rf third_party/rust
|
||||
mkdir -p third_party
|
||||
RUST_EXTRACT="$(mktemp -d "${TMPDIR:-/tmp}/marqdo-rust.XXXXXX")"
|
||||
tar -xzf "$RUST_TARBALL" -C "$RUST_EXTRACT"
|
||||
INSTALL_SH="$(find "$RUST_EXTRACT" -maxdepth 2 -name install.sh | head -1)"
|
||||
if [ -z "$INSTALL_SH" ]; then
|
||||
echo "error: install.sh not found in ${RUST_TARBALL}" >&2
|
||||
exit 1
|
||||
fi
|
||||
bash "$INSTALL_SH" \
|
||||
--prefix="$PKG_ROOT/third_party/rust" \
|
||||
--without=rust-docs \
|
||||
--disable-ldconfig
|
||||
rm -rf "$RUST_EXTRACT"
|
||||
"$PKG_ROOT/third_party/rust/bin/rustc" --version
|
||||
"$PKG_ROOT/third_party/rust/bin/cargo" --version
|
||||
|
||||
cd "$(dirname "$PKG_ROOT")"
|
||||
echo "==> packing ${ORIG_NAME} (vendor + third_party/rust)"
|
||||
rm -f "$BUILD_AREA/$ORIG_NAME"
|
||||
tar -cJf "$BUILD_AREA/$ORIG_NAME" \
|
||||
--exclude=debian \
|
||||
-C "$(dirname "$PKG_ROOT")" "$(basename "$PKG_ROOT")"
|
||||
fi
|
||||
|
||||
cd "$PKG_ROOT"
|
||||
python3 - <<PY
|
||||
@@ -79,58 +239,19 @@ p.write_text(text2, encoding="utf-8")
|
||||
print("changelog:", p.read_text(encoding="utf-8").splitlines()[0])
|
||||
PY
|
||||
|
||||
echo "==> cargo vendor (Launchpad offline)"
|
||||
mkdir -p .cargo
|
||||
cargo vendor --locked vendor >/tmp/marqdo-cargo-vendor.conf
|
||||
cat > .cargo/config.toml <<'EOF'
|
||||
[source.crates-io]
|
||||
replace-with = "vendored-sources"
|
||||
|
||||
[source.vendored-sources]
|
||||
directory = "vendor"
|
||||
EOF
|
||||
|
||||
echo "==> bundle Rust ${RUST_VER} (${RUST_TRIPLE}) for Launchpad"
|
||||
if [ ! -f "$RUST_TARBALL" ]; then
|
||||
echo " downloading ${RUST_URL}"
|
||||
curl -fL --retry 3 --retry-delay 2 -o "${RUST_TARBALL}.partial" "$RUST_URL"
|
||||
mv "${RUST_TARBALL}.partial" "$RUST_TARBALL"
|
||||
else
|
||||
echo " cache hit ${RUST_TARBALL}"
|
||||
fi
|
||||
rm -rf third_party/rust
|
||||
mkdir -p third_party
|
||||
RUST_EXTRACT="$(mktemp -d "${TMPDIR:-/tmp}/marqdo-rust.XXXXXX")"
|
||||
tar -xzf "$RUST_TARBALL" -C "$RUST_EXTRACT"
|
||||
# Official dist tarball contains install.sh
|
||||
INSTALL_SH="$(find "$RUST_EXTRACT" -maxdepth 2 -name install.sh | head -1)"
|
||||
if [ -z "$INSTALL_SH" ]; then
|
||||
echo "error: install.sh not found in ${RUST_TARBALL}" >&2
|
||||
exit 1
|
||||
fi
|
||||
# --disable-ldconfig avoids needing root; strip docs to save space
|
||||
bash "$INSTALL_SH" \
|
||||
--prefix="$PKG_ROOT/third_party/rust" \
|
||||
--without=rust-docs \
|
||||
--disable-ldconfig
|
||||
rm -rf "$RUST_EXTRACT"
|
||||
"$PKG_ROOT/third_party/rust/bin/rustc" --version
|
||||
"$PKG_ROOT/third_party/rust/bin/cargo" --version
|
||||
|
||||
# Always rebuild orig (vendor + rust toolchain change every run)
|
||||
cd "$(dirname "$PKG_ROOT")"
|
||||
ORIG="marqdo_${VER}.orig.tar.xz"
|
||||
echo "==> packing ${ORIG} (vendor + third_party/rust)"
|
||||
rm -f "$BUILD_AREA/$ORIG" "marqdo_${VER}.orig.tar.xz"
|
||||
tar -cJf "$BUILD_AREA/$ORIG" \
|
||||
--exclude=debian \
|
||||
-C "$(dirname "$PKG_ROOT")" "$(basename "$PKG_ROOT")"
|
||||
ln -sfn "$BUILD_AREA/$ORIG" "marqdo_${VER}.orig.tar.xz"
|
||||
ls -lh "$BUILD_AREA/$ORIG"
|
||||
ln -sfn "$BUILD_AREA/$ORIG_NAME" "$(dirname "$PKG_ROOT")/$ORIG_NAME"
|
||||
ls -lh "$BUILD_AREA/$ORIG_NAME"
|
||||
|
||||
cd "$PKG_ROOT"
|
||||
echo "==> debuild -S (key ${GPG_KEY})"
|
||||
debuild -S -sa -k"${GPG_KEY}" -d
|
||||
# -sd: debian-only upload (reuse published orig). -sa: include orig (new upstream).
|
||||
if [ "$REUSE_ORIG" -eq 1 ]; then
|
||||
DEBUILD_ORIG_FLAG="-sd"
|
||||
echo "==> debuild -S ${DEBUILD_ORIG_FLAG} (key ${GPG_KEY}; not re-uploading .orig)"
|
||||
else
|
||||
DEBUILD_ORIG_FLAG="-sa"
|
||||
echo "==> debuild -S ${DEBUILD_ORIG_FLAG} (key ${GPG_KEY}; including new .orig)"
|
||||
fi
|
||||
debuild -S ${DEBUILD_ORIG_FLAG} -k"${GPG_KEY}" -d
|
||||
|
||||
# debuild writes next to package parent (/tmp/marqdo-ppa/); collect into build-area
|
||||
mkdir -p "$BUILD_AREA"
|
||||
@@ -146,6 +267,10 @@ shopt -u nullglob
|
||||
|
||||
echo "==> artifacts in $BUILD_AREA:"
|
||||
ls -la "$BUILD_AREA"/marqdo_"${DEB_VER}"* "$BUILD_AREA"/marqdo_"${VER}".orig.tar.* 2>/dev/null || true
|
||||
if [ "$REUSE_ORIG" -eq 1 ]; then
|
||||
echo " sha256 of reused orig (must match PPA):"
|
||||
sha256sum "$BUILD_AREA/$ORIG_NAME"
|
||||
fi
|
||||
CHANGES="$BUILD_AREA/marqdo_${DEB_VER}_source.changes"
|
||||
if [ -f "$CHANGES" ]; then
|
||||
echo
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
---
|
||||
title: web form source live server
|
||||
description: Request-context field sources — body only; author/slug stamped server-side.
|
||||
import web:ext/web/web.mq.md
|
||||
import plugin:lib/plugin.mq.md
|
||||
import sys:lib/sys.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
**p = > plugin.native_path name="web"**
|
||||
1. `p`
|
||||
> plugin.load path=`p`
|
||||
2. *
|
||||
> sys.exit code=1
|
||||
|
||||
`post_schema` =
|
||||
|
||||
| 字段 | 类型 | 必填 |
|
||||
|------|------|------|
|
||||
| id | integer | false |
|
||||
| slug | text | true |
|
||||
| title | text | true |
|
||||
| content | text | true |
|
||||
|
||||
`comment_schema` =
|
||||
|
||||
| 字段 | 类型 | 必填 |
|
||||
|------|------|------|
|
||||
| id | integer | false |
|
||||
| post_slug | text | true |
|
||||
| author | text | true |
|
||||
| body | text | true |
|
||||
| created_at | text | false |
|
||||
|
||||
**store = > web.db url="sqlite:web-fixtures/data/form-source-live.db"**
|
||||
> `store`.init name=posts fields=`post_schema`
|
||||
> `store`.init name=comments fields=`comment_schema`
|
||||
> `store`.exec sql="DELETE FROM comments"
|
||||
> `store`.exec sql="DELETE FROM posts"
|
||||
|
||||
`seed` =
|
||||
|
||||
| slug | title | content |
|
||||
|------|-------|---------|
|
||||
| hello | Hello | Body of hello |
|
||||
|
||||
> `store`.insert table=posts rows=`seed`
|
||||
|
||||
`detail` =
|
||||
|
||||
| 属性 | 值 | 样式 |
|
||||
|------|-----|------|
|
||||
| title | posts.title | |
|
||||
| body | posts.content | |
|
||||
|
||||
`post_q` =
|
||||
|
||||
| 字段 | 操作 | 值 |
|
||||
|------|------|-----|
|
||||
| slug | = | {slug} |
|
||||
|
||||
`comment_fields` =
|
||||
|
||||
| 字段 | 标签 | 类型 | 必填 | 默认 | 来源 |
|
||||
|------|------|------|------|------|------|
|
||||
| body | Comment | textarea | true | | client |
|
||||
| author | | text | true | | session.username |
|
||||
| post_slug | | text | true | | route.slug |
|
||||
| created_at | | text | false | | now |
|
||||
|
||||
`comment_rules` =
|
||||
|
||||
| 字段 | 规则 | 消息 |
|
||||
|------|------|------|
|
||||
| body | required | body required |
|
||||
| author | required | login required |
|
||||
| post_slug | required | slug required |
|
||||
|
||||
**cf = > web.form table="comments" action="insert"**
|
||||
**cf = > `cf`.fields fields=`comment_fields`**
|
||||
**cf = > `cf`.rules rules=`comment_rules`**
|
||||
|
||||
`comment_cards` =
|
||||
|
||||
| 属性 | 值 | 样式 |
|
||||
|------|-----|------|
|
||||
| title | comments.author | |
|
||||
| body | comments.body | |
|
||||
| meta | comments.created_at | |
|
||||
|
||||
`comment_q` =
|
||||
|
||||
| 字段 | 操作 | 值 |
|
||||
|------|------|-----|
|
||||
| post_slug | = | {slug} |
|
||||
|
||||
**post = > web.page title="Post" intro="<section class='post-comments'><h2>Comments</h2><div id='comment-list'></div><div id='comment-form-mount'></div></section>"**
|
||||
**post = > `post`.compose_main main=`detail`**
|
||||
**post = > `post`.query query=`post_q`**
|
||||
**post = > `post`.detail detail=True**
|
||||
**post = > `post`.compose_list main=`comment_cards` query=`comment_q` order="-created_at" target="#comment-list"**
|
||||
**post = > `post`.compose_form form=`cf` id="comment" target="#comment-form-mount"**
|
||||
|
||||
`users` =
|
||||
|
||||
| 行 | 用户 | 密码 |
|
||||
|----|------|------|
|
||||
| 1 | alice | secret |
|
||||
|
||||
**app = > web.app page=`post` db=`store` port=18117**
|
||||
**app = > `app`.route path="/post/{slug}" page=`post`**
|
||||
**app = > `app`.auth users=`users` login_path="/login" login_redirect="/" session_ttl=3600**
|
||||
**app = > `app`.mount_form id="comment" form=`cf`**
|
||||
|
||||
`api` =
|
||||
|
||||
| 路径 | 方法 | 表 | 条件 | 排序 | 上限 |
|
||||
|------|------|----|------|------|------|
|
||||
| /api/comments | GET | comments | | "-created_at" | 50 |
|
||||
|
||||
**app = > `app`.configure json=`api`**
|
||||
> `app`.listen
|
||||
+152
@@ -84,6 +84,14 @@ fn ensure_web_plugin_built() {
|
||||
assert!(lib.is_file(), "missing Go web plugin at {}", lib.display());
|
||||
// SAFETY: single-threaded Once; children inherit for the rest of the test process.
|
||||
std::env::set_var("MARQDO_WEB_PLUGIN", &lib);
|
||||
// Prefer repo `ext/` over a stale `~/.marqdo/ext` so new page methods (e.g. compose_list)
|
||||
// are visible without requiring `marqdo ext add web` before gold.
|
||||
if std::env::var_os("MARQDO_EXT").is_none() {
|
||||
let ext = root.join("ext");
|
||||
if ext.join("web").join("web.mq.md").is_file() {
|
||||
std::env::set_var("MARQDO_EXT", &ext);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1784,6 +1792,150 @@ slot-ok",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_web_form_source_live() {
|
||||
// Field sources: only body is client-editable; author/slug stamped from session/route.
|
||||
ensure_web_plugin_built();
|
||||
|
||||
let script = "tests/ext/web-form-source-live-server.mq.md";
|
||||
let bin = env!("CARGO_BIN_EXE_marqdo");
|
||||
let mut child = Command::new(bin)
|
||||
.args(["run", script])
|
||||
.current_dir(env!("CARGO_MANIFEST_DIR"))
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn form-source live server");
|
||||
|
||||
let base = "http://127.0.0.1:18117";
|
||||
let ready = std::time::Instant::now();
|
||||
loop {
|
||||
if ready.elapsed().as_secs() > 15 {
|
||||
let _ = child.kill();
|
||||
panic!("form-source live server did not start in time");
|
||||
}
|
||||
let out = Command::new("curl")
|
||||
.args([
|
||||
"-s",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{http_code}",
|
||||
&format!("{base}/post/hello"),
|
||||
])
|
||||
.output()
|
||||
.expect("curl probe");
|
||||
if String::from_utf8_lossy(&out.stdout) == "200" {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
}
|
||||
|
||||
let page = Command::new("curl")
|
||||
.args(["-s", &format!("{base}/post/hello")])
|
||||
.output()
|
||||
.expect("curl post page");
|
||||
let html = String::from_utf8_lossy(&page.stdout);
|
||||
assert!(
|
||||
html.contains(r#"name="body""#),
|
||||
"body field missing: {html}"
|
||||
);
|
||||
assert!(
|
||||
!html.contains(r#"name="author""#),
|
||||
"author must not render (server-only): {html}"
|
||||
);
|
||||
assert!(
|
||||
!html.contains(r#"name="post_slug""#),
|
||||
"post_slug must not render (server-only): {html}"
|
||||
);
|
||||
assert!(
|
||||
html.contains("_mq_params") && html.contains("hello"),
|
||||
"expected _mq_params with slug: {html}"
|
||||
);
|
||||
|
||||
let jar = std::env::temp_dir().join("marqdo-form-source-cookies.txt");
|
||||
let _ = std::fs::remove_file(&jar);
|
||||
let login = Command::new("curl")
|
||||
.args([
|
||||
"-s",
|
||||
"-c",
|
||||
jar.to_str().unwrap(),
|
||||
"-b",
|
||||
jar.to_str().unwrap(),
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{http_code}",
|
||||
"-X",
|
||||
"POST",
|
||||
&format!("{base}/login"),
|
||||
"-d",
|
||||
"username=alice&password=secret",
|
||||
])
|
||||
.output()
|
||||
.expect("curl login");
|
||||
let login_code = String::from_utf8_lossy(&login.stdout);
|
||||
assert!(
|
||||
login_code == "303" || login_code == "302" || login_code == "200",
|
||||
"login http_code={login_code}"
|
||||
);
|
||||
|
||||
let post = Command::new("curl")
|
||||
.args([
|
||||
"-s",
|
||||
"-c",
|
||||
jar.to_str().unwrap(),
|
||||
"-b",
|
||||
jar.to_str().unwrap(),
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{http_code}",
|
||||
"-X",
|
||||
"POST",
|
||||
&format!("{base}/_form/comment"),
|
||||
"--data-urlencode",
|
||||
"body=gold comment",
|
||||
"--data-urlencode",
|
||||
"author=forged-attacker",
|
||||
"--data-urlencode",
|
||||
"post_slug=evil-slug",
|
||||
"--data-urlencode",
|
||||
r#"_mq_params={"slug":"hello"}"#,
|
||||
"--data-urlencode",
|
||||
"_mq_return=/post/hello",
|
||||
])
|
||||
.output()
|
||||
.expect("curl form post");
|
||||
let post_code = String::from_utf8_lossy(&post.stdout);
|
||||
assert!(
|
||||
post_code == "303" || post_code == "302",
|
||||
"form post http_code={post_code}"
|
||||
);
|
||||
|
||||
let api = Command::new("curl")
|
||||
.args(["-s", &format!("{base}/api/comments")])
|
||||
.output()
|
||||
.expect("curl comments api");
|
||||
let body = String::from_utf8_lossy(&api.stdout);
|
||||
assert!(
|
||||
body.contains("\"author\":\"alice\"") && body.contains("gold comment"),
|
||||
"author must be session user, not forged: {body}"
|
||||
);
|
||||
assert!(
|
||||
body.contains("\"post_slug\":\"hello\""),
|
||||
"post_slug must be route param, not forged: {body}"
|
||||
);
|
||||
assert!(
|
||||
!body.contains("forged-attacker") && !body.contains("evil-slug"),
|
||||
"forged values must not persist: {body}"
|
||||
);
|
||||
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
let _ = std::fs::remove_file(&jar);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_web_part_smoke() {
|
||||
ensure_web_plugin_built();
|
||||
|
||||
Reference in new issue
Block a user