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/shashankswe2020-ux/rigspark";
222const MAX_CHECKSUMS: usize = 64 * 1024;
223
224fn release_version(version: &str) -> io::Result<()> {
225 validate(version, TARGETS[0], &["llmup", "rigspark", "rigspark-gui"])
226}
227
228pub fn release_archive_stem(target: &str) -> io::Result<String> {
230 if !TARGETS.contains(&target) {
231 return Err(invalid("invalid native package version or target"));
232 }
233 Ok(format!("rigspark-{target}"))
234}
235
236pub fn parse_checksums(text: &str) -> io::Result<std::collections::BTreeMap<String, String>> {
237 if text.is_empty() || text.len() > MAX_CHECKSUMS {
238 return Err(invalid("checksum file is empty or too large"));
239 }
240 let mut entries = std::collections::BTreeMap::new();
241 for line in text.lines() {
242 let (hash, name) = line
243 .split_once(" ")
244 .ok_or_else(|| invalid("checksum lines must be `<sha256> <file>`"))?;
245 if hash.len() != 64
246 || !hash
247 .bytes()
248 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
249 || name.is_empty()
250 || name.contains(['/', '\\', ' '])
251 || name.starts_with('.')
252 || entries.insert(name.to_owned(), hash.to_owned()).is_some()
253 {
254 return Err(invalid("invalid or duplicate checksum entry"));
255 }
256 }
257 Ok(entries)
258}
259
260pub fn homebrew_formula(
261 version: &str,
262 checksums: &std::collections::BTreeMap<String, String>,
263) -> io::Result<String> {
264 release_version(version)?;
265 let asset = |target: &str| -> io::Result<String> {
266 let file = format!("{}.tar.gz", release_archive_stem(target)?);
267 let sha = checksums
268 .get(&file)
269 .ok_or_else(|| invalid("checksum file is missing a Homebrew archive"))?;
270 Ok(format!(
271 " url \"{REPOSITORY}/releases/download/v{version}/{file}\"\n sha256 \"{sha}\"\n"
272 ))
273 };
274 Ok(format!(
275 "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 test do\n assert_match version.to_s, shell_output(\"#{{bin}}/llmup --version\")\n end\nend\n",
276 asset("aarch64-apple-darwin")?,
277 asset("x86_64-apple-darwin")?,
278 asset("aarch64-unknown-linux-gnu")?,
279 asset("x86_64-unknown-linux-gnu")?,
280 ))
281}