Zum Inhalt springen

Die Entwickler-Doku gibt es nur auf Englisch.

Java SDK

The Java SDK wraps the C SDK, which in turn is the stable interface of the Rust SDK. It has the same calls, states and error codes, and speaks protocol version 1. Java 8 or newer, one dependency: JNA, which Maven and Gradle pull in by themselves. Source: sdks/java/.

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

This SDK is for apps that run on the end user's machine (desktop apps, tools, launchers). Checking license tokens in a Java backend is not covered yet; the Node backend SDK covers that case.

Get it

  • JAR: one JAR, license-sdk-<version>.jar, with the native library for each platform inside, plus its pom. It is not on Maven Central yet; the final coordinates follow with the first release there. Build both with sdks/java/pack.sh (writes to dist/java/) and install them into your local repository:

    mvn install:install-file -Dfile=dist/java/license-sdk-<version>.jar -DpomFile=dist/java/license-sdk-<version>.pom
    

    Then use it like any other dependency:

    <dependency>
      <groupId>foundation.sparx</groupId>
      <artifactId>license-sdk</artifactId>
      <version>0.1.0-alpha.1</version>
    </dependency>
    

    Gradle: implementation("foundation.sparx:license-sdk:0.1.0-alpha.1") with mavenLocal() among the repositories.

  • Platforms: without arguments pack.sh puts in the library for the current machine. Libraries for other systems come from the prebuilt C SDK packages: pack.sh linux-x64=<dir> win-x64=<dir> osx-arm64=<dir>. JNA picks the right one at run time. Signed releases contain the JAR, the pom, the sources and javadoc JARs and an SBOM.

  • Own library location: set the environment variable LICENSE_SDK_LIBRARY to the path of the native library if your app ships it outside the JAR.

  • Modules: the JAR has the automatic module name licensesdk.

Quickstart

import licensesdk.*;

LicenseOptions options = LicenseOptions.builder()
        .productId("prod_01J...")
        .environment(LicenseEnvironment.LIVE)
        .apiBase("https://...")          // your Client API base URL
        .appVersion("1.4.0")
        .publicKey("k4.public....")      // from the dashboard
        .build();

try (LicenseClient client = new LicenseClient(options)) {
    LicenseStatus status;
    // At every start: check locally, no network needed.
    try {
        status = client.check();
    } catch (LicenseException e) {
        if (!e.code().equals("not_activated")) throw e;
        try {
            status = client.activate(keyFromUser);
        } catch (LicenseException failed) {
            showActivationScreen(failed.code());
            return;
        }
    }

    boolean pro = status.has("pro");
    OptionalLong seats = status.limit("seats");   // empty if the plan has no such limit
}

start() combines both steps for app start: it checks locally and, if a token is stored, renews it in the background. The app can continue on the local result at once.

LicenseStart start = client.start();
start.status().ifPresent(this::use);              // now
if (start.renewal().isPresent()) {
    try (LicenseRenewal renewal = start.renewal().get()) {
        use(renewal.await());
    } catch (LicenseException e) {
        if (!e.isTransient()) throw e;            // offline: keep the local result
    }
}

Closing a renewal without waiting lets it finish on its own, which is the usual case: await it only on a worker thread. await() may be called once. The renewal waits for a random point in the token's window, usually hours away, and retries on its own after network failures and rate_limited while the token is usable offline (when the SDK renews). Closing the client ends a waiting renewal.

Calls

