DOCS LLMs

Machine File Format

Machine File Format

This is the complete wire format of a LicenseSeat offline machine file, written so you can verify one in any language without an SDK. The format is stable: everything below is what the server emits today, and it changes only with a new schema_version. If you implement exactly these steps, your verifier is correct; nothing here is "try a few algorithms".

A machine file is encrypted to one device, then signed: AES-256-GCM with a key derived from the license key and the device fingerprint means it opens only on the device it was issued for, and an Ed25519 signature over the ciphertext proves LicenseSeat issued it.

What you need on the device, offline:

Input Where it comes from
The certificate POST /api/v1/products/{slug}/licenses/{key}/machine-file, once, online
The license key What the user entered
The device fingerprint Re-derived from the device on every launch (see Storage)
Your product's slug The product the app is, fixed at build time
Your organization's Ed25519 public key(s), by kid Shipped in the app (see Trust only your own keys)

Test vectors generated by the LicenseSeat engine are at /machine-file-test-vectors.json; see Test vectors. A working reference verifier in Python is at the end of this page.

1. Armor

The certificate is text:

-----BEGIN MACHINE FILE-----
eyJlbmMiOiJzaENoeDdCSzZJRzQzTTlMMGtxMVFZYkVjZkphR3lKb0hWelIxM2ds
...
-----END MACHINE FILE-----
  • Trim surrounding whitespace, split into lines, and trim each line.
  • The first line must be exactly -----BEGIN MACHINE FILE----- and the last exactly -----END MACHINE FILE-----, with at least one line between.
  • Every inner line is 1–64 characters (the server wraps at 64 and rejects longer lines).
  • Join the inner lines with nothing between them. The result is standard Base64 with padding (A–Z a–z 0–9 + /, =), not base64url. The server wraps it at 64 characters per line.
  • Decoding yields UTF-8 JSON: the envelope.

The server rejects a certificate over 1 MiB, a decoded envelope over 768 KiB, a ciphertext over 512 KiB, and JSON nested deeper than 20 levels; enforce the same bounds before parsing, so an unsigned file cannot make your verifier allocate or recurse without limit. It also rejects, before any cryptography, a license key that is empty, longer than 512 bytes or contains control characters, and a fingerprint shorter than 8 or longer than 255 bytes or containing control characters (VERIFICATION_FAILED).

2. Envelope

{"enc":"<ciphertext>.<nonce>.<tag>","sig":"<signature>","alg":"aes-256-gcm+ed25519","kid":"<key id>"}
Member Type Meaning
enc string Three base64url segments joined with .: ciphertext.nonce.tag
sig string base64url Ed25519 signature, 64 bytes decoded
alg string Always aes-256-gcm+ed25519 for this format. Reject anything else.
kid string Signing key ID, 1–255 bytes matching ^[A-Za-z0-9][A-Za-z0-9._:-]*$. Selects the public key.

The envelope has exactly these four members. Reject an envelope with any other member, and reject duplicate member names. Member order is not significant.

base64url here means without padding. enc's three segments and sig are RFC 4648 §5 base64url with the trailing = removed. Most standard-library decoders reject that input until you pad it back to a multiple of 4 (s + "=" * (-len(s) % 4)). A decoder error at this step is a padding problem, not a sign you have the wrong algorithm. The server always emits the canonical unpadded spelling; a verifier may (and the reference below does) reject any other spelling of the same bytes, so a certificate has exactly one accepted form.

3. Verify the signature first

Verify before you decrypt, exactly as the server does, so a forged file never reaches the decryption code.

  • Message: the ASCII bytes of the string "machine/" followed by enc exactly as it appears in the envelope. Do not decode, re-encode, or canonicalize enc. The machine/ prefix is part of the signed message; leaving it out is the most common reason an otherwise correct implementation fails here.
  • Algorithm: Ed25519 (RFC 8032, pure Ed25519, not Ed25519ph), the 64-byte signature from sig, and the 32-byte public key for kid.
  • An unknown kid, a key that is not 32 bytes, a signature that is not 64 bytes, or a failed verification are all VERIFICATION_FAILED.

