Documentation menuLicense server
License server
Turn Polar orders and subscriptions into signed licenses automatically.
lib/licenses.ts
import { createPolarClient } from "@sweberdev/integral/polar";
import { createLicenseServer, sqlStore } from "@weber-development/integral-server";
export const licenses = createLicenseServer({
privateKey: process.env.INTEGRAL_PRIVATE_KEY!,
product: "my-app",
store: sqlStore((sql, params) => pool.query(sql, params).then((r) => r.rows), {
dialect: "postgres",
}),
plans: {
// Polar product id → plan
"a1b2…": { plan: "pro" },
"c3d4…": { plan: "team", seats: 10, limits: { projects: null } },
},
polar: createPolarClient({ organizationId: process.env.POLAR_ORG_ID! }),
onLicense: async (record, event) => {
if (event === "issued") await mail(record.email, `Your license: ${record.license}`);
},
});
plans can also be a function ({ id, name }) => PlanMapping | null. Products that map to null are ignored, so one Polar organization can sell several products.
Routes
app/api/integral/[...path]/route.ts
import { createLicenseHandler } from "@weber-development/integral-server";
import { licenses } from "@/lib/licenses";
const handler = createLicenseHandler(licenses, {
webhookSecret: process.env.POLAR_WEBHOOK_SECRET!,
basePath: "/api/integral",
corsOrigin: "https://app.example.ch", // only if a browser app on another origin calls it
});
export { handler as GET, handler as POST, handler as OPTIONS };
| Route | Purpose |
|---|---|
POST /webhook | Polar webhook endpoint. Verifies the signature and age of each delivery |
POST /webhook/<source> | Webhook of another payment source (stripe, paddle, lemonsqueezy or your own), since 2.0 |
POST /devices { license } | Devices the license is activated on and the limit, for the customer's own view, since 2.0 |
POST /overview { license, periods? } | Plan, status, dates, features, limits, usage per period, seats in use and devices for the customer's own view, since 2.1 |
POST /exchange { key } | Polar license key → the customer's signed license |
POST /refresh { license } | Current version of a license, e.g. after a renewal |
GET /revocations | Signed list of all revoked licenses (plain text, cached 5 minutes), since 0.2.0 |
POST /activate { license | key | request, machine, label? } | License bound to this device, within the device limit, since 0.3.0 |
POST /deactivate { license, machine } | Frees the device's place, since 0.3.0 |
POST /lease { license, holder, label?, ttlSeconds? } | Takes or renews a floating seat, since 0.4.0 |
POST /lease/release { license, holder } | Gives the seat back, since 0.4.0 |
POST /usage { license, metric, amount?, period? } | Counts usage against the license's limit, since 0.4.0 |
POST /trial { email, name? } | Starts a trial license, since 0.7.0 |
GET /offline | Page that turns an activation request into a license, since 0.7.0 |
GET /public-key | Public key of the signing key (and publicKeys with the earlier ones) |
In Polar, add a webhook (Settings → Webhooks) to https://your-app/api/integral/webhook with the events order.paid, order.refunded and all subscription.* events. For /exchange, attach a License Keys benefit to the products.
Other payment sources
Since 2.0 the handler takes a list of sources. Each one checks the signature of its provider's webhook and hands a normalized event to the same logic as Polar, so licenses, renewals, cancellations, refunds, emails, webhooks and the audit trail work the same. Ids are prefixed (stripe:sub_…), so the sources never collide.
import {
createLicenseHandler,
lemonSqueezySource,
paddleSource,
polarSource,
stripeSource,
} from "@weber-development/integral-server";
const handler = createLicenseHandler(licenses, {
basePath: "/api/integral",
sources: [
polarSource({ secret: process.env.POLAR_WEBHOOK_SECRET! }),
stripeSource({ secret: process.env.STRIPE_WEBHOOK_SECRET!, apiKey: process.env.STRIPE_KEY }),
paddleSource({ secret: process.env.PADDLE_WEBHOOK_SECRET!, apiKey: process.env.PADDLE_KEY }),
lemonSqueezySource({ secret: process.env.LS_WEBHOOK_SECRET!, oneTimeProducts: ["777"] }),
],
});
webhookSecret still works and is the same as polarSource at /webhook. Point each provider to /webhook/<name>: polar, stripe, paddle, lemonsqueezy. Map the provider's product ids in plans (Stripe prod_…, Paddle pro_…, Lemon Squeezy numeric product_id as a string).
| Source | Events handled | Notes |
|---|---|---|
| Polar | order.paid, order.refunded, subscription.* | Verified in production use |
| Stripe | customer.subscription.created|updated|deleted, checkout.session.completed (mode payment) | Stripe does not send the email with subscription events: pass apiKey (a restricted key that can read customers) or customer for your own lookup. One-time checkouts take the product from metadata.product_id or the product option. Since 2.1 charge.refunded (full refunds) revokes the license and cancel_at counts as a cancellation at the period end |
| Paddle Billing | subscription.*, transaction.completed without a subscription, approved refund adjustment.* (since 2.1) | Email via apiKey or customer, as with Stripe |
| Lemon Squeezy | subscription_*, order_created and order_refunded for oneTimeProducts | Lemon Squeezy sends order_created for every subscription payment too, so list only the products you sell once |
Beta. The Stripe, Paddle and Lemon Squeezy sources follow the providers' documentation (signature schemes, event fields) and are tested with locally signed sample events. They were not verified against real provider accounts. Test them in the providers' test mode, check the first licenses in the admin view and report differences. A PaymentSource is just { name, verify(body, headers) } returning a Polar-shaped event or null, so you can adapt a provider that differs.
Partial refunds are not treated as a revocation; revoke by hand if you want that.
Customer overview
server.overview(license, { periods }) (1 to 24 periods, default 3) and POST /overview return what a customer wants to see about their license: plan, status, exp, updatesUntil, features, limits, usage per metric and period (current period first), floating seats in use with their holders, and the devices with the device limit. Revoked or unknown licenses are refused. The portal's CustomerPortal shows it. Since 2.1. Whoever holds the license key can read it, as with /devices.
Signing with a KMS or HSM
Instead of privateKey the server takes a signer and the matching publicKey. The private key never leaves the service.
import { vaultTransitSigner } from "@weber-development/integral-server";
createLicenseServer({
signer: vaultTransitSigner({
url: process.env.VAULT_ADDR!,
token: process.env.VAULT_TOKEN!,
key: "licenses",
alg: "ES256", // transit key type ecdsa-p256
kid: "2027-a",
}),
publicKey: process.env.INTEGRAL_PUBLIC_KEY!, // p256.…
// …
});
vaultTransitSignersigns over the HTTP API of HashiCorp Vault's transit engine (ecdsa-p256ored25519keys). Tested against a mocked API.kmsSigner({ alg, kid, sign })wraps any KMS call: forES256it hashes the message with SHA-256, passes you the digest and converts the DER answer. AWS KMS (SignwithMessageType: "DIGEST",ECDSA_SHA_256), Google Cloud KMS (asymmetricSignwithdigest.sha256) and Azure Key Vault (signwithES256,signature: "raw") fit this shape. Pass the call of your SDK; Integral adds no SDK dependency.publicKeyFromSpki(derOrPem, alg)turns the public key you export from the KMS into the string forpublicKeyand your apps.
Beta. Only the Vault adapter has a (mocked) test, and none of the three cloud recipes was run against a real account. Sign and verify one license in your setup before you rely on it. The same signer works with bindLicense, signRevocationList and resignAll, so activation, revocation and rotation keep working.
Revocation list
A refund or server.revoke(id) re-signs the license with an end date. An app that only checks offline never sees the new version, and a lifetime license had no end date before. GET /revocations (or server.revocationList()) returns a list of every revoked license id, signed with the same key. The portal downloads it automatically. In other apps, pass it to verifyLicense:
const list = await verifyRevocationList(await (await fetch("/api/integral/revocations")).text(), {
publicKey,
product: "my-app",
});
await verifyLicense(license, { publicKey, revocations: list });
Device activations
Since 0.3.0 the server can bind licenses to devices and limit how many devices one license may use. The app sends its license (or a Polar key) and its machineId() to /activate and gets back a copy bound to that device. The portal does this with bindToMachine.
const result = await licenses.activate({ key: polarKey, machine, label: "Office laptop" });
if (result.ok) result.license; // bound to `machine`
else result.reason; // "not_found", "revoked", "device_limit", "expired", …
await licenses.deactivate(result.license, machine); // frees the place
await licenses.activations(licenseId); // [{ machine, label, createdAt, lastSeenAt }]
- The limit is
seats × devicesPerSeat(optiondevicesPerSeat, default 3). A license without seats counts as one seat. Activating a device that already has a place does not count again. /refreshreturns a renewed license bound to the same device, so renewals keep the binding.- For offline activation, pass the customer's request file as
{ request }(see Device activation). It counts against the same limit. - Activations need storage:
memoryStoreandsqlStoresupport them.sqlSchemanow also creates the tableintegral_licenses_activations(or<table>_activations); run it again after updating. Custom stores implementlistActivations,saveActivationanddeleteActivation.
Floating licenses
Since 0.4.0 a license can be shared between running apps: seats is the number of apps that may run at the same time. Each running app is a holder (any stable id, e.g. one per window or session). The app calls lease when it starts and again as a heartbeat; a seat that is not renewed expires by itself after leaseSeconds (default 300, between 30 and 3600).
const result = await licenses.lease({ license, holder: "session-42", label: "Anna's laptop" });
if (result.ok) result.expiresAt; // seat held until then, call again to renew
else result.reason; // "lease_limit", "revoked", "not_found", …
await licenses.releaseLease(license, "session-42");
await licenses.leases(licenseId); // who holds a seat right now
Devices and seats are independent: device binding limits where a license is installed, floating seats limit how many run at once. The portal holds a seat with useLease().
Usage metering
Count what a customer uses and refuse it above the limit stored in the license (limits in the plan mapping).
const usage = await licenses.recordUsage({ license, metric: "exports", amount: 1 });
if (!usage.ok) usage.reason; // "limit_reached", …
else usage.used; // total in this period
await licenses.usage(licenseId); // [{ metric, period, amount }]
The period is month (default, option usagePeriod), year or none. A metric without a limit is only counted. Refused usage is not counted.
Audit trail
Every change is stored as an event: issued, renewed, revoked, activated, deactivated, and seats taken, released or removed. Read them with licenses.events({ licenseId?, limit? }) (newest first, at most 1000, default 100) or export them from the admin API.
Storage: sqlSchema now also creates <table>_leases, <table>_usage and <table>_events (or integral_licenses_…). Run it again after updating; it keeps existing data. Custom stores implement the optional methods listLeases, saveLease, deleteLease, addUsage, listUsage, saveEvent and listEvents.
Key rotation
Since 0.5.0 you can replace the signing key without locking anyone out. Generate a new key pair, set the new private key and list the old public key:
createLicenseServer({
privateKey: process.env.INTEGRAL_PRIVATE_KEY!, // the new key (Ed25519 or P-256)
previousPublicKeys: [process.env.INTEGRAL_OLD_PUBLIC_KEY!], // may use the other algorithm
// …
});
Licenses signed with an old key stay valid for the server (refresh, activate, lease, usage). Then ship your app with await licenses.publicKeys() (or GET /public-key, which answers publicKeys): verifyLicense accepts a list. resignAll() signs every license that is not revoked again with the new key without emailing customers; apps receive the new version with their next refresh. Remove the old key from your apps and the server once no license of it is in use anymore.
Webhooks
createLicenseServer({
// …
webhooks: [
{ url: "https://example.ch/hooks/integral", secret: process.env.HOOK_SECRET },
{ url: process.env.SLACK_URL!, format: "slack", events: ["issued", "revoked"] },
],
});
Every event of the audit trail is sent to the matching targets. format is json (default: { id, type, at, licenseId, data }), slack or teams (a short text). With a secret, each request carries x-integral-signature: sha256=<hex>, the HMAC-SHA256 of the body; signDelivery(body, secret) computes it for your check. A target that does not answer within 5 seconds or fails is skipped and never breaks the license change.
Emails
createLicenseServer({
// …
mail: {
appName: "My App",
locale: "de", // or "en"
portalUrl: "https://polar.sh/my-org/portal",
supportEmail: "support@example.ch",
send: ({ to, subject, text, html }) => mailer.send({ from, to, subject, text, html }),
},
});
The customer gets a mail on issued, renewed, canceled, ended and revoked (option events to choose). The license key is included unless the license was revoked or ended. licenseMail(record, event, options) returns the texts if you prefer to send them yourself. A failing send is logged as mail_failed and does not fail the license change.
Import from another system
Since 0.6.0 you can move customers from Keygen, Cryptlex or a spreadsheet. Export the licenses as CSV and import them:
import { importLicenses, rowsFromCsv } from "@weber-development/integral-server";
const rows = rowsFromCsv(await readFile("licenses.csv", "utf8"));
const check = await importLicenses(licenses, rows, {
plans: { "Pro Yearly": "pro", "Team": "team" }, // plan or policy of the old system → your plan
defaultPlan: "pro", // optional; without it unknown plans are refused
dryRun: true,
});
check.errors; // [{ row: 3, reason: 'unknown plan "Trial"' }]
await importLicenses(licenses, rows, { plans: { "Pro Yearly": "pro", Team: "team" } });
rowsFromCsv finds the columns by common names: key or id (reference), email, policy, plan or product, expiry or expiresAt, maxMachines or seats, name. Pass { plan: "Your column" } as second argument for other headers. The old keys do not work with Integral: every customer gets a new license, which you can send with licenseMail(). Importing the same file twice does not create duplicates. Leave the mail option unset during the import, or customers get a mail for each license.
Usage billing with Polar Meters
createLicenseServer({
// …
polarMeters: { accessToken: process.env.POLAR_TOKEN! },
});
Every counted recordUsage is sent to Polar as an event (POST /v1/events/ingest) named after the metric, for the Polar customer of the license, with the metadata amount, license_id and period. In Polar, create a meter that filters on this event name and sums amount, and attach it to a product. The token needs the events:write scope. Use eventName: (metric) => "app." + metric to rename events. Refused usage and licenses without a Polar customer (manual or imported ones) are not sent. If Polar cannot be reached, the usage is still counted and meter_failed appears in the audit trail.
Trials
Since 0.7.0 your app can hand out free trials without you issuing them by hand:
createLicenseServer({
// …
trial: { plan: "pro", days: 14 }, // optional: features, limits, seats
});
POST /trial { email } (or licenses.startTrial({ email })) returns a license marked trial that ends after the trial days; licenseStatus() reports it and the status banner warns before it ends. Each email address gets one trial: upper and lower case and a +tag count as the same address, so anna+2@example.ch cannot start a second one. A second request answers 409 trial_used. With the mail option the customer also receives the license by email, which is a simple way to check the address. Put the route behind your own rate limit if your app is public, because a person can still use many addresses. When the customer buys, the paid license replaces the trial.
Offline activation page
GET /offline (add ?lang=de for German) is a small page without dependencies that turns an activation request into a license bound to the device. Link to it from the portal's <OfflineActivation>: the customer copies the request from the offline computer, opens the page on any computer with internet, pastes it, and copies the license back. The page uses the normal /activate route, so the device limit applies, and it sets a strict content security policy.
Lifecycle
| Polar event | License |
|---|---|
order.paid (one-time) | Issued without end, e.g. Lifetime |
subscription.active | Issued, updatesUntil = end of period + graceDays (default 3) |
subscription.updated (renewal) | Re-issued with the same id and a later updatesUntil |
subscription.canceled | Status canceled, license unchanged until the period ends |
subscription.revoked / ended | Status ended, updatesUntil = end date |
order.refunded | Revoked: exp set to now |
With afterCancel: "expire", licenses also get exp, so they stop working when the subscription ends.
Storage
memoryStore()for tests.sqlStore(query, { dialect, table? })for Postgres ($1), SQLite and MySQL (?).query(sql, params)must return the rows.sqlSchema({ dialect })returns theCREATE TABLEstatement.- Or implement
LicenseStore(get,findBySource,findByCustomer,save,list, and for device activationslistActivations,saveActivation,deleteActivation) for anything else.
Manual licenses
await licenses.issueManual({ email: "kunde@example.ch", plan: "team", reference: "INV-2026-041", updatesUntil: "2027-10-31" });
await licenses.revoke(licenseId);
Other frameworks
verifyPolarWebhook(rawBody, headers, secret) and licenses.handleEvent(event) work without the fetch handler, e.g. in Express. Always pass the raw request body: re-serialised JSON breaks the signature.