Call Network What it does
check() No Verifies the stored license token: signature, product, environment, clock, offline end, device. Use it at every start and before gated features
start() Background check() now, then a renewal on a background thread
activate(key), activate(key, deviceName) Yes Activates this device. The only call that reads hardware features for the first time. The device name comes from the user or is left out
signIn(email, password), signIn(email, password, totpCode) Yes Signs the end customer in with their account at your company, for products with identity mode account or both (protocol section 6.3). Your app asks for email and password; the SDK sends them once and keeps neither. Returns an account valid for 10 minutes, kept in memory only. Error code totp_required: ask for the six digits of the authenticator app and call again with the code. Wrong email, password or code give invalid_credentials, five failures in a row rate_limited. Reads no hardware. Returns an Account (expiresAt(), AutoCloseable)
activateWithAccount(account), activateWithAccount(account, deviceName) Yes Activates this device with the account's license for this product, like activate with a key. invalid_credentials means the account expired or the password changed: sign in again
activateWithUserToken(userToken), activateWithUserToken(userToken, deviceName) Yes Activates this device for a user of your own account system, with a user token your backend signed. It sends the token once and keeps it nowhere; invalid_credentials means the token expired or does not verify, ask your backend for a new one. How your backend signs it: protocol section 6.5
validate() Yes Renews the token. Due when the state is TokenState.GRACE, and at least once a day
heartbeat() Yes Reports a running session, returns the Duration until the next heartbeat
deactivate() Yes Frees this device's activation and deletes the stored token
offlineRequest(), offlineRequest(deviceName) No Starts an offline activation. Returns the request code to show as text or QR code. Reads hardware features like activate
importOffline(file) No Imports the license file issued for the pending request and stores its token
revocationsSeq() No Sequence number of the revocation list this device holds, or empty
remoteConfig() Yes Fetches the remote config of the license and keeps the values the schema of configSchema allows
cachedRemoteConfig() No The last remote config answer while the stored token passes check(), or empty

Calls with network block until the answer or the transport's timeout. Do not call them on the UI thread (Swing EDT, JavaFX application thread); use a worker thread or CompletableFuture.supplyAsync. A client is thread-safe; calls on one client run one after another. close() waits for running calls, and calls after it throw invalid_argument.

A LicenseStatus is a plain snapshot: state(), expiresAt(), offlineUntil(), licenseExpiresAt() (empty for perpetual licenses), licenseGraceUntil() (end of the grace period once the term has ended, else empty), all as Instant; licenseId(), activationId(), channel() (release channel, for example beta, else empty), entitlements (has, limit, variant) and all claims as JSON (claimsJson()).

Remote config

LicenseOptions options = LicenseOptions.builder()
        // ...
        .configSchema(Files.readString(Path.of("config-schema.json"))) // from GET /v1/products/{id}/config-schema
        .build();
RemoteConfig config = client.remoteConfig(); // or client.cachedRemoteConfig() offline, empty if none
boolean dark = config.getBoolean("dark_mode").orElse(false);
long maxProjects = config.integer("max_projects").orElse(5);

A RemoteConfig is a plain snapshot: values(), json(), dropped(), omitted(), serverTime(), and getBoolean, number, integer, text. Only values the schema allows reach the app; the keys of the others are listed as dropped. Keys the server left out because the answer would have been too large are listed as omitted. What the schema may contain and how the cache works is explained in the Rust SDK.

Approved builds

If your product checks builds (build_check in the product settings), tell the client the SHA-256 of the program you ship:

LicenseOptions options = LicenseOptions.builder()
        // ...
        .buildDigest(LicenseClient.buildDigestOf(Main.class))
        .build();

buildDigestOf hashes the JAR that holds the class, not the Java runtime; register the digest of that JAR. LicenseClient.buildDigest(file) hashes any other file. Both throw config_invalid if the file cannot be read or the class does not come from a JAR.

The SDK then sends it as build with validate, heartbeat, update checks, remote config and downloads (protocol, section 6.8). In your build pipeline, register the digest of the same file for its release and platform with POST /v1/releases/{id}/builds (sha256sum of the shipped file). With build_check set to deny, a build the server does not know gets an empty remote config and no updates; with flag it is only recorded. The license keeps working either way. The digest is what the device reports: it catches a patched program that still runs the SDK unchanged, not one whose author also patches the digest.

