Keyfly documentation

Add accounts, license keys and device locking to the software you sell. Two small APIs: one your software calls, one for your own tools.

Log in to get ready-to-paste samples
The code below uses placeholders. When you are logged in, it carries your own App ID and public key.

How it works

  1. 1Create a productOne per piece of software. It gets an App ID and its own signing key.
  2. 2Add featuresName each part a key can unlock: “pro”, “export”, “module_x”.
  3. 3Create keysEach key unlocks one or more features for a set time, starting when it is redeemed.
  4. 4Your software asks KeyflyIt logs the user in and gets a signed list of what that user can use on that machine, plus any update or maintenance notice.

A user has one account per product. They can hold several keys at once: a 30-day key for pro and a lifetime key for export give two entitlements with two expiry dates. When two keys unlock the same feature, the one that lasts longest counts.

Quick start

Copy the function below into your software. It sends the request, checks the signature and returns what the user can use. A complete client with every call lives in examples/keyfly.mjs.

import { createPublicKey, randomBytes, verify } from "node:crypto"

const API = "https://keyfly.mirandanetwork.es/api/v1/client"
const APP_ID = "app_YOUR_APP_ID"
const PUBLIC_KEY = "YOUR_PUBLIC_KEY" // safe to ship inside your app

const pub = createPublicKey({
  key: Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), Buffer.from(PUBLIC_KEY, "base64")]),
  format: "der",
  type: "spki",
})

export async function keyfly(action, hwid, body = {}) {
  const nonce = randomBytes(16).toString("hex")
  const res = await fetch(`${API}/${action}`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ app_id: APP_ID, hwid, nonce, version: "1.0.0", ...body }),
  })
  const r = await res.json()
  if (!r.ok) throw Object.assign(new Error(r.error.message), { code: r.error.code })

  // Never skip this: it is what stops a fake server from unlocking your app.
  if (typeof r.payload !== "string" || typeof r.signature !== "string") throw new Error("bad signature")
  if (!verify(null, Buffer.from(r.payload), pub, Buffer.from(r.signature, "base64"))) throw new Error("bad signature")
  const data = JSON.parse(r.payload)
  const fresh = Math.abs(Date.now() / 1000 - data.iat) < 300
  const mine = data.app === APP_ID && data.action === action && data.nonce === nonce && data.hwid === hwid
  if (!mine || !fresh) throw new Error("bad response")
  return data
}

// Log in, then gate a feature
const me = await keyfly("login", hwid, { username, password })
const has = (feature) => me.entitlements.some((e) => e.feature === feature && e.status === "live")
if (!has("pro")) throw new Error("You need a Pro license")

// Redeem a key the user typed
await keyfly("redeem", hwid, { session: me.session, key: "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" })

// Every few minutes while the app runs
await keyfly("check", hwid, { session: me.session })

Client API

The API your software calls. No API key: the App ID is public, and the answers are what is protected. Every call is a POST with a JSON body, and every call takes these fields:

FieldWhat it is
app_idYour product's App ID.
hwidA stable ID for the machine, 8 to 256 characters. See Hardware IDs.
nonceA fresh random string for each request, 16 to 128 characters. The answer echoes it back, signed.
versionYour app's version, such as 1.4.0. Send it always: it is how Keyfly knows whether to offer or require an update. Without it, a required update refuses the request.
channelOptional. "beta" to also receive beta releases. Defaults to "stable".
POST/api/v1/client/status· Product status, no login

What a launcher shows first: whether the product is live or paused and why, your announcement, the update this version should or must install, and each feature's name, status and version. It answers even when the product is paused or the caller is too old, so there is always a signed way to explain what is going on.

  • (none)Only the common fields above.
POST/api/v1/client/register· Create an account

Creates the account and logs it in. If a key is sent and it is bad, no account is created.

  • username3 to 32 characters: letters, numbers, dot, dash, underscore.
  • passwordAt least 8 characters.
  • emailOptional.
  • keyOptional license key to redeem right away. Required if you turned on “Require a license key to sign up”.