Trust only your own keys

Verify with a public key you already trust, chosen by kid from a list you ship in your app. Never fetch whatever kid a certificate names and trust the answer: GET /api/v1/signing_keys/{kid} resolves any LicenseSeat organization's key without authentication, so a verifier that does that accepts machine files signed for someone else's organization.

Get your key once, at build time: call GET /api/v1/signing_keys/{kid} with the kid from one of your own machine files. Its public_key field is standard padded Base64 of the raw 32-byte key. On licenseseat.com, rotation always issues a new kid and never changes the bytes behind an existing one, so ship the new kid/key pair alongside the old one before you rotate. (A self-hosted license_seat engine serves whatever its configured key resolver returns; its operator must keep the same rule.)

4. Derive the key and decrypt

key = SHA-256( UTF-8(license_key) || UTF-8(fingerprint) )

Plain SHA-256 over the two strings concatenated, with no separator, salt, HMAC, or KDF. The result is the 32-byte AES-256 key. license_key is the key exactly as issued (case and dashes included); fingerprint is exactly the string the device was activated with.

Then decrypt with AES-256-GCM:

Parameter Value
Ciphertext base64url-decode enc segment 1
Nonce (IV) base64url-decode segment 2: 12 bytes
Tag base64url-decode segment 3: 16 bytes
Associated data empty

Libraries that take "ciphertext with tag appended" (Python cryptography, WebCrypto, Go crypto/cipher) want ciphertext || tag. A tag failure means the license key or fingerprint is wrong, or the data is corrupt: DECRYPTION_FAILED. A wrong fingerprint is indistinguishable from a wrong license key at this step, by design.

The plaintext is a UTF-8 JSON object, the payload. The server writes it with keys sorted, but nothing is signed over the plaintext, so do not depend on member order or formatting. Reject duplicate member names.

5. Payload

{
  "meta": { ... },
  "data": { "type": "machines", ... },
  "included": [ { "type": "licenses", ... } ]
}

meta

Field Type Meaning
schema_version integer 2. Reject any other value.
iat integer Issued at, Unix seconds
nbf integer Not before, Unix seconds. Currently equal to iat.
exp integer Expiry, Unix seconds
ttl integer Lifetime in seconds, 1 to 3,162,240,000 (100 × 366 days). Always exp - iat; whole days on issue.
grace_period integer Seconds the file stays valid after exp (0–2,592,000)
issued string The instant iat as ISO 8601 with an offset (Z on licenseseat.com)
expiry string The instant exp as ISO 8601 with an offset
lic string The license key this file was issued for
license_exp integer or null When the license itself ends (Unix seconds), or null for a license that never ends. Treat a missing field as null.
kid string Same as the envelope kid
sdk_version string or null The requesting SDK, informational

data (the machine)

type is "machines". id is the activation's ID. attributes.fingerprint (a non-empty string) is the fingerprint the file is bound to; attributes also carries name, platform, created, metadata and fingerprint_components as recorded at activation. relationships.license.data is { "type": "licenses", "id": "<license key>" } and relationships.product.data is { "type": "products", "id": "<product slug>" }.

included

An array (a missing included means []): either empty or one license resource { "type": "licenses", "id": "<license key>", "attributes": { ... } } with key, status, mode, seat_limit, plan_key, product_slug, starts_at, ends_at, entitlements (array of { key, expires_at }, expires_at an ISO 8601 string or null) and metadata. ends_at is null or an ISO 8601 timestamp with an offset. It is present unless the machine file was requested without license data.

The shape of a payload is fixed for a given schema_version: LicenseSeat does not add fields to it without bumping schema_version. Ignoring unknown fields and rejecting them are both conforming. Checking that issued and expiry denote exactly iat and exp is also conforming; the Swift SDK does.

