diff --git a/CHANGELOG.md b/CHANGELOG.md index 4260dad..331861e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,10 +8,12 @@ ### Fixed - **`agent.step` / `plan` 写回**:参数名 `writeback` 遮蔽 `lib/writeback` import,导致 `writeback=True` 时 `method receiver must be an object map`;改为 `host_writeback_record`。金样 `agent-writeback-shadow`。 +- **`ext/web` C0**:`admin=False` 不再挂载/保留 `/admin*`;可配 `admin_prefix` / `login_redirect` / `logout_redirect`;金样 `web-c0-admin-prefix`。 ### Changed - `build_step_context`:call site 提前到 task 之后;开场白强调 code-as-documentation。 - 中文 `构建单步上下文` 委托英文版(含预算 / READ);新增 `dump_step_context`;live 用例改用仓库根 `.env`。 +- 文档:[ext-web 定制限制](doc/research/ext-web-customization-limits.md) + [解决设计 C0–C4](doc/design/ext-web-customization/)。 ## v0.3.3 — 2026-09-04 diff --git a/doc/design/ext-web-customization/01-routes-and-admin-prefix.md b/doc/design/ext-web-customization/01-routes-and-admin-prefix.md index 5e2e2d3..8fd2a4e 100644 --- a/doc/design/ext-web-customization/01-routes-and-admin-prefix.md +++ b/doc/design/ext-web-customization/01-routes-and-admin-prefix.md @@ -67,6 +67,8 @@ --- -## 6. 过渡期作者 workaround(实现前) +## 6. 过渡期 → 已落地 -继续用 `/desk` 旁路 + JS 调 `/admin/login`;**实现 C0 后应删除该兜底**,避免双入口长期并存。 +~~继续用 `/desk` 旁路 + JS 调 `/admin/login`。~~ + +**C0 已落地(2026-09):** `admin=False` 可直接 `route path="/admin/…"`;或 `admin=True` + `admin_prefix="/desk"` + `login_redirect` / `logout_redirect`。见金样 `tests/ext/web-c0-admin-prefix.mq.md`。 diff --git a/doc/design/ext-web-customization/README.md b/doc/design/ext-web-customization/README.md index dcad52f..b07ed3d 100644 --- a/doc/design/ext-web-customization/README.md +++ b/doc/design/ext-web-customization/README.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **设计草案(待排期实现)** | +| 状态 | **C0 done · C1–C4 planned** | | 日期 | 2026-09-04 | | 问题盘点 | [../../research/ext-web-customization-limits.md](../../research/ext-web-customization-limits.md) | | 相关 | [../ext-web.md](../ext-web.md) · [../ext-web-net.md](../ext-web-net.md) · [../../roadmap/ext-web.md](../../roadmap/ext-web.md) | diff --git a/doc/roadmap/ext-web.md b/doc/roadmap/ext-web.md index 6c90bcf..1feeeab 100644 --- a/doc/roadmap/ext-web.md +++ b/doc/roadmap/ext-web.md @@ -41,7 +41,7 @@ | 波次 | 内容 | 状态 | |------|------|------| -| **C0** | `admin` 关则不占路径;`admin_prefix` / 登录回跳可配 | **planned** | +| **C0** | `admin` 关则不占路径;`admin_prefix` / 登录回跳可配 | **done** | | **C1** | gate 匹配与未登录策略一致;段边界默认 admin gate | **planned** | | **C2** | `shell_css` + `layout` 松绑 | **planned** | | **C3** | 样式 strict / 脚本 defer·version | **planned** | diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md index 5a3fdef..ccffa4e 100644 --- a/ext/web/web.mq.md +++ b/ext/web/web.mq.md @@ -565,9 +565,14 @@ Field table + rules table; submit writes through `# db`. + `admin`=False + `host`=127.0.0.1 + `port`=18081 + + `admin_prefix`=/admin + + `login_redirect`=None + + `logout_redirect`=None + +Construct an app. `admin=True` mounts the built-in CRUD UI under `admin_prefix` (default `/admin`). When `admin=False`, that prefix is **not** reserved — you may `route` your own pages there. Optional `login_redirect` / `logout_redirect` override post-auth landing (defaults: `{admin_prefix}` and `{admin_prefix}/login`). > ensure_plugin -**> web_app_new page=`page` db=`db` admin=`admin` host=`host` port=`port`** +**> web_app_new page=`page` db=`db` admin=`admin` host=`host` port=`port` admin_prefix=`admin_prefix` login_redirect=`login_redirect` logout_redirect=`logout_redirect`** ## route + `path` @@ -636,10 +641,13 @@ Register a WebSocket endpoint at `path` (e.g. `/live`). `mode` is `echo` (defaul ## auth + `users` + `session_ttl`=3600 + + `admin_prefix`=None + + `login_redirect`=None + + `logout_redirect`=None -Keep the app's `admin=True`, and gate `/admin*` behind a login page. `users` is an admin-users table (`|username|password|` / `|用户名|密码|`); optional `role` / `角色` column (`admin` / `author` / `visitor`). Unauthenticated requests redirect to `/admin/login`. Registers a default gate `/admin*` → `admin`. +Keep the app's `admin=True`, and gate `{admin_prefix}*` behind a login page (default prefix `/admin`). `users` is an admin-users table (`|username|password|` / `|用户名|密码|`); optional `role` / `角色` column (`admin` / `author` / `visitor`). Unauthenticated requests under the prefix redirect to `{admin_prefix}/login`. Registers a default gate `{admin_prefix}*` → `admin`. Optional args override `admin_prefix` / `login_redirect` / `logout_redirect` on the app. -**> web_app_auth app=`self` users=`users` session_ttl=`session_ttl`** +**> web_app_auth app=`self` users=`users` session_ttl=`session_ttl` admin_prefix=`admin_prefix` login_redirect=`login_redirect` logout_redirect=`logout_redirect`** ## gate + `path` diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md index ee1faee..e0e4923 100644 --- a/ext/web/网页.mq.md +++ b/ext/web/网页.mq.md @@ -545,9 +545,14 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c + `后台`=False + `主机`=127.0.0.1 + `端口`=18081 + + `后台前缀`=/admin + + `登录回跳`=None + + `登出回跳`=None + +构造应用。`后台=真` 时在 `后台前缀`(默认 `/admin`)挂载内置 CRUD。`后台=假` 时该前缀**不再保留**,可自行 `路由` 到 `/admin…`。可选 `登录回跳` / `登出回跳`(默认分别为前缀本身与 `{前缀}/login`)。 > 确保插件 -**> web_app_new page=`页面` db=`数据库` admin=`后台` host=`主机` port=`端口`** +**> web_app_new page=`页面` db=`数据库` admin=`后台` host=`主机` port=`端口` admin_prefix=`后台前缀` login_redirect=`登录回跳` logout_redirect=`登出回跳`** ## 路由 + `路径` @@ -611,10 +616,13 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c ## 鉴权 + `用户表` + `会话时长`=3600 + + `后台前缀`=None + + `登录回跳`=None + + `登出回跳`=None -在保持 `后台=真` 的同时,为 `/admin*` 加登录门禁。`用户表` 为 `|用户名|密码|`(可选 `角色`:`admin`/`author`/`visitor`);未登录重定向到 `/admin/login`。默认登记门禁 `/admin*` → `admin`。 +在保持 `后台=真` 的同时,为 `{后台前缀}*` 加登录门禁(默认前缀 `/admin`)。`用户表` 为 `|用户名|密码|`(可选 `角色`:`admin`/`author`/`visitor`);未登录重定向到 `{前缀}/login`。默认登记门禁 `{前缀}*` → `admin`。可选参数可覆盖应用上的前缀与回跳。 -**> web_app_auth app=`self` users=`用户表` session_ttl=`会话时长`** +**> web_app_auth app=`self` users=`用户表` session_ttl=`会话时长` admin_prefix=`后台前缀` login_redirect=`登录回跳` logout_redirect=`登出回跳`** ## 门禁 + `路径` diff --git a/plugins/web/src/form.rs b/plugins/web/src/form.rs index 7f896a5..bb73732 100644 --- a/plugins/web/src/form.rs +++ b/plugins/web/src/form.rs @@ -193,11 +193,13 @@ fn sql_type_to_input(sql_type: &str, name: &str) -> &'static str { } /// Build a form handle from live SQLite schema (admin new/edit). +/// `admin_prefix` is the mount root (default `/admin`), without trailing slash. pub fn from_schema( db_url: &str, table: &str, action: &str, id: Option<&str>, + admin_prefix: &str, ) -> Result { let action = match action { "update" | "更新" => "update", @@ -223,22 +225,24 @@ pub fn from_schema( "pk": c.pk, })); } + let base = admin_prefix.trim_end_matches('/'); + let table_href = format!("{base}/{table}"); let mut form = form_new(Some(table), action, id); if let Some(obj) = form.as_object_mut() { obj.insert("fields".into(), Value::Array(fields)); - obj.insert("redirect".into(), json!(format!("/admin/{table}"))); + obj.insert("redirect".into(), json!(&table_href)); if action == "insert" { - obj.insert("action_url".into(), json!(format!("/admin/{table}/new"))); + obj.insert("action_url".into(), json!(format!("{table_href}/new"))); obj.insert("title".into(), json!(format!("New {table}"))); } else if let Some(i) = id { obj.insert( "action_url".into(), - json!(format!("/admin/{table}/{i}/edit")), + json!(format!("{table_href}/{i}/edit")), ); obj.insert("title".into(), json!(format!("Edit {table} #{i}"))); obj.insert("id".into(), json!(i)); } - obj.insert("cancel_href".into(), json!(format!("/admin/{table}"))); + obj.insert("cancel_href".into(), json!(&table_href)); } Ok(form) } diff --git a/plugins/web/src/http.rs b/plugins/web/src/http.rs index 84c9b29..38a6a98 100644 --- a/plugins/web/src/http.rs +++ b/plugins/web/src/http.rs @@ -74,6 +74,10 @@ pub struct AppState { page: Value, pub db_url: Option, admin: bool, + /// Built-in admin mount root (e.g. `/admin` or `/desk`); unused when `admin` is false. + admin_prefix: String, + login_redirect: String, + logout_redirect: String, forms: HashMap, /// Page that owns an embedded form (for re-render on validation errors). form_owners: HashMap, @@ -90,6 +94,26 @@ pub struct AppState { site_head: Vec, } +impl AppState { + fn ap(&self) -> &str { + self.admin_prefix.trim_end_matches('/') + } + + fn admin_href(&self, rest: &str) -> String { + let p = self.ap(); + let rest = rest.trim().trim_start_matches('/'); + if rest.is_empty() { + p.to_string() + } else { + format!("{p}/{rest}") + } + } + + fn login_path(&self) -> String { + self.admin_href("login") + } +} + fn collect_page_forms( page: &Value, forms: &mut HashMap, @@ -118,6 +142,9 @@ pub fn listen( host: &str, port: u16, admin: bool, + admin_prefix: &str, + login_redirect: &str, + logout_redirect: &str, mut forms: HashMap, routes: HashMap, static_dir: Option, @@ -166,10 +193,23 @@ pub fn listen( // Resolve relative icon paths: try as-is absolute, else leave for entry_dir resolve in lib. // (Absolute paths preferred; relative already joined in web_listen.) + let admin_prefix = { + let mut p = admin_prefix.trim().to_string(); + if !p.starts_with('/') { + p = format!("/{p}"); + } + while p.len() > 1 && p.ends_with('/') { + p.pop(); + } + p + }; let state = Arc::new(AppState { page: page.clone(), db_url: db_url.map(|s| s.to_string()), admin, + admin_prefix: admin_prefix.clone(), + login_redirect: login_redirect.to_string(), + logout_redirect: logout_redirect.to_string(), forms, form_owners, auth_users, @@ -185,17 +225,23 @@ pub fn listen( let mut app = Router::new() .route("/", get(home)) .route("/_part/{id}", get(home_part)) - .route("/_form/{id}", get(form_get).post(form_post)) - .route("/admin", get(admin_home)) - .route("/admin/login", get(admin_login_get).post(admin_login_post)) - .route("/admin/logout", get(admin_logout)) - .route("/admin/{table}", get(admin_table)) - .route("/admin/{table}/new", get(admin_new_get).post(admin_new_post)) - .route( - "/admin/{table}/{id}/edit", - get(admin_edit_get).post(admin_edit_post), - ) - .route("/admin/{table}/{id}/delete", get(admin_delete)); + .route("/_form/{id}", get(form_get).post(form_post)); + + // Built-in admin only when enabled — otherwise `/admin…` is free for author routes. + if admin { + let admin_routes = Router::new() + .route("/", get(admin_home)) + .route("/login", get(admin_login_get).post(admin_login_post)) + .route("/logout", get(admin_logout)) + .route("/{table}", get(admin_table)) + .route("/{table}/new", get(admin_new_get).post(admin_new_post)) + .route( + "/{table}/{id}/edit", + get(admin_edit_get).post(admin_edit_post), + ) + .route("/{table}/{id}/delete", get(admin_delete)); + app = app.nest(&admin_prefix, admin_routes); + } // Register each author route as an exact GET path + `{path}/_part/{id}`. // Paths containing `{param}` become dynamic routes (e.g. `/post/{slug}`); @@ -434,10 +480,14 @@ pub fn listen( let app = crate::middleware::apply(app, middleware); let app = if !gates.is_empty() { let gates_for_mw = gates.clone(); + let login_path_for_mw = state.login_path(); + let admin_prefix_for_mw = state.admin_prefix.clone(); app.layer(axum::middleware::from_fn( move |req: axum::http::Request, next: axum::middleware::Next| { let gates = gates_for_mw.clone(); - async move { rbac_middleware(gates, req, next).await } + let login_path = login_path_for_mw.clone(); + let admin_prefix = admin_prefix_for_mw.clone(); + async move { rbac_middleware(gates, login_path, admin_prefix, req, next).await } }, )) } else { @@ -911,8 +961,14 @@ fn path_matches(path: &str, pattern: &str) -> bool { } } +fn path_under_admin_prefix(path: &str, prefix: &str) -> bool { + path == prefix || path.starts_with(&format!("{prefix}/")) +} + async fn rbac_middleware( gates: Vec<(String, Vec)>, + login_path: String, + admin_prefix: String, req: axum::http::Request, next: axum::middleware::Next, ) -> Response { @@ -927,13 +983,13 @@ async fn rbac_middleware( continue; } // Login page itself must stay reachable. - if path == "/admin/login" || path.starts_with("/admin/login?") { + if path == login_path || path.starts_with(&format!("{login_path}?")) { break; } let role = session::session_role(cookie.as_deref()); if !session::role_allowed(&role, roles) { - if role == "visitor" && path.starts_with("/admin") { - return Redirect::to("/admin/login").into_response(); + if role == "visitor" && path_under_admin_prefix(&path, &admin_prefix) { + return Redirect::to(&login_path).into_response(); } return ( StatusCode::FORBIDDEN, @@ -1044,18 +1100,15 @@ h1{{margin:0 0 1rem;font-size:1.5rem}} } fn admin_gate(st: &AppState, cookie_header: Option<&str>) -> Option { + // When admin=false the built-in routes are not mounted; defense-in-depth only. if !st.admin { - return Some(Html(admin_shell(st, "Admin", None, "

