leptoskit_codepush 0.3.0

Code push releases, manifests, binary deltas, and update protocol for wasm app bundles.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
//! Durable native bundle selection. A downloaded release is a trial until the
//! host confirms its first attached frame. Use one owner on a serialized worker
//! per directory; no UI/interpreter pointer belongs on that worker.
//!
//! An [`UpdateConfiguration`] with a `provenance` policy also requires [source
//! approvals](crate::provenance): a release is staged only with enough of
//! them, they are stored next to it, and they are verified again every time
//! the release is loaded, so a release whose stored approvals no longer
//! verify never launches. The store-shipped baseline is part of the installed
//! host, trusted through its store distribution like the policy itself, and
//! needs no approvals. Only the registry's approvals file counts; a file in
//! the bundle, whatever its name, is just a bundle file.

mod ownership;

use std::fs;
use std::path::Path;
use std::path::PathBuf;

use semver::Version;
use serde::Deserialize;
use serde::Serialize;

use crate::BundleManifest;
use crate::CodePushClient;
use crate::CodePushError;
use crate::ReleaseSignature;
use crate::Transport;
use crate::TrustedKeys;
use crate::UpdatePlan;
use crate::durable::is_temporary;
use crate::durable::sync_directory;
use crate::durable::write_atomically;
use crate::manifest::Container;
use crate::provenance::MAX_APPROVALS_BYTES;
use crate::provenance::ProvenanceConfiguration;
use crate::provenance::ProvenancePolicy;
use crate::provenance::ReleaseApprovals;
use crate::read_container;

/// Maximum HTTP response and decompressed native bundle size (32 MiB).
pub const MAX_BUNDLE_BYTES: u64 = crate::manifest::MAX_CONTAINER_BYTES;

/// The approvals stored next to an installed release, under a provenance
/// policy. It lives outside the bundle's files, which are never consulted.
const APPROVALS_FILE: &str = "approvals.json";

/// Authenticated native requirements in the bundle's `runtime.json`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RuntimeContract {
	/// Native guest ABI revision.
	pub abi: u32,
	/// Shell compatibility identity, changed when native capabilities change.
	pub shell: String,
	/// Required plugin names; the host may support additional plugins.
	pub plugins: Vec<String>,
}

/// Store-shell configuration. Downloaded code cannot replace these trust pins.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UpdateConfiguration {
	/// Whether registry access is enabled.
	pub enabled: bool,
	/// Expected app identity.
	pub app: String,
	/// Expected release channel.
	pub channel: String,
	/// Registry base URL.
	pub server: String,
	/// Trusted ed25519 public keys, hex encoded.
	pub public_keys: Vec<String>,
	/// ABI, shell identity, and plugins supported by the store shell.
	pub runtime: RuntimeContract,
	/// Explicit development-only permission to use cleartext HTTP.
	pub allow_http: bool,
	/// Independent source approvals every downloaded release must carry. When
	/// absent, a publisher signature is enough. The store-shipped baseline
	/// never needs approvals.
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub provenance: Option<ProvenanceConfiguration>,
}

/// Executable bytes and a generation-bound activation receipt.
#[derive(Debug)]
pub struct LaunchBundle {
	/// The manifest's verified entry module.
	pub wasm: Vec<u8>,
	/// Identity returned to the native worker for confirmation/rejection.
	pub metadata: LaunchMetadata,
}

/// Metadata is separate from Wasm bytes across native FFI boundaries.
#[derive(Debug, Clone, Serialize)]
pub struct LaunchMetadata {
	/// Opaque receipt; callbacks from older launches cannot confirm a new one.
	pub receipt: String,
	/// Selected release version.
	pub version: Version,
	/// Selected release build.
	pub build: u64,
	/// True until this downloaded release receives its first healthy frame.
	pub candidate: bool,
}

/// Result of checking and staging, without activating the guest.
#[derive(Debug, Clone, Serialize)]
pub struct UpdateReport {
	/// Whether a compatible update is ready to launch.
	pub status: UpdateStatus,
	/// Current or staged release version.
	pub version: Version,
	/// Current or staged release build.
	pub build: u64,
}

