Modern Apps git

← Modern-Apps.git

euicc: add profile download (ES9+/SM-DP+) with QR and activation code

Commit
e083ed29cbda06152a08cd37b8aae3f8c996e55d
Author
Vayun Mathur <[email protected]>
When
2026-08-12 16:41 UTC (3 months ago)
Parents
f13ce74

Diff

Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 47f64ec765..0b75b74e14 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -591,6 +591,7 @@ name = "euicc" version = "0.1.0" dependencies = [  "jni",+ "jni_http",  "log",  "serde_json", ]
euicc/build.gradle.kts
diff --git a/euicc/build.gradle.kts b/euicc/build.gradle.ktsindex 3825a5cb11..e3f8619d1b 100644--- a/euicc/build.gradle.kts+++ b/euicc/build.gradle.kts@@ -33,4 +33,10 @@ dependencies {     implementation(project(":library:network"))     // Local per-profile nicknames / prefs.     implementation(libs.androidx.datastore.preferences)+    // QR activation-code scanning (CameraX preview + ZXing decode).+    implementation(libs.androidx.camera.core)+    implementation(libs.androidx.camera.camera2)+    implementation(libs.androidx.camera.lifecycle)+    implementation(libs.androidx.camera.view)+    implementation(libs.zxing.core) }
euicc/src/main/AndroidManifest.xml
diff --git a/euicc/src/main/AndroidManifest.xml b/euicc/src/main/AndroidManifest.xmlindex 905806d231..8d4c10a2f7 100644--- a/euicc/src/main/AndroidManifest.xml+++ b/euicc/src/main/AndroidManifest.xml@@ -5,6 +5,11 @@          privileges or a platform-signed system app holding these permissions. -->     <uses-permission android:name="android.permission.READ_PHONE_STATE" />     <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />+    <!-- Reaching the SM-DP+ for profile download. -->+    <uses-permission android:name="android.permission.INTERNET" />+    <!-- Scanning eSIM activation-code QR codes. -->+    <uses-permission android:name="android.permission.CAMERA" />+    <uses-feature android:name="android.hardware.camera.any" android:required="false" />      <application         android:allowBackup="true"
euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt b/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.ktindex d72f624878..b6cd62d17e 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt@@ -62,4 +62,11 @@ object EuiccNative {      /** Removes the notification with sequence number [seq]. 0 = success, else error / -1. */     external fun nativeRemoveNotification(seq: Int): Int++    /**+     * Runs the full SGP.22 download for an activation code and returns a JSON+     * `{"success":Boolean,"message":String}` string. Must be called while the+     * ISD-R channel is open (inside `withIsdrChannel`).+     */+    external fun nativeDownloadProfile(activationCode: String): String }
euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.ktindex d8419faabc..0c8b6b7e4e 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt@@ -24,6 +24,7 @@ import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.ConfirmDialog+import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconRefresh import com.vayunmathur.library.ui.ListItem@@ -38,10 +39,12 @@ fun EuiccApp(viewModel: EuiccViewModel) {     val state = viewModel.state     var renameTarget by remember { mutableStateOf<Profile?>(null) }     var deleteTarget by remember { mutableStateOf<Profile?>(null) }+    var showDownload by remember { mutableStateOf(false) }      AppScaffold(         title = "EUICC",         actions = {+            IconButton(onClick = { showDownload = true }, enabled = !state.loading) { IconAdd() }             IconButton(onClick = viewModel::reload, enabled = !state.loading) { IconRefresh() }         },     ) { padding ->@@ -55,6 +58,7 @@ fun EuiccApp(viewModel: EuiccViewModel) {         ) {             if (state.loading) CircularProgressIndicator()             state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }+            state.message?.let { Text(it, color = MaterialTheme.colorScheme.primary) }              ProfilesSection(                 profiles = state.profiles,@@ -95,6 +99,52 @@ fun EuiccApp(viewModel: EuiccViewModel) {             onDismiss = { deleteTarget = null },         )     }++    if (showDownload) {+        DownloadDialog(+            onDownload = {+                viewModel.downloadProfile(it)+                showDownload = false+            },+            onDismiss = { showDownload = false },+        )+    }+}++@Composable+private fun DownloadDialog(onDownload: (String) -> Unit, onDismiss: () -> Unit) {+    var code by remember { mutableStateOf("") }+    var scanning by remember { mutableStateOf(false) }++    if (scanning) {+        QrScannerScreen(+            onResult = { code = it; scanning = false },+            onCancel = { scanning = false },+        )+        return+    }++    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text("Download profile") },+        text = {+            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+                OutlinedTextField(+                    value = code,+                    onValueChange = { code = it },+                    label = { Text("Activation code") },+                )+                TextButton(onClick = { scanning = true }) { Text("Scan QR code") }+            }+        },+        confirmButton = {+            TextButton(+                onClick = { if (code.isNotBlank()) onDownload(code.trim()) },+                enabled = code.isNotBlank(),+            ) { Text("Download") }+        },+        dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },+    ) }  @Composable
euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccViewModel.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccViewModel.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccViewModel.ktindex 83714ca386..3de6bc02a2 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccViewModel.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccViewModel.kt@@ -20,12 +20,18 @@ import kotlinx.serialization.json.Json data class EuiccScreenState(     val loading: Boolean = true,     val error: String? = null,+    /** Transient success/info notice (e.g. after a download). */+    val message: String? = null,     val eid: String? = null,     val info: EuiccInfo? = null,     val profiles: List<Profile> = emptyList(),     val notifications: List<Notification> = emptyList(), ) +/** Native download outcome (`{success, message}`). */[email protected]+private data class DownloadResult(val success: Boolean = false, val message: String = "")+ class EuiccViewModel(app: Application) : AndroidViewModel(app) {     private val channelManager = EuiccChannelManager(app)     private val json = Json { ignoreUnknownKeys = true }@@ -39,6 +45,7 @@ class EuiccViewModel(app: Application) : AndroidViewModel(app) {      /** Reads EID, eUICC info, profiles, and notifications in one channel session. */     fun reload() {+        val carryMessage = state.message         state = state.copy(loading = true, error = null)         viewModelScope.launch {             val outcome = withContext(Dispatchers.IO) {@@ -46,6 +53,7 @@ class EuiccViewModel(app: Application) : AndroidViewModel(app) {                     channelManager.withIsdrChannel {                         EuiccScreenState(                             loading = false,+                            message = carryMessage,                             eid = EuiccNative.nativeGetEid(),                             info = EuiccNative.nativeGetEuiccInfo()?.let { json.decodeFromString<EuiccInfo>(it) },                             profiles = EuiccNative.nativeGetProfiles()@@ -62,6 +70,32 @@ class EuiccViewModel(app: Application) : AndroidViewModel(app) {         }     } +    /** Downloads and installs the profile for an activation code, then reloads. */+    fun downloadProfile(activationCode: String) {+        state = state.copy(loading = true, error = null, message = null)+        viewModelScope.launch {+            val outcome = withContext(Dispatchers.IO) {+                runCatching {+                    channelManager.withIsdrChannel { EuiccNative.nativeDownloadProfile(activationCode) }+                }+            }+            outcome.fold(+                onSuccess = { raw ->+                    val result = runCatching { json.decodeFromString<DownloadResult>(raw) }.getOrNull()+                    when {+                        result == null -> state = state.copy(loading = false, error = "Download failed")+                        result.success -> {+                            state = state.copy(message = result.message)+                            reload()+                        }+                        else -> state = state.copy(loading = false, error = result.message)+                    }+                },+                onFailure = { state = state.copy(loading = false, error = it.message ?: "Download failed") },+            )+        }+    }+     fun enable(iccid: String) = action { EuiccNative.nativeEnableProfile(iccid) }     fun disable(iccid: String) = action { EuiccNative.nativeDisableProfile(iccid) }     fun delete(iccid: String) = action { EuiccNative.nativeDeleteProfile(iccid) }
euicc/src/main/java/com/vayunmathur/euicc/ui/QrScanner.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/QrScanner.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/QrScanner.ktnew file mode 100644index 0000000000..d7c280a7fa--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/QrScanner.kt@@ -0,0 +1,152 @@+package com.vayunmathur.euicc.ui++import android.Manifest+import android.content.pm.PackageManager+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.annotation.OptIn as AndroidOptIn+import androidx.camera.core.CameraSelector+import androidx.camera.core.ExperimentalGetImage+import androidx.camera.core.ImageAnalysis+import androidx.camera.core.ImageProxy+import androidx.camera.core.Preview+import androidx.camera.lifecycle.ProcessCameraProvider+import androidx.camera.lifecycle.awaitInstance+import androidx.camera.view.PreviewView+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import androidx.compose.ui.viewinterop.AndroidView+import androidx.core.content.ContextCompat+import androidx.lifecycle.compose.LocalLifecycleOwner+import com.google.zxing.BinaryBitmap+import com.google.zxing.MultiFormatReader+import com.google.zxing.NotFoundException+import com.google.zxing.PlanarYUVLuminanceSource+import com.google.zxing.common.HybridBinarizer+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import java.util.concurrent.Executors++/**+ * Full-screen QR scanner for eSIM activation codes. Requests the camera+ * permission, shows a CameraX preview, and calls [onResult] with the first+ * decoded activation code (a string containing `$`, optionally `LPA:`-prefixed).+ */+@Composable+fun QrScannerScreen(onResult: (String) -> Unit, onCancel: () -> Unit) {+    val context = LocalContext.current+    var hasPermission by remember {+        mutableStateOf(+            ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==+                PackageManager.PERMISSION_GRANTED,+        )+    }+    val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) {+        hasPermission = it+    }+    LaunchedEffect(Unit) {+        if (!hasPermission) launcher.launch(Manifest.permission.CAMERA)+    }++    Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+        if (hasPermission) {+            CameraScanner(onResult = onResult)+        } else {+            Column(+                modifier = Modifier.padding(24.dp),+                verticalArrangement = Arrangement.spacedBy(12.dp),+                horizontalAlignment = Alignment.CenterHorizontally,+            ) {+                Text("Camera permission is required to scan a QR code.")+            }+        }+        Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.BottomCenter) {+            TextButton(onClick = onCancel) { Text("Cancel") }+        }+    }+}++@Composable+private fun CameraScanner(onResult: (String) -> Unit) {+    val context = LocalContext.current+    val lifecycleOwner = LocalLifecycleOwner.current+    val previewView = remember { PreviewView(context) }+    val executor = remember { Executors.newSingleThreadExecutor() }+    var delivered by remember { mutableStateOf(false) }++    DisposableEffect(Unit) { onDispose { executor.shutdown() } }++    LaunchedEffect(Unit) {+        val provider = ProcessCameraProvider.awaitInstance(context)+        val preview = Preview.Builder().build().also { it.surfaceProvider = previewView.surfaceProvider }+        val analysis = ImageAnalysis.Builder()+            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)+            .build()+            .also { analyzer ->+                analyzer.setAnalyzer(executor, QrCodeAnalyzer { text ->+                    if (!delivered && looksLikeActivationCode(text)) {+                        delivered = true+                        ContextCompat.getMainExecutor(context).execute { onResult(text) }+                    }+                })+            }+        runCatching {+            provider.unbindAll()+            provider.bindToLifecycle(+                lifecycleOwner,+                CameraSelector.DEFAULT_BACK_CAMERA,+                preview,+                analysis,+            )+        }+    }++    AndroidView(factory = { previewView }, modifier = Modifier.fillMaxSize())+}++private fun looksLikeActivationCode(text: String): Boolean =+    text.startsWith("LPA:", ignoreCase = true) || text.contains('$')++/** ImageAnalysis analyzer that decodes QR codes with ZXing. */+private class QrCodeAnalyzer(private val onDecoded: (String) -> Unit) : ImageAnalysis.Analyzer {+    private val reader = MultiFormatReader()++    @AndroidOptIn(ExperimentalGetImage::class)+    override fun analyze(imageProxy: ImageProxy) {+        val plane = imageProxy.planes[0]+        val buffer = plane.buffer+        val bytes = ByteArray(buffer.remaining())+        buffer.get(bytes)+        val source = PlanarYUVLuminanceSource(+            bytes,+            plane.rowStride,+            imageProxy.height,+            0, 0,+            imageProxy.width,+            imageProxy.height,+            false,+        )+        val bitmap = BinaryBitmap(HybridBinarizer(source))+        try {+            onDecoded(reader.decodeWithState(bitmap).text)+        } catch (_: NotFoundException) {+        } finally {+            reader.reset()+            imageProxy.close()+        }+    }+}
euicc/src/main/rust/Cargo.toml
diff --git a/euicc/src/main/rust/Cargo.toml b/euicc/src/main/rust/Cargo.tomlindex 30175654d1..1159f873db 100644--- a/euicc/src/main/rust/Cargo.toml+++ b/euicc/src/main/rust/Cargo.toml@@ -16,6 +16,9 @@ crate-type = ["cdylib", "rlib"] jni.workspace = true log.workspace = true serde_json.workspace = true+# Rust reaches the SM-DP+ over HTTP through the flat-framed JNI bridge in+# library:network, so no TLS is linked into libeuicc.so.+jni_http = { path = "../../../../library/jni-http/src/main/rust" }  [profile.release] opt-level = 3
euicc/src/main/rust/src/base64.rs
diff --git a/euicc/src/main/rust/src/base64.rs b/euicc/src/main/rust/src/base64.rsnew file mode 100644index 0000000000..94f86a87bd--- /dev/null+++ b/euicc/src/main/rust/src/base64.rs@@ -0,0 +1,92 @@+//! Minimal standard base64 (RFC 4648) encode/decode.+//!+//! The ES9+ interface exchanges DER blobs as base64 strings inside JSON. This is+//! the only base64 the crate needs, so it is implemented here rather than adding+//! a dependency. Pure and host-testable.++const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";++/// Standard base64 with padding.+pub fn encode(data: &[u8]) -> String {+    let mut out = String::with_capacity((data.len() + 2) / 3 * 4);+    for chunk in data.chunks(3) {+        let b0 = chunk[0] as u32;+        let b1 = *chunk.get(1).unwrap_or(&0) as u32;+        let b2 = *chunk.get(2).unwrap_or(&0) as u32;+        let n = (b0 << 16) | (b1 << 8) | b2;+        out.push(ALPHABET[((n >> 18) & 0x3F) as usize] as char);+        out.push(ALPHABET[((n >> 12) & 0x3F) as usize] as char);+        out.push(if chunk.len() > 1 {+            ALPHABET[((n >> 6) & 0x3F) as usize] as char+        } else {+            '='+        });+        out.push(if chunk.len() > 2 {+            ALPHABET[(n & 0x3F) as usize] as char+        } else {+            '='+        });+    }+    out+}++/// Decodes standard base64, ignoring ASCII whitespace. Returns `None` on invalid input.+pub fn decode(s: &str) -> Option<Vec<u8>> {+    fn val(c: u8) -> Option<u32> {+        match c {+            b'A'..=b'Z' => Some((c - b'A') as u32),+            b'a'..=b'z' => Some((c - b'a' + 26) as u32),+            b'0'..=b'9' => Some((c - b'0' + 52) as u32),+            b'+' => Some(62),+            b'/' => Some(63),+            _ => None,+        }+    }++    let mut buf = 0u32;+    let mut bits = 0;+    let mut out = Vec::with_capacity(s.len() / 4 * 3);+    for &c in s.as_bytes() {+        if c == b'=' || c.is_ascii_whitespace() {+            continue;+        }+        let v = val(c)?;+        buf = (buf << 6) | v;+        bits += 6;+        if bits >= 8 {+            bits -= 8;+            out.push((buf >> bits) as u8);+        }+    }+    Some(out)+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn known_vectors() {+        assert_eq!(encode(b""), "");+        assert_eq!(encode(b"f"), "Zg==");+        assert_eq!(encode(b"fo"), "Zm8=");+        assert_eq!(encode(b"foo"), "Zm9v");+        assert_eq!(encode(b"foobar"), "Zm9vYmFy");+    }++    #[test]+    fn round_trip() {+        let data: Vec<u8> = (0..=255u8).collect();+        assert_eq!(decode(&encode(&data)).unwrap(), data);+    }++    #[test]+    fn decode_ignores_whitespace() {+        assert_eq!(decode("Zm9v\nYmFy").unwrap(), b"foobar");+    }++    #[test]+    fn decode_rejects_bad_chars() {+        assert!(decode("****").is_none());+    }+}
euicc/src/main/rust/src/download.rs
diff --git a/euicc/src/main/rust/src/download.rs b/euicc/src/main/rust/src/download.rsnew file mode 100644index 0000000000..9dccae2a47--- /dev/null+++ b/euicc/src/main/rust/src/download.rs@@ -0,0 +1,131 @@+//! Profile download orchestration (SGP.22 Common Mutual Authentication ++//! Profile Download and Installation).+//!+//! Ties the eUICC-side ES10b commands ([`crate::es10`]) to the SM-DP+-side ES9++//! calls ([`crate::es9p`]). The LPA only relays DER blobs: the eUICC verifies the+//! server, agrees keys, decrypts the Bound Profile Package, and installs it; the+//! SM-DP+ produces the signed material. This module sequences the exchange.+//!+//! The full flow requires a live SM-DP+, a real eUICC, and a platform-signed+//! install, so it cannot be exercised in host tests. Only+//! [`parse_activation_code`] is unit-tested here.++use jni::JNIEnv;++use crate::jni::store_data;+use crate::{es10, es9p};++/// A parsed SGP.22 activation code.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ActivationCode {+    /// SM-DP+ FQDN (no scheme).+    pub smdp: String,+    /// Matching ID for this download.+    pub matching_id: String,+    /// Whether the SM-DP+ requires a confirmation code.+    pub confirmation_code_required: bool,+}++/// Parses `LPA:1$smdp.example.com$MATCHINGID[$OID][$1]` (the `LPA:` prefix and+/// trailing fields are optional).+pub fn parse_activation_code(code: &str) -> Result<ActivationCode, String> {+    let body = code.trim().strip_prefix("LPA:").unwrap_or(code.trim());+    let parts: Vec<&str> = body.split('$').collect();+    if parts.len() < 3 {+        return Err("Activation code must be LPA:1$smdp$matchingId".to_string());+    }+    // parts[0] is the format version ("1").+    let smdp = parts[1].trim();+    let matching_id = parts[2].trim();+    if smdp.is_empty() {+        return Err("Activation code is missing the SM-DP+ address".to_string());+    }+    let confirmation_code_required = parts.get(4).map(|s| *s == "1").unwrap_or(false);+    Ok(ActivationCode {+        smdp: smdp.to_string(),+        matching_id: matching_id.to_string(),+        confirmation_code_required,+    })+}++/// Runs the full download for an activation code, driving the eUICC over the+/// already-open ISD-R channel (via [`store_data`]) and the SM-DP+ over HTTP.+///+/// Confirmation-code-protected profiles are not yet supported; such downloads+/// will be rejected by the eUICC at PrepareDownload.+pub fn download_profile(+    env: &mut JNIEnv,+    activation_code: &str,+) -> Result<es10::InstallResult, String> {+    let ac = parse_activation_code(activation_code)?;++    // 1. eUICC challenge + info for the server's authentication.+    let challenge = es10::parse_euicc_challenge(&store_data(env, &es10::build_get_euicc_challenge())?)?;+    let euicc_info1 = store_data(env, &es10::build_get_euicc_info1())?;++    // 2. Server authentication material.+    let r1 = es9p::initiate_authentication(&ac.smdp, &challenge, &euicc_info1)?;++    // 3. eUICC authenticates the server and signs its own material.+    let ctx = es10::build_ctx_params1(&ac.matching_id, &[0, 0, 0, 0]);+    let auth_req = es10::build_authenticate_server(+        &r1.server_signed1,+        &r1.server_signature1,+        &r1.euicc_ci_pkid,+        &r1.server_certificate,+        &ctx,+    );+    let auth_resp = store_data(env, &auth_req)?;++    // 4. SM-DP+ binds the profile to this eUICC.+    let r2 = es9p::authenticate_client(&ac.smdp, &r1.transaction_id, &auth_resp)?;++    // 5. eUICC prepares to receive the profile.+    let prep_req =+        es10::build_prepare_download(&r2.smdp_signed2, &r2.smdp_signature2, None, &r2.smdp_certificate);+    let prep_resp = store_data(env, &prep_req)?;++    // 6. Fetch the (encrypted) Bound Profile Package.+    let bpp = es9p::get_bound_profile_package(&ac.smdp, &r1.transaction_id, &prep_resp)?;++    // 7. Stream the BPP into the eUICC segment by segment; the last segment+    //    returns the ProfileInstallationResult.+    let segments = es10::segment_bpp(&bpp)?;+    let mut last = Vec::new();+    for segment in &segments {+        last = store_data(env, segment)?;+    }+    let result = es10::parse_install_result(&last)?;++    // 8. Deliver the install notification (best-effort).+    let _ = es9p::handle_notification(&ac.smdp, &result.notification);++    Ok(result)+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn parses_full_activation_code() {+        let ac = parse_activation_code("LPA:1$smdp.example.com$MATCH-123").unwrap();+        assert_eq!(ac.smdp, "smdp.example.com");+        assert_eq!(ac.matching_id, "MATCH-123");+        assert!(!ac.confirmation_code_required);+    }++    #[test]+    fn parses_confirmation_code_flag() {+        let ac = parse_activation_code("1$rsp.truphone.com$QR-ABC$$1").unwrap();+        assert_eq!(ac.smdp, "rsp.truphone.com");+        assert_eq!(ac.matching_id, "QR-ABC");+        assert!(ac.confirmation_code_required);+    }++    #[test]+    fn rejects_short_codes() {+        assert!(parse_activation_code("LPA:1$smdp.example.com").is_err());+        assert!(parse_activation_code("garbage").is_err());+    }+}
euicc/src/main/rust/src/es10.rs
diff --git a/euicc/src/main/rust/src/es10.rs b/euicc/src/main/rust/src/es10.rsindex b1aff6b0df..41a0f14630 100644--- a/euicc/src/main/rust/src/es10.rs+++ b/euicc/src/main/rust/src/es10.rs@@ -44,6 +44,30 @@ const TAG_NOTIFICATION_EVENT: u32 = 0x81; // [1] profileManagementOperation BIT const TAG_NOTIFICATION_ADDRESS: u32 = 0x82; // [2] notificationAddress UTF8String const TAG_REMOVE_NOTIFICATION: u32 = 0xBF30; // ES10b RemoveNotificationFromList +const TAG_GET_EUICC_CHALLENGE: u32 = 0xBF2E; // ES10b GetEUICCChallenge+const TAG_EUICC_CHALLENGE: u32 = 0x80; // [0] euiccChallenge Octet16+const TAG_AUTHENTICATE_SERVER: u32 = 0xBF38; // ES10b AuthenticateServer+const TAG_PREPARE_DOWNLOAD: u32 = 0xBF21; // ES10b PrepareDownload+const TAG_HASH_CC: u32 = 0x04; // hashCc Octet32 (confirmation code)+const TAG_BPP: u32 = 0xBF36; // BoundProfilePackage+const TAG_INITIALISE_SECURE_CHANNEL: u32 = 0xBF23; // initialiseSecureChannelRequest+const TAG_BPP_SEQ_87: u32 = 0xA0; // firstSequenceOf87+const TAG_BPP_SEQ_88: u32 = 0xA1; // sequenceOf88+const TAG_BPP_SEQ_87B: u32 = 0xA2; // secondSequenceOf87+const TAG_BPP_SEQ_86: u32 = 0xA3; // sequenceOf86+const TAG_PROFILE_INSTALL_RESULT: u32 = 0xBF37; // ProfileInstallationResult+const TAG_PIR_DATA: u32 = 0xBF27; // profileInstallationResultData+const TAG_FINAL_RESULT: u32 = 0xA2; // [2] finalResult+const TAG_SUCCESS_RESULT: u32 = 0xA0; // [0] successResult+const TAG_ERROR_RESULT: u32 = 0xA1; // [1] errorResult++// ctxParams1 / DeviceInfo construction tags.+const TAG_CTX_PARAMS_COMMON: u32 = 0xA0; // [0] ctxParamsForCommonAuthentication+const TAG_MATCHING_ID: u32 = 0x80; // [0] matchingId UTF8String+const TAG_DEVICE_INFO: u32 = 0x30; // DeviceInfo SEQUENCE+const TAG_TAC: u32 = 0x80; // [0] tac Octet4+const TAG_DEVICE_CAPS: u32 = 0xA1; // [1] deviceCapabilities SEQUENCE+ /// Parsed subset of EUICCInfo1 useful for display. #[derive(Debug, Clone, PartialEq, Eq)] pub struct EuiccInfo1 {@@ -284,6 +308,133 @@ pub fn parse_remove_result(response: &[u8]) -> Result<i64, String> {     Ok(parse_int(code)) } +// ---------------------------------------------------------------------------+// Download flow (ES10b): challenge, AuthenticateServer, PrepareDownload,+// LoadBoundProfilePackage+// ---------------------------------------------------------------------------++/// Outcome of installing a Bound Profile Package.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct InstallResult {+    pub success: bool,+    pub message: String,+    /// The raw ProfileInstallationResult (BF37) to deliver via HandleNotification.+    pub notification: Vec<u8>,+}++/// Builds the ES10b GetEUICCChallenge request (empty BF2E).+pub fn build_get_euicc_challenge() -> Vec<u8> {+    asn1::tlv(TAG_GET_EUICC_CHALLENGE, &[])+}++/// Parses a GetEUICCChallenge response into the 16-byte challenge.+pub fn parse_euicc_challenge(response: &[u8]) -> Result<Vec<u8>, String> {+    let body = asn1::find(response, TAG_GET_EUICC_CHALLENGE).ok_or("GetEUICCChallenge: missing BF2E")?;+    let challenge = asn1::find(body, TAG_EUICC_CHALLENGE).ok_or("GetEUICCChallenge: missing challenge")?;+    Ok(challenge.to_vec())+}++/// Builds ctxParams1 for common authentication: matchingId + a minimal DeviceInfo.+///+/// `tac` is the 4-byte Type Allocation Code; deviceCapabilities is sent empty.+pub fn build_ctx_params1(matching_id: &str, tac: &[u8; 4]) -> Vec<u8> {+    let mut device_info_val = asn1::tlv(TAG_TAC, tac);+    device_info_val.extend(asn1::tlv(TAG_DEVICE_CAPS, &[])); // empty DeviceCapabilities+    let device_info = asn1::tlv(TAG_DEVICE_INFO, &device_info_val);++    let mut common = asn1::tlv(TAG_MATCHING_ID, matching_id.as_bytes());+    common.extend(device_info);+    asn1::tlv(TAG_CTX_PARAMS_COMMON, &common)+}++/// Builds the ES10b AuthenticateServer request by concatenating the server blobs+/// (each already a complete DER TLV) with ctxParams1, wrapped in BF38.+pub fn build_authenticate_server(+    server_signed1: &[u8],+    server_signature1: &[u8],+    euicc_ci_pkid: &[u8],+    server_certificate: &[u8],+    ctx_params1: &[u8],+) -> Vec<u8> {+    let mut v = Vec::new();+    v.extend_from_slice(server_signed1);+    v.extend_from_slice(server_signature1);+    v.extend_from_slice(euicc_ci_pkid);+    v.extend_from_slice(server_certificate);+    v.extend_from_slice(ctx_params1);+    asn1::tlv(TAG_AUTHENTICATE_SERVER, &v)+}++/// Builds the ES10b PrepareDownload request from the SM-DP+ blobs (each a+/// complete DER TLV), wrapped in BF21.+pub fn build_prepare_download(+    smdp_signed2: &[u8],+    smdp_signature2: &[u8],+    hash_cc: Option<&[u8]>,+    smdp_certificate: &[u8],+) -> Vec<u8> {+    let mut v = Vec::new();+    v.extend_from_slice(smdp_signed2);+    v.extend_from_slice(smdp_signature2);+    if let Some(cc) = hash_cc {+        v.extend(asn1::tlv(TAG_HASH_CC, cc));+    }+    v.extend_from_slice(smdp_certificate);+    asn1::tlv(TAG_PREPARE_DOWNLOAD, &v)+}++/// Segments a Bound Profile Package (BF36) into the ordered list of TLVs the LPA+/// must transmit to the eUICC via STORE DATA: the initialiseSecureChannelRequest+/// followed by each element of the 87/88/87/86 sequences.+pub fn segment_bpp(bpp: &[u8]) -> Result<Vec<Vec<u8>>, String> {+    let body = asn1::find(bpp, TAG_BPP).ok_or("BoundProfilePackage: missing BF36")?;+    let mut segments = Vec::new();+    for child in asn1::children(body).ok_or("BoundProfilePackage: malformed")? {+        match child.tag {+            TAG_INITIALISE_SECURE_CHANNEL => {+                segments.push(asn1::tlv(child.tag, child.value));+            }+            TAG_BPP_SEQ_87 | TAG_BPP_SEQ_88 | TAG_BPP_SEQ_87B | TAG_BPP_SEQ_86 => {+                for element in asn1::children(child.value).ok_or("BPP: malformed sequence")? {+                    segments.push(asn1::tlv(element.tag, element.value));+                }+            }+            other => {+                // Unknown top-level element: forward it verbatim to be safe.+                segments.push(asn1::tlv(other, child.value));+            }+        }+    }+    Ok(segments)+}++/// Parses a ProfileInstallationResult (BF37) into an [`InstallResult`].+pub fn parse_install_result(response: &[u8]) -> Result<InstallResult, String> {+    let body = asn1::find(response, TAG_PROFILE_INSTALL_RESULT)+        .ok_or("ProfileInstallationResult: missing BF37")?;+    let data = asn1::find(body, TAG_PIR_DATA).ok_or("ProfileInstallationResult: missing BF27")?;+    let final_result = asn1::find(data, TAG_FINAL_RESULT)+        .ok_or("ProfileInstallationResult: missing finalResult")?;++    let (success, message) = if asn1::find(final_result, TAG_SUCCESS_RESULT).is_some() {+        (true, "Profile installed".to_string())+    } else if let Some(err) = asn1::find(final_result, TAG_ERROR_RESULT) {+        // errorResult ::= SEQUENCE { bppCommandId INTEGER, errorReason ENUMERATED, ... }+        let reason = asn1::children(err)+            .and_then(|kids| kids.get(1).map(|k| parse_int(k.value)))+            .unwrap_or(-1);+        (false, format!("Install failed (errorReason {reason})"))+    } else {+        (false, "Install failed (unknown result)".to_string())+    };++    Ok(InstallResult {+        success,+        message,+        notification: response.to_vec(),+    })+}+ // --------------------------------------------------------------------------- // Helpers // ---------------------------------------------------------------------------@@ -522,4 +673,72 @@ mod tests {         assert_eq!(notes[0].operation, "enable");         assert_eq!(notes[0].address, "smdp.example.com");     }++    #[test]+    fn euicc_challenge_roundtrip() {+        assert_eq!(build_get_euicc_challenge(), vec![0xBF, 0x2E, 0x00]);+        let challenge = [0x11u8; 16];+        let inner = asn1::tlv(TAG_EUICC_CHALLENGE, &challenge);+        let resp = asn1::tlv(TAG_GET_EUICC_CHALLENGE, &inner);+        assert_eq!(parse_euicc_challenge(&resp).unwrap(), challenge.to_vec());+    }++    #[test]+    fn ctx_params1_shape() {+        let ctx = build_ctx_params1("MID-123", &[0, 0, 0, 0]);+        // A0 { 80 <mid> 30 { 80 04 <tac> A1 00 } }+        let common = asn1::find(&ctx, TAG_CTX_PARAMS_COMMON).unwrap();+        assert_eq!(asn1::find(common, TAG_MATCHING_ID).unwrap(), b"MID-123");+        let di = asn1::find(common, TAG_DEVICE_INFO).unwrap();+        assert_eq!(asn1::find(di, TAG_TAC).unwrap(), &[0, 0, 0, 0]);+        assert_eq!(asn1::find(di, TAG_DEVICE_CAPS).unwrap(), &[] as &[u8]);+    }++    #[test]+    fn authenticate_server_concatenates_blobs() {+        let req = build_authenticate_server(&[0x30, 0x01, 0xAA], &[0x5F, 0x37, 0x01, 0xBB], &[0x04, 0x01, 0xCC], &[0x30, 0x01, 0xDD], &[0xA0, 0x00]);+        let body = asn1::find(&req, TAG_AUTHENTICATE_SERVER).unwrap();+        assert_eq!(body, &[0x30, 0x01, 0xAA, 0x5F, 0x37, 0x01, 0xBB, 0x04, 0x01, 0xCC, 0x30, 0x01, 0xDD, 0xA0, 0x00]);+    }++    #[test]+    fn segment_bpp_orders_elements() {+        let isc = asn1::tlv(TAG_INITIALISE_SECURE_CHANNEL, &[0x01]);+        let seq87 = asn1::tlv(TAG_BPP_SEQ_87, &asn1::tlv(0x87, &[0x11, 0x22]));+        let mut seq88_inner = asn1::tlv(0x88, &[0x33]);+        seq88_inner.extend(asn1::tlv(0x88, &[0x44]));+        let seq88 = asn1::tlv(TAG_BPP_SEQ_88, &seq88_inner);+        let seq86 = asn1::tlv(TAG_BPP_SEQ_86, &asn1::tlv(0x86, &[0x55]));+        let mut body = Vec::new();+        body.extend(isc);+        body.extend(seq87);+        body.extend(seq88);+        body.extend(seq86);+        let bpp = asn1::tlv(TAG_BPP, &body);++        let segments = segment_bpp(&bpp).unwrap();+        assert_eq!(segments.len(), 5); // BF23, 87, 88, 88, 86+        assert_eq!(segments[0], vec![0xBF, 0x23, 0x01, 0x01]);+        assert_eq!(segments[1], vec![0x87, 0x02, 0x11, 0x22]);+        assert_eq!(segments[2], vec![0x88, 0x01, 0x33]);+        assert_eq!(segments[3], vec![0x88, 0x01, 0x44]);+        assert_eq!(segments[4], vec![0x86, 0x01, 0x55]);+    }++    #[test]+    fn install_result_success_and_error() {+        let ok_final = asn1::tlv(TAG_FINAL_RESULT, &asn1::tlv(TAG_SUCCESS_RESULT, &[]));+        let ok_data = asn1::tlv(TAG_PIR_DATA, &ok_final);+        let ok = asn1::tlv(TAG_PROFILE_INSTALL_RESULT, &ok_data);+        assert!(parse_install_result(&ok).unwrap().success);++        let mut err_inner = asn1::tlv(TAG_RESULT, &[0x00]); // bppCommandId+        err_inner.extend(asn1::tlv(0x81, &[0x05])); // errorReason = 5+        let err_final = asn1::tlv(TAG_FINAL_RESULT, &asn1::tlv(TAG_ERROR_RESULT, &err_inner));+        let err_data = asn1::tlv(TAG_PIR_DATA, &err_final);+        let err = asn1::tlv(TAG_PROFILE_INSTALL_RESULT, &err_data);+        let r = parse_install_result(&err).unwrap();+        assert!(!r.success);+        assert!(r.message.contains('5'));+    } }
euicc/src/main/rust/src/es9p.rs
diff --git a/euicc/src/main/rust/src/es9p.rs b/euicc/src/main/rust/src/es9p.rsnew file mode 100644index 0000000000..7c232e7207--- /dev/null+++ b/euicc/src/main/rust/src/es9p.rs@@ -0,0 +1,221 @@+//! ES9+ SM-DP+ orchestration (SGP.22 §5.6).+//!+//! The LPA relays DER blobs between the eUICC and the SM-DP+ over HTTPS. Each+//! call is an HTTP POST of a small JSON object whose binary members are base64+//! DER; the SM-DP+ replies with JSON in the same shape. Networking goes through+//! the `library:network` JNI bridge ([`jni_http`]), so no TLS is linked here.+//!+//! The eUICC performs all SGP.22 cryptography (signature generation/verification,+//! key agreement, and Bound Profile Package decryption); this module never+//! inspects or transforms the blobs it forwards.+//!+//! The HTTP calls require a live SM-DP+ and cannot be exercised in host tests;+//! only the pure URL/JSON helpers are unit-tested.++use serde_json::{json, Value};++use crate::base64;++const ES9P_PATH: &str = "/gsma/rsp2/es9plus/";++/// Result of ES9+.InitiateAuthentication.+pub struct InitiateAuthResult {+    pub transaction_id: String,+    pub server_signed1: Vec<u8>,+    pub server_signature1: Vec<u8>,+    pub euicc_ci_pkid: Vec<u8>,+    pub server_certificate: Vec<u8>,+}++/// Result of ES9+.AuthenticateClient.+pub struct AuthenticateClientResult {+    pub smdp_signed2: Vec<u8>,+    pub smdp_signature2: Vec<u8>,+    pub smdp_certificate: Vec<u8>,+}++/// InitiateAuthentication: sends the eUICC challenge + info; gets the server's+/// signed authentication material.+pub fn initiate_authentication(+    smdp: &str,+    euicc_challenge: &[u8],+    euicc_info1: &[u8],+) -> Result<InitiateAuthResult, String> {+    let body = json!({+        "smdpAddress": host_of(smdp),+        "euiccChallenge": base64::encode(euicc_challenge),+        "euiccInfo1": base64::encode(euicc_info1),+    });+    let v = post(&endpoint(smdp, "initiateAuthentication"), &body)?;+    Ok(InitiateAuthResult {+        transaction_id: get_str(&v, "transactionId")?,+        server_signed1: get_b64(&v, "serverSigned1")?,+        server_signature1: get_b64(&v, "serverSignature1")?,+        euicc_ci_pkid: get_b64(&v, "euiccCiPKIdToBeUsed")?,+        server_certificate: get_b64(&v, "serverCertificate")?,+    })+}++/// AuthenticateClient: forwards the eUICC's AuthenticateServer response; gets the+/// SM-DP+'s signed profile-binding material.+pub fn authenticate_client(+    smdp: &str,+    transaction_id: &str,+    authenticate_server_response: &[u8],+) -> Result<AuthenticateClientResult, String> {+    let body = json!({+        "transactionId": transaction_id,+        "authenticateServerResponse": base64::encode(authenticate_server_response),+    });+    let v = post(&endpoint(smdp, "authenticateClient"), &body)?;+    Ok(AuthenticateClientResult {+        smdp_signed2: get_b64(&v, "smdpSigned2")?,+        smdp_signature2: get_b64(&v, "smdpSignature2")?,+        smdp_certificate: get_b64(&v, "smdpCertificate")?,+    })+}++/// GetBoundProfilePackage: forwards the eUICC's PrepareDownload response; gets the+/// encrypted Bound Profile Package.+pub fn get_bound_profile_package(+    smdp: &str,+    transaction_id: &str,+    prepare_download_response: &[u8],+) -> Result<Vec<u8>, String> {+    let body = json!({+        "transactionId": transaction_id,+        "prepareDownloadResponse": base64::encode(prepare_download_response),+    });+    let v = post(&endpoint(smdp, "getBoundProfilePackage"), &body)?;+    get_b64(&v, "boundProfilePackage")+}++/// HandleNotification: delivers a pending notification to the SM-DP+. Best-effort;+/// the eUICC keeps the notification until acknowledged, so a failure is not fatal.+pub fn handle_notification(smdp: &str, pending_notification: &[u8]) -> Result<(), String> {+    let body = json!({ "pendingNotification": base64::encode(pending_notification) });+    // A 204/empty body is normal here; ignore the parsed value.+    let _ = post(&endpoint(smdp, "handleNotification"), &body)?;+    Ok(())+}++// ---------------------------------------------------------------------------+// HTTP + helpers+// ---------------------------------------------------------------------------++fn post(url: &str, body: &Value) -> Result<Value, String> {+    let headers = [+        ("Content-Type".to_string(), "application/json".to_string()),+        ("X-Admin-Protocol".to_string(), "gsma/rsp/v2.2.0".to_string()),+        ("User-Agent".to_string(), "gsma-rsp-lpad".to_string()),+        ("Accept".to_string(), "application/json".to_string()),+    ];+    let bytes = serde_json::to_vec(body).map_err(|e| format!("encode body: {e}"))?;+    let resp = jni_http::request(jni_http::Method::Post, url, &headers, Some(&bytes))+        .map_err(|e| format!("{e}"))?;+    if resp.status < 200 || resp.status >= 300 {+        return Err(format!("SM-DP+ HTTP {} at {url}", resp.status));+    }+    if resp.body.is_empty() {+        return Ok(Value::Null);+    }+    let v: Value = serde_json::from_slice(&resp.body).map_err(|e| format!("parse response: {e}"))?;+    check_function_execution_status(&v)?;+    Ok(v)+}++/// Surfaces an SM-DP+ ES9+ functionExecutionStatus error, if present.+fn check_function_execution_status(v: &Value) -> Result<(), String> {+    let status = v+        .get("header")+        .and_then(|h| h.get("functionExecutionStatus"));+    if let Some(status) = status {+        let state = status.get("status").and_then(Value::as_str).unwrap_or("");+        if !state.is_empty() && state != "Executed-Success" {+            let reason = status+                .get("statusCodeData")+                .and_then(|d| d.get("reasonCode"))+                .and_then(Value::as_str)+                .unwrap_or("unknown");+            return Err(format!("SM-DP+ {state} ({reason})"));+        }+    }+    Ok(())+}++/// Builds the full ES9+ endpoint URL for a function.+fn endpoint(smdp: &str, function: &str) -> String {+    format!("{}{ES9P_PATH}{function}", base_url(smdp))+}++/// Normalizes an SM-DP+ address into an `https://host[:port]` base URL.+fn base_url(smdp: &str) -> String {+    let s = smdp.trim().trim_end_matches('/');+    if s.starts_with("http://") || s.starts_with("https://") {+        s.to_string()+    } else {+        format!("https://{s}")+    }+}++/// The bare host[:port] the SM-DP+ expects in `smdpAddress`.+fn host_of(smdp: &str) -> String {+    smdp.trim()+        .trim_start_matches("https://")+        .trim_start_matches("http://")+        .trim_end_matches('/')+        .to_string()+}++fn get_str(v: &Value, key: &str) -> Result<String, String> {+    v.get(key)+        .and_then(Value::as_str)+        .map(str::to_string)+        .ok_or_else(|| format!("SM-DP+ response missing '{key}'"))+}++fn get_b64(v: &Value, key: &str) -> Result<Vec<u8>, String> {+    let s = get_str(v, key)?;+    base64::decode(&s).ok_or_else(|| format!("SM-DP+ '{key}' is not valid base64"))+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn endpoint_urls() {+        assert_eq!(+            endpoint("smdp.example.com", "initiateAuthentication"),+            "https://smdp.example.com/gsma/rsp2/es9plus/initiateAuthentication",+        );+        assert_eq!(+            endpoint("https://rsp.truphone.com/", "authenticateClient"),+            "https://rsp.truphone.com/gsma/rsp2/es9plus/authenticateClient",+        );+    }++    #[test]+    fn host_normalization() {+        assert_eq!(host_of("https://smdp.example.com/"), "smdp.example.com");+        assert_eq!(host_of("smdp.example.com"), "smdp.example.com");+    }++    #[test]+    fn extract_b64_field() {+        let v = json!({ "serverSigned1": base64::encode(&[1u8, 2, 3]) });+        assert_eq!(get_b64(&v, "serverSigned1").unwrap(), vec![1, 2, 3]);+        assert!(get_b64(&v, "missing").is_err());+    }++    #[test]+    fn function_status_error_is_surfaced() {+        let v = json!({+            "header": { "functionExecutionStatus": {+                "status": "Failed",+                "statusCodeData": { "reasonCode": "8.1.1" }+            }}+        });+        assert!(check_function_execution_status(&v).is_err());+    }+}
euicc/src/main/rust/src/jni.rs
diff --git a/euicc/src/main/rust/src/jni.rs b/euicc/src/main/rust/src/jni.rsindex 04248b0877..ff2fea1408 100644--- a/euicc/src/main/rust/src/jni.rs+++ b/euicc/src/main/rust/src/jni.rs@@ -48,7 +48,7 @@ fn transmit_apdu(env: &mut JNIEnv, apdu: &[u8]) -> Result<Vec<u8>, String> { /// Sends an ES10 command TLV to the ISD-R via GlobalPlatform STORE DATA, /// splitting into ≤255-byte blocks, and returns the final response TLV with the /// trailing `90 00` status stripped.-fn store_data(env: &mut JNIEnv, command: &[u8]) -> Result<Vec<u8>, String> {+pub(crate) fn store_data(env: &mut JNIEnv, command: &[u8]) -> Result<Vec<u8>, String> {     // A zero-length command still sends one (empty) block.     let blocks: Vec<&[u8]> = if command.is_empty() {         vec![&command[0..0]]@@ -232,6 +232,30 @@ pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeRemoveNotifi     } } +/// `nativeDownloadProfile(activationCode)` — runs the full SGP.22 download for+/// an activation code and returns a JSON `{success, message}` string. Must be+/// called while the ISD-R channel is open (inside `withIsdrChannel`).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeDownloadProfile<'l>(+    mut env: JNIEnv<'l>,+    _class: JClass<'l>,+    activation_code: JString<'l>,+) -> jstring {+    // Resolve the HTTP bridge (library:network) once; harmless if already done.+    jni_http::init(&mut env);++    let Some(code) = read_string(&mut env, &activation_code) else {+        let json = serde_json::json!({ "success": false, "message": "Invalid activation code" });+        return new_jstring(&env, &json.to_string());+    };++    let json = match crate::download::download_profile(&mut env, &code) {+        Ok(result) => serde_json::json!({ "success": result.success, "message": result.message }),+        Err(message) => serde_json::json!({ "success": false, "message": message }),+    };+    new_jstring(&env, &json.to_string())+}+ /// `nativeVersion()` — native core version string. #[no_mangle] pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeVersion<'l>(
euicc/src/main/rust/src/lib.rs
diff --git a/euicc/src/main/rust/src/lib.rs b/euicc/src/main/rust/src/lib.rsindex 232718173b..e82520ffdd 100644--- a/euicc/src/main/rust/src/lib.rs+++ b/euicc/src/main/rust/src/lib.rs@@ -13,10 +13,14 @@ //! (GPL-3.0-only). Ported files carry attribution in their own headers. //! //! Phase 3 adds the ASN.1 + ES10 (local ISD-R) layers and the STORE DATA-//! transport; the ES9+/SM-DP+ and crypto modules land in later phases.+//! transport; Phase 4 adds profile management; Phase 5 adds the ES9+/SM-DP++//! orchestration and the profile download/install flow.  mod asn1;+mod base64;+mod download; mod es10;+mod es9p; mod jni;  /// Version string reported by the native core.