Clavem

Validate a license key in a Node.js app or CLI tool

Send the key to POST /v1/licenses/validate with the global fetch, read the valid field and not just the status code, and keep the last signed token so the tool still starts offline. The code below has no dependencies and runs on Node 18 or later.

The check in one function

Most Node.js programs that need a license are command-line tools, self-hosted servers and build scripts. They start often, they may run without a screen, and some run on machines that cannot reach the internet. So the check below does three things beyond the plain request. It asks the server at most once a day. It never waits on a retry. When the server cannot answer, it falls back to the signed token from the last good answer.

The token check is verifyToken and isLicensed from offline verification in Node.js. The first activation, where the file is created, is on the device activation page.

// license.mjs: Node 18 or later, no dependencies.
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { dirname, join } from 'node:path';
import { isLicensed, verifyToken } from './token.mjs'; // from the offline verification page

const BASE = 'https://clavem.io';
const PUBLIC_KEY = 'YOUR_PUBLIC_KEY'; // from your product page
const PRODUCT_ID = 75; // from your product page
const ONLINE_EVERY = 24 * 60 * 60; // seconds between online checks; the token covers the days in between

export const dir =
  process.platform === 'win32'
    ? join(process.env.APPDATA ?? homedir(), 'inkwell')
    : join(process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'inkwell');
export const FILE = join(dir, 'license.json');

export const load = () => readFile(FILE, 'utf8').then(JSON.parse, () => null);

export async function save(license) {
  await mkdir(dir, { recursive: true });
  await writeFile(FILE + '.tmp', JSON.stringify(license), { mode: 0o600 });
  await rename(FILE + '.tmp', FILE); // atomic: a crash never leaves half a file
}

/** One POST. Resolves with status 0 when there is no answer; never throws. */
async function call(action, body) {
  try {
    const res = await fetch(`${BASE}/v1/licenses/${action}`, {
      method: 'POST',
      headers: { 'content-type': 'application/json', 'user-agent': 'inkwell-cli/1.4.0' },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(5000),
    });
    const retryAfter = Number(res.headers.get('retry-after')) || null;
    return { status: res.status, retryAfter, json: await res.json().catch(() => ({})) };
  } catch {
    return { status: 0, retryAfter: null, json: {} }; // offline, DNS failure or timeout
  }
}

/** Returns { state: 'licensed' | 'invalid' | 'needs-network' | 'unlicensed', message? }. */
export async function check() {
  const saved = await load();
  if (!saved) return { state: 'unlicensed' };
  const now = Math.floor(Date.now() / 1000);

  if (now - (saved.checkedAt ?? 0) >= ONLINE_EVERY && now >= (saved.pauseUntil ?? 0)) {
    const { status, retryAfter, json } = await call('validate', { license_key: saved.key, instance_id: saved.instanceId });
    if (status === 200 && typeof json.valid === 'boolean') {
      // Keep the new token even when the license is not valid: offline, it then says so.
      await save({ ...saved, token: json.token, checkedAt: now, pauseUntil: 0 });
      return json.valid ? { state: 'licensed' } : { state: 'invalid', message: json.error };
    }
    if (status === 404 && json.valid === false) {
      await rm(FILE, { force: true }); // unknown key, or this device was removed: ask for the key again
      return { state: 'invalid', message: json.error };
    }
    // 429 and 503 say when to come back. Do not wait here: skip the online check until then.
    if (status === 429 || status === 503) await save({ ...saved, pauseUntil: now + (retryAfter ?? 60) });
  }

  // Not asked today, offline, rate limited or the service is down: use the stored token.
  const claims = verifyToken(saved.token, PUBLIC_KEY);
  if (claims?.valid === false) return { state: 'invalid', message: `This license is ${claims.status}.` };
  return isLicensed(claims, PRODUCT_ID) ? { state: 'licensed' } : { state: 'needs-network' };
}

What each answer does

