DevEntitle

Client code

Ready-made licence clients to copy into your product. Each one activates and deactivates a licence, checks for updates, and downloads an update only after checking its SHA-256 and Ed25519 signature.

They all follow the same rules: send only the four protocol fields, treat only network failures and 5xx answers as "server unreachable", and never switch product features off. Set your server URL (https://terminal.deventitle.com), your product slug and your release public key.

PHP (no framework)

<?php

/**
 * DevEntitle licence client for PHP (no framework). Copy into your product.
 *
 *   $client = new DevEntitleClient('https://terminal.deventitle.com', 'acme-crm', ACME_RELEASE_PUBLIC_KEY);
 *   $result = $client->activate($key, 'crm.buyer.com', '1.4.2');      // ['valid' => true, 'message' => …]
 *   $latest = $client->checkForUpdate($key, 'crm.buyer.com', '1.4.2'); // null when up to date
 *   if ($latest && isset($latest['download_url'])) {
 *       $client->downloadVerified($latest, '/tmp/acme-crm-'.$latest['version'].'.zip');
 *   }
 *
 * Rules: never switch features off because of a licence answer or because
 * the server can't be reached. Show the message; hold back updates only.
 * Sends only the licence key, product, domain and version.
 *
 * Needs PHP 7.4+ with curl and sodium. Licence: MIT.
 */
final class DevEntitleClient
{
    /** @var string */
    private $server;

    /** @var string */
    private $product;

    /** @var string|null base64 Ed25519 public key, built into your product */
    private $publicKey;

    public function __construct(string $server, string $product, ?string $publicKey = null)
    {
        $this->server = rtrim($server, '/');
        $this->product = $product;
        $this->publicKey = $publicKey;
    }

    /** @return array{valid: bool, message: string, buyer?: string, license_type?: string, supported_until?: ?string} */
    public function activate(string $licenseKey, string $domain, string $version): array
    {
        return $this->post('activate', $licenseKey, $domain, $version);
    }

    /** Free this domain so the key can be used elsewhere. */
    public function deactivate(string $licenseKey, string $domain, string $version): void
    {
        $this->post('deactivate', $licenseKey, $domain, $version);
    }

    /**
     * The newest release offered to this licence when it is newer than
     * $version, else null. Check $latest['download_url']: when it is missing,
     * show $latest['message'] (e.g. support ended) instead of an install button.
     */
    public function checkForUpdate(string $licenseKey, string $domain, string $version): ?array
    {
        $result = $this->post('updates', $licenseKey, $domain, $version);
        $latest = $result['latest'] ?? null;

        return is_array($latest) && version_compare((string) ($latest['version'] ?? '0'), $version, '>') ? $latest : null;
    }

    /**
     * Download a release and check its SHA-256 and Ed25519 signature before
     * returning. Throws (and deletes the file) if anything doesn't match.
     */
    public function downloadVerified(array $latest, string $targetPath): void
    {
        if (empty($latest['download_url']) || empty($latest['signature'])) {
            throw new RuntimeException($latest['message'] ?? 'This licence may not download this release.');
        }
        if (! $this->publicKey) {
            throw new RuntimeException('No release public key is configured, so the download can\'t be checked.');
        }

        $file = fopen($targetPath, 'wb');
        $curl = curl_init($latest['download_url']);
        curl_setopt_array($curl, [CURLOPT_FILE => $file, CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => 600, CURLOPT_FAILONERROR => true]);
        $ok = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
        curl_close($curl);
        fclose($file);

        if (! $ok || $status !== 200) {
            @unlink($targetPath);
            throw new RuntimeException("The download failed (HTTP {$status}). Check for updates again to get a fresh link.");
        }

        $sha = hash_file('sha256', $targetPath);
        $signature = base64_decode((string) $latest['signature'], true);
        $public = base64_decode($this->publicKey, true);
        $message = $this->product.'|'.$latest['version'].'|'.$sha;

        // Length checks first: sodium throws on a malformed signature or key instead of returning false.
        if (! hash_equals(strtolower((string) $latest['sha256']), $sha)
            || $signature === false || strlen($signature) !== SODIUM_CRYPTO_SIGN_BYTES
            || $public === false || strlen($public) !== SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES
            || ! sodium_crypto_sign_verify_detached($signature, $message, $public)) {
            @unlink($targetPath);
            throw new RuntimeException('The download did not pass the integrity and signature check. Nothing was installed.');
        }
    }

    private function post(string $endpoint, string $licenseKey, string $domain, string $version): array
    {
        $curl = curl_init($this->server.'/api/v1/'.$endpoint);
        curl_setopt_array($curl, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode(['license_key' => $licenseKey, 'product' => $this->product, 'domain' => $domain, 'version' => $version]),
            CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Accept: application/json'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 20,
        ]);
        $body = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
        curl_close($curl);

        $data = is_string($body) ? json_decode($body, true) : null;

        // Licence answers are HTTP 200 (and 429 when checking too often); anything else is the server's problem.
        if (! is_array($data) || $status >= 500 || $status === 0) {
            throw new RuntimeException('The licence server could not be reached (HTTP '.$status.'). Try again later.');
        }

        return $data;
    }
}

