Clavem

Check for updates and download builds from a Node.js app

GET /v1/releases/:productId/latest with the license key in the X-License-Key header returns the newest published release, and signed download links only when the key is valid for the product. Check at most once a day, compare with semver, and ask for the link when the user accepts.

Check once, download later

The releases endpoint is public, so a tool can call it without a key. What the answer contains depends on the key. The code below checks at most once a day, remembers the answer in the config folder, and fetches a signed link only when the user accepts the update. It reuses dir and load from the validation page, and it needs one dependency, semver.

// update.mjs: Node 18 or later. npm install semver. load and dir come from license.mjs on the validation page.
import { createWriteStream } from 'node:fs';
import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
import { basename, join } from 'node:path';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import semver from 'semver';
import { dir, load } from './license.mjs';

const BASE = 'https://clavem.io';
const PRODUCT_ID = 75; // from your product page
const VERSION = '1.4.0'; // the running app's version
// Use the platform labels you gave your uploads in the dashboard.
const PLATFORM = { darwin: 'macos', win32: 'windows', linux: 'linux' }[process.platform] + '-' + process.arch;
const STAMP = join(dir, 'update-check.json');
const DAY = 24 * 60 * 60 * 1000;

/** The newest published release, with signed file links when the key is valid for this product. */
async function latest(key) {
  const res = await fetch(`${BASE}/v1/releases/${PRODUCT_ID}/latest?platform=${PLATFORM}`, {
    headers: { 'user-agent': 'inkwell-cli/' + VERSION, ...(key ? { 'X-License-Key': key } : {}) },
    signal: AbortSignal.timeout(5000),
  });
  if (res.status === 404) return null; // nothing published yet
  if (!res.ok) throw new Error('HTTP ' + res.status); // 429 and 5xx: try again later
  return res.json();
}

/** Resolves { version, notes, canDownload } when a newer release exists, otherwise null. One request a day at most. */
export async function checkForUpdate() {
  const stamp = await readFile(STAMP, 'utf8').then(JSON.parse, () => null);
  if (stamp && Date.now() - stamp.at < DAY) return stamp.result;

  let result = null;
  let at = Date.now();
  try {
    const release = await latest((await load())?.key);
    if (release && semver.valid(release.version) && semver.gt(release.version, VERSION)) {
      // Without a valid key the answer holds only the version: say an update exists, and why it cannot be fetched.
      result = { version: release.version, notes: release.notes ?? null, canDownload: Boolean(release.files?.some((f) => f.url)) };
    }
  } catch {
    at = Date.now() - DAY + 60 * 60 * 1000; // offline, rate limited or down: ask again in an hour, not on every run
  }
  await mkdir(dir, { recursive: true });
  await writeFile(STAMP, JSON.stringify({ at, result }));
  return result;
}

/** Call this when the user accepts the update. The signed link lasts one hour, so ask for it now, not at check time. */
export async function download() {
  const release = await latest((await load())?.key);
  const file = release?.files?.find((f) => f.url);
  if (!file) throw new Error('This license cannot download this release.');

  await mkdir(join(dir, 'downloads'), { recursive: true });
  const target = join(dir, 'downloads', basename(file.filename)); // basename: the name comes from the server
  const part = target + '.part';
  const have = await stat(part).then((s) => s.size, () => 0);

  if (have < file.size) {
    const res = await fetch(file.url, { headers: have ? { Range: `bytes=${have}-` } : {} });
    if (res.status !== 200 && res.status !== 206) throw new Error('Download failed: HTTP ' + res.status);
    // 206 continues the partial file; 200 means the server ignored the range, so start over.
    await pipeline(Readable.fromWeb(res.body), createWriteStream(part, { flags: res.status === 206 ? 'a' : 'w' }));
  }
  if ((await stat(part)).size !== file.size) throw new Error('Download incomplete: run it again to resume.');
  await rename(part, target);
  return target;
}

Call checkForUpdate() after your real work has finished, and print one line to stderr when it returns something, such as Inkwell 3.2.1 is available. Run "inkwell update". The check must never delay or break the command the user typed.

What comes back

The response depends on the key. With a license that is valid for the product, it holds version, notes, published_at and a files list in which every file has a signed url. With no key, or a key that is expired, disabled or for another product, it holds only version and published_at. That is not an error: the code reports canDownload: false, and your tool can say that version 3.2.1 exists and a renewal is needed to fetch it.

The platform query asks only for files with that label, plus files that have none. The labels are whatever you typed when you uploaded, so the sample maps process.platform and process.arch to macos-arm64, windows-x64 and the like. Name your uploads the same way, or the list comes back empty.

Against the live demo product, which has no release published, the endpoint answers:

GET https://clavem.io/v1/releases/1/latest   (with or without X-License-Key)
404  { "error": { "code": "not_found", "message": "This product has no published release yet." } }

The code treats that as “no update”. Every other row ran against a local server that returns the documented shapes. With no license stored it reported version 3.2.1 with canDownload: false. With a valid key it returned the notes and canDownload: true. A second call the same day made no request. After a 429 it stored a stamp that schedules the next try in one hour.

Version comparison

The sample on the releases page compares dotted numbers with localeCompare. That breaks on prerelease tags. We ran it: with 4.0.0 published and 4.0.0-beta.2 running, localeCompare ranks the release lower, because the longer string sorts higher, so a beta tester never sees the final build. semver.gt('4.0.0', '4.0.0-beta.2') is true. The same holds for rc tags.

One more trap: Clavem accepts release versions such as 3.2, which semver.valid rejects, and the code then reports no update. Publish three-part versions.

Remember what latest means: the most recently published release, not the highest number. If you publish a 3.1.9 backport after 4.0.0, 3.1.9 becomes latest. Users on 3.1.0 get it, and users on 4.0.0 see no update, which is usually right.

Downloading

  • Request the link on accept. A link is valid for one hour. The check may have run days ago.
  • Resume. Downloads support byte ranges. The code keeps a .part file and sends Range: bytes=<size>-. We interrupted a download at 100,000 bytes of 300,000 and the second run fetched the rest. The result was byte-identical.
  • File names. basename keeps a name like ../../x from leaving the downloads folder.
  • Integrity. The response lists size, which the code checks. It has no checksum field, so if you want a hash, publish it in your release notes or on your site.

Applying the update

Clavem delivers files and notes. Replacing the running program is your tool’s job. On Linux and macOS you can rename a new binary over the old one. On Windows a running executable cannot be overwritten, so save the new file next to it and swap on the next start. If your tool arrives through npm, let npm update do the replacing and use the check only to announce a version.

Doing this with Clavem

You upload a release once in the dashboard; buyers download it from their order page, and your tool uses this endpoint. The limits, storage and link behavior are in releases and downloads. The releases endpoint has its own budget of 120 requests per minute per IP, so a once-a-day check cannot use up your validation limit.

Questions

Why did a beta user not get the 4.0.0 update prompt?

Comparing versions with localeCompare and numeric sorting ranks 4.0.0 below 4.0.0-beta.2, because the longer string sorts higher. Use the semver package, which ranks a prerelease below its release.

How long does a download link last?

One hour. Ask the releases endpoint again when the user accepts the update, not when the check ran, because a prompt can sit unanswered for longer.