feat(companion): embedded FIPS mesh replaces WireGuard for remote access
- Android/rust/archy-fips-core: leaf-only fips node as a JNI cdylib (fips pinned to the fips-native fork rev with VpnService fd support), built by gradle via cargo-ndk (arm64), tested on host - ArchyVpnService: split-tunnel VpnService routing only fd00::/8 (MTU 1280, foreground specialUse); FipsManager handles the one-time VPN consent and silent auto-start — no settings surface at all - pairing QR now fully configures the mesh: fnpub/fip/fhost/fudp/ftcp plus fanchors (the node's seed-anchor list, npub@addr/transport) so the phone can rendezvous through public anchors when the LAN endpoint is unreachable - default seed anchors gain the two dual-transport join.fips.network test anchors (23.182.128.74:443/tcp, 217.77.8.91:443/tcp); anchor adverts are Nostr kind-37195 events - device token rides the password field end-to-end: backend accepts tokens wherever it accepts the password, so scan = instant login (WebSocket auth + WebView form injection unchanged); token logins skip TOTP - ServerEntry.meshIp + IPv6-bracketed URLs; WebView retries the mesh address on main-frame errors, auto-login and origin checks honor it - companion v0.5.0 (versionCode 20), arm64 abiFilter; FipsNative.available gates everything so non-arm64 still runs as a plain companion Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,12 +11,17 @@ android {
|
||||
applicationId = "com.archipelago.app"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 19
|
||||
versionName = "0.4.15"
|
||||
versionCode = 20
|
||||
versionName = "0.5.0"
|
||||
|
||||
vectorDrawables {
|
||||
useSupportLibrary = true
|
||||
}
|
||||
|
||||
// The embedded FIPS mesh (libarchy_fips_core.so) is built arm64-only,
|
||||
// matching real handsets. FipsNative.available gates every call, so
|
||||
// the app still runs as a plain companion elsewhere (e.g. x86 emu).
|
||||
ndk { abiFilters += "arm64-v8a" }
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
@@ -80,6 +85,44 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Embedded FIPS mesh: cross-compile Android/rust/archy-fips-core via cargo-ndk
|
||||
// into jniLibs before the native-libs merge, so a plain `gradlew assembleDebug`
|
||||
// builds the Rust too. Requires rustup target aarch64-linux-android, cargo-ndk,
|
||||
// and an NDK (ANDROID_NDK_HOME or the SDK's ndk/ dir).
|
||||
// ---------------------------------------------------------------------------
|
||||
val rustCrateDir = layout.projectDirectory.dir("../rust/archy-fips-core")
|
||||
val jniLibsDir = layout.projectDirectory.dir("src/main/jniLibs")
|
||||
|
||||
tasks.register<Exec>("buildRustArm64") {
|
||||
workingDir = rustCrateDir.asFile
|
||||
inputs.dir(rustCrateDir.dir("src"))
|
||||
inputs.file(rustCrateDir.file("Cargo.toml"))
|
||||
outputs.dir(jniLibsDir)
|
||||
// cargo/cargo-ndk live in ~/.cargo/bin, which Gradle's env may not have.
|
||||
val home = System.getProperty("user.home")
|
||||
environment("PATH", "$home/.cargo/bin:${System.getenv("PATH")}")
|
||||
if (System.getenv("ANDROID_NDK_HOME") == null) {
|
||||
val sdkNdk = file("$home/Library/Android/sdk/ndk")
|
||||
.listFiles()?.maxByOrNull { it.name }
|
||||
if (sdkNdk != null) environment("ANDROID_NDK_HOME", sdkNdk.absolutePath)
|
||||
}
|
||||
commandLine(
|
||||
"cargo", "ndk",
|
||||
"-t", "arm64-v8a",
|
||||
"--platform", "26",
|
||||
"-o", jniLibsDir.asFile.absolutePath,
|
||||
"build", "--release",
|
||||
)
|
||||
}
|
||||
|
||||
tasks.matching {
|
||||
it.name in listOf(
|
||||
"mergeDebugNativeLibs", "mergeReleaseNativeLibs",
|
||||
"mergeDebugJniLibFolders", "mergeReleaseJniLibFolders",
|
||||
)
|
||||
}.configureEach { dependsOn("buildRustArm64") }
|
||||
|
||||
dependencies {
|
||||
val composeBom = platform("androidx.compose:compose-bom:2024.05.00")
|
||||
implementation(composeBom)
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
<!-- Pairing-QR scanner. Camera is optional: manual entry still works without one. -->
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-feature android:name="android.hardware.camera.any" android:required="false" />
|
||||
<!-- Embedded FIPS mesh tunnel (ArchyVpnService) runs as a foreground service. -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
|
||||
<application
|
||||
android:name=".ArchipelagoApp"
|
||||
@@ -39,6 +43,21 @@
|
||||
<data android:scheme="archipelago" android:host="pair" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- Embedded FIPS mesh node: split-tunnel VpnService (fd00::/8 only),
|
||||
configured entirely by scanning the node's pairing QR. -->
|
||||
<service
|
||||
android:name=".fips.ArchyVpnService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="specialUse"
|
||||
android:permission="android.permission.BIND_VPN_SERVICE">
|
||||
<property
|
||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="mesh-vpn-tunnel" />
|
||||
<intent-filter>
|
||||
<action android:name="android.net.VpnService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
|
||||
@@ -19,25 +19,35 @@ data class ServerEntry(
|
||||
val port: String = "",
|
||||
val password: String = "",
|
||||
val name: String = "",
|
||||
/** Node's FIPS mesh ULA (IPv6) — reachable from anywhere once meshed. */
|
||||
val meshIp: String = "",
|
||||
) {
|
||||
/** Label to show in lists — the user-given name, or the address if unnamed. */
|
||||
fun displayName(): String = name.ifBlank { address }
|
||||
|
||||
/** Bracket bare IPv6 literals (the mesh ULA) so they form valid URLs. */
|
||||
private fun urlHost(host: String): String =
|
||||
if (host.contains(":") && !host.startsWith("[")) "[$host]" else host
|
||||
|
||||
fun toUrl(): String {
|
||||
val scheme = if (useHttps) "https" else "http"
|
||||
val portSuffix = if (port.isNotBlank()) ":$port" else ""
|
||||
return "$scheme://$address$portSuffix"
|
||||
return "$scheme://${urlHost(address)}$portSuffix"
|
||||
}
|
||||
|
||||
fun toWsUrl(): String {
|
||||
val scheme = if (useHttps) "wss" else "ws"
|
||||
val portSuffix = if (port.isNotBlank()) ":$port" else ""
|
||||
return "$scheme://$address$portSuffix"
|
||||
return "$scheme://${urlHost(address)}$portSuffix"
|
||||
}
|
||||
|
||||
// name is the trailing field so entries saved before naming existed
|
||||
// (4 fields) still deserialize, with name defaulting to "".
|
||||
fun serialize(): String = "$address|$useHttps|$port|$password|$name"
|
||||
/** Mesh-address UI URL, or null when the node never advertised one. */
|
||||
fun toMeshUrl(): String? =
|
||||
meshIp.takeIf { it.isNotBlank() }?.let { "http://${urlHost(it)}" }
|
||||
|
||||
// name/meshIp are trailing fields so entries saved before they existed
|
||||
// (4/5 fields) still deserialize, defaulting to "".
|
||||
fun serialize(): String = "$address|$useHttps|$port|$password|$name|$meshIp"
|
||||
|
||||
companion object {
|
||||
fun deserialize(raw: String): ServerEntry? {
|
||||
@@ -49,6 +59,7 @@ data class ServerEntry(
|
||||
port = parts.getOrElse(2) { "" },
|
||||
password = parts.getOrElse(3) { "" },
|
||||
name = parts.getOrElse(4) { "" },
|
||||
meshIp = parts.getOrElse(5) { "" },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -61,6 +72,7 @@ class ServerPreferences(private val context: Context) {
|
||||
private val activePortKey = stringPreferencesKey("active_port")
|
||||
private val activePasswordKey = stringPreferencesKey("active_password")
|
||||
private val activeNameKey = stringPreferencesKey("active_name")
|
||||
private val activeMeshIpKey = stringPreferencesKey("active_mesh_ip")
|
||||
private val savedServersKey = stringSetPreferencesKey("saved_servers")
|
||||
private val introSeenKey = booleanPreferencesKey("intro_seen")
|
||||
|
||||
@@ -72,6 +84,7 @@ class ServerPreferences(private val context: Context) {
|
||||
port = prefs[activePortKey] ?: "",
|
||||
password = prefs[activePasswordKey] ?: "",
|
||||
name = prefs[activeNameKey] ?: "",
|
||||
meshIp = prefs[activeMeshIpKey] ?: "",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -91,6 +104,7 @@ class ServerPreferences(private val context: Context) {
|
||||
prefs[activePortKey] = server.port
|
||||
prefs[activePasswordKey] = server.password
|
||||
prefs[activeNameKey] = server.name
|
||||
prefs[activeMeshIpKey] = server.meshIp
|
||||
}
|
||||
addSavedServer(server)
|
||||
}
|
||||
@@ -102,6 +116,7 @@ class ServerPreferences(private val context: Context) {
|
||||
prefs.remove(activePortKey)
|
||||
prefs.remove(activePasswordKey)
|
||||
prefs.remove(activeNameKey)
|
||||
prefs.remove(activeMeshIpKey)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,6 +154,7 @@ class ServerPreferences(private val context: Context) {
|
||||
prefs[activePortKey] = updated.port
|
||||
prefs[activePasswordKey] = updated.password
|
||||
prefs[activeNameKey] = updated.name
|
||||
prefs[activeMeshIpKey] = updated.meshIp
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,6 +178,7 @@ class ServerPreferences(private val context: Context) {
|
||||
merged = server.copy(
|
||||
password = server.password.ifBlank { existing.password },
|
||||
name = server.name.ifBlank { existing.name },
|
||||
meshIp = server.meshIp.ifBlank { existing.meshIp },
|
||||
)
|
||||
}
|
||||
val filtered = current.filterNot { raw ->
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.archipelago.app.data
|
||||
|
||||
import android.net.Uri
|
||||
import com.archipelago.app.fips.AnchorPeer
|
||||
import com.archipelago.app.fips.FipsPairInfo
|
||||
|
||||
/**
|
||||
* Result of parsing a pairing QR / deep link.
|
||||
@@ -10,7 +12,11 @@ import android.net.Uri
|
||||
* user to update the app rather than call the code invalid.
|
||||
*/
|
||||
sealed class PairResult {
|
||||
data class Success(val server: ServerEntry) : PairResult()
|
||||
data class Success(
|
||||
val server: ServerEntry,
|
||||
/** Mesh info when the node advertises FIPS (fnpub present). */
|
||||
val fips: FipsPairInfo? = null,
|
||||
) : PairResult()
|
||||
object UnsupportedVersion : PairResult()
|
||||
object Invalid : PairResult()
|
||||
}
|
||||
@@ -19,13 +25,18 @@ sealed class PairResult {
|
||||
* Parser for the companion pairing QR / OS deep link. Contract:
|
||||
* docs/companion-pairing-qr.md (repo root).
|
||||
*
|
||||
* archipelago://pair?v=1&url=<percent-encoded origin>[&pw=<password>]
|
||||
* archipelago://pair?v=1&url=<origin>&name=…[&tok=…][&pw=…][&fnpub=…&fip=…&fhost=…&fudp=…&ftcp=…]
|
||||
*
|
||||
* - `url` is a full origin including scheme (http for LAN/mDNS nodes, https
|
||||
* for the public demo); trailing slashes are normalized away.
|
||||
* - `pw` is only ever present for the public demo.
|
||||
* - Unknown extra query params are tolerated (forward compat under v=1 —
|
||||
* `name` is already honored if present).
|
||||
* - `tok` is a device token minted by the node; it goes through the password
|
||||
* field on purpose — the whole password auto-login path (WebSocket auth +
|
||||
* WebView form injection) then works unchanged, and the backend accepts
|
||||
* device tokens wherever it accepts the password. `pw` (demo only) wins if
|
||||
* both are ever present.
|
||||
* - `fnpub`/`fip`/`fhost`/`fudp`/`ftcp` describe the node's FIPS mesh; their
|
||||
* absence just means LAN-only pairing (older node, or FIPS not provisioned).
|
||||
* - Unknown extra query params are tolerated (forward compat under v=1).
|
||||
*/
|
||||
object ServerQrParser {
|
||||
private const val SUPPORTED_MAJOR = 1
|
||||
@@ -54,14 +65,51 @@ object ServerQrParser {
|
||||
val host = server.host
|
||||
if (host.isNullOrBlank()) return PairResult.Invalid
|
||||
|
||||
val fips = parseFips(uri)
|
||||
val credential = uri.getQueryParameter("pw")?.takeIf { it.isNotBlank() }
|
||||
?: uri.getQueryParameter("tok")
|
||||
?: ""
|
||||
|
||||
return PairResult.Success(
|
||||
ServerEntry(
|
||||
server = ServerEntry(
|
||||
address = host,
|
||||
useHttps = scheme == "https",
|
||||
port = if (server.port != -1) server.port.toString() else "",
|
||||
password = uri.getQueryParameter("pw") ?: "",
|
||||
password = credential,
|
||||
name = uri.getQueryParameter("name") ?: "",
|
||||
)
|
||||
meshIp = fips?.ula ?: "",
|
||||
),
|
||||
fips = fips,
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseFips(uri: Uri): FipsPairInfo? {
|
||||
val npub = uri.getQueryParameter("fnpub")?.trim()
|
||||
val host = uri.getQueryParameter("fhost")?.trim()
|
||||
if (npub.isNullOrBlank() || host.isNullOrBlank()) return null
|
||||
return FipsPairInfo(
|
||||
npub = npub,
|
||||
ula = uri.getQueryParameter("fip")?.trim().orEmpty(),
|
||||
host = host,
|
||||
udpPort = uri.getQueryParameter("fudp")?.toIntOrNull() ?: 2121,
|
||||
tcpPort = uri.getQueryParameter("ftcp")?.toIntOrNull() ?: 8443,
|
||||
anchors = parseAnchors(uri.getQueryParameter("fanchors")),
|
||||
)
|
||||
}
|
||||
|
||||
/** `fanchors` = comma-joined `npub@host:port/transport`; bad items skipped. */
|
||||
private fun parseAnchors(raw: String?): List<AnchorPeer> {
|
||||
if (raw.isNullOrBlank()) return emptyList()
|
||||
return raw.split(",").mapNotNull { item ->
|
||||
val at = item.indexOf('@')
|
||||
val slash = item.lastIndexOf('/')
|
||||
if (at <= 0 || slash <= at) return@mapNotNull null
|
||||
val npub = item.substring(0, at).trim()
|
||||
val addr = item.substring(at + 1, slash).trim()
|
||||
val transport = item.substring(slash + 1).trim().lowercase()
|
||||
if (npub.isBlank() || !addr.contains(":")) return@mapNotNull null
|
||||
if (transport != "udp" && transport != "tcp") return@mapNotNull null
|
||||
AnchorPeer(npub = npub, addr = addr, transport = transport)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.archipelago.app.fips
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import com.archipelago.app.MainActivity
|
||||
import com.archipelago.app.R
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* VpnService hosting the embedded FIPS mesh node.
|
||||
*
|
||||
* Split tunnel: only fd00::/8 (the FIPS ULA space) routes into the TUN, so
|
||||
* normal phone traffic is untouched — this is mesh reachability, not a
|
||||
* default-route VPN. The established fd is detached and handed to the Rust
|
||||
* node (Node::start_with_tun_fd); the node owns it until stop.
|
||||
*/
|
||||
class ArchyVpnService : VpnService() {
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent?.action == ACTION_STOP) {
|
||||
shutdown()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
startForeground(NOTIFICATION_ID, buildNotification())
|
||||
scope.launch { startMesh() }
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
private suspend fun startMesh() {
|
||||
if (!FipsNative.available) {
|
||||
shutdown()
|
||||
return
|
||||
}
|
||||
val prefs = FipsPreferences(this)
|
||||
val identity = FipsManager.ensureIdentity(prefs)
|
||||
val peersJson = prefs.peersJson()
|
||||
if (identity == null || peersJson == "[]") {
|
||||
Log.w(TAG, "mesh not configured — stopping")
|
||||
shutdown()
|
||||
return
|
||||
}
|
||||
|
||||
// Re-establishing while running would strand the old fd; restart clean.
|
||||
if (FipsNative.isRunning()) FipsNative.stop()
|
||||
|
||||
val pfd = try {
|
||||
Builder()
|
||||
.setSession("Archipelago Mesh")
|
||||
.setMtu(1280)
|
||||
.addAddress(identity.address, 128)
|
||||
.addRoute("fd00::", 8)
|
||||
.establish()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "VPN establish failed", e)
|
||||
null
|
||||
}
|
||||
if (pfd == null) {
|
||||
shutdown()
|
||||
return
|
||||
}
|
||||
|
||||
val fd = pfd.detachFd()
|
||||
val result = FipsNative.start(identity.secret, peersJson, fd)
|
||||
Log.i(TAG, "mesh start: $result")
|
||||
if (result.contains("\"error\"")) shutdown()
|
||||
}
|
||||
|
||||
private fun shutdown() {
|
||||
FipsNative.stop()
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
FipsNative.stop()
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onRevoke() {
|
||||
// User pulled VPN permission from system settings.
|
||||
shutdown()
|
||||
}
|
||||
|
||||
private fun buildNotification(): Notification {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
"Mesh connection",
|
||||
NotificationManager.IMPORTANCE_MIN,
|
||||
).apply { description = "Keeps the node reachable from anywhere" }
|
||||
)
|
||||
}
|
||||
val tapIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
Intent(this, MainActivity::class.java),
|
||||
PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
return Notification.Builder(this, CHANNEL_ID)
|
||||
.setContentTitle("Connected to your Archipelago")
|
||||
.setContentText("Secure mesh link active")
|
||||
.setSmallIcon(R.mipmap.ic_launcher)
|
||||
.setContentIntent(tapIntent)
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ACTION_STOP = "com.archipelago.app.fips.STOP"
|
||||
private const val CHANNEL_ID = "archy_mesh"
|
||||
private const val NOTIFICATION_ID = 4841
|
||||
private const val TAG = "ArchyVpnService"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.archipelago.app.fips
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
|
||||
/**
|
||||
* Glue between pairing and the mesh: persists the node peer from a scanned
|
||||
* QR and asks the UI to bring the tunnel up. There is deliberately no
|
||||
* settings surface — scanning a node's QR is the entire configuration.
|
||||
*
|
||||
* The one unavoidable interaction is Android's VPN consent dialog
|
||||
* (VpnService.prepare), which only an Activity can launch; [consentNeeded]
|
||||
* signals AppNavHost to run it, once, on first pairing.
|
||||
*/
|
||||
object FipsManager {
|
||||
|
||||
/** Set when a pairing registered mesh info and the VPN needs starting. */
|
||||
private val _consentNeeded = MutableStateFlow(false)
|
||||
val consentNeeded: StateFlow<Boolean> = _consentNeeded
|
||||
|
||||
fun consentHandled() {
|
||||
_consentNeeded.value = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist mesh info from a pairing scan and request tunnel start.
|
||||
* No-op on devices without the native lib (non-arm64).
|
||||
*/
|
||||
suspend fun registerNode(context: Context, info: FipsPairInfo?, alias: String) {
|
||||
if (info == null || !FipsNative.available) return
|
||||
val prefs = FipsPreferences(context)
|
||||
ensureIdentity(prefs)
|
||||
prefs.upsertNodePeer(info, alias)
|
||||
_consentNeeded.value = true
|
||||
}
|
||||
|
||||
/** Generate-once mesh identity. Returns null only if the RNG/native fails. */
|
||||
suspend fun ensureIdentity(prefs: FipsPreferences): FipsNative.Identity? {
|
||||
prefs.identity()?.let { return it }
|
||||
val generated = FipsNative.parseIdentity(FipsNative.generateIdentity()) ?: return null
|
||||
prefs.saveIdentity(generated)
|
||||
return generated
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the mesh service if this device is paired and the user has already
|
||||
* consented to the VPN (prepare() == null). Called on app start so the
|
||||
* tunnel comes back without any interaction; first-time consent goes
|
||||
* through AppNavHost instead.
|
||||
*/
|
||||
suspend fun autoStartIfReady(context: Context) {
|
||||
if (!FipsNative.available) return
|
||||
val prefs = FipsPreferences(context)
|
||||
if (prefs.identity() == null || !prefs.hasPeers()) return
|
||||
if (VpnService.prepare(context) != null) return // consent missing — don't prompt here
|
||||
startService(context)
|
||||
}
|
||||
|
||||
fun startService(context: Context) {
|
||||
val intent = Intent(context, ArchyVpnService::class.java)
|
||||
context.startForegroundService(intent)
|
||||
}
|
||||
|
||||
fun stopService(context: Context) {
|
||||
val intent = Intent(context, ArchyVpnService::class.java)
|
||||
.setAction(ArchyVpnService.ACTION_STOP)
|
||||
context.startService(intent)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.archipelago.app.fips
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* JNI binding to the embedded FIPS mesh node (Android/rust/archy-fips-core,
|
||||
* built into libarchy_fips_core.so by the buildRustArm64 gradle task).
|
||||
*
|
||||
* All calls return JSON strings; failures come back as {"error": "…"} rather
|
||||
* than exceptions. [available] is false on ABIs the .so isn't built for
|
||||
* (anything but arm64) — every caller must gate on it so the app still runs
|
||||
* as a plain companion there.
|
||||
*/
|
||||
object FipsNative {
|
||||
val available: Boolean = try {
|
||||
System.loadLibrary("archy_fips_core")
|
||||
true
|
||||
} catch (_: Throwable) {
|
||||
false
|
||||
}
|
||||
|
||||
external fun generateIdentity(): String
|
||||
external fun deriveIdentity(secret: String): String
|
||||
external fun start(secret: String, peersJson: String, tunFd: Int): String
|
||||
external fun stop()
|
||||
external fun isRunning(): Boolean
|
||||
external fun statusJson(): String
|
||||
|
||||
data class Identity(val secret: String, val npub: String, val address: String)
|
||||
|
||||
/** Parse an identity JSON reply; null on {"error": …} or malformed. */
|
||||
fun parseIdentity(json: String): Identity? = try {
|
||||
val obj = JSONObject(json)
|
||||
if (obj.has("error")) null
|
||||
else Identity(
|
||||
secret = obj.getString("secret"),
|
||||
npub = obj.getString("npub"),
|
||||
address = obj.getString("address"),
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.archipelago.app.fips
|
||||
|
||||
/**
|
||||
* Node mesh parameters carried by the pairing QR (fnpub/fip/fhost/fudp/ftcp —
|
||||
* docs/companion-pairing-qr.md). The phone's embedded FIPS node dials
|
||||
* host:udpPort / host:tcpPort claiming nothing; the mesh accepts inbound peers
|
||||
* without registration, so possession of these params is all pairing takes.
|
||||
*/
|
||||
data class FipsPairInfo(
|
||||
val npub: String,
|
||||
/** Node's fips0 ULA — where its UI stays reachable once meshed. May be empty. */
|
||||
val ula: String,
|
||||
val host: String,
|
||||
val udpPort: Int,
|
||||
val tcpPort: Int,
|
||||
/**
|
||||
* Public rendezvous anchors (the node's seed-anchor list). The phone
|
||||
* peers with these too, so it can route to the node via the mesh when
|
||||
* the node's LAN endpoint isn't directly dialable.
|
||||
*/
|
||||
val anchors: List<AnchorPeer> = emptyList(),
|
||||
)
|
||||
|
||||
/** One rendezvous anchor from the QR's `fanchors` param (npub@addr/transport). */
|
||||
data class AnchorPeer(
|
||||
val npub: String,
|
||||
val addr: String,
|
||||
val transport: String,
|
||||
)
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.archipelago.app.fips
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import kotlinx.coroutines.flow.first
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
|
||||
private val Context.fipsDataStore: DataStore<Preferences> by preferencesDataStore(name = "fips_prefs")
|
||||
|
||||
/**
|
||||
* Mesh identity + known node peers. Follows the same plaintext-DataStore
|
||||
* storage model as ServerPreferences (the server password lives there the
|
||||
* same way); the mesh secret only grants mesh membership, not node login.
|
||||
*/
|
||||
class FipsPreferences(private val context: Context) {
|
||||
|
||||
private val secretKey = stringPreferencesKey("fips_secret")
|
||||
private val npubKey = stringPreferencesKey("fips_npub")
|
||||
private val addressKey = stringPreferencesKey("fips_address")
|
||||
/** JSON array of node peers in fips PeerConfig shape (see NodePeer). */
|
||||
private val peersKey = stringPreferencesKey("fips_node_peers")
|
||||
|
||||
suspend fun identity(): FipsNative.Identity? {
|
||||
val prefs = context.fipsDataStore.data.first()
|
||||
val secret = prefs[secretKey] ?: return null
|
||||
return FipsNative.Identity(
|
||||
secret = secret,
|
||||
npub = prefs[npubKey] ?: "",
|
||||
address = prefs[addressKey] ?: "",
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun saveIdentity(identity: FipsNative.Identity) {
|
||||
context.fipsDataStore.edit { prefs ->
|
||||
prefs[secretKey] = identity.secret
|
||||
prefs[npubKey] = identity.npub
|
||||
prefs[addressKey] = identity.address
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun peersJson(): String {
|
||||
val prefs = context.fipsDataStore.data.first()
|
||||
return prefs[peersKey] ?: "[]"
|
||||
}
|
||||
|
||||
suspend fun hasPeers(): Boolean = JSONArray(peersJson()).length() > 0
|
||||
|
||||
/**
|
||||
* Add or update the node peer plus its rendezvous anchors (each matched
|
||||
* by npub, so re-pairing updates addresses instead of duplicating).
|
||||
* Stored directly in the fips PeerConfig JSON shape the Rust side
|
||||
* deserializes. The node's direct addresses get the best priorities;
|
||||
* anchors trail so the mesh prefers the direct path when it works.
|
||||
*/
|
||||
suspend fun upsertNodePeer(info: FipsPairInfo, alias: String) {
|
||||
val incoming = mutableListOf<JSONObject>()
|
||||
incoming += JSONObject().apply {
|
||||
put("npub", info.npub)
|
||||
put("alias", alias.ifBlank { "Archipelago" })
|
||||
val addresses = JSONArray()
|
||||
if (info.udpPort > 0) {
|
||||
addresses.put(JSONObject().apply {
|
||||
put("transport", "udp")
|
||||
put("addr", "${info.host}:${info.udpPort}")
|
||||
put("priority", 10)
|
||||
})
|
||||
}
|
||||
if (info.tcpPort > 0) {
|
||||
addresses.put(JSONObject().apply {
|
||||
put("transport", "tcp")
|
||||
put("addr", "${info.host}:${info.tcpPort}")
|
||||
put("priority", 20)
|
||||
})
|
||||
}
|
||||
put("addresses", addresses)
|
||||
}
|
||||
for (anchor in info.anchors) {
|
||||
if (anchor.npub == info.npub) continue
|
||||
incoming += JSONObject().apply {
|
||||
put("npub", anchor.npub)
|
||||
put("alias", "Mesh anchor")
|
||||
put("addresses", JSONArray().put(JSONObject().apply {
|
||||
put("transport", anchor.transport)
|
||||
put("addr", anchor.addr)
|
||||
put("priority", 30)
|
||||
}))
|
||||
}
|
||||
}
|
||||
val incomingNpubs = incoming.map { it.optString("npub") }.toSet()
|
||||
context.fipsDataStore.edit { prefs ->
|
||||
val current = JSONArray(prefs[peersKey] ?: "[]")
|
||||
val merged = JSONArray()
|
||||
for (i in 0 until current.length()) {
|
||||
val existing = current.optJSONObject(i) ?: continue
|
||||
if (existing.optString("npub") !in incomingNpubs) merged.put(existing)
|
||||
}
|
||||
incoming.forEach { merged.put(it) }
|
||||
prefs[peersKey] = merged.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,6 @@ import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.archipelago.app.R
|
||||
import com.archipelago.app.data.PairResult
|
||||
import com.archipelago.app.data.ServerEntry
|
||||
import com.archipelago.app.data.ServerQrParser
|
||||
import com.archipelago.app.ui.screens.GlassButton
|
||||
import com.archipelago.app.ui.theme.BitcoinOrange
|
||||
@@ -82,7 +81,7 @@ import java.util.concurrent.Executors
|
||||
fun QrScannerOverlay(
|
||||
visible: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onServerScanned: (ServerEntry) -> Unit,
|
||||
onServerScanned: (PairResult.Success) -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var hasPermission by remember {
|
||||
@@ -131,7 +130,7 @@ fun QrScannerOverlay(
|
||||
when (val result = ServerQrParser.parse(text)) {
|
||||
is PairResult.Success -> {
|
||||
handled = true
|
||||
onServerScanned(result.server)
|
||||
onServerScanned(result)
|
||||
}
|
||||
is PairResult.UnsupportedVersion -> hintRes = R.string.update_app_for_qr
|
||||
is PairResult.Invalid -> hintRes = R.string.invalid_pairing_qr
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.archipelago.app.ui.navigation
|
||||
|
||||
import android.net.VpnService
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
@@ -16,6 +19,7 @@ import com.archipelago.app.data.PairResult
|
||||
import com.archipelago.app.data.ServerEntry
|
||||
import com.archipelago.app.data.ServerPreferences
|
||||
import com.archipelago.app.data.ServerQrParser
|
||||
import com.archipelago.app.fips.FipsManager
|
||||
import com.archipelago.app.ui.screens.IntroScreen
|
||||
import com.archipelago.app.ui.screens.RemoteInputScreen
|
||||
import com.archipelago.app.ui.screens.ServerConnectScreen
|
||||
@@ -46,6 +50,34 @@ fun AppNavHost(
|
||||
// connect form so the user lands on the password prompt for that server.
|
||||
var pairPrefill by remember { mutableStateOf<ServerEntry?>(null) }
|
||||
|
||||
// Mesh tunnel: Android's VPN consent dialog is the single unavoidable
|
||||
// interaction — it can only be launched from an Activity, so pairing
|
||||
// paths raise FipsManager.consentNeeded and it is handled here, once.
|
||||
val consentNeeded by FipsManager.consentNeeded.collectAsState()
|
||||
val vpnConsentLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult()
|
||||
) { result ->
|
||||
FipsManager.consentHandled()
|
||||
if (result.resultCode == android.app.Activity.RESULT_OK) {
|
||||
FipsManager.startService(context)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(consentNeeded) {
|
||||
if (!consentNeeded) return@LaunchedEffect
|
||||
val consentIntent = VpnService.prepare(context)
|
||||
if (consentIntent == null) {
|
||||
FipsManager.consentHandled()
|
||||
FipsManager.startService(context)
|
||||
} else {
|
||||
vpnConsentLauncher.launch(consentIntent)
|
||||
}
|
||||
}
|
||||
|
||||
// Paired + previously consented → the mesh comes back silently on launch.
|
||||
LaunchedEffect(Unit) {
|
||||
FipsManager.autoStartIfReady(context)
|
||||
}
|
||||
|
||||
if (introSeen == null) return
|
||||
|
||||
// Declared after the introSeen gate so it can't fire before the NavHost
|
||||
@@ -58,6 +90,7 @@ fun AppNavHost(
|
||||
// Pairing implies the app is installed and in use — skip the intro.
|
||||
prefs.markIntroSeen()
|
||||
val merged = prefs.upsertServer(result.server)
|
||||
FipsManager.registerNode(context, result.fips, merged.displayName())
|
||||
if (merged.password.isNotBlank()) {
|
||||
// Demo flow: password came with the link — connect in one step.
|
||||
prefs.setActiveServer(merged)
|
||||
@@ -125,6 +158,7 @@ fun AppNavHost(
|
||||
WebViewScreen(
|
||||
serverUrl = server.toUrl(),
|
||||
serverPassword = server.password,
|
||||
meshFallbackUrl = server.toMeshUrl(),
|
||||
onDisconnect = {
|
||||
scope.launch {
|
||||
prefs.clearActiveServer()
|
||||
|
||||
@@ -37,6 +37,7 @@ import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.archipelago.app.R
|
||||
import com.archipelago.app.data.ServerPreferences
|
||||
import com.archipelago.app.fips.FipsManager
|
||||
import com.archipelago.app.network.ConnectionState
|
||||
import com.archipelago.app.network.InputWebSocket
|
||||
import com.archipelago.app.ui.components.NESController
|
||||
@@ -256,10 +257,11 @@ fun RemoteInputScreen(onBack: () -> Unit) {
|
||||
QrScannerOverlay(
|
||||
visible = showQrScanner,
|
||||
onDismiss = { showQrScanner = false },
|
||||
onServerScanned = { server ->
|
||||
onServerScanned = { scan ->
|
||||
showQrScanner = false
|
||||
scope.launch {
|
||||
val merged = prefs.upsertServer(server)
|
||||
val merged = prefs.upsertServer(scan.server)
|
||||
FipsManager.registerNode(context, scan.fips, merged.displayName())
|
||||
if (activeServer == null) prefs.setActiveServer(merged)
|
||||
}
|
||||
},
|
||||
|
||||
@@ -71,8 +71,10 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.archipelago.app.R
|
||||
import com.archipelago.app.data.PairResult
|
||||
import com.archipelago.app.data.ServerEntry
|
||||
import com.archipelago.app.data.ServerPreferences
|
||||
import com.archipelago.app.fips.FipsManager
|
||||
import com.archipelago.app.ui.components.QrScannerOverlay
|
||||
import com.archipelago.app.ui.theme.BitcoinOrange
|
||||
import com.archipelago.app.ui.theme.ErrorRed
|
||||
@@ -190,12 +192,14 @@ fun ServerConnectScreen(
|
||||
}
|
||||
|
||||
// Pairing QR scanned: dedupe against saved servers, then either auto-connect
|
||||
// (payload carried a password — the demo flow) or land on the password
|
||||
// prompt with everything else filled in (real nodes never embed one).
|
||||
fun onQrScanned(scanned: ServerEntry) {
|
||||
// (payload carried a credential — demo password or a real node's device
|
||||
// token) or land on the password prompt with everything else filled in.
|
||||
// Mesh info (when present) is registered so the FIPS tunnel comes up too.
|
||||
fun onQrScanned(scan: PairResult.Success) {
|
||||
showScanner = false
|
||||
scope.launch {
|
||||
val merged = prefs.upsertServer(scanned)
|
||||
val merged = prefs.upsertServer(scan.server)
|
||||
FipsManager.registerNode(context, scan.fips, merged.displayName())
|
||||
prefill(merged)
|
||||
if (merged.password.isNotBlank()) {
|
||||
connect(merged)
|
||||
|
||||
@@ -146,9 +146,14 @@ fun WebViewScreen(
|
||||
// non-blank, the login page is auto-filled and submitted — the one-step
|
||||
// demo flow from docs/companion-pairing-qr.md.
|
||||
serverPassword: String = "",
|
||||
// Node's FIPS mesh URL (http://[fd…]). When the primary address fails on
|
||||
// a main-frame load — typically the phone left the LAN — retry there
|
||||
// before surfacing the error page: the mesh tunnel works from anywhere.
|
||||
meshFallbackUrl: String? = null,
|
||||
) {
|
||||
var isLoading by remember { mutableStateOf(true) }
|
||||
var loadProgress by remember { mutableIntStateOf(0) }
|
||||
var triedMeshFallback by remember { mutableStateOf(false) }
|
||||
var hasError by remember { mutableStateOf(false) }
|
||||
var webView by remember { mutableStateOf<WebView?>(null) }
|
||||
|
||||
@@ -336,8 +341,13 @@ fun WebViewScreen(
|
||||
)
|
||||
|
||||
// Auto-login with the stored password (QR pairing /
|
||||
// saved server) — only on our own server's pages.
|
||||
if (serverPassword.isNotBlank() && url != null && url.startsWith(serverUrl)) {
|
||||
// saved server) — only on our own server's pages
|
||||
// (LAN origin or the mesh address).
|
||||
val onOwnServer = url != null && (
|
||||
url.startsWith(serverUrl) ||
|
||||
(meshFallbackUrl != null && url.startsWith(meshFallbackUrl))
|
||||
)
|
||||
if (serverPassword.isNotBlank() && onOwnServer) {
|
||||
view.evaluateJavascript(buildAutoLoginScript(serverPassword), null)
|
||||
}
|
||||
}
|
||||
@@ -348,6 +358,15 @@ fun WebViewScreen(
|
||||
error: WebResourceError?,
|
||||
) {
|
||||
if (request?.isForMainFrame == true) {
|
||||
val mesh = meshFallbackUrl
|
||||
if (mesh != null && !triedMeshFallback &&
|
||||
request.url?.toString()?.startsWith(mesh) != true
|
||||
) {
|
||||
triedMeshFallback = true
|
||||
isLoading = true
|
||||
view?.loadUrl(mesh)
|
||||
return
|
||||
}
|
||||
hasError = true
|
||||
isLoading = false
|
||||
}
|
||||
@@ -380,6 +399,8 @@ fun WebViewScreen(
|
||||
val url = request?.url?.toString() ?: return false
|
||||
// Keep kiosk navigation (same origin incl. port) in place
|
||||
if (url.startsWith(serverUrl)) return false
|
||||
// Mesh address is the same server too
|
||||
if (meshFallbackUrl != null && url.startsWith(meshFallbackUrl)) return false
|
||||
// Same node (other port) → in-app; external → browser
|
||||
routeOutbound(url)
|
||||
return true
|
||||
|
||||
Reference in New Issue
Block a user