6. Checks after decryption

Run these in order; the first failure decides the result. The order only decides which code a file that breaks several rules reports, never whether it is valid. Every published test vector breaks exactly one rule.

Structure and binding (VERIFICATION_FAILED if any fails):

  1. schema_version is 2, and meta.kid equals the envelope kid.
  2. meta.lic equals the license key you decrypted with (compare in constant time).
  3. iat, nbf, exp, ttl and grace_period are integers, license_exp is an integer or null.
  4. 0 < ttl ≤ 3162240000, 0 ≤ grace_period ≤ 2592000, exp − iat = ttl, and iat ≤ nbf < exp. The window must have positive width: a file with nbf = exp is malformed, never "valid for an instant".
  5. data.type is "machines", data.attributes.fingerprint is a non-empty string, and data.relationships.license.data is { "type": "licenses", "id": <license key> }.
  6. included is an array, and if it has a license resource, its id and attributes.key equal the license key.

Product (PRODUCT_MISMATCH if it fails): data.relationships.product.data is { "type": "products", "id": <your product slug> }, and if included has a license resource, its attributes.product_slug is your product slug. One organization key signs every product of that organization, so without this check a file for a cheap product verifies in an expensive one. The server cannot check this for you: it is a property of the app doing the verifying.

Time, with now in Unix seconds:

Check Fails with
nbf > now + 300 TOKEN_NOT_YET_VALID
now ≥ exp + grace_period TOKEN_EXPIRED
license_exp is not null and now ≥ license_exp LICENSE_EXPIRED
the included license's ends_at is not null and is not a valid timestamp VERIFICATION_FAILED
the included license's ends_at is not null and ends_at ≤ now LICENSE_EXPIRED

Put together, a file is valid for now in the half-open window [nbf − 300, exp + grace_period), and never at or after license_exp. The 300 seconds of clock tolerance apply to nbf only, never to expiry. Every boundary is pinned by a test vector.

Device (defense in depth; a different fingerprint already failed decryption):

Check Fails with
data.attributes.fingerprint ≠ your fingerprint (constant time) FINGERPRINT_MISMATCH

If everything passes, the file is valid: the license is entitled on this device until the earliest of exp + grace_period, license_exp and the included license's ends_at.

Entitlements expire on their own. included[0].attributes.entitlements is the list that was active when the file was issued. Each entry grants only while its expires_at is null or later than now, so check it every time you authorize a feature: an entitlement that ends on day 2 of a 30-day file must stop working on day 2. Every authorization must also re-check the file's and the license's deadlines above, since an app can keep running past them. The reference's active_entitlements does all of this on each call.

Stricter verifiers, and the Swift SDK

The checks above are what the server's own verifier enforces, and what the test vectors expect. A verifier may reject more than this (never less) and may report its own error codes. LicenseSeat's Swift SDK does both, so on the same file it can disagree with this page:

  • It checks the device fingerprint before the clock, and reports a future iat (beyond its clock skew) as clock_tamper rather than TOKEN_NOT_YET_VALID.
  • It requires the included license's status to be active and its starts_at to be at or before now, with no clock tolerance, reported as included_license_mismatch. Because a file's license starts at iat, the Swift SDK rejects the valid-at-nbf-minus-clock-tolerance vector, which this page and the server accept.
  • It rejects more than one included license, non-string fingerprint_components values, oversized text fields (an enc longer than 64 KiB), and non-canonical Base64.
  • Its codes are lowercase and SDK-specific (fingerprint_mismatch, product_mismatch, token_expired, …).

Files LicenseSeat issues satisfy all of these, so the difference only shows on crafted files or at the edge of the clock tolerance.

Result codes

