Activation without Android classes
Activation ties a license key to one device. You call it once, when the customer enters the key, and keep the instance.id, which validate and deactivate need, with the signed token. Checking the license on later launches is validation. The class below reuses LicenseApi, LicenseStore and Saved from that page and has no Android dependency, so the device-specific parts are passed in as strings.
// Activation.kt: no Android classes. LicenseApi, LicenseStore and Saved come from the validation page.
import java.io.File
import java.security.MessageDigest
import java.util.UUID
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
private data class Instance(val id: String)
@Serializable
private data class KeyInfo(
val status: String = "",
@SerialName("activation_limit") val activationLimit: Int? = null, // null means unlimited
@SerialName("activation_usage") val activationUsage: Int = 0,
)
@Serializable
private data class ActivateReply(
val activated: Boolean = false,
val error: String? = null,
val instance: Instance? = null,
@SerialName("license_key") val licenseKey: KeyInfo? = null,
val token: String? = null,
)
sealed interface ActivateResult {
data class Activated(val used: Int, val limit: Int?) : ActivateResult
data class LimitReached(val used: Int, val limit: Int?) : ActivateResult
data class Refused(val reason: String, val message: String?) : ActivateResult // expired, disabled, unknown-key, error
data object Offline : ActivateResult
}
fun sha256Hex(text: String): String =
MessageDigest.getInstance("SHA-256").digest(text.toByteArray()).joinToString("") { "%02x".format(it) }
/** For a desktop JVM, which has no portable machine id: an id made once and kept in the app folder. */
fun installId(dir: File): String {
val file = File(dir, "install-id")
if (file.exists()) return file.readText().trim()
dir.mkdirs()
return UUID.randomUUID().toString().also { file.writeText(it) } // deleting the folder means a new seat
}
class Activation(
private val api: LicenseApi,
private val store: LicenseStore,
private val now: () -> Long = { System.currentTimeMillis() / 1000 },
) {
private val lenient = Json { ignoreUnknownKeys = true }
/** [fingerprint] is a hash such as sha256Hex("inkwell:" + deviceId). [deviceName] is what the buyer sees. */
suspend fun activate(key: String, deviceName: String, fingerprint: String): ActivateResult {
val trimmed = key.trim()
val reply = api.post(
"activate",
mapOf("license_key" to trimmed, "instance_name" to deviceName.take(120), "fingerprint" to fingerprint),
)
if (reply.status == 0) return ActivateResult.Offline
val parsed = runCatching { lenient.decodeFromString<ActivateReply>(reply.body) }.getOrNull()
?: return ActivateResult.Refused("error", null) // not Clavem: a captive portal or a proxy page
val instance = parsed.instance
val info = parsed.licenseKey
return when {
parsed.activated && instance != null && parsed.token != null && info != null -> {
store.save(Saved(trimmed, instance.id, parsed.token, checkedAt = now()))
ActivateResult.Activated(info.activationUsage, info.activationLimit)
}
// Branch on data, not on error text. Expired and disabled are refused before the limit is checked.
reply.status == 400 && info != null && info.status in setOf("expired", "disabled") ->
ActivateResult.Refused(info.status, parsed.error)
reply.status == 400 && info != null -> ActivateResult.LimitReached(info.activationUsage, info.activationLimit)
reply.status == 404 -> ActivateResult.Refused("unknown-key", parsed.error)
else -> ActivateResult.Refused("error", parsed.error)
}
}
/** Frees this device's seat. Keeps the local copy when the server could not be reached, so you can retry. */
suspend fun deactivate(): Boolean {
val saved = store.load() ?: return true
val instanceId = saved.instanceId
if (instanceId != null) {
val reply = api.post("deactivate", mapOf("license_key" to saved.key, "instance_id" to instanceId))
if (reply.status != 200 && reply.status != 404) return false // 404: the seat was already gone
}
store.clear()
return true
}
}
Fingerprints on Android
instance_name is for people: the buyer sees it on the device page, so Build.MANUFACTURER plus Build.MODEL is enough. fingerprint is for machines, and on Android it comes from ANDROID_ID:
// Android only.
fun deviceName() = "${Build.MANUFACTURER} ${Build.MODEL}"
fun deviceFingerprint(context: Context): String {
val androidId = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
// A blank id would give every such phone the same hash and the same seat, so fall back to an id of our own.
val seed = if (androidId.isNullOrBlank()) installId(context.noBackupFilesDir) else androidId
return sha256Hex("inkwell:$seed")
}
The Android reference describes ANDROID_ID on API 26 and later as unique to each combination of app-signing key, user and device. That has three consequences for seats:
- Signing keys. A debug build and a release build are signed with different keys, so one phone reports two values and takes two seats. Count your own testers’ phones against the limit of a test license, or give test builds their own product.
- Resets and users. A factory reset gives the phone a new value, and a second user profile has its own.
- Other apps. Apps signed with other keys see different values, so the id is not a cross-app tracker.
The code hashes it with the prefix inkwell:, so the raw value never leaves the device and another app cannot be matched against it. The fallback to installId runs only for a blank value.
Fingerprints on the desktop JVM
A JVM has no portable machine id. installId makes a UUID once and keeps it in the app folder, for example File(System.getProperty("user.home"), ".config/inkwell"). Delete that folder and the next activation takes another seat, which is the trade for a fingerprint that asks for no operating-system permission. Reinstalling the app without deleting the folder keeps the same seat: activating again with a fingerprint that is already active on the license returns that seat, with its name updated.
The limit and the refusals
A fourth device on a license with three seats gets a 400 whose body includes the license_key object. Expired and disabled licenses get the same status, which is why the code reads license_key.status first. limit is null for an unlimited license.
fun message(result: ActivateResult): String = when (result) {
is ActivateResult.Activated -> "Activated. ${result.used} of ${result.limit ?: "unlimited"} devices in use."
is ActivateResult.LimitReached ->
"This key is already active on ${result.used} of ${result.limit} devices. Remove one at clavem.io/licenses/manage."
is ActivateResult.Refused -> result.message ?: "This key cannot be activated (${result.reason})."
ActivateResult.Offline -> "No connection. Try again when you are online."
}
New phone, old phone, uninstall
An app cannot run code when it is uninstalled, so a seat stays used until someone removes it. Put a Remove this device action in settings that calls deactivate(). When a buyer gets a new phone, noBackupFilesDir keeps the license file out of Auto Backup, as the validation page explains, so the new phone asks for the key and takes a seat. The old phone’s seat stays until it is removed. The buyer can do that at /licenses/manage with the key and no email round trip.
What ran
Activation ran on a JVM 17 with Kotlin 2.4.21 against scripted responses in the documented shapes:
| Response | Result |
|---|---|
| 200, 2 of 3 used | Activated(used=2, limit=3), instance id stored |
| 200, unlimited license | Activated(used=12, limit=null) |
| 400, 3 of 3 used | LimitReached(used=3, limit=3), nothing stored |
| 400, expired or disabled | Refused with the reason, nothing stored |
| 404 | Refused("unknown-key") |
| 400, missing field | Refused("error") with the server’s text |
| Status 0, or a 200 HTML page | Offline, or Refused("error") |
| Deactivate, 200 or 404 | true, local file removed |
| Deactivate, status 0 or 429 | false, local file kept |
A 200-character device name was cut to 120, and the key was trimmed before sending. installId returned the same value twice, and the hash of a test id matched sha256 computed separately.
Doing this with Clavem
Your product’s default device limit is set in the dashboard, and a license can carry its own. The fields are in the API reference.
Questions
Does ANDROID_ID stay the same between a debug build and a release build?
Not necessarily. The Android reference says that on API 26 and later it is unique to each combination of app-signing key, user and device. A build signed with another key gives the same phone another value, so a tester can take a second seat.
Can an Android app free its seat when it is uninstalled?
No. An app cannot run code when it is uninstalled. Offer a Remove this device action in settings, and point buyers to clavem.io/licenses/manage for phones they no longer have.