use sha2::{Digest, Sha256};
pub const COMPONENT: &[u8] = include_bytes!("../core/aethel_core.component.wasm");
const DECLARED: &str = include_str!("../core/component.sha256");
const PIN: &str = include_str!("../core/pin.toml");
pub fn declared_sha256() -> &'static str {
DECLARED
.split_whitespace()
.next()
.expect("core/component.sha256 is empty; run scripts/sync-core.sh")
}
pub fn core_revision() -> &'static str {
pin_value("rev").expect("core/pin.toml has no rev; run scripts/sync-core.sh")
}
pub fn canonical_platform() -> &'static str {
pin_value("platform").unwrap_or("unknown")
}
fn pin_value(key: &str) -> Option<&'static str> {
PIN.lines()
.map(str::trim)
.filter(|line| !line.starts_with('#'))
.find_map(|line| {
let (name, rest) = line.split_once('=')?;
if name.trim() != key {
return None;
}
rest.trim().strip_prefix('"')?.split('"').next()
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IntegrityError {
pub declared: String,
pub actual: String,
}
impl core::fmt::Display for IntegrityError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"aethel-core component hash mismatch: declared {}, got {}. \
The embedded artifact is not the one this package claims to ship.",
self.declared, self.actual
)
}
}
impl std::error::Error for IntegrityError {}
pub fn sha256_hex(bytes: &[u8]) -> String {
let digest = Sha256::digest(bytes);
let mut hex = String::with_capacity(64);
for byte in digest {
use core::fmt::Write;
let _ = write!(hex, "{byte:02x}");
}
hex
}
pub fn verify(bytes: &[u8]) -> Result<(), IntegrityError> {
let declared = declared_sha256();
let actual = sha256_hex(bytes);
if actual == declared {
Ok(())
} else {
Err(IntegrityError {
declared: declared.to_string(),
actual,
})
}
}
pub fn verify_embedded() -> Result<(), IntegrityError> {
verify(COMPONENT)
}