POST/api/v1/client/login· Log in

Returns a session and the user's entitlements on this machine. With the device lock on, the first machine to use a license is linked to it.

  • usernameNot case-sensitive.
  • passwordAfter 8 wrong passwords from one address, that address waits up to 10 minutes before trying this username again.
POST/api/v1/client/check· Heartbeat

Call it when your app starts and every few minutes while it runs. It returns the user's entitlements as they are right now, so a revoked key, a ban or an expiry takes effect at the next check. A session only works on the machine that opened it.

  • sessionThe session token from login or register.
POST/api/v1/client/redeem· Redeem a key

Ties the key to the logged-in user and starts its clock. A key can be redeemed once.

  • sessionThe session token.
  • keyThe key the user typed. Spaces, dashes and lower case are fine.
POST/api/v1/client/license· Key-only mode

For software without accounts. Turn on “Allow keys without an account” in Settings first. The key alone unlocks its features on the machine it is linked to. Call it again as your heartbeat. Keys redeemed by an account can't be used this way.

  • keyThe license key.
POST/api/v1/client/logout· Log out

Ends the session. The answer is signed like the others and carries no entitlements.

  • sessionThe session token to end.

What comes back

A successful answer is an envelope with the payload as a string and its signature. Check the signature over the exact string, then parse it.

{
  "ok": true,
  "payload": "{\"v\":1,\"app\":\"app_YOUR_APP_ID\",…}",
  "signature": "base64 Ed25519 signature of the payload string"
}

entitlements is what the user owns on this machine right now. Run a feature only when its status is "live"; "maintenance" means you switched it off for now, and message says why. release is the feature's newest version, when you published one. expires_at is null for a key that never expires. notice is your announcement and update is the newer version of the app itself, or null when the caller is up to date. blocked lists features the user owns a license for but can't use here because the license is linked to other devices: show them a “this license is in use on another computer” message.

Checking the signature

Each product has its own Ed25519 key pair. The private half never leaves Keyfly; the public half is on your Developers page and goes inside your software. After each call, check five things:

CheckWhat it stops
The signature is valid for the payload stringA fake server, or a proxy that edits the answer.
The nonce is the one you just sentReplaying an old “yes” captured earlier.
The hwid and app are yoursAn answer captured on another machine or from another product.
The action is the call you madeThe answer to one call being passed off as the answer to another.
iat is within 5 minutes of nowStale answers and a clock turned back.
Errors are not signed
An error can only ever say “no”, so there is nothing to forge. Treat anything that isn't a valid signed answer as “not licensed”. The time check means a computer whose clock is more than 5 minutes off is refused: tell the user to fix their clock.

Hardware IDs

The hwid is any string that stays the same on one machine and differs on another. Keyfly never stores it as sent: it keeps a keyed hash, so the value can't be read back from the database. Build it from one stable system value and hash it yourself first:

import { createHash } from "node:crypto"
import { execSync } from "node:child_process"
import os from "node:os"

// One stable value per machine. Hash it so you never send raw serial numbers.
function machineId() {
  if (process.platform === "win32")
    return execSync('reg query "HKLM\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid').toString()
  if (process.platform === "darwin")
    return execSync("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID").toString()
  return execSync("cat /etc/machine-id").toString()
}
export const hwid = createHash("sha256").update(machineId().trim() + os.arch()).digest("hex")

Avoid values that change (IP address, free disk space, MAC addresses of virtual adapters) or customers will be locked out after a reboot. When a customer changes computer, use Reset devices on their key, or the reset-hwid endpoint.

Updates

Publish a release in Releases each time you ship a version: a version number, the build file and what changed. Upload the file to Keyfly, or link to one you host yourself.

