Skip to main content

offline_rn_shell/
lib.rs

1//! Copy React Native `android/` + `ios/` shells after scaffold.
2//!
3//! Shells are cached under `~/.offline/cache/` by RN version; module identity
4//! is rewritten when applying to a project.
5
6use std::path::{Path, PathBuf};
7use std::process::Command;
8
9use anyhow::{bail, Context, Result};
10
11/// Env var override for `~/.offline` (matches offline-cli config dir).
12const ENV_CONFIG_DIR: &str = "OFFLINE_CONFIG_DIR";
13
14fn offline_config_dir() -> Result<PathBuf> {
15    if let Some(dir) = std::env::var_os(ENV_CONFIG_DIR) {
16        return Ok(PathBuf::from(dir));
17    }
18    let home = dirs::home_dir().context("could not determine home directory")?;
19    Ok(home.join(".offline"))
20}
21
22/// React Native version pinned in our starter templates' package.json.
23const RN_VERSION: &str = "0.85.2";
24
25/// Fixed module name used inside the on-disk shell cache. Rewritten to the
26/// project module name when copying into a target app.
27const CACHE_MODULE: &str = "OfflineShell";
28
29/// Convert a slug like `my-offline-app` → `MyOfflineApp` for RN native module names.
30pub fn rn_module_name(slug: &str) -> String {
31    slug.split('-')
32        .filter(|part| !part.is_empty())
33        .map(capitalize_ascii)
34        .collect()
35}
36
37fn capitalize_ascii(part: &str) -> String {
38    let mut chars = part.chars();
39    match chars.next() {
40        None => String::new(),
41        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
42    }
43}
44
45fn rn_shell_cache_dir() -> Result<PathBuf> {
46    Ok(offline_config_dir()?
47        .join("cache")
48        .join(format!("rn-shell-{RN_VERSION}")))
49}
50
51fn shell_cache_ready(cache: &Path) -> bool {
52    cache.join(".ready").is_file() && cache.join("android").is_dir() && cache.join("ios").is_dir()
53}
54
55/// `@react-native-community/cli` version that React Native 0.85.2's own
56/// template (`@react-native-community/template@0.85.2`) depends on. Pinned so
57/// the shell generation is reproducible instead of following npm `latest`.
58const RN_COMMUNITY_CLI_VERSION: &str = "20.1.0";
59
60/// Env var naming a prebuilt shell tarball (`android/`, `ios/`, optional
61/// `Gemfile` at the archive root) to use instead of running `init`.
62const ENV_SHELL_URL: &str = "OFFLINE_RN_SHELL_URL";
63
64/// Ensure a cached RN shell exists.
65///
66/// No prebuilt shell is published: the CLI repository is internal and its
67/// releases carry no shell tarball, so a default download URL would only
68/// 404. The shell is therefore generated deliberately with
69/// `npx @react-native-community/cli@<pinned> init --version <RN_VERSION>` on a
70/// cache miss. Set `OFFLINE_RN_SHELL_URL` to use a prebuilt tarball (for
71/// example an internal mirror); if that download fails, `init` still runs.
72fn ensure_shell_cache() -> Result<PathBuf> {
73    let cache = rn_shell_cache_dir()?;
74    if shell_cache_ready(&cache) {
75        return Ok(cache);
76    }
77
78    // Drop a partial cache before regenerating.
79    if cache.exists() {
80        let _ = std::fs::remove_dir_all(&cache);
81    }
82
83    if let Some(url) = rn_shell_download_url() {
84        if try_download_shell_cache(&url, &cache).is_ok() && shell_cache_ready(&cache) {
85            return Ok(cache);
86        }
87        let _ = std::fs::remove_dir_all(&cache);
88    }
89
90    populate_shell_cache_via_npx(&cache)
91}
92
93fn rn_shell_download_url() -> Option<String> {
94    std::env::var(ENV_SHELL_URL)
95        .ok()
96        .map(|u| u.trim().to_string())
97        .filter(|u| !u.is_empty())
98}
99
100fn try_download_shell_cache(url: &str, cache: &Path) -> Result<()> {
101    let agent = ureq::Agent::new_with_config(
102        ureq::Agent::config_builder()
103            .timeout_global(Some(std::time::Duration::from_secs(120)))
104            .user_agent(concat!("offline-cli/", env!("CARGO_PKG_VERSION")))
105            .build(),
106    );
107    let response = agent
108        .get(url)
109        .call()
110        .map_err(|e| anyhow::anyhow!("download RN shell from {url}: {e}"))?;
111
112    let tmp_tar = std::env::temp_dir().join(format!(
113        "offline-rn-shell-{}-{}.tar.gz",
114        std::process::id(),
115        std::time::SystemTime::now()
116            .duration_since(std::time::UNIX_EPOCH)
117            .map(|d| d.as_nanos())
118            .unwrap_or(0)
119    ));
120    let mut file = std::fs::File::create(&tmp_tar)
121        .with_context(|| format!("create temp archive at {}", tmp_tar.display()))?;
122    std::io::copy(&mut response.into_body().into_reader(), &mut file)
123        .context("write downloaded RN shell archive")?;
124    drop(file);
125
126    std::fs::create_dir_all(cache)
127        .with_context(|| format!("create shell cache at {}", cache.display()))?;
128
129    let tar_gz = std::fs::File::open(&tmp_tar).context("reopen downloaded RN shell archive")?;
130    let decoder = flate2::read::GzDecoder::new(tar_gz);
131    let mut archive = tar::Archive::new(decoder);
132    archive.unpack(cache).context("extract RN shell archive")?;
133    let _ = std::fs::remove_file(&tmp_tar);
134
135    if !cache.join(".ready").is_file() {
136        std::fs::write(cache.join(".ready"), RN_VERSION.as_bytes())
137            .with_context(|| format!("write {}", cache.join(".ready").display()))?;
138    }
139    Ok(())
140}
141
142fn populate_shell_cache_via_npx(cache: &Path) -> Result<PathBuf> {
143    let tmp_base = std::env::temp_dir().join(format!(
144        "offline-rn-init-{}-{}",
145        std::process::id(),
146        std::time::SystemTime::now()
147            .duration_since(std::time::UNIX_EPOCH)
148            .map(|d| d.as_nanos())
149            .unwrap_or(0)
150    ));
151    std::fs::create_dir_all(&tmp_base).with_context(|| {
152        format!(
153            "create temp dir for react-native init at {}",
154            tmp_base.display()
155        )
156    })?;
157
158    let init_result = (|| -> Result<()> {
159        let cli = format!("@react-native-community/cli@{RN_COMMUNITY_CLI_VERSION}");
160        let output = Command::new("npx")
161            .args([
162                "--yes",
163                cli.as_str(),
164                "init",
165                CACHE_MODULE,
166                "--version",
167                RN_VERSION,
168                "--skip-install",
169                "--pm",
170                "npm",
171            ])
172            .current_dir(&tmp_base)
173            .output()
174            .with_context(|| format!("failed to spawn `npx {cli} init` (is Node.js installed?)"))?;
175
176        if !output.status.success() {
177            let stdout = String::from_utf8_lossy(&output.stdout);
178            let stderr = String::from_utf8_lossy(&output.stderr);
179            bail!(
180                "react-native init exited with {}:\n{stdout}{stderr}",
181                output.status
182            );
183        }
184
185        let shell_root = tmp_base.join(CACHE_MODULE);
186        std::fs::create_dir_all(cache)
187            .with_context(|| format!("create shell cache at {}", cache.display()))?;
188        copy_dir_all(&shell_root.join("android"), &cache.join("android"))
189            .context("cache android/")?;
190        copy_dir_all(&shell_root.join("ios"), &cache.join("ios")).context("cache ios/")?;
191        copy_file_if_missing(&shell_root.join("Gemfile"), &cache.join("Gemfile"))?;
192        // Marker written last so a partial cache is never treated as ready.
193        std::fs::write(cache.join(".ready"), RN_VERSION.as_bytes())
194            .with_context(|| format!("write {}", cache.join(".ready").display()))?;
195        Ok(())
196    })();
197
198    let _ = std::fs::remove_dir_all(&tmp_base);
199    if let Err(err) = init_result {
200        let _ = std::fs::remove_dir_all(cache);
201        return Err(err);
202    }
203    Ok(cache.to_path_buf())
204}
205
206fn apply_shell_from_cache(cache: &Path, target_dir: &Path, module_name: &str) -> Result<()> {
207    copy_dir_all(&cache.join("android"), &target_dir.join("android")).context("copy android/")?;
208    copy_dir_all(&cache.join("ios"), &target_dir.join("ios")).context("copy ios/")?;
209    copy_file_if_missing(&cache.join("Gemfile"), &target_dir.join("Gemfile"))?;
210    copy_file_if_missing(
211        &cache.join("ios").join(".xcode.env"),
212        &target_dir.join("ios").join(".xcode.env"),
213    )?;
214    if module_name != CACHE_MODULE {
215        rewrite_shell_identity(target_dir, module_name)?;
216    }
217    Ok(())
218}
219
220/// Rename path segments and rewrite text contents from `CACHE_MODULE` → `module_name`.
221fn rewrite_shell_identity(root: &Path, module_name: &str) -> Result<()> {
222    let from = CACHE_MODULE;
223    let to = module_name;
224    let from_lower = from.to_ascii_lowercase();
225    let to_lower = to.to_ascii_lowercase();
226    let from_pkg = format!("com.{from_lower}");
227    let to_pkg = format!("com.{to_lower}");
228
229    rename_path_components(root, from, to)?;
230    if from_lower != from {
231        rename_path_components(root, &from_lower, &to_lower)?;
232    }
233
234    replace_in_text_files(
235        root,
236        &[
237            (from_pkg.as_str(), to_pkg.as_str()),
238            (from, to),
239            (from_lower.as_str(), to_lower.as_str()),
240        ],
241    )?;
242    Ok(())
243}
244
245fn rename_path_components(root: &Path, from: &str, to: &str) -> Result<()> {
246    let mut paths = Vec::new();
247    collect_paths(root, &mut paths)?;
248    // Deepest paths first so parents rename after children.
249    paths.sort_by_key(|p| std::cmp::Reverse(p.components().count()));
250    for path in paths {
251        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
252            continue;
253        };
254        if !name.contains(from) {
255            continue;
256        }
257        let new_name = name.replace(from, to);
258        let dest = path.with_file_name(new_name);
259        if dest != path {
260            std::fs::rename(&path, &dest)
261                .with_context(|| format!("rename {} → {}", path.display(), dest.display()))?;
262        }
263    }
264    Ok(())
265}
266
267fn collect_paths(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
268    for entry in std::fs::read_dir(dir)? {
269        let entry = entry?;
270        let path = entry.path();
271        if path.is_dir() {
272            collect_paths(&path, out)?;
273        }
274        out.push(path);
275    }
276    Ok(())
277}
278
279fn replace_in_text_files(root: &Path, replacements: &[(&str, &str)]) -> Result<()> {
280    let mut files = Vec::new();
281    collect_files(root, &mut files)?;
282    for path in files {
283        let Ok(bytes) = std::fs::read(&path) else {
284            continue;
285        };
286        let Ok(mut content) = String::from_utf8(bytes) else {
287            continue;
288        };
289        let mut changed = false;
290        for (from, to) in replacements {
291            if content.contains(from) {
292                content = content.replace(from, to);
293                changed = true;
294            }
295        }
296        if changed {
297            std::fs::write(&path, content)
298                .with_context(|| format!("rewrite {}", path.display()))?;
299        }
300    }
301    Ok(())
302}
303
304fn collect_files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
305    for entry in std::fs::read_dir(dir)? {
306        let entry = entry?;
307        let path = entry.path();
308        if path.is_dir() {
309            collect_files(&path, out)?;
310        } else {
311            out.push(path);
312        }
313    }
314    Ok(())
315}
316
317/// Copy cached (or freshly generated) `android/` + `ios/` shells into `target_dir`.
318pub fn add_native_shells(target_dir: &Path, module_name: &str) -> Result<()> {
319    if target_dir.join("android").is_dir() && target_dir.join("ios").is_dir() {
320        return Ok(());
321    }
322
323    let cache = ensure_shell_cache()?;
324    apply_shell_from_cache(&cache, target_dir, module_name)
325}
326
327/// Result of post-scaffold React Native native setup.
328#[derive(Debug, Default)]
329pub struct ReactNativeFinalizeResult {
330    pub native_shells_added: bool,
331    pub extra_files: Vec<String>,
332    pub warnings: Vec<String>,
333}
334
335/// After JS/TS template generation: add native shells and mesh-related native config.
336pub fn finalize_react_native_mesh_app(
337    target_dir: &Path,
338    module_name: &str,
339    mesh_enabled: bool,
340) -> ReactNativeFinalizeResult {
341    let mut result = ReactNativeFinalizeResult::default();
342
343    match add_native_shells(target_dir, module_name) {
344        Ok(()) => {
345            result.native_shells_added =
346                target_dir.join("android").is_dir() && target_dir.join("ios").is_dir();
347            if result.native_shells_added {
348                result.extra_files.push("android/".to_string());
349                result.extra_files.push("ios/".to_string());
350            }
351        }
352        Err(err) => result
353            .warnings
354            .push(format!("Native android/ios shells not added: {err:#}")),
355    }
356
357    if target_dir.join("android").is_dir() {
358        if let Err(err) = patch_network_binding(target_dir, module_name) {
359            result.warnings.push(format!(
360                "Android Wi‑Fi network binding not applied: {err:#}"
361            ));
362        }
363    }
364
365    if mesh_enabled && target_dir.join("ios").is_dir() {
366        if let Err(err) = patch_mesh_native_permissions(target_dir, module_name) {
367            result
368                .warnings
369                .push(format!("Mesh native permissions/pod not applied: {err:#}"));
370        }
371    }
372
373    if uses_offline_id(target_dir) && target_dir.join("ios").is_dir() {
374        match patch_app_attest_entitlement(target_dir, module_name) {
375            Ok(true) => result
376                .extra_files
377                .push(format!("ios/{module_name}/{module_name}.entitlements")),
378            Ok(false) => {}
379            Err(err) => result.warnings.push(format!(
380                "App Attest entitlement not added (add the App Attest capability in Xcode): {err:#}"
381            )),
382        }
383    }
384
385    result
386}
387
388/// The app depends on `@offline-protocol/id-react-native`, whose sign-ins
389/// carry an App Attest proof on iOS.
390fn uses_offline_id(target_dir: &Path) -> bool {
391    std::fs::read_to_string(target_dir.join("package.json"))
392        .map(|pkg| pkg.contains("\"@offline-protocol/id-react-native\""))
393        .unwrap_or(false)
394}
395
396/// The App Attest environment entitlement. `production` makes every build,
397/// including one run from Xcode, attest in Apple's production environment,
398/// which auth-service accepts without `offline apps native dev-builds on`.
399pub const APP_ATTEST_ENTITLEMENT: &str = "com.apple.developer.devicecheck.appattest-environment";
400
401const APP_ATTEST_ENTITLEMENTS_PLIST: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
402<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
403<plist version="1.0">
404<dict>
405	<key>com.apple.developer.devicecheck.appattest-environment</key>
406	<string>production</string>
407</dict>
408</plist>
409"#;
410
411/// Give the iOS app target the App Attest entitlement: write
412/// `ios/<Module>/<Module>.entitlements` and point the target's
413/// `CODE_SIGN_ENTITLEMENTS` at it (Debug and Release). Idempotent; an
414/// existing entitlements setting is left alone. Returns whether the
415/// entitlements file was written.
416pub fn patch_app_attest_entitlement(target_dir: &Path, module_name: &str) -> Result<bool> {
417    let pbxproj = target_dir.join(format!("ios/{module_name}.xcodeproj/project.pbxproj"));
418    if !pbxproj.is_file() {
419        bail!("{} not found", pbxproj.display());
420    }
421    let content =
422        std::fs::read_to_string(&pbxproj).with_context(|| format!("read {}", pbxproj.display()))?;
423    if content.contains("CODE_SIGN_ENTITLEMENTS") {
424        return Ok(false);
425    }
426    let info_plist = format!("INFOPLIST_FILE = {module_name}/Info.plist;");
427    let setting = format!("CODE_SIGN_ENTITLEMENTS = {module_name}/{module_name}.entitlements;");
428    let mut patched = String::with_capacity(content.len() + 256);
429    let mut count = 0;
430    for line in content.split_inclusive('\n') {
431        if line.trim() == info_plist {
432            let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
433            patched.push_str(&indent);
434            patched.push_str(&setting);
435            patched.push('\n');
436            count += 1;
437        }
438        patched.push_str(line);
439    }
440    if count == 0 {
441        bail!(
442            "no build configuration with `{info_plist}` in {}",
443            pbxproj.display()
444        );
445    }
446    let entitlements = target_dir.join(format!("ios/{module_name}/{module_name}.entitlements"));
447    let written = !entitlements.exists();
448    if written {
449        std::fs::write(&entitlements, APP_ATTEST_ENTITLEMENTS_PLIST)
450            .with_context(|| format!("write {}", entitlements.display()))?;
451    }
452    std::fs::write(&pbxproj, patched).with_context(|| format!("write {}", pbxproj.display()))?;
453    Ok(written)
454}
455
456/// Add Android/iOS permissions and iOS Podfile cleanup required by mesh-sdk.
457pub fn patch_mesh_native_permissions(target_dir: &Path, module_name: &str) -> Result<()> {
458    let podfile = target_dir.join("ios/Podfile");
459    if podfile.is_file() {
460        patch_mesh_ios_podfile(&podfile)?;
461        patch_mesh_ios_podfile_build_settings(&podfile)?;
462    }
463    let manifest = target_dir.join("android/app/src/main/AndroidManifest.xml");
464    if manifest.is_file() {
465        patch_android_mesh_permissions(&manifest)?;
466    }
467    let plist = target_dir.join(format!("ios/{module_name}/Info.plist"));
468    if plist.is_file() {
469        patch_ios_mesh_permissions(&plist)?;
470    }
471    Ok(())
472}
473
474/// Add Android NetworkBinding for unvalidated Wi‑Fi uplinks.
475pub fn patch_network_binding(target_dir: &Path, module_name: &str) -> Result<()> {
476    let package = format!("com.{}", module_name.to_ascii_lowercase());
477    let java_root = target_dir
478        .join("android/app/src/main/java")
479        .join(package.replace('.', "/"));
480    if !java_root.is_dir() {
481        // Default package path missing; scan the java tree.
482        return patch_network_binding_in_java_tree(target_dir, module_name);
483    }
484    write_network_binding_sources(&java_root, &package)?;
485    patch_main_application_for_network_binding(&java_root)?;
486    let manifest = target_dir.join("android/app/src/main/AndroidManifest.xml");
487    if manifest.is_file() {
488        patch_android_network_binding_permissions(&manifest)?;
489    }
490    Ok(())
491}
492
493fn patch_network_binding_in_java_tree(target_dir: &Path, module_name: &str) -> Result<()> {
494    let java_base = target_dir.join("android/app/src/main/java");
495    if !java_base.is_dir() {
496        return Ok(());
497    }
498    let main_app = find_file_named(&java_base, "MainApplication.kt")
499        .or_else(|| find_file_named(&java_base, "MainApplication.java"));
500    let Some(main_app) = main_app else {
501        return Ok(());
502    };
503    let java_root = main_app.parent().unwrap().to_path_buf();
504    let package = package_from_java_root(&java_base, &java_root)
505        .unwrap_or_else(|| format!("com.{}", module_name.to_ascii_lowercase()));
506    write_network_binding_sources(&java_root, &package)?;
507    patch_main_application_for_network_binding(&java_root)?;
508    let manifest = target_dir.join("android/app/src/main/AndroidManifest.xml");
509    if manifest.is_file() {
510        patch_android_network_binding_permissions(&manifest)?;
511    }
512    Ok(())
513}
514
515fn find_file_named(dir: &Path, name: &str) -> Option<std::path::PathBuf> {
516    let mut stack = vec![dir.to_path_buf()];
517    while let Some(cur) = stack.pop() {
518        let Ok(entries) = std::fs::read_dir(&cur) else {
519            continue;
520        };
521        for entry in entries.flatten() {
522            let path = entry.path();
523            if path.is_dir() {
524                stack.push(path);
525            } else if entry.file_name() == name {
526                return Some(path);
527            }
528        }
529    }
530    None
531}
532
533fn package_from_java_root(java_base: &Path, java_root: &Path) -> Option<String> {
534    let rel = java_root.strip_prefix(java_base).ok()?;
535    let parts: Vec<_> = rel
536        .components()
537        .filter_map(|c| match c {
538            std::path::Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
539            _ => None,
540        })
541        .collect();
542    if parts.is_empty() {
543        None
544    } else {
545        Some(parts.join("."))
546    }
547}
548
549fn write_network_binding_sources(java_root: &Path, package: &str) -> Result<()> {
550    let module_path = java_root.join("NetworkBindingModule.kt");
551    let package_path = java_root.join("NetworkBindingPackage.kt");
552    if !module_path.exists() {
553        std::fs::write(&module_path, network_binding_module_kt(package))
554            .with_context(|| format!("write {}", module_path.display()))?;
555    }
556    if !package_path.exists() {
557        std::fs::write(&package_path, network_binding_package_kt(package))
558            .with_context(|| format!("write {}", package_path.display()))?;
559    }
560    Ok(())
561}
562
563fn patch_main_application_for_network_binding(java_root: &Path) -> Result<()> {
564    let kt = java_root.join("MainApplication.kt");
565    if kt.is_file() {
566        let mut content =
567            std::fs::read_to_string(&kt).with_context(|| format!("read {}", kt.display()))?;
568        if content.contains("NetworkBindingPackage") {
569            return Ok(());
570        }
571        let needle = "PackageList(this).packages.apply {";
572        let Some(idx) = content.find(needle) else {
573            bail!("MainApplication.kt missing PackageList apply block");
574        };
575        let insert_at = idx + needle.len();
576        content.insert_str(
577            insert_at,
578            "\n          // Bind Offline ID HTTPS to Wi‑Fi even when Android marks it unvalidated.\n          add(NetworkBindingPackage())",
579        );
580        std::fs::write(&kt, content).with_context(|| format!("write {}", kt.display()))?;
581        return Ok(());
582    }
583    Ok(())
584}
585
586fn patch_android_network_binding_permissions(path: &Path) -> Result<()> {
587    let mut content =
588        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
589    let mut changed = false;
590    for perm in [
591        "android.permission.ACCESS_NETWORK_STATE",
592        "android.permission.CHANGE_NETWORK_STATE",
593    ] {
594        if content.contains(perm) {
595            continue;
596        }
597        let line = format!("    <uses-permission android:name=\"{perm}\" />\n");
598        if let Some(idx) =
599            content.find("<uses-permission android:name=\"android.permission.INTERNET\" />")
600        {
601            let end = content[idx..]
602                .find('\n')
603                .map(|i| idx + i + 1)
604                .unwrap_or(content.len());
605            content.insert_str(end, &line);
606            changed = true;
607        } else if let Some(idx) = content.find("<application") {
608            content.insert_str(idx, &line);
609            changed = true;
610        }
611    }
612    if changed {
613        std::fs::write(path, content).with_context(|| format!("write {}", path.display()))?;
614    }
615    Ok(())
616}
617
618fn network_binding_module_kt(package: &str) -> String {
619    format!(
620        r#"package {package}
621
622import android.content.Context
623import android.net.ConnectivityManager
624import android.net.Network
625import android.net.NetworkCapabilities
626import android.net.NetworkRequest
627import android.os.Build
628import android.os.Handler
629import android.os.Looper
630import com.facebook.react.bridge.Promise
631import com.facebook.react.bridge.ReactApplicationContext
632import com.facebook.react.bridge.ReactContextBaseJavaModule
633import com.facebook.react.bridge.ReactMethod
634import java.util.concurrent.atomic.AtomicBoolean
635
636/** Prefer VALIDATED Wi‑Fi, else cellular; avoid unvalidated Wi‑Fi. */
637class NetworkBindingModule(
638  private val reactContext: ReactApplicationContext,
639) : ReactContextBaseJavaModule(reactContext) {{
640
641  private val mainHandler = Handler(Looper.getMainLooper())
642  @Volatile private var pendingCallback: ConnectivityManager.NetworkCallback? = null
643
644  override fun getName(): String = NAME
645
646  @ReactMethod
647  fun preferWifi(promise: Promise) {{
648    preferUplink(promise)
649  }}
650
651  @ReactMethod
652  fun preferUplink(promise: Promise) {{
653    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {{
654      promise.resolve(false)
655      return
656    }}
657
658    val cm =
659      reactContext.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
660    if (cm == null) {{
661      promise.resolve(false)
662      return
663    }}
664
665    val existing = findValidatedUplink(cm)
666    if (existing != null && bindTo(cm, existing)) {{
667      promise.resolve(true)
668      return
669    }}
670
671    requestValidatedInternet(cm, promise)
672  }}
673
674  @ReactMethod
675  fun clearBinding(promise: Promise) {{
676    val cm =
677      reactContext.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
678    if (cm == null) {{
679      promise.resolve(false)
680      return
681    }}
682    unregisterPending(cm)
683    val cleared =
684      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {{
685        cm.bindProcessToNetwork(null)
686      }} else {{
687        @Suppress("DEPRECATION")
688        ConnectivityManager.setProcessDefaultNetwork(null)
689      }}
690    promise.resolve(cleared)
691  }}
692
693  private fun isValidated(caps: NetworkCapabilities): Boolean {{
694    if (!caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {{
695      return false
696    }}
697    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {{
698      caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
699    }} else {{
700      true
701    }}
702  }}
703
704  private fun findValidatedUplink(cm: ConnectivityManager): Network? {{
705    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return null
706
707    var validatedWifi: Network? = null
708    var validatedOther: Network? = null
709
710    for (network in cm.allNetworks) {{
711      val caps = cm.getNetworkCapabilities(network) ?: continue
712      if (!isValidated(caps)) continue
713      if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {{
714        validatedWifi = network
715      }} else {{
716        validatedOther = network
717      }}
718    }}
719
720    return validatedWifi ?: validatedOther
721  }}
722
723  private fun requestValidatedInternet(cm: ConnectivityManager, promise: Promise) {{
724    val settled = AtomicBoolean(false)
725    fun settle(ok: Boolean) {{
726      if (settled.compareAndSet(false, true)) {{
727        promise.resolve(ok)
728      }}
729    }}
730
731    val builder =
732      NetworkRequest.Builder()
733        .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
734    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {{
735      builder.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
736    }}
737    val request = builder.build()
738
739    val callback =
740      object : ConnectivityManager.NetworkCallback() {{
741        override fun onAvailable(network: Network) {{
742          tryBindValidated(cm, network, settled, promise)
743        }}
744
745        override fun onCapabilitiesChanged(
746          network: Network,
747          networkCapabilities: NetworkCapabilities,
748        ) {{
749          if (isValidated(networkCapabilities)) {{
750            tryBindValidated(cm, network, settled, promise)
751          }}
752        }}
753
754        override fun onUnavailable() {{
755          mainHandler.post {{
756            unregisterPending(cm)
757            settle(false)
758          }}
759        }}
760      }}
761
762    pendingCallback = callback
763    try {{
764      cm.requestNetwork(request, callback)
765    }} catch (_: SecurityException) {{
766      pendingCallback = null
767      settle(false)
768      return
769    }} catch (_: RuntimeException) {{
770      pendingCallback = null
771      settle(false)
772      return
773    }}
774
775    mainHandler.postDelayed(
776      {{
777        if (settled.get()) return@postDelayed
778        unregisterPending(cm)
779        val network = findValidatedUplink(cm)
780        settle(network != null && bindTo(cm, network))
781      }},
782      REQUEST_TIMEOUT_MS,
783    )
784  }}
785
786  private fun tryBindValidated(
787    cm: ConnectivityManager,
788    network: Network,
789    settled: AtomicBoolean,
790    promise: Promise,
791  ) {{
792    mainHandler.post {{
793      if (settled.get()) return@post
794      val caps = cm.getNetworkCapabilities(network)
795      if (caps == null || !isValidated(caps)) return@post
796      val ok = bindTo(cm, network)
797      unregisterPending(cm)
798      if (settled.compareAndSet(false, true)) {{
799        promise.resolve(ok)
800      }}
801    }}
802  }}
803
804  private fun bindTo(cm: ConnectivityManager, network: Network): Boolean {{
805    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {{
806      cm.bindProcessToNetwork(network)
807    }} else {{
808      @Suppress("DEPRECATION")
809      ConnectivityManager.setProcessDefaultNetwork(network)
810    }}
811  }}
812
813  private fun unregisterPending(cm: ConnectivityManager) {{
814    val callback = pendingCallback ?: return
815    pendingCallback = null
816    try {{
817      cm.unregisterNetworkCallback(callback)
818    }} catch (_: IllegalArgumentException) {{
819      // Already unregistered.
820    }}
821  }}
822
823  companion object {{
824    const val NAME = "NetworkBinding"
825    private const val REQUEST_TIMEOUT_MS = 6_000L
826  }}
827}}
828"#
829    )
830}
831
832fn network_binding_package_kt(package: &str) -> String {
833    format!(
834        r#"package {package}
835
836import com.facebook.react.ReactPackage
837import com.facebook.react.bridge.NativeModule
838import com.facebook.react.bridge.ReactApplicationContext
839import com.facebook.react.uimanager.ViewManager
840
841class NetworkBindingPackage : ReactPackage {{
842  override fun createNativeModules(
843    reactContext: ReactApplicationContext,
844  ): List<NativeModule> = listOf(NetworkBindingModule(reactContext))
845
846  override fun createViewManagers(
847    reactContext: ReactApplicationContext,
848  ): List<ViewManager<*, *>> = emptyList()
849}}
850"#
851    )
852}
853
854fn patch_android_mesh_permissions(path: &Path) -> Result<()> {
855    let mut content =
856        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
857    if content.contains("BLUETOOTH_SCAN") {
858        return Ok(());
859    }
860    const PERMS: &str = r#"
861    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
862    <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
863    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
864    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
865    <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:usesPermissionFlags="neverForLocation" />
866"#;
867    let marker = "<application";
868    let Some(idx) = content.find(marker) else {
869        bail!("AndroidManifest.xml missing <application> tag");
870    };
871    content.insert_str(idx, PERMS);
872    std::fs::write(path, content).with_context(|| format!("write {}", path.display()))?;
873    Ok(())
874}
875
876fn patch_ios_mesh_permissions(path: &Path) -> Result<()> {
877    let mut content =
878        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
879    const PLIST_SNIPPETS: &[(&str, &str)] = &[
880        (
881            "NSBluetoothAlwaysUsageDescription",
882            r#"
883	<key>NSBluetoothAlwaysUsageDescription</key>
884	<string>Find and message nearby people over the mesh.</string>"#,
885        ),
886        (
887            "NSBluetoothPeripheralUsageDescription",
888            r#"
889	<key>NSBluetoothPeripheralUsageDescription</key>
890	<string>Find and message nearby people over the mesh.</string>"#,
891        ),
892        (
893            "NSLocationWhenInUseUsageDescription",
894            r#"
895	<key>NSLocationWhenInUseUsageDescription</key>
896	<string>Location is used for Bluetooth peer discovery.</string>"#,
897        ),
898        (
899            "UIBackgroundModes",
900            r#"
901	<key>UIBackgroundModes</key>
902	<array>
903		<string>bluetooth-central</string>
904		<string>bluetooth-peripheral</string>
905	</array>"#,
906        ),
907    ];
908    let marker = "</dict>";
909    let Some(mut idx) = content.rfind(marker) else {
910        bail!("Info.plist missing closing </dict>");
911    };
912    for (key, snippet) in PLIST_SNIPPETS {
913        if !content.contains(key) {
914            content.insert_str(idx, snippet);
915            idx += snippet.len();
916        }
917    }
918    std::fs::write(path, content).with_context(|| format!("write {}", path.display()))?;
919    Ok(())
920}
921
922/// Remove legacy manual MeshSdk pod lines; `@offline-protocol/mesh-sdk` autolinks via
923/// `MeshSdk.podspec` at the package root (`use_native_modules!`).
924fn patch_mesh_ios_podfile(path: &Path) -> Result<()> {
925    let content =
926        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
927    let mut lines: Vec<&str> = content.lines().collect();
928    let before = lines.len();
929    lines.retain(|line| !is_manual_mesh_sdk_pod_line(line));
930    if lines.len() == before {
931        return Ok(());
932    }
933    let mut patched = lines.join("\n");
934    if content.ends_with('\n') {
935        patched.push('\n');
936    }
937    std::fs::write(path, patched).with_context(|| format!("write {}", path.display()))?;
938    Ok(())
939}
940
941fn is_manual_mesh_sdk_pod_line(line: &str) -> bool {
942    let trimmed = line.trim();
943    trimmed.starts_with("pod 'MeshSdk'") || trimmed.starts_with("pod \"MeshSdk\"")
944}
945
946/// Xcode 26 / RN fmt and modular-include build fixes for mesh iOS shells.
947fn patch_mesh_ios_podfile_build_settings(path: &Path) -> Result<()> {
948    let mut content =
949        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
950    if content.contains("FMT_USE_CONSTEVAL") {
951        return Ok(());
952    }
953    const SNIPPET: &str = r##"
954    # offline-rn-shell: fmt + modular includes for Xcode 26 / RN 0.82+
955    fmt_base = File.join(installer.sandbox.root, 'fmt', 'include', 'fmt', 'base.h')
956    if File.exist?(fmt_base)
957      original = File.read(fmt_base)
958      patched = original.gsub('#  define FMT_USE_CONSTEVAL 1',
959                              '#  define FMT_USE_CONSTEVAL 0')
960      if patched != original
961        File.write(fmt_base, patched)
962        Pod::UI.puts 'Patched fmt/base.h: forced FMT_USE_CONSTEVAL=0 (Xcode 26.5 / clang 21)'.yellow
963      end
964    end
965
966    installer.pods_project.targets.each do |target|
967      target.build_configurations.each do |build_config|
968        build_config.build_settings['CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES'] = 'YES'
969        other_cflags = build_config.build_settings['OTHER_CFLAGS'] || '$(inherited)'
970        other_cxxflags = build_config.build_settings['OTHER_CPLUSPLUSFLAGS'] || '$(inherited)'
971        warning_flag = '-Wno-error=return-type'
972        unless other_cflags.include?(warning_flag)
973          build_config.build_settings['OTHER_CFLAGS'] = "#{other_cflags} #{warning_flag}"
974        end
975        unless other_cxxflags.include?(warning_flag)
976          build_config.build_settings['OTHER_CPLUSPLUSFLAGS'] = "#{other_cxxflags} #{warning_flag}"
977        end
978        build_config.build_settings['SWIFT_STRICT_CONCURRENCY'] ||= 'minimal'
979      end
980    end
981"##;
982    let marker = "react_native_post_install(";
983    let Some(start) = content.find(marker) else {
984        return Ok(());
985    };
986    // Insert after the closing `)` of react_native_post_install(...) — typically the
987    // line `    )` immediately following the call.
988    let after_start = &content[start..];
989    let Some(close_paren) = after_start.find("\n    )") else {
990        return Ok(());
991    };
992    let insert_at = start + close_paren + "\n    )".len();
993    content.insert_str(insert_at, SNIPPET);
994    std::fs::write(path, content).with_context(|| format!("write {}", path.display()))?;
995    Ok(())
996}
997
998fn copy_file_if_missing(from: &Path, to: &Path) -> Result<()> {
999    if to.exists() || !from.is_file() {
1000        return Ok(());
1001    }
1002    if let Some(parent) = to.parent() {
1003        std::fs::create_dir_all(parent)?;
1004    }
1005    std::fs::copy(from, to)?;
1006    Ok(())
1007}
1008
1009fn copy_dir_all(from: &Path, to: &Path) -> Result<()> {
1010    if !from.is_dir() {
1011        bail!("expected directory at {}", from.display());
1012    }
1013    std::fs::create_dir_all(to)?;
1014    for entry in std::fs::read_dir(from)? {
1015        let entry = entry?;
1016        let dest = to.join(entry.file_name());
1017        if entry.file_type()?.is_dir() {
1018            copy_dir_all(&entry.path(), &dest)?;
1019        } else {
1020            std::fs::copy(entry.path(), dest)?;
1021        }
1022    }
1023    Ok(())
1024}
1025
1026#[cfg(test)]
1027mod tests {
1028    use super::*;
1029
1030    #[test]
1031    fn app_attest_entitlement_is_added_to_both_configurations_once() {
1032        let tmp = tempfile::tempdir().unwrap();
1033        let root = tmp.path();
1034        std::fs::create_dir_all(root.join("ios/MyApp.xcodeproj")).unwrap();
1035        std::fs::create_dir_all(root.join("ios/MyApp")).unwrap();
1036        let pbxproj = root.join("ios/MyApp.xcodeproj/project.pbxproj");
1037        std::fs::write(
1038            &pbxproj,
1039            "\t\t\tbuildSettings = {\n\t\t\t\tENABLE_BITCODE = NO;\n\t\t\t\tINFOPLIST_FILE = MyApp/Info.plist;\n\t\t\t};\n\t\t\tbuildSettings = {\n\t\t\t\tINFOPLIST_FILE = MyApp/Info.plist;\n\t\t\t};\n",
1040        )
1041        .unwrap();
1042        assert!(patch_app_attest_entitlement(root, "MyApp").unwrap());
1043        let first = std::fs::read_to_string(&pbxproj).unwrap();
1044        assert_eq!(
1045            first
1046                .matches("\t\t\t\tCODE_SIGN_ENTITLEMENTS = MyApp/MyApp.entitlements;\n\t\t\t\tINFOPLIST_FILE")
1047                .count(),
1048            2
1049        );
1050        let plist = std::fs::read_to_string(root.join("ios/MyApp/MyApp.entitlements")).unwrap();
1051        assert!(plist.contains(APP_ATTEST_ENTITLEMENT));
1052        assert!(plist.contains("<string>production</string>"));
1053        assert!(!patch_app_attest_entitlement(root, "MyApp").unwrap());
1054        assert_eq!(std::fs::read_to_string(&pbxproj).unwrap(), first);
1055    }
1056
1057    #[test]
1058    fn app_attest_entitlement_follows_offline_id() {
1059        let tmp = tempfile::tempdir().unwrap();
1060        std::fs::write(
1061            tmp.path().join("package.json"),
1062            r#"{"dependencies":{"react-native":"0.85.2"}}"#,
1063        )
1064        .unwrap();
1065        assert!(!uses_offline_id(tmp.path()));
1066        std::fs::write(
1067            tmp.path().join("package.json"),
1068            r#"{"dependencies":{"@offline-protocol/id-react-native":"^0.4.0"}}"#,
1069        )
1070        .unwrap();
1071        assert!(uses_offline_id(tmp.path()));
1072    }
1073
1074    #[test]
1075    fn rn_module_name_pascal_cases_slug() {
1076        assert_eq!(rn_module_name("my-offline-app"), "MyOfflineApp");
1077        assert_eq!(rn_module_name("myapp"), "Myapp");
1078        assert_eq!(rn_module_name("my_app"), "My_app");
1079    }
1080
1081    #[test]
1082    fn patch_android_mesh_permissions_is_idempotent() {
1083        let tmp = tempfile::tempdir().unwrap();
1084        let manifest = tmp.path().join("AndroidManifest.xml");
1085        std::fs::write(
1086            &manifest,
1087            r#"<manifest xmlns:android="http://schemas.android.com/apk/res/android">
1088    <uses-permission android:name="android.permission.INTERNET" />
1089    <application android:name=".MainApplication" />
1090</manifest>"#,
1091        )
1092        .unwrap();
1093        patch_android_mesh_permissions(&manifest).unwrap();
1094        let first = std::fs::read_to_string(&manifest).unwrap();
1095        assert!(first.contains("BLUETOOTH_SCAN"));
1096        patch_android_mesh_permissions(&manifest).unwrap();
1097        let second = std::fs::read_to_string(&manifest).unwrap();
1098        assert_eq!(
1099            first.matches("BLUETOOTH_SCAN").count(),
1100            second.matches("BLUETOOTH_SCAN").count()
1101        );
1102    }
1103
1104    #[test]
1105    fn patch_android_network_binding_permissions_is_idempotent() {
1106        let tmp = tempfile::tempdir().unwrap();
1107        let manifest = tmp.path().join("AndroidManifest.xml");
1108        std::fs::write(
1109            &manifest,
1110            r#"<manifest xmlns:android="http://schemas.android.com/apk/res/android">
1111    <uses-permission android:name="android.permission.INTERNET" />
1112    <application android:name=".MainApplication" />
1113</manifest>"#,
1114        )
1115        .unwrap();
1116        patch_android_network_binding_permissions(&manifest).unwrap();
1117        let first = std::fs::read_to_string(&manifest).unwrap();
1118        assert!(first.contains("ACCESS_NETWORK_STATE"));
1119        assert!(first.contains("CHANGE_NETWORK_STATE"));
1120        patch_android_network_binding_permissions(&manifest).unwrap();
1121        let second = std::fs::read_to_string(&manifest).unwrap();
1122        assert_eq!(
1123            first.matches("ACCESS_NETWORK_STATE").count(),
1124            second.matches("ACCESS_NETWORK_STATE").count()
1125        );
1126    }
1127
1128    #[test]
1129    fn patch_main_application_adds_network_binding_package() {
1130        let tmp = tempfile::tempdir().unwrap();
1131        let main = tmp.path().join("MainApplication.kt");
1132        std::fs::write(
1133            &main,
1134            r#"package com.example
1135
1136class MainApplication {
1137  val packages =
1138    PackageList(this).packages.apply {
1139          // placeholder
1140        }
1141}
1142"#,
1143        )
1144        .unwrap();
1145        patch_main_application_for_network_binding(tmp.path()).unwrap();
1146        let content = std::fs::read_to_string(&main).unwrap();
1147        assert!(content.contains("add(NetworkBindingPackage())"));
1148        patch_main_application_for_network_binding(tmp.path()).unwrap();
1149        assert_eq!(content.matches("NetworkBindingPackage").count(), 1);
1150    }
1151
1152    #[test]
1153    fn patch_mesh_ios_podfile_strips_legacy_manual_mesh_sdk_pod() {
1154        let tmp = tempfile::tempdir().unwrap();
1155        let podfile = tmp.path().join("Podfile");
1156        std::fs::write(
1157            &podfile,
1158            "target 'App' do\n  config = use_native_modules!\n  pod 'MeshSdk', :path => '../node_modules/@offline-protocol/mesh-sdk/ios'\n  use_react_native!\nend\n",
1159        )
1160        .unwrap();
1161        patch_mesh_ios_podfile(&podfile).unwrap();
1162        let content = std::fs::read_to_string(&podfile).unwrap();
1163        assert!(!content.contains("MeshSdk"));
1164        patch_mesh_ios_podfile(&podfile).unwrap();
1165        assert!(!content.contains("MeshSdk"));
1166    }
1167
1168    #[test]
1169    fn patch_mesh_ios_podfile_build_settings_is_idempotent() {
1170        let tmp = tempfile::tempdir().unwrap();
1171        let podfile = tmp.path().join("Podfile");
1172        std::fs::write(
1173            &podfile,
1174            r#"target 'App' do
1175  post_install do |installer|
1176    react_native_post_install(
1177      installer,
1178      config[:reactNativePath],
1179      :mac_catalyst_enabled => false,
1180    )
1181  end
1182end
1183"#,
1184        )
1185        .unwrap();
1186        patch_mesh_ios_podfile_build_settings(&podfile).unwrap();
1187        let first = std::fs::read_to_string(&podfile).unwrap();
1188        assert!(first.contains("FMT_USE_CONSTEVAL"));
1189        patch_mesh_ios_podfile_build_settings(&podfile).unwrap();
1190        assert_eq!(first, std::fs::read_to_string(&podfile).unwrap());
1191    }
1192
1193    #[test]
1194    fn rewrite_shell_identity_renames_paths_and_contents() {
1195        let tmp = tempfile::tempdir().unwrap();
1196        let root = tmp.path();
1197        let ios_dir = root.join("ios").join(CACHE_MODULE);
1198        let java_dir = root
1199            .join("android/app/src/main/java/com")
1200            .join(CACHE_MODULE.to_ascii_lowercase());
1201        std::fs::create_dir_all(&ios_dir).unwrap();
1202        std::fs::create_dir_all(&java_dir).unwrap();
1203        std::fs::write(
1204            ios_dir.join("AppDelegate.swift"),
1205            format!("// module {CACHE_MODULE}\npackage com.offlineshell\n"),
1206        )
1207        .unwrap();
1208        std::fs::write(
1209            java_dir.join("MainApplication.kt"),
1210            "package com.offlineshell\nclass MainApplication\n",
1211        )
1212        .unwrap();
1213
1214        rewrite_shell_identity(root, "MyOfflineApp").unwrap();
1215
1216        assert!(root.join("ios/MyOfflineApp/AppDelegate.swift").is_file());
1217        assert!(root
1218            .join("android/app/src/main/java/com/myofflineapp/MainApplication.kt")
1219            .is_file());
1220        let swift =
1221            std::fs::read_to_string(root.join("ios/MyOfflineApp/AppDelegate.swift")).unwrap();
1222        assert!(swift.contains("MyOfflineApp"));
1223        assert!(swift.contains("com.myofflineapp"));
1224        assert!(!swift.contains(CACHE_MODULE));
1225        let kt = std::fs::read_to_string(
1226            root.join("android/app/src/main/java/com/myofflineapp/MainApplication.kt"),
1227        )
1228        .unwrap();
1229        assert!(kt.contains("package com.myofflineapp"));
1230    }
1231}