Code Meaning
VERIFICATION_FAILED Bad armor or envelope, unknown kid, bad signature, or inconsistent signed claims. The file is not genuine or not well-formed.
DECRYPTION_FAILED Wrong license key or fingerprint for this file, or corrupted data
PRODUCT_MISMATCH The file was issued for another product. Checked by the app; the server's own verifier has no product input.
TOKEN_NOT_YET_VALID nbf is more than 300 seconds in the future (check the device clock)
TOKEN_EXPIRED Past exp + grace_period: go online and fetch a new machine file
LICENSE_EXPIRED The license itself has ended
FINGERPRINT_MISMATCH The file was issued for a different device

What to store on the device

  1. Once, online: activate the device (POST …/licenses/activate with the fingerprint) and then fetch its machine file (POST …/licenses/{key}/machine-file with the same fingerprint). The seat is consumed by activation; the machine file is a signed copy of that state.
  2. Store: the certificate and the license key. Your public key(s) ship with the app.
  3. Never store the fingerprint next to them. Re-derive it on every launch, from the device itself or from storage the OS will not copy to another machine: a Keychain item with kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly (what the Swift SDK uses), DPAPI with machine scope, a TPM-backed key. A plain file is not enough, whoever owns it: a fingerprint that can be read and copied travels with the certificate, which turns device binding off.
  4. Every launch: verify as above with the current time. Every time you authorize a feature: check again with the current time, because a running app can outlive the file, the license or an entitlement; the reference's active_entitlements(payload, now) re-checks all three deadlines and grants nothing once any has passed. Before exp, refresh the machine file whenever the device is online, so a user who goes offline always has a full window ahead.

A machine file reflects the license at the moment it was issued. While offline, revocations, suspensions, plan changes and entitlement changes are not visible until the next refresh; that is the trade-off of offline licensing, bounded by the file's lifetime.

Test vectors

/machine-file-test-vectors.json is generated by the LicenseSeat engine and replayed by its test suite, so it matches what the server issues and how the server verifies.

  • signing_key: the kid, the Ed25519 public key (Base64), and the seed of a test-only private key. The seed is published on purpose so you can craft your own negative cases. Never put that kid or key in a shipped app: anyone can sign with it.
  • walkthrough: every intermediate value for one valid file, in order: the decoded envelope JSON, the exact signed message (machine/…), the signature, the derived AES key, the ciphertext, nonce and tag, and the decrypted plaintext. When your verifier disagrees, compare step by step to find where.
  • cases: each has a certificate, license_key, fingerprint, the app's product_slug, a Unix time now, and the expected result, VALID or one of the codes above. They cover a valid file; both sides of the 300-second nbf tolerance, of exp + grace_period and of license_exp; an expired included ends_at; a wrong fingerprint, license key and product; a flipped ciphertext byte; and validly signed files that break each structural rule in §6 (kid, license and product binding, schema, window consistency and limits, types, envelope members, alg, a zero-width window, an embedded fingerprint that differs from the one the file is encrypted to).

Passing every case is necessary, not sufficient: it is the fastest way to find a mistake, and the steps above are the definition.

Reference verifier (Python)

The only dependency is cryptography. This exact code passes every test vector above.

"""Reference verifier for LicenseSeat offline machine files (schema_version 2).

Only dependency: `cryptography` (pip install cryptography).
"""
import base64, binascii, hashlib, hmac, json, re, time
from datetime import datetime

from cryptography.exceptions import InvalidSignature, InvalidTag
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

ALG = "aes-256-gcm+ed25519"
CLOCK_TOLERANCE = 300                # seconds, applied to nbf only
MAX_TTL = 100 * 366 * 86400          # seconds
MAX_GRACE = 30 * 86400               # seconds
MAX_CERTIFICATE = 1024 * 1024        # bytes
MAX_ENVELOPE = 768 * 1024            # bytes, decoded armor
MAX_CIPHERTEXT = 512 * 1024          # bytes
MAX_DEPTH = 20                       # JSON nesting
KID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,254}")
CONTROL = re.compile(r"[\x00-\x1f\x7f]")


class MachineFileError(Exception):
    def __init__(self, code, message):
        super().__init__(f"{code}: {message}")
        self.code = code


