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