offline-mcp 0.4.0

Model Context Protocol server exposing the Offline Protocol registry to AI agents
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
//! Read a project's native app identities from the files that define them, so
//! an agent does not have to ask a person: Expo `app.json` / `app.config.json`
//! (`ios.bundleIdentifier`, `ios.appleTeamId`, `android.package`), an Xcode
//! project (`PRODUCT_BUNDLE_IDENTIFIER`, `DEVELOPMENT_TEAM`), Gradle
//! (`applicationId`), Android App Links files (`assetlinks.json`, which list
//! the release and Play signing certificates) and the Android debug keystore
//! (its password is the public default `android`).
//!
//! Nothing secret is read: a release keystore needs its password, so it is
//! only read when the developer passes `--keystore` and puts the password in
//! `OFFLINE_KEYSTORE_PASSWORD`.

use std::path::{Path, PathBuf};

use serde::Serialize;
use serde_json::Value;

use super::native::{normalize_bundle_id, normalize_package, normalize_sha256, normalize_team_id};

#[derive(Debug, Clone, Default, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DetectedIos {
    pub bundle_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub team_id: Option<String>,
    pub source: String,
}

#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DetectedCert {
    pub sha256: String,
    /// `release` (App Links file, release keystore) or `debug` (debug keystore).
    pub kind: &'static str,
    pub source: String,
}

#[derive(Debug, Clone, Default, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DetectedAndroid {
    pub package: String,
    pub source: String,
    pub certificates: Vec<DetectedCert>,
}

/// An Expo app and what it still needs to attest.
#[derive(Debug, Clone, Default, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ExpoProject {
    /// The app's directory, relative to the scanned root (`.` for the root).
    pub dir: String,
    /// `app.json` or `app.config.json`.
    pub config: String,
    /// `@expo/app-integrity` is a dependency.
    pub has_app_integrity: bool,
    /// `ios.entitlements["com.apple.developer.devicecheck.appattest-environment"]` is set.
    pub has_app_attest_entitlement: bool,
    /// `@offline-protocol/id-react-native` is 0.4.0 or later (attests code requests).
    pub sdk_attests: bool,
    /// The `@offline-protocol/id-react-native` range in package.json, if any.
    pub sdk_range: Option<String>,
}

pub const APP_ATTEST_ENTITLEMENT: &str = "com.apple.developer.devicecheck.appattest-environment";

/// Whether a semver range or version (`^0.4.0`, `0.4.1`, `~0.5.0`) admits only
/// 0.4.0 or later of a 0.x package.
pub fn range_at_least_0_4(range: &str) -> bool {
    let v = range
        .trim()
        .trim_start_matches(['^', '~', '=', '>', 'v', ' ']);
    let mut parts = v.split(['.', '-']).map(|p| p.parse::<u64>().ok());
    match (parts.next().flatten(), parts.next().flatten()) {
        (Some(major), _) if major >= 1 => true,
        (Some(0), Some(minor)) => minor >= 4,
        _ => false,
    }
}

#[derive(Debug, Clone, Default, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Detected {
    pub ios: Vec<DetectedIos>,
    pub android: Vec<DetectedAndroid>,
    /// The first Expo app found, with what it needs for attestation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expo: Option<ExpoProject>,
    /// What could not be read, and what to do about it.
    pub notes: Vec<String>,
}

#[derive(Debug, Clone, Default)]
pub struct DetectOptions {
    /// A release keystore to read (`--keystore`), with `--keystore-alias`.
    pub keystore: Option<PathBuf>,
    pub keystore_alias: Option<String>,
    /// Read `~/.android/debug.keystore` too (the project's own
    /// `android/app/debug.keystore` is always read).
    pub home_debug_keystore: bool,
}

const SKIP_DIRS: &[&str] = &[
    "node_modules",
    ".git",
    "Pods",
    "build",
    "dist",
    ".expo",
    ".next",
    "target",
    "DerivedData",
];

