selfhost: add ternary parser and plugin prefix guard

This commit is contained in:
Selfhosting Dev
2025-09-16 17:38:22 +09:00
parent fce0d2cdef
commit fa1619bf4b
9 changed files with 221 additions and 45 deletions

View File

@ -15,6 +15,7 @@ pub struct BoxIndex {
pub aliases: HashMap<String, String>,
pub plugin_boxes: HashSet<String>,
pub plugin_meta: HashMap<String, PluginMeta>,
pub plugin_meta_by_box: HashMap<String, PluginMeta>,
pub plugins_require_prefix_global: bool,
}
@ -43,6 +44,7 @@ impl BoxIndex {
// plugin box types (best-effort; may be empty if host not initialized yet)
let mut plugin_boxes: HashSet<String> = HashSet::new();
let mut plugin_meta: HashMap<String, PluginMeta> = HashMap::new();
let mut plugin_meta_by_box: HashMap<String, PluginMeta> = HashMap::new();
let mut plugins_require_prefix_global = false;
// Read per-plugin meta and global flags from nyash.toml when available
@ -59,7 +61,13 @@ impl BoxIndex {
let prefix = t.get("prefix").and_then(|x| x.as_str()).map(|s| s.to_string());
let require_prefix = t.get("require_prefix").and_then(|x| x.as_bool()).unwrap_or(false);
let expose_short_names = t.get("expose_short_names").and_then(|x| x.as_bool()).unwrap_or(true);
plugin_meta.insert(k.clone(), PluginMeta { prefix, require_prefix, expose_short_names });
let meta = PluginMeta { prefix, require_prefix, expose_short_names };
plugin_meta.insert(k.clone(), meta.clone());
if let Some(arr) = t.get("boxes").and_then(|x| x.as_array()) {
for b in arr {
if let Some(name) = b.as_str() { plugin_meta_by_box.insert(name.to_string(), meta.clone()); }
}
}
}
}
}
@ -68,13 +76,18 @@ impl BoxIndex {
let host = crate::runtime::get_global_plugin_host();
if let Ok(h) = host.read() {
if let Some(cfg) = h.config_ref() {
for (_lib, def) in &cfg.libraries {
for bt in &def.boxes { plugin_boxes.insert(bt.clone()); }
for (lib, def) in &cfg.libraries {
for bt in &def.boxes {
plugin_boxes.insert(bt.clone());
if let Some(meta) = plugin_meta.get(lib) {
plugin_meta_by_box.insert(bt.clone(), meta.clone());
}
}
}
}
}
Self { aliases, plugin_boxes, plugin_meta, plugins_require_prefix_global }
Self { aliases, plugin_boxes, plugin_meta, plugin_meta_by_box, plugins_require_prefix_global }
}
pub fn is_known_plugin_short(name: &str) -> bool {

View File

@ -8,7 +8,6 @@
*/
use super::*;
use super::box_index::BoxIndex;
use std::collections::HashMap;
/// Using/module resolution context accumulated from config/env/nyash.toml
@ -135,39 +134,24 @@ pub(super) fn resolve_using_target(
) -> Result<String, String> {
if is_path { return Ok(tgt.to_string()); }
let trace = verbose || std::env::var("NYASH_RESOLVE_TRACE").ok().as_deref() == Some("1");
// Strict plugin prefix: if enabled and target matches a known plugin box type
// and is not qualified (contains '.'), require a qualified/prefixed name.
// Strict mode: env or nyash.toml [plugins] require_prefix=true
let mut strict_effective = strict;
if !strict_effective {
if let Ok(text) = std::fs::read_to_string("nyash.toml") {
if let Ok(doc) = toml::from_str::<toml::Value>(&text) {
if let Some(tbl) = doc.get("plugins").and_then(|v| v.as_table()) {
if let Some(v) = tbl.get("require_prefix").and_then(|v| v.as_bool()) { if v { strict_effective = true; } }
}
}
}
}
let idx = super::box_index::get_box_index();
let mut strict_effective = strict || idx.plugins_require_prefix_global;
if std::env::var("NYASH_PLUGIN_REQUIRE_PREFIX").ok().as_deref() == Some("1") { strict_effective = true; }
if strict_effective {
let mut is_plugin_short = super::box_index::BoxIndex::is_known_plugin_short(tgt);
if !is_plugin_short {
// Fallback: heuristic list or env override
if let Ok(raw) = std::env::var("NYASH_KNOWN_PLUGIN_SHORTNAMES") {
let set: std::collections::HashSet<String> = raw.split(',').map(|s| s.trim().to_string()).collect();
is_plugin_short = set.contains(tgt);
} else {
// Minimal builtins set
const KNOWN: &[&str] = &[
"ArrayBox","MapBox","StringBox","ConsoleBox","FileBox","PathBox","MathBox","IntegerBox","TOMLBox"
];
is_plugin_short = KNOWN.iter().any(|k| *k == tgt);
let meta_for_target = idx.plugin_meta_by_box.get(tgt).cloned();
let mut require_prefix_target = meta_for_target.as_ref().map(|m| m.require_prefix).unwrap_or(false);
if let Some(m) = &meta_for_target { if !m.expose_short_names { require_prefix_target = true; } }
let mut is_plugin_short = meta_for_target.is_some();
if !is_plugin_short {
is_plugin_short = idx.plugin_boxes.contains(tgt) || super::box_index::BoxIndex::is_known_plugin_short(tgt);
}
if (strict_effective || require_prefix_target) && is_plugin_short && !tgt.contains('.') {
let mut msg = format!("plugin short name '{}' requires prefix", tgt);
if let Some(meta) = &meta_for_target {
if let Some(pref) = &meta.prefix {
msg.push_str(&format!(" (use '{}.{}')", pref, tgt));
}
}
if is_plugin_short && !tgt.contains('.') {
return Err(format!("plugin short name '{}' requires prefix (strict)", tgt));
}
return Err(msg);
}
let key = {
let base = context_dir.and_then(|p| p.to_str()).unwrap_or("");
@ -332,3 +316,48 @@ pub(super) fn lint_fields_top(code: &str, strict: bool, verbose: bool) -> Result
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn plugin_meta_requires_prefix_even_when_relaxed() {
let dir = tempdir().expect("tempdir");
let old = std::env::current_dir().expect("cwd");
std::env::set_current_dir(dir.path()).expect("chdir");
let toml = r#"
[plugins]
require_prefix = false
[plugins."test-plugin"]
prefix = "test"
require_prefix = true
expose_short_names = false
boxes = ["ArrayBox"]
"#;
std::fs::write("nyash.toml", toml).expect("write nyash.toml");
crate::runner::box_index::refresh_box_index();
crate::runner::box_index::cache_clear();
let res = resolve_using_target(
"ArrayBox",
false,
&[],
&[],
&HashMap::new(),
None,
false,
false,
);
assert!(res.is_err(), "expected prefix enforcement");
let err = res.err().unwrap();
assert!(err.contains("requires prefix"));
assert!(err.contains("test."));
std::env::set_current_dir(old).expect("restore cwd");
crate::runner::box_index::refresh_box_index();
crate::runner::box_index::cache_clear();
}
}