pub mod detect;
pub mod native;
use anyhow::{bail, Result};
use serde_json::{json, Value};
use native::Native;
pub const SDK_MIN_VERSION: &str = "0.4.0";
pub const DOCS_ATTESTATION: &str = "https://www.offlineprotocol.com/docs/id-sdk/app-attestation";
pub const DOCS_AGENT_QUICKSTART: &str =
"https://www.offlineprotocol.com/docs/getting-started/agent-quickstart";
#[derive(Debug, PartialEq, Eq)]
pub struct Feature {
pub name: &'static str,
pub config_key: &'static str,
pub product: &'static str,
pub setting: &'static str,
pub about: &'static str,
}
pub const FEATURES: &[Feature] = &[
Feature {
name: "telemetry",
config_key: "telemetry",
product: "mesh_sdk",
setting: "mesh_telemetry",
about: "Mesh SDK telemetry: delivery and peer analytics in the portal",
},
Feature {
name: "relay",
config_key: "relay",
product: "mesh_sdk",
setting: "hosted_relay",
about: "Hosted relay (wss://relay.offlineprotocol.com) for delivery between distant peers",
},
Feature {
name: "proof-of-location",
config_key: "proofOfLocation",
product: "proof_of_location",
setting: "enabled",
about: "Proof of Location commitments for this application",
},
];
pub fn feature(name: &str) -> Result<&'static Feature> {
let key = name.trim().to_ascii_lowercase().replace('_', "-");
let key = match key.as_str() {
"mesh-telemetry" => "telemetry",
"hosted-relay" => "relay",
"pol" | "proofoflocation" => "proof-of-location",
k => k,
};
FEATURES.iter().find(|f| f.name == key).ok_or_else(|| {
anyhow::anyhow!(
"unknown feature `{name}`; features: {}",
FEATURES
.iter()
.map(|f| f.name)
.collect::<Vec<_>>()
.join(", ")
)
})
}
pub fn now_rfc3339() -> String {
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
rem / 3600,
(rem % 3600) / 60,
rem % 60
)
}
pub fn is_future(timestamp: &str) -> bool {
let normalized = timestamp.trim().replace("+00:00", "Z");
match (normalized.get(..19), now_rfc3339().get(..19)) {
(Some(t), Some(now)) => t > now,
_ => false,
}
}
pub fn application_from_app_setup(setup: &Value) -> (Value, Vec<(&'static Feature, bool)>) {
let native = &setup["native"];
let app = json!({
"id": setup["application_id"],
"name": setup["name"],
"origins": setup["origins"],
"android_package_names": native["android_package_names"],
"native_attestation": {
"ios_apps": native["ios_apps"],
"android_apps": native["android_apps"],
"allow_development": native["allow_development"],
"production": native["production"],
"android_degraded": native["android_degraded"],
"development_mode": native["development_mode_until"].as_str().map(|until| json!({ "until": until })),
},
});
let features = FEATURES
.iter()
.map(|f| {
let key = if f.name == "proof-of-location" {
"proof_of_location"
} else {
f.name
};
(f, setup["features"][key].as_bool().unwrap_or(false))
})
.collect();
(app, features)
}
pub fn string_list(app: &Value, key: &str) -> Vec<String> {
app.get(key)
.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter_map(Value::as_str)
.map(str::to_string)
.collect()
})
.unwrap_or_default()
}
pub fn normalize_origin(raw: &str) -> Result<String> {
let raw = raw.trim();
let with_scheme = if raw.contains("://") {
raw.to_string()
} else {
format!("https://{raw}")
};
let Some((scheme, rest)) = with_scheme.split_once("://") else {
bail!("`{raw}` is not an origin; use https://example.com");
};
let scheme = scheme.to_ascii_lowercase();
let host = rest
.split(['/', '?', '#'])
.next()
.unwrap_or("")
.to_ascii_lowercase();
let (name, port) = match host.rsplit_once(':') {
Some((n, p)) => (n, Some(p)),
None => (host.as_str(), None),
};
let valid_host = !name.is_empty()
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-')
&& port.map_or(true, |p| {
!p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())
});
if !(scheme == "https" || scheme == "http") || !valid_host {
bail!("`{raw}` is not an origin; use https://example.com (http only for localhost)");
}
let host = host
.strip_suffix(":443")
.filter(|_| scheme == "https")
.or_else(|| host.strip_suffix(":80").filter(|_| scheme == "http"))
.unwrap_or(&host);
Ok(format!("{scheme}://{host}"))
}
pub fn status_report(
app: &Value,
features: Option<&[(&'static Feature, bool)]>,
api_keys: Option<usize>,
detected: Option<&detect::Detected>,
) -> Value {
let app_id = app
.get("id")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
let native = Native::from_application(app);
let ios = native.ios_apps();
let android = native.android_apps();
let flag = format!(" --app-id {app_id}");
let mut next: Vec<String> = Vec::new();
let mut ios_missing: Vec<String> = Vec::new();
if ios.is_empty() {
ios_missing.push("No iOS app registered: native sign-in from iOS is refused.".into());
next.push(format!(
"offline apps native add ios --bundle-id <bundle id> --team-id <Apple Team ID>{flag}"
));
}
if !ios.is_empty() && !native.allow_development() {
ios_missing.push(
"Development builds are not accepted: builds run from Xcode (or `expo run:ios`) attest as development and are refused. Turn it on while developing."
.into(),
);
}
let mut android_missing: Vec<String> = Vec::new();
if android.is_empty() {
android_missing
.push("No Android app registered: native sign-in from Android is refused.".into());
next.push(format!(
"offline apps native add android --package <package name> --sha256 <signing certificate SHA-256>{flag}"
));
}
for package in native.android_packages_without_certificate() {
android_missing.push(format!(
"{package} has no signing certificate SHA-256, so it cannot attest."
));
next.push(format!(
"offline apps native add android --package {package} --sha256 <signing certificate SHA-256>{flag}"
));
}
if let Some(found) = detected {
for d in &found.ios {
let registered = ios.iter().any(|a| a.bundle_id == d.bundle_id);
if !registered {
ios_missing.push(format!(
"{} (from {}) is not registered.",
d.bundle_id, d.source
));
next.push(format!(
"offline apps native add ios --bundle-id {} --team-id {}{flag}",
d.bundle_id,
d.team_id.as_deref().unwrap_or("<Apple Team ID>")
));
}
}
for d in &found.android {
let registered = android.iter().find(|a| a.package == d.package);
for cert in &d.certificates {
if registered.is_some_and(|a| a.sha256.contains(&cert.sha256)) {
continue;
}
android_missing.push(format!(
"{} {} certificate {} (from {}) is not registered.",
d.package, cert.kind, cert.sha256, cert.source
));
next.push(format!(
"offline apps native add android --package {} --sha256 {}{flag}",
d.package, cert.sha256
));
}
if registered.is_none() && d.certificates.is_empty() {
android_missing.push(format!(
"{} (from {}) is not registered.",
d.package, d.source
));
}
}
}
if !ios.is_empty() && !native.allow_development() {
next.push(format!("offline apps native dev-builds on{flag}"));
}
let dev_until = native.development_until();
let dev_command = format!("offline apps native dev-mode on --hours 24{flag}");
if let Some(expo) = detected.and_then(|d| d.expo.as_ref()) {
if !expo.has_app_integrity || !expo.has_app_attest_entitlement || !expo.sdk_attests {
next.push(format!(
"offline apps native setup-project --write --dir {}",
expo.dir
));
}
if !expo.has_app_integrity && dev_until.is_none() && !native.production() {
next.push(dev_command.clone());
}
}
let origins = string_list(app, "origins");
let ios_ready = !ios.is_empty();
let android_ready = !android.is_empty();
let sdk_note = format!(
"Native apps: pass attestation providers (`ios`, `androidKey`) to OfflineAppProvider; \
@offline-protocol/id-react-native {SDK_MIN_VERSION} or later attests every code request and \
sign-in (Expo: @expo/app-integrity). Simulators and emulators cannot attest: sign in on a device."
);
if !ios_ready || !android_ready {
next.push("offline apply --detect".into());
}
let mut report = json!({
"appId": app_id,
"name": app.get("name").cloned().unwrap_or(Value::Null),
"ready": {
"ios": ios_ready,
"android": android_ready,
"web": !origins.is_empty(),
"server": api_keys.map(|n| n > 0),
},
"ios": {
"registered": ios,
"allowDevelopmentBuilds": native.allow_development(),
"missing": ios_missing,
},
"android": {
"registered": android,
"packagesWithoutCertificate": native.android_packages_without_certificate(),
"missing": android_missing,
},
"web": {
"origins": origins,
"note": "Browsers sign in from these origins without attestation. Add one with `offline apps origins add <origin>`.",
},
"server": {
"apiKeys": api_keys,
"note": "Servers send a product API key in X-Api-Key (`offline keys create`).",
},
"development": {
"active": dev_until.is_some(),
"until": dev_until,
"available": !native.production(),
"command": if native.production() { Value::Null } else { json!(dev_command) },
"note": if native.production() {
"The app is marked production, so development mode is off for it: use a separate development application for simulators, emulators and Expo Go."
} else {
"Simulators, emulators and Expo Go cannot attest: turn on development mode (1 to 72 hours) while developing on them."
},
},
"production": native.production(),
"androidDegraded": native.android_degraded(),
"sdk": {
"package": "@offline-protocol/id-react-native",
"minVersion": SDK_MIN_VERSION,
"requires": sdk_note,
},
"nextSteps": dedupe(next),
"docs": DOCS_ATTESTATION,
"agentQuickstart": DOCS_AGENT_QUICKSTART,
});
if let Some(features) = features {
let map: serde_json::Map<String, Value> = features
.iter()
.map(|(f, on)| (f.name.to_string(), Value::Bool(*on)))
.collect();
report["features"] = Value::Object(map);
}
report
}
fn dedupe(items: Vec<String>) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for i in items {
if !out.contains(&i) {
out.push(i);
}
}
out
}
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Desired {
pub ios: Vec<(String, String)>,
pub android: Vec<(String, Vec<String>)>,
pub allow_development: Option<bool>,
pub origins: Vec<String>,
pub features: Vec<(&'static Feature, bool)>,
pub problems: Vec<String>,
}
pub fn desired_from_config(config: &Value) -> Desired {
let mut d = Desired::default();
let Some(app) = config.get("app") else {
return d;
};
let Some(obj) = app.as_object() else {
d.problems.push("`app` must be an object".into());
return d;
};
for key in obj.keys() {
if !["native", "origins", "features"].contains(&key.as_str()) {
d.problems.push(format!(
"unknown key `app.{key}` (expected native, origins, features)"
));
}
}
if let Some(native) = app.get("native") {
for (i, ios) in native
.get("ios")
.and_then(Value::as_array)
.into_iter()
.flatten()
.enumerate()
{
let bundle = ios
.get("bundleId")
.and_then(Value::as_str)
.and_then(native::normalize_bundle_id);
let team = ios
.get("teamId")
.and_then(Value::as_str)
.and_then(native::normalize_team_id);
match (bundle, team) {
(Some(b), Some(t)) => d.ios.push((b, t)),
(None, _) => d.problems.push(format!(
"app.native.ios[{i}].bundleId: {}",
native::BUNDLE_ID_HELP
)),
(_, None) => d.problems.push(format!(
"app.native.ios[{i}].teamId: {}",
native::TEAM_ID_HELP
)),
}
}
for (i, android) in native
.get("android")
.and_then(Value::as_array)
.into_iter()
.flatten()
.enumerate()
{
let Some(package) = android
.get("package")
.and_then(Value::as_str)
.and_then(native::normalize_package)
else {
d.problems.push(format!(
"app.native.android[{i}].package: {}",
native::PACKAGE_HELP
));
continue;
};
let mut certs = Vec::new();
for raw in android
.get("sha256")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
match raw.as_str().and_then(native::normalize_sha256) {
Some(c) => certs.push(c),
None => d.problems.push(format!(
"app.native.android[{i}].sha256: {}",
native::SHA256_HELP
)),
}
}
d.android.push((package, certs));
}
d.allow_development = native
.get("allowDevelopmentBuilds")
.and_then(Value::as_bool);
}
for origin in app
.get("origins")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
match origin.as_str().map(normalize_origin) {
Some(Ok(o)) => d.origins.push(o),
_ => d.problems.push(format!(
"app.origins: `{origin}` is not an origin (https://example.com)"
)),
}
}
if let Some(features) = app.get("features").and_then(Value::as_object) {
for (key, value) in features {
match (
FEATURES.iter().find(|f| f.config_key == key),
value.as_bool(),
) {
(Some(f), Some(on)) => d.features.push((f, on)),
(None, _) => d.problems.push(format!(
"unknown feature `app.features.{key}` (expected {})",
FEATURES
.iter()
.map(|f| f.config_key)
.collect::<Vec<_>>()
.join(", ")
)),
(_, None) => d
.problems
.push(format!("app.features.{key} must be true or false")),
}
}
}
d
}
pub fn merge_detected(d: &mut Desired, found: &detect::Detected, include_debug: bool) {
for ios in &found.ios {
if let Some(team) = &ios.team_id {
if !d.ios.iter().any(|(b, _)| b == &ios.bundle_id) {
d.ios.push((ios.bundle_id.clone(), team.clone()));
}
}
}
for android in &found.android {
let certs: Vec<String> = android
.certificates
.iter()
.filter(|c| include_debug || c.kind != "debug")
.map(|c| c.sha256.clone())
.collect();
if certs.is_empty() {
continue;
}
match d.android.iter_mut().find(|(p, _)| p == &android.package) {
Some((_, existing)) => {
for c in certs {
if !existing.contains(&c) {
existing.push(c);
}
}
}
None => d.android.push((android.package.clone(), certs)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn origins_are_normalized() {
assert_eq!(
normalize_origin("Example.com/login").unwrap(),
"https://example.com"
);
assert_eq!(
normalize_origin("https://shop.example:443/").unwrap(),
"https://shop.example"
);
assert_eq!(
normalize_origin("http://localhost:5173").unwrap(),
"http://localhost:5173"
);
assert!(normalize_origin("javascript:alert(1)").is_err());
}
#[test]
fn features_accept_their_aliases() {
assert_eq!(feature("telemetry").unwrap().setting, "mesh_telemetry");
assert_eq!(feature("hosted_relay").unwrap().name, "relay");
assert_eq!(feature("PoL").unwrap().product, "proof_of_location");
assert!(feature("phone-login").is_err());
}
#[test]
fn the_config_block_is_parsed_and_typos_are_refused() {
let cfg = json!({ "appId": "app_x", "app": {
"native": {
"ios": [{ "bundleId": "com.example.app", "teamId": "abcde12345" }],
"android": [{ "package": "com.example.app", "sha256": ["ab".repeat(32)] }],
"allowDevelopmentBuilds": true
},
"origins": ["example.com"],
"features": { "telemetry": true, "relay": false }
}});
let d = desired_from_config(&cfg);
assert!(d.problems.is_empty(), "{:?}", d.problems);
assert_eq!(
d.ios,
vec![("com.example.app".to_string(), "ABCDE12345".to_string())]
);
assert_eq!(d.android[0].1[0].len(), 95);
assert_eq!(d.origins, vec!["https://example.com"]);
assert_eq!(d.features.len(), 2);
let bad = desired_from_config(
&json!({ "app": { "native": { "ios": [{ "bundleId": "x" }] }, "feature": {}, "features": { "phoneLogin": true } } }),
);
assert_eq!(bad.problems.len(), 3, "{:?}", bad.problems);
}
#[test]
fn status_names_what_is_missing_with_the_command_that_fixes_it() {
let app = json!({ "id": "app_x", "name": "X", "origins": [],
"native_attestation": { "ios_apps": [{ "bundle_id": "com.example.app", "app_id_prefix": "ABCDE12345" }], "android_apps": [], "allow_development": false },
"android_package_names": [] });
let found = detect::Detected {
android: vec![detect::DetectedAndroid {
package: "com.example.app".into(),
source: "app.json".into(),
certificates: vec![detect::DetectedCert {
sha256: "AB".into(),
kind: "release",
source: "assetlinks.json".into(),
}],
}],
..Default::default()
};
let r = status_report(&app, None, Some(1), Some(&found));
assert_eq!(r["ready"]["ios"], true);
assert_eq!(r["ready"]["android"], false);
let steps = r["nextSteps"].to_string();
assert!(steps.contains("offline apps native add android --package com.example.app --sha256 AB --app-id app_x"), "{steps}");
assert!(
steps.contains("offline apps native dev-builds on --app-id app_x"),
"{steps}"
);
}
#[test]
fn detected_debug_certificates_are_opt_in() {
let mut d = Desired::default();
let found = detect::Detected {
ios: vec![detect::DetectedIos {
bundle_id: "com.a.b".into(),
team_id: Some("ABCDE12345".into()),
source: "app.json".into(),
}],
android: vec![detect::DetectedAndroid {
package: "com.a.b".into(),
source: "app.json".into(),
certificates: vec![detect::DetectedCert {
sha256: "D".into(),
kind: "debug",
source: "debug.keystore".into(),
}],
}],
notes: vec![],
expo: None,
};
merge_detected(&mut d, &found, false);
assert_eq!(d.ios.len(), 1);
assert!(d.android.is_empty());
merge_detected(&mut d, &found, true);
assert_eq!(d.android[0].1, vec!["D".to_string()]);
}
}