use base64::prelude::*;
use reqwest::Url;
use sha2::{Digest, Sha256};
use std::str::FromStr;
use syn::{LitStr, Token, parse::Parse, parse_macro_input};
struct UrlWithHash {
url: LitStr,
hash: LitStr,
}
impl Parse for UrlWithHash {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let url = input.parse()?;
let _: Token![,] = input.parse()?;
let hash = input.parse()?;
Ok(UrlWithHash { url, hash })
}
}
fn hash_bytes_b64_sha256(data: &[u8]) -> String {
BASE64_STANDARD.encode(Sha256::digest(data))
}
#[proc_macro]
pub fn embed_url(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
let UrlWithHash { url, hash } = parse_macro_input!(item as UrlWithHash);
let url_str = url.value();
let expected_hash = hash.value();
let url = Url::parse(url_str.as_str()).unwrap_or_else(|e| {
panic!("Invalid URL '{}': {}", url_str, e);
});
let response = reqwest::blocking::get(url.as_str()).unwrap_or_else(|e| {
panic!("Failed to fetch URL '{}': {}", url_str, e);
});
let status_code = response.status().as_u16();
if !(200..300).contains(&status_code) {
let error_body = response.text().unwrap_or_default();
panic!(
"Failed to fetch URL '{}': HTTP {} {}",
url_str,
status_code,
error_body.lines().next().unwrap_or("Unknown error")
);
}
let bytes = response.bytes().unwrap_or_else(|e| {
panic!("Failed to read response body from '{}': {}", url_str, e);
});
let computed_hash = hash_bytes_b64_sha256(&bytes);
if computed_hash != expected_hash {
panic!(
"Hash verification failed for URL '{}'.\n\
Expected: {}\n\
Computed: {}",
url_str, expected_hash, computed_hash
);
}
let byte_literals: Vec<String> = bytes.iter().map(|b| format!("0x{:02x}", b)).collect();
let array_content = byte_literals.join(",");
let output = format!(
"{{ let data = [{}]; let bytes: Box<[u8]> = data.into(); bytes }}",
array_content
);
proc_macro::TokenStream::from_str(&output).unwrap()
}