///|
/// Relative paths only; native adapters additionally validate canonical targets.
/// Backslashes are treated as separators on every OS to avoid portable-config surprises.
pub fn safe_relative(path : String) -> Bool {
if path.is_empty() ||
path.length() > 4096 ||
path.has_prefix("/") ||
path.has_prefix("\\") ||
path.contains(":") ||
path.iter().any(c => c.is_control()) {
return false
}
let parts = path.replace_all(old="\\", new="/").split("/").collect()
parts
.iter()
.all(p => {
!p.is_empty() && p != ".." && !p.has_suffix(".") && !p.has_suffix(" ")
})
}
///|
/// A lightweight scan bounds nesting before invoking the JSON parser.
pub fn validate_input(
text : String,
max_bytes~ : Int32 = 65536,
max_depth~ : Int32 = 32,
) -> Unit raise DoctorError {
if max_bytes < 1 || max_bytes > 1048576 || max_depth < 1 || max_depth > 64 {
raise DoctorError("invalid input limits")
}
if text.length() > max_bytes || @utf8.encode(text).length() > max_bytes {
raise DoctorError("input too large")
}
let mut depth = 0
let mut quoted = false
let mut escaped = false
for c in text {
if quoted {
if escaped {
escaped = false
} else if c == '\\' {
escaped = true
} else if c == '"' {
quoted = false
}
} else if c == '"' {
quoted = true
} else if c == '{' || c == '[' {
depth += 1
if depth > max_depth {
raise DoctorError("input nesting too deep")
}
} else if c == '}' || c == ']' {
depth -= 1
}
}
}
///|
pub fn sensitive_key(key : String) -> Bool {
let key = key.to_lower()
[
"token", "password", "secret", "credential", "authorization", "cookie", "private_key",
"api_key",
]
.iter()
.any(k => key.contains(k))
}
///|
/// Bound and sanitize display strings, including terminal controls.
pub fn display_text(text : String, limit~ : Int32 = 1024) -> String {
let safe_limit = if limit < 0 { 0 } else { limit }
let out = StringBuilder()
let mut count = 0
for c in text {
if count >= safe_limit {
out.write_string("…")
break
}
if c.is_control() {
out.write_char(' ')
} else {
out.write_char(c)
}
count += 1
}
out.to_string()
}