When you upload the build to KeyflyWhat happens
Who can uploadOnly you: from the dashboard while logged in, or with a full-access API key. Never your users.
The checksumKeyfly computes the SHA-256 while it receives the file. Nobody types it, so it can't be wrong.
What is acceptedBuild formats only (.zip, .jar, .exe, .msi, .dmg, .7z, .tar, .gz and similar), and the content must match the extension: a .zip that is really something else is refused.
Changing a fileNot possible. A stored build is never modified; to fix one, publish a new version.
How users get itThrough a private link that is signed and expires after a few hours. A fresh one comes with every answer.
Limits1 GB per file and 20 GB per account by default (KEYFLY_MAX_UPLOAD_MB, KEYFLY_STORAGE_QUOTA_MB).

Keyfly doesn't scan uploads for viruses. These checks stop mistakes, swapped files and outsiders; what you upload is still your responsibility.

You wantDo thisWhat your software sees
Tell users a new version is outPublish a releaseEvery answer carries update with the version, link, checksum and notes, and required: false.
Force everyone to updatePublish it with Require this update onOlder versions get the error update_required on every call except status, which returns update with required: true.
Test with a few users firstPublish it to Beta testers onlyOnly callers that send channel: "beta" are told about it.
Update one module, mod or pluginPick the feature when publishingThe release appears in that feature's entitlement, so only users who own it get the link.

Publishing from your build pipeline

The upload is the raw file as the request body, with its name in the X-Filename header. The answer gives a file ID to use in the release.

# Upload the build, then publish it. Works from any CI (GitHub Actions, GitLab, a script).
FILE_ID=$(curl -sf -X POST https://keyfly.mirandanetwork.es/api/v1/apps/app_YOUR_APP_ID/uploads \
  -H "Authorization: Bearer $KEYFLY_API_KEY" \
  -H "X-Filename: app-1.5.0.zip" \
  --data-binary @dist/app-1.5.0.zip | jq -r .file.id)

curl -sf -X POST https://keyfly.mirandanetwork.es/api/v1/apps/app_YOUR_APP_ID/releases \
  -H "Authorization: Bearer $KEYFLY_API_KEY" -H "Content-Type: application/json" \
  -d "{\"version\": \"1.5.0\", \"file\": \"$FILE_ID\", \"notes\": \"Faster exports\"}"

A required release must have a file (uploaded, or a link with its checksum), so there is always a way forward for your users. Beta is a way to choose who is told first, not a secret: anyone who asks for the beta channel sees beta releases of the app.

Two rules make forced updates safe. First, always send version, as numbers and dots only. Second, when you get update_required, call status and take the link from its signed answer. Never take a download link from an error: errors are not signed.

Check the checksum before you run a download
The link and the checksum arrive inside the signed answer, so nobody can swap them. If your software hashes the file it downloaded and compares, a file changed on the download server or on the network is refused. The download() helper in examples/keyfly.mjs does exactly this.

Maintenance and status

There are three switches, from narrow to wide. All take effect the next time your software checks in, and none of them touches anyone's keys.

SwitchWhereEffect
Feature maintenanceFeatures → Start maintenanceThat feature's entitlement comes back with status: "maintenance" and your message. Everything else keeps working.
AnnouncementSettings → AnnouncementEvery answer carries your text in notice. Nothing is blocked.
Pause the productSettings → Pause this productEvery call except status answers app_paused with your message.

When a feature was down for a while, Add time to all keys on that feature gives the time back to every active key in one step.

# Publish version 1.5.0 and require it: older versions are refused until they update
curl -X POST https://keyfly.mirandanetwork.es/api/v1/apps/app_YOUR_APP_ID/releases \
  -H "Authorization: Bearer $KEYFLY_API_KEY" -H "Content-Type: application/json" \
  -d '{"version": "1.5.0", "mandatory": true, "notes": "Security fix",
       "url": "https://downloads.yoursite.com/app-1.5.0.zip", "sha256": "9f86d081…"}'

