Skip to main content

rigspark_cli/
distribution.rs

1use serde::{Deserialize, Serialize};
2use sha2::{Digest, Sha256};
3use std::{
4    collections::BTreeSet,
5    fs,
6    io::{self, Read},
7    path::{Path, PathBuf},
8};
9
10const MAX_FILE: u64 = 256 * 1024 * 1024;
11const TARGETS: &[&str] = &[
12    "aarch64-apple-darwin",
13    "x86_64-apple-darwin",
14    "x86_64-unknown-linux-gnu",
15    "aarch64-unknown-linux-gnu",
16    "x86_64-pc-windows-msvc",
17];
18const FILES: &[&str] = &[
19    "llmup",
20    "llmup.exe",
21    "rigspark",
22    "rigspark.exe",
23    "rigspark-gui",
24    "rigspark-gui.exe",
25    "LICENSE",
26    "marked.LICENSE.md",
27    "dompurify.LICENSE",
28    "katex.LICENSE",
29    "crossterm.LICENSE",
30    "fonts.OFL.txt",
31    "CROSSTERM-PATCH.md",
32    "THIRD-PARTY.md",
33];
34
35#[derive(Debug, Serialize, Deserialize)]
36#[serde(deny_unknown_fields)]
37pub struct Artifact {
38    pub name: String,
39    pub bytes: u64,
40    pub sha256: String,
41}
42#[derive(Debug, Serialize, Deserialize)]
43#[serde(rename_all = "camelCase", deny_unknown_fields)]
44pub struct Manifest {
45    pub schema_version: u8,
46    pub version: String,
47    pub target: String,
48    pub signing: String,
49    pub files: Vec<Artifact>,
50}
51fn invalid(message: &str) -> io::Error {
52    io::Error::new(io::ErrorKind::InvalidData, message)
53}
54pub fn archive_path(directory: &Path) -> io::Result<PathBuf> {
55    let mut name = directory
56        .file_name()
57        .ok_or_else(|| invalid("missing archive directory name"))?
58        .to_os_string();
59    name.push(".tar.gz");
60    Ok(directory.with_file_name(name))
61}
62fn validate(version: &str, target: &str, names: &[&str]) -> io::Result<()> {
63    let parts: Vec<_> = version.split('.').collect();
64    if parts.len() != 3
65        || parts.iter().any(|part| {
66            part.is_empty() || part.len() > 8 || !part.bytes().all(|byte| byte.is_ascii_digit())
67        })
68        || !TARGETS.contains(&target)
69    {
70        return Err(invalid("invalid native package version or target"));
71    }
72    let mut seen = BTreeSet::new();
73    if names.is_empty()
74        || names.len() > FILES.len()
75        || names
76            .iter()
77            .any(|name| !FILES.contains(name) || !seen.insert(*name))
78    {
79        return Err(invalid("invalid or duplicate native artifact name"));
80    }
81    let (required, foreign) = if target.contains("windows") {
82        (
83            ["llmup.exe", "rigspark.exe", "rigspark-gui.exe"],
84            ["llmup", "rigspark", "rigspark-gui"],
85        )
86    } else {
87        (
88            ["llmup", "rigspark", "rigspark-gui"],
89            ["llmup.exe", "rigspark.exe", "rigspark-gui.exe"],
90        )
91    };
92    if required.iter().any(|name| !seen.contains(name))
93        || foreign.iter().any(|name| seen.contains(name))
94    {
95        return Err(invalid(
96            "native package requires both public aliases and the GUI companion with target-correct names",
97        ));
98    }
99    Ok(())
100}
101pub fn checksum(path: &Path) -> io::Result<(u64, String)> {
102    let metadata = fs::symlink_metadata(path)?;
103    if !metadata.is_file() || metadata.len() == 0 || metadata.len() > MAX_FILE {
104        return Err(invalid("invalid native artifact file"));
105    }
106    let mut file = fs::File::open(path)?.take(MAX_FILE + 1);
107    let mut hash = Sha256::new();
108    let mut total = 0u64;
109    let mut buffer = [0u8; 65536];
110    loop {
111        let count = file.read(&mut buffer)?;
112        if count == 0 {
113            break;
114        }
115        total += count as u64;
116        hash.update(&buffer[..count]);
117    }
118    if total != metadata.len() || total > MAX_FILE {
119        return Err(invalid("native artifact changed while reading"));
120    }
121    Ok((total, format!("{:x}", hash.finalize())))
122}
123fn verify_permissions(name: &str, path: &Path) -> io::Result<()> {
124    #[cfg(unix)]
125    {
126        use std::os::unix::fs::PermissionsExt;
127        if ["llmup", "rigspark", "rigspark-gui"].contains(&name)
128            && fs::symlink_metadata(path)?.permissions().mode() & 0o100 == 0
129        {
130            return Err(invalid("native binary must have owner execute permission"));
131        }
132    }
133    #[cfg(not(unix))]
134    let _ = (name, path);
135    Ok(())
136}
137pub fn package_directory(
138    output: &Path,
139    version: &str,
140    target: &str,
141    files: &[(&str, &Path)],
142) -> io::Result<Manifest> {
143    validate(
144        version,
145        target,
146        &files.iter().map(|(name, _)| *name).collect::<Vec<_>>(),
147    )?;
148    let mut manifest = Manifest {
149        schema_version: 1,
150        version: version.into(),
151        target: target.into(),
152        signing: "unsigned".into(),
153        files: Vec::new(),
154    };
155    for (name, source) in files {
156        let (bytes, sha256) = checksum(source)?;
157        verify_permissions(name, source)?;
158        manifest.files.push(Artifact {
159            name: (*name).into(),
160            bytes,
161            sha256,
162        });
163    }
164    fs::create_dir(output)?;
165    for (name, source) in files {
166        fs::copy(source, output.join(name))?;
167    }
168    fs::write(
169        output.join("manifest.json"),
170        serde_json::to_vec_pretty(&manifest)?,
171    )?;
172    verify_directory(output)?;
173    Ok(manifest)
174}
175pub fn verify_directory(directory: &Path) -> io::Result<Manifest> {
176    if !fs::symlink_metadata(directory)?.is_dir() {
177        return Err(invalid("native package must be a directory"));
178    }
179    let path = directory.join("manifest.json");
180    if !fs::symlink_metadata(&path)?.is_file() {
181        return Err(invalid("invalid manifest file"));
182    }
183    let mut bytes = Vec::new();
184    fs::File::open(path)?.take(65537).read_to_end(&mut bytes)?;
185    if bytes.len() > 65536 {
186        return Err(invalid("manifest exceeds limit"));
187    }
188    let manifest: Manifest = serde_json::from_slice(&bytes)?;
189    validate(
190        &manifest.version,
191        &manifest.target,
192        &manifest
193            .files
194            .iter()
195            .map(|file| file.name.as_str())
196            .collect::<Vec<_>>(),
197    )?;
198    if manifest.schema_version != 1 || manifest.signing != "unsigned" {
199        return Err(invalid("unsupported native manifest"));
200    }
201    let mut expected = BTreeSet::from(["manifest.json".to_owned()]);
202    for file in &manifest.files {
203        let (bytes, hash) = checksum(&directory.join(&file.name))?;
204        verify_permissions(&file.name, &directory.join(&file.name))?;
205        if bytes != file.bytes || hash != file.sha256 {
206            return Err(invalid("native artifact checksum mismatch"));
207        }
208        expected.insert(file.name.clone());
209    }
210    for entry in fs::read_dir(directory)? {
211        if !expected.remove(&entry?.file_name().to_string_lossy().into_owned()) {
212            return Err(invalid("unexpected package file"));
213        }
214    }
215    if !expected.is_empty() {
216        return Err(invalid("missing package file"));
217    }
218    Ok(manifest)
219}
220
221const REPOSITORY: &str = "https://github.com/rigspark/rigspark";
222pub const SPONSOR_URL: &str = "https://buymeacoffee.com/shashanksw9";
223pub const SPONSOR_MESSAGE: &str = "If Sparky helps you, please consider sponsoring the project:";
224pub const SPONSOR_HELP: &str = "If Sparky helps you, please consider sponsoring the project:\nhttps://buymeacoffee.com/shashanksw9";
225const MAX_CHECKSUMS: usize = 64 * 1024;
226
227fn release_version(version: &str) -> io::Result<()> {
228    validate(version, TARGETS[0], &["llmup", "rigspark", "rigspark-gui"])
229}
230
231/// Archive and top-level directory name; `cargo binstall` metadata depends on this exact shape.
232pub fn release_archive_stem(target: &str) -> io::Result<String> {
233    if !TARGETS.contains(&target) {
234        return Err(invalid("invalid native package version or target"));
235    }
236    Ok(format!("rigspark-{target}"))
237}
238
239pub fn parse_checksums(text: &str) -> io::Result<std::collections::BTreeMap<String, String>> {
240    if text.is_empty() || text.len() > MAX_CHECKSUMS {
241        return Err(invalid("checksum file is empty or too large"));
242    }
243    let mut entries = std::collections::BTreeMap::new();
244    for line in text.lines() {
245        let (hash, name) = line
246            .split_once("  ")
247            .ok_or_else(|| invalid("checksum lines must be `<sha256>  <file>`"))?;
248        if hash.len() != 64
249            || !hash
250                .bytes()
251                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
252            || name.is_empty()
253            || name.contains(['/', '\\', ' '])
254            || name.starts_with('.')
255            || entries.insert(name.to_owned(), hash.to_owned()).is_some()
256        {
257            return Err(invalid("invalid or duplicate checksum entry"));
258        }
259    }
260    Ok(entries)
261}
262
263pub fn homebrew_formula(
264    version: &str,
265    checksums: &std::collections::BTreeMap<String, String>,
266) -> io::Result<String> {
267    release_version(version)?;
268    let asset = |target: &str| -> io::Result<String> {
269        let file = format!("{}.tar.gz", release_archive_stem(target)?);
270        let sha = checksums
271            .get(&file)
272            .ok_or_else(|| invalid("checksum file is missing a Homebrew archive"))?;
273        Ok(format!(
274            "      url \"{REPOSITORY}/releases/download/v{version}/{file}\"\n      sha256 \"{sha}\"\n"
275        ))
276    };
277    Ok(format!(
278        "class Rigspark < Formula\n  desc \"Hardware-aware CLI for choosing and running local LLMs\"\n  homepage \"{REPOSITORY}\"\n  license \"MIT\"\n\n  on_macos do\n    on_arm do\n{}    end\n    on_intel do\n{}    end\n  end\n\n  on_linux do\n    on_arm do\n{}    end\n    on_intel do\n{}    end\n  end\n\n  def install\n    bin.install \"llmup\", \"rigspark\", \"rigspark-gui\"\n  end\n\n  def caveats\n    <<~EOS\n      {SPONSOR_MESSAGE}\n      {SPONSOR_URL}\n    EOS\n  end\n\n  test do\n    assert_match version.to_s, shell_output(\"#{{bin}}/llmup --version\")\n  end\nend\n",
279        asset("aarch64-apple-darwin")?,
280        asset("x86_64-apple-darwin")?,
281        asset("aarch64-unknown-linux-gnu")?,
282        asset("x86_64-unknown-linux-gnu")?,
283    ))
284}