/// Serialized as `current` or `staged` for both mobile hosts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UpdateStatus {
	/// No newer usable release is staged.
	Current,
	/// A verified candidate is ready for explicit activation.
	Staged,
}

/// How many rejected releases to remember. A registry only re-offers its
/// newest release, so only recency matters, and the oldest remembered
/// rejection names a release the device will never be offered again.
const MAX_REJECTED: usize = 64;

/// The version floor's file, kept apart from `state.json` and the releases so
/// that losing either never lowers it.
const FLOOR_FILE: &str = "floor.json";

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct State {
	format: u32,
	embedded: String,
	confirmed: Option<String>,
	candidate: Option<Candidate>,
	generation: u64,
	rejected: Vec<String>,
	launch: Option<Receipt>,
	/// A copy of `floor.json`, so damage to either file keeps the floor.
	#[serde(default)]
	floor: Option<Floor>,
}

/// The newest release ever confirmed on this store build, or the store
/// baseline. Nothing at or below it is installed, even when the confirmed
/// release can no longer be read: an older release stays validly signed
/// forever, so a stale or hostile index could otherwise roll the device back.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Floor {
	format: u32,
	/// The store baseline it applies to. A new store build ships its own
	/// baseline and starts a new floor.
	embedded: String,
	version: Version,
	build: u64,
}

impl Floor {
	fn of(manifest: &BundleManifest, embedded: &str) -> Self {
		Self {
			format: 1,
			embedded: embedded.to_owned(),
			version: manifest.version.clone(),
			build: manifest.build,
		}
	}

