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