One checker, two thin adapters
The check is plain Kotlin with no Android classes. It talks to the network through a small LicenseApi interface and to the disk through a LicenseStore, so the same code runs in an Android app, a Compose Desktop app and a unit test. It asks the server at most once a day, never sleeps on a retry, and uses the stored token when the server cannot answer. The token check, verifyToken and isLicensed, is on offline verification in Kotlin. Creating the stored license in the first place is device activation.
// LicenseChecker.kt: no Android classes, so it also runs in a desktop JVM and in unit tests.
// verifyToken and isLicensed come from the offline verification page.
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
const val BASE = "https://clavem.io"
const val PUBLIC_KEY = "YOUR_PUBLIC_KEY" // from your product page
const val PRODUCT_ID = 75L // from your product page
private const val ONLINE_EVERY = 24 * 60 * 60L // seconds between online checks; the token covers the days in between
@Serializable
data class Saved(
val key: String,
val instanceId: String? = null,
val token: String? = null,
val checkedAt: Long = 0,
val pauseUntil: Long = 0,
)
@Serializable
private data class Reply(val valid: Boolean, val error: String? = null, val token: String? = null)
/** status 0 means no answer: offline, DNS failure or timeout. */
class ApiResponse(val status: Int, val retryAfter: Long?, val body: String)
interface LicenseApi {
suspend fun post(action: String, form: Map<String, String>): ApiResponse
}
interface LicenseStore {
suspend fun load(): Saved?
suspend fun save(saved: Saved)
suspend fun clear()
}
sealed interface LicenseState {
data object Licensed : LicenseState
data object NeedsNetwork : LicenseState
data object Unlicensed : LicenseState
data class Invalid(val message: String) : LicenseState
}
class LicenseChecker(
private val api: LicenseApi,
private val store: LicenseStore,
private val now: () -> Long = { System.currentTimeMillis() / 1000 },
) {
private val json = Json { ignoreUnknownKeys = true }
suspend fun check(): LicenseState {
val saved = store.load() ?: return LicenseState.Unlicensed
val t = now()
if (t - saved.checkedAt >= ONLINE_EVERY && t >= saved.pauseUntil) {
val form = buildMap {
put("license_key", saved.key)
saved.instanceId?.let { put("instance_id", it) }
}
val reply = api.post("validate", form)
// A captive portal or proxy page is not Clavem: only a JSON body with `valid` counts as an answer.
val parsed = runCatching { json.decodeFromString<Reply>(reply.body) }.getOrNull()
when {
reply.status == 200 && parsed != null -> {
// Keep the new token even when the license is not valid: offline, it then says so.
store.save(saved.copy(token = parsed.token, checkedAt = t, pauseUntil = 0))
return if (parsed.valid) LicenseState.Licensed
else LicenseState.Invalid(parsed.error ?: "This license is not valid.")
}
reply.status == 404 && parsed != null && !parsed.valid -> {
store.clear() // unknown key, or this device was removed: ask for the key again
return LicenseState.Invalid(parsed.error ?: "This license was not found.")
}
// 429 and 503 say when to come back. Do not wait here: skip the online check until then.
reply.status == 429 || reply.status == 503 ->
store.save(saved.copy(pauseUntil = t + (reply.retryAfter ?: 60)))
}
}
// Not asked today, offline, rate limited or the service is down: use the stored token.
val claims = verifyToken(saved.token, PUBLIC_KEY)
if (claims != null && !claims.valid) return LicenseState.Invalid("This license is ${claims.status}.")
return if (isLicensed(claims, PRODUCT_ID, t)) LicenseState.Licensed else LicenseState.NeedsNetwork
}
}
The adapters
OkHttpLicenseApi sends the form body that the License API accepts next to JSON and moves to Dispatchers.IO itself, so no caller can put the request on the main thread. FileLicenseStore writes a temporary file and moves it over the old one.
// Adapters.kt. Dependencies: com.squareup.okhttp3:okhttp, org.jetbrains.kotlinx:kotlinx-coroutines-core,
// org.jetbrains.kotlinx:kotlinx-serialization-json. The manifest needs <uses-permission android:name="android.permission.INTERNET" />.
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
class OkHttpLicenseApi(
private val client: OkHttpClient = OkHttpClient.Builder().callTimeout(5, TimeUnit.SECONDS).build(),
) : LicenseApi {
override suspend fun post(action: String, form: Map<String, String>): ApiResponse = withContext(Dispatchers.IO) {
val body = FormBody.Builder().apply { form.forEach { (k, v) -> add(k, v) } }.build()
val request = Request.Builder().url("$BASE/v1/licenses/$action").header("User-Agent", "Inkwell/1.4.0").post(body).build()
try {
client.newCall(request).execute().use { res ->
ApiResponse(res.code, res.header("Retry-After")?.toLongOrNull(), res.body?.string().orEmpty())
}
} catch (e: IOException) {
ApiResponse(0, null, "") // offline, DNS failure or timeout
}
}
}
class FileLicenseStore(private val file: File) : LicenseStore {
private val json = Json { ignoreUnknownKeys = true }
override suspend fun load(): Saved? = withContext(Dispatchers.IO) {
runCatching { json.decodeFromString<Saved>(file.readText()) }.getOrNull()
}
override suspend fun save(saved: Saved) = withContext(Dispatchers.IO) {
file.parentFile?.mkdirs()
val temp = File(file.path + ".tmp")
temp.writeText(json.encodeToString(saved))
// Replaces the old file in one step: a crash never leaves half a file.
Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
Unit
}
override suspend fun clear() = withContext(Dispatchers.IO) {
file.delete()
Unit
}
}
// Android: val checker = LicenseChecker(OkHttpLicenseApi(), FileLicenseStore(File(context.noBackupFilesDir, "license.json")))
// viewModelScope.launch { _state.value = checker.check() }
// Desktop: FileLicenseStore(File(System.getProperty("user.home"), ".config/inkwell/license.json"))
Where it lives on Android
filesDir is private to the app, but it is also what Auto Backup copies when a user sets up a new phone. The license file holds the key, the instanceId and the token. A restored copy lets the new phone validate against an instance that belongs to the old one, and the two phones then share a seat. noBackupFilesDir is excluded from Auto Backup, so the new phone starts unlicensed and asks for the key, which is the behavior you want. A desktop JVM has no such rule: use the user’s config folder, %APPDATA% on Windows.
Two smaller points. Add INTERNET to the manifest, or every request fails. And keep the timeout short. callTimeout(5) covers the whole call, including DNS, so a dead network costs the user at most five seconds, and the check runs while the screen is already up.
Scenarios that were run
The checker ran on a JVM 17 with Kotlin 2.4.21, with a scripted LicenseApi and an in-memory LicenseStore, and the verification code from the offline page. Tokens came from a throwaway key pair and the product id was 75.
| Scenario | Result | Left on disk |
|---|---|---|
| No stored license | Unlicensed |
nothing |
200, valid: true |
Licensed |
new token, checkedAt set |
429 with Retry-After: 60 |
Licensed from the token |
pauseUntil 60 seconds ahead |
503 with Retry-After: 5 |
Licensed from the token |
pauseUntil 5 seconds ahead |
| Paused, or checked today | Licensed, no request made |
unchanged |
| Status 0, stale token | NeedsNetwork |
unchanged |
| 200 or 404 with an HTML body | Licensed from the token |
unchanged |
404 with valid: false |
Invalid, “instance_id not found.” |
file removed |
200, valid: false, expired |
Invalid, “This license key has expired.” |
the expired token |
| That expired token, offline | Invalid, “This license is expired.” |
unchanged |
FileLicenseStore ran too: an empty read, a save, an overwrite that left one file, a corrupt file read as null, and a clear. It sends the same fields as the API reference describes.
Doing this with Clavem
The License API needs no secret, so nothing sensitive ships in the APK or the jar. For apps distributed through Google Play, check Google’s payment rules for digital features before you ask for a license key inside the app. The calls and responses are in the API reference.
Questions
Why keep the license in noBackupFilesDir on Android?
Auto Backup copies files from filesDir to a new phone, and the license file holds the key, the instance id and the token. A restored copy would let a second phone validate against a seat it never activated. Files in noBackupFilesDir are excluded from Auto Backup.
Will validate on the main thread crash an Android app?
Yes. Android throws NetworkOnMainThreadException for network calls on the main thread in apps that target Honeycomb or newer. The code here switches to Dispatchers.IO inside the API class, so calling check() from viewModelScope.launch is safe.