/// Files named `name` under `root`, at most `depth` directories down,
/// skipping dependency and build folders.
fn find_files(root: &Path, name: &str, depth: usize) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let mut stack = vec![(root.to_path_buf(), 0usize)];
    while let Some((dir, d)) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        let mut entries: Vec<_> = entries.flatten().collect();
        entries.sort_by_key(|e| e.file_name());
        for entry in entries {
            let path = entry.path();
            let file_name = entry.file_name().to_string_lossy().to_string();
            if path.is_dir() {
                let wanted = file_name == ".well-known"
                    || (!SKIP_DIRS.contains(&file_name.as_str()) && !file_name.starts_with('.'));
                if d < depth && wanted {
                    stack.push((path, d + 1));
                }
            } else if file_name == name {
                out.push(path);
            }
        }
    }
    out.sort();
    out
}

fn rel(root: &Path, path: &Path) -> String {
    path.strip_prefix(root)
        .unwrap_or(path)
        .display()
        .to_string()
}

pub fn detect(root: &Path, opts: &DetectOptions) -> Detected {
    let mut found = Detected::default();
    expo_configs(root, &mut found);
    xcode_projects(root, &mut found);
    gradle_files(root, &mut found);
    asset_links(root, &mut found);
    debug_keystores(root, opts, &mut found);
    if let Some(keystore) = &opts.keystore {
        release_keystore(root, keystore, opts.keystore_alias.as_deref(), &mut found);
    }
    for app in &found.ios {
        if app.team_id.is_none() {
            found.notes.push(format!(
                "No Apple Team ID found for {}: add `ios.appleTeamId` to app.json, or pass --team-id (Apple Developer → Membership).",
                app.bundle_id
            ));
        }
    }
    for app in &found.android {
        if !app.certificates.iter().any(|c| c.kind == "release") {
            found.notes.push(format!(
                "No release signing certificate found for {}: copy the App signing key certificate SHA-256 from Play Console → App integrity → App signing (and the upload key's), or run `./gradlew signingReport`, then `offline apps native add android --package {} --sha256 <fingerprint>`.",
                app.package, app.package
            ));
        }
    }
    if found.ios.is_empty() && found.android.is_empty() {
        found.notes.push(
            "No native app found (looked for app.json / app.config.json, ios/*.xcodeproj, android/app/build.gradle). Pass --dir to point at the app.".into(),
        );
    }
    found
}

fn add_ios(found: &mut Detected, bundle: &str, team: Option<&str>, source: String) {
    let Some(bundle_id) = normalize_bundle_id(bundle) else {
        return;
    };
    let team_id = team.and_then(normalize_team_id);
    match found.ios.iter_mut().find(|a| a.bundle_id == bundle_id) {
        Some(existing) => {
            if existing.team_id.is_none() {
                existing.team_id = team_id;
            }
        }
        None => found.ios.push(DetectedIos {
            bundle_id,
            team_id,
            source,
        }),
    }
}

fn add_android(found: &mut Detected, package: &str, source: String) -> Option<usize> {
    let package = normalize_package(package)?;
    if let Some(i) = found.android.iter().position(|a| a.package == package) {
        return Some(i);
    }
    found.android.push(DetectedAndroid {
        package,
        source,
        certificates: Vec::new(),
    });
    Some(found.android.len() - 1)
}

fn add_cert(app: &mut DetectedAndroid, raw: &str, kind: &'static str, source: String) {
    if let Some(sha256) = normalize_sha256(raw) {
        if !app.certificates.iter().any(|c| c.sha256 == sha256) {
            app.certificates.push(DetectedCert {
                sha256,
                kind,
                source,
            });
        }
    }
}

fn expo_configs(root: &Path, found: &mut Detected) {
    for name in ["app.json", "app.config.json"] {
        for path in find_files(root, name, 4) {
            let Ok(text) = std::fs::read_to_string(&path) else {
                continue;
            };
            let Ok(json) = serde_json::from_str::<Value>(&text) else {
                continue;
            };
            let expo = json.get("expo").unwrap_or(&json);
            let source = rel(root, &path);
            if found.expo.is_none() && json.get("expo").is_some() {
                found.expo = Some(expo_project(root, &path, expo));
            }
            if let Some(bundle) = expo
                .pointer("/ios/bundleIdentifier")
                .and_then(Value::as_str)
            {
                let team = expo.pointer("/ios/appleTeamId").and_then(Value::as_str);
                add_ios(found, bundle, team, source.clone());
            }
            if let Some(package) = expo.pointer("/android/package").and_then(Value::as_str) {
                add_android(found, package, source);
            }
        }
    }
    let dynamic: Vec<PathBuf> = ["app.config.js", "app.config.ts"]
        .iter()
        .flat_map(|n| find_files(root, n, 4))
        .collect();
    if !dynamic.is_empty() && found.ios.is_empty() && found.android.is_empty() {
        found.notes.push(format!(
            "{} is code, which this command does not run: run `npx expo config --json` there and pass the bundle ID / package with `offline apps native add`.",
            rel(root, &dynamic[0])
        ));
    }
}

