DeviceIdentity.kt

6.3 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            if (resetRequiredByExistingTrustState(context)) {36                throw IllegalStateException("identity_migration_required")37            }38            val fresh = randomLocalIdentityCredentials(UUID.randomUUID().toString())39            persistIdentity(context, fresh, System.currentTimeMillis())40            fresh41        }42        is IdentityRecord.LegacyRandom -> {43            // Same private material, missing stored public values and creation44            // time: complete the record without changing the identity.45            persistIdentity(context, record.credentials, System.currentTimeMillis())46            record.credentials47        }48        is IdentityRecord.Current -> record.credentials49        IdentityRecord.Invalid -> {50            resetRequiredByExistingTrustState(context)51            throw IllegalStateException("identity_migration_required")52        }53    }54}5556/**57 * A missing or corrupt identity may only be minted on a genuinely fresh58 * installation. With any trust state present it is a reset condition (§11.5):59 * minting would hand every peer an unknown device whose new keys no longer match60 * the revocation ledger. An unresolvable store therefore counts as trust state —61 * the refusal is the safe direction.62 */63private fun resetRequiredByExistingTrustState(context: Context): Boolean = runCatching {64    mintDecision(syncGenerationStore(context), System.currentTimeMillis()) ==65        IdentityMintDecision.REFUSE_RESET_REQUIRED66}.getOrDefault(true)6768private fun persistIdentity(69    context: Context,70    credentials: LocalIdentityCredentials,71    createdAt: Long,72) {73    val editor = secureIdentityPrefs(context).edit()74    for ((key, value) in identityRecordFields(credentials, createdAt)) {75        when (value) {76            is Int -> editor.putInt(key, value)77            is Long -> editor.putLong(key, value)78            is String -> editor.putString(key, value)79            else -> error("unsupported identity record field: $key")80        }81    }82    check(editor.commit()) { "identity_persist_failed" }83}8485// The persisted names below are retained for device-name migration only.86// upgrade. The name is stale; the cost of fixing it is not worth paying.87private const val DEVICE_ID_KEY = "peach_chirp_device_id"88private const val DEVICE_NAME_KEY = "peach_chirp_device_name"89private const val PREFS_FILE = "peach_chirp_identity"9091data class LocalDeviceIdentity(92    val deviceId: String,93    val deviceName: String,94    val deviceType: DeviceType,95    val longTermPublicKeyHex: String,96    val signingPublicKeyHex: String,97    val wsPort: Int? = null,98    val relayUrl: String = Rendezvous.DEFAULT_RELAY_URL,99    /**100     * This device's signed Pro license blob (`PPK-…`), set only when Pro. Sent101     * in the outbound PAIR_IDENTITY so the peer can activate it after SAS — one102     * Pro device grants Pro to the other when pairing. Either direction.103     */104    val license: String? = null,105)106107fun getOrCreateDeviceId(context: Context): String = loadOrCreateLocalIdentity(context).deviceId108109/** Replace the local identity after an authenticated peer detects a collision. */110fun rotateDeviceId(context: Context): String {111    val fresh = randomLocalIdentityCredentials(UUID.randomUUID().toString())112    persistIdentity(context, fresh, System.currentTimeMillis())113    return fresh.deviceId114}115116fun getDeviceName(context: Context): String {117    val prefs = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)118    return prefs.getString(DEVICE_NAME_KEY, null).orEmpty().ifBlank { defaultDeviceName() }119}120121fun setDeviceName(context: Context, name: String) {122    val trimmed = name.trim()123    require(trimmed.isNotEmpty()) { "device name must not be empty" }124    require(trimmed.length <= 64) { "device name must be 64 chars or fewer" }125    context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)126        .edit()127        .putString(DEVICE_NAME_KEY, trimmed)128        .apply()129}130131fun clearDeviceIdentity(context: Context) {132    context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)133        .edit()134        .clear()135        .apply()136}137138fun buildLocalIdentity(context: Context, masterKey: ByteArray): LocalDeviceIdentity {139    VaultCrypto.zero(masterKey)140    return buildLocalIdentity(context, loadOrCreateLocalIdentity(context))141}142143fun buildLocalIdentity(context: Context, credentials: LocalIdentityCredentials): LocalDeviceIdentity {144    return LocalDeviceIdentity(145        deviceId = credentials.deviceId,146        deviceName = getDeviceName(context),147        deviceType = extensionDeviceType(),148        longTermPublicKeyHex = pubkeyToHex(credentials.x25519PublicKey),149        signingPublicKeyHex = pubkeyToHex(credentials.ed25519PublicKey),150        wsPort = null,151        relayUrl = RelaySettingsStore.readRelayUrl(context),152    )153}154155private fun defaultDeviceName(): String {156    return "Android"157}158159private fun extensionDeviceType(): DeviceType {160    return DeviceType.ANDROID161}