Documentation
Build with Keyfern
Everything you need to license your software with Keyfern: create keys, check them from your app, verify the signed answers, and automate the rest through the API.
Quickstart
- Create a free account and click New product. Pick a name, an optional key prefix such as
ACME, and how many machines one key may activate. - Open the product, go to Keys and click Create keys. Generate one key to try it.
- Open the Integrate tab. Copy the product ID and the public key into your app. The public key is safe to publish.
- Check a key from your app (see below), or try it from a terminal first:
curl -X POST https://keyfern.com/v1/activate \
-H "Content-Type: application/json" \
-d '{"product":"prod_8fQ2xLw1","key":"ACME-7KQ2M-XXXXX-XXXXX-XXXXX","machine":"my-laptop","nonce":"abc123"}'
You get back a signed license. With the Python SDK the whole check is:
from keyfern import Keyfern, KeyfernError
kf = Keyfern(product="prod_8fQ2xLw1", public_key="<public key>",
url="https://keyfern.com", cache_path="license.cache")
try:
lic = kf.activate_or_cached(user_entered_key) # online, falls back to the signed cache offline
except KeyfernError as e:
print("License problem:", e.code) # blocked, expired, invalid_key, machine_limit...
else:
if lic.has(1): # feature flag F1
unlock_pro()
The JavaScript SDK has the same shape: new Keyfern({ product, publicKey, storage: fileStorage('license.cache') }) then await kf.activateOrCached(key, await machineId()). In C# it is new KeyfernClient(product, publicKey, cachePath: ...) and await kf.ActivateOrCachedAsync(key). All three SDKs verify the signature for you, keep the signed license for offline use, and reject answers that were replayed, forged or made before a clock rollback. The server URL defaults to https://keyfern.com. Any other language can call the REST API and verify the signature itself, see Verifying answers.
Install the SDKs
Python 3.8+ (installs the cryptography package for you):
pip install keyfern
No access to PyPI? pip install https://keyfern.com/dl/keyfern-1.0.0-py3-none-any.whl
Building a Python app? Follow the step-by-step Python licensing guide.
JavaScript / TypeScript: Node 20+, Electron, Deno, and browsers with WebCrypto Ed25519 (Chrome 137+, Firefox 129+, Safari 17+). No dependencies, types included.
npm install keyfern
No access to the npm registry? npm install https://keyfern.com/dl/keyfern-1.1.0.tgz
Building an Electron app? Follow the step-by-step Electron licensing guide. React Native and Expo work too: see the React Native guide.
Kotlin and Java: Android 8+ (API 26) and any JVM 11+, one file with no dependencies: KeyfernClient.kt. See the Android and Kotlin guide.
Dart and Flutter: iOS, Android, macOS, Windows and Linux, one file: keyfern.dart (needs the cryptography package). See the Flutter guide.
Tauri and Rust: no official crate yet. Call the REST API with reqwest and verify with ed25519-dalek: see the Tauri and Rust licensing guide.
C# / .NET: .NET Framework 4.6.2+, .NET 6/8/9+, WPF, WinForms, console and ASP.NET apps, from nuget.org:
dotnet add package Keyfern
In Visual Studio: right-click your project, Manage NuGet Packages, search Keyfern on nuget.org and click Install.
No access to nuget.org? Use the Keyfern feed: dotnet add package Keyfern --source https://keyfern.com/nuget/index.json (in Visual Studio add https://keyfern.com/nuget/index.json under Tools, NuGet Package Manager, Package Sources), or download Keyfern.1.0.0.nupkg into a local folder and add that folder as a package source.
Prefer single files? keyfern.py (needs pip install cryptography), keyfern.mjs and keyfern.d.ts.
Example apps on GitHub
Small, complete apps you can clone and run, each with activation, error handling and the verified offline cache:
- electron-license-key-example: Electron (JavaScript)
- python-license-key-example: Python CLI or desktop app (PyQt, PySide, Tkinter)
- wpf-license-key-example: C# / .NET 8 WPF
Core concepts
- Product: one piece of software. It owns an Ed25519 key pair, a machine limit, trial settings and an offline lease length. Product IDs look like
prod_8fQ2xLw1. - Key: a license string such as
ACME-7KQ2M-4XJ9P-HT3WD-NB6RC. It has a status (active, expired, blocked), an optional expiry, eight feature flags, an optional machine limit that overrides the product's, customer details, notes, free-form JSONmetaand an optional usage counter. - Features F1 to F8: eight on/off flags per key. They appear in the signed license as
"features": [1, 3]. You decide what each flag unlocks in your app. - Machine: the device that activated a key, identified by a stable string you choose (maximum 200 characters). Hash a hardware id rather than sending it raw. Each key may activate up to its machine limit (0 means unlimited).
- Floating licenses: set a seat timeout on the product and a machine that has been silent for that many seconds stops counting. Apps just call activate again to keep their seat. Guide: floating licenses.
- Trial: when a product has trial days,
/v1/trialissues a one-machine key namedTRIAL-...with the product's trial features. One trial per machine, and a reinstall during the trial gets the same license back. - Lease: every signed answer says until when an app may run offline (
lease_until). Offline use is off by default (lease_days0:lease_untilequals the time of the answer, so the app must be online); setlease_dayson the product to allow that many days.
Authentication
The license API in /v1 needs no authentication: your app only knows the product ID and public key, and every answer is signed. The management API under /api accepts two kinds of credentials.
Dashboard session
Signing in sets the cookie kf_session (HttpOnly, SameSite=Strict, 30 days). Every request other than GET must also carry the header X-KF: 1, which blocks cross-site request forgery. The dashboard does this for you. Some actions only accept a session: creating, changing and deleting products, API tokens, webhooks, billing, password changes and account deletion.
API tokens
Create a token under API tokens in the dashboard. It looks like kf_... and is shown once; Keyfern stores only a hash. Send it as a bearer token:
curl https://keyfern.com/api/products \
-H "Authorization: Bearer kf_YOUR_TOKEN"
| Scope | Can do |
|---|---|
read | Every GET: list products and keys, read stats and the audit log, download CSV. |
write | Everything a read token can, plus create, change, block, extend and delete keys, change usage, reset machines and import. It cannot manage products, tokens, webhooks or billing. |
A token can be restricted to one product. It then only sees that product, gets product_not_found for any other, and cannot read account-wide data (/api/me, /api/audit answer forbidden). Tokens do not need the X-KF header.
Never embed an API token in your app. Treat tokens like passwords: the app only needs the product ID and the public key.
Responses
Every response is JSON. Successful ones contain "ok": true. Failures look like this, with a machine-readable error code (see Error codes) and a message you can show to people:
{ "ok": false, "error": "plan_limit", "message": "Your plan allows 50 keys. Upgrade to add more." }
Timestamps are unix seconds. Key strings are case-insensitive (stored upper-case); machine codes are case-sensitive.
License API (public)
Base URL: your Keyfern host, for example https://keyfern.com. All endpoints take and return JSON and send Access-Control-Allow-Origin: *, so they also work from browsers and Electron renderers. Rate limits are listed under Limits.
Every successful answer has this shape. payload and sig are what you verify; license is the same data already decoded, for convenience and display only:
{
"ok": true,
"payload": "eyJ2IjoxLCJwcm9kdWN0IjoicHJvZF84ZlEyeExXMSIs...",
"sig": "uQ4v0m2m...",
"license": {
"v": 1,
"product": "prod_8fQ2xLw1",
"key": "ACME-7KQ2M-4XJ9P-HT3WD-NB6RC",
"machine": "my-laptop",
"nonce": "abc123",
"iat": 1760000000,
"status": "active",
"expires": 1791536000,
"lease_until": 1762592000,
"features": [1, 3],
"max_machines": 2,
"machines_used": 1,
"customer": { "name": "Jane Doe", "email": "jane@example.com" },
"meta": {},
"usage": { "count": 0, "limit": null }
}
}
| Field | Meaning |
|---|---|
iat | When Keyfern signed this answer (unix seconds). |
status | active, expired or blocked. Only active should unlock your app. |
expires | When the key stops being valid, or null for a key that never expires. |
start_days | Set only while the key has never been activated: it will expire this many days after its first activation (then it becomes null and expires is set). |
lease_until | Until when the app may run offline on this answer. Equal to iat when the product has offline use off. Never later than expires. |
features | Enabled feature flags, numbers 1 to 8. |
max_machines | Machine limit for this key. 0 means unlimited. |
machines_used | Machines currently counting against the limit. |
meta, customer, usage | Your custom data, the customer name and email, and the usage counter with its optional limit. |
POST/v1/activate
Registers a machine for a key and returns a signed license. Calling it again from the same machine just refreshes it, so apps can call it at every start. It fails with machine_limit when the key already has the maximum number of other machines, and with blocked or expired for unusable keys.
| Field | Type | Notes |
|---|---|---|
product | string | Required. The product ID. |
key | string | Required. The license key. |
machine | string | Required. Stable machine identifier, up to 200 characters. |
nonce | string | Recommended. Random string, up to 100 characters. It is echoed inside the signed payload; check it matches to stop replayed answers. |
name | string | Optional. A label such as the computer name, shown in the dashboard. |
curl -X POST https://keyfern.com/v1/activate \
-H "Content-Type: application/json" \
-d '{"product":"prod_8fQ2xLw1","key":"ACME-7KQ2M-4XJ9P-HT3WD-NB6RC","machine":"my-laptop","name":"Jane laptop","nonce":"abc123"}'
Response: the signed license shown above. Error example:
HTTP 403
{ "ok": false, "error": "machine_limit", "message": "Machine limit reached (2)" }
POST/v1/validate
Read-only check. It never registers a machine and it also answers for expired keys, which is handy to show a "Renew" button. Fields: product, key (required), machine and nonce (optional). The answer is a signed license whose decoded license.machine_registered is true or false when you sent a machine, and null otherwise.
curl -X POST https://keyfern.com/v1/validate \
-H "Content-Type: application/json" \
-d '{"product":"prod_8fQ2xLw1","key":"ACME-7KQ2M-4XJ9P-HT3WD-NB6RC","machine":"my-laptop","nonce":"n-2"}'
POST/v1/deactivate
Frees a machine so the customer can activate another. Fields: product, key, machine (all required). Returns {"ok": true, "removed": 1}, with removed: 0 if that machine was not registered. Fails with not_allowed when you turned off self-service deactivation for the product. You can always remove machines yourself in the dashboard or with the management API.
curl -X POST https://keyfern.com/v1/deactivate \
-H "Content-Type: application/json" \
-d '{"product":"prod_8fQ2xLw1","key":"ACME-7KQ2M-4XJ9P-HT3WD-NB6RC","machine":"my-laptop"}'
POST/v1/trial
Starts a free trial for a machine and returns a signed license, exactly like activate. It needs trial days to be set on the product. The trial key is named TRIAL-..., allows one machine and unlocks the product's trial features. A machine gets one trial: asking again during the trial returns the same license, and after it ends you get trial_used. Fields: product, machine (required), nonce (optional).
curl -X POST https://keyfern.com/v1/trial \
-H "Content-Type: application/json" \
-d '{"product":"prod_8fQ2xLw1","machine":"my-laptop","nonce":"n-3"}'
GET/v1/products/:pid/public-key
Returns the product's public key. You normally copy it from the dashboard and embed it, because fetching it at runtime from the same server you want to verify defeats the purpose.
curl https://keyfern.com/v1/products/prod_8fQ2xLw1/public-key
{ "ok": true, "product": "prod_8fQ2xLw1", "algorithm": "ed25519",
"public_key": "hX3kQ...", // 32 raw bytes, base64url
"public_key_pem": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----\n" }
Verifying answers
This is what makes Keyfern safe against a fake server or a tampered response. Your app embeds only the public key. Keyfern signs the answer with the matching private key, which never leaves the server.
- Decode
payloadfrom base64url (the URL-safe alphabet, no padding) to bytes. Those exact bytes are what was signed. Do not parse and re-serialise the JSON before verifying. - Decode
sigfrom base64url. It is a 64-byte Ed25519 signature over the payload bytes. - Verify the signature with the product public key (32 raw bytes, base64url). Reject on failure.
- Only now parse the payload as JSON and check it:
productequals your product ID andkeyis the key you sent.nonceequals the nonce you sent. This stops an attacker replaying an old valid answer.iatis close to your clock, for example within 10 minutes, for live checks.statusisactive, andexpiresisnullor in the future.- For offline use, store the whole answer. Allow the app to run while the current time is before
lease_until, and also remember the latest time you saw so that setting the clock back does not extend the lease.
import base64, json, time
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
from cryptography.exceptions import InvalidSignature
def b64d(s):
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
def verify(resp, public_key_b64u, product, nonce):
pub = Ed25519PublicKey.from_public_bytes(b64d(public_key_b64u))
payload_bytes = b64d(resp["payload"])
try:
pub.verify(b64d(resp["sig"]), payload_bytes) # raises if forged
except InvalidSignature:
raise ValueError("bad signature")
p = json.loads(payload_bytes)
if p["product"] != product or p["nonce"] != nonce:
raise ValueError("wrong product or replayed answer")
if abs(time.time() - p["iat"]) > 600:
raise ValueError("answer is too old or the clock is wrong")
if p["status"] != "active" or (p["expires"] is not None and p["expires"] <= time.time()):
raise ValueError("license is " + p["status"])
return pimport crypto from 'node:crypto';
const b64u = s => Buffer.from(s, 'base64url');
const SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex'); // wraps a raw Ed25519 key
export function verify(resp, publicKey, { product, nonce }) {
const key = crypto.createPublicKey({ key: Buffer.concat([SPKI_PREFIX, b64u(publicKey)]), format: 'der', type: 'spki' });
const bytes = b64u(resp.payload);
if (!crypto.verify(null, bytes, key, b64u(resp.sig))) throw new Error('bad signature');
const p = JSON.parse(bytes.toString('utf8'));
if (p.product !== product || p.nonce !== nonce) throw new Error('wrong product or replayed answer');
if (Math.abs(Date.now() / 1000 - p.iat) > 600) throw new Error('answer too old or clock wrong');
if (p.status !== 'active' || (p.expires !== null && p.expires <= Date.now() / 1000)) throw new Error('license is ' + p.status);
return p;
}The browser crypto.subtle API supports Ed25519 in current browsers (the JavaScript SDK uses it). If you target an older runtime, add a small library such as tweetnacl.
Never skip the signature check. Without it a hosts-file entry pointing at a fake server unlocks your app.
Error codes
The HTTP status tells the family of problem, the error code the exact one. Show message to people, branch on error in code.
| error | HTTP | Meaning |
|---|---|---|
invalid_request | 400 | A field is missing, too long or has the wrong type. The message says which. |
invalid_json | 400 | The body is not a JSON object. |
invalid_key | 404 | That key does not exist for this product. |
product_not_found | 404 | Unknown product ID, or a restricted token asked for another product. |
blocked | 403 | The key was blocked by the vendor. |
expired | 403 | The key passed its expiry date. /v1/validate still answers for it. |
machine_limit | 403 | The key is already active on the maximum number of machines. |
not_allowed | 403 | Self-service deactivation is turned off for this product. |
trial_unavailable | 403 | The product has no trial days set. |
trial_used | 403 | This machine already had its trial and it is over. |
usage_limit | 403 | The change would push the key's usage counter above its limit. |
rate_limited | 429 | Too many requests, invalid keys, trials or sign-in attempts. Retry later. |
plan_limit | 402 | Your Keyfern plan does not allow this (more keys, products, tokens, webhooks, or selling keys). |
captcha_required | 403 | The dashboard must show a quick human check first (sign-up, sign-in, password reset, large batches). Requests with an API token never get it. |
captcha_unavailable | 503 | The human check service could not be reached. Retry in a moment. |
unauthorized | 401 | No valid session. Sign in again. |
invalid_token | 401 | The bearer token is unknown or was deleted. |
bad_credentials | 401 | Wrong email or password. |
csrf | 403 | A session request other than GET is missing the X-KF: 1 header. |
session_required | 403 | That action needs a dashboard login, not an API token. |
insufficient_scope | 403 | The token is read-only but the request changes data. |
forbidden | 403 | Operator-only endpoint. |
not_found | 404 | Unknown endpoint, token, webhook or account. |
email_taken, name_taken, key_exists | 409 | An account, product name or custom key already exists. |
too_large | 413 | Request body over the limit (1 MB, 20 MB for import). |
bad_token | 400 | A password reset link is invalid or expired. |
no_subscription | 400 | There is no subscription to manage yet. |
billing_unavailable, stripe_error | 503, 502 | Billing is not configured on this server, or the payment provider failed. |
server_error | 500 | Unexpected. Retry; if it persists, contact support. |
Treat 429 and 5xx as "could not check". Keep the app running on its cached license and try again. Do not treat them as an invalid license.
Management API
The dashboard uses exactly these endpoints, so everything you can click you can script. "token" in the Auth column means a session or an API token (write scope for anything but GET). "session" means a dashboard login only. Examples use a token in $KF:
export KF=kf_YOUR_TOKEN
export HOST=https://keyfern.com
Products and account
| Endpoint | Auth | Description |
|---|---|---|
GET/api/me | token | Your account, plan, limits and usage. |
GET/api/plans | none | Public plan list. Prices are in US cents. |
GET/api/products | token | All products, including public_key, public_key_pem, stripe_webhook_url. |
POST/api/products | session | Create a product. Fields: name (required), key_prefix, max_machines, trial_days, trial_features (array 1-8), lease_days, floating_ttl (seconds), allow_deactivate. |
GET/api/products/:pid | token | One product. |
PATCH/api/products/:pid | session | Change any of the fields above, plus stripe_webhook_secret and sale (see Stripe). |
DELETE/api/products/:pid | session | Delete a product and all its keys. Body {"confirm": "<exact product name>"}. |
GET/api/products/:pid/stats | token | Key counts, machine count and daily activations and trials for 30 days. |
curl $HOST/api/products -H "Authorization: Bearer $KF"
Keys
| Endpoint | Description |
|---|---|
GET/api/products/:pid/keys | List keys, newest first. Query: q (matches key, customer name, email, notes), status (active, expired, blocked), limit (1-200, default 50), offset. Returns {total, keys}; each key has machines_used. |
GET/api/products/:pid/keys.csv | CSV download of the same filtered list: key, status, expires_at, features, max_machines, customer_name, customer_email, notes, created_at. |
POST/api/products/:pid/keys | Create keys. Body fields below. |
GET/api/products/:pid/keys/:key | One key with its activated machines (code, name, ip, first_seen, last_seen). |
PATCH/api/products/:pid/keys/:key | Change expires_at (unix seconds, ISO date or null for never), extend_days, status (active or blocked), features, max_machines (null = product default), customer_name, customer_email, notes, meta (object up to 4 KB), usage_limit. |
POST.../keys/:key/blockPOST .../keys/:key/unblock | Block or unblock. Blocked keys fail with blocked. |
POST.../keys/:key/extend | Body {"days": 30} adds days to the later of now and the current expiry (a never-expiring key stays that way), or {"expires_at": ...} sets a date. |
POST.../keys/:key/usage | Body {"delta": 1} adds to or subtracts from the usage counter, never below 0. Returns usage_limit (403) if it would exceed the limit. Use it to count exports, renders, API calls. |
POST.../keys/:key/reset-machines | Remove every activated machine. |
DELETE.../keys/:key/machines/:code | Remove one machine. |
DELETE.../keys/:key | Delete a key and its machines. |
Create body: count (1 to 1000, default 1), days (valid for that many days) or expires_at, leave both out for a key that never expires; start_days instead of days starts the period at the key’s first activation (keys you keep in stock and sell later); features (array of 1 to 8), max_machines, customer_name, customer_email, notes, meta, usage_limit, and key to choose the key string yourself (only with count 1; 6 to 80 characters of A-Z 0-9 dash underscore dot). The response is {count, keys, key} where key is the first one.
# 50 keys valid for a year, with features 1 and 2
curl -X POST $HOST/api/products/prod_8fQ2xLw1/keys \
-H "Authorization: Bearer $KF" -H "Content-Type: application/json" \
-d '{"count":50,"days":365,"features":[1,2],"customer_name":"Acme GmbH"}'
# find a customer's key
curl "$HOST/api/products/prod_8fQ2xLw1/keys?q=jane@example.com" -H "Authorization: Bearer $KF"
# block it, then extend another by 30 days
curl -X POST $HOST/api/products/prod_8fQ2xLw1/keys/ACME-7KQ2M-4XJ9P-HT3WD-NB6RC/block \
-H "Authorization: Bearer $KF" -H "Content-Type: application/json" -d '{}'
curl -X POST $HOST/api/products/prod_8fQ2xLw1/keys/ACME-AAAAA-BBBBB-CCCCC-DDDDD/extend \
-H "Authorization: Bearer $KF" -H "Content-Type: application/json" -d '{"days":30}'
# count one use against a limit
curl -X POST $HOST/api/products/prod_8fQ2xLw1/keys/ACME-7KQ2M-4XJ9P-HT3WD-NB6RC/usage \
-H "Authorization: Bearer $KF" -H "Content-Type: application/json" -d '{"delta":1}'
# export CSV
curl -OJ $HOST/api/products/prod_8fQ2xLw1/keys.csv -H "Authorization: Bearer $KF"
Import
POST/api/products/:pid/import (token, write scope) takes {"keys": [ ... ]} with up to 20,000 keys and 20 MB per request. Keys that already exist are updated, new keys are created, and every key is validated on its own: bad rows are reported back (first 50) while the rest are imported. New keys count against your plan. The dashboard's Import button takes the same data as CSV or JSON. Add "dry_run": true to get the same counts without saving anything: the dashboard shows that preview before every import. The answer also has duplicates, the rows that repeat a key already in the list.
| Field | Notes |
|---|---|
key | Required. 6 to 80 characters: A-Z 0-9 dash underscore dot, starting with a letter or digit. Stored upper-case. |
status or blocked | "blocked" or blocked: true imports the key blocked. Anything else is active. |
expires_at | Unix seconds or an ISO date string. Empty or null means never. |
features | Array such as [1, 3], or an integer bit mask. |
max_machines | Per-key machine limit. Empty means use the product's. |
customer_name, customer_email, notes | Optional text. |
meta | Optional JSON object, truncated at 4 KB. |
created_at | Optional, unix seconds or ISO date. |
machines | Optional list of {code, name, ip, first_seen, last_seen}. Machine codes are kept as they are, so customers do not need to reactivate. |
meta.source_id | Only for rows without key, such as subscriptions from a billing export: the first import creates a new key for it, later imports update that same key. |
curl -X POST $HOST/api/products/prod_8fQ2xLw1/import \
-H "Authorization: Bearer $KF" -H "Content-Type: application/json" \
-d '{"keys":[{"key":"OLD-AAAAA-11111","expires_at":"2027-12-31","features":[1,2],"customer_email":"jane@example.com","machines":[{"code":"3f9c2d"}]}]}'
{ "ok": true, "created": 1, "updated": 0, "duplicates": 0, "errors": [] }
POST/api/products/:pid/import/fetch (token, write scope) reads every license key from another service and returns them in the import format above, without saving anything. Body: {"source": "lemonsqueezy" | "creem", "api_key": "...", "machines": false}. The API key is used for that request only and never stored. Set machines to true to keep the existing activations as machines. Send the returned keys to /import. Step by step: migrating from another service.
Tokens and webhooks
| Endpoint | Auth | Description |
|---|---|---|
GET/api/tokens | session | List tokens (name, prefix, scope, product, created, last used). Secrets are never returned. |
POST/api/tokens | session | Body {"name": "CI", "scopes": "read" | "write", "product": "prod_..."} (product optional). Returns the token once. |
PATCH/api/tokens/:id | session | Body {"name"}. Renames a token; scope and product cannot change. |
DELETE/api/tokens/:id | session | Revoke a token. |
GET/api/hooks | session | List outgoing webhooks with their signing secrets. |
POST/api/hooks | session | Body {"url": "https://..."}. Returns {hook: {id, url, secret}}. Paid plans only. |
DELETE/api/hooks/:id | session | Delete a webhook. |
Audit log, stats, billing, operator
| Endpoint | Auth | Description |
|---|---|---|
GET/api/audit?limit=100 | token | Latest events (1 to 500): ts, actor, action, target, detail. Kept 400 days. |
GET/api/products/:pid/stats | token | {keys: {total, active, expired, blocked}, machines, activity: [{day, activations, trials}]} |
GET/api/products/:pid/analytics | token | Paid plans. Where the product is used. ?days= 1 to 365 (default 30). {countries: [{cc, machines, activations, checks}], daily: [{day, activations, checks}], totals}. Country comes from the request IP; ZZ = unknown. |
GET/api/products/:pid/analytics.csv | token | The same as CSV, by country, or per day with ?by=day. |
POST/api/billing/checkout | session | Body {"plan": "starter" | "business" | "enterprise", "interval": "month" | "year"}. Returns a Stripe Checkout url. If you already pay for a plan, the subscription is changed in place (prorated) and the answer is {"changed": true, "url": ...}. |
POST/api/billing/portal | session | Returns a Stripe customer portal url to update the card or cancel. |
POST/api/password | session | Body {"password", "new_password"}. |
DELETE/api/me | session | Body {"password"}, or {"confirm_email"} for accounts that only sign in with Google. Deletes the account and all its data. |
POST/api/forgot, POST/api/reset | none | Password reset: {"email"} sends a one-hour link, {"token", "password"} sets the new password. |
GET/api/admin/overviewGET /api/admin/accounts?q=POST /api/admin/accounts/:id/plan | operator | Platform totals, account search, and manually setting an account's plan. Only for operator accounts. |
Webhooks
Add an HTTPS endpoint under Webhooks in the dashboard (paid plans). Keyfern POSTs a JSON body for these events:
| Event | Sent when |
|---|---|
key.created | Keys are created (not for batches above 20). |
key.activated | A key is activated on its first machine. data has product, key, machine. |
key.deactivated | A customer deactivates a machine. |
key.blocked, key.unblocked | A key is blocked or unblocked. |
key.extended | A key's expiry changes, including Stripe renewals. data.expires_at is the new date. |
trial.started | A new trial key is issued. |
sale.completed | A Stripe purchase created a key. data.email is the buyer. |
POSThttps://your-server.example/keyfern-webhook
Content-Type: application/json
Keyfern-Signature: t=1760000000,v1=5f2b...e91c
{ "event": "key.activated", "created": 1760000000,
"data": { "product": "prod_8fQ2xLw1", "key": "ACME-7KQ2M-4XJ9P-HT3WD-NB6RC", "machine": "my-laptop" } }
Verify the signature
The header carries a timestamp t and v1, the hex HMAC-SHA256 of t + "." + rawBody keyed with your webhook secret (the full whsec_... string). Compare in constant time and reject timestamps older than a few minutes.
import crypto from 'node:crypto';
function verifyKeyfern(rawBody, header, secret, tolerance = 300) {
const parts = Object.fromEntries(header.split(',').map(p => p.split('=')));
const expected = crypto.createHmac('sha256', secret).update(parts.t + '.' + rawBody).digest('hex');
return Math.abs(Date.now() / 1000 - Number(parts.t)) <= tolerance &&
parts.v1?.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(parts.v1), Buffer.from(expected));
}import hmac, hashlib, time
def verify_keyfern(raw_body: bytes, header: str, secret: str, tolerance=300) -> bool:
parts = dict(p.split("=", 1) for p in header.split(","))
expected = hmac.new(secret.encode(), parts["t"].encode() + b"." + raw_body, hashlib.sha256).hexdigest()
return abs(time.time() - int(parts["t"])) <= tolerance and hmac.compare_digest(parts["v1"], expected)Answer with any 2xx within 5 seconds. A failed delivery is retried once after 30 seconds, then dropped, and retries do not survive a server restart. Make your handler idempotent and treat webhooks as a notification: when it matters, confirm with the management API. Webhook URLs must be https and resolve to a public address.
Stripe webhook setup
Keyfern can create and email a license key after each Stripe purchase, using your own Stripe account (overview: selling license keys with Stripe). Payments go to you; Keyfern only receives the result. It needs a paid plan and no Stripe API key of yours: only the webhook signing secret.
- In your Stripe dashboard create a Payment Link (or your own Checkout) for the price you want. One-time and subscription prices both work.
- Add a webhook endpoint under Developers, Webhooks. The URL is shown on the product's Sell with Stripe tab and looks like
https://keyfern.com/hooks/stripe/prod_8fQ2xLw1. Select the eventscheckout.session.completedandinvoice.paid. - Copy the endpoint's signing secret (
whsec_...) into the same tab. - Set the key defaults: days valid (empty means lifetime), the features to unlock and an optional machine limit. Save, then make a test purchase in Stripe test mode.
What happens: when a checkout is paid, Keyfern creates a key with those defaults (using your key prefix), stores the buyer's name and email, emails the key to the buyer, records it in the audit log and fires a sale.completed webhook. Each checkout makes exactly one key, even if Stripe delivers the event twice. For subscriptions leave days valid empty: the key starts valid for about a month and every paid invoice.paid extends it to the end of the paid period plus three days of grace, so a failed card payment does not lock customers out immediately. Cancelled subscriptions simply stop being extended and the key expires. If your plan's key limit is reached the sale cannot create a key: you see it in the audit log, and Stripe keeps retrying the event for up to three days, so the key is created as soon as you upgrade.
Limits and rate limits
| What | Limit |
|---|---|
Public license API (/v1) | 300 requests per minute per IP address |
| Invalid keys (probing) | 15 per 10 minutes per IP address, then rate_limited |
| New trials | 5 per day per IP address, 300 per day per product |
| Sign-ups, password reset requests | 5 per hour per IP address |
| Sign-in attempts | 20 per 15 minutes per IP address and 10 per 15 minutes per email |
| Keys per create request | 1,000 |
| Keys per import request | 20,000 and 20 MB |
| Request body (everything else) | 1 MB |
| Key string | 6 to 80 characters (A-Z 0-9 dash underscore dot, starting with a letter or digit) |
meta per key | 4 KB of JSON |
| Webhook delivery | 5 second timeout, one retry after 30 seconds |
| Audit log retention | 400 days |
Plan limits
Plans count keys, never API calls. These numbers come live from the server:
| Plan | Price | Products | Keys | API tokens | Webhooks | Sell keys |
|---|---|---|---|---|---|---|
| Loading… | ||||||
Need help? Check the dashboard, or reach us through the contact address on the Terms page.