Laravel

<?php

namespace App\Support;

use Illuminate\Support\Facades\Http;
use RuntimeException;

/**
 * DevEntitle licence client for Laravel. Copy to app/Support/DevEntitle.php.
 *
 * config/services.php:
 *   'deventitle' => [
 *       'server' => env('DEVENTITLE_SERVER', 'https://terminal.deventitle.com'),
 *       'product' => 'acme-crm',
 *       'public_key' => env('DEVENTITLE_RELEASE_PUBLIC_KEY'), // or hard-code it
 *   ],
 *
 *   $result = DevEntitle::activate($key);           // ['valid' => true, 'message' => …]
 *   $latest = DevEntitle::checkForUpdate($key);     // null when up to date
 *   DevEntitle::downloadVerified($latest, storage_path('app/update.zip'));
 *
 * Never switch features off because of a licence answer or an unreachable
 * server. Sends only the licence key, product, domain and version.
 */
class DevEntitle
{
    public static function domain(): string
    {
        return strtolower((string) parse_url((string) config('app.url'), PHP_URL_HOST)) ?: 'localhost';
    }

    public static function activate(string $licenseKey, ?string $version = null): array
    {
        return static::post('activate', $licenseKey, $version);
    }

    public static function deactivate(string $licenseKey, ?string $version = null): void
    {
        static::post('deactivate', $licenseKey, $version);
    }

    /** The newest offered release when newer than $version (default: your app's version), else null. */
    public static function checkForUpdate(string $licenseKey, ?string $version = null): ?array
    {
        $version ??= (string) config('app.version', '0.0.0');
        $latest = static::post('updates', $licenseKey, $version)['latest'] ?? null;

        return is_array($latest) && version_compare($latest['version'] ?? '0', $version, '>') ? $latest : null;
    }

    /** Download and check SHA-256 + Ed25519 signature; throws and deletes the file on any mismatch. */
    public static function downloadVerified(array $latest, string $targetPath): void
    {
        if (empty($latest['download_url']) || empty($latest['signature'])) {
            throw new RuntimeException($latest['message'] ?? 'This licence may not download this release.');
        }

        $response = Http::timeout(600)->withoutRedirecting()->sink($targetPath)->get($latest['download_url']);
        if (! $response->successful()) {
            @unlink($targetPath);
            throw new RuntimeException('The download failed (HTTP '.$response->status().'). Check for updates again to get a fresh link.');
        }

        $sha = hash_file('sha256', $targetPath);
        $signature = base64_decode((string) $latest['signature'], true);
        $public = base64_decode((string) config('services.deventitle.public_key'), true);
        $message = config('services.deventitle.product').'|'.$latest['version'].'|'.$sha;

        // Length checks first: sodium throws on a malformed signature or key instead of returning false.
        if (! hash_equals(strtolower($latest['sha256']), $sha)
            || ! $signature || strlen($signature) !== SODIUM_CRYPTO_SIGN_BYTES
            || ! $public || strlen($public) !== SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES
            || ! sodium_crypto_sign_verify_detached($signature, $message, $public)) {
            @unlink($targetPath);
            throw new RuntimeException('The download did not pass the integrity and signature check. Nothing was installed.');
        }
    }

    protected static function post(string $endpoint, string $licenseKey, ?string $version): array
    {
        $response = Http::acceptJson()->timeout(20)->post(rtrim((string) config('services.deventitle.server'), '/').'/api/v1/'.$endpoint, [
            'license_key' => $licenseKey,
            'product' => config('services.deventitle.product'),
            'domain' => static::domain(),
            'version' => $version ?? (string) config('app.version', '0.0.0'),
        ]);

        if ($response->serverError() || ! is_array($response->json())) {
            throw new RuntimeException('The licence server could not be reached (HTTP '.$response->status().'). Try again later.');
        }

        return $response->json();
    }
}

Node.js

/**
 * DevEntitle licence client for Node.js 18+ (no packages). Copy into your product.
 *
 *   import { DevEntitleClient } from './deventitle-client.mjs';
 *   const client = new DevEntitleClient({ server: 'https://terminal.deventitle.com', product: 'acme-crm', publicKey: ACME_RELEASE_PUBLIC_KEY });
 *   const result = await client.activate(key, 'crm.buyer.com', '1.4.2');      // { valid: true, message: … }
 *   const latest = await client.checkForUpdate(key, 'crm.buyer.com', '1.4.2'); // null when up to date
 *   if (latest?.download_url) await client.downloadVerified(latest, `/tmp/acme-crm-${latest.version}.zip`);
 *
 * Never switch features off because of a licence answer or an unreachable
 * server. Sends only the licence key, product, domain and version. Licence: MIT.
 */