# Put one module under maintenance, with a message your launcher can show
curl -X POST https://keyfly.mirandanetwork.es/api/v1/apps/app_YOUR_APP_ID/features/FEATURE_ID \
  -H "Authorization: Bearer $KEYFLY_API_KEY" -H "Content-Type: application/json" \
  -d '{"status": "maintenance", "message": "Updating for the new game patch. Back in 2 hours."}'

# It was down for a day: give every key of that module a day back
curl -X POST https://keyfly.mirandanetwork.es/api/v1/apps/app_YOUR_APP_ID/features/FEATURE_ID/extend \
  -H "Authorization: Bearer $KEYFLY_API_KEY" -H "Content-Type: application/json" \
  -d '{"duration": "1d"}'

Building a launcher

A launcher starts other things: a game with a mod, a set of tools, plugins. Model each thing it can start as a feature. Then the launcher follows four steps, and the calls below are all it needs. A runnable version is in examples/launcher.mjs.

import { createClient, download, feature } from "./keyfly.mjs"

const keyfly = createClient({ api, appId, publicKey, hwid, version: "1.0.0" })

// 1. No login yet: is the product up, and is this launcher too old?
const s = await keyfly.status()
if (s.notice) showBanner(s.notice)
if (s.state === "paused") return showMaintenance(s.message)
if (s.update?.required) {
  const file = await download(s.update) // refuses a file that doesn't match the signed checksum
  return installAndRestart(file)
}
if (s.update_required) return showText("Version " + s.required_version + " or newer is required.")
showModules(s.features) // name, status ("live" | "maintenance"), message, version

// 2. Log in: from now on every answer says what this user can run here
const me = await keyfly.login(username, password)

// 3. Start a module only when it is live
const mod = feature(me, "skyblock_mod")
if (mod.state === "maintenance") return showMaintenance(mod.message)
if (mod.state !== "live") return showBuyScreen()
if (mod.release && mod.release.version !== installedVersion) {
  await install(await download(mod.release)) // only owners ever receive this link
}
const game = launch()

// 4. While it runs, check in every few minutes
setInterval(async () => {
  try {
    const now = feature(await keyfly.check(), "skyblock_mod")
    if (now.state !== "live") {
      game.stop()
      showMaintenance(now.message)
    }
  } catch (e) {
    game.stop() // session_invalid, app_paused, update_required
    showError(myTextFor(e.code)) // errors are unsigned: show your own words, never theirs
  }
}, 5 * 60 * 1000)
SituationWhat the launcher seesWhat to do
You put a mod under maintenancefeature(...).state === "maintenance" at the next checkStop the mod and show the message.
You shipped a required launcher updateupdate_required error, then status().update.requiredDownload, verify, install, restart.
You shipped a required mod updaterelease.mandatory on that featureInstall it before starting the mod.
The key expired or was revokedstate === "none"Stop the mod and offer to renew.
The user was bannedsession_invalid error on checkStop everything and return to login.
Keyfly can't be reachedThe request failsYour call: keep running for a grace period, then stop.

How often to check is a trade: every 5 minutes means a maintenance switch reaches everyone within 5 minutes. The limit is 120 checks a minute per address.

Error codes

Errors look like {"ok": false, "error": {"code": "…", "message": "…"}}. Branch on the code and show your own text for it. The message is there to help you while building: because errors are not signed, never show a link from one or act on it.

