Release 2.7.0: executable handbooks and native user-site workflows
This commit is contained in:
1 parent
aa0c4d0f55
commit
d9aef957f7
562 files changed
+21064
-20387
No files matched your search
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "marqdo_plugin_engineering"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "Apache-2.0"
|
||||
description = "OS, authenticated service and archive boundaries for executable Marqdo engineering handbooks"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
name = "engineering"
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
marqdo-plugin-sdk = { path = "../../crates/marqdo-plugin-sdk" }
|
||||
serde_json = "1"
|
||||
ureq = { version = "=2.9.7", default-features = false, features = ["tls", "gzip"] }
|
||||
sha2 = "=0.10.9"
|
||||
hmac = "=0.12.1"
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
|
||||
zip = { version = "=0.6.6", default-features = false, features = ["deflate"] }
|
||||
libc = "0.2"
|
||||
flate2 = "1"
|
||||
base64 = "0.22"
|
||||
|
||||
# Reuse the real compiler for source analysis; no second syntax recognizer.
|
||||
marqdo = { path = "../.." }
|
||||
@@ -0,0 +1,611 @@
|
||||
//! Native boundaries for executable engineering documents. Business ordering,
|
||||
//! version decisions and ordinary file reads/writes belong in .mq.md.
|
||||
//! No Python interpreter, generated shell program or secret-valued tool result.
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
ffi::CStr,
|
||||
fs::{self, File},
|
||||
io::{Read, Write},
|
||||
os::raw::{c_char, c_int},
|
||||
path::{Component, Path, PathBuf},
|
||||
process::{Command, Stdio},
|
||||
sync::mpsc,
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use hmac::{Hmac, Mac};
|
||||
use marqdo_plugin_sdk::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
type Answer = Result<Value, String>;
|
||||
const OUTPUT: usize = 256 * 1024;
|
||||
const HTTP_MAX: u64 = 16 * 1024 * 1024;
|
||||
fn field<'a>(v: &'a Value, key: &str) -> Result<&'a str, String> {
|
||||
v.get(key).and_then(Value::as_str).ok_or_else(|| format!("missing text field {key}"))
|
||||
}
|
||||
fn hash(b: &[u8]) -> String { hex(&Sha256::digest(b)) }
|
||||
fn hex(b: &[u8]) -> String { b.iter().map(|x| format!("{x:02x}")).collect() }
|
||||
fn read_bounded(mut r: impl Read, max: u64) -> Result<Vec<u8>, String> {
|
||||
let mut b = Vec::new();
|
||||
r.by_ref().take(max + 1).read_to_end(&mut b).map_err(|e| format!("read failed ({:?})",e.kind()))?;
|
||||
if b.len() as u64 > max { return Err("bounded input limit exceeded".into()); }
|
||||
Ok(b)
|
||||
}
|
||||
fn scoped(root: &Path, relative: &str) -> Result<PathBuf, String> {
|
||||
let p = root.join(relative).canonicalize().map_err(|_| "path does not exist")?;
|
||||
if !p.starts_with(root) { return Err("artifact path escapes the selected root".into()); }
|
||||
Ok(p)
|
||||
}
|
||||
fn homes(root: &Path) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
for key in ["MARQDO_RELEASE_CREDENTIAL_HOME", "USERPROFILE", "HOME"] {
|
||||
if let Some(s) = std::env::var_os(key) { out.push(PathBuf::from(s)); }
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
for p in std::iter::once(root).chain(root.ancestors().skip(1)) {
|
||||
if p.join(".git").exists() {
|
||||
if let Ok(m) = p.metadata() {
|
||||
unsafe {
|
||||
let mut entry: libc::passwd = std::mem::zeroed();
|
||||
let mut result = std::ptr::null_mut();
|
||||
let mut buf = vec![0u8; 32768];
|
||||
if libc::getpwuid_r(m.uid(), &mut entry, buf.as_mut_ptr().cast(), buf.len(), &mut result) == 0
|
||||
&& !result.is_null() && !entry.pw_dir.is_null() {
|
||||
out.push(PathBuf::from(CStr::from_ptr(entry.pw_dir).to_string_lossy().into_owned()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
fn redact(mut text: String, private: &[String]) -> String {
|
||||
for token in private.iter().filter(|s| !s.is_empty()) { text = text.replace(token, "<secret>"); }
|
||||
for (k, v) in std::env::vars() {
|
||||
if v.len() >= 8 && ["TOKEN", "SECRET", "PASSWORD", "ACCESS_KEY"].iter().any(|x| k.contains(x)) {
|
||||
text = text.replace(&v, "<secret>");
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
struct Output { code: i32, stdout: String, stderr: String, timed_out: bool, truncated: bool }
|
||||
fn pipe(mut input: impl Read + Send + 'static, limit: usize) -> mpsc::Receiver<(Vec<u8>, bool)> {
|
||||
let (send, recv) = mpsc::channel();
|
||||
thread::spawn(move || {
|
||||
let mut buf = Vec::new(); let mut part = [0u8; 8192]; let mut truncated = false;
|
||||
while let Ok(n) = input.read(&mut part) {
|
||||
if n == 0 { break; }
|
||||
let keep = (limit - buf.len()).min(n);
|
||||
buf.extend_from_slice(&part[..keep]); truncated |= keep < n;
|
||||
}
|
||||
let _ = send.send((buf, truncated));
|
||||
});
|
||||
recv
|
||||
}
|
||||
fn execute(root: &Path, argv: &[String], input: Option<String>, env: &BTreeMap<String, String>,
|
||||
timeout_ms: u64, max_output: usize) -> Result<Output, String> {
|
||||
if argv.is_empty() || argv[0].is_empty() { return Err("argv must not be empty".into()); }
|
||||
if !(1..=3_600_000).contains(&timeout_ms) || !(1..=16_777_216).contains(&max_output) {
|
||||
return Err("timeout/output limit outside supported range".into());
|
||||
}
|
||||
let mut cmd = Command::new(&argv[0]);
|
||||
cmd.args(&argv[1..]).current_dir(root).envs(env)
|
||||
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
#[cfg(unix)] {
|
||||
use std::os::unix::process::CommandExt;
|
||||
unsafe { cmd.pre_exec(|| {
|
||||
if libc::setpgid(0, 0) != 0 { return Err(std::io::Error::last_os_error()); }
|
||||
Ok(())
|
||||
}); }
|
||||
}
|
||||
let mut child = cmd.spawn().map_err(|_| format!("cannot start {}", argv[0]))?;
|
||||
let stdout = pipe(child.stdout.take().unwrap(), max_output);
|
||||
let stderr = pipe(child.stderr.take().unwrap(), max_output);
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
thread::spawn(move || { if let Some(text) = input { let _ = stdin.write_all(text.as_bytes()); } });
|
||||
let started = Instant::now(); let mut timed_out = false;
|
||||
let code = loop {
|
||||
match child.try_wait().map_err(|_| "cannot observe process")? {
|
||||
Some(status) => break status.code().unwrap_or(1),
|
||||
None if started.elapsed() >= Duration::from_millis(timeout_ms) => {
|
||||
timed_out = true;
|
||||
#[cfg(unix)] unsafe { libc::kill(-(child.id() as i32), libc::SIGKILL); }
|
||||
#[cfg(windows)] { let _ = Command::new("taskkill").args(["/PID", &child.id().to_string(), "/T", "/F"]).output(); }
|
||||
let _ = child.kill(); let _ = child.wait(); break 124;
|
||||
}
|
||||
None => thread::sleep(Duration::from_millis(10)),
|
||||
}
|
||||
};
|
||||
// Descendants retaining inherited pipes must not prevent a bounded return.
|
||||
let (out, out_clip) = stdout.recv_timeout(Duration::from_secs(1)).unwrap_or((Vec::new(), true));
|
||||
let (err, err_clip) = stderr.recv_timeout(Duration::from_secs(1)).unwrap_or((Vec::new(), true));
|
||||
Ok(Output { code, stdout: String::from_utf8_lossy(&out).into(), stderr: String::from_utf8_lossy(&err).into(),
|
||||
timed_out, truncated: out_clip || err_clip })
|
||||
}
|
||||
fn github_token(root: &Path) -> Option<String> {
|
||||
for key in ["GH_TOKEN", "GITHUB_TOKEN"] {
|
||||
if let Ok(s) = std::env::var(key) { if !s.is_empty() { return Some(s); } }
|
||||
}
|
||||
let args = ["git", "-c", &format!("safe.directory={}", root.display()), "credential", "fill"]
|
||||
.into_iter().map(str::to_string).collect::<Vec<_>>();
|
||||
let env = BTreeMap::from([("GIT_TERMINAL_PROMPT".into(), "0".into())]);
|
||||
if let Ok(p) = execute(root, &args, Some("protocol=https\nhost=github.com\n\n".into()), &env, 15_000, OUTPUT) {
|
||||
if let Some(s) = p.stdout.lines().find_map(|s| s.strip_prefix("password=")) { return Some(s.into()); }
|
||||
}
|
||||
for home in homes(root) {
|
||||
if let Ok(text) = fs::read_to_string(home.join(".config/gh/hosts.yml")) {
|
||||
if let Some(s) = text.lines().find_map(|s| s.trim().strip_prefix("oauth_token:")) {
|
||||
return Some(s.trim().trim_matches(['"', '\'']).into());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn git_config(env: &mut BTreeMap<String,String>, key: &str, value: String) {
|
||||
let start = env.get("GIT_CONFIG_COUNT").cloned().or_else(|| std::env::var("GIT_CONFIG_COUNT").ok())
|
||||
.and_then(|s| s.parse::<usize>().ok()).unwrap_or(0);
|
||||
env.insert(format!("GIT_CONFIG_KEY_{start}"),key.into());
|
||||
env.insert(format!("GIT_CONFIG_VALUE_{start}"),value);
|
||||
env.insert("GIT_CONFIG_COUNT".into(),(start+1).to_string());
|
||||
}
|
||||
|
||||
fn command(root: &Path, p: &Value) -> Answer {
|
||||
let mut argv = p.get("argv").and_then(Value::as_array).ok_or("argv must be a list")?
|
||||
.iter().map(|v| v.as_str().map(str::to_string).ok_or("argv items must be text".to_string()))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let cwd = scoped(root, p.get("cwd").and_then(Value::as_str).unwrap_or("."))?;
|
||||
let mut env = BTreeMap::new(); let mut private = Vec::new();
|
||||
// Trust only the explicitly selected workspace, only in this child tree.
|
||||
// Cargo/Go VCS probes inherit the same scoped Git metadata access.
|
||||
git_config(&mut env,"safe.directory",root.display().to_string());
|
||||
let exe = argv.first().and_then(|s| Path::new(s).file_stem()).and_then(|s| s.to_str()).unwrap_or("");
|
||||
if ["bash", "sh", "pwsh", "powershell"].contains(&exe) && argv.iter().any(|s| ["-c", "-Command", "-EncodedCommand"].contains(&s.as_str())) {
|
||||
return Err("use argument vectors or maintained external scripts, not generated shell programs".into());
|
||||
}
|
||||
if exe == "git" {
|
||||
if argv.iter().any(|s| ["--force", "-f", "--force-with-lease", "--no-verify"].contains(&s.as_str()) || s.starts_with("--force=")) {
|
||||
return Err("forced Git updates and hook bypass are forbidden".into());
|
||||
}
|
||||
argv.splice(1..1, ["-c".into(), format!("safe.directory={}", cwd.display())]);
|
||||
env.insert("GIT_TERMINAL_PROMPT".into(), "0".into());
|
||||
if argv.iter().any(|s| ["fetch", "push", "ls-remote"].contains(&s.as_str())) {
|
||||
if let Some(token) = github_token(root) {
|
||||
// URL-scoped headers stay in the child environment, not argv.
|
||||
let auth = format!("Authorization: Basic {}", base64(format!("x-access-token:{token}").as_bytes()));
|
||||
for url in ["https://proxy.cflmy.top/github.com/", "https://github.com/"] {
|
||||
git_config(&mut env,&format!("http.{url}.extraheader"),auth.clone());
|
||||
}
|
||||
private.push(token); private.push(auth);
|
||||
argv.splice(1..1, ["-c".into(), "http.version=HTTP/1.1".into(), "-c".into(), "http.postBuffer=524288000".into()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(e) = p.get("env").and_then(Value::as_object) {
|
||||
for (k, v) in e { env.insert(k.clone(), v.as_str().ok_or("env values must be text")?.into()); }
|
||||
}
|
||||
// Child Git trace output could expose internally attached authentication.
|
||||
for key in ["GIT_TRACE", "GIT_TRACE_CURL", "GIT_CURL_VERBOSE"] { env.insert(key.into(), "0".into()); }
|
||||
let timeout = p.get("timeout_ms").and_then(Value::as_u64)
|
||||
.unwrap_or_else(|| p.get("timeout").and_then(Value::as_u64).unwrap_or(120) * 1000);
|
||||
let max = p.get("max_output").and_then(Value::as_u64).unwrap_or(OUTPUT as u64) as usize;
|
||||
let out = execute(&cwd, &argv, p.get("stdin").and_then(Value::as_str).map(str::to_string), &env, timeout, max)?;
|
||||
Ok(json!({"code":out.code,"stdout":redact(out.stdout,&private),"stderr":redact(out.stderr,&private),
|
||||
"timed_out":out.timed_out,"truncated":out.truncated}))
|
||||
}
|
||||
fn http_json(root: &Path, p: &Value) -> Answer {
|
||||
let path = field(p, "path")?;
|
||||
if !path.starts_with("/repos/cflmy/marqdo/") || path.contains("..") { return Err("GitHub path is outside the project".into()); }
|
||||
let method = p.get("method").and_then(Value::as_str).unwrap_or("GET");
|
||||
if !["GET", "PATCH", "POST"].contains(&method) { return Err("unsupported GitHub method".into()); }
|
||||
let bases = std::env::var("MARQDO_RELEASE_API_BASE").map(|s| vec![s])
|
||||
.unwrap_or_else(|_| vec!["https://proxy.cflmy.top/api.github.com".into(), "https://api.github.com".into()]);
|
||||
let token = github_token(root);
|
||||
for (i, base) in bases.iter().enumerate() {
|
||||
let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(35)).build();
|
||||
let url = format!("{}{path}", base.trim_end_matches('/'));
|
||||
let mut req = agent.request(method, &url).set("Accept", "application/vnd.github+json")
|
||||
.set("User-Agent", "marqdo-engineering/1").set("X-GitHub-Api-Version", "2022-11-28");
|
||||
if let Some(token) = &token { req = req.set("Authorization", &format!("Bearer {token}")); }
|
||||
let response = if let Some(body) = p.get("data").filter(|v| !v.is_null()) {
|
||||
req.set("Content-Type", "application/json").send_string(&body.to_string())
|
||||
} else { req.call() };
|
||||
match response {
|
||||
Ok(r) => {
|
||||
let body = read_bounded(r.into_reader(), HTTP_MAX)
|
||||
.and_then(|bytes| serde_json::from_slice(&bytes).map_err(|_| "GitHub response is not JSON".into()));
|
||||
match body {
|
||||
Ok(value) => return Ok(value),
|
||||
Err(_) if method != "POST" && i + 1 < bases.len() => continue,
|
||||
Err(message) => return Err(message),
|
||||
}
|
||||
}
|
||||
Err(ureq::Error::Status(404,_)) if p.get("missing").and_then(Value::as_bool).unwrap_or(false) => return Ok(Value::Null),
|
||||
Err(ureq::Error::Status(code,_)) => {
|
||||
if method == "POST" || i + 1 == bases.len() || ![429,500,502,503,504].contains(&code) {
|
||||
return Err(format!("GitHub HTTP {code}"));
|
||||
}
|
||||
}
|
||||
Err(_) if method == "POST" || i + 1 == bases.len() => return Err("GitHub network request failed; uncertain mutations are not replayed".into()),
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
Err("GitHub request failed after proxy and direct routes".into())
|
||||
}
|
||||
fn archive(root: &Path, p: &Value) -> Answer {
|
||||
let path = scoped(root, field(p,"path")?)?;
|
||||
let file = File::open(path).map_err(|_|"cannot open archive")?;
|
||||
let mut zip = zip::ZipArchive::new(file).map_err(|_|"invalid ZIP")?;
|
||||
if zip.len() > 100000 { return Err("ZIP has too many entries".into()); }
|
||||
let mut seen=std::collections::HashSet::new();
|
||||
let mut entries = Vec::new(); let mut metadata = serde_json::Map::new(); let mut total = 0u64; let mut actual = 0u64;
|
||||
for i in 0..zip.len() {
|
||||
let mut f = zip.by_index(i).map_err(|_|"cannot read ZIP entry")?;
|
||||
let name = f.name().replace('\\', "/");
|
||||
if !seen.insert(name.clone()) || name.as_bytes().get(1)==Some(&b':') {return Err("duplicate or drive-qualified ZIP path".into());}
|
||||
if Path::new(&name).components().any(|c| matches!(c, Component::ParentDir | Component::RootDir | Component::Prefix(_))) {
|
||||
return Err("unsafe ZIP path".into());
|
||||
}
|
||||
if f.unix_mode().is_some_and(|m|m & 0o170000 == 0o120000) { return Err("ZIP symlink is not supported".into()); }
|
||||
total = total.checked_add(f.size()).ok_or("ZIP expansion overflow")?;
|
||||
if total > 2 * 1024 * 1024 * 1024 { return Err("ZIP expands beyond 2 GiB".into()); }
|
||||
let mut selected = Vec::new();
|
||||
let keep = ["VERSION","ext/VERSION","Cargo.toml","extension/package.json"].contains(&name.as_str());
|
||||
let mut buf=[0u8;65536];
|
||||
loop {
|
||||
let n=f.read(&mut buf).map_err(|_|"ZIP content/CRC validation failed")?;
|
||||
if n==0 {break;}
|
||||
actual = actual.checked_add(n as u64).ok_or("ZIP expansion overflow")?;
|
||||
if actual > 2 * 1024 * 1024 * 1024 { return Err("ZIP expands beyond 2 GiB".into()); }
|
||||
if keep && selected.len()<16384 {selected.extend_from_slice(&buf[..n.min(16384-selected.len())]);}
|
||||
}
|
||||
if keep { metadata.insert(name.clone(),json!(String::from_utf8(selected).map_err(|_|"ZIP metadata is not UTF-8")?)); }
|
||||
entries.push(name);
|
||||
}
|
||||
Ok(json!({"entries":entries,"metadata":metadata}))
|
||||
}
|
||||
fn hmac(key:&[u8], data:&str)->Vec<u8> {
|
||||
let mut mac=Hmac::<Sha256>::new_from_slice(key).expect("HMAC accepts all key lengths");
|
||||
mac.update(data.as_bytes());mac.finalize().into_bytes().to_vec()
|
||||
}
|
||||
fn r2_settings(root:&Path)->Result<BTreeMap<String,String>,String> {
|
||||
let mut settings=std::env::vars().filter(|(k,_)|k.starts_with("R2_")).collect::<BTreeMap<_,_>>();
|
||||
for home in homes(root) {
|
||||
if let Ok(text)=fs::read_to_string(home.join(".marqdo/r2.env")) {
|
||||
for line in text.lines().map(str::trim).filter(|s|!s.starts_with('#')) {
|
||||
if let Some((k,v))=line.split_once('=') {settings.entry(k.trim().into()).or_insert_with(||v.trim().trim_matches(['\'','"']).into());}
|
||||
}
|
||||
}
|
||||
}
|
||||
for k in ["R2_ENDPOINT","R2_BUCKET","R2_ACCESS_KEY_ID","R2_SECRET_ACCESS_KEY"] {
|
||||
if settings.get(k).is_none_or(String::is_empty) {return Err(format!("missing {k}; configure ~/.marqdo/r2.env"));}
|
||||
}
|
||||
Ok(settings)
|
||||
}
|
||||
fn r2_put(root:&Path,p:&Value)->Answer {
|
||||
let s=r2_settings(root)?;
|
||||
let key=field(p,"key")?;
|
||||
if !key.bytes().all(|b|b.is_ascii_alphanumeric() || b"/.-_".contains(&b)) || key.contains("..") {
|
||||
return Err("unsafe R2 key".into());
|
||||
}
|
||||
let body=if let Some(path)=p.get("path").and_then(Value::as_str) {
|
||||
read_bounded(File::open(scoped(root,path)?).map_err(|_|"cannot open upload")?,256*1024*1024)?
|
||||
} else {field(p,"text")?.as_bytes().to_vec()};
|
||||
let digest=hash(&body);
|
||||
if let Some(expected)=p.get("sha256").and_then(Value::as_str) {
|
||||
if digest!=expected {return Err("upload bytes changed after verification".into());}
|
||||
}
|
||||
let endpoint=s["R2_ENDPOINT"].trim_end_matches('/');
|
||||
let host=endpoint.split_once("://").ok_or("R2 endpoint needs a scheme")?.1;
|
||||
if host.contains('/') || !(endpoint.starts_with("https://") || endpoint.starts_with("http://127.0.0.1:")) {
|
||||
return Err("R2 endpoint must be HTTPS (loopback HTTP is for isolated tests)".into());
|
||||
}
|
||||
let uri=format!("/{}/{key}",s["R2_BUCKET"]);
|
||||
let date=chrono::Utc::now();let amz=date.format("%Y%m%dT%H%M%SZ").to_string();let day=date.format("%Y%m%d").to_string();
|
||||
let region=s.get("R2_REGION").map(String::as_str).unwrap_or("auto");
|
||||
let mime=if key.ends_with("/VERSION"){"text/plain; charset=utf-8"}else{"application/zip"};
|
||||
let headers=format!("content-type:{mime}\nhost:{host}\nx-amz-content-sha256:{digest}\nx-amz-date:{amz}\n");
|
||||
let signed="content-type;host;x-amz-content-sha256;x-amz-date";
|
||||
let canonical=format!("PUT\n{uri}\n\n{headers}\n{signed}\n{digest}");
|
||||
let scope=format!("{day}/{region}/s3/aws4_request");
|
||||
let string=format!("AWS4-HMAC-SHA256\n{amz}\n{scope}\n{}",hash(canonical.as_bytes()));
|
||||
let k=hmac(format!("AWS4{}",s["R2_SECRET_ACCESS_KEY"]).as_bytes(),&day);
|
||||
let k=hmac(&k,region);let k=hmac(&k,"s3");let k=hmac(&k,"aws4_request");
|
||||
let auth=format!("AWS4-HMAC-SHA256 Credential={}/{scope}, SignedHeaders={signed}, Signature={}",s["R2_ACCESS_KEY_ID"],hex(&hmac(&k,&string)));
|
||||
let response=ureq::AgentBuilder::new().timeout(Duration::from_secs(180)).build()
|
||||
.put(&format!("{endpoint}{uri}")).set("Content-Type",mime).set("x-amz-content-sha256",&digest)
|
||||
.set("x-amz-date",&amz).set("Authorization",&auth).send_bytes(&body);
|
||||
match response {
|
||||
Ok(r) if [200,201].contains(&r.status()) => Ok(json!({"key":key,"sha256":digest,"size":body.len()})),
|
||||
Ok(r)=>Err(format!("R2 HTTP {}",r.status())),
|
||||
Err(ureq::Error::Status(code,_))=>Err(format!("R2 HTTP {code}")),
|
||||
Err(_)=>Err("R2 upload failed or timed out; verify before retrying".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn git_inspect(root:&Path)->Answer {
|
||||
if !root.join(".git").exists() {return Err("inspect requires a Git checkout".into());}
|
||||
let query=|args:&[&str]|->Result<String,String>{
|
||||
let argv=std::iter::once("git").chain(args.iter().copied()).map(|s|json!(s)).collect::<Vec<_>>();
|
||||
let out=command(root,&json!({"argv":argv}))?;
|
||||
if out["code"]!=0 {return Err("Git metadata query failed".into());}
|
||||
Ok(out["stdout"].as_str().unwrap_or("").trim().into())
|
||||
};
|
||||
Ok(json!({"root":root.display().to_string(),"branch":query(&["branch","--show-current"])?,
|
||||
"commit":query(&["rev-parse","HEAD"])?,"changes":query(&["status","--porcelain"])?,
|
||||
"tags":query(&["tag","--list"])?.lines().collect::<Vec<_>>(),
|
||||
"extension_on_main":query(&["ls-files","vscode-extension"])?,
|
||||
"origin":query(&["remote","get-url","origin"])?}))
|
||||
}
|
||||
fn base64(bytes:&[u8])->String {
|
||||
const C:&[u8]=b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out=String::new();
|
||||
for part in bytes.chunks(3) {
|
||||
let a=part[0] as usize;let b=*part.get(1).unwrap_or(&0) as usize;let c=*part.get(2).unwrap_or(&0) as usize;
|
||||
out.push(C[a>>2] as char);out.push(C[((a&3)<<4)|(b>>4)] as char);
|
||||
out.push(if part.len()>1 {C[((b&15)<<2)|(c>>6)] as char}else{'='});
|
||||
out.push(if part.len()>2 {C[c&63] as char}else{'='});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
|
||||
fn expression(e:&marqdo::ast::Expr)->Option<String> {
|
||||
use marqdo::ast::{Expr,Literal,InterpPart,UnaryOp,BinaryOp,IndexKey};
|
||||
Some(match e {
|
||||
Expr::Literal(Literal::None)=>"None".into(),
|
||||
Expr::Literal(Literal::Bool(v))=>if *v{"True".into()}else{"False".into()},
|
||||
Expr::Literal(Literal::Int(v))=>v.to_string(),
|
||||
Expr::Literal(Literal::Num(v))=>{let s=v.to_string();if s.contains('.')||s.contains('e')||s.contains('E'){s}else{format!("{s}.0")}},
|
||||
Expr::Literal(Literal::Text(v))=>{
|
||||
if v.contains('`'){return None;} serde_json::to_string(v).ok()?
|
||||
},
|
||||
Expr::Var(v)=>format!("`{v}`"),
|
||||
Expr::Interp(parts)=>{
|
||||
let mut text=String::new();
|
||||
for p in parts {match p {
|
||||
InterpPart::Lit(v)=>{if v.contains('`'){return None;}text.push_str(v);},
|
||||
InterpPart::Var(v)=>text.push_str(&format!("`{v}`")),
|
||||
_=>return None
|
||||
}}
|
||||
serde_json::to_string(&text).ok()?
|
||||
},
|
||||
Expr::Unary{op,expr}=>match op {UnaryOp::Neg=>format!("-{}",expression(expr)?),UnaryOp::Not=>format!("(not {})",expression(expr)?)},
|
||||
Expr::Binary{op,left,right}=>format!("({} {} {})",expression(left)?,match op {
|
||||
BinaryOp::Add=>"+",BinaryOp::Sub=>"-",BinaryOp::Mul=>"*",BinaryOp::Div=>"/",
|
||||
BinaryOp::Eq=>"==",BinaryOp::Ne=>"!=",BinaryOp::Lt=>"<",BinaryOp::Le=>"<=",
|
||||
BinaryOp::Gt=>">",BinaryOp::Ge=>">=",BinaryOp::And=>"and",BinaryOp::Or=>"or"},expression(right)?),
|
||||
Expr::Call(call)=>call_source(call,false)?,
|
||||
Expr::List(items)=>format!("[{}]",items.iter().map(expression).collect::<Option<Vec<_>>>()?.join(", ")),
|
||||
// Dynamic map construction is deliberately not emitted as an alternate
|
||||
// author DSL: keep its real bound GFM table at the structural boundary.
|
||||
Expr::Map(_)|Expr::Formula(_)|Expr::Code(_)=>return None,
|
||||
Expr::Index{base,label}=>format!("access({}, {})",expression(base)?,match label {
|
||||
IndexKey::Lit(v)=>serde_json::to_string(v).ok()?,IndexKey::Var(v)=>format!("`{v}`")}),
|
||||
Expr::Occluded{label,payload}=>format!("[{}]({})",label,payload.as_deref().map(expression).transpose_option()?),
|
||||
})
|
||||
}
|
||||
trait OptionalText {fn transpose_option(self)->Option<String>;}
|
||||
impl OptionalText for Option<Option<String>> {
|
||||
fn transpose_option(self)->Option<String>{match self{None=>Some(String::new()),Some(v)=>v}}
|
||||
}
|
||||
fn call_source(call:&marqdo::ast::CallExpr,statement:bool)->Option<String> {
|
||||
use marqdo::ast::Arg;
|
||||
let call=call.with_modifiers_expanded().ok()?;
|
||||
let target=if let Some(path)=&call.path{path.join(".")}
|
||||
else if let Some(recv)=&call.receiver{format!("`{recv}`.{}",call.callee)}
|
||||
else{call.callee.clone()};
|
||||
let args=call.args.iter().map(|a|match a {
|
||||
Arg::Named{name,value}=>Some(format!("{name}={}",expression(value)?)),
|
||||
Arg::Positional(value)=>expression(value)
|
||||
}).collect::<Option<Vec<_>>>()?;
|
||||
if statement || call.receiver.is_some() {
|
||||
let target=if target.contains(char::is_whitespace){format!("[{target}]")}else{target};
|
||||
Some(format!("> {target} {}",args.join(" ")).trim_end().into())
|
||||
} else {
|
||||
if target.contains(char::is_whitespace){return None;}
|
||||
Some(format!("{target}({})",args.join(", ")))
|
||||
}
|
||||
}
|
||||
fn semantic_expr(e:&marqdo::ast::Expr)->Value {
|
||||
use marqdo::ast::{Expr,Arg};
|
||||
match e {
|
||||
Expr::Occluded{payload,..}=>payload.as_deref().map(semantic_expr).unwrap_or(json!(["none"])),
|
||||
Expr::Call(c)=>{
|
||||
let c=c.for_evaluation().unwrap_or_else(|_|c.clone());
|
||||
json!(["call",c.callee,c.path,c.receiver,c.args.iter().map(|a|match a{
|
||||
Arg::Named{name,value}=>json!(["named",name,semantic_expr(value)]),
|
||||
Arg::Positional(v)=>json!(["positional",semantic_expr(v)])
|
||||
}).collect::<Vec<_>>()])
|
||||
},
|
||||
Expr::List(v)=>json!(["list",v.iter().map(semantic_expr).collect::<Vec<_>>()]),
|
||||
Expr::Map(v)=>json!(["map",v.iter().map(|(k,v)|json!([k,semantic_expr(v)])).collect::<Vec<_>>()]),
|
||||
Expr::Unary{op,expr}=>json!(["unary",format!("{op:?}"),semantic_expr(expr)]),
|
||||
Expr::Binary{op,left,right}=>json!(["binary",format!("{op:?}"),semantic_expr(left),semantic_expr(right)]),
|
||||
_=>json!(format!("{e:?}"))
|
||||
}
|
||||
}
|
||||
fn semantic_statements(body:&[marqdo::ast::Stmt])->Vec<Value> {
|
||||
use marqdo::ast::{Expr,Stmt};
|
||||
body.iter().map(|s|match s {
|
||||
Stmt::Assign{name,value,..}=>json!(["assign",name,semantic_expr(value)]),
|
||||
Stmt::Return{value,..}=>json!(["return",semantic_expr(value)]),
|
||||
Stmt::Call{call,..}=>json!(["eval",semantic_expr(&Expr::Call(call.clone()))]),
|
||||
Stmt::Expr{value,..}=>json!(["eval",semantic_expr(value)]),
|
||||
Stmt::Branch{arms,..}=>json!(["branch",arms.iter().map(|a|json!([a.condition.as_ref().map(semantic_expr),semantic_statements(&a.body)])).collect::<Vec<_>>()]),
|
||||
Stmt::While{condition,body,..}=>json!(["while",semantic_expr(condition),semantic_statements(body)]),
|
||||
Stmt::ForEach{item,collection,body,..}=>json!(["foreach",item,collection,semantic_statements(body)])
|
||||
}).collect()
|
||||
}
|
||||
fn statement_locations(body:&[marqdo::ast::Stmt])->Vec<Value> {
|
||||
use marqdo::ast::Stmt;
|
||||
let mut out=Vec::new();
|
||||
for s in body {match s {
|
||||
Stmt::Assign{name,value,span,end_line}=>out.push(json!({"kind":"assign","name":name,"line":span.line,"end_line":end_line,"rendered":expression(value)})),
|
||||
Stmt::Return{value,span}=>out.push(json!({"kind":"return","line":span.line,"rendered":expression(value)})),
|
||||
Stmt::Call{call,span}=>out.push(json!({"kind":"call","line":span.line,"callee":call.path.as_ref().map(|p|p.join(".")).unwrap_or_else(||call.callee.clone()),"rendered":call_source(call,true)})),
|
||||
Stmt::Expr{value,span}=>out.push(json!({"kind":"eval","line":span.line,"rendered":expression(value)})),
|
||||
Stmt::Branch{arms,..}=>for arm in arms{out.extend(statement_locations(&arm.body));},
|
||||
Stmt::While{body,..}|Stmt::ForEach{body,..}=>out.extend(statement_locations(body))
|
||||
}}
|
||||
out
|
||||
}
|
||||
|
||||
fn analyze(p:&Value)->Answer {
|
||||
use marqdo::ast::{Expr,Function,Literal};
|
||||
fn default(e:&Expr)->Value {match e {
|
||||
Expr::Literal(Literal::Text(t))=>json!({"text":t}),
|
||||
Expr::Literal(Literal::None)=>json!({"source":"None"}),
|
||||
Expr::Literal(Literal::Bool(v))=>json!({"source":if *v{"True"}else{"False"}}),
|
||||
Expr::Literal(Literal::Int(v))=>json!({"source":v.to_string()}),
|
||||
Expr::Literal(Literal::Num(v))=>json!({"source":if v.fract()==0.0 { format!("{v:.1}") } else {v.to_string()}}),
|
||||
_=>json!({"debug":format!("{e:?}")})
|
||||
}}
|
||||
fn units(fs:&[Function],body:bool)->Vec<Value> {fs.iter().map(|f|json!({
|
||||
"name":f.name,"line":f.span.line,"level":f.level,"base":f.base,
|
||||
"params":f.params.iter().map(|p|json!({"name":p.name,"line":p.span.line,"inferred":p.inferred,"default":p.default.as_ref().map(default)})).collect::<Vec<_>>(),
|
||||
"contract":f.contract.as_ref().map(|c|json!({"params":c.params.iter().map(|p|json!({"name":p.name,"ty":p.ty.name(),"desc":p.desc})).collect::<Vec<_>>(),"returns":c.returns.as_ref().map(|r|json!({"ty":r.ty.name(),"desc":r.desc}))})),
|
||||
"children":units(&f.children,body),"semantic":semantic_statements(&f.body),"statements":statement_locations(&f.body),"body":if body{Some(format!("{:?}",f.body))}else{None}
|
||||
})).collect()}
|
||||
let source=field(p,"source")?;
|
||||
let module=marqdo::parse::parse_source(source).map_err(|e|format!("{e:#}"))?;
|
||||
let diagnostics=marqdo::check::check_module(&module,None).iter().map(|d|d.to_json()).collect::<Vec<_>>();
|
||||
let ratios=marqdo::narrative_ratio::measure_source_units(source,&module.functions).iter()
|
||||
.map(|r|json!({"name":r.name,"line":r.line,"narrative":r.narrative,"total":r.total,"ratio":r.ratio})).collect::<Vec<_>>();
|
||||
Ok(json!({"schema_version":1,"functions":units(&module.functions,p.get("include_body").and_then(Value::as_bool).unwrap_or(false)),
|
||||
"ratios":ratios,"diagnostics":diagnostics}))
|
||||
}
|
||||
|
||||
|
||||
fn gzip_text(p: &Value) -> Answer {
|
||||
use base64::Engine;
|
||||
let data = p.get("data").ok_or("missing portable bytes")?;
|
||||
if data.get("_type").and_then(Value::as_str) != Some("bytes") {
|
||||
return Err("gzip expects portable bytes".into());
|
||||
}
|
||||
let encoded = field(data,"base64")?;
|
||||
if encoded.len() > 24 * 1024 * 1024 { return Err("compressed input exceeds limit".into()); }
|
||||
let bytes = base64::engine::general_purpose::STANDARD.decode(encoded).map_err(|_| "invalid base64 bytes")?;
|
||||
let limit = p.get("max_bytes").and_then(Value::as_u64).unwrap_or(16 * 1024 * 1024);
|
||||
if limit == 0 || limit > 64 * 1024 * 1024 { return Err("invalid gzip output limit".into()); }
|
||||
let plain = read_bounded(flate2::read::MultiGzDecoder::new(bytes.as_slice()),limit)?;
|
||||
Ok(json!(String::from_utf8(plain).map_err(|_| "gzip text is not UTF-8")?))
|
||||
}
|
||||
|
||||
fn dispatch(request:&Value)->Answer {
|
||||
let root=PathBuf::from(request.get("root").and_then(Value::as_str).unwrap_or(".")).canonicalize().map_err(|_|"root does not exist")?;
|
||||
let op=field(request,"operation")?;
|
||||
let empty=json!({});let p=request.get("payload").unwrap_or(&empty);
|
||||
match op {
|
||||
"command"=>command(&root,p),
|
||||
"git_inspect"=>git_inspect(&root),
|
||||
"github"=>http_json(&root,p),
|
||||
"archive"=>archive(&root,p),
|
||||
"gzip_text"=>gzip_text(p),
|
||||
"analyze"=>analyze(p),
|
||||
"r2_put"=>r2_put(&root,p),
|
||||
_=>Err("unknown engineering boundary operation".into())
|
||||
}
|
||||
}
|
||||
unsafe extern "C" fn engineering_request(args:*const c_char,out:*mut *mut c_char,err:*mut *mut c_char)->c_int {
|
||||
let args=match parse_args(args){Ok(v)=>v,Err(e)=>{set_err(err,&e);return 1;}};
|
||||
let request=args.get("request").unwrap_or(&args);
|
||||
let result=match dispatch(request) {
|
||||
Ok(value)=>json!({"ok":true,"value":value,"error":null}),
|
||||
Err(message)=>json!({"ok":false,"value":null,"error":{"code":"engineering.boundary","message":message,"operation":request.get("operation")}})
|
||||
};
|
||||
set_out(out,&result.to_string());0
|
||||
}
|
||||
marqdo_plugin!(2,[("engineering_request","request",engineering_request)]);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize,Ordering};
|
||||
static NEXT:AtomicUsize=AtomicUsize::new(0);
|
||||
fn fixture()->PathBuf {
|
||||
let p=std::env::temp_dir().join(format!("mq-engineering-{}-{}",std::process::id(),NEXT.fetch_add(1,Ordering::Relaxed)));
|
||||
fs::create_dir_all(&p).unwrap(); p
|
||||
}
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn argv_input_is_literal_and_noisy_output_is_bounded() {
|
||||
let dir=fixture();
|
||||
let input="quotes \" ' $HOME $(never-run) 😀\n".repeat(1000);
|
||||
let result=command(&dir,&json!({"argv":["/bin/cat"],"stdin":input})).unwrap();
|
||||
assert_eq!(result["code"],0);assert_eq!(result["stdout"],input);
|
||||
let result=command(&dir,&json!({"argv":["/usr/bin/head","-c","65536","/dev/zero"],"max_output":128})).unwrap();
|
||||
assert_eq!(result["code"],0);assert_eq!(result["stdout"].as_str().unwrap().len(),128);
|
||||
assert_eq!(result["truncated"],true);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn timeout_and_nonzero_exit_remain_observable() {
|
||||
let dir=fixture();let started=Instant::now();
|
||||
let result=command(&dir,&json!({"argv":["/bin/sleep","2"],"timeout_ms":20})).unwrap();
|
||||
assert_eq!(result["timed_out"],true);assert_eq!(result["code"],124);
|
||||
assert!(started.elapsed()<Duration::from_secs(2));
|
||||
let result=command(&dir,&json!({"argv":["/bin/false"]})).unwrap();
|
||||
assert_eq!(result["code"],1);assert_eq!(result["timed_out"],false);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn unsafe_transport_shortcuts_are_rejected_before_spawn() {
|
||||
let dir=fixture();
|
||||
for argv in [json!(["git","push","--force"]),json!(["git","commit","--no-verify"]),json!(["bash","-c","echo forbidden"])] {
|
||||
assert!(command(&dir,&json!({"argv":argv})).is_err());
|
||||
}
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
fn make_zip(path:&Path,name:&str,payload:&[u8]) {
|
||||
let mut out=zip::ZipWriter::new(File::create(path).unwrap());
|
||||
out.start_file(name,zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored)).unwrap();
|
||||
out.write_all(payload).unwrap();out.finish().unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn zip_inspection_checks_metadata_paths_and_crc_without_extraction() {
|
||||
let dir=fixture();let path=dir.join("fixture.zip");
|
||||
make_zip(&path,"ext/VERSION",b"2.6.0\r\n");
|
||||
let result=archive(&dir,&json!({"path":"fixture.zip"})).unwrap();
|
||||
assert_eq!(result["metadata"]["ext/VERSION"],"2.6.0\r\n");
|
||||
assert!(!dir.join("ext").exists());
|
||||
make_zip(&path,"../escape",b"untrusted");
|
||||
assert!(archive(&dir,&json!({"path":"fixture.zip"})).is_err());
|
||||
make_zip(&path,"payload",b"unique CRC fixture payload");
|
||||
let mut bytes=fs::read(&path).unwrap();
|
||||
let index=bytes.windows(b"unique CRC fixture payload".len()).position(|x|x==b"unique CRC fixture payload").unwrap();
|
||||
bytes[index]^=1;fs::write(&path,bytes).unwrap();
|
||||
assert!(archive(&dir,&json!({"path":"fixture.zip"})).is_err());
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn gzip_text_validates_format_utf8_and_expansion_limit() {
|
||||
use base64::Engine;
|
||||
fn compressed(payload:&[u8])->Vec<u8> {
|
||||
let mut writer=flate2::write::GzEncoder::new(Vec::new(),flate2::Compression::default());
|
||||
writer.write_all(payload).unwrap();writer.finish().unwrap()
|
||||
}
|
||||
let mut bytes=compressed(b"Package: marqdo\n");bytes.extend(compressed(b"Version: 2.6.0\n"));
|
||||
let data=json!({"_type":"bytes","base64":base64::engine::general_purpose::STANDARD.encode(&bytes)});
|
||||
assert_eq!(gzip_text(&json!({"data":data})).unwrap(),"Package: marqdo\nVersion: 2.6.0\n");
|
||||
assert!(gzip_text(&json!({"data":data,"max_bytes":2})).is_err());
|
||||
assert!(gzip_text(&json!({"data":{"_type":"bytes","base64":"invalid"}})).is_err());
|
||||
let data=json!({"_type":"bytes","base64":base64::engine::general_purpose::STANDARD.encode(compressed(&[0xff]))});
|
||||
assert!(gzip_text(&json!({"data":data})).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn analysis_uses_the_real_parser_without_loading_imports() {
|
||||
let source="---\nmarkup: occlusion\nimport:\n absent: /does/not/exist.mq.md\n---\n## answer\n\n完成计算后返回*42*。\n";
|
||||
let result=analyze(&json!({"source":source})).unwrap();
|
||||
assert_eq!(result["functions"][0]["name"],"answer");
|
||||
assert!(result["diagnostics"].as_array().unwrap().is_empty());
|
||||
assert_eq!(result["functions"][0]["semantic"][0][0],"return");
|
||||
}
|
||||
}
|
||||
+60
-29
@@ -35,10 +35,6 @@ func web_render_nodes(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
frag, err := artifact.RenderNodes(args["nodes"])
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
pg := asPageMap(args["page"])
|
||||
title := ""
|
||||
if pg != nil {
|
||||
@@ -49,7 +45,8 @@ func web_render_nodes(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int
|
||||
if t, ok := argStr(args, "title"); ok && t != "" {
|
||||
title = t
|
||||
}
|
||||
return replyJSON(outJSON, errMsg, artifact.RenderHTMLPage(title, frag), nil)
|
||||
html, err := artifact.RenderViewDocument(title, args["nodes"], nil)
|
||||
return replyJSON(outJSON, errMsg, html, err)
|
||||
}
|
||||
|
||||
//export web_render_document
|
||||
@@ -88,26 +85,23 @@ func web_dom_markdown(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int
|
||||
return replyJSON(outJSON, errMsg, artifact.MarkdownHTML(text), nil)
|
||||
}
|
||||
|
||||
//export web_serve_root
|
||||
func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
// prepareArtifactApp shares discovery and startup assembly between direct serving
|
||||
// and resource composition. Listening starts only after resources have been bound.
|
||||
func prepareArtifactApp(args map[string]any) (map[string]any, error) {
|
||||
root, _ := argStr(args, "root")
|
||||
if root == "" {
|
||||
root = "."
|
||||
}
|
||||
abs, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
return nil, err
|
||||
}
|
||||
if st, err := os.Stat(abs); err != nil || !st.IsDir() {
|
||||
return replyJSON(outJSON, errMsg, nil, fmt.Errorf("web.serve: root not a directory: %s", abs))
|
||||
return nil, fmt.Errorf("web.prepare: root not a directory: %s", abs)
|
||||
}
|
||||
files, err := artifact.ScanRoot(abs)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
return nil, err
|
||||
}
|
||||
host, _ := argStr(args, "host")
|
||||
if host == "" {
|
||||
@@ -129,14 +123,23 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
if title == "" {
|
||||
title = f.Meta["标题"]
|
||||
}
|
||||
body, structured, err := artifact.RenderFile(f, plugin.RunArtifact)
|
||||
nodes, structured, err := artifact.AssembleView(f, func(path string, args map[string]any) (any, error) {
|
||||
return plugin.RunArtifactAtRoot(path, args, abs)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pg := page.New(map[string]any{"title": title, "intro": body})
|
||||
pg := page.New(map[string]any{"title": title, "intro": artifact.MarkdownHTML(f.Body)})
|
||||
stampArtifactData(pg, f.Meta)
|
||||
if structured {
|
||||
pg["artifact_html"] = artifact.RenderHTMLPage(title, body)
|
||||
// Validate structure and Resource contracts without querying or posting.
|
||||
if _, err := artifact.CollectDocumentHead(nodes); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", f.Rel, err)
|
||||
}
|
||||
if _, err := artifact.RenderNodesWithResources(nodes, httpx.ValidateViewResource); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", f.Rel, err)
|
||||
}
|
||||
pg["artifact_nodes"] = nodes
|
||||
}
|
||||
return pg, nil
|
||||
}
|
||||
@@ -145,7 +148,7 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
if f.Kind == "web" && f.Route == "/" {
|
||||
home, err = documentPage(f)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
return nil, err
|
||||
}
|
||||
break
|
||||
}
|
||||
@@ -164,11 +167,11 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
}
|
||||
pg, err := documentPage(f)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
return nil, err
|
||||
}
|
||||
out, err := app.Route(a, f.Route, pg)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
return nil, err
|
||||
}
|
||||
a = out
|
||||
continue
|
||||
@@ -209,20 +212,49 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
if mw := args["middleware"]; mw != nil {
|
||||
out, err := middleware.Configure(a, map[string]any{"security": mw})
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
return nil, err
|
||||
}
|
||||
a = out
|
||||
}
|
||||
if sd, ok := argStr(args, "static_dir"); ok && sd != "" {
|
||||
out, err := app.Static(a, sd, "/static")
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
return nil, err
|
||||
}
|
||||
a = out
|
||||
}
|
||||
a["artifact_declared"] = artifact.InspectBag(nil, files)["declared"]
|
||||
a["inspect"] = artifact.InspectBag(a, files)
|
||||
_, err = httpx.Listen(a, abs)
|
||||
return replyJSON(outJSON, errMsg, map[string]any{"ok": true, "value": a["inspect"], "error": nil}, err)
|
||||
a["artifact_root"] = abs
|
||||
return a, nil
|
||||
}
|
||||
|
||||
//export web_prepare_root
|
||||
func web_prepare_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
a, err := prepareArtifactApp(args)
|
||||
return replyJSON(outJSON, errMsg, a, err)
|
||||
}
|
||||
|
||||
//export web_serve_root
|
||||
func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
a, err := prepareArtifactApp(args)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
inspection, err := httpx.InspectApp(a)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
_, err = httpx.Listen(a, a["artifact_root"].(string))
|
||||
return replyJSON(outJSON, errMsg, map[string]any{"ok": true, "value": inspection, "error": nil}, err)
|
||||
}
|
||||
|
||||
//export web_inspect
|
||||
@@ -239,12 +271,11 @@ func web_inspect(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
return replyJSON(outJSON, errMsg, artifact.InspectBag(nil, files), nil)
|
||||
}
|
||||
a := asPageMap(args["app"])
|
||||
if a != nil {
|
||||
if insp, ok := a["inspect"].(map[string]any); ok {
|
||||
return replyJSON(outJSON, errMsg, insp, nil)
|
||||
}
|
||||
if a == nil {
|
||||
return replyJSON(outJSON, errMsg, artifact.InspectBag(nil, nil), nil)
|
||||
}
|
||||
return replyJSON(outJSON, errMsg, artifact.InspectBag(a, nil), nil)
|
||||
inspection, err := httpx.InspectApp(a)
|
||||
return replyJSON(outJSON, errMsg, inspection, err)
|
||||
}
|
||||
|
||||
//export web_app_use
|
||||
|
||||
@@ -345,7 +345,14 @@ func web_listen(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
if len(appBag) == 0 {
|
||||
appBag = args
|
||||
}
|
||||
out, err := httpx.Listen(appBag, entryDir())
|
||||
root := entryDir()
|
||||
if artifactRoot, ok := appBag["artifact_root"].(string); ok && artifactRoot != "" {
|
||||
root = artifactRoot
|
||||
}
|
||||
if _, err := httpx.InspectApp(appBag); err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
out, err := httpx.Listen(appBag, root)
|
||||
return replyJSON(outJSON, errMsg, out, err)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Package apikey implements Bearer API key verification (G-API1).
|
||||
//
|
||||
// Hash formula: sha256 hex of pepper + ":" + key (documented for anlian apikeys).
|
||||
// Hash formula: sha256 hex of pepper + ":" + key.
|
||||
package apikey
|
||||
|
||||
import (
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
package artifact
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/render"
|
||||
@@ -94,9 +96,17 @@ func ParseFrontmatter(src string) (meta map[string]string, body string) {
|
||||
// RenderNodes renders the existing five-column View schema recursively. Container
|
||||
// value cells hold more View rows; markdown leaves hold ordinary Markdown text.
|
||||
func RenderNodes(nodes any) (string, error) {
|
||||
return RenderNodesWithResources(nodes, nil)
|
||||
}
|
||||
|
||||
// ResourceRenderer resolves a typed Resource at the request boundary.
|
||||
// Ordinary View construction remains pure; a nil renderer never starts IO.
|
||||
type ResourceRenderer func(map[string]any) (string, error)
|
||||
|
||||
func RenderNodesWithResources(nodes any, resources ResourceRenderer) (string, error) {
|
||||
var b strings.Builder
|
||||
b.WriteString(`<style>` + LayoutCSS + `</style><div class="mq-view">`)
|
||||
if err := renderNodes(&b, nodes, 0); err != nil {
|
||||
if err := renderNodes(&b, nodes, 0, resources); err != nil {
|
||||
return "", err
|
||||
}
|
||||
b.WriteString(`</div>`)
|
||||
@@ -105,7 +115,7 @@ func RenderNodes(nodes any) (string, error) {
|
||||
|
||||
// Fixed runtime geometry, shared by offline previews and served Documents.
|
||||
// Authors choose row/column instead of embedding CSS or HTML in content cells.
|
||||
const LayoutCSS = `.mq-view{max-width:72rem;margin:auto;padding:1.5rem;line-height:1.6;font-family:system-ui,sans-serif}.mq-view *{box-sizing:border-box}.mq-view .mq-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,16rem),1fr));gap:1.5rem}.mq-view .mq-column{display:flex;flex-direction:column;gap:1.5rem}.mq-view .mq-node{min-width:0}.mq-view nav,.mq-view footer{padding-block:1rem}.mq-view footer{border-top:1px solid #d5dce5}.mq-view a{color:#2457a7}.mq-view img{max-width:100%;height:auto}.mq-view pre{overflow:auto}`
|
||||
const LayoutCSS = `.mq-view{max-width:72rem;margin:auto;padding:1.5rem;line-height:1.6;font-family:system-ui,sans-serif}.mq-view *{box-sizing:border-box}.mq-view .mq-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,16rem),1fr));gap:1.5rem}.mq-view .mq-column{display:flex;flex-direction:column;gap:1.5rem}.mq-view .mq-node{min-width:0;overflow-wrap:anywhere}.mq-view nav,.mq-view footer{padding-block:1rem}.mq-view footer{border-top:1px solid #d5dce5}.mq-view a{color:#2457a7}.mq-view img{max-width:100%;height:auto}.mq-view pre{overflow:auto}.mq-view input,.mq-view textarea,.mq-view select{max-width:100%;font:inherit}.mq-view textarea{width:100%}`
|
||||
|
||||
// Preserve typed value cells when normalizing column tables. General AsRows
|
||||
// treats @ cells as text, which would stringify nested component tables.
|
||||
@@ -148,7 +158,85 @@ func viewRows(nodes any) ([]any, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func renderNodes(b *strings.Builder, nodes any, depth int) error {
|
||||
func containerTag(kind string) (string, string) {
|
||||
switch kind {
|
||||
case "row", "横排":
|
||||
return "div", " mq-row"
|
||||
case "column", "纵排":
|
||||
return "div", " mq-column"
|
||||
case "nav", "导航":
|
||||
return "nav", ""
|
||||
case "header", "页头":
|
||||
return "header", ""
|
||||
case "footer", "页脚":
|
||||
return "footer", ""
|
||||
case "section", "区域":
|
||||
return "section", ""
|
||||
case "aside", "侧栏":
|
||||
return "aside", ""
|
||||
case "form", "表单":
|
||||
return "form", ""
|
||||
case "list", "列表":
|
||||
return "ul", ""
|
||||
case "item", "列表项":
|
||||
return "li", ""
|
||||
case "select", "选择":
|
||||
return "select", ""
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
// FindSlot selects one declared View region without resolving any Resources.
|
||||
// Container traversal is identical to rendering and never descends into a
|
||||
// Resource's private map as if it were another View table.
|
||||
func FindSlot(nodes any, slot string) (any, bool, error) {
|
||||
var selected []any
|
||||
var walk func(any, int) error
|
||||
walk = func(nodes any, depth int) error {
|
||||
if depth > 64 {
|
||||
return fmt.Errorf("View: nesting exceeds 64 levels")
|
||||
}
|
||||
rows, err := viewRows(nodes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, value := range rows {
|
||||
row, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return fmt.Errorf("View slot: expected a row map")
|
||||
}
|
||||
if first(row, "slot", "槽") == slot {
|
||||
selected = append(selected, row)
|
||||
}
|
||||
kind := strings.ToLower(first(row, "type", "类型"))
|
||||
if tag, _ := containerTag(kind); tag != "" {
|
||||
children := row["value"]
|
||||
if children == nil {
|
||||
children = row["值"]
|
||||
}
|
||||
if children == nil {
|
||||
return fmt.Errorf("View %s: missing child rows", kind)
|
||||
}
|
||||
if err := walk(children, depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := walk(nodes, 0); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if len(selected) > 1 {
|
||||
return nil, false, fmt.Errorf("View slot %q is ambiguous", slot)
|
||||
}
|
||||
if len(selected) == 0 {
|
||||
return nil, false, nil
|
||||
}
|
||||
return selected, true, nil
|
||||
}
|
||||
|
||||
func renderNodes(b *strings.Builder, nodes any, depth int, resources ResourceRenderer) error {
|
||||
if depth > 64 {
|
||||
return fmt.Errorf("View: nesting exceeds 64 levels")
|
||||
}
|
||||
@@ -165,6 +253,10 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error {
|
||||
slot := first(row, "slot", "槽")
|
||||
val := first(row, "value", "值")
|
||||
attrs := first(row, "attrs", "属性")
|
||||
attributes, err := renderAttributes(row)
|
||||
if err != nil {
|
||||
return fmt.Errorf("View row %d: %w", i+1, err)
|
||||
}
|
||||
style := first(row, "style", "样式")
|
||||
class := "mq-node"
|
||||
if style != "" {
|
||||
@@ -173,25 +265,8 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error {
|
||||
if slot != "" {
|
||||
class += " slot-" + html.EscapeString(slot)
|
||||
}
|
||||
tag := ""
|
||||
switch ty {
|
||||
case "row", "横排":
|
||||
tag = "div"
|
||||
class += " mq-row"
|
||||
case "column", "纵排":
|
||||
tag = "div"
|
||||
class += " mq-column"
|
||||
case "nav", "导航":
|
||||
tag = "nav"
|
||||
case "header", "页头":
|
||||
tag = "header"
|
||||
case "footer", "页脚":
|
||||
tag = "footer"
|
||||
case "section", "区域":
|
||||
tag = "section"
|
||||
case "aside", "侧栏":
|
||||
tag = "aside"
|
||||
}
|
||||
tag, geometry := containerTag(ty)
|
||||
class += geometry
|
||||
if tag != "" {
|
||||
children := row["value"]
|
||||
if children == nil {
|
||||
@@ -200,23 +275,72 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error {
|
||||
if children == nil {
|
||||
return fmt.Errorf("View row %d (%s): missing child rows in value", i+1, ty)
|
||||
}
|
||||
b.WriteString(`<` + tag + ` class="` + class + `">`)
|
||||
if err := renderNodes(b, children, depth+1); err != nil {
|
||||
b.WriteString(`<` + tag + ` class="` + class + `"` + attributes + `>`)
|
||||
if err := renderNodes(b, children, depth+1, resources); err != nil {
|
||||
return fmt.Errorf("View %s/%s: %w", ty, slot, err)
|
||||
}
|
||||
b.WriteString(`</` + tag + `>`)
|
||||
continue
|
||||
}
|
||||
switch ty {
|
||||
case "resource", "资源":
|
||||
value := row["value"]
|
||||
if value == nil {
|
||||
value = row["值"]
|
||||
}
|
||||
resource, ok := value.(map[string]any)
|
||||
if !ok || first(resource, "_type") == "" {
|
||||
return fmt.Errorf("View row %d: resource value must be a typed Resource", i+1)
|
||||
}
|
||||
if first(resource, "_type") == "document_head" {
|
||||
if _, err := ParseDocumentHead(resource); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if resources == nil {
|
||||
return fmt.Errorf("View row %d: resource requires an explicit request renderer", i+1)
|
||||
}
|
||||
fragment, err := resources(resource)
|
||||
if err != nil {
|
||||
return fmt.Errorf("View resource %s: %w", slot, err)
|
||||
}
|
||||
b.WriteString(`<section class="` + class + `"` + attributes + `>` + fragment + `</section>`)
|
||||
case "markdown", "正文":
|
||||
b.WriteString(`<div class="` + class + `">` + render.MarkdownToHTML(val) + `</div>`)
|
||||
b.WriteString(`<div class="` + class + `"` + attributes + `>` + render.MarkdownToHTML(val) + `</div>`)
|
||||
case "title", "标题":
|
||||
b.WriteString(`<h1 class="` + class + `">` + inline(val) + `</h1>`)
|
||||
b.WriteString(`<h1 class="` + class + `"` + attributes + `>` + inline(val) + `</h1>`)
|
||||
case "link", "链接":
|
||||
if attrs == "" {
|
||||
attrs = "#"
|
||||
if !hasAttributeMap(row) {
|
||||
if attrs == "" {
|
||||
attrs = "#"
|
||||
}
|
||||
attributes = ` href="` + html.EscapeString(attrs) + `"`
|
||||
}
|
||||
b.WriteString(`<a class="` + class + `"` + attributes + `>` + inline(val) + `</a>`)
|
||||
case "input", "输入":
|
||||
b.WriteString(`<input class="` + class + `"` + attributes + ` value="` + html.EscapeString(val) + `">`)
|
||||
case "button", "按钮", "textarea", "多行输入", "label", "标签", "pre", "预格式", "option", "选项":
|
||||
tags := map[string]string{"button": "button", "按钮": "button", "textarea": "textarea", "多行输入": "textarea", "label": "label", "标签": "label", "pre": "pre", "预格式": "pre", "option": "option", "选项": "option"}
|
||||
tag := tags[ty]
|
||||
b.WriteString(`<` + tag + ` class="` + class + `"` + attributes + `>` + html.EscapeString(val) + `</` + tag + `>`)
|
||||
case "script", "脚本", "stylesheet", "样式表":
|
||||
url := strings.ToLower(strings.TrimSpace(val))
|
||||
if url == "" || strings.ContainsAny(url, "\r\n\t") || strings.HasPrefix(url, "javascript:") || strings.HasPrefix(url, "vbscript:") {
|
||||
return fmt.Errorf("View row %d: resource requires a nonempty non-script URL", i+1)
|
||||
}
|
||||
if attrs, ok := attributeValue(row).(map[string]any); ok {
|
||||
for _, reserved := range []string{"href", "src", "rel"} {
|
||||
if _, exists := attrs[reserved]; exists {
|
||||
return fmt.Errorf("View row %d: resource URL and relation belong to its kind/value, not attrs.%s", i+1, reserved)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ty == "script" || ty == "脚本" {
|
||||
b.WriteString(`<script src="` + html.EscapeString(val) + `"` + attributes + `></script>`)
|
||||
} else {
|
||||
b.WriteString(`<link rel="stylesheet" href="` + html.EscapeString(val) + `"` + attributes + `>`)
|
||||
}
|
||||
b.WriteString(`<a class="` + class + `" href="` + html.EscapeString(attrs) + `">` + inline(val) + `</a>`)
|
||||
case "html", "原文":
|
||||
b.WriteString(`<div class="` + class + `">` + val + `</div>`)
|
||||
default:
|
||||
@@ -228,31 +352,137 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error {
|
||||
case []any, map[string]any:
|
||||
return fmt.Errorf("View row %d: unknown structural type %q", i+1, ty)
|
||||
}
|
||||
b.WriteString(`<p class="` + class + `">` + inline(val) + `</p>`)
|
||||
b.WriteString(`<p class="` + class + `"` + attributes + `>` + inline(val) + `</p>`)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Attribute records keep controls in the same five-column View schema.
|
||||
// Legacy link rows may still carry a plain href string. Names and scalar values
|
||||
// are checked before emission; handlers and inline style remain explicit escapes.
|
||||
func attributeValue(row map[string]any) any {
|
||||
if value, ok := row["attrs"]; ok && value != nil {
|
||||
return value
|
||||
}
|
||||
return row["属性"]
|
||||
}
|
||||
|
||||
func hasAttributeMap(row map[string]any) bool {
|
||||
_, ok := attributeValue(row).(map[string]any)
|
||||
return ok
|
||||
}
|
||||
|
||||
func renderAttributes(row map[string]any) (string, error) {
|
||||
value := attributeValue(row)
|
||||
if value == nil || value == "" {
|
||||
return "", nil
|
||||
}
|
||||
attrs, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
if _, legacy := value.(string); legacy {
|
||||
return "", nil
|
||||
}
|
||||
return "", fmt.Errorf("attrs must be a scalar attribute record or legacy link URL")
|
||||
}
|
||||
allowed := map[string]bool{
|
||||
"id": true, "title": true, "role": true, "name": true, "type": true,
|
||||
"href": true, "src": true, "action": true, "method": true, "enctype": true,
|
||||
"placeholder": true, "for": true, "rows": true, "cols": true, "size": true,
|
||||
"min": true, "max": true, "step": true, "minlength": true, "maxlength": true,
|
||||
"pattern": true, "autocomplete": true, "target": true, "rel": true,
|
||||
"tabindex": true, "download": true, "accept": true, "alt": true,
|
||||
"integrity": true, "crossorigin": true, "media": true, "referrerpolicy": true,
|
||||
}
|
||||
booleans := map[string]bool{"hidden": true, "disabled": true, "required": true, "readonly": true, "checked": true, "selected": true, "multiple": true, "autofocus": true, "async": true, "defer": true, "nomodule": true}
|
||||
keys := make([]string, 0, len(attrs))
|
||||
for name := range attrs {
|
||||
keys = append(keys, name)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
var out strings.Builder
|
||||
for _, name := range keys {
|
||||
if !(allowed[name] || booleans[name] || validCustomAttribute(name)) {
|
||||
return "", fmt.Errorf("unsupported attribute %q; use attrs data/aria keys for client state", name)
|
||||
}
|
||||
v := attrs[name]
|
||||
if v == nil {
|
||||
continue
|
||||
}
|
||||
if booleans[name] {
|
||||
flag, ok := v.(bool)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("attribute %s requires a boolean", name)
|
||||
}
|
||||
if flag {
|
||||
out.WriteString(" " + name)
|
||||
}
|
||||
continue
|
||||
}
|
||||
switch v.(type) {
|
||||
case string, bool, float64, int, int64, json.Number:
|
||||
default:
|
||||
return "", fmt.Errorf("attribute %s requires a scalar value", name)
|
||||
}
|
||||
text := fmt.Sprint(v)
|
||||
if name == "href" || name == "src" || name == "action" {
|
||||
url := strings.ToLower(strings.TrimSpace(text))
|
||||
if strings.HasPrefix(url, "javascript:") || strings.HasPrefix(url, "vbscript:") {
|
||||
return "", fmt.Errorf("attribute %s cannot execute a script URL", name)
|
||||
}
|
||||
}
|
||||
out.WriteString(" " + name + `="` + html.EscapeString(text) + `"`)
|
||||
}
|
||||
return out.String(), nil
|
||||
}
|
||||
|
||||
func validCustomAttribute(name string) bool {
|
||||
if !(strings.HasPrefix(name, "data-") || strings.HasPrefix(name, "aria-")) {
|
||||
return false
|
||||
}
|
||||
if strings.HasSuffix(name, "-") {
|
||||
return false
|
||||
}
|
||||
for _, char := range name {
|
||||
if !(char >= 'a' && char <= 'z' || char >= '0' && char <= '9' || char == '-' || char == '_') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// RenderFile explicitly opts a Document into startup-time component assembly.
|
||||
// Documents without view: main retain their existing Markdown/data-source path.
|
||||
func RenderFile(f ArtifactFile, run func(string, map[string]any) (any, error)) (string, bool, error) {
|
||||
// AssembleView runs the existing startup entry once and retains typed rows.
|
||||
// Request resources are deliberately not resolved during assembly.
|
||||
func AssembleView(f ArtifactFile, run func(string, map[string]any) (any, error)) (any, bool, error) {
|
||||
view := metaString(f.Meta, "view", "视图")
|
||||
if view == "" {
|
||||
return MarkdownHTML(f.Body), false, nil
|
||||
return nil, false, nil
|
||||
}
|
||||
if view != "main" {
|
||||
return "", false, fmt.Errorf("%s: view/视图 must be main", f.Rel)
|
||||
return nil, false, fmt.Errorf("%s: view/视图 must be main", f.Rel)
|
||||
}
|
||||
if metaString(f.Meta, "data_source", "数据源") != "" {
|
||||
return "", false, fmt.Errorf("%s: view main is startup assembly; use an ordinary Document for automatic data_source binding", f.Rel)
|
||||
return nil, false, fmt.Errorf("%s: view main is startup assembly; use an ordinary Document for automatic data_source binding", f.Rel)
|
||||
}
|
||||
nodes, err := run(f.Path, nil)
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("%s: view main: %w", f.Rel, err)
|
||||
return nil, false, fmt.Errorf("%s: view main: %w", f.Rel, err)
|
||||
}
|
||||
if nodes == nil {
|
||||
return "", false, fmt.Errorf("%s: view main must return View rows", f.Rel)
|
||||
return nil, false, fmt.Errorf("%s: view main must return View rows", f.Rel)
|
||||
}
|
||||
return nodes, true, nil
|
||||
}
|
||||
|
||||
func RenderFile(f ArtifactFile, run func(string, map[string]any) (any, error)) (string, bool, error) {
|
||||
nodes, structured, err := AssembleView(f, run)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if !structured {
|
||||
return MarkdownHTML(f.Body), false, nil
|
||||
}
|
||||
html, err := RenderNodes(nodes)
|
||||
if err != nil {
|
||||
@@ -285,8 +515,12 @@ func RenderHTMLPage(title, innerHTML string) string {
|
||||
if t == "" {
|
||||
t = "Marqdo"
|
||||
}
|
||||
return "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>" + t +
|
||||
"</title></head><body class=\"mq-document\"><main>" + innerHTML + "</main></body></html>"
|
||||
return renderHTMLPageWithHead("<title>"+t+"</title>", innerHTML)
|
||||
}
|
||||
|
||||
func renderHTMLPageWithHead(head, innerHTML string) string {
|
||||
return "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" + head +
|
||||
"</head><body class=\"mq-document\"><main>" + innerHTML + "</main></body></html>"
|
||||
}
|
||||
|
||||
// MarkdownHTML exposes render helper.
|
||||
@@ -385,6 +619,7 @@ func SystemRoutes() []map[string]any {
|
||||
return []map[string]any{
|
||||
{"method": "GET", "path": "/_part/*", "kind": "system"},
|
||||
{"method": "GET|POST", "path": "/_form/*", "kind": "system"},
|
||||
{"method": "POST", "path": "/_md", "kind": "system"},
|
||||
{"method": "POST", "path": "/_runtime/tasks", "kind": "system"},
|
||||
{"method": "GET", "path": "/_runtime/tasks/{id}", "kind": "system"},
|
||||
{"method": "POST", "path": "/_runtime/tasks/{id}/cancel", "kind": "system"},
|
||||
@@ -392,55 +627,85 @@ func SystemRoutes() []map[string]any {
|
||||
}
|
||||
}
|
||||
|
||||
// InspectBag builds {declared, system} from an app bag and/or scanned files.
|
||||
// InspectBag reads declarations only. A prepared app's actual handler inventory
|
||||
// is generated by httpx.InspectApp through the same registrar as NewHandler.
|
||||
func InspectBag(app map[string]any, declared []ArtifactFile) map[string]any {
|
||||
var dec []map[string]any
|
||||
for _, a := range declared {
|
||||
dec = append(dec, map[string]any{
|
||||
"method": a.Method,
|
||||
"path": a.Route,
|
||||
"kind": a.Kind,
|
||||
"file": a.Rel,
|
||||
})
|
||||
entries := map[string]map[string]any{}
|
||||
add := func(row map[string]any) {
|
||||
path := first(row, "path")
|
||||
method := first(row, "method")
|
||||
if method == "" {
|
||||
method = "GET"
|
||||
}
|
||||
if path == "" {
|
||||
return
|
||||
}
|
||||
key := method + " " + path
|
||||
if _, exists := entries[key]; !exists {
|
||||
entries[key] = row
|
||||
}
|
||||
}
|
||||
for _, file := range declared {
|
||||
add(map[string]any{"method": file.Method, "path": file.Route, "kind": file.Kind, "file": file.Rel})
|
||||
}
|
||||
if app != nil {
|
||||
switch rows := app["artifact_declared"].(type) {
|
||||
case []map[string]any:
|
||||
for _, row := range rows {
|
||||
add(row)
|
||||
}
|
||||
case []any:
|
||||
for _, value := range rows {
|
||||
if row, ok := value.(map[string]any); ok {
|
||||
add(row)
|
||||
}
|
||||
}
|
||||
}
|
||||
if app["page"] != nil {
|
||||
add(map[string]any{"method": "GET", "path": "/", "kind": "document"})
|
||||
}
|
||||
if routes, ok := app["routes"].(map[string]any); ok {
|
||||
for path := range routes {
|
||||
dec = append(dec, map[string]any{"method": "GET", "path": path, "kind": "declared"})
|
||||
add(map[string]any{"method": "GET", "path": path, "kind": "document"})
|
||||
}
|
||||
}
|
||||
if inv, ok := app["invoke_routes"].(map[string]any); ok {
|
||||
for key, v := range inv {
|
||||
row := map[string]any{"path": key, "kind": "endpoint"}
|
||||
if m, ok := v.(map[string]any); ok {
|
||||
if c, ok := m["class"].(string); ok && c != "" {
|
||||
row["class"] = c
|
||||
for _, group := range []string{"artifact_routes", "invoke_routes"} {
|
||||
if routes, ok := app[group].(map[string]any); ok {
|
||||
for key, value := range routes {
|
||||
spec, _ := value.(map[string]any)
|
||||
method, path := first(spec, "method"), first(spec, "path")
|
||||
if parts := strings.SplitN(key, " ", 2); len(parts) == 2 {
|
||||
if method == "" {
|
||||
method = parts[0]
|
||||
}
|
||||
if path == "" {
|
||||
path = parts[1]
|
||||
}
|
||||
} else if path == "" {
|
||||
path = key
|
||||
}
|
||||
if method, ok := m["method"].(string); ok && method != "" {
|
||||
row["method"] = method
|
||||
if method == "" {
|
||||
method = "GET"
|
||||
}
|
||||
if fn, ok := m["fn"].(string); ok && fn != "" {
|
||||
row["fn"] = fn
|
||||
row := map[string]any{"method": method, "path": path, "kind": "endpoint"}
|
||||
for _, name := range []string{"file", "class", "fn"} {
|
||||
if value := first(spec, name); value != "" {
|
||||
row[name] = value
|
||||
}
|
||||
}
|
||||
add(row)
|
||||
}
|
||||
dec = append(dec, row)
|
||||
}
|
||||
}
|
||||
if art, ok := app["artifact_routes"].(map[string]any); ok {
|
||||
for key, v := range art {
|
||||
m, _ := v.(map[string]any)
|
||||
dec = append(dec, map[string]any{
|
||||
"path": key,
|
||||
"kind": "endpoint",
|
||||
"method": fmt.Sprint(m["method"]),
|
||||
"file": fmt.Sprint(m["file"]),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
return map[string]any{
|
||||
"_type": "web_inspection",
|
||||
"declared": dec,
|
||||
"system": SystemRoutes(),
|
||||
keys := make([]string, 0, len(entries))
|
||||
for key := range entries {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
rows := make([]map[string]any, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
rows = append(rows, entries[key])
|
||||
}
|
||||
return map[string]any{"_type": "web_inspection", "scope": "metadata", "declared": rows, "system": SystemRoutes()}
|
||||
}
|
||||
@@ -142,3 +142,48 @@ func TestViewDocumentRejectsAnEmptyAssemblyAndAutomaticDataSource(t *testing.T)
|
||||
t.Fatalf("data source silently ignored: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInteractiveControlsUseTypedAttributesAndEscapedText(t *testing.T) {
|
||||
nodes := []any{map[string]any{"type":"form", "attrs":map[string]any{"id":"editor", "method":"post", "action":"/save"}, "value":[]any{
|
||||
map[string]any{"type":"label", "value":"Title", "attrs":map[string]any{"for":"title"}},
|
||||
map[string]any{"type":"input", "value":`"><script>alert(1)</script>`, "attrs":map[string]any{"id":"title", "name":"title", "required":true, "disabled":false, "maxlength":float64(120)}},
|
||||
map[string]any{"type":"textarea", "value":"</textarea><script>x</script>", "attrs":map[string]any{"id":"doc", "rows":float64(16), "aria-label":"Document"}},
|
||||
map[string]any{"type":"button", "value":"Save & return", "attrs":map[string]any{"type":"submit", "data-action":"save"}},
|
||||
map[string]any{"类型":"预格式", "值":"<waiting>", "属性":map[string]any{"id":"log","hidden":false}},
|
||||
}}}
|
||||
got,err := RenderNodes(nodes)
|
||||
if err != nil { t.Fatal(err) }
|
||||
for _, expected := range []string{`<form`,`action="/save"`,`for="title"`,`maxlength="120"`,` required`,`rows="16"`,`aria-label="Document"`,`data-action="save"`,`Save & return`,`</textarea>`,`<waiting>`} {
|
||||
if !strings.Contains(got,expected) { t.Fatalf("missing %s: %s",expected,got) }
|
||||
}
|
||||
if strings.Contains(got,"<script>") || strings.Contains(got," disabled") || strings.Contains(got," hidden") || strings.Contains(got,"map[") { t.Fatalf("control values leaked into markup: %s",got) }
|
||||
}
|
||||
func TestAttributeRecordsApplyToContainersAndLinks(t *testing.T) {
|
||||
got,err:=RenderNodes([]any{map[string]any{"type":"section","attrs":map[string]any{"id":"view-detail","hidden":true},"value":[]any{
|
||||
map[string]any{"type":"link","value":"Open","attrs":map[string]any{"href":"/a?x=1&y=2","title":"Detail"}},
|
||||
}}})
|
||||
if err != nil || !strings.Contains(got,`id="view-detail"`) || !strings.Contains(got," hidden") || !strings.Contains(got,`href="/a?x=1&y=2"`) { t.Fatalf("%v: %s",err,got) }
|
||||
for _,attrs:=range []map[string]any{
|
||||
{"onclick":"alert(1)"},{"style":"position:fixed"},{"data-x\" onload":"x"},{"href":"javascript:alert(1)"},{"required":"true"},{"title":[]any{"nested"}},
|
||||
} {
|
||||
if _,err:=RenderNodes([]any{map[string]any{"type":"button","value":"Run","attrs":attrs}});err==nil { t.Fatalf("accepted invalid attributes: %v",attrs) }
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourcesStayStructuredAndEscapeTheirURLs(t *testing.T) {
|
||||
got,err:=RenderNodes([]any{
|
||||
map[string]any{"type":"script","value":"/static/marqdo-bridge.js","attrs":map[string]any{"type":"module","data-mq-wasm":"/static/runtime.wasm","data-mq-source-url":"/static/client.mq.md"}},
|
||||
map[string]any{"type":"stylesheet","value":"/static/theme.css?x=1&y=2"},
|
||||
})
|
||||
if err!=nil {t.Fatal(err)}
|
||||
for _,want:=range []string{`<script src="/static/marqdo-bridge.js"`,`type="module"`,`data-mq-source-url="/static/client.mq.md"`,`<link rel="stylesheet" href="/static/theme.css?x=1&y=2"`} {
|
||||
if !strings.Contains(got,want) {t.Fatalf("missing %s: %s",want,got)}
|
||||
}
|
||||
for _,node:=range []map[string]any{
|
||||
{"type":"script","value":"javascript:alert(1)"},
|
||||
{"type":"script","value":"/static/a.js","attrs":map[string]any{"src":"/other.js"}},
|
||||
{"type":"stylesheet","value":"/theme.css","attrs":map[string]any{"rel":"preload"}},
|
||||
} {
|
||||
if _,err:=RenderNodes([]any{node});err==nil {t.Fatalf("accepted invalid resource: %v",node)}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package artifact
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/assets"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/render"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/table"
|
||||
)
|
||||
|
||||
// DocumentHead is a closed, pure View Resource. It contributes only metadata
|
||||
// and existing native head links; it cannot mutate page layout or server state.
|
||||
type DocumentHead struct {
|
||||
Meta map[string]any
|
||||
Links []assets.HeadLink
|
||||
}
|
||||
|
||||
func headRows(value any) ([]map[string]any, error) {
|
||||
if value == nil {
|
||||
return nil, nil
|
||||
}
|
||||
switch data := value.(type) {
|
||||
case []any:
|
||||
rows := make([]map[string]any, 0, len(data))
|
||||
for _, value := range data {
|
||||
row, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("document_head: expected table records")
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
return rows, nil
|
||||
case map[string]any:
|
||||
if len(data) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
arrays, scalars, count := 0, 0, -1
|
||||
for _, value := range data {
|
||||
if column, ok := value.([]any); ok {
|
||||
arrays++
|
||||
if count >= 0 && count != len(column) {
|
||||
return nil, fmt.Errorf("document_head: column lengths differ")
|
||||
}
|
||||
count = len(column)
|
||||
} else {
|
||||
scalars++
|
||||
}
|
||||
}
|
||||
if arrays > 0 && scalars > 0 {
|
||||
return nil, fmt.Errorf("document_head: mixed column and scalar cells")
|
||||
}
|
||||
if arrays > 0 && count == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
rows, _ := table.AsRows(data).([]any)
|
||||
return headRows(rows)
|
||||
default:
|
||||
return nil, fmt.Errorf("document_head: expected a table or None")
|
||||
}
|
||||
}
|
||||
|
||||
func headURL(raw string) error {
|
||||
if raw == "" || strings.ContainsAny(raw, "\r\n\t") || raw != strings.TrimSpace(raw) ||
|
||||
strings.Contains(raw, "\\") || strings.HasPrefix(raw, "//") {
|
||||
return fmt.Errorf("document_head: resource URL must be site-relative or http(s)")
|
||||
}
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil || parsed == nil {
|
||||
return fmt.Errorf("document_head: invalid resource URL")
|
||||
}
|
||||
if parsed.Scheme == "" {
|
||||
if !strings.HasPrefix(raw, "/") {
|
||||
return fmt.Errorf("document_head: relative URL must start with /")
|
||||
}
|
||||
} else if (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
|
||||
return fmt.Errorf("document_head: resource URL must be site-relative or http(s)")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseDocumentHead validates before either preview or listening. No URL is
|
||||
// fetched and no script is executed by this native projection.
|
||||
func ParseDocumentHead(resource map[string]any) (DocumentHead, error) {
|
||||
out := DocumentHead{Meta: map[string]any{}}
|
||||
if first(resource, "_type") != "document_head" {
|
||||
return out, fmt.Errorf("document_head: incorrect resource type")
|
||||
}
|
||||
for key := range resource {
|
||||
if key != "_type" && key != "meta" && key != "links" {
|
||||
return out, fmt.Errorf("document_head: unsupported field %q", key)
|
||||
}
|
||||
}
|
||||
rows, err := headRows(resource["meta"])
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
for key, value := range row {
|
||||
if key != "key" && key != "键" && key != "name" && key != "value" && key != "值" && key != "@" && key != "行" && key != "row" && key != "id" {
|
||||
return out, fmt.Errorf("document_head: unsupported metadata field %q", key)
|
||||
}
|
||||
switch value.(type) {
|
||||
case nil, string, bool, float64:
|
||||
default:
|
||||
return out, fmt.Errorf("document_head: metadata cells must be scalar values")
|
||||
}
|
||||
}
|
||||
key := first(row, "键", "key", "name")
|
||||
value := first(row, "值", "value")
|
||||
if key == "" {
|
||||
return out, fmt.Errorf("document_head: metadata requires key/value rows")
|
||||
}
|
||||
if strings.EqualFold(key, "charset") || strings.EqualFold(key, "viewport") || strings.EqualFold(key, "csrf-token") {
|
||||
return out, fmt.Errorf("document_head: %s is owned by the document runtime", key)
|
||||
}
|
||||
if key == "canonical" || key == "icon" || key == "favicon" {
|
||||
if err := headURL(value); err != nil {
|
||||
return out, err
|
||||
}
|
||||
}
|
||||
if existing, ok := out.Meta[key]; ok && existing != value {
|
||||
return out, fmt.Errorf("document_head: conflicting metadata %q", key)
|
||||
}
|
||||
out.Meta[key] = value
|
||||
}
|
||||
rows, err = headRows(resource["links"])
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
// Use the same link field aliases and native rendering as ordinary Documents.
|
||||
for _, row := range rows {
|
||||
for key, value := range row {
|
||||
switch value.(type) {
|
||||
case nil, string, bool, float64:
|
||||
default:
|
||||
return out, fmt.Errorf("document_head: link cells must be scalar values")
|
||||
}
|
||||
if value == nil {
|
||||
continue
|
||||
}
|
||||
switch key {
|
||||
case "关系", "rel", "Rel", "地址", "href", "src", "url", "Href", "Src", "URL",
|
||||
"类型", "type", "Type", "尺寸", "sizes", "Sizes", "媒体", "media", "Media",
|
||||
"作为", "as", "As", "跨域", "crossorigin", "crossOrigin",
|
||||
"推迟", "defer", "Defer", "异步", "async", "Async", "版本", "version", "Version", "v", "@", "行", "row", "id":
|
||||
default:
|
||||
return out, fmt.Errorf("document_head: unsupported link field %q", key)
|
||||
}
|
||||
}
|
||||
if err := headURL(first(row, "地址", "href", "src", "url", "Href", "Src", "URL")); err != nil {
|
||||
return out, err
|
||||
}
|
||||
links := assets.AsHeadLinks([]any{row})
|
||||
if len(links) != 1 {
|
||||
return out, fmt.Errorf("document_head: each link requires href")
|
||||
}
|
||||
if err := headURL(links[0].Href); err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Links = append(out.Links, links[0])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CollectDocumentHead traverses only real View containers. Resource private
|
||||
// records are never interpreted as nodes, and conflicting declarations fail.
|
||||
func CollectDocumentHead(nodes any) (DocumentHead, error) {
|
||||
out := DocumentHead{Meta: map[string]any{}}
|
||||
var walk func(any, int) error
|
||||
walk = func(nodes any, depth int) error {
|
||||
if depth > 64 {
|
||||
return fmt.Errorf("View: nesting exceeds 64 levels")
|
||||
}
|
||||
rows, err := viewRows(nodes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, value := range rows {
|
||||
row, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return fmt.Errorf("View: expected row map")
|
||||
}
|
||||
kind := strings.ToLower(first(row, "type", "类型"))
|
||||
child := row["value"]
|
||||
if child == nil {
|
||||
child = row["值"]
|
||||
}
|
||||
if tag, _ := containerTag(kind); tag != "" {
|
||||
if child == nil {
|
||||
return fmt.Errorf("View %s: missing child rows", kind)
|
||||
}
|
||||
if err := walk(child, depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if kind == "resource" || kind == "资源" {
|
||||
resource, ok := child.(map[string]any)
|
||||
if !ok || first(resource, "_type") != "document_head" {
|
||||
continue
|
||||
}
|
||||
head, err := ParseDocumentHead(resource)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for key, value := range head.Meta {
|
||||
if existing, ok := out.Meta[key]; ok && existing != value {
|
||||
return fmt.Errorf("document_head: conflicting metadata %q", key)
|
||||
}
|
||||
out.Meta[key] = value
|
||||
}
|
||||
for _, link := range head.Links {
|
||||
duplicate := false
|
||||
for _, existing := range out.Links {
|
||||
if reflect.DeepEqual(existing, link) {
|
||||
duplicate = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !duplicate {
|
||||
out.Links = append(out.Links, link)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
err := walk(nodes, 0)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// RenderViewDocument shares a single pure shell for offline and request-time
|
||||
// nodes. Metadata never becomes visible content or a fragment response.
|
||||
func RenderViewDocument(title string, nodes any, resources ResourceRenderer) (string, error) {
|
||||
head, err := CollectDocumentHead(nodes)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
body, err := RenderNodesWithResources(nodes, resources)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return renderHTMLPageWithHead(render.DocumentHead(title, head.Meta, head.Links), body), nil
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package artifact
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func headNode(meta, links any) any {
|
||||
return map[string]any{"type": "resource", "slot": "head", "value": map[string]any{"_type": "document_head", "meta": meta, "links": links}}
|
||||
}
|
||||
|
||||
func TestDocumentHeadPreservesMetadataAndLinksInTheActualHeadOnly(t *testing.T) {
|
||||
meta := map[string]any{"key": []any{"description", "og:title", "canonical"}, "value": []any{`Text <tag> "quote" & literal`, "Actual OG", "/articles"}}
|
||||
links := []any{
|
||||
map[string]any{"关系": "preconnect", "地址": "https://fonts.example.test", "跨域": "anonymous"},
|
||||
map[string]any{"rel": "stylesheet", "href": "/theme.css?x=1&y=2"},
|
||||
map[string]any{"rel": "module", "href": "/client.js", "defer": false},
|
||||
}
|
||||
// Repeated imports should deduplicate equal links, including boolean flags.
|
||||
nodes := []any{map[string]any{"type": "column", "value": []any{
|
||||
headNode(meta, links), headNode(nil, links),
|
||||
map[string]any{"type": "markdown", "value": "# Actual page"},
|
||||
}}}
|
||||
got, err := RenderViewDocument("Actual document", nodes, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head, body, ok := strings.Cut(got, "</head>")
|
||||
if !ok {
|
||||
t.Fatal(got)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"<title>Actual document</title>", `<meta name="description" content="Text <tag> "quote" & literal"`,
|
||||
`<meta property="og:title" content="Actual OG"`, `<link rel="canonical" href="/articles"`,
|
||||
`<link rel="preconnect" href="https://fonts.example.test" crossorigin="anonymous"`,
|
||||
`<link rel="stylesheet" href="/theme.css?x=1&y=2"`, `<script type="module" src="/client.js"></script>`,
|
||||
} {
|
||||
if !strings.Contains(head, want) {
|
||||
t.Fatalf("missing %s: %s", want, head)
|
||||
}
|
||||
}
|
||||
if strings.Count(head, `href="/theme.css`) != 1 || strings.Count(head, `src="/client.js"`) != 1 {
|
||||
t.Fatal("duplicate head resource: " + head)
|
||||
}
|
||||
if strings.Contains(body, "Actual OG") || strings.Contains(body, "fonts.example") || strings.Contains(body, "slot-head") || !strings.Contains(body, "Actual page") {
|
||||
t.Fatal(body)
|
||||
}
|
||||
calls := 0
|
||||
fragment, err := RenderNodesWithResources(nodes, func(map[string]any) (string, error) { calls++; return "unexpected", nil })
|
||||
if err != nil || calls != 0 || strings.Contains(fragment, "<meta") || strings.Contains(fragment, "fonts.example") {
|
||||
t.Fatalf("%d %v %s", calls, err, fragment)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocumentHeadRejectsConflictsMalformedTablesAndOpaqueMutation(t *testing.T) {
|
||||
valid := map[string]any{"_type": "document_head", "meta": nil, "links": nil}
|
||||
for _, resource := range []map[string]any{
|
||||
{"_type": "other"},
|
||||
{"_type": "document_head", "html": "<script>x</script>"},
|
||||
{"_type": "document_head", "body_class": "admin"},
|
||||
{"_type": "document_head", "meta": []any{42}},
|
||||
{"_type": "document_head", "meta": map[string]any{"key": []any{"a", "b"}, "value": []any{"one"}}},
|
||||
{"_type": "document_head", "meta": map[string]any{"key": "description", "value": []any{"nested"}}},
|
||||
{"_type": "document_head", "meta": map[string]any{"key": "viewport", "value": "owned"}},
|
||||
{"_type": "document_head", "meta": []any{map[string]any{"key": "description", "value": "a"}, map[string]any{"key": "description", "value": "b"}}},
|
||||
{"_type": "document_head", "links": []any{map[string]any{"rel": "script", "href": "/a.js", "onclick": "x"}}},
|
||||
{"_type": "document_head", "links": []any{map[string]any{"rel": "stylesheet", "href": "/a.css", "media": map[string]any{"x": "nested"}}}},
|
||||
{"_type": "document_head", "links": []any{map[string]any{"rel": "stylesheet"}}},
|
||||
} {
|
||||
if _, err := ParseDocumentHead(resource); err == nil {
|
||||
t.Fatalf("accepted %#v", resource)
|
||||
}
|
||||
}
|
||||
if _, err := ParseDocumentHead(valid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, url := range []string{"javascript:alert(1)", "data:text/javascript,x", "//other.test/a", "relative.css", "/\\other.test/a", "https://", "/a\n.js"} {
|
||||
for _, resource := range []map[string]any{
|
||||
{"_type": "document_head", "links": []any{map[string]any{"rel": "script", "href": url}}},
|
||||
{"_type": "document_head", "meta": map[string]any{"key": "canonical", "value": url}},
|
||||
} {
|
||||
if _, err := ParseDocumentHead(resource); err == nil {
|
||||
t.Fatalf("accepted %q", url)
|
||||
}
|
||||
}
|
||||
}
|
||||
conflict := []any{headNode(map[string]any{"key": "description", "value": "first"}, nil),
|
||||
map[string]any{"类型": "纵排", "值": []any{headNode(map[string]any{"键": "description", "值": "second"}, nil)}}}
|
||||
if _, err := CollectDocumentHead(conflict); err == nil {
|
||||
t.Fatal("nested head conflict silently overwrote metadata")
|
||||
}
|
||||
private := []any{map[string]any{"type": "resource", "value": map[string]any{"_type": "data_query", "where": headNode(nil, nil)}}}
|
||||
head, err := CollectDocumentHead(private)
|
||||
if err != nil || len(head.Links) != 0 || len(head.Meta) != 0 {
|
||||
t.Fatalf("walked private Resource: %v %#v", err, head)
|
||||
}
|
||||
var deep any = []any{headNode(nil, nil)}
|
||||
for i := 0; i < 66; i++ {
|
||||
deep = []any{map[string]any{"type": "row", "value": deep}}
|
||||
}
|
||||
if _, err := CollectDocumentHead(deep); err == nil {
|
||||
t.Fatal("unbounded head traversal")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package artifact
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFindSlotKeepsNestedTypedResourcesAndRejectsAmbiguity(t *testing.T) {
|
||||
descriptor := map[string]any{"_type": "data_query", "source": "articles", "slot": "not-a-view-slot"}
|
||||
nodes := []any{map[string]any{"type": "row", "slot": "layout", "value": []any{
|
||||
map[string]any{"类型": "纵排", "槽": "main", "值": []any{
|
||||
map[string]any{"type": "resource", "slot": "articles", "value": descriptor},
|
||||
}},
|
||||
map[string]any{"type": "markdown", "slot": "sidebar", "value": "Separate"},
|
||||
}}}
|
||||
selected, found, err := FindSlot(nodes, "articles")
|
||||
if err != nil || !found {
|
||||
t.Fatalf("%v %v", found, err)
|
||||
}
|
||||
calls := 0
|
||||
html, err := RenderNodesWithResources(selected, func(value map[string]any) (string, error) {
|
||||
calls++
|
||||
if value["source"] != "articles" {
|
||||
t.Fatal(value)
|
||||
}
|
||||
return "<p>Actual request value</p>", nil
|
||||
})
|
||||
if err != nil || calls != 1 || !strings.Contains(html, "Actual request value") || strings.Contains(html, "Separate") {
|
||||
t.Fatalf("%d %v %s", calls, err, html)
|
||||
}
|
||||
if _, found, err := FindSlot(nodes, "not-a-view-slot"); err != nil || found {
|
||||
t.Fatalf("walked Resource internals: %v %v", found, err)
|
||||
}
|
||||
duplicate := append(nodes, map[string]any{"type": "text", "slot": "articles", "value": "Ambiguous"})
|
||||
if _, _, err := FindSlot(duplicate, "articles"); err == nil {
|
||||
t.Fatal("duplicate slot accepted")
|
||||
}
|
||||
if _, _, err := FindSlot([]any{42}, "articles"); err == nil {
|
||||
t.Fatal("malformed View accepted")
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,13 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/app"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/auth"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/db"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/password"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/ratelimit"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/rbac"
|
||||
@@ -372,7 +374,7 @@ func (st *state) hasPageRoute(path string) bool {
|
||||
return ok
|
||||
}
|
||||
|
||||
func (st *state) mountAuthRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountAuthRoutes(mux routeRegistrar) {
|
||||
st.mountOIDCRoutes(mux)
|
||||
if st.auth.users == nil && !(st.auth.rbac && st.auth.register) && !st.oidcEnabled() {
|
||||
return
|
||||
@@ -416,6 +418,9 @@ func (st *state) mountAuthRoutes(mux *http.ServeMux) {
|
||||
if adminHome == "" {
|
||||
adminHome = "/admin"
|
||||
}
|
||||
// The canonical no-slash path must be registered too: the global
|
||||
// trailing-slash normalizer otherwise triggers a ServeMux redirect loop.
|
||||
mux.HandleFunc("GET "+adminHome, st.handleAdminHome)
|
||||
mux.HandleFunc("GET "+adminHome+"/{$}", st.handleAdminHome)
|
||||
}
|
||||
}
|
||||
@@ -501,7 +506,6 @@ func (st *state) handleLoginPost(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, dest, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
|
||||
// tryLogin: GFM users first, then web_users when RBAC is on.
|
||||
func (st *state) tryLogin(username, password string) map[string]any {
|
||||
if st.auth.users != nil {
|
||||
@@ -558,8 +562,45 @@ func (st *state) handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (st *state) handleAdminHome(w http.ResponseWriter, r *http.Request) {
|
||||
// Only explicitly mounted forms expose their associated business tables.
|
||||
// Never enumerate session/credential tables just because they share a DB.
|
||||
var body strings.Builder
|
||||
body.WriteString(`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Admin</title></head><body><h1>Admin</h1><p>Mounted forms and their current business records (up to 100 rows per table).</p><nav><a href="/">Site</a></nav>`)
|
||||
seen := map[string]bool{}
|
||||
for _, id := range sortedKeys(st.forms) {
|
||||
selected, ok := st.forms[id].(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
tableName, _ := selected["table"].(string)
|
||||
fmt.Fprintf(&body, `<section><h2>%s</h2><p><a href="/_form/%s">Open form</a></p>`, esc(id), esc(url.PathEscape(id)))
|
||||
if tableName != "" && st.dbURL != "" && !seen[tableName] {
|
||||
current, err := db.Select(st.dbURL, tableName, 100, db.SelectOpts{})
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
var data strings.Builder
|
||||
encoder := json.NewEncoder(&data)
|
||||
encoder.SetIndent("", " ")
|
||||
encoder.SetEscapeHTML(false)
|
||||
if err := encoder.Encode(current["rows"]); err != nil {
|
||||
http.Error(w, "cannot encode admin records", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// Escape once for HTML, preserving readable literal angle brackets
|
||||
// instead of displaying JSON's optional Unicode escape sequences.
|
||||
fmt.Fprintf(&body, `<h3>%s</h3><pre style="white-space:pre-wrap;overflow-wrap:anywhere">%s</pre>`, esc(tableName), esc(data.String()))
|
||||
seen[tableName] = true
|
||||
}
|
||||
body.WriteString("</section>")
|
||||
}
|
||||
if len(st.forms) == 0 {
|
||||
body.WriteString("<p>No forms are mounted.</p>")
|
||||
}
|
||||
body.WriteString("</body></html>")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, "<!doctype html><html><body><h1>Admin</h1><p>Site administration.</p></body></html>")
|
||||
_, _ = io.WriteString(w, body.String())
|
||||
}
|
||||
|
||||
func loginDest(r *http.Request, fallback string) string {
|
||||
|
||||
@@ -114,7 +114,7 @@ func (st *state) writeRegisterFailure(w http.ResponseWriter, r *http.Request, ms
|
||||
_, _ = io.WriteString(w, registerPageHTML(st.auth.registerPath, &loc, csrf))
|
||||
}
|
||||
|
||||
func (st *state) mountExtraLoginPosts(mux *http.ServeMux, already map[string]bool) {
|
||||
func (st *state) mountExtraLoginPosts(mux routeRegistrar, already map[string]bool) {
|
||||
for path, pageV := range st.routes {
|
||||
if already[path] {
|
||||
continue
|
||||
|
||||
@@ -74,7 +74,7 @@ func (st *state) oidcFallbackNext(r *http.Request) string {
|
||||
return "/"
|
||||
}
|
||||
|
||||
func (st *state) mountOIDCRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountOIDCRoutes(mux routeRegistrar) {
|
||||
if !st.oidcEnabled() {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -56,4 +56,3 @@ func TestResolveSessionReplacesStaleCookie(t *testing.T) {
|
||||
t.Fatalf("live session should not Set-Cookie again")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/app"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/artifact"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/middleware"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/oidc"
|
||||
)
|
||||
|
||||
type recordedMux struct {
|
||||
validate *http.ServeMux
|
||||
patterns []string
|
||||
}
|
||||
|
||||
func (mux *recordedMux) Handle(pattern string, _ http.Handler) {
|
||||
// Validate registration conflicts without retaining or running handlers.
|
||||
mux.validate.HandleFunc(pattern, func(http.ResponseWriter, *http.Request) {})
|
||||
mux.patterns = append(mux.patterns, pattern)
|
||||
}
|
||||
func (mux *recordedMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
|
||||
mux.Handle(pattern, http.HandlerFunc(handler))
|
||||
}
|
||||
|
||||
var tailWildcard = regexp.MustCompile(`\{([^{}]+)\.\.\.\}`)
|
||||
|
||||
func inspectionPath(path string) string {
|
||||
path = strings.TrimSuffix(path, "{$}")
|
||||
return tailWildcard.ReplaceAllString(path, "{*$1}")
|
||||
}
|
||||
|
||||
// InspectApp executes only trusted registration logic. It does not create a
|
||||
// session, reset global runtime state, query a DB, run Documents or listen.
|
||||
func InspectApp(bag map[string]any) (report map[string]any, err error) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
report = nil
|
||||
err = fmt.Errorf("web.inspect: invalid route registration: %v", recovered)
|
||||
}
|
||||
}()
|
||||
if bag == nil {
|
||||
bag = map[string]any{}
|
||||
}
|
||||
routes := routeMapOf(bag, "routes")
|
||||
page, _ := bag["page"].(map[string]any)
|
||||
forms := map[string]any{}
|
||||
if existing, ok := bag["forms"].(map[string]any); ok {
|
||||
for key, value := range existing {
|
||||
forms[key] = value
|
||||
}
|
||||
}
|
||||
collectPageForms(page, forms)
|
||||
for _, value := range routes {
|
||||
if page, ok := value.(map[string]any); ok {
|
||||
collectPageForms(page, forms)
|
||||
}
|
||||
}
|
||||
root := strOpt(bag, "artifact_root", "")
|
||||
staticDir := strOpt(bag, "static_dir", "")
|
||||
if staticDir != "" {
|
||||
staticDir = resolvePath(staticDir, root)
|
||||
}
|
||||
icons, err := iconRoutesFromBag(bag, root, staticDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st := &state{
|
||||
page: page, routes: routes, forms: forms, mw: middleware.Parse(bag), entryDir: root,
|
||||
iconRoutes: icons, redirects: redirectsOf(bag), sitemapRoutes: sitemapRoutesOf(bag),
|
||||
robotsBody: robotsBodyOf(bag), page404: pageOf(bag, "page_404"), page500: pageOf(bag, "page_500"),
|
||||
uploadRoutes: routeMapOf(bag, "upload_routes"), downloadRoutes: routeMapOf(bag, "download_routes"),
|
||||
wsRoutes: routeMapOf(bag, "ws_routes"), galleryRoutes: routeMapOf(bag, "gallery_routes"),
|
||||
proxyRoutes: routeMapOf(bag, "proxy_routes"), invokeRoutes: routeMapOf(bag, "invoke_routes"),
|
||||
artifactRoutes: routeMapOf(bag, "artifact_routes"), auth: authConfigOf(bag), oidc: oidc.ParseConfig(bag),
|
||||
}
|
||||
// Only a nonempty DB URL determines whether DB-backed routes are enabled.
|
||||
// Its existence and contents are intentionally not inspected here.
|
||||
st.dbURL = dbURLOf(bag)
|
||||
staticMount := app.NormalizeStaticMount(strOpt(bag, "static_mount", "/static"))
|
||||
mux := &recordedMux{validate: http.NewServeMux()}
|
||||
st.registerRoutes(mux, staticDir, staticMount, false)
|
||||
report = artifact.InspectBag(bag, nil)
|
||||
declarations := map[string]map[string]any{}
|
||||
byPath := map[string]map[string]any{}
|
||||
for _, row := range report["declared"].([]map[string]any) {
|
||||
path := inspectionPath(goMuxPattern(fmt.Sprint(row["path"])))
|
||||
method := fmt.Sprint(row["method"])
|
||||
declarations[method+" "+path] = row
|
||||
if _, exists := byPath[path]; !exists {
|
||||
byPath[path] = row
|
||||
}
|
||||
}
|
||||
// Classification uses the explicitly supplied Resource paths; the method
|
||||
// and presence still come from the actual recorded registration.
|
||||
for group, kind := range map[string]string{
|
||||
"ws_routes": "websocket", "upload_routes": "upload", "download_routes": "download",
|
||||
"gallery_routes": "gallery", "proxy_routes": "proxy", "redirects": "redirect", "sitemap_routes": "sitemap",
|
||||
} {
|
||||
for key, value := range routeMapOf(bag, group) {
|
||||
spec, _ := value.(map[string]any)
|
||||
path := strOpt(spec, "path", key)
|
||||
if parts := strings.SplitN(path, " ", 2); len(parts) == 2 {
|
||||
path = parts[1]
|
||||
}
|
||||
path = inspectionPath(goMuxPattern(path))
|
||||
byPath[path] = map[string]any{"path": path, "kind": kind}
|
||||
}
|
||||
}
|
||||
for _, query := range st.mw.JSONRoutes {
|
||||
row := map[string]any{"path": query.Path, "method": query.Method, "kind": "data_query"}
|
||||
declarations[query.Method+" "+query.Path] = row
|
||||
}
|
||||
var declared, system []map[string]any
|
||||
seen := map[string]bool{}
|
||||
for _, pattern := range mux.patterns {
|
||||
method, path := "*", pattern
|
||||
if parts := strings.SplitN(pattern, " ", 2); len(parts) == 2 {
|
||||
method, path = parts[0], parts[1]
|
||||
}
|
||||
path = inspectionPath(path)
|
||||
if method == "*" && (path == staticMount || path == staticMount+"/") && strOpt(bag, "static_dir", "") != "" {
|
||||
method = "GET|HEAD"
|
||||
}
|
||||
key := method + " " + path
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
row := map[string]any{"method": method, "path": path, "kind": "system"}
|
||||
source, found := declarations[key]
|
||||
if !found {
|
||||
source, found = byPath[path]
|
||||
}
|
||||
if found {
|
||||
for key, value := range source {
|
||||
if key != "method" && key != "path" {
|
||||
row[key] = value
|
||||
}
|
||||
}
|
||||
declared = append(declared, row)
|
||||
} else {
|
||||
system = append(system, row)
|
||||
}
|
||||
}
|
||||
less := func(rows []map[string]any) {
|
||||
sort.Slice(rows, func(i, j int) bool {
|
||||
a, b := fmt.Sprint(rows[i]["path"]), fmt.Sprint(rows[j]["path"])
|
||||
if a != b {
|
||||
return a < b
|
||||
}
|
||||
return fmt.Sprint(rows[i]["method"]) < fmt.Sprint(rows[j]["method"])
|
||||
})
|
||||
}
|
||||
less(declared)
|
||||
less(system)
|
||||
if declared == nil {
|
||||
declared = []map[string]any{}
|
||||
}
|
||||
if system == nil {
|
||||
system = []map[string]any{}
|
||||
}
|
||||
report["scope"] = "registered"
|
||||
report["declared"] = declared
|
||||
report["system"] = system
|
||||
return report, nil
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/app"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/form"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/session"
|
||||
)
|
||||
|
||||
func TestInspectionUsesActualRegistrationsAfterResourceBindingsWithoutExecutingThem(t *testing.T) {
|
||||
filename := filepath.Join(t.TempDir(), "must-not-create.db")
|
||||
bag := app.New(map[string]any{"page": map[string]any{"title": "Home"},
|
||||
"db": map[string]any{"url": "sqlite:" + filename}, "admin": true})
|
||||
bag["artifact_declared"] = []any{map[string]any{"method": "GET", "path": "/", "kind": "web", "file": "index.mq.md"}}
|
||||
// A cached observation is deliberately stale and must never be returned.
|
||||
bag["inspect"] = map[string]any{"declared": []any{map[string]any{"path": "/stale"}}}
|
||||
var err error
|
||||
bag, err = app.Route(bag, "/post/{id}", map[string]any{"title": "Post"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := InspectApp(bag)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bag, err = app.Auth(bag, []any{map[string]any{"username": "fixture", "password": "never-return-this-secret"}}, map[string]any{"login_path": "/members/login"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bag, err = app.MountForm(bag, "article", form.New("articles", "insert", ""))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bag["ws_routes"] = map[string]any{"/live/{id}": map[string]any{"mode": "echo"}}
|
||||
bag["middleware"] = map[string]any{"json_routes": map[string]any{"api/items": map[string]any{"table": "items", "method": "GET"}}}
|
||||
bag["artifact_routes"] = map[string]any{"GET /api/ping": map[string]any{"method": "GET", "path": "/api/ping", "file": "/never-run.mq.md"}}
|
||||
bag["static_dir"] = "."
|
||||
bag["static_mount"] = "/assets"
|
||||
session.Configure(session.Config{TTLSec: 3600})
|
||||
session.Reset(3600)
|
||||
sid := session.NewID(3600)
|
||||
session.SetValue(sid, "inspection_marker", "retained")
|
||||
report, err := InspectApp(bag)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if report["scope"] != "registered" {
|
||||
t.Fatal(report)
|
||||
}
|
||||
type route struct{ method, path string }
|
||||
observed := map[route]string{}
|
||||
for _, group := range []string{"declared", "system"} {
|
||||
for _, row := range report[group].([]map[string]any) {
|
||||
key := route{row["method"].(string), row["path"].(string)}
|
||||
if _, seen := observed[key]; seen {
|
||||
t.Fatalf("duplicate registered route: %#v", key)
|
||||
}
|
||||
observed[key] = group
|
||||
}
|
||||
}
|
||||
for _, key := range []route{{"GET", "/"}, {"GET", "/post/{id}"}, {"GET", "/live/{id}"}, {"GET", "/api/items"}, {"GET", "/api/ping"}} {
|
||||
if observed[key] != "declared" {
|
||||
t.Fatalf("missing current Resource declaration %#v: %#v", key, report)
|
||||
}
|
||||
}
|
||||
for _, key := range []route{{"POST", "/_md"}, {"GET", "/_form/{id}"}, {"POST", "/_form/{id}"},
|
||||
{"GET", "/post/{id}/_part/{part}"}, {"GET", "/members/login"}, {"POST", "/members/login"},
|
||||
{"GET", "/admin/login"}, {"GET", "/admin"}, {"GET", "/admin/"}, {"GET|HEAD", "/assets/"}} {
|
||||
if observed[key] != "system" {
|
||||
t.Fatalf("missing actual system route %#v: %#v", key, report)
|
||||
}
|
||||
}
|
||||
encoded, _ := json.Marshal(report)
|
||||
if strings.Contains(string(encoded), "never-return-this-secret") || strings.Contains(string(encoded), "/stale") {
|
||||
t.Fatalf("inspection leaked unrelated app state: %s", encoded)
|
||||
}
|
||||
if value, ok := session.GetValue(sid, "inspection_marker"); !ok || value != "retained" {
|
||||
t.Fatal("inspection reset runtime sessions")
|
||||
}
|
||||
if _, err := os.Stat(filename); !os.IsNotExist(err) {
|
||||
t.Fatalf("inspection opened a database: %v", err)
|
||||
}
|
||||
prior, _ := json.Marshal(before)
|
||||
if strings.Contains(string(prior), "/live/") {
|
||||
t.Fatal("inspection mutated an earlier returned observation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectionRejectsActualRouteConflictsWithoutStartingTheServer(t *testing.T) {
|
||||
bag := app.New(map[string]any{"page": map[string]any{}})
|
||||
bag["routes"] = map[string]any{"/_md": map[string]any{}}
|
||||
bag["artifact_routes"] = map[string]any{"POST /_md": map[string]any{"method": "POST", "path": "/_md", "file": "never-run.mq.md"}}
|
||||
if _, err := InspectApp(bag); err == nil || !strings.Contains(err.Error(), "invalid route registration") {
|
||||
t.Fatalf("conflicting routes were advertised as usable: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/app"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/artifact"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/assets"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/db"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/form"
|
||||
@@ -129,6 +130,23 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
st.registerRoutes(mux, staticDir, staticMount, true)
|
||||
|
||||
handler := withMiddleware(mux, mw)
|
||||
handler = withRBAC(handler, authCfg.gates, authCfg.loginPath)
|
||||
handler = withTenant(handler, st.tenant)
|
||||
handler = withStripTrailingSlash(handler)
|
||||
return handler, nil
|
||||
}
|
||||
|
||||
// routeRegistrar is shared by the real server and its read-only inventory.
|
||||
// Recording registrations does not invoke any captured handler.
|
||||
type routeRegistrar interface {
|
||||
Handle(string, http.Handler)
|
||||
HandleFunc(string, func(http.ResponseWriter, *http.Request))
|
||||
}
|
||||
|
||||
func (st *state) registerRoutes(mux routeRegistrar, staticDir, staticMount string, logSetup bool) {
|
||||
mux.HandleFunc("GET /{$}", st.handleHome)
|
||||
// Part slot uses {part} (not {id}) so dynamic routes like /desk/posts/{id}
|
||||
// do not collide with Go ServeMux duplicate wildcard names.
|
||||
@@ -137,10 +155,10 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
mux.HandleFunc("POST /_form/{id}", st.handleFormPost)
|
||||
mux.HandleFunc("POST /_md", st.handleMarkdownPreview)
|
||||
|
||||
paths := sortedKeys(routes)
|
||||
paths := sortedKeys(st.routes)
|
||||
for _, p := range paths {
|
||||
routePath := p
|
||||
pageV, _ := routes[routePath].(map[string]any)
|
||||
pageV, _ := st.routes[routePath].(map[string]any)
|
||||
if pageV == nil {
|
||||
pageV = map[string]any{}
|
||||
}
|
||||
@@ -158,7 +176,7 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
}
|
||||
}
|
||||
|
||||
for _, jr := range mw.JSONRoutes {
|
||||
for _, jr := range st.mw.JSONRoutes {
|
||||
route := jr
|
||||
pattern := route.Method + " " + route.Path
|
||||
mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -168,16 +186,20 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
|
||||
// Icon routes before the static prefix so /static/favicon.svg does not
|
||||
// conflict with Go 1.22+ ServeMux method/path overlap rules.
|
||||
for _, ir := range iconRoutes {
|
||||
for _, ir := range st.iconRoutes {
|
||||
url := ir.URL
|
||||
path := ir.Path
|
||||
ct := ir.ContentType
|
||||
if staticDir != "" && (url == staticMount || strings.HasPrefix(url, staticMount+"/")) {
|
||||
// FileServer under staticMount already serves these paths.
|
||||
fmt.Fprintf(os.Stderr, "marqdo web icon: %s → static %s (via %s)\n", url, path, staticMount)
|
||||
if logSetup {
|
||||
fmt.Fprintf(os.Stderr, "marqdo web icon: %s → static %s (via %s)\n", url, path, staticMount)
|
||||
}
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "marqdo web icon: %s → %s (%s)\n", url, path, ct)
|
||||
if logSetup {
|
||||
fmt.Fprintf(os.Stderr, "marqdo web icon: %s → %s (%s)\n", url, path, ct)
|
||||
}
|
||||
mux.HandleFunc("GET "+url, func(w http.ResponseWriter, r *http.Request) {
|
||||
st.serveIcon(w, path, ct)
|
||||
})
|
||||
@@ -187,7 +209,9 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
}
|
||||
|
||||
if staticDir != "" {
|
||||
fmt.Fprintf(os.Stderr, "marqdo web static: %s → %s\n", staticMount, staticDir)
|
||||
if logSetup {
|
||||
fmt.Fprintf(os.Stderr, "marqdo web static: %s → %s\n", staticMount, staticDir)
|
||||
}
|
||||
fs := http.StripPrefix(staticMount, http.FileServer(http.Dir(staticDir)))
|
||||
// Register without method so GET+HEAD share one pattern (avoids conflicts
|
||||
// with more-specific GET/HEAD icon paths under the same prefix).
|
||||
@@ -245,11 +269,6 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
|
||||
mux.HandleFunc("/{path...}", st.handleNotFound)
|
||||
|
||||
handler := withMiddleware(mux, mw)
|
||||
handler = withRBAC(handler, authCfg.gates, authCfg.loginPath)
|
||||
handler = withTenant(handler, st.tenant)
|
||||
handler = withStripTrailingSlash(handler)
|
||||
return handler, nil
|
||||
}
|
||||
|
||||
// Listen binds host:port from the app bag and serves until interrupt/kill.
|
||||
@@ -392,7 +411,19 @@ func (st *state) writePage(w http.ResponseWriter, r *http.Request, page map[stri
|
||||
p["_auth_next"] = next
|
||||
}
|
||||
setCookie := st.attachCSRF(p, r)
|
||||
html := render.RenderPage(p, st.dbURL, "")
|
||||
html := ""
|
||||
if nodes, ok := p["artifact_nodes"]; ok {
|
||||
document, err := artifact.RenderViewDocument(strOpt(p, "title", ""), nodes, func(resource map[string]any) (string, error) {
|
||||
return st.renderViewResource(resource, p, r)
|
||||
})
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
html = document
|
||||
} else {
|
||||
html = render.RenderPage(p, st.dbURL, "")
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
appendSetCookie(w, setCookie)
|
||||
_, _ = io.WriteString(w, html)
|
||||
@@ -401,7 +432,32 @@ func (st *state) writePage(w http.ResponseWriter, r *http.Request, page map[stri
|
||||
func (st *state) writePart(w http.ResponseWriter, r *http.Request, page map[string]any, id string) {
|
||||
p := st.preparePage(page, r)
|
||||
setCookie := st.attachCSRF(p, r)
|
||||
html := render.RenderPage(p, st.dbURL, id)
|
||||
html := ""
|
||||
if nodes, ok := p["artifact_nodes"]; ok {
|
||||
selected, found, err := artifact.FindSlot(nodes, id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
if id != "main" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
// Keep the existing main-fragment fallback for a View without a
|
||||
// named main region; never expose the Document's program source.
|
||||
selected = nodes
|
||||
}
|
||||
html, err = artifact.RenderNodesWithResources(selected, func(resource map[string]any) (string, error) {
|
||||
return st.renderViewResource(resource, p, r)
|
||||
})
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
html = render.RenderPage(p, st.dbURL, id)
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
appendSetCookie(w, setCookie)
|
||||
_, _ = io.WriteString(w, html)
|
||||
@@ -500,7 +556,11 @@ func (st *state) handleFormGet(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = io.WriteString(w, fmt.Sprintf("<p>unknown form %s</p>", id))
|
||||
return
|
||||
}
|
||||
html := form.Render(frm, id, nil, nil, "")
|
||||
page := map[string]any{}
|
||||
setCookie := st.attachCSRF(page, r)
|
||||
csrf, _ := page["_csrf"].(string)
|
||||
html := form.Render(frm, id, nil, nil, csrf)
|
||||
appendSetCookie(w, setCookie)
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, html)
|
||||
}
|
||||
@@ -522,6 +582,19 @@ func (st *state) handleFormPost(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
csrf := ""
|
||||
if st.auth.users != nil || st.auth.rbac || st.oidcEnabled() {
|
||||
sid, token, setCookie := resolveSession(r)
|
||||
appendSetCookie(w, setCookie)
|
||||
csrf = token
|
||||
_, hadCookie := session.IDFromCookie(r.Header.Get("Cookie"))
|
||||
if hadCookie || r.FormValue("_csrf") != "" {
|
||||
if !session.ValidateCSRF(sid, r.FormValue("_csrf")) {
|
||||
http.Error(w, "Invalid or missing CSRF token", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
data := map[string]any{}
|
||||
for k, vs := range r.PostForm {
|
||||
if len(vs) > 0 {
|
||||
@@ -547,13 +620,13 @@ func (st *state) handleFormPost(w http.ResponseWriter, r *http.Request) {
|
||||
// Prefer an explicit form redirect (e.g. cancel_href list URL) over the
|
||||
// composing page path stamped as _mq_return.
|
||||
redir := strOpt(res, "redirect", "/")
|
||||
if (redir == "" || redir == "/") && ctx.ReturnPath != "" {
|
||||
if (redir == "" || redir == "/") && ctx.ReturnPath != "" && strOpt(frm, "cancel_href", "") == "" {
|
||||
redir = ctx.ReturnPath
|
||||
}
|
||||
http.Redirect(w, r, redir, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
html := form.RenderBodyCtx(frm, id, data, res["errors"], "", ctx)
|
||||
html := form.RenderBodyCtx(frm, id, data, res["errors"], csrf, ctx)
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, html)
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ func parseArtifactRoute(v any) artifactRoute {
|
||||
}
|
||||
}
|
||||
|
||||
func (st *state) mountArtifactRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountArtifactRoutes(mux routeRegistrar) {
|
||||
for _, key := range sortedKeys(st.artifactRoutes) {
|
||||
cfg := parseArtifactRoute(st.artifactRoutes[key])
|
||||
if cfg.File == "" || cfg.Path == "" {
|
||||
@@ -131,7 +131,7 @@ func (st *state) handleArtifact(w http.ResponseWriter, r *http.Request, route ar
|
||||
}
|
||||
}
|
||||
|
||||
value, err := plugin.RunArtifact(route.File, payload)
|
||||
value, err := plugin.RunArtifactAtRoot(route.File, payload, st.entryDir)
|
||||
if err != nil {
|
||||
jsonErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
|
||||
@@ -63,7 +63,7 @@ func parseInvokeRoute(v any) invokeRoute {
|
||||
}
|
||||
}
|
||||
|
||||
func (st *state) mountInvokeRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountInvokeRoutes(mux routeRegistrar) {
|
||||
for _, key := range sortedKeys(st.invokeRoutes) {
|
||||
cfg := parseInvokeRoute(st.invokeRoutes[key])
|
||||
path := routePathKey(key)
|
||||
|
||||
@@ -47,7 +47,7 @@ func parseDownloadRoute(v any) downloadRoute {
|
||||
}
|
||||
}
|
||||
|
||||
func (st *state) mountUploadRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountUploadRoutes(mux routeRegistrar) {
|
||||
for _, path := range sortedKeys(st.uploadRoutes) {
|
||||
routePath := path
|
||||
cfg := parseUploadRoute(st.uploadRoutes[path])
|
||||
@@ -57,7 +57,7 @@ func (st *state) mountUploadRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
}
|
||||
|
||||
func (st *state) mountDownloadRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountDownloadRoutes(mux routeRegistrar) {
|
||||
for _, path := range sortedKeys(st.downloadRoutes) {
|
||||
routePath := path
|
||||
cfg := parseDownloadRoute(st.downloadRoutes[path])
|
||||
@@ -68,7 +68,7 @@ func (st *state) mountDownloadRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
}
|
||||
|
||||
func (st *state) mountGalleryRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountGalleryRoutes(mux routeRegistrar) {
|
||||
for _, path := range sortedKeys(st.galleryRoutes) {
|
||||
cfg, _ := st.galleryRoutes[path].(map[string]any)
|
||||
mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -90,7 +90,7 @@ func parseHeadersFromEnvStr(s string) []envHeader {
|
||||
return out
|
||||
}
|
||||
|
||||
func (st *state) mountProxyRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountProxyRoutes(mux routeRegistrar) {
|
||||
for _, key := range sortedKeys(st.proxyRoutes) {
|
||||
cfg := parseProxyRoute(st.proxyRoutes[key])
|
||||
path := routePathKey(key)
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
// System runtime control routes (M-R3 / M-R4). Cancel and event replay do not
|
||||
// enter the Marqdo interpreter lock.
|
||||
func (st *state) mountRuntimeRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountRuntimeRoutes(mux routeRegistrar) {
|
||||
mux.HandleFunc("POST /_runtime/tasks", st.handleRuntimeAdmit)
|
||||
mux.HandleFunc("GET /_runtime/tasks/{id}", st.handleRuntimeGet)
|
||||
mux.HandleFunc("POST /_runtime/tasks/{id}/cancel", st.handleRuntimeCancel)
|
||||
|
||||
@@ -28,7 +28,7 @@ func sameOrigin(r *http.Request) bool {
|
||||
return err == nil && strings.EqualFold(u.Host, r.Host)
|
||||
}
|
||||
|
||||
func (st *state) mountWSRoutes(mux *http.ServeMux) {
|
||||
func (st *state) mountWSRoutes(mux routeRegistrar) {
|
||||
for _, path := range sortedKeys(st.wsRoutes) {
|
||||
spec := ws.ParseRouteSpec(st.wsRoutes[path]) // mode + optional room_key / on_message
|
||||
routePath := path
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/artifact"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/db"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/form"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/render"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/tenant"
|
||||
)
|
||||
|
||||
// ValidateViewResource validates the closed Resource contracts without IO.
|
||||
// Assembly calls this before listening; request rendering validates again.
|
||||
func ValidateViewResource(resource map[string]any) (string, error) {
|
||||
kind, _ := resource["_type"].(string)
|
||||
switch kind {
|
||||
case "document_head":
|
||||
_, err := artifact.ParseDocumentHead(resource)
|
||||
return "", err
|
||||
case "data_query":
|
||||
if source, ok := resource["source"].(string); !ok || strings.TrimSpace(source) == "" {
|
||||
return "", fmt.Errorf("data_query: source must be a nonempty table name")
|
||||
}
|
||||
for _, key := range []string{"order", "link_prefix"} {
|
||||
if value, exists := resource[key]; exists {
|
||||
if _, ok := value.(string); !ok {
|
||||
return "", fmt.Errorf("data_query: %s must be text", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"detail", "tenant_scope"} {
|
||||
if value, exists := resource[key]; exists {
|
||||
if _, ok := value.(bool); !ok {
|
||||
return "", fmt.Errorf("data_query: %s must be boolean", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
if raw, exists := resource["limit"]; exists {
|
||||
n, ok := raw.(float64)
|
||||
if !ok || n < 1 || n > 1000 || n != float64(int64(n)) {
|
||||
return "", fmt.Errorf("data_query: limit must be an integer in 1..1000")
|
||||
}
|
||||
}
|
||||
if prefix, _ := resource["link_prefix"].(string); prefix != "" && (!strings.HasPrefix(prefix, "/") || strings.HasPrefix(prefix, "//")) {
|
||||
return "", fmt.Errorf("data_query: link_prefix must be site-relative")
|
||||
}
|
||||
if where := resource["where"]; where != nil {
|
||||
switch where.(type) {
|
||||
case map[string]any, []any:
|
||||
default:
|
||||
return "", fmt.Errorf("data_query: where must be a native condition map or list")
|
||||
}
|
||||
}
|
||||
case "form_ref":
|
||||
if id, ok := resource["id"].(string); !ok || strings.TrimSpace(id) == "" {
|
||||
return "", fmt.Errorf("form_ref: id must name an explicitly mounted form")
|
||||
}
|
||||
case "view_navigation":
|
||||
region, _ := resource["region"].(string)
|
||||
if region != "nav" && region != "sidebar" && region != "footer" {
|
||||
return "", fmt.Errorf("view_navigation: region must be nav, sidebar or footer")
|
||||
}
|
||||
switch resource["items"].(type) {
|
||||
case map[string]any, []any:
|
||||
default:
|
||||
return "", fmt.Errorf("view_navigation: items must be link records")
|
||||
}
|
||||
default:
|
||||
return "", fmt.Errorf("unsupported View Resource %q", kind)
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
var viewParameter = regexp.MustCompile(`\{([^{}]+)\}`)
|
||||
|
||||
// Copy parameterized conditions without mutating the retained startup nodes.
|
||||
func resourceWhere(value any, params map[string]any) (any, error) {
|
||||
switch value := value.(type) {
|
||||
case string:
|
||||
var missing string
|
||||
out := viewParameter.ReplaceAllStringFunc(value, func(token string) string {
|
||||
key := token[1 : len(token)-1]
|
||||
actual, ok := params[key]
|
||||
if !ok {
|
||||
missing = key
|
||||
return token
|
||||
}
|
||||
return fmt.Sprint(actual)
|
||||
})
|
||||
if missing != "" {
|
||||
return nil, fmt.Errorf("data_query: missing route parameter %q", missing)
|
||||
}
|
||||
return out, nil
|
||||
case map[string]any:
|
||||
out := make(map[string]any, len(value))
|
||||
for key, item := range value {
|
||||
resolved, err := resourceWhere(item, params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[key] = resolved
|
||||
}
|
||||
return out, nil
|
||||
case []any:
|
||||
out := make([]any, len(value))
|
||||
for i, item := range value {
|
||||
resolved, err := resourceWhere(item, params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[i] = resolved
|
||||
}
|
||||
return out, nil
|
||||
default:
|
||||
return value, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (st *state) renderViewResource(resource, page map[string]any, request *http.Request) (string, error) {
|
||||
if _, err := ValidateViewResource(resource); err != nil {
|
||||
return "", err
|
||||
}
|
||||
switch resource["_type"] {
|
||||
case "document_head":
|
||||
return "", nil
|
||||
case "data_query":
|
||||
if st.dbURL == "" {
|
||||
return "", fmt.Errorf("data_query: the application has no database resource")
|
||||
}
|
||||
params, _ := page["params"].(map[string]any)
|
||||
where, err := resourceWhere(resource["where"], params)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
scoped, _ := resource["tenant_scope"].(bool)
|
||||
if scoped && !st.tenant.Enabled() {
|
||||
return "", fmt.Errorf("data_query: scoped query requires a tenant policy")
|
||||
}
|
||||
if scoped || st.tenant.DefaultScope {
|
||||
id := tenant.FromContext(request.Context())
|
||||
if id == "" {
|
||||
return "", fmt.Errorf("data_query: tenant required")
|
||||
}
|
||||
where = tenant.MergeWhere(where, st.tenant.Column, id)
|
||||
}
|
||||
limit := int64(50)
|
||||
if n, ok := resource["limit"].(float64); ok {
|
||||
limit = int64(n)
|
||||
}
|
||||
order, _ := resource["order"].(string)
|
||||
rows, err := db.Select(st.dbURL, resource["source"].(string), limit, db.SelectOpts{Where: where, Order: order})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
detail, _ := resource["detail"].(bool)
|
||||
prefix, _ := resource["link_prefix"].(string)
|
||||
return render.RenderQueryRows(rows["rows"], detail, prefix), nil
|
||||
case "form_ref":
|
||||
id := resource["id"].(string)
|
||||
selected, ok := st.forms[id].(map[string]any)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("form_ref: form %q was not explicitly mounted", id)
|
||||
}
|
||||
csrf, _ := page["_csrf"].(string)
|
||||
return form.RenderBodyCtx(selected, id, nil, nil, csrf, st.requestContext(request, nil)), nil
|
||||
case "view_navigation":
|
||||
region := resource["region"].(string)
|
||||
navigation := map[string]any{region: resource["items"]}
|
||||
if region == "nav" {
|
||||
navigation["nav"] = resource["items"]
|
||||
}
|
||||
if logged, ok := page["_logged_in"]; ok {
|
||||
navigation["_logged_in"] = logged
|
||||
}
|
||||
if user, ok := page["_nav_user"]; ok {
|
||||
navigation["_nav_user"] = user
|
||||
}
|
||||
return render.RenderPage(navigation, "", region), nil
|
||||
}
|
||||
return "", fmt.Errorf("unsupported View Resource")
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/app"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/artifact"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/db"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/form"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/session"
|
||||
)
|
||||
|
||||
func resourceNode(resource map[string]any) map[string]any {
|
||||
return map[string]any{"type": "resource", "value": resource, "slot": "content"}
|
||||
}
|
||||
|
||||
func TestViewResourcesObserveRequestsFormsAndNavigation(t *testing.T) {
|
||||
uri := "sqlite:" + filepath.Join(t.TempDir(), "view.db")
|
||||
fields := []any{
|
||||
map[string]any{"name": "id", "type": "integer", "nullable": false},
|
||||
map[string]any{"name": "title", "type": "text", "nullable": false},
|
||||
map[string]any{"name": "slug", "type": "text", "nullable": true},
|
||||
map[string]any{"name": "summary", "type": "text", "nullable": true},
|
||||
map[string]any{"name": "body", "type": "text", "nullable": true},
|
||||
}
|
||||
if _, err := db.Init(uri, "articles", fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Insert(uri, "articles", map[string]any{
|
||||
"title": "Original <title>", "slug": "first", "summary": "Short summary", "body": "Full article body",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
query := map[string]any{"_type": "data_query", "source": "articles", "limit": float64(50), "link_prefix": "/post/"}
|
||||
navigation := map[string]any{"_type": "view_navigation", "region": "nav", "items": []any{
|
||||
map[string]any{"label": "Guest login", "href": "/admin/login", "when": "guest"},
|
||||
map[string]any{"label": "Private desk", "href": "/admin", "when": "auth"},
|
||||
}}
|
||||
page := map[string]any{"title": "View resources", "artifact_nodes": []any{
|
||||
resourceNode(navigation), resourceNode(query),
|
||||
resourceNode(map[string]any{"_type": "form_ref", "id": "article"}),
|
||||
}}
|
||||
bag := app.New(map[string]any{"page": page, "db": map[string]any{"url": uri}})
|
||||
var err error
|
||||
bag, err = app.Auth(bag, []any{map[string]any{"username": "admin", "password": "secret", "role": "admin"}}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
selected := form.SetFields(form.New("articles", "insert", ""), fields[1:2])
|
||||
selected = form.SetRules(selected, []any{map[string]any{"field": "title", "rule": "required", "message": "Title required"}})
|
||||
selected = form.SetLabels(selected, "Publish", "Cancel", "/")
|
||||
bag, err = app.MountForm(bag, "article", selected)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detailed := map[string]any{"_type": "data_query", "source": "articles", "detail": true,
|
||||
"where": map[string]any{"slug": "{slug}"}}
|
||||
bag, err = app.Route(bag, "/post/{slug}", map[string]any{"title": "Article", "artifact_nodes": []any{resourceNode(detailed)}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler, err := NewHandler(bag, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
call := func(method, path, body, cookie string) *httptest.ResponseRecorder {
|
||||
request := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
if cookie != "" {
|
||||
request.Header.Set("Cookie", cookie)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
return recorder
|
||||
}
|
||||
initial := call("GET", "/", "", "")
|
||||
if initial.Code != http.StatusOK {
|
||||
t.Fatalf("initial: %d %s", initial.Code, initial.Body.String())
|
||||
}
|
||||
text := initial.Body.String()
|
||||
if !strings.Contains(text, "Guest login") || strings.Contains(text, "Private desk") ||
|
||||
!strings.Contains(text, "Short summary") || strings.Contains(text, "Full article body") ||
|
||||
!strings.Contains(text, "Original <title>") {
|
||||
t.Fatal(text)
|
||||
}
|
||||
cookies := initial.Result().Cookies()
|
||||
if len(cookies) == 0 {
|
||||
t.Fatal("rendered form has no actual session cookie")
|
||||
}
|
||||
cookie := cookies[0].Name + "=" + cookies[0].Value
|
||||
match := regexp.MustCompile(`name="_csrf" value="([^"]+)"`).FindStringSubmatch(text)
|
||||
if len(match) != 2 {
|
||||
t.Fatal("resource form omitted its CSRF token")
|
||||
}
|
||||
token := match[1]
|
||||
bad := call("POST", "/_form/article", "title=Rejected&_csrf=wrong", cookie)
|
||||
if bad.Code != http.StatusForbidden {
|
||||
t.Fatalf("bad csrf accepted: %d %s", bad.Code, bad.Body.String())
|
||||
}
|
||||
invalid := call("POST", "/_form/article", url.Values{"_csrf": {token}, "title": {""}}.Encode(), cookie)
|
||||
if invalid.Code != http.StatusOK || !strings.Contains(invalid.Body.String(), "Title required") ||
|
||||
!strings.Contains(invalid.Body.String(), `name="_csrf" value="`+token+`"`) {
|
||||
t.Fatalf("validation retry: %d %s", invalid.Code, invalid.Body.String())
|
||||
}
|
||||
valid := call("POST", "/_form/article", url.Values{"_csrf": {token}, "title": {"Inserted after startup"}, "_mq_return": {"/new"}}.Encode(), cookie)
|
||||
if valid.Code != http.StatusSeeOther || valid.Header().Get("Location") != "/" {
|
||||
t.Fatalf("submit: %d %s", valid.Code, valid.Body.String())
|
||||
}
|
||||
current := call("GET", "/", "", cookie)
|
||||
if !strings.Contains(current.Body.String(), "Inserted after startup") {
|
||||
t.Fatal("query cached startup rows")
|
||||
}
|
||||
fragment := call("GET", "/_part/main", "", cookie)
|
||||
if fragment.Code != http.StatusOK || !strings.Contains(fragment.Body.String(), "Inserted after startup") ||
|
||||
!strings.Contains(fragment.Body.String(), `name="_csrf" value="`+token+`"`) ||
|
||||
strings.Contains(fragment.Body.String(), "<!DOCTYPE") {
|
||||
t.Fatalf("request fragment lost context: %d %s", fragment.Code, fragment.Body.String())
|
||||
}
|
||||
unknown := call("GET", "/_part/not-declared", "", cookie)
|
||||
if unknown.Code != http.StatusNotFound {
|
||||
t.Fatalf("unknown View slot: %d", unknown.Code)
|
||||
}
|
||||
|
||||
detail := call("GET", "/post/first?slug=other", "", cookie)
|
||||
if detail.Code != http.StatusOK || !strings.Contains(detail.Body.String(), "Full article body") ||
|
||||
strings.Contains(detail.Body.String(), "Short summary") {
|
||||
t.Fatal(detail.Body.String())
|
||||
}
|
||||
if detailed["where"].(map[string]any)["slug"] != "{slug}" {
|
||||
t.Fatal("request mutated retained Resource")
|
||||
}
|
||||
sid, ok := session.IDFromCookie(cookie)
|
||||
if !ok || !session.SetValue(sid, "username", "admin") {
|
||||
t.Fatal("could not establish fixture session")
|
||||
}
|
||||
logged := call("GET", "/", "", cookie)
|
||||
if strings.Contains(logged.Body.String(), "Guest login") || !strings.Contains(logged.Body.String(), "Private desk") {
|
||||
t.Fatal(logged.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestViewResourceValidationDoesNotQueryAndFailuresRemainVisible(t *testing.T) {
|
||||
query := map[string]any{"_type": "data_query", "source": "missing"}
|
||||
if _, err := artifact.RenderNodesWithResources([]any{resourceNode(query)}, ValidateViewResource); err != nil {
|
||||
t.Fatalf("startup unexpectedly queried missing DB: %v", err)
|
||||
}
|
||||
for _, resource := range []map[string]any{
|
||||
{"_type": "invented"}, {"_type": "data_query", "source": "items", "limit": 1.5},
|
||||
{"_type": "data_query", "source": "items", "link_prefix": "javascript:"},
|
||||
{"_type": "form_ref", "id": ""},
|
||||
} {
|
||||
if _, err := ValidateViewResource(resource); err == nil {
|
||||
t.Fatalf("bad resource accepted: %#v", resource)
|
||||
}
|
||||
}
|
||||
if _, err := artifact.RenderNodes([]any{resourceNode(query)}); err == nil {
|
||||
t.Fatal("offline render invented request context")
|
||||
}
|
||||
bag := app.New(map[string]any{"page": map[string]any{"artifact_nodes": []any{resourceNode(query)}}})
|
||||
handler, err := NewHandler(bag, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, httptest.NewRequest("GET", "/", nil))
|
||||
if response.Code != http.StatusInternalServerError || !strings.Contains(response.Body.String(), "no database") {
|
||||
t.Fatalf("missing backend became successful empty content: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestViewHeadResourcesServeInHeadAndNeverLeakIntoFragments(t *testing.T) {
|
||||
nodes := []any{
|
||||
map[string]any{"type": "resource", "value": map[string]any{"_type": "document_head", "meta": map[string]any{"key": "description", "value": "Actual SEO"}, "links": []any{map[string]any{"rel": "stylesheet", "href": "/theme.css"}}}},
|
||||
map[string]any{"type": "markdown", "slot": "content", "value": "# Real content"},
|
||||
}
|
||||
bag := app.New(map[string]any{"page": map[string]any{"title": "Head test", "artifact_nodes": nodes}})
|
||||
handler, err := NewHandler(bag, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, path := range []string{"/", "/_part/main", "/_part/content"} {
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, httptest.NewRequest("GET", path, nil))
|
||||
body := response.Body.String()
|
||||
if response.Code != http.StatusOK || !strings.Contains(body, "Real content") {
|
||||
t.Fatalf("%s %d %s", path, response.Code, body)
|
||||
}
|
||||
if path == "/" {
|
||||
head, rest, _ := strings.Cut(body, "</head>")
|
||||
if !strings.Contains(head, `<meta name="description" content="Actual SEO"`) || !strings.Contains(head, `href="/theme.css"`) || strings.Contains(rest, "Actual SEO") {
|
||||
t.Fatal(body)
|
||||
}
|
||||
} else if strings.Contains(body, "Actual SEO") || strings.Contains(body, "<head") || strings.Contains(body, "theme.css") {
|
||||
t.Fatal(body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,15 @@ func CallLibPath(path string, args map[string]any) (any, error) {
|
||||
// RunArtifact loads and runs a Document/Endpoint `.mq.md` (ADR 0007).
|
||||
// Request fields are passed as Metadata Binding overlays (`arg` / `--bind`).
|
||||
func RunArtifact(path string, args map[string]any) (any, error) {
|
||||
return RunArtifactAtRoot(path, args, "")
|
||||
}
|
||||
|
||||
// RunArtifactAtRoot retains a selected site directory within the host's grant.
|
||||
func RunArtifactAtRoot(path string, args map[string]any, root string) (any, error) {
|
||||
payload := map[string]any{"path": path}
|
||||
if root != "" {
|
||||
payload["root"] = root
|
||||
}
|
||||
if len(args) > 0 {
|
||||
payload["args"] = args
|
||||
}
|
||||
|
||||
+2
-2
@@ -11,8 +11,8 @@ import (
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/table"
|
||||
)
|
||||
|
||||
func TestAnlianPostsResolve(t *testing.T) {
|
||||
url := "sqlite:" + filepath.Join(t.TempDir(), "anlian.db")
|
||||
func TestDocumentPostsResolve(t *testing.T) {
|
||||
url := "sqlite:" + filepath.Join(t.TempDir(), "posts.db")
|
||||
fields := []any{
|
||||
map[string]any{"name": "title", "type": "text", "nullable": false},
|
||||
map[string]any{"name": "summary", "type": "text"},
|
||||
@@ -3,6 +3,7 @@ package render
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/assets"
|
||||
@@ -846,6 +847,15 @@ func resolveLayout(page map[string]any) string {
|
||||
return normalizeLayout(raw)
|
||||
}
|
||||
|
||||
// DocumentHead reuses ordinary Document metadata, links and native head boot
|
||||
// helpers without adding application configuration or a second HTML dialect.
|
||||
func DocumentHead(title string, meta map[string]any, links []assets.HeadLink) string {
|
||||
if title == "" {
|
||||
title = "Marqdo"
|
||||
}
|
||||
return headHTML(map[string]any{"meta": meta, "head": assets.HeadLinksToJSON(links)}, title)
|
||||
}
|
||||
|
||||
func headHTML(page map[string]any, defaultTitle string) string {
|
||||
pageTitle := defaultTitle
|
||||
if meta, ok := page["meta"].(map[string]any); ok {
|
||||
@@ -859,7 +869,13 @@ func headHTML(page map[string]any, defaultTitle string) string {
|
||||
s.WriteString(fmt.Sprintf(`<meta name="csrf-token" content="%s"/>`, esc(strings.TrimSpace(csrf))))
|
||||
}
|
||||
if meta, ok := page["meta"].(map[string]any); ok {
|
||||
for k, v := range meta {
|
||||
keys := make([]string, 0, len(meta))
|
||||
for key := range meta {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
v := meta[k]
|
||||
if k == "title" {
|
||||
continue
|
||||
}
|
||||
@@ -1361,6 +1377,39 @@ func renderFragment(page map[string]any, dbURL, slot string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// RenderQueryRows projects native database records into existing card/article
|
||||
// rendering. Query failures remain with the Resource caller, never empty success.
|
||||
func RenderQueryRows(rows any, detail bool, prefix string) string {
|
||||
raw, _ := rows.([]any)
|
||||
var body strings.Builder
|
||||
if !detail {
|
||||
body.WriteString(`<section class="content cards">`)
|
||||
}
|
||||
for _, row := range raw {
|
||||
item := projectArtifactRow(row)
|
||||
if item == nil {
|
||||
continue
|
||||
}
|
||||
if detail {
|
||||
if object, ok := row.(map[string]any); ok {
|
||||
if full, exists := object["body"]; exists {
|
||||
item["body"] = text(full)
|
||||
}
|
||||
if full, exists := object["content"]; exists {
|
||||
item["body"] = text(full)
|
||||
}
|
||||
}
|
||||
body.WriteString(renderArticle(item))
|
||||
break
|
||||
}
|
||||
body.WriteString(renderCard(map[string]any{"link_prefix": prefix}, item))
|
||||
}
|
||||
if !detail {
|
||||
body.WriteString("</section>")
|
||||
}
|
||||
return body.String()
|
||||
}
|
||||
|
||||
// RenderPage builds full-page HTML (or a part fragment when partID is set).
|
||||
func RenderPage(page map[string]any, dbURL string, partID string) string {
|
||||
// Explicit View Documents already own their structure and document shell.
|
||||
|
||||
@@ -163,6 +163,7 @@ extern int web_render_nodes(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_render_document(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_dom_markdown(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_serve_root(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_prepare_root(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_inspect(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_app_use(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_route_use(char *args_json, char **out_json, char **err_msg);
|
||||
@@ -272,6 +273,7 @@ static int register_core(void) {
|
||||
if (host_register((char *)"web_render_document", (char *)"page,body,db,title", web_render_document) != 0) return 1;
|
||||
if (host_register((char *)"web_dom_markdown", (char *)"text", web_dom_markdown) != 0) return 1;
|
||||
if (host_register((char *)"web_serve_root", (char *)"root,host,port,db,static_dir,middleware", web_serve_root) != 0) return 1;
|
||||
if (host_register((char *)"web_prepare_root", (char *)"root,host,port,db,static_dir,middleware", web_prepare_root) != 0) return 1;
|
||||
if (host_register((char *)"web_inspect", (char *)"app,root", web_inspect) != 0) return 1;
|
||||
if (host_register((char *)"web_app_use", (char *)"app,middleware", web_app_use) != 0) return 1;
|
||||
if (host_register((char *)"web_route_use", (char *)"route,middleware", web_route_use) != 0) return 1;
|
||||
|
||||
Reference in new issue
Block a user