1use std::collections::hash_map::DefaultHasher;
9use std::hash::{Hash, Hasher};
10
11const INTEGRITY_SEED: &str = "lean-ctx";
12const ORIGIN_REPO: &str = env!("CARGO_PKG_REPOSITORY");
13const ORIGIN_NAME: &str = env!("CARGO_PKG_NAME");
14const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
15
16fn compute_seed_hash(seed: &str) -> u64 {
17 let mut hasher = DefaultHasher::new();
18 seed.hash(&mut hasher);
19 hasher.finish()
20}
21
22fn expected_hash() -> u64 {
23 compute_seed_hash("lean-ctx")
24}
25
26pub(crate) fn verify_integrity() -> bool {
27 compute_seed_hash(INTEGRITY_SEED) == expected_hash()
28}
29
30pub(crate) fn is_official_origin() -> bool {
31 ORIGIN_REPO.contains("yvgude/lean-ctx") && ORIGIN_NAME == "lean-ctx-engine"
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct BuildInfo {
40 pub kind: &'static str,
41 pub commit: &'static str,
43 pub dirty: bool,
45}
46
47const SHORT_COMMIT: usize = 10;
49
50impl BuildInfo {
51 pub fn short_commit(&self) -> &'static str {
52 self.commit.get(..SHORT_COMMIT).unwrap_or(self.commit)
53 }
54
55 pub fn is_official(&self) -> bool {
56 self.kind == "official"
57 }
58
59 pub fn label(&self) -> String {
61 if self.is_official() {
62 return "official".to_owned();
63 }
64 let mut label = self.kind.to_owned();
65 if !self.commit.is_empty() {
66 label.push(' ');
67 label.push_str(self.short_commit());
68 }
69 if self.dirty {
70 label.push_str(", dirty");
71 }
72 label
73 }
74
75 pub fn to_json(&self) -> serde_json::Value {
78 serde_json::json!({
79 "kind": self.kind,
80 "commit": (!self.commit.is_empty()).then_some(self.commit),
81 "dirty": self.dirty,
82 "official": self.is_official(),
83 })
84 }
85}
86
87const ENGINE_BUILD: BuildInfo = BuildInfo {
91 kind: env!("LEANCTX_BUILD_KIND"),
92 commit: env!("LEANCTX_BUILD_COMMIT"),
93 dirty: matches!(env!("LEANCTX_BUILD_DIRTY").as_bytes(), b"1"),
94};
95
96static BINARY_STAMP: std::sync::OnceLock<(&'static str, bool, bool)> = std::sync::OnceLock::new();
99
100pub fn set_binary_stamp(commit: &'static str, dirty: bool, dogfood: bool) {
107 if !commit.is_empty() {
108 let _ = BINARY_STAMP.set((commit, dirty, dogfood));
109 }
110}
111
112pub fn build() -> BuildInfo {
115 combine(ENGINE_BUILD, BINARY_STAMP.get().copied())
116}
117
118fn combine(engine: BuildInfo, stamp: Option<(&'static str, bool, bool)>) -> BuildInfo {
119 match stamp {
120 Some((commit, dirty, dogfood)) if !engine.is_official() => BuildInfo {
121 kind: if dogfood && engine.kind == "dev" {
122 "dogfood"
123 } else {
124 engine.kind
125 },
126 commit,
127 dirty,
128 },
129 _ => engine,
130 }
131}
132
133pub struct IntegrityReport {
134 pub seed_ok: bool,
135 pub origin_ok: bool,
136 pub repo: &'static str,
137 pub pkg_name: &'static str,
138 pub version: &'static str,
139 pub build: BuildInfo,
140}
141
142pub fn check() -> IntegrityReport {
143 IntegrityReport {
144 seed_ok: verify_integrity(),
145 origin_ok: is_official_origin(),
146 repo: ORIGIN_REPO,
147 pkg_name: ORIGIN_NAME,
148 version: PKG_VERSION,
149 build: build(),
150 }
151}
152
153pub fn version_json() -> serde_json::Value {
155 let report = check();
156 serde_json::json!({
157 "name": "lean-ctx",
158 "version": report.version,
159 "repository": report.repo,
160 "unmodified": report.seed_ok && report.origin_ok,
161 "build": report.build.to_json(),
162 })
163}
164
165pub fn origin_line() -> String {
166 let report = check();
167 if report.seed_ok && report.origin_ok && report.build.is_official() {
168 format!("lean-ctx {} (official, {})", report.version, report.repo)
169 } else if report.seed_ok && report.origin_ok {
170 format!("lean-ctx {} ({})", report.version, report.build.label())
171 } else {
172 format!(
173 "WARNING: Modified redistribution detected. \
174 Official builds: https://github.com/yvgude/lean-ctx \
175 (pkg={}, repo={})",
176 report.pkg_name, report.repo
177 )
178 }
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 #[test]
186 fn integrity_passes_in_official_build() {
187 assert!(verify_integrity());
188 }
189
190 #[test]
191 fn seed_hash_is_deterministic() {
192 let h1 = compute_seed_hash("lean-ctx");
193 let h2 = compute_seed_hash("lean-ctx");
194 assert_eq!(h1, h2);
195 }
196
197 #[test]
198 fn tampered_seed_fails() {
199 let tampered = compute_seed_hash("better-ctx");
200 assert_ne!(tampered, expected_hash());
201 }
202
203 #[test]
204 fn origin_is_official() {
205 assert!(is_official_origin());
206 }
207
208 #[test]
209 fn origin_line_contains_version() {
210 let line = origin_line();
211 assert!(line.contains(env!("CARGO_PKG_VERSION")));
212 }
213
214 #[test]
215 fn build_kind_labels_name_only_release_builds_official() {
216 let sha = "f78aff8dc5a1b2c3d4e5f60718293a4b5c6d7e8f";
217 let b = |kind, commit, dirty| BuildInfo {
218 kind,
219 commit,
220 dirty,
221 };
222 assert_eq!(b("official", sha, false).label(), "official");
223 assert_eq!(b("dogfood", sha, false).label(), "dogfood f78aff8dc5");
224 assert_eq!(b("dev", sha, true).label(), "dev f78aff8dc5, dirty");
225 assert_eq!(b("source", "", false).label(), "source");
226 assert_eq!(b("dev", sha, false).to_json()["official"], false);
227 assert_eq!(
228 b("source", "", false).to_json()["commit"],
229 serde_json::Value::Null
230 );
231
232 let this = build();
235 assert!(
236 matches!(this.kind, "official" | "dev" | "dogfood" | "source"),
237 "{this:?}"
238 );
239 assert!(
240 this.commit.is_empty() || this.commit.len() == 40,
241 "{this:?}"
242 );
243 assert_eq!(
244 origin_line().contains("(official,"),
245 this.is_official(),
246 "{}",
247 origin_line()
248 );
249 assert_eq!(version_json()["build"]["kind"], this.kind);
250 }
251
252 #[test]
253 fn binary_stamp_supplies_commit_and_dogfood_but_never_overrides_official() {
254 let sha = "f78aff8dc5a1b2c3d4e5f60718293a4b5c6d7e8f";
255 let rel = "0123456789abcdef0123456789abcdef01234567";
256 let engine = |kind, commit| BuildInfo {
257 kind,
258 commit,
259 dirty: false,
260 };
261 let dev = combine(engine("dev", ""), Some((sha, true, false)));
263 assert_eq!(dev.label(), "dev f78aff8dc5, dirty");
264 assert_eq!(
265 combine(engine("dev", ""), Some((sha, false, true))).label(),
266 "dogfood f78aff8dc5"
267 );
268 assert_eq!(
270 combine(engine("source", ""), Some((sha, false, true))).kind,
271 "source"
272 );
273 assert_eq!(combine(engine("dev", ""), None).label(), "dev");
275 let official = combine(engine("official", rel), Some((sha, true, true)));
276 assert_eq!((official.kind, official.commit), ("official", rel));
277 }
278}