Zum Inhalt springen

Die Entwickler-Doku gibt es nur auf Englisch.

Kotlin SDK

The Kotlin SDK puts Kotlin calls on top of the Java SDK: a configuration block instead of a builder, null instead of Optional, kotlin.time.Duration and default arguments. Underneath it is the same client, with the same calls, states and error codes, speaking protocol version 1. It runs on the JVM from Java 8 on. Source: sdks/kotlin/.

Pre-release. Versions 0.x are test versions and not meant for production. LicenseClient.isPrerelease() is true for them. The artifact ID license-sdk-kotlin and the package name licensesdk.kotlin are provisional; the group ID foundation.sparx stays.

It runs on the JVM (desktop apps, tools and launchers written in Kotlin) and on Android through the Android package: an AAR with the native library for each ABI, storage in the Android Keystore and Play Integrity. Store apps sign the end customer in with an account instead of asking for a key (signing in).

Get it

The Kotlin SDK is not published yet. Install the Java SDK into your local Maven repository as described in Java SDK, Get it, then build this one from the repository:

mvn -f sdks/java/pom.xml install -DskipTests   # or the JAR from sdks/java/pack.sh
cd sdks/kotlin && gradle publishToMavenLocal
repositories { mavenLocal(); mavenCentral() }
dependencies { implementation("foundation.sparx:license-sdk-kotlin:0.1.0-alpha.1") }

It brings the Java SDK and JNA along. The native library comes from the Java SDK's JAR, or from the path in LICENSE_SDK_LIBRARY.

Quickstart

import licensesdk.LicenseEnvironment
import licensesdk.LicenseException
import licensesdk.kotlin.*

licenseClient {
    productId = "prod_01J..."
    environment = LicenseEnvironment.LIVE
    apiBase = "https://..."          // your Client API base URL
    appVersion = "1.4.0"
    publicKey("k4.public....")       // from the dashboard
}.use { client ->
    // At every start: check locally, no network needed.
    val status = try {
        client.check()
    } catch (e: LicenseException) {
        if (e.code() != "not_activated") throw e
        try {
            client.activate(keyFromUser)
        } catch (failed: LicenseException) {
            showActivationScreen(failed.code())
            return
        }
    }

    val pro = status.has("pro")
    val seats: Long? = status.limitOrNull("seats")   // null if the plan has no such limit
}

licenseClient { } returns the Java SDK's LicenseClient; licenseOptions { } returns only the LicenseOptions. The block has the settings of the Java builder as properties (productId, environment, apiBase, appVersion, store, transport, chip, configSchema, actionSchema, buildDigest) and publicKey(...) and releaseKey(...) for the key lists. A setting the client needs but the block left out fails when the client is created.

Start with start() as in the Java SDK, read with the Kotlin properties:

val start = client.start()
start.statusOrNull?.let(::use)                    // now
start.renewalOrNull?.use { renewal ->
    try {
        use(renewal.await())
    } catch (e: LicenseException) {
        if (!e.isTransient) throw e               // offline: keep the local result
    }
}

Signing in instead of a key

val account = try {
    client.signIn(email, password)
} catch (e: LicenseException) {
    if (e.code() != "totp_required") throw e
    client.signIn(email, password, askForCode())
}
account.use { client.activateWithAccount(it) }

activateWithUserToken(token) activates with a token your own backend signed. What the calls do, which codes they give and what the SDK keeps is described in Java SDK, Calls.

Kotlin calls

All Java calls stay usable as they are. The Kotlin SDK adds these, so you rarely touch Optional:

Kotlin Java SDK
client.heartbeatInterval(): Duration heartbeat(): java.time.Duration
client.cachedRemoteConfigOrNull() cachedRemoteConfig()
client.checkUpdateOrNull(language = null) checkUpdate(language)
client.requestDownloadOrNull(version) requestDownload(version)
client.assets(language = null) listAssets(language)
client.requestAssetDownloadOrNull(name) requestAssetDownload(name)
client.callProxyOrNull(target, bodyJson = null) callProxy(target), callProxy(target, bodyJson)
client.releaseListSeqOrNull(), client.revocationsSeqOrNull() releaseListSeq(), revocationsSeq()
status.licenseExpiresAtOrNull, status.licenseGraceUntilOrNull, status.channelOrNull licenseExpiresAt(), licenseGraceUntil(), channel()
status.limitOrNull(code), status.variantOrNull(code) limit(code), variant(code)
e.retryAfterOrNull: Duration? retryAfter()
start.statusOrNull, start.errorOrNull, start.renewalOrNull status(), error(), renewal()
config.booleanOrNull(key), numberOrNull, integerOrNull, textOrNull getBoolean(key), number, integer, text
update.notesOrNull, notesLanguageOrNull, fileOrNull notes(), notesLanguage(), file()
asset.groupOrNull, titleOrNull, descriptionOrNull group(), title(), description()
proxy.statusOrNull, bodyJsonOrNull, failureOrNull status(), bodyJson(), failure()

