1use crate::qapp_paths::{ensure_qapps_dir, qapps_dir};
7use crate::qapp_registry::{QappPackageManifest, QAPP_PACKAGE_MANIFEST};
8use crate::qapp_version::{is_version_newer, normalize_version_label};
9use ed25519_dalek::{Signature, Verifier, VerifyingKey};
10use serde::{Deserialize, Serialize};
11use sha2::{Digest, Sha256};
12use std::collections::HashMap;
13use std::fs;
14use std::io;
15use std::path::{Component, Path, PathBuf};
16
17pub const QAPP_REGISTRY_FILE: &str = "registry.json";
18pub const PACKAGE_MANIFEST_SIDECAR: &str = "package-manifest.json";
19pub const SUPPORTED_QAPP_ABI_VERSION: &str = "1.0";
20pub const SUPPORTED_HOST_API_VERSION: &str = "1";
21
22#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
23pub struct QappFileHash {
24 pub path: String,
25 pub sha256: String,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
29pub struct QappContentManifest {
30 pub schema_version: u32,
31 pub package_id: String,
32 pub version: String,
33 #[serde(default, skip_serializing_if = "String::is_empty")]
34 pub abi_version: String,
35 #[serde(default, skip_serializing_if = "String::is_empty")]
36 pub host_api_version: String,
37 pub files: Vec<QappFileHash>,
38 #[serde(default, skip_serializing_if = "String::is_empty")]
39 pub signature_hex: String,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
43pub struct QappRegistryEntry {
44 pub package_id: String,
45 pub active_version: String,
46 pub content_hash: String,
47 pub installed_at_unix: u64,
48 pub revoked: bool,
49 #[serde(default, skip_serializing_if = "Vec::is_empty")]
50 pub archived_versions: Vec<String>,
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
54pub struct QappInstallRegistry {
55 pub packages: HashMap<String, QappRegistryEntry>,
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum InstallPolicy {
60 Development,
62 Production,
64}
65
66#[derive(Debug, PartialEq, Eq)]
67pub enum QappInstallError {
68 InvalidPackageId(String),
69 PathTraversal(String),
70 ManifestMissing,
71 ManifestInvalid(String),
72 ContentManifestInvalid(String),
73 HashMismatch {
74 path: String,
75 expected: String,
76 actual: String,
77 },
78 SignatureInvalid(String),
79 AbiMismatch {
80 found: String,
81 supported: String,
82 },
83 PackageRevoked(String),
84 StagingFailed(String),
85 RegistryCorrupt(String),
86 Io(String),
87}
88
89impl std::fmt::Display for QappInstallError {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 match self {
92 Self::InvalidPackageId(id) => write!(f, "invalid package id: {id}"),
93 Self::PathTraversal(p) => write!(f, "path traversal rejected: {p}"),
94 Self::ManifestMissing => write!(f, "qapp.json not found"),
95 Self::ManifestInvalid(e) => write!(f, "invalid qapp.json: {e}"),
96 Self::ContentManifestInvalid(e) => write!(f, "invalid package-manifest.json: {e}"),
97 Self::HashMismatch {
98 path,
99 expected,
100 actual,
101 } => {
102 write!(
103 f,
104 "hash mismatch for {path}: expected {expected}, got {actual}"
105 )
106 }
107 Self::SignatureInvalid(e) => write!(f, "signature invalid: {e}"),
108 Self::AbiMismatch { found, supported } => {
109 write!(f, "ABI version {found} not supported (need {supported})")
110 }
111 Self::PackageRevoked(id) => write!(f, "package revoked: {id}"),
112 Self::StagingFailed(e) => write!(f, "staging failed: {e}"),
113 Self::RegistryCorrupt(e) => write!(f, "registry corrupt: {e}"),
114 Self::Io(e) => write!(f, "io error: {e}"),
115 }
116 }
117}
118
119impl From<io::Error> for QappInstallError {
120 fn from(value: io::Error) -> Self {
121 Self::Io(value.to_string())
122 }
123}
124
125pub fn package_id_from_manifest(manifest: &QappPackageManifest) -> String {
127 manifest.name.trim().to_string()
128}
129
130pub fn validate_package_id(package_id: &str) -> Result<(), QappInstallError> {
132 if package_id.is_empty() {
133 return Err(QappInstallError::InvalidPackageId("empty".into()));
134 }
135 if package_id.contains("..") || package_id.contains('/') || package_id.contains('\\') {
136 return Err(QappInstallError::InvalidPackageId(package_id.into()));
137 }
138 for ch in package_id.chars() {
139 let ok = ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == ' ';
140 if !ok {
141 return Err(QappInstallError::InvalidPackageId(package_id.into()));
142 }
143 }
144 Ok(())
145}
146
147fn sha256_hex(bytes: &[u8]) -> String {
148 let digest = Sha256::digest(bytes);
149 hex::encode(digest.as_slice())
150}
151
152fn sha256_file(path: &Path) -> Result<String, QappInstallError> {
153 let bytes = fs::read(path)?;
154 Ok(sha256_hex(&bytes))
155}
156
157fn registry_path(storage: &Path) -> PathBuf {
158 qapps_dir(storage).join(QAPP_REGISTRY_FILE)
159}
160
161fn versions_dir(storage: &Path, package_id: &str) -> PathBuf {
162 qapps_dir(storage).join(package_id).join("versions")
163}
164
165fn active_package_dir(storage: &Path, package_id: &str) -> PathBuf {
166 qapps_dir(storage).join(package_id)
167}
168
169fn staging_root(storage: &Path) -> PathBuf {
170 qapps_dir(storage).join(".staging")
171}
172
173pub fn load_install_registry(storage: &Path) -> Result<QappInstallRegistry, QappInstallError> {
175 let path = registry_path(storage);
176 if !path.is_file() {
177 return Ok(QappInstallRegistry::default());
178 }
179 let content =
180 fs::read_to_string(&path).map_err(|e| QappInstallError::RegistryCorrupt(e.to_string()))?;
181 serde_json::from_str(&content).map_err(|e| QappInstallError::RegistryCorrupt(e.to_string()))
182}
183
184pub fn save_install_registry(
186 storage: &Path,
187 registry: &QappInstallRegistry,
188) -> Result<(), QappInstallError> {
189 ensure_qapps_dir(storage)?;
190 let path = registry_path(storage);
191 let staging = path.with_extension("json.staging");
192 let json = serde_json::to_string_pretty(registry)
193 .map_err(|e| QappInstallError::RegistryCorrupt(e.to_string()))?;
194 fs::write(&staging, json)?;
195 fs::rename(&staging, &path)?;
196 Ok(())
197}
198
199pub fn resolve_active_package_dir(storage: &Path, package_id: &str) -> PathBuf {
201 let active = active_package_dir(storage, package_id);
202 if active.join(QAPP_PACKAGE_MANIFEST).is_file() {
203 return active;
204 }
205 active
206}
207
208pub fn is_package_revoked(storage: &Path, package_id: &str) -> bool {
210 load_install_registry(storage)
211 .ok()
212 .and_then(|r| r.packages.get(package_id).map(|e| e.revoked))
213 .unwrap_or(false)
214}
215
216fn relative_path_ok(rel: &str) -> bool {
217 let path = Path::new(rel);
218 for component in path.components() {
219 match component {
220 Component::ParentDir | Component::RootDir | Component::Prefix(_) => return false,
221 _ => {}
222 }
223 }
224 true
225}
226
227fn collect_package_files(dir: &Path) -> Result<Vec<(String, String)>, QappInstallError> {
228 let mut out = Vec::new();
229 collect_package_files_inner(dir, dir, &mut out)?;
230 out.sort_by(|a, b| a.0.cmp(&b.0));
231 Ok(out)
232}
233
234fn collect_package_files_inner(
235 root: &Path,
236 current: &Path,
237 out: &mut Vec<(String, String)>,
238) -> Result<(), QappInstallError> {
239 for entry in fs::read_dir(current)? {
240 let entry = entry?;
241 let path = entry.path();
242 let file_name = entry.file_name().to_string_lossy().to_string();
243 if file_name == ".staging" || file_name == QAPP_REGISTRY_FILE {
244 continue;
245 }
246 if path.is_dir() {
247 if file_name == "versions" {
248 continue;
249 }
250 collect_package_files_inner(root, &path, out)?;
251 } else {
252 let rel = path
253 .strip_prefix(root)
254 .map_err(|_| QappInstallError::PathTraversal(path.display().to_string()))?
255 .to_string_lossy()
256 .replace('\\', "/");
257 if !relative_path_ok(&rel) {
258 return Err(QappInstallError::PathTraversal(rel));
259 }
260 let hash = sha256_file(&path)?;
261 out.push((rel, hash));
262 }
263 }
264 Ok(())
265}
266
267fn verify_content_manifest(
268 source_dir: &Path,
269 manifest: &QappContentManifest,
270 policy: InstallPolicy,
271 trust_pubkey: Option<&[u8; 32]>,
272) -> Result<(), QappInstallError> {
273 validate_package_id(&manifest.package_id)?;
274 if !manifest.abi_version.is_empty() && manifest.abi_version != SUPPORTED_QAPP_ABI_VERSION {
275 return Err(QappInstallError::AbiMismatch {
276 found: manifest.abi_version.clone(),
277 supported: SUPPORTED_QAPP_ABI_VERSION.into(),
278 });
279 }
280 if !manifest.host_api_version.is_empty()
281 && manifest.host_api_version != SUPPORTED_HOST_API_VERSION
282 {
283 return Err(QappInstallError::AbiMismatch {
284 found: manifest.host_api_version.clone(),
285 supported: SUPPORTED_HOST_API_VERSION.into(),
286 });
287 }
288
289 for file in &manifest.files {
290 if !relative_path_ok(&file.path) {
291 return Err(QappInstallError::PathTraversal(file.path.clone()));
292 }
293 let disk_path = source_dir.join(&file.path);
294 if !disk_path.is_file() {
295 return Err(QappInstallError::HashMismatch {
296 path: file.path.clone(),
297 expected: file.sha256.clone(),
298 actual: "missing".into(),
299 });
300 }
301 let actual = sha256_file(&disk_path)?;
302 if actual != file.sha256 {
303 return Err(QappInstallError::HashMismatch {
304 path: file.path.clone(),
305 expected: file.sha256.clone(),
306 actual,
307 });
308 }
309 }
310
311 if policy == InstallPolicy::Production {
312 let sig_hex = manifest.signature_hex.trim();
313 if sig_hex.is_empty() {
314 return Err(QappInstallError::SignatureInvalid(
315 "production install requires signature_hex".into(),
316 ));
317 }
318 let pk = trust_pubkey.ok_or_else(|| {
319 QappInstallError::SignatureInvalid("no trust pubkey configured".into())
320 })?;
321 let sig_bytes =
322 hex::decode(sig_hex).map_err(|e| QappInstallError::SignatureInvalid(e.to_string()))?;
323 if sig_bytes.len() != 64 {
324 return Err(QappInstallError::SignatureInvalid(
325 "expected 64-byte ed25519 signature".into(),
326 ));
327 }
328 let mut sig_arr = [0u8; 64];
329 sig_arr.copy_from_slice(&sig_bytes);
330 let signature = Signature::from_bytes(&sig_arr);
331 let verifying_key = VerifyingKey::from_bytes(pk)
332 .map_err(|e| QappInstallError::SignatureInvalid(e.to_string()))?;
333 let mut sign_payload = serde_json::to_vec(manifest)
334 .map_err(|e| QappInstallError::SignatureInvalid(e.to_string()))?;
335 if let Ok(value) = serde_json::from_slice::<serde_json::Value>(&sign_payload) {
336 if let Some(obj) = value.as_object() {
337 let mut unsigned = obj.clone();
338 unsigned.remove("signature_hex");
339 sign_payload = serde_json::to_vec(&unsigned)
340 .map_err(|e| QappInstallError::SignatureInvalid(e.to_string()))?;
341 }
342 }
343 verifying_key
344 .verify(&sign_payload, &signature)
345 .map_err(|e| QappInstallError::SignatureInvalid(e.to_string()))?;
346 }
347
348 Ok(())
349}
350
351fn load_sidecar_manifest(source_dir: &Path) -> Option<QappContentManifest> {
352 let path = source_dir.join(PACKAGE_MANIFEST_SIDECAR);
353 if !path.is_file() {
354 return None;
355 }
356 let content = fs::read_to_string(path).ok()?;
357 serde_json::from_str(&content).ok()
358}
359
360fn copy_dir_all(src: &Path, dst: &Path) -> Result<(), QappInstallError> {
361 fs::create_dir_all(dst)?;
362 for entry in fs::read_dir(src)? {
363 let entry = entry?;
364 let file_type = entry.file_type()?;
365 let name = entry.file_name();
366 let name_str = name.to_string_lossy();
367 if name_str == "versions" {
368 continue;
369 }
370 let target = dst.join(&name);
371 if file_type.is_dir() {
372 copy_dir_all(&entry.path(), &target)?;
373 } else {
374 fs::copy(entry.path(), target)?;
375 }
376 }
377 Ok(())
378}
379
380fn remove_dir_contents(dir: &Path) -> Result<(), QappInstallError> {
381 if !dir.exists() {
382 return Ok(());
383 }
384 for entry in fs::read_dir(dir)? {
385 let entry = entry?;
386 let path = entry.path();
387 let name = entry.file_name().to_string_lossy().to_string();
388 if name == "versions" {
389 continue;
390 }
391 if path.is_dir() {
392 fs::remove_dir_all(&path)?;
393 } else {
394 fs::remove_file(&path)?;
395 }
396 }
397 Ok(())
398}
399
400fn archive_active_version(
401 storage: &Path,
402 package_id: &str,
403 version: &str,
404) -> Result<(), QappInstallError> {
405 let active = active_package_dir(storage, package_id);
406 if !active.join(QAPP_PACKAGE_MANIFEST).is_file() {
407 return Ok(());
408 }
409 let archive_root = versions_dir(storage, package_id).join(version);
410 if archive_root.exists() {
411 return Ok(());
412 }
413 fs::create_dir_all(archive_root.parent().unwrap())?;
414 copy_dir_all(&active, &archive_root)?;
415 Ok(())
416}
417
418pub fn validate_package_source(
420 source_dir: &Path,
421 policy: InstallPolicy,
422 trust_pubkey: Option<&[u8; 32]>,
423) -> Result<(QappPackageManifest, String), QappInstallError> {
424 let manifest_path = source_dir.join(QAPP_PACKAGE_MANIFEST);
425 if !manifest_path.is_file() {
426 return Err(QappInstallError::ManifestMissing);
427 }
428 let content = fs::read_to_string(&manifest_path)?;
429 let manifest: QappPackageManifest = serde_json::from_str(&content)
430 .map_err(|e| QappInstallError::ManifestInvalid(e.to_string()))?;
431 let package_id = package_id_from_manifest(&manifest);
432 validate_package_id(&package_id)?;
433
434 if let Some(sidecar) = load_sidecar_manifest(source_dir) {
435 if sidecar.package_id != package_id {
436 return Err(QappInstallError::ContentManifestInvalid(format!(
437 "package_id mismatch: manifest {} vs sidecar {}",
438 package_id, sidecar.package_id
439 )));
440 }
441 verify_content_manifest(source_dir, &sidecar, policy, trust_pubkey)?;
442 } else if policy == InstallPolicy::Production {
443 return Err(QappInstallError::ContentManifestInvalid(
444 "production install requires package-manifest.json".into(),
445 ));
446 }
447
448 let files = collect_package_files(source_dir)?;
449 let aggregate = files
450 .iter()
451 .map(|(p, h)| format!("{p}:{h}"))
452 .collect::<Vec<_>>()
453 .join("\n");
454 let content_hash = sha256_hex(aggregate.as_bytes());
455 Ok((manifest, content_hash))
456}
457
458pub fn install_package_atomic(
460 storage: &Path,
461 source_dir: &Path,
462 policy: InstallPolicy,
463 trust_pubkey: Option<&[u8; 32]>,
464) -> Result<QappRegistryEntry, QappInstallError> {
465 let (manifest, content_hash) = validate_package_source(source_dir, policy, trust_pubkey)?;
466 let package_id = package_id_from_manifest(&manifest);
467 let version = normalize_version_label(&manifest.version);
468
469 if is_package_revoked(storage, &package_id) {
470 return Err(QappInstallError::PackageRevoked(package_id));
471 }
472
473 ensure_qapps_dir(storage)?;
474 let staging_parent = staging_root(storage);
475 fs::create_dir_all(&staging_parent)?;
476 let staging_dir =
477 staging_parent.join(format!("{package_id}-{version}-{}", uuid::Uuid::new_v4()));
478 copy_dir_all(source_dir, &staging_dir)?;
479
480 let dest = active_package_dir(storage, &package_id);
481 let mut registry = load_install_registry(storage)?;
482
483 let install_result = (|| -> Result<QappRegistryEntry, QappInstallError> {
484 if let Some(existing) = registry.packages.get(&package_id) {
485 if !is_version_newer(&version, &existing.active_version)
486 && version != existing.active_version
487 {
488 return Err(QappInstallError::StagingFailed(format!(
489 "refusing downgrade from {} to {}",
490 existing.active_version, version
491 )));
492 }
493 if version != existing.active_version {
494 archive_active_version(storage, &package_id, &existing.active_version)?;
495 }
496 }
497
498 fs::create_dir_all(dest.parent().unwrap())?;
499 if dest.exists() {
500 remove_dir_contents(&dest)?;
501 } else {
502 fs::create_dir_all(&dest)?;
503 }
504 copy_dir_all(&staging_dir, &dest)?;
505
506 let installed_at_unix = std::time::SystemTime::now()
507 .duration_since(std::time::UNIX_EPOCH)
508 .map(|d| d.as_secs())
509 .unwrap_or(0);
510
511 let mut archived = registry
512 .packages
513 .get(&package_id)
514 .map(|e| e.archived_versions.clone())
515 .unwrap_or_default();
516 if let Some(prev) = registry.packages.get(&package_id) {
517 if prev.active_version != version && !archived.contains(&prev.active_version) {
518 archived.push(prev.active_version.clone());
519 }
520 }
521
522 let entry = QappRegistryEntry {
523 package_id: package_id.clone(),
524 active_version: version,
525 content_hash,
526 installed_at_unix,
527 revoked: false,
528 archived_versions: archived,
529 };
530 registry.packages.insert(package_id, entry.clone());
531 save_install_registry(storage, ®istry)?;
532 Ok(entry)
533 })();
534
535 let _ = fs::remove_dir_all(&staging_dir);
536 install_result
537}
538
539pub fn revoke_package(storage: &Path, package_id: &str) -> Result<(), QappInstallError> {
541 validate_package_id(package_id)?;
542 let mut registry = load_install_registry(storage)?;
543 let entry = registry
544 .packages
545 .get_mut(package_id)
546 .ok_or_else(|| QappInstallError::StagingFailed(format!("unknown package {package_id}")))?;
547 entry.revoked = true;
548 save_install_registry(storage, ®istry)
549}
550
551pub fn list_registry_entries(storage: &Path) -> Result<Vec<QappRegistryEntry>, QappInstallError> {
553 Ok(load_install_registry(storage)?
554 .packages
555 .into_values()
556 .collect())
557}
558
559pub fn reconcile_registry_with_disk(
561 storage: &Path,
562) -> Result<QappInstallRegistry, QappInstallError> {
563 ensure_qapps_dir(storage)?;
564 let mut registry = load_install_registry(storage)?;
565 let root = qapps_dir(storage);
566
567 if let Ok(entries) = fs::read_dir(&root) {
568 for entry in entries.filter_map(Result::ok) {
569 let path = entry.path();
570 if !path.is_dir() {
571 continue;
572 }
573 let name = entry.file_name().to_string_lossy().to_string();
574 if name.starts_with('.') || name == QAPP_REGISTRY_FILE {
575 continue;
576 }
577 if !path.join(QAPP_PACKAGE_MANIFEST).is_file() {
578 continue;
579 }
580 if registry.packages.contains_key(&name) {
581 continue;
582 }
583 let content = fs::read_to_string(path.join(QAPP_PACKAGE_MANIFEST))?;
584 let manifest: QappPackageManifest = serde_json::from_str(&content)
585 .map_err(|e| QappInstallError::ManifestInvalid(e.to_string()))?;
586 let files = collect_package_files(&path)?;
587 let aggregate = files
588 .iter()
589 .map(|(p, h)| format!("{p}:{h}"))
590 .collect::<Vec<_>>()
591 .join("\n");
592 let content_hash = sha256_hex(aggregate.as_bytes());
593 registry.packages.insert(
594 name.clone(),
595 QappRegistryEntry {
596 package_id: name,
597 active_version: normalize_version_label(&manifest.version),
598 content_hash,
599 installed_at_unix: 0,
600 revoked: false,
601 archived_versions: Vec::new(),
602 },
603 );
604 }
605 }
606
607 save_install_registry(storage, ®istry)?;
608 Ok(registry)
609}
610
611pub fn uninstall_package(
613 storage: &Path,
614 package_id: &str,
615 purge_data: bool,
616) -> Result<(), QappInstallError> {
617 validate_package_id(package_id)?;
618 let mut registry = load_install_registry(storage)?;
619 if !registry.packages.contains_key(package_id) {
620 return Err(QappInstallError::StagingFailed(format!(
621 "package '{package_id}' is not installed in registry"
622 )));
623 }
624 registry.packages.remove(package_id);
625 save_install_registry(storage, ®istry)?;
626
627 let pkg_dir = active_package_dir(storage, package_id);
628 if pkg_dir.exists() {
629 fs::remove_dir_all(&pkg_dir)?;
630 }
631
632 if purge_data {
633 let data_dir = qapps_dir(storage).join(".data").join(package_id);
634 if data_dir.exists() {
635 fs::remove_dir_all(&data_dir)?;
636 }
637 }
638
639 Ok(())
640}
641
642#[cfg(test)]
643mod tests {
644 use super::*;
645 use std::time::{SystemTime, UNIX_EPOCH};
646
647 fn temp_storage() -> PathBuf {
648 let nanos = SystemTime::now()
649 .duration_since(UNIX_EPOCH)
650 .unwrap()
651 .as_nanos();
652 std::env::temp_dir().join(format!("qualia-qapp-install-test-{nanos}"))
653 }
654
655 fn write_minimal_package(dir: &Path, name: &str, version: &str) {
656 fs::create_dir_all(dir).unwrap();
657 let manifest = format!(
658 r#"{{
659 "name": "{name}",
660 "version": "{version}",
661 "required_shapes": ["schema:Test"]
662}}"#
663 );
664 fs::write(dir.join(QAPP_PACKAGE_MANIFEST), manifest).unwrap();
665 fs::write(dir.join("index.html"), "<html></html>").unwrap();
666 }
667
668 #[test]
669 fn rejects_path_traversal_package_id() {
670 assert!(validate_package_id("..").is_err());
671 assert!(validate_package_id("foo/bar").is_err());
672 assert!(validate_package_id("Anatomy").is_ok());
673 }
674
675 #[test]
676 fn atomic_install_and_registry_round_trip() {
677 let storage = temp_storage();
678 let source = storage.join("source");
679 write_minimal_package(&source, "TestApp", "0.0.1");
680
681 let entry =
682 install_package_atomic(&storage, &source, InstallPolicy::Development, None).unwrap();
683 assert_eq!(entry.package_id, "TestApp");
684 assert_eq!(entry.active_version, "0.0.1");
685 assert!(active_package_dir(&storage, "TestApp")
686 .join("index.html")
687 .is_file());
688
689 let registry = load_install_registry(&storage).unwrap();
690 assert!(registry.packages.contains_key("TestApp"));
691 let _ = fs::remove_dir_all(&storage);
692 }
693
694 #[test]
695 fn interrupted_staging_keeps_prior_version() {
696 let storage = temp_storage();
697 let v1 = storage.join("v1");
698 let v2 = storage.join("v2");
699 write_minimal_package(&v1, "TestApp", "0.0.1");
700 write_minimal_package(&v2, "TestApp", "0.0.2");
701 fs::write(v2.join("index.html"), "<html>v2</html>").unwrap();
702
703 install_package_atomic(&storage, &v1, InstallPolicy::Development, None).unwrap();
704 install_package_atomic(&storage, &v2, InstallPolicy::Development, None).unwrap();
705
706 let html =
707 fs::read_to_string(active_package_dir(&storage, "TestApp").join("index.html")).unwrap();
708 assert!(html.contains("v2"));
709 let registry = load_install_registry(&storage).unwrap();
710 assert_eq!(registry.packages["TestApp"].active_version, "0.0.2");
711 assert!(versions_dir(&storage, "TestApp").join("0.0.1").is_dir());
712 let _ = fs::remove_dir_all(&storage);
713 }
714
715 #[test]
716 fn revoked_package_cannot_reinstall() {
717 let storage = temp_storage();
718 let source = storage.join("source");
719 write_minimal_package(&source, "TestApp", "0.0.1");
720 install_package_atomic(&storage, &source, InstallPolicy::Development, None).unwrap();
721 revoke_package(&storage, "TestApp").unwrap();
722 let err = install_package_atomic(&storage, &source, InstallPolicy::Development, None)
723 .unwrap_err();
724 assert!(matches!(err, QappInstallError::PackageRevoked(_)));
725 let _ = fs::remove_dir_all(&storage);
726 }
727
728 #[test]
729 fn reconcile_discovers_flat_install() {
730 let storage = temp_storage();
731 write_minimal_package(
732 &active_package_dir(&storage, "LegacyApp"),
733 "LegacyApp",
734 "1.0.0",
735 );
736 let registry = reconcile_registry_with_disk(&storage).unwrap();
737 assert!(registry.packages.contains_key("LegacyApp"));
738 let _ = fs::remove_dir_all(&storage);
739 }
740
741 #[test]
742 fn uninstall_package_removes_entry_and_files() {
743 let storage = temp_storage();
744 let source = storage.join("source");
745 write_minimal_package(&source, "TestApp", "0.0.1");
746
747 install_package_atomic(&storage, &source, InstallPolicy::Development, None).unwrap();
748 assert!(active_package_dir(&storage, "TestApp").is_dir());
749
750 uninstall_package(&storage, "TestApp", false).unwrap();
751 assert!(!active_package_dir(&storage, "TestApp").exists());
752
753 let registry = load_install_registry(&storage).unwrap();
754 assert!(!registry.packages.contains_key("TestApp"));
755 let _ = fs::remove_dir_all(&storage);
756 }
757}