Clavem

Activate and deactivate devices from a Node.js app

Call POST /v1/licenses/activate once per device with an instance_name for people and a hashed fingerprint for machines, then store the returned instance.id. With a stable fingerprint, activating again returns the same seat, which is what keeps redeployed servers from using up the limit.

Activation in two calls

Activation ties a license key to one device. You make the call once, when the customer enters the key, and you keep what comes back: the instance.id, which validate and deactivate need, and the signed token. Checking the license on later starts is validation. The code below saves into the same license.json, using load, save, dir and FILE from that page.

// activate.mjs: Node 18 or later. load, save, dir and FILE come from license.mjs on the validation page.
import { execFile } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { hostname, platform } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
import { dir, FILE, load, save } from './license.mjs';

const run = promisify(execFile);
const BASE = 'https://clavem.io';
const post = (action, body) =>
  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(8000),
  }).then(async (res) => ({ status: res.status, json: await res.json().catch(() => ({})) }));

/** The operating system's machine id, or null. Reads one file or runs one fixed command. */
async function systemId() {
  try {
    if (process.platform === 'linux') return (await readFile('/etc/machine-id', 'utf8')).trim();
    if (process.platform === 'darwin') {
      const { stdout } = await run('ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice']);
      return /"IOPlatformUUID" = "([^"]+)"/.exec(stdout)[1];
    }
    if (process.platform === 'win32') {
      const { stdout } = await run('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\Cryptography', '/v', 'MachineGuid']);
      return /MachineGuid\s+REG_SZ\s+(\S+)/.exec(stdout)[1];
    }
  } catch {
    // fall through to the generated id
  }
  return null;
}

/** Last resort: an id generated once and kept in the config folder. Deleting the folder means a new seat. */
async function installId() {
  const file = join(dir, 'install-id');
  try {
    return (await readFile(file, 'utf8')).trim();
  } catch {
    await mkdir(dir, { recursive: true });
    const id = randomUUID();
    await writeFile(file, id);
    return id;
  }
}

/** Stable per machine, different per app, and not reversible to the raw id. */
export async function fingerprint() {
  // Containers and servers: set a name you choose, and every redeploy of that deployment returns the same seat.
  const seed = process.env.INKWELL_INSTANCE ?? (await systemId()) ?? (await installId());
  return createHash('sha256').update('inkwell:' + seed).digest('hex');
}

/** Resolves { ok: true, used, limit } or { ok: false, reason, ... }. Never throws for server answers. */
export async function activate(key) {
  const { status, json } = await post('activate', {
    license_key: key.trim(),
    instance_name: `${hostname()} (${platform()})`.slice(0, 120), // up to 120 characters; the buyer sees it
    fingerprint: await fingerprint(),
  });
  if (json.activated) {
    await save({ key: key.trim(), instanceId: json.instance.id, token: json.token, checkedAt: Math.floor(Date.now() / 1000) });
    return { ok: true, used: json.license_key.activation_usage, limit: json.license_key.activation_limit };
  }
  const lk = json.license_key;
  if (status === 400 && lk) {
    // Branch on data, not on error text. Expired and disabled are refused before the limit is checked.
    if (lk.status === 'expired' || lk.status === 'disabled') return { ok: false, reason: lk.status, message: json.error };
    return { ok: false, reason: 'limit', used: lk.activation_usage, limit: lk.activation_limit };
  }
  return { ok: false, reason: status === 404 ? 'unknown-key' : 'error', message: json.error };
}

/** Frees this machine's seat. Keeps the local copy when the server could not be reached, so you can retry. */
export async function deactivate() {
  const saved = await load();
  if (!saved) return { ok: true };
  try {
    const { status } = await post('deactivate', { license_key: saved.key, instance_id: saved.instanceId });
    if (status !== 200 && status !== 404) return { ok: false, status }; // 404: the seat was already gone
  } catch {
    return { ok: false, status: 0 };
  }
  await rm(FILE, { force: true });
  return { ok: true };
}

Choosing the fingerprint

instance_name is for people. The buyer sees it on the device page, so host (linux) helps them tell machines apart. fingerprint is for machines. The code hashes the source with an app-specific prefix, so the raw id never leaves the machine and two of your products cannot be matched by it.

Where the code runs Source What to know
Linux /etc/machine-id Survives upgrades. Changes when the OS is reinstalled. A VM cloned from one image carries the same id, so the clones share one seat.
macOS IOPlatformUUID from ioreg Tied to the Mac. Survives reinstalling macOS.
Windows MachineGuid in the registry Changes on a clean Windows install.
Server, container, CI INKWELL_INSTANCE, a name you set You decide what counts as the same installation.
Nothing readable An install-id file Lost when the folder is deleted, and the next activation takes another seat.

Run on a Mac, the function returned the same 64-character hash on two calls. Pass execFile a fixed argument list, as above, and never build the command from user input.

Servers, containers and CI

A self-hosted Node.js product often runs where the disk does not last: a container, a serverless function, a build agent. A machine id read inside a container may be missing, or new with each container. A file in the container’s own file system disappears with it. Either way, every redeploy would activate as a stranger and take a seat.

The documented behavior of the fingerprint solves this. Activating again with a fingerprint that is already active on the license returns that seat, with its name updated, instead of using another. So give the deployment a name that outlives the container, for example INKWELL_INSTANCE=prod-eu, and call activate on every boot. It costs one request and no extra seat. The response carries the instance.id again, so nothing needs to be stored.

For CI there is a simpler way: do not activate at all. Validation works with the key alone and uses no seat.

When the limit is reached

A fourth device on a license with three seats gets a 400 whose body includes the license_key object. Expired and disabled licenses get the same status, so read license_key.status first, as the code does, and only then treat the rest as the limit. Show numbers instead of the server’s sentence:

const result = await activate(key);
if (!result.ok && result.reason === 'limit') {
  console.error(`This key is already active on ${result.used} of ${result.limit} devices.`);
  console.error('Free one with "inkwell logout" on that machine, or at https://clavem.io/licenses/manage.');
}

Deactivating

deactivate removes the seat. The code deletes the local file only after the server confirms, or answers 404 because the seat was already gone. When the network is down it keeps the file and returns ok: false, so the command can say “try again online” and the customer does not end up with a seat that is used but unrecorded.

What was run

The code ran against a local server that returns the documented responses, with a limit of two devices. Machine a activated twice and got the same instance id both times. Machine b took the second seat. Machine c was refused with used: 2, limit: 2. An expired key and an unknown key returned their own reasons. Deactivating while the server was unreachable kept the file, deactivating online removed it, and machine c could then activate. We did not call activate or deactivate on the live demo license.

Doing this with Clavem

Buyers manage their devices themselves at /licenses/manage, and your product’s default device limit is set in the dashboard. The request and response fields are in the API reference.

Questions

What happens when a Node.js server is redeployed and loses its disk?

If the fingerprint comes from something you control, such as a deployment name, activating again returns the seat that fingerprint already holds. If it came from a file on the lost disk, the new container gets a new random id and takes a second seat.

Where do customers free a seat when the machine is gone?

On the device page at clavem.io/licenses/manage. They enter the key, see the machines using it by the instance_name you sent, and remove one. No email round trip is needed.