ext/web W1–W3: middleware, data layer, and security hardening

Deliver the interrupted network extension backlog: declarative middleware
(CORS, security headers, gzip, JSON API), SQLite pool/transactions/pagination,
and W3 security (argon2 passwords, CSRF on forms/login, persistent sessions,
CSPRNG ids, login rate limiting). Adds gold smokes and author-facing
hash_password on ext/web.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-28 09:35:39 +08:00
1 parent da9fc75b1e
commit be6223f1fb
22 files changed
+3081 -343

No files matched your search

+422 -94
View File
@@ -1,10 +1,67 @@
//! SQLite helpers for `# db` CRUD (`init` / `insert` / `select` / `get` / `update` / `delete` / `exec`).
//! SQLite helpers for `# db` CRUD and W2 data-layer capabilities.
//!
//! - **连接池**:进程级 `Pool` 复用连接(WAL + busy_timeout + foreign_keys),
//! 避免每请求重连与并发写 `database is locked`。
//! - **事务**:`begin` 把连接从池中借出并独占,`commit` / `rollback` 后归还。
//! - **查询表达力**:where 支持 OR 组、`in` / `between` / `is null`。
//! - **分页**:`select` 支持 `offset`,返回 `{rows, total}`。
use rusqlite::{types::ValueRef, Connection, OptionalExtension, params_from_iter};
use serde_json::{json, Map, Value};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
fn open(url: &str) -> Result<Connection, String> {
/// Process-wide pool: url → shared connection. Connections are reused across
/// calls instead of reopening per request.
static POOL: Mutex<Option<HashMap<String, Arc<Mutex<Connection>>>>> = Mutex::new(None);
/// Process-wide active transactions: txn id → (url, borrowed connection).
static TXNS: Mutex<Option<HashMap<String, (String, Arc<Mutex<Connection>>)>>> =
Mutex::new(None);
/// Reset pools (used between listens / tests).
#[allow(dead_code)]
pub fn reset_pool() {
let mut p = POOL.lock().unwrap_or_else(|e| e.into_inner());
*p = Some(HashMap::new());
let mut t = TXNS.lock().unwrap_or_else(|e| e.into_inner());
*t = Some(HashMap::new());
}
fn next_txn_id() -> String {
use std::time::{SystemTime, UNIX_EPOCH};
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.subsec_nanos())
.unwrap_or(0);
let pid = std::process::id();
static COUNTER: Mutex<u64> = Mutex::new(0x243f_6a88_85a3_08d3);
let mut c = COUNTER.lock().unwrap_or_else(|e| e.into_inner());
let mut x = *c;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
*c = x;
format!("txn-{pid:x}{nanos:x}{x:x}")
}
/// Open (or reuse) a pooled connection. WAL + busy_timeout + foreign_keys are
/// applied once per physical connection.
fn pooled(url: &str) -> Result<Arc<Mutex<Connection>>, String> {
let mut guard = POOL.lock().unwrap_or_else(|e| e.into_inner());
let pool = guard.get_or_insert_with(HashMap::new);
if let Some(c) = pool.get(url) {
return Ok(c.clone());
}
let conn = open_conn(url)?;
let arc = Arc::new(Mutex::new(conn));
pool.insert(url.to_string(), arc.clone());
Ok(arc)
}
/// Open a fresh physical connection to `url`, creating parent dirs as needed.
fn open_conn(url: &str) -> Result<Connection, String> {
let path = url
.strip_prefix("sqlite:")
.or_else(|| url.strip_prefix("SQLITE:"))
@@ -15,11 +72,32 @@ fn open(url: &str) -> Result<Connection, String> {
}
}
let conn = Connection::open(path).map_err(|e| e.to_string())?;
conn.execute_batch("PRAGMA foreign_keys = ON;")
.map_err(|e| e.to_string())?;
conn.execute_batch(
"PRAGMA foreign_keys = ON;
PRAGMA journal_mode = WAL;
PRAGMA busy_timeout = 5000;",
)
.map_err(|e| e.to_string())?;
Ok(conn)
}
/// Borrow a connection for a single statement. If `txn_id` is set, the txn's
/// borrowed connection is used (transactional reads/writes); otherwise the pool.
fn conn_for<'a>(
url: &str,
txn_id: Option<&'a str>,
) -> Result<Arc<Mutex<Connection>>, String> {
if let Some(tid) = txn_id {
let guard = TXNS.lock().unwrap_or_else(|e| e.into_inner());
match guard.as_ref().and_then(|m| m.get(tid)) {
Some((_, c)) => Ok(c.clone()),
None => Err(format!("unknown transaction `{tid}`")),
}
} else {
pooled(url)
}
}
fn ident(s: &str) -> Result<&str, String> {
let s = s.trim();
if s.is_empty()
@@ -139,16 +217,18 @@ pub fn init(url: &str, table: &str, fields: &Value) -> Result<Value, String> {
"CREATE TABLE IF NOT EXISTS \"{table}\" ({})",
parts.join(", ")
);
let conn = open(url)?;
conn.execute_batch(&sql).map_err(|e| e.to_string())?;
let conn = pooled(url)?;
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
c.execute_batch(&sql).map_err(|e| e.to_string())?;
Ok(json!({ "_type": "db_table", "name": table, "url": url }))
}
pub fn insert(url: &str, table: &str, rows: &Value) -> Result<Value, String> {
pub fn insert(url: &str, table: &str, rows: &Value, txn_id: Option<&str>) -> Result<Value, String> {
let table = ident(table)?;
let rows = crate::table::as_rows(rows);
let arr = rows.as_array().ok_or("rows must be a list")?;
let conn = open(url)?;
let conn = conn_for(url, txn_id)?;
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
let mut n = 0i64;
for row in arr {
let obj = row.as_object().ok_or("row must be a map")?;
@@ -172,7 +252,7 @@ pub fn insert(url: &str, table: &str, rows: &Value) -> Result<Value, String> {
cols.join(", "),
placeholders.join(", ")
);
conn.execute(&sql, params_from_iter(vals.iter().cloned()))
c.execute(&sql, params_from_iter(vals.iter().cloned()))
.map_err(|e| e.to_string())?;
n += 1;
}
@@ -192,64 +272,161 @@ fn where_op(raw: &str) -> Result<&'static str, String> {
"<" | "lt" | "小于" => Ok("<"),
"<=" | "lte" | "小于等于" => Ok("<="),
"like" | "contains" | "包含" | "匹配" => Ok("LIKE"),
"in" | "在" => Ok("IN"),
"between" | "介于" | "在之间" => Ok("BETWEEN"),
"is null" | "isnull" | "为空" | "空" => Ok("IS NULL"),
other => Err(format!("unsupported where op `{other}`")),
}
}
/// Parse simple filters: map of column→value (AND `=`), or rows
/// `{field|字段, op|操作|=, value|值}` / `{列, 值}`.
fn parse_where(where_v: Option<&Value>) -> Result<(Vec<String>, Vec<rusqlite::types::Value>), String> {
let mut clauses = Vec::new();
let mut vals = Vec::new();
let Some(w) = where_v else {
return Ok((clauses, vals));
};
match w {
Value::Null => {}
Value::Object(m) => {
// Filter-row shape vs column→value map.
let field = m
.get("field")
.or_else(|| m.get("字段"))
.or_else(|| m.get("列"))
.map(cell_str)
.unwrap_or_default();
if !field.is_empty()
&& (m.contains_key("value")
|| m.contains_key("值")
|| m.contains_key("op")
|| m.contains_key("操作"))
{
let col = ident(&field)?;
let op = where_op(
&m.get("op")
.or_else(|| m.get("操作"))
.map(cell_str)
.unwrap_or_default(),
)?;
let val = m
.get("value")
.or_else(|| m.get("值"))
.cloned()
.unwrap_or(Value::Null);
clauses.push(format!("\"{col}\" {op} ?"));
vals.push(to_sql(&val));
} else {
for (k, v) in m {
if skip_where_key(k) {
continue;
}
let col = ident(k)?;
clauses.push(format!("\"{col}\" = ?"));
vals.push(to_sql(v));
}
}
/// One parsed filter clause: column, op, bound values, and whether the clause
/// joins the previous one with `OR` (false ⇒ AND).
struct Clause {
expr: String,
vals: Vec<rusqlite::types::Value>,
or: bool,
}
fn in_values(v: &Value) -> Vec<rusqlite::types::Value> {
match v {
Value::Array(a) => a.iter().map(to_sql).collect(),
Value::String(s) => s
.split(',')
.map(|p| to_sql(&Value::String(p.trim().to_string())))
.collect(),
other => vec![to_sql(other)],
}
}
fn between_values(v: &Value) -> Result<Vec<rusqlite::types::Value>, String> {
match v {
Value::Array(a) if a.len() == 2 => Ok(vec![to_sql(&a[0]), to_sql(&a[1])]),
Value::String(s) => {
let mut it = s.split(',');
let lo = it.next().unwrap_or("").trim().to_string();
let hi = it.next().unwrap_or("").trim().to_string();
Ok(vec![
to_sql(&Value::String(lo)),
to_sql(&Value::String(hi)),
])
}
_ => Err("between expects two bounds (\"lo,hi\" or [lo,hi])".into()),
}
}
/// Parse a filter table row into a `Clause`.
fn clause_from_row(m: &Map<String, Value>) -> Result<Option<Clause>, String> {
let field = m
.get("field")
.or_else(|| m.get("字段"))
.or_else(|| m.get("列"))
.map(cell_str)
.unwrap_or_default();
if field.is_empty() {
return Ok(None);
}
let col = ident(&field)?;
let op = where_op(
&m.get("op")
.or_else(|| m.get("操作"))
.map(cell_str)
.unwrap_or_default(),
)?;
let val = m
.get("value")
.or_else(|| m.get("值"))
.cloned()
.unwrap_or(Value::Null);
let or = m
.get("or")
.or_else(|| m.get("或"))
.and_then(|v| match v {
Value::Bool(b) => Some(*b),
Value::String(s) => Some(matches!(s.trim().to_ascii_lowercase().as_str(), "1" | "true" | "是" | "or" | "或者")),
_ => None,
})
.unwrap_or(false);
let (expr, vals) = match op {
"IS NULL" => (format!("\"{col}\" IS NULL"), vec![]),
"IN" => {
let vs = in_values(&val);
let ph: Vec<&str> = vs.iter().map(|_| "?").collect();
(
format!("\"{col}\" IN ({})", ph.join(", ")),
vs,
)
}
"BETWEEN" => {
let vs = between_values(&val)?;
(format!("\"{col}\" BETWEEN ? AND ?"), vs)
}
_ => (format!("\"{col}\" {op} ?"), vec![to_sql(&val)]),
};
Ok(Some(Clause { expr, vals, or }))
}
/// Parse simple filters: map of column→value (AND `=`), or rows
/// `{field|字段, op|操作|=, value|值, or|或?}` / `{列, 值}`.
/// Supports `in` / `between` / `is null` and OR groups via the `或` column.
///
/// GFM tables reach the plugin in columnar form (`{字段:[…], 值:[…]}`), so the
/// value is first normalized via `as_rows` into a row list.
fn parse_where(where_v: Option<&Value>) -> Result<(Vec<String>, Vec<rusqlite::types::Value>), String> {
let mut clauses: Vec<Clause> = Vec::new();
let Some(w) = where_v else {
return Ok((vec![], vec![]));
};
// Normalize GFM tables (columnar object) into row arrays; a single map
// (column→value filter) becomes a one-element row list.
let w = crate::table::as_rows(w);
match &w {
Value::Null => {}
Value::Array(arr) => {
for item in arr {
let (c, v) = parse_where(Some(item))?;
clauses.extend(c);
vals.extend(v);
match item {
Value::Object(m) => {
let field = m
.get("field")
.or_else(|| m.get("字段"))
.or_else(|| m.get("列"))
.map(cell_str)
.unwrap_or_default();
if !field.is_empty()
&& (m.contains_key("value")
|| m.contains_key("值")
|| m.contains_key("op")
|| m.contains_key("操作"))
{
if let Some(cl) = clause_from_row(m)? {
clauses.push(cl);
}
} else {
for (k, v) in m {
if skip_where_key(k) {
continue;
}
let col = ident(k)?;
clauses.push(Clause {
expr: format!("\"{col}\" = ?"),
vals: vec![to_sql(v)],
or: false,
});
}
}
}
other => {
return Err(format!(
"where must be a map or filter table, got {}",
match other {
Value::String(_) => "string",
Value::Number(_) => "number",
Value::Bool(_) => "bool",
_ => "value",
}
));
}
}
}
}
other => {
@@ -264,7 +441,26 @@ fn parse_where(where_v: Option<&Value>) -> Result<(Vec<String>, Vec<rusqlite::ty
));
}
}
Ok((clauses, vals))
// Assemble: AND by default, OR where the clause is marked.
let mut exprs = Vec::new();
let mut vals = Vec::new();
let mut group: Vec<String> = Vec::new();
for cl in clauses {
if cl.or {
group.push(cl.expr);
} else {
if !group.is_empty() {
exprs.push(format!("({})", group.join(" OR ")));
group.clear();
}
group.push(cl.expr);
}
vals.extend(cl.vals);
}
if !group.is_empty() {
exprs.push(format!("({})", group.join(" OR ")));
}
Ok((exprs, vals))
}
pub fn select(
@@ -273,28 +469,37 @@ pub fn select(
limit: i64,
where_v: Option<&Value>,
) -> Result<Value, String> {
select_order(url, table, limit, where_v, None)
select_order(url, table, limit, where_v, None, None, None)
}
/// Like `select`, with an optional `ORDER BY`.
/// Like `select`, with an optional `ORDER BY`, `OFFSET` and a transaction.
///
/// `order` is a column name, optionally prefixed with `-` for descending
/// (`"created_at"`, `"-created_at"`). Comma-separated lists are allowed.
/// - `order` is a column name, optionally prefixed with `-` for descending
/// (`"created_at"`, `"-created_at"`). Comma-separated lists are allowed.
/// - `offset` (页偏移/跳过) enables pagination: `LIMIT … OFFSET …`.
/// - When `offset` is provided, the result carries `total` (row count without
/// limit/offset) so pages can render `上一页 / 下一页`.
/// - `txn_id` routes the read through an open transaction (事务内一致性读).
pub fn select_order(
url: &str,
table: &str,
limit: i64,
where_v: Option<&Value>,
order: Option<&str>,
offset: Option<i64>,
txn_id: Option<&str>,
) -> Result<Value, String> {
let table = ident(table)?;
let (clauses, mut vals) = parse_where(where_v)?;
let conn = open(url)?;
let (exprs, mut vals) = parse_where(where_v)?;
let conn = conn_for(url, txn_id)?;
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
let mut sql = format!("SELECT * FROM \"{table}\"");
if !clauses.is_empty() {
sql.push_str(" WHERE ");
sql.push_str(&clauses.join(" AND "));
}
let where_sql = if exprs.is_empty() {
String::new()
} else {
format!(" WHERE {}", exprs.join(" AND "))
};
sql.push_str(&where_sql);
if let Some(order) = order {
let order = order.trim();
if !order.is_empty() {
@@ -303,30 +508,61 @@ pub fn select_order(
.map(|p| p.trim())
.filter(|p| !p.is_empty())
.collect();
let mut exprs = Vec::new();
let mut order_exprs = Vec::new();
for part in parts {
let (col, dir) = match part.strip_prefix('-') {
Some(col) => (col, " DESC"),
None => (part, ""),
};
exprs.push(format!("\"{}\"{}", ident(col)?, dir));
order_exprs.push(format!("\"{}\"{}", ident(col)?, dir));
}
if !exprs.is_empty() {
if !order_exprs.is_empty() {
sql.push_str(" ORDER BY ");
sql.push_str(&exprs.join(", "));
sql.push_str(&order_exprs.join(", "));
}
}
}
sql.push_str(&format!(" LIMIT ?{}", vals.len() + 1));
vals.push(rusqlite::types::Value::Integer(limit));
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
if let Some(off) = offset {
if off > 0 {
sql.push_str(&format!(" OFFSET ?{}", vals.len() + 1));
vals.push(rusqlite::types::Value::Integer(off));
}
}
let rows = query_rows(&c, &sql, &vals)?;
// Total count (ignoring limit/offset) for pagination.
let total = if offset.is_some() {
let (_exprs2, where_vals) = parse_where(where_v)?;
let n_where = where_vals.len();
let count_sql = format!("SELECT COUNT(*) FROM \"{table}\"{where_sql}");
count_rows(&c, &count_sql, &vals[..n_where]).unwrap_or(rows.len() as i64)
} else {
rows.len() as i64
};
if offset.is_some() {
Ok(json!({ "rows": rows, "total": total }))
} else {
Ok(json!({ "rows": rows }))
}
}
/// Run `SELECT …` and collect rows as a list of column→value maps.
fn query_rows(
c: &Connection,
sql: &str,
vals: &[rusqlite::types::Value],
) -> Result<Vec<Value>, String> {
let mut stmt = c.prepare(sql).map_err(|e| e.to_string())?;
let names: Vec<String> = (0..stmt.column_count())
.map(|i| stmt.column_name(i).unwrap_or("?").to_string())
.collect();
let mut rows = Vec::new();
let mut rows_iter = stmt
.query(params_from_iter(vals.iter().cloned()))
.map_err(|e| e.to_string())?;
let mut rows = Vec::new();
while let Some(r) = rows_iter.next().map_err(|e| e.to_string())? {
let mut m = Map::new();
for (i, name) in names.iter().enumerate() {
@@ -334,14 +570,25 @@ pub fn select_order(
}
rows.push(Value::Object(m));
}
Ok(json!({ "rows": rows }))
Ok(rows)
}
pub fn get(url: &str, table: &str, id: &str) -> Result<Value, String> {
/// Run `SELECT COUNT(*) …` and return the scalar.
fn count_rows(
c: &Connection,
sql: &str,
vals: &[rusqlite::types::Value],
) -> Result<i64, String> {
c.query_row(sql, params_from_iter(vals.iter().cloned()), |r| r.get(0))
.map_err(|e| e.to_string())
}
pub fn get(url: &str, table: &str, id: &str, txn_id: Option<&str>) -> Result<Value, String> {
let table = ident(table)?;
let conn = open(url)?;
let conn = conn_for(url, txn_id)?;
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
let sql = format!("SELECT * FROM \"{table}\" WHERE \"id\" = ?1 LIMIT 1");
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
let mut stmt = c.prepare(&sql).map_err(|e| e.to_string())?;
let names: Vec<String> = (0..stmt.column_count())
.map(|i| stmt.column_name(i).unwrap_or("?").to_string())
.collect();
@@ -358,7 +605,13 @@ pub fn get(url: &str, table: &str, id: &str) -> Result<Value, String> {
Ok(row.unwrap_or(Value::Null))
}
pub fn update(url: &str, table: &str, id: &str, row: &Value) -> Result<Value, String> {
pub fn update(
url: &str,
table: &str,
id: &str,
row: &Value,
txn_id: Option<&str>,
) -> Result<Value, String> {
let table = ident(table)?;
let obj = row.as_object().ok_or("row must be a map")?;
let mut sets = Vec::new();
@@ -379,38 +632,112 @@ pub fn update(url: &str, table: &str, id: &str, row: &Value) -> Result<Value, St
"UPDATE \"{table}\" SET {} WHERE \"id\" = ?",
sets.join(", ")
);
let conn = open(url)?;
let n = conn
let conn = conn_for(url, txn_id)?;
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
let n = c
.execute(&sql, params_from_iter(vals.iter().cloned()))
.map_err(|e| e.to_string())?;
Ok(json!({ "ok": true, "updated": n }))
}
pub fn delete(url: &str, table: &str, id: &str) -> Result<Value, String> {
pub fn delete(url: &str, table: &str, id: &str, txn_id: Option<&str>) -> Result<Value, String> {
let table = ident(table)?;
let conn = open(url)?;
let conn = conn_for(url, txn_id)?;
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
let sql = format!("DELETE FROM \"{table}\" WHERE \"id\" = ?1");
let n = conn
let n = c
.execute(&sql, rusqlite::params![id])
.map_err(|e| e.to_string())?;
Ok(json!({ "ok": true, "deleted": n }))
}
pub fn exec(url: &str, sql: &str, args: Option<&Value>) -> Result<Value, String> {
let conn = open(url)?;
pub fn exec(url: &str, sql: &str, args: Option<&Value>, txn_id: Option<&str>) -> Result<Value, String> {
let conn = conn_for(url, txn_id)?;
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
let vals: Vec<rusqlite::types::Value> = match args {
Some(Value::Array(a)) => a.iter().map(to_sql).collect(),
_ => Vec::new(),
};
let n = conn
let n = c
.execute(sql, params_from_iter(vals.iter().cloned()))
.map_err(|e| e.to_string())?;
Ok(json!({ "ok": true, "changes": n }))
}
/// Run a `SELECT …` and return the result set (count / join / group / subquery).
/// Bare SQL — the result carries `{ rows, count }`.
pub fn query(url: &str, sql: &str, args: Option<&Value>, txn_id: Option<&str>) -> Result<Value, String> {
let conn = conn_for(url, txn_id)?;
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
let vals: Vec<rusqlite::types::Value> = match args {
Some(Value::Array(a)) => a.iter().map(to_sql).collect(),
_ => Vec::new(),
};
let rows = query_rows(&c, sql, &vals)?;
Ok(json!({ "rows": rows, "count": rows.len() }))
}
/// Count rows matching a `where` filter (aggregation helper).
pub fn count(url: &str, table: &str, where_v: Option<&Value>, txn_id: Option<&str>) -> Result<Value, String> {
let table = ident(table)?;
let (exprs, vals) = parse_where(where_v)?;
let conn = conn_for(url, txn_id)?;
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
let mut sql = format!("SELECT COUNT(*) FROM \"{table}\"");
if !exprs.is_empty() {
sql.push_str(&format!(" WHERE {}", exprs.join(" AND ")));
}
let n = count_rows(&c, &sql, &vals)?;
Ok(json!({ "count": n }))
}
/// Begin a transaction. Borrows the pooled connection exclusively and records
/// it under a fresh txn id; returns `{ txn, url }` for `commit` / `rollback`.
pub fn begin(url: &str) -> Result<Value, String> {
let conn = pooled(url)?;
{
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
c.execute_batch("BEGIN IMMEDIATE").map_err(|e| e.to_string())?;
}
let id = next_txn_id();
{
let mut guard = TXNS.lock().unwrap_or_else(|e| e.into_inner());
guard
.get_or_insert_with(HashMap::new)
.insert(id.clone(), (url.to_string(), conn));
}
Ok(json!({ "_type": "txn", "txn": id, "url": url, "事务": id, "地址": url }))
}
/// Commit a transaction and return its connection to the pool.
pub fn commit(txn_id: &str) -> Result<Value, String> {
let (_, conn) = take_txn(txn_id)?;
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
c.execute_batch("COMMIT").map_err(|e| e.to_string())?;
Ok(json!({ "ok": true }))
}
/// Roll back a transaction and return its connection to the pool.
pub fn rollback(txn_id: &str) -> Result<Value, String> {
let (_, conn) = take_txn(txn_id)?;
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
c.execute_batch("ROLLBACK").map_err(|e| e.to_string())?;
Ok(json!({ "ok": true }))
}
/// Remove a txn from the registry, returning its connection for reuse.
fn take_txn(txn_id: &str) -> Result<(String, Arc<Mutex<Connection>>), String> {
let mut guard = TXNS.lock().unwrap_or_else(|e| e.into_inner());
guard
.as_mut()
.and_then(|m| m.remove(txn_id))
.ok_or_else(|| format!("unknown transaction `{txn_id}`"))
}
pub fn list_tables(url: &str) -> Result<Vec<String>, String> {
let conn = open(url)?;
let mut stmt = conn
let conn = pooled(url)?;
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
let mut stmt = c
.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_marqdo%' ORDER BY name",
)
@@ -434,9 +761,10 @@ pub struct ColumnInfo {
/// `PRAGMA table_info` → column metadata for admin forms.
pub fn table_info(url: &str, table: &str) -> Result<Vec<ColumnInfo>, String> {
let table = ident(table)?;
let conn = open(url)?;
let conn = pooled(url)?;
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
let sql = format!("PRAGMA table_info(\"{table}\")");
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
let mut stmt = c.prepare(&sql).map_err(|e| e.to_string())?;
let rows = stmt
.query_map([], |r| {
Ok(ColumnInfo {
+17 -4
View File
@@ -429,6 +429,7 @@ pub fn render_body(
form_id: &str,
data: Option<&Value>,
errors: Option<&Value>,
csrf: Option<&str>,
) -> String {
let fields = form
.get("fields")
@@ -490,6 +491,12 @@ pub fn render_body(
"<form method=\"post\" action=\"{}\">",
esc(&post_to)
));
if let Some(token) = csrf.filter(|s| !s.is_empty()) {
body.push_str(&format!(
"<input type=\"hidden\" name=\"_csrf\" value=\"{}\"/>",
esc(token)
));
}
if action == "update" && !row_id.is_empty() {
body.push_str(&format!(
"<input type=\"hidden\" name=\"id\" value=\"{}\"/>",
@@ -569,7 +576,13 @@ pub fn render_body(
}
/// Standalone form document (`GET|POST /_form/{id}`).
pub fn render(form: &Value, form_id: &str, data: Option<&Value>, errors: Option<&Value>) -> String {
pub fn render(
form: &Value,
form_id: &str,
data: Option<&Value>,
errors: Option<&Value>,
csrf: Option<&str>,
) -> String {
let heading = form
.get("title")
.and_then(|v| v.as_str())
@@ -593,7 +606,7 @@ body{font-family:"IBM Plex Sans","Noto Sans SC",sans-serif;margin:1.5rem;backgro
</style></head><body>"#,
);
body.push_str(&format!("<h1>{}</h1>", esc(heading)));
body.push_str(&render_body(form, form_id, data, errors));
body.push_str(&render_body(form, form_id, data, errors, csrf));
body.push_str("</body></html>");
body
}
@@ -631,9 +644,9 @@ pub fn submit(form: &Value, data: &Value, db_url: &str) -> Result<Value, String>
.filter(|s| !s.is_empty())
.or_else(|| data_map(&data).get("id").map(cell_str))
.ok_or_else(|| "update requires `id`".to_string())?;
db::update(db_url, table, &id, &row)?
db::update(db_url, table, &id, &row, None)?
} else {
db::insert(db_url, table, &json!([row]))?
db::insert(db_url, table, &json!([row]), None)?
};
let redirect = form
.get("redirect")
+208 -73
View File
@@ -16,13 +16,15 @@ use tower_http::services::ServeDir;
use crate::db;
use crate::form;
use crate::middleware::Middleware;
use crate::rate_limit;
use crate::render;
use crate::session;
#[derive(Clone)]
struct AppState {
pub struct AppState {
page: Value,
db_url: Option<String>,
pub db_url: Option<String>,
admin: bool,
forms: HashMap<String, Value>,
/// Page that owns an embedded form (for re-render on validation errors).
@@ -30,6 +32,7 @@ struct AppState {
/// Admin users table (`|用户名|密码|`) when login-gated admin is configured.
auth_users: Option<Value>,
session_ttl: u64,
cookie_secure: bool,
}
fn collect_page_forms(
@@ -66,14 +69,22 @@ pub fn listen(
static_mount: &str,
auth_users: Option<Value>,
session_ttl: u64,
cookie_secure: bool,
ws_routes: HashMap<String, bool>,
middleware: &Middleware,
) -> Result<Value, String> {
let mut form_owners = HashMap::new();
collect_page_forms(page, &mut forms, &mut form_owners);
for p in routes.values() {
collect_page_forms(p, &mut forms, &mut form_owners);
}
session::configure(session::Config {
db_url: db_url.map(|s| s.to_string()),
ttl_sec: session_ttl,
cookie_secure,
});
session::reset(session_ttl);
rate_limit::reset();
let state = Arc::new(AppState {
page: page.clone(),
db_url: db_url.map(|s| s.to_string()),
@@ -82,6 +93,7 @@ pub fn listen(
form_owners,
auth_users,
session_ttl,
cookie_secure,
});
let mut app = Router::new()
@@ -111,10 +123,13 @@ pub fn listen(
let page_for_render = page.clone();
app = app.route(
&path,
get(async move |State(st): State<Arc<AppState>>, Path(params): Path<HashMap<String, String>>| {
get(async move |State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap, Path(params): Path<HashMap<String, String>>| {
let mut p = page_for_render.clone();
inject_params(&mut p, &params);
Html(render::render_page(&p, st.db_url.as_deref())).into_response()
let (_, csrf, set_cookie) = resolve_session(&headers);
let mut resp = Html(render::render_page(&p, st.db_url.as_deref(), Some(&csrf))).into_response();
append_set_cookie(&mut resp, set_cookie);
resp
}),
);
// Dynamic `{path}/_part/{id}` with the same path params.
@@ -132,9 +147,12 @@ pub fn listen(
let page_for_render = page.clone();
app = app.route(
&path,
get(async move |State(st): State<Arc<AppState>>| {
Html(render::render_page(&page_for_render, st.db_url.as_deref()))
.into_response()
get(async move |State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap| {
let (_, csrf, set_cookie) = resolve_session(&headers);
let mut resp = Html(render::render_page(&page_for_render, st.db_url.as_deref(), Some(&csrf)))
.into_response();
append_set_cookie(&mut resp, set_cookie);
resp
}),
);
let part_path = format!("{path}/_part/{{id}}");
@@ -178,6 +196,7 @@ pub fn listen(
app = app.nest_service(&mount, svc);
}
let app = crate::middleware::apply(app, middleware);
let app = app.with_state(state);
let addr: SocketAddr = format!("{host}:{port}")
@@ -213,9 +232,12 @@ pub fn normalize_static_mount(raw: &str) -> String {
m
}
async fn home(State(st): State<Arc<AppState>>) -> Html<String> {
let html = render::render_page(&st.page, st.db_url.as_deref());
Html(html)
async fn home(State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap) -> Response {
let (_, csrf, set_cookie) = resolve_session(&headers);
let html = render::render_page(&st.page, st.db_url.as_deref(), Some(&csrf));
let mut resp = Html(html).into_response();
append_set_cookie(&mut resp, set_cookie);
resp
}
/// Inject captured dynamic-route params into a page copy as `params` (a map),
@@ -256,15 +278,23 @@ async fn home_part(State(st): State<Arc<AppState>>, Path(id): Path<String>) -> R
render_part_from_page(&st.page, &id, st.db_url.as_deref())
}
async fn form_get(State(st): State<Arc<AppState>>, Path(id): Path<String>) -> Response {
async fn form_get(
State(st): State<Arc<AppState>>,
headers: axum::http::HeaderMap,
Path(id): Path<String>,
) -> Response {
let Some(frm) = st.forms.get(&id) else {
return Html(format!("<p>unknown form {id}</p>")).into_response();
};
Html(form::render(frm, &id, None, None)).into_response()
let (_, csrf, set_cookie) = resolve_session(&headers);
let mut resp = Html(form::render(frm, &id, None, None, Some(&csrf))).into_response();
append_set_cookie(&mut resp, set_cookie);
resp
}
async fn form_post(
State(st): State<Arc<AppState>>,
headers: axum::http::HeaderMap,
Path(id): Path<String>,
Form(posted): Form<HashMap<String, String>>,
) -> Response {
@@ -274,7 +304,13 @@ async fn form_post(
let Some(url) = st.db_url.as_deref() else {
return Html(String::from("<p>no database</p>")).into_response();
};
submit_and_respond(&st, frm, &id, url, posted, None)
let (_, csrf, set_cookie, posted) = match validate_csrf_post(&headers, posted) {
Ok(v) => v,
Err(r) => return r,
};
let mut resp = submit_and_respond(&st, frm, &id, url, posted, None, Some(&csrf));
append_set_cookie(&mut resp, set_cookie);
resp
}
fn posted_to_value(posted: HashMap<String, String>) -> Value {
@@ -300,6 +336,7 @@ fn submit_and_respond(
url: &str,
posted: HashMap<String, String>,
admin_table: Option<&str>,
csrf: Option<&str>,
) -> Response {
let data_v = posted_to_value(posted);
match form::submit(frm, &data_v, url) {
@@ -331,6 +368,7 @@ fn submit_and_respond(
form_id,
Some(&data_v),
errors,
csrf,
))
.into_response()
} else if let Some(page) = st.form_owners.get(form_id) {
@@ -339,10 +377,11 @@ fn submit_and_respond(
st.db_url.as_deref(),
Some(&data_v),
errors,
csrf,
))
.into_response()
} else {
Html(form::render(frm, form_id, Some(&data_v), errors)).into_response()
Html(form::render(frm, form_id, Some(&data_v), errors, csrf)).into_response()
}
}
Err(e) => Html(format!("<p>submit error: {}</p>", esc(&e))).into_response(),
@@ -355,6 +394,50 @@ fn cookie_from_headers(headers: &axum::http::HeaderMap) -> Option<&str> {
.and_then(|v| v.to_str().ok())
}
fn client_ip(headers: &axum::http::HeaderMap) -> String {
headers
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.split(',').next())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "127.0.0.1".into())
}
fn resolve_session(headers: &axum::http::HeaderMap) -> (String, String, Option<String>) {
let cookie = cookie_from_headers(headers);
let (id, set_cookie) = session::ensure_from_cookie(cookie);
let csrf = session::csrf_for(&id).unwrap_or_default();
(id, csrf, set_cookie)
}
fn append_set_cookie(resp: &mut Response, set_cookie: Option<String>) {
if let Some(c) = set_cookie {
let _ = resp.headers_mut().try_append(
axum::http::header::SET_COOKIE,
c.parse().unwrap(),
);
}
}
fn validate_csrf_post(
headers: &axum::http::HeaderMap,
posted: HashMap<String, String>,
) -> Result<(String, String, Option<String>, HashMap<String, String>), Response> {
let (sid, csrf, set_cookie) = resolve_session(headers);
let token = posted.get("_csrf").map(|s| s.as_str()).unwrap_or("");
if !session::validate_csrf(&sid, token) {
return Err(Html(
"<p class=\"flash err\">Invalid or missing CSRF token. Refresh and try again.</p>"
.to_string(),
)
.into_response());
}
let mut posted = posted;
posted.remove("_csrf");
Ok((sid, csrf, set_cookie, posted))
}
fn admin_gate(st: &AppState, cookie_header: Option<&str>) -> Option<Response> {
if !st.admin {
return Some(Html(admin_shell(st, "Admin", None, "<p class=\"flash err\">Admin is disabled for this app.</p>")).into_response());
@@ -380,51 +463,70 @@ fn admin_authed(_st: &AppState, cookie_header: Option<&str>) -> bool {
session::session_get(&sid, "username").is_some()
}
#[derive(Deserialize)]
struct LoginForm {
username: Option<String>,
password: Option<String>,
}
async fn admin_login_get(State(st): State<Arc<AppState>>) -> Response {
// Already logged in → straight to admin home.
async fn admin_login_get(State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap) -> Response {
if st.auth_users.is_none() {
return Redirect::to("/admin").into_response();
}
Html(login_page(&st, None)).into_response()
if admin_authed(&st, cookie_from_headers(&headers)) {
return Redirect::to("/admin").into_response();
}
let (_, csrf, set_cookie) = resolve_session(&headers);
let mut resp = Html(login_page(&st, None, Some(&csrf))).into_response();
append_set_cookie(&mut resp, set_cookie);
resp
}
async fn admin_login_post(
State(st): State<Arc<AppState>>,
Form(posted): Form<LoginForm>,
headers: axum::http::HeaderMap,
Form(posted): Form<HashMap<String, String>>,
) -> Response {
let Some(users) = &st.auth_users else {
return Redirect::to("/admin").into_response();
};
let username = posted.username.unwrap_or_default();
let password = posted.password.unwrap_or_default();
if session::check_credentials(users, &username, &password).is_none() {
return Html(login_page(&st, Some("Invalid username or password."))).into_response();
let (_, csrf, set_cookie, posted) = match validate_csrf_post(&headers, posted) {
Ok(v) => v,
Err(r) => return r,
};
let username = posted.get("username").cloned().unwrap_or_default();
let password = posted.get("password").cloned().unwrap_or_default();
let ip = client_ip(&headers);
if let Err(msg) = rate_limit::check(&ip, &username) {
let mut resp = Html(login_page(&st, Some(&msg), Some(&csrf))).into_response();
append_set_cookie(&mut resp, set_cookie);
return resp;
}
if session::check_credentials(users, &username, &password).is_none() {
rate_limit::record_failure(&ip, &username);
let mut resp =
Html(login_page(&st, Some("Invalid username or password."), Some(&csrf)))
.into_response();
append_set_cookie(&mut resp, set_cookie);
return resp;
}
rate_limit::clear_success(&ip, &username);
let sid = session::session_new(Some(st.session_ttl));
session::session_set(&sid, "username", json!(username));
let mut resp = Redirect::to("/admin").into_response();
if let Ok(h) = resp.headers_mut().try_append(
let _ = resp.headers_mut().try_append(
axum::http::header::SET_COOKIE,
session::session_cookie(&sid, st.session_ttl)
session::session_cookie(&sid, st.session_ttl, st.cookie_secure)
.parse()
.unwrap(),
) {
let _ = h;
}
);
append_set_cookie(&mut resp, set_cookie);
resp
}
fn login_page(_st: &AppState, error: Option<&str>) -> String {
fn login_page(_st: &AppState, error: Option<&str>, csrf: Option<&str>) -> String {
let err = match error {
Some(e) => format!("<p class=\"flash err\">{}</p>", esc(e)),
None => String::new(),
};
let csrf_field = csrf
.filter(|s| !s.is_empty())
.map(|t| format!("<input type=\"hidden\" name=\"_csrf\" value=\"{}\"/>", esc(t)))
.unwrap_or_default();
format!(
r#"<!DOCTYPE html>
<html lang="zh-CN"><head>
@@ -452,6 +554,7 @@ body {{ margin:0; min-height:100vh; display:grid; place-items:center; background
<p class="sub">Sign in to manage this site.</p>
{err}
<form method="post" action="/admin/login">
{csrf_field}
<label>Username<input name="username" autocomplete="username" required autofocus/></label>
<label>Password<input name="password" type="password" autocomplete="current-password" required/></label>
<button type="submit">Sign in</button>
@@ -459,6 +562,7 @@ body {{ margin:0; min-height:100vh; display:grid; place-items:center; background
</div>
</body></html>"#,
err = err,
csrf_field = csrf_field,
)
}
@@ -616,13 +720,14 @@ fn admin_form_page(
form_id: &str,
data: Option<&Value>,
errors: Option<&Value>,
csrf: Option<&str>,
) -> String {
let mut body = format!(
"<p class=\"crumbs\"><a href=\"/admin\">Admin</a> / <a href=\"/admin/{t}\">{t}</a> / {kind}</p><h1>{kind} {t}</h1>",
t = esc(table),
kind = esc(kind),
);
body.push_str(&form::render_body(frm, form_id, data, errors));
body.push_str(&form::render_body(frm, form_id, data, errors, csrf));
admin_shell(st, &format!("{kind} {table}"), Some(table), &body)
}
@@ -767,17 +872,23 @@ async fn admin_new_get(
return r;
}
let url = st.db_url.as_deref().unwrap();
let (_, csrf, set_cookie) = resolve_session(&headers);
match form::from_schema(url, &table, "insert", None) {
Ok(frm) => Html(admin_form_page(
&st,
&table,
"New",
&frm,
&format!("admin-{table}-new"),
None,
None,
))
.into_response(),
Ok(frm) => {
let mut resp = Html(admin_form_page(
&st,
&table,
"New",
&frm,
&format!("admin-{table}-new"),
None,
None,
Some(&csrf),
))
.into_response();
append_set_cookie(&mut resp, set_cookie);
resp
}
Err(e) => Html(admin_shell(
&st,
&table,
@@ -798,15 +909,24 @@ async fn admin_new_post(
return r;
}
let url = st.db_url.as_deref().unwrap();
let (_, csrf, set_cookie, posted) = match validate_csrf_post(&headers, posted) {
Ok(v) => v,
Err(r) => return r,
};
match form::from_schema(url, &table, "insert", None) {
Ok(frm) => submit_and_respond(
&st,
&frm,
&format!("admin-{table}-new"),
url,
posted,
Some(&table),
),
Ok(frm) => {
let mut resp = submit_and_respond(
&st,
&frm,
&format!("admin-{table}-new"),
url,
posted,
Some(&table),
Some(&csrf),
);
append_set_cookie(&mut resp, set_cookie);
resp
}
Err(e) => Html(admin_shell(
&st,
&table,
@@ -826,7 +946,7 @@ async fn admin_edit_get(
return r;
}
let url = st.db_url.as_deref().unwrap();
let row = match db::get(url, &table, &id) {
let row = match db::get(url, &table, &id, None) {
Ok(Value::Null) => {
return Html(admin_shell(
&st,
@@ -847,17 +967,23 @@ async fn admin_edit_get(
.into_response();
}
};
let (_, csrf, set_cookie) = resolve_session(&headers);
match form::from_schema(url, &table, "update", Some(&id)) {
Ok(frm) => Html(admin_form_page(
&st,
&table,
"Edit",
&frm,
&format!("admin-{table}-edit"),
Some(&row),
None,
))
.into_response(),
Ok(frm) => {
let mut resp = Html(admin_form_page(
&st,
&table,
"Edit",
&frm,
&format!("admin-{table}-edit"),
Some(&row),
None,
Some(&csrf),
))
.into_response();
append_set_cookie(&mut resp, set_cookie);
resp
}
Err(e) => Html(admin_shell(
&st,
&table,
@@ -878,15 +1004,24 @@ async fn admin_edit_post(
return r;
}
let url = st.db_url.as_deref().unwrap();
let (_, csrf, set_cookie, posted) = match validate_csrf_post(&headers, posted) {
Ok(v) => v,
Err(r) => return r,
};
match form::from_schema(url, &table, "update", Some(&id)) {
Ok(frm) => submit_and_respond(
&st,
&frm,
&format!("admin-{table}-edit"),
url,
posted,
Some(&table),
),
Ok(frm) => {
let mut resp = submit_and_respond(
&st,
&frm,
&format!("admin-{table}-edit"),
url,
posted,
Some(&table),
Some(&csrf),
);
append_set_cookie(&mut resp, set_cookie);
resp
}
Err(e) => Html(admin_shell(
&st,
&table,
@@ -906,7 +1041,7 @@ async fn admin_delete(
return r;
}
let url = st.db_url.as_deref().unwrap();
if let Err(e) = db::delete(url, &table, &id) {
if let Err(e) = db::delete(url, &table, &id, None) {
return Html(admin_shell(
&st,
&table,
+165 -17
View File
@@ -4,6 +4,9 @@ mod compose;
mod db;
mod form;
mod http;
mod middleware;
mod password;
mod rate_limit;
mod render;
mod session;
mod table;
@@ -355,7 +358,7 @@ web_ffi!(web_compose_form, |args: &Value| {
web_ffi!(web_render, |args: &Value| {
let page = args.get("page").cloned().unwrap_or_else(|| args.clone());
let db_url = db_url_of(args).ok();
let html = render::render_page(&page, db_url.as_deref());
let html = render::render_page(&page, db_url.as_deref(), None);
Ok(Value::String(html))
});
@@ -381,7 +384,8 @@ web_ffi!(web_db_insert, |args: &Value| {
.or_else(|| args.get("row"))
.cloned()
.unwrap_or(json!([]));
db::insert(&url, &table, &rows)
let txn = args.get("txn").and_then(|v| v.as_str());
db::insert(&url, &table, &rows, txn)
});
web_ffi!(web_db_select, |args: &Value| {
@@ -403,18 +407,51 @@ web_ffi!(web_db_select, |args: &Value| {
Some(v) => Some(v),
};
let order = args.get("order").and_then(|v| v.as_str());
if order.is_some_and(|s| !s.trim().is_empty()) {
db::select_order(&url, &table, limit, where_v, order)
} else {
db::select(&url, &table, limit, where_v)
}
let offset = args
.get("offset")
.or_else(|| args.get("跳过"))
.and_then(|v| v.as_i64());
let txn = args.get("txn").and_then(|v| v.as_str());
db::select_order(&url, &table, limit, where_v, order, offset, txn)
});
web_ffi!(web_db_query, |args: &Value| {
let url = db_url_of(args)?;
let sql = arg_str(args, "sql")?.to_string();
let args_v = args.get("args");
let txn = args.get("txn").and_then(|v| v.as_str());
db::query(&url, &sql, args_v, txn)
});
web_ffi!(web_db_count, |args: &Value| {
let url = db_url_of(args)?;
let table = arg_str(args, "table")?.to_string();
let where_v = args.get("where").filter(|v| !v.is_null());
let txn = args.get("txn").and_then(|v| v.as_str());
db::count(&url, &table, where_v, txn)
});
web_ffi!(web_db_begin, |args: &Value| {
let url = db_url_of(args)?;
db::begin(&url)
});
web_ffi!(web_db_commit, |args: &Value| {
let txn = arg_str(args, "txn")?.to_string();
db::commit(&txn)
});
web_ffi!(web_db_rollback, |args: &Value| {
let txn = arg_str(args, "txn")?.to_string();
db::rollback(&txn)
});
web_ffi!(web_db_get, |args: &Value| {
let url = db_url_of(args)?;
let table = arg_str(args, "table")?.to_string();
let id = arg_text(args, "id")?;
db::get(&url, &table, &id)
let txn = args.get("txn").and_then(|v| v.as_str());
db::get(&url, &table, &id, txn)
});
web_ffi!(web_db_update, |args: &Value| {
@@ -422,21 +459,24 @@ web_ffi!(web_db_update, |args: &Value| {
let table = arg_str(args, "table")?.to_string();
let id = arg_text(args, "id")?;
let row = args.get("row").cloned().unwrap_or(json!({}));
db::update(&url, &table, &id, &row)
let txn = args.get("txn").and_then(|v| v.as_str());
db::update(&url, &table, &id, &row, txn)
});
web_ffi!(web_db_delete, |args: &Value| {
let url = db_url_of(args)?;
let table = arg_str(args, "table")?.to_string();
let id = arg_text(args, "id")?;
db::delete(&url, &table, &id)
let txn = args.get("txn").and_then(|v| v.as_str());
db::delete(&url, &table, &id, txn)
});
web_ffi!(web_db_exec, |args: &Value| {
let url = db_url_of(args)?;
let sql = arg_str(args, "sql")?.to_string();
let args_v = args.get("args");
db::exec(&url, &sql, args_v)
let txn = args.get("txn").and_then(|v| v.as_str());
db::exec(&url, &sql, args_v, txn)
});
web_ffi!(web_db_list_tables, |args: &Value| {
@@ -597,6 +637,10 @@ web_ffi!(web_auth_logout, |args: &Value| {
session::abi_auth_logout(args)
});
web_ffi!(web_password_hash, |args: &Value| {
session::abi_password_hash(args)
});
web_ffi!(web_auth_new, |args: &Value| {
let users = args.get("users").cloned().unwrap_or(Value::Null);
let session_ttl = args
@@ -667,6 +711,69 @@ web_ffi!(web_app_static, |args: &Value| {
Ok(app)
});
// Configure cross-cutting HTTP middleware on an app: CORS, security response
// headers, gzip compression, request-body limits, and JSON API routes.
//
// Every capability is passed in as *data* (GFM tables from the Marqdo side,
// normalized here into the `middleware` map): 配置即数据、装配即函数.
//
// - `cors` : `|允许来源|方法|头|暴露头|凭证|` table (one row per origin).
// - `security` : `|头|值|` table of response headers (e.g. `X-Frame-Options`).
// - `compress` : bool — enable gzip response compression.
// - `body_limit` : number — max request body bytes (e.g. `1048576`).
// - `json_routes`: `|路径|方法|表|条件|排序|上限|` table of JSON API endpoints
// backed by db queries (method GET/POST, `表`=table name).
web_ffi!(web_app_middleware, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let obj = app
.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?;
let mw = obj
.entry("middleware".to_string())
.or_insert_with(|| json!({}));
let m = mw
.as_object_mut()
.ok_or_else(|| "app.middleware must be a map".to_string())?;
if let Some(cors) = args.get("cors") {
m.insert(
"cors".into(),
middleware::cors_from_table(cors),
);
}
if let Some(security) = args.get("security") {
m.insert(
"security".into(),
middleware::security_from_table(security),
);
}
if let Some(compress) = args.get("compress") {
let on = match compress {
Value::Bool(b) => *b,
Value::String(s) => matches!(s.as_str(), "true" | "True" | "1" | "yes" | "on"),
Value::Number(n) => n.as_i64().unwrap_or(0) != 0,
_ => false,
};
m.insert("compress".into(), json!(on));
}
if let Some(bl) = args.get("body_limit") {
let n = bl
.as_u64()
.or_else(|| bl.as_i64().map(|i| i as u64))
.unwrap_or(0);
if n > 0 {
m.insert("body_limit".into(), json!(n));
}
}
if let Some(routes) = args.get("json_routes") {
m.insert(
"json_routes".into(),
middleware::json_routes_from_table(routes),
);
}
Ok(app)
});
web_ffi!(web_form_new, |args: &Value| {
let table = arg_str_opt(args, "table");
let action = arg_str_opt(args, "action").unwrap_or("insert");
@@ -712,6 +819,7 @@ web_ffi!(web_form_render, |args: &Value| {
id,
data,
errors,
arg_str_opt(args, "csrf"),
)))
});
@@ -770,6 +878,8 @@ web_ffi!(web_listen, |args: &Value| {
auth_users,
session_ttl,
ws_routes,
middleware,
cookie_secure,
) = if args.get("page").is_some() || args.get("host").is_some() {
let page = args.get("page").cloned().unwrap_or(json!({}));
let db_url = db_url_of(args).ok();
@@ -795,6 +905,10 @@ web_ffi!(web_listen, |args: &Value| {
.get("session_ttl")
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
.unwrap_or(3600);
let cookie_secure = args
.get("cookie_secure")
.and_then(|v| v.as_bool())
.unwrap_or(false);
(
page,
db_url,
@@ -808,6 +922,8 @@ web_ffi!(web_listen, |args: &Value| {
auth_users,
session_ttl,
HashMap::new(),
middleware::Middleware::default(),
cookie_secure,
)
} else {
let app = args.get("app").cloned().unwrap_or_else(|| args.clone());
@@ -887,6 +1003,15 @@ web_ffi!(web_listen, |args: &Value| {
.unwrap_or(3600),
),
};
let middleware = middleware::parse(&app);
let mw_summary = middleware::summary(&app);
if !mw_summary.is_empty() {
eprintln!("marqdo web middleware: {mw_summary}");
}
let cookie_secure = app
.get("cookie_secure")
.and_then(|v| v.as_bool())
.unwrap_or(false);
(
page,
db_url,
@@ -900,6 +1025,8 @@ web_ffi!(web_listen, |args: &Value| {
auth_users,
session_ttl,
ws_routes,
middleware,
cookie_secure,
)
};
let static_dir = static_dir.map(|p| {
@@ -921,7 +1048,9 @@ web_ffi!(web_listen, |args: &Value| {
&static_mount,
auth_users,
session_ttl,
cookie_secure,
ws_routes,
&middleware,
)
});
@@ -1003,16 +1132,29 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
("web_render", "page", web_render as PluginFn),
("web_db_new", "url", web_db_new as PluginFn),
("web_db_init", "url,name,fields", web_db_init as PluginFn),
("web_db_insert", "url,table,rows", web_db_insert as PluginFn),
("web_db_insert", "url,table,rows,txn", web_db_insert as PluginFn),
(
"web_db_select",
"url,table,where,limit,order",
"url,table,where,limit,order,offset,txn",
web_db_select as PluginFn,
),
("web_db_get", "url,table,id", web_db_get as PluginFn),
("web_db_update", "url,table,id,row", web_db_update as PluginFn),
("web_db_delete", "url,table,id", web_db_delete as PluginFn),
("web_db_exec", "url,sql,args", web_db_exec as PluginFn),
(
"web_db_query",
"url,sql,args,txn",
web_db_query as PluginFn,
),
(
"web_db_count",
"url,table,where,txn",
web_db_count as PluginFn,
),
("web_db_begin", "url", web_db_begin as PluginFn),
("web_db_commit", "txn", web_db_commit as PluginFn),
("web_db_rollback", "txn", web_db_rollback as PluginFn),
("web_db_get", "url,table,id,txn", web_db_get as PluginFn),
("web_db_update", "url,table,id,row,txn", web_db_update as PluginFn),
("web_db_delete", "url,table,id,txn", web_db_delete as PluginFn),
("web_db_exec", "url,sql,args,txn", web_db_exec as PluginFn),
("web_db_list_tables", "url", web_db_list_tables as PluginFn),
(
"web_app_new",
@@ -1030,6 +1172,11 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
"app,dir,mount",
web_app_static as PluginFn,
),
(
"web_app_middleware",
"app,cors,security,compress,body_limit,json_routes",
web_app_middleware as PluginFn,
),
("web_form_new", "table,action,id", web_form_new as PluginFn),
("web_form_fields", "form,fields", web_form_fields as PluginFn),
("web_form_rules", "form,rules", web_form_rules as PluginFn),
@@ -1058,6 +1205,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
),
("web_auth_check", "session_id", web_auth_check as PluginFn),
("web_auth_logout", "session_id", web_auth_logout as PluginFn),
("web_password_hash", "password", web_password_hash as PluginFn),
("web_auth_new", "users,session_ttl", web_auth_new as PluginFn),
("web_app_auth", "app,users,session_ttl", web_app_auth as PluginFn),
(
+438
View File
@@ -0,0 +1,438 @@
//! Declarative middleware for the web app.
//!
//! All cross-cutting HTTP capabilities (CORS, security headers, compression,
//! body limits, JSON API routes) are configured as *data* on the `app` object
//! and applied to the axum router here. This keeps the authoring surface
//! declarative: a GFM table in Marqdo becomes a `middleware` map, and this
//! module turns it into axum layers — 配置即数据、装配即函数.
use std::sync::Arc;
use axum::body::Body;
use axum::extract::State;
use axum::http::{header, HeaderValue, Method, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::Router;
use serde_json::{json, Map, Value};
use tower_http::compression::CompressionLayer;
use tower_http::cors::{Any, CorsLayer};
use tower_http::limit::RequestBodyLimitLayer;
use tower_http::set_header::SetResponseHeaderLayer;
use crate::db;
/// Render a cell value as text (strings stay, numbers/bools stringify).
fn cell_text(v: &Value) -> String {
match v {
Value::Null => String::new(),
Value::String(s) => s.clone(),
Value::Bool(b) => b.to_string(),
Value::Number(n) => n.to_string(),
other => other.to_string(),
}
}
/// Parsed middleware configuration (from `app["middleware"]`).
#[derive(Clone, Default)]
pub struct Middleware {
pub cors: Option<CorsConfig>,
pub security: Vec<(String, String)>,
pub compress: bool,
pub body_limit: Option<u64>,
/// JSON API routes: `path -> { method, table, where?, order?, limit? }`.
pub json_routes: Vec<(String, JsonRoute)>,
}
#[derive(Clone)]
pub struct CorsConfig {
pub allow_origins: Vec<String>,
pub methods: Vec<String>,
pub headers: Vec<String>,
pub expose_headers: Vec<String>,
pub credentials: bool,
}
#[derive(Clone)]
pub struct JsonRoute {
pub method: String,
pub table: String,
pub where_v: Option<Value>,
pub order: Option<String>,
pub limit: i64,
}
/// Parse `app["middleware"]` (a map) into a `Middleware`.
pub fn parse(app: &Value) -> Middleware {
let mut mw = Middleware::default();
let Some(obj) = app.get("middleware").and_then(|v| v.as_object()) else {
return mw;
};
if let Some(c) = obj.get("cors") {
mw.cors = parse_cors(c);
}
if let Some(sec) = obj.get("security").and_then(|v| v.as_object()) {
mw.security = sec
.iter()
.map(|(k, v)| (k.clone(), v.as_str().unwrap_or("").to_string()))
.filter(|(_, v)| !v.is_empty())
.collect();
}
mw.compress = obj
.get("compress")
.and_then(|v| v.as_bool())
.unwrap_or(false);
mw.body_limit = obj
.get("body_limit")
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
.filter(|n| *n > 0);
if let Some(routes) = obj.get("json_routes").and_then(|v| v.as_object()) {
for (path, spec) in routes {
if let Some(route) = parse_json_route(path, spec) {
mw.json_routes.push(route);
}
}
mw.json_routes.sort_by(|a, b| a.0.cmp(&b.0));
}
mw
}
fn parse_cors(v: &Value) -> Option<CorsConfig> {
let obj = v.as_object()?;
let str_list = |key: &str| -> Vec<String> {
obj.get(key)
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|x| x.as_str().map(|s| s.to_string()))
.collect()
})
.unwrap_or_default()
};
Some(CorsConfig {
allow_origins: str_list("allow_origins"),
methods: str_list("methods"),
headers: str_list("headers"),
expose_headers: str_list("expose_headers"),
credentials: obj
.get("credentials")
.and_then(|v| v.as_bool())
.unwrap_or(false),
})
}
fn parse_json_route(path: &str, spec: &Value) -> Option<(String, JsonRoute)> {
let spec = spec.as_object()?;
let method = spec
.get("method")
.and_then(|v| v.as_str())
.unwrap_or("GET")
.to_uppercase();
let table = spec.get("table")?.as_str()?.to_string();
let order = spec.get("order").and_then(|v| v.as_str()).map(|s| s.to_string());
let limit = spec
.get("limit")
.and_then(|v| v.as_i64())
.unwrap_or(200);
Some((
format!("/{}", path.trim_start_matches('/')),
JsonRoute {
method,
table,
where_v: spec.get("where").cloned(),
order,
limit,
},
))
}
/// Apply the middleware configuration to a router (state already provided).
pub fn apply(
router: Router<Arc<crate::http::AppState>>,
mw: &Middleware,
) -> Router<Arc<crate::http::AppState>> {
let mut app = router;
// JSON API routes first: axum layers only wrap routes registered before
// the `.layer()` call, so these must be mounted ahead of the pipeline.
for (path, route) in &mw.json_routes {
app = mount_json(app, path, route.clone());
}
// CORS
if let Some(c) = &mw.cors {
let mut layer = CorsLayer::new();
if c.allow_origins.is_empty() {
layer = layer.allow_origin(Any);
} else {
layer = layer.allow_origin(
c.allow_origins
.iter()
.filter_map(|o| o.parse::<HeaderValue>().ok())
.collect::<Vec<_>>(),
);
}
if c.methods.is_empty() {
layer = layer.allow_methods(Any);
} else {
layer = layer.allow_methods(
c.methods
.iter()
.filter_map(|m| m.parse::<Method>().ok())
.collect::<Vec<_>>(),
);
}
if c.headers.is_empty() {
layer = layer.allow_headers(Any);
} else {
layer = layer.allow_headers(
c.headers
.iter()
.filter_map(|h| h.parse::<axum::http::HeaderName>().ok())
.collect::<Vec<_>>(),
);
}
if !c.expose_headers.is_empty() {
layer = layer.expose_headers(
c.expose_headers
.iter()
.filter_map(|h| h.parse::<axum::http::HeaderName>().ok())
.collect::<Vec<_>>(),
);
}
layer = layer.allow_credentials(c.credentials);
app = app.layer(layer);
}
// Security response headers
for (name, value) in &mw.security {
let Some(header_name) = header_name_from(&name.to_ascii_lowercase()) else {
continue;
};
if let Ok(v) = HeaderValue::from_str(value) {
app = app.layer(SetResponseHeaderLayer::overriding(header_name, v));
}
}
// Compression
if mw.compress {
app = app.layer(CompressionLayer::new());
}
// Request body limit
if let Some(bytes) = mw.body_limit {
app = app.layer(RequestBodyLimitLayer::new(bytes as usize));
}
app
}
fn header_name_from(name: &str) -> Option<axum::http::HeaderName> {
let h = match name {
"x_frame_options" | "x-frame-options" => header::X_FRAME_OPTIONS,
"content_security_policy" | "content-security-policy" => header::CONTENT_SECURITY_POLICY,
"x_content_type_options" | "x-content-type-options" => header::X_CONTENT_TYPE_OPTIONS,
"referrer_policy" | "referrer-policy" => header::REFERRER_POLICY,
"strict_transport_security" | "strict-transport-security" | "hsts" => {
header::STRICT_TRANSPORT_SECURITY
}
"x_xss_protection" | "x-xss-protection" => header::X_XSS_PROTECTION,
_ => return None,
};
Some(h)
}
/// Mount a JSON API route backed by a db query.
fn mount_json(
app: Router<Arc<crate::http::AppState>>,
path: &str,
route: JsonRoute,
) -> Router<Arc<crate::http::AppState>> {
let handler = match route.method.as_str() {
"POST" => post(move |State(st): State<Arc<crate::http::AppState>>| {
json_handler(st, route.clone())
}),
_ => get(move |State(st): State<Arc<crate::http::AppState>>| {
json_handler(st, route.clone())
}),
};
app.route(path, handler)
}
async fn json_handler(st: Arc<crate::http::AppState>, route: JsonRoute) -> Response {
let Some(url) = st.db_url.as_deref() else {
return (
StatusCode::INTERNAL_SERVER_ERROR,
JsonBody(json!({ "error": "no database" })),
)
.into_response();
};
let res = match &route.order {
Some(o) if !o.trim().is_empty() => {
db::select_order(url, &route.table, route.limit, route.where_v.as_ref(), Some(o), None, None)
}
_ => db::select(url, &route.table, route.limit, route.where_v.as_ref()),
};
match res {
Ok(data) => JsonBody(data).into_response(),
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
JsonBody(json!({ "error": e })),
)
.into_response(),
}
}
/// A JSON body response wrapper (sets `Content-Type: application/json`).
pub struct JsonBody(pub Value);
impl IntoResponse for JsonBody {
fn into_response(self) -> Response {
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "application/json; charset=utf-8")
.body(Body::from(self.0.to_string()))
.unwrap()
}
}
/// Normalize a `security` table into the `middleware.security` map shape.
/// Accepts a GFM table `|头|值|` (list of rows) or an already-shaped map.
pub fn security_from_table(table: &Value) -> Value {
let rows = crate::table::as_rows(table);
let mut m = Map::new();
if let Some(arr) = rows.as_array() {
for row in arr {
let col = |keys: &[&str]| -> String {
keys.iter()
.find_map(|k| row.get(*k).map(cell_text))
.unwrap_or_default()
};
let k = col(&["头", "header", "Header", "name"]);
let v = col(&["值", "value", "Value"]);
if !k.is_empty() {
m.insert(k, json!(v));
}
}
}
Value::Object(m)
}
/// Normalize a CORS table `|允许来源|方法|头|暴露头|凭证|` (one row per origin)
/// into the `middleware.cors` map shape.
pub fn cors_from_table(table: &Value) -> Value {
let rows = crate::table::as_rows(table);
let mut allow_origins = Vec::new();
let mut methods = Vec::new();
let mut headers = Vec::new();
let mut expose_headers = Vec::new();
let mut credentials = false;
if let Some(arr) = rows.as_array() {
for row in arr {
let col = |keys: &[&str]| -> String {
keys.iter()
.find_map(|k| row.get(*k).map(cell_text))
.unwrap_or_default()
};
let origin = col(&["允许来源", "origin", "Origin"]);
if !origin.is_empty() && origin != "*" {
allow_origins.push(origin);
}
for m in col(&["方法", "methods", "Methods"]).split(',') {
let m = m.trim();
if !m.is_empty() {
methods.push(m.to_string());
}
}
for h in col(&["头", "headers", "Headers"]).split(',') {
let h = h.trim();
if !h.is_empty() {
headers.push(h.to_string());
}
}
for h in col(&["暴露头", "expose_headers", "Expose-Headers"]).split(',') {
let h = h.trim();
if !h.is_empty() {
expose_headers.push(h.to_string());
}
}
let cred = col(&["凭证", "credentials", "Credentials"]);
if cred.eq_ignore_ascii_case("true")
|| cred == "1"
|| cred.eq_ignore_ascii_case("yes")
{
credentials = true;
}
}
}
json!({
"allow_origins": allow_origins,
"methods": methods,
"headers": headers,
"expose_headers": expose_headers,
"credentials": credentials,
})
}
/// Normalize a JSON-routes table into `middleware.json_routes` map shape.
/// Accepts a GFM table `|路径|方法|表|条件|排序|上限|` (rows).
pub fn json_routes_from_table(table: &Value) -> Value {
let rows = crate::table::as_rows(table);
let mut routes = Map::new();
if let Some(arr) = rows.as_array() {
for row in arr {
let col = |keys: &[&str]| -> String {
keys.iter()
.find_map(|k| row.get(*k).map(cell_text))
.unwrap_or_default()
};
let path = col(&["路径", "path", "Path"]).trim_start_matches('/').to_string();
if path.is_empty() {
continue;
}
let method = col(&["方法", "method", "Method"]).to_uppercase();
let method = if method.is_empty() { "GET".into() } else { method };
let table = col(&["表", "table", "Table"]);
if table.is_empty() {
continue;
}
let order = col(&["排序", "order", "Order"]);
let limit = col(&["上限", "limit", "Limit"]).parse::<i64>().unwrap_or(200);
let mut spec = Map::new();
spec.insert("method".into(), json!(method));
spec.insert("table".into(), json!(table));
if !order.is_empty() {
spec.insert("order".into(), json!(order));
}
spec.insert("limit".into(), json!(limit));
routes.insert(path, Value::Object(spec));
}
}
Value::Object(routes)
}
/// Read the `middleware` map out of an app object (for logging/debug).
pub fn summary(app: &Value) -> String {
let mw = parse(app);
let mut parts = Vec::new();
if mw.cors.is_some() {
parts.push("cors".to_string());
}
if !mw.security.is_empty() {
parts.push("security".to_string());
}
if mw.compress {
parts.push("compress".to_string());
}
if mw.body_limit.is_some() {
parts.push("body_limit".to_string());
}
if !mw.json_routes.is_empty() {
parts.push(format!("json:{}", mw.json_routes.len()));
}
if parts.is_empty() {
String::new()
} else {
parts.join(" + ")
}
}
+64
View File
@@ -0,0 +1,64 @@
//! Password hashing (argon2id) for admin users and auth tables.
use argon2::{
password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
Argon2,
};
use getrandom::getrandom;
/// True when `stored` looks like an argon2 PHC string.
pub fn is_hashed(stored: &str) -> bool {
stored.starts_with("$argon2")
}
/// Hash a plaintext password (argon2id, random salt).
pub fn hash_password(plain: &str) -> Result<String, String> {
if plain.is_empty() {
return Err("password must not be empty".into());
}
let mut salt_bytes = [0u8; 16];
getrandom(&mut salt_bytes).map_err(|e| format!("getrandom: {e}"))?;
let salt = SaltString::encode_b64(&salt_bytes).map_err(|e| e.to_string())?;
let argon2 = Argon2::default();
argon2
.hash_password(plain.as_bytes(), &salt)
.map(|h| h.to_string())
.map_err(|e| e.to_string())
}
/// Verify plaintext against stored hash or legacy plaintext (dev / gold tests).
pub fn verify_password(plain: &str, stored: &str) -> bool {
if stored.is_empty() || plain.is_empty() {
return false;
}
if is_hashed(stored) {
let parsed = match PasswordHash::new(stored) {
Ok(h) => h,
Err(_) => return false,
};
Argon2::default()
.verify_password(plain.as_bytes(), &parsed)
.is_ok()
} else {
plain == stored
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hash_and_verify_roundtrip() {
let hash = hash_password("secret").unwrap();
assert!(is_hashed(&hash));
assert!(verify_password("secret", &hash));
assert!(!verify_password("wrong", &hash));
}
#[test]
fn legacy_plaintext_still_works() {
assert!(verify_password("secret", "secret"));
assert!(!verify_password("other", "secret"));
}
}
+95
View File
@@ -0,0 +1,95 @@
//! Login rate limiting — max failures per IP+username within a window.
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
const MAX_FAILS: u32 = 5;
const WINDOW_SEC: u64 = 900; // 15 minutes
struct Window {
count: u32,
start: u64,
}
static ATTEMPTS: Mutex<Option<HashMap<String, Window>>> = Mutex::new(None);
fn now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
fn key(ip: &str, username: &str) -> String {
format!("{ip}|{username}")
}
fn with_map<T>(f: impl FnOnce(&mut HashMap<String, Window>) -> T) -> T {
let mut guard = ATTEMPTS.lock().unwrap_or_else(|e| e.into_inner());
let map = guard.get_or_insert_with(HashMap::new);
f(map)
}
/// Reset attempt counters (between listens / tests).
pub fn reset() {
let mut guard = ATTEMPTS.lock().unwrap_or_else(|e| e.into_inner());
*guard = Some(HashMap::new());
}
/// Returns `Err(message)` when the client is temporarily locked out.
pub fn check(ip: &str, username: &str) -> Result<(), String> {
let k = key(ip, username);
let now = now_secs();
with_map(|map| {
if let Some(w) = map.get(&k) {
if now.saturating_sub(w.start) < WINDOW_SEC && w.count >= MAX_FAILS {
return Err(
"Too many failed login attempts. Try again in about 15 minutes.".into(),
);
}
if now.saturating_sub(w.start) >= WINDOW_SEC {
map.remove(&k);
}
}
Ok(())
})
}
pub fn record_failure(ip: &str, username: &str) {
let k = key(ip, username);
let now = now_secs();
with_map(|map| {
let entry = map.entry(k).or_insert(Window { count: 0, start: now });
if now.saturating_sub(entry.start) >= WINDOW_SEC {
entry.count = 0;
entry.start = now;
}
entry.count = entry.count.saturating_add(1);
});
}
pub fn clear_success(ip: &str, username: &str) {
let k = key(ip, username);
with_map(|map| {
map.remove(&k);
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn locks_after_max_fails() {
reset();
let ip = "127.0.0.1";
let user = "admin";
for _ in 0..MAX_FAILS {
record_failure(ip, user);
}
assert!(check(ip, user).is_err());
clear_success(ip, user);
assert!(check(ip, user).is_ok());
}
}
+6 -4
View File
@@ -188,7 +188,7 @@ fn select_page_data(
}
let order = args.get("order").and_then(|v| v.as_str());
if order.is_some_and(|s| !s.trim().is_empty()) {
db::select_order(url, table, limit, where_v.as_ref(), order)
db::select_order(url, table, limit, where_v.as_ref(), order, None, None)
} else {
db::select(url, table, limit, where_v.as_ref())
}
@@ -321,8 +321,8 @@ a:hover { color:var(--accent); }
.article-code { background:#f5f5f4; border:1px solid var(--line); border-radius:6px; padding:1rem; overflow-x:auto; font-size:.9rem; }
"#;
pub fn render_page(args: &Value, db_url: Option<&str>) -> String {
render_page_ex(args, db_url, None, None)
pub fn render_page(args: &Value, db_url: Option<&str>, csrf: Option<&str>) -> String {
render_page_ex(args, db_url, None, None, csrf)
}
/// Like `render_page`, optionally replaying form POST data/errors into the embedded form.
@@ -331,6 +331,7 @@ pub fn render_page_ex(
db_url: Option<&str>,
form_data: Option<&Value>,
form_errors: Option<&Value>,
csrf: Option<&str>,
) -> String {
let title = args
.get("title")
@@ -372,6 +373,7 @@ pub fn render_page_ex(
form_id,
form_data,
form_errors,
csrf,
));
}
if !items.is_empty() {
@@ -466,7 +468,7 @@ pub fn render_fragment(args: &Value, db_url: Option<&str>) -> String {
.get("form_id")
.and_then(|v| v.as_str())
.unwrap_or("form");
body.push_str(&crate::form::render_body(form, form_id, None, None));
body.push_str(&crate::form::render_body(form, form_id, None, None, None));
}
if !items.is_empty() {
let is_detail = args
+372 -127
View File
@@ -1,22 +1,40 @@
//! In-memory session store + cookie helpers (design ext-web-net §3.1 / §3.2).
//! Session store + cookie helpers + CSRF tokens (ext-web-net W3).
//!
//! Sessions live for the lifetime of the plugin process (same as `web_listen`).
//! Session ids are random hex strings; cookies are `marqdo_sid=<id>` with
//! `HttpOnly; Path=/; SameSite=Lax`.
//! - **CSPRNG** session ids (`getrandom`).
//! - **SQLite persistence** when `configure` receives a `db_url`; otherwise in-memory (offline gold).
//! - **Sliding expiry** on read/write.
//! - **CSRF** token per session (`_csrf` key).
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use getrandom::getrandom;
use serde_json::{json, Map, Value};
use crate::db;
use crate::password;
type SessionMap = HashMap<String, Value>;
struct Store {
#[derive(Clone, Default)]
pub struct Config {
pub db_url: Option<String>,
pub ttl_sec: u64,
pub cookie_secure: bool,
}
static CONFIG: Mutex<Option<Config>> = Mutex::new(None);
struct MemStore {
ttl_sec: u64,
data: HashMap<String, (u64, SessionMap)>,
}
static STORE: Mutex<Option<Store>> = Mutex::new(None);
static MEM: Mutex<Option<MemStore>> = Mutex::new(None);
const SESSION_TABLE: &str = "_marqdo_sessions";
const CSRF_KEY: &str = "_csrf";
fn now_secs() -> u64 {
SystemTime::now()
@@ -25,111 +43,310 @@ fn now_secs() -> u64 {
.unwrap_or(0)
}
fn with_store<T>(f: impl FnOnce(&mut Store) -> T) -> T {
let mut guard = STORE.lock().unwrap_or_else(|e| e.into_inner());
let store = guard.get_or_insert_with(|| Store {
ttl_sec: 3600,
fn cfg() -> Config {
CONFIG
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
.unwrap_or(Config {
db_url: None,
ttl_sec: 3600,
cookie_secure: false,
})
}
/// Configure session backend before `listen` or offline ABI calls.
pub fn configure(config: Config) {
let ttl = if config.ttl_sec > 0 {
config.ttl_sec
} else {
3600
};
let mut c = config;
c.ttl_sec = ttl;
if let Some(ref url) = c.db_url {
let _ = ensure_session_table(url);
}
let mut guard = CONFIG.lock().unwrap_or_else(|e| e.into_inner());
*guard = Some(c);
}
/// Reset in-memory sessions (tests / each listen).
pub fn reset(ttl_sec: u64) {
let ttl = if ttl_sec > 0 { ttl_sec } else { 3600 };
{
let mut guard = CONFIG.lock().unwrap_or_else(|e| e.into_inner());
if let Some(ref mut c) = *guard {
c.ttl_sec = ttl;
} else {
*guard = Some(Config {
db_url: None,
ttl_sec: ttl,
cookie_secure: false,
});
}
}
let mut mem = MEM.lock().unwrap_or_else(|e| e.into_inner());
*mem = Some(MemStore {
ttl_sec: ttl,
data: HashMap::new(),
});
}
fn ensure_session_table(url: &str) -> Result<(), String> {
db::exec(
url,
&format!(
"CREATE TABLE IF NOT EXISTS \"{SESSION_TABLE}\" (
id TEXT PRIMARY KEY,
expires_at INTEGER NOT NULL,
data TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_marqdo_sessions_exp ON \"{SESSION_TABLE}\"(expires_at);"
),
None,
None,
)?;
Ok(())
}
fn prune_mem(store: &mut MemStore) {
let now = now_secs();
store.data.retain(|_, (exp, _)| *exp > now);
}
fn prune_sql(url: &str) {
let now = now_secs() as i64;
let _ = db::exec(
url,
&format!("DELETE FROM \"{SESSION_TABLE}\" WHERE expires_at <= ?1"),
Some(&json!([now])),
None,
);
}
fn secure_random_id() -> Result<String, String> {
let mut bytes = [0u8; 32];
getrandom(&mut bytes).map_err(|e| format!("getrandom: {e}"))?;
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
}
fn random_csrf() -> Result<String, String> {
let mut bytes = [0u8; 24];
getrandom(&mut bytes).map_err(|e| format!("getrandom: {e}"))?;
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
}
fn map_to_json(m: &SessionMap) -> Result<String, String> {
let obj: Map<String, Value> = m.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
serde_json::to_string(&Value::Object(obj)).map_err(|e| e.to_string())
}
fn json_to_map(s: &str) -> SessionMap {
match serde_json::from_str::<Value>(s) {
Ok(Value::Object(m)) => m.into_iter().collect(),
_ => HashMap::new(),
}
}
fn load_sql(url: &str, id: &str) -> Option<(u64, SessionMap)> {
let q = db::query(
url,
&format!("SELECT expires_at, data FROM \"{SESSION_TABLE}\" WHERE id = ?1"),
Some(&json!([id])),
None,
)
.ok()?;
let rows = q.get("rows")?.as_array()?;
let row = rows.first()?;
let exp = row.get("expires_at")?.as_i64()? as u64;
let data_s = row.get("data")?.as_str()?;
Some((exp, json_to_map(data_s)))
}
fn save_sql(url: &str, id: &str, exp: u64, data: &SessionMap) -> Result<(), String> {
let data_s = map_to_json(data)?;
db::exec(
url,
&format!(
"INSERT INTO \"{SESSION_TABLE}\" (id, expires_at, data) VALUES (?1, ?2, ?3)
ON CONFLICT(id) DO UPDATE SET expires_at = excluded.expires_at, data = excluded.data"
),
Some(&json!([id, exp as i64, data_s])),
None,
)?;
Ok(())
}
fn delete_sql(url: &str, id: &str) {
let _ = db::exec(
url,
&format!("DELETE FROM \"{SESSION_TABLE}\" WHERE id = ?1"),
Some(&json!([id])),
None,
);
}
fn touch_expiry(ttl: u64) -> u64 {
now_secs() + ttl
}
fn ensure_csrf(data: &mut SessionMap) -> Result<String, String> {
if let Some(Value::String(t)) = data.get(CSRF_KEY) {
if !t.is_empty() {
return Ok(t.clone());
}
}
let t = random_csrf()?;
data.insert(CSRF_KEY.to_string(), json!(t));
Ok(t)
}
pub fn session_new(ttl_sec: Option<u64>) -> String {
let cfg = cfg();
let ttl = ttl_sec.unwrap_or(cfg.ttl_sec);
if ttl > 0 {
if let Ok(mut guard) = CONFIG.lock() {
if let Some(ref mut c) = *guard {
c.ttl_sec = ttl;
}
}
}
let id = secure_random_id().unwrap_or_else(|_| format!("fallback-{}", now_secs()));
let exp = touch_expiry(ttl);
let mut data = SessionMap::new();
let _ = ensure_csrf(&mut data);
if let Some(ref url) = cfg.db_url {
prune_sql(url);
let _ = save_sql(url, &id, exp, &data);
} else {
with_mem(|store| {
store.ttl_sec = ttl;
prune_mem(store);
store.data.insert(id.clone(), (exp, data));
});
}
id
}
fn with_mem<T>(f: impl FnOnce(&mut MemStore) -> T) -> T {
let mut guard = MEM.lock().unwrap_or_else(|e| e.into_inner());
let store = guard.get_or_insert_with(|| MemStore {
ttl_sec: cfg().ttl_sec,
data: HashMap::new(),
});
f(store)
}
fn prune(store: &mut Store) {
fn get_record(id: &str) -> Option<(u64, SessionMap)> {
let cfg = cfg();
let now = now_secs();
store.data.retain(|_, (exp, _)| *exp > now);
}
fn random_id() -> String {
use std::time::{SystemTime, UNIX_EPOCH};
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.subsec_nanos())
.unwrap_or(0);
let pid = std::process::id();
// Cheap but adequate unique-enough id for an in-memory session store.
format!("{pid:x}{nanos:x}{:x}", rand_word())
}
fn rand_word() -> u64 {
// xorshift64 from a counter; not cryptographically strong but fine for
// session cookies when combined with pid+time. (Plugin is single-process.)
static COUNTER: Mutex<u64> = Mutex::new(0x9e3779b97f4a7c15);
let mut c = COUNTER.lock().unwrap_or_else(|e| e.into_inner());
let mut x = *c;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
*c = x;
x
}
/// Reset the store (used between listens / for tests).
pub fn reset(ttl_sec: u64) {
let mut guard = STORE.lock().unwrap_or_else(|e| e.into_inner());
*guard = Some(Store {
ttl_sec,
data: HashMap::new(),
});
}
pub fn session_new(ttl_sec: Option<u64>) -> String {
with_store(|store| {
if let Some(ttl) = ttl_sec {
if ttl > 0 {
store.ttl_sec = ttl;
}
if let Some(ref url) = cfg.db_url {
prune_sql(url);
let (exp, data) = load_sql(url, id)?;
if exp <= now {
delete_sql(url, id);
return None;
}
prune(store);
let id = random_id();
let exp = now_secs() + store.ttl_sec;
store.data.insert(id.clone(), (exp, SessionMap::new()));
id
})
Some((exp, data))
} else {
with_mem(|store| {
prune_mem(store);
let (exp, data) = store.data.get(id)?.clone();
if exp <= now {
store.data.remove(id);
return None;
}
Some((exp, data))
})
}
}
fn put_record(id: &str, exp: u64, data: SessionMap) -> bool {
let cfg = cfg();
if let Some(ref url) = cfg.db_url {
save_sql(url, id, exp, &data).is_ok()
} else {
with_mem(|store| {
store.data.insert(id.to_string(), (exp, data));
true
})
}
}
pub fn session_set(id: &str, key: &str, value: Value) -> bool {
with_store(|store| {
prune(store);
let Some((exp, m)) = store.data.get_mut(id) else {
return false;
};
if *exp <= now_secs() {
return false;
}
m.insert(key.to_string(), value);
true
})
let cfg = cfg();
let Some((_, mut data)) = get_record(id) else {
return false;
};
data.insert(key.to_string(), value);
put_record(id, touch_expiry(cfg.ttl_sec), data)
}
pub fn session_get(id: &str, key: &str) -> Option<Value> {
with_store(|store| {
prune(store);
let (exp, m) = store.data.get(id)?;
if *exp <= now_secs() {
return None;
}
m.get(key).cloned()
})
let cfg = cfg();
let (_, data) = get_record(id)?;
let v = data.get(key).cloned()?;
put_record(id, touch_expiry(cfg.ttl_sec), data);
Some(v)
}
pub fn session_del(id: &str, key: &str) -> bool {
with_store(|store| {
prune(store);
let Some((exp, m)) = store.data.get_mut(id) else {
return false;
};
if *exp <= now_secs() {
return false;
}
m.remove(key).is_some()
})
let cfg = cfg();
let Some((_, mut data)) = get_record(id) else {
return false;
};
let ok = data.remove(key).is_some();
if ok {
put_record(id, touch_expiry(cfg.ttl_sec), data);
}
ok
}
pub fn session_destroy(id: &str) -> bool {
with_store(|store| {
prune(store);
store.data.remove(id).is_some()
})
let cfg = cfg();
if let Some(ref url) = cfg.db_url {
delete_sql(url, id);
true
} else {
with_mem(|store| store.data.remove(id).is_some())
}
}
/// CSRF token for an existing session (creates one if missing).
pub fn csrf_for(id: &str) -> Option<String> {
let cfg = cfg();
let (_, mut data) = get_record(id)?;
let token = ensure_csrf(&mut data).ok()?;
put_record(id, touch_expiry(cfg.ttl_sec), data);
Some(token)
}
pub fn validate_csrf(id: &str, token: &str) -> bool {
if token.is_empty() {
return false;
}
match session_get(id, CSRF_KEY) {
Some(Value::String(stored)) => stored == token,
_ => false,
}
}
/// Resolve session from cookie: reuse valid id or create a new one.
/// Returns `(session_id, set_cookie_header)`.
pub fn ensure_from_cookie(cookie_header: Option<&str>) -> (String, Option<String>) {
if let Some(id) = session_id_from_cookie(cookie_header) {
if get_record(&id).is_some() {
let _ = csrf_for(&id);
return (id, None);
}
}
let id = session_new(None);
let cfg = cfg();
(
id.clone(),
Some(session_cookie(&id, cfg.ttl_sec, cfg.cookie_secure)),
)
}
/// Parse the session id from a `Cookie` request header (looks for `marqdo_sid=…`).
@@ -147,16 +364,18 @@ pub fn session_id_from_cookie(cookie_header: Option<&str>) -> Option<String> {
None
}
/// `Set-Cookie: marqdo_sid=<id>; HttpOnly; Path=/; SameSite=Lax; Max-Age=<ttl>`
pub fn session_cookie(id: &str, ttl_sec: u64) -> String {
format!(
/// `Set-Cookie: marqdo_sid=<id>; HttpOnly; Path=/; SameSite=Lax; Max-Age=<ttl>[; Secure]`
pub fn session_cookie(id: &str, ttl_sec: u64, secure: bool) -> String {
let mut s = format!(
"marqdo_sid={id}; HttpOnly; Path=/; SameSite=Lax; Max-Age={ttl_sec}"
)
);
if secure {
s.push_str("; Secure");
}
s
}
/// Validate `username`/`password` against an admin-users table (`|用户名|密码|`
/// with headers `username`/`密码` or `用户`/`密码`, or plain `username`/`password`).
/// Returns the matched username on success.
/// Validate credentials; supports argon2 hashes or legacy plaintext in the password column.
pub fn check_credentials(users: &Value, username: &str, password: &str) -> Option<String> {
let rows = match users {
Value::Array(a) => a,
@@ -173,7 +392,7 @@ pub fn check_credentials(users: &Value, username: &str, password: &str) -> Optio
let p = pick_cell(m, &["密码", "password", "pass", "口令"])
.map(cell_str)
.unwrap_or_default();
if u == username && p == password {
if u == username && password::verify_password(password, &p) {
return Some(u);
}
}
@@ -194,7 +413,6 @@ fn cell_str(v: &Value) -> String {
}
}
/// ABI helpers.
pub fn abi_session_new(args: &Value) -> Result<Value, String> {
let ttl = args
.get("ttl_sec")
@@ -260,6 +478,12 @@ pub fn abi_auth_logout(args: &Value) -> Result<Value, String> {
Ok(json!({ "ok": session_destroy(id) }))
}
pub fn abi_password_hash(args: &Value) -> Result<Value, String> {
let plain = arg_str(args, "password")?;
let hash = password::hash_password(plain)?;
Ok(json!({ "hash": hash }))
}
fn arg_str<'a>(v: &'a Value, key: &str) -> Result<&'a str, String> {
v.get(key)
.and_then(|x| x.as_str())
@@ -283,10 +507,7 @@ mod tests {
let id = session_new(None);
assert!(!id.is_empty());
assert!(session_set(&id, "username", json!("admin")));
assert_eq!(
session_get(&id, "username"),
Some(json!("admin"))
);
assert_eq!(session_get(&id, "username"), Some(json!("admin")));
assert!(session_del(&id, "username"));
assert_eq!(session_get(&id, "username"), None);
assert!(session_destroy(&id));
@@ -305,7 +526,6 @@ mod tests {
let sid = r["session_id"].as_str().unwrap().to_string();
let check = abi_auth_check(&json!({ "session_id": sid })).unwrap();
assert_eq!(check["ok"].as_bool(), Some(true));
assert_eq!(check["username"], "admin");
let bad = abi_auth_login(&json!({
"username": "admin",
@@ -315,39 +535,64 @@ mod tests {
.unwrap();
assert_eq!(bad["ok"].as_bool(), Some(false));
// Chinese column headers also work.
let zh = abi_auth_login(&json!({
"username": "站长",
"password": "pw123",
"users": users(),
}))
.unwrap();
assert_eq!(zh["ok"].as_bool(), Some(true));
let out = abi_auth_logout(&json!({ "session_id": sid })).unwrap();
assert_eq!(out["ok"].as_bool(), Some(true));
let check2 = abi_auth_check(&json!({ "session_id": sid })).unwrap();
assert_eq!(check2["ok"].as_bool(), Some(false));
}
#[test]
fn csrf_roundtrip() {
reset(3600);
let id = session_new(None);
let t = csrf_for(&id).unwrap();
assert!(validate_csrf(&id, &t));
assert!(!validate_csrf(&id, "bad"));
}
#[test]
fn cookie_roundtrip() {
reset(3600);
let id = session_new(None);
let cookie = session_cookie(&id, 3600);
let cookie = session_cookie(&id, 3600, false);
assert!(cookie.starts_with("marqdo_sid="));
let got = session_id_from_cookie(Some(&format!(
"theme=light; {cookie}"
)));
let got = session_id_from_cookie(Some(&format!("theme=light; {cookie}")));
assert_eq!(got.as_deref(), Some(id.as_str()));
assert_eq!(session_id_from_cookie(Some("theme=light")), None);
assert_eq!(session_id_from_cookie(None), None);
}
#[test]
fn check_credentials_missing() {
assert!(check_credentials(&json!(null), "a", "b").is_none());
assert!(check_credentials(&json!("x"), "a", "b").is_none());
assert!(check_credentials(&json!([]), "a", "b").is_none());
fn hashed_password_login() {
reset(3600);
let hash = password::hash_password("secret").unwrap();
let users = json!([{ "username": "admin", "password": hash }]);
let r = abi_auth_login(&json!({
"username": "admin",
"password": "secret",
"users": users,
}))
.unwrap();
assert_eq!(r["ok"].as_bool(), Some(true));
}
#[test]
fn session_persists_in_sqlite() {
let dir = std::env::temp_dir().join(format!("marqdo_web_sess_{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let path = dir.join("persist.db");
let _ = std::fs::remove_file(&path);
let url = format!("sqlite:{}", path.display());
configure(Config {
db_url: Some(url.clone()),
ttl_sec: 3600,
cookie_secure: false,
});
let id = session_new(None);
assert!(session_set(&id, "theme", json!("dark")));
// Re-configure (simulates listen restart with same db).
configure(Config {
db_url: Some(url),
ttl_sec: 3600,
cookie_secure: false,
});
assert_eq!(session_get(&id, "theme"), Some(json!("dark")));
let _ = std::fs::remove_dir_all(dir);
}
}