Node.js

Add licensing to a Node.js or Electron app with the pwfauth package from npm

The pwfauth package from npm handles the encryption, the heartbeat and the kill switch for you. It needs Node.js 18 or newer, has no dependencies (it runs on Node's own fetch and crypto) and ships TypeScript definitions. It is an ES module: load it with import, or with await import('pwfauth') from CommonJS

The package holds your app secret, so it belongs in the Node.js side of your program: an Electron main process, a command-line tool, a service or a bot. Never bundle it into code that runs in a web page, because whoever has the secret can call the API as your program

For an Electron application, run the SDK in the main process and keep protected operations behind a validated session. Use a narrow preload interface for the UI; do not send the app secret or management credentials to the renderer. Client code can still be inspected, so process separation does not make a bundled secret impossible to recover. See the integration overview.

Install

Terminal
npm install pwfauth

Use version 1.1.0 or newer. In 1.0.0 a PC clock moved more than five minutes kept a banned copy running, and a plain "success" from a fake server signed the customer in

Keep the secret out of your code

Read the 64-character app secret of your application (see Applications) at start-up instead of writing it in the source, for example from an environment variable, as the code below does with PWFAUTH_SECRET. Never commit a real secret

Sign in and start the heartbeat

JavaScript
import { PwfClient } from 'pwfauth';

const client = new PwfClient(process.env.PWFAUTH_SECRET);

client.on('sessionEnded', ({ errorCode, message }) => {
    console.error(`Signed out (${errorCode}): ${message}`);
    process.exit(1);
});

const login = await client.login(key.trim());
if (!login.success) {
    console.error(login.message);        // written for the customer
    process.exit(1);
}

client.startHeartbeat();                 // the kill switch: never skip it
Always call startHeartbeat(). Without it the program never learns that a key was banned, paused or expired, and the server drops the silent session

sessionEnded fires with { errorCode, message } when the key is banned, paused, expired, deleted or reset, when you end the session from the panel, when the app goes into maintenance, when an account's password changes, and when three heartbeats in a row get no encrypted answer (NETWORK_LOST, or CLOCK_SKEW when the PC's clock is the reason). How often it checks is in How protection works

The heartbeat's timer does not keep the process alive by itself: when your program has nothing else left to do, Node.js exits as usual

Show the license

The sign-in reply carries everything about the key, and login.license reads the license part:

JavaScript
const lic = login.license;
const status = lic.isLifetime
    ? 'Lifetime license'                // expiresAt and daysRemaining are null for lifetime keys
    : `Expires ${lic.expiresAt.toISOString().slice(0, 10)}, ${lic.daysRemaining} day(s) left`;

It also has licenseKey, keyType, duration, hwid, activatedAt and status, and login.features holds the key's feature flags. The rest is in login.data: app (name, version, and your welcome message in message), texts and slides

Remote texts come as a map of names to texts, with the key's own values applied (see Texts & slides). getTexts() fetches them again for the signed-in key while the program runs:

JavaScript
const { texts } = (await client.getTexts()).data;
const title = texts?.welcome ?? 'Welcome';

Move the license to a new PC

When the key belongs to another PC, offer to move it. This works when self-service is on for the app (see HWID resets):

JavaScript
import { PwfErrorCodes } from 'pwfauth';

let login = await client.login(key);
if (login.errorCode === PwfErrorCodes.HWID_MISMATCH || login.errorCode === PwfErrorCodes.DEVICE_LIMIT) {
    if (await askUser(`${login.message}\nMove your license to this PC?`)) {
        const moved = await client.resetHardwareId(key, 'Moved to a new PC');
        show(moved.message);
        if (moved.success) login = await client.login(key);
    }
}

The move unbinds the key from every PC and ends its sessions. A refusal names the reason in moved.errorCode: SELF_RESET_DISABLED, RATE_LIMITED (the message says how long to wait), KEY_NOT_ACTIVE or NO_HWID

Customer accounts

Instead of a key, a customer can sign in with a username and password (see Users). The session and the heartbeat work exactly as with a key:

JavaScript
const login = await client.accountLogin(username, password);
if (!login.success) {
    show(login.message);                 // INVALID_CREDENTIALS, BANNED, PAUSED, EXPIRED, HWID_MISMATCH …
} else {
    client.startHeartbeat();
}

Sign-up, keys and password changes, when sign-up is on for the app:

JavaScript
let r = await client.registerAccount(username, password, email);   // REGISTRATION_DISABLED when sign-up is off
if (r.errorCode === PwfErrorCodes.KEY_REQUIRED) {                    // "Sign-up needs a license key" is on
    r = await client.registerAccountWithKey(username, password, key, email);
}

const more = await client.redeemKey(key);                            // signed in: adds the key's time
const back = await client.redeemKey(key, username, password);        // signed out, works after expiry too
const c = await client.changeAccountPassword(username, currentPassword, newPassword);

A changed password signs out every copy using the account, the one that changed it too: sign in again with the new password. An account is bound to one PC; when it moves, you reset its machine in Users. A key spent on an account cannot sign in on its own any more: login answers KEY_REDEEMED

Sign out

JavaScript
await client.logout();       // ends the session; the key stays bound to this PC

Errors and what the customer sees

A refusal resolves like any other reply: success is false, errorCode is for your code and message is written for the customer, in your own words if you set them in Applications → Messages. Show the message; branch on the code (each one is on PwfErrorCodes, see Error codes). A call rejects only when the reply never came or cannot be used:

ErrorMeans
PwfHttpErrorNo usable reply: e.status is 401 for a wrong app secret, 0 for no connection or no answer in time
PwfSecurityErrorA plain "success" where an encrypted reply was due, so not the license server. Never unlock the program on it
PwfCryptoErrorThe encrypted reply could not be opened, usually because of a wrong app secret

All three extend PwfError. Every call also takes a signal to cancel it, for example client.login(key, { signal: AbortSignal.timeout(5000) })

Signed replies

The Node.js package does not check PWF Auth's reply signature yet. The .NET, Python and C++ clients do

PWF Auth signs a reply whenever the request asks for it, with a key that never leaves the server, and the other clients always ask and refuse a reply without that signature. The Node.js package does not ask, so its replies come unsigned and it relies on HTTPS and on the encryption made with your app secret: a reply to an encrypted call must be sealed with that secret, and a plain "success" is refused

The gap is the secret itself. In a program you hand to customers, such as an Electron app, every copy carries it, and someone who digs it out on their own PC could answer in PWF Auth's place. On machines only you control, such as your own server or bot, nobody else has it

More calls

CallDoes
checkKey(key)Reads a key's status without signing in or using a machine seat
createTrial()A trial key for this PC, when trials are on for the app
getAppInfo() / getSlides()App name, version, download link and maintenance state; announcement slides
checkUpdate(version, channel)Is there a newer build? See Updates
getHardwareId()This PC's ID, made the same way as in the other official clients, so one PC counts as one device
postEnvelope(path, body) / getEnvelope(path) / postPlain(path, body)Any endpoint the package does not wrap yet, see API reference

User variables, add-ons and protected files have no calls of their own in the Node.js package yet; postEnvelope reaches them, for example client.postEnvelope('/api/auth/var.php', { session_id: client.sessionId, action: 'get', name: 'theme' }) (fields in API reference)

Instead of the secret, new PwfClient() also takes an options object: appSecret plus, for example, timeoutMs (15000), maxHeartbeatFailures (3) and autoCorrectClock, which corrects a wrong PC clock from the server's time and is on by default

Step by step

For a walk-through from a new application to a protected program, read How to add license keys with an HWID lock to a Node.js app. The package is on npm

Something missing or unclear? Tell us on Telegram