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.
How it works
- 1Create a productOne per piece of software. It gets an App ID and its own signing key.
- 2Add featuresName each part a key can unlock: “pro”, “export”, “module_x”.
- 3Create keysEach key unlocks one or more features for a set time, starting when it is redeemed.
- 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:
| Field | What it is |
|---|---|
app_id | Your product's App ID. |
hwid | A stable ID for the machine, 8 to 256 characters. See Hardware IDs. |
nonce | A fresh random string for each request, 16 to 128 characters. The answer echoes it back, signed. |
version | Your 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. |
channel | Optional. "beta" to also receive beta releases. Defaults to "stable". |
/api/v1/client/status· Product status, no loginWhat 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.
/api/v1/client/register· Create an accountCreates 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”.
/api/v1/client/login· Log inReturns 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.
/api/v1/client/check· HeartbeatCall 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.
/api/v1/client/redeem· Redeem a keyTies 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.
/api/v1/client/license· Key-only modeFor 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.
/api/v1/client/logout· Log outEnds 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:
| Check | What it stops |
|---|---|
| The signature is valid for the payload string | A fake server, or a proxy that edits the answer. |
The nonce is the one you just sent | Replaying an old “yes” captured earlier. |
The hwid and app are yours | An answer captured on another machine or from another product. |
The action is the call you made | The answer to one call being passed off as the answer to another. |
iat is within 5 minutes of now | Stale answers and a clock turned back. |
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 Keyfly | What happens |
|---|---|
| Who can upload | Only you: from the dashboard while logged in, or with a full-access API key. Never your users. |
| The checksum | Keyfly computes the SHA-256 while it receives the file. Nobody types it, so it can't be wrong. |
| What is accepted | Build 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 file | Not possible. A stored build is never modified; to fix one, publish a new version. |
| How users get it | Through a private link that is signed and expires after a few hours. A fresh one comes with every answer. |
| Limits | 1 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 want | Do this | What your software sees |
|---|---|---|
| Tell users a new version is out | Publish a release | Every answer carries update with the version, link, checksum and notes, and required: false. |
| Force everyone to update | Publish it with Require this update on | Older versions get the error update_required on every call except status, which returns update with required: true. |
| Test with a few users first | Publish it to Beta testers only | Only callers that send channel: "beta" are told about it. |
| Update one module, mod or plugin | Pick the feature when publishing | The 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.
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.
| Switch | Where | Effect |
|---|---|---|
| Feature maintenance | Features → Start maintenance | That feature's entitlement comes back with status: "maintenance" and your message. Everything else keeps working. |
| Announcement | Settings → Announcement | Every answer carries your text in notice. Nothing is blocked. |
| Pause the product | Settings → Pause this product | Every 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)| Situation | What the launcher sees | What to do |
|---|---|---|
| You put a mod under maintenance | feature(...).state === "maintenance" at the next check | Stop the mod and show the message. |
| You shipped a required launcher update | update_required error, then status().update.required | Download, verify, install, restart. |
| You shipped a required mod update | release.mandatory on that feature | Install it before starting the mod. |
| The key expired or was revoked | state === "none" | Stop the mod and offer to renew. |
| The user was banned | session_invalid error on check | Stop everything and return to login. |
| Keyfly can't be reached | The request fails | Your 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.
| Code | HTTP | Meaning |
|---|---|---|
invalid_credentials | 401 | Wrong username or password. The same answer for both, on purpose. |
banned | 403 | You banned this user. The message includes your reason. |
session_invalid | 401 | Session missing, expired, ended by a ban, or used on another machine. Ask the user to log in. |
username_taken | 409 | Pick another username. |
registration_closed | 403 | Sign-ups are turned off for this product. |
key_required | 400 | This product needs a key to sign up. |
invalid_key | 400 | The key doesn't exist for this product. |
key_used | 400 | The key was already redeemed. |
key_revoked | 400 | You revoked the key. |
key_expired | 400 | Key-only mode: the key's time is over. |
device_limit | 403 | Key-only mode: the key is linked to other devices. |
key_only_disabled | 403 | Key-only mode is off for this product. The user needs an account. |
busy | 503 | The server is handling too many logins at once. Retry in a moment. |
update_required | 426 | The app is older than your minimum version or your newest required release, or didn't send its version. Call status for the update. |
app_paused | 403 | You paused the product. The message is the one you wrote in Settings. |
invalid_version | 400 | version was sent but isn't numbers separated by dots, like 1.4.0. |
invalid_hwid / invalid_nonce | 400 | A common field is missing or the wrong length. |
unknown_app | 404 | No product has that App ID. |
invalid_json / body_too_large | 400 / 413 | The body isn't a JSON object, or is over 16 KB. |
rate_limited | 429 | Too 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"| Request | What it does |
|---|---|
GET /apps | List your products with their App ID and public key. |
POST /apps | Create a product. Body: name. |
POST /apps/:app | Change 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/features | List features. |
POST /apps/:app/features | Add a feature. Body: key, name. |
POST /apps/:app/features/:id | Start or end maintenance. Body: status (live or maintenance), optional message. |
POST /apps/:app/features/:id/extend | Add time to every active key of the feature. Body: duration. |
DELETE /apps/:app/features/:id | Delete a feature. |
GET /apps/:app/releases | List releases. |
POST /apps/:app/uploads | Upload a build. The body is the file; send its name in X-Filename. Returns file.id, file.sha256 and file.size. |
POST /apps/:app/releases | Publish 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/:id | Delete a release. Deleting a required one lets older versions run again. |
GET /apps/:app/licenses | List keys. Query: state (unused, active, expired, revoked), search, limit, offset. |
POST /apps/:app/licenses | Create keys. Body: features (list of feature keys), duration, and optionally count (1–500), max_devices, note. |
GET /licenses/:id | One license with its linked devices. Use the license ID or the full key. |
POST /licenses/:id/revoke | Stop it from working. Undo with /restore. |
POST /licenses/:id/reset-hwid | Unlink every device, so the next machine can be linked. |
POST /licenses/:id/extend | Add time. Body: duration. |
DELETE /licenses/:id | Delete it for good. |
GET /apps/:app/users | List users. Query: search, limit, offset. |
GET /users/:id | One user with their licenses. |
POST /users/:id/ban | Ban and log out everywhere. Body: optional reason. Undo with /unban. |
DELETE /users/:id | Delete the account and revoke its keys. |
GET /apps/:app/events | The 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:
| Thing | How it is protected |
|---|---|
| License keys | 125 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. |
| Passwords | Argon2id with a server-side secret mixed in. Never stored or logged in clear. |
| Answers to your software | Signed with Ed25519, one key pair per product. The private key is encrypted at rest and never leaves the server. |
| Hardware IDs | Stored only as a keyed hash. |
| Uploaded builds | Only 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 keys | 256 random bits. Only a SHA-256 fingerprint is stored, so a database leak doesn't hand out working tokens. |
| Guessing | Rate 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”. |
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.
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.