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,
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>,
}
#[derive(Debug, Clone, Default, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ExpoProject {
pub dir: String,
pub config: String,
pub has_app_integrity: bool,
pub has_app_attest_entitlement: bool,
pub sdk_attests: bool,
pub sdk_range: Option<String>,
}
pub const APP_ATTEST_ENTITLEMENT: &str = "com.apple.developer.devicecheck.appattest-environment";
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>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expo: Option<ExpoProject>,
pub notes: Vec<String>,
}
#[derive(Debug, Clone, Default)]
pub struct DetectOptions {
pub keystore: Option<PathBuf>,
pub keystore_alias: Option<String>,
pub home_debug_keystore: bool,
}
const SKIP_DIRS: &[&str] = &[
"node_modules",
".git",
"Pods",
"build",
"dist",
".expo",
".next",
"target",
"DerivedData",
];
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,
}
}
#[derive(Debug, Clone, Default, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProjectSetup {
pub config: Option<String>,
pub changes: Vec<String>,
pub install: Option<String>,
pub notes: Vec<String>,
pub written: bool,
}
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
}
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") {
add_ios(found, &bundle, team.as_deref(), rel(root, &path));
}
}
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));
}
}
}
}
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 {
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();
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}");
}
}
}