12345678, * 'purchase_code' => $code, * 'storage' => __DIR__ . '/storage/smc-license.json', * ]); * $smc->activate(); * if ($smc->isLicensed()) { ... } * $update = $smc->checkUpdate('1.2.0'); * if ($update->updateAvailable) { * $zip = $smc->downloadUpdate($update); * } * * Docs: https://sellmycode.net/api-docs/licence-sdk */ if (!class_exists('SellMyCodeLicenseException', false)) { class SellMyCodeLicenseException extends RuntimeException { /** @var string machine-readable reason, e.g. "checksum_mismatch" */ public $reason; /** @var SellMyCodeLicenseAnswer|null the signed answer behind the error, when there is one */ public $answer; public function __construct(string $reason, string $message, ?SellMyCodeLicenseAnswer $answer = null) { parent::__construct($message); $this->reason = $reason; $this->answer = $answer; } } } if (!class_exists('SellMyCodeLicenseAnswer', false)) { /** * One answer from the licence API. Only answers whose signature and nonce checked out * carry data; anything else is reported as offline (network down, bad signature). */ class SellMyCodeLicenseAnswer { /** @var bool the server answered "success" */ public $success = false; /** @var string answer code ("valid", "activated", "update_available", "invalid_code", …) or a client-side one ("offline", "untrusted_answer", "sodium_missing") */ public $code = 'offline'; /** @var string|null human-readable message of an error */ public $message; /** @var bool no trustworthy answer was received — the server could not be reached or the answer failed verification */ public $offline = true; /** @var int HTTP status, 0 when the server was not reached */ public $status = 0; /** @var array the decoded, verified payload */ public $data = []; /** @var bool checkUpdate(): a package newer than the running version can be downloaded */ public $updateAvailable = false; /** @var string|null */ public $latestVersion; /** @var array|null {download_url, expires_at, max_uses, sha256, size, integrity} */ public $package; /** @var array|null {version, body, released_at} */ public $changelog; /** @var string|null where the buyer renews once the update period has ended */ public $renewUrl; /** @var string|null activate/verify: a 24-hour JWT your own update server can check offline */ public $entitlement; public static function offline(string $code, string $message, int $status = 0): self { $a = new self(); $a->code = $code; $a->message = $message; $a->status = $status; return $a; } public static function fromPayload(array $data, int $status): self { $a = new self(); $a->offline = false; $a->status = $status; $a->data = $data; $a->success = ($data['status'] ?? '') === 'success'; $a->code = (string) ($data['code'] ?? ($a->success ? 'success' : 'error')); $a->message = isset($data['msg']) ? (string) $data['msg'] : null; $a->latestVersion = isset($data['latest_version']) ? (string) $data['latest_version'] : null; $a->package = isset($data['package']) && is_array($data['package']) ? $data['package'] : null; $a->changelog = isset($data['changelog']) && is_array($data['changelog']) ? $data['changelog'] : null; $a->renewUrl = $data['updates']['renew_url'] ?? null; $a->entitlement = isset($data['entitlement']) && is_string($data['entitlement']) ? $data['entitlement'] : null; $a->updateAvailable = $a->success && $a->package !== null && in_array($a->code, ['update_available', 'latest'], true); return $a; } /** read a payload field, with dots for nested keys: get('updates.until') */ public function get(string $key, $default = null) { $value = $this->data; foreach (explode('.', $key) as $part) { if (!is_array($value) || !array_key_exists($part, $value)) { return $default; } $value = $value[$part]; } return $value; } } } if (!class_exists('SellMyCodeLicense', false)) { class SellMyCodeLicense { const VERSION = '1.1.1'; const DEFAULT_API = 'https://sellmycode.net/api'; /** kid => base64 Ed25519 public key; filled in when the file is downloaded from SellMyCode */ const DEFAULT_KEYS = array('k1' => '5Uk3p1+J0PXzJkwS4wVFvTN9GcHpJzX5ClRI8zlI0yQ=', 'k2' => 'erOiojOdS5F/IfhPMO9gvjAvuEPVapIadTDaWU0z83o='); /** answers that mean "this site is licensed" */ const LICENSED = ['valid', 'activated', 'reactivated', 'already_activated']; /** answers that mean "we could not get a trustworthy answer" — the grace period applies */ const TRANSIENT = ['offline', 'untrusted_answer', 'rate_limited', 'signing_unavailable']; /** @var int */ private $itemId; /** @var string */ private $code; /** @var string */ private $domain; /** @var string */ private $api; /** @var array */ private $keys; /** @var string|array */ private $storage; /** @var int */ private $timeout; /** @var bool */ private $allowUnverified; /** @var callable|null */ private $transport; /** @var array|null */ private $state; /** @var array|null the raw envelope of the most recent signed answer, kept so storage can be re-verified */ private $lastEnvelope; /** * @param array $config * item_id (int, required) your item's ID on SellMyCode * purchase_code (string) the buyer's purchase code * storage (string|array, required) a JSON file path, or ['get' => fn(): ?array, 'set' => fn(?array)] * domain (string) defaults to the current host * public_keys (array) kid => base64 key; defaults to the keys in this file * public_key (string) shortcut for a single key * allow_unverified (bool) download packages without a checksum (default false) * timeout (int) seconds per request (default 15) * api (string) defaults to https://sellmycode.net/api * transport (callable) custom HTTP: fn(string $method, string $url, ?string $json, ?string $sinkPath): array{status:int, body:string} */ public function __construct(array $config) { $this->itemId = (int) ($config['item_id'] ?? 0); if ($this->itemId < 1) { throw new InvalidArgumentException('SellMyCodeLicense: item_id is required.'); } if (empty($config['storage'])) { throw new InvalidArgumentException('SellMyCodeLicense: storage is required — the activation token must survive between requests.'); } $this->code = trim((string) ($config['purchase_code'] ?? '')); $this->storage = $config['storage']; $this->api = rtrim((string) ($config['api'] ?? self::DEFAULT_API), '/'); $this->timeout = max(3, (int) ($config['timeout'] ?? 15)); $this->allowUnverified = !empty($config['allow_unverified']); $this->transport = isset($config['transport']) && is_callable($config['transport']) ? $config['transport'] : null; $keys = $config['public_keys'] ?? (isset($config['public_key']) ? ['*' => $config['public_key']] : self::DEFAULT_KEYS); $this->keys = is_array($keys) ? $keys : []; $domain = $config['domain'] ?? ($_SERVER['HTTP_HOST'] ?? ($_SERVER['SERVER_NAME'] ?? '')); $this->domain = self::normalizeDomain((string) $domain); } /** what is missing on this server, as human-readable lines; empty when all is fine */ public static function requirements(): array { $missing = []; if (!function_exists('sodium_crypto_sign_verify_detached') && !class_exists('ParagonIE_Sodium_Compat')) { $missing[] = 'ext-sodium (or paragonie/sodium_compat) to verify signed answers'; } if (!function_exists('curl_init') && !ini_get('allow_url_fopen')) { $missing[] = 'ext-curl or allow_url_fopen to reach the licence server'; } return $missing; } public function domain(): string { return $this->domain; } public function hasActivation(): bool { return $this->activationToken() !== null; } /** the token issued when this site was activated, needed for updates and deactivation */ public function activationToken(): ?string { $s = $this->state(); return isset($s['token']) && is_string($s['token']) ? $s['token'] : null; } /** claim a slot for this domain; keeps the activation token on success */ public function activate(): SellMyCodeLicenseAnswer { $answer = $this->call('activate', ['activation_token' => $this->activationToken()]); if ($answer->success) { $token = $answer->get('activation_token'); $this->remember($answer, is_string($token) && $token !== '' ? $token : $this->activationToken()); } return $answer; } /** ask the server whether this site is still licensed */ public function verify(): SellMyCodeLicenseAnswer { $answer = $this->call('verify', ['activation_token' => $this->activationToken()]); if ($answer->success) { $this->remember($answer, $this->activationToken()); } elseif (!$answer->offline && !in_array($answer->code, self::TRANSIENT, true)) { $this->forgetAnswer(); } return $answer; } /** pause this site; it keeps its slot and can activate again */ public function deactivate(): SellMyCodeLicenseAnswer { $token = $this->activationToken(); if ($token === null) { return SellMyCodeLicenseAnswer::offline('no_activation_token', 'This site has no activation token — activate it first.'); } $answer = $this->call('deactivate', ['activation_token' => $token]); if ($answer->success) { $this->save(null); } return $answer; } /** * true while this site is licensed. Uses the last verified answer for up to $maxAge * seconds, then asks the server; when the server cannot be reached it keeps running * on the last answer until its grace_until. */ public function isLicensed(int $maxAge = 43200): bool { $last = $this->lastAnswer(); if ($last && in_array($last->code, self::LICENSED, true) && time() - (int) strtotime((string) $last->get('issued_at')) < $maxAge) { return true; } $answer = $this->verify(); if ($answer->success && in_array($answer->code, self::LICENSED, true)) { return true; } if ($answer->offline || in_array($answer->code, self::TRANSIENT, true)) { return $last !== null && in_array($last->code, self::LICENSED, true) && time() < (int) strtotime((string) $last->get('grace_until')); } return false; } /** the last successful activate/verify answer, re-verified from storage */ public function lastAnswer(): ?SellMyCodeLicenseAnswer { $s = $this->state(); if (empty($s['answer']) || !is_array($s['answer'])) { return null; } $data = $this->trusted($s['answer'], null); return $data ? SellMyCodeLicenseAnswer::fromPayload($data, 200) : null; } /** * A current entitlement token (JWT) for this site, to send to your own update * server. Reuses the last one while it has more than $minLife seconds left, * otherwise calls verify for a fresh one. null when the site is not licensed. */ public function entitlement(int $minLife = 3600): ?string { $last = $this->lastAnswer(); if ($last && $last->entitlement) { $claims = self::entitlementClaims($last->entitlement); if ($claims && (int) ($claims['exp'] ?? 0) - time() > $minLife) { return $last->entitlement; } } $answer = $this->verify(); return $answer->success ? $answer->entitlement : null; } /** * For YOUR update server: check an entitlement token offline. Returns its claims * when the signature, issuer, expiry and (if given) item and domain match, else null. * * @param array $options public_keys (kid => base64), item_id, domain, issuer, leeway (seconds, default 60) */ public static function verifyEntitlement(string $token, array $options = []): ?array { $parts = explode('.', $token); if (count($parts) !== 3) { return null; } $head = json_decode((string) self::b64urlDecode($parts[0]), true); $sig = self::b64urlDecode($parts[2]); if (!is_array($head) || ($head['alg'] ?? '') !== 'EdDSA' || $sig === null || strlen($sig) !== 64) { return null; } $keys = $options['public_keys'] ?? self::DEFAULT_KEYS; $key = $keys[(string) ($head['kid'] ?? '')] ?? ($keys['*'] ?? null); $pk = is_string($key) ? base64_decode($key, true) : false; if ($pk === false || strlen($pk) !== 32 || !self::ed25519($sig, $parts[0] . '.' . $parts[1], $pk)) { return null; } $claims = self::entitlementClaims($token); $leeway = (int) ($options['leeway'] ?? 60); $issuer = $options['issuer'] ?? preg_replace('~/api$~', '', self::DEFAULT_API); if (!$claims || ($claims['iss'] ?? null) !== $issuer || (int) ($claims['exp'] ?? 0) < time() - $leeway || (int) ($claims['iat'] ?? 0) > time() + $leeway) { return null; } if (isset($options['item_id']) && (int) ($claims['item_id'] ?? 0) !== (int) $options['item_id']) { return null; } if (isset($options['domain']) && ($claims['domain'] ?? null) !== self::normalizeDomain((string) $options['domain'])) { return null; } return $claims; } /** the claims of a token WITHOUT checking it — use verifyEntitlement() to trust them */ private static function entitlementClaims(string $token): ?array { $parts = explode('.', $token); $claims = count($parts) === 3 ? json_decode((string) self::b64urlDecode($parts[1]), true) : null; return is_array($claims) ? $claims : null; } private static function b64urlDecode(string $value): ?string { $raw = base64_decode(strtr($value, '-_', '+/') . str_repeat('=', (4 - strlen($value) % 4) % 4), true); return $raw === false ? null : $raw; } private static function ed25519(string $sig, string $message, string $pk): bool { try { return function_exists('sodium_crypto_sign_verify_detached') ? sodium_crypto_sign_verify_detached($sig, $message, $pk) : (class_exists('ParagonIE_Sodium_Compat') && ParagonIE_Sodium_Compat::crypto_sign_verify_detached($sig, $message, $pk)); } catch (Throwable $e) { return false; } } /** is there a newer version, and may this licence download it? */ public function checkUpdate(?string $currentVersion = null): SellMyCodeLicenseAnswer { $token = $this->activationToken(); if ($token === null) { return SellMyCodeLicenseAnswer::offline('no_activation_token', 'This site has no activation token — activate it first.'); } return $this->call('update', ['activation_token' => $token, 'current_version' => $currentVersion]); } /** * Download the package of a checkUpdate() answer into $dir (system temp by default) and * check it against the signed SHA-256. Returns the path of the .zip; the caller installs it. * * @throws SellMyCodeLicenseException */ public function downloadUpdate(SellMyCodeLicenseAnswer $update, ?string $dir = null): string { $package = $update->package; if (!$update->updateAvailable || !$package || empty($package['download_url'])) { throw new SellMyCodeLicenseException('no_package', 'This answer carries no package to download.', $update); } $url = (string) $package['download_url']; if (strpos($url, $this->api . '/license/download/') !== 0) { throw new SellMyCodeLicenseException('bad_package_url', 'The package URL does not point at the licence server.', $update); } $integrity = (string) ($package['integrity'] ?? 'unverified'); if ($integrity !== 'sha256' && !$this->allowUnverified) { throw new SellMyCodeLicenseException('unverified_package', 'This package has no checksum (integrity: ' . $integrity . '). Set allow_unverified to install it anyway.', $update); } $dir = rtrim($dir ?: sys_get_temp_dir(), '/\\'); $tmp = @tempnam($dir, 'smc'); if ($tmp === false) { throw new SellMyCodeLicenseException('not_writable', 'Cannot create a file in ' . $dir . '.'); } // keep the file tempnam() created (no unlink/re-create window a neighbour on a // shared host could fill with a symlink); the upgrader accepts any path $path = $tmp; $res = $this->http('GET', $url, null, $path); if ($res['status'] !== 200) { $body = is_file($path) ? (string) @file_get_contents($path, false, null, 0, 65536) : $res['body']; @unlink($path); $answer = $this->parse($body, $res['status'], null); throw new SellMyCodeLicenseException($answer->offline ? 'download_failed' : $answer->code, $answer->message ?: 'The package could not be downloaded (HTTP ' . $res['status'] . ').', $answer); } if ($integrity === 'sha256') { $size = isset($package['size']) ? (int) $package['size'] : null; if (($size !== null && filesize($path) !== $size) || !hash_equals(strtolower((string) $package['sha256']), (string) hash_file('sha256', $path))) { @unlink($path); throw new SellMyCodeLicenseException('checksum_mismatch', 'The downloaded package does not match its signed checksum.', $update); } } return $path; } private function call(string $endpoint, array $extra): SellMyCodeLicenseAnswer { if (!function_exists('sodium_crypto_sign_verify_detached') && !class_exists('ParagonIE_Sodium_Compat')) { return SellMyCodeLicenseAnswer::offline('sodium_missing', 'Install ext-sodium or paragonie/sodium_compat to verify licence answers.'); } if ($this->code === '' || $this->domain === '') { return SellMyCodeLicenseAnswer::offline('not_configured', 'Purchase code or domain missing.'); } $nonce = bin2hex(random_bytes(16)); $body = array_merge([ 'purchase_code' => $this->code, 'item_id' => $this->itemId, 'domain' => $this->domain, 'nonce' => $nonce, ], array_filter($extra, function ($v) { return $v !== null && $v !== ''; })); $res = $this->http('POST', $this->api . '/license/' . $endpoint, json_encode($body), null); $answer = $this->parse($res['body'], $res['status'], $nonce); // one key signs for every product on SellMyCode: a relay could pass on a genuine // answer about another item or another site, with our nonce in it if (!$answer->offline && (int) $answer->get('item.id', $this->itemId) !== $this->itemId) { return SellMyCodeLicenseAnswer::offline('untrusted_answer', 'The answer is for another item.', $res['status']); } if (!$answer->offline && $answer->get('domain') !== null && $answer->get('domain') !== $this->domain) { return SellMyCodeLicenseAnswer::offline('untrusted_answer', 'The answer is for another site.', $res['status']); } return $answer; } private function parse(string $body, int $status, ?string $nonce): SellMyCodeLicenseAnswer { if ($status === 0) { return SellMyCodeLicenseAnswer::offline('offline', 'The licence server could not be reached.'); } $env = json_decode($body, true); if (!is_array($env) || !isset($env['payload'])) { $code = is_array($env) && isset($env['code']) ? (string) $env['code'] : 'offline'; return SellMyCodeLicenseAnswer::offline($code === 'signing_unavailable' ? $code : 'offline', 'The licence server sent no signed answer (HTTP ' . $status . ').', $status); } $data = $this->trusted($env, $nonce); if ($data === null) { return SellMyCodeLicenseAnswer::offline('untrusted_answer', 'The answer failed signature or nonce verification.', $status); } $this->lastEnvelope = ['payload' => $env['payload'], 'signature' => $env['signature'], 'kid' => $env['kid'] ?? null, 'alg' => $env['alg']]; return SellMyCodeLicenseAnswer::fromPayload($data, $status); } /** the decoded payload when the signature (and nonce, if given) check out */ private function trusted(array $env, ?string $nonce): ?array { if (($env['alg'] ?? '') !== 'Ed25519' || !is_string($env['payload'] ?? null) || !is_string($env['signature'] ?? null)) { return null; } $kid = (string) ($env['kid'] ?? ''); $key = $this->keys[$kid] ?? ($this->keys['*'] ?? null); $pk = is_string($key) ? base64_decode($key, true) : false; $sig = base64_decode($env['signature'], true); if ($pk === false || strlen($pk) !== 32 || $sig === false || strlen($sig) !== 64) { return null; } if (!self::ed25519($sig, $env['payload'], $pk)) { return null; } $data = json_decode($env['payload'], true); if (!is_array($data)) { return null; } if ($nonce !== null && !hash_equals($nonce, (string) ($data['nonce'] ?? ''))) { return null; } return $data; } /** @return array{status:int, body:string} status 0 = not reached */ private function http(string $method, string $url, ?string $json, ?string $sink): array { if ($this->transport) { $res = call_user_func($this->transport, $method, $url, $json, $sink); return ['status' => (int) ($res['status'] ?? 0), 'body' => (string) ($res['body'] ?? '')]; } $headers = ['Accept: application/json', 'User-Agent: SellMyCodeLicense/' . self::VERSION . ' PHP/' . PHP_VERSION]; if ($json !== null) { $headers[] = 'Content-Type: application/json'; } if (function_exists('curl_init')) { $ch = curl_init($url); $fh = $sink ? @fopen($sink, 'wb') : null; if ($sink && !$fh) { return ['status' => 0, 'body' => '']; } $opts = [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => $sink ? max(300, $this->timeout) : $this->timeout, CURLOPT_FOLLOWLOCATION => $sink !== null, CURLOPT_MAXREDIRS => 5, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, ]; if (defined('CURLOPT_PROTOCOLS')) { $opts[CURLOPT_PROTOCOLS] = CURLPROTO_HTTPS | CURLPROTO_HTTP; $opts[CURLOPT_REDIR_PROTOCOLS] = CURLPROTO_HTTPS; } if ($json !== null) { $opts[CURLOPT_POSTFIELDS] = $json; } if ($fh) { $opts[CURLOPT_FILE] = $fh; } else { $opts[CURLOPT_RETURNTRANSFER] = true; } curl_setopt_array($ch, $opts); $body = curl_exec($ch); $status = curl_errno($ch) ? 0 : (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); if (PHP_VERSION_ID < 80000) { curl_close($ch); } if ($fh) { fclose($fh); } return ['status' => $status, 'body' => is_string($body) ? $body : '']; } $ctx = stream_context_create(['http' => [ 'method' => $method, 'header' => implode("\r\n", $headers) . "\r\n", 'content' => $json ?? '', 'timeout' => $sink ? max(300, $this->timeout) : $this->timeout, 'ignore_errors' => true, 'follow_location' => $sink !== null ? 1 : 0, 'max_redirects' => 5, ], 'ssl' => ['verify_peer' => true, 'verify_peer_name' => true]]); $in = @fopen($url, 'rb', false, $ctx); if (!$in) { return ['status' => 0, 'body' => '']; } $status = 0; foreach (stream_get_meta_data($in)['wrapper_data'] ?? [] as $line) { if (preg_match('#^HTTP/\S+\s+(\d{3})#', (string) $line, $m)) { $status = (int) $m[1]; } } if ($sink) { $out = @fopen($sink, 'wb'); if (!$out) { fclose($in); return ['status' => 0, 'body' => '']; } stream_copy_to_stream($in, $out); fclose($out); $body = ''; } else { $body = (string) stream_get_contents($in); } fclose($in); return ['status' => $status, 'body' => $body]; } private function remember(SellMyCodeLicenseAnswer $answer, ?string $token): void { $s = $this->state() ?: []; $s['token'] = $token; $s['answer'] = $this->lastEnvelope; $this->save($s); } private function forgetAnswer(): void { $s = $this->state(); if ($s) { unset($s['answer']); $this->save($s); } } private function state(): ?array { if ($this->state !== null) { return $this->state ?: null; } if (is_array($this->storage)) { $raw = call_user_func($this->storage['get']); } else { $raw = is_file($this->storage) ? json_decode((string) @file_get_contents($this->storage), true) : null; } $ok = is_array($raw) && ($raw['item_id'] ?? null) === $this->itemId && ($raw['domain'] ?? null) === $this->domain && ($raw['code'] ?? null) === hash('sha256', $this->code); $this->state = $ok ? $raw : []; return $this->state ?: null; } private function save(?array $s): void { if ($s !== null) { $s['item_id'] = $this->itemId; $s['domain'] = $this->domain; $s['code'] = hash('sha256', $this->code); } $this->state = $s ?: []; if (is_array($this->storage)) { call_user_func($this->storage['set'], $s); return; } if ($s === null) { @unlink($this->storage); return; } $dir = dirname($this->storage); if (!is_dir($dir)) { @mkdir($dir, 0700, true); } $tmp = $this->storage . '.' . bin2hex(random_bytes(4)); if (@file_put_contents($tmp, json_encode($s)) !== false) { @chmod($tmp, 0600); @rename($tmp, $this->storage); } } private static function normalizeDomain(string $value): string { $value = trim($value); if ($value === '') { return ''; } $host = parse_url(strpos($value, '://') === false ? 'http://' . $value : $value, PHP_URL_HOST); return $host ? preg_replace('/^www\./', '', strtolower(trim($host, '.'))) : ''; } } }