@permitplane/backend
v0.1.0
Published
Server-side helpers for PermitPlane vendor backends (integration/v1).
Maintainers
Readme
@permitplane/backend (Node)
Server-side helpers for PermitPlane vendor backends: a typed client for the
/integration/v1 backend routes, typed errors, safe retries and webhook
signature verification. TypeScript, ESM only, zero runtime dependencies
(global fetch, node:crypto). Node >= 22.
Install
npm install @permitplane/backendLicensed under Apache-2.0. Homepage: https://permitplane.com
Use
import { PermitPlaneBackend, deriveIdempotencyKey } from "@permitplane/backend";
const pp = new PermitPlaneBackend({
baseUrl: "https://licensing.example.com", // https only; a path prefix is allowed
token: process.env.PERMITPLANE_BACKEND_TOKEN!, // VendorBackend bearer secret
});
// resolve -> read the enrollment -> authorize
const { customer_id } = await pp.resolveCustomer({
product_id, namespace_id, external_subject: user.id, verification_reference: "myapp-verified:" + user.id,
});
const enrollment = await pp.getEnrollment(enrollmentId);
await pp.authorizeEnrollment(enrollmentId, {
customer_id, mode: "trial", verification_reference: "myapp-verified:" + user.id,
expected_revision: enrollment.revision,
});
// issue a licence; derive the key from your own order so a restarted worker replays
await pp.issueLicense(
{ product_id, namespace_id, customer_id, policy_id, paid_through: new Date("2027-01-01T00:00:00Z"), reason: "Order ord_123" },
{ idempotencyKey: deriveIdempotencyKey("order", "ord_123", "issue") },
);Wire objects stay snake_case. Also available: denyEnrollment, listPolicies,
getLicense, actOnLicense, deliverLicenseKey, revokeLicenseKey,
issueLicenseFile.
Offline (air-gapped) installs: issueLicenseFile signs a licence file (scope
license_files.issue). valid_days (1 to 21) and installation_key_thumbprint
(43 base64url characters, binds the file to one installation) are optional.
Write license_file to disk exactly as returned.
const issued = await pp.issueLicenseFile(licenseId, {
product_id, customer_id, valid_days: 7, installation_key_thumbprint: thumbprint,
});
await writeFile(issued.filename, issued.license_file, "utf8");Self-hosting behind a sub-path works: baseUrl: "https://host/licensing"
(a trailing slash is normalised; backslashes, % escapes and dot segments are rejected). Plain http is accepted only for
127.0.0.1, localhost and [::1] and only with allowInsecureHttp: true.
Errors
Everything extends PermitPlaneError. Server errors are ApiError subclasses
carrying status, code, requestId, details, retryAfterSeconds,
idempotencyKey, method and path.
try {
await pp.authorizeEnrollment(id, input);
} catch (err) {
if (err instanceof RevisionConflictError) { /* reload the enrollment and retry */ }
else if (err instanceof IdempotencyConflictError) { /* same key, different body: a bug */ }
else throw err;
}The server's text is in err.serverMessage; err.message is
<code> (HTTP <status>, request <id>). Error objects never contain the token,
request bodies or response bodies.
Idempotency and retries
Keyed operations (resolve, authorize, deny, issue, act) always send an
Idempotency-Key: yours via { idempotencyKey }, or a generated one reused
for every automatic retry and exposed as err.idempotencyKey. The server
keeps receipts for 24 hours for resolve/authorize/deny and permanently for
issue/act. A changed body with the same key gives IdempotencyConflictError.
Automatic retries (default 2, so at most 3 attempts; timeoutMs 15000 per
attempt; maxRetryDelayMs 5000; timeouts and delays must be positive and finite, retries an integer from 0 to 10, else ConfigurationError or, per call, RequestValidationError) apply to GETs and keyed POSTs on transport
errors, timeouts, 502, 503, 504, 429 and 409 operation_in_progress.
deliverLicenseKey, revokeLicenseKey and issueLicenseFile are never
retried automatically; repeating them yourself is safe (a repeated
issueLicenseFile signs and records a new file).
The server currently sends Retry-After: 60 on every 429 and 503. That is
above maxRetryDelayMs, so those surface immediately as RateLimitedError or
ServiceUnavailableError with retryAfterSeconds = 60. Do not block a
request handler for a minute; queue the work and retry later.
Security
- The token is server-only. Never ship it to apps or browsers.
- Redirects are refused (
UnexpectedResponseError); the token is never forwarded elsewhere. deliverLicenseKeyresponses contain a secret licence key. Do not log them.
Webhooks
Header PermitPlane-Signature: t=<unix seconds>,v1=<sig>[,v1=<sig>], where
sig is the lowercase hex HMAC-SHA256 of "<t>." + raw body keyed with the
UTF-8 bytes of the full secret (ppwhsec_...). Tolerance is 300 seconds (inclusive), uppercase hex is tolerated, and
any matching v1 is accepted, so you can pass old and new secrets together.
app.post("/webhooks/permitplane", express.raw({ type: "application/json" }), (req, res) => {
const event = parseWebhookEvent({
payload: req.body, // the RAW body, never re-serialized JSON
header: req.get(WEBHOOK_SIGNATURE_HEADER),
secrets: [process.env.PP_WEBHOOK_SECRET!],
});
// dedupe on the event id, then call getLicense for the authoritative state
res.sendStatus(204);
});Do not rely on arrival order; fetch the current state with getLicense.
Development
npm ci --include=dev # NODE_ENV=production would skip dev dependencies
npm test && npm pack --dry-run