Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quiet-bears-breathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'voltra': minor
---

Add support for server-driven Home Screen widgets on iOS and Android, so widgets can refresh with content from your backend even when the app is closed.
18 changes: 18 additions & 0 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,20 @@ if (useManagedAndroidSdkVersions) {
}
}

// Read version from package.json for BuildConfig
def packageJsonFile = new File(project.projectDir.parentFile, "package.json")
def packageJson = new groovy.json.JsonSlurper().parseText(packageJsonFile.text)
def voltraVersion = packageJson.version

android {
namespace "voltra"
defaultConfig {
versionCode 1
versionName "0.1.0"
buildConfigField "String", "VOLTRA_VERSION", "\"${voltraVersion}\""
}
buildFeatures {
buildConfig true
}
lintOptions {
abortOnError false
Expand Down Expand Up @@ -84,6 +93,15 @@ dependencies {
// Compose runtime (required for Glance)
api "androidx.compose.runtime:runtime:1.6.8"

// WorkManager (for periodic server-driven widget updates)
api "androidx.work:work-runtime-ktx:2.9.1"

// DataStore (credential storage for widget server updates)
api "androidx.datastore:datastore-preferences:1.1.4"

// Google Tink (encryption for credential storage)
implementation "com.google.crypto.tink:tink-android:1.19.0"

// JSON parsing
implementation "com.google.code.gson:gson:2.10.1"

Expand Down
44 changes: 44 additions & 0 deletions android/src/main/java/voltra/VoltraModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,50 @@ class VoltraModule : Module() {
imageManager.clearPreloadedImages(keys)
}

// Widget Server Credentials APIs

AsyncFunction("setWidgetServerCredentials") { credentials: Map<String, Any?> ->
Log.d(TAG, "setWidgetServerCredentials called")

val context = appContext.reactContext!!
val token =
credentials["token"] as? String
?: throw IllegalArgumentException("token is required in credentials")

@Suppress("UNCHECKED_CAST")
val headers = credentials["headers"] as? Map<String, String>

runBlocking {
voltra.widget.VoltraWidgetCredentialStore.saveToken(context, token)
if (headers != null && headers.isNotEmpty()) {
voltra.widget.VoltraWidgetCredentialStore.saveHeaders(context, headers)
}
}

Log.d(TAG, "Widget server credentials saved")

val widgetManager = voltra.widget.VoltraWidgetManager(context)
runBlocking {
widgetManager.reloadAllWidgets()
}
}

AsyncFunction("clearWidgetServerCredentials") {
Log.d(TAG, "clearWidgetServerCredentials called")

val context = appContext.reactContext!!
runBlocking {
voltra.widget.VoltraWidgetCredentialStore.clearAll(context)
}

Log.d(TAG, "Widget server credentials cleared")

val widgetManager = voltra.widget.VoltraWidgetManager(context)
runBlocking {
widgetManager.reloadAllWidgets()
}
}

AsyncFunction("reloadLiveActivities") { activityNames: List<String>? ->
// On Android, we don't have "Live Activities" in the same sense as iOS,
// but we might want to refresh widgets or notifications.
Expand Down
99 changes: 99 additions & 0 deletions android/src/main/java/voltra/widget/VoltraCryptoManager.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package voltra.widget

import android.content.Context
import android.util.Base64
import android.util.Log
import com.google.crypto.tink.Aead
import com.google.crypto.tink.KeyTemplates
import com.google.crypto.tink.KeysetHandle
import com.google.crypto.tink.aead.AeadConfig
import com.google.crypto.tink.integration.android.AndroidKeysetManager

/**
* Encryption helper using Google Tink's AEAD primitive.
*
* Uses AES-256-GCM backed by the Android Keystore for key management.
* The keyset is stored encrypted in SharedPreferences and the master key
* never leaves the hardware-backed Keystore.
*
* This replaces the deprecated EncryptedSharedPreferences approach with
* the modern DataStore + Tink architecture.
*/
object VoltraCryptoManager {
private const val TAG = "VoltraCryptoManager"
private const val KEYSET_NAME = "voltra_widget_keyset"
private const val PREF_FILE_NAME = "voltra_widget_keyset_prefs"
private const val MASTER_KEY_URI = "android-keystore://voltra_widget_master_key"

@Volatile
private var aead: Aead? = null

/**
* Get or initialize the AEAD primitive.
* Thread-safe via double-checked locking.
*/
private fun getAead(context: Context): Aead =
aead ?: synchronized(this) {
aead ?: initAead(context).also { aead = it }
}

private fun initAead(context: Context): Aead {
AeadConfig.register()

val keysetHandle: KeysetHandle =
AndroidKeysetManager
.Builder()
.withSharedPref(context, KEYSET_NAME, PREF_FILE_NAME)
.withKeyTemplate(KeyTemplates.get("AES256_GCM"))
.withMasterKeyUri(MASTER_KEY_URI)
.build()
.keysetHandle

return keysetHandle.getPrimitive(Aead::class.java)
}

/**
* Encrypt a plaintext string.
* Returns a Base64-encoded ciphertext, or null on failure.
*
* @param context Application context
* @param plaintext The string to encrypt
* @param associatedData Optional associated data for AEAD authentication
*/
fun encrypt(
context: Context,
plaintext: String,
associatedData: ByteArray = ByteArray(0),
): String? =
try {
val aead = getAead(context)
val ciphertext = aead.encrypt(plaintext.toByteArray(Charsets.UTF_8), associatedData)
Base64.encodeToString(ciphertext, Base64.NO_WRAP)
} catch (e: Exception) {
Log.e(TAG, "Encryption failed: ${e.message}", e)
null
}

/**
* Decrypt a Base64-encoded ciphertext string.
* Returns the plaintext string, or null on failure.
*
* @param context Application context
* @param encryptedBase64 The Base64-encoded ciphertext to decrypt
* @param associatedData Optional associated data for AEAD authentication (must match encryption)
*/
fun decrypt(
context: Context,
encryptedBase64: String,
associatedData: ByteArray = ByteArray(0),
): String? =
try {
val aead = getAead(context)
val ciphertext = Base64.decode(encryptedBase64, Base64.NO_WRAP)
val plaintext = aead.decrypt(ciphertext, associatedData)
String(plaintext, Charsets.UTF_8)
} catch (e: Exception) {
Log.e(TAG, "Decryption failed: ${e.message}", e)
null
}
}
174 changes: 174 additions & 0 deletions android/src/main/java/voltra/widget/VoltraWidgetCredentialStore.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
package voltra.widget

import android.content.Context
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.stringSetPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking

/**
* Secure credential storage for widget server-driven updates.
* Uses Jetpack DataStore with Preferences for persistence, and Google Tink AEAD
* for encrypting sensitive values (tokens and headers) at rest.
*
* Since Android widgets are part of the main app binary, they inherently share
* this storage; no special grouping or sharing configuration is required.
*/

private val Context.voltraCredentialsDataStore: DataStore<Preferences> by preferencesDataStore(
name = "voltra_widget_credentials",
)

object VoltraWidgetCredentialStore {
private const val TAG = "VoltraWidgetCredStore"

private val KEY_TOKEN = stringPreferencesKey("auth_token")
private val KEY_HEADER_KEYS = stringSetPreferencesKey("header_keys")
private const val KEY_HEADERS_PREFIX = "header_"

/**
* Save an auth token (encrypted via Tink AEAD).
* Called from the main app after user login.
*/
suspend fun saveToken(
context: Context,
token: String,
): Boolean =
try {
val encrypted =
VoltraCryptoManager.encrypt(context, token)
?: throw IllegalStateException("Failed to encrypt token")
context.voltraCredentialsDataStore.edit { prefs ->
prefs[KEY_TOKEN] = encrypted
}
Log.d(TAG, "Token saved (encrypted)")
true
} catch (e: Exception) {
Log.e(TAG, "Failed to save token: ${e.message}", e)
false
}

/**
* Read the auth token (decrypted via Tink AEAD).
* Called from the WorkManager Worker during background fetch.
*/
suspend fun readToken(context: Context): String? =
try {
val encrypted =
context.voltraCredentialsDataStore.data
.map { prefs -> prefs[KEY_TOKEN] }
.firstOrNull()
encrypted?.let { VoltraCryptoManager.decrypt(context, it) }
} catch (e: Exception) {
Log.e(TAG, "Failed to read token: ${e.message}", e)
null
}

/**
* Read the auth token synchronously (blocking).
* Use only from contexts where a suspend function is not available.
*/
fun readTokenBlocking(context: Context): String? = runBlocking { readToken(context) }

/**
* Save custom headers (values encrypted via Tink AEAD).
*/
suspend fun saveHeaders(
context: Context,
headers: Map<String, String>,
): Boolean =
try {
context.voltraCredentialsDataStore.edit { prefs ->
// Clear existing headers
val existingKeys = prefs[KEY_HEADER_KEYS] ?: emptySet()
existingKeys.forEach { key ->
prefs.remove(stringPreferencesKey("$KEY_HEADERS_PREFIX$key"))
}

// Save new headers with encrypted values
val headerKeys = mutableSetOf<String>()
headers.forEach { (key, value) ->
val encrypted =
VoltraCryptoManager.encrypt(context, value)
?: throw IllegalStateException("Failed to encrypt header value for key: $key")
prefs[stringPreferencesKey("$KEY_HEADERS_PREFIX$key")] = encrypted
headerKeys.add(key)
}
prefs[KEY_HEADER_KEYS] = headerKeys
}
Log.d(TAG, "Headers saved (${headers.size} headers, encrypted)")
true
} catch (e: Exception) {
Log.e(TAG, "Failed to save headers: ${e.message}", e)
false
}

/**
* Read custom headers (values decrypted via Tink AEAD).
* Called from the WorkManager Worker during background fetch.
*/
suspend fun readHeaders(context: Context): Map<String, String> =
try {
context.voltraCredentialsDataStore.data
.map { prefs ->
val headerKeys = prefs[KEY_HEADER_KEYS] ?: emptySet()
val headers = mutableMapOf<String, String>()
headerKeys.forEach { key ->
val encrypted = prefs[stringPreferencesKey("$KEY_HEADERS_PREFIX$key")]
if (encrypted != null) {
val decrypted = VoltraCryptoManager.decrypt(context, encrypted)
if (decrypted != null) {
headers[key] = decrypted
} else {
Log.w(TAG, "Failed to decrypt header value for key: $key")
}
}
}
headers as Map<String, String>
}.firstOrNull() ?: emptyMap()
} catch (e: Exception) {
Log.e(TAG, "Failed to read headers: ${e.message}", e)
emptyMap()
}

/**
* Read custom headers synchronously (blocking).
* Use only from contexts where a suspend function is not available.
*/
fun readHeadersBlocking(context: Context): Map<String, String> = runBlocking { readHeaders(context) }

/**
* Delete the auth token.
*/
suspend fun deleteToken(context: Context): Boolean =
try {
context.voltraCredentialsDataStore.edit { prefs ->
prefs.remove(KEY_TOKEN)
}
true
} catch (e: Exception) {
Log.e(TAG, "Failed to delete token: ${e.message}", e)
false
}

/**
* Clear all stored credentials.
*/
suspend fun clearAll(context: Context): Boolean =
try {
context.voltraCredentialsDataStore.edit { prefs ->
prefs.clear()
}
Log.d(TAG, "All credentials cleared")
true
} catch (e: Exception) {
Log.e(TAG, "Failed to clear credentials: ${e.message}", e)
false
}
}
Loading
Loading