lean_ctx/core/context_package/
remote.rs1use sha2::{Digest, Sha256};
9
10use super::manifest::PackageManifest;
11
12pub const DEFAULT_REGISTRY: &str = "https://ctxpkg.com/api";
14
15pub fn registry_base(flag: Option<&str>) -> String {
18 flag.map(str::to_string)
19 .or_else(|| std::env::var("CTXPKG_REGISTRY").ok())
20 .filter(|s| !s.trim().is_empty())
21 .unwrap_or_else(|| DEFAULT_REGISTRY.to_string())
22 .trim_end_matches('/')
23 .to_string()
24}
25
26pub fn publish_token(flag: Option<&str>) -> Option<String> {
30 flag.map(str::to_string)
31 .or_else(|| std::env::var("CTXPKG_TOKEN").ok())
32 .filter(|s| !s.trim().is_empty())
33}
34
35#[derive(Debug, PartialEq, Eq)]
38pub struct RemoteRef {
39 pub namespace: String,
40 pub name: String,
41 pub version: Option<String>,
42}
43
44pub fn parse_remote_ref(input: &str) -> Option<RemoteRef> {
46 let trimmed = input.strip_prefix('@').unwrap_or(input);
47 let (ns, rest) = trimmed.split_once('/')?;
48 let (name, version) = match rest.split_once('@') {
49 Some((n, v)) => (n, Some(v.to_string())),
50 None => (rest, None),
51 };
52 if ns.is_empty() || name.is_empty() {
53 return None;
54 }
55 Some(RemoteRef {
56 namespace: ns.to_string(),
57 name: name.to_string(),
58 version,
59 })
60}
61
62#[derive(Debug)]
64pub struct VersionInfo {
65 pub version: String,
66 pub artifact_sha256: String,
67 pub yanked: bool,
68}
69
70pub fn fetch_versions(
73 base: &str,
74 ns: &str,
75 name: &str,
76 token: Option<&str>,
77) -> Result<Vec<VersionInfo>, String> {
78 let url = format!("{base}/v1/packages/{ns}/{name}/index.json");
79 let body = http_get(&url, token)?;
80 let doc: serde_json::Value =
81 serde_json::from_str(&body).map_err(|e| format!("registry returned non-JSON: {e}"))?;
82 let versions = doc
83 .get("versions")
84 .and_then(|v| v.as_array())
85 .ok_or("registry index has no versions array")?;
86 Ok(versions
87 .iter()
88 .filter_map(|v| {
89 Some(VersionInfo {
90 version: v.get("version")?.as_str()?.to_string(),
91 artifact_sha256: v.get("artifact_sha256")?.as_str()?.to_string(),
92 yanked: v
93 .get("yanked")
94 .and_then(serde_json::Value::as_bool)
95 .unwrap_or(false),
96 })
97 })
98 .collect())
99}
100
101pub fn select_version<'a>(
104 versions: &'a [VersionInfo],
105 pin: Option<&str>,
106) -> Result<&'a VersionInfo, String> {
107 match pin {
108 Some(want) => versions
109 .iter()
110 .find(|v| v.version == want)
111 .ok_or(format!("version {want} not found in the registry")),
112 None => versions
113 .iter()
114 .find(|v| !v.yanked)
115 .ok_or("no installable (non-yanked) version found".to_string()),
116 }
117}
118
119pub fn download_verified(
121 base: &str,
122 ns: &str,
123 name: &str,
124 info: &VersionInfo,
125 token: Option<&str>,
126) -> Result<Vec<u8>, String> {
127 let url = format!("{base}/v1/packages/{ns}/{name}/{}/download", info.version);
128 let bytes = http_get_bytes(&url, token)?;
129 let actual = sha256_hex(&bytes);
130 if actual != info.artifact_sha256 {
131 return Err(format!(
132 "artifact checksum mismatch — registry index says {}, downloaded bytes hash to {actual}; \
133 refusing to install",
134 info.artifact_sha256
135 ));
136 }
137 Ok(bytes)
138}
139
140#[derive(Debug)]
142pub struct PublishReceipt {
143 pub published: String,
144 pub artifact_sha256: String,
145}
146
147pub fn publish(
149 base: &str,
150 token: &str,
151 ns: &str,
152 name: &str,
153 version: &str,
154 bytes: &[u8],
155) -> Result<PublishReceipt, String> {
156 let url = format!("{base}/v1/packages/{ns}/{name}/{version}");
157 let agent: ureq::Agent = ureq::Agent::config_builder()
158 .http_status_as_error(false)
159 .build()
160 .into();
161 let resp = agent
162 .put(&url)
163 .header("Authorization", &format!("Bearer {token}"))
164 .header("Content-Type", "application/octet-stream")
165 .send(bytes)
166 .map_err(|e| format!("registry unreachable: {e}"))?;
167 let status = resp.status().as_u16();
168 let body = resp
169 .into_body()
170 .read_to_string()
171 .map_err(|e| format!("read registry response: {e}"))?;
172
173 if status == 201 {
174 let doc: serde_json::Value =
175 serde_json::from_str(&body).map_err(|e| format!("registry returned non-JSON: {e}"))?;
176 return Ok(PublishReceipt {
177 published: doc
178 .get("published")
179 .and_then(|v| v.as_str())
180 .unwrap_or("(unknown)")
181 .to_string(),
182 artifact_sha256: doc
183 .get("artifact_sha256")
184 .and_then(|v| v.as_str())
185 .unwrap_or("")
186 .to_string(),
187 });
188 }
189 let detail = serde_json::from_str::<serde_json::Value>(&body)
191 .ok()
192 .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string))
193 .unwrap_or(body);
194 Err(format!(
195 "registry rejected the publish (HTTP {status}): {detail}"
196 ))
197}
198
199pub fn preflight_bundle(bytes: &[u8]) -> Result<(String, String, String), String> {
203 #[derive(serde::Deserialize)]
204 struct BundleProbe {
205 manifest: PackageManifest,
206 }
207 let probe: BundleProbe =
208 serde_json::from_slice(bytes).map_err(|e| format!("not a ctxpkg bundle: {e}"))?;
209 let manifest = probe.manifest;
210
211 let signed = super::signing::verify_signature(&manifest)?;
212 if !signed {
213 return Err(
214 "package is unsigned — the hosted registry requires ed25519 signatures \
215 (re-export with `lean-ctx pack export <name> --sign`)"
216 .to_string(),
217 );
218 }
219
220 let scoped = manifest.name.clone();
221 let stripped = scoped.strip_prefix('@').ok_or(format!(
222 "manifest.name '{scoped}' is not scoped — hosted packages need '@namespace/name'"
223 ))?;
224 let (ns, name) = stripped
225 .split_once('/')
226 .ok_or(format!("manifest.name '{scoped}' is not '@namespace/name'"))?;
227 Ok((ns.to_string(), name.to_string(), manifest.version))
228}
229
230fn not_found_hint(token: Option<&str>) -> &'static str {
233 if token.is_some() {
234 "package not found in the registry (or your token's namespace does not own it)"
235 } else {
236 "package not found in the registry — private packages need CTXPKG_TOKEN"
237 }
238}
239
240fn payment_hint(body: &str) -> String {
243 serde_json::from_str::<serde_json::Value>(body)
244 .ok()
245 .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string))
246 .unwrap_or_else(|| "this is a paid package — purchase required".to_string())
247}
248
249fn http_get(url: &str, token: Option<&str>) -> Result<String, String> {
250 let agent: ureq::Agent = ureq::Agent::config_builder()
251 .http_status_as_error(false)
252 .build()
253 .into();
254 let mut req = agent.get(url);
255 if let Some(t) = token {
256 req = req.header("Authorization", &format!("Bearer {t}"));
257 }
258 let resp = req
259 .call()
260 .map_err(|e| format!("registry unreachable: {e}"))?;
261 let status = resp.status().as_u16();
262 let body = resp
263 .into_body()
264 .read_to_string()
265 .map_err(|e| format!("read registry response: {e}"))?;
266 if status == 404 {
267 return Err(not_found_hint(token).to_string());
268 }
269 if status == 402 {
270 return Err(payment_hint(&body));
271 }
272 if status >= 400 {
273 return Err(format!("registry error (HTTP {status})"));
274 }
275 Ok(body)
276}
277
278fn http_get_bytes(url: &str, token: Option<&str>) -> Result<Vec<u8>, String> {
279 let agent: ureq::Agent = ureq::Agent::config_builder()
280 .http_status_as_error(false)
281 .build()
282 .into();
283 let mut req = agent.get(url);
284 if let Some(t) = token {
285 req = req.header("Authorization", &format!("Bearer {t}"));
286 }
287 let resp = req
288 .call()
289 .map_err(|e| format!("registry unreachable: {e}"))?;
290 let status = resp.status().as_u16();
291 if status == 404 {
292 return Err(not_found_hint(token).to_string());
293 }
294 let mut reader = resp.into_body().into_reader();
295 let mut buf = Vec::new();
296 std::io::Read::read_to_end(&mut reader, &mut buf).map_err(|e| format!("read artifact: {e}"))?;
297 if status == 402 {
298 return Err(payment_hint(&String::from_utf8_lossy(&buf)));
299 }
300 if status >= 400 {
301 return Err(format!("registry error (HTTP {status})"));
302 }
303 Ok(buf)
304}
305
306fn sha256_hex(bytes: &[u8]) -> String {
307 let mut h = Sha256::new();
308 h.update(bytes);
309 format!("{:x}", h.finalize())
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315
316 #[test]
317 fn remote_ref_parsing() {
318 assert_eq!(
319 parse_remote_ref("acme/auth-context"),
320 Some(RemoteRef {
321 namespace: "acme".into(),
322 name: "auth-context".into(),
323 version: None
324 })
325 );
326 assert_eq!(
327 parse_remote_ref("@acme/auth-context@1.2.0"),
328 Some(RemoteRef {
329 namespace: "acme".into(),
330 name: "auth-context".into(),
331 version: Some("1.2.0".into())
332 })
333 );
334 assert_eq!(parse_remote_ref("local-package"), None);
335 assert_eq!(parse_remote_ref("/x"), None);
336 assert_eq!(parse_remote_ref("ns/"), None);
337 }
338
339 #[test]
340 fn version_selection_skips_yanked_unless_pinned() {
341 let versions = vec![
342 VersionInfo {
343 version: "2.0.0".into(),
344 artifact_sha256: "b".into(),
345 yanked: true,
346 },
347 VersionInfo {
348 version: "1.0.0".into(),
349 artifact_sha256: "a".into(),
350 yanked: false,
351 },
352 ];
353 assert_eq!(
354 select_version(&versions, None).expect("latest").version,
355 "1.0.0"
356 );
357 assert_eq!(
358 select_version(&versions, Some("2.0.0"))
359 .expect("pinned")
360 .version,
361 "2.0.0"
362 );
363 assert!(select_version(&versions, Some("3.0.0")).is_err());
364 }
365
366 #[test]
367 fn registry_base_resolution_order() {
368 assert_eq!(
369 registry_base(Some("https://r.example/api/")),
370 "https://r.example/api"
371 );
372 if std::env::var("CTXPKG_REGISTRY").is_err() {
374 assert_eq!(registry_base(None), DEFAULT_REGISTRY);
375 }
376 }
377
378 #[test]
379 fn preflight_rejects_garbage_and_unscoped() {
380 assert!(preflight_bundle(b"not json").is_err());
381 }
382}