CodeHTTPMeaning
invalid_credentials401Wrong username or password. The same answer for both, on purpose.
banned403You banned this user. The message includes your reason.
session_invalid401Session missing, expired, ended by a ban, or used on another machine. Ask the user to log in.
username_taken409Pick another username.
registration_closed403Sign-ups are turned off for this product.
key_required400This product needs a key to sign up.
invalid_key400The key doesn't exist for this product.
key_used400The key was already redeemed.
key_revoked400You revoked the key.
key_expired400Key-only mode: the key's time is over.
device_limit403Key-only mode: the key is linked to other devices.
key_only_disabled403Key-only mode is off for this product. The user needs an account.
busy503The server is handling too many logins at once. Retry in a moment.
update_required426The app is older than your minimum version or your newest required release, or didn't send its version. Call status for the update.
app_paused403You paused the product. The message is the one you wrote in Settings.
invalid_version400version was sent but isn't numbers separated by dots, like 1.4.0.
invalid_hwid / invalid_nonce400A common field is missing or the wrong length.
unknown_app404No product has that App ID.
invalid_json / body_too_large400 / 413The body isn't a JSON object, or is over 16 KB.
rate_limited429Too many requests, or too many wrong passwords for one username. The message says how long to wait.

Management API

Everything the dashboard does, for your own code. Create an API key in Developers and send it on every request as Authorization: Bearer kf_live_…. Keep it on your server: it must never be inside the software you ship.

# Create 5 keys that unlock "pro" for 30 days
curl -X POST https://keyfly.mirandanetwork.es/api/v1/apps/app_YOUR_APP_ID/licenses \
  -H "Authorization: Bearer $KEYFLY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"features": ["pro"], "duration": "30d", "count": 5}'

# A customer changed computer: unlink their devices
curl -X POST https://keyfly.mirandanetwork.es/api/v1/licenses/XXXXX-XXXXX-XXXXX-XXXXX-XXXXX/reset-hwid \
  -H "Authorization: Bearer $KEYFLY_API_KEY"
RequestWhat it does
GET /appsList your products with their App ID and public key.
POST /appsCreate a product. Body: name.
POST /apps/:appChange settings. Body: any of name, paused, hwid_lock, default_max_devices, session_ttl_s, allow_register, require_key, allow_key_only, min_version, paused_message, notice.
GET /apps/:app/featuresList features.
POST /apps/:app/featuresAdd a feature. Body: key, name.
POST /apps/:app/features/:idStart or end maintenance. Body: status (live or maintenance), optional message.
POST /apps/:app/features/:id/extendAdd time to every active key of the feature. Body: duration.
DELETE /apps/:app/features/:idDelete a feature.
GET /apps/:app/releasesList releases.
POST /apps/:app/uploadsUpload a build. The body is the file; send its name in X-Filename. Returns file.id, file.sha256 and file.size.
POST /apps/:app/releasesPublish a release. Body: version, and optionally feature (a feature key; leave out for the app itself), channel, notes, mandatory, and either file (an uploaded file ID) or url with sha256.
DELETE /apps/:app/releases/:idDelete a release. Deleting a required one lets older versions run again.
GET /apps/:app/licensesList keys. Query: state (unused, active, expired, revoked), search, limit, offset.
POST /apps/:app/licensesCreate keys. Body: features (list of feature keys), duration, and optionally count (1–500), max_devices, note.
GET /licenses/:idOne license with its linked devices. Use the license ID or the full key.
POST /licenses/:id/revokeStop it from working. Undo with /restore.
POST /licenses/:id/reset-hwidUnlink every device, so the next machine can be linked.
POST /licenses/:id/extendAdd time. Body: duration.
DELETE /licenses/:idDelete it for good.
GET /apps/:app/usersList users. Query: search, limit, offset.
GET /users/:idOne user with their licenses.
POST /users/:id/banBan and log out everywhere. Body: optional reason. Undo with /unban.
DELETE /users/:idDelete the account and revoke its keys.
GET /apps/:app/eventsThe activity log, newest first.

All paths start with https://keyfly.mirandanetwork.es/api/v1. A duration is "12h", "30d", "2w", "6mo", "1y", "lifetime" or a number of seconds, up to 100 years. It is always required: leaving it out is an error, never a lifetime key. Limits: 240 requests a minute per API key. A read-only API key can call the GET requests only.

