Check once, download on request
The releases endpoint is public, and what it returns depends on the key. This module checks at most once a day, caches the answer in the config folder, and asks for a signed link only when the user accepts the update. It reuses dir, load and the error handling from the validation page.
// update.ts: dir and load come from license.ts on the validation page.
import { greaterThan, tryParse } from "jsr:@std/semver@1";
import { dir, load } from "./license.ts";
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. Deno.build needs no permission.
const OS: Record<string, string> = { darwin: "macos", windows: "windows", linux: "linux" };
const PLATFORM = `${OS[Deno.build.os] ?? Deno.build.os}-${Deno.build.arch === "aarch64" ? "arm64" : "x64"}`;
const STAMP = `${dir}/update-check.json`;
const DAY = 24 * 60 * 60 * 1000;
interface Release {
version: string;
notes?: string;
published_at: string;
files?: { id: number; filename: string; size: number; platform?: string; url?: string }[];
}
export interface Update {
version: string;
notes: string | null;
canDownload: boolean;
}
/** The newest published release, with signed file links when the key is valid for this product. */
async function latest(key?: string): Promise<Release | null> {
const res = await fetch(`${BASE}/v1/releases/${PRODUCT_ID}/latest?platform=${PLATFORM}`, {
headers: { "user-agent": `inkwell/${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 an Update when a newer release exists, otherwise null. One request a day at most. */
export async function checkForUpdate(): Promise<Update | null> {
const stamp = await Deno.readTextFile(STAMP).then(JSON.parse, () => null);
if (stamp && Date.now() - stamp.at < DAY) return stamp.result;
let result: Update | null = null;
let at = Date.now();
try {
const release = await latest((await load())?.key);
const next = release && tryParse(release.version);
const current = tryParse(VERSION);
if (release && next && current && greaterThan(next, current)) {
// 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 (error) {
if (error instanceof Deno.errors.NotCapable) throw error; // a missing --allow-net, not a network problem
at = Date.now() - DAY + 60 * 60 * 1000; // offline, rate limited or down: ask again in an hour, not on every run
}
await Deno.mkdir(dir, { recursive: true });
await Deno.writeTextFile(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(): Promise<string> {
const release = await latest((await load())?.key);
const file = release?.files?.find((f) => f.url);
if (!file?.url) throw new Error("This license cannot download this release.");
await Deno.mkdir(`${dir}/downloads`, { recursive: true });
const target = `${dir}/downloads/${file.filename.split(/[\\/]/).pop()}`; // never trust a path from the server
const part = target + ".part";
const have = await Deno.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.
const out = await Deno.open(part, res.status === 206 ? { write: true, append: true } : { write: true, create: true, truncate: true });
await res.body!.pipeTo(out.writable); // closes the file when the body ends
}
if ((await Deno.stat(part)).size !== file.size) throw new Error("Download incomplete: run it again to resume.");
await Deno.rename(part, target);
return target;
}
The signed download link is on clavem.io as well, so --allow-net=clavem.io covers both calls. Run the check after the user’s command has finished and print one line to stderr when it returns something. It must never delay or break the command that was typed.
Platform labels from deno compile targets
The platform query returns only files with that label, plus files that have none. The labels are the ones you typed when you uploaded. A compile target maps to a label in one line, so name the uploads to match:
deno compile --target |
Upload label |
|---|---|
aarch64-apple-darwin |
macos-arm64 |
x86_64-apple-darwin |
macos-x64 |
x86_64-pc-windows-msvc |
windows-x64 |
aarch64-pc-windows-msvc |
windows-arm64 |
x86_64-unknown-linux-gnu |
linux-x64 |
aarch64-unknown-linux-gnu |
linux-arm64 |
The Windows ARM target needs Deno 2.9.3 or later, according to the compile documentation. Deno.build.os and Deno.build.arch report the build the tool is running as, with no permission, which is why the code can derive the label at runtime.
Versions
tryParse from @std/semver returns undefined for a string it cannot parse, and the code then reports no update. We ran a few inputs. 4.0.0 against 4.0.0-beta.2 is newer, as it should be. 3.10.0 against 3.9.0 is newer. v3.2.1 parses. 3.2 does not parse, and Clavem accepts it as a release version, so a two-part version would never be offered. Use three parts.
Latest means the most recently published release, not the highest number. A backport published after 4.0.0 becomes latest.
What came back
Against the live demo product, which has no release published, the endpoint answers 404 with { "error": { "code": "not_found", "message": "This product has no published release yet." } }, with or without a key. The code treats that as no update. The rest ran against a local server with the documented shapes: no license returned the version with canDownload: false, a valid key returned the notes and canDownload: true, a second call the same day made no request, and a 429 scheduled the next try in an hour. A download interrupted at 100,000 of 300,000 bytes resumed and finished byte-identical.
Replacing the executable
Clavem delivers the file. Replacing the running program is yours. For a deno compile executable:
/** Replaces the running executable with a downloaded build. Compiled executables only. */
export async function installUpdate(downloaded: string): Promise<void> {
if (!Deno.build.standalone) throw new Error("Not a compiled executable: execPath() is Deno itself.");
const exe = Deno.execPath();
if (Deno.build.os === "windows") await Deno.rename(exe, exe + ".old"); // a running .exe can be renamed, not overwritten
await Deno.rename(downloaded, exe);
if (Deno.build.os !== "windows") await Deno.chmod(exe, 0o755); // a download has no execute bit
}
On macOS we compiled one build that replaced itself with a second, and the next run printed the second. With deno run the guard refused, because execPath() was bin/deno.
This costs permissions that are fixed when you compile: write access to the folder of the executable, which you cannot know in advance. A simpler design downloads into the config folder and tells the user where the file is, which needs nothing beyond what the license file already uses.
Doing this with Clavem
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 endpoint has its own budget of 120 requests per minute per IP, separate from validation.
Questions
Why is Deno.execPath() dangerous in an updater?
With deno run, execPath() is the Deno binary itself, so a tool that replaces "its own executable" would overwrite Deno. In a deno compile executable it is your program. Check Deno.build.standalone before replacing anything.
Why does my version check never find an update?
The version parser may be rejecting the release. Clavem accepts versions such as 3.2, but @std/semver cannot parse them, so tryParse returns undefined and the code reports no update. Publish three-part versions, or normalize before comparing.