fn expo_project(root: &Path, config: &Path, expo: &Value) -> ExpoProject {
    let dir = config.parent().unwrap_or(root);
    let package: Value = std::fs::read_to_string(dir.join("package.json"))
        .ok()
        .and_then(|t| serde_json::from_str(&t).ok())
        .unwrap_or(Value::Null);
    let dep = |name: &str| {
        ["dependencies", "devDependencies"]
            .iter()
            .find_map(|k| package[*k][name].as_str().map(str::to_string))
    };
    let sdk_range = dep("@offline-protocol/id-react-native");
    let rel_dir = rel(root, dir);
    ExpoProject {
        dir: if rel_dir.is_empty() {
            ".".into()
        } else {
            rel_dir
        },
        config: rel(root, config),
        has_app_integrity: dep("@expo/app-integrity").is_some(),
        has_app_attest_entitlement: expo
            .pointer("/ios/entitlements")
            .and_then(|e| e.get(APP_ATTEST_ENTITLEMENT))
            .and_then(Value::as_str)
            .is_some(),
        sdk_attests: sdk_range.as_deref().is_some_and(range_at_least_0_4),
        sdk_range,
    }
}

/// What `offline apps native setup-project` changes and asks for.
#[derive(Debug, Clone, Default, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProjectSetup {
    pub config: Option<String>,
    /// Edits made (or, without `write`, that would be made) to the config.
    pub changes: Vec<String>,
    /// Packages to install (the CLI does not run the package manager).
    pub install: Option<String>,
    pub notes: Vec<String>,
    pub written: bool,
}

/// Prepare an Expo app for attestation: the App Attest entitlement in
/// app.json (written with `write`), and the packages it must install.
pub fn setup_expo_project(root: &Path, write: bool) -> ProjectSetup {
    let mut out = ProjectSetup::default();
    let found = detect(root, &DetectOptions::default());
    let Some(expo) = found.expo else {
        let dynamic = ["app.config.js", "app.config.ts"]
            .iter()
            .flat_map(|n| find_files(root, n, 4))
            .next();
        out.notes.push(match dynamic {
            Some(p) => format!(
                "{} is code, so it is not edited: add `ios: {{ entitlements: {{ \"{APP_ATTEST_ENTITLEMENT}\": \"production\" }} }}` to it.",
                rel(root, &p)
            ),
            None => "No Expo app (app.json with an \"expo\" key) found; for a bare React Native or native app, add the App Attest capability in Xcode.".into(),
        });
        return out;
    };
    out.config = Some(expo.config.clone());
    let mut packages = Vec::new();
    if !expo.has_app_integrity {
        packages.push("@expo/app-integrity");
    }
    if !expo.sdk_attests {
        packages.push("@offline-protocol/id-react-native@^0.4.0");
    }
    if !packages.is_empty() {
        out.install = Some(format!(
            "cd {} && npx expo install {}",
            expo.dir,
            packages.join(" ")
        ));
    }
    if !expo.has_app_attest_entitlement {
        out.changes.push(format!(
            "{}: ios.entitlements[\"{APP_ATTEST_ENTITLEMENT}\"] = \"production\"",
            expo.config
        ));
        if write {
            let path = root.join(&expo.config);
            let edited = std::fs::read_to_string(&path)
                .ok()
                .and_then(|t| serde_json::from_str::<Value>(&t).ok())
                .and_then(|mut v| {
                    let expo = v.get_mut("expo")?.as_object_mut()?;
                    let ios = expo
                        .entry("ios")
                        .or_insert_with(|| Value::Object(Default::default()))
                        .as_object_mut()?;
                    let ent = ios
                        .entry("entitlements")
                        .or_insert_with(|| Value::Object(Default::default()))
                        .as_object_mut()?;
                    ent.insert(
                        APP_ATTEST_ENTITLEMENT.into(),
                        Value::String("production".into()),
                    );
                    serde_json::to_string_pretty(&v).ok()
                });
            match edited {
                Some(text) if std::fs::write(&path, format!("{text}\n")).is_ok() => {
                    out.written = true
                }
                _ => out.notes.push(format!(
                    "{} could not be edited; add the entitlement by hand.",
                    expo.config
                )),
            }
        }
    }
    out.notes.push(
        "Development builds from Xcode attest in Apple's development environment: run `offline apps native dev-builds on` while testing them, and build with `npx expo run:ios` / `eas build` (Expo Go cannot attest).".into(),
    );
    out
}

