1use anyhow::{Result, ensure};
4use serde::{Deserialize, Serialize};
5use std::path::Path;
6
7pub(crate) const RUNTIME_FRAME: &str = "previews/0-pag-player.html";
8pub(crate) const RUNTIME_WASM: &str = "previews/0-libpag-4.3.51.wasm";
9pub(crate) const RUNTIME_LICENSE: &str = "previews/0-libpag-license.txt";
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct PagInfo {
13 pub container_version: u8,
14 pub runtime_version: String,
15}
16
17pub(crate) fn inspect(bytes: &[u8]) -> Result<PagInfo> {
18 ensure!(
19 bytes.len() >= 11 && bytes.starts_with(b"PAG"),
20 "pag_invalid_header"
21 );
22 ensure!(bytes.len() <= 16 * 1024 * 1024, "pag_preview_input_limit");
23 ensure!(
24 bytes[3] == 1 && bytes[8] == b'U',
25 "pag_unsupported_version_or_compression"
26 );
27 let body = u32::from_le_bytes(bytes[4..8].try_into()?) as usize;
29 ensure!(body == bytes.len() - 9, "pag_body_length_mismatch");
30 Ok(PagInfo {
31 container_version: bytes[3],
32 runtime_version: "4.3.51".into(),
33 })
34}
35
36pub(crate) fn write_runtime(out: &Path) -> Result<()> {
37 let frame = include_str!("ui/pag-frame.html")
38 .replace("/*__LIBPAG__*/", include_str!("ui/vendor/libpag/libpag.js"));
39 crate::filesystem::write_new(&out.join(RUNTIME_FRAME), frame.as_bytes())?;
40 for (name, bytes) in [
41 (
42 RUNTIME_WASM,
43 include_bytes!("ui/vendor/libpag/libpag.wasm").as_slice(),
44 ),
45 (
46 RUNTIME_LICENSE,
47 include_bytes!("ui/vendor/libpag/LICENSE.txt").as_slice(),
48 ),
49 ] {
50 crate::filesystem::write_new(&out.join(name), bytes)?;
51 }
52 Ok(())
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58 #[test]
59 fn validates_body_length_version_and_compression_before_browser_decoding() {
60 let mut bytes = b"PAG\x01\x02\x00\x00\x00U\x00\x00".to_vec();
61 assert_eq!(inspect(&bytes).unwrap().container_version, 1);
62 bytes[4] = 3;
63 assert!(inspect(&bytes).is_err());
64 bytes[4] = 2;
65 bytes[3] = 2;
66 assert!(inspect(&bytes).is_err());
67 bytes[3] = 1;
68 bytes[8] = b'Z';
69 assert!(inspect(&bytes).is_err());
70 assert!(inspect(b"PAG").is_err());
71 }
72}