def _b64url(text):
    # Unpadded base64url, and only its canonical spelling (no padding, no
    # stray low bits), so one byte string has exactly one accepted encoding.
    if not isinstance(text, str) or not re.fullmatch(r"[A-Za-z0-9_-]+", text):
        raise ValueError("not base64url")
    raw = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
    if base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") != text:
        raise ValueError("non-canonical base64url")
    return raw


def _reject(_):
    raise ValueError("NaN and Infinity are not JSON")


def _no_duplicates(pairs):
    if len({k for k, _ in pairs}) != len(pairs):
        raise ValueError("duplicate JSON key")
    return dict(pairs)


def _json(raw):
    # Strict UTF-8 JSON with bounded nesting; any problem is a ValueError.
    try:
        value = json.loads(raw.decode("utf-8"), object_pairs_hook=_no_duplicates, parse_constant=_reject)
    except (UnicodeDecodeError, RecursionError) as error:
        raise ValueError("invalid JSON") from error
    stack = [(value, 1)]
    while stack:
        node, depth = stack.pop()
        if depth > MAX_DEPTH:
            raise ValueError("JSON nested too deeply")
        children = node.values() if isinstance(node, dict) else node if isinstance(node, list) else ()
        stack.extend((child, depth + 1) for child in children)
    return value


def _is_int(v):
    return isinstance(v, int) and not isinstance(v, bool)


def _same(a, b):
    # Constant-time string equality; works for any Unicode text.
    return isinstance(a, str) and isinstance(b, str) and hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))


def _get(obj, *path):
    for key in path:
        obj = obj.get(key) if isinstance(obj, dict) else None
    return obj


def _timestamp(text):
    # ISO 8601 with an explicit offset, as the server writes it.
    if not isinstance(text, str):
        raise ValueError
    value = datetime.fromisoformat(text.replace("Z", "+00:00"))
    if value.tzinfo is None:
        raise ValueError
    return value.timestamp()