Remote config, updates, assets, usage quotas, proxy calls, remote actions, crash reports, modules and offline files work as in the Java SDK.

Threads and coroutines

Calls with network block until the answer or the transport's timeout. Never call them on the main thread; with coroutines, wrap them:

val status = withContext(Dispatchers.IO) { client.validate() }

A client is thread-safe; calls on one client run one after another. Close it with use or close() when the app ends.

Errors

Every failure is a licensesdk.LicenseException, the exception of the Java SDK, unchecked like every Kotlin exception. Decide on code(), the same code as in every SDK (full list in protocol section 7); kind(), isTransient and retryAfterOrNull work as in Java SDK, Errors. The message is English text for logs, never for end users.

Storage and transport

Own storage and transport are the Java interfaces, written as Kotlin lambdas or objects:

licenseClient {
    // ...
    transport = LicenseTransport { url, body -> myHttp.post(url, body).let { TransportReply(it.code, it.text) } }
}

What they must do and how to protect the store: Java SDK, Storage and transport.

Android

The Android package foundation.sparx:license-sdk-android (package licensesdk.android, provisional like the other names) is an AAR for Android 8 (API 26) and later. It holds the native library for arm64-v8a, armeabi-v7a and x86_64, brings JNA as an AAR, and adds what Android needs:

  • androidLicenseClient(context) { ... }: licenseClient with Android's defaults. The block is the same as above; leave store and chip out to get the two below.
  • KeystoreStore: the SDK's state, encrypted with AES-256-GCM under a key in the Android Keystore that never leaves it. One store per product and environment, as files in noBackupFilesDir, which Android leaves out of backups: a phone restored from a backup activates again instead of carrying the old phone's license. An entry the key cannot open counts as missing.
  • KeystoreChip: binds the activation to a P-256 key in the phone's secure hardware (StrongBox where there is one, else the TEE). The device ID is the SHA-256 of its public key, and every signed call carries its signature, so a copied activation does not work on another phone (security chip). A phone whose Keystore keeps keys in software only binds by installation ID.
  • PlayIntegrity: a classic Play Integrity request for the call that creates the activation, for products where you set up Play Integrity (PATCH /v1/products/{id}/attestation). The server decrypts and checks the verdict with your own response keys. Set it only then: the server refuses a token it does not expect, and requires one when Play Integrity is set up.
import licensesdk.android.*

val client = androidLicenseClient(context) {
    productId = "prod_01J..."
    apiBase = "https://..."
    appVersion = BuildConfig.VERSION_NAME
    publicKey("k4.public....")
    // Only when Play Integrity is set up for the product:
    chip = KeystoreChip(PlayIntegrity(context, cloudProjectNumber = 123456789012))
}

// Off the main thread, as every call with network:
lifecycleScope.launch(Dispatchers.IO) {
    val status = client.activate(key)
}

PlayIntegrity needs Google Play on the phone and the library in your app, which the package does not bring, so apps without Play Integrity stay free of it: implementation("com.google.android.play:integrity:1.6.0"). Its request blocks for up to 30 seconds and must not run on the main thread. If it fails, activate fails with storage_failed and nothing is sent.

The package declares the INTERNET permission and no other. Its consumer R8 rules keep the classes JNA reaches by reflection. Store apps sign the customer in with an account (signing in); checks run at every start with check() as on the JVM.

The package is not published yet. Build it from the repository with the Android SDK and NDK and the Rust targets aarch64-linux-android, armv7-linux-androideabi and x86_64-linux-android:

ANDROID_HOME=~/Android/Sdk sdks/android/build.sh publishToMavenLocal
repositories { mavenLocal(); google(); mavenCentral() }
dependencies { implementation("foundation.sparx:license-sdk-android:0.1.0-alpha.1") }

Security properties

As for the Rust SDK: public keys only, no secret in the app, no plain http:// except for localhost, no code from the server is ever run. The Kotlin layer adds no network or storage of its own.

Tests

sdks/kotlin/test.sh builds the native library with the test hooks, installs the Java SDK into the local Maven repository and runs every license token and activation answer of the test vectors through the Kotlin calls.

Example app. sdks/android/example is a small app for Android 8 and later with the same flow as the Swift example: the local check at start, the renewal behind it, sign-in with a second factor, activateWithAccount, what the plan unlocks, and sign-out with deactivate(), never a key. Publish the package to the local Maven repository as above, enter your product's settings in Settings.kt and open the folder in Android Studio. Its texts are in English and German. It has not run on a phone yet; it is compiled against the Android 16 classes only.

sdks/android/test.sh runs the Android package with Robolectric on the JVM: the Keystore store (encryption, entries bound to their names, entries a key cannot open), the names of the keys, and activate through the native library with the chip key and a Play Integrity token in the request. Robolectric has no Android Keystore, so these tests use software keys behind the same seams; the Keystore calls themselves need a phone or an emulator.