Extend network stack: session/auth, WebSocket, cookie/multipart primitives
Add the network-extension wave to lib/net and the web ABI plugin:
- lib/net cookie_parse / multipart_parse host primitives (EN/ZH)
- plugins/web session store + /admin login gate + WebSocket client/server
- ext/web author surface (EN/ZH) for session, auth, ws
- form update flow and page-level validation echo tests
- fix string escapes: \xHH, \u{...}, unknown escapes kept verbatim
- map Chinese component slots (导航/侧栏/页脚) so sidebar renders
- resolve relative static/db paths against the entry script dir (entry_dir)
- new tutorial chapter 14, EN/ZH example sites, and gold tests
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
7dfa161422
commit
7645dd4c1f
47 files changed
+3380
-75
No files matched your search
+196
-9
@@ -18,6 +18,7 @@ use tower_http::services::ServeDir;
|
||||
use crate::db;
|
||||
use crate::form;
|
||||
use crate::render;
|
||||
use crate::session;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct AppState {
|
||||
@@ -28,6 +29,9 @@ struct AppState {
|
||||
/// Page that owns an embedded form (for re-render on validation errors).
|
||||
form_owners: HashMap<String, Value>,
|
||||
routes: HashMap<String, Value>,
|
||||
/// Admin users table (`|用户名|密码|`) when login-gated admin is configured.
|
||||
auth_users: Option<Value>,
|
||||
session_ttl: u64,
|
||||
}
|
||||
|
||||
fn collect_page_forms(
|
||||
@@ -62,12 +66,16 @@ pub fn listen(
|
||||
routes: HashMap<String, Value>,
|
||||
static_dir: Option<PathBuf>,
|
||||
static_mount: &str,
|
||||
auth_users: Option<Value>,
|
||||
session_ttl: u64,
|
||||
ws_routes: HashMap<String, bool>,
|
||||
) -> 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::reset(session_ttl);
|
||||
let state = Arc::new(AppState {
|
||||
page: page.clone(),
|
||||
db_url: db_url.map(|s| s.to_string()),
|
||||
@@ -75,6 +83,8 @@ pub fn listen(
|
||||
forms,
|
||||
form_owners,
|
||||
routes: routes.clone(),
|
||||
auth_users,
|
||||
session_ttl,
|
||||
});
|
||||
|
||||
let mut app = Router::new()
|
||||
@@ -82,6 +92,8 @@ pub fn listen(
|
||||
.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(
|
||||
@@ -99,6 +111,19 @@ pub fn listen(
|
||||
app = app.route(&part_path, get(routed_part));
|
||||
}
|
||||
|
||||
// WebSocket endpoints (`ws://…/{path}`), echo-mode by default.
|
||||
let mut ws_paths: Vec<String> = ws_routes.keys().cloned().collect();
|
||||
ws_paths.sort();
|
||||
for path in ws_paths {
|
||||
let echo = ws_routes.get(&path).copied().unwrap_or(true);
|
||||
app = app.route(
|
||||
&path,
|
||||
axum::routing::get(move |ws: axum::extract::WebSocketUpgrade| {
|
||||
ws_upgrade(ws, echo)
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
let mount = normalize_static_mount(static_mount);
|
||||
if let Some(dir) = static_dir {
|
||||
if !dir.is_dir() {
|
||||
@@ -294,16 +319,142 @@ fn submit_and_respond(
|
||||
}
|
||||
}
|
||||
|
||||
fn admin_gate(st: &AppState) -> Option<Response> {
|
||||
fn cookie_from_headers(headers: &axum::http::HeaderMap) -> Option<&str> {
|
||||
headers
|
||||
.get(axum::http::header::COOKIE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
if st.db_url.is_none() {
|
||||
return Some(Html(admin_shell(st, "Admin", None, "<p class=\"flash err\">No database bound to this app.</p>")).into_response());
|
||||
}
|
||||
// Login-gated admin: require a valid session cookie.
|
||||
if st.auth_users.is_some() && !admin_authed(st, cookie_header) {
|
||||
return Some(
|
||||
Redirect::to("/admin/login")
|
||||
.into_response(),
|
||||
);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// True when a valid admin session cookie is present.
|
||||
fn admin_authed(_st: &AppState, cookie_header: Option<&str>) -> bool {
|
||||
let Some(sid) = session::session_id_from_cookie(cookie_header) else {
|
||||
return false;
|
||||
};
|
||||
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.
|
||||
if st.auth_users.is_none() {
|
||||
return Redirect::to("/admin").into_response();
|
||||
}
|
||||
Html(login_page(&st, None)).into_response()
|
||||
}
|
||||
|
||||
async fn admin_login_post(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Form(posted): Form<LoginForm>,
|
||||
) -> 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 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(
|
||||
axum::http::header::SET_COOKIE,
|
||||
session::session_cookie(&sid, st.session_ttl)
|
||||
.parse()
|
||||
.unwrap(),
|
||||
) {
|
||||
let _ = h;
|
||||
}
|
||||
resp
|
||||
}
|
||||
|
||||
fn login_page(_st: &AppState, error: Option<&str>) -> String {
|
||||
let err = match error {
|
||||
Some(e) => format!("<p class=\"flash err\">{}</p>", esc(e)),
|
||||
None => String::new(),
|
||||
};
|
||||
format!(
|
||||
r#"<!DOCTYPE html>
|
||||
<html lang="zh-CN"><head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<title>Admin Login</title>
|
||||
<style>
|
||||
:root {{ --ink:#1c1917; --muted:#78716c; --paper:#fafaf9; --line:#e7e5e4; --accent:#0f766e; --err:#b91c1c; }}
|
||||
* {{ box-sizing:border-box; }}
|
||||
body {{ margin:0; min-height:100vh; display:grid; place-items:center; background:var(--paper); color:var(--ink); font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; }}
|
||||
.login {{ background:#fff; border:1px solid var(--line); border-radius:10px; padding:2rem 2.25rem; width:min(92vw,22rem); box-shadow:0 8px 24px rgba(0,0,0,.05); }}
|
||||
.login h1 {{ margin:0 0 .25rem; font-size:1.4rem; }}
|
||||
.login .sub {{ color:var(--muted); margin:0 0 1.25rem; font-size:.9rem; }}
|
||||
.login form {{ display:grid; gap:.9rem; }}
|
||||
.login label {{ display:grid; gap:.25rem; font-size:.9rem; }}
|
||||
.login input {{ padding:.55rem .65rem; border:1px solid var(--line); border-radius:6px; font:inherit; }}
|
||||
.login button {{ background:var(--accent); color:#fff; border:0; padding:.6rem 1rem; border-radius:6px; cursor:pointer; font:inherit; }}
|
||||
.login button:hover {{ filter:brightness(1.05); }}
|
||||
.flash.err {{ background:#fef2f2; color:var(--err); border:1px solid #fecaca; padding:.6rem .8rem; border-radius:6px; margin:0 0 .9rem; font-size:.9rem; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="login">
|
||||
<h1>Admin</h1>
|
||||
<p class="sub">Sign in to manage this site.</p>
|
||||
{err}
|
||||
<form method="post" action="/admin/login">
|
||||
<label>Username<input name="username" autocomplete="username" required autofocus/></label>
|
||||
<label>Password<input name="password" type="password" autocomplete="current-password" required/></label>
|
||||
<button type="submit">Sign in</button>
|
||||
</form>
|
||||
</div>
|
||||
</body></html>"#,
|
||||
err = err,
|
||||
)
|
||||
}
|
||||
|
||||
async fn admin_logout(
|
||||
State(_st): State<Arc<AppState>>,
|
||||
headers: axum::http::HeaderMap,
|
||||
) -> Response {
|
||||
if let Some(sid) = session::session_id_from_cookie(
|
||||
headers
|
||||
.get(axum::http::header::COOKIE)
|
||||
.and_then(|v| v.to_str().ok()),
|
||||
) {
|
||||
session::session_destroy(&sid);
|
||||
}
|
||||
let mut resp = Redirect::to("/admin/login").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"
|
||||
.parse()
|
||||
.unwrap(),
|
||||
) {
|
||||
let _ = h;
|
||||
}
|
||||
resp
|
||||
}
|
||||
|
||||
fn flash_html(flash: Option<&str>) -> String {
|
||||
match flash {
|
||||
Some("created") => "<div class=\"flash ok\">Row created.</div>".into(),
|
||||
@@ -452,9 +603,10 @@ struct FlashQuery {
|
||||
|
||||
async fn admin_home(
|
||||
State(st): State<Arc<AppState>>,
|
||||
headers: axum::http::HeaderMap,
|
||||
Query(q): Query<FlashQuery>,
|
||||
) -> Response {
|
||||
if let Some(r) = admin_gate(&st) {
|
||||
if let Some(r) = admin_gate(&st, cookie_from_headers(&headers)) {
|
||||
return r;
|
||||
}
|
||||
let url = st.db_url.as_deref().unwrap();
|
||||
@@ -480,10 +632,11 @@ async fn admin_home(
|
||||
|
||||
async fn admin_table(
|
||||
State(st): State<Arc<AppState>>,
|
||||
headers: axum::http::HeaderMap,
|
||||
Path(table): Path<String>,
|
||||
Query(q): Query<FlashQuery>,
|
||||
) -> Response {
|
||||
if let Some(r) = admin_gate(&st) {
|
||||
if let Some(r) = admin_gate(&st, cookie_from_headers(&headers)) {
|
||||
return r;
|
||||
}
|
||||
let url = st.db_url.as_deref().unwrap();
|
||||
@@ -575,8 +728,12 @@ async fn admin_table(
|
||||
Html(admin_shell(&st, &table, Some(&table), &inner)).into_response()
|
||||
}
|
||||
|
||||
async fn admin_new_get(State(st): State<Arc<AppState>>, Path(table): Path<String>) -> Response {
|
||||
if let Some(r) = admin_gate(&st) {
|
||||
async fn admin_new_get(
|
||||
State(st): State<Arc<AppState>>,
|
||||
headers: axum::http::HeaderMap,
|
||||
Path(table): Path<String>,
|
||||
) -> Response {
|
||||
if let Some(r) = admin_gate(&st, cookie_from_headers(&headers)) {
|
||||
return r;
|
||||
}
|
||||
let url = st.db_url.as_deref().unwrap();
|
||||
@@ -603,10 +760,11 @@ async fn admin_new_get(State(st): State<Arc<AppState>>, Path(table): Path<String
|
||||
|
||||
async fn admin_new_post(
|
||||
State(st): State<Arc<AppState>>,
|
||||
headers: axum::http::HeaderMap,
|
||||
Path(table): Path<String>,
|
||||
Form(posted): Form<HashMap<String, String>>,
|
||||
) -> Response {
|
||||
if let Some(r) = admin_gate(&st) {
|
||||
if let Some(r) = admin_gate(&st, cookie_from_headers(&headers)) {
|
||||
return r;
|
||||
}
|
||||
let url = st.db_url.as_deref().unwrap();
|
||||
@@ -631,9 +789,10 @@ async fn admin_new_post(
|
||||
|
||||
async fn admin_edit_get(
|
||||
State(st): State<Arc<AppState>>,
|
||||
headers: axum::http::HeaderMap,
|
||||
Path((table, id)): Path<(String, String)>,
|
||||
) -> Response {
|
||||
if let Some(r) = admin_gate(&st) {
|
||||
if let Some(r) = admin_gate(&st, cookie_from_headers(&headers)) {
|
||||
return r;
|
||||
}
|
||||
let url = st.db_url.as_deref().unwrap();
|
||||
@@ -681,10 +840,11 @@ async fn admin_edit_get(
|
||||
|
||||
async fn admin_edit_post(
|
||||
State(st): State<Arc<AppState>>,
|
||||
headers: axum::http::HeaderMap,
|
||||
Path((table, id)): Path<(String, String)>,
|
||||
Form(posted): Form<HashMap<String, String>>,
|
||||
) -> Response {
|
||||
if let Some(r) = admin_gate(&st) {
|
||||
if let Some(r) = admin_gate(&st, cookie_from_headers(&headers)) {
|
||||
return r;
|
||||
}
|
||||
let url = st.db_url.as_deref().unwrap();
|
||||
@@ -709,9 +869,10 @@ async fn admin_edit_post(
|
||||
|
||||
async fn admin_delete(
|
||||
State(st): State<Arc<AppState>>,
|
||||
headers: axum::http::HeaderMap,
|
||||
Path((table, id)): Path<(String, String)>,
|
||||
) -> Response {
|
||||
if let Some(r) = admin_gate(&st) {
|
||||
if let Some(r) = admin_gate(&st, cookie_from_headers(&headers)) {
|
||||
return r;
|
||||
}
|
||||
let url = st.db_url.as_deref().unwrap();
|
||||
@@ -732,3 +893,29 @@ fn esc(s: &str) -> String {
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
}
|
||||
|
||||
/// WebSocket server endpoint: `echo=true` replies with each received text frame;
|
||||
/// otherwise it just drains frames (extension point for custom logic).
|
||||
async fn ws_upgrade(
|
||||
ws: axum::extract::WebSocketUpgrade,
|
||||
echo: bool,
|
||||
) -> Response {
|
||||
ws.on_upgrade(move |socket| ws_echo_loop(socket, echo))
|
||||
}
|
||||
|
||||
async fn ws_echo_loop(mut socket: axum::extract::ws::WebSocket, echo: bool) {
|
||||
use axum::extract::ws::Message;
|
||||
while let Some(Ok(msg)) = socket.recv().await {
|
||||
match msg {
|
||||
Message::Text(text) => {
|
||||
if echo {
|
||||
if socket.send(Message::Text(text)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Message::Close(_) => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
+235
-15
@@ -5,10 +5,13 @@ mod db;
|
||||
mod form;
|
||||
mod http;
|
||||
mod render;
|
||||
mod session;
|
||||
mod table;
|
||||
mod ws;
|
||||
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
use std::path::PathBuf;
|
||||
use std::ptr;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
@@ -138,6 +141,37 @@ fn call_lib(path: &str) -> Result<Value, String> {
|
||||
host_query_json("call_lib_path", &json!({ "path": path }))
|
||||
}
|
||||
|
||||
/// Absolute directory of the entry `.mq.md` (falls back to process cwd).
|
||||
fn entry_dir() -> PathBuf {
|
||||
host_query_json("entry_dir", &json!({}))
|
||||
.ok()
|
||||
.and_then(|v| v.as_str().map(|s| PathBuf::from(s)))
|
||||
.unwrap_or_else(|| {
|
||||
std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
|
||||
})
|
||||
}
|
||||
|
||||
/// `sqlite:` URL with a relative path → absolute against `entry_dir()`.
|
||||
fn resolve_db_url(url: &str) -> String {
|
||||
let stripped = url
|
||||
.strip_prefix("sqlite:")
|
||||
.or_else(|| url.strip_prefix("SQLITE:"))
|
||||
.unwrap_or(url);
|
||||
let abs = PathBuf::from(stripped);
|
||||
let abs = if abs.is_absolute() {
|
||||
abs
|
||||
} else {
|
||||
entry_dir().join(abs)
|
||||
};
|
||||
if stripped.len() == url.len() {
|
||||
abs.to_string_lossy().into_owned()
|
||||
} else if url.starts_with("sqlite:") {
|
||||
format!("sqlite:{}", abs.to_string_lossy())
|
||||
} else {
|
||||
format!("SQLITE:{}", abs.to_string_lossy())
|
||||
}
|
||||
}
|
||||
|
||||
fn arg_text(v: &Value, key: &str) -> Result<String, String> {
|
||||
match v.get(key) {
|
||||
None | Some(Value::Null) => Err(format!("missing `{key}`")),
|
||||
@@ -159,15 +193,22 @@ fn arg_str_opt<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
|
||||
}
|
||||
|
||||
fn db_url_of(args: &Value) -> Result<String, String> {
|
||||
if let Some(s) = arg_str_opt(args, "url").or_else(|| arg_str_opt(args, "db_url")) {
|
||||
return Ok(s.to_string());
|
||||
}
|
||||
if let Some(db) = args.get("db") {
|
||||
let raw = if let Some(s) = arg_str_opt(args, "url").or_else(|| arg_str_opt(args, "db_url"))
|
||||
{
|
||||
Some(s.to_string())
|
||||
} else if let Some(db) = args.get("db") {
|
||||
if let Some(s) = db.get("url").and_then(|v| v.as_str()) {
|
||||
return Ok(s.to_string());
|
||||
Some(s.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match raw {
|
||||
Some(s) => Ok(resolve_db_url(&s)),
|
||||
None => Err("missing db url".into()),
|
||||
}
|
||||
Err("missing db url".into())
|
||||
}
|
||||
|
||||
fn reply(out_json: *mut *mut c_char, err_msg: *mut *mut c_char, r: Result<Value, String>) -> c_int {
|
||||
@@ -354,6 +395,7 @@ web_ffi!(web_app_new, |args: &Value| {
|
||||
"admin": admin,
|
||||
"forms": {},
|
||||
"routes": {},
|
||||
"ws_routes": {},
|
||||
"static_dir": null,
|
||||
"static_mount": "/static",
|
||||
}))
|
||||
@@ -414,6 +456,101 @@ web_ffi!(web_app_route, |args: &Value| {
|
||||
Ok(app)
|
||||
});
|
||||
|
||||
web_ffi!(web_app_route_ws, |args: &Value| {
|
||||
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
||||
let path = normalize_route_path(arg_str(args, "path")?)?;
|
||||
let echo = match args.get("echo") {
|
||||
None | Some(Value::Null) => true,
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(Value::String(s)) => matches!(s.as_str(), "true" | "True" | "1" | "yes"),
|
||||
Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0,
|
||||
Some(_) => true,
|
||||
};
|
||||
let obj = app
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| "app must be a map".to_string())?;
|
||||
let ws_routes = obj
|
||||
.entry("ws_routes".to_string())
|
||||
.or_insert_with(|| json!({}));
|
||||
let wmap = ws_routes
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| "app.ws_routes must be a map".to_string())?;
|
||||
wmap.insert(path, json!(echo));
|
||||
Ok(app)
|
||||
});
|
||||
|
||||
web_ffi!(web_ws_connect, |args: &Value| {
|
||||
let url = arg_str(args, "url")?.to_string();
|
||||
let message = arg_str_opt(args, "message").unwrap_or("");
|
||||
let headers = args.get("headers");
|
||||
let timeout_sec = args
|
||||
.get("timeout_sec")
|
||||
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
||||
.unwrap_or(30);
|
||||
match crate::ws::connect(&url, message, headers, timeout_sec) {
|
||||
Ok(v) => Ok(v),
|
||||
Err(e) => Ok(json!({ "ok": false, "error": e })),
|
||||
}
|
||||
});
|
||||
|
||||
web_ffi!(web_session_new, |args: &Value| {
|
||||
session::abi_session_new(args)
|
||||
});
|
||||
|
||||
web_ffi!(web_session_set, |args: &Value| {
|
||||
session::abi_session_set(args)
|
||||
});
|
||||
|
||||
web_ffi!(web_session_get, |args: &Value| {
|
||||
session::abi_session_get(args)
|
||||
});
|
||||
|
||||
web_ffi!(web_session_del, |args: &Value| {
|
||||
session::abi_session_del(args)
|
||||
});
|
||||
|
||||
web_ffi!(web_session_destroy, |args: &Value| {
|
||||
session::abi_session_destroy(args)
|
||||
});
|
||||
|
||||
web_ffi!(web_auth_login, |args: &Value| {
|
||||
session::abi_auth_login(args)
|
||||
});
|
||||
|
||||
web_ffi!(web_auth_check, |args: &Value| {
|
||||
session::abi_auth_check(args)
|
||||
});
|
||||
|
||||
web_ffi!(web_auth_logout, |args: &Value| {
|
||||
session::abi_auth_logout(args)
|
||||
});
|
||||
|
||||
web_ffi!(web_auth_new, |args: &Value| {
|
||||
let users = args.get("users").cloned().unwrap_or(Value::Null);
|
||||
let session_ttl = args
|
||||
.get("session_ttl")
|
||||
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
||||
.unwrap_or(3600);
|
||||
Ok(json!({ "users": users, "session_ttl": session_ttl }))
|
||||
});
|
||||
|
||||
web_ffi!(web_app_auth, |args: &Value| {
|
||||
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
||||
let users = args.get("users").cloned().unwrap_or(Value::Null);
|
||||
let session_ttl = args
|
||||
.get("session_ttl")
|
||||
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
||||
.unwrap_or(3600);
|
||||
let obj = app
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| "app must be a map".to_string())?;
|
||||
obj.insert(
|
||||
"auth".to_string(),
|
||||
json!({ "users": users, "session_ttl": session_ttl }),
|
||||
);
|
||||
Ok(app)
|
||||
});
|
||||
|
||||
web_ffi!(web_app_mount_form, |args: &Value| {
|
||||
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
||||
let id = arg_str(args, "id")?.to_string();
|
||||
@@ -548,11 +685,20 @@ web_ffi!(web_db_table_info, |args: &Value| {
|
||||
web_ffi!(web_listen, |args: &Value| {
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
let (page, db_url, host, port, admin, forms, routes, static_dir, static_mount) = if args
|
||||
.get("page")
|
||||
.is_some()
|
||||
|| args.get("host").is_some()
|
||||
{
|
||||
let (
|
||||
page,
|
||||
db_url,
|
||||
host,
|
||||
port,
|
||||
admin,
|
||||
forms,
|
||||
routes,
|
||||
static_dir,
|
||||
static_mount,
|
||||
auth_users,
|
||||
session_ttl,
|
||||
ws_routes,
|
||||
) = 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();
|
||||
let host = arg_str_opt(args, "host").unwrap_or("127.0.0.1");
|
||||
@@ -568,6 +714,15 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
let static_mount = arg_str_opt(args, "static_mount")
|
||||
.unwrap_or("/static")
|
||||
.to_string();
|
||||
let auth_users = args
|
||||
.get("auth")
|
||||
.or_else(|| args.get("users"))
|
||||
.cloned()
|
||||
.filter(|v| !matches!(v, Value::Null));
|
||||
let session_ttl = args
|
||||
.get("session_ttl")
|
||||
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
||||
.unwrap_or(3600);
|
||||
(
|
||||
page,
|
||||
db_url,
|
||||
@@ -578,6 +733,9 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
HashMap::new(),
|
||||
static_dir,
|
||||
static_mount,
|
||||
auth_users,
|
||||
session_ttl,
|
||||
HashMap::new(),
|
||||
)
|
||||
} else {
|
||||
let app = args.get("app").cloned().unwrap_or_else(|| args.clone());
|
||||
@@ -587,7 +745,8 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
.and_then(|d| d.get("url"))
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string())
|
||||
.or_else(|| arg_str_opt(&app, "db_url").map(|s| s.to_string()));
|
||||
.or_else(|| arg_str_opt(&app, "db_url").map(|s| s.to_string()))
|
||||
.map(|s| resolve_db_url(&s));
|
||||
let host = app
|
||||
.get("host")
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -613,6 +772,17 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
routes.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
let mut ws_routes = HashMap::new();
|
||||
if let Some(obj) = app.get("ws_routes").and_then(|v| v.as_object()) {
|
||||
for (k, v) in obj {
|
||||
let echo = match v {
|
||||
Value::Bool(b) => *b,
|
||||
Value::String(s) => matches!(s.as_str(), "true" | "True" | "1" | "yes"),
|
||||
_ => true,
|
||||
};
|
||||
ws_routes.insert(k.clone(), echo);
|
||||
}
|
||||
}
|
||||
let static_dir = app
|
||||
.get("static_dir")
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -623,6 +793,28 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("/static")
|
||||
.to_string();
|
||||
// `auth` may hold the users table directly or `{users:…, ttl:…}`.
|
||||
let (auth_users, session_ttl) = match app.get("auth") {
|
||||
Some(Value::Object(m)) if m.contains_key("users") => (
|
||||
m.get("users").cloned(),
|
||||
m.get("ttl")
|
||||
.or_else(|| m.get("session_ttl"))
|
||||
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
||||
.unwrap_or(3600),
|
||||
),
|
||||
Some(other) if !matches!(other, Value::Null) => (
|
||||
Some(other.clone()),
|
||||
app.get("session_ttl")
|
||||
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
||||
.unwrap_or(3600),
|
||||
),
|
||||
_ => (
|
||||
None,
|
||||
app.get("session_ttl")
|
||||
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
||||
.unwrap_or(3600),
|
||||
),
|
||||
};
|
||||
(
|
||||
page,
|
||||
db_url,
|
||||
@@ -633,15 +825,16 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
routes,
|
||||
static_dir,
|
||||
static_mount,
|
||||
auth_users,
|
||||
session_ttl,
|
||||
ws_routes,
|
||||
)
|
||||
};
|
||||
let static_dir = static_dir.map(|p| {
|
||||
if p.is_absolute() {
|
||||
p
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.unwrap_or_else(|_| PathBuf::from("."))
|
||||
.join(p)
|
||||
entry_dir().join(p)
|
||||
}
|
||||
});
|
||||
http::listen(
|
||||
@@ -654,6 +847,9 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
routes,
|
||||
static_dir,
|
||||
&static_mount,
|
||||
auth_users,
|
||||
session_ttl,
|
||||
ws_routes,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -748,6 +944,30 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
web_form_from_schema as PluginFn,
|
||||
),
|
||||
("web_db_table_info", "url,table", web_db_table_info as PluginFn),
|
||||
("web_session_new", "ttl_sec", web_session_new as PluginFn),
|
||||
("web_session_set", "id,key,value", web_session_set as PluginFn),
|
||||
("web_session_get", "id,key", web_session_get as PluginFn),
|
||||
("web_session_del", "id,key", web_session_del as PluginFn),
|
||||
("web_session_destroy", "id", web_session_destroy as PluginFn),
|
||||
(
|
||||
"web_auth_login",
|
||||
"username,password,users,session_ttl",
|
||||
web_auth_login as PluginFn,
|
||||
),
|
||||
("web_auth_check", "session_id", web_auth_check as PluginFn),
|
||||
("web_auth_logout", "session_id", web_auth_logout 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),
|
||||
(
|
||||
"web_app_route_ws",
|
||||
"app,path,echo",
|
||||
web_app_route_ws as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_ws_connect",
|
||||
"url,message,headers,timeout_sec",
|
||||
web_ws_connect as PluginFn,
|
||||
),
|
||||
("web_listen", "app", web_listen as PluginFn),
|
||||
];
|
||||
for (name, params, f) in regs {
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
//! In-memory session store + cookie helpers (design ext-web-net §3.1 / §3.2).
|
||||
//!
|
||||
//! 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`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
type SessionMap = HashMap<String, Value>;
|
||||
struct Store {
|
||||
ttl_sec: u64,
|
||||
data: HashMap<String, (u64, SessionMap)>,
|
||||
}
|
||||
|
||||
static STORE: Mutex<Option<Store>> = Mutex::new(None);
|
||||
|
||||
fn now_secs() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.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,
|
||||
data: HashMap::new(),
|
||||
});
|
||||
f(store)
|
||||
}
|
||||
|
||||
fn prune(store: &mut Store) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
prune(store);
|
||||
let id = random_id();
|
||||
let exp = now_secs() + store.ttl_sec;
|
||||
store.data.insert(id.clone(), (exp, SessionMap::new()));
|
||||
id
|
||||
})
|
||||
}
|
||||
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
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()
|
||||
})
|
||||
}
|
||||
|
||||
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()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn session_destroy(id: &str) -> bool {
|
||||
with_store(|store| {
|
||||
prune(store);
|
||||
store.data.remove(id).is_some()
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse the session id from a `Cookie` request header (looks for `marqdo_sid=…`).
|
||||
pub fn session_id_from_cookie(cookie_header: Option<&str>) -> Option<String> {
|
||||
let header = cookie_header?;
|
||||
for part in header.split(';') {
|
||||
let part = part.trim();
|
||||
if let Some(v) = part.strip_prefix("marqdo_sid=") {
|
||||
let v = v.trim_matches('"');
|
||||
if !v.is_empty() {
|
||||
return Some(v.to_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!(
|
||||
"marqdo_sid={id}; HttpOnly; Path=/; SameSite=Lax; Max-Age={ttl_sec}"
|
||||
)
|
||||
}
|
||||
|
||||
/// Validate `username`/`password` against an admin-users table (`|用户名|密码|`
|
||||
/// with headers `username`/`密码` or `用户`/`密码`, or plain `username`/`password`).
|
||||
/// Returns the matched username on success.
|
||||
pub fn check_credentials(users: &Value, username: &str, password: &str) -> Option<String> {
|
||||
let rows = match users {
|
||||
Value::Array(a) => a,
|
||||
_ => return None,
|
||||
};
|
||||
for row in rows {
|
||||
let m = match row {
|
||||
Value::Object(m) => m,
|
||||
_ => continue,
|
||||
};
|
||||
let u = pick_cell(m, &["用户名", "用户", "username", "user", "账号"])
|
||||
.map(cell_str)
|
||||
.unwrap_or_default();
|
||||
let p = pick_cell(m, &["密码", "password", "pass", "口令"])
|
||||
.map(cell_str)
|
||||
.unwrap_or_default();
|
||||
if u == username && p == password {
|
||||
return Some(u);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn pick_cell<'a>(m: &'a Map<String, Value>, keys: &[&str]) -> Option<&'a Value> {
|
||||
keys.iter().find_map(|k| m.get(*k))
|
||||
}
|
||||
|
||||
fn cell_str(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(),
|
||||
}
|
||||
}
|
||||
|
||||
/// ABI helpers.
|
||||
pub fn abi_session_new(args: &Value) -> Result<Value, String> {
|
||||
let ttl = args
|
||||
.get("ttl_sec")
|
||||
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)));
|
||||
let id = session_new(ttl);
|
||||
Ok(json!({ "id": id }))
|
||||
}
|
||||
|
||||
pub fn abi_session_set(args: &Value) -> Result<Value, String> {
|
||||
let id = arg_str(args, "id")?;
|
||||
let key = arg_str(args, "key")?;
|
||||
let value = args.get("value").cloned().unwrap_or(Value::Null);
|
||||
Ok(json!({ "ok": session_set(id, key, value) }))
|
||||
}
|
||||
|
||||
pub fn abi_session_get(args: &Value) -> Result<Value, String> {
|
||||
let id = arg_str(args, "id")?;
|
||||
let key = arg_str(args, "key")?;
|
||||
match session_get(id, key) {
|
||||
Some(v) => Ok(json!({ "ok": true, "value": v })),
|
||||
None => Ok(json!({ "ok": false })),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn abi_session_del(args: &Value) -> Result<Value, String> {
|
||||
let id = arg_str(args, "id")?;
|
||||
let key = arg_str(args, "key")?;
|
||||
Ok(json!({ "ok": session_del(id, key) }))
|
||||
}
|
||||
|
||||
pub fn abi_session_destroy(args: &Value) -> Result<Value, String> {
|
||||
let id = arg_str(args, "id")?;
|
||||
Ok(json!({ "ok": session_destroy(id) }))
|
||||
}
|
||||
|
||||
pub fn abi_auth_login(args: &Value) -> Result<Value, String> {
|
||||
let username = arg_str(args, "username")?;
|
||||
let password = arg_str(args, "password")?;
|
||||
let users = args.get("users").cloned().unwrap_or(Value::Null);
|
||||
let ttl = args
|
||||
.get("session_ttl")
|
||||
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)));
|
||||
match check_credentials(&users, username, password) {
|
||||
Some(_) => {
|
||||
let id = session_new(ttl);
|
||||
session_set(&id, "username", json!(username));
|
||||
Ok(json!({ "ok": true, "session_id": id, "username": username }))
|
||||
}
|
||||
None => Ok(json!({ "ok": false })),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn abi_auth_check(args: &Value) -> Result<Value, String> {
|
||||
let id = arg_str(args, "session_id")?;
|
||||
match session_get(id, "username") {
|
||||
Some(Value::String(u)) => Ok(json!({ "ok": true, "username": u })),
|
||||
_ => Ok(json!({ "ok": false })),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn abi_auth_logout(args: &Value) -> Result<Value, String> {
|
||||
let id = arg_str(args, "session_id")?;
|
||||
Ok(json!({ "ok": session_destroy(id) }))
|
||||
}
|
||||
|
||||
fn arg_str<'a>(v: &'a Value, key: &str) -> Result<&'a str, String> {
|
||||
v.get(key)
|
||||
.and_then(|x| x.as_str())
|
||||
.ok_or_else(|| format!("missing `{key}`"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn users() -> Value {
|
||||
json!([
|
||||
{ "username": "admin", "password": "secret" },
|
||||
{ "用户": "站长", "密码": "pw123" }
|
||||
])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_set_get_del() {
|
||||
reset(3600);
|
||||
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!(session_del(&id, "username"));
|
||||
assert_eq!(session_get(&id, "username"), None);
|
||||
assert!(session_destroy(&id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_login_check_logout() {
|
||||
reset(3600);
|
||||
let r = abi_auth_login(&json!({
|
||||
"username": "admin",
|
||||
"password": "secret",
|
||||
"users": users(),
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(r["ok"].as_bool(), Some(true));
|
||||
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",
|
||||
"password": "wrong",
|
||||
"users": users(),
|
||||
}))
|
||||
.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 cookie_roundtrip() {
|
||||
reset(3600);
|
||||
let id = session_new(None);
|
||||
let cookie = session_cookie(&id, 3600);
|
||||
assert!(cookie.starts_with("marqdo_sid="));
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -253,19 +253,19 @@ pub fn as_compose(table: &Value) -> Value {
|
||||
fn infer_slot(src: &str) -> String {
|
||||
let base = src.rsplit('.').next().unwrap_or(src);
|
||||
match base {
|
||||
"nav" | "links" => "nav".into(),
|
||||
"side" | "sidebar" => "sidebar".into(),
|
||||
"foot" | "footer" => "footer".into(),
|
||||
"nav" | "links" | "导航" => "nav".into(),
|
||||
"side" | "sidebar" | "侧栏" => "sidebar".into(),
|
||||
"foot" | "footer" | "页脚" => "footer".into(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn normalize_slot(name: &str) -> String {
|
||||
match name {
|
||||
"nav" | "links" => "nav".into(),
|
||||
"side" | "sidebar" => "sidebar".into(),
|
||||
"foot" | "footer" => "footer".into(),
|
||||
"main" | "index" | "" => "main".into(),
|
||||
"nav" | "links" | "导航" => "nav".into(),
|
||||
"side" | "sidebar" | "侧栏" => "sidebar".into(),
|
||||
"foot" | "footer" | "页脚" => "footer".into(),
|
||||
"main" | "index" | "" | "主体" => "main".into(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
//! WebSocket client primitive (design ext-web-net §3.4).
|
||||
//!
|
||||
//! Single request–response style: connect, send one text `message`, collect all
|
||||
//! server text replies until close, then return `{ok, messages}`.
|
||||
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde_json::{json, Value};
|
||||
use tokio_tungstenite::tungstenite::http::header::HeaderName;
|
||||
|
||||
/// Convert `headers` (a JSON map) into tungstenite header pairs.
|
||||
fn headers_from_value(headers: Option<&Value>) -> Vec<(HeaderName, String)> {
|
||||
let Some(h) = headers else {
|
||||
return Vec::new();
|
||||
};
|
||||
match h {
|
||||
Value::Object(m) => m
|
||||
.iter()
|
||||
.filter_map(|(k, v)| {
|
||||
HeaderName::from_bytes(k.as_bytes())
|
||||
.ok()
|
||||
.map(|hn| (hn, v.as_str().unwrap_or("").to_string()))
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect to a WebSocket URL, send `message`, drain text replies until close.
|
||||
pub fn connect(
|
||||
url: &str,
|
||||
message: &str,
|
||||
headers: Option<&Value>,
|
||||
timeout_sec: u64,
|
||||
) -> Result<Value, String> {
|
||||
if !(url.starts_with("ws://") || url.starts_with("wss://")) {
|
||||
return Err("ws url must start with ws:// or wss://".into());
|
||||
}
|
||||
|
||||
let hdrs = headers_from_value(headers);
|
||||
let mut builder = tokio_tungstenite::tungstenite::client::IntoClientRequest::into_client_request(
|
||||
url.to_string(),
|
||||
)
|
||||
.map_err(|e| format!("bad ws url: {e}"))?;
|
||||
for (hn, v) in &hdrs {
|
||||
builder
|
||||
.headers_mut()
|
||||
.insert(hn.clone(), v.parse().map_err(|e| format!("bad header value: {e}"))?);
|
||||
}
|
||||
|
||||
let rt = tokio::runtime::Runtime::new().map_err(|e| e.to_string())?;
|
||||
rt.block_on(async move {
|
||||
let timeout = tokio::time::Duration::from_secs(timeout_sec.max(1));
|
||||
let fut = tokio_tungstenite::connect_async(builder);
|
||||
let (mut socket, _resp) = tokio::time::timeout(timeout, fut)
|
||||
.await
|
||||
.map_err(|_| "ws connect timeout".to_string())?
|
||||
.map_err(|e| format!("ws connect: {e}"))?;
|
||||
|
||||
let send = tokio_tungstenite::tungstenite::Message::Text(message.to_string());
|
||||
socket
|
||||
.send(send)
|
||||
.await
|
||||
.map_err(|e| format!("ws send: {e}"))?;
|
||||
|
||||
let mut messages = Vec::new();
|
||||
loop {
|
||||
match tokio::time::timeout(timeout, socket.next()).await {
|
||||
Ok(Some(Ok(tokio_tungstenite::tungstenite::Message::Text(t)))) => {
|
||||
messages.push(t.to_string());
|
||||
}
|
||||
Ok(Some(Ok(tokio_tungstenite::tungstenite::Message::Close(_))))
|
||||
| Ok(Some(Err(_))) => break,
|
||||
Ok(None) => break,
|
||||
Ok(Some(Ok(_))) => {}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
Ok(json!({ "ok": true, "messages": messages }))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
#[test]
|
||||
fn echo_roundtrip() {
|
||||
let rt = tokio::runtime::Runtime::new().expect("rt");
|
||||
let listener = rt.block_on(async { TcpListener::bind("127.0.0.1:0").await.expect("bind") });
|
||||
let addr = listener.local_addr().expect("addr");
|
||||
let server = std::thread::spawn(move || {
|
||||
let rt = tokio::runtime::Runtime::new().expect("server rt");
|
||||
rt.block_on(async move {
|
||||
let (stream, _) = listener.accept().await.expect("accept");
|
||||
let ws = tokio_tungstenite::accept_async(stream).await.expect("ws");
|
||||
let (mut sink, mut source) = ws.split();
|
||||
if let Some(Ok(Message::Text(t))) = source.next().await {
|
||||
let _ = sink.send(Message::Text(t)).await;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
let url = format!("ws://{addr}/");
|
||||
let got = connect(&url, "ping", None, 5).expect("connect");
|
||||
assert_eq!(got["ok"], true);
|
||||
assert_eq!(got["messages"], json!(["ping"]));
|
||||
server.join().expect("server join");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_bad_url() {
|
||||
let err = connect("http://127.0.0.1:1", "hi", None, 1).unwrap_err();
|
||||
assert!(err.contains("ws://") || err.contains("ws url"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_connection() {
|
||||
// Connect to a port that is closed; connect_async fails fast.
|
||||
let rt = tokio::runtime::Runtime::new().expect("rt");
|
||||
let listener = rt.block_on(async { TcpListener::bind("127.0.0.1:0").await.expect("bind") });
|
||||
let addr = listener.local_addr().expect("addr");
|
||||
drop(listener); // port now closed
|
||||
let url = format!("ws://{addr}/");
|
||||
let err = connect(&url, "hi", None, 2).unwrap_err();
|
||||
assert!(
|
||||
err.starts_with("ws connect") || err.contains("timeout"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user