def verify_machine_file(certificate, license_key, fingerprint, product_slug, trusted_keys, now=None):
    """Verify a machine file for THIS app.

    trusted_keys: {kid: 32-byte Ed25519 public key} for your organization only.
    Returns the decrypted payload dict, or raises MachineFileError(code).
    """
    now = int(time.time()) if now is None else int(now)

    def fail(code, message):
        return MachineFileError(code, message)

    # 0. Inputs: the same bounds the server enforces.
    if not (isinstance(license_key, str) and 1 <= len(license_key.encode("utf-8")) <= 512 and not CONTROL.search(license_key)):
        raise fail("VERIFICATION_FAILED", "invalid license key")
    if not (isinstance(fingerprint, str) and 8 <= len(fingerprint.encode("utf-8")) <= 255 and not CONTROL.search(fingerprint)):
        raise fail("VERIFICATION_FAILED", "invalid fingerprint")
    if not isinstance(certificate, str) or len(certificate.encode("utf-8")) > MAX_CERTIFICATE:
        raise fail("VERIFICATION_FAILED", "invalid certificate")

    # 1. Armor: PEM-style lines around standard (padded) base64 of a JSON envelope.
    lines = [line.strip() for line in certificate.strip().splitlines()]
    body = lines[1:-1]
    if (len(lines) < 3 or lines[0] != "-----BEGIN MACHINE FILE-----" or lines[-1] != "-----END MACHINE FILE-----"
            or not all(1 <= len(line) <= 64 for line in body)):
        raise fail("VERIFICATION_FAILED", "invalid armor")
    try:
        decoded = base64.b64decode("".join(body), validate=True)
        if len(decoded) > MAX_ENVELOPE:
            raise ValueError
        envelope = _json(decoded)
    except (ValueError, binascii.Error):
        raise fail("VERIFICATION_FAILED", "invalid envelope")
    if not isinstance(envelope, dict) or set(envelope) != {"enc", "sig", "alg", "kid"}:
        raise fail("VERIFICATION_FAILED", "envelope must have exactly enc, sig, alg, kid")
    enc, sig, alg, kid = (envelope[k] for k in ("enc", "sig", "alg", "kid"))
    if alg != ALG or not all(isinstance(v, str) and v for v in (enc, sig, kid)) or not KID.fullmatch(kid):
        raise fail("VERIFICATION_FAILED", "invalid envelope fields")

    # 2. Signature FIRST: Ed25519 over the ASCII bytes of "machine/" + enc,
    #    with a key you already trust. Never trust a kid just because the file names it.
    public_key = trusted_keys.get(kid)
    if not isinstance(public_key, bytes) or len(public_key) != 32:
        raise fail("VERIFICATION_FAILED", "unknown kid")
    try:
        signature = _b64url(sig)
        if len(signature) != 64:
            raise ValueError
        Ed25519PublicKey.from_public_bytes(public_key).verify(signature, b"machine/" + enc.encode("ascii"))
    except (InvalidSignature, ValueError, UnicodeEncodeError):
        raise fail("VERIFICATION_FAILED", "bad signature")

    # 3. Key = SHA-256(license_key || fingerprint): raw UTF-8 concatenation, no separator.
    key = hashlib.sha256(license_key.encode("utf-8") + fingerprint.encode("utf-8")).digest()

    # 4. AES-256-GCM, 12-byte nonce, 16-byte tag, EMPTY associated data.
    try:
        parts = enc.split(".")
        if len(parts) != 3:
            raise ValueError
        ciphertext, nonce, tag = (_b64url(p) for p in parts)
        if len(nonce) != 12 or len(tag) != 16 or len(ciphertext) > MAX_CIPHERTEXT:
            raise ValueError
        payload = _json(AESGCM(key).decrypt(nonce, ciphertext + tag, b""))
        if not isinstance(payload, dict):
            raise ValueError
    except (InvalidTag, ValueError):
        raise fail("DECRYPTION_FAILED", "wrong license key or fingerprint, or corrupted data")

    # 5. Structure: the signed claims must be self-consistent and bound to this license.
    meta, data = payload.get("meta"), payload.get("data")
    included = payload.get("included", [])
    if not isinstance(meta, dict) or not isinstance(data, dict) or not isinstance(included, list):
        raise fail("VERIFICATION_FAILED", "missing meta or data, or included is not an array")
    if (not _is_int(meta.get("schema_version")) or meta["schema_version"] != 2
            or not _same(meta.get("kid"), kid) or not _same(meta.get("lic"), license_key)):
        raise fail("VERIFICATION_FAILED", "unsupported schema, or kid/license mismatch")
    iat, nbf, exp, ttl, grace = (meta.get(k) for k in ("iat", "nbf", "exp", "ttl", "grace_period"))
    license_exp = meta.get("license_exp")
    if not all(_is_int(v) for v in (iat, nbf, exp, ttl, grace)) or not (license_exp is None or _is_int(license_exp)):
        raise fail("VERIFICATION_FAILED", "time claims must be integers")
    if not (0 < ttl <= MAX_TTL and 0 <= grace <= MAX_GRACE and exp - iat == ttl and iat <= nbf < exp):
        raise fail("VERIFICATION_FAILED", "inconsistent time claims")
    embedded_fingerprint = _get(data, "attributes", "fingerprint")
    if (data.get("type") != "machines" or not isinstance(embedded_fingerprint, str) or not embedded_fingerprint
            or _get(data, "relationships", "license", "data", "type") != "licenses"
            or not _same(_get(data, "relationships", "license", "data", "id"), license_key)):
        raise fail("VERIFICATION_FAILED", "machine data does not match")
    licenses = [e for e in included if isinstance(e, dict) and e.get("type") == "licenses"]
    license = licenses[0] if licenses else None
    if len(licenses) > 1 or (license is not None and not (
            _same(license.get("id"), license_key) and _same(_get(license, "attributes", "key"), license_key))):
        raise fail("VERIFICATION_FAILED", "included license does not match")

    # 6. Product: the file must be for THIS app (same organization key signs all its products).
    if (_get(data, "relationships", "product", "data", "type") != "products"
            or not _same(_get(data, "relationships", "product", "data", "id"), product_slug)
            or (license is not None and not _same(_get(license, "attributes", "product_slug"), product_slug))):
        raise fail("PRODUCT_MISMATCH", "issued for a different product")

    # 7. Clock: valid in [nbf - 300, exp + grace_period), and never at/after the license's end.
    if nbf > now + CLOCK_TOLERANCE:
        raise fail("TOKEN_NOT_YET_VALID", "not yet valid")
    if now >= exp + grace:
        raise fail("TOKEN_EXPIRED", "expired")
    if license_exp is not None and now >= license_exp:
        raise fail("LICENSE_EXPIRED", "license expired")
    ends_at = _get(license, "attributes", "ends_at")
    if ends_at is not None:
        try:
            ends = _timestamp(ends_at)
        except (ValueError, OverflowError):
            raise fail("VERIFICATION_FAILED", "invalid ends_at")
        if ends <= now:
            raise fail("LICENSE_EXPIRED", "license expired")

    # 8. Device binding (defense in depth; a different fingerprint already failed step 4).
    if not _same(embedded_fingerprint, fingerprint):
        raise fail("FINGERPRINT_MISMATCH", "issued for a different device")

    return payload


