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::config::Config::builder()
158 .tls_config(crate::core::http_client::platform_tls_config())
159 .http_status_as_error(false)
160 .build()
161 .into();
162 let resp = agent
163 .put(&url)
164 .header("Authorization", &format!("Bearer {token}"))
165 .header("Content-Type", "application/octet-stream")
166 .send(bytes)
167 .map_err(|e| format!("registry unreachable: {e}"))?;
168 let status = resp.status().as_u16();
169 let body = resp
170 .into_body()
171 .read_to_string()
172 .map_err(|e| format!("read registry response: {e}"))?;
173
174 if status == 201 {
175 let doc: serde_json::Value =
176 serde_json::from_str(&body).map_err(|e| format!("registry returned non-JSON: {e}"))?;
177 return Ok(PublishReceipt {
178 published: doc
179 .get("published")
180 .and_then(|v| v.as_str())
181 .unwrap_or("(unknown)")
182 .to_string(),
183 artifact_sha256: doc
184 .get("artifact_sha256")
185 .and_then(|v| v.as_str())
186 .unwrap_or("")
187 .to_string(),
188 });
189 }
190 let detail = serde_json::from_str::<serde_json::Value>(&body)
192 .ok()
193 .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string))
194 .unwrap_or(body);
195 Err(format!(
196 "registry rejected the publish (HTTP {status}): {detail}"
197 ))
198}
199
200pub fn preflight_bundle(bytes: &[u8]) -> Result<(String, String, String), String> {
204 #[derive(serde::Deserialize)]
205 struct BundleProbe {
206 manifest: PackageManifest,
207 }
208 let probe: BundleProbe =
209 serde_json::from_slice(bytes).map_err(|e| format!("not a ctxpkg bundle: {e}"))?;
210 let manifest = probe.manifest;
211
212 let signed = super::signing::verify_signature(&manifest)?;
213 if !signed {
214 return Err(
215 "package is unsigned — the hosted registry requires ed25519 signatures \
216 (re-export with `lean-ctx pack export <name> --sign`)"
217 .to_string(),
218 );
219 }
220
221 let scoped = manifest.name.clone();
222 let stripped = scoped.strip_prefix('@').ok_or(format!(
223 "manifest.name '{scoped}' is not scoped — hosted packages need '@namespace/name'"
224 ))?;
225 let (ns, name) = stripped
226 .split_once('/')
227 .ok_or(format!("manifest.name '{scoped}' is not '@namespace/name'"))?;
228 Ok((ns.to_string(), name.to_string(), manifest.version))
229}
230
231fn not_found_hint(token: Option<&str>) -> &'static str {
234 if token.is_some() {
235 "package not found in the registry (or your token's namespace does not own it)"
236 } else {
237 "package not found in the registry — private packages need CTXPKG_TOKEN"
238 }
239}
240
241fn payment_hint(body: &str) -> String {
244 serde_json::from_str::<serde_json::Value>(body)
245 .ok()
246 .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string))
247 .unwrap_or_else(|| "this is a paid package — purchase required".to_string())
248}
249
250fn http_get(url: &str, token: Option<&str>) -> Result<String, String> {
251 let agent: ureq::Agent = ureq::config::Config::builder()
252 .tls_config(crate::core::http_client::platform_tls_config())
253 .http_status_as_error(false)
254 .build()
255 .into();
256 let mut req = agent.get(url);
257 if let Some(t) = token {
258 req = req.header("Authorization", &format!("Bearer {t}"));
259 }
260 let resp = req
261 .call()
262 .map_err(|e| format!("registry unreachable: {e}"))?;
263 let status = resp.status().as_u16();
264 let body = resp
265 .into_body()
266 .read_to_string()
267 .map_err(|e| format!("read registry response: {e}"))?;
268 if status == 404 {
269 return Err(not_found_hint(token).to_string());
270 }
271 if status == 402 {
272 return Err(payment_hint(&body));
273 }
274 if status >= 400 {
275 return Err(format!("registry error (HTTP {status})"));
276 }
277 Ok(body)
278}
279
280fn http_get_bytes(url: &str, token: Option<&str>) -> Result<Vec<u8>, String> {
281 let agent: ureq::Agent = ureq::config::Config::builder()
282 .tls_config(crate::core::http_client::platform_tls_config())
283 .http_status_as_error(false)
284 .build()
285 .into();
286 let mut req = agent.get(url);
287 if let Some(t) = token {
288 req = req.header("Authorization", &format!("Bearer {t}"));
289 }
290 let resp = req
291 .call()
292 .map_err(|e| format!("registry unreachable: {e}"))?;
293 let status = resp.status().as_u16();
294 if status == 404 {
295 return Err(not_found_hint(token).to_string());
296 }
297 let mut reader = resp.into_body().into_reader();
298 let mut buf = Vec::new();
299 std::io::Read::read_to_end(&mut reader, &mut buf).map_err(|e| format!("read artifact: {e}"))?;
300 if status == 402 {
301 return Err(payment_hint(&String::from_utf8_lossy(&buf)));
302 }
303 if status >= 400 {
304 return Err(format!("registry error (HTTP {status})"));
305 }
306 Ok(buf)
307}
308
309fn sha256_hex(bytes: &[u8]) -> String {
310 let mut h = Sha256::new();
311 h.update(bytes);
312 crate::core::agent_identity::hex_encode(&h.finalize())
313}
314
315#[cfg(test)]
316mod tests {
317 use super::*;
318
319 #[test]
320 fn remote_ref_parsing() {
321 assert_eq!(
322 parse_remote_ref("acme/auth-context"),
323 Some(RemoteRef {
324 namespace: "acme".into(),
325 name: "auth-context".into(),
326 version: None
327 })
328 );
329 assert_eq!(
330 parse_remote_ref("@acme/auth-context@1.2.0"),
331 Some(RemoteRef {
332 namespace: "acme".into(),
333 name: "auth-context".into(),
334 version: Some("1.2.0".into())
335 })
336 );
337 assert_eq!(parse_remote_ref("local-package"), None);
338 assert_eq!(parse_remote_ref("/x"), None);
339 assert_eq!(parse_remote_ref("ns/"), None);
340 }
341
342 #[test]
343 fn version_selection_skips_yanked_unless_pinned() {
344 let versions = vec![
345 VersionInfo {
346 version: "2.0.0".into(),
347 artifact_sha256: "b".into(),
348 yanked: true,
349 },
350 VersionInfo {
351 version: "1.0.0".into(),
352 artifact_sha256: "a".into(),
353 yanked: false,
354 },
355 ];
356 assert_eq!(
357 select_version(&versions, None).expect("latest").version,
358 "1.0.0"
359 );
360 assert_eq!(
361 select_version(&versions, Some("2.0.0"))
362 .expect("pinned")
363 .version,
364 "2.0.0"
365 );
366 assert!(select_version(&versions, Some("3.0.0")).is_err());
367 }
368
369 #[test]
370 fn registry_base_resolution_order() {
371 assert_eq!(
372 registry_base(Some("https://r.example/api/")),
373 "https://r.example/api"
374 );
375 if std::env::var("CTXPKG_REGISTRY").is_err() {
377 assert_eq!(registry_base(None), DEFAULT_REGISTRY);
378 }
379 }
380
381 #[test]
382 fn preflight_rejects_garbage_and_unscoped() {
383 assert!(preflight_bundle(b"not json").is_err());
384 }
385}