Admin is disabled for this app.

")).into_response()); + return Some((StatusCode::NOT_FOUND, "Not Found").into_response()); } if st.db_url.is_none() { return Some(Html(admin_shell(st, "Admin", None, "

No database bound to this app.

")).into_response()); } - // Login-gated admin: require a valid admin-role session. if st.auth_users.is_some() && !admin_authed(st, cookie_header) { - return Some( - Redirect::to("/admin/login") - .into_response(), - ); + return Some(Redirect::to(&st.login_path()).into_response()); } None } @@ -1074,10 +1127,10 @@ fn admin_authed(_st: &AppState, cookie_header: Option<&str>) -> bool { async fn admin_login_get(State(st): State>, headers: axum::http::HeaderMap) -> Response { if st.auth_users.is_none() { - return Redirect::to("/admin").into_response(); + return Redirect::to(&st.login_redirect).into_response(); } if admin_authed(&st, cookie_from_headers(&headers)) { - return Redirect::to("/admin").into_response(); + return Redirect::to(&st.login_redirect).into_response(); } let (_, csrf, set_cookie) = resolve_session(&headers); let mut resp = Html(login_page(&st, None, Some(&csrf))).into_response(); @@ -1091,7 +1144,7 @@ async fn admin_login_post( Form(posted): Form>, ) -> Response { let Some(users) = &st.auth_users else { - return Redirect::to("/admin").into_response(); + return Redirect::to(&st.login_redirect).into_response(); }; let (_, csrf, set_cookie, posted) = match validate_csrf_post(&headers, posted) { Ok(v) => v, @@ -1117,7 +1170,7 @@ async fn admin_login_post( let sid = session::session_new(Some(st.session_ttl)); session::session_set(&sid, "username", json!(user)); session::session_set(&sid, "role", json!(role)); - let mut resp = Redirect::to("/admin").into_response(); + let mut resp = Redirect::to(&st.login_redirect).into_response(); let _ = resp.headers_mut().try_append( axum::http::header::SET_COOKIE, session::session_cookie(&sid, st.session_ttl, st.cookie_secure) @@ -1128,7 +1181,7 @@ async fn admin_login_post( resp } -fn login_page(_st: &AppState, error: Option<&str>, csrf: Option<&str>) -> String { +fn login_page(st: &AppState, error: Option<&str>, csrf: Option<&str>) -> String { let err = match error { Some(e) => format!("

{}

", esc(e)), None => String::new(), @@ -1163,7 +1216,7 @@ body {{ margin:0; min-height:100vh; display:grid; place-items:center; background

Admin

Sign in to manage this site.

{err} -
+ {csrf_field} @@ -1173,11 +1226,12 @@ body {{ margin:0; min-height:100vh; display:grid; place-items:center; background "#, err = err, csrf_field = csrf_field, + login_action = esc(&st.login_path()), ) } async fn admin_logout( - State(_st): State>, + State(st): State>, headers: axum::http::HeaderMap, ) -> Response { if let Some(sid) = session::session_id_from_cookie( @@ -1187,7 +1241,7 @@ async fn admin_logout( ) { session::session_destroy(&sid); } - let mut resp = Redirect::to("/admin/login").into_response(); + let mut resp = Redirect::to(&st.logout_redirect).into_response(); if let Ok(h) = resp.headers_mut().try_append( axum::http::header::SET_COOKIE, "marqdo_sid=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax" @@ -1217,7 +1271,7 @@ fn admin_shell(st: &AppState, title: &str, active: Option<&str>, inner: &str) -> .as_deref() .and_then(|u| db::list_tables(u).ok()) .unwrap_or_default(); - let mut side = String::from("