def active_entitlements(payload, now=None):
    """Entitlement keys a VERIFIED payload grants at `now`. Call it on every use.

    Grants nothing once any deadline has passed: the file's (`exp` plus
    `grace_period`), the license's (`license_exp`, the included `ends_at`), or
    the entitlement's own `expires_at`. The entitlement list is the one active
    when the file was issued, so an entry can end while the file is still valid.
    """
    now = int(time.time()) if now is None else int(now)
    meta = payload.get("meta") or {}
    exp, grace, license_exp = meta.get("exp"), meta.get("grace_period"), meta.get("license_exp")
    if not (_is_int(exp) and _is_int(grace)) or now >= exp + grace:
        return set()
    if license_exp is not None and (not _is_int(license_exp) or now >= license_exp):
        return set()
    license = next((e for e in payload.get("included") or [] if isinstance(e, dict) and e.get("type") == "licenses"), None)
    granted = set()
    try:
        ends_at = _get(license, "attributes", "ends_at")
        if ends_at is not None and _timestamp(ends_at) <= now:
            return set()
    except (ValueError, OverflowError):
        return set()
    for entitlement in _get(license, "attributes", "entitlements") or []:
        expires_at = entitlement.get("expires_at") if isinstance(entitlement, dict) else None
        try:
            if expires_at is None or _timestamp(expires_at) > now:
                granted.add(entitlement["key"])
        except (ValueError, OverflowError, KeyError, TypeError):
            continue  # malformed entitlement: grants nothing
    return granted

Usage, with your organization's public key shipped in the app:

import base64

# From GET /api/v1/signing_keys/{kid} for YOUR kid, copied in at build time.
TRUSTED_KEYS = {"org-xxx-offline-v1": base64.b64decode("…public_key…")}

payload = verify_machine_file(
    certificate=open("machine-file.lic").read(),
    license_key=stored_license_key,
    fingerprint=fingerprint_of_this_device(),
    product_slug="my-app",
    trusted_keys=TRUSTED_KEYS,
)
if "pro" in active_entitlements(payload):   # re-check on every use, not once per launch
    enable_pro_features()

Two things the reference leaves to you, because they are policy rather than format: protecting against the user winding the system clock back (remember the latest time you have seen and refuse to go backwards), and an optional maximum offline age shorter than the file allows. A verifier may always be stricter than the signed deadlines, never more lenient: nothing may grant past exp + grace_period, license_exp, the included ends_at, or an entitlement's expires_at.