LicenseRepository.kt

2.1 KB · raw

1package com.peachpasswords.license23import android.content.Context4import androidx.security.crypto.EncryptedSharedPreferences5import androidx.security.crypto.MasterKey6import dagger.hilt.android.qualifiers.ApplicationContext7import javax.inject.Inject8import javax.inject.Singleton910/**11 * Validation lives in [LicenseCodec]; this class owns storage only.12 */13@Singleton14class LicenseRepository @Inject constructor(@ApplicationContext context: Context) {15    companion object {16        private const val PREFS_FILE = "peach_license_prefs"17        private const val KEY_LICENSE = "peach_license"18        private const val KEY_PRO_CELEBRATED = "peach_pro_celebrated"19    }2021    private val masterKey = MasterKey.Builder(context)22        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)23        .build()2425    private val prefs = EncryptedSharedPreferences.create(26        context,27        PREFS_FILE,28        masterKey,29        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,30        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,31    )3233    fun storeLicense(key: String): Boolean {34        if (!validateLicense(key)) return false35        prefs.edit()36            .putString(KEY_LICENSE, key)37            .remove(KEY_PRO_CELEBRATED)38            .apply()39        return true40    }4142    fun getLicenseKey(): String? = prefs.getString(KEY_LICENSE, null)4344    fun getLicenseIssuedAtMillis(): Long? = getLicenseKey()?.let(::licenseIssuedAtMillis)4546    fun clearLicense() = prefs.edit().remove(KEY_LICENSE).apply()4748    fun isProCelebrated(): Boolean = prefs.getBoolean(KEY_PRO_CELEBRATED, false)4950    fun markProCelebrated() = prefs.edit().putBoolean(KEY_PRO_CELEBRATED, true).apply()5152    fun isProActive(): Boolean = getLicenseKey()?.let(::validateLicense) == true5354    // The signed payload is only 12 bytes and carries no per-feature data; gates use the licence verdict directly.55    fun hasFeature(): Boolean = isProActive()5657    fun validateLicense(licenseKey: String): Boolean = LicenseCodec.validate(licenseKey)5859    fun licenseIssuedAtMillis(licenseKey: String): Long? = LicenseCodec.issuedAtMillis(licenseKey)60}