import { createHash, createPublicKey, verify } from 'node:crypto';
import { writeFile } from 'node:fs/promises';

export class DevEntitleClient {
    constructor({ server, product, publicKey = null }) {
        this.server = server.replace(/\/+$/, '');
        this.product = product;
        this.publicKey = publicKey;
    }

    activate(licenseKey, domain, version) {
        return this.#post('activate', licenseKey, domain, version);
    }

    async deactivate(licenseKey, domain, version) {
        await this.#post('deactivate', licenseKey, domain, version);
    }

    /** The newest offered release when newer than `version`, else null. Without `download_url`, show `message`. */
    async checkForUpdate(licenseKey, domain, version) {
        const { latest } = await this.#post('updates', licenseKey, domain, version);
        return latest && compareVersions(latest.version, version) > 0 ? latest : null;
    }

    /** Download and check SHA-256 + Ed25519 signature; throws (and deletes the file) on any mismatch. */
    async downloadVerified(latest, targetPath) {
        if (!latest?.download_url || !latest?.signature) throw new Error(latest?.message ?? 'This licence may not download this release.');
        if (!this.publicKey) throw new Error("No release public key is configured, so the download can't be checked.");

        const response = await fetch(latest.download_url, { redirect: 'error' });
        if (response.status !== 200) throw new Error(`The download failed (HTTP ${response.status}). Check for updates again to get a fresh link.`);

        const body = Buffer.from(await response.arrayBuffer());
        const sha = createHash('sha256').update(body).digest('hex');
        const key = createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: Buffer.from(this.publicKey, 'base64').toString('base64url') }, format: 'jwk' });
        const ok = sha === String(latest.sha256).toLowerCase()
            && verify(null, Buffer.from(`${this.product}|${latest.version}|${sha}`), key, Buffer.from(latest.signature, 'base64'));

        if (!ok) throw new Error('The download did not pass the integrity and signature check. Nothing was installed.');
        await writeFile(targetPath, body);
    }

    async #post(endpoint, licenseKey, domain, version) {
        let response;
        try {
            response = await fetch(`${this.server}/api/v1/${endpoint}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
                body: JSON.stringify({ license_key: licenseKey, product: this.product, domain, version }),
                signal: AbortSignal.timeout(20000),
            });
        } catch {
            throw new Error('The licence server could not be reached. Try again later.');
        }
        const data = await response.json().catch(() => null);
        if (response.status >= 500 || !data) throw new Error(`The licence server could not be reached (HTTP ${response.status}). Try again later.`);
        return data;
    }
}

/** 1.10.0 > 1.9.0; a pre-release (1.0.0-beta.1) is older than its release. */
export function compareVersions(a, b) {
    const [mainA, preA] = String(a).split('-', 2);
    const [mainB, preB] = String(b).split('-', 2);
    const partsA = mainA.split('.').map(Number);
    const partsB = mainB.split('.').map(Number);
    for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
        const diff = (partsA[i] ?? 0) - (partsB[i] ?? 0);
        if (diff !== 0) return Math.sign(diff);
    }
    if (preA === preB) return 0;
    if (!preA) return 1;
    if (!preB) return -1;
    return preA.localeCompare(preB, 'en', { numeric: true });
}

Python

"""
DevEntitle licence client for Python 3.8+. Copy into your product.

    client = DevEntitleClient("https://terminal.deventitle.com", "acme-crm", ACME_RELEASE_PUBLIC_KEY)
    result = client.activate(key, "crm.buyer.com", "1.4.2")        # {"valid": True, "message": ...}
    latest = client.check_for_update(key, "crm.buyer.com", "1.4.2") # None when up to date
    if latest and latest.get("download_url"):
        client.download_verified(latest, "/tmp/acme-crm-%s.zip" % latest["version"])

Signature checks need PyNaCl (`pip install pynacl`) or `cryptography`.
Never switch features off because of a licence answer or an unreachable
server. Sends only the licence key, product, domain and version. Licence: MIT.
"""

import base64
import hashlib
import json
import os
import re
import urllib.error
import urllib.request


class DevEntitleError(Exception):
    pass


class DevEntitleClient:
    def __init__(self, server, product, public_key=None):
        self.server = server.rstrip("/")
        self.product = product
        self.public_key = public_key

    def activate(self, license_key, domain, version):
        return self._post("activate", license_key, domain, version)

    def deactivate(self, license_key, domain, version):
        self._post("deactivate", license_key, domain, version)

    def check_for_update(self, license_key, domain, version):
        """The newest offered release when newer than `version`, else None. Without download_url, show latest["message"]."""
        latest = self._post("updates", license_key, domain, version).get("latest")
        return latest if latest and compare_versions(latest["version"], version) > 0 else None

    def download_verified(self, latest, target_path):
        """Download and check SHA-256 + Ed25519 signature; raises (and writes nothing) on any mismatch."""
        if not latest.get("download_url") or not latest.get("signature"):
            raise DevEntitleError(latest.get("message") or "This licence may not download this release.")
        if not self.public_key:
            raise DevEntitleError("No release public key is configured, so the download can't be checked.")

        try:
            with urllib.request.urlopen(latest["download_url"], timeout=600) as response:
                body = response.read()
        except urllib.error.HTTPError as error:
            raise DevEntitleError("The download failed (HTTP %d). Check for updates again to get a fresh link." % error.code)

        sha = hashlib.sha256(body).hexdigest()
        message = ("%s|%s|%s" % (self.product, latest["version"], sha)).encode()
        if sha != str(latest["sha256"]).lower() or not _verify(self.public_key, latest["signature"], message):
            raise DevEntitleError("The download did not pass the integrity and signature check. Nothing was installed.")

        with open(target_path, "wb") as handle:
            handle.write(body)

    def _post(self, endpoint, license_key, domain, version):
        data = json.dumps({"license_key": license_key, "product": self.product, "domain": domain, "version": version}).encode()
        request = urllib.request.Request(
            "%s/api/v1/%s" % (self.server, endpoint),
            data=data,
            headers={"Content-Type": "application/json", "Accept": "application/json"},
            method="POST",
        )
        try:
            with urllib.request.urlopen(request, timeout=20) as response:
                return json.loads(response.read())
        except urllib.error.HTTPError as error:
            # 429 (too many checks) still carries a JSON message; 5xx means the server has a problem.
            if error.code < 500:
                try:
                    return json.loads(error.read())
                except ValueError:
                    pass
            raise DevEntitleError("The licence server could not be reached (HTTP %d). Try again later." % error.code)
        except (urllib.error.URLError, OSError, ValueError):
            raise DevEntitleError("The licence server could not be reached. Try again later.")


def _verify(public_key_b64, signature_b64, message):
    try:
        public = base64.b64decode(public_key_b64, validate=True)
        signature = base64.b64decode(signature_b64, validate=True)
    except (ValueError, TypeError):
        return False
    # A malformed signature or key is simply "not verified", never a crash.
    if len(public) != 32 or len(signature) != 64:
        return False
    try:
        from nacl.exceptions import BadSignatureError
        from nacl.signing import VerifyKey

        try:
            VerifyKey(public).verify(message, signature)
            return True
        except BadSignatureError:
            return False
    except ImportError:
        pass
    try:
        from cryptography.exceptions import InvalidSignature
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

        try:
            Ed25519PublicKey.from_public_bytes(public).verify(signature, message)
            return True
        except InvalidSignature:
            return False
    except ImportError:
        raise DevEntitleError("Install PyNaCl (pip install pynacl) or cryptography to check release signatures.")


def compare_versions(a, b):
    """1.10.0 > 1.9.0; a pre-release (1.0.0-beta.1) is older than its release."""
    main_a, _, pre_a = str(a).partition("-")
    main_b, _, pre_b = str(b).partition("-")
    parts_a = [int(p) for p in re.findall(r"\d+", main_a)]
    parts_b = [int(p) for p in re.findall(r"\d+", main_b)]
    length = max(len(parts_a), len(parts_b))
    parts_a += [0] * (length - len(parts_a))
    parts_b += [0] * (length - len(parts_b))
    if parts_a != parts_b:
        return 1 if parts_a > parts_b else -1
    if pre_a == pre_b:
        return 0
    if not pre_a:
        return 1
    if not pre_b:
        return -1
    return 1 if pre_a > pre_b else -1


if __name__ == "__main__" and os.environ.get("DEVENTITLE_SELFTEST"):
    assert compare_versions("1.10.0", "1.9.0") == 1
    assert compare_versions("1.0.0-beta.1", "1.0.0") == -1
    print("ok")

Calling the Management API

The Management API is plain REST with a Bearer token, so any HTTP client works; see the reference and openapi.json (which most languages can generate a client from). For example, issuing a licence from a PHP checkout:

$response = Http::withToken(env('DEVENTITLE_TOKEN'))
    ->withHeaders(['Idempotency-Key' => 'order-'.$order->id])
    ->post('https://terminal.deventitle.com/api/manage/v1/licenses', [
        'product' => 'acme-crm',
        'license_type_id' => 12,
        'customer' => ['email' => $order->email, 'name' => $order->name],
        'external_ref' => (string) $order->id,
        'send_email' => true,
    ]);

$key = $response->json('data.key'); // shown once: store it or show it to the buyer now