SDKs
Official, open-source clients live at github.com/sunlicense-com. They all use the same two settings:
| Setting | Value |
|---|---|
| Base URL | https://api.sunlicense.com |
| Token | an API key from Dashboard → API keys (slk_…) |
The examples read the API key from the SUNLICENSE_API_KEY environment variable (or, in FiveM, the sunlicense_api_key convar). Keep it apart from SUNLICENSE_TOKEN, which holds a personal access token (slp_…) for the CLI and AI assistants: that one can manage your organization and never belongs in an app.
Every SDK calls POST /api/v2/license/validate. HTTP 200 means valid; 400 means rejected, and the body's code says why (result codes). Pass a stable machine id as host so machine limits work.
// implementation 'com.sunlicense:sunlicense:0.0.1'
SunLicense client = new SunLicense.Builder()
.baseUrl("https://api.sunlicense.com")
.token(System.getenv("SUNLICENSE_API_KEY"))
.build();
SunLicense.Result result = client.validate(licenseKey, Map.of("host", machineId));
if (!result.isValid()) { /* result.getBody() has the code */ }// npm install sunlicense
import { SunLicense } from "sunlicense";
const client = new SunLicense({ baseUrl: "https://api.sunlicense.com", token: process.env.SUNLICENSE_API_KEY });
const result = await client.validate(licenseKey, { host: machineId });# pip install sunlicense
import os
import platform
from sunlicense import SunLicense
client = SunLicense(base_url="https://api.sunlicense.com", token=os.environ["SUNLICENSE_API_KEY"])
result = client.validate(license_key, host=platform.node())// dotnet add package SunLicense
using var client = new SunLicenseClient("https://api.sunlicense.com",
token: Environment.GetEnvironmentVariable("SUNLICENSE_API_KEY"));
var result = await client.ValidateAsync(licenseKey, new Dictionary<string, string> { ["host"] = machineId });// composer require sunlicense/sunlicense
$client = new SunLicenseClient('https://api.sunlicense.com', token: getenv('SUNLICENSE_API_KEY'));
$result = $client->validate($licenseKey, ['host' => $machineId]);-- luarocks install sunlicense (or drop sunlicense.lua into your FiveM/GMod resource)
local SunLicense = require("sunlicense")
local client = SunLicense.new({ baseUrl = "https://api.sunlicense.com", token = GetConvar("sunlicense_api_key", "") })
client:validate(licenseKey, { host = GetConvar("sv_hostname", "") }, function(ok, status, body) end)The Rust client (cargo add sunlicense) currently provides configuration only; validation is coming.
Writing a Minecraft plugin or mod, a FiveM resource or a Discord bot? Start from a template: the SDK, store placeholders, messages and an offline fallback, ready to build.
Using an AI coding assistant? Use SunLicense with your AI assistant has one prompt that sets everything up in any language, and the docs in a format assistants read well.
Built-in analytics
Every official SDK (Java, JavaScript, Python, .NET, PHP and Lua, from 0.1.0; the templates already) reports anonymous usage statistics for the product's Analytics tab: which versions of your product people run, on which OS, runtime and platform, like bStats. You write no code beyond starting it; it never runs on the license check's path, never delays or fails a check, and swallows its own errors.
// A licensed product: the same API key, license key and machine id it validates with.
SunLicenseAnalytics analytics = SunLicenseAnalytics.builder()
.apiKey(System.getenv("SUNLICENSE_API_KEY")).licenseKey(licenseKey).fingerprint(machineId)
.productVersion("2.3.1")
.enabled(config.getBoolean("analytics", true)) // your config's switch
.start();
// A free product, no license: its public product analytics id (Product → Analytics).
SunLicenseAnalytics analytics = SunLicense.analytics("pa_7Hk2mQ9xZr4LbN8vT1wYcD");
analytics.close(); // on shutdown, e.g. a plugin's onDisable// Licensed: the client's base URL and API key, plus the license key and machine id it validates with.
const analytics = client.analytics({ licenseKey, fingerprint: machineId, productVersion: '2.3.1',
enabled: config.analytics !== false });
// Free: the product analytics id. The install id lives in a hidden per-user dir by default (defaultStateDir()).
const analytics = SunLicense.analytics('pa_7Hk2mQ9xZr4LbN8vT1wYcD');
analytics.close(); // on shutdown (its timers never keep the process alive)# Licensed
analytics = client.analytics(license_key, machine_id, product_version="2.3.1",
enabled=config.get("analytics", True))
# Free
analytics = SunLicense.analytics_for("pa_7Hk2mQ9xZr4LbN8vT1wYcD", data_directory="data")
analytics.close() # on shutdown (it runs on a daemon thread)// Licensed
using var analytics = client.Analytics(licenseKey, machineId,
new SunLicenseAnalyticsOptions { ProductVersion = "2.3.1", Enabled = config.Analytics });
// Free
using var analytics = SunLicenseAnalytics.ForProduct("pa_7Hk2mQ9xZr4LbN8vT1wYcD");// Licensed. PHP has no background thread: a due report is sent after the script ends (at most every 30 minutes),
// and its schedule is kept in dataDirectory.
$analytics = $client->analytics(['licenseKey' => $key, 'fingerprint' => $machineId,
'productVersion' => '2.3.1', 'dataDirectory' => __DIR__ . '/storage']);
// Free
$analytics = SunLicenseAnalytics::forProduct('pa_7Hk2mQ9xZr4LbN8vT1wYcD', ['dataDirectory' => __DIR__ . '/storage']);-- Licensed (FiveM, RedM, Garry's Mod; plain Lua calls analytics:poll() from its main loop)
local analytics = client:analytics({ licenseKey = key, fingerprint = machineId,
enabled = GetConvar("myresource_analytics", "true") ~= "false" })
-- Free
local analytics = SunLicense.analytics("pa_7Hk2mQ9xZr4LbN8vT1wYcD")The first report goes 1 to 30 minutes after start (random, so a fleet restarted together doesn't report together), then one every 30 minutes to POST /api/v2/analytics/report. When SunLicense answers with Retry-After (analytics switched off for the product, rate limits) the SDK waits that long, at most 24 hours.
What is sent (raw values; SunLicense groups them, e.g. 5.15.0-1051-oracle into Linux 5.15):
| Field | Example | Where it comes from |
|---|---|---|
productVersion | 2.3.1 | What you pass as the product version; the templates use their build version (FiveM: fxmanifest.lua's version) |
os, osVersion | Linux, 5.15.0-1051-oracle | The runtime's OS name and version (FiveM: from the server build string; Garry's Mod: the OS family only) |
arch | aarch64 | The CPU architecture, where the runtime tells it |
cores | 4 | Processors available to the runtime, where it tells them |
locale | en_US | The default locale |
runtime, runtimeVersion | java, 21.0.4 | See the table below |
platform, platformVersion | paper, 1.21.1-R0.1-SNAPSHOT | Detected, see the table below; every SDK lets you override it |
sdk | java 0.1.0 | The SDK's name and version |
| Identity | Licensed: the license key and machine id, with the API key. Free: the product analytics id and a random install id kept in a hidden per-user directory (where SDK state lives), one file per product — never next to the product |
| SDK | Runtime | Platforms it detects (else standalone) |
|---|---|---|
| Java | java + java.version | Paper, Spigot, Purpur, Folia and other Bukkit servers (by their own name), BungeeCord, Waterfall, Velocity, Sponge, Fabric, Quilt, Forge, NeoForge (the Minecraft version), a Discord bot on JDA or Javacord (the library's version) |
| JavaScript | node, bun or deno + version | fivem/redm (server build), electron, discord (discord.js, Eris, Oceanic or Discordeno installed: its version) |
| Python | python + version | discord (discord.py, nextcord, disnake, interactions.py or hikari imported: its version) |
| .NET | dotnet or mono + version | fivem/redm (CitizenFX loaded: the server build), discord (Discord.Net, DSharpPlus, NetCord, Remora), unity |
| PHP | php + PHP_VERSION | wordpress, laravel, symfony (with their version) |
| Lua | lua (luajit on Garry's Mod) + version | fivem/redm (the server build, e.g. 7290), gmod |
The country comes from Cloudflare's edge, not from the SDK; no IP address is stored. Nothing personal is sent: no user, host, server or player names, IP addresses or file paths.
Switching it off. Nothing is sent, not even an empty report, when any of these says so, checked before every report:
- your product's own setting:
enabled(false)/enabled: false/Enabled = false(the templates'analytics: false,ANALYTICS=falsein the bot's.env,set my_resource_analytics falseon FiveM); - the environment variable
SUNLICENSE_ANALYTICS=off(alsofalseor0), for every product on the machine; - the platform's global switch: the system property
-Dsunlicense.analytics=false(Java), the runtime settingsunlicense.analytics(.NETruntimeconfig.json), the constantSUNLICENSE_ANALYTICSdefined asfalse(PHP), the convarsunlicense_analytics(FiveM, every SunLicense resource on the server) or the globalSUNLICENSE_ANALYTICS = false(Lua).
Feature usage and custom charts
Count how often your features are used and add your own charts, bStats' chart types. Feature uses are counted in memory and sent with the next report, kept until one is accepted and dropped while analytics is off; chart callbacks run just before each report, and one that throws or returns nothing is left out. Names and chart ids: [a-z0-9][a-z0-9._-]{0,47}; at most 50 different features and 30 charts per report. A report that would pass 16 KB leaves out the charts first, then the features.
analytics.feature("auto-sell");
analytics.simplePie("storage", () -> config.getString("storage"))
.singleLine("players", () -> Bukkit.getOnlinePlayers().size());analytics.feature('auto-sell');
analytics.simplePie('storage', () => config.storage)
.singleLine('servers', () => client.guilds.cache.size);analytics.feature("auto-sell")
analytics.simple_pie("storage", lambda: config["storage"]).single_line("servers", lambda: len(bot.guilds))analytics.Feature("auto-sell");
analytics.SimplePie("storage", () => config.Storage).SingleLine("players", () => Players.Count);$analytics->feature('auto-sell');
$analytics->simplePie('storage', fn () => $config['driver'])->singleLine('users', fn () => $userCount);analytics:feature("auto-sell")
analytics:simplePie("framework", function() return Config.Framework end)
:singleLine("players", function() return #GetPlayers() end)| Chart | Callback returns | Java / JS / PHP / Lua | Python | .NET |
|---|---|---|---|---|
| Simple pie | a value ("mysql") | simplePie | simple_pie | SimplePie |
| Advanced pie | weighted values ({mysql: 2, sqlite: 1}) | advancedPie | advanced_pie | AdvancedPie |
| Drilldown pie | values with a second level ({"Java 21": {"21.0.4": 1}}) | drilldownPie | drilldown_pie | DrilldownPie |
| Single line | a number, summed over installs | singleLine | single_line | SingleLine |
| Multi line | several numbers ({overworld: 30, nether: 12}) | multiLine | multi_line | MultiLine |
| Simple bar | numbers per category | simpleBar | simple_bar | SimpleBar |
| Advanced bar | several numbers per category ({gold: [1, 2, 3]}) | advancedBar | advanced_bar | AdvancedBar |
removeChart(id) stops sending one. Feature usage and custom charts show up on the Lite and Standard plans (product analytics); the reports are the same on every plan.
Protection: core unlock, tamper reports, notice, protected files
Part of your product can be made to run only with a valid license, so a copy whose license check was deleted (by a cracker or an AI editor asked to "remove the license check") has nothing to run. Every SDK does it the same way (Java; JavaScript, Python, .NET, PHP and Lua from 0.2.0). The honest limit: someone with a valid license can still pull the key out of memory and patch their copy; that copy then reports itself as modified, and download watermarks name the leaker. How it fits together, and the steps without an SDK: Protection.
| Piece | What the SDK does |
|---|---|
| Core unlock | sunlicense seal encrypts the core at build time (an SLS1.… blob). A valid check's answer carries unlock, the key that opens it; unseal(blob) returns the core. A rejected check (suspended, expired, revoked…) carries none and makes the SDK forget the one it had |
| Outages | The unlock from the last valid check is kept for 7 days, encrypted with a key from the license key, the machine id and this machine, so a copied cache file is useless elsewhere. An offline license file carries it too (Java, JavaScript, Python, PHP) |
| Tamper reports | The seal can carry SHA-256 digests of your other files. integrity(…) compares them with what's running and the result (OK or MODIFIED, plus up to 200 characters of which files) goes with the next license check, where Sentinel sees it |
| Ownership notice | notice() is one start-up log line: product, owner, the masked key and your terms link. Never the buyer's name or a full key |
| Protected files | protectedFile(name) downloads a file you uploaded to the product (Standard plan); SunLicense sends it only while the license is valid |
sunlicense seal core.lua --product my-resource -o core.sealed --digest fxmanifest.lua// SunLicenseProtection: one dependency-free file (Java 11+), see Single-file sources below. Copy it; don't edit it.
SunLicenseProtection protection = SunLicenseProtection.builder()
.apiKey(apiKey).licenseKey(licenseKey).fingerprint(machineId)
.product("MyPlugin", "Example Studio").terms("https://example.com/terms")
.productCode("myplugin") // for protected files
// the 7-day unlock cache lives in a hidden per-user dir by default (defaultStateDir()), not next to your
// product; call .cacheDirectory(...) only to put it somewhere specific
.build();
log.info(protection.notice()); // "MyPlugin is licensed software by Example Studio. License AX8P-XXXX-…"
Map<String, String> context = new LinkedHashMap<>(Map.of("host", machineId));
context.putAll(protection.validateFields()); // integrity: OK / MODIFIED, once the jar was checked
SunLicense.Result r = client.validate(licenseKey, context);
if (r.isValid()) protection.accept(r.getBody()); // keeps (and caches) the unlock
else if (r.getStatus() == 400) protection.rejected(); // a "no": the unlock is gone
// Offline fallback: protection.acceptOffline(licFile, publicKey) takes the .lic file's unlock.
byte[] core = protection.unseal(SEALED_CORE); // throws Locked without a valid unlock
protection.integrity(MyPlugin.class.getClassLoader()); // OK / MODIFIED, sent with the next check
ClassLoader coreClasses = SunLicenseProtection.classLoader(core, MyPlugin.class.getClassLoader());
byte[] rules = protection.protectedFile("rules.dat"); // Standard planconst protection = client.protection({ licenseKey, fingerprint: machineId, product: 'My Bot',
owner: 'Example Studio', terms: 'https://example.com/terms' }); // unlock cache: hidden per-user dir by default
console.log(protection.notice());
await client.validate(licenseKey, { fingerprint: machineId }); // sends integrity, keeps or forgets the unlock
const core = protection.unseal(SEALED_CORE); // throws Locked without a valid unlock
protection.integrity(appDir); // 'OK' / 'MODIFIED', sent with the next checkprotection = client.protection(license_key=key, fingerprint=machine_id, product="My Bot",
owner="Example Studio", terms="https://example.com/terms", cache_directory="data")
print(protection.notice())
client.validate(key, fingerprint=machine_id) # sends integrity, keeps or forgets the unlock
core = protection.unseal(SEALED_CORE) # raises Locked without a valid unlock
protection.integrity(app_dir) # "OK" / "MODIFIED", sent with the next checkvar protection = client.Protection(new SunLicenseProtectionOptions {
LicenseKey = key, Fingerprint = machineId, Product = "My App", Owner = "Example Studio",
Terms = "https://example.com/terms", CacheDirectory = dataFolder });
Console.WriteLine(protection.Notice());
await client.ValidateAsync(key, new Dictionary<string, string> { ["fingerprint"] = machineId });
byte[] core = protection.Unseal(SealedCore); // throws SunLicenseLockedException without a valid unlock
protection.Integrity(AppContext.BaseDirectory); // "OK" / "MODIFIED", sent with the next check$protection = $client->protection(['licenseKey' => $key, 'fingerprint' => $machineId, 'product' => 'My Plugin',
'owner' => 'Example Studio', 'terms' => 'https://example.com/terms', 'cacheDirectory' => $dataDir]);
error_log($protection->notice());
$client->validate($key, ['fingerprint' => $machineId]); // sends integrity, keeps or forgets the unlock
$core = $protection->unseal(SEALED_CORE); // throws LockedException without a valid unlock
$protection->integrity(__DIR__); // 'OK' / 'MODIFIED', sent with the next checklocal protection = client:protection({ licenseKey = key, fingerprint = machineId, product = "My Script",
owner = "Example Studio", terms = "https://example.com/terms" })
print(protection:notice())
client:validate(key, { fingerprint = machineId }, function(ok)
local core, err = protection:unseal(LoadResourceFile(GetCurrentResourceName(), "core.sealed"))
if core then load(core, "@core")() end -- nil + reason without a valid unlock
protection:integrity() -- "OK" / "MODIFIED", sent with the next check
end)The Java templates do all of this for you: their core package is sealed in release builds (./gradlew build -PsunlicenseProduct=<code>, which calls sunlicense seal on the final jar and digests your other classes), loaded through license/SealedCore.java, and the notice is logged at start-up. Apps that use none of it behave exactly as before: no integrity is sent and nothing is cached until a product has sealed data.
The FiveM and discord.js templates seal server/core.lua and src/core.js the same way (SUNLICENSE_PRODUCT=<code> when you run scripts/package.sh or npm run build) and log the notice at start-up.
Without a native AES-GCM the SDKs bring their own: pure Lua on FiveM, Garry's Mod and plain Lua; pure Python when cryptography isn't installed; the platform's AES block cipher on .NET (netstandard2.0, Mono, Unity, CitizenFX). PHP needs ext-openssl (or ext-sodium on a CPU with AES). Digest files that don't contain the sealed text itself, and on FiveM only files Tebex's escrow leaves readable.
Single-file sources
Some SDK classes are one file with no dependencies, so you can copy them into a project whose installed SDK release doesn't have them yet. Copy the current file and change only its package line; don't write it yourself from these pages. Each file is built from the SDK on every docs release:
| Language | Class | File |
|---|---|---|
| Java 11+ | SunLicenseProtection (core unlock, tamper reports, notice, protected files, offline unlock) | /sdk/java/SunLicenseProtection.java |
| Java 11+ | SunLicenseAnalytics (built-in analytics) | /sdk/java/SunLicenseAnalytics.java |
The templates carry the same files in their license/ folder. Other SDKs: install the latest release, or for Lua copy sunlicense.lua, which is one file already (the FiveM template's lib/sunlicense.lua).
Choosing a machine id
Use something stable across reboots and updates: a hash of hardware identifiers, or an id you generate once and store. Don't use the IP address. The Java CLI's fingerprint command shows one approach.
Prefer an id derived from host facts over one you store, so there is no file to leave next to your product. The Java SDK exposes SunLicenseProtection.machineId() (OS, architecture, hostname and MAC addresses, hashed) and the JavaScript SDK exports machineId(); the templates use these. If you do store an id, keep it in a hidden per-user directory (see below), not the product's own folder.
Where SDK state lives
By default the SDKs keep their state — the 7‑day unlock cache, the analytics install id, and any machine id you store — in a hidden per-user directory, never next to your product, so there is nothing for an end user to see or delete:
| OS | Directory |
|---|---|
| Linux / other | $XDG_CACHE_HOME/sunlicense or ~/.cache/sunlicense |
| macOS | ~/Library/Caches/SunLicense |
| Windows | %LOCALAPPDATA%\SunLicense |
Falling back to ~/.sunlicense, then the system temp directory. It is one small file per product. The Java SDK exposes the directory as SunLicenseProtection.defaultStateDir() / SunLicenseAnalytics.defaultStateDir(); the JavaScript SDK exports defaultStateDir(). If you set cacheDirectory / dataDirectory explicitly, the SDK writes a single file there instead. When an older build kept an id next to the product (a .server-id, .machine-id or .sunlicense-install-id), the SDK carries that value into the hidden directory once and removes the old file, so installs keep their machine slot. Anything that can't reach an OS directory (a FiveM resource, which may only use LoadResourceFile/SaveResourceFile) keeps a single file inside the resource folder instead, and says so.
Handling errors
| HTTP | Meaning | Recommended behaviour |
|---|---|---|
| 200 | Valid | Continue |
| 400 | Rejected (see code) | Block or prompt, depending on the code |
| 401 | Missing or wrong API key | A configuration bug in your app |
| 429 | Rate limited | Retry later |
| 5xx / network error | SunLicense is unreachable | Fall back to the offline license |
