DeviceIdentity.kt

5.4 KB · raw

1package com.peachpasswords.sync23import android.content.Context4import androidx.security.crypto.EncryptedSharedPreferences5import androidx.security.crypto.MasterKey6import java.util.UUID7import java.security.SecureRandom8import com.peachpasswords.vault.VaultCrypto910private const val LOCAL_IDENTITY_PREFS = "peach_local_identity_v2"1112private fun secureIdentityPrefs(context: Context) = EncryptedSharedPreferences.create(13    context,14    LOCAL_IDENTITY_PREFS,15    MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(),16    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,17    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,18)1920/**21 * Loads the canonical random identity, creating it once under Keystore22 * protection. A record that is absent, partial, of an unknown version, or23 * inconsistent between its private and stored public values fails closed with24 * `identity_migration_required`; it is never regenerated underneath an existing25 * installation. The schema and its consistency rules live in [readIdentityRecord].26 */27fun loadOrCreateLocalIdentity(context: Context): LocalIdentityCredentials {28    val stored: Map<String, Any?> = try {29        secureIdentityPrefs(context).all30    } catch (_: Exception) {31        throw IllegalStateException("identity_migration_required")32    }33    return when (val record = readIdentityRecord(stored)) {34        is IdentityRecord.Absent -> {35            val fresh = randomLocalIdentityCredentials(UUID.randomUUID().toString())36            persistIdentity(context, fresh, System.currentTimeMillis())37            fresh38        }39        is IdentityRecord.LegacyRandom -> {40            // Same private material, missing stored public values and creation41            // time: complete the record without changing the identity.42            persistIdentity(context, record.credentials, System.currentTimeMillis())43            record.credentials44        }45        is IdentityRecord.Current -> record.credentials46        IdentityRecord.Invalid -> throw IllegalStateException("identity_migration_required")47    }48}4950private fun persistIdentity(51    context: Context,52    credentials: LocalIdentityCredentials,53    createdAt: Long,54) {55    val editor = secureIdentityPrefs(context).edit()56    for ((key, value) in identityRecordFields(credentials, createdAt)) {57        when (value) {58            is Int -> editor.putInt(key, value)59            is Long -> editor.putLong(key, value)60            is String -> editor.putString(key, value)61            else -> error("unsupported identity record field: $key")62        }63    }64    check(editor.commit()) { "identity_persist_failed" }65}6667// The persisted names below are retained for device-name migration only.68// upgrade. The name is stale; the cost of fixing it is not worth paying.69private const val DEVICE_ID_KEY = "peach_chirp_device_id"70private const val DEVICE_NAME_KEY = "peach_chirp_device_name"71private const val PREFS_FILE = "peach_chirp_identity"7273data class LocalDeviceIdentity(74    val deviceId: String,75    val deviceName: String,76    val deviceType: DeviceType,77    val longTermPublicKeyHex: String,78    val signingPublicKeyHex: String,79    val wsPort: Int? = null,80    val relayUrl: String = Rendezvous.DEFAULT_RELAY_URL,81    /**82     * This device's signed Pro license blob (`PPK-…`), set only when Pro. Sent83     * in the outbound PAIR_IDENTITY so the peer can activate it after SAS — one84     * Pro device grants Pro to the other when pairing. Either direction.85     */86    val license: String? = null,87)8889fun getOrCreateDeviceId(context: Context): String = loadOrCreateLocalIdentity(context).deviceId9091/** Replace the local identity after an authenticated peer detects a collision. */92fun rotateDeviceId(context: Context): String {93    val fresh = randomLocalIdentityCredentials(UUID.randomUUID().toString())94    persistIdentity(context, fresh, System.currentTimeMillis())95    return fresh.deviceId96}9798fun getDeviceName(context: Context): String {99    val prefs = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)100    return prefs.getString(DEVICE_NAME_KEY, null).orEmpty().ifBlank { defaultDeviceName() }101}102103fun setDeviceName(context: Context, name: String) {104    val trimmed = name.trim()105    require(trimmed.isNotEmpty()) { "device name must not be empty" }106    require(trimmed.length <= 64) { "device name must be 64 chars or fewer" }107    context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)108        .edit()109        .putString(DEVICE_NAME_KEY, trimmed)110        .apply()111}112113fun clearDeviceIdentity(context: Context) {114    context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)115        .edit()116        .clear()117        .apply()118}119120fun buildLocalIdentity(context: Context, masterKey: ByteArray): LocalDeviceIdentity {121    VaultCrypto.zero(masterKey)122    return buildLocalIdentity(context, loadOrCreateLocalIdentity(context))123}124125fun buildLocalIdentity(context: Context, credentials: LocalIdentityCredentials): LocalDeviceIdentity {126    return LocalDeviceIdentity(127        deviceId = credentials.deviceId,128        deviceName = getDeviceName(context),129        deviceType = extensionDeviceType(),130        longTermPublicKeyHex = pubkeyToHex(credentials.x25519PublicKey),131        signingPublicKeyHex = pubkeyToHex(credentials.ed25519PublicKey),132        wsPort = null,133        relayUrl = RelaySettingsStore.readRelayUrl(context),134    )135}136137private fun defaultDeviceName(): String {138    return "Android"139}140141private fun extensionDeviceType(): DeviceType {142    return DeviceType.ANDROID143}