Discord bot example

A bot is a small program that holds your API key and calls the Management API. This one gives your admins two slash commands.

// A /key command that makes a 30-day Pro key, and /reset for customers who change computer.
import { Client, GatewayIntentBits } from "discord.js"

const API = "https://keyfly.mirandanetwork.es/api/v1"
const headers = { authorization: `Bearer ${process.env.KEYFLY_API_KEY}`, "content-type": "application/json" }
const keyfly = (method, path, body) =>
  fetch(`${API}/${path}`, { method, headers, body: body && JSON.stringify(body) }).then((r) => r.json())

const bot = new Client({ intents: [GatewayIntentBits.Guilds] })
bot.on("interactionCreate", async (i) => {
  if (!i.isChatInputCommand() || !i.memberPermissions.has("Administrator")) return

  if (i.commandName === "key") {
    const r = await keyfly("POST", "apps/app_YOUR_APP_ID/licenses", { features: ["pro"], duration: "30d", note: `Discord: ${i.user.tag}` })
    return i.reply({ content: r.ok ? `\`${r.licenses[0].key}\`` : r.error.message, ephemeral: true })
  }
  if (i.commandName === "reset") {
    const r = await keyfly("POST", `licenses/${i.options.getString("key")}/reset-hwid`)
    return i.reply({ content: r.ok ? `Unlinked ${r.devices_removed} device(s).` : r.error.message, ephemeral: true })
  }
})
bot.login(process.env.DISCORD_TOKEN)

Security model

What Keyfly does, so you know exactly what you are relying on:

ThingHow it is protected
License keys125 random bits from the system generator. A key holds no data, so there is nothing to decode or forge: guessing one is not feasible. The database stores a keyed hash for lookups and an AES-256-GCM encrypted copy so you can see your keys in the dashboard.
PasswordsArgon2id with a server-side secret mixed in. Never stored or logged in clear.
Answers to your softwareSigned with Ed25519, one key pair per product. The private key is encrypted at rest and never leaves the server.
Hardware IDsStored only as a keyed hash.
Uploaded buildsOnly the seller can upload. The checksum is computed on the server, the content must match the file type, a stored file can never be changed, and it is served only through signed links that expire, always as a download.
Sessions and API keys256 random bits. Only a SHA-256 fingerprint is stored, so a database leak doesn't hand out working tokens.
GuessingRate limits per address and per product on every endpoint, and a growing wait after wrong passwords for one username. Nobody can be locked out of their account for good by someone else's guesses.
Your data vs. other sellers'Every lookup is scoped to your account. An ID from another account answers “not found”.
What no licensing system can do
Code that runs on your customer's computer can be modified by that customer. Someone skilled enough can patch your program to skip the license check, whatever service you use. Keyfly makes sure nobody can forge a license, share one across machines or keep using one you revoked. To raise the bar further, keep the valuable part behind your own server and have it check the entitlement, and obfuscate the client.

Running it yourself

Locally, Keyfly runs with pnpm dev: the database and uploaded builds are in .data/ and the master key is in .env.local, both created on first start. In production it is one Docker container with a Postgres database and a volume for uploads; the repository's README has the steps.

Back up the master key
KEYFLY_MASTER_KEY encrypts your license keys and signing keys. If you lose it, existing keys can't be shown again and every product needs a new public key, which means shipping an update to your customers. Keep a copy somewhere safe and never commit it.

In production: HTTPS behind a reverse proxy that sets X-Forwarded-For; KEYFLY_TRUSTED_PROXIES set to the number of proxies in front (usually 1) so rate limits count real addresses; KEYFLY_PUBLIC_URL set to your address; DATABASE_URL pointing at Postgres. Sign-ups are closed by default in production: list the emails that may create an account in KEYFLY_ALLOWED_EMAILS. Back up three things: the database, the uploads volume and the master key. Run a single instance, or move the rate limiter to a shared store first.