Skip to content

Rust SDK

The Rust SDK (crates/sdk-core) is the first SDK and the core that later SDKs (C, C++, C# and others) wrap. It speaks protocol version 1.

Pre-release. Versions 0.x.y-alpha.n are test versions and not meant for production. sdk_core::PRERELEASE is true for them.

Quickstart

use sdk_core::{Client, Config, Environment, Error};

let client = Client::new(Config {
    product_id: "prod_01J...".into(),
    environment: Environment::Live,
    public_keys: vec!["k4.public....".into()], // from the dashboard
    api_base: "https://...".into(),            // your Client API base URL
    app_version: env!("CARGO_PKG_VERSION").into(),
})?;

// At every start: check locally, no network needed.
let status = match client.check() {
    Ok(status) => status,
    Err(Error::NotActivated) => client.activate(&key_from_user, None)?,
    Err(e) => return Err(e),
};

// Gate features by entitlement.
let pro = status.claims.ent.0.contains_key("pro");

A runnable version is crates/sdk-core/examples/quickstart.rs:

PRODUCT_ID=prod_... PUBLIC_KEY=k4.public.... API_BASE=https://... LICENSE_KEY=... \
  cargo run -p sdk-core --example quickstart

Calls

Call Network What it does
check() No Verifies the stored license token: signature, product, environment, clock, offline end, device, revocation list. Use it at every start and before gated features
start() Background check() now, then validate() on a background thread at a random point in the token's window, with retries (when the SDK renews). The app can start on the local result at once
activate(key, device_name) Yes Activates this device. The only call that reads hardware features for the first time. device_name comes from the user, the SDK never reads the host name
validate() Yes Renews the token. Due when check() reports 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
sign_in(email, password, totp_code) Yes Signs the customer in with their account at your store, for products with identity mode account or both. Returns an AccountToken valid for 10 minutes, kept in memory only. Stores nothing and reads no hardware
activate_with_account(&account, device_name) Yes Activates this device with the account's license for this product, like activate with a key
activate_with_user_token(user_token, device_name) Yes Activates this device for a user of your own account system, with a user token your backend signed
check_update(language) Yes Asks whether a newer release is published for this device's channel and platform. Returns Some(UpdateInfo) with version, channel, published_at and the release notes in language (en or de, else English), or None when the app is current. Leaves the stored token as it is
report_update(version, rolled_back) Yes Reports whether the release version your updater installed runs or was rolled back. Call it from the version that runs afterwards. A rolled-back release is not offered to this device again
report_usage(entitlement, amount, report_id) Yes Reports amount units of a quota of the plan, such as "exports": 1000, used by this device. report_id is your own ID of this use: the same ID counts once, so send it again when an answer got lost. Returns UsageGrant with counted, used, limit and remaining. A report past the quota is refused with quota_exhausted and counts nothing. Leaves the stored token as it is
call_proxy(target, body) Yes Calls an endpoint of yours through the platform, set up as a proxy target in the Management API, so its URL and credentials never ship in your app. body (optional) is a JSON object or array of at most 8 KiB. Returns ProxyResult with the endpoint's status and JSON body, or a failure (timeout, unreachable, response_too_large, response_invalid); None if the license may not call a target of that name. Your endpoint gets license, activation and plan with each call, signed like a webhook. Leaves the stored token as it is
remote_actions() Yes Fetches the actions waiting for this device, oldest first, up to 20 per call, each at most once. Needs with_action_schema(json) with the definitions your app accepts; actions outside them or already expired are dropped. See Remote actions. Leaves the stored token as it is
remote_config() Yes Fetches the remote config of the license and keeps the values the embedded schema allows (with_config_schema). Stores the signed answer. Leaves the stored token as it is
cached_remote_config() No The last remote config answer, checked again, while the stored token passes check(); None if none is stored
start_device_code(device_name) Yes Starts redeeming in the browser, for devices without a convenient keyboard. Returns a DeviceCode with user_code to show, expires_at and interval_s. Reads hardware features like activate
poll_device_code(&code) Yes Asks once: Pending until the customer confirms the code, then Activated with the stored token
wait_for_device_code(&code) Yes Polls every interval_s until the code is confirmed, refused or expired. Blocks the calling thread
offline_request(device_name) 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, if any

A Status holds the state, the verified claims and license_grace_until: once the license term (claims.lexp) has ended and the plan grants a grace period, the end of that period (gexp), so the app can show "usable until …"; None within the term. claims.chn names the release channel the license gets updates from, for example beta; the end customer can switch it in the portal if the vendor allows it.

The API is synchronous and uses plain data, so the C interface wraps it without changes. Calls on one Client are serialized; share it with Arc.

Redeeming with a device code

On a TV, console or kiosk, typing a 25-character key is a chore. Show a short code instead and let the customer confirm it on a phone or computer (protocol section 6.1):

let code = client.start_device_code(Some("Living room"))?;
println!("Go to https://example.com/activate and enter {}", code.user_code);
let status = client.wait_for_device_code(&code)?;

The address of the confirmation page is yours: a page of your site that calls the Management API (GET /v1/device-codes/{user_code} to show what the code stands for, POST /v1/device-codes/{user_code}/approve with the license or key the customer chose), or the customer portal: <portal>/<en|de>/portal/device?code=<user_code> opens its confirmation page with the code filled in; the customer signs in there and picks one of their licenses or enters a key. A code expires after 10 minutes (device_code_expired: start again). The device limit applies when the code is redeemed; on device_limit_reached the code stays valid, so the customer can free a device and you can keep polling.

Activating with an account

If your product uses customer accounts (identity mode account or both), your customers sign in instead of typing a key (protocol section 6.3). Your app asks for email and password; the SDK sends them once and keeps neither:

let account = match client.sign_in(&email, &password, None) {
    Err(e) if e.code() == "totp_required" => {
        let code = ask_for_totp_code();
        client.sign_in(&email, &password, Some(&code))?
    }
    other => other?,
};
let status = client.activate_with_account(&account, Some("Desk"))?;

The server picks the license: one this device is already activated on, else the newest usable one of this product. Wrong email, password or code give invalid_credentials, the same answer whether the address has an account or not. After five failures in a row the account is locked for 15 minutes (rate_limited with retry_after_s). An account token works only for the product and environment it was issued for, and only until it expires or the password changes; on invalid_credentials from activate_with_account, sign in again.

Activating with your own accounts

If your users sign in to your own account system, your backend can vouch for them instead of a license key (protocol section 6.5). Register your backend's Ed25519 public key once (POST /v1/products/{id}/user-token-keys), give each customer the external_user_id of their user in your system, and let the backend sign a short-lived user token after its own sign-in (Node: signUserToken). The app passes it on:

let user_token = my_backend.user_token_for_this_app()?; // your API, after your sign-in
let status = client.activate_with_user_token(&user_token, Some("Desk"))?;

The server picks the license of that customer as for accounts. A token that is expired, signed with an unregistered key or for another product gives invalid_credentials: get a new one from the backend. A user without a customer gives license_not_found. The SDK keeps the token nowhere.

When the SDK renews

start() spreads the renewals of all devices, so that not every device asks at the same moment after an outage or on your update day:

  • A fresh token is renewed at a random point between 50 and 90 percent of its lifetime: with the default of 24 hours, between 12 and about 21.6 hours after it was issued. If that point has passed, or the token is in grace, the renewal runs within a minute of the start.
  • After server_unreachable (also an unsigned 429 or 503) or rate_limited, the renewal tries again after 15 to 30 seconds, then 30 to 60, and so on, doubling up to 15 to 30 minutes. A retry_after_s from the server is a lower bound, spread over up to half of it again.
  • It gives up on any other refusal, and when the next try would fall after the token's offline end. A token that fails the local check is renewed once, at once.
  • The app is never blocked: check() answers from the stored token while the renewal waits. If the app renews meanwhile with validate(), the background renewal ends with that result when its wait is over, without another request.

Renewal::join returns the result, but can wait for hours; Renewal::cancel and Client::stop_renewals end a waiting renewal (its result is then server_unreachable). If you renew on your own instead, use sdk_core::renewal::renew_after and retry_after for the same timing.

Telling users about updates

Publish a release with notes in the Management API (/v1/releases), and the app can show them (protocol section 6.4):

if let Some(update) = client.check_update(Some("en"))? {
    println!("Version {} is available.", update.version);
    if let Some(notes) = &update.notes {
        println!("{notes}");
    }
}

The answer considers the license's release channel and the channels below it, and only releases for this platform or for every platform. Notes longer than 6000 characters arrive cut, with notes_truncated. The check works below the minimum version too, so an app refused with version_outdated can still name the version to install.

Downloading an update

When check_update returns an update with a file, ask for a link and fetch it:

if let Some(update) = client.check_update(Some("en"))? {
    if update.file.is_some() {
        if let Some(grant) = client.request_download(&update.version)? {
            let dest = downloads_dir.join(&grant.file.filename);
            sdk_core::download::fetch(&grant, &dest)?; // checks size and SHA-256, decrypts
            // Hand `dest` to your updater. The SDK never runs it.
        }
    }
}
  • The link works for 5 minutes and only for a usable license. None means the server offers no file of that version to this device, for example because the rollout has not reached it yet or was paused.
  • fetch writes to <dest>.part and renames only a file with the expected size and SHA-256; anything else is deleted and refused with InvalidData. If you fetch the file yourself, check it with sdk_core::download::file_matches.
  • Links must be https (plain http only for localhost).
  • Installing, checking the installation and rolling back are the job of your updater. The example updater does all three on Linux, Windows and macOS.
  • After installing, report the outcome from the version that runs then: client.report_update(&update.version, false) when the new version started, true when your updater went back to the earlier one. Too many rollbacks pause the rollout for every device (protocol, section 6.10).
  • update.required is Some(true) when the running version was blocked or is below the minimum version: install that release before the app carries on. validate refuses a blocked version with version_outdated, and check_update still works then.

Assets

Files outside releases, such as models or content packs: client.list_assets(language) lists the ones this license may fetch, client.request_asset_download(name) gives a link for 5 minutes or None, and sdk_core::download::fetch_asset(&grant, &dest) saves and checks the file like fetch. See Assets for visibility, groups and an example.

Encrypted release files

To create, upload and publish a release from your pipeline in one step, see Publish from CI.

So that a leaked download link is useless without a license, let your pipeline encrypt each file before uploading it (protocol, section 6.12). Only a device that asked for the download can open it.

  1. Fetch the product's public wrapping key with GET /v1/products/{id}/wrapping-key (per environment).
  2. Encrypt: release-tool encrypt <product_id> <test|live> <key_id> <public_key> app.msi app.msi.sealed. It prints size_bytes, sha256 and encryption for the announcement.
  3. Announce app.msi.sealed with POST /v1/releases/{id}/files using those fields and the file name devices should see (app.msi), and upload it as usual. In a signed release list, list app.msi.sealed (release-tool file), since that is what the server stores.

Nothing changes in the app: request_download sends a key made for that one download, and fetch checks the encrypted file and then decrypts it to dest. grant.encrypted() tells you whether it did. The customer portal does not offer encrypted files; ship the first installer unencrypted. Older SDKs get no link for an encrypted file.

Releases signed by you

So that not even a compromised server can hand your app a foreign, older or revoked version, sign a list of your releases in your own pipeline (protocol, section 6.11). Noctix never sees the private key.

  1. Create a key once with release-tool keygen (from crates/release-tool), keep the private key in your pipeline's secrets as RELEASE_KEY and register the public key with POST /v1/products/{id}/release-keys. Create a reserve key the same way.
  2. For every release, write the list (pid, env, a higher seq, releases with the entries release-tool file <platform> <path> prints, revoked), sign it with release-tool sign list.json and upload the token with POST /v1/products/{id}/release-lists.
  3. Embed both public keys in the app:
let client = client.with_release_keys(&["k4.public.…active…", "k4.public.…reserve…"])?;

From then on check_update and request_download accept only versions and files the newest list names and does not revoke, never a version older than the running app, and fail with token_mismatch otherwise (key_unknown while no list has arrived yet). To change keys, ship the reserve key first, then sign with it and remove the old one.

Modules you signed

Logic you want to change without a release can ship as a WebAssembly module that runs in a sandbox, without files, network or processes, and only if you signed it with your release key. The runtime is the separate crate sdk-modules; see Modules.

Remote config

Set values per product, plan, entitlement or license in the Management API (/v1/products/{id}/config-keys, /v1/products/{id}/config-values), and the app reads the ones of its license (protocol section 6.6). Embed the product's schema from GET /v1/products/{id}/config-schema in the app:

let client = Client::new(config)?.with_config_schema(include_str!("config-schema.json"))?;

let config = client.remote_config()?; // online; stores the signed answer
let dark = config.bool("dark_mode").unwrap_or(false);
let max = config.integer("max_projects").unwrap_or(5);

// Offline: the last answer, checked again, while the license token is valid.
if let Some(config) = client.cached_remote_config()? {
    println!("{}", config.to_json());
}

Remote config is data, never code: booleans, numbers and texts. The SDK checks every answer against the schema you embedded, not against one the server sends:

  • Supported per key: type (boolean, integer, number, string), minimum, maximum, maxLength and description; at the top additionalProperties: false. The schema of the Management API uses exactly these. Any other keyword gives config_invalid, so you never rely on a rule the SDK does not check.
  • Values of keys the schema does not know and values it does not allow are dropped and listed in dropped. Add a key in the Management API before a new app version embeds it, and old apps simply drop it.
  • An answer holds at most 16 KiB. If the values do not fit, the server leaves out keys in key order and lists them in omitted; keep long texts few.
  • cached_remote_config() gives the last answer without network after checking its signature again, while the stored license token passes check() and belongs to the same activation. None if nothing is stored.
  • Remote config is readable on the device. Never put secrets in it.

Approved builds

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

let client = Client::new(config)?.with_build(sdk_core::current_build_digest()?);

The SDK then sends it as build with validate, heartbeat, check_update, remote_config and request_download (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 executable). Use build_digest(path) if the program is a different file than the executable, such as an assembly or a bundle. 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.

Devices without internet

For machines that never reach the Client API, for example in a closed company network, use an offline license (protocol section 6.2):

// 1. Show the request code, as text and as a QR code.
let request = client.offline_request(Some("Lab PC 3"))?;
println!("Enter this code with your license key in the customer portal:\n{request}");

// 2. The customer brings back the license file (`.lic`) and you pass its content.
let file = std::fs::read_to_string("license.lic")?;
let status = client.import_offline(&file)?;

// 3. From now on check() works without network, until the file's end.
client.check()?;

The file works only on the device that made the request and only for that request. A changed file fails the signature check (signature_invalid), a file from another device fails with device_mismatch or nonce_mismatch.

What to tell your customers and plan for:

  • An offline license runs until the end of its offline term. Revoking it early needs contact: if the device gets online, every answer of the Client API carries the product's signed revocation list, and a later file does too. A license on the list stops working at the next check() (token_revoked). An older list never replaces a newer one.
  • A device that never gets a new list keeps its file until it ends, also after a refund or a device change. Keep the offline term short and renew it, and keep the reset allowance of offline plans small.
  • The SDK remembers the latest server time it has seen, so a clock set back by more than 5 minutes is refused. Without contact this protects only back to the time of the last file or list.

Devices behind a host

A device without its own internet access can reach the Client API through a host in its local network, such as a gateway or a PC (protocol section 6.19). On the device, pass a RelayTransport over any link that reads and writes, and fetch files through it:

use sdk_core::relay::RelayTransport;
use std::sync::Arc;

let link = std::net::TcpStream::connect("192.168.1.10:7700")?;
let relay = Arc::new(RelayTransport::new(link));
let client = Client::with_parts(config, store, Box::new(relay.clone()))?;
// ...
if let Some(download) = client.request_download("2.0.0")? {
    relay.fetch(&download, &dest)?;   // checked against size and SHA-256
}

api_base still has to be a valid https URL; the host ignores it and uses its own. On the host, Host::new(api_base, transport, fetch) serves one device per link with serve(link): it forwards only Client API calls to its own base URL and fetches only links that it relayed in the last 5 minutes (HttpFetch for HTTPS). The host can delay or drop calls but cannot change them, because calls are signed on the device and answers are signed by the server. It does see what the device sends, so it should be your machine or your customer's.

Offline and errors

  • Without a usable answer (no network, timeout, unsigned or unverifiable answer) a call fails with server_unreachable. The stored token keeps working until its offline end (oexp), 7 days by default.
  • A signed refusal ends the license on this device at once. On license_* codes and activation_not_found the SDK deletes the stored token. rate_limited, version_outdated, session_limit_reached, quota_exhausted and account_blocked (the vendor's account is blocked) leave it in place, as do authorization_pending and device_code_expired of the device code flow and invalid_credentials and totp_required of the sign-in.
  • The SDK never accepts a system time more than 300 seconds before the latest server time it has seen (clock_rollback).

Error::code() returns the same codes in every SDK:

Code Meaning
not_activated No token stored. Call activate
Server codes, e.g. license_revoked, device_limit_reached Signed refusal, protocol section 7.1
token_expired, device_mismatch, clock_rollback, token_revoked, ... The stored token failed the local check, protocol section 7.2
server_unreachable No usable answer, see above
storage_failed The secure storage failed
config_invalid Wrong product ID, key, URL or app version

Storage

Client::new keeps the license token, the last seen server time, the device secret, the device key of the activation, the installation ID, a pending offline request, the revocation list and the last remote config answer in the operating system's secure storage: Keychain on macOS, Credential Manager on Windows, Secret Service on Linux. The entries live under the service name <product_id>.<environment>. The Credential Manager takes at most 2560 bytes per entry, so on Windows the SDK splits longer values, such as a large revocation list or remote config, over several entries named <entry>.<generation>.<part>.

Headless Linux and containers often have no Secret Service. Pass your own storage there with Client::with_parts and a type that implements sdk_core::store::Store. MemoryStore keeps everything in memory (tests, CI).

Each call of the system's storage waits at most 60 seconds (OS_STORE_TIMEOUT, change it with OsStore::with_timeout) and then fails with storage_failed. The storage can wait for an answer forever: the macOS Keychain asks before a program reads an entry that another program created, for example an unsigned build after a rebuild or two apps with the same product ID, and a locked Secret Service collection asks to be unlocked. Without a screen, as on a build machine, nobody can answer. Sign your app so its updates keep access to its entries, and give each app its own product ID or storage.

Security properties

  • The SDK holds public keys only, never a secret of the vendor or of Noctix. The device secret is created on the device and never sent.
  • Each activation creates its own Ed25519 device key on the device. Only its public half goes to the server, with activate or the device code poll; the SDK signs every later call of that activation with it (protocol, section 6.7). A copied license token alone cannot act for the device, and a copied request is refused once it was used. The key is kept in the same storage as the license and deleted with deactivate. Where the device has a usable security chip (TPM 2.0 on Linux and Windows, the Secure Enclave on macOS), the activation binds to a key in the chip, and the chip signs every call too; a copy of the stored activation on another device is refused. See device-identification.md; a device from your own production also sends its factory certificate with with_device_certificate (devices from your own production).
  • Plain http:// is refused except for localhost and 127.0.0.1.
  • The SDK never starts, loads or runs code it receives. License tokens and remote config are data checked against a schema. Modules you signed run only through the separate crate sdk-modules, in a sandbox (Modules).
  • Device identification: device-identification.md.

Not yet included

  • Issuing offline license files in the customer portal and the Management API, and revocation lists in answers of the Client API, follow on the server side with #253; the SDK side is ready.