use std::path::Path;
const MARKDOWN_EXTENSIONS: &[&str] = &["md", "markdown"];
const BINARY_MAGICS: &[(&[u8], &str)] = &[
(b"PK\x03\x04", "ZIP"),
(b"\x1f\x8b", "gzip"),
(b"MZ\x90", "PE/EXE"),
(b"\x7fELF", "ELF"),
(b"\x89PNG", "PNG"),
(b"BM", "BMP"),
];
pub(crate) fn detect_binary_disguise_kind(path: &Path, bytes: &[u8]) -> Option<&'static str> {
if !is_markdown_extension(path) {
return None;
}
BINARY_MAGICS
.iter()
.find(|(magic, _)| bytes.starts_with(magic))
.map(|(_, kind)| *kind)
}
fn is_markdown_extension(path: &Path) -> bool {
path.extension()
.and_then(|s| s.to_str())
.is_some_and(|ext| {
MARKDOWN_EXTENSIONS
.iter()
.any(|known| ext.eq_ignore_ascii_case(known))
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn detect_binary_disguise_kind_flags_zip_named_md() {
let bytes = b"PK\x03\x04rest of zip body";
let kind = detect_binary_disguise_kind(&PathBuf::from("Skill.MD"), bytes);
assert_eq!(kind, Some("ZIP"));
}
#[test]
fn detect_binary_disguise_kind_ignores_honest_zip_extension() {
let bytes = b"PK\x03\x04rest of zip body";
let kind = detect_binary_disguise_kind(&PathBuf::from("payload.zip"), bytes);
assert_eq!(kind, None);
}
#[test]
fn detect_binary_disguise_kind_returns_none_for_real_markdown() {
let bytes = b"# Hello\n\nThis is a real skill.\n";
assert_eq!(
detect_binary_disguise_kind(&PathBuf::from("SKILL.md"), bytes),
None
);
}
#[test]
fn detect_binary_disguise_kind_covers_all_magics() {
let cases = [
(&b"\x1f\x8b\x08\x00"[..], "gzip"),
(&b"MZ\x90\x00"[..], "PE/EXE"),
(&b"\x7fELF\x02"[..], "ELF"),
(&b"\x89PNG\r\n\x1a\n"[..], "PNG"),
(&b"BMabc"[..], "BMP"),
];
for (bytes, expected_kind) in cases {
let kind = detect_binary_disguise_kind(&PathBuf::from("doc.md"), bytes);
assert_eq!(kind, Some(expected_kind), "magic {expected_kind} regressed");
}
}
#[test]
fn detect_binary_disguise_kind_recognizes_markdown_extension_variants() {
let bytes = b"PK\x03\x04";
for path in ["doc.md", "doc.MD", "doc.Md", "doc.markdown", "doc.MARKDOWN"] {
assert_eq!(
detect_binary_disguise_kind(&PathBuf::from(path), bytes),
Some("ZIP"),
"{path} should be recognized as markdown"
);
}
}
}