/// `KEY = value;` from a pbxproj, skipping build-setting variables.
fn pbx_values(text: &str, key: &str) -> Vec<String> {
    let mut out = Vec::new();
    for line in text.lines() {
        let line = line.trim();
        if let Some(rest) = line.strip_prefix(key) {
            let rest = rest.trim_start();
            if let Some(value) = rest.strip_prefix('=') {
                let value = value.trim().trim_end_matches(';').trim().trim_matches('"');
                if !value.is_empty() && !value.contains("$(") && !out.contains(&value.to_string()) {
                    out.push(value.to_string());
                }
            }
        }
    }
    out
}

fn xcode_projects(root: &Path, found: &mut Detected) {
    for path in find_files(root, "project.pbxproj", 5) {
        if !path
            .parent()
            .and_then(|p| p.extension())
            .is_some_and(|e| e == "xcodeproj")
        {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(&path) else {
            continue;
        };
        let teams = pbx_values(&text, "DEVELOPMENT_TEAM");
        let team = (teams.len() == 1).then(|| teams[0].clone());
        for bundle in pbx_values(&text, "PRODUCT_BUNDLE_IDENTIFIER") {
            // Test and extension targets are separate identities; the app is
            // the shortest bundle ID that prefixes the others.
            add_ios(found, &bundle, team.as_deref(), rel(root, &path));
        }
    }
    // Keep only bundles that are not extensions of another found bundle.
    let all: Vec<String> = found.ios.iter().map(|a| a.bundle_id.clone()).collect();
    found.ios.retain(|a| {
        !all.iter()
            .any(|b| b != &a.bundle_id && a.bundle_id.starts_with(&format!("{b}.")))
    });
}

fn gradle_files(root: &Path, found: &mut Detected) {
    for name in ["build.gradle", "build.gradle.kts"] {
        for path in find_files(root, name, 5) {
            if path.parent().and_then(|p| p.file_name()) != Some(std::ffi::OsStr::new("app")) {
                continue;
            }
            let Ok(text) = std::fs::read_to_string(&path) else {
                continue;
            };
            for line in text.lines() {
                let line = line.trim();
                if let Some(rest) = line.strip_prefix("applicationId") {
                    let value = rest
                        .trim_start_matches([' ', '='])
                        .trim()
                        .trim_matches(['"', '\'']);
                    add_android(found, value, rel(root, &path));
                }
            }
        }
    }
}

fn asset_links(root: &Path, found: &mut Detected) {
    for path in find_files(root, "assetlinks.json", 6) {
        let Ok(text) = std::fs::read_to_string(&path) else {
            continue;
        };
        let Ok(Value::Array(statements)) = serde_json::from_str::<Value>(&text) else {
            continue;
        };
        for statement in statements {
            let Some(package) = statement
                .pointer("/target/package_name")
                .and_then(Value::as_str)
            else {
                continue;
            };
            let Some(i) = add_android(found, package, rel(root, &path)) else {
                continue;
            };
            for cert in statement
                .pointer("/target/sha256_cert_fingerprints")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
                .filter_map(Value::as_str)
            {
                add_cert(&mut found.android[i], cert, "release", rel(root, &path));
            }
        }
    }
}

/// The SHA-256 line of `keytool -list -v` output.
pub fn keytool_sha256(output: &str) -> Option<String> {
    output.lines().find_map(|line| {
        let line = line.trim();
        line.strip_prefix("SHA256:")
            .and_then(|v| normalize_sha256(v.trim()))
    })
}

fn keytool(keystore: &Path, alias: &str, password_env: Option<&str>) -> Result<String, String> {
    let mut cmd = std::process::Command::new("keytool");
    cmd.args(["-list", "-v", "-keystore"]).arg(keystore);
    cmd.args(["-alias", alias]);
    match password_env {
        // `:env` keeps the password out of the process arguments.
        Some(var) => {
            cmd.arg("-storepass:env").arg(var);
        }
        None => {
            cmd.args(["-storepass", "android"]);
        }
    }
    let output = cmd
        .output()
        .map_err(|e| format!("keytool could not run ({e}); install a JDK or pass --sha256"))?;
    if !output.status.success() {
        return Err("keytool could not read the keystore (wrong alias or password?)".into());
    }
    keytool_sha256(&String::from_utf8_lossy(&output.stdout))
        .ok_or_else(|| "keytool printed no SHA-256".to_string())
}

fn debug_keystores(root: &Path, opts: &DetectOptions, found: &mut Detected) {
    if found.android.is_empty() {
        return;
    }
    let mut stores: Vec<PathBuf> = find_files(root, "debug.keystore", 5);
    if opts.home_debug_keystore {
        if let Some(home) = dirs::home_dir() {
            let path = home.join(".android").join("debug.keystore");
            if path.exists() {
                stores.push(path);
            }
        }
    }
    for store in stores {
        match keytool(&store, "androiddebugkey", None) {
            Ok(sha) => {
                for app in found.android.iter_mut() {
                    add_cert(app, &sha, "debug", rel(root, &store));
                }
            }
            Err(e) => found.notes.push(format!("{}: {e}", rel(root, &store))),
        }
    }
}

fn release_keystore(root: &Path, keystore: &Path, alias: Option<&str>, found: &mut Detected) {
    if std::env::var_os("OFFLINE_KEYSTORE_PASSWORD").is_none() {
        found.notes.push(
            "--keystore needs its password in OFFLINE_KEYSTORE_PASSWORD (it is never printed or sent anywhere)."
                .into(),
        );
        return;
    }
    let Some(alias) = alias else {
        found
            .notes
            .push("--keystore needs --keystore-alias.".into());
        return;
    };
    match keytool(keystore, alias, Some("OFFLINE_KEYSTORE_PASSWORD")) {
        Ok(sha) => {
            for app in found.android.iter_mut() {
                add_cert(app, &sha, "release", rel(root, keystore));
            }
        }
        Err(e) => found.notes.push(format!("{}: {e}", rel(root, keystore))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const SHA_A: &str = "06:7C:28:AF:49:FB:03:9D:33:9B:05:2F:3E:FE:6D:52:B4:B4:AF:40:83:F1:26:94:DD:53:EA:1C:B3:EA:18:59";

    #[test]
    fn reads_an_expo_monorepo_and_its_app_links_file() {
        let dir = tempfile::tempdir().unwrap();
        let mobile = dir.path().join("apps/mobile");
        std::fs::create_dir_all(&mobile).unwrap();
        std::fs::write(
            mobile.join("app.json"),
            r#"{"expo":{"ios":{"bundleIdentifier":"xyz.example.app","appleTeamId":"abcde12345"},"android":{"package":"xyz.example.app"}}}"#,
        )
        .unwrap();
        let wk = dir.path().join("apps/site/public/.well-known");
        std::fs::create_dir_all(&wk).unwrap();
        std::fs::write(
            wk.join("assetlinks.json"),
            format!(r#"[{{"target":{{"namespace":"android_app","package_name":"xyz.example.app","sha256_cert_fingerprints":["{SHA_A}"]}}}}]"#),
        )
        .unwrap();
        // Dependencies are never read.
        let nm = dir.path().join("node_modules/dep");
        std::fs::create_dir_all(&nm).unwrap();
        std::fs::write(
            nm.join("app.json"),
            r#"{"expo":{"android":{"package":"com.dep.other"}}}"#,
        )
        .unwrap();

        let found = detect(dir.path(), &DetectOptions::default());
        assert_eq!(found.ios.len(), 1);
        assert_eq!(found.ios[0].bundle_id, "xyz.example.app");
        assert_eq!(found.ios[0].team_id.as_deref(), Some("ABCDE12345"));
        assert_eq!(found.android.len(), 1);
        assert_eq!(found.android[0].certificates[0].sha256, SHA_A);
        assert_eq!(found.android[0].certificates[0].kind, "release");
        assert!(found.notes.is_empty(), "{:?}", found.notes);
    }

    #[test]
    fn reads_bare_native_projects_and_says_what_is_missing() {
        let dir = tempfile::tempdir().unwrap();
        let pbx = dir.path().join("ios/App.xcodeproj");
        std::fs::create_dir_all(&pbx).unwrap();
        std::fs::write(
            pbx.join("project.pbxproj"),
            "PRODUCT_BUNDLE_IDENTIFIER = com.example.app;\nPRODUCT_BUNDLE_IDENTIFIER = com.example.app.widget;\nPRODUCT_BUNDLE_IDENTIFIER = \"$(PRODUCT_NAME)\";\nDEVELOPMENT_TEAM = ABCDE12345;\n",
        )
        .unwrap();
        let app = dir.path().join("android/app");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("build.gradle"),
            "android {\n  defaultConfig {\n    applicationId \"com.example.app\"\n  }\n}\n",
        )
        .unwrap();
        let found = detect(dir.path(), &DetectOptions::default());
        assert_eq!(found.ios.len(), 1, "{:?}", found.ios);
        assert_eq!(found.ios[0].team_id.as_deref(), Some("ABCDE12345"));
        assert_eq!(found.android[0].package, "com.example.app");
        assert!(found
            .notes
            .iter()
            .any(|n| n.contains("No release signing certificate")));
    }

    #[test]
    fn reads_the_sha256_line_of_keytool_output() {
        let out = "Alias name: androiddebugkey\nCertificate fingerprints:\n\t SHA1: 00:11\n\t SHA256: 06:7c:28:af:49:fb:03:9d:33:9b:05:2f:3e:fe:6d:52:b4:b4:af:40:83:f1:26:94:dd:53:ea:1c:b3:ea:18:59\n";
        assert_eq!(keytool_sha256(out).as_deref(), Some(SHA_A));
    }
}

#[cfg(test)]
mod expo_tests {
    use super::*;

    #[test]
    fn an_expo_app_is_prepared_for_attestation_once() {
        let dir = tempfile::tempdir().unwrap();
        let app = dir.path().join("apps/mobile");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("app.json"),
            r#"{"expo":{"name":"X","ios":{"bundleIdentifier":"com.example.app","appleTeamId":"ABCDE12345"}}}"#,
        )
        .unwrap();
        std::fs::write(
            app.join("package.json"),
            r#"{"dependencies":{"@offline-protocol/id-react-native":"^0.3.6"}}"#,
        )
        .unwrap();
        let found = detect(dir.path(), &DetectOptions::default());
        let expo = found.expo.unwrap();
        assert_eq!(expo.dir, "apps/mobile");
        assert!(!expo.has_app_integrity && !expo.has_app_attest_entitlement && !expo.sdk_attests);

        let dry = setup_expo_project(dir.path(), false);
        assert!(!dry.written);
        assert_eq!(dry.changes.len(), 1);
        assert_eq!(
            dry.install.as_deref(),
            Some("cd apps/mobile && npx expo install @expo/app-integrity @offline-protocol/id-react-native@^0.4.0")
        );
        let wrote = setup_expo_project(dir.path(), true);
        assert!(wrote.written);
        let text = std::fs::read_to_string(app.join("app.json")).unwrap();
        assert!(
            text.starts_with("{\n  \"expo\": {\n    \"name\""),
            "key order kept: {text}"
        );
        assert!(text.contains(APP_ATTEST_ENTITLEMENT));
        assert!(setup_expo_project(dir.path(), true).changes.is_empty());
    }

    #[test]
    fn sdk_ranges_that_attest_code_requests() {
        for ok in ["^0.4.0", "0.4.1", "~0.5.0", "1.0.0", ">=0.4.0"] {
            assert!(range_at_least_0_4(ok), "{ok}");
        }
        for no in ["^0.3.6", "0.3.0", "latest", ""] {
            assert!(!range_at_least_0_4(no), "{no}");
        }
    }
}