package com.peachpasswords.sync import android.content.Context import androidx.security.crypto.EncryptedSharedPreferences import androidx.security.crypto.MasterKey import java.util.UUID import java.security.SecureRandom import com.peachpasswords.vault.VaultCrypto private const val LOCAL_IDENTITY_PREFS = "peach_local_identity_v2" private const val LOCAL_IDENTITY_VERSION = 2 private fun secureIdentityPrefs(context: Context) = EncryptedSharedPreferences.create( context, LOCAL_IDENTITY_PREFS, MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(), EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM, ) /** Loads the canonical random identity, creating it once under Keystore protection. */ fun loadOrCreateLocalIdentity(context: Context): LocalIdentityCredentials { val prefs = secureIdentityPrefs(context) check(prefs.getInt("version", LOCAL_IDENTITY_VERSION) == LOCAL_IDENTITY_VERSION) { "identity_migration_required" } val id = prefs.getString("device_id", null) val xHex = prefs.getString("x25519_private", null) val eHex = prefs.getString("ed25519_seed", null) if (id != null || xHex != null || eHex != null) { require(!id.isNullOrBlank() && xHex != null && eHex != null) { "identity_migration_required" } require(xHex.matches(Regex("^[0-9a-fA-F]{64}$")) && eHex.matches(Regex("^[0-9a-fA-F]{64}$"))) { "identity_migration_required" } val x = hexToBytes(xHex) val e = hexToBytes(eHex) val xp = org.bouncycastle.crypto.params.X25519PrivateKeyParameters(x, 0) val ep = org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters(e, 0) return LocalIdentityCredentials(id, x, xp.generatePublicKey().encoded, e, ep.generatePublicKey().encoded) } val fresh = randomLocalIdentityCredentials(UUID.randomUUID().toString()) check(prefs.edit().putInt("version", LOCAL_IDENTITY_VERSION) .putString("device_id", fresh.deviceId) .putString("x25519_private", pubkeyToHex(fresh.x25519PrivateKey)) .putString("ed25519_seed", pubkeyToHex(fresh.ed25519Seed)).commit()) { "identity_persist_failed" } return fresh } // The persisted names below are retained for device-name migration only. // upgrade. The name is stale; the cost of fixing it is not worth paying. private const val DEVICE_ID_KEY = "peach_chirp_device_id" private const val DEVICE_NAME_KEY = "peach_chirp_device_name" private const val PREFS_FILE = "peach_chirp_identity" data class LocalDeviceIdentity( val deviceId: String, val deviceName: String, val deviceType: DeviceType, val longTermPublicKeyHex: String, val signingPublicKeyHex: String, val wsPort: Int? = null, val relayUrl: String = Rendezvous.DEFAULT_RELAY_URL, /** * This device's signed Pro license blob (`PPK-…`), set only when Pro. Sent * in the outbound PAIR_IDENTITY so the peer can activate it after SAS — one * Pro device grants Pro to the other when pairing. Either direction. */ val license: String? = null, ) fun getOrCreateDeviceId(context: Context): String = loadOrCreateLocalIdentity(context).deviceId /** Replace the local identity after an authenticated peer detects a collision. */ fun rotateDeviceId(context: Context): String { val fresh = randomLocalIdentityCredentials(UUID.randomUUID().toString()) check(secureIdentityPrefs(context).edit() .putInt("version", LOCAL_IDENTITY_VERSION) .putString("device_id", fresh.deviceId) .putString("x25519_private", pubkeyToHex(fresh.x25519PrivateKey)) .putString("ed25519_seed", pubkeyToHex(fresh.ed25519Seed)) .commit()) { "identity_persist_failed" } return fresh.deviceId } fun getDeviceName(context: Context): String { val prefs = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE) return prefs.getString(DEVICE_NAME_KEY, null).orEmpty().ifBlank { defaultDeviceName() } } fun setDeviceName(context: Context, name: String) { val trimmed = name.trim() require(trimmed.isNotEmpty()) { "device name must not be empty" } require(trimmed.length <= 64) { "device name must be 64 chars or fewer" } context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE) .edit() .putString(DEVICE_NAME_KEY, trimmed) .apply() } fun clearDeviceIdentity(context: Context) { context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE) .edit() .clear() .apply() } fun buildLocalIdentity(context: Context, masterKey: ByteArray): LocalDeviceIdentity { VaultCrypto.zero(masterKey) return buildLocalIdentity(context, loadOrCreateLocalIdentity(context)) } fun buildLocalIdentity(context: Context, credentials: LocalIdentityCredentials): LocalDeviceIdentity { return LocalDeviceIdentity( deviceId = credentials.deviceId, deviceName = getDeviceName(context), deviceType = extensionDeviceType(), longTermPublicKeyHex = pubkeyToHex(credentials.x25519PublicKey), signingPublicKeyHex = pubkeyToHex(credentials.ed25519PublicKey), wsPort = null, relayUrl = RelaySettingsStore.readRelayUrl(context), ) } fun deriveLocalSyncKeypair(masterKey: ByteArray, deviceId: String): SyncIdentityKeypair { throw IllegalStateException("identity_migration_required") } private fun defaultDeviceName(): String { return "Android" } private fun extensionDeviceType(): DeviceType { return DeviceType.ANDROID }