	fn order(&self) -> (&Version, u64) {
		(&self.version, self.build)
	}
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
enum Candidate {
	Ready { release: String },
	Trying { release: String },
}

impl Candidate {
	fn release(&self) -> &str {
		match self {
			Self::Ready { release } | Self::Trying { release } => release,
		}
	}
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Receipt {
	id: String,
	release: Option<String>,
	resolution: Resolution,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum Resolution {
	Pending,
	Confirmed,
	Rejected,
}

/// Owns durable selection and authenticated offline releases. Methods block;
/// callers must keep this owner on their serialized background worker.
/// A lifetime file lock prevents other owners from opening the same directory.
pub struct InstalledBundles {
	directory: PathBuf,
	embedded: Vec<u8>,
	config: UpdateConfiguration,
	keys: Option<TrustedKeys>,
	provenance: Option<ProvenancePolicy>,
	state: State,
	floor: Floor,
	recovery: Option<String>,
	// The old native screen remains alive until the confirmation result
	// returns. Permit that one live handoff to reject even if its disk commit
	// won the race.
	just_confirmed: Option<(String, Option<String>)>,
	_directory_lock: fs::File,
}

impl InstalledBundles {
	/// Opens installed state, rejects interrupted trials, and revalidates
	/// stored artifacts. Corrupt/incompatible installed state recovers to the
	/// trusted store baseline and exposes a diagnostic through
	/// `recovery_diagnostic`.
	///
	/// Returns an error if another owner holds this directory. Drop that owner
	/// before retrying; a failed open never recovers or prunes its live state.
	pub fn open(
		directory: &Path,
		embedded: &[u8],
		config: UpdateConfiguration,
	) -> Result<Self, CodePushError> {
		let keys = if config.enabled || !config.public_keys.is_empty() {
			Some(TrustedKeys::from_hex(&config.public_keys)?)
		} else {
			None
		};
		let provenance = provenance_policy(&config, keys.as_ref())?;

		let baseline = validate_container(embedded, &config)?;
		let baseline_hash = baseline.manifest.bundle_hash();
		let directory_lock = ownership::acquire(directory)?;
		fs::create_dir_all(directory.join("releases"))?;
		let initial = || {
			State {
				format: 1,
				embedded: baseline_hash.clone(),
				confirmed: None,
				candidate: None,
				generation: 0,
				rejected: Vec::new(),
				launch: None,
				floor: None,
			}
		};
		let mut recovery = None;

		let state = match fs::read(directory.join("state.json")) {
			Ok(bytes) => {
				match serde_json::from_slice::<State>(&bytes) {
					Ok(state) if state.format == 1 => state,
					parsed => {
						recovery =
							Some(format!("discarded invalid installed selector: {parsed:?}"));
						initial()
					}
				}
			}

			Err(error) if error.kind() == std::io::ErrorKind::NotFound => initial(),
			Err(error) => return Err(error.into()),
		};

		// A floor that can't be read is unknown, not absent: opening fails
		// rather than accept a release below it. A damaged one falls back to
		// the copy in the selector and the confirmed release.
		let stored_floor = match fs::read(directory.join(FLOOR_FILE)) {
			Ok(bytes) => {
				match serde_json::from_slice::<Floor>(&bytes) {
					Ok(floor) if floor.format == 1 => Some(floor),
					parsed => {
						recovery = Some(format!("discarded invalid version floor: {parsed:?}"));
						None
					}
				}
			}

			Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
			Err(error) => return Err(error.into()),
		};
		// Floors recorded for another store build no longer apply.
		let recorded: Vec<Floor> = stored_floor
			.iter()
			.chain(&state.floor)
			.filter(|floor| floor.embedded == baseline_hash)
			.cloned()
			.collect();

		let mut installed = Self {
			directory: directory.to_owned(),
			embedded: embedded.to_vec(),
			config,
			keys,
			provenance,
			state,
			floor: Floor::of(&baseline.manifest, &baseline_hash),
			recovery,
			just_confirmed: None,
			_directory_lock: directory_lock,
		};
		// A new store build is the newest trusted code even when it keeps the
		// app version: downloads made for the previous build no longer apply.
		if installed.state.embedded != baseline_hash {
			installed.state.confirmed = None;
			installed.state.candidate = None;
			installed.state.launch = None;
			// The new build may support releases the previous one could not
			// run; one that still fails is rejected again.
			installed.state.rejected.clear();
		}

		installed.recover(&baseline.manifest, recorded);
		installed.state.embedded = baseline_hash;

		if stored_floor.as_ref() != Some(&installed.floor) {
			installed.write_floor()?;
		}

		installed.persist()?;
		installed.prune()?;

		Ok(installed)
	}

	/// Last recovery reason, retained for host status/logging after
	/// open/launch.
	pub fn recovery_diagnostic(&self) -> Option<&str> {
		self.recovery.as_deref()
	}

	/// Revalidates executable identity and durably marks a trial before handing
	/// bytes to the host. Starting another launch abandons an unconfirmed
	/// trial.
	///
	/// `open` and `sync_with` already ordered the candidate above the
	/// confirmed release and that above the store baseline, so only the release
	/// that runs is read, verified, and decompressed again. If it is damaged,
	/// the next one down runs instead.
	pub fn launch(&mut self) -> Result<LaunchBundle, CodePushError> {
		self.just_confirmed = None;

		if let Some(Candidate::Trying { release }) = self.state.candidate.clone() {
			self.recovery = Some("unconfirmed trial recovered to working release".to_owned());
			self.reject_release(release);
		}

		let (release, parsed) = loop {
			let release = self
				.state
				.candidate
				.as_ref()
				.map(|candidate| candidate.release().to_owned())
				.or_else(|| self.state.confirmed.clone());
			// The store baseline was verified at `open`; only stored releases
			// can have been damaged since.
			match (self.load(release.as_deref()), release) {
				(Err(error), Some(damaged)) => self.forget_damaged(&damaged, &error),
				(loaded, release) => break (release, loaded?.1),
			}
		};

		let candidate = self.state.candidate.is_some();

		let wasm = entry_of(&parsed)?.to_vec();
		self.state.generation = self
			.state
			.generation
			.checked_add(1)
			.ok_or_else(|| activation("launch generation exhausted"))?;
		let receipt = format!(
			"{}:{}:{}",
			self.state.embedded,
			self.state.generation,
			parsed.manifest.bundle_hash()
		);
		self.state.launch = Some(Receipt {
			id: receipt.clone(),
			release: release.clone(),
			resolution: Resolution::Pending,
		});

		if candidate {
			self.state.candidate = release.map(|release| Candidate::Trying { release });
		}

		self.persist()?;

		Ok(LaunchBundle {
			wasm,
			metadata: LaunchMetadata {
				receipt,
				version: parsed.manifest.version,
				build: parsed.manifest.build,
				candidate,
			},
		})
	}

	/// Promotes only this generation after native first-frame success.
	pub fn confirm(&mut self, receipt: &str) -> Result<(), CodePushError> {
		let launch = self.receipt(receipt, Resolution::Confirmed)?;

		if launch.resolution == Resolution::Confirmed {
			return Ok(());
		}

		let (_, parsed) = self.load(launch.release.as_deref())?;
		let release = launch.release.clone();
		let confirms_trial = self.state.candidate.as_ref().is_some_and(|candidate| {
			matches!(candidate, Candidate::Trying { .. })
				&& release.as_deref() == Some(candidate.release())
		});

		if confirms_trial {
			// Raised before the selection, so a crash in between leaves a
			// floor that is too high, never one that is too low.
			self.raise_floor(&parsed.manifest)?;
			self.just_confirmed = Some((receipt.to_owned(), self.state.confirmed.clone()));
			self.state.confirmed = release;
			self.state.candidate = None;
		}

		self.state
			.launch
			.as_mut()
			.expect("receipt checked")
			.resolution = Resolution::Confirmed;
		self.persist()
	}

	/// Rejects a failed trial while preserving the last working release. The
	/// caller then invokes `launch` to obtain the verified fallback.
	pub fn reject(&mut self, receipt: &str) -> Result<(), CodePushError> {
		if self
			.just_confirmed
			.as_ref()
			.is_some_and(|(id, _)| id == receipt)
		{
			let launch = self.receipt(receipt, Resolution::Confirmed)?;
			let release = launch
				.release
				.clone()
				.ok_or_else(|| activation("confirmed trial has no release"))?;
			let (_, previous) = self
				.just_confirmed
				.take()
				.expect("matching live confirmation");
			self.state.confirmed = previous;
			self.reject_release(release);
			self.state
				.launch
				.as_mut()
				.expect("receipt checked")
				.resolution = Resolution::Rejected;

			return self.persist();
		}

		let launch = self.receipt(receipt, Resolution::Rejected)?;

		if launch.resolution == Resolution::Rejected {
			return Ok(());
		}

		let release = launch.release.clone();
		let is_trial = self
			.state
			.candidate
			.as_ref()
			.is_some_and(|candidate| release.as_deref() == Some(candidate.release()));

		if !is_trial {
			return Err(activation(
				"the working baseline failed; no earlier trial to recover",
			));
		}

		if let Some(release) = release {
			self.reject_release(release);
		}

		self.state
			.launch
			.as_mut()
			.expect("receipt checked")
			.resolution = Resolution::Rejected;
		self.persist()
	}

	/// Checks through the bounded HTTPS transport. Run exclusively off the UI
	/// thread. Disabled configurations never contact the registry.
	#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
	pub fn sync(&mut self) -> Result<UpdateReport, CodePushError> {
		let mut transport = HttpTransport::new(self.config.allow_http);
		self.sync_with(&mut transport)
	}

	/// Checks via an injected transport, sharing all trust and activation
	/// rules. Downloads remain candidates until explicitly launched and
	/// confirmed.
	///
	/// A release that failed activation on this device is never downloaded
	/// again: while the registry still offers it, the check reports the
	/// working release as current, having fetched only the channel index.
	pub fn sync_with(
		&mut self,
		transport: &mut impl Transport,
	) -> Result<UpdateReport, CodePushError> {
		self.just_confirmed = None;

		if let Some(Candidate::Ready { release }) = &self.state.candidate {
			let (_, parsed) = self.load(Some(release))?;

			return Ok(report(UpdateStatus::Staged, parsed.manifest));
		}

		let (current_bytes, current) = self.load(self.state.confirmed.as_deref())?;

		if !self.config.enabled {
			return Ok(report(UpdateStatus::Current, current.manifest));
		}

		if matches!(self.state.candidate, Some(Candidate::Trying { .. })) {
			return Err(activation(
				"confirm or reject the outstanding trial before checking",
			));
		}

		self.prune()?;

		let keys = self
			.keys
			.clone()
			.ok_or_else(|| activation("no update trust keys"))?;
		let mut client = CodePushClient::new(
			transport,
			&self.config.server,
			&self.config.app,
			&self.config.channel,
			current.manifest.version.clone(),
			current.manifest.build,
			current_bytes,
			keys,
		)
		.with_max_container_bytes(MAX_BUNDLE_BYTES);

		if let Some(policy) = &self.provenance {
			client = client.with_provenance(policy.clone());
		}

		let UpdatePlan::Available(offer) = client.check()? else {
			return Ok(report(UpdateStatus::Current, current.manifest));
		};
		// The client compared the offer with the release that runs, which is
		// the store baseline when the confirmed release couldn't be read.
		if release_order(&offer.manifest) <= self.floor.order() {
			return Ok(report(UpdateStatus::Current, current.manifest));
		}
		// The container must carry exactly the offered manifest, so its hash
		// is the release's identifier before a byte of it is downloaded.
		if self.state.rejected.contains(&offer.manifest.bundle_hash()) {
			return Ok(report(UpdateStatus::Current, current.manifest));
		}

		let offered = offer.manifest.bundle_hash();
		let download = client.download_offer(*offer)?;
		let parsed = match validate_container(&download.container, &self.config) {
			Ok(parsed) => parsed,
			Err(error) => {
				// The signed container fails the same way on every check, and
				// would be downloaded again each time while it stays the
				// channel's newest release.
				self.reject_release(offered);
				self.persist()?;
				return Err(error);
			}
		};
		let id = parsed.manifest.bundle_hash();

		let release_dir = self.release_directory(&id)?;
		fs::create_dir_all(&release_dir)?;
		write_atomically(&release_dir.join("release.lkb"), &download.container)?;
		write_atomically(
			&release_dir.join("release.sig"),
			&serde_json::to_vec(&download.signature)?,
		)?;

		if let Some(approvals) = &download.approvals {
			write_atomically(&release_dir.join(APPROVALS_FILE), &approvals.to_vec()?)?;
		}

		sync_directory(&self.directory.join("releases"))?;
		self.state.candidate = Some(Candidate::Ready { release: id });
		self.persist()?;

		Ok(report(UpdateStatus::Staged, parsed.manifest))
	}

	fn receipt(&self, id: &str, resolution: Resolution) -> Result<&Receipt, CodePushError> {
		let receipt = self
			.state
			.launch
			.as_ref()
			.filter(|launch| launch.id == id)
			.ok_or_else(|| activation("stale launch receipt"))?;

		if receipt.resolution != Resolution::Pending && receipt.resolution != resolution {
			return Err(activation("launch receipt already resolved differently"));
		}

		Ok(receipt)
	}

	fn reject_release(&mut self, release: String) {
		if !self.state.rejected.contains(&release) {
			// The list is bounded: state a publisher cannot shrink is state
			// a device carries forever, and the oldest entry is the one the
			// registry can no longer offer.
			if self.state.rejected.len() >= MAX_REJECTED {
				self.state.rejected.remove(0);
			}

			self.state.rejected.push(release);
		}

		self.state.candidate = None;
	}

	/// Drops a stored release that failed verification at launch: a damaged
	/// candidate is rejected, a damaged confirmed release falls back to the
	/// store baseline.
	fn forget_damaged(&mut self, release: &str, error: &CodePushError) {
		self.recovery = Some(format!("installed release rejected: {error}"));
		let is_candidate = self
			.state
			.candidate
			.as_ref()
			.is_some_and(|candidate| candidate.release() == release);

		if is_candidate {
			self.reject_release(release.to_owned());
		} else {
			self.state.confirmed = None;
		}
	}

	/// Selects the releases to run and the version floor: the highest of the
	/// `recorded` floors, the confirmed release, and the store baseline.
	fn recover(&mut self, baseline: &BundleManifest, recorded: Vec<Floor>) {
		if let Some(Candidate::Trying { release }) = self.state.candidate.clone() {
			self.recovery = Some("unconfirmed trial recovered to working release".to_owned());
			self.reject_release(release);
			self.state.launch = None;
		}

		// The release a candidate must beat; each stored release is read once.
		let mut working = baseline.clone();

		if let Some(id) = self.state.confirmed.clone() {
			match self.load(Some(&id)) {
				Ok((_, parsed)) if release_order(&parsed.manifest) > release_order(baseline) => {
					working = parsed.manifest;
				}

				Ok(_) => {
					self.state.confirmed = None;
					self.state.launch = None;
				}
				Err(error) => {
					self.recovery = Some(format!("installed release rejected: {error}"));
					self.state.confirmed = None;
					self.state.launch = None;
				}
			}
		}

		// The confirmed release may have failed to read for a reason that
		// passes, so it never lowers the floor.
		self.floor = Floor::of(&working, &self.floor.embedded);

		for floor in recorded {
			if floor.order() > self.floor.order() {
				self.floor = floor;
			}
		}

		self.state.floor = Some(self.floor.clone());

		if let Some(candidate) = self.state.candidate.clone() {
			match self.load(Some(candidate.release())) {
				Ok((_, parsed)) if release_order(&parsed.manifest) > self.floor.order() => {}
				Ok(_) => self.state.candidate = None,
				Err(error) => {
					self.recovery = Some(format!("staged release rejected: {error}"));
					self.reject_release(candidate.release().to_owned());
				}
			}
		}
	}

	fn release_directory(&self, id: &str) -> Result<PathBuf, CodePushError> {
		if id.len() != 64 || !id.bytes().all(|byte| byte.is_ascii_hexdigit()) {
			return Err(activation("invalid installed release identifier"));
		}

		Ok(self.directory.join("releases").join(id))
	}

	fn load(&self, id: Option<&str>) -> Result<(Vec<u8>, Container), CodePushError> {
		let Some(id) = id else {
			return Ok((
				self.embedded.clone(),
				validate_container(&self.embedded, &self.config)?,
			));
		};
		let directory = self.release_directory(id)?;
		let bytes = fs::read(directory.join("release.lkb"))?;
		let parsed = validate_container(&bytes, &self.config)?;
		let signature: ReleaseSignature =
			serde_json::from_slice(&fs::read(directory.join("release.sig"))?)?;
		self.keys
			.as_ref()
			.ok_or_else(|| activation("installed release has no trusted key"))?
			.verify(&parsed.manifest, Some(&signature))?;

		if parsed.manifest.bundle_hash() != id {
			return Err(activation(
				"installed release identifier does not match signed container",
			));
		}

		if let Some(policy) = &self.provenance {
			let approvals = ReleaseApprovals::from_slice(&read_bounded(
				&directory.join(APPROVALS_FILE),
				MAX_APPROVALS_BYTES,
			)?)?;
			policy.verify(&parsed.manifest, &approvals.approvals)?;
		}

		Ok((bytes, parsed))
	}

	/// Removes stored releases that can never run again: everything except the
	/// confirmed release and the staged or trying candidate. Callers run it
	/// only when no live rollback still needs the previously confirmed release.
	///
	/// Also removes the temporary files of selector writes a crash
	/// interrupted. This owner is the directory's only writer, so none of
	/// them is still being written.
	fn prune(&self) -> Result<(), CodePushError> {
		for entry in fs::read_dir(&self.directory)? {
			let entry = entry?;
			let interrupted = entry.file_name().to_str().is_some_and(is_temporary);

			if interrupted && entry.file_type()?.is_file() {
				fs::remove_file(entry.path())?;
			}
		}

		let keep = [
			self.state.confirmed.as_deref(),
			self.state.candidate.as_ref().map(Candidate::release),
		];

		for entry in fs::read_dir(self.directory.join("releases"))? {
			let entry = entry?;

			if keep.contains(&entry.file_name().to_str()) {
				continue;
			}

			if entry.file_type()?.is_dir() {
				fs::remove_dir_all(entry.path())?;
			} else {
				fs::remove_file(entry.path())?;
			}
		}

		Ok(())
	}

	/// Raises the floor to `manifest` if it is newer; the floor never falls on
	/// the same store build.
	fn raise_floor(&mut self, manifest: &BundleManifest) -> Result<(), CodePushError> {
		if release_order(manifest) <= self.floor.order() {
			return Ok(());
		}

		let raised = Floor::of(manifest, &self.floor.embedded);
		let previous = std::mem::replace(&mut self.floor, raised);

		if let Err(error) = self.write_floor() {
			self.floor = previous;
			return Err(error);
		}

		self.state.floor = Some(self.floor.clone());
		Ok(())
	}

	fn write_floor(&self) -> Result<(), CodePushError> {
		write_atomically(
			&self.directory.join(FLOOR_FILE),
			&serde_json::to_vec(&self.floor)?,
		)?;
		Ok(())
	}

	fn persist(&self) -> Result<(), CodePushError> {
		write_atomically(
			&self.directory.join("state.json"),
			&serde_json::to_vec(&self.state)?,
		)?;
		Ok(())
	}
}

/// Reads at most `limit + 1` bytes of `path`, so an oversized file is
/// refused by its parser rather than read whole.
fn read_bounded(path: &Path, limit: u64) -> Result<Vec<u8>, CodePushError> {
	use std::io::Read;

	let mut bytes = Vec::new();
	fs::File::open(path)?
		.take(limit.saturating_add(1))
		.read_to_end(&mut bytes)?;
	Ok(bytes)
}

/// The configuration's provenance policy. Approvers are a second trust
/// root, so a key that is also a publisher key, which could approve its own
/// releases, is refused.
fn provenance_policy(
	config: &UpdateConfiguration,
	publishers: Option<&TrustedKeys>,
) -> Result<Option<ProvenancePolicy>, CodePushError> {
	let Some(configuration) = &config.provenance else {
		return Ok(None);
	};
	let policy = ProvenancePolicy::from_configuration(configuration)?;
	let shared = publishers.and_then(|publishers| {
		policy
			.approvers()
			.iter()
			.find(|key| publishers.contains(key))
	});

	if let Some(shared) = shared {
		return Err(CodePushError::InvalidProvenance(format!(
			"{} is both a publisher key and an approver key",
			shared.to_hex()
		)));
	}

	Ok(Some(policy))
}

fn release_order(manifest: &BundleManifest) -> (&Version, u64) {
	(&manifest.version, manifest.build)
}

fn report(status: UpdateStatus, manifest: BundleManifest) -> UpdateReport {
	UpdateReport {
		status,
		version: manifest.version,
		build: manifest.build,
	}
}

fn activation(message: impl Into<String>) -> CodePushError {
	CodePushError::Activation(message.into())
}

/// The verified entry module of a trusted store-shipped container, for a host
/// that runs it without the update store: updates are disabled, or the store
/// cannot open. Every file hash is checked and the same size bounds apply.
pub fn entry_module(container: &[u8]) -> Result<Vec<u8>, CodePushError> {
	let parsed = parse_bounded(container)?;
	Ok(entry_of(&parsed)?.to_vec())
}

/// Parses a container after checking its size and declared expansion, so a
/// hostile manifest cannot make the parser allocate past the native bound.
fn parse_bounded(bytes: &[u8]) -> Result<Container, CodePushError> {
	if bytes.len() as u64 > MAX_BUNDLE_BYTES {
		return Err(activation("container exceeds 32 MiB"));
	}

	// Inspect declared expansion before the shared parser allocates file
	// contents.
	let (manifest, _) = crate::manifest::container_manifest(bytes)?;
	let total = manifest
		.files
		.iter()
		.try_fold(0_u64, |sum, file| sum.checked_add(file.size));

	if total.is_none_or(|size| size > MAX_BUNDLE_BYTES) {
		return Err(activation("expanded bundle exceeds 32 MiB"));
	}

	read_container(bytes)
}

/// The bundle's entry module, which must be WebAssembly version 1.
fn entry_of(parsed: &Container) -> Result<&[u8], CodePushError> {
	let entry = parsed
		.files
		.iter()
		.find(|(path, _)| path == &parsed.manifest.entry)
		.ok_or_else(|| activation("bundle entry is missing"))?;

	if !entry.1.starts_with(b"\0asm\x01\0\0\0") {
		return Err(activation(
			"bundle entry is not a WebAssembly version 1 module",
		));
	}

	Ok(&entry.1)
}

fn validate_container(
	bytes: &[u8],
	config: &UpdateConfiguration,
) -> Result<Container, CodePushError> {
	let parsed = parse_bounded(bytes)?;

	if parsed.manifest.app != config.app || parsed.manifest.channel != config.channel {
		return Err(CodePushError::WrongTarget {
			tracked: format!("{}/{}", config.app, config.channel),
			offered: format!("{}/{}", parsed.manifest.app, parsed.manifest.channel),
		});
	}

	let descriptor = parsed
		.files
		.iter()
		.find(|(path, _)| path == "runtime.json")
		.ok_or_else(|| activation("native bundle is missing runtime.json"))?;
	let runtime: RuntimeContract = serde_json::from_slice(&descriptor.1)?;

	if runtime.abi != config.runtime.abi
		|| runtime.shell != config.runtime.shell
		|| runtime
			.plugins
			.iter()
			.any(|plugin| !config.runtime.plugins.contains(plugin))
	{
		return Err(activation(
			"bundle requires an incompatible native ABI, shell, or plugin",
		));
	}

	entry_of(&parsed)?;
	Ok(parsed)
}

/// Blocking HTTP transport with no redirects and bodies capped at
/// [`MAX_BUNDLE_BYTES`]. Connecting has 15 s and the response head 30 s; a
/// whole request, body included, has 10 minutes. A 404 is
/// [`CodePushError::NotFound`], which a static registry uses for "no release
/// yet". HTTPS is required unless development opts in.
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
pub struct HttpTransport {
	agent: ureq::Agent,
	allow_http: bool,
}

#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
impl HttpTransport {
	/// Builds a transport for a serialized background worker.
	pub fn new(allow_http: bool) -> Self {
		let config = ureq::Agent::config_builder()
			.max_redirects(0)
			// Status codes are classified below: a 404 is how a static registry
			// says a channel has no release (or a delta does not exist).
			.http_status_as_error(false)
			// Fail fast on an unreachable registry, but give a large bundle on a
			// slow link time to arrive. The overall bound keeps the worker free
			// for the next request.
			.timeout_connect(Some(std::time::Duration::from_secs(15)))
			.timeout_recv_response(Some(std::time::Duration::from_secs(30)))
			.timeout_global(Some(std::time::Duration::from_mins(10)))
			.build();
		Self {
			agent: config.into(),
			allow_http,
		}
	}
}

#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
impl Transport for HttpTransport {
	fn fetch(&mut self, url: &str) -> Result<Vec<u8>, CodePushError> {
		self.fetch_within(url, MAX_BUNDLE_BYTES)
	}

	fn fetch_within(&mut self, url: &str, max_bytes: u64) -> Result<Vec<u8>, CodePushError> {
		let secure = url.starts_with("https://");
		let development = self.allow_http && url.starts_with("http://");

		if !(secure || development) {
			return Err(CodePushError::Transport(
				"HTTPS is required; enable allow_http only for development".to_owned(),
			));
		}

		let mut response = self
			.agent
			.get(url)
			.call()
			.map_err(|error| CodePushError::Transport(error.to_string()))?;

		let status = response.status();

		if status == ureq::http::StatusCode::NOT_FOUND {
			return Err(CodePushError::NotFound(url.to_owned()));
		}

		if !status.is_success() {
			return Err(CodePushError::Transport(format!("HTTP {status}")));
		}

		response
			.body_mut()
			.with_config()
			.limit(max_bytes.min(MAX_BUNDLE_BYTES))
			.read_to_vec()
			.map_err(|error| CodePushError::Transport(error.to_string()))
	}
}