DeviceIdentity.kt

5.5 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"11private const val LOCAL_IDENTITY_VERSION = 21213private fun secureIdentityPrefs(context: Context) = EncryptedSharedPreferences.create(14    context,15    LOCAL_IDENTITY_PREFS,16    MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(),17    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,18    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,19)2021/** Loads the canonical random identity, creating it once under Keystore protection. */22fun loadOrCreateLocalIdentity(context: Context): LocalIdentityCredentials {23    val prefs = secureIdentityPrefs(context)24    check(prefs.getInt("version", LOCAL_IDENTITY_VERSION) == LOCAL_IDENTITY_VERSION) {25        "identity_migration_required"26    }27    val id = prefs.getString("device_id", null)28    val xHex = prefs.getString("x25519_private", null)29    val eHex = prefs.getString("ed25519_seed", null)30    if (id != null || xHex != null || eHex != null) {31        require(!id.isNullOrBlank() && xHex != null && eHex != null) { "identity_migration_required" }32        require(xHex.matches(Regex("^[0-9a-fA-F]{64}$")) && eHex.matches(Regex("^[0-9a-fA-F]{64}$"))) {33            "identity_migration_required"34        }35        val x = hexToBytes(xHex)36        val e = hexToBytes(eHex)37        val xp = org.bouncycastle.crypto.params.X25519PrivateKeyParameters(x, 0)38        val ep = org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters(e, 0)39        return LocalIdentityCredentials(id, x, xp.generatePublicKey().encoded, e, ep.generatePublicKey().encoded)40    }41    val fresh = randomLocalIdentityCredentials(UUID.randomUUID().toString())42    check(prefs.edit().putInt("version", LOCAL_IDENTITY_VERSION)43        .putString("device_id", fresh.deviceId)44        .putString("x25519_private", pubkeyToHex(fresh.x25519PrivateKey))45        .putString("ed25519_seed", pubkeyToHex(fresh.ed25519Seed)).commit()) {46        "identity_persist_failed"47    }48    return fresh49}5051// The persisted names below are retained for device-name migration only.52// upgrade. The name is stale; the cost of fixing it is not worth paying.53private const val DEVICE_ID_KEY = "peach_chirp_device_id"54private const val DEVICE_NAME_KEY = "peach_chirp_device_name"55private const val PREFS_FILE = "peach_chirp_identity"5657data class LocalDeviceIdentity(58    val deviceId: String,59    val deviceName: String,60    val deviceType: DeviceType,61    val longTermPublicKeyHex: String,62    val signingPublicKeyHex: String,63    val wsPort: Int? = null,64    val relayUrl: String = Rendezvous.DEFAULT_RELAY_URL,65    /**66     * This device's signed Pro license blob (`PPK-…`), set only when Pro. Sent67     * in the outbound PAIR_IDENTITY so the peer can activate it after SAS — one68     * Pro device grants Pro to the other when pairing. Either direction.69     */70    val license: String? = null,71)7273fun getOrCreateDeviceId(context: Context): String = loadOrCreateLocalIdentity(context).deviceId7475/** Replace the local identity after an authenticated peer detects a collision. */76fun rotateDeviceId(context: Context): String {77    val fresh = randomLocalIdentityCredentials(UUID.randomUUID().toString())78    check(secureIdentityPrefs(context).edit()79        .putInt("version", LOCAL_IDENTITY_VERSION)80        .putString("device_id", fresh.deviceId)81        .putString("x25519_private", pubkeyToHex(fresh.x25519PrivateKey))82        .putString("ed25519_seed", pubkeyToHex(fresh.ed25519Seed))83        .commit()) {84        "identity_persist_failed"85    }86    return fresh.deviceId87}8889fun getDeviceName(context: Context): String {90    val prefs = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)91    return prefs.getString(DEVICE_NAME_KEY, null).orEmpty().ifBlank { defaultDeviceName() }92}9394fun setDeviceName(context: Context, name: String) {95    val trimmed = name.trim()96    require(trimmed.isNotEmpty()) { "device name must not be empty" }97    require(trimmed.length <= 64) { "device name must be 64 chars or fewer" }98    context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)99        .edit()100        .putString(DEVICE_NAME_KEY, trimmed)101        .apply()102}103104fun clearDeviceIdentity(context: Context) {105    context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)106        .edit()107        .clear()108        .apply()109}110111fun buildLocalIdentity(context: Context, masterKey: ByteArray): LocalDeviceIdentity {112    VaultCrypto.zero(masterKey)113    return buildLocalIdentity(context, loadOrCreateLocalIdentity(context))114}115116fun buildLocalIdentity(context: Context, credentials: LocalIdentityCredentials): LocalDeviceIdentity {117    return LocalDeviceIdentity(118        deviceId = credentials.deviceId,119        deviceName = getDeviceName(context),120        deviceType = extensionDeviceType(),121        longTermPublicKeyHex = pubkeyToHex(credentials.x25519PublicKey),122        signingPublicKeyHex = pubkeyToHex(credentials.ed25519PublicKey),123        wsPort = null,124        relayUrl = RelaySettingsStore.readRelayUrl(context),125    )126}127128fun deriveLocalSyncKeypair(masterKey: ByteArray, deviceId: String): SyncIdentityKeypair {129    throw IllegalStateException("identity_migration_required")130}131132private fun defaultDeviceName(): String {133    return "Android"134}135136private fun extensionDeviceType(): DeviceType {137    return DeviceType.ANDROID138}