Updates

checkUpdate(language) asks whether a newer release is published for this device's channel and platform (protocol, section 6.4) and returns an empty Optional when the app is current:

client.checkUpdate("en").ifPresent(update -> {
    System.out.println("Version " + update.version() + " is available.");
    update.notes().ifPresent(System.out::println); // plain text, never HTML
});

UpdateInfo also has channel(), publishedAt(), notesLanguage(), notesTruncated() and required(). Pass null as the language for English. The stored token stays as it is.

If the release has a file for this platform, ask for a short-lived link and fetch it (protocol, section 6.9):

Optional<UpdateInfo> update = client.checkUpdate("en");
if (update.isPresent() && update.get().file().isPresent()) {
    Optional<LicenseDownload> download = client.requestDownload(update.get().version());
    if (download.isPresent()) {
        try (LicenseDownload d = download.get()) {
            d.fetch(new File(downloadsDir, d.file().name())); // checks size and SHA-256
        }
        // Hand the file to your updater. The SDK never runs it.
    }
}

LicenseDownload.fetch saves the bytes to a temporary file next to the destination and gives the file its final name only once size and SHA-256 match; an encrypted file (Rust SDK) is decrypted first. It fails with file_mismatch (kind verify) if the file does not match, server_unreachable if the link fails or has expired (ask for a new one), and storage_failed if the destination cannot be written. requestDownload gives an empty Optional if the server offers no file of that version to this device; with release keys, only files your signed list names are accepted. Fetching the file yourself is possible with the link (url()) and the size and SHA-256 of the file, but not for encrypted files.

  • Installing, checking the installation and rolling back are the job of your updater. The SDK never runs anything it gets.
  • required is true when the running version was blocked or is below the minimum version: install that release before the app carries on. validate then refuses with version_outdated; the update check still works.
  • After installing, report the outcome from the version that runs then: client.reportUpdate(version, false) when the new version started, true when your updater went back to the earlier one. A rolled-back release is not offered to this device again, and too many rollbacks pause the rollout for every device (protocol, section 6.10).

To make sure not even a compromised server can offer a foreign, older or revoked version, sign your release lists in your pipeline as described in the Rust SDK and embed both public keys:

LicenseOptions options = LicenseOptions.builder()
        // ...
        .releaseKey("k4.public.…active…")
        .releaseKey("k4.public.…reserve…")
        .build();

From then on the update check accepts only versions the newest list names and does not revoke, never one older than the running app, and fails with token_mismatch otherwise (key_unknown while no list has arrived yet). releaseListSeq() gives the sequence number of the newest list the client accepted.

Assets

Files outside releases, such as models or content packs: client.listAssets(language) returns AssetInfo values, client.requestAssetDownload(name) an Optional<AssetDownload>, and its fetch(dest) saves and checks the file. Close the download when done. See Assets for visibility, groups and an example.

Usage quotas

An entitlement of the plan with an integer value, such as "exports": 1000, is a quota for the whole term of the license. client.reportUsage("exports", 1, reportId) reports what this device used and returns a UsageGrant with counted(), used(), limit() and remaining() (protocol, section 6.15). The same report_id counts once, so send it again with the same ID when an answer got lost; counted is then false. A report past the quota fails with quota_exhausted (LicenseException, kind server), counts nothing and keeps the stored license token. Vendors grant more units through the Management API.

Proxy calls

client.callProxy("weather", "{\"city\":\"Berlin\"}") calls an endpoint of yours through the platform, so its URL and credentials never ship in your app (protocol, section 6.16). It returns Optional<ProxyResult>: empty if the license may not call a target of that name, else target(), status() and bodyJson() (JSON text) of the endpoint's answer, or failure() (timeout, unreachable, response_too_large, response_invalid). callProxy("weather") sends no body. Set up the target in the Management API; your endpoint gets license, activation and plan with each call, signed like a webhook. A target name the SDK refuses (1 to 100 of a-z, 0-9, ., _, -) or a body that is not a JSON object or array of at most 8 KiB fails with config_invalid before anything is sent. The call needs an activation and keeps the stored license token.

Remote actions

LicenseOptions.builder().actionSchema(schema) takes the action definitions your app accepts, the answer of GET /v1/products/{id}/remote-action-types. client.remoteActions() then returns the actions sent to this device, each a RemoteAction with id(), name(), params() (a Map of String, Long and Boolean), paramsJson(), sentBy() (vendor or customer), issuedAt() and expiresAt() (protocol, section 6.17). Each action comes once and the list holds up to 20, oldest first; call again until it is empty. The SDK drops actions with an unknown name, parameters that do not fit your definitions or an expiry in the past. Without an action schema the call fails with config_invalid, and a schema the SDK cannot use fails when the client is created. The call needs an activation and keeps the stored license token. See Remote actions.

Crash reports

CrashReporter queues crash and error reports on disk, LicenseClient.sendCrashReports sends them, and installUncaughtExceptionHandler() turns uncaught exceptions into crash reports with their stack. Off until your app creates a reporter. See Crash and error reports.

Modules

ModuleRuntime runs WebAssembly modules you signed with your release key, in a sandbox without files, network or processes, so you can change logic such as a quote without a release. See Modules.

Devices without internet

String request = client.offlineRequest("Lab PC 3"); // show as text and QR code
// Later, with the content of the license file (.lic):
LicenseStatus status = client.importOffline(Files.readString(Path.of("license.lic")));
// From now on check() works without network, until the file's end.

The file works only on the device that made the request and only for that request. A changed file fails with signature_invalid, a file from another device with device_mismatch or nonce_mismatch. What offline licenses mean for revocation and refunds is explained in the Rust SDK.

Errors

Every failure is a LicenseException, an unchecked exception. Decide on code(), the same code as in every SDK, for example not_activated, license_revoked, token_expired, server_unreachable, storage_failed, config_invalid (full list in protocol section 7). The message is English text for logs, never for end users.

  • kind() groups the codes: NOT_ACTIVATED, SERVER, VERIFY, UNREACHABLE, STORAGE, CONFIG, INVALID_ARGUMENT, INTERNAL.
  • isTransient() is true when trying again later can help; retryAfter() gives the wait time the server sent.
  • internal_error is a bug in the SDK. Please report it.

The constructor throws with kind CONFIG for an unusable configuration, for example a malformed public key or a plain http:// URL other than localhost.

Offline behavior is that of the Rust SDK: without a usable answer a call fails with server_unreachable, and the stored token keeps working until its offline end.

Storage and transport

By default the client uses the operating system's secure storage under <product_id>.<environment> and HTTPS with a 10 second timeout.

  • Own storage (headless Linux, containers): implement LicenseStore (load, save, remove; load returns null for a missing entry) and pass it to store(...). Protect it like a password store: it holds the device secret.

  • Own transport (proxies, an HTTP client you already configure): implement LicenseTransport (post(url, body) returns a TransportReply) and pass it to transport(...). Return HTTP error statuses as a TransportReply; throw only if no answer arrived.

  • Own chip key (a key in a security chip the app opens itself, such as the Android Keystore): implement LicenseChip (publicKey(productId) returns the SubjectPublicKeyInfo DER or null without a chip, sign(productId, message) returns an ECDSA P-256 signature with SHA-256 in DER, integrity(productId, nonce) optionally a Play Integrity token) and pass it to chip(...). The Android package brings one for the Android Keystore.

All three are called from any thread, never at the same time for the same client. An exception in your implementation never crosses into the native library; the SDK turns it into storage_failed or server_unreachable. The client keeps your objects alive until it is closed.

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 JAR contains no test hooks; those exist only in a native library built with the cargo feature test-hooks, which the SDK's own tests use.