Skip to content

Python SDK

The Python 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. Python 3.10 or newer, no dependencies besides the standard library. Source: sdks/python/.

Pre-release. Versions 0.x are test versions and not meant for production. license_sdk.is_prerelease() is True for them. The package name license-sdk is provisional.

This SDK is for apps that run on the end user's machine. To check license tokens that an app sends to your Python backend, use TokenVerifier from the same package (Verify tokens in a backend).

Get it

  • Wheel: one wheel per platform, license_sdk-<version>-py3-none-<platform>.whl, with the native library inside. It is not on PyPI yet. Build it with sdks/python/pack.sh (writes to dist/python/) and install it with pip install --no-index --find-links dist/python license-sdk.
  • Platforms: without arguments pack.sh builds the wheel for the current machine. Wheels for other systems come from the prebuilt C SDK packages: pack.sh linux-x64=<dir> win-x64=<dir> osx-arm64=<dir>. Signed releases contain the wheels and an SBOM.
  • Linux: wheels carry the manylinux tag their library qualifies for. Built with cargo-zigbuild (pip install ziglang cargo-zigbuild), the library targets glibc 2.17 and the wheel is manylinux_2_17 (CentOS 7, Ubuntu 14.04, Debian 8 and newer, x64 and arm64); pack.sh linux-x64=build linux-arm64=build builds both here. Without cargo-zigbuild the wheel needs at least this machine's glibc.
  • Own library location: set LICENSE_SDK_LIBRARY to the path of the native library if your app ships it outside the package (for example in a frozen app).

Quickstart

from license_sdk import Environment, LicenseClient, LicenseError

with LicenseClient(
    product_id="prod_01J...",
    environment=Environment.LIVE,
    api_base="https://...",          # your Client API base URL
    app_version="1.4.0",
    public_keys=["k4.public...."],   # from the dashboard
) as client:
    # At every start: check locally, no network needed.
    try:
        status = client.check()
    except LicenseError as e:
        if e.code != "not_activated":
            raise
        try:
            status = client.activate(key_from_user)
        except LicenseError as failed:
            show_activation_screen(failed.code)
            raise SystemExit(1)

    pro = status.has("pro")
    seats = status.limit("seats")    # None 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.

start = client.start()
if start.status is not None:
    use(start.status)               # now
if start.renewal is not None:
    with start.renewal as renewal:
        try:
            fresh = renewal.wait()
        except LicenseError as e:
            if not e.is_transient:  # offline: keep the local result
                raise

Closing a renewal without waiting lets it finish on its own, which is the usual case: wait only on a worker thread. 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, device_name=None) Yes Activates this device. The only call that reads hardware features for the first time. The device name comes from the user or is None
sign_in(email, password, totp_code=None) 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 (expires_at, close(), usable with with)
activate_with_account(account, device_name=None) 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
activate_with_user_token(user_token, device_name=None) 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 seconds until the next heartbeat
deactivate() Yes Frees this device's activation and deletes the stored token
offline_request(device_name=None) No Starts an offline activation. Returns the request code to show as text or QR code. Reads hardware features like activate
import_offline(file) No Imports the license file issued for the pending request and stores its token
revocations_seq() No Sequence number of the revocation list this device holds, or None
remote_config() Yes Fetches the remote config of the license and keeps the values the schema of config_schema allows
cached_remote_config() No The last remote config answer while the stored token passes check(), or None

Calls with network block until the answer or the transport's timeout. They release the GIL while they wait, so other threads keep running; to keep a UI responsive, call them from a worker thread or with asyncio.to_thread. A client is thread-safe; calls on one client run one after another. close() waits for running calls.

A LicenseStatus is a plain snapshot: state, expires_at, offline_until, license_expires_at (None for perpetual licenses), license_grace_until (end of the grace period once the term has ended, else None), all as UTC datetime; license_id, activation_id, channel (release channel, for example "beta", else None), entitlements (has, limit, variant) and all claims (claims, claims_json).

Remote config

client = LicenseClient(..., config_schema=Path("config-schema.json").read_text())  # from GET /v1/products/{id}/config-schema
config = client.remote_config()  # or client.cached_remote_config() offline, None if none
dark = config.get_bool("dark_mode") or False
max_projects = config.integer("max_projects") or 5

A RemoteConfig is a plain snapshot: values, dropped, omitted, server_time, and get_bool, 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:

import sys
from license_sdk import build_digest

client = LicenseClient(..., build=build_digest(sys.executable))

Pass the file you ship: sys.executable in a frozen app (PyInstaller, Nuitka), otherwise your wheel or main module, never the Python interpreter of a normal installation. build_digest raises config_invalid if the file cannot be read.

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

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

update = client.check_update("en")
if update is not None:
    print(f"Version {update.version} is available.")
    if update.notes:
        print(update.notes)  # plain text, never HTML

UpdateInfo also has channel, published_at, notes_language, notes_truncated and required. 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):

if update is not None and update.file is not None:
    download = client.request_download(update.version)
    if download is not None:
        with download:
            download.fetch(downloads_dir / download.file.name)  # checks size and SHA-256
        # Hand the file to your updater. The SDK never runs it.

Download.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. request_download gives None 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.report_update(version, rolled_back=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:

client = LicenseClient(..., release_keys=["k4.public.…active…", "k4.public.…reserve…"])

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). release_list_seq() gives the sequence number of the newest list the client accepted.

Assets

Files outside releases, such as models or content packs: client.list_assets(language) returns AssetInfo values, client.request_asset_download(name) an AssetDownload or None, and its fetch(dest) saves and checks the file. Use the download as a context manager. 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.report_usage("exports", 1, report_id=...) 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 (LicenseError, kind server), counts nothing and keeps the stored license token. Vendors grant more units through the Management API.

Proxy calls

client.call_proxy("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 a ProxyResult with target, status and body (parsed JSON) of the endpoint's answer, or failure (timeout, unreachable, response_too_large, response_invalid); None if the license may not call a target of that name. The body is optional. 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

Pass action_schema= to LicenseClient: the action definitions your app accepts, the answer of GET /v1/products/{id}/remote-action-types. client.remote_actions() then returns the actions sent to this device, each a RemoteAction with id, name, params (a dict), sent_by (vendor or customer), issued_at and expires_at (UTC datetime) (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.send_crash_reports sends them, and install_excepthook() turns uncaught exceptions into crash reports with their traceback. 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

request = client.offline_request("Lab PC 3")  # show as text and QR code
# Later, with the content of the license file (.lic):
status = client.import_offline(Path("license.lic").read_text())
# 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.

Verify tokens in a backend

If your app sends its license token to your own server, check it there before you serve gated features. TokenVerifier does the same checks as check() without a client, storage or network: structure, key, signature, schema, product, environment, clock and offline end (protocol section 4). The device check is skipped, because your backend cannot measure the app's device.

from license_sdk import Environment, LicenseError, TokenVerifier

verifier = TokenVerifier(
    product_id="prod_01J...",
    environment=Environment.LIVE,
    public_keys=["k4.public...."],   # one key, or two during a key rotation
)

def handle(request):
    try:
        status = verifier.verify(request.headers["X-License-Token"])
    except LicenseError as e:
        return reject(e.code)        # for example token_expired, signature_invalid
    if not status.has("pro"):
        return reject("not_entitled")
    ...
  • verify(token, now=None, last_server_time=None) returns a LicenseStatus as above. now defaults to the current time; pass last_server_time if you track the latest server time, for the clock rule. Both are timezone-aware datetime values.
  • A failed check raises LicenseError with kind VERIFY and the code of protocol section 7.2. A malformed key or product ID raises kind CONFIG in the constructor.
  • A verifier holds no state and is thread-safe; create one at startup and share it.
  • A token proves that the server issued it for this product recently. It does not prove which device sends it; if that matters, let the app call validate() and send the fresh token.

Errors

Every failure is a LicenseError. 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.
  • is_transient is True when trying again later can help; retry_after gives the wait time the server sent.
  • internal_error is a bug in the SDK. Please report it.

The constructor raises 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): pass an object with load(key) -> bytes | None, save(key, value) and remove(key) as store (protocol LicenseStore). Protect it like a password store: it holds the device secret.
  • Own transport (proxies, an HTTP client you already configure): pass an object with post(url, body) -> TransportReply as transport (protocol LicenseTransport). Return HTTP error statuses as a TransportReply; raise only if no answer arrived.

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