Add licensing to an Electron or Node app (TypeScript)
At the end, your Node, Electron or React Native app activates a licence key and unlocks its features offline.
From your product page in PermitPlane (app.permitplane.com/ops/vendor/), click Download permitplane.json and Create test key.
1. Install
Download permitplane-client-0.2.0.tgz and compare its sha256 with manifest.json. It needs Node 22+, Electron 28+ or React Native 0.79+ (Hermes), and it is ESM only.
sha256sum permitplane-client-0.2.0.tgz
npm install ./permitplane-client-0.2.0.tgz2. Activate a licence key
Load the config, create the client with the built-in Node host and activate once:
import { LicenseClient } from '@permitplane/client';
import {
createDefaultHost,
readConfig,
} from '@permitplane/client/node';
const config = await readConfig('permitplane.json');
const client = new LicenseClient({
config, ...createDefaultHost(config),
});
// Loads the saved state, so a restart needs no request.
await client.initialize();
if (client.status === 'free') {
// paste your test key here; in your real app, ask the user for it
await client.activateWithKey('PP-7KQ4M-X9T2H-B6WRN-3FJ8D');
}3. Unlock features in your app
Turn parts of your app on or off based on what the customer's licence includes. The check is synchronous and works offline up to your policy's offline days.
if (client.hasFeature('export')) {
enableExport();
} else {
showUpgradeOffer();
}const seats = client.getLimit('seats');
// seats.unlimited, or seats.value
// 'free', 'trial', 'paid', 'online_required', 'expired',
// 'recovery_required' or 'seat_unavailable'
const status = client.status;4. Keep it current
- Call
await client.refresh()on start. The client then refreshes every hour. - Call
await client.dispose()before exit. It saves the clock state. - Call
await client.release()to release the device.
Errors
| Error | What to do |
|---|---|
InvalidLicenseKeyError | The key is mistyped. Ask the user to check it. |
ApiFailure with code invalid_license_key | The key is unknown or revoked. Ask for the key from the purchase email. |
ApiFailure with code device_limit | Every device slot is taken. Release another device first. |
ApiFailure with code license_expired, license_suspended or license_revoked | Show a renew or contact link. |
TransportError | The network failed. Retry later. Unlocked features keep working. |
try {
await client.refresh();
} catch (e) {
if (e instanceof ApiFailure) console.error(e.code, e.status);
}Going further
- Unattended and offline activation: installers, services and air-gapped machines.
- Floating licences: concurrent seats with leases.
- Network requirements: what your customer's firewall must allow.
- Reference: your own storage, Electron, React Native, silent activation and floating seats.
Reference
Package
- The tarball is the
@permitplane/clientpackage. - Publishing on npm under the same name is a later option.
- You can also install from the full URL of the file.
- Downloads need no sign-in. On Windows, check a file with
Get-FileHash -Algorithm SHA256 <file>.
Built-in host
createDefaultHost(config) runs in Node and the Electron main process. It gives the client:
- A P-256 installation key and the saved state, in files only your user can read.
- One folder per vendor, product and environment:
%LOCALAPPDATA%\PermitPlane,~/Library/Application Support/PermitPlaneor~/.local/share/permitplane. - A clock from the system uptime and the boot id.
Pass { scope: 'machine' } for a folder every user of the machine shares, or { dir } for your own folder. In an installer, create the machine folder first:
# vendor_id and product_id from permitplane.json
$dir = "$env:ProgramData\vendor_demo\product_demo"
New-Item -ItemType Directory -Force $dir | Out-Null
icacls $dir /inheritance:r `
/grant:r "*S-1-5-18:(OI)(CI)F" "*S-1-5-32-544:(OI)(CI)F"Requests go through fetch.
Use your own storage or HTTP
In React Native, the Electron renderer or the browser, pass your own adapters:
const client = new LicenseClient({
config,
// keep this device's P-256 key in the OS key store
keyStore: myKeyStore,
// load and save the licence state in protected storage
stateStore: myStateStore,
// monotonic time, so clock changes can't extend a licence
clock: myClock,
// send one HTTPS request; never follow redirects
fetch: myFetch,
});- Implement
StateStoreon protected storage: Keychain, Android Keystore or ElectronsafeStorage. - The clock reports monotonic time that includes suspend, plus a boot id.
- Never log the state.
- The memory versions in
@permitplane/client/testingare for tests only. - A sandbox product's
permitplane.jsonalready setsenvironmenttosandbox.
Electron
- Run
LicenseClientin the main process. - Expose
status,hasFeatureandgetLimitto the renderer throughcontextBridge.
React Native
- The client cannot detect React Native. Set
config.platformyourself. - Inject a
cryptoprovider if your runtime has no WebCrypto.
Unattended installs and services
For an installer, container or service with no user, activate from a key the vendor staged. Keep the activation in a machine-wide store.
// %ProgramData%\<vendor>\<product>\<environment>, /var/lib/...
const service = new LicenseClient({
config,
...createDefaultHost(config, { scope: 'machine' }),
});
await service.initialize();
await service.activateSilently({
keySources: [{ env: 'ACME_LICENSE_KEY' },
{ file: '/etc/acme/license.key' }],
consumeKeyFile: true,
});activateSilentlydoes nothing when the saved state is already valid.- It retries network errors and honours
Retry-After. - It never logs the key.
- With
offlineRequestPath, it writes an offline request file when there is no network. - Installer recipes (MSI, pkg, Docker, Kubernetes) are in Unattended and offline activation.
Floating seats
Floating seats need @permitplane/client 0.2.0 or newer. Activate as above, then take a seat:
await client.checkoutSeat(); // or { borrowHours: 48 } to borrow
await client.renewSeat(); // online seats renew at half the lease
await client.releaseSeat(); // give the seat back earlyseatInfo()returns{ kind, expiresAt }ornull.- No free seat:
checkoutSeatthrowsSeatsExhaustedError. Read itsretryAfter. - The status then becomes
'seat_unavailable'. LeaseRequiredErrormeans you must check out a seat first.dispose()returns an online seat but keeps a borrowed one.- With
backgroundRefreshMsat 0 or less, there is no heartbeat. - Then call
renewSeat()yourself, or the seat lapses at the lease TTL.
Error classes
| Class | Fields |
|---|---|
ApiFailure | code, status, requestId, retryAfter |
SeatsExhaustedError, LeaseRequiredError | Subclasses of ApiFailure. |
TransportError | reason: network, timeout or malformed_response. |
InvalidLicenseKeyError | The key is not a valid licence key. |
Good to know
hasFeatureandgetLimitnever touch the network.- The client saves the clock state every minute while access is allowed.
- Concepts explains installations, trials and offline days.