Clavem

Validate a license key in a JetBrains IDE plugin

Keep the key in PasswordSafe, keep the instance id and token in a non-roaming state file so each machine gets its own seat, and call POST /v1/licenses/validate from a coroutine on Dispatchers.IO, never on the EDT. If you sell through JetBrains Marketplace, its own licensing may fit better.

Marketplace licensing, or your own

JetBrains Marketplace has licensing for paid plugins. According to its documentation you declare the plugin’s paid attributes in plugin.xml, and the license checks, including a check on IDE startup and at least one a day, happen on the platform side. If you sell through Marketplace, start there.

Your own keys make sense when you sell outside Marketplace, for example from your site through Stripe, or when one license has to cover a plugin and a desktop app. The rest of this guide is for that case.

Where each piece lives

Item Store it in Why
License key PasswordSafe The platform’s credential store, for passwords and API keys. Blocking, so never on the EDT.
Instance id and token a state component with roamingType = RoamingType.DISABLED The default DEFAULT shares settings between IDE installations. With sharing, a second machine inherits the instance id and never activates.

The platform docs also say an application-level light service that is a PersistentStateComponent must disable roaming, so the setting is required here anyway. The token holds the buyer’s email address, which is another reason to keep it local.

The code

LicenseToken is the verifier from the offline verification guide. This uses java.net.http from the JDK and Gson for JSON; check that Gson is on your target IDE’s classpath, or bundle it.

package com.example.inkwell

import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.credentialStore.generateServiceName
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.ProjectActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
import java.util.concurrent.atomic.AtomicBoolean

private const val BASE = "https://clavem.io"

enum class LicenseStatus { LICENSED, INVALID, NEEDS_NETWORK, UNLICENSED }

/** Instance id and token. Not roamed: each machine activates for itself. */
@Service(Service.Level.APP)
@State(name = "InkwellLicense", storages = [Storage(value = "inkwell-license.xml", roamingType = RoamingType.DISABLED)])
class LicenseStorage : SimplePersistentStateComponent<LicenseStorage.State>(State()) {
    class State : BaseState() {
        var instanceId by string()
        var token by string()
    }
}

@Service(Service.Level.APP)
class LicenseService {
    private val http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(4)).build()
    private val keyAttributes = CredentialAttributes(generateServiceName("Inkwell", "License key"))
    private val checked = AtomicBoolean(false)

    @Volatile
    var status = LicenseStatus.UNLICENSED
        private set

    private class Reply(val status: Int, val json: JsonObject?)

    /** Blocks the calling thread for up to 8 seconds, so call it from Dispatchers.IO. */
    private fun post(action: String, body: Map<String, String>): Reply {
        val request = HttpRequest.newBuilder(URI.create("$BASE/v1/licenses/$action"))
            .timeout(Duration.ofSeconds(8))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(Gson().toJson(body)))
            .build()
        return try {
            val res = http.send(request, HttpResponse.BodyHandlers.ofString())
            Reply(res.statusCode(), runCatching { JsonParser.parseString(res.body()).asJsonObject }.getOrNull())
        } catch (e: IOException) {
            Reply(0, null) // no network, DNS failure or timeout
        }
    }

    /** Once per machine, when the user pastes the key. Returns a message to show, or null on success. */
    suspend fun activate(licenseKey: String): String? = withContext(Dispatchers.IO) {
        val key = licenseKey.trim()
        val name = "${ApplicationNamesInfo.getInstance().fullProductName} on ${System.getProperty("os.name")}"
        val json = post("activate", mapOf("license_key" to key, "instance_name" to name)).json
        if (json?.get("activated")?.asBoolean != true) {
            return@withContext json?.get("error")?.asString ?: "Could not reach the license server."
        }
        PasswordSafe.instance.setPassword(keyAttributes, key)
        val state = service<LicenseStorage>().state
        state.instanceId = json["instance"].asJsonObject["id"].asString
        state.token = json["token"].asString
        status = LicenseStatus.LICENSED
        null
    }

    suspend fun checkOncePerSession() {
        if (checked.compareAndSet(false, true)) status = check()
    }

    private suspend fun check(): LicenseStatus = withContext(Dispatchers.IO) {
        val key = PasswordSafe.instance.getPassword(keyAttributes)
        val state = service<LicenseStorage>().state
        val instanceId = state.instanceId
        if (key.isNullOrBlank() || instanceId.isNullOrBlank()) return@withContext LicenseStatus.UNLICENSED

        val reply = post("validate", mapOf("license_key" to key, "instance_id" to instanceId))
        val json = reply.json
        when {
            reply.status == 200 && json != null -> {
                // Keep the new token even when the license is not valid: offline, it then says so.
                state.token = json["token"].asString
                if (json["valid"].asBoolean) LicenseStatus.LICENSED else LicenseStatus.INVALID
            }
            reply.status == 404 -> {
                state.instanceId = null // unknown key, or this machine was removed: ask for the key again
                state.token = null
                LicenseStatus.INVALID
            }
            // Offline, rate limited (429) or the service is down (503): trust the stored token while it is fresh.
            else -> if (LicenseToken.isLicensed(LicenseToken.verify(state.token.orEmpty()))) LicenseStatus.LICENSED
                    else LicenseStatus.NEEDS_NETWORK
        }
    }
}

/** Runs for every project that opens, so the AtomicBoolean keeps it to one check per IDE session. */
class LicenseStartup : ProjectActivity {
    override suspend fun execute(project: Project) {
        service<LicenseService>().checkOncePerSession()
    }
}

Register the activity in plugin.xml:

<extensions defaultExtensionNs="com.intellij">
  <postStartupActivity implementation="com.example.inkwell.LicenseStartup"/>
</extensions>

Gate a feature with service<LicenseService>().status == LicenseStatus.LICENSED in an action’s update(). That is a plain read, safe on the EDT. Never call check() or post() from there.

Outcomes

Answer check() returns State
200, valid: true LICENSED token replaced
200, valid: false INVALID token replaced, key kept
404 INVALID instance id and token cleared
429 or 503 stored token decides unchanged, asks again next session
no network, timeout stored token decides unchanged

JetBrains traps

  • Threads. The threading page says operations on the EDT must be fast so the UI does not freeze. PasswordSafe and HttpClient.send are both blocking, so both sit inside withContext(Dispatchers.IO).
  • Once per session. ProjectActivity runs for each project you open. Without the guard, three open projects make three calls.
  • Proxies. The IDE has its own proxy settings, and the platform’s HttpRequests helper handles proxy authentication. A plain HttpClient does not go through that code, so test it behind a corporate proxy, or switch to HttpRequests.
  • The sandbox. The Gradle sandbox IDE starts with its own configuration, so a license you activate there is not in your everyday IDE.

What I could not test

I could not compile or run this Kotlin: no Kotlin compiler or IntelliJ Platform was available. The PasswordSafe, service, state and ProjectActivity usage follows the platform docs linked above. The same HTTP flow, written in TypeScript, Python and PHP, was run against a mock server and against the demo key. The key encoding used in the offline guide was checked by running its logic in Node.

Doing this with Clavem

The License API needs no secret, so the plugin ships none. Clavem activates, validates and deactivates devices through three POSTs described in the API reference, and the buyer can free a seat on their device page.

Questions

Does the IDE's settings sync copy the license to my other computer?

It can. A persistent state component uses roamingType DEFAULT unless you change it, and the platform docs say that means the settings are shared. Set roamingType to DISABLED so the instance id and token stay on one machine and each machine activates for itself.

Why is PasswordSafe not called from the UI thread?

The platform docs say getPassword is blocking and must not run on the EDT, the thread that handles UI events. Call it from a coroutine on Dispatchers.IO.

Sources

  1. IntelliJ Platform docs, persisting sensitive data (PasswordSafe; checked November 2026)
  2. IntelliJ Platform docs, roaming settings (RoamingType; checked November 2026)
  3. IntelliJ Platform docs, plugin services (light services and roaming; checked November 2026)
  4. IntelliJ Platform docs, plugin components (ProjectActivity; checked November 2026)
  5. IntelliJ Platform docs, threading model (checked November 2026)
  6. JetBrains Marketplace docs, license verification calls in plugin code (checked November 2026)