Answer What the code does
200, valid: true Stores the new token, which restarts the 14-day window. Licensed.
200, valid: false The license is expired or disabled. Stores the token anyway, so the same verdict holds offline, and shows error. The key stays, because a renewal can revive it.
404 The key is unknown, or instance_id not found: this device was removed. Deletes the file and asks for a key.
429, Retry-After: 60 Writes pauseUntil and uses the token. No loop, no sleep.
503, Retry-After: 5 The same. The next run after the pause asks again.
No answer Timeout after five seconds, no DNS, refused connection. The token decides.
400 A bug in your request, such as a missing field. It falls through to the token. Log it.
200 or 404 without the JSON body A captive portal or a proxy error page, not Clavem. Ignored, so the token decides and the license file survives.

The decision rests on the status and on valid, never on the text of error, which is a sentence meant for people.

Output against the demo key

The demo license answers like this when only the key is sent. The product here is the demo’s own, so its ids are 1, not the 75 used in the code above.

POST https://clavem.io/v1/licenses/validate   {"license_key":"S1GNE-TDEM0-7K4QX-9WZ2P-H5RB8"}
200  { "valid": true, "error": null,
       "license_key": { "id": 1, "status": "active", "activation_limit": 3, "activation_usage": 1, "expires_at": null },
       "instance": null, "token": "sgt1.eyJ2IjoxLCJsaWQiOjEsInB…" }

POST … {"license_key":"AAAAA-BBBBB-CCCCC-DDDDD-EEEEE"}   404  { "valid": false, "error": "license_key not found." }
POST … {}                                                400  { "valid": false, "error": "license_key: Invalid input: expected string, received undefined" }

Running check() against a license file that holds only that key printed { state: 'licensed' } and wrote a token, a checkedAt and a pauseUntil of zero into the file. The other rows of the table were run against a local server that returns the documented shapes, including the 429 and 503 answers, a dropped connection, a five-second timeout, and a hotel Wi-Fi page that answers 200 with HTML.

Where the key lives

A command-line tool keeps one JSON file in the user’s config folder: XDG_CONFIG_HOME or ~/.config on Linux and macOS, %APPDATA% on Windows. The write goes to a temporary file first and is renamed, so two runs at once, or a crash, cannot leave a half-written license.

The 0o600 mode keeps other users out on Linux and macOS. It applies only when the file is created, and on Windows Node can change only the write permission, so do not count on it there. The key is the credential for the license, so do not log it and do not put it in a command-line argument that shows up in the process list.

For a server product, read the key from an environment variable or the secret store of your platform and keep only the token on disk. A server process also holds that token in memory, so validate once at boot and then on a timer, not per request.

Proxies, CI and clusters

  • Proxies. Until you opt in, Node’s fetch ignores HTTPS_PROXY. Behind a corporate proxy every check then fails as “offline” and the tool quietly runs on the token until it expires. We ran one request twice with HTTPS_PROXY pointing at a closed port. It succeeded without the flag, so the proxy was ignored, and failed with NODE_USE_ENV_PROXY=1, so the proxy was used. Tell buyers behind a proxy to set the flag on Node 24.5, 22.21 or later.
  • CI. Build agents share one outgoing address, and the API allows 120 requests per minute per IP and 60 per minute per key. A matrix of a hundred jobs that each validate can hit 429. Send only license_key, cache the stored token between runs, and let offline verification cover the rest.
  • Clusters and workers. One process in the group should validate and share the result. Eight workers that each check on boot are eight requests against the same key.

Doing this with Clavem

Clavem’s License API answers on the Lemon Squeezy paths, so this code works for keys imported from there. The calls are in the API reference, and the same flow in other languages is in the platform guides.

Questions

Does Node's fetch use HTTP_PROXY and HTTPS_PROXY?

Not by default. Node 24.5 and 22.21 added proxy support for fetch and http.request, switched on with NODE_USE_ENV_PROXY=1 or the --use-env-proxy flag. On older versions a licensed tool behind a corporate proxy sees every check fail as "offline".

Do I have to activate a device before I can validate?

No. validate needs only license_key. Without instance_id it checks the license and uses no seat, which suits CI jobs and short-lived containers. With instance_id it also checks that this device is still active.

Sources

  1. Node.js documentation, built-in proxy support (checked November 2026)
  2. Node.